diff --git "a/3178.jsonl" "b/3178.jsonl"
new file mode 100644--- /dev/null
+++ "b/3178.jsonl"
@@ -0,0 +1,729 @@
+{"seq_id":"193833197","text":"#!/usr/bin/python3\n\nimport math\nimport re\nfrom collections import defaultdict\n\nqueue = [1,12,0,20,8,16]\n#queue = [0,3,6]\nspoken = {}\nturn = 1\n\npending = None\nfor v in queue:\n if pending is not None:\n spoken[pending] = turn-1\n \n pending = v\n turn += 1\nprint(\"YYY \"+str(spoken))\nwhile 1:\n #print(\"turn \" + str(turn) + \" pending is \" + str(pending))\n if pending not in spoken:\n spoken[pending] = turn - 1\n pending = 0\n else:\n temp_pending = turn - 1 - spoken[pending]\n spoken[pending] = turn - 1\n pending = temp_pending\n\n if turn == 30000000:\n print(str(pending))\n break\n\n if turn % 300000 == 0:\n print(\"turn \" + str(turn) + \"/30000000\")\n turn+=1\n\n","sub_path":"15/solution2.py","file_name":"solution2.py","file_ext":"py","file_size_in_byte":742,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"237745688","text":"from flask import request, make_response, jsonify, url_for\nimport uuid, jwt, datetime\nfrom functools import wraps\n\nfrom api import app\nfrom api.routes import api\nfrom api.models import db\nfrom api.models.users import User\nfrom api.utils.blood import withinRange\n\n\n@api.route(\"/find\", methods=[\"POST\"])\ndef find_blod():\n \"\"\"\n Find blood\n \"\"\"\n\n usersList = list()\n data = request.get_json(silent=True)\n\n bloodgroup, lat, lon, radius = (\n data.get(\"blood\"),\n data.get(\"lat\"),\n data.get(\"lon\"),\n int(data.get(\"radius\", 30)),\n )\n\n users = User.query.filter_by(bloodgroup=bloodgroup).all()\n\n for user in users:\n requestLocation = (lat, lon)\n donorLocation = (user.lat, user.lon)\n\n if withinRange(requestLocation, donorLocation, radius):\n usersList.append(user.serialize)\n\n return make_response(\n jsonify(\n {\n \"message\": \"success\",\n \"users\": usersList,\n }\n ),\n 200,\n )\n","sub_path":"src/backend/api/routes/blood.py","file_name":"blood.py","file_ext":"py","file_size_in_byte":1028,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"15554485","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Tue Aug 22 16:50:31 2017\n\n@author: aglick\n\"\"\"\n\ndef PSD(detectorData,timeData,pulseData,plane,tic):\n import numpy as np\n import matplotlib.pyplot as plt\n import time\n #from numpy import *\n\n\n i = 0\n pulseIntegral = 0\n tailIntegral = 0\n totalIntegral = 0\n peakVal = 0\n peakTime = 0\n neutronTailToTotalRatio = []\n\n tailToTotalRatio = []\n adcVal = []\n #tic = time.time()\n for row in pulseData:\n# peakVal, peakTime = max(enumerate(row), key=operator.itemgetter(1)) #findPeaks(row)\n #print('temp = ',temp)\n row = row - np.average(row[0:15])\n rowAdj = [i for i in row if i >= 0]\n rowAdj = np.array(rowAdj)\n peakTime = rowAdj.argmax()\n #pulseIntegral = integratePulse(row,peakTime)\n #tailIntegral = integrateTail(row,peakTime)\n pulseIntegral = sum(rowAdj[0:(peakTime+8)])\n totalIntegral = sum(rowAdj[0:(len(rowAdj))])\n\n tailIntegral = totalIntegral-pulseIntegral\n #tailIntegral = sum(rowAdj[(peakTime+9):(len(row))])\n #if tailIntegral < 0 or tailIntegral > totalIntegral:\n # tail = row[peakTime+1:len(rowAdj)]\n # tailMin = tail.argmin()\n # tailMax = tail.argmax()\n # print('peak val = ',rowAdj[peakTime])\n # print('tail min = ',tail[tailMin])\n # print('tail max = ',tail[tailMax])\n #if 0 < tailIntegral <= 1:\n tailToTotalRatio += [tailIntegral/float(totalIntegral)]\n adcVal += [totalIntegral]\n #if r < 0 or r > 1:\n # print('ratio = ',r)\n\n if i%100000 == 0 and i!= 0:\n print('m = ', i)\n print('elapsed time = ',time.time()-tic,'s')\n print('tailIntegral = ', tailIntegral)\n print('totalIntegral = ',totalIntegral)\n i=i+1\n\n\n adcVal = np.asarray(adcVal,dtype='float')\n tailToTotalRatio = np.asarray(tailToTotalRatio,dtype='float')\n localMin = 0\n truMax = adcVal.argmax()\n np.savetxt('tailToTotalRaio.csv',tailToTotalRatio,delimiter = \",\")#(\"neutron.csv\", neutronTailToTotalRatio, delimiter=\",\")\n np.savetxt('adcVal.csv',adcVal,delimiter = \",\")\n localMin = 999999999\n truMax = adcVal.argmax()\n truMin = adcVal.argmin()\n ttrArg = 0\n print('ratio = ',tailToTotalRatio[truMax])\n print('adc = ',adcVal[truMax])\n for i in range(0,len(tailToTotalRatio)):\n if tailToTotalRatio[truMax]-0.1 < tailToTotalRatio[i] < tailToTotalRatio[truMax]:\n if localMin > adcVal[i] and adcVal[i] > 1000:#7*adcVal[truMin]:\n localMin = adcVal[i]\n ttrArg = tailToTotalRatio[i]\n #b = (diff(sign(diff(tailToTotalRatio))) > 0).nonzero()[0] + 1 # local min\n #localMin = tailToTotalRatio[b[0]]\n neutronTailToTotalRatio = [i for i in tailToTotalRatio if i >= ttrArg]\n photonTailToTotalRatio = [i for i in tailToTotalRatio if 0 < i < ttrArg]\n\n########################################################################################\n### Sum up ADC values of pulse (integrate pulse) to put into neutron/photon category ###\n########################################################################################\n\n neutronADC = []\n photonADC = []\n neutronDets = []\n neutronTimes = []\n nTTR = []\n pTTR = []\n for i in range(0,len(tailToTotalRatio)):\n if tailToTotalRatio[i] >= ttrArg:\n neutronADC += [adcVal[i]]\n neutronDets += [detectorData[i]]\n neutronTimes += [timeData[i]]\n nTTR += [tailToTotalRatio[i]]\n else:\n photonADC += [adcVal[i]]\n pTTR += [tailToTotalRatio[i]]\n\n neutronADC = np.asarray(neutronADC)\n neutronDets = np.asarray(neutronDets,dtype = 'int')\n neutronTimes = np.asarray(neutronTimes)\n photonADC = np.asarray(photonADC)\n nTTR = np.asarray(nTTR,dtype = 'float')\n pTTR = np.asarray(pTTR,dtype = 'float')\n plt.figure()\n plt.scatter(neutronADC,nTTR,c = 'r',label = 'neutrons')\n plt.scatter(photonADC,pTTR,c = 'b',label='photons')\n plt.xlabel('ADC Val')\n plt.ylabel('Tail to Total Ratio')\n plt.show()\n\n# a = 0\n# b = 0\n# c = 0\n# d = 0\n# e = 0\n# f = 0\n #numpy.savetxt(\"neutron.csv\", neutronTailToTotalRatio, delimiter=\",\")\n #numpy.savetxt(\"photon.csv\", photonTailToTotalRatio, delimiter=\",\")\n# histTTTPT = np.histogram(photonTailToTotalRatio,100000)\n\n# histPADC = np.histogram(photonADC,100000)\n #histTTTRT = photonTailToTotalRatio.hist(bins=100000)\n# a = histTTTPT[0]\n# b = histTTTPT[1]\n# c = b[0:100000]\n# a1 = histPADC[0]\n# b1 = histPADC[1]\n# c1 = b1[0:100000]\n\n# histTTT = np.histogram(neutronTailToTotalRatio,100000)\n# histNADC = np.histogram(neutronADC,100000)\n #histTTT = neutronTailToTotalRatio.hist(bins=100000)\n# d = histTTT[0]\n# e = histTTT[1]\n# f = e[0:100000]\n# d1 = histNADC[0]\n# e1 = histNADC[1]\n# f1 = e1[0:100000]\n\n# plt.figure(2)\n# plt.plot(a,c,'r',label='photons')\n# plt.plot(d,f,'b--',label='neutrons')\n# plt.xlabel('Counts')\n# plt.ylabel('Tail to Total Ratio')\n# plt.legend(loc='upper right')\n# plt.title(plane)\n #plt.plot(d,f)\n# plt.show()\n# eVal = slope*f1 + intercept\n# eValP = slope*c1 + intercept\n# plt.figure(3)\n# plt.plot(eValP,a1,'r',label='photons')\n# plt.plot(eVal,d1,'b--',label='neutrons')\n# plt.xlabel('Energy [keV]')\n# plt.ylabel('Counts')\n# plt.legend(loc='upper right')\n# plt.title(plane)\n #plt.plot(d,f)\n# plt.show()\n\n\n\n return neutronDets, neutronTimes, neutronADC\n\ndef PSDRT(ttr,timeData,detectorData,adcVal,ttrArg):\n import numpy as np\n import matplotlib.pyplot as plt\n import time\n #from numpy import *\n\n\n i = 0\n pulseIntegral = 0\n tailIntegral = 0\n totalIntegral = 0\n peakVal = 0\n peakTime = 0\n neutronTailToTotalRatio = []\n\n tailToTotalRatio = []\n #adcVal = []\n #ttrArg = 5\n neutronTailToTotalRatio = [i for i in ttr if i >= ttrArg]\n photonTailToTotalRatio = [i for i in ttr if 0 < i < ttrArg]\n\n########################################################################################\n### Sum up ADC values of pulse (integrate pulse) to put into neutron/photon category ###\n########################################################################################\n\n neutronADC = []\n photonADC = []\n neutronDets = []\n neutronTimes = []\n nTTR = []\n pTTR = []\n L = [len(ttr), len(timeData), len(detectorData), len(adcVal)]\n for i in range(0,int(min(L))-1):\n if ttr[i] >= ttrArg:\n neutronADC += [adcVal[i]]\n neutronDets += [detectorData[i]]\n neutronTimes += [timeData[i]]\n nTTR += [ttr[i]]\n# else:\n# photonADC += [adcVal[i]]\n# pTTR += [tailToTotalRatio[i]]\n\n neutronDets = np.array(neutronDets,dtype = 'int')\n neutronTimes = np.array(neutronTimes, dtype = 'float')\n neutronADC = np.array(neutronADC, dtype = 'int')\n\n# photonADC = np.asarray(photonADC)\n nTTR = np.asarray(nTTR,dtype = 'float')\n\n\n\n\n return neutronDets, neutronTimes, neutronADC\n","sub_path":"NSCIR/src/nscir/PSD.py","file_name":"PSD.py","file_ext":"py","file_size_in_byte":7140,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"198554393","text":"import csv\nimport json\nimport os\nimport time\n\nfrom rover_common import aiolcm\nfrom rover_common.aiohelper import run_coroutines\nfrom rover_msgs import IMUData, GPS, Odometry\n\n\nclass Logger:\n\n def __init__(self):\n # Read in options from logConfig\n config_path = os.getenv('MROVER_CONFIG')\n config_path += \"/config_filter/logConfig.json\"\n with open(config_path, \"r\") as config:\n self.logConfig = json.load(config)\n\n config_path = os.getenv('MROVER_CONFIG')\n config_path += \"/config_filter/config.json\"\n with open(config_path, \"r\") as config:\n self.filterConfig = json.load(config)\n\n # Make logs if they don't already exist\n os.makedirs(os.path.join(os.getcwd(), 'onboard', 'filter', 'logs'),\n exist_ok=True)\n\n # Create files and write headers\n self.write(['lat_deg', 'lat_min', 'long_deg', 'long_min', 'bearing',\n 'speed'], 'gps')\n self.write(['accel_x', 'accel_y', 'accel_z', 'gyro_x', 'gyro_y',\n 'gyro_z', 'mag_x', 'mag_y', 'mag_z', 'bearing'], 'imu')\n self.write(['nav_state', 'nav_state_name', 'completed_wps',\n 'missed_wps', 'total_wps', 'found_tbs', 'total_tbs'],\n 'navStatus')\n self.write(['lat_deg', 'lat_min', 'long_deg', 'long_min', 'bearing',\n 'speed'], 'phone')\n self.write(['lat_deg', 'lat_min', 'long_deg', 'long_min', 'bearing',\n 'speed'], 'odom')\n self.write(['lat_deg', 'lat_min', 'long_deg', 'long_min', 'bearing',\n 'speed'], 'movAvg')\n self.write(['Q', 'FilterType', 'P_initial', 'R', 'dt', 'UpdateRate'], 'config')\n\n P_initial_str = str(self.filterConfig['P_initial']).replace(',', ' ')\n R_str = str(self.filterConfig['R']).replace(',', ' ')\n self.write([self.filterConfig['Q'], self.filterConfig['FilterType'],\n P_initial_str, R_str, self.filterConfig['dt'],\n self.filterConfig['UpdateRate']], 'config')\n\n # Subscribe to LCM channels\n self.lcm = aiolcm.AsyncLCM()\n self.lcm.subscribe(\"/gps\", self.gps_callback)\n self.lcm.subscribe(\"/imu\", self.imu_callback)\n self.lcm.subscribe(\"/odometry\", self.odom_callback)\n\n # Initialize sensor timestamps\n self.gps_millis = time.time() * 1000\n self.imu_millis = time.time() * 1000\n self.odom_millis = time.time() * 1000\n\n def write(self, contents, type):\n # Writes contents to the log specified by type\n # with open(self.file_path + type + 'Log.csv', 'w') as log:\n with open(os.path.join('onboard', 'filter', 'logs', type + 'Log.csv'),\n mode=self.logConfig['mode']) as log:\n writer = csv.writer(log)\n writer.writerow(contents)\n\n def gps_callback(self, channel, msg):\n gps = GPS.decode(msg)\n if (time.time()*1000 - self.gps_millis) > \\\n self.logConfig['rate_millis']['gps']:\n self.write([gps.latitude_deg, gps.latitude_min, gps.longitude_deg,\n gps.longitude_min, gps.bearing_deg, gps.speed], 'gps')\n self.gps_millis = time.time()*1000\n\n def imu_callback(self, channel, msg):\n imu = IMUData.decode(msg)\n if (time.time()*1000 - self.imu_millis) > \\\n self.logConfig['rate_millis']['imu']:\n self.write([imu.accel_x_g, imu.accel_y_g, imu.accel_z_g, imu.gyro_x_dps,\n imu.gyro_y_dps, imu.gyro_z_dps, imu.mag_x_uT, imu.mag_y_uT,\n imu.mag_z_uT, imu.bearing_deg], 'imu')\n self.imu_millis = time.time()*1000\n\n def odom_callback(self, channel, msg):\n odom = Odometry.decode(msg)\n if (time.time()*1000 - self.odom_millis) > \\\n self.logConfig['rate_millis']['odom']:\n self.write([odom.latitude_deg, odom.latitude_min,\n odom.longitude_deg, odom.longitude_min,\n odom.bearing_deg, odom.speed], 'odom')\n self.odom_millis = time.time()*1000\n\n\ndef main():\n logger = Logger()\n run_coroutines(logger.lcm.loop())\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"onboard/sensor_logging/src/__main__.py","file_name":"__main__.py","file_ext":"py","file_size_in_byte":4250,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"360378","text":"#!/usr/bin/env python\n#-*- coding: UTF-8 -*- \n\nimport socket\n\nsk = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)\nsk.bind(\"/tmp/test\")\nsk.listen(5)\nsk.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)\n\nwhile True:\n conn, addr = sk.accept()\n conn.sendall('欢迎致电 10086,请输入1xxx,0转人工服务.') \n Flag = True \n while Flag: \n data = conn.recv(1024) \n if data == 'exit':\n Flag = False \n elif data == '0': \n conn.sendall('通过可能会被录音.balabala一大推')\n else: \n conn.sendall('请重新输入.')\n conn.close()\n","sub_path":"socket/AF_UNIX/SOCK_STREAM/server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":621,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"69076342","text":"DUMP_FILE_PATH = '/gost-ssl/rzs/dump/dump.xml'\n\nimport xml.etree.ElementTree as etree\nimport MySQLdb as _mydb\nimport optparse\nimport sys\nimport logging\n\n# never blocking sites\nallow_sites = ('www.youtube.com', 'youtube.com', 'vk.com', 'ru.wikipedia.org', 'habrahabr.ru', 'google.com', 'www.google.com',)\n\nopt = optparse.OptionParser()\nopt.add_option(\"-d\", \"--dns-host\", action=\"store\", type=\"string\", dest=\"host\")\nopts, args = opt.parse_args()\n\nif not opts.host:\n\tlogging.debug('Host not present')\n\tsys.exit(1)\n\nlogging.basicConfig(format='%(asctime)s %(levelname)s HOST:' + opts.host + ' %(message)s', filename='/var/log/rzs_pasres.log', level = logging.DEBUG)\n\ndef db_insert(connection, sites):\n\tINSERT_SQL = \"INSERT INTO sites (domain) VALUES (%s)\"\n\tTRUNCATE_SQL = \"TRUNCATE sites\"\n\tTIMESTAMP_SQL = \"INSERT INTO update_time (TIMESTAMP) VALUES (NOW())\"\n\ttry:\n\t\tconnection.autocommit(False)\n\t\tcursor = connection.cursor()\n\t\tcursor.execute(TRUNCATE_SQL)\n\t\tfor site in sites:\n\t\t\tdata_site = (site.encode('utf-8'),)\n\t\t\tcursor.execute(INSERT_SQL, data_site)\n\n\t\tconnection.commit()\n\t\tconnection.autocommit(True)\n\t\tcursor.execute(TIMESTAMP_SQL)\n\t\tconnection.commit()\n\t\tlogging.info(\"Successfully completed\")\n\texcept Exception as e:\n\t\tlogging.debug(\"MySQL error: %s\" % (e.message,))\n\tfinally:\n\t\tconnection.rollback()\n\t\tcursor.close()\n\t\tconnection.close()\n\ndef db_init():\n\ttry:\n\t\tcon = _mydb.connect(\n\t\t\thost=opts.host,\n\t\t\tdb=\"rzs\",\n\t\t\tuser=\"rzs\",\n\t\t\tpasswd=\"\"\n\t\t)\n\n\t\treturn con\n\texcept Exception as e:\n\t\tlogging.debug(\"Error while mysql connect to Host %s: %s\" % (opts.host, e.message,))\n\n\ntree = etree.parse(DUMP_FILE_PATH)\nroot = tree.getroot()\n\nsites_list = []\n\nfor elem in root:\n\tsites_list.append(elem.find('domain').text.encode(\"idna\"))\n\nsites = set(sites_list)\n\nfor allow_site in allow_sites:\n if allow_site in sites:\n sites.remove(allow_site)\n\n\nconnection = db_init()\nif connection:\n\tdb_insert(connection, sites)\n","sub_path":"rzs_xml_parser.py","file_name":"rzs_xml_parser.py","file_ext":"py","file_size_in_byte":1925,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"533207455","text":"#把可能发生错误的语句放在try模块里,错误由except处理\n# a=10\n# b=0\n# try:\n# c=a/b\n# print (c)\n# except ZeroDivisionError:\n# print(\"done!\")\n# print(\"not done!\")\n\n#raise\n# a=input(\"input a number\")\n# if not isinstance(a,int):\n# raise ValueError\n# else:\n# print(\"no error\")\n\n#合并起来使用\ndef binToDec(bin_no): #这是一个关于输入判断类型的,一般都要判断类型\n \"\"\"\n @param bin_no: an integer or str representation of a binary number\n @return: an integer value of the binary number passed\n \"\"\"\n dec = 0\n i = 0\n if not isinstance(bin_no, int): #先判断是不是\n try:\n bin_no = int(bin_no) #不是的话判断能不能转换,不能转换的话会出现错误\n except:\n raise TypeError #不能转换就产生一个TypeError\n while bin_no > 0:\n dec += ((bin_no % 10) * (2 ** i))\n bin_no //= 10\n i += 1\n return dec\nprint(binToDec(input(\"input a number\")))\n#isinstance函数\n# isinstance(object, classinfo)\n# 判断实例是否是这个类或者object是变量\n#\n# classinfo\n# 是类型(tuple, dict, int, float)\n# 判断变量是否是这个类型\n# 其第一个参数为对象,第二个为类型名或类型名的一个列表。其返回值为布尔型。若对象的类型与参数二的类型相同则返回True。若参数二为一个元组,则若对象类型与元组中类型名之一相同即返回True。\n#\n# >> > isinstance(lst, list)\n# True\n#\n# >> > isinstance(lst, (int, str, list))\n# True","sub_path":"Mega_Project_List/binary_demical_convert.py","file_name":"binary_demical_convert.py","file_ext":"py","file_size_in_byte":1566,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"496170335","text":"import sys\nimport scipy.io as spio\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport scipy\nfrom scipy.signal import freqz\nfrom scipy.signal import butter, lfilter, lfilter_zi\n\nfrom scipy.signal import filtfilt\n\n# Load the mat file with data in struct format\ndef loadmat(filename):\n '''\n this function should be called instead of direct spio.loadmat\n as it cures the problem of not properly recovering python dictionaries\n from mat files. It calls the function check keys to cure all entries\n which are still mat-objects\n '''\n data = spio.loadmat(filename, struct_as_record=False, squeeze_me=True)\n return _check_keys(data)\n\ndef _check_keys(dict):\n '''\n checks if entries in dictionary are mat-objects. If yes\n todict is called to change them to nested dictionaries\n '''\n for key in dict:\n if isinstance(dict[key], spio.matlab.mio5_params.mat_struct):\n dict[key] = _todict(dict[key])\n return dict\n\ndef _todict(matobj):\n '''\n A recursive function which constructs from matobjects nested dictionaries\n '''\n dict = {}\n for strg in matobj._fieldnames:\n elem = matobj.__dict__[strg]\n if isinstance(elem, spio.matlab.mio5_params.mat_struct):\n dict[strg] = _todict(elem)\n else:\n dict[strg] = elem\n return dict\n\n\ndef get_data(load_file, data_type_name):\n mat = loadmat(load_file)\n # channel_data will be a list. Every element of the list\n # is one trial (an ndarray) containing 8 channels by n number of datapoints\n # To get a single decimal datapoint: channel_data[trial][channel][timestep]\n channel_data = []\n for i in range(len(mat['Data'][data_type_name])):\n data = _todict(mat['Data'][data_type_name][i])\n print(data)\n channel_data.append(data['PSUEEG']['Channels'])\n try:\n trial_type = list(mat['Data']['TrialType'])\n except:\n print(\"No trial type data found. Returning empty vector for trial_type.\")\n trial_type = []\n return channel_data, trial_type\n\n# Shift stimulus to t = 0 for each trial, and reflect the last bit of the final trial to keep lengths nearly equal\ndef reframe(stimulus_delay, data_object, sample_rate):\n reformatted_data_object = [[[] for i in range(len(data_object[0]))] for i in range(len(data_object))]\n print(\"Length of reformmatted_data_object: \" + str(len(reformatted_data_object)))\n print(\"Reformatting data to adjust for trail start offset.\")\n for trial in range(len(data_object)-1):\n for channel in range(len(data_object[0])):\n print(\"Writing trial \" + str(trial+1) + \" channel \" + str(channel+1))\n #test = list(data_object[trial][channel][int(stimulus_delay * sample_rate):]) + list(data_object[trial+1][channel][:int(stimulus_delay * sample_rate)])\n #print(\"Test length: \" + str(len(test)))\n reformatted_data_object[trial][channel].append(list(data_object[trial][channel][int(stimulus_delay * sample_rate):]) + list(data_object[trial+1][channel][:int(stimulus_delay * sample_rate)]))\n last_trial = len(data_object) - 1\n for channel in range(len(data_object[last_trial])):\n print(\"Writing trial \" + str(last_trial+1) + \" channel \" + str(channel+1))\n reformatted_data_object[last_trial][channel].append(list(data_object[last_trial][channel][int(stimulus_delay * sample_rate):]) + list(reversed(data_object[last_trial][channel][-int(stimulus_delay * sample_rate):])))\n return reformatted_data_object\n\n\n################################################\n# Bandpass Filter\n################################################\ndef butter_bandpass(lowcut, highcut, fs, order=5):\n nyq = 0.5 * fs\n low = lowcut / nyq\n high = highcut / nyq\n b, a = butter(order, [low, high], btype='band')\n return b, a\n\ndef butter_bandpass_filter(data, lowcut, highcut, fs, order=5):\n b, a = butter_bandpass(lowcut, highcut, fs, order=order)\n y = lfilter(b, a, data)\n return y\n\ndef bandpass_filt(fs, lowcut, highcut, shifted_data_object):\n \"\"\"\n # Plot the frequency response for a few different orders.\n plt.figure(1)\n plt.clf()\n for order in [3, 6, 9]:\n b, a = butter_bandpass(lowcut, highcut, fs, order=order)\n w, h = freqz(b, a, worN=2000)\n plt.plot((fs * 0.5 / np.pi) * w, abs(h), label=\"order = %d\" % order)\n\n plt.plot([0, 0.5 * fs], [np.sqrt(0.5), np.sqrt(0.5)],\n '--', label='sqrt(0.5)')\n plt.xlabel('Frequency (Hz)')\n plt.ylabel('Gain')\n plt.grid(True)\n plt.legend(loc='best')\n plt.show()\n \"\"\"\n\n # Concatenate all of the trials\n # all_data has shape(numchannels, sum_time_all_trials)\n all_data = [[] for i in range(len(shifted_data_object[0]))]\n print(\"Appending data into one large vector.\")\n for trial in shifted_data_object:\n print(\"Iterating trial.\")\n for i in range(len(trial)):\n all_data[i] = list(all_data[i]) + list(trial[i][0])\n \"\"\"\n plt.figure(32)\n plt.clf()\n plt.plot(all_data[0], 'c-', label=(\"Prefiltered channel data for channel \" + str(1)), linewidth=1.5)\n plt.axis('tight')\n plt.legend(loc='upper left')\n \"\"\"\n\n # Get the indices used to compose / decompose the all_data matrix\n trial_lengths = []\n for trial_num in range(len(shifted_data_object)):\n trial_lengths.append(len(shifted_data_object[trial_num][0][0]))\n\n # Plot the function we wish to filter\n T = len(all_data[0])/fs\n nsamples = int(T * fs)\n t = np.linspace(0, T, nsamples, endpoint=False)\n\n # Filter all of the channels individually\n b, a = butter_bandpass(lowcut, highcut, fs)\n y_filtered = []\n for i in range(len(all_data)):\n x = all_data[i][:nsamples]\n y = filtfilt(b, a, x, padlen = 1000)\n ## Or, lfilter_zi\n #zi = lfilter_zi(b, a)\n #y3, zo = lfilter(b, a, x, zi=zi*x[0])\n y_filtered.append(y)\n\n \"\"\"\n plt.figure(33)\n plt.clf()\n plt.plot(y_filtered[0], 'c-', label=(\"Post-filtered channel data for channel \" + str(1)), linewidth=1.5)\n plt.axis('tight')\n plt.legend(loc='upper left')\n plt.show()\n\n\n # Plot some of the filtered data\n for i in range(len(y_filtered)):\n plt.figure(2+i)\n plt.clf()\n plt.plot(t, y_filtered[i], 'c-', label=(\"filtfilt signal channel \" + str(i+1)), linewidth=1.5)\n plt.axis('tight')\n plt.legend(loc='upper left')\n plt.show()\n \"\"\"\n\n # But we don't want to return y_filtered, we want to return y_filtered separated by trial\n return y_filtered\n\n#####################################\n# Bandpower\n#####################################\ndef bandpower(x, fs, fmin, fmax):\n f, Pxx = scipy.signal.periodogram(x, fs=fs)\n ind_min = scipy.argmax(f > fmin) - 1\n ind_max = scipy.argmax(f > fmax) - 1\n return scipy.trapz(Pxx[ind_min: ind_max], f[ind_min: ind_max])\n\n# Compute the alpha bandpower for each of the channels for all time recorded\n'''def windowed_bandpower(filtered_data, band_low, band_high, windowsize, fs, slice_width):\n power_data = [[] for k in range(len(filtered_data))]\n windowhalf = int(windowsize/2)\n for i in range(len(filtered_data)):\n for j in range(windowhalf,int(slice_width/fs)-windowhalf,1):\n data_subset = filtered_data[i][(sample_rate*j-(sample_rate*windowhalf)):(sample_rate*j+sample_rate*windowhalf)]\n power_out = bandpower(data_subset,sample_rate,band_low,band_high)\n power_data[i].append(power_out)\n #print(\"Writing \" + str(power_out) + \" to power vector \" + str(i+1))\n return power_data'''\n\ndef windowed_bandpower(filtered_data, band_low, band_high, windowsize, windowstep, fs, slice_width):\n power_data = [[] for k in range(len(filtered_data))]\n windowhalf = windowsize/2\n for i in range(len(filtered_data)):\n #print(slice_width/fs - windowhalf)\n j = windowhalf\n while j <= (slice_width/fs - windowhalf):\n data_subset = filtered_data[i][int(fs*j-(fs*windowhalf)):int(fs*j+fs*windowhalf)]\n power_out = bandpower(data_subset,fs,band_low,band_high)\n power_data[i].append(power_out)\n j += windowstep\n #print(\"Writing \" + str(power_out) + \" to power vector \" + str(i+1))\n return power_data\n\ndef mean_slicer(shifted_data_object, filtered_data):\n indices = []\n for i in range(len(shifted_data_object)):\n indices.append(len(shifted_data_object[i][0][0]))\n print(indices)\n slice_width = min(indices)\n print(\"Slice_width: \" + str(slice_width))\n slices=[list(np.zeros(slice_width)) for i in range(len(filtered_data))]\n slice_width = min(indices)\n for j in range(len(filtered_data)):\n for i in range(len(indices)):\n lower = sum(indices[:i])\n upper = lower + slice_width\n print(\"Working on channel \" + str(i + 1) + \" slices with indices \" + str(lower) + \" to \" + str(upper) + \".\")\n slices[j] = list(np.array(slices[j]) + np.array(filtered_data[j][lower:upper])/(len(indices)+1))\n return slices, slice_width\n\ndef trial_slicer(shifted_data_object, filtered_data):\n indices = []\n for i in range(len(shifted_data_object)):\n indices.append(len(shifted_data_object[i][0][0]))\n print(indices)\n slice_width = min(indices)\n print(\"Slice_width: \" + str(slice_width))\n all_trials = []\n slice_width = min(indices)\n for i in range(len(indices)):\n trial = []\n for j in range(len(filtered_data)):\n lower = sum(indices[:i])\n upper = lower + slice_width\n print(\"Working on segmenting channel \" + str(i + 1) + \" slices with indices \" + str(lower) + \" to \" + str(upper) + \".\")\n trial.append(filtered_data[j][lower:upper])\n all_trials.append(trial)\n return all_trials, slice_width\n\ndef data_subset(dataset, time_window, sample_rate):\n t_low = int(time_window[0]*sample_rate)\n t_high = int(time_window[1]*sample_rate)\n sub_data = []\n for trial_num in range(len(dataset)):\n trial = []\n for channel_num in range(len(dataset[0])):\n trial.append(dataset[trial_num][channel_num][t_low:t_high])\n sub_data.append(trial)\n return sub_data\n\ndef trial_type_separator(dataset, trial_labels):\n A = []\n B = []\n for trial_num in range(len(dataset)):\n trial = []\n for channel_num in range(len(dataset[0])):\n trial.append(dataset[trial_num][channel_num])\n if trial_labels[trial_num] == 0:\n A.append(trial)\n else:\n B.append(trial)\n return A, B\n\ndef matrix_plotter(plot_data, plot_label):\n for i in range(len(plot_data)):\n plt.figure(i+1)\n plt.clf()\n plt.plot(plot_data[i], 'c-', label=(str(plot_label) + \" for channel \" + str(i+1)), linewidth=1.5)\n plt.axis('tight')\n plt.legend(loc='upper left')\n plt.show()\n\ndef channel_plotter(plot_data, channel_list, plot_title, sample_rate):\n fig, ax = plt.subplots()\n time_vec = np.asarray(list(range(len(plot_data[0]))))/float(sample_rate)\n for channel in range(len(channel_list)):\n line_label = \"Channel \" + str(channel_list[channel])\n ax.plot(time_vec, plot_data[channel_list[channel]-1], linewidth=2, label=line_label)\n plt.legend(loc='lower right')\n plt.title(str(plot_title))\n plt.xlabel(\"Time (s)\")\n plt.ylabel(\"EEG Signal\")\n plt.show()\n\n\ndef channel_remover(dataset, rm_channels_list):\n for channel_number in reversed(sorted(rm_channels_list)):\n print(\"removing channel \" + str(channel_number))\n dataset = dataset[:channel_number - 1] + dataset[channel_number:]\n return dataset\n\ndef apply_CSP_filter(csp_filter, data):\n out_data = np.matmul(csp_filter, data)\n return out_data\n\ndef mean_of_channels(data, channel_list):\n ch_sum = np.asarray(data[channel_list[0]-1])\n for i in range(1,len(channel_list)):\n ch_sum = ch_sum + np.asarray(data[channel_list[i]-1])\n mean = ch_sum / len(channel_list)\n return list(mean)\n\nif __name__ == '__main__':\n sample_rate = 1000 #Hz\n load_file = 'BCI_AlphaBlock_Bruce_180125.mat'\n #load_file = 'feb_1_data.mat'\n stimulus_delay = 3 #Seconds\n low_cut = 2 #Hz\n high_cut = 60 #Hz\n # Parameters for calculation of bandpower\n band_low = 7 #Hz\n band_high = 14 #Hz\n windowsize = 3 #seconds\n windowstep = .2 #seconds\n\n # Load EEG data from .mat file\n data_object = get_data(load_file)\n # Shift each trial by offset to the left. Last trial will have mirrored end.\n shifted_data_object = reframe(stimulus_delay, data_object, sample_rate)\n # Apply a bandpass filter and concatenate all trials\n filtered_data = bandpass_filt(sample_rate, low_cut, high_cut, shifted_data_object)\n # Take the mean of filtered data by trial (now length = min(length(trials)))\n mean_trial_data, slice_width = mean_slicer(shifted_data_object, filtered_data)\n # Calculate the bandpower for alpha, beta, etc defined by [band_low, band_high]\n alpha_power_data = windowed_bandpower(mean_trial_data, band_low, band_high, windowsize, windowstep, sample_rate, slice_width)\n\n # Plot the result\n matrix_plotter(alpha_power_data, \"alpha bandpower\")\n\n\n sys.stdout.write('Hello World')\n","sub_path":"filter2.py","file_name":"filter2.py","file_ext":"py","file_size_in_byte":13256,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"418348861","text":"import time\nimport sys\nfrom psychopy import visual,event,core\n\n#Show the following sequence: blue, red, blue, red, blue, red (with each square appearing for 1 s with a 50 ms blank screen in the middle).\n\nwin = visual.Window([400,400],color=\"black\", units='pix') # make a window\nsquareRed = visual.Rect(win,lineColor=\"black\",fillColor=\"red\",size=[100,100]) # make a RED square!\nsquareBlue = visual.Rect(win,lineColor=\"black\",fillColor=\"blue\",size=[100,100]) # make a RED square!\n\n\nfor num in range(6):\n\tif num % 2 == 0:\n\t\tsquareBlue.draw() # redraw\n\telse:\n\t\tsquareRed.draw() # redraw\n\twin.flip() # show\n\tcore.wait(1) # flash #1\n\twin.flip() # hide\n\tcore.wait(.5) # hide for a little \n\n\nsys.exit()","sub_path":"exercise_1_5.py","file_name":"exercise_1_5.py","file_ext":"py","file_size_in_byte":695,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"569225184","text":"import requests\nimport json\n\nclass SpotifyClientAPI():\n def __init__(self, client_id, client_secret, access_token):\n self.client_id = client_id\n self.client_secret = client_secret\n self.access_token = access_token\n\n # Set up headers for API calls\n def get_resource_header(self):\n headers = {\"Authorization\": f\"Bearer {self.access_token}\"}\n return headers\n\n # Get User ID: https://developer.spotify.com/documentation/web-api/reference/users-profile/get-current-users-profile/\n def get_user_id(self):\n endpoint = 'https://api.spotify.com/v1/me'\n headers = self.get_resource_header()\n r = requests.get(endpoint, headers=headers)\n response = r.json()\n user_id = response['id']\n return user_id\n\n # API calls\n def get_audio_features(self, track_id):\n headers = self.get_resource_header()\n endpoint = f\"https://api.spotify.com/v1/audio-features/{track_id}\"\n r = requests.get(endpoint, headers=headers)\n # print(r.status_code)\n if r.status_code not in range(200, 299):\n return {}\n return r.json()\n\n def get_tracks(self):\n headers = self.get_resource_header()\n endpoint = 'https://api.spotify.com/v1/me/tracks'\n r = requests.get(endpoint, headers=headers)\n # print(r.status_code)\n if r.status_code not in range(200, 299):\n return {}\n return r.json()\n\n def get_playlist_info(self, playlist_id, fields=None):\n headers = self.get_resource_header()\n endpoint = f\"https://api.spotify.com/v1/playlists/{playlist_id}\"\n if fields is None:\n lookup_url = endpoint\n else:\n lookup_url = f\"{endpoint}?fields={fields}\"\n r = requests.get(endpoint, headers=headers)\n # print(r.status_code)\n if r.status_code not in range(200, 299):\n return {}\n return r.json()\n\n def get_playlist_tracks(self, playlist_id):\n headers = self.get_resource_header()\n endpoint = f\"https://api.spotify.com/v1/playlists/{playlist_id}/tracks\"\n r = requests.get(endpoint, headers=headers)\n # print(r.status_code)\n if r.status_code not in range(200, 299):\n return {}\n return r.json()\n\n def create_playlist(self, pl_name):\n user_id = self.get_user_id()\n token = self.access_token\n request_body = json.dumps({\n \"name\": f\"{pl_name}\",\n \"public\": False\n })\n endpoint = f\"https://api.spotify.com/v1/users/{user_id}/playlists\"\n headers = {\n \"Content-Type\": \"application/json\",\n \"Authorization\": f\"Bearer {token}\"\n }\n r = requests.post(endpoint, data=request_body, headers=headers)\n # print(r.status_code)\n response_json = r.json()\n return response_json[\"id\"]\n\n def add_songs_to_playlist(self, playlist_id, track_uris):\n access_token = self.access_token\n request_data = json.dumps({\n \"uris\": track_uris\n })\n print(request_data)\n query = f\"https://api.spotify.com/v1/playlists/{playlist_id}/tracks\"\n r = requests.post(\n query,\n data=request_data,\n headers={\n \"Content-Type\": \"application/json\",\n \"Authorization\": f\"Bearer {access_token}\"\n }\n )\n # print(r.status_code)\n response = r.json()\n return response\n","sub_path":"client.py","file_name":"client.py","file_ext":"py","file_size_in_byte":3481,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"262201674","text":"class Schema():\n def __init__(self, schema=None, default={}):\n self._default_schema_item = dict(\n format=None,\n justification='ljust',\n min_width=0,\n width_calc_func=lambda width: width,\n )\n self._default_schema_item.update(default)\n self._schema = dict()\n if schema:\n self.set_schema(schema)\n\n def validate_schema(self, schema_dict):\n formatting = schema_dict.get('format')\n justification = schema_dict.get('justification')\n min_width = schema_dict.get('min_width', 0)\n width_calc_func = schema_dict.get('width_calc_func', None)\n\n if formatting and (justification or min_width or width_calc_func):\n raise Exception(\n \"Can not use justification or min_width, when use formatting.\")\n\n def set_schema(self, schema):\n if not schema:\n return\n\n if type(schema) is list:\n for index in range(len(schema)):\n self.validate_schema(schema[index])\n self._schema = dict(zip(list(range(len(schema))), schema))\n elif type(schema) is dict:\n for key in list(schema.keys()):\n self.validate_schema(schema[key])\n self._schema = schema\n else:\n raise Exception(f\"schema must be list or dict. {type(schema)}\")\n\n def get_schema(self, index_or_key):\n return self._schema.get(index_or_key, self._default_schema_item)\n\n def format_column_value(self, index_or_key, val, default_width):\n width = default_width\n justification = 'ljust'\n width_calc_func = lambda width: width # noqa: E731\n formatting = None\n if self._schema:\n min_width = self.get_schema(index_or_key).get('min_width', 0)\n justification = self.get_schema(index_or_key).get(\n 'justification', justification)\n width_calc_func = self.get_schema(index_or_key).get(\n 'width_calc_func', width_calc_func)\n formatting = self.get_schema(\n index_or_key).get('format', formatting)\n\n width = max(int(width), int(min_width))\n width = width_calc_func(width)\n\n if formatting:\n val = (\"{\" + formatting + \"}\").format(val)\n else:\n justification_func = getattr(val, justification)\n val = justification_func(width)\n return val\n\n\nclass FixedWidthFormatter():\n def __init__(self, schema=None):\n self._schema = Schema(schema)\n self._headers = []\n self._valid_headers = False\n self._rows = []\n\n def extract_headers(self, array_of_dict):\n headers = [header for row in array_of_dict for header in row.keys()]\n headers = list({value: \"\" for value in headers})\n return headers\n\n def from_dict(self, array_of_dict, headers=None, valid_headers=True):\n if valid_headers and headers:\n self._headers = headers\n self._valid_headers = True\n elif valid_headers and not headers:\n headers = self.extract_headers(array_of_dict)\n self._headers = headers\n self._valid_headers = True\n else:\n headers = self.extract_headers(array_of_dict)\n self._headers = headers\n self._valid_headers = False\n\n self._rows = array_of_dict\n return self\n\n def from_list(self, array_of_array, has_header=False, headers=None):\n import copy\n tmp = copy.deepcopy(array_of_array)\n _headers = None\n _valid_headers = False\n\n if has_header:\n _headers = [str(val).strip() for val in tmp.pop(0)]\n _valid_headers = True\n\n if headers:\n _headers = headers\n _valid_headers = True\n\n if not _headers:\n _headers = list(range(len(tmp[0])))\n _valid_headers = False\n\n data = []\n for row in tmp:\n data.append(dict(zip(_headers, row)))\n\n self.from_dict(data, _headers, valid_headers=_valid_headers)\n return self\n\n def from_text(self, text, sep=\",\", has_header=False):\n lines = text.rstrip().split(\"\\n\")\n _rows = []\n for line in lines:\n vals = list(map(lambda val: val.strip(), line.split(sep)))\n _rows.append(vals)\n return self.from_list(_rows, has_header)\n\n def _column_width(self, rows):\n data_t = list(zip(*rows))\n widths = list(map(lambda val: len(val), [max(row, key=len) for row in data_t]))\n return widths\n\n def _column_width_from_dict(self, rows):\n headers = self.extract_headers(rows)\n data = []\n for row in rows:\n data.append(list(map(lambda header: str(row.get(header, '')), headers)))\n widths = self._column_width(data)\n return dict(zip(headers, widths))\n\n def to_list_inner(self, rows_of_dict=None, default_widths=None):\n new_rows = []\n for row in rows_of_dict:\n new_row = []\n\n for header in self._headers:\n default_width = default_widths[header]\n val = str(row.get(header, ''))\n val = self._schema.format_column_value(\n header, val, default_width)\n new_row.append(val)\n\n new_rows.append(new_row)\n return new_rows\n\n def to_list(self, rows_of_dict=None, write_headers=True):\n # criteriaの準備\n data = []\n if not rows_of_dict:\n rows_of_dict = self._rows\n\n if write_headers and self._valid_headers:\n data.append(dict(zip(self._headers, self._headers)))\n data.extend(rows_of_dict)\n widths = self._column_width_from_dict(data)\n\n # to_list_innerを使ってself._rowsをフォーマット\n return self.to_list_inner(rows_of_dict=data, default_widths=widths)\n\n def to_dict(self, write_header=True):\n if not self._valid_headers:\n raise Exception(\"Headers not defined.\")\n\n new_rows = []\n array = self.to_list()\n\n if not write_header:\n array.pop(0)\n for row in array:\n new_rows.append(dict(list(zip(self._headers, row))))\n return new_rows\n\n def to_text(self, padding=1, end=\"\\n\", sep=\",\"):\n new_rows = []\n sep = ' ' * padding + sep + ' ' * padding\n for row in self.to_list():\n new_rows.append(sep.join(row))\n return \"\\n\".join(new_rows) + end\n\n def format_rows_to_dict(self, rows, write_headers=False, consider_headers=True):\n array = self.format_rows_to_list(rows, write_headers=write_headers, consider_headers=consider_headers)\n new_rows = []\n for row in array:\n new_rows.append(dict(list(zip(self._headers, row))))\n return new_rows\n\n def format_rows_to_list(self, rows, write_headers=False, consider_headers=True):\n import copy\n tmp = copy.deepcopy(rows)\n\n # criteriaの準備\n data = []\n if consider_headers and self._valid_headers:\n data.append(dict(zip(self._headers, self._headers)))\n data.extend(self._rows)\n widths = self._column_width_from_dict(data)\n\n if write_headers and self._valid_headers:\n tmp.insert(0, dict(zip(self._headers, self._headers)))\n\n # to_list_innerを使ってself._rowsをフォーマット\n array = self.to_list_inner(rows_of_dict=tmp, default_widths=widths)\n return array","sub_path":"src/kafka_admin/pyfixedwidths.py","file_name":"pyfixedwidths.py","file_ext":"py","file_size_in_byte":7504,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"91620178","text":"from __future__ import division,print_function\nfrom os import environ\nimport sys\nHOME=environ['HOME']\nPROJECT_ROOT=HOME+'/Panzer/NCSU/Spatial and Temporal/crater'\nEXPTS = PROJECT_ROOT+'/expts'\nsys.path.extend([PROJECT_ROOT,EXPTS])\nsys.dont_write_bytecode = True\n\nfrom sklearn.neural_network import BernoulliRBM\nfrom sklearn.linear_model import LogisticRegression\nfrom sklearn.pipeline import Pipeline\nfrom george.lib import *\nfrom expts.csvParser import parseCSV, randomPoints\nimport config\n\ndef builder(fname = config.TRAIN_FILE, hiddens=256, learn_rate=0.01):\n points = parseCSV(fname, False)\n rbm = BernoulliRBM(n_components=hiddens,learning_rate=learn_rate,n_iter=30,random_state=1)\n logistic = LogisticRegression(C=20)\n clf = Pipeline(steps=[('rbm', rbm), ('logistic',logistic)])\n X, y = [], []\n for point in points:\n X.append(normalize(point.x))\n y.append(point.y)\n clf.fit(X,y)\n return clf\n\ndef predictor(classifier, points):\n X,actuals = [], []\n for point in points:\n X.append(normalize(point.x))\n actuals.append(point.y)\n predicts = classifier.predict(X)\n return predicts, actuals\n\ndef _runner():\n hiddens = 250\n learn_rate = 0.01\n points = parseCSV(config.FEATURES_FOLDER+\"all.csv\", False)\n #points += parseCSV(config.FEATURES_FOLDER+\"1_25.csv\", False)\n classifier = builder(config.TRAIN_FILE, hiddens, learn_rate)\n predicted, actual = predictor(classifier, points)\n stat = ABCD()\n for p,a in zip(predicted,actual):\n stat.update(p, a)\n print(p, a)\n print(stat)\n\nif __name__==\"__main__\":\n _runner()","sub_path":"george/nn.py","file_name":"nn.py","file_ext":"py","file_size_in_byte":1547,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"10847891","text":"class Solution:\n def twoSum(self, nums, target):\n dict = {} # 元素 : 序号\n for i, num in enumerate(nums):\n another_num = target - num\n if another_num in dict:\n return [dict[another_num], i]\n dict[num] = i\n\ns = Solution()\nprint(s.twoSum([2, 7, 11, 15], 9))","sub_path":"初级算法/初级-数组-两数之和.py","file_name":"初级-数组-两数之和.py","file_ext":"py","file_size_in_byte":327,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"82320875","text":"import serial\nfrom time import sleep\n\n\nclass SerialDevice(object):\n\n WRITE_TERMINATION = '\\n'\n READ_TERMINATION = '\\n'\n\n ERRORS = {}\n\n def __init__(self, port, baudrate=9600, timeout=1):\n self._intf = serial.Serial(port=port, baudrate=baudrate, timeout=timeout) \n sleep(0.5) # Allow connections to be made\n \n def reset_buffers(self):\n \"\"\"\n Sleep for a bit and reset buffers to reset serial\n \"\"\"\n sleep(0.5)\n self._intf.reset_input_buffer()\n self._intf.reset_output_buffer()\n\n def write(self, msg):\n \"\"\"\n Write *msg* on the serial port. If necessary, convert to string and encode\n\n Parameters\n ----------\n msg : str, bytes\n Message to be written on the serial port\n \"\"\"\n if not isinstance(msg, bytes):\n msg = str(msg).encode()\n\n self._intf.write(msg + self.WRITE_TERMINATION.encode())\n\n def read(self):\n \"\"\"\n Reads from serial port until self.READ_TERMINATION byte is encountered.\n This is equivalent to serial.Serial.readline() but respects timeouts\n If the rad value is found in self.ERROS dict, raise a RuntimeError. If not just return read value\n\n Returns\n -------\n str\n Decoded, stripped string, read from serial port\n\n Raises\n ------\n RuntimeError\n Value read from serial bus is an error\n \"\"\"\n\n read_value = self._intf.read_until(self.READ_TERMINATION.encode()).decode().strip()\n\n if read_value in self.ERRORS:\n raise RuntimeError(self.ERRORS[read_value])\n \n return read_value\n\n def query(self, msg):\n \"\"\"\n Queries a message *msg* and reads the answer\n\n Parameters\n ----------\n msg : str, bytes\n Message to be queried\n\n Returns\n -------\n str\n Decoded, stripped string, read from serial port\n \"\"\"\n self.write(msg)\n return self.read()\n","sub_path":"irrad_control/devices/serial_device.py","file_name":"serial_device.py","file_ext":"py","file_size_in_byte":2037,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"137141282","text":"\"\"\"Resource and resource type graph API unit tests.\n\nTests:\n /core/resources/\n /core/resources/uuid/\n\n\"\"\"\n# Copyright 2015 Solinea, 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.\nimport json\n\nfrom django.conf import settings\nfrom mock import patch\nfrom rest_framework.status import HTTP_200_OK, HTTP_404_NOT_FOUND\n\nfrom goldstone.core.models import Host, AvailabilityZone, Hypervisor, \\\n Aggregate, Server, Project, Network, Limits, PolyResource, Image\nfrom goldstone.core import resource\nfrom goldstone.core.resource import Instances, GraphNode\nfrom goldstone.test_utils import Setup, create_and_login, \\\n AUTHORIZATION_PAYLOAD, BAD_UUID\n\n# Aliases to make the Resource Graph definitions less verbose.\nTYPE = settings.R_ATTRIBUTE.TYPE\n\nALLOCATED_TO = settings.R_EDGE.ALLOCATED_TO\nAPPLIES_TO = settings.R_EDGE.APPLIES_TO\nASSIGNED_TO = settings.R_EDGE.ASSIGNED_TO\nATTACHED_TO = settings.R_EDGE.ATTACHED_TO\nCONSUMES = settings.R_EDGE.CONSUMES\nCONTAINS = settings.R_EDGE.CONTAINS\nDEFINES = settings.R_EDGE.DEFINES\nINSTANCE_OF = settings.R_EDGE.INSTANCE_OF\nMANAGES = settings.R_EDGE.MANAGES\nMEMBER_OF = settings.R_EDGE.MEMBER_OF\nOWNS = settings.R_EDGE.OWNS\nROUTES_TO = settings.R_EDGE.ROUTES_TO\nSUBSCRIBED_TO = settings.R_EDGE.SUBSCRIBED_TO\nUSES = settings.R_EDGE.USES\n\n# URLs for the tests.\nRES_URL = \"/core/resources/\"\nRES_DETAIL_URL = RES_URL + \"%s/\"\n\n\nclass CoreResourcesUnpacking(Setup):\n \"\"\"The unpacking of persistent data into the in-memory graph.\"\"\"\n\n def test_unpacking_none(self):\n \"\"\"Test unpacking when the in-memory graph is empty.\"\"\"\n\n # Create two persistent graph rows, with one edge between them.\n image = Image.objects.create(native_id=\"bar\",\n native_name=\"foo\",\n edges=[],\n cloud_attributes={\"high\": \"school\"})\n project = Project.objects.create(native_id=\"foo\",\n native_name=\"bar\",\n edges=[(image.uuid,\n {\"edgescore\": 7})],\n cloud_attributes={\"madonn\": 'a'})\n\n # Unpack the graph\n resource.instances.graph # pylint: disable=W0104\n\n # Check the number of nodes and edges\n self.assertEqual(resource.instances.graph.number_of_nodes(), 2)\n self.assertEqual(resource.instances.graph.number_of_edges(), 1)\n\n # Check the node information.\n for entry, entrytype in ((image, Image), (project, Project)):\n node = resource.instances.get_uuid(entry.uuid)\n self.assertEqual(node.uuid, entry.uuid)\n self.assertEqual(node.resourcetype, entrytype)\n self.assertEqual(node.attributes, entry.cloud_attributes)\n\n # Check the edge information.\n edge = resource.instances.graph.edges(data=True)[0]\n self.assertEqual(edge[2], project.edges[0][1])\n\n def test_unpack_empty(self):\n \"\"\"Test unpacking an empty graph.\"\"\"\n\n # Create two persistent graph rows, with one edge between them.\n image = Image.objects.create(native_id=\"bar\",\n native_name=\"foo\",\n edges=[],\n cloud_attributes={\"high\": \"school\"})\n Project.objects.create(native_id=\"foo\",\n native_name=\"bar\",\n edges=[(image.uuid, {\"edgescore\": 7})],\n cloud_attributes={\"madonn\": 'a'})\n\n # Unpack the graph\n resource.instances.graph # pylint: disable=W0104\n\n # Delete the persistent graph.\n Image.objects.all().delete()\n Project.objects.all().delete()\n\n # Unpack an empty graph.\n resource.instances._graph = None # pylint: disable=W0212\n resource.instances.graph # pylint: disable=W0104\n\n # Check the number of nodes and edges\n self.assertEqual(resource.instances.graph.number_of_nodes(), 0)\n self.assertEqual(resource.instances.graph.number_of_edges(), 0)\n\n def test_unpack_bad_nodes(self):\n \"\"\"The persistent graph has edges that reference non-existent nodes.\"\"\"\n\n # Create five persistent graph rows and four edges. Two edges will\n # reference destination uuids that don't exist.\n #\n # image -> server, good\n server = Server.objects.create(native_id=\"bar\",\n native_name=\"foo\",\n edges=[],\n cloud_attributes={\"id\": \"42\"})\n image = Image.objects.create(native_id=\"bar77\",\n native_name=\"foo77\",\n edges=[(server.uuid, {\"some!\": \"stuff\"})],\n cloud_attributes={\"id\": \"42\"})\n # host -> hypervisor, but bad uuid used.\n hypervisor = \\\n Hypervisor.objects.create(native_id=\"bbbbbar\",\n native_name=\"fffffoo\",\n edges=[],\n cloud_attributes={\"hypervisor_hostname\":\n \"school\"})\n host = Host.objects.create(native_id=\"barfjohn\",\n native_name=\"foojohn\",\n edges=[(\"66\", {\"SOME\": \"stuFF\"})],\n cloud_attributes={\"host_name\": \"school\"})\n # project -> image, but bad uuid used.\n # project -> server, good\n project = \\\n Project.objects.create(native_id=\"sigh\",\n native_name=\"gasp\",\n edges=[(\"66666\", {\"edgescore\": 17}),\n (server.uuid, {\"success!\": True})],\n cloud_attributes={\"id\": '42'})\n\n # Unpack the graph\n resource.instances.graph # pylint: disable=W0104\n\n # Check the number of nodes and edges\n self.assertEqual(resource.instances.graph.number_of_nodes(), 5)\n self.assertEqual(resource.instances.graph.number_of_edges(), 2)\n\n # Check the node information.\n for entry, entrytype in ((server, Server), (image, Image),\n (hypervisor, Hypervisor), (host, Host),\n (project, Project)):\n node = resource.instances.get_uuid(entry.uuid)\n self.assertEqual(node.uuid, entry.uuid)\n self.assertEqual(node.resourcetype, entrytype)\n self.assertEqual(node.attributes, entry.cloud_attributes)\n\n # Check the edge information.\n edge_attributes = [x[2]\n for x in resource.instances.graph.edges(data=True)]\n self.assertIn({\"some!\": \"stuff\"}, edge_attributes)\n self.assertIn({\"success!\": True}, edge_attributes)\n\n\nclass CoreResources(Setup):\n \"\"\"Test /core/resources/.\"\"\"\n\n def test_empty(self):\n \"\"\"The resource graph is empty.\"\"\"\n\n # Create a user.\n token = create_and_login()\n\n # Mock out resources so that it has no nodes or edges.\n mock_r_graph = Instances()\n mock_r_graph.graph.clear()\n\n with patch(\"goldstone.core.views.resource.instances\", mock_r_graph):\n response = self.client.get(\n RES_URL,\n HTTP_AUTHORIZATION=AUTHORIZATION_PAYLOAD % token)\n\n # Test the result.\n # pylint: disable=E1101\n self.assertEqual(response.status_code, HTTP_200_OK)\n self.assertEqual(json.loads(response.content),\n {\"nodes\": [], \"edges\": []})\n\n def test_mix(self):\n \"\"\"The resource graph is populated with a mixture of nodes.\"\"\"\n\n # pylint: disable=R0914\n\n # The resource graph nodes in this test. Each entry is (resource_type,\n # native_id, native_name, attributes).\n NODES = [(Host, \"1234\", \"host 0\", {\"quality\": \"poor\"}),\n (Host, \"12345\", \"host 1\", {\"quality\": \"good\"}),\n (Host, \"123456\", \"host 2\", {\"quality\": \"poor\"}),\n (AvailabilityZone,\n \"a1\",\n \"availabilityzone 0\",\n {\"quality\": \"poor\"}),\n (AvailabilityZone,\n \"a2\",\n \"availabilityzone 1\",\n {\"quality\": \"good\"}),\n (AvailabilityZone,\n \"a3\",\n \"availabiltiyzone 2\",\n {\"quality\": \"poor\"}),\n (Hypervisor, \"f234\", \"hypervisor 0\", {\"quality\": \"poor\"}),\n (Hypervisor, \"f2345\", \"hypervisor 0\", {\"quality\": \"poor\"}),\n (Hypervisor, \"f23456\", \"hypervisor 0\", {\"quality\": \"good\"}),\n (Aggregate, \"dead1\", \"aggregate 0\", {\"quality\": \"poor\"}),\n (Aggregate, \"dead2\", \"aggregate 1\", {\"quality\": \"good\"}),\n (Server, \"beef1\", \"server 1\", {\"quality\": \"good\"}),\n (Server, \"beef2\", \"server 2\", {\"quality\": \"good\"}),\n (Project, \"p0\", \"project 0\", {\"quality\": \"poor\"}),\n (Project, \"p1\", \"project 1\", {\"quality\": \"poor\"}),\n (Project, \"p2\", \"project 2\", {\"quality\": \"good\"}),\n (Network, \"n1234\", \"network 0\", {\"quality\": \"good\"}),\n (Network, \"n12345\", \"network 1\", {\"quality\": \"good\"}),\n (Limits, \"l1234\", \"limits 0\", {\"quality\": \"good\"}),\n (Limits, \"l12345\", \"limits 1\", {\"quality\": \"good\"}),\n (Limits, \"l123456\", \"limits 2\", {\"quality\": \"good\"}),\n ]\n\n # The resource graph edges in this test. Each entry is (from, to,\n # attributes). The edge attributes here are meaningless.\n EDGES = [\n # Hosts\n (\"1234\", \"dead1\", {TYPE: ALLOCATED_TO}),\n (\"1234\", \"f2345\", {TYPE: APPLIES_TO}),\n (\"1234\", \"f23456\", {TYPE: ASSIGNED_TO}),\n # Availablity Zones\n (\"a3\", \"dead2\", {TYPE: CONSUMES}),\n (\"a2\", \"123456\", {TYPE: CONTAINS}),\n # Hypervisors\n (\"f23456\", \"beef2\", {TYPE: DEFINES}),\n # Projects\n (\"p1\", \"n1234\", {TYPE: INSTANCE_OF}),\n (\"p1\", \"n12345\", {TYPE: MANAGES}),\n (\"p2\", \"n1234\", {TYPE: MEMBER_OF}),\n (\"p2\", \"n12345\", {TYPE: OWNS}),\n (\"p0\", \"l1234\", {TYPE: ROUTES_TO}),\n (\"p0\", \"l12345\", {TYPE: SUBSCRIBED_TO}),\n (\"p0\", \"l123456\", {TYPE: USES}),\n (\"p2\", \"l1234\", {TYPE: ALLOCATED_TO}),\n (\"p2\", \"l12345\", {TYPE: APPLIES_TO}),\n (\"p2\", \"l123456\", {TYPE: ASSIGNED_TO}),\n ]\n\n # Expected node results, sans UUIDs.\n EXPECTED_NODES = [{u'native_id': u'p2',\n u'native_name': u'project 2',\n u'resourcetype':\n {u'label': u'projects',\n u'resourcetype': u'projects',\n u'unique_id':\n u\"\"},\n },\n {u'native_id': u'beef2',\n u'native_name': u'server 2',\n u'resourcetype':\n {u'label': u'servers',\n u'resourcetype': u'servers',\n u'unique_id':\n u\"\"},\n },\n {u'native_id': u'beef1',\n u'native_name': u'server 1',\n u'resourcetype':\n {u'label': u'servers',\n u'resourcetype': u'servers',\n u'unique_id':\n u\"\"},\n },\n {u'native_id': u'a2',\n u'native_name': u'availabilityzone 1',\n u'resourcetype':\n {u'label': u'availability zones',\n u'resourcetype': u'availability zones',\n u'unique_id':\n u\"\"\n },\n },\n {u'native_id': u'12345',\n u'native_name': u'host 1',\n u'resourcetype':\n {u'label': u'hosts',\n u'resourcetype': u'hosts',\n u'unique_id':\n u\"\"},\n },\n {u'native_id': u'p1',\n u'native_name': u'project 1',\n u'resourcetype':\n {u'label': u'projects',\n u'resourcetype': u'projects',\n u'unique_id':\n u\"\"},\n },\n {u'native_id': u'1234',\n u'native_name': u'host 0',\n u'resourcetype':\n {u'label': u'hosts',\n u'resourcetype': u'hosts',\n u'unique_id':\n u\"\"},\n },\n {u'native_id': u'l123456',\n u'native_name': u'limits 2',\n u'resourcetype':\n {u'label': u'limits',\n u'resourcetype': u'limits',\n u'unique_id':\n u\"\"},\n },\n {u'native_id': u'dead1',\n u'native_name': u'aggregate 0',\n u'resourcetype':\n {u'label': u'aggregates',\n u'resourcetype': u'aggregates',\n u'unique_id':\n u\"\"},\n },\n {u'native_id': u'dead2',\n u'native_name': u'aggregate 1',\n u'resourcetype':\n {u'label': u'aggregates',\n u'resourcetype': u'aggregates',\n u'unique_id':\n u\"\"},\n },\n {u'native_id': u'f23456',\n u'native_name': u'hypervisor 0',\n u'resourcetype':\n {u'label': u'hypervisors',\n u'resourcetype': u'hypervisors',\n u'unique_id':\n u\"\"},\n },\n {u'native_id': u'p0',\n u'native_name': u'project 0',\n u'resourcetype':\n {u'label': u'projects',\n u'resourcetype': u'projects',\n u'unique_id':\n u\"\"},\n },\n {u'native_id': u'f2345',\n u'native_name': u'hypervisor 0',\n u'resourcetype':\n {u'label': u'hypervisors',\n u'resourcetype': u'hypervisors',\n u'unique_id':\n u\"\"},\n },\n {u'native_id': u'n12345',\n u'native_name': u'network 1',\n u'resourcetype':\n {u'label': u'networks',\n u'resourcetype': u'networks',\n u'unique_id':\n u\"\"},\n },\n {u'native_id': u'a1',\n u'native_name': u'availabilityzone 0',\n u'resourcetype':\n {u'label': u'availability zones',\n u'resourcetype': u'availability zones',\n u'unique_id':\n u\"\"\n },\n },\n {u'native_id': u'n1234',\n u'native_name': u'network 0',\n u'resourcetype':\n {u'label': u'networks',\n u'resourcetype': u'networks',\n u'unique_id':\n u\"\"},\n },\n {u'native_id': u'123456',\n u'native_name': u'host 2',\n u'resourcetype':\n {u'label': u'hosts',\n u'resourcetype': u'hosts',\n u'unique_id':\n u\"\"},\n },\n {u'native_id': u'l12345',\n u'native_name': u'limits 1',\n u'resourcetype':\n {u'label': u'limits',\n u'resourcetype': u'limits',\n u'unique_id':\n u\"\"},\n },\n {u'native_id': u'l1234',\n u'native_name': u'limits 0',\n u'resourcetype':\n {u'label': u'limits',\n u'resourcetype': u'limits',\n u'unique_id':\n u\"\"},\n },\n {u'native_id': u'f234',\n u'native_name': u'hypervisor 0',\n u'resourcetype':\n {u'label': u'hypervisors',\n u'resourcetype': u'hypervisors',\n u'unique_id':\n u\"\"},\n },\n {u'native_id': u'a3',\n u'native_name': u'availabiltiyzone 2',\n u'resourcetype':\n {u'label': u'availability zones',\n u'resourcetype': u'availability zones',\n u'unique_id':\n u\"\"\n },\n },\n ]\n\n # Create the nodes for the test.\n for nodetype, native_id, native_name, attributes in NODES:\n if nodetype == Host:\n db_node = nodetype.objects.create(native_id=native_id,\n native_name=native_name,\n fqdn=native_name+\".com\")\n else:\n db_node = nodetype.objects.create(native_id=native_id,\n native_name=native_name)\n\n resource.instances.graph.add_node(GraphNode(uuid=db_node.uuid,\n resourcetype=nodetype,\n attributes=attributes))\n\n # Force the instance graph to be re-evaluated now.\n resource.instances._graph = None # pylint: disable=W0212\n\n # Create the edges for the test.\n for source_id, destination_id, attr_dict in EDGES:\n # Locate the source and destination nodes in the resource graph.\n source_row = PolyResource.objects.get(native_id=source_id)\n destination_row = \\\n PolyResource.objects.get(native_id=destination_id)\n\n source_node = [x for x in resource.instances.graph.nodes()\n if x.uuid == source_row.uuid][0]\n destination_node = [x for x in resource.instances.graph.nodes()\n if x.uuid == destination_row.uuid][0]\n\n resource.instances.graph.add_edge(source_node,\n destination_node,\n attr_dict=attr_dict)\n\n # Create a user, do the test.\n token = create_and_login()\n\n response = self.client.get(\n RES_URL,\n HTTP_AUTHORIZATION=AUTHORIZATION_PAYLOAD % token)\n\n # Test the results.\n # pylint: disable=E1101\n self.assertEqual(response.status_code, HTTP_200_OK)\n\n # Test the result's edges.\n content = json.loads(response.content)\n self.assertEqual(len(EDGES), len(content[\"edges\"]))\n\n edge_types_uses = [x[2][TYPE] for x in EDGES]\n edge_types_actual = [x[TYPE] for x in content[\"edges\"]]\n\n # For every edge attribute dictionary...\n for entry in set(edge_types_uses):\n # The count of this type used in this test must be found in the\n # response. This isn't a complete verification, but is good enough.\n self.assertEqual(edge_types_uses.count(entry),\n edge_types_actual.count(entry))\n\n # Test the result's nodes, sans UUIDs.\n for entry in content[\"nodes\"]:\n del entry[\"uuid\"]\n\n self.assertItemsEqual(content[\"nodes\"], EXPECTED_NODES)\n\n\nclass CoreResourcesDetail(Setup):\n \"\"\"Test /core/resource//.\"\"\"\n\n def test_empty(self):\n \"\"\"The resource graph is empty.\"\"\"\n\n # Create a user.\n token = create_and_login()\n\n # The parent class' setUp() has alcread cleared the resource graph.\n # Mock out resources so that it has no nodes or edges.\n response = self.client.get(\n RES_DETAIL_URL % BAD_UUID,\n HTTP_AUTHORIZATION=AUTHORIZATION_PAYLOAD % token)\n\n # Test the result.\n self.assertContains(response, '{}', status_code=HTTP_404_NOT_FOUND)\n\n def test_not_found(self):\n \"\"\"The desired resource isn't in the graph.\"\"\"\n\n # The resource graph nodes in this test. Each entry is (resource_type,\n # native_id, native_name, attributes). We don't create edges for these\n # nodes, because the code paths being tested don't need the edges in\n # the resource graph.\n NODES = [(Host, \"1234\", \"host 0\", {\"quality\": \"poor\"}),\n (Host, \"12345\", \"host 1\", {\"quality\": \"good\"}),\n (Host, \"123456\", \"host 2\", {\"quality\": \"poor\"}),\n ]\n\n # Create the nodes for the test.\n for nodetype, native_id, native_name, attributes in NODES:\n if nodetype == Host:\n db_node = nodetype.objects.create(native_id=native_id,\n native_name=native_name,\n fqdn=native_name+\".com\")\n else:\n db_node = nodetype.objects.create(native_id=native_id,\n native_name=native_name)\n\n resource.instances.graph.add_node(GraphNode(uuid=db_node.uuid,\n resourcetype=nodetype,\n attributes=attributes))\n\n # Create a user.\n token = create_and_login()\n\n # Now do the test.\n response = self.client.get(\n RES_DETAIL_URL % BAD_UUID,\n HTTP_AUTHORIZATION=AUTHORIZATION_PAYLOAD % token)\n\n # Test the result.\n self.assertContains(response, '{}', status_code=HTTP_404_NOT_FOUND)\n\n def test_mix(self):\n \"\"\"The desired resource is in the graph.\"\"\"\n\n # The resource graph nodes in this test. Each entry is (resource_type,\n # native_id, native_name, attributes). We don't create edges for these\n # nodes, because the code paths being tested don't need the edges in\n # the resource graph.\n NODES = [(Host, \"1234\", \"host 0\", {\"quality\": \"poor\"}),\n (Host, \"12345\", \"host 1\", {\"quality\": \"good\"}),\n (Host, \"123456\", \"host 2\", {\"quality\": \"poor\"}),\n (AvailabilityZone,\n \"a1\",\n \"availabilityzone 0\",\n {\"quality\": \"poor\"}),\n (AvailabilityZone,\n \"a2\",\n \"availabilityzone 1\",\n {\"quality\": \"good\"}),\n (AvailabilityZone,\n \"a3\",\n \"availabiltiyzone 2\",\n {\"quality\": \"poor\"}),\n (Hypervisor, \"f234\", \"hypervisor 0\", {\"quality\": \"poor\"}),\n (Hypervisor, \"f2345\", \"hypervisor 0\", {\"quality\": \"poor\"}),\n (Hypervisor, \"f23456\", \"hypervisor 0\", {\"quality\": \"good\"}),\n (Aggregate, \"dead1\", \"aggregate 0\", {\"quality\": \"poor\"}),\n (Aggregate, \"dead2\", \"aggregate 1\", {\"quality\": \"good\"}),\n (Server, \"beef1\", \"server 1\", {\"quality\": \"good\"}),\n (Server, \"beef2\", \"server 2\", {\"quality\": \"good\"}),\n (Project, \"p0\", \"project 0\", {\"quality\": \"poor\"}),\n (Project, \"p1\", \"project 1\", {\"quality\": \"poor\"}),\n (Project, \"p2\", \"project 2\", {\"quality\": \"good\"}),\n (Network, \"n1234\", \"network 0\", {\"quality\": \"good\"}),\n (Network, \"n12345\", \"network 1\", {\"quality\": \"good\"}),\n (Limits, \"l1234\", \"limits 0\", {\"quality\": \"good\"}),\n (Limits, \"l12345\", \"limits 1\", {\"quality\": \"good\"}),\n (Limits, \"l123456\", \"limits 2\", {\"quality\": \"good\"}),\n ]\n\n # Create the nodes for the test.\n for nodetype, native_id, native_name, attributes in NODES:\n if nodetype == Host:\n db_node = nodetype.objects.create(native_id=native_id,\n native_name=native_name,\n fqdn=native_name+\".com\")\n else:\n db_node = nodetype.objects.create(native_id=native_id,\n native_name=native_name)\n\n resource.instances.graph.add_node(GraphNode(uuid=db_node.uuid,\n resourcetype=nodetype,\n attributes=attributes))\n\n # Create a user.\n token = create_and_login()\n\n # Get the UUID of one of the nodes we just made, and calculate the\n # expected result. We deliberately do this crudely.\n response = self.client.get(\n RES_URL,\n HTTP_AUTHORIZATION=AUTHORIZATION_PAYLOAD % token)\n\n # pylint: disable=E1101\n uuid = json.loads(response.content)[\"nodes\"][1][\"uuid\"]\n\n for node in resource.instances.graph.nodes():\n if node.uuid == uuid:\n break\n else:\n node = None # Should never happen.\n\n row = PolyResource.objects.get(uuid=uuid) # Should always succeed.\n\n expected = {\"native_id\": row.native_id,\n \"native_name\": row.native_name,\n \"attributes\": node.attributes}\n\n # Now we can do the test.\n response = self.client.get(\n RES_DETAIL_URL % uuid,\n HTTP_AUTHORIZATION=AUTHORIZATION_PAYLOAD % token)\n\n self.assertEqual(response.status_code, HTTP_200_OK)\n self.assertEqual(json.loads(response.content), expected)\n","sub_path":"goldstone/core/tests_resource_api_2.py","file_name":"tests_resource_api_2.py","file_ext":"py","file_size_in_byte":29150,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"220902628","text":"'''\n\nJadon Lemkin\nPyCSV: A library to help Python interact with csv files.\n\n'''\n\nclass csv():\n def __init__(s,contents,config):\n s._raw = ''\n s.parsed = ''\n s.output = ''\n s.config = config\n if (type(contents) == str):\n s.parsed = s.parse(contents)\n s._raw = contents\n s.output = s._parse(s.parsed,'row')\n elif (type(contents) == list):\n s.parsed = contents\n s.output = s._parse(contents,'row')\n\n def _getConfig(s,k):\n if (k in s.config):\n return s.config[k]\n return {'use_headers':0,'verbose':0,'strict':0,'keyvalue':0}[k] #Inherit default properties\n\n def exists(s,x,y):\n return ( (x >= 0 and x <= len(s.parsed[0])-1) and (y >= 0 and y <= len(s.parsed)-1) )\n #return (s.inRange(x,0,len(s.parsed[0])-1) and s.inRange(y,0,len(s.parsed)-1) )\n \n def getcell(s,x,y):\n if (not s.exists(x,y)): #Does table contain specified cell\n if (s._getConfig('strict')):\n raise ValueError('Cell ({x},{y}) does not exist.')\n if (s._getConfig('verbose')):\n print(f'Cell ({x},{y}) does not exist.')\n return None\n if (s._getConfig('use_headers') and s._getConfig('keyvalue')):\n return {s.parsed[0][x]:s.parsed[y][x]}\n return s.parsed[y][x]\n\n def getcolumn(s,x):\n return list(row[x] for row in s.parsed)\n \n def getrow(s,y):\n return list(s.parsed[y])\n\n def getrange(s,x1,y1,x2,y2):\n if (not (s.exists(x1,y1+1) and s.exists(x2,y2+1))):\n if (s._getConfig('strict')):\n raise ValueError('Range outside of table.')\n if (s._getConfig('verbose')):\n ValueError('Range outside of table.')\n return None\n return csv(list(row[x1:x2+1] for row in s.parsed[y1:y2+1]),s.config)\n \n def setcell(s,x,y,v):\n if (not s.exists(x,y+s._getConfig('use_headers') )):\n if (s._getConfig('strict')):\n raise ValueError('Cell ({x},{y}) does not exist.')\n if (s._getConfig('verbose')):\n print(f'Cell ({x},{y}) does not exist.')\n return None\n s.parsed[ y + s._getConfig('use_headers') ][x] = v\n\n def addrow(s,r):\n if (type(r) == list):\n if (not len(r) == len(s.parsed[0])):\n if (s._getConfig('strict')):\n raise ValueError('Length of new row does not match that of table.')\n if (s._getConfig('verbose')):\n print('Length of new row does not match that of table. Creating blank row.')\n #add blank row to table\n s.parsed.append( ['']*len(s.parsed[0]) )\n return None\n #add specified row to table\n s.parsed.append(list(str(cell) for cell in r))\n \n def getrow(s,r):\n #If headers are enabled, check if the cell below exists\n if ( s.exists(0,r+s._getConfig('use_headers') )):\n if (s._getConfig('keyvalue') and s._getConfig('use_headers')):\n #keyvalue format: return dictionary of {header:cell}\n output = {}\n for ind,cell in enumerate(s.parsed[r+1]):\n output[s.parsed[0][ind]] = cell\n return output\n #Return non-dictionary format\n return s.parsed[r+s._getConfig('use_headers')]\n \n #If c does not exist\n if (s._getConfig('strict')):\n raise ValueError(f'Row {r} outside of table.')\n if (s._getConfig('verbose')):\n print(f'Row {r} outside of table.')\n return None\n \n def addcolumn(s,c):\n if (type(c) == list):\n if (not len(c) == len(s.parsed)):\n if (s._getConfig('strict')):\n raise ValueError('Length of new column does not match that of table.')\n if (s._getConfig('verbose')):\n print('Length of new column does not match that of table. Creating blank column.')\n #For row in table, add to row\n for row in s.parsed:\n row.append('')\n return\n #For row,index in table, add to row\n for ind,row in enumerate(s.parsed):\n row.append(c[ind])\n \n def getcolumn(s,c):\n if (type(c) == str and s._getConfig('use_headers')):\n index = s.parsed[0].index(c)\n if (s._getConfig('keyvalue')):\n return {s.parsed[0][index]:list(row[index] for row in s.parsed)[1::]}\n return csv(list(row[index] for row in s.parsed[1::]),s.config)\n if (s.exists(c,0)):\n if (s._getConfig('keyvalue') and s._getConfig('use_headers')):\n #keyvalue format: return dictionary of {header:list of cells}\n return {s.parsed[0][c]:list(row[c] for row in s.parsed)[1::]}\n \n return csv(list(row[c] for row in s.parsed),s.config) #for every row in column, return cell\n\n #If c does not exist\n if (s._getConfig('strict')):\n raise ValueError(f'Column {c} outside of table.')\n if (s._getConfig('verbose')):\n print(f'Column {c} outside of table.')\n return None\n \n def collapserow(s,func):\n #if (s._getConfig('use_headers') and s._getConfig('keyvalue')):\n # return dict([s.parsed[0][col],func(list(row[col] for row in s.parsed[s._getConfig('use_headers')::]))] for col in range(0,len(s.parsed[0])))\n \n return csv(list(func(list(row[col] for row in s.parsed[s._getConfig('use_headers')::])) for col in range(0,len(s.parsed[0]))),s.config) #for each column\n\n def importraw(s,r):\n s._raw = r\n s.parsed = s.parse(r)\n \n def exportraw(s):\n if (not s.verify()):\n print('Warning: csv is invalid!')\n s._raw = '\\n'.join(','.join(row) for row in s.parsed)\n return s._raw\n \n # At the moment, rotate lacks keyvalue support\n def rotate(s):\n return list( list((row[column] for row in s.parsed)) for column in range(0,len(s.parsed[0])) )\n\n def split(s,col):\n output = {}\n for row in s.parsed[s._getConfig('use_headers')::]:\n if (row[col] in output):\n output[row[col]].append(row)\n else:\n output[row[col]] = [row]\n return dict([i,csv(output[i],s.config)] for i in output)\n \n def verify(s):\n return all((len(row) == len(s.parsed[0]) for row in s.parsed))\n \n def parse(s,r):\n return list(row.split(',') for row in r.split('\\n'))\n def _parse(s,r,di):\n if (s._getConfig('use_headers') and s._getConfig('keyvalue')):\n if (di == 'col'):\n #column-joined dictionary output\n return ([ s.parsed[0][col], list(row[col] for row in s.parsed[1::]) ] for col in range(0,len(s.parsed[0])))\n #row-joined dictionary output\n return list(dict([s.parsed[0][ind],cell] for ind,cell in enumerate(row)) for row in s.parsed[1::])\n\n #return list(row.split(',') for row in r.split('\\n'))\n else:\n if (di == 'col'):\n return list((row[col] for row in s.parsed) for col in range(0,len(s.parsed[0])))\n return s.parsed\n","sub_path":"python_csv.py","file_name":"python_csv.py","file_ext":"py","file_size_in_byte":9069,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"497020594","text":"\"\"\"\nOverview\n========\n\nThis plugin implements a way to place the cursor at a given row.col.\n\nUsage\n=====\n\nWhen dealing with some programming files we get some warnings/errors from the interpreter/compiler\nthen we need to quickly jump to that line to see whats going on.\n\nIn order to make the cursor jump to a given line.row, just press in NORMAL mode.\nIt will show up an input data field where you can insert the line or the row.\n\nExample:\n\nWould make the cursor be placed at the line 30 and at the col 4.\n30.4\n\nWould make the cursor be placed at the line 30 and at the col 0.\n10\n\nKey-Commands\n============\n\nMode: NORMAL\nEvent: \nDescription: Shows an input text field to insert a Line.Col value to place the cursor at that position.\n\n\"\"\"\nfrom vyapp.ask import *\n\ndef go_to_pos(area):\n ask = Ask(area, '')\n\n if not ask.data: return\n\n try:\n line, col = ask.data.split('.')\n except ValueError:\n area.setcurl(ask.data)\n else:\n area.setcur(line, col) \n\ninstall = lambda area: area.install(('NORMAL', '', lambda event: go_to_pos(event.widget)))\n\n\n\n\n\n","sub_path":"vy-code/vyapp/plugins/set_pos.py","file_name":"set_pos.py","file_ext":"py","file_size_in_byte":1096,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"524491947","text":"import socket\nimport time\n\nfrom .BaseSink import BaseSink\n\n\nclass UdpSink(BaseSink):\n def __init__(self, module, server, port):\n super().__init__(module, server, port)\n \n self.socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)\n\n def trace(self, level, module, frame, text):\n m = super().pack(level, module, frame, text)\n \n self.socket.sendto(m, (self.server, self.port))\n\n\nclass TcpSink(BaseSink):\n def __init__(self, module, server, port):\n super().__init__(module, server, port)\n \n self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n self.connected = False\n self.lastConnectAttempt = None\n self.__connect() \n\n def __connect(self):\n if self.connected:\n return True\n\n now = time.time()\n\n if (not self.lastConnectAttempt) or (now - self.lastConnectAttempt > 5):\n self.lastConnectAttempt = now\n\n try:\n self.socket.connect((self.server, self.port))\n self.connected = True\n except:\n print (\"Failed to connect to \" + self.server + \":\" + str(self.port))\n return False\n\n return True\n\n return False \n\n def trace(self, level, module, frame, text):\n if not self.__connect():\n return\n\n m = super().pack(level, module, frame, text)\n self.socket.send(m)\n \n\n","sub_path":"tools/PySketch/Trace/NetSink.py","file_name":"NetSink.py","file_ext":"py","file_size_in_byte":1466,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"563917989","text":"from flask import Blueprint, render_template, session, request, url_for\r\nfrom werkzeug.utils import redirect\r\n\r\nfrom src.models.articles.article import Article\r\nfrom src.models.users.user import User\r\n\r\nimport src.models.users.decorators as user_decorators\r\nimport src.models.admin_panel.decorators as admin_decorators\r\n\r\narticle_blueprint = Blueprint('articles', __name__)\r\n\r\n\r\n@article_blueprint.route('/')\r\n@user_decorators.requires_login\r\ndef show_article(article_id):\r\n user = User.find_user_hashed(session['login'])\r\n article = Article.find_by_id(article_id)\r\n author = User.find_user_by_id(article.author_id)\r\n article_list = Article.find_all(order_by='sort_index', only_published=True)\r\n\r\n context = {\r\n 'user': user,\r\n 'article': article,\r\n 'author': author,\r\n 'article_list': article_list\r\n }\r\n return render_template('articles/article.jinja2', context=context)\r\n\r\n\r\n@article_blueprint.route('/edit/', methods=['GET', 'POST'])\r\n@user_decorators.requires_login\r\n@admin_decorators.requires_admin_permission\r\ndef edit(article_id):\r\n article = Article.find_by_id(article_id)\r\n user = User.find_user_hashed(session['login'])\r\n # Edit an article and save to database if request method is POST\r\n if request.method == 'POST':\r\n\r\n article.title = request.form['title']\r\n article.text = request.form['text']\r\n article.style = request.form['style']\r\n article.sort_index = request.form['sort_index']\r\n article.is_published = True if 'is_published' in request.form else False\r\n # article.parent_id = request.form['parent_id'] # Not in use yet\r\n\r\n article.save_to_db()\r\n return redirect(url_for('articles.show_article', article_id=article_id))\r\n\r\n # If request method is GET, just render a form\r\n context = {\r\n 'user': user,\r\n 'article': article\r\n }\r\n return render_template('articles/edit_article.jinja2', context=context)\r\n\r\n\r\n@article_blueprint.route('/delete/')\r\n@user_decorators.requires_login\r\n@admin_decorators.requires_admin_permission\r\ndef delete(article_id):\r\n # Find an article and mark it as deleted\r\n article = Article.find_by_id(article_id)\r\n article.is_deleted = True\r\n article.save_to_db()\r\n # Redirect to admin panel\r\n return redirect(url_for('admin.manage_articles'))\r\n\r\n\r\n@article_blueprint.route('/create', methods=['GET', 'POST'])\r\n@user_decorators.requires_login\r\n@admin_decorators.requires_admin_permission\r\ndef create():\r\n user = User.find_user_hashed(session['login'])\r\n # Create an article and save to database if request method is POST\r\n if request.method == 'POST':\r\n author_id = user.id\r\n title = request.form['title']\r\n text = request.form['text']\r\n style = request.form['style']\r\n sort_index = request.form['sort_index']\r\n is_published = True if 'is_published' in request.form else False\r\n # article.parent_id = request.form['parent_id'] # Not in use yet\r\n article = Article(title=title, text=text, style=style, author_id=author_id,\r\n sort_index=sort_index, is_published=is_published)\r\n article.save_to_db()\r\n # We can't get new article ID in that moment, so redirecting to the admin panel instead\r\n return redirect(url_for('admin.manage_articles'))\r\n\r\n # If request method is GET, just render a form\r\n context = {\r\n 'user': user\r\n }\r\n return render_template('articles/create_article.jinja2', context=context)\r\n pass\r\n","sub_path":"src/models/articles/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":3598,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"234313665","text":"\n\n#calss header\nclass _OVERCOOK():\n\tdef __init__(self,): \n\t\tself.name = \"OVERCOOK\"\n\t\tself.definitions = [u'to cook food for longer than necessary, reducing its quality as a result: ']\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/_overcook.py","file_name":"_overcook.py","file_ext":"py","file_size_in_byte":357,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"229933490","text":"import asyncio\n\nimport discord\nimport datetime\nimport pytz\nfrom discord.ext import commands\nfrom IreneUtility.util import u_logger as log\nfrom IreneUtility.Utility import Utility\n\n\n# noinspection PyBroadException,PyPep8\nclass Profile(commands.Cog):\n def __init__(self, ex):\n \"\"\"\n\n :param ex: Utility object.\n \"\"\"\n self.ex: Utility = ex\n\n @commands.command()\n async def avatar(self, ctx, user: discord.Member = None):\n try:\n if not user:\n user_id = ctx.author.id\n user = ctx.author\n else:\n user_id = user.id\n embed = await self.ex.create_embed(title=f\"{user.display_name}'s Avatar ({user_id})\")\n embed.set_image(url=user.avatar_url)\n await ctx.send(embed=embed)\n except Exception as e:\n log.console(e)\n\n @commands.command()\n async def profile(self, ctx, user: discord.Member = None):\n try:\n if not user:\n user_id = ctx.author.id\n user = ctx.author\n roles_list = []\n else:\n user_id = user.id\n roles_list = user.roles\n if user.bot:\n user_bot = \"Yes\"\n else:\n user_bot = \"No\"\n\n irene_user = await self.ex.get_user(user_id)\n\n count = 0\n roles = \"\"\n for role in roles_list:\n await asyncio.sleep(0)\n if count and count != (len(roles_list) - 1):\n roles += f\"{role.name}, \"\n if count == (len(roles_list)-1):\n roles += role.name\n count += 1\n\n if len(roles) > 500:\n roles = f\"{roles[0:498]}....\"\n\n user_level = irene_user.profile_level\n shortened_money = await irene_user.get_shortened_balance()\n rob_beg_daily_level = f\"{irene_user.rob_level}/{irene_user.beg_level}/{irene_user.daily_level}\"\n\n user_scores = f\"{await self.ex.u_guessinggame.get_user_score('easy', user_id)}/\" \\\n f\"{await self.ex.u_guessinggame.get_user_score('medium', user_id)}/\" \\\n f\"{await self.ex.u_guessinggame.get_user_score('hard', user_id)}\"\n user_timezone = await self.ex.u_reminder.get_user_timezone(user_id)\n\n try:\n timezone_utc = datetime.datetime.now(pytz.timezone(user_timezone)).strftime('%Z, UTC%z')\n except:\n timezone_utc = None\n\n if await self.ex.u_patreon.check_if_patreon(user_id):\n embed = discord.Embed(title=f\"{user.name} ({user_id})\", color=0x90ee90, url=f\"{user.avatar_url}\",\n description=f\"**{user.name} is supporting Irene on Patreon!**\")\n else:\n embed = discord.Embed(title=f\"{user.name} ({user_id})\", color=0x90ee90, url=f\"{user.avatar_url}\")\n embed = await self.ex.set_embed_author_and_footer(embed, \"Thanks for using Irene!\")\n\n try:\n user_activity = user.activity.name\n except:\n user_activity = None\n\n embed.set_thumbnail(url=user.avatar_url)\n embed.add_field(name=\"Profile Level\", value=user_level, inline=True)\n embed.add_field(name=\"Money\", value=f\"${shortened_money}\", inline=True)\n\n if type(user) == discord.Member:\n embed.add_field(name=\"Status\", value=f\"{user.status}\", inline=True)\n embed.add_field(name=\"Server Nickname\", value=user.nick, inline=True)\n embed.add_field(name=\"Server Join Date\", value=user.joined_at, inline=True)\n if roles:\n embed.add_field(name=\"Roles\", value=roles, inline=False)\n\n embed.add_field(name=\"Rob/Beg/Daily Level\", value=rob_beg_daily_level, inline=True)\n embed.add_field(name=\"Account Join Date\", value=user.created_at, inline=True)\n embed.add_field(name=\"Bot\", value=user_bot, inline=True)\n\n if user_activity:\n embed.add_field(name=\"Activity\", value=user_activity, inline=True)\n\n if user_timezone:\n embed.add_field(name=\"Timezone\", value=f\"{user_timezone} ({timezone_utc})\", inline=True)\n\n embed.add_field(name=\"GuessingGame [Easy/Medium/Hard]\", value=user_scores, inline=True)\n\n await ctx.send(embed=embed)\n\n except Exception as e:\n server_prefix = await self.ex.get_server_prefix(ctx)\n await ctx.send(f\"> **There was an error. Please {server_prefix}report it**\")\n log.console(e)\n\n async def increase_profile_level(self, msg):\n \"\"\"Increase the profile level appropriately after every message.\"\"\"\n # do not attempt to increase level if cache is not loaded\n # this is very dangerous as it can reset all the profile levels for the users sent here\n # if it takes too long for cache to load.\n if not self.ex.irene_cache_loaded:\n return\n\n user = await self.ex.get_user(msg.author.id)\n try:\n xp_per_message = 10\n current_level = user.profile_level\n current_xp = await user.get_profile_xp()\n xp_needed_for_level = await user.get_needed_for_level(current_level, \"profile\")\n\n if current_xp + xp_per_message < xp_needed_for_level:\n return await user.set_profile_xp(current_xp + xp_per_message)\n await user.set_profile_xp(1)\n await user.set_level(current_level + 1, \"profile\")\n except Exception as e:\n log.useless(f\"{e} (Exception) - {user.id} failed to increase profile level\",\n method=self.increase_profile_level)\n","sub_path":"module/Profile.py","file_name":"Profile.py","file_ext":"py","file_size_in_byte":5780,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"171508750","text":"import configparser\nimport json\nimport os\nfrom datetime import datetime\n\n\nconfig = configparser.ConfigParser()\n\n# config\nCONFIG_DIR = 'config'\nCONFIG_FILE_NAME = 'config.ini'\nCONFIG_PATH = os.path.join(os.getcwd(), CONFIG_DIR, CONFIG_FILE_NAME)\n\ntry:\n config.read(CONFIG_PATH, encoding='utf-8')\nexcept IOError:\n print('File {} does not exist. Exit!'.format(CONFIG_PATH))\n exit(1)\n\n# `__file__` is relative to the current working directory\n# `os.chdir()` can change current working directory, but don't change `__file__`\n# so if `os.chdir()` is used, this method fails to get current directory\n# current_dir = os.path.dirname(os.path.realpath(__file__))\n# COOKIES = open(os.path.join(current_dir, 'cookie.txt'), 'r').readline().strip()\n\n# cookie\nCOOKIE = config['BASIC']['cookie']\n\n# behavior\nconfig_behavior = config['BEHAVIOR']\nGRANULARITY_HOUR = config_behavior.getboolean('granularity_hour')\nFORCE_CRAWL = config_behavior.getboolean('force_crawl')\n\n# common\nconfig_common = config['COMMON']\nDOLLAR_TO_CNY = float(config_common['dollar_to_cny'])\nSTEAM_SELL_TAX = float(config_common['steam_sell_tax'])\nTIMESTAMP = str(datetime.now().strftime('%Y-%m-%d-%H:%M:%S'))\n\n# filter\n# 爬取历史价格的话,每个都要单独爬一次,爬取量翻了好几十倍,所以扔掉一些,只爬取某个价格区间内的饰品……\n# 大致价格分位点:0 - 10000; 20 - 5000; 50 - 4000; 100 - 3400; 200 - 3000; 500 - 2200; 1000 - 1200\nconfig_filter = config['FILTER']\nCRAWL_MIN_PRICE_ITEM = int(config_filter['crawl_min_price_item'])\nCRAWL_MAX_PRICE_ITEM = int(config_filter['crawl_max_price_item'])\nMIN_SOLD_THRESHOLD = int(config_filter['min_sold_threshold'])\n# https://stackoverflow.com/questions/335695/lists-in-configparser\n# CATEGORY_BLACK_LIST = json.loads(config_filter['category_black_list'])\n\n# result\nTOP_N = int(config['RESULT']['top_n'])\n\n# 文件\nDATE_DAY = str(datetime.now().strftime('%Y-%m-%d'))\nDATE_HOUR = str(datetime.now().strftime('%Y-%m-%d-%H'))\nDATE_TIME = DATE_HOUR if GRANULARITY_HOUR else DATE_DAY\n\n# data file\nDATABASE_PATH = \"database\"\nDATABASE_FILE = os.path.join(DATABASE_PATH, \"csgo_skins_\" + DATE_TIME + \".csv\")\nDATABASE_FILE_DAY = os.path.join(DATABASE_PATH, \"csgo_skins_\" + DATE_DAY + \".csv\")\n\n# log file\nLOG_PATH = \"log\"\nNORMAL_LOGGER = os.path.join(LOG_PATH, 'log_' + DATE_TIME + '.log')\n\n# suggestion file\nSUGGESTION_PATH = \"suggestion\"\nSUGGESTION_LOGGER = os.path.join(SUGGESTION_PATH, 'suggestion_' + DATE_TIME + '.txt')\n","sub_path":"src/config/definitions.py","file_name":"definitions.py","file_ext":"py","file_size_in_byte":2474,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"171819986","text":"#!/usr/bin/env python2.7.\nimport sys; sys.path.append('..') # help python find open_bci_v3.py relative to scripts folder\nimport open_bci_v3 as bci\nimport os\nimport matplotlib.pyplot as plt # for plot\nimport collections # circular buffer\nimport time # sleep functions\ni = 0\n\ndef printData(sample):\n\t#os.system('clear')\n\t# print \"----------------\"\n\t# print(\"%f\" %(sample.id))\n\t# print sample.channel_data[channel]\n\tglobal i\n\ti += 1\n\n\tdataBuff.append(sample.channel_data[channel])\n\ttempBuff.append(i)\n\n\t# print dataBuff\n\t# print tempBuff\n\t# tempBuff.append(sample.id)\n\n\tplt.plot(tempBuff, dataBuff)\n\tplt.draw()\n # time.sleep(0.05)\n\n\t# print sample.aux_data\n\t# print \"----------------\"\n\nif __name__ == '__main__':\n\t# Circular buffer setup\n\tbufflen = 250\n\n\tdataBuff = collections.deque(maxlen = bufflen)\n\ttempBuff = collections.deque(maxlen = bufflen)\n\n\t# Which channel will be plotted\n\tchannel = 1;\n\n\t# Plot figure setup\n\t# plt.axis([0, 1000, 0, 1])\n\tplt.ion()\n\tplt.show()\n\tplt.hold(False) # hold is off\n\n\tport = '/dev/ttyUSB0'\n\tbaud = 115200\n\tboard = bci.OpenBCIBoard(port=port, baud=baud)\n\tboard.test_signal(3) # set all input channels to 0\n\n\ttime.sleep(1) # need to include this to wait for test config setup\n\n\tboard.start_streaming(printData)\n\n","sub_path":"read_plot_1ch.py","file_name":"read_plot_1ch.py","file_ext":"py","file_size_in_byte":1247,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"339853402","text":"from sqlalchemy import create_engine\nfrom sqlalchemy.orm import sessionmaker\n\n# from sqlalchemy_utils import database_exists, drop_database, create_database\n\nfrom database_setup import Category # Category is name of Class in database\nfrom database_setup import CatalogItem # Item is name of Class in database\nfrom database_setup import Base\n\nengine = create_engine('postgresql://catalog:password@localhost/catalog')\n\n# Clear database\nBase.metadata.drop_all(engine)\nBase.metadata.create_all(engine)\n\nBase.metadata.bind = engine\n\nDBSession = sessionmaker(bind=engine)\nsession = DBSession()\n\n\ncategory1 = Category(name=\"Horror\")\nsession.add(category1)\nsession.commit()\n\nitem1 = CatalogItem(\n name=\"Gok-seong\",\n description=\" min:156 | year:2016 \",\n price=\"18$\",\n category=category1)\nsession.add(item1)\nsession.commit()\n\nitem2 = CatalogItem(\n name=\"28 Days Later\",\n description=\" min:113 | year:2002 \",\n price=\"14$\",\n category=category1)\nsession.add(item2)\nsession.commit()\n\nitem3 = CatalogItem(\n name=\"Lat den ratte komma in\",\n description=\" min:115 | year:2008 \",\n price=\"8$\",\n category=category1)\nsession.add(item3)\nsession.commit()\n\nitem4 = CatalogItem(\n name=\"Busanhaeng\",\n description=\" min:118 | year:2016 \",\n price=\"15$\",\n category=category1)\nsession.add(item4)\nsession.commit()\n\nitem5 = CatalogItem(\n name=\"The Conjuring\",\n description=\" min:112 | year:2013 \",\n price=\"8$\",\n category=category1)\nsession.add(item5)\nsession.commit()\n\nitem6 = CatalogItem(\n name=\"Pitch Black\",\n description=\" min:109 | year:2000 \",\n price=\"9$\",\n category=category1)\nsession.add(item6)\nsession.commit()\n\nitem7 = CatalogItem(\n name=\"A Quiet Place \",\n description=\" min:90 | year:2018 \",\n price=\"11$\",\n category=category1)\nsession.add(item7)\nsession.commit()\n\nitem8 = CatalogItem(\n name=\"[Rec]\",\n description=\" min:78 | year:2007 \",\n price=\"5$\",\n category=category1)\nsession.add(item8)\nsession.commit()\n\ncategory2 = Category(name=\"Action\")\nsession.add(category2)\nsession.commit()\n\nitem9 = CatalogItem(\n name=\"The Equalizer\",\n description=\" min:132 | year:2014 \",\n price=\"8$\",\n category=category2)\nsession.add(item9)\nsession.commit()\n\nitem10 = CatalogItem(\n name=\"The Equalizer 2\",\n description=\" min:121 | year:2018 \",\n price=\"9$\",\n category=category2)\nsession.add(item10)\nsession.commit()\n\nitem11 = CatalogItem(\n name=\"Mad Max: Fury Road\",\n description=\" min:120 | year:2015 \",\n price=\"13$\",\n category=category2)\nsession.add(item11)\nsession.commit()\n\nitem12 = CatalogItem(\n name=\"Logan\",\n description=\" min:137 | year:2017 \",\n price=\"5$\",\n category=category2)\nsession.add(item12)\nsession.commit()\n\nitem13 = CatalogItem(\n name=\"Black Panther\",\n description=\" min:134 | year:2018 \",\n price=\"16$\",\n category=category2)\nsession.add(item13)\nsession.commit()\n\nitem14 = CatalogItem(\n name=\"Wonder Woman\",\n description=\" min:141 | year:2017 \",\n price=\"3$\",\n category=category2)\nsession.add(item14)\nsession.commit()\n\nitem15 = CatalogItem(\n name=\"Aquaman\",\n description=\" min:143 | year:2018 \",\n price=\"10$\",\n category=category2)\nsession.add(item15)\nsession.commit()\n\nitem16 = CatalogItem(\n name=\"Dunkirk\",\n description=\" min:106 | year:2017 \",\n price=\"7$\",\n category=category2)\nsession.add(item16)\nsession.commit()\n\ncategory3 = Category(name=\"comedy\")\nsession.add(category3)\nsession.commit()\n\nitem17 = CatalogItem(\n name=\"Step Brothers\",\n description=\" min:98 | year:2008 \",\n price=\"14$\",\n category=category3)\nsession.add(item17)\nsession.commit()\n\nitem18 = CatalogItem(\n name=\"White Chicks\",\n description=\" min:109 | year:2004 \",\n price=\"12$\",\n category=category3)\nsession.add(item18)\nsession.commit()\n\nitem19 = CatalogItem(\n name=\"The Hot Chick\",\n description=\" min:104 | year:2002 \",\n price=\"11$\",\n category=category3)\nsession.add(item19)\nsession.commit()\n\nitem20 = CatalogItem(\n name=\"The Hangover\",\n description=\" min:100 | year:2009 \",\n price=\"9$\",\n category=category3)\nsession.add(item20)\nsession.commit()\n\nitem21 = CatalogItem(\n name=\"Horrible Bosses\",\n description=\" min:98 | year:2011 \",\n price=\"5$\",\n category=category3)\nsession.add(item21)\nsession.commit()\n","sub_path":"fakedata.py","file_name":"fakedata.py","file_ext":"py","file_size_in_byte":4296,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"501950190","text":"import sublime, sublime_plugin\n\nclass BuildResultView(sublime_plugin.EventListener):\n\n class Context:\n def __init__(self, window, out_view, last_read, buffer):\n self.window = window\n self.out_view = out_view\n self.last_read = last_read\n self.buffer = buffer\n\n def __init__(self):\n self.context_table = {}\n\n def on_post_window_command(self, window, command_name, args):\n if command_name != \"build\": return\n if args != None and args.get('select', False): return\n\n # Get build result panel and create context if it doesn't exist\n build_panel = window.find_output_panel(\"exec\")\n if build_panel.id() not in self.context_table:\n self.context_table[build_panel.id()] = self.Context(window, None, 0, \"\")\n\n context = self.context_table[build_panel.id()]\n\n context.last_read = 0\n\n # We save these values now, so that we don't lose them when we create a new output view.\n orig_view = window.active_view()\n orig_group = window.active_group()\n\n if context.out_view == None or -1 in context.window.get_view_index(context.out_view):\n context.out_view = None\n\n # Try to find an output view from an earlier session\n for view in context.window.views():\n if view.settings().get(\"is_build_result_output_view\", False):\n context.out_view = view\n break\n\n if context.out_view == None:\n # Create new output view\n new_view = window.new_file()\n new_view.set_name(\"Build results\")\n new_view.set_scratch(True)\n new_view.set_read_only(True)\n new_view.settings().set(\"is_build_result_output_view\", True)\n context.out_view = new_view\n\n # Copy settings from build build_panel view to output view\n build_panel_settings = build_panel.settings()\n for key in [\"result_file_regex\",\n \"result_line_regex\",\n \"result_base_dir\",\n \"word_wrap\",\n \"line_numbers\",\n \"gutter\",\n \"scroll_past_end\"]:\n context.out_view.settings().set(key, build_panel_settings.get(key))\n context.out_view.assign_syntax(build_panel_settings.get(\"syntax\"))\n\n # Move output view if necessary\n if orig_view.id() != context.out_view.id():\n window.focus_view(context.out_view)\n if window.num_groups() > 1:\n target_group = orig_group + 1\n if target_group >= window.num_groups():\n target_group = orig_group - 1\n window.set_view_index(context.out_view, target_group, 0)\n window.focus_view(orig_view)\n\n # Clear output view, and fill it with any buffered contents\n context.out_view.run_command(\"write_to_output_view\", {\n 'content': context.buffer,\n 'begin': 0,\n 'end': context.out_view.size()\n })\n context.buffer = \"\"\n\n def on_modified(self, modified_view):\n # Check if the modified view is a known build panel\n context = None\n for panel_id in self.context_table:\n if panel_id == modified_view.id():\n context = self.context_table[panel_id]\n break\n if context == None: return\n\n begin = context.last_read\n end = modified_view.size()\n content = modified_view.substr(sublime.Region(begin, end))\n\n # If we don't have an output view for some reason, buffer the output until we do\n if context.out_view == None:\n context.buffer += content\n else:\n # If we have buffered content, prepend it\n if len(context.buffer) > 0:\n content = context.buffer + content\n context.buffer = \"\"\n context.out_view.run_command(\"write_to_output_view\", {\n 'content': content,\n 'begin': begin,\n 'end': end\n })\n\n context.last_read = end\n\nclass WriteToOutputView(sublime_plugin.TextCommand):\n def run(self, edit, content, begin, end):\n self.view.set_read_only(False)\n self.view.replace(edit, sublime.Region(begin, end), content)\n self.view.set_read_only(True)\n self.view.show(end)\n","sub_path":"BuildResultView.py","file_name":"BuildResultView.py","file_ext":"py","file_size_in_byte":4434,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"310973905","text":"#!/usr/bin/env python\n# Copyright (c) 2012 The Chromium Authors. All rights reserved.\n# Use of this source code is governed by a BSD-style license that can be\n# found in the LICENSE file.\n\nimport re\n\n\nclass GTestLogParser(object):\n \"\"\"This helper class process GTest test output.\"\"\"\n\n def __init__(self):\n # State tracking for log parsing\n self._current_test = ''\n self._failure_description = []\n self._current_suppression_hash = ''\n self._current_suppression = []\n self._parsing_failures = False\n\n # Line number currently being processed.\n self._line_number = 0\n\n # List of parsing errors, as human-readable strings.\n self._internal_error_lines = []\n\n # Tests are stored here as 'test.name': (status, [description]).\n # The status should be one of ('started', 'OK', 'failed', 'timeout',\n # 'warning'). Warning indicates that a test did not pass when run in\n # parallel with other tests but passed when run alone. The description is\n # a list of lines detailing the test's error, as reported in the log.\n self._test_status = {}\n\n # Suppressions are stored here as 'hash': [suppression].\n self._suppressions = {}\n\n # This may be either text or a number. It will be used in the phrase\n # '%s disabled' or '%s flaky' on the waterfall display.\n self._disabled_tests = 0\n self._flaky_tests = 0\n\n # Regular expressions for parsing GTest logs. Test names look like\n # SomeTestCase.SomeTest\n # SomeName/SomeTestCase.SomeTest/1\n # This regexp also matches SomeName.SomeTest/1, which should be harmless.\n test_name_regexp = r'((\\w+/)?\\w+\\.\\w+(/\\d+)?)'\n\n self._test_name = re.compile(test_name_regexp)\n self._test_start = re.compile('\\[\\s+RUN\\s+\\] ' + test_name_regexp)\n self._test_ok = re.compile('\\[\\s+OK\\s+\\] ' + test_name_regexp)\n self._test_fail = re.compile('\\[\\s+FAILED\\s+\\] ' + test_name_regexp)\n self._test_timeout = re.compile(\n 'Test timeout \\([0-9]+ ms\\) exceeded for ' + test_name_regexp)\n self._disabled = re.compile(' YOU HAVE (\\d+) DISABLED TEST')\n self._flaky = re.compile(' YOU HAVE (\\d+) FLAKY TEST')\n\n self._suppression_start = re.compile(\n 'Suppression \\(error hash=#([0-9A-F]+)#\\):')\n self._suppression_end = re.compile('^}\\s*$')\n\n self._retry_message = re.compile('RETRYING FAILED TESTS:')\n self.retrying_failed = False\n\n def _StatusOfTest(self, test):\n \"\"\"Returns the status code for the given test, or 'not known'.\"\"\"\n test_status = self._test_status.get(test, ('not known', []))\n return test_status[0]\n\n def _TestsByStatus(self, status, include_fails, include_flaky):\n \"\"\"Returns list of tests with the given status.\n\n Args:\n include_fails: If False, tests containing 'FAILS_' anywhere in their\n names will be excluded from the list.\n include_flaky: If False, tests containing 'FLAKY_' anywhere in their\n names will be excluded from the list.\n \"\"\"\n test_list = [x[0] for x in self._test_status.items()\n if self._StatusOfTest(x[0]) == status]\n\n if not include_fails:\n test_list = [x for x in test_list if x.find('FAILS_') == -1]\n if not include_flaky:\n test_list = [x for x in test_list if x.find('FLAKY_') == -1]\n\n return test_list\n\n def _RecordError(self, line, reason):\n \"\"\"Record a log line that produced a parsing error.\n\n Args:\n line: text of the line at which the error occurred\n reason: a string describing the error\n \"\"\"\n self._internal_error_lines.append(\"%s: %s [%s]\" %\n (self._line_number, line.strip(), reason))\n\n def RunningTests(self):\n \"\"\"Returns list of tests that appear to be currently running.\"\"\"\n return self._TestsByStatus('started', True, True)\n\n def ParsingErrors(self):\n \"\"\"Returns a list of lines that have caused parsing errors\"\"\"\n return self._internal_error_lines\n\n def ClearParsingErrors(self):\n \"\"\"Clears the currently stored parsing errors.\"\"\"\n self._internal_error_lines = ['Cleared.']\n\n def FailedTests(self, include_fails=False, include_flaky=False):\n \"\"\"Returns list of tests that failed, timed out, or didn't finish\n (crashed).\n\n This list will be incorrect until the complete log has been processed,\n because it will show currently running tests as having failed.\n\n Args:\n include_fails: If true, all failing tests with FAILS_ in their names will\n be included. Otherwise, they will only be included if they crashed or\n timed out.\n include_flaky: If true, all failing tests with FLAKY_ in their names will\n be included. Otherwise, they will only be included if they crashed or\n timed out.\n\n \"\"\"\n return (self._TestsByStatus('failed', include_fails, include_flaky) +\n self._TestsByStatus('timeout', True, True) +\n self._TestsByStatus('warning', include_fails, include_flaky) +\n self.RunningTests())\n\n def DisabledTests(self):\n \"\"\"Returns the name of the disabled test (if there is only 1) or the number\n of disabled tests.\n \"\"\"\n return self._disabled_tests\n\n def FlakyTests(self):\n \"\"\"Returns the name of the flaky test (if there is only 1) or the number\n of flaky tests.\n \"\"\"\n return self._flaky_tests\n\n def FailureDescription(self, test):\n \"\"\"Returns a list containing the failure description for the given test.\n\n If the test didn't fail or timeout, returns [].\n \"\"\"\n test_status = self._test_status.get(test, ('', []))\n return [\"%s: \" % test] + test_status[1]\n\n def SuppressionHashes(self):\n \"\"\"Returns list of suppression hashes found in the log.\"\"\"\n return self._suppressions.keys()\n\n def Suppression(self, suppression_hash):\n \"\"\"Returns a list containing the suppression for a given hash.\n\n If the suppression hash doesn't exist, returns [].\n \"\"\"\n return self._suppressions.get(suppression_hash, [])\n\n def ProcessLine(self, line):\n \"\"\"This is called once with each line of the test log.\"\"\"\n\n # Track line number for error messages.\n self._line_number += 1\n\n # Note: When sharding, the number of disabled and flaky tests will be read\n # multiple times, so this will only show the most recent values (but they\n # should all be the same anyway).\n\n # Is it a line reporting disabled tests?\n results = self._disabled.search(line)\n if results:\n try:\n disabled = int(results.group(1))\n except ValueError:\n disabled = 0\n if disabled > 0 and isinstance(self._disabled_tests, int):\n self._disabled_tests = disabled\n else:\n # If we can't parse the line, at least give a heads-up. This is a\n # safety net for a case that shouldn't happen but isn't a fatal error.\n self._disabled_tests = 'some'\n return\n\n # Is it a line reporting flaky tests?\n results = self._flaky.search(line)\n if results:\n try:\n flaky = int(results.group(1))\n except ValueError:\n flaky = 0\n if flaky > 0 and isinstance(self._flaky_tests, int):\n self._flaky_tests = flaky\n else:\n # If we can't parse the line, at least give a heads-up. This is a\n # safety net for a case that shouldn't happen but isn't a fatal error.\n self._flaky_tests = 'some'\n return\n\n # Is it the start of a test?\n results = self._test_start.search(line)\n if results:\n test_name = results.group(1)\n self._test_status[test_name] = ('started', ['Did not complete.'])\n self._current_test = test_name\n if self.retrying_failed:\n self._failure_description = self._test_status[test_name][1]\n self._failure_description.extend(['', 'RETRY OUTPUT:', ''])\n else:\n self._failure_description = []\n return\n\n # Is it a test success line?\n results = self._test_ok.search(line)\n if results:\n test_name = results.group(1)\n status = self._StatusOfTest(test_name)\n if status != 'started':\n self._RecordError(line, 'success while in status %s' % status)\n if self.retrying_failed:\n self._test_status[test_name] = ('warning', self._failure_description)\n else:\n self._test_status[test_name] = ('OK', [])\n self._failure_description = []\n self._current_test = ''\n return\n\n # Is it a test failure line?\n results = self._test_fail.search(line)\n if results:\n test_name = results.group(1)\n status = self._StatusOfTest(test_name)\n if status not in ('started', 'failed', 'timeout'):\n self._RecordError(line, 'failure while in status %s' % status)\n # Don't overwrite the failure description when a failing test is listed a\n # second time in the summary, or if it was already recorded as timing\n # out.\n if status not in ('failed', 'timeout'):\n self._test_status[test_name] = ('failed', self._failure_description)\n self._failure_description = []\n self._current_test = ''\n return\n\n # Is it a test timeout line?\n results = self._test_timeout.search(line)\n if results:\n test_name = results.group(1)\n status = self._StatusOfTest(test_name)\n if status not in ('started', 'failed'):\n self._RecordError(line, 'timeout while in status %s' % status)\n self._test_status[test_name] = (\n 'timeout', self._failure_description + ['Killed (timed out).'])\n self._failure_description = []\n self._current_test = ''\n return\n\n # Is it the start of a new valgrind suppression?\n results = self._suppression_start.search(line)\n if results:\n suppression_hash = results.group(1)\n if suppression_hash in self._suppressions:\n self._RecordError(line, 'suppression reported more than once')\n self._suppressions[suppression_hash] = []\n self._current_suppression_hash = suppression_hash\n self._current_suppression = [line]\n return\n\n # Is it the end of a valgrind suppression?\n results = self._suppression_end.search(line)\n if results and self._current_suppression_hash:\n self._current_suppression.append(line)\n self._suppressions[self._current_suppression_hash] = (\n self._current_suppression)\n self._current_suppression_hash = ''\n self._current_suppression = []\n return\n\n # Is it the start of the retry tests?\n results = self._retry_message.search(line)\n if results:\n self.retrying_failed = True\n return\n\n # Random line: if we're in a suppression, collect it. Suppressions are\n # generated after all tests are finished, so this should always belong to\n # the current suppression hash.\n if self._current_suppression_hash:\n self._current_suppression.append(line)\n return\n\n # Random line: if we're in a test, collect it for the failure description.\n # Tests may run simultaneously, so this might be off, but it's worth a try.\n # This also won't work if a test times out before it begins running.\n if self._current_test:\n self._failure_description.append(line)\n\n # Parse the \"Failing tests:\" list at the end of the output, and add any\n # additional failed tests to the list. For example, this includes tests\n # that crash after the OK line.\n if self._parsing_failures:\n results = self._test_name.search(line)\n if results:\n test_name = results.group(1)\n status = self._StatusOfTest(test_name)\n if status in ('not known', 'OK'):\n self._test_status[test_name] = (\n 'failed', ['Unknown error, see stdio log.'])\n else:\n self._parsing_failures = False\n elif line.startswith('Failing tests:'):\n self._parsing_failures = True\n","sub_path":"WProf/build/scripts/common/gtest_utils.py","file_name":"gtest_utils.py","file_ext":"py","file_size_in_byte":11691,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"341438346","text":"import logging\nimport logging.config\nimport threading\nimport socket\nimport time\nimport rpyc\nimport json\nimport os\n\nfrom datetime import datetime\nfrom time import gmtime, strftime\n\nfrom server import ServerService\nfrom rpyc.utils.server import ThreadedServer\n\nfrom config.server import WHO_AM_I, ROUND_TIME, TIME_FORMAT, KING, WORKER\n\nimport models.chats as ChatModel\nimport models.users as UserModel\nimport models.groups as GroupModel\nimport models.contacts as ContactModel\n\nimport models.default_servers_list as Default_list_Model\nimport models.workers_servers_list as Workers_list_Model\nimport models.suspects_servers_list as Suspects_list_Model\nimport models.round_times as Round_times_Model\n\n\ndef server_sync_Users(SERVERCONNECTION, _newRound, _oldRound):\n allItensToSync = UserModel.atRound(\n _roundStarted=_oldRound[1],\n _roundFinished=_newRound[1]\n )\n print ('+++ Users Total to sync: ', str(len(allItensToSync)))\n for item in allItensToSync:\n SERVERCONNECTION.root.serverReplaceCreateUser(\n email=item[0],\n name=item[1],\n created_at=item[2]\n )\n\n\ndef server_sync_Contacts(SERVERCONNECTION, _newRound, _oldRound):\n allItensToSync = ContactModel.atRound(\n _roundStarted=_oldRound[1],\n _roundFinished=_newRound[1]\n )\n print ('+++ Contacts Total to sync: ', str(len(allItensToSync)))\n for item in allItensToSync:\n SERVERCONNECTION.root.serverReplaceAddContact(\n _id=item[0],\n user_id=item[1],\n contact_id=item[2],\n created_at=item[3]\n )\n\n\ndef server_sync_Chats(SERVERCONNECTION, _newRound, _oldRound):\n allItensToSync = ChatModel.chats_atRound(\n _roundStarted=_oldRound[1],\n _roundFinished=_newRound[1]\n )\n print ('+++ Chats Total to sync: ', str(len(allItensToSync)))\n for item in allItensToSync:\n SERVERCONNECTION.root.serverReplaceCreateChat(\n _id=item[0],\n user_id=item[1],\n contact_id=item[2],\n created_at=item[3]\n )\n\n\ndef server_sync_Chat_Messages(SERVERCONNECTION, _newRound, _oldRound):\n allItensToSync = ChatModel.messages_atRound(\n _roundStarted=_oldRound[1],\n _roundFinished=_newRound[1]\n )\n print ('+++ Chats Message Total to sync: ', str(len(allItensToSync)))\n for item in allItensToSync:\n SERVERCONNECTION.root.serverReplaceSendChatMessage(\n _id=item[0],\n chat_id=item[1],\n sender_id=item[2],\n message=item[3],\n created_at=item[4]\n )\n\n\ndef server_sync_Groups(SERVERCONNECTION, _newRound, _oldRound):\n allItensToSync = GroupModel.groups_atRound(\n _roundStarted=_oldRound[1],\n _roundFinished=_newRound[1]\n )\n print ('+++ Groups Total to sync: ', str(len(allItensToSync)))\n for item in allItensToSync:\n SERVERCONNECTION.root.serverReplaceCreateGroup(\n _id=item[0],\n group_name=item[1],\n created_at=item[2]\n )\n\n\ndef server_sync_User_Groups(SERVERCONNECTION, _newRound, _oldRound):\n allItensToSync = GroupModel.usersAdd_atRound(\n _roundStarted=_oldRound[1],\n _roundFinished=_newRound[1]\n )\n print ('+++ User Groups Total to sync: ', str(len(allItensToSync)))\n for item in allItensToSync:\n SERVERCONNECTION.root.serverReplaceAddUserToAGroup(\n _id=item[0],\n user_id=item[1],\n group_id=item[2],\n created_at=item[3]\n )\n\n\ndef server_sync_Group_Messages(SERVERCONNECTION, _newRound, _oldRound):\n allItensToSync = GroupModel.messages_atRound(\n _roundStarted=_oldRound[1],\n _roundFinished=_newRound[1]\n )\n print ('+++ Group Message Total to sync: ', str(len(allItensToSync)))\n for item in allItensToSync:\n SERVERCONNECTION.root.serverReplaceSendGroupMessage(\n _id=item[0],\n group_id=item[1],\n sender_id=item[2],\n message=item[3],\n created_at=item[4]\n )\n# #####################################################\n\n\ndef start():\n _oldRound = Round_times_Model.last()\n Round_times_Model.create(\n _round=(\n int(\n _oldRound[0]\n ) + 1\n ),\n created_at=strftime(\n \"%Y-%m-%d %H:%M:%S\",\n gmtime()\n )\n )\n _newRound = Round_times_Model.last()\n print ('\\n... new round ' + str(_newRound))\n for server in Workers_list_Model.all():\n try:\n SERVERCONNECTION = rpyc.connect(\n server['ip'],\n server['port'],\n config={\n 'allow_public_attrs': True,\n \"allow_pickle\": True\n }\n )\n workerLastRound = SERVERCONNECTION.root.lastRoundSync()\n if workerLastRound[0] == 0:\n workerLastRound = Round_times_Model.first()\n SERVERCONNECTION.root.newRound(_newRound)\n server_sync_Users(\n SERVERCONNECTION,\n _newRound,\n workerLastRound\n )\n server_sync_Contacts(\n SERVERCONNECTION,\n _newRound,\n workerLastRound\n )\n server_sync_Chats(\n SERVERCONNECTION,\n _newRound,\n workerLastRound\n )\n server_sync_Chat_Messages(\n SERVERCONNECTION,\n _newRound,\n workerLastRound\n )\n server_sync_Groups(\n SERVERCONNECTION,\n _newRound,\n workerLastRound\n )\n server_sync_User_Groups(\n SERVERCONNECTION,\n _newRound,\n workerLastRound\n )\n server_sync_Group_Messages(\n SERVERCONNECTION,\n _newRound,\n workerLastRound\n )\n SERVERCONNECTION.close()\n except(socket.error, AttributeError, EOFError):\n logging.error(\n '+ + + + + + + + [CONNECTION ERROR] + + + + + + + +'\n )\n logging.error('Server: ' + server['name'])\n logging.error('IP: ' + server['ip'])\n logging.error('Port:' + str(server['port']))\n print ('')\n","sub_path":"servers/WhatsApp/controllers/syncContents.py","file_name":"syncContents.py","file_ext":"py","file_size_in_byte":6411,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"441011959","text":"\nimport matplotlib.image as mpimg\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport cv2\nimport glob\nfrom skimage.feature import hog\n\n# Read in our vehicles and non-vehicles\ncar1_img = mpimg.imread(\"/Users/robert/KittyHawk/SDCN/vehicle_detection/vehicles/GTI_MiddleClose/image0000.png\")\nnotcar1_img = mpimg.imread(\"/Users/robert/KittyHawk/SDCN/vehicle_detection/non-vehicles/GTI/image3861.png\")\n\ndef combo_plot_test_imgs(gray, imgs):\n fig = plt.figure(figsize=(24, 9))\n\n ax1 = fig.add_subplot(221)\n ax1.imshow(gray, cmap='gray')\n ax1.set_title(\"Orig image\", fontsize=50)\n\n ax2 = fig.add_subplot(222)\n ax2.imshow(imgs[0], cmap='gray')\n ax2.set_title(\"HOG CH0\", fontsize=50)\n\n ax3 = fig.add_subplot(223)\n ax3.imshow(imgs[1], cmap='gray')\n ax3.set_title(\"HOG CH1\", fontsize=50)\n\n ax4 = fig.add_subplot(224)\n ax4.imshow(imgs[2], cmap='gray')\n ax4.set_title(\"HOG CH2\", fontsize=50)\n\n fig.tight_layout()\n plt.subplots_adjust(left=0., right=1, top=0.9, bottom=0.)\n plt.show()\n\n\n# Define a function to return HOG features and visualization\ndef get_hog_features(img, orient, pix_per_cell, cell_per_block, vis=False, feature_vec=True):\n if vis == True:\n features, hog_image = hog(img, orientations=orient, pixels_per_cell=(pix_per_cell, pix_per_cell),\n cells_per_block=(cell_per_block, cell_per_block), transform_sqrt=True,\n visualise=True, feature_vector=False)\n return features, hog_image\n else:\n features = hog(img, orientations=orient, pixels_per_cell=(pix_per_cell, pix_per_cell),\n cells_per_block=(cell_per_block, cell_per_block), transform_sqrt=True,\n visualise=False, feature_vector=feature_vec)\n return features\n\n\n# Define HOG parameters\norient = 9\npix_per_cell = 8\ncell_per_block = 2\n\ncar1_img = notcar1_img\n\n# Read in the image\ngray_car1 = cv2.cvtColor(car1_img, cv2.COLOR_RGB2GRAY)\nyuv_car1 = cv2.cvtColor(car1_img, cv2.COLOR_RGB2YUV)\n\nhog_images = []\nfor channel in range(yuv_car1.shape[2]):\n # Call our function with vis=True to see an image output\n features, hog_image = get_hog_features(yuv_car1[:,:,channel], orient,\n pix_per_cell, cell_per_block,\n vis=True, feature_vec=False)\n\n hog_images.append(hog_image)\n\ncombo_plot_test_imgs(gray_car1, hog_images)\n # Plot the examples\n # fig = plt.figure()\n # plt.subplot(121)\n # plt.imshow(gray_car1, cmap='gray')\n # plt.title('Example Car Image')\n # plt.subplot(122)\n # plt.imshow(hog_image, cmap='gray')\n # plt.title('HOG Visualization')\n # plt.show()\n\n\n# done\n","sub_path":"get_hog.py","file_name":"get_hog.py","file_ext":"py","file_size_in_byte":2704,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"173852378","text":"#######################################################\n# Copyright (c) 2015, ArrayFire\n# All rights reserved.\n#\n# This file is distributed under 3-clause BSD license.\n# The complete license agreement can be obtained at:\n# http://arrayfire.com/licenses/BSD-3-Clause\n########################################################\n\nfrom sys import version_info\nfrom .library import *\nfrom .array import *\nfrom .util import *\n\ndef constant(val, d0, d1=None, d2=None, d3=None, dtype=f32):\n out = array()\n out.arr = constant_array(val, d0, d1, d2, d3, dtype)\n return out\n\n# Store builtin range function to be used later\nbrange = range\n\ndef range(d0, d1=None, d2=None, d3=None, dim=-1, dtype=f32):\n\n if not isinstance(dtype, ct.c_int):\n if isinstance(dtype, int):\n dtype = ct.c_int(dtype)\n else:\n raise TypeError(\"Invalid dtype\")\n\n out = array()\n dims = dim4(d0, d1, d2, d3)\n\n safe_call(clib.af_range(ct.pointer(out.arr), 4, ct.pointer(dims), dim, dtype))\n return out\n\n\ndef iota(d0, d1=None, d2=None, d3=None, dim=-1, tile_dims=None, dtype=f32):\n if not isinstance(dtype, ct.c_int):\n if isinstance(dtype, int):\n dtype = ct.c_int(dtype)\n else:\n raise TypeError(\"Invalid dtype\")\n\n out = array()\n dims = dim4(d0, d1, d2, d3)\n td=[1]*4\n\n if tile_dims is not None:\n for i in brange(len(tile_dims)):\n td[i] = tile_dims[i]\n\n tdims = dim4(td[0], td[1], td[2], td[3])\n\n safe_call(clib.af_iota(ct.pointer(out.arr), 4, ct.pointer(dims), 4, ct.pointer(tdims), dtype))\n return out\n\ndef randu(d0, d1=None, d2=None, d3=None, dtype=f32):\n\n if not isinstance(dtype, ct.c_int):\n if isinstance(dtype, int):\n dtype = ct.c_int(dtype)\n else:\n raise TypeError(\"Invalid dtype\")\n\n out = array()\n dims = dim4(d0, d1, d2, d3)\n\n safe_call(clib.af_randu(ct.pointer(out.arr), 4, ct.pointer(dims), dtype))\n return out\n\ndef randn(d0, d1=None, d2=None, d3=None, dtype=f32):\n\n if not isinstance(dtype, ct.c_int):\n if isinstance(dtype, int):\n dtype = ct.c_int(dtype)\n else:\n raise TypeError(\"Invalid dtype\")\n\n out = array()\n dims = dim4(d0, d1, d2, d3)\n\n safe_call(clib.af_randn(ct.pointer(out.arr), 4, ct.pointer(dims), dtype))\n return out\n\ndef set_seed(seed=0):\n safe_call(clib.af_set_seed(ct.c_ulonglong(seed)))\n\ndef get_seed():\n seed = ct.c_ulonglong(0)\n safe_call(clib.af_get_seed(ct.pointer(seed)))\n return seed.value\n\ndef identity(d0, d1=None, d2=None, d3=None, dtype=f32):\n\n if not isinstance(dtype, ct.c_int):\n if isinstance(dtype, int):\n dtype = ct.c_int(dtype)\n else:\n raise TypeError(\"Invalid dtype\")\n\n out = array()\n dims = dim4(d0, d1, d2, d3)\n\n safe_call(clib.af_identity(ct.pointer(out.arr), 4, ct.pointer(dims), dtype))\n return out\n\ndef diag(a, num=0, extract=True):\n out = array()\n if extract:\n safe_call(clib.af_diag_extract(ct.pointer(out.arr), a.arr, ct.c_int(num)))\n else:\n safe_call(clib.af_diag_create(ct.pointer(out.arr), a.arr, ct.c_int(num)))\n return out\n\ndef join(dim, first, second, third=None, fourth=None):\n out = array()\n if (third is None and fourth is None):\n safe_call(clib.af_join(ct.pointer(out.arr), dim, first.arr, second.arr))\n else:\n ct.c_array_vec = dim4(first, second, 0, 0)\n num = 2\n if third is not None:\n ct.c_array_vec[num] = third.arr\n num+=1\n if fourth is not None:\n ct.c_array_vec[num] = fourth.arr\n num+=1\n\n safe_call(clib.af_join_many(ct.pointer(out.arr), dim, num, ct.pointer(ct.c_array_vec)))\n\n\ndef tile(a, d0, d1=1, d2=1, d3=1):\n out = array()\n safe_call(clib.af_tile(ct.pointer(out.arr), a.arr, d0, d1, d2, d3))\n return out\n\n\ndef reorder(a, d0=1, d1=0, d2=2, d3=3):\n out = array()\n safe_call(clib.af_reorder(ct.pointer(out.arr), a.arr, d0, d1, d2, d3))\n return out\n\ndef shift(a, d0, d1=0, d2=0, d3=0):\n out = array()\n safe_call(clib.af_shift(ct.pointer(out.arr), a.arr, d0, d1, d2, d3))\n return out\n\ndef moddims(a, d0, d1=1, d2=1, d3=1):\n out = array()\n dims = dim4(d0, d1, d2, d3)\n safe_call(clib.af_moddims(ct.pointer(out.arr), a.arr, 4, ct.pointer(dims)))\n return out\n\ndef flat(a):\n out = array()\n safe_call(clib.af_flat(ct.pointer(out.arr), a.arr))\n return out\n\ndef flip(a, dim=0):\n out = array()\n safe_call(clib.af_flip(ct.pointer(out.arr), a.arr, ct.c_int(dim)))\n return out\n\ndef lower(a, is_unit_diag=False):\n out = array()\n safe_call(clib.af_lower(ct.pointer(out.arr), a.arr, is_unit_diag))\n return out\n\ndef upper(a, is_unit_diag=False):\n out = array()\n safe_call(clib.af_upper(ct.pointer(out.arr), a.arr, is_unit_diag))\n return out\n","sub_path":"arrayfire/data.py","file_name":"data.py","file_ext":"py","file_size_in_byte":4849,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"112892395","text":"import os\nimport time\nfrom collections import Counter\n\nimport numpy as np\n\nfrom garageofcode.kaggle.word2vec import get_words as get_words_list\n\ndef get_top_1000_words():\n data_dir = \"/home/jdw/garageofcode/data/\"\n fn = os.path.join(data_dir, \"1-1000.txt\")\n\n return [line for line in open(fn, \"r\").read().split()]\n\ndef get_sentences():\n fn = \"/home/jdw/garageofcode/data/compression/big.txt\"\n\n text = open(fn, \"r\").read()\n #text = text.replace(\"\\n\", \" \")\n text = \"\".join([\" \" if ch in \"\\n;,:-\\\"\" else ch for ch in text])\n text = \"\".join([\".\" if ch in \"!?\" else ch for ch in text])\n sentences = [sentence.strip() for sentence in text.split(\".\") if len(sentence.strip().split(\" \")) == 15]\n return sentences\n\ndef test_category(get_items):\n while True:\n elems = get_items()\n s = \"\".join([\"%s \" %elem for elem in elems])\n line = \">> \" + s\n print(line, end=\"\\r\")\n time.sleep(5)\n print(\" \"*100, end=\"\\r\")\n try:\n ans = input(\">> \").split(\" \")\n except KeyboardInterrupt:\n print()\n break\n c_elems = Counter(elems)\n c_ans = Counter(ans)\n if c_elems == c_ans:\n print(\" \" + s)\n print(\"Correct\")\n else:\n print(\" \" + s)\n try:\n input()\n except KeyboardInterrupt:\n print()\n break\n print()\n\n\ndef main():\n get_ints = lambda: [str(i) for i in np.random.randint(0, 10, size=[7])]\n get_letters = lambda: [chr(i) for i in np.random.randint(97, 123, size=[7])]\n #words_list = get_words_list()\n #get_words = lambda: np.random.choice(words_list, size=[5])\n words_list_1000 = get_top_1000_words()\n get_words_1000 = lambda: np.random.choice(words_list_1000, size=[7])\n sentences = get_sentences()\n get_sentence = lambda: [np.random.choice(sentences)]\n test_category(get_sentence)\n\n #for i in range(10):\n # print(\"line %d\" %i, end=\"\\r\")\n # time.sleep(0.5)\n\n\n\n\n\nif __name__ == '__main__':\n main()\n\n","sub_path":"garageofcode/other/brainram.py","file_name":"brainram.py","file_ext":"py","file_size_in_byte":2054,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"380570784","text":"#!/usr/bin/python\n\nimport argparse as arg\nimport cnn_kernel as ker\nimport cnn_img_seg as seg\nimport os\nimport numpy\nfrom PIL import Image\nfrom time import localtime, strftime\n__author__ = 'yurchenko'\n\n\ndef kernel_shape_handler(value):\n if value[-1] == ',':\n value[-1] = ''\n value_list = map(int, value.split(','))\n # print value_list\n if value_list.__len__() % 4 != 0:\n raise arg.ArgumentTypeError(\"Count of values must be \"\n \"divisible by 4\")\n value_tuple_list = []\n value_list = value_list[::-1]\n for cnt in range(value_list.__len__() / 4):\n value_tuple_list.append((value_list.pop(), value_list.pop(),\n value_list.pop(), value_list.pop()))\n\n return value_tuple_list\n\n\ndef get_params():\n\n parser = arg.ArgumentParser(description='Application does images'\n 'segmentation or '\n 'traing CNN for images '\n 'segmentation')\n\n parser.add_argument('action', choices=['train', 'segm', 'info'])\n\n parser.add_argument('ker_path_name',\n help='path and name of npyfile '\n 'containing cnn kernel')\n\n parser.add_argument('--kernel_shape', '-k', help='Creating '\n 'kernel with '\n 'specified'\n 'shapes. Shapes must be: '\n 'Fi1,Fo1,H1,W1,Fi2,Fo2,H2,W2,'\n 'Fi3,Fo3,H3,W3,Fi4,Fo4,H4,W4',\n default='0,0,0,0', type=kernel_shape_handler)\n\n parser.add_argument('--hdf_path_name', '-d',\n help='path and name of hdf5 file '\n 'containing images', default='')\n\n default_path = './' + strftime(\"%d%m%y-%H%M%S\", localtime()) + '/'\n parser.add_argument('--masks_path', '-m',\n help='Path for saving obtained masks',\n default=default_path)\n\n parser.add_argument('--batch_size', '-b',\n help='Batch size', type=int,\n default=2)\n\n parser.add_argument('--epochs_count', '-e', help='Epoch count',\n type=int, default=1)\n\n parser.add_argument('--stat_path_name', '-s',\n help='Filecontaining per epochs costs',\n default='')\n\n args = parser.parse_args()\n\n return args.hdf_path_name, args.ker_path_name, args.masks_path,\\\n args.action, args.batch_size, args.epochs_count, \\\n args.stat_path_name, args.kernel_shape\n\n\ndef train(hdf_path_name, ker_path_name, batch_size, epochs_count,\n stat_path_name, kernel_shape):\n cnn_kernel = ker.CNNKernel(ker_path_name)\n if kernel_shape == [(0, 0, 0, 0)]:\n cnn_kernel.load(ker_path_name)\n else:\n cnn_kernel.create(kernel_shape)\n cnn_kernel.save(ker_path_name)\n\n img_seg = seg.CNNImgSeg()\n img_seg.create_net(cnn_kernel)\n\n img_seg.train(hdf_path_name, batch_size=batch_size,\n epochs_count=epochs_count,\n stat_path_name=stat_path_name)\n\n\ndef save_masks(path, masks):\n print('Start masks saving')\n\n if not os.path.exists(path):\n os.makedirs(path)\n\n for img_num in range(masks.shape[0]):\n\n # Split single matrix to different layers\n layer_r = ((masks[img_num, 0, :, :]) == 0).\\\n astype('uint8') * 255 # HAIR\n layer_g = ((masks[img_num, 0, :, :]) == 1).\\\n astype('uint8') * 255 # SKIN\n layer_b = ((masks[img_num, 0, :, :]) == 2).\\\n astype('uint8') * 255 # OTHER\n\n # Merge different layers into single multilayers image\n img_arr_bgr = numpy.concatenate(([layer_r],\n [layer_g],\n [layer_b]), axis=0)\n\n # Set layers into usual order\n img_arr_bgr_t = img_arr_bgr.transpose((1, 2, 0))\n img = Image.fromarray(img_arr_bgr_t)\n\n file_name = path + '/' + str(img_num) + '.png'\n\n img.save(file_name, 'PNG')\n\n print('{0} saved'.format(file_name))\n\n print('Masks saving finished')\n\n\ndef segm(hdf_path_name, ker_path_name, path_to_masks_dir, batch_size):\n\n cnn_kernel = ker.CNNKernel(ker_path_name)\n cnn_kernel.load(ker_path_name)\n\n img_seg = seg.CNNImgSeg()\n img_seg.create_net(cnn_kernel)\n\n masks = img_seg.eval(hdf_path_name, batch_size=batch_size)\n\n save_masks(path_to_masks_dir, masks)\n\n\ndef info(ker_path_name):\n cnn_kernel = ker.CNNKernel(ker_path_name)\n cnn_kernel.load(ker_path_name)\n shapes = cnn_kernel.get_kernels_shapes()\n print('Kernel {0} has shape \\n{1}'.format(ker_path_name, shapes))\n\n\ndef main():\n\n hdf_path_name, ker_path_name, path_to_masks_dir, action,\\\n batch_size, epochs_count, stat_path_name, create_kernel =\\\n get_params()\n\n if action == 'train':\n train(hdf_path_name, ker_path_name, batch_size, epochs_count,\n stat_path_name, create_kernel)\n elif action == 'segm':\n segm(hdf_path_name, ker_path_name, path_to_masks_dir,\n batch_size)\n elif action == 'info':\n info(ker_path_name)\n\n# *******************************************************************\nmain()\n","sub_path":"segmentator.py","file_name":"segmentator.py","file_ext":"py","file_size_in_byte":5469,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"75630718","text":"from general import *\n\nclass Ship(Transport):\n def swim(self):\n print(\"I can swim\")\n\nclass Aircraft(Transport):\n def fly(self):\n print(\"I can fly\")\n\n def speed_up(self):\n self.speed += 5\n self.noise += 2\n\nboat = Ship(\"Speedboat\")\nboat2 = Ship(\"Nameboat\")\nplane = Aircraft(\"Boeing\")\n\nboat.say_name()\nboat2.say_name()\nplane.say_name()\n\nprint(plane.get_speed(), plane.get_noise())\nplane.speed_up()\nprint(plane.get_speed(), plane.get_noise())\nplane.set_speed(100)\nprint(plane.get_speed(), plane.get_noise())\n\n\n","sub_path":"Lesson_2/lesson.py","file_name":"lesson.py","file_ext":"py","file_size_in_byte":543,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"555212156","text":"# This is a sample Python script.\n\n# Press Shift+F10 to execute it or replace it with your code.\n# Press Double Shift to search everywhere for classes, files, tool windows, actions, and settings.\n\nimport glob\nimport os\nimport random\nimport sys\n\nimport cv2\nimport matplotlib.pyplot as plt\nimport numpy as np\nfrom PyQt5.QtWidgets import QMainWindow\n\nimport tensorflow as tf\nfrom tensorflow.keras import datasets, layers, optimizers, Sequential, metrics\nfrom tensorflow.keras.layers import Dense, Conv2D, MaxPool2D, Flatten\nfrom tensorflow.keras.models import load_model\n\nfrom hw2_4 import *\n\nbgsub_path = 'img/Q1_image/bgSub.mp4'\nfeatureTracking_path = 'img/Q2_image/opticalFlow.mp4'\n\n\n_PATTERN_SIZE = (11, 8)\n_WIDGETS = []\n_KEY = lambda x: int(os.path.splitext(x)[0])\n\nclass MainWindow(QMainWindow, Ui_MainWindow):\n def __init__(self):\n super(MainWindow, self).__init__()\n self.jacky = Ui_MainWindow()\n self.jacky.setupUi(self)\n self.jacky.Btn_1.clicked.connect(self.click_1_1)\n self.jacky.Btn_2.clicked.connect(self.click_2_1)\n self.jacky.Btn_3.clicked.connect(self.click_2_2)\n self.jacky.Btn_4.clicked.connect(self.click_3_1)\n self.jacky.Btn_5.clicked.connect(self.click_4_1)\n self.jacky.Btn_6.clicked.connect(self.click_4_2)\n self.jacky.Btn5_1.clicked.connect(self.click_5_1)\n self.jacky.Btn5_2.clicked.connect(self.click_5_2)\n self.jacky.Btn5_3.clicked.connect(self.click_5_3)\n self.jacky.Btn5_4.clicked.connect(self.click_5_4)\n\n\n def click_1_1(self):\n cap = cv2.VideoCapture(bgsub_path)\n\n fgbg_mog = cv2.bgsegm.createBackgroundSubtractorMOG()\n fgbg_gmg = cv2.bgsegm.createBackgroundSubtractorGMG(50, 0.9)\n\n kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (3, 3))\n\n while (1):\n ret, frame = cap.read()\n\n fgmask_mog = fgbg_mog.apply(frame)\n fgmask_gmg = fgbg_gmg.apply(frame)\n fgmask4 = cv2.morphologyEx(fgmask_gmg, cv2.MORPH_OPEN, kernel, iterations=1)\n\n cv2.imshow('frame', frame)\n cv2.imshow('fgmask', fgmask_mog)\n # cv2.imshow('gmg',fgmask_gmg)\n # cv2.imshow('MORPH_ELLIPSE',fgmask4)\n k = cv2.waitKey(30) & 0xff\n if k == 27:\n break\n\n cv2.destroyAllWindows()\n cap.release()\n\n def click_2_1(self):\n cap = cv2.VideoCapture(featureTracking_path)\n _, first_frame = cap.read()\n first_frame = cv2.convertScaleAbs(first_frame)\n params = cv2.SimpleBlobDetector_Params()\n params.filterByCircularity = True\n params.minCircularity = 0.84\n params.filterByArea = True\n params.minArea = 30\n params.maxArea = 100\n detector = cv2.SimpleBlobDetector_create(params)\n keypoints = detector.detect(first_frame)\n\n keyP = cv2.KeyPoint_convert(keypoints)\n # cv2.DRAW_MATCHES_FLAGS_DRAW_RICH_KEYPOINTS ensures the size of the circle corresponds to the size of blob\n # im_with_keypoints = cv2.drawKeypoints(first_frame, keypoints, np.array([]), (0, 0, 255), cv2.DRAW_MATCHES_FLAGS_DRAW_RICH_KEYPOINTS)\n for x in range(len(keyP)):\n (P_Y, P_X) = keyP[x]\n # print((P_Y, P_X))\n im_rec = cv2.rectangle(first_frame, (int(P_Y - 5), int(P_X - 5)), (int(P_Y + 5), int(P_X + 5)), (0, 0, 255),\n 1)\n\n cv2.imshow(\"rec\", im_rec)\n cv2.waitKey(0)\n cv2.destroyAllWindows()\n cap.release()\n\n def click_2_2(self):\n lk_params = dict(winSize=(21, 21),\n maxLevel=2,\n criteria=(cv2.TERM_CRITERIA_EPS | cv2.TERM_CRITERIA_COUNT, 10, 0.03))\n\n # Create some random colors\n # color = np.random.randint(0,255,(100,3))\n cap = cv2.VideoCapture(featureTracking_path)\n ret, old_frame = cap.read()\n params = cv2.SimpleBlobDetector_Params()\n params.filterByCircularity = True\n params.minCircularity = 0.84\n params.filterByArea = True\n params.minArea = 30\n params.maxArea = 100\n detector = cv2.SimpleBlobDetector_create(params)\n keypoints = detector.detect(old_frame)\n\n KeyP = np.reshape(cv2.KeyPoint_convert(keypoints), (-1, 1, 2))\n # print(KeyP.shape)\n # print(len(KeyP))\n # Create a mask image for drawing purposes\n mask = np.zeros_like(old_frame)\n\n while (1):\n ret, frame = cap.read()\n\n if not ret:\n break\n im_rec = frame.copy()\n p1, st, err = cv2.calcOpticalFlowPyrLK(old_frame, frame, KeyP, None, **lk_params)\n\n # Select good points\n good_new = p1[st == 1]\n good_old = KeyP[st == 1]\n\n # draw the tracks\n for i, (new, old) in enumerate(zip(good_new, good_old)):\n a, b = new.ravel()\n c, d = old.ravel()\n mask = cv2.line(mask, (a, b), (c, d), (0, 0, 255), 2)\n # circle = cv2.circle(frame,(a,b),5,color[i].tolist(),-1)\n im_rec = cv2.rectangle(im_rec, (int(a - 5), int(b - 5)), (int(a + 5), int(b + 5)), (0, 0, 255), 1)\n\n # img = cv2.add(frame,mask)\n imCombine = cv2.add(im_rec, mask)\n if ret == True:\n # video.write(imCombine)\n # cv2.imshow('frame',img)\n cv2.imshow('point', imCombine)\n old_frame = frame.copy()\n KeyP = good_new.reshape(-1, 1, 2)\n else:\n cap.release()\n break\n\n k = cv2.waitKey(30) & 0xff\n if k == 27:\n break\n cv2.destroyAllWindows()\n cap.release()\n\n def click_3_1(self):\n m_src = cv2.imread('img/Q3_Image/rl.jpg')\n cap = cv2.VideoCapture('img/Q3_Image/test4perspective.mp4')\n\n while (cap.isOpened()):\n try:\n ret, frame = cap.read()\n\n if frame is None: break\n dictionary = cv2.aruco.Dictionary_get(cv2.aruco.DICT_6X6_250)\n parameters = cv2.aruco.DetectorParameters_create()\n markerCorners, markerIDs, rejectedCandidates = cv2.aruco.detectMarkers(\n frame, dictionary, parameters=parameters)\n\n index = np.squeeze(np.where(markerIDs == 25))\n refPt1 = np.squeeze(markerCorners[index[0]])[1]\n\n index = np.squeeze(np.where(markerIDs == 33))\n refPt2 = np.squeeze(markerCorners[index[0]])[2]\n\n distance = np.linalg.norm(refPt1 - refPt2)\n\n scalingFac = 0.02\n pts_dst = [\n [refPt1[0] - round(scalingFac * distance), refPt1[1] - round((scalingFac * distance))]]\n pts_dst = pts_dst + \\\n [[refPt2[0] + round(scalingFac * distance),\n refPt2[1] - round(scalingFac * distance)]]\n\n index = np.squeeze(np.where(markerIDs == 30))\n refPt3 = np.squeeze(markerCorners[index[0]])[0]\n pts_dst = pts_dst + \\\n [[refPt3[0] + round(scalingFac * distance),\n refPt3[1] + round(scalingFac * distance)]]\n\n index = np.squeeze(np.where(markerIDs == 23))\n refPt4 = np.squeeze(markerCorners[index[0]])[0]\n pts_dst = pts_dst + \\\n [[refPt4[0] - round(scalingFac * distance),\n refPt4[1] + round(scalingFac * distance)]]\n pts_src = [[0, 0], [m_src.shape[1], 0], [\n m_src.shape[1], m_src.shape[0]], [0, m_src.shape[0]]]\n\n pts_dst = np.float32(pts_dst)\n pts_src = np.float32(pts_src)\n\n h, mask = cv2.findHomography(pts_src, pts_dst, cv2.RANSAC, 5.0)\n im_out = cv2.warpPerspective(m_src, h, (frame.shape[1], frame.shape[0]))\n\n res = np.where(im_out == 0, frame, im_out)\n res = cv2.resize(res, (700, 500), interpolation=cv2.INTER_CUBIC)\n frame = cv2.resize(frame, (700, 500), interpolation=cv2.INTER_CUBIC)\n result = np.hstack([frame, res])\n cv2.imshow(\"result\", result)\n if (cv2.waitKey(30) & 0xff == ord('q')):\n break\n except:\n pass\n\n def click_4_1(self):\n\n def pca_reconstruction(image, num_features=33):\n \"\"\"\n This function is equivalent to:\n from sklearn.decomposition import PCA\n pca = PCA(num_features)\n recon = pca.fit_transform(image)\n recon = pca.inverse_transform(recon)\n \"\"\"\n average_image = np.expand_dims(np.mean(image, axis=1), axis=1)\n X = image - average_image\n U, S, VT = np.linalg.svd(X, full_matrices=False)\n recon = average_image + np.matmul(np.matmul(U[:, :num_features], U[:, :num_features].T), X)\n return np.uint8(np.absolute(recon))\n\n np.random.seed(42)\n img_path = sorted(glob.glob(\"img/Q4_Image/*.jpg\"))\n gray_img = None\n original_img = None\n\n for img_test in img_path:\n if gray_img is None:\n img = cv2.imread(img_test)\n original_img = np.expand_dims(cv2.cvtColor(img, cv2.COLOR_BGR2RGB), axis=0)\n gray_img = np.expand_dims(cv2.cvtColor(img, cv2.COLOR_BGR2GRAY), axis=0)\n else:\n img = cv2.imread(img_test)\n img1 = np.expand_dims(cv2.cvtColor(img, cv2.COLOR_BGR2RGB), axis=0)\n img2 = np.expand_dims(cv2.cvtColor(img, cv2.COLOR_BGR2GRAY), axis=0)\n original_img = np.concatenate((original_img, img1), axis=0)\n gray_img = np.concatenate((gray_img, img2), axis=0)\n\n img_shape = original_img.shape\n r = original_img[:, :, :, 0].reshape(img_shape[0], -1)\n g = original_img[:, :, :, 1].reshape(img_shape[0], -1)\n b = original_img[:, :, :, 2].reshape(img_shape[0], -1)\n r_r, r_g, r_b = pca_reconstruction(r), pca_reconstruction(g), pca_reconstruction(b)\n recon_img = np.dstack((r_r, r_g, r_b))\n recon_img = np.reshape(recon_img, img_shape)\n\n # Setup a figure 6 inches by 6 inches\n fig = plt.figure(figsize=(17, 4))\n fig.subplots_adjust(left=0, right=1, bottom=0, top=1, hspace=0.05, wspace=0.05)\n\n length = 17\n for i in range(length):\n ax1 = fig.add_subplot(4, length, i + 1, xticks=[], yticks=[])\n ax1.imshow(original_img[i], cmap=plt.cm.bone, interpolation='nearest')\n ax2 = fig.add_subplot(4, length, i + length + 1, xticks=[], yticks=[])\n ax2.imshow(recon_img[i], cmap=plt.cm.bone, interpolation='nearest')\n ax3 = fig.add_subplot(4, length, i + length * 2 + 1, xticks=[], yticks=[])\n ax3.imshow(original_img[i + length], cmap=plt.cm.bone, interpolation='nearest')\n ax4 = fig.add_subplot(4, length, i + length * 3 + 1, xticks=[], yticks=[])\n ax4.imshow(recon_img[i + length], cmap=plt.cm.bone, interpolation='nearest')\n\n plt.show()\n\n def click_4_2(self):\n def pca_reconstruction(image, num_features=33):\n \"\"\"\n This function is equivalent to:\n from sklearn.decomposition import PCA\n pca = PCA(num_features)\n recon = pca.fit_transform(image)\n recon = pca.inverse_transform(recon)\n \"\"\"\n average_image = np.expand_dims(np.mean(image, axis=1), axis=1)\n X = image - average_image\n U, S, VT = np.linalg.svd(X, full_matrices=False)\n recon = average_image + np.matmul(np.matmul(U[:, :num_features], U[:, :num_features].T), X)\n return np.uint8(np.absolute(recon))\n\n def reconstruction_error(gray):\n gray = gray.reshape(gray.shape[0], -1)\n gray_recon = pca_reconstruction(gray)\n re = np.sum(np.abs(gray - gray_recon), axis=1)\n return np.mean(re)\n np.random.seed(42)\n gray_img = None\n original_img = None\n for i in range(1, 35):\n if gray_img is None:\n img = cv2.imread('img/Q4_Image\\\\' + str(i) + '.jpg')\n original_img = np.expand_dims(cv2.cvtColor(img, cv2.COLOR_BGR2RGB), axis=0)\n gray_img = np.expand_dims(cv2.cvtColor(img, cv2.COLOR_BGR2GRAY), axis=0)\n else:\n img = cv2.imread('img/Q4_Image\\\\' + str(i) + '.jpg')\n img1 = np.expand_dims(cv2.cvtColor(img, cv2.COLOR_BGR2RGB), axis=0)\n img2 = np.expand_dims(cv2.cvtColor(img, cv2.COLOR_BGR2GRAY), axis=0)\n original_img = np.concatenate((original_img, img1), axis=0)\n gray_img = np.concatenate((gray_img, img2), axis=0)\n\n total_error = []\n for img in gray_img:\n error = reconstruction_error(img)\n total_error.append(error)\n print(\"Reconstruction Error:\", total_error)\n\n def click_5_1(self):\n # print(\"[001/015] 255.81 sec(s) Train Acc: 0.588212 Loss: 0.042064 | Val Acc: 0.644800 loss: 0.039310\")\n # print(\"[002/015] 261.49 sec(s) Train Acc: 0.677379 Loss: 0.037449 | Val Acc: 0.707200 loss: 0.036967\")\n # print(\"[003/015] 262.77 sec(s) Train Acc: 0.732675 Loss: 0.033910 | Val Acc: 0.754400 loss: 0.030774\")\n # print(\"[004/015] 263.44 sec(s) Train Acc: 0.761435 Loss: 0.030856 | Val Acc: 0.807200 loss: 0.026251\")\n # print(\"[005/015] 262.79 sec(s) Train Acc: 0.798551 Loss: 0.027394 | Val Acc: 0.708800 loss: 0.040540\")\n # print(\"[006/015] 262.89 sec(s) Train Acc: 0.821176 Loss: 0.025098 | Val Acc: 0.831200 loss: 0.024857\")\n # print(\"[007/015] 263.23 sec(s) Train Acc: 0.838912 Loss: 0.022884 | Val Acc: 0.900000 loss: 0.015484\")\n # print(\"[008/015] 262.87 sec(s) Train Acc: 0.853936 Loss: 0.020625 | Val Acc: 0.841200 loss: 0.023092\")\n # print(\"[009/015] 263.05 sec(s) Train Acc: 0.866693 Loss: 0.018931 | Val Acc: 0.921600 loss: 0.012802\")\n # print(\"[010/015] 263.13 sec(s) Train Acc: 0.881984 Loss: 0.017347 | Val Acc: 0.894400 loss: 0.017913\")\n # print(\"[011/015] 263.00 sec(s) Train Acc: 0.892074 Loss: 0.016163 | Val Acc: 0.922800 loss: 0.012087\")\n # print(\"[012/015] 262.88 sec(s) Train Acc: 0.899498 Loss: 0.015189 | Val Acc: 0.941600 loss: 0.009736\")\n # print(\"[013/015] 263.31 sec(s) Train Acc: 0.905454 Loss: 0.014267 | Val Acc: 0.887200 loss: 0.018436\")\n # print(\"[014/015] 262.95 sec(s) Train Acc: 0.911366 Loss: 0.013362 | Val Acc: 0.928400 loss: 0.010985\")\n # print(\"[015/015] 262.78 sec(s) Train Acc: 0.911055 Loss: 0.013047 | Val Acc: 0.927200 loss: 0.010813\")\n print(\"[001/005] 104.05 sec(s) Train Acc: 0.591138 Loss: 0.042446 | Val Acc: 0.669613 loss: 0.038570\")\n print(\"[002/005] 103.24 sec(s) Train Acc: 0.673622 Loss: 0.037993 | Val Acc: 0.692818 loss: 0.037700\")\n print(\"[003/005] 103.32 sec(s) Train Acc: 0.719774 Loss: 0.035279 | Val Acc: 0.720442 loss: 0.038500\")\n print(\"[004/005] 103.27 sec(s) Train Acc: 0.741377 Loss: 0.033147 | Val Acc: 0.737017 loss: 0.032527\")\n print(\"[005/005] 103.33 sec(s) Train Acc: 0.765681 Loss: 0.031379 | Val Acc: 0.771271 loss: 0.031345\")\n\n def click_5_2(self):\n img = cv2.imread('img/Q5_Image/tensorboard.PNG',)\n cv2.imshow('img', img)\n\n def click_5_3(self):\n r = random.randint(1, 1000)\n #print(r)\n test = cv2.imread('img/Q5_Image/test/'+str(r)+'.jpg')\n saved_model = load_model(\"ResNet50_10_origin_rgb_10000.h5\")\n test= cv2.resize(test,(224, 224))\n test = test.reshape(-1, 224, 224, 3)\n predict = saved_model.predict(test)\n print(predict)\n test = test.reshape(224,224, 3)\n\n if predict[0][0] < predict[0][1]:\n plt.title(\"Class:dog\")\n else:\n plt.title(\"Class:cat\")\n plt.imshow(test)\n plt.show()\n\n\n def click_5_4(self):\n acc = [17.127, 25.6]\n candidates = [\"Before random_erase\", \"After random_erase\"]\n x = np.arange(len(candidates))\n plt.bar(x, acc, tick_label=candidates, width=0.5, bottom=60)\n plt.title('Random-Erasing Algo') # 設定圖形標題\n #plt.xlabel('Candidates') # 設定X軸標籤\n plt.ylabel('accuracy(%)') # 設定Y軸標籤\n plt.show()\n\n #img = cv2.imread(\"erase_cho.png\")\n #cv2.imshow(\"img\",img)\n\n\n\n\nif __name__ == \"__main__\":\n app = QtWidgets.QApplication([])\n window = MainWindow()\n window.show()\n sys.exit(app.exec_())\n","sub_path":"proj_3/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":16743,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"394349348","text":"# coding: utf-8\r\n# course - 参考解答.py\r\n# 2019/4/5 10:56\r\nimport random\r\nimport sys\r\nimport math\r\n\r\n\r\ndef q1():\r\n # 选择困难症\r\n return random.choice(['苹果', '香蕉'])\r\n\r\n\r\ndef q2():\r\n # 猜数字\r\n # 生成1-20随机整数\r\n number = random.randint(1, 20)\r\n # 进入死循环\r\n while True:\r\n # 由于需要猜对为止,所以要在循环里input\r\n choice = int(input('输入数字'))\r\n if choice == number:\r\n print('猜对了')\r\n break # 猜对了break程序,或者sys.exit\r\n elif choice < number:\r\n print('小')\r\n elif choice > number:\r\n print('大')\r\n\r\n\r\ndef q3(a, b, c):\r\n \"\"\"\r\n 一元二次方程,接受三个参数abc\r\n :param a:\r\n :param b:\r\n :param c:\r\n :return: x1 x2\r\n \"\"\"\r\n # 判断是否有实数解\r\n delta = b * b - 4 * a * c\r\n if delta < 0:\r\n print('没有实数解')\r\n else:\r\n # 求根公式不要用错了\r\n x1 = (-b + delta ** 0.5) / (2 * a)\r\n x2 = (-b - delta ** 0.5) / (2 * a)\r\n return x1, x2\r\n\r\n\r\ndef q4():\r\n # 将用户从input输入的内容写入到123.txt中\r\n # 需要先进入一个死循环\r\n while True:\r\n content = input('请输入内容,q退出')\r\n if content.lower() == 'q': # 如果用户输入了q,那么break循环\r\n break\r\n else: # 输入的不是q,写文件,追加模式\r\n with open('123.txt', 'a', encoding='u8') as f:\r\n f.write(content)\r\n\r\n\r\ndef q5():\r\n # 计算球体积,需要注意异常处理\r\n try:\r\n # 1. 需要用float转\r\n # 2. 这一步可能输入abc,这个时候需要用异常处理下\r\n radius = float(input('输入半径'))\r\n except ValueError:\r\n print('输入的值不是数字')\r\n sys.exit()\r\n return (4 / 3) * math.pi * radius ** 3\r\n\r\n\r\ndef q6():\r\n # 根据区号转换城市,同样输入q退出,因此需要死循环\r\n city = {'010': '北京', '024': '沈阳'}\r\n\r\n while True:\r\n code = input('输入区号')\r\n if code.lower() == 'q':\r\n # 输入值是q 退出程序\r\n break\r\n else:\r\n # 使用get方法,没找到时不会出KeyError,并定义自定义返回值\r\n print(city.get(code, '没找到对应信息'))\r\n\r\n\r\ndef q7():\r\n # 处理文件\r\n read = open('assignments.md', 'r', encoding='utf-8')\r\n # 先去掉开头的五行,使得文件指针指向第一道题前面\r\n for i in range(5):\r\n read.readline()\r\n # 将文件内容全部读取位字符串\r\n content = read.read()\r\n # 使用\\n##作为分隔符将字符串分割为列表\r\n content = content.split('\\n##')\r\n # 第一个元素是空的,删掉\r\n content.pop(0)\r\n # 遍历列表\r\n for question in content:\r\n # 提取标题,先按换行分割,再按.分割\r\n filename = question.split('\\n')[0].split('. ')[-1]\r\n # with打开文件,注意filename\r\n with open(f'{filename}.txt', 'w', encoding='utf-8') as write:\r\n # write写文件,补全##\r\n write.write(f'##{question}')\r\n # 关闭读文件流\r\n read.close()\r\n","sub_path":"0324/keys.py","file_name":"keys.py","file_ext":"py","file_size_in_byte":3230,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"591831979","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sat Jun 10 10:44:20 2017\n@author: pankaj\n\"\"\"\nfrom subprocess import call\nimport sys\nimport os\nimport codecs\nimport time\nimport io\nimport re\n\n\nvowel_map = {\t\n\t\t\t\t\"AA\" : \"आ\",\t\"AE\" : \"ऐ\",\t\"AH\" : \"अ\",\t\"AO\" : \"औ\",\n\t\t\t\t\"AW\" :\"आउ\",\t\"AY\" : \"आय\",\t\"EH\" : \"ऍ\", \t\"EY\" : \"ए\", \n\t\t\t\t\"IH\" : \"इ\",\t\"IY\" : \"ई\", \t\"OW\" : \"ओ\",\t\"OY\" : \"ऑय\", \n\t\t\t\t\"UH\" : \"उ\", \t\"UW\" : \"ऊ\"\n\t\t\t}\n\t\t\t\nmatra_map = {\t\t\t\t\n\t\t\t\t\"AA\" : \"ा\",\t\"AE\" : \"ै\",\t\"AH\" : \"\",\t\"AO\" : \"ौ\",\n\t\t\t\t\"AW\" :\"ाउ\",\t\"AY\" : \"ाय\",\t\"EH\" : \"ॅ\", \t\"EY\" : \"े\", \n\t\t\t\t\"IH\" : \"ि\",\t\"IY\" : \"ी\", \t\"OW\" : \"ो\",\t\"OY\" : \"ॉय\", \n\t\t\t\t\"UH\" : \"ु\", \t\"UW\" : \"ू\"\n\t\t\t}\n\t\t\t\nconsonant_map = {\n\t\t\t\t\t\"B\" : \"ब\",\t\"CH\" : \"च\",\t\"D\" : \"ड\",\t\"DH\" : \"द\",\n\t\t\t\t\t\"ER\" : \"र\",\t\"F\"\t : \"फ\",\t\"G\" : \"ग\",\t\"HH\" : \"ह\",\n\t\t\t\t\t\"JH\" : \"ज\",\t\"K\" : \"क\",\t\"L\" : \"ल\",\t\"M\"\t : \"म\",\n\t\t\t\t\t\"N\"\t : \"न\", \"NG\" : \"न्ग\",\t\"P\" : \"प\",\t\"R\"\t : \"र\",\n\t\t\t\t\t\"S\"\t : \"स\",\t\"SH\" : \"श\",\t\"T\" : \"ट\",\t\"TH\" : \"थ\",\n\t\t\t\t\t\"V\" : \"व\",\t\"W\" : \"व\", \"Y\"\t: \"य\",\t\"Z\"\t : \"ज़\",\n\t\t\t\t\t\"ZH\" : \"झ\"\n\t\t\t\t}\n\t\t\t\t\ninput_strings = [\n \"AH M IY R\", \"AH L AH K AH N AH N D AA\", \n \"K UH T T AA\", \"JH AH M P AH R\", \"M EY R IY V IH DH EY SH Y AA T R AA\",\n \"IH N T ER S EH P T ER Z\",\"G R AE N T IH NG\",\"G EH G IH N HH AY M ER\",\"P L EY T L AY K\",\"K ER S\"\n ]\n\ndef phone_to_word(instr):\n\tfirst_char = 1\n\tprev_char = \"VOWEL\"\n\tphnlist = instr.split()\n\tphnlen = len(phnlist)\n\tchcnt = 0\n\tchstr = []\n\twhile chcnt < phnlen:\n\t\tch = phnlist[chcnt]\n\t\tif first_char == 1:\n\t\t\tif ch in vowel_map:\n\t\t\t\tchstr.append(vowel_map[ch])\n\t\t\t\tprev_char = \"VOWEL\"\n\t\t\telse:\n\t\t\t\tif (chcnt + 1) < phnlen:\n\t\t\t\t\tif phnlist[chcnt+1] in vowel_map:\n\t\t\t\t\t\tchstr.append(consonant_map[ch])\n\t\t\t\t\t\tprev_char = \"CONSONANT\"\n\t\t\t\t\telse:\n\t\t\t\t\t\tif phnlist[chcnt+1] == \"ER\":\n\t\t\t\t\t\t\tchstr.append(consonant_map[ch])\n\t\t\t\t\t\telse:\n\t\t\t\t\t\t\tchstr.append(consonant_map[ch])\n\t\t\t\t\t\t\tchstr.append(\"्\")\n\t\t\tfirst_char = 0\n\t\t\tchcnt += 1\n\t\telse:\n\t\t\tif ch in vowel_map:\n\t\t\t\tif prev_char == \"CONSONANT\":\n\t\t\t\t\tchstr.append(matra_map[ch])\n\t\t\t\t\tprev_char = \"VOWEL\"\n\t\t\t\telse:\n\t\t\t\t\tchstr.append(vowel_map[ch])\n\t\t\t\t\tprev_char = \"VOWEL\"\n\t\t\t\tchcnt += 1\n\t\t\telse:\n\t\t\t\tif (chcnt + 1) < phnlen:\n\t\t\t\t\tif phnlist[chcnt+1] in vowel_map:\n\t\t\t\t\t\tchstr.append(consonant_map[ch])\n\t\t\t\t\t\tprev_char = \"CONSONANT\"\n\t\t\t\t\telse:\n\t\t\t\t\t\tif phnlist[chcnt+1] == \"ER\":\n\t\t\t\t\t\t\tchstr.append(consonant_map[ch])\n\t\t\t\t\t\telse:\n\t\t\t\t\t\t\tchstr.append(consonant_map[ch])\n\t\t\t\t\t\t\tchstr.append(\"्\")\n\t\t\t\t\t\tprev_char = \"CONSONANT\"\n\t\t\t\telse:\n\t\t\t\t\tchstr.append(consonant_map[ch])\n\t\t\t\t\tprev_char = \"CONSONANT\"\t\t\t\t\n\t\t\t\tchcnt += 1\n\tchstr = ''.join(chstr)\n\treturn chstr\t\t\t\n\t\t","sub_path":"utils/phtochar.py","file_name":"phtochar.py","file_ext":"py","file_size_in_byte":2701,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"361445948","text":"# encoding: UTF-8\n\n\"\"\"\n本模块中主要包含:\n1. 从通联数据下载历史行情的引擎\n2. 用来把MultiCharts导出的历史数据载入到MongoDB中用的函数\n3. 增加从通达信导出的历史数据载入到MongoDB中的函数\n\"\"\"\n\nimport datetime as dt\nimport mysql.connector\nfrom mysql_operation import *\nfrom multiprocessing.pool import ThreadPool\n\nfrom ctaBase import *\nfrom vtFunction import loadMysqlSetting\nfrom allText import *\n\n# 以下为vn.trader和通联数据规定的交易所代码映射\nVT_TO_DATAYES_EXCHANGE = {}\nVT_TO_DATAYES_EXCHANGE[EXCHANGE_CFFEX] = 'CCFX' # 中金所\nVT_TO_DATAYES_EXCHANGE[EXCHANGE_SHFE] = 'XSGE' # 上期所\nVT_TO_DATAYES_EXCHANGE[EXCHANGE_CZCE] = 'XZCE' # 郑商所\nVT_TO_DATAYES_EXCHANGE[EXCHANGE_DCE] = 'XDCE' # 大商所\nDATAYES_TO_VT_EXCHANGE = {v: k for k, v in VT_TO_DATAYES_EXCHANGE.items()}\n\n\n# ----------------------------------------------------------------------\ndef loadMcCsv(fileName, dbName, symbol):\n \"\"\"将Multicharts导出的csv格式的历史数据插入到Mongo数据库中\"\"\"\n import csv\n\n print(u'开始读取CSV文件%s中的数据插入到%s的%s中' % (fileName, dbName, symbol))\n\n # 锁定集合,并创建索引\n dbconfig, logging = loadMysqlSetting()\n\n # 预设数据库名和表名\n d = dict()\n d['db'] = dbName\n d['table'] = symbol\n\n cnx = mysql.connector.connect(**dbconfig)\n cursor = cnx.cursor()\n query = table_sqlcreate['ctp_tick'] % d\n cursor.execute(query)\n\n # 读取数据和插入到数据库\n reader = csv.DictReader(open(fileName, 'r'))\n for d in reader:\n datetime = dt.datetime.strptime(str(d['datetime']), \"%Y-%m-%d %H:%M:%S.%f\")\n date = str(datetime.strftime(\"%Y%m%d\"))\n time = str(datetime.strftime(\"%H%M%S.%f\"))\n\n tick = CtaTickData()\n tick.vtSymbol = str(d['instrument']) # vt系统代码\n tick.symbol = str(d['instrument']) # 合约代码\n tick.exchange = '' # 交易所代码\n\n # 成交数据\n tick.lastPrice = float(d['last_price']) # 最新成交价\n tick.volume = int(d['volume']) # 最新成交量\n tick.openInterest = int(d['open_int']) # 持仓量\n\n tick.upperLimit = float(d['upper_limit_price']) # 涨停价\n tick.lowerLimit = float(d['lower_limit_price']) # 跌停价\n\n # tick的时间\n tick.date = date # 日期\n tick.time = time # 时间\n tick.datetime = datetime # python的datetime时间对象\n\n # 五档行情\n tick.bidPrice1 = float(d['bid_price1'])\n tick.bidPrice2 = float(d['bid_price2'])\n tick.bidPrice3 = float(d['bid_price3'])\n tick.bidPrice4 = float(d['bid_price4'])\n tick.bidPrice5 = float(d['bid_price5'])\n\n tick.askPrice1 = float(d['ask_price1'])\n tick.askPrice2 = float(d['ask_price2'])\n tick.askPrice3 = float(d['ask_price3'])\n tick.askPrice4 = float(d['ask_price4'])\n tick.askPrice5 = float(d['ask_price5'])\n\n tick.bidVolume1 = int(d['bid_vol1'])\n tick.bidVolume2 = int(d['bid_vol2'])\n tick.bidVolume3 = int(d['bid_vol3'])\n tick.bidVolume4 = int(d['bid_vol4'])\n tick.bidVolume5 = int(d['bid_vol5'])\n\n tick.askVolume1 = int(d['ask_vol1'])\n tick.askVolume2 = int(d['ask_vol2'])\n tick.askVolume3 = int(d['ask_vol3'])\n tick.askVolume4 = int(d['ask_vol4'])\n tick.askVolume5 = int(d['ask_vol5'])\n\n print(tick.__dict__)\n\n cnx.close()\n\n\nif __name__ == '__main__':\n # 这里将项目中包含的股指日内分钟线csv导入MongoDB,作者电脑耗时大约3分钟\n loadMcCsv('rb5.csv', TICK_DB_NAME, 'rb0000')\n","sub_path":"ctaStrategy/ctaHistoryData.py","file_name":"ctaHistoryData.py","file_ext":"py","file_size_in_byte":3684,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"150777232","text":"from PythonWebDav import VirtualFS as vfs\nimport os\nimport time\nimport hashlib\nimport shutil\n\n\"\"\"\nclass 'audioFiler' provides functions for working with the virtual audio file system\n\"\"\"\n\n\nclass AudioFiler(object):\n def __new__(cls, *args, **kwargs):\n if not hasattr(cls, 'instance'):\n cls.instance = super(AudioFiler, cls).__new__(cls)\n return cls.instance\n\n def __init__(self, folder):\n if not hasattr(AudioFiler, 'instance_inited'):\n AudioFiler.instance_inited = True\n self.fs = vfs.VFolder(\"/\")\n self.base_folder = folder\n print(\"Creating virtual file system...\")\n self.fs.create_audio_fs(folder)\n print(\"Complete!\")\n\n def get_file(self, path):\n f = self.fs.find_file(path)\n return open(f.path, \"rb\")\n\n def isdir(self, path):\n f = self.fs.find_file(path)\n return type(f) == vfs.VFolder\n\n def childs(self, path):\n f = self.fs.find_file(path)\n return list(map(lambda x: x.name, f.data))\n\n def get_creationdate(self, path):\n f = self.fs.find_file(path)\n if type(f) == vfs.VFolder:\n return time.ctime(time.time())\n return time.ctime(os.path.getctime(f.path))\n\n def get_lastmodified(self, path):\n f = self.fs.find_file(path)\n if type(f) == vfs.VFolder:\n return time.ctime(time.time())\n return time.ctime(os.path.getmtime(f.path))\n\n def get_name(self, path):\n f = self.fs.find_file(path)\n return f.name\n\n def get_size(self, path):\n f = self.fs.find_file(path)\n if type(f) == vfs.VFolder:\n return str(10**5)\n return str(os.path.getsize(f.path))\n\n def get_mimetype(self, path):\n f = self.fs.find_file(path)\n if type(f) == vfs.vfile:\n return 'audio/mpeg'\n\n def get_hash(self, path):\n f = self.fs.find_file(path)\n if type(f) == vfs.vfile:\n file = open(f.path, 'rb')\n m = hashlib.md5()\n while True:\n data = file.read(8000)\n if not data:\n break\n m.update(data)\n file.close()\n return m.hexdigest()\n\n def getsize(self, path):\n f = self.fs.find_file(path)\n if type(f) == vfs.VFolder:\n return str(10**5)\n return str(os.path.getsize(f.path))\n\n def getfreesize(self, path):\n return str(10**5)\n\n def create_folder(self, path):\n f = self.base_folder+path\n os.mkdir(f)\n\n def create_file(self, path, data, length):\n f = self.base_folder+\"/\"+path.split(\"/\")[-1]\n file = open(f, \"wb\")\n file.write(data.read(length))\n new_art, new_alb = (path.split(\"/\") + [\"\", \"\"])[1:3]\n if new_art != \"\":\n self.fs.change_data(f, artist=new_art)\n if new_alb != \"\":\n self.fs.change_data(f, album=new_alb)\n self.fs.add_file(f)\n print(new_alb, new_art)\n file.close()\n\n def move_file(self, path_from, path_to, ov_wr):\n f_from = self.base_folder+path_from\n f_to = self.base_folder+path_to\n shutil.move(f_from, f_to)\n return f_to\n\n def copy_file(self, path_from, path_to, ov_wr):\n f_from = self.base_folder+path_from\n f_to = self.base_folder+path_to\n shutil.copy(f_from, f_to)\n return f_to\n\n def delete(self, path):\n f = self.fs.find_file(path)\n if self.fs.is_unknown(path):\n os.remove(f.path)\n else:\n self.fs.change_data(f.path, artist=\"Unknow Artist\", album=\"Unknow Album\")\n self.fs.delete_file(path)\n","sub_path":"PythonWebDav/AudioFiler.py","file_name":"AudioFiler.py","file_ext":"py","file_size_in_byte":3670,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"154445484","text":"from perso_lib.xml_parse import XmlParser\nfrom perso_lib import utils\nfrom perso_lib.cps import Dgi,Cps\nfrom perso_lib.rule import Rule,RuleXml\nfrom perso_lib.log import Log\n\ndef _parse_tlv(dgi_name,data):\n dgi = Dgi()\n data = utils.remove_dgi(data,dgi_name)\n int_dgi = utils.str_to_int(dgi_name)\n if int_dgi < 0x0B01:\n if data[0:2] != '70':\n Log.error('数据有误,小于0B01的DGI应包含70模板')\n return None\n data = utils.remove_template70(data)\n if not utils.is_rsa(dgi_name) and utils.is_tlv(data):\n tlvs = utils.parse_tlv(data)\n if len(tlvs) > 0 and tlvs[0].is_template is True:\n value = utils.assemble_tlv(tlvs[0].tag,tlvs[0].value)\n dgi.add_tag_value(dgi_name,value)\n else:\n for tlv in tlvs:\n value = utils.assemble_tlv(tlv.tag,tlv.value)\n dgi.add_tag_value(tlv.tag,value)\n else:\n dgi.add_tag_value(dgi_name,data)\n return dgi\n\ndef _process_pse_and_ppse(dgi_name,data):\n dgi = Dgi()\n if dgi_name == 'Store_PSE_1':\n dgi.name = 'PSE'\n data = utils.remove_dgi(data,'0101')\n data = utils.remove_template70(data)\n dgi.add_tag_value('0101',data)\n elif dgi_name == 'Store_PSE_2':\n dgi.name = 'PSE'\n data = utils.remove_dgi(data,'9102')\n value = utils.assemble_tlv('A5','880101' + data)\n dgi.add_tag_value('9102',value)\n elif dgi_name == 'Store_PPSE':\n dgi.name = 'PPSE'\n # value = dgi.assemble_tlv('BF0C',data)\n # value = dgi.assemble_tlv('A5',value)\n data = utils.remove_dgi(data,'9102')\n dgi.add_tag_value('9102',data)\n return dgi\n\ndef _pre_process_rule(rule_file_name,cps):\n rule_handle = RuleXml(rule_file_name)\n rule = Rule(cps,rule_handle)\n rule.wrap_process_decrypt() \n return rule.cps\n\ndef _process_rule(rule_file_name,cps): \n rule_handle = RuleXml(rule_file_name)\n rule = Rule(cps,rule_handle)\n rule.wrap_process_dgi_map()\n rule.wrap_process_exchange()\n rule.wrap_process_remove_dgi()\n rule.wrap_process_remove_tag()\n return rule.cps\n\n\n\ndef _process_rsa(cps):\n rsa_dgi_list = ['8201','8202','8203','8204','8205']\n for dgi in cps.dgi_list:\n if dgi.name in rsa_dgi_list:\n data = dgi.get_value(dgi.name)\n length = utils.str_to_int(data[0:2]) * 2\n data = data[2: 2 + length]\n dgi.modify_value(dgi.name,data)\n return cps\n\ndef _process_8000_and_8020(cps):\n append_80_and_len_dgi_list = ['8000','8020']\n for dgi in cps.dgi_list:\n if dgi.name in append_80_and_len_dgi_list:\n decrypted_data = ''\n data = dgi.get_value(dgi.name)\n for cur_pos in range(0,len(data),48):\n decrypted_data += data[cur_pos + 2: cur_pos + 34]\n dgi.modify_value(dgi.name,decrypted_data)\n return cps\n\ndef _process_8400(cps):\n for dgi in cps.dgi_list:\n if dgi.name == '8400':\n decrypted_data = ''\n data = dgi.get_value(dgi.name)\n for cur_pos in range(0,len(data),48):\n decrypted_data += data[cur_pos: cur_pos + 32]\n dgi.modify_value(dgi.name,decrypted_data)\n return cps \n\ndef process_dp(dp_file,rule_file=None):\n cps_list = []\n xml = XmlParser(dp_file)\n batch_information_header_node = xml.get_first_node(xml.root_element,'batch_information_header')\n dgi_name_list_node = xml.get_first_node(batch_information_header_node,'dgi_name_list')\n dgi_name_list = xml.get_text(dgi_name_list_node)\n dgi_name_list = dgi_name_list.split(',')\n card_data_nodes = xml.get_child_nodes(xml.root_element,'card_data')\n for card_data_node in card_data_nodes:\n cps = Cps()\n cps.dp_file_path = dp_file\n # account_node = xml.get_first_node(card_data_node,'PAN')\n # account = xml.get_text(account_node).replace('F','')\n for dgi_name in dgi_name_list:\n dgi_node = xml.get_first_node(card_data_node,dgi_name)\n dgi_text = xml.get_text(dgi_node)\n if dgi_name == 'AID':\n cps.aid = dgi_text[4:]\n continue\n if dgi_name == 'B001' or dgi_name == 'PAN':\n continue\n elif dgi_name in ('Store_PSE_1','Store_PSE_2','Store_PPSE'):\n dgi = _process_pse_and_ppse(dgi_name,dgi_text)\n else:\n dgi_name = dgi_name[3:] #默认DGI为DGIXXXX形式\n dgi = _parse_tlv(dgi_name,dgi_text)\n dgi.name = dgi_name\n cps.add_dgi(dgi)\n if rule_file:\n cps = _pre_process_rule(rule_file,cps)\n cps = _process_rsa(cps)\n cps = _process_8000_and_8020(cps)\n cps = _process_8400(cps)\n cps = _process_rule(rule_file,cps)\n cps_list.append(cps)\n return cps_list\n","sub_path":"perso_lib/dp_format/jy_xml_dp.py","file_name":"jy_xml_dp.py","file_ext":"py","file_size_in_byte":4884,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"209561500","text":"class Solution:\r\n # @param {string} s\r\n # @return {integer}\r\n def calculate(self, s):\r\n countReg, nReg, ls = [[]], [], len(s)\r\n for i in range(ls):\r\n if s[i] in \" ()+-\":\r\n if nReg:\r\n countReg[-1].append(self.nRegToNum(nReg))\r\n nReg = []\r\n if s[i] == \"(\":\r\n countReg.append([])\r\n if s[i] == \")\":\r\n eqVal = self.eqToNum(countReg[-1])\r\n countReg.pop(-1)\r\n countReg[-1].append(eqVal)\r\n if s[i] in \"+-\":\r\n countReg[-1].append(s[i])\r\n if s[i].isdigit():\r\n nReg.append(s[i])\r\n if nReg:\r\n countReg[-1].append(self.nRegToNum(nReg))\r\n return self.eqToNum(countReg[-1])\r\n\r\n\r\n\r\n def nRegToNum(self, nReg):\r\n lr, num = len(nReg), 0\r\n for i in range(lr):\r\n num += pow(10, lr-i-1)*int(nReg[i])\r\n return num\r\n\r\n def eqToNum(self, eq):\r\n if eq[0] == \"-\":\r\n eq[1] *= -1\r\n eq.pop(0)\r\n ans, le = eq[0], len(eq)\r\n for i in range(2, le, 2):\r\n if eq[i-1] == \"+\":\r\n ans += eq[i]\r\n else:\r\n ans -= eq[i]\r\n return ans\r\n\r\n\r\n\r\n\r\n\r\n\r\ndef check(inp, truth):\r\n solver = Solution()\r\n ans = solver.calculate(inp)\r\n if ans != truth:\r\n print('your: %s\\ntruth: %s' % (ans, truth))\r\n else:\r\n print(\"pass\\n===========\\n\")\r\n\r\ncheck(\"0\", 0)\r\ncheck(\"1-(2-(3))\", 2)\r\ncheck(\"(1+(4+5+2)-3)+(6+8)\", 23)\r\ncheck(\"(1-(4+5+2)-3)+(6+8)\", 1)\r\ncheck(\"1-(2-(3+4))\", 6)\r\ncheck(\"-(2-(3+4))\", 5)\r\n\r\n","sub_path":"Mine/224_basic calculator.py","file_name":"224_basic calculator.py","file_ext":"py","file_size_in_byte":1686,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"369397003","text":"import sys\nimport select\nimport numpy as np\nimport tensorflow as tf\n\nfrom tensorflow.contrib.rnn import BasicLSTMCell, MultiRNNCell\n\nif sys.version_info.major != 2:\n raise RuntimeError('Python 2 required')\n\n\nclass DataSource(object):\n def __init__(self, file_name, batch_size, seq_length, **ignored_args):\n self.file_name = file_name\n self.batch_size = batch_size\n self.seq_length = seq_length\n\n # pre-process\n\n self.text = ''.join(open(self.file_name).readlines()) # full text in a str\n self.n_batches = len(self.text) // (self.batch_size * self.seq_length)\n self.vocab = sorted(set(self.text)) # \"abcdefg...\"\n self.r_vocab = {c: i for i, c in enumerate(self.vocab)} # {'a': 0, 'b': 1, ...}\n\n def get_data(self):\n input_text = self.text[:self.n_batches * self.batch_size * self.seq_length]\n output_text = input_text[1:] + input_text[:1]\n return zip(self._text_to_batches(input_text), self._text_to_batches(output_text))\n\n def _text_to_batches(self, text):\n assert len(text) == self.n_batches * self.batch_size * self.seq_length\n encoded = np.array([self.r_vocab[c] for c in text]) # .dtype=int, .shape=(len(text),)\n encoded_reshaped = encoded.reshape((self.n_batches, self.batch_size, self.seq_length))\n batches = (x.T for x in encoded_reshaped) # .shape = (n_batches, seq_length, batch_size)\n return batches\n\n\nclass RnnModel(object):\n def __init__(self, batch_size, seq_length, n_layers, rnn_size, vocab_size, scope, **ignored_args):\n self.batch_size = batch_size\n self.seq_length = seq_length\n self.rnn_size = rnn_size\n self.vocab_size = vocab_size\n self.n_layers = n_layers\n self.scope = scope\n self.grad_clip = 5.0\n\n self.input_data = tf.placeholder(tf.int32, (self.seq_length, self.batch_size))\n self.target_data = tf.placeholder(tf.int32, (self.seq_length, self.batch_size))\n self.embedding = tf.get_variable(\"embedding\", (self.vocab_size, self.rnn_size))\n embedded = tf.nn.embedding_lookup(self.embedding, self.input_data)\n # embedded.shape = (self.seq_length, self.batch_size, self.rnn_size)\n self.softmax_w = tf.get_variable(\"softmax_w\", (self.rnn_size, self.vocab_size))\n self.softmax_b = tf.get_variable(\"softmax_b\", (self.vocab_size,))\n self.learning_rate = tf.placeholder(tf.float32, ())\n\n cell = MultiRNNCell([BasicLSTMCell(self.rnn_size) for _ in range(self.n_layers)])\n state = self.init_state = cell.zero_state(batch_size=self.batch_size, dtype=tf.float32)\n logits = [] # .shape = (seq_length, batch_size, vocab_size)\n\n with tf.variable_scope(self.scope):\n for i in range(self.seq_length):\n output, state = cell(embedded[i], state) # output.shape = (batch_size, rnn_size)\n logits.append(tf.matmul(output, self.softmax_w) + self.softmax_b)\n tf.get_variable_scope().reuse_variables()\n\n self.final_state = state\n loss = tf.nn.sparse_softmax_cross_entropy_with_logits(labels=self.target_data, logits=logits)\n self.cost = tf.reduce_mean(loss)\n\n tvars = tf.trainable_variables()\n grads, _ = tf.clip_by_global_norm(tf.gradients(self.cost, tvars), self.grad_clip)\n self.train_op = tf.train.AdamOptimizer(self.learning_rate).apply_gradients(zip(grads, tvars))\n\n # sample model\n\n self.sample_input_char = tf.placeholder(tf.int32)\n embedded = tf.nn.embedding_lookup(self.embedding, tf.reshape(self.sample_input_char, (1,)))\n self.sample_init_state = cell.zero_state(batch_size=1, dtype=tf.float32)\n with tf.variable_scope(self.scope, reuse=True):\n output, self.sample_final_state = cell(embedded, self.sample_init_state)\n logits = tf.matmul(output, self.softmax_w) + self.softmax_b\n self.sample_output_probs = tf.nn.softmax(logits[0])\n\n @staticmethod\n def _state_feed(placeholder, value):\n return {p: v for placeholder_i, value_i in zip(placeholder, value) for p, v in zip(placeholder_i, value_i)}\n\n def train(self, sess, input_data, target_data, learning_rate, init_state=None):\n feed = {self.input_data: input_data, self.target_data: target_data, self.learning_rate: learning_rate}\n if init_state: # continued training, start from last state\n feed.update(RnnModel._state_feed(self.init_state, init_state))\n loss, state, _ = sess.run([self.cost, self.final_state, self.train_op], feed_dict=feed)\n return loss, state\n\n def sample(self, sess, initial_text, source, length):\n state = probs = None\n result = []\n for i in range(length):\n c = initial_text[i] if i < len(initial_text) else np.random.choice(source.vocab, p=probs)\n result.append(c)\n feed = {self.sample_input_char: source.r_vocab[c]}\n if state:\n feed.update(RnnModel._state_feed(self.sample_init_state, state))\n probs, state = sess.run([self.sample_output_probs, self.sample_final_state], feed)\n return ''.join(result)\n\n\ndef main():\n args = {\n 'scope': 'a_scope_for_reusing_cell_weights',\n 'file_name': 'resource/input.txt',\n 'batch_size': 50,\n 'seq_length': 50,\n 'n_layers': 2,\n 'rnn_size': 128,\n 'n_epoch': 50,\n 'learning_rate': 0.002,\n 'decay_rate': 0.97,\n }\n\n source = DataSource(**args)\n args['vocab_size'] = len(source.vocab)\n\n model = RnnModel(**args)\n lr = args['learning_rate']\n with tf.Session() as sess:\n sess.run(tf.global_variables_initializer())\n\n state = None\n for i_epoch in range(args['n_epoch']):\n for i_batch, (input_data, target_data) in enumerate(source.get_data()):\n loss, state = model.train(sess,\n input_data=input_data,\n target_data=target_data,\n learning_rate=lr,\n init_state=state)\n print('\\x1b[33m[Press Enter to sample]\\x1b[0m'\n ' epoch {}, batch {}: loss = {:.3f}'.format(i_epoch, i_batch, loss))\n\n if sys.stdin in select.select([sys.stdin], [], [], 0)[0]:\n raw_input()\n print('\\x1b[33m------ sample start ------\\x1b[0m')\n print(model.sample(sess, 'The ', source, 200))\n print('\\x1b[33m------- sample end -------\\x1b[0m')\n print('\\x1b[33mPress Enter to continue ...\\x1b[0m')\n raw_input()\n\n lr *= args['decay_rate']\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"py2/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":6809,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"487577000","text":"N, A, B = map(int, input().split())\n\ncandidate = []\nfor i in range(N+1):\n splited = map(int,list(str(i)))\n s = sum(splited) \n if A <= s and s <= B:\n candidate.append(i)\n\nprint(sum(candidate))\n","sub_path":"abc083/run_b.py","file_name":"run_b.py","file_ext":"py","file_size_in_byte":208,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"360097234","text":"\"\"\"\nSimple script that:\n - Connects to local Orion\n - Creates a Room entity\n - Updates its temperature with random values every SLEEP seconds.\n\nNotifications are sent to NOTIFY_URL\n\"\"\"\nfrom client.client import OrionClient\nfrom experiments.common import sense\nfrom random import random\nfrom utils.common import create_simple_subscription_v1\nfrom utils.hosts import LOCAL\nimport json\n\nSLEEP = 5\nENTITY_ID = 'Room1'\nNOTIFY_URL = 'http://comet:8666/notify'\n\n\ndef subscribe_v1(orion, subscription):\n \"\"\"\n :param OrionClient orion:\n :param dict subscription: The subscription to be done, v1 format\n :return:\n \"\"\"\n # v2 subscriptions are not returning the generated subscription id :s\n r = orion.subscribe_v1(subscription)\n assert r.ok, r.text\n\n data = json.loads(r.text)\n subscription_id = data['subscribeResponse']['subscriptionId']\n return subscription_id\n\n\ndef create_entity(entity_id):\n entity = {\n 'id': entity_id,\n 'type': 'Room',\n 'temperature': {\n 'value': 23,\n 'type': 'Number'\n },\n }\n return entity\n\n\ndef update_args():\n v = 10 + 30 * random()\n res = {'temperature': {'value': v, 'type': 'Number'}}\n return res\n\n\nif __name__ == '__main__':\n entity = create_entity(ENTITY_ID)\n subscription = create_simple_subscription_v1(NOTIFY_URL)\n\n orion = OrionClient(host=LOCAL)\n subscription_id = subscribe_v1(orion, subscription)\n try:\n sense(orion, entity, update_args, SLEEP)\n finally:\n r = orion.unsubscribe(subscription_id)\n assert r.ok, r.text\n\n","sub_path":"experiments/comet/crazy_sensor.py","file_name":"crazy_sensor.py","file_ext":"py","file_size_in_byte":1594,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"51207722","text":"import ephem\r\n\r\ndef main():\r\n\r\n def receive_full_moon_date(user_text):\r\n trash_list = [\",\", \".\", \"\\\\\", \"-\"]\r\n splitted_user_text = user_text.split()[1]\r\n for word in splitted_user_text:\r\n for symbol in word:\r\n if symbol in trash_list:\r\n splitted_user_text = splitted_user_text.replace(symbol, \"/\")\r\n else:\r\n break\r\n splitted_date = splitted_user_text.split(\"/\")\r\n\r\n for index, number in enumerate(splitted_date):\r\n if len(number) > 3:\r\n year = splitted_date.pop(index)\r\n if index == 0:\r\n month = splitted_date.pop(index + 1)\r\n day = splitted_date.pop()\r\n elif index == 2:\r\n month = splitted_date.pop(index - 1)\r\n day = splitted_date.pop(index - 2)\r\n else:\r\n continue\r\n\r\n correct_date = \"/\".join([year, month, day])\r\n return correct_date\r\n print(receive_full_moon_date(\"/command 23-02-1999\"))\r\n\r\n\r\nif __name__ == \"__main__\":\r\n main()","sub_path":"receive_next_full_moon.py","file_name":"receive_next_full_moon.py","file_ext":"py","file_size_in_byte":1127,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"78784418","text":"import numpy as np\nimport torch\nimport torch.nn as nn\n\n\n# 在 cpu 下,比 nn.Embedding 快,但是在 gpu 的序列模型下比后者慢太多了\nclass CpuEmbedding(nn.Module):\n\n def __init__(self, num_embeddings, embed_dim):\n super(CpuEmbedding, self).__init__()\n\n self.weight = nn.Parameter(torch.zeros((num_embeddings, embed_dim)))\n nn.init.xavier_uniform_(self.weight.data)\n\n def forward(self, x):\n \"\"\"\n :param x: shape (batch_size, num_fields)\n :return: shape (batch_size, num_fields, embedding_dim)\n \"\"\"\n return self.weight[x]\n\n\nclass Embedding:\n\n def __new__(cls, num_embeddings, embed_dim):\n if torch.cuda.is_available():\n embedding = nn.Embedding(num_embeddings, embed_dim)\n nn.init.xavier_uniform_(embedding.weight.data)\n return embedding\n else:\n return CpuEmbedding(num_embeddings, embed_dim)\n\n\nclass FeaturesEmbedding(nn.Module):\n\n def __init__(self, field_dims, embed_dim):\n super(FeaturesEmbedding, self).__init__()\n self.embedding = Embedding(sum(field_dims), embed_dim)\n\n # e.g. field_dims = [2, 3, 4, 5], offsets = [0, 2, 5, 9]\n self.offsets = np.array((0, *np.cumsum(field_dims)[:-1]), dtype=np.long)\n\n def forward(self, x):\n \"\"\"\n :param x: shape (batch_size, num_fields)\n :return: shape (batch_size, num_fields, embedding_dim)\n \"\"\"\n x = x + x.new_tensor(self.offsets)\n return self.embedding(x)\n\n\nclass EmbeddingsInteraction(nn.Module):\n\n def __init__(self):\n super(EmbeddingsInteraction, self).__init__()\n\n def forward(self, x):\n \"\"\"\n :param x: shape (batch_size, num_fields, embedding_dim)\n :return: shape (batch_size, num_fields*(num_fields)//2, embedding_dim)\n \"\"\"\n\n num_fields = x.shape[1]\n i1, i2 = [], []\n for i in range(num_fields):\n for j in range(i + 1, num_fields):\n i1.append(i)\n i2.append(j)\n interaction = torch.mul(x[:, i1], x[:, i2])\n\n return interaction\n\n\nclass MultiLayerPerceptron(nn.Module):\n\n def __init__(self, layer, batch_norm=True):\n super(MultiLayerPerceptron, self).__init__()\n layers = []\n input_size = layer[0]\n for output_size in layer[1: -1]:\n layers.append(nn.Linear(input_size, output_size))\n if batch_norm:\n layers.append(nn.BatchNorm1d(output_size))\n layers.append(nn.ReLU())\n input_size = output_size\n layers.append(nn.Linear(input_size, layer[-1]))\n\n self.mlp = nn.Sequential(*layers)\n\n def forward(self, x):\n return self.mlp(x)\n","sub_path":"model/layer/layer.py","file_name":"layer.py","file_ext":"py","file_size_in_byte":2717,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"510488093","text":"# Write a program to implement insertion sort\r\n\r\ndef insertionSort(arr):\r\n\r\n for i in range(1, len(arr)):\r\n\r\n key = arr[i]\r\n j = i-1\r\n while j >=0 and key < arr[j] :\r\n arr[j+1] = arr[j]\r\n j -= 1\r\n arr[j+1] = key\r\n\r\nn = int(input('enter numbeer of element : '))\r\narr = []\r\nfor i in range(0,n):\r\n element = int(input())\r\n arr.append(element)\r\n\r\nprint(f'list you entered is {arr}')\r\ninsertionSort(arr)\r\nprint (\"Sorted array is:\")\r\nfor i in range(len(arr)):\r\n print (arr[i])","sub_path":"assignment4.py","file_name":"assignment4.py","file_ext":"py","file_size_in_byte":540,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"314241104","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sun Mar 24 15:43:37 2019\n\n@author: phill\n\"\"\"\n\n#iterative\nprev_rand_var = []\ndef rand_num_gen(a,c,K,x,i):\n if i==1:\n return ((a*x+c)%K)/K\n \n y = (a*x+c)%K\n return rand_num_gen(a,c,K,y,i-1)\n\n#non-iterative\ndef rand_num_gen2(a,c,K,x,i):\n if i==1:\n prev_rand_var.append(((a*x+c)%K))\n return ((a*x+c)%K)/K\n \n y = (a*prev_rand_var[i-2]+c)%K\n prev_rand_var.append(y)\n return y/K\n\n#method to return the array of random variables\ndef get_random_variables():\n return prev_rand_var\n\nk = pow(2,14)\n#print(rand_num_gen(7893,3517,k,1000,51))\n#print(rand_num_gen(7893,3517,k,1000,52))\n#print(rand_num_gen(7893,3517,k,1000,53))","sub_path":"Rand_Num_Gen.py","file_name":"Rand_Num_Gen.py","file_ext":"py","file_size_in_byte":701,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"321631039","text":"import asyncio\nimport datetime\n\n\n# курутина, которая отображает текущую дату и время каждую секунду в течении 5 секунд, используя функцию sleep()\n@asyncio.coroutine\ndef display_date(loop):\n end_time = loop.time() + 5.0\n\n while True:\n print('Текущая дата и время: {}'.format(datetime.datetime.now().strftime('%Y-%-m-%d %H:%M:%S')))\n\n if (loop.time() + 1.0) >= end_time:\n break\n\n # вызываем курутину, которая вернет значение через 1 секунду\n yield from asyncio.sleep(1)\n\n\ndef main():\n loop = asyncio.get_event_loop()\n loop.run_until_complete(display_date(loop))\n loop.close()\n\n\nif __name__ == '__main__':\n main()","sub_path":"asyncio_module/tasks_and_coroutines/app2.py","file_name":"app2.py","file_ext":"py","file_size_in_byte":818,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"273114203","text":"import logging\nimport traceback\n\nimport pandas as pd\nfrom trading_ig import IGStreamService\nfrom trading_ig.lightstreamer import Subscription\n\nfrom qstrader import setup_logging\nfrom .base import AbstractTickPriceHandler\nfrom ..event import TickEvent\nfrom ..price_parser import PriceParser\n\nsetup_logging\n\n\nclass IGTickPriceHandler(AbstractTickPriceHandler):\n def __init__(self, events_queue, ig_service, tickers, config):\n self.price_event = None\n self.events_queue = events_queue\n self.ig_stream_service, self.ig_stream_session = self._create_streaming_session(ig_service, accountId=config.IG_ACC_ID)\n self.tickers_lst = tickers\n self.tickers_subs = [\"MARKET:\" + ticker for ticker in tickers]\n self.tickers = {}\n for ticker in self.tickers_lst:\n self.tickers[ticker] = {}\n # Set up logging\n self.logger = logging.getLogger(__name__)\n\n def subscribe(self):\n # Making a new Subscription in MERGE mode\n subcription_prices = Subscription(\n mode=\"MERGE\",\n items=self.tickers_subs,\n fields=[\"BID\", \"OFFER\", \"CHANGE\", \"MARKET_STATE\", \"UPDATE_TIME\"],\n # adapter=\"QUOTE_ADAPTER\"\n )\n\n # Adding the \"on_price_update\" function to Subscription\n subcription_prices.addlistener(self._on_prices_update)\n\n # Registering the Subscription\n self.logger.info(\"Registering the Subscription\")\n try:\n self.ig_stream_service.ls_client.subscribe(subcription_prices)\n except Exception:\n self.logger.error(\"Error while subscribing\")\n print(traceback.format_exc())\n\n def _create_streaming_session(self, ig_service, accountId):\n\n # Cretes Streaming service and session\n ig_stream_service = IGStreamService(ig_service)\n ig_stream_session = ig_stream_service.create_session()\n\n # Connect with specified Listener\n ig_stream_service.connect(accountId)\n\n return ig_stream_service, ig_stream_session\n\n def _on_prices_update(self, data):\n if data[\"values\"][\"MARKET_STATE\"] == \"TRADEABLE\":\n tick_event = self._create_event(data)\n if tick_event is not None:\n self.logger.debug(\"Price update received\")\n self.logger.debug('Data received: %s' % data)\n self.logger.debug(\"Storing price update as instrument is tradeable\")\n self._store_price_event(tick_event)\n else:\n self.logger.info(\"Event not stored as market is closed/instrument is not tradeable\")\n\n def _create_event(self, data):\n ticker = data[\"name\"][7:]\n index = pd.to_datetime(data[\"values\"][\"UPDATE_TIME\"])\n bid = PriceParser.parse(data[\"values\"][\"BID\"]) / 10000\n ask = PriceParser.parse(data[\"values\"][\"OFFER\"]) / 10000\n return TickEvent(ticker, index, bid, ask)\n\n def _store_price_event(self, tick_event):\n \"\"\"\n Place the next PriceEvent (BarEvent or TickEvent) onto the event queue.\n \"\"\"\n if tick_event is not None:\n self._store_event(tick_event)\n self.events_queue.put(tick_event)\n","sub_path":"qstrader/price_handler/ig.py","file_name":"ig.py","file_ext":"py","file_size_in_byte":3171,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"607917832","text":"import net\nfrom algopy import UTPM\nimport tensorflow as tf\nimport numpy as np\nfrom tensorflow import keras\nimport alm\nfrom matplotlib import pyplot\nimport time\n\nrng = np.random.default_rng()\ndelta = 0.1\nW = 8\nK = 20\n\nsigma = lambda x: tf.math.tanh(x)\nsigma_ = lambda x: 2/(np.cosh(2*x)+1)\n\ntau = lambda x: x\ntau_ = lambda x: np.ones(x.shape)\n\n\nfor N in [10,20,40]:\n x = np.linspace(0,np.pi,N).reshape((N,1))\n y = np.sin(x*x)+rng.normal(0,delta,x.shape)\n per = rng.permutation(N)\n\n te = np.empty((K,4))\n for k in range(K):\n madam = keras.Sequential() \n madam.add(keras.layers.Dense(activation=\"tanh\",units=W,input_shape=(x.shape[1],)))\n madam.add(keras.layers.Dense(activation=\"tanh\",units=W))\n madam.add(keras.layers.Dense(units=y.shape[1]))\n adam = keras.optimizers.Adam()\n es = keras.callbacks.EarlyStopping(monitor='loss',patience=10)\n madam.compile(optimizer=adam, loss='mean_squared_error')\n\n malm = keras.Sequential()\n malm.add(alm.Dense_d(activation=sigma,activation_=sigma_,units=W,input_shape=(x.shape[1],)))\n malm.add(alm.Dense_d(activation=sigma,activation_=sigma_,units=W))\n malm.add(alm.Dense_d(activation=tau,activation_=tau_,units=y.shape[1]))\n \n w = madam.get_weights()\n malm.set_weights(w)\n \n t0 = time.process_time()\n hist = madam.fit(x[per,:],y[per,:],batch_size=N,epochs=4000,callbacks=[es],verbose=0)\n t1 = time.process_time()-t0\n e1 = len(hist.history['loss'])\n print(\"t: \",t1,\"k: \",e1,'loss: ', hist.history['loss'][-1])\n\n almnet = alm.ALMModel(malm, x[per,:], y[per,:])\n\n t0 = time.process_time()\n hist2 = almnet.fit_alm()\n t2 = time.process_time()-t0\n e2 = hist2['loss'].size\n print(\"t: \",t2,\"k: \",e2, 'loss: ', hist2['loss'][-1])\n \n te[k,:] = [t1,t2,e1,e2]\n with open('testtanhn.npy','ab') as f:\n np.save(f,np.array(hist.history['loss']))\n np.save(f,np.concatenate([np.array(value) for value in hist2.values()]).reshape((3,-1)).transpose())\n with open('testtanhn.npy','ab') as f:\n np.save(f,te)\n\n \n\n \n","sub_path":"python/testtanhn.py","file_name":"testtanhn.py","file_ext":"py","file_size_in_byte":2176,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"601259879","text":"import h5py\nimport torch\nfrom torch.nn import Parameter\nimport torch.nn.functional as F\nimport numpy as np\nimport copy\nimport re\nimport math\n\n\n\ndef load_data_test(imglabelpath, dataset, length_ratio=-1, is_sr=False, convert_msd=True, min_length=-1):\n\tdata = h5py.File(imglabelpath, 'r')\n\timage = data['raw']\n\tlabel = data['label']\n\n\t# change from dataset to array\n\timage = np.array(image).astype(np.float32)\n\tlabel = np.array(label).astype(dtype=np.uint8)\n\n\t## do the zero mean and unit variance\n\t# only caculate the mean and variance values of the positive\n\tif is_sr:\n\t\timage -= image.min()\n\t\timage /= image.max()\n\telse:\n\t\tmean_val = np.mean(image[image > 0])\n\t\tstd_val = np.std(image[image > 0])\n\n\t\timage = (image - mean_val) / std_val\n\n\tif length_ratio > 0:\n\t\texpected_length = int(length_ratio * image.shape[0])\n\t\tif expected_length < min_length:\n\t\t\texpected_length = min_length\n\t\texpected_size = (expected_length, ) + image.shape[1:]\n\t\timage = np.reshape(image, (1, 1,) + image.shape).astype(np.float32)\n\t\timage = F.interpolate(torch.from_numpy(image), size=expected_size, mode='trilinear', align_corners=False).numpy()[0, 0, :, :, :]\n\n\tif 'msd' in dataset or 'nih' in dataset:\n\t\tlabel[label > 1] = 0\n\n\t\tif 'liver' in dataset:\n\t\t\ttarget_class = 5\n\t\telif 'pancreas' in dataset:\n\t\t\ttarget_class = 6\n\t\telif 'spleen' in dataset:\n\t\t\ttarget_class = 7\n\t\telse:\n\t\t\tprint('dataset error')\n\t\t\texit(-1)\n\t\tif convert_msd:\n\t\t\tlabel[label == 1] = target_class\n\n\treturn image, label\n\n\ndef construct_PE(image, weight):\n\t# image is (H, W, L) shape torch tensor\n\t# return (1, 1, H, W, L)-shaped image if weight <= 0\n\tassert image.dim() == 3\n\tif weight <= 0:\n\t\treturn image.unsqueeze(0).unsqueeze(0)\n\n\tdevice = image.device\n\tI1 = np.arange(image.shape[-3]).astype(np.float) / (image.shape[-3] - 1)\n\tI1 = I1[:, np.newaxis, np.newaxis]\n\tI1 = np.tile(I1, (1, image.shape[-2], image.shape[-1]))\n\tI2 = np.arange(image.shape[-2]).astype(np.float) / (image.shape[-2] - 1)\n\tI2 = I2[np.newaxis, :, np.newaxis]\n\tI2 = np.tile(I2, (image.shape[-3], 1, image.shape[-1]))\n\tI3 = np.arange(image.shape[-1]).astype(np.float) / (image.shape[-1] - 1)\n\tI3 = I3[np.newaxis, np.newaxis, :]\n\tI3 = np.tile(I3, (image.shape[-3], image.shape[-2], 1))\n\n\tposition_encoding = np.stack([I1, I2, I3]) * weight # 4, H, W, L\n\tposition_encoding = torch.from_numpy(position_encoding).unsqueeze(0).to(device)\n\n\treturn position_encoding\n\n\ndef color_map(N=256, normalized=False):\n\tdef bitget(byteval, idx):\n\t\treturn ((byteval & (1 << idx)) != 0)\n\n\tdtype = 'float32' if normalized else 'uint8'\n\tcmap = np.zeros((N, 3), dtype=dtype)\n\tfor i in range(N):\n\t\tr = g = b = 0\n\t\tc = i\n\t\tfor j in range(8):\n\t\t\tr = r | (bitget(c, 0) << 7 - j)\n\t\t\tg = g | (bitget(c, 1) << 7 - j)\n\t\t\tb = b | (bitget(c, 2) << 7 - j)\n\t\t\tc = c >> 3\n\n\t\tcmap[i] = np.array([r, g, b])\n\n\tcmap = cmap / 255 if normalized else cmap\n\treturn cmap\n\n\ndef adjust_opt(optAlg, optimizer, init_lr, iter_num, max_iterations, power=0.9):\n\tif optAlg == 'sgd':\n\t\tlr = init_lr * math.pow(1.0 - (iter_num / max_iterations), power)\n\n\t\tfor param_group in optimizer.param_groups:\n\t\t\tparam_group['lr'] = lr\n\n\ndef visualize(im, vote_map, label, n_class=9, ratio=1.0):\n\tim -= im.min()\n\tim = (im / im.max() * 255).astype(np.uint8)\n\tcmap = color_map()\n\tim = im[..., np.newaxis]\n\tim = im.repeat(3, axis=-1)\n\tpre_vis = copy.deepcopy(im)\n\n\tfor c_idx in range(1, n_class):\n\t\tim[..., 0][label == c_idx] = cmap[c_idx, 0] * ratio + im[..., 0][label == c_idx] * (1. - ratio)\n\t\tim[..., 1][label == c_idx] = cmap[c_idx, 1] * ratio + im[..., 1][label == c_idx] * (1. - ratio)\n\t\tim[..., 2][label == c_idx] = cmap[c_idx, 2] * ratio + im[..., 2][label == c_idx] * (1. - ratio)\n\n\t\tpre_vis[..., 0][vote_map == c_idx] = cmap[c_idx, 0] * ratio + pre_vis[..., 0][vote_map == c_idx] * (1. - ratio)\n\t\tpre_vis[..., 1][vote_map == c_idx] = cmap[c_idx, 1] * ratio + pre_vis[..., 1][vote_map == c_idx] * (1. - ratio)\n\t\tpre_vis[..., 2][vote_map == c_idx] = cmap[c_idx, 2] * ratio + pre_vis[..., 2][vote_map == c_idx] * (1. - ratio)\n\n\tvis = np.concatenate((im, pre_vis), axis=2)\n\treturn vis\n\n\ndef vis_one_image(im, label, n_class=9, ratio=0.8):\n\tim = im.astype(np.float32)\n\tim -= im.min()\n\tim = (im / im.max() * 255).astype(np.uint8)\n\tcmap = color_map()\n\tim = im[..., np.newaxis]\n\tim = im.repeat(3, axis=-1)\n\n\tfor c_idx in range(1, n_class):\n\t\tcolor_idx = c_idx\n\t\tif c_idx == 8:\n\t\t\tcolor_idx = 11\n\t\tif c_idx == 6:\n\t\t\tcmap[c_idx, 1] = 255\n\t\t\tcmap[c_idx, 2] = 255\n\t\tim[..., 0][label == c_idx] = cmap[color_idx, 0] * ratio + im[..., 0][label == c_idx] * (1. - ratio)\n\t\tim[..., 1][label == c_idx] = cmap[color_idx, 1] * ratio + im[..., 1][label == c_idx] * (1. - ratio)\n\t\tim[..., 2][label == c_idx] = cmap[color_idx, 2] * ratio + im[..., 2][label == c_idx] * (1. - ratio)\n\n\treturn im\n\n\ndef vis_sr_images(im, output_map):\n\tassert im.min() >= 0 and output_map.min() >= 0\n\tassert im.max() <= 1 and output_map.max() <= 1\n\n\tim = (im * 255.).astype(np.uint8)[..., np.newaxis]\n\toutput_map = (output_map * 255.).astype(np.uint8)[..., np.newaxis]\n\tim = im.repeat(3, axis=-1)\n\toutput_map = output_map.repeat(3, axis=-1)\n\tvis = np.concatenate((im, output_map), axis=2)\n\treturn vis\n\n\ndef cal_histogram(im, label, cls):\n\tassert im.min() >= 0 and im.max() <= 1\n\tim = (im * 255.).astype(np.uint8)\n\n\tim = im[label == cls].ravel()\n\thist = np.bincount(im, minlength=256)\n\treturn hist\n\n\ndef load_state_dict(net, state_dict, remove='', add=''):\n\town_state = net.state_dict()\n\tfor param in own_state.items():\n\t\tname = add + param[0].replace(remove, '')\n\t\tif name not in state_dict:\n\t\t\tprint('{} not in pretrained model'.format(param[0]))\n\tfor name, param in state_dict.items():\n\t\tif remove + name.replace(add, '') not in own_state:\n\t\t\tprint('skipping {}'.format(name))\n\t\tcontinue\n\t\tif isinstance(param, Parameter):\n\t\t# backwards compatibility for serialized parameters\n\t\t\tparam = param.data\n\t\tif param.shape == own_state[remove + name.replace(add, '')].shape:\n\t\t\town_state[remove + name.replace(add, '')].copy_(param)\n\t\telse:\n\t\t\tprint('skipping {} because of shape inconsistency'.format(name))\n\n\ndef dice(x, y, eps=1e-7):\n\tintersect = np.sum(np.sum(np.sum(x * y)))\n\ty_sum = np.sum(np.sum(np.sum(y)))\n\tx_sum = np.sum(np.sum(np.sum(x)))\n\treturn 2 * intersect / (x_sum + y_sum + eps)\n\n\ndef binary_dice_loss(input, target):\n\tsmooth = 1.\n\n\t# apply softmax to input\n\tinput = F.softmax(input, dim=1)\n\tinput = input[:, 1]\n\n\tiflat = input.contiguous().view(-1)\n\ttflat = target.contiguous().view(-1)\n\tintersection = (iflat * tflat).sum()\n\n\tloss = 1 - ((2. * intersection + smooth) / (iflat.sum() + tflat.sum() + smooth))\n\treturn loss\n\n\ndef sort_nicely(l):\n\t\"\"\" Sort the given list in the way that humans expect.\n\t\"\"\"\n\tconvert = lambda text: int(text) if text.isdigit() else text\n\talphanum_key = lambda key: [ convert(c) for c in re.split('([0-9]+)', key) ]\n\tl.sort( key=alphanum_key )\n\treturn l\n\n","sub_path":"uda/utils/utils_legacy.py","file_name":"utils_legacy.py","file_ext":"py","file_size_in_byte":6827,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"263192035","text":"from decimal import Decimal\nfrom django.conf import settings\nfrom django.shortcuts import get_object_or_404\nfrom games.models import Product\n\nfrom membership.models import Membership\nfrom datetime import datetime\nfrom decimal import *\n\n\ndef get_discount(request):\n user = request.user\n discount = 1.0\n\n try:\n user_membership = Membership.objects.get(user=user)\n current_date = datetime.now().date()\n if current_date < user_membership.expiry:\n # 10% for premium members\n if user_membership.is_premium:\n discount = 0.9\n # 5% for members\n else:\n discount = 0.95\n except (Membership.DoesNotExist, TypeError) as e:\n discount = 1.0\n\n return discount\n\n\ndef bag_contents(request):\n\n bag_items = []\n total = 0\n product_count = 0\n bag = request.session.get('bag', {})\n\n total_discount = 0\n gross_total = 0\n\n for item_id, quantity in bag.items():\n\n try:\n product = Product.objects.get(pk=item_id)\n\n # apply membership discounts, if needed\n unit_price = product.price\n\n discount = get_discount(request)\n if not product.is_membership:\n product.discounted_price = round(Decimal(discount * float(product.price)), 2)\n unit_price = product.discounted_price\n\n subtotal = quantity * unit_price\n gross_total += quantity * product.price\n\n total += subtotal\n product_count += quantity\n bag_items.append({\n 'item_id': item_id,\n 'quantity': quantity,\n 'product': product,\n 'subtotal': subtotal\n })\n except Product.DoesNotExist as e:\n print(\"Can't find product:\", e)\n\n grand_total = total\n total_discount = grand_total - gross_total\n\n context = {\n 'bag_items': bag_items,\n 'total': total,\n 'product_count': product_count,\n 'grand_total': grand_total,\n 'gross_total': gross_total,\n 'total_discount': total_discount\n }\n\n return context\n","sub_path":"bag/contexts.py","file_name":"contexts.py","file_ext":"py","file_size_in_byte":2140,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"197708022","text":"\"\"\"\nSolve riemann shock tube problem for a general equation of state using\nthe method of Colella and Glaz. Use a two shock approximation, and\nlinearly interpolation between the head and tail of a rarefaction to\ntreat rarefactions.\n\nThe Riemann problem for the Euler's equation produces 4 states,\nseparated by the three characteristics (u - cs, u, u + cs):\n\n\n l_1 t l_2 l_3\n \\ ^ . /\n \\ *L | . *R /\n \\ | . /\n \\ | . /\n L \\ | . / R\n \\ | . /\n \\ |. /\n \\|./\n ----------+----------------> x\n\n l_1 = u - cs eigenvalue\n l_2 = u eigenvalue (contact)\n l_3 = u + cs eigenvalue\n\n only density jumps across l_2\n\n References:\n\n CG: Colella & Glaz 1985, JCP, 59, 264.\n\n CW: Colella & Woodward 1984, JCP, 54, 174.\n\n Fry: Fryxell et al. 2000, ApJS, 131, 273.\n\n Toro: Toro 1999, ``Riemann Solvers and Numerical Methods for Fluid\n Dynamcs: A Practical Introduction, 2nd Ed.'', Springer-Verlag\n\"\"\"\n\nimport numpy as np\nimport sys\n\nURHO = 0\nUMX = 1\nUENER = 2\n\nQRHO = 0\nQU = 1\nQP = 2\n\nNVAR = 3\n\n\ndef riemann(q_l, q_r, gamma):\n\n flux = np.zeros(NVAR)\n\n # some parameters\n riemann_tol = 1.e-5\n nriem = 15\n\n smlrho = 1.e-10\n smallp = 1.e-10\n smallu = 1.e-10\n\n rho_l = q_l[QRHO]\n u_l = q_l[QU]\n p_l = max(q_l[QP], smallp)\n\n rho_r = q_r[QRHO]\n u_r = q_r[QU]\n p_r = max(q_r[QP], smallp)\n\n # specific volume\n tau_l = 1./max(rho_l, smlrho)\n tau_r = 1./max(rho_r, smlrho)\n\n c_l = np.sqrt(gamma*p_l*rho_l)\n c_r = np.sqrt(gamma*p_r*rho_r)\n\n # construct first guess for secant iteration by assuming that the\n # nonlinear wave speed is equal to the sound speed -- the resulting\n # expression is the same as Toro, Eq. 9.28 in the Primitive Variable\n # Riemann Solver (PVRS). See also Fry Eq. 72.\n pstar1 = p_r - p_l - c_r*(u_r - u_l)\n pstar1 = p_l + pstar1*(c_l/(c_l + c_r))\n pstar1 = max(smallp, pstar1)\n\n # calculate nonlinear wave speeds for the left and right moving\n # waves based on the first guess for the pressure jump. Again,\n # there is a left and a right wave speed. Compute this using CG\n # Eq. 34.\n\n # note -- we simplify a lot here, assuming constant gamma\n w_l1 = pstar1 + 0.5*(gamma - 1.0)*(pstar1 + p_l)\n w_l1 = np.sqrt(rho_l*abs(w_l1))\n\n w_r1 = pstar1 + 0.5*(gamma - 1.0)*(pstar1 + p_r)\n w_r1 = np.sqrt(rho_r*abs(w_r1))\n\n # construct second guess for the pressure using the nonlinear wave\n # speeds from the first guess. This is basically the same thing we\n # did to get pstar1, except now we are using the better wave speeds\n # instead of the sound speed.\n pstar2 = p_r - p_l - w_r1*(u_r - u_l)\n pstar2 = p_l + pstar2*w_l1/(w_l1 + w_r1)\n pstar2 = max(smallp, pstar2)\n\n # begin the secant iteration -- see CG Eq. 17 for details. We will\n # continue to interate for convergence until the error falls below\n # tol (in which case, things are good), or we hit nriem iterations\n # (in which case we have a problem, and we spit out an error).\n has_converged = False\n\n for n in range(nriem):\n\n # new nonlinear wave speeds, using CG Eq. 34\n w_l = pstar2 + 0.5*(gamma - 1.)*(pstar2 + p_l)\n w_l = np.sqrt(rho_l*abs(w_l))\n\n w_r = pstar2 + 0.5*(gamma - 1.)*(pstar2 + p_r)\n w_r = np.sqrt(rho_r*abs(w_r))\n\n # compute the velocities in the \"star\" state -- using CG\n # Eq. 18 -- ustar_l2 and ustar_r2 are the velocities they define\n # there. ustar_l1 and ustar_l2 seem to be the velocities at the\n # last time, since pstar1 is the old 'star' pressure, and\n # w_l1 is the old wave speed.\n ustar_l1 = u_l - (pstar1 - p_l)/w_l1\n ustar_r1 = u_r + (pstar1 - p_r)/w_r1\n ustar_l2 = u_l - (pstar2 - p_l)/w_l\n ustar_r2 = u_r + (pstar2 - p_r)/w_r\n\n delu1 = ustar_l1 - ustar_r1\n delu2 = ustar_l2 - ustar_r2\n\n scratch = delu2 - delu1\n\n if abs(pstar2 - pstar1) <= smallp:\n scratch = 0.\n\n if abs(scratch) < smallu:\n delu2 = 0.\n scratch = 1.\n\n # pressure at the \"star\" state -- using CG Eq. 18\n pstar = pstar2 - delu2*(pstar2 - pstar1)/scratch\n pstar = max(smallp, pstar)\n\n # check for convergence of iteration\n pres_err = abs(pstar - pstar2)/pstar\n if pres_err < riemann_tol:\n has_converged = True\n break\n\n # reset variables for next iteration\n pstar1 = pstar2\n pstar2 = pstar\n\n w_l1 = w_l\n w_r1 = w_r\n\n\n if not has_converged:\n print(\"Nonconvergence in subroutine rieman!\")\n print(\"Pressure error = \", pres_err)\n print(\"pL = \", p_l, \" pR = \", p_r)\n print(\"uL = \", u_l, \" uR = \", u_r)\n print(\"cL = \", c_l, \" c_r = \", c_r)\n print(\"Terminating execution\")\n sys.exit(\"stopping\")\n\n # end of secant iteration\n\n # calculate fluid velocity for the \"star\" state -- this comes from\n # the shock jump equations, Fry Eq. 68 and 69. The ustar velocity\n # can be computed using either the jump eq. for a left moving or\n # right moving shock -- we use the average of the two.\n\n scratch = u_l - (pstar - p_l)/w_l\n scratch2 = u_r + (pstar - p_r)/w_r\n ustar = 0.5*(scratch + scratch2)\n\n if ustar < 0:\n ustar_sgn = -1.0\n elif ustar == 0.0:\n ustar_sgn = 0.0\n else:\n ustar_sgn = 1.0\n\n # decide which state is located at the zone iterface based on\n # the values of the wave speeds. This is just saying that if\n # ustar > 0, then the state is U_L. if ustar < 0, then the\n # state on the axis is U_R.\n scratch = 0.5*(1.0 + ustar_sgn)\n scratch2 = 0.5*(1.0 - ustar_sgn)\n\n ps = p_l*scratch + p_r*scratch2\n us = u_l*scratch + u_r*scratch2\n vs = tau_l*scratch + tau_r*scratch2\n\n rhos = 1.0/vs\n rhos = max(smlrho, rhos)\n\n vs = 1.0/rhos\n ws = w_l*scratch + w_r*scratch2\n ces = np.sqrt(gamma*ps*vs)\n\n # compute rhostar, using the shock jump condition (Fry Eq. 80)\n vstar = vs - (pstar - ps)/(ws*ws)\n rhostr = 1.0/ vstar\n cestar = np.sqrt(gamma*pstar*vstar)\n\n # compute some factors, Fry Eq. 81 and 82\n wes = ces - ustar_sgn*us\n westar = cestar - ustar_sgn*ustar\n\n scratch = ws*vs - ustar_sgn*us\n\n if pstar - ps >= 0.0:\n wes = scratch\n westar = scratch\n\n # compute correct state for rarefaction fan by linear interpolation\n scratch = max(wes - westar, wes + westar)\n scratch = max(scratch, smallu)\n\n scratch = (wes + westar)/scratch\n\n scratch = 0.5*(1.0 + scratch)\n scratch2 = 1.0 - scratch\n\n rhoav = scratch*rhostr + scratch2*rhos\n uav = scratch*ustar + scratch2*us\n pav = scratch*pstar + scratch2*ps\n\n if westar >= 0.0:\n rhoav = rhostr\n uav = ustar\n pav = pstar\n\n if wes < 0.0:\n rhoav = rhos\n uav = us\n pav = ps\n\n # now compute the fluxes\n flux[URHO] = rhoav*uav\n flux[UMX] = rhoav*uav*uav + pav\n flux[UENER] = uav*(pav/(gamma - 1.0) + 0.5*rhoav*uav*uav + pav)\n\n return flux\n","sub_path":"Intro_Comp_Astrophysical_Hydrodynamics_Zingale/compressible/MOL/python/riemann.py","file_name":"riemann.py","file_ext":"py","file_size_in_byte":7156,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"74568366","text":"from django.conf.urls import url\n\nfrom . import views\n\n\nurlpatterns = [\n url(r'^login/$', views.StaffLogin.as_view(), name='staff-login'),\n\n url(r'^home/$', views.StaffHome.as_view(), name='staff-home'),\n\n url(r'^org/$', views.Organization.as_view(), name='org'),\n url(r'^org/add/$', views.AddOrganization.as_view(), name='add-org'),\n url(r'^org/view/$', views.ViewOrganization.as_view(), name='view-org'),\n url(r'^org/(?P[0-9]+)/delete/$', views.DeleteOrganization.as_view(), name='delete-org'),\n url(r'^org/(?P[0-9]+)/detail/$', views.DetailOrganization.as_view(), name='detail-org'),\n url(r'^org/(?P[0-9]+)/edit/$', views.EditOrganization.as_view(), name='edit-org'),\n url(r'^org/(?P[0-9]+)/member/$', views.OrganizationMember.as_view(), name='org-member'),\n\n url(r'^save/(?P[a-zA-Z0-9_-]+)/$', views.some_streaming_csv_view, name='save_file'),\n\n\n url(r'^member/$', views.Member.as_view(), name='member'),\n url(r'^member/(?P[0-9]+)/add/$', views.AddMember.as_view(), name='add-member'),\n url(r'^member/view/$', views.ViewMember.as_view(), name='view-member'),\n url(r'^member/(?P[0-9]+)/delete/$', views.DeleteMember.as_view(), name='delete-member'),\n url(r'^member/(?P[0-9]+)/detail/$', views.DetailMember.as_view(), name='detail-member'),\n url(r'^member/(?P[0-9]+)/activate-deactivate/$', views.ActivateDeactivateAccount.as_view(), name='activate-deactivate-account'),\n url(r'^member/(?P[0-9]+)/change-password/$', views.ChangePassword.as_view(), name='change-password'),\n url(r'^member/(?P[0-9]+)/edit/$', views.EditMember.as_view(), name='edit-member'),\n\n\n url(r'^member/upload/$', views.MemberUpload.as_view(), name='member-upload'),\n\n]\n","sub_path":"staff/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1797,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"387898610","text":"import os\nimport librosa\nimport sys\nsys.path.append(os.path.abspath(__file__)[:os.path.abspath(__file__).rfind(\"\\\\hlp\\\\\")])\nfrom hlp.tts.utils.spec import get_spectrograms\nimport tensorflow as tf\nimport numpy as np\nimport io\n# 处理语音文件\ndef load_wav(path, sample_rate):\n print(\"path::\", path)\n y = librosa.load(path, sr=sample_rate)[0]\n return y\n\ndef process_wav(path, sample_rate, peak_norm, voc_mode, bits, mu_law, preemphasis, n_fft, n_mels, hop_length, win_length\n , max_db, ref_db, top_db):\n y = load_wav(path, sample_rate)\n peak = np.abs(y).max()\n if peak_norm or peak > 1.0:\n y /= peak\n mel, mag = get_spectrograms(path, preemphasis, n_fft, n_mels, hop_length, win_length, max_db, ref_db, top_db)\n if voc_mode == 'RAW':\n quant = encode_mu_law(y, mu=2**bits) if mu_law else float_2_label(y, bits=bits)\n elif voc_mode == 'MOL':\n quant = float_2_label(y, bits=16)\n\n return mel.astype(np.float32), quant.astype(np.int64)\n\n\ndef read_data(path, sample_rate, peak_norm, voc_mode, bits, mu_law, wav_name_list2, preemphasis, n_fft, n_mels,\n hop_length, win_length, max_db, ref_db, top_db):\n mel_list = []\n sig_list = []\n for file in wav_name_list2:\n m, x = process_wav(path + file+'.wav', sample_rate, peak_norm, voc_mode, bits, mu_law, preemphasis, n_fft,\n n_mels, hop_length, win_length, max_db, ref_db, top_db)\n print(\"m\", m.shape)\n print(\"x\", x.shape)\n\n mel_list.append(m.tolist())\n sig_list.append(x.tolist())\n\n # mel_list = tf.keras.preprocessing.sequence.pad_sequences(mel_list, maxlen=max_len_mel, padding='post',\n # dtype='float32')\n # sig_list = tf.keras.preprocessing.sequence.pad_sequences(sig_list, maxlen=max_len_sig, padding='post',\n # dtype='float32')\n # input_mel = tf.convert_to_tensor(mel_list)\n # input_sig = tf.convert_to_tensor(sig_list)\n\n return mel_list, sig_list\n\ndef encode_mu_law(x, mu):\n mu = mu - 1\n fx = np.sign(x) * np.log(1 + mu * np.abs(x)) / np.log(1 + mu)\n return np.floor((fx + 1) / 2 * mu + 0.5)\n\ndef float_2_label(x, bits):\n assert abs(x).max() <= 1.0\n x = (x + 1.) * (2**bits - 1) / 2\n return x.clip(0, 2**bits - 1)\n\n\n# 提取语音文件名\ndef process_wav_name(wav_path):\n datanames = os.listdir(wav_path)\n wav_name_list = []\n for i in datanames:\n wav_name_list.append(i[:10])\n return wav_name_list\n\n\ndef label_2_float(x, bits):\n return 2 * x / (2**bits - 1.) - 1.","sub_path":"hlp/tts/wavernn/preprocess.py","file_name":"preprocess.py","file_ext":"py","file_size_in_byte":2625,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"200369771","text":"import os\n\nfrom google.appengine.api import users\nfrom google.appengine.ext import db\nfrom google.appengine.ext import webapp\nfrom google.appengine.ext.webapp import template\n\nimport entities\n\n\"\"\"\nCreates a form for Producers to enter information \nabout a Product\n\"\"\"\nclass CreateProductPage(webapp.RequestHandler):\n def get(self):\n user = users.get_current_user()\n\n factory_names = []\n factories = entities.Factory.all()\n for factory in factories:\n factory_names.append(factory.name)\n template_values = {\n 'producerName' : user.nickname(),\n 'badges' : entities.Badge.all(),\n 'factory_names' : factory_names\n }\n path = os.path.join(os.path.dirname(__file__), 'createproduct.html')\n self.response.out.write(template.render(path, template_values))\n \n\"\"\"\nPage that stores Product in datastore\n\"\"\"\nclass StoreProductPage(webapp.RequestHandler):\n def post(self):\n user = users.get_current_user()\n if user:\n _name = self.request.get('name')\n _producerName = self.request.get('producerName')\n _factoryName = self.request.get('factoryName')\n _badges = self.request.get_all('badges')\n _picture = self.request.get('picture')\n if isinstance(_picture, unicode):\n _picture = _picture.encode('utf-8', 'replace')\n _factoryMade = entities.Factory.gql(\"WHERE name = :1\", _factoryName).get()\n\n p = entities.Product(name=_name, producerName=_producerName, factoryMade=_factoryMade.key())\n for _badge in _badges:\n p.badges.append(db.Key(_badge))\n p.picture = db.Blob(_picture)\n p.put()\n self.redirect('/view?id=' + str(p.key()))\n else:\n greeting = (\"Sign in or register .\" %\n users.create_login_url(\"/storeproduct\"))\n self.response.out.write(\"%s\" % greeting)\n","sub_path":"create_product.py","file_name":"create_product.py","file_ext":"py","file_size_in_byte":2022,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"518859073","text":"import pandas as pd\nfrom decimal import Decimal, getcontext\n\nclass StrategyEvaluator:\n\t\"\"\" Used to evaluate the performace of strategies \"\"\"\n\n\tdef __init__(self, strategy_function, strategy_settings:dict={'indicators':['low_boll', 'fast_sma', 'slow_sma']}):\n\n\t\tself.strategy = strategy_function\n\t\tself.settings = strategy_settings\n\t\tself.buy_times = []\n\t\tself.sell_times = []\n\n\t\tself.profitable_symbols = 0\n\t\tself.unprofitable_symbols = 0\n\n\t\tself.complete_starting_balance = 0\n\t\tself.complete_resulting_balance = 0\n\n\t\tself.profits_list = []\n\t\tself.results = dict()\n\n\tdef backtest(self,\n\tmodel,\n\tstarting_balance:float = 100,\n\tinitial_profits:float = 1.045,\n\tinitial_stop_loss:float = 0.85,\n\tincremental_profits:float = 1.04,\n\tincremental_stop_loss:float = 0.975):\n\t\t'''\n\t\tFunction used to backtest a strategy given a TradingModel model\n\n\t\tParameters\n\t\t--\n\t\t\tfloat starting balance\n\t\t\t\tThe balance with which to start the strategy backtesting\n\t\t\t\n\t\t\t(etc)\n\n\t\tReturns\n\t\t--\n\t\t\tfloat the balance after having run the strategy\n\t\t'''\n\n\t\tif initial_stop_loss >= 1 or initial_stop_loss <= 0:\n\t\t\tAssertionError(\"initial_stop_loss should be betweem 0 and 1!\")\n\n\t\tif initial_profits <= 1:\n\t\t\tAssertionError(\"initial_profits should be greater than 1!\")\n\n\t\tdf = model.df\n\t\tbuy_times = []\n\t\tsell_times = []\n\n\t\tlast_buy = None\n\n\t\tgetcontext().prec = 30\n\n\t\tresulting_balance = Decimal(starting_balance)\n\t\tstop_loss = Decimal(initial_stop_loss)\n\t\tprofit_target = Decimal(initial_profits)\n\t\tbuy_price = 0\n\n\t\t# Go through all candlesticks\n\t\tfor i in range(0, len(df['close'])-1):\n\t\t\t# Have we already bought? (We're not doing parallel trades on the same symbol)\n\t\t\tif last_buy is None:\n\t\t\t\t# No, then check whether the strategy is fulfilled at this point in time\n\t\t\t\tstrategy_result = self.strategy(model.df, i)\n\n\t\t\t\tif strategy_result:\n\t\t\t\t\t# IF strategy fulfilled, buy some amount of coin\n\t\t\t\t\tbuy_price = Decimal(strategy_result)\n\t\t\t\t\tlast_buy = {\n\t\t\t\t\t\t\"index\" : i,\n\t\t\t\t\t\t\"price\" : buy_price,\n\t\t\t\t\t}\n\t\t\t\t\tbuy_times.append([df['time'][i], buy_price])\n\n\t\t\t\t\tstop_loss = Decimal(initial_stop_loss)\n\t\t\t\t\tprofit_target = Decimal(initial_profits)\n\n\t\t\telif last_buy is not None and i > last_buy[\"index\"] + 1:\n\t\t\t\t# Yes (we already bought) so check whether the price has hit \n\t\t\t\t# EITHER the stop loss price OR the target price\n\t\t\t\tstop_loss_price = last_buy[\"price\"] * stop_loss\n\t\t\t\tnext_target_price = last_buy[\"price\"] * profit_target\n\n\t\t\t\tif df['low'][i] < stop_loss_price:\n\t\t\t\t\t# If price went below our stop_loss, we sold at that point\n\t\t\t\t\tsell_times.append([df['time'][i], stop_loss_price])\n\t\t\t\t\tresulting_balance = resulting_balance * (stop_loss_price / buy_price)\n\n\t\t\t\t\tlast_buy = None\n\t\t\t\t\tbuy_price = Decimal(0)\n\n\t\t\t\telif df['high'][i] > next_target_price:\n\t\t\t\t\t# If price went above our target, it means we increased our stop loss \n\t\t\t\t\t# and set our next target\n\t\t\t\t\tlast_buy = {\n\t\t\t\t\t\t\"index\" : i,\n\t\t\t\t\t\t\"price\" : Decimal(next_target_price)\n\t\t\t\t\t}\n\n\t\t\t\t\tstop_loss = Decimal(incremental_stop_loss)\n\t\t\t\t\tprofit_target = Decimal(incremental_profits)\n\t\t\n\t\t# Now, aggregate results and add them to this model's symbol\n\t\tself.results[model.symbol] = dict(\n\t\t\treturns = round(Decimal(100.0) * (resulting_balance/Decimal(starting_balance) - Decimal(1.0)), 3),\n\t\t\tbuy_times = buy_times,\n\t\t\tsell_times = sell_times\n\t\t)\n\n\t\tif resulting_balance > starting_balance:\n\t\t\tself.profitable_symbols = self.profitable_symbols + 1\n\t\telif resulting_balance < starting_balance:\n\t\t\tself.unprofitable_symbols = self.unprofitable_symbols + 1\n\t\t\n\t\treturn resulting_balance\n\n\tdef evaluate(self, model):\n\t\tlast_entry = len(model.df['close']) - 1\n\t\treturn self.strategy(model.df, last_entry)\n\t\n\tdef updateResult(self, starting_balance, resulting_balance):\n\t\tself.complete_starting_balance = self.complete_starting_balance + starting_balance\n\t\tself.complete_resulting_balance = self.complete_resulting_balance + resulting_balance\n\n\tdef printResults(self):\n\t\tprint(self.strategy.__name__+\" STATS: \")\n\t\tprint(\"Profitable Symbols: \"+str(self.profitable_symbols))\n\t\tprint(\"Unprofitable Symbols: \"+str(self.unprofitable_symbols))\n\t\t\n\t\tif len(self.profits_list) > 0:\n\t\t\tprofitability = Decimal(100.0) * (self.complete_resulting_balance/self.complete_starting_balance - Decimal(1.0))\n\t\t\tprint(\"Overall Profits: \"+str(round(sum(self.profits_list), 2)))\n\t\t\tprint(\"Least Profitable Trade: \"+str(round(min(self.profits_list), 2)))\n\t\t\tprint(\"Most Profitable Trade: \"+str(round(max(self.profits_list), 2)))\n\t\t\tprint(\"With an initial balance of \"+str(self.complete_starting_balance)+\\\n\t\t\t\" and a final balance of \"+str(round(self.complete_resulting_balance, 2)))\n\t\t\tprint(\"The profitability is \"+str(round(profitability, 2))+\"%\")","sub_path":"trading/Part 5/Final Version/StrategyEvaluator.py","file_name":"StrategyEvaluator.py","file_ext":"py","file_size_in_byte":4677,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"390222854","text":"# ======================\n# -*- coding: utf-8 -*-\n# @author:LiZhuo\n# @time :2020/10/13 9:42\n# @email :358840393@qq.com\n# 今天的你要比昨天的你更优秀!\n# ======================\nimport unittest\nimport sys\nsys.path.append(\"..\")\nfrom scripts.handle_log import HandleLogger\nfrom scripts.handle_request import do_request \nfrom scripts.handle_excel import HandleExcel\nfrom libs.ddt import ddt,data\nfrom scripts.handle_config import do_config,HandleConfig\nfrom scripts.constants import TEST_CONFIG_PATH,TESTCASE_PAHT\nget_log = HandleLogger().get_logger()\ncases = HandleExcel(TESTCASE_PAHT,\"login\").get_cases()\n@ddt\nclass TestLogin(unittest.TestCase):\n\n @classmethod\n def setUpClass(cls) -> None:\n get_log.info(\"{:=^40s}\".format(\"开始执行login接口测试用例\"))\n\n @classmethod\n def tearDownClass(cls) -> None:\n get_log.info(\"{:=^40s}\".format(\"login接口测试用例执行结束\"))\n\n @data(*cases)\n def test_login(self,case):\n url = do_config.get_value(\"url\",\"aiot\") + case[\"url\"]\n data = case[\"data\"]\n res = do_request.to_request(url,data=data)\n except_result = case[\"except\"]\n real_result = res.json()[\"msg\"]\n ms = case[\"title\"]\n try:\n self.assertIn(except_result,real_result,msg=ms)\n get_log.info(\"{}执行通过\".format(ms))\n if res.json()[\"data\"]:\n datas = {\"info\":{\"Authorization\":res.json()[\"data\"]}}\n HandleConfig(TEST_CONFIG_PATH).write_config(datas,TEST_CONFIG_PATH)\n except Exception as e :\n get_log.error(\"{}执行失败\".format(ms))\n raise e\nif __name__ == '__main__':\n unittest.main()\n","sub_path":"cases/test_01_login.py","file_name":"test_01_login.py","file_ext":"py","file_size_in_byte":1686,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"196410173","text":"import os, discord, random\nfrom discord.ext import commands\nfrom dotenv import load_dotenv\n\n# Retrieve token using dotenv\nload_dotenv()\nTOKEN = os.getenv(\"BOT_TOKEN\")\n\n# Initialization of client\nintent = discord.Intents(messages = True, reactions = True,\\\n guilds = True, members = True, presences = True)\nclient = commands.Bot(command_prefix='!', intents=intent)\n\n@client.event\nasync def on_ready():\n print(f\"{client.user.name} has connected to Discord\")\n\n@client.event\nasync def on_member_join(member):\n guild = client.guilds[0]\n channel = discord.utils.get(guild.channels, name = \"bottest\")\n await channel.send(f\"{member.name} ч гэнэ үү, {guild.name}-д тавтай морилно уу?\\nХужаа л биш бол яахав\")\n\n@client.command(help=\"Creates an instant-invite link\")\nasync def invite(ctx):\n link = await ctx.channel.create_invite(max_age = 0)\n await ctx.send(f\"Here is an instant-invite link: {link}\")\n\n@client.command(help=\"Kicks a member from the guild\")\nasync def kick(ctx, member: discord.Member, *, reason):\n await member.send(f\"You have been kicked for: {reason}\")\n await member.kick(reason = reason)\n\n@client.command(help=\"Bans a member from the guild\")\nasync def ban(ctx, member: discord.Member):\n await member.send(f\"You have been banned for: {reason}\")\n await member.ban()\n\n@client.command(help=\"Unbans a user from the guild\")\nasync def unban(ctx, name, *, reason):\n guild = client.guilds[0]\n bans = await guild.bans()\n user = None\n for tuuple in bans:\n if tuuple[1].name == name:\n user = tuuple[1]\n await guild.unban(user)\n return\n\n@client.command(help=\"Sends a direct message to a member\")\nasync def dm(ctx, member:discord.Member, *, msg:str):\n await member.send(msg)\n\nclient.run(TOKEN)\n","sub_path":"bot.py","file_name":"bot.py","file_ext":"py","file_size_in_byte":1809,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"629348523","text":"import os\nimport skimage\nfrom skimage import data, io, filters\nimport tensorflow as tf\n\ndef load_data(data_dir):\n # Get all subdirectories of data_dir. Each represents a label.\n directories = [d for d in os.listdir(data_dir) \n if os.path.isdir(os.path.join(data_dir, d))]\n # Loop through the label directories and collect the data in\n # two lists, labels and images.\n labels = []\n images = []\n for d in directories:\n label_dir = os.path.join(data_dir, d)\n file_names = [os.path.join(label_dir, f) for f in os.listdir(label_dir) if f.endswith(\".ppm\")]\n for f in file_names:\n images.append(skimage.data.imread(f))\n labels.append(int(d))\n return images, labels\n\nimages, labels = load_data('Training')\n\nfor image in images[:5]:\n print(\"shape: {0}, min: {1}, max: {2}\".format(\n image.shape, image.min(), image.max()))\n\n\ngraph = tf.Graph()\n\n# Create model in the graph.\nwith graph.as_default():\n # Placeholders for inputs and labels.\n images_ph = tf.placeholder(tf.float32, [None, 32, 32, 3])\n labels_ph = tf.placeholder(tf.int32, [None])\n\n # Flatten input from: [None, height, width, channels]\n # To: [None, height * width * channels] == [None, 3072]\n images_flat = tf.contrib.layers.flatten(images_ph)\n\n # Fully connected layer. \n # Generates logits of size [None, 62]\n logits = tf.contrib.layers.fully_connected(images_flat, 62, tf.nn.relu)\n\n # Convert logits to label indexes (int).\n # Shape [None], which is a 1D vector of length == batch_size.\n predicted_labels = tf.argmax(logits, 1)\n\n # Define the loss function. \n # Cross-entropy is a good choice for classification.\n loss = tf.reduce_mean(tf.nn.sparse_softmax_cross_entropy_with_logits(\n logits, labels_ph))\n\n # Create training op.\n train = tf.train.AdamOptimizer(learning_rate=0.001).minimize(loss)\n\n # And, finally, an initialization op to execute before training.\n init = tf.global_variables_initializer()","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2023,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"287363470","text":"from selenium import webdriver\nfrom selenium.common.exceptions import NoSuchElementException\nimport os\nimport time\n\nemail = os.environ[\"lin_email\"]\npw = os.environ[\"lin_pw\"]\nphone = os.environ[\"phone\"]\n\nchrome_driver_path = \"C:\\\\Users\\chane\\OneDrive\\Documents\\Development\\chromedriver.exe\"\ndriver = webdriver.Chrome(executable_path=chrome_driver_path)\n\nlink = \"https://www.linkedin.com/jobs/search/?f_LF=f_AL&keywords=python%20developer\"\ndriver.get(link)\ntime.sleep(2)\n\nsign_in = driver.find_element_by_class_name(\"cta-modal__primary-btn\")\nsign_in.click()\ntime.sleep(2)\n\nemail_entry = driver.find_element_by_id(\"username\")\nemail_entry.send_keys(email)\npw_entry = driver.find_element_by_id(\"password\")\npw_entry.send_keys(pw)\nenter_button = driver.find_element_by_class_name(\"from__button--floating\")\nenter_button.click()\ntime.sleep(3)\n\njobs = driver.find_elements_by_class_name(\"jobs-search-results__list-item\")\n\n# saving jobs automatically\nfor job in jobs:\n job.click()\n time.sleep(2)\n\n try:\n save = driver.find_element_by_class_name(\"jobs-save-button\")\n save.click()\n time.sleep(2)\n\n except NoSuchElementException:\n print(\"already applied\")\n continue\n\ntime.sleep(2)\ndriver.quit()\n\n# # applying to jobs automatically\n# for job in jobs:\n# job.click()\n# time.sleep(1)\n#\n# try:\n# apply = driver.find_element_by_xpath(\"//span[contains(@class, 'artdeco-button__text') and text()='Apply now']\")\n# apply.click()\n# time.sleep(2)\n#\n# phone_num = driver.find_element_by_class_name(\"ember-text-field\")\n# phone_num.send_keys(phone)\n#\n# next = driver.find_element_by_css_selector(\".display-flex button\")\n# next.click()\n# time.sleep(1)\n#\n# progress = driver.find_element_by_class_name(\"t-black--light\")\n#\n# if progress.text == \"50%\":\n# review = driver.find_element_by_xpath(\"//span[contains(@class, 'artdeco-button__text') and text()='Review']\")\n# review.click()\n# time.sleep(1)\n#\n# submit = driver.find_element_by_xpath(\"//span[contains(@class, 'artdeco-button__text') and text()='Submit application']\")\n# submit.click()\n#\n# print(\"job applied\")\n# time.sleep(1)\n# else:\n# cancel = driver.find_element_by_class_name(\"artdeco-modal__dismiss\")\n# cancel.click()\n# time.sleep(1)\n#\n# discard = driver.find_element_by_xpath(\"//span[contains(@class, 'artdeco-button__text') and text()='Discard']\")\n# discard.click()\n#\n# print(\"job skipped\")\n# time.sleep(1)\n#\n# except NoSuchElementException:\n# print(\"already applied\")\n# continue\n#\n# time.sleep(2)\n# driver.quit()\n","sub_path":"Day 49 - LinkedinAutoJobApplier Selenium/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2778,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"566108792","text":"import time, logging\nfrom classifier.assignment import load_data, get_precision_recall_fscore_overall, cross_validation\nfrom sklearn.metrics import precision_recall_fscore_support\nimport numpy as np\nimport xgboost as xgb\n\ndef main():\n logging.basicConfig(filename='resultsXGB.log', filemode='w', level=logging.INFO)\n logging.info('Started')\n ## load data\n\n start_time = time.time()\n logging.info('Loading data')\n X_train, y_train, X_test = load_data()\n list_classes = list(set(y_train))\n list_classes.sort()\n y_train = label_to_index(y_train,list_classes)\n m, n = X_train.shape\n k = 3\n logging.info(\"--- %s seconds ---\" % (time.time() - start_time))\n\n models = []\n eta = [0.7]\n num_round = [120]\n colsample_bytree = [0.5]\n param = [(i, j, k) for i in eta for j in num_round for k in colsample_bytree]\n\n for p in param:\n start_time = time.time()\n logging.info('XGBoost with {} rounds, {} of eta, '\n 'and colsample_bytree {}'.format(p[1], p[0], p[2]))\n print('XGBoost with {} rounds, {} of eta, '\n 'and colsample_bytree {}'.format(p[1], p[0], p[2]))\n results = []\n c_cross = 0\n for training, validation in cross_validation(k, m):\n print('cross validation iteration {}'.format(c_cross))\n y_train_cross = [y_train[y] for y in training]\n y_val_cross = [y_train[y] for y in validation]\n\n xg_train = xgb.DMatrix(X_train[training], label=y_train_cross)\n xg_test = xgb.DMatrix(X_train[validation], label=y_val_cross)\n\n # setup parameters for xgboost\n param = {}\n # use softmax multi-class classification\n param['objective'] = 'multi:softmax'\n # scale weight of positive examples\n param['eta'] = p[0]\n param['max_depth'] = 6\n param['colsample_bytree'] = p[2]\n param['silent'] = 1\n param['nthread'] = 8\n param['num_class'] = 30\n\n watchlist = [(xg_train, 'train'), (xg_test, 'test')]\n num_round = p[1]\n bst = xgb.train(param, xg_train, num_round, watchlist)\n # get prediction\n y_pred = bst.predict(xg_test)\n\n res = precision_recall_fscore_support(y_val_cross, y_pred, average='micro')\n results.append(res)\n c_cross += 1\n\n results = get_precision_recall_fscore_overall(results, k)\n\n logging.info(results)\n logging.info(\"--- %s seconds ---\" % (time.time() - start_time))\n\n logging.info('Finished')\n\ndef label_to_index(labels, list_classes):\n return np.array([list_classes.index(i) for i in labels], dtype='f')\n\n\nif __name__ == \"__main__\":\n main()","sub_path":"classifier/xgboost_exp.py","file_name":"xgboost_exp.py","file_ext":"py","file_size_in_byte":2762,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"88057423","text":"from commands import ValidCommands\r\n\r\nclass Messages:\r\n @staticmethod\r\n def wellcome_message():\r\n print(\"The first valid command to the robot is a PLACE command.\")\r\n print(\"After that, any sequence of commands may be issued, in any order, including another PLACE command.\\n\")\r\n print(\"Valid commands are: {0}, {1}, {2}, {3}, {4}:\".format(ValidCommands.PLACE.name, ValidCommands.MOVE.name, ValidCommands.LEFT.name, ValidCommands.RIGHT.name, ValidCommands.REPORT.name))\r\n print(\" * PLACE will put the toy robot on the table in position X,Y and facing NORTH, SOUTH, EAST or WEST.\")\r\n print(\" * MOVE will move the toy robot one unit forward in the direction it is currently facing.\")\r\n print(\" * LEFT and RIGHT will rotate the robot 90 degrees in the specified direction without changing the position of the robot.\")\r\n print(\" * REPORT will announce the X,Y and orientation of the robot.\\n\")\r\n print(\"A robot that is not on the table can choose to ignore the MOVE, LEFT, RIGHT and REPORT commands.\\n\")\r\n print(\"Example of valid command: PLACE 0,0,NORTH MOVE REPORT\\n\")\r\n \r\n @staticmethod\r\n def get_invalid_message(command, robot_placed):\r\n if ValidCommands.PLACE.name in command:\r\n Messages.incorrect_placement_message()\r\n elif ValidCommands.is_valid_command(command) == False:\r\n Messages.invalid_command_message(command)\r\n elif robot_placed == False:\r\n Messages.robot_not_placed_message()\r\n else:\r\n Messages.unknown_error_message()\r\n\t\r\n @staticmethod\r\n def incorrect_placement_message():\r\n print(\"Sorry the place command is incorrectly formatted or outside the table bounds\")\r\n print(\"A place command looks like [ PLACE 0,0,WEST ]\")\r\n\r\n @staticmethod\r\n def invalid_command_message(command):\r\n print(\"Sorry but [ {0} ] is not a valid command\".format(command))\r\n\r\n @staticmethod\r\n def robot_not_placed_message():\r\n print(\"Sorry but you need to place the robot before you can do that.\")\r\n \r\n @staticmethod\r\n def unknown_error_message():\r\n print(\"Unknown error occurred: maybe incorrect command format!\")\r\n","sub_path":"toy_robot/messages.py","file_name":"messages.py","file_ext":"py","file_size_in_byte":2219,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"318083529","text":"from PyQt4.QtGui import QDialog, QColor, QGraphicsScene, QPen, QTableWidgetItem, QBrush, QImage, QPainter, QFileDialog, QFont\nfrom PyQt4.QtCore import Qt\nfrom GUI.Windows.ui_MetamodelsRes import Ui_MetamodelsRes\nfrom Common.Module import NVP01, NONE, RB01, Module\nfrom Common.System import System\nimport copy, random\n\nclass SimpleSystem:\n def __init__(self, id, mmrel, simrel, rel):\n self.id = id\n self.mmrel = mmrel\n self.simrel = simrel\n self.rel = rel\n\nclass MetamodelsRes(QDialog):\n settings = {\"axis\": QColor(0, 0, 0),\n \"mm\": QColor(255, 0, 0),\n \"sim\": QColor(0, 255, 0),\n \"num_points\": 20}\n\n def __init__(self, best, randomSolutions=False):\n QDialog.__init__(self)\n self.ui = Ui_MetamodelsRes()\n self.ui.setupUi(self)\n self.points_mm = []\n self.points_sim = []\n self.best = best\n self.random = randomSolutions\n self.num = 0\n for m in Module.conf.modules:\n self.num += m.GetConfigsNum()\n self.num -= 3\n self.num = min(self.num, self.settings[\"num_points\"])\n self.GetData()\n for i in range(Module.conf.modNum):\n self.ui.moduleNum.addItem(str(i))\n self.Paint()\n\n def GetData(self):\n self.points_mm = []\n self.points_sim = []\n self.systems = []\n self.simplesystems = []\n self.systems.append(self.best)\n for i in range(self.num):\n mm = []\n sim = []\n s = None\n if not self.random:\n while not s or any(s1 == s for s1 in self.systems):\n s = copy.deepcopy(self.best)\n j = random.randint(0, len(s.modules)-1)\n type = random.choice(Module.conf.modules[j].tools)\n if type == \"none\":\n s.modules[j] = NONE(j)\n elif type == \"nvp01\":\n s.modules[j] = NVP01(j)\n else:\n s.modules[j] = RB01(j)\n else:\n while not s or any(s1 == s for s1 in self.systems):\n s = System()\n s.modules = []\n for j in range(Module.conf.modNum):\n type = random.choice(Module.conf.modules[j].tools)\n if type == \"none\":\n s.modules.append(NONE(j))\n elif type == \"nvp01\":\n s.modules.append(NVP01(j))\n else:\n s.modules.append(RB01(j))\n self.systems.append(s)\n s.Update(use_metamodel=True, add=False)\n for m in s.modules:\n mm.append(m.time)\n mmrel = s.rel * s.penalty\n s.Update(use_metamodel=False, add=False)\n simrel = s.rel * s.penalty\n for m in s.modules:\n sim.append(m.time)\n self.points_mm.append(mm)\n self.points_sim.append(sim)\n self.simplesystems.append(SimpleSystem(\"System_\"+str(i), mmrel, simrel, s.rel))\n\n\n def Paint(self):\n scene = QGraphicsScene()\n scene.setBackgroundBrush(Qt.transparent)\n scene.addLine(5, 5, 5, 213, QPen(self.settings[\"axis\"]))\n scene.addLine(2, 210, 210, 210, QPen(self.settings[\"axis\"]))\n mod_num = int(self.ui.moduleNum.currentText())\n max_sim = max(self.points_sim, key=lambda x: x[mod_num])[mod_num]\n max_mm = max(self.points_mm, key=lambda x: x[mod_num])[mod_num]\n max_time = max(max_mm, max_sim)\n\n for i in range(10):\n scene.addLine(4, 210 - (i + 1) * 20, 6, 210 - (i + 1) * 20, QPen(self.settings[\"axis\"]))\n font = QFont()\n font.setPointSize(6)\n if int(0.1*max_time*(i + 1)) != 0:\n t2 = scene.addText(str(int(0.1*max_time*(i + 1))), font)\n t2.setPos(-18, 200 - (i + 1) * 20)\n\n i = 1\n x0 = 5 + 200 / self.num\n y0 = 210 - float(self.points_mm[0][mod_num]) / max_time * 200\n for p in self.points_mm:\n x = 5 + i * 200 / self.num\n y = 210 - float(p[mod_num])/max_time * 200\n scene.addLine(x0, y0, x, y, QPen(self.settings[\"mm\"]))\n scene.addLine(x - 2, y - 2, x + 2, y + 2, QPen(self.settings[\"mm\"]))\n scene.addLine(x + 2, y - 2, x - 2, y + 2, QPen(self.settings[\"mm\"]))\n x0 = x\n y0 = y\n i += 1\n i = 1\n x0 = 5 + 200 / self.num\n y0 = 210 - float(self.points_sim[0][mod_num]) / max_time * 200\n for p in self.points_sim:\n x = 5 + i * 200 / self.num\n y = 210 - float(p[mod_num])/max_time * 200\n scene.addLine(x0, y0, x, y, QPen(self.settings[\"sim\"]))\n scene.addLine(x - 2, y - 2, x + 2, y + 2, QPen(self.settings[\"sim\"]))\n scene.addLine(x + 2, y - 2, x - 2, y + 2, QPen(self.settings[\"sim\"]))\n x0 = x\n y0 = y\n i += 1\n self.ui.graph.setScene(scene)\n\n self.ui.table.setRowCount(len(self.simplesystems))\n self.simplesystems.sort(key = lambda x: x.simrel)\n for i in range(len(self.simplesystems)):\n self.ui.table.setItem(i, 0, QTableWidgetItem(self.simplesystems[i].id))\n self.simplesystems.sort(key = lambda x: x.mmrel)\n for i in range(len(self.simplesystems)):\n self.ui.table.setItem(i, 1, QTableWidgetItem(self.simplesystems[i].id))\n if self.ui.table.item(i, 0).text() != self.ui.table.item(i, 1).text():\n self.ui.table.item(i, 0).setForeground(QBrush(QColor(255,0,0)))\n self.ui.table.item(i, 1).setForeground(QBrush(QColor(255,0,0)))\n else:\n self.ui.table.item(i, 0).setForeground(QBrush(QColor(0,255,0)))\n self.ui.table.item(i, 1).setForeground(QBrush(QColor(0,255,0)))\n self.simplesystems.sort(key = lambda x: x.rel)\n for i in range(len(self.simplesystems)):\n self.ui.table.setItem(i, 2, QTableWidgetItem(self.simplesystems[i].id))\n\n def Replot(self, i):\n self.Paint()\n\n def Save(self):\n fileName = unicode(QFileDialog.getSaveFileName(directory=\"graph.png\", filter=\"*.png\"))\n if fileName == '':\n return\n scene = self.ui.graph.scene()\n scene.clearSelection()\n scene.setSceneRect(scene.itemsBoundingRect())\n scene.setBackgroundBrush(QBrush(QColor(255,255,255)))\n img = QImage(scene.sceneRect().size().toSize(), QImage.Format_ARGB32)\n img.fill(Qt.transparent)\n ptr = QPainter(img)\n self.ui.graph.scene().render(ptr)\n ptr.end()\n img.save(fileName)\n self.Paint()","sub_path":"GUI/MetamodelsRes.py","file_name":"MetamodelsRes.py","file_ext":"py","file_size_in_byte":6789,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"57106472","text":"#!/usr/bin/env python\n##\n## See COPYING file distributed along with the ncanda-data-integration package\n## for the copyright and license terms\n##\n\"\"\"\nBaseline cases\n==============\nThis script generates a list of all subject that have a valid baseline.\n\nUsage:\npython baseline_cases.py\n\"\"\"\nfrom __future__ import print_function\nimport os\n\nimport pandas\nimport redcap\n\ndef get_project(args):\n # First REDCap connection for the Summary project (this is where we put data)\n summary_key_file = open(os.path.join( os.path.expanduser(\"~\"), '.server_config/redcap-dataentry-token' ), 'r')\n summary_api_key = summary_key_file.read().strip()\n rc_summary = redcap.Project('https://ncanda.sri.com/redcap/api/', summary_api_key, verify_ssl=False)\n\n # Get all np reports for baseline and 1r\n visit = rc_summary.export_records(fields=['study_id', 'exclude',\n 'visit_ignore___yes'],\n forms=['mr_session_report','visit_date'],\n events=['baseline_visit_arm_1'],\n format='df')\n return visit\n\ndef np_filter_dataframe(dataframe):\n # Create filters for cases that are included\n case_included = dataframe.exclude != 1 # subject excluded from NCANDA Study\n visit_included = dataframe.visit_ignore___yes != 1 # subject did not have a valid visit for this event\n\n # Apply filters for results\n included = dataframe[case_included]\n results = included[visit_included]\n return results\n\ndef main(args):\n if args.verbose:\n print(\"Connecting to REDCap...\")\n project = get_project(args)\n if args.verbose:\n print(\"Filtering dataframe...\")\n if args.subjectlist:\n with open(args.subjectlist, 'r') as f:\n subject_list = [line.strip() for line in f]\n project = project[project['mri_xnat_sid'].isin(subject_list)]\n results = np_filter_dataframe(project)\n if args.verbose:\n print(\"Writing results to {}...\".format(args.outfile))\n # Write out results\n results.to_csv(os.path.join(args.csvdir, args.outfile), columns = ['exclude',\n 'visit_ignore___yes', 'mri_xnat_sid','mri_xnat_eids'])\n\nif __name__ == '__main__':\n import argparse\n\n formatter = argparse.RawDescriptionHelpFormatter\n default = 'default: %(default)s'\n parser = argparse.ArgumentParser(prog=\"baseline_cases.py\",\n description=__doc__,\n formatter_class=formatter)\n parser.add_argument('-c', '--csvdir', action=\"store\", default = '',\n help=\"Directory where CSV will be stored.\")\n parser.add_argument('-o', '--outfile', dest=\"outfile\",\n help=\"File to write out. {}\".format(default),\n default='baseline_1yr_cases.csv')\n parser.add_argument('-v', '--verbose', dest=\"verbose\",\n help=\"Turn on verbose\", action='store_true')\n argv = parser.parse_args()\n sys.exit(main(args=argv))\n","sub_path":"scripts/reporting/baseline_cases.py","file_name":"baseline_cases.py","file_ext":"py","file_size_in_byte":3078,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"321949921","text":"#!/usr/bin/env python\n# coding: utf-8\n\n# In[1]:\n\n\nimport sys\nimport os\nsys.path.append('C:\\\\Users\\\\luoyan011\\\\Desktop\\\\PersonalLearning\\\\GitHub\\\\python_functions\\\\jl_nlp_pkg')\nsys.path.append('C:\\\\Users\\\\luoyan011\\\\Desktop\\\\PersonalLearning\\\\GitHub\\\\python_functions\\\\jl_model_explain_pkg')\nimport nlpbasic.textClean as textClean\nimport nlpbasic.docVectors as DocVector\nimport nlpbasic.dataExploration as DataExploration\nimport nlpbasic.lda as lda\nimport nlpbasic.tfidf as tfidf\nimport nlpbasic.text_summarize as txtsmr\nimport nlpbasic.word_embedding as wdembd\nfrom numpy import array,asarray,zeros\nimport model_explain.plot as meplot\nimport model_explain.shap as meshap\nimport data_visualization.distribution_plot as dbplot\nfrom sklearn.model_selection import train_test_split\n\nfrom tensorflow.keras.preprocessing.text import Tokenizer\nfrom tensorflow.keras.preprocessing.sequence import pad_sequences\nfrom tensorflow.keras.models import Sequential\nfrom tensorflow.keras.layers import Dense,Flatten,Embedding,LSTM\n\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport seaborn as sb\nimport numpy as np\nimport re\nimport seaborn as sns\ndatapath = 'C:\\\\Users\\\\luoyan011\\\\Desktop\\\\PersonalLearning\\\\GitHub\\\\NLP_data'\n\n\n# In[2]:\n\n\ndata = pd.read_csv(os.path.join(datapath,'ner_dataset.csv'), encoding= 'unicode_escape')\ndata.columns = ['sentence', 'word', 'pos', 'tag']\ndata.ffill(inplace=True)\ndata.head()\n\n\n# In[3]:\n\n\nclass SentenceGetter(object):\n \n def __init__(self, dataset):\n self.n_sent = 1\n self.dataset = dataset\n self.empty = False\n agg_func = lambda s: [(w, t) for w,t in zip(s[\"word\"].values.tolist(),\n s[\"tag\"].values.tolist())]\n self.grouped = self.dataset.groupby(\"sentence\").apply(agg_func)\n self.sentences = [s for s in self.grouped]\n \n def get_next(self):\n try:\n s = self.grouped[\"Sentence: {}\".format(self.n_sent)]\n self.n_sent += 1\n return s\n except:\n return None\ngetter = SentenceGetter(data)\nsentences = getter.sentences\n\n\n# In[23]:\n\n\nword2idx\n\n\n# In[15]:\n\n\nn_tags = 17\nword2idx = {w: i for i, w in enumerate(list(set(data[\"word\"].values)))}\nX = [[w[0] for w in s] for s in sentences]\nX\ntags = list(set(data[\"tag\"].values))\ntag2idx = {t: i for i, t in enumerate(tags)}\ny = [[tag2idx[w[1]] for w in s] for s in sentences]\ny = pad_sequences(maxlen=140, sequences=y, padding=\"post\", value=tag2idx[\"O\"])\nfrom tensorflow.keras.utils import to_categorical\ny = [to_categorical(i, num_classes=n_tags) for i in y]\ny\n\n\n# ## Prepare training/testing/validation dataset\n\n# In[10]:\n\n\nn_words = 30174\nfrom keras.preprocessing.sequence import pad_sequences\nX = [[word2idx[w[0]] for w in s] for s in sentences]\nX = pad_sequences(maxlen=140, sequences=X, padding=\"post\",value=n_words - 1)\ny = [[tag2idx[w[1]] for w in s] for s in sentences]\ny = pad_sequences(maxlen=140, sequences=y, padding=\"post\", value=tag2idx[\"O\"])\nfrom tensorflow.keras.utils import to_categorical\ny = [to_categorical(i, num_classes=n_tags) for i in y]\nX\n\n\n# In[ ]:\n\n\n\n\n\n# In[21]:\n\n\n# X = [x for x in data.word]\n# y = pd.get_dummies(data.tag).values\nX_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.2, random_state = 11)\nX_train, X_val, y_train, y_val = train_test_split(X_train, y_train, test_size = 0.125, random_state = 11)\n# X\n\n\n# In[22]:\n\n\n# load the whole embedding into memory\nembeddings_index = dict()\nembedding_dim = 100 \n# download glove word embedding first and then load it with the following code\nf = open('C:/ProgramData/Anaconda3/append_file/glove/glove.6B.100d.txt', encoding = 'utf8')\nfor line in f:\n values = line.split()\n word = values[0]\n coefs = asarray(values[1:], dtype = 'float32')\n embeddings_index[word] = coefs\nf.close\nprint('loaded %s word vectors.' % len(embeddings_index))\n\nmax_length = 140\n# we also tried max length, but it cause overfitting\n\nt = Tokenizer()\nt.fit_on_texts(X_train)\n# print(\"words with freq:\", t.word_docs)\n\nvocab_size = len(t.word_index) + 1\nencoded_docs = t.texts_to_sequences(X_train)\nprint('Encoding:\\n', encoded_docs[0])\nprint('\\nText:\\n', list(X_train)[0])\nprint('\\nWord Indices:\\n', [(t.index_word[i], i) for i in encoded_docs[0]])\nprint('vocab size:', vocab_size)\ntrain_padded_docs = pad_sequences(encoded_docs, maxlen = max_length, padding = 'post')\n\n# Initialize a matrix with zeros having dimensions equivalent to vocab size and 100\nembedding_matrix = zeros((vocab_size, embedding_dim))\nfor word, idx_word in t.word_index.items():\n word_vector = embeddings_index.get(word)\n if word_vector is not None:\n embedding_matrix[idx_word] = word_vector\nprint('word:', t.index_word[1])\nprint('Embedding:\\n', embedding_matrix[1])\nprint('length of embedding matrix is:', len(embedding_matrix))\nprint('vocabulary size is %s.' % vocab_size)\n\nencoded_val_doc = t.texts_to_sequences(X_val)\npadded_val_doc = pad_sequences(encoded_val_doc, maxlen = max_length, padding = 'post')\nencoded_test_doc = t.texts_to_sequences(X_test)\npadded_test_doc = pad_sequences(encoded_test_doc, maxlen = max_length, padding = 'post')\n\n\n# In[27]:\n\n\nfrom keras.models import Model, Input\nfrom keras.layers import LSTM, Embedding, Dense, TimeDistributed, Dropout, Bidirectional\nn_words = len((list(set(data.word.values))))\nn_tags = 17\ninput = Input(shape=(140,))\nmodel = Embedding(input_dim=n_words, output_dim=140, input_length=140)(input)\nmodel = Dropout(0.1)(model)\nmodel = Bidirectional(LSTM(units=100, return_sequences=True, recurrent_dropout=0.1))(model)\nout = TimeDistributed(Dense(n_tags, activation=\"softmax\"))(model) # softmax output layer\nmodel = Model(input, out)\nmodel.compile(optimizer=\"adam\", loss=\"categorical_crossentropy\", metrics=[\"accuracy\"])\n\n\n# In[28]:\n\n\nhistory = model.fit(train_padded_docs, np.array(y_train), epochs = 1, verbose = 1, batch_size = 32, \n validation_data = (padded_val_doc, np.array(y_val)))\n\n\n# In[30]:\n\n\nlabel_list = list(set(data[\"tag\"].values))\n[label_list[np.argmax(i)] for i in model.predict(padded_test_doc[5])]\n\n\n# In[53]:\n\n\ni = 5\np =[label_list[np.argmax(i)] for i in model.predict(padded_test_doc[i])]\np_real = [label_list[np.argmax(x)] for x in y_test[i]]\nprint(\"{:14}:{:5}:{}\".format(\"Word\", \"True\", \"Pred\"))\nfor w,y, pred in zip(X_test[i],p_real, p):\n print(\"{:14}:{:5}:{}\".format(w, y, pred))\n\n","sub_path":"information_extraction/NER/NER_Bi-LSTM.py","file_name":"NER_Bi-LSTM.py","file_ext":"py","file_size_in_byte":6387,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"261920928","text":"from rest_framework import status\n\nfrom django.urls import reverse\n\nfrom test_helpers.clients import DataTestClient\n\n\nclass AppealApplicationTests(DataTestClient):\n def test_appeal_standard_application(self):\n application = self.create_standard_application_case(self.organisation)\n\n self.assertIsNone(application.appeal)\n\n url = reverse(\n \"applications:appeal\",\n kwargs={\"pk\": application.id},\n )\n response = self.client.post(\n url,\n {\"grounds_for_appeal\": \"These are the grounds for appeal\"},\n **self.exporter_headers,\n )\n\n self.assertEqual(response.status_code, status.HTTP_201_CREATED)\n application.refresh_from_db()\n self.assertIsNotNone(application.appeal)\n self.assertEqual(\n application.appeal.grounds_for_appeal,\n \"These are the grounds for appeal\",\n )\n self.assertEqual(\n response.json(),\n {\n \"id\": str(application.appeal.pk),\n \"grounds_for_appeal\": \"These are the grounds for appeal\",\n },\n )\n\n def test_appeal_invalid_application_pk(self):\n url = reverse(\n \"applications:appeal\",\n kwargs={\"pk\": \"4ec19e01-71ec-40fc-83c1-442c2706868d\"},\n )\n response = self.client.post(\n url,\n {\"grounds_for_appeal\": \"These are the grounds for appeal\"},\n **self.exporter_headers,\n )\n self.assertEqual(response.status_code, 404)\n","sub_path":"api/applications/tests/test_appeal.py","file_name":"test_appeal.py","file_ext":"py","file_size_in_byte":1547,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"148420142","text":"import os\r\nimport csv\r\nimport re\r\nimport sqlite3\r\n\r\nimport sqlalchemy\r\nfrom sqlalchemy import Column, Integer, String, ForeignKey\r\nfrom sqlalchemy.ext.declarative import declarative_base\r\nfrom sqlalchemy.orm import sessionmaker, relationship\r\n\r\nengine = sqlalchemy.create_engine(\"sqlite:///secundaria.db\")\r\nbase = declarative_base()\r\nsession = sessionmaker(bind=engine)()\r\n\r\nfrom config import config\r\n\r\nscript_path = os.path.dirname(os.path.realpath(__file__))\r\n\r\nconfig_path_name = os.path.join(script_path, 'config.ini')\r\ndataset = config('dataset', config_path_name)\r\n\r\nclass Author(base):\r\n __tablename__ = \"autor\"\r\n id = Column(Integer, primary_key=True)\r\n name = Column(String)\r\n \r\n def __repr__(self):\r\n return f\"Author: {self.name}\"\r\n\r\n\r\nclass Book(base):\r\n __tablename__ = \"libro\"\r\n id = Column(Integer, primary_key=True)\r\n title = Column(String)\r\n pags = Column(Integer)\r\n author_id = Column(Integer, ForeignKey(\"autor.id\"))\r\n autor = relationship(\"Author\")\r\n\r\n def __repr__(self):\r\n return f\"Book: {self.title}, title {self.title}, pags {self.pags}, autor {self.autor.name}\"\r\n\r\n\r\ndef create_schema():\r\n # Borrar todos las tablas existentes en la base de datos\r\n # Esta linea puede comentarse sino se eliminar los datos\r\n base.metadata.drop_all(engine)\r\n\r\n # Crear las tablas\r\n base.metadata.create_all(engine)\r\n\r\ndef add_autor(autor):\r\n\r\n Session = sessionmaker(bind=engine)\r\n session = Session()\r\n\r\n data = Author(name=autor)\r\n session.add(data)\r\n session.commit()\r\n\r\ndef add_data(title, pags, author):\r\n Session = sessionmaker(bind=engine)\r\n session = Session()\r\n\r\n query = session.query(Author).filter(Author.name == author)\r\n add = query.first()\r\n\r\n if add is None:\r\n print(f\"el libro {title} no existe con este autor: {author}\")\r\n return\r\n\r\n book = Book(title=title, pags=pags, autor=author)\r\n book.autor = add\r\n session.add(book)\r\n session.commit()\r\n\r\ndef fill():\r\n\r\n with open(dataset['author']) as fi:\r\n data = list(csv.DictReader(fi))\r\n\r\n for row in data:\r\n add_autor(row['autor'])\r\n\r\n\r\n with open(dataset['book']) as fi:\r\n data = list(csv.DictReader(fi))\r\n\r\n for row in data:\r\n add_data(row['titulo'], int(row['cantidad_paginas']), row['autor'])\r\n\r\ndef fetch(id):\r\n \r\n Session = sessionmaker(bind=engine)\r\n session = Session()\r\n\r\n if id == 0:\r\n query = session.query(Book).order_by(Book.title.desc())\r\n\r\n for data in query:\r\n print(data)\r\n\r\n else:\r\n book_filter = session.query(Book).filter(Book.id == id)\r\n\r\n for data in book_filter:\r\n print(\"Libro filtrado:\", data)\r\n\r\ndef search_author(valor):\r\n\r\n Session = sessionmaker(bind=engine)\r\n session = Session()\r\n\r\n autor_filter = session.query(Book).join(Book.autor).filter(Book.title == valor)\r\n\r\n for data in autor_filter:\r\n autor = data.autor\r\n return autor\r\n\r\nif __name__ == \"__main__\":\r\n # Crear DB\r\n create_schema()\r\n\r\n # Completar la DB con el CSV\r\n fill()\r\n\r\n # Leer filas\r\n fetch(1) # Ver todo el contenido de la DB\r\n fetch(3) # Ver la fila 3\r\n #fetch(20) # Ver la fila 20\r\n\r\n # Buscar autor\r\n print(search_author('Relato de un naufrago'))","sub_path":"ejercicio_profundizacion.py","file_name":"ejercicio_profundizacion.py","file_ext":"py","file_size_in_byte":3295,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"546635960","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed May 19 11:18:16 2021\n\n@author: briglia\n\"\"\"\nimport socket, time, random\nfrom datetime import datetime\n\nnanoseconds = lambda: int(time.time()*1000000)\n\nclient2 = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)\nclient2_ip = \"192,168.1.16\"\nclient2_mac = \"10:AF:CB:EF:19:CF\"\ntemp = 0\nhum = 2\ntimer = 24*60*60 #24 ore\nrouter_ip = '192.168.1.20'\nrouter_mac = '05:10:0A:CB:24:EF'\nrouter_address = ('localhost', 5200)\n\nIP_header = '' + client2_ip + router_ip\nethernet_header = '' + client2_mac + router_mac\n\nwhile True:\n \n print ('smart meter 2 is sending message...')\n now = datetime.now()\n now = now.strftime(\"%H:%M:%S\")\n temp = temp + random.randint(-1,1)\n hum = hum + random.randint(-1,1)\n if hum < 0:\n hum = 0\n message = '{:020d} - {} - {}C - {}%'.format(nanoseconds(), now, temp, hum)\n\n packet = ethernet_header + IP_header + message\n sent = client2.sendto(packet.encode('utf-8'), router_address)\n print ('sent {} bytes to gateway at IP address {}'.format(sent, router_ip))\n time.sleep(timer)\n","sub_path":"client2.py","file_name":"client2.py","file_ext":"py","file_size_in_byte":1100,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"217137253","text":"import pandas as pd\nfrom sklearn.model_selection import GridSearchCV\nfrom sklearn.ensemble import RandomForestClassifier\nfrom sklearn.preprocessing import OneHotEncoder\nfrom sklearn.metrics import cohen_kappa_score\nimport numpy as np\n\n\ndef scoring(m, X, y):\n return cohen_kappa_score(y, m.predict(X), list(range(1, 6)), 'quadratic')\n\n\ndef run(tr, ts):\n usecols = ['id']\n\n Xtr = tr.as_matrix(usecols)\n ytr = tr.as_matrix(['y'])[:, 0].astype(int)\n Xts = ts.as_matrix(usecols)\n\n enc = OneHotEncoder(handle_unknown='ignore')\n Xtr = enc.fit_transform(Xtr)\n Xts = enc.transform(Xts)\n\n clf = GridSearchCV(\n RandomForestClassifier(100), {\n 'class_weight': ['balanced'],\n 'max_depth': (10.**np.arange(1, 4).astype(int)),\n },\n scoring, n_jobs=-1, return_train_score=False)\n clf.fit(Xtr, ytr)\n print(pd.DataFrame(clf.cv_results_))\n\n yptr = clf.predict(Xtr)\n ypts = clf.predict(Xts)\n return pd.DataFrame({'idy': yptr}), pd.DataFrame({'idy': ypts})\n","sub_path":"src/step1/taxiid_pred.py","file_name":"taxiid_pred.py","file_ext":"py","file_size_in_byte":1021,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"166327378","text":"# Copyright 2018 Carsten Blank\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.\nr\"\"\"\nFlipFlopQuantumRam\n====================\n\n.. currentmodule:: dc_qiskit_algorithms.FlipFlopQuantumRam\n\nThis module implements the state preparation scheme called FFQRAM see https://arxiv.org/abs/1901.02362.\n\n.. autosummary::\n :nosignatures:\n\n FFQramEntry\n FFQramDb\n add_vector\n\nEach DB has entries that are created by controlled rotations. The final step is a measurement to cancel out\nthe wrong branch. This makes the algorithm probabilistic in its nature.\n\nFFQramEntry\n#############\n\n.. autoclass:: FFQramEntry\n\nFFQramDb\n##########\n\n.. autoclass:: FFQramEntry\n\n\nadd_vector\n###########\n\n-- autofunction:: add_vector\n\n\"\"\"\n\nimport math\nfrom typing import List, Union\n\nfrom bitarray import bitarray\nfrom qiskit import QuantumRegister, QuantumCircuit\nfrom qiskit.circuit import Qubit\nfrom qiskit.extensions.standard.x import x\n\nfrom .UniformRotation import cnry\n\n\nclass FFQramEntry(object):\n \"\"\"\n An DB entry of the FF QRAM scheme\n \"\"\"\n\n def __init__(self):\n \"\"\"\n Creates an entry with binary data & label as well as an (optional) amplitude\n \"\"\"\n self.probability_amplitude = 0.0 # type: float\n self.data = bytes() # type: bytes\n self.label = bytes() # type: bytes\n\n def get_bits(self):\n # type: (FFQramEntry) -> bitarray\n \"\"\"\n Get the binary bit representation of data and label\n for state basis identification\n\n :return: a bit array\n \"\"\"\n b = self.data + self.label\n ba = bitarray()\n ba.frombytes(b)\n ba = bitarray(ba.to01().lstrip('0'))\n ba.reverse()\n return ba\n\n def bus_size(self):\n # type: (FFQramEntry) -> int\n \"\"\"\n Returns needed bus size for this entry\n\n :return: the length\n \"\"\"\n return self.get_bits().length()\n\n def add_to_circuit(self, qc, bus, register):\n # type: (FFQramEntry, QuantumCircuit, Union[QuantumRegister, list], Qubit) -> QuantumCircuit\n \"\"\"\n This method adds the gates to encode this entry into the circuit\n :param qc: quantum circuit to apply the entry to\n :param bus: the registers for the bus\n :param register: the target register for the amplitude\n :return: the applied circuit\n \"\"\"\n theta = math.asin(self.probability_amplitude)\n if theta == 0:\n return qc\n bus_register = [] # type: List[Qubit]\n if isinstance(bus, QuantumRegister):\n bus_register = list(bus)\n else:\n bus_register = bus\n\n ba = self.get_bits()\n for i in range(len(bus_register) - ba.length()):\n ba.append(False)\n\n for i, b in enumerate(ba):\n if not b: x(qc, bus_register[i])\n\n cnry(qc, theta, bus_register, register)\n\n for i, b in enumerate(ba):\n if not b: x(qc, bus_register[i])\n\n return qc\n\n def __str__(self):\n return \"FFQramEntry(%.8f, %s)\" % (self.probability_amplitude, self.get_bits().to01())\n\n @staticmethod\n def _count_set_bits(b):\n # type: (bytes) -> int\n \"\"\"\n Returns the number of ones in the byte array\n :param b: the data\n :return: the count\n \"\"\"\n ba = bitarray()\n ba.frombytes(b)\n return ba.count()\n\n\nclass FFQramDb(List[FFQramEntry]):\n \"\"\"\n The DB object with methods to create circuits\n \"\"\"\n\n def bus_size(self):\n # type: (FFQramDb) -> int\n \"\"\"\n From all entries get the maximum needed bus size\n\n :return: the bus size for the DB\n \"\"\"\n return max([e.bus_size() for e in self])\n\n def add_to_circuit(self, qc, bus, register):\n # type: (FFQramDb, QuantumCircuit, Union[QuantumRegister, List[Qubit]], Qubit) -> None\n \"\"\"\n Add the DB to the circuit.\n\n :param qc: the quantum circuit\n :param bus: the bus register\n :param register: the target register for the amplitudes\n :return: the circuit after DB being applied\n \"\"\"\n for entry in self:\n entry.add_to_circuit(qc, bus, register)\n\n def add_entry(self, pa, data, label):\n # type: (FFQramDb, float, bytes, bytes) -> None\n \"\"\"\n Add an entry to the (classical representation of) the DB.\n\n :param pa: probability amplitude\n :param data: binary representation of data\n :param label: binary representation of the label\n \"\"\"\n entry = FFQramEntry()\n entry.probability_amplitude = pa\n entry.data = data\n entry.label = label\n self.append(entry)\n\n def add_entry_int(self, pa, data, label):\n # type: (FFQramDb, float, int, int) -> None\n \"\"\"\n Add an entry to the (classical representation of) the DB.\n\n :param pa: probability amplitude\n :param data: the integer value of the data\n :param label: the integer value of the label\n \"\"\"\n data_bits = [d == '1' for d in \"{0:b}\".format(data)]\n label_bits = [d == '1' for d in \"{0:b}\".format(label)]\n data_bits.reverse()\n label_bits.reverse()\n data_bytes = bitarray(data_bits, endian='little').tobytes()\n label_bytes = bitarray(label_bits, endian='little').tobytes()\n self.add_entry(pa, data_bytes, label_bytes)\n\n\ndef add_vector(db, vec):\n # type: (FFQramDb, List[complex]) -> None\n \"\"\"\n Add a vector to the DB. It makes sense to give an empty DB.\n\n :param db: The FFQRAM DB\n :param vec: the vector to be added\n \"\"\"\n import numpy as np\n vector = np.asarray(vec)\n l2_norm = np.linalg.norm(vector)\n unit_vector = vector / l2_norm\n for i, v in enumerate(unit_vector):\n db.add_entry_int(v, 0, i)\n","sub_path":"dc_qiskit_algorithms/FlipFlopQuantumRam.py","file_name":"FlipFlopQuantumRam.py","file_ext":"py","file_size_in_byte":6294,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"146645383","text":"# CMPT 145: Linear ADTs\n# Bracket Matching Algorithm\n\n# An application of the Stack ADT\n# and the Queue ADT\n\n\nimport Queue as Queue\nimport Stack as Stack\n\nexample = '()(()'\n\n# create the initial empty data structures\nchars = Queue.create()\nbrackets = Stack.create()\nunmatched_close = False\n\n\n# put all the characters in the Queue\nfor c in example:\n Queue.enqueue(chars, c)\n\n\n# brackets match iff every '(' has a corresponding ')'\nwhile not Queue.is_empty(chars) and not unmatched_close:\n c = Queue.dequeue(chars)\n if c == '(':\n Stack.push(brackets,c)\n elif c == ')' and not Stack.is_empty(brackets):\n Stack.pop(brackets)\n elif c == ')' and Stack.is_empty(brackets):\n unmatched_close = True\n else:\n pass\n\n\n# check how the analysis turned out\nif unmatched_close:\n print(\"Brackets did not match! Found a ')' with no matching '('\")\nelif not Queue.is_empty(brackets):\n print(\"Brackets did not match! At least one '(' without a matching ')'\")\nelse:\n print('Brackets matched')\n\n","sub_path":"examples/ch06/Brackets.py","file_name":"Brackets.py","file_ext":"py","file_size_in_byte":1031,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"581872253","text":"import os\n\nimport pandas as pd\nfrom pylab import rcParams\nimport seaborn as sns\nimport matplotlib.pyplot as plt\n\nimport pyspark\nimport pyspark.sql.functions as sf\nfrom pyspark.ml.evaluation import RegressionEvaluator\nfrom pyspark.ml.recommendation import ALS\n\n\nplt.style.use('ggplot')\nrcParams['figure.figsize'] = (10, 6)\n\nDATA_DIR = '../data'\nMASTER = 'local[2]'\n\nspark = (\n pyspark.sql.SparkSession.builder\n .master(MASTER)\n .getOrCreate()\n)\n\n# Load and pre-process the ratings dataset.\nratings = spark.read.csv(os.path.join(DATA_DIR, \"sample_movielens_ratings.txt\"))\n\nratings = (\n ratings\n .withColumn(\"_tmp\", sf.split(sf.col(\"_c0\"), \"::\"))\n .withColumn(\"userId\", sf.col(\"_tmp\")[0].cast(\"int\"))\n .withColumn(\"movieId\", sf.col(\"_tmp\")[1].cast(\"int\"))\n .withColumn(\"rating\", sf.col(\"_tmp\")[2].cast(\"float\"))\n .withColumn(\"timestamp\", sf.col(\"_tmp\")[3].cast(\"int\").cast(\"timestamp\"))\n .drop(\"_c0\", \"_tmp\")\n)\n\n# Split into train/test set.\n(training, test) = ratings.randomSplit([0.8, 0.2])\n\n# Fit model.\nals = ALS(\n rank=10,\n maxIter=5,\n regParam=0.01,\n userCol=\"userId\",\n itemCol=\"movieId\",\n ratingCol=\"rating\",\n coldStartStrategy=\"drop\")\n\nmodel = als.fit(training)\n\n# Evaluate the model by computing the RMSE on the test data\npredictions = model.transform(test)\n\nevaluator = RegressionEvaluator(\n metricName=\"rmse\",\n labelCol=\"rating\",\n predictionCol=\"prediction\")\n\nrmse = evaluator.evaluate(predictions)\nprint(\"Root-mean-square error = \" + str(rmse))\n\n# Show user recommendations.\nuser_recs = model.recommendForAllUsers(10)\nuser_recs.show()\n\n# Show movie recommendations.\nmovie_recs = model.recommendForAllItems(10)\nmovie_recs.show()\n\n# Recommend for specific users.\nusers = ratings.select(als.getUserCol()).distinct().limit(3)\nuser_subset_recs = model.recommendForUserSubset(users, 10)\n\nuser_subset_recs.show()\n\n# Visualize item factors.\nitem_factors_df = (\n model.itemFactors\n .select(\"features\")\n .toPandas()[\"features\"]\n .apply(pd.Series).T\n)\n\nsns.clustermap(item_factors_df, figsize=(12, 6))\n\n# Visualize user factors.\nuser_factors_df = (\n model.userFactors\n .select(\"features\")\n .toPandas()[\"features\"]\n .apply(pd.Series).T\n)\n\nsns.clustermap(user_factors_df, figsize=(12, 6))\n","sub_path":"shared-vol/accelerator/training/answers/03_movielens.py","file_name":"03_movielens.py","file_ext":"py","file_size_in_byte":2268,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"601675444","text":"from argparse import ArgumentParser\n\nfrom .meta import version\n\n\ndef arguments():\n _args = ArgumentParser(add_help=False)\n\n # -=\\=-\\-=\\=-\\-=\\=-\\-=\\=-\\-=\\=-\\-=\\=-\\-=\\=-\\-=\\=-\\-=\\=-\\-=\\=-\\-=\\=-\\-=\\=-\n general = _args.add_argument_group('General arguments')\n general.add_argument('-m', '--parse-marks', action='store_const',\n help='parse marks/models', default=False, const=True)\n general.add_argument('-g', '--parse-generations', action='store_const',\n help='parse generations', default=False, const=True)\n general.add_argument('-s', '--parse-specifications', action='store_const',\n help='parse specifications', default=False, const=True)\n general.add_argument('-D', '--delay-duration', type=float, metavar='SEC',\n help='delay after every loop, sec', default=5.0)\n general.add_argument('-T', '--page-load-timeout', type=float, metavar='SEC',\n help='webdriver page load timeout', default=None)\n\n general.add_argument('--make-database', action='store_const', const=True,\n help='make database', default=False)\n\n general.add_argument('-a', '--auto', action='store_const', const=True,\n help='auto mode (not worked now)', default=False)\n\n general.add_argument('-f', '--use-firefox', action='store_const', const=True,\n help='use firefox browser instead chrome', default=False)\n\n general.add_argument('-L', '--log-file', type=str, metavar='path', help='log file location')\n\n general.add_argument('--driver-version', type=str, metavar='str', help='web driver version')\n\n # general.add_argument('--clean-db', action='store_const', const=True,\n # help='clean database and exit', default=False)\n\n # -=\\=-\\-=\\=-\\-=\\=-\\-=\\=-\\-=\\=-\\-=\\=-\\-=\\=-\\-=\\=-\\-=\\=-\\-=\\=-\\-=\\=-\\-=\\=-\n\n display = _args.add_argument_group('Display arguments')\n display.add_argument('-S', '--show-browser', action='store_const', const=True,\n help='show web browser', default=False)\n\n display.add_argument('-W', '--display-size-width', type=int, metavar='w',\n help='display size (width)', default=500)\n\n display.add_argument('-H', '--display-size-height', type=int, metavar='h',\n help='display size (height)', default=600)\n\n display.add_argument('--disable-full-screen', action='store_const', const=True, default=False,\n help='run browser in non-FullScreen mode (on the virtual display)')\n\n # -=\\=-\\-=\\=-\\-=\\=-\\-=\\=-\\-=\\=-\\-=\\=-\\-=\\=-\\-=\\=-\\-=\\=-\\-=\\=-\\-=\\=-\\-=\\=-\n\n optionals = _args.add_argument_group('Optional arguments')\n optionals.add_argument('-h', '--help', action='help', help='show help and exit')\n optionals.add_argument('--version', action='version', version=version, help='show version and exit')\n optionals.add_argument('-d', '--debug', action='store_const', const=True,\n help='debug mode', default=False)\n optionals.add_argument('--not-random-sleep', action='store_const', const=True,\n help='disable random sleep', default=False)\n\n optionals.add_argument('-v', action='store_const', const=True,\n help='verbose mode', default=False)\n\n optionals.add_argument('-V', '--vv', action='store_const', const=True,\n help='verbose mode (deeper)', default=False)\n\n # optionals.add_argument('--cookies', type=str, metavar='PATH',\n # help='cookies file location')\n\n optionals.add_argument('-c', '--browser-cookies', type=str, metavar='PATH',\n help='browser cookies file location')\n\n general.add_argument('--not-parse-bodies', action='store_const',\n help='NOT parse specifications', default=False, const=True)\n\n # optionals.add_argument('-A', '--disable-auto-open-captcha-files', action='store_const', const=True,\n # help='browser cookies file location', default=False)\n\n return _args\n","sub_path":"autoru/_cli.py","file_name":"_cli.py","file_ext":"py","file_size_in_byte":4159,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"491039689","text":"import argparse\nimport matplotlib.pyplot as plt\n\nargparser = argparse.ArgumentParser(description=\"Plot Analysis.c Result File\")\nargparser.add_argument('result_file', help=\"the result file\")\n\nargs = argparser.parse_args()\n\nresult_file = args.result_file\n\ncounter = []\n\n\ndef loadResultFile():\n global counter\n fid = open(result_file, 'r')\n lines = fid.readlines()\n fid.close()\n def lineHandler(x): return map(float, x.split(' '))\n counter = map(lineHandler, lines)\n counter = map(list, counter)\n counter = list(counter)\n\n\ndef plotCounter():\n fig, axes = plt.subplots(4, 4, sharex='all', sharey='all')\n y0 = 99999\n y2 = 0\n for i in range(16):\n col = i % 4\n row = int(i / 4)\n axes[row, col].plot(range(256), counter[i], '.')\n axes[row, col].set_title('K'+str(i))\n if y0 > min(counter[i]):\n y0 = min(counter[i])\n if y2 < max(counter[i]):\n y2 = max(counter[i])\n y1 = int((y2 - y0) / 2 + y0)\n plt.setp(axes, xticks=[0, 128, 255], yticks=[y0, y1, y2])\n # plt.show()\n plt.savefig(result_file + '.png')\n\n\nloadResultFile()\n# plt.show()\nplotCounter()\n","sub_path":"plot_analysis.py","file_name":"plot_analysis.py","file_ext":"py","file_size_in_byte":1151,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"379828487","text":"curr = dummy = ListNode(0)\ncarry = 0\nwhile l1 or l2:\n v1 = l1.val if l1 else 0\n v2 = l2.val if l2 else 0\n v3 = v1+v2+carry\n carry = v3//10\n v3 = v3%10\n curr.next = ListNode(v3)\n curr = curr.next\n l1 = l1.next if l1 else None \n l2 = l2.next if l2 else None\nreturn dummy.next\n \n","sub_path":"Leetcode2_Add_2_numbers.py","file_name":"Leetcode2_Add_2_numbers.py","file_ext":"py","file_size_in_byte":314,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"174844152","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Tue Apr 28 11:37:51 2015\n\nsingle emg plot from c3d\n\n@author: Jussi\n\"\"\"\n\nfrom gp.plot import gaitplotter\nimport gp.layouts\n\nplotvars = gp.layouts.std_emg\n\ntrialpath = \"C:/Users/HUS20664877/Desktop/Vicon/vicon_data/test/Verrokki10v_OK/2015_10_12_boy10v_OK/2015_10_12_boy10v_OK09.c3d\"\n\ngplotter = gaitplotter()\ngplotter.open_c3d_trial(trialpath)\ngplotter.read_trial(plotvars)\nmaintitle = 'EMG plot for ' + gplotter.trial.trialname + '\\n' + gplotter.get_emg_filter_description()\ngplotter.plot_trial(maintitle=maintitle)\n \ngplotter.show()\n\n","sub_path":"c3d/c3d_emgplot.py","file_name":"c3d_emgplot.py","file_ext":"py","file_size_in_byte":576,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"306000620","text":"from sklearn.metrics import mean_squared_error\nfrom .models import make_model\nimport numpy as np\nimport math\n\nfrom keras.optimizers import Adam\nfrom skimage import measure\n\nimport scipy.io as sio\n\nfrom keras import backend as K\ndef fine_tuning_loss(y_true,y_pred): #\n return K.mean(K.square(y_true[:,:,:,1]-(y_pred[:,:,:,0]*y_true[:,:,:,1]+y_pred[:,:,:,1])) + 2*y_pred[:,:,:,0]*K.square(y_true[:,:,:,2]) - K.square(y_true[:,:,:,2]))\n\nclass Supervised_test:\n \n def __init__(self, clean_image, noisy_image, noise_sigma):\n \n self.clean_img = np.float32(clean_image)\n self.noisy_img = np.float32(noisy_image)\n self.noise_sigma = noise_sigma\n \n self.img_x = clean_image.shape[0]\n self.img_y = clean_image.shape[1]\n \n return\n\n def get_PSNR(self, X, X_hat):\n \n mse = mean_squared_error(X,X_hat)\n test_PSNR = 10 * math.log10(1/mse)\n \n return test_PSNR\n \n def get_SSIM(self, X, X_hat):\n \n test_SSIM = measure.compare_ssim(X, X_hat, dynamic_range=X.max() - X.min())\n \n return test_SSIM\n \n def preprocessing(self):\n \n self.noisy_img /= 255.\n self.clean_img /= 255.\n \n self.X_data = (self.noisy_img - 0.5) / 0.2\n self.X_data = self.X_data.reshape(1,self.img_x, self.img_y, 1)\n \n def denoising(self):\n \n self.preprocessing()\n self.model = make_model(self.img_x, self.img_y)\n self.model.load_weights('./weights/' + 'blind' +'.hdf5')\n\n returned_score = self.model.predict(self.X_data,batch_size=1, verbose=0)\n returned_score = np.array(returned_score)\n returned_score = returned_score.reshape(1,self.img_x,self.img_y,2)\n\n denoised_test_image = returned_score[0,:,:,0] * (self.noisy_img) + returned_score[0,:,:,1]\n\n ssim = self.get_SSIM(self.clean_img, denoised_test_image)\n psnr = self.get_PSNR(self.clean_img, denoised_test_image)\n\n\n return denoised_test_image, psnr, ssim","sub_path":"core/test_blind_sup.py","file_name":"test_blind_sup.py","file_ext":"py","file_size_in_byte":2036,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"430662968","text":"from nltk import ngrams\nimport random\n\n\ndef get_hash(gram, mask):\n \"\"\"\n the \"random hash function used to get different hash functions for each different permutation\n :param gram: the object to be hashed\n :param mask: the random string (of size 64 bits) used to make every hash function different but consistently so\n :return: the hash value of gram with our specific hash function\n \"\"\"\n return hash(gram) ^ mask\n\n\ndef permutation(df, mask, gram_size):\n \"\"\"\n generate a list of permutations based on the minhash algorithm for each document in the collection df\n :param df: the collection of all documents\n :param mask: a supportvalue used by the hashfunction to change the function each time a new permutation is done\n :param gram_size: size of the shingles\n :return: a list of permutations based on the minhash algorithm for each document in the collection df\n \"\"\"\n result = []\n for index, line in df.iterrows(): # loop over each document in df\n doc_id = line[\"News_ID\"]\n doc = line[\"article\"]\n\n # split our documnet into shingles of size gram_size\n grams = list((ngrams(doc.split(), gram_size)))\n\n # initialize the minimal value infinity so another will always take it's place\n lowest = float(\"inf\")\n\n for g in grams: # for each shingle get the hash and check it to our smallest hash, if it's smaller , replace it\n h = get_hash(g, mask)\n\n if h < lowest:\n lowest = h\n\n # append the minhash for each document to the results\n result.append((doc_id, lowest))\n\n return result\n\n\ndef build_signature_matrix(df, iterations, gram_size, debug=False):\n \"\"\"\n build a signature matrix of all documents in df using a number of different permutations\n :param df:the collection of all documents\n :param iterations:the amount of different permutations we will do\n :param gram_size: size of the shingles\n :param debug:used to make the algorithm do a consistent value instead of random\n :return: the complete signature matrix, which is a list of lists, where each inner list is a different minHash\n permutation for all documents\n \"\"\"\n m = []\n if debug:\n random.seed(1)\n for i in range(iterations): # get iterations amount of permutations\n\n # get the mask used to make each permutation different\n mask = random.getrandbits(64)\n # get a list of the permutation for each document\n res = permutation(df, mask, gram_size)\n m.append(res) # append it to the signature matrix\n\n return m\n","sub_path":"signatureMatrix.py","file_name":"signatureMatrix.py","file_ext":"py","file_size_in_byte":2599,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"541010325","text":"# test_firewall_policies.py\n# This class tests the firewall_policies service class\nimport os\nimport sys\n# Authentication via the test_authorization.py\nfrom tests import test_authorization as Authorization\n# Import our sibling src folder into the path\nsys.path.append(os.path.abspath('src'))\n# flake8: noqa=R0402 # Classes to test - manually imported from sibling folder\nfrom falconpy import firewall_policies as FalconFirewallPolicy\n\nauth = Authorization.TestAuthorization()\ntoken = auth.getConfigExtended()\nfalcon = FalconFirewallPolicy.Firewall_Policies(access_token=token)\nAllowedResponses = [200, 429] # Adding rate-limiting as an allowed response for now\n\n\nclass TestFirewallPolicy:\n\n def serviceFirewall_queryFirewallPolicies(self):\n if falcon.queryFirewallPolicies(parameters={\"limit\": 1})[\"status_code\"] in AllowedResponses:\n return True\n else:\n return False\n\n def serviceFirewall_GenerateErrors(self):\n falcon.base_url = \"nowhere\"\n errorChecks = True\n commandList = [\n [\"queryCombinedFirewallPolicyMembers\", \"\"],\n [\"queryCombinedFirewallPolicies\", \"\"],\n [\"performFirewallPoliciesAction\", \"action_name='enable', body={}, parameters={}\"],\n [\"performFirewallPoliciesAction\", \"body={}, parameters={'action_name':'PooF'}\"],\n [\"performFirewallPoliciesAction\", \"body={}, parameters={}\"],\n [\"setFirewallPoliciesPrecedence\", \"body={}\"],\n [\"getFirewallPolicies\", \"ids='12345678'\"],\n [\"createFirewallPolicies\", \"body={}\"],\n [\"deleteFirewallPolicies\", \"ids='12345678'\"],\n [\"updateFirewallPolicies\", \"body={}\"],\n [\"queryFirewallPolicyMembers\", \"\"],\n [\"queryFirewallPolicies\", \"\"]\n ]\n for cmd in commandList:\n if eval(\"falcon.{}({})['status_code']\".format(cmd[0], cmd[1])) != 500:\n errorChecks = False\n\n return errorChecks\n\n def test_Errors(self):\n assert self.serviceFirewall_GenerateErrors() is True\n","sub_path":"tests/test_firewall_policies.py","file_name":"test_firewall_policies.py","file_ext":"py","file_size_in_byte":2051,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"21517397","text":"from bs4 import BeautifulSoup\nimport urllib.request\nimport os\nfrom datetime import datetime\nimport glob\nfrom threading import Timer\n\nprint ('==============YTS============ started at:' + str(datetime.now().time()))\nsearch = input(\"Search for:\")\nsearch2 = search.replace(\" \",\"+\")\nif input(\"Download?\") == \"y\":\n dlbool = True\nelse:\n dlbool = False\n\nif input(\"Convert to audio?\") == \"y\":\n mp3bool = True\nelse:\n mp3bool = False\n\nmax_dls = input(\"Max Downloads per Page:\")\t#20 is max\npageNo = input(\"Max Pages:\")\nstartTime = input(\"Delay in minutes:\") #delay before scraper starts\n\n#insert current files into array for checking\n#for filenames in os.walk('/home/dragonite/Videos/YTS_files'):\n#\tcurrentfiles.append(filenames)\n#glob???\n#youtube-dl currently checks files in the output directory for duplicates already\n\ndef youtubeScraper():\n\tprint ('==============Scraping started at:' + str(datetime.now().time()))\n\tfor page in range(1,int(pageNo)+1):\n\t\tprint('###########Page ' + str(page) +'#############')\n\t\turl = \"https://www.youtube.com/results?search_query=\" + search2 +\"&page=\" + str(page) +\"&utm_source=opensearch\"\n\t\tprint('url page:' + url)\n\t\tcontent = urllib.request.urlopen(url).read()\n\t\tsoup = BeautifulSoup(content, 'lxml') #lxml is the default HTML parser can check for new ones\n\t\ti =1\t\n\t\tfor link in soup.find_all('a'):\n\t\t\ta = link.get('href')\t\n\t\t\tif (a[:6] == '/watch') and i <= int(max_dls) and link.get('title'):# and os.path.isfile( link.get('title')):\n\t\t\t\tprint ('==============Link ' + str(i) +'============ ' + str(datetime.now().time()))\n\t\t\t\ti +=1\n\t\t\t\tprint (link.get('title'))\n\n\t\t\t\t\n\t\t\t\t#print(link.string)\n\t\t\t\tpage = 'https://www.youtube.com' + a\n\t\t\t\t#title = str(link.string, encoding='utf-8', errors = 'ignore'))\n\t\t\t\t\n\t\t\t\t#check if file already exists in library\n\t\t\t\t#if (dir.findname(link.get('title'))):\n\t\t\t\t#\tnext link\n\n\t\t\t\t#-r 50K download rate in bytes\n\t\t\t\t#-v --verbose -q quiet\n\t\t\t\t#-x extract audio\n\t\t\t\t#--audio-format FORMAT Specify audio format: \"best\", \"aac\", \"vorbis\", \"mp3\", \"m4a\", \"opus\", or \"wav\"; \"best\" by default\n\t\t\t\t#--max-filesize SIZE Do not download any videos larger than SIZE (e.g. 50k or 44.6m)\n\t\t\t\t#--yes-playlist Download the playlist, if the URL refers to a video and a playlist.\n\n\t\t\t\tif mp3bool:\n\t\t\t\t\tcommand = 'youtube-dl -x -q -o \"./%(title)s.%(ext)s\" ' + str(page) \n\t\t\t\telse:\n\t\t\t\t\tcommand = 'youtube-dl -q -o \"./%(title)s.%(ext)s\" ' + str(page) \n\n\t\t\t\t#command = 'youtube-dl -q --yes-playlist ' + str(page)\n\n\t\t\t\tprint(command)\n\t\t\t\t#os.system('cd C:\\Python\\Python35-32\\Lib\\site-packages & ' + command) #for windows\n\t\t\t\tif dlbool:\n\t\t\t\t os.system(command) #for linux\n\tprint('++++++++finished search result: ' + search+ ' ++++++++')\n\treturn\n\n#Incorporate a timer for a certain time or add a delay using startTime\nprint ('It is currently:' + str(datetime.now().time()))\nprint ('waiting ' + str(float(startTime)) + ' minutes' )\nt = Timer(float(startTime)*60,youtubeScraper).start()","sub_path":"superseded/YTS_linuxV1.py","file_name":"YTS_linuxV1.py","file_ext":"py","file_size_in_byte":2940,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"345950425","text":"import numpy as np\nimport tensorflow as tf\nimport math \n\nx = np.array([[1,1],[1,0],[0,1],[0,0]]) #입력값 x\ny = np.array([[1],[0],[0],[0]]) #신경망 OR연산하기\nw = tf.random.normal([2],0,1) # 가중치값\nb = tf.random.normal([1],0,1) #편향값\nb_x = 1 \n\n#시그모이드함수\ndef sigmoid(x):\n return 1 / (1 + math.exp(-x))\nfor i in range(2000):\n error_sum = 0\n #4개의 입력값\n for j in range(4):\n output= sigmoid(np.sum(x[j]*w)+b_x *b)\n error = y[j][0] - output\n w = w + x[j] * 0.1 * error\n b = b + b_x * 0.1 * error\n error_sum += error\n if i % 200 == 199:\n print(i, error, output)\n \nfor i in range(4):\n print('X :',x[i], 'Y(기대값):',y[i], 'output(출력값) : ', sigmoid(np.sum(x[i] * w)+ b))\n","sub_path":"tensorflow_test/신경망연산/신경망_and.py","file_name":"신경망_and.py","file_ext":"py","file_size_in_byte":780,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"270145222","text":"# Copyright 2015 Intel Corporation.\n# All Rights Reserved.\n#\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 time\n\nfrom oslo_config import cfg\nfrom oslo_log import log as logging\nfrom oslo_serialization import jsonutils\nimport yaml\n\nfrom tacker._i18n import _\nfrom tacker.common import log\nfrom tacker.common import utils\nfrom tacker.extensions import vnfm\nfrom tacker.vnfm.infra_drivers import abstract_driver\nfrom tacker.vnfm.infra_drivers.openstack import constants as infra_cnst\nfrom tacker.vnfm.infra_drivers.openstack import heat_client as hc\nfrom tacker.vnfm.infra_drivers.openstack import translate_template\nfrom tacker.vnfm.infra_drivers.openstack import vdu\nfrom tacker.vnfm.infra_drivers import scale_driver\n\n\nLOG = logging.getLogger(__name__)\nCONF = cfg.CONF\n\nOPTS = [\n cfg.IntOpt('stack_retries',\n default=60,\n help=_(\"Number of attempts to retry for stack\"\n \" creation/deletion\")),\n cfg.IntOpt('stack_retry_wait',\n default=10,\n help=_(\"Wait time (in seconds) between consecutive stack\"\n \" create/delete retries\")),\n]\n\nCONF.register_opts(OPTS, group='openstack_vim')\n\n\ndef config_opts():\n return [('openstack_vim', OPTS)]\n\n\n# Global map of individual resource type and\n# incompatible properties, alternate properties pair for\n# upgrade/downgrade across all Heat template versions (starting Kilo)\n#\n# Maintains a dictionary of {\"resource type\": {dict of \"incompatible\n# property\": \"alternate_prop\"}}\n\nHEAT_VERSION_INCOMPATIBILITY_MAP = {'OS::Neutron::Port': {\n 'port_security_enabled': 'value_specs', }, }\n\nHEAT_TEMPLATE_BASE = \"\"\"\nheat_template_version: 2013-05-23\n\"\"\"\n\nOUTPUT_PREFIX = 'mgmt_ip-'\nALARMING_POLICY = 'tosca.policies.tacker.Alarming'\nSCALING_POLICY = 'tosca.policies.tacker.Scaling'\n\n\ndef get_scaling_policy_name(action, policy_name):\n return '%s_scale_%s' % (policy_name, action)\n\n\nclass OpenStack(abstract_driver.VnfAbstractDriver,\n scale_driver.VnfScaleAbstractDriver):\n \"\"\"Openstack infra driver for hosting vnfs\"\"\"\n\n def __init__(self):\n super(OpenStack, self).__init__()\n self.STACK_RETRIES = cfg.CONF.openstack_vim.stack_retries\n self.STACK_RETRY_WAIT = cfg.CONF.openstack_vim.stack_retry_wait\n\n def get_type(self):\n return 'openstack'\n\n def get_name(self):\n return 'openstack'\n\n def get_description(self):\n return 'Openstack infra driver'\n\n @log.log\n def create(self, plugin, context, vnf, auth_attr):\n LOG.debug('vnf %s', vnf)\n\n region_name = vnf.get('placement_attr', {}).get('region_name', None)\n heatclient = hc.HeatClient(auth_attr, region_name)\n\n tth = translate_template.TOSCAToHOT(vnf, heatclient)\n tth.generate_hot()\n stack = self._create_stack(heatclient, tth.vnf, tth.fields)\n return stack['stack']['id']\n\n @log.log\n def _create_stack(self, heatclient, vnf, fields):\n if 'stack_name' not in fields:\n name = vnf['name'].replace(' ', '_') + '_' + vnf['id']\n if vnf['attributes'].get('failure_count'):\n name += ('-RESPAWN-%s') % str(vnf['attributes'][\n 'failure_count'])\n fields['stack_name'] = name\n\n # service context is ignored\n LOG.debug('service_context: %s', vnf.get('service_context', []))\n LOG.debug('fields: %s', fields)\n LOG.debug('template: %s', fields['template'])\n stack = heatclient.create(fields)\n\n return stack\n\n @log.log\n def create_wait(self, plugin, context, vnf_dict, vnf_id, auth_attr):\n region_name = vnf_dict.get('placement_attr', {}).get(\n 'region_name', None)\n heatclient = hc.HeatClient(auth_attr, region_name)\n\n stack = self._wait_until_stack_ready(\n vnf_id, auth_attr, infra_cnst.STACK_CREATE_IN_PROGRESS,\n infra_cnst.STACK_CREATE_COMPLETE,\n vnfm.VNFCreateWaitFailed, region_name=region_name)\n\n # scaling enabled\n if vnf_dict['attributes'].get('scaling_group_names'):\n group_names = jsonutils.loads(\n vnf_dict['attributes'].get('scaling_group_names')).values()\n mgmt_ips = self._find_mgmt_ips_from_groups(heatclient,\n vnf_id,\n group_names)\n else:\n mgmt_ips = self._find_mgmt_ips(stack.outputs)\n\n if mgmt_ips:\n vnf_dict['mgmt_ip_address'] = jsonutils.dump_as_bytes(mgmt_ips)\n\n def _wait_until_stack_ready(self, vnf_id, auth_attr, wait_status,\n expected_status, exception_class,\n region_name=None):\n heatclient = hc.HeatClient(auth_attr, region_name)\n stack_retries = self.STACK_RETRIES\n status = wait_status\n stack = None\n while stack_retries > 0:\n try:\n stack_retries = stack_retries - 1\n stack = heatclient.get(vnf_id)\n status = stack.stack_status\n if status == expected_status:\n LOG.debug('stack status: %(stack)s %(status)s',\n {'stack': str(stack), 'status': status})\n return stack\n time.sleep(self.STACK_RETRY_WAIT)\n LOG.debug('status: %s', status)\n except Exception:\n LOG.warning(\"VNF Instance setup may not have \"\n \"happened because Heat API request failed \"\n \"while waiting for the stack %(stack)s to be \"\n \"created\", {'stack': vnf_id})\n # continue to avoid temporary connection error to target\n # VIM\n if stack_retries == 0 and status != expected_status:\n error_reason = _(\"action is not completed within {wait} \"\n \"seconds on stack {stack}\").format(\n wait=(self.STACK_RETRIES *\n self.STACK_RETRY_WAIT),\n stack=vnf_id)\n raise exception_class(reason=error_reason)\n elif stack_retries != 0 and status != wait_status:\n error_reason = stack.stack_status_reason\n LOG.warning(error_reason)\n raise exception_class(reason=error_reason)\n\n def _find_mgmt_ips(self, outputs):\n LOG.debug('outputs %s', outputs)\n mgmt_ips = dict((output['output_key'][len(OUTPUT_PREFIX):],\n output['output_value'])\n for output in outputs\n if output.get('output_key',\n '').startswith(OUTPUT_PREFIX))\n return mgmt_ips\n\n @log.log\n def update(self, plugin, context, vnf_id, vnf_dict, vnf,\n auth_attr):\n region_name = vnf_dict.get('placement_attr', {}).get(\n 'region_name', None)\n heatclient = hc.HeatClient(auth_attr, region_name)\n heatclient.get(vnf_id)\n\n # update config attribute\n config_yaml = vnf_dict.get('attributes', {}).get('config', '')\n update_yaml = vnf['vnf'].get('attributes', {}).get('config', '')\n LOG.debug('yaml orig %(orig)s update %(update)s',\n {'orig': config_yaml, 'update': update_yaml})\n\n # If config_yaml is None, yaml.safe_load() will raise Attribute Error.\n # So set config_yaml to {}, if it is None.\n if not config_yaml:\n config_dict = {}\n else:\n config_dict = yaml.safe_load(config_yaml) or {}\n update_dict = yaml.safe_load(update_yaml)\n if not update_dict:\n return\n\n LOG.debug('dict orig %(orig)s update %(update)s',\n {'orig': config_dict, 'update': update_dict})\n utils.deep_update(config_dict, update_dict)\n LOG.debug('dict new %(new)s update %(update)s',\n {'new': config_dict, 'update': update_dict})\n new_yaml = yaml.safe_dump(config_dict)\n vnf_dict.setdefault('attributes', {})['config'] = new_yaml\n\n @log.log\n def update_wait(self, plugin, context, vnf_dict, auth_attr,\n region_name=None):\n stack = self._wait_until_stack_ready(vnf_dict['instance_id'],\n auth_attr, infra_cnst.STACK_UPDATE_IN_PROGRESS,\n infra_cnst.STACK_UPDATE_COMPLETE,\n vnfm.VNFUpdateWaitFailed, region_name=region_name)\n\n mgmt_ips = self._find_mgmt_ips(stack.outputs)\n\n if mgmt_ips:\n vnf_dict['mgmt_ip_address'] = jsonutils.dump_as_bytes(mgmt_ips)\n\n @log.log\n def delete(self, plugin, context, vnf_id, auth_attr, region_name=None):\n heatclient = hc.HeatClient(auth_attr, region_name)\n heatclient.delete(vnf_id)\n\n @log.log\n def delete_wait(self, plugin, context, vnf_id, auth_attr,\n region_name=None):\n self._wait_until_stack_ready(vnf_id, auth_attr,\n infra_cnst.STACK_DELETE_IN_PROGRESS,\n infra_cnst.STACK_DELETE_COMPLETE, vnfm.VNFDeleteWaitFailed,\n region_name=region_name)\n\n @classmethod\n def _find_mgmt_ips_from_groups(cls, heat_client, instance_id, group_names):\n\n def _find_mgmt_ips(attributes):\n mgmt_ips = {}\n for k, v in attributes.items():\n if k.startswith(OUTPUT_PREFIX):\n mgmt_ips[k.replace(OUTPUT_PREFIX, '')] = v\n\n return mgmt_ips\n\n mgmt_ips = {}\n for group_name in group_names:\n # Get scale group\n grp = heat_client.resource_get(instance_id, group_name)\n for rsc in heat_client.resource_get_list(grp.physical_resource_id):\n # Get list of resources in scale group\n scale_rsc = heat_client.resource_get(grp.physical_resource_id,\n rsc.resource_name)\n\n # findout the mgmt ips from attributes\n for k, v in _find_mgmt_ips(scale_rsc.attributes).items():\n if k not in mgmt_ips:\n mgmt_ips[k] = [v]\n else:\n mgmt_ips[k].append(v)\n\n return mgmt_ips\n\n @log.log\n def scale(self, context, plugin, auth_attr, policy, region_name):\n heatclient = hc.HeatClient(auth_attr, region_name)\n policy_rsc = get_scaling_policy_name(policy_name=policy['name'],\n action=policy['action'])\n events = heatclient.resource_event_list(policy['instance_id'],\n policy_rsc, limit=1,\n sort_dir='desc',\n sort_keys='event_time')\n\n heatclient.resource_signal(policy['instance_id'], policy_rsc)\n return events[0].id\n\n @log.log\n def scale_wait(self, context, plugin, auth_attr, policy, region_name,\n last_event_id):\n heatclient = hc.HeatClient(auth_attr, region_name)\n\n # TODO(kanagaraj-manickam) make wait logic into separate utility method\n # and make use of it here and other actions like create and delete\n stack_retries = self.STACK_RETRIES\n while (True):\n try:\n time.sleep(self.STACK_RETRY_WAIT)\n stack_id = policy['instance_id']\n policy_name = get_scaling_policy_name(\n policy_name=policy['name'], action=policy['action'])\n events = heatclient.resource_event_list(stack_id, policy_name,\n limit=1,\n sort_dir='desc',\n sort_keys='event_time')\n\n if events[0].id != last_event_id:\n if events[0].resource_status == 'SIGNAL_COMPLETE':\n break\n else:\n # When the number of instance reaches min or max, the below\n # comparision will let VNF status turn into ACTIVE state.\n if events[0].resource_status == 'CREATE_COMPLETE' or \\\n events[0].resource_status == 'SIGNAL_COMPLETE':\n break\n except Exception as e:\n error_reason = _(\"VNF scaling failed for stack %(stack)s with \"\n \"error %(error)s\") % {\n 'stack': policy['instance_id'],\n 'error': str(e)}\n LOG.warning(error_reason)\n raise vnfm.VNFScaleWaitFailed(vnf_id=policy['vnf']['id'],\n reason=error_reason)\n\n if stack_retries == 0:\n metadata = heatclient.resource_metadata(stack_id, policy_name)\n if not metadata['scaling_in_progress']:\n error_reason = _('When signal occurred within cool down '\n 'window, no events generated from heat, '\n 'so ignore it')\n LOG.warning(error_reason)\n break\n error_reason = _(\n \"VNF scaling failed to complete within %(wait)s seconds \"\n \"while waiting for the stack %(stack)s to be \"\n \"scaled.\") % {'stack': stack_id,\n 'wait': self.STACK_RETRIES *\n self.STACK_RETRY_WAIT}\n LOG.warning(error_reason)\n raise vnfm.VNFScaleWaitFailed(vnf_id=policy['vnf']['id'],\n reason=error_reason)\n stack_retries -= 1\n\n def _fill_scaling_group_name():\n vnf = policy['vnf']\n scaling_group_names = vnf['attributes']['scaling_group_names']\n policy['group_name'] = jsonutils.loads(\n scaling_group_names)[policy['name']]\n\n _fill_scaling_group_name()\n\n mgmt_ips = self._find_mgmt_ips_from_groups(heatclient,\n policy['instance_id'],\n [policy['group_name']])\n\n return jsonutils.dump_as_bytes(mgmt_ips)\n\n @log.log\n def get_resource_info(self, plugin, context, vnf_info, auth_attr,\n region_name=None):\n instance_id = vnf_info['instance_id']\n heatclient = hc.HeatClient(auth_attr, region_name)\n try:\n # nested_depth=2 is used to get VDU resources\n # in case of nested template\n resources_ids =\\\n heatclient.resource_get_list(instance_id, nested_depth=2)\n details_dict = {resource.resource_name:\n {\"id\": resource.physical_resource_id,\n \"type\": resource.resource_type}\n for resource in resources_ids}\n return details_dict\n # Raise exception when Heat API service is not available\n except Exception:\n raise vnfm.InfraDriverUnreachable(service=\"Heat API service\")\n\n def heal_vdu(self, plugin, context, vnf_dict, heal_request_data_obj):\n try:\n heal_vdu = vdu.Vdu(context, vnf_dict, heal_request_data_obj)\n heal_vdu.heal_vdu()\n except Exception:\n LOG.error(\"VNF '%s' failed to heal\", vnf_dict['id'])\n raise vnfm.VNFHealFailed(vnf_id=vnf_dict['id'])\n","sub_path":"tacker/vnfm/infra_drivers/openstack/openstack.py","file_name":"openstack.py","file_ext":"py","file_size_in_byte":16257,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"449097457","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Fri May 8 23:42:32 2020\r\n\r\n@author: OGK\r\n\"\"\"\r\n\r\nimport mahotas\r\nimport cv2\r\nimage = cv2.imread(\"manzara.jpg\")\r\ncv2.imshow(\"Original\",image)\r\nimage=cv2.cvtColor(image,cv2.COLOR_BGR2GRAY)\r\n\r\nblurred = cv2.GaussianBlur(image,(5,5),0)\r\ncv2.imshow(\"imshow\",image)\r\n\r\nT=mahotas.thresholding.otsu(blurred)\r\nprint(\"otsu threshold: {}\".format(T))\r\nthresh = image.copy()\r\nthresh[thresh>T]=255\r\nthresh[thresh<255]=0\r\nthresh=cv2.bitwise_not(thresh)\r\ncv2.imshow(\"otsu\",thresh)\r\n\r\nT=mahotas.thresholding.rc(blurred)\r\nprint(\"Riddler-Calvard: {}\",format(T))\r\nthresh=image.copy()\r\nthresh[thresh>T]=255\r\nthresh[thresh<255]=0\r\nthresh=cv2.bitwise_not(thresh)\r\ncv2.imshow(\"Riddler-Calvard\",thresh)\r\ncv2.waitKey(0)","sub_path":"otsudd.py","file_name":"otsudd.py","file_ext":"py","file_size_in_byte":734,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"252618246","text":"import logging\n\nfrom celery import chain\n\nfrom waldur_core.core import executors as core_executors\nfrom waldur_core.core import tasks as core_tasks\nfrom waldur_core.core import utils as core_utils\nfrom waldur_core.structure import executors as structure_executors\nfrom waldur_core.structure import models as structure_models\n\nfrom . import models, tasks\n\nlogger = logging.getLogger(__name__)\n\n\nclass SecurityGroupCreateExecutor(core_executors.CreateExecutor):\n @classmethod\n def get_task_signature(cls, security_group, serialized_security_group, **kwargs):\n return core_tasks.BackendMethodTask().si(\n serialized_security_group,\n 'create_security_group',\n state_transition='begin_creating',\n )\n\n\nclass ServerGroupCreateExecutor(core_executors.CreateExecutor):\n @classmethod\n def get_task_signature(cls, server_group, serialized_server_group, **kwargs):\n return core_tasks.BackendMethodTask().si(\n serialized_server_group,\n 'create_server_group',\n state_transition='begin_creating',\n )\n\n\nclass ServerGroupDeleteExecutor(core_executors.DeleteExecutor):\n @classmethod\n def get_task_signature(cls, server_group, serialized_server_group, **kwargs):\n if server_group.backend_id:\n return core_tasks.BackendMethodTask().si(\n serialized_server_group,\n 'delete_server_group',\n state_transition='begin_deleting',\n )\n else:\n return core_tasks.StateTransitionTask().si(\n serialized_server_group, state_transition='begin_deleting'\n )\n\n\nclass SecurityGroupUpdateExecutor(core_executors.UpdateExecutor):\n @classmethod\n def get_task_signature(cls, security_group, serialized_security_group, **kwargs):\n return core_tasks.BackendMethodTask().si(\n serialized_security_group,\n 'update_security_group',\n state_transition='begin_updating',\n )\n\n\nclass SecurityGroupPullExecutor(core_executors.ActionExecutor):\n @classmethod\n def get_task_signature(cls, security_group, serialized_security_group, **kwargs):\n return core_tasks.BackendMethodTask().si(\n serialized_security_group,\n 'pull_security_group',\n state_transition='begin_updating',\n )\n\n\nclass ServerGroupPullExecutor(core_executors.ActionExecutor):\n @classmethod\n def get_task_signature(cls, server_group, serialized_server_group, **kwargs):\n return core_tasks.BackendMethodTask().si(\n serialized_server_group,\n 'pull_server_group',\n state_transition='begin_updating',\n )\n\n\nclass SecurityGroupDeleteExecutor(core_executors.BaseExecutor):\n \"\"\"\n Security group is being deleted in the last task instead of\n using separate DeleteTask from DeleteExecutorMixin so that\n deletion is performed transactionally.\n \"\"\"\n\n @classmethod\n def pre_apply(cls, instance, **kwargs):\n instance.schedule_deleting()\n instance.save(update_fields=['state'])\n\n @classmethod\n def get_failure_signature(\n cls, instance, serialized_instance, force=False, **kwargs\n ):\n return core_tasks.ErrorStateTransitionTask().s(serialized_instance)\n\n @classmethod\n def get_task_signature(cls, security_group, serialized_security_group, **kwargs):\n state_transition_task = core_tasks.StateTransitionTask().si(\n serialized_security_group, state_transition='begin_deleting'\n )\n detach_task = core_tasks.BackendMethodTask().si(\n serialized_security_group, 'detach_security_group_from_all_instances'\n )\n detach_ports_task = core_tasks.BackendMethodTask().si(\n serialized_security_group, 'detach_security_group_from_all_ports'\n )\n delete_task = core_tasks.BackendMethodTask().si(\n serialized_security_group, 'delete_security_group'\n )\n _tasks = [state_transition_task]\n if security_group.backend_id:\n _tasks.append(detach_task)\n _tasks.append(detach_ports_task)\n _tasks.append(delete_task)\n return chain(*_tasks)\n\n\nclass PushSecurityGroupRulesExecutor(core_executors.ActionExecutor):\n @classmethod\n def get_task_signature(cls, security_group, serialized_security_group, **kwargs):\n return core_tasks.BackendMethodTask().si(\n serialized_security_group,\n 'push_security_group_rules',\n state_transition='begin_updating',\n )\n\n\nclass TenantCreateExecutor(core_executors.CreateExecutor):\n @classmethod\n def get_task_signature(\n cls, tenant, serialized_tenant, pull_security_groups=True, **kwargs\n ):\n \"\"\"Create tenant, add user to it, create internal network, pull quotas\"\"\"\n # we assume that tenant one network and subnet after creation\n network = tenant.networks.first()\n subnet = network.subnets.first()\n serialized_network = core_utils.serialize_instance(network)\n serialized_subnet = core_utils.serialize_instance(subnet)\n creation_tasks = [\n core_tasks.BackendMethodTask().si(\n serialized_tenant,\n 'create_tenant_safe',\n state_transition='begin_creating',\n ),\n core_tasks.BackendMethodTask().si(\n serialized_tenant, 'add_admin_user_to_tenant'\n ),\n core_tasks.BackendMethodTask().si(serialized_tenant, 'create_tenant_user'),\n core_tasks.BackendMethodTask().si(\n serialized_network, 'create_network', state_transition='begin_creating'\n ),\n core_tasks.BackendMethodTask().si(\n serialized_subnet, 'create_subnet', state_transition='begin_creating'\n ),\n ]\n quotas = tenant.quotas.all()\n quotas = {\n q.name: int(q.limit) if q.limit.is_integer() else q.limit for q in quotas\n }\n creation_tasks.append(\n core_tasks.BackendMethodTask().si(\n serialized_tenant, 'push_tenant_quotas', quotas\n )\n )\n # handle security groups\n # XXX: Create default security groups\n for security_group in tenant.security_groups.all():\n creation_tasks.append(\n SecurityGroupCreateExecutor.as_signature(security_group)\n )\n\n if pull_security_groups:\n creation_tasks.append(\n core_tasks.BackendMethodTask().si(\n serialized_tenant, 'pull_tenant_security_groups'\n )\n )\n\n # initialize external network if it defined in service settings\n service_settings = tenant.service_settings\n customer = tenant.project.customer\n external_network_id = service_settings.get_option('external_network_id')\n\n try:\n customer_openstack = models.CustomerOpenStack.objects.get(\n settings=service_settings, customer=customer\n )\n external_network_id = customer_openstack.external_network_id\n except models.CustomerOpenStack.DoesNotExist:\n pass\n\n if external_network_id and not kwargs.get('skip_connection_extnet'):\n creation_tasks.append(\n core_tasks.BackendMethodTask().si(\n serialized_tenant,\n 'connect_tenant_to_external_network',\n external_network_id=external_network_id,\n )\n )\n creation_tasks.append(\n core_tasks.BackendMethodTask().si(\n serialized_tenant,\n backend_method='pull_tenant_routers',\n )\n )\n\n creation_tasks.append(\n core_tasks.BackendMethodTask().si(serialized_tenant, 'pull_tenant_quotas')\n )\n return chain(*creation_tasks)\n\n @classmethod\n def get_success_signature(cls, tenant, serialized_tenant, **kwargs):\n return tasks.TenantCreateSuccessTask().si(serialized_tenant)\n\n @classmethod\n def get_failure_signature(cls, tenant, serialized_tenant, **kwargs):\n return tasks.TenantCreateErrorTask().s(serialized_tenant)\n\n\nclass TenantImportExecutor(core_executors.ActionExecutor):\n @classmethod\n def get_task_signature(cls, tenant, serialized_tenant, **kwargs):\n tasks = [\n core_tasks.BackendMethodTask().si(\n serialized_tenant,\n 'add_admin_user_to_tenant',\n state_transition='begin_updating',\n ),\n core_tasks.BackendMethodTask().si(\n serialized_tenant, 'create_or_update_tenant_user'\n ),\n core_tasks.BackendMethodTask().si(serialized_tenant, 'pull_tenant_quotas'),\n core_tasks.BackendMethodTask().si(\n serialized_tenant, 'pull_tenant_floating_ips'\n ),\n core_tasks.BackendMethodTask().si(\n serialized_tenant, 'pull_tenant_security_groups'\n ),\n core_tasks.BackendMethodTask().si(\n serialized_tenant, 'import_tenant_networks'\n ),\n core_tasks.BackendMethodTask().si(\n serialized_tenant, 'import_tenant_subnets'\n ),\n core_tasks.BackendMethodTask().si(\n serialized_tenant, 'detect_external_network'\n ),\n ]\n\n service_settings = structure_models.ServiceSettings.objects.get(scope=tenant)\n serialized_service_settings = core_utils.serialize_instance(service_settings)\n create_service_settings = (\n structure_executors.ServiceSettingsCreateExecutor.get_task_signature(\n service_settings, serialized_service_settings\n )\n )\n\n return chain(*tasks) | create_service_settings\n\n @classmethod\n def get_success_signature(cls, tenant, serialized_tenant, **kwargs):\n service_settings = structure_models.ServiceSettings.objects.get(scope=tenant)\n serialized_service_settings = core_utils.serialize_instance(service_settings)\n tasks = [\n core_tasks.StateTransitionTask().si(\n serialized_tenant, state_transition='set_ok'\n ),\n core_tasks.StateTransitionTask().si(\n serialized_service_settings, state_transition='set_ok'\n ),\n ]\n\n return chain(*tasks)\n\n\nclass TenantUpdateExecutor(core_executors.UpdateExecutor):\n @classmethod\n def get_task_signature(cls, tenant, serialized_tenant, **kwargs):\n updated_fields = kwargs['updated_fields']\n if 'name' in updated_fields or 'description' in updated_fields:\n return core_tasks.BackendMethodTask().si(\n serialized_tenant, 'update_tenant', state_transition='begin_updating'\n )\n else:\n return core_tasks.StateTransitionTask().si(\n serialized_tenant, state_transition='begin_updating'\n )\n\n\nclass TenantDeleteExecutor(core_executors.DeleteExecutor):\n @classmethod\n def get_task_signature(cls, tenant, serialized_tenant, **kwargs):\n state_transition = core_tasks.StateTransitionTask().si(\n serialized_tenant, state_transition='begin_deleting'\n )\n if not tenant.backend_id:\n return state_transition\n\n cleanup_networks = cls.get_networks_cleanup_tasks(serialized_tenant)\n cleanup_instances = cls.get_instances_cleanup_tasks(serialized_tenant)\n cleanup_identities = cls.get_identity_cleanup_tasks(serialized_tenant)\n\n return chain(\n [state_transition]\n + cleanup_networks\n + cleanup_instances\n + cleanup_identities\n )\n\n @classmethod\n def get_networks_cleanup_tasks(cls, serialized_tenant):\n return [\n core_tasks.BackendMethodTask().si(\n serialized_tenant,\n backend_method='delete_tenant_floating_ips',\n ),\n core_tasks.BackendMethodTask().si(\n serialized_tenant,\n backend_method='delete_tenant_routes',\n ),\n core_tasks.BackendMethodTask().si(\n serialized_tenant,\n backend_method='delete_tenant_ports',\n ),\n core_tasks.BackendMethodTask().si(\n serialized_tenant,\n backend_method='delete_tenant_routers',\n ),\n core_tasks.BackendMethodTask().si(\n serialized_tenant,\n backend_method='pull_tenant_routers',\n ),\n core_tasks.BackendMethodTask().si(\n serialized_tenant,\n backend_method='delete_tenant_networks',\n ),\n ]\n\n @classmethod\n def get_instances_cleanup_tasks(cls, serialized_tenant):\n return [\n core_tasks.BackendMethodTask().si(\n serialized_tenant,\n backend_method='delete_tenant_security_groups',\n ),\n core_tasks.BackendMethodTask().si(\n serialized_tenant,\n backend_method='delete_tenant_snapshots',\n ),\n core_tasks.PollBackendCheckTask().si(\n serialized_tenant,\n backend_check_method='are_all_tenant_snapshots_deleted',\n ),\n core_tasks.BackendMethodTask().si(\n serialized_tenant,\n backend_method='delete_tenant_instances',\n ),\n core_tasks.PollBackendCheckTask().si(\n serialized_tenant,\n backend_check_method='are_all_tenant_instances_deleted',\n ),\n core_tasks.BackendMethodTask().si(\n serialized_tenant,\n backend_method='delete_tenant_volumes',\n ),\n core_tasks.PollBackendCheckTask().si(\n serialized_tenant, backend_check_method='are_all_tenant_volumes_deleted'\n ),\n core_tasks.BackendMethodTask().si(\n serialized_tenant,\n backend_method='delete_tenant_server_groups',\n ),\n ]\n\n @classmethod\n def get_identity_cleanup_tasks(cls, serialized_tenant):\n return [\n core_tasks.BackendMethodTask().si(\n serialized_tenant,\n backend_method='delete_tenant_user',\n ),\n core_tasks.BackendMethodTask().si(\n serialized_tenant,\n backend_method='delete_tenant',\n ),\n ]\n\n\nclass TenantAllocateFloatingIPExecutor(core_executors.ActionExecutor):\n @classmethod\n def get_task_signature(cls, tenant, serialized_tenant, **kwargs):\n return core_tasks.BackendMethodTask().si(\n serialized_tenant,\n 'allocate_floating_ip_address',\n state_transition='begin_updating',\n )\n\n\nclass FloatingIPCreateExecutor(core_executors.CreateExecutor):\n @classmethod\n def get_task_signature(cls, floating_ip, serialized_floating_ip, **kwargs):\n return core_tasks.BackendMethodTask().si(\n serialized_floating_ip,\n 'create_floating_ip',\n state_transition='begin_creating',\n )\n\n\nclass FloatingIPUpdateExecutor(core_executors.UpdateExecutor):\n @classmethod\n def get_task_signature(cls, floating_ip, serialized_floating_ip, **kwargs):\n return core_tasks.BackendMethodTask().si(\n serialized_floating_ip,\n 'update_floating_ip_description',\n state_transition='begin_updating',\n serialized_description=kwargs.get('description'),\n )\n\n\nclass FloatingIPDeleteExecutor(core_executors.DeleteExecutor):\n @classmethod\n def get_task_signature(cls, floating_ip, serialized_floating_ip, **kwargs):\n return core_tasks.BackendMethodTask().si(\n serialized_floating_ip,\n 'delete_floating_ip',\n state_transition='begin_deleting',\n )\n\n\nclass FloatingIPPullExecutor(core_executors.ActionExecutor):\n @classmethod\n def get_task_signature(cls, floating_ip, serialized_floating_ip, **kwargs):\n return core_tasks.BackendMethodTask().si(\n serialized_floating_ip,\n 'pull_floating_ip',\n state_transition='begin_updating',\n )\n\n\nclass FloatingIPAttachExecutor(core_executors.ActionExecutor):\n @classmethod\n def get_task_signature(cls, floating_ip, serialized_floating_ip, **kwargs):\n return core_tasks.BackendMethodTask().si(\n serialized_floating_ip,\n 'attach_floating_ip_to_port',\n state_transition='begin_updating',\n serialized_port=kwargs.get('port'),\n )\n\n\nclass FloatingIPDetachExecutor(core_executors.ActionExecutor):\n @classmethod\n def get_task_signature(cls, floating_ip, serialized_floating_ip, **kwargs):\n return core_tasks.BackendMethodTask().si(\n serialized_floating_ip,\n 'detach_floating_ip_from_port',\n state_transition='begin_updating',\n )\n\n\nclass TenantPullFloatingIPsExecutor(core_executors.ActionExecutor):\n @classmethod\n def get_task_signature(cls, tenant, serialized_tenant, **kwargs):\n return core_tasks.BackendMethodTask().si(\n serialized_tenant,\n 'pull_tenant_floating_ips',\n state_transition='begin_updating',\n )\n\n\nclass TenantPushQuotasExecutor(core_executors.ActionExecutor):\n @classmethod\n def get_task_signature(cls, tenant, serialized_tenant, quotas=None, **kwargs):\n return core_tasks.BackendMethodTask().si(\n serialized_tenant,\n 'push_tenant_quotas',\n quotas,\n state_transition='begin_updating',\n )\n\n\nclass TenantPullQuotasExecutor(core_executors.ActionExecutor):\n @classmethod\n def get_task_signature(cls, tenant, serialized_tenant, **kwargs):\n return core_tasks.BackendMethodTask().si(\n serialized_tenant, 'pull_tenant_quotas', state_transition='begin_updating'\n )\n\n\nclass TenantPullExecutor(core_executors.ActionExecutor):\n @classmethod\n def get_task_signature(cls, tenant, serialized_tenant, **kwargs):\n service_settings = structure_models.ServiceSettings.objects.get(scope=tenant)\n serialized_settings = core_utils.serialize_instance(service_settings)\n return chain(\n core_tasks.BackendMethodTask().si(\n serialized_tenant, 'pull_tenant', state_transition='begin_updating'\n ),\n core_tasks.BackendMethodTask().si(serialized_tenant, 'pull_tenant_quotas'),\n # Some resources are synchronized from openstack to openstack_tenant via handlers,\n # so for pulling them needed use serialized_tenant\n core_tasks.BackendMethodTask().si(\n serialized_tenant, 'pull_tenant_floating_ips'\n ),\n core_tasks.BackendMethodTask().si(\n serialized_tenant, 'pull_tenant_security_groups'\n ),\n core_tasks.BackendMethodTask().si(\n serialized_tenant, 'pull_tenant_server_groups'\n ),\n core_tasks.BackendMethodTask().si(\n serialized_tenant, 'pull_tenant_networks'\n ),\n core_tasks.IndependentBackendMethodTask().si(\n serialized_settings, 'pull_images'\n ),\n core_tasks.IndependentBackendMethodTask().si(\n serialized_settings, 'pull_flavors'\n ),\n core_tasks.IndependentBackendMethodTask().si(\n serialized_settings, 'pull_volume_types'\n ),\n core_tasks.BackendMethodTask().si(serialized_tenant, 'pull_subnets'),\n core_tasks.BackendMethodTask().si(\n serialized_tenant, backend_method='pull_tenant_routers'\n ),\n core_tasks.BackendMethodTask().si(\n serialized_tenant, backend_method='pull_tenant_ports'\n ),\n )\n\n @classmethod\n def get_success_signature(cls, instance, serialized_instance, **kwargs):\n return chain(\n core_tasks.StateTransitionTask().si(\n serialized_instance,\n state_transition='set_ok',\n action='',\n action_details={},\n ),\n tasks.SendSignalTenantPullSucceeded().si(serialized_instance),\n )\n\n\nclass TenantPullSecurityGroupsExecutor(core_executors.ActionExecutor):\n @classmethod\n def get_task_signature(cls, tenant, serialized_tenant, **kwargs):\n return core_tasks.BackendMethodTask().si(\n serialized_tenant,\n 'pull_tenant_security_groups',\n state_transition='begin_updating',\n )\n\n\nclass TenantPullServerGroupsExecutor(core_executors.ActionExecutor):\n @classmethod\n def get_task_signature(cls, tenant, serialized_tenant, **kwargs):\n return core_tasks.BackendMethodTask().si(\n serialized_tenant,\n 'pull_tenant_server_groups',\n state_transition='begin_updating',\n )\n\n\nclass TenantDetectExternalNetworkExecutor(core_executors.ActionExecutor):\n @classmethod\n def get_task_signature(cls, tenant, serialized_tenant, **kwargs):\n return core_tasks.BackendMethodTask().si(\n serialized_tenant,\n 'detect_external_network',\n state_transition='begin_updating',\n )\n\n\nclass TenantChangeUserPasswordExecutor(core_executors.ActionExecutor):\n @classmethod\n def get_task_signature(cls, tenant, serialized_tenant, **kwargs):\n return core_tasks.BackendMethodTask().si(\n serialized_tenant,\n 'change_tenant_user_password',\n state_transition='begin_updating',\n )\n\n\nclass RouterSetRoutesExecutor(core_executors.ActionExecutor):\n action = 'set_static_routes'\n\n @classmethod\n def get_task_signature(cls, router, serialized_router, **kwargs):\n return core_tasks.BackendMethodTask().si(\n serialized_router, 'set_static_routes', state_transition='begin_updating'\n )\n\n\nclass NetworkCreateExecutor(core_executors.CreateExecutor):\n @classmethod\n def get_task_signature(cls, network, serialized_network, **kwargs):\n return core_tasks.BackendMethodTask().si(\n serialized_network, 'create_network', state_transition='begin_creating'\n )\n\n\nclass NetworkUpdateExecutor(core_executors.UpdateExecutor):\n @classmethod\n def get_task_signature(cls, network, serialized_network, **kwargs):\n return core_tasks.BackendMethodTask().si(\n serialized_network, 'update_network', state_transition='begin_updating'\n )\n\n\nclass NetworkDeleteExecutor(core_executors.DeleteExecutor):\n @classmethod\n def get_task_signature(cls, network, serialized_network, **kwargs):\n if network.backend_id:\n return core_tasks.BackendMethodTask().si(\n serialized_network, 'delete_network', state_transition='begin_deleting'\n )\n else:\n return core_tasks.StateTransitionTask().si(\n serialized_network, state_transition='begin_deleting'\n )\n\n\nclass NetworkPullExecutor(core_executors.ActionExecutor):\n action = 'pull'\n\n @classmethod\n def get_task_signature(cls, network, serialized_network, **kwargs):\n return core_tasks.BackendMethodTask().si(\n serialized_network, 'pull_network', state_transition='begin_updating'\n )\n\n\nclass SetMtuExecutor(core_executors.ActionExecutor):\n action = 'set_mtu'\n\n @classmethod\n def get_task_signature(cls, network, serialized_network, **kwargs):\n return core_tasks.BackendMethodTask().si(\n serialized_network, 'set_network_mtu', state_transition='begin_updating'\n )\n\n\nclass SubNetCreateExecutor(core_executors.CreateExecutor):\n @classmethod\n def get_task_signature(cls, subnet, serialized_subnet, **kwargs):\n return core_tasks.BackendMethodTask().si(\n serialized_subnet,\n 'create_subnet',\n state_transition='begin_creating',\n )\n\n\nclass SubNetUpdateExecutor(core_executors.UpdateExecutor):\n @classmethod\n def get_task_signature(cls, subnet, serialized_subnet, **kwargs):\n return core_tasks.BackendMethodTask().si(\n serialized_subnet,\n 'update_subnet',\n state_transition='begin_updating',\n )\n\n\nclass SubnetConnectExecutor(core_executors.ActionExecutor):\n action = 'connect'\n\n @classmethod\n def get_task_signature(cls, subnet, serialized_subnet, **kwargs):\n serialized_tenant = core_utils.serialize_instance(subnet.network.tenant)\n return chain(\n core_tasks.BackendMethodTask().si(\n serialized_subnet,\n 'connect_subnet',\n state_transition='begin_updating',\n ),\n core_tasks.BackendMethodTask().si(\n serialized_tenant, backend_method='pull_tenant_routers'\n ),\n )\n\n\nclass SubnetDisconnectExecutor(core_executors.ActionExecutor):\n action = 'disconnect'\n\n @classmethod\n def get_task_signature(cls, subnet, serialized_subnet, **kwargs):\n serialized_tenant = core_utils.serialize_instance(subnet.network.tenant)\n return chain(\n core_tasks.BackendMethodTask().si(\n serialized_subnet,\n 'disconnect_subnet',\n state_transition='begin_updating',\n ),\n core_tasks.BackendMethodTask().si(\n serialized_tenant, backend_method='pull_tenant_routers'\n ),\n )\n\n\nclass SubNetDeleteExecutor(core_executors.DeleteExecutor):\n @classmethod\n def get_task_signature(cls, subnet, serialized_subnet, **kwargs):\n if subnet.backend_id:\n return core_tasks.BackendMethodTask().si(\n serialized_subnet, 'delete_subnet', state_transition='begin_deleting'\n )\n else:\n return core_tasks.StateTransitionTask().si(\n serialized_subnet, state_transition='begin_deleting'\n )\n\n\nclass SubNetPullExecutor(core_executors.ActionExecutor):\n action = 'pull'\n\n @classmethod\n def get_task_signature(cls, subnet, serialized_subnet, **kwargs):\n return core_tasks.BackendMethodTask().si(\n serialized_subnet, 'pull_subnet', state_transition='begin_updating'\n )\n\n\nclass OpenStackCleanupExecutor(structure_executors.BaseCleanupExecutor):\n executors = (\n (models.SecurityGroup, SecurityGroupDeleteExecutor),\n (models.FloatingIP, FloatingIPDeleteExecutor),\n (models.SubNet, SubNetDeleteExecutor),\n (models.Network, NetworkDeleteExecutor),\n (models.Tenant, TenantDeleteExecutor),\n (models.ServerGroup, ServerGroupDeleteExecutor),\n )\n\n\nclass PortCreateExecutor(core_executors.CreateExecutor):\n @classmethod\n def get_task_signature(cls, port, serialized_port, **kwargs):\n return core_tasks.BackendMethodTask().si(\n serialized_port,\n 'create_port',\n state_transition='begin_creating',\n serialized_network=kwargs.get('network'),\n )\n\n\nclass PortDeleteExecutor(core_executors.DeleteExecutor):\n @classmethod\n def get_task_signature(cls, port, serialized_port, **kwargs):\n return core_tasks.BackendMethodTask().si(\n serialized_port,\n 'delete_port',\n state_transition='begin_deleting',\n )\n","sub_path":"src/waldur_openstack/openstack/executors.py","file_name":"executors.py","file_ext":"py","file_size_in_byte":27601,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"484345830","text":"# Group 1\n# Elsy Fernandes 1001602253\n# Maria Lancy 1001639262\nimport os\nimport re\nfrom prettytable import PrettyTable\n\n# declaring variables needed\nfileLine = []\ncounter = []\ntransactionObjects = []\nlockObjects = []\nexecutinop = []\n\nroot = os.path.dirname(os.path.abspath(__file__))\ntemplates_dir = os.path.join(root, 'templates')\nprint(templates_dir)\n\ntransactionsWaiting = []\nwaitingop = []\nabortingTransaction = []\nrestart = []\n\n# declaring and defining Transaction Table which contains TransactionId,Transaction state,Timestamp\nclass transactionTable():\n def __init__(self, tranID, Timestamp, State, lockBy, lockedOp):\n self.tranID = tranID\n self.Timestamp = Timestamp\n self.State = State\n if lockedOp == None:\n self.lockedOp = []\n else:\n self.lockedOp = [lockedOp]\n self.itemsLockedByTransaction = []\n self.waitingop = []\n self.lockBy = lockBy\n self.waitingop.append(tranID)\n\n # This function adds list of items locked by the transaction to the transaction\n def itemLockedByTransaction(self, dataitem):\n self.itemsLockedByTransaction.append(dataitem)\n\n # This function is used to change the transaction state\n def changeState(self, newstate):\n self.State = newstate\n\n # This function is used to denote which data items are locked by which transaction\n def newlockedby(self, newlockedby):\n self.lockBy = newlockedby\n\n # This operation is used to tell which operation is in waiting state for a transaction\n def lockop(self, newlockop):\n if not (newlockop in self.lockedOp):\n self.lockedOp.append(newlockop)\n\n def toString(self):\n op = ''\n op = op.join(self.tranID)\n op = op + '-'\n op = op.join(self.State)\n op = op + '-'\n op = op.join(self.lockBy)\n op = op + '-'\n print(op.join(self.lockedOp))\n\n# This class is used to define lock table which contains information about data item locked like data item name,\n# Type of lock ,Locked by which transaction\nclass lockedTable():\n def __init__(self, dataitem, lock, tranID):\n self.dataitem = dataitem\n self.lock = lock\n self.tranID = tranID\n self.transactionIDHoldingWriteLock = []\n self.transactionIDHoldingReadLock = []\n\n self.transactionWaiting = []\n self.transactionWaiting.append(tranID)\n\n self.abortingTransaction = []\n self.abortingTransaction.append(tranID)\n\n self.transactionIDHoldingReadLock = []\n self.transactionIDHoldingReadLock.append(tranID)\n\n # This functions add transaction which have read lock on items\n def transactionIDHoldingReadLockFun(self, tranID):\n self.transactionIDHoldingReadLock.append(tranID)\n\n # This function is used to change lock state of a data item in lock table\n def changeLockState(self, lock):\n self.lock = lock\n\n# This function is called when a transaction begins for the first time\n# We add the Transaction to the transaction table with its Id,timestamp,Active state\ndef beginDatabaseTransaction(j, writefile):\n for k in j:\n if k.isdigit():\n digit = k.split()\n print(\n \"************************************************************************************************************\")\n writeToFile(writefile,\n \"*********************************************************************************************\")\n\n print('Begin Transaction for Transaction num: ' + str(digit))\n writeToFile(writefile, 'Begin Transaction for Transaction num: ' + str(digit))\n\n timestamp = len(counter) + 1\n transactionObjects.append(transactionTable(digit, timestamp, 'Active', None, None))\n counter.append(1)\n printTable(transactionObjects)\n\n# This function is called when a read lock on data item is requested\n# It checks if lock table is empty,it grants read lock to transaction and updates the lock and transaction table\n# If lock table is not empty,it checks if requested data item is already on lock table\n# if present it checks whether it is read locked or write locked.\n# If read locked ,it grants read lock to transaction and updates the lock and transaction table\n# If write locked, it calls wound wait function and passes lock holding Tid and lock requesting Tid as inputs\n# If lock table is not empty,it checks if requested data item is already on lock table\n# If not present it grants read lock to transaction and updates the lock and transaction table\ndef read(j, writefile):\n readflag = 0\n if j == 'Ignore':\n print('Ignore the operation')\n else:\n\n for k in j:\n if k.isdigit():\n digit = k.split()\n\n dataitem = re.search(r\"\\(([A-Za-z0-9_]+)\\)\", j).group(1)\n print('Data Item is :' + dataitem)\n writeToFile(writefile, 'Data Item is :' + dataitem)\n\n if len(lockObjects) == 0:\n lockObjects.append(lockedTable(dataitem, 'ReadLock', digit))\n for t in transactionObjects:\n if t.tranID == digit:\n t.itemLockedByTransaction(dataitem)\n print(\n \"Transaction for Data Item \"'\\t' + dataitem + '\\t'\"is Read locked by the transaction\"'\\t' + str(\n digit))\n writeToFile(writefile,\n \"Transaction for Data Item \"'\\t' + dataitem + '\\t'\"is Read locked by the transaction\"'\\t' + str(\n digit))\n writeToFile(writefile, \"\\n\")\n elif len(lockObjects) != 0:\n length = len(lockObjects)\n for i in range(0, length):\n if lockObjects[i].dataitem == dataitem:\n readflag = 1\n if lockObjects[i].lock == 'ReadLock':\n lockObjects.append(lockedTable(dataitem, 'ReadLock', digit))\n lockObjects[i].transactionIDHoldingReadLockFun(digit)\n for t in transactionObjects:\n if t.tranID == digit:\n t.itemLockedByTransaction(dataitem)\n print(\n \"Transaction for Data Item \"'\\t' + dataitem + '\\t' \" Read locked by the transaction\" '\\t' + str(\n digit))\n writeToFile(writefile,\n \"Transaction for Data Item \"'\\t' + dataitem + '\\t'\"is Read locked by the transaction\"'\\t' + str(\n digit))\n writeToFile(writefile, \"\\n\")\n break\n else:\n tran = str(lockObjects[i].transactionIDHoldingReadLock[0])\n holdingTran = lockObjects[i].transactionIDHoldingReadLock[0]\n print(\n \"Conflicting : Transaction for Data Item is\"'\\t' + dataitem + '\\t' \"is already Write Lock by Transaction\" '\\t'\n + tran)\n writeToFile(writefile,\n \"Conflicting : Transaction for Data Item is\"'\\t' + dataitem + '\\t' \"is already Write Lock by Transaction\" '\\t'\n + tran)\n writeToFile(writefile, \"\\n\")\n\n woundWait(digit, holdingTran, j)\n\n if readflag == 0:\n lockObjects.append(lockedTable(dataitem, 'ReadLock', digit))\n for t in transactionObjects:\n if t.tranID == digit:\n t.itemLockedByTransaction(dataitem)\n print(\"Transaction for Data Item \"'\\t' + dataitem + '\\t' \" Read locked by the transaction\", str(digit))\n writeToFile(writefile,\n \"Transaction for Data Item \"'\\t' + dataitem + '\\t'\"is Read locked by the transaction\"'\\t' + str(\n digit))\n writeToFile(writefile, \"\\n\")\n\n locktable = PrettyTable(['dataitem', 'lock', 'tranID'])\n for lockvalues in lockObjects:\n locktable.add_row([lockvalues.dataitem, lockvalues.lock, lockvalues.tranID])\n print('Lock Table :-')\n writeToFile(writefile, 'Lock Table :-')\n\n print(locktable)\n writeToFile(writefile, str(locktable))\n\n# This function is called when a write lock on data item is requested\n# It checks if lock table is empty then it grants write lock to transaction and updates the lock and transaction table\n# If lock table is not empty,it checks if requested data item is already on lock table\n# if present it checks whether it is read locked or write locked.\n# If read locked ,it checks whether Tid which holds read lock is same as one requesting write lock\n# If so it grants write lock to transaction and updates the lock and transaction table\n# If they are many Tid holding read lock for data Item it calls wound wait\n# If not same Tid as requesting,it calls wound wait function and passes lock holding Tid and lock requesting Tid\n# If item is already write locked it calls wound wait function and passes lock holding Tid and lock requesting Tid\n# If lock table is not empty,it checks if requested data item is already on lock table\n# If not present it grants write lock to transaction and updates the lock and transaction table\ndef write(j, writefile):\n if j == 'Ignore':\n print('Ignore the operation')\n else:\n writeflag = 0\n for k in j:\n if k.isdigit():\n digit = k.split()\n\n dataitem = re.search(r\"\\(([A-Za-z0-9_]+)\\)\", j).group(1)\n print('Data Item is :' + dataitem)\n writeToFile(writefile, 'Data Item is :' + dataitem)\n\n if len(lockObjects) == 0:\n lockObjects.append(lockedTable(dataitem, 'WriteLock', digit))\n for t in transactionObjects:\n if t.tranID == digit:\n t.itemLockedByTransaction(dataitem)\n print(\n \"Transaction for Data Item \"'\\t' + dataitem + '\\t'\"is Write locked by the transaction\"'\\t' + str(\n digit))\n writeToFile(writefile,\n \"Transaction for Data Item \"'\\t' + dataitem + '\\t'\"is Write locked by the transaction\"'\\t' + str(\n digit))\n writeToFile(writefile, \"\\n\")\n\n locktable = PrettyTable(['dataitem', 'lock', 'tranID'])\n for lockvalues in lockObjects:\n locktable.add_row([lockvalues.dataitem, lockvalues.lock, lockvalues.tranID])\n print(locktable)\n writeToFile(writefile, str(locktable))\n\n elif len(lockObjects) != 0:\n length = len(lockObjects)\n count = 0\n for i in range(0, length):\n if lockObjects[i].dataitem == dataitem:\n count += 1\n for i in range(0, length):\n if lockObjects[i].dataitem == dataitem:\n writeflag = 1\n if lockObjects[i].lock == 'ReadLock':\n if len(lockObjects[i].transactionIDHoldingReadLock) == 1:\n if lockObjects[i].transactionIDHoldingReadLock[0] == digit and count <= 1:\n lockObjects[i].lock = 'WriteLock'\n print(\n \"Upgrading the Read Lock to Write Lock on Data Item\" '\\t' + dataitem + '\\t' \"by the Transaction\" '\\t' + str(\n digit))\n writeToFile(writefile,\n \"Upgrading the Read Lock to Write Lock on Data Item\" '\\t' + dataitem + '\\t' \"by the Transaction\" '\\t' + str(\n digit))\n writeToFile(writefile, \"\\n\")\n\n\n elif lockObjects[i].transactionIDHoldingReadLock[0] != digit:\n holdingTran = lockObjects[i].transactionIDHoldingReadLock[0]\n holdingTranstr = str(lockObjects[i].transactionIDHoldingReadLock[0])\n print(\n \"Transaction for the the Data Item\" '\\t' + dataitem + '\\t'\" is Read Locked by the Transaction\"'\\t' + holdingTranstr + '\\t' \".Hence , Cannot perform Write operation on it!!\")\n writeToFile(writefile,\n \"Transaction for the the Data Item\" '\\t' + dataitem + '\\t'\" is Read Locked by the Transaction\"'\\t' + holdingTranstr + '\\t' \".Hence , Cannot perform Write operation on it!!\")\n writeToFile(writefile, \"\\n\")\n woundWait(digit, holdingTran, j)\n break\n\n elif (digit != lockObjects[i].transactionIDHoldingReadLock[0]):\n holdingTran = lockObjects[i].transactionIDHoldingReadLock[0]\n holdingTranstr = str(lockObjects[i].transactionIDHoldingReadLock[0])\n print(\n \"Transaction for the Data Item\" '\\t' + dataitem + '\\t'\" is Read Locked by the Transaction\"'\\t' + holdingTranstr + '\\t' \".Hence , Cannot perform Write operation on it!!\")\n writeToFile(writefile,\n \"Transaction for the Data Item\" '\\t' + dataitem + '\\t'\" is Read Locked by the Transaction\"'\\t' + holdingTranstr + '\\t' \".Hence , Cannot perform Write operation on it!!\")\n writeToFile(writefile, \"\\n\")\n woundWait(digit, holdingTran, j)\n break\n else:\n c = 0\n for lockedresource in lockObjects:\n if lockedresource.dataitem == dataitem:\n for temp in lockedresource.transactionIDHoldingReadLock:\n if temp == digit:\n c += 1\n holdingTran = lockObjects[i].transactionIDHoldingReadLock[0]\n print(\n \"Conflicting:Transaction for the Data Item \"'\\t' + dataitem + '\\t' \"is already write Locked by the Transaction\"'\\t' + str(\n holdingTran) + '\\t')\n writeToFile(writefile,\n \"Conflicting:Transaction for the Data Item \"'\\t' + dataitem + '\\t' \"is already write Locked by the Transaction\"'\\t' + str(\n holdingTran) + '\\t')\n writeToFile(writefile, \"\\n\")\n woundWait(digit, holdingTran, j)\n\n if writeflag == 0:\n lockObjects.append(lockedTable(dataitem, 'WriteLock', digit))\n for t in transactionObjects:\n if t.tranID == digit:\n t.itemLockedByTransaction(dataitem)\n print(\"Transaction for Data Item \"'\\t' + dataitem + '\\t' \" Write locked by the transaction\", str(digit))\n writeToFile(writefile,\n \"Transaction for Data Item \"'\\t' + dataitem + '\\t'\"is Write locked by the transaction\"'\\t' + str(\n digit))\n writeToFile(writefile, \"\\n\")\n locktable = PrettyTable(['dataitem', 'lock', 'tranID'])\n for lockvalues in lockObjects:\n locktable.add_row([lockvalues.dataitem, lockvalues.lock, lockvalues.tranID])\n print('Lock Table :-')\n writeToFile(writefile, 'Lock Table :-')\n\n print(locktable)\n writeToFile(writefile, str(locktable))\n\n# This function is called before write lock is obtained by Transaction\n# If transaction state is Abort it ignores the operation\ndef checkwriteState(i, writefile):\n for k in i:\n if k.isdigit():\n digit = k.split()\n for t in transactionObjects:\n if t.tranID == digit:\n if t.State == 'Abort':\n print(\"Transaction\" '\\t' + str(digit) + '\\t'\"is Already Aborted ! Ignore its operation \" + str(i))\n writeToFile(writefile,\n \"Transaction\" '\\t' + str(digit) + '\\t'\"is Already Aborted ! Ignore its operation \" + str(\n i))\n\n i = 'Ignore'\n write(i, writefile)\n elif t.State == 'Waiting':\n t.lockop(i)\n print(\"Transaction\"'\\t' + str(\n digit) + '\\t' \"is already in Waiting State. Add the operation to waiting Queue\"'\\t' + str(i) + '\\t')\n\n writeToFile(writefile,\n \"Transaction\"'\\t' + str(digit) + '\\t' \"is already in Waiting State\"'\\t' + str(i) + '\\t')\n elif t.State == 'Active':\n write(i, writefile)\n\n# This function is called before read lock is obtained by Transaction\n# If transaction state is Abort it ignores the operation\ndef checkreadState(i, writefile):\n for k in i:\n if k.isdigit():\n digit = k.split()\n for t in transactionObjects:\n if t.tranID == digit:\n if t.State == 'Abort':\n print(\"Transaction\" '\\t' + str(digit) + '\\t'\"is Already Aborted ! Ignore its operation \" + str(i))\n writeToFile(writefile,\n \"Transaction\" '\\t' + str(digit) + '\\t'\"is Already Aborted ! Ignore its operation \" + str(\n i))\n i = 'Ignore'\n read(i, writefile)\n elif t.State == 'Waiting':\n t.lockop(i)\n print(\"Transaction\"'\\t' + str(\n digit) + '\\t' \"is already in Waiting State. Add the operation to waiting Queue\"'\\t' + str(i) + '\\t')\n writeToFile(writefile,\n \"Transaction\"'\\t' + str(digit) + '\\t' \"is already in Waiting State\"'\\t' + str(i) + '\\t')\n elif t.State == 'Active':\n read(i, writefile)\n printTable(transactionObjects)\n\n# This function performs the wound wait protocol\n# If lock requesting Tid < lock holding Tid, then lock Holding Tid is aborted and requesting Tid is given access\n# If lock requesting Tid > lock holding Tid, then requesting Tid is changed to waiting state\n# and operation is added to its list of waiting operation, which resumes once requesting Tid changes to Active state\ndef woundWait(requestingT, holdingT, j):\n print('Calling Wound - Wait............')\n writeToFile(writefile, 'Calling Wound - Wait............')\n holdingTstr = str(holdingT)\n for requestingTimestamp in transactionObjects:\n if requestingTimestamp.tranID == requestingT:\n requestTimestamp = requestingTimestamp.Timestamp\n request = requestingTimestamp\n for holdingTimestamp in transactionObjects:\n if holdingTimestamp.tranID == holdingT:\n holdTimestamp = holdingTimestamp.Timestamp\n hold = holdingTimestamp\n if requestTimestamp < holdTimestamp:\n hold.changeState('Abort')\n hold.newlockedby('None')\n hold.lockedOp = []\n print(\"Aborting the Transaction \"'\\t' + holdingTstr + '\\t')\n writeToFile(writefile, \"Aborting the Transaction \"'\\t' + holdingTstr + '\\t')\n abortingTransaction.append(holdingT)\n abort(holdingT)\n print(\"Performing the Operation:---------\")\n if j.find('r') != -1:\n read(j, writefile)\n if j.find('w') != -1:\n write(j, writefile)\n else:\n print(\"Transaction Waiting\"'\\t' + str(requestingT) + '\\t')\n writeToFile(writefile, \"Transaction Waiting\"'\\t' + str(requestingT) + '\\t')\n request.changeState('Waiting')\n request.newlockedby(holdingT)\n if checkDuplicateTransaction(request):\n transactionsWaiting.append(request)\n waitingop.append(j)\n\n request.lockop(j)\n\n printTable(transactionObjects)\n\n# This function is used to block same transaction to change to wait state more than once\ndef checkDuplicateTransaction(transaction):\n print(transaction.tranID)\n for t in transactionsWaiting:\n if t.tranID == transaction.tranID:\n return 0\n return 1\n\n# This Function is called when Transaction is aborted\n# It changes the transaction state to Abort and unlocks all locks held by the transaction\n# It updates lock and transaction table\ndef abort(holdingT):\n holdingTstr = str(holdingT)\n print(\"Unlocking all the dataitems held by\"'\\t' + holdingTstr + '\\t')\n writeToFile(writefile, \"Unlocking all the data items held by\"'\\t' + holdingTstr + '\\t')\n for t in transactionObjects:\n if t.tranID == holdingT:\n for lock in t.itemsLockedByTransaction:\n for dataitem in lockObjects:\n if dataitem.dataitem == lock:\n if len(dataitem.transactionIDHoldingReadLock) == 1 and dataitem.tranID == holdingT:\n lockObjects.remove(dataitem)\n\n elif dataitem.tranID == holdingT:\n lockObjects.remove(dataitem)\n break\n startblockTrans(holdingT)\n\n# This Function is called to execute waiting operations when transaction is committed and released all locks\n# so that any waiting transaction can execute its waiting operation, acquire lock and go to active state\n# Updates Transaction and lock table\ndef startblockTrans(holdingT):\n for t in transactionsWaiting:\n if t.State == 'Abort':\n transactionsWaiting.remove(t)\n\n else:\n for i in transactionObjects:\n if i.lockBy == holdingT and i.State == 'Waiting':\n\n s = 0\n while s < len(i.lockedOp) and i.lockBy == holdingT:\n print('Attempting to perform the operation' '\\t' + i.lockedOp[s])\n writeToFile(writefile, 'Attempting to perform the operation' '\\t' + i.lockedOp[s])\n transaction = i.lockedOp.pop(0)\n if transaction.find('r') != -1:\n read(transaction, writefile)\n if transaction.find('w') != -1:\n write(transaction, writefile)\n if i.lockBy == holdingT:\n i.State = 'Active'\n i.lockBy = None\n\n# Function to print the contents of the Transaction table\ndef printTable(transactionobjects):\n transactiontable = PrettyTable(['tranID', 'Timestamp', 'State', 'Lockedby', 'Locked Operation'])\n for i in transactionobjects:\n transactiontable.add_row([i.tranID, i.Timestamp, i.State, i.lockBy, i.lockedOp])\n print('Transaction Table :-')\n print(transactiontable)\n writeToFile(writefile, 'Transaction Table :-')\n writeToFile(writefile, str(transactiontable))\n\n# Function to write the output in a output text file\ndef writeToFile(file, message):\n file.writelines(message)\n file.writelines('\\n')\n\n# This function is called when commit operation is requested\n# Commits the transaction and unlocks all data items held by transaction\n# Changes transaction state to Commit\n# Updates lock and transaction table\n\ndef end(i, writefile):\n for k in i:\n if k.isdigit():\n digit = k.split()\n for t in transactionObjects:\n\n if t.tranID == digit and t.State != 'Abort' and t.State != 'Waiting':\n print(\"Committing transaction\"'\\t' + str(digit))\n writeToFile(writefile, \"Committing transaction\"'\\t' + str(digit))\n\n t.State = 'Commit'\n t.lockedOp = []\n abort(digit)\n elif t.tranID == digit and t.State == 'Abort':\n print('Transaction''\\t' + str(digit) + '\\t'' is Already Aborted!!')\n writeToFile(writefile, 'Transaction''\\t' + str(digit) + '\\t'' is Already Aborted!!')\n\n abort(digit)\n elif t.tranID == digit and t.State == 'Waiting':\n print('Since state is in waiting, cannot commit transaction''\\t' + str(digit))\n writeToFile(writefile, 'Since state is in waiting, cannot commit transaction''\\t' + str(digit))\n printTable(transactionObjects)\n\n# Reads input file and perform operation requested\nval = input(\"Enter File Name: \")\nfilename = val\nif filename == 'file1.txt':\n writefile = open(\"output1.txt\", \"a\")\nif filename == 'file2.txt':\n writefile = open(\"output2.txt\", \"a\")\nif filename == 'file3.txt':\n writefile = open(\"output3.txt\", \"a\")\nif filename == 'file4.txt':\n writefile = open(\"output4.txt\", \"a\")\nif filename == 'file5.txt':\n writefile = open(\"output5.txt\", \"a\")\nif filename == 'file6.txt':\n writefile = open(\"output6.txt\", \"a\")\nif filename == 'file7.txt':\n writefile = open(\"output7.txt\", \"a\")\nlines = [line.rstrip('\\n') for line in open(filename)]\nfor line in lines:\n fileLine.append(line)\nfor i in fileLine:\n print(\"Looking into operation\\n\" + i)\n writeToFile(writefile, \"Looking into operation\\n\" + i)\n if i.find('b') != -1:\n beginDatabaseTransaction(i, writefile)\n if i.find('r') != -1:\n print('Beginning of Read Operation :-')\n writeToFile(writefile, 'Beginning of Read Operation :-\\n')\n checkreadState(i, writefile)\n if i.find('w') != -1:\n print('Beginning of Write Operation :-')\n writeToFile(writefile, 'Beginning of Write Operation :-\\n')\n checkwriteState(i, writefile)\n if i.find('e') != -1:\n print('End Database Transaction')\n writeToFile(writefile, 'End Operation :-\\n')\n end(i, writefile)\n","sub_path":"PythonFile/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":25836,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"188356354","text":"\"\"\"\n160\neasy\nintersection of two linked lists\n\nGiven the heads of two singly linked-lists headA and headB,\nreturn the node at which the two lists intersect. If the two\nlinked lists have no intersection at all, return null\n\"\"\"\n\n\n# Definition for singly-linked list.\nclass ListNode:\n def __init__(self, x):\n self.val = x\n self.next = None\n\n# hash table\nclass Solution:\n def getIntersectionNode(self, headA: ListNode, headB: ListNode) -> ListNode:\n\n visited_nodes = set()\n p1, p2 = headA, headB\n while p1:\n visited_nodes.add(p1)\n p1 = p1.next\n while p2:\n if p2 in visited_nodes:\n return p2\n p2 = p2.next\n return None\n\n\n\n\n","sub_path":"Q160.py","file_name":"Q160.py","file_ext":"py","file_size_in_byte":732,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"463928916","text":"# -*- coding: utf-8 -*-\n# Django settings for Editores project.\nimport os\nimport sys\n\n\n__author__ = 'Roberto Guimaraes Morati Junior '\n__copyright__ = 'Copyright (c) 2014 AutEnvLDG/AutoCoop/Nemo'\n__version__ = '1.0.0'\n\n\n\nif 'runserver' in sys.argv:\n DEBUG = True\nelse:\n DEBUG = False\n\n#from statsd import statsd\n\nALLOWED_HOSTS = ['*']\n\n#APPEND_SLASH=False\nSESSION_COOKIE_SECURE = False\nCSRF_COOKIE_SECURE = False\n#SESSION_EXPIRE_AT_BROWSER_CLOSE = True\n\n\nTEMPLATE_DEBUG = DEBUG\n\nPROJECT_DIR = os.path.dirname(__file__)\n#STATICFILES_DIRS = ( os.path.join(PROJECT_DIR,'static/'),)\n#ICONES_URL = '../media/imagens/icones/'\nCRISPY_TEMPLATE_PACK = 'uni_form'\n\nADMINS = (\n # ('Your Name', 'your_email@example.com'),\n)\n\nMANAGERS = ADMINS\nSECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https')\n\n\n\nDATABASES = {\n 'default': {\n 'ENGINE': 'django.db.backends.sqlite3',\n 'NAME': os.path.join(PROJECT_DIR, \"../editores.db\"),\n }\n}\n\n# Local time zone for this installation. Choices can be found here:\n# http://en.wikipedia.org/wiki/List_of_tz_zones_by_name\n# although not all choices may be available on all operating systems.\n# On Unix systems, a value of None will cause Django to use the same\n# timezone as the operating system.\n# If running in a Windows environment this must be set to the same as your\n# system time zone.\nTIME_ZONE = 'America/Chicago'\n\n# Language code for this installation. All choices can be found here:\n# http://www.i18nguy.com/unicode/language-identifiers.html\nLANGUAGE_CODE = 'pt-BR'\n\nSITE_ID = True\n\n# If you set this to False, Django will make some optimizations so as not\n# to load the internationalization machinery.\nUSE_I18N = True\n\nLANGUAGES = (\n ('pt_BR', ('pt_br')),\n ('en_US', ('en_us')),\n)\nDEFAULT_LANGUAGE = 1\n\n# If you set this to False, Django will not format dates, numbers and\n# calendars according to the current locale.\nUSE_L10N = True\n\n# If you set this to False, Django will not use timezone-aware datetimes.\nUSE_TZ = True\n\n# Absolute filesystem path to the directory that will hold user-uploaded files.\n# Example: \"/home/media/media.lawrence.com/media/\"\nMEDIA_ROOT = os.path.join(PROJECT_DIR, 'media/')\n\n# URL that handles the media served from MEDIA_ROOT. Make sure to use a\n# trailing slash.\n# Examples: \"http://media.lawrence.com/media/\", \"http://example.com/media/\"\nMEDIA_URL = '/media/'\n\n# Absolute path to the directory static files should be collected to.\n# Don't put anything in this directory yourself; store your static files\n# in apps' \"static/\" subdirectories and in STATICFILES_DIRS.\n# Example: \"/home/media/media.lawrence.com/static/\"\nSTATIC_ROOT = os.path.join(PROJECT_DIR, '../staticfiles/')\n\n# URL prefix for static files.\n# Example: \"http://media.lawrence.com/static/\"\nSTATIC_URL = '/static/'\n\n# URL of the login page.\n#LOGIN_URL='/autenvldg/'\n\n#datalog config\nDATADOG_API_KEY = '429b85a4274f59adfeb8a438e3478d59'\nDATADOG_APP_KEY = '0b3bfdd2d4adafe4b1c65fce58be58658c87fdf9'\nDATADOG_APP_NAME = 'page.views'\nDATADOG_APP_NAME = 'editores'\nDATADOG_APP_NAME = 'editor_enredos'\nDATADOG_APP_NAME = 'editor_missoes'\nDATADOG_APP_NAME = 'editor_jogadores'\nDATADOG_APP_NAME = 'editor_movimentos'\nDATADOG_APP_NAME = 'editor_aventuras'\n\n\n#STATSD_HOST = 'localhost'\n#STATSD_PORT = 8125\n#STATSD_PREFIX = None\n#STATSD_MAXUDPSIZE = 512\n\n\n#statsd.incr('page.views')\n\n\n\n# Optionally, configure the host and port if you're running Statsd on a\n# non-standard port.\n#statsd.connect('localhost', 8125)\n\n# Increment a counter.\n#statsd.increment('page.views')\n\n# Record a gauge 50% of the time.\n#statsd.gauge('users.online', 123, sample_rate=0.5)\n\n\n\n# Additional locations of static files\nSTATICFILES_DIRS = (\n os.path.join(PROJECT_DIR, \"static\"),\n # Put strings here, like \"/home/html/static\" or \"C:/www/django/static\".\n # Always use forward slashes, even on Windows.\n # Don't forget to use absolute paths, not relative paths.\n)\n\n# List of finder classes that know how to find static files in\n# various locations.\nSTATICFILES_FINDERS = (\n 'django.contrib.staticfiles.finders.FileSystemFinder',\n 'django.contrib.staticfiles.finders.AppDirectoriesFinder',\n #'django.contrib.staticfiles.finders.DefaultStorageFinder',\n)\n\n# Make this unique, and don't share it with anybody.\nSECRET_KEY = 'ttjzle-dgs#r!#uc*j5l&(q++2%lg35$0=@b-z@ic=x%dmq*99'\n\n# List of callables that know how to import templates from various sources.\nTEMPLATE_LOADERS = (\n 'django.template.loaders.filesystem.Loader',\n 'django.template.loaders.app_directories.Loader',\n# 'django.template.loaders.eggs.Loader',\n)\n\n#TEMPLATE_DIRS = (\n # Put strings here, like \"/home/html/django_templates\" or \"C:/www/django/templates\".\n # Always use forward slashes, even on Windows.\n # Don't forget to use absolute paths, not relative paths.\n #os.path.join(PROJECT_DIR, '../editor_objetos/templates/'),\n#)\n\nMIDDLEWARE_CLASSES = (\n 'django.contrib.sessions.middleware.SessionMiddleware',\n 'django.middleware.common.CommonMiddleware',\n 'django.middleware.csrf.CsrfViewMiddleware',\n 'django.contrib.auth.middleware.AuthenticationMiddleware',\n 'django.contrib.messages.middleware.MessageMiddleware',\n 'django.middleware.clickjacking.XFrameOptionsMiddleware',\n 'django.middleware.locale.LocaleMiddleware',\n 'datadog.middleware.DatadogMiddleware',\n # Uncomment the next line for simple clickjacking protection:\n # 'django.middleware.clickjacking.XFrameOptionsMiddleware',\n)\n\nTEMPLATE_CONTEXT_PROCESSORS = (\n 'django.core.context_processors.debug',\n 'django.core.context_processors.i18n',\n 'django.core.context_processors.media',\n 'django.core.context_processors.static',\n 'django.contrib.auth.context_processors.auth',\n 'django.core.context_processors.tz',\n 'django.contrib.messages.context_processors.messages', \n)\n\nMESSAGE_STORAGE = 'django.contrib.messages.storage.cookie.CookieStorage'\n\n#Fix Json django 1.4 to django 1.6\nSESSION_SERIALIZER = (\n 'django.contrib.sessions.serializers.PickleSerializer')\n\n\nCODEMIRROR_PATH = r\"javascript/codemirror\"\n\nROOT_URLCONF = 'editores.urls'\n\n# Python dotted path to the WSGI application used by Django's runserver.\nWSGI_APPLICATION = 'editores.wsgi.application'\n\nTEMPLATE_DIRS = (\n os.path.join(PROJECT_DIR, \"templates\"),\n # Put strings here, like \"/home/html/django_templates\" or \"C:/www/django/templates\".\n # Always use forward slashes, even on Windows.\n # Don't forget to use absolute paths, not relative paths.\n)\n \nAUTH_PROFILE_MODULE = 'editores_objetos.Autor'\n\n\n#instalação das aplicações\nINSTALLED_APPS = (\n 'django.contrib.auth',\n 'django.contrib.contenttypes',\n 'django.contrib.sessions',\n 'django.contrib.sites',\n 'django.contrib.messages',\n 'django.contrib.staticfiles',\n 'editores',\n 'editor_objetos',\n 'django.contrib.admin',\n 'bootstrap_toolkit',\n 'PIL',\n 'imagekit',\n #'south',\n 'rest_framework',\n 'editor_enredos',\n 'editor_missoes',\n 'editor_jogadores',\n 'editor_movimentos',\n 'editor_aventuras',\n 'bootstrap3', \n 'statsd',\n #'django_cleanup', # remove old files\n # Uncomment the next line to enable the admin:\n # 'django.contrib.admin',\n # Uncomment the next line to enable admin documentation:\n # 'django.contrib.admindocs',\n)\n\nPASSWORD_HASHERS = (\n 'django.contrib.auth.hashers.PBKDF2PasswordHasher',\n 'django.contrib.auth.hashers.PBKDF2SHA1PasswordHasher',\n 'django.contrib.auth.hashers.BCryptPasswordHasher',\n 'django.contrib.auth.hashers.SHA1PasswordHasher',\n 'django.contrib.auth.hashers.MD5PasswordHasher',\n 'django.contrib.auth.hashers.CryptPasswordHasher',\n)\n\n#AUTHENTICATION_BACKENDS = (\n# 'editores.auth_backends.CustomUserModelBackend',\n#)\n\n#CUSTOM_USER_MODEL = 'accounts.CustomUser'\n\n# A sample logging configuration. The only tangible logging\n# performed by this configuration is to send an email to\n# the site admins on every HTTP 500 error when DEBUG=False.\n# See http://docs.djangoproject.com/en/dev/topics/logging for\n# more details on how to customize your logging configuration.\nLOGGING = {\n 'version': 1,\n 'disable_existing_loggers': False,\n 'filters': {\n 'require_debug_false': {\n '()': 'django.utils.log.RequireDebugFalse'\n }\n },\n 'handlers': {\n 'mail_admins': {\n 'level': 'ERROR',\n 'filters': ['require_debug_false'],\n 'class': 'django.utils.log.AdminEmailHandler'\n }\n },\n 'loggers': {\n 'django.request': {\n 'handlers': ['mail_admins'],\n 'level': 'ERROR',\n 'propagate': True,\n },\n }\n}\n\n\n#rest framerwork\nREST_FRAMEWORK = {\n # Use hyperlinked styles by default.\n # Only used if the `serializer_class` attribute is not set on a view.\n 'DEFAULT_MODEL_SERIALIZER_CLASS':\n 'rest_framework.serializers.HyperlinkedModelSerializer',\n\n # Use Django's standard `django.contrib.auth` permissions,\n # or allow read-only access for unauthenticated users.\n 'DEFAULT_PERMISSION_CLASSES': [\n 'rest_framework.permissions.DjangoModelPermissionsOrAnonReadOnly'\n ]\n}\n\n\n# Default settings\nBOOTSTRAP3_DEFAULTS = {\n 'jquery_url': '//code.jquery.com/jquery.min.js',\n 'base_url': '//netdna.bootstrapcdn.com/bootstrap/3.1.1/',\n 'css_url': None,\n 'theme_url': None,\n 'javascript_url': None,\n 'javascript_in_head': False,\n 'include_jquery': False,\n 'horizontal_label_class': 'col-md-2',\n 'horizontal_field_class': 'col-md-4',\n 'set_required': True,\n 'form_required_class': '',\n 'form_error_class': '',\n 'form_renderers': {\n 'default': 'bootstrap3.renderers.FormRenderer',\n },\n 'field_renderers': {\n 'default': 'bootstrap3.renderers.FieldRenderer',\n 'inline': 'bootstrap3.renderers.InlineFieldRenderer',\n },\n}","sub_path":"Editores/editores/settings.py","file_name":"settings.py","file_ext":"py","file_size_in_byte":9874,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"318596533","text":"from .base import APIBase\nimport logging as log\nfrom .common import loggingSetup, formatRFOutput\nfrom .TestProjects import TestProjects\n\n\nclass TestSuites(APIBase):\n \"\"\"\n Deal test suites\n \"\"\"\n __projects = TestProjects()\n\n def getTestSuites(self, projectName):\n \"\"\"\n Return a list of suites\n \"\"\"\n log.debug(\"getTestSuites %s\" % projectName)\n projID = self.__projects.projectIDFromName(projectName)\n path = \"get_suites/%s\" % projID\n log.debug(\"End point: '%s'\" % path)\n rslt = self.client.send_get(path)\n log.debug(rslt)\n return rslt\n\n def getTestSuite(self, suiteID):\n \"\"\"\n Return details on a specific suite\n \"\"\"\n log.debug(\"getTestSuite '%s'\" % suiteID)\n path = \"get_suite/%s\" % suiteID\n log.debug(\"Path = '%s'\" % path)\n rslt = self.client.send_get(path)\n log.debug(rslt)\n return rslt\n\n def addTestSuite(self, projectName, name, description):\n \"\"\"\n Add a new test suite\n \"\"\"\n log.debug(\"addTestSuite '%s', '%s', '%s'\" % (projectName, name, description))\n path = \"add_suite/%s\" % projectName\n log.debug(\"Path='%s'\" % path)\n rslt = self.client.send_post(path, {\"name\":name, \"description\": description})\n log.debug(rslt)\n return rslt\n\n def updateTestSuite(self, suiteID, name, description):\n \"\"\"\n update an existing test suite\n \"\"\"\n log.debug(\"updateTestSuite '%s', '%s', '%s'\" % (suiteID, name, description))\n path = \"update_suite/%s\" % suiteID\n log.debug(\"Path = \" % path)\n rslt = self.client.send_post(path, {\"name\": name, \"description\": description})\n log.debug(rslt)\n return rslt\n\n def suiteNameFromID(self, projectName, suiteID):\n \"\"\"\n Derive a suite name from a suite ID.\n \"\"\"\n log.debug(\"suiteNameFromID %s, %s\" % (projectName, suiteID))\n suites = self.getTestSuites(projectName)\n rslt = \"\"\n for s in suites:\n if s[\"id\"] == suiteID:\n rslt = s[\"name\"]\n break\n log.debug(\"Suite Name: '%s'\" % rslt)\n return rslt\n","sub_path":"src/TestRail/TestSuites.py","file_name":"TestSuites.py","file_ext":"py","file_size_in_byte":2208,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"84660908","text":"import json\nfrom pymodules.logger import logger\nfrom pymodules.http_requests import APICaller\nfrom pymodules import constant\nfrom pymodules.constant import NASA_FIREBALL_BASE_URL\n\n\nclass NasaFireballAPI(object):\n \"\"\"\n Fireball API\n \"\"\"\n url = NASA_FIREBALL_BASE_URL\n data = None\n\n def __init__(self):\n self.dbapi = APICaller(self.url)\n\n def fetch_all_data(self):\n endpoint = \"fireball.api\"\n status, response = self.dbapi.call_api(\n endpoint, \"GET\", auth=None, max_attempt=constant.FIREBALL_API_MAX_ATTEMPT\n )\n\n res = None\n if status == 200:\n res = json.loads(response.content)\n else:\n logger.warn(\n \"Could,n't get data from endpoint {}, get_all_fireball_data returned status - {}\".format(\n endpoint, status\n )\n )\n return status, res\n\n def fetch_most_recent_data(self, count):\n endpoint = \"fireball.api?limit = {count_of_records}\".format(\n count_of_records=count\n )\n status, response = self.dbapi.call_api(\n endpoint, \"GET\", auth=None, max_attempt=constant.FIREBALL_API_MAX_ATTEMPT\n )\n\n res = None\n if status == 200:\n res = json.loads(response.content)\n else:\n logger.warn(\n \"Could,n't get data from endpoint {}, get_all_fireball_data returned status - {}\".format(\n endpoint, status\n )\n )\n return status, res\n\n def fetch_data_by_altitude(self, date_min, req_alt=True):\n endpoint = \"fireball.api?date-min={date}&req-alt={req_alt}\".format(\n date=date_min,\n req_alt=req_alt\n )\n status, response = self.dbapi.call_api(\n endpoint, \"GET\", auth=None, max_attempt=constant.FIREBALL_API_MAX_ATTEMPT\n )\n\n res = None\n if status == 200:\n res = json.loads(response.content)\n else:\n logger.warn(\n \"Could,n't get data from endpoint {}, get_all_fireball_data returned status - {}\".format(\n endpoint, status\n )\n )\n return status, res\n\n def fetch_data_by_location(self, date_min, req_loc=False):\n \"\"\"\n Fetch data from NASA API\n :param date_min:\n :param req_loc:\n :return:\n \"\"\"\n endpoint = \"fireball.api?date-min={date}&req-loc={req_loc}\".format(\n date=date_min,\n req_loc=req_loc\n )\n status, response = self.dbapi.call_api(\n endpoint, \"GET\", auth=None, max_attempt=constant.FIREBALL_API_MAX_ATTEMPT\n )\n\n res = None\n assert int(status) == 200, \"API respond status code {}. Something went wrong while fetching data by location\".format(status)\n\n res = json.loads(response.content)\n if res != [] and res != {}:\n try:\n assert (res.get('signature',None) == constant.FIREBALL_RESPONSE_SIGNATURE_MAP), \"SIGNATURE IS NOT MATCHING\"\n assert (int(res.get('count', 0)) > 0), \"API could not find data matching criteria\"\n return status, res\n except Exception as e:\n raise Exception(\"Issue with Signature or count in API response, Exception: {} \".format(e))\n else:\n logger.warn(\"Found no records in response content body\")","sub_path":"pymodules/fireball_service_api.py","file_name":"fireball_service_api.py","file_ext":"py","file_size_in_byte":3427,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"259273004","text":"#(19) 기지국 설치\n\ndef solution(n, stations, w):\n answer = 0\n split_num = []\n start = 0\n for i in range(len(stations)):\n end = stations[i] - w - 1\n split_num.append(end-start)\n start = stations[i] + w\n if start > n: break\n if len(stations)-1 == i: split_num.append(n-start)\n for num in split_num:\n value, remainder = divmod(num,(w*2+1))\n if remainder: answer += (value+1)\n else: answer += value\n return answer","sub_path":"level3/level3_ex19.py","file_name":"level3_ex19.py","file_ext":"py","file_size_in_byte":488,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"149805629","text":"import logging\nfrom django.shortcuts import render\nfrom django.template.context import RequestContext\nfrom django.http import HttpResponse\nfrom django.contrib.auth.decorators import login_required\nimport json\nimport requests\nfrom hbp_app_python_auth.auth import get_access_token, get_token_type\nfrom django.conf import settings\n\nimport os.path\nimport tempfile\nimport shutil\nimport mimetypes\nfrom simqueue.models import Job\ntry:\n from urlparse import urlparse\n from urllib import urlretrieve\nexcept ImportError: # Py3\n from urllib.parse import urlparse\n from urllib.request import urlretrieve\nimport errno\n\nlogger = logging.getLogger(\"simqueue\")\n\n\n@login_required(login_url='/login/hbp/')\ndef home(request):\n # from the request context, load user\n context = {'request': request, 'user': request.user}\n request.access_token = ''\n return render(request, 'home.html', context)\n\n\n@login_required(login_url='/login/hbp/')\ndef config(request):\n '''Render the config file'''\n\n res = requests.get(settings.HBP_ENV_URL)\n config = res.json()\n\n # Use this app client ID\n config['auth']['clientId'] = settings.SOCIAL_AUTH_HBP_KEY\n\n # Add user token information\n logger.debug(\"user = {}\".format(request.user))\n config['auth']['token'] = {\n 'access_token': get_access_token(request.user.social_auth.get()),\n 'token_type': get_token_type(request.user.social_auth.get()),\n 'expires_in': request.session.get_expiry_age(),\n }\n config['build'] = settings.BUILD_INFO\n\n return HttpResponse(json.dumps(config), content_type='application/json')\n\n\ndef mkdir_p(path):\n # not needed in Python >= 3.2, use os.makedirs(path, exist_ok=True)\n try:\n os.makedirs(path)\n except OSError as exc:\n if exc.errno == errno.EEXIST and os.path.isdir(path):\n pass\n else:\n raise\n\n\n@login_required(login_url='/login/hbp/')\ndef copy_datafiles_to_storage(request, target, job_id):\n # get list of output data files from job_id\n job = Job.objects.get(pk=job_id)\n datalist = job.output_data.all()\n # for now, we copy all files. In future, could allow selection of subset\n\n # todo: check that the files haven't already been copied to the collab\n\n if datalist:\n # download to local storage\n server_paths = [urlparse(item.url)[2] for item in datalist]\n if len(server_paths) > 1:\n common_prefix = os.path.commonprefix(server_paths)\n assert common_prefix[-1] == \"/\"\n else:\n common_prefix = os.path.dirname(server_paths[0])\n relative_paths = [os.path.relpath(p, common_prefix) for p in server_paths]\n\n local_dir = tempfile.mkdtemp()\n for relative_path, dataitem in zip(relative_paths, datalist):\n url = dataitem.url\n (scheme, netloc, path, params, query, fragment) = urlparse(url)\n if not scheme:\n url = \"file://\" + url\n local_path = os.path.join(local_dir, relative_path)\n dir = os.path.dirname(local_path)\n mkdir_p(dir)\n urlretrieve(url, local_path)\n\n # upload files\n if target == \"collab\":\n target_paths = copy_datafiles_to_collab_storage(request, job, local_dir, relative_paths)\n else:\n target_paths = copy_datafiles_with_unicore(request, target, job, local_dir, relative_paths)\n\n # todo: change path of data files in job record to point to collab storage\n # todo: update provenance record to reflect the copy\n # todo: change the ownership metadata to reflect who launched the job rather than who initiated the copy\n\n # clean up local dir # should put most of the function body in a try..except, to ensure we always clean up\n shutil.rmtree(local_dir)\n else:\n target_paths = []\n\n return HttpResponse(json.dumps(target_paths), content_type='application/json')\n\ndef copy_datafiles_to_collab_storage(request, job, local_dir, relative_paths):\n\n # upload local files to collab storage\n #from bbp_client.oidc.client import BBPOIDCClient\n #from bbp_client.document_service.client import Client as DocClient\n #import bbp_services.client as bsc\n import hbp_service_client.document_service.client as doc_service_client\n #services = bsc.get_services()\n access_token = get_access_token(request.user.social_auth.get())\n #oidc_client = BBPOIDCClient.bearer_auth(services['oidc_service']['prod']['url'], access_token)\n #doc_client = DocClient(services['document_service']['prod']['url'], oidc_client)\n #dsc = doc_service_client.Client.__init__()\n dsc = doc_service_client.Client.new(access_token)\n\n #project = doc_client.get_project_by_collab_id(job.collab_id)\n project_dict = dsc.list_projects(None, None, None, job.collab_id)\n project = project_dict['results']\n #root = doc_client.get_path_by_id(project[\"_uuid\"])\n root = dsc.get_entity_path(project[0]['uuid'])\n collab_folder = root + \"/job_{}\".format(job.pk)\n collab_folder_2 = \"job_{}\".format(job.pk)\n #folder_id = doc_client.mkdir(collab_folder)\n folder = dsc.create_folder(collab_folder_2, str(project[0]['uuid']))\n folder_id = folder['uuid']\n\n collab_paths = []\n for relative_path in relative_paths:\n collab_path = os.path.join(collab_folder, relative_path)\n cps = collab_path.split('/')\n collab_path_2 = cps[3]\n if os.path.dirname(relative_path): # if there are subdirectories...\n #doc_client.makedirs(os.path.dirname(collab_path))\n collab_path_id = dsc.create_folder(collab_path_2, folder_id)\n local_path = os.path.join(local_dir, relative_path)\n\n #id = doc_client.upload_file(local_path, collab_path)\n #file = dsc.create_file(\"file_to_upload\", \"plain/text\", collab_path_id['uuid'])\n file = dsc.create_file(relative_path, \"plain/text\", folder_id)\n with open(local_path, 'rb') as fp:\n file_contents = fp.read()\n\n id = dsc.upload_file_content(file['uuid'], None, None, file_contents)\n #logging.warning(\"successful upload content\")\n\n collab_paths.append(collab_path)\n content_type = mimetypes.guess_type(local_path)[0]\n if content_type:\n #doc_client.set_standard_attr(collab_path, {'_contentType': content_type})\n os.path.normpath(os.path.join('/', str(collab_path)))\n return collab_paths\n\n\n\n\ndef copy_datafiles_with_unicore(request, target, job, local_dir, relative_paths):\n\n from simqueue import unicore_client\n url = unicore_client.get_site(target)['url']\n access_token = get_access_token(request.user.social_auth.get())\n auth = unicore_client.get_oidc_auth(\"Bearer {}\".format(access_token))\n headers_query = auth.copy()\n headers_query['Accept'] = 'application/json'\n storages = requests.get(url + '/storages', headers=headers_query, verify=False).json()['storages']\n home_url = [st for st in storages if \"home\" in st.lower()][0] + '/files'\n headers_upload = auth.copy()\n headers_upload['Content-Type'] = \"application/octet-stream\"\n\n # upload files\n remote_dir = home_url + \"/neuromorphic/job_{}/\".format(job.pk)\n remote_paths = []\n for relative_path in relative_paths:\n remote_path = os.path.join(remote_dir, relative_path)\n local_path = os.path.join(local_dir, relative_path)\n with open(local_path, 'rb') as fp:\n file_contents = fp.read()\n response = requests.put(remote_path, headers=headers_upload,\n data=file_contents, verify=False)\n if response.status_code != 204:\n # bail out early\n break\n remote_paths.append(remote_path)\n\n return remote_paths\n","sub_path":"simqueue/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":7736,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"548061315","text":"\"\"\"Database\"\"\"\nimport sqlite3\n\n\"\"\"\nTables:\ngame:\n id INTEGER,\n winner INTEGER, #1 We, #2 Opponents\n \nhit:\n game INTEGER,\n in_vec_x REAL,\n in_vec_y REAL,\n out_vec_x REAL,\n out_vec_y REAL,\n pad_speed REAL,\n hit_x REAL,\n hit_y REAL\n\"\"\"\nDATABASE_NAME = 'database.db'\n\nclass GameDAO(object):\n def __init__(self, game_id, winner):\n self.game_id = game_id\n self.winner = winner\n\n def save(self):\n conn = sqlite3.connect(DATABASE_NAME)\n c = conn.cursor()\n c.execute('INSERT INTO game (id, winner) VALUES (?,?)', [self.game_id, \n self.winner])\n conn.commit()\n c.close()\n\nclass Hit(object):\n def __init__(self, game_id, hitter, in_vector, out_vector, pad, hit):\n self.game_id = game_id\n self.hitter = hitter\n if in_vector:\n self.in_vec_x = in_vector.x\n self.in_vec_y = in_vector.y\n else:\n self.in_vec_x = None\n self.in_vec_y = None\n if out_vector:\n self.out_vec_x = out_vector.x\n self.out_vec_y = out_vector.y\n else:\n self.out_vec_x = None\n self.out_vec_y = None\n if pad:\n self.pad_speed = pad.vector.y\n else:\n self.pad_speed = None\n if hit:\n self.hit_x = hit.x\n self.hit_y = hit.y\n else:\n self.hit_x = None\n self.hit_y = None\n \n def save(self):\n conn = sqlite3.connect(DATABASE_NAME)\n c = conn.cursor()\n c.execute('INSERT INTO hit (game, in_vec_x, in_vec_y, out_vec_x, \\\n out_vec_y, pad_speed, hit_x, hit_y) VALUES (?,?,?,?,?,?,?,?)',\n [self.game_id, self.in_vec_x, self.in_vec_y, self.out_vec_x, \n self.out_vec_y, self.pad_speed, self.hit_x, self.hit_y])\n conn.commit()\n c.close()\n\ndef create_tables():\n conn = sqlite3.connect(DATABASE_NAME)\n c = conn.cursor()\n c.execute('''CREATE TABLE game (id text, winner INTEGER)''')\n c.execute('''CREATE TABLE hit (game INTEGER, hitter INTEGER, in_vec_x REAL,\\\n in_vec_y REAL, out_vec_x REAL, out_vec_y REAL, pad_speed REAL, \\\n hit_x REAL, hit_y REAL)''')\n conn.commit()\n c.close()","sub_path":"backup_bot1/dao.py","file_name":"dao.py","file_ext":"py","file_size_in_byte":2303,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"329438472","text":"# %load q07_extras/build.py\n# Default Imports\nfrom greyatomlib.python_getting_started.q01_read_data.build import read_data\ndata = read_data()\n\n# Your Solution\ndef extras_runs(data=data):\n\n # Write your code here\n difference =0\n extras_1 = []\n extras_2 = []\n balls_1 = data['innings'][0]['1st innings']['deliveries']\n balls_2 = data['innings'][1]['2nd innings']['deliveries']\n \n for delivery in balls_1:\n for n in delivery.values():\n if ('extras' in n.keys()):\n extras_1 += n['extras'].values()\n \n for delivery in balls_2:\n for n in delivery.values():\n if ('extras' in n.keys()):\n extras_2 += n['extras'].values()\n\n difference = len(extras_2) - len(extras_1)\n return difference\n\nextras_runs()\n\n\n","sub_path":"q07_extras/build.py","file_name":"build.py","file_ext":"py","file_size_in_byte":801,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"584830874","text":"import os\nimport sys\nfrom pathlib import Path\nimport random\n\nimport yaml\nfrom PySide2 import QtWidgets\nfrom PySide2.QtCore import Qt, QTimer, QEvent\nfrom PySide2.QtWidgets import QMainWindow, QAbstractButton, QComboBox, QSpinBox, QListView, QCheckBox, \\\n QRadioButton, QFileDialog, QMessageBox, QErrorMessage\n\nfrom logic.constants import ALL_TYPES\nfrom options import OPTIONS, Options\nfrom gui.progressdialog import ProgressDialog\nfrom gui.guithreads import RandomizerThread, ExtractSetupThread\nfrom ssrando import Randomizer, VERSION\nfrom gui.ui_randogui import Ui_MainWindow\nfrom witmanager import WitManager\n\n# Allow keyboard interrupts on the command line to instantly close the program.\nimport signal\n\nsignal.signal(signal.SIGINT, signal.SIG_DFL)\n\n\nclass RandoGUI(QMainWindow):\n def __init__(self, options: Options):\n super().__init__()\n\n self.wit_manager = WitManager(Path('.').resolve())\n self.randothread = None\n self.error_msg = None\n self.progress_dialog = None\n self.randomize_after_iso_extract = False\n\n self.ui = Ui_MainWindow()\n self.ui.setupUi(self)\n\n self.setWindowTitle(\"Skyward Sword Randomizer v\" + VERSION)\n\n self.options = options\n self.settings_path = \"settings.txt\"\n if os.path.isfile(self.settings_path):\n with open(self.settings_path) as f:\n try:\n self.options.update_from_permalink(f.readline())\n except Exception as e:\n print(\"couldn't update from saved settings!\", e)\n\n self.option_map = {}\n for option_key, option in OPTIONS.items():\n if option[\"name\"] != \"Banned Types\" and option[\"name\"] != \"Seed\":\n ui_name = option.get('ui', None)\n self.option_map[ui_name] = option\n if not ui_name:\n continue\n widget = getattr(self.ui, ui_name)\n widget.installEventFilter(self)\n if isinstance(widget, QAbstractButton):\n widget.setChecked(self.options[option_key])\n widget.clicked.connect(self.update_settings)\n elif isinstance(widget, QComboBox):\n for option_val in option['choices']:\n widget.addItem(str(option_val))\n widget.setCurrentIndex(option['choices'].index(self.options[option_key]))\n widget.currentIndexChanged.connect(self.update_settings)\n elif isinstance(widget, QListView):\n pass\n elif isinstance(widget, QSpinBox):\n if 'min' in option:\n widget.setMinimum(option['min'])\n if 'max' in option:\n widget.setMaximum(option['max'])\n widget.setValue(self.options[option_key])\n widget.valueChanged.connect(self.update_settings)\n\n self.location_descriptions = {\n \"skyloft\": \"Enables progression items to appear on Skyloft\",\n \"sky\": \"Enables progression items to appear in The Sky\",\n \"thunderhead\": \"Enables progression items to appear in The Thunderhead\",\n \"faron\": \"Enables progression items to appear in the Faron Province\",\n \"eldin\": \"Enables progression items to appear in the Eldin Province\",\n \"lanayru\": \"Enables progression items to appear in the Lanayru Province\",\n \"dungeon\": \"Enables progression items to appear in dungeons\",\n \"mini_dungeon\": \"Enables progression items to appear inside Mini Dungeons (i.e. the nodes in \"\n \"Lanayru Desert)\",\n \"free_gift\": \"Enables progression items to appear as free gifts from NPCs (i.e. the shield from \"\n \"Professor Owlan)\",\n \"freestanding\": \"Enables progression items to appear as freestanding items in the world \"\n \"(does not include the freestanding gratitude crystals)\",\n \"miscellaneous\": \"Enables progression items to appear in miscellaneous locations that don't fit into \"\n \"any other category (i.e. overworld chests) \",\n \"silent_realm\": \"Enables progression items to appear as rewards for completing Silent Realm trials\",\n \"digging\": \"Enables progression items to appear in digging spots in the world (does not include Mogma \"\n \"Mitts checks, such as the one in Volcano Summit or in Fire Sanctuary)\",\n \"bombable\": \"Enables progression items to appear behind bombable walls or other bombable structures\",\n \"combat\": \"Enables progression items to appear as rewards for combat or completing a quest involving \"\n \"combat (i.e. Digging Mitts fight, Kikwi rescue). Does not impact combat within dungeons\",\n \"song\": \"Enables progression items to appear in place of learning songs (from Isle of Song, Ballad of the \"\n \"Goddess in Sealed Temple, Song of the Hero from Levias)\",\n \"spiral_charge\": \"Enables progression items to appear in the chests in the sky requiring Spiral Charge to\"\n \" access\",\n \"minigame\": \"Enables progression items to appear as rewards from winning minigames\",\n \"crystal\": \"Enables progression items to appear as loose crystals (currently not randomized and must \"\n \"always be enabled)\",\n \"short\": \"Enables progression items to appear as rewards for completing short quests (i.e. rescuing\"\n \" Orielle)\",\n \"long\": \"Enables progression items to appear as rewards for completing long quests (i.e. Peatrice)\",\n \"fetch\": \"Enables progression items to appear as rewards for returning items to NPCs \",\n \"crystal_quest\": \"Enables progression items to appear as rewards for completing Gratitude Crystal quests\",\n \"scrapper\": \"Enables progression items to appear as rewards for Scrapper Quests\",\n \"peatrice\": \"Enables a progression item to appear as the reward for completing the Peatrice side quest\",\n\n \"beedle\": \"Enables progression items to be sold in Beedle's shop\",\n \"cheap\": \"Enables progression items to be sold for 300 rupees or less. Applies to all shops where \"\n \"progression items can appear.\",\n \"medium\": \"Enables progression items to be sold for between 300 and 1000 rupees. Applies to all \"\n \"shops where progression items can appear\",\n \"expensive\": \"Enables progression items to be sold for more than 1000 rupees. Appleis to all shops\"\n \"where progression items can appear\",\n\n \"goddess\": \"Enables progression items to appear as items in Goddess Chests\",\n \"faron_goddess\": \"Enables progression items to appear in the Goddess Chests linked to the Goddess Cubes in \"\n \"Faron Woods and Deep Woods\",\n \"eldin_goddess\": \"Enables progression items to appear in the Goddess Chests linked to the Goddess Cubes in \"\n \"the main part of Eldin Volcano and Mogma Turf\",\n \"lanayru_goddess\": \"Enables progression items to appear in the Goddess Chests linked to the Goddess Cubes \"\n \"in the main part of Lanayru Desert, Temple of Time and Lanayru Mines\",\n \"floria_goddess\": \"Enables progression items to appear in the Goddess Chests linked to the Goddess Cubes \"\n \"in Lake Floria\",\n \"summit_goddess\": \"Enables progression items to appear in the Goddess Chests linked to the Goddess Cubes \"\n \"in Volcano Summit\",\n \"sand_sea_goddess\": \"Enables progression items to appear in the Goddess Chests linked to the Goddess Cubes \"\n \"in Sand Sea\",\n }\n for check_type in ALL_TYPES:\n widget = getattr(self.ui, \"progression_\" + check_type.replace(\" \", \"_\"))\n widget.setChecked(not check_type in self.options['banned-types'])\n if check_type == 'crystal':\n widget.setEnabled(False)\n widget.clicked.connect(self.update_settings)\n widget.installEventFilter(self)\n\n self.ui.ouput_folder_browse_button.clicked.connect(self.browse_for_output_dir)\n self.ui.randomize_button.clicked.connect(self.randomize)\n self.ui.permalink.textChanged.connect(self.permalink_updated)\n self.ui.seed.textChanged.connect(self.update_settings)\n self.ui.progression_goddess.clicked.connect(self.goddess_cubes_toggled)\n self.ui.seed_button.clicked.connect(self.gen_new_seed)\n self.update_ui_for_settings()\n self.set_option_description(None)\n\n if 'NOGIT' in VERSION:\n self.error_msg = QErrorMessage()\n self.error_msg.showMessage('Running from source without git is not supported!')\n\n elif not self.wit_manager.actual_extract_already_exists():\n self.ask_for_clean_iso()\n\n def ask_for_clean_iso(self):\n selected = QMessageBox.question(self, 'Extract now?',\n 'For randomizing purposes, a clean NTSC-U 1.00 ISO is needed, browse for it now? This is only needed once',\n defaultButton=QMessageBox.Yes)\n if selected == QMessageBox.Yes:\n self.browse_for_iso()\n else:\n self.randomize_after_iso_extract = False\n\n def randomize(self):\n if not self.randothread is None:\n print('ERROR: tried to randomize multiple times at once!')\n return\n dry_run = self.options['dry-run']\n if not (dry_run or self.wit_manager.actual_extract_already_exists()):\n self.randomize_after_iso_extract = True\n self.ask_for_clean_iso()\n return\n # make sure user can't mess with the options now\n self.rando = Randomizer(self.options.copy())\n\n if dry_run:\n extra_steps = 1 # done\n else:\n extra_steps = 101 # wit create wbfs + done\n\n self.progress_dialog = ProgressDialog(\"Randomizing\", \"Initializing...\",\n self.rando.get_total_progress_steps() + extra_steps)\n self.randomizer_thread = RandomizerThread(self.rando, self.wit_manager, self.options['output-folder'])\n self.randomizer_thread.update_progress.connect(self.ui_progress_callback)\n self.randomizer_thread.randomization_complete.connect(self.randomization_complete)\n self.randomizer_thread.error_abort.connect(self.on_error)\n self.randomizer_thread.start()\n\n def ui_progress_callback(self, current_action, completed_steps, total_steps=None):\n self.progress_dialog.setValue(completed_steps)\n self.progress_dialog.setLabelText(current_action)\n if not total_steps is None:\n self.progress_dialog.setMaximum(total_steps)\n\n def on_error(self, message):\n self.error_msg = QErrorMessage(self)\n self.progress_dialog.reset()\n self.error_msg.showMessage(message)\n\n def randomization_complete(self):\n self.progress_dialog.reset()\n\n if self.options['no-spoiler-log']:\n text = f\"\"\"Randomization complete. RANDO HASH: {self.rando.randomizer_hash}\"\"\"\n else:\n text = f\"\"\"Randomization complete. RANDO HASH: {self.rando.randomizer_hash} \n If you get stuck, check the progression spoiler log in the output folder.\"\"\"\n\n self.complete_dialog = QMessageBox()\n self.complete_dialog.setTextFormat(Qt.TextFormat.RichText)\n self.complete_dialog.setWindowTitle(\"Randomization complete\")\n self.complete_dialog.setText(text)\n self.complete_dialog.setWindowIcon(self.windowIcon())\n self.complete_dialog.show()\n self.randomizer_thread = None\n\n def browse_for_iso(self):\n clean_iso_path, selected_filter = QFileDialog.getOpenFileName(self, \"Select Clean Skyward Sword NTSC-U 1.0 ISO\",\n None, \"Wii ISO Files (*.iso)\")\n if not clean_iso_path:\n return\n self.progress_dialog = ProgressDialog(\"Extracting Game Files\", \"Initializing...\", 100)\n self.progress_dialog.setAutoClose(True)\n self.extract_thread = ExtractSetupThread(self.wit_manager, clean_iso_path, None)\n self.extract_thread.update_total_steps.connect(lambda total_steps: self.progress_dialog.setMaximum(total_steps))\n self.extract_thread.update_progress.connect(self.ui_progress_callback)\n\n def on_complete():\n self.progress_dialog.reset()\n if self.randomize_after_iso_extract:\n self.randomize()\n\n self.extract_thread.extract_complete.connect(on_complete)\n\n def on_error(msg):\n self.progress_dialog.reset()\n self.error_msg = QMessageBox.critical(self, \"Error\", msg)\n\n self.extract_thread.error_abort.connect(on_error)\n self.extract_thread.start()\n\n def browse_for_output_dir(self):\n if self.options['output-folder'] and os.path.isfile(self.options['output-folder']):\n default_dir = os.path.dirname(self.options['output-folder'])\n else:\n default_dir = None\n\n output_folder = QFileDialog.getExistingDirectory(self, \"Select output folder\", default_dir)\n if not output_folder:\n return\n self.ui.output_folder.setText(output_folder)\n self.update_settings()\n\n def update_ui_for_settings(self):\n self.ui.output_folder.setText(str(self.options['output-folder']))\n self.ui.seed.setText(str(self.options[\"seed\"]))\n current_settings = self.options.copy()\n for option_key, option in OPTIONS.items():\n if option[\"name\"] != \"Banned Types\" and option[\"name\"] != \"Seed\":\n ui_name = option.get('ui', None)\n if not ui_name:\n continue\n widget = getattr(self.ui, ui_name)\n if isinstance(widget, QAbstractButton):\n widget.setChecked(current_settings[option_key])\n elif isinstance(widget, QComboBox):\n widget.setCurrentIndex(option['choices'].index(current_settings[option_key]))\n elif isinstance(widget, QListView):\n pass\n elif isinstance(widget, QSpinBox):\n widget.setValue(current_settings[option_key])\n getattr(self.ui, f\"label_for_{ui_name}\").installEventFilter(self)\n\n for check_type in ALL_TYPES:\n widget = getattr(self.ui, \"progression_\" + check_type.replace(\" \", \"_\"))\n widget.setChecked(not check_type in current_settings['banned-types'])\n self.ui.permalink.setText(current_settings.get_permalink())\n\n def save_settings(self):\n with open(self.settings_path, \"w\") as f:\n f.write(self.options.get_permalink())\n\n def update_settings(self):\n self.options.set_option('output-folder', self.ui.output_folder.text())\n try:\n self.options.set_option(\"seed\", int(self.ui.seed.text()))\n except ValueError:\n if self.ui.seed.text() == \"\":\n self.options.set_option(\"seed\", -1)\n else:\n # TODO: give an error dialog or some sort of error message that the seed is invalid\n pass\n\n for option_command, option in OPTIONS.items():\n if option[\"name\"] != \"Banned Types\" and option[\"name\"] != \"Seed\":\n ui_name = option.get('ui', None)\n if not ui_name:\n continue\n self.options.set_option(option_command, self.get_option_value(ui_name))\n\n self.options.set_option(\"banned-types\", self.get_banned_types())\n self.save_settings()\n self.ui.permalink.setText(self.options.get_permalink())\n\n def get_option_value(self, option_name):\n widget = getattr(self.ui, option_name)\n if isinstance(widget, QCheckBox) or isinstance(widget, QRadioButton):\n return widget.isChecked()\n elif isinstance(widget, QComboBox):\n return widget.itemText(widget.currentIndex())\n elif isinstance(widget, QSpinBox):\n return widget.value()\n elif isinstance(widget, QListView):\n pass\n else:\n print(\"Option widget is invalid: %s\" % option_name)\n\n def get_banned_types(self):\n banned_types = []\n for check_type in ALL_TYPES:\n widget = getattr(self.ui, \"progression_\" + check_type.replace(\" \", \"_\"))\n if not widget.isChecked():\n banned_types.append(check_type)\n return banned_types\n\n def eventFilter(self, target, event):\n if event.type() == QEvent.Enter:\n ui_name = target.objectName()\n\n if ui_name.startswith(\"progression_\"):\n ui_name = ui_name[len(\"progression_\"):]\n self.set_option_description(self.location_descriptions[ui_name])\n\n else:\n if ui_name.startswith(\"label_for_\"):\n ui_name = ui_name[len(\"label_for_\"):]\n\n option = self.option_map[ui_name]\n self.set_option_description(option[\"help\"])\n\n return True\n elif event.type() == QEvent.Leave:\n self.set_option_description(None)\n return True\n\n return QMainWindow.eventFilter(self, target, event)\n\n def set_option_description(self, new_description):\n if new_description is None:\n self.ui.option_description.setText(\"(Hover over an option to see a description of what it does.)\")\n self.ui.option_description.setStyleSheet(\"color: grey;\")\n else:\n self.ui.option_description.setText(new_description)\n self.ui.option_description.setStyleSheet(\"\")\n\n def permalink_updated(self):\n try:\n self.options.update_from_permalink(self.ui.permalink.text())\n except ValueError as e:\n # Ignore errors from faultly permalinks, with updating ui it gets reset anyways\n print(e)\n except IndexError as e:\n print(e)\n self.update_ui_for_settings()\n\n def goddess_cubes_toggled(self):\n enabled = self.ui.progression_goddess.isChecked()\n self.ui.progression_faron_goddess.setEnabled(enabled)\n self.ui.progression_eldin_goddess.setEnabled(enabled)\n self.ui.progression_lanayru_goddess.setEnabled(enabled)\n self.ui.progression_floria_goddess.setEnabled(enabled)\n self.ui.progression_summit_goddess.setEnabled(enabled)\n self.ui.progression_sand_sea_goddess.setEnabled(enabled)\n \n def gen_new_seed(self):\n self.ui.seed.setText(str(random.randrange(0, 1_000_000)))\n\n\ndef run_main_gui(options: Options):\n app = QtWidgets.QApplication([])\n\n widget = RandoGUI(options)\n widget.show()\n\n sys.exit(app.exec_())\n\n\nif __name__ == \"__main__\":\n run_main_gui()\n","sub_path":"gui/randogui.py","file_name":"randogui.py","file_ext":"py","file_size_in_byte":19260,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"256779570","text":"from pathlib import Path\nimport pandas as pd\nimport gmsh\nimport pygimli as pg\nimport pygimli.meshtools as mt\nfrom pygimli.physics.ert import ERTManager\n\n# Path to directory with geometry and ERT experiment design\npath = Path.cwd()\n\n# Starting it up (tutorial t1.py)\ngmsh.initialize()\ngmsh.option.setNumber(\"General.Terminal\", 1)\ngmsh.option.setString(\"Geometry.OCCTargetUnit\", \"M\") # Units to meters (t20.py)\ngmsh.model.add(\"Dike for Modeling\")\n# Set characteristic lengths, controls mesh size at points\ncl_elec = 0.1\ncl_dike = 0.6\ncl_outer = 30\n\n# Volumes (3), Surfaces (2), Curve (1), Point (0)\n# Load a BREP or STEP file (t20.py & demo step_assembly.py)\n# geom = gmsh.model.occ.importShapes(str(path.joinpath(\"dike_mod.step\")))\n# gmsh.model.occ.healShapes()\n# gmsh.model.occ.synchronize()\ngmsh.option.setNumber(\"Geometry.OCCScaling\", 0.001)\ngeom = gmsh.model.occ.importShapes(str(path.joinpath(\"dike_mod.brep\")))\n\n\n# Read electrode positions from Excel. Electrodes are put at 2 cm depth, \n# such that they can be embeded in the volume of the dike. Embeding the\n# electrodes into the surface elements is complicated.\nelec_depth = 0.02 # elec depth [m]\npos = pd.read_excel(\n path.joinpath(\"ERT_pos_and_scheme.xlsx\"), \n sheet_name=\"elec_pos\")\npos[\"z\"] = pos[\"z\"] - elec_depth\nne = len(pos) # Number of electrodes\n# Gmsh geometry tags of relevant parts. Find the tags in the Gmsh interface.\ntags = {\"outer region\": 2,\n \"dike\": 3,\n \"channel\": 1,\n \"surface\": [7, 11, 12, 13, 21, 23, 24, \n 25, 27, 29, 30, 31],\n \"boundary\": [8, 14, 15, 16, 20], # \"Underground\"\n \"electrodes\": [0] * ne}\n# Add the electrodes to the Gmsh model and put the tags into the Dict\nfor i, xyz in pos.iterrows():\n tag = int(200 + xyz[\"elec #\"])\n gmsh.model.occ.addPoint(xyz[\"x\"], \n xyz[\"y\"], \n xyz[\"z\"], \n cl_elec, \n tag)\n tags[\"electrodes\"][i] = tag\n\n# Syncronize CAD representation with the Gmsh model (t1.py)\n# Otherwise gmsh.model.get* methods don't work.\ngmsh.model.occ.synchronize()\n\n# Set mesh sizes for the dike and outer region.\n# I think that the order, in which mesh sizes are set, matters. Big -> Small \ngmsh.model.mesh.setSize( # Especially t16.py, also t2; 15; 18; 21\n gmsh.model.getBoundary( # get dimTags of boundary elements of\n (3, tags[\"outer region\"]), # dimTag: (dim, tag)\n recursive=True), # recursive -> dimTags of points\n cl_outer)\ngmsh.model.mesh.setSize(\n gmsh.model.getBoundary(\n (3, tags[\"dike\"]),\n # (3, tags[\"channel\"]),\n recursive=True),\n cl_dike)\n\n# Embed electrodes in dike volume. (t15.py)\ngmsh.model.mesh.embed(0, tags[\"electrodes\"], 3, tags[\"dike\"])\n\n# Further refine the mesh with a background field (t10.py)\n# LcMax - /------------------\n# /\n# /\n# /\n# LcMin -o----------------/\n# | | |\n# Point DistMin DistMax\n# Field 1: Distance to electrodes\ngmsh.model.mesh.field.add(\"Distance\", 1)\ngmsh.model.mesh.field.setNumbers(1, \"NodesList\", tags[\"electrodes\"])\n# Field 2: Threshold that dictates the mesh size of the background field\ngmsh.model.mesh.field.add(\"Threshold\", 2)\ngmsh.model.mesh.field.setNumber(2, \"IField\", 1)\ngmsh.model.mesh.field.setNumber(2, \"LcMin\", cl_elec)\ngmsh.model.mesh.field.setNumber(2, \"LcMax\", cl_dike)\ngmsh.model.mesh.field.setNumber(2, \"DistMin\", 0.2)\ngmsh.model.mesh.field.setNumber(2, \"DistMax\", 1.5)\ngmsh.model.mesh.field.setNumber(2, \"StopAtDistMax\", 1)\ngmsh.model.mesh.field.setAsBackgroundMesh(2)\n\n\n# Specify physical groups (t1.py)\n# The physical group tags are imported to PyGIMLi (right?)\n# Physical Volumes, \"Regions\" in pyGIMLi\npgrp = gmsh.model.addPhysicalGroup(3, [tags[\"outer region\"]], 1) #(dim, tag, pgrp tag)\ngmsh.model.setPhysicalName(3, pgrp, \"Outer Region\") # Physical group name in Gmsh\npgrp = gmsh.model.addPhysicalGroup(3, [tags[\"dike\"]], 2)\ngmsh.model.setPhysicalName(3, pgrp, \"Dike\")\npgrp = gmsh.model.addPhysicalGroup(3, [tags[\"channel\"]], 3)\ngmsh.model.setPhysicalName(3, pgrp, \"Channel\")\n# Physical Surfaces, \"Boundaries\" in pyGIMLi,\n# pgrp tag = 1 --> Free Surface | pgrp tag > 1 --> Mixed BC\npgrp = gmsh.model.addPhysicalGroup(2, tags[\"surface\"], 1)\ngmsh.model.setPhysicalName(2, pgrp, \"Surface\")\npgrp = gmsh.model.addPhysicalGroup(2, tags[\"boundary\"], 2)\ngmsh.model.setPhysicalName(2, pgrp, \"Underground Boundary\")\n# Physical Points, \"Electrodes / Sensors\" in pyGIMLi, pgrp tag 99\npgrp = gmsh.model.addPhysicalGroup(0, tags[\"electrodes\"], 99)\ngmsh.model.setPhysicalName(0, pgrp, \"Electrodes\")\n\n# Generate mesh\ngmsh.model.mesh.generate(3)\ngmsh.write(str(path.joinpath(\"dike_mod.msh\")))\n\n# Run the Gmsh application to verify that importing the geometry went correctly.\n# gmsh.fltk.run()\ngmsh.finalize()\n\n\n\n# Write to BERT/pyGIMLi unified data format .dat file. This file tells PyGIMLi \n# what measurement scheme should be used in modeling and inversion.\nscheme = pd.read_excel(\n path.joinpath(\"ERT_pos_and_scheme.xlsx\"), \n sheet_name=\"ERT_scheme\")\n\nert_dat = open('ert.dat', 'w')\nert_dat.write(f'{ne}\\n' + '# x y z\\n')\nfor i, xyz in pos.iterrows():\n ert_dat.write('%.3f %.3f %.3f\\n' % (xyz['x'], xyz['y'], xyz['z']))\nert_dat.write(f'{scheme.shape[0]}\\n')\nert_dat.write('# a b m n\\n')\nfor i, abmn in scheme.iterrows():\n ert_dat.write('%d %d %d %d\\n' % (abmn['A'], abmn['B'], abmn['M'], abmn['N']))\nert_dat.write('0')\nert_dat.close()\n\n\n### Read Gmsh .msh and model ERT ####\nmesh_mod = mt.readGmsh(str(path.joinpath(\"dike_mod.msh\")))\n# Read electrode positions and ERT scheme from .dat file\nert_dat = pg.importData('ert.dat')\n# Initiate PyGIMLi ERTManager object\nert = ERTManager()\n# Model ERT\nrhomap = [[1, 10.], [2, 10.], [3, 300.]]\ndata_mod = ert.simulate(mesh_mod, res=rhomap, scheme=ert_dat)\ndata_mod.save('ert_mod.dat')","sub_path":"pygimli/mesh_dike.py","file_name":"mesh_dike.py","file_ext":"py","file_size_in_byte":5945,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"552095046","text":"'''\nMain objects for working with electrophysiology data\n'''\n\nimport os\nimport numpy as np\nimport pandas as pd\nfrom jaratoolbox import loadopenephys\nfrom jaratoolbox import loadbehavior\nfrom jaratoolbox import settings\n\n# Define the event channel mapping for each paradigm. For each paradigm, you\n# should include a dict like this: {eventName:intanEventChannel}\n# where intanEventChannel is the digital input channel that your event TTL is connected to\nCHANNELMAPS = {'am_tuning_curve': {'stim':0, 'trialStart':1, 'laser':2, 'soundDetector':5},\n 'bandwidth_am':{'stim':0, 'trialStart':1, 'laser':2, 'soundDetector':5},\n 'laser_tuning_curve':{'stim':0, 'trialStart':1, 'laser':2},\n '2afc':{'stim':0, 'trialStart':1}}\n\nclass Cell(object):\n def __init__(self, dbRow, useModifiedClusters=False):\n '''\n Things to check at the end:\n * When looping through cells, make sure that nothing is preserved from iteration to the next\n Args:\n dbRow (pandas.core.series.Series): A row from a dataframe. Must contain at least:\n * sessionType\n useModifiedClusters (bool): Whether to load the modified cluster files created after cleaning clusters, if they exist.\n '''\n if not isinstance(dbRow, pd.core.series.Series):\n raise TypeError('This object must be initialized with a pandas Series object.')\n self.dbRow = dbRow\n self.useModifiedClusters = useModifiedClusters\n\n # We use these variables many times to load data\n # Date and depth are not really used to load the data\n self.subject = dbRow['subject']\n self.tetrode = dbRow['tetrode']\n self.cluster = dbRow['cluster']\n self.ephysBaseDir = os.path.join(settings.EPHYS_PATH, self.subject)\n\n def load(self, sessiontype, behavClass=None):\n '''\n Load the spikes, events, and behavior data for a single session. Loads the LAST recorded\n session of the type that was recorded from the cell.\n Args:\n sessiontype (str): the type of session to load data for.\n behavClass (jaratoolbox.loadbehavior Class): The loading class to use, each class of behavData will have different methods.\n Returns:\n ephysData (dict):'spikeTimes' (array), 'samples' (array) and 'events' (dict)\n The dictionary 'events' contains two keys for each type of event\n used in the paradigm - one for the eventOn, when the event turns on,\n and one for the eventOff, when the event turns off. These will look like\n 'stimOn' and 'stimOff' for the event type 'stim' defined in the paradigm.\n behavData (jaratoolbox.loadbehavior.BehaviorData): Behavior data dict\n '''\n sessionInds = self.get_session_inds(sessiontype)\n sessionIndToUse = sessionInds[-1] #NOTE: Taking the last session of this type!\n ephysData, behavData = self.load_by_index(sessionIndToUse, behavClass=behavClass)\n return ephysData, behavData\n\n def get_session_inds(self, sessiontype):\n '''\n Get the indices of sessions of a particular sessiontype that were recorded for the cell.\n Args:\n sessiontype (str): The type of session to look for (as written in the inforec file)\n Returns:\n sessionInds (list): List of the indices for this session type\n '''\n sessionInds = [i for i, st in enumerate(self.dbRow['sessionType']) if st==sessiontype]\n return sessionInds\n\n def load_by_index(self, sessionInd, behavClass=None):\n '''\n Load both ephys and behavior data for a session using the absolute index in the list of sessions for the cell.\n Args:\n sessionInd (int): The index of the session in the list of sessions recorded for the cell.\n behavClass (jaratoolbox.loadbehavior Class): The loading class to use, each class of behavData will have different methods.\n Returns:\n ephysData (list): Spiketimes (array), samples (array) and events (dict)\n behavData (jaratoolbox.loadbehavior.BehaviorData): Behavior data dict\n '''\n ephysData = self.load_ephys_by_index(sessionInd)\n behavData = self.load_behavior_by_index(sessionInd, behavClass=behavClass)\n return ephysData, behavData\n\n def load_ephys_by_index(self, sessionInd):\n '''\n Load the ephys data for a session using the absolute index in the list of sessions for the cell.\n Args:\n sessionInd (int): The index of the session in the list of sessions recorded for the cell.\n Returns:\n ephysData (list): Spiketimes (array), samples (array) and events (dict)\n '''\n\n (sessionDir, paradigm) = self.get_ephys_filename(sessionInd)\n #TODO: Maybe sessionDir and paradigm should be a tuple?\n ephysData = load_ephys(self.subject, paradigm, sessionDir, self.tetrode, self.cluster, useModifiedClusters=self.useModifiedClusters)\n return ephysData\n\n def get_ephys_filename(self, sessionInd):\n '''\n Return the full path for the .spikes and .events files for a session.\n Args:\n sessionInd (int): The index of the session in the list of sessions recorded for the cell.\n Returns:\n spikesFilename (str): Full path to the .spikes file\n eventsFilename (str): Full path to the .events file\n '''\n ephysTime = self.dbRow['ephysTime'][sessionInd]\n sessionDir = '{}_{}'.format(self.dbRow['date'], ephysTime)\n paradigm = self.dbRow['paradigm'][sessionInd]\n return (sessionDir, paradigm)\n\n def load_behavior_by_index(self, sessionInd, behavClass=None):\n '''\n Load the behavior data for a session using the absolute index in the list of sessions for the cell.\n Args:\n sessionInd (int): The index of the session in the list of sessions recorded for the cell.\n behavClass (jaratoolbox.loadbehavior Class): The loading class to use, each class of behavData will have different methods.\n Returns:\n behavData (jaratoolbox.loadbehavior.BehaviorData): Behavior data dict\n\n To implement in the future:\n * Allow use of different readmode for loading partial data\n * Allow use of different loading class for paradigms like FlexCategBehaviorData\n '''\n #Set the loading class for behavior data\n if behavClass==None:\n behavClass = loadbehavior.BehaviorData\n\n #Load the behavior data\n if self.dbRow['behavSuffix'][sessionInd] is not None:\n dateStr = ''.join(self.dbRow['date'].split('-'))\n fullSessionStr = '{}{}'.format(dateStr, self.dbRow['behavSuffix'][sessionInd])\n behavDataFilePath = loadbehavior.path_to_behavior_data(self.subject,\n self.dbRow['paradigm'][sessionInd],\n fullSessionStr)\n bdata = behavClass(behavDataFilePath,readmode='full')\n else:\n bdata = None\n return bdata\n\n def load_all_spikedata(self):\n '''\n Load the spike data for all recorded sessions into a set of arrays.\n Returns:\n timestamps (np.array): The timestamps for all spikes across all sessions\n samples (np.array): The samples for all spikes across all sessions\n recordingNumber (np.array): The index of the session where the spike was recorded\n '''\n samples=np.array([])\n timestamps=np.array([])\n recordingNumber=np.array([])\n for sessionInd, sessionType in enumerate(self.dbRow['sessionType']):\n try:\n ephysData = self.load_ephys_by_index(sessionInd)\n except ValueError as errMsg: #File contains no spikes\n print(str(errMsg))\n continue\n numSpikes = len(ephysData['spikeTimes'])\n sessionVector = np.zeros(numSpikes)+sessionInd\n if len(samples)==0:\n samples = ephysData['samples']\n timestamps = ephysData['spikeTimes']\n recordingNumber = sessionVector\n else:\n samples = np.concatenate([samples, ephysData['samples']])\n # Check to see if next session ts[0] is lower than self.timestamps[-1]\n # If so, add self.timestamps[-1] to all new timestamps before concat\n if not len(ephysData['spikeTimes'])==0:\n if ephysData['spikeTimes'][0] model labels\nDATASET_DATA_ORDERING_KEY = \"model_class_order\" # model output classes (same indices)\nDATASET_DATA_MODEL_MAPPING = \"model_output_mapping\" # model output classes (same indices)\nDATASET_DATA_PATCH_KEY = \"patches\"\nDATASET_DATA_PATCH_CLASS_KEY = \"class\" # class id associated to the patch\nDATASET_DATA_PATCH_SPLIT_KEY = \"split\" # group train/test of the patch\nDATASET_DATA_PATCH_CROPS_KEY = \"crops\" # extra data such as coordinates\nDATASET_DATA_PATCH_IMAGE_KEY = \"image\" # original image path that was used to generate the patch\nDATASET_DATA_PATCH_PATH_KEY = \"path\" # crop image path of the generated patch\nDATASET_DATA_PATCH_MASK_KEY = \"mask\" # mask image path of the generated patch\nDATASET_DATA_PATCH_MASK_PATH_KEY = 'mask' # original mask path that was used to generate the patch\nDATASET_DATA_PATCH_INDEX_KEY = \"index\" # data loader getter index reference\nDATASET_DATA_PATCH_FEATURE_KEY = \"feature\" # annotation reference id\nDATASET_BACKGROUND_ID = 999 # background class id\nDATASET_DATA_PATCH_DONTCARE = 255 # dontcare value in the test set\nDATASET_DATA_CHANNELS = \"channels\" # channels information\n# see bottom for mapping definition\nMAPPING_TASK = \"task\"\nMAPPING_LOADER = \"loader\"\nMAPPING_RESULT = \"result\"\nMAPPING_TESTER = \"tester\"\n\ndef update_class_mapping(class_mappings, model_task):\n # type: (List[Tuple[Union[str,int], Union[str,int]]], str, Optional[str]) -> None\n \"\"\"Updates the model task using provided class mapping.\"\"\"\n \n model_task = thelper.tasks.utils.create_task(model_task)\n if len(model_task.class_names) != len(class_mappings):\n raise ValueError(f\"Task classes and class mapping size do not match \"\n f\"({len(model_task.class_names)} != {len(class_mappings)}) :\\n\"\n f\" {model_task.class_names}\\n {class_mappings} \")\n class_mapped = {}\n class_mappings = dict(class_mappings)\n for class_name in model_task.class_names:\n if class_name not in class_mappings:\n raise ValueError(f\"Missing mapping for class '{class_name}'.\")\n new_class = class_mappings[class_name]\n idx_class = model_task.class_indices[class_name]\n class_mapped[new_class] = idx_class\n setattr(model_task, \"_class_indices\", class_mapped)\n model_outputs_sorted_by_index = list(sorted(class_mapped.items(), key=lambda _map: _map[1]))\n setattr(model_task, \"_class_names\", [str(_map[0]) for _map in model_outputs_sorted_by_index])\n return model_task\n\ndef fully_qualified_name(obj):\n # type: (Union[Any, Type[Any]]) -> AnyStr\n \"\"\"Obtains the ``'.'`` full path definition of the object to allow finding and importing it.\"\"\"\n cls = obj if isclass(obj) else type(obj)\n return '.'.join([obj.__module__, cls.__name__])\n\ndef isclass(obj):\n # type: (Any) -> bool\n \"\"\"Evaluates ``obj`` for ``class`` type (ie: class definition, not an instance nor any other type).\"\"\"\n return isinstance(obj, six.class_types)\n\ndef fix_str_model_task(model_task):\n # type: (str) -> ParamsType\n \"\"\"\n Attempts to convert the input model task definition as literal string to the equivalent dictionary of task\n input parameters.\n\n For example, a model with classification task is expected to have the following format::\n\n \"thelper.tasks.classif.Classification(class_names=['cls1', 'cls2'], input_key='0', label_key='1', meta_keys=[])\"\n\n And will be converted to::\n\n {'class_names': ['cls1', 'cls2'], 'input_key': '0', 'label_key': '1', 'meta_keys': []}\n\n :return: dictionary of task input parameters converted from the literal string definition\n :raises ValueError: if the literal string cannot be parsed as a task input parameters definition\n \"\"\"\n try:\n if not isinstance(model_task, str):\n raise ValueError(f\"Invalid input is not a literal string for model task parsing, got '{type(model_task)}'\")\n params = model_task.split(\"(\", 1)[-1].split(\")\", 1)[0]\n params = re.sub(r\"(\\w+)\\s*=\", r\"'\\1': \", params)\n param_dict = ast.literal_eval(f\"{{{params}}}\")\n if not all([isinstance(name, str) for name in param_dict['class_names']]):\n param_dict['class_names'] = {str(k): v for k, v in param_dict[\n 'class_names'].items()} # some tasks are expecting class names as string\n return param_dict\n except ValueError:\n raise # failing ast converting raises ValueError\n except Exception as exc:\n raise ValueError(f\"Failed literal string parsing for model task, exception: [{exc!s}]\")\n\ndef maybe_download_and_extract(file_id, dest_path ):\n filename = dest_path.split('/')[-1]\n file_path = dest_path\n download_dir= osp.dirname(osp.abspath(dest_path))\n if not osp.isfile(dest_path):\n gdd.download_file_from_google_drive(file_id= file_id, dest_path= file_path)\n print(\"Download finished. Extracting files.\")\n\n if file_path.endswith(\".zip\"):\n # Unpack the zip-file.\n zipfile.ZipFile(file=file_path, mode=\"r\").extractall(download_dir)\n elif file_path.endswith((\".tar.gz\", \".tgz\")):\n # Unpack the tar-ball.\n tarfile.open(name=file_path, mode=\"r:gz\").extractall(download_dir)\n print(\"Done.\")\n else:\n print(\"Data has apparently already been downloaded and unpacked.\")\n\nclass ImageFolderSegDataset(thelper.data.SegmentationDataset):\n \"\"\"Image folder dataset specialization interface for segmentation tasks.\n\n This specialization is used to parse simple image subfolders, and it essentially replaces the very\n basic ``torchvision.datasets.ImageFolder`` interface with similar functionalities. It it used to provide\n a proper task interface as well as path metadata in each loaded packet for metrics/logging output.\n\n .. seealso::\n | :class:`thelper.data.parsers.ImageDataset`\n | :class:`thelper.data.parsers.SegmentationDataset`\n \"\"\"\n\n def __init__(self, root, transforms=None, channels= None, image_key=\"image\", label_key=\"label\", mask_key=\"mask\", mask_path_key=\"mask_path\", path_key=\"path\", idx_key=\"idx\"):\n \"\"\"Image folder dataset parser constructor.\"\"\"\n self.root = root\n if self.root is None or not os.path.isdir(self.root):\n raise AssertionError(\"invalid input data root '%s'\" % self.root)\n class_map = {}\n for child in os.listdir(self.root):\n if os.path.isdir(os.path.join(self.root, child)):\n class_map[child] = []\n if not class_map:\n raise AssertionError(\"could not find any image folders at '%s'\" % self.root)\n image_exts = [\".jpg\", \".jpeg\", \".bmp\", \".png\", \".ppm\", \".pgm\", \".tif\"]\n self.image_key = image_key\n self.path_key = path_key\n self.idx_key = idx_key\n self.label_key = label_key\n self.mask_key = mask_key\n self.mask_path_key = mask_path_key\n self.channels = channels if channels else [1, 2, 3]\n samples = []\n for class_name in class_map:\n class_folder = os.path.join(self.root, class_name)\n for folder, subfolder, files in os.walk(class_folder):\n for file in files:\n ext = os.path.splitext(file)[1].lower()\n if ext in image_exts:\n class_map[class_name].append(len(samples))\n samples.append({\n self.path_key: os.path.join(folder, file),\n self.label_key: class_name\n })\n old_unsorted_class_names = list(class_map.keys())\n class_map = {k: class_map[k] for k in sorted(class_map.keys()) if len(class_map[k]) > 0}\n if old_unsorted_class_names != list(class_map.keys()):\n # new as of v0.4.4; this may only be an issue for old models trained on windows and ported to linux\n # (this is caused by the way os.walk returns folders in an arbitrary order on some platforms)\n logger.warning(\"class name ordering changed due to folder name sorting; this may impact the \"\n \"behavior of previously-trained models as task class indices may be swapped!\")\n if not class_map:\n raise AssertionError(\"could not locate any subdir in '%s' with images to load\" % self.root)\n meta_keys = [self.path_key, self.idx_key]\n super(ImageFolderSegDataset, self).__init__(class_names=list(class_map.keys()), input_key=self.image_key,\n label_key=self.label_key, meta_keys=meta_keys, transforms=transforms)\n self.samples = samples\n\n def __getitem__(self, idx):\n \"\"\"Returns the data sample (a dictionary) for a specific (0-based) index.\"\"\"\n if isinstance(idx, slice):\n return self._getitems(idx)\n if idx >= len(self.samples):\n raise AssertionError(\"sample index is out-of-range\")\n if idx < 0:\n idx = len(self.samples) + idx\n sample = self.samples[idx]\n image_path = sample[self.path_key]\n rasterfile = gdal.Open(image_path, gdal.GA_ReadOnly)\n # image = cv2.imread(image_path)\n image = []\n for raster_band_idx in range(rasterfile.RasterCount):\n curr_band = rasterfile.GetRasterBand(raster_band_idx+1) # offset, starts at 1\n band_array = curr_band.ReadAsArray()\n band_nodataval = curr_band.GetNoDataValue()\n # band_ma = np.ma.array(band_array.astype(np.float32))\n image.append(band_array)\n image = np.dstack(image)\n rasterfile = None # close input fd\n mask_path = sample[self.mask_path_key] if hasattr(self, 'mask_path_key') else None\n mask = None\n def convert(img, target_type_min, target_type_max, target_type):\n imin = img.min()\n imax = img.max()\n\n a = (target_type_max - target_type_min) / (imax - imin)\n b = target_type_max - a * imax\n new_img = (a * img + b).astype(target_type)\n return new_img\n if mask_path is not None:\n mask = cv2.imread(mask_path)\n not_zero=np.count_nonzero(mask)\n #assert not_zero > 0\n mask = mask if mask.ndim == 2 else mask[:, :, 0] # masks saved with PIL have three bands\n if self.dontcare is not None:\n mask = mask.astype(int)\n mask[(mask <= 0)] = -1\n mask[(mask > 0)] = sample[self.label_key]\n if False:\n import matplotlib\n #matplotlib.use('Agg')\n import matplotlib.pyplot as plt\n fig, axes = plt.subplots(1, 2, figsize=(10, 20))\n plt.tight_layout()\n axes[0].imshow(convert(image,0,255, np.uint8))\n axes[0].get_xaxis().set_visible(False)\n axes[0].get_yaxis().set_visible(False)\n axes[1].imshow(mask)\n axes[1].get_xaxis().set_visible(False)\n axes[1].get_yaxis().set_visible(False)\n plt.show()\n plt.savefig('/home/sfoucher/DEV/eval.png')\n plt.show()\n plt.close()\n \n if image is None:\n raise AssertionError(\"invalid image at '%s'\" % image_path)\n sample = {\n self.image_key: np.array(image.data, copy=True, dtype='float32'),\n self.mask_key: mask,\n self.label_key: sample[self.label_key],\n self.idx_key: idx,\n # **sample\n }\n # FIXME: not clear how to handle transformations on the image as well as on the mask\n # in particular for geometric transformations\n if self.transforms:\n sample = self.transforms(sample)\n return sample\n\nclass BatchTestPatchesBaseDatasetLoader(ImageFolderSegDataset):\n \"\"\"\n Batch dataset parser that loads only patches from 'test' split and matching\n class IDs (or their parents) known by the model as defined in its ``task``.\n\n .. note::\n\n Uses :class:`thelper.data.SegmentationDataset` ``__getitem__`` implementation to load image\n from a folder, but overrides the ``__init__`` to adapt the configuration to batch format.\n \"\"\"\n\n # noinspection PyMissingConstructor\n def __init__(self, dataset=None, transforms=None, split = 'test', dontcare = None, channels = None):\n if not (isinstance(dataset, dict) and len(dataset)):\n raise ValueError(\"Expected dataset parameters as configuration input.\")\n thelper.data.Dataset.__init__(self, transforms=transforms, deepcopy=False)\n self.root = dataset[\"path\"]\n # keys matching dataset config for easy loading and referencing to same fields\n self.image_key = IMAGE_DATA_KEY # key employed by loader to extract image data (pixel values)\n self.label_key = IMAGE_LABEL_KEY # class id from API mapped to match model task\n self.path_key = DATASET_DATA_PATCH_PATH_KEY # actual file path of the patch\n self.idx_key = DATASET_DATA_PATCH_INDEX_KEY # increment for __getitem__\n self.mask_key = DATASET_DATA_PATCH_MASK_KEY # actual mask path of the patch\n self.mask_path_key = DATASET_DATA_PATCH_MASK_PATH_KEY # actual mask path of the patch\n self.meta_keys = [self.path_key, self.idx_key, self.mask_key, DATASET_DATA_PATCH_CROPS_KEY,\n DATASET_DATA_PATCH_IMAGE_KEY, DATASET_DATA_PATCH_FEATURE_KEY]\n model_class_map = dataset[DATASET_DATA_KEY][DATASET_DATA_MODEL_MAPPING]\n model_class_map = {int(k): v for k, v in model_class_map.items()} # forcing the key to be integer\n class_id_to_nodel_output = dataset[DATASET_DATA_KEY][DATASET_DATA_MODEL_MAPPING]\n sample_class_ids = set()\n samples = []\n self.dontcare = dontcare # dataset.get('dontcare', None)\n # channels = dataset.get(DATASET_DATA_CHANNELS, None)\n self.channels = channels # channels if channels else [1, 2, 3] # by default we take the first 3 channels\n for patch_path, patch_info in zip(dataset[DATASET_FILES_KEY],\n dataset[DATASET_DATA_KEY][DATASET_DATA_PATCH_KEY]):\n if patch_info[DATASET_DATA_PATCH_SPLIT_KEY] == split:\n # convert the dataset class ID into the model class ID using mapping, drop sample if not found\n class_name = model_class_map.get(patch_info[DATASET_DATA_PATCH_CLASS_KEY])\n #nodel_output = class_id_to_nodel_output.get(class_name)\n if class_name is not None:\n sample_class_ids.add(class_name)\n samples.append(deepcopy(patch_info))\n samples[-1][self.path_key] = os.path.join(self.root, patch_path)\n samples[-1][self.label_key] = class_name\n samples[-1][self.mask_path_key] = None\n if not len(sample_class_ids):\n raise ValueError(\"No patch/class could be retrieved from batch loading for specific model task.\")\n self.samples = samples\n self.sample_class_ids = sample_class_ids\n\nclass BatchTestPatchesBaseSegDatasetLoader(ImageFolderSegDataset):\n \"\"\"\n Batch dataset parser that loads only patches from 'test' split and matching\n class IDs (or their parents) known by the model as defined in its ``task``.\n\n .. note::\n\n Uses :class:`thelper.data.SegmentationDataset` ``__getitem__`` implementation to load image\n from a folder, but overrides the ``__init__`` to adapt the configuration to batch format.\n \"\"\"\n\n # noinspection PyMissingConstructor\n def __init__(self, dataset=None, transforms=None, split = 'test', dontcare = None, channels = None):\n if not (isinstance(dataset, dict) and len(dataset)):\n raise ValueError(\"Expected dataset parameters as configuration input.\")\n thelper.data.Dataset.__init__(self, transforms=transforms, deepcopy=False)\n self.root = dataset[\"path\"]\n # keys matching dataset config for easy loading and referencing to same fields\n self.image_key = IMAGE_DATA_KEY # key employed by loader to extract image data (pixel values)\n self.label_key = IMAGE_LABEL_KEY # class id from API mapped to match model task\n self.path_key = DATASET_DATA_PATCH_PATH_KEY # actual file path of the patch\n self.idx_key = DATASET_DATA_PATCH_INDEX_KEY # increment for __getitem__\n self.mask_key = DATASET_DATA_PATCH_MASK_KEY # actual mask path of the patch\n self.mask_path_key = DATASET_DATA_PATCH_MASK_PATH_KEY # actual mask path of the patch\n self.meta_keys = [self.path_key, self.idx_key, self.mask_key, DATASET_DATA_PATCH_CROPS_KEY,\n DATASET_DATA_PATCH_IMAGE_KEY, DATASET_DATA_PATCH_FEATURE_KEY]\n model_class_map = dataset[DATASET_DATA_KEY][DATASET_DATA_MODEL_MAPPING]\n model_class_map = {int(k): v for k,v in model_class_map.items()} # forcing the key to be integer\n class_id_to_nodel_output = dataset[DATASET_DATA_KEY][DATASET_DATA_MODEL_MAPPING]\n sample_class_ids = set()\n samples = []\n self.dontcare = dontcare # dataset.get('dontcare', None)\n # channels = dataset.get(DATASET_DATA_CHANNELS, None)\n self.channels = channels # channels if channels else [1, 2, 3] # by default we take the first 3 channels\n for patch_path, patch_info in zip(dataset[DATASET_FILES_KEY],\n dataset[DATASET_DATA_KEY][DATASET_DATA_PATCH_KEY]):\n if patch_info[DATASET_DATA_PATCH_SPLIT_KEY] == split:\n # convert the dataset class ID into the model class ID using mapping, drop sample if not found\n class_name = model_class_map.get(patch_info[DATASET_DATA_PATCH_CLASS_KEY])\n #nodel_output = class_id_to_nodel_output.get(class_name)\n if class_name is not None:\n sample_class_ids.add(class_name)\n samples.append(deepcopy(patch_info))\n samples[-1][self.path_key] = os.path.join(self.root, patch_path)\n samples[-1][self.label_key] = class_name\n mask_name = patch_info.get(DATASET_DATA_PATCH_CROPS_KEY)[0].get(DATASET_DATA_PATCH_MASK_PATH_KEY, None)\n if mask_name is not None:\n samples[-1][self.mask_path_key] = os.path.join(self.root, mask_name)\n if not len(sample_class_ids):\n raise ValueError(\"No patch/class could be retrieved from batch loading for specific model task.\")\n self.samples = samples\n self.sample_class_ids = sample_class_ids\n\ndef get_dataset_classes(dataset, min_occurence = 0):\n # type: (Dataset) -> Tuple[Dict, Dict, List, Dict, Dict]\n \"\"\"\n Generates a training set the meta.json file.\n\n :param dataset: original dictionary loaded from the meta.json file.\n :param min_occurence: minimal number of samples per class (Default: 0).\n :return: class_mapping, all_classes_with_files, all_classes_names, classes_per_taxo, datasets_per_taxo\n \"\"\"\n \n samples_all = dataset[DATASET_DATA_KEY][DATASET_DATA_PATCH_KEY] # type: JSON\n\n all_child_classes = set() # only taxonomy child classes IDs\n all_classes_mapping = dict() # child->parent taxonomy class ID mapping\n all_child_names = dict()\n all_child_taxo = dict()\n all_classes_with_files = Counter([s[\"class\"] for s in samples_all])\n def find_class_mapping(taxonomy_class, parent=None, name=None):\n \"\"\"Finds existing mappings defined by taxonomy.\"\"\"\n children = taxonomy_class.get(\"children\")\n class_id = taxonomy_class.get(\"id\")\n if not name and parent:\n name = taxonomy_class.get(\"name_en\")\n elif name:\n name = '{} {}'.format(name, taxonomy_class.get(\"name_en\"))\n taxo_id = taxonomy_class.get(\"taxonomy_id\")\n if children:\n for child in children:\n find_class_mapping(child, taxonomy_class)\n elif class_id in all_classes_with_files:\n all_child_classes.add(class_id)\n all_child_names[class_id] = name\n all_child_taxo[class_id] = taxo_id\n all_classes_mapping[class_id] = None if not parent else parent.get(\"id\")\n for taxo in dataset[DATASET_DATA_KEY][DATASET_DATA_TAXO_KEY]:\n find_class_mapping(taxo)\n # print(\"Taxonomy class mapping: {}\".format(all_classes_mapping))\n all_classes_names = [all_child_names[c] for c in all_classes_with_files]\n classes_per_taxo = dict()\n datasets_per_taxo = dict()\n for taxo in dataset[DATASET_DATA_KEY][DATASET_DATA_TAXO_KEY]:\n datasets_per_taxo[taxo['name_en']] = {'data': [], 'class_mapping': {}}\n print(\"Taxonomie name: {}\".format(taxo['name_en']))\n\n sub_samples_nosplit = [s for s in samples_all if all_child_taxo[s[\"class\"]] == taxo['taxonomy_id']]\n sub_samples_train = [s for s in sub_samples_nosplit if s[\"split\"] == 'train']\n temp = Counter([s[\"class\"] for s in sub_samples_train])\n\n datasets_per_taxo[taxo['name_en']]['data'] = [s for s in sub_samples_nosplit if temp[s[\"class\"]] > min_occurence]\n datasets_per_taxo[taxo['name_en']]['class_mapping'] = {all_child_names[s[\"class\"]]: s[\"class\"] for s in datasets_per_taxo[taxo['name_en']]['data']}\n classes_per_taxo[taxo['name_en']] = Counter([s[\"class\"] for s in datasets_per_taxo[taxo['name_en']]['data'] if all_child_taxo[s[\"class\"]] == taxo['taxonomy_id']])\n\n\n print(\"Dataset class names: {}\".format(all_classes_names))\n # print(\"Dataset class parents: {}\".format(all_class_parents))\n class_mapping = dict(zip(all_classes_names, all_classes_with_files.keys()))\n return class_mapping, all_classes_with_files, all_classes_names, classes_per_taxo, datasets_per_taxo\n\ndef adapt_dataset_for_model_task(model_task, dataset, split = 'test'):\n # type: (AnyTask, Dataset) -> JSON\n \"\"\"\n Generates dataset parameter definition for loading from checkpoint configuration with ``thelper``.\n\n Retrieves available classes from the loaded dataset parameters and preserves only matching classes with the task\n defined by the original model task. Furthermore, parent/child class IDs are resolved recursively in a bottom-top\n manner to adapt specific classes into corresponding `categories` in the case the model uses them as more generic\n classes.\n\n .. seealso::\n - :class:`BatchTestPatchesBaseDatasetLoader` for dataset parameters used for loading filtered patches.\n\n :param model_task: original task defined by the model training which specifies known classes.\n :param dataset: batch of patches from which to extract matching classes known to the model.\n :return: configuration that allows ``thelper`` to generate a data loader for testing the model on desired patches.\n \"\"\"\n try:\n dataset_params = dataset #.json() # json required because thelper dumps config during logs\n all_classes_mapping = dict() # child->parent taxonomy class ID mapping\n all_model_ordering = list() # class ID order as defined by the model\n all_model_mapping = dict() # taxonomy->model class ID mapping\n all_child_classes = set() # only taxonomy child classes IDs\n all_test_patch_files = list() # list of the test patch files\n\n def find_class_mapping(taxonomy_class, parent=None):\n \"\"\"Finds existing mappings defined by taxonomy.\"\"\"\n children = taxonomy_class.get(\"children\")\n class_id = taxonomy_class.get(\"id\")\n if children:\n for child in children:\n find_class_mapping(child, taxonomy_class)\n else:\n all_child_classes.add(class_id)\n all_classes_mapping[class_id] = None if not parent else parent.get(\"id\")\n\n # Some models will use a generic background class so we add it systematically in case the model needs it\n for taxo in dataset_params[DATASET_DATA_KEY][DATASET_DATA_TAXO_KEY]:\n taxo.get(\"children\").insert(0, {\"id\": DATASET_BACKGROUND_ID,\n \"name_fr\": \"Classe autre\",\n \"taxonomy_id\": taxo.get(\"taxonomy_id\"),\n \"code\": \"BACK\",\n \"name_en\": \"Background\",\n \"children\": []})\n\n for taxo in dataset_params[DATASET_DATA_KEY][DATASET_DATA_TAXO_KEY]:\n find_class_mapping(taxo)\n print(\"Taxonomy class mapping: {}\".format(all_classes_mapping))\n print(\"Taxonomy class children: {}\".format(all_child_classes))\n\n # find model mapping using taxonomy hierarchy\n def get_children_class_ids(parent_id):\n children_ids = set()\n filtered_ids = set([c for c, p in all_classes_mapping.items() if p == parent_id])\n for c in filtered_ids:\n if c not in all_child_classes:\n children_ids = children_ids | get_children_class_ids(c)\n return children_ids | filtered_ids\n\n for model_class_id in model_task.class_names:\n # attempt str->int conversion of model string, they should match taxonomy class IDs\n try:\n model_class_id = int(model_class_id)\n except ValueError:\n raise ValueError(\"Unknown class ID '{}' cannot be matched with taxonomy classes\".format(model_class_id))\n if model_class_id not in all_classes_mapping:\n raise ValueError(\"Unknown class ID '{}' cannot be found in taxonomy\".format(model_class_id))\n # while looking for parent/child mapping, also convert IDs as thelper requires string labels\n if model_class_id in all_child_classes:\n print(\"Class {0}: found direct child ID ({0}->{0})\".format(model_class_id))\n all_model_mapping[model_class_id] = str(model_class_id)\n else:\n categorized_classes = get_children_class_ids(model_class_id)\n for cat_id in categorized_classes:\n all_model_mapping[cat_id] = str(model_class_id)\n print(\"Class {0}: found category class IDs ({0}->AnyOf{1})\"\n .format(model_class_id, list(categorized_classes)))\n all_model_ordering.append(model_class_id)\n all_model_mapping = {c: all_model_mapping[c] for c in sorted(all_model_mapping)}\n print(\"Model class mapping (only supported classes): {}\".format(all_model_mapping))\n print(\"Model class ordering (indexed class outputs): {}\".format(all_model_ordering))\n\n # add missing classes mapping\n all_model_mapping.update({c: None for c in sorted(set(all_classes_mapping) - set(all_model_mapping))})\n print(\"Model class mapping (added missing classes): {}\".format(all_model_mapping))\n\n # update obtained mapping with dataset parameters for loader\n dataset_params[DATASET_DATA_KEY][DATASET_DATA_MAPPING_KEY] = all_model_mapping\n dataset_params[DATASET_DATA_KEY][DATASET_DATA_ORDERING_KEY] = all_model_ordering\n dataset_params[DATASET_DATA_KEY][DATASET_DATA_MODEL_MAPPING] = model_task.class_indices\n dataset_params[DATASET_FILES_KEY] = all_test_patch_files\n\n # update patch info for classes of interest\n # this is necessary for BatchTestPatchesClassificationDatasetLoader\n class_mapped = [c for c, m in all_model_mapping.items() if m is not None]\n samples_all = dataset_params[DATASET_DATA_KEY][DATASET_DATA_PATCH_KEY] # type: JSON\n all_classes_with_files = sorted(set([s[\"class\"] for s in samples_all]))\n all_model_classes = set(class_mapped + all_model_ordering)\n samples_mapped = [s for s in samples_all if s[DATASET_DATA_PATCH_CLASS_KEY] in all_model_classes]\n # retain class Ids with test patches\n classes_with_files = sorted(set([s[\"class\"] for s in samples_mapped if s[\"split\"] == split]))\n if len(classes_with_files) == 0:\n raise ValueError(\"No test patches for the classes of interest!\")\n all_test_patch_files = [s[DATASET_DATA_PATCH_CROPS_KEY][0][\"path\"] for s in samples_mapped]\n dataset_params[DATASET_FILES_KEY] = all_test_patch_files\n\n # test_samples = [\n # {\"class_id\": s[DATASET_DATA_PATCH_CLASS_KEY],\n # \"sample_id\": s[DATASET_DATA_PATCH_FEATURE_KEY]} for s in samples_all\n # ]\n\n model_task_name = fully_qualified_name(model_task)\n return {\n \"type\": MODEL_TASK_MAPPING[model_task_name][MAPPING_LOADER],\n \"params\": {TEST_DATASET_KEY: dataset_params, 'channels': dataset_params.get('channels', None), 'dontcare': dataset_params.get('dontcare', None), 'split': split},\n \"task\": model_task\n }\n except Exception as exc:\n raise RuntimeError(\"Failed dataset adaptation to model task classes for evaluation. [{!r}]\".format(exc))\n\n\n# FIXME: add definitions/implementations to support other task types (ex: object-detection)\nMODEL_TASK_MAPPING = {\n fully_qualified_name(thelper.tasks.classif.Classification): {\n MAPPING_TASK: fully_qualified_name(thelper.tasks.classif.Classification),\n MAPPING_LOADER: fully_qualified_name(BatchTestPatchesBaseDatasetLoader),\n MAPPING_TESTER: fully_qualified_name(thelper.train.classif.ImageClassifTrainer),\n },\n fully_qualified_name(thelper.tasks.segm.Segmentation): {\n MAPPING_TASK: fully_qualified_name(thelper.tasks.segm.Segmentation),\n MAPPING_LOADER: fully_qualified_name(BatchTestPatchesBaseSegDatasetLoader),\n MAPPING_TESTER: fully_qualified_name(thelper.train.segm.ImageSegmTrainer),\n },\n}\n","sub_path":"ginmodelrepo/util.py","file_name":"util.py","file_ext":"py","file_size_in_byte":30949,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"530323730","text":"# coding: utf8\n\nimport csv\n\n# with open('confs.csv') as f:\n# reader = csv.DictReader(f)\n# print(reader)\n# for row in reader:\n# print(row['name'], row['age'])\n\n\ncsv.register_dialect('conf', delimiter=' ', quoting=csv.QUOTE_NONE)\nwith open('confs.csv') as f:\n reader = csv.reader(f, 'conf')\n\n for row in reader:\n print(row)","sub_path":"csv_test/reader.py","file_name":"reader.py","file_ext":"py","file_size_in_byte":354,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"139284962","text":"# uncompyle6 version 3.7.4\n# Python bytecode 2.6 (62161)\n# Decompiled from: Python 3.6.9 (default, Apr 18 2020, 01:56:04) \n# [GCC 8.4.0]\n# Embedded file name: build/bdist.linux-i686/egg/benchbase/sar.py\n# Compiled at: 2011-09-15 17:15:00\n\"\"\"Extract information from a sysstat sar text file.\"\"\"\nimport logging\nfrom util import mygzip\n\nclass Sar(object):\n \"\"\"Handle sysstat sar file.\"\"\"\n\n def __init__(self, db, options):\n self.options = options\n self.db = db\n\n def doImport(self, bid, filename):\n c = self.db.cursor()\n options = self.options\n host = options.host\n t = (bid, host, options.comment)\n logging.info('Importing sar file %s into bid: %s' % (filename, bid))\n c.execute('INSERT INTO host (bid, host, comment) VALUES (?, ?, ?)', t)\n if filename.endswith('.gz'):\n f = mygzip(filename)\n else:\n f = open(filename)\n in_cpu = False\n in_disk = False\n count = 0\n while True:\n line = f.readline()\n if not line:\n break\n if 'CPU %usr' in line:\n in_cpu = True\n continue\n if 'DEV tps' in line:\n in_disk = True\n continue\n if in_cpu:\n if 'all' not in line:\n continue\n if 'Average' in line:\n in_cpu = False\n continue\n t = [\n bid, host] + line.split()\n t.remove('all')\n c.execute('INSERT INTO cpu (bid, host, date, usr, nice, sys, iowait, steal, irq, soft, guest, idle) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)', t)\n count += 1\n elif in_disk:\n if 'Average' in line:\n in_disk = False\n break\n r = line.split()\n t = [bid, host, r[0], r[1], r[2], r[3], r[4], r[9]]\n c.execute('INSERT INTO disk (bid, host, date, dev, tps, rd_sec_per_s, wr_sec_per_s, util) VALUES (?, ?, ?, ?, ?, ?, ?, ?)', t)\n count += 1\n\n c.close()\n self.db.commit()\n logging.info('%d lines imported.' % count)\n\n def getInfo(self, bid):\n t = (\n bid,)\n c = self.db.cursor()\n c.execute('SELECT host, comment FROM host WHERE bid = ?', t)\n ret = {'sar': {}}\n for (host, comment) in c:\n ret['sar'][host] = comment\n\n return ret","sub_path":"pycfiles/benchbase-1.1.0-py2.6/sar.py","file_name":"sar.py","file_ext":"py","file_size_in_byte":2520,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"66884500","text":"import argparse\nimport sys\nimport uuid\n\nimport chess\nimport chess.engine\nimport requests\n\nparser = argparse.ArgumentParser(description=\"Simple Versus client\")\nparser.add_argument(\"-u\", \"--url\",\n help=\"URL or IP of the Versus instance\",\n default=\"http://localhost\",\n dest=\"url\")\nparser.add_argument(\"-n\", \"--name\",\n help=\"display name\",\n default=\"Default\",\n dest=\"name\")\nparser.add_argument(\"-c\", \"--computer\",\n help=\"Specify whether computer mode is enabled or not\",\n default=\"yes\",\n dest=\"computer\")\nparser.add_argument(\"-e\", \"--engine\",\n help=\"Path to the chess engine which should be moved for move generation, if --computer is set to yes\",\n default=\"stockfish_20011801_x64.exe\",\n dest=\"engine\")\n\nargs = parser.parse_args()\n\nif args.computer == \"yes\":\n human_mode = False\nelse:\n human_mode = True\n\n\ndef new_game():\n print(\"1 - Create new game\")\n print(\"2 - Join existing game\")\n local_game_id = None\n choice = int(input())\n if choice == 1:\n try:\n r = requests.get(url=args.url + \"/newgame?name=\" + args.name + \"&pin=\" + pin)\n except:\n print(\"Connection to \" + args.url + \" could not be established.\")\n raise\n local_game_id = r.json()[\"id\"]\n print(r.json()[\"message\"] + \" \" + r.json()[\"id\"])\n print(\"Waiting for all players to join...\")\n if choice == 2:\n print(\"Please enter game ID:\")\n local_game_id = str(input())\n try:\n r = requests.get(\n url=args.url + \"/newgame?id=\" + local_game_id + \"&name=\" + args.name + \"&pin=\" + pin)\n response = r.json()\n print(response[\"message\"] + \" \" + response[\"id\"])\n except:\n print(\"Connection to \" + args.url + \" could not be established.\")\n raise\n return local_game_id\n\n\ndef calculate_move():\n r = requests.get(\n url=args.url + \"/getfen?id=\" + game_id)\n response = r.json()[\"fen\"]\n board = chess.Board(response)\n while not board.is_game_over():\n result = engine.play(board, chess.engine.Limit(time=0.3), ponder=True)\n return str(result.move)\n\n\ndef move():\n if human_mode:\n print(\"Enter a move in UCI notation:\")\n choice = str(input())\n else:\n choice = calculate_move()\n print(\"Engine made move \" + choice)\n r = requests.get(url=args.url + \"/move?id=\" + game_id + \"&move=\" + choice + \"&name=\" + args.name + \"&pin=\" + pin)\n if r.status_code != 200:\n print(r.json()[\"message\"])\n print(\"Waiting for other player...\")\n\n\ndef game_is_active():\n r = requests.get(url=args.url + \"/games?&id=\" + game_id)\n if r.json()[\"game_state\"] != \"FINISHED\":\n return True\n return False\n\n\ndef game_is_full():\n r = requests.get(url=args.url + \"/games?&id=\" + game_id)\n response = r.json()\n if len(response[\"players\"]) == 2:\n return True\n return False\n\n\ndef is_my_turn():\n r = requests.get(url=args.url + \"/games?&id=\" + game_id)\n response = r.json()\n for idx, player in enumerate(response[\"players\"]):\n if player == args.name:\n turn = idx % 2\n return len(response[\"moves\"]) % 2 == turn\n\n\ndef is_player_human():\n print(\"Who is going to provide UCI moves for the upcoming game?\")\n print(\"1 - Machine\")\n print(\"2 - Human\")\n choice = input()\n if choice == 1:\n return False\n else:\n return True\n\n\nengine = chess.engine.SimpleEngine.popen_uci(args.engine)\npin = str(uuid.uuid4())\ntry:\n game_id = new_game()\nexcept:\n sys.exit(-1)\n\nwhile not game_is_full():\n pass\n\nwhile True:\n if is_my_turn():\n move()\nprint(\"Game over.\")\nengine.close()\n","sub_path":"versus_client/client.py","file_name":"client.py","file_ext":"py","file_size_in_byte":3891,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"24537609","text":"\"\"\"Classes for forms used by this blueprint.\"\"\"\n\n# Python imports.\nimport io\n\n# Flask imports.\nfrom flask import current_app\nfrom flask_wtf import Form\n\n# 3rd party imports.\nfrom wtforms import FileField, RadioField, SelectMultipleField, SubmitField, TextAreaField, widgets\nfrom wtforms.validators import DataRequired, ValidationError\n\n# User imports.\nfrom .ConceptCollection import ConceptCollection\n\n\ndef concept_definitions_validator(form, field):\n \"\"\"Validate the concept definitions.\"\"\"\n\n isFileUploaded = bool(form.conceptFile.data)\n isTextEntered = bool(form.conceptText.data)\n if isFileUploaded and isTextEntered:\n # Concepts were uploaded as a file and text.\n raise ValidationError(\"Only one source of concepts can be provided.\")\n elif not isFileUploaded and not isTextEntered:\n # No concepts were uploaded.\n raise ValidationError(\"No source of concepts was provided.\")\n else:\n # Concepts were provided, so validate them.\n\n # Determine the content that was uploaded, and record some information about it.\n # Wrap the text area's content in StringIO in order to enable file-like operations on it, and to keep it in\n # line with how the uploaded file content is accessed.\n if isFileUploaded:\n # A file was uploaded.\n filename = form.conceptFile.data.filename\n fileFormat = (filename.rsplit('.', 1)[1]).lower()\n uploadContents = io.TextIOWrapper(form.conceptFile.data, newline=None)\n else:\n # Text was entered in the text area.\n fileFormat = form.textAreaType.data\n uploadContents = io.StringIO(form.conceptText.data, newline=None)\n\n # Ensure that the format of the uploaded file is correct.\n allowedExtensions = current_app.config[\"ALLOWED_EXTENSIONS\"]\n if fileFormat not in allowedExtensions:\n # The format of the file is not one of the accepted ones.\n raise ValidationError(\"Uploaded {0:s} file is not in one of the accepted formats - {1:s} or {2:s}.\"\n .format(fileFormat, \", \".join(allowedExtensions[:-1]), allowedExtensions[-1]))\n\n # Validate the uploaded concept(s). The only real constraint on the the concept file is that at least one\n # concept is defined in the correct format.\n errors = ConceptCollection.validate_concept_file(uploadContents, fileFormat, isFileUploaded)\n\n if errors:\n # Found an error in the uploaded file or text area.\n if not isFileUploaded:\n form.conceptSubmit.errors.append(\"Errors found while validating the pasted text.\")\n else:\n form.conceptSubmit.errors.append(\"Errors found while validating the uploaded file.\")\n form.conceptSubmit.errors.extend(errors)\n\n uploadContents.seek(0) # Reset the stream back to the start so that it can be properly validated.\n if isFileUploaded:\n # Only need to detach when it was a file uploaded.\n uploadContents.detach() # Detach the buffer to prevent TextIOWrapper closing the underlying file.\n\n\nclass MultiCheckboxField(SelectMultipleField):\n \"\"\"A multiple select element that displays a list of checkboxes.\n\n Iterating the field will produce subfields, allowing custom rendering of the enclosed checkbox fields.\n\n \"\"\"\n\n widget = widgets.ListWidget(prefix_label=False)\n option_widget = widgets.CheckboxInput()\n\n\nclass ConceptUploadForm(Form):\n \"\"\"Class representing the form for uploading information about the concepts to find codes for.\"\"\"\n\n conceptText = TextAreaField()\n textAreaType = RadioField(\"Concept format:\", choices=[(\"txt\", \"Flat File\"), (\"json\", \"JSON\")], default=\"txt\")\n conceptFile = FileField()\n codeFormats = RadioField(choices=[(\"ReadV2\", \"Read v2\"), (\"CTV3\", \"CTV3\"), (\"SNOMED_CT\", \"SNOMED-CT\")],\n default=\"ReadV2\",\n validators=[DataRequired(message=\"At least one code format must be selected.\")])\n conceptSubmit = SubmitField(\"Upload Concepts\", validators=[concept_definitions_validator])\n","sub_path":"webapp/mod_concept_discovery/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":4155,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"381589668","text":"#-*-coding:utf-8-*- \n\n# Given a string containing only three types of characters: '(', ')' and '*',\n# write a function to check whether this string is valid. We define the\n# validity of a string by these rules:\n#\n# Any left parenthesis '(' must have a corresponding right parenthesis ')'.\n# Any right parenthesis ')' must have a corresponding left parenthesis '('.\n# Left parenthesis '(' must go before the corresponding right parenthesis ')'.\n# '*' could be treated as a single right parenthesis ')' or a single left\n# parenthesis '(' or an empty string.\n# An empty string is also valid.\n# Example 1:\n#\n# Input: \"()\"\n# Output: True\n# Example 2:\n#\n# Input: \"(*)\"\n# Output: True\n# Example 3:\n#\n# Input: \"(*))\"\n# Output: True\n# Note:\n#\n# The string size will be in the range [1, 100].\n\nclass Solution(object):\n def checkValidString(self, s):\n stack1 = [] #store the index of '('\n stack2 = [] #store the index of *\n result = True\n\n if len(s) == 0:\n return result\n\n for i in range(len(s)):\n if s[i] == ')':\n if len(stack1) > 0:\n stack1.pop()\n elif len(stack2) > 0 and stack2[-1] < i:\n stack2.pop()\n else:\n return False\n\n elif s[i] == '(':\n stack1.append(i)\n else:\n stack2.append(i)\n\n while len(stack1) > 0:\n if len(stack2) > 0 and stack2[-1] > stack1[-1]:\n stack1.pop()\n stack2.pop()\n else:\n break\n if len(stack1) > 0:\n return False\n return result\n\ns = Solution()\nprint(s.checkValidString(\"()\"))\nprint(s.checkValidString(\"(*)\"))\nprint(s.checkValidString(\"(*))\"))\n","sub_path":"src/leetcode/LC_678_valid_parenthesis_string.py","file_name":"LC_678_valid_parenthesis_string.py","file_ext":"py","file_size_in_byte":1772,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"509142233","text":"# Consecutive prime sum\nfrom time import time\n\nstart = time()\n\n\ndef isprime(n): # here is a function determines if the number is prime\n if n == 2:\n return True\n if n > 2 and n % 2 != 0:\n for i in range(3, int(n ** 0.5) + 1, 2):\n if n % i == 0:\n return False\n return True\n return False\n\n\ndef e50():\n prs = [2, 3, 5, 7]\n n = prs[-1] + 2\n while sum(prs) < 1000000:\n for p in prs:\n if not n % p:\n break\n else:\n prs.append(n)\n n += 2\n a = len(prs[:-1]) - 1\n for i in range(a, 0, -2): # here is the \"window\"-method\n for j in range(a - i + 1):\n sump = sum(prs[1 + j:i + j + 1])\n if j == 0 and isprime(sump + 2):\n return sump + 2\n if isprime(sump):\n return sump\n\n\nprint('Prime =', e50(), 'is the longest sum of consecutive primes') # 997651\nprint('Runtime =', time() - start)\n","sub_path":"euler50_Consecutive_prime_sum.py","file_name":"euler50_Consecutive_prime_sum.py","file_ext":"py","file_size_in_byte":970,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"89209170","text":"#!/usr/bin/env python\n#! -*- coding: utf-8 -*-\n\nfrom glob import glob\nfrom os.path import basename\nfrom run_ipynb import convert_nb_html\nimport IPython.nbformat.current as nbf\nfrom flask import Flask, render_template, abort, g\n\napp = Flask(__name__)\n\n\n@app.before_request\ndef before_request():\n g.nbs = [basename(f).split('.')[0] for f in glob('notebooks/*ipynb')]\n\n\n@app.route(\"/\")\ndef index():\n return render_template('index.html')\n\n\n@app.route(\"/notebook/\")\ndef notebook(notebook):\n try:\n notebook = nbf.read(open('notebooks/%s' % notebook, 'r'), 'ipynb')\n except IOError:\n abort(418)\n html_notebook= convert_nb_html(notebook)\n return render_template('notebook.html', content=html_notebook)\n\n\nif __name__ == \"__main__\":\n app.run(debug=True)\n","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":789,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"475319055","text":"# Реализовать структуру «Рейтинг», представляющую собой не возрастающий набор натуральных чисел.\n# У пользователя необходимо запрашивать новый элемент рейтинга.\n# Если в рейтинге существуют элементы с одинаковыми значениями,\n# то новый элемент с тем же значением должен разместиться после них.\n\nwhile True:\n if input(\"Для продолжения нажмите Enter, для выхода наберите Q :\") == \"Q\":\n break\n else:\n my_list = [7, 5, 3, 3, 2]\n user_inp = int(input(\"Введите целое число: \"))\n pos = 0\n for ind, el in enumerate(my_list):\n if user_inp <= el:\n pos = ind + 1\n my_list.insert(pos, user_inp)\n print(f\"{my_list} \\n\")\n","sub_path":"lesson02/lesson02hw05.py","file_name":"lesson02hw05.py","file_ext":"py","file_size_in_byte":988,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"371953716","text":"# -*- coding: utf-8 -*-\n \nimport logging\nimport os\nimport subprocess\nimport time\nimport socket\nimport requests\nimport random\nimport binascii\nimport base64\n\nfrom Crypto.PublicKey import RSA\nfrom jinja2 import Environment, FileSystemLoader\nfrom kube.kubectl import Kubectl\n\nlog = logging.getLogger(name=__name__)\n\nclass Deployer(object):\n \"\"\"Deploy one kubernetes node\"\"\"\n def __init__(self, role, master_ip=None):\n self.role = role\n self.master_ip = master_ip\n\n def deploy_node(self, ip, hostname):\n if self.role == \"all_in_one\":\n path = \"/etc/kubernetes\"\n pki_path = path + \"/pki\"\n\n if not os.path.isfile(pki_path + \"/ca.crt\"):\n self._create_ca(pki_path, \"ca\")\n self._create_ca(pki_path, \"front-proxy-ca\") \n self._create_cert(pki_path, \"apiserver\", \"ca\", \"ca-config\", ip, hostname)\n self._create_cert(pki_path, \"apiserver-kubelet-client\", \"ca\", \"ca-config\", ip, hostname)\n self._create_cert(pki_path, \"front-proxy-client\", \"front-proxy-ca\", \"front-proxy-ca-config\", ip, hostname) \n\n # create sa keys\n new_key = RSA.generate(2048, e=65537) \n public_key = new_key.publickey().exportKey(\"PEM\") \n private_key = new_key.exportKey(\"PEM\") \n\n with open(pki_path + \"/sa.key\", 'wb') as out:\n out.write(private_key)\n\n with open(pki_path + \"/sa.pub\", 'wb') as out:\n out.write(public_key)\n\n # create config files\n self._create_config(path, \"admin\", \"ca\", \"ca-config\", ip, hostname) \n self._create_config(path, \"controller-manager\", \"ca\", \"ca-config\", ip, hostname) \n self._create_config(path, \"kubelet\", \"ca\", \"ca-config\", ip, hostname) \n self._create_config(path, \"scheduler\", \"ca\", \"ca-config\", ip, hostname) \n\n # create manifests\n self._create_manifest(path, \"etcd\", ip, hostname) \n self._create_manifest(path, \"kube-apiserver\", ip, hostname) \n self._create_manifest(path, \"kube-controller-manager\", ip, hostname) \n self._create_manifest(path, \"kube-scheduler\", ip, hostname) \n\n # wait until apiserver is up\n log.info(\"waiting for apiserver\")\n\n start_time = time.perf_counter()\n socket.setdefaulttimeout(600)\n while True:\n try:\n r = requests.get(\"https://127.0.0.1:6443/healthz\", verify='/etc/kubernetes/pki/ca.crt', timeout=600)\n if r.text == \"ok\":\n break\n except OSError as ex:\n time.sleep(0.01)\n if time.perf_counter() - start_time >= 240.0:\n raise TimeoutError('Waited too long for the port {} on host {} to start accepting '\n 'connections.'.format(ip, 6443)) from ex \n\n kubectl = Kubectl(\"/etc/kubernetes/admin.conf\")\n # mark as master\n kubectl.markMaster(hostname)\n\n j2_te = Environment(\n autoescape=False,\n loader=FileSystemLoader(\"deployments/bootstrap/\"),\n trim_blocks=False)\n\n # create token\n token_id = bytearray(random.getrandbits(8) for i in range(3))\n token_secret = bytearray(random.getrandbits(8) for i in range(8))\n \n token = binascii.hexlify(token_id).decode(encoding='ascii') + \".\" + binascii.hexlify(token_secret).decode(encoding='ascii')\n secret_name = \"bootstrap-token-\" + binascii.hexlify(token_id).decode(encoding='ascii')\n\n expiration = 0\n\n # create cluster-info\n context = {\n 'secret_name': secret_name,\n 'token_id': base64.b64encode(binascii.hexlify(token_id)).decode('utf-8'),\n 'token_secret': base64.b64encode(binascii.hexlify(token_secret)).decode('utf-8'),\n 'description': base64.b64encode(b'The default bootstrap token generated by helvi').decode('utf-8'),\n 'expiration': expiration\n }\n\n with open(\"deployments/bootstrap/token.yaml\", 'w') as f:\n tpl = j2_te.get_template(\"token.yaml.j2\").render(context)\n f.write(tpl)\n\n kubectl.create(\"token\", \"deployments/bootstrap\")\n\n # create cluster-info\n context = {\n 'ip': ip,\n 'ca': self._read_cert(path + \"/pki/ca.crt\")\n }\n\n with open(\"deployments/bootstrap/cluster-info.yaml\", 'w') as f:\n tpl = j2_te.get_template(\"cluster-info.yaml.j2\").render(context)\n f.write(tpl)\n\n kubectl.create(\"cluster-info\", \"deployments/bootstrap\")\n\n kubectl.create(\"roles\", \"deployments/bootstrap\")\n\n with open(\"deployments/bootstrap/kube-proxy.yaml\", 'w') as f:\n tpl = j2_te.get_template(\"kube-proxy.yaml.j2\").render(context)\n f.write(tpl)\n\n kubectl.create(\"kube-proxy\", \"deployments/bootstrap\")\n\n # create service accounts\n kubectl.create(\"serviceaccounts\", \"deployments/bootstrap\")\n kubectl.create(\"calico\", \"deployments/calico\")\n kubectl.create(\"kubedns\", \"deployments/bootstrap\")\n kubectl.create(\"kubernetes-dashboard\", \"deployments/bootstrap\")\n\n # deploy rook\n kubectl.create(\"rook-operator\", \"deployments/rook\")\n kubectl.waitForLabelPod(\"app=rook-operator\")\n kubectl.create(\"rook-cluster\", \"deployments/rook\")\n kubectl.create(\"rook-storageclass\", \"deployments/rook\")\n\n # deploy helvi services\n kubectl.create(\"helvi\", \"deployments/helvi\")\n kubectl.create(\"helvi-operator\", \"deployments/helvi\")\n else:\n log.error(\"Role not implemented: \" + self.role)\n\n def _create_ca(self, path, name):\n log.info(\"creating \" + name + \" CA\")\n stdoutdata = subprocess.getoutput(\"cfssl gencert -initca pki/\" + name + \"-csr.json | cfssljson -bare \" + path + \"/\" + name)\n log.info(\"stdoutdata: \" + stdoutdata)\n\n os.rename(path + \"/\" + name + \".pem\", path + \"/\" + name + \".crt\") \n os.rename(path + \"/\" + name + \"-key.pem\", path + \"/\" + name + \".key\") \n os.remove(path + \"/\" + name + \".csr\")\n\n def _create_cert(self, path, name, ca, config, ip, hostname):\n # replace ip\n j2_te = Environment(\n autoescape=False,\n loader=FileSystemLoader(\"pki/templates/\"),\n trim_blocks=False)\n\n context = {\n 'ip': ip,\n 'hostname': hostname\n }\n\n with open(\"pki/\" + name + \"-csr.json\", 'w') as f:\n tpl = j2_te.get_template(name + \"-csr.json.j2\").render(context)\n f.write(tpl)\n\n # create cert\n log.info(\"creating \" + name + \" cert\")\n stdoutdata = subprocess.getoutput(\"cfssl gencert \\\n -ca=\" + path + \"/\" + ca + \".crt \\\n -ca-key=\" + path + \"/\" + ca + \".key \\\n -config=pki/\" + config + \".json \\\n -profile=kubernetes \\\n pki/\" + name + \"-csr.json | cfssljson -bare \" + path + \"/\" + name)\n log.info(\"stdoutdata: \" + stdoutdata) \n os.rename(path + \"/\" + name + \".pem\", path + \"/\" + name + \".crt\") \n os.rename(path + \"/\" + name + \"-key.pem\", path + \"/\" + name + \".key\") \n os.remove(path + \"/\" + name + \".csr\") \n\n def _create_config(self, path, name, ca, config, ip, hostname):\n self._create_cert(path, name, \"pki/ca\", config, ip, hostname)\n\n j2_te = Environment(\n autoescape=False,\n loader=FileSystemLoader(\"conf/\"),\n trim_blocks=False)\n\n context = {\n 'ip': ip,\n 'hostname': hostname,\n 'ca': self._read_cert(path + \"/pki/ca.crt\"),\n 'crt': self._read_cert(path + \"/\" + name + \".crt\"),\n 'key': self._read_cert(path + \"/\" + name + \".key\")\n }\n\n with open(path + \"/\" + name + \".conf\", 'w') as f:\n tpl = j2_te.get_template(name + \".conf.j2\").render(context)\n f.write(tpl)\n\n os.remove(path + \"/\" + name + \".crt\") \n os.remove(path + \"/\" + name + \".key\") \n\n def _read_cert(self, name):\n with open(name, \"rb\") as crt:\n data = crt.read()\n\n data = base64.b64encode(data)\n return data.decode('utf-8')\n\n def _create_manifest(self, path, name, ip, hostname): \n j2_te = Environment(\n autoescape=False,\n loader=FileSystemLoader('manifests/'),\n trim_blocks=False)\n\n context = {\n 'ip': ip,\n 'kubernetes_dir': '/etc/kubernetes',\n 'etcd_dir': '/var/lib/etcd'\n }\n\n with open(path + \"/manifests/\" + name + \".yaml\", 'w') as f:\n tpl = j2_te.get_template(name + \".yaml.j2\").render(context)\n f.write(tpl) \n","sub_path":"helvi-node/kube/deployer.py","file_name":"deployer.py","file_ext":"py","file_size_in_byte":9489,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"604030778","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed Sep 19 03:12:24 2018\n\n@author: niveditanatarajan\n\"\"\"\nimport pymysql\nimport sqlalchemy\nimport pyodbc\n#!/usr/bin/python3\n'''\nimport pymysql\n\n# Open database connection\ndb = pymysql.connect(\"localhost\",\"testuser\",\"test123\",\"TESTDB\" )\n\n# prepare a cursor object using cursor() method\ncursor = db.cursor()\n\n# Prepare SQL query to INSERT a record into the database.\nsql = \"\"\"INSERT INTO JIVELY\n (NAME, HUMIDITY, TEMPERATURE)\n VALUES ('Niv', 20, 30)\"\"\" #change to values generated by temp.py\ntry:\n # Execute the SQL command\n cursor.execute(sql)\n # Commit your changes in the database\n db.commit()\nexcept:\n # Rollback in case there is any error\n db.rollback()\n\n# disconnect from server\ndb.close()\n'''\ndef sqlinsert(UID,NAME):\n db=pymysql.connect(\"localhost\",\"testuser\",\"test123\",\"TESTDB\")\n cursor=db.cursor()\n \n UID=UID+1\n #UID = fList[0][0];NAME=fList[0][1]\n #queryInsertStudentTable = \"\"\"CREATE TABLE JIVELY (UID INT, NAME varchar(25) not null)\"\"\"\n\n #cursor.execute(queryInsertStudentTable)\n '''\n sql = \"\"\"CREATE TABLE JIVELY (\n UID INT,\n NAME varchar(25) not null)\"\"\"\n cursor.execute(sql)\n '''\n queryInsert = \"INSERT INTO JIVELY (UID,NAME) VALUES (%s,%s)\"\n val=(UID,NAME)\n #Generate multiple values from the list to be placed in a query\n \n \n try:\n cursor.execute(queryInsert,val)\n print(\"record inserted\")\n db.commit()\n except:\n db.rollback()\n \n db.close()","sub_path":"database/db_insert_into_table.py","file_name":"db_insert_into_table.py","file_ext":"py","file_size_in_byte":1558,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"511309461","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCommon definitions for NER\n\"\"\"\n\n\nLBLS = [\n \"B-Component\",\n \"I-Component\",\n \"B-ScientificConcept\",\n \"I-ScientificConcept\",\n \"B-Material\",\n \"I-Material\",\n \"B-Others\",\n \"I-Others\",\n \"B-Location\",\n \"I-Location\",\n \"B-Function\",\n \"I-Function\",\n \"B-Operation\",\n \"I-Operation\",\n \"B-Attribution\",\n \"I-Attribution\",\n \"B-PhysicsFlow\",\n \"I-PhysicsFlow\",\n \"B-InfoFlow\",\n \"I-InfoFlow\",\n \"B-EnergyFlow\",\n \"I-EnergyFlow\",\n \"B-Measure\",\n \"I-Measure\",\n \"B-Value\",\n \"I-Value\",\n \"B-State\",\n \"I-State\",\n \"B-Shape\",\n \"I-Shape\",\n \"B-System\",\n \"I-System\",\n \"B-Consequence\",\n \"I-Consequence\",\n \"O\"\n]\n\n","sub_path":"patent_ner_api/model/defs.py","file_name":"defs.py","file_ext":"py","file_size_in_byte":732,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"358652172","text":"import re\n\ndef censor(text,words_to_censor,double_occurrences):\n\t#removes words and negative words after 2 occurrences\n\toriginal_text = text\n\ttext = text.lower()\n\tto_remove=[]\n\n\tfor word in words_to_censor:\n\t\tword = re.compile(rf\"\\b{word}\\b\")\n\t\tfor m in word.finditer(text):\n\t\t\tto_remove.append([[m.group()],[m.start(),m.end()]])\n\tfor word in to_remove:\n\t\toriginal_text = original_text[:word[1][0]] + \"X\"*len(word[0][0]) + original_text[word[1][1]:]\n\n\tto_remove =[]\n\n\tfor word in double_occurrences:\n\t\tword = re.compile(rf\"\\b{word}\\b\")\n\t\tfor m in word.finditer(text):\n\t\t\tto_remove.append([[m.group()],[m.start(),m.end()]])\n\t\n\tto_remove.sort(key=lambda x: x[1][1])\n\t\n\tfor word in to_remove[2:]:\n\t\toriginal_text = original_text[:word[1][0]] + \"X\"*len(word[0][0]) + original_text[word[1][1]:]\n\n\treturn original_text\n\ndef censor_plus_next_words(text,list1,list2):\n\tbig_list = list1+list2\n\toriginal_text = text\n\ttext = text.lower()\n\n\tto_remove =[]\n\n\tfor word in big_list:\n\t\tword = re.compile(rf\"\\b\\w*['-]?\\w*\\b ?\\b{word}\\b ?\\b\\w*['-]?\\w*\\b\")\n\t\tfor m in word.finditer(text):\n\t\t\tto_remove.append([[m.group()],[m.start(),m.end()]])\n\tto_remove.sort(key=lambda x: x[1][1])\n\n\tfor word in to_remove:\n\t\toriginal_text = original_text[:word[1][0]] +\"X\"*len(word[0][0])+ original_text[word[1][1]:]\n\treturn original_text\n\nemail_one = open(\"email_one.txt\", \"r\").read()\nemail_two = open(\"email_two.txt\", \"r\").read()\nemail_three = open(\"email_three.txt\", \"r\").read()\nemail_four = open(\"email_four.txt\", \"r\").read()\n\nproprietary_terms = [\"she\", \"personality matrix\", \"sense of self\", \"self-preservation\", \"learning algorithms \", \"her\", \"herself\"]\nnegative_words = [\"concerned\", \"behind\", \"danger\", \"dangerous\", \"alarming\", \"alarmed\", \"out of control\", \"help\", \"unhappy\", \"bad\", \"upset\", \"awful\", \"broken\", \"damage\", \"damaging\", \"dismal\", \"distressing\", \"distressed\", \"concerning\", \"horrible\", \"horribly\", \"questionable\"]\n\nprint(censor(email_three,proprietary_terms,negative_words))\nprint(censor_plus_next_words(email_four,proprietary_terms,negative_words))\n\n","sub_path":"Censor_dispenser/censor_dispenser.py","file_name":"censor_dispenser.py","file_ext":"py","file_size_in_byte":2037,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"357206371","text":"from core.providers import ALL_PROVIDERS\nfrom core.urls import UrlsExtractor\n\nBOT_RESPONSE = '{music_urls}'\nMUSIC_FROMAT = '{name}:\\n{urls}'\n\n\ndef process_message(message):\n msg_urls = UrlsExtractor.get_music_urls(message)\n if not msg_urls:\n return None\n\n musics = {}\n for url in msg_urls:\n name = url.get_name()\n if not name:\n return None\n musics[name] = []\n\n for provider in ALL_PROVIDERS:\n if type(url.provider) == provider:\n alternative_url = f'[{provider.NAME}]({url.url})'\n else:\n try:\n alternative_url = f'[{provider.NAME}]({provider().get_music_url(name)})'\n except Exception:\n alternative_url = None\n\n if alternative_url:\n musics[name].append(alternative_url)\n\n musics_texts = []\n for name, music_urls in musics.items():\n musics_texts.append(MUSIC_FROMAT.format(name=name, urls='\\n'.join(music_urls)))\n\n if musics_texts:\n response = BOT_RESPONSE.format(music_urls='\\n'.join(musics_texts))\n else:\n response = None\n\n return response\n","sub_path":"core/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":1165,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"428403600","text":"import math\n\np1 = input()\np2 = input()\n\nx1, y1 = p1.split(' ')\nx2, y2 = p2.split(' ')\n\nx1 = float(x1)\ny1 = float(y1)\nx2 = float(x2)\ny2 = float(y2)\n\nd = math.sqrt(pow(x2 - x1, 2) + pow(y2 - y1, 2))\n\nprint('{:.4f}'.format(d))","sub_path":"Python/1015.py","file_name":"1015.py","file_ext":"py","file_size_in_byte":223,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"59084087","text":"__author__ = 'MAKJANG_DRAMA' \n\nimport pygame, sys, time, math\nfrom pygame.locals import *\n\npygame.init()\n\n#setting_information\ndisplay_width = 800\ndisplay_height = 600\nsscore = 0\nLife = 100\n\n# glocken = pygame.mixer.Sound('glocken.wav')\npygame.mixer.music.load('music.mp3')\n# mixer.music.set_volume(0.4)\npygame.mixer.music.play(-1)\n\n\n\ngame_display = pygame.display.set_mode((display_width,display_height))\npygame.display.set_caption('본격! 육성, 나만의 틀린그림찾기!')\nintro_img = pygame.image.load('0.png').convert()\nicon_img = pygame.image.load('mm.png')\ncloud_img = pygame.image.load('cloud.png')\ncloud2_img = pygame.image.load('cloud2.png')\ngame_img_01 = pygame.image.load('img_01.png')\ngame_img_02 = pygame.image.load('img_02.png')\ngame_img_03 = pygame.image.load('img_03.png')\ngame_img_04 = pygame.image.load('img_04.png')\ngame_img_05 = pygame.image.load('img_06.png')\nred_img = pygame.image.load('red_2.png')\n\nwoman_img = pygame.image.load('girl.png')\nwoman_img_v = pygame.transform.scale(woman_img, (100, 550))\nman_img = pygame.image.load('boy.png')\nman_img_v = pygame.transform.scale(man_img, (100, 550))\n\n\npygame.display.set_icon(icon_img)\n\nclock = pygame.time.Clock()\n\n#fontsize\nXsmallfont = pygame.font.Font('aa.ttf', 20)\nsmallfont = pygame.font.Font('aa.ttf', 30)\nmediumfont = pygame.font.Font('aa.ttf', 50)\nlargefont = pygame.font.Font('aa.ttf', 80)\nXlargefont = pygame.font.Font('aa.ttf', 130)\n\n#colors\nblack = (0, 0, 0)\nwhite = (255, 255, 255)\nred = (255, 0, 0)\ngreen = (34,177,76)\nblue = (0,0,255)\ndarkBlue = (0,0,128)\npink = (255,200,200)\nyellow = (200,200,0)\nlight_green = (0,255,0)\nlight_red = (255,0,0)\nlight_yellow = (255,255,0)\nlight_pink = (255,170,170)\nlight_black = (30, 30, 30)\n\n\n#함수\ndef woman():\n\n\twoman_exit = False\n\n\twhile not woman_exit:\n\t\tfor event in pygame.event.get():\n\t\t\tif event == pygame.QUIT:\n\t\t\t\tpygame.quit()\n\t\t\t\tquit()\n\t\t\tif event.type == pygame.KEYDOWN:\n\t\t\t\tif event.key == pygame.K_ESCAPE:\n\t\t\t\t\tpause()\n\t\t\t\tif event.key == pygame.K_m:\n\t\t\t\t\tgame_intro()\n\n\t\tgame_display.blit(intro_img, (0,0))\n\t\tgame_display.blit(woman_img_v, (0, 15))\n\t\tmessage(\" 여성님 환영합니다!\",\n\t\t\t\tblack,\n\t\t\t\t-90,\n\t\t\t\t\"large\")\n\t\tmessage(\" 게임을 시작하겠습니까?\",\n\t\t\t\tblack,\n\t\t\t\t-0,\n\t\t\t\t\"large\")\n\n\t\tbutton(\"YES\", 166,400,150,80, pink, light_pink, action = \"YES\")\n\t\tbutton(\"NO\", 800-150-166,400,150,80, pink, light_pink, action = \"NO\")\n\n\t\tpygame.display.update()\n\ndef man():\n\n\tman_exit = False\n\n\twhile not man_exit:\n\t\tfor event in pygame.event.get():\n\t\t\tif event == pygame.QUIT:\n\t\t\t\tpygame.quit()\n\t\t\t\tquit()\n\t\t\tif event.type == pygame.KEYDOWN:\n\t\t\t\tif event.key == pygame.K_ESCAPE:\n\t\t\t\t\tpause()\n\t\t\t\tif event.key == pygame.K_m:\n\t\t\t\t\tgame_intro()\n\n\t\tgame_display.blit(intro_img, (0,0))\n\t\tgame_display.blit(man_img_v, (0, 15))\n\t\tmessage(\" 남성님 환영합니다!\",\n\t\t\t\tblack,\n\t\t\t\t-90,\n\t\t\t\t\"large\")\n\t\tmessage(\" 게임을 시작하겠습니까?\",\n\t\t\t\tblack,\n\t\t\t\t-0,\n\t\t\t\t\"large\")\n\n\t\tbutton(\"YES\", 166,400,150,80, black, light_black, action = \"YES\")\n\t\tbutton(\"NO\", 800-150-166,400,150,80, black, light_black, action = \"NO\")\n\n\t\tpygame.display.update()\n\ndef button(text, x, y, width, height, inactive_color, active_color, action = None): #text_color = black\n\tcur = pygame.mouse.get_pos()\n\tclick = pygame.mouse.get_pressed()\n\t#print(click)\n\tif x + width > cur[0] > x and y + height > cur[1] > y:\n\t\tpygame.draw.rect(game_display, active_color, (x,y,width,height))\n\t\tif click[0] == 1 and action != None:\n\t\t\tif action == \"여성\":\n\t\t\t\twoman()\n\t\t\tif action == \"남성\":\n\t\t\t\tman()\n\t\t\tif action == \"YES\":\n\t\t\t\tgame_start()\n\t\t\tif action == \"NO\":\n\t\t\t\tchoose_sex()\n\t\t\tif action == \"그만하기\":\n\t\t\t\tpygame.quit()\n\t\t\t\tquit()\n\t\t\tif action == \"다시하기\":\n\t\t\t\tgame_intro()\n\n\telse:\n\t\tpygame.draw.rect(game_display, inactive_color, (x,y,width,height))\n\n\ttext_to_button(text,black,x,y,width,height)\n\ndef text_to_button(msg, color, buttonx, buttony, buttonwidth, buttonheight, size = \"small\"):\n\ttextSurf, textRect = text_size(msg, white, \"large\")\n\ttextRect.center = ((buttonx +(buttonwidth/2)), buttony+(buttonheight/2))\n\tgame_display.blit(textSurf, textRect)\n\ndef game_Manual():\n\tgM = True\n\n\twhile gM:\n\t\tfor event in pygame.event.get():\n\t\t\tif event == pygame.QUIT:\n\t\t\t\tpygame.quit()\n\t\t\t\tquit()\n\t\t\tif event.type == pygame.KEYDOWN:\n\t\t\t\tif event.key == pygame.K_ESCAPE:\n\t\t\t\t\tpause()\n\t\t\t\tif event.key == pygame.K_m:\n\t\t\t\t\tgame_intro()\n\n\t\tgame_display.blit(intro_img,[0,0])\n\t\tmessage(\"본격! 육성, 나만의 틀린그림찾기 게임은 오직 당신만을 위한 게임입니다\",\n\t\t\t\tblack,\n\t\t\t\t-100,\n\t\t\t\tsize = \"Xsmall\")\n\t\tmessage(\"다른 틀린그림찾기와 많은 차별점으로 당신께 다가가겠습니다 \",\n\t\t\t\tblack,\n\t\t\t\t-75,\n\t\t\t\tsize = \"Xsmall\")\n\t\timg_change_color(\"단축키 설명\", 166.7,300,145,120,cloud_img, cloud2_img, action = \"단축키 설명\")\n\t\timg_change_color(\"제작사\", 166.7*2 + 145 ,300,145,120,cloud_img, cloud2_img, action = \"제작사\")\n\n\t\tpygame.display.update()\n\t\tclock.tick(60)\n\ndef pause():\n\tpaused = True\n\n\twhile paused:\n\t\tgame_display.blit(intro_img,[0,0])\n\t\tmessage(\"게임 중지\",\n\t\t\t\tblack,\n\t\t\t\t0,\n\t\t\t\tsize = \"Xlarge\")\n\n\t\tfor event in pygame.event.get():\n\t\t\tif event.type == pygame.QUIT:\n\t\t\t\tpygame.quit()\n\t\t\t\tquit()\n\t\t\telif event.type == pygame.KEYDOWN:\n\t\t\t\tif event.key == pygame.K_ESCAPE:\n\t\t\t\t\tpaused = False\n\t\t\t\tif event.key == pygame.K_m:\n\t\t\t\t\tgame_intro()\n\n\t\tpygame.display.update()\n\t\ttime.sleep(0.01)\n\ndef author():\n\n\tauthor_exit = False\n\n\twhile not author_exit:\n\t\tfor event in pygame.event.get():\n\t\t\tif event.type == pygame.QUIT:\n\t\t\t\tpygame.quit()\n\t\t\t\tquit()\n\t\t\tif event.type == pygame.KEYDOWN:\n\t\t\t\tif event.key == pygame.K_ESCAPE:\n\t\t\t\t\tpause()\n\t\t\t\tif event.key == pygame.K_m:\n\t\t\t\t\tgame_intro()\n\n\t\tgame_display.blit(intro_img, (0,0))\n\t\tmessage(\"(주)막장드라마\", black, -100, \"large\")\n\t\tmessage(\"김동원\", black, -35, \"medium\")\n\t\tmessage(\"김영기\", black, 20, \"medium\")\n\t\tmessage(\"박민수\", black, 75, \"medium\")\n\t\tmessage(\"이아름\", black, 130, \"medium\")\n\t\tmessage(\"이용승\", black, 185, \"medium\")\n\n\t\tpygame.display.update()\n\ndef key_explain():\n\n\tkey_explain = False\n\n\twhile not key_explain:\n\t\tfor event in pygame.event.get():\n\t\t\tif event.type == pygame.QUIT:\n\t\t\t\tpygame.quit()\n\t\t\t\tquit()\n\t\t\tif event.type == pygame.KEYDOWN:\n\t\t\t\tif event.key == pygame.K_ESCAPE:\n\t\t\t\t\tpause()\n\t\t\t\tif event.key == pygame.K_m:\n\t\t\t\t\tgame_intro()\n\n\t\tgame_display.blit(intro_img, (0,0))\n\t\tmessage(\"ESC*1 = 중지\", black, -90, \"large\")\n\t\tmessage(\"ESC*2 = 중지 취소\", black, 0, \"large\")\n\t\tmessage(\"M = 처음으로\", black, 90, \"large\")\n\n\t\tpygame.display.update()\n\ndef You_win():\n\n\tYou_win_exit = False\n\n\twhile not You_win_exit:\n\t\tfor event in pygame.event.get():\n\t\t\tif event.type == pygame.QUIT:\n\t\t\t\tpygame.quit()\n\t\t\t\tquit()\n\t\t\tif event.type == pygame.KEYDOWN:\n\t\t\t\tif event.key == pygame.K_ESCAPE:\n\t\t\t\t\tpause()\n\t\t\t\tif event.key == pygame.K_SPACE:\n\t\t\t\t\tNEXT = True\n\t\t\t\tif event.key == pygame.K_m:\n\t\t\t\t\tgame_intro()\n\n\t\tgame_display.blit(intro_img, (0,0))\n\t\tmessage(\"You Win!!!!\", black, -30, \"large\")\n\n\t\tbutton(\"그만하기\", 166,400,220,80, yellow, light_yellow, action = \"그만하기\")\n\t\tbutton(\"다시하기\", 800-150-166,400,220,80, yellow, light_yellow, action = \"다시하기\")\n\n\t\tpygame.display.update()\n\ndef game_intro():\n\tintro = True\n\n\twhile intro:\n\t\tfor event in pygame.event.get():\n\t\t\tif event.type == pygame.QUIT:\n\t\t\t\tpygame.quit()\n\t\t\t\tquit()\n\t\t\tif event.type == pygame.KEYDOWN:\n\t\t\t\tif event.key == pygame.K_ESCAPE:\n\t\t\t\t\tpause()\n\t\t\t\tif event.key == pygame.K_m:\n\t\t\t\t\tgame_intro()\n\n\t\tgame_display.blit(intro_img,[0,0])\n\t\tmessage(\"본격! 육성, 나만의\",\n\t\t\t\tblack,\n\t\t\t\t-180,\n\t\t\t\t\"large\")\n\t\tmessage(\"틀린그림찾기\",\n\t\t\t\tblack,\n\t\t\t\t-90,\n\t\t\t\t\"large\")\n\t\timg_change_color(\"Manual\", 87.5,300,145,120,cloud_img, cloud2_img, action = \"Manual\")\n\t\timg_change_color(\"Play\", 325,300,145,120,cloud_img, cloud2_img, action = \"Play\")\n\t\timg_change_color(\"Setting\", 562.5,300,145,120,cloud_img, cloud2_img, action = \"Settings\")\n\t\timg_change_color(\"EXIT\", 325,450,145,120,cloud_img, cloud2_img, action = \"EXIT\")\n\n\t\tpygame.display.update()\n\t\t\ndef choose_sex():\n\n\tchoose_sex_exit = False\n\n\twhile not choose_sex_exit:\n\t\tfor event in pygame.event.get():\n\t\t\tif event.type == pygame.QUIT:\n\t\t\t\tpygame.quit()\n\t\t\t\tquit()\n\t\t\tif event.type == pygame.KEYDOWN:\n\t\t\t\tif event.key == pygame.K_ESCAPE:\n\t\t\t\t\tpause()\n\t\t\t\tif event.key == pygame.K_m:\n\t\t\t\t\tgame_intro()\n\n\t\tgame_display.blit(intro_img,(0,0))\n\t\tmessage(\"당신의 성별을 선택해 주세요\",\n\t\t\t\tblack,\n\t\t\t\t-90,\n\t\t\t\t\"large\")\n\t\tbutton(\"여성\", 166,350,150,100, darkBlue, blue, action = \"여성\")\n\t\tbutton(\"남성\", 484,350,150,100, darkBlue, blue, action = \"남성\")\n\n\t\tpygame.display.update()\n\ndef score(score):\n\ttext = largefont.render(\"Score: \"+str(score), True, black)\n\tgame_display.blit(text, [0,0])\n\ndef Settings():\n\n\tSettings_exit = False\n\n\twhile not Settings_exit:\n\t\tfor event in pygame.event.get():\n\t\t\tif event.type == pygame.QUIT:\n\t\t\t\tpygame.quit()\n\t\t\t\tquit()\n\t\t\tif event.type == pygame.KEYDOWN:\n\t\t\t\tif event.key == pygame.K_ESCAPE:\n\t\t\t\t\tpause()\n\t\t\t\tif event.key == pygame.K_SPACE:\n\t\t\t\t\tNEXT = True\n\t\t\t\tif event.key == pygame.K_m:\n\t\t\t\t\tgame_intro()\n\ndef img_change_color(text, x, y, width, height, img_1, img_2, action = None):\n\tcur = pygame.mouse.get_pos()\n\tclick = pygame.mouse.get_pressed()\n\n\tif x + width > cur[0] > x and y + height > cur[1] > y:\n\t\tgame_display.blit(img_2,(x,y))\n\t\tif click[0] == 1 and action != None:\n\t\t\tif action == \"Manual\":\n\t\t\t\tclick[0] == 0\n\t\t\t\tgame_Manual()\n\t\t\telif action == \"Play\":\n\t\t\t\tchoose_sex()\n\t\t\telif action == \"Settings\":\n\t\t\t\tSettings()\n\t\t\telif action == \"EXIT\":\n\t\t\t\tpygame.quit()\n\t\t\t\tquit()\t\t\t\n\t\t\telif action == \"단축키 설명\":\n\t\t\t\tkey_explain()\n\t\t\telif action == \"제작사\":\n\t\t\t\tauthor()\n\telse:\n\t\tgame_display.blit(img_1,(x,y))\n\ttext_to_img(text,black,x,y,width,height)\n\ndef message(message, color, y_displace=0, size=\"small\"):\n\ttextSurf, textRect = text_size(message, color, size)\n\ttextRect.center = (display_width / 2), (display_height / 2) + y_displace\n\tgame_display.blit(textSurf, textRect)\n\ndef text_size(text, color, size):\n\tif size == \"small\":\n\t\ttextSurface = smallfont.render(text, True, color)\n\telif size == \"Xsmall\":\n\t\ttextSurface = Xsmallfont.render(text, True, color)\n\telif size == \"medium\":\n\t\ttextSurface = mediumfont.render(text, True, color)\n\telif size == \"large\":\n\t\ttextSurface = largefont.render(text, True, color)\n\telif size == \"Xlarge\":\n\t\ttextSurface = Xlargefont.render(text, True, color)\n\n\treturn textSurface, textSurface.get_rect()\n\ndef text_to_img(message, color, button_x, button_y, button_width, button_height, size = \"Xsmall\"):\n\ttextSurf, textRect = text_size(message, color, size)\n\ttextRect.center = ((button_x +(button_width/2)), (button_y+(button_height/2)))\n\tgame_display.blit(textSurf, textRect)\n\ndef life(life):\n\tif life > 75:\n\t\tlife_color = green\n\telif life > 50:\n\t\tlife_color = yellow\n\telse:\n\t\tlife_color = red\n\tLIFE = largefont.render(\"LIFE :\", True, black)\n\tgame_display.blit(LIFE, [500,0])\n\ta = pygame.draw.rect(game_display, life_color, (683, 25, life, 25))\n\ndef stage_02():\n\tglobal sscore, Life\n\tgame_exit = False\n\tclick1 = False\n\tclick2 = False\n\tclick3 = False\n\tclick4 = False\n\tclick5 = False\n\tNEXT = False\n\twhile not game_exit:\n\t\tcur = pygame.mouse.get_pos()\n\t\tclick = pygame.mouse.get_pressed()\n\t\tgame_display.fill(white)\n\t\tgame_display.blit(game_img_02, [0,0])\n\t\tfor event in pygame.event.get():\n\t\t\tif event.type == pygame.QUIT:\n\t\t\t\tpygame.quit()\n\t\t\t\tquit()\n\t\t\tif event.type == pygame.KEYDOWN:\n\t\t\t\tif event.key == pygame.K_ESCAPE:\n\t\t\t\t\tpause()\n\t\t\t\tif event.key == pygame.K_SPACE:\n\t\t\t\t\tNEXT = True\n\t\t\t\tif event.key == pygame.K_m:\n\t\t\t\t\tgame_intro()\n\t\t\tif event.type == pygame.MOUSEBUTTONDOWN and event.button == 1:\n\t\t\t\t# x, y = event.pos\n\t\t\t\tif 690 > cur[0] > 660 and 130 > cur[1] > 103:\n\t\t\t\t\tsscore += 2\n\t\t\t\t\tclick1 = True\n\t\t\t\telif 620 > cur[0] > 570 and 270 > cur[1] > 225:\n\t\t\t\t\tsscore += 2\n\t\t\t\t\tclick2 = True\n\t\t\t\telif 635 > cur[0] > 615 and 125 > cur[1] > 100:\n\t\t\t\t\tsscore += 2\n\t\t\t\t\tclick3 = True\n\t\t\t\telif 595 > cur[0] > 560 and 435 > cur[1] > 390:\n\t\t\t\t\tclick4 = True\n\t\t\t\t\tsscore += 2\n\t\t\t\telif 590 > cur[0] > 540 and 555 > cur[1] > 505:\n\t\t\t\t\tclick5 = True\n\t\t\t\t\tsscore += 2\n\t\t\t\telse:\n\t\t\t\t\tpygame.draw.line(game_display,black,(cur[0] - 30, cur[1] - 30),(cur[0] + 30, cur[1] + 30),10)\n\t\t\t\t\tpygame.draw.line(game_display,black,(cur[0] + 30, cur[1] - 30),(cur[0] - 30, cur[1] + 30),10)\n\t\t\t\t\tLife -= 20\n\t\tscore(sscore)\n\t\tlife(Life)\n\t\tif click1 == True:\n\t\t\tgame_display.blit(red_img, (650,100))\n\t\tif click2 == True:\n\t\t\tgame_display.blit(red_img, (560,220))\n\t\tif click3 == True:\n\t\t\tgame_display.blit(red_img, (595,90))\n\t\tif click4 == True:\n\t\t\tgame_display.blit(red_img, (550,380))\n\t\tif click5 == True:\n\t\t\tgame_display.blit(red_img, (530,505))\n\t\tif sscore >= 15:\n\t\t\tmessage(\"STAGE CLEAR!\",\n\t\t\t\t\tblack,\n\t\t\t\t\t-90,\n\t\t\t\t\t\"large\")\n\t\t\tmessage(\"다음스테이지로 이동은\",\n\t\t\t\t\tblack,\n\t\t\t\t\t0,\n\t\t\t\t\t\"large\")\n\t\t\tmessage(\"SPACE BAR\",\n\t\t\t\t\tblack,\n\t\t\t\t\t90,\n\t\t\t\t\t\"large\")\n\n\t\tif Life <= 0:\n\t\t\tgame_over()\n\n\t\tif NEXT is True:\n\t\t\tstage_03()\n\t\tpygame.display.update()\n\t\ttime.sleep(0.13)\n\ndef stage_03():\n\tglobal sscore, Life\n\tgame_exit = False\n\tclick1 = False\n\tclick2 = False\n\tclick3 = False\n\tclick4 = False\n\tclick5 = False\n\tclick6 = False\n\tclick7 = False\n\tNEXT = False\n\twhile not game_exit:\n\t\tcur = pygame.mouse.get_pos()\n\t\tclick = pygame.mouse.get_pressed()\n\t\tgame_display.fill(white)\n\t\tgame_display.blit(game_img_03, [0,0])\n\t\tfor event in pygame.event.get():\n\t\t\tif event.type == pygame.QUIT:\n\t\t\t\tpygame.quit()\n\t\t\t\tquit()\n\t\t\tif event.type == pygame.KEYDOWN:\n\t\t\t\tif event.key == pygame.K_ESCAPE:\n\t\t\t\t\tpause()\n\t\t\t\tif event.key == pygame.K_SPACE:\n\t\t\t\t\tNEXT = True\n\t\t\t\tif event.key == pygame.K_m:\n\t\t\t\t\tgame_intro()\n\t\t\tif event.type == pygame.MOUSEBUTTONDOWN and event.button == 1:\n\t\t\t\t# x, y = event.pos\n\t\t\t\tif 675 > cur[0] > 655 and 100 > cur[1] > 60:\n\t\t\t\t\tsscore += 3\n\t\t\t\t\tclick1 = True\n\t\t\t\telif 491 > cur[0] > 410 and 240 > cur[1] > 180:\n\t\t\t\t\tsscore += 3\n\t\t\t\t\tclick2 = True\n\t\t\t\telif 585 > cur[0] > 545 and 215 > cur[1] > 155:\n\t\t\t\t\tsscore += 3\n\t\t\t\t\tclick3 = True\n\t\t\t\telif 670 > cur[0] > 645 and 550 > cur[1] > 500:\n\t\t\t\t\tclick4 = True\n\t\t\t\t\tsscore += 3\n\t\t\t\telif 475 > cur[0] > 445 and 280 > cur[1] > 250:\n\t\t\t\t\tclick5 = True\n\t\t\t\t\tsscore += 3\n\t\t\t\telif 565 > cur[0] > 532 and 360 > cur[1] > 315:\n\t\t\t\t\tclick6 = True\n\t\t\t\t\tsscore += 3\n\t\t\t\telif 790 > cur[0] > 760 and 430 > cur[1] > 375:\n\t\t\t\t\tclick7 = True\n\t\t\t\t\tsscore += 3\n\t\t\t\telse:\n\t\t\t\t\tpygame.draw.line(game_display,black,(cur[0] - 30, cur[1] - 30),(cur[0] + 30, cur[1] + 30),10)\n\t\t\t\t\tpygame.draw.line(game_display,black,(cur[0] + 30, cur[1] - 30),(cur[0] - 30, cur[1] + 30),10)\n\t\t\t\t\tLife -= 30\n\n\t\tscore(sscore)\n\t\tlife(Life)\n\t\tif click1 == True:\n\t\t\tgame_display.blit(red_img, (645, 60))\n\t\tif click2 == True:\n\t\t\tgame_display.blit(red_img, (420, 190))\n\t\tif click3 == True:\n\t\t\tgame_display.blit(red_img, (542, 165))\n\t\tif click4 == True:\n\t\t\tgame_display.blit(red_img, (632, 502))\n\t\tif click5 == True:\n\t\t\tgame_display.blit(red_img, (437, 242))\n\t\tif click6 == True:\n\t\t\tgame_display.blit(red_img, (525, 306))\n\t\tif click7 == True:\n\t\t\tgame_display.blit(red_img, (750, 370))\n\t\tif sscore >= 30:\n\t\t\tmessage(\"STAGE CLEAR!\",\n\t\t\t\t\tblack,\n\t\t\t\t\t-90,\n\t\t\t\t\t\"large\")\n\t\t\tmessage(\"다음스테이지로 이동은\",\n\t\t\t\t\tblack,\n\t\t\t\t\t0,\n\t\t\t\t\t\"large\")\n\t\t\tmessage(\"SPACE BAR\",\n\t\t\t\t\tblack,\n\t\t\t\t\t90,\n\t\t\t\t\t\"large\")\n\n\t\tif Life <= 0:\n\t\t\tgame_over()\n\n\t\tif NEXT is True:\n\t\t\tstage_04()\n\n\t\tpygame.display.update()\n\t\ttime.sleep(0.13)\n\ndef stage_04():\n\tglobal sscore, Life\n\tgame_exit = False\n\tclick1 = False\n\tclick2 = False\n\tclick3 = False\n\tclick4 = False\n\tclick5 = False\n\tclick6 = False\n\tNEXT = False\n\twhile not game_exit:\n\t\tcur = pygame.mouse.get_pos()\n\t\tclick = pygame.mouse.get_pressed()\n\t\tgame_display.fill(white)\n\t\tgame_display.blit(game_img_04, [0,0])\n\t\tfor event in pygame.event.get():\n\t\t\tif event.type == pygame.QUIT:\n\t\t\t\tpygame.quit()\n\t\t\t\tquit()\n\t\t\tif event.type == pygame.KEYDOWN:\n\t\t\t\tif event.key == pygame.K_ESCAPE:\n\t\t\t\t\tpause()\n\t\t\t\tif event.key == pygame.K_SPACE:\n\t\t\t\t\tNEXT = True\n\t\t\t\tif event.key == pygame.K_m:\n\t\t\t\t\tgame_intro()\n\t\t\tif event.type == pygame.MOUSEBUTTONDOWN and event.button == 1:\n\t\t\t\t# x, y = event.pos\n\t\t\t\tif 700 > cur[0] > 650 and 300 > cur[1] > 255:\n\t\t\t\t\tsscore += 4\n\t\t\t\t\tclick1 = True\n\t\t\t\telif 540 > cur[0] > 465 and 330 > cur[1] > 275:\n\t\t\t\t\tsscore += 4\n\t\t\t\t\tclick2 = True\n\t\t\t\telif 470 > cur[0] > 440 and 280 > cur[1] > 250:\n\t\t\t\t\tsscore += 4\n\t\t\t\t\tclick3 = True\n\t\t\t\telif 675 > cur[0] > 645 and 385 > cur[1] > 340:\n\t\t\t\t\tclick4 = True\n\t\t\t\t\tsscore += 4\n\t\t\t\telif 765 > cur[0] > 730 and 400 > cur[1] > 350:\n\t\t\t\t\tclick5 = True\n\t\t\t\t\tsscore += 4\n\t\t\t\telif 435 > cur[0] > 400 and 300 > cur[1] > 270:\n\t\t\t\t\tclick6 = True\n\t\t\t\t\tsscore += 4\n\t\t\t\telse:\n\t\t\t\t\tpygame.draw.line(game_display,black,(cur[0] - 30, cur[1] - 30),(cur[0] + 30, cur[1] + 30),10)\n\t\t\t\t\tpygame.draw.line(game_display,black,(cur[0] + 30, cur[1] - 30),(cur[0] - 30, cur[1] + 30),10)\n\t\t\t\t\tLife -= 40\n\n\t\tscore(sscore)\n\t\tlife(Life)\n\t\tif click1 == True:\n\t\t\tgame_display.blit(red_img, (650, 250))\n\t\tif click2 == True:\n\t\t\tgame_display.blit(red_img, (470, 264))\n\t\tif click3 == True:\n\t\t\tgame_display.blit(red_img, (430, 240))\n\t\tif click4 == True:\n\t\t\tgame_display.blit(red_img, (630, 342))\n\t\tif click5 == True:\n\t\t\tgame_display.blit(red_img, (720, 355))\n\t\tif sscore >= 50:\n\t\t\tmessage(\"STAGE CLEAR!\",\n\t\t\t\t\tblack,\n\t\t\t\t\t-90,\n\t\t\t\t\t\"large\")\n\t\t\tmessage(\"다음스테이지로 이동은\",\n\t\t\t\t\tblack,\n\t\t\t\t\t0,\n\t\t\t\t\t\"large\")\n\t\t\tmessage(\"SPACE BAR\",\n\t\t\t\t\tblack,\n\t\t\t\t\t90,\n\t\t\t\t\t\"large\")\n\n\t\tif Life <= 0:\n\t\t\tgame_over()\n\n\t\tif NEXT is True:\n\t\t\tstage_05()\n\t\tpygame.display.update()\n\t\ttime.sleep(0.13)\n\ndef stage_05():\n\tglobal sscore, Life\n\tgame_exit = False\n\tclick1 = False\n\tclick2 = False\n\tclick3 = False\n\tclick4 = False\n\tclick5 = False\n\tclick6 = False\n\tNEXT = False\n\twhile not game_exit:\n\t\tcur = pygame.mouse.get_pos()\n\t\tclick = pygame.mouse.get_pressed()\n\t\tgame_display.fill(white)\n\t\tgame_display.blit(game_img_05, [0,0])\n\t\tfor event in pygame.event.get():\n\t\t\tif event.type == pygame.QUIT:\n\t\t\t\tpygame.quit()\n\t\t\t\tquit()\n\t\t\tif event.type == pygame.KEYDOWN:\n\t\t\t\tif event.key == pygame.K_ESCAPE:\n\t\t\t\t\tpause()\n\t\t\t\tif event.key == pygame.K_SPACE:\n\t\t\t\t\tNEXT = True\n\t\t\t\tif event.key == pygame.K_m:\n\t\t\t\t\tgame_intro()\n\t\t\tif event.type == pygame.MOUSEBUTTONDOWN and event.button == 1:\n\t\t\t\t# x, y = event.pos\n\t\t\t\tif 580 > cur[0] > 560 and 205 > cur[1] > 175:\n\t\t\t\t\tsscore += 5\n\t\t\t\t\tclick1 = True\n\t\t\t\telif 445 > cur[0] > 409 and 145 > cur[1] > 110:\n\t\t\t\t\tsscore += 5\n\t\t\t\t\tclick2 = True\n\t\t\t\telif 515 > cur[0] > 465 and 195 > cur[1] > 170:\n\t\t\t\t\tsscore += 5\n\t\t\t\t\tclick3 = True\n\t\t\t\telif 595 > cur[0] > 535 and 490 > cur[1] > 465:\n\t\t\t\t\tclick4 = True\n\t\t\t\t\tsscore += 5\n\t\t\t\telif 767 > cur[0] > 675 and 590 > cur[1] > 560:\n\t\t\t\t\tclick5 = True\n\t\t\t\t\tsscore += 5\n\t\t\t\telse:\n\t\t\t\t\tpygame.draw.line(game_display,black,(cur[0] - 30, cur[1] - 30),(cur[0] + 30, cur[1] + 30),10)\n\t\t\t\t\tpygame.draw.line(game_display,black,(cur[0] + 30, cur[1] - 30),(cur[0] - 30, cur[1] + 30),10)\n\t\t\t\t\tLife -= 50\n\n\t\tscore(sscore)\n\t\tlife(Life)\n\t\tif click1 == True:\n\t\t\tgame_display.blit(red_img, (545, 170))\n\t\tif click2 == True:\n\t\t\tgame_display.blit(red_img, (400, 105))\n\t\tif click3 == True:\n\t\t\tgame_display.blit(red_img, (453, 162))\n\t\tif click4 == True:\n\t\t\tgame_display.blit(red_img, (533, 453))\n\t\tif click5 == True:\n\t\t\tgame_display.blit(red_img, (685, 550))\n\t\tif sscore >= 75:\n\t\t\tmessage(\"ALL GAME CLEAR!!\",\n\t\t\t\t\tblack,\n\t\t\t\t\t-90,\n\t\t\t\t\t\"large\")\n\t\t\tmessage(\"다시 시작은\",\n\t\t\t\t\tblack,\n\t\t\t\t\t0,\n\t\t\t\t\t\"large\")\n\t\t\tmessage(\"SPACE BAR\",\n\t\t\t\t\tblack,\n\t\t\t\t\t90,\n\t\t\t\t\t\"large\")\n\n\t\tif Life <= 0:\n\t\t\tgame_over()\n\n\t\tif NEXT is True:\n\t\t\tsscore = 0\n\t\t\tLife = 100\n\t\t\tYou_win()\n\n\t\tpygame.display.update()\n\t\ttime.sleep(0.13)\n\ndef game_start():\n\tglobal sscore, Life\n\tgame_exit = False\n\tclick1 = False\n\tclick2 = False\n\tclick3 = False\n\tclick4 = False\n\tclick5 = False\n\tNEXT = False\n\twhile not game_exit:\n\t\tcur = pygame.mouse.get_pos()\n\t\tclick = pygame.mouse.get_pressed()\n\t\tgame_display.fill(white)\n\t\tgame_display.blit(game_img_01, [0,0])\n\n\t\tfor event in pygame.event.get():\n\t\t\tprint(event)\n\t\t\tif event.type == pygame.QUIT:\n\t\t\t\tpygame.quit()\n\t\t\t\tquit()\n\t\t\tif event.type == pygame.KEYDOWN:\n\t\t\t\tif event.key == pygame.K_ESCAPE:\n\t\t\t\t\tpause()\n\t\t\t\tif event.key == pygame.K_SPACE:\n\t\t\t\t\tNEXT = True\n\t\t\t\tif event.key == pygame.K_m:\n\t\t\t\t\tgame_intro()\n\n\t\t\tif event.type == pygame.MOUSEBUTTONDOWN and event.button == 1:\n\t\t\t\t# x, y = event.pos\n\t\t\t\tif 455 > cur[0] > 410 and 340 > cur[1] > 270:\n\t\t\t\t\tsscore += 1\n\t\t\t\t\tclick1 = True\n\t\t\t\telif 630 > cur[0] > 585 and 400 > cur[1] > 345:\n\t\t\t\t\tsscore += 1\n\t\t\t\t\tclick2 = True\n\t\t\t\telif 635 > cur[0] > 600 and 150 > cur[1] > 112:\n\t\t\t\t\tsscore += 1\n\t\t\t\t\tclick3 = True\n\t\t\t\telif 675 > cur[0] >645 and 255 > cur[1] > 210:\n\t\t\t\t\tclick4 = True\n\t\t\t\t\tsscore += 1\n\t\t\t\telif 780 > cur[0] > 740 and 215 > cur[1] > 170:\n\t\t\t\t\tclick5 = True\n\t\t\t\t\tsscore += 1\t\n\t\t\t\telse:\n\t\t\t\t\tpygame.draw.line(game_display,black,(cur[0] - 30, cur[1] - 30),(cur[0] + 30, cur[1] + 30),10)\n\t\t\t\t\tpygame.draw.line(game_display,black,(cur[0] + 30, cur[1] - 30),(cur[0] - 30, cur[1] + 30),10)\n\t\t\t\t\tLife -= 20\t\n\n\t\tscore(sscore)\n\t\tlife(Life)\n\t\tif click1 == True:\n\t\t\tgame_display.blit(red_img, (415,303))\n\t\tif click2 == True:\n\t\t\tgame_display.blit(red_img, (590,352))\n\t\tif click3 == True:\n\t\t\tgame_display.blit(red_img, (600,110))\n\t\tif click4 == True:\n\t\t\tgame_display.blit(red_img, (634,210))\n\t\tif click5 == True:\n\t\t\tgame_display.blit(red_img, (735,170))\n\t\tif sscore >= 5:\n\t\t\tmessage(\"STAGE CLEAR!\",\n\t\t\t\t\tblack,\n\t\t\t\t\t-90,\n\t\t\t\t\t\"large\")\n\t\t\tmessage(\"다음스테이지로 이동은\",\n\t\t\t\t\tblack,\n\t\t\t\t\t0,\n\t\t\t\t\t\"large\")\n\t\t\tmessage(\"SPACE BAR\",\n\t\t\t\t\tblack,\n\t\t\t\t\t90,\n\t\t\t\t\t\"large\")\n\n\t\tif Life <= 0:\n\t\t\tgame_over()\n\n\t\tif NEXT is True:\n\t\t\tstage_02()\n\n\t\tpygame.display.update()\n\t\ttime.sleep(0.13)\n\ndef game_over():\n\n\tgame_over_exit = False\n\n\twhile not game_over_exit:\n\t\tfor event in pygame.event.get():\n\t\t\tprint(event)\n\t\t\tif event.type == pygame.QUIT:\n\t\t\t\tpygame.quit()\n\t\t\t\tquit()\n\t\t\tif event.type == pygame.KEYDOWN:\n\t\t\t\tif event.key == pygame.K_ESCAPE:\n\t\t\t\t\tpause()\n\t\t\t\tif event.key == pygame.K_SPACE:\n\t\t\t\t\tNEXT = True\n\t\t\t\tif event.key == pygame.K_m:\n\t\t\t\t\tgame_intro()\n\n\t\tgame_display.blit(intro_img, (0,0))\n\n\t\tmessage(\"LOSE\",\n\t\t\t\t\t\tblack,\n\t\t\t\t\t\t-30,\n\t\t\t\t\t\t\"large\")\n\n\t\tbutton(\"그만하기\", 166,400,220,80, yellow, light_yellow, action = \"그만하기\")\n\t\tbutton(\"다시하기\", 800-150-166,400,220,80, yellow, light_yellow, action = \"다시���기\")\n\n\t\tpygame.display.update()\n\ngame_intro()","sub_path":"civil_mid_final/막장드라마조/foryou.py","file_name":"foryou.py","file_ext":"py","file_size_in_byte":22264,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"215424799","text":"import ipaddress\nimport logging\nimport os\nimport re\nfrom urllib.parse import urlsplit\n#from urlfinderlib import is_valid\n\n\nclass SIPWhitelist:\n def __init__(self, whitelist_tags, sip):\n \"\"\" Initiates the SIP whitelist system.\n\n whitelist_tags: A list of tags from Deprecated SIP indicators you want included in your whitelist.\n sip: A connected PySIP object (see https://github.com/integraldefense/pysip for details)\n \"\"\"\n\n # Initiate logging.\n self.logger = logging.getLogger()\n\n # Set up the whitelist and cache.\n self.whitelist = {}\n self.cache_whitelisted = []\n self.cache_nonwhitelisted = []\n\n try:\n # Search for the whitelisted indicators with raw mongo because the API is slow.\n sip_result = sip.get('/api/indicators?status=Deprecated&tags={}&bulk=true'.format(','.join(whitelist_tags)))\n for r in sip_result:\n if not r['type'] in self.whitelist:\n self.whitelist[r['type']] = []\n\n # If this indicator is an \"Address - ipv4-net\", make it an IPv4Network.\n if r['type'] == 'Address - ipv4-net':\n try:\n self.whitelist[r['type']].append(ipaddress.ip_network(r['value'], strict=False))\n except:\n pass\n # Otherwise just add the value to the whitelist.\n else:\n self.whitelist[r['type']].append(r['value'])\n\n # Make sure the whitelist only contains unique entries.\n for indicator_type in self.whitelist:\n self.whitelist[indicator_type] = list(set(self.whitelist[indicator_type]))\n except:\n self.logger.exception('Error getting whitelisted indicators from SIP.')\n\n def _is_cached_whitelisted(self, thing):\n \"\"\" Checks if 'thing' has been added to the whitelisted cache. \"\"\"\n\n if thing:\n if str(thing).lower() in self.cache_whitelisted:\n self.logger.debug('Cached whitelisted: {}'.format(thing))\n return True\n return False\n\n def _is_cached_nonwhitelisted(self, thing):\n \"\"\" Checks if 'thing' has been added to the nonwhitelisted cache. \"\"\"\n\n if thing:\n if str(thing).lower() in self.cache_nonwhitelisted:\n self.logger.debug('Cached non-whitelisted: {}'.format(thing))\n return True\n return False\n\n def _add_whitelisted_cache(self, thing):\n \"\"\" Adds 'thing' to the whitelisted cache. Removes it from the nonwhitelisted cache if it exists. \"\"\"\n\n try:\n self.logger.debug(\"Adding '{}' to the whitelist cache.\".format(thing))\n self.cache_whitelisted.append(str(thing).lower())\n except:\n pass\n\n try:\n self._remove_nonwhitelisted_cache(str(thing).lower())\n except:\n pass\n\n def _remove_whitelisted_cache(self, thing):\n \"\"\" Removes 'thing' from the whitelisted cache. \"\"\"\n\n try:\n self.cache_whitelisted.remove(str(thing).lower())\n except:\n pass\n\n def _add_nonwhitelisted_cache(self, thing):\n \"\"\" Adds 'thing' to the nonwhitelisted cache. Removes it from the whitelisted cache if it exists. \"\"\"\n\n try:\n self.cache_nonwhitelisted.append(str(thing).lower())\n except:\n pass\n\n try:\n self._remove_whitelisted_cache(str(thing).lower())\n except:\n pass\n\n def _remove_nonwhitelisted_cache(self, thing):\n \"\"\" Removes 'thing' from the nonwhitelisted cache. \"\"\"\n\n try:\n self.cache_nonwhitelisted.remove(str(thing).lower())\n except:\n pass\n\n def _is_whitelisted(self, thing, indicator_types, value_in_indicator=True, indicator_in_value=False, verbose_check=False):\n \"\"\" Check if 'thing' is whitelisted by the given indicator types. \"\"\"\n\n # helpful debug log\n self.logger.debug(\"Checking for '{}' with types:{} and value_in_indicator={} and indicator_in_value={} and verbose_check={}\\\n \".format(thing, indicator_types, value_in_indicator, indicator_in_value, verbose_check))\n\n # Make sure we actually have a \"thing\".\n if not thing:\n self.logger.debug('Given an invalid thing to check!')\n return True\n\n # First check if 'thing' was already cached.\n if self._is_cached_whitelisted(thing):\n return True\n if self._is_cached_nonwhitelisted(thing):\n return False\n \n # used if verbose_check is True\n results = {}\n\n try:\n for indicator_type in indicator_types:\n if indicator_type in self.whitelist:\n for indicator in self.whitelist[indicator_type]:\n # Return True if there is an exact match.\n if thing.lower() == indicator.lower():\n self._add_whitelisted_cache(thing)\n self.logger.debug('Exact {} whitelist match: {}'.format(indicator_type, thing))\n if verbose_check:\n if indicator_type not in results:\n results[indicator_type] = []\n results[indicator_type].append((thing, indicator))\n continue\n else:\n return True\n # Check if we want to look for the value inside the indicator.\n # This accounts for there already being a more specific version of\n # \"thing\" already whitelisted in SIP.\n if value_in_indicator:\n if thing.lower() in indicator.lower():\n self._add_whitelisted_cache(thing)\n self.logger.debug('{} is in whitelisted {} indicator: {}'.format(thing, indicator_type, indicator))\n if verbose_check:\n if indicator_type not in results:\n results[indicator_type] = []\n results[indicator_type].append((thing, indicator))\n continue\n else:\n return True\n # Check if we want to look for the indicator inside the value.\n # This accounts for things like file paths, where we want to\n # whitelist a directory and everything inside of it.\n if indicator_in_value:\n if indicator.lower() in thing.lower():\n self._add_whitelisted_cache(thing)\n self.logger.debug('Whitelisted {} indicator {} is in: {}'.format(indicator_type, thing, indicator))\n if verbose_check:\n if indicator_type not in results:\n results[indicator_type] = []\n results[indicator_type].append((thing, indicator))\n else:\n return True\n except:\n self.logger.exception('Could not check \"{}\" against whitelist types: {}'.format(thing, indicator_types))\n\n if verbose_check and results:\n return results\n\n self._add_nonwhitelisted_cache(thing)\n return False\n\n \"\"\"\n #\n # FILE WHITELIST\n #\n \"\"\"\n def _is_hash_whitelisted(self, hash_value, hash_type, **kwargs):\n \"\"\" Returns True if the hash_value is invalid or whitelisted. \"\"\"\n\n # First check if the hash_value was already cached.\n if self._is_cached_whitelisted(hash_value):\n return True\n if self._is_cached_nonwhitelisted(hash_value):\n return False\n\n # Check if the hash_value is valid.\n try:\n if hash_type == 'Hash - MD5':\n if not re.compile(r'^[a-fA-F0-9]{32}$').match((hash_value)):\n self._add_whitelisted_cache(hash_value)\n self.logger.debug('Invalid MD5 hash: {}'.format(hash_value))\n return True\n if hash_type == 'Hash - SHA1':\n if not re.compile(r'^[a-fA-F0-9]{40}$').match((hash_value)):\n self._add_whitelisted_cache(hash_value)\n self.logger.debug('Invalid SHA1 hash: {}'.format(hash_value))\n return True\n if hash_type == 'Hash - SHA256':\n if not re.compile(r'^[a-fA-F0-9]{64}$').match((hash_value)):\n self._add_whitelisted_cache(hash_value)\n self.logger.debug('Invalid SHA256 hash: {}'.format(hash_value))\n return True\n if hash_type == 'Hash - SHA512':\n if not re.compile(r'^[a-fA-F0-9]{128}$').match((hash_value)):\n self._add_whitelisted_cache(hash_value)\n self.logger.debug('Invalid SHA512 hash: {}'.format(hash_value))\n return True\n except:\n self._add_whitelisted_cache(hash_value)\n return True\n\n return self._is_whitelisted(hash_value, [hash_type], value_in_indicator=False, **kwargs)\n\n def is_md5_whitelisted(self, md5, **kwargs):\n \"\"\" Returns True if the MD5 is invalid or whitelisted. \"\"\"\n\n return self._is_hash_whitelisted(md5, 'Hash - MD5')\n\n def is_sha1_whitelisted(self, sha1, **kwargs):\n \"\"\" Returns True if the SHA1 is invalid or whitelisted. \"\"\"\n\n return self._is_hash_whitelisted(sha1, 'Hash - SHA1', **kwargs)\n\n def is_sha256_whitelisted(self, sha256, **kwargs):\n \"\"\" Returns True if the SHA256 is invalid or whitelisted. \"\"\"\n\n return self._is_hash_whitelisted(sha256, 'Hash - SHA256', **kwargs)\n\n def is_sha512_whitelisted(self, sha512, **kwargs):\n \"\"\" Returns True if the SHA512 is invalid or whitelisted. \"\"\"\n\n return self._is_hash_whitelisted(sha512, 'Hash - SHA512', **kwargs)\n\n def is_ssdeep_whitelisted(self, ssdeep, **kwargs):\n \"\"\" Returns True if the ssdeep is whitelisted. \"\"\"\n\n return self._is_whitelisted(ssdeep, ['Hash - SSDEEP'], **kwargs)\n\n def is_file_name_whitelisted(self, name, value_in_indicator=False, indicator_in_value=True, **kwargs):\n \"\"\" Returns True if the file name is whitelisted. \"\"\"\n\n return self._is_whitelisted(name, ['Windows - FileName'], value_in_indicator=value_in_indicator, indicator_in_value=indicator_in_value, **kwargs)\n\n def is_file_path_whitelisted(self, path, value_in_indicator=True, indicator_in_value=True, **kwargs):\n \"\"\" Returns True if the file path is whitelisted. \"\"\"\n\n return self._is_whitelisted(path, ['Windows - FilePath'], value_in_indicator=value_in_indicator, indicator_in_value=indicator_in_value, **kwargs)\n\n \"\"\"\n #\n # EMAIL WHITELIST\n #\n \"\"\"\n def is_email_subject_whitelisted(self, subject, value_in_indicator=True, indicator_in_value=False, **kwargs):\n \"\"\" Returns True if the subject is whitelisted. \"\"\"\n\n return self._is_whitelisted(subject, ['Email - Subject'], value_in_indicator=value_in_indicator, indicator_in_value=indicator_in_value, **kwargs)\n\n def is_email_address_whitelisted(self, address, value_in_indicator=True, indicator_in_value=False, **kwargs):\n \"\"\" Returns True if the email address is whitelisted. \"\"\"\n\n # First check if the address was already cached.\n if self._is_cached_whitelisted(address):\n return True\n if self._is_cached_nonwhitelisted(address):\n return False\n\n # Check if the address is valid.\n email_pattern = re.compile(r'[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,63}')\n try:\n if not email_pattern.match(address):\n self._add_whitelisted_cache(address)\n self.logger.debug('Invalid e-mail address: {}'.format(address))\n return True\n except:\n self._add_whitelisted_cache(address)\n return True\n\n # Check if the domain is valid.\n \"\"\"\n try:\n domain = address.split('@')[1]\n if not is_valid(domain):\n self._add_whitelisted_cache(address)\n self.logger.debug('Invalid e-mail address domain: {}'.format(address))\n return True\n except:\n self._add_whitelisted_cache(address)\n return True\n \"\"\"\n\n return self._is_whitelisted(address, ['Email - Address', 'WHOIS Registrant Email Address', 'Email Address From', 'Email Address Sender'], value_in_indicator=value_in_indicator, indicator_in_value=indicator_in_value, **kwargs)\n\n \"\"\"\n #\n # NETWORK WHITELIST\n #\n \"\"\"\n def is_url_whitelisted(self, u, value_in_indicator=False, indicator_in_value=False, **kwargs):\n \"\"\" Returns True if the URL is invalid or is whitelisted. \"\"\"\n\n # First check if the URL was already cached.\n if self._is_cached_whitelisted(u):\n return True\n if self._is_cached_nonwhitelisted(u):\n return False\n\n # Check if the URL is valid.\n \"\"\"\n if not is_valid(u):\n self._add_whitelisted_cache(u)\n self.logger.debug('Invalid URL: {}'.format(u))\n return True\n \"\"\"\n\n # Split the URL and check each part against the whitelist.\n split_url = urlsplit(u)\n\n # First check if the netloc has a ':' in it, which indicates that\n # there is a port number specified. We need to remove that in order\n # to properly check it against the whitelists.\n if ':' in split_url.netloc:\n netloc = split_url.netloc.split(':')[0]\n else:\n netloc = split_url.netloc\n\n # Look for the edge case of the URL having a username:password notation.\n if ':' in split_url.netloc and '@' in split_url.netloc:\n user_pass = re.compile(r'(.*?:.*?@)').findall(split_url.netloc)[0]\n user_pass_url = u.replace(user_pass, '')\n split_url = urlsplit(user_pass_url)\n netloc = split_url.netloc\n\n # Check the netloc. Check if it is an IP address.\n try:\n ipaddress.ip_address(netloc)\n if self.is_ip_whitelisted(netloc):\n self._add_whitelisted_cache(u)\n self.logger.debug('URL whitelisted because of IP: {}'.format(u))\n return True\n # If we got an exception, it must be a domain name.\n except:\n result = self.is_domain_whitelisted(netloc, **kwargs)\n print(result)\n if result:\n self._add_whitelisted_cache(u)\n self.logger.debug('URL whitelisted because of domain: {}'.format(u))\n return True\n\n # Check the URI path if it exists.\n if split_url.path and split_url.path != '/':\n if self.is_uri_path_whitelisted(split_url.path):\n self._add_whitelisted_cache(u)\n self.logger.debug('URL whitelisted because of path: {}'.format(u))\n return True\n\n # Check the URI query if it exists.\n if split_url.query:\n if self.is_uri_path_whitelisted(split_url.query):\n self._add_whitelisted_cache(u)\n self.logger.debug('URL whitelisted \"{}\" because of query: {}'.format(u, split_url.query))\n return True\n\n # Finally check the entire URL.\n return self._is_whitelisted(u, ['URI - URL'], value_in_indicator=value_in_indicator, indicator_in_value=indicator_in_value, **kwargs)\n\n def is_uri_path_whitelisted(self, path, relationships=[], value_in_indicator=True, indicator_in_value=True, **kwargs):\n \"\"\" Returns True if the URI path is whitelisted. \"\"\"\n\n # First check if the path was already cached.\n if self._is_cached_whitelisted(path):\n return True\n if self._is_cached_nonwhitelisted(path):\n return False\n\n # Check if any of the relationships (if we were given any) are whitelisted.\n for r in relationships:\n\n # Check if the relationship is a full URL by using urlsplit. If there is no\n # netloc attribute, then it is either an IP or a domain, not a full URL.\n split = urlsplit(r)\n if not split.netloc:\n\n # Check if the relationship is an IP address.\n try:\n ipaddress.ip_address(r)\n # If the IP is whitelisted, we should whitelist that path.\n if self.is_ip_whitelisted(r):\n self._add_whitelisted_cache(path)\n self.logger.debug('{} URI - Path whitelisted because of relationship to IP address: {}'.format(path, r))\n return True\n # If we got an exception, it must be a domain name.\n except:\n # If the domain is whitelisted, we should whitelist the path.\n if self.is_domain_whitelisted(r):\n self._add_whitelisted_cache(path)\n self.logger.debug('{} URI - Path whitelisted because of relationship to domain: {}'.format(path, r))\n return True\n # Otherwise it must be a full URL.\n else:\n if self.is_url_whitelisted(r):\n self._add_whitelisted_cache(path)\n self.logger.debug('{} URI - Path whitelisted because of relationship to URL: {}'.format(path, r))\n return True\n\n return self._is_whitelisted(path, ['URI - Path'], value_in_indicator=value_in_indicator, indicator_in_value=indicator_in_value, **kwargs)\n\n def is_domain_whitelisted(self, domain, value_in_indicator=False, indicator_in_value=True, **kwargs):\n \"\"\" Returns True if the domain has an invalid TLD or is whitelisted. \"\"\"\n\n # First check if the domain was already cached.\n if self._is_cached_whitelisted(domain):\n return True\n if self._is_cached_nonwhitelisted(domain):\n return False\n\n # Check if the domain has a valid TLD.\n \"\"\"\n if not is_valid(domain):\n self._add_whitelisted_cache(domain)\n self.logger.debug('Invalid domain: {}'.format(domain))\n return True\n \"\"\"\n\n return self._is_whitelisted(domain, ['URI - Domain Name'], value_in_indicator=value_in_indicator, indicator_in_value=indicator_in_value, **kwargs)\n\n def is_ip_whitelisted(self, ip, value_in_indicator=False, indicator_in_value=False, **kwargs):\n \"\"\" Returns True if the IP is invalid, private, or whitelisted. \"\"\"\n\n # First check if the IP was already cached.\n if self._is_cached_whitelisted(ip):\n return True\n if self._is_cached_nonwhitelisted(ip):\n return False\n\n # Check if the IP address is valid.\n try:\n ipaddress.ip_address(ip)\n except:\n self._add_whitelisted_cache(ip)\n self.logger.debug('Invalid IP address: {}'.format(ip))\n return True\n\n # Make sure this is a public IP address.\n # .is_global was added in Python 3.4\n try:\n if not ipaddress.ip_address(ip).is_global:\n self._add_whitelisted_cache(ip)\n self.logger.debug('IP {} whitelisted because it is not a global address'.format(ip))\n return True\n except:\n # Make sure this is a public IP address.\n if ipaddress.ip_address(ip).is_private:\n self._add_whitelisted_cache(ip)\n self.logger.debug('IP {} whitelisted because it is a private address'.format(ip))\n return True\n\n # Check if the IP address falls inside a whitelisted network.\n try:\n for network in self.whitelist['Address - ipv4-net']:\n if ipaddress.ip_address(ip) in network:\n self._add_whitelisted_cache(ip)\n self.logger.debug('IP {} whitelisted because it is in network {}'.format(ip, network))\n return True\n except:\n self.logger.exception('Could not check IP \"{}\" against whitelisted networks'.format(ip))\n\n # Lastly check if the IP address itself is whitelisted.\n return self._is_whitelisted(ip, ['Address - ipv4-addr', 'Email Originating IP', 'Email X-Originating IP'], value_in_indicator=value_in_indicator, indicator_in_value=indicator_in_value, **kwargs)\n","sub_path":"sipwhitelist/sipwhitelist.py","file_name":"sipwhitelist.py","file_ext":"py","file_size_in_byte":20909,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"160188343","text":"# Copyright 2015 ZTE Corp.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n# not use this file except in compliance with the License. You may obtain\n# a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the\n# License for the specific language governing permissions and limitations\n# under the License.\n\nfrom horizon.tables import actions\n\n\nclass OperateRegionAction(actions.LinkAction):\n def __init__(self, attrs=None, **kwargs):\n super(OperateRegionAction, self).__init__(**kwargs)\n self.verbose_name = kwargs.get('verbose_name', self.name.title())\n self.action_type = kwargs.get('action_type', \"operate_region\")\n self.icon = kwargs.get('icon', None)\n\n\nclass AutofillAction(actions.LinkAction):\n def __init__(self, attrs=None, **kwargs):\n super(AutofillAction, self).__init__(**kwargs)\n self.verbose_name = kwargs.get('verbose_name', self.name.title())\n self.action_type = kwargs.get('action_type', \"auto_fill\")\n\n\nclass ManuallyAssignRoleAction(actions.LinkAction):\n def __init__(self, attrs=None, **kwargs):\n super(ManuallyAssignRoleAction, self).__init__(**kwargs)\n self.verbose_name = kwargs.get('verbose_name', self.name.title())\n self.action_type = kwargs.get('action_type', \"manually_assign_role\")\n self.icon = kwargs.get('icon', None)\n","sub_path":"code/horizon/openstack_dashboard/dashboards/environment/deploy/actions.py","file_name":"actions.py","file_ext":"py","file_size_in_byte":1628,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"186213550","text":"# This problem was asked by Google.\n\n# A unival tree (which stands for \"universal value\") is a tree where all nodes \n# under it have the same value.\n\n# Given the root to a binary tree, count the number of unival subtrees.\n\n# For example, the following tree has 5 unival subtrees:\n\n# 0\n# / \\\n# 1 0\n# / \\\n# 1 0\n# / \\\n# 1 1\nclass Node:\n left = None\n right = None\n value = None\n def __init__(self, value,left=None,right=None):\n self.value = value\n self.left = left\n self.right = right\n\ndef dfs(node):\n print(node.value)\n if node.left != None:\n dfs(node.left)\n if node.right != None:\n dfs(node.right)\n\ndef count_univ_value(node):\n if node.left == None and node.right == None:\n return 1\n else:\n tmp = 0\n if (node.left is not None) and (node.right is not None) and node.left.value == node.right.value:\n tmp = 1\n return tmp + (count_univ_value(node.left) if node.left is not None else 0) + (count_univ_value(node.right) if node.right is not None else 0)\n\n\ndef main():\n print('This is the 11/12/2020 problem by Google:')\n # Construct tree\n root = Node(0, left=Node(1), right=Node(0,left=Node(1,left=Node(1),right=Node(1)),right=Node(0)))\n\n # dfs to test tree\n # dfs(root)\n\n # test func:\n print(count_univ_value(root))\n\n\n # test run:\n print(\"Result = {}\".format(count_universal(root)))\n\n\n\nif __name__=='__main__':\n main()","sub_path":"11122020-Google-3.py","file_name":"11122020-Google-3.py","file_ext":"py","file_size_in_byte":1466,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"313659047","text":"import mcpi.minecraft as minecraft\nimport mcpi.block as block\nimport glob\nimport time\nimport random\n\nmc = minecraft.Minecraft.create()\nSIZEX = 10\nSIZEY = 10\nSIZEZ = 10\nroomx = 1\nroomy = 1\nroomz = 1\n\ndef buildRoom(x, y, z):\n global roomx, roomy, roomz\n\n roomx = x\n roomy = y\n roomz = z\n\n mc.setBlocks(roomx, roomy, roomz, roomx + SIZEX + 1, roomy + SIZEY + 1, roomz + SIZEZ + 1, block.GLASS.id)\n\n mc.setBlocks(roomx + 1, roomy + 1, roomz, roomx + SIZEX, roomy + SIZEY, roomz + SIZEZ, block.AIR.id)\n\ndef demolishRoom():\n global roomx, roomy, roomz\n mc.setBlocks(roomx, roomy, roomz, roomx + SIZEX + 1, roomy + SIZEY + 1, roomz + SIZEZ + 1, block.AIR.id)\n\ndef cleanRoom():\n mc.setBlocks(roomx + 1, roomy + 1, roomz + 1, roomx + SIZEX, roomy + SIZEY, roomz + SIZEZ, block.AIR.id)\n\ndef listFiles():\n print('\\nFILES:')\n files = glob.glob('*.csv')\n for filename in files:\n print(filename)\n print('\\n')\n\ndef scan3D(filename, originx, originy, originz):\n f = open(filename, \"w\")\n f.write(str(SIZEX) + \",\" + str(SIZEY) + \",\" + str(SIZEZ) + \"\\n\")\n for y in range(SIZEY):\n mc.postToChat('scan:' + str(y))\n f.write(\"\\n\")\n #print 1\n for x in range(SIZEX):\n line = \" \"\n for z in range(SIZEZ):\n blockid = mc.getBlockWithData(originx + x, originy + y, originz + z)\n if line != \" \":\n line = line + ','\n line = line + str(blockid.id) + ',' + str(blockid.data)\n f.write(line + \"\\n\")\n f.close()\n\ndef print3D(filename, originx, originy, originz):\n f = open(filename, \"r\")\n lines = f.readlines()\n coords = lines[0].split(\",\")\n sizex = int(coords[0])\n sizey = int(coords[1])\n sizez = int(coords[2])\n lineidx = 1\n for y in range(sizey):\n mc.postToChat(str(y))\n lineidx = lineidx + 1\n for x in range(sizex):\n line = lines[lineidx]\n lineidx = lineidx + 1\n data = line.split(\",\")\n for z in range(sizez * 2)[::2]:\n #print z\n time.sleep(0)\n mc.setBlock(originx + x, originy + y, originz + z / 2, int(data[z]), int(data[z + 1]))\n\ndef menu():\n while True:\n print('DUPLICATOR MENU')\n print(' 1. BUILD the dupplicator room')\n print(' 2. LIST files')\n print(' 3. SCAN from duplicator room to file')\n print(' 4. LOAD from file into duplicator room')\n print(' 5. PRINT from duplicator room to player.pos')\n print(' 6. CLEAN the duplicator room')\n print(' 7. DEMOLISH the duplicator room')\n print(' 8. QUIT')\n\n choice = int(raw_input('please choose: '))\n if choice < 1 or choice > 8:\n print('Sorry, please choose a number between 1 and 8')\n else:\n return choice\n\nanotherGo = True\nwhile anotherGo:\n choice = menu()\n\n if choice == 1:\n pos = mc.player.getTilePos()\n buildRoom(pos.x, pos.y, pos.z)\n\n elif choice == 2:\n listFiles()\n\n elif choice == 3:\n filename = raw_input('filename?')\n scan3D(filename, roomx + 1, roomy + 1, roomz + 1)\n\n elif choice == 4:\n filename = raw_input('filename?')\n print3D(filename, roomx + 1, roomy + 1, roomz + 1)\n\n elif choice == 5:\n scan3D('scantemp', roomx + 1, roomy + 1, roomz + 1)\n pos = mc.player.getTilePos()\n print3D('scantemp', pos.x + 1, pos.y + 1, pos.z + 1)\n\n elif choice == 6:\n cleanRoom()\n\n elif choice == 7:\n demolishRoom()\n\n elif choice == 8:\n anotherGo = False\n","sub_path":"MyAdventures/duplicator.py","file_name":"duplicator.py","file_ext":"py","file_size_in_byte":3611,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"95209217","text":"## Start Ec2 Instances by irrespective of Tags\n\nimport boto3 \n\n#re = boto3.resource('ec2')\n#print(dir(re))\nprint( \"==================================\")\n\nec = boto3.client('ec2')\n\n#print(type(ec))\n\n#print(dir(ec))\n\ninst = ec.describe_instances()\n#print(inst)\n\nprint( \"==================================\")\n\ninstancelist = []\nfor i in inst['Reservations']:\n for st in i['Instances']:\n print(st['InstanceId'])\n instancelist.append(st['InstanceId'])\nprint(\"-------------------\")\nprint(instancelist)\nec.start_instances(InstanceIds = instancelist)\n \n# print(\"Public IP Address : \" + st['PublicIpAddress'], \"Public DNS Name : \" + st['PublicDnsName'], \"Instance ID : \" + st['InstanceId'])\n# print(ec.stop_instances(InstanceIds = ['i-098d91a038f924470']))\n","sub_path":"Boto3/start_ec2_instances.py","file_name":"start_ec2_instances.py","file_ext":"py","file_size_in_byte":756,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"209184057","text":"import sys\nsys.path.append('../')\nimport importlib\nimport numpy as np\nfrom copy import deepcopy\nfrom dataclasses import dataclass\n\n@dataclass\nclass History:\n pid: int\n total_reward: np.float\n q_values: np.float\n epsilon: np.float\n episode: int\n step: int\n global_step: int\n\nclass Tester():\n def __init__(self, pid, env, epsilon, config, mode=\"train\"):\n self.pid = pid\n self.mode = mode\n self.config = config\n self.env = env(config)\n self.epsilon = epsilon\n self.global_steps = 0\n # build Q network\n self.q_network = self.config.network(config) #network\n self.q_network.summary()\n \n def initialize(self, episodes):\n self.buffer = []\n self.experiences = []\n self.td_errors = []\n self.R = 0\n self.forward(np.random.rand(*self.config.input_shape[1:]))\n \n return self.env.reset(self.mode, episodes)\n \n def play_with_error(self,episodes):\n try:\n return self.play(episodes)\n except Exception as e:\n print ('=== error ===')\n print ('type:' + str(type(e)))\n print ('args:' + str(e.args))\n print ('e :' + str(e))\n self.env.exp.stop()\n return self.play_with_error(episodes)\n \n def play(self, episodes):\n total_reward = 0\n steps = 0\n max_Qs = 0\n done = False\n state = self.initialize(episodes)\n\n while not done:\n action, max_q = self.forward(state)\n next_state, reward, done, _ = self.env.step(action)\n self.backward(*(state, action, reward, next_state, done, max_q))\n state = next_state\n \n steps += 1\n total_reward += reward\n max_Qs += max_q\n \n self.global_steps += steps\n history = History(self.pid, total_reward, max_Qs/steps, self.epsilon, \n episodes, steps, self.global_steps)\n \n return self.td_errors, self.experiences, history\n\n\n\n def sample_action(self, state):\n q = self.q_network.predict([state])\n if np.random.random() < self.epsilon:\n return np.random.choice(self.config.action_space), np.max(q)\n else:\n return np.argmax(q), np.max(q)\n\n def forward(self, state):\n if self.mode == \"train\":\n return self.sample_action(state)\n else: \n q = self.q_network.predict([state])\n return np.argmax(q), np.max(q)\n\n def get_sample(self, n):\n s, a, _, _, _ = self.buffer[0]\n _, _, _, s_, max_q_ = self.buffer[n-1]\n p = self.R + self.config.gamma_n * max_q_\n return s, a, self.R, s_, p\n\n def n_step_transition(self, reward, done):\n self.R = round((self.R + reward * self.config.gamma_n) / self.config.gamma,3)\n\n # n-step transition\n if done: # terminal state\n while len(self.buffer) > 0:\n n = len(self.buffer)\n s, a, r, s_, p = self.get_sample(n)\n # add to local memory\n self.experiences.append((s, a, r, s_))\n self.td_errors.append(p)\n self.R = round((self.R - self.buffer[0][2]) / self.config.gamma,3)\n self.buffer.pop(0)\n self.R = 0\n\n if len(self.buffer) >= self.config.n_step:\n s, a, r, s_, p = self.get_sample(self.config.n_step) \n # add to local memory\n self.experiences.append((s, a, r, s_))\n self.td_errors.append(p)\n self.R = self.R - self.buffer[0][2]\n self.buffer.pop(0)\n\n def backward(self, state, action, reward, next_state, done, q):\n self.buffer.append((state, action, reward, next_state, q))\n self.n_step_transition(reward, done)\n\ndef main():\n env_name = \"flowcontrol\"\n module = importlib.import_module(\"env.\" + env_name)\n env = module.Env\n config = module.Config()\n agent = Tester(0, env, 0.5, config)\n agent_test = Tester(0, env, 0.5, config, mode=\"test\")\n \n for i in range(20):\n a, b, c = agent.play_with_error(i)\n print(i, c)\n if i%5==0:\n a, b, c = agent_test.play_with_error(i)\n print(i, c)\n \n \n\nif __name__ == \"__main__\":\n main()\n","sub_path":"test/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":4554,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"169295184","text":"'''Ce module contient une fonction networkx'''\nimport networkx as nx\nimport matplotlib.pyplot as plt\n\n\ndef construire_graphe(joueurs, murs_horizontaux, murs_verticaux):\n \"\"\"\n Crée le graphe des déplacements admissibles pour les joueurs.\n\n :param joueurs: une liste des positions (x,y) des joueurs.\n :param murs_horizontaux: une liste des positions (x,y) des murs horizontaux.\n :param murs_verticaux: une liste des positions (x,y) des murs verticaux.\n :returns: le graphe bidirectionnel (en networkX) des déplacements admissibles.\n \"\"\"\n graphe = nx.DiGraph()\n\n # pour chaque colonne du damier\n for x in range(1, 10):\n # pour chaque ligne du damier\n for y in range(1, 10):\n # ajouter les arcs de tous les déplacements possibles pour cette tuile\n if x > 1:\n graphe.add_edge((x, y), (x-1, y))\n if x < 9:\n graphe.add_edge((x, y), (x+1, y))\n if y > 1:\n graphe.add_edge((x, y), (x, y-1))\n if y < 9:\n graphe.add_edge((x, y), (x, y+1))\n\n # retirer tous les arcs qui croisent les murs horizontaux\n for x, y in murs_horizontaux:\n graphe.remove_edge((x, y-1), (x, y))\n graphe.remove_edge((x, y), (x, y-1))\n graphe.remove_edge((x+1, y-1), (x+1, y))\n graphe.remove_edge((x+1, y), (x+1, y-1))\n\n # retirer tous les arcs qui croisent les murs verticaux\n for x, y in murs_verticaux:\n graphe.remove_edge((x-1, y), (x, y))\n graphe.remove_edge((x, y), (x-1, y))\n graphe.remove_edge((x-1, y+1), (x, y+1))\n graphe.remove_edge((x, y+1), (x-1, y+1))\n\n # s'assurer que les positions des joueurs sont bien des tuples (et non des listes)\n j1, j2 = tuple(joueurs[0]), tuple(joueurs[1])\n\n # traiter le cas des joueurs adjacents\n if j2 in graphe.successors(j1) or j1 in graphe.successors(j2):\n\n # retirer les liens entre les joueurs\n graphe.remove_edge(j1, j2)\n graphe.remove_edge(j2, j1)\n\n def ajouter_lien_sauteur(noeud, voisin):\n \"\"\"\n :param noeud: noeud de départ du lien.\n :param voisin: voisin par dessus lequel il faut sauter.\n \"\"\"\n saut = 2*voisin[0]-noeud[0], 2*voisin[1]-noeud[1]\n\n if saut in graphe.successors(voisin):\n # ajouter le saut en ligne droite\n graphe.add_edge(noeud, saut)\n\n else:\n # ajouter les sauts en diagonale\n for saut in graphe.successors(voisin):\n graphe.add_edge(noeud, saut)\n\n ajouter_lien_sauteur(j1, j2)\n ajouter_lien_sauteur(j2, j1)\n\n # ajouter les destinations finales des joueurs\n for x in range(1, 10):\n graphe.add_edge((x, 9), 'B1')\n graphe.add_edge((x, 1), 'B2')\n\n return graphe\n\ndef jouer_coup(état):\n\n graphe = construire_graphe(\n [joueur['pos'] for joueur in état['joueurs']],\n état['murs']['horizontaux'],\n état['murs']['verticaux']\n )\n\n pos_soi = état['joueurs'][0]['position']\n pos_adversaire = état['joueurs'][1]['position']\n\n delta = (\n nx.shortest_path_length(graphe, (pos_adversaire), 'B2') -\n nx.shortest_path_length(graphe, (pos_soi), 'B1')\n )\n\n coup = 'mur' if delta < 0 else 'bouge'\n\n if coup == 'mur':\n position_prochaine = nx.shortest_path(\n graphe, (pos_adversaire), 'B2')[0]\n if pos_adversaire[1] - position_prochaine[1] != 0: # Si bouge verticalement\n orientation = 'horizontal'\n position_mur = pos_adversaire\n else: # Si bouge horizontalement\n orientation = 'vertical'\n if pos_adversaire[0] - position_prochaine[0] <= 0: # Si bouge vers la droite\n position_mur = (\n position_prochaine[0], position_prochaine[1] - 1)\n else: # Si bouge vers la gauche\n position_mur = (\n position_prochaine[0] - 1, position_prochaine[1] - 1)\n\n invalide = False\n\n if orientation == 'horizontal':\n for mur in état['murs']['horizontaux']:\n if mur[1] == position_mur[1]:\n if -1 < mur[0] - position_mur[0] < 1: # Si les murs se chevauchent\n invalide = True\n\n for mur in état['murs']['verticaux']:\n if position_mur == (mur[0] + 1, mur[1] - 1):\n invalide = True\n\n if not (1 <= position_mur[0] <= 8 and 2 <= position_mur[1] <= 9):\n invalide = True\n\n else:\n for mur in état['murs']['verticaux']:\n if mur[0] == position_mur[0]:\n if -1 < mur[1] - position_mur[1] < 1: # Si les murs se chevauchent\n invalide = True\n\n for mur in état['murs']['horizontaux']:\n if position_mur == (mur[0] - 1, mur[1] + 1):\n invalide = True\n\n if not (2 <= position_mur[0] <= 9 and 1 <= position_mur[1] <= 8):\n invalide = True\n\n if orientation == 'vertical':\n nouveau_graphe = construire_graphe(\n [joueur['pos'] for joueur in état['joueurs']],\n état['murs']['horizontaux'],\n état['murs']['verticaux'] + [position_mur]\n )\n\n else:\n nouveau_graphe = construire_graphe(\n [joueur['pos'] for joueur in état['joueurs']],\n état['murs']['horizontaux'] + [position_mur],\n état['murs']['verticaux']\n )\n\n if not nx.has_path(nouveau_graphe, (pos_adversaire), 'B2'):\n invalide = True\n\n if invalide:\n coup = 'déplacement'\n \n if coup == 'mur':\n pass\n # self.placer_mur(1, position_mur, orientation)\n\n else:\n pass\n # self.déplacer_jeton(1, nx.shortest_path(graphe, (pos_soi), 'B1')[0])\n\n\n\n\nif __name__ == \"__main__\":\n état = {\n \"joueurs\": [\n {\"nom\": \"idul\", \"murs\": 7, \"pos\": [5, 6]},\n {\"nom\": \"automate\", \"murs\": 3, \"pos\": [5, 7]}\n ],\n \"murs\": {\n \"horizontaux\": [[4, 4], [2, 6], [3, 8], [5, 8], [7, 8]],\n \"verticaux\": [[6, 2], [4, 4], [2, 5], [7, 5], [7, 7]]\n }\n }\n\n graphe = construire_graphe(\n [joueur['pos'] for joueur in état['joueurs']],\n état['murs']['horizontaux'],\n état['murs']['verticaux']\n )\n positions = {'B1': (5, 10), 'B2': (5, 0)}\n\n colors = {\n 'B1': 'red', 'B2': 'green',\n tuple(état['joueurs'][0]['pos']): 'red',\n tuple(état['joueurs'][1]['pos']): 'green',\n }\n sizes = {\n tuple(état['joueurs'][0]['pos']): 300,\n tuple(état['joueurs'][1]['pos']): 300\n }\n\n nx.draw(\n graphe,\n pos={node: positions.get(node, node) for node in graphe},\n node_size=[sizes.get(node, 100) for node in graphe],\n node_color=[colors.get(node, 'gray') for node in graphe],\n )\n plt.show()\n\n\n","sub_path":"graphe.py","file_name":"graphe.py","file_ext":"py","file_size_in_byte":7061,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"343252271","text":"#!/usr/bin/env python\n\nimport sys\nimport os\nimport json\nimport shlex\nimport datetime\nimport subprocess\n\ndef main():\n\n today = datetime.date.today()\n gemini_root_dir = os.environ['GEMINI_ROOT_DIR']\n params = json.loads( open( sys.argv[1] ).read() )\n target_directory = params[ 'output_data' ][0]['extra_files_path']\n os.mkdir( target_directory )\n gemini_exec = os.path.join( gemini_root_dir, 'gemini', 'gemini', 'install-data.py' )\n cmd = gemini_exec + \" %s %s\" % (' '.join( [params['param_dict']['gerp_bp'], params['param_dict']['cadd']] ), target_directory)\n #cmd = gemini_exec + \" --help > %s/foo.txt\" % target_directory\n ret = subprocess.check_call( cmd, shell=True )\n data_manager_dict = { \n 'data_tables': \n {'gemini_databases': [ \n {'value': today.isoformat(), 'dbkey': 'hg19', 'name': 'GEMINI annotations (%s)' % today.isoformat(), 'path': './%s' % today.isoformat() } \n ] \n }\n }\n\n #save info to json file\n with open( sys.argv[1], 'wb' ) as out:\n out.write( json.dumps( data_manager_dict ) )\n\nif __name__ == \"__main__\":\n main()\n\n","sub_path":"data_managers/data_manager_gemini_database_downloader/data_manager/data_manager_gemini_download.py","file_name":"data_manager_gemini_download.py","file_ext":"py","file_size_in_byte":1216,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"171562357","text":"\n#!/usr/bin/env python\n\nimport sys\nimport cv2\nimport math\nimport time\nimport os\nimport argparse\nimport struct\nimport sys\nimport copy\nimport numpy as np\nimport rospy\nimport rospkg\nimport csv\n\nfrom geometry_msgs.msg import (\n PoseStamped,\n Pose,\n PoseArray,\n PoseWithCovarianceStamped,\n Point,\n Quaternion,\n)\n\nfrom std_msgs.msg import (\n Header,\n Empty,\n)\n\nfrom tf.transformations import *\n\nAPVimage_Filepath = os.path.dirname(os.path.realpath(__file__)) + \"/../../../action_primitive_variation/images/\"\nAPVdata_Filepath = os.path.dirname(os.path.realpath(__file__)) + \"/../../../action_primitive_variation/data/\"\nPDDLdata_Filepath = os.path.dirname(os.path.realpath(__file__)) + \"/../../../pddl/data/\"\n\ndef writeToDomainFile(filePath, _name, _reqs, _types, _preds, _actions):\n\n define = 'define (domain ' + _name + ')\\n\\n'\n\n # maybe use join instead \n reqs = '(:requirements'\n for r in _reqs:\n reqs = reqs + ' ' + r\n reqs = reqs + ')\\n\\n'\n\n types = '(:types\\n' \n for t in _types:\n types = types + ' ' + t + '\\n'\n types = types + ')\\n\\n'\n\n preds = '(:predicates\\n'\n for p in _preds:\n preds = preds + ' ' + p + '\\n'\n preds = preds + ')\\n\\n'\n\n actions = ''\n for a in _actions:\n actions = actions + a + '\\n\\n'\n\n # open file \n with open(filePath, 'w') as f:\n f.write('(')\n f.write(define)\n f.write(reqs)\n f.write(types)\n f.write(preds)\n f.write(actions)\n f.write(')')\n\ndef writeToProblemFile(filePath, _task, _domain, _objs, _init, _goals):\n\n define = 'define (problem ' + _task + ')\\n\\n'\n domain = '(:domain ' + _domain + ')\\n\\n'\n\n # # maybe use join instead \n objs = '(:objects'\n for o in _objs:\n objs = objs + '\\n ' + o\n objs = objs + '\\n)\\n\\n'\n\n init = '(:init' \n for i in _init:\n init = init + '\\n ' + i\n init = init + '\\n)\\n\\n'\n\n if len(_goals) > 1:\n goals = '(:goal (and '\n for g in _goals:\n goals = goals + '\\n ' + g\n goals = goals + ')\\n)\\n\\n'\n else:\n goals = '(:goal ' + _goals[0] + ')\\n\\n'\n\n # # open file \n with open(filePath, 'w') as f:\n f.write('(')\n f.write(define)\n f.write(domain)\n f.write(objs)\n f.write(init)\n f.write(goals)\n f.write(')')\n\n\ndef getPlanFromSolutionFile(filePath):\n plan_data = None\n plan = []\n if (os.path.exists(filePath)):\n with open(filePath) as f:\n plan_data = f.readlines()\n\n for full_action in plan_data:\n data = full_action.replace(\")\\n\", \"\").replace(\"(\", \"\")\n args = data.split()\n action = {}\n params = []\n action['actionName'] = args[0]\n for p in range(len(args) -1):\n if args[p+1] is not None: \n params.append(args[p+1])\n \n action['params'] = params\n plan.append(action)\n return plan\n\ndef saveFigureToImage(fig, filename, loc):\n if loc == 'APV':\n fig.savefig(str(APVimage_Filepath) + str(filename))\n\n\ndef deleteAllPddlFiles():\n for the_file in os.listdir(PDDLdata_Filepath):\n file_path = os.path.join(PDDLdata_Filepath, the_file)\n try:\n if os.path.isfile(file_path):\n os.unlink(file_path)\n except Exception as e:\n print(e)\n\n\ndef deleteAllAPVFiles():\n for the_file in os.listdir(APVdata_Filepath):\n file_path = os.path.join(APVdata_Filepath, the_file)\n # try:\n if os.path.isfile(file_path):\n os.unlink(file_path)\n # except Exception as e:\n # print(e)\n for the_file in os.listdir(APVimage_Filepath):\n file_path = os.path.join(APVimage_Filepath, the_file)\n # try:\n if os.path.isfile(file_path):\n os.unlink(file_path)\n # except Exception as e:\n # print(e)\n\n\ndef writeBagData(data, APVtrialName):\n filePath = APVdata_Filepath + APVtrialName\n bagData_fp = filePath + '_bag.csv'\n CPs_fp = filePath + '_cps.csv'\n CPs_filtered_fp = filePath + '_cps_filtered.csv'\n\n with open(bagData_fp, 'a') as csvFile:\n writer = csv.writer(csvFile)\n writer.writerow(data['gripper_x'])\n writer.writerow(data['gripper_y'])\n writer.writerow(data['gripper_z'])\n\n with open(CPs_fp, 'a') as csvFile:\n writer = csv.writer(csvFile)\n writer.writerows(data['groupedCps'])\n\n with open(CPs_filtered_fp, 'a') as csvFile:\n writer = csv.writer(csvFile)\n writer.writerow(data['filteredCps'])\n\n\n\ndef readBagData(APVtrialName):\n filePath = APVdata_Filepath + APVtrialName\n bagData_fp = filePath + '_bag.csv'\n CPs_fp = filePath + '_cps.csv'\n CPs_filtered_fp = filePath + '_cps_filtered.csv'\n\n\n bagData = []\n cps = []\n cps_filtered = []\n\n with open(bagData_fp) as csv_file:\n csv_reader = csv.reader(csv_file, delimiter=',')\n for row in csv_reader:\n bagData.append(row)\n\n with open(CPs_fp) as csv_file:\n csv_reader = csv.reader(csv_file, delimiter=',')\n for row in csv_reader:\n cps.append(row)\n\n with open(CPs_filtered_fp) as csv_file:\n csv_reader = csv.reader(csv_file, delimiter=',')\n for row in csv_reader:\n cps.append(row)\n\n data = {}\n data['bagData'] = bagData\n data['cps'] = cps\n data['cps_filtered'] = cps_filtered\n return data\n\ndef processLogData(filePath, logDataList, outputMode='log'): \n if outputMode == 'log': \n with open(filePath, 'w') as f:\n for row in logDataList:\n f.write(str(row))\n f.write('\\n')\n else:\n for row in logDataList:\n print(str(row))\n print('\\n')","sub_path":"util/src/util/file_io.py","file_name":"file_io.py","file_ext":"py","file_size_in_byte":5802,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"74171406","text":"\"\"\"\nauthor: L\ndate: 2021/8/18 10:27\n\"\"\"\nimport tensorflow as tf\nfrom tensorflow.keras.callbacks import EarlyStopping\nfrom tensorflow.keras.losses import binary_crossentropy\nfrom tensorflow.keras.optimizers import Adam\nfrom tensorflow.keras.metrics import AUC\n\nfrom model import WideDeep\nfrom load_data import create_criteo_dataset\n\nimport os\nos.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'\nif __name__ == '__main__':\n # =============================== GPU ==============================\n # gpu = tf.config.experimental.list_physical_devices(device_type='GPU')\n # print(gpu)\n # os.environ['CUDA_VISIBLE_DEVICES'] = '4'\n\n # ========================= Hyper Parameters =======================\n file = '../data/Criteo/train.txt'\n read_part = True\n sample_num = 100000\n test_size = 0.2\n\n embed_dim = 8\n dnn_dropout = 0.5\n hidden_units = [256, 128, 64]\n\n learning_rate = 0.001\n batch_size = 4096\n epochs = 10\n\n # ========================== Create dataset =======================\n feature_columns, train, test = create_criteo_dataset(file=file,embed_dim=embed_dim,read_part=read_part,sample_num=sample_num,test_size=test_size)\n train_X, train_y = train\n test_X, test_y = test\n\n # ============================Build Model==========================\n # mirrored_strategy = tf.distribute.MirroredStrategy()\n # with mirrored_strategy.scope():\n model = WideDeep(feature_columns, hidden_units=hidden_units, dnn_dropout=dnn_dropout)\n model.summary()\n # ============================Compile==============================\n model.compile(loss=binary_crossentropy, optimizer=Adam(learning_rate=learning_rate),metrics=[AUC()])\n # ============================model checkpoint======================\n # check_path = '../save/wide_deep_weights.epoch_{epoch:04d}.val_loss_{val_loss:.4f}.ckpt'\n # checkpoint = tf.keras.callbacks.ModelCheckpoint(check_path, save_weights_only=True,\n # verbose=1, period=5)\n # ==============================Fit==============================\n model.fit(train_X,train_y,epochs=epochs,\n callbacks=[EarlyStopping(monitor='val_loss', patience=2, restore_best_weights=True)], # checkpoint\n batch_size=batch_size,validation_split=0.1)\n # ===========================Test==============================\n print('test AUC: %f' % model.evaluate(test_X, test_y, batch_size=batch_size)[1])\n # loss:0.4672 auc:0.7827 test AUC: 0.782748\n","sub_path":"9 Wide&Deep/train.py","file_name":"train.py","file_ext":"py","file_size_in_byte":2483,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"199628871","text":"import sys\nimport json\nimport re\nfrom watson_developer_cloud import ToneAnalyzerV3\nfrom prawcore import NotFound\nimport plotly\nimport plotly.graph_objs as go\n\nredditList = []\n\ntone_analyzer = ToneAnalyzerV3(\n\tversion='2017-09-21',\n\tiam_apikey='SgwSyRomsfn-o6-hO4OSwfwQDI5SiT_22cBcPjHemOBu',\n\turl='https://gateway.watsonplatform.net/tone-analyzer/api'\n)\nclass RedditParser(object):\n def __init__(self, sbreddit):\n self.sbreddit = sbreddit\n @classmethod\n def sub_exists(cls,sub):\n import praw\n reddit = praw.Reddit(client_id='AuC3ZsQDIwDKWQ',\n client_secret='-jtdciDnmP_B_QrGiaqLD7F7L-Q',\n user_agent='Emotion Analysis 1.0 for cuHacking2019')\n exists = True\n try:\n reddit.subreddits.search_by_name(sub, exact=True)\n except NotFound:\n exists = False\n print(json.dumps({}))\n return exists\n def run(self):\n import praw\n global redditList\n POSTS = 3 #How many submissions in a subreddit to analyze\n #a_dict = {'subreddit' : {'name': str(self.sbreddit), 'submission': {'title': None, 'description': None, 'comments': []}}}\n if (RedditParser.sub_exists(self.sbreddit)):\n b_dict = {'subreddit' : {'name': str(self.sbreddit), 'text': []}}\n reddit = praw.Reddit(client_id='AuC3ZsQDIwDKWQ',\n client_secret='-jtdciDnmP_B_QrGiaqLD7F7L-Q',\n user_agent='Emotion Analysis 1.0 for cuHacking2019')\n for submission in reddit.subreddit(self.sbreddit).hot(limit = POSTS):\n submission.comments.replace_more(limit = 0)\n b_dict['subreddit']['text'].append(submission.title)\n #a_dict['subreddit']['submission']['title'] = submission.title\n #a_dict['subreddit']['submission']['description'] = submission.description\n for allcomment in submission.comments.list():\n #a_dict['subreddit']['submission']['comments'].append(allcomment.body)\n b_dict['subreddit']['text'].append(allcomment.body)\n redditList = b_dict['subreddit']['text']\n b_dict['subreddit']['text'] = \"\\n\".join(b_dict['subreddit']['text'])\n return b_dict\n else:\n return None\n\n# If no arguments\nif len(sys.argv) == 1:\n print (json.dumps({}))\n exit(1)\nargs = sys.argv[1]\nrunner = RedditParser(args)\nlongstr = runner.run()\nif longstr:\n if longstr['subreddit']['text'][:30000]:\n tones = {}\n tone_analysis = tone_analyzer.tone(\n {'text': longstr['subreddit']['text'][:30000]},\n 'application/json'\n ).get_result()\n\n redditSentences = json.loads(json.dumps(tone_analysis, indent=2)).get(\"sentences_tone\")\n for sentence in redditSentences:\n for tone in sentence.get(\"tones\"):\n tone = tone.get(\"tone_id\")\n tones[tone] = tones.get(tone, 0) + 1\n data = [go.Bar(\n\t\tx=list(tones.keys()),\n\t\ty=list(tones.values())\n )]\n plotly.offline.plot(data, filename='public/reddit-graph.html', auto_open=False)\n #f = open(\"public/reddit-graph.html\", \"r\")\n #html = f.read();\n #html = html.split(\"
\")[1]\n #html = html.replace(\"'\", '\"')\n\n returnDic = {}\n\n for i in range(len(redditList)):\n redditList[i] = redditList[i].replace(\"'\", \"KNIJOU(*HIBJNKHUY&T^FYGVHBGUYTR%\")\n\n # for i in range(len(redditList)):\n # redditList[i] = redditList[i].replace('\"', \"JISDFOHD*S(HFINKJ@#(\")\n\n # returnDic[\"html\"] = html\n returnDic[\"tweetList\"] = redditList\n print(json.dumps(returnDic))\n\n sys.stdout.flush()\n else:\n print (json.dumps({})) #no contents\n sys.stdout.flush()\n","sub_path":"public/reddit.py","file_name":"reddit.py","file_ext":"py","file_size_in_byte":3870,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"64171495","text":"from __future__ import division\nfrom scipy import spatial\n\nimport numpy as np \nimport math\n\n\ndef get_cosine_sim(a, b):\n\n\twhile len(a) < len(b):\n\t\ta.append(0)\n\twhile len(b) < len(a):\n\t\tb.append(0)\n\n\treturn 1 - spatial.distance.cosine(a,b)\n\n\ndef sig_filter(val, lcompress, rcompress, shift=0):\n\treturn ( 1 / (1+math.exp(-(lcompress)*(val-shift)) ) )*( 1 / (1+math.exp((rcompress)*(val-shift)) ) )\n\n\ndef hamming_distance(s1, s2):\n\tif len(s1) != len(s2):\n\t\traise ValueError(\"Undefined for sequences of unequal length\")\n\treturn sum(el1 != el2 for el1, el2 in zip(s1, s2))\n\n\ndef entropy(vec):\n\th=0\n\tfor v in vec:\n\t\th=h+(v)*math.log(v,2)\n\th=h*(-1)\n\treturn h\n\n\ndef jaccard_index(ap, bp):\n\ta=set(ap)\n\tb=set(bp)\n\tr_int=a.intersection(b)\n\tr_uni=a.union(b)\n\t\n\treturn len(r_int)/len(r_uni)\n","sub_path":"math_utils.py","file_name":"math_utils.py","file_ext":"py","file_size_in_byte":777,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"125983959","text":"#coding=utf-8\nfrom django.shortcuts import render\nfrom django.db.models import Q\nfrom django.http import JsonResponse\nfrom django.http import HttpResponseRedirect\nfrom default.models import Personlist,Machine,User,Temperature_log,Warning_log,State_log\nfrom django.contrib.auth import authenticate,login,logout\nfrom django.contrib.auth.decorators import login_required\nfrom django.contrib.auth.models import User\nimport logging\nimport time\nfrom default.email import send_email\nimport random,json\n\n# Create your views here.\n\nNowUser ='123'\nlogger = logging.getLogger('django')\n\n\n\n\n#开发者信息页面\ndef getdeveloper(request):\n user = request.session['username']\n return render(request,'developer.html',{ 'username': user,})\n\n#获取主页函数\n\ndef getindex(request):\n logger.info(\"XXXXXXXXXXXXXXXXXXXXXXXXlogging\")\n if 'username'in request.session:\n username=request.session['username']\n user = User.objects.get(username=username)\n machinelist = Machine.objects.filter(user=user)\n all_machine = 0\n run_machine = 0\n stop_machine = 0\n pause_machine = 0\n break_machine = 0\n for i in range(len(machinelist)):\n all_machine+=1\n if machinelist[i].state == \"正常\":\n run_machine+=1\n elif machinelist[i].state == \"暂停\":\n pause_machine+=1\n elif machinelist[i].state == \"关闭\":\n stop_machine+=1\n elif machinelist[i].state == \"故障\":\n break_machine+=1\n\n return render(request,'index.html',locals())\n else:\n return render(request,'login.html')\n\n\n@login_required()\ndef gettable(request):\n if request.method == 'GET':\n if 'username' in request.session:\n username = request.session['username']\n user = User.objects.filter(username=username)\n machinelist = Machine.objects.filter(user=user)\n return render(request, 'table.html', locals())\n else:\n return render(request, 'login.html')\n elif request.method == 'POST':\n username = request.session['username']\n user = User.objects.filter(username=username)\n machinelist = Machine.objects.filter(SN=request.POST['machinesn'])\n return render(request, 'table.html', locals())\n\n# ajax动态更新主页详情,获取设备列表\ndef AjaxTable(request):\n username = request.session['username']\n NowUser=username #设置全局变量\n user = User.objects.get(username=username)\n print(\"username:::::\"+username)\n print('AJAX:NOUSER:'+NowUser)\n machinel = Machine.objects.filter(user=user)\n machinelist = []\n all_machine = len(machinel)\n run_machine = 0\n stop_machine = 0\n pause_machine = 0\n break_machine = 0\n for item in machinel:\n temp = {'id': item.id, 'SN': item.SN, 'name': item.name, 'temperature': item.temperature, 'time': item.time,\n 'warning': item.warning, 'state': item.state, 'limit': item.limit}\n machinelist.append(temp)\n if item.state == \"正常\":\n run_machine += 1\n elif item.state == \"暂停\":\n pause_machine += 1\n elif item.state == \"关闭\":\n stop_machine += 1\n elif item.state == \"故障\":\n break_machine += 1\n\n res = {'success': \"true\", \"machinelist\": machinelist,'all_machine':all_machine,'run_machine':run_machine,'stop_machine':stop_machine,'pause_machine':pause_machine,'break_machine':break_machine}\n return JsonResponse(res)\n\ndef warning_histort(request):\n username = request.session['username']\n user = User.objects.get(username=username)\n machinelist = Machine.objects.filter(user=user)\n warning_list= []\n for item in machinelist:\n warningl = Warning_log.objects.filter(Q(machine=item) , ~Q(history_warning = \"无\"))\n warning_list.extend(warningl)\n return render(request,'warning_history.html',locals())\n\ndef warning_history_ajax(request):\n username = request.session['username']\n user = User.objects.get(username=username)\n machinelist = Machine.objects.filter(user=user)\n warning_list = []\n for item in machinelist:\n warningl = Warning_log.objects.filter(Q(machine=item), ~Q(history_warning=\"无\"))\n warning_list.extend(warningl)\n dictionary_warning_list = []\n for item in warning_list:\n temp = {'id':item.id,'SN':item.machine.SN,'history_warning':item.history_warning,'warning_change_time':item.warning_change_time}\n dictionary_warning_list.append(temp)\n res = {'success':'true','warning_list':dictionary_warning_list}\n return JsonResponse(res)\n\n\n\n\n#----------------------------设备添加修改删除---------------------\n# @login_required()\n# 添加设备\ndef addlist(request):\n if request.method == 'GET':\n return render(request,'form-elements.html')\n elif request.method == 'POST':\n username = request.session['username']\n user=User.objects.get(username=username)\n li =request.POST['limit']\n sn = request.POST['SN']\n na= request.POST['name']\n tempera = request.POST['temperature']\n #获取系统当前时间\n Time = time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(time.time()))\n state = request.POST['state']\n warning = request.POST['warning']\n machine = Machine(user=user, SN=sn, name=na, temperature=tempera, time=Time, state=state, warning=warning,limit=li)\n #检查是否有重名SN\n item = Machine.objects.filter(SN=sn)\n if len(item) != 0:\n return render(request, 'form-elements.html', {'machine': machine, 'username': username,'result_information':\"已存在该SN!!\"})\n\n machine.save()\n #创建该机器的LOG日志 !!!!!要先machine.save才能 创建log 要不然数据库会报错,因为machine没有储存进去\n tempera_log = Temperature_log(machine=machine,history_temperature=tempera,temperature_change_time=Time)\n warning_log = Warning_log(machine=machine,history_warning=warning,warning_change_time=Time)\n state_log = State_log(machine=machine,history_state=state,state_change_time=Time)\n tempera_log.save()\n warning_log.save()\n state_log.save()\n machinelist = Machine.objects.filter(user=user)\n #监测函数,检测温度有没有到阈值\n detection(machine.SN,user)\n return render(request,'table.html',{'machinelist':machinelist,'username':username})\n#ajax实现开\ndef open(request):\n machineid = request.GET['machineid']\n machine = Machine.objects.get(id=machineid)\n if machine.state == \"关闭\" :\n machine.state = \"正常\"\n machine.save()\n Time = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time()))\n statelog = State_log(machine=machine, history_state=machine.state, state_change_time=Time)\n statelog.save()\n res = {'success': \"true\"}\n print(res)\n return JsonResponse(res)\n\n#ajax实现关\ndef close(request):\n # 改变状态为关并记录\n machineid = request.GET['machineid']\n machine = Machine.objects.get(id=machineid)\n if machine.state != \"关闭\":\n machine.state = \"关闭\"\n machine.save()\n Time = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time()))\n statelog = State_log(machine=machine, history_state=machine.state, state_change_time=Time)\n statelog.save()\n res = {'success': \"true\"}\n print(res)\n return JsonResponse(res)\n\n# @login_required()\n#更新机器表 已改\ndef updatelist(request):\n if request.method == 'GET':\n username = request.session['username']\n machine_id = request.GET['machineid']\n machine = Machine.objects.get(id=machine_id)\n return render(request,'update.html',{'machine':machine,'username':username})\n elif request.method == 'POST':\n machine_id = request.POST['id']\n machine = Machine.objects.get(id=machine_id)\n username = request.session['username']\n user = User.objects.get(username=username)\n\n\n machine.SN = request.POST['SN']\n machine.name = request.POST['name']\n machine.time = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time()))\n machine.limit = request.POST['limit']\n #保存原来的值,作为比对是否更改\n te = machine.temperature\n st = machine.state\n wr = machine.warning\n machine.state = request.POST['state']\n machine.warning = request.POST['warning']\n machine.temperature = request.POST['temperature']\n machine.save()\n\n if machine.temperature != te :\n temperature_log = Temperature_log(machine=machine,history_temperature=machine.temperature,temperature_change_time=machine.time)\n temperature_log.save()\n\n if machine.warning != wr :\n warning_log = Warning_log(machine=machine,history_warning=machine.warning,warning_change_time=machine.time)\n warning_log.save()\n\n if machine.state != st :\n state_log = State_log(machine=machine,history_state=machine.state,state_change_time=machine.time)\n state_log.save()\n\n\n machinelist = Machine.objects.filter(user=user)\n # 监测函数,检测温度有没有到阈值\n detection(machine.SN,user)\n return render(request,'table.html',{'machinelist':machinelist,'username':username})\n\n# @login_required()\ndef dellist(request):\n machineid= request.GET['machineid']\n Machine.objects.get(id=machineid).delete()\n # Temperature_log.delete(machine= machine)\n\n res = {\"success\":\"true\"}\n return JsonResponse(res)\n\n# 显示该设备详情,POST方式实现动态刷新\ndef detail(request):\n if request.method == \"GET\":\n print(\"jin ru detail get\")\n machineid = request.GET['machineid']\n print(\"detail id:\"+machineid)\n machine = Machine.objects.get(id=machineid)\n username = request.session['username']\n return render(request, 'detail.html', {'machine': machine, 'username': username})\n elif request.method == 'POST':\n print(\"jin ru detail get\")\n username = request.session['username']\n user = User.objects.filter(username=username)\n machinelist = Machine.objects.filter(SN=request.POST['machinesn'],user = user)\n if(len(machinelist)!= 0 ):\n machine=machinelist[0]\n\n return render(request, 'detail.html', locals())\n\n#ajax实现log表动态刷新\ndef get_log_table(request):\n machineid = request.POST['machineid']\n print(\"machineid:\"+machineid)\n machine = Machine.objects.get(id=machineid)\n print(machine)\n state_log = []\n temperature_log = []\n warning_log = []\n statelist = State_log.objects.filter(machine=machine)\n temperaturelist = Temperature_log.objects.filter(machine=machine)\n warninglist = Warning_log.objects.filter(machine=machine)\n for item in statelist:\n temp = {'state': item.history_state, 'time': item.state_change_time}\n state_log.append(temp)\n for item in temperaturelist:\n temp = {'temperature': item.history_temperature, 'time': item.temperature_change_time}\n temperature_log.append(temp)\n for item in warninglist:\n temp = {'warning': item.history_warning, 'time': item.warning_change_time}\n warning_log.append(temp)\n res = {'success': \"true\", 'state_log': state_log, 'temperature_log': temperature_log, 'warning_log': warning_log}\n return JsonResponse(res)\n\n# #无用\n# def searchlist(request):\n# if request.method == 'GET':\n# return render(request,'search.html')\n# elif request.method == 'POST':\n# na = request.POST['name']\n# per = Personlist.objects.filter(name=na)\n# return render(request,'showsearch.html',locals())\n# return render(request,'table.html',locals())\n#\n# #无用\n# def getaddpage(request):\n# if 'username' in request.session:\n# username = request.session['username']\n# return render(request, 'table.html', locals())\n# else:\n# return render(request, 'login.html')\n\n# def getlist(request):\n# # personlist = Personlist.objects.all()\n# #logger.info(\"XXXXXXXXXXXXXXXXXXXXXXXXlogging\")\n# return render(request, 'index.html')\n\n\n#-------------------------------------用户注册登录管理--------------------------------\ndef my_login(request):\n if request.method == 'GET':\n return render(request,'login.html',{\"notice\":\" \"})\n\n elif request.method == 'POST':\n username= request.POST['username']\n password= request.POST['password']\n user = authenticate(username=username,password=password)\n if user is not None:\n if user.is_active:\n request.session['username']=username\n NowUser = username\n print(\"Loin1111\"+NowUser)\n login(request,user)\n print(\"login:\"+username)\n return HttpResponseRedirect(\"/\")\n #重定向到成功页面\n else:\n print (\"user is not active\")\n return render(request, 'login.html', {\"notice\": \"密码错误!\"})\n #重定向到失败页面,省略\n else:\n print (\"user is None\")\n return render(request, 'login.html',{\"notice\":\"无此用户,或密码错误,请确认用户名和密码!\"})\n #return HttpResponseRedirect(\"/login/\")\n\n #重定向到失败页面,省略\n print (request.session.keys())\n #print request.session['_auth_user_id']\n return HttpResponseRedirect(\"/\")\n\n\ndef my_logout(request):\n logout(request)\n NowUser = None\n print (request.session.keys())\n return render(request,'login.html',{'notice':\"请登录\"})\n\n\ndef register(request):\n print(\"jin ru request\")\n na = request.POST['username']\n em = request.POST['email']\n password = request.POST['password']\n # password2=request.POST['password2']\n # if password!=password2:\n #\n users=User.objects.filter(username=na)\n\n if len(users) != 0:\n print(\"该用户已注册\")\n return render(request, 'login.html',{'notice':\"该用户已注册,请直接登录\"})\n\n user = User.objects.create_user(username=na,email=em,password=password)\n user.save()\n print(\"creat a User\")\n return render(request,'login.html',{'notice':\"注册成功,请登录\"})\n\n\ndef user_set(request):\n if request.method == 'GET':\n username = request.session['username']\n user = User.objects.get(username=username)\n return render(request,'user_set.html',{'username':username,'password':user.password})\n elif request.method == 'POST':\n username = request.session['username']\n old_password = request.POST['old_password']\n new_password = request.POST['new_password_affirm']\n user = User.objects.get(username=username)\n if user.check_password(old_password):\n user.set_password(new_password)\n user.save()\n my_logout(request)\n return render(request,'login.html',{'notice':\"请登录\"})\n else:\n return render(request, 'user_set.html',{'username': username, 'password': user.password, 'result_information': \"原始密码输入错误\"})\n\n\n# -------------------------------------------------------状态监测-------------------------------------\ndef detection(SN,user):\n machine = Machine.objects.get(SN=SN)\n if int(machine.temperature) > int(machine.limit):\n\n send_email(user.email, machine.SN)\n\n#此处需要一个全局变量来处理当前用户的的问题\n#\ndef client_model(request):\n #print(NowUser)\n if request.method == 'GET':\n if NowUser ==None:\n return JsonResponse({}) #如果出现未登陆状态,则返回空\n\n machineALL = Machine.objects.all()\n if len(machineALL)==0:\n #print(\"向客户端发送!(get)\")\n return JsonResponse({})\n else:\n sendMachine = {}\n for item in machineALL:\n if item.state == \"正常\":\n sendMachine[item.SN]=item.limit\n print(\"向客户端发送:(get)\")\n print(sendMachine) # 检查是否已经构建好字典\n return JsonResponse(sendMachine)\n\n #之前的版本\n # userN=User.objects.get(username=NowUser)\n # sendMachine={}\n # machineALL = Machine.objects.filter(user=userN)\n # print(machineALL)\n #\n # if len(machineALL)==0:\n # print(\"Don't have any equipment!\")\n # return JsonResponse(sendMachine)\n #\n # for item in machineALL:\n # print (item.SN)\n # print(item.limit)\n # sendMachine[item.SN]=item.limit\n #\n # print(sendMachine) #检查是否已经构建好字典\n # return JsonResponse(sendMachine)\n\n elif request.method == 'POST':\n\n allList = request.POST\n print(\"客户端获得:\")\n print(allList)\n\n for item in allList:\n changeM=Machine.objects.get(SN=item)\n if len(Machine.objects.filter(SN=item))==0:\n print(\"无此用户!\")\n pass\n else:\n Time = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time()))\n changeM.temperature=allList[item]\n changeM.time=Time\n changeM.warning='无'\n changeM.save()\n detection(item,changeM.user)\n\n if int(allList[item])>int(changeM.limit):\n print(\"超过温度!\"+allList[item]+\">\"+changeM.limit)\n P=Warning_log(machine=changeM,history_warning=\"温度超过阈值\",warning_change_time=Time)\n changeM.warning='报警'\n changeM.save()\n P.save()\n Temp=Temperature_log(machine=changeM,history_temperature=allList[item],temperature_change_time=Time)\n Temp.save()\n\n machineALL = Machine.objects.all()\n if len(machineALL) == 0:\n print(\"返回设备列表为空!(post)\")\n return JsonResponse({})\n else:\n sendMachine = {}\n for item in machineALL:\n if item.state == \"正常\":\n sendMachine[item.SN] = item.limit\n print(\"正常返回设备列表!(post)\")\n print(sendMachine) # 检查是否已经构建好字典\n return JsonResponse(sendMachine)\n\n #之前的版本\n # if NowUser is None:\n # #print(\"当前无用户登录!\")\n # return JsonResponse({}) # 如果出现未登陆状态,则返回空\n #\n # userN = User.objects.get(username=NowUser)\n # allList=request.POST\n #\n #\n # for item in allList:\n # changeM=Machine.objects.get(SN=item)\n #\n # if len(Machine.objects.filter(SN=item))==0:\n # print(\"无此用户!\")\n # pass\n # else:\n # print(\"有此用户!\")\n # if changeM.state==\"正常\":\n # print(\"进入数据库操作!\")\n # Time = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time()))\n # changeM.temperature=allList[item]\n # changeM.time=Time\n # changeM.warning='无'\n # changeM.save()\n # detection(item,userN)\n #\n # if int(allList[item]>changeM.limit):\n # P=Warning_log(machine=changeM,history_warning=\"温度超过阈值\",warning_change_time=Time)\n # changeM.warning='报警'\n # changeM.save()\n # P.save()\n # Temp=Temperature_log(machine=changeM,history_temperature=allList[item],temperature_change_time=Time)\n # Temp.save()\n #\n #\n # print(\"post bunch!\")\n # print(request.POST)\n #\n # userN = User.objects.get(username=NowUser)\n # sendMachine = {}\n # machineALL = Machine.objects.filter(user=userN)\n # #print(machineALL) #返回的设备列表\n #\n # if len(machineALL) == 0:\n # print(\"Don't have any equipment!\")\n # return JsonResponse(sendMachine)\n #\n # for item in machineALL:\n # #print(item.SN)\n # #print(item.limit)\n # sendMachine[item.SN] = item.limit\n #\n # # #print(sendMachine) # 检查是否已经构建好字典\n # return JsonResponse(sendMachine)\n#\n# #下面的部分为原始的设计\n# # def client_model(request):\n# # print(\"ok get into this view function!\")\n# # if NowUser is None:\n# # return render(request,'')\n# # else:\n# # print(NowUser)\n# # machineALL=Machine.objects.filter(user=NowUser) #返回值为list\n# # for item in machineALL:\n# # if item.state=='关闭':\n# # pass\n# # else:\n# # Mlimit=item.limit #阈值\n# # climateR=random.randint(0,Mlimit+5)\n# # M=Machine.objects.get(SN=item.SN)\n# # M.temperature=climateR\n# # M.save()\n# #\n# # Time = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time()))\n# # tempera_log = Temperature_log(machine=M,history_temperature=climateR,temperature_change_time=Time)\n# # tempera_log.save()\n# # detection(item.SN,NowUser)\n# # if climateR>=Mlimit:\n# # store_warning_log=Warning_log(machine=M,history_warning='报警')\n# # store_warning_log.save( )\n# #\n# # return render(request,'login.html',{'notice':\"请登录\"})","sub_path":"网络编程大作业 设备管理/final_show/control_app/default/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":21971,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"41722566","text":"\n\n#calss header\nclass _SKIING():\n\tdef __init__(self,): \n\t\tself.name = \"SKIING\"\n\t\tself.definitions = [u'the activity or sport of moving on skis: ']\n\n\t\tself.parents = []\n\t\tself.childen = []\n\t\tself.properties = []\n\t\tself.jsondata = {}\n\n\n\t\tself.specie = 'nouns'\n\n\n\tdef run(self, obj1 = [], obj2 = []):\n\t\treturn self.jsondata\n","sub_path":"xai/brain/wordbase/nouns/_skiing.py","file_name":"_skiing.py","file_ext":"py","file_size_in_byte":321,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"189697129","text":"import json\nimport os\nimport random\nimport bottle\nimport copy\n\nfrom api import ping_response, start_response, move_response, end_response\n\nmaxwidth = 11+2\nmaxheight = 11+2\nprev_move = None\n\nLAND = '_' #[1,0,0,0,0]\nMYSNAKE = 'M' #[0,1,0,0,0]\nSNAKE = 'S' #[0,0,1,0,0]\nWALL = 'W' #[0,0,0,1,0]\nFOOD = 'F' #[0,0,0,0,1]\n\n\n# Print the state of the game in grid format in the command line interface.\ndef printgrid(grid):\n\tfor row in grid:\n\t\tprint(' '.join(row))\n\t\t#print(''.join(str(row)))\n\n# Make new grid and store the state information in the grid\ndef load(data):\n\twidth = data['board']['width']\n\theight = data['board']['height']\n\tgrid = [[LAND for i in range(width)] for j in range(height)]\n\n\t#print(\"enemy snake body: \" + str(data['board']['snakes']))\n\tfor snake in data['board']['snakes']:\n\t\tfor coord in snake['body']:\n\t\t\tgrid[coord['y']][coord['x']] = SNAKE\t\t\n\n\t#print(\"mysnake body: \" + str(data['you']['body']))\n\tfor coord in data['you']['body']:\n\t\tgrid[coord['y']][coord['x']] = MYSNAKE\t\t\n\t\n\tfor f in data['board']['food']:\n\t\tgrid[f['y']][f['x']] = FOOD\n\n\tpad_walls(grid)\n\n\treturn grid\n\n\ndef pad_walls(grid):\n\t#pad the top wall\n\twidth = len(grid[0])\n\thorz_wall = [WALL for i in range(width)]\n\tgrid.insert(0, copy.deepcopy(horz_wall))\n\n\t#pad the bottom wall\n\tbottom_pad_size = maxheight - len(grid)\n\tfor i in range(bottom_pad_size):\n\t\tgrid.append(copy.deepcopy(horz_wall))\n\n\t#pad the left wall\n\tfor j in range(maxheight):\n\t\tgrid[j].insert(0, WALL)\n\n\t#pad the right wall\n\tright_pad_size = maxwidth - len(grid[0])\n\tfor k in range(maxheight):\n\t\tfor l in range(right_pad_size):\n\t\t\tgrid[k].append(WALL)\n\n\treturn \n\n\ndef check_alive():\n\talive = 0\n\t\n\t\t\n\n\treturn alive\n\n###################################\n########## SERVER CALLS ###########\n###################################\n\n@bottle.route('/')\ndef index():\n return '''\n Battlesnake documentation can be found at\n https://docs.battlesnake.com .\n '''\n\n\n@bottle.route('/static/')\ndef static(path):\n \"\"\"\n Given a path, return the static file located relative\n to the static folder.\n\n This can be used to return the snake head URL in an API response.\n \"\"\"\n return bottle.static_file(path, root='static/')\n\n\n@bottle.post('/ping')\ndef ping():\n \"\"\"\n A keep-alive endpoint used to prevent cloud application platforms,\n such as Heroku, from sleeping the application instance.\n \"\"\"\n return ping_response()\n\n\n@bottle.post('/start')\ndef start():\n\tdata = bottle.request.json\n\tgrid = load(data)\n\t# printgrid(grid)\n\n\n\t\"\"\"\n\tTODO: If you intend to have a stateful snake AI,\n\t\t initialize your snake state here using the\n\t\t request's data if necessary.\n\t\"\"\"\n\n\tcolor = \"#000550\"\n\n\t#print(json.dumps(data, indent=4))\n\treturn start_response(color)\n\n\n@bottle.post('/move')\ndef move():\n\tdata = bottle.request.json\n\tgrid = load(data)\n\tprintgrid(grid)\n\n\tturn = data['turn']\t\n\tcheck_alive(data['you'], data['snakes'])\n\n\tprint('\\n')\n\tprint('turn: ' + str(turn))\n\n\t#Use trained DQN network to choose a direction to move in\n\tdirections = ['up', 'down', 'left', 'right']\n\t\n\tdirection = random.choice(directions)\n\tprint('direction: ' + direction + '\\n')\n\n\tprev_move = direction\n\treturn move_response(direction)\n\n\n@bottle.post('/end')\ndef end():\n\tdata = bottle.request.json\n\n\tprint(json.dumps(data, indent=4))\n\tprint('\\n============GAMEOVER==============\\n')\n\n\t#concat the state info to a json file\n\n\n\treturn end_response()\n\n\n# Expose WSGI app (so gunicorn can find it)\napplication = bottle.default_app()\n\nif __name__ == '__main__':\n bottle.run(\n application,\n host=os.getenv('IP', '0.0.0.0'),\n port=os.getenv('PORT', '8080'),\n debug=os.getenv('DEBUG', True)\n )\n\t\n\n\n","sub_path":"app/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":3721,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"254989451","text":"import sys\nfrom collections import deque\nsys.stdin = open(\"input.txt\",\"r\")\n\nN, K = (map(int, sys.stdin.readline().rstrip().split()))\n\ndef inRange(a):\n if 0<= a and a <= 100000:\n return True\n return False\n\nPos = deque()\ncheck = [0 for i in range(100001)]\n\nPos.append((N,0))\ncheck[N] = 1\n\nwhile deque:\n a = Pos.popleft()\n current = a[0]\n time = a[1]\n\n if current == K:\n print(time)\n break\n\n nextPos = current - 1\n if inRange(nextPos) and check[nextPos] != 1:\n Pos.append((nextPos, time+1))\n check[nextPos] = 1\n\n nextPos = current + 1\n if inRange(nextPos)and check[nextPos] != 1:\n Pos.append((nextPos, time+1))\n check[nextPos] = 1\n\n nextPos = current * 2\n if inRange(nextPos) and check[nextPos] != 1:\n Pos.append((nextPos,time+1))\n check[nextPos] = 1\n\n","sub_path":"숨바꼭질.py","file_name":"숨바꼭질.py","file_ext":"py","file_size_in_byte":848,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"157293804","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.db import models, migrations\nimport repo.models\nfrom django.conf import settings\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('repo', '0005_auto_20150103_0642'),\n ]\n\n operations = [\n migrations.AddField(\n model_name='organization',\n name='avatar_image',\n field=models.ImageField(default=None, null=True, upload_to=repo.models.organization_avatar_upload, blank=True),\n preserve_default=True,\n ),\n migrations.AlterField(\n model_name='organizationteam',\n name='permissions',\n field=models.ManyToManyField(related_name='+', to='repo.Permission', blank=True),\n preserve_default=True,\n ),\n migrations.AlterField(\n model_name='organizationteam',\n name='projects',\n field=models.ManyToManyField(related_name='organizationteams', to='repo.Project', blank=True),\n preserve_default=True,\n ),\n migrations.AlterField(\n model_name='organizationteam',\n name='users',\n field=models.ManyToManyField(related_name='organizationteams', to=settings.AUTH_USER_MODEL, blank=True),\n preserve_default=True,\n ),\n migrations.AlterField(\n model_name='projectteam',\n name='permissions',\n field=models.ManyToManyField(related_name='+', to='repo.Permission', blank=True),\n preserve_default=True,\n ),\n migrations.AlterField(\n model_name='projectteam',\n name='users',\n field=models.ManyToManyField(related_name='projectteams', to=settings.AUTH_USER_MODEL, blank=True),\n preserve_default=True,\n ),\n ]\n","sub_path":"repo/migrations/0006_auto_20150103_1654.py","file_name":"0006_auto_20150103_1654.py","file_ext":"py","file_size_in_byte":1828,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"559131709","text":"\"\"\"\nunix_server_conditions\n\n\"\"\"\n\nimport logging\nfrom pubsub import pub\nfrom condition import Condition, link\n\nLOGGER = logging.getLogger(__name__)\n\nCONDITION_CLASS_NAME = 'UnixServerConditions'\n\nclass UnixServerConditions(Condition):\n \"\"\"\n UnixServerConditions\n\n Conditions for handling messages sent to the UnixSocketServer\n node\n \"\"\"\n\n def __init__(self, *args, **kwargs):\n \"\"\"\n Constructor\n \"\"\"\n\n super().__init__(*args, **kwargs)\n LOGGER.debug('Initialized')\n\n @link\n def evaluate(self, msg):\n \"\"\"\n Handler for receiving messages\n \"\"\"\n\n LOGGER.info('Evaluating')\n\n if 'stop' == msg['content'].strip():\n return True\n","sub_path":"src/packages/default/conditions/unix_server_conditions.py","file_name":"unix_server_conditions.py","file_ext":"py","file_size_in_byte":724,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"405244785","text":"'''\n项目 10\n\n\n本次需要给之前做的词典软件加上单词读音功能\n\n界面上增加一个读音按钮,按了后会播放单词的语音\n播放单词语音的具体做法见如下描述\n\n播放单词语音需要两步\n1,获取到语音文件\n2,用 kivy 播放这个语音文件\n\n在项目 4 的说明中有如下部分内容\n截取如下(删除了多余的部分)\n其中 symbols 的 ph_am_mp3 里存的是单词的美式发音 mp3 文件\n{\n \"word_name\": \"name\",\n \"symbols\": [{\n \"ph_en_mp3\": \"http://res.iciba.com/resource/amp3/oxford/0/1b/c3/1bc38ba928f40072e7c62d427a05c03e.mp3\",\n \"ph_am_mp3\": \"http://res.iciba.com/resource/amp3/1/0/b0/68/b068931cc450442b63f5b3d276ea4297.mp3\",\n \"ph_tts_mp3\": \"http://res-tts.iciba.com/b/0/6/b068931cc450442b63f5b3d276ea4297.mp3\",\n }]\n}\n\n我们可以下载并保存这个 mp3 文件然后播放\n比如例子这个文件可以保存为 name.mp3 (因为有 word_name)\n\n下载文件并保存的代码如下\n为了把单词语音保存为 单词名.mp3 的形式你需要修改这个函数\ndef download(url):\n path = '文件名.mp3'\n s = urllib.request.urlopen(url).read()\n # 'w' 表示写入 'b' 表示二进制模式\n with open(path, 'wb') as f:\n f.write(s)\n'''\n\n# 下面的例子下载了一个 mp3 文件并保存为 文件名.mp3 \nimport urllib.request\n\n\ndef download(url):\n path = '文件名.mp3'\n s = urllib.request.urlopen(url).read()\n # 'w' 表示写入 'b' 表示二进制模式\n with open(path, 'wb') as f:\n f.write(s)\n\n\ndef main():\n # 注意,这里一定要有查单词的那个 key,否则下载是不成功的\n key = ''\n ph_am_mp3 = \"http://res-tts.iciba.com/b/0/6/b068931cc450442b63f5b3d276ea4297.mp3\"\n url = '{}?key={}'.format(ph_am_mp3, key)\n download(url)\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"project/项目10.带单词读音的词典.py","file_name":"项目10.带单词读音的词典.py","file_ext":"py","file_size_in_byte":1859,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"168669310","text":"import timeit\nimport cProfile\nfrom itertools import product\nimport math\nfrom itertools import permutations\nfrom itertools import combinations\n\nQUOTIENT_OF_FOLLOWING_DECIMAL_DIGITS = 0xa\nENGLAND_COINS = (1, 2, 5, 10, 20, 50, 100, 200)\nNUM_OF_DIGITS_OF_PANDIGITAL_PRODUCT = 4\nDIGITS_THAT_PANDIGITAL_PRODUCT_CANT_END_WITH = ('5', '9')\nFIRST_TWO_DIGITS_NUM = 0xa\nFIRST_THREE_DIGITS_NUM = 0x64\nFIRST_FIVE_DIGITS_NUM = 0x2710\nFIRST_FOUR_DIGITS_NUM = 0x3e8\nFIRST_NINE_DIGITS_NUM = 0x5f5e100\nFIRST_SPECIAL_PANDIGITAL = 1023456789\nLAST_SPECIAL_PANDIGITAL = 9876543210\nLAST_SEVEN_DIGITS_NUM = 0x98967f\nHIGHEST_POTENTIAL_PANDIGITAL_NUM = 7654321\nLAST_DIGIT = 9\nNUM_OF_TRUNCATABLE_PRIMES = 0xb\nONE_DIGIT_PRIMES = {2, 3, 5, 7}\nUPPERCASE_A_ASCII_VALUE = 0x41\nNUM_OF_ENGLISH_LETTERS = 0x1a\nLENGTH_OF_LONGEST_PANDIGITAL_NUM = 0xa\nSEVENTH_PRIME = 0x11\nNON_ZERO_DIGITS = '123456789'\nALL_DIGITS = '0123456789'\nEVEN_DIGITS = '02468'\nFIVE_MULTIPLES_DIGITS = '05'\nSEVENTEEN_LOWEST_THREE_DIGITS_MULTIPLE = 0x66\nSEVEN_LOWEST_THREE_DIGITS_MULTIPLE = 0x69\nSUM_OF_ALL_DIGITS = 0x37\nDIFF_OF_DIFFES_BETWEEN_CONSECUTIVE_PENTAGON_NUMS = 3\n\ndef is_pandigital(num, lowest_digit=1):\n num_digits = {digit for digit in str(num)}\n for digit in range(lowest_digit, len(num_digits)):\n if str(digit) not in num_digits:\n return False\n return True\n\ndef get_pandigital_multiple(num):\n multiple = num\n for i in range(2, LAST_DIGIT + 1):\n multiple = str(multiple) + str(num * i)\n if 9 < len(multiple):\n return None\n if 9 == len(multiple):\n multiple_digits = {digit for digit in str(multiple)}\n if ('0' not in multiple_digits) and (9 == len(multiple_digits)):\n return int(multiple)\n\ndef get_largest_pandigital_multiple():\n for i in range(FIRST_FIVE_DIGITS_NUM - 1, 0x3e8 - 1, -1):\n pandigital_multiple = get_pandigital_multiple(i)\n if pandigital_multiple:\n return pandigital_multiple\n\ndef get_left_truncated(num):\n truncated = str(num)[1:]\n if truncated:\n return int(truncated)\n return 0\n\ndef get_right_truncated(num):\n truncated = str(num)[:-1]\n if truncated:\n return int(truncated)\n return 0\n\ndef is_palindrome(num):\n return str(num) == str(num)[::-1]\n\ndef is_bin_palindrom(num):\n return bin(num)[2:] == bin(num)[2:][::-1]\n\ndef get_bin_and_dec_palindromes(high_limit):\n bin_and_dec_palindromes = set()\n for i in range(high_limit):\n if is_palindrome(i) and is_bin_palindrom(i):\n bin_and_dec_palindromes.add(i)\n return bin_and_dec_palindromes\n\ndef get_rotated_right_num(num):\n num_as_str = str(num)\n rotated_num = num_as_str[-1] + num_as_str[:-1]\n if '0' == rotated_num[0]:\n return rotated_num\n return int(rotated_num)\n\ndef get_factorial(num, digits_factorials_cache=None):\n if (digits_factorials_cache is not None) and (\n num in digits_factorials_cache):\n return digits_factorials_cache[num]\n factorial = 1\n for i in range(2, num + 1):\n factorial *= i\n if digits_factorials_cache is not None:\n digits_factorials_cache[num] = factorial\n return factorial\n\ndef get_digits_factorials_cache():\n digits_factorials_cache = {}\n for i in range(LAST_DIGIT + 1):\n get_factorial(i, digits_factorials_cache)\n return digits_factorials_cache\n\ndef get_divisors_pairs(num):\n divisors_pairs = set()\n for i in range(1, int(num ** 0.5) + 1):\n if 0 == (num % i):\n divisors_pairs.add((i, num // i))\n return divisors_pairs\n\ndef is_prime(num):\n if num <= 1:\n return False\n num_root = num ** 0.5\n\n for i in range(2, int(num_root) + 1):\n if 0 == (num % i):\n return False\n return True\n\ndef get_primes_in_range(start, stop):\n if start < 2:\n start = 2\n primes = {i for i in range(start, stop)}\n stop_root = stop ** 0.5\n for i in range(2, int(stop_root) + 1):\n for product in range(i * 2, stop, i):\n if product in primes:\n primes.remove(product)\n return primes\n\ndef sum_digits_arrays(first_digits_array,\n second_digits_array):\n sum_digits_array = []\n for digits_pair in zip(first_digits_array,\n second_digits_array):\n sum_digits_array.append(sum(digits_pair))\n for i in range(len(sum_digits_array) - 1):\n sum_digits_array[i + 1] += \\\n sum_digits_array[i] // \\\n QUOTIENT_OF_FOLLOWING_DECIMAL_DIGITS\n sum_digits_array[i] %= \\\n QUOTIENT_OF_FOLLOWING_DECIMAL_DIGITS\n return sum_digits_array\n\ndef get_first_x_digits_fibonacci_num(num_of_digits):\n if 1 == num_of_digits:\n return 1\n\n previous_num = [0] * num_of_digits\n current_num = [0] * num_of_digits\n\n fibbonaci_num_index = 2\n previous_num[0] = 1\n current_num[0] = 1\n\n\n while 0 == current_num[num_of_digits - 1]:\n fibbonaci_num_index += 1\n temp_current_num = current_num[:]\n current_num = sum_digits_arrays(current_num, previous_num)\n previous_num = temp_current_num\n\n return fibbonaci_num_index\n\ndef get_length_of_fraction_recurring_cycle(num, num_to_divide_by):\n curr_divideable_num = num\n divideable_nums = []\n while 0 != curr_divideable_num:\n while curr_divideable_num < num_to_divide_by:\n curr_divideable_num *= QUOTIENT_OF_FOLLOWING_DECIMAL_DIGITS\n if curr_divideable_num in divideable_nums:\n return len(divideable_nums) - divideable_nums.index(\n curr_divideable_num)\n divideable_nums.append(curr_divideable_num)\n curr_divideable_num %= num_to_divide_by\n return 0\n\ndef get_denominator_with_longest_recurring_cycle(numerator,\n max_denominator):\n recurring_cycle_lengthes = []\n for i in range(1, max_denominator + 1):\n recurring_cycle_lengthes.append(\n get_length_of_fraction_recurring_cycle(numerator, i))\n return recurring_cycle_lengthes.index(max(recurring_cycle_lengthes)) + 1\n\ndef get_quadratic_formula_num_of_consecutive_primes_results(a, b):\n n = 0\n while True:\n if is_prime(n ** 2 + a * n + b):\n n += 1\n else:\n return n\n\ndef get_quadratic_formula_with_max_consecutive_primes_results(\n max_absolute_a, max_b):\n # each element is a tuple: (a, b, num_of_consecutive_primes_results)\n formulas_num_of_consecutive_primes_results = []\n b_possibilities = get_primes_in_range(2, max_b)\n for a in range(-max_absolute_a, max_absolute_a + 1):\n for b in b_possibilities:\n formulas_num_of_consecutive_primes_results.append((a, b,\n get_quadratic_formula_num_of_consecutive_primes_results(a, b)))\n quadratic_formula_with_max_consecutive_primes_results = \\\n max(formulas_num_of_consecutive_primes_results, key = \\\n lambda quadratic_formula_tuple: quadratic_formula_tuple[2])\n return quadratic_formula_with_max_consecutive_primes_results\n return quadratic_formula_with_max_consecutive_primes_results[0] * \\\n quadratic_formula_with_max_consecutive_primes_results[1]\n\ndef get_spiral_diagonals_sum(spiral_side_length):\n main_diagonal_sum = 0 # not including the 1 in the middle\n for i in range(1, spiral_side_length):\n main_diagonal_sum += (i ** 2) + i + 1\n secondary_diagonal_sum = 0\n for i in range(1, spiral_side_length + 1):\n secondary_diagonal_sum += i ** 2 + (1 - (i % 2))\n return main_diagonal_sum + secondary_diagonal_sum\n\ndef get_num_of_distinct_powers(high_limit):\n LOW_LIMIT = 2\n powers_to_subtract = set()\n for i in range(LOW_LIMIT, int(high_limit ** 0.5) + 1):\n i_exponents_till_high_limit_power = range(\n LOW_LIMIT, int(math.log(high_limit, i)) + 1)\n print(i, i_exponents_till_high_limit_power)\n\n for i_exponent in i_exponents_till_high_limit_power:\n i_power = i ** i_exponent\n # handle dups such as i ** 8, (i ** 2) ** 3\n for i_power_exponent in range(\n LOW_LIMIT, (high_limit // i_exponent) + 1):\n powers_to_subtract.add((i_power, i_power_exponent))\n # handle dups such as (i ** 2) ** 51, (i ** 3) ** 34\n for i_power_exponent in range(LOW_LIMIT, high_limit + 1):\n #(high_limit // i_exponent) + 1, high_limit + 1):\n for another_i_exponent in i_exponents_till_high_limit_power:\n if another_i_exponent > i_exponent:\n another_i_power = i ** another_i_exponent\n another_i_power_exponent = (i_exponent * \\\n i_power_exponent) / another_i_exponent\n if int(another_i_power_exponent) == \\\n another_i_power_exponent and \\\n another_i_power_exponent <= high_limit and \\\n another_i_power_exponent >= LOW_LIMIT:\n powers_to_subtract.add((another_i_power,\n int(another_i_power_exponent)))\n\n num_of_distinct_powers = (high_limit - 1) ** 2 - len(powers_to_subtract)\n print(sorted(tuple(powers_to_subtract)))\n return num_of_distinct_powers\n\ndef is_num_equal_to_digits_powers_sum(num, exponent, digits_powers_cache=None):\n if 1 >= num:\n return False\n\n num_left = num\n digits_powers_sum = 0\n while 0 < num_left:\n digit = num_left % QUOTIENT_OF_FOLLOWING_DECIMAL_DIGITS\n if digits_powers_cache:\n digits_powers_sum += digits_powers_cache[digit]\n else:\n digits_powers_sum += digit ** exponent\n num_left //= QUOTIENT_OF_FOLLOWING_DECIMAL_DIGITS\n\n return (digits_powers_sum == num)\n\ndef get_highest_num_potentially_equal_to_digits_powers_sum(exponent):\n num = QUOTIENT_OF_FOLLOWING_DECIMAL_DIGITS - 1\n digits_powers_sum = num ** exponent\n while digits_powers_sum >= num:\n num *= QUOTIENT_OF_FOLLOWING_DECIMAL_DIGITS\n num += QUOTIENT_OF_FOLLOWING_DECIMAL_DIGITS - 1\n digits_powers_sum += (\n QUOTIENT_OF_FOLLOWING_DECIMAL_DIGITS - 1) ** exponent\n return num\n\ndef get_sum_of_nums_equal_to_digits_powers_sum(exponent):\n powers_cache = []\n for i in range(QUOTIENT_OF_FOLLOWING_DECIMAL_DIGITS):\n powers_cache.append(i ** exponent)\n\n sum_of_nums_equal_to_digits_powers_sum = 0\n for i in range(\n get_highest_num_potentially_equal_to_digits_powers_sum(exponent)):\n if is_num_equal_to_digits_powers_sum(\n i, exponent, digits_powers_cache = powers_cache):\n sum_of_nums_equal_to_digits_powers_sum += i\n return sum_of_nums_equal_to_digits_powers_sum\n\ndef add_coin_to_each_combination(coin_combinations, coin):\n old_coin_combinations = []\n new_coin_combinations = set()\n coin_index = ENGLAND_COINS.index(coin)\n\n if coin_combinations:\n for combination in coin_combinations:\n old_coin_combinations.append(list(combination))\n for combination in old_coin_combinations:\n combination[coin_index] += 1\n new_coin_combinations.add(tuple(combination))\n else:\n the_combination = [0] * len(ENGLAND_COINS)\n the_combination[coin_index] += 1\n new_coin_combinations.add(tuple(the_combination))\n return new_coin_combinations\n\ndef get_coin_combinations(sum, combinations_cache):\n if 0 == sum:\n return set()\n\n if combinations_cache[sum]:\n return combinations_cache[sum]\n\n coin_combinations = set()\n for coin in ENGLAND_COINS:\n if 0 <= (sum - coin):\n coin_combinations = coin_combinations.union(\n add_coin_to_each_combination(\n get_coin_combinations(sum - coin, combinations_cache), coin))\n else:\n break\n combinations_cache[sum] = coin_combinations\n return coin_combinations\n\ndef get_num_of_coin_combinations(sum):\n combinations_cache = []\n for i in range(sum + 1):\n combinations_cache.append(set())\n for i in range(sum + 1):\n get_coin_combinations(i, combinations_cache)\n\n return len(combinations_cache[sum])\n\ndef get_potential_pandigital_products():\n prev_potential_pandigital_products = set(('',))\n\n for i in range(NUM_OF_DIGITS_OF_PANDIGITAL_PRODUCT):\n curr_potential_pandigital_products = set()\n for prev_product in prev_potential_pandigital_products:\n for digit in PANDIGITAL_DIGITS:\n if (digit not in prev_product) and not (\n (i == NUM_OF_DIGITS_OF_PANDIGITAL_PRODUCT - 1) and (\n digit in (\n DIGITS_THAT_PANDIGITAL_PRODUCT_CANT_END_WITH))):\n curr_potential_pandigital_products.add(\n prev_product + digit)\n prev_potential_pandigital_products = (\n curr_potential_pandigital_products)\n\n curr_potential_pandigital_products = set()\n for product_as_string in prev_potential_pandigital_products:\n curr_potential_pandigital_products.add(int(product_as_string))\n return curr_potential_pandigital_products\n\ndef is_pandigital_product(product):\n product_digits = {digit for digit in str(product)}\n divisors_pairs = get_divisors_pairs(product)\n\n for (divisor1, divisor2) in divisors_pairs:\n divisor1_digits = {digit for digit in str(divisor1)}\n divisor2_digits = {digit for digit in str(divisor2)}\n if (set(PANDIGITAL_DIGITS) == divisor1_digits.union(\n divisor2_digits).union(product_digits)) and (9 == (\n len(str(divisor1)) + len(str(divisor2)) +len(str(product)))):\n return True\n return False\n\ndef get_sum_of_pandigital_products():\n sum = 0\n for potential_product in get_potential_pandigital_products():\n if is_pandigital_product(potential_product):\n sum += potential_product\n print(potential_product)\n return sum\n\ndef get_cancelling_fractions():\n cancelling_fractions = set()\n for denominator in range(FIRST_TWO_DIGITS_NUM, FIRST_THREE_DIGITS_NUM):\n denominator_digits = {digit for digit in str(denominator)}\n for numerator in range(FIRST_TWO_DIGITS_NUM, FIRST_THREE_DIGITS_NUM):\n numerator_digits = {digit for digit in str(numerator)}\n shared_digit = denominator_digits.intersection(numerator_digits)\n if (1 == len(shared_digit)) and (numerator < denominator) and (\n shared_digit != set(('0'))):\n shared_digit = shared_digit.pop()\n quotient = numerator / denominator\n new_numerator = int(\n str(numerator).replace(shared_digit, '', 1))\n new_denominator = int(\n str(denominator).replace(shared_digit, '', 1))\n if 0 != new_denominator:\n new_quotient = new_numerator / new_denominator\n if quotient == new_quotient:\n cancelling_fractions.add((numerator, denominator))\n return cancelling_fractions\n\ndef get_max_num_potentially_equal_to_digits_factorials():\n lowest_num = 1\n num_of_digits = 1\n while int(lowest_num) <= (get_factorial(LAST_DIGIT) * num_of_digits):\n lowest_num *= 10\n num_of_digits += 1\n return (get_factorial(LAST_DIGIT) * (num_of_digits - 1))\n\ndef get_digits_factorials(num, digits_factorials_cache):\n if num in digits_factorials_cache:\n return digits_factorials_cache[num]\n digits_factorials = get_digits_factorials(\n num // 10, digits_factorials_cache) + (\n digits_factorials_cache[num % 10])\n digits_factorials_cache[num] = digits_factorials\n return digits_factorials\n\ndef is_equal_to_digits_factorials(num, digits_factorials_cache):\n return num == get_digits_factorials(num, digits_factorials_cache)\n\ndef get_sum_of_nums_equal_to_digits_factorials():\n digits_factorials_cache = get_digits_factorials_cache()\n sum = 0\n for num in range(\n get_max_num_potentially_equal_to_digits_factorials() + 1):\n if is_equal_to_digits_factorials(num, digits_factorials_cache):\n sum += num\n print(num)\n return sum\n\ndef is_circular_prime(prime, primes):\n rotated_prime = get_rotated_right_num(prime)\n while prime != int(rotated_prime):\n if int(rotated_prime) not in primes:\n return False\n rotated_prime = get_rotated_right_num(rotated_prime)\n return True\n\ndef get_circular_primes(max_circular_prime):\n primes = get_primes_in_range(2, max_circular_prime + 1)\n circular_primes = set()\n while primes:\n prime = primes.pop()\n is_prime_circular = is_circular_prime(prime, primes)\n if is_prime_circular:\n circular_primes.add(prime)\n rotated_prime = get_rotated_right_num(prime)\n while prime != int(rotated_prime):\n if int(rotated_prime) in primes:\n primes.remove(int(rotated_prime))\n if is_prime_circular:\n circular_primes.add(int(rotated_prime))\n rotated_prime = get_rotated_right_num(rotated_prime)\n return circular_primes\n\ndef is_truncatable_prime(prime, primes):\n truncated_prime = get_left_truncated(prime)\n while 0 < truncated_prime:\n if truncated_prime not in primes:\n return False\n truncated_prime = get_left_truncated(truncated_prime)\n truncated_prime = get_right_truncated(prime)\n while 0 < truncated_prime:\n if truncated_prime not in primes:\n return False\n truncated_prime = get_right_truncated(truncated_prime)\n return True\n\ndef get_truncatable_primes():\n primes = get_primes_in_range(0, 1000000)\n primes_left = set(primes).difference(ONE_DIGIT_PRIMES)\n truncatable_primes = set()\n\n while NUM_OF_TRUNCATABLE_PRIMES < len(primes_left):\n prime = primes_left.pop()\n if is_truncatable_prime(prime, primes):\n truncatable_primes.add(prime)\n return truncatable_primes\n\ndef get_pythagorean_triplets(triangle_perimeter_high_limit):\n pythagorean_triplets = set()\n for a in range(1, triangle_perimeter_high_limit // 3 + 1):\n for b in range(a, triangle_perimeter_high_limit // 2 + 1):\n c = (a ** 2 + b ** 2) ** 0.5\n if (c == int(c)) and (a + b + c < triangle_perimeter_high_limit):\n pythagorean_triplets.add((a, b, int(c)))\n return pythagorean_triplets\n\ndef get_perimeter_with_max_num_of_pythagorean_triplets(\n triangle_perimeter_high_limit):\n pythagorean_triplets = get_pythagorean_triplets(\n triangle_perimeter_high_limit)\n num_of_triplets_for_perimeter = {}\n for triplet in pythagorean_triplets:\n perimeter = sum(triplet)\n if perimeter in num_of_triplets_for_perimeter:\n num_of_triplets_for_perimeter[perimeter] += 1\n else:\n num_of_triplets_for_perimeter[perimeter] = 1\n\n return max(num_of_triplets_for_perimeter.items(),\n key = lambda perimeter_and_num_of_triplets: (\n perimeter_and_num_of_triplets[1]))[0]\n\ndef champernowne_constant(digit_index_high_limit):\n digit_index = 1\n current_num = '1'\n current_num_digit_index = 0\n product = 1\n while digit_index < digit_index_high_limit:\n digit_index_log = math.log10(digit_index)\n if digit_index_log == int(digit_index_log):\n product *= int(current_num[current_num_digit_index])\n if len(current_num) - 1 == current_num_digit_index:\n current_num_digit_index = 0\n current_num = str(int(current_num) + 1)\n else:\n current_num_digit_index += 1\n digit_index += 1\n return product\n\ndef get_highest_pandigital_prime():\n for num in range(HIGHEST_POTENTIAL_PANDIGITAL_NUM, - 1, -1):\n if (is_pandigital(num)) and (is_prime(num)):\n return num\n\ndef is_triangle_word(word, triangle_nums):\n word_value = sum((ord(letter) - UPPERCASE_A_ASCII_VALUE + 1) for (\n letter) in word)\n if word_value in triangle_nums:\n return True\n return False\n\ndef get_triangle_nums(stop):\n triangle_nums = set()\n sum = 1\n num = 1\n while sum < stop:\n triangle_nums.add(sum)\n num += 1\n sum += num\n\n return triangle_nums\n\ndef get_num_of_triangle_words(words):\n triangle_nums = get_triangle_nums(1000)\n num_of_triangle_words = 0\n for word in words:\n if is_triangle_word(word, triangle_nums):\n num_of_triangle_words += 1\n return num_of_triangle_words\n\ndef get_words_in_file(filename):\n with open(filename, 'r') as words_file:\n words = words_file.read()\n words = words.replace('\"', '')\n words = set(words.split(','))\n return words\n\ndef get_longest_pandigital_nums():\n longest_pandigitals = set()\n for permutation in permutations(\n range(1, QUOTIENT_OF_FOLLOWING_DECIMAL_DIGITS - 1)):\n curr_pandigital = ''\n for digit in permutation:\n curr_pandigital += str(digit)\n longest_pandigitals.add(int(curr_pandigital))\n return longest_pandigitals\n\ndef is_special_pandigital(num):\n if LENGTH_OF_LONGEST_PANDIGITAL_NUM != len(str(num)):\n return False\n if not is_pandigital(num, lowest_digit=0):\n return False\n first_primes = sorted(get_primes_in_range(0, SEVENTH_PRIME + 1))\n num_as_string = str(num)\n for digit_index in range(1, LENGTH_OF_LONGEST_PANDIGITAL_NUM - 2):\n current_sub_num = int(num_as_string[digit_index:digit_index + 3])\n if 0 != current_sub_num % first_primes[digit_index - 1]:\n return False\n return True\n\ndef get_longer_unique_digits_nums(nums_strings, digits_to_add=ALL_DIGITS):\n new_nums_strings = set()\n for num_string in nums_strings:\n for digit in digits_to_add:\n if digit not in num_string:\n new_nums_strings.add(num_string + digit)\n #print(new_nums_strings)\n return new_nums_strings\n\ndef get_all_unique_digits_concats(left_nums_strings, right_nums_strings):\n unique_digits_concats = set()\n for left_num_string in left_nums_strings:\n for right_num_string in right_nums_strings:\n concat_num_string = left_num_string + right_num_string\n if (len(left_num_string) + len(right_num_string)) == len(\n set(concat_num_string)):\n unique_digits_concats.add(concat_num_string)\n return unique_digits_concats\n\ndef get_special_pandigitals_sum():\n special_pandigitals = set(('',))\n # second and third digits\n for i in range(2):\n special_pandigitals = get_longer_unique_digits_nums(special_pandigitals)\n # fourth digits\n special_pandigitals = get_longer_unique_digits_nums(\n special_pandigitals, digits_to_add=EVEN_DIGITS)\n # fifth, sixth and seventh digits\n seven_multiples = {str(multiple) for multiple in range(\n SEVEN_LOWEST_THREE_DIGITS_MULTIPLE, FIRST_FOUR_DIGITS_NUM, 7)}\n special_pandigitals = get_all_unique_digits_concats(\n special_pandigitals, seven_multiples)\n # eighth, ninth and tenth digits\n seventeen_multiples = {str(multiple) for multiple in range(\n SEVENTEEN_LOWEST_THREE_DIGITS_MULTIPLE, FIRST_FOUR_DIGITS_NUM, 17)}\n special_pandigitals = get_all_unique_digits_concats(\n special_pandigitals, seventeen_multiples)\n # first digit\n for pandigital in set(special_pandigitals):\n special_pandigitals.remove(pandigital)\n if '0' in pandigital:\n real_pandigital = int(\n (set(ALL_DIGITS) - set(pandigital)).pop() + pandigital)\n if is_special_pandigital(real_pandigital):\n special_pandigitals.add(real_pandigital)\n\n print(special_pandigitals)\n return sum(special_pandigitals)\n\ndef get_pentagon_nums(stop):\n if 1 >= stop:\n return list()\n pentagon_nums = [1]\n curr_diff = 4\n while (stop > pentagon_nums[-1]):\n pentagon_nums.append(pentagon_nums[-1] + curr_diff)\n curr_diff += DIFF_OF_DIFFES_BETWEEN_CONSECUTIVE_PENTAGON_NUMS\n return pentagon_nums[:-1]\n\ndef get_hexagon_nums(stop):\n if 1 >= stop:\n return set()\n hexagon_nums = [1]\n curr_diff = 5\n while (stop > hexagon_nums[-1]):\n hexagon_nums.append(hexagon_nums[-1] + curr_diff)\n curr_diff += 4\n return set(hexagon_nums[:-1])\n\n\ndef is_special_pentagon_pair(pentagons_pair, pentagon_nums_cache):\n pair_diff = abs(pentagons_pair[0] - pentagons_pair[1])\n pair_sum = sum(pentagons_pair)\n if (pair_diff in pentagon_nums_cache) and (\n pair_sum in pentagon_nums_cache):\n return True\n return False\n\ndef get_special_pentagons_pairs(stop):\n pentagon_nums = get_pentagon_nums(stop)\n pentagon_nums_cache = get_pentagon_nums(stop * 2)\n\n for pair in product(pentagon_nums, repeat=2):\n if is_special_pentagon_pair(pair, pentagon_nums_cache):\n print(pair)\n\ndef get_triangle_pentagon_hexagon_nums(stop):\n triangle_nums = get_triangle_nums(stop)\n pentagon_nums = get_pentagon_nums(stop)\n hexagon_nums = get_hexagon_nums(stop)\n\n return triangle_nums.intersection(\n pentagon_nums).intersection(hexagon_nums)\n\ndef get_twice_sqaure_pows(stop):\n return {((i ** 2) * 2) for i in range(int((stop / 2) ** 0.5) + 1)}\n\ndef is_confirming_goldbach_conjecture(\n odd_composite, primes_cache, twices_square_pows_cache):\n for twice_sqaure in twices_square_pows_cache:\n if (odd_composite - twice_sqaure) in primes_cache:\n return True\n return False\n\ndef check_goldbach_conjecture(stop):\n primes_cache = get_primes_in_range(0, stop)\n twices_square_pows_cache = get_twice_sqaure_pows(stop)\n odd_composites = set(range(9, stop, 2)) - primes_cache\n\n for odd in odd_composites:\n if not is_confirming_goldbach_conjecture(\n odd, primes_cache, twices_square_pows_cache):\n return odd\n\ndef get_nums_of_distinct_prime_factors(stop):\n distinct_prime_factors = [set() for i in range(stop)]\n primes = get_primes_in_range(0, stop // 2)\n for prime in primes:\n prime_multiple = prime\n while prime_multiple < stop:\n distinct_prime_factors[prime_multiple].add(prime)\n prime_multiple += prime\n return [len(distinct_prime_factors_of_num) for (\n distinct_prime_factors_of_num) in distinct_prime_factors]\n\ndef find_consecutive_nums_with_same_num_of_distinct_prime_factors(\n num_of_distinct_prime_factors, num_of_consecutive_nums, stop):\n nums_of_distinct_prime_factors = get_nums_of_distinct_prime_factors(stop)\n for i in range(stop - num_of_consecutive_nums):\n if ([num_of_distinct_prime_factors] * num_of_consecutive_nums) == (\n nums_of_distinct_prime_factors[\n i:i + num_of_consecutive_nums]):\n return i\n\ndef get_least_signif_digits_of_power(base, exponent, num_of_digits=10):\n modulo_arg_to_truncate_least_signif_digits = int(\n '1' + ('0' * num_of_digits))\n least_signif_digits_of_power = 1\n for i in range(exponent):\n least_signif_digits_of_power *= base\n least_signif_digits_of_power %= (\n modulo_arg_to_truncate_least_signif_digits)\n return least_signif_digits_of_power\n\ndef get_self_powers_sum(stop=1001):\n sum = 0\n for num in range(1, stop):\n sum += get_least_signif_digits_of_power(num, num)\n return sum\n\ndef in_place_map(func, mute_iterable):\n for i in range(len(mute_iterable)):\n mute_iterable[i] = func(mute_iterable[i])\n\ndef find_pentagonal_pair_with_min_diff():\n pentagon_nums = get_pentagon_nums(10000000)\n pentagon_nums_set = set(pentagon_nums)\n pairs_sums = pentagon_nums[1:]\n #print(pairs_sums)\n sums_and_pairs_firsts_diffs = []\n diff_from_last_sum = 4\n for pair_sum_i in range(len(pairs_sums)):\n sums_and_pairs_firsts_diffs.append(0)\n in_place_map(lambda x: x + diff_from_last_sum,\n sums_and_pairs_firsts_diffs)\n for sum_and_pairs_first_diff_i in range(\n len(sums_and_pairs_firsts_diffs)):\n if sums_and_pairs_firsts_diffs[sum_and_pairs_first_diff_i] in (\n pentagon_nums_set):\n pair_second = sums_and_pairs_firsts_diffs[\n sum_and_pairs_first_diff_i]\n pair_first = pairs_sums[pair_sum_i] - pair_second\n #print(pair_first, pair_second)\n if int(math.fabs(pair_first - pair_second)) in (\n pentagon_nums_set):\n return pair_first, pair_second\n diff_from_last_sum += (\n DIFF_OF_DIFFES_BETWEEN_CONSECUTIVE_PENTAGON_NUMS)\n\ndef find_prime_permutations(start, stop):\n potential_primes = {str(prime) for prime in get_primes_in_range(\n start, stop)}\n for prime in set(potential_primes):\n curr_permutations_as_lists = set(permutations(prime))\n curr_permutations = {\n ''.join(permus_list) for permus_list in curr_permutations_as_lists}\n curr_prime_permutations = curr_permutations.intersection(\n potential_primes)\n if 3 <= len(curr_prime_permutations):\n for triple_permus in combinations(curr_prime_permutations, 3):\n perm1, perm2, perm3 = map(int, sorted(triple_permus))\n if (perm2 - perm1) == (perm3 - perm2):\n print(perm1, perm2, perm3, sep='')\n\ndef get_prime_families_with_x_members(num_of_digits, num_of_members):\n start = 10 ** (num_of_digits - 1)\n stop = 10 ** num_of_digits\n primes_to_scan = {str(prime) for prime in get_primes_in_range(start,\n stop)}\n combs = get_diff_digits_indexes_combs(num_of_digits)\n families_with_x_members = []\n\n while primes_to_scan:\n curr_prime = primes_to_scan.pop()\n for diff_digits_indexes in combs:\n if is_prime_potentially_family_member(curr_prime,\n diff_digits_indexes):\n potential_primes_family = gen_potential_primes_family(\n curr_prime, diff_digits_indexes)\n\n curr_primes_family = potential_primes_family.intersection(\n primes_to_scan)\n if (num_of_members - 1) <= len(curr_primes_family):\n curr_primes_family.add(curr_prime)\n families_with_x_members.append(curr_primes_family)\n\n return families_with_x_members\n\ndef gen_potential_primes_family(prime, diff_digits_indexes):\n return {update_chars_by_indexes(prime,\n diff_digits_indexes,\n str(i)) for i in range(10)}\n\ndef update_chars_by_indexes(a_str, indexes, update_char):\n chars = list(a_str)\n for i in indexes:\n chars[i] = update_char\n return ''.join(chars)\n\ndef get_diff_digits_indexes_combs(num_of_digits):\n diff_digits_indexes_combs = []\n for num_of_diff_digits in range(1, num_of_digits):\n diff_digits_combs = (\n set(comb) for comb in combinations(range(num_of_digits),\n num_of_diff_digits))\n diff_digits_indexes_combs.extend(diff_digits_combs)\n return diff_digits_indexes_combs\n\ndef is_prime_potentially_family_member(prime, diff_digits_indexes):\n #diff_digits = {prime[i] for i in diff_digits_indexes}\n #return 1 == len(diff_digits)\n diff_digits_indexes_copy = set(diff_digits_indexes)\n diff_digit = prime[diff_digits_indexes_copy.pop()]\n for i in diff_digits_indexes_copy:\n if prime[i] != diff_digit:\n return False\n return True\n\ndef dummy():\n primes_families = get_prime_families_with_x_members(6, 8)\n for i in primes_families:\n print(i)\n cProfile.run('dummy()', sort=1)\n\ndef are_prob_having_same_digits(num1, num2):\n num1_digits = set(str(num1))\n num2_digits = set(str(num2))\n return num1_digits == num2_digits\n\ndef find_smallest_permutated_multiple():\n curr_num_of_digits = 2\n while True:\n print(curr_num_of_digits)\n smallest_permutated_multiple = (\n find_smallest_permutated_multiple_in_range(\n 10 ** (curr_num_of_digits - 1),\n (10 ** curr_num_of_digits) // 6))\n if smallest_permutated_multiple:\n return smallest_permutated_multiple\n curr_num_of_digits += 1\n\ndef find_smallest_permutated_multiple_in_range(start, stop):\n for num in range(start, stop):\n if all([are_prob_having_same_digits(num, num * i) for i in range(2,\n 7)]):\n return [num * j for j in range(1, 7)]\n\ndef main():\n print(find_smallest_permutated_multiple())\n\nif '__main__' == __name__:\n main()\n","sub_path":"solve_eulers.py","file_name":"solve_eulers.py","file_ext":"py","file_size_in_byte":32908,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"163636108","text":"import numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport logging\nfrom datetime import datetime\nfrom point_selectors.unlabeled_selector import unlabeled_selector\nfrom score_functions.search_expected_utility import search_expected_utility\nfrom models.knn_model import knn_model_prob, knn_search\nfrom query_strategies.argmax import argmax\nfrom label_oracles.lookup_oracle import lookup_oracle\n\npd.set_option('display.max_columns', 30)\npd.set_option('display.max_rows', None)\nlogging.getLogger().setLevel(logging.INFO)\nlogging.basicConfig(format='%(message)s')\n#logging.info(\"{}\".format(datetime.now()))\n\ndef twoStep(data_df, train_df, weights, alpha, visual, num_queries):\n \n \n num_points = data_df.shape[0]\n \n # for plotting\n clr = {0:'silver',1:'dimgrey'}\n clr_update = {0:'blue',1:'red'}\n df = data_df[\"labels\"].apply(lambda x: clr[x])\n\n if visual:\n plt.ion()\n\n for query in range(num_queries):\n #print(\"*** query: \",query, \" *** \",datetime.now())\n logging.info(\"*** query: {}/{} *** {}\".format(query, num_queries-1, datetime.now()))\n\n if visual:\n plt.scatter(data_df['x'], data_df['y'], s=20, color=df, alpha=0.7, marker='o')\n df.iloc[train_df.index]=data_df.loc[train_df.index,\"labels\"].apply(lambda x: clr_update[x])\n plt.draw()\n plt.waitforbuttonpress(-2)\n plt.clf()\n\n test_idx = unlabeled_selector(data_df, train_df.index)\n positive_train_idx = train_df.loc[train_df['labels']==1].index.values.tolist()\n negative_train_idx = train_df.loc[train_df['labels']==0].index.values.tolist()\n\n #Calculate score for all points in test set\n probs = knn_model_prob(alpha, weights,\n positive_train_idx, negative_train_idx, test_idx)\n\n # **************2-Step policy **************\n scores = search_expected_utility(train_df['labels'], probs)\n for point in test_idx:\n temp = 0\n for Y_x in [0, 1]:\n train_fake_df = pd.concat([train_df, data_df.iloc[[point]]])\n train_fake_df.loc[point, 'labels'] = Y_x\n positive_train_fake_idx = train_fake_df.loc[train_fake_df['labels']==1].index.values.tolist()\n negative_train_fake_idx = train_fake_df.loc[train_fake_df['labels']==0].index.values.tolist()\n test_fake_idx = unlabeled_selector(data_df, train_fake_df.index)\n next_probs = knn_model_prob(alpha, weights,\n positive_train_fake_idx, negative_train_fake_idx, test_fake_idx)\n p_y_x_1 = probs.loc[point]\n temp += ((1-p_y_x_1)*(1-Y_x) + p_y_x_1*Y_x)* next_probs.max()\n scores.loc[point] += temp\n\n selected_point_idx = argmax(scores)\n\n #Ask Oracle\n label = lookup_oracle(data_df, selected_point_idx)\n\n #Update observed data\n train_df = pd.concat([train_df, data_df.iloc[[selected_point_idx]]])\n\n print(\"***** 2-step policy *****\")\n print(\"num_queries : \", num_queries)\n print(\"found target: \",train_df['labels'].sum())\n print()\n\n pos_targets_count = train_df['labels'].sum()\n\n return pos_targets_count","sub_path":"two_step_policy.py","file_name":"two_step_policy.py","file_ext":"py","file_size_in_byte":3233,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"483004288","text":"import pandas as pd\nimport numpy as np\n\n\ninputDir = \"E:/pennyLearner\"\n\npenny_values = pd.read_csv(inputDir + '/pennies_trimmed.csv', header=0)\nlabels = pd.read_csv(inputDir + '/labels.txt', header=0)\n\nlabels = labels.values\nsymbols = penny_values.symbol.unique()\n\nprint(labels.shape)\nprint(symbols.shape)\n\n\nprint(symbols.shape)\n\n\ndef pad(A, length):\n arr = np.zeros(length)\n arr[:len(A)] = A\n return arr\n\ndef split_tickers(pennies):\n\n closes = list()\n\n max_length = 0\n\n for symbol in symbols:\n ticker_stock_values = penny_values[penny_values['symbol'] == symbol]\n\n length = ticker_stock_values.shape[0]\n if length > max_length:\n max_length = length\n\n closes.append(ticker_stock_values.close.values)\n\n\n print(\"Closes shape = \" + str(closes[0].shape))\n\n print (\"Max length = \" + str(max_length))\n\n\n padded_list = list()\n\n\n for close in closes:\n padded = pad(close, max_length)\n padded_list.append(padded)\n\n\n\n return padded_list\n\n\ntickers = split_tickers(penny_values)\n\n\nfor ticker in tickers:\n print (len(ticker))","sub_path":"DataDescribe.py","file_name":"DataDescribe.py","file_ext":"py","file_size_in_byte":1100,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"490496878","text":"import tensorflow as tf\nimport time\nfrom settings import cluster_spec, create_done_queue, NUMBER_OF_WORKERS\n\ndef ps_server_run(create_graph_proc):\n start = time.time()\n\n server = tf.train.Server(cluster_spec(), job_name='ps', task_index=0)\n sess = tf.Session(server.target)\n\n end = time.time()\n print(\"ps cluster init: \" + str(end - start))\n\n params_ops, _ = create_graph_proc(0)\n start = time.time()\n\n sess.run(params_ops)\n\n queue = create_done_queue()\n\n for _ in range(NUMBER_OF_WORKERS):\n sess.run(queue.dequeue())\n\n end = time.time()\n print(\"ps param init time total: \" + str(end - start))\n\n print(sess.run(tf.get_default_graph().get_tensor_by_name('C11:0')))\n print(sess.run(tf.get_default_graph().get_tensor_by_name('C12:0')))\n print(sess.run(tf.get_default_graph().get_tensor_by_name('C21:0')))\n print(sess.run(tf.get_default_graph().get_tensor_by_name('C22:0')))\n","sub_path":"split_matrix/ps.py","file_name":"ps.py","file_ext":"py","file_size_in_byte":926,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"526996152","text":"import logging\nfrom kotoba2.common import MapCollection\nfrom kotoba2.lexer import *\n\nlogging.basicConfig(level = logging.WARN)\n\nclass UnknownTokenError(Exception): pass\n\nclass Node(object):\n _global_last_uuid = 0\n\n def __init__(self):\n Node._global_last_uuid += 1\n\n self._uuid = Node._global_last_uuid\n\nclass DataNode(Node):\n def __init__(self):\n Node.__init__(self)\n self.data = None\n\nclass ElementNode(Node):\n TOKEN_TYPES = (OpenTagToken, SoloTagToken, CloseTagToken, IrregularTagToken)\n\n def __init__(self):\n Node.__init__(self)\n self.name = None\n self.attributes = MapCollection()\n self.parent = None\n self.children = []\n\n def __repr__(self):\n label = self.name\n\n if self.parent:\n label = '{}.{}'.format(self.parent.name, self.name)\n\n return '<{} {}>'.format(self.__class__.__name__, label)\n\nclass NodeFactory(object):\n logger = logging.getLogger('kotoba2.parser.NodeFactory')\n logger.setLevel(logging.WARN)\n\n @staticmethod\n def make(token):\n token_type = type(token)\n\n if token_type not in ElementNode.TOKEN_TYPES:\n NodeFactory.logger.debug(u'-- DATA ----- {} ({})'.format(token_type.__name__, token))\n\n data = token.data.strip()\n node = DataNode()\n\n node.data = data\n\n return node\n\n NodeFactory.logger.debug(u'-- ELEMENT -- {} ({})'.format(token_type.__name__, token))\n\n data = token.data.strip()\n node = ElementNode()\n\n node.name = token.name\n node.attributes = token.attributes\n\n return node\n\nclass Parser(object):\n logger = logging.getLogger('kotoba2.parser.Parser')\n logger.setLevel(logging.DEBUG)\n\n def parse(self, tokens):\n origin = None\n cursor = None\n cursor_index = 0\n token_count = len(tokens)\n stack = []\n\n while cursor_index < token_count:\n cursor = tokens[cursor_index]\n cursor_index += 1\n\n token_type = type(cursor)\n\n parent = stack[-1] if stack else None\n node = NodeFactory.make(cursor)\n\n if parent and token_type != CloseTagToken:\n node.parent = parent\n parent.children.append(node)\n\n if token_type == OpenTagToken:\n stack.append(node)\n elif token_type == CloseTagToken:\n if parent.name != cursor.name:\n raise RuntimeError('Expected <{}>, got <{}> instead'.format(parent.name, cursor.name))\n stack.pop()\n\n Parser.logger.debug(u'-- LEVEL -- {}'.format(len(stack)))\n Parser.logger.debug(u'-- CLASS -- {}'.format(token_type.__name__))\n Parser.logger.debug(u'-- STACK -- {}'.format(stack))\n\n if not origin and token_type == OpenTagToken:\n Parser.logger.debug(u'-- ORIGIN -- {}'.format(node))\n origin = node\n\n return origin\n","sub_path":"kotoba2/parser.py","file_name":"parser.py","file_ext":"py","file_size_in_byte":3001,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"492187027","text":"\"\"\"\nBackend file contains functions for the game logic.\n\"\"\"\n\nimport json\nfrom pathlib import Path\nimport random\n\n\nclass Tile:\n def __init__(self, rotation, path):\n self.rotation = rotation\n self.path = path\n\n\nclass Robot:\n def __init__(self, rotation, path):\n self.rotation = rotation\n self.path = path\n\n\nclass State:\n def __init__(self, board, robots):\n self.board = board\n self.robots = robots\n\n\ndef get_data(map_name):\n \"\"\"\n Return decoded JSON map file as a dictionary.\n\n map_name: a map of the game board created in Tiled 1.2 and saved as JSON file\n json.load() turns JSON encoded data into Python objects\n \"\"\"\n with open(map_name, encoding=\"utf-8\") as f:\n data = json.load(f)\n return data\n\n\ndef get_coordinates(data):\n \"\"\"\n Return a list of coordinates for individual tiles on the map.\n\n data: a dict created from decoded Tiled 1.2 JSON file\n Get the size of the game board and x, y vectors for each tile and creates a list of all tile coordinates, for example:\n [(0, 11), (0, 10), (0, 9), ..., (0, 0), (1, 11), (1, 10), ..., (11, 1), (11, 0)]\n Transformation with reversed is required as the JSON tiles are in an opposite direction.\n \"\"\"\n coordinates = []\n for y in reversed(range(data['layers'][0]['height'])):\n for x in range(data['layers'][0]['width']):\n coordinates.append((x, y))\n return coordinates\n\n\ndef get_paths(data):\n \"\"\"\n Return a dictionary with modified tile ID as a key and path to a real image as a value.\n\n data: a dict created from decoded Tiled 1.2 JSON file\n Create a dictionary where tile ID is modified with the number of the layer so it matches the number of the tile in the tilelist.\n \"\"\"\n paths = {}\n for i in data['tilesets'][0]['tiles']:\n image_id = i['id'] + data['tilesets'][0]['firstgid']\n image_path = i['image']\n image_path = image_path[1:] # unelegant way of removing ../ at the beginning of the path\n paths[image_id] = image_path\n return paths\n\n\ndef get_tile_id(number):\n return number & 0xFFFFFF\n\n\ndef get_tile_rotation(number):\n return number >> (4*7)\n\n\ndef get_board(data):\n \"\"\"\n Return dictionary of tiles together with path to image and its rotation.\n\n data: a dict created from decoded Tiled 1.2 JSON file\n coordinates: a list of coordinates of all tiles\n\n More about dictionaries: https://naucse.python.cz/2018/pyladies-brno-podzim/beginners/dict/\n \"\"\"\n paths = get_paths(data)\n coordinates = get_coordinates(data)\n rotation_dict = {0: 0, 10: 90, 12: 180, 6: 270}\n board = {}\n for layer in data['layers']:\n tiles_layer = []\n for data in layer['data']:\n id = get_tile_id(data)\n if id == 0:\n tile = Tile(0, 0)\n else:\n rotation_index = get_tile_rotation(data)\n rotation = rotation_dict[rotation_index]\n tile = Tile(rotation, paths[id])\n tiles_layer.append(tile)\n board[layer['id']] = dict(zip(coordinates, tiles_layer))\n return board\n\n\ndef get_starting_coordinates(board):\n \"\"\"\n Return a list with coordinates where are starting squares\n ...\n \"\"\"\n starting_coordinates = []\n for list in board.items():\n for key, value in list[1].items():\n for i in range(9):\n if value.path == (\"./img/squares/png/starting_square0{}.png\".format(i)):\n starting_coordinates.append(key)\n return starting_coordinates\n\n\ndef get_robot_paths():\n \"\"\"\n Return a list with paths to robots images\n ...\n \"\"\"\n robot_paths = []\n for path in Path('./img/robots_map/png/').iterdir(): # search image file\n robot = Robot(0, path)\n robot_paths.append(robot)\n return robot_paths\n\n\ndef get_robots_to_start(board):\n starting_coordinates = get_starting_coordinates(board)\n robot_paths = get_robot_paths()\n robots_start = {}\n for coordinate in starting_coordinates:\n if robot_paths:\n robot = random.choice(robot_paths)\n robot_paths.remove(robot)\n robots_start[coordinate] = robot\n return robots_start\n\n\ndef get_start_state(data):\n board = get_board(data)\n robots_start = get_robots_to_start(board)\n state = State(board, robots_start)\n return state\n","sub_path":"backend.py","file_name":"backend.py","file_ext":"py","file_size_in_byte":4378,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"263803352","text":"from JsonProcess import JsonProcess\r\nimport re\r\n\r\n\r\ndef main():\r\n file_name = 'materials/jawiki-country.json'\r\n json_pro = JsonProcess(file_name)\r\n sentence = json_pro.search_text('イギリス')\r\n template_dict = json_pro.extract_template(sentence)\r\n\r\n # knock26\r\n pattern = re.compile(r\"'+\")\r\n for k, v in template_dict.items():\r\n new_v = re.sub(pattern, '', v)\r\n template_dict[k] = new_v\r\n\r\n # knock28\r\n # knock27 + Fileも処理に含めるようにpattern変更(':'の修正と(xxx|)の出現回数を0or1から*に)\r\n # pattern = re.compile(r'\\[\\[([^|:\\]]*?\\|)?([^:]*?)\\]\\]')\r\n pattern = re.compile(r'\\[\\[([^|\\]]*?\\|)*(.*?)\\]\\]')\r\n for k, v in template_dict.items():\r\n new_v = re.sub(pattern, r'\\2', v) # [[xxx|yyy]]or[[yyy]]に一致する文字列をyyyに置換\r\n template_dict[k] = new_v\r\n\r\n # URLの削除\r\n # [http://xxx] or [http://xxx yyy] -> yyy\r\n pattern = re.compile(r'\\[http://(\\S)*\\s(.*?)\\]')\r\n for k, v in template_dict.items():\r\n new_v = re.sub(pattern, r'\\2', v)\r\n template_dict[k] = new_v\r\n\r\n # br, ref, referenceの削除\r\n pattern = re.compile(r'?(br|ref)[^>]*?>')\r\n for k, v in template_dict.items():\r\n new_v = re.sub(pattern, '', v)\r\n template_dict[k] = new_v\r\n\r\n # {{lang|xxx|yyy}} -> yyy\r\n pattern = re.compile(r'\\{\\{lang\\|([^\\|]+?)\\|([^\\}]*?)\\}\\}')\r\n for k, v in template_dict.items():\r\n new_v = re.sub(pattern, r'\\2', v)\r\n template_dict[k] = new_v\r\n\r\n\r\n # print('基礎情報: {0}'.format(template_name))\r\n for tt in template_dict.items():\r\n print(tt)\r\n\r\n\r\nif __name__ == '__main__':\r\n main()\r\n","sub_path":"knock28.py","file_name":"knock28.py","file_ext":"py","file_size_in_byte":1680,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"517883167","text":"import numba\nimport pytest\n\nak = pytest.importorskip(\"awkward\")\n\nfrom vector.numba.awkward.lorentz.xyzt import behavior # noqa: E402\nfrom vector.single.lorentz.xyzt import LorentzXYZTFree # noqa: E402\n\n\n@numba.njit\ndef fill_it(testit, output):\n output.append(testit)\n output.append(testit)\n\n\ndef test_fillable():\n testit = LorentzXYZTFree(1, 2, 3, 4)\n output = ak.ArrayBuilder(behavior=behavior)\n fill_it(testit, output)\n\n assert str(output.snapshot()) == \"[Lxyz(1 2 3 4), Lxyz(1 2 3 4)]\"\n\n\n@numba.njit\ndef adding_muons(input):\n for muons in input:\n for i in range(len(muons)):\n for j in range(i + 1, len(muons)):\n return muons[i] + muons[j]\n\n\ndef test_addition(ak_HZZ_example):\n example = ak.Array(ak_HZZ_example, behavior=behavior)\n assert str(adding_muons(example)) == \"Lxyz(-15.2 -11 -19.5 94.2)\"\n\n\n@numba.njit\ndef do_cool_stuff(input, output):\n for muons in input:\n output.begin_list()\n\n for i in range(len(muons)):\n output.begin_list()\n\n for j in range(i + 1, len(muons)):\n zboson = muons[i] + muons[j]\n\n output.begin_tuple(2)\n output.index(0)\n output.append(zboson)\n output.index(1)\n output.append(zboson.mag)\n output.end_tuple()\n\n output.end_list()\n\n output.end_list()\n\n\ndef test_cool_stuff(ak_HZZ_example):\n example = ak.Array(ak_HZZ_example, behavior=behavior)\n output = ak.ArrayBuilder(behavior=behavior)\n do_cool_stuff(example, output)\n\n assert (\n str(output.snapshot())\n == \"[[[(Lxyz(-15.2 -11 -19.5 94.2), 90.2)], []], [[]], [[(, ... [[]], [[]], [[]], [[]]]\"\n )\n","sub_path":"tests/numba_tests/test_awkward.py","file_name":"test_awkward.py","file_ext":"py","file_size_in_byte":1729,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"565062013","text":"from train_nn import *\nfrom test_nn import *\nimport subprocess\n\ntrain_path = '../../data/titles-en-train.labeled'\ntrain_nn(train_path, layer_num=1, node_num=2, epoch_num=1, λ=0.1)\n\ntest_path = '../../data/titles-en-test.word'\nout_path = './out.txt'\ntest_nn(test_path, out_path)\n\nscript_path = '../../script/grade-prediction.py'\nans_path = '../../data/titles-en-test.labeled'\nsubprocess.run(f'{script_path} {ans_path} {out_path}'.split())\n\n\n''' RESULT\nAccuracy = 92.915338%\n'''\n","sub_path":"kiyuna/tutorial07/tutorial07.py","file_name":"tutorial07.py","file_ext":"py","file_size_in_byte":478,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"528425623","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Mon Jun 19 15:29:31 2017\n\n@author: lenovo\n\"\"\"\n\n#display a range of records with limit and skip functions\n#display rumbers form 11 to 20\n\nimport sys\nfrom pymongo import MongoClient\nfrom pymongo import ASCENDING\nfrom pymongo.errors import ConnectionFailure\n\ndef main():\n try:\n c = MongoClient()\n print(\"Connected sucessfully to MongoDB\")\n except ConnectionFailure as err:\n print(\"Connection to MongoDB failed\")\n sys.exit(1)\n \n tutorial = c['tutorial']\n cursor = tutorial.numbers.find().sort(\"num\", ASCENDING).skip(11).limit(10)\n \n for document in cursor:\n print(document.get(\"num\"))\n \nif __name__ == \"__main__\":\n main()","sub_path":"pymongo/range_with_limit_skip.py","file_name":"range_with_limit_skip.py","file_ext":"py","file_size_in_byte":722,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"231802930","text":"#!/usr/bin/env python3\n#\n# Copyright (c) 2020 Miklos Vajna and contributors.\n# Use of this source code is governed by a BSD-style license that can be\n# found in the LICENSE file.\n\n\"\"\"\nThe config module contains functionality related to configuration handling.\nIt intentionally doesn't import any other 'own' modules, so it can be used anywhere.\n\"\"\"\n\nfrom typing import Any\nfrom typing import List\nfrom typing import Optional\nimport configparser\nimport os\n\n\nclass Config:\n \"\"\"Exposes config key values from wsgi.ini.\"\"\"\n __config: Optional[configparser.ConfigParser] = None\n\n @staticmethod\n def __get() -> configparser.ConfigParser:\n \"\"\"Gives direct access to the read config key values.\"\"\"\n if Config.__config is None:\n Config.__config = configparser.ConfigParser()\n config_path = get_abspath(\"wsgi.ini\")\n Config.__config.read(config_path)\n\n return Config.__config\n\n @staticmethod\n def get_value(key: str) -> str:\n \"\"\"Gets the value of key.\"\"\"\n Config.__get()\n assert Config.__config is not None\n return Config.__config.get(\"wsgi\", key)\n\n @staticmethod\n def set_value(key: str, value: str) -> None:\n \"\"\"Sets key to value in the in-memory config.\"\"\"\n Config.__get()\n assert Config.__config is not None\n if value:\n Config.__config.read_dict({\"wsgi\": {key: value}})\n else:\n Config.__config.remove_option(\"wsgi\", key)\n\n @staticmethod\n def has_value(key: str) -> bool:\n \"\"\"Determines if key is set in the config.\"\"\"\n Config.__get()\n assert Config.__config is not None\n return Config.__config.has_option(\"wsgi\", key)\n\n @staticmethod\n def get_workdir() -> str:\n \"\"\"Gets the directory which is writable.\"\"\"\n Config.__get()\n assert Config.__config is not None\n return get_abspath(Config.__config.get('wsgi', 'workdir').strip())\n\n @staticmethod\n def get_reference_housenumber_paths() -> List[str]:\n \"\"\"Gets the abs paths of ref housenumbers.\"\"\"\n Config.__get()\n assert Config.__config is not None\n relpaths = Config.__config.get(\"wsgi\", \"reference_housenumbers\").strip().split(' ')\n return [get_abspath(relpath) for relpath in relpaths]\n\n @staticmethod\n def get_reference_street_path() -> str:\n \"\"\"Gets the abs path of ref streets.\"\"\"\n Config.__get()\n assert Config.__config is not None\n relpath = Config.__config.get(\"wsgi\", \"reference_street\").strip()\n return get_abspath(relpath)\n\n @staticmethod\n def get_reference_citycounts_path() -> str:\n \"\"\"Gets the abs path of ref citycounts.\"\"\"\n Config.__get()\n assert Config.__config is not None\n relpath = Config.__config.get(\"wsgi\", \"reference_citycounts\").strip()\n return get_abspath(relpath)\n\n @staticmethod\n def get_locale() -> str:\n \"\"\"Gets the locale.\"\"\"\n Config.__get()\n assert Config.__config is not None\n return Config.__config.get(\"wsgi\", \"locale\").strip()\n\n @staticmethod\n def get_timezone() -> str:\n \"\"\"Gets the timezone.\"\"\"\n Config.__get()\n assert Config.__config is not None\n return Config.__config.get(\"wsgi\", \"timezone\").strip()\n\n @staticmethod\n def get_uri_prefix() -> str:\n \"\"\"Gets the global URI prefix.\"\"\"\n Config.__get()\n assert Config.__config is not None\n return Config.__config.get(\"wsgi\", \"uri_prefix\").strip()\n\n @staticmethod\n def get_tcp_port() -> int:\n \"\"\"Gets the TCP port to be used.\"\"\"\n Config.__get()\n assert Config.__config is not None\n return int(Config.__config.get(\"wsgi\", \"tcp_port\", fallback=\"8000\").strip())\n\n @staticmethod\n def get_overpass_uri() -> str:\n \"\"\"Gets the URI of the overpass instance to be used.\"\"\"\n Config.__get()\n assert Config.__config is not None\n return Config.__config.get(\"wsgi\", \"overpass_uri\", fallback=\"https://overpass-api.de\").strip()\n\n @staticmethod\n def get_cron_update_inactive() -> bool:\n \"\"\"Should cron.py update inactive relations?\"\"\"\n Config.__get()\n assert Config.__config is not None\n return Config.__config.get(\"wsgi\", \"cron_update_inactive\", fallback=\"False\").strip() == \"True\"\n\n\nclass ConfigContext:\n \"\"\"Context manager for Config.\"\"\"\n def __init__(self, key: str, value: str) -> None:\n \"\"\"Remembers what should be the new value.\"\"\"\n self.key = key\n self.value = value\n self.old_value = \"\"\n if Config.has_value(key):\n self.old_value = Config.get_value(key)\n\n def __enter__(self) -> 'ConfigContext':\n \"\"\"Switches to the new value.\"\"\"\n Config.set_value(self.key, self.value)\n return self\n\n def __exit__(self, _exc_type: Any, _exc_value: Any, _exc_traceback: Any) -> bool:\n \"\"\"Switches back to the old value.\"\"\"\n Config.set_value(self.key, self.old_value)\n return True\n\n\ndef get_abspath(path: str) -> str:\n \"\"\"Make a path absolute, taking the repo root as a base dir.\"\"\"\n if os.path.isabs(path):\n return path\n\n return os.path.join(os.path.dirname(__file__), path)\n\n\n# vim:set shiftwidth=4 softtabstop=4 expandtab:\n","sub_path":"config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":5297,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"505268458","text":"from google.appengine.ext import webapp\r\nfrom google.appengine.ext.webapp.util import run_wsgi_app\r\nfrom google.appengine.ext import db\r\nfrom google.appengine.api import users\r\nimport cgi\r\nimport datetime\r\nimport webapp2\r\n\r\nclass Comment(db.Expando):\r\n pass\r\n\r\nclass CommentHandler(webapp2.RequestHandler):\r\n def post(self):\r\n c = Comment()\r\n c.commenter = users.get_current_user()\r\n c.message = db.Text(self.request.get('message'))\r\n c.date = datetime.datetime.now()\r\n c.put()\r\n\r\n self.redirect('/')\r\n\r\nclass CommentFormHandler(webapp2.RequestHandler):\r\n def get(self):\r\n self.response.out.write('Comments:
')\r\n # Borrowing a bit from chapter 5...\r\n for c in Comment.all().order('-date'):\r\n self.response.out.write('%s posted by %s on %s '\r\n % (cgi.escape(c.message),\r\n cgi.escape(c.commenter.nickname()),\r\n c.date))\r\n self.response.out.write(' ')\r\n\r\n self.response.out.write('''Post a comment:
\r\n\r\n''')\r\n\r\napp = webapp2.WSGIApplication(\r\n [('/', CommentFormHandler),\r\n ('/post', CommentHandler)],\r\n debug=True)\r\n","sub_path":"datastore/commentform/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1378,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"29661697","text":"__author__ = 'Milad'\r\nfrom staticobject import *\r\nclass Block (StaticObject):\r\n def __init__(self, pos, width, height):\r\n \"\"\"\r\n\r\n :param pos: Vector\r\n :param size: Vector\r\n \"\"\"\r\n super(Block, self).__init__(pos)\r\n self.width = width\r\n self.height = height\r\n","sub_path":"server/block.py","file_name":"block.py","file_ext":"py","file_size_in_byte":310,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"627652433","text":"# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.\nimport torch\n#import torchvision\n\nimport sys\nimport os\nimport cv2\nfrom PIL import Image\n# modified\nsys.path.append('/home/wangcheng/FcosNet')\n\nfrom maskrcnn_benchmark.structures.bounding_box import BoxList\n#from maskrcnn_benchmark.structures.segmentation_mask import SegmentationMask\n#from maskrcnn_benchmark.structures.keypoint import PersonKeypoints\n\n\nmin_keypoints_per_image = 10\n\n\ndef _count_visible_keypoints(anno):\n return sum(sum(1 for v in ann[\"keypoints\"][2::3] if v > 0) for ann in anno)\n\n\ndef _has_only_empty_bbox(anno):\n return all(any(o <= 1 for o in obj[\"bbox\"][2:]) for obj in anno)\n\n\ndef has_valid_annotation(anno):\n # if it's empty, there is no annotation\n if len(anno) == 0:\n return False\n # if all boxes have close to zero area, there is no annotation\n if _has_only_empty_bbox(anno):\n return False\n # keypoints task have a slight different critera for considering\n # if an annotation is valid\n if \"keypoints\" not in anno[0]:\n return True\n # for keypoint detection tasks, only consider valid images those\n # containing at least min_keypoints_per_image\n if _count_visible_keypoints(anno) >= min_keypoints_per_image:\n return True\n return False\n\n\nclass CocoDetection(object):\n \"\"\"`MS Coco Detection `_ Dataset.\n\n Args:\n root (string): Root directory where images are downloaded to.\n annFile (string): Path to json annotation file.\n transform (callable, optional): A function/transform that takes in an PIL image\n and returns a transformed version. E.g, ``transforms.ToTensor``\n target_transform (callable, optional): A function/transform that takes in the\n target and transforms it.\n \"\"\"\n def __init__(self, root, annFile, slice_range):\n super(CocoDetection, self).__init__()\n from cocoapi.PythonAPI.pycocotools.coco import COCO\n self.root = root\n self.range = slice_range\n self.coco = COCO(annFile)\n self.ids = list(sorted(self.coco.imgs.keys()))\n\n def __getitem__(self, index):\n \"\"\"\n Args:\n index (int): Index\n\n Returns:\n tuple: Tuple (image, target). target is the object returned by ``coco.loadAnns``.\n \"\"\"\n coco = self.coco\n img_id = self.ids[index]\n ann_ids = coco.getAnnIds(imgIds=img_id)\n #print('ann_ids:', ann_ids)\n target = coco.loadAnns(ann_ids)\n #print('target:', target)\n\n path = coco.loadImgs(img_id)[0]['file_name']\n #print(path)\n\n # modified (add for lung detection)\n path_split = path.split('/')\n sub_dir = path[:-len(path_split[-1])]\n slice_index = int(path_split[-1][:-4]) # current slice index\n\n '''\n image_merge = []\n half_range = self.range // 2\n for i in range(self.range):\n merge_slice_index = slice_index + i - half_range\n merge_slice_path = os.path.join(self.root, sub_dir, '%03d.png'%merge_slice_index)\n if not os.path.exists(merge_slice_path):\n merge_slice_path = os.path.join(self.root, sub_dir, '%03d.png'%slice_index)\n image_merge.append(Image.open(merge_slice_path))\n '''\n\n #print(slice_index)\n slice_index_before = slice_index - 1\n slice_index_next = slice_index + 1\n\n slice_before_path = os.path.join(self.root, sub_dir, '%03d.png'%slice_index_before)\n slice_next_path = os.path.join(self.root, sub_dir, '%03d.png'%slice_index_next)\n if not os.path.exists(slice_before_path):\n slice_before_path = os.path.join(self.root, sub_dir, '%03d.png'%slice_index)\n if not os.path.exists(slice_next_path):\n slice_next_path = os.path.join(self.root, sub_dir, '%03d.png'%slice_index)\n\n #print('slice_before_path:', slice_before_path)\n #print('middle_path:', os.path.join(self.root, path))\n #print('slice_next_path:', slice_next_path)\n img_up = Image.open(slice_before_path)\n img_middle = Image.open(os.path.join(self.root, path))\n img_bottom = Image.open(slice_next_path)\n\n img = Image.merge('RGB', [img_up, img_middle, img_bottom])\n\n\n # modified\n #img = Image.open(os.path.join(self.root, path)).convert('RGB')\n\n return img, target, os.path.join(self.root, path)\n\n\n def __len__(self):\n return len(self.ids)\n\nclass COCODataset(CocoDetection):\n#class COCODataset(torchvision.datasets.coco.CocoDetection):\n def __init__(\n # modified\n #self, ann_file, root, remove_images_without_annotations, transforms=None, expands=None\n self, ann_file, root, slice_range, transforms=None, expands=None\n ):\n super(COCODataset, self).__init__(root, ann_file, slice_range)\n # sort indices for reproducible results\n self.ids = sorted(self.ids)\n #print('success:', slice_range)\n\n '''\n # filter images without detection annotations\n if remove_images_without_annotations:\n ids = []\n for img_id in self.ids:\n ann_ids = self.coco.getAnnIds(imgIds=img_id, iscrowd=None)\n anno = self.coco.loadAnns(ann_ids)\n if has_valid_annotation(anno):\n ids.append(img_id)\n self.ids = ids\n '''\n\n self.json_category_id_to_contiguous_id = {\n v: i + 1 for i, v in enumerate(self.coco.getCatIds())\n }\n self.contiguous_category_id_to_json_id = {\n v: k for k, v in self.json_category_id_to_contiguous_id.items()\n }\n\n self.id_to_img_map = {k: v for k, v in enumerate(self.ids)}\n self.transforms = transforms\n self.expands = expands\n\n def __getitem__(self, idx):\n img, anno, img_path = super(COCODataset, self).__getitem__(idx)\n\n # filter crowd annotations\n # TODO might be better to add an extra field\n anno = [obj for obj in anno if obj[\"iscrowd\"] == 0]\n\n boxes = [obj[\"bbox\"] for obj in anno]\n boxes = torch.as_tensor(boxes).reshape(-1, 4) # guard against no boxes\n target = BoxList(boxes, img.size, mode=\"xywh\").convert(\"xyxy\") # convert xywh format to xyxy format\n\n # modified (add expands to target)\n if self.expands != [] and self.expands is not None:\n #print('success')\n target = target.expand_bbox_by_pix(expand=self.expands[0], size_thresh=self.expands[1])\n #target = target.expand_bbox_by_pix(3, 16)\n\n\n classes = [obj[\"category_id\"] for obj in anno]\n classes = [self.json_category_id_to_contiguous_id[c] for c in classes]\n classes = torch.tensor(classes)\n #print('class:', classes)\n target.add_field(\"labels\", classes)\n\n # modified\n '''\n masks = [obj[\"segmentation\"] for obj in anno]\n masks = SegmentationMask(masks, img.size, mode='poly')\n target.add_field(\"masks\", masks)\n\n if anno and \"keypoints\" in anno[0]:\n keypoints = [obj[\"keypoints\"] for obj in anno]\n keypoints = PersonKeypoints(keypoints, img.size)\n target.add_field(\"keypoints\", keypoints)\n '''\n\n #print('before clip: ', target.bbox)\n #print('before_clip_path: ', img_path)\n\n #print('target before:', target)\n target = target.clip_to_image(remove_empty=True) # make sure bbox is inside the image\n #print('target after:', target)\n\n #print('before: ', target.bbox)\n #print('before_path: ', img_path)\n\n if self.transforms is not None:\n img, target = self.transforms(img, target)\n\n #print('trans: ', target.bbox)\n #print('path: ', img_path)\n\n return img, target, img_path, idx\n\n # get image's information:\n def get_img_info(self, index):\n img_id = self.id_to_img_map[index]\n img_data = self.coco.imgs[img_id]\n return img_data\n","sub_path":"build/lib.linux-x86_64-3.7/maskrcnn_benchmark/data/datasets/coco_fcos.py","file_name":"coco_fcos.py","file_ext":"py","file_size_in_byte":8043,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"609227664","text":"import sys\nsys.setrecursionlimit(1 << 25)\nread = sys.stdin.readline\nra = range\nenu = enumerate\n\n\ndef exit(*argv, **kwarg):\n print(*argv, **kwarg)\n sys.exit()\n\n\ndef mina(*argv, sub=1): return list(map(lambda x: x - sub, argv))\n# 受け渡されたすべての要素からsubだけ引く.リストを*をつけて展開しておくこと\n\n\ndef a_int(): return int(read())\n\n\ndef ints(): return list(map(int, read().split()))\n\n\ndef read_col(H):\n '''H is number of rows\n A列、B列が与えられるようなとき\n ex1)A,B=read_col(H) ex2) A,=read_col(H) #一列の場合'''\n ret = []\n for _ in range(H):\n ret.append(list(map(int, read().split())))\n return tuple(map(list, zip(*ret)))\n\n\ndef read_tuple(H):\n '''H is number of rows'''\n ret = []\n for _ in range(H):\n ret.append(tuple(map(int, read().split())))\n return ret\n\n\ndef read_matrix(H):\n '''H is number of rows'''\n ret = []\n for _ in range(H):\n ret.append(list(map(int, read().split())))\n return ret\n # return [list(map(int, read().split())) for _ in range(H)] # 内包表記はpypyでは遅いため\n\n\nMOD = 10**9 + 7\nINF = 2**31 # 2147483648 > 10**9\n# default import\nfrom collections import defaultdict, Counter, deque\nfrom operator import itemgetter, xor, add\nfrom itertools import product, permutations, combinations\nfrom bisect import bisect_left, bisect_right # , insort_left, insort_right\nfrom functools import reduce\nfrom math import gcd\n\n\ndef lcm(a, b):\n # 最小公倍数\n g = gcd(a, b)\n return a // g * b\n\n# エラトステネスの篩の篩みたいに約数の個数をどんどん作っていくのは?\n\n\ndef ret_eratos(N: int):\n '''エラトステネスの篩'''\n '''is_primeは約数の個数'''\n is_prime = [0] * (N + 1)\n is_prime[0] = -2 # 0と1は素数ではない\n is_prime[1] = -1\n for i in range(2, N // 2 + 1):\n for j in range(i * 2, N + 1, i): # iの倍数は素数でない\n is_prime[j] += 1\n for i in range(N + 1):\n is_prime[i] += 2\n return is_prime\n\n\nN = a_int()\neratos = ret_eratos(N)\n# print(eratos)\nans = 0\nfor k in range(1, N + 1):\n ans += k * eratos[k]\nprint(ans)\n\n# でも多分TLEだなぁ\n","sub_path":"contests/abc172/d/d.py","file_name":"d.py","file_ext":"py","file_size_in_byte":2219,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"198456275","text":"import os\nimport numpy as np\nimport pandas as pd\n\nfrom tqdm import tqdm\n\nfrom sklearn.model_selection import train_test_split\n\nimport torch\nfrom torch.utils.data import DataLoader\n\nimport similarity\n\n\nMODEL_DIR = 'model/'\n\nWORD_SEP = '▁'\n\nDATA_FILE = './data/qa_data.csv'\nEMBEDDINGS_FILE = './cc.ru.300.vec'\n\nPAD_TOKEN = 'PAD'\nPAD_INDEX = 0\nTOTAL_WORDS = 1000000\n\nTOTAL_DATA = -1\n\nN_EPOCHS = 5\nBATCH_SIZE = 512\nLEARNING_RATE = 0.001\n\nSAMPLING_TYPE = 'random'\n\ndevice = torch.device('cuda') if torch.cuda.is_available() else torch.device('cpu')\n\ndata = pd.read_csv(DATA_FILE)\ndata = data[:TOTAL_DATA]\n\nword2index, embeddings = similarity.read_word2vec_file(file_path=EMBEDDINGS_FILE, \n pad_token=PAD_TOKEN,\n pad_index=PAD_INDEX,\n total_words=TOTAL_WORDS)\n\ntrain_data, validation_data = train_test_split(data, test_size=0.1)\n\ntrain_data = similarity.W2WSimilarityDataset(query=list(train_data.question),\n response=list(train_data.answer),\n word2index=word2index)\n\nvalidation_data = similarity.W2WSimilarityDataset(query=list(validation_data.question), \n response=list(validation_data.answer),\n word2index=word2index)\n\ntrain_loader = DataLoader(dataset=train_data, batch_size=BATCH_SIZE, shuffle=True)\nvalidation_loader = DataLoader(dataset=validation_data, batch_size=BATCH_SIZE, shuffle=False)\n\nembeddings_layer = torch.nn.Embedding.from_pretrained(embeddings=embeddings, padding_idx=PAD_INDEX)\n\nquery_encoder = similarity.Encoder(embeddings_layer=embeddings_layer)\ncandidate_encoder = similarity.Encoder(embeddings_layer=embeddings_layer)\n\nmodel = similarity.ClassificationWrapper(query_encoder, candidate_encoder, sampling_type=SAMPLING_TYPE)\n\nmodel.to(device)\n\noptimizer = torch.optim.Adam(params=model.parameters(), lr=LEARNING_RATE)\n\nrunner = similarity.Runner(model, optimizer, train_loader, validation_loader, model_dir=MODEL_DIR, device=device)\n\nrunner.train(epochs=N_EPOCHS)\n","sub_path":"train.py","file_name":"train.py","file_ext":"py","file_size_in_byte":2233,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"3769121","text":"import sys\nimport time\n\nimport psycopg2\nfrom selenium.common.exceptions import NoSuchElementException\nfrom selenium.common.exceptions import TimeoutException\nfrom selenium.webdriver import ActionChains\nfrom selenium.webdriver.common.by import By\nfrom selenium.webdriver.support import expected_conditions as EC\nfrom selenium.webdriver.support.ui import WebDriverWait\n\nfrom Pages.taobao.itemdetail import TBCrawler, ItemDetailCrawler\n\n# 品牌有两个拼写,一个是淘宝的品牌名,一个是搜索此品牌时该打的字母(按品牌名有时会搜到不相关的品牌)\n\nitem_section = ['auctions', 'personalityData']\n\n\ndef ring(n):\n a = 0\n while a < n:\n sys.stdout.write('\\a')\n sys.stdout.flush()\n a += 1\n\n\nclass BrandSalesCrawler(TBCrawler):\n def __init__(self, brand, date):\n super().__init__()\n self.brand = brand\n\n self.crawl_date = date\n self.dbinfo = \"dbname='tbbrandsales' user='jiangjiang' host='localhost' password='8326022'\"\n # list of dictionary {price, tbupc, volume, category}\n\n self.search_name, self.tb_brand, self.gabage_brand = self.get_brand_info()\n\n # list of dictionary {tbupc, brand}\n self.data = []\n self.wrong_data = []\n self.already_data = self.get_already_data()\n self.stop = False\n\n def get_brand_info(self):\n con = psycopg2.connect(self.dbinfo)\n cur = con.cursor()\n cur.execute(\"\"\"SELECT tb_search_term, tb_name, tb_not_name FROM brand WHERE name=%s;\"\"\", (self.brand,))\n d = cur.fetchall()\n search = d[0][0]\n br = d[0][1].split(';;')\n if d[0][2]:\n bc = d[0][2].split(';;')\n else:\n bc = []\n return search, br, bc\n\n def get_already_data(self):\n con = psycopg2.connect(self.dbinfo)\n cur = con.cursor()\n cur.execute(\n \"\"\"SELECT itemid FROM sales WHERE time=%s and itemid IN (SELECT itemid FROM item WHERE brand=%s);\"\"\",\n (self.crawl_date, self.brand))\n d = [i[0] for i in cur.fetchall()]\n con.close()\n print(str(len(d)) + \" already crawled\")\n return set(d)\n\n def start(self):\n self.search_brand()\n self.crawl_items()\n\n while not self.is_final_page() and not self.stop:\n self.goto_next_page()\n time.sleep(3)\n self.crawl_items()\n\n print(\"done\")\n\n def search_brand(self):\n self.login()\n time.sleep(3)\n self.home_search(self.search_name)\n self.filter_category()\n time.sleep(3)\n self.filter_rank()\n time.sleep(3)\n\n def filter_category(self):\n WebDriverWait(self.driver, self.wait_time).until(\n EC.presence_of_element_located((By.XPATH, \"//a[@title='彩妆/香水/美妆工具']\"))).click()\n\n def filter_rank(self):\n WebDriverWait(self.driver, self.wait_time).until(\n EC.presence_of_element_located((By.XPATH, \"//li[@class='sort']/a[@trace='sortSaleDesc']\"))).click()\n\n def is_final_page(self):\n try:\n self.driver.find_element_by_css_selector('.item.next.next-disabled')\n return True\n except NoSuchElementException:\n return False\n\n def crawl_items(self):\n print(self.get_pages())\n for i in item_section:\n print(i)\n if not self.stop:\n self.crawl_section(i)\n else:\n break\n\n self.write_data()\n\n def write_data(self):\n con = psycopg2.connect(self.dbinfo)\n cur = con.cursor()\n for i in self.data:\n i['brand'] = self.brand\n i['time'] = self.crawl_date\n try:\n cur.executemany(\n \"\"\"INSERT INTO item(itemid, categoryid, brand) VALUES (%(tbupc)s, %(category)s, %(brand)s);\"\"\",\n self.data\n )\n except psycopg2.IntegrityError as ie:\n con.rollback()\n new_cid = self.find_new_cid(str(ie))\n cur.execute(\"\"\"INSERT INTO category (categoryid) VALUES(%s);\"\"\", (new_cid,))\n print(\"insert new cid \" + str(new_cid))\n con.commit()\n con.close()\n self.write_data()\n else:\n cur.executemany(\n \"\"\"INSERT INTO sales(itemid, price, volume, time) VALUES (%(tbupc)s, %(price)s, %(volume)s, %(time)s);\"\"\",\n self.data\n )\n con.commit()\n con.close()\n self.data = []\n print(self.wrong_data)\n\n def find_new_cid(self, ie):\n pre_str = 'Key (categoryid)=('\n start_pos = ie.find(pre_str)\n after_pos = ie[start_pos + len(pre_str):].find(')')\n return int(ie[start_pos + len(pre_str):][:after_pos])\n\n def crawl_section(self, section):\n try:\n items = len(self.get_item_elements(section))\n except TimeoutException:\n print(\"no \" + section)\n return\n\n for i in range(items):\n if not self.stop:\n print(str(i) + \"/\" + str(range(items)))\n self.crawl_single_item(self.get_item_xpath(i, section))\n else:\n return\n\n def get_item_elements(self, section):\n return WebDriverWait(\n self.driver, 3).until(\n EC.presence_of_all_elements_located(\n (By.XPATH, \"//div[@class='items']//div[@data-category='{0}']\".format(section))))\n\n def crawl_single_item(self, item):\n # 在搜索页看到的宝贝交易数量,因为是按数量由大到小排序,因此如果到0,即可终止程序\n outer_volume = self.get_item_outer_volume(item)\n if outer_volume == 0:\n self.stop = True\n return\n\n # 如果之前已经爬过这个宝贝,skip\n tbupc = self.get_item_tbupc(item)\n if tbupc in self.already_data:\n print(\"already crawled: \" + str(tbupc))\n return\n\n price = self.get_item_price(item)\n detail = self.get_item_detail(item)\n\n if detail:\n brand = detail[0]\n category = detail[1]\n volume = detail[2]\n if brand in self.tb_brand:\n self.data.append({'category': category, 'price': price, 'volume': volume, 'tbupc': tbupc})\n print(\"宝贝\" + str(tbupc) + \", 第\" + str(len(self.data)) + \"个, \" + str(volume) + \"人购买\")\n else:\n if brand in self.gabage_brand:\n self.wrong_data.append({'tbupc': tbupc, 'reason': \"wrong brand: \" + brand})\n print(\"错误品牌: \" + brand)\n else:\n ring(15)\n if input(\"add brand: \" + brand + \" to database?\") == 'yes':\n self.insert_brand_db(brand)\n self.data.append({'category': category, 'price': price, 'volume': volume, 'tbupc': tbupc})\n print(\"宝贝\" + str(tbupc) + \", 第\" + str(len(self.data)) + \"个, \" + str(volume) + \"人购买\")\n else:\n self.insert_gabage_brand(brand)\n self.wrong_data.append({'tbupc': tbupc, 'reason': \"wrong brand: \" + brand})\n print(\"错误品牌: \" + brand)\n\n else:\n self.wrong_data.append({'tbupc': tbupc, \"reason\": \"miss detail\"})\n print(\"miss detail: \" + str(tbupc))\n\n def insert_gabage_brand(self, gabage):\n con = psycopg2.connect(self.dbinfo)\n cur = con.cursor()\n self.gabage_brand.append(gabage)\n new_tb_not_name = ';;'.join(self.gabage_brand)\n cur.execute(\"\"\"UPDATE brand SET tb_not_name=%s WHERE name=%s;\"\"\", (new_tb_not_name, self.brand))\n con.commit()\n con.close()\n\n def insert_brand_db(self, brand):\n con = psycopg2.connect(self.dbinfo)\n cur = con.cursor()\n self.tb_brand.append(brand)\n new_tb_name = \";;\".join(self.tb_brand)\n cur.execute(\"\"\"UPDATE brand SET tb_name=%s WHERE name=%s;\"\"\", (new_tb_name, self.brand))\n con.commit()\n con.close()\n\n def get_item_tbupc(self, item_xpath):\n return int(WebDriverWait(self.driver, self.wait_time).until(\n EC.presence_of_element_located(\n (By.XPATH, item_xpath + \"//div[@class='shop']/a\"))).get_attribute('data-nid'))\n\n def get_item_detail(self, item_xpath):\n\n item_link = WebDriverWait(self.driver, self.wait_time).until(\n EC.presence_of_element_located(\n (By.XPATH, item_xpath + \"//a[@class='J_ClickStat']\")))\n\n self.open_tab(item_link)\n item_detail_crawler = ItemDetailCrawler(self.driver)\n item_detail = item_detail_crawler.get_attributes()\n self.close_tab()\n return item_detail\n\n def get_item_price(self, item_xpath):\n price_text = WebDriverWait(self.driver, self.wait_time).until(\n EC.presence_of_element_located(\n (By.XPATH, item_xpath + \"//div[@class='price g_price g_price-highlight']\"))).text\n\n return float(price_text[1:])\n\n def get_item_outer_volume(self, item_xpath):\n volume_text = WebDriverWait(self.driver, self.wait_time).until(\n EC.presence_of_element_located(\n (By.XPATH, item_xpath + \"//div[@class='deal-cnt']\"))).text\n\n return self.find_number_in_string(volume_text)\n\n def find_number_in_string(self, string):\n start = 0\n end = 0\n for i in range(len(string) - 1):\n if string[i].isdigit():\n start = i\n break\n\n for i in range(len(string) - 1, -1, -1):\n if string[i].isdigit():\n end = i\n break\n\n return int(string[start:end + 1])\n\n def get_item_xpath(self, index, section):\n return \"//div[@class='items']//div[@data-index='{0}'][@data-category='{1}']\".format(index, section)\n\n def goto_next_page(self):\n print(\"next page\")\n next_page_link = self.driver.find_element_by_css_selector('.item.next')\n ActionChains(self.driver).move_to_element(next_page_link).click(next_page_link).perform()\n\n def get_pages(self):\n page_text = self.driver.find_element_by_class_name('current').find_element_by_xpath('..').text\n return page_text\n\n def goto_page(self, page_number):\n WebDriverWait(self.driver, self.wait_time).until(\n EC.presence_of_element_located(\n (By.XPATH, \"//div[@id='mainsrp-pager']//input\")\n )\n ).send_keys(page_number)\n\n WebDriverWait(self.driver, self.wait_time).until(\n EC.presence_of_element_located(\n (By.XPATH, \"//div[@id='mainsrp-pager']//div[@class='form']/span[@class='btn J_Submit']\")\n )\n ).click()\n time.sleep(5)\n\n\nif __name__ == '__main__':\n aaaa = BrandSalesCrawler(sys.argv[1], sys.argv[2])\n aaaa.start()\n","sub_path":"Pages/taobao/TBBrandSales.py","file_name":"TBBrandSales.py","file_ext":"py","file_size_in_byte":10928,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"648069902","text":"#!/usr/bin/env python3\r\n#\r\n\r\nimport sqlalchemy\r\nimport enum\r\nfrom sqlalchemy import create_engine\r\nfrom sqlalchemy.ext.declarative import declarative_base\r\nfrom sqlalchemy import Column, Integer, String, Enum\r\n\r\nengine = create_engine('mysql+pymysql://chekawa_admin:chekawa_admin@192.168.250.239/chekawa', encoding='utf-8',\r\n echo=True)\r\n\r\n# ORM基类\r\nBase = declarative_base()\r\n\r\n\r\nclass User(Base):\r\n class __EnumRole(enum.Enum):\r\n User = 1\r\n Adversary = 2\r\n ISP = 3\r\n Justice = 4\r\n Prover = 5\r\n Verifier = 6\r\n Arbitrator = 6\r\n Warden = 7\r\n\r\n __tablename__ = 'test_user'\r\n uid = Column(Integer, primary_key=True)\r\n user = Column(String(32))\r\n role = Column(Enum(__EnumRole))\r\n\r\n\r\n# 建表功能\r\nUser.metadata.create_all(engine)\r\n","sub_path":"basic_/mysql_/create.py","file_name":"create.py","file_ext":"py","file_size_in_byte":826,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"177647529","text":"from Event.Event import Event, EventType\nfrom Logic.Logic import Logic\n\n\nclass DeadForkLogic(Logic):\n def __init__(self, index, analyseKLine):\n super().__init__(index, analyseKLine)\n self._logicID = \"00002\"\n self._logicName = \"死叉逻辑\"\n self._logicDesc = \"上一个周期dif-dea>0 当前周期dif - dea<0 \"\n\n def _getBeginIndex(self):\n return self._index\n\n def _getEndIndex(self):\n return self._index\n\n def _doLogic(self, index):\n lastValue = self._analyseKLine.getDifByIndex(index - 1) - self._analyseKLine.getDeaByIndex(index - 1)\n value = self._analyseKLine.getDifByIndex(index) - self._analyseKLine.getDeaByIndex(index)\n ret = None\n if lastValue > 0 and value < 0:\n ret = Event()\n ret.setBIndex(index)\n ret.setEIndex(index)\n ret.setEventIndex(index)\n ret.setEventType(EventType.DEAD_FORK)\n ret.setEventValue(value)\n return ret\n\n def _doReverseLogic(self):\n pass\n\n\n","sub_path":"Logic/DeadForkLogic.py","file_name":"DeadForkLogic.py","file_ext":"py","file_size_in_byte":1038,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"86795644","text":"class RingBuffer:\n def __init__(self, capacity):\n self.capacity = capacity\n self.storage = []\n self.index = 0\n\n def append(self, item):\n # add item to list if storage has not met capacity\n if len(self.storage) < self.capacity: \n self.storage.append(item)\n else:\n # if capacity has been met, replace index 0 of storage with new item\n self.storage[self.index] = item\n # put index at one, so it's the next item changed\n self.index += 1\n # if index has made it to capacity/the end, set it back to 0\n if self.index == self.capacity:\n self.index = 0\n\n def get(self):\n # return storage list\n return self.storage","sub_path":"ring_buffer/ring_buffer.py","file_name":"ring_buffer.py","file_ext":"py","file_size_in_byte":752,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"97300720","text":"\"\"\"\nCopyright (c) Facebook, Inc. and its affiliates.\nAll rights reserved.\n\nThis source code is licensed under the BSD-style license found in the\nLICENSE file in the root directory of this source tree.\n\"\"\"\n\nimport fire\nfrom lte.protos.pipelined_pb2 import SerializedRyuPacket\nfrom lte.protos.pipelined_pb2_grpc import PipelinedStub\nfrom magma.common.service_registry import ServiceRegistry\nfrom ryu.lib.packet import ethernet, arp, ipv4, icmp, tcp\nfrom ryu.lib.packet.ether_types import ETH_TYPE_ARP, ETH_TYPE_IP\nfrom ryu.lib.packet.packet import Packet\nfrom termcolor import colored\n\n\nclass PacketTracerCLI:\n \"\"\"\n Packet tracer for magma OVS tables.\n Use to generate traffic from packets and send it through magma OVS tables.\n PacketTracer reports which OVS table caused a drop of the packet.\n \"\"\"\n\n def raw(self, data, imsi='001010000000013'):\n \"\"\"\n Send a packet constructed from raw bytes through the magma switch and\n display which tabled caused a drop\n (-1 if the packet wasn't dropped by any table)\n \"\"\"\n data = bytes(data)\n pkt = Packet(data)\n\n # Send the packet to a grpc service\n chan = ServiceRegistry.get_rpc_channel('pipelined',\n ServiceRegistry.LOCAL)\n client = PipelinedStub(chan)\n\n print('Sending: {}'.format(pkt))\n table_id = client.TracePacket(SerializedRyuPacket(\n pkt=data,\n imsi=imsi,\n )).table_id\n\n if table_id == -1:\n print('Successfully passed through all the tables!')\n else:\n print('Dropped by table: {}'.format(table_id))\n\n def icmp(self, imsi='001010000000013',\n src_mac='00:00:00:00:00:00', src_ip='192.168.70.2',\n dst_mac='ff:ff:ff:ff:ff:ff', dst_ip='192.168.70.3'):\n \"\"\"\n Send an ICMP packet through the magma switch and display which tabled\n caused a drop (-1 if the packet wasn't dropped by any table)\n \"\"\"\n pkt = ethernet.ethernet(src=src_mac, dst=dst_mac) / \\\n ipv4.ipv4(src=src_ip, dst=dst_ip, proto=1) / \\\n icmp.icmp()\n pkt.serialize()\n self.raw(data=pkt.data, imsi=imsi)\n\n def arp(self, imsi='001010000000013',\n src_mac='00:00:00:00:00:00', src_ip='192.168.70.2',\n dst_mac='ff:ff:ff:ff:ff:ff', dst_ip='192.168.70.3'):\n \"\"\"\n Send an ARP packet through the magma switch and display which tabled\n caused a drop (-1 if the packet wasn't dropped by any table)\n \"\"\"\n pkt = ethernet.ethernet(ethertype=ETH_TYPE_ARP,\n src=src_mac, dst=dst_mac) / \\\n arp.arp(hwtype=arp.ARP_HW_TYPE_ETHERNET, proto=ETH_TYPE_IP,\n hlen=6, plen=4,\n opcode=arp.ARP_REQUEST,\n src_mac=src_mac, src_ip=src_ip,\n dst_mac=dst_mac, dst_ip=dst_ip)\n pkt.serialize()\n self.raw(data=pkt.data, imsi=imsi)\n\n def tcp(self, imsi='001010000000013',\n src_mac='00:00:00:00:00:00', src_ip='192.168.70.2', src_port=80,\n dst_mac='ff:ff:ff:ff:ff:ff', dst_ip='192.168.70.3', dst_port=80,\n bits=tcp.TCP_SYN, seq=0, ack=0):\n \"\"\"\n Send a TCP packet through the magma switch and display which tabled\n caused a drop (-1 if the packet wasn't dropped by any table)\n \"\"\"\n pkt = ethernet.ethernet(src=src_mac, dst=dst_mac) / \\\n ipv4.ipv4(ttl=55, proto=6, src=src_ip, dst=dst_ip) / \\\n tcp.tcp(src_port=src_port, dst_port=dst_port, bits=bits,\n seq=seq, ack=ack)\n pkt.serialize()\n self.raw(data=pkt.data, imsi=imsi)\n\n def http(self, imsi='001010000000013',\n src_ip='192.168.70.2',\n dst_ip='8.8.8.8'):\n \"\"\"\n Perform (mock) an HTTP handshake and send each of the 3 packets through\n the magma switch and display which tabled caused a drop\n (-1 if the packet wasn't dropped by any table)\n \"\"\"\n self.tcp(imsi=imsi, src_ip=src_ip, dst_ip=dst_ip, bits=tcp.TCP_SYN)\n self.tcp(imsi=imsi, src_ip=dst_ip, dst_ip=src_ip, dst_port=20,\n bits=(tcp.TCP_SYN | tcp.TCP_ACK),\n seq=3833491143, ack=1)\n self.tcp(imsi=imsi, src_ip=src_ip, src_port=20, dst_ip=dst_ip,\n bits=tcp.TCP_ACK,\n seq=1, ack=3833491144)\n\n\nif __name__ == '__main__':\n cli = PacketTracerCLI()\n try:\n fire.Fire(cli)\n except Exception as e:\n print(colored('Error', 'red'), e)\n","sub_path":"lte/gateway/python/scripts/packet_tracer_cli.py","file_name":"packet_tracer_cli.py","file_ext":"py","file_size_in_byte":4613,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"353399912","text":"import subprocess\n\n\ncommand = 'awk -F \",\" \\'{print $12}\\' /Users/mathurinkasten/Downloads/69765-geotags_63021.csv'\noutput = subprocess.call(command, shell=True)\n#output = subprocess.check_output(['awk -F \",\"', '{print $12}', '/Users/mathurinkasten/Downloads/69765-geotags_63021.csv'], shell=True)\n\n\n# Taking command and checking if the values are greater than 0.02\ndef geoCheck():\n for i in output:\n print(i)\n# result = 0\n# if int(i) > 0.020:\n# result += 1\n\n\n\n","sub_path":"Geotag_check.py","file_name":"Geotag_check.py","file_ext":"py","file_size_in_byte":485,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"360421654","text":"#!/usr/bin/env python3\n\n# Copyright (c) Facebook, Inc. and its affiliates.\n# This source code is licensed under the MIT license found in the\n# LICENSE file in the root directory of this source tree.\n\n\"\"\"\nThe following is a series of functions built to work with argparse\nversion 1.1. They exist to be able to extract arguments out from\nan argparser for usage in other places. This allows Mephisto\nto be able to request the correct arguments from the frontend\nand construct valid argument strings from user input there.\n\nIt relies on underlying implementation details of argparse (ick)\nand as such is only guaranteed stable for argparse 1.1\n\"\"\"\n\nimport argparse\nfrom typing import Optional, Dict, Any, List\n\n\ndef str2bool(v):\n if isinstance(v, bool):\n return v\n if v.lower() in (\"yes\", \"true\", \"t\", \"y\", \"1\"):\n return True\n elif v.lower() in (\"no\", \"false\", \"f\", \"n\", \"0\"):\n return False\n else:\n raise argparse.ArgumentTypeError(\"Boolean value expected.\")\n\n\ndef str2none(value: str):\n \"\"\"\n If the value is a variant of `none`, return None.\n\n Otherwise, return the original value.\n \"\"\"\n if value.lower() == \"none\":\n return None\n else:\n return value\n\n\ndef str2floats(s):\n \"\"\"\n Look for single float or comma-separated floats.\n \"\"\"\n return tuple(float(f) for f in s.split(\",\"))\n\n\ndef collect_groups_recurse(group: argparse._ArgumentGroup):\n \"\"\"\n Recursively traverse an argument group, returning\n the group and all sub-groups.\n\n Ignores groups without the description attribute set\n \"\"\"\n pop_list = [group]\n ret_list: List[argparse._ArgumentGroup] = []\n while len(pop_list) > 0:\n cur_group = pop_list.pop()\n ret_list.append(cur_group)\n if len(cur_group._action_groups) > 0:\n pop_list += cur_group._action_groups.copy()\n return [g for g in ret_list if g.description is not None]\n\n\ndef get_argument_groups(\n parser: argparse.ArgumentParser,\n) -> Dict[str, argparse._ArgumentGroup]:\n \"\"\"\n Extract all of the groups from an arg parser and\n return a dict mapping from group title to group\n \"\"\"\n groups: Dict[str, Any] = {\"__NO_TITLE__\": []}\n all_action_groups: List[argparse._ArgumentGroup] = []\n for group in parser._action_groups:\n all_action_groups += collect_groups_recurse(group)\n for group in all_action_groups:\n if group.title is None:\n groups[\"__NO_TITLE__\"].append(group)\n else:\n groups[group.title] = group\n return groups\n\n\ndef get_arguments_from_group(group: argparse._ArgumentGroup) -> Dict[str, Any]:\n \"\"\"\n Extract all of the arguments from an argument group\n and return a dict mapping from argument dest to argument dict\n \"\"\"\n if group.description is None:\n return {}\n parsed_actions = {}\n for action in group._group_actions:\n action_type = action.type\n type_string = None\n if action_type is None:\n type_string = \"str\"\n elif isinstance(action_type, argparse.FileType):\n type_string = \"FileType\"\n elif hasattr(action_type, \"__name__\"):\n type_string = action_type.__name__\n else:\n type_string = \"unknown_type\"\n parsed_actions[action.dest] = {\n \"dest\": action.dest,\n \"help\": action.help,\n \"default\": action.default,\n \"type\": type_string,\n \"choices\": action.choices,\n \"option_string\": action.option_strings[0],\n \"required\": action.required,\n }\n return parsed_actions\n\n\ndef get_argument_group_dict(group: argparse._ArgumentGroup) -> Optional[Dict[str, Any]]:\n \"\"\"\n Extract an argument group (to be ready to send it to frontend)\n \"\"\"\n if group.description is None:\n return None\n return {\"desc\": group.description, \"args\": get_arguments_from_group(group)}\n\n\ndef get_extra_argument_dicts(customizable_class: Any) -> List[Dict[str, Any]]:\n \"\"\"\n Produce the argument dicts for the given customizable class\n (Blueprint, Architect, etc)\n \"\"\"\n dummy_parser = argparse.ArgumentParser()\n arg_group = dummy_parser.add_argument_group(\"test_arguments\")\n customizable_class.add_args_to_group(arg_group)\n groups = collect_groups_recurse(arg_group)\n parsed_groups = [get_argument_group_dict(g) for g in groups]\n return [g for g in parsed_groups if g is not None]\n\n\ndef parse_arg_dict(customizable_class: Any, args: Dict[str, Any]) -> Dict[str, Any]:\n \"\"\"\n Get the argparser for a class, then parse the given args using\n it. Return the dict of the finalized namespace.\n \"\"\"\n final_args = []\n # Extract the expected argument string\n for _key, val in args.items():\n final_args.append(val[\"option_string\"])\n final_args.append(val[\"value\"])\n\n # Get an argparser with the current class\n dummy_parser = argparse.ArgumentParser()\n arg_group = dummy_parser.add_argument_group(\"test_arguments\")\n customizable_class.add_args_to_group(arg_group)\n\n # Parse the namespace and return\n arg_namespace = dummy_parser.parse_args(final_args)\n return vars(arg_namespace)\n\n\ndef get_default_arg_dict(customizable_class: Any) -> Dict[str, Any]:\n \"\"\"\n Produce an opt dict containing the defaults for all\n arguments for the arguments added to the parser\n \"\"\"\n init_arg_dicts = get_extra_argument_dicts(customizable_class)\n found_opts: Dict[str, Any] = {}\n for arg_group in init_arg_dicts:\n for arg_name, arg_attributes in arg_group[\"args\"].items():\n found_opts[arg_name] = arg_attributes[\"default\"]\n filtered_opts = {k: v for k, v in found_opts.items() if v is not None}\n return filtered_opts\n","sub_path":"mephisto/core/argparse_parser.py","file_name":"argparse_parser.py","file_ext":"py","file_size_in_byte":5728,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"449576843","text":"import pandas as pd\nimport sqlalchemy\nfrom datetime import timedelta, datetime\nimport json\nimport multiprocessing\nfrom typing import List\n\nfrom programs.common.config import Config\n\n\nfrom datautils.multiprocessing import exec_function_in_parallel\nfrom datautils.http import http_get\nfrom datautils.logging import logger\nfrom datautils.pandas.db import PandasPostgresRepository\n\n\nclass DataIngestor(object):\n def __init__(self, pandas_postgres_repo: PandasPostgresRepository):\n self.pandas_postgres_repo: PandasPostgresRepository = pandas_postgres_repo\n\n def get_date_range_to_process(self) -> List[str]:\n logger.info(\"Getting date range to process...\")\n\n latest_processed_date = self._get_latest_processed_date()\n first_date_to_process = latest_processed_date + timedelta(days=1)\\\n if latest_processed_date is not None else Config.first_date_to_process\n\n last_day_to_process = datetime.now() - timedelta(days=1)\n\n return list(pd.date_range(start=first_date_to_process, end=last_day_to_process).strftime(\"%Y-%m-%d\"))\n\n def extract_exchange_rates(self, date_range: List[str]) -> pd.DataFrame:\n logger.info(\"Getting exchange rates from REST API...\")\n exchange_rates_df_list = exec_function_in_parallel(self._extract_exchange_rates_for_date,\n date_range,\n multiprocessing.cpu_count())\n return pd.concat([x for x in exchange_rates_df_list if x is not None]).reset_index(drop=True)\\\n if exchange_rates_df_list else None\n\n def persist_exchange_rates(self, exchange_rates: pd.DataFrame):\n if exchange_rates is not None:\n logger.info(\"Persisting exchange rates...\")\n sql_files_path = \"programs/sql\"\n try:\n # drop and recreate indexes for performance during bulk load\n self.pandas_postgres_repo.postgres_repo.exec_sql_from_script(f\"{sql_files_path}/indexes_drop.sql\")\n self.pandas_postgres_repo.persist_df(exchange_rates)\n self.pandas_postgres_repo.postgres_repo.exec_sql_from_script(f\"{sql_files_path}/indexes_create.sql\")\n except sqlalchemy.exc.ProgrammingError:\n raise Exception(\"Error while persisting to the DB\")\n else:\n logger.info(\"No new exchange rates to add...\")\n\n @staticmethod\n def _get_latest_processed_date() -> datetime:\n return pd.read_sql(\"\"\"\n select\n max(date_) as latest_processed_date\n from\n currency.exchange_rates;\n \"\"\", Config.conn_string).loc[0, \"latest_processed_date\"]\n\n def _extract_exchange_rates_for_date(self, date: str):\n logger.info(f\"Getting exchange rates for {date}...\")\n response = http_get(Config.source_api_endpoint + f\"/{date}\")\n try:\n return self._format_exchange_rates(response.json(), date)\n except Exception:\n raise Exception(\"Error while parsing HTTP response (format different than expected)\")\n\n @staticmethod\n def _format_exchange_rates(exchange_rates_http_response: dict, date: str) -> pd.DataFrame:\n # if API cannot find exchange rate for the day, it returns the last one available\n exchange_rates_series = pd.read_json(json.dumps(exchange_rates_http_response[\"rates\"]),\n orient=\"records\",\n typ=\"series\")\n exchange_rates_df = pd.DataFrame()\n exchange_rates_df[\"currency_code\"] = exchange_rates_series.index\n exchange_rates_df[\"exchange_rate_against_eur\"] = exchange_rates_series.values\n exchange_rates_df[\"date_\"] = date\n return exchange_rates_df\n","sub_path":"programs/data_ingestor/data_ingestor.py","file_name":"data_ingestor.py","file_ext":"py","file_size_in_byte":3806,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"617562816","text":"import asyncio\n\nimport pytest\nfrom pytest_toolbox import mktree\n\nfrom aiohttp_devtools.runserver import serve_static\n\n\n@pytest.yield_fixture\ndef cli(loop, tmpworkdir, test_client):\n asyncio.set_event_loop(loop)\n app, _, _ = serve_static(static_path=str(tmpworkdir), livereload=False)\n yield loop.run_until_complete(test_client(app))\n\n\nasync def test_simple_serve(cli, tmpworkdir):\n mktree(tmpworkdir, {\n 'foo': 'hello world',\n })\n r = await cli.get('/foo')\n assert r.status == 200\n assert r.headers['content-type'] == 'application/octet-stream'\n assert 'Access-Control-Allow-Origin' in r.headers and r.headers['Access-Control-Allow-Origin'] == '*'\n text = await r.text()\n assert text == 'hello world'\n\n\nasync def test_file_missing(cli):\n r = await cli.get('/foo')\n assert r.status == 404\n text = await r.text()\n assert '404: Not Found\\n' in text\n\n\nasync def test_html_file_livereload(loop, test_client, tmpworkdir):\n app, port, _ = serve_static(static_path=str(tmpworkdir), livereload=True)\n assert port == 8000\n cli = await test_client(app)\n mktree(tmpworkdir, {\n 'foo.html': 'hi ',\n })\n r = await cli.get('/foo')\n assert r.status == 200\n assert r.headers['content-type'] == 'text/html'\n text = await r.text()\n assert text == 'hi \\n\\n'\n r = await cli.get('/livereload.js')\n assert r.status == 200\n assert r.headers['content-type'] == 'application/javascript'\n text = await r.text()\n assert text.startswith('(function e(t,n,r){')\n\n\nasync def test_serve_index(loop, test_client, tmpworkdir):\n app, port, _ = serve_static(static_path=str(tmpworkdir), livereload=False)\n assert port == 8000\n cli = await test_client(app)\n mktree(tmpworkdir, {\n 'index.html': 'hello index ',\n })\n r = await cli.get('/')\n assert r.status == 200\n assert r.headers['content-type'] == 'text/html'\n text = await r.text()\n assert text == 'hello index '\n","sub_path":"tests/test_serve.py","file_name":"test_serve.py","file_ext":"py","file_size_in_byte":2037,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"306217089","text":"import math\nimport random\nimport json\nimport copy\n\nrandom.seed(0)\n\nSIGMOID = 0\nTANH = 1\n\ndef rand(a, b):\n return (b-a)*random.random() + a\n\ndef randNet(layer, type=SIGMOID):\n bias = []\n for l in range(0, len(layer)):\n bias.append([])\n for j in range(0, layer[l]):\n bias[l].append(rand(-0.2, 0.2))\n\n weight = []\n weight.append([])\n\n for l in range(1, len(layer)):\n weight.append([])\n for i in range(0, layer[l-1]):\n weight[l].append([])\n for j in range(0, layer[l]):\n weight[l][i].append(rand(-0.2, 0.2))\n\n return net(layer, weight, bias, type)\n\ndef load(filename):\n fr = open(filename, \"r\")\n ann = json.load(fr)\n layer = ann[0]\n weight = ann[1]\n bias = ann[2]\n type = ann[3]\n\n return net(layer, weight, bias, type)\n\nclass net:\n def __init__(self, layer, weight, bias, type=SIGMOID, filename=None):\n self.type = type\n self.layer = layer\n self.weight = weight\n self.bias = bias\n self.node = []\n for i in range(0, len(layer)):\n self.node.append([0]*layer[i])\n\n def _func(self, x):\n if self.type==SIGMOID:\n return 1/(1+math.exp(-x))\n else:\n return math.tanh(x)\n\n def process(self, input):\n if len(input)!=self.layer[0]:\n raise ValueError('wrong number of inputs')\n\n self.node[0] = input\n for l in range(1, len(self.layer)):\n self.node[l] = copy.deepcopy(self.bias[l])\n for i in range(0,self.layer[l]):\n for j in range(0,self.layer[l-1]):\n self.node[l][i] = self.node[l][i] + self.node[l-1][j] * self.weight[l][j][i]\n\n self.node[l][i] = self._func(self.node[l][i])\n\n def setWeight(self, l, j, i, w):\n self.weight[l][j][i] = w\n\n def getWeight(self, l, j, i):\n return self.weight[l][j][i]\n\n def setBias(self, l, i, b):\n self.bias[l][i] = b\n\n def getBias(self, l, i):\n return self.bias[l][i]\n\n def getNode(self, l, i):\n return self.node[l][i]\n\n def getLayer(self):\n return self.layer\n\n def getType(self):\n return self.type\n\n def getOutput(self):\n return [x for x in self.node[-1]]\n\n def save(self, filename):\n ann = [self.layer, self.weight, self.bias, self.type]\n fw = open(filename, \"w\")\n json.dump(ann, fw)\n\n def load(self, filename):\n fr = open(filename, \"r\")\n ann = json.load(fr)\n self.layer = ann[0]\n self.weight = ann[1]\n self.bias = ann[2]\n self.type = ann[3]\n","sub_path":"ann/net.py","file_name":"net.py","file_ext":"py","file_size_in_byte":2358,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"202105423","text":"# -*- coding: utf-8 -*-\n\"\"\"\n@author: Adam Eaton\n\nUsed to send notifications to the designated Slack channel regarding errors\nthat occur during runtime.\n\n\"\"\"\n\nfrom slack import WebClient\nimport traceback\nimport sys\n\nSLACK_TOKEN = open('SLACK_TOKEN.txt', 'r')\n\ndef send_notification(msg):\n client = WebClient(token=slack_token)\n \n stack = traceback.format_exception_only(sys.last_type, sys.last_value)\n error = str(stack[len(stack)-1])\n message = msg + error\n \n response = client.chat_postMessage(\n channel='#notifications',\n text=message)\n assert response[\"ok\"]\n assert response[\"message\"][\"text\"] == message\n \n return\n\n \n","sub_path":"Slack_Notify.py","file_name":"Slack_Notify.py","file_ext":"py","file_size_in_byte":671,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"592747900","text":"import discord\nfrom discord.ext import commands\nimport random\nimport giphy_client\nfrom discord.ext.commands import Bot\nfrom giphy_client.rest import ApiException\n\n\n# Create an instance of the API class\napi_instance = giphy_client.DefaultApi()\ngiphy_token = 'token' #place giphy key \napi_key = 'key' #place discord key here\n\napi_instance = giphy_client.DefaultApi()\nbot = commands.Bot(command_prefix='!')\n\n\n@bot.event\nasync def on_ready():\n print('bot is ready')\n\n@bot.event\nasync def on_member_join(member):\n print(f'{member} is here.')\n\n@bot.event\nasync def on_member_remove(member):\n print(member +\" is gone\")\n\n@bot.command(aliases =['8ball', '8BALL'])\nasync def _8Ball(ctx, *, question):\n answers = ['It is certain', 'It is decidedly so', 'Without a doubt', 'Yes – definitely', 'You may rely on it', 'As I see it, yes', 'Most likely', 'Outlook good', 'Yes Signs point to yes', 'Reply hazy', 'try again', 'Ask again later', 'Better not tell you now', 'Cannot predict now', 'Concentrate and ask again', 'Dont count on it', 'My reply is no', 'My sources say no', 'Outlook not so good', 'Very doubtful']\n await ctx.send(f\"Question: {question}\\nAnswer: {random.choice(answers)}\")\n\n@bot.command()\nasync def ping(ctx): \n await ctx.send(f'Heres my Ping : {bot.latency * 1000}')\n\n\n\n@bot.command(aliases =['send'])\nasync def send_anonymous_dm(ctx, member: discord.Member, *, content):\n for i in range(25):\n channel = await member.create_dm() \n await channel.send(content) \n\n\n\nasync def search_gifs(query):\n try:\n response = api_instance.gifs_search_get(giphy_token, query, limit=3, rating='g')\n lst = list(response.data)\n gif = random.choices(lst)\n\n return gif[0].url\n\n except ApiException as e:\n return \"Exception when calling DefaultApi->gifs_search_get: %s\\n\" % e\n\n\n@bot.command(name='gif')\nasync def gif(ctx,foo):\n\n gif = await search_gifs(foo)\n await ctx.send(gif)\n\n\n\nbot.run(api_key)\n\n","sub_path":"bot.py","file_name":"bot.py","file_ext":"py","file_size_in_byte":1977,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"13218873","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sat Jan 18 00:09:31 2020\n@author: gabriel, hugo\n\"\"\"\nfrom collections import defaultdict\nfrom tfidf import TFIDF\nimport pandas as pd\nimport numpy as np\n\nclass getScores ():\n def __init__(self):\n self.tfidf = TFIDF ()\n\n def calcScore(self, dic_query, dic_documents):\n query_data = pd.DataFrame.from_dict (dic_query, orient='index') \n cosine_results = pd.DataFrame(columns=['PMID','Score'])\n try:\n query_array = np.array(query_data[0])\n except KeyError:\n return cosine_results\n \n print(\"A organizar os dados e calcular cosine similarity\")\n for k, v in dic_documents.items():\n doc_list = []\n list_names = []\n for name, value in v: \n if name not in list_names:\n list_names.append(name)\n doc_list.append(value)\n doc_array = np.array(doc_list)\n cosine = self.tfidf.calc_cosine(query_array, doc_array)\n cosine_results = cosine_results.append({'PMID':k,'Score':cosine}, ignore_index=True)\n # print(\"A calcular a similaridade do coseno\")\n # print(len(query_data.columns))\n # for i in range(1,len(query_data.columns)):\n # column_name = query_data.columns[i]\n # cosine = self.tfidf.calc_cosine(query_data[0].to_numpy(), query_data[column_name].astype(float).to_numpy())\n return cosine_results\n \n def find_words_in_file(self, list_query):\n files = [\"file_0_to_9.txt\", \"file_A_to_F.txt\", \"file_G_to_L.txt\", \"file_M_to_S.txt\", \"file_T_to_Z.txt\"]\n numbers = \"0123456789\"\n a_to_f = 'abcdef'\n g_to_l = 'ghijkl'\n m_to_s = 'mnopqrs'\n t_to_z = 'tuvwxyz'\n # i = 0\n dic_for_words = defaultdict (list)\n for word in list_query:\n\n if any (word[0].startswith (x) for x in numbers):\n f = open (\"final_blocks/\" + files[0], \"r\")\n\n elif any (word[0].startswith (x) for x in a_to_f):\n f = open (\"final_blocks/\" + files[1], \"r\")\n\n elif any (word[0].startswith (x) for x in g_to_l):\n f = open (\"final_blocks/\" + files[2], \"r\")\n\n elif any (word[0].startswith (x) for x in m_to_s):\n f = open (\"final_blocks/\" + files[3], \"r\")\n\n elif any (word[0].startswith (x) for x in t_to_z):\n f = open (\"final_blocks/\" + files[4], \"r\")\n\n for line in f.readlines ():\n if line.startswith (word[0]):\n splited_line = line.split (\";\")\n splited_word = splited_line[0].split (\":\") # Splits the docids so we can get all the values\n if word[0] == splited_word[0]:\n for element in splited_line:\n idf = splited_line[0].split (\":\")[1] # Splits the line with ; and gets the idf value\n if element == splited_line[0]:\n pass\n elif element == \"\\n\":\n pass\n else:\n doc_id = element.split (\":\")\n if doc_id[0] in dic_for_words:\n tfidf_value = self.tfidf.calc_tfidf(float(doc_id[1]),float(idf))\n dic_for_words[doc_id[0]].append([word[0], tfidf_value])\n else:\n tfidf_value = self.tfidf.calc_tfidf (float (doc_id[1]), float (idf))\n dic_for_words[doc_id[0]] = [[word[0], tfidf_value]]\n\n for word in list_query:\n for key in dic_for_words:\n for i in range(0, len(dic_for_words[key])):\n if word[0] in dic_for_words[key][i]:\n break\n else:\n if i == len(dic_for_words[key])-1:\n dic_for_words[key].append ([word[0], 0])\n f.close ()\n return dic_for_words\n","sub_path":"Codigo/getScore.py","file_name":"getScore.py","file_ext":"py","file_size_in_byte":4159,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"119280744","text":"# Copyright (c) Microsoft Corporation.\n# Licensed under the MIT License.\n\n\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport os\nimport numpy as np\nimport pandas as pd\nfrom typing import Text, Union\nfrom sklearn.metrics import roc_auc_score, mean_squared_error\n\nimport torch\nimport torch.nn as nn\nimport torch.optim as optim\n\nfrom .pytorch_utils import count_parameters\nfrom ...model.base import Model\nfrom ...data.dataset import DatasetH\nfrom ...data.dataset.handler import DataHandlerLP\nfrom ...utils import unpack_archive_with_buffer, save_multiple_parts_file, get_or_create_path\nfrom ...log import get_module_logger\nfrom ...workflow import R\n\n\nclass DNNModelPytorch(Model):\n \"\"\"DNN Model\n\n Parameters\n ----------\n input_dim : int\n input dimension\n output_dim : int\n output dimension\n layers : tuple\n layer sizes\n lr : float\n learning rate\n lr_decay : float\n learning rate decay\n lr_decay_steps : int\n learning rate decay steps\n optimizer : str\n optimizer name\n GPU : int\n the GPU ID used for training\n \"\"\"\n\n def __init__(\n self,\n input_dim=360,\n output_dim=1,\n layers=(256,),\n lr=0.001,\n max_steps=300,\n batch_size=2000,\n early_stop_rounds=50,\n eval_steps=20,\n lr_decay=0.96,\n lr_decay_steps=100,\n optimizer=\"gd\",\n loss=\"mse\",\n GPU=0,\n seed=None,\n weight_decay=0.0,\n **kwargs\n ):\n # Set logger.\n self.logger = get_module_logger(\"DNNModelPytorch\")\n self.logger.info(\"DNN pytorch version...\")\n\n # set hyper-parameters.\n self.layers = layers\n self.lr = lr\n self.max_steps = max_steps\n self.batch_size = batch_size\n self.early_stop_rounds = early_stop_rounds\n self.eval_steps = eval_steps\n self.lr_decay = lr_decay\n self.lr_decay_steps = lr_decay_steps\n self.optimizer = optimizer.lower()\n self.loss_type = loss\n self.device = torch.device(\"cuda:%d\" % (GPU) if torch.cuda.is_available() and GPU >= 0 else \"cpu\")\n self.seed = seed\n self.weight_decay = weight_decay\n\n self.logger.info(\n \"DNN parameters setting:\"\n \"\\nlayers : {}\"\n \"\\nlr : {}\"\n \"\\nmax_steps : {}\"\n \"\\nbatch_size : {}\"\n \"\\nearly_stop_rounds : {}\"\n \"\\neval_steps : {}\"\n \"\\nlr_decay : {}\"\n \"\\nlr_decay_steps : {}\"\n \"\\noptimizer : {}\"\n \"\\nloss_type : {}\"\n \"\\neval_steps : {}\"\n \"\\nseed : {}\"\n \"\\ndevice : {}\"\n \"\\nuse_GPU : {}\"\n \"\\nweight_decay : {}\".format(\n layers,\n lr,\n max_steps,\n batch_size,\n early_stop_rounds,\n eval_steps,\n lr_decay,\n lr_decay_steps,\n optimizer,\n loss,\n eval_steps,\n seed,\n self.device,\n self.use_gpu,\n weight_decay,\n )\n )\n\n if self.seed is not None:\n np.random.seed(self.seed)\n torch.manual_seed(self.seed)\n\n if loss not in {\"mse\", \"binary\"}:\n raise NotImplementedError(\"loss {} is not supported!\".format(loss))\n self._scorer = mean_squared_error if loss == \"mse\" else roc_auc_score\n\n self.dnn_model = Net(input_dim, output_dim, layers, loss=self.loss_type)\n self.logger.info(\"model:\\n{:}\".format(self.dnn_model))\n self.logger.info(\"model size: {:.4f} MB\".format(count_parameters(self.dnn_model)))\n\n if optimizer.lower() == \"adam\":\n self.train_optimizer = optim.Adam(self.dnn_model.parameters(), lr=self.lr, weight_decay=self.weight_decay)\n elif optimizer.lower() == \"gd\":\n self.train_optimizer = optim.SGD(self.dnn_model.parameters(), lr=self.lr, weight_decay=self.weight_decay)\n else:\n raise NotImplementedError(\"optimizer {} is not supported!\".format(optimizer))\n\n # Reduce learning rate when loss has stopped decrease\n self.scheduler = torch.optim.lr_scheduler.ReduceLROnPlateau(\n self.train_optimizer,\n mode=\"min\",\n factor=0.5,\n patience=10,\n verbose=True,\n threshold=0.0001,\n threshold_mode=\"rel\",\n cooldown=0,\n min_lr=0.00001,\n eps=1e-08,\n )\n\n self.fitted = False\n self.dnn_model.to(self.device)\n\n @property\n def use_gpu(self):\n return self.device != torch.device(\"cpu\")\n\n def fit(\n self,\n dataset: DatasetH,\n evals_result=dict(),\n verbose=True,\n save_path=None,\n ):\n df_train, df_valid = dataset.prepare(\n [\"train\", \"valid\"], col_set=[\"feature\", \"label\"], data_key=DataHandlerLP.DK_L\n )\n x_train, y_train = df_train[\"feature\"], df_train[\"label\"]\n x_valid, y_valid = df_valid[\"feature\"], df_valid[\"label\"]\n try:\n wdf_train, wdf_valid = dataset.prepare([\"train\", \"valid\"], col_set=[\"weight\"], data_key=DataHandlerLP.DK_L)\n w_train, w_valid = wdf_train[\"weight\"], wdf_valid[\"weight\"]\n except KeyError as e:\n w_train = pd.DataFrame(np.ones_like(y_train.values), index=y_train.index)\n w_valid = pd.DataFrame(np.ones_like(y_valid.values), index=y_valid.index)\n\n save_path = get_or_create_path(save_path)\n stop_steps = 0\n train_loss = 0\n best_loss = np.inf\n evals_result[\"train\"] = []\n evals_result[\"valid\"] = []\n # train\n self.logger.info(\"training...\")\n self.fitted = True\n # return\n # prepare training data\n x_train_values = torch.from_numpy(x_train.values).float()\n y_train_values = torch.from_numpy(y_train.values).float()\n w_train_values = torch.from_numpy(w_train.values).float()\n train_num = y_train_values.shape[0]\n # prepare validation data\n x_val_auto = torch.from_numpy(x_valid.values).float().to(self.device)\n y_val_auto = torch.from_numpy(y_valid.values).float().to(self.device)\n w_val_auto = torch.from_numpy(w_valid.values).float().to(self.device)\n\n for step in range(self.max_steps):\n if stop_steps >= self.early_stop_rounds:\n if verbose:\n self.logger.info(\"\\tearly stop\")\n break\n loss = AverageMeter()\n self.dnn_model.train()\n self.train_optimizer.zero_grad()\n choice = np.random.choice(train_num, self.batch_size)\n x_batch_auto = x_train_values[choice].to(self.device)\n y_batch_auto = y_train_values[choice].to(self.device)\n w_batch_auto = w_train_values[choice].to(self.device)\n\n # forward\n preds = self.dnn_model(x_batch_auto)\n cur_loss = self.get_loss(preds, w_batch_auto, y_batch_auto, self.loss_type)\n cur_loss.backward()\n self.train_optimizer.step()\n loss.update(cur_loss.item())\n R.log_metrics(train_loss=loss.avg, step=step)\n\n # validation\n train_loss += loss.val\n # for evert `eval_steps` steps or at the last steps, we will evaluate the model.\n if step % self.eval_steps == 0 or step + 1 == self.max_steps:\n stop_steps += 1\n train_loss /= self.eval_steps\n\n with torch.no_grad():\n self.dnn_model.eval()\n loss_val = AverageMeter()\n\n # forward\n preds = self.dnn_model(x_val_auto)\n cur_loss_val = self.get_loss(preds, w_val_auto, y_val_auto, self.loss_type)\n loss_val.update(cur_loss_val.item())\n R.log_metrics(val_loss=loss_val.val, step=step)\n if verbose:\n self.logger.info(\n \"[Epoch {}]: train_loss {:.6f}, valid_loss {:.6f}\".format(step, train_loss, loss_val.val)\n )\n evals_result[\"train\"].append(train_loss)\n evals_result[\"valid\"].append(loss_val.val)\n if loss_val.val < best_loss:\n if verbose:\n self.logger.info(\n \"\\tvalid loss update from {:.6f} to {:.6f}, save checkpoint.\".format(\n best_loss, loss_val.val\n )\n )\n best_loss = loss_val.val\n stop_steps = 0\n torch.save(self.dnn_model.state_dict(), save_path)\n train_loss = 0\n # update learning rate\n self.scheduler.step(cur_loss_val)\n\n # restore the optimal parameters after training\n self.dnn_model.load_state_dict(torch.load(save_path))\n if self.use_gpu:\n torch.cuda.empty_cache()\n\n def get_loss(self, pred, w, target, loss_type):\n if loss_type == \"mse\":\n sqr_loss = torch.mul(pred - target, pred - target)\n loss = torch.mul(sqr_loss, w).mean()\n return loss\n elif loss_type == \"binary\":\n loss = nn.BCELoss(weight=w)\n return loss(pred, target)\n else:\n raise NotImplementedError(\"loss {} is not supported!\".format(loss_type))\n\n def predict(self, dataset: DatasetH, segment: Union[Text, slice] = \"test\"):\n if not self.fitted:\n raise ValueError(\"model is not fitted yet!\")\n x_test_pd = dataset.prepare(segment, col_set=\"feature\", data_key=DataHandlerLP.DK_I)\n x_test = torch.from_numpy(x_test_pd.values).float().to(self.device)\n self.dnn_model.eval()\n with torch.no_grad():\n preds = self.dnn_model(x_test).detach().cpu().numpy()\n return pd.Series(np.squeeze(preds), index=x_test_pd.index)\n\n def save(self, filename, **kwargs):\n with save_multiple_parts_file(filename) as model_dir:\n model_path = os.path.join(model_dir, os.path.split(model_dir)[-1])\n # Save model\n torch.save(self.dnn_model.state_dict(), model_path)\n\n def load(self, buffer, **kwargs):\n with unpack_archive_with_buffer(buffer) as model_dir:\n # Get model name\n _model_name = os.path.splitext(list(filter(lambda x: x.startswith(\"model.bin\"), os.listdir(model_dir)))[0])[\n 0\n ]\n _model_path = os.path.join(model_dir, _model_name)\n # Load model\n self.dnn_model.load_state_dict(torch.load(_model_path))\n self.fitted = True\n\n\nclass AverageMeter:\n \"\"\"Computes and stores the average and current value\"\"\"\n\n def __init__(self):\n self.reset()\n\n def reset(self):\n self.val = 0\n self.avg = 0\n self.sum = 0\n self.count = 0\n\n def update(self, val, n=1):\n self.val = val\n self.sum += val * n\n self.count += n\n self.avg = self.sum / self.count\n\n\nclass Net(nn.Module):\n def __init__(self, input_dim, output_dim, layers=(256, 512, 768, 512, 256, 128, 64), loss=\"mse\"):\n super(Net, self).__init__()\n layers = [input_dim] + list(layers)\n dnn_layers = []\n drop_input = nn.Dropout(0.05)\n dnn_layers.append(drop_input)\n for i, (input_dim, hidden_units) in enumerate(zip(layers[:-1], layers[1:])):\n fc = nn.Linear(input_dim, hidden_units)\n activation = nn.LeakyReLU(negative_slope=0.1, inplace=False)\n bn = nn.BatchNorm1d(hidden_units)\n seq = nn.Sequential(fc, bn, activation)\n dnn_layers.append(seq)\n drop_input = nn.Dropout(0.05)\n dnn_layers.append(drop_input)\n if loss == \"mse\":\n fc = nn.Linear(hidden_units, output_dim)\n dnn_layers.append(fc)\n\n elif loss == \"binary\":\n fc = nn.Linear(hidden_units, output_dim)\n sigmoid = nn.Sigmoid()\n dnn_layers.append(nn.Sequential(fc, sigmoid))\n else:\n raise NotImplementedError(\"loss {} is not supported!\".format(loss))\n # optimizer\n self.dnn_layers = nn.ModuleList(dnn_layers)\n self._weight_init()\n\n def _weight_init(self):\n for m in self.modules():\n if isinstance(m, nn.Linear):\n nn.init.kaiming_normal_(m.weight, a=0.1, mode=\"fan_in\", nonlinearity=\"leaky_relu\")\n\n def forward(self, x):\n cur_output = x\n for i, now_layer in enumerate(self.dnn_layers):\n cur_output = now_layer(cur_output)\n return cur_output\n","sub_path":"qlib/contrib/model/pytorch_nn.py","file_name":"pytorch_nn.py","file_ext":"py","file_size_in_byte":12814,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"123170752","text":"import io\nimport socket\nimport sys\nimport datetime\n\nclass WSGIServer(object):\n addr_family = socket.AF_INET\n socket_type = socket.SOCK_STREAM\n request_queue_size = 1\n\n def __init__(self, server_addr):\n self.listen_socket = listen_socket = socket.socket(\n self.addr_family,\n self.socket_type\n )\n listen_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)\n listen_socket.bind(server_addr)\n listen_socket.listen(self.request_queue_size)\n host, port = self.listen_socket.getsockname()[:2]\n self.server_name = socket.getfqdn(host)\n self.server_port = port\n\n #Return headers set by Web framework\n\n def set_app(self, application):\n self.application = application\n\n def serve_forever(self):\n listen_socket = self.listen_socket\n while True:\n self.client_connection, client_addr = listen_socket.accept()\n self.handle_one_request()\n\n def handle_one_request(self, packet_size=2048):\n request_data = self.client_connection.recv(packet_size)\n self.request_data = request_data = request_data.decode('utf-8')\n self.parse_request(request_data)\n env = self.get_env()\n result = self.application(env, self.start_response)\n self.finish_response(result)\n\n def parse_request(self, text):\n text = text.splitlines()\n extracted_data = '\\r\\n'.join((text[0], text[-1]))\n request_line = extracted_data.rstrip('\\r\\n').split()\n if len(request_line) == 4:\n (self.request_method, self.path, self.request_version, self.request_body) = request_line\n else:\n (self.request_method, self.path, self.request_version) = request_line\n self.request_body = ''\n\n def get_env(self):\n env = {\n 'wsgi.version': (1, 0),\n 'wsgi.url_scheme': 'http',\n 'wsgi.input': io.StringIO(self.request_data),\n 'wsgi.errors': sys.stderr,\n 'wsgi.multithread': False,\n 'wsgi.multiprocess': False,\n 'wsgi.run_once': False,\n 'REQUEST_METHOD': self.request_method,\n 'PATH_INFO': self.path,\n 'SERVER_NAME': self.server_name,\n 'SERVER_PORT': str(self.server_port),\n 'REQUEST_BODY': self.request_body,\n }\n return env\n\n def start_response(self, status, response_headers, exc_info=None):\n server_headers = [\n ('Date', datetime.datetime.now()),\n ('Server', ('WSGIServer 0.2'))\n ]\n self.headers_set = [status, response_headers + server_headers]\n\n\n def finish_response(self, result):\n try:\n status, response_headers = self.headers_set\n response = f'HTTP/1.1 {status}\\r\\n'\n for header in response_headers:\n response += '{0}: {1}\\r\\n'.format(*header)\n response += '\\r\\n'\n for data in result:\n response += data.decode('utf-8')\n response_bytes = response.encode()\n self.client_connection.sendall(response_bytes)\n finally:\n self.client_connection.close()\n\nSERVER_ADDR = (HOST, PORT) = '127.0.0.1', 8080\n\ndef make_server(server_addr, application):\n server = WSGIServer(server_addr)\n server.set_app(application)\n return server\n\nif __name__ == '__main__':\n default = True\n if not default:\n if len(sys.argv) < 2:\n sys.exit('Provide a WSGI application object as module:callable')\n app_path = sys.argv[1]\n else:\n app_path = 'apps:app'\n module, application = app_path.split(':')\n module = __import__(module)\n application = getattr(module, application)\n httpd = make_server(SERVER_ADDR, application)\n print(f'WSGIServer: Serving HTTP on {PORT} ...')\n httpd.serve_forever()\n","sub_path":"wsgi.py","file_name":"wsgi.py","file_ext":"py","file_size_in_byte":3909,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"402294438","text":"# Write a script that checks every character in a string given by the user\n# and keeps a count of all the vowels. When you're done counting, print out the\n# number of vowels. If the number is odd, also print \"The number of vowels is odd.\"\n#-------------------------------------------------------------------------------\n#YOUR CODE HERE\nuser_string = input(\"give me a sentence: \")\nvowels = 0\nfor char in user_string:\n if char in \"AEIOUaeiou\":\n vowels += 1\nprint(vowels)\nif vowels%2 != 0:\n print(\"The number of vowels is odd.\")\n\n#-------------------------------------------------------------------------------\n# Write a \"space count\" script that takes in user input (as them to write a sentence)\n# and counts the number of spaces (use \" \") in that sentence. Then ask them if they'd\n# like to include another sentence. If they say yes, repeat the above process. If they\n# say no, print out the space count.\n#-------------------------------------------------------------------------------\n#YOUR CODE HERE\nuser_string = input(\"give me a sentence: \")\nspaces = 0\nanswer = \"Y\"\nwhile answer == \"Y\":\n for char in user_string:\n if char == \" \":\n spaces += 1\n answer = input(\"Would you like to add a sentence? Y for yes, N for no \")\n if answer == \"Y\":\n user_string = input(\"give me a sentence: \")\nprint(spaces, \"spaces.\")\n\n#-------------------------------------------------------------------------------\n# Ask the user for two numbers, a and b. Then check whether a/b is larger, or\n# smaller than 2.5, if it is larger, print \"larger\". Otherwise print nothing.\n#-------------------------------------------------------------------------------\n#YOUR CODE HERE\n\na = float(input(\"give me a number: \"))\nb = float(input(\"give me another number: \"))\nif a/b > 2.5:\n print(\"larger\")\n#-------------------------------------------------------------------------------\n#Write a script that will keep asking the user for a number until they guess 42.\n#Once they guess 42, tell them \"goodbye\"\n#-------------------------------------------------------------------------------\n#YOUR CODE HERE\nnum = float(input(\"number: \"))\nwhile num != 42:\n num = float(input(\"number: \"))\nprint(\"goodbye\")\n#-------------------------------------------------------------------------------\n","sub_path":"Supplementary Materials/ExtraPractice for Exams/ExtraPracticeAnswers1.py","file_name":"ExtraPracticeAnswers1.py","file_ext":"py","file_size_in_byte":2292,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"409143421","text":"#!/usr/bin/env python\n\nclass Solution(object):\n def romanToInt(self, s):\n \"\"\"\n :type x: str\n :rtype: int\n \"\"\"\n symbols = {\n 'I': 1,\n 'V': 5,\n 'X': 10,\n 'L': 50,\n 'C': 100,\n 'D': 500,\n 'M': 1000,\n }\n\n values = []\n for symbol in s.upper():\n value = symbols[symbol]\n if values and values[-1] < value:\n values[-1] = -values[-1]\n values.append(value)\n return sum(values)\n\n\nif __name__ == '__main__':\n items = [\n ('I', 1),\n ('II', 2),\n ('III', 3),\n ('IV', 4),\n ('V', 5),\n ('VI', 6),\n ('VII', 7),\n ('VIII', 8),\n ('IX', 9),\n ('X', 10),\n ('XI', 11),\n ('XII', 12),\n ('XXVII', 27),\n ('LVIII', 58),\n ('MCMXCIV', 1994),\n ('DCXXI', 621),\n ]\n\n s = Solution()\n for k, v in items:\n assert(s.romanToInt(k) == v)\n\n","sub_path":"roman_to_int.py","file_name":"roman_to_int.py","file_ext":"py","file_size_in_byte":1017,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"11313182","text":"# GUI Application automation and testing library\n# Copyright (C) 2015 Intel Corporation\n# Copyright (C) 2015 airelil\n# Copyright (C) 2010 Mark Mc Mahon\n#\n# This library is free software; you can redistribute it and/or\n# modify it under the terms of the GNU Lesser General Public License\n# as published by the Free Software Foundation; either version 2.1\n# of the License, or (at your option) any later version.\n#\n# This library 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.\n# See the GNU Lesser General Public License for more details.\n#\n# You should have received a copy of the GNU Lesser General Public\n# License along with this library; if not, write to the\n# Free Software Foundation, Inc.,\n# 59 Temple Place,\n# Suite 330,\n# Boston, MA 02111-1307 USA\n\n\"Some clipboard wrapping functions - more to be added later\"\n\n__revision__ = \"$Revision$\"\n\nimport win32clipboard\n\n\n#====================================================================\ndef _get_standard_formats():\n \"Get the known formats by looking in win32clipboard\"\n formats = {}\n for define_name in win32clipboard.__dict__.keys():\n if define_name.startswith(\"CF_\"):\n formats[getattr(win32clipboard, define_name)] = define_name\n return formats\n\n# get all the formats names keyed on the value\n_standard_formats = _get_standard_formats()\n\n\n#====================================================================\ndef GetClipboardFormats():\n \"Get a list of the formats currently in the clipboard\"\n win32clipboard.OpenClipboard()\n \n available_formats = []\n format = 0\n while True:\n # retrieve the next format\n format = win32clipboard.EnumClipboardFormats(format)\n\n # stop enumerating because all formats have been\n # retrieved\n if not format:\n break\n\n available_formats.append(format)\n\n win32clipboard.CloseClipboard()\n\n return available_formats\n\n\n#====================================================================\ndef GetFormatName(format):\n \"Get the string name for a format value\"\n\n # standard formats should not be passed to GetClipboardFormatName\n if format in _standard_formats:\n return _standard_formats[format]\n\n win32clipboard.OpenClipboard()\n format_name = win32clipboard.GetClipboardFormatName(format)\n win32clipboard.CloseClipboard()\n\n return format_name\n\n\n#====================================================================\ndef GetData(format = win32clipboard.CF_UNICODETEXT):\n \"Return the data from the clipboard in the requested format\"\n if format not in GetClipboardFormats():\n raise RuntimeError(\"That format is not available\")\n\n win32clipboard.OpenClipboard()\n data = win32clipboard.GetClipboardData(format)\n win32clipboard.CloseClipboard()\n\n return data\n\n\n#====================================================================\ndef EmptyClipboard():\n win32clipboard.OpenClipboard()\n win32clipboard.EmptyClipboard()\n win32clipboard.CloseClipboard()\n\n\n#====================================================================\n# Todo: Implement setting clipboard data\n#def SetData(data, formats = [win32clipboard.CF_UNICODETEXT, ]):\n# pass\n\n\n#====================================================================\n#if __name__ == \"__main__\":\n# _unittests()\n","sub_path":"python27/1.0/Lib/site-packages/pywinauto-0.5.0-py2.7.egg/pywinauto/clipboard.py","file_name":"clipboard.py","file_ext":"py","file_size_in_byte":3433,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"426572305","text":"import baca\n\n\ndef spackle(m, grid, mask):\n \"\"\"\n Creates subdivision grid under m; subdivides sections in mask.\n \"\"\"\n\n grid = baca.sequence(grid)\n grid = grid.helianthate(1, 1)\n grid = grid.repeat_to_length(len(m.leaves))\n\n positions = [range(x[0], x[1] + 1) for x in mask]\n positions = baca.sequence(positions).flatten()\n positions = [pair[-1] if pair[0] in positions else 0 for pair in enumerate(grid)]\n # sekka.etc.transforms.subdivide(m, positions)\n","sub_path":"sekka/etc/transforms/spackle.py","file_name":"spackle.py","file_ext":"py","file_size_in_byte":482,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"522879216","text":"import json\n\nfrom django.contrib.gis.db import models\nfrom spillway.models import GeoManager, AbstractRasterStore\n\n_geom = {\n 'type': 'Polygon',\n 'coordinates': [[\n [ -64.95, -31.42 ],\n [ -61.69, -28.22 ],\n [ -61.61, -32.39 ],\n [ -64.95, -31.42 ]\n ]]\n}\n\n\nclass Location(models.Model):\n name = models.CharField(max_length=30)\n geom = models.GeometryField()\n objects = GeoManager()\n\n def __str__(self):\n return self.name\n\n @classmethod\n def create(cls, **defaults):\n data = {'name': 'Vancouver',\n 'geom': json.dumps(defaults.pop('geom', _geom))}\n data.update(**defaults)\n obj = cls(**data)\n obj.save()\n return obj\n\n\nclass RasterStore(AbstractRasterStore):\n objects = GeoManager()\n","sub_path":"tests/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":793,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"535749033","text":"import turtle\nimport random\n\ndef quasirecursive_planet(t, length, decrement, n, recurse_angle):\n t.rt(random.randint(1,359))\n recursing = True\n color=\"#\"+str(random.randint(555555,999999))\n t.color(\"black\",color)\n while recursing == True:\n if length <= 0:\n recursing = False\n else: \n t.begin_fill()\n for i in range(n):\n t.fd(length)\n t.rt(360/n) #360/n makes sure that the turning number of shape is 0\n t.end_fill()\n t.rt(recurse_angle)\n length=length-decrement\n return","sub_path":"recursive-planet.py","file_name":"recursive-planet.py","file_ext":"py","file_size_in_byte":608,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"325560057","text":"#! /usr/bin/env python\n#-* coding: utf-8 -*\n\n# __all__ = ['log', 'access_log', 'app_log', 'gen_log']\n\n# Official packages\nimport os\nimport json\nimport logging\nfrom logging.handlers import TimedRotatingFileHandler\n\n# 3rd-party Packages\nimport tornado.log\n\n# Local Packages\n\n# CONST\n\n# Class&Function Defination\nclass LogManager():\n def __init__(self):\n self.root = logging.getLogger()\n\n\n def get_base_logger(self):\n self.root.setLevel(logging._nameToLevel['DEBUG'])\n __handler_during_start__ = logging.StreamHandler()\n __handler_during_start__.setFormatter(logging.Formatter('[%(asctime)s] %(levelname)s %(filename)s %(funcName)s %(lineno)d -- %(message)s'))\n self.root.addHandler(__handler_during_start__)\n\n def get_logger(self, log_configuration):\n # 获取配置参数\n __log_level__ = logging._nameToLevel[log_configuration['level'].upper()]\n __access_log_formater__ = logging.Formatter('[%(asctime)s] %(message)s')\n __app_log_formater__ = logging.Formatter(log_configuration['format'])\n\n\n # 配置文件handler\n __access_file_handler = TimedRotatingFileHandler(\n os.path.join(log_configuration['path'], 'access.log'), when='D')\n __access_file_handler.setFormatter(__access_log_formater__)\n __app_file_handler__ = TimedRotatingFileHandler(\n os.path.join(log_configuration['path'], 'autop.log'), when='D')\n __app_file_handler__.setFormatter(__app_log_formater__)\n\n\n from tornado.log import access_log\n from tornado.log import gen_log\n from tornado.log import app_log\n root_log = self.root\n __loggers__ = [root_log, access_log, gen_log, app_log]\n\n # 设置logger级别\n list(map(lambda x: x.setLevel(__log_level__), __loggers__))\n list(map(root_log.removeHandler, root_log.handlers)) # 清空root logger的所有handler\n\n # 添加handler到logger\n access_log.addHandler(__access_file_handler)\n app_log.addHandler(__app_file_handler__)\n gen_log.addHandler(__app_file_handler__)\n root_log.addHandler(__app_file_handler__)\n\n if log_configuration['console']:\n ___console_handler_ = logging.StreamHandler()\n ___console_handler_.setFormatter(__app_log_formater__)\n # access_log.addHandler(___console_handler_)\n # app_log.addHandler(___console_handler_)\n # gen_log.addHandler(___console_handler_)\n root_log.addHandler(___console_handler_)\n # print(__loggers__)\n # [x.addHandler(___console_handler_) for x in __loggers__]\n # print(access_log.handlers)\n # print(app_log.handlers)\n # print(gen_log.handlers)\n # print(gen_log.handlers)\n\n# Logic\nif __name__ == '__main__':\n import time_generator\n # log.debug(time.strftime(\"%Y-%m-%d %H:%M:%S\"))\n","sub_path":"api/classes/log_manager.py","file_name":"log_manager.py","file_ext":"py","file_size_in_byte":2902,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"2158420","text":"#for video\nfrom imutils.video import VideoStream\nfrom imutils.video import FPS\nimport numpy as np\nimport imutils\nimport time\nimport cv2\n#for text to sppech\nfrom audioplayer import AudioPlayer\nfrom gtts import gTTS\n\nprint(\"***********************LOADING Model**********************************\")\nnet = cv2.dnn.readNet(\"yolov4.weights\", \"yolov4.cfg\")\n#save all the names in file o the list classes\nclasses = []\nwith open(\"coco.names\", \"r\") as f:\n classes = [line.strip() for line in f.readlines()]\n#get layers of the network\nlayer_names = net.getLayerNames()\n#Determine the detectionput layer names from the YOLO model \noutput_layers = [layer_names[i[0] - 1] for i in net.getUnconnectedOutLayers()]\nprint(\"***********************Model LOADED*************************************\")\n\nprint(\"[INFO] starting video stream...\")\nvs = VideoStream(src=0).start()\ntime.sleep(2.0)\nfps = FPS().start()\n# loop over the frames from the video stream\noldLabel=''\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\theight, width, channels = frame.shape\n\tframe = imutils.resize(frame, width=400)\n\t# grab the frame dimensions and convert it to a blob\n\t(h, w) = frame.shape[:2]\n\tblob = cv2.dnn.blobFromImage(frame, 1 / 255.0, (416, 416),swapRB=True, crop=False)\n\t# pass the blob through the network and obtain the detections and predictions\n\tnet.setInput(blob)\n\tdetections = net.forward(output_layers)\n\t# Showing informations on the screen\n\tclass_ids = []\n\tconfidences = []\n\tboxes = []\n\tfor detection in detections:\n\t\tfor detection_info in detection:\n\t\t\tscores = detection_info[5:]\n\t\t\tclass_id = np.argmax(scores)\n\t\t\tconfidence = scores[class_id]\n\t\t\tif confidence > 0.7:\n\t\t\t\t# Object detected\n\t\t\t\tcenter_x = int(detection_info[0] * width)\n\t\t\t\tcenter_y = int(detection_info[1] * height)\n\t\t\t\tw = int(detection_info[2] * width)\n\t\t\t\th = int(detection_info[3] * height)\n\t\t\t\t# Rectangle coordinates\n\t\t\t\tx = int(center_x - w / 2)\n\t\t\t\ty = int(center_y - h / 2)\n\t\t\t\tboxes.append([x, y, w, h])\n\t\t\t\tconfidences.append(float(confidence))\n\t\t\t\tclass_ids.append(class_id)\n\t#We use NMS function in opencv to perform Non-maximum Suppression\n\t#we give it score threshold and nms threshold as arguments.\n\tindexes = cv2.dnn.NMSBoxes(boxes, confidences, 0.5, 0.4)\n\tcolors = np.random.uniform(0, 255, size=(len(classes), 3))\n\tfor i in range(len(boxes)):\n\t\tif i in indexes:\n\t\t\tx, y, w, h = boxes[i]\n\t\t\tlabel = str(classes[class_ids[i]])\n\t\t\tcolor = colors[class_ids[i]]\n\t\t\tcv2.rectangle(frame, (x, y), (x + w, y + h), color, 2)\n\t\t\t#a = math.floor(w / 2)\n\t\t\t#cv2.line(frame, (x+a, y), (x+a ,y + h),color,1)\n\t\t\tcv2.putText(frame, label, (x, y-5),cv2.FONT_HERSHEY_SIMPLEX, 1/2, color, 2)\n\t\t\t#code for playing audio\n\t\t\tif oldLabel != label :\n\t\t\t\tobjectName = \"{} is near to you\".format(label)\n\t\t\t\tif x < 100 :\n\t\t\t\t\tobjName = \"{} is on your right\".format(label)\n\t\t\t\telif x > 300 :\n\t\t\t\t\tobjName = \"{} is on your left\".format(label)\n\t\t\t\telse :\n\t\t\t\t\tobjName = \"{} is in front of you\".format(label)\n\t\t\t\tprint(\"{}\".format(objName)) \n\t\t\t\ttts = gTTS(objName)\n\t\t\t\ttts.save('1.wav')\n\t\t\t\tsoundfile='1.wav'\n\t\t\t\tAudioPlayer(\"1.wav\").play(block=True)\n\t\t\t\toldLabel = label\n\tcv2.imshow(\"Image\",frame)\n\tkey = cv2.waitKey(1) & 0xFF\n\t# if the `q` key was pressed, break from the loop\n\tif key == ord(\"q\"):\n\t\tbreak\n\t# update the FPS counter\n\tfps.update()\n # stop the timer and display FPS information\nfps.stop()\nprint(\"[INFO] elapsed time: {:.2f}\".format(fps.elapsed()))\nprint(\"[INFO] approx. FPS: {:.2f}\".format(fps.fps()))\n# do a bit of cleanup\ncv2.destroyAllWindows()\nvs.stop()\n","sub_path":"ObjectDetection.py","file_name":"ObjectDetection.py","file_ext":"py","file_size_in_byte":3607,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"569022049","text":"from __future__ import absolute_import, print_function, unicode_literals\n\nimport re\n\nfrom validator.errorbundler import maybe_tuple, merge_description\nfrom validator.decorator import define_post_init\nfrom validator.testcases.regex import javascript as regex_javascript\nfrom validator.testcases.regex.javascript import JSRegexTest, STRING_REGEXPS\nfrom .jstypes import Global, Interfaces\n\n\nPREFERENCE_ERROR_ID = 'testcases_regex', 'string', 'preference'\n\nNETWORK_PREF_MESSAGE = {\n 'description':\n 'Changing network preferences may be dangerous, and often leads to '\n 'performance costs.',\n 'signing_help':\n 'Changes to these preferences are strongly discouraged. If at all '\n 'possible, you should remove any reference to them from '\n 'your extension. Extensions which do modify these preferences '\n 'must undergo light manual code review for at least one submission.',\n 'signing_severity': 'low',\n}\n\nBANNED_PREF_BRANCHES = [\n # Network\n ('network.proxy.autoconfig_url', {\n 'description':\n 'As many add-ons have reason to change the proxy autoconfig URL, '\n 'and only one at a time may do so without conflict, extensions '\n 'must make proxy changes using other mechanisms. Installing a '\n 'proxy filter is the recommended alternative: '\n 'https://developer.mozilla.org/en-US/docs/Mozilla/Tech/XPCOM/'\n 'Reference/Interface/nsIProtocolProxyService#registerFilter()',\n 'signing_help':\n 'Dynamic proxy configuration should be implemented via proxy '\n 'filters, as described above. This preference should not be '\n 'set, except directly by end users.',\n 'signing_severity': 'low'}),\n ('network.proxy.', NETWORK_PREF_MESSAGE),\n ('network.http.', NETWORK_PREF_MESSAGE),\n ('network.websocket.', NETWORK_PREF_MESSAGE),\n\n # Other\n ('browser.preferences.instantApply', None),\n\n ('extensions.alwaysUnpack', None),\n ('extensions.bootstrappedAddons', None),\n ('extensions.dss.', None),\n ('extensions.installCache', None),\n ('extensions.lastAppVersion', None),\n ('extensions.pendingOperations', None),\n\n ('general.useragent.', None),\n\n ('nglayout.debug.disable_xul_cache', None),\n]\n\nBANNED_PREF_REGEXPS = []\n\nPREF_REGEXPS = []\n\n\ndef add_pref_help(desc):\n \"\"\"Add help text to an error description suggesting passing the preference\n directly to preference getter functions.\n\n This is used to add additional help text to warnings about bare preference\n string literals which would not apply if said literal is being passed\n directly to a known preference API method.\"\"\"\n\n desc = desc.copy()\n for key in 'description', 'signing_help':\n if key in desc:\n desc[key] = maybe_tuple(desc[key]) + maybe_tuple(PREF_STRING_HELP)\n\n return desc\n\nPREF_STRING_HELP = (\n 'If you are reading, but not writing, this preference, please consider '\n 'passing a string literal directly to `Preferences.get()` or '\n '`nsIPrefBranch.get*Pref`.')\n\n\n@define_post_init\ndef pref_tester():\n \"\"\"Create a JSRegexTest instance based on the final values in the\n PREF_REGEXPS, BANNED_PREF_REGEXPS, and BANNED_PREF_BRANCHES definitions,\n and add most of the resulting expressions to the bare JS string\n tester as well.\"\"\"\n\n # Match exact preference names from BANNED_PREF_REGEXPS.\n PREF_REGEXPS.extend(\n (pattern,\n {'err_id': PREFERENCE_ERROR_ID,\n 'warning': 'Potentially unsafe preference branch referenced',\n 'description': 'Extensions should not alter preferences '\n 'matching /%s/.' % pattern})\n for pattern in BANNED_PREF_REGEXPS)\n\n # Match any preference under each branch in BANNED_PREF_BRANCHES.\n PREF_REGEXPS.extend(\n ('^%s' % re.escape(branch),\n merge_description(\n {'err_id': PREFERENCE_ERROR_ID,\n 'warning': 'Potentially unsafe preference branch referenced'},\n reason or ('Extensions should not alter preferences in '\n 'the `%s` preference branch' % branch)))\n for branch, reason in BANNED_PREF_BRANCHES)\n\n # Make sure our string tester has not yet been finalized.\n assert regex_javascript.string_tester is None\n STRING_REGEXPS.extend((pattern, add_pref_help(desc))\n for pattern, desc in PREF_REGEXPS)\n\n # The following patterns should only be flagged in strings we're certain\n # are being passed to preference setter functions, so add them after\n # appending the others to the literal string tests.\n PREF_REGEXPS.append(\n (r'.*password.*',\n {'err_id': PREFERENCE_ERROR_ID,\n 'warning': 'Passwords should not be stored in preferences',\n 'description': 'Storing passwords in preferences is insecure. '\n 'The Login Manager should be used instead.'}),\n )\n\n return JSRegexTest(PREF_REGEXPS)\n\n\ndef validate_pref(*args, **kw):\n return pref_tester.test(*args, **kw)\n\n\n# Preference APIs.\n\n@Global.hook(('**', 'getBranch'), 'return')\n@Global.hook(('**', 'getDefaultBranch'), 'return')\ndef create_preference_branch(this, args, callee):\n \"\"\"Creates a preference branch, which can be used for testing composed\n preference names.\"\"\"\n\n if args:\n if args[0].is_literal:\n res = this.traverser.wrap().query_interface('nsIPrefBranch')\n res.hooks['preference_branch'] = args[0].as_str()\n return res\n\n\ndef drop_pref_messages(wrapper):\n \"\"\"Drop any preference-related messages for the given wrapper, if that\n wrapper is an immediate literal that was passed as an argument, and the\n messages are on the same line as the traverser.\n\n Used to ignore preference warnings when the strings are provably being\n read rather than written, or when they're provably being written and\n have a more useful, redundant warning already.\n \"\"\"\n\n traverser = wrapper.traverser\n\n if wrapper.parse_node['type'] == 'Literal':\n for msg in wrapper.value.messages:\n if (msg['id'] == PREFERENCE_ERROR_ID and\n (msg['file'], msg['line']) == (\n traverser.filename, traverser.line)):\n traverser.err.drop_message(msg)\n\n\nnsIPrefBranch = Interfaces.hook('nsIPrefBranch')\n\n\n@nsIPrefBranch.hook('getBoolPref', 'on_call')\n@nsIPrefBranch.hook('getCharPref', 'on_call')\n@nsIPrefBranch.hook('getChildList', 'on_call')\n@nsIPrefBranch.hook('getComplexValue', 'on_call')\n@nsIPrefBranch.hook('getFloatPref', 'on_call')\n@nsIPrefBranch.hook('getIntPref', 'on_call')\n@nsIPrefBranch.hook('getPrefType', 'on_call')\n@nsIPrefBranch.hook('prefHasUserValue', 'on_call')\ndef get_preference(this, args, callee):\n \"\"\"Test get preference calls, and remove preference write warnings\n when they are not necessary.\"\"\"\n\n if args and args[0].is_clean_literal:\n drop_pref_messages(args[0])\n\n\n@nsIPrefBranch.hook('setBoolPref', 'on_call')\n@nsIPrefBranch.hook('setCharPref', 'on_call')\n@nsIPrefBranch.hook('setComplexValue', 'on_call')\n@nsIPrefBranch.hook('setIntPref', 'on_call')\n@nsIPrefBranch.hook('clearUserPref', 'on_call')\n@nsIPrefBranch.hook('deleteBranch', 'on_call')\n@nsIPrefBranch.hook('resetBranch', 'on_call')\ndef set_preference(this, args, callee):\n \"\"\"Test set preference calls against dangerous values.\"\"\"\n\n if len(args) < 1:\n return\n\n arg = args[0]\n if arg.is_literal:\n parent = getattr(callee, 'parent', this)\n pref = arg.as_str()\n\n # If we're being called on a preference branch other than the root,\n # prepend its branch name to the passed preference name.\n branch = parent.hooks.get('preference_branch')\n if branch:\n pref = branch + pref\n elif arg.is_clean_literal:\n drop_pref_messages(arg)\n\n kw = {'err_id': ('testcases_javascript_actions',\n '_call_expression', 'called_set_preference'),\n 'warning': 'Attempt to set a dangerous preference'}\n\n validate_pref(pref, traverser=this.traverser, extra=kw, wrapper=arg)\n\n\ndef default_prefs_file(traverser):\n return traverser.filename.startswith('defaults/preferences/')\n\n\n@Global.hook('pref', 'on_call', scope_filter=default_prefs_file)\n@Global.hook('user_pref', 'on_call', scope_filter=default_prefs_file)\ndef call_pref(this, args, callee):\n \"\"\"\n Handler for pref() and user_pref() calls in defaults/preferences/*.js files\n to ensure that they don't touch preferences outside of the \"extensions.\"\n branch.\n \"\"\"\n if args:\n set_preference(this, args, callee)\n return test_preference(args[0].as_str())\n\n\ndef test_preference(value):\n for branch in 'extensions.', 'services.sync.prefs.sync.extensions.':\n if value.startswith(branch) and value.rindex('.') > len(branch):\n return\n\n return ('Extensions should not alter preferences outside of the '\n \"'extensions.' preference branch. Please make sure that \"\n \"all of your extension's preferences are prefixed with \"\n \"'extensions.add-on-name.', where 'add-on-name' is a \"\n 'distinct string unique to and indicative of your add-on.')\n\n\nGlobal.hook('Preferences', {\n # From Preferences.jsm.\n # TODO: Support calls that return instances of this object which\n # operate on non-root branches.\n 'get': {'on_call': get_preference},\n 'reset': {'on_call': set_preference},\n 'resetBranch': {'on_call': set_preference},\n 'set': {'on_call': set_preference},\n})\n","sub_path":"validator/testcases/javascript/preferences.py","file_name":"preferences.py","file_ext":"py","file_size_in_byte":9609,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"596706709","text":"from django.conf.urls import url, include\nfrom . import views\n\nurlpatterns = [\n\n # /location/create/\n url(r'^create/$', views.LocationCreate.as_view()),\n\n # /location/{location_id}\n url(r'^(?P[0-9]+)/$', views.LocationDetail.as_view()),\n\n # /location/country/list/?name=\n url(r'^country/list/$', views.CountryList.as_view()),\n\n # /location/country/{country_id}/city/list/?name=\n url(r'^country/(?P[0-9]+)/city/list/$', views.CityList.as_view()),\n\n # /location/city/{city_id}/zip_code/list/\n url(r'^city/(?P[0-9]+)/zip_code/list/$', views.ZipCodeCityList.as_view()),\n\n # /location/country/{country_id}/zip_code/list/?city=\n url(r'^country/(?P[0-9]+)/zip_code/list/$', views.ZipCodeCountryList.as_view()),\n\n ##########\n # School #\n ##########\n\n url(r'', include('location.school.urls')),\n\n ########\n # Room #\n ########\n\n url(r'', include('location.room.urls')),\n]\n","sub_path":"location/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":968,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"506408672","text":"# -*- coding: utf-8 -*-\n\"\"\"PierianDx API Client ::: API client CLI/SDK for PierianDx web services\n\nUsage:\n pyriandx [options] [...]\n\nCommand:\n help Print help and exit\n version Print version and exit\n case Get a case from Case API\n list List cases from Case API, optionally apply filters to limit results\n create Accession a new case from given input JSON file\n upload Upload case files for given Case ID\n run Create sequencer run for given Case ID\n job Create informatics job for given Case ID and Run ID\n poll Poll informatics job status for given Case ID and Job ID\n report Get a report for given Case ID\n\n(See 'pyriandx help' for more information on a specific command)\n\nOptions:\n -b, --base_url=base_url Base URL.\n -u, --username=username Required if PDX_USERNAME does not exist. Usually email address.\n -p, --password=password Required if PDX_PASSWORD does not exist.\n -i, --institution=institution Required if PDX_INSTITUTION does not exist.\n -d, --debug Make output more verbose innit.\n -t, --trace Make output more and more verbose innit.\n\nEnvironment variables:\n PDX_USERNAME If defined, uses this as username for authenticating to PierianDx\n PDX_PASSWORD If defined, uses this as password for authenticating to PierianDx\n PDX_INSTITUTION If defined, uses this as institution for authenticating to PierianDx\n PDX_BASE_URL If defined, uses this as base URL for PierianDx service\n\"\"\"\nimport json\nimport logging\nimport os\nimport sys\nimport time\n\nimport coloredlogs\nimport verboselogs\nfrom docopt import docopt\n\nfrom pyriandx.client import Client\nfrom . import __version__\n\nlogger = verboselogs.VerboseLogger(__name__)\nverboselogs.add_log_level(verboselogs.SPAM, 'TRACE')\nverboselogs.install()\n\ncoloredlogs.DEFAULT_LOG_FORMAT = '%(asctime)s %(name)-12s \\t %(levelname)-8s %(message)s'\ncoloredlogs.DEFAULT_LEVEL_STYLES = dict(\n spam=dict(color='green', faint=True),\n debug=dict(color='green'),\n verbose=dict(),\n info=dict(),\n notice=dict(color='magenta'),\n warning=dict(color='yellow'),\n success=dict(color='green', bold=True),\n error=dict(color='red'),\n critical=dict(color='red', bold=True),\n)\ncoloredlogs.install()\n\nDEFAULT_BASE_URL = \"https://app.uat.pieriandx.com/cgw-api/v2.0.0\"\n\n\ndef _help(msg):\n print(msg)\n sys.exit(0)\n\n\ndef _die(msg):\n print(__doc__)\n logger.critical(f\"{msg}.\")\n sys.exit(1)\n\n\ndef _halt(msg, doc):\n print(doc)\n logger.critical(f\"{msg}.\")\n sys.exit(1)\n\n\ndef _build(global_args):\n username = global_args.get('--username', None)\n if username is None:\n username = os.getenv('PDX_USER', None) # backward compatible\n if username is None:\n username = os.getenv('PDX_USERNAME', None)\n assert username is not None, _die(\"Please provide username via -u flag or PDX_USERNAME environment variable\")\n\n pw = global_args.get('--password', None)\n if pw is None:\n pw = os.getenv('PDX_SECRET', None) # backward compatible\n if pw is None:\n pw = os.getenv('PDX_PASSWORD', None)\n assert pw is not None, _die(\"Please provide password via -p flag or PDX_PASSWORD environment variable\")\n\n inst = global_args.get('--institution', None)\n if inst is None:\n inst = os.getenv('PDX_INSTITUTION', None)\n assert inst is not None, _die(\"Please provide institution via -i flag or PDX_INSTITUTION environment variable\")\n\n base_url = global_args.get('--base_url', None)\n if base_url is None:\n base_url = os.getenv('PDX_BASE_URL', None)\n if base_url is None:\n base_url = DEFAULT_BASE_URL\n\n if \"uat\" in base_url:\n logger.warning(f\"You are working on PierianDx CGW 'UAT' environment -- {base_url}\")\n else:\n logger.notice(f\"Your working PierianDx CGW environment is -- {base_url}\")\n\n return Client(email=username, key=pw, institution=inst, base_url=base_url)\n\n\ndef _dispatch():\n global_args: dict = docopt(__doc__, sys.argv[1:], version=__version__)\n\n if global_args['--debug']:\n coloredlogs.install(level=logging.DEBUG)\n\n if global_args['--trace']:\n coloredlogs.install(level=verboselogs.SPAM)\n os.environ['DEBUG_HTTP'] = \"true\"\n\n command_argv = [global_args['']] + global_args['']\n\n logger.spam(f\"Global arguments:\\n {global_args}\")\n logger.spam(f\"Command arguments:\\n {command_argv}\")\n\n cmd = global_args['']\n if cmd == 'help':\n _help(__doc__)\n elif cmd == 'version':\n _help(__version__)\n elif cmd == 'case':\n Case(global_args, command_argv)\n elif cmd == 'list' or cmd == 'ls':\n List(global_args, command_argv)\n elif cmd == 'create':\n Create(global_args, command_argv)\n elif cmd == 'upload':\n Upload(global_args, command_argv)\n elif cmd == 'run':\n Run(global_args, command_argv)\n elif cmd == 'job':\n Job(global_args, command_argv)\n elif cmd == 'poll':\n Poll(global_args, command_argv)\n elif cmd == 'report':\n Report(global_args, command_argv)\n else:\n _die(f\"Command '{cmd}' is invalid. See 'pyriandx help'\")\n\n\nclass Command:\n\n def __int__(self):\n # sub-class should set these\n self.case_id = None\n self.client = None\n self.resources = None\n\n def get_case(self):\n assert str(self.case_id).isnumeric(), _halt(f\"Invalid Case ID: {self.case_id}\", self.__doc__)\n logger.info(f\"Get a case with ID: {self.case_id}\")\n case = self.client.get_case_info(self.case_id)\n assert case is not None and \"id\" in case, _halt(f\"Case not found for ID: {self.case_id}\", self.__doc__)\n logger.debug(f\"Found case with ID: {self.case_id}\")\n return case\n\n def upload_case_files(self):\n files = []\n for r in self.resources:\n if os.path.isdir(r):\n case_files = [f for f in os.listdir(r) if os.path.isfile(os.path.join(r, f))]\n for cf in case_files:\n files.append(os.path.join(r, cf))\n else:\n files.append(r)\n\n for f in files:\n logger.info(f\"Uploading case file: {f}\")\n self.client.upload_file(f, self.case_id)\n\n\nclass Case(Command):\n \"\"\"Usage:\n pyriandx case help\n pyriandx case [options] \n\nDescription:\n Get a case by given ID from PierianDx CGW. It returns in JSON\n format. You can further process it e.g. pretty print by pipe\n through with program such as jq.\n\nExample:\n pyriandx case 69695\n pyriandx case 69695 | jq\n \"\"\"\n\n def __init__(self, global_args, command_argv):\n args: dict = docopt(self.__doc__, argv=command_argv)\n logger.spam(f\"Case arguments:\\n {args}\")\n assert args['case'] is True, _die(\"Command mismatch: Case\")\n\n if args['help']:\n _help(self.__doc__)\n\n self.client: Client = _build(global_args)\n self.case_id = args['']\n self.case = self.get_case()\n print(json.dumps(self.case)) # print here is intended i.e. pyriandx case 1234 | jq\n\n\nclass List(Command):\n \"\"\"Usage:\n pyriandx list help\n pyriandx list [options] [...]\n\nDescription:\n List all cases by from PierianDx CGW. It returns in JSON format.\n You can further process it e.g. pretty print by pipe through with\n program such as jq. Optionally you can provide filters to limit\n the return list.\n\nAllow filters:\n id Case ID\n accessionNumber Accession Number\n panel The name of the case's panel\n dateCreatedStart Inclusive start range for the date created\n dateCreatedEnd Exclusive end range for the date created\n dateSignedOutStart Inclusive start range for the date signed out\n dateSignedOutEnd Exclusive end range for the date signed out\n\nExample:\n pyriandx list\n pyriandx list | jq\n pyriandx list id=1234\n pyriandx list accessionNumber=SBJ000123\n pyriandx list dateSignedOutStart=2020-04-01\n \"\"\"\n\n _F = ['id', 'accessionNumber', 'panel', 'dateCreatedStart',\n 'dateCreatedEnd', 'dateSignedOutStart', 'dateSignedOutEnd']\n\n def __init__(self, global_args, command_argv):\n args: dict = docopt(self.__doc__, argv=command_argv)\n logger.spam(f\"List arguments:\\n {args}\")\n assert args['list'] is True, _die(\"Command mismatch: List\")\n\n if args['help']:\n _help(self.__doc__)\n\n self.client: Client = _build(global_args)\n self.filters = args['']\n\n logger.debug(f\"Filters: {self.filters}\")\n\n params = {}\n for ftr in self.filters:\n assert '=' in ftr, _halt(f\"Invalid filter supplied: {ftr}\", self.__doc__)\n fil = ftr.split('=')\n assert fil[0] in self._F, _halt(f\"Invalid filter supplied: {ftr}\", self.__doc__)\n params.update({fil[0]: fil[1]})\n\n self.cases = self.client.list_cases(filters=params)\n print(json.dumps(self.cases)) # print here is intended i.e. pyriandx list | jq\n\n\nclass Upload(Command):\n \"\"\"Usage:\n pyriandx upload help\n pyriandx upload [options] FILES...\n\nDescription:\n FILES... can be a directory that contains list of files that\n stage to upload. Or, you can also provide individual file with\n space separated for multiple of them.\n\nExample:\n pyriandx upload 69695 path/to/SBJ00123/\n pyriandx upload 69695 file1.vcf.gz file2.vcf.gz file3.cnv\n \"\"\"\n\n def __init__(self, global_args, command_argv):\n args: dict = docopt(self.__doc__, argv=command_argv)\n logger.spam(f\"Create arguments:\\n {args}\")\n assert args['upload'] is True, _die(\"Command mismatch: Upload\")\n\n if args['help']:\n _help(self.__doc__)\n\n self.case_id = args['']\n self.resources = args['FILES']\n self.client: Client = _build(global_args)\n\n if self.get_case():\n self.upload_case_files()\n\n\nclass Create(Command):\n \"\"\"Usage:\n pyriandx create help\n pyriandx create [options] [FILES...]\n\nDescription:\n Accession a new case from given input JSON file. Optionally,\n FILES... can be a directory that contains list of files that\n stage to upload. Or, you can also provide individual file with\n space separated for multiple of them.\n\nExample:\n pyriandx create my_case.json path/to/SBJ00123/\n pyriandx create my_case.json file1.vcf.gz file2.vcf.gz file3.cnv\n \"\"\"\n\n def __init__(self, global_args, command_argv):\n args: dict = docopt(self.__doc__, argv=command_argv)\n logger.spam(f\"Create arguments:\\n {args}\")\n assert args['create'] is True, _die(\"Command mismatch: Create\")\n\n if args['help']:\n _help(self.__doc__)\n\n self.input_file = args['']\n self.resources = args['FILES']\n\n assert str(self.input_file).endswith('.json'), _halt(f\"Case input file must be in JSON format\", self.__doc__)\n assert os.path.exists(self.input_file), _halt(f\"No such file: {self.input_file}\", self.__doc__)\n\n self.client: Client = _build(global_args)\n\n logger.info(f\"Creating case from input file: {self.input_file}\")\n self.case_id = self.client.create_case(self.input_file)\n logger.success(f\"Created case with ID: {self.case_id}\")\n\n if self.resources:\n self.upload_case_files()\n\n\nclass Run(Command):\n \"\"\"Usage:\n pyriandx run help\n pyriandx run [options] \n\nDescription:\n Create sequencer run for given Case ID. Note that each invocation\n will create a sequencer run for given case. At the moment, it uses\n internal `create_sequencer_run.json` template to create a sequencer\n run. It returns Run ID. It will associate this Run ID with accession\n number of given case. You typically need at least 1 sequencer run\n after case has accessioned.\n\nExample:\n pyriandx run 69695\n > 1\n pyriandx run 69695\n > 2\n pyriandx case 69695 | jq\n pyriandx case 69695 | jq '.sequencerRuns[] | select(.runId == \"1\")'\n \"\"\"\n\n def __init__(self, global_args, command_argv):\n args: dict = docopt(self.__doc__, argv=command_argv)\n logger.spam(f\"Run arguments:\\n {args}\")\n assert args['run'] is True, _die(\"Command mismatch: Run\")\n\n if args['help']:\n _help(self.__doc__)\n\n self.client: Client = _build(global_args)\n self.case_id = args['']\n\n case = self.get_case()\n\n if case:\n self.accession_number = str(case['specimens'][0]['accessionNumber'])\n next_run_id = 1 # start from 1\n\n # check existing sequence run\n if 'sequencerRuns' in case:\n logger.info(f\"Case ID {self.case_id} has existing sequencer runs:\")\n run_ids = []\n for run in case['sequencerRuns']:\n rid = run['runId']\n logger.info(f\"\\tRun ID: {rid}, Date Created: {run['dateCreated']}\")\n if str(rid).isnumeric(): # ignore if not numeric\n run_ids.append(rid)\n if len(run_ids) > 0:\n next_run_id = int(sorted(run_ids, reverse=True)[0]) + 1 # increase serial\n\n logger.info(f\"Creating sequencer run for case {self.case_id}\")\n id_ = self.client.create_sequencer_run(self.accession_number, next_run_id)\n self.run_id = next_run_id\n logger.success(f\"Created sequencer run with ID: {self.run_id}\")\n\n\nclass Job(Command):\n \"\"\"Usage:\n pyriandx job help\n pyriandx job [options] \n\nDescription:\n Create informatics job for given Case ID and Run ID. At the moment,\n it uses internal `create_job.json` template to create analysis job.\n It returns Job ID. It will associate this informatics job with given\n case. The analysis informatics job will kick off right away for the\n given case and uploaded case files. Note that each invocation will\n create a new informatics job for given case. It also implies that\n you should create a case, a sequencer run and uploaded case files\n before running informatics analysis job.\n\nExample:\n pyriandx job 69695 1\n > 19635\n pyriandx job 69695 1\n > 19636\n pyriandx case 69695 | jq\n pyriandx case 69695 | jq '.informaticsJobs[] | select(.id == \"19635\")'\n \"\"\"\n\n def __init__(self, global_args, command_argv):\n args: dict = docopt(self.__doc__, argv=command_argv)\n logger.spam(f\"Job arguments:\\n {args}\")\n assert args['job'] is True, _die(\"Command mismatch: Job\")\n\n if args['help']:\n _help(self.__doc__)\n\n self.client: Client = _build(global_args)\n self.case_id = args['']\n self.run_id = args['']\n\n case = self.get_case()\n\n if 'caseFiles' not in case:\n logger.warning(f\"No case files found in your accessioned case. Very likely that informatics job may fail!\")\n\n assert 'sequencerRuns' in case, _halt(f\"No sequencer run found in case {self.case_id}\", self.__doc__)\n\n found = False\n for run in case['sequencerRuns']:\n if run['runId'] == self.run_id:\n found = True\n continue\n assert found is True, _halt(f\"Sequencer run ID {self.run_id} is not found in case {self.case_id}\", self.__doc__)\n\n if case:\n logger.info(f\"Creating informatics job for case {self.case_id}\")\n self.job_id = self.client.create_job(case, self.run_id)\n logger.success(f\"Created informatics job with ID: {self.job_id}\")\n\n\nclass Poll(Command):\n \"\"\"Usage:\n pyriandx poll help\n pyriandx poll [options] \n\nDescription:\n Poll informatics job for given Case ID and Job ID. Maximum wait\n time for polling job status is 30 minutes. It will timeout after\n 30 minutes. You can poll again. Alternatively, you can check the\n informatics job status in PierianDx CGW dashboard. Or, get a case\n and filter job ID on the return JSON using jq.\n\n CAVEAT: Polling job status through API is not perfected yet. Please\n do not rely on this feature for status check.\n\nExample:\n pyriandx poll 69695 19635\n pyriandx poll 69695 19636\n pyriandx case 69695 | jq\n pyriandx case 69695 | jq '.informaticsJobs[] | select(.id == \"19635\")'\n pyriandx case 69695 | jq '.informaticsJobs[] | select(.id == \"19635\") | .status'\n \"\"\"\n\n def __init__(self, global_args, command_argv):\n args: dict = docopt(self.__doc__, argv=command_argv)\n logger.spam(f\"Poll arguments:\\n {args}\")\n assert args['poll'] is True, _die(\"Command mismatch: Poll\")\n\n if args['help']:\n _help(self.__doc__)\n\n self.client: Client = _build(global_args)\n self.case_id = args['']\n self.job_id = args['']\n\n case = self.get_case()\n self.accession_number = str(case['specimens'][0]['accessionNumber'])\n logger.info(f\"Accession Number: {self.accession_number}\")\n\n self.complete = False\n self.__start_poll()\n\n def __start_poll(self):\n status = self.client.get_job_status(self.case_id, self.job_id)\n logger.info(f\"Started polling job {self.job_id} status... (Ctrl+C to exit) \")\n\n count = 0\n while status != \"complete\" and status != \"failed\" and count < 60: # wait 30 minutes max\n logger.info(f\"Status is: {status}\")\n time.sleep(30) # Check API every 30 seconds\n status = self.client.get_job_status(self.case_id, self.job_id)\n count = count + 1\n\n if count == 60:\n logger.info(\"Job polling has reached timeout 30 minutes\")\n elif status == \"complete\":\n logger.warning(f\"Informatics job {self.job_id} for case {self.case_id} with accession number \"\n f\"{self.accession_number} might have completed\")\n logger.warning(f\"You should check in CGW dashboard to make sure it has completed successfully\")\n logger.warning(f\"CLI API call does not able to differentiate `status` transition effectively at the moment\")\n self.complete = True\n elif status == \"failed\":\n logger.critical(f\"Job did not complete, status was {status}\")\n logger.info(f\"Please send support request to support@pieriandx.com with the following info:\")\n logger.info(f\"Case ID: {self.case_id}\")\n logger.info(f\"Job ID: {self.job_id}\")\n logger.info(f\"Accession Number: {self.accession_number}\")\n\n\nclass Report(Command):\n \"\"\"Usage:\n pyriandx report help\n pyriandx report [options] \n\nDescription:\n Get a report for given Case ID. It will download report in\n PDF format and save it into ./output folder.\n\n CAVEAT: Download report through API is not perfected yet.\n Please do not rely on this feature.\n\nExample:\n pyriandx report 69695\n \"\"\"\n\n def __init__(self, global_args, command_argv):\n args: dict = docopt(self.__doc__, argv=command_argv)\n logger.spam(f\"Report arguments:\\n {args}\")\n assert args['report'] is True, _die(\"Command mismatch: Report\")\n\n if args['help']:\n _help(self.__doc__)\n\n self.client: Client = _build(global_args)\n self.case_id = args['']\n\n logger.info(f\"Finding report IDs for case: {str(self.case_id)}\")\n case_ = self.get_case()\n\n if 'reports' not in case_:\n logger.info(f\"No reports available for case {self.case_id}. Try again later.\")\n else:\n logger.info(f\"Downloading report for case {self.case_id}\")\n self.client.get_report(case_, \"output\")\n logger.success(\"Report download complete. Check in ./output folder\")\n\n\ndef main():\n if len(sys.argv) == 1:\n sys.argv.append('help')\n python_version = \".\".join(map(str, sys.version_info[:3]))\n assert sys.version_info >= (3, 6), _die(f\"This tool requires Python >=3.6. Found {python_version}\")\n try:\n _dispatch()\n except KeyboardInterrupt:\n pass\n","sub_path":"pyriandx/cli.py","file_name":"cli.py","file_ext":"py","file_size_in_byte":20295,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"477950247","text":"\nfrom . import BackupHandler\nfrom ..result import CommandExecutionResult\nfrom ..entity.definition import LocalFileDefinition\nimport os\n\n\nclass LocalFileBackup(BackupHandler):\n\n def _get_definition(self) -> LocalFileDefinition:\n return self._definition\n\n def _validate(self):\n for path in self._get_definition().get_paths():\n if not os.path.exists(path):\n raise Exception('Path \"' + path + '\" does not exist')\n\n def _read(self) -> CommandExecutionResult:\n \"\"\" Read from local directory and return as a TAR-OPENSSL stream \"\"\"\n\n tar_cmd = self._get_definition().get_pack_cmd(self._get_definition().get_paths())\n\n return self._execute_command(\n self._pipe_factory.create_backup_command(tar_cmd, self._get_definition())\n )\n\n def _write(self, stream) -> CommandExecutionResult:\n \"\"\" Write to a local directory - unpack a TAR archive \"\"\"\n\n return self._execute_command(\n self._pipe_factory.create_restore_command(\n self._get_definition().get_unpack_cmd(),\n self._get_definition()\n ),\n stdin=stream\n )\n","sub_path":"client/bahub/bahubapp/handler/localfilebackup.py","file_name":"localfilebackup.py","file_ext":"py","file_size_in_byte":1169,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"16717957","text":"import logging\n\nfrom django.http import QueryDict\nfrom django.contrib.auth.models import User\nfrom django.core.exceptions import ValidationError\nfrom django.conf import settings\nfrom rest_framework import serializers\n\nfrom talentmap_api.common.common_helpers import resolve_path_to_view\nfrom talentmap_api.common.serializers import PrefetchedSerializer, StaticRepresentationField\nfrom talentmap_api.available_positions.models import AvailablePositionFavorite\nfrom talentmap_api.fsbid.services.cdo import single_cdo\nfrom talentmap_api.user_profile.models import UserProfile, SavedSearch\nfrom talentmap_api.fsbid.services.available_positions import get_available_positions\nfrom talentmap_api.fsbid.services.employee import get_employee_information\nfrom talentmap_api.fsbid.services.client import get_user_information, fsbid_clients_to_talentmap_clients\nfrom talentmap_api.fsbid.services.common import get_employee_profile_urls, get_fsbid_results\n\nlogger = logging.getLogger(__name__)\n\nCLIENTS_ROOT_V2 = settings.CLIENTS_API_V2_URL\n\n\nclass UserSerializer(PrefetchedSerializer):\n class Meta:\n model = User\n fields = [\"username\", \"email\", \"first_name\", \"last_name\"]\n\n\nclass UserProfilePublicSerializer(PrefetchedSerializer):\n first_name = serializers.CharField(source=\"user.first_name\")\n last_name = serializers.CharField(source=\"user.last_name\")\n email = serializers.CharField(source=\"user.email\")\n user_info = serializers.SerializerMethodField()\n\n def get_user_info(self, obj):\n request = self.context['request']\n try:\n jwt = request.META['HTTP_JWT']\n user = UserProfile.objects.get(user=request.user)\n return get_user_information(jwt, user.emp_id)\n except BaseException:\n return {}\n\n class Meta:\n model = UserProfile\n fields = [\"first_name\", \"last_name\", \"email\", \"user_info\"]\n\n\nclass UserProfileShortSerializer(PrefetchedSerializer):\n is_cdo = serializers.ReadOnlyField()\n username = serializers.CharField(source=\"user.username\")\n first_name = serializers.CharField(source=\"user.first_name\")\n last_name = serializers.CharField(source=\"user.last_name\")\n email = serializers.CharField(source=\"user.email\")\n initials = serializers.ReadOnlyField()\n avatar = serializers.ReadOnlyField()\n display_name = serializers.ReadOnlyField()\n\n class Meta:\n model = UserProfile\n fields = [\"username\", \"first_name\", \"last_name\", \"email\", \"is_cdo\", \"initials\", \"avatar\", \"display_name\"]\n\n\nclass ClientSerializer(PrefetchedSerializer):\n grade = StaticRepresentationField(read_only=True)\n is_cdo = serializers.ReadOnlyField()\n initials = serializers.ReadOnlyField()\n avatar = serializers.ReadOnlyField()\n display_name = serializers.ReadOnlyField()\n\n class Meta:\n model = UserProfile\n fields = [\"id\", \"skills\", \"grade\", \"is_cdo\", \"bid_statistics\", \"user\", \"initials\", \"avatar\", \"display_name\"]\n nested = {\n \"user\": {\n \"class\": UserSerializer,\n \"kwargs\": {\n \"read_only\": True\n }\n }\n }\n\n\nclass ClientDetailSerializer(ClientSerializer):\n pass\n\n\nclass UserProfileSerializer(PrefetchedSerializer):\n cdo = StaticRepresentationField(read_only=True)\n is_cdo = serializers.ReadOnlyField()\n initials = serializers.ReadOnlyField()\n avatar = serializers.ReadOnlyField()\n display_name = serializers.ReadOnlyField()\n # Use cdo_info so we don't have to break legacy CDO functionality\n cdo_info = serializers.SerializerMethodField()\n employee_info = serializers.SerializerMethodField()\n user_info = serializers.SerializerMethodField()\n current_assignment = serializers.SerializerMethodField()\n employee_profile_url = serializers.SerializerMethodField()\n\n def get_favorite_positions(self, obj):\n request = self.context['request']\n user = UserProfile.objects.get(user=request.user)\n aps = AvailablePositionFavorite.objects.filter(user=user).values_list(\"cp_id\", flat=True)\n if len(aps) > 0:\n pos_nums = ','.join(aps)\n aps = get_available_positions(QueryDict(f\"id={pos_nums}\"), request.META['HTTP_JWT'])[\"results\"]\n return ({'id': o['id']} for o in aps)\n return []\n\n def get_cdo_info(self, obj):\n request = self.context['request']\n try:\n jwt = request.META['HTTP_JWT']\n user = UserProfile.objects.get(user=request.user)\n return single_cdo(jwt, user.emp_id)\n except BaseException:\n return {}\n\n def get_employee_info(self, obj):\n request = self.context['request']\n try:\n jwt = request.META['HTTP_JWT']\n user = UserProfile.objects.get(user=request.user)\n return get_employee_information(jwt, user.emp_id)\n except BaseException:\n return {}\n\n def get_user_info(self, obj):\n request = self.context['request']\n try:\n jwt = request.META['HTTP_JWT']\n user = UserProfile.objects.get(user=request.user)\n return get_user_information(jwt, user.emp_id)\n except BaseException:\n return {}\n\n def get_current_assignment(self, obj):\n request = self.context['request']\n try:\n jwt = request.META['HTTP_JWT']\n user = UserProfile.objects.get(user=request.user)\n perdet = user.emp_id\n if not perdet:\n return {}\n\n uriCurrentAssignment = f\"?request_params.perdet_seq_num={perdet}&request_params.currentAssignmentOnly=true\"\n responseCurrentAssignment = get_fsbid_results(uriCurrentAssignment, jwt, fsbid_clients_to_talentmap_clients, None, False, CLIENTS_ROOT_V2)\n return list(responseCurrentAssignment)[0].get('current_assignment', {})\n except BaseException:\n return {}\n\n def get_employee_profile_url(self, obj):\n request = self.context['request']\n user = UserProfile.objects.get(user=request.user)\n emp_id = user.emp_id\n return get_employee_profile_urls(emp_id) or {}\n\n class Meta:\n model = UserProfile\n fields = \"__all__\"\n nested = {\n \"user\": {\n \"class\": UserSerializer,\n \"kwargs\": {\n \"read_only\": True\n }\n }\n }\n\n\nclass UserProfileWritableSerializer(PrefetchedSerializer):\n\n class Meta:\n model = UserProfile\n fields = [\"initials\", \"avatar\", \"display_name\"]\n writable_fields = ()\n\n\nclass SavedSearchSerializer(PrefetchedSerializer):\n owner = serializers.StringRelatedField(read_only=True)\n\n def save(self, **kwargs):\n super().save(owner=kwargs['owner'])\n self.instance.update_count(True, kwargs['jwt_token'])\n\n def validate(self, data):\n # We'll need the endpoint to validate our filters, so determine if our\n # datasource is an instance or a fresh object (in which case we use initial data)\n datasource = self.initial_data\n if self.instance:\n datasource = self.instance.__dict__\n\n # The endpoint to test our filters against is either the one stored, or the incoming endpoint\n endpoint = data.get(\"endpoint\", datasource.get(\"endpoint\"))\n # Likewise for the filters\n filters = data.get(\"filters\", datasource.get(\"filters\"))\n\n # Get our viewset using the endpoint\n try:\n view = resolve_path_to_view(endpoint)\n except BaseException:\n view = None\n finally:\n if not view:\n # Raise a validation error if the endpoint isn't good\n raise ValidationError(f\"Endpoint {endpoint} is not a valid API path\")\n\n \"\"\"\n Disabling validation, as the benefit is negligible and requires us to keep the\n allowed fields up to date with FSBid API.\n \"\"\"\n # Get our list of filters, and verify that the specified filters are valid\n # if hasattr(view, \"filter_class\"):\n # validate_filters_exist(filters, view.filter_class)\n # else:\n # raise ValidationError(\"Specified endpoint does not support filters\")\n\n return data\n\n class Meta:\n model = SavedSearch\n fields = \"__all__\"\n writable_fields = (\"name\", \"endpoint\", \"filters\", \"is_bureau\")\n","sub_path":"talentmap_api/user_profile/serializers.py","file_name":"serializers.py","file_ext":"py","file_size_in_byte":8419,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"115845195","text":"# -*- coding: utf-8 -*-\nimport os.path, sys\nfrom time import sleep\nfrom string import lower\nsys.path.append(os.path.join(os.path.dirname(os.path.realpath('__file__')), os.pardir))\nfrom sites.ISite import ISite\nfrom SitesConfig import SITES\nfrom sites.dantri_com_vn import dantri_com_vn\nfrom sites.vnexpress_net import vnexpress_net\nfrom sites.nongnghiep_vn import nongnghiep_vn\nfrom sites.tuoitre_vn import tuoitre_vn\nfrom sites.vietnamnet_vn import vietnamnet_vn\n\nfrom tokenizer.VnTokenizer import VnTokenizer\n\nimport pika\nimport json\nimport time\nimport logging\nimport traceback \nimport os\n\nimport json\n\n'''\n Parse URL \n Created on Oct 25, 2014\n @author: phuckx\n'''\n#import logging\n\n#FORMATER = '[%(asctime)-15s] - %(message)s'\n#FORMATER = '%(asctime)s\\t%(process)-6d\\t%(levelname)-6s\\t%(name)s\\t%(message)s'\n#logging.basicConfig(level=logging.INFO, format=FORMATER,)\nimport logging.handlers\n#formatter = logging.Formatter('%(asctime)s\\t%(process)-6d\\t%(levelname)-6s\\t%(name)s\\t%(message)s')\nformatter = logging.Formatter('%(asctime)s\\t%(name)s\\t%(message)s')\n\nlogger = logging.getLogger('CRAWLER')\n\nlogger.setLevel(logging.DEBUG)\nfile_handler = logging.handlers.RotatingFileHandler('logs/log.txt', 'a', 5000000, 5) # 5M - 5 files\nfile_handler.setFormatter(formatter)\n\nconsole_handler = logging.StreamHandler()\nconsole_handler.setLevel(logging.DEBUG)\nconsole_handler.setFormatter(formatter)\n\n#logger.addHandler(file_handler) \nlogger.addHandler(console_handler)\n\nlogging.getLogger('pika').setLevel(logging.INFO)\nlogging.getLogger('pika.frame').setLevel(logging.INFO)\n\nQUEUE_URL = 'QUEUE_URL'\n\nfrom DB import DB \n\n# Load URL --> redis\nimport redis\nrc = redis.Redis('localhost')\n\n'''\nLoad các URL đã crawler vào Redis để cache\n'''\ndef loadURL2Redis():\n '''\n query1 = \"select id, site, url from visited_url\"\n db = DB() \n cursor = db.cursor()\n logger.info(query1)\n cursor.execute(query1)\n rows = cursor.fetchall()\n for row in rows:\n site = row['site']\n url = row['url'] \n rc.sadd(site, url)\n logger.info('Load : ' + str(len(rows)) + ' to Redis')\n '''\n \n WINDOW_SIZE = 1000 # so luong item muon fetch\n WINDOW_INDEX = 0\n db = DB()\n \n logger.info('Deleting OLD keys ...')\n query1 = \"SELECT DISTINCT site FROM visited_url\"\n cursor = db.cursor()\n cursor.execute(query1)\n rows = cursor.fetchall()\n for row in rows:\n site = row['site'] \n redisKey = 'VISITED_URL_' + site\n rc.delete(redisKey)\n logger.info('deleting key: ' + redisKey)\n logger.info('Deleted OLD keys')\n logger.info('-----------------------------')\n sleep(2)\n totalUrl = 0\n while True:\n start = WINDOW_SIZE * WINDOW_INDEX + 1\n stop = WINDOW_SIZE * (WINDOW_INDEX + 1)\n # things = query.slice(start, stop).all()\n query = \"select site, url from visited_url order by id limit \" + str(start) + \", \" + str(WINDOW_SIZE)\n logger.info(query)\n #sleep(3)\n cursor = db.cursor()\n cursor.execute(query)\n rows = cursor.fetchall()\n \n # query toi khi het row \n if rows == None or len(rows) == 0:\n break\n else:\n logger.info(\"Query size: \" + str(len(rows)))\n pipe = rc.pipeline()\n pipe.multi()\n for row in rows:\n totalUrl += 1\n site = row['site']\n url = row['url']\n redisKey = 'VISITED_URL_' + site\n pipe.sadd(redisKey, url)\n pipe.execute()\n logger.info('Add : ' + str(len(rows)) + ' URL to Redis')\n WINDOW_INDEX += 1\n logger.info('Added URL --> Redis ==> OK, total URL: ' + str(totalUrl))\n \n'''\n Insert URL đã crawl được vào database và Redis\n''' \ndef insertUrl(site, url):\n query = \"insert into visited_url (site, url) values( '%s', '%s') \" % (site, url)\n logger.info(query)\n db = DB()\n cur = db.cursor()\n cur.execute(query)\n db.conn.commit()\n \n # add --> Redis \n if rc.sadd(site, url) == 0:\n logger.error(\"Insert URL \" + url + \" to Redis --> Failed\")\n \n'''\n Ktra một URL đã được crawl hay chưa bằng cách check trong Redis\n''' \ndef existURL(siteName, url):\n res = True\n if rc.sismember(siteName, url) == 0:\n res = False\n return res\n\nif __name__ == '__main__':\n \n logger.info('Load URL --> Redis')\n loadURL2Redis() \n \n \n db = DB()\n\n tokenizer = VnTokenizer()\n \n connection = pika.BlockingConnection(pika.ConnectionParameters(host='localhost'))\n channel = connection.channel()\n channel.queue_declare(queue=QUEUE_URL, durable=True)\n \n #channel.queue_declare(queue=QUEUE_ANTI_DUPLICATE, durable=True) \n # Get content from Queue \n def callback(ch, method, properties, content):\n logger.info('------------------------------------')\n try :\n #print ch\n #print method\n #print properties \n obj = json.loads(content)\n cateId = obj['cateId']\n #siteName = obj['className']\n url = obj['url']\n className = obj['className']\n initCommand = className + \"()\"\n siteObj = eval(initCommand)\n logger.info(url)\n \n termFrequencyDict = {} \n \n #TODO: check URL da dc crawl hay chua\n if not existURL(className, url):\n content = siteObj.getPageDetail(url)\n if content:\n # Tokenizing\n tokenContent = tokenizer.tokenize(content)\n words = tokenContent.split()\n filterWords = []\n for word in words: \n word = word.strip()\n #check stop word\n \n # change to lower case\n if isinstance(word, str): \n word = unicode(word, 'utf-8').lower().encode('utf-8')\n else:\n word = word.lower()\n \n if not tokenizer.isStopWord(word):\n filterWords.append(word)\n \n # check term freq\n #word = word.encode('utf-8')\n #print type(word)\n if termFrequencyDict.has_key(word):\n curCounter = termFrequencyDict.get(word)\n termFrequencyDict[word] = curCounter + 1\n else:\n termFrequencyDict[word] = 1\n #print json.dumps(termFrequency, sort_keys=True, indent=4, separators=(',', ': '))\n termFrequencyJson = json.dumps(termFrequencyDict, ensure_ascii=False, encoding='utf-8')\n #logger.info(termFrequencyJson)\n logger.info('Total word' + str(len(termFrequencyDict)))\n \n # join --> string\n filterContent = ' '.join(filterWords)\n \n #import pdb\n #pdb.set_trace()\n content = content.replace(\"'\", \"\\\\'\")\n tokenContent = tokenContent.replace(\"'\", \"\\\\'\")\n filterContent = filterContent.replace(\"'\", \"\\\\'\")\n \n query = \"INSERT INTO site_content_vnex_thethao (cate_id, site, url, content, word_1, word_2, tf) values (%s, '%s', '%s', '%s', '%s', '%s', '%s')\" % \\\n (str(cateId), className.encode('utf-8'), url.encode('utf-8'), content.encode('utf-8'), tokenContent, filterContent, termFrequencyJson)\n cur = db.cursor()\n cur.execute(query)\n db.conn.commit()\n \n # insert --> visited URL\n insertUrl(className, url)\n \n \n \n #time.sleep(SLEEP_TIME)\n time.sleep(3)\n else:\n logger.info('EXISTED URL: ' + url) \n except:\n tb = traceback.format_exc()\n logging.error(tb)\n ch.basic_ack(delivery_tag=method.delivery_tag)\n channel.basic_qos(prefetch_count=1) \n channel.basic_consume(callback, queue=QUEUE_URL)\n channel.start_consuming()\n\n #logging.info('DONE')\n ","sub_path":"Crawler2.py","file_name":"Crawler2.py","file_ext":"py","file_size_in_byte":8664,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"360500063","text":"from django.urls import path\n\nfrom . import views\n\n\napp_name = \"login\"\nurlpatterns = [\n path('',views.login,name = \"login\"),\n path('logout',views.logout,name=\"log_out\"),\n path('register',views.register,name=\"register\"),\n path('info/',views.info,name=\"info\")\n]\n","sub_path":"MedicalProgram/apps/login/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":272,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"493965425","text":"import webapp2\nfrom webapp2_extras import sessions\nimport sessions_module\nimport cgi\nimport os\nimport logging\n\nimport vk_auth\nimport json\nimport urllib2\nfrom urllib import urlencode\nimport getpass\nimport sys\nfrom google.appengine.api import urlfetch\n\nimport jinja2\n\nJINJA_ENVIRONMENT = jinja2.Environment(\n loader=jinja2.FileSystemLoader(os.path.dirname(__file__)),\n extensions=['jinja2.ext.autoescape'],\n autoescape=True)\n \nemail = 'anzhu@list.ru'\npassword = 'qwerewq'\nclient_id = \"3351788\"\nclient_secret = \"a1uRIpssyFOWHg1pNKok\"\ntoken, user_id = vk_auth.auth(email, password, client_id, \"photos\")\n#token = \"\"\nOFFSET = 5\n\ndef call_api(method, params, token):\n params.append((\"access_token\", token))\n url = \"https://api.vk.com/method/%s?%s\" % (method, urlencode(params))\n content = urlfetch.fetch(url, deadline=30).content\n result = json.loads(content)\n \n if result.has_key(\"response\"): \n return result[\"response\"]\n else: \n logging.error(result[\"error\"])\n return content \n\ndef get_token(code):\n url = \"https://oauth.vk.com/access_token?client_id=\"+client_id+\"&client_secret=\"+client_secret+\"&code=\"+code+\"&redirect_uri=oauth.vk.com/blank.html\"\n content = urlfetch.fetch(url, deadline=30).content\n result = json.loads(content)\n logging.error(result)\n return result['access_token']\n \ndef get_photos(offset):\n\n babies = call_api(\"users.search\", [(\"city\", 1), (\"sex\", 1), (\"age_from\", 18), (\"age_to\", 24), (\"has_photo\", 1), (\"count\", 5), (\"offset\", offset)], token)\n babies_count = babies[0]\n babies = babies[1:]\n \n for baby in babies[1:]:\n photos = call_api(\"photos.get\", [(\"owner_id\", baby['uid']), (\"album_id\", \"profile\"), (\"rev\", 1), (\"count\", 3)], token)\n baby['photos'] = photos\n \n return babies\n \ndef get_more_photos(offset):\n\n babies = call_api(\"users.search\", [(\"city\", 1), (\"sex\", 1), (\"age_from\", 18), (\"age_to\", 24), (\"has_photo\", 1), (\"count\", 3), (\"offset\", offset), (\"fields\", \"bdate,online\")], token)\n babies_count = babies[0]\n babies = babies[1:]\n \n for baby in babies[1:]:\n photos = call_api(\"photos.get\", [(\"owner_id\", baby['uid']), (\"album_id\", \"profile\"), (\"rev\", 1), (\"count\", 3)], token)\n baby['photos'] = photos\n \n return babies\n\n\nclass GetMore(webapp2.RequestHandler):\n def post(self):\n global OFFSET\n babies = get_more_photos(OFFSET)\n OFFSET = OFFSET + 3\n htmlel = \"\"\n for baby in babies:\n if baby.has_key('photos'):\n for photo in baby['photos']:\n htmlel = htmlel + \" \\n\"\n self.response.write(htmlel)\n \n \nclass MainPage(sessions_module.BaseSessionHandler):\n \n def get(self):\n # global token\n #code = self.request.get(\"code\")\n #access_token = self.request.get(\"access_token\")\n #url = self.request.url\n \n #logging.error(\"URL=\"+url)\n #logging.error(\"CODE=\"+code)\n #logging.error(self.session.get('access_token'))\n \n #if code:\n # self.session['access_token'] = get_token(code)\n # token = self.session.get('access_token')\n \n #if access_token:\n # self.session['access_token'] = access_token\n # token = self.session.get('access_token')\n \n \n babies = get_photos(0)\n \n template_values = {\n 'count': 0,\n 'babies': babies,\n }\n \n template = JINJA_ENVIRONMENT.get_template('index.html')\n self.response.write(template.render(template_values))\n \n \n\napplication = webapp2.WSGIApplication([\n ('/', MainPage),\n ('/token', MainPage),\n ('/more', GetMore),\n ], config = sessions_module.myconfig_dict, debug=True)","sub_path":"anzhuvk.py","file_name":"anzhuvk.py","file_ext":"py","file_size_in_byte":3868,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"181095067","text":"# coding=utf-8\n# --------------------------------------------------------------------------\n# Copyright (c) Microsoft Corporation. All rights reserved.\n# Licensed under the MIT License. See License.txt in the project root for license information.\n# Code generated by Microsoft (R) AutoRest Code Generator.\n# Changes may cause incorrect behavior and will be lost if the code is regenerated.\n# --------------------------------------------------------------------------\n\nfrom copy import deepcopy\nfrom typing import Any, Awaitable, TYPE_CHECKING\n\nfrom azure.core.rest import AsyncHttpResponse, HttpRequest\nfrom azure.mgmt.core import AsyncARMPipelineClient\n\nfrom .. import models as _models\nfrom ..._serialization import Deserializer, Serializer\nfrom ._configuration import NetworkManagementClientConfiguration\nfrom .operations import (\n ApplicationGatewaysOperations,\n ApplicationSecurityGroupsOperations,\n AvailableDelegationsOperations,\n AvailableEndpointServicesOperations,\n AvailablePrivateEndpointTypesOperations,\n AvailableResourceGroupDelegationsOperations,\n AvailableServiceAliasesOperations,\n AzureFirewallFqdnTagsOperations,\n AzureFirewallsOperations,\n BastionHostsOperations,\n BgpServiceCommunitiesOperations,\n ConnectionMonitorsOperations,\n DdosCustomPoliciesOperations,\n DdosProtectionPlansOperations,\n DefaultSecurityRulesOperations,\n ExpressRouteCircuitAuthorizationsOperations,\n ExpressRouteCircuitConnectionsOperations,\n ExpressRouteCircuitPeeringsOperations,\n ExpressRouteCircuitsOperations,\n ExpressRouteConnectionsOperations,\n ExpressRouteCrossConnectionPeeringsOperations,\n ExpressRouteCrossConnectionsOperations,\n ExpressRouteGatewaysOperations,\n ExpressRouteLinksOperations,\n ExpressRoutePortsLocationsOperations,\n ExpressRoutePortsOperations,\n ExpressRouteServiceProvidersOperations,\n FirewallPoliciesOperations,\n FirewallPolicyRuleGroupsOperations,\n HubVirtualNetworkConnectionsOperations,\n InboundNatRulesOperations,\n IpGroupsOperations,\n LoadBalancerBackendAddressPoolsOperations,\n LoadBalancerFrontendIPConfigurationsOperations,\n LoadBalancerLoadBalancingRulesOperations,\n LoadBalancerNetworkInterfacesOperations,\n LoadBalancerOutboundRulesOperations,\n LoadBalancerProbesOperations,\n LoadBalancersOperations,\n LocalNetworkGatewaysOperations,\n NatGatewaysOperations,\n NetworkInterfaceIPConfigurationsOperations,\n NetworkInterfaceLoadBalancersOperations,\n NetworkInterfaceTapConfigurationsOperations,\n NetworkInterfacesOperations,\n NetworkManagementClientOperationsMixin,\n NetworkProfilesOperations,\n NetworkSecurityGroupsOperations,\n NetworkWatchersOperations,\n Operations,\n P2SVpnGatewaysOperations,\n PacketCapturesOperations,\n PeerExpressRouteCircuitConnectionsOperations,\n PrivateEndpointsOperations,\n PrivateLinkServicesOperations,\n PublicIPAddressesOperations,\n PublicIPPrefixesOperations,\n ResourceNavigationLinksOperations,\n RouteFilterRulesOperations,\n RouteFiltersOperations,\n RouteTablesOperations,\n RoutesOperations,\n SecurityRulesOperations,\n ServiceAssociationLinksOperations,\n ServiceEndpointPoliciesOperations,\n ServiceEndpointPolicyDefinitionsOperations,\n ServiceTagsOperations,\n SubnetsOperations,\n UsagesOperations,\n VirtualHubRouteTableV2SOperations,\n VirtualHubsOperations,\n VirtualNetworkGatewayConnectionsOperations,\n VirtualNetworkGatewaysOperations,\n VirtualNetworkPeeringsOperations,\n VirtualNetworkTapsOperations,\n VirtualNetworksOperations,\n VirtualRouterPeeringsOperations,\n VirtualRoutersOperations,\n VirtualWansOperations,\n VpnConnectionsOperations,\n VpnGatewaysOperations,\n VpnLinkConnectionsOperations,\n VpnServerConfigurationsAssociatedWithVirtualWanOperations,\n VpnServerConfigurationsOperations,\n VpnSiteLinkConnectionsOperations,\n VpnSiteLinksOperations,\n VpnSitesConfigurationOperations,\n VpnSitesOperations,\n WebApplicationFirewallPoliciesOperations,\n)\n\nif TYPE_CHECKING:\n # pylint: disable=unused-import,ungrouped-imports\n from azure.core.credentials_async import AsyncTokenCredential\n\n\nclass NetworkManagementClient(\n NetworkManagementClientOperationsMixin\n): # pylint: disable=client-accepts-api-version-keyword,too-many-instance-attributes\n \"\"\"Network Client.\n\n :ivar application_gateways: ApplicationGatewaysOperations operations\n :vartype application_gateways:\n azure.mgmt.network.v2019_09_01.aio.operations.ApplicationGatewaysOperations\n :ivar application_security_groups: ApplicationSecurityGroupsOperations operations\n :vartype application_security_groups:\n azure.mgmt.network.v2019_09_01.aio.operations.ApplicationSecurityGroupsOperations\n :ivar available_delegations: AvailableDelegationsOperations operations\n :vartype available_delegations:\n azure.mgmt.network.v2019_09_01.aio.operations.AvailableDelegationsOperations\n :ivar available_resource_group_delegations: AvailableResourceGroupDelegationsOperations\n operations\n :vartype available_resource_group_delegations:\n azure.mgmt.network.v2019_09_01.aio.operations.AvailableResourceGroupDelegationsOperations\n :ivar available_service_aliases: AvailableServiceAliasesOperations operations\n :vartype available_service_aliases:\n azure.mgmt.network.v2019_09_01.aio.operations.AvailableServiceAliasesOperations\n :ivar azure_firewalls: AzureFirewallsOperations operations\n :vartype azure_firewalls:\n azure.mgmt.network.v2019_09_01.aio.operations.AzureFirewallsOperations\n :ivar azure_firewall_fqdn_tags: AzureFirewallFqdnTagsOperations operations\n :vartype azure_firewall_fqdn_tags:\n azure.mgmt.network.v2019_09_01.aio.operations.AzureFirewallFqdnTagsOperations\n :ivar bastion_hosts: BastionHostsOperations operations\n :vartype bastion_hosts: azure.mgmt.network.v2019_09_01.aio.operations.BastionHostsOperations\n :ivar ddos_custom_policies: DdosCustomPoliciesOperations operations\n :vartype ddos_custom_policies:\n azure.mgmt.network.v2019_09_01.aio.operations.DdosCustomPoliciesOperations\n :ivar ddos_protection_plans: DdosProtectionPlansOperations operations\n :vartype ddos_protection_plans:\n azure.mgmt.network.v2019_09_01.aio.operations.DdosProtectionPlansOperations\n :ivar available_endpoint_services: AvailableEndpointServicesOperations operations\n :vartype available_endpoint_services:\n azure.mgmt.network.v2019_09_01.aio.operations.AvailableEndpointServicesOperations\n :ivar express_route_circuit_authorizations: ExpressRouteCircuitAuthorizationsOperations\n operations\n :vartype express_route_circuit_authorizations:\n azure.mgmt.network.v2019_09_01.aio.operations.ExpressRouteCircuitAuthorizationsOperations\n :ivar express_route_circuit_peerings: ExpressRouteCircuitPeeringsOperations operations\n :vartype express_route_circuit_peerings:\n azure.mgmt.network.v2019_09_01.aio.operations.ExpressRouteCircuitPeeringsOperations\n :ivar express_route_circuit_connections: ExpressRouteCircuitConnectionsOperations operations\n :vartype express_route_circuit_connections:\n azure.mgmt.network.v2019_09_01.aio.operations.ExpressRouteCircuitConnectionsOperations\n :ivar peer_express_route_circuit_connections: PeerExpressRouteCircuitConnectionsOperations\n operations\n :vartype peer_express_route_circuit_connections:\n azure.mgmt.network.v2019_09_01.aio.operations.PeerExpressRouteCircuitConnectionsOperations\n :ivar express_route_circuits: ExpressRouteCircuitsOperations operations\n :vartype express_route_circuits:\n azure.mgmt.network.v2019_09_01.aio.operations.ExpressRouteCircuitsOperations\n :ivar express_route_service_providers: ExpressRouteServiceProvidersOperations operations\n :vartype express_route_service_providers:\n azure.mgmt.network.v2019_09_01.aio.operations.ExpressRouteServiceProvidersOperations\n :ivar express_route_cross_connections: ExpressRouteCrossConnectionsOperations operations\n :vartype express_route_cross_connections:\n azure.mgmt.network.v2019_09_01.aio.operations.ExpressRouteCrossConnectionsOperations\n :ivar express_route_cross_connection_peerings: ExpressRouteCrossConnectionPeeringsOperations\n operations\n :vartype express_route_cross_connection_peerings:\n azure.mgmt.network.v2019_09_01.aio.operations.ExpressRouteCrossConnectionPeeringsOperations\n :ivar express_route_gateways: ExpressRouteGatewaysOperations operations\n :vartype express_route_gateways:\n azure.mgmt.network.v2019_09_01.aio.operations.ExpressRouteGatewaysOperations\n :ivar express_route_connections: ExpressRouteConnectionsOperations operations\n :vartype express_route_connections:\n azure.mgmt.network.v2019_09_01.aio.operations.ExpressRouteConnectionsOperations\n :ivar express_route_ports_locations: ExpressRoutePortsLocationsOperations operations\n :vartype express_route_ports_locations:\n azure.mgmt.network.v2019_09_01.aio.operations.ExpressRoutePortsLocationsOperations\n :ivar express_route_ports: ExpressRoutePortsOperations operations\n :vartype express_route_ports:\n azure.mgmt.network.v2019_09_01.aio.operations.ExpressRoutePortsOperations\n :ivar express_route_links: ExpressRouteLinksOperations operations\n :vartype express_route_links:\n azure.mgmt.network.v2019_09_01.aio.operations.ExpressRouteLinksOperations\n :ivar firewall_policies: FirewallPoliciesOperations operations\n :vartype firewall_policies:\n azure.mgmt.network.v2019_09_01.aio.operations.FirewallPoliciesOperations\n :ivar firewall_policy_rule_groups: FirewallPolicyRuleGroupsOperations operations\n :vartype firewall_policy_rule_groups:\n azure.mgmt.network.v2019_09_01.aio.operations.FirewallPolicyRuleGroupsOperations\n :ivar ip_groups: IpGroupsOperations operations\n :vartype ip_groups: azure.mgmt.network.v2019_09_01.aio.operations.IpGroupsOperations\n :ivar load_balancers: LoadBalancersOperations operations\n :vartype load_balancers: azure.mgmt.network.v2019_09_01.aio.operations.LoadBalancersOperations\n :ivar load_balancer_backend_address_pools: LoadBalancerBackendAddressPoolsOperations operations\n :vartype load_balancer_backend_address_pools:\n azure.mgmt.network.v2019_09_01.aio.operations.LoadBalancerBackendAddressPoolsOperations\n :ivar load_balancer_frontend_ip_configurations: LoadBalancerFrontendIPConfigurationsOperations\n operations\n :vartype load_balancer_frontend_ip_configurations:\n azure.mgmt.network.v2019_09_01.aio.operations.LoadBalancerFrontendIPConfigurationsOperations\n :ivar inbound_nat_rules: InboundNatRulesOperations operations\n :vartype inbound_nat_rules:\n azure.mgmt.network.v2019_09_01.aio.operations.InboundNatRulesOperations\n :ivar load_balancer_load_balancing_rules: LoadBalancerLoadBalancingRulesOperations operations\n :vartype load_balancer_load_balancing_rules:\n azure.mgmt.network.v2019_09_01.aio.operations.LoadBalancerLoadBalancingRulesOperations\n :ivar load_balancer_outbound_rules: LoadBalancerOutboundRulesOperations operations\n :vartype load_balancer_outbound_rules:\n azure.mgmt.network.v2019_09_01.aio.operations.LoadBalancerOutboundRulesOperations\n :ivar load_balancer_network_interfaces: LoadBalancerNetworkInterfacesOperations operations\n :vartype load_balancer_network_interfaces:\n azure.mgmt.network.v2019_09_01.aio.operations.LoadBalancerNetworkInterfacesOperations\n :ivar load_balancer_probes: LoadBalancerProbesOperations operations\n :vartype load_balancer_probes:\n azure.mgmt.network.v2019_09_01.aio.operations.LoadBalancerProbesOperations\n :ivar nat_gateways: NatGatewaysOperations operations\n :vartype nat_gateways: azure.mgmt.network.v2019_09_01.aio.operations.NatGatewaysOperations\n :ivar network_interfaces: NetworkInterfacesOperations operations\n :vartype network_interfaces:\n azure.mgmt.network.v2019_09_01.aio.operations.NetworkInterfacesOperations\n :ivar network_interface_ip_configurations: NetworkInterfaceIPConfigurationsOperations\n operations\n :vartype network_interface_ip_configurations:\n azure.mgmt.network.v2019_09_01.aio.operations.NetworkInterfaceIPConfigurationsOperations\n :ivar network_interface_load_balancers: NetworkInterfaceLoadBalancersOperations operations\n :vartype network_interface_load_balancers:\n azure.mgmt.network.v2019_09_01.aio.operations.NetworkInterfaceLoadBalancersOperations\n :ivar network_interface_tap_configurations: NetworkInterfaceTapConfigurationsOperations\n operations\n :vartype network_interface_tap_configurations:\n azure.mgmt.network.v2019_09_01.aio.operations.NetworkInterfaceTapConfigurationsOperations\n :ivar network_profiles: NetworkProfilesOperations operations\n :vartype network_profiles:\n azure.mgmt.network.v2019_09_01.aio.operations.NetworkProfilesOperations\n :ivar network_security_groups: NetworkSecurityGroupsOperations operations\n :vartype network_security_groups:\n azure.mgmt.network.v2019_09_01.aio.operations.NetworkSecurityGroupsOperations\n :ivar security_rules: SecurityRulesOperations operations\n :vartype security_rules: azure.mgmt.network.v2019_09_01.aio.operations.SecurityRulesOperations\n :ivar default_security_rules: DefaultSecurityRulesOperations operations\n :vartype default_security_rules:\n azure.mgmt.network.v2019_09_01.aio.operations.DefaultSecurityRulesOperations\n :ivar network_watchers: NetworkWatchersOperations operations\n :vartype network_watchers:\n azure.mgmt.network.v2019_09_01.aio.operations.NetworkWatchersOperations\n :ivar packet_captures: PacketCapturesOperations operations\n :vartype packet_captures:\n azure.mgmt.network.v2019_09_01.aio.operations.PacketCapturesOperations\n :ivar connection_monitors: ConnectionMonitorsOperations operations\n :vartype connection_monitors:\n azure.mgmt.network.v2019_09_01.aio.operations.ConnectionMonitorsOperations\n :ivar operations: Operations operations\n :vartype operations: azure.mgmt.network.v2019_09_01.aio.operations.Operations\n :ivar private_endpoints: PrivateEndpointsOperations operations\n :vartype private_endpoints:\n azure.mgmt.network.v2019_09_01.aio.operations.PrivateEndpointsOperations\n :ivar available_private_endpoint_types: AvailablePrivateEndpointTypesOperations operations\n :vartype available_private_endpoint_types:\n azure.mgmt.network.v2019_09_01.aio.operations.AvailablePrivateEndpointTypesOperations\n :ivar private_link_services: PrivateLinkServicesOperations operations\n :vartype private_link_services:\n azure.mgmt.network.v2019_09_01.aio.operations.PrivateLinkServicesOperations\n :ivar public_ip_addresses: PublicIPAddressesOperations operations\n :vartype public_ip_addresses:\n azure.mgmt.network.v2019_09_01.aio.operations.PublicIPAddressesOperations\n :ivar public_ip_prefixes: PublicIPPrefixesOperations operations\n :vartype public_ip_prefixes:\n azure.mgmt.network.v2019_09_01.aio.operations.PublicIPPrefixesOperations\n :ivar route_filters: RouteFiltersOperations operations\n :vartype route_filters: azure.mgmt.network.v2019_09_01.aio.operations.RouteFiltersOperations\n :ivar route_filter_rules: RouteFilterRulesOperations operations\n :vartype route_filter_rules:\n azure.mgmt.network.v2019_09_01.aio.operations.RouteFilterRulesOperations\n :ivar route_tables: RouteTablesOperations operations\n :vartype route_tables: azure.mgmt.network.v2019_09_01.aio.operations.RouteTablesOperations\n :ivar routes: RoutesOperations operations\n :vartype routes: azure.mgmt.network.v2019_09_01.aio.operations.RoutesOperations\n :ivar bgp_service_communities: BgpServiceCommunitiesOperations operations\n :vartype bgp_service_communities:\n azure.mgmt.network.v2019_09_01.aio.operations.BgpServiceCommunitiesOperations\n :ivar service_endpoint_policies: ServiceEndpointPoliciesOperations operations\n :vartype service_endpoint_policies:\n azure.mgmt.network.v2019_09_01.aio.operations.ServiceEndpointPoliciesOperations\n :ivar service_endpoint_policy_definitions: ServiceEndpointPolicyDefinitionsOperations\n operations\n :vartype service_endpoint_policy_definitions:\n azure.mgmt.network.v2019_09_01.aio.operations.ServiceEndpointPolicyDefinitionsOperations\n :ivar service_tags: ServiceTagsOperations operations\n :vartype service_tags: azure.mgmt.network.v2019_09_01.aio.operations.ServiceTagsOperations\n :ivar usages: UsagesOperations operations\n :vartype usages: azure.mgmt.network.v2019_09_01.aio.operations.UsagesOperations\n :ivar virtual_networks: VirtualNetworksOperations operations\n :vartype virtual_networks:\n azure.mgmt.network.v2019_09_01.aio.operations.VirtualNetworksOperations\n :ivar subnets: SubnetsOperations operations\n :vartype subnets: azure.mgmt.network.v2019_09_01.aio.operations.SubnetsOperations\n :ivar resource_navigation_links: ResourceNavigationLinksOperations operations\n :vartype resource_navigation_links:\n azure.mgmt.network.v2019_09_01.aio.operations.ResourceNavigationLinksOperations\n :ivar service_association_links: ServiceAssociationLinksOperations operations\n :vartype service_association_links:\n azure.mgmt.network.v2019_09_01.aio.operations.ServiceAssociationLinksOperations\n :ivar virtual_network_peerings: VirtualNetworkPeeringsOperations operations\n :vartype virtual_network_peerings:\n azure.mgmt.network.v2019_09_01.aio.operations.VirtualNetworkPeeringsOperations\n :ivar virtual_network_gateways: VirtualNetworkGatewaysOperations operations\n :vartype virtual_network_gateways:\n azure.mgmt.network.v2019_09_01.aio.operations.VirtualNetworkGatewaysOperations\n :ivar virtual_network_gateway_connections: VirtualNetworkGatewayConnectionsOperations\n operations\n :vartype virtual_network_gateway_connections:\n azure.mgmt.network.v2019_09_01.aio.operations.VirtualNetworkGatewayConnectionsOperations\n :ivar local_network_gateways: LocalNetworkGatewaysOperations operations\n :vartype local_network_gateways:\n azure.mgmt.network.v2019_09_01.aio.operations.LocalNetworkGatewaysOperations\n :ivar virtual_network_taps: VirtualNetworkTapsOperations operations\n :vartype virtual_network_taps:\n azure.mgmt.network.v2019_09_01.aio.operations.VirtualNetworkTapsOperations\n :ivar virtual_routers: VirtualRoutersOperations operations\n :vartype virtual_routers:\n azure.mgmt.network.v2019_09_01.aio.operations.VirtualRoutersOperations\n :ivar virtual_router_peerings: VirtualRouterPeeringsOperations operations\n :vartype virtual_router_peerings:\n azure.mgmt.network.v2019_09_01.aio.operations.VirtualRouterPeeringsOperations\n :ivar virtual_wans: VirtualWansOperations operations\n :vartype virtual_wans: azure.mgmt.network.v2019_09_01.aio.operations.VirtualWansOperations\n :ivar vpn_sites: VpnSitesOperations operations\n :vartype vpn_sites: azure.mgmt.network.v2019_09_01.aio.operations.VpnSitesOperations\n :ivar vpn_site_links: VpnSiteLinksOperations operations\n :vartype vpn_site_links: azure.mgmt.network.v2019_09_01.aio.operations.VpnSiteLinksOperations\n :ivar vpn_sites_configuration: VpnSitesConfigurationOperations operations\n :vartype vpn_sites_configuration:\n azure.mgmt.network.v2019_09_01.aio.operations.VpnSitesConfigurationOperations\n :ivar vpn_server_configurations: VpnServerConfigurationsOperations operations\n :vartype vpn_server_configurations:\n azure.mgmt.network.v2019_09_01.aio.operations.VpnServerConfigurationsOperations\n :ivar virtual_hubs: VirtualHubsOperations operations\n :vartype virtual_hubs: azure.mgmt.network.v2019_09_01.aio.operations.VirtualHubsOperations\n :ivar hub_virtual_network_connections: HubVirtualNetworkConnectionsOperations operations\n :vartype hub_virtual_network_connections:\n azure.mgmt.network.v2019_09_01.aio.operations.HubVirtualNetworkConnectionsOperations\n :ivar vpn_gateways: VpnGatewaysOperations operations\n :vartype vpn_gateways: azure.mgmt.network.v2019_09_01.aio.operations.VpnGatewaysOperations\n :ivar vpn_connections: VpnConnectionsOperations operations\n :vartype vpn_connections:\n azure.mgmt.network.v2019_09_01.aio.operations.VpnConnectionsOperations\n :ivar vpn_site_link_connections: VpnSiteLinkConnectionsOperations operations\n :vartype vpn_site_link_connections:\n azure.mgmt.network.v2019_09_01.aio.operations.VpnSiteLinkConnectionsOperations\n :ivar vpn_link_connections: VpnLinkConnectionsOperations operations\n :vartype vpn_link_connections:\n azure.mgmt.network.v2019_09_01.aio.operations.VpnLinkConnectionsOperations\n :ivar p2_svpn_gateways: P2SVpnGatewaysOperations operations\n :vartype p2_svpn_gateways:\n azure.mgmt.network.v2019_09_01.aio.operations.P2SVpnGatewaysOperations\n :ivar vpn_server_configurations_associated_with_virtual_wan:\n VpnServerConfigurationsAssociatedWithVirtualWanOperations operations\n :vartype vpn_server_configurations_associated_with_virtual_wan:\n azure.mgmt.network.v2019_09_01.aio.operations.VpnServerConfigurationsAssociatedWithVirtualWanOperations\n :ivar virtual_hub_route_table_v2_s: VirtualHubRouteTableV2SOperations operations\n :vartype virtual_hub_route_table_v2_s:\n azure.mgmt.network.v2019_09_01.aio.operations.VirtualHubRouteTableV2SOperations\n :ivar web_application_firewall_policies: WebApplicationFirewallPoliciesOperations operations\n :vartype web_application_firewall_policies:\n azure.mgmt.network.v2019_09_01.aio.operations.WebApplicationFirewallPoliciesOperations\n :param credential: Credential needed for the client to connect to Azure. Required.\n :type credential: ~azure.core.credentials_async.AsyncTokenCredential\n :param subscription_id: The subscription credentials which uniquely identify the Microsoft\n Azure subscription. The subscription ID forms part of the URI for every service call. Required.\n :type subscription_id: str\n :param base_url: Service URL. Default value is \"https://management.azure.com\".\n :type base_url: str\n :keyword int polling_interval: Default waiting time between two polls for LRO operations if no\n Retry-After header is present.\n \"\"\"\n\n def __init__(\n self,\n credential: \"AsyncTokenCredential\",\n subscription_id: str,\n base_url: str = \"https://management.azure.com\",\n **kwargs: Any\n ) -> None:\n self._config = NetworkManagementClientConfiguration(\n credential=credential, subscription_id=subscription_id, **kwargs\n )\n self._client: AsyncARMPipelineClient = AsyncARMPipelineClient(base_url=base_url, config=self._config, **kwargs)\n\n client_models = {k: v for k, v in _models.__dict__.items() if isinstance(v, type)}\n self._serialize = Serializer(client_models)\n self._deserialize = Deserializer(client_models)\n self._serialize.client_side_validation = False\n self.application_gateways = ApplicationGatewaysOperations(\n self._client, self._config, self._serialize, self._deserialize, \"2019-09-01\"\n )\n self.application_security_groups = ApplicationSecurityGroupsOperations(\n self._client, self._config, self._serialize, self._deserialize, \"2019-09-01\"\n )\n self.available_delegations = AvailableDelegationsOperations(\n self._client, self._config, self._serialize, self._deserialize, \"2019-09-01\"\n )\n self.available_resource_group_delegations = AvailableResourceGroupDelegationsOperations(\n self._client, self._config, self._serialize, self._deserialize, \"2019-09-01\"\n )\n self.available_service_aliases = AvailableServiceAliasesOperations(\n self._client, self._config, self._serialize, self._deserialize, \"2019-09-01\"\n )\n self.azure_firewalls = AzureFirewallsOperations(\n self._client, self._config, self._serialize, self._deserialize, \"2019-09-01\"\n )\n self.azure_firewall_fqdn_tags = AzureFirewallFqdnTagsOperations(\n self._client, self._config, self._serialize, self._deserialize, \"2019-09-01\"\n )\n self.bastion_hosts = BastionHostsOperations(\n self._client, self._config, self._serialize, self._deserialize, \"2019-09-01\"\n )\n self.ddos_custom_policies = DdosCustomPoliciesOperations(\n self._client, self._config, self._serialize, self._deserialize, \"2019-09-01\"\n )\n self.ddos_protection_plans = DdosProtectionPlansOperations(\n self._client, self._config, self._serialize, self._deserialize, \"2019-09-01\"\n )\n self.available_endpoint_services = AvailableEndpointServicesOperations(\n self._client, self._config, self._serialize, self._deserialize, \"2019-09-01\"\n )\n self.express_route_circuit_authorizations = ExpressRouteCircuitAuthorizationsOperations(\n self._client, self._config, self._serialize, self._deserialize, \"2019-09-01\"\n )\n self.express_route_circuit_peerings = ExpressRouteCircuitPeeringsOperations(\n self._client, self._config, self._serialize, self._deserialize, \"2019-09-01\"\n )\n self.express_route_circuit_connections = ExpressRouteCircuitConnectionsOperations(\n self._client, self._config, self._serialize, self._deserialize, \"2019-09-01\"\n )\n self.peer_express_route_circuit_connections = PeerExpressRouteCircuitConnectionsOperations(\n self._client, self._config, self._serialize, self._deserialize, \"2019-09-01\"\n )\n self.express_route_circuits = ExpressRouteCircuitsOperations(\n self._client, self._config, self._serialize, self._deserialize, \"2019-09-01\"\n )\n self.express_route_service_providers = ExpressRouteServiceProvidersOperations(\n self._client, self._config, self._serialize, self._deserialize, \"2019-09-01\"\n )\n self.express_route_cross_connections = ExpressRouteCrossConnectionsOperations(\n self._client, self._config, self._serialize, self._deserialize, \"2019-09-01\"\n )\n self.express_route_cross_connection_peerings = ExpressRouteCrossConnectionPeeringsOperations(\n self._client, self._config, self._serialize, self._deserialize, \"2019-09-01\"\n )\n self.express_route_gateways = ExpressRouteGatewaysOperations(\n self._client, self._config, self._serialize, self._deserialize, \"2019-09-01\"\n )\n self.express_route_connections = ExpressRouteConnectionsOperations(\n self._client, self._config, self._serialize, self._deserialize, \"2019-09-01\"\n )\n self.express_route_ports_locations = ExpressRoutePortsLocationsOperations(\n self._client, self._config, self._serialize, self._deserialize, \"2019-09-01\"\n )\n self.express_route_ports = ExpressRoutePortsOperations(\n self._client, self._config, self._serialize, self._deserialize, \"2019-09-01\"\n )\n self.express_route_links = ExpressRouteLinksOperations(\n self._client, self._config, self._serialize, self._deserialize, \"2019-09-01\"\n )\n self.firewall_policies = FirewallPoliciesOperations(\n self._client, self._config, self._serialize, self._deserialize, \"2019-09-01\"\n )\n self.firewall_policy_rule_groups = FirewallPolicyRuleGroupsOperations(\n self._client, self._config, self._serialize, self._deserialize, \"2019-09-01\"\n )\n self.ip_groups = IpGroupsOperations(\n self._client, self._config, self._serialize, self._deserialize, \"2019-09-01\"\n )\n self.load_balancers = LoadBalancersOperations(\n self._client, self._config, self._serialize, self._deserialize, \"2019-09-01\"\n )\n self.load_balancer_backend_address_pools = LoadBalancerBackendAddressPoolsOperations(\n self._client, self._config, self._serialize, self._deserialize, \"2019-09-01\"\n )\n self.load_balancer_frontend_ip_configurations = LoadBalancerFrontendIPConfigurationsOperations(\n self._client, self._config, self._serialize, self._deserialize, \"2019-09-01\"\n )\n self.inbound_nat_rules = InboundNatRulesOperations(\n self._client, self._config, self._serialize, self._deserialize, \"2019-09-01\"\n )\n self.load_balancer_load_balancing_rules = LoadBalancerLoadBalancingRulesOperations(\n self._client, self._config, self._serialize, self._deserialize, \"2019-09-01\"\n )\n self.load_balancer_outbound_rules = LoadBalancerOutboundRulesOperations(\n self._client, self._config, self._serialize, self._deserialize, \"2019-09-01\"\n )\n self.load_balancer_network_interfaces = LoadBalancerNetworkInterfacesOperations(\n self._client, self._config, self._serialize, self._deserialize, \"2019-09-01\"\n )\n self.load_balancer_probes = LoadBalancerProbesOperations(\n self._client, self._config, self._serialize, self._deserialize, \"2019-09-01\"\n )\n self.nat_gateways = NatGatewaysOperations(\n self._client, self._config, self._serialize, self._deserialize, \"2019-09-01\"\n )\n self.network_interfaces = NetworkInterfacesOperations(\n self._client, self._config, self._serialize, self._deserialize, \"2019-09-01\"\n )\n self.network_interface_ip_configurations = NetworkInterfaceIPConfigurationsOperations(\n self._client, self._config, self._serialize, self._deserialize, \"2019-09-01\"\n )\n self.network_interface_load_balancers = NetworkInterfaceLoadBalancersOperations(\n self._client, self._config, self._serialize, self._deserialize, \"2019-09-01\"\n )\n self.network_interface_tap_configurations = NetworkInterfaceTapConfigurationsOperations(\n self._client, self._config, self._serialize, self._deserialize, \"2019-09-01\"\n )\n self.network_profiles = NetworkProfilesOperations(\n self._client, self._config, self._serialize, self._deserialize, \"2019-09-01\"\n )\n self.network_security_groups = NetworkSecurityGroupsOperations(\n self._client, self._config, self._serialize, self._deserialize, \"2019-09-01\"\n )\n self.security_rules = SecurityRulesOperations(\n self._client, self._config, self._serialize, self._deserialize, \"2019-09-01\"\n )\n self.default_security_rules = DefaultSecurityRulesOperations(\n self._client, self._config, self._serialize, self._deserialize, \"2019-09-01\"\n )\n self.network_watchers = NetworkWatchersOperations(\n self._client, self._config, self._serialize, self._deserialize, \"2019-09-01\"\n )\n self.packet_captures = PacketCapturesOperations(\n self._client, self._config, self._serialize, self._deserialize, \"2019-09-01\"\n )\n self.connection_monitors = ConnectionMonitorsOperations(\n self._client, self._config, self._serialize, self._deserialize, \"2019-09-01\"\n )\n self.operations = Operations(self._client, self._config, self._serialize, self._deserialize, \"2019-09-01\")\n self.private_endpoints = PrivateEndpointsOperations(\n self._client, self._config, self._serialize, self._deserialize, \"2019-09-01\"\n )\n self.available_private_endpoint_types = AvailablePrivateEndpointTypesOperations(\n self._client, self._config, self._serialize, self._deserialize, \"2019-09-01\"\n )\n self.private_link_services = PrivateLinkServicesOperations(\n self._client, self._config, self._serialize, self._deserialize, \"2019-09-01\"\n )\n self.public_ip_addresses = PublicIPAddressesOperations(\n self._client, self._config, self._serialize, self._deserialize, \"2019-09-01\"\n )\n self.public_ip_prefixes = PublicIPPrefixesOperations(\n self._client, self._config, self._serialize, self._deserialize, \"2019-09-01\"\n )\n self.route_filters = RouteFiltersOperations(\n self._client, self._config, self._serialize, self._deserialize, \"2019-09-01\"\n )\n self.route_filter_rules = RouteFilterRulesOperations(\n self._client, self._config, self._serialize, self._deserialize, \"2019-09-01\"\n )\n self.route_tables = RouteTablesOperations(\n self._client, self._config, self._serialize, self._deserialize, \"2019-09-01\"\n )\n self.routes = RoutesOperations(self._client, self._config, self._serialize, self._deserialize, \"2019-09-01\")\n self.bgp_service_communities = BgpServiceCommunitiesOperations(\n self._client, self._config, self._serialize, self._deserialize, \"2019-09-01\"\n )\n self.service_endpoint_policies = ServiceEndpointPoliciesOperations(\n self._client, self._config, self._serialize, self._deserialize, \"2019-09-01\"\n )\n self.service_endpoint_policy_definitions = ServiceEndpointPolicyDefinitionsOperations(\n self._client, self._config, self._serialize, self._deserialize, \"2019-09-01\"\n )\n self.service_tags = ServiceTagsOperations(\n self._client, self._config, self._serialize, self._deserialize, \"2019-09-01\"\n )\n self.usages = UsagesOperations(self._client, self._config, self._serialize, self._deserialize, \"2019-09-01\")\n self.virtual_networks = VirtualNetworksOperations(\n self._client, self._config, self._serialize, self._deserialize, \"2019-09-01\"\n )\n self.subnets = SubnetsOperations(self._client, self._config, self._serialize, self._deserialize, \"2019-09-01\")\n self.resource_navigation_links = ResourceNavigationLinksOperations(\n self._client, self._config, self._serialize, self._deserialize, \"2019-09-01\"\n )\n self.service_association_links = ServiceAssociationLinksOperations(\n self._client, self._config, self._serialize, self._deserialize, \"2019-09-01\"\n )\n self.virtual_network_peerings = VirtualNetworkPeeringsOperations(\n self._client, self._config, self._serialize, self._deserialize, \"2019-09-01\"\n )\n self.virtual_network_gateways = VirtualNetworkGatewaysOperations(\n self._client, self._config, self._serialize, self._deserialize, \"2019-09-01\"\n )\n self.virtual_network_gateway_connections = VirtualNetworkGatewayConnectionsOperations(\n self._client, self._config, self._serialize, self._deserialize, \"2019-09-01\"\n )\n self.local_network_gateways = LocalNetworkGatewaysOperations(\n self._client, self._config, self._serialize, self._deserialize, \"2019-09-01\"\n )\n self.virtual_network_taps = VirtualNetworkTapsOperations(\n self._client, self._config, self._serialize, self._deserialize, \"2019-09-01\"\n )\n self.virtual_routers = VirtualRoutersOperations(\n self._client, self._config, self._serialize, self._deserialize, \"2019-09-01\"\n )\n self.virtual_router_peerings = VirtualRouterPeeringsOperations(\n self._client, self._config, self._serialize, self._deserialize, \"2019-09-01\"\n )\n self.virtual_wans = VirtualWansOperations(\n self._client, self._config, self._serialize, self._deserialize, \"2019-09-01\"\n )\n self.vpn_sites = VpnSitesOperations(\n self._client, self._config, self._serialize, self._deserialize, \"2019-09-01\"\n )\n self.vpn_site_links = VpnSiteLinksOperations(\n self._client, self._config, self._serialize, self._deserialize, \"2019-09-01\"\n )\n self.vpn_sites_configuration = VpnSitesConfigurationOperations(\n self._client, self._config, self._serialize, self._deserialize, \"2019-09-01\"\n )\n self.vpn_server_configurations = VpnServerConfigurationsOperations(\n self._client, self._config, self._serialize, self._deserialize, \"2019-09-01\"\n )\n self.virtual_hubs = VirtualHubsOperations(\n self._client, self._config, self._serialize, self._deserialize, \"2019-09-01\"\n )\n self.hub_virtual_network_connections = HubVirtualNetworkConnectionsOperations(\n self._client, self._config, self._serialize, self._deserialize, \"2019-09-01\"\n )\n self.vpn_gateways = VpnGatewaysOperations(\n self._client, self._config, self._serialize, self._deserialize, \"2019-09-01\"\n )\n self.vpn_connections = VpnConnectionsOperations(\n self._client, self._config, self._serialize, self._deserialize, \"2019-09-01\"\n )\n self.vpn_site_link_connections = VpnSiteLinkConnectionsOperations(\n self._client, self._config, self._serialize, self._deserialize, \"2019-09-01\"\n )\n self.vpn_link_connections = VpnLinkConnectionsOperations(\n self._client, self._config, self._serialize, self._deserialize, \"2019-09-01\"\n )\n self.p2_svpn_gateways = P2SVpnGatewaysOperations(\n self._client, self._config, self._serialize, self._deserialize, \"2019-09-01\"\n )\n self.vpn_server_configurations_associated_with_virtual_wan = (\n VpnServerConfigurationsAssociatedWithVirtualWanOperations(\n self._client, self._config, self._serialize, self._deserialize, \"2019-09-01\"\n )\n )\n self.virtual_hub_route_table_v2_s = VirtualHubRouteTableV2SOperations(\n self._client, self._config, self._serialize, self._deserialize, \"2019-09-01\"\n )\n self.web_application_firewall_policies = WebApplicationFirewallPoliciesOperations(\n self._client, self._config, self._serialize, self._deserialize, \"2019-09-01\"\n )\n\n def _send_request(self, request: HttpRequest, **kwargs: Any) -> Awaitable[AsyncHttpResponse]:\n \"\"\"Runs the network request through the client's chained policies.\n\n >>> from azure.core.rest import HttpRequest\n >>> request = HttpRequest(\"GET\", \"https://www.example.org/\")\n \n >>> response = await client._send_request(request)\n \n\n For more information on this code flow, see https://aka.ms/azsdk/dpcodegen/python/send_request\n\n :param request: The network request you want to make. Required.\n :type request: ~azure.core.rest.HttpRequest\n :keyword bool stream: Whether the response payload will be streamed. Defaults to False.\n :return: The response of your network call. Does not do error handling on your response.\n :rtype: ~azure.core.rest.AsyncHttpResponse\n \"\"\"\n\n request_copy = deepcopy(request)\n request_copy.url = self._client.format_url(request_copy.url)\n return self._client.send_request(request_copy, **kwargs)\n\n async def close(self) -> None:\n await self._client.close()\n\n async def __aenter__(self) -> \"NetworkManagementClient\":\n await self._client.__aenter__()\n return self\n\n async def __aexit__(self, *exc_details: Any) -> None:\n await self._client.__aexit__(*exc_details)\n","sub_path":"sdk/network/azure-mgmt-network/azure/mgmt/network/v2019_09_01/aio/_network_management_client.py","file_name":"_network_management_client.py","file_ext":"py","file_size_in_byte":39377,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"386070628","text":"\"\"\"\n(c) 2012 Erik Rose\nMIT Licensed\nhttps://github.com/erikrose/blessings\n\"\"\"\nimport curses.has_key\nimport contextlib\nimport platform\nimport termios\nimport struct\nimport curses\nimport fcntl\nimport os\nimport sys\n\ntry:\n from io import UnsupportedOperation as IOUnsupportedOperation\nexcept ImportError:\n class IOUnsupportedOperation(Exception):\n \"\"\"\n dummy exception to take of Python 3's ``io.UnsupportedOperation`` in\n Python 2.\n \"\"\"\n\n\n__all__ = ['Terminal']\n\n\nif ('3', '0', '0') <= platform.python_version_tuple() < ('3', '2', '2+'):\n # Good till 3.2.10\n # Python 3.x < 3.2.3 has a bug in which tparm() erroneously takes a string.\n raise ImportError('Blessings needs Python 3.2.3 or greater for Python 3 '\n 'support due to http://bugs.python.org/issue10570.')\n\n\nclass Terminal(object):\n \"\"\"An abstraction around terminal capabilities\n\n Unlike curses, this doesn't require clearing the screen before doing\n anything, and it's friendlier to use. It keeps the endless calls to\n ``tigetstr()`` and ``tparm()`` out of your code, and it acts intelligently\n when somebody pipes your output to a non-terminal.\n\n Instance attributes:\n\n ``stream``\n The stream the terminal outputs to. It's convenient to pass the stream\n around with the terminal; it's almost always needed when the terminal\n is and saves sticking lots of extra args on client functions in\n practice.\n ``is_a_tty``\n Whether ``stream`` appears to be a terminal. You can examine this value\n to decide whether to draw progress bars or other frippery.\n\n \"\"\"\n def __init__(self, kind=None, stream=None, force_styling=False):\n \"\"\"Initialize the terminal.\n\n If ``stream`` is not a tty, I will default to returning an empty\n Unicode string for all capability values, so things like piping your\n output to a file won't strew escape sequences all over the place. The\n ``ls`` command sets a precedent for this: it defaults to columnar\n output when being sent to a tty and one-item-per-line when not.\n\n :arg kind: A terminal string as taken by ``setupterm()``. Defaults to\n the value of the ``TERM`` environment variable.\n :arg stream: A file-like object representing the terminal. Defaults to\n the original value of stdout, like ``curses.initscr()`` does.\n :arg force_styling: Whether to force the emission of capabilities, even\n if we don't seem to be in a terminal. This comes in handy if users\n are trying to pipe your output through something like ``less -r``,\n which supports terminal codes just fine but doesn't appear itself\n to be a terminal. Just expose a command-line option, and set\n ``force_styling`` based on it. Terminal initialization sequences\n will be sent to ``stream`` if it has a file descriptor and to\n ``sys.__stdout__`` otherwise. (``setupterm()`` demands to send them\n somewhere, and stdout is probably where the output is ultimately\n headed. If not, stderr is probably bound to the same terminal.)\n\n If you want to force styling to not happen, pass\n ``force_styling=None``.\n\n \"\"\"\n if stream is None:\n stream = sys.__stdout__\n try:\n stream_descriptor = (stream.fileno() if hasattr(stream, 'fileno')\n and callable(stream.fileno) else None)\n except IOUnsupportedOperation:\n stream_descriptor = None\n\n self.stream = stream\n self.is_a_tty = (stream_descriptor is not None\n and os.isatty(stream_descriptor))\n self._does_styling = ((self.is_a_tty or force_styling) and\n force_styling is not None)\n\n # The desciptor to direct terminal initialization sequences to.\n # sys.__stdout__ seems to always have a descriptor of 1, even if output\n # is redirected.\n self._init_descriptor = (sys.__stdout__.fileno()\n if stream_descriptor is None\n else stream_descriptor)\n if self._does_styling:\n # Make things like tigetstr() work. Explicit args make setupterm()\n # work even when -s is passed to nosetests. Lean toward sending\n # init sequences to the stream if it has a file descriptor, and\n # send them to stdout as a fallback, since they have to go\n # somewhere.\n curses.setupterm(kind or os.environ.get('TERM', 'unknown'),\n self._init_descriptor)\n\n # curses capability names are inherited for comparison\n for attr in (a for a in dir(curses) if a.startswith('KEY')):\n setattr(self, attr, getattr(curses, attr))\n\n # after sucessful setupterm(), a _keymap of keyboard sequences to\n # curses capability names can be constructed, this creates things\n # such as self.KEY_ENTER (..)\n self._keymap = dict([(curses.tigetstr(cap).decode('utf-8'),\n keycode) for (keycode,cap) in\n curses.has_key._capability_names.iteritems() if\n curses.tigetstr(cap) is not None])\n\n # various terminal default sequences mappings\n self._keymap.update ([\n (unichr(10), self.KEY_ENTER),\n (unichr(13), self.KEY_ENTER),\n (unichr(8), self.KEY_BACKSPACE),\n (unichr(127), self.KEY_BACKSPACE),\n (unichr(27) + u\"OA\", self.KEY_UP),\n (unichr(27) + u\"OB\", self.KEY_DOWN),\n (unichr(27) + u\"OC\", self.KEY_RIGHT),\n (unichr(27) + u\"OD\", self.KEY_LEFT),\n (unichr(27) + u\"[A\", self.KEY_UP),\n (unichr(27) + u\"[B\", self.KEY_DOWN),\n (unichr(27) + u\"[C\", self.KEY_RIGHT),\n (unichr(27) + u\"[D\", self.KEY_LEFT),\n (unichr(27) + u\"A\", self.KEY_UP),\n (unichr(27) + u\"B\", self.KEY_DOWN),\n (unichr(27) + u\"C\", self.KEY_RIGHT),\n (unichr(27) + u\"D\", self.KEY_LEFT),\n (unichr(27) + u\"?x\", self.KEY_UP),\n (unichr(27) + u\"?r\", self.KEY_DOWN),\n (unichr(27) + u\"?v\", self.KEY_RIGHT),\n (unichr(27) + u\"?t\", self.KEY_LEFT),\n (unichr(27) + u\"[H\", self.KEY_HOME),\n (unichr(27) + u\"[F\", self.KEY_END),])\n\n # Sugary names for commonly-used capabilities, intended to help avoid trips\n # to the terminfo man page and comments in your code:\n _sugar = dict(\n # Don't use \"on\" or \"bright\" as an underscore-separated chunk in any of\n # these (e.g. on_cology or rock_on) so we don't interfere with\n # __getattr__.\n save='sc',\n restore='rc',\n\n clear_eol='el',\n clear_bol='el1',\n clear_eos='ed',\n # 'clear' clears the whole screen.\n position='cup', # deprecated\n enter_fullscreen='smcup',\n exit_fullscreen='rmcup',\n move='cup',\n move_x='hpa',\n move_y='vpa',\n move_left='cub1',\n move_right='cuf1',\n move_up='cuu1',\n move_down='cud1',\n\n hide_cursor='civis',\n normal_cursor='cnorm',\n\n reset_colors='op', # oc doesn't work on my OS X terminal.\n\n normal='sgr0',\n reverse='rev',\n # 'bold' is just 'bold'. Similarly...\n # blink\n # dim\n # flash\n italic='sitm',\n no_italic='ritm',\n shadow='sshm',\n no_shadow='rshm',\n standout='smso',\n no_standout='rmso',\n subscript='ssubm',\n no_subscript='rsubm',\n superscript='ssupm',\n no_superscript='rsupm',\n underline='smul',\n no_underline='rmul')\n\n def __getattr__(self, attr):\n \"\"\"Return parametrized terminal capabilities, like bold.\n\n For example, you can say ``term.bold`` to get the string that turns on\n bold formatting and ``term.normal`` to get the string that turns it off\n again. Or you can take a shortcut: ``term.bold('hi')`` bolds its\n argument and sets everything to normal afterward. You can even combine\n things: ``term.bold_underline_red_on_bright_green('yowzers!')``.\n\n For a parametrized capability like ``cup``, pass the parameters too:\n ``some_term.cup(line, column)``.\n\n ``man terminfo`` for a complete list of capabilities.\n\n Return values are always Unicode.\n\n \"\"\"\n resolution = (self._resolve_formatter(attr) if self._does_styling\n else NullCallableString())\n setattr(self, attr, resolution) # Cache capability codes.\n return resolution\n\n @property\n def height(self):\n \"\"\"The height of the terminal in characters\n\n If no stream or a stream not representing a terminal was passed in at\n construction, return the dimension of the controlling terminal so\n piping to things that eventually display on the terminal (like ``less\n -R``) work. If a stream representing a terminal was passed in, return\n the dimensions of that terminal. If there somehow is no controlling\n terminal, return ``None``. (Thus, you should check that ``is_a_tty`` is\n True before doing any math on the result.)\n\n \"\"\"\n return self._height_and_width()[0]\n\n @property\n def width(self):\n \"\"\"The width of the terminal in characters\n\n See ``height()`` for some corner cases.\n\n \"\"\"\n return self._height_and_width()[1]\n\n def _height_and_width(self):\n \"\"\"Return a tuple of (terminal height, terminal width).\"\"\"\n # tigetnum('lines') and tigetnum('cols') update only if we call\n # setupterm() again.\n for descriptor in self._init_descriptor, sys.__stdout__:\n try:\n return struct.unpack('hhhh', fcntl.ioctl(descriptor,\n termios.TIOCGWINSZ, chr(0) * 8))[0:2]\n except IOError:\n pass\n return None, None # Should never get here\n\n @contextlib.contextmanager\n def location(self, xloc=None, yloc=None):\n \"\"\"Return a context manager for temporarily moving the cursor.\n\n Move the cursor to a certain position on entry, let you print stuff\n there, then return the cursor to its original position::\n\n term = Terminal()\n with term.location(2, 5):\n print 'Hello, world!'\n for x in xrange(10):\n print 'I can do it %i times!' % x\n\n Specify ``x`` to move to a certain column, ``y`` to move to a certain\n row, both, or neither. If you specify neither, only the saving and\n restoration of cursor position will happen. This can be useful if you\n simply want to restore your place after doing some manual cursor\n movement.\n\n \"\"\"\n # Save position and move to the requested column, row, or both:\n self.stream.write(self.save)\n if xloc is not None and yloc is not None:\n self.stream.write(self.move(yloc, xloc))\n elif xloc is not None:\n self.stream.write(self.move_x(xloc))\n elif yloc is not None:\n self.stream.write(self.move_y(yloc))\n yield\n\n # Restore original cursor position:\n self.stream.write(self.restore)\n\n @contextlib.contextmanager\n def fullscreen(self):\n \"\"\"\n Return a context manager that enters fullscreen mode while inside it\n and restores normal mode on leaving.\n \"\"\"\n self.stream.write(self.enter_fullscreen)\n yield\n self.stream.write(self.exit_fullscreen)\n\n @contextlib.contextmanager\n def hidden_cursor(self):\n \"\"\"\n Return a context manager that hides the cursor while inside it and\n makes it visible on leaving.\n \"\"\"\n self.stream.write(self.hide_cursor)\n yield\n self.stream.write(self.normal_cursor)\n\n @property\n def color(self):\n \"\"\"Return a capability that sets the foreground color.\n\n The capability is unparametrized until called and passed a number\n (0-15), at which point it returns another string which represents a\n specific color change. This second string can further be called to\n color a piece of text and set everything back to normal afterward.\n\n :arg num: The number, 0-15, of the color\n\n \"\"\"\n return ParametrizingString(self._foreground_color, self.normal)\n\n @property\n def on_color(self):\n \"\"\"Return a capability that sets the background color.\n\n See ``color()``.\n\n \"\"\"\n return ParametrizingString(self._background_color, self.normal)\n\n @property\n def number_of_colors(self):\n \"\"\"Return the number of colors the terminal supports.\n\n Common values are 0, 8, 16, 88, and 256.\n\n Though the underlying capability returns -1 when there is no color\n support, we return 0. This lets you test more Pythonically::\n\n if term.number_of_colors:\n ...\n\n We also return 0 if the terminal won't tell us how many colors it\n supports, which I think is rare.\n \"\"\"\n #pylint: disable=R0201\n # Method could be a function\n # This is actually the only remotely useful numeric capability. We\n # don't name it after the underlying capability, because we deviate\n # slightly from its behavior, and we might someday wish to give direct\n # access to it.\n colors = curses.tigetnum('colors')\n # Returns -1 if no color support, -2 if no such cap.\n return colors if colors >= 0 else 0\n\n def _resolve_formatter(self, attr):\n \"\"\"\n Resolve a sugary or plain capability name, color, or compound\n formatting function name into a callable capability.\n \"\"\"\n if attr in COLORS:\n return self._resolve_color(attr)\n elif attr in COMPOUNDABLES:\n # Bold, underline, or something that takes no parameters\n return self._formatting_string(self._resolve_capability(attr))\n else:\n formatters = split_into_formatters(attr)\n if all(f in COMPOUNDABLES for f in formatters):\n # It's a compound formatter, like \"bold_green_on_red\". Future\n # optimization: combine all formatting into a single escape\n # sequence.\n return self._formatting_string(\n u''.join(self._resolve_formatter(s) for s in formatters))\n else:\n return ParametrizingString(self._resolve_capability(attr))\n\n def _resolve_capability(self, atom):\n \"\"\"\n Return a terminal code for a capname or a sugary name, or an empty\n Unicode.\n\n The return value is always Unicode, because otherwise it is clumsy\n (especially in Python 3) to concatenate with real (Unicode) strings.\n\n \"\"\"\n code = curses.tigetstr(self._sugar.get(atom, atom))\n if code:\n # We can encode escape sequences as UTF-8 because they never\n # contain chars > 127, and UTF-8 never changes anything within that\n # range..\n return code.decode('utf-8')\n return u''\n\n def trans_input (self, data, encoding='utf8'):\n \"\"\"\n Yield either a unicode byte or a curses key constant as integer.\n If data is a bytestring, it is converted to unicode using encoding.\n \"\"\"\n if isinstance(data, str):\n data = data.decode (encoding, 'replace')\n\n def scan_keymap(text):\n \"\"\"\n Return sequence and keycode if text begins with any known sequence.\n \"\"\"\n for (keyseq, keycode) in self._keymap.iteritems():\n if text.startswith (keyseq):\n return (keyseq, keycode)\n return (None, None) # no match\n\n while len(data):\n if ('\\r','\\x00') == (data[0], data[1] if 1 != len(data) else None):\n # skip beyond nul (nvt telnet)\n yield self.KEY_ENTER #data[0]\n data = data[2:]\n continue\n if ('\\r','\\n') == (data[0], data[1] if 1 != len(data) else None):\n # skip beyond \\n (putty, SyncTerm)\n yield self.KEY_ENTER\n data = data[2:]\n continue\n keyseq, keycode = scan_keymap(data)\n # keymap KEY_ sequence\n if (keyseq, keycode) != (None, None):\n yield keycode\n data = data[len(keyseq):]\n else:\n yield data[0]\n data = data[1:]\n\n def keyname(self, value):\n \"\"\"Return a matching keycode attribute name given a keycode value.\"\"\"\n try:\n return (a for a in dir(self) if a.startswith('KEY_') and value ==\n getattr(self, a)).next()\n except StopIteration:\n return '' % (value,)\n\n def _resolve_color(self, color):\n \"\"\"\n Resolve a color like red or on_bright_green into a callable capability.\n \"\"\"\n # TODO: Does curses automatically exchange red and blue and cyan and\n # yellow when a terminal supports setf/setb rather than setaf/setab?\n # I'll be blasted if I can find any documentation. The following\n # assumes it does.\n color_cap = (self._background_color if 'on_' in color else\n self._foreground_color)\n # curses constants go up to only 7, so add an offset to get at the\n # bright colors at 8-15:\n offset = 8 if 'bright_' in color else 0\n base_color = color.rsplit('_', 1)[-1]\n return self._formatting_string(\n color_cap(getattr(curses, 'COLOR_' + base_color.upper()) + offset))\n\n @property\n def _foreground_color(self):\n return self.setaf or self.setf\n\n @property\n def _background_color(self):\n return self.setab or self.setb\n\n def _formatting_string(self, formatting):\n \"\"\"\n Return a new ``FormattingString`` which implicitly receives my notion\n of \"normal\".\n \"\"\"\n return FormattingString(formatting, self.normal)\n\n\ndef derivative_colors(colors):\n \"\"\"Return the names of valid color variants, given the base colors.\"\"\"\n return set([('on_' + c) for c in colors] +\n [('bright_' + c) for c in colors] +\n [('on_bright_' + c) for c in colors])\n\n\nCOLORS = set(['black', 'red', 'green', 'yellow', 'blue',\n 'magenta', 'cyan', 'white'])\nCOLORS.update(derivative_colors(COLORS))\nCOMPOUNDABLES = (COLORS |\n set(['bold', 'underline', 'reverse', 'blink', 'dim', 'italic',\n 'shadow', 'standout', 'subscript', 'superscript']))\n\n\nclass ParametrizingString(unicode):\n \"\"\"\n A Unicode string which can be called to parametrize it as a terminal\n capability.\n \"\"\"\n def __new__(cls, formatting, normal=None):\n \"\"\"Instantiate.\n\n :arg normal: If non-None, indicates that, once parametrized, this can\n be used as a ``FormattingString``. The value is used as the\n \"normal\" capability.\n\n \"\"\"\n new = unicode.__new__(cls, formatting)\n new._normal = normal\n return new\n\n def __call__(self, *args):\n try:\n # Re-encode the cap, because tparm() takes a bytestring in Python\n # 3. However, appear to be a plain Unicode string otherwise so\n # concats work.\n lookup = self.encode('utf-8')\n parametrized = curses.tparm(lookup, *args).decode ('utf-8')\n return (parametrized if self._normal is None else\n FormattingString(parametrized, self._normal))\n except curses.error:\n # Catch \"must call (at least) setupterm() first\" errors, as when\n # running simply `nosetests` (without progressive) on nose-\n # progressive. Perhaps the terminal has gone away between calling\n # tigetstr and calling tparm.\n return u''\n except TypeError:\n # If the first non-int (i.e. incorrect) arg was a string, suggest\n # something intelligent:\n if len(args) == 1 and isinstance(args[0], basestring):\n raise TypeError(\n 'A native or nonexistent capability template received '\n '%r when it was expecting ints. You probably misspelled a '\n 'formatting call like bright_red_on_white(...).' % args)\n else:\n # Somebody passed a non-string; I don't feel confident\n # guessing what they were trying to do.\n raise\n\n\nclass FormattingString(unicode):\n \"\"\"A Unicode string which can be called upon a piece of text to wrap it in formatting\"\"\"\n def __new__(cls, formatting, normal):\n new = unicode.__new__(cls, formatting)\n new._normal = normal\n return new\n\n def __call__(self, text):\n \"\"\"Return a new string that is ``text`` formatted with my contents.\n\n At the beginning of the string, I prepend the formatting that is my\n contents. At the end, I append the \"normal\" sequence to set everything\n back to defaults. The return value is always a Unicode.\n\n \"\"\"\n return self + text + self._normal\n\n\nclass NullCallableString(unicode):\n \"\"\"\n A dummy class to stand in for ``FormattingString`` and\n ``ParametrizingString``.\n\n A callable bytestring that returns an empty Unicode when called with an int\n and the arg otherwise. We use this when there is no tty and so all\n capabilities are blank.\n\n \"\"\"\n def __new__(cls):\n new = unicode.__new__(cls, u'')\n return new\n\n def __call__(self, arg):\n if isinstance(arg, int):\n return u''\n return arg\n\n\ndef split_into_formatters(compound):\n \"\"\"Split a possibly compound format string into segments.\n\n >>> split_into_formatters('bold_underline_bright_blue_on_red')\n ['bold', 'underline', 'bright_blue', 'on_red']\n\n \"\"\"\n merged_segs = []\n # These occur only as prefixes, so they can always be merged:\n mergeable_prefixes = ['on', 'bright', 'on_bright']\n for spx in compound.split('_'):\n if merged_segs and merged_segs[-1] in mergeable_prefixes:\n merged_segs[-1] += '_' + spx\n else:\n merged_segs.append(spx)\n return merged_segs\n","sub_path":"blessings.py","file_name":"blessings.py","file_ext":"py","file_size_in_byte":22651,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"473535795","text":"import csv\nimport sys\n\nfilename = sys.argv[1]\n\nwith open(filename, newline='') as csvfile:\n data = list(csv.reader(csvfile,'excel'))\nz=len(data)\nx = 0\nend = False\n\n\n\nl1=[]\nl2=[]\noutput=[]\nwhile (end != True):\n print(x)\n if(x<1): \n data.remove(data[x])\n z-=1\n \n if(len(data[x]) == 1 or len(data[x]) == 3 or data[x][1] == \"\" or data[x][0] == \"\" or int(data[x][0]) < 1000 or int(data[x][0])>90000000000 or int(data[x][1])>50000 or int(data[x][1])<10): \n data.remove(data[x])\n print('reeeee')\n z-=1\n #else:\n # if((x-1)%400==0):\n # \n # output.append([int(sum(l1)/len(l1))/1000000, (int(sum(l2)/len(l2))-25000)*1.1/(10*185)])\n # \n # l1 = [int(data[x][0])]\n # l2 = [int(data[x][1])]\n # else:\n # l1.append(int(data[x][0]))\n # l2.append(int(data[x][1]))\n output = data[x]\n data[x][0] = int(output[0])/1000000\n data[x][1] = (int(output[1])-25000)*1.1/(10*185)\n \n \n x+=1\n if(x>=z):end = True\n\n\n\n \n\nwith open(filename, 'w' , newline='') as myfile:\n wr = csv.writer(myfile, dialect = 'excel')\n wr.writerows(data)\n\n","sub_path":"test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":1171,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"479483008","text":"import boto3\nimport pprint\nclient=boto3.client('dynamodb')\ntable = client.create_table(\n AttributeDefinitions=[\n {\n 'AttributeName': 'GID',\n 'AttributeType': 'N'\n }\n ],\n TableName='KavishGames',\n KeySchema=[\n {\n 'AttributeName': 'GID',\n 'KeyType': 'HASH'\n }\n ],\n BillingMode='PROVISIONED',\n ProvisionedThroughput={\n 'ReadCapacityUnits': 123,\n 'WriteCapacityUnits': 123\n },\n)\npprint.pprint(table)\n\n\n","sub_path":"AWS Assignment1/ques9.py","file_name":"ques9.py","file_ext":"py","file_size_in_byte":508,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"28192677","text":"import pathlib\nimport json\n\nfrom flask import Flask, request, jsonify\n\nfrom sgnlp.models.span_extraction import (\n RecconSpanExtractionConfig,\n RecconSpanExtractionModel,\n RecconSpanExtractionTokenizer,\n RecconSpanExtractionPreprocessor,\n RecconSpanExtractionPostprocessor,\n)\nfrom sgnlp.models.span_extraction.utils import (\n get_all_evidence_utterance_from_conversation,\n)\n\n\napp = Flask(__name__)\n\nconfig = RecconSpanExtractionConfig.from_pretrained(\n \"https://sgnlp.blob.core.windows.net/models/reccon_span_extraction/config.json\"\n)\ntokenizer = RecconSpanExtractionTokenizer.from_pretrained(\n \"mrm8488/spanbert-finetuned-squadv2\"\n)\nmodel = RecconSpanExtractionModel.from_pretrained(\n \"https://sgnlp.blob.core.windows.net/models/reccon_span_extraction/pytorch_model.bin\",\n config=config,\n)\npreprocessor = RecconSpanExtractionPreprocessor(tokenizer)\npostprocessor = RecconSpanExtractionPostprocessor()\n\n\n@app.route(\"/model-card\", methods=[\"GET\"])\ndef get_model_card():\n \"\"\"GET method for model card\n\n Returns:\n json: return the model card in json format\n \"\"\"\n model_card_path = str(\n pathlib.Path(__file__).parent.joinpath(\"model_card/span_extraction.json\")\n )\n with open(model_card_path) as f:\n model_card = json.load(f)\n return jsonify(**model_card)\n\n\n@app.route(\"/predict\", methods=[\"POST\"])\ndef predict():\n \"\"\"Iterate through each evidence utt in context to perform RECCON span extraction.\n The last utterance in context is used as the target utterance.\n\n Inputs:\n A json with 'context' and 'emotion' keys\n Example:\n {\"context\": [\n \"Linda ? Is that you ? I haven't seen you in ages !\",\n \"Hi George ! It's good to see you !\"\n ],\n \"emotion\": \"surprise\"}\n\n Returns:\n json: return a json which consists of the emotion, evidence span index,\n the probability and utterances broken up into spans\n Example:\n {\"emotion\": \"surprise\",\n \"evidence_span\": [[0,1],\n [0, 1]],\n \"probability\": [[-1, 0.943615029866203],\n [-1, 0.8712913786944898]],\n \"utterances\": [[\"Linda ? Is that you ? \",\n \"I haven't seen you in ages !\"],\n [\"Hi George ! \",\n \"It's good to see you !\"]]}\n \"\"\"\n req_body = request.get_json()\n conversation_history = req_body[\"context\"]\n emotion = req_body[\"emotion\"]\n\n input_batch = get_all_evidence_utterance_from_conversation(\n emotion=emotion, conversation_history=conversation_history\n )\n tensor_dict, evidences, examples, features = preprocessor(input_batch)\n raw_output = model(**tensor_dict)\n context, evidence_span, probability = postprocessor(\n raw_output, evidences, examples, features\n )\n\n return jsonify(\n {\n \"utterances\": context,\n \"evidence_span\": evidence_span,\n \"probability\": probability,\n \"emotion\": req_body[\"emotion\"],\n }\n )\n\n\nif __name__ == \"__main__\":\n app.run(host=\"0.0.0.0\")\n","sub_path":"demo_api/span_extraction/model_api.py","file_name":"model_api.py","file_ext":"py","file_size_in_byte":3117,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"516319217","text":"# -*- coding: utf-8 -*-\nimport config\nfrom flask import Flask\nfrom views import qr_gen, main_view\n\n__author__ = 'KostaNau'\n\n\napp = Flask(__name__)\napp.config.from_object(config)\n\napp.register_blueprint(main_view)\napp.register_blueprint(qr_gen)\n\n# @app.route('/qr')\n# def hello_world():\n# return 'Hello World!'\n\n\nif __name__ == '__main__':\n app.run()\n","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":357,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"291674602","text":"import argparse\nimport torch\nimport logging\nimport pathlib\nimport traceback\nfrom FOTS.base.base_model import BaseModel\nfrom FOTS.model.model import FOTSModel\nfrom FOTS.utils.bbox import Toolbox\n\nlogging.basicConfig(level=logging.DEBUG, format='')\n\n\ndef main(args:argparse.Namespace):\n model_path = args.model\n input_dir = args.input_dir\n output_dir = args.output_dir\n with_image = True if output_dir else False\n\n model = FOTSModel().to(torch.device(\"cuda\"))\n model.load_state_dict(torch.load(model_path))\n model.eval()\n\n with torch.no_grad():\n for image_fn in input_dir.glob('*.jpg'):\n ploy, im = Toolbox.predict(image_fn, model, with_image, output_dir, with_gpu=True)\n\n\nif __name__ == '__main__':\n logger = logging.getLogger()\n\n parser = argparse.ArgumentParser(description='Model eval')\n parser.add_argument('-m', '--model', default=None, type=pathlib.Path, required=True,\n help='path to model')\n parser.add_argument('-o', '--output_dir', default=None, type=pathlib.Path,\n help='output dir for drawn images')\n parser.add_argument('-i', '--input_dir', default=None, type=pathlib.Path, required=False,\n help='dir for input images')\n args = parser.parse_args()\n main(args)\n","sub_path":"eval.py","file_name":"eval.py","file_ext":"py","file_size_in_byte":1304,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"189693730","text":"#!/usr/bin/python3\n\nimport sys\nimport os\nimport random\nimport datetime\nimport pickle\n\nimport backtrack\nimport cli\nfrom ciphers.spritz import Spritz\nfrom states import SpritzState\nfrom stats import Stats\n\n\ndef read_states(input_file):\n states = []\n while True:\n initial = input_file.readline()\n if initial == '':\n break\n revealed = input_file.readline()\n shift = int(input_file.readline())\n states.append((\n SpritzState(string=initial), \n SpritzState(string=revealed),\n shift\n ))\n return states\n\n\nclass Settings:\n def __init__(self, args):\n self.__dict__ = args.__dict__.copy()\n\n\ndef main(args):\n states = read_states(sys.stdin)\n\n stats = Stats(sys.argv)\n cipher = Spritz()\n\n settings = Settings(args)\n\n prompt_step = max(1, len(states) // 20)\n i = 0\n for initial_state, revealed_state, prefix_length in states:\n if args.verbosity >= 3 and i % prompt_step == 0:\n print('test #:', i)\n i += 1\n\n KNOWN_KEYSTREAM_SIZE = 3 * initial_state.size + 1\n cipher.initialize_state(initial_state.state)\n known_keystream = cipher.keystream(prefix_length + KNOWN_KEYSTREAM_SIZE)\n settings.prefix_length = prefix_length\n\n cipher.initialize_state(initial_state.state)\n cipher.keystream(prefix_length)\n found_state, round_stats = backtrack.kpa(\n known_keystream,\n revealed_state,\n settings,\n )\n\n if found_state and initial_state != found_state:\n print('incorrect result, this should not happen')\n assert False\n\n stats.add(round_stats)\n\n stats.print_stats(args.verbosity)\n # dump pickled stats object\n if not args.no_stats_log:\n timestamp = datetime.datetime.today().strftime('%y%m%d_%H%M%S_%f')\n os.makedirs('stats/', exist_ok=True)\n with open('stats/' + timestamp, 'wb') as f:\n pickle.dump(stats, f)\n\nif __name__ == '__main__':\n main(cli.parse_benchmark_args())\n","sub_path":"backtrack/spritz-py/benchmark.py","file_name":"benchmark.py","file_ext":"py","file_size_in_byte":2063,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"515359416","text":"#!/usr/bin/env python\n# coding: utf-8\n\n# # Python User Define Function Practice Activity - 2 \n\n# Asst. Prof. Syed Faisal Ali $\\;\\;\\;\\;\\;\\;$ Programming Fundamentals - FALL 2019 $\\;\\;\\;\\;\\;\\;$ Software Engineering $\\;\\;\\;\\;\\;\\;$ Dated: 27 Nov 2019\n\n# Question 1: Create a function to find the following:\n# If the base of triangle is 3 cm long and its equilateral triangle and the radius of circle is 1.5 cm then find the area of triangle shaded. \n# \n\n# \n\n# In[ ]:\n\n\n\n\n\n# Question 2: Create a function which can read a dictionary of your family members such as 5 members. \n# 1 Abbu, 1 Ammi, 2 Brothers 1 Sister. Now feed this data in dictionary in terms of name and relations.\n# The UDF will ask findrelation() in this you will enter Brother it will return the names of two brothers you have inserted. In case if the relation is not found it will return “Sorry the relation doesn’t exist in your family.” \n# \n\n# In[ ]:\n\n\n\n\n\n# Question 3: Create a function to find the following:\n# If the base of triangle is 5 cm long and its equilateral triangle and the radius of circle is 2.25 cm then find the area of triangle shaded. \n# \n\n# \n\n# In[39]:\n\n\nimport math\ndef area1(r,l):\n circlearea=math.pi*r*r\n triarea=l*l*3\n x=circlearea-triarea\n print(\"the area of shaded region is \",r,\"cm^2\")\narea1(2.25,5)\n#completed in 5 mints.\n\n\n# Question 4:\n# Create a function that takes a list of random numbers from users and add only those which are even. If all the numbers are odd it will return sorry no even number found.\n# \n\n# In[36]:\n\n\nlist1 = [15, 100, 3, 50, 23, 88, 10] \neven_count, odd_count = 0, 0\nfor num in list1: \n if num % 2 == 0: \n even_count += 1\n else: \n print(\"sorry\")\nprint(\"Even numbers in the list: \", even_count)\n\n\n# Question 5:\n# Write a function which can take a list of numbers and it will return sorted list.\n# \n\n# In[35]:\n\n\nnumbers = [5, 66, 1, 8]\nnumbers.sort() \nprint(numbers) \n\n\n# Question 6:\n# Write a function that will take the radius and return the perimeter and area of circle with 5% increment.\n# \n\n# In[44]:\n\n\nimport math\ndef area_perimeter(r):\n area=math.pi*r*r\n peri=5*math.pi*r\n x=area/10\n a=area+x\n y=peri/10\n b=peri*y\n print(\"The Area Of Circle With 5% Increment is:\",a,\"\\nthe perimeter of circle with 5% increment is:\",b)\narea_perimeter(5) \n#completed in 5 mints.. \n\n\n# Question 7:\n# Write a function that will take the strings as argument and return number of vowels and consonants.\n# \n\n# In[47]:\n\n\ndef vowels(s):\n vowel=0\n consonant=0\n for i in s:\n if i in \"aeiouAEIOU\":\n vowel+=1\n else:\n consonant+=1\n print(\"The Vowels are:\", vowel)\n print(\"The Consonants are:\", consonant)\nvowels(\"Haris\") \n#completed in 5mints...\n\n\n# Question 8:\n# Write a function that will take length and breadth for a rectangle and return perimeter and area of rectangle with 8% increment.\n# \n\n# In[58]:\n\n\ndef peri_area(l,b):\n p=2*(l+b)\n a=l*b\n x=p/14+p\n y=a/14+a\n print(\"the perimeter of rectangle is \",x,\"\\nthe area of rectangle is\",y)\nperi_area(2,4)\n#completed in 4 mints..\n\n\n# Question 9:\n# Write a function that can take the numbers in strings. From string find which number is even and which one is odd. Save them in two different lists and generate the result.\n# \n\n# In[4]:\n\n\ndef str1(a,b,c,d,e,f):\n even=[]\n odd=[]\n lst=[a,b,c,d,e,f]\n for i in lst:\n if i%2==0:\n even.append(i)\n else:\n odd.append(i)\n print(\"even list are\",even,\"\\noddlist are \",odd) \nstr1(10,25,45,11,83,57)\n#completed in 10 mints..\n\n\n# Question 10:\n# Write a function which will take the string from the user and return how many alphabets have been used in it and which alphabets are missing.\n# \n\n# In[53]:\n\n\ndef alpha(s):\n alphabets=['a','b','c','d','e','f','g','h','i','j','k','m','n','o','p','q','r','s','t','u','v','w','y','z']\n for i in s:\n alphabets.remove(i)\n print('the missing alphabets are',alphabets)\n print(\"the used alphabets are\",s)\n for i in s:\n print(i,end=\" \")\nalpha(\"haris\")\n#completed in 10 mints..\n\n\n# Question 11:\n# Write a function that will take verbs in words and return a list of verbs with continuous tense by adding (ing) at the end of each verb.\n# \n\n# In[55]:\n\n\ndef verb(x):\n return x+\"ing\"\nprint(verb(\"cut\"))\nprint(verb(\"put\"))\n#completed in 2 mints..\n\n\n# Question 12:\n# Make a function which can take two radius of circles and find the areas of it and subtract smaller one from larger one and tell the remaining area of circle.\n# \n\n# In[ ]:\n\n\n\n\n\n# Question 13:\n# Write a function that will take a string and calculate number of Upper case letters and lower case letters.\n# \n\n# In[6]:\n\n\ndef strtest(s):\n d={\"UPPER_CASE\":0, \"LOWER_CASE\":0}\n for i in s:\n if i.isupper():\n d[\"UPPER_CASE\"]+=1\n elif i.islower():\n d[\"LOWER_CASE\"]+=1\n else:\n pass\n print(\"The main String: \", s)\n print(\"No of Upper case:\", d[\"UPPER_CASE\"])\n print(\"No of Lower case:\", d[\"LOWER_CASE\"])\nstrtest('We Are Programmer') \n#completed in 10 mints.\n\n\n# Question 14:\n# Write a function which will take length and breadth of two rectangles. Subtract the smaller rectangle from the larger rectangle and return the area left behind.\n# \n\n# In[ ]:\n\n\n\n\n\n# Question 15:\n# Create a function that can add the fractions in series such as 1 to 8 = 1/8+1/7+1/6+1/5 …… ½ and return the result in fraction not in decimal.\n# \n\n# In[ ]:\n\n\n\n\n\n# Question 16:\n# Write a function which will take height and base for a triangle and \n# \n\n# In[ ]:\n\n\n\n\n\n# Question 17:\n# Write a function which will take a list of fruits names. The function will return how many alphabets are repetitive in the names of fruits and how many are unique letters.\n# \n\n# In[ ]:\n\n\n\n\n\n# Question 18:\n# Write a function that can take square length and radius of circle. Find the area of both and subtract the smallest shape from largest one and return the remaining shape area.\n# \n\n# In[ ]:\n\n\n\n\n","sub_path":"UDF Activity 2 by Asst. Prof. Syed Faisal Ali.py","file_name":"UDF Activity 2 by Asst. Prof. Syed Faisal Ali.py","file_ext":"py","file_size_in_byte":6106,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"253005805","text":"'''\nTask 3:\nPlease write a binary search function that will look for an item in a sorted list. The\nfunction will return the index of element to be searched in the list.\n'''\ndef binary_search(lst, item):\n low = 0\n high = len(lst) - 1\n\n while low <= high:\n mid = round((low + high) / 2)\n\n if lst[mid] == item:\n return mid\n elif lst[mid] > item:\n high = mid - 1\n else:\n low = mid + 1\n return None\n\n\nlst = [1, 3, 5, 7, ]\nprint(binary_search(lst, 9))","sub_path":"cit_CyberSecurity/session_9/task_3.py","file_name":"task_3.py","file_ext":"py","file_size_in_byte":518,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"574191510","text":"# help.py\n\n# Metadata\n\nNAME = 'help'\nENABLE = True\nTYPE = 'command'\nPATTERN = '^!help\\s*(?P.*)$'\nUSAGE = '''Usage: !help [ | all]\nEither list all the modules or provide the usage message for a particular\nmodule.\n'''\n\n# Command\n\ndef command(bot, nick, message, channel, module_name=None):\n if not module_name or module_name == 'all':\n response = sorted([m.NAME for m in bot.modules.values()])\n bot.send_response(response, nick, channel, notice=True)\n\n for module in bot.modules.values():\n if module.NAME == module_name:\n response = module.USAGE.splitlines()\n bot.send_response(response, nick, channel, notice=True)\n\n# Register\n\ndef register(bot):\n return (\n (PATTERN, command),\n )\n\n# vim: set sts=4 sw=4 ts=8 expandtab ft=python:\n","sub_path":"modules/help.py","file_name":"help.py","file_ext":"py","file_size_in_byte":826,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"528518019","text":"import typing\n\nimport sqlalchemy as sa\n\nfrom sqlalchemy.dialects.postgresql import UUID\n\nfrom app.db.base_class import Base\n\n\nM = typing.TypeVar(\"M\", bound=\"ModelBase\")\n\n\nclass ModelBase(Base):\n __abstract__ = True\n id = sa.Column(\n UUID(as_uuid=True),\n primary_key=True,\n server_default=sa.text(\"uuid_generate_v4()\"),\n )\n\n created_at = sa.Column(sa.DateTime, server_default=sa.func.now(), nullable=False)\n updated_at = sa.Column(\n sa.DateTime,\n onupdate=sa.func.now(),\n server_default=sa.func.now(),\n nullable=False,\n )\n\n\nclass RelationBase(Base):\n __abstract__ = True\n\n created_at = sa.Column(sa.DateTime, server_default=sa.func.now(), nullable=False)\n updated_at = sa.Column(\n sa.DateTime,\n onupdate=sa.func.now(),\n server_default=sa.func.now(),\n nullable=False,\n )\n","sub_path":"app/models/orm/base.py","file_name":"base.py","file_ext":"py","file_size_in_byte":876,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"120225502","text":"import re\nimport pickle\nimport string\nfrom string import digits\nfrom nltk.corpus import stopwords\n\n\"\"\"\nParse through already downloaded movie scripts/subtitles to reduce to only words\n\"\"\"\n\ndef edited_file_name(movie_script):\t\n\t\"\"\"\n\tEnsure new movie file name is clear\n\n\t>>> edited_file_name('StarWars.srt')\n\tStarWars_edited.txt\n\n\t>>> edited_file_name('BTTF.srt')\n\tBTTF_edited.txt\n\t\"\"\"\n\n\tmovie_clear = movie_script.replace('.srt', '')\n\treturn '%s' % movie_clear + '_edited.txt'\n\ndef edit_all(movie_list):\n\t\"\"\"\n\tEdit all movie names and all movie subtitles in movie_list\n\tIncrease efficiency\n\t\"\"\"\n\n\tfor movie in movie_list:\n\t\tedit_script(movie)\n\t\tnew_name = edited_file_name(movie)\n\t\thist = process_script(new_name)\n\ndef edit_script(movie_script):\n\t\"\"\"\n\tEdit original movie subtitles to extract any unnecessary text\n\tSave as new file\n\t\"\"\"\n\n\tnew_name = edited_file_name(movie_script)\n\n\toriginal_script = file(movie_script)\t\t\t\t# name variable to original version of movie script\n\n\tnew_script = open(new_name, 'w')\t\t\t\t\t# open new file for writing\n\tfor line in original_script:\t\t\t\t\t\t# read through original script\n\t\tline = line.translate(None, digits)\t\t\t\t# remove numbers (0123456789)\n\t\tline = re.sub('<.*?>', '', line)\t\t\t\t# remove any text between '<>', including the symbols themselves (if text on screen)\n\n\n\t\tif '-->' not in line and 'Subtitle' not in line and '()' not in line and '^' not in line:\t\t# further parse to reduce to scripted words only\n\t\t\tnew_script.write(line)\t\t\t\t\t\t# write edited lines onto new file\n\tnew_script.close()\t\t\t\t\t\t\t\t\t# close file\n\ndef process_script(file_name):\n\t\"\"\"\n\tOpens edited script for further parsing\n\t\"\"\"\n\n\thist = dict()\n\tf1_script = open(file_name)\n\tfor line in f1_script:\n\t\tprocess_line(line, hist)\n\treturn hist\n\ndef process_line(line, hist):\n\t\"\"\"\n\tReads words in edited script to further extract unnecessary characters\n\t\"\"\"\n\n\tstop = set(stopwords.words('english'))\t\t\t\t# sets up to remove most common boring words (ex: 'the', 'at', 'me', etc)\n\tline = line.replace('-', ' ')\t\t\t\t\t\t# replace hyphens with spaces\n\n\tfor word in line.split():\n\t\tword = word.strip(string.punctuation + string.whitespace)\t\t# remove punctuation and redundant whitespace\n\t\tword = word.lower()\t\t\t\t\t\t\t\t# make all letters lowercase to avoid technical difficulties\n\t\tif word not in stop:\t\t\t\t\t\t\t# filter out stopwords\n\t\t\treturn word\n\t\telse:\n\t\t\tpass\n\n\t\thist[word] = hist.get(word, 0) + 1\t\t\t\t# observe frequency of words\n\n# def most_common(hist):\t\t\t\t\t\t\t\t# sorts hist by frequency of words (largest to smallest) instead of by word itself\n# \tt = []\n# \tfor key,value in hist.items():\n# \t\tt.append((value,key))\n\n# \tt.sort(reverse = True)\n# \treturn t\n\n# def print_most_common(hist, num=10):\t\t\t\t\t# prints out most common words\n# \tt = most_common(hist)\n# \tprint 'The most common words are:'\n# \tfor freq,word in t[:num]:\n# \t\tprint word, '\\t', freq\n\n\n\n#edit_script('StarWars.srt')\n#hist = process_script('blahblah.txt')\n#print_most_common(hist, 30)\n\n\nmovies1 = ['StarWars.srt', 'TheGodfather.srt', 'TheMatrix.srt', 'Rocky.srt', 'JurassicPark.srt', 'KillBill1.srt', 'LOTR1.srt', 'ForrestGump.srt']\nmovies2 = ['Frozen.srt', 'HSM.srt', 'Mulan.srt', 'HarryPotter1.srt', 'FindingNemo.srt', 'Up.srt', 'BTTF.srt']\nedit_all(movies1)\nedit_all(movies2)","sub_path":"movie_subtitles.py","file_name":"movie_subtitles.py","file_ext":"py","file_size_in_byte":3232,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"193517307","text":"from __future__ import unicode_literals\n\nfrom django.conf.urls import patterns, url\nfrom django.db import connection\nfrom django.http import HttpResponse\n\nfrom .views import raise_exception\n\n\nurlpatterns = patterns('',\n url(r'^$',\n lambda request: HttpResponse(),\n name='default'\n ),\n url(r'^global$',\n lambda request: HttpResponse(\n connection.tenant.name if connection.tenant else ''\n ),\n name='tenant'\n ),\n url(r'^exception$',\n raise_exception,\n name='exception'\n )\n)\n","sub_path":"tenancy/tests/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":549,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"374243915","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Thu Oct 18 14:43:48 2018\n\n@author: minamelek\n\"\"\"\nimport cv2\nimport os\nimport argparse\nimport logging\nimport sys\nimport time\n\nfrom tf_pose import common\nimport numpy as np\nimport pandas as pd\nfrom tf_pose.estimator import TfPoseEstimator\nfrom tf_pose.networks import get_graph_path, model_wh\nfrom UsedFunctions import manipulate, Get_Coords, Get_Mass, Calculate_D, Calculate_L, Calculate_PCM, Calculate_TCM, Calculate_R, Add_Features_To_dataframe\n\nlogger = logging.getLogger('TfPoseEstimator')\nlogger.setLevel(logging.DEBUG)\nch = logging.StreamHandler()\nch.setLevel(logging.DEBUG)\nformatter = logging.Formatter('[%(asctime)s] [%(name)s] [%(levelname)s] %(message)s')\nch.setFormatter(formatter)\nlogger.addHandler(ch)\n\n\n\"\"\" write your own path here \"\"\"\nvideos_path = './Videos'\nnewpath=os.getcwd()+'/Output'+'/'\nif not os.path.exists(newpath):\n os.makedirs(newpath)\nOUTPUT_PATH=newpath+'/'+'Humans.csv'\n# optional: to activate un comment the first section in the for loop\nvalid_videos = [\".avi\",\".mp4\",\".mov\",\".mkv\",\".rmvb\", \".dv\", \".Ts\"] \nOUTPUTS = []\nfor f in os.listdir(videos_path):\n \"\"\"\n # for including only video formates\n ext = os.path.splitext(f)[1]\n if ext.lower() not in valid_videos:\n continue\n \"\"\"\n print(\"Reading video file \", os.path.join(videos_path,f))\n h_name = os.path.splitext(f)[0]\n parser = argparse.ArgumentParser(description='tf-pose-estimation Video')\n parser.add_argument('--video', type=str, default=os.path.join(videos_path,f))\n parser.add_argument('--resolution', type=str, default='432x368', help='network input resolution. default=432x368')\n parser.add_argument('--model', type=str, default='mobilenet_thin', help='cmu / mobilenet_thin')\n parser.add_argument('--show-process', type=bool, default=False,\n help='for debug purpose, if enabled, speed for inference is dropped.')\n parser.add_argument('--showBG', type=bool, default=True, help='False to show skeleton only.')\n args = parser.parse_args()\n\n logger.debug('initialization %s : %s' % (args.model, get_graph_path(args.model)))\n w, h = model_wh(args.resolution)\n e = TfPoseEstimator(get_graph_path(args.model), target_size=(w, h))\n cap = cv2.VideoCapture(args.video)\n ret_val = True\n if cap.isOpened() is False:\n print(\"Error opening video stream or file\")\n count = 0\n while cap.isOpened() and ret_val:\n begin_counting=time.time() # For time computing\n ret_val, image = cap.read()\n if not ret_val:\n break\n humans = e.inference(image)\n if len(humans)==0:\n print(\"No humans detected in this frame\")\n count = count + 1\n continue\n Co_ordinates=manipulate(humans, h_name+'_'+str(count)) # Computes the Co-ordinates from the given data by O-Nect\n \n print('Time taken for Co-ordinate calculations for {} Frames is {:.3f} ms'.format(len(Co_ordinates),(time.time()-begin_counting)*1000))\n \n # Extracting X, Y Coordinates\n start=time.time()\n X_Coords, Y_Coords= Get_Coords(Co_ordinates)\n print('Time taken for Co-ordinate extractions for {} Frames is {:.3f} ms'.format(len(Co_ordinates),(time.time()-start)*1000))\n \n start=time.time()\n PCM_Frames= Calculate_PCM(X_Coords, Y_Coords)\n print('Time taken for PCM for {} Frames is {:.3f} ms'.format(len(PCM_Frames),(time.time()-start)*1000))\n \n start=time.time()\n TCM_x, TCM_y= Calculate_TCM(PCM_Frames)\n print('Time taken for TCM for {} Frames is {:.3f} ms'.format(len(TCM_x),(time.time()-start)*1000))\n \n start=time.time()\n L= Calculate_L(TCM_x, TCM_y, PCM_Frames)\n print('Time taken for L features for {} Frames is {:.3f} ms'.format(len(PCM_Frames),(time.time()-start)*1000))\n \n start=time.time()\n D1, D2, D3 = Calculate_D(PCM_Frames, TCM_x, TCM_y, 'Degrees')\n print('Time taken for D1, D2, D3 features for {} Frames is {:.3f} ms'.format(len(PCM_Frames),(time.time()-start)*1000))\n \n start=time.time()\n R=Calculate_R(PCM_Frames)\n print('Time taken for R feature for {} Frames is {:.3f} ms'.format(len(PCM_Frames),(time.time()-start)*1000))\n \n start=time.time()\n out=Add_Features_To_dataframe(Co_ordinates, PCM_Frames, TCM_x, TCM_y, L, R, D1, D2, D3)\n print('Time taken for adding features to dataframe for {} Frames is {:.3f} ms'.format(len(Co_ordinates),(time.time()-start)*1000))\n \n print('Time taken the for whole file of {} Frames is {:.3f} ms'.format(len(PCM_Frames),(time.time()-begin_counting)*1000))\n count = count + 1\n OUTPUTS.append(out)\n \nresult = pd.concat(OUTPUTS)\nresult.to_csv(OUTPUT_PATH)","sub_path":"tf-openpose/MINArun/MainRun.py","file_name":"MainRun.py","file_ext":"py","file_size_in_byte":4846,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"256863808","text":"import os\n\ndef getRegisters():\n registers = dict()\n cur_path = os.path.dirname(__file__)\n path = cur_path + '/Instructions/Registers.txt'\n with open(path, 'r') as f:\n instructions = f.read().split('\\n')\n for i in instructions:\n currentIns = i.split()\n registers[currentIns[1]] = currentIns[0]\n return registers\n","sub_path":"src/HexTranslator/InstructionSet/Registers.py","file_name":"Registers.py","file_ext":"py","file_size_in_byte":350,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"342015990","text":"#https://docs.python.org/2/library/argparse.html\n\nimport argparse\ndef arg_parsing():\n parser = argparse.ArgumentParser(description='Test ArgumentParser')\n parser.add_argument(\"--input\", required=True,\n help='Input directory')\n args = parser.parse_args()\n args = vars(args)\n #args['input'] = os.path.abspath(args['input'])\n return args\n \ndef arg_parsing_v2(params):\n parser = argparse.ArgumentParser(description='Test ArgumentParser')\n for param in params:\n param='-'+str(param)\n parser.add_argument(param, required=True,\n help='Input parammeter')\n args = parser.parse_args()\n args = vars(args)\n return args\n\n#ARGS = arg_parsing()\n#pathresultTVDI = ARGS['input']\n#print(pathresultTVDI)\n\n#python2 argu.py --txtinput \"hello\" --hallo \"xin chao\"\n#python2 argu.py --input \"/opt/lampp/htdocs/python/upload/0901201993905am_h1.tif\" --hallo \"xin chao\"\n\n\nparams=['input','hallo','xinchao']\nARGS = arg_parsing_v2(params)\n\n# python argu.py -input \"input\" -hallo \"hallo\" -xinchao \"xinchao\"\n\ntxtinput = ARGS['input']\nprint(txtinput)\n\nhallo = ARGS['hallo']\nprint(hallo)\n\nxinchao = ARGS['xinchao']\nprint(xinchao)","sub_path":"argu.py","file_name":"argu.py","file_ext":"py","file_size_in_byte":1195,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"257746993","text":"import csv\nimport cv2\nimport numpy as np\nimport keras\nimport gc\n\nlines = []\nwith open('./training_data/driving_log.csv') as csvfile:\n\treader =csv.reader(csvfile)\n\t#skip header\n\tnext(reader, None)\n\tfor line in reader:\n\t\tlines.append(line)\n\nimages = []\nmeasurements = []\n\n#due to mem constraints only use random side cameras and flipped images to augment\nline_count = 0\nfor line in lines:\n\tline_count +=1\n\tif line_count%3 == 0: \n\t\tfor i in range(3):\n\t\t\tsource_path = line[i]\n\t\t\tfilename = source_path.split('/')[-1]\n\t\t\tlocal_path = \"./training_data/IMG/\" + filename\n\t\t\timage = cv2.imread(local_path)\n\t\t\timages.append(image)\n\t\tmeasurement = line[3]\n\t\tmeasurements.append(measurement)\n\t\t#need to correct for left and right cameras\n\t\tmeasurements.append(float(measurement)+ 0.15)\n\t\tmeasurements.append(float(measurement) - 0.15)\n\telse:\n\t\tsource_path = line[0]\n\t\tfilename = source_path.split('/')[-1]\n\t\tlocal_path = \"./training_data/IMG/\" + filename\n\t\timage = cv2.imread(local_path)\n\t\timages.append(image)\n\t\tmeasurements.append(line[3])\n\n\n#tried using the flipped images but it made training a lot slower and had already recorder the clockwise laps\naugmented_images = []\naugmented_measurements = []\naugmented_count = 0\nfor image, measurement in zip(images, measurements):\n\taugmented_count +=1\n\taugmented_images.append(image)\n\taugmented_measurements.append(measurement)\n\tif augmented_count%3 == 0:\n\t\tflipped_image = cv2.flip(image, 1)\n\t\tflipped_measurement = float(measurement) * -1.0\n\t\taugmented_images.append(flipped_image)\n\t\taugmented_measurements.append(flipped_measurement)\n\nX_train = np.array(augmented_images)\ny_train = np.array(augmented_measurements)\nprint(len(X_train))\n\nfrom keras.models import Sequential\nfrom keras.layers import Flatten, Dense, Lambda, Convolution2D, Cropping2D, Dropout\n\nmodel = Sequential()\n\n#crop image to get rid of sky and font of car\nmodel.add(Cropping2D(cropping=((65,23),(0,0)), input_shape=(160,320,3)))\nprint(model.output_shape)\n#normalize features -- color image normalization\nmodel.add(Lambda(lambda x: x / 255.0 - 0.5))\nprint(model.output_shape)\n#try nvidias autonomous vehicle netowrk architecture\nmodel.add(Convolution2D(24,5,5, subsample=(2,2), activation=\"relu\"))\nprint(model.output_shape)\nmodel.add(Convolution2D(36,5,5, subsample=(2,2), activation=\"relu\"))\nprint(model.output_shape)\nmodel.add(Convolution2D(48,5,5, subsample=(2,2), activation=\"relu\"))\nprint(model.output_shape)\nmodel.add(Convolution2D(64,3,3, activation=\"relu\"))\nprint(model.output_shape)\nmodel.add(Convolution2D(64,3,3, activation=\"relu\"))\nprint(model.output_shape)\nmodel.add(Flatten())\nprint(model.output_shape)\nmodel.add(Dense(100))\nprint(model.output_shape)\nmodel.add(Dropout(0.5))\nmodel.add(Dense(50))\nprint(model.output_shape)\nmodel.add(Dense(10))\nprint(model.output_shape)\nmodel.add(Dense(1))\nprint(model.output_shape)\nmodel.compile(optimizer='adam', loss='mse')\n\n#by default already shuffles\nmodel.fit(X_train, y_train, validation_split=0.2, nb_epoch=3)\n\nmodel.save('model.h5')\n\n\n","sub_path":"model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":2997,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"201388446","text":"\"\"\"\nStack Rasters\n-------------\n\ntools for stacking rasters into multitemporal data\n\"\"\"\n# try:\nfrom atm.images import raster\n# except ImportError:\n# from ..atm_io import raster\n\nimport numpy as np\n\ndef load_and_stack(files, out_filename):\n \"\"\"Load rasters, flatten, and stack in memory mapped np array.\n \n Parameters\n ----------\n files: list\n sorted list of raster files to read\n filename:\n name of memory maped fie\n \n Returns\n -------\n data: np.memorymap\n memory mapped data\n shape: tuple\n shape of the input rasters\n \"\"\"\n for fdx in range(len(files)):\n f = files[fdx]\n \n if fdx == 0:\n \n r, md = raster.load_raster(f)\n \n shape = (len(files), r.shape[0] * r.shape[1])\n data = np.memmap(\n out_filename, dtype='float32', mode='w+', shape=shape\n )\n \n shape = r.shape\n data[0] = r.flatten()\n else:\n data[fdx] = raster.load_raster(f)[0].flatten()\n \n return data, shape\n \n \ndef stack_np_arrays_from_file (files, out_filename):\n \"\"\"Loads and stacks data from nparrays that have been written to a file\n \n Parameters\n ----------\n files: list\n sorted list of files to load\n out_filename: path\n file to create stacked data in\n \n Returns\n -------\n data:\n mameory mapped data, fist index is timestep, second is flattened array\n index.\n shape:\n flattened shape for the firest array read\n \"\"\"\n for fdx in range(len(files)):\n f = files[fdx]\n \n if fdx == 0:\n \n init = np.fromfile(f).flatten()\n \n \n shape = (len(files), init.shape[0] )\n data = np.memmap(\n out_filename, dtype='float32', mode='w+', shape=shape\n )\n \n shape = init.shape\n data[0] = init\n else:\n data[fdx] = np.fromfile(f).flatten()\n\n \n \n #~ print data.shape\n return data, shape\n","sub_path":"atm/tools/stack_rasters.py","file_name":"stack_rasters.py","file_ext":"py","file_size_in_byte":2127,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"586739882","text":"#! /usr/bin/env python\n##########################################################################\n# NSAP - Copyright (C) CEA, 2013\n# Distributed under the terms of the CeCILL-B license, as published by\n# the CEA-CNRS-INRIA. Refer to the LICENSE file or to\n# http://www.cecill.info/licences/Licence_CeCILL-B_V1-en.html\n# for details.\n##########################################################################\n\n# System import\nimport os\nimport glob\nimport numpy\nimport nibabel\nimport scipy\nimport json\n\n# Dipy import\nfrom dipy.segment.clustering import QuickBundles\n\n# Clindmri import\nfrom clindmri.tractography.pydipy import deterministic\nfrom clindmri.tractography.gaussian_processes import FiberGP\nfrom clindmri.tractography.utils import resample\nfrom clindmri.tractography.utils import filter_by_length\nfrom clindmri.clustering.agglomerative_clustering import fdist\nfrom clindmri.clustering.agglomerative_clustering import agglomerative_clustering\nfrom clindmri.registration.utils import extract_image\nfrom clindmri.segmentation.fsl import bet2\nfrom clindmri.plot.slicer import plot_image\nimport clindmri.plot.pvtk as pvtk\nfrom clindmri.plot.colors import line_colors\n\n\n# Global parameters\ndiffusion_file = \"/volatile/imagen/dmritest/001/raw/hardi-b1500-1-001.nii.gz\"\nbvecs_file = \"/volatile/imagen/dmritest/001/raw/hardi-b1500-1-001.bvec\"\nbvals_file = \"/volatile/imagen/dmritest/001/raw/hardi-b1500-1-001.bval\"\nmask_file = \"/volatile/imagen/dmritest/001/cortex_mask.nii.gz\" #None\noutdir = \"/volatile/imagen/dmritest/001/processed/tGP\"\nuse_vtk = False\nnb_seeds_per_voxel = 1\ndisplay_amount = 20000\nrfactor = 3\nspeed_factor = 1\nmin_length = 10\nactor_ang = (-90, 0, -90)\n\n\n\"\"\"\nDefine first a quality check folder.\n\"\"\"\nqcdir = os.path.join(outdir, \"qc\")\nif not os.path.isdir(qcdir):\n os.makedirs(qcdir)\n\n\n\"\"\"\nTest\n----\n\"\"\"\nfiber1 = []\nderiv = 1\ntensor1 = []\neigval = 0.1\nfor i in range(40):\n fiber1.append([20 * numpy.sin(i * numpy.pi / 40 ), i, 5])\n eigval += 0.1\nfiber1= numpy.asarray(fiber1)\n\n#fiber1 = scipy.signal.resample(fiber1, 200)\n\nfiber2 = []\nderiv = 1\nfor i in range(40):\n fiber2.append([ - 20 * numpy.sin(i * numpy.pi / 40 ) + 20, i, 5])\nfiber2= numpy.asarray(fiber2)\n\nif 0:\n fiber1 = numpy.array([\n [ 1.7326782, 0.25029223, 5. ],\n [ 2.70803832, 1.71739357, 5. ],\n [ 3.67926713, 2.43806875, 5. ],\n [ 4.0906216, 3.27442217, 5. ],\n [ 4.27240855, 4.4456303, 5. ],\n [ 5.2095575, 5.5033897, 5. ],\n [ 5.53538539, 6.29320943, 5. ],\n [ 5.59439468, 7.36038572, 5. ],\n [ 6.06738832, 8.2942982, 5. ],\n [ 6.92363806, 9.03236326, 5. ]])\n fiber2 = numpy.array([\n [ 1.1796562, 0.16609008, 5. ],\n [ 1.19413916, 1.96607455, 5. ],\n [ 1.85886967, 2.93353053, 5. ],\n [ 2.79900016, 3.09145943, 5. ],\n [ 3.26364434, 4.95455423, 5. ],\n [ 3.46143541, 5.12321982, 5. ],\n [ 3.70400735, 6.00718094, 5. ],\n [ 4.64417862, 7.91226521, 5. ],\n [ 4.86004664, 8.64782218, 5. ],\n [ 5.01891052, 9.34209871, 5. ]])\n\n\n\"\"\"\nNon-diffusion-weighted mask\n---------------------------\n\nFor tractography, we need to generate a mask within which we\nconstrain tractography. We first select the first non-diffusion weighted\nvolume of the DTI sequence and then use 'bet2' on this image with a fractional\nintensity threshold of 0.25 (this is generally a robust threshold to\nremove unwanted tissue from a non-diffusion weighted image) and the 'm' option\nthat creates a binary 'nodif_brain_mask' image.\n\"\"\"\nif mask_file is None:\n\n # Extract the b0 map\n bvals = numpy.loadtxt(bvals_file).tolist()\n b0_index = bvals.index(0)\n b0_file = os.path.join(outdir, \"nodif.nii.gz\")\n if not os.path.isfile(b0_file):\n extract_image(diffusion_file, index=b0_index, out_file=b0_file)\n snap_file = os.path.join(qcdir, \"nodif.png\")\n plot_image(b0_file, snap_file=snap_file, name=\"nodif\")\n\n # Extract the brain mask from the b0 map\n b0_brain_file = os.path.join(outdir, \"nodif_brain\")\n bet_files = glob.glob(b0_brain_file + \"*\")\n if len(bet_files) == 0:\n (output, mask_file, mesh_file, outline_file,\n inskull_mask_file, inskull_mesh_file,\n outskull_mask_file, outskull_mesh_file, outskin_mask_file,\n outskin_mesh_file, skull_mask_file) = bet2(\n b0_file,\n b0_brain_file,\n m=True,\n f=0.25)\n else:\n mask_file = sorted(bet_files)[0]\n if not os.path.isfile(mask_file):\n raise IOError(\"FileDoesNotExist: '{0}'.\".format(mask_file))\n snap_file = os.path.join(qcdir, \"bet.png\")\n plot_image(b0_file, contour_file=mask_file, snap_file=snap_file,\n name=\"bet\")\n\n\n\"\"\"\nTractography\n------------\n\nWe use dipy to generate a streamline tractography. Play with the\n'nb_seeds_per_voxel' parameter to increase/decrease the fiber density. Then\nwe count the tracks that start and end at each label pair.\nFinally, computed fibers are length filtered.\n\"\"\"\ntrack_outdir = os.path.join(outdir, \"streamline\")\ntrack_file = os.path.join(track_outdir, \"fibers.trk\")\ntrack_filtered_file = os.path.join(track_outdir, \"filtered_fibers.trk\")\nif not os.path.isdir(track_outdir):\n os.mkdir(track_outdir)\nif not os.path.isfile(track_file):\n trackvis_fibers, trackvis_header = deterministic(\n diffusion_file,\n bvecs_file,\n bvals_file,\n track_file,\n mask_file=mask_file,\n order=4,\n nb_seeds_per_voxel=nb_seeds_per_voxel,\n step=0.5)\nelse:\n trackvis_fibers, trackvis_header = nibabel.trackvis.read(\n track_file, as_generator=False, points_space=\"voxel\")\nif not os.path.isfile(track_filtered_file):\n fibers = [track_item[0] for track_item in trackvis_fibers]\n fibers = filter_by_length(fibers, min_length)\n streamlines = ((track, None, None) for track in fibers)\n nibabel.trackvis.write(track_filtered_file, streamlines, trackvis_header,\n points_space=\"voxel\")\nelse:\n trackvis_fibers, trackvis_header = nibabel.trackvis.read(\n track_filtered_file, as_generator=False, points_space=\"voxel\")\n fibers = [track_item[0] for track_item in trackvis_fibers]\n\nif use_vtk:\n ren = pvtk.ren()\n colors = line_colors(fibers)\n actor = pvtk.tubes(fibers, colors)\n actor.RotateX(actor_ang[0])\n actor.RotateY(actor_ang[1])\n actor.RotateZ(actor_ang[2])\n pvtk.add(ren, actor)\n ren.SetBackground(1, 1, 1)\n pvtk.record(ren, qcdir, \"fibers\", az_ang=45, n_frames=2)\n pvtk.record(ren, qcdir, \"fibers\", n_frames=36, az_ang=10, animate=True,\n delay=25)\n pvtk.show(ren)\n pvtk.clear(ren)\n\n\n\"\"\"\nFiber clustering\n----------------\n\nBased on an agglomerative clustering, and a geometric distance.\n\"\"\"\n\nclustering_outdir = os.path.join(outdir, \"clustering\")\ncluster_file = os.path.join(clustering_outdir, \"clusters.json\")\nif not os.path.isdir(clustering_outdir):\n os.mkdir(clustering_outdir)\nif not os.path.isfile(cluster_file):\n fibers_18 = [resample(track, nb_pol=18) for track in fibers]\n qb = QuickBundles(threshold=10.)\n clusters_ = qb.cluster(fibers_18)\n clusters = {}\n for cnt, cluster in enumerate(clusters_):\n clusters[str(cnt)] = {\"indices\": cluster.indices}\n with open(cluster_file, \"w\") as open_file:\n json.dump(clusters, open_file, indent=4)\nelse:\n with open(cluster_file) as open_file:\n clusters = json.load(open_file)\n\nif 1: #use_vtk:\n ren = pvtk.ren()\n colors = numpy.ones((len(fibers),))\n nb_clusters = len(clusters)\n for clusterid, item in clusters.items():\n indices = item[\"indices\"]\n colors[indices] = numpy.random.rand()\n actor = pvtk.line(fibers, colors.tolist())\n actor.RotateX(actor_ang[0])\n actor.RotateY(actor_ang[1])\n actor.RotateZ(actor_ang[2])\n pvtk.add(ren, actor)\n ren.SetBackground(1, 1, 1)\n #pvtk.record(ren, qcdir, \"clusters\", az_ang=45, n_frames=2)\n pvtk.record(ren, qcdir, \"clusters\", n_frames=36, az_ang=10, animate=True,\n delay=25)\n pvtk.show(ren)\n pvtk.clear(ren)\n print(stop)\n\n\n\"\"\"\nBundle statistic\n----------------\n\nCombine the N fiber of a bundle by simply averaging the GPs corresponding to\nthese fibers, and obtain a GP that corresponds to the indicator function\nof the fiber bundle.\n\"\"\"\nstats_outdir = os.path.join(outdir, \"statistics\")\nbundle_id = \"50\"\nmean_file = os.path.join(stats_outdir, \"mean_{0}.nii.gz\".format(bundle_id))\nvar_file = os.path.join(stats_outdir, \"var_{0}.nii.gz\".format(bundle_id))\nif not os.path.isdir(stats_outdir):\n os.mkdir(stats_outdir)\nif not (os.path.isfile(mean_file) and os.path.isfile(var_file)):\n bundle_mean_array = numpy.zeros(trackvis_header[\"dim\"])\n bundle_var_array = numpy.zeros(trackvis_header[\"dim\"])\n nb_fibers = len(clusters[bundle_id][\"indices\"])\n for index in clusters[bundle_id][\"indices\"]:\n track = fibers[index]\n gp = FiberGP(track, rfactor)\n bundle_mean_array += gp.get_mean_field(shape=trackvis_header[\"dim\"])\n bundle_var_array += gp.get_variance_field(shape=trackvis_header[\"dim\"])\n bundle_mean_array /= float(nb_fibers)\n bundle_var_array /= float(nb_fibers)**2\n nifti_image = nibabel.Nifti1Image(bundle_mean_array, numpy.eye(4))\n nibabel.save(nifti_image, mean_file)\n nifti_image = nibabel.Nifti1Image(bundle_var_array, numpy.eye(4))\n nibabel.save(nifti_image, var_file)\n\n if 1: #use_vtk:\n bundle_fibers = [fibers[index] \n for index in clusters[bundle_id][\"indices\"]]\n ren = pvtk.ren()\n actor = pvtk.line(bundle_fibers, 1)\n pvtk.add(ren, actor)\n ren.SetBackground(1, 1, 1)\n pvtk.record(ren, qcdir, \"bundle_{0}\".format(bundle_id), az_ang=45,\n n_frames=2)\n pvtk.show(ren)\n pvtk.clear(ren)\n\n\n","sub_path":"clindmri/scripts/fiber_bundles.py","file_name":"fiber_bundles.py","file_ext":"py","file_size_in_byte":10014,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"390378714","text":"import time\nimport numpy as np\nimport matplotlib.pyplot as plt\n\nfrom out_put import log\n\n\ndef inference(w, b, x):\n \"\"\"\n 做一个预测,同过给定一个w、b,之后给出任意一个x,都可以得到一个预测值y\n :param w: 线性回归的斜率,x的系数\n :param b: 与x轴的截距\n :param x: 因变量\n :return: 预测值\n \"\"\"\n pred_y = w * x + b\n return pred_y\n\n\ndef eval_loss(w, b, x_list, gt_y_list):\n \"\"\"\n cost function, 做一个Loss计算\n :param w: 线性回归的斜率,x的系数\n :param b: 与x轴的截距\n :param x_list: x的集合\n :param gt_y_list: 实际的y值集合\n gt : ground trues 实际值\n :return: 所有的gt_y和pred_y的方差和\n \"\"\"\n avg_loss = 0\n for i in range(len(x_list)):\n pred_y = inference(w, b, x_list[i])\n avg_loss += 0.5 * (pred_y - gt_y_list[i]) ** 2\n avg_loss /= len(gt_y_list)\n return avg_loss\n\n\ndef gradient(pred_y, gt_y, x):\n \"\"\"\n 求梯度, 关于w和b\n \"\"\"\n diff = pred_y - gt_y\n dw = diff * x\n db = diff\n return dw, db\n\n\ndef cal_step_gradient(batch_x_list, batch_gt_y_list, w, b, lr):\n \"\"\"\n 取一部分的数据做计算,其中的x、y 对w、b所带来的更新\n :param batch_x_list: 选取的部分x样本\n :param batch_gt_y_list: 选取的部分y样本\n :param lr: 学习率(阿发)\n :return: 经过一次迭代之后,w、b的值\n \"\"\"\n avg_dw, avg_db = 0, 0\n batch_size = len(batch_x_list)\n for i in range(batch_size):\n pred_y = inference(w, b, batch_x_list[i])\n dw, db = gradient(pred_y, batch_gt_y_list[i], batch_x_list[i])\n avg_dw += dw\n avg_db += db\n avg_dw /= batch_size\n avg_db /= batch_size\n w -= lr * avg_dw\n b -= lr * avg_db\n return w, b\n\n\ndef train_Linear(x_list, gt_y_list, batch_size, lr, max_iter):\n \"\"\"\n\n :param x_list:\n :param gt_y_list:\n :param batch_size: 全部的值\n :param lr: 学习率\n :param max_iter: 迭代次数,要更新的次数\n :return:\n \"\"\"\n w, b = 0, 0\n num_samples = len(x_list)\n\n # plt.ion()\n # fig, ax = plt.subplots()\n # plt.rcParams['lines.markersize'] = 3\n for i in range(max_iter):\n # 随机抽取(batch_size)个样本\n batch_idxs = np.random.choice(num_samples, batch_size)\n batch_x = [x_list[j] for j in batch_idxs]\n batch_y = [gt_y_list[j] for j in batch_idxs]\n w, b = cal_step_gradient(batch_x, batch_y, w, b, lr)\n s1 = 'w:{}, b:{}'.format(w, b)\n s2 = 'loss is {}'.format(eval_loss(w, b, x_list, gt_y_list))\n log('s_1', s1, '\\n', 's_2', s2)\n\n # ax.cla()\n # time.sleep(1)\n return w, b","sub_path":"lesson_3/Linear_Regression.py","file_name":"Linear_Regression.py","file_ext":"py","file_size_in_byte":2700,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"421315396","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreate Time: 2021/4/25 8:23\nAuthor: Kevin\nPython Version:3.7.6\n\"\"\"\nfrom PIL import Image\nfrom pylab import *\nimport numpy as np\nimport cv2\n\ndef histeq(im,nbr_bins = 256):\n \"\"\"对一幅灰度图像进行直方图均衡化\"\"\"\n #计算图像的直方图\n #在numpy中,也提供了一个计算直方图的函数histogram(),第一个返回的是直方图的统计量,第二个为每个bins的中间值\n imhist,bins = np.histogram(im.flatten(),nbr_bins,normed= True)\n cdf = imhist.cumsum() #\n cdf = 255.0 * cdf / cdf[-1]\n #使用累积分布函数的线性插值,计算新的像素值\n im2 = np.interp(im.flatten(),bins[:-1],cdf)\n return im2.reshape(im.shape),cdf\n\n\npil_im = Image.open(r'E:\\kevin\\THX\\code\\plotfigure\\zhupi1.png') #打开原图\npil_im_gray = pil_im.convert('L') #转化为灰度图像\npil_im_gray.show() #显示灰度图像\n\nim = np.array(Image.open(r'E:\\kevin\\THX\\code\\plotfigure\\zhupi1.png').convert('L'))\n# figure()\n# hist(im.flatten(),256)\n\nim2,cdf = histeq(im)\n# figure()\n# hist(im2.flatten(),256)\n# show()\n\nim2 = Image.fromarray(uint8(im2))\nim2.show()\n# print(cdf)\n# plot(cdf)\nim2.save(\"zhupi_junheng.png\")\n\n#opencv EqualizeHist\ncv2.imread(r'E:\\kevin\\THX\\code\\plotfigure\\zhupi1.png',0)\ncv2.imshow('equalhist',cv2.equalizeHist(im2))","sub_path":"terahertz/plotfigure/cvCalHist.py","file_name":"cvCalHist.py","file_ext":"py","file_size_in_byte":1326,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"14957402","text":"import numpy as np\nimport cv2\nimport dlib\nfrom scipy.spatial import distance as dist\nfrom scipy.spatial import ConvexHull\n\nPREDICTOR_PATH = \"shape_predictor_68_face_landmarks.dat\"\n\nFULL_POINTS = list(range(0, 68))\nFACE_POINTS = list(range(17, 68))\nUPFACE_POINTS = list(range(0, 48))\nJAWLINE_POINTS = list(range(0, 17))\nRIGHT_EYEBROW_POINTS = list(range(17, 22))\nLEFT_EYEBROW_POINTS = list(range(22, 27))\nNOSE_POINTS = list(range(27, 36))\nRIGHT_EYE_POINTS = list(range(36, 42))\nLEFT_EYE_POINTS = list(range(42, 48))\nMOUTH_OUTLINE_POINTS = list(range(48, 61))\nMOUTH_INNER_POINTS = list(range(61, 68))\nMOUTH_POINTS = list(range(48, 68))\n\ndetector = dlib.get_frontal_face_detector()\n\npredictor = dlib.shape_predictor(PREDICTOR_PATH)\n\n#Compute Eyes\ndef eye_size(eye):\n eyeWidth = dist.euclidean(eye[0], eye[3])\n hull = ConvexHull(eye)\n eyeCenter = np.mean(eye[hull.vertices, :], axis=0)\n\n eyeCenter = eyeCenter.astype(int)\n\n return int(eyeWidth), eyeCenter\n\n\ndef place_eye(frame, eyeCenter, eyeSize):\n eyeSize = int(eyeSize * 1.5)\n\n x1 = int(eyeCenter[0, 0] - (eyeSize / 2))\n x2 = int(eyeCenter[0, 0] + (eyeSize / 2))\n y1 = int(eyeCenter[0, 1] - (eyeSize / 2))\n y2 = int(eyeCenter[0, 1] + (eyeSize / 2))\n\n h, w = frame.shape[:2]\n\n # check for clipping\n if x1 < 0:\n x1 = 0\n if y1 < 0:\n y1 = 0\n if x2 > w:\n x2 = w\n if y2 > h:\n y2 = h\n\n # re-calculate the size to avoid clipping\n eyeOverlayWidth = x2 - x1\n eyeOverlayHeight = y2 - y1\n\n # calculate the masks for the overlay\n eyeOverlay = cv2.resize(imgEye, (eyeOverlayWidth, eyeOverlayHeight), interpolation=cv2.INTER_AREA)\n mask = cv2.resize(orig_mask_eye, (eyeOverlayWidth, eyeOverlayHeight), interpolation=cv2.INTER_AREA)\n mask_inv = cv2.resize(orig_mask_inv_eye, (eyeOverlayWidth, eyeOverlayHeight), interpolation=cv2.INTER_AREA)\n\n # take ROI for the verlay from background, equal to size of the overlay image\n roi = frame[y1:y2, x1:x2]\n\n # roi_bg contains the original image only where the overlay is not, in the region that is the size of the overlay.\n roi_bg = cv2.bitwise_and(roi, roi, mask=mask_inv)\n\n # roi_fg contains the image pixels of the overlay only where the overlay should be\n roi_fg = cv2.bitwise_and(eyeOverlay, eyeOverlay, mask=mask)\n\n # join the roi_bg and roi_fg\n dst = cv2.add(roi_bg, roi_fg)\n\n # place the joined image, saved to dst back over the original image\n frame[y1:y2, x1:x2] = dst\n\n#Compute Nose\ndef nose_size(nose):\n noseWidth = dist.euclidean(nose[0], nose[8])\n hull = ConvexHull(nose)\n noseCenter = np.mean(nose[hull.vertices, :], axis=0)\n\n noseCenter = noseCenter.astype(int)\n\n return int(noseWidth), noseCenter\n\ndef place_nose(frame, noseCenter, noseSize):\n noseSize = int(noseSize * 1.5)\n\n x1 = int(noseCenter[0, 0] - (noseSize / 2))\n x2 = int(noseCenter[0, 0] + (noseSize / 2))\n y1 = int(noseCenter[0, 1] - (noseSize / 2) * 0.4)\n y2 = int(noseCenter[0, 1] + (noseSize / 2) * 0.4)\n\n h, w = frame.shape[:2]\n\n # check for clipping\n if x1 < 0:\n x1 = 0\n if y1 < 0:\n y1 = 0\n if x2 > w:\n x2 = w\n if y2 > h:\n y2 = h\n\n # re-calculate the size to avoid clipping\n noseOverlayWidth = x2 - x1\n noseOverlayHeight = y2 - y1\n # calculate the masks for the overlay\n noseOverlay = cv2.resize(imgNose, (noseOverlayWidth, noseOverlayHeight), interpolation=cv2.INTER_AREA)\n mask = cv2.resize(origin_mask_nose, (noseOverlayWidth, noseOverlayHeight), interpolation=cv2.INTER_AREA)\n mask_inv = cv2.resize(orig_mask_inv_nose, (noseOverlayWidth, noseOverlayHeight), interpolation=cv2.INTER_AREA)\n\n # take ROI for the verlay from background, equal to size of the overlay image\n roi = frame[y1:y2, x1:x2]\n\n # roi_bg contains the original image only where the overlay is not, in the region that is the size of the overlay.\n roi_bg = cv2.bitwise_and(roi, roi, mask=mask_inv)\n\n # roi_fg contains the image pixels of the overlay only where the overlay should be\n roi_fg = cv2.bitwise_and(noseOverlay, noseOverlay, mask=mask)\n\n # join the roi_bg and roi_fg\n dst = cv2.add(roi_bg, roi_fg)\n\n # place the joined image, saved to dst back over the original image\n frame[y1:y2, x1:x2] = dst\n\n#Compute Hat\ndef hat_size(hat):\n hatWidth = dist.euclidean(hat[0], hat[9])\n hatCenter = hat[10]\n\n return int(hatWidth), hatCenter\n\ndef place_hat(frame, hatCenter, hatSize):\n hatSize = int(hatSize * 1.5)\n\n x1 = int(hatCenter[0, 0] - (hatSize / 2))\n x2 = int(hatCenter[0, 0] + (hatSize / 2))\n y1 = int(hatCenter[0, 1]*0.8 - (200*hatSize / 201)*0.9)\n y2 = int(hatCenter[0, 1]*0.8 + (hatSize / 201)*0.9)\n\n h, w = frame.shape[:2]\n\n # check for clipping\n if x1 < 0:\n x1 = 0\n if y1 < 0:\n y1 = 0\n if x2 > w:\n x2 = w\n if y2 > h:\n y2 = h\n\n # re-calculate the size to avoid clipping\n hatOverlayWidth = x2 - x1\n hatOverlayHeight = y2 - y1\n # calculate the masks for the overlay\n hatOverlay = cv2.resize(imgHat, (hatOverlayWidth, hatOverlayHeight), interpolation=cv2.INTER_AREA)\n mask = cv2.resize(origin_mask_hat, (hatOverlayWidth, hatOverlayHeight), interpolation=cv2.INTER_AREA)\n mask_inv = cv2.resize(orig_mask_inv_hat, (hatOverlayWidth, hatOverlayHeight), interpolation=cv2.INTER_AREA)\n\n # take ROI for the verlay from background, equal to size of the overlay image\n roi = frame[y1:y2, x1:x2]\n\n # roi_bg contains the original image only where the overlay is not, in the region that is the size of the overlay.\n roi_bg = cv2.bitwise_and(roi, roi, mask=mask_inv)\n\n # roi_fg contains the image pixels of the overlay only where the overlay should be\n roi_fg = cv2.bitwise_and(hatOverlay, hatOverlay, mask=mask)\n\n # join the roi_bg and roi_fg\n dst = cv2.add(roi_bg, roi_fg)\n\n # place the joined image, saved to dst back over the original image\n frame[y1:y2, x1:x2] = dst\n\n#Compute Mostache\ndef moustache_size(moustache):\n moustacheWidth = dist.euclidean(moustache[0], moustache[6])\n hull = ConvexHull(moustache)\n moustacheCenter = np.mean(moustache[hull.vertices, :], axis=0)\n\n moustacheCenter = moustacheCenter.astype(int)\n\n return int(moustacheWidth), moustacheCenter\n\ndef place_moustache(frame, moustacheCenter, moustacheSize):\n moustacheSize = int(moustacheSize * 1.5)\n\n x1 = int(moustacheCenter[0, 0] - (moustacheSize / 2))\n x2 = int(moustacheCenter[0, 0] + (moustacheSize / 2))\n y1 = int(moustacheCenter[0, 1] - (moustacheSize / 3))\n y2 = int(moustacheCenter[0, 1] + (moustacheSize / 2))\n\n h, w = frame.shape[:2]\n\n # check for clipping\n if x1 < 0:\n x1 = 0\n if y1 < 0:\n y1 = 0\n if x2 > w:\n x2 = w\n if y2 > h:\n y2 = h\n\n # re-calculate the size to avoid clipping\n moustacheOverlayWidth = x2 - x1\n moustacheOverlayHeight = y2 - y1\n # calculate the masks for the overlay\n moustacheOverlay = cv2.resize(imgMoustache, (moustacheOverlayWidth, moustacheOverlayHeight), interpolation=cv2.INTER_AREA)\n mask = cv2.resize(origin_mask_moustache, (moustacheOverlayWidth, moustacheOverlayHeight), interpolation=cv2.INTER_AREA)\n mask_inv = cv2.resize(orig_mask_inv_moustache, (moustacheOverlayWidth, moustacheOverlayHeight), interpolation=cv2.INTER_AREA)\n\n # take ROI for the verlay from background, equal to size of the overlay image\n roi = frame[y1:y2, x1:x2]\n\n # roi_bg contains the original image only where the overlay is not, in the region that is the size of the overlay.\n roi_bg = cv2.bitwise_and(roi, roi, mask=mask_inv)\n\n # roi_fg contains the image pixels of the overlay only where the overlay should be\n roi_fg = cv2.bitwise_and(moustacheOverlay, moustacheOverlay, mask=mask)\n\n # join the roi_bg and roi_fg\n dst = cv2.add(roi_bg, roi_fg)\n\n # place the joined image, saved to dst back over the original image\n frame[y1:y2, x1:x2] = dst\n\n#Compute Close Mouth\ndef mouth_size(mouth):\n mouthWidth = dist.euclidean(mouth[0], mouth[6])\n hull = ConvexHull(mouth)\n mouthCenter = np.mean(mouth[hull.vertices, :], axis=0)\n\n mouthCenter = mouthCenter.astype(int)\n\n distMouth = mouth[18, 1] - mouth[14, 1]\n\n return int(mouthWidth), mouthCenter, distMouth\n\ndef place_mouth(frame, mouthCenter, mouthSize):\n mouthSize = int(mouthSize * 1.5)\n\n x1 = int(mouthCenter[0, 0] - (mouthSize / 1.8))\n x2 = int(mouthCenter[0, 0] + (mouthSize / 1.8))\n y1 = int(mouthCenter[0, 1] - (mouthSize / 2)*0.5)\n y2 = int(mouthCenter[0, 1] + (mouthSize / 2)*0.5)\n\n h, w = frame.shape[:2]\n\n # check for clipping\n if x1 < 0:\n x1 = 0\n if y1 < 0:\n y1 = 0\n if x2 > w:\n x2 = w\n if y2 > h:\n y2 = h\n\n # re-calculate the size to avoid clipping\n mouthOverlayWidth = x2 - x1\n mouthOverlayHeight = y2 - y1\n # calculate the masks for the overlay\n mouthOverlay = cv2.resize(imgMouth, (mouthOverlayWidth, mouthOverlayHeight), interpolation=cv2.INTER_AREA)\n mask = cv2.resize(origin_mask_mouth, (mouthOverlayWidth, mouthOverlayHeight), interpolation=cv2.INTER_AREA)\n mask_inv = cv2.resize(orig_mask_inv_mouth, (mouthOverlayWidth, mouthOverlayHeight), interpolation=cv2.INTER_AREA)\n\n # take ROI for the verlay from background, equal to size of the overlay image\n roi = frame[y1:y2, x1:x2]\n\n # roi_bg contains the original image only where the overlay is not, in the region that is the size of the overlay.\n roi_bg = cv2.bitwise_and(roi, roi, mask=mask_inv)\n\n # roi_fg contains the image pixels of the overlay only where the overlay should be\n roi_fg = cv2.bitwise_and(mouthOverlay, mouthOverlay, mask=mask)\n\n # join the roi_bg and roi_fg\n dst = cv2.add(roi_bg, roi_fg)\n\n # place the joined image, saved to dst back over the original image\n frame[y1:y2, x1:x2] = dst\n\n#Compute Open Mouth\ndef mouth_open_size(mouth):\n mouthWidth = dist.euclidean(mouth[0], mouth[6])\n hull = ConvexHull(mouth)\n mouthCenter = np.mean(mouth[hull.vertices, :], axis=0)\n\n mouthCenter = mouthCenter.astype(int)\n\n distMouth = mouth[18, 1] - mouth[14, 1]\n\n return int(mouthWidth), mouthCenter, distMouth\n\ndef place_mouth_open(frame, mouthCenter, mouthSize):\n mouthSize = int(mouthSize * 1.5)\n\n x1 = int(mouthCenter[0, 0] - (mouthSize / 1.5))\n x2 = int(mouthCenter[0, 0] + (mouthSize / 1.5))\n y1 = int(mouthCenter[0, 1] - (mouthSize / 1.8)*0.7)\n y2 = int(mouthCenter[0, 1] + (mouthSize / 1.8)*0.7)\n\n h, w = frame.shape[:2]\n\n # check for clipping\n if x1 < 0:\n x1 = 0\n if y1 < 0:\n y1 = 0\n if x2 > w:\n x2 = w\n if y2 > h:\n y2 = h\n\n # re-calculate the size to avoid clipping\n mouthOverlayWidth = x2 - x1\n mouthOverlayHeight = y2 - y1\n # calculate the masks for the overlay\n mouthOverlay = cv2.resize(imgMouthOpen, (mouthOverlayWidth, mouthOverlayHeight), interpolation=cv2.INTER_AREA)\n mask = cv2.resize(origin_mask_mouth_open, (mouthOverlayWidth, mouthOverlayHeight), interpolation=cv2.INTER_AREA)\n mask_inv = cv2.resize(orig_mask_inv_mouth_open, (mouthOverlayWidth, mouthOverlayHeight), interpolation=cv2.INTER_AREA)\n\n # take ROI for the verlay from background, equal to size of the overlay image\n roi = frame[y1:y2, x1:x2]\n\n # roi_bg contains the original image only where the overlay is not, in the region that is the size of the overlay.\n roi_bg = cv2.bitwise_and(roi, roi, mask=mask_inv)\n\n # roi_fg contains the image pixels of the overlay only where the overlay should be\n roi_fg = cv2.bitwise_and(mouthOverlay, mouthOverlay, mask=mask)\n\n # join the roi_bg and roi_fg\n dst = cv2.add(roi_bg, roi_fg)\n\n # place the joined image, saved to dst back over the original image\n frame[y1:y2, x1:x2] = dst\n\n#Compute Masks\ndef masks_size(masks):\n masksWidth = dist.euclidean(masks[0], masks[15])\n masksCenter = masks[29]\n\n return int(masksWidth), masksCenter\n\ndef place_masks(frame, masksCenter, masksSize):\n masksSize = int(masksSize * 1.5)\n\n x1 = int(masksCenter[0, 0] - (masksSize / 2))\n x2 = int(masksCenter[0, 0] + (masksSize / 2))\n y1 = int(masksCenter[0, 1] - (masksSize / 2))\n y2 = int(masksCenter[0, 1] + (masksSize / 2))\n\n h, w = frame.shape[:2]\n\n # check for clipping\n if x1 < 0:\n x1 = 0\n if y1 < 0:\n y1 = 0\n if x2 > w:\n x2 = w\n if y2 > h:\n y2 = h\n\n # re-calculate the size to avoid clipping\n masksOverlayWidth = x2 - x1\n masksOverlayHeight = y2 - y1\n # calculate the masks for the overlay\n masksOverlay = cv2.resize(imgMasks, (masksOverlayWidth, masksOverlayHeight), interpolation=cv2.INTER_AREA)\n mask = cv2.resize(origin_mask_masks, (masksOverlayWidth, masksOverlayHeight), interpolation=cv2.INTER_AREA)\n mask_inv = cv2.resize(orig_mask_inv_masks, (masksOverlayWidth, masksOverlayHeight), interpolation=cv2.INTER_AREA)\n\n # take ROI for the verlay from background, equal to size of the overlay image\n roi = frame[y1:y2, x1:x2]\n\n # roi_bg contains the original image only where the overlay is not, in the region that is the size of the overlay.\n roi_bg = cv2.bitwise_and(roi, roi, mask=mask_inv)\n\n # roi_fg contains the image pixels of the overlay only where the overlay should be\n roi_fg = cv2.bitwise_and(masksOverlay, masksOverlay, mask=mask)\n\n # join the roi_bg and roi_fg\n dst = cv2.add(roi_bg, roi_fg)\n\n # place the joined image, saved to dst back over the original image\n frame[y1:y2, x1:x2] = dst\n\n#Compute Nose And Year\ndef nose_and_year_size(noseandyear):\n noseandyearWidth = dist.euclidean(noseandyear[0], noseandyear[15])\n noseandyearCenter = noseandyear[26]\n\n return int(noseandyearWidth), noseandyearCenter\n\ndef place_noseandyear(frame, noseandyearCenter, noseandyearSize):\n noseandyearSize = int(noseandyearSize * 1.2)\n\n x1 = int(noseandyearCenter[0, 0] - (noseandyearSize / 2))\n x2 = int(noseandyearCenter[0, 0] + (noseandyearSize / 2))\n y1 = int(noseandyearCenter[0, 1] - (2*noseandyearSize / 3))\n y2 = int(noseandyearCenter[0, 1] + (noseandyearSize / 3))\n\n h, w = frame.shape[:2]\n\n # check for clipping\n if x1 < 0:\n x1 = 0\n if y1 < 0:\n y1 = 0\n if x2 > w:\n x2 = w\n if y2 > h:\n y2 = h\n\n # re-calculate the size to avoid clipping\n noseandyearOverlayWidth = x2 - x1\n noseandyearOverlayHeight = y2 - y1\n # calculate the masks for the overlay\n noseandyearOverlay = cv2.resize(imgNoseAndYear, (noseandyearOverlayWidth, noseandyearOverlayHeight), interpolation=cv2.INTER_AREA)\n mask = cv2.resize(origin_mask_noseandyear, (noseandyearOverlayWidth, noseandyearOverlayHeight), interpolation=cv2.INTER_AREA)\n mask_inv = cv2.resize(orig_mask_inv_noseandyear, (noseandyearOverlayWidth, noseandyearOverlayHeight), interpolation=cv2.INTER_AREA)\n\n # take ROI for the verlay from background, equal to size of the overlay image\n roi = frame[y1:y2, x1:x2]\n\n # roi_bg contains the original image only where the overlay is not, in the region that is the size of the overlay.\n roi_bg = cv2.bitwise_and(roi, roi, mask=mask_inv)\n\n # roi_fg contains the image pixels of the overlay only where the overlay should be\n roi_fg = cv2.bitwise_and(noseandyearOverlay, noseandyearOverlay, mask=mask)\n\n # join the roi_bg and roi_fg\n dst = cv2.add(roi_bg, roi_fg)\n\n # place the joined image, saved to dst back over the original image\n frame[y1:y2, x1:x2] = dst\n\n#Compute Glasses\ndef glasses_size(glasses):\n glassesWidth = dist.euclidean(glasses[0], glasses[15])\n glassesCenter = glasses[26]\n\n return int(glassesWidth), glassesCenter\n\ndef place_glasses(frame, glassesCenter, glassesSize):\n glassesSize = int(glassesSize * 1.1)\n\n x1 = int(glassesCenter[0, 0] - (glassesSize / 2))\n x2 = int(glassesCenter[0, 0] + (glassesSize / 2))\n y1 = int(glassesCenter[0, 1] - (2*glassesSize / 3)*0.7)\n y2 = int(glassesCenter[0, 1] + (glassesSize / 3)*0.7)\n\n h, w = frame.shape[:2]\n\n # check for clipping\n if x1 < 0:\n x1 = 0\n if y1 < 0:\n y1 = 0\n if x2 > w:\n x2 = w\n if y2 > h:\n y2 = h\n\n # re-calculate the size to avoid clipping\n glassesOverlayWidth = x2 - x1\n glassesOverlayHeight = y2 - y1\n # calculate the masks for the overlay\n glassesOverlay = cv2.resize(imgGlasses, (glassesOverlayWidth, glassesOverlayHeight), interpolation=cv2.INTER_AREA)\n mask = cv2.resize(origin_mask_glasses, (glassesOverlayWidth, glassesOverlayHeight), interpolation=cv2.INTER_AREA)\n mask_inv = cv2.resize(orig_mask_inv_glasses, (glassesOverlayWidth, glassesOverlayHeight), interpolation=cv2.INTER_AREA)\n\n # take ROI for the verlay from background, equal to size of the overlay image\n roi = frame[y1:y2, x1:x2]\n\n # roi_bg contains the original image only where the overlay is not, in the region that is the size of the overlay.\n roi_bg = cv2.bitwise_and(roi, roi, mask=mask_inv)\n\n # roi_fg contains the image pixels of the overlay only where the overlay should be\n roi_fg = cv2.bitwise_and(glassesOverlay, glassesOverlay, mask=mask)\n\n # join the roi_bg and roi_fg\n dst = cv2.add(roi_bg, roi_fg)\n\n # place the joined image, saved to dst back over the original image\n frame[y1:y2, x1:x2] = dst\n\n#Compute eyebrows\ndef eyebrows_size(eyebrows):\n eyebrowsWidth = dist.euclidean(eyebrows[0], eyebrows[9])\n eyebrowsCenter = eyebrows[10]\n\n return int(eyebrowsWidth), eyebrowsCenter\n\ndef place_eyebrows(frame, eyebrowsCenter, eyebrowsSize):\n eyebrowsSize = int(eyebrowsSize * 1.5)\n\n x1 = int(eyebrowsCenter[0, 0] - (eyebrowsSize / 2)*2)\n x2 = int(eyebrowsCenter[0, 0] + (eyebrowsSize / 2)*2)\n y1 = int(eyebrowsCenter[0, 1] * 0.8 - (200 * eyebrowsSize / 201) * 0.9)\n y2 = int(eyebrowsCenter[0, 1] * 0.8 + (eyebrowsSize / 201) * 0.9)\n\n h, w = frame.shape[:2]\n\n # check for clipping\n if x1 < 0:\n x1 = 0\n if y1 < 0:\n y1 = 0\n if x2 > w:\n x2 = w\n if y2 > h:\n y2 = h\n\n # re-calculate the size to avoid clipping\n eyebrowsOverlayWidth = x2 - x1\n eyebrowsOverlayHeight = y2 - y1\n # calculate the masks for the overlay\n eyebrowsOverlay = cv2.resize(imgEyebrows, (eyebrowsOverlayWidth, eyebrowsOverlayHeight), interpolation=cv2.INTER_AREA)\n mask = cv2.resize(origin_mask_eyebrows, (eyebrowsOverlayWidth, eyebrowsOverlayHeight), interpolation=cv2.INTER_AREA)\n mask_inv = cv2.resize(orig_mask_inv_eyebrows, (eyebrowsOverlayWidth, eyebrowsOverlayHeight), interpolation=cv2.INTER_AREA)\n\n # take ROI for the verlay from background, equal to size of the overlay image\n roi = frame[y1:y2, x1:x2]\n\n # roi_bg contains the original image only where the overlay is not, in the region that is the size of the overlay.\n roi_bg = cv2.bitwise_and(roi, roi, mask=mask_inv)\n\n # roi_fg contains the image pixels of the overlay only where the overlay should be\n roi_fg = cv2.bitwise_and(eyebrowsOverlay, eyebrowsOverlay, mask=mask)\n\n # join the roi_bg and roi_fg\n dst = cv2.add(roi_bg, roi_fg)\n\n # place the joined image, saved to dst back over the original image\n frame[y1:y2, x1:x2] = dst\n\ndef estimate_distance(pointsFace):\n\n thirtyseven = pointsFace[36]\n ninteen = pointsFace[18]\n fortyfour = pointsFace[43]\n twentyfour = pointsFace[23]\n\n face_width = dist.euclidean(pointsFace[15], pointsFace[0])\n dis_right = dist.euclidean(thirtyseven, ninteen)\n dis_left = dist.euclidean(fortyfour, twentyfour)\n\n return int(face_width), dis_right, dis_left\n\n#Compute stars\ndef stars_size(stars):\n starsWidth = dist.euclidean(stars[0], stars[9])\n starsCenter = stars[10]\n\n return int(starsWidth), starsCenter\n\ndef place_stars(frame, starsCenter, starsSize):\n starsSize = int(starsSize * 1.5)\n\n x1 = int(starsCenter[0, 0] - (starsSize / 2)*3)\n x2 = int(starsCenter[0, 0] + (starsSize / 2)*3)\n y1 = int(starsCenter[0, 1] - (starsSize / 2)*3)\n y2 = int(starsCenter[0, 1] + (starsSize / 2)*3)\n\n h, w = frame.shape[:2]\n\n # check for clipping\n if x1 < 0:\n x1 = 0\n if y1 < 0:\n y1 = 0\n if x2 > w:\n x2 = w\n if y2 > h:\n y2 = h\n\n # re-calculate the size to avoid clipping\n starsOverlayWidth = x2 - x1\n starsOverlayHeight = y2 - y1\n # calculate the masks for the overlay\n starsOverlay = cv2.resize(imgEffectbrows, (starsOverlayWidth, starsOverlayHeight), interpolation=cv2.INTER_AREA)\n mask = cv2.resize(origin_mask_stars, (starsOverlayWidth, starsOverlayHeight), interpolation=cv2.INTER_AREA)\n mask_inv = cv2.resize(orig_mask_inv_stars, (starsOverlayWidth, starsOverlayHeight), interpolation=cv2.INTER_AREA)\n\n # take ROI for the verlay from background, equal to size of the overlay image\n roi = frame[y1:y2, x1:x2]\n\n # roi_bg contains the original image only where the overlay is not, in the region that is the size of the overlay.\n roi_bg = cv2.bitwise_and(roi, roi, mask=mask_inv)\n\n # roi_fg contains the image pixels of the overlay only where the overlay should be\n roi_fg = cv2.bitwise_and(starsOverlay, starsOverlay, mask=mask)\n\n # join the roi_bg and roi_fg\n dst = cv2.add(roi_bg, roi_fg)\n\n # place the joined image, saved to dst back over the original image\n frame[y1:y2, x1:x2] = dst\n\nprint(\"************************************************************************\")\nflag = False\nchoose = input('Choose:\\n (0) eyes filter,\\n (1) nose filter,\\n (2) hat filter,\\n (3) moustache filter,\\n (4) mouth filter,\\n (5) mask filter,\\n (6) nose and ears filter,\\n (7) glasses filter,\\n (8) nose and eyes filter,\\n (9) moustache and glasses filter,\\n (10) eyebrows filter: ')\nwhile choose > 10:\n print(\"Warning: type value less than 11!\")\n choose = input('***Choose:\\n (0) eyes filter,\\n (1) nose filter,\\n (2) hat filter,\\n (3) moustache filter,\\n (4) mouth filter,\\n (5) mask filter,\\n (6) nose and ears filter,\\n (7) glasses filter,\\n (8) nose and eyes filter,\\n (9) moustache and glasses filter,\\n (10) eyebrows filter: ')\n\nprint(\"************************************************************************\")\nprint(\"Type 'q' to close the window!\\n Type 'c' to change filter!\")\nprint(\"************************************************************************\")\n\n# ---------------------------------------------------------\n# Load and pre-process the eye-overlay\n# ---------------------------------------------------------\n# Load the image to be used as our overlay\nimgEye = cv2.imread('png/Eye.png', -1)\nimgNose = cv2.imread('png/Nose.png', -1)\nimgHat = cv2.imread('png/Hat.png', -1)\nimgMoustache = cv2.imread('png/Moustache.png', -1)\nimgMouth = cv2.imread('png/Close-Mouth.png', -1)\nimgMouthOpen = cv2.imread('png/Open-Mouth.png', -1)\nimgMasks = cv2.imread('png/Mask.png', -1)\nimgNoseAndYear = cv2.imread('png/NoseAndYear.png', -1)\nimgGlasses = cv2.imread('png/Glasses.png', -1)\nimgEyebrows = cv2.imread('png/TextEyebrows.png', -1)\nimgEffectbrows = cv2.imread('png/Stars.png', -1)\n\norigin_mask_hat = imgHat[:, :, 3]\norig_mask_inv_hat = cv2.bitwise_not(origin_mask_hat)\nimgHat = imgHat[:, :, 0:3]\norigHatHeight, origHatWidth = imgHat.shape[:2]\n\norigin_mask_mouth = imgMouth[:, :, 3]\norig_mask_inv_mouth = cv2.bitwise_not(origin_mask_mouth)\nimgMouth = imgMouth[:, :, 0:3]\norigMouthHeight, origMouthWidth = imgMouth.shape[:2]\n\norigin_mask_mouth_open = imgMouthOpen[:, :, 3]\norig_mask_inv_mouth_open = cv2.bitwise_not(origin_mask_mouth_open)\nimgMouthOpen = imgMouthOpen[:, :, 0:3]\norigMouthOpenHeight, origMouthOpenWidth = imgMouthOpen.shape[:2]\n\norigin_mask_masks = imgMasks[:, :, 3]\norig_mask_inv_masks = cv2.bitwise_not(origin_mask_masks)\nimgMasks = imgMasks[:, :, 0:3]\norigMasksHeight, origMasksWidth = imgMasks.shape[:2]\n\norigin_mask_noseandyear = imgNoseAndYear[:, :, 3]\norig_mask_inv_noseandyear = cv2.bitwise_not(origin_mask_noseandyear)\nimgNoseAndYear = imgNoseAndYear[:, :, 0:3]\norigNoseAndYearHeight, origNoseAndYearWidth = imgMasks.shape[:2]\n\n# Create the mask from the overlay image\norig_mask_eye = imgEye[:, :, 3]\n# Create the inverted mask for the overlay image\norig_mask_inv_eye = cv2.bitwise_not(orig_mask_eye)\n# Convert the overlay image image to BGR\n# and save the original image size\nimgEye = imgEye[:, :, 0:3]\norigEyeHeight, origEyeWidth = imgEye.shape[:2]\n\norigin_mask_nose = imgNose[:, :, 3]\norig_mask_inv_nose = cv2.bitwise_not(origin_mask_nose)\nimgNose = imgNose[:, :, 0:3]\norigNoseHeight, origNoseWidth = imgNose.shape[:2]\n\n# Create the mask from the overlay image\norigin_mask_glasses = imgGlasses[:, :, 3]\n# Create the inverted mask for the overlay image\norig_mask_inv_glasses = cv2.bitwise_not(origin_mask_glasses)\n# Convert the overlay image image to BGR\n# and save the original image size\nimgGlasses = imgGlasses[:, :, 0:3]\norigGlassesHeight, origGlassesWidth = imgGlasses.shape[:2]\n\norigin_mask_moustache = imgMoustache[:, :, 3]\norig_mask_inv_moustache = cv2.bitwise_not(origin_mask_moustache)\nimgMoustache = imgMoustache[:, :, 0:3]\norigMoustacheHeight, origMoustacheWidth = imgMoustache.shape[:2]\n\n#elif choose == 10:\norigin_mask_eyebrows = imgEyebrows[:, :, 3]\norig_mask_inv_eyebrows = cv2.bitwise_not(origin_mask_eyebrows)\nimgEyebrows = imgEyebrows[:, :, 0:3]\norigEyebrowsHeight, origEyebrowsWidth = imgEyebrows.shape[:2]\n\norigin_mask_stars = imgEffectbrows[:, :, 3]\norig_mask_inv_stars = cv2.bitwise_not(origin_mask_stars)\nimgEffectbrows = imgEffectbrows[:, :, 0:3]\norigStarsHeight, origStarsWidth = imgEyebrows.shape[:2]\n\n# Start capturing the WebCam\nvideo_capture = cv2.VideoCapture(0)\n\nwhile True:\n\n ret, frame = video_capture.read()\n\n if ret:\n gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)\n\n rects = detector(gray, 0)\n\n for rect in rects:\n x = rect.left()\n y = rect.top()\n x1 = rect.right()\n y1 = rect.bottom()\n\n landmarks = np.matrix([[p.x, p.y] for p in predictor(frame, rect).parts()])\n\n if choose == 0:\n left_eye = landmarks[LEFT_EYE_POINTS]\n right_eye = landmarks[RIGHT_EYE_POINTS]\n #center_nose = landmarks[NOSE_POINTS]\n\n # cv2.rectangle(frame, (x, y), (x1, y1), (0, 255, 0), 2)\n leftEyeSize, leftEyeCenter = eye_size(left_eye)\n rightEyeSize, rightEyeCenter = eye_size(right_eye)\n #centerNoseSize, centerNoseCenter = nose_size(center_nose)\n\n place_eye(frame, leftEyeCenter, leftEyeSize)\n place_eye(frame, rightEyeCenter, rightEyeSize)\n #place_nose(frame, centerNoseCenter, centerNoseSize)\n elif choose == 1:\n center_nose = landmarks[NOSE_POINTS]\n centerNoseSize, centerNoseCenter = nose_size(center_nose)\n place_nose(frame, centerNoseCenter, centerNoseSize)\n\n elif choose == 2:\n center_hat = landmarks[FACE_POINTS]\n centerHatSize, centerHatCenter = hat_size(center_hat)\n place_hat(frame, centerHatCenter, centerHatSize)\n\n elif choose == 3:\n center_moustache = landmarks[MOUTH_OUTLINE_POINTS]\n centerMoustacheSize, centerMoustacheCenter = moustache_size(center_moustache)\n place_moustache(frame, centerMoustacheCenter, centerMoustacheSize)\n\n elif choose == 4:\n center_mouth = landmarks[MOUTH_POINTS]\n centerMouthSize, centerMouthCenter, distMouth = mouth_size(center_mouth)\n if distMouth < 5:\n place_mouth(frame, centerMouthCenter, centerMouthSize)\n else:\n center_mouth_open = landmarks[MOUTH_POINTS]\n centerMouthOpenSize, centerMouthOpenCenter, distMouth = mouth_open_size(center_mouth_open)\n place_mouth_open(frame, centerMouthOpenCenter, centerMouthOpenSize)\n\n elif choose == 5:\n center_masks = landmarks[FULL_POINTS]\n centerMasksSize, centerMasksCenter = masks_size(center_masks)\n place_masks(frame, centerMasksCenter, centerMasksSize)\n\n elif choose == 6:\n center_noseandyear = landmarks[FULL_POINTS]\n centerNoseAndYearSize, centerNoseAndYearCenter = masks_size(center_noseandyear)\n place_noseandyear(frame, centerNoseAndYearCenter, centerNoseAndYearSize)\n\n elif choose == 7:\n center_glasses = landmarks[FULL_POINTS]\n centerGlassesSize, centerGlasses = masks_size(center_glasses)\n place_glasses(frame, centerGlasses, centerGlassesSize)\n\n elif choose == 8:\n left_eye = landmarks[LEFT_EYE_POINTS]\n right_eye = landmarks[RIGHT_EYE_POINTS]\n center_nose = landmarks[NOSE_POINTS]\n\n # cv2.rectangle(frame, (x, y), (x1, y1), (0, 255, 0), 2)\n leftEyeSize, leftEyeCenter = eye_size(left_eye)\n rightEyeSize, rightEyeCenter = eye_size(right_eye)\n centerNoseSize, centerNoseCenter = nose_size(center_nose)\n\n place_eye(frame, leftEyeCenter, leftEyeSize)\n place_eye(frame, rightEyeCenter, rightEyeSize)\n place_nose(frame, centerNoseCenter, centerNoseSize)\n\n elif choose == 9:\n center_glasses = landmarks[FULL_POINTS]\n centerGlassesSize, centerGlasses = masks_size(center_glasses)\n place_glasses(frame, centerGlasses, centerGlassesSize)\n\n center_moustache = landmarks[MOUTH_OUTLINE_POINTS]\n centerMoustacheSize, centerMoustacheCenter = moustache_size(center_moustache)\n place_moustache(frame, centerMoustacheCenter, centerMoustacheSize)\n\n elif choose == 10:\n face_width, dis_right, dis_left = estimate_distance(landmarks[FULL_POINTS])\n threshold = (31.4 * face_width) / 152\n if (dis_right > threshold or dis_left > threshold):\n center_stars = landmarks[FULL_POINTS]\n centerStarsSize, centerStars = masks_size(center_stars)\n place_stars(frame, centerStars, centerStarsSize)\n else:\n center_eyebrows = landmarks[FACE_POINTS]\n centerEyebrowsSize, centerEyebrows = eyebrows_size(center_eyebrows)\n place_eyebrows(frame, centerEyebrows, centerEyebrowsSize)\n\n\n cv2.imshow(\"Faces with Overlay\", frame)\n\n ch = 0xFF & cv2.waitKey(1)\n\n if ch == ord('q'):\n break\n if ch == ord('c'):\n choose = choose + 1\n if choose > 10:\n choose = 0\n\ncv2.destroyAllWindows()\n","sub_path":"image_processing/face_filters/manip/imageprocessing-filters.py","file_name":"imageprocessing-filters.py","file_ext":"py","file_size_in_byte":30718,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"468089117","text":"def create_num(all_num):\n\n a,b = 0,1\n\n current_num = 0\n while current_num < all_num:\n ret = yield a\n print(\"---ret------\",ret)\n\n yield a\n a,b = b, a+b\n current_num+=1\n\n#如果在调用函数的时候,发现函数中与yield,那么此时不再是调用函数,而是创建一生成器\nobj = create_num(10)\n#如果已创建生成器就send会报错,yeild,也没有ret去接受\nobj.send(None)\n\nret = next(obj)\nprint(\"obj:\",ret)\n\nret = obj.send(None)\nprint(ret)\n","sub_path":"--master/web/006.通过send启动生成器.py","file_name":"006.通过send启动生成器.py","file_ext":"py","file_size_in_byte":483,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"400259162","text":"from django.urls import path, include\nfrom . import views\nfrom django.conf import settings\nfrom django.conf.urls.static import static\n\nurlpatterns = [\n path('', views.index, name=\"index\"),\n path('/-/', views.post, name=\"post\"),\n path('comment---/', views.comment, name=\"comment\"),\n path('edit_comment---/', views.edit_comment, name=\"edit_comment\"),\n path('delete_comment--/', views.delete_comment, name=\"delete_comment\"),\n path('get_comment--/', views.get_comment, name=\"get_comment\"),\n path('like--/', views.like, name=\"like\"),\n path('bookmark--/', views.bookmark, name=\"bookmark\"),\n path('follow--/', views.follow, name=\"follow\"),\n path('follow_user-/', views.follow_user, name=\"follow_user\"),\n path('search/', views.search, name=\"search\"),\n path('/', views.author, name=\"author\"),\n] + static(settings.MEDIA_URL, document_root = settings.MEDIA_ROOT)","sub_path":"blog-medium/comments/blog/homepage/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1168,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"29917290","text":"\"\"\"\r\nThis file defines actions, i.e. functions the URLs are mapped into\r\nThe @action(path) decorator exposed the function at URL:\r\n\r\n http://127.0.0.1:8000/{app_name}/{path}\r\n\r\nIf app_name == '_default' then simply\r\n\r\n http://127.0.0.1:8000/{path}\r\n\r\nIf path == 'index' it can be omitted:\r\n\r\n http://127.0.0.1:8000/\r\n\r\nThe path follows the bottlepy syntax.\r\n\r\n@action.uses('generic.html') indicates that the action uses the generic.html template\r\n@action.uses(session) indicates that the action uses the session\r\n@action.uses(db) indicates that the action uses the db\r\n@action.uses(T) indicates that the action uses the i18n & pluralization\r\n@action.uses(auth.user) indicates that the action requires a logged in user\r\n@action.uses(auth) indicates that the action requires the auth object\r\n\r\nsession, db, T, auth, and tempates are examples of Fixtures.\r\nWarning: Fixtures MUST be declared with @action.uses({fixtures}) else your app will result in undefined behavior\r\n\"\"\"\r\n\r\nimport uuid\r\n\r\nfrom py4web import action, request, abort, redirect, URL, Field\r\nfrom py4web.utils.form import Form, FormStyleBulma\r\nfrom py4web.utils.url_signer import URLSigner\r\n\r\nfrom yatl.helpers import A\r\nfrom . common import db, session, T, cache, auth, signed_url\r\nfrom . models import get_user_email\r\n\r\nurl_signer = URLSigner(session)\r\n\r\n# The auth.user below forces login.\r\n@action('index')\r\n@action.uses('index.html', url_signer, auth.user)\r\ndef index():\r\n return dict(\r\n # This is an example of a signed URL for the callback.\r\n get_posts_url = URL('get_posts', signer=url_signer),\r\n add_posts_url = URL('add_post', signer=url_signer),\r\n delete_post_url = URL('delete_post', signer=url_signer),\r\n get_rating_url = URL('get_rating', signer=url_signer),\r\n set_rating_url = URL('set_rating', signer=url_signer),\r\n get_peopleLIKE_url = URL('get_peopleLIKE', signer=url_signer),\r\n get_peopleDISLIKE_url = URL('get_peopleDISLIKE', signer=url_signer),\r\n\r\n # Add other callbacks here.\r\n user_email = get_user_email(),\r\n username = auth.current_user.get('first_name') + \" \" + auth.current_user.get(\"last_name\")\r\n )\r\n\r\n@action('get_posts')\r\n@action.uses(url_signer.verify(), auth.user)\r\ndef get_posts():\r\n # Complete.\r\n posts = db(db.post).select(orderby=~db.post.ts).as_list() # Just to keep code from breaking.\r\n for p in posts:\r\n r = db(db.auth_user.email == p[\"user_email\"]).select().first()\r\n name = r.first_name + \" \" + r.last_name if r is not None else \"Unknown\"\r\n p[\"usernames\"] = name\r\n return dict(posts=posts)\r\n\r\n@action('add_post', method=\"POST\")\r\n@action.uses(url_signer.verify(), auth.user)\r\ndef add_post():\r\n # Complete.\r\n id = db.post.insert(\r\n post_text = request.json.get('post_text'),\r\n )\r\n return dict(id=id) # You need to fill this in.\r\n \r\n@action('get_rating')\r\n@action.uses(url_signer.verify(), auth.user, db)\r\ndef get_rating():\r\n postID = request.params.get('postID')\r\n #print (\"This is the postID = \", end = ''), print(postID)\r\n #user_id = auth.current_user.get('id')\r\n user_email = get_user_email(),\r\n if postID is not None:\r\n rating_entry = db((db.thumb.post_id == postID) & (db.thumb.user_email == user_email)).select().first()\r\n rating = rating_entry.rating if rating_entry is not None else 0\r\n #print (\"This is the rating = \", end = ''), print(rating)\r\n return dict(rating=rating)\r\n\r\n@action('set_rating', method='POST')\r\n@action.uses(url_signer.verify(), auth.user, db)\r\ndef set_rating():\r\n postID = request.json.get('postID')\r\n\r\n user_id = auth.current_user.get('id')\r\n rating = request.json.get('rating')\r\n\r\n user_emailREAL = get_user_email(),\r\n \r\n if postID is not None:\r\n db.thumb.update_or_insert(\r\n ((db.thumb.post_id == postID) & (db.thumb.user_email == user_emailREAL)),\r\n post_id=postID,\r\n user_email = user_emailREAL,\r\n rating=rating, \r\n )\r\n #selector = db(db.thumb).select((db.thumb.post_id == postID) & (db.thumb.user_email == user_emailREAL))\r\n #print(selector.post_id)\r\n #print(selector.user_email)\r\n #print(selector.rating)\r\n return \"ok\"\r\n \r\n@action('get_peopleLIKE')\r\n@action.uses(url_signer.verify(), auth.user, db)\r\ndef get_peopleLIKE():\r\n postID = request.params.get('postID') \r\n user_email = get_user_email(),\r\n if postID is not None:\r\n #I think we need to find the thumb reference instead.\r\n #There is going to be multiple people who liked it not just one. \r\n #Maybe a for loop that sets a string of likes, and makes that the first element in a list\r\n #And then another string of dislikes, second element in a list. \r\n rating_entry = db(db.thumb.post_id == postID).select().as_list()\r\n LIKERS = \"Liked by \"\r\n DISLIKERS = \"\"\r\n for p in rating_entry:\r\n #X is the user_email, but I had to trim the parantheses and commas \r\n x = p[\"user_email\"]\r\n x = x[2:]\r\n x = x[:-3]\r\n\r\n r = db(db.auth_user.email == x).select().first()\r\n name = r.first_name + \" \" + r.last_name if r is not None else \"Unknown\"\r\n\r\n if p[\"rating\"] == 1:\r\n LIKERS = LIKERS + name + \", \"\r\n\r\n DISLIKERS = \"There\"\r\n print(p[\"rating\"])\r\n \r\n if LIKERS == \"Liked by \":\r\n LIKERS = \"\"\r\n else:\r\n LIKERS = LIKERS[:-2]\r\n epicList = [LIKERS, DISLIKERS]\r\n\r\n return dict(epicList=epicList)\r\n \r\n \r\n \r\n \r\n@action('get_peopleDISLIKE')\r\n@action.uses(url_signer.verify(), auth.user, db)\r\ndef get_peopleDISLIKE():\r\n postID = request.params.get('postID') \r\n user_email = get_user_email(),\r\n if postID is not None:\r\n #I think we need to find the thumb reference instead.\r\n #There is going to be multiple people who liked it not just one. \r\n #Maybe a for loop that sets a string of likes, and makes that the first element in a list\r\n #And then another string of dislikes, second element in a list. \r\n rating_entry = db(db.thumb.post_id == postID).select().as_list()\r\n DISLIKERS = \"Disliked by \"\r\n for p in rating_entry:\r\n #X is the user_email, but I had to trim the parantheses and commas \r\n x = p[\"user_email\"]\r\n x = x[2:]\r\n x = x[:-3]\r\n\r\n r = db(db.auth_user.email == x).select().first()\r\n name = r.first_name + \" \" + r.last_name if r is not None else \"Unknown\"\r\n\r\n if p[\"rating\"] == 2:\r\n DISLIKERS = DISLIKERS + name + \", \"\r\n\r\n\r\n if DISLIKERS == \"Disliked by \":\r\n DISLIKERS = \"\"\r\n else:\r\n DISLIKERS = DISLIKERS[:-2]\r\n epicList = [DISLIKERS]\r\n return dict(epicList=epicList)\r\n \r\n \r\n#What if we make something that calls add_post() and then redirects to get_posts()?\r\n \r\n@action('delete_post', method=\"POST\")\r\n@action.uses(url_signer.verify(), auth.user)\r\ndef delete_post():\r\n id = request.json.get('id')\r\n if id is not None:\r\n db(db.post.id == id).delete()\r\n return(\"ok\")\r\n \r\n# Complete.","sub_path":"grader/hw5grader/CSE_183_Spring_2020_Assignment_5_Submission_3/controllers.py","file_name":"controllers.py","file_ext":"py","file_size_in_byte":7266,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"231431941","text":"import frappe\nfrom datetime import datetime, timedelta\nfrom frappe.utils import add_days,today\nfrom erpnext.hr.doctype.employee.employee import get_holiday_list_for_employee\nfrom erpnext.hr.doctype.holiday_list.holiday_list import is_holiday\nfrom erpnext.hr.doctype.employee.employee import get_holiday_list_for_employee\n\n@frappe.whitelist()\ndef process_sandwich_leave(self,method):\n\t# try:\n\tprocess_sandwich_leave_daily(self)\n\t# process_sandwich_leave_weekly(self)\n\t# except Exception as e:\n\t# \tfrappe.log_error(frappe.get_traceback())\n\ndef process_sandwich_leave_daily(self):\n\tholiday_date = []\n\tlast_date = add_days(self.attendance_date,-1)\n\ton_leave = leave_check = False\n\twhile leave_check == False:\n\t\tif check_leave(self,last_date):\n\t\t\tlast_date = add_days(last_date,-1)\n\t\t\ton_leave = True\n\t\telse:\n\t\t\tleave_check = True\n\tholiday = get_holiday_list_for_employee(self.employee)\n\tfrappe.errprint(holiday)\n\tif on_leave == True:\n\t\twhile check_holiday(last_date,holiday):\n\t\t\tfrappe.errprint('holiday')\n\t\t\tholiday_date.append(last_date)\n\t\t\tlast_date = add_days(last_date,-1)\n\t\tif len(holiday_date) >= 1:\n\t\t\tif check_leave(self,last_date):\n\t\t\t\tfor hd in holiday_date:\n\t\t\t\t\tcreate_leave(self.employee,hd,0)\n\n@frappe.whitelist()\ndef process_sandwich_leave_weekly():\n\tsunday = today()\n\tfirst_day_of_week = add_days(sunday,-6)\n\temployees = get_employess(first_day_of_week,sunday)\n\tfor employee in employees:\n\t\tif check_weekly_leave(employee.employee,first_day_of_week,sunday):\n\t\t\tcreate_leave(employee.employee,sunday,0)\n\ndef check_weekly_leave(employee,from_date,to_date):\n\tfilters = [\n\t\t['employee', '=', employee],\n\t\t['from_date', '>=', from_date],\n\t\t['to_date', '<=',to_date],\n\t\t['docstatus','=',1],\n\t\t['leave_type', 'in',[\"Leave Without Pay\",\"Miss Punch\"]]\n\t]\n\tleave_application = frappe.get_all(\"Leave Application\",filters=filters,fields=[\"name\"])\n\tif len(leave_application) > 1:\n\t\treturn True\n\telse:\n\t\treturn False\n\n\ndef check_holiday(date,holiday):\n\tholiday = frappe.db.sql(\"\"\"select holiday_date from `tabHoliday` where holiday_date=%s and parent=%s\"\"\",(date,holiday),as_dict=1)\n\tif len(holiday) >= 1:\n\t\treturn True\n\telse:\n\t\treturn False\n\ndef check_leave(self,date):\n\tfilters = [\n\t\t['employee', '=', self.employee],\n\t\t['docstatus','=',1],\n\t\t['from_date', '<=', date],\n\t\t['to_date', '>=',date],\n\t\t['half_day', '=',0],\n\t\t['leave_type', 'in',[\"Leave Without Pay\",\"Miss Punch\"]]\n\t]\n\tleave_application = frappe.get_all(\"Leave Application\",filters=filters,fields=[\"name\"])\n\tfrappe.errprint(leave_application)\n\tif len(leave_application) >= 1:\n\t\treturn True\n\telse:\n\t\treturn False\n\ndef create_leave(employee,date,half_day):\n\tif half_day == 1:\n\t\tdoc = frappe.get_doc(dict(\n\t\t\tdoctype = \"Leave Application\",\n\t\t\temployee = employee,\n\t\t\tfrom_date = date,\n\t\t\tto_date = date,\n\t\t\thalf_day = half_day,\n\t\t\tleave_type = \"Half Day\",\n\t\t\tfollow_via_email = 0,\n\t\t\tleave_approver = frappe.db.get_value(\"Employee\",employee,\"leave_approver\")\n\t\t)).insert(ignore_permissions = True)\n\t\tdoc.status = \"Approved\"\n\t\tdoc.submit()\n\n\tif half_day == 0:\n\t\tdoc = frappe.get_doc(dict(\n\t\t\tdoctype = \"Leave Application\",\n\t\t\temployee = employee,\n\t\t\tfrom_date = date,\n\t\t\tto_date = date,\n\t\t\thalf_day = half_day,\n\t\t\tleave_type = \"Leave Without Pay\",\n\t\t\tfollow_via_email = 0,\n\t\t\tleave_approver = frappe.db.get_value(\"Employee\",employee,\"leave_approver\")\n\t\t)).insert(ignore_permissions = True)\n\t\tdoc.status = \"Approved\"\n\t\tdoc.submit()\n\n\ndef get_employess(from_date,to_date):\n\temployee_list = frappe.db.sql(\"\"\"select distinct employee from `tabLeave Application` where from_date>=%s and to_date<=%s\"\"\",(from_date,add_days(to_date,-1)),as_dict=1)\n\tprint(employee_list)\n\treturn employee_list or []\n","sub_path":"hr_policies/process_attendance.py","file_name":"process_attendance.py","file_ext":"py","file_size_in_byte":3650,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"601979644","text":"#coding:utf-8\r\nimport tornado.web\r\nimport tornado.ioloop\r\nimport config\r\nimport tornado.httpserver\r\nimport json\r\n\r\n# class IndexHandler(tornado.web.RequestHandler):\r\n# def initialize(self):\r\n# print \"调用了initialize()\"\r\n#\r\n# def prepare(self):\r\n# print \"调用了prepare()\"\r\n#\r\n# def set_default_headers(self):\r\n# print \"调用了set_default_headers()\"\r\n#\r\n# def write_error(self, status_code, **kwargs):\r\n# print \"调用了write_error()\"\r\n#\r\n# def get(self,*args,**kwargs):\r\n# self.render('blog/article.html',title=\"周杰伦错去\",content=\"朕错了吗\",author=\"大脸猫\")\r\n#\r\n# print \"调用了get()\"\r\n#\r\n# def post(self):\r\n# #print \"调用了post()\"\r\n# self.send_error(200) # 注意此出抛出了错误\r\n#\r\n# def on_finish(self):\r\n# print \"调用了on_finish()\"\r\n\r\n # def get(self, *args, **kwargs):\r\n # err_code=self.get_argument(\"code\",None)\r\n # err_title=self.get_argument(\"title\",\"\")\r\n # err_content=self.get_argument(\"content\",\"\")\r\n # if err_code:\r\n # self.send_error(err_code, title=err_title,content=err_content)\r\n # else:\r\n # self.write(\"主页\")\r\n # def write_error(self, status_code, **kwargs):\r\n # self.write(u\"出错了,程序员GG正在赶过来! \")\r\n # self.write(u\"错误名:%s
\" % kwargs[\"title\"])\r\n # self.write(u\"错误详情:%s
\" % kwargs[\"content\"])\r\n\r\n # self.write(\"主页\")\r\n # self.send_error(404, content=\"出现404错误\")\r\n # self.write(\"结束\")\r\n\r\n # def get(self):\r\n # stu={\r\n # \"name\":\"zhangsan\",\r\n # \"age\":24,\r\n # \"gender\":1\r\n # }\r\n #stu_json=json.dumps(stu)\r\n #self.write(stu_json)\r\n\r\n # self.write(stu)\r\n\r\n # stu_json=json.dumps(stu)\r\n # self.write(stu_json)\r\n # self.set_header(\"Content_Type\",\"application/json;charset=UTF-8\")\r\n # def set_default_headers(self):\r\n # print \"执行了 set_default_headers()\"\r\n # self.set_header(\"Content-Type\", \"application/json; charset=UTF-8\")\r\n # self.set_header(\"qianfeng\",\"python\")\r\n #\r\n # def get(self, *args, **kwargs):\r\n # print \"执行了get()\"\r\n # stu = {\r\n # \"name\":\"zhangsan\",\r\n # \"age\":24,\r\n # \"gender\":1\r\n # }\r\n # stu_json = json.dumps(stu)\r\n # self.write(stu_json)\r\n # self.set_header(\"qianfeng\", \"i love python\")\r\n #\r\n # def post(self):\r\n # print \"执行了post()\"\r\n #\r\n # stu = {\r\n # \"name\": \"zhangsan\",\r\n # \"age\": 24,\r\n # \"gender\": 1\r\n # }\r\n # stu_json = json.dumps(stu)\r\n # self.write(stu_json)\r\n\r\n# class Err210Handler(tornado.web.RequestHandler):\r\n# def get(self):\r\n# self.write(\"hello qianfeng\")\r\n# self.set_status(210,\"qianfeng good\")\r\n# class LoginHandler(tornado.web.RequestHandler):\r\n# def get(self, *args, **kwargs):\r\n# self.write(' ')\r\n# def post(self, *args, **kwargs):\r\n# self.redirect(\"/\")\r\nclass Handler58(tornado.web.RequestHandler):\r\n def get(self, *args, **kwargs):\r\n info_dic={\r\n 'price':10000,\r\n 'price1': 10000,\r\n 'price2': 10000,\r\n 'title':'宝盛里1居室',\r\n 'titles':['宝盛里','千锋','28技师'],\r\n 'score':\"五星好评\",\r\n 'comments':'洗的很好',\r\n 'position':\"千锋三楼38教室\",\r\n 'fuwu_price':100,\r\n\r\n }\r\n self.render('blog/58.html',**info_dic)\r\n\r\nclass Handler68(tornado.web.RequestHandler):\r\n def get(self, *args, **kwargs):\r\n info_dic={\r\n 'price':10000,\r\n 'price1': 10000,\r\n 'price2': 10000,\r\n 'title':'宝盛里1居室',\r\n 'titles':['宝盛里','千锋','28技师'],\r\n 'score':\"五星好评\",\r\n 'comments':'洗的很好',\r\n 'position':\"千锋三楼38教室\",\r\n 'fuwu_price':100,\r\n\r\n }\r\n self.render('blog/68.html', info_dic=info_dic)\r\n\r\nif __name__=='__main__':\r\n app=tornado.web.Application(\r\n [\r\n #(r'/',IndexHandler),\r\n # (r'/error',Err210Handler),\r\n #(r'/tz/',LoginHandler),\r\n (r'/58',Handler58),\r\n (r'/68', Handler68),\r\n ],\r\n **config.settings\r\n )\r\n http_server=tornado.httpserver.HTTPServer(app)\r\n http_server.bind(config.port)\r\n http_server.start()\r\n tornado.ioloop.IOLoop.current().start()\r\n\r\n\r\n\r\n","sub_path":"2/code/server1.py","file_name":"server1.py","file_ext":"py","file_size_in_byte":4695,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"215649753","text":"# -----------------------------------------------------------------------------\n# \n# Copyright 2013-2019 lispers.net - Dino Farinacci \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# lisp-get-bits\n#\n# Usage: python lisp-get-bits.py [force]\n#\n# Do a wget on supplied URL and install in current directory.\n# \n# -----------------------------------------------------------------------------\nfrom __future__ import print_function\nfrom builtins import input\nimport sys\nimport os\n\n#\n# Get parameter step.\n#\nif (len(sys.argv) == 1):\n print((\"Usage: python lisp-get-bits.py \" + \\\n \"[force]\"))\n exit(1)\n#endif\n\n#\n# Check to see if wget is installed on the system.\n#\nif (os.system(\"which wget > /dev/null\") != 0):\n print(\"wget not installed\")\n exit(1)\n#endif\n\nforce = (\"force\" in sys.argv)\n\nurl = sys.argv[1]\nimage = url.split(\"/\")[-1]\nindex = image.find(\"tgz\") + len(\"tgz\")\nimage = image[0:index]\n\n#\n# Check if file exists, if so, ask user if they want to remove it.\n#\nif (force == False and os.path.exists(image)):\n line = \"{} already exists, remove it? (y/n): \".format(image)\n if (input(line) != \"y\"): exit(0)\n os.system(\"rm -fr {}\".format(image))\n#endif\n\n#\n# Download step.\n#\nprint(\"Downloading {} ...\".format(url))\n\nif (os.system(\"wget -q {}\".format(url)) != 0):\n print(\"Could not download image\")\n exit(1)\n#endif\nos.system(\"mv file {}\".format(image))\n\n#\n# Untar step.\n#\nif (force == False):\n yesno = input(\"Do you want to install image? (y/n): \")\n if (yesno != \"y\"): exit(0)\n#endif\n\nprint(\"Untaring {} ...\".format(image))\nif (os.system(\"tar zxvf {}\".format(image)) != 0):\n print(\"Could not untar image\")\n exit(1)\n#endif\n\nprint(\"To restart the LISP subsystem, run './RESTART-LISP'\")\nexit(0)\n","sub_path":"build/releases/release-0.582/src/lisp-get-bits.py","file_name":"lisp-get-bits.py","file_ext":"py","file_size_in_byte":2415,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"264959800","text":"def lambda_handler(event, context):\n qs = event[\"queryStringParameters\"]\n name = qs['name'] if qs and 'name' in qs else 'World'\n\n return {\n 'isBase64Encoded': False,\n 'statusCode': 200,\n 'headers': {},\n 'body': f'{{\"message\": \"Hello {name}!\"}}',\n }\n","sub_path":"05/src/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":289,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"66774223","text":"\nfrom .base import BaseCmd\n\nclass SubCmd(BaseCmd):\n '''\n Get qrcode from a string\n\n Usage:\n meteor qrcode \"http://www.google.com\"\n '''\n\n def config(self, parser):\n parser.set_defaults(func=self.action)\n parser.add_argument('string', help='string to convert to')\n\n def action(self, args):\n\n import os\n import tempfile\n temp_dir = os.path.join(tempfile.gettempdir(), 'meteor')\n if not os.path.isdir(temp_dir):\n os.mkdir(temp_dir)\n\n imgpath = os.path.join(temp_dir, 'qrcode.png')\n\n import qrcode\n string = args.string\n img = qrcode.make(string)\n img.save(imgpath)\n\n try:\n os.startfile(imgpath)\n except AttributeError:\n import subprocess\n subprocess.call(['open', imgpath])\n\n","sub_path":"Meteor/scripts/qrcode.py","file_name":"qrcode.py","file_ext":"py","file_size_in_byte":831,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"531659523","text":"from pathlib import Path\nimport argparse\nfrom meth5 import MetH5File\n\n\ndef argtype_M5File(value):\n try:\n MetH5File(value, \"r\").get_chromosomes()\n except:\n raise argparse.ArgumentTypeError(f\"Failed to read '{value}'. Is it a valid MetH5 file?\")\n return Path(value)\n\n\ndef argtype_genomic_range(value: str):\n try:\n value = value.split(\":\")\n chrom = value[0]\n if len(value) == 1:\n start = 0\n end = -1\n else:\n value = value[1].split(\"-\")\n start = int(value[0])\n if value[1] == \"\":\n end = -1\n else:\n end = int(value[1])\n \n return dict(chrom=chrom, start=start, end=end)\n except:\n raise argparse.ArgumentTypeError(f\"Failed to parse '{value}' as a genomic range. Must be chrom:start-end\")\n","sub_path":"meth5/util.py","file_name":"util.py","file_ext":"py","file_size_in_byte":855,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"114892345","text":"# -*- coding: utf-8 -*-\n\n\"\"\"\n普量学院量化投资课程系列案例源码包\n普量学院版权所有\n仅用于教学目的,严禁转发和用于盈利目的,违者必究\n©Plouto-Quants All Rights Reserved\n\n普量学院助教微信:niuxiaomi3\n\"\"\"\n\n\nfrom datetime import datetime, timedelta\n\nfrom pymongo import UpdateOne, ASCENDING\n\nfrom database import DB_CONN\nfrom stock_util import get_trading_dates, get_all_codes\n\n\"\"\"\n对日行情数据做进一步的处理:\n1. 填充is_trading字段,is_trading用来区分某只股票在某个交易日是否为停牌\n2. 填充停牌日的行情数据\n3. 填充复权因子和前收\n\"\"\"\n\n\ndef fill_is_trading_between(begin_date=None, end_date=None):\n \"\"\"\n 填充指定时间段内的is_trading字段\n :param begin_date: 开始日期\n :param end_date: 结束日期\n \"\"\"\n\n # 获取指定日期范围的所有交易日列表,按日期正序排列\n all_dates = get_trading_dates(begin_date, end_date)\n\n # 循环填充所有交易日的is_trading字段\n for date in all_dates:\n # 填充daily数据集\n fill_single_date_is_trading(date, 'daily')\n # 填充daily_hfq数据集\n fill_single_date_is_trading(date, 'daily_hfq')\n\n\ndef fill_is_trading(date=None):\n \"\"\"\n 为日线数据增加is_trading字段,表示是否交易的状态,True - 交易 False - 停牌\n 从Tushare来的数据不包含交易状态,也不包含停牌的日K数据,为了系统中使用的方便,我们需要填充停牌是的K数据。\n 一旦填充了停牌的数据,那么数据库中就同时包含了停牌和交易的数据,为了区分这两种数据,就需要增加这个字段。\n\n 在填充该字段时,要考虑到是否最坏的情况,也就是数据库中可能已经包含了停牌和交易的数据,但是却没有is_trading\n 字段。这个方法通过交易量是否为0,来判断是否停牌\n \"\"\"\n\n if date is None:\n all_dates = get_trading_dates()\n else:\n all_dates = [date]\n\n for date in all_dates:\n fill_single_date_is_trading(date, 'daily')\n fill_single_date_is_trading(date, 'daily_hfq')\n\n\ndef fill_single_date_is_trading(date, collection_name):\n \"\"\"\n 填充某一个日行情的数据集的is_trading\n :param date: 日期\n :param collection_name: 集合名称\n \"\"\"\n print('填充字段, 字段名: is_trading,日期:%s,数据集:%s' %\n (date, collection_name), flush=True)\n daily_cursor = DB_CONN[collection_name].find(\n {'date': date},\n projection={'code': True, 'volume': True, 'index': True, '_id': False},\n batch_size=1000)\n\n update_requests = []\n for daily in daily_cursor:\n # 当日成交量大于0,则为交易状态\n is_trading = daily['volume'] > 0\n\n update_requests.append(\n UpdateOne(\n {'code': daily['code'], 'date': date, 'index': daily['index']},\n {'$set': {'is_trading': is_trading}}))\n\n if len(update_requests) > 0:\n update_result = DB_CONN[collection_name].bulk_write(update_requests, ordered=False)\n print('填充字段, 字段名: is_trading,日期:%s,数据集:%s,更新:%4d条' %\n (date, collection_name, update_result.modified_count), flush=True)\n\n\ndef fill_daily_k_at_suspension_days(begin_date=None, end_date=None):\n \"\"\"\n 填充指定日期范围内,股票停牌日的行情数据。\n 填充时,停牌的开盘价、最高价、最低价和收盘价都为最近一个交易日的收盘价,成交量为0,\n is_trading是False\n\n :param begin_date: 开始日期\n :param end_date: 结束日期\n \"\"\"\n\n # 当前日期的前一天\n before = datetime.now() - timedelta(days=1)\n # 找到据当前最近一个交易日的所有股票的基本信息\n basics = []\n while 1:\n # 转化为str\n last_trading_date = before.strftime('%Y-%m-%d')\n # 因为TuShare的基本信息最早知道2016-08-09,所以如果日期早于2016-08-09\n # 则结束查找\n if last_trading_date < '2016-08-09':\n break\n\n # 找到当日的基本信息\n basic_cursor = DB_CONN['basic'].find(\n {'date': last_trading_date},\n # 填充时需要用到两个字段股票代码code和上市日期timeToMarket,\n # 上市日期用来判断\n projection={'code': True, 'timeToMarket': True, '_id': False},\n # 一次返回5000条,可以降低网络IO开销,提高速度\n batch_size=5000)\n\n # 将数据放到basics列表中\n basics = [basic for basic in basic_cursor]\n\n # 如果查询到了数据,在跳出循环\n if len(basics) > 0:\n break\n\n # 如果没有找到数据,则继续向前一天\n before -= timedelta(days=1)\n\n # 获取指定日期范围内所有交易日列表\n all_dates = get_trading_dates(begin_date, end_date)\n\n # 填充daily数据集中的停牌日数据\n fill_daily_k_at_suspension_days_at_date_one_collection(\n basics, all_dates, 'daily')\n # 填充daily_hfq数据中的停牌日数据\n fill_daily_k_at_suspension_days_at_date_one_collection(\n basics, all_dates, 'daily_hfq')\n\n\ndef fill_daily_k_at_suspension_days_at_date_one_collection(\n basics, all_dates, collection):\n \"\"\"\n 更新单个数据集的单个日期的数据\n :param basics:\n :param all_dates:\n :param collection:\n :return:\n \"\"\"\n code_last_trading_daily_dict = dict()\n for date in all_dates:\n update_requests = []\n last_daily_code_set = set(code_last_trading_daily_dict.keys())\n for basic in basics:\n code = basic['code']\n # 如果循环日期小于\n if date < basic['timeToMarket']:\n print('日期:%s, %s 还没上市,上市日期: %s' % (date, code, basic['timeToMarket']), flush=True)\n else:\n # 找到当日数据\n daily = DB_CONN[collection].find_one({'code': code, 'date': date, 'index': False})\n if daily is not None:\n code_last_trading_daily_dict[code] = daily\n last_daily_code_set.add(code)\n else:\n if code in last_daily_code_set:\n last_trading_daily = code_last_trading_daily_dict[code]\n suspension_daily_doc = {\n 'code': code,\n 'date': date,\n 'close': last_trading_daily['close'],\n 'open': last_trading_daily['close'],\n 'high': last_trading_daily['close'],\n 'low': last_trading_daily['close'],\n 'volume': 0,\n 'is_trading': False\n }\n update_requests.append(\n UpdateOne(\n {'code': code, 'date': date, 'index': False},\n {'$set': suspension_daily_doc},\n upsert=True))\n if len(update_requests) > 0:\n update_result = DB_CONN[collection].bulk_write(update_requests, ordered=False)\n print('填充停牌数据,日期:%s,数据集:%s,插入:%4d条,更新:%4d条' %\n (date, collection, update_result.upserted_count, update_result.modified_count), flush=True)\n\n\ndef fill_au_factor_pre_close(begin_date, end_date):\n \"\"\"\n 为daily数据集填充:\n 1. 复权因子au_factor,复权的因子计算方式:au_factor = hfq_close/close\n 2. pre_close = close(-1) * au_factor(-1)/au_factor\n :param begin_date: 开始日期\n :param end_date: 结束日期\n \"\"\"\n all_codes = get_all_codes()\n\n for code in all_codes:\n hfq_daily_cursor = DB_CONN['daily_hfq'].find(\n {'code': code, 'date': {'$lte': end_date, '$gte': begin_date}, 'index': False},\n sort=[('date', ASCENDING)],\n projection={'date': True, 'close': True})\n\n date_hfq_close_dict = dict([(x['date'], x['close']) for x in hfq_daily_cursor])\n\n daily_cursor = DB_CONN['daily'].find(\n {'code': code, 'date': {'$lte': end_date, '$gte': begin_date}, 'index': False},\n sort=[('date', ASCENDING)],\n projection={'date': True, 'close': True}\n )\n\n last_close = -1\n last_au_factor = -1\n\n update_requests = []\n for daily in daily_cursor:\n date = daily['date']\n try:\n close = daily['close']\n\n doc = dict()\n\n # 复权因子 = 当日后复权价格 / 当日实际价格\n au_factor = round(date_hfq_close_dict[date] / close, 2)\n doc['au_factor'] = au_factor\n # 当日前收价 = 前一日实际收盘价 * 前一日复权因子 / 当日复权因子\n if last_close != -1 and last_au_factor != -1:\n pre_close = last_close * last_au_factor / au_factor\n doc['pre_close'] = round(pre_close, 2)\n\n last_au_factor = au_factor\n last_close = close\n\n update_requests.append(\n UpdateOne(\n {'code': code, 'date': date, 'index': False},\n {'$set': doc}))\n except:\n print('计算复权因子时发生错误,股票代码:%s,日期:%s' % (code, date), flush=True)\n # 恢复成初始值,防止用错\n last_close = -1\n last_au_factor = -1\n\n if len(update_requests) > 0:\n update_result = DB_CONN['daily'].bulk_write(update_requests, ordered=False)\n print('填充复权因子和前收,股票:%s,更新:%4d条' %\n (code, update_result.modified_count), flush=True)\n\n\nif __name__ == '__main__':\n fill_au_factor_pre_close('2015-01-01', '2015-12-31')\n fill_is_trading_between('2015-01-01', '2015-12-31')\n fill_daily_k_at_suspension_days('2015-01-01', '2015-12-31')\n","sub_path":"初阶-量化交易 策略编写及系统搭建第4期/第3课代码/daily_fixing.py","file_name":"daily_fixing.py","file_ext":"py","file_size_in_byte":10239,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"430465924","text":"# Copyright (c) 2020 Raytheon BBN Technologies, Inc. All Rights Reserved.\n# This document does not contain technology or Technical Data controlled under either\n# the U.S. International Traffic in Arms Regulations or the U.S. Export Administration\nfrom ..util import *\n\nclass PPrintUnderlay:\n @classmethod\n def static_init(cls, **kwargs):\n super(PPrintUnderlay, cls).static_init(**kwargs)\n cls.enums = dict()\n cls.bitmasks = dict()\n cls.alts = dict()\n cls.alt_handlers = dict()\n\n\n @classmethod\n def parse_config_line(cls, key, entry):\n if key == 'ENUM' and len(entry) == 3:\n cls.add_enum(entry[0], atoi(entry[1]), entry[2])\n elif key == 'BITMASK' and len(entry) == 3:\n cls.add_bitmask(entry[0], atoi(entry[1]), entry[2])\n elif key == 'ALT' and len(entry) == 2:\n cls.add_alt(entry[0], entry[1])\n else:\n super(PPrintUnderlay, cls).parse_config_line(key, entry)\n\n @classmethod\n def add_enum(cls, name, val, display):\n cls.enums.setdefault(name, dict())[val] = display\n\n @classmethod\n def get_enum(cls, name, val):\n if name not in cls.enums:\n cls.l.error(\"{:s} doesn't appear to be an enum field\")\n raise AttributeError(\"Invalid enum field\")\n if val in cls.enums[name]:\n return cls.enums[name][val]\n else:\n return None\n\n @classmethod\n def add_bitmask(cls, name, val, display):\n cls.bitmasks.setdefault(name, dict())[val] = display\n \n @classmethod\n def get_bitmasks(cls, name, val):\n out = set()\n if name not in cls.bitmasks:\n cls.l.error(\"{:s} doesn't appear to be a bitmask field.\")\n raise AttributeError(\"Invalid bitmask field\")\n for mask in cls.bitmasks[name]:\n if mask & val != 0:\n out.add(cls.bitmasks[name][mask])\n val &= ~mask\n if val != 0:\n out.add(\"UNKNOWN ({:d})\".format(val))\n return out\n\n @classmethod\n def add_alt_handler(cls, h_name, handler):\n cls.alt_handlers[h_name] = handler\n\n @classmethod\n def add_alt(cls, name, h_name):\n if h_name not in cls.alt_handlers:\n cls.l.error(\"Missing alt handler {:s} for field {:s}\".format(h_name, name))\n raise AttributeError(\"Invalid alt handler\")\n cls.alts[name] = cls.alt_handlers[h_name]\n\n def field_to_pstring(self, name, idx, val):\n if name in self.enums:\n enum = self.get_enum(name, val)\n if enum is not None:\n return enum\n elif name in self.bitmasks:\n return \" | \".join(self.get_bitmasks(name, val))\n elif name in self.alts:\n return \"{!s}\".format(self.alts[name](self, name))\n return super().field_to_pstring(name, idx, val) \n","sub_path":"torch/base/underlays/pprint.py","file_name":"pprint.py","file_ext":"py","file_size_in_byte":2861,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"188951313","text":"# 1342. 将数字变成 0 的操作次数 https://leetcode.com/problems/number-of-steps-to-reduce-a-number-to-zero/\nnum = 123\ncount = 0\nwhile num > 0:\n if num%2 == 0:\n num = num/2\n else:\n num -= 1\n count += 1\n\nprint(count)\n\n\n\n\n# ans = 6","sub_path":"course-8/1342.py","file_name":"1342.py","file_ext":"py","file_size_in_byte":261,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"61258620","text":"import time\n\n# Import the ADS1x15 module.\nimport Adafruit_ADS1x15\n\n# map function similar to arduino \ndef valmap(x, in_min, in_max, out_min, out_max):\n return int((x-in_min) * (out_max-out_min) / (in_max-in_min) + out_min)\n\n# Create an ADS1115 ADC (16-bit) instance.\nadc = Adafruit_ADS1x15.ADS1115()\n\ncurrent_value = previous_value = 0\n\ndef stepper_direction_movement():\n global current_value\n global previous_value\n direction = None\n current_value = adc.read_adc(1)\n if abs(current_value-previous_value) >= 100:\n if current_value > previous_value:\n direction = \"Right\" \n elif current_value < previous_value:\n direction = \"Left\"\n else:\n direction = \"Steady\"\n previous_value = current_value\n return direction\n\ntry:\n while True:\n servo_map_value = valmap(adc.read_adc(0), 0, 31767, 126, 625 )\n print('Channel 0:', servo_map_value, 'Channel 1:', stepper_direction_movement())\n time.sleep(1)\nexcept KeyboardInterrupt:\n adc.stop_adc()\n","sub_path":"Samples/ads1115sample.py","file_name":"ads1115sample.py","file_ext":"py","file_size_in_byte":1027,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"648344579","text":"#! python3\n\nfrom __future__ import print_function\n\nimport getopt\nimport multiprocessing\nimport logging\nimport sys\nimport time\n\nfrom gensim import corpora, models\n\ndef usage ():\n print(\"\"\"Usage: python3 map_topics_to_docs.py --dict_file= \n --mm_file= --lda_file= \n --mappings_file=\"\"\")\n\n# Taken from http://stackoverflow.com/questions/5574702/how-to-print-to-stderr-in-python\ndef eprint(*args, **kwargs):\n print(time.strftime(\"%Y-%m-%dT%H:%M:%S\"), \" \", *args, file=sys.stderr, **kwargs)\n\ndef main():\n try:\n opts, args = getopt.getopt(sys.argv[1:], 'd:m:l:t', [\"dict_file=\", \"mm_file=\", \n \"mappings_file=\", \"lda_file=\"])\n except getopt.GetoptError as err:\n print(err)\n usage()\n sys.exit()\n\n for o,a in opts:\n if o in (\"-d\", \"--dict_file\"):\n dict_file = a\n elif o in (\"-m\", \"--mm_file\"):\n mm_file = a\n elif o in (\"-m\", \"--lda_file\"):\n lda_file = a\n elif o in (\"-t\", \"--mappings_file\"):\n mappings_file = a\n else:\n usage()\n sys.exit()\n\n logging.basicConfig(format='%(asctime)s : %(levelname)s : %(message)s', level=logging.INFO)\n\n eprint(\"Loading dictionary and corpus...\")\n dictionary = corpora.Dictionary.load(dict_file)\n\n corpus = corpora.MmCorpus(mm_file)\n # train the model. Using tfidf for now because it is fast\n eprint(\"Creating TfidfModel...\")\n tfidf = models.TfidfModel(corpus)\n \n # Use model to transform original corpus\n eprint(\"Transforming original corpus...\")\n corpus_tfidf = tfidf[corpus]\n\n eprint(\"Loading LDA model...\")\n # Transform to LDA model. \n lda_model = models.LdaModel.load(lda_file)\n\n eprint(\"Generating mappings file...\")\n with open(mappings_file, 'w', encoding='utf-8') as f:\n eprint(\"Mapping topics to doc indices...\")\n f.write(\"%%Mapping Topics to Doc Indices\\n\")\n f.write(\"%%doc_index [[topic_index1 topic_index1_probability] [topic_index2 topic2_index2_probability]...]\\n\")\n\n doc_index = 0\n for doc in corpus_tfidf:\n f.write(\"%s \" % doc_index)\n topic_indices = []\n topics = lda_model[doc]\n for topic in topics:\n # Setting arbitrary minimum threshold for probability here\n if(topic[1] > 0.20):\n topic_indices.append(topic[0])\n topic_indices.append(round(topic[1],2))\n\n if(len(topic_indices) == 0 and len(topics) > 0):\n # Since no topics met our threshold, we'll try going for the closest match\n index = max(topics, key=lambda x:x[1])\n topic_indices.append(topic[0])\n topic_indices.append(round(topic[1],2))\n\n f.write(\" \".join(map(str, topic_indices)))\n f.write(\"\\n\")\n if(doc_index % 1000 == 0):\n eprint(\"%s documents processed...\" % doc_index)\n doc_index += 1\n\n print(\"Mapping terms to topic indices...\")\n f.write(\"%%Mapping Terms to Topic Indices\\n\")\n f.write(\"%%topic_index^[term1^term2...]\\n\")\n\n for x in range(0, lda_model.num_topics):\n f.write(\"%s\" % x)\n for terms in lda_model.get_topic_terms(x):\n # TODO: Do we really just want to ignore non-ASCII characters?\n # It 'works' for the prototype, but we might consider a more robust \n # approach moving forward\n f.write(\"^%s\" % dictionary[terms[0]].encode('utf-8').decode('utf-8', 'ignore'))\n f.write(\"\\n\")\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"bin/map_topics_to_docs.py","file_name":"map_topics_to_docs.py","file_ext":"py","file_size_in_byte":3741,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"29755485","text":"# tic tac toe\n\nimport sys\nimport numpy as np\n\nLENGTH = 3\nXVAL = -1\nOVAL = 1\n\ndebug=False\n\nclass SmartAgent :\n def __init__(self, eps=0.1, alpha=0.5) :\n self.eps = eps\n self.alpha = alpha\n self.state_history = []\n self.V = [0.5]*(3**(LENGTH * LENGTH))\n\n def resetHistory(self) :\n self.state_history = []\n\n def set_symbol(self,sym) :\n self.sym = sym # XVAL or OVAL\n\n def saveBrainX(self):\n outf = open(\"./myhistoryX\",\"w\")\n for i in range(len(self.V)):\n outf.write(str(self.V[i]) + \"\\n\")\n outf.close()\n\n def saveBrainO(self):\n outf = open(\"./myhistoryO\",\"w\")\n for i in range(len(self.V)):\n outf.write(str(self.V[i]) + \"\\n\")\n outf.close()\n\n def loadBrainX(self):\n inf = open(\"./myhistoryX\",\"r\")\n i = 0\n for line in inf:\n v = float(line)\n self.V[i] = v\n i = i + 1\n inf.close()\n\n def loadBrainO(self):\n inf = open(\"./myhistoryO\",\"r\")\n i = 0\n for line in inf:\n v = float(line)\n self.V[i] = v\n i = i + 1\n inf.close()\n\n def update_state_history(self, s) :\n self.state_history.append(s)\n\n if debug :\n print(\"smart robot updating state history \")\n for ii in reversed(self.state_history) :\n print(ii)\n\n def update(self,env) :\n reward = None\n if env.is_tie():\n reward = 0.5\n else:\n reward = env.reward(self.sym) # 1 if this player won; 0 otherwise\n\n state = env.get_state()\n\n if reward == 1:\n self.V[state] = 1.0\n elif reward == 0.5:\n self.V[state] = 0.5\n else:\n self.V[state] = 0.0\n\n if debug :\n print(\"current state, value\")\n for ii in reversed(self.state_history) :\n print(\"state \",ii, \"value \", self.V[ii])\n \n target = reward\n\n for prev in reversed(self.state_history) :\n value = self.V[prev] + self.alpha * (target - self.V[prev])\n self.V[prev] = value\n target = value\n\n if debug :\n print(\"iteration learned state, value\")\n for ii in reversed(self.state_history) :\n print(\"state \",ii, \"value \", self.V[ii])\n\n self.resetHistory()\n\n def take_action(self, env):\n r = np.random.rand()\n if r < self.eps : # explore by taking a random action\n if debug :\n print(\"Making a Random Move\")\n possible_moves = []\n for i in range(LENGTH):\n for j in range(LENGTH):\n if env.is_empty(i, j):\n possible_moves.append((i, j))\n idx = np.random.choice(len(possible_moves))\n next_move = possible_moves[idx]\n env.board[next_move[0], next_move[1]] = self.sym\n else: # choose best action based on current values\n qvalues={}\n best_value = -1\n for i in range(LENGTH) :\n for j in range(LENGTH) :\n if env.is_empty(i,j) :\n # we want to know the state we would be in, if we\n # made this move. Why? so we can get the \"Value\"\n # of making this move. We want to choose the\n # best next move - i.e., the one with the highest\n # value\n\n env.board[i,j] = self.sym # pretend to make the move\n state = env.get_state() # the integer representing the state\n\n # is this a winning move?\n if env.game_over() :\n self.V[state] = 1 \n\n env.board[i,j] = 0 # unmove as soon as possible\n qvalues[(i,j)] = self.V[state]\n if self.V[state] > best_value :\n best_value = self.V[state]\n next_move = (i,j)\n\n \n if debug :\n print(\"Making a Greedy Move\")\n for i in range(LENGTH):\n print(\"-----------------\")\n for j in range(LENGTH):\n if env.is_empty(i,j):\n print('\"%.2f|\" % qvalues[(i,j)]',end=\"\")\n else:\n if env.board[i,j] == env.x:\n print(\" x|\",end=\"\")\n elif env.board[i,j] == env.o:\n print(\" o|\",end=\"\")\n else:\n print(\" |\",end=\"\")\n print(\"\")\n print(\"-----------------\")\n \n env.board[next_move[0], next_move[1]] = self.sym\n\nclass Environment:\n def __init__(self):\n self.board = np.zeros((LENGTH, LENGTH))\n self.x = XVAL # represents an x on the board, player 1\n self.o = OVAL # represents an o on the board, player 2\n self.winner = 0\n self.ended = False\n self.num_states = 3**(LENGTH*LENGTH) # 19683\n\n def is_empty(self, i, j) :\n return self.board[i,j] == 0\n\n def is_tie(self):\n return (self.winner == 0)\n\n def reward(self, sym) :\n # the winner gets the reward\n if self.winner == sym :\n return 1\n else:\n return 0\n\n def get_state(self) :\n # \"godelize\" state\n # 9 cells, each cell can have 3 possible values:\n # empty, x, o ==> 0, 1, -1\n # cell 8 (2,2) = 3^8 * 0 | 3^8 * 1 | 3^8 * 2 for empty, x, o (0,6561,13122)\n # cell 7 (2,1) = 3^7 * 0 | 3^7 * 1 | 3^7 * 2 for empty, x, o (0,2187,4374)\n # cell 6 (2,0) = 3^6 * 0 | 3^6 * 1 | 3^6 * 2 for empty, x, o (0,729,1458)\n # cell 5 (1,2) = 3^5 * 0 | 3^5 * 1 | 3^5 * 2 for empty, x, o (0,243,486)\n # cell 4 (1,1) = 3^4 * 0 | 3^4 * 1 | 3^4 * 2 for empty, x, o (0,81,192)\n # cell 3 (1,0) = 3^3 * 0 | 3^3 * 1 | 3^3 * 2 for empty, x, o (0,27,54)\n # cell 2 (0,2) = 3^2 * 0 | 3^2 * 1 | 3^2 * 2 for empty, x, o (0,9,18)\n # cell 1 (0,1) = 3^1 * 0 | 3^1 * 1 | 3^1 * 2 for empty, x, o (0,3,6)\n # cell 0 (0,0) = 3^0 * 0 | 3^0 * 1 | 3^0 * 2 for empty, x, o (0,1,2)\n\n # examine each cell and calculate the integer corresponding\n # to the state (symbols in each cell)\n\n k = 0\n h = 0\n for i in range(LENGTH):\n for j in range(LENGTH):\n if self.board[i,j] == 0:\n v = 0\n elif self.board[i,j] == self.x:\n v = 1\n elif self.board[i,j] == self.o:\n v = 2\n\n h += (3**k) * v\n k += 1\n\n return h\n\n def game_over(self) :\n \n # check rows\n # (i,j) == 1 ==> o in cell, so if (i,0) + (i,1) + (i,2) == 3, then o won!\n # (i,j) == -1 ==> x in cell, so if (i,0) + (i,1) + (i,2) == -3, then x won!\n\n for i in range(LENGTH) :\n for player in (self.x, self.o) :\n if self.board[i].sum() == player*LENGTH :\n self.winner = player\n self.ended = True\n return True\n\n # check columns\n for j in range(LENGTH) :\n for player in (self.x, self.o) :\n if self.board[:,j].sum() == player*LENGTH :\n self.winner = player\n self.ended = True\n return True\n\n # check diagonals\n for player in (self.x, self.o) :\n if (self.board[0,0] + self.board[1,1] + self.board[2,2]) == player*LENGTH :\n self.winner = player\n self.ended = True\n return True\n\n if (self.board[0,2] + self.board[1,1] + self.board[2,0]) == player*LENGTH :\n self.winner = player\n self.ended = True\n return True\n\n # check if draw\n # all cells have an x or o\n if np.all((self.board == 0) == False):\n self.winner = 0\n self.ended = True\n return True\n\n # game is not over\n self.winner = 0\n return False\n\n # Example board\n # -------------\n # | x | | |\n # -------------\n # | | | |\n # -------------\n # | | | o |\n # -------------\n def draw_board(self):\n for i in range(LENGTH):\n print(\"-------------\")\n for j in range(LENGTH):\n print(\"|\",end=\"\")\n if self.board[i,j] == self.x:\n print(\"x\",end=\"\")\n elif self.board[i,j] == self.o:\n print(\"o\",end=\"\")\n else:\n print(\" \",end=\"\")\n print(\"|\")\n print(\"-------------\")\n\nclass Human:\n def __init__(self):\n pass\n\n def set_symbol(self, sym):\n self.sym = sym\n\n def take_action(self, env):\n while True:\n move = input(\"Enter coordinates i,j for your next move (i,j=0..2): \")\n i, j = move.split(',')\n i = int(i)\n j = int(j)\n if env.is_empty(i, j):\n env.board[i,j] = self.sym\n break\n\n def update(self, env) :\n pass\n\n def update_state_history(self, s):\n pass\n\ndef play_smartgame(p1, p2, env, draw=False):\n current_player = None\n while not env.game_over():\n if current_player == p1:\n current_player = p2\n else:\n current_player = p1\n\n if draw:\n if draw == 1 and current_player == p1:\n env.draw_board()\n if draw == 2 and current_player == p2:\n env.draw_board()\n\n current_player.take_action(env)\n\n # track state history, so\n # when game over, we can update\n # \"values\" so that are able\n # to play better next time\n\n state = env.get_state()\n\n p1.update_state_history(state)\n p2.update_state_history(state)\n\n # game over - \n if draw:\n env.draw_board()\n\n # update the value function\n p1.update(env)\n p2.update(env)\n\ndef play_game(p1, p2, env, draw=False):\n current_player = None\n while not env.game_over():\n if current_player == p1:\n current_player = p2\n else:\n current_player = p1\n\n # draw the board before the user who wants to see it makes a move\n if draw:\n if draw == 1 and current_player == p1:\n env.draw_board()\n if draw == 2 and current_player == p2:\n env.draw_board()\n\n # current player makes a move\n current_player.take_action(env)\n\n # game over\n if draw:\n env.draw_board()\n\nif __name__ == '__main__':\n\n print(\"Training Experts\")\n\n ai1=SmartAgent()\n ai1.set_symbol(XVAL)\n\n ai2=SmartAgent()\n ai2.set_symbol(OVAL)\n\n T=30000\n zz=0\n for t in range(T):\n if t % 200 == 0 :\n zz = zz + 1\n print(\". \",end=\"\")\n if zz % 10 == 0 :\n print(\"\")\n sys.stdout.flush()\n\n play_smartgame(ai1,ai2,Environment())\n\n print(\"\\nDone! Experts Trained.\")\n\n ai1.eps = 0.0\n ai2.eps = 0.0\n\n debug=False\n\n goFirst = False\n answer = input(\"Go First? [Y/n]: \")\n if answer.lower()[0] == 'n':\n goFirst = False\n else:\n goFirst = True\n\n human = Human()\n\n if goFirst :\n human.set_symbol(XVAL)\n ai = ai2\n while True:\n myenv = Environment()\n play_smartgame(human, ai, myenv, draw=1)\n\n print(\"\")\n if myenv.winner == XVAL :\n print(\"Congratulations! You Won!!!!\")\n elif myenv.winner == OVAL :\n print(\"Good Try! You're Still Learning.\")\n else:\n print(\"Tie! Let's Play More.\")\n print(\"\")\n \n answer = input(\"Play again? [Y/n]: \")\n if answer.lower()[0] == 'n':\n break\n else:\n human.set_symbol(OVAL)\n ai = ai1\n while True:\n myenv = Environment()\n play_smartgame(ai, human, myenv, draw=2)\n \n print(\"\")\n if myenv.winner == OVAL :\n print(\"Congratulations! You Won!!!!\")\n elif myenv.winner == XVAL :\n print(\"Good Try! You're Still Learning.\")\n else:\n print(\"Tie! Let's Play More.\")\n print(\"\")\n\n answer = input(\"Play again? [Y/n]: \")\n if answer.lower()[0] == 'n':\n break\n","sub_path":"Expert/tttExpert.py","file_name":"tttExpert.py","file_ext":"py","file_size_in_byte":9866,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"169624581","text":"from __future__ import absolute_import\nfrom pyswagger import const\nimport json\nimport six\nimport os\n\n\nclass Getter(six.Iterator):\n \"\"\" base of getter object\n\n Idealy, to subclass a getter, you just need to override load function.\n The part to extend getter would be finalized once Swagger 2.0 is ready.\n \"\"\"\n\n def __init__(self, path):\n self.base_path = path\n\n def __iter__(self):\n return self\n\n def __next__(self):\n if len(self.urls) == 0:\n raise StopIteration\n\n path, name = self.urls.pop(0)\n obj = self.load(path)\n if isinstance(obj, six.string_types):\n obj = json.loads(obj)\n elif isinstance(obj, six.binary_type):\n obj = json.loads(obj.decode('utf-8'))\n else:\n raise ValueError('Unknown types: [{0}]'.format(str(type(obj))))\n\n # find urls to retrieve from resource listing file\n if name == '':\n urls = self.__find_urls(obj)\n self.urls.extend(zip(\n map(lambda u: self.base_path + u, urls),\n map(lambda u: u[1:], urls)\n ))\n\n return obj, name\n\n def load(self, path):\n \"\"\" load the resource, and return for parsing.\n\n :return: name and json object of resources\n :rtype: (str, dict)\n \"\"\"\n raise NotImplementedError()\n\n def __find_urls(self, obj):\n \"\"\" helper function to located relative url in Resource Listing object.\n\n :param dict obj: json of Resource Listing object.\n :return: urls of resources\n :rtype: a list of str\n \"\"\"\n urls = []\n if const.SCHEMA_APIS in obj:\n if isinstance(obj[const.SCHEMA_APIS], list):\n for api in obj[const.SCHEMA_APIS]:\n urls.append(api[const.SCHEMA_PATH])\n else:\n raise TypeError('Invalid type of apis: ' + type(obj[const.SCHEMA_APIS]))\n\n return urls\n\n\nclass LocalGetter(Getter):\n \"\"\" default getter implmenetation for local resource file\n \"\"\"\n def __init__(self, path):\n super(LocalGetter, self).__init__(path)\n\n for n in const.SWAGGER_FILE_NAMES:\n if self.base_path.endswith(n):\n self.base_path = os.path.dirname(self.base_path)\n self.urls = [(path, '')]\n break\n else:\n p = os.path.join(path, n)\n if os.path.isfile(p):\n self.urls = [(p, '')]\n break\n else:\n raise ValueError('Unable to locate resource file: [{0}]'.format(path))\n\n def load(self, path):\n ret = None\n # make sure we get .json files\n if not path.endswith(const.RESOURCE_FILE_EXT):\n path = path + '.' + const.RESOURCE_FILE_EXT\n\n with open(path, 'r') as f:\n ret = f.read()\n\n return ret\n\n\nclass UrlGetter(Getter):\n \"\"\" default getter implementation for remote resource file\n \"\"\"\n def __init__(self, path):\n super(UrlGetter, self).__init__(path)\n if self.base_path.endswith('/'):\n self.base_path = self.base_path[:-1]\n self.urls = [(path, '')]\n\n def load(self, path):\n ret = f = None\n try:\n f = six.moves.urllib.request.urlopen(path)\n ret = f.read()\n finally:\n if f:\n f.close()\n\n return ret\n\n","sub_path":"pyswagger/getter.py","file_name":"getter.py","file_ext":"py","file_size_in_byte":3414,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"22136277","text":"#!/usr/bin/env python3\n# © 2015 James R. Barlow: github.com/jbarlow83\n\nfrom __future__ import print_function\nfrom subprocess import Popen, PIPE, check_output\nimport os\nimport shutil\nfrom contextlib import suppress\nimport sys\nimport pytest\nfrom ocrmypdf.pageinfo import pdf_get_all_pageinfo\nimport PyPDF2 as pypdf\nfrom ocrmypdf import ExitCode\n\n\nif sys.version_info.major < 3:\n print(\"Requires Python 3.4+\")\n sys.exit(1)\n\nTESTS_ROOT = os.path.abspath(os.path.dirname(__file__))\nPROJECT_ROOT = os.path.dirname(TESTS_ROOT)\nOCRMYPDF = os.path.join(PROJECT_ROOT, 'OCRmyPDF.sh')\nTEST_RESOURCES = os.path.join(PROJECT_ROOT, 'tests', 'resources')\nTEST_OUTPUT = os.environ.get(\n 'OCRMYPDF_TEST_OUTPUT',\n default=os.path.join(PROJECT_ROOT, 'tests', 'output'))\nTEST_BINARY_PATH = os.path.join(TEST_OUTPUT, 'fakebin')\n\n\ndef setup_module():\n with suppress(FileNotFoundError):\n shutil.rmtree(TEST_OUTPUT)\n with suppress(FileExistsError):\n os.mkdir(TEST_OUTPUT)\n\n\ndef run_ocrmypdf_sh(input_file, output_file, *args):\n sh_args = ['sh', OCRMYPDF] + list(args) + [input_file, output_file]\n sh = Popen(\n sh_args, close_fds=True, stdout=PIPE, stderr=PIPE,\n universal_newlines=True)\n out, err = sh.communicate()\n return sh, out, err\n\n\ndef _make_input(input_basename):\n return os.path.join(TEST_RESOURCES, input_basename)\n\n\ndef _make_output(output_basename):\n return os.path.join(TEST_OUTPUT, output_basename)\n\n\ndef check_ocrmypdf(input_basename, output_basename, *args):\n input_file = _make_input(input_basename)\n output_file = _make_output(output_basename)\n\n sh, _, err = run_ocrmypdf_sh(input_file, output_file, *args)\n assert sh.returncode == 0, err\n assert os.path.exists(output_file), \"Output file not created\"\n assert os.stat(output_file).st_size > 100, \"PDF too small or empty\"\n return output_file\n\n\ndef run_ocrmypdf_env(input_basename, output_basename, *args, env=None):\n input_file = _make_input(input_basename)\n output_file = _make_output(output_basename)\n\n if env is None:\n env = os.environ\n\n p_args = ['ocrmypdf'] + list(args) + [input_file, output_file]\n p = Popen(\n p_args, close_fds=True, stdout=PIPE, stderr=PIPE,\n universal_newlines=True, env=env)\n out, err = p.communicate()\n return p, out, err\n\n\ndef test_quick():\n check_ocrmypdf('c02-22.pdf', 'test_quick.pdf')\n\n\ndef test_deskew():\n # Run with deskew\n deskewed_pdf = check_ocrmypdf('skew.pdf', 'test_deskew.pdf', '-d')\n\n # Now render as an image again and use Leptonica to find the skew angle\n # to confirm that it was deskewed\n from ocrmypdf.ghostscript import rasterize_pdf\n import logging\n log = logging.getLogger()\n\n deskewed_png = _make_output('deskewed.png')\n\n rasterize_pdf(\n deskewed_pdf,\n deskewed_png,\n xres=150,\n yres=150,\n raster_device='pngmono',\n log=log)\n\n from ocrmypdf.leptonica import pixRead, pixDestroy, pixFindSkew\n pix = pixRead(deskewed_png)\n skew_angle, skew_confidence = pixFindSkew(pix)\n pix = pixDestroy(pix)\n\n print(skew_angle)\n assert -0.5 < skew_angle < 0.5, \"Deskewing failed\"\n\n\ndef test_clean():\n check_ocrmypdf('skew.pdf', 'test_clean.pdf', '-c')\n\n\ndef check_exotic_image(pdf, renderer):\n check_ocrmypdf(\n pdf,\n 'test_{0}_{1}.pdf'.format(pdf, renderer),\n '-dc',\n '--pdf-renderer', renderer)\n\n\ndef test_exotic_image():\n yield check_exotic_image, 'palette.pdf', 'hocr'\n yield check_exotic_image, 'palette.pdf', 'tesseract'\n yield check_exotic_image, 'cmyk.pdf', 'hocr'\n yield check_exotic_image, 'cmyk.pdf', 'tesseract'\n\n\ndef test_preserve_metadata():\n pdf_before = pypdf.PdfFileReader(_make_input('graph.pdf'))\n\n output = check_ocrmypdf('graph.pdf', 'test_metadata_preserve.pdf')\n\n pdf_after = pypdf.PdfFileReader(output)\n\n for key in ('/Title', '/Author'):\n assert pdf_before.documentInfo[key] == pdf_after.documentInfo[key]\n\n\ndef test_override_metadata():\n input_file = _make_input('c02-22.pdf')\n output_file = _make_output('test_override_metadata.pdf')\n\n german = 'Du siehst den Wald vor lauter Bäumen nicht.'\n chinese = '孔子'\n high_unicode = 'U+1030C is: 𐌌'\n\n p, out, err = run_ocrmypdf_env(\n input_file, output_file,\n '--title', german,\n '--author', chinese,\n '--subject', high_unicode)\n\n assert p.returncode == ExitCode.ok\n\n pdf = output_file\n\n out_pdfinfo = check_output(['pdfinfo', pdf], universal_newlines=True)\n lines_pdfinfo = out_pdfinfo.splitlines()\n pdfinfo = {}\n for line in lines_pdfinfo:\n k, v = line.strip().split(':', maxsplit=1)\n pdfinfo[k.strip()] = v.strip()\n\n assert pdfinfo['Title'] == german\n assert pdfinfo['Author'] == chinese\n assert pdfinfo['Subject'] == high_unicode\n assert pdfinfo.get('Keywords', '') == ''\n\n\ndef check_oversample(renderer):\n oversampled_pdf = check_ocrmypdf(\n 'skew.pdf', 'test_oversample_%s.pdf' % renderer, '--oversample', '300',\n '--pdf-renderer', renderer)\n\n pdfinfo = pdf_get_all_pageinfo(oversampled_pdf)\n\n print(pdfinfo[0]['xres'])\n assert abs(pdfinfo[0]['xres'] - 300) < 1\n\n\ndef test_oversample():\n yield check_oversample, 'hocr'\n yield check_oversample, 'tesseract'\n\n\ndef test_repeat_ocr():\n sh, _, _ = run_ocrmypdf_sh('graph_ocred.pdf', 'wontwork.pdf')\n assert sh.returncode != 0\n\n\ndef test_force_ocr():\n out = check_ocrmypdf('graph_ocred.pdf', 'test_force.pdf', '-f')\n pdfinfo = pdf_get_all_pageinfo(out)\n assert pdfinfo[0]['has_text']\n\n\ndef test_skip_ocr():\n check_ocrmypdf('graph_ocred.pdf', 'test_skip.pdf', '-s')\n\n\ndef test_argsfile():\n with open(_make_output('test_argsfile.txt'), 'w') as argsfile:\n print('--title', 'ArgsFile Test', '--author', 'Test Cases',\n sep='\\n', end='\\n', file=argsfile)\n check_ocrmypdf('graph.pdf', 'test_argsfile.pdf',\n '@' + _make_output('test_argsfile.txt'))\n\n\ndef check_ocr_timeout(renderer):\n out = check_ocrmypdf('skew.pdf', 'test_timeout_%s.pdf' % renderer,\n '--tesseract-timeout', '1.0')\n pdfinfo = pdf_get_all_pageinfo(out)\n assert pdfinfo[0]['has_text'] == False\n\n\ndef test_ocr_timeout():\n yield check_ocr_timeout, 'hocr'\n yield check_ocr_timeout, 'tesseract'\n\n\ndef test_skip_big():\n out = check_ocrmypdf('enormous.pdf', 'test_enormous.pdf',\n '--skip-big', '10')\n pdfinfo = pdf_get_all_pageinfo(out)\n assert pdfinfo[0]['has_text'] == False\n\n\ndef check_maximum_options(renderer):\n check_ocrmypdf(\n 'multipage.pdf', 'test_multipage%s.pdf' % renderer,\n '-d', '-c', '-i', '-g', '-f', '-k', '--oversample', '300',\n '--skip-big', '10', '--title', 'Too Many Weird Files',\n '--author', 'py.test', '--pdf-renderer', renderer)\n\n\ndef test_maximum_options():\n yield check_maximum_options, 'hocr'\n yield check_maximum_options, 'tesseract'\n\n\ndef override_binary(binary, replacement):\n '''Create a directory that contains a symlink named 'binary' that\n points to replacement, another program to use in place of the\n regular binary for testing.\n\n override_binary('gs', 'replace_gs.py') will create an environment\n in which \"gs\" will invoke replace_gs.py.\n\n Not thread-safe with other test at the moment.\n\n Returns the os.environ[\"PATH\"] string under which this binary will\n be invoked.'''\n\n replacement_path = os.path.abspath(os.path.join(TESTS_ROOT,\n replacement))\n subdir = os.path.splitext(os.path.basename(replacement))[0]\n binary_path = os.path.abspath(os.path.join(TEST_BINARY_PATH,\n subdir,\n binary))\n with suppress(FileExistsError):\n os.makedirs(os.path.dirname(binary_path))\n assert os.path.isdir(os.path.dirname(binary_path))\n assert not os.path.lexists(binary_path)\n print(\"symlink %s -> %s\" % (replacement_path, binary_path))\n os.symlink(replacement_path, binary_path)\n\n os.chmod(replacement_path, int('755', base=8))\n\n return os.path.dirname(binary_path) + os.pathsep + os.environ[\"PATH\"]\n\n\n@pytest.fixture\ndef break_ghostscript_pdfa():\n return override_binary('gs', 'replace_ghostscript_nopdfa.py')\n\n\n@pytest.mark.skipif(os.environ.get('OCRMYPDF_IN_DOCKER', False),\n reason=\"Requires writable filesystem\")\ndef test_ghostscript_pdfa_fails(break_ghostscript_pdfa):\n env = os.environ.copy()\n env['PATH'] = break_ghostscript_pdfa\n\n p, out, err = run_ocrmypdf_env(\n 'graph_ocred.pdf', 'not_a_pdfa.pdf', '-v', '1', '--skip-text', env=env)\n assert p.returncode == ExitCode.ok, err # no longer using JHOVE PDFA check\n\n\ndef test_tesseract_missing_tessdata():\n env = os.environ.copy()\n env['TESSDATA_PREFIX'] = '/tmp'\n\n p, _, err = run_ocrmypdf_env(\n 'graph_ocred.pdf', 'not_a_pdfa.pdf', '-v', '1', '--skip-text', env=env)\n assert p.returncode == ExitCode.missing_dependency, err\n\n\ndef test_invalid_input_pdf():\n p, out, err = run_ocrmypdf_env(\n 'invalid.pdf', 'wont_be_created.pdf')\n assert p.returncode == ExitCode.input_file, err\n\n\ndef test_blank_input_pdf():\n p, out, err = run_ocrmypdf_env(\n 'blank.pdf', 'still_blank.pdf')\n assert p.returncode == ExitCode.ok\n\n\ndef test_french():\n p, out, err = run_ocrmypdf_env(\n 'francais.pdf', 'francais.pdf', '-l', 'fra')\n assert p.returncode == ExitCode.ok, \\\n \"This test may fail if Tesseract language packs are missing\"\n\n\ndef test_klingon():\n p, out, err = run_ocrmypdf_env(\n 'francais.pdf', 'francais.pdf', '-l', 'klz')\n assert p.returncode == ExitCode.bad_args\n\n\ndef test_missing_docinfo():\n p, out, err = run_ocrmypdf_env(\n 'missing_docinfo.pdf', 'missing_docinfo.pdf', '-l', 'eng', '-c')\n assert p.returncode == ExitCode.ok, err\n\n\ndef test_uppercase_extension():\n shutil.copy(_make_input(\"skew.pdf\"), _make_input(\"UPPERCASE.PDF\"))\n try:\n check_ocrmypdf(\"UPPERCASE.PDF\", \"UPPERCASE_OUT.PDF\")\n finally:\n os.unlink(_make_input(\"UPPERCASE.PDF\"))\n\n\ndef test_input_file_not_found():\n input_file = \"does not exist.pdf\"\n sh, out, err = run_ocrmypdf_sh(\n _make_input(input_file),\n _make_output(\"will not happen.pdf\"))\n assert sh.returncode == ExitCode.input_file\n assert (input_file in out or input_file in err)\n\n\ndef test_input_file_not_a_pdf():\n input_file = __file__ # Try to OCR this file\n sh, out, err = run_ocrmypdf_sh(\n _make_input(input_file),\n _make_output(\"will not happen.pdf\"))\n assert sh.returncode == ExitCode.input_file\n assert (input_file in out or input_file in err)\n\n","sub_path":"tests/test_main.py","file_name":"test_main.py","file_ext":"py","file_size_in_byte":10792,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"267249716","text":"# Play audio when stuff happens\nimport math\nimport struct\nimport numpy\nimport pygame.mixer\nFREQ = 44100\npygame.mixer.init(frequency=FREQ, size=-16, channels=1)\n\nAMPLITUDE = 2048\n\npips = []\ndef make_pip(pitch, duration):\n\tsamples = [math.sin(2.0 * math.pi * pitch * t / FREQ) for t in range(0, int(duration * FREQ))]\n\tdata = numpy.array([int(s * AMPLITUDE) for s in samples], dtype=numpy.int16)\n\tsound = pygame.sndarray.make_sound(data)\n\tpips.append(sound)\n\nmake_pip(440, 0.0625) # One point gained\nmake_pip(523, 0.0625) # Two points gained at once\nmake_pip(660, 0.125) # Three ditto ditto\nmake_pip(880, 0.125)\nmake_pip(1047, 0.125) # The last one gets \"and anything higher\"\n\ndef play_pip(pip):\n\tif pip < 0: return\n\tif pip >= len(pips): pip = -1 # Past the end? Take the last one.\n\tpips[pip].play()\n\n# Stuff happens when you gain score\nfrom pprint import pprint\nfrom flask import Flask, request # ImportError? Try \"pip install flask\".\napp = Flask(__name__)\n\nlast_score = {}\n@app.route(\"/\", methods=[\"POST\"])\ndef update_configs():\n\tif not isinstance(request.json, dict): return \"\", 400\n\tif 0: # Dump everything out to the console\n\t\tif \"previously\" in request.json: del request.json[\"previously\"]\n\t\tif \"added\" in request.json: del request.json[\"added\"]\n\t\tif request.json: pprint(request.json)\n\ttry:\n\t\tscore = request.json[\"player\"][\"match_stats\"][\"score\"]\n\t\tperson = request.json[\"player\"][\"name\"]\n\texcept KeyError: return \"\" # Probably not in a match\n\tif person in last_score and score > last_score[person]:\n\t\tprint(person, \"gained\", score - last_score[person], \"=>\", score)\n\t\tplay_pip(score - last_score[person] - 1)\n\tlast_score[person] = score\n\treturn \"\" # Response doesn't matter\n\nif __name__ == \"__main__\":\n\timport logging; logging.basicConfig(level=24) # use logging.INFO to see timestamped lines every request\n\t# import os; logging.log(25, \"I am %d / %d\", os.getuid(), os.getgid())\n\tapp.run(host=\"127.0.0.1\", port=27016)\n","sub_path":"csgo/beep_on_score.py","file_name":"beep_on_score.py","file_ext":"py","file_size_in_byte":1925,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"174102861","text":"import random\nimport time\n\ndef main():\n cards = [1,2,3,4,5,6,7,8,9,10,11,12,13]*4\n for i in range(random.randint(10,20)): random.shuffle(cards)\n cards_p1 = cards[:26]\n cards_p2 = cards[26:]\n for i in range(random.randint(10,20)): random.shuffle(cards_p1)\n for i in range(random.randint(10,20)): random.shuffle(cards_p2)\n\n tied_cards = []\n\n round_num = 1\n p1_wins = 0\n p2_wins = 0\n ties = 0\n\n while len(cards_p1) > 0 or len(cards_p2) > 0:\n if len(tied_cards) == 0:\n print('Round:', round_num)\n print('Player 1 card number:', len(cards_p1), 'Player 2 card number:', len(cards_p2))\n print('P1 wins:', p1_wins, 'P2 wins:', p2_wins, 'Ties:', ties)\n p1_card = cards_p1[0]\n print('Player 1:', p1_card)\n p2_card = cards_p2[0]\n print('Player 2:', p2_card)\n del cards_p1[0], cards_p2[0]\n\n if p1_card > p2_card or p1_card == 1 and p2_card == 13:\n p1_wins += 1\n if len(tied_cards) > 0:\n cards_p1 += tied_cards\n tied_cards = []\n cards_p1.append(p1_card)\n cards_p1.append(p2_card)\n elif p2_card > p1_card or p2_card == 1 and p1_card == 13:\n p2_wins += 1\n if len(tied_cards) > 0:\n cards_p2 += tied_cards\n tied_cards = []\n cards_p2.append(p1_card)\n cards_p2.append(p2_card)\n elif p1_card == p2_card:\n ties += 1\n tied_cards.append(p1_card)\n tied_cards.append(p2_card)\n continue\n \n round_num += 1\n\nt1 = time.time()\nmain()\nt2 = time.time()\nprint(t2-t1)\n \n","sub_path":"War Simulation.py","file_name":"War Simulation.py","file_ext":"py","file_size_in_byte":1677,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"151533487","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed Feb 1 14:45:12 2017\n\n@author: S. Hutchins\n\"\"\"\n\n#------------------------------------------------------------------------------\n# Modules Used\n#------------------------------------------------------------------------------\n\nimport mygene\nimport pandas as pd\n\n#------------------------------------------------------------------------------\n# Create a lists using pandas\n#------------------------------------------------------------------------------\n\n# Create lists for the 3 columns in the file 'Tier, 'Gene', 'Accession'\n# Use tga.keys() to figure out the names of the columns you should use\ntga = pd.read_csv('tiers_genes_accessions.csv') # List of refseq\nrefseq_list = list(tga.Accession)\n\n#------------------------------------------------------------------------------\n# Use MyGene to get gene information\n#------------------------------------------------------------------------------\n\n# Import mygene.MyGeneInfo() search command\nmg = mygene.MyGeneInfo()\n\n# Create a mygene query handle to get the data\nbasic_info = mg.querymany(refseq_list, scopes='refseq',\n fields='symbol,name,entrezgene,summary',\n species='human', returnall=True, as_dataframe=True,\n size=1, verbose=True)\n\n#------------------------------------------------------------------------------\n# Use pandas to turn results of the mygene queries into dataframes\n#------------------------------------------------------------------------------\n\n# Reset the index on the dataframe\nbasic_info['out'].reset_index(level=0, inplace=True)\ndata = basic_info['out']\ngene_info = pd.DataFrame(data)\ngene_info.drop(gene_info.columns[[1,2,6]], axis=1, inplace=True)\n\n# Rename the columns\ngene_info.rename(columns={'entrezgene': 'Entrez ID','summary':\n 'Gene Summary','query': 'RefSeqRNA Accession','name': 'Gene Name'},\n inplace=True)\n\n\n#------------------------------------------------------------------------------\n# Create the NCBI links using a for loop\n#------------------------------------------------------------------------------\n\n# This is the base url for gene specific pages on NCBI\nbaseurl = 'https://www.ncbi.nlm.nih.gov/gene/'\n\n# Create an empty list that can be appended\nurllist = []\n\n# Create a for loop that creates the url using the Entrez ID\n# This loop also appends the url to a list and turns it into a link\nfor entrezid in gene_info['Entrez ID']:\n entrezid = int(entrezid)\n url = baseurl + str(entrezid)\n # Important step\n # Format the url so that it becomes a hyperlink\n url = '{0} '.format(url)\n urllist.append(url)\n\n#------------------------------------------------------------------------------\n# Use pandas to add the urllist & tiers list as columns\n#------------------------------------------------------------------------------\n\n# Turn the ncbiurls list into a dataframe using pandas\nncbiurls = pd.DataFrame(urllist, columns=['NCBI Link'], dtype=str)\n\n# List of dataframes I want to combine\nframes = [tga.Tier, tga.Gene, gene_info, ncbiurls]\n\n# Merge the dataframes into 1 dataframe\nalldata = pd.concat(frames, axis=1)\nalldata.rename(columns={'Gene': 'Gene Symbol'}, inplace=True)\n\n# Save the merged dataframes to one file that contains all of the information\nalldata.to_csv('final_gene_info.csv', index=False)\n\n","sub_path":"GeneInfoApp/MyGene Integration/Archives/mygene_refseq_test.py","file_name":"mygene_refseq_test.py","file_ext":"py","file_size_in_byte":3357,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"618843970","text":"def leq(a, x):\n return sum(y <= x for y in a)\n\nn, k = map(int, input().split())\na = [int(x) for x in input().split()]\na.sort()\nif k == 0:\n ans = a[0] - 1\nelse:\n ans = a[k - 1]\n\nif ans <= 0 or leq(a, ans) != k:\n print(-1)\nelse:\n print(ans)\n\n","sub_path":"codeforces/977/c.py","file_name":"c.py","file_ext":"py","file_size_in_byte":255,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"50197062","text":"from collections import Counter\nimport os\nimport pickle\n\nfrom nltk.tokenize import word_tokenize\nfrom tqdm import tqdm\n\nVOCAB_SIZE = 10000\n\nprint('Loading')\nwith open('04_07_12_data_train_sentences.pkl', 'rb') as f:\n train_data = pickle.load(f)\nwith open('04_07_13_data_valid_sentences.pkl', 'rb') as f:\n valid_data = pickle.load(f)\n\nif os.path.exists('vocab.txt'):\n with open('vocab.txt', 'r') as f:\n vocab = f.read().strip().splitlines()\nelse:\n print('Counting')\n token_counts = Counter()\n for data in [train_data]:\n for doc, _ in tqdm(data):\n title, doc = doc.splitlines()\n doc_tokens = word_tokenize(doc.strip().lower())\n for t in doc_tokens:\n token_counts[t] += 1\n\n print('Aggregating')\n vocab = ['', '', '']\n for token, _ in sorted(token_counts.items(), key=lambda x: -x[1]):\n vocab.append(token)\n if VOCAB_SIZE is not None:\n vocab = vocab[:VOCAB_SIZE]\n with open('vocab.txt', 'w') as f:\n f.write('\\n'.join(vocab))\ntok_to_id = {t:i for i, t in enumerate(vocab)}\nassert len(tok_to_id) == len(vocab)\n\nprint('Tokenizing')\nfor data_split, data in zip(['train', 'valid', 'test'], [train_data, valid_data, valid_data]):\n max_length = 0\n lines = []\n for doc, _ in tqdm(data):\n title, doc = doc.splitlines()\n doc_tokens = word_tokenize(doc.strip().lower())\n doc_tokens = [('' if t not in tok_to_id else t) for t in doc_tokens]\n if len(doc_tokens) > max_length:\n max_length = len(doc_tokens)\n lines.append(' '.join(doc_tokens))\n\n with open('roc.{}.txt'.format(data_split), 'w') as f:\n f.write('\\n'.join(lines))\n print(max_length)\n","sub_path":"format_roc_for_zhu.py","file_name":"format_roc_for_zhu.py","file_ext":"py","file_size_in_byte":1621,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"117258887","text":"import os\n\nbasedir = os.path.abspath(os.path.dirname(__file__))\n\nALLOWED_EMAILS = \"allowed_emails.txt\"\nUSES_OAUTH = False\nPUBLIC_DIR = \"/static/data/public\"\nENABLE_CORS_REQUESTS = True\n\nDATA_PATH = \"/home/toniher/remote-work/bio/igv.js-flask/igvjs/static/data/public\"\n\nDEBUG = False\n","sub_path":"igvjs/_config.py","file_name":"_config.py","file_ext":"py","file_size_in_byte":283,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"464100062","text":"class Node(object): \n def __init__(self, data):\n self.data = data\n self.leftChild = None\n self.rightChild = None \n\nclass BinarySearchTree(object):\n def __init__(self):\n self.root = None\n \n def insert(self, data): \n if not self.root : \n self.root = Node(data)\n else:\n self.insertNode(data, self.root)\n \n # O(logn) - if the tree is balanced -> can be reduce to O(N)\n def insertNode(self, data, node): \n if data < node.data: # leftChild \n if node.leftChild: \n self.insertNode(data, node.leftChild) # recursive\n else :\n node.leftChild = Node(data) # insert it into leftnode\n else : # rightChild\n if node.rightChild: \n self.insertNode(data, node.rightChild) # recursive\n else: \n node.rightChild = Node(data) # insert it into righnode\n\n def remove(self, data): \n if self.root: \n self.root = self.removeNode(data , self.root)\n\n def removeNode(self , data , node): \n if not node :\n return node\n \n if data < node.data: \n node.leftChild = self.removeNode(data , node.leftChild)\n elif data > node.data: \n node.righnode = self.removeNode(data , node.rightChild)\n else : \n if not node.leftChild and not node.rightChild : \n print(\"removing a leaf node ...\")\n del node\n return None\n\n if not node.leftChild: \n print(\"removing the node with single right child\")\n tempNode = node.rightChild\n del node; \n return tempNode\n elif not node.rightChild: \n print(\"Removing node with single left child\")\n tempNode = node.leftChild \n del node\n return tempNode\n\n print('Removing node with two childern ')\n tempNode = self.getPredeccor(node.leftChild)\n node.data = tempNode.data\n node.leftChild = self.removeNode(tempNode.data, node.leftChild)\n\n return node\n\n\n def getPredeccor(self , node): \n if node.rightChild: \n return self.getPredeccor(node.rightChild)\n\n return node\n\n def getMinValue(self) : \n if self.root: \n return self.getMin(self.root)\n\n def getMin(self , node): \n if node.leftChild: \n return self.getMin(node.leftChild)\n\n return node.data\n\n def getMaxValue(self) : \n if self.root: \n return self.getMax(self.root)\n\n def getMax(self , node): \n if node.rightChild: \n return self.getMax(node.rightChild)\n\n return node.data\n\n def traverse(self):\n if self.root: \n self.traverseInOrder(self.root)\n \n def traverseInOrder(self, node): \n if node.leftChild: \n self.traverseInOrder(node.leftChild)\n\n print(\"%s\" %node.data)\n \n if node.rightChild: \n self.traverseInOrder(node.rightChild)\n \n\n\nbst = BinarySearchTree()\nbst.insert(10)\nbst.insert(13)\nbst.insert(5)\nbst.insert(14)\nbst.remove(10)\n \nbst.traverse()\n\n\n\n","sub_path":"tutorial/3-bst/binary_search_tree.py","file_name":"binary_search_tree.py","file_ext":"py","file_size_in_byte":3227,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"591693956","text":"#!/usr/bin/env python\n\nimport matplotlib.pyplot as plt\nimport numpy as np\n\nfrom lmfit.lineshapes import gaussian, lorentzian, s2pi\nfrom lmfit.models import GaussianModel, LorentzianModel\n\n\ndef dfunc_gaussian(params, *ys, **xs):\n x = xs['x']\n var = params.valuesdict()\n A, s, mu = var['amplitude'], var['sigma'], var['center']\n fac = np.exp(-(x-mu)**2/(2.*s**2))\n\n da = fac / (s2pi * s)\n ds = A * fac * ((x-mu)**2-s**2) / (s2pi*s**4)\n dmu = A * fac * (x-mu) / (s2pi*s**3)\n return np.array([ds, dmu, da])\n\n\ndef dfunc_lorentzian(params, *ys, **xs):\n xx = xs['x']\n var = params.valuesdict()\n A, s, mu = var['amplitude'], var['sigma'], var['center']\n fac = ((xx-mu)**2+s**2)\n\n ds = (A*((xx-mu)**2-s**2)) / (np.pi * fac**2)\n da = s / (np.pi*fac)\n dmu = (2. * A * (xx-mu)*s)/(np.pi * fac**2)\n return np.array([ds, dmu, da])\n\n\nif __name__ == '__main__':\n xs = np.linspace(-4, 4, 100)\n\n print('**********************************')\n print('***** Test Gaussian **************')\n print('**********************************')\n ys = gaussian(xs, 2.5, 0, 0.5)\n yn = ys + 0.1*np.random.normal(size=len(xs))\n\n mod = GaussianModel()\n pars = mod.guess(yn, xs)\n out = mod.fit(yn, pars, x=xs)\n out2 = mod.fit(yn, pars, x=xs, fit_kws={'Dfun': dfunc_gaussian,\n 'col_deriv': 1})\n print('lmfit without dfunc **************')\n print('number of function calls: ', out.nfev)\n print('params', out.best_values)\n print('lmfit with dfunc *****************')\n print('number of function calls: ', out2.nfev)\n print('params', out2.best_values)\n print('\\n \\n')\n out2.plot(datafmt='.')\n\n print('**********************************')\n print('***** Test Lorentzian ************')\n print('**********************************')\n ys = lorentzian(xs, 2.5, 0, 0.5)\n yn = ys + 0.1*np.random.normal(size=len(xs))\n\n mod = LorentzianModel()\n pars = mod.guess(yn, xs)\n out = mod.fit(yn, pars, x=xs)\n out2 = mod.fit(yn, pars, x=xs, fit_kws={'Dfun': dfunc_lorentzian, 'col_deriv': 1})\n print('lmfit without dfunc **************')\n print('number of function calls: ', out.nfev)\n print('params', out.best_values)\n print('lmfit with dfunc *****************')\n print('number of function calls: ', out2.nfev)\n print('params', out2.best_values)\n print('\\n \\n')\n out2.plot(datafmt='.')\n\n plt.show()\n","sub_path":"examples/fit_with_analytic_jacobian.py","file_name":"fit_with_analytic_jacobian.py","file_ext":"py","file_size_in_byte":2437,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"451838977","text":"import json\nimport os\nimport shutil\nfrom pathlib import Path\nfrom typing import Any, Dict, List, Union\n\nimport pandas as pd\nimport pendulum\nimport prefect\nfrom prefect import Flow, Task, apply_map, task\nfrom prefect.backend import set_key_value\nfrom prefect.tasks.secrets import PrefectSecret\nfrom prefect.utilities import logging\nfrom visions.functional import infer_type\nfrom visions.typesets.complete_set import CompleteSet\n\nfrom ..task_utils import add_ingestion_metadata_task\nfrom ..tasks import (\n AzureDataLakeUpload,\n CloudForCustomersToDF,\n)\n\nlogger = logging.get_logger(__name__)\n\ncloud_for_customers_to_df_task = CloudForCustomersToDF()\nfile_to_adls_task = AzureDataLakeUpload()\n\n\n@task\ndef df_to_csv_task(df, path: str, if_exists: str = \"replace\"):\n if if_exists == \"append\":\n if os.path.isfile(path):\n csv_df = pd.read_csv(path)\n out_df = pd.concat([csv_df, df])\n else:\n out_df = df\n elif if_exists == \"replace\":\n out_df = df\n out_df.to_csv(path, index=False)\n\n\n@task\ndef df_to_parquet_task(df, path: str, if_exists: str = \"replace\"):\n if if_exists == \"append\":\n if os.path.isfile(path):\n parquet_df = pd.read_parquet(path)\n out_df = pd.concat([parquet_df, df])\n else:\n out_df = df\n elif if_exists == \"replace\":\n out_df = df\n out_df.to_parquet(path, index=False)\n\n\nclass CloudForCustomersToADLS(Flow):\n def __init__(\n self,\n url: str = None,\n endpoint: str = None,\n name: str = None,\n params: Dict[str, Any] = {},\n adls_sp_credentials_secret: str = None,\n fields: List[str] = None,\n local_file_path: str = None,\n output_file_extension: str = \".csv\",\n adls_dir_path: str = None,\n if_empty: str = \"warn\",\n if_exists: str = \"replace\",\n *args: List[any],\n **kwargs: Dict[str, Any],\n ):\n\n # CloudForCustomersToDF\n self.if_empty = if_empty\n self.url = url\n self.endpoint = endpoint\n self.fields = fields\n self.params = params\n\n # AzureDataLakeUpload\n self.adls_sp_credentials_secret = adls_sp_credentials_secret\n self.if_exists = if_exists\n self.output_file_extension = output_file_extension\n self.local_file_path = (\n local_file_path or self.slugify(name) + self.output_file_extension\n )\n self.now = str(pendulum.now(\"utc\"))\n self.adls_dir_path = adls_dir_path\n self.adls_file_path = os.path.join(\n adls_dir_path, self.now + self.output_file_extension\n )\n\n super().__init__(*args, name=name, **kwargs)\n\n self.gen_flow()\n\n def gen_flow(self) -> Flow:\n\n df = cloud_for_customers_to_df_task.bind(\n url=self.url,\n endpoint=self.endpoint,\n fields=self.fields,\n params=self.params,\n flow=self,\n )\n\n df_with_metadata = add_ingestion_metadata_task.bind(df, flow=self)\n\n if self.output_file_extension == \".parquet\":\n df_to_file = df_to_parquet_task.bind(\n df=df_with_metadata,\n path=self.local_file_path,\n if_exists=self.if_exists,\n flow=self,\n )\n else:\n df_to_file = df_to_csv_task.bind(\n df=df_with_metadata,\n path=self.local_file_path,\n if_exists=self.if_exists,\n flow=self,\n )\n\n file_to_adls_task.bind(\n from_path=self.local_file_path,\n to_path=self.adls_file_path,\n sp_credentials_secret=self.adls_sp_credentials_secret,\n flow=self,\n )\n\n file_to_adls_task.set_upstream(df_to_file, flow=self)\n set_key_value(key=self.adls_dir_path, value=self.adls_file_path)\n\n @staticmethod\n def slugify(name):\n return name.replace(\" \", \"_\").lower()\n","sub_path":"viadot/flows/cloud_for_customers_to_adls.py","file_name":"cloud_for_customers_to_adls.py","file_ext":"py","file_size_in_byte":3963,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"130335768","text":"def swap(list , pos1 , pos2):\r\n\tlist[pos1] , list [pos2] = list[pos2] , list [pos1]\r\n\treturn list\r\n\r\ndef selection_sort(list):\r\n\tfor i in range(0 , len(a)-1):\r\n\t\tk = i\r\n\t\tfor j in range(i , len(a)):\r\n\t\t\tif list[j] < list[k]:\r\n\t\t\t\tk = j\r\n\t\tswap(list , k , i)\r\n\treturn list\r\n\r\n\r\na = [2,7,4,1,5,3]\r\nprint(a)\r\nselection_sort(a)\r\nprint(a)\r\n","sub_path":"selection sort.py","file_name":"selection sort.py","file_ext":"py","file_size_in_byte":335,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"328517833","text":"'''\nkatakanaTest,py\nEric Oropezaelwood\n25 September 2015\nA quiz app that tests the users knowledge of katakana and Japanese vocabulary\n'''\n\nclass Student:\n\tdef __init__(self, name):\n\t\tself.name = name\n\t\tprint(\"Konichiwa {0}\".format(self.name), \"san\")\n\nprint(\"What is your name?\")\nresponse = input()\nstudent1 = Student(response)\n\n#start of alpha class\nclass alpha():\n\n\tdef basics(self):\n\t\tkatakanaBasic = {\n\t\t\t'ア': \"a\",\n\t\t\t'イ': \"i\",\n\t\t\t'ウ': \"u\",\n\t\t\t'エ': \"e\",\n\t\t\t'オ': \"o\",\n\t\t\t'ン': \"n\"\n\t\t\t}\n\n\t\tcorrect = 0\n\t\tincorrect = 0\n\t\tfor k, v in katakanaBasic.items():\n\n\t\t\tprint(\"translate: \", k)\n\t\t\tanswer = input()\n\t\t\tif answer == v:\n\t\t\t\tprint(\"correct\")\n\t\t\t\tcorrect = correct + 1\n\t\t\telse:\n\t\t\t\tprint(\"incorrect, answer: \", v)\n\t\t\t\tincorrect = incorrect + 1\n\t\tprint(\"correct: \",correct, \"incorrect: \", incorrect)\n\n\t\treturn katakanaBasic\n\n\tdef k(self):\n\t\tkatakanaK = {\n\t\t\t'カ': \"ka\",\n\t\t\t'キ': \"ki\",\n\t\t\t'ク': \"ku\",\n\t\t\t'ケ': \"ke\",\n\t\t\t'コ': \"ko\"\n\t\t\t}\n\n\t\tcorrect = 0\n\t\tincorrect = 0\n\t\tfor k, v in katakanaK.items():\n\n\t\t\tprint(\"translate: \", k)\n\t\t\tanswer = input()\n\t\t\tif answer == v:\n\t\t\t\tprint(\"correct\")\n\t\t\t\tcorrect = correct + 1\n\t\t\telse:\n\t\t\t\tprint(\"incorrect, answer: \", v)\n\t\t\t\tincorrect = incorrect + 1\n\t\tprint(\"correct: \",correct, \"incorrect: \", incorrect)\n\n\t\treturn katakanaK\n\n\tdef s(self):\n\t\tkatakanaS = {\n\t\t\t'サ': \"sa\",\n\t\t\t'シ': \"shi\",\n\t\t\t'ス': \"su\",\n\t\t\t'セ': \"se\",\n\t\t\t'ソ': \"so\"\n\t\t\t}\n\n\t\tcorrect = 0\n\t\tincorrect = 0\n\t\tfor k, v in katakanaS.items():\n\n\t\t\tprint(\"translate: \", k)\n\t\t\tanswer = input()\n\t\t\tif answer == v:\n\t\t\t\tprint(\"correct\")\n\t\t\t\tcorrect = correct + 1\n\t\t\telse:\n\t\t\t\tprint(\"incorrect, answer: \", v)\n\t\t\t\tincorrect = incorrect + 1\n\t\tprint(\"correct: \",correct, \"incorrect: \", incorrect)\n\n\t\treturn katakanaS\n\tdef t(self):\n\t\tkatakanaT = {\n\t\t\t'タ': \"ta\",\n\t\t\t'チ': \"chi\",\n\t\t\t'ツ': \"tsu\",\n\t\t\t'テ': \"te\",\n\t\t\t'ト': \"to\"\n\t\t\t}\n\n\t\tcorrect = 0\n\t\tincorrect = 0\n\t\tfor k, v in katakanaT.items():\n\n\t\t\tprint(\"translate: \", k)\n\t\t\tanswer = input()\n\t\t\tif answer == v:\n\t\t\t\tprint(\"correct\")\n\t\t\t\tcorrect = correct + 1\n\t\t\telse:\n\t\t\t\tprint(\"incorrect, answer: \", v)\n\t\t\t\tincorrect = incorrect + 1\n\t\tprint(\"correct: \",correct, \"incorrect: \", incorrect)\n\n\t\treturn katakanaT\n\n\tdef n(self):\n\t\tkatakanaN = {\n\t\t\t'ナ': \"na\",\n\t\t\t'ニ': \"ni\",\n\t\t\t'ヌ': \"nu\",\n\t\t\t'ネ': \"ne\",\n\t\t\t'ノ': \"no\"\n\t\t\t}\n\n\t\tcorrect = 0\n\t\tincorrect = 0\n\t\tfor k, v in katakanaN.items():\n\n\t\t\tprint(\"translate: \", k)\n\t\t\tanswer = input()\n\t\t\tif answer == v:\n\t\t\t\tprint(\"correct\")\n\t\t\t\tcorrect = correct + 1\n\t\t\telse:\n\t\t\t\tprint(\"incorrect, answer: \", v)\n\t\t\t\tincorrect = incorrect + 1\n\t\tprint(\"correct: \",correct, \"incorrect: \", incorrect)\n\n\t\treturn katakanaN\n\n\tdef h(self):\n\t\tkatakanaH = {\n\t\t\t'ハ': \"ha\",\n\t\t\t'ヒ': \"hi\",\n\t\t\t'フ': \"fu\",\n\t\t\t'ヘ': \"he\",\n\t\t\t'ホ': \"ho\"\n\t\t\t}\n\n\t\tcorrect = 0\n\t\tincorrect = 0\n\t\tfor k, v in katakanaH.items():\n\n\t\t\tprint(\"translate: \", k)\n\t\t\tanswer = input()\n\t\t\tif answer == v:\n\t\t\t\tprint(\"correct\")\n\t\t\t\tcorrect = correct + 1\n\t\t\telse:\n\t\t\t\tprint(\"incorrect, answer: \", v)\n\t\t\t\tincorrect = incorrect + 1\n\t\tprint(\"correct: \",correct, \"incorrect: \", incorrect)\n\n\t\treturn katakanaH\n\n\tdef m(self):\n\t\tkatakanaM = {\n\t\t\t'マ': \"ma\",\n\t\t\t'ミ': \"mi\",\n\t\t\t'ム': \"mu\",\n\t\t\t'メ': \"me\",\n\t\t\t'モ': \"mo\"\n\t\t\t}\n\n\t\tcorrect = 0\n\t\tincorrect = 0\n\t\tfor k, v in katakanaM.items():\n\n\t\t\tprint(\"translate: \", k)\n\t\t\tanswer = input()\n\t\t\tif answer == v:\n\t\t\t\tprint(\"correct\")\n\t\t\t\tcorrect = correct + 1\n\t\t\telse:\n\t\t\t\tprint(\"incorrect, answer: \", v)\n\t\t\t\tincorrect = incorrect + 1\n\t\tprint(\"correct: \",correct, \"incorrect: \", incorrect)\n\n\t\treturn katakanaM\n\n\tdef y(self):\n\t\tkatakanaY = {\n\t\t\t'ヤ': \"ya\",\n\t\t\t'ユ': \"yu\",\n\t\t\t'ヨ': \"yo\"\n\t\t\t}\n\n\t\tcorrect = 0\n\t\tincorrect = 0\n\t\tfor k, v in katakanaY.items():\n\n\t\t\tprint(\"translate: \", k)\n\t\t\tanswer = input()\n\t\t\tif answer == v:\n\t\t\t\tprint(\"correct\")\n\t\t\t\tcorrect = correct + 1\n\t\t\telse:\n\t\t\t\tprint(\"incorrect, answer: \", v)\n\t\t\t\tincorrect = incorrect + 1\n\t\tprint(\"correct: \",correct, \"incorrect: \", incorrect)\n\n\t\treturn katakanaY\n\tdef r(self):\n\t\tkatakanaR = {\n\t\t\t'ラ': \"ra\",\n\t\t\t'リ': \"ri\",\n\t\t\t'ル': \"ru\",\n\t\t\t'レ': \"re\",\n\t\t\t'ロ': \"ro\"\n\t\t\t}\n\n\t\tcorrect = 0\n\t\tincorrect = 0\n\t\tfor k, v in katakanaR.items():\n\n\t\t\tprint(\"translate: \", k)\n\t\t\tanswer = input()\n\t\t\tif answer == v:\n\t\t\t\tprint(\"correct\")\n\t\t\t\tcorrect = correct + 1\n\t\t\telse:\n\t\t\t\tprint(\"incorrect, answer: \", v)\n\t\t\t\tincorrect = incorrect + 1\n\t\tprint(\"correct: \",correct, \"incorrect: \", incorrect)\n\n\t\treturn katakanaR\n\tdef w(self):\n\t\tkatakanaW = {\n\t\t\t'ワ': \"wa\",\n\t\t\t'ヲ': \"wo\"\n\t\t\t}\n\n\t\tcorrect = 0\n\t\tincorrect = 0\n\t\tfor k, v in katakanaW.items():\n\n\t\t\tprint(\"translate: \", k)\n\t\t\tanswer = input()\n\t\t\tif answer == v:\n\t\t\t\tprint(\"correct\")\n\t\t\t\tcorrect = correct + 1\n\t\t\telse:\n\t\t\t\tprint(\"incorrect, answer: \", v)\n\t\t\t\tincorrect = incorrect + 1\n\t\tprint(\"correct: \",correct, \"incorrect: \", incorrect)\n\n\t\treturn katakanaW\n\n#end of aplha class\n\n#start of nouns!!!!!!!!\n\nclass noun():\n\tdef locations(self):\n\t\tplaces = {\n\t\t\"としょかん\":\"library\",\n\t\t\"といれ\":\"toilet\",\n\t\t\"おてら\":\"temple\",\n\t\t\"こうえん\":\"park\",\n\t\t\"スーパー\":\"supermarket\",\n\t\t\"デパート\":\"department store\",\n\t\t\"バスてい\":\"bus stop\",\n\t\t\"びょういん\":\"hospital\",\n\t\t\"ホテル\":\"hotel\",\n\t\t\"ほんや\":\"bookstore\",\n\t\t\"まち\":\"town\",\n\t\t\"レストラン\":\"restaurant\"\n\t\t}\n\t\tcorrect = 0\n\t\tincorrect = 0\n\t\tfor k, v in places.items():\n\n\t\t\tprint(\"translate: \", k)\n\t\t\tanswer = input()\n\t\t\tif answer == v:\n\t\t\t\tprint(\"correct\")\n\t\t\t\tcorrect = correct + 1\n\t\t\telse:\n\t\t\t\tprint(\"incorrect, answer: \", v)\n\t\t\t\tincorrect = incorrect + 1\n\t\tprint(\"correct: \",correct, \"incorrect: \", incorrect)\n\t\t\n\n\t\t# activates Japanese bot, a highly intelligent robot whose calculations determine one's lifespan in Japan based on their results\n\t\tif correct < 1:\n\t\t\tprint(\"Beep boop \\\"My calculations suggest you would survive 1/2 a day in Japan\\\" beep boop\")\n\t\telif correct < 5:\n\t\t\tprint(\"Beep boop \\\"My calculations suggest you would survive 1 week in Japan\\\" beep boop\")\n\t\telse:\n\t\t\tprint(\"Beep boop \\\"My calculation suggest you would be able to order ramen in Japan, CONGRATULATIONS! おめでとうございます!\\\" beep boop\")\n\t\treturn places\n\ndef main():\n\t\n\tagain = \"yes\"\n\t#Create objects in order to use classes\n\taChoice=alpha()\n\tbChoice=noun()\n\twhile again != \"no\":\n\t\t#prompts the user on what to study\n\t\tprint(\"What do you want to study: locations or katakana?\")\n\t\tchoice1 = input()\n\t\t\n\t\t#prompt for katakana review\n\t\tif choice1 == \"katakana\":\n\t\t\tprint(\"choose a category: a-o/n, k, s, t, n, h, m, y, r, or w?\")\n\t\t\tchoice = input()\n\t\t\tif choice == \"a-o/n\":\n\t\t\t\taChoice.basics()\n\t\t\telif choice == \"k\":\n\t\t\t\taChoice.k()\n\t\t\telif choice == \"s\":\n\t\t\t\taChoice.s()\n\t\t\telif choice == \"t\":\n\t\t\t\taChoice.t()\n\t\t\telif choice ==\"n\":\n\t\t\t\taChoice.n()\n\t\t\telif choice ==\"h\":\n\t\t\t\taChoice.h()\n\t\t\telif choice ==\"m\":\n\t\t\t\taChoice.m()\n\t\t\telif choice ==\"y\":\n\t\t\t\taChoice.y()\n\t\t\telif choice ==\"r\":\n\t\t\t\taChoice.r()\n\t\t\telif choice ==\"w\":\n\t\t\t\taChoice.w()\n\n\t\t#execute locations() and begin quizzing\n\t\telif choice1 ==\"locations\":\n\t\t\tbChoice.locations()\n\t\n\t\tprint(\"Do you want to go again? yes or no\")\n\t\tagain = input()\nmain()\n\n\n\n\n\n\n","sub_path":"katakanaTest.py","file_name":"katakanaTest.py","file_ext":"py","file_size_in_byte":6981,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"392796855","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n# @Date : 2019-06-24 21:11:06\n# @Author : Your Name (you@example.org)\n# @Link : http://example.org\n# @Version : $Id$\n\nimport os\nimport itertools\nimport time\n\n\ndef BFS(adj: dict, n, start=None):\n \"\"\"\n 广度优先\n 先看周围(邻接的点)\n 再看周围的周围\n 有点类似二叉树层序初始化\n 控制访问的方法是设置flag\n \"\"\"\n\n if not start:\n start = 0 # 从第一个节点开始\n queue = [start]\n # visit(start)\n # n = len(adj[0])\n visited = [0 for i in range(n)]\n visited[start] = 1\n while queue:\n start = queue[0]\n for i in range(n):\n _ = start\n if _ > i:\n _, i = i, _\n if (_, i) in adj and visited[i] == 0:\n # visit(i)\n visited[i] = 1\n queue.append(i)\n del queue[0]\n return visited\n\n\nclass Solution:\n def numIslands(self, grid: list) -> int:\n \"\"\"\n 方法一:把所有1的邻接矩阵构造出来,然后BFS\n 方法二:边遍历边构造,0的时候停止\n \"\"\"\n if grid == []:\n return 0\n # 矩阵转化为图\n h = len(grid)\n w = len(grid[0])\n\n coords = list(itertools.product(list(range(h)), list(range(w))))\n one_coords = []\n for c in coords:\n if grid[c[0]][c[1]] == '1':\n one_coords.append(c)\n n = len(one_coords) # 27141个1\n adj = dict()\n start = time.clock()\n # 按照1的坐标\n for i in range(n):\n ith_coord = one_coords[i]\n # 上下左右\n for jth_coord in [(ith_coord[0]+1, ith_coord[1]),\n (ith_coord[0]-1, ith_coord[1]),\n (ith_coord[0], ith_coord[1]+1),\n (ith_coord[0], ith_coord[1]-1)]:\n # 范围\n if 0 <= jth_coord[0] < h and 0 <= jth_coord[1] < w:\n if grid[jth_coord[0]][jth_coord[1]] == '1':\n j = one_coords.index(jth_coord)\n # adj[(i, j)], adj[(j, i)] = 1, 1 # 只存一半\n _i = i\n _j = j\n if _i > _j:\n _i, _j = _j, _i\n if (_i, _j) not in adj.keys():\n adj[(_i, _j)] = '1'\n\n elapsed = (time.clock() - start)\n # adj, one_coords, n\n visited = [0 for i in range(n)]\n # start = 0\n num_of_islands = 0\n while 0 in visited:\n start = visited.index(0)\n this_visited = BFS(adj, n, start)\n for i in range(n):\n visited[i] = visited[i] | this_visited[i]\n num_of_islands += 1\n\n return num_of_islands\n","sub_path":"leetcode/num-of-island-graph-ver2.py","file_name":"num-of-island-graph-ver2.py","file_ext":"py","file_size_in_byte":2874,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"223193980","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\nimport math\nimport matplotlib.pyplot as plt\t# matplotlib.org\nimport numpy as np\n\n# Cálculo de la derivada considerando que: f'(x) = (f(x+h) - f(x-h))/(2h) + o(h^2)\nepsilon = np.logspace(-1,-15,15,base = 10)\ndsindx = (np.sin(1. + epsilon) - np.sin(1.))/epsilon;\ndsindx_mejorado = (np.sin(1.+epsilon) - np.sin(1.-epsilon))/(2*epsilon)\n\nplt.plot(epsilon, dsindx - np.cos(1.));\nplt.plot(epsilon,dsindx_mejorado - np.cos(1.));\nplt.xscale('log')\nplt.axhline(0,color='0.8');\nplt.title('Comparacion $\\\\frac{d}{dx}\\\\left(sin(x)\\\\right)|_{x = 1}$ y cos(1)')\nplt.xlabel('$\\epsilon$',fontsize = 20);\nplt.ylabel('$\\\\frac{d}{dx}\\\\left(sin(x)\\\\right) - cos(1.)$',fontsize = 20);\n_ = plt.xticks(epsilon[::2]);\nplt.savefig('Derivada dsindx Mejorada.png');\n\n# Cálculo integrales Numéricas\n\n# Haciendo Taylor:\tint_{x_0}^{x_0+\\Delta x}{f(x) dx} = int_{x_0}^{x_0+\\Delta x}{f(x_0) + f'(x_0)(x-x_0) + ... dx}\n#\t\t\t\t\tint_{x_0}^{x_0+\\Delta x}{f(x) dx} = f(x_0){\\Delta x} + f'(x_0){\\Delta x}^2/2 + ...\n#\t\t\t\t\tint_{x_0}^{x_0+\\Delta x}{f(x) dx} = {\\Delta x}/2 (f_(x_0) + {f(x_0) + f'(x_0){\\Delta x} + ...}) - f''(x_0){\\Delta x}^2/6 - ...\n#\t\t\t\t\tint_{x_0}^{x_0+\\Delta x}{f(x) dx} = ( f(x_0) + f(x+\\Delta x) )*( {\\Delta x}/2 ) + o({\\Delta x}^3)\n# Como esto funciona para {\\Delta x} chico. Las integrales hay que dividirlas en N pedazos con N = (lim_sup - lim_inf)/{\\Delta x}\n# Así se tiene que:\tint_{a}^{b}{f(x) dx} ~ \\sum_{i = 0}^{N-1} {(f(a + i*{\\Delta x}) + (f(a + (i+1)*{\\Delta x}))/2*{\\Delta x} + o({\\Delta x}^3)}\n# El error tiene una cota superior: o({\\Delta x}^3) <= cota_superior({\\Delta x}^3) = o_2({\\Delta x}^3)\n# Reemplazando esa cota superior, la integral queda:\n# int_{a}^{b}{f(x) dx} ~ \\sum_{i = 0}^{N-1} {(f(a + i*{\\Delta x}) + (f(a + (i+1)*{\\Delta x}))/{2*\\Delta x}} + o({\\Delta x}^2)\n\n# FINALMENTE: int_{a}^{b}{f(x) dx} = f(a)/2 + f(b)/2 + 2*(\\sum_{i = 1}^{N-2} {f(x+i*{\\Delta x})*{\\Delta x}}) + o({\\Delta x}^2)\n\n# Regla de SIMPSON para evaluar integrales: Mayor presición al llamar mas veces la función\n# int_{x_0}^{x_0+2*\\Delta x}{f(x) dx} = ({\\Delta x}/3)*(f(\\Delta x) + 4*f(x + {\\Delta x}) + f(x + 2*{\\Delta x})) + o({\\Delta x}^5)\n\n\nhelp(np.linspace);","sub_path":"Cátedra 2/Cátedra 2.py","file_name":"Cátedra 2.py","file_ext":"py","file_size_in_byte":2192,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"486776563","text":"\"\"\"\r\nMade by Adam Suchý, 2019\r\nfor the frankfurt competition in robotics 2020\r\n\"\"\"\r\n\r\nimport logging\r\nimport time\r\n\r\nimport cv2\r\nimport numpy as np\r\n\r\n# setting constants\r\nTURN_THRESHOLD = 75\r\nRESOLUTION = 15\r\nVIDEO_CAPTURE_DEVICE = 2\r\n\r\n# setting up logging\r\nlogger = logging.getLogger(__name__)\r\nlogger.setLevel(logging.DEBUG)\r\nfileHandler = logging.FileHandler(\"imageRecognition.log\")\r\nfileHandler.setLevel(logging.INFO)\r\nfileHandler.setFormatter(logging.Formatter(\"%(levelname)s %(asctime)s : %(message)s\"))\r\nlogger.addHandler(fileHandler)\r\n\r\n\r\ndef predict(image: np.ndarray, clean: bool = False):\r\n \"\"\"\r\n A function that takes in an image in BGR format and finds a black line on a white background on the image.\r\n It detects turns and calculates the angle of the line.\r\n\r\n TODO: Make angle not be relative but absolute (do not rely on sides from the y axis)? Maybe more efficient this way.\r\n\r\n :param image: numpy array of an image in BGR format\r\n :param clean: Should the function be in the background? if true: image displayed\r\n :return:\r\n nav (points of the line),\r\n turn (the point on the image of the turn (none if not detected),\r\n angle (angle of the line before any turn),\r\n ori (orientation of the line. if it goes to the left or right)\r\n \"\"\"\r\n\r\n # creating the image of the edges\r\n gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)\r\n _, edges = cv2.threshold(gray, 70, 255, cv2.THRESH_BINARY_INV)\r\n # edges = cv2.Canny(thresh, 100, 200)\r\n if not clean:\r\n cv2.imshow('b', edges) # shows the black and white image mask\r\n cv2.waitKey(1)\r\n # creating points\r\n height = edges.shape[0]\r\n width = edges.shape[1]\r\n blocks = int((height - 1) / RESOLUTION)\r\n nav = list()\r\n for line in range(0, RESOLUTION):\r\n points_on_row = []\r\n for j in range(0, width):\r\n if edges[(height - 1) - blocks * line, j] != 0:\r\n points_on_row.append(j)\r\n\r\n if len(points_on_row) == 0: # continue to next line if no line found\r\n continue\r\n else:\r\n avrg = int(np.average(points_on_row))\r\n nav.append((avrg, height - blocks * line - 1))\r\n\r\n if len(nav) < 2:\r\n return [], (0, 0), 0, \"right\"\r\n\r\n # looking for turns, more accurately: any line which angle is more than TURN_THRESHOLD\r\n p1 = nav[0]\r\n turn = None\r\n for p2 in nav[1:]:\r\n tan = abs(p1[0] - p2[0]) / abs(p1[1] - p2[1])\r\n angle = np.arctan(tan) * 57.2957795\r\n if angle > TURN_THRESHOLD:\r\n turn = nav.index(p1)\r\n break\r\n p1 = p2\r\n\r\n # getting the angle of the line\r\n p1 = nav[0]\r\n if turn and abs(p1[1] - nav[turn][1]) != 0:\r\n p2 = nav[turn]\r\n else:\r\n p2 = nav[-1]\r\n tan = abs(p1[0] - p2[0]) / abs(p1[1] - p2[1])\r\n angle = np.arctan(tan) * 57.2957795 # converting radians to degrees\r\n ori = \"left\"\r\n if p1[0] <= p2[0]:\r\n ori = \"right\"\r\n return nav, turn, angle, ori\r\n\r\n\r\nif __name__ == '__main__':\r\n consoleH = logging.StreamHandler()\r\n consoleH.setLevel(logging.DEBUG)\r\n consoleH.setFormatter(logging.Formatter(\"%(levelname)s: %(message)s\"))\r\n logger.addHandler(consoleH)\r\n logger.info(\"logging initialized\")\r\n i = cv2.imread('r-l.jpg')\r\n cap = cv2.VideoCapture(VIDEO_CAPTURE_DEVICE)\r\n if cap.read()[1] is None:\r\n logger.warning(f\"Cannot read fom video capture device on index {VIDEO_CAPTURE_DEVICE}. Defaulting to 0.\")\r\n cap = cv2.VideoCapture(0)\r\n\r\n logger.debug(predict(i))\r\n sec = 0\r\n try:\r\n while True:\r\n tp = \"Ok\"\r\n ret, frame = cap.read()\r\n if frame is None:\r\n logger.critical(f\"The video capture device did not output a frame, exiting.\")\r\n exit()\r\n c_frame = frame[70:400, 5:1280]\r\n start = time.time()\r\n pnts, t, a, o = predict(c_frame)\r\n sec = time.time() - start\r\n if pnts:\r\n if t is not None:\r\n cv2.circle(c_frame, pnts[t], 6, (0, 255, 0), thickness=5)\r\n if pnts[0][0] < c_frame.shape[1] / 4:\r\n tp = \"left\"\r\n elif pnts[0][0] > c_frame.shape[1] / 4 * 3:\r\n tp = \"right\"\r\n elif a > 10 and o == \"left\":\r\n tp = \"left\"\r\n elif a > 10 and o == \"right\":\r\n tp = \"right\"\r\n logger.debug(f\"Angle: {a}\")\r\n logger.debug(f\"Orientation: {o}\")\r\n logger.debug(f\"Turn pred. : {tp}\")\r\n prev = pnts[0]\r\n for point in pnts:\r\n cv2.circle(c_frame, point, 3, (0, 0, 255), thickness=3)\r\n cv2.line(c_frame, prev, point, (0, 0, 255), 2)\r\n prev = point\r\n # show the final output image\r\n cv2.imshow('vision', c_frame)\r\n cv2.waitKey(1)\r\n except KeyboardInterrupt:\r\n print(\"Finish.\")\r\n logger.info(f\"Exit. Last prediction was calculated in {round(sec, 3)} seconds.\")\r\n","sub_path":"imageRecognition.py","file_name":"imageRecognition.py","file_ext":"py","file_size_in_byte":5103,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"257233226","text":"########################################\n# BTagging_jobOptions.py\n# author: andreas.wildauer@cern.ch\n# devivie@lal.in2p3.fr\n# vacavant@in2p3.fr \n#\n# Main jobO for b-tagging:\n# - load all the necessary tools\n# - configure the b-tagging algorithms\n########################################\n\n# <================= IMPORTANT ==============================================>\n # !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\n # NOTE: The inclusion of the LoadTools is no longer needed with the\n # new configuration; the default configuration is automatically set up\n # for any unconfigured jet collection where which setupJetBTaggerTool\n # is called. In fact the only thing the LoadTools does now is just call\n # this default setup on all jet collections in BTaggingFlags.Jets.\n #\n # If you need to modify the default setup permanently can modify\n # BTaggingConfiguration_LoadTools.py in the ./python/ directory.\n #\n # If you want different settings not obtainable via the BTaggingFlags,\n # you need to use the new configuration scheme before any call to\n # setupJetBTaggerTools is made for the jet collection in question.\n # You can start by calling BTaggingConfiguration_LoadTools.py's\n # Initiate() function.\n # !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\n# <================= IMPORTANT ==============================================>\n\n# <================= IMPORTANT ==============================================>\n # !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\n # NOTE: Consider adding some of the stuff found here to the Initiate()\n # function in BTaggingConfiguration_LoadTools.py. The code there is\n # run exactly once; if B-tagging is enabled.\n #\n # DOING SO WILL MAKE THE CODE COMPATIBLE WITH A FUTURE CHANGE IN JETREC\n # WHERE THEY WILL RETRIEVE OUR BTAGGING FUNCTION IF REQUESTED BY A USER.\n # !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\n# <================= IMPORTANT ==============================================>\n\nimport re\n\nif not BTaggingFlags.DoNotSetupBTagging: # Temporary measure so the JetRec people can test setting this all up from their side.\n #\n # ========== Load and configure everything\n #\n \n from BTagging.BTaggingConfiguration import getConfiguration\n ConfInstance = getConfiguration()\n\n if ConfInstance.checkFlagsUsingBTaggingFlags():\n\n #Jet collections\n #JetCollectionList = ['AntiKt4LCTopoJets', 'AntiKt4EMTopoJets', 'AntiKt4TrackJets', 'AntiKt4EMPFlowJets', 'AntiKt2TrackJets']\n JetCollectionList = ['AntiKt4EMTopoJets']\n\n BTaggingFlags.Jets = [ name[:-4] for name in JetCollectionList]\n\n from AthenaCommon.AlgSequence import AlgSequence\n topSequence = AlgSequence()\n\n for i, jet in enumerate(JetCollectionList):\n btagger = ConfInstance.setupJetBTaggerAlg(ToolSvc, jet) #The [:-4] is not needed here; this function automatically removes trailing 'jets' or 'Jets'.\n if btagger is None:\n continue\n topSequence += btagger\n #jet = jet.replace(\"Track\", \"PV0Track\")\n #jetname = getattr(jtm, jet)\n #jetname.unlock()\n #jetname.JetModifiers += [ btagger ]\n #jetname.lock()\n if BTaggingFlags.OutputLevel < 3:\n printfunc (ConfInstance.getJetCollectionTool(jet[:-4]))\n\n","sub_path":"PhysicsAnalysis/JetTagging/JetTagAlgs/BTagging/share/BTagging_jobOptions.py","file_name":"BTagging_jobOptions.py","file_ext":"py","file_size_in_byte":3363,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"309096850","text":"# -*- coding: utf-8 -*-\n\"\"\"\nThis file should hold almost all string literals and magic numbers used throughout the code base.\nThe exception is if a literal is specifically meant to be private to and isolated within a module.\n\"\"\"\nfrom __future__ import absolute_import, division, print_function, unicode_literals\n\nimport sys\nfrom enum import Enum\nfrom logging import getLogger\nfrom platform import machine\n\nfrom .._vendor.auxlib.collection import frozendict\n\nlog = getLogger(__name__)\n\n\nclass Arch(Enum):\n x86 = 'x86'\n x86_64 = 'x86_64'\n armv6l = 'armv6l'\n armv7l = 'armv7l'\n ppc64le = 'ppc64le'\n\n @classmethod\n def from_sys(cls):\n return cls[machine()]\n\n def __json__(self):\n return self.value\n\n\nclass Platform(Enum):\n linux = 'linux'\n win = 'win32'\n openbsd = 'openbsd5'\n osx = 'darwin'\n\n @classmethod\n def from_sys(cls):\n p = sys.platform\n if p.startswith('linux'):\n # Changed in version 2.7.3: Since lots of code check for sys.platform == 'linux2',\n # and there is no essential change between Linux 2.x and 3.x, sys.platform is always\n # set to 'linux2', even on Linux 3.x. In Python 3.3 and later, the value will always\n # be set to 'linux'\n p = 'linux'\n return cls(p)\n\n def __json__(self):\n return self.value\n\n\nclass FileMode(Enum):\n text = 'text'\n binary = 'binary'\n\n def __str__(self):\n return \"%s\" % self.value\n\n\nclass LinkType(Enum):\n # LINK_HARD = 1\n # LINK_SOFT = 2\n # LINK_COPY = 3\n # link_name_map = {\n # LINK_HARD: 'hard-link',\n # LINK_SOFT: 'soft-link',\n # LINK_COPY: 'copy',\n # }\n hardlink = 1\n softlink = 2\n copy = 3\n directory = 4\n\n def __int__(self):\n return self.value\n\n def __str__(self):\n return self.name\n\n\nPREFIX_PLACEHOLDER = ('/opt/anaconda1anaconda2'\n # this is intentionally split into parts,\n # such that running this program on itself\n # will leave it unchanged\n 'anaconda3')\n\nmachine_bits = 8 * tuple.__itemsize__\n\nCONDA = 'CONDA'\nCONDA_ = 'CONDA_'\nconda = 'conda'\n\nSEARCH_PATH = (\n '/etc/conda/condarc',\n '/etc/conda/condarc.d/',\n '/var/lib/conda/condarc',\n '/var/lib/conda/condarc.d/',\n '$CONDA_ROOT/condarc',\n '$CONDA_ROOT/.condarc',\n '$CONDA_ROOT/condarc.d/',\n '~/.conda/condarc',\n '~/.conda/condarc.d/',\n '~/.condarc',\n '$CONDA_PREFIX/.condarc',\n '$CONDA_PREFIX/condarc.d/',\n '$CONDARC',\n)\n\nDEFAULT_CHANNEL_ALIAS = 'https://conda.anaconda.org'\nCONDA_HOMEPAGE_URL = 'http://conda.pydata.org'\nDEFAULTS = 'defaults'\n\nPLATFORM_DIRECTORIES = (\"linux-64\",\n \"linux-32\",\n \"win-64\",\n \"win-32\",\n \"osx-64\",\n \"linux-ppc64le\",\n \"linux-armv6l\",\n \"linux-armv7l\",\n \"noarch\",\n )\n\nRECOGNIZED_URL_SCHEMES = ('http', 'https', 'ftp', 's3', 'file')\n\nDEFAULT_CHANNELS_UNIX = ('https://repo.continuum.io/pkgs/free',\n 'https://repo.continuum.io/pkgs/r',\n 'https://repo.continuum.io/pkgs/pro',\n )\n\nDEFAULT_CHANNELS_WIN = ('https://repo.continuum.io/pkgs/free',\n 'https://repo.continuum.io/pkgs/r',\n 'https://repo.continuum.io/pkgs/pro',\n 'https://repo.continuum.io/pkgs/msys2',\n )\n\nif Platform.from_sys() is Platform.win:\n DEFAULT_CHANNELS = DEFAULT_CHANNELS_WIN\nelse:\n DEFAULT_CHANNELS = DEFAULT_CHANNELS_UNIX\n\nROOT_ENV_NAME = 'root'\n\nEMPTY_MAP = frozendict()\n\n\nclass _Null(object):\n def __nonzero__(self):\n return False\n\n def __bool__(self):\n return False\n\n def __len__(self):\n return 0\n\n\nNULL = _Null()\n\nUTF8 = 'UTF-8'\nROOT_NO_RM = (\n 'python',\n 'pycosat',\n 'ruamel_yaml',\n 'conda',\n 'openssl',\n 'requests',\n)\n\n# Maximum priority, reserved for packages we really want to remove\nMAX_CHANNEL_PRIORITY = 10000\n","sub_path":"conda/base/constants.py","file_name":"constants.py","file_ext":"py","file_size_in_byte":4194,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"243109963","text":"#!/usr/bin/env python\n#\n# Copyright (C) 2015, Luca Baldini (luca.baldini@pi.infn.it).\n#\n# This program is free software; you can redistribute it and/or modify\n# it under the terms of the GNU General Public License as published by\n# the Free Software Foundation; either version 3 of the License, or\n# (at your option) any later version.\n#\n# This program is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n# GNU General Public License for more details.\n#\n# You should have received a copy of the GNU General Public License along\n# with this program; if not, write to the Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.\n\n\nfrom matplotlib_ import *\n\n\nSCORES = {\n 18: 1,\n 22: 3,\n 23: 13,\n 24: 9,\n 25: 3,\n 26: 7,\n 27: 15,\n 28: 22,\n 30: 12\n}\n\nprint('Number of students: %d' % sum(SCORES.values()))\n\nleft = SCORES.keys()\nleft.sort()\nheight = [SCORES[key] for key in left]\n\nplt.figure()\nbar_plot(left, height, xlabel='Voto d\\'esame', ylabel='Numero di occorrenze',\n show_values=True)\nplt.axis([17, 31, None, None])\nsave_current_figure('voti_appello_esame.pgf')\n\nshow_figures()\n","sub_path":"macro/plt_appello_esami.py","file_name":"plt_appello_esami.py","file_ext":"py","file_size_in_byte":1278,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"199148549","text":"# coding=utf8\r\n\r\nimport pytop.topapi as topapi\r\nimport requests\r\nimport urllib.parse\r\nimport datetime, hashlib, json\r\n\r\n\r\nclass TOPBaseClient:\r\n \"\"\" TOP请求客户端的 base class. \"\"\"\r\n OPENER = requests.session()\r\n # 子类须重设request url.\r\n REQUEST_URL = ''\r\n\r\n def __init__(self, app_key, app_secret):\r\n self.url = self.REQUEST_URL\r\n self.app_key = app_key\r\n self.app_secret = app_secret\r\n self.opener = self.OPENER\r\n\r\n def urlencode(self, params, encoding='utf8'):\r\n return urllib.parse.urlencode(params, encoding=encoding, safe=',')\r\n\r\n def create_param(self, top_request, format='json', **kwargs):\r\n \"\"\" 创建调用参数. \"\"\"\r\n pass\r\n\r\n def request(self, top_request, method, data=None, format='json', is_transform=False, **kwargs):\r\n \"\"\" @param kwargs(dict): 全部用于URI query 的拼接. \"\"\"\r\n if method.lower() not in {'get', 'post'}:\r\n raise Exception('不支持的请求方法 %s!' % method)\r\n if not top_request.check_required():\r\n raise Exception('缺少必须的参数!')\r\n # 如用请求需要提交数据, 强制将请求方法设置为 post.\r\n if data and method=='get': method = 'post'\r\n if method=='get':\r\n response = self.opener.get(self.url, params=self.create_param(top_request, format=format, **kwargs))\r\n else:\r\n response = self.opener.post(self.url, params=self.create_param(top_request, format=format, **kwargs), data=data)\r\n return top_request.response(response, format=format, is_transform=is_transform)\r\n\r\n def get(self, top_request, format='json', is_transform=False, **kwargs):\r\n \"\"\" GET 请求. request 的便捷方式. \"\"\"\r\n return self.request(top_request, method='get', format=format, is_transform=is_transform, **kwargs)\r\n\r\n def post(self, top_request, data=None, format='json', is_transform=False, **kwargs):\r\n \"\"\" POST 请求. request 的便捷方式. \"\"\"\r\n return self.request(top_request, method='post', data=data, format=format, is_transform=is_transform, **kwargs)\r\n\r\n\r\nclass TOPClient(TOPBaseClient):\r\n \"\"\" TOP请求客户端(须签名). \"\"\"\r\n REQUEST_URL = 'http://gw.api.taobao.com/router/rest'\r\n\r\n def create_sign(self, params):\r\n \"\"\" 创建签名. \"\"\"\r\n sign = '%s%s%s' % (self.app_secret, ''.join(('%s%s' % item for item in sorted(params.items()))), self.app_secret)\r\n return hashlib.md5(sign.encode('utf8')).hexdigest().upper()\r\n\r\n def create_param(self, top_request, format='json', **kwargs):\r\n \"\"\" 创建调用参数. \"\"\"\r\n sys_params = {\r\n 'method': top_request.api,\r\n 'timestamp': datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S'),\r\n 'format': format,\r\n 'app_key': self.app_key,\r\n 'v': '2.0',\r\n 'sign_method': 'md5',\r\n 'partner_id': 'top-sdk-php-20120526',\r\n }\r\n sys_params.update(top_request)\r\n sys_params.update(kwargs)\r\n sys_params['sign'] = self.create_sign(sys_params)\r\n return self.urlencode(sys_params)\r\n\r\n\r\nclass TOPAuthClient(TOPBaseClient):\r\n \"\"\" TOP请求客户端(免签名). \"\"\"\r\n REQUEST_URL = 'https://eco.taobao.com/router/rest'\r\n\r\n def __init__(self, app_key, app_secret, access_token=None, redirect_uri=''):\r\n self.access_token = access_token\r\n self.redirect_uri = redirect_uri\r\n super().__init__(app_key, app_secret)\r\n\r\n def set_access_token(self, access_token):\r\n self.access_token = access_token\r\n\r\n def set_redirect_uri(self, redirect_uri):\r\n self.redirect_uri = redirect_uri\r\n\r\n def create_param(self, top_request, format='json', **kwargs):\r\n \"\"\" 创建调用参数. \"\"\"\r\n sys_params = {\r\n 'method': top_request.api,\r\n 'format': format,\r\n 'v': '2.0',\r\n 'access_token': self.access_token,\r\n }\r\n sys_params.update(top_request)\r\n sys_params.update(kwargs)\r\n return self.urlencode(sys_params)\r\n\r\n def create_auth_url(self, kind, **kwargs):\r\n \"\"\" 创建显示给用户的授权页面的 url, kind=server时,必须传入redirect_uri. \"\"\"\r\n url = 'https://oauth.taobao.com/authorize'\r\n kinds = {\r\n 'server': {'response_type': 'code'},\r\n 'client': {'response_type': 'token'},\r\n 'native': {'response_type': 'code', 'redirect_uri': 'urn:ietf:wg:oauth:2.0:oob'},\r\n }\r\n sys_args = {\r\n 'client_id': self.app_key,\r\n 'redirect_uri': self.redirect_uri,\r\n }\r\n sys_args.update(kinds.get(kind.lower()))\r\n sys_args.update(kwargs)\r\n return '%s?%s' % (url, self.urlencode(sys_args))\r\n\r\n\r\n def create_native_code_url(self, track_id, state='', scope='', view='web'):\r\n \"\"\" 用于 native application 授权方式, 创建包含有授权码(code)页面的url. \"\"\"\r\n url = 'https://oauth.taobao.com/authorize'\r\n sys_args = {\r\n 'client_id': self.app_key,\r\n 'track_id': track_id,\r\n 'response_type': 'code',\r\n 'redirect_uri': 'urn:ietf:wg:oauth:2.0:oob',\r\n 'state': state,\r\n 'scope': scope,\r\n 'view': view,\r\n 'agreement': 'true',\r\n }\r\n return '%s?%s' % (url, self.urlencode(sys_args))\r\n\r\n\r\n def fetch_token(self, kind, code, saved=False, **kwargs):\r\n \"\"\" 由授权码获取访问令牌(access_token). Server-side flow 和 Native Application 才需要通过这方式取得访问令牌, 前者必须正确指定 redirect_uri. \"\"\"\r\n url = 'https://oauth.taobao.com/token'\r\n kinds = {\r\n 'server': {'grant_type': 'authorization_code'},\r\n 'native': {'grant_type': 'authorization_code', 'redirect_uri': 'urn:ietf:wg:oauth:2.0:oob'},\r\n }\r\n sys_args = {\r\n 'client_id': self.app_key,\r\n 'client_secret': self.app_secret,\r\n 'code': code,\r\n 'redirect_uri': self.redirect_uri,\r\n }\r\n sys_args.update(kinds.get(kind.lower()))\r\n sys_args.update(kwargs)\r\n params = self.urlencode(sys_args)\r\n r = self.opener.post(url, params=params)\r\n json_obj = json.loads(r.text)\r\n if saved and 'error' not in json_obj: self.access_token = json_obj.get('access_token')\r\n return json_obj\r\n\r\n def refresh_tocken(self, refresh_token, saved=False, **kwargs):\r\n url = 'https://oauth.taobao.com/token'\r\n sys_params = {\r\n 'client_id': self.app_key,\r\n 'client_secret': self.app_secret,\r\n 'grant_type': 'refresh_token',\r\n 'refresh_token': refresh_token,\r\n }\r\n sys_params.update(kwargs)\r\n params = self.urlencode(sys_params)\r\n r = self.opener.post(url, params=params)\r\n json_obj = json.loads(r.text)\r\n if saved and 'error' not in json_obj: self.access_token = json_obj.get('access_token')\r\n return json_obj\r\n\r\n def logoff(self, redirect_uri='', view='web'):\r\n url = 'https://oauth.taobao.com/logoff'\r\n sys_params = {\r\n 'client_id': self.app_key,\r\n 'redirect_uri': redirect_uri or self.redirect_uri,\r\n 'view': view,\r\n }\r\n params = self.urlencode(sys_params)\r\n self.opener.get(url, params=params)\r\n\r\n\r\n","sub_path":"Python/pyTOP/pytop/topclient.py","file_name":"topclient.py","file_ext":"py","file_size_in_byte":7413,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"536746410","text":"\"\"\"\nНапишите программу, которая меняет местами столбцы в матрице.\n\n*Формат входных данных\nНа вход программе на разных строках подаются два натуральных числа n и m — количество строк\nи столбцов в матрице, затем элементы матрицы построчно через пробел, затем числа i и j — номера столбцов,\nподлежащих обмену.\n\n*Формат выходных данных\nПрограмма должна вывести указанную таблицу с замененными столбцами.\n\"\"\"\n\nn, m = int(input()), int(input())\n\nmatrix = []\n\nfor i in range(n):\n elem = input().split()\n matrix.append(elem)\n\nc, r = input().split()\nc, r = int(c), int(r)\n\nfor i in range(len(matrix)):\n for j in range(len(matrix[i])):\n if j == c:\n print(matrix[i][r], end=' ')\n elif j == r:\n print(matrix[i][c], end=' ')\n else:\n print(matrix[i][j], end=' ')\n print()","sub_path":"Columns_Swapping.py","file_name":"Columns_Swapping.py","file_ext":"py","file_size_in_byte":1148,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"498593646","text":"# Copyright 2021 BlobCity, 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\"\"\"\nThis Python file consists of function to perform basic data cleaning/data preprocessing operation on most dataset.\nFunctions includes, Removal of Unique COlumns,High Null value ratio, Missing Value Handling, String Categorical feature Handling .\n\"\"\"\n\nimport numpy as np\nimport pandas as pd\nfrom sklearn.preprocessing import LabelEncoder\nfrom blobcity.utils.ProblemType import ProType\nimport warnings\nwarnings.filterwarnings(\"ignore\")\n\ndef dataCleaner(df,features,target,DictionaryClass):\n \"\"\"\n Funciton to check null occurances and handles other functions.\n\n param1: pandas DataFrame\n param2: target column name\n param3: Dictionary Class object\n\n return: pandas dataframe\n\n working:\n First the function identifies the problem type that is either regression or classification using ProType Class and its function checkType.\n For the Complete dataframe if any rows has more then 50% null values or missing values we will drop it.\n For the Complete dataframe if any columns has more then equal to 80% null missing values we will drop it to avoid any noise or sequed data imputation.\n Then check whether the dataframe has any null values. \n if TRUE then : get all the columns names with null/missing values.\n for each columns with missing data call Cleaner function to Handle missing value with appropriate missing value handling strategy.\n Once Missing values are handled perform categorical value handling operation by calling Encoder() function with appropriate arguments\n \"\"\"\n problemtype=ProType()\n missingdict=dict()\n DictionaryClass.addKeyValue('problem',problemtype.checkType(df[target]))\n \n updateddf=df[features].copy(deep=True)\n updateddf[target]=df[target].copy(deep=True)\n updateddf=RemoveRowsWithHighNans(updateddf)\n updateddf=RemoveHighNullValues(updateddf)\n updateddf=dropUniqueColumn(updateddf,target)\n if updateddf.isnull().values.any(): \n cols=updateddf.columns[updateddf.isnull().any()].tolist()\n for i in cols:\n Cleaner(updateddf,i,missingdict)\n DictionaryClass.addKeyValue('cleaning',{'missingValues':missingdict})\n\n X_values,Y_value=updateddf.drop(target,axis=1),updateddf[target]\n\n EncoderResult=Encoder(DictionaryClass,X_values,Y_value,target)\n\n DictionaryClass.addKeyValue('features',{'X_values':X_values.columns.to_list(),'Y_values':target})\n\n return EncoderResult\n\ndef dropUniqueColumn(X_values,target):\n \"\"\"\n param1: pandas.DataFrame \n return : pandas.DataFrame\n\n Function Drop Column with Complete Unique data for example data such as ID,UniqueID etc.\n for all available feature in the dataframe it checks whether the column has unique value counts equal to number of entries\n in the dataset. and drops if exists and return dataframe once dropped.\n \"\"\" \n row_counts = len(X_values)\n for i in X_values.columns.to_list():\n if len(X_values[i].unique())==row_counts and i!=target:\n X_values.drop(i, axis=1, inplace=True)\n return X_values\n\ndef RemoveHighNullValues(dataframe):\n \"\"\"\n param1: pandas.DataFrame\n return: pandas.DataFrame\n\n Function drops any feature with more then 80% of Null Values and return the Dataframe\n \"\"\"\n thresh = len(dataframe) * .2\n dataframe.dropna(thresh = thresh, axis = 1, inplace = True)\n return dataframe\n\ndef Cleaner(df,i,missingdict):\n \"\"\"\n param1: pandas DataFrame\n param2: column name\n param3: placeholder dictionary for YAML record\n\n Working:\n This funciton Handles missing values in the dataset by considering the datatype of each passed column to the function. \n if the columns datatype is object to uses mode imputation.\n while if the datatype is integer ir float, and has 3 or less unique values in it mode imputation is used,else mean imputation\n \n \"\"\"\n if(df[i].dtype in [\"float\",\"int\"]):\n if(len(np.unique(df[i]))<=3):\n df[i].fillna(df[i].mode()[0],inplace=True)\n missingdict[i]=\"mode\"\n else:\n df[i].fillna(df[i].mean(),inplace=True) \n missingdict[i]=\"mean\"\n elif(df[i].dtype==\"object\"):\n df[i].fillna(df[i].mode()[0],inplace=True)\n missingdict[i]=\"mode\"\n\ndef Encoder(DictionaryClass,X,Y,target):\n \"\"\"\n Function to Encode categorical data from the feature set and target sets.\n \n param1: X_values pd.dataframe type\n param2: y_values pd.series or numpy.ndarray\n\n return: DataFrame \n\n working:\n if the feature set(X_values) has any string categorical data(object/string/category) \n then: apply one hot encoding to the feature \n and \n if the target (Y_values) is a categorical data (object/category) \n then : Apply Label Encoding Technique to the target columns\n\n finally return both the feature and target .\n \"\"\"\n encode=dict()\n if(\"object\" in X.dtypes.to_list() or Y.dtype==\"object\"):\n if(\"object\" in X.dtypes.to_list()):\n objectTypes(X,DictionaryClass)\n X=pd.get_dummies(X)\n encode['X']='OneHotEncode' \n if(Y.dtype==\"object\" ):\n encode['Y']='LabelEncoder' \n Y=LabelEncoder().fit_transform(Y)\n dataframe=X.copy(deep=True)\n dataframe[target]=Y\n DictionaryClass.UpdateNestedKeyValue('cleaning','encode',encode)\n return dataframe\n else:\n dataframe=X.copy(deep=True)\n dataframe[target]=Y\n return dataframe\n\ndef objectTypes(X,DictionaryClass):\n \"\"\"\n param1: pandas.dataframe\n param2: class object\n\n Function indentifies existence of String Categorical features.\n If String Categorical Feature exist record the list of features with string data in Class List Variable,\n and set boolean flag for existence to True else False\n \"\"\"\n\n g = X.columns.to_series().groupby(X.dtypes).groups\n gd={k.name: v for k, v in g.items()}\n if 'object' in gd.keys():\n DictionaryClass.ObjectExist=True\n DictionaryClass.ObjectList= gd['object'].to_list() \n else:\n DictionaryClass.ObjectExist= False\n\ndef RemoveRowsWithHighNans(dataframe):\n \"\"\"\n param1: pandas.DataFrame\n return: pandas.DataFrame\n\n Function delete rows containing more than 50% NaN Values\n \"\"\"\n percent = 50.0\n min_count = int(((100-percent)/100)*dataframe.shape[1] + 1)\n dataframe = dataframe.dropna( axis=0, \n thresh=min_count)\n return dataframe\n","sub_path":"blobcity/utils/Cleaner.py","file_name":"Cleaner.py","file_ext":"py","file_size_in_byte":7052,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"137973515","text":"import pytz\n\nfrom django.utils import timezone\nfrom django.utils.deprecation import MiddlewareMixin\n\n\nclass TimezoneMiddleware(MiddlewareMixin):\n def process_request(self, request):\n try:\n user_timezone = request.user.profile.preferred_timezone\n except:\n user_timezone = 'Australia/Sydney'\n tzname = request.session.get(\n 'django_timezone', user_timezone\n )\n if tzname:\n timezone.activate(pytz.timezone(tzname))\n else:\n timezone.deactivate()\n","sub_path":"src/gbr/middleware.py","file_name":"middleware.py","file_ext":"py","file_size_in_byte":542,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"224352424","text":"import matplotlib.pyplot as plt\r\n\r\ndecision_node = dict(boxstyle=\"sawtooth\", fc=\"0.8\")\r\nleaf_node = dict(boxstyle=\"round4\", fc=\"0.8\")\r\narrow_args = dict(arrowstyle=\"<-\")\r\n\r\n\r\ndef plot_node(node_text, center, parent, node_type):\r\n # create_plot.ax1 函数变量??\r\n create_plot.ax1.annotate(node_text, xy=parent, xycoords='axes fraction', xytext=center, textcoords='axes fraction',\r\n va='center', ha='center', bbox=node_type, arrowprops=arrow_args)\r\n\r\n\r\ndef create_plot(tree):\r\n # 创建新图形并清空绘图区\r\n figure = plt.figure(1, facecolor='white', figsize=(12, 7))\r\n figure.clf()\r\n # 下面三行就绘制的那个示例\r\n # create_plot.ax1 = plt.subplot(111,frameon = False)\r\n # plot_node('a decision node',(0.5,0.1),(0.1,0.5),decision_node)\r\n # plot_node('a leaf node',(0.8,0.1),(0.3,0.8),leaf_node)\r\n\r\n axprops = dict(xticks=[], yticks=[])\r\n create_plot.ax1 = plt.subplot(111, frameon=False, **axprops)\r\n plot_tree.total_w = float(get_num_leafs(tree))\r\n plot_tree.total_d = float(get_tree_depth(tree))\r\n plot_tree.x_off = -0.5 / plot_tree.total_w\r\n plot_tree.y_off = 1.\r\n plot_tree(tree, (0.5, 1.), '')\r\n\r\n plt.show()\r\n\r\n\r\ndef plot_mid_text(center, parent, txt_string):\r\n # 中间文本的坐标,上减下加上下\r\n x_mid = (parent[0] - center[0]) / 2. + center[0]\r\n y_mid = (parent[1] - center[1]) / 2. + center[1]\r\n create_plot.ax1.text(x_mid, y_mid, txt_string)\r\n\r\n\r\ndef plot_tree(tree, parent, node_text):\r\n \"\"\"晦涩\"\"\"\r\n # 计算叶子数量\r\n num_leafs = get_num_leafs(tree)\r\n depth = get_tree_depth(tree)\r\n first_str = list(tree.keys())[0]\r\n # 定位\r\n center = (plot_tree.x_off + (1.0 + float(num_leafs)) / 2. / plot_tree.total_w, plot_tree.y_off)\r\n # 中间的文本\r\n plot_mid_text(center, parent, node_text)\r\n # 节点\r\n plot_node(first_str, center, parent, decision_node)\r\n second_dict = tree[first_str]\r\n plot_tree.y_off -= 1. / plot_tree.total_d\r\n # 开始画了,也是递归\r\n for key in second_dict.keys():\r\n if type(second_dict[key]).__name__ == 'dict':\r\n plot_tree(second_dict[key], center, str(key))\r\n else:\r\n plot_tree.x_off += 1. / plot_tree.total_w\r\n plot_node(second_dict[key], (plot_tree.x_off, plot_tree.y_off), center, leaf_node)\r\n plot_mid_text((plot_tree.x_off, plot_tree.y_off), center, str(key))\r\n plot_tree.y_off += 1. / plot_tree.total_d\r\n\r\n\r\ndef get_num_leafs(tree):\r\n \"\"\"递归求叶子\"\"\"\r\n num_leafs = 0\r\n first_str = list(tree.keys())[0]\r\n second_dict = tree[first_str]\r\n for key in second_dict.keys():\r\n # 如果节点还是一个字典,就说明还可以继续\r\n if type(second_dict[key]).__name__ == 'dict':\r\n num_leafs += get_num_leafs(second_dict[key])\r\n else:\r\n # 每次发现一个节点就加一,最终的那个子叶也是加个1就跑了\r\n num_leafs += 1\r\n\r\n return num_leafs\r\n\r\n\r\ndef get_tree_depth(tree):\r\n \"\"\"其实差不太多\"\"\"\r\n max_depth = 0\r\n first_str = list(tree.keys())[0]\r\n second_dict = tree[first_str]\r\n for key in second_dict.keys():\r\n if type(second_dict[key]).__name__ == 'dict':\r\n this_depth = 1 + get_tree_depth(second_dict[key])\r\n else:\r\n this_depth = 1\r\n if this_depth > max_depth:\r\n max_depth = this_depth\r\n return max_depth\r\n\r\n\r\ndef main(tree):\r\n create_plot(tree)\r\n print(get_num_leafs(tree))\r\n print(get_tree_depth(tree))\r\n return\r\n","sub_path":"src/print_tree.py","file_name":"print_tree.py","file_ext":"py","file_size_in_byte":3585,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"349550241","text":"import sys, os, pickle\nimport numpy as np\nimport gensim\nfrom gensim import corpora\nimport codecs\n\"\"\"\ntag2label = {\"O\": 0,\n \"B-NP\":1, \"I-NP\":2,\n \"B-VP\":3, \"I-VP\":4,\n \"B-PP\":5, \"I-PP\":6,\n \"B-SBAR\":7, \"I-SBAR\":8,\n \"B-ADVP\":9, \"I-ADVP\":10,\n \"B-ADJP\":11, \"I-ADJP\":12,\n \"B-CONJP\":13, \"I-CONJP\":14,\n \"B-INTJ\":15, \"I-INTJ\":16,\n \"B-LST\":17, \"I-LST\":18,\n \"B-PRT\":19,\n }\n\"\"\"\ntag2label = {\"O\":0, \"B-AP\":1,\"I-AP\":2,}\n\ndef read_data(data_path):\n data = []\n with open(data_path,'r',encoding='utf-8') as fr:\n lines= fr.readlines()\n for line in lines:\n [char,label] = line.strip('\\n').split(' ||| ')\n data.append([char,label])\n# print(data)\n return data\n\ndef read1_data(data_path):\n data = []\n with codecs.open(data_path,'r',encoding='utf-8') as fr:\n lines = []\n sent_, tag_ = [], []\n for line in fr:\n if len(line.strip().split(' ')) ==2:\n [char,label] = line.strip().split(' ')\n sent_.append(char)\n tag_.append(label)\n #print(char)\n # print(label)\n else:\n if len(line.strip())==0:\n data.append([' '.join(sent_),' '.join(tag_)])\n sent_,tag_=[], []\n\n# print(data)\n return data \n \ndef read_vocab(data_path):\n data = []\n with open(data_path,'r',encoding='utf-8') as fr:\n lines= fr.readlines()\n for line in lines:\n [char,label] = line.strip('\\n').split(' ||| ')\n data.append([char])\n return data\n\ndef vocab_build(vocab_path, data_path):\n data = read_vocab(data_path)\n word2id = {}\n for num,sent_ in enumerate(data):\n tokens = [[token for token in sentence.split()] for sentence in sent_]\n if num == 0:\n gensim_dictionary = corpora.Dictionary(tokens)\n else:\n gensim_dictionary.add_documents(tokens)\n word2id = gensim_dictionary.token2id\n with open(vocab_path,'wb') as fw:\n pickle.dump(word2id,fw,0)\n\n\ndef sentence2id(sent, word2id):\n\n sentence_id = []\n for word in sent:\n sentence_id.append(word2id[word])\n return sentence_id\n\ndef read_dictionary(data_path):\n data_path = os.path.join(data_path)\n with open(data_path, 'rb') as fr:\n word2id = pickle.load(fr)\n return word2id\n\ndef pad_sequences(sequences, pad=0):\n max_len = max(map(lambda x : len(x),sequences))\n seq_list, seq_len_list = [], []\n for seq in sequences:\n seq = list(seq)\n seq_ = seq[:max_len] + [pad] * max(max_len -len(seq),0)\n seq_list.append(seq_)\n seq_len_list.append(min(len(seq), max_len))\n return seq_list, seq_len_list\n\ndef get_token(data, batch_size, vocab,tag2label):\n assert len(data)==2\n for sequences in data:\n token = data[0]\n label = data[-1]\n\ndef get_id_data(data,vocab,tag2label):\n seqs,labels=[],[]\n sent_ = data[0].split(' ')\n tag_ = data[-1].split(' ')\n sent_ = sentence2id(sent_,vocab)\n label_ = [tag2label[tag] for tag in tag_]\n seqs.append(sent_)\n labels.append(label_)\n \n id_data= zip(seqs,labels)\n return id_data\n\ndef batch_yield(data, batch_size, vocab,tag2label):\n seqs, labels = [], []\n for (sent_,tag_) in data:\n sent_ = sentence2id(sent_, vocab)\n label_ = [tag2label[tag] for tag in tag_]\n if len(seqs) == batch_size:\n yield seqs, labels\n seqs, labels = [], []\n\n seqs.append(sent_)\n labels.append(label_)\n \n batch_m = (seqs,labels)\n # print(\"129 vocab.py\"+\"\\n\") \n# print(seqs)\n if len(seqs) !=0:\n yield batch_m\n\n","sub_path":"vocab.py","file_name":"vocab.py","file_ext":"py","file_size_in_byte":3743,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"428706702","text":"\"\"\"\nImports\n\n\"\"\"\nimport struct\nfrom hashlib import sha256\n\n\"\"\"\nGeneral variables\n\nThis has variables that are important to the comunication\n\n\"\"\"\n\nPORT = 52377\n\n\"\"\"\nEnums\n\nthis has type enum and subtypes enums\nthe value of the enum is the value of the type in the protocol\n\n\"\"\"\n\n# Enum for type\nclass Type:\n # general\n ERROR = 0\n\n # control/initial\n NAME = 1\n ID = 2\n BOARD = 3\n DISCONNECTION = 4\n INITIAL = 5\n CONTROL = 8\n GAME = 9\n\n # management/update\n SNAKE = 6\n ORB = 7\n\n\n# Enum for subtypes\nclass Subtype:\n class ERROR:\n name_error = 0\n full_server = 1\n\n class NAME:\n request = 0\n response = 1\n\n class ID:\n send = 0\n confirm = 1\n\n class BOARD:\n send_dimensions = 0\n confirm_dimensions = 1\n request_location = 2\n send_location = 3\n\n class DISCONNECTION:\n announce = 0\n confirm = 1\n\n class SNAKE:\n new = 0\n full_update = 1\n delete = 2\n change_angle = 3\n\n class ORB:\n new = 0\n delete = 1\n\n class INITIAL:\n server = 0\n client = 1\n\n class CONTROL:\n stream_end = 0\n\n class GAME:\n start = 0\n\n\n\"\"\"\nBuilders\n\nthis has functions to build all the possible message types\n\n\"\"\"\n\n\ndef error_name_error():\n message = 'This name is already taken.'\n data = struct.pack('!H', Type.ERROR)\n data += struct.pack('!H', Subtype.ERROR.name_error)\n data += message\n return data\n\n\ndef error_full_server():\n message = 'Server in full entry denied'\n data = struct.pack('!H', Type.ERROR)\n data += struct.pack('!H', Subtype.ERROR.full_server)\n data += message\n return data\n\n\ndef name_request():\n data = struct.pack('!H', Type.NAME)\n data += struct.pack('!H', Subtype.NAME.request)\n return data\n\n\ndef name_response(name):\n data = struct.pack('!H', Type.NAME)\n data += struct.pack('!H', Subtype.NAME.response)\n data += name\n return data\n\n\ndef id_send(id_):\n data = struct.pack('!H', Type.ID)\n data += struct.pack('!H', Subtype.ID.send)\n data += id_\n return data\n\n\ndef id_confirm():\n data = struct.pack('!H', Type.ID)\n data += struct.pack('!H', Subtype.ID.confirm)\n return data\n\n\ndef board_send_dimensions(width, height):\n data = struct.pack('!H', Type.BOARD)\n data += struct.pack('!H', Subtype.BOARD.send_dimensions)\n data += struct.pack('!H', width)\n data += struct.pack('!H', height)\n return data\n\n\ndef board_confirm_dimensions():\n data = struct.pack('!H', Type.BOARD)\n data += struct.pack('!H', Subtype.BOARD.confirm_dimensions)\n return data\n\n\ndef board_request_location():\n return struct.pack('!HH', Type.BOARD, Subtype.BOARD.request_location)\n\n\ndef board_send_location(x, y):\n data = struct.pack('!H', Type.BOARD)\n data += struct.pack('!H', Subtype.BOARD.send_location)\n data += struct.pack('!f', x)\n data += struct.pack('!f', y)\n return data\n\n\ndef disconnection_announce():\n data = struct.pack('!H', Type.DISCONNECTION)\n data += struct.pack('!H', Subtype.DISCONNECTION.announce)\n return data\n\n\ndef disconnection_confirm():\n data = struct.pack('!H', Type.DISCONNECTION)\n data += struct.pack('!H', Subtype.DISCONNECTION.confirm)\n return data\n\n\ndef snake_new(id_, name, mass, head, tail):\n data = struct.pack('!H', Type.SNAKE)\n data += struct.pack('!H', Subtype.SNAKE.new)\n data += id_\n data += struct.pack('!b', len(name))\n data += name\n data += struct.pack('!l', mass)\n x, y = head\n data += struct.pack('!ff', x, y)\n for x, y in tail:\n data += struct.pack('!ff', x, y)\n return data\n\n\ndef snake_full_update(id_, mass, head, tail):\n data = struct.pack('!H', Type.SNAKE)\n data += struct.pack('!H', Subtype.SNAKE.full_update)\n data += id_\n data += struct.pack('!l', mass)\n x, y = head\n data += struct.pack('!f', x)\n data += struct.pack('!f', y)\n for x, y in tail:\n data += struct.pack('!f', x)\n data += struct.pack('!f', y)\n return data\n\n\ndef snake_delete(id_):\n data = struct.pack('!H', Type.SNAKE)\n data += struct.pack('!H', Subtype.SNAKE.delete)\n data += id_\n return data\n\n\ndef snake_change_angle(angle):\n data = struct.pack('!H', Type.SNAKE)\n data += struct.pack('!H', Subtype.SNAKE.change_angle)\n data += struct.pack('!f', angle)\n return data\n\n\ndef orb_new(id_, mass, x, y, color):\n data = struct.pack('!H', Type.ORB)\n data += struct.pack('!H', Subtype.ORB.new)\n data += id_\n data += struct.pack('!B', mass)\n data += struct.pack('!f', x)\n data += struct.pack('!f', y)\n r, g, b = color\n data += struct.pack('!B', r)\n data += struct.pack('!B', g)\n data += struct.pack('!B', b)\n return data\n\n\ndef orb_delete(id_):\n data = struct.pack('!H', Type.ORB)\n data += struct.pack('!H', Subtype.ORB.delete)\n data += id_\n return data\n\n\ndef initial_server(width, height, id_):\n data = struct.pack('!H', Type.INITIAL)\n data += struct.pack('!H', Subtype.INITIAL.server)\n data += struct.pack('!H', width)\n data += struct.pack('!H', height)\n data += id_\n return data\n\n\ndef initial_client(name):\n data = struct.pack('!H', Type.INITIAL)\n data += struct.pack('!H', Subtype.INITIAL.client)\n data += name\n return data\n\n\ndef control_stream_end():\n data = struct.pack('!H', Type.CONTROL)\n data += struct.pack('!H', Subtype.CONTROL.stream_end)\n return data\n\n\ndef game_start():\n data = struct.pack('!H', Type.GAME)\n data += struct.pack('!H', Subtype.GAME.start)\n return data\n\n\n\"\"\"\nProtocol Parsing\n\nthis section has all the code that parsers given recived data.\nthis has three parts.\n- individuals parsers for each protocol message types. \n- dispatcher that connects types to their function.\n- general parsing function.\n\n\"\"\"\n\n\ndef __error_parser(data):\n kwargs = {}\n kwargs['message'] = data\n return kwargs\n\n\ndef __name_request_parser(data):\n kwargs = {}\n return kwargs\n\n\ndef __name_response_parser(data):\n kwargs = {}\n kwargs['name'] = data\n return kwargs\n\n\ndef __id_send_parser(data):\n kwargs = {}\n kwargs['id'] = data\n return kwargs\n\n\ndef __id_confirm_parser(data):\n kwargs = {}\n return kwargs\n\n\ndef __board_send_dimensions_parser(data):\n kwargs = {}\n kwargs['width'] = struct.unpack('!H', data[:2])[0]\n kwargs['height'] = struct.unpack('!H', data[2:])[0]\n return kwargs\n\n\ndef __board_confirm_dimensions_parser(data):\n kwargs = {}\n return kwargs\n\n\ndef __board_request_location_parser(data):\n kwargs = {}\n return kwargs\n\n\ndef __board_send_location_parser(data):\n kwargs = {}\n kwargs['x'] = struct.unpack('!f', data[:4])[0]\n kwargs['y'] = struct.unpack('!f', data[4:])[0]\n return kwargs\n\n\ndef __disconnection_announce_parser(data):\n kwargs = {}\n return kwargs\n\n\ndef __disconnection_confirm_parser(data):\n kwargs = {}\n return kwargs\n\n\ndef __snake_new_parser(data):\n kwargs = {}\n\n kwargs['id'] = data[:KEY_SIZE]\n data = data[KEY_SIZE:]\n\n name_len = struct.unpack('!b', data[:1])[0]\n data = data[1:]\n\n kwargs['name'] = data[:name_len]\n data = data[name_len:]\n\n kwargs['mass'] = struct.unpack('!l', data[:4])[0]\n data = data[4:]\n\n x = struct.unpack('!f', data[:4])[0]\n y = struct.unpack('!f', data[4:8])[0]\n kwargs['head'] = (x, y)\n data = data[8:]\n\n tail = []\n while data:\n x = struct.unpack('!f', data[:4])[0]\n y = struct.unpack('!f', data[4:8])[0]\n tail.append((x, y))\n data = data[8:]\n kwargs['tail'] = tail\n\n return kwargs\n\n\ndef __snake_full_update_parser(data):\n kwargs = {}\n\n kwargs['id'] = data[:KEY_SIZE]\n data = data[KEY_SIZE:]\n\n kwargs['mass'] = struct.unpack('!l', data[:4])[0]\n data = data[4:]\n x = struct.unpack('!f', data[:4])[0]\n y = struct.unpack('!f', data[4:8])[0]\n kwargs['head'] = (x, y)\n data = data[8:]\n\n tail = []\n while data:\n x = struct.unpack('!f', data[:4])[0]\n y = struct.unpack('!f', data[4:8])[0]\n tail.append((x, y))\n data = data[8:]\n kwargs['tail'] = tail\n\n return kwargs\n\n\ndef __snake_delete_parser(data):\n kwargs = {}\n kwargs['id'] = data\n return kwargs\n\n\ndef __snake_change_angle_parser(data):\n kwargs = {}\n kwargs['angle'] = float(struct.unpack('!f', data)[0])\n return kwargs\n\n\ndef __orb_new_parser(data):\n kwargs = {}\n kwargs['id'] = data[:KEY_SIZE]\n data = data[KEY_SIZE:]\n kwargs['mass'] = struct.unpack('!B', data[:1])[0]\n kwargs['x'] = struct.unpack('!f', data[1:5])[0]\n kwargs['y'] = struct.unpack('!f', data[5:9])[0]\n r = struct.unpack('!B', data[9:10])[0]\n g = struct.unpack('!B', data[10:11])[0]\n b = struct.unpack('!B', data[11:12])[0]\n kwargs['color'] = (r, g, b)\n return kwargs\n\n\ndef __orb_delete_parser(data):\n kwargs = {}\n kwargs['id'] = data\n return kwargs\n\n\ndef __initial_server_parser(data):\n kwargs = {}\n kwargs['width'] = struct.unpack('!H', data[:2])[0]\n kwargs['height'] = struct.unpack('!H', data[2:4])[0]\n kwargs['id'] = data[4:]\n return kwargs\n\n\ndef __initial_client_parser(data):\n kwargs = {}\n kwargs['name'] = data\n return kwargs\n\n\ndef __control_stream_end_parser(data):\n kwargs = {}\n return kwargs\n\n\ndef __game_start_parser(data):\n kwargs = {}\n return kwargs\n\n\n# this \"translates\" the type and subtype to the matching parsing function\nDISPATCHER = {\n (Type.ERROR, Subtype.ERROR.name_error): __error_parser,\n (Type.ERROR, Subtype.ERROR.full_server): __error_parser,\n (Type.NAME, Subtype.NAME.request): __name_request_parser,\n (Type.NAME, Subtype.NAME.response): __name_response_parser,\n (Type.ID, Subtype.ID.send): __id_send_parser,\n (Type.ID, Subtype.ID.confirm): __id_confirm_parser,\n (Type.BOARD, Subtype.BOARD.send_dimensions): __board_send_dimensions_parser,\n (Type.BOARD, Subtype.BOARD.confirm_dimensions): __board_confirm_dimensions_parser,\n (Type.BOARD, Subtype.BOARD.request_location): __board_request_location_parser,\n (Type.BOARD, Subtype.BOARD.send_location): __board_send_location_parser,\n (Type.DISCONNECTION, Subtype.DISCONNECTION.announce): __disconnection_announce_parser,\n (Type.DISCONNECTION, Subtype.DISCONNECTION.confirm): __disconnection_confirm_parser,\n (Type.SNAKE, Subtype.SNAKE.new): __snake_new_parser,\n (Type.SNAKE, Subtype.SNAKE.full_update): __snake_full_update_parser,\n (Type.SNAKE, Subtype.SNAKE.delete): __snake_delete_parser,\n (Type.SNAKE, Subtype.SNAKE.change_angle): __snake_change_angle_parser,\n (Type.ORB, Subtype.ORB.new): __orb_new_parser,\n (Type.ORB, Subtype.ORB.delete): __orb_delete_parser,\n (Type.INITIAL, Subtype.INITIAL.server): __initial_server_parser,\n (Type.INITIAL, Subtype.INITIAL.client): __initial_client_parser,\n (Type.CONTROL, Subtype.CONTROL.stream_end): __control_stream_end_parser,\n (Type.GAME, Subtype.GAME.start): __game_start_parser,\n}\n\n\ndef parse(data):\n \"\"\"\n\n Args:\n data:\n\n Returns:\n\n \"\"\"\n kwargs = {}\n kwargs['type'] = struct.unpack('!H', data[0:2])[0]\n kwargs['subtype'] = struct.unpack('!H', data[2:4])[0]\n\n # this gets the matching parsing function from the dispathcer and calls it\n # with the data without the type and subtype.\n additional_kwargs = DISPATCHER[kwargs['type'], kwargs['subtype']](data[4:])\n kwargs.update(additional_kwargs)\n return kwargs\n\n\n\"\"\"\nAdditional functions\n\n\"\"\"\n\n\ndef add_length(data):\n \"\"\"\n\n Args:\n data:\n\n Returns:\n\n \"\"\"\n length = len(data)\n\n if length > 65536:\n raise ValueError('length of the packet cant be more than 65536. ({})'.format(length))\n\n length = struct.pack('!H', len(data))\n return length + data\n\n\nKEY_SIZE = 32 # key is made with sha256 (32 bytes)\n\n\ndef key(obj):\n \"\"\"\n\n Args:\n obj:\n\n Returns:\n\n \"\"\"\n return sha256(str(id(obj))).digest()\n\n\ndef hex_con(data):\n \"\"\"\n\n Args:\n data:\n\n Returns:\n\n \"\"\"\n return ''.join([r'\\x{:x}'.format(ord(c)) for c in data])\n\n\n\"\"\"\nIO Functions\n\nthis functions use a length before the message for safe transfer\n\n\"\"\"\n\n\ndef send_data(sock, data):\n \"\"\"\n\n Args:\n sock:\n data:\n\n Returns:\n\n \"\"\"\n sock.send(add_length(data))\n # print 'send >', hex_con(data)\n\n\nLENGTH_HEADER_SIZE = 2\n\n\ndef recv_data(sock):\n \"\"\"\n\n Args:\n sock:\n\n Returns:\n\n \"\"\"\n length_str = ''\n length = 0\n while len(length_str) < LENGTH_HEADER_SIZE:\n length_str += sock.recv(LENGTH_HEADER_SIZE - len(length_str))\n if length_str == '':\n break\n\n data = ''\n if length_str != '':\n length = struct.unpack('!H', length_str)[0]\n while len(data) < length:\n data += sock.recv(length - len(data))\n if data == '':\n break\n\n if length != len(data):\n data = ''\n\n # print 'recv >', length, hex_con(data)\n return data\n","sub_path":"connection/protocol.py","file_name":"protocol.py","file_ext":"py","file_size_in_byte":12941,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"184569561","text":"from building import *\n\ncwd = GetCurrentDir()\n\nImport('asenv')\nMODULES = asenv['MODULES']\n\nobjs = []\n\nobjs += Glob('CMSIS/NN/Source/*/*.c')\nobjs += Glob('CMSIS/NN/Examples/ARM/arm_nn_examples/cifar10/*.cpp')\nobjs += Glob('CMSIS/NN/Examples/ARM/arm_nn_examples/mnist/code/*.c')\n\nasenv.Append(CPPPATH=['%s/CMSIS/NN/Include'%(cwd),\n '%s/CMSIS/DSP/Include'%(cwd),\n '%s/CMSIS/Core/Include'%(cwd),])\nasenv.Append(CPPDEFINES=['__ARM_ARCH_8M_BASE__'])\n\nReturn('objs')\n","sub_path":"SConscript","file_name":"SConscript","file_ext":"","file_size_in_byte":502,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"171331775","text":"\n\n# make sure you have ran: pip3 install requests\nimport requests\n\nimport json\nimport csv\n# change this\nurl = \"http://159.89.242.202:3000/document/e651dacfe4bf966347452b38d2fb1380/export\"\n\n\nprint('downloading from selavy')\n\nr = requests.get(url)\ndata = json.loads(r.text)\n\nentities = {}\nprint('extracting entities')\nfor b in data['blocks']:\n\tfor i in b['identities']:\n\t\tkey = i['identLabel'] + str(i['identType']) + str(i['identUri'])\n\t\tif key not in entities:\n\t\t\tentities[key] = {'label':i['identLabel'],'type':i['identType'],\"uri\":i['identUri']}\n\n\nwith open('csv_out.csv','w') as out:\n\n\twriter = csv.writer(out)\n\n\tfor x in entities:\n\t\twriter.writerow([entities[x]['label'],entities[x]['type'],entities[x]['uri']])","sub_path":"selavy/export_entities.py","file_name":"export_entities.py","file_ext":"py","file_size_in_byte":715,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"543132385","text":"#!/usr/bin/env python\n\nfrom dist_tools import *\nfrom shutil import copyfile as cp\n\n\npol_states = [\"fl\", \"il\", \"la\", \"md\", \"mn\", \"nc\", \"pa\", \"tn\", \"tx\", \"va\", \"wi\"]\nstates = [\"ca\", \"ny\", \"al\", \"oh\"]\nstates = [\"nc\", \"tx\", \"fl\"]\n\n# files = sorted(glob.glob(\"cd/*.geojson\") + \\\n# glob.glob(\"../chalk/s3/res/*/power/s26*/c*/*geojson\") + \\\n# glob.glob(\"../chalk/s3/res/*/split/s001/*geojson\") + \\\n# sum([glob.glob(\"../chalk/s3/res/res/{}/*/s26*/c*/*geojson\".format(s)) for s in states], []))\n# \n# files = glob.glob(\"../chalk/s3/res/*/path_frac/s26*/c*/*geojson\") + \\\n# glob.glob(\"../chalk/s3/res/*/hull_*/s26*/c*/*geojson\") + \\\n# glob.glob(\"../chalk/s3/res/*/split/s001/*geojson\") \n# \n# files = glob.glob(\"maps/*split*geojson\")\n\n# files = glob.glob(\"cd/*115*geojson\")\n\n# files = glob.glob(\"../cluscious/res/wi_as/power/s27*/c*/*geojson\")\n# files = glob.glob(\"cd/wi_as_2016L.geojson\")\nfiles = glob.glob(\"extras/*geojson\")\n\nfiles.sort()\n\nprint(\"Running\", len(files), \"maps.\")\n\nlast_state, map_json = None, {}\ncols = [\"state\", \"method\", \"seed\", \"cycle\", \"file\",\n \"spatial\", \"dseats\", \"rseats\", \"eg\", \"bseats\", \"hseats\"]\n\n# with open(\"map_listing.csv\", \"w\") as out: pass\n# print(files)\n\nprocessed = pd.read_csv(\"map_listing.csv\", names = cols)\\\n .drop_duplicates(\"file\", keep = \"last\")[\"file\"].values\n\nfor fi, f in enumerate(files): \n \n fo = f.replace(\"../chalk/s3/res/\", \"\")\n fo = fo.replace(\"../cluscious/res/\", \"\")\n fo = fo.replace(\"res/\", \"\")\n fo = fo.replace(\"maps/\", \"\")\n fo = fo.replace(\"extras/\", \"\")\n fo = re.sub(r\"cd/([a-z][a-z])_(1[01][1457])\", r\"\\1/cd_\\2\", fo)\n fo = re.sub(r\"cd/wi_as_2016L\", r\"wi_as/2016L\", fo)\n fo = fo.replace(\"/final\", \"\")\n\n if \"maps/\" in f:\n fl = re.sub(r\"([a-z][a-z])_([a-z_]+)_(s[0-9]{3})_(c[0-9]{3}).geojson\", r\"\\1+\\2+\\3+\\4\", fo)\n fl = re.sub(r\"([a-z][a-z])_(cd_1[01][1457]).geojson\", r\"\\1+\\2\", fl)\n fl = re.sub(r\"([a-z][a-z])_split_s001.geojson\", r\"\\1+split+s001+c000\", fl)\n file_list = fl.split(\"+\")\n elif \"extras\" in f:\n fl = re.sub(r\"([a-z][a-z])_(cd_1[01][14567]).geojson\", r\"\\1+\\2\", fo)\n file_list = fl.split(\"+\")\n else:\n file_list = fo.replace(\".geojson\", \"\").split(\"/\")\n\n fo = fo.replace(\"/\", \"_\")\n fo = \"maps/\" + fo\n\n if fo in processed: continue\n if not \"maps/\" in f: cp(f, fo)\n\n with open(\"evaluate.sub\", \"a\") as out: out.write(fo + \"\\n\")\n \n if len(file_list) < 3: file_list.append(\"s001\")\n if len(file_list) < 4: file_list.append(\"c000\")\n print(file_list)\n \n state_tag, method, seed, cycle = file_list\n state = state_tag.split(\"_\")[0]\n\n if state_tag != last_state:\n epsg, fips, seats = get_state_info(state)\n trdf = get_state_cells(state, 2015, epsg, \"tract\")\n last_state = state_tag\n\n \n plan_dict = {\"state\" : state_tag, \"method\" : method, \"file\" : fo,\n \"seed\" : int(seed[1:]), \"cycle\" : int(cycle[1:])}\n\n # gdf = gpd.read_file(fo).rename(columns = {\"id\" : \"cd\"}).set_index(\"cd\").to_crs(epsg = epsg)\n gdf = gpd.read_file(fo).to_crs(epsg = epsg)\n\n if state_tag != state:\n seats = gdf.shape[0]\n \n\n if \"cd\" in method or \"201\" in method:\n\n plan_dict[\"spatial\"] = gdf[\"PCA1\"].mean()\n\n else:\n\n try: evaluate_spatial(gdf, trdf)\n except: continue\n plan_dict[\"spatial\"] = gdf[\"obj_pca1\"].mean()\n\n\n if state in pol_states:\n plan_dict[\"eg\"] = efficiency_gap_rep(gdf)\n plan_dict[\"dseats\"], plan_dict[\"rseats\"] = party_seats(gdf, seats)\n else:\n plan_dict[\"eg\"] = -1\n plan_dict[\"dseats\"] = -1\n plan_dict[\"rseats\"] = -1\n\n plan_dict[\"bseats\"], plan_dict[\"hseats\"] = minority_seats(gdf, seats)\n \n with open(\"map_listing.csv\", \"a\") as out:\n pd.DataFrame([plan_dict])[cols].to_csv(out, float_format='%.4g', header = False, index = False)\n\n\ndf = pd.read_csv(\"map_listing.csv\", names = cols).drop_duplicates(\"file\", keep = \"last\")\\\n .sort_values(by = [\"state\", \"method\", \"seed\", \"cycle\"])\n\nfor s in df.state.unique():\n sdf = df.loc[df.state == s, cols].to_json(\"{}_dir.json\".format(s), orient = \"records\")\n\n\n\n","sub_path":"evaluate.py","file_name":"evaluate.py","file_ext":"py","file_size_in_byte":4198,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"116606245","text":"from flask import Flask\r\nfrom flask_restful import Resource, Api, reqparse\r\n\r\napp = Flask(__name__)\r\napi = Api(app)\r\n\r\nrestaurants = []\r\nrestaurant_menus = []\r\nmenu_items = []\r\n\r\n\r\nclass Restaurant(Resource):\r\n @classmethod\r\n def get(cls, name):\r\n restaurant = next(filter(lambda rest: rest['name'] == name, restaurants), None)\r\n if restaurant:\r\n return {'restaurant': restaurant}, 200\r\n else:\r\n return 404 # 404 error code if restaurant cannot be found\r\n\r\n @classmethod\r\n def post(cls, name):\r\n # filters to only return a matching restaurant with that name, returns nothing if there is none\r\n if next(filter(lambda rest: rest['name'] == name, restaurants), None):\r\n return {'Error': \"A restaurant with name '{}' already exists.\".format(name)}, 400\r\n\r\n restaurant = {'name': name}\r\n restaurants.append(restaurant)\r\n return restaurant, 201\r\n\r\n @classmethod\r\n def delete(cls, name):\r\n global restaurants\r\n # re-creates the list without the deleted restaurant\r\n restaurants = list(filter(lambda rest: rest['name'] != name, restaurants))\r\n return {'Result': \"Restaurant was successfully deleted.\"}\r\n\r\n\r\nclass Menu(Resource):\r\n @classmethod\r\n def get(cls, name):\r\n restaurant_menu = next(filter(lambda menu: menu['name'] == name, restaurant_menus), None)\r\n if restaurant_menu:\r\n return {'restaurant_menu': restaurant_menu}, 200\r\n else:\r\n return {'Error': \"Menu '{}' could not be found.\".format(name)}, 404\r\n\r\n @classmethod\r\n def post(cls, name):\r\n if next(filter(lambda menu: menu['name'] == name, restaurant_menus), None):\r\n return {'Error': \"A menu with name '{}' already exists. \".format(name)}, 400\r\n else:\r\n restaurant_menu = {'name': name}\r\n restaurant_menus.append(restaurant_menu)\r\n return restaurant_menu, 201\r\n\r\n @classmethod\r\n def delete(cls, name):\r\n global restaurant_menus\r\n restaurant_menus = list(filter(lambda menu: menu['name'] != name, restaurant_menus))\r\n return {'Result': \"Item was successfully deleted.\"}\r\n\r\n\r\nclass MenuItem(Resource):\r\n @classmethod\r\n def get(cls, name):\r\n menu_item = next(filter(lambda item: item['name'] == name, menu_items), None)\r\n if menu_item:\r\n return {'menu_item': menu_item}, 200\r\n else:\r\n return 404 # 404 error code if item cannot be found\r\n\r\n menu_parser = reqparse.RequestParser()\r\n menu_parser.add_argument('price', type=float, required=True, help=\"The price is required.\")\r\n\r\n @classmethod\r\n def post(cls, name):\r\n # filters to only return a matching menu item with that name, returns nothing if there is none\r\n if next(filter(lambda item: item['name'] == name, menu_items), None):\r\n return {'Error': \"An item with name '{}' already exists on the menu.\".format(name)}, 400\r\n data = MenuItem.menu_parser.parse_args()\r\n\r\n menu_item = {'name': name, 'price': data['price']}\r\n menu_items.append(menu_item)\r\n return menu_item, 201\r\n\r\n @classmethod\r\n def delete(cls, name):\r\n global menu_items\r\n menu_items = list(filter(lambda item: item['name'] != name, menu_items))\r\n return {'Result': \"Item was successfully deleted.\"}\r\n\r\n @classmethod\r\n def put(cls, name):\r\n data = MenuItem.menu_parser.parse_args()\r\n menu_item = next(filter(lambda item: item['name'] == name, menu_items), None)\r\n\r\n # if the menu item does not exist, it will create a new menu item\r\n if menu_item is None:\r\n menu_item = {'name': name, 'price': data['price']}\r\n # add the new item to the existing items list\r\n menu_items.append(menu_item)\r\n # if the item already exists, the existing item will be updated with the data\r\n else:\r\n menu_item.update(data)\r\n return menu_item\r\n\r\n\r\nclass AllItems(Resource):\r\n @classmethod\r\n def get(cls):\r\n # returns all the menu items\r\n return {'All Menu Items': menu_items}\r\n\r\n\r\nclass AllMenus(Resource):\r\n @classmethod\r\n def get(cls):\r\n return {'All Menus': restaurant_menus}\r\n\r\n\r\nclass AllRestaurants(Resource):\r\n @classmethod\r\n def get(cls):\r\n return {'Restaurants': restaurants}\r\n\r\n\r\n# adds path to all menus\r\napi.add_resource(AllMenus, '/menus')\r\n# adds path to a specific item on a menu in a restaurant\r\napi.add_resource(MenuItem, '/item/')\r\n# adds path to all menu items\r\napi.add_resource(AllItems, '/items')\r\n# adds path to the list of all restaurants\r\napi.add_resource(AllRestaurants, '/restaurants')\r\n# adds path to a specific menu\r\napi.add_resource(Menu, '/menu/')\r\n# adds path to a specific restaurant\r\napi.add_resource(Restaurant, '/restaurant/')\r\n\r\napp.run(port=5000, debug=True)\r\n","sub_path":"Zappos.py","file_name":"Zappos.py","file_ext":"py","file_size_in_byte":4945,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"357412753","text":"import yaml\n\nprint(\"This is a test.\")\n\n# dummy comment\n\nwith open(\"example.yaml\", 'r') as stream:\n try:\n # waiting for sonarqube\n print(yaml.load(stream))\n # print(yaml.safe_load(stream))\n except yaml.YAMLError as exc:\n print(exc)\n\n# code smells\n\nDATA = ['a', 'b', 'c']\n\nfor i in range(len(DATA)):\n print(DATA[i])\n\ndef foo(a): # NonCompliant\n b = 12\n if a == 1:\n return b\n return b\n\n# bugs\n\nclass MyClass:\n def instance_method(): # Noncompliant. \"self\" parameter is missing.\n print(\"instance_method\")\n\n @classmethod\n def class_method(): # Noncompliant. \"cls\" parameter is missing.\n print(\"class_method\")\n\n# vulnerabilities\n\nimport tempfile\n\nfilename = tempfile.mktemp() # Noncompliant\ntmp_file = open(filename, \"w+\")","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":795,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"294220503","text":"#!/usr/bin/env python\nimport datetime\nimport os\nfrom PIL import Image\nfrom abc import abstractmethod\nimport RPi.GPIO as GPIO\nimport time\nimport wiringpi2 as wp\n\n\nclass Sensor:\n @abstractmethod\n def update(self):\n pass\n\n\nclass Ultrasonic(Sensor):\n def __init__(self):\n\n self.value = None\n\n # These should correspond to the GPIO pins connected to trig and echo on the sensor.\n\n self.trig_pin = 26\n self.echo_pin = 11\n self.setup()\n\n def setup(self):\n GPIO.setmode(GPIO.BOARD)\n GPIO.setup(self.trig_pin, GPIO.OUT)\n GPIO.setup(self.echo_pin, GPIO.IN)\n\n def get_value(self):\n\n return self.value\n\n def update(self):\n\n self.value = self.sensor_get_value()\n\n return self.value\n\n def reset(self):\n\n self.value = None\n\n def sensor_get_value(self):\n\n self.send_activation_pulse()\n\n # Sensoren starter saa programmet sitt.\n # Det den gjor er aa sende ut 8 sykler av et ultrasonisk signal paa 40kHz.\n # Den venter saa paa at signalet skal bli reflektert tilbake til leseren.\n\n # Vi leser signalet den mottar paa echo_pin\n read_val = GPIO.input(self.echo_pin)\n\n # Det som er interessent her er hvor lang tid det tar fra signalet er sendt ut, til noe er returnert\n # Naar sensoren mottar et reflektert signal vil echo pinnen settes hoy like lang tid som\n # signalet brukte fra det ble sendt ut til det ble returnert\n\n # Vi finner tiden paa siste gang echo signalet er lavt\n signaloff_start = time.time()\n\n signaloff = signaloff_start\n\n # signalet timer ut dersom det tar mer en 0.5 s, da annsees det som tapt og vi prover igjen\n while read_val == 0 and signaloff - signaloff_start < 0.5:\n read_val = GPIO.input(self.echo_pin)\n signaloff = time.time()\n\n signalon = signaloff\n\n # Finner saa den tiden det siste signalet kommer inn paa echo_pin\n while read_val == 1:\n read_val = GPIO.input(self.echo_pin)\n signalon = time.time() # Kan flytte denne ut av loopen dersom det skaper delay og unoyaktighet\n\n # Den kalkulerte avstanden\n distance = self.compute_distance(signalon, signaloff)\n\n # Returnerer distanset til objektet forran sensoren i cm\n return distance\n\n def send_activation_pulse(self):\n GPIO.output(self.trig_pin, GPIO.LOW)\n # Sensoren kan krasje dersom man ikke har et delay her. Dersom den fortsatt krasjer, prov aa oke delayet\n time.sleep(0.3)\n\n # Ultralyd-sensoren starter naar den mottar en puls, med lengde 10uS paa trig pinnen.\n # Vi gjor dette ved aa sette trig_pin hoy, venter i 10uS og setter den lav igjen.\n GPIO.output(self.trig_pin, True)\n\n # 0.00001 seconds = 10 micro seconds\n time.sleep(0.00001)\n GPIO.output(self.trig_pin, False)\n\n def compute_distance(self, signalon, signaloff):\n #print('on: ',signalon, ' off: ',signaloff)\n\n # Tiden det tok fra signalet ble sendt til det ble returnert\n timepassed = signalon - signaloff\n\n # Vi vet at signalet gaar med lydens hastighet som er ca 344 m/s\n # Avstanden til objektet forran sensoren kan vi da finne med formelen: strekning = hastighet * tid\n distance = 344 * timepassed * 100\n\n # Dette er tur retur distansen. For aa faa distansen en vei deler vi bare paa 2\n distance /= 2\n return distance\n\n\nclass ZumoButton():\n def __init__(self):\n wp.wiringPiSetupGpio()\n wp.pinMode(22, 0)\n wp.pullUpDnControl(22, 2)\n\n def wait_for_press(self):\n read_val = wp.digitalRead(22)\n while read_val:\n read_val = wp.digitalRead(22)\n print(\"Button pressed!!\")\n\n\nclass ReflectanceSensors():\n # The constructor allows students to decide if they want to auto_calibrate\n # the robot, or if they want to hard code the min and max readings of the\n # reflectance sensors\n def __init__(self, auto_calibrate=False, min_reading=100, max_reading=1000):\n self.setup()\n if (auto_calibrate):\n # Calibration loop should last ~5 seconds\n # Calibrates all sensors\n for i in range(5):\n self.calibrate()\n time.sleep(1)\n else:\n for i in range(len(self.max_val)):\n self.max_val[i] = max_reading\n self.min_val[i] = min_reading\n\n print(\"Calibration results\")\n print(self.max_val)\n print(self.min_val)\n\n def setup(self):\n # Initialize class variables\n self.max_val = [-1, -1, -1, -1, -1, -1]\n self.min_val = [-1, -1, -1, -1, -1, -1]\n self.start_time = -1\n # Initialize value array to all negative values, which should never appear\n # as an actual result\n self.value = [-1.0, -1.0, -1.0, -1.0, -1.0, -1.0]\n # A dictionary mapping each channel to the index it's value is located in\n # the value array\n self.sensor_indices = {29: 5, 36: 4, 37: 3, 31: 2, 32: 1, 33: 0}\n self.updated = False\n # For GPIO.BOARD\n self.sensor_inputs = [33, 32, 31, 37, 36, 29] # Sensors from left to right\n\n # Set the mode to GPIO.BOARD\n GPIO.setmode(GPIO.BOARD)\n\n def calibrate(self):\n print(\"calibrating...\")\n self.recharge_capacitors()\n\n # GPIO.setup(sensor_inputs, GPIO.IN)\n for pin in self.sensor_inputs:\n time = self.get_sensor_reading(pin)\n\n # Get the index from the map\n index = self.sensor_indices[pin]\n\n # This is the first iteration\n if (self.max_val[index] == -1):\n self.max_val[index] = time.microseconds\n self.min_val[index] = time.microseconds\n else:\n # Store the min and max values seen during calibration\n if (time.microseconds > self.max_val[index]):\n self.max_val[index] = time.microseconds\n elif (time.microseconds < self.min_val[index]):\n self.min_val[index] = time.microseconds\n\n # Print the calculated time in microseconds\n print(\"Pin: \" + str(pin))\n print(time.microseconds)\n\n def get_sensor_reading(self, pin):\n GPIO.setup(pin, GPIO.IN)\n # Measure the time\n start_time = datetime.datetime.now()\n\n while GPIO.input(pin):\n pass\n\n # Measure time again\n end_time = datetime.datetime.now()\n # Calculate the time passed\n time = end_time - start_time\n return time\n\n def recharge_capacitors(self):\n # Make all sensors an output, and set all to HIGH\n GPIO.setup(self.sensor_inputs, GPIO.OUT)\n GPIO.output(self.sensor_inputs, True)\n # Wait 5 milliseconds to ensure that the capacitor is fully charged\n time.sleep(0.005)\n\n def reset(self):\n self.updated = False\n self.value = [-1.0, -1.0, -1.0, -1.0, -1.0, -1.0]\n\n # Function should return a list of 6 reals between 0 and 1.0 indicating\n # the amount of reflectance picked up by each one. A high reflectance (near 1) indicates a LIGHT surface, while\n # a value near 0 indicates a DARK surface.\n\n def get_value(self):\n return self.value\n\n def update(self):\n self.compute_value()\n return self.value\n\n def compute_value(self):\n self.recharge_capacitors()\n for pin in self.sensor_inputs:\n time = self.get_sensor_reading(pin)\n\n index = self.sensor_indices[pin]\n self.value[index] = 1 - self.normalize(index, time.microseconds)\n\n # Uses the calibrated min and maxs for each sensor to return a normalized\n # value for the @param sensor_time for the given @param index\n def normalize(self, index, sensor_time):\n normalized_value = float(sensor_time) / (self.max_val[index] - self.min_val[index])\n if (normalized_value > 1.0):\n return 1.0\n elif (normalized_value < 0.0):\n return 0.0\n return normalized_value\n\n\nclass Camera:\n def __init__(self, img_width=128, img_height=96, img_rot=0):\n self.value = None\n self.img_width = img_width\n self.img_height = img_height\n self.img_rot = img_rot\n\n def get_value(self):\n return self.value\n\n def update(self):\n self.sensor_get_value()\n return self.value\n\n def reset(self):\n self.value = None\n\n def sensor_get_value(self):\n # This is a OS call that takes a image and makes it accessible to PIL operations in the same directory\n os.system('raspistill -t 1 -o image.png -w \"' + str(self.img_width) + '\" -h \"' + str(self.img_height) + '\" -rot \"' + str(self.img_rot) + '\"')\n # Open the image just taken by raspicam\n # Stores the RGB array in the value field\n self.value = Image.open('image.png').convert('RGB')\n\n# Just testing the camera in python\n# os.system('raspistill -t 1 -o image.png -w \"' + str(200) + '\" -h \"' + str(200) + '\" -rot \"' + str(0) + '\"')","sub_path":"basic_robot/sensors.py","file_name":"sensors.py","file_ext":"py","file_size_in_byte":9124,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"611301667","text":"import decimal\n\n\ndef drange(x, y, jump):\n while x < y:\n yield float(x)\n x += decimal.Decimal(jump)\n\n\ndef main():\n n = 10\n semilla = [0] * n\n matriz = generar_matriz_inicializada(n)\n f = [0] * n\n iteraciones_w = dict()\n tol = 0.01\n for w in drange(1, 2, '0.05'):\n x, cant_iter = SOR(matriz, semilla, f, w, tol)\n iteraciones_w[w] = cant_iter\n minimo = 1\n for (w, cant_iter) in iteraciones_w:\n if cant_iter < minimo:\n minimo = cant_iter\n w_optimo = w\n tol = 0.0001\n x, cant_iter = SOR(matriz, semilla, f, w_optimo, tol)\n\n\ndef matriz_ceros(n):\n matriz = []\n for i in range(n):\n vector_ceros = [0] * n\n matriz.append(vector_ceros)\n return matriz\n\n\ndef generar_matriz_inicializada(n):\n if n < 5:\n return 0\n matriz = matriz_ceros(n)\n matriz[0][0] = 1 # i = 0\n # i = 1:\n matriz[1][0] = -4\n matriz[1][1] = 5\n matriz[1][2] = -4\n matriz[1][3] = 1\n # i:\n k = 0\n for i in range(2, n - 2):\n vect = [1, -4, 6, -4, 1]\n for j in range(k, 5 + k):\n matriz[i][j] = vect.pop()\n k += 1\n matriz[n - 2] = matriz[1][::-1] # n-1\n matriz[n - 1][n - 1] = 1 # n\n\n\ndef SOR(A, x, b, w, tol):\n n = len(A)\n s = x.copy()\n cant_iteraciones = 0\n e = 1\n while (e > tol):\n xant = x.copy()\n for i in range(n):\n x[i] = s[i] * (1 - w) + w * GS(A[i], s, b[i], i, n)\n cant_iteraciones += 1\n s = x.copy()\n e = error(x, xant)\n return (x, cant_iteraciones)\n\n\ndef GS(coeficientes, semilla, b, i, n):\n suma = 0\n # der\n j = i + 1\n if j != n:\n while j < n & coeficientes[j] != 0:\n suma += coeficientes[j] * semilla[j] / coeficientes[i]\n j += 1\n # izq\n j = i - 1\n if j != -1:\n while j >= 0 & coeficientes[j] != 0:\n suma += coeficientes[j] * semilla[j] / coeficientes[i]\n j = j - 1\n return b / coeficientes[i] - suma\n\n\ndef error(x, xant):\n resultado = []\n for i in range(len(x)):\n resultado.append((x[i] - xant[i]))\n norma = max(resultado) / max(x)\n return norma\n\ngenerar_matriz_inicializada(10)\n","sub_path":"numerico.py","file_name":"numerico.py","file_ext":"py","file_size_in_byte":2206,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"250435158","text":"#!/usr/bin/env python2\n# $File: setup.py\n# $Author: Jiakai \n# $Date: Sat Dec 31 21:13:53 2011 +0800\n#\n# This file is part of orzoj\n# \n# Copyright (C) <2010> Jiakai \n# \n# Orzoj is free software: you can redistribute it and/or modify\n# it under the terms of the GNU General Public License as published by\n# the Free Software Foundation, either version 3 of the License, or\n# (at your option) any later version.\n# \n# Orzoj is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n# GNU General Public License for more details.\n# \n# You should have received a copy of the GNU General Public License\n# along with orzoj. If not, see .\n#\n\nfrom distutils.core import setup, Extension\nimport subprocess, platform\n\ncflags = None\nlibs = None\n\nif platform.system() == \"Linux\":\n cflags = [\"-Wall\", \"-DORZOJ_DEBUG\"]\n cflags.extend(subprocess.check_output([\"pkg-config\", \"--cflags\", \"openssl\"]).split())\n libs = subprocess.check_output([\"pkg-config\", \"--libs\", \"openssl\"]).split()\n\n\nmodule = Extension(\"orzoj._snc\", sources = [\"_snc.c\"], \n extra_compile_args = cflags,\n extra_link_args = libs)\n\nsetup(name = \"orzoj\", ext_modules = [module])\n\n","sub_path":"orzoj/lib/setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":1347,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"543914634","text":"from shared.logger_util import Logger\nfrom db.sqlalchemy_fulltext import FullTextSearch, FullTextMode\nfrom db.engine_factory import EngineFactory\n\n\nclass DBSearcher:\n RESULT_FORMAT_ONLY_ID = 2\n RESULT_FORMAT_ALL_INFO = 1\n ALL_RESULT = 0\n MAX_RESULT_NUM = 500\n\n def __init__(self, session=None, logger=None):\n self.__session = session\n if logger is None:\n self.logger = Logger(\"DBSearcher\").get_log()\n else:\n self.logger = logger\n\n def get_session(self):\n if not self.__session:\n # init the session from a factory instance,this factory is intit in the construction\n self.__session = EngineFactory.create_session(autocommit=True, echo=True)\n\n return self.__session\n\n def clean_session(self):\n self.__session = None\n\n def commit(self):\n self.__session.commit()\n self.__session.close()\n\n def full_text_search_in_nature_language(self, query, model_class, limit=ALL_RESULT,\n result_format=RESULT_FORMAT_ALL_INFO):\n if result_format == DBSearcher.RESULT_FORMAT_ALL_INFO:\n session_query = self.get_session().query(model_class)\n else:\n session_query = self.get_session().query(model_class.id)\n\n session_query = session_query.filter(FullTextSearch(query, model_class, FullTextMode.NATURAL))\n if limit == DBSearcher.ALL_RESULT:\n limit = DBSearcher.MAX_RESULT_NUM\n return session_query.limit(limit).all()\n\n\nclass WikiSearcher(DBSearcher):\n def search_wikipedia_text(self):\n try:\n statement = self.get_session().query()\n # print statement\n api_answer = statement.first()\n # print api_answer\n\n if api_answer is not None:\n return {\"api_name\": api_answer[0], \"api_id\": api_answer[1], \"kg_id\": None}\n else:\n return None\n except Exception as e:\n print(e)\n self.clean_session()\n return None\n","sub_path":"db/sqlalchemy_fulltext/search.py","file_name":"search.py","file_ext":"py","file_size_in_byte":2056,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"185703322","text":"import turtle\r\nimport sys\r\n\r\nSIZE = 600\r\nturn = 0\r\nXO = {0:'X', 1:'O'} \r\nmatrix = [[None for r in range(3)] for c in range(3)]\r\n\r\ngame_over = False\r\n\r\nSCREEN = turtle.Screen()\r\nSCREEN.title('TIC-TAC-TOE')\r\nSCREEN.bgcolor('black')\r\nSCREEN.setup(SIZE, SIZE)\r\nSCREEN.tracer(0)\r\n\r\npen = turtle.Turtle()\r\npen.color('white')\r\npen.width(10)\r\npen.up()\r\n\r\npen.goto(-SIZE/2, SIZE/6)\r\npen.down()\r\npen.forward(SIZE)\r\npen.up()\r\npen.goto(-SIZE/2, -SIZE/6)\r\npen.down()\r\npen.forward(SIZE)\r\npen.up()\r\npen.hideturtle()\r\n\r\npen.left(90)\r\npen.goto(-SIZE/6, -SIZE/2)\r\npen.down()\r\npen.forward(SIZE)\r\npen.up()\r\npen.goto(SIZE/6, -SIZE/2)\r\npen.down()\r\npen.forward(SIZE)\r\npen.up()\r\npen.right(90)\r\npen.hideturtle()\r\n\r\nwhile not game_over:\r\n\r\n SCREEN.update()\r\n\r\n def winning_turn():\r\n for r in range(3):\r\n if (matrix[r][0] != None) and (matrix[r][1] != None) and (matrix[r][2] != None): \r\n if (matrix[r][0] == matrix[r][1]) and (matrix[r][1] == matrix[r][2]):\r\n SCREEN.bye()\r\n for c in range(3):\r\n if (matrix[0][c] != None) and (matrix[1][c] != None) and (matrix[2][c] != None):\r\n if (matrix[0][c] == matrix[1][c]) and (matrix[1][c] == matrix[2][c]):\r\n SCREEN.bye()\r\n if (matrix[0][0] != None) and (matrix[1][1] != None) and (matrix[2][2] != None):\r\n if (matrix[0][0] == matrix[1][1]) and (matrix[1][1] == matrix[2][2]):\r\n SCREEN.bye()\r\n if (matrix[0][2] != None) and (matrix[1][1] != None) and (matrix[2][0] != None):\r\n if (matrix[0][2] == matrix[1][1]) and (matrix[1][1] == matrix[2][0]):\r\n SCREEN.bye()\r\n \r\n def draw_cross(x,y):\r\n pen.goto(x + SIZE/30, y + SIZE/30)\r\n pen.down()\r\n pen.goto(x + SIZE*0.3, y + SIZE*0.3)\r\n pen.up()\r\n pen.goto(x + SIZE/30, y + SIZE*0.3)\r\n pen.down()\r\n pen.goto(x + SIZE*0.3, y + SIZE/30)\r\n pen.up()\r\n winning_turn()\r\n\r\n def draw_circle(x,y):\r\n pen.goto(x + SIZE/6, y + SIZE/30)\r\n pen.down()\r\n pen.circle(SIZE/6 - SIZE/30)\r\n pen.up()\r\n winning_turn()\r\n\r\n def draw(x,y):\r\n \r\n global turn\r\n if ((x >= -SIZE/2) and (x <= -SIZE/6)):\r\n if ((y <= SIZE/2) and (y >= SIZE/6)):\r\n if (matrix[0][0] == None):\r\n matrix[0][0] = XO[turn]\r\n draw_cross(-SIZE/2, SIZE/6) if(XO[turn] == 'X') else draw_circle(-SIZE/2, SIZE/6)\r\n elif ((y <= SIZE/6) and (y >= -SIZE/6)):\r\n if (matrix[0][1] == None):\r\n matrix[0][1] = XO[turn]\r\n draw_cross(-SIZE/2, -SIZE/6) if(XO[turn] == 'X') else draw_circle(-SIZE/2, -SIZE/6)\r\n if ((y <= -SIZE/6) and (y >= -SIZE/2)):\r\n if (matrix[0][2] == None):\r\n matrix[0][2] = XO[turn]\r\n draw_cross(-SIZE/2, -SIZE/2) if(XO[turn] == 'X') else draw_circle(-SIZE/2, -SIZE/2)\r\n elif ((x >= -SIZE/6) and (x <= SIZE/6)):\r\n if ((y <= SIZE/2) and (y >= SIZE/6)):\r\n if (matrix[1][0] == None):\r\n matrix[1][0] = XO[turn]\r\n draw_cross(-SIZE/6, SIZE/6) if(XO[turn] == 'X') else draw_circle(-SIZE/6, SIZE/6)\r\n elif ((y <= SIZE/6) and (y >= -SIZE/6)):\r\n if (matrix[1][1] == None):\r\n matrix[1][1] = XO[turn]\r\n draw_cross(-SIZE/6, -SIZE/6) if(XO[turn] == 'X') else draw_circle(-SIZE/6, -SIZE/6)\r\n if ((y <= -SIZE/6) and (y >= -SIZE/2)):\r\n if (matrix[1][2] == None):\r\n matrix[1][2] = XO[turn]\r\n draw_cross(-SIZE/6, -SIZE/2) if(XO[turn] == 'X') else draw_circle(-SIZE/6, -SIZE/2)\r\n elif ((x >= SIZE/6) and (x <= SIZE/2)):\r\n if ((y <= SIZE/2) and (y >= SIZE/6)):\r\n if (matrix[2][0] == None):\r\n matrix[2][0] = XO[turn]\r\n draw_cross(SIZE/6, SIZE/6) if(XO[turn] == 'X') else draw_circle(SIZE/6, SIZE/6)\r\n elif ((y <= SIZE/6) and (y >= -SIZE/6)):\r\n if (matrix[2][1] == None):\r\n matrix[2][1] = XO[turn]\r\n draw_cross(SIZE/6, -SIZE/6) if(XO[turn] == 'X') else draw_circle(SIZE/6, -SIZE/6)\r\n if ((y <= -SIZE/6) and (y >= -SIZE/2)):\r\n if (matrix[2][2] == None):\r\n matrix[2][2] = XO[turn]\r\n draw_cross(SIZE/6, -SIZE/2) if(XO[turn] == 'X') else draw_circle(SIZE/6, -SIZE/2)\r\n \r\n turn += 1\r\n turn %= 2\r\n\r\n SCREEN.onscreenclick(draw)\r\n SCREEN.mainloop()\r\n","sub_path":"tic tac toe.py","file_name":"tic tac toe.py","file_ext":"py","file_size_in_byte":4649,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"18846079","text":"import sys\nimport io\nfrom google.cloud import vision\nsys.path.insert(1, '/Users/andrew/Documents/py_basic/util')\nimport timeutil\n\n\ndef detect_text(path):\n ocrtimer = timeutil.TimeElapsed()\n \"\"\"Detects text in the file.\"\"\"\n client = vision.ImageAnnotatorClient()\n\n with io.open(path, 'rb') as image_file:\n content = image_file.read()\n\n image = vision.types.Image(content=content)\n\n response = client.text_detection(image=image)\n texts = response.text_annotations\n print('Type(texts):', type(texts))\n # print('Texts:', texts)\n print('--------------------')\n\n print(\"\\nOCR elapsed: \", ocrtimer.getelapsed())\n print('\\nAll Data:')\n\n # ---- 전체 단어와 position을 나열한다\n count = 0\n for text in texts:\n newtext = text.description.replace('\\n', ' ')\n print('{:>2} Desc:[{:>10s}],'.format(count, newtext), end='')\n\n vertices = (['({},{})'.format(vertex.x, vertex.y) for vertex in text.bounding_poly.vertices])\n # print('\\n\\tvertices:', vertices, ' Type:', type(vertices))\n print('bounds: {}'.format(','.join(vertices)))\n\n count = count + 1\n\n # ---- 해당하는 단어의 position을 가져온다\n print('--------------------')\n for text in texts:\n if text.description == '당도':\n for vertex in text.bounding_poly.vertices:\n print ('Found....', vertex)\n\n\nif __name__ == '__main__':\n wholetimer = timeutil.TimeElapsed()\n detect_text('/Volumes/USB3-64/Image/10167389_1.jpg')\n print(\"\\n\\nTotal elapsed: \", wholetimer.getelapsed())","sub_path":"ssgtv/detectText.py","file_name":"detectText.py","file_ext":"py","file_size_in_byte":1579,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"646553779","text":"# -*- coding: utf-8 -*\n\n# author :lth\n# date : 2019-09-01\n# description:将 md 文件转为 pdf\n\nfrom pathlib import Path\nimport os\nimport pdfkit\nimport sys\nimport time\n\nhtml_template = \"\"\"\n \n \n \n \n \n \n{content} \n \n \n\"\"\"\n\ng_work_path = r'D:\\Users\\xxx\\Downloads\\renzhengfei-master' #所下载的 md 文件夹路径\ng_output_html_dir = '\\output_html'\ng_output_pdf_dir = '\\output_pdf'\n\n# md 文件转换 html\ndef convert_to_file_html(md_file_name):\n\tif md_file_name.endswith('.md'):\n\t\tpdf_file_name = md_file_name.replace('.md', '.html')\n\t\tpdf_file_name = pdf_file_name.replace(g_work_path, g_work_path + g_output_html_dir)\n\t\t\n\t\t#创建目录\n\t\ttmp_path = os.path.dirname(pdf_file_name)\n\t\tif not os.path.exists(tmp_path):\n\t\t\tos.makedirs(tmp_path)\n\t\t\n\t\tprint(\"1:\", pdf_file_name)\n\t\tcmd = \"pandoc \" + md_file_name + \" -o \" + pdf_file_name #我的微云盘上上有 pandoc 安装包\n\t\tos.system(cmd)\n\n# 将指定目录下所有 md 文件转换 html(包含子目录)\ndef convert_to_path_html(src_path):\n\tfor maindir, subdir_list, file_name_list in os.walk(src_path):\n\t\t# print(\"1:\",maindir) #当前主目录\n\t\t# print(\"2:\",subdir_list) #当前主目录下的所有目录\n\t\t# print(\"3:\",file_name_list) #当前主目录下的所有文件\n\t\tfor filename in file_name_list:\n\t\t\tmd_file_name = os.path.join(maindir, filename)#合并成一个完整路径\n\t\t\tconvert_to_file_html(md_file_name)\n\n\t\tfor subdir in subdir_list:\n\t\t\tconvert_to_path_html(subdir) #递归\n\n# html 文件转换 pdf\ndef convert_to_file_pdf(html_file_name):\n\tif html_file_name.endswith('.html'):\n\t\tpdf_file_name = html_file_name.replace('.html', '.pdf')\n\t\tpdf_file_name = pdf_file_name.replace(g_work_path + g_output_html_dir, g_work_path + g_output_pdf_dir)\n\t\t\n\t\t#创建目录\n\t\ttmp_path = os.path.dirname(pdf_file_name)\n\t\tif not os.path.exists(tmp_path):\n\t\t\tos.makedirs(tmp_path)\n\t\t\n\t\tprint(\"1:\", pdf_file_name)\n\t\tpath_wk = r'D:\\xxx\\wkhtmltopdf.exe' # wkhtmltopdf安装位置\n\t\tconfig = pdfkit.configuration(wkhtmltopdf = path_wk)\n\t\twith open(html_file_name, 'r', encoding='utf-8') as f:\n\t\t\thtml = f.read()\n\t\t\thtml = html_template.format(content=html) \n\t\t\tpdfkit.from_string(html, pdf_file_name, configuration=config)\n\t\t\ttime.sleep(0.05)\n\n# 将指定目录下的所有 html 文件转换 pdf(包含子目录)\ndef convert_to_path_pdf(src_path):\n\tprint(src_path)\n\tfor maindir, subdir_list, file_name_list in os.walk(src_path):\n\t\tfor filename in file_name_list:\n\t\t\thtml_file_name = os.path.join(maindir, filename)#合并成一个完整路径\n\t\t\tconvert_to_file_pdf(html_file_name)\n\n\t\tfor subdir in subdir_list:\n\t\t\tconvert_to_path_pdf(subdir) #递归\n\t\t\t\t\t\ndef main():\n\tconvert_to_path_html(g_work_path)\n\tconvert_to_path_pdf(g_work_path + g_output_html_dir)\n\t\t\n\nif __name__ == '__main__':\n\tmain()\n\t\n\t\t\n\t\t\n\t\t\n\t","sub_path":"convert_md_to_pdf.py","file_name":"convert_md_to_pdf.py","file_ext":"py","file_size_in_byte":2878,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"76051924","text":"import numpy as np\n\nfrom mygrad import Tensor\nfrom mygrad.operation_base import Operation\n\n__all__ = ['selu']\n\nclass SELU(Operation):\n ''' Returns the scaled exponential linear activation (SELU) elementwise along x. The SELU is\n given by λɑ(exp(x) - 1) for x < 0 and λx for x ≥ 0.\n\n Notes\n -----\n The SELU activation was proposed in the paper\n Self-Normalizing Neural Networks\n Günter Klambauer, Thomas Unterthiner, Andreas Mayr, Sepp Hochreiter\n at https://arxiv.org/abs/1706.02515\n '''\n def __call__(self, x):\n '''\n Parameters\n ----------\n x : mygrad.Tensor\n Input data.\n\n Returns\n -------\n numpy.ndarray\n The SELU function applied to `x` elementwise.\n '''\n self.variables = (x,)\n\n x = x.data\n self.alpha = 1.6732632423543772848170429916717\n self.scale = 1.0507009873554804934193349852946\n self.exp = self.alpha * (np.exp(x) - 1)\n return self.scale * np.where(x < 0, self.exp, x)\n\n def backward_var(self, grad, index, **kwargs):\n x = self.variables[index]\n x.backward(grad * self.scale * np.where(x.data < 0, self.exp + self.alpha, 1), **kwargs)\n\ndef selu(x):\n ''' Returns the scaled exponential linear activation (SELU) elementwise along x. The SELU is\n given by λɑ(exp(x) - 1) for x < 0 and λx for x ≥ 0.\n\n Parameters\n ----------\n x : mygrad.Tensor\n Input data.\n\n Returns\n -------\n mygrad.Tensor\n The SELU function applied to `x` elementwise.\n\n Notes\n -----\n The SELU activation was proposed in the paper\n Self-Normalizing Neural Networks\n Günter Klambauer, Thomas Unterthiner, Andreas Mayr, Sepp Hochreiter\n at https://arxiv.org/abs/1706.02515\n '''\n return Tensor._op(SELU, x)\n","sub_path":"mynn/activations/selu.py","file_name":"selu.py","file_ext":"py","file_size_in_byte":1841,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"178037222","text":"import torch\nimport torch.nn as nn\nimport torch.nn.functional as F\n\"\"\"\n[Effective Approaches to Attention-based Neural Machine Translation by Luong et al.](https://arxiv.org/pdf/1508.04025.pdf) describe a few more attention models that offer improvements and simplifications. They describe a few \"global attention\" models, the distinction between them being the way the attention scores are calculated.\n\nThe general form of the attention calculation relies on the target (decoder) side hidden state and corresponding source (encoder) side state, normalized over all states to get values summing to 1.\n\nThe specific \"score\" function that compares two states is either ; ; or \n\nThe modular definition of these scoring functions gives us an opportunity to build specific attention module that can switch between the different score methods. The input to this module is always the hidden state (of the decoder RNN) and set of encoder outputs.\n\n\"\"\"\nclass Attn(nn.Module):\n def __init__(self, method, hidden_size):\n super(Attn, self).__init__()\n \n self.method = method\n self.hidden_size = hidden_size\n \n self.cat = nn.Linear(hidden_size * 2, hidden_size)\n \n if self.method == 'general':\n self.score = self.score_general\n self.attn = nn.Linear(self.hidden_size, hidden_size)\n\n elif self.method == 'concat':\n self.score = self.score_concat\n self.attn = nn.Linear(self.hidden_size * 2, hidden_size)\n self.v = nn.Parameter(torch.FloatTensor(1, hidden_size))\n \n elif self.method == \"dot\":\n self.score = self.score_dot\n\n def forward(self, hidden, encoder_outputs):\n # given...\n # input_len -> 6\n # target_len -> 7\n \n # then...\n # hidden -> (target_len) 7 x 256\n # enc_outs -> (input_len) 6 x 256\n \n # 7 x 256 @ 256 x 6 -> 7 x 6\n attn_weights = self.score(hidden , encoder_outputs)\n attn_weights = F.log_softmax(attn_weights, dim = 1)\n\n # 256 x 6 @ 6 x 7 -> 256 x 7 (or 7 x 256)\n context = encoder_outputs.transpose(1,2) @ attn_weights.transpose(1,2)\n attn = torch.cat([hidden, context.transpose(1,2)], dim = -1).squeeze(1)\n return attn, attn_weights\n \n # \"dot, a simple dot product between the states\"\n def score_dot(self, hidden, enc_out):\n return hidden @ enc_out.transpose(1,2)\n \n # \"general, a dot product between the decoder hidden state and a linear transform of the encoder state\"\n def score_general(self, hidden, enc_out):\n return hidden @ self.attn(enc_out).transpose(1,2)\n \n # \"concat, a dot product between a new parameter $v_a$ and a linear transform of the states concatenated together\"\n def score_concat(self, hidden, enc_out):\n catted = torch.cat((hidden, enc_out), 1)\n catted_transf = self.attn(catted)\n return self.v @ catted_transf","sub_path":"models/attn.py","file_name":"attn.py","file_ext":"py","file_size_in_byte":3050,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"439065973","text":"import os\nimport pandas as pd\nimport numpy as np\nfrom hydroDL import kPath\n\n# fileName = r'C:\\Users\\geofk\\work\\waterQuality\\USGS\\dailyTS\\08075400'\n\n__all__ = ['readSample', 'readStreamflow', 'readUsgsText', 'removeFlag']\n\n\ndef readSample(siteNo, codeLst, startDate=None, csv=True, flag=0):\n \"\"\"read USGS sample data, did:\n 1. extract data of interested code and date\n 2. average repeated daily observation\n Arguments:\n siteNo {str} -- site number\n Keyword Arguments:\n codeLst {list} -- usgs code of interesting fields (default: {sampleCodeLst})\n startDate {date} -- start date (default: {None})\n flag {int} -- 0 no flag; 1 str flag; 2 num flag \n Returns:\n pandas.DataFrame -- [description]\n \"\"\"\n if csv is False:\n fileC = os.path.join(kPath.dirData, 'USGS', 'sample', siteNo)\n dfC = readUsgsText(fileC, dataType='sample')\n if startDate is not None:\n dfC = dfC[dfC['date'] >= startDate]\n dfC = dfC.set_index('date')\n codeSel = list(set(codeLst) & set(dfC.columns.tolist()))\n codeSel_cd = [code + '_cd' for code in codeSel]\n dfC = dfC[codeSel+codeSel_cd].dropna(how='all')\n if len(dfC) == 0:\n return None if flag == 0 else (None, None)\n dfC1 = dfC[codeSel]\n dfC2 = dfC[codeSel_cd]\n bx = dfC1.notna().values & dfC2.isna().values\n dfC2[bx] = 'x'\n dfC2 = dfC2.fillna('')\n bDup = dfC.index.duplicated(keep=False)\n indUni = dfC.index[~bDup]\n indDup = dfC.index[bDup].unique()\n indAll = dfC.index.unique()\n dfO1 = pd.DataFrame(index=indAll, columns=codeSel)\n dfO2 = pd.DataFrame(index=indAll, columns=codeSel_cd)\n dfO1.loc[indUni] = dfC1.loc[indUni][codeSel]\n dfO2.loc[indUni] = dfC2.loc[indUni][codeSel_cd]\n for ind in indDup:\n temp1 = dfC1.loc[ind]\n temp2 = dfC2.loc[ind]\n for code in codeSel:\n if 'x' in temp2[code+'_cd'].tolist():\n dfO1.loc[ind][code] = temp1[code][temp2[code+'_cd']\n == 'x'].mean()\n if temp2[code+'_cd'].tolist().count('x') > 1:\n dfO2.loc[ind][code+'_cd'] = 'X'\n else:\n dfO2.loc[ind][code+'_cd'] = 'x'\n else:\n dfO1.loc[ind][code] = temp1[code].mean()\n dfO2.loc[ind][code+'_cd'] = ''.join(temp2[code+'_cd'])\n else:\n dirC = os.path.join(kPath.dirData, 'USGS', 'sample', 'csv')\n fileC1 = os.path.join(dirC, siteNo)\n if not os.path.exists(fileC1):\n return None if flag == 0 else (None, None)\n dfO1 = pd.read_csv(fileC1)\n dfO1['date'] = pd.to_datetime(dfO1['date'], format='%Y-%m-%d')\n dfO1 = dfO1.set_index('date')\n if flag > 0:\n fileC2 = os.path.join(dirC, siteNo+'_flag')\n dfO2 = pd.read_csv(fileC2)\n dfO2['date'] = pd.to_datetime(dfO2['date'], format='%Y-%m-%d')\n dfO2 = dfO2.set_index('date')\n if startDate is not None:\n dfO1 = dfO1[dfO1.index >= startDate]\n if flag > 0:\n dfO2 = dfO2[dfO2.index >= startDate]\n if flag > 0:\n if flag == 2:\n dfO3 = pd.DataFrame(\n index=dfO2.index, columns=dfO2.columns, dtype=int)\n dfO3[(dfO2 == 'x') | (dfO2 == 'X')] = 0\n dfO3[(dfO2 != 'x') & (dfO2 != 'X') & (dfO2.notna())] = 1\n dfO2 = dfO3\n codeLst_cd = [code + '_cd' for code in codeLst]\n return (dfO1.reindex(columns=codeLst), dfO2.reindex(columns=codeLst_cd))\n else:\n return dfO1.reindex(columns=codeLst)\n\n\ndef readStreamflow(siteNo, startDate=None, csv=True):\n \"\"\"read USGS streamflow (00060) data, did:\n 1. fill missing average observation (00060_00003) by available max and min.\n Arguments:\n siteNo {str} -- site number\n Keyword Arguments:\n startDate {date} -- start date (default: {None})\n Returns:\n pandas.DataFrame -- [description]\n \"\"\"\n if csv is False:\n fileQ = os.path.join(kPath.dirData, 'USGS', 'streamflow', siteNo)\n dfQ = readUsgsText(fileQ, dataType='streamflow')\n if dfQ is None:\n return None\n if startDate is not None:\n dfQ = dfQ[dfQ['date'] >= startDate]\n if '00060_00001' in dfQ.columns and '00060_00002' in dfQ.columns:\n # fill nan using other two fields\n avgQ = dfQ[['00060_00001', '00060_00002']].mean(\n axis=1, skipna=False)\n dfQ['00060_00003'] = dfQ['00060_00003'].fillna(avgQ)\n dfQ = dfQ[['date', '00060_00003']]\n else:\n dfQ = dfQ[['date', '00060_00003']]\n else:\n fileQ = os.path.join(kPath.dirData, 'USGS',\n 'streamflow', 'csv', siteNo)\n dfQ = pd.read_csv(fileQ)\n dfQ['date'] = pd.to_datetime(dfQ['date'], format='%Y-%m-%d')\n if startDate is not None:\n dfQ = dfQ[dfQ['date'] >= startDate]\n return dfQ.set_index('date')\n\n\ndef readUsgsText(fileName, dataType=None):\n \"\"\"read usgs text file, rename head for given dataType\n Arguments:\n fileName {str} -- file name\n Keyword Arguments:\n dataType {str} -- dailyTS, streamflow or sample (default: {None})\n \"\"\"\n with open(fileName) as f:\n k = 0\n line = f.readline()\n while line[0] == \"#\":\n line = f.readline()\n k = k + 1\n headLst = line[:-1].split('\\t')\n typeLst = f.readline()[:-1].split('\\t')\n if k == 0:\n return None\n\n pdf = pd.read_table(fileName, header=k, dtype=str).drop(0)\n for i, x in enumerate(typeLst):\n if x[-1] == 'n':\n pdf[headLst[i]] = pd.to_numeric(pdf[headLst[i]], errors='coerce')\n if x[-1] == 'd':\n pdf[headLst[i]] = pd.to_datetime(pdf[headLst[i]], errors='coerce')\n # modify - only rename head or add columns, will not modify values\n if dataType == 'dailyTS':\n out = renameDailyTS(pdf)\n elif dataType == 'sample':\n out = renameSample(pdf)\n elif dataType == 'streamflow':\n out = renameStreamflow(pdf)\n else:\n out = pdf\n return out\n\n\ndef renameDailyTS(pdf):\n # rename observation fields\n headLst = pdf.columns.tolist()\n for i, head in enumerate(headLst):\n temp = head.split('_')\n if temp[0].isdigit():\n if len(temp) == 3:\n headLst[i] = temp[1] + '_' + temp[2]\n pdf[head] = pdf[head].astype(np.float)\n else:\n headLst[i] = temp[1] + '_' + temp[2] + '_cd'\n pdf.columns = headLst\n # time field\n pdf['date'] = pd.to_datetime(pdf['datetime'], format='%Y-%m-%d')\n return pdf\n\n\ndef renameStreamflow(pdf):\n # pick the longest average Q field\n headLst = pdf.columns.tolist()\n tempS = [head.split('_') for head in headLst if head[-1].isdigit()]\n codeLst = list(set([int(s[0])-int(s[2]) for s in tempS]))\n tempN = list()\n for code in codeLst:\n for k in range(3):\n head = '{}_00060_{:05n}'.format(code+k+1, k+1)\n if head not in headLst:\n pdf[head] = np.nan\n pdf[head+'_cd'] = 'N'\n tempLst = ['{}_00060_{:05n}'.format(code+k+1, k+1) for k in range(3)]\n temp = ((~pdf[tempLst[0]].isna()) & (~pdf[tempLst[1]].isna())) | (\n ~pdf[tempLst[2]].isna())\n tempN.append(temp.sum())\n code = codeLst[tempN.index(max(tempN))]\n # (searched and no code of leading zero)\n pdf = pdf.rename(columns={'{}_00060_{:05n}'.format(\n code+x+1, x+1): '00060_{:05n}'.format(x+1) for x in range(3)})\n pdf = pdf.rename(columns={'{}_00060_{:05n}_cd'.format(\n code+x+1, x+1): '00060_{:05n}_cd'.format(x+1) for x in range(3)})\n\n # time field\n pdf['date'] = pd.to_datetime(pdf['datetime'], format='%Y-%m-%d')\n return pdf\n\n\ndef renameSample(pdf):\n # rename observation fields\n headLst = pdf.columns.tolist()\n for i, head in enumerate(headLst):\n if head[1:].isdigit():\n if head.startswith('p'):\n headLst[i] = head[1:]\n pdf[head] = pdf[head].astype(np.float)\n else:\n headLst[i] = head[1:] + '_cd'\n pdf.columns = headLst\n # time field - not work for nan time, use date for current\n # temp = pdf['sample_dt'] + ' ' + pdf['sample_tm']\n # pdf['datetime'] = pd.to_datetime(temp, format='%Y-%m-%d %H:%M')\n pdf['date'] = pd.to_datetime(pdf['sample_dt'], format='%Y-%m-%d')\n return pdf\n\n\ndef removeFlag(dfC, dfCF):\n codeLstF = dfCF.columns.tolist()\n codeLst = [code[:5] for code in codeLstF]\n dfOut = dfC.copy()\n data = dfC[codeLst].values\n dataF = dfCF[codeLstF].values\n data[dataF == 1] = np.nan\n dfOut[codeLst] = data\n return dfOut\n","sub_path":"hydroDL/data/usgs/read.py","file_name":"read.py","file_ext":"py","file_size_in_byte":8904,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"644063350","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: /home/ykent/GitLab/pygrisb/pygrisb/pygrisb/io/h5io.py\n# Compiled at: 2019-02-22 23:25:01\n# Size of source mod 2**32: 2334 bytes\nfrom scipy.sparse import csr_matrix, coo_matrix\n\ndef h5auto_read(f, path, default=None):\n if path in f:\n return f[path][()]\n return default\n\n\ndef h5auto_write(f, path, data):\n if path in f:\n del f[path]\n f[path] = data\n\n\ndef get_csr_matrix(f, path):\n \"\"\"\n Read the csr_matrix located at path in the hdf5 file f.\n \"\"\"\n nrow = f[(path + '/nrow')][0]\n ncol = f[(path + '/ncol')][0]\n data = f[(path + '/data')][()]\n base = f[(path + '/base')][0]\n indices = f[(path + '/indices')][()] - base\n indptr = f[(path + '/indptr')][()] - base\n return csr_matrix((data, indices, indptr), shape=(nrow, ncol))\n\n\ndef get_coo_matrix(f, path):\n \"\"\"\n Read the coo_matrix located at path in the hdf5 file f.\n \"\"\"\n nrow = f[(path + '/nrow')][0]\n ncol = f[(path + '/ncol')][0]\n data = f[(path + '/data')][()]\n base = f[(path + '/base')][0]\n indi = f[(path + '/i')][()] - base\n indj = f[(path + '/j')][()] - base\n return coo_matrix((data, (indi, indj)), shape=(nrow, ncol))\n\n\ndef write_csr_matrix(f, path, a):\n \"\"\"\n Read the csr_matrix located at path in the hdf5 file f.\n \"\"\"\n if path in f:\n del path\n f[path + '/nrow'] = [\n a.shape[0]]\n f[path + '/ncol'] = [a.shape[1]]\n f[path + '/data'] = a.data\n f[path + '/base'] = [0]\n f[path + '/indices'] = a.indices\n f[path + '/indptr'] = a.indptr\n\n\ndef write_coo_matrix(f, path, a):\n \"\"\"\n Write the coo_matrix located at path in the hdf5 file f.\n \"\"\"\n f[path + '/nrow'] = [\n a.shape[0]]\n f[path + '/ncol'] = [a.shape[1]]\n f[path + '/nnz'] = [a.nnz]\n f[path + '/data'] = a.data\n f[path + '/base'] = [0]\n f[path + '/i'] = a.row\n f[path + '/j'] = a.col\n\n\ndef get_hs_rotations(f, imp, valences):\n \"\"\"\n Get rotation representations in Hilbert space.\n \"\"\"\n Rpr_list = []\n for val in valences:\n Rpr_list.append([])\n dim_rot = f['Impurity_{}/val_block={}/dim_rotations'.format(imp, val)][()]\n for i in range(dim_rot):\n Rpr_list[(-1)].append(get_csr_matrix(f, '/Impurity_{}/val_block={}/rotation_{}'.format(imp, val, i)))\n\n return Rpr_list\n\n\nif __name__ == '__main__':\n pass","sub_path":"pycfiles/pygrisb-2019.3.18.1.tar/h5io.cpython-37.py","file_name":"h5io.cpython-37.py","file_ext":"py","file_size_in_byte":2485,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"200730740","text":"import uuid\nimport datetime\n\nimport pytest\n\nfrom fire.api import FireDb\nfrom fire.api.model import (\n Sag,\n Sagsevent,\n Sagsinfo,\n Koordinat,\n Punkt,\n Observation,\n Beregning,\n Point,\n Geometry,\n ObservationType,\n)\n\n\ndef test_observation(firedb: FireDb, observation: Observation):\n firedb.session.commit()\n o1 = firedb.session.query(Observation).get(observation.objectid)\n assert o1.objectid == observation.objectid\n\n\ndef test_hent_observationer(firedb: FireDb, observationer):\n firedb.session.commit()\n id1 = observationer[0].objectid\n id2 = observationer[1].objectid\n os = firedb.hent_observationer((id1, id2))\n assert len(os) is 2\n os = firedb.hent_observationer((-999, -998))\n assert len(os) is 0\n\n\n@pytest.mark.skip(\"Undlades indtil et bedre test datasæt er indlæst i databasen\")\ndef test_hent_observationer_naer_opstillingspunkt(firedb: FireDb):\n p = firedb.hent_punkt(\"814E9044-1AAB-5A4E-E053-1A041EACF9E4\")\n os = firedb.hent_observationer_naer_opstillingspunkt(p, 100)\n assert len(os) is 32\n os = firedb.hent_observationer_naer_opstillingspunkt(\n p, 100, datetime.datetime(2015, 10, 8)\n )\n assert len(os) is 12\n os = firedb.hent_observationer_naer_opstillingspunkt(\n p, 100, datetime.datetime(2016, 11, 1)\n )\n assert len(os) is 6\n os = firedb.hent_observationer_naer_opstillingspunkt(p, 1000)\n assert len(os) is 34\n os = firedb.hent_observationer_naer_opstillingspunkt(\n p, 1000, datetime.datetime(2015, 10, 8)\n )\n assert len(os) is 12\n os = firedb.hent_observationer_naer_opstillingspunkt(\n p, 1000, datetime.datetime(2015, 10, 8), datetime.datetime(2016, 10, 9)\n )\n assert len(os) is 6\n\n\n@pytest.mark.skip(\"Undlades indtil et bedre test datasæt er indlæst i databasen\")\ndef test_hent_observationer_naer_geometri(firedb: FireDb):\n go = firedb.hent_geometri_objekt(\"814E9044-1AAB-5A4E-E053-1A041EACF9E4\")\n os = firedb.hent_observationer_naer_geometri(go.geometri, 10000)\n assert len(os) is 46\n point = Geometry(\"POINT (10.4811749340072 56.3061226484564)\")\n os = firedb.hent_observationer_naer_geometri(point, 100)\n assert len(os) is 2\n polygon = Geometry(\n \"POLYGON ((10.4811749340072 56.3061226484564, 10.5811749340072 56.3061226484564, 10.5811749340072 56.4061226484564, 10.4811749340072 56.4061226484564, 10.4811749340072 56.3061226484564))\"\n )\n os = firedb.hent_observationer_naer_geometri(polygon, 100)\n assert len(os) is 6\n\n\ndef test_indset_observation(firedb: FireDb, sag: Sag, punkt: Punkt):\n obstype = firedb.session.query(ObservationType).first()\n observation = Observation(\n antal=0,\n observationstype=obstype,\n observationstidspunkt=datetime.datetime.utcnow(),\n opstillingspunkt=punkt,\n value1=0,\n value2=0,\n value3=0,\n value4=0,\n value5=0,\n value6=0,\n value7=0,\n value8=0,\n )\n firedb.indset_observation(Sagsevent(sag=sag), observation)\n","sub_path":"test/test_observation.py","file_name":"test_observation.py","file_ext":"py","file_size_in_byte":3033,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"41509643","text":"from util import *\nimport Runnables\nfrom Runnables.Runnable import Runnable\n\nclass FlightSearchMenu(Runnable):\n \"\"\"\n UATravel FlightSearchMenu\n\n Description:\n Provides users with the ability to seach for one-way trips\n as well as round trips. Users are given the option whether \n they would like to search for flights with 2 or 3 connections.\n\n Expects:\n \"db\": Database object\n \"user\" Authenticated User\n\n update returns:\n True: Keep menu running\n (1, None, {}): User selected return\n \"\"\"\n def __init__(self, params={}):\n self._commands = {\"1\": self.search_direct_flights, \"2\": self.search_round_trips,\n \"3\": self.exit}\n self._db = params[\"db\"]\n self._user = params[\"user\"]\n # self.list_bookings()\n\n def update(self):\n print(\"-----------------\\n\" + \\\n \"Options:\\n\" + \\\n \"1. Search One-Way Trips\\n\" + \\\n \"2. Search Round Trips\\n\" + \\\n \"3. Return\")\n\n user_input = input(\"\").strip();\n \n if user_input in self._commands.keys():\n return self._commands[user_input]()\n else:\n print(\"The input \" + \"'\" + user_input + \"'\" + \" is not recognized.\")\n\n return True\n \n def search_direct_flights(self):\n src = self.get_airport_code(\"Enter source airport code or name: \")\n dst = self.get_airport_code(\"Enter destination airport code or name: \")\n dep_date = None\n while not dep_date:\n dep_date = get_date(\"Enter departure date in the form DD/Mon/YYYY: \")\n\n max_stops = 1\n\n max_stops1 = re.search(r\"(1|2)\", input(\"Would you like to search for flights with\\n1. Flights with at most 2 connections\\n2. Flights with up to 3 connections\\n\"))\n if max_stops1:\n if max_stops1.group(1) == 2:\n max_stops = 2\n\n while True:\n order_by = re.search(r\"(1|2)\",input(\"Would you like to order by \\n1. Price \\n2. Number of connections\\n\"))\n if order_by:\n order_by = int(order_by.group(1))\n break\n else:\n print(\"Invalid input: please enter 1 or 2\")\n\n result = self.search_flights(src, dst, dep_date, max_stops, order_by)\n\n if result:\n print(\"Options:\\n\" + \\\n \"1. Book a flight\\n\" + \\\n \"2. Return\")\n if input() == \"1\":\n rownum = -1\n while rownum < 0 or rownum >= len(result):\n try:\n rownum = int(input(\"Please select row number from the flights list: \")) - 1\n except TypeError as exc:\n pass\n\n self.book_trip([(result[rownum][1], result[rownum][4], result[rownum][16]),\n (result[rownum][2], result[rownum][5], result[rownum][18]),\n (result[rownum][3], result[rownum][6], result[rownum][20])], result[rownum][14])\n else:\n print(\"Sorry! No flights matched your search.\")\n\n return True \n\n def search_round_trips(self):\n src = self.get_airport_code(\"Enter source airport code or name: \")\n dst = self.get_airport_code(\"Enter destination airport code or name: \")\n dep_date = None\n while not dep_date:\n dep_date = get_date(\"Enter departure date in the form DD/Mon/YYYY: \")\n return_date = None\n while not return_date:\n return_date = get_date(\"Enter return date in the form DD/Mon/YYYY: \")\n \n max_stops = 1\n\n max_stops1 = re.search(r\"(1|2)\", input(\"Would you like to search for flights with\\n1. Flights with at most 2 connections\\n2. Flights with up to 3 connections\\n\"))\n if max_stops1:\n if max_stops1.group(1) == 2:\n max_stops = 2\n\n while True:\n order_by = re.search(r\"(1|2)\",input(\"Would you like to order by \\n1. Price \\n2. Number of connections\\n\"))\n if order_by:\n order_by = int(order_by.group(1))\n break\n else:\n print(\"Invalid input: please enter 1 or 2\")\n\n print(\"Flights on the departure date:\\n----------------\")\n to_result = self.search_flights(src, dst, dep_date, max_stops, order_by)\n if not to_result:\n print(\"No flights could be found on the departing date!\\n\")\n\n print(\"Flights on return date:\\n----------------\")\n return_result = self.search_flights(dst, src, return_date, max_stops, order_by)\n if not return_result:\n print(\"No flights could be found on the returning date!\\n\")\n\n if to_result and return_result:\n print(\"Options:\\n\" + \\\n \"1. Book a flight\\n\" + \\\n \"2. Return\")\n if input() == \"1\":\n rownum1, rownum2 = -1, -1\n while rownum1 < 0 or rownum1 >= len(to_result):\n try:\n rownum1 = int(input(\"Please select row number from the departing list: \")) - 1\n except TypeError as exc:\n pass\n while rownum2 < 0 or rownum2 >= len(return_result):\n try:\n rownum2 = int(input(\"Please select row number from the returning list: \")) - 1\n except TypeError as exc:\n pass\n\n self.book_trip([(to_result[rownum1][1], to_result[rownum1][4], to_result[rownum1][16]),\n (to_result[rownum1][2], to_result[rownum1][5], to_result[rownum1][18]),\n (to_result[rownum1][3], to_result[rownum1][6], to_result[rownum1][20]),\n (return_result[rownum2][1], return_result[rownum2][4], return_result[rownum2][16]),\n (return_result[rownum2][2], return_result[rownum2][5], return_result[rownum2][18]),\n (return_result[rownum2][3], return_result[rownum2][6], return_result[rownum2][20])], \n float(to_result[rownum1][14]) + float(return_result[rownum2][14]))\n else:\n print(\"Sorry! No flights matched your search.\")\n\n return True\n\n def search_flights(self, src, dst, dep_date, max_stops, order_by, display_results=True):\n sql_path = \"sql/flight_select_c3\"\n\n if order_by == \"1\":\n sql_path += \".sql\"\n else:\n sql_path += \"_by_connections.sql\"\n\n with open(sql_path) as f:\n query = f.read().format(src, dst, max_stops, dep_date)\n result = self._db.execute(query)\n\n if result and display_results:\n print_table([\"Row #\", \"Flight No. 1\", \"Flight No. 2\", \"Flight No. 3\", \"Source\", \"Destination\", \"Departure Date\", \"Arrival Date\",\n \"Stops\", \"Layover 1\", \"Layover 2\", \"Price\", \"Seats 1\", \"Seats 2\", \"Seats 3\"], \\\n [6, 12, 12, 12, 10, 11, 20, 20, 10, 10, 10, 10, 10, 10, 10], \\\n result, \\\n [0, 1, 2, 3, 7, 8, 9, 10, 11, 12, 13, 14, 15, 17, 19])\n return result\n\n def book_trip(self, flights, price):\n user = self._user\n user_exists = self._db.execute(\"select * from passengers where LOWER(email) = '{}'\".format(user).lower())\n if not user_exists:\n user_values = self._db.execute(\"select * from users where LOWER(email) = '{}'\".format(user).lower())\n name = input(\"Please provide your name: \").strip()\n country = input(\"Please enter your country of residence: \").strip()\n\n self._db.update(\"insert into passengers (email, name, country) values ('{}', '{}', '{}')\"\\\n .format(user_values[0][0].strip(), name, country))\n else:\n name = user_exists[0][1]\n\n for flight in flights:\n if flight[0]:\n if not self._db.execute(\"select * from available_flights where flightno = '{}' and dep_date=to_date('{}','YYYY-MM-DD HH24:MI:SS') and fare='{}'\"\\\n .format(flight[0], str(flight[1]), flight[2])):\n print(\"Sorry! That Flight no. {} longer has any available seats!\".format(flight[0]))\n return True\n\n print(\"Generating ticket...\")\n tno = tno_gen([i[0] for i in self._db.execute(\"select tno from tickets\")])\n self._db.update(\"insert into tickets (tno, name, email, paid_price) values ({},'{}','{}', '{}')\"\\\n .format(tno, name.strip(), self._user.strip(), price))\n\n print(\"Finding seats...\")\n for flight in flights:\n if flight[0]:\n seat_no = seat_gen([i[0] for i in self._db.execute(\"select seat from bookings where flightno = '{}' and dep_date=to_date('{}','YYYY-MM-DD HH24:MI:SS') and fare='{}'\"\\\n .format(flight[0], str(flight[1])[:-3], flight[2]))])\n self._db.update(\"insert into bookings (tno, flightno, fare, dep_date, seat) values ({},'{}','{}',to_date('{}','YYYY-MM-DD'),'{}')\"\\\n .format(tno, flight[0].strip(), flight[2], str(flight[1])[:-9], seat_no))\n\n print(\"Booking Successful! Your ticket number is {}\".format(tno))\n\n return True\n\n def get_airport_code(self, prompt=\"\"):\n if prompt == \"\":\n prompt = \"Enter airport code or name: \"\n\n while True:\n acode = input(prompt).strip().lower()\n\n query_acode = \"Select acode from airports where lower(acode) = '{}'\".format(acode)\n acodes = self._db.execute(query_acode)\n if len(acodes) < 2 and len(acodes) > 0:\n acode = re.search((\"[A-Z]+\"), str(acodes)).group(0)\n break\n\n else:\n query_src = \"select * from airports where lower(name) LIKE '%{}%'\".format(acode)\n sources = self._db.execute(query_src)\n print(\"\\nPlease enter a 3 letter code from the list above\")\n for row in sources:\n print(\"Code: \" + row[0] + \" Name: \" + row[1])\n\n return acode\n\n def exit(self):\n return (1, None, {})\n\nRunnables.runnable_types[\"FlightSearchMenu\"] = FlightSearchMenu","sub_path":"Runnables/FlightSearchMenu.py","file_name":"FlightSearchMenu.py","file_ext":"py","file_size_in_byte":10247,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"548889709","text":"from django.urls import path\nfrom . import views\n\nurlpatterns = [\n path('communityhome/', views.PostView, name = 'communityhome'),\n path('newpost/',views.PostCreate, name='newpost'),\n path('addpost/',views.AddPost, name='addpost'),\n path('like/', views.like_post, name = 'like'),\n path('dislike/', views.dislike_post, name = 'dislike'),\n path('comment/', views.CommentPost, name = 'comment'),\n path('search', views.search, name = 'search'),\n path('filter/', views.filterpost, name = 'filter'),\n path('sort/', views.sortpost, name = 'sort')\n]\n","sub_path":"community/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":621,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"135433044","text":"\nimport pandas as pd\ncleanTweet = pd.read_pickle('./pickles/data_clean.pkl')\n\nx = list(cleanTweet.polarity)\ny = list(cleanTweet.subjectivity)\n\ndata = {\n \"sentiment_plot_X\": x,\n \"sentiment_plot_Y\": y\n}\n\ndata_two = [1, 2, 3, 4]\n","sub_path":"dashboard.py","file_name":"dashboard.py","file_ext":"py","file_size_in_byte":232,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"210682340","text":"from PyQt5 import QtWidgets\nfrom PyQt5.QtCore import pyqtSignal, QSize\nfrom PyQt5.QtWidgets import QCheckBox\n\nfrom view.qt import MainWindow\nfrom time import strftime\nimport time\n\n\nclass MainWindowView(QtWidgets.QMainWindow):\n open_data_signal = pyqtSignal()\n open_accounts_signal = pyqtSignal()\n start_signal = pyqtSignal()\n pause_signal = pyqtSignal()\n stop_signal = pyqtSignal()\n test_only_signal = pyqtSignal(bool)\n print_log_signal = pyqtSignal(str, time.struct_time)\n print_progress_signal = pyqtSignal(int, int)\n print_email_stat_signal = pyqtSignal(str, int, int)\n start_without_test_message = pyqtSignal(bool)\n\n clear_window_signal = pyqtSignal()\n\n check_filter_from_signal = pyqtSignal(bool)\n check_filter_to_signal = pyqtSignal(bool)\n check_filter_title_signal = pyqtSignal(bool)\n check_filter_message_signal = pyqtSignal(bool)\n\n def __init__(self):\n super().__init__()\n self.ui = MainWindow.Ui_MainWindow()\n self.ui.setupUi(self)\n self.ui.actionData.triggered.connect(self.open_data_signal)\n self.ui.actionAccounts.triggered.connect(self.open_accounts_signal)\n self.ui.pushButton_play.clicked.connect(self.start_signal)\n self.ui.pushButton_pause.clicked.connect(self.pause_signal)\n self.ui.pushButton_stop.clicked.connect(self.stop_signal)\n self.ui.checkBox_testOnly.toggled.connect(self.test_only_signal)\n self.print_log_signal.connect(self.print_log)\n self.print_progress_signal.connect(self.print_progress)\n self.print_email_stat_signal.connect(self.print_email_stat)\n\n self.ui.pushButton_clearWindow.clicked.connect(self.clear_window)\n\n self.ui.checkBox_to.toggled.connect(self.check_filter_to_signal)\n self.ui.checkBox_from.toggled.connect(self.check_filter_from_signal)\n self.ui.checkBox_title.toggled.connect(self.check_filter_title_signal)\n self.ui.checkBox_message.toggled.connect(self.check_filter_message_signal)\n\n def print_log(self, text, time=None):\n if time:\n self.ui.plainText_log.appendHtml('[ %s ] ' % strftime(\"%H:%M:%S\", time))\n self.ui.plainText_log.insertPlainText(text)\n else:\n self.ui.plainText_log.appendPlainText(text)\n\n def print_progress(self, count: int, total: int):\n self.ui.progressBar_mailing.setValue(count)\n self.ui.progressBar_mailing.setMaximum(total if total else 1)\n self.ui.label_sendedMails.setText(f'Sent: {count} / {total:<6}')\n\n def print_email_stat(self, email: str, count: int, total: int):\n self.ui.label_curentEmail.setText(f'Current email: {email}')\n self.ui.label_countEmails.setText(f'Accounts: {count} / {total:<6}')\n\n def test_checked(self, is_checked):\n self.ui.checkBox_testOnly.setChecked(is_checked)\n\n def start_mailing(self):\n self.__state_player(False, True, True)\n self.ui.checkBox_testOnly.setEnabled(True)\n self.ui.checkBox_testOnly.setEnabled(False)\n\n def pause_mailing(self):\n self.__state_player(True, False, True)\n\n def stop_mailing(self):\n self.__state_player(True, False, False)\n self.ui.checkBox_testOnly.setEnabled(True)\n\n def show_no_test_message(self):\n qm = QtWidgets.QMessageBox()\n result = qm.question(self, '', \"Are you sure to start WITHOUT TEST?\", qm.Yes | qm.No)\n self.start_without_test_message.emit(result == qm.Yes)\n\n def __state_player(self, is_start, is_pause, is_stop):\n self.ui.pushButton_play.setEnabled(is_start)\n self.ui.pushButton_pause.setEnabled(is_pause)\n self.ui.pushButton_stop.setEnabled(is_stop)\n\n def clear_window(self):\n self.ui.plainText_log.clear()\n\n def show_error(self, text: str):\n msg = QtWidgets.QMessageBox()\n msg.setIcon(QtWidgets.QMessageBox.Critical)\n msg.setText(\"Error\")\n msg.setInformativeText(text)\n msg.setWindowTitle(\"Error\")\n msg.exec()\n","sub_path":"view/MainWindowView.py","file_name":"MainWindowView.py","file_ext":"py","file_size_in_byte":4013,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"483111179","text":"\"\"\"\nCopyright 2019 Lummetry.AI (Knowledge Investment Group SRL). All Rights Reserved.\n* NOTICE: All information contained herein is, and remains\n* the property of Knowledge Investment Group SRL. \n* The intellectual and technical concepts contained\n* herein are proprietary to Knowledge Investment Group SRL\n* and may be covered by Romanian and Foreign Patents,\n* patents in process, and are protected by trade secret or copyright law.\n* Dissemination of this information or reproduction of this material\n* is strictly forbidden unless prior written permission is obtained\n* from Knowledge Investment Group SRL.\n@copyright: Lummetry.AI\n@author: Lummetry.AI\n@project: \n@description:\n\"\"\"\nimport os\nimport shutil\nimport torch as th\nimport numpy as np\nimport constants as ct\n\nfrom libraries import Logger\nfrom torch2trt import TRTModule\nfrom data import get_path_results, read_images, save_benchmark_results\nfrom benchmark_methods import benchmark_pytorch_model\nfrom lumm_pytorch.pytorch_applications import MODELS\n\ndef qualitative_benchmark_pytorch_models_trt(log, lst_paths, np_imgs_bgr, batch_size, n_warmup, n_iters, debug=False):\n log.p('Qualitative benchmarking PyTorchTRT {} on image tensor: {}'.format(','.join(MODELS.keys()), np_imgs_bgr.shape))\n dct_classes = log.load_json('imagenet_classes_json.txt', folder='data')\n for model_name, dct_opt in MODELS.items():\n try:\n path_model = os.path.join(log.get_models_folder(), 'th_{}_trt.pth'.format(model_name))\n model_trt = TRTModule()\n model_trt.load_state_dict(th.load(path_model))\n log.p('Benchmarking {}'.format(model_name))\n lst_preds, lst_time = benchmark_pytorch_model(\n log=log,\n model=model_trt, \n np_imgs_bgr=np_imgs_bgr, \n batch_size=batch_size, \n n_warmup=n_warmup, \n n_iters=n_iters,\n as_rgb=True,\n preprocess_input_fn=dct_opt['PREPROCESS']\n )\n\n np_preds = np.array(lst_preds).squeeze()\n for i,pred in enumerate(np_preds):\n path_src = lst_paths[i]\n path_dst = get_path_results(log, batch_size=1, fn=os.path.join(ct.PYTORCH_TRT, \n ct.DATA_FOLDER_CLASSIFICATION, \n model_name))\n os.makedirs(path_dst, exist_ok=True)\n idx = np.argmax(pred, axis=-1)\n lbl = dct_classes[idx][1]\n shutil.copyfile(path_src, os.path.join(path_dst, lbl + '.png'))\n #endfor\n del model_trt\n log.clear_gpu_memory()\n except Exception as e:\n log.p('Exception on {}: {}'.format(model_name, str(e)))\n if debug:\n raise e\n #endfor\n return\n\n\nif __name__ == '__main__':\n log = Logger(\n lib_name='BENCHMARK', \n config_file='config.txt',\n TF_KERAS=False\n )\n log.set_nice_prints(df_precision=5)\n\n BS = 1\n N_WP = 0\n N_IT = 1\n \n lst_paths, lst_imgs = read_images(log=log, folder=ct.DATA_FOLDER_CLASSIFICATION)\n qualitative_benchmark_pytorch_models_trt(\n log=log,\n lst_paths=lst_paths,\n np_imgs_bgr=lst_imgs, \n batch_size=BS, \n n_warmup=N_WP, \n n_iters=N_IT,\n debug=True\n )\n \n \n \n \n\n ","sub_path":"lumm_pytorch/pytorch_applications_qualitative_benchmark_trt.py","file_name":"pytorch_applications_qualitative_benchmark_trt.py","file_ext":"py","file_size_in_byte":3178,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"476242030","text":"#!/usr/bin/env python\n# coding=utf8\n\"\"\"\nhttps://leetcode.com//problems/binary-tree-level-order-traversal/\n\nac_rate:\t29.6%\ndifficulty:\tEasy\n\n\nGiven a binary tree, return the level order traversal of its nodes' values. (ie, from left to right, level by level).\nFor example:\nGiven binary tree {3,9,20,#,#,15,7},\n3\n/ \\\n9 20\n/ \\\n15 7\nreturn its level order traversal as:\n[\n[3],\n[9,20],\n[15,7]\n]\nconfused what \"{1,#,2,3}\" means? > read more on how binary tree is serialized on OJ.\nOJ's Binary Tree Serialization:\nThe serialization of a binary tree follows a level order traversal, where '#' signifies a path terminator where no node exists below.\nHere's an example:\n1\n/ \\\n2 3\n/\n4\n\\\n5\nThe above binary tree is serialized as \"{1,2,3,#,#,4,#,#,5}\".\n\nShow Tags:\tTree, Breadth-first Search\n\"\"\"\n\n\n\n# Definition for a binary tree node.\nclass TreeNode:\n def __init__(self, x):\n self.val = x\n self.left = None\n self.right = None\n\nclass Solution:\n # @param {TreeNode} root\n # @return {integer[][]}\n def levelOrder(self, root):\n rst = []\n if root is None:\n return rst\n\n from collections import deque\n q = deque()\n q.append(root)\n while len(q) > 0:\n current_level = list(q)\n rst.append([one.val for one in current_level])\n q.clear()\n for i in current_level:\n if i.left:\n q.append(i.left)\n if i.right:\n q.append(i.right)\n return rst\n\n\nif __name__ == '__main__':\n root = TreeNode(3)\n right","sub_path":"leetcode/finished/binary_tree_level_order_traversal.py","file_name":"binary_tree_level_order_traversal.py","file_ext":"py","file_size_in_byte":1589,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"478685361","text":"# -*- coding: utf-8 -*-\n#\n# Copyright (c) 2018 Leland Stanford Junior University\n# Copyright (c) 2018 The Regents of the University of California\n#\n# This file is part of the SimCenter Backend Applications\n#\n# Redistribution and use in source and binary forms, with or without\n# modification, are permitted provided that the following conditions are met:\n#\n# 1. Redistributions of source code must retain the above copyright notice,\n# this list of conditions and the following disclaimer.\n#\n# 2. Redistributions in binary form must reproduce the above copyright notice,\n# this list of conditions and the following disclaimer in the documentation\n# and/or other materials provided with the distribution.\n#\n# 3. Neither the name of the copyright holder nor the names of its contributors\n# may be used to endorse or promote products derived from this software without\n# specific prior written permission.\n#\n# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE\n# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n# POSSIBILITY OF SUCH DAMAGE.\n#\n# You should have received a copy of the BSD 3-Clause License along with\n# this file. If not, see .\n#\n# Contributors:\n# Adam Zsarnóczay\n# Kuanshi Zhong\n#\n# Based on rulesets developed by:\n# Karen Angeles\n# Meredith Lockhead\n# Tracy Kijewski-Correa\n\nimport random\nimport numpy as np\nimport datetime\n\n\ndef WSF_config(BIM):\n \"\"\"\n Rules to identify a HAZUS WSF configuration based on BIM data\n\n Parameters\n ----------\n BIM: dictionary\n Information about the building characteristics.\n\n Returns\n -------\n config: str\n A string that identifies a specific configration within this buidling\n class.\n \"\"\"\n\n year = BIM['year_built'] # just for the sake of brevity\n\n # Secondary Water Resistance (SWR)\n # Minimum drainage recommendations are in place in NJ (See below).\n # However, SWR indicates a code-plus practice.\n SWR = False # Default in Reorganzied Rulesets - WIND\n if year > 2000:\n # For buildings built after 2000, SWR is based on homeowner compliance\n # data from NC Coastal Homeowner Survey (2017) to capture potential\n # human behavior (% of sealed roofs in NC dataset).\n SWR = random.random() < 0.6\n elif year > 1983:\n # CABO 1995:\n # According to 903.2 in the 1995 CABO, for roofs with slopes between\n # 2:12 and 4:12, an underlayment consisting of two layers of No. 15\n # felt must be applied. In severe climates (less than or equal to 25\n # degrees Fahrenheit average in January), these two layers must be\n # cemented together.\n # According to 903.3 in the 1995 CABO, roofs with slopes greater than\n # or equal to 4:12 shall have an underlayment of not less than one ply\n # of No. 15 felt.\n #\n # Similar rules are prescribed in CABO 1992, 1989, 1986, 1983\n #\n # Since low-slope roofs require two layers of felt, this is taken to\n # be secondary water resistance. This ruleset is for asphalt shingles.\n # Almost all other roof types require underlayment of some sort, but\n # the ruleset is based on asphalt shingles because it is most\n # conservative.\n if BIM['roof_shape'] == 'flt': # note there is actually no 'flt'\n SWR = True\n elif BIM['roof_shape'] in ['gab','hip']:\n if BIM['roof_slope'] <= 0.17:\n SWR = True\n elif BIM['roof_slope'] < 0.33:\n SWR = (BIM['avg_jan_temp'] == 'below')\n\n # Roof Deck Attachment (RDA)\n # IRC codes:\n # NJ code requires 8d nails (with spacing 6”/12”) for sheathing thicknesses\n # between ⅜”-1” - see Table R602.3(1)\n # Fastener selection is contingent on thickness of sheathing in building\n # codes. Commentary for Table R602.3(1) indicates 8d nails with 6”/6”\n # spacing (enhanced roof spacing) for ultimate wind speeds greater than\n # a speed_lim. speed_lim depends on the year of construction\n RDA = '6d' # Default (aka A) in Reorganized Rulesets - WIND\n if year > 2000:\n if year >= 2016:\n # IRC 2015\n speed_lim = 130.0 # mph\n else:\n # IRC 2000 - 2009\n speed_lim = 100.0 # mph\n if BIM['V_ult'] > speed_lim:\n RDA = '8s' # 8d @ 6\"/6\" ('D' in the Reorganized Rulesets - WIND)\n else:\n RDA = '8d' # 8d @ 6\"/12\" ('B' in the Reorganized Rulesets - WIND)\n elif year > 1995:\n if ((BIM['sheathing_t'] >= 0.3125) and (BIM['sheathing_t'] <= 0.5)):\n RDA = '6d' # 6d @ 6\"/12\" ('A' in the Reorganized Rulesets - WIND)\n elif ((BIM['sheathing_t'] >= 0.59375) and (BIM['sheathing_t'] <= 1.125)):\n RDA = '8d' # 8d @ 6\"/12\" ('B' in the Reorganized Rulesets - WIND)\n elif year > 1986:\n if ((BIM['sheathing_t'] >= 0.3125) and (BIM['sheathing_t'] <= 0.5)):\n RDA = '6d' # 6d @ 6\"/12\" ('A' in the Reorganized Rulesets - WIND)\n elif ((BIM['sheathing_t'] >= 0.59375) and (BIM['sheathing_t'] <= 1.0)):\n RDA = '8d' # 8d @ 6\"/12\" ('B' in the Reorganized Rulesets - WIND)\n else:\n # year <= 1986\n if ((BIM['sheathing_t'] >= 0.3125) and (BIM['sheathing_t'] <= 0.5)):\n RDA = '6d' # 6d @ 6\"/12\" ('A' in the Reorganized Rulesets - WIND)\n elif ((BIM['sheathing_t'] >= 0.625) and (BIM['sheathing_t'] <= 1.0)):\n RDA = '8d' # 8d @ 6\"/12\" ('B' in the Reorganized Rulesets - WIND)\n\n # Roof-Wall Connection (RWC)\n # IRC 2015\n # \"Assume all homes not having wind speed consideration are Toe Nail\n # (regardless of year)\n # For homes with wind speed consideration, 2015 IRC Section R802.11: no\n # specific connection type, must resist uplift forces using various\n # guidance documents, e.g., straps would be required (based on WFCM 2015);\n # will assume that if classified as HPR, then enhanced connection would be\n # used.\n if year > 2015:\n if BIM['HPR']:\n RWC = 'strap' # Strap\n else:\n RWC = 'tnail' # Toe-nail\n # IRC 2000-2009\n # In Section R802.11.1 Uplift Resistance of the NJ 2009 IRC, roof\n # assemblies which are subject to wind uplift pressures of 20 pounds per\n # square foot or greater are required to have attachments that are capable\n # of providing resistance, in this case assumed to be straps.\n # Otherwise, the connection is assumed to be toe nail.\n # CABO 1992-1995:\n # 802.11 Roof Tie-Down: Roof assemblies subject to wind uplift pressures of\n # 20 lbs per sq ft or greater shall have rafter or truess ties. The\n # resulting uplift forces from the rafter or turss ties shall be\n # transmitted to the foundation.\n # Roof uplift pressure varies by wind speed, exposure category, building\n # aspect ratio and roof height. For a reference building (9 ft tall in\n # exposure B -- WSF1) analysis suggests that wind speeds in excess of\n # 110 mph begin to generate pressures of 20 psf in high pressure zones of\n # the roof. Thus 110 mph is used as the critical velocity.\n elif year > 1992:\n if BIM['V_ult'] > 110:\n RWC = 'strap' # Strap\n else:\n RWC = 'tnail' # Toe-nail\n # CABO 1989 and earlier\n # There is no mention of straps or enhanced tie-downs in the CABO codes\n # older than 1992, and there is no description of these adoptions in IBHS\n # reports or the New Jersey Construction Code Communicator .\n # Although there is no explicit information, it seems that hurricane straps\n # really only came into effect in Florida after Hurricane Andrew (1992).\n # Because Florida is the leader in adopting hurricane protection measures\n # into codes and because there is no mention of shutters or straps in the\n # CABO codes, it is assumed that all roof-wall connections for residential\n # buildings are toe nails before 1992.\n else:\n # year <= 1992\n RWC = 'tnail' # Toe-nail\n\n # Shutters\n # IRC 2000-2015:\n # R301.2.1.2 in NJ IRC 2015 says protection of openings required for\n # buildings located in WBD regions, mentions impact-rated protection for\n # glazing, impact-resistance for garage door glazed openings, and finally\n # states that wood structural panels with a thickness > 7/16\" and a\n # span <8' can be used, as long as they are precut, attached to the framing\n # surrounding the opening, and the attachments are resistant to corrosion\n # and are able to resist component and cladding loads;\n # Earlier IRC editions provide similar rules.\n if year > 2000:\n shutters = BIM['WBD']\n # CABO:\n # Based on Human Subjects Data, roughly 45% of houses built in the 1980s\n # and 1990s had entries that implied they had shutters on at some or all of\n # their windows. Therefore, 45% of houses in this time should be randomly\n # assigned to have shutters.\n # Data ranges checked:\n # 1992 to 1995, 33/74 entries (44.59%) with shutters\n # 1986 to 1992, 36/79 entries (45.57%) with shutters\n # 1983 to 1986, 19/44 entries (43.18%) with shutters\n else:\n # year <= 2000\n if BIM['WBD']:\n shutters = random.random() < 0.45\n else:\n shutters = False\n\n # Garage\n # As per IRC 2015:\n # Garage door glazed opening protection for windborne debris shall meet the\n # requirements of an approved impact-resisting standard or ANSI/DASMA 115.\n # Exception: Wood structural panels with a thickness of not less than 7/16\n # inch and a span of not more than 8 feet shall be permitted for opening\n # protection. Panels shall be predrilled as required for the anchorage\n # method and shall be secured with the attachment hardware provided.\n # Permitted for buildings where the ultimate design wind speed is 180 mph\n # or less.\n #\n # Average lifespan of a garage is 30 years, so garages that are not in WBD\n # (and therefore do not have any strength requirements) that are older than\n # 30 years are considered to be weak, whereas those from the last 30 years\n # are considered to be standard.\n if BIM['garage_tag'] == -1:\n # no garage data, using the default \"standard\"\n garage = 'std'\n shutters = 0 # HAZUS ties standard garage to w/o shutters\n else:\n if year > 2000:\n if shutters:\n if BIM['garage_tag'] < 1:\n garage = 'no'\n else:\n garage = 'sup' # SFBC 1994\n shutters = 1 # HAZUS ties SFBC 1994 to with shutters\n else:\n if BIM['garage_tag'] < 1:\n garage = 'no' # None\n else:\n garage = 'std' # Standard\n shutters = 0 # HAZUS ties standard garage to w/o shutters\n elif year > (datetime.datetime.now().year - 30):\n if BIM['garage_tag'] < 1:\n garage = 'no' # None\n else:\n garage = 'std' # Standard\n shutters = 0 # HAZUS ties standard garage to w/o shutters\n else:\n # year <= current year - 30\n if BIM['garage_tag'] < 1:\n garage = 'no' # None\n else:\n garage = 'wkd' # Weak\n shutters = 0 # HAZUS ties weak garage to w/o shutters\n\n # building configuration tag\n bldg_config = f\"WSF\" \\\n f\"{int(min(BIM['stories'],2))}_\" \\\n f\"{BIM['roof_shape']}_\" \\\n f\"{int(SWR)}_\" \\\n f\"{RDA}_\" \\\n f\"{RWC}_\" \\\n f\"{garage}_\" \\\n f\"{int(shutters)}_\" \\\n f\"{int(BIM['terrain'])}\"\n return bldg_config\n\n","sub_path":"docs/common/testbeds/atlantic_city/data/WindWSFRulesets.py","file_name":"WindWSFRulesets.py","file_ext":"py","file_size_in_byte":12426,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"37403521","text":"from flask import Response, json, jsonify, request, url_for\n\nfrom config import flask_app, redis_db\nfrom helpers import send_mail as sendmail\n\napp = flask_app\n\n\nstatus_label = {\n 'PENDING': 'QUEUED',\n 'SUCCESS': 'SENT',\n 'FAILURE': 'FAILED'\n}\n\ndef get_status(celery_state):\n return status_label[celery_state]\n\n\n@app.route('/')\ndef index():\n return 'Index page'\n\n@app.route('/api/emails')\ndef emails():\n tasks = redis_db.hgetall('task')\n status = [{'state': get_status(sendmail.AsyncResult(k).state), 'email': v} for k, v in tasks.items()]\n return jsonify(status)\n\n@app.route('/api/send-email', methods=['POST'])\ndef send_email():\n\n try:\n \n data = request.get_json()\n task = sendmail.apply_async((data['email'], data['subject'], data['body']))\n\n redis_db.hset('task', task.id, data['email'])\n \n return Response(json.dumps({ 'msg': 'done sending email!' }), status=200, mimetype='application/json')\n\n except Exception as e:\n return Response(e, status=500, mimetype='application/json')\n\n\n\nif __name__ == '__main__':\n app.run(debug=True)\n","sub_path":"src/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":1119,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"277472833","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 ('myapp', '0010_auto_20151203_2332'),\n ]\n\n operations = [\n migrations.AlterModelOptions(\n name='page',\n options={'verbose_name': 'Старница', 'verbose_name_plural': 'Страницы'},\n ),\n migrations.AlterModelOptions(\n name='tag_news',\n options={'verbose_name': 'Категория новсти', 'verbose_name_plural': 'Категории новостей'},\n ),\n ]\n","sub_path":"myapp/migrations/0011_auto_20151203_2334.py","file_name":"0011_auto_20151203_2334.py","file_ext":"py","file_size_in_byte":635,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"407350054","text":"text = input()\n\nparentheses = []\n\nfor i in range(len(text)):\n\n if text[i] == \"(\":\n parentheses.append(i)\n\n elif text[i] == \")\":\n\n start_index = parentheses.pop()\n\n print(text[start_index:i + 1])\n# 1 + (2 - (2 + 3) * 4 / (3 + 1)) * 5\n# (((\n# )))\n","sub_path":"FirstStepsInPython/Advanced/Lab/Lists_as_Stacks_and_Queues/02_Matching_Parentheses.py","file_name":"02_Matching_Parentheses.py","file_ext":"py","file_size_in_byte":273,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"350023791","text":"__author__ = 'Aidan'\nyourssn = \"Please input your social security number. Include dashes. \"\nsep = tuple()\n\ndef ExcHand(ssn):\n try:\n a, g, s = ssn.split(\"-\")\n except ValueError:\n return None\n try:\n int(a)\n int(g)\n int(s)\n except ValueError:\n return None\n if len(a) != 3 or len(g) != 2 or len(s) != 4:\n return None\n elif int(a) == 000 or int(a) == 666 or 900 <= int(a) <= 999 or int(g) == 00 or int(s) == 0000:\n return None\n sep = (a,g,s)\n if sep == (\"078\",\"05\",\"1120\"):\n return None\n return sep\n\ndef SS(SSN = input(yourssn)):\n while ExcHand(SSN) is None:\n SSN = input(yourssn)\n ExcHand(SSN)\n\nSS()","sub_path":"Exception Handling.py","file_name":"Exception Handling.py","file_ext":"py","file_size_in_byte":702,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"178631847","text":"\n\nfrom xai.brain.wordbase.verbs._correlate import _CORRELATE\n\n#calss header\nclass _CORRELATING(_CORRELATE, ):\n\tdef __init__(self,): \n\t\t_CORRELATE.__init__(self)\n\t\tself.name = \"CORRELATING\"\n\t\tself.specie = 'verbs'\n\t\tself.basic = \"correlate\"\n\t\tself.jsondata = {}\n","sub_path":"xai/brain/wordbase/verbs/_correlating.py","file_name":"_correlating.py","file_ext":"py","file_size_in_byte":261,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"84187924","text":"\"\"\"Students Table.\"\"\"\nfrom django.db import models\nfrom taggit.managers import TaggableManager\nfrom PyIntern.users.models import User\n\n\nclass Student(User):\n \"\"\"Student.\"\"\"\n\n INFORMATIONSYSTEMS = 'SI'\n COMPUTERSCIENCE = 'CC'\n COMPUTERINFORMATION = 'SC'\n COURSE = (\n (INFORMATIONSYSTEMS, 'Sistemas de Informação'),\n (COMPUTERSCIENCE, 'Ciêncida da Computação'),\n (COMPUTERINFORMATION, ' Tecnólogo em Sistemas de Computação'),\n )\n register = models.IntegerField('Matrícula', unique=True)\n course = models.CharField(\n 'Curso', max_length=2, choices=COURSE, default=INFORMATIONSYSTEMS)\n mini_bio = models.CharField('Mini Biografia', max_length=600)\n resume = models.FileField('Curriculo', upload_to='curriculos/', blank=True)\n allowed = models.BooleanField('Autorizado', default=False)\n competences = TaggableManager('Competências')\n\n class Meta:\n \"\"\"Meta class for student.\"\"\"\n\n verbose_name = 'Estudante'\n verbose_name_plural = 'Estudantes'\n ordering = ('name', )\n\n def __str__(self):\n return self.name\n","sub_path":"PyIntern/PyIntern/students/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":1115,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"320282487","text":"\"\"\"\nThis module declares locations for searching data for projects CMIP5 for all frequencies, and where the data is\nat CNRM and on Ciclad\n\nAttributes for CMIP5 datasets are : model, rip (called simulation), frequency, table, realm, version\n\nSyntax for these attributes is described in `the CMIP5 DRS document `_\n\nExample for a CMIP5 dataset declaration ::\n\n >>> tas1pc=ds(project='CMIP5', model='CNRM-CM5', experiment='1pctCO2', variable='tas', frequency='monthly', period='1860-1861')\n\n\n\"\"\"\n\nimport os\nfrom climaf.dataloc import dataloc\nfrom climaf.classes import cproject, calias, cfreqs,cdef\nfrom climaf.site_settings import atCNRM, onCiclad, atCEDA\n\np=cproject(\"CMIP5\" ,\"model\",\"experiment\", (\"frequency\",\"monthly\"),\n (\"table\",\"*\"),(\"realm\",\"*\"),(\"version\",\"last\"),\n ensemble=[\"model\",\"simulation\"])\ncdef(\"simulation\",\"r1i1p1\",project=\"CMIP5\")\n\n# Frequency alias\ncfreqs('CMIP5', {'monthly':'mon' , 'daily':'day' })\n\nurls_CMIP5=None\n\nif atCNRM :\n # Declare the directory for CNRM-CM CMIP5 data on CNRM's Lustre file system.\n urls_CMIP5=[\"/cnrm/cmip/cnrm/ESG\"]\nif onCiclad :\n # Declare a list of root directories for CMIP5 data on IPLS's Ciclad file system\n urls_CMIP5=[\"/prodigfs/project/\"]\nif atCEDA:\n urls_CMIP5=[\"/badc/cmip5/data\"]\n\nif urls_CMIP5 :\n # Next command will lead to explore all directories in 'url' \n # for searching data for a CliMAF dataset (by function ds) except if \n # a more specific dataloc entry matches the arguments to 'ds'\n dataloc(project=\"CMIP5\", organization=\"CMIP5_DRS\", url=urls_CMIP5)\n","sub_path":"climaf/projects/cmip5.py","file_name":"cmip5.py","file_ext":"py","file_size_in_byte":1638,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"492662046","text":"# Django settings for NMTK_apps project.\nimport os\nimport djcelery\n\nAPP_ROOT = \"/var/www/tools\" # Change for local installation\nBASE_PATH = APP_ROOT\nFILES_PATH=APP_ROOT+'/nmtk_files'\nLOGFILE_PATH=APP_ROOT+'/logs'\n\n\n# Used to initialize the sites model (see: NMTK_server/management/__init__.py)\nSITE_DOMAIN='localhost:8080'\nDEBUG = True\nTEMPLATE_DEBUG = DEBUG\ndjcelery.setup_loader()\n\n\n\nADMINS = (\n # ('Your Name', 'your_email@example.com'),\n)\n\n\n\n\n\n\n\n\n\n\n\n\nMANAGERS = ADMINS\nALLOWED_HOSTS= [\"*\"] # = [SITE_DOMAIN,]\nDATABASES = {\n 'default': {\n 'ENGINE': 'django.contrib.gis.db.backends.spatialite', # Add 'postgresql_psycopg2', 'mysql', 'sqlite3' or 'oracle'.\n 'NAME': APP_ROOT+'/nmtk_files/nmtk.sqlite', # Or path to database file if using sqlite3.\n 'USER': '', # Not used with sqlite3.\n 'PASSWORD': '', # Not used with sqlite3.\n 'HOST': '', # Set to empty string for localhost. Not used with sqlite3.\n 'PORT': '', # Set to empty string for default. Not used with sqlite3.\n }\n}\n\n# Local time zone for this installation. Choices can be found here:\n# http://en.wikipedia.org/wiki/List_of_tz_zones_by_name\n# although not all choices may be available on all operating systems.\n# In a Windows environment this must be set to your system time zone.\nTIME_ZONE = 'America/New_York'\n\n# Language code for this installation. All choices can be found here:\n# http://www.i18nguy.com/unicode/language-identifiers.html\nLANGUAGE_CODE = 'en-us'\n\nSITE_ID = 1\n\n# If you set this to False, Django will make some optimizations so as not\n# to load the internationalization machinery.\nUSE_I18N = True\n\n# If you set this to False, Django will not format dates, numbers and\n# calendars according to the current locale.\nUSE_L10N = True\n\n# If you set this to False, Django will not use timezone-aware datetimes.\nUSE_TZ = True\n\n# Absolute filesystem path to the directory that will hold user-uploaded files.\n# Example: \"/home/media/media.lawrence.com/media/\"\nMEDIA_ROOT = ''\n\n# URL that handles the media served from MEDIA_ROOT. Make sure to use a\n# trailing slash.\n# Examples: \"http://media.lawrence.com/media/\", \"http://example.com/media/\"\nMEDIA_URL = ''\n\n# Absolute path to the directory static files should be collected to.\n# Don't put anything in this directory yourself; store your static files\n# in apps' \"static/\" subdirectories and in STATICFILES_DIRS.\n# Example: \"/home/media/media.lawrence.com/static/\"\nSTATIC_ROOT=APP_ROOT+'/htdocs/static'\n\n# URL prefix for static files.\n# Example: \"http://media.lawrence.com/static/\"\nSTATIC_URL = 'http://localhost:8080/static/'\n\n# Additional locations of static files\nSTATICFILES_DIRS = (\n # Put strings here, like \"/home/html/static\" or \"C:/www/django/static\".\n # Always use forward slashes, even on Windows.\n # Don't forget to use absolute paths, not relative paths.\n)\n\n# List of finder classes that know how to find static files in\n# various locations.\nSTATICFILES_FINDERS = (\n 'django.contrib.staticfiles.finders.FileSystemFinder',\n 'django.contrib.staticfiles.finders.AppDirectoriesFinder',\n# 'django.contrib.staticfiles.finders.DefaultStorageFinder',\n)\n\n# Make this unique, and don't share it with anybody.\nSECRET_KEY = 'hk(f4*q-%yo9xf*x@_4#cv=wc8zp=%03=sukgl+_6sz2=zdmy='\n\n# List of callables that know how to import templates from various sources.\nTEMPLATE_LOADERS = (\n 'django.template.loaders.filesystem.Loader',\n 'django.template.loaders.app_directories.Loader',\n# 'django.template.loaders.eggs.Loader',\n)\n\nMIDDLEWARE_CLASSES = (\n 'django.middleware.common.CommonMiddleware',\n 'django.contrib.sessions.middleware.SessionMiddleware',\n 'django.middleware.csrf.CsrfViewMiddleware',\n 'django.contrib.auth.middleware.AuthenticationMiddleware',\n 'django.contrib.messages.middleware.MessageMiddleware',\n # 'NMTK_server.middleware.StrictAuthentication',\n # Uncomment the next line for simple clickjacking protection:\n # 'django.middleware.clickjacking.XFrameOptionsMiddleware',\n)\n\nROOT_URLCONF = 'NMTK_apps.urls'\n\n# Python dotted path to the WSGI application used by Django's runserver.\nWSGI_APPLICATION = 'NMTK_apps.wsgi.application'\nTEMPLATE_DIRS = (\n # Put strings here, like \"/home/html/django_templates\" or \"C:/www/django/templates\".\n # Always use forward slashes, even on Windows.\n # Don't forget to use absolute paths, not relative paths.\n\n # This directory adds the templates that may be stored in the NMTK_apps directory,\n # Which is not an app - but the underpinnings for everything else.\n APP_ROOT+\"/NMTK_Apps/NMTK_Apps/templates\",\n)\n\n\n\n\nTEMPLATE_CONTEXT_PROCESSORS=(\"django.contrib.auth.context_processors.auth\",\n \"django.core.context_processors.debug\",\n \"django.core.context_processors.i18n\",\n \"django.core.context_processors.media\",\n \"django.core.context_processors.static\",\n \"django.core.context_processors.tz\",\n \"django.contrib.messages.context_processors.messages\",\n \"django.core.context_processors.request\", \n )\n\nINSTALLED_APPS = (\n #'django.contrib.auth',\n 'django.contrib.contenttypes',\n 'django.contrib.sessions',\n 'django.contrib.sites',\n 'django.contrib.messages',\n 'django.contrib.staticfiles',\n # 'NMTK_server', # A test NMTK server for NMTK validating tools locally.\n # Uncomment the next line to enable the admin:\n # 'django.contrib.admin',\n # Uncomment the next line to enable admin documentation:\n # 'django.contrib.admindocs',\n 'NMTK_tools', # An app used to generate a list of tools.\n 'MN_model', # The tool for the Minnesota pedestrian/cycle models\n 'SF_model', # The tool for the SF pedestrian model\n 'HCM2010_Bike', # HCM 2010 Bike Tools\n 'djcelery',\n 'kombu.transport.django',\n)\n\n\n\n\n\n# Define a GeoJSON serializer so we can serialize and return results of\n# various tasks in the GeoJSON format.\nSERIALIZATION_MODULES = { 'geojson' : 'NMTK_apps.serializers.geojson' }\n\n\n\n\n\n# if you want to change the logging (to disable debug) do it here..\nMIN_LOG_LEVEL='DEBUG' # 'INFO' for non-debug, 'DEBUG' for debugging\n\n# A sample logging configuration. The only tangible logging\n# performed by this configuration is to send an email to\n# the site admins on every HTTP 500 error when DEBUG=False.\n# See http://docs.djangoproject.com/en/dev/topics/logging for\n# more details on how to customize your logging configuration.\n \nLOGGING = {\n 'version': 1,\n 'disable_existing_loggers': True,\n 'formatters': {\n 'standard': {\n 'format': '%(asctime)s [%(levelname)s] %(name)s: %(message)s'\n },\n },\n 'handlers': {\n 'null': {\n 'level':'DEBUG',\n 'class':'django.utils.log.NullHandler',\n },\n 'debug': {\n 'level':'DEBUG',\n 'class':'logging.handlers.WatchedFileHandler',\n 'filename': os.path.join(LOGFILE_PATH,'django-debug.log'),\n 'formatter':'standard',\n }, \n 'default': {\n 'level':'INFO',\n 'class':'logging.handlers.WatchedFileHandler',\n 'filename': os.path.join(LOGFILE_PATH,'django-request.log'),\n 'formatter':'standard',\n },\n 'apache': {\n 'level':'INFO',\n 'class':'logging.StreamHandler',\n 'formatter':'standard',\n },\n },\n 'loggers': { \n '': {\n 'handlers': ['debug', 'default'],\n 'level': MIN_LOG_LEVEL,\n 'propagate': True,\n },\n 'django.request': { # Stop request debug from logging to main logger\n 'handlers': ['apache'],\n 'level': 'INFO',\n 'propagate': False,\n },\n 'django.db': { # We can turn on db logging by switching the handler to debug\n 'handlers': ['null'],\n 'level': MIN_LOG_LEVEL,\n 'propagate': False,\n },\n }\n}\n\n# This dictionary is used by NMTK tools to interact with the NMTK server\n# In particular, it stores the public/private keys for each tool server.\n#\n# Note: by design if you are using the NMTK_server app (which is a \n# client-interface to NMTK tools that provides data management, among other\n# things) it won't use this data - it's for tools only. The Server app will\n# use it's database records for managing this. However, it's important to\n# note that what's here, and what's in the DB should match or requests to/from\n# the server will fail.\n\n# In the case below, the key is the public key that the server has assigned \n# to this tool. The url is the URL for the server, and the secret is the\n# shared secret key used for signing requests. Note that the client identifies\n# the server using the public key - which is included in any dialog between \n# the client and the server.\n\n# First one corresponds to a demo webapp running on the Digital Ocean core\n# Second one corresponds to a demo webapp running on the Amazon Web Services core\n\nNMTK_SERVERS={'e0fa4ad39af445c28fa7c83446955588': {'url': 'http://192.241.172.151/demo/',\n 'secret': '''vyt38)+(-))i-ncv-%f(rib^jy$(rx1(fp&(xzjf7=g3qny''' },\n 'a9d6ca9527f14eba81f10a5a57e71a2d': {'url': 'http://ec2-184-72-160-215.compute-1.amazonaws.com/demo/',\n 'secret': '''4ownulw_b9(--bo8(1(ujg-+mfzl$-!#e*yjx*f6u_#xv%)e*3''' },\n }\n\nBROKER_URL = 'django://'\n\n","sub_path":"NMTK_apps/NMTK_apps/settings.py","file_name":"settings.py","file_ext":"py","file_size_in_byte":9671,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"7400610","text":"from PyQt5 import QtCore, QtGui, QtWidgets\nimport numpy as np\nimport time\nimport scipy.optimize as spo\nimport pyqtgraph as pg\nimport os\n\ntry:\n from .calibrator_ui import Ui_PyroCalibration\nexcept ModuleNotFoundError:\n from calibrator_ui import Ui_PyroCalibration\n\n \nclass PyroCalibrator(QtWidgets.QMainWindow):\n def __init__(self):\n super(PyroCalibrator, self).__init__()\n self.initUI()\n self.calData = []\n self.calFactor = 0\n self.clearCalData()\n\n self.intermediateData = [None, None]\n\n # A timer to make sure the signals from the TK and\n # pyro come at the same time, to prevent mixing\n # results from different pulses\n self.synchronizer = QtCore.QTimer()\n self.synchronizer.setSingleShot(True)\n # Set it to 150ms interval, so the two signals have to be\n # that close together. I don't think the FEL will ever run\n # at 7 Hz, so we don't need to worry about this allowing\n # different pulses.\n self.synchronizer.setInterval(150)\n\n # Set the pyro widget to always try to count\n # pulses\n self.ui.pyroWid.settings[\"exposing\"] = True\n\n self.saveDir = r'Z:\\~HSG\\Data\\2018'\n\n def initUI(self):\n self.ui = Ui_PyroCalibration()\n self.ui.setupUi(self)\n\n self.ui.pyroWid.sigPulseCounted.connect(self.appendData)\n self.ui.TKWid.sigPulseEnergy.connect(self.appendData)\n self.ui.TKWid.ui.gbAveraging.setChecked(False)\n\n\n # add a textbox for pk-pk value\n self.calText = pg.TextItem('', color=(0, 0, 0))\n self.calText.setPos(0, 0)\n self.calText.setFont(QtGui.QFont(\"\", 15))\n self.ui.gRatio.sigRangeChanged.connect(self.updateCalTextPos)\n\n self.ui.gRatio.addItem(self.calText, ignoreBounds=True)\n self.pCalPoints = self.ui.gRatio.plotItem.plot(pen=None, symbol='o')\n self.pCalLine = self.ui.gRatio.plotItem.plot(pen='k')\n pi = self.ui.gRatio.plotItem\n pi.setLabel(\"bottom\", \"Pyro Signal\", \"V\")\n pi.setLabel(\"left\", \"Pulse Energy\", \"mJ\")\n\n save = pi.vb.menu.addAction(\"Save Points...\")\n save.triggered.connect(self.saveData)\n\n self.ui.bDoublePause.clicked.connect(self.toggleBothScopes)\n self.ui.pyroWid.ui.bOPause.clicked.connect(self.toggleBothScopes)\n self.ui.TKWid.ui.bOPause.clicked.connect(self.toggleBothScopes)\n self.ui.bClear.clicked.connect(self.clearCalData)\n\n\n\n self.show()\n\n def toggleBothScopes(self, newVal):\n if self.sender() == self.ui.bDoublePause:\n for wid in [self.ui.pyroWid.ui.bOPause, self.ui.TKWid.ui.bOPause]:\n # wid.blockSignals(True)\n wid.clicked.disconnect(self.toggleBothScopes)\n wid.setChecked(newVal)\n wid.clicked.emit(newVal)\n wid.clicked.connect(self.toggleBothScopes)\n # wid.blockSignals(False)\n # self.ui.pyroWid.ui.bOPause.setChecked(newVal)\n # self.ui.TKWid.ui.bOPause.setChecked(newVal)\n else:\n tp = self.ui.TKWid.ui.bOPause.isChecked()\n pp = self.ui.pyroWid.ui.bOPause.isChecked()\n\n if (tp and pp):\n self.ui.bDoublePause.setChecked(True)\n else:\n self.ui.bDoublePause.setChecked(False)\n\n def updateCalTextPos(self, null, range):\n self.calText.setPos(range[0][0], range[1][1])\n\n def clearCalData(self):\n self.ui.pyroWid.settings[\"FELPulses\"] = 0\n self.calData = np.empty((0,2))\n\n def appendData(self, data):\n if not self.ui.bCal.isChecked(): return\n if self.sender() is self.ui.pyroWid:\n idx = 0\n # skip a bad pulse\n if data<0: return\n data = self.ui.pyroWid.settings[\"pyroVoltage\"][-1]\n elif self.sender() is self.ui.TKWid:\n idx = 1\n else:\n raise RuntimeError(\"Who sent this data? {}, {}\".format(self.sender(), data))\n\n self.intermediateData[idx] = data\n if self.synchronizer.isActive():\n if None in self.intermediateData:\n raise RuntimeError(\"How is the timer active with not-full data? {}\".format(self.intermediateData))\n self.calData = np.row_stack((self.calData, self.intermediateData))\n self.intermediateData = [None]*2\n self.updateCalibration()\n else:\n self.synchronizer.start()\n\n def saveData(self):\n loc = QtWidgets.QFileDialog.getSaveFileName(\n self, \"Choose save file\", self.saveDir, \"Text files (*.txt)\"\n )[0]\n loc = str(loc)\n if not loc: return\n self.saveDir = os.path.dirname(loc)\n\n\n oh = \"#{\"+\"\\n#\\t'Freq': {}\\n#\\t'Cal Factor': {}\\n#\".format(\n self.ui.TKWid.ui.tFELFreq.value()*29.9979,\n self.calFactor*1e-3\n )+\"}\\n\"\n oh += \"Pyro Voltage,TK Energy\\n\"\n oh += \"mV,mJ\\n\"\n oh += \"Pyro Voltage,TK Energy\"\n\n saveData = self.calData.copy()\n saveData[:,0]*=1e3\n\n np.savetxt(loc, saveData, fmt='%f', delimiter=',',\n comments='', header=oh)\n\n\n\n def updateCalibration(self):\n self.pCalPoints.setData(self.calData)\n cal, _ = spo.curve_fit(lambda x,m: m*x, *self.calData.T)\n mn, mx = self.calData[:,0].min(), self.calData[:,0].max()\n\n self.calFactor = cal[0]\n pts = np.array([mn-(mx-mn)*.05, mx+(mx-mn)*.05 ])\n self.calText.setText(\"{:.3f} mJ/mV\".format(self.calFactor*1e-3), color=(0,0,0))\n self.pCalLine.setData(pts, pts*self.calFactor)\n\n def closeEvent(self, *args, **kwargs):\n self.ui.pyroWid.close()\n self.ui.TKWid.close()\n super(PyroCalibrator, self).closeEvent(*args, **kwargs)\n\n\n\nif __name__ == '__main__':\n\timport sys\n\n\n\tap = QtWidgets.QApplication(sys.argv)\n\twid = PyroCalibrator()\n\twid.show()\n\tsys.exit(ap.exec_())\n","sub_path":"InstsAndQt/PyroCalibrator/pyroCal.py","file_name":"pyroCal.py","file_ext":"py","file_size_in_byte":5917,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"191255771","text":"#!/usr/bin/env python\n\n# # Copyright (c) 2012 Aldebaran Robotics. All rights reserved.\n# # Use of this source code is governed by a BSD-style license that can be\n# # found in the COPYING file.\n\n\"\"\" Contains all modules needed to convert a xar file\n.. module:: node\n\"\"\"\n\n\nclass Node(object):\n \"\"\" Parent class of any object in the xar format\n \"\"\"\n\n def __init__(self, type):\n self.id = -1\n self.name = \"\"\n self.node_type = type\n self.node_path = \"\"\n self.parent_path = \"\"\n\n self.children_node = []\n self.parent_node = None\n self._function_map = None\n\n def diff(self, other):\n result = \"\"\n\n if self != other:\n if not other:\n result += str(self.node_type) + \": value of other is None\"\n if self.node_type != other.node_type:\n result += \"Types different: \" + self.node_type + \" and \" + other.node_type\n\n rdict = self.__dict__\n ldict = other.__dict__\n for key in rdict.keys():\n ignored_keys = [\"parent_node\", \"children_node\", \"_function_map\", \"uuid\"]\n if key in ignored_keys:\n continue\n elif isinstance(rdict[key], list) and isinstance(ldict[key], list):\n if len(rdict[key]) != len(ldict[key]):\n result += \"%s length is different\\n\" % str(key)\n return result\n\n for j in range(len(rdict[key])):\n if rdict[key][j] != ldict[key][j]:\n result += (\"Values different for attrib \\\"{}\\\" | row {}\\n\").format(\n str(key), j)\n\n if isinstance(rdict[key][j], Node) and isinstance(ldict[key][j], Node):\n result += rdict[key][j].diff(ldict[key][j])\n else:\n result += \" value 1: %s\\n\" % str(rdict[key][j])\n result += \" value 2: %s\\n\" % str(ldict[key][j])\n return result\n else:\n if rdict[key] != ldict[key]:\n result += \"Values different for attrib \\\"%s\\\"\\n\" % str(key)\n\n if isinstance(rdict[key], Node) and isinstance(ldict[key], Node):\n result += rdict[key].diff(ldict[key])\n else:\n if key == \"timeline\":\n result += \" value 1: %s\\n\" % str(rdict[key].__dict__)\n result += \" value 2: %s\\n\" % str(ldict[key].__dict__)\n else:\n result += \" value 1: %s\\n\" % str(rdict[key])\n result += \" value 2: %s\\n\" % str(ldict[key])\n return result\n\n return result\n\n def __eq__(self, other):\n if not other:\n return False\n\n if not isinstance(other, self.__class__):\n return False\n\n if self.node_type != other.node_type:\n return False\n\n rdict = self.__dict__\n ldict = other.__dict__\n for key in rdict.keys():\n ignored_keys = [\"parent_node\", \"children_node\", \"_function_map\", \"uuid\"]\n if key in ignored_keys:\n continue\n elif isinstance(rdict[key], list) and isinstance(ldict[key], list):\n if len(rdict[key]) != len(ldict[key]):\n return False\n\n for j in range(len(rdict[key])):\n if rdict[key][j] != ldict[key][j]:\n return False\n else:\n if rdict[key] != ldict[key]:\n return False\n\n return True\n\n def __ne__(self, other):\n return not self.__eq__(other)\n\n def add_child(self, child):\n self.children_node.append(child)\n child.parent_node = self\n\n def attach_attribute(self, name, attrs):\n if (name in self._function_map.keys()):\n self._function_map[name](self, attrs)\n\n def beacon(self):\n return \"Node\"\n","sub_path":"xarconverter/converter/node/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":4190,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"113179998","text":"# maybe read in the baseline\n# then loop through reads of all models...\n# perform the diff\n# then groupby month and compute means / stdev\n\ndef sort_files( files, split_on='_', elem_month=-2, elem_year=-1 ):\n\t'''\n\tsort a list of files properly using the month and year parsed\n\tfrom the filename. This is useful with SNAP data since the standard\n\tis to name files like '_MM_YYYY.tif'. If sorted using base\n\tPythons sort/sorted functions, things will be sorted by the first char\n\tof the month, which makes thing go 1, 11, ... which sucks for timeseries\n\tthis sorts it properly following SNAP standards as the default settings.\n\n\tARGUMENTS:\n\t----------\n\tfiles = [list] list of `str` pathnames to be sorted by month and year. usually from glob.glob.\n\tsplit_on = [str] `str` character to split the filename on. default:'_', SNAP standard.\n\telem_month = [int] slice element from resultant split filename list. Follows Python slicing syntax.\n\t\tdefault:-2. For SNAP standard.\n\telem_year = [int] slice element from resultant split filename list. Follows Python slicing syntax.\n\t\tdefault:-1. For SNAP standard.\n\n\tRETURNS:\n\t--------\n\tsorted `list` by month and year ascending. \n\n\t'''\n\timport pandas as pd\n\tmonths = [ int(fn.split('.')[0].split( split_on )[elem_month]) for fn in files ]\n\tyears = [ int(fn.split('.')[0].split( split_on )[elem_year]) for fn in files ]\n\tdf = pd.DataFrame( {'fn':files, 'month':months, 'year':years} )\n\tdf_sorted = df.sort_values( ['year', 'month' ] )\n\treturn df_sorted.fn.tolist()\n\ndef only_years( files, begin=1901, end=2100, split_on='_', elem_year=-1 ):\n\t'''\n\treturn new list of filenames where they are truncated to begin:end\n\n\tARGUMENTS:\n\t----------\n\tfiles = [list] list of `str` pathnames to be sorted by month and year. usually from glob.glob.\n\tbegin = [int] four digit integer year of the begin time default:1901\n\tend = [int] four digit integer year of the end time default:2100\n\tsplit_on = [str] `str` character to split the filename on. default:'_', SNAP standard.\n\telem_year = [int] slice element from resultant split filename list. Follows Python slicing syntax.\n\t\tdefault:-1. For SNAP standard.\n\n\tRETURNS:\n\t--------\n\tsliced `list` to begin and end year.\n\t'''\n\timport pandas as pd\n\tyears = [ int(fn.split('.')[0].split( split_on )[elem_year]) for fn in files ]\n\tdf = pd.DataFrame( { 'fn':files, 'year':years } )\n\tdf_slice = df[ (df.year >= begin ) & (df.year <= end ) ]\n\treturn df_slice.fn.tolist()\n\nclass SubDomains( object ):\n\t'''\n\trasterize subdomains shapefile to ALFRESCO AOI of output set\n\t'''\n\tdef __init__( self, subdomains_fn, rasterio_raster, id_field, name_field, background_value=0, *args, **kwargs ):\n\t\t'''\n\t\tinitializer for the SubDomains object\n\t\tThe real magic here is that it will use a generator to loop through the \n\t\tunique ID's in the sub_domains raster map generated.\n\t\t'''\n\t\timport numpy as np\n\t\tself.subdomains_fn = subdomains_fn\n\t\tself.rasterio_raster = rasterio_raster\n\t\tself.id_field = id_field\n\t\tself.name_field = name_field\n\t\tself.background_value = background_value\n\t\tself._rasterize_subdomains( )\n\t\tself._get_subdomains_dict( )\n\n\tdef _rasterize_subdomains( self ):\n\t\t'''\n\t\trasterize a subdomains shapefile to the extent and resolution of \n\t\ta template raster file. The two must be in the same reference system \n\t\tor there will be potential issues. \n\t\treturns:\n\t\t\tnumpy.ndarray with the shape of the input raster and the shapefile\n\t\t\tpolygons burned in with the values of the id_field of the shapefile\n\t\tgotchas:\n\t\t\tcurrently the only supported data type is uint8 and all float values will be\n\t\t\tcoerced to integer for this purpose. Another issue is that if there is a value\n\t\t\tgreater than 255, there could be some error-type issues. This is something that \n\t\t\tthe user needs to know for the time-being and will be fixed in subsequent versions\n\t\t\tof rasterio. Then I can add the needed changes here.\n\t\t'''\n\t\timport geopandas as gpd\n\t\timport numpy as np\n\n\t\tgdf = gpd.read_file( self.subdomains_fn )\n\t\tid_groups = gdf.groupby( self.id_field ) # iterator of tuples (id, gdf slice)\n\n\t\tout_shape = self.rasterio_raster.height, self.rasterio_raster.width\n\t\tout_transform = self.rasterio_raster.affine\n\n\t\tarr_list = [ self._rasterize_id( df, value, out_shape, out_transform, background_value=self.background_value ) for value, df in id_groups ]\n\t\tself.sub_domains = arr_list\n\t@staticmethod\n\tdef _rasterize_id( df, value, out_shape, out_transform, background_value=0 ):\n\t\tfrom rasterio.features import rasterize\n\t\tgeom = df.geometry\n\t\tout = rasterize( ( ( g, value ) for g in geom ),\n\t\t\t\t\t\t\tout_shape=out_shape,\n\t\t\t\t\t\t\ttransform=out_transform,\n\t\t\t\t\t\t\tfill=background_value )\n\t\treturn out\n\tdef _get_subdomains_dict( self ):\n\t\timport geopandas as gpd\n\t\tgdf = gpd.read_file( self.subdomains_fn )\n\t\tself.names_dict = dict( zip( gdf[self.id_field], gdf[self.name_field] ) )\n\ndef f( x ):\n\t''' apply function for multiprocessing.pool \n\t\thelps with clean i/o '''\n\twith rasterio.open( x ) as rst:\n\t\tarr = rst.read( 1 )\n\treturn arr\n\ndef get_metrics( base_path, variable, model, scenario, decade, mask, domain_name=None, ncpus=32 ):\n\t'''\n\tmain function to return monthly summary stats for the group\n\tas a `dict`\n\t'''\n\tdecade_begin, decade_end = decade\n\tmodeled_files = glob.glob( os.path.join( base_path, model, scenario, variable, '*.tif' ) )\n\tmodeled_files = sort_files( only_years( modeled_files, begin=decade_begin, end=decade_end, split_on='_', elem_year=-1 ) )\n\t\n\t# groupby month here\n\tmonth_grouped = pd.Series( modeled_files ).groupby([ os.path.basename(i).split('_')[-2] for i in modeled_files ])\n\tmonth_grouped = { i:j.tolist() for i,j in month_grouped } # make a dict\n\t\n\tmonth_dict = {}\n\tfor month in month_grouped:\n\t\t# get diffs in parallel\n\t\tpool = mp.Pool( ncpus )\n\t\tarr = np.array( pool.map( f, month_grouped[ month ] ) )\n\t\tpool.close()\n\t\tpool.join()\n\t\tpool.terminate()\n\t\tpool = None\n\n\t\t# this derives a mean from 3D (time, x, y) to 2D (x, y)\n\t\t# mean_arr = np.mean( arr, axis=0 )\n\t\tmasked = np.ma.masked_array( arr, np.broadcast_to( mask == 0, arr.shape ) )\n\t\t# arr = None\n\n\t\t# calculate metrics across the 2D space\n\t\tmonth_dict[ str(month) ] = { 'stdev':str( np.std( masked ) ),\n\t\t\t\t\t\t\t\t\t'mean':str( np.mean( masked ) ),\n\t\t\t\t\t\t\t\t\t'min':str( np.min( masked ) ),\n\t\t\t\t\t\t\t\t\t'max':str( np.max( masked ) ) }\n\n\t\t# domain_name\n\t\tif domain_name == None:\n\t\t\tdomain_name, = str( np.unique( mask > 0 ) )\n\t\n\treturn { '_'.join([ model, scenario, variable, domain_name, str(decade_begin), str(decade_end) ]) : month_dict }\n\n\nif __name__ == '__main__':\n\timport os, glob, itertools, rasterio, json\n\tfrom copy import deepcopy\n\timport xarray as xr\n\timport numpy as np\n\timport pandas as pd\n\tfrom pathos import multiprocessing as mp\n\n\t# setup args\n\tbase_path = '/workspace/Shared/Tech_Projects/EPSCoR_Southcentral/project_data/downscaled_cru_v2_clipped/CRU_TS323'\n\toutput_path = '/workspace/Shared/Tech_Projects/EPSCoR_Southcentral/project_data/derived_tabular_ALL_SPACE_TIME'\n\tncpus = 32\n\tproject = 'cru' # 'cmip5'\n\tvariables = [ 'tasmin', 'tasmax', 'tas', 'pr' ]\n\tmodels = [ 'ts323' ] # [ 'IPSL-CM5A-LR', 'MRI-CGCM3', 'GISS-E2-R', 'GFDL-CM3', 'CCSM4', '5ModelAvg' ]\n\tscenarios = [ 'historical' ] # [ 'historical', 'rcp26', 'rcp45', 'rcp60', 'rcp85' ]\n\tbegin_out = 1901\n\tend_out = 2014\n\ttemplate_rst = '/workspace/Shared/Tech_Projects/EPSCoR_Southcentral/project_data/downscaled_cmip5_v2_clipped/NCAR-CCSM4/historical/tasmax/tasmax_mean_C_ar5_NCAR-CCSM4_historical_01_1901.tif'\n\trst = rasterio.open( template_rst )\n\t# subdomain_fn = '/workspace/Shared/Tech_Projects/EPSCoR_Southcentral/project_data/SCTC_studyarea/Kenai_StudyArea.shp'\n\tsubdomain_fn = '/workspace/Shared/Tech_Projects/EPSCoR_Southcentral/project_data/SCTC_studyarea/SCTC_watersheds.shp'\n\n\t# create the rasterized version of the input shapefile for spatial query\n\t# subdomains = SubDomains( subdomain_fn, rst, id_field='OBJECTID', name_field='OBJECTID', background_value=0 )\n\tsubdomains = SubDomains( subdomain_fn, rst, id_field='OBJECTID', name_field='HU_12_Name', background_value=0 )\n\tmasks = subdomains.sub_domains\n\n\t# make sure no NoData pixels are in the domain\n\tnodata_mask = rst.read_masks( 1 ) # mask where zero\n\tfor count, mask in enumerate( masks ):\n\t\tmask[ nodata_mask == 0 ] = 0\n\t\tmasks[ count ] = mask\n\n\tfor variable in variables:\n\t\tall_data = {}\n\t\tfor model, scenario in itertools.product( models, scenarios ):\n\t\t\tif scenario == 'historical':\n\t\t\t\tdecades = [(1900,1909),(1910, 1919),(1920, 1929),(1930, 1939),(1940, 1949),\\\n\t\t\t\t\t\t\t(1950, 1959),(1960, 1969),(1970, 1979),(1980, 1989),(1990, 1999),(2000,2009),(2010, 2014)]\n\t\t\t\tbegin = 1901\n\t\t\t\tend = 2014\n\t\t\telse:\n\t\t\t\tdecades = [(2006,2009),(2010, 2019),(2020, 2029),(2030, 2039),(2040, 2049),(2050, 2059),\\\n\t\t\t\t\t\t\t(2060, 2069),(2070, 2079),(2080, 2089),(2090, 2099)]\n\t\t\t\tbegin = 2006\n\t\t\t\tend = 2100\n\n\t\t\tfor decade in decades:\n\t\t\t\tprint( 'running: {} {} {} {}'.format( model, variable, scenario, decade ) )\n\t\t\t\tfor mask in masks:\n\t\t\t\t\tdomain_num, = np.unique(mask[mask > 0])\n\t\t\t\t\tdomain_name = subdomains.names_dict[ domain_num ].replace( ' ', '' )\n\t\t\t\t\t# run it\n\t\t\t\t\tall_data.update( get_metrics( base_path, variable, model, scenario, decade, mask, domain_name, ncpus ) )\n\n\t\t# write it out to disk\n\t\tif not os.path.exists( output_path ):\n\t\t\tos.makedirs( output_path )\n\t\t\n\t\tprefix = '_'.join([ variable, project, 'decadal', 'summaries', str(begin_out), str(end_out) ])\n\n\t\t# its LONG FORMAT output with all datas in rows for a single var/metric\n\t\toutput_filename = os.path.join( output_path, prefix + '.json' )\n\t\twith open( output_filename, 'w' ) as out_json:\n\t\t\tjson.dump( all_data, out_json )\n\n\t\t# now some panel-y stuff with the output JSON\n\t\tpanel = pd.Panel( deepcopy( all_data ) ).copy()\n\t\tmetrics = ['mean','max','min','stdev']\n\t\tfor metric in metrics:\t\n\t\t\tdf = panel[ :, metric, : ].T\n\t\t\tdf = df[ [ '01', '02', '03', '04', '05', '06', '07', '08', '09', '10', '11', '12' ] ] # sort the months\n\t\t\t# sort the model combos\n\t\t\t# df = df.reindex_axis([ '_'.join([s,v,m]) for v,m,s in itertools.product(scenarios, variables, models) ], 0)\n\t\t\t# strip variable and underscore\n\t\t\t# df.index = [ ' '.join(i.split('_')[:-1]) for i in df.index ]\n\t\t\toutput_filename = os.path.join( output_path, prefix + '_' + metric +'.csv' )\n\t\t\tdf.to_csv( output_filename, sep=',' )\n","sub_path":"snap_scripts/epscor_sc/tabular_test/model_variability_metrics_epscor_se_DECADAL_multidomain_cru.py","file_name":"model_variability_metrics_epscor_se_DECADAL_multidomain_cru.py","file_ext":"py","file_size_in_byte":10248,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"52623427","text":"# Challenge 1\n\ndef collatzSequence(n):\n\n sequence = []\n\n if n <= 0:\n return n\n else:\n while n != 1:\n if n % 2 == 0:\n n = n // 2\n sequence.append(n)\n else:\n n = n * 3 + 1\n sequence.append(n)\n return sequence\n\n# print(collatzSequence(37))\n\n# ------------------------------------------------------------------------------------\n\n# Challenge 2\n\ndef largestPalindrome(n1, n2):\n\n limit1 = range(1, n1 + 1)\n limit2 = range(1, n2 + 1)\n palindromes = [i * j for i in limit1 for j in limit2 if str(i * j) == str(i * j)[::-1]]\n\n return max(palindromes)\n\n# print(largestPalindrome(999, 999))\n\n# ------------------------------------------------------------------------------------\n\n# Challenge 3\n\ndef smallestDivisible(n):\n\n arr = [i for i in range(1, n + 1)]\n limit = 1\n for num in arr:\n limit = limit * num\n \n for i in range(n, limit + 1):\n check = True\n for num in arr:\n if i % num != 0:\n check = False\n break\n \n if check:\n return i\n \n# print(smallestDivisible(20))\n\ncheck_list = [i for i in range(1, 21)]\n\ndef find_solution(step):\n for num in range(step, 999999999, step):\n if all(num % n == 0 for n in check_list):\n return num\n return None\n\nprint(find_solution(2520))\n\n# ------------------------------------------------------------------------------------\n\n# Challenge 4\n\n","sub_path":"Week_4/12-7-18/algorithms_challenge.py","file_name":"algorithms_challenge.py","file_ext":"py","file_size_in_byte":1525,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"317625836","text":"class Solution(object):\n def maxWidthRamp(self, A):\n ans = 0\n m = float('inf')\n for i in sorted(range(len(A)), key = A.__getitem__):\n ans = max(ans, i - m)\n m = min(m, i)\n return ans\n\nimport bisect\n\nclass Solution2(object):\n def maxWidthRamp(self, A):\n N = len(A)\n\n ans = 0\n candidates = [(A[N-1], N-1)]\n # candidates: i's decreasing, by increasing value of A[i]\n for i in xrange(N-2, -1, -1):\n # Find largest j in candidates with A[j] >= A[i]\n jx = bisect.bisect(candidates, (A[i],))\n if jx < len(candidates):\n ans = max(ans, candidates[jx][1] - i)\n else:\n candidates.append((A[i], i))\n\n return ans","sub_path":"cpp/leetcode/962.py","file_name":"962.py","file_ext":"py","file_size_in_byte":771,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"552750773","text":"import csv\n\ndef save_to_file(jobs):\n f = open(\"jobs.csv\", mode=\"w\", encoding=\"utf-8\")\n #w = write, 쓰기 전용\n #r = read, 읽기 전용\n writer = csv.writer(f)\n #csv.writer 함수에 값을 쓸 파일을 불러와 변수로 설정\n writer.writerow([\"title\", \"company\", \"location\", \"link\"])\n #comma로 값을 구분해서 각 열에 넣어줌\n for job in jobs:\n writer.writerow(list(job.values()))\n #job이라는 dictionary에서 value들만을 가져오는 함수\n #이 함수는 dict_values 자료형을 return하므로, list로 형변환 해줌","sub_path":"_nomad-python/0301/save_func.py","file_name":"save_func.py","file_ext":"py","file_size_in_byte":594,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"627703367","text":"import json\nfrom flask import Blueprint, request, current_app\nfrom flask_security import current_user, auth_token_required\nfrom .models import Community, UserRegister\nfrom .response import Response, InvalidArgument\nfrom .photo import save_photo, get_photo_url\n\nbp = Blueprint('communities', __name__)\n\n\n@bp.route('/', methods=['GET'])\ndef get_communities():\n data = request.args\n if current_user.is_authenticated():\n university = current_user.university\n elif 'university' in data:\n university = data['university']\n else:\n return Response.error('Unknown university')\n try:\n results = Community.query\\\n .filter(Community.university == university)\\\n .paginate(int(data.get('page', 1)), int(data.get('per_page', 10)))\n except:\n return Response.error('Invalid argument')\n return Response.success(results.items)\n\n\n@bp.route('/', methods=['GET'])\ndef get_community(id):\n community = Community.query.get(id)\n if community:\n return Response.success(community)\n else:\n return Response.error('Invalid ID')\n\n\n@bp.route('//users', methods=['GET'])\ndef community_users(id):\n community = Community.query.get(id)\n if community:\n registers = UserRegister.query.filter_by(\n community_id=community.id, status='APPROVED').all()\n users = [r.user for r in registers]\n return Response.success(users)\n else:\n return Response.error('Invalid ID')\n\n\n@bp.route('//register_form', methods=['GET'])\ndef get_community_register_form(id):\n community = Community.query.get(id)\n if community:\n\n return Response.success(\n json.loads(community.register_form) if community.register_form else None)\n else:\n return Response.error('Invalid ID')\n\n\n@bp.route('//register', methods=['GET'])\n@auth_token_required\ndef get_community_register(id):\n return Response.success(\n UserRegister.query.filter_by(community_id=id, user_id=current_user.id).first())\n\n\n@bp.route('//register', methods=['POST'])\n@auth_token_required\ndef set_community_register(id):\n community = Community.query.get(id)\n if not community:\n return Response.error('Invalid ID')\n if not community.enable_register:\n return Response.error('This community does\\'t allow register at this time')\n data = request.get_json()\n user_register = UserRegister(**{\n 'community_id': id,\n 'user_id': current_user.id,\n 'answers': json.dumps(data.get('answers')),\n 'status': 'PENDING',\n 'reason': ''\n })\n current_app.db.session.merge(user_register)\n return Response.success()\n\n\n@bp.route('//register/images', methods=['POST'])\n@auth_token_required\ndef community_register_upload_images(id):\n path = 'user/%s/community_register' % current_user.id\n return Response.success(get_photo_url(save_photo(path, id, 'images'), True))","sub_path":"server/iwx/communities.py","file_name":"communities.py","file_ext":"py","file_size_in_byte":2944,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"193346259","text":"# -*- coding: utf-8 -*-\nfrom django.views.generic import ListView\nfrom django.contrib import messages\nfrom django.utils.translation import ugettext_lazy as _\nfrom .models import Product\nfrom apps.partner.models import Affiliate\n\n\nclass ProductListView(ListView):\n template_name = \"products/list.html\"\n model = Product\n context_object_name = 'products'\n\n def post(self, request, *args, **kwargs):\n self.buy_product(request)\n return super(ProductListView, self).get(request, *args, **kwargs)\n\n def buy_product(self, request):\n # just to show how affiliate works.\n pk = None\n for key in request.POST:\n if key.startswith('product'):\n pk = int(key.split(\"_\")[-1])\n break\n if pk:\n product = Product.objects.get(pk=pk)\n messages.add_message(request, messages.INFO,\n _(\"Product %(product)s was bought\" % {\"product\": product.title}))\n if request.aid:\n affiliate = Affiliate.objects.get(aid=request.aid)\n affiliate.reward_affiliate(product.price)\n","sub_path":"example/web_project/apps/products/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1130,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"366907205","text":"# encoding: utf-8\n\"\"\"\n@author: xingyu liao\n@contact: sherlockliao01@gmail.com\n\"\"\"\n\nimport argparse\nimport logging\nimport sys\nimport json\nimport scipy.io\nfrom IPython import embed\n\nimport numpy as np\nimport torch\nimport tqdm\nfrom torch.backends import cudnn\n\nsys.path.append('.')\n\nfrom fastreid.data.datasets import DATASET_REGISTRY\nfrom fastreid.evaluation import evaluate_rank\nfrom fastreid.config import get_cfg\nfrom fastreid.utils.logger import setup_logger\nfrom fastreid.data import build_reid_test_loader\nfrom predictor import FeatureExtractionDemo\nfrom fastreid.utils.visualizer import Visualizer\n\ncudnn.benchmark = True\nlogger = logging.getLogger('fastreid.visualize_result')\n\ndef setup_cfg(args):\n # load config from file and command-line arguments\n cfg = get_cfg()\n cfg.merge_from_file(args.config_file)\n cfg.merge_from_list(args.opts)\n cfg.freeze()\n return cfg\n\n\ndef get_parser():\n parser = argparse.ArgumentParser(description=\"Feature extraction with reid models\")\n parser.add_argument(\n \"--config-file\",\n metavar=\"FILE\",\n help=\"path to config file\",\n )\n parser.add_argument(\n '--parallel',\n action='store_true',\n help='if use multiprocess for feature extraction.'\n )\n parser.add_argument(\n \"--dataset-name\",\n help=\"a test dataset name for visualizing ranking list.\"\n )\n parser.add_argument(\n \"--output\",\n default=\"./vis_rank_list\",\n help=\"a file or directory to save rankling list result.\",\n\n )\n parser.add_argument(\n \"--vis-label\",\n action='store_true',\n help=\"if visualize label of query instance\"\n )\n parser.add_argument(\n \"--num-vis\",\n default=100,\n help=\"number of query images to be visualized\",\n )\n parser.add_argument(\n \"--rank-sort\",\n default=\"ascending\",\n help=\"rank order of visualization images by AP metric\",\n )\n parser.add_argument(\n \"--label-sort\",\n default=\"ascending\",\n help=\"label order of visualization images by cosine similarity metric\",\n )\n parser.add_argument(\n \"--max-rank\",\n default=10,\n help=\"maximum number of rank list to be visualized\",\n )\n parser.add_argument(\n \"--opts\",\n help=\"Modify config options using the command-line 'KEY VALUE' pairs\",\n default=[],\n nargs=argparse.REMAINDER,\n )\n return parser\n\n\nif __name__ == '__main__':\n args = get_parser().parse_args()\n logger = setup_logger()\n cfg = setup_cfg(args)\n test_loader, num_query, dataset = build_reid_test_loader(cfg, args.dataset_name)\n demo = FeatureExtractionDemo(cfg, parallel=args.parallel)\n # dataset = DATASET_REGISTRY.get(args.dataset_name)\n\n logger.info(\"Start extracting image features\")\n feats = []\n pids = []\n camids = []\n for (feat, pid, camid) in tqdm.tqdm(demo.run_on_loader(test_loader), total=len(test_loader)):\n feats.append(feat)\n pids.extend(pid)\n camids.extend(camid)\n\n feats = torch.cat(feats, dim=0)\n q_feat = feats[:num_query]\n g_feat = feats[num_query:]\n q_pids = np.asarray(pids[:num_query])\n g_pids = np.asarray(pids[num_query:])\n q_camids = np.asarray(camids[:num_query])\n g_camids = np.asarray(camids[num_query:])\n\n # compute cosine distance\n #distmat = torch.mm(q_feat, g_feat.t())\n distmat = 1 - torch.mm(q_feat, g_feat.t())\n distmat = distmat.numpy()\n\n result = {'qg_fea': distmat}\n scipy.io.savemat('result.mat',result)\n print('distmat saved as result.mat')\n\n # -----------------------split line-----------------------------------\n\n # result = scipy.io.loadmat('result.mat')\n # distmat = result['qg_fea']\n \n result_dict = {}\n\n q_index = 7533 # query total number: 2900\n\n for i in range(q_index):\n\n index = np.argsort(distmat[i]) #from large to small\n #index = index[::-1]\n\n query_path = dataset.query[i][0]\n # query_path = '../train/pytorch/query/11/7655_c1s1_00002570.png'\n query_path = query_path.split('/')[-1] # get '7655_c1s1_00002570.png'\n query_path = query_path.split('_')[-1] # get '00002570.png'\n\n img_path_list = []\n for j in range(200): # top-200\n img_path = dataset.gallery[index[j]][0]\n # img_path = '../train/pytorch/gallery/99/7655_c1s1_00108716.png'\n img_path = img_path.split('/')[-1] # get '7655_c1s1_00108716.png'\n img_path = img_path.split('_')[-1] # get '00002570.png'\n img_path_list.append(img_path)\n\n result_dict[query_path] = img_path_list\n if i % 500 == 0:\n print('{}/{} processed..........'.format(i+1, q_index))\n\n import datetime\n nowTime = datetime.datetime.now().strftime('%Y-%m-%d-%H-%M-%S')\n\n with open('result_' + str(nowTime) + '.json','w') as fp:\n json.dump(result_dict, fp, indent = 4, separators=(',', ': '))\n # json.dump(result_dict, fp)\n\n print('The result generated................')\n\n","sub_path":"demo/my_visualize_result.py","file_name":"my_visualize_result.py","file_ext":"py","file_size_in_byte":5076,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"636529090","text":"#!/usr/bin/env python\nfrom os.path import *\nfrom epydoc.docbuilder import build_doc_index\nfrom epydoc.docwriter.html import HTMLWriter\nfrom dir import *\n\ndocindex = build_doc_index(['lxml'])\nhtml_writer = HTMLWriter(\n docindex,\n prj_name='os',\n prj_url='http://www.language-binding.net',\n show_private=False,\n show_frames=False)\npath = tempdir()\nhtml_writer.write(path)\nprint(path)\n","sub_path":"python/epydoc/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":397,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"252726918","text":"from utils import *\nfrom consts import *\nimport log\n\nimport wave\nimport math\nimport time\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport tests\n\nimport encoding as enc\n\n\ndef hamming_7_4(bit_array, auto_unpad=True):\n log.debug(\"decoding hamming 7_4,\\trecieved {} bits\".format(len(bit_array)))\n from consts import inv\n assert len(bit_array) % 7 == 0, 'For hamming 7:4 decoding array must be multiple of 7'\n chunks = chunk(bit_array, 7)\n bit_array = np.empty_like([], dtype='bool')\n for l in chunks:\n p1_err, p2_err, p3_err = False, False, False\n if l[4] != ((l[0]+l[1]+l[3]) % 2):\n p1_err = True\n if l[5] != ((l[0]+l[2]+l[3]) % 2):\n p2_err = True\n if l[6] != ((l[1]+l[2]+l[3]) % 2):\n p3_err = True\n\n if p1_err and p2_err and p3_err:\n l[3] = inv[l[3]]\n elif p1_err and p2_err:\n l[0] = inv[l[0]]\n elif p1_err and p3_err:\n l[1] = inv[l[1]]\n elif p2_err and p3_err:\n l[2] = inv[l[2]]\n\n x = l[:4]\n bit_array = np.concatenate((bit_array, x))\n if auto_unpad:\n bit_array = unpad(bit_array, 4)\n log.debug(\"\\t\\t\\t\\t\\t\\treturned {} bits\".format(len(bit_array)))\n return bit_array\n\n\n# def hamming_8_4(bit_array):\n# # print(\"decoding hamming 7_4,\\trecieved {} bits\".format(len(bit_array)))\n# from consts import inv\n# assert len(bit_array) % 8 == 0, 'For hamming 7:4 decoding array must be multiple of 7'\n# chunks = chunk(bit_array, 8)\n# bit_array = np.empty_like([], dtype='bool')\n# for l in chunks:\n# p1_err, p2_err, p3_err, p4_err = 0, 0, 0, 0\n# if l[4] != ((l[0]+l[1]+l[3]) % 2):\n# p1_err = 1\n# if l[5] != ((l[0]+l[2]+l[3]) % 2):\n# p2_err = 1\n# if l[6] != ((l[1]+l[2]+l[3]) % 2):\n# p3_err = 1\n# if l[7] != (np.sum(l[:7]) % 2):\n# p4_err = 1\n#\n# if p1_err and p2_err and p3_err:\n# l[3] = inv[l[3]]\n# elif p1_err and p2_err:\n# l[0] = inv[l[0]]\n# elif p1_err and p3_err:\n# l[1] = inv[l[1]]\n# elif p2_err and p3_err:\n# l[2] = inv[l[2]]\n#\n# if sum([p1_err, p2_err, p3_err, p4_err]) % :\n# raise Exception(\"Double bit flip detected in hamming 8 4\")\n#\n# x = l[:4]\n# bit_array = np.concatenate((bit_array, x))\n# bit_array = unpad(bit_array, 4)\n# # print(\"\\t\\t\\t\\t\\t\\treturned {} bits\".format(len(bit_array)))\n# return bit_array\n\n\ndef decode(bit_count, compression, freqs, coding, modulation, **kwargs):\n bit_rates = get_data_rates(freqs)\n assert len(freqs) == len(bit_rates), 'Must have same number of specified frequencies and data rates'\n\n # TODO Fix\n if coding == 'hamming':\n bit_count = bit_count * 7//4\n # Test data for plotting\n test_bit_streams = split_data_into_streams(enc.hamming_7_4(tests.testbits, auto_pad=True), bit_rates)\n else:\n test_bit_streams = split_data_into_streams(tests.testbits, bit_rates)\n\n with wave.open('rec/' + 'bin.wav') as f:\n audio = f.readframes(-1)\n audio = np.frombuffer(audio, dtype='int16')\n\n # Demodulate\n coded_bit_streams = demodulate(bit_count, audio, freqs, bit_rates, modulation, **kwargs)\n\n bit_streams = []\n for stream in coded_bit_streams:\n # Decode\n if coding == 'hamming':\n log.info(\"Decoding: Hamming\")\n bit_streams.append(hamming_7_4(stream))\n else:\n log.info(\"Decoding: None\")\n bit_streams = coded_bit_streams\n\n # Join streams\n ret = []\n for stream in bit_streams:\n ret.extend(stream)\n\n # Decompress\n log.info(\"Decompression: None\")\n\n return ret\n\n\ndef demodulate(bit_count, signal, freqs, bit_rates, modulation, **kwargs):\n # Find start\n i_best = find_start_sample(signal, **kwargs)\n signal = signal[i_best:]\n\n # Plot signal after sync\n if kwargs.get('plot_main'):\n plt.figure('main')\n plt.plot(signal)\n plt.draw()\n\n # Calculate bit lengths of each stream\n stream_lengths = get_split_stream_lengths(bit_count, bit_rates)\n\n bit_streams = []\n for freq, bit_rate, stream_length in zip(freqs, bit_rates, stream_lengths):\n if modulation == 'psk':\n log.info(\"Demodulation: PSK\")\n bit_streams.append(demodulate_psk(signal, freq, bit_rate, bit_count, **kwargs))\n elif modulation == 'simple':\n log.info(\"Demodulation: Simple\")\n bit_streams.append(demodulate_simple(signal, freq, bit_rate, bit_count, **kwargs))\n\n return bit_streams\n\n\ndef generate_bit_centres(bit_rate, bit_count=-1):\n \"\"\" Generates the sample number for the centre of each symbol for PSK\"\"\"\n n = 0\n while True:\n ctr = round((n + 0.5) * SAMPLE_RATE / bit_rate)\n yield ctr\n n += 1\n if 0 < bit_count < n*2:\n break\n\n\ndef get_psk_magnitudes(conv, no_of_bits, phase_shift, bit_centre_generator, plot=False):\n ret = []\n for i in range(no_of_bits):\n bit_ctr = next(bit_centre_generator)\n sin_mag = conv[bit_ctr]\n cos_mag = conv[bit_ctr + phase_shift]\n ret.append((sin_mag, cos_mag))\n if plot:\n plot_complex(sin_mag, cos_mag, 'fig1', 'rx')\n return ret\n\n\ndef get_transform_matrix(magnitudes):\n \"\"\"\"\n Gets a least squares solution to mapping the first four symbols\n to known true values.\n \"\"\"\n a = []\n for sin_mag, cos_mag in magnitudes[:4]:\n a.append([sin_mag, cos_mag])\n a = np.asarray(a)\n b = np.asarray([[0, -1], [-1, 0], [0, 1], [1, 0]])\n x, _c, _d, _e = np.linalg.lstsq(a, b)\n return x\n\n\ndef get_psk_symbol_stream(magnitudes, plot=False):\n \"\"\"\n Takes the transformed magnitudes (i.e mapped onto 1,0 etc) and returns\n a list of symbols: 'a', 'b', 'c', 'd'\n \"\"\"\n symbol_stream = []\n for i, mags in enumerate(magnitudes):\n sin_mag, cos_mag = mags\n if sin_mag > cos_mag:\n if cos_mag > -sin_mag:\n symbol_stream.append('a')\n graph_format = 'rx'\n else:\n symbol_stream.append('b')\n graph_format = 'gx'\n else:\n if cos_mag > -sin_mag:\n symbol_stream.append('c')\n graph_format = 'bx'\n else:\n symbol_stream.append('d')\n graph_format = 'yx'\n\n if plot:\n plt.figure('complex2')\n plt.plot(sin_mag, cos_mag, graph_format)\n return symbol_stream\n\n\ndef demodulate_psk(signal, freq, bit_rate, bit_count, **kwargs):\n bit_pair_centres = generate_bit_centres(bit_rate)\n # No of samples in quarter wavelength shift\n phase_shift = round(SAMPLE_RATE / freq / 4)\n\n filter = get_bandpass(freq, SAMPLE_RATE, **kwargs)\n conv = np.convolve(filter, signal, mode='same')\n\n if kwargs.get('plot_conv'):\n plot_psk_conv(freq, conv, signal, generate_bit_centres(bit_rate, bit_count + 8 + 16*7//4), phase_shift)\n\n # Decode data frame\n df_magnitudes = get_psk_magnitudes(conv, 4 + 8*7//4, phase_shift, bit_pair_centres, plot=kwargs.get('plot_complex'))\n x = get_transform_matrix(df_magnitudes)\n tfd_df_magnitudes = np.matmul(df_magnitudes, x)\n df_symbol_stream = get_psk_symbol_stream(tfd_df_magnitudes, kwargs.get('plot_complex'))\n\n # Build map between symbols and bits\n for y in range(4):\n for z in range(4):\n if y != z:\n if df_symbol_stream[y] == df_symbol_stream[z]:\n plt.show()\n raise Exception('Same symbol mapped twice')\n\n symbol_map = dict()\n symbol_map[df_symbol_stream[0]] = [1, 1]\n symbol_map[df_symbol_stream[1]] = [1, 0]\n symbol_map[df_symbol_stream[2]] = [0, 1]\n symbol_map[df_symbol_stream[3]] = [0, 0]\n\n coded_df_bits = []\n for symbol in df_symbol_stream[4:]:\n coded_df_bits.extend(symbol_map[symbol])\n log.debug(\"Coded bit count frame: {}\".format(''.join([str(i) for i in coded_df_bits])))\n df_bits = hamming_7_4(coded_df_bits, auto_unpad=False)\n bit_count = int(''.join([str(bit) for bit in df_bits]), 2)\n\n log.debug(\"Data frame bits: {}\".format(''.join([str(i) for i in df_bits])))\n log.debug(\"no of bits to recieve: {}\".format(bit_count))\n\n assert bit_count % 2 == 0, 'Error in recieved bit count, must be even for psk after padding'\n symbol_count = bit_count//2\n\n data_magnitudes = get_psk_magnitudes(conv, symbol_count, phase_shift, bit_pair_centres)\n tfd_data_magnitudes = np.matmul(data_magnitudes, x)\n data_symbol_stream = get_psk_symbol_stream(tfd_data_magnitudes, kwargs.get('plot_complex'))\n\n data_stream = []\n for symbol in data_symbol_stream:\n data_stream.extend(symbol_map[symbol])\n\n # Unpad for PSK\n bit_stream = unpad(data_stream, 2)\n\n return bit_stream\n\n\ndef plot_psk_conv(freq, conv, signal, bit_pair_centres, phase_shift):\n f, (ax1, ax2) = plt.subplots(2, sharex=True, sharey=True)\n ax1.set_title('Convolution for freq = {}'.format(str(freq)))\n ax2.set_title('Signal'.format(str(freq)))\n ax1.plot(conv)\n ax2.plot(signal)\n for i, bit_ctr in enumerate(bit_pair_centres):\n ax1.axvline(x=bit_ctr, color='g')\n ax2.axvline(x=bit_ctr, color='g')\n ax1.axvline(x=bit_ctr + phase_shift, color='r')\n ax2.axvline(x=bit_ctr + phase_shift, color='r')\n\n\ndef plot_complex(sin_mag, cos_mag, fig, graph_format='rx'):\n if fig == 'fig1':\n plt.figure('complex1')\n plt.title('First 4 symbols')\n elif fig == 'fig2':\n plt.figure('complex2')\n plt.title('All complex points')\n else:\n raise Exception(\"Invalid fig\")\n plt.xlabel('R')\n plt.ylabel('I')\n plt.grid(True)\n plt.axes().set_aspect('equal', 'datalim')\n plt.plot(sin_mag, cos_mag, graph_format)\n\n\ndef find_start_sample(signal, **kwargs):\n sync_pulse = get_sync_pulse()\n sig = signal[:SAMPLE_RATE * 2]\n conv = np.convolve(sync_pulse, sig, mode='full')\n i_best = np.argmax(conv)\n if kwargs.get('plot_sync'):\n # Plot sync\n plt.figure('sync')\n # plt.plot(conv / max(conv), color='y')\n plt.plot(sig, color='r')\n plt.axvline(x=i_best, color='g')\n return i_best\n\n\ndef demodulate_simple(signal, freq, bit_rate, bit_count, **kwargs):\n # Convolve and store conv values at bit boundaries\n # bit_width = SAMPLE_RATE / rate\n bit_ctrs = [round((n+0.4) * SAMPLE_RATE/bit_rate) for n in range(bit_count)]\n duration = 1000 / bit_rate\n filter = get_bandpass(freq, SAMPLE_RATE, **kwargs)\n conv = np.convolve(filter, signal, mode='same')\n # conv = conv[len(filter)//2:]\n if kwargs.get('plot_conv'):\n plot_simple_conv(freq, bit_ctrs, conv)\n\n conv_values = [np.sum(abs(conv[bit_ctr-3:bit_ctr+3])) for i, bit_ctr in enumerate(bit_ctrs)]\n\n if kwargs.get('plot_conv') or kwargs.get('plot_main'):\n plt.draw()\n\n # Thresholding\n bit_stream = []\n threshold = np.mean(conv_values)\n for conv_value in conv_values:\n if conv_value > threshold:\n bit_stream.append(1)\n else:\n bit_stream.append(0)\n\n return bit_stream\n\n\ndef plot_simple_conv(freq, bit_ctrs, conv):\n plt.figure('conv for freq = {}'.format(str(freq)))\n plt.plot(conv)\n for i, bit_ctr in enumerate(bit_ctrs):\n plt.figure('conv for freq = {}'.format(str(freq)))\n plt.axvline(x=bit_ctr, color='r')","sub_path":"decoding.py","file_name":"decoding.py","file_ext":"py","file_size_in_byte":11494,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"641828017","text":"def g(x,a,b,c):\n return (-c-(x*x*a))/b\ndef check(w,a,b,c):\n x=g(w,a,b,c);y=g(x,a,b,c);z=g(y,a,b,c)\n if abs(x-y)>abs(y-z):\n return True\n else:\n return False\n\nprint(\"Assuming the equation as aX2+bX+c=0\\nEnter the value of a,b and c correspondingly:\")\na,b,c=map(int,input().split())\nif (b*b-4*a*c)>=0:\n x=float(2);y=float(3)\n while 1:\n if check(x,a,b,c):\n break\n elif check(y,a,b,c):\n x=y\n break\n else:\n x-=1;y+=1\n y=g(x,a,b,c)\n while round(x,6)!=round(y,6):\n x=y;y=g(y,a,b,c) \n print(\"The root of this equation is\",round(x,6))\nelse:\n print(\"The equation has no root of real number.\")\n","sub_path":"Iterative.py","file_name":"Iterative.py","file_ext":"py","file_size_in_byte":692,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"52584199","text":"import copy\n\n\ndef getRow(rowIndex):\n rowIndex = rowIndex + 1\n previous = []\n tempList = []\n for const in range(0, rowIndex):\n tempList.append(1)\n for a in range(1, const):\n tempList[a] = previous[a] + previous[a - 1]\n previous = copy.deepcopy(tempList)\n return previous\n\n\nprint(getRow(0))\n","sub_path":"LeetCode/119.pascalTriangle.py","file_name":"119.pascalTriangle.py","file_ext":"py","file_size_in_byte":336,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"8933348","text":"import RPi.GPIO as GPIO\nimport time\nimport os\nGPIO.setmode(GPIO.BCM)\n##GPIO.setmode(GPIO.BOARD)\n#GPIO.setwarnings(False)\n\n## note=after calling GPIO.cleanup() function all data on display will get erase.\n## You cannot use __send_data(), __send() functions and any variables used\n## in all functions of this library. The functions which available for user is\n## Print(note that capital P),clear,shift,begin,setCursor,blinkCursorOn,\n## blinkCursorOff and The variables which available for user is right and left\n## which used to indicated direction for shift the display.thanks for using\n## this library. for more details or query you can mail me at\n## shubham@electro-passion.com \nclass lcd:\n right=True\n left=False\n __cmd=False\n __data=True\n def __send_data(self,value,signal):\n GPIO.output(self.__RS,signal)\n self.__send(value>>4)\n self.__send(value)\n time.sleep(0.001) \n \n def __send(self,val):\n self.__val=val\n for i in range (0,4):\n GPIO.output(self.__D[i],((self.__val>>i) & 0x01))\n GPIO.output(self.__EN,False)\n time.sleep(0.000001)\n GPIO.output(self.__EN,True)\n time.sleep(0.000001)\n GPIO.output(self.__EN,False)\n time.sleep(0.0001)\n\n def Print(self,text):\n self.__text=str(text)\n self.__length=len(self.__text)\n for i in range (0,self.__length):\n self.__a=ord(self.__text[i])\n self.__send_data(self.__a,self.__data)\n\n def clear(self):\n self.__send_data(0x01,self.__cmd)\n \n def setCursor(self,row,col):\n self.__col=col-1\n self.__row=row\n if(self.__row==1):\n self.__pos=0x80\n if(self.__row==2):\n self.__pos=0xC0\n self.__cursor=self.__pos+self.__col\n self.__send_data(self.__cursor,self.__cmd) \n \n def begin(self,d4,d5,d6,d7,rs,en):\n self.__D=[d4,d5,d6,d7]\n self.__RS=rs\n self.__EN=en\n for i in range(0,4):\n GPIO.setup(self.__D[i],GPIO.OUT)\n GPIO.setup(self.__RS,GPIO.OUT)\n GPIO.setup(self.__EN,GPIO.OUT)\n time.sleep(0.050)\n self.__send_data(0x30,self.__cmd)##first try\n time.sleep(0.05)\n self.__send_data(0x30,self.__cmd)##sencond try\n time.sleep(0.05)\n self.__send_data(0x30,self.__cmd)##third try\n time.sleep(0.0015)\n self.__send_data(0x20,self.__cmd)##final go\n self.__send_data(0x28,self.__cmd)##select 4 bit, mode 2 lins ,5x7 font\n self.__send_data(0x01,self.__cmd)##clear screen\n self.__send_data(0x06,self.__cmd)##display ON\n self.__send_data(0x80,self.__cmd)## bring cursor to position 0 of line 1\n self.__send_data(0x0C,self.__cmd)## turn display ON for cursor blinking\n\n def shift(self,direction,count):\n self.__direction=direction\n self.__count=count\n if(self.__direction==self.left):\n for i in range (0,self.__count):\n self.__send_data(0x18,self.__cmd)\n time.sleep(1)\n if(self.__direction==self.right):\n for i in range (0,self.__count):\n self.__send_data(0x1C,self.__cmd)\n time.sleep(1)\n def blinkCursorOn(self):\n self.__send_data(0x0F,self.__cmd)\n \n def blinkCursorOff(self):\n self.__send_data(0x0C,self.__cmd)\n","sub_path":"Training/Rpi_lcd/lcd.py","file_name":"lcd.py","file_ext":"py","file_size_in_byte":3388,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"270083813","text":"import imageio\r\nimport time\r\nimport numpy as np\r\nimport tensorflow as tf\r\nfrom agent import AtariDQN\r\n\r\n\r\nclass PlayAtari(AtariDQN):\r\n def __init__(self, env, path):\r\n AtariDQN.__init__(self, env)\r\n self.env = env\r\n self.path = path\r\n self.captured = []\r\n self._load_model()\r\n\r\n def _load_model(self):\r\n ckpt = tf.train.get_checkpoint_state(self.path)\r\n self.saver.restore(self.sess, ckpt.model_checkpoint_path)\r\n print('Session has been restored !')\r\n\r\n def next_move(self, state):\r\n action = self.q_values.eval(feed_dict={self.s: [np.float32(state)]})\r\n action = np.argmax(action)\r\n return action\r\n\r\n def play(self, num_episodes, make_gif=False):\r\n for ep in range(num_episodes):\r\n done = False\r\n obs = self.env.reset()\r\n prev_obs = obs\r\n self.ep_reward = 0\r\n self.captured = []\r\n self.captured.append(obs)\r\n state = self.init_memory(obs, prev_obs)\r\n while not done:\r\n action = self.next_move(state)\r\n obs, reward, done, _ = self.env.step(action)\r\n self.captured.append(obs)\r\n obs = self._preprocess(obs)\r\n obs = np.reshape(obs, (self.height, self.width, 1))\r\n state = np.append(state[:, :, 1:], obs, axis=-1)\r\n self.env.render()\r\n self.ep_reward += reward\r\n time.sleep(0.02)\r\n print('Episode: {}, Score: {}'.format(ep + 1, self.ep_reward))\r\n if make_gif:\r\n string = '{}ep{}_{}.gif'\r\n imageio.mimsave(string.format(self.path, ep + 1, self.ep_reward), self.captured, duration=0.0286)\r\n self.env.close()\r\n","sub_path":"play.py","file_name":"play.py","file_ext":"py","file_size_in_byte":1783,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"138678515","text":"from wx import *\r\nimport wx.html2 as webview\r\n\r\n#----------------------------------------------------------------------\r\n\r\nclass Web(Panel):\r\n def __init__(self, parent, direccionWeb):\r\n Panel.__init__(self, parent, -1)\r\n self.current = direccionWeb\r\n sizer = BoxSizer(VERTICAL)\r\n btnSizer = BoxSizer(HORIZONTAL)\r\n self.wv = webview.WebView.New(self)\r\n sizer.Add(self.wv, 1, EXPAND)\r\n self.SetSizer(sizer)\r\n\r\n b = Button(self, -1, \"Refrescar Página\", style=BU_EXACTFIT)\r\n self.Bind(EVT_BUTTON, self.botonRefrescar, b)\r\n sizer.Add(btnSizer, 0, EXPAND)\r\n btnSizer.Add(b, 0, EXPAND|ALL, 2)\r\n\r\n self.wv.LoadURL(self.current)\r\n\r\n def botonRefrescar(self, evt):\r\n self.wv.Reload()\r\n\r\n\r\n","sub_path":"efis/Alvaro&Lucas/accederPaginaExterna.py","file_name":"accederPaginaExterna.py","file_ext":"py","file_size_in_byte":778,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"90240265","text":"import sys\nimport cv2\nimport configparser\nfrom map import *\n\nfrom PyQt5.QtCore import Qt, QPoint, QRect\nfrom PyQt5.QtGui import QPainter, QPixmap, QPen, QImage\nfrom PyQt5.QtWidgets import QApplication, QWidget, QLabel\n\n\n\n\nclass Ditu_fenbushi(QWidget, Ui_map):\n \"\"\"地图操作窗口\"\"\"\n def __init__(self, parent=None):\n super(Ditu_fenbushi, self).__init__(parent)\n self.setupUi(self)\n\n # 新建MyLabel的类\n self.map_position = Mylabel_fenbushi(self.scrollAreaWidgetContents)\n # 读取地图文件\n img = cv2.imread('./map.png')\n # 获取图像高度和宽度值\n height, width, bytesPerComponent = img.shape\n # 设置地图尺寸,为坐标计算做准备\n self.map_position.setGeometry(QRect(0, 0, width, height))\n print(self.map_position.width(), self.map_position.height())\n\n bytesPerLine = 3 * width\n cv2.cvtColor(img, cv2.COLOR_BGR2RGB, img)\n QImg = QImage(img.data, width, height, bytesPerLine, QImage.Format_RGB888)\n self.pixmap = QPixmap.fromImage(QImg)\n\n self.map_position.setPixmap(self.pixmap)\n # CrossCursor 十字型 PointingHandCursor 手型 ArrowCursor 箭头型\n self.map_position.setCursor(Qt.ArrowCursor)\n\n\n # self.show()\n # 重写地图页面的关闭窗口事件\n def closeEvent(self, e):\n # global fenbushi_flag\n self.box = QMessageBox(QMessageBox.Warning, \"系统提示信息\", \"是否完成配置并退出地图?\")\n qyes = self.box.addButton(self.tr(\"是\"), QMessageBox.YesRole)\n qno = self.box.addButton(self.tr(\"否\"), QMessageBox.NoRole)\n self.box.exec_()\n if self.box.clickedButton() == qyes:\n print(self.map_position.position,self.map_position.position_str)\n print(type(self.map_position.position))\n # print(fenbushi_list, len(fenbushi_list))\n # print(fenbushi_flag)\n # if fenbushi_flag == 1:\n # fenbushi_point[0].setText(self.map_position.fenbushi_poi)\n # fenbushi_list[0].setText(self.map_position.position)\n # elif fenbushi_flag == 2:\n # fenbushi_point[1].setText(self.map_position.fenbushi_poi)\n # fenbushi_list[1].setText(self.map_position.position)\n # elif fenbushi_flag == 3:\n # fenbushi_point[2].setText(self.map_position.fenbushi_poi)\n # fenbushi_list[2].setText(self.map_position.position)\n # elif fenbushi_flag == 4:\n # fenbushi_point[3].setText(self.map_position.fenbushi_poi)\n # fenbushi_list[3].setText(self.map_position.position)\n # elif fenbushi_flag == 5:\n # fenbushi_point[4].setText(self.map_position.fenbushi_poi)\n # fenbushi_list[4].setText(self.map_position.position)\n # elif fenbushi_flag == 6:\n # fenbushi_point[5].setText(self.map_position.fenbushi_poi)\n # fenbushi_list[5].setText(self.map_position.position)\n # elif fenbushi_flag == 7:\n # fenbushi_point[6].setText(self.map_position.fenbushi_poi)\n # fenbushi_list[6].setText(self.map_position.position)\n # elif fenbushi_flag == 8:\n # fenbushi_point[7].setText(self.map_position.fenbushi_poi)\n # fenbushi_list[7].setText(self.map_position.position)\n # elif fenbushi_flag == 9:\n # fenbushi_point[8].setText(self.map_position.fenbushi_poi)\n # fenbushi_list[8].setText(self.map_position.position)\n # elif fenbushi_flag == 10:\n # fenbushi_point[9].setText(self.map_position.fenbushi_poi)\n # fenbushi_list[9].setText(self.map_position.position)\n # elif fenbushi_flag == 11:\n # fenbushi_point[10].setText(self.map_position.fenbushi_poi)\n # fenbushi_list[10].setText(self.map_position.position)\n # elif fenbushi_flag == 12:\n # fenbushi_point[11].setText(self.map_position.fenbushi_poi)\n # fenbushi_list[11].setText(self.map_position.position)\n # elif fenbushi_flag == 13:\n # fenbushi_point[12].setText(self.map_position.fenbushi_poi)\n # fenbushi_list[12].setText(self.map_position.position)\n # elif fenbushi_flag == 14:\n # fenbushi_point[13].setText(self.map_position.fenbushi_poi)\n # fenbushi_list[13].setText(self.map_position.position)\n # elif fenbushi_flag == 15:\n # fenbushi_point[14].setText(self.map_position.fenbushi_poi)\n # fenbushi_list[14].setText(self.map_position.position)\n\n e.accept()\n QWidget.closeEvent(self, e)\n\n\n\n # sys.exit().accept()\n\n else:\n e.ignore()\n\n# 重写新的Qlabel类-对应分布式地图展示\nclass Mylabel_fenbushi(QLabel):\n def __init__(self, parent=None):\n super(Mylabel_fenbushi, self).__init__(parent)\n self.x0 = 0\n self.y0 = 0\n self.position = []\n self.begin_point = QPoint()\n self.end_point = QPoint()\n self.position_point = []\n self.position_str = []\n self.flag_click = None # 左键False 右键 True\n self.flag_left = False\n self.flag_right = False\n self.flag_mid = False\n\n self.pen1 = QPen()\n self.pen1.setColor(Qt.blue)\n self.pen1.setWidth(10)\n self.pen2 = QPen()\n self.pen2.setColor(Qt.red)\n self.pen2.setWidth(10)\n\n # 创建一个Qlabal实现鼠标位置跟踪,展示转变后坐标\n self.label = QLabel(self)\n self.label.setText('')\n # 设定初始位置\n print(self.label.height())\n self.label.move(300, 300)\n # 背景色和字体大小设置\n self.label.setStyleSheet('background:white;font-size:15px;')\n # 开启鼠标位置跟踪\n self.setMouseTracking(True)\n print(self.width(), self.height())\n\n\n def mousePressEvent(self, event):\n if event.button() == Qt.LeftButton:\n self.flag_left = True\n # self.begin_point = event.pos()\n # self.x0 = event.x()\n # self.y0 = event.y()\n # self.end_point = event.pos()\n # self.update()\n elif event.button() == Qt.RightButton:\n self.flag_right = True\n\n # 鼠标移动\n def mouseMoveEvent(self, event):\n # # if event.buttons() == Qt.LeftButton:\n # # self.end_point = event.pos()\n # if event.buttons() and Qt.LeftButton:\n # self.endPoint = event.pos()\n #\n # # self.update()\n x = event.localPos().x()\n y = event.localPos().y()\n self.label.move(x, y)\n # 设置标签的显示\n p_move = \",\".join([str(i) for i in [int((x - self.width() / 2) * 0.05 * 1000) / 1000,\n int((self.height() / 2 - y) * 0.05 * 1000) / 1000, 0]])\n self.label.setText('(' + p_move + ')')\n # 自适应大小:因为x的坐标可能是0,有可能是100,y同理,所以label长度需要自适应\n self.label.adjustSize()\n print(self.height(), self.width())\n print(\"原先\", x, y)\n print(\"当前鼠标坐标:\", p_move)\n\n def mouseReleaseEvent(self, event):\n painter_p = QPainter(self.pixmap())\n self.end_point = event.pos()\n\n if event.button() == Qt.LeftButton:\n self.position_point.append(self.end_point)\n print(int((self.position_point[-1].x()-self.width()/2)*0.05*1000)/1000,type((self.position_point[-1].x()-self.width()/2)*0.05))\n # 将坐标点坐标转换为str类型\n position_int_str =\",\".join( [str(i) for i in[int((self.position_point[-1].x()-self.width()/2)*0.05*1000)/1000, int((self.height()/2-self.position_point[-1].y())*0.05*1000)/1000, 0]])\n # 各个坐标点写入列表\n self.position_str.append(position_int_str)\n # print(round(self.position_str[0],3))\n self.fenbushi_poi = self.position_str[0]\n # print(self.fenbushi_poi)\n self.fenbushi_poilist = self.position_str[1:]\n self.position= \";\".join(self.fenbushi_poilist)\n # print(self.height(), self.width())\n # # self.position.append([(self.x0-self.map_position.width()/2)*0.05, (self.map_position.height()/2-self.y0)*0.05, 0])\n print(self.position)\n\n # 设置线颜色(蓝)粗细形式\n if len(self.position_point) == 1:\n painter_p.setPen(QPen(self.pen1))\n painter_p.drawPoint(self.position_point[0])\n else:\n painter_p.setPen(QPen(self.pen2))\n # 画点\n # painter_p.drawPoint(self.begin_point)\n painter_p.drawPoint(self.position_point[-1])\n elif event.button() == Qt.RightButton and len(self.position_point) > 0:\n painter_p.setPen(QPen(Qt.white, 10))\n painter_p.drawPoint(self.position_point[-1])\n del self.position_point[-1]\n # 各个坐标点写入列表\n del self.position_str[-1]\n # print(round(self.position_str[0],3))\n self.fenbushi_poi = self.position_str[0]\n # print(self.fenbushi_poi)\n self.fenbushi_poilist = self.position_str[1:]\n self.position = \";\".join(self.fenbushi_poilist)\n # print(self.height(), self.width())\n # # self.position.append([(self.x0-self.map_position.width()/2)*0.05, (self.map_position.height()/2-self.y0)*0.05, 0])\n print(self.position)\n\n self.update()\n\n\n\n def paintEvent(self, event):\n super().paintEvent(event)\n\n # 实现双缓冲\n painter2 = QPainter(self)\n painter2.drawPixmap(0, 0, self.pixmap())\n\n\n\n\nif __name__ == '__main__':\n app = QApplication(sys.argv)\n demo = Ditu_fenbushi()\n demo.show()\n sys.exit(app.exec_())","sub_path":"fenbushi_test.py","file_name":"fenbushi_test.py","file_ext":"py","file_size_in_byte":10070,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"360802169","text":"\"\"\"\nDefines GenericForeignFileField, a subclass of GenericRelation from\ndjango.contrib.contenttypes.\n\"\"\"\nimport six\nfrom six.moves import reduce\n\nimport operator\n\nimport django\nfrom django.contrib.contenttypes.models import ContentType\nfrom django.core.exceptions import ObjectDoesNotExist\nfrom django.core.files.base import File\nfrom django.core.files.uploadedfile import UploadedFile\nfrom django.db import connection, router, models\nfrom django.db.models.deletion import DO_NOTHING\nfrom django.db.models.fields.files import FieldFile, FileDescriptor\nfrom django.db.models.fields.related import RelatedField, Field, ManyToOneRel\nfrom django.utils.functional import curry\n\ntry:\n # Django 1.8+\n from django.contrib.contenttypes.fields import GenericRelation\nexcept ImportError:\n from django.contrib.contenttypes.generic import GenericRelation\n\ntry:\n # Django 1.8+\n from django.contrib.contenttypes.admin import GenericInlineModelAdmin\nexcept ImportError:\n from django.contrib.contenttypes.generic import GenericInlineModelAdmin\n\ntry:\n # Django 1.7+\n from django.contrib.contenttypes.fields import GenericRel\nexcept ImportError:\n from django.contrib.contenttypes.generic import GenericRel\n\ntry:\n from django.db.models.fields.related import ForeignObject, ForeignObjectRel\nexcept ImportError:\n # Django <= 1.5\n class ForeignObject(RelatedField, Field):\n pass\n\n class ForeignObjectRel(ManyToOneRel):\n def __init__(self, field, to, **kwargs):\n self.related_query_name = kwargs.pop('related_query_name', None)\n self.field = field\n super(ForeignObjectRel, self).__init__(to, self.field.name, **kwargs)\n\nfrom generic_plus.forms import (\n generic_fk_file_formfield_factory, generic_fk_file_widget_factory)\n\n\nclass GenericForeignFileField(GenericRelation):\n \"\"\"\n The base class for GenericForeignFileField; adds descriptors to the model.\n\n This field accepts the same keyword arguments as models.FileField. It\n enables GenericForeignFileField to act as both a FileField and a\n GenericForeignKey.\n\n If assigned to a model with name ``field_name``, allows retrieval of\n the generic related object's information by several attributes (via\n descriptors):\n\n getattr(instance, field_name):\n An instance of FieldFile, with obj.field_name.related_object\n as the generic related instance (or None if there is no\n related object). A getattr on ``field_name`` will perform a\n database query.\n getattr(instance, '%%s_raw' %% field_name):\n An instance of FieldFile that does not sync with the generic\n related object. Use this if you need to retrieve the file path\n but do not want to make a database query.\n getattr(instance, '%%s_generic_rel' %% field_name):\n The generic related manager for the field.\n \"\"\"\n\n file_kwargs = None\n file_field = None\n\n generic_descriptor = None\n file_descriptor = None\n\n file_descriptor_cls = FileDescriptor\n file_field_cls = models.FileField\n rel_file_field_name = 'file'\n field_identifier_field_name = None\n\n def __init__(self, to, rel_file_field_name=None, field_identifier=\"\",\n missing_file_fallback=True, **kwargs):\n \"\"\"\n Parameters\n ----------\n to : Model or str\n rel_file_field_name : str\n Name of the FileField on the generic related model (e.g. \"image\",\n \"file\" [the default])\n field_identifier : str\n A string to uniquely identify the field on the model, allowing\n multiple GenericForeignFileFields to point to a single model class\n missing_file_fallback : bool\n If set to True (the default), the GenericForeignFileField widget\n will show the admin's file field widget in the event that there is\n a value on the model for the file field, but no corresponding row\n in the table with the generic foreign key.\n \"\"\"\n self.rel_file_field_name = rel_file_field_name or self.rel_file_field_name\n self.field_identifier = field_identifier\n self.missing_file_fallback = missing_file_fallback\n\n self.file_kwargs = {\n 'editable': False,\n 'default': '',\n 'blank': True,\n 'upload_to': kwargs.pop('upload_to', None),\n 'storage': kwargs.pop('storage', None),\n 'max_length': kwargs.pop('max_length', 100),\n 'db_index': kwargs.pop('db_index', False),\n # width_field and height_field will be removed from this dict\n # if, in contribute_to_related_class(), the related FileField\n # is not found to be an instance of models.ImageField.\n 'width_field': kwargs.pop('width_field', None),\n 'height_field': kwargs.pop('height_field', None),\n }\n\n symmetrical = kwargs.pop('symmetrical', True)\n\n if issubclass(GenericRel, ForeignObjectRel):\n # Django 1.6\n kwargs['rel'] = GenericRel(self, to,\n related_name=kwargs.pop('related_name', None),\n limit_choices_to=kwargs.pop('limit_choices_to', None))\n kwargs['rel'].on_delete = DO_NOTHING\n else:\n # Django <= 1.5\n kwargs['rel'] = GenericRel(to,\n related_name=kwargs.pop('related_name', None),\n limit_choices_to=kwargs.pop('limit_choices_to', None),\n symmetrical=symmetrical)\n\n # Override content-type/object-id field names on the related class\n self.object_id_field_name = kwargs.pop(\"object_id_field\", \"object_id\")\n self.content_type_field_name = kwargs.pop(\"content_type_field\", \"content_type\")\n self.field_identifier_field_name = kwargs.pop(\"field_identifier_field\", self.field_identifier_field_name)\n\n self.for_concrete_model = kwargs.pop(\"for_concrete_model\", True)\n\n kwargs.update({\n 'blank': True,\n 'editable': True,\n 'serialize': False,\n 'max_length': self.file_kwargs['max_length'],\n })\n\n if isinstance(self, ForeignObject):\n # Django 1.6\n super(GenericRelation, self).__init__(\n to, to_fields=[],\n from_fields=[self.object_id_field_name], **kwargs)\n else:\n # Django <= 1.5\n models.Field.__init__(self, **kwargs)\n\n self.file_kwargs['db_column'] = kwargs.get('db_column', self.name)\n\n if django.VERSION[:2] in ((1, 6), (1, 7)):\n # Prior to Django 1.6, Model._meta.get_field_by_name() never returned\n # virtual fields. django-generic-plus takes advantage of this fact in\n # order to have _both_ a virtual field (the generic relation) and a\n # local field (the FileField). In Django 1.6, get_field_by_name() will\n # return the virtual field if the field has the 'related' attr. To get\n # around this new inconvenience, we make an @property for related that\n # raises an AttributeError while Model._meta.init_name_map() is being\n # executed.\n def do_related_class(self, other, cls):\n from django.db.models.related import RelatedObject\n\n self.set_attributes_from_rel()\n self._related = RelatedObject(other, cls, self)\n if not cls._meta.abstract:\n self.contribute_to_related_class(other, self._related)\n\n @property\n def related(self):\n if hasattr(self.model._meta, '_name_map') or not hasattr(self.model._meta, '_related_objects_cache'):\n return self._related\n elif hasattr(self.model._meta, '_related_objects_cache') and self._related not in self.model._meta._related_objects_cache:\n return self._related\n else:\n raise AttributeError(\"'%s' object has no attribute 'related'\" % type(self).__name__)\n\n def contribute_to_class(self, cls, name):\n self.generic_rel_name = '%s_generic_rel' % name\n self.raw_file_field_name = '%s_raw' % name\n self.file_field_name = name\n\n if hasattr(self, 'set_attributes_from_name'):\n self.set_attributes_from_name(name)\n self.file_kwargs['db_column'] = self.db_column or self.attname\n\n # Save a reference to which model this class is on for future use\n self.model = cls\n\n super(GenericForeignFileField, self).contribute_to_class(cls, name)\n\n if django.VERSION >= (1, 8):\n self.column = self.file_kwargs['db_column']\n\n if not isinstance(self.file_field_cls, models.ImageField):\n self.file_kwargs.pop('width_field', None)\n self.file_kwargs.pop('height_field', None)\n else:\n if not self.file_kwargs['width_field']:\n del self.file_kwargs['width_field']\n if not self.file_kwargs['height_field']:\n del self.file_kwargs['height_field']\n\n self.__dict__['file_field'] = self.file_field_cls(**self.file_kwargs)\n ### HACK: manually fix creation counter\n self.file_field.creation_counter = self.creation_counter\n\n # This calls contribute_to_class() for the FileField\n parents = cls._meta.parents.keys()\n parent_field_names = []\n if parents:\n parent_fields = reduce(operator.add, [p._meta.local_fields for p in parents], [])\n parent_field_names = [f.name for f in parent_fields]\n # Don't duplicate the field when inherited from a parent model\n if self.file_field_name not in parent_field_names:\n # Don't add field to proxy models\n if not cls._meta.proxy:\n cls.add_to_class(self.file_field_name, self.file_field)\n\n # Add the descriptor for the generic relation\n generic_descriptor = GenericForeignFileDescriptor(self, self.file_field)\n # We use self.__dict__ to avoid triggering __get__()\n self.__dict__['generic_descriptor'] = generic_descriptor\n setattr(cls, self.generic_rel_name, generic_descriptor)\n\n # Add the descriptor for the FileField\n file_descriptor = GenericForeignFileDescriptor(self, self.file_field,\n is_file_field=True)\n self.__dict__['file_descriptor'] = file_descriptor\n setattr(cls, self.file_field_name, file_descriptor)\n\n self.file_field.__dict__.update({\n 'generic_descriptor': generic_descriptor,\n 'file_descriptor': file_descriptor,\n 'db_field': self,\n 'generic_field': getattr(cls, self.generic_rel_name),\n })\n setattr(cls, self.raw_file_field_name, self.file_descriptor_cls(self.file_field))\n\n def is_cached(self, instance):\n return hasattr(instance, self.get_cache_name())\n\n def get_prefetch_queryset(self, instances, queryset=None):\n return (self.bulk_related_objects(instances),\n operator.attrgetter(self.object_id_field_name),\n lambda obj: obj._get_pk_val(),\n True,\n self.attname)\n\n if django.VERSION < (1, 7):\n get_prefetch_query_set = get_prefetch_queryset\n\n def bulk_related_objects(self, *args, **kwargs):\n \"\"\"\n Return all objects related to ``objs`` via this ``GenericRelation``.\n\n \"\"\"\n qs = super(GenericForeignFileField, self).bulk_related_objects(*args, **kwargs)\n if self.field_identifier_field_name:\n qs = qs.filter(**{\"%s__exact\" % self.field_identifier_field_name: self.field_identifier})\n return qs\n\n def south_init(self):\n \"\"\"\n This method is called by south before it introspects the field.\n\n South assumes that this is a related field if self.rel is set and it\n is not None. While this is a reasonable assumption, and it is *mostly*\n true for GenericForeignFileField, it is incorrect as far as South is\n concerned; we need South to treat this as a FileField so that\n it creates a column in the containing model.\n\n To deal with this situation we conditionally return the same values as\n FileField from get_internal_type() and db_type() while south is\n introspecting the field, and otherwise return the values that would be\n returned by a GenericRelation (which are the same as those returned\n by a ManyToManyField)\n\n self.south_executing is the basis for the conditional logic. It is set\n to True in this method (south_init()) and then back to False in\n GenericForeignFileField.post_create_sql().\n \"\"\"\n self.south_executing = True\n self._rel = self.rel\n self.rel = None\n\n def post_create_sql(self, style, db_table):\n \"\"\"\n This method is called after south is done introspecting the field.\n\n See GenericForeignFileField.south_init() for more documentation\n about the reason this is overridden here.\n \"\"\"\n self.south_executing = False\n if self.rel is None and hasattr(self, '_rel'):\n self.rel = self._rel\n return []\n\n def get_internal_type(self):\n \"\"\"\n Related to the implementation of db_type(), returns the pre-existing\n Django Field class whose database column is the same as the current\n field class, if such a class exists.\n\n See GenericForeignFileField.south_init() for more documentation\n about the reason this is overridden here.\n \"\"\"\n if self.south_executing:\n return 'FileField'\n else:\n # super() returns 'ManyToManyField'\n return super(GenericForeignFileField, self).get_internal_type()\n\n def db_type(self, connection):\n \"\"\"\n Returns the database column data type for this field, for the provided\n connection.\n\n See GenericForeignFileField.south_init() for more documentation\n about the reason this is overridden here.\n \"\"\"\n if self.south_executing:\n return models.Field.db_type(self, connection)\n else:\n # super() returns None\n return super(GenericForeignFileField, self).db_type(connection)\n\n def save_form_data(self, instance, data):\n super(GenericForeignFileField, self).save_form_data(instance, data)\n\n # pre_save returns getattr(instance, self.name), which is itself\n # the return value of the descriptor's __get__() method.\n # This method (GenericForeignFileDescriptor.__get__()) has side effects,\n # for the same reason that the descriptors of FileField and\n # GenericForeignKey have side-effects.\n #\n # So, although we don't _appear_ to be doing anything with the\n # value if not(isinstance(data, UploadedFile)), it is still\n # necessary to call pre_save() for the FileField part of the\n # instance's GenericForeignFileField to sync.\n value = self.pre_save(instance, False)\n\n # If we have a file uploaded via the fallback FileField, make\n # sure that it's saved.\n if isinstance(data, UploadedFile):\n if value and isinstance(value, FieldFile) and not value._committed:\n # save=True saves the instance. Since this field (GenericForeignFileField)\n # is considered a \"related field\" by Django, its save_form_data()\n # gets called after the instance has already been saved. We need\n # to resave it if we have a new file.\n value.save(value.name, value, save=True)\n else:\n instance.save()\n\n def formfield(self, **kwargs):\n factory_kwargs = {\n 'related': getattr(self, 'related', None),\n }\n widget = kwargs.pop('widget', None) or generic_fk_file_widget_factory(**factory_kwargs)\n formfield = kwargs.pop('form_class', None) or generic_fk_file_formfield_factory(widget=widget, **factory_kwargs)\n widget.parent_admin = formfield.parent_admin = kwargs.pop('parent_admin', None)\n widget.request = formfield.request = kwargs.pop('request', None)\n formfield.file_field_name = widget.file_field_name = self.file_field_name\n\n if isinstance(widget, type):\n widget = widget(field=self)\n else:\n widget.field = self\n kwargs.update({\n 'widget': widget,\n 'form_class': formfield,\n })\n return super(GenericForeignFileField, self).formfield(**kwargs)\n\n def get_inline_admin_formset(self, formset_cls=None, **kwargs):\n from generic_plus.forms import generic_fk_file_formset_factory, BaseGenericFileInlineFormSet\n\n formset_cls = formset_cls or BaseGenericFileInlineFormSet\n\n attrs = {\n 'model': self.rel.to,\n 'default_prefix': self.name,\n 'field': self,\n 'formset_kwargs': kwargs.pop('formset_kwargs', None) or {},\n }\n\n attrs.update(kwargs.pop('attrs', None) or {})\n\n if getattr(formset_cls, 'fields', None):\n attrs['fieldsets'] = ((None, {\n 'fields': formset_cls.fields,\n }),)\n\n class GenericForeignFileInline(GenericInlineModelAdmin):\n\n # This InlineModelAdmin exists for dual purposes: to be displayed\n # inside of the GenericForeignFileField's widget, and as the mechanism\n # by which changes are saved when a ModelAdmin is saved. For the\n # latter purpose we would not want the inline to actually render,\n # as it would be a duplicate of the inline rendered in the\n # GenericForeignFileField. For this reason we set the template to an\n # empty html file.\n template = \"generic_plus/blank.html\"\n\n extra = 1\n max_num = 1\n\n if not attrs.get('get_formset'):\n def get_formset(self, request, obj=None, **kwargs):\n formset = generic_fk_file_formset_factory(\n formset=formset_cls,\n formset_attrs=kwargs,\n field=self.field,\n prefix=self.default_prefix,\n formfield_callback=curry(self.formfield_for_dbfield, request=request))\n if getattr(self, 'default_prefix', None):\n formset.default_prefix = self.default_prefix\n return formset\n else:\n get_formset = attrs.pop('get_formset')\n\n return type('GenericForeignFileInline', (GenericForeignFileInline,), attrs)\n\n\nclass GenericForeignFileDescriptor(object):\n\n def __init__(self, field, file_field, is_file_field=False, for_concrete_model=True):\n self.field = field\n self.file_field = file_field\n self.is_file_field = is_file_field\n self.for_concrete_model = for_concrete_model\n\n def __get__(self, instance, instance_type=None):\n if instance is None:\n return self.field\n\n cache_name = self.field.get_cache_name()\n file_val = None\n\n if self.is_file_field:\n file_val = instance.__dict__[self.file_field.name]\n\n # Dynamically create a class that subclasses the related model's\n # default manager.\n rel_model = self.field.rel.to\n superclass = rel_model._default_manager.__class__\n RelatedManager = create_generic_related_manager(superclass)\n\n qn = connection.ops.quote_name\n\n manager_kwargs = {\n 'prefetch_cache_name': self.field.attname,\n }\n\n if hasattr(self.field.rel, 'symmetrical'):\n # Django <= 1.5\n manager_kwargs['symmetrical'] = (self.field.rel.symmetrical and instance.__class__ == rel_model)\n\n if hasattr(self.field, 'get_joining_columns'):\n join_cols = self.field.get_joining_columns(reverse_join=True)[0]\n else:\n join_cols = [self.field.m2m_column_name(), self.field.m2m_reverse_name()]\n\n ct_manager = ContentType.objects.db_manager(instance._state.db)\n try:\n content_type = ct_manager.get_for_model(instance, for_concrete_model=self.for_concrete_model)\n except TypeError:\n # Django <= 1.5\n if not self.for_concrete_model:\n raise\n else:\n content_type = ct_manager.get_for_model(instance)\n\n manager = RelatedManager(\n model=rel_model,\n instance=instance,\n field=self.field,\n source_col_name=qn(join_cols[0]),\n target_col_name=qn(join_cols[1]),\n content_type=content_type,\n content_type_field_name=self.field.content_type_field_name,\n object_id_field_name=self.field.object_id_field_name,\n field_identifier_field_name=self.field.field_identifier_field_name,\n **manager_kwargs)\n\n if not manager.pk_val:\n val = None\n else:\n if not self.is_file_field:\n return manager\n\n try:\n val = getattr(instance, cache_name)\n except AttributeError:\n db = manager._db or router.db_for_read(rel_model, instance=instance)\n if django.VERSION < (1, 7):\n qset = superclass.get_query_set(manager).using(db)\n else:\n qset = superclass.get_queryset(manager).using(db)\n\n try:\n val = qset.get(**manager.core_filters)\n except rel_model.DoesNotExist:\n val = None\n\n self.set_file_value(instance, file_val, obj=val)\n setattr(instance, self.field.get_cache_name(), val)\n return instance.__dict__[self.file_field.name]\n\n def set_file_value(self, instance, value, obj=None):\n # Sort out what to do with the file_val\n # For reference, see django.db.models.fields.files.FileDescriptor, upon\n # which this logic is based.\n\n # If this value is a string (instance.file = \"path/to/file\") or None\n # then we simply wrap it with the appropriate attribute class according\n # to the file field. [This is FieldFile for FileFields and\n # ImageFieldFile for ImageFields; it's also conceivable that user\n # subclasses might also want to subclass the attribute class]. This\n # object understands how to convert a path to a file, and also how to\n # handle None.\n attr_cls = self.file_field.attr_class\n\n # Because of the (some would say boneheaded) way pickle works,\n # the underlying FieldFile might not actually itself have an associated\n # file. So we need to reset the details of the FieldFile in those cases.\n if isinstance(value, attr_cls):\n value.instance = instance\n value.field = self.file_field\n value.storage = self.file_field.storage\n value.related_object = obj\n instance.__dict__[self.file_field.name] = value\n return\n\n if isinstance(obj, self.field.rel.to):\n value = getattr(obj, self.field.rel_file_field_name)\n elif isinstance(value, self.field.rel.to):\n obj = value\n value = getattr(obj, self.field.rel_file_field_name)\n\n if isinstance(value, six.string_types) or value is None:\n attr = attr_cls(instance, self.file_field, value)\n attr.related_object = obj\n instance.__dict__[self.file_field.name] = attr\n\n # Other types of files may be assigned as well, but they need to have\n # the correct FieldFile interface added to them. Thus, we wrap any\n # other type of File inside a FieldFile (well, the field's attr_class,\n # which is usually FieldFile).\n elif isinstance(value, File):\n file_copy = attr_cls(instance, self.file_field, value.name)\n if isinstance(value, FieldFile):\n # Avoid unnecessary IO caused by accessing ``value.file``\n if value and getattr(value, '_file', None):\n file_copy.file = value.file\n file_copy._committed = value._committed\n else:\n file_copy.file = value\n file_copy._committed = False\n file_copy.related_object = obj\n instance.__dict__[self.file_field.name] = file_copy\n\n def __set__(self, instance, value):\n if instance is None:\n raise AttributeError(\"Manager must be accessed via instance\")\n\n if isinstance(value, self.field.rel.to) or value is None:\n setattr(instance, self.field.get_cache_name(), value)\n\n if self.is_file_field:\n self.set_file_value(instance, value)\n else:\n manager = self.__get__(instance)\n manager.clear()\n if value is None:\n return\n if isinstance(value, self.field.rel.to):\n rel_obj_file = getattr(value, self.field.rel_file_field_name)\n file_val = rel_obj_file.path if rel_obj_file else None\n setattr(instance, self.field.file_field_name, file_val)\n manager.add(value)\n else:\n for obj in value:\n field_value = getattr(obj, self.field.file_field_name)\n file_val = field_value.path if field_value else None\n setattr(instance, self.field.file_field_name, file_val)\n manager.add(obj)\n setattr(instance, self.field.get_cache_name(), value)\n\n\ndef create_generic_related_manager(superclass):\n \"\"\"\n Factory function for a manager that subclasses 'superclass' (which is a\n Manager) and adds behavior for generic related objects.\n \"\"\"\n\n class GenericRelatedObjectManager(superclass):\n\n def __init__(self, model=None, instance=None, symmetrical=None,\n source_col_name=None, target_col_name=None, content_type=None,\n content_type_field_name=None, object_id_field_name=None,\n field_identifier_field_name=None, **kwargs):\n super(GenericRelatedObjectManager, self).__init__()\n self.model = model\n self.content_type = content_type\n self.symmetrical = symmetrical\n self.instance = instance\n self._field = kwargs.pop('field', None)\n self.file_field_name = self._field.file_field_name\n self.core_filters = {\n '%s__pk' % content_type_field_name: content_type.id,\n '%s__exact' % object_id_field_name: instance._get_pk_val(),\n }\n if field_identifier_field_name:\n self.core_filters['%s__exact' % field_identifier_field_name] = getattr(self._field, field_identifier_field_name)\n\n if 'prefetch_cache_name' in kwargs:\n # django 1.4+\n self.prefetch_cache_name = kwargs['prefetch_cache_name']\n self.source_col_name = source_col_name\n self.target_col_name = target_col_name\n self.content_type_field_name = content_type_field_name\n self.object_id_field_name = object_id_field_name\n self.pk_val = self.instance._get_pk_val()\n\n def get_queryset(self):\n if hasattr(self, 'prefetch_cache_name'):\n try:\n return self.instance._prefetched_objects_cache[self.prefetch_cache_name]\n except (AttributeError, KeyError):\n pass\n db = self._db or router.db_for_read(self.model, instance=self.instance)\n query = {\n ('%s__pk' % self.content_type_field_name): self.content_type.id,\n ('%s__exact' % self.object_id_field_name): self.pk_val,\n }\n if django.VERSION < (1, 7):\n return superclass.get_query_set(self).using(db).filter(**query)\n else:\n return superclass.get_queryset(self).using(db).filter(**query)\n\n if django.VERSION < (1, 7):\n get_query_set = get_queryset\n\n def get_prefetch_queryset(self, instances, queryset=None):\n db = self._db or router.db_for_read(self.model, instance=instances[0])\n query = {\n ('%s__pk' % self.content_type_field_name): self.content_type.id,\n ('%s__in' % self.object_id_field_name): set(obj._get_pk_val() for obj in instances),\n }\n if django.VERSION < (1, 7):\n qs = super(GenericRelatedObjectManager, self).get_query_set()\n else:\n qs = super(GenericRelatedObjectManager, self).get_queryset()\n return (qs.using(db).filter(**query),\n operator.attrgetter(self.object_id_field_name),\n lambda obj: obj._get_pk_val(),\n False,\n self.prefetch_cache_name)\n\n if django.VERSION < (1, 7):\n get_prefetch_query_set = get_prefetch_queryset\n\n def add(self, *objs):\n for obj in objs:\n if not isinstance(obj, self.model):\n raise TypeError(\"'%s' instance expected\" % self.model._meta.object_name)\n setattr(obj, self.content_type_field_name, self.content_type)\n setattr(obj, self.object_id_field_name, self.pk_val)\n obj.save()\n related_obj = self.__get_related_obj()\n setattr(related_obj, self.file_field_name, obj.path)\n add.alters_data = True\n\n @property\n def field(self):\n related_obj = self.__get_related_obj()\n return related_obj._meta.get_field(self.file_field_name)\n\n def __get_related_obj(self):\n related_cls = self.content_type.model_class()\n related_obj = related_cls.objects.get(pk=self.pk_val)\n return related_obj\n\n def remove(self, *objs):\n db = router.db_for_write(self.model, instance=self.instance)\n for obj in objs:\n obj.delete(using=db)\n try:\n related_obj = self.__get_related_obj()\n except ObjectDoesNotExist:\n pass\n else:\n setattr(related_obj, self.file_field_name, None)\n remove.alters_data = True\n\n def clear(self):\n db = router.db_for_write(self.model, instance=self.instance)\n for obj in self.all():\n obj.delete(using=db)\n related_obj = self.__get_related_obj()\n setattr(related_obj, self.file_field_name, None)\n clear.alters_data = True\n\n def create(self, **kwargs):\n kwargs[self.content_type_field_name] = self.content_type\n kwargs[self.object_id_field_name] = self.pk_val\n db = router.db_for_write(self.model, instance=self.instance)\n super_ = super(GenericRelatedObjectManager, self).using(db)\n new_obj = super_.create(**kwargs)\n if new_obj.path:\n related_obj = self.__get_related_obj()\n setattr(related_obj, self.file_field_name, new_obj.path)\n return new_obj\n create.alters_data = True\n\n return GenericRelatedObjectManager\n\n\ntry:\n from south.modelsinspector import add_introspection_rules\nexcept ImportError:\n pass\nelse:\n add_introspection_rules(rules=[\n (\n (GenericForeignFileField,),\n [],\n {\n \"to\": [\"rel.to\", {}],\n \"symmetrical\": [\"rel.symmetrical\", {\"default\": True}],\n \"object_id_field\": [\"object_id_field_name\", {\"default\": \"object_id\"}],\n \"content_type_field\": [\"content_type_field_name\", {\"default\": \"content_type\"}],\n \"blank\": [\"blank\", {\"default\": True}],\n },\n ),\n ], patterns=[\"^generic_plus\\.fields\\.GenericForeignFileField\"])\n","sub_path":"generic_plus/fields.py","file_name":"fields.py","file_ext":"py","file_size_in_byte":31975,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"43135378","text":"from bs4 import BeautifulSoup\n\nimport requests\nimport urllib.request\nimport shutil\n\nurl = \"https://brickset.com/parts/in-45678-1\"\nresponse = requests.get(url)\n\nsoup = BeautifulSoup(response.text, \"html.parser\")\n\naas = soup.find_all(\"a\", class_='highslide plain mainimg')\n\n\nimage_info = []\n\nfor a in aas:\n image_tag = a.findChildren(\"img\")\n image_info.append((image_tag[0][\"src\"], image_tag[0][\"title\"]))\n\n\ndef download_image(image):\n response = requests.get(image[0], stream=True)\n realname = ''.join(e for e in image[1] if e.isalnum())\n\n file = open(\"/Users/gbernal/Documents/GitHub/Firebase_PTC/Data/Lego/{}.jpg\".format(realname), 'wb')\n\n response.raw.decode_content = True\n shutil.copyfileobj(response.raw, file)\n del response\n\nfor i in range(0, len(image_info)):\n download_image(image_info[i])\n","sub_path":"scrapeImg.py","file_name":"scrapeImg.py","file_ext":"py","file_size_in_byte":829,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"42996007","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nLBT\nMartín & José\n\nScript para el ajuste de IV simulando el circuito del modelo 4B (dos diodos\nSchottky con resistencias en serie, en paralelo con una resistencia y un \nelemento SCLC)\n\nEste programa hace un ajuste de los datos de la muestra amorfa a 300K, \nutilizando como función de ajuste 'generar_IV', definida en el script \nsimul_modelo4B. Como parámetros iniciales, se utilizan los guess_param, \ndefinidos en ese mismo script. \n\n\n\"\"\"\n\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom scipy.optimize import curve_fit\nfrom funciones_gamma import gamma_sin\nfrom simul_modelo4B import generar_IV, guess_param, n\n\nfrom gammas_amorfa_sinplot import Vp_bajada300, Ip_bajada300\n\nfrom gammas_amorfa_sinplot import Vs_bajada300_mas, gamma_filt_bajada300_mas\n\nmuestra = 'Circuito Modelo 4B'\n\n\nimport lmfit as lmf\n\n#%%\n\nV_bot = 0.0\nV_top = 1.2\n\nmask = Vp_bajada300['300'] > 0 \n\nx_data = np.asarray(Vp_bajada300[mask]).ravel()\ny_data = np.asarray(Ip_bajada300[mask]).ravel()\n\n\n# En lugar de usar curve_fit, intentemos usar lmfit\n#popt, pcov = curve_fit(generar_IV, x_data, y_data, p0 = guess_param)\n\n# ver: https://lmfit.github.io/lmfit-py/intro.html\n\nparams = lmf.Parameters()\nparams.add(\"A\", value = 0.41)\nparams.add(\"n\", min = 0, value = 3, vary = False)\nparams.add(\"R\", min = 0.0, value = 5.0)\nparams.add(\"I0\", value = 0.1)\nparams.add(\"b\", value = 0.0001)\nparams.add(\"Rb\", min = 0.0, value = 100)\n\n\ndef Residual(params, x, data):\n A = params[\"A\"]\n n = params[\"n\"]\n R = params[\"R\"]\n I_0 = params[\"I0\"]\n b = params[\"b\"]\n R_b = params[\"Rb\"]\n\n model = generar_IV(x, A.value, R.value, I_0.value, b.value, R_b.value, n.value)\n return (data - model)\n\nminner = lmf.Minimizer(Residual, params, fcn_args = (x_data, y_data), nan_policy = 'omit')\nresult = minner.minimize()\n\nV = np.linspace(V_bot, V_top, 1000)\nI = generar_IV(V, result.params[\"A\"], result.params[\"R\"], result.params[\"I0\"],\n result.params[\"b\"], result.params[\"Rb\"], result.params[\"n\"])\n \n#%% Cálculo del gamma\n\ngamma = gamma_sin(V, I)\n\nexponente = 0.5\nVs = np.abs(V)**exponente\n\n#%%\n\nparams = ''\n# params = ' $A = {0}$\\n $R = {1}$\\n $I_0 = {2:.2E}$\\n $b = {3}$\\n $R_b = {4}$\\n $n = {5}$'.format(result.params[\"A\"].value, result.params[\"R\"].value, result.params[\"I0\"].value, result.params[\"b\"].value, result.params[\"Rb\"].value, result.params[\"n\"].value)\n\nfig, (ax_1, ax_2) = plt.subplots(1,2)\n\nax_1.plot(V, I, label = 'ajuste\\n'+ params)\nax_1.plot(Vp_bajada300, Ip_bajada300, 'c-.', label = 'datos a 300K')\nax_1.set_xlabel('$V$', fontsize = 15)\nax_1.set_ylabel('$I$', fontsize = 15)\n#ax_1.title(muestra + ': curva IV', fontsize = 15)\nax_1.legend()\n\nax_2.plot(Vs, gamma, color = 'r', label = 'ajuste\\n'+params)\nax_2.plot(Vs_bajada300_mas, gamma_filt_bajada300_mas, 'c-.', label = 'datos a 300K')\nax_2.set_xlabel('$|V|^{%.1f}$'%exponente, fontsize = 15)\nax_2.set_ylabel('$\\\\gamma$', fontsize = 15)\n#plt.title(muestra + ': curva $\\\\gamma$', fontsize = 15)\nax_2.legend()\n\nfig.savefig('file.pdf', format = 'pdf')\n\n","sub_path":"fit_modelo4B_lmfit.py","file_name":"fit_modelo4B_lmfit.py","file_ext":"py","file_size_in_byte":3062,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"133108983","text":"'''\nCreated on Oct 3, 2012\n\n@author: nils\n'''\nimport logging\nfrom optparse import make_option\n\nfrom django.core.management.base import BaseCommand, CommandError\n\nfrom galaxy_connector.models import Instance\n\n\nlogger = logging.getLogger(__name__)\n\n\nclass Command(BaseCommand):\n args = \" \"\n help = \"Creates a new Galaxy instance.\"\n\n option_list = BaseCommand.option_list + (\n make_option('--file_name',\n action='store',\n type='string'\n ),\n make_option('--description',\n action='store',\n type='string',\n default=\"\"\n ),\n make_option('--api_url',\n action='store',\n type='string',\n default=\"api\"\n ),\n make_option('--data_url',\n action='store',\n type='string',\n default=\"datasets\"\n ),\n )\n \"\"\"\n Name: handle\n Description:\n main program; creates a new Galaxy instance.\n At least a base url and an API key are required.\n \"\"\"\n def handle(self, *args, **options):\n try:\n base_url = args[0]\n except IndexError:\n raise CommandError(\"Please provide a base URL for Galaxy instance\")\n try:\n api_key = args[1]\n except IndexError:\n raise CommandError(\"Please provide an API key\")\n instance_count = Instance.objects.filter(\n base_url__exact=base_url).count()\n if instance_count > 0:\n self.stdout.write(\"Instance with URL '%s' already exists\" %\n base_url)\n logger.error(\"Instance with URL '%s' already exists\", base_url)\n return\n instance = Instance.objects.create(base_url=base_url,\n api_key=api_key,\n data_url=options['data_url'],\n api_url=options['api_url'],\n description=options['description'])\n if instance is not None:\n self.stdout.write(\"Instance '%s -- %s' created\" %\n base_url, api_key)\n logger.info(\"Instance '%s -- %s' created\", base_url, api_key)\n else:\n self.stdout.write(\"Unable to create instance '%s -- %s'\" %\n base_url, api_key)\n logger.error(\"Unable to create instance '%s -- %s'\",\n base_url, api_key)\n","sub_path":"refinery/galaxy_connector/management/commands/create_galaxy_instance.py","file_name":"create_galaxy_instance.py","file_ext":"py","file_size_in_byte":2638,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"145410032","text":"from django.shortcuts import render, render_to_response, HttpResponse, HttpResponseRedirect\nimport cloudinary\nfrom cloudinary.uploader import upload\nfrom user_profile.models import UserProfile, User\nfrom task.models import Task\n\n\ncloudinary.config(\n cloud_name = \"tasker\",\n api_key = \"182752138494444\",\n api_secret = \"A0hYlMFlca2uaMBFmWvNSSYSXGY\"\n)\n\n\ndef get_profile(request):\n user_profile = UserProfile.objects.get_user_profile(request.user)\n tasks = Task.objects.filter(author=request.user)\n return render(request, 'user_profile/profile.html', {'user_profile': user_profile, 'tasks': tasks})\n\n\ndef edit_username(request):\n try:\n new_username = request.POST['value']\n if request.user.username == new_username or len(new_username) == 0:\n return HttpResponse(request.POST['value'], status=200)\n if User.objects.filter(username=new_username).exists():\n new_username = request.user.username\n else:\n current_user = request.user\n current_user.username = new_username\n current_user.save()\n except Exception as e:\n print(e)\n return HttpResponse(status=500)\n return HttpResponse(new_username, status=200)\n\n\ndef set_theme_dark(request):\n user_profile = UserProfile.objects.get_user_profile(request.user)\n user_profile.theme = 'dark'\n user_profile.save()\n return HttpResponseRedirect('/profile/')\n\n\ndef set_theme_light(request):\n user_profile = UserProfile.objects.get_user_profile(request.user)\n user_profile.theme = 'light'\n user_profile.save()\n return HttpResponseRedirect('/profile/')\n\n\ndef show_user(request):\n user_id = request.GET['id']\n user = User.objects.filter(username=user_id)\n user_profile = UserProfile.objects.get_user_profile(user=user)\n user_tasks = Task.objects.filter(author=user_profile.user)\n current_user = UserProfile.objects.get(user=request.user)\n user = UserProfile.objects.get_user_profile(user=request.user)\n return render(request, 'user_profile/profile_another_user.html', {'current_user': user_profile,\n 'tasks': user_tasks,\n 'user_profile': current_user,\n 'user': user.user})\n\n\n","sub_path":"TASKER/user_profile/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2377,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"378176313","text":"#################################################################################\n#################################################################################\n#################################################################################\n# Refinement Clustering Algorithm Functions\n\n\n\n#################################################################################\n#################################################################################\n#################################################################################\n# Modules. Import these to each file that uses the algorithm.\nimport numpy as np\nimport random\n# Plotting\nimport matplotlib.pyplot as plt\nfrom mpl_toolkits.mplot3d import Axes3D\n# sklearn. Maybe do import sklearn * or something?\nimport sklearn.cluster\nfrom sklearn.cluster import KMeans\nfrom sklearn.neighbors import NearestNeighbors\nfrom sklearn.linear_model import LogisticRegression\n# Other\nimport itertools # For permutations\nimport csv # To make csv's\nimport time # To time things\nrng = np.random.RandomState(0) # Random number generator\n\n\n\n\n#################################################################################\n#################################################################################\n#################################################################################\n# Several general functions used throughout:\n\n# Return the permutation of sigma_est that's closest to sigma:\n# Takes as input TKTK\ndef perm_true(sigma, sigma_est, n, k, perms):\n sigma_est_perms = np.empty((len(perms), n))\n for i in range(0, len(perms)):\n for j in range(0,k):\n sigma_est_perms[i,sigma_est==j] = perms[i,j]\n\n errors = np.empty(len(perms))\n for i in range(0, len(perms)):\n errors[i] = np.sum( sigma != sigma_est_perms[i,] )\n\n loc = np.where(errors == errors.min())[0]\n loc_min_error = loc[0] # In case there is more than one min\n return sigma_est_perms[loc_min_error,]\n\n\n# Create adjacency matrices:\ndef create_adjacency_matrix(n, X, rho):\n A1 = np.zeros((n,n))\n A3 = np.zeros((n,n))\n for i in range(0,n):\n A1[i,] = (np.linalg.norm(X[i,]))**2\n A3[i,] = (np.linalg.norm(X[i,]))**2\n\n A2 = np.dot(X, X.T)\n A = A1 + A3.T - (2*A2)\n A = np.exp(-A/rho)\n #np.fill_diagonal(A, 0)\n return A\n\ndef create_adjacency_matrix(n, X, rho):\n A1 = np.zeros((n,n))\n A3 = np.zeros((n,n))\n for i in range(0,n):\n A1[i,] = (np.linalg.norm(X[i,]))**2\n A3[i,] = (np.linalg.norm(X[i,]))**2\n\n A2 = np.dot(X, X.T)\n A = A1 + A3.T - (2*A2)\n A = np.exp(-A/rho)\n #np.fill_diagonal(A, 0)\n return A\n\n# Create the m-rank approximation of X:\ndef lra(X, n, p, m):\n U, D, V = np.linalg.svd(X, full_matrices=True)\n U_m = U[:,:m]\n D_m = np.diag(D[:m])\n V_m = V[:m,]\n return U_m.dot(D_m.dot(V_m))\n\n\n\n###############################################################################\n###############################################################################\n###############################################################################\n# Dimension Reduction.\n\n# Local Linear Projection:\ndef reduce_dimension_llp(X, n, p, m, k, sigma_tilde, nc):\n all_manifolds_est = np.zeros((n,p))\n for l in range(k):\n # Reduce dimension to nc (number of clusters on single mani) and do kmeans:\n X_mani = X[sigma_tilde == l,]\n #X_nc = lra(X_mani, n, p, p) # Use this in k-means below if you do dimension reduction!!\n labels_nc = KMeans(n_clusters=nc, init='k-means++', n_init=10, max_iter=300, tol=0.0001, precompute_distances='auto', verbose=0, random_state=None, copy_x=True, n_jobs=1).fit(X_mani).labels_\n if m < np.bincount(labels_nc).min():\n m = m\n else:\n m = np.bincount(labels_nc).min()\n one_manifold_est = np.zeros((len(X_mani), p))\n for j in range(nc):\n X_local = X_mani[labels_nc == j,]\n mani_est_local = lra(X_local, n, p, m)\n one_manifold_est[labels_nc == j,] = mani_est_local\n all_manifolds_est[sigma_tilde == l, ] = one_manifold_est\n\n return all_manifolds_est\n\n# No dimension reduction:\ndef reduce_dimension_none(X, n, p, m, k, sigma_tilde, nc):\n return X\n\n\n###############################################################################\n###############################################################################\n###############################################################################\n# Estimate the manifolds. \n\n# Estimate the manifolds via a weighted average:\ndef estimate_manifold_avg(X, n, p, k, sigma_tilde, nb_size, coeff):\n mani_est = np.zeros((n, p)) \n for l in range(k):\n X_sub = X[sigma_tilde==l,]\n coeff_sub = coeff[sigma_tilde==l,]\n mani_sub = mani_est[sigma_tilde==l,]\n nbrs = NearestNeighbors(n_neighbors=int(nb_size[l]), algorithm='ball_tree').fit(X_sub)\n distances, indices = nbrs.kneighbors(X_sub)\n for i in range(0, len(X_sub)):\n mani_sub[i,] = np.array(np.average(X_sub[indices[i,],], axis=0, weights=coeff_sub[i,indices[i,]]))\n mani_est[sigma_tilde==l,] = mani_sub\n \n return mani_est, sigma_tilde\n\n\n\n###############################################################################\n###############################################################################\n###############################################################################\n# Create new points for testing (no dependence on manifolds):\n\n# Estimate a new version of X via a weighted average:\ndef create_X_new(X, n, p, nb_size_X, coeff):\n X_new = np.zeros((n,p))\n nbrs = NearestNeighbors(n_neighbors=int(nb_size_X), algorithm='ball_tree').fit(X)\n distances, indices = nbrs.kneighbors(X)\n for i in range(0, n):\n X_new[i,] = np.array(np.average(X[indices[i,],], axis=0, weights=coeff[i,indices[i,]]))\n return X_new\n\n\n###############################################################################\n###############################################################################\n###############################################################################\n# Test\n\n# Nearest neighbors testing function. In the event of a tie, it picks the first.\n# For this function, sigma_centers must match mani_est.\ndef test(X, mani_est, k, sigma_centers, K):\n n = len(X)\n nc_full = len(mani_est)\n distance = np.zeros((n,nc_full)).reshape(n, nc_full)\n for i in range(n):\n for j in range(nc_full):\n distance[i,j] = np.linalg.norm(X[i,] - mani_est[j,])\n\n sigma_hat = np.empty(n)\n\n for i in range(n):\n ind = np.argpartition(distance[i,], K)[:K]\n nbs = sigma_centers[ind]\n counts = np.empty(k)\n for j in range(k):\n counts[j] = np.sum(nbs == j)\n # In the event of a tie, we just take the first one:\n sigma_hat[i] = np.where(counts == counts.max())[0][0]\n\n return sigma_hat\n\n\n################################################################################\n################################################################################\n################################################################################\n# The full refinement procedure with the option to reduce the dimension: \n \ndef refine(X, n, p, m, k, rho,\n sigma, sigma_tilde, perms,\n dimension_reduction_method, nc, \n manifold_estimation_method, nb_size_mani, coeff_mani_est,\n X_new_creation_method, nb_size_X, coeff_X_new,\n K):\n\n # Reduce dimension: \n X_dr = dimension_reduction_method(X, n, p, m, k, sigma_tilde, nc)\n\n # Estimate manifold using dimension reduced data:\n mani_estimate = manifold_estimation_method(X_dr, n, p, k, sigma_tilde, nb_size_mani, coeff_mani_est)\n mani_est = mani_estimate[0]\n sigma_mani = mani_estimate[1]\n \n # Create X_new: NOT using dimension reduced version of X to average right now:\n X_new = create_X_new(X, n, p, nb_size_X, coeff_X_new)\n \n # Test:\n sigma_hat = test(X_new, mani_est, k, sigma_mani, K)\n\n # Return the final estimate of sigma:\n return perm_true(sigma, sigma_hat, n, k, perms)\n\n\n################################################################################\n################################################################################\n################################################################################\n# The following tests several algorithms after the same initializer: spectral clustering.\n\ndef initialize_and_refine(X, n, p, m, k, rho, sigma, nc, nb_size_mani, coeff_mani_est, X_new_creation_method, nb_size_X, coeff_X_new, K):\n \n A = create_adjacency_matrix(n, X, rho)\n # Do for infs and other special cases too:\n A[np.where(np.isnan(A))] = 0\n A[np.where(np.isinf(A))] = 0\n sigma_tilde = sklearn.cluster.spectral_clustering(A, n_clusters=k, assign_labels='kmeans')\n perms = np.array(list(itertools.permutations(range(0,k))))\n sigma_tilde_final = perm_true(sigma, sigma_tilde, n, k, perms)\n\n sigma_hat_nodr = refine(X, n, p, m, k, rho, sigma, sigma_tilde, perms, reduce_dimension_none, nc, estimate_manifold_avg, nb_size_mani, coeff_mani_est, create_X_new, nb_size_X, coeff_X_new, K)\n sigma_hat_dr = refine(X, n, p, m, k, rho, sigma, sigma_tilde, perms, reduce_dimension_llp, nc, estimate_manifold_avg, nb_size_mani, coeff_mani_est, create_X_new, nb_size_X, coeff_X_new, K)\n\n return sigma_tilde_final, sigma_hat_nodr, sigma_hat_dr\n\n\n","sub_path":"KSC_Mani_Learn_Algo/Refinement_Algorithm_Package/refinement.py","file_name":"refinement.py","file_ext":"py","file_size_in_byte":9438,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"611089771","text":"def excelTile(n):\n \"\"\"if n == 0:\n return ''\n elif (n>0 and n<=26):\n return chr(n+64)\n else:\n return excelTile(int(n/26)) + excelTile (n%26)\"\"\"\n\n if n == 0:\n return ''\n if n <26 or n<0:\n return chr(n+64)\n else:\n q = int(n/26)\n r = n%26\n if r == 0:\n return excelTile(q-1)+'Z'\n else :\n return excelTile(q)+excelTile(r)\n\nprint (excelTile(27))","sub_path":"LatestCodes/LeetCodePractise/excelTile.py","file_name":"excelTile.py","file_ext":"py","file_size_in_byte":441,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"396664131","text":"\t\n\nimport dash\nimport dash_html_components as html\nimport dash_core_components as dcc\nimport dash_bootstrap_components as dbc\nimport dash_table\nfrom dash.dependencies import Input, Output\n\nimport pandas as pd\nimport numpy as np\nimport json\n\n\nimport pandas as pd\nimport plotly.express as px\nimport plotly \nimport plotly.graph_objs as go \nimport warnings\nfrom data import new_variables\n\n\nfrom app import app\n\n\n#Load datasets Archivo Plano\n#original = pd.read_hdf(\"./data.h5\", \"original\")\n#new_variables = pd.read_hdf(\"./data.h5\", \"new_variables\")\n#univariado = pd.read_hdf(\"./data.h5\", \"univariado\")\n\n#Load datasets DataBase\n#engine = create_engine(\"postgresql+psycopg2://postgres:7$col&ds0@ds4a-70-db.cgxzuy7k08ix.us-east-2.rds.amazonaws.com/\")\n#df_model = pd.read_sql_table('df_model',engine)\n#original = pd.read_sql_table('skit_final',engine)\n#SKIT_FINAL = pd.read_sql_table('skit_final',engine)\n#Table_Stage = pd.read_sql_table('table_stage',engine)\n#new_variables = pd.read_sql_table('new_variables',engine)\n\n\n# Define Funtions\ndef get_Horas_Ejecutadas_Propias_Proyecto():\n\tpl=new_variables.groupby(new_variables['etapa']).agg({'Horas Ejecutadas Propias Proyecto':'mean'}).reset_index()\n\tpl['etapa']=pl['etapa'].apply(str)\n\tfig = px.scatter(pl, x=\"etapa\", y=\"Horas Ejecutadas Propias Proyecto\",size=\"Horas Ejecutadas Propias Proyecto\", color=\"etapa\",size_max=60,color_discrete_sequence=px.colors.sequential.Blues)\n\treturn fig\n''' \n\tfig = px.box(new_variables, x = \"etapa\", y = \"Horas Ejecutadas Propias Proyecto\" , points = 'all')\n fig.update_layout(autosize = True, title = {\"text\": \"Hours Executed Own Project\", \"font\": {\"color\": \"black\", \"size\": 25}, 'x': 0.5}, xaxis_title='Stage', yaxis_title='Hours')\n return fig\n'''\n\n# Figura Lina (Horas promedio por Etapas)\nfig = go.Figure()\nfig.update_layout(autosize = True, title = {\"text\": \"Avarage Hours Executed Vs Project Stages\", \"font\": {\"color\": \"black\", \"size\": 25}, 'x': 0.5})\nfig.add_trace(go.Violin(y=new_variables['preventa'],box_visible=True, name = 'preventa'))\nfig.add_trace(go.Violin(y=new_variables['mercadeo'],box_visible=True, name = 'mercadeo'))\nfig.add_trace(go.Violin(y=new_variables['venta'], box_visible=True,name = 'venta'))\nfig.add_trace(go.Violin(y=new_variables['seguimiento ofertas koncilia'],box_visible=True, name = 'seguimiento ofertas koncilia'))\nfig.add_trace(go.Violin(y=new_variables['requerimientos'], box_visible=True,name = 'requerimientos'))\nfig.add_trace(go.Violin(y=new_variables['consultoria'],box_visible=True, name = 'consultoria'))\nfig.add_trace(go.Violin(y=new_variables['desarrollo'],box_visible=True, name = 'desarrollo'))\nfig.add_trace(go.Violin(y=new_variables['pruebas'],box_visible=True, name = 'pruebas'))\nfig.add_trace(go.Violin(y=new_variables['instalaciones'],box_visible=True,name = 'instalaciones'))\nfig.add_trace(go.Violin(y=new_variables['infraestructura skit'],box_visible=True, name = 'infraestructura skit'))\nfig.add_trace(go.Violin(y=new_variables['capacitacion'],box_visible=True, name='capacitacion'))\nfig.add_trace(go.Violin(y=new_variables['soporte'],box_visible=True, name = 'soporte'))\nfig.add_trace(go.Violin(y=new_variables['garantia'],box_visible=True, name = 'garantia'))\nfig.add_trace(go.Violin(y=new_variables['reprocesos'],box_visible=True, name = 'reprocesos'))\nfig.add_trace(go.Violin(y=new_variables['post venta'],box_visible=True, name = 'post venta'))\nfig.add_trace(go.Violin(y=new_variables['capacitacion interna'], box_visible=True,name = 'capacitacion interna'))\nfig.add_trace(go.Violin(y=new_variables['investigacion'],box_visible=True, name = 'investigacion'))\nfig.update_traces(fillcolor='White', line_color='royalblue')\n\n\n# Figuta 2 (Horas promedio por Etapas 2 Parte)\nfig2 = go.Figure()\nfig2.add_trace(go.Violin(y=new_variables['preventa_funcionarios'], box_visible=True, name = 'preventa_funcionarios'))\nfig2.add_trace(go.Violin(y=new_variables['mercadeo_funcionarios'], box_visible=True,name = 'mercadeo_funcionarios'))\nfig2.add_trace(go.Violin(y=new_variables['venta_funcionarios'],box_visible=True, name = 'venta_funcionarios'))\nfig2.add_trace(go.Violin(y=new_variables['seguimiento ofertas koncilia_funcionarios'],box_visible=True, name = 'seguimiento ofertas koncilia_funcionarios'))\nfig2.add_trace(go.Violin(y=new_variables['requerimientos_funcionarios'],box_visible=True, name = 'requerimientos_funcionarios'))\nfig2.add_trace(go.Violin(y=new_variables['consultoria_funcionarios'],box_visible=True, name = 'consultoria_funcionarios'))\nfig2.add_trace(go.Violin(y=new_variables['desarrollo_funcionarios'],box_visible=True, name = 'desarrollo_funcionarios'))\nfig2.add_trace(go.Violin(y=new_variables['pruebas_funcionarios'],box_visible=True, name = 'pruebas_funcionarios'))\nfig2.add_trace(go.Violin(y=new_variables['instalaciones_funcionarios'],box_visible=True, name = 'instalaciones_funcionarios'))\nfig2.add_trace(go.Violin(y=new_variables['infraestructura skit_funcionarios'],box_visible=True, name = 'infraestructura skit_funcionarios'))\nfig2.add_trace(go.Violin(y=new_variables['capacitacion_funcionarios'], box_visible=True,name='capacitacion_funcionarios'))\nfig2.add_trace(go.Violin(y=new_variables['soporte_funcionarios'],box_visible=True, name = 'soporte_funcionarios'))\nfig2.add_trace(go.Violin(y=new_variables['garantia_funcionarios'],box_visible=True, name = 'garantia_funcionarios'))\nfig2.add_trace(go.Violin(y=new_variables['reprocesos_funcionarios'],box_visible=True, name = 'reprocesos_funcionarios'))\nfig2.add_trace(go.Violin(y=new_variables['post venta_funcionarios'],box_visible=True, name = 'post venta_funcionarios'))\nfig2.add_trace(go.Violin(y=new_variables['capacitacion interna_funcionarios'],box_visible=True, name = 'capacitacion interna_funcionarios'))\nfig2.add_trace(go.Violin(y=new_variables['investigacion_funcionarios'], box_visible=True,name = 'investigacion_funcionarios'))\nfig2.update_traces(fillcolor='White', line_color='salmon')\n\n\n#Layout Grap \"Horas Ejecutadas\"\nlayout_Horas_Ejecutadas_Propias_Proyecto = html.Div(\n #className = \"row\", \n children = [\n html.Div(\n \n children = [\n #html.H4(children = \"Horas Ejecutadas Propias Proyecto\"),\n dcc.Graph(\n id = \"Hours Executed Own Project\",\n figure = get_Horas_Ejecutadas_Propias_Proyecto()\n )\n ],style = {\"text-align\": \"center\"}\n )\n ]\n)\n\n\n\n#Layout \"Figura 1 Horas por Proyecto parte 1\"\nlayout_Lina = html.Div(\n #className = \"row\", \n children = [\n # html.H4(children = \"Etapas vs Horas Promedio\"),\n dcc.Graph(\n id='example-graph-2', \n figure=fig\n )\n])\n\n\n#Layout \"Figura 2 Horas por Proyecto parte 2\"\nlayout_Proyecto2 = html.Div(\n #className = \"row\", \n children = [\n # html.H4(children = \"Etapas vs Horas Promedio\"),\n dcc.Graph(\n id='example-graph-3', \n figure=fig2\n )\n])\n\nlayout = html.Div([\n layout_Lina,\n layout_Proyecto2,\n\t\t\tlayout_Horas_Ejecutadas_Propias_Proyecto\n ])\n","sub_path":"web_app/apps/grafica.py","file_name":"grafica.py","file_ext":"py","file_size_in_byte":7048,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"110398920","text":"def fib(nterms):\n # first two terms\n n1=0\n n2 =1\n count = 1\n if nterms == 1:\n return n1\n else:\n while count < nterms:\n print(n1)\n nth = n1 + n2\n # update values\n n1 = n2\n n2 = nth\n count += 1\n return n1\n \n\ndef main():\n nterms = eval(input(\"Enter the number of terms to get their :\\n\"))\n # check if the number of terms is valid\n if (nterms>0):\n result=fib(nterms)\n print(\"Fibonacci sequence upto\",nterms,\":\", result)\n else:\n print(\"Fibonacci sequence not valid for negative numbers\")\n print(\"Please enter positive numbers\")\n\nmain() # Call the main function\n#can you rpeat this program as long as suer says yes\n","sub_path":"Week 6/fib.py","file_name":"fib.py","file_ext":"py","file_size_in_byte":758,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"612602385","text":"import numpy as np\nfrom keras.optimizers import Adam\nfrom keras.engine import Model\nfrom keras.layers import Flatten, Dense\nfrom keras.applications.vgg16 import VGG16\nfrom keras.callbacks import ModelCheckpoint\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.preprocessing import StandardScaler\nfrom keras.callbacks import TensorBoard\nfrom keras.utils import to_categorical\nimport gc\nimport time\nimport h5py\n\n\ndef vgg_face_model(classes=4, hidden_dim=512, shape=(160, 160, 3)):\n # Convolution Features\n model = VGG16(include_top=False, input_shape=shape)\n last_layer = model.get_layer('pool5').output\n x = Flatten(name='flatten')(last_layer)\n x = Dense(hidden_dim, activation='relu', name='fc4096')(x)\n x = Dense(hidden_dim, activation='relu', name='fc4097')(x)\n out = Dense(classes, activation='softmax', name='fc1000')(x)\n vgg_model = Model(model.input, out)\n return vgg_model\n\n\n# ==============================load data====================================\n\nf = h5py.File('images.h5', 'r')\nX_data = np.array(f['data'])\ny_data = np.array(f['ethnic'])\ny_data=to_categorical(y_data,num_classes=4)\nX_train, y_train, X_dev, y_dev = train_test_split(X_data, y_data, test_size=0.3,random_state=87)\nX_data=None\ny_data=None\ngc.collect()\n# normalization\nscaler = StandardScaler()\nX_train = scaler.fit_transform(X_train)\nX_dev = scaler.transform(X_dev)\nwith open(\"Scaler_parameters.txt\", 'w') as f:\n print(\"mean is {}. variance is {}\".format(scaler.mean_, scaler.var_))\n f.write(\"mean is {}. variance is {}\".format(scaler.mean_, scaler.var_))\n\n# =============================hypermeters====================================\nlearning_rate = 1e-3\noptimizaion_method = \"Adam\"\nbatch_size = 320\niteration_times = 100\n# hypermeter objects\nadam = Adam(lr=learning_rate, beta_1=0.9, beta_2=0.99)\n# =============================build model====================================\nmodel = vgg_face_model()\ncheckpoint = ModelCheckpoint('weights_ethnic.hdf5', monitor='val_acc', verbose=2, save_best_only=True,\n save_weights_only=True, mode='max')\nmodel.compile(optimizer=adam, loss='categorical_crossentropy', metrics=['accuracy'])\nmodel.fit(X_train, y_train,\n batch_size=batch_size,\n epochs=iteration_times,\n verbose=1,\n callbacks=[checkpoint,TensorBoard(log_dir='log')],\n validation_data=(X_dev, y_dev),\n initial_epoch=0)\nlocaltime = time.strftime('%Y-%m-%d_%H%M%S', time.localtime(time.time()))\nfilename = localtime + '.h5'\nmodel.save(filename)\nprint(model.summary())\n","sub_path":"train_network.py","file_name":"train_network.py","file_ext":"py","file_size_in_byte":2579,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"319884526","text":"\nfrom django.db import router\ntry:\n # ObjectId has been moved to bson.objectid in newer versions of PyMongo\n from bson.objectid import ObjectId\nexcept ImportError:\n from pymongo.objectid import ObjectId\n\n\n\nclass MongoDBM2MQueryError(Exception): pass\n\n\nclass MongoDBM2MQuerySet(object):\n \"\"\"\n Helper for returning a set of objects from the managers.\n Works similarly to Django's own query set objects.\n Lazily loads non-embedded objects when iterated.\n If embed=False, objects are always loaded from database.\n \"\"\"\n def __init__(self, rel, model, objects, use_cached,\n appear_as_relationship=(None, None, None, None, None)):\n self.db = router.db_for_read(rel.model if rel.model else rel.field.model)\n self.rel = rel\n self.objects = list(objects) # make a copy of the list to avoid problems\n self.model = model\n (self.appear_as_relationship_model, self.rel_model_instance,\n self.rel_to_instance, self.rel_model_name, self.rel_to_name) = \\\n appear_as_relationship # appear as an intermediate m2m model\n if self.appear_as_relationship_model:\n self.model = self.appear_as_relationship_model\n if not use_cached:\n # Reset any cached instances\n self.objects = [{'pk': obj['pk'], 'obj': None}\n for obj in self.objects]\n\n def _get_obj(self, obj):\n if not obj.get('obj'):\n # Load referred instance from db and keep in memory\n obj['obj'] = self.rel.to.objects.get(pk=obj['pk'])\n if self.appear_as_relationship_model:\n # Wrap us in a relationship class\n if self.rel_model_instance:\n args = {'pk': \"%s$f$%s\" %\n (self.rel_model_instance.pk, obj['pk']),\n self.rel_model_name: self.rel_model_instance,\n self.rel_to_name: obj['obj']}\n else:\n # Reverse\n args = {'pk': \"%s$r$%s\" % (self.rel_to_instance.pk, obj['pk']),\n self.rel_model_name: obj['obj'],\n self.rel_to_name: self.rel_to_instance}\n wrapper = self.appear_as_relationship_model(**args)\n return wrapper\n return obj['obj']\n\n def __iter__(self):\n for obj in self.objects:\n yield self._get_obj(obj)\n\n def __repr__(self):\n from . import REPR_OUTPUT_SIZE\n # limit list after conversion because mongodb doesn't use integer indices\n data = list(self)[:REPR_OUTPUT_SIZE + 1]\n if len(data) > REPR_OUTPUT_SIZE:\n data[-1] = \"...(remaining elements truncated)...\"\n return repr(data)\n\n def __getitem__(self, key):\n obj = self.objects[key]\n return self._get_obj(obj)\n\n def ordered(self, *args, **kwargs):\n return self\n\n def __len__(self):\n return len(self.objects)\n\n def using(self, db, *args, **kwargs):\n self.db = db\n return self\n\n def filter(self, *args, **kwargs):\n return self\n\n def get(self, *args, **kwargs):\n if 'pk' in kwargs:\n pk = ObjectId(kwargs['pk'])\n for obj in self.objects:\n if pk == obj['pk']:\n return self._get_obj(obj)\n return None\n\n def count(self):\n return len(self.objects)\n","sub_path":"django_mongom2m/query.py","file_name":"query.py","file_ext":"py","file_size_in_byte":3395,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"121832451","text":"#!/usr/bin/env python\nimport os, sys, argparse\n\ndef argParser():\n\n\ttakeArgs = argparse.ArgumentParser()\n\ttakeArgs.add_argument('file', type=str, default='', help='takes a file [example.txt]')\n\targs = takeArgs.parse_args()\n\n\tfileContents = []\n\n\ttry:\n\t\twith open(args.file, 'rb') as readFile:\n\t\t\tfor num in readFile:\n\t\t\t\tfileContents.append(num)\n\texcept:\n\t\tprint(\"unable to open file...\")\n\tfinally:\n\t\treadFile.close()\n\n\tnumSum = sum(fileContents)\n\tprint(numSum)\n\t\n\ndef main():\n\n\targParser()\n\nif __name__=='__main__':\n\tmain()\n","sub_path":"modules/argparse/tests/read_files.py","file_name":"read_files.py","file_ext":"py","file_size_in_byte":523,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"492113747","text":"from django.conf.urls import url\n\nfrom . import views\n\nurlpatterns = [\n url(r'^$', views.show_index, name='show_index'),\n url(r'^add_category$', views.add_category, name='add_category'),\n url(r'^(?:(?P\\w+)/)?start_topic/$', views.start_topic, name='start_topic'),\n url(r'^(?P\\w+)/$', views.show_category, name='show_category'),\n url(r'^(?P\\w+)/(?P[0-9]+)/$', views.show_or_comment_topic, name='show_or_comment_topic'),\n url(r'^(?P\\w+)/(?P[0-9]+)/vote$', views.vote_for_topic, name='vote_for_topic'),\n url(r'^upload_image$', views.upload_image, name='upload_image'),\n url(r'^(?P\\w+)/(?P[0-9]+)/(?P[0-9]+)/vote$',\n views.vote_for_comment, name='vote_for_comment'\n ),\n]\n","sub_path":"forum/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":818,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"320265853","text":"# coding=utf8\nimport os\nimport re\nimport wave\n\nimport numpy as np\nimport pyaudio\nimport time\n\n\n#plt.xlim(6000,6030)\n#plt.ylim(0,500)\n#注:时间以窗口位置表示(转移到真实时间单位ms需要除每秒窗口数windows_density),频率就是真实频率\n#加入了汉明窗,分辨率20,全局阈值,不合并声道\n\n\nclass voice():\n def load(self, filepath):\n '''\n\n :param filepath: 文件路径,为wav文件\n :return: 如果无异常则返回True,如果有异常退出并返回False\n self.wave_data内储存着多通道的音频数据,其中self.wave_data[0]代表第一通道\n 具体有几通道,看self.nchannels\n '''\n f = wave.open(filepath)\n params = f.getparams()\n self.nchannels, self.sampwidth, self.framerate, self.nframes = params[:4] #nchannels:通道数(2)/samplewidth:采样大小(2字节,即16bit)/framerate:采样频率(48000:一秒采样几次,采样一次一帧,一帧数据大小为采样大小*通道数)\n #print(filepath,'音频文件属性————通道:',self.nchannels,'采样大小:',self.sampwidth,'采样频率:',self.framerate,'帧数:',self.nframes)\n str_data = f.readframes(self.nframes) #nframes: 总共的帧数(采样次数)\n self.wave_data = np.fromstring(str_data, dtype=np.short) #wave中readframes以bytes类型(与str类似)读出音频中所有帧,用numpy转换成int型一维向量----wave_data(此时向量是[LRLRLR...])\n self.wave_data.shape = -1, self.nchannels #调整矩阵长宽,使一行包含这一帧的L通道和R通道分量如[[LR][LR]...],-1表示行数根据列数自动适应----理论上行数就是帧数。\n self.wave_data = self.wave_data.T #将向量转置,使第一行包含所有帧的L通道分量,第二行...,最终的wave_data变成[[LLL...][RRR...]]\n #下面两行合并声道(删除不合并)\n f.close()\n self.name = os.path.basename(filepath) # 记录下文件名\n return True\n\n #计算歌的指纹--------四分钟用时大约1.5秒\n #输入:windows_density每秒窗口数,denoise是否需要降噪(用于录音音频)\n def fp(self, windows_density=20, denoise=False):\n windows_size=self.framerate//windows_density #windows_size:每个窗口的帧数\n hamming_window = np.hamming(windows_size)\n if denoise:\n noise_fft=self.denoise(2, windows_size)\n self.landmarks = [] # 用landmarks储存landmark,landmark是一个tuple:(时间,频率),并根据先时间后频率对landmark在list中从前到后排序\n #!!!\n time = []\n frequency = []\n\n # 每次的fft先暂时储存起来!等找出最大的aver_max再秋后算账(处理处landmark)\n ffts = []\n max_aver_max = 0\n for i in range(0, self.nframes - windows_size, windows_size):\n window = self.wave_data[0][i:i + windows_size] # window即一个窗口(离散的时域函数)\n fft = np.abs(np.fft.fft(window)) # fft即对这个窗口进行傅里叶转换得到的离散频域函数\n #对噪声反向补偿\n fft = fft-noise_fft\n # 滤波并保留landmark----(出现的时���,频率)\n max1 = np.max(fft[:10])\n max2 = np.max(fft[10:20])\n max3 = np.max(fft[20:40])\n max4 = np.max(fft[40:80])\n max5 = np.max(fft[80:160])\n max6 = np.max(fft[160:511])\n aver_max = (max1 + max2 + max3 + max4 + max5 + max6) / 6\n if aver_max > max_aver_max:\n max_aver_max = aver_max\n ffts.append(fft[:windows_size // 2])\n max_aver_max *= 0.8\n for i in range(len(ffts)):\n for j in range(windows_size // 2): # 只有前一般的频谱是不重复的,所以统计landmark只统计前一半\n if ffts[i][j] > max_aver_max:\n self.landmarks.append((int((i)), int(j * windows_density)))\n #!!!\n time.append(int(i))\n frequency.append(int(j * windows_density))\n\n # 计算锚(取targetzone为紧跟在锚点后面的5个点),储存在fps中,每个锚就是一个指纹,用一个tuple表示:(锚点绝对时间位置,锚点频率,目标点频率,时间差)-------全部转换成string!\n self.fps = []\n for i in range(0, len(self.landmarks) - 5):\n for j in range(i+1, i + 6):\n self.fps.append((str(self.landmarks[i][0]), str(self.landmarks[i][1]), str(self.landmarks[j][1]),\n str(self.landmarks[j][0] - self.landmarks[i][0])))\n #!!!\n plt.scatter(time, frequency)\n plt.show()\n print(len(self.landmarks))\n\n\n\n else:\n self.landmarks = [] # 用landmarks储存landmark,landmark是一个tuple:(时间,频率),并根据先时间后频率对landmark在list中从前到后排序\n '''\n time = []\n frequency = []\n '''\n #每次的fft先暂时储存起来!等找出最大的aver_max再秋后算账(处理处landmark)\n ffts=[]\n max_aver_max=0\n for i in range(0, self.nframes - windows_size, windows_size):\n window = self.wave_data[0][i:i + windows_size] # window即一个窗口(离散的时域函数)\n #下面两行用汉明窗(删除即默认矩形窗)\n tailored_window = np.array(window) * np.array(hamming_window) # 用haming窗口剪裁\n fft = np.abs(np.fft.fft(tailored_window)) # fft即对这个窗口进行傅里叶转换得到的离散频域函数\n # 滤波并保留landmark----(出现的时间,频率)\n max1 = np.max(fft[:10])\n max2 = np.max(fft[10:20])\n max3 = np.max(fft[20:40])\n max4 = np.max(fft[40:80])\n max5 = np.max(fft[80:160])\n max6 = np.max(fft[160:511])\n aver_max = (max1 + max2 + max3 + max4 + max5 + max6) / 6\n if aver_max>max_aver_max:\n max_aver_max=aver_max\n ffts.append(fft[:windows_size//2])\n max_aver_max *= 0.8\n for i in range(len(ffts)):\n for j in range(windows_size // 2): # 只有前一般的频谱是不重复的,所以统计landmark只统计前一半\n if ffts[i][j] > max_aver_max:\n self.landmarks.append((int((i)), int(j * windows_density)))\n '''\n time.append(int(i))\n frequency.append(int(j * windows_density))\n '''\n # 计算锚(取targetzone为紧跟在锚点后面的5个点),储存在fps中,每个锚就是一个指纹,用一个tuple表示:(锚点绝对时间位置,锚点频率,目标点频率,时间差)-------全部转换成string!\n self.fps = []\n for i in range(0, len(self.landmarks) - 5):\n for j in range(i+1, i+6):\n self.fps.append((str(self.landmarks[i][0]), str(self.landmarks[i][1]), str(self.landmarks[j][1]), str(self.landmarks[j][0] - self.landmarks[i][0])) )\n '''\n plt.scatter(time, frequency)\n plt.show()\n print(len(self.landmarks))\n '''\n\n #设等待时长是2s,所用时间大概0.26秒\n #输入:wait_time开始录音前的等待时间,windows_size窗口大小; 输出噪声的频谱\n def denoise(self, wait_time, windows_size):\n windows_num=wait_time*self.framerate//windows_size #根据(等待时间内)总的帧数与窗口大小确定一共几个窗口,各个窗口分别计算频谱后取平均\n ffts=[]\n for i in range(0, wait_time*self.framerate, windows_size):\n window=self.wave_data[0][i:i+windows_size]\n fft=np.abs(np.fft.fft(window))\n ffts.append(fft)\n average_fft=np.array([0 for i in range(windows_size)])\n for i in range(windows_num):\n for j in range(windows_size):\n average_fft[j]+=ffts[i][j]\n for j in range(windows_size):\n average_fft[j]/=windows_num\n return average_fft\n\n\n\n\n def play(self, filepath):\n '''\n 音频播放方法\n :param filepath:文件路径\n :return:\n '''\n chunk = 1024 #一次读取1024字节数据\n wf = wave.open(filepath, 'rb')\n p = pyaudio.PyAudio()\n # 打开声音输出流\n stream = p.open(format=p.get_format_from_width(wf.getsampwidth()),\n channels=wf.getnchannels(),\n rate=wf.getframerate(),\n output=True)\n # 写声音输出流进行播放\n while True:\n data = wf.readframes(chunk)\n if data == \"\": break\n stream.write(data)\n stream.close()\n p.terminate()\n\n\nif __name__ == '__main__':\n p=voice()\n p.play('65538test.wav')\n","sub_path":"final_project/on_linux_part/My_process.py","file_name":"My_process.py","file_ext":"py","file_size_in_byte":9480,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"424736893","text":"#from scipy.stats import ttest_ind\nimport numpy as np\nfrom scipy.stats import t\nfrom scipy.stats import ttest_ind\n\ntest_methods = {\"welch_ttest\" : lambda v1, v2: welch_ttest(v1, v2)}\n\ndef welch_ttest(v1, v2):\n #m1, m2 = v1.mean() ,v2.mean()\n ts, p_value = ttest_ind(v1, v2, equal_var=False)\n return(p_value)\n\n\ndef welch_ttest_rebuilt(v1, v2):\n m1, m2 = v1.mean(), v2.mean()\n n1, n2 = len(v1), len(v2)\n var1, var2 = n1 / (n1 - 1) * v1.var(), n2 / (n2 - 1) * v2.var()\n\n ts = np.absolute(m2 - m1) / np.sqrt(var1 / n1 + var2 / n2)\n v = ((var1 / n1 + var2 / n2) ** 2\n / (var1 ** 2 / n1 ** 2 / (n1 - 1) + var2 ** 2 / n2 ** 2 / (n2 - 1))\n )\n p_value = 2 * (1 - t.cdf(ts, v))\n return (p_value)\n","sub_path":"TestMethods.py","file_name":"TestMethods.py","file_ext":"py","file_size_in_byte":733,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"480319462","text":"#!/usr/bin/python\r\n\r\ndef closest(pos, boards):\r\n ranges = []\r\n jarak = []\r\n for board in boards:\r\n x = abs(board[0] - pos[0])\r\n y = abs(board[1] - pos[1])\r\n ranges.append([x,y])\r\n for range in ranges:\r\n jarak.append(range[0] + range[1]) \r\n return boards[jarak.index(min(jarak))] #result => matrix terdekat\r\n \r\ndef move(pos, terdekat):\r\n \r\n if (pos[0] > terdekat[0]):\r\n return 'LEFT'\r\n elif (pos[0] < terdekat[0]):\r\n return 'RIGHT'\r\n elif (pos[1] < terdekat[1]):\r\n return 'DOWN'\r\n elif (pos[1] > terdekat[1]):\r\n return 'UP'\r\n elif (pos[0] == terdekat[0]):\r\n if (pos[1] == terdekat[1]):\r\n return 'CLEAN'\r\n \r\n \r\n \r\ndef dirty_finder(boards):\r\n dirty = []\r\n for i in xrange(len(boards)): \r\n col = boards[i]\r\n for n in xrange(len(col)):\r\n if (col[n] == 'd'):\r\n dirty.append([n,i])\r\n return dirty \r\n\r\ndef location(x, y):\r\n coordinat = [x, y]\r\n return coordinat \r\n\r\n\r\n#(x,y) \r\n\r\ndef next_move(bot_x, bot_y, board):\r\n dirty = dirty_finder(board)\r\n bot = [bot_y, bot_x] #ditukar posisi\r\n terdekat = closest(bot, dirty)\r\n \r\n print(move(bot, terdekat))\r\n #continue on print function\r\n #print terdekat[0]\r\n #print terdekat[1] \r\n\r\nif __name__ == \"__main__\":\r\n dirty = []\r\n terdekat = []\r\n bot = [int(i) for i in raw_input().strip().split()]\r\n board = [[j for j in raw_input().strip()] for i in range(5)]\r\n \r\n \r\n next_move(bot[0], bot[1], board)\r\n \r\n \r\n","sub_path":"botclean.py","file_name":"botclean.py","file_ext":"py","file_size_in_byte":1572,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"95409568","text":"import flask\nfrom celery import Celery\nfrom flask_migrate import Migrate\nfrom flask_login import LoginManager\nfrom flask_mail import Mail\nfrom flask_bootstrap import Bootstrap\nfrom flask_moment import Moment\nfrom flask_sqlalchemy import SQLAlchemy\n\n\nclass FlaskCelery(Celery):\n\n def __init__(self, *args, **kwargs):\n\n super(FlaskCelery, self).__init__(*args, **kwargs)\n self.patch_task()\n\n if 'app' in kwargs:\n self.init_app(kwargs['app'])\n\n def patch_task(self):\n TaskBase = self.Task\n _celery = self\n\n class ContextTask(TaskBase):\n abstract = True\n\n def __call__(self, *args, **kwargs):\n if flask.has_app_context():\n return TaskBase.__call__(self, *args, **kwargs)\n else:\n with _celery.app.app_context():\n return TaskBase.__call__(self, *args, **kwargs)\n\n self.Task = ContextTask\n\n def init_app(self, app):\n self.app = app\n self.config_from_object(app.config)\n\ncelery = FlaskCelery()\ndb = SQLAlchemy()\nmigrate = Migrate()\nlogin = LoginManager()\nlogin.login_view = 'auth.login'\nlogin.login_message = 'Please log in to access this page.'\nmail = Mail()\nbootstrap = Bootstrap()\nmoment = Moment()\n","sub_path":"extensions.py","file_name":"extensions.py","file_ext":"py","file_size_in_byte":1290,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"394360014","text":"from __future__ import absolute_import\n\nimport npyscreen\n\nfrom mylinux.libs import overrides\nfrom mylinux.libs import AppErr\n\nfrom .SelectForm import SelectForm\n\nclass SelectApp(npyscreen.NPSAppManaged):\n\trequiredModelValues = [\n\t\t'action',\n\t\t'packages',\n\t\t'modules',\n\t\t'classes',\n\t\t'packageNames',\n\t\t'packageInfos',\n\t\t'packageStates',\n\t\t'configStates'\n\t]\n\n\t@overrides(npyscreen.NPSAppManaged)\n\tdef onStart(self):\n\n\t\tself.setModelValues()\n\t\tself.checkModelValues()\n\n\t\tself.mainForm = SelectForm(\n\t\t\tname='Select & {0} packages'.format(self.modelValues['action'].upper())\n\t\t)\n\n\t\tself.mainForm.action = self.modelValues['action']\n\t\tself.mainForm.packages = self.modelValues['packages']\n\t\tself.mainForm.modules.values = self.modelValues['modules']\n\t\tself.mainForm.classes.values = self.modelValues['classes']\n\t\tself.mainForm.packageNames.values = self.modelValues['packageNames']\n\t\tself.mainForm.packageInfos.values = self.modelValues['packageInfos']\n\t\tself.mainForm.packageStates.values = self.modelValues['packageStates']\n\t\tself.mainForm.configStates.values = self.modelValues['configStates']\n\n\t\t''' REGISTER FORM '''\n\t\tself.registerForm('MAIN', self.mainForm)\n\n\t@overrides(npyscreen.NPSAppManaged)\n\tdef onCleanExit(self):\n\t\tself.exit(packageNames=self.mainForm.packageNames.get_selected_objects())\n\n\tdef checkModelValues(self):\n\t\terror = []\n\t\tfor requiredElement in SelectApp.requiredModelValues:\n\t\t\tif not requiredElement in self.modelValues:\n\t\t\t\terror.append(requiredElement)\n\n\t\tif error:\n\t\t\traise AppErr.developer('Missing in modelValues! ==> ' + str(error))\n\n\tdef setModelValues(self):\n\t\tpass\n\n\tdef exit(self, packageNames):\n\t\tpass\n","sub_path":"mylinux/view/tuiElement/SelectApp.py","file_name":"SelectApp.py","file_ext":"py","file_size_in_byte":1651,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"600339519","text":"#!/usr/bin/env python\n\"\"\"Convert the WCS coordinates in a polarization file to pixels.\nUses rotatevector.py to do the heavy lifting.\"\"\"\n\nfrom readcmd import ReadCmd\nimport os,sys\n\nspec = \"\"\"in = ??? # Input polarization file\n fits = ??? # FITS image\n out = ??? # Output file\n ext = 0 # Extension number\n cd = False # Set to True to use cd_matrix instead of cdelt\"\"\"\n\narg = ReadCmd(spec,__doc__)\ninfile = arg.getstr('in',exist=True)\nfits = arg.getstr('fits',exist=True)\noutfile= arg.getstr('out',exist=False)\next = arg.getint('ext')\ncdFlag = arg.getstr('cd')\n\nimport nlclib\n\nblah = nlclib.createtempname() # new file made by rotatevector.py\n\n# get path of this script so we can call rotatevector.py in the same dir\npath,junk = os.path.split(os.path.abspath(sys.argv[0]))\nos.system('%s/rotatevector.py in=%s fits=%s out=%s ext=%d cd=%s' %(path,\n infile,fits,blah,ext,cdFlag))\n\ndata1 = nlclib.readdata(infile)\ndata2 = nlclib.readdata(blah,dtype=float)\n\nif len(data1) != len(data2):\n arg.error('Problem rotating vectors!')\n\nfp = open(outfile,'w')\nfp.write('# x y Pol dPol Angle dAngle H dH Filename\\n')\nfp.write('# (pix) (pix) (%) (%) (deg) (deg) (mag) (mag) (string)\\n')\n\nfor l1,l2 in zip(data1,data2):\n fp.write('%8.3f %8.3f ' %(l2[0],l2[1])) # x,y from data2\n fp.write('%6s %6s ' %(l1[2],l1[3])) # pol,dpol from data1\n try:\n fp.write('%7.3f %7s ' %(l2[3],l1[5])) # angle from data2,dangle from data1\n except IndexError:\n fp.close()\n arg.error('Missing angle or delta angle for input file')\n try:\n fp.write('%7s %7s ' %(l1[6],l1[7])) # Hmag,dHmag from data1\n fp.write('%s\\n' %(l1[8])) # filename from data1\n except IndexError:\n fp.write('%7s %7s ' %('0.00','0.00')) # Hmag,dHmag\n fp.write('%s\\n' %infile) # filename \nfp.close()\n\nnlclib.remove(blah)\n","sub_path":"polarization/sky2xy.py","file_name":"sky2xy.py","file_ext":"py","file_size_in_byte":1962,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"540590668","text":"#minimax.py - example of minimax algorithm using tic-tac-toe (X's and O's)\n# 2 players, each player makes best move so that they will win (playing optimally)\n# P1 = 'X', P2 = 'O', P1 goes first\n# based off http://beej.us/blog/data/minimax/\n\nRESULT_P1_WIN = 1\nRESULT_P2_WIN = 2\nRESULT_DRAW = 3\nRESULT_NONE = 4\n\nPOSITIVE_INFINITY = 1\nNEGATIVE_INFINITY = -1\nDRAW = 0\n\nclass Turn:\n\tdef __init__(self, move=[-1, -1], result=RESULT_NONE):\n\t\tself.move = move\n\t\tself.result = result\n\n\tdef __repr__(self):\n\t\treturn (\"Turn - %s, %d\") % (self.move, self.result)\n\ndef minimax(board, isP1Turn, turn):\n\tresult = getResult(board)\n\tif result == RESULT_P1_WIN:\n\t\tturn.result = POSITIVE_INFINITY\n\t\treturn\n\telif result == RESULT_P2_WIN:\n\t\tturn.result = NEGATIVE_INFINITY\n\t\treturn\n\telif result == RESULT_DRAW:\n\t\tturn.result = DRAW\n\t\treturn\n\n\tmoves = getMoves(board)\n\n\tif isP1Turn:\n\t\t# want to get maximum result from moves so that p1 wins\n\t\tturn.result = NEGATIVE_INFINITY\n\t\tfor move in moves:\n\t\t\tnewBoard = doMove(move, board, True)\n\t\t\tnewTurn = Turn(move)\n\t\t\tminimax(newBoard, False, newTurn)\n\t\t\tif newTurn.result > turn.result:\n\t\t\t\tturn.move = move\n\t\t\t\tturn.result = newTurn.result\n\telse:\n\t\t# want to get minimum result from moves so that p1 loses (p2 wins)\n\t\tturn.result = POSITIVE_INFINITY\n\t\tfor move in moves:\n\t\t\tnewBoard = doMove(move, board, False)\n\t\t\tnewTurn = Turn(move)\n\t\t\tminimax(newBoard, True, newTurn)\n\t\t\tif newTurn.result < turn.result:\n\t\t\t\tturn.move = move\n\t\t\t\tturn.result = newTurn.result\n\ndef main():\n\tboard = []\n\tfor i in range(3):\n\t\tboard.append(raw_input().split())\n\n\tturn = Turn()\n\tminimax(board, True, turn)\n\tprint(('Best move for p1 - %d, %d - result - %d') % (turn.move[0], turn.move[1], turn.result))\n\ndef getResult(board):\n\tfor i in range(3):\n\t\twinnerHorizontal = (board[i][0] == 'X' or board[i][0] == 'O') and (board[i][0] == board[i][1] == board[i][2])\n\t\tif winnerHorizontal:\n\t\t\tif board[i][0] == 'X':\n\t\t\t\treturn RESULT_P1_WIN\n\t\t\telse:\n\t\t\t\treturn RESULT_P2_WIN\n\n\tfor i in range(3):\n\t\twinnerVertical = (board[0][i] == 'X' or board[0][i] == 'O') and (board[0][i] == board[1][i] == board[2][i])\n\t\tif winnerVertical:\n\t\t\tif board[0][i] == 'X':\n\t\t\t\treturn RESULT_P1_WIN\n\t\t\telse:\n\t\t\t\treturn RESULT_P2_WIN\n\n\twinnerDiagonal = (board[0][0] == 'X' or board[0][0] == 'O') and (board[0][0] == board[1][1] == board[2][2])\n\twinnerDiagonal = winnerDiagonal or ((board[0][2] == 'X' or board[0][2] == 'O') and (board[0][2] == board[1][1] == board[2][0]))\n\tif winnerDiagonal:\n\t\tif board[1][1] == 'X':\n\t\t\treturn RESULT_P1_WIN\n\t\telse:\n\t\t\treturn RESULT_P2_WIN\n\n\t# if squares are all Xs or Os, result is draw\n\tfor i in range(3):\n\t\tfor j in range(3):\n\t\t\tif board[i][j] != 'X' and board[i][j] != 'O':\n\t\t\t\treturn RESULT_NONE\n\treturn RESULT_DRAW\n\ndef getMoves(board):\n\tmoves = []\n\tfor i in range(3):\n\t\tfor j in range(3):\n\t\t\tif board[i][j] != 'X' and board[i][j] != 'O':\n\t\t\t\tmoves.append([i, j])\n\treturn moves\n\ndef doMove(move, board, isP1Turn):\n\tnewBoard = [row[:] for row in board]\n\tsymbol = 'X' if isP1Turn else 'O'\n\tnewBoard[move[0]][move[1]] = symbol\n\treturn newBoard\n\ndef printBoard(board):\n\tprint(\"\\n\".join(map(str, board)))\n\n\n\nmain()\n\t\n\n","sub_path":"minimax.py","file_name":"minimax.py","file_ext":"py","file_size_in_byte":3127,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"317993437","text":"#Este comando de import serve para importar uma lista de estilos para seu progama.\nimport random\n#Aqui embaixo temos as palavras nas quais vão fazer parte do progama.\npalavras = [ ]\n# Letras erradas e certas estão em branco porque na hora do progama ele vai acrescentar o que a pessoa escreveu.\nletrasErradas = ''\nletrasCertas = ''\n#Ele mostra as imagens que vão ser impressas na tela na hora do progama.\nFORCAIMG = ['''\n \n +---+\n | |\n |\n |\n |\n |\n=========''','''\n \n +---+\n | |\n O |\n |\n |\n |\n=========''','''\n \n +---+\n | |\n O |\n | |\n |\n |\n=========''','''\n \n +---+\n | |\n O |\n /| |\n |\n |\n=========''','''\n \n +---+\n | |\n O |\n /|\\ |\n |\n |\n=========''','''\n \n +---+\n | |\n O |\n /|\\ |\n / |\n |\n=========''','''\n \n +---+\n | |\n O |\n /|\\ |\n / \\ |\n |\n=========''']\n\ndef receberpalavras():\n global palavras\n while True:\n p=input('Digite as palavras desejadas:') \n palavras.append(p)\n if p ==\"\":\n break\n#O def serve para criar uma função.\ndef principal():\n \"\"\"\n Função Princial do programa\n \"\"\"\n print('F O R C A')\n receberpalavras()\n#O print serve para que apareça na tela o que você deseja,geralmente o resultado final.No caso para dizer o nome do jogo.\n palavraSecreta = sortearPalavra()\n #Este comando sortea uma das palavras,para ser a palavra na qual a pessoa tem que adivinhar.\n palpite = ''\n #O palpite te da a chance de você falar uma letra.\n desenhaJogo(palavraSecreta,palpite)\n#While True é um looping feito para que você diga uma letra e ele te fala se está certo ou errado.\n while True:\n palpite = receberPalpite() \n desenhaJogo(palavraSecreta,palpite)\n if perdeuJogo():\n #O if significa 'Se'.\n print('Voce Perdeu!!!')\n #Se você errou o palpite ele dirá 'Você perdeu'.\n break\n #Com o break você paralisa o progama.\n if ganhouJogo(palavraSecreta):\n print('Voce Ganhou!!!')\n #Se você acertar o palpite ele dirá que você 'Você ganhou'.\n break \n \ndef perdeuJogo():\n #Aqui com este def você criou uma função.\n global FORCAIMG\n #O global é uma variavel na qual pode chamar outra variavel de qualquer lugar do progama.\n if len(letrasErradas) == len(FORCAIMG):\n #O len é para falar quantos itens tem na lista.\n return True\n #O return True ele retorna para quem lhe chamou,em verdade. \n else:\n return False\n #O return False retorna para quem lhe chamou,em falso.\ndef ganhouJogo(palavraSecreta):\n global letrasCertas\n ganhou = True\n for letra in palavraSecreta:\n #Se a letra este na palavra secreta você acertou.\n #O for é para falar que um item está dentro da lista.\n if letra not in letrasCertas:\n ganhou = False\n #Se a letra não tiver na palvra você errou.\n return ganhou \n \n\n\ndef receberPalpite():\n \n palpite = input(\"Adivinhe uma letra: \")\n #Você poderá falar uma letra.\n palpite = palpite.upper()\n if len(palpite) != 1:\n print('Coloque um unica letra.')\n receberPalpite()\n #Aqui o progama te avisa de que só pode falar uma palvra por vez.\n elif palpite in letrasCertas or palpite in letrasErradas:\n print('Voce ja disse esta letra.')\n receberPalpite()\n #Aqui o comando te avisa se você está falando uma letra,na qual você ja falou.\n #O elif é para o comando de 'Se não se'.\n elif not \"A\" <= palpite <= \"Z\":\n print('Por favor escolha apenas letras')\n receberPalpite()\n #Neste caso é se você escrever um número ou outra coisa que não seja uma letra.\n else:\n #O else é um comando de 'Se não'.\n return palpite\n \n \ndef desenhaJogo(palavraSecreta,palpite):\n global letrasCertas\n global letrasErradas\n global FORCAIMG\n\n print(FORCAIMG[len(letrasErradas)])\n \n \n vazio = len(palavraSecreta)*'-'\n \n if palpite in palavraSecreta:\n letrasCertas += palpite\n else:\n letrasErradas += palpite\n\n for letra in letrasCertas:\n for x in range(len(palavraSecreta)):\n if letra == palavraSecreta[x]:\n vazio = vazio[:x] + letra + vazio[x+1:]\n \n print('Acertos: ',letrasCertas )\n print('Erros: ',letrasErradas)\n print(vazio)\n \n\ndef sortearPalavra():\n global palavras\n return random.choice(palavras).upper()\n\n \nprincipal()\n","sub_path":"forca-comentario-por-ana-maria.py","file_name":"forca-comentario-por-ana-maria.py","file_ext":"py","file_size_in_byte":4615,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"611323386","text":"#!/usr/bin/python\n#Topology for Assignment 5 Comnetii ECE423/544\n#Author: Sanyam Jain\nfrom socket import socket, AF_INET, SOCK_DGRAM\nimport MulticastPacket as p\n\nclass Host3:\n\n def sendReceive(self):\n currentNode=103\n s = socket(AF_INET, SOCK_DGRAM)\n s.bind(('localhost', 1026))\n try:\n while(True):\n data, addr = s.recvfrom(1024)\n pkttype, pktlen, ndest, rdst, dest1, dest2, dest3, src, seq = p.read_header_datapacket(data)\n print(p.read_data_datapacket(data).decode('utf-8') + \" from \",src)\n if(currentNode==dest1):\n ackPacket=p.create_dataack(5,1,currentNode,202)\n s.sendto(ackPacket,addr)\n\n except KeyboardInterrupt:\n s.close()\n print('interrupted!')\n\ndef run():\n h2 = Host3()\n h2.sendReceive()\n\nif __name__ == '__main__':\n run()\n","sub_path":"comnets2/Host3.py","file_name":"Host3.py","file_ext":"py","file_size_in_byte":911,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"274100704","text":"import sys\nfrom rpiDevices.rpi import tc08\n\nif __name__ == '__main__':\n # Initiate an instance of the tc08 class to startup the unit\n # Specify the channels used by the instance.\n\n try:\n channels = [int(f) for f in sys.argv[1:]]\n if not channels:\n raise IndexError\n except:\n channels = [1,3,5,7]\n\n tc = tc08(channel=channels)\n\n # tc08.get_temp() returns both the temperatures on the channels specified (as a dict) and the temperature of the cold junction.\n output_temp = tc.get_temp()\n\n for ch in channels:\n print(f'Ch {ch} temperature = {output_temp[ch]:.2f}')\n\n # Shutdown unit\n tc.shutdown()","sub_path":"Examples/tc08.py","file_name":"tc08.py","file_ext":"py","file_size_in_byte":663,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"288411793","text":"'''\nA school punishes students if they are absent more than once per term,\nor if they are ever late 3 days in a row. Accordingly, every day,\nfor each student, the school records a single letter:\n'A' for absent,\n'O' for on time, and\n'L' for late.\nFor example: \"LAOLL\" (Here, the student is not in trouble\nbecause there is only one absence, and although there are 3 late days, they are not consecutive.)\n\nWrite a program that returns the number of strings of length 30\nfor which the student is in good standing.\n'''\n\nfrom itertools import *\nimport re\ndef checkRecord(n):\n all_comb = []\n count = 0\n comb = list(combinations_with_replacement('ALP', n))\n for c in comb:\n permute = list(permutations(c, n))\n\n for p in permute:\n string = \"\"\n for ele in p:\n string += ele\n if string not in all_comb:\n all_comb.append(string)\n\n for record in all_comb:\n if re.findall('LLL', record) or len(re.findall('A', record)) >= 2:\n count += 1\n print (len(all_comb) - count)\n\ncheckRecord(2)\n\n\n'''\nDP: Top-Down \n'''\nfrom itertools import *\nimport re\n\n\nclass Solution:\n def checkRecord(self, n: int) -> int:\n M = 1000000007\n\n @cache\n def dfs(n, cons_L, has_A):\n\n if n == 0:\n return 1\n tmp = 0\n # if (n,cons_L,has_A) in cache:\n # return cache[n,cons_L,has_A]\n if not has_A:\n tmp += dfs(n - 1, 0, True)\n tmp %= M\n if cons_L < 2:\n tmp += dfs(n - 1, cons_L + 1, has_A)\n tmp %= M\n tmp += dfs(n - 1, 0, has_A)\n tmp %= M\n\n # cache[n,cons_L,has_A] = tmp\n return tmp\n\n return dfs(n, 0, False)\n\n\n'''\nBottom Up Approach\n'''\nfrom itertools import *\nimport re\n\n\nclass Solution:\n def checkRecord(self, n: int) -> int:\n M = 1000000007\n\n dp = [[[0 for _ in range(2)] for _ in range(3)] for _ in range(n + 1)]\n # Base Cases\n dp[1][0][0] = 1\n dp[1][0][1] = 1\n dp[1][1][0] = 1\n dp[1][1][1] = 0\n dp[1][2][0] = 0\n dp[1][2][1] = 0\n for i in range(2, n + 1):\n dp[i][0][0] = (dp[i - 1][0][0] + dp[i - 1][1][0] + dp[i - 1][2][0]) % M # no A\n dp[i][0][1] = dp[i][0][0] + (dp[i - 1][0][1] + dp[i - 1][1][1] + dp[i - 1][2][1]) % M # one A\n dp[i][1][0] = dp[i - 1][0][0] % M\n dp[i][1][1] = dp[i - 1][0][1] % M\n dp[i][2][0] = dp[i - 1][1][0] % M\n dp[i][2][1] = dp[i - 1][1][1] % M\n total = 0\n for i in range(3):\n for j in range(2):\n total += dp[-1][i][j]\n total %= M\n return total\n","sub_path":"Leetcode_Practice/Backtracking/studentAttendance.py","file_name":"studentAttendance.py","file_ext":"py","file_size_in_byte":2764,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"222156831","text":"import csv\n\n\nclass City:\n def __init__(self, name, lat, lng, country):\n self.name = name\n self.lat = lat\n self.lng = lng\n self.country = country\n\n def __str__(self):\n return f\"{self.name}\"\n\n def __repr__(self):\n return f\"City(name={self.name!r}, lat={self.lat}, lng={self.lng}, country={self.country!r})\"\n\n\ndef main():\n with open(\"../data/worldcities.csv\") as csv_file:\n reader = csv.DictReader(csv_file)\n\n for row in reader:\n city = City(\n name=row['city_ascii'],\n lat=float(row['lat']),\n lng=float(row['lng']),\n country=row['country'],\n )\n\n if city.country != \"Israel\":\n continue\n\n print(repr(city))\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"examples/cities_1_csv/cities_csv03_class_0repr.py","file_name":"cities_csv03_class_0repr.py","file_ext":"py","file_size_in_byte":829,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"239649156","text":"import gym\nfrom gym import error, spaces, utils\nfrom gym.utils import seeding\n\nimport pybullet as p\nimport pybullet_data\nimport numpy as np\nimport cv2\nimport os\nimport inspect\nimport time\n\nimport pkg_resources\n\ncurrentdir = os.path.dirname(os.path.abspath(\n inspect.getfile(inspect.currentframe())))\nparentdir = os.path.dirname(os.path.dirname(currentdir))\nos.sys.path.insert(0, parentdir)\n\n\nclass finger():\n lower = None\n upper = None\n\n def __init__(self, lower_joint, upper_joint,handid,clientId):\n self.lower = lower_joint\n self.upper = upper_joint\n self.handid = handid\n self.clientId=clientId\n\n def rotate(self, lower_angle, upper_angle):\n p.setJointMotorControlArray(bodyIndex=self.handid,\n jointIndices=(self.lower, self.upper),\n controlMode=p.POSITION_CONTROL,\n targetPositions=(lower_angle, upper_angle),\n forces=[500, 500],\n physicsClientId=self.clientId)\n p.stepSimulation(physicsClientId=self.clientId)\n\n\nclass robo_hand():\n fingers = list()\n elbow_index = 0\n wrist_index = 1\n\n def __init__(self,handid,finger_joint_indices,clientId):\n \n self.handid=handid\n self.finger_joint_indices = finger_joint_indices\n self.clientId=clientId\n self.wave_arm(0)\n for indices in self.finger_joint_indices:\n self.fingers.append(finger(*indices,self.handid,self.clientId))\n\n def fold_finger(self, index, lower_angle, upper_angle):\n self.fingers[index].rotate(lower_angle, upper_angle)\n \n def wave_arm(self, angle):\n # p.resetJointState(\n # bodyUniqueId=self.handid,\n # jointIndex=self.elbow_index,\n # targetValue=angle,\n # )\n p.setJointMotorControl2(\n bodyIndex = self.handid,\n jointIndex = self.elbow_index,\n controlMode = p.POSITION_CONTROL,\n targetPosition = angle,\n force = 0.5,\n maxVelocity = 0.4,\n physicsClientId=self.clientId\n )\n p.stepSimulation(physicsClientId=self.clientId)\n\n def move_wrist(self, angle):\n p.setJointMotorControl2(\n bodyIndex = self.handid,\n jointIndex = self.wrist_index,\n controlMode = p.POSITION_CONTROL,\n targetPosition = angle,\n force = 0.5,\n maxVelocity = 0.4,\n physicsClientId=self.clientId\n )\n p.stepSimulation(physicsClientId=self.clientId)\n def array_input(self,arr):\n for i in range(5):\n self.fingers[i].rotate(*arr[i])\n self.move_wrist(arr[5])\n self.wave_arm(arr[6])\n #p.stepSimulation(physicsClientId=self.clientId)\n\n\n\n\nclass HandOfJusticeEnv(gym.Env):\n metadata = {'render.modes':['human']}\n\n def __init__(self,cap=cv2.VideoCapture(0),mod=\"Direct\",epsilon=150,preprocess=None,resolution=(56,56,3)):\n self.cap = cap\n if mod == \"GUI\":\n self.clientId = p.connect(p.GUI)\n ## This is just to see the hand through opengl window so hence set this as you see the hand as you want to see\n else:\n self.clientId = p.connect(p.DIRECT)\n\n \n #p.setRealTimeSimulation(1,physicsClientId=self.clientId)\n #p.resetDebugVisualizerCamera(cameraDistance=2, cameraYaw=0, cameraPitch=-40, cameraTargetPosition=[0,0,2],physicsClientId=self.clientId)\n \n self.action_space = spaces.Box(low=np.array([0]*10+[-0.52,-1.04]) ,high=np.array([1.55]*10+[0.52,1.04]))\n ## down and up (thumb, index, middle, ring, little) , wrist, elbow\n\n if len(resolution)!=3:\n raise Exception(\"Only a ndim n=3 image can be given as a input\")\n\n self.res=resolution\n self.observation_space = spaces.Box(0,2.55,shape=(self.res[0],self.res[1]*2,self.res[2]))\n \n p.setAdditionalSearchPath(pybullet_data.getDataPath())\n self.plane = p.loadURDF( \"plane.urdf\" , physicsClientId=self.clientId)\n p.setAdditionalSearchPath(os.path.abspath(\"Simulation\"))\n self.handid = p.loadURDF(currentdir+\"/hand.urdf\",physicsClientId=self.clientId)\n for i in range(p.getNumJoints(self.handid,physicsClientId=self.clientId)):\n print(p.getJointInfo(bodyUniqueId=self.handid,jointIndex=i,physicsClientId=self.clientId))\n if preprocess is None:\n self.hand_thresh=self.handmask\n else:\n self.hand_thresh=preprocess\n self.epsilon=epsilon ## Find a good one and set as default\n self.seed(int(time.time()))\n ## THis is to match up the no of pixels of our PHATTTT\n p.createConstraint(\n self.handid,\n -1,\n -1,\n -1,\n p.JOINT_FIXED,\n (0, 0, 1),\n (0, 0, 0),\n (0, 0, 0),\n physicsClientId=self.clientId\n )\n finger_joint_indices = (\n (2, 3), # thumb\n (4, 5), # index\n (6, 7), # middle\n (8, 9), # ring\n (10, 11), # little\n )\n self.hand = robo_hand(self.handid,finger_joint_indices,clientId=self.clientId)\n self.resetState = p.saveState()\n self.reset()\n\n\n def seed(self, seed=None):\n self.np_random, seed = seeding.np_random(seed)\n return [seed]\n\n def getImage(self,flag=False):\n position = (0, -3, 2)\n targetPosition = (0, 0, 2)\n viewMatrix = p.computeViewMatrix(\n position, targetPosition, cameraUpVector=[0, 0, 1],\n physicsClientId=self.clientId)\n projectionMatrix = p.computeProjectionMatrixFOV(60, 1, 0.1, 3.5,physicsClientId=self.clientId)\n img = p.getCameraImage(self.res[0], self.res[1], viewMatrix, projectionMatrix,\n renderer=p.ER_BULLET_HARDWARE_OPENGL,\n physicsClientId=self.clientId)\n img = np.reshape(img[2], (self.res[0],self.res[1], 4))\n \n if flag:\n img = img[:,:,:3]\n else:\n img = img[:,:,:3]\n img= cv2.cvtColor(img,cv2.COLOR_RGB2GRAY)\n _,img = cv2.threshold(img,180,255,cv2.THRESH_BINARY_INV)\n\n return img.astype('uint8')\n\n def handmask(self,frame):\n frame=cv2.flip(frame,1)\n kernel = np.ones((3,3),np.uint8)\n #cv2.rectangle(frame,(100,100),(300,400),(0,255,0),0)\n lab = cv2.cvtColor(frame, cv2.COLOR_BGR2LAB)\n lower_skin = np.array([40,120,120], dtype=np.uint8)\n upper_skin = np.array([255,170,170], dtype=np.uint8)\n mask = cv2.inRange(lab, lower_skin, upper_skin)\n #cv2.imshow('mask',mask) ## This would also need a waitkey to work\n #cv2.imshow('frame',frame) ## THis would as crash ones computer as ram is not more that 16 gb in a normal computer\n #cv2.imshow(\"cropped\",cr_frame)\n return mask\n \n def step(self,action):\n #print(armCam.shape)\n #print(tuple(list((action[2*i],action[(2*i)+1]) for i in range(5))+[action[10],action[11]])) \n self.hand.array_input(tuple(list((action[2*i],action[(2*i)+1]) for i in range(5))+[action[10],action[11]]))\n p.stepSimulation(physicsClientId=self.clientId)\n armCam=self.getImage()\n robo = armCam>100\n handthr = self.hand_thresh(self.target) > 100\n u = robo^handthr\n error = np.sum(u)\n if error<=self.epsilon:\n done = True\n else:\n done = False\n\n if self.noofrun>1000:\n done=True\n self.noofrun+=1\n armCam=self.getImage(flag=True)\n return np.append(self.target,armCam,axis=1), -1*error , done, {}\n\n def reset(self):\n p.restoreState(self.resetState)\n p.configureDebugVisualizer(p.COV_ENABLE_RENDERING,0,physicsClientId=self.clientId)\n p.setGravity(0,0,-10)\n self.noofrun=0\n ## Initilize the hand same like the one done in __init__\n ## Or just call to reset to that point\n ## This can be skipped if a continues feel is to be got\n\n\n self.target = self.cap.read()[1]\n try:\n self.target = cv2.resize(self.target,(self.res[0],self.res[1]))\n except:\n print(\"found \",self.target.size)\n raise Exception(\"the aspect tatio of the resolution and the given image doesnt match up\")\n\n return np.append(self.target,self.getImage(flag=True),axis=1)\n\n def render(self,mode='human'):\n armCam=self.getImage(flag=True)\n return armCam\n\n def close(self):\n p.disconnect()\n","sub_path":"Simulation/gym_handOfJustice/build/lib/gym_handOfJustice/envs/handOfJustice_env.py","file_name":"handOfJustice_env.py","file_ext":"py","file_size_in_byte":8684,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"354769343","text":"import argparse\nimport math\nfrom typing import Tuple\n\nimport pandas as pd\n\nimport ray\nfrom ray.data.dataset import Dataset\nfrom ray.ml.batch_predictor import BatchPredictor\nfrom ray.ml.predictors.integrations.sklearn import SklearnPredictor\nfrom ray.ml.preprocessors import Chain, OrdinalEncoder, StandardScaler\nfrom ray.ml.result import Result\nfrom ray.ml.train.integrations.sklearn import SklearnTrainer\n\nfrom sklearn.datasets import load_breast_cancer\nfrom sklearn.ensemble import RandomForestClassifier\nfrom sklearn.model_selection import train_test_split\n\n\ntry:\n from cuml.ensemble import RandomForestClassifier as cuMLRandomForestClassifier\nexcept ImportError:\n cuMLRandomForestClassifier = None\n\n\ndef prepare_data() -> Tuple[Dataset, Dataset, Dataset]:\n data_raw = load_breast_cancer()\n dataset_df = pd.DataFrame(data_raw[\"data\"], columns=data_raw[\"feature_names\"])\n dataset_df[\"target\"] = data_raw[\"target\"]\n # add a random categorical column\n num_samples = len(dataset_df)\n dataset_df[\"categorical_column\"] = pd.Series(\n ([\"A\", \"B\"] * math.ceil(num_samples / 2))[:num_samples]\n )\n train_df, test_df = train_test_split(dataset_df, test_size=0.3)\n train_dataset = ray.data.from_pandas(train_df)\n valid_dataset = ray.data.from_pandas(test_df)\n test_dataset = ray.data.from_pandas(test_df.drop(\"target\", axis=1))\n return train_dataset, valid_dataset, test_dataset\n\n\ndef train_sklearn(num_cpus: int, use_gpu: bool = False) -> Result:\n if use_gpu and not cuMLRandomForestClassifier:\n raise RuntimeError(\"cuML must be installed for GPU enabled sklearn estimators.\")\n\n train_dataset, valid_dataset, _ = prepare_data()\n\n # Scale some random columns\n columns_to_scale = [\"mean radius\", \"mean texture\"]\n preprocessor = Chain(\n OrdinalEncoder([\"categorical_column\"]), StandardScaler(columns=columns_to_scale)\n )\n\n if use_gpu:\n trainer_resources = {\"CPU\": 1, \"GPU\": 1}\n estimator = cuMLRandomForestClassifier()\n else:\n trainer_resources = {\"CPU\": num_cpus}\n estimator = RandomForestClassifier()\n\n trainer = SklearnTrainer(\n estimator=estimator,\n label_column=\"target\",\n datasets={\"train\": train_dataset, \"valid\": valid_dataset},\n preprocessor=preprocessor,\n cv=5,\n scaling_config={\n \"trainer_resources\": trainer_resources,\n },\n )\n result = trainer.fit()\n print(result.metrics)\n\n return result\n\n\ndef predict_sklearn(result: Result, use_gpu: bool = False):\n _, _, test_dataset = prepare_data()\n\n batch_predictor = BatchPredictor.from_checkpoint(\n result.checkpoint, SklearnPredictor\n )\n\n predicted_labels = (\n batch_predictor.predict(\n test_dataset,\n num_gpus_per_worker=int(use_gpu),\n )\n .map_batches(lambda df: (df > 0.5).astype(int), batch_format=\"pandas\")\n .to_pandas(limit=float(\"inf\"))\n )\n print(f\"PREDICTED LABELS\\n{predicted_labels}\")\n\n\nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser()\n parser.add_argument(\n \"--address\", required=False, type=str, help=\"the address to use for Ray\"\n )\n parser.add_argument(\n \"--num-cpus\",\n \"-n\",\n type=int,\n default=2,\n help=\"Sets number of CPUs used for training.\",\n )\n parser.add_argument(\n \"--use-gpu\", action=\"store_true\", default=False, help=\"Enables GPU training\"\n )\n args, _ = parser.parse_known_args()\n\n ray.init(address=args.address)\n result = train_sklearn(num_cpus=args.num_cpus, use_gpu=args.use_gpu)\n predict_sklearn(result, use_gpu=args.use_gpu)\n","sub_path":"python/ray/ml/examples/sklearn_example.py","file_name":"sklearn_example.py","file_ext":"py","file_size_in_byte":3656,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"359278447","text":"#!/usr/bin/env python3\nimport gi\ngi.require_version('Gtk', '3.0')\nfrom gi.repository import Gtk\nfrom datetime import datetime\n\ntime_format = '{hour}:{minute}:{second}.{microsecond}'\n\ndef insert_time(time):\n return time_format.format(\n hour=time.hour,\n minute=time.minute,\n second=time.second,\n microsecond=time.microsecond\n )\n\nui_file = 'ui.glade'\nRIGHT = 1\nLEFT = 0\nb = Gtk.Builder()\nb.add_from_file(ui_file)\nw = b.get_object('window')\nw.connect('destroy', Gtk.main_quit)\nw.show_all()\n\npositions = {LEFT: Gtk.PositionType.RIGHT, RIGHT: Gtk.PositionType.BOTTOM}\n\n\ndef add_row(self, left_content, right_content):\n \"\"\"\n Adds row to a Gtk.Grid with two columns.\n First the right row is added, then left. It is done so because when \n there is nothing in the Gtk.Grid its 'attach_next_to()' method inserts new\n child at the bottom left of Grid. So first we insert a child to left bottom,\n and then we insert a child to the left of existing child.\n \"\"\"\n def add_part_row(side, content):\n self.attach_next_to(\n child=content,\n sibling=self.get_child_at(left=side, top=self.last_row),\n side=positions[side],\n width=1,\n height=1\n )\n add_part_row(RIGHT, right_content)\n print(self.get_children())\n add_part_row(LEFT, left_content)\n print(self.get_children())\n \n self.last_row += 1\n self.show_all()\n\ndef label_to_str(self):\n return self.get_text()\n\n\nsetattr(Gtk.Grid, 'add_row', add_row)\nsetattr(Gtk.Grid, 'last_row', 0)\nsetattr(Gtk.Label, '__str__', label_to_str)\nsetattr(Gtk.Label, '__repr__', label_to_str)\n\ng = b.get_object('grid')\n\ndef a(widget=None, data=None):\n left_time = datetime.now()\n right_time = datetime.now()\n left = Gtk.Label(insert_time(left_time))\n right = Gtk.Label(insert_time(right_time))\n g.add_row(left, right)\n\n\nb.connect_signals({'add_row': a})\n\nif __name__ == '__main__':\n Gtk.main()\n","sub_path":"small_examples/grid/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1969,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"267357243","text":"#!/usr/bin/env python\n# -*- coding:utf-8 -*-\n# @datetime:2018/11/30 11:27\n\n\"\"\"\nGiven a string containing only digits, restore it by returning all possible valid IP address combinations.\n\nExample:\n\nInput: \"25525511135\"\nOutput: [\"255.255.11.135\", \"255.255.111.35\"]\n\"\"\"\n\n\nclass Solution:\n def restoreIpAddresses(self, s):\n \"\"\"\n :type s: str\n :rtype: List[str]\n \"\"\"\n res = []\n for a in range(1, 4):\n for b in range(1, 4):\n for c in range(1, 4):\n for d in range(1, 4):\n if a + b + c + d == len(s):\n A = int(s[:a])\n B = int(s[a:a + b])\n C = int(s[(a + b):a + b + c])\n D = int(s[(a + b + c):a + b + c + d])\n if A <= 255 and B <= 255 and C <= 255 and D <= 255:\n ans = \".\".join([str(A), str(B), str(C), str(D)])\n if len(ans) == len(s) + 3:\n res.append(ans)\n return res\n\n\nif __name__ == '__main__':\n so = Solution()\n testStr = \"25525511135\"\n print(so.restoreIpAddresses(testStr))\n","sub_path":"leetcode/93. Restore IP Addresses.py","file_name":"93. Restore IP Addresses.py","file_ext":"py","file_size_in_byte":1231,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"158629346","text":"from django.views.generic import ListView, FormView, DetailView, View\nfrom leaderboard.models import LeaderBoard\nfrom leaderboard.forms import AddBoardForm\nfrom django.shortcuts import HttpResponseRedirect, render\nfrom django.core.urlresolvers import reverse\nfrom braces.views import LoginRequiredMixin\nfrom guardian.shortcuts import assign_perm\nfrom django.contrib.auth.models import User\n\n\n# Create your views here.\ndef index(request):\n return render(request, 'index.html')\n\n\nclass ListBoardView(ListView):\n model = LeaderBoard\n template_name = 'leaderboard/list_boards.html'\n context_object_name = 'all_my_boards'\n\n\nclass AddBoardView(LoginRequiredMixin, FormView):\n template_name = 'leaderboard/add_board.html'\n form_class = AddBoardForm\n\n #login required optionals TODO tk how to show msg on login page.\n #login_url = '/accounts/login_for_action/'\n\n def post(self, request, *args, **kwargs):\n form = self.form_class(request.POST)\n\n if form.is_valid():\n # \n title = form.cleaned_data['title']\n description = form.cleaned_data['description']\n expiration = form.cleaned_data['expiration']\n creator = request.user\n\n myboard = LeaderBoard(title=title, description=description, expiration=expiration, creator=creator)\n myboard.save()\n # add group permission for the new board\n assign_perm('update_board', myboard.members, myboard)\n\n return HttpResponseRedirect(reverse('leaderboard:list_boards'))\n else:\n return render(request, 'leaderboard/add_board.html', {'form':form})\n\nclass DeleteBoardView(LoginRequiredMixin, FormView):\n\n def get(self, request, *args, **kwargs):\n board_id = self.kwargs['board_id']\n board = LeaderBoard.objects.get(pk=board_id)\n # todo how to soft couple this url?\n return render(request, 'leaderboard/delete_board.html', {'board':board})\n\n def post(self, request, *args, **kwargs):\n board_id = self.kwargs['board_id']\n board = LeaderBoard.objects.get(pk=board_id)\n if (request.user == board.creator):\n board.delete()\n\n return HttpResponseRedirect(reverse('leaderboard:list_boards'))\n\n\nclass ViewBoardDetailsView(DetailView):\n model = LeaderBoard\n template_name = 'leaderboard/view_board.html'\n #context_object_name = 'board'\n #pk_url_kwarg = 'board_id'\n members = []\n\n def get(self, request, *args, **kwargs):\n board_id = self.kwargs['board_id']\n board = LeaderBoard.objects.get(pk=board_id)\n members = board.members.user_set.all()\n\n return render(request, self.template_name, {'board':board, 'members':members})\n\n\nclass UpdateBoardMemberView(LoginRequiredMixin, View):\n template_name='leaderboard/update_board_member.html'\n\n\n def get(self, request, *args, **kwargs):\n # get board\n board_id = self.kwargs['board_id']\n board = LeaderBoard.objects.get(pk=board_id)\n # get creator\n creator = board.creator\n # get current members to board\n members = board.members.user_set.all() #.values('username')\n # create list of usernames\n member_list = list()\n for member in members.values():\n member_list.append(member['username'])\n\n # add creator\n member_list.append(creator)\n\n # get list of all users excluding staff and current users\n all_users = User.objects.exclude(is_staff=True).values('username').exclude(username__in=member_list)\n\n return render(request, self.template_name, {'board':board, 'creator':creator, 'members':members, 'non_members':all_users})\n\n def post(self, request, *args, **kwargs):\n # get board\n board_id = self.kwargs['board_id']\n board = LeaderBoard.objects.get(pk=board_id)\n\n # update members\n add_this_user = request.POST.getlist('add_me')\n add_this_user_obj = User.objects.filter(username__in = add_this_user)\n for this_user in add_this_user_obj:\n this_user.groups.add(board.members)\n\n delete_this_user = request.POST.getlist('delete_me')\n # delete_this_user = _post.getlist('delete_me')\n delete_this_user_obj = User.objects.filter(username__in = delete_this_user)\n for this_user in delete_this_user_obj:\n this_user.groups.remove(board.members)\n\n # redirect to GET view\n url = reverse('leaderboard:update_board_member', kwargs={'board_id':board_id})\n return HttpResponseRedirect(url)\n\n\n\n","sub_path":"leaderboard/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":4589,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"140565525","text":"import os\nimport wget\nimport tarfile\nimport re\nfrom nltk.tokenize import word_tokenize\nimport collections\nimport pandas as pd\nimport pickle\nimport numpy as np\nimport random\n\nTRAIN_DICT_PATH = \"dbpedia_csv/train.csv\"\n\n\ndef download_dbpedia():\n dbpedia_url = 'https://github.com/le-scientifique/torchDatasets/raw/master/dbpedia_csv.tar.gz'\n\n wget.download(dbpedia_url)\n with tarfile.open(\"dbpedia_csv.tar.gz\", \"r:gz\") as tar:\n tar.extractall()\n\n\ndef clean_str(text):\n if re.match('[\\u4e00-\\u9fa5]+', text) is not None:\n if len(text) % 4 == 3:\n text = text + '。'\n char_list = list(text)\n for i, index in enumerate([x.start() for x in re.finditer('[,。?!:]', text)]):\n if i % 2 == 0:\n char_list[index] = ','\n else:\n char_list[index] = '。'\n text = ' '.join(char_list)\n else:\n text = re.sub(r\"[^A-Za-z0-9(),!?\\'\\`\\\"]\", \" \", text)\n text = re.sub(r\"\\s{2,}\", \" \", text)\n text = text.strip().lower()\n return text\n\n\ndef build_word_dict(dict_dir, vocabulary_size=None, dict_src_path=TRAIN_DICT_PATH):\n if not os.path.exists(dict_dir):\n os.makedirs(dict_dir)\n dict_path = os.path.join(dict_dir, \"word_dict.pickle\")\n if os.path.exists(dict_path):\n with open(dict_path, \"rb\") as f:\n word_dict = pickle.load(f)\n # if vocabulary_size is None or len(word_dict) == vocabulary_size:\n print(\"use word dictionary at %s, vocabulary size: %d\" % (dict_path, len(word_dict)))\n return word_dict\n train_df = pd.read_csv(dict_src_path, names=[\"class\", \"title\", \"content\"])\n contents = train_df[\"content\"]\n\n words = list()\n for content in contents:\n for word in word_tokenize(clean_str(content)):\n words.append(word)\n\n word_counter = collections.Counter(words).most_common()\n word_dict = dict()\n word_dict[\"\"] = 0\n word_dict[\"\"] = 1\n word_dict[\"\"] = 2\n word_dict[\" \"] = 3\n for word, count in word_counter:\n if vocabulary_size is None or len(word_dict) != vocabulary_size:\n word_dict[word] = len(word_dict)\n\n with open(dict_path, \"wb\") as f:\n pickle.dump(word_dict, f)\n print(\"build dictionary from %s, vocabulary size: %d\" % (dict_path, len(word_dict)))\n\n return word_dict\n\n\ndef build_word_dataset(train_path, test_path, step, word_dict, document_max_len, label_map=None, up_sample=0):\n if step == \"train\":\n df = pd.read_csv(train_path, names=[\"class\", \"title\", \"content\"])\n else:\n df = pd.read_csv(test_path, names=[\"class\", \"title\", \"content\"])\n\n # Shuffle dataframe\n df = df.sample(frac=1)\n x = list(map(lambda d: word_tokenize(clean_str(d)), df[\"content\"]))\n x = list(map(lambda d: list(map(lambda w: word_dict.get(w, word_dict[\"\"]), d)), x))\n x = list(map(lambda d: d[:document_max_len], x))\n x = list(map(lambda d: d + (document_max_len - len(d)) * [word_dict[\"\"]], x))\n\n # y = list(map(lambda d: d - 1, list(df[\"class\"])))\n y = list(map(lambda d: d, list(df[\"class\"])))\n if label_map is not None:\n y = [label_map[i] for i in y]\n if step == 'train' and up_sample > 0:\n up_samples = len(np.unique(y)) * up_sample\n # if up_samples > len(y):\n z = list(zip(x, y))\n z = z * (int(up_samples / len(y)) + 1)\n z = random.sample(z, up_samples)\n x, y = zip(*z)\n return x, y\n\n\ndef batch_iter(inputs, outputs, batch_size, num_epochs):\n inputs = np.array(inputs)\n outputs = np.array(outputs)\n\n num_batches_per_epoch = (len(inputs) - 1) // batch_size + 1\n for epoch in range(num_epochs):\n for batch_num in range(num_batches_per_epoch):\n start_index = batch_num * batch_size\n end_index = min((batch_num + 1) * batch_size, len(inputs))\n yield inputs[start_index:end_index], outputs[start_index:end_index]\n","sub_path":"data_utils.py","file_name":"data_utils.py","file_ext":"py","file_size_in_byte":3928,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"58148503","text":"from __future__ import absolute_import\n\nfrom torch import nn\n\nfrom torch.nn import init\nfrom torchvision import models\nimport torch\n\n\ndef weights_init_kaiming(m):\n classname = m.__class__.__name__\n # print(classname)\n if classname.find('Conv') != -1:\n init.kaiming_normal(m.weight.data, a=0, mode='fan_in')\n elif classname.find('Linear') != -1:\n init.kaiming_normal(m.weight.data, a=0, mode='fan_out')\n init.constant(m.bias.data, 0.0)\n elif classname.find('BatchNorm1d') != -1:\n init.normal(m.weight.data, 1.0, 0.02)\n init.constant(m.bias.data, 0.0)\n\ndef weights_init_classifier(m):\n classname = m.__class__.__name__\n if classname.find('Linear') != -1:\n init.normal(m.weight.data, std=0.001)\n init.constant(m.bias.data, 0.0)\n\n\nclass ClassBlock(nn.Module):\n def __init__(self, input_dim, class_num, dropout=0, relu=True, num_bottleneck=512):\n super(ClassBlock, self).__init__()\n add_block = []\n add_block += [nn.Linear(input_dim, num_bottleneck)]\n add_block += [nn.BatchNorm1d(num_bottleneck)]\n if relu:\n add_block += [nn.LeakyReLU(0.1)]\n if dropout > 0:\n add_block += [nn.Dropout(dropout)]\n add_block = nn.Sequential(*add_block)\n add_block.apply(weights_init_kaiming)\n\n classifier = []\n classifier += [nn.Linear(num_bottleneck, class_num)]\n classifier = nn.Sequential(*classifier)\n classifier.apply(weights_init_classifier)\n\n self.add_block = add_block\n self.classifier = classifier\n\n def forward(self, x):\n x = self.add_block(x)\n x = self.classifier(x)\n return x\n\n\nclass DenseNet(nn.Module):\n\n def __init__(self, pretrained=True, cut_at_pooling=False,\n num_features=1024, norm=False, dropout=0, num_classes=0 ):\n super(DenseNet,self).__init__()\n model_ft = models.densenet121(pretrained=pretrained)\n model_ft.features.avgpool = nn.AdaptiveAvgPool2d((1, 1))\n model_ft.fc = nn.Sequential()\n self.model = model_ft\n # For DenseNet, the feature dim is 1024\n print (dropout)\n self.classifier = ClassBlock(num_features, num_classes, dropout=dropout)\n self.norm = norm\n self.cut_at_pooling = cut_at_pooling\n self.pretrained = pretrained\n if not self.pretrained:\n print(\"params reset\")\n self.reset_params()\n\n def forward(self, x):\n x = self.model.features(x)\n x = torch.squeeze(x)\n if self.cut_at_pooling:\n return x\n x = self.classifier(x)\n return x\n\n def reset_params(self):\n for m in self.modules():\n if isinstance(m, nn.Conv2d):\n init.kaiming_normal(m.weight, mode='fan_out')\n if m.bias is not None:\n init.constant(m.bias, 0)\n elif isinstance(m, nn.BatchNorm2d):\n init.constant(m.weight, 1)\n init.constant(m.bias, 0)\n elif isinstance(m, nn.Linear):\n init.normal(m.weight, std=0.001)\n if m.bias is not None:\n init.constant(m.bias, 0)\n\n\ndef densenet121(**kwargs):\n return DenseNet(**kwargs)\n","sub_path":"reid/models/densenet.py","file_name":"densenet.py","file_ext":"py","file_size_in_byte":3249,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"53931268","text":"import os\nimport sys\n\ncur_dir = os.path.split(__file__)[0]\nroot_dir = os.path.split(cur_dir)[0]\nsys.path.append(root_dir)\n\nimport time\nimport json\nfrom load.fixed_mean_sent_emb_for_a_company_loader import Loader as CLoader\nfrom load.fixed_mean_sent_emb_loader_v2 import Loader\nfrom models.sim import Model\nfrom lib import logs\n\nModel.name = 'fixed_mean_sent_emb_similarity'\nlogs.MODEL = Model.name\n\n\nclass Train:\n M = Model\n\n def __init__(self):\n company_loader = CLoader(use_cache=True)\n train_loader = Loader(self.M.data_params['neg_rate_train'],\n 0, self.M.data_params['train_ratio'], use_cache=False)\n val_loader = Loader(self.M.data_params['neg_rate_val'],\n self.M.data_params['train_ratio'],\n self.M.data_params['train_ratio'] + self.M.data_params['val_ratio'], use_cache=False)\n test_loader = Loader(self.M.data_params['neg_rate_test'],\n self.M.data_params['train_ratio'] + self.M.data_params['val_ratio'], 1.0, use_cache=False)\n\n self.__X, self.__names = company_loader.all()\n self.__train_X1, self.__train_X2, self.__train_Y, self.__train_names_1, self.__train_names_2 = train_loader.all()\n self.__val_X1, self.__val_X2, self.__val_Y, self.__val_names_1, self.__val_names_2 = val_loader.all()\n self.__test_X1, self.__test_X2, self.__test_Y, self.__test_names_1, self.__test_names_2 = test_loader.all()\n\n logs.new_paragraph(True)\n logs.add(self.M.name, 'data_shape', json.dumps({\n 'X': self.__X.shape,\n 'train_x': self.__train_X1.shape,\n 'train_y': self.__train_Y.shape,\n 'val_x': self.__val_X1.shape,\n 'val_y': self.__val_Y.shape,\n 'test_x': self.__test_X1.shape,\n 'test_y': self.__test_Y.shape,\n }), logs.LEVEL_DATA, True)\n\n def train(self, use_cache=True):\n print('\\nBuilding model ({}) ...'.format(self.M.TIME))\n self.model = self.M()\n\n print('\\nTraining model ...')\n start_time = time.time()\n self.model.train(self.__X, self.__names, use_cache)\n train_time = time.time() - start_time\n print('\\nFinish training')\n\n logs.add(self.M.name, 'training_time', f'{train_time}')\n\n def test(self, load_model=False):\n # load the model\n if load_model:\n self.model = self.M()\n self.model.train(self.__X, self.__names)\n self.__train_time = 0.\n\n self.evaluate('training', self.__train_X1, self.__train_X2, self.__train_Y,\n False, self.__train_names_1, self.__train_names_2)\n self.evaluate('val', self.__val_X1, self.__val_X2, self.__val_Y,\n False, self.__val_names_1, self.__val_names_2)\n self.evaluate('test', self.__test_X1, self.__test_X2, self.__test_Y,\n False, self.__test_names_1, self.__test_names_2)\n\n def evaluate(self, prefix, X1, X2, Y, record_details=False, names_1=None, names_2=None):\n ret = self.model.test(Y, names_1, names_2)\n\n logs.new_line(True)\n for indicator, score in ret.items():\n logs.add(self.M.name, f'{prefix}_evaluation', f'{indicator}: {score}', logs.LEVEL_RET, True)\n\n if record_details:\n predict_y = self.model.predict_labels(names_1, names_2)\n\n logs.new_line(True)\n for i, v in enumerate(predict_y):\n logs.add(\n self.M.name,\n 'test_samples',\n json.dumps({\n 'ret': \"success\" if v == Y[i] else \"fail\",\n 'predict': int(v),\n 'ground_truth': int(Y[i]),\n 'name_1': names_1[i],\n 'name_2': names_2[i],\n }),\n logs.LEVEL_DETAIL,\n False\n )\n\n\n# for i, top_k in enumerate(list(range(370, 510, 10))):\nModel.model_params['top_k'] = 410\nlogs.VARIANT = f'top_{Model.model_params[\"top_k\"]}_threshold_{Model.model_params[\"threshold\"]}_v5'\n\no_train = Train()\no_train.train(use_cache=False)\no_train.test(False)\n","sub_path":"train/fixed_mean_sent_emb_use_sim.py","file_name":"fixed_mean_sent_emb_use_sim.py","file_ext":"py","file_size_in_byte":4218,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"630654830","text":"# 基本的元素, declare several path to pre-downloaded images for use later.\r\nBACKGROUND_PATH = './assets/sprites/background-black.png' #image of the background\r\nPIPE_PATH = './assets/sprites/pipe-green.png' #image of the pipe\r\nBASE_PATH = './assets/sprites/base.png' #image of the ground\r\nPLAYER_PATH = ( #bird has 3 types of form, 1. wing flap upwards; 2. wing flag downwards; 3. wing at middle horizontally\r\n './assets/sprites/redbird-upflap.png',\r\n './assets/sprites/redbird-midflap.png',\r\n './assets/sprites/redbird-downflap.png'\r\n) \r\n\r\n#set up game interface size\r\nSCREENWIDTH = 288\r\nSCREENHEIGHT = 512\r\n\r\n#declare a dictionary to store all kinds of images to be loaded by pygame.\r\nIMAGES = {}\r\n\r\n\r\n\r\nimport pygame\r\nfrom pygame.locals import *\r\nfrom sys import exit #引入sys中exit函数\r\n\r\n#初始化pygame,为使用硬件做准备\r\npygame.init()\r\n\r\n#创建了窗口 - GAME INTERFACE\r\nSCREEN = pygame.display.set_mode((SCREENWIDTH, SCREENHEIGHT))\r\n\r\n#设置窗口标题\r\npygame.display.set_caption(\"Flappy Bird\")\r\n\r\n#load图像,convert vs convert_alpha!\r\nIMAGES['background'] = pygame.image.load(BACKGROUND_PATH).convert() #pygame.image.load().convert: convert whole image to pygame-type-of-image WITH IMAGE'S BACKGROUND (e.g. if background of a picture is black, pygame-type-of-image after conversion will have black background)\r\nIMAGES['base'] = pygame.image.load(BASE_PATH).convert_alpha() #pygame.image.load().convert_alpha: convert whole image to pygame-type-of-image WITHOUT IMAGE'S BACKGROUND (e.g. if background of a picture is white, pygame-type-of-image after conversion will not have any background color)\r\nIMAGES['bird'] = (\r\n pygame.image.load(PLAYER_PATH[0]).convert_alpha(),\r\n pygame.image.load(PLAYER_PATH[1]).convert_alpha(),\r\n pygame.image.load(PLAYER_PATH[2]).convert_alpha(),\r\n)\r\nIMAGES['pipe'] = (\r\n pygame.transform.rotate(pygame.image.load(PIPE_PATH).convert_alpha(), 180), #rotate pipe image upwards for 180 degrees.\r\n pygame.image.load(PIPE_PATH).convert_alpha() #pipe image without rotation.\r\n)\r\n\r\n#get pipe's width adn height information for later use.\r\nPIPE_WIDTH = IMAGES['pipe'][0].get_width()\r\nPIPE_HEIGHT = IMAGES['pipe'][0].get_height()\r\n\r\n# check if QUIT type of event is triggered constantly, if so, then exit the game; if not, then update game interface (pygame.display) with updated background and pipe\r\n # e.g. if user close the window of game interface (click \"X\" at top right corner), for THIS ACTION, event.type=QUIT, then game will exit.\r\nwhile True:\r\n for event in pygame.event.get():\r\n if event.type == QUIT:\r\n exit()\r\n\r\n # background\r\n SCREEN.blit(IMAGES['background'], (0,0)) # insert background at (0,0) position of game interface.\r\n SCREEN.blit(IMAGES['pipe'][0], (0,0)) # rotated pipe (180 degree, upside down), inserted at (0,0) position of game interface. (note: (0,0) is at top left of the game interface, x increased-> means to the right; y increased -> to downside)\r\n SCREEN.blit(IMAGES['pipe'][1], (0,SCREENHEIGHT-PIPE_HEIGHT)) # pipe without rotation, inserted at (0,SCREENHEIGHT-PIPE_HEIGHT) position of game interface.\r\n\r\n\r\n pygame.display.update()\r\n #刷新一下画面\r\n","sub_path":"Data Science_WANMEN_course/Chapter 31. Build Flappy Bird Game from Scratch using Pygame/pygame_1.py","file_name":"pygame_1.py","file_ext":"py","file_size_in_byte":3303,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"595061072","text":"#!/usr/bin/env python3\n\"\"\" Inverse matrix \"\"\"\n\n\ndef determinant(matrix):\n \"\"\" Inverse matrix \"\"\"\n if len(matrix[0]) == 0:\n return 1\n if len(matrix[0]) == 1:\n return matrix[0][0]\n det = 0\n if len(matrix) == 2:\n det = matrix[0][0] * matrix[1][1]\n det -= matrix[0][1] * matrix[1][0]\n return det\n sign = 1\n for j in range(len(matrix[0])):\n tmp = matrix[1:]\n for i in range(len(tmp)):\n tmp[i] = tmp[i][0:j] + tmp[i][j + 1:]\n det += (sign * matrix[0][j]) * determinant(tmp)\n sign *= -1\n return det\n\n\ndef cofactor(matrix):\n \"\"\" Inverse matrix \"\"\"\n if type(matrix) is not list or not matrix:\n raise TypeError(\"matrix must be a list of lists\")\n for x in matrix:\n if type(x) is not list:\n raise TypeError(\"matrix must be a list of lists\")\n if len(matrix) != len(x):\n raise ValueError(\"matrix must be a non-empty square matrix\")\n\n if len(matrix) == 1:\n return [[1]]\n minor_matrix = [x[:] for x in matrix]\n for i in range(len(matrix)):\n sub = matrix[:i] + matrix[i + 1:]\n for j in range(len(matrix)):\n tmp = sub[:]\n for k in range(len(tmp)):\n tmp[k] = tmp[k][0:j] + tmp[k][j + 1:]\n if len(tmp) > 1:\n if len(tmp) > 2:\n minor_matrix[i][j] = ((-1)**(i + j)) * determinant(tmp)\n else:\n a = tmp[0][0]\n b = tmp[0][1]\n c = tmp[1][0]\n d = tmp[1][1]\n minor_matrix[i][j] = ((-1)**(i + j)) * (a * d - b * c)\n else:\n minor_matrix[i][j] = ((-1)**(i + j)) * tmp[0][0]\n return minor_matrix\n\n\ndef adjugate(matrix):\n \"\"\" Inverse matrix \"\"\"\n cofactor_matrix = cofactor(matrix)\n adj_matrix = [[cofactor_matrix[j][i] for j in range(len(cofactor_matrix))]\n for i in range(len(cofactor_matrix))]\n return adj_matrix\n\n\ndef inverse(matrix):\n \"\"\" Inverse matrix \"\"\"\n adj_matrix = adjugate(matrix)\n det = determinant(matrix)\n if det == 0:\n return None\n for i in range(len(adj_matrix)):\n for j in range(len(adj_matrix)):\n adj_matrix[i][j] = adj_matrix[i][j] * 1 / det\n return adj_matrix\n","sub_path":"math/0x05-advanced_linear_algebra/4-inverse.py","file_name":"4-inverse.py","file_ext":"py","file_size_in_byte":2320,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"428807232","text":"import pygame as pg\nimport config as c, resource\n\nclass Coin():\n '''\n flushing coin to blink, showing on top of screen;\n switch images based on time interval to achieve the blinking effect\n '''\n def __init__(self, x, y):\n self.image_sheet = resource.GFX['item_objects']\n self.images = []\n self.create_images(self.images)\n self.image = self.images[0]\n self.image_index = 0\n self.rect = self.image.get_rect()\n self.rect.x, self.rect.y = x, y\n self.time = 0\n\n def create_images(self, images):\n images.append(self.get_image(1, 160, 5, 8))\n images.append(self.get_image(9, 160, 5, 8))\n images.append(self.get_image(17, 160, 5, 8))\n\n def get_image(self, x, y, width, height):\n image = pg.Surface([width, height])\n image.blit(self.image_sheet, (0, 0), (x, y, width, height)) #draw img onto image\n image.set_colorkey(c.BLACK) #创建的surface对象背景色为黑色\n image = pg.transform.scale(image, (int(width * 2.69), int(height * 2.69)))\n return image\n\n def update(self, current_time):\n if self.image_index == 0:\n if current_time - self.time > 375:\n self.image_index = 1\n self.time = current_time\n elif current_time - self.time > 125:\n self.image_index = (self.image_index + 1) % 3\n self.time = current_time\n self.image = self.images[self.image_index]\n","sub_path":"component/flashing_coin.py","file_name":"flashing_coin.py","file_ext":"py","file_size_in_byte":1470,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"387113432","text":"from django_mako_plus.controller import view_function\nimport homepage.models as hmod\nfrom django_mako_plus.controller.router import get_renderer\nfrom django import forms\nfrom homepage.customform import CustomForm\nfrom django.http import Http404, HttpResponseRedirect, HttpResponse\nfrom django.contrib.auth.models import Group\nfrom django.contrib.auth.decorators import permission_required, login_required\n\n\ntemplater = get_renderer('catalog')\n\n\n@view_function\ndef process_request(request):\n params = {}\n site_user_id = request.urlparams[0]\n address_id = request.urlparams[1]\n phone_id = request.urlparams[2]\n\n try:\n user = hmod.SiteUser.objects.get(id=site_user_id)\n except hmod.SiteUser.DoesNotExist:\n return HttpResponseRedirect('/catalog/index/')\n\n try:\n address = hmod.Address.objects.get(id=address_id)\n except hmod.Address.DoesNotExist:\n return HttpResponseRedirect('/catalog/index/')\n\n try:\n phone = hmod.Phone.objects.get(id=phone_id)\n except hmod.Phone.DoesNotExist:\n return HttpResponseRedirect('/catalog/index/')\n\n params[\"user\"] = user\n params[\"address\"] = address\n params[\"phone\"] = phone\n\n return templater.render_to_response(request, 'shipping.html', params)\n\n\n@view_function\ndef edit(request):\n params = {}\n try:\n site_user = hmod.SiteUser.objects.get(id=request.urlparams[0])\n except hmod.SiteUser.DoesNotExist:\n return HttpResponseRedirect('/homepage/users/')\n\n form = SiteUserEditForm(request, initial={\n 'first_name': site_user.first_name,\n 'last_name': site_user.last_name,\n 'username': site_user.username,\n 'password': site_user.password,\n 'security_question': site_user.security_question,\n 'security_answer': site_user.security_answer,\n 'email': site_user.email,\n 'authorization': site_user.groups.all()[0],\n })\n\n if request.method == 'POST':\n form = SiteUserEditForm(request, request.POST) # POST is a dictionary of all the data sent with the form\n if form.is_valid():\n site_user.first_name = form.cleaned_data['first_name']\n site_user.last_name = form.cleaned_data['last_name']\n site_user.username = form.cleaned_data['username']\n site_user.set_password(form.cleaned_data['password'])\n site_user.security_question = form.cleaned_data['security_question']\n site_user.security_answer = form.cleaned_data['security_answer']\n site_user.email = form.cleaned_data['email']\n\n site_user.groups.clear() # remove user from all current groups before adding them to the new group\n\n authorization = Group.objects.get(name=form.cleaned_data['authorization'])\n site_user.groups.add(authorization)\n\n site_user.save()\n return HttpResponseRedirect('/homepage/users/')\n\n params['form'] = form\n\n return templater.render_to_response(request, 'users.edit.html', params)\n\n\nclass SiteUserEditForm(CustomForm):\n BIRTHDAY = \"What is your oldest sibling's birthday month and year?\"\n CITY = 'In what city or town did your mother and father meet?'\n KISS = 'What is the first name of the first person you kissed?'\n NICKNAME = 'What was your childhood nickname?'\n\n SECURITY_QUESTION_CHOICES = (\n (BIRTHDAY, \"What is your oldest sibling's birthday month and year?\"),\n (CITY, 'In what city or town did your mother and father meet?'),\n (KISS, 'What is the first name of the first person you kissed?'),\n (NICKNAME, 'What was your childhood nickname?'),\n )\n first_name = forms.CharField(label='First Name', max_length=100)\n last_name = forms.CharField(label='Last Name', max_length=100)\n username = forms.CharField(min_length=6, max_length=100)\n password = forms.CharField(min_length=4, max_length=100, widget=forms.PasswordInput)\n security_question = forms.ChoiceField(label='Security Question', choices=SECURITY_QUESTION_CHOICES,\n widget=forms.Select)\n security_answer = forms.CharField(label='Security Answer', max_length=50)\n email = forms.EmailField(max_length=50)\n authorization = forms.ModelChoiceField(label='Authorization', queryset=Group.objects.all().order_by('name'),\n widget=forms.RadioSelect, empty_label=None)\n\n def clean_username(self):\n site_users_count = hmod.SiteUser.objects.filter(username=self.cleaned_data['username']).exclude(\n id=self.request.urlparams[0]).count()\n if site_users_count >= 1:\n raise forms.ValidationError('This username is already being used.')\n\n return self.cleaned_data['username']\n\n\n@view_function\n# @permission_required('homepage.add_siteuser', login_url='/homepage/login/')\ndef create(request):\n site_user = hmod.SiteUser()\n site_user.first_name = ''\n site_user.last_name = ''\n site_user.username = ''\n site_user.password = ''\n site_user.security_question = ''\n site_user.security_answer = ''\n site_user.email = ''\n site_user.save()\n\n try:\n authorization = Group.objects.get(name='Guest')\n except Group.DoesNotExist:\n return HttpResponseRedirect('/homepage/users/')\n\n site_user.groups.add(authorization)\n site_user.save()\n\n return HttpResponseRedirect('/homepage/users.edit/{}/new/'.format(site_user.id))\n\n\n@view_function\n@permission_required('homepage.delete_siteuser', login_url='/homepage/login/')\ndef delete(request):\n try:\n site_user = hmod.SiteUser.objects.get(id=request.urlparams[0])\n except hmod.SiteUser.DoesNotExist:\n return HttpResponseRedirect('/homepage/users/')\n site_user.delete()\n\n return HttpResponseRedirect('/homepage/users/')","sub_path":"catalog/views/shipping.py","file_name":"shipping.py","file_ext":"py","file_size_in_byte":5788,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"265665948","text":"# Copyright 2015 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\"\"\"Tests for modules/admin. (See also test_classes.AdminAspectTest.\"\"\"\n\n__author__ = 'John Orr (jorr@google.com)'\n\nfrom controllers import sites\nfrom models import courses\nfrom tests.functional import actions\n\nfrom google.appengine.api import namespace_manager\n\n\nclass AdminDashboardTabTests(actions.TestBase):\n\n ADMIN_EMAIL = 'adin@foo.com'\n COURSE_NAME = 'admin_tab_test_course'\n\n def setUp(self):\n super(AdminDashboardTabTests, self).setUp()\n\n self.base = '/' + self.COURSE_NAME\n context = actions.simple_add_course(\n self.COURSE_NAME, self.ADMIN_EMAIL, 'I18N Course')\n self.old_namespace = namespace_manager.get_namespace()\n namespace_manager.set_namespace('ns_%s' % self.COURSE_NAME)\n\n self.course = courses.Course(None, context)\n\n def tearDown(self):\n del sites.Registry.test_overrides[sites.GCB_COURSES_CONFIG.name]\n namespace_manager.set_namespace(self.old_namespace)\n super(AdminDashboardTabTests, self).tearDown()\n\n def get_nav_bar(self, dom, level=1):\n return dom.find(\n './/tr[@class=\"gcb-nav-bar-level-%s\"]' % level)\n\n def test_admin_tab_not_present_for_non_admin(self):\n actions.login(self.ADMIN_EMAIL, is_admin=False)\n dom = self.parse_html_string(self.get('/dashboard').body)\n self.assertIsNone(dom.find('.//a[@href=\"admin?action=admin\"]'))\n\n def test_admin_tab_is_present_for_admin(self):\n actions.login(self.ADMIN_EMAIL, is_admin=True)\n dom = self.parse_html_string(self.get('/dashboard').body)\n self.assertIsNotNone(dom.find('.//a[@href=\"admin?action=admin\"]'))\n\n def test_admin_actions_unavailable_for_non_admin(self):\n actions.login(self.ADMIN_EMAIL, is_admin=False)\n\n response = self.get('admin?action=admin')\n self.assertEqual(302, response.status_int)\n\n response = self.post(\n 'admin?action=config_reset&name=gcb_admin_user_emails', {})\n self.assertEqual(302, response.status_int)\n\n def test_admin_actions_available_for_admin(self):\n actions.login(self.ADMIN_EMAIL, is_admin=True)\n\n dom = self.parse_html_string(self.get('admin?action=admin').body)\n self.assertEqual(\n 'Site Admin',\n self.get_nav_bar(dom).find('.//a[@class=\"selected\"]').text)\n","sub_path":"coursebuilder/tests/functional/modules_admin.py","file_name":"modules_admin.py","file_ext":"py","file_size_in_byte":2916,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"602266080","text":"\"\"\"\nThis library interfaces with the pickled model.\n\"\"\"\n\nimport os\nimport pickle\nimport pandas as pd\nimport numpy as np\nimport operator\n\n\n###################\n##BUILD PREDICTOR##\n###################\n\nclass Predictor():\n def __init__(self, model=None, df=None):\n self.model = load_file('model')\n self.df = pd.read_csv('app/model/track_master_df.csv')\n\n def predict(self, user_input=None, size=10):\n \n \"\"\"\n nearest neighbors model and feature matrix passed, returns recommendations data\n\n \"\"\"\n\n distances, indices = self.model.kneighbors(user_input)\n\n recommend_indices = []\n for ii, dists in enumerate(distances):\n for jj, val in enumerate(dists):\n if (val > 0) & (val < 50):\n recommend_indices.append((indices[ii][jj], int(round(val))))\n\n recommend_indices = sorted(recommend_indices, key = operator.itemgetter(1))\n\n ind, val = zip(*recommend_indices) \n\n columns = ['artist', 'album', 'track']\n\n recommendations = self.df.iloc[list(ind[:size])][columns]\n\n rec_json = recommendations.to_json(orient = 'table', index = False, force_ascii = False)\n\n return rec_json\n\n######################\n###Helper Functions###\n######################\n\ndef get_abs_path(filename, **kwargs):\n if os.path.isfile(os.path.abspath(filename)):\n return os.path.abspath(filename)\n else:\n return os.path.join(\n os.getcwd(), 'app/model/'+filename,\n )\n \ndef load_file(file_key):\n with open(get_abs_path(params[file_key]), 'rb') as f:\n opened = pickle.load(f)\n return opened\n\n##################\n##SET PARAMETERS##\n##################\n\nparams = {\n 'model': 'knn_model.pkl'\n}","sub_path":"app/model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":1757,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"327567098","text":"#!/usr/bin/env python3\n\n\nimport numpy as np\nfrom scipy.special import erf\nimport sys\nsys.path.append('../lib')\nprint(sys.path)\nfrom libsim import simulate_hist\n\nname = 'double_well'\nnum_particles = 1000\nM = np.array([-3,3]).astype(np.float64)\nS = np.array([1,1]).astype(np.float64)\nD = 50\nbeta = 0.1\ndt = 0.001\ntotal_steps = 500000\nstep_block = 5000\nx0 = 0.0\nx_eq = 1000\neq_f = 1-x_eq/total_steps\n\nprint('Simulation:', name)\nprint('Eqilibration fraction: {:0.2f}%'.format((1-eq_f)*100))\n\nnum_bins = 150\nbins = np.linspace(-9, 9, num_bins).astype(np.float64)\nx0s = np.random.uniform(-9, 9, num_particles).astype(np.float64)\nhist, error = simulate_hist(x0s, bins,\n S=S, M=M, beta=beta, D=D,\n dt=dt, total_steps=total_steps,\n step_block=step_block, eq_time=x_eq,)\n\ndef integral(a, b, M, S):\n return 1/(2*len(M)) * np.sum([erf((b-m)/(np.sqrt(2)*s)) - erf((a-m)/(np.sqrt(2)*s))\n for m, s in zip(M, S)])\n\nexp_norm_factor = total_steps * eq_f\nexpected = exp_norm_factor * np.array([integral(bins[i], bins[i+1], M, S)\n for i in range(num_bins-1)])\n\nwith open('../data/{}.data'.format(name), 'w') as f:\n for b, h, err, exp in zip(bins, hist, error, expected):\n f.write('{} {} {} {}\\n'.format(b, h, err, exp))\n","sub_path":"cython/simulations/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":1344,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"222582968","text":"from flask import Flask, render_template, url_for, request, redirect\n# Blueprintをimportする\nfrom flask import Blueprint\n\n# 関数名(page1)でBlueprintオブジェクトを生成\npage1_app = Blueprint('page1', __name__)\n\n# ページ1\n@page1_app.route('/page1')\ndef page1():\n name = \"ページ1\"\n message = \"ページ1のメッセージ\"\n\n # 変数展開(messageとnameの値がHTMLに渡される)\n return render_template('page1.html',\n message=message, name=name)\n","sub_path":"python/flask/02_template/sample04/page1.py","file_name":"page1.py","file_ext":"py","file_size_in_byte":507,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"535307668","text":"# covid-19 economic tracker\n\nimport requests\nimport json\nimport os\nimport pandas as pd\nimport plotly\nimport plotly.graph_objects as go\nimport plotly.express as px\n\nfrom dotenv import load_dotenv\nload_dotenv()\n\napi_key = os.environ.get(\"FRED_API_KEY\")\n\n# User Input and API Pull\n\nwhile True: \n try:\n state = input(\"Please input a state abbreviation: \")\n FRED_series_id = (state) + \"UR\"\n request_url = f\"https://api.stlouisfed.org/fred/series/observations?series_id={FRED_series_id}&api_key={api_key}&file_type=json\"\n response = requests.get(request_url)\n\n parsed_response = json.loads(response.text)\n\n total_observations = parsed_response[\"count\"]\n break\n\n except KeyError:\n print(\"Hey, didn't find that state. Please try again with a state abbreviation.\")\n \n\n# Getting the state's most recent UR\n\nlast_value = float(parsed_response[\"observations\"][total_observations-1][\"value\"]) # assumes oldest data point comes first, as is FRED standard\n\n# Getting the state's all-time high/all-time low UR\n\nall_values = []\nindex = -1\n\nfor v in parsed_response[\"observations\"]:\n index = index + 1\n value = float(parsed_response[\"observations\"][index][\"value\"])\n all_values.append(value)\n\nall_time_high = max(all_values)\nall_time_low = min(all_values)\n\nmatching_dates_low = [v for v in parsed_response[\"observations\"] if float(v[\"value\"]) == all_time_low]\nmatching_date_low = matching_dates_low[0]\nall_time_low_date = matching_date_low[\"date\"]\n\nmatching_dates_high = [v for v in parsed_response[\"observations\"] if float(v[\"value\"]) == all_time_high]\nmatching_date_high = matching_dates_high[0]\nall_time_high_date = matching_date_high[\"date\"]\n\n# Getting the state's pre-COVID-19 unemployment rate\n\npre_covid_date = \"2020-02-01\"\n\nmatching_observations = [v for v in parsed_response[\"observations\"] if v[\"date\"] == pre_covid_date] \nmatching_observation = matching_observations[0]\npre_covid_level = float(matching_observation[\"value\"])\n\n# Getting the current national UR\n\nrequest_url_us = f\"https://api.stlouisfed.org/fred/series/observations?series_id=UNRATE&api_key={api_key}&file_type=json\"\nresponse_us = requests.get(request_url_us)\nparsed_response_us = json.loads(response_us.text)\n\ntotal_observations_us = parsed_response_us[\"count\"]\nlast_value_us = float(parsed_response_us[\"observations\"][total_observations_us-1][\"value\"])\n\n# Calculate and the difference between the state and national URs\n\nUR_difference = round(last_value - last_value_us, 1)\n\n# Information Output\n\nprint(\"----------------------------------------------------------------------\")\nprint(f\"The {str.upper(state)} Labor Market During the COVID-19 Pandemic\")\nprint(\"----------------------------------------------------------------------\")\nprint(f\"Current Unemployment Rate: {str(last_value)}%\")\nprint(f\"February 2020 Unemployment Rate {str(pre_covid_level)}%\")\nprint(f\"All-Time High Unemployment Rate ({all_time_high_date}): {str(all_time_high)}%\")\nprint(f\"All-Time Low Unemployment Rate ({all_time_low_date}): {str(all_time_low)}%\")\nprint(f\"Current Unemployment Rate for the United States: {str(last_value_us)}%\")\nprint(f\"Difference between {str.upper(state)} and the US: {str(UR_difference)}ppts\")\nprint(\"----------------------------------------------------------------------\")\nif last_value > last_value_us:\n print(\"THIS STATE'S LABOR MARKET IS AT HIGHER RISK OF NEEDING ECONOMIC POLICY ASSISTANCE\")\nelse:\n print(\"THIS STATE'S LABOR MARKET IS AT LOWER RISK OF NEEDING ECONOMIC POLICY ASSISTANCE\")\nprint(\"----------------------------------------------------------------------\")\n\n# Data Visualization 1 REFERENCE: https://plotly.com/python/time-series/\n\nall_val = []\nk = -1\nfor t in parsed_response[\"observations\"]:\n k += 1\n valuec = float(parsed_response[\"observations\"][k][\"value\"])\n all_val.append(valuec) \nvalues = all_val \n\n\nall_date = []\nm = -1\nfor r in parsed_response[\"observations\"]:\n m += 1\n val_date = parsed_response[\"observations\"][m][\"date\"]\n all_date.append(val_date)\ndates = all_date \n\n\nfig = px.line(x=dates, y=values, title=str.upper(state) + \" State Unemployment Rate\")\nfig.update_xaxes(\n rangeslider_visible=True,\n rangeselector=dict(\n buttons=list([\n dict(count=1, label=\"1m\", step=\"month\", stepmode=\"backward\"),\n dict(count=6, label=\"6m\", step=\"month\", stepmode=\"backward\"),\n dict(count=1, label=\"YTD\", step=\"year\", stepmode=\"todate\"),\n dict(count=1, label=\"1y\", step=\"year\", stepmode=\"backward\"),\n dict(step=\"all\")])))\nfig.update_yaxes(ticksuffix=\"%\") #reference : https://plotly.com/python/axes/\nfig.update_layout(xaxis_title='Date',yaxis_title='Value, %')\n\nfig.show()\n\n# Data Visualization 2 REFERENCE: https://plotly.com/python/line-charts/\n\nall_val2 = []\na = -1\nfor w in parsed_response[\"observations\"]:\n a += 1\n valuec2 = float(parsed_response[\"observations\"][a][\"value\"])\n all_val2.append(valuec2)\nvalues2 = all_val2\n\nall_val_us2 = []\nb = -1\nfor x in parsed_response_us[\"observations\"]:\n b += 1\n valuec_us2 = float(parsed_response_us[\"observations\"][b][\"value\"])\n all_val_us2.append(valuec_us2)\nvalues_us2 = all_val_us2\n\n\nall_date2 = []\nc = -1\nfor y in parsed_response[\"observations\"]:\n c += 1\n val_date2 = parsed_response[\"observations\"][c][\"date\"]\n all_date2.append(val_date2)\ndates2 = all_date2 \n\nall_us_date2 = []\nd = -1\nfor z in parsed_response_us[\"observations\"]:\n d += 1\n us_date2 = parsed_response_us[\"observations\"][d][\"date\"]\n all_us_date2.append(us_date2)\nus_dates2 = all_us_date2 \n\nfig2 = go.Figure()\n\n# Create and style traces\n\nfig2.add_trace(go.Scatter(x=all_date2, y=values2, name='state', line = dict(color='firebrick', width=4)))\nfig2.add_trace(go.Scatter(x=all_us_date2, y=values_us2, name='national', line = dict(color='royalblue', width=4, dash='dash')))\n\nfig2.update_xaxes(\n rangeslider_visible=True,\n rangeselector=dict(\n buttons=list([\n dict(count=1, label=\"1m\", step=\"month\", stepmode=\"backward\"),\n dict(count=6, label=\"6m\", step=\"month\", stepmode=\"backward\"),\n dict(count=1, label=\"YTD\", step=\"year\", stepmode=\"todate\"),\n dict(count=1, label=\"1y\", step=\"year\", stepmode=\"backward\"),\n dict(step=\"all\")])))\n\n# Edit the layout\n\nfig2.update_yaxes(ticksuffix=\"%\")\nfig2.update_layout(title=\"The National & \" + str.upper(state) + \" Unemployment Rates\", xaxis_title='Date', yaxis_title='Value, %')\nfig2.show()","sub_path":"covid-economic-tracker.py","file_name":"covid-economic-tracker.py","file_ext":"py","file_size_in_byte":6487,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"270827186","text":"from Bio import SeqIO, motifs, Seq\nfrom sklearn.feature_extraction.text import CountVectorizer\nimport numpy as np\nimport re\nimport pandas as pd\nfrom textwrap import wrap\nfrom pathlib import Path\n\nimport python_codon_tables as pct # Provides codon usage tables as dictionnaries, for Python 3+. see https://pypi.org/project/python_codon_tables/\nfrom dnachisel import * # a library for optimizing DNA sequences with respect to a set of constraints and optimization objectives. see https://github.com/Edinburgh-Genome-Foundry/DNAChisel\nfrom dnachisel import reports # to create a pdf report and anotated genebank file\n\nfrom os import getcwd\nfrom glob import glob\nimport gzip\nfrom os.path import join, sep\nimport pypugjs\nimport pypugjs.ext\nimport pypugjs.ext.jinja\nimport pypugjs.ext.html\nimport pypugjs.ext.mako\nimport pypugjs.ext.underscore\nimport zipfile\nfrom os import remove\nfrom sequenticon import sequenticon\n\n\ndef plot_sequenticons(seq, final_sequence, output_path, target):\n \"\"\"Helper function.\n This function plots the sequenticon of the sequence before and after the optimization process.\n The icons are being saved in the specified output path.\n The function has no output parameter.\n\n Parameters\n ------------\n seq: the original sequence (SeqRecord or string).\n final_sequence: the optimized sequence, after applying the 'translation_optimizer' function (string).\n output_path: the plot will be saved in this path.\n target: the path to the zip report file\n\n \"\"\"\n\n ### original sequence (before optimization): extract [0:45] for convenience\n sequenticon(seq, output_format=\"png\", size=24, output_path=join(output_path, 'sequenticon_before.png'))\n sequenticon(final_sequence, output_format=\"png\", size=24, output_path=join(output_path, 'sequenticon_after.png'))\n\n # Open a zip file at the given filepath. If it doesn't exist, create one.\n # If the directory does not exist, it fails with FileNotFoundError\n filepath = target\n\n with zipfile.ZipFile(filepath, 'a') as zipf:\n # Add a file located at the source_path to the destination within the zip file.\n source_path = join(output_path, 'sequenticon_before.png') # from\n destination = 'sequenticon_before.png' # to\n zipf.write(source_path, destination)\n remove(source_path) # remove the file from the output_path\n\n source_path = join(output_path, 'sequenticon_after.png') # from\n destination = 'sequenticon_after.png' # to\n zipf.write(source_path, destination)\n remove(source_path) # remove the file from the output_path\n\n\ndef modify_df_slippage(df_slippage):\n \"\"\"Helper function.\n The input is a dataframe containing all the identified slippage areas.\n The function converts each row with N = num_base_units to N-1 rows of the base units to be avoided.\n If the length of the base unit is 1, the output dataframe will only include half of the base units (with \"jumps\")\n This way, each basic unit will be treated as a constraint in the optimization function,\n since we want to avoid most of the repetitions.\n\n Example: In an input df_slippage, one of the rows indicates that the sequence \"TGTGTGTG\" includes a base unit\n of length L=3 with N=4 repetitions.\n start stop sequence length_base_unit num_base_units\n __________________________________________________________________\n 0 395 403 TGTGTGTG 2 4\n\n So the output dataframe of the current function will convert this row to N-1=three rows:\n start stop sequence\n __________________\n 0 395 397 TG\n 1 397 399 TG\n 2 399 401 TG\n such that each row contains a basic unit and its indices.\n \"\"\"\n df = pd.DataFrame(columns=('start', 'end', 'sequence'))\n\n for j in range(0, len(df_slippage)): # rows of df_slippage\n NBU = df_slippage.iloc[j].num_base_units\n L = df_slippage.iloc[j].length_base_unit\n if L == 1:\n step = 2\n else:\n step = 1\n for i in range(0, NBU - 1, step):\n df = df.append({'sequence': df_slippage.iloc[j].sequence[int(i * L):int(i * L + L)],\n 'start': int(df_slippage.iloc[j].start + i * L),\n 'end': int(df_slippage.iloc[j].start + i * L + L)},\n ignore_index=True)\n return df\n\n\ndef convert_df_to_constraints(df_fixed):\n \"\"\"Helper function.\n The input df has 3 columns: {start, end, and sequence}.\n The \"sequence\" is a pattern, and the \"start\" and \"end\" specify the location of this pattern.\n First, the function creates from this df a dictionary that maps each pattern constraint to its location\n (and convert the location to a tuple).\n The result is in following form: patterns = {\"TTT\":(292,292+7),\"CTGCTGCTG\":(673,673+9)}.\n Then, the function converts the patterns into a constraints, to be used an input to the DNAChisel problem.\n \"\"\"\n patterns = df_fixed.set_index('sequence')[['start', 'end']].T.apply(tuple)\n pattern_constraints = [AvoidPattern(patterns.keys()[k], location=patterns.values[k]) for k in\n range(0, len(patterns.keys()))]\n return pattern_constraints\n\n\ndef EFM_optimizer(seq, miniGC=0.3, maxiGC=0.7, window_size_GC=None, method='use_best_codon',\n organism_name=\"not_specified\",\n df_recombination=pd.DataFrame(), df_slippage=pd.DataFrame(), df_methylation=pd.DataFrame(),\n curr_output_path=None,\n filename='Optimization_report_staubility.zip', with_report=False, indexes=None):\n \"\"\"\n Description\n ----------\n This function optimizes the input sequence (string or SeqRecord) based on the identified suspected area for\n recombination, slippage and methylation, that are given as inputs (df_recombination, df_slippage, df_methylation).\n The identification of those areas is based on the principles that are described in the EFM calculator web tool and\n the article cited below.\n Those areas contain patterns that are likely to go under recombination, slippage or methylation, thus avoiding those\n patterns should increase the stability of the input gene.\n The translation of the gene is kept (no changes to the amino acid sequence).\n Citation: Benjamin R. Jack, Sean P. Leonard, Dennis M. Mishler, Brian A. Renda, Dacia Leon, Gabriel A. Suรกrez, and\n Jeffrey E Barrick (2015). Predicting the genetic stability of engineered DNA sequences with the EFM Calculator.\n ACS Synthetic Biology. Just Accepted Manuscript. DOI: 10.1021/acssynbio.5b00068\n\n Other aspects that this optimizer takes into consideration are:\n a. If the sequence is divisible by 3, the optimization parameter is \"Codon usage fraction\":\n the relative frequency of the codon in the host genome (specified by the organism_name input).\n Meaning, each codon is optimized based on its frequency in the host, in one of the methods below.\n The frequency data is from kazusa database (http://www.kazusa.or.jp/codon/readme_codon.html).\n Citation: Codon usage tabulated from the international DNA sequence databases, status for the year 2000.,\n Nakamura, Y., Gojobori, T. and Ikemura, T. (2000) Nucl. Acids Res. 28, 292.\n b. Codon Optimization method (for sequences that are divisible by 3):\n - For method = \"use_best_codon\", every codon will be replaced by the \"best\" (i.e. most frequent) synonymous codon\n in the target organism. This is equivalent to Codon Adaptation Index (CAI) optimization.\n - For method = \"match_codon_usage\", the final sequence's codon usage will match as much as possible the codon usage\n profile of the target species (this method is used throughout the literature,\n see for instance Hale and Thomson 1998).\n - For method = \"harmonize_rca\", Each codon will be replaced by a synonymous codon whose usage in the target organism\n matches the usage of the original codon in its host organism (as per Claassens 2017).\n Those methods are provided through the use of DNAchisel package for the optimization task.\n c. GC content (optional) - the requested range (minimum and maximum) of the percentage of nitrogenous bases in the\n sequence. the algorithm will split the sequence to windows of a specified size and on optimize each window.\n Basically, The lower the GC content, the more stable is the sequence, so one should take that into consideration.\n\n Parameters\n ----------\n seq: string of ACGT alphabet (copy-paste of DNA sequence), or SeqRecord (originated from a fasta file)\n miniGC and maxiGC: a numerical value from 0 to 1, specifies the range of GC content.\n window_size_GC: numerical. The window size (number of nucleotides) in which the requested GC content is to\n be maintained.\n method: optimization method.\n This is a string from the following: {\"use_best_codon\", \"match_codon_usage\", \"harmonize_rca\"}.\n organism_name: the name of the host of the gene. The codon optimization is done according to the host codon's frequency.\n This is a string from the following: {'b_subtilis', 'c_elegans', 'd_melanogaster', 'e_coli',\n 'g_gallus', 'h_sapiens', 'm_musculus', 'm_musculus_domesticus', 's_cerevisiae','not_specified'}.\n One can access this list (aside from 'not_specified') via \"python_codon_tables.available_codon_tables_names\".\n If the organism is 'not_specified' then the codon optimization objective will not be defined.\n df_recombination, df_slippage, df_methylation: dataframes, each containing a list of patterns and their locations that\n may influence the genetic stability of the gene and thus should be avoided.\n These dataframes will be saved as csv. files in a different function,\n as the output of the EFM calculator.\n indexes: a tuple that specifies the ORF indices. For the sub-sequence in those indices, the optimizer enforces\n translation (keeps amino-acid sequence), and optimizes the codon usage. The rest of the sequence is optimized by means\n of GC content and EFM constraints (if provided).\n curr_output_path: a path in which the output report will be saved (see \"returns\" below).\n filename: the file name (of the output report). with a \".zip\" suffix.\n with_report: a flag that indicates if the function will output a pdf report or just optimize the sequence.\n\n Returns\n ----------\n final_sequence: the optimized sequence\n final_record: a brief summary of the changes, includes sequence edits\n exported file named 'Translation_report.zip' if the input sequence is a string,\n or 'Translation_report_seqID.zip' if the input is FASTA format with an id.\n The file will be saved in \"curr_output_path\" folder.\n This file contains a report of the changes in anotated genbank format, in a pdf format and csv lists,\n all including a detailed description of the changes from the constraints and objectives.\"\"\"\n\n # set a default value for the window size as 1/50 of the sequence length.\n if window_size_GC is None:\n window_size_GC = round(len(seq) / 50)\n\n # Match the weight table for the organism (when the organism is specified):\n if organism_name == 'not_specified':\n obj = []\n else:\n codon_usage_table = pct.get_codons_table(organism_name).copy()\n # objective function:\n obj = [CodonOptimize(species=organism_name, location=indexes, codon_usage_table=codon_usage_table.copy(),\n method=method)]\n\n ## Define area for codon optimization while keeping amino-acid translation:\n if indexes == None:\n indexes = (0, len(seq))\n\n # DEFINE THE CONTSTRAINTS:\n cnst = [\n EnforceGCContent(mini=miniGC, maxi=maxiGC, window=window_size_GC),\n # enforce GC content between 30% to 50% (default)\n EnforceTranslation(location=indexes) # Enforce a specific amino-acid sequence translation.\n ]\n\n ### EFM constraints (if given):\n # recombination:\n if not df_recombination.empty:\n # change column names to the same name in each df and then send to a function that produces the patterns dictionary:\n df_rec = df_recombination[0:10].copy()[['start_1', 'end_1', 'sequence']].rename(\n columns={'start_1': 'start', 'end_1': 'end'})\n # convert df to a list of constraints to be used as input for the optimization problem:\n cnst_rec = convert_df_to_constraints(df_rec)\n # add to the constraints:\n cnst.extend(cnst_rec)\n\n # slippage:\n if not df_slippage.empty:\n # change column names to the same name in each df and then send to a function that produces the patterns dictionary:\n # convert the slippage dataframe to the basic repeated units for the constrains:\n df_slip = df_slippage[0:10].copy()\n df_slip = df_slip.loc[df_slip.log10_prob_slippage_ecoli > -9] # only 'severe' constraints.\n df_slip = modify_df_slippage(df_slip)\n # convert df to a list of constraints to be used as input for the optimization problem:\n cnst_slip = convert_df_to_constraints(df_slip)\n # add to the constraints:\n cnst.extend(cnst_slip)\n\n # methylation:\n if not df_methylation.empty:\n # change column names to the same name in each df and then send to a function that produces the patterns dictionary:\n df_meth = df_methylation[0:10].copy()[['start_index', 'end_index', 'actual_site']].rename(\n columns={'start_index': 'start', 'end_index': 'end', 'actual_site': 'sequence'})\n df_meth.loc[:, 'start'] = df_meth['start'].astype(int)\n df_meth.loc[:, 'end'] = df_meth['end'].astype(int)\n\n # convert df to a list of constraints to be used as input for the optimization problem:\n cnst_meth = convert_df_to_constraints(df_meth)\n\n # add to the constraints:\n cnst.extend(cnst_meth)\n\n # DEFINE THE OPTIMIZATION PROBLEM\n flag = 1\n while flag < 30: # while there are less than 10 hard constraints that were not satisfied\n problem = DnaOptimizationProblem(\n sequence=seq,\n constraints=cnst,\n objectives=obj\n )\n\n # SOLVE THE CONSTRAINTS, OPTIMIZE WITH RESPECT TO THE OBJECTIVE AND PRODUCE A REPORT\n try:\n problem.resolve_constraints()\n flag = 0 # all constraints passed.\n break\n except NoSolutionError as e:\n cnst.remove(e.constraint) # remove the problematic contstraint\n # print(\"Warning \"+ str(flag) + \": The constraint \" +str(e.constraint)+\" has been failed. trying to solve the problem without it.\")\n flag = flag + 1\n else:\n raise NoSolutionError(\n \"Unfortunately, more than 30 hard constraints were not satistied.\" + str(flag),\n problem=problem\n )\n\n ## OPTIMIZE OBJECTIVE FUNCTION:\n if with_report == False:\n problem.optimize() # without a report.\n else:\n target = join(curr_output_path, filename) # define the exported file name (and path)\n try:\n reports.optimization_reports.write_optimization_report(target=target, problem=problem,\n project_name=\"staubility_EFM_optimizer\",\n plot_figure=True)\n except FileNotFoundError:\n # The sequence is too long or perhaps there are too many changes to be displayed in an annotated figure,\n # so the report will be produced without it.\n # The annotated sequence after changes can be obtained from the exported genebank file.\n reports.optimization_reports.write_optimization_report(target=target, problem=problem,\n project_name=\"staubility_EFM_optimizer\",\n plot_figure=False)\n\n # GET THE FINAL SEQUENCE (AS STRING OR ANNOTATED BIOPYTHON RECORDS)\n final_sequence = problem.sequence # string\n if with_report == True:\n plot_sequenticons(seq, final_sequence, curr_output_path, target) ##plot the sequenticons\n\n # final_record = problem.to_record(with_sequence_edits=True)\n # if isinstance(seq, SeqRecord): # if the original sequence is a fasta file:\n # final_record.id = seq.id\n # final_record.name = seq.name\n # final_record.description = seq.description\n return final_sequence\n\n\n### calculate part of sequence based on start and end indexes\ndef genome_cutter(start, end, seq):\n return seq[start:end]\n\n\ndef find_recombination_sites(example_seq, num_sites):\n ### count all sequences of length 16\n vectorizer = CountVectorizer(analyzer='char_wb', ngram_range=(16, 16))\n counter = vectorizer.fit_transform([example_seq]).toarray()\n\n ### find those that appear more than once\n sites_recombination = list(np.where(counter > 1)[1])\n\n if len(sites_recombination) == 0:\n return pd.DataFrame(\n columns=['start_1', 'end_1', 'sequence', 'start_2', 'end_2', 'location_delta', 'site_length',\n 'log10_prob_recombination_ecoli', 'sequence_number'])\n\n ### get all sequences\n all_sites = vectorizer.get_feature_names()\n\n suspect_recombination = []\n\n for site in sites_recombination:\n ### get current site\n curr_seq = all_sites[site]\n ### get list of locations that are a match to the site\n list_regions = list(re.finditer(curr_seq.upper(), example_seq))\n ### extract coordinates from Match object\n list_regions = [x.span() for x in list_regions]\n\n suspect_recombination.extend(list_regions)\n\n ### this is now a list of tuples, containing coordinates of suspect recombination sites\n suspect_recombination = sorted(suspect_recombination)\n\n ### turn the tuples into a dataframe of start and end coordinates of the sites\n df_recombination = pd.DataFrame(suspect_recombination, columns=['start', 'end'])\n\n ### when we have matches larger than 16, they will turn into subsequent matches of 16. The following script is meant\n ### to join them together back to one larger region\n\n ### find the difference between current start and previous start, and between next end to current end. For ranges in\n ### the middle of a larger region, these will be 1 and 1. For our larger region, we only need the edges, so we get rid\n ### of the rest.\n df_recombination.loc[:, 'start_delta'] = df_recombination['start'] - df_recombination['start'].shift()\n df_recombination.loc[:, 'end_delta'] = df_recombination['end'].shift(-1) - df_recombination['end']\n df_recombination = df_recombination[(df_recombination.start_delta != 1.0) | (df_recombination.end_delta != 1.0)]\n\n ### starts of region will have end_delta==1, while ends of region will have start_delta = 1. We'll want to backpropagate\n ### the true end coordinate to the true start coordinate. So, we delete the end values in region starts, and backfill the end coordinates\n ### afterwards, we will keep only the region starts, which now have both coordinates correct\n df_recombination.loc[(df_recombination.end_delta == 1.0), 'end'] = None\n df_recombination.loc[:, 'end'] = df_recombination.loc[:, 'end'].fillna(method='bfill').astype(int) - 1\n df_recombination = df_recombination[df_recombination.start_delta != 1.0][['start', 'end']]\n\n ### attach the segment of the genetic sequence marked by these coordinates\n df_recombination.loc[:, 'sequence'] = df_recombination.apply(\n lambda x: genome_cutter(x['start'], x['end'], example_seq), axis=1)\n\n ### merge same sequences, so can easily see where the duplicates are\n df_recombination = df_recombination.merge(df_recombination, on='sequence', suffixes=('_1', '_2'))\n ### keep them as ordered matches - also gets rid of duplicates\n df_recombination = df_recombination[df_recombination.end_1 < df_recombination.start_2]\n\n ### find length of site and distance between sites\n df_recombination.loc[:, 'location_delta'] = df_recombination.start_2 - df_recombination.end_1\n df_recombination.loc[:, 'site_length'] = df_recombination.end_1 - df_recombination.start_1\n\n ### insert empirical formula for mutation probability from paper.\n A = 5.8\n B = 1465.6\n C = 0\n alpha = 29\n\n df_recombination.loc[:, 'log10_prob_recombination_ecoli_1'] = (A + df_recombination['location_delta'])\n df_recombination.loc[:, 'log10_prob_recombination_ecoli_2'] = (-1 * alpha / df_recombination['site_length'])\n df_recombination.loc[:, 'log10_prob_recombination_ecoli_3'] = (df_recombination['site_length']) / (\n 1 + B * df_recombination['site_length']\n + C * df_recombination['location_delta'])\n\n df_recombination.loc[:, 'log10_prob_recombination_ecoli'] = ((df_recombination[\n 'log10_prob_recombination_ecoli_1']) **\n (df_recombination[\n 'log10_prob_recombination_ecoli_2'])) * \\\n (df_recombination['log10_prob_recombination_ecoli_3'])\n\n df_recombination.loc[:, 'log10_prob_recombination_ecoli'] = df_recombination[\n 'log10_prob_recombination_ecoli'].apply(lambda x: np.log10(x))\n\n del df_recombination['log10_prob_recombination_ecoli_1']\n del df_recombination['log10_prob_recombination_ecoli_2']\n del df_recombination['log10_prob_recombination_ecoli_3']\n\n ### sort from mostly likely to mutate\n\n df_recombination = df_recombination.sort_values('log10_prob_recombination_ecoli', ascending=False)\n\n if num_sites < np.inf:\n df_recombination = df_recombination.head(num_sites)\n\n for col in df_recombination:\n if df_recombination[col].isnull().all():\n del df_recombination[col]\n\n return df_recombination\n\n\ndef find_slippage_sites_length_L(sequence, L):\n ### this function takes a sequence and a length L, and finds all locations where sequences of L length repeat themselves\n ### back to back. For L=1, this means all locations where a nucleotides repeats 4 times or more. For L>1, all sites where\n ### a sequence of length L repeats 3 times or more.\n\n slippage_sites = []\n\n ### this process needs to repeated for all frameshifts up to L, because the repeating sequence can start in any frameshift.\n for frameshift in range(L):\n ### frame shift the whole sequence for ease of calculation\n curr_seq = sequence[frameshift:]\n ### split sequence into equal parts of length L (shortening the last part as needed).\n curr_seq_split = wrap(curr_seq, L)\n\n ### until what small sequence d owe need to check\n end_of_range = len(curr_seq_split) - 2\n if L == 1:\n end_of_range -= 1\n for ii in range(end_of_range):\n\n ### in case of L>1, this expression is true when current sequence is equal to the next two. this is to mark\n ### the site that is prone to polymerase slippage\n is_followed2 = ((curr_seq_split[ii] == curr_seq_split[ii + 1]) and (\n curr_seq_split[ii] == curr_seq_split[ii + 2]) and L > 1)\n ### relevant expression for L=1\n is_followed1 = ((curr_seq_split[ii] == curr_seq_split[ii + 1]) and (\n curr_seq_split[ii] == curr_seq_split[ii + 2]) and\n (curr_seq_split[ii] == curr_seq_split[ii + 3]) and L == 1)\n\n ### save index of start and end of region, for L>1 and L = 1\n if is_followed2:\n curr_start = frameshift + ii * L\n curr_end = frameshift + L * (ii + 3)\n slippage_sites.append((curr_start, curr_end))\n\n if is_followed1:\n curr_start = ii\n curr_end = ii + 4\n slippage_sites.append((curr_start, curr_end))\n\n ### if no regions found, return empty dataframe\n if len(slippage_sites) == 0:\n return pd.DataFrame(columns=['start', 'end', 'sequence', 'length_base_unit'])\n\n df_slippage = pd.DataFrame(sorted(slippage_sites), columns=['start', 'end'])\n\n ### once again, we have larger suspect regions represented as a sequence of small suspect regions. As before, we find\n ### the delta to nearby start and end indices. We get rid of middle regions, and from the edges find once again the\n ### site's coordinates\n\n df_slippage.loc[:, 'start_delta'] = df_slippage['start'] - df_slippage['start'].shift()\n df_slippage.loc[:, 'end_delta'] = df_slippage['end'].shift(-1) - df_slippage['end']\n df_slippage = df_slippage[(df_slippage.start_delta != 1.0) | (df_slippage.end_delta != 1.0)]\n df_slippage.loc[(df_slippage.end_delta == 1.0), 'end'] = None\n df_slippage.loc[:, 'end'] = df_slippage.loc[:, 'end'].fillna(method='bfill').astype(int)\n df_slippage = df_slippage[df_slippage.start_delta != 1.0][['start', 'end']]\n\n ### round down end index to have complete number of units\n df_slippage.loc[:, 'end'] = (((df_slippage['end'] - df_slippage['start']) / L).astype(int) * L) + df_slippage[\n 'start']\n\n ### add sequence found, and length of base unit\n df_slippage.loc[:, 'sequence'] = df_slippage.apply(lambda x: genome_cutter(x['start'], x['end'], sequence), axis=1)\n df_slippage.loc[:, 'length_base_unit'] = L\n\n return df_slippage\n\n\ndef find_slippage_sites(seq, num_sites):\n ### create df of slippage sites for all base unit lengths up to 15\n slippage_sites_list = []\n for ii in range(1, 16):\n slippage_sites_list.append(find_slippage_sites_length_L(seq, ii))\n df_slippage = pd.concat(slippage_sites_list, ignore_index=True)[['start', 'end', 'length_base_unit', 'sequence']]\n\n ### find nmber of repeats per site, and calculate mutation rate from empirical formula\n df_slippage.loc[:, 'num_base_units'] = (\n df_slippage.sequence.apply(lambda x: len(x)) / df_slippage.length_base_unit).astype(int)\n\n df_slippage.loc[:, 'log10_prob_slippage_ecoli'] = -4.749 + 0.063 * df_slippage['num_base_units']\n df_slippage.loc[df_slippage.length_base_unit == 1, 'log10_prob_slippage_ecoli'] = -12.9 + 0.729 * df_slippage[\n 'num_base_units']\n\n ### return slippage sites, sorted by risk and limited in number of sites\n df_slippage = df_slippage.sort_values(['log10_prob_slippage_ecoli', 'length_base_unit'], ascending=[False, False])\n\n if num_sites < np.inf:\n df_slippage = df_slippage.head(num_sites)\n\n return df_slippage\n\n\ndef find_motif_sites(example_seq, effective_num_sites, relevant_motifs):\n site_scores_list = []\n motifs_list = []\n\n for ii, motif in enumerate(relevant_motifs):\n motif_scores = list(motif.pssm.calculate(example_seq))\n motif_rev_scores = list(motif.pssm.reverse_complement().calculate(example_seq))\n site_scores_list.append(motif_scores)\n site_scores_list.append(motif_rev_scores)\n motifs_list.append((ii, motif.name, motif.__len__()))\n\n df_motifs = pd.DataFrame.from_records(motifs_list, columns=['motif_number', 'matching_motif', 'motif_length'])\n\n df_sites = pd.DataFrame(site_scores_list).melt(var_name='start_index', value_name='PSSM_score')#,ignore_index=False, )\n df_sites = df_sites.reset_index().rename(columns={'index': 'PSSM_column'})\n\n df_sites = df_sites.sort_values('PSSM_score', ascending=False).drop_duplicates('start_index')\n\n df_sites.loc[:, 'motif_number'] = df_sites.PSSM_column.astype(int) // 2\n df_sites.loc[:, 'is_conjugate'] = df_sites.PSSM_column.apply(lambda x: x % 2 == 1)\n\n df_sites = df_sites[df_sites.PSSM_score > 0]\n\n if effective_num_sites < df_sites.shape[0]:\n df_sites = df_sites.head(effective_num_sites)\n\n df_sites = df_sites.merge(df_motifs, on='motif_number').sort_values('PSSM_score', ascending=False)\n df_sites.loc[:, 'end_index'] = df_sites.start_index + df_sites.motif_length - 1\n df_sites.loc[:, 'actual_site'] = str(example_seq).upper()\n\n df_sites.loc[:, 'actual_site'] = df_sites.apply(lambda x: x.actual_site[x.start_index:(x.end_index + 1)], axis=1)\n\n conjugate_dict = {'A': 'T', 'T': 'A', 'G': 'C', 'C': 'G'}\n df_sites.loc[:, 'actual_site_reverse_conjugate'] = df_sites.actual_site.apply(\n lambda x: ''.join([conjugate_dict[ii] for ii in x[::-1]]))\n\n df_sites = df_sites[\n ['start_index', 'end_index', 'matching_motif', 'PSSM_score', 'actual_site', 'actual_site_reverse_conjugate']]\n\n return df_sites\n\n\ndef suspect_site_extractor(example_seq, compute_motifs, num_sites, motifs_path, extension=''):\n sites_collector = {}\n df_recombination = find_recombination_sites(str(example_seq).upper(), num_sites)\n\n print('finished finding RMD sites')\n\n df_slippage = find_slippage_sites(str(example_seq).upper(), num_sites)\n\n print('finished finding SSR sites')\n\n sites_collector['df_recombination' + extension] = df_recombination\n sites_collector['df_slippage' + extension] = df_slippage\n\n ### do methylation only if requested\n if compute_motifs == True:\n with open(motifs_path, \"r\") as handle:\n relevant_motifs = motifs.parse(handle, \"minimal\")\n\n df_motifs = find_motif_sites(example_seq, num_sites, relevant_motifs)\n\n print('finished finding motif sites')\n\n sites_collector['df_motifs' + extension] = df_motifs\n\n return sites_collector\n\n\ndef data_handler(data, file, output_path, compute_motifs, num_sites, motifs_path, input_folder,\n optimize, miniGC, maxiGC, method, organism_name, indexes):\n print('starting the following file: ' + file)\n\n recombination_collector = []\n slippage_collector = []\n motifs_collector = []\n\n filename_indexes = file.split(input_folder + sep)[1].split('.fasta')[0]\n\n # define a new output folder inside \"output_path\", with name according to the 'file' name.\n new_path = file.split(input_folder)[1].split('.fasta')[0]\n curr_output_path = output_path + new_path\n Path(curr_output_path).mkdir(parents=True, exist_ok=True)\n\n for ii, record in enumerate(data): # the loop iterates on sequences inside a single FASTA file.\n\n print('____________________________')\n\n example_seq = str(record.seq).upper()\n\n seq_indexes = str(ii)\n\n print('starting sequence number ' + seq_indexes)\n\n ## FIRST OPTIMIZATION - optimize codon usage and GC content, without EFM constraints.\n if indexes == None:\n relevant_indexes = None\n else:\n # seq_indexes is the sequence identifier, not the start-stop.\n relevant_indexes = indexes[(filename_indexes, seq_indexes)] ##list\n relevant_indexes[0] = relevant_indexes[0] - 1 # convert to python\n relevant_indexes = tuple(relevant_indexes) # tuple (for the optimizer)\n\n if optimize:\n example_seq = EFM_optimizer(example_seq, window_size_GC=None, curr_output_path=output_path,\n filename='EFM_without_report_' + str(ii) + '.zip', miniGC=miniGC,\n maxiGC=maxiGC, method=method, organism_name=organism_name, with_report=False,\n indexes=relevant_indexes)\n\n print('finished first optimization')\n ####################\n\n\n ## extract suspected sites according to EFM criteria:\n curr_sites_collector = suspect_site_extractor(record.seq, compute_motifs, num_sites,\n motifs_path, extension='_' + str(ii))\n\n df_recombination = curr_sites_collector['df_recombination_' + str(ii)]\n if len(df_recombination) > 0:\n df_recombination.loc[:, 'sequence_number'] = str(ii)\n recombination_collector.append(df_recombination)\n\n df_slippage = curr_sites_collector['df_slippage_' + str(ii)]\n if len(df_slippage) > 0:\n df_slippage.loc[:, 'sequence_number'] = str(ii)\n slippage_collector.append(df_slippage)\n\n if compute_motifs == True:\n df_motifs = curr_sites_collector['df_motifs_' + str(ii)]\n if len(df_motifs) > 0:\n df_motifs.loc[:, 'sequence_number'] = str(ii)\n motifs_collector.append(df_motifs)\n else:\n df_motifs = pd.DataFrame()\n ## SECOND OPTIMIZATION - optimize codon usage and GC content, WITH EFM constraints.\n if optimize:\n _ = EFM_optimizer(example_seq, window_size_GC=None, df_recombination=df_recombination,\n df_slippage=df_slippage, df_methylation=df_motifs, miniGC=miniGC,\n maxiGC=maxiGC, method=method, organism_name=organism_name,\n curr_output_path=curr_output_path, filename='Optimization_report_' + str(ii) + '.zip',\n with_report=True, indexes=relevant_indexes)\n\n print('finished final optimization')\n\n ###########\n\n # combine the dfs of all the sequences together to a single csv. file.\n df_recombination = pd.concat(recombination_collector, ignore_index=True)\n if len(df_recombination) == 0:\n df_recombination = pd.DataFrame()\n\n df_slippage = pd.concat(slippage_collector, ignore_index=True)\n\n df_recombination.to_csv(join(curr_output_path, r'recombination_sites.csv'), index=False)\n df_slippage.to_csv(join(curr_output_path, r'slippage_sites.csv'), index=False)\n\n if compute_motifs == True:\n df_motifs = pd.concat(motifs_collector, ignore_index=True)\n df_motifs.to_csv(join(curr_output_path, r'motif_sites.csv'), index=False)\n\n print('finished saving results')\n\n return\n\n\ndef advanced_data_handler(data, file, input_folder):\n list_sequences = []\n\n new_path = file.split(input_folder + sep)[1].split('.fasta')[0]\n\n for ii, record in enumerate(data):\n seq_id = str(ii)\n len_seq = len(record)\n list_sequences.append([new_path, seq_id, len_seq])\n\n return list_sequences\n\n\ndef advenced_function(input_folder=getcwd()):\n \"\"\"\n The function gets as input a directory. It returns a list of lists,\n where each list is of the form (filename, seq_id, seq_length).\n This is used in order to be able to select subsequences to optimize.\n\n\n Args:\n\n input_folder(str): path from which to read fasta and fasta.gz files. Default value is current path.\n\n Returns:\n sequence_ids(list of lists). The convention:\n sequence_ids = [ [file name, seq_index, seq_length], [file name, seq_index, seq_length], ...]\n \"\"\"\n\n sequences_ids = []\n\n files_fas_1 = glob(join(input_folder, '*', '*.fasta'), recursive=True)\n files_fas = glob(join(input_folder, '*.fasta'), recursive=True)\n\n files_fasgz_1 = glob(join(input_folder, '*', '*.fasta.gz'), recursive=True)\n files_fasgz = glob(join(input_folder, '*.fasta.gz'), recursive=True)\n\n files_fas.extend(files_fas_1)\n files_fasgz.extend(files_fasgz_1)\n\n for file in files_fas:\n with open(file, \"rU\") as handle:\n data = list(SeqIO.parse(handle, \"fasta\"))\n\n curr_sequences = advanced_data_handler(data, file, input_folder)\n sequences_ids.extend(curr_sequences)\n\n for file in files_fasgz:\n with gzip.open(file, \"rt\") as handle:\n data = list(SeqIO.parse(handle, \"fasta\"))\n\n curr_sequences = advanced_data_handler(data, file, input_folder)\n sequences_ids.extend(curr_sequences)\n\n return sequences_ids\n\n\ndef test_input(miniGC, maxiGC, indexes):\n if miniGC < 0.0:\n return 'The minimum GC content must be over 0!'\n if maxiGC > 1.0:\n return 'The maximum GC content must be less than 1!'\n if miniGC >= maxiGC:\n return 'The minimum GC content must be less than the maximum!'\n\n if indexes != None:\n index_values = list(indexes.values())\n for index_pair in index_values:\n if (type(index_pair[0]) != int) or (type(index_pair[1]) != int):\n return 'Indexes must be integers!'\n if index_pair[0] < 1:\n return 'Start index must be greater than 0!'\n if index_pair[0] >= index_pair[1]:\n return 'Start index must be smaller than end index!'\n if (index_pair[1] - index_pair[0] + 1) % 3 != 0:\n return 'Indexes must describe sequence length divisible by 3!'\n\n return 'Success!'\n\n\ndef main(input_folder=getcwd(), output_path=join(getcwd(), 'output'), compute_motifs=False, num_sites=np.inf,\n motifs_path=join(getcwd(), r'topEnriched.313.meme.txt'), test=False, optimize=False, miniGC=0.3,\n maxiGC=0.5, method='use_best_codon', organism_name='not_specified', indexes=None):\n \"\"\"\n The function gets as input a directory. This directory and all subdirectories are copied into the output folder. Each fasta and fasta.gz\n file gets replaced by a directory of the same name, and populated by csv files, detailing recombination sites, slippage sites,\n and possibly methylation sites.\n\n\n Args:\n\n input_folder(str): path from which to read fasta and fasta.gz files. Default value is current path.\n\n output_path(str): directory into which to write csv's detailing suspect sites. Default value is 'output' within path of script.\n\n compute_motifs(bool): whether to calculate methylation sites. Relevant only for mammalian and insectoid cells.\n Default value is False.\n\n num_sites(Union[int, None]): How many values to keep per output file. If None, keep all. Default is None.\n\n motifs_path(str): path of methylation sites file, which is an input to the methylation probability calculation.\n Default value is 'topEnriched.313.meme.txt' within script path.\n\n test(bool): whether this is a test run and you only need a couple of files for testing purposes. Default value: False.\n\n optimize(bool): whether to use karin's optimization mechanism. Default is False.\n\n miniGC(float): minimal GC fraction in optimized sequence. Default value is 0.3\n\n maxiGC(float): maximal GC fraction in optimized sequence. Default value is 0.5\n\n method(string): which optimization method to use. Default is 'use_best_codon'. Possible values are: 'use_best_codon',\n 'match_codon_usage', 'harmonize_rca'.\n\n organism_name(string): the name of the host of the gene, used for the optimization algorithms. Default value is 'not_specified'.\n possible values are {'b_subtilis', 'c_elegans', 'd_melanogaster', 'e_coli',\n 'g_gallus', 'h_sapiens', 'm_musculus', 'm_musculus_domesticus', 's_cerevisiae','not_specified}.\n If the organism is 'not_specified' then the codon optimization objective will not be defined.\n\n indexes(dict): a dictionary of tuples (filename,seq_index), where each value is a list containing the\n sequence start and stop indexes of the ORF. It is defined within the advanced page in GUI, and defaults to None if\n the user does not specify an input.\n the convention for indexes is:\n `{\n (filename, seq_index(str)): [start(int),stop(int)] ,\n (filename, seq_index(str)): [start(int),stop(int)] , ...\n }`\n\n Returns:\n No variable. Saves output csv's in output_path.\n \"\"\"\n\n print('_____________________________________________________________________')\n\n if type(num_sites) == str:\n num_sites = np.inf\n\n message = test_input(miniGC, maxiGC, indexes)\n\n if message != 'Success!':\n print('illegal inputs')\n return message\n\n print('legal inputs')\n\n files_fas_1 = glob(join(input_folder, '*', '*.fasta'), recursive=True)\n files_fas = glob(join(input_folder, '*.fasta'), recursive=True)\n\n files_fasgz_1 = glob(join(input_folder, '*', '*.fasta.gz'), recursive=True)\n files_fasgz = glob(join(input_folder, '*.fasta.gz'), recursive=True)\n\n files_fas.extend(files_fas_1)\n files_fasgz.extend(files_fasgz_1)\n\n if test == True:\n files_fas = files_fas[0:2]\n files_fasgz = files_fasgz[0:2]\n\n for file in files_fas:\n with open(file, \"rU\") as handle:\n data = list(SeqIO.parse(handle, \"fasta\"))\n\n data_handler(data, file, output_path, compute_motifs, num_sites, motifs_path, input_folder, optimize=optimize,\n miniGC=miniGC, maxiGC=maxiGC, method=method, organism_name=organism_name, indexes=indexes)\n\n for file in files_fasgz:\n with gzip.open(file, \"rt\") as handle:\n data = list(SeqIO.parse(handle, \"fasta\"))\n\n print(data)\n print(len(data))\n data_handler(data, file, output_path, compute_motifs, num_sites, motifs_path, input_folder, optimize=optimize,\n miniGC=miniGC, maxiGC=maxiGC, method=method, organism_name=organism_name, indexes=indexes)\n\n return message\n\n#\n# path = r'C:\\Users\\imenu\\Desktop\\studies\\igem_data\\EFM detector\\example setup'\n#\n# from time import time\n#\n# aa = time()\n#\n# main(input_folder=r\"C:\\Users\\niv.a\\PycharmProjects\\IGEM\\EFM\\fasta_draft_200703\\HC\", output_path=r\"C:\\Users\\niv.a\\PycharmProjects\\IGEM\\EFM\\new_output\", compute_motifs=True,\n# motifs_path=join(r\"C:\\Users\\niv.a\\PycharmProjects\\IGEM\\In\", r'topEnriched.313.meme.txt'), optimize=True, num_sites=10)\n#\n# print(time() - aa)","sub_path":"EFM/ESO.py","file_name":"ESO.py","file_ext":"py","file_size_in_byte":41690,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"133430254","text":"# The string \"PAYPALISHIRING\" is written in a zigzag pattern on a given number of rows like this: (you may want to display this pattern in a fixed font for better legibility)\n#\n#\n# P A H N\n# A P L S I I G\n# Y I R\n#\n#\n# And then read line by line: \"PAHNAPLSIIGYIR\"\n#\n# Write the code that will take a string and make this conversion given a number of rows:\n#\n#\n# string convert(string s, int numRows);\n#\n# Example 1:\n#\n#\n# Input: s = \"PAYPALISHIRING\", numRows = 3\n# Output: \"PAHNAPLSIIGYIR\"\n#\n#\n# Example 2:\n#\n#\n# Input: s = \"PAYPALISHIRING\", numRows = 4\n# Output: \"PINALSIGYAHRPI\"\n# Explanation:\n#\n# P I N\n# A L S I G\n# Y A H R\n# P I\n#\n\n\nclass Solution:\n def convert(self, s, numRows):\n \"\"\"\n :type s: str\n :type numRows: int\n :rtype: str\n \"\"\"\n if (s == '' or len(s) <= numRows or numRows == 1): return s\n p = 2*(numRows-1)\n zigzag = [''] * numRows\n \n for i in range(len(s)):\n idx = i%p\n if(idx < numRows):\n zigzag[idx] += s[i]\n else:\n zigzag[p-idx] += s[i]\n \n return ''.join(zigzag)\n \n","sub_path":"006-zigzag-conversion/zigzag-conversion.py","file_name":"zigzag-conversion.py","file_ext":"py","file_size_in_byte":1174,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"439284495","text":"#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~#\n#\n# Light curve from paper. This is to make sure all the equations\n# as they appear in the paper are consistent with my program.\n#\n# History\n# This is a version of Sumit Sarbarchicary's 2017 model\n# to predict radio luminosities. This version has \n# minor changes to try to accommodate a situation where\n# all of the input parameters are numbers. Sumit's\n# original version requred rs and vs in the luminosity\n# function to be numpy arrays. \n#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~#\n\nimport numpy as np\nimport matplotlib.pyplot as plt\n\n#<><><><><><><><><> F U N C T I O N S <><><><><><><><><><><><>#\n\ndef radius_velocity(t, n0, mej, e51, sntype='cc'):\n \"\"\"\n Returns the shock radius and velocity for a given density, \n energy and ejecta mass.\n\n Parameters:\n ----------\n\n t : age of SNR (in years)\n n0 : density (atoms/cc)\n e51 : energy (in units of 10^51 ergs)\n mej : ejecta mass (in units of Msun)\n sntype : ['ia' or 'cc']\n \"\"\"\n\n#Characteristic variables - TM99 \n tch = 423*(e51**(-0.5))*(mej**(5.0/6.0))*(n0**(-1.0/3.0)) #years \n rch = 3.07*(mej**(1.0/3.0))*(n0**(-1.0/3.0)) #pcs \n vch = 7090*(e51**0.5)*(mej**(-0.5)) #km/s \n \n #Check whether to apply Ia or CC physics of TM99 \n\n if (sntype=='ia'):\n tstar_st = 0.481\n t_st0 = tstar_st*tch\n tstar = t/tch\n vstar = 0.805*tstar**(-(3.0/10.0)) if t0.1] = 0.1 #See Section A2\n epsCR=np.array(epsCR)\n epsCR=np.select([epsCR>0.1],[0.1],default=epsCR)\n\n epsub = (epsCR/2.)*((vs_cgs/c) + (1./MA)) #Eq A7\n Bu = np.sqrt(8.*3.14*epsub*rho0*vs_cgs**2) #Eq A3\n B = Bu*np.sqrt((1. + 2.*(eta**2))/3.) #Eq A8\n\n B=np.array(B)\n B=np.select([B<4*B0],[4*B0],default=B)\n # B[np.where(B<4.*B0)] = 4.*B0 #We assert that SNR magnetic field should atleast be a simple compression of the ISM field (B0)\n\n #~~~~~~ Luminosity ~~~~~~~~~~~~~~~~~~~#\n s = ef*(4./3.)*(rs_cgs) #Eq A9\n nu1 = 2.*c1*((s*c6*N_0)**(2./(p+4)))*(B**((p+2)/(p+4))) #Eq A11\n \n L1 = 4.0*(3.14**2)*(rs_cgs**2)*(B**(-0.5))*(c5/c6) #Breaking Eq A10 into 3 parts - L1, L2, L3 - for simplicity\n L2 = 1 - np.exp(-(nu/nu1)**(-(p+4)/2.))\n\n #This is a short step I am adding because the above equation for L2 runs into numerical errors\n #for nu>>nu1 (i.e. much later in the SNR age). This is particularly apparent for very low densities (e.g. n0<0.01)\n #To avoid this for now, I enforce the approximation: e^-x = 1 - x (for x<<1). May revisit this at some point\n\n L2=np.select([nu>20.*nu1],[((nu/nu1)**(-1.0*(p+4)/2.))],default=L2)\n # L2[nu>20.*nu1] = ((nu/nu1)**(-1.0*(p+4)/2.))[nu>20.*nu1]\n\n L3 = (nu/(2.*c1))**(5./2.)\n\n return L1*L2*L3 #Eq A10\n \n#<><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><>#\n\n\n","sub_path":"s17lc.py","file_name":"s17lc.py","file_ext":"py","file_size_in_byte":6357,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"533881277","text":"from django.shortcuts import render\nfrom opsweb.models import Element_Type, Element, Visible\nfrom bokeh.plotting import figure\nfrom bokeh.resources import INLINE\nfrom bokeh.embed import components\nimport numpy as np\nfrom datetime import datetime\n\n\ndef index(request):\n plot = figure(responsive=True,\n x_axis_type='datetime',\n plot_width=500,\n plot_height=250,\n tools='xwheel_zoom,xpan',\n ) \n \n start = datetime(2016,7,20)\n end = datetime(2016,7,30)\n visible_start = []\n visible_end = []\n \n for i in Visible.objects.filter(start__gte=start,\n start__lte=end\n ).order_by('start')[0:100000]:\n visible_start.append(i.start)\n visible_end.append(i.end)\n\n #source.data = dict(x=timestamp, y=value) \n #plot.line(source=source, x='x', y='y')\n #plot.x_range.callback = CustomJS.from_py_func(callback)\n \n x1 = np.array(visible_start, dtype='datetime64[s]')\n x2 = np.array(visible_end, dtype='datetime64[s]')\n plot.quad(top=0.5, bottom=0, left=x1, right=x2)\n \n script, div = components(plot, INLINE)\n context = {\n 'bokeh_script' : script,\n 'bokeh_div' : div,\n 'js_resources' : INLINE.render_js(),\n 'css_resources' : INLINE.render_css()\n }\n return render(request, 'visibility/index.html', context)\n","sub_path":"opsweb/visibility/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1460,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"417837270","text":"import unittest\n\nfrom parameterized import parameterized\n\nfrom DailyCodingProblem.dcp.array_of_products import ArrayOfProducts\n\n\nclass TestArrayOfProducts(unittest.TestCase):\n\n @parameterized.expand([\n ['1', [1, 2, 3, 4, 5], [120, 60, 40, 30, 24]],\n ['2', [3, 2, 1], [2, 3, 6]],\n ['3', [], []]\n ])\n def test_array_of_products(self, name, input, expected):\n self.assertEqual(\n ArrayOfProducts(input).build_products(),\n expected\n )","sub_path":"crackinginterview-source/algo/tests/DailyCodingProblem/test_array_of_products.py","file_name":"test_array_of_products.py","file_ext":"py","file_size_in_byte":495,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"641212631","text":"import glob\r\nimport random\r\nimport os\r\nimport cv2\r\nimport sys\r\nsys.path.append('../')\r\nimport numpy as np\r\nfrom PIL import Image, ImageEnhance\r\nfrom tqdm import tqdm\r\n\r\nimport torch\r\nimport torch.nn.functional as F\r\nfrom torch.utils.data import Dataset\r\nimport torchvision.transforms as transforms\r\n\r\nfrom config import cfg\r\nfrom IPython import embed\r\n\r\ndef resize(image, size):\r\n image = F.interpolate(image.unsqueeze(0), size=size, mode=\"nearest\").squeeze(0)\r\n return image\r\n\r\ndef random_crop(img,img_size):\r\n width,height=img.size\r\n # left = np.random.uniform(0, 5)\r\n #---上下随机crop,左右不crop\r\n top= np.random.uniform(0, 5)\r\n\r\n # convert to integer rect x1,y1,x2,y2\r\n rect =[0, int(top), int(img_size[0]), int(img_size[1]+top)]\r\n img=img.crop(rect) \r\n return img\r\n\r\n\r\ndef random_brightness(img):\r\n prob = np.random.uniform(0, 1)\r\n if np.random.rand()>0.5:\r\n delta = np.random.uniform(-cfg.brightness_delta,\r\n cfg.brightness_delta) + 1\r\n img = ImageEnhance.Brightness(img).enhance(delta)\r\n return img\r\n\r\n\r\nclass ImageFolder(Dataset):\r\n def __init__(self, folder_path, img_size=416):\r\n self.files = sorted(glob.glob(\"%s/*.*\" % folder_path))\r\n self.img_size = img_size\r\n\r\n def __getitem__(self, index):\r\n img_path = self.files[index % len(self.files)]\r\n # Extract image as PyTorch tensor\r\n img = transforms.ToTensor()(Image.open(img_path))\r\n # Pad to square resolution\r\n img, _ = pad_to_square(img, 0)\r\n # Resize\r\n img = resize(img, self.img_size)\r\n\r\n return img_path, img\r\n\r\n def __len__(self):\r\n return len(self.files)\r\n\r\n\r\nclass KeyDataset(Dataset):\r\n def __init__(self, list_path, img_size=(224, 165), phase='train'):\r\n with open(list_path, \"r\") as file:\r\n self.img_files = file.readlines()\r\n self.img_size = img_size\r\n self.transforms=True if phase=='train' else False\r\n\r\n def __getitem__(self, index):\r\n lines = self.img_files[index % len(self.img_files)].strip().split()\r\n img_path=lines[0]\r\n keys=lines[1:]\r\n targets = np.zeros(12)\r\n for index in keys:\r\n #---标签中标的是从0-11,已经是从1开始了 \r\n targets[int(index)]=1\r\n\r\n w, h = self.img_size\r\n # Extract image as PyTorch tensor\r\n img = Image.open(img_path).convert('RGB')\r\n file_seq=os.path.basename(os.path.split(img_path)[0]) \r\n \r\n img = img.resize((w, h + 5))\r\n img = random_crop(img, (w, h))\r\n\r\n if self.transforms:\r\n img = random_brightness(img)\r\n\r\n img = transforms.ToTensor()(img)\r\n return img, targets\r\n\r\n def __len__(self):\r\n return len(self.img_files)\r\n\r\n#---还可以加上pos信息\r\nclass KeyDataset_select(Dataset):\r\n def __init__(self, list_path, img_size=(224, 165),phase='train'):\r\n self.phase=phase\r\n\r\n self.img_files, self.img_dict, self.key_num = self.get_imgs(list_path)\r\n self.num_classes = len(self.key_num) #12\r\n print('the key num is {}'.format(self.key_num))\r\n # print(len(self.key_num))\r\n\r\n self.img_size = img_size\r\n self.transforms=True if phase=='train' else False\r\n\r\n def get_imgs(self,list_path):\r\n with open(list_path, \"r\") as file:\r\n img_files = file.readlines()\r\n img_dict = self.get_classes_nums(img_files)\r\n key_threshold = cfg.train_key_threshold if self.phase == 'train' else cfg.val_key_threshold\r\n #---筛选出数量大于500的键\r\n key_num = [key for key, value in img_dict.items() if value > key_threshold]\r\n # for key,value in img_dict.items():\r\n # if key in key_num:\r\n # print(key,value)\r\n\r\n new_lines=[]\r\n for line in tqdm(img_files):\r\n line=line.strip().split()\r\n keys=line[1:]\r\n for key in keys:\r\n #---如果当前帧有键属于数量较多的键\r\n if int(key) in key_num:\r\n new_lines.append(line)\r\n break\r\n\r\n return new_lines, img_dict, key_num\r\n\r\n def __getitem__(self, index):\r\n lines = self.img_files[index % len(self.img_files)]\r\n img_path = lines[0]\r\n keys = lines[1:]\r\n targets = np.zeros(self.num_classes)\r\n for index in keys:\r\n pressed=int(index)\r\n if pressed in self.key_num:\r\n #---对应到key_num中的位置\r\n idx = self.key_num.index(pressed)\r\n targets[idx]=1\r\n\r\n # Extract image as PyTorch tensor\r\n img=Image.open(img_path).convert('RGB')\r\n file_seq = os.path.basename(os.path.split(img_path)[0])\r\n w, h = self.img_size\r\n if self.transforms:\r\n img = img.resize((w, h + 5))\r\n #---random crop还是有用的,可以增加模型的鲁棒性0.0\r\n img = random_crop(img, (w, h))\r\n img = random_brightness(img)\r\n else: \r\n img = img.resize((w, h))\r\n img = transforms.ToTensor()(img)\r\n return img_path,img, targets\r\n\r\n def __len__(self):\r\n return len(self.img_files)\r\n\r\n def get_classes_nums(self,img_files):\r\n key_dic={}\r\n for i in range(12):\r\n key_dic[i] = 0\r\n\r\n key_num=0\r\n for line in img_files:\r\n line = line.strip().split()\r\n keys = line[1:]\r\n for key in keys:\r\n key_dic[int(key)]+=1\r\n \r\n key_lists=[]\r\n for i in range(12):\r\n if key_dic[i] == 0: continue\r\n key_lists.append((i,key_dic[i]))\r\n key_num+=key_dic[i]\r\n\r\n # key_lists=sorted(key_lists,key=lambda x:(x[1]))\r\n print('the training phase is {}'.format(self.phase))\r\n # for key in key_lists:\r\n # print(key)\r\n print('the total num is {}'.format(key_num))\r\n return key_dic\r\n\r\n#---得到当前帧前后的连续几帧---\r\ndef get_continue_path(path, begin_frame, end_frame, cur_frame, continuous_frame):\r\n sequence_imgs = []\r\n #---对于一开始的几帧----\r\n if cur_frame - begin_frame < continuous_frame:\r\n temp_frame = cur_frame\r\n #---将前面的几帧补上\r\n while True:\r\n if temp_frame - 1 >= begin_frame:\r\n temp_frame -= 1\r\n before_path = path.replace('{:0>4d}'.format(cur_frame),\r\n '{:0>4d}'.format(temp_frame))\r\n # img = cv2.imread(before_path)\r\n sequence_imgs.insert(0, before_path)\r\n else:\r\n tmp_path = path.replace('{:0>4d}'.format(cur_frame),\r\n '{:9>4d}'.format(9))\r\n sequence_imgs.insert(0, tmp_path)\r\n if len(sequence_imgs) == continuous_frame:\r\n break\r\n sequence_imgs.append(path)\r\n #---将后面的几帧补上\r\n temp_frame = cur_frame\r\n while True:\r\n temp_frame += 1\r\n after_path = path.replace('{:0>4d}'.format(cur_frame),\r\n '{:0>4d}'.format(temp_frame))\r\n # img = cv2.imread(after_path)\r\n sequence_imgs.append(after_path)\r\n if len(sequence_imgs) == cfg.Consecutive_frames:\r\n break\r\n #---对于最后面的几帧,其之后没有对应帧\r\n elif cur_frame + continuous_frame > end_frame:\r\n temp_frame = cur_frame\r\n #---将前面的几帧补上\r\n while True: \r\n temp_frame -= 1\r\n before_path = path.replace('{:0>4d}'.format(cur_frame),\r\n '{:0>4d}'.format(temp_frame))\r\n # img = cv2.imread(before_path)\r\n sequence_imgs.insert(0, before_path)\r\n if len(sequence_imgs) == continuous_frame:\r\n break\r\n\r\n sequence_imgs.append(path)\r\n #---将后面的几帧补上\r\n temp_frame = cur_frame\r\n while True:\r\n if temp_frame + 1 > end_frame:\r\n after_path = path.replace('{:0>4d}'.format(cur_frame),\r\n '{:9>4d}'.format(9))\r\n # img = cv2.imread(before_path)\r\n sequence_imgs.append(after_path)\r\n else:\r\n temp_frame += 1\r\n tmp_path = path.replace('{:0>4d}'.format(cur_frame),\r\n '{:0>4d}'.format(temp_frame))\r\n sequence_imgs.append(tmp_path)\r\n if len(sequence_imgs) == cfg.Consecutive_frames:\r\n break\r\n #---对于一般的帧,加上其前后几帧\r\n else:\r\n for i in range(1,continuous_frame+1):\r\n before_path = path.replace('{:0>4d}'.format(cur_frame),\r\n '{:0>4d}'.format(cur_frame - i))\r\n after_path = path.replace('{:0>4d}'.format(cur_frame),\r\n '{:0>4d}'.format(cur_frame + i))\r\n sequence_imgs.insert(0, before_path)\r\n sequence_imgs.append(after_path)\r\n sequence_imgs.insert(continuous_frame, path)\r\n return sequence_imgs\r\n\r\nclass WBDataset(Dataset):\r\n def __init__(self, list_path, img_size=(224, 165), k=5, mode='white', phase='train'):\r\n self.phase = phase\r\n self.mode = mode\r\n self.nums = cfg.octave_w if mode == 'white' else cfg.octave_b\r\n self.k = k #---输入连续k帧\r\n self.continuous_frame = int((self.k - 1) / 2)\r\n\r\n self.img_files, self.img_dict, self.key_num = self.get_imgs(list_path)\r\n self.num_classes = len(self.key_num) #12\r\n print('the key num is {}'.format(self.key_num))\r\n # print(len(self.key_num))\r\n\r\n self.img_size = img_size\r\n self.transforms=True if phase=='train' else False\r\n\r\n def get_imgs(self,list_path):\r\n with open(list_path, \"r\") as file:\r\n img_files = file.readlines()\r\n img_dict = self.get_classes_nums(img_files)\r\n \r\n #---筛选出数量大于500的键\r\n key_num = [key for key, value in img_dict.items() if key in self.nums]\r\n\r\n for key,value in img_dict.items():\r\n if key in key_num:\r\n print(key, value)\r\n img_lists = []\r\n\r\n for line in tqdm(img_files):\r\n line=line.strip().split()\r\n keys = line[1:]\r\n path = line[0]\r\n dir_name = os.path.dirname(path).split('/')[-1]\r\n file_seq = os.path.dirname(path).split('/')[-3]\r\n begin_frame = cfg.EVALUATE_MAP[file_seq]['begin_frame']\r\n end_frame = cfg.EVALUATE_MAP[file_seq]['end_frame']\r\n path = path.replace(dir_name, 'total_path')\r\n cur_img = cv2.imread(path)\r\n self.continuous_frame = int((self.k - 1) / 2)\r\n cur_frame = int(os.path.basename(path).split('.')[0].split('_')[0])\r\n #---对于刚开始的几帧,其之前没有对应帧\r\n sequence_imgs = get_continue_path(path, begin_frame,end_frame, cur_frame, self.continuous_frame)\r\n seq_imgs = (sequence_imgs, keys)\r\n for key in keys:\r\n #---如果当前帧的按键为白/黑键\r\n if int(key) in key_num:\r\n img_lists.append(seq_imgs)\r\n break\r\n\r\n return img_lists, img_dict, key_num\r\n\r\n def __getitem__(self, index):\r\n lines = self.img_files[index % len(self.img_files)]\r\n img_paths = lines[0]\r\n keys = lines[1]\r\n targets = np.zeros(self.num_classes)\r\n for index in keys:\r\n pressed = int(index)\r\n if pressed in self.key_num:\r\n #---对应到key_num中的位置\r\n idx = self.key_num.index(pressed)\r\n targets[idx]=1\r\n\r\n img_lists = []\r\n w, h = self.img_size\r\n for i, img_path in enumerate(img_paths):\r\n if '9999' in img_path:\r\n tmp_img = cv2.imread(img_paths[self.continuous_frame])\r\n #---这里的tmp_img的h/w不能和上面self.img_size的相同\r\n tmp_h, tmp_w, tmp_c = tmp_img.shape\r\n img = np.random.randint(128, 129, (tmp_h, tmp_w, tmp_c)).astype(np.uint8)\r\n img = Image.fromarray(img).convert('RGB')\r\n else:\r\n img = Image.open(img_path).convert('RGB')\r\n\r\n if self.phase == 'train':\r\n img = img.resize((w, h + 5))\r\n img = random_crop(img, (w, h))\r\n img = random_brightness(img)\r\n else:\r\n img = img.resize((w, h))\r\n img = transforms.ToTensor()(img)\r\n img_lists.append(img)\r\n return img_paths, img_lists, targets\r\n\r\n def __len__(self):\r\n return len(self.img_files)\r\n\r\n def get_classes_nums(self,img_files):\r\n key_dic={}\r\n for i in range(12):\r\n key_dic[i] = 0\r\n\r\n key_num=0\r\n for line in img_files:\r\n line = line.strip().split()\r\n keys = line[1:]\r\n for key in keys:\r\n key_dic[int(key)]+=1\r\n \r\n key_lists=[]\r\n for i in range(12):\r\n if key_dic[i] == 0: continue\r\n key_lists.append((i,key_dic[i]))\r\n key_num+=key_dic[i]\r\n\r\n # key_lists=sorted(key_lists,key=lambda x:(x[1]))\r\n print('the training phase is {}'.format(self.phase))\r\n # for key in key_lists:\r\n # print(key)\r\n print('the total num is {}'.format(key_num))\r\n return key_dic\r\n\r\nif __name__ == '__main__':\r\n val_set = WBDataset(cfg.octave_val_list, img_size=cfg.octave_final_size,\r\n k=5, mode='black', phase='val')\r\n train_set = WBDataset(cfg.octave_train_list, img_size=cfg.octave_final_size,\r\n k=5, mode='black', phase='train')\r\n img_paths, img_lists, targets = val_set.__getitem__(2)\r\n\r\n","sub_path":"octave_label/data/wb_dataset.py","file_name":"wb_dataset.py","file_ext":"py","file_size_in_byte":14106,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"7807834","text":"# -*- coding: utf-8 -*-\n\"\"\"\n @File : file_utils.py\n @Time : 2022/2/9 上午10:06\n @Author : yizuotian\n @Description :\n\"\"\"\nimport os\n\n\ndef get_sub_files(dir_path, recursive=True):\n \"\"\"\n\n :param dir_path:\n :param recursive:\n :return:\n \"\"\"\n file_path_list = []\n for file_name in os.listdir(dir_path):\n file_path = os.path.join(dir_path, file_name)\n if file_name.startswith(\".\"):\n continue\n if os.path.isdir(file_path):\n # print(file_path)\n if recursive:\n file_path_list.extend(get_sub_files(file_path, True))\n else:\n file_path_list.append(file_path)\n file_path_list.sort()\n return file_path_list\n\n\nif __name__ == '__main__':\n print(len(get_sub_files(\"./..\")))\n print(len(get_sub_files(\"./..\", False)))\n print(get_sub_files(\"./../big_data\", True))\n print(get_sub_files(\"../\", True))\n","sub_path":"python/file_utils.py","file_name":"file_utils.py","file_ext":"py","file_size_in_byte":915,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"447596359","text":"import asyncio\nimport hashlib\nimport os\n\nimport pytest\n\n\ndef pytest_collection_modifyitems(config, items):\n n_splits = int(os.environ.get('PYTEST_SPLITS', '1'))\n split_index = int(os.environ.get('PYTEST_SPLIT_INDEX', '-1'))\n if n_splits <= 1:\n return\n if not (0 <= split_index < n_splits):\n raise RuntimeError(f\"invalid split_index: index={split_index}, n_splits={n_splits}\\n env={os.environ}\")\n skip_this = pytest.mark.skip(reason=\"skipped in this round\")\n\n def digest(s):\n return int.from_bytes(hashlib.md5(str(s).encode('utf-8')).digest(), 'little')\n\n for item in items:\n if not digest(item.name) % n_splits == split_index:\n item.add_marker(skip_this)\n\n@pytest.fixture(scope=\"session\", autouse=True)\ndef ensure_event_loop_is_initialized_in_test_thread():\n try:\n asyncio.get_event_loop()\n except RuntimeError as err:\n assert err.args[0] == \"There is no current event loop in thread 'Dummy-1'.\"\n asyncio.set_event_loop(asyncio.new_event_loop())\n","sub_path":"hail/python/test/hail/conftest.py","file_name":"conftest.py","file_ext":"py","file_size_in_byte":1034,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"535629450","text":"from __future__ import absolute_import, division, print_function\r\nfrom setuptools import setup, find_packages\r\nimport os\r\nfrom os.path import isdir, isfile\r\nimport glob\r\n\r\n\r\n# Makes setup work inside of a virtualenv\r\nuse_system_lib = True\r\nif os.environ.get(\"BUILD_LIB\") == \"1\":\r\n use_system_lib = False\r\n\r\n\r\nbase_dir = os.path.dirname(__file__)\r\n\r\n__author__ = \"Wu Haifeng\"\r\n__email__ = \"wuhaifengdhu@163.com\"\r\n\r\n# Change this line to the module name you want to create\r\n__title__ = \"pyshifu\"\r\n__version__ = \"0.0.9\"\r\n__summary__ = \"An end-to-end machine learning and data mining framework on Hadoop.\"\r\n__uri__ = \"https://github.com/shifuml/pyshifu\"\r\n\r\n__requirements__ = [\r\n 'six>=1.11.0'\r\n]\r\n\r\n\r\ndef get_shifu_package_data():\r\n _data_files = add_recursively('pyshifu/java/')\r\n return _data_files\r\n\r\n\r\nwith open(os.path.join(base_dir, \"README.rst\")) as f:\r\n long_description = f.read()\r\n\r\n\r\ndef add_recursively(directory):\r\n _data_files = {}\r\n if not directory.endswith(\"/\"):\r\n directory += \"/\"\r\n items = glob.glob(directory + '*')\r\n _files = []\r\n _dirs = []\r\n for item in items:\r\n if isfile(item):\r\n _files.append(item)\r\n elif isdir(item):\r\n _dirs.append(item)\r\n _data_files[directory] = _files\r\n for _dir in _dirs:\r\n _data_files.update(add_recursively(_dir))\r\n return _data_files\r\n\r\n\r\nsetup(\r\n name=__title__,\r\n version=__version__,\r\n description=__summary__,\r\n long_description=long_description,\r\n packages=find_packages(exclude=['tests']),\r\n include_package_data=True,\r\n package_data=get_shifu_package_data(),\r\n author=__author__,\r\n author_email=__email__,\r\n url=__uri__,\r\n zip_safe=False,\r\n install_requires=__requirements__,\r\n data_files=[\r\n ('', ['ReleaseNotes.md']),\r\n ],\r\n # For data inside packages can use the automatic inclusion\r\n # include_package_data = True,\r\n # or the explicit inclusion, eg:\r\n # package_data = { 'package_name': ['data.file1', 'data.file2' , ...] }\r\n)","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":2039,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"74977359","text":"#!/usr/bin/env python\n# -*- coding:utf-8 -*-\n# @author:Spring\n\nimport tensorflow as tf\nfrom RecognizeMe.train_faces import cnnLayer, keep_prob_75, keep_prob_5, size, x\nimport cv2\nimport sys\nimport dlib\n\noutput = cnnLayer()\npredict = tf.argmax(output, 1)\n\nsaver = tf.train.Saver()\nsess = tf.Session()\nsaver.restore(sess, tf.train.latest_checkpoint('.'))\n\ndef is_my_face(image):\n res = sess.run(predict, feed_dict={x: [image/255.0], keep_prob_5:1.0, keep_prob_75: 1.0})\n if res[0] == 1:\n return True\n else:\n return False\n\n#使用dlib自带的frontal_face_detector作为我们的特征提取器\ndetector = dlib.get_frontal_face_detector()\n\ncam = cv2.VideoCapture(0)\n\nwhile True:\n _, img = cam.read()\n gray_image = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)\n dets = detector(gray_image, 1)\n if not len(dets):\n #print('Can`t get face.')\n cv2.imshow('img', img)\n key = cv2.waitKey(30) & 0xff\n if key == 27:\n sys.exit(0)\n\n for i, d in enumerate(dets):\n x1 = d.top() if d.top() > 0 else 0\n y1 = d.bottom() if d.bottom() > 0 else 0\n x2 = d.left() if d.left() > 0 else 0\n y2 = d.right() if d.right() > 0 else 0\n face = img[x1:y1,x2:y2]\n # 调整图片的尺寸\n face = cv2.resize(face, (size,size))\n print('Is this my face? %s' % is_my_face(face))\n\n cv2.rectangle(img, (x2,x1),(y2,y1), (255,0,0),3)\n cv2.imshow('image',img)\n key = cv2.waitKey(30) & 0xff\n if key == 27:\n sys.exit(0)\n\nsess.close()\n","sub_path":"RecognizeMe/is_my_face.py","file_name":"is_my_face.py","file_ext":"py","file_size_in_byte":1553,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"299820131","text":"\"\"\"\nVerb implementations for a :class:`pandas.DataFrame`\n\"\"\"\n\nimport re\nimport warnings\nfrom copy import copy\n\nimport numpy as np\nimport pandas as pd\n\nfrom .grouped_datatypes import GroupedDataFrame\nfrom .options import get_option, options\nfrom .utils import hasattrs, temporary_key, Q\n\n\ndef define(verb):\n if get_option('modify_input_data'):\n data = verb.data\n else:\n data = verb.data.copy()\n\n new_data = _evaluate_expressions(verb)\n for col in new_data:\n data[col] = new_data[col]\n return data\n\n\ndef create(verb):\n data = _get_base_dataframe(verb.data)\n new_data = _evaluate_expressions(verb)\n for col in new_data:\n data[col] = new_data[col]\n return data\n\n\ndef sample_n(verb):\n return verb.data.sample(**verb.kwargs)\n\n\ndef sample_frac(verb):\n return verb.data.sample(**verb.kwargs)\n\n\ndef select(verb):\n kw = verb.kwargs\n columns = verb.data.columns\n groups = _get_groups(verb)\n c0 = np.array([False]*len(columns))\n c1 = c2 = c3 = c4 = c5 = c6 = c0\n\n if verb.args:\n c1 = [x in set(verb.args) for x in columns]\n\n if kw['startswith']:\n c2 = [isinstance(x, str) and x.startswith(kw['startswith'])\n for x in columns]\n\n if kw['endswith']:\n c3 = [isinstance(x, str) and x.endswith(kw['endswith'])\n for x in columns]\n\n if kw['contains']:\n c4 = [isinstance(x, str) and kw['contains'] in x\n for x in columns]\n\n if kw['matches']:\n if hasattr(kw['matches'], 'match'):\n pattern = kw['matches']\n else:\n pattern = re.compile(kw['matches'])\n c5 = [isinstance(x, str) and bool(pattern.match(x))\n for x in columns]\n\n if groups:\n c6 = [x in set(groups) for x in columns]\n\n cond = np.logical_or.reduce((c1, c2, c3, c4, c5, c6))\n\n if kw['drop']:\n cond = ~cond\n\n data = verb.data.loc[:, cond]\n if data.is_copy:\n data.is_copy = None\n\n return data\n\n\ndef rename(verb):\n inplace = get_option('modify_input_data')\n data = verb.data.rename(columns=verb.lookup, inplace=inplace)\n return verb.data if inplace else data\n\n\ndef distinct(verb):\n if hasattrs(verb, ('new_columns', 'expressions')):\n data = define(verb)\n else:\n data = verb.data\n return data.drop_duplicates(subset=verb.columns,\n keep=verb.keep)\n\n\ndef arrange(verb):\n name_gen = ('col_{}'.format(x) for x in range(100))\n df = pd.DataFrame(index=verb.data.index)\n env = verb.env.with_outer_namespace({'Q': Q})\n for col, expr in zip(name_gen, verb.expressions):\n try:\n df[col] = verb.data[expr]\n except KeyError:\n df[col] = env.eval(expr, inner_namespace=verb.data)\n\n if len(df.columns):\n sorted_index = df.sort_values(by=list(df.columns)).index\n data = verb.data.loc[sorted_index, :]\n if data.is_copy:\n data.is_copy = None\n else:\n data = verb.data\n\n return data\n\n\ndef group_by(verb):\n copy = not get_option('modify_input_data')\n verb.data = GroupedDataFrame(verb.data, verb.groups, copy=copy)\n return define(verb)\n\n\ndef ungroup(verb):\n return pd.DataFrame(verb.data)\n\n\ndef group_indices(verb):\n data = verb.data\n groups = verb.groups\n if isinstance(data, GroupedDataFrame):\n if groups:\n msg = \"GroupedDataFrame ignored extra groups {}\"\n warnings.warn(msg.format(groups))\n else:\n groups = data.plydata_groups\n else:\n data = create(verb)\n\n indices_dict = data.groupby(groups).indices\n indices = -np.ones(len(data), dtype=int)\n for i, (_, idx) in enumerate(sorted(indices_dict.items())):\n indices[idx] = i\n\n return indices\n\n\ndef summarize(verb):\n cols = verb.new_columns\n exprs = verb.expressions\n data = verb.data\n\n env = verb.env.with_outer_namespace(_aggregate_functions)\n env = env.with_outer_namespace({'Q': Q})\n\n try:\n grouper = data.groupby(data.plydata_groups)\n except AttributeError:\n data = _eval_summarize_expressions(exprs, cols, env, data)\n else:\n dfs = [_eval_summarize_expressions(exprs, cols, env, gdf)\n for _, gdf in grouper]\n data = pd.concat(dfs, axis=0, ignore_index=True)\n\n return data\n\n\ndef query(verb):\n data = verb.data.query(\n verb.expression,\n global_dict=verb.env.namespace,\n **verb.kwargs)\n if data.is_copy:\n data.is_copy = None\n return data\n\n\ndef do(verb):\n if verb.single_function:\n return _do_single_function(verb)\n else:\n return _do_functions(verb)\n\n\ndef head(verb):\n if isinstance(verb.data, GroupedDataFrame):\n grouper = verb.data.groupby(verb.data.plydata_groups)\n dfs = [gdf.head(verb.n) for _, gdf in grouper]\n data = pd.concat(dfs, axis=0, ignore_index=True)\n data.plydata_groups = list(verb.data.plydata_groups)\n else:\n data = verb.data.head(verb.n)\n\n return data\n\n\ndef tail(verb):\n if isinstance(verb.data, GroupedDataFrame):\n grouper = verb.data.groupby(verb.data.plydata_groups)\n dfs = [gdf.tail(verb.n) for _, gdf in grouper]\n data = pd.concat(dfs, axis=0, ignore_index=True)\n data.plydata_groups = list(verb.data.plydata_groups)\n else:\n data = verb.data.tail(verb.n)\n\n return data\n\n\ndef tally(verb):\n verb = copy(verb)\n # Prepare for summarize\n verb.new_columns = ['n']\n if verb.weights:\n if isinstance(verb.weights, str):\n verb.weights = 'sum({})'.format(verb.weights)\n verb.expressions = [verb.weights]\n else:\n verb.expressions = ['{n}']\n\n data = summarize(verb)\n if verb.sort:\n data = data.sort_values(by='n')\n data.reset_index(drop=True, inplace=True)\n\n return data\n\n\ndef count(verb):\n if (not isinstance(verb.data, GroupedDataFrame) and\n verb.groups):\n verb.data = GroupedDataFrame(verb.data, verb.groups, copy=True)\n return tally(verb)\n\n\ndef modify_where(verb):\n if get_option('modify_input_data'):\n data = verb.data\n else:\n data = verb.data.copy()\n idx = data.query(verb.where, global_dict=verb.env.namespace).index\n qdf = data.loc[idx, :]\n\n env = verb.env.with_outer_namespace({'Q': Q})\n for col, expr in zip(verb.columns, verb.expressions):\n # Do not create new columns, define does that\n if col not in data:\n raise KeyError(\"Column '{}' not in dataframe\".format(col))\n if isinstance(expr, str):\n data.loc[idx, col] = env.eval(expr, inner_namespace=qdf)\n else:\n data.loc[idx, col] = expr\n\n return data\n\n\ndef define_where(verb):\n verb = copy(verb)\n if not get_option('modify_input_data'):\n verb.data = verb.data.copy()\n\n alt_expressions = [x[0] for x in verb.expressions]\n default_expressions = [x[1] for x in verb.expressions]\n\n with options(modify_input_data=True):\n verb.expressions = default_expressions\n verb.data = define(verb)\n\n verb.columns = verb.new_columns\n verb.expressions = alt_expressions\n data = modify_where(verb)\n\n return data\n\n\ndef inner_join(verb):\n verb.kwargs['how'] = 'inner'\n return _join(verb)\n\n\ndef outer_join(verb):\n verb.kwargs['how'] = 'outer'\n return _join(verb)\n\n\ndef left_join(verb):\n verb.kwargs['how'] = 'left'\n return _join(verb)\n\n\ndef right_join(verb):\n verb.kwargs['how'] = 'right'\n return _join(verb)\n\n\ndef anti_join(verb):\n verb.kwargs['how'] = 'left'\n verb.kwargs['suffixes'] = ('', '_y')\n verb.kwargs['indicator'] = '_plydata_merge'\n df = _join(verb)\n data = df.query('_plydata_merge==\"left_only\"')[verb.x.columns]\n data.is_copy = None\n return data\n\n\ndef semi_join(verb):\n verb.kwargs['how'] = 'left'\n verb.kwargs['suffixes'] = ('', '_y')\n verb.kwargs['indicator'] = '_plydata_merge'\n df = _join(verb)\n data = df.query('_plydata_merge==\"both\"')[verb.x.columns]\n data.is_copy = None\n data.drop_duplicates(inplace=True)\n return data\n\n\n# Helper functions\n\ndef _get_groups(verb):\n \"\"\"\n Return groups\n \"\"\"\n try:\n return verb.data.plydata_groups\n except AttributeError:\n return []\n\n\ndef _get_base_dataframe(df):\n \"\"\"\n Remove all columns other than those grouped on\n \"\"\"\n if isinstance(df, GroupedDataFrame):\n base_df = GroupedDataFrame(\n df.loc[:, df.plydata_groups], df.plydata_groups,\n copy=True)\n else:\n base_df = pd.DataFrame(index=df.index)\n return base_df\n\n\ndef _evaluate_expressions(verb):\n \"\"\"\n Evaluate Expressions and return the columns in a new dataframe\n \"\"\"\n data = pd.DataFrame(index=verb.data.index)\n env = verb.env.with_outer_namespace({'Q': Q})\n for col, expr in zip(verb.new_columns, verb.expressions):\n if isinstance(expr, str):\n data[col] = env.eval(expr, inner_namespace=verb.data)\n else:\n data[col] = expr\n\n return data\n\n\ndef _eval_summarize_expressions(expressions, columns, env, gdf):\n \"\"\"\n Evaluate expressions to create a dataframe.\n\n Parameters\n ----------\n expressions : list of str\n columns : list of str\n env : environment\n gdf : dataframe\n Dataframe where all items are assumed to belong to the\n same group.\n\n This excutes an *apply* part of the *split-apply-combine*\n data manipulation strategy. Callers of the function do\n the *split* and the *combine*.\n\n A peak into the function\n\n >>> import pandas as pd\n >>> from .utils import get_empty_env\n\n A Dataframe with many groups\n\n >>> df = GroupedDataFrame(\n ... {'x': list('aabbcc'),\n ... 'y': [0, 1, 2, 3, 4, 5]\n ... }, groups=['x'])\n\n Do a groupby and obtain a dataframe with a single group,\n (i.e. the *split*)\n\n >>> grouper = df.groupby(df.plydata_groups)\n >>> group = 'b' # The group we want to evalualte\n >>> gdf = grouper.get_group(group)\n >>> gdf\n groups: ['x']\n x y\n 2 b 2\n 3 b 3\n\n Create the other parameters\n\n >>> env = get_empty_env()\n >>> columns = ['ysq', 'ycubed']\n >>> expressions = ['y**2', 'y**3']\n\n Finally, the *apply*\n\n >>> _eval_summarize_expressions(expressions, columns, env, gdf)\n x ysq ycubed\n 0 b 4 8\n 1 b 9 27\n\n The caller does the *combine*, for one or more of these\n results.\n \"\"\"\n # Extra aggregate function that the user references with\n # the name `{n}`. It returns the length of the dataframe.\n def _plydata_n():\n return len(gdf)\n\n for col, expr in zip(columns, expressions):\n if isinstance(expr, str):\n expr = expr.format(n='_plydata_n()')\n with temporary_key(_aggregate_functions,\n '_plydata_n', _plydata_n):\n value = env.eval(expr, inner_namespace=gdf)\n else:\n value = expr\n\n # Non-consecutive 0-n pd.series indices create gaps with\n # nans when inserted into a dataframe\n value = np.asarray(value)\n\n try:\n data[col] = value\n except NameError:\n try:\n n = len(value)\n except TypeError:\n n = 1\n data = pd.DataFrame({col: value}, index=range(n))\n\n # Add the grouped-on columns\n if isinstance(gdf, GroupedDataFrame):\n for i, col in enumerate(gdf.plydata_groups):\n data.insert(i, col, gdf[col].iloc[0])\n\n return data\n\n\ndef _eval_do_single_function(function, gdf):\n \"\"\"\n Evaluate an expression to create a dataframe.\n\n Similar to :func:`_eval_summarize_expressions`, but for the\n ``do`` operation.\n \"\"\"\n gdf.is_copy = None\n data = function(gdf)\n\n # Add the grouped-on columns\n if isinstance(gdf, GroupedDataFrame):\n for i, col in enumerate(gdf.plydata_groups):\n if col not in data:\n data.insert(i, col, gdf[col].iloc[0])\n\n return data\n\n\ndef _eval_do_functions(functions, columns, gdf):\n \"\"\"\n Evaluate functions to create a dataframe.\n\n Similar to :func:`_eval_summarize_expressions`, but for the\n ``do`` operation.\n \"\"\"\n gdf.is_copy = None\n for col, func in zip(columns, functions):\n value = np.asarray(func(gdf))\n\n try:\n data[col] = value\n except NameError:\n try:\n n = len(value)\n except TypeError:\n n = 1\n data = pd.DataFrame({col: value}, index=range(n))\n\n # Add the grouped-on columns\n if isinstance(gdf, GroupedDataFrame):\n for i, col in enumerate(gdf.plydata_groups):\n if col not in data:\n data.insert(i, col, gdf[col].iloc[0])\n\n return data\n\n\ndef _do_single_function(verb):\n func = verb.single_function\n data = verb.data\n\n try:\n groups = data.plydata_groups\n except AttributeError:\n data = _eval_do_single_function(func, data)\n else:\n dfs = [_eval_do_single_function(func, gdf)\n for _, gdf in data.groupby(groups)]\n data = pd.concat(dfs, axis=0, ignore_index=True)\n data.plydata_groups = list(groups)\n\n return data\n\n\ndef _do_functions(verb):\n cols = verb.columns\n funcs = verb.functions\n data = verb.data\n\n try:\n groups = data.plydata_groups\n except AttributeError:\n data = _eval_do_functions(funcs, cols, data)\n else:\n dfs = [_eval_do_functions(funcs, cols, gdf)\n for _, gdf in data.groupby(groups)]\n data = pd.concat(dfs, axis=0, ignore_index=True)\n data.plydata_groups = list(groups)\n\n return data\n\n\ndef _join(verb):\n \"\"\"\n Join helper\n \"\"\"\n data = pd.merge(verb.x, verb.y, **verb.kwargs)\n\n # Preserve x groups\n if isinstance(verb.x, GroupedDataFrame):\n data.plydata_groups = list(verb.x.plydata_groups)\n return data\n\n\n# Aggregations functions\n\ndef _nth(arr, n):\n \"\"\"\n Return the nth value of array\n\n If it is missing return NaN\n \"\"\"\n try:\n return arr.iloc[n]\n except KeyError:\n raise np.nan\n\n\ndef _n_distinct(arr):\n \"\"\"\n Number of unique values in array\n \"\"\"\n return len(pd.unique(arr))\n\n\n_aggregate_functions = {\n 'min': np.min,\n 'max': np.max,\n 'sum': np.sum,\n 'cumsum': np.cumsum,\n 'mean': np.mean,\n 'median': np.median,\n 'std': np.std,\n 'first': lambda x: _nth(x, 0),\n 'last': lambda x: _nth(x, -1),\n 'nth': _nth,\n 'n_distinct': _n_distinct,\n 'n_unique': _n_distinct,\n}\n","sub_path":"plydata/dataframe.py","file_name":"dataframe.py","file_ext":"py","file_size_in_byte":14591,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"131998928","text":"from RPG.consts.game_states import CARGO_HOLD\nfrom RPG.bot_classes.locations.base_location import BaseLocation\n\n\nclass CargoHold(BaseLocation):\n def __init__(self, game, spaceship):\n super().__init__(game, CARGO_HOLD, 'Bodega', 'Entras en un amplio compartimento de carga. Hasta aquí '\n 'está vacío. Más tarde, puedes transportar mercancías aquí.')\n self.spaceship = spaceship\n self.reply_keyboard.row('🚀Puente de mando', '🛏Cabina personal')\n self.reply_keyboard.row('👣Salir de la nave', '📟Menú principal')\n\n def handle(self, message):\n if message.text == '🚀Puente de mando':\n self.spaceship.captain_bridge.start(message)\n elif message.text == '📟Menú principal':\n self.game.main_menu.start(message)\n elif message.text == '👣Salir de la nave':\n if not self.game.current_planet:\n self.game.bot.send_message(message.chat.id, '¿Un paseo espacial?0_o No es la mejor idea.',\n reply_markup=self.reply_keyboard)\n else:\n self.game.current_planet.start(message)\n elif message.text == '🛏Cabina personal':\n self.spaceship.cabin.start(message)\n else:\n self.show_input_error(message)\n","sub_path":"RPG/bot_classes/locations/spaceship/cargo_hold.py","file_name":"cargo_hold.py","file_ext":"py","file_size_in_byte":1377,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"36150007","text":"import numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nfrom pylab import *\n\n\ndef mean_stddev(value, series, param):\n mean = series.mean()\n std_dev = series.std()\n return abs(value - mean) > param * std_dev\n\n\ndef median_deviation(value, series, param):\n median = series.median()\n demedianed = np.abs(value - median)\n\n if demedianed == 0 or value == 0:\n return False\n\n test_statistic = value / demedianed\n if test_statistic < param:\n return True\n else:\n return False\n\n\ndef trend_statistic(value,series):\n smoothed_val = []\n prediction = []\n N = len(series)\n alpha = 0.3 # param to define how quickly you forget the past values\n beta = 0.5 # param to define how quickly you forget past slope\n std_window = 3 #define std window range\n\n smoothed_val.append(value[0])\n smoothed_slope = np.zeros((N, ))\n prediction.append(value[0])\n\n for i in range(1, N):\n #calculate new smoothed value from exponetial weighted average of current value and old value\n smoothed_val.append(alpha*value[i] + (1-alpha) * (smoothed_val[i-1] + smoothed_slope[i-1]))\n\n smoothed_slope[i] = (beta * (smoothed_val[i] - smoothed_val[i-1]) + (1-beta)*smoothed_slope[i-1])\n\n #Calculate prediction of value at current time, using only information from previous time.\n prediction.append(smoothed_val[i - 1] + smoothed_slope[i-1])\n\n #MEASURE PREDICTION ERROR\n\n #Calculate 'normal' limits of deviation based on variance earlier in the process\n #Use expotentially weighted standard deviation (so past data has less influence).\n #The shift by 1 is to exclude the difference of the current predicted and actual values from\n #the assessment of past prediction accurancy.\n\n smoothed_std_ts = pd.Series(\n pd.ewma(np.sqrt((value-prediction)**2), halflife=4), # halflife - how quickly std measure adjusts to change\n name='smoothed_std').shift(1)\n prediction_ts = pd.Series(prediction, name='predicted')\n results = pd.DataFrame(pd.Series(value),columns=['actual']).join(\n prediction_ts).join(smoothed_std_ts)\n results['lower']= results.predicted - std_window * results.smoothed_std\n results['upper']=results.predicted + std_window * results.smoothed_std\n\n counter = []\n for x in range(len(results['actual'])):\n if results.actual[x] < results.lower[x]:\n counter.append(x)\n elif results.actual[x] > results.upper[x]:\n counter.append(x)\n\n results['anomalies'] = results.actual[counter]\n\n results.plot() #plotin all result df columns\n plt.plot(results.anomalies, 'ro') #ploting nomalies\n show()\n return results.anomalies\n\n\ndef calculate_trend(series):\n x = np.arange(0,len(series))\n y = np.array(series)\n z = np.polyfit(x,y,1)\n print (\"{0}x + {1}\".format(*z))\n return z\n\n\ndef anomaly_trend(trends, param):\n results = []\n for i,t in enumerate(trends):\n tmp_trends = list(trends)\n tmp_trends.pop(i)\n mean = np.mean(tmp_trends)\n std = np.std(trends)\n if abs(t - mean) > param*std:\n results.append(i)\n print (\"Day {0} is an anomaly trend. Value: {1}, mean: {2}, stddev: {3}\".format(i+1, t, mean, std))\n return results\n","sub_path":"lib/exp_avg.py","file_name":"exp_avg.py","file_ext":"py","file_size_in_byte":3279,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"232465086","text":"import matplotlib.pyplot as plt\nimport matplotlib.cm as cm\nfrom matplotlib.colors import LogNorm\n\n\nimport numpy as np \nfrom scipy.io import wavfile\nfrom scipy import signal\n\n\nif __name__ == \"__main__\":\n #Load in sound file\n soundfiles_path = \"soundfiles/\"\n soundfile = \"ei.wav\"\n\n fs, x = wavfile.read(soundfiles_path + soundfile)\n \n time_series = np.linspace(0, len(x) / fs, num=len(x))\n\n #Simple cleaning/enhancement\n y_offset = np.mean(x)\n x = x - y_offset\n\n #plot time-series and spectrogram\n vowel_period_length = 0.075\n NFFT = int(0.01 * fs)\n noverlap = int(0.005 * fs)\n nperseg = int((NFFT + noverlap) / 2)\n print(NFFT, noverlap, nperseg)\n f, t, Sxx = signal.spectrogram(x,\n fs=fs,\n nperseg=nperseg,\n noverlap=noverlap,\n nfft=NFFT,\n window=signal.get_window('hanning', nperseg),\n detrend=False)\n \n #Upsample and guassian smooth?\n \n\n fig, (ax1,ax2) = plt.subplots(2)\n ax1.set(xlabel='Time [sec]')\n ax1.plot(time_series, x)\n\n ax2.pcolormesh(t, f, Sxx, cmap=cm.gray_r, shading='gouraud', norm=LogNorm())\n ax2.set(xlabel='Time [sec]', ylabel='Frequency [Hz]')\n ax2.set_ylim(0,5000)\n plt.show()","sub_path":"SpectrogramPractice.py","file_name":"SpectrogramPractice.py","file_ext":"py","file_size_in_byte":1215,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"315734676","text":"import scrapy\nimport re\nfrom ..items import Student\n\nclass MySpider(scrapy.Spider):\n name = 'kma-students'\n\n def start_requests(self):\n return [scrapy.FormRequest(\n 'http://my.ukma.edu.ua/checklogin.php',\n formdata={'cmd': '', 'login': '', 'password': ''},\n callback=self.logged_in)]\n\n def logged_in(self, response):\n self.logger.info('logged_in method response.url: %s', response.url)\n logged_in = response.url == 'http://my.ukma.edu.ua/index.php'\n if logged_in:\n self.logger.info('logged_in method auth: ok')\n return scrapy.Request('http://my.ukma.edu.ua/?menuitem=students',\n callback=self.parse)\n else:\n self.logger.info('logged_in method auth: not ok')\n return []\n\n def parse(self, response):\n self.logger.info('parse method: processing a singe page...')\n div = response.xpath('//div[contains(@class, \"col-xs-9\")]')\n data = div.extract_first()\n #processing of the page could have been elegant\n #if the author of the web site had written better html page\n #replacing special characters is done to ease subsequent regex matching\n data = data.replace('\\r\\n', '') \\\n .replace('\\t', '')\n #web resourse was modified recently, the line below in unwanted\n #data = data[ data.index('') : ]\n if 'page' in response.url:\n response.meta['my-data'] = data\n for student in self.parse_students(response):\n yield student\n pages_selector = div.xpath('.//a[contains(@class, \"pages\")]')\n links_to_pages = pages_selector.xpath('./@href').extract()\n if not links_to_pages:\n self.logger.info('parse method: the last page has been reached!')\n else:\n self.logger.info('parse method: current page %s', response.url)\n for link in links_to_pages:\n yield scrapy.Request(response.urljoin(link), callback=self.parse)\n\n def parse_students(self, response):\n data = response.meta['my-data']\n pattern = r'((.*?) (.*?)(.*?) (.*?)) '\n #omitting first item is done due to peculiar way the web site is written\n #if this is not done, the first found item would be invalid\n omit_current = True\n for match in re.finditer(pattern, data):\n if omit_current:\n omit_current = False\n continue\n name, year_and_specialty, plan_link, credits = match.group(2, 3, 4, 6)\n yield Student(\n full_name = name.replace('.', '').strip(),\n year_and_specialty = year_and_specialty.strip(),\n plan_link = response.urljoin(plan_link.replace('&', '&')),\n credits = credits.strip())\n","sub_path":"kma_students_scrapy/kma_students_scrapy/spiders/my_spider.py","file_name":"my_spider.py","file_ext":"py","file_size_in_byte":2926,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"576140701","text":"# -*- coding: utf-8 -*-\n\nimport os\nimport martian\nfrom sys import modules\nfrom megrok.icon import (\n getIconsRegistriesMap, IconsRegistry, ITemporaryIconsRegistry)\nfrom zope.interface import directlyProvides\n\n\ndef icon_absolute_path(frame, path):\n if not os.path.isfile(path):\n pyfile = modules[frame.f_locals['__module__']].__file__\n path = os.path.join(os.path.dirname(pyfile), path)\n if not os.path.isfile(path):\n raise ValueError('%r is not a valid file' % path)\n return path\n\n\nclass icon(martian.Directive):\n scope = martian.CLASS\n store = martian.ONCE\n\n def factory(self, name, registry=\"common\", path=None):\n mapping = getIconsRegistriesMap()\n if path is not None:\n if not registry in mapping:\n reg = mapping.register(registry, IconsRegistry)\n directlyProvides(reg, ITemporaryIconsRegistry)\n else:\n reg = mapping.get(registry)\n\n reg.add(name, icon_absolute_path(self.frame, path))\n else:\n reg = mapping.get(registry)\n if not name in reg:\n raise ValueError('Icon %r does not exist' % name)\n\n return (name, registry)\n","sub_path":"megrok.icon/branches/utility-less/src/megrok/icon/directive.py","file_name":"directive.py","file_ext":"py","file_size_in_byte":1215,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"217189826","text":"from libs.pdf import pdf_merger\n\nfiles_path = \"C:/Users/lhalvorsen/Desktop/presto/\"\nfiles_sub_path = \"pdf_01-BKP/\"\ntarget_filename = \"borrar34d2.pdf\"\n\nsource_dir = files_path + files_sub_path\ntarget_dir = files_path + target_filename\n\npdf_merger(source_dir, target_dir)\n","sub_path":"Projects/vakiten/merge_pdf.py","file_name":"merge_pdf.py","file_ext":"py","file_size_in_byte":270,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"439430975","text":"import os\nimport torch\nimport argparse\n\nimport torchvision\nfrom config import Config\nimport timm\nimport torch.nn as nn\nfrom tqdm import tqdm\nfrom wandb_checkpoint_saver import CheckpointSaver\nimport wandb\nimport logging \nfrom timm.utils.log import setup_default_logging\n\n_logger = logging.getLogger('train')\n\n# test\n\ndef train_fn(model, train_data_loader, optimizer, epoch):\n model.train()\n fin_loss = 0.0\n tk = tqdm(train_data_loader, desc=\"Epoch\" + \" [TRAIN] \" + str(epoch + 1))\n\n for t, data in enumerate(tk):\n data[0] = data[0].to('cuda')\n data[1] = data[1].to('cuda')\n\n optimizer.zero_grad()\n out = model(data[0])\n loss = nn.CrossEntropyLoss()(out, data[1])\n loss.backward()\n optimizer.step()\n\n fin_loss += loss.item()\n tk.set_postfix(\n {\n \"loss\": \"%.6f\" % float(fin_loss / (t + 1)),\n \"LR\": optimizer.param_groups[0][\"lr\"],\n }\n )\n return fin_loss / len(train_data_loader), optimizer.param_groups[0][\"lr\"]\n\n\ndef eval_fn(model, eval_data_loader, epoch):\n model.eval()\n fin_loss = 0.0\n tk = tqdm(eval_data_loader, desc=\"Epoch\" + \" [VALID] \" + str(epoch + 1))\n\n with torch.no_grad():\n for t, data in enumerate(tk):\n data[0] = data[0].to('cuda')\n data[1] = data[1].to('cuda')\n out = model(data[0])\n loss = nn.CrossEntropyLoss()(out, data[1])\n fin_loss += loss.item()\n tk.set_postfix({\"loss\": \"%.6f\" % float(fin_loss / (t + 1))})\n return fin_loss / len(eval_data_loader)\n\n\ndef train(args=None, wandb_run=None):\n # train and eval datasets\n train_dataset = torchvision.datasets.ImageFolder(\n Config[\"TRAIN_DATA_DIR\"], transform=Config[\"TRAIN_AUG\"]\n )\n eval_dataset = torchvision.datasets.ImageFolder(\n Config[\"TEST_DATA_DIR\"], transform=Config[\"TEST_AUG\"]\n )\n\n # train and eval dataloaders\n train_dataloader = torch.utils.data.DataLoader(\n train_dataset,\n batch_size=Config[\"BS\"],\n shuffle=True,\n )\n eval_dataloader = torch.utils.data.DataLoader(\n eval_dataset, batch_size=Config[\"BS\"],\n )\n\n # model\n model = timm.create_model(Config[\"MODEL\"], pretrained=Config[\"PRETRAINED\"])\n model = model.cuda()\n\n # optimizer\n optimizer = torch.optim.Adam(model.parameters(), lr=Config[\"LR\"])\n\n # setup checkpoint saver\n saver = CheckpointSaver(model=model, optimizer=optimizer, args=args, decreasing=True, \n wandb_run=wandb_run, max_history=args.num_checkpoints)\n\n for epoch in range(Config[\"EPOCHS\"]):\n avg_loss_train, lr = train_fn(\n model, train_dataloader, optimizer, epoch\n )\n avg_loss_eval = eval_fn(model, eval_dataloader, epoch)\n saver.save_checkpoint(epoch, metric=avg_loss_eval)\n \n\nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser()\n parser.add_argument('--project', type=str, default='artifacts', required=False)\n parser.add_argument('--num-checkpoints', type=int, default=2, required=False)\n args = parser.parse_args()\n\n setup_default_logging()\n\n run = wandb.init(project=args.project)\n\n train(args=args, wandb_run=run)\n","sub_path":"src/train.py","file_name":"train.py","file_ext":"py","file_size_in_byte":3244,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"539634038","text":"#!/usr/bin/env python\n\"\"\"Process the 3d model data and create required files for NMS.\n\nThis function will take all the data provided by the blender script and create a number of\n.exml files that contain all the data required by the game to view the 3d model created.\n\"\"\"\n\n__author__ = \"monkeyman192\"\n__credits__ = [\"monkeyman192\", \"gregkwaste\"]\n\nfrom classes import *\nimport os\nimport subprocess\nfrom LOOKUPS import *\nfrom shutil import copy2\nfrom array import array\n\nBASEPATH = 'CUSTOMMODELS'\n\nclass Create_Data():\n def __init__(self, name, directory, object_names, index_stream, vertex_stream, uv_stream=None, n_stream=None, t_stream=None,\n mat_indices = [], materials = [], collisions=[]):\n\n \"\"\"\n name - the name of the file we want to create. Most entities within will have a name derived from this.\n directory - the full relative location of where the scene file will be located.\n object_names - A list of the names of the children objects. This can be None, and if so the children will be given default names\n index_stream - A list containing lists of triangle indexes. Each sub list to the main list represents an entire 3d object.\n vertex_stream - A list containing lists of vertices. Each sublist to the main list represents an entire 3d object.\n\n \"\"\"\n\n self.name = name # this is the name of the file\n self.directory = directory # the path that the file is supposed to be located at\n self.object_names = object_names # this is a list of names for each object. Each will be a child of the main model\n\n self.fix_names()\n\n # assign each of the input streams to a variable\n self.index_stream = index_stream\n self.vertex_stream = vertex_stream\n self.uv_stream = uv_stream\n self.n_stream = n_stream\n self.t_stream = t_stream\n self.mat_indices = mat_indices # this will be the same length as the list of objects, \n self.mats = materials # this will be a list of TkMaterialData objects\n self.collisions = collisions # a list of Collision objects\n\n self.TkMaterialData_list = list()\n\n # process the stream and object_names inputs to make sure they are all fine:\n self.process_inputs()\n # The above function will define self.i_stream_lens and self.v_stream_lens and will ensure all inputs are the same length\n \n self.num_objects = len(self.object_names) # only the number of objects, doesn't include collisions\n self.num_total = len(index_stream) # total number of objects including collision meshes\n\n self.path = os.path.join(BASEPATH, self.directory, self.name) # the path location including the file name.\n self.texture_path = os.path.join(self.path, 'TEXTURES')\n self.ent_path = os.path.join(self.path, 'ENTITIES') # path location of the entity folder. Calling makedirs of this will ensure all the folders are made in one go\n\n self.create_paths()\n\n # This dictionary contains all the information for the geometry file \n self.GeometryData = dict()\n # This dictionary contais all the data for the scene file\n self.SceneData = dict()\n # This dictionary contains all the data for the material file\n self.Materials = list()\n for i in range(self.num_objects):\n self.Materials.append(dict())\n\n # create the attachment data here as we will just write it when creating the related nodes in the scene file\n self.TkAttachmentData = TkAttachmentData()\n self.TkAttachmentData.make_elements(main=True)\n\n self.process_data()\n\n self.get_bounds()\n\n self.check_streams() #self.stream_list is created here\n\n self.create_vertex_layouts() # this creates the VertexLayout and SmallVertexLayout properties\n\n \"\"\" Basic values \"\"\"\n # Scene defaults\n self.SceneData['Name'] = self.path\n self.SceneData['Transform'] = TkTransformData(TransX = 0, TransY = 0, TransZ = 0,\n RotX = 0, RotY = 0, RotZ = 0,\n ScaleX = 1, ScaleY = 1, ScaleZ = 1)\n self.SceneData['Attributes'] = List(TkSceneNodeAttributeData(Name = \"GEOMETRY\",\n AltID = \"\",\n Value = str(self.path) + \".GEOMETRY.MBIN\"))\n self.SceneData['Children'] = None\n # Material defaults\n self.process_materials()\n\n self.process_nodes()\n\n self.mix_streams() # make this last to make sure flattening each stream doesn't affect other data.\n\n # Assign each of the class objects that contain all of the data their data\n self.TkGeometryData = TkGeometryData(**self.GeometryData)\n self.TkGeometryData.make_elements(main=True)\n self.TkSceneNodeData = TkSceneNodeData(**self.SceneData)\n self.TkSceneNodeData.make_elements(main=True)\n for material in self.mats:\n material.make_elements(main=True)\n\n # write all the files\n self.write()\n\n # convert all the created exml files to mbin files\n self.convert_to_mbin()\n\n def create_paths(self):\n # check whether the require paths exist and make them\n if not os.path.exists(self.ent_path):\n os.makedirs(self.ent_path)\n if not os.path.exists(self.texture_path):\n os.makedirs(self.texture_path)\n\n def process_inputs(self):\n # Makes sure that the number of sublists in vertex_stream and index_stream are the same, and also the same as the number of object names\n # (if specified). If not, generate a number of default names for the object_names list.\n # The vertex and index lists will always come in a list, even if there is only one object (i. = [[(p1), (p2)]]\n \n len_streams = len(self.index_stream)\n self.i_stream_lens = list()\n self.v_stream_lens = list()\n\n self.child_collisions = [None]*len_streams\n\n # We have an added complication that the collision data *may* contain a mesh collision in which case we need to add the vertex and index streams.\n # these will be added first\n j = 0 # index to track which collision index and vertex element belongs to which object\n for i in range(len(self.collisions)):\n collision = self.collisions[i]\n if self.collisions[i] is not None:\n if collision.Type == 'Mesh':\n self.child_collisions[i] = len_streams + j # this is the index in the index and vertex streams and related objects of the collision data for each object\n j += 1\n self.index_stream.append(collision.Indexes)\n self.vertex_stream.append(collision.Vertices)\n if collision.uv_stream is not None and self.uv_stream is not None:\n self.uv_stream.append(collision.uv_stream)\n if collision.Normals is not None and self.n_stream is not None:\n self.n_stream.append(collision.Normals)\n # assign to the above two lists the lengths of each sub-stream\n for lst in self.index_stream:\n self.i_stream_lens.append(len(lst))\n for lst in self.vertex_stream:\n self.v_stream_lens.append(len(lst))\n # now check the object_names\n if self.object_names is not None and type(self.object_names) == list:\n len_names = len(self.object_names)\n if len_names != len_streams: # this is the original length, not the modified length\n # we have a bit of a problem.\n # If there are less, add some default ones up to the right amount.\n # If there are more remove the trailing ones.\n # Either way, notify the user that something is wrong.\n if len_names < len_streams:\n diff = len_streams - len_names\n for i in range(diff):\n self.object_names.append('{0}_{1}'.format(self.name, i))\n error = 'less'\n elif len_names > len_streams:\n self.object_names = self.object_names[:len_streams]\n error = 'more'\n print(\"ERROR! The number of names supplied was {} than required. Please check your inputs.\".format(error))\n else:\n # In this case no names have been provided, or they have been provided in the wrong format.\n # Notify the user and generate default names\n self.object_names = list()\n for i in range(len_streams):\n self.object_names.append('{0}_{1}'.format(self.name, i))\n print('No names for constituent objects specified. Objects given default names.')\n\n def fix_names(self):\n # just make sure that the name and path is all in uppercase\n self.name = self.name.upper()\n self.directory = self.directory.upper()\n\n def process_data(self):\n # This will do the main processing of the different streams.\n \n # indexes\n index_counts = list(3*x for x in self.i_stream_lens) # the total number of index points in each object\n self.batches = list((sum(index_counts[:i]), index_counts[i]) for i in range(len(self.i_stream_lens)))\n # vertices\n self.vert_bounds = list((sum(self.v_stream_lens[:i]), sum(self.v_stream_lens[:i+1])-1) for i in range(len(self.v_stream_lens)))\n\n # we need to fix up the index stream as the numbering needs to be continuous across all the streams\n k = 0 # additive constant\n for i in range(len(self.index_stream)):\n # first add k to every element in every tuple\n curr_max = 0\n for j in range(len(self.index_stream[i])):\n self.index_stream[i][j] = tuple(k + index for index in self.index_stream[i][j])\n local_max = max(self.index_stream[i][j])\n if local_max > curr_max:\n curr_max = local_max\n # now we set k to be the current max and this is added on to the next set.\n k = curr_max + 1\n #print(self.index_stream)\n \n\n # First we need to find the length of each stream.\n self.GeometryData['IndexCount'] = 3*sum(self.i_stream_lens)\n self.GeometryData['VertexCount'] = sum(self.v_stream_lens)\n self.GeometryData['MeshVertRStart'] = list(self.vert_bounds[i][0] for i in range(len(self.vert_bounds)))\n self.GeometryData['MeshVertREnd'] = list(self.vert_bounds[i][1] for i in range(len(self.vert_bounds)))\n\n def process_nodes(self):\n # this will look at the list in object_names and create child nodes for them\n # If the name is COLLISION the name becomes path + name, and the Type is COLLISION\n if len(self.object_names) != 0:\n self.SceneData['Children'] = List()\n if self.collisions == []:\n self.collisions = [None]*self.num_objects\n for i in range(self.num_objects):\n name = self.object_names[i]\n scene_data = dict()\n\n # get some info from the associated material file\n try:\n mat_name = self.mats[self.mat_indices[i]]['Name'].rstrip('_Mat')\n except:\n # in this case there aren't as many materials as there are things... Let's just give it default value...\n mat_name = ''\n scene_data['Name'] = name\n scene_data['Type'] = 'MESH'\n scene_data['Transform'] = TkTransformData(TransX = 0, TransY = 0, TransZ = 0,\n RotX = 0, RotY = 0, RotZ = 0,\n ScaleX = 1, ScaleY = 1, ScaleZ = 1)\n scene_data['Attributes'] = List(TkSceneNodeAttributeData(Name = 'BATCHSTART',\n Value = self.batches[i][0]),\n TkSceneNodeAttributeData(Name = 'BATCHCOUNT',\n Value = self.batches[i][1]),\n TkSceneNodeAttributeData(Name = 'VERTRSTART',\n Value = self.vert_bounds[i][0]),\n TkSceneNodeAttributeData(Name = 'VERTREND',\n Value = self.vert_bounds[i][1]),\n TkSceneNodeAttributeData(Name = 'FIRSTSKINMAT',\n Value = 0),\n TkSceneNodeAttributeData(Name = 'LASTSKINMAT',\n Value = 0),\n TkSceneNodeAttributeData(Name = 'MATERIAL',\n Value = os.path.join(self.path, self.name)+ '_{}'.format(mat_name.upper()) + '.MATERIAL.MBIN'),\n TkSceneNodeAttributeData(Name = 'MESHLINK',\n Value = name + 'Shape'),\n TkSceneNodeAttributeData(Name = 'ATTACHMENT',\n Value = os.path.join(self.ent_path, name.upper()) + '.ENTITY.MBIN'))\n # also write the entity file now as it is pretty much empty anyway\n self.TkAttachmentData.tree.write(\"{}.ENTITY.exml\".format(os.path.join(self.ent_path, name.upper())))\n \n if self.collisions[i] != None:\n collision_data = self.collisions[i]\n # in this case the object has some collision data. Create a child that is a TkCollision object (which is in fact just a renamed TkSceneNodeData object.\n collision_node = TkSceneNodeData(Name = self.path, Type='COLLISION')\n collision_node['Transform'] = collision_data.Transform\n if collision_data.col_type == 'Primitive':\n # this case is simple, call the function and it will create the required List\n collision_data.process_primitives() # this will give the collision_data object an Attributes property that is a List of TkSceneNode AttributeData objects\n collision_node['Attributes'] = collision_data.Attributes\n elif collision_data.col_type == 'Mesh':\n # in this case, we need to get the correct batch start and count and vertr start and end\n # self.child_collisions contains the required index to get the vert and index info.\n collision_data.process_mesh(self.batches[self.child_collisions[i]][0],\n self.batches[self.child_collisions[i]][1],\n self.vert_bounds[self.child_collisions[i]][0],\n self.vert_bounds[self.child_collisions[i]][1])\n collision_node['Attributes'] = collision_data.Attributes\n # set the collision data as a child\n scene_data['Children'] = List(collision_node)\n else:\n scene_data['Children'] = None\n # now add the child object the the list of children of the mian object\n self.SceneData['Children'].append(TkSceneNodeData(**scene_data))\n\n def create_vertex_layouts(self):\n # sort out what streams are given and create appropriate vertex layouts\n VertexElements = List()\n ElementCount = len(self.stream_list)\n for sID in self.stream_list:\n # sID is the SemanticID\n Offset = 8*self.stream_list.index(sID)\n VertexElements.append(TkVertexElement(SemanticID = sID,\n Size = 4,\n Type = 5131,\n Offset = Offset,\n Normalise = 0,\n Instancing = \"PerVertex\",\n PlatformData = \"\"))\n # fow now just make the small vert and vert layouts the same\n self.GeometryData['VertexLayout'] = TkVertexLayout(ElementCount = ElementCount,\n Stride = 8*ElementCount,\n PlatformData = \"\",\n VertexElements = VertexElements)\n self.GeometryData['SmallVertexLayout'] = TkVertexLayout(ElementCount = ElementCount,\n Stride = 8*ElementCount,\n PlatformData = \"\",\n VertexElements = VertexElements)\n \n def mix_streams(self):\n # this combines all the input streams into one single stream with the correct offset etc as specified by the VertexLayout\n # This also flattens each stream\n # Again, for now just make the SmallVertexStream the same. Later, change this.\n \n VertexStream = array('d')\n for i in range(self.num_total):\n for j in range(self.v_stream_lens[i]):\n for sID in self.stream_list:\n # get the j^th 4Vector element of i^th object of the corresponding stream as specified by the stream list.\n # As self.stream_list is ordered this will be mixed in the correct way wrt. the VertexLayouts\n try: \n VertexStream.extend(self.__dict__[SEMANTICS[sID]][i][j])\n except:\n # in the case this fails there is an index error caused by collisions. In this case just add a default value\n VertexStream.extend((0,0,0,1))\n \n self.GeometryData['VertexStream'] = VertexStream\n self.GeometryData['SmallVertexStream'] = VertexStream\n\n # finally we can also flatten the index stream:\n IndexBuffer = array('I')\n for obj in self.index_stream:\n for tri in obj:\n IndexBuffer.extend(tri)\n self.GeometryData['IndexBuffer'] = IndexBuffer\n\n def get_bounds(self):\n # this analyses the vertex stream and finds the smallest bounding box corners.\n\n self.GeometryData['MeshAABBMin'] = List()\n self.GeometryData['MeshAABBMax'] = List()\n \n for i in range(len(self.vertex_stream)):\n obj = self.vertex_stream[i]\n x_verts = [i[0] for i in obj]\n y_verts = [i[1] for i in obj]\n z_verts = [i[2] for i in obj]\n x_bounds = (min(x_verts), max(x_verts))\n y_bounds = (min(y_verts), max(y_verts))\n z_bounds = (min(z_verts), max(z_verts))\n\n self.GeometryData['MeshAABBMin'].append(Vector4f(x=x_bounds[0], y=y_bounds[0], z=z_bounds[0], t=1))\n self.GeometryData['MeshAABBMax'].append(Vector4f(x=x_bounds[1], y=y_bounds[1], z=z_bounds[1], t=1))\n\n def check_streams(self):\n # checks what streams have been given. Vertex and index streams are always required.\n # self.stream list \n self.stream_list = []\n for i in SEMANTICS:\n if self.__dict__[SEMANTICS[i]] is not None:\n self.stream_list.append(i)\n self.stream_list.sort()\n\n def process_materials(self):\n # process the material data and gives the textures the correct paths\n for material in self.mats:\n samplers = material['Samplers']\n # this will have the order Diffuse, Masks, Normal and be a List\n for sample in samplers.subElements:\n # this will be a TkMaterialSampler object\n t_path = sample['Map'] # this should be the current absolute path to the image, we want to move it to the correct relative path\n new_path = os.path.join(self.texture_path, os.path.basename(t_path).upper())\n try:\n copy2(t_path, new_path)\n except FileNotFoundError:\n # in this case the path is probably broken, just set as empty if it wasn't before\n new_path = \"\"\n f_name, ext = os.path.splitext(new_path)\n if ext != '.DDS' and ext != '':\n # in this case the file is not in the correct format. Put the correct file extension in the material file\n print('The file {} needs to be converted to .DDS format (file extention to be capitalised also!)'.format(new_path))\n sample['Map'] = f_name + '.DDS'\n else:\n # all good in this case\n sample['Map'] = new_path\n \n def write(self):\n # write each of the exml files.\n self.TkGeometryData.tree.write(\"{}.GEOMETRY.exml\".format(self.path))\n self.TkSceneNodeData.tree.write(\"{}.SCENE.exml\".format(self.path))\n for material in self.mats:\n material.tree.write(\"{0}_{1}.MATERIAL.exml\".format(os.path.join(self.path, self.name), material['Name'].rstrip('_Mat').upper()))\n\n def convert_to_mbin(self):\n # passes all the files produced by\n print('Converting all .exml files to .mbin. Please wait while this finishes.')\n for directory, folders, files in os.walk(os.path.join(BASEPATH, self.directory)):\n for file in files:\n location = os.path.join(directory, file)\n if os.path.splitext(location)[1] == '.exml':\n subprocess.call([\"MBINCompiler.exe\", location])\n if os.path.splitext(os.path.splitext(location)[0])[1] == \".SCENE\":\n os.remove(location)\n \n\n \nif __name__ == '__main__':\n\n main = Create_Data('SQUARE', 'TEST', ['Square1', 'Square2'],\n index_stream = [[(0,1,2), (2,3,0)],\n [(0,1,2), (2,3,0)]],\n vertex_stream = [[(-1,1,0,1), (1,1,0,1), (1,-1,0,1), (-1,-1,0,1)],\n [(2,1,0,1), (4,1,0,1), (4,-1,0,1), (2,-1,0,1)]],\n uv_stream = [[(0.3,0,0,1), (0,0.2,0,1), (0,0.1,0,1), (0.1,0.2,0,1)],\n [(0.5,0,0,1), (0.2,0.2,0,1), (0,0.5,0,1), (0.1,0.2,0,1)]],\n collisions = [Collision(Type='Mesh', Vertices=[(-4,4,0,1),(4,4,0,1), (4,-4,0,1), (-4,-4,0,1)],\n Indexes=[(0,1,2), (2,3,0)]),\n Collision(Type='Sphere', Radius=5)])\n\n\n from lxml import etree\n\n def prettyPrintXml(xmlFilePathToPrettyPrint):\n assert xmlFilePathToPrettyPrint is not None\n parser = etree.XMLParser(resolve_entities=False, strip_cdata=False)\n document = etree.parse(xmlFilePathToPrettyPrint, parser)\n document.write(xmlFilePathToPrettyPrint, xml_declaration='', pretty_print=True, encoding='utf-8')\n\n prettyPrintXml('TEST\\SQUARE.GEOMETRY.exml')\n prettyPrintXml('TEST\\SQUARE.SCENE.exml')\n #prettyPrintXml('TEST\\SQUARE\\SQUARE_SQUARE.MATERIAL.exml')\n","sub_path":"nms_imp/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":23885,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"437936303","text":"# -*- coding: utf-8 -*-\n\"\"\"\n@author: s.jayanthi\n\"\"\"\n\n# Docstrings Usage\nimport numpy as np\n\ndef funcA(arg1: int, arg2: list, arg3: 'string' = 'My Default String')->float:\n \"\"\"\n Python does not automatically check if your inputs are oif same type as required by this method. You have to check it yourself. Source: https://stackoverflow.com/questions/2489669/function-parameter-types-in-python\n \"\"\"\n if not isinstance(arg1, int):\n raise TypeError\n if not isinstance(arg2, list):\n raise TypeError('arg2: list')\n print(arg3)\n return np.float(arg1)\nhelp(funcA)\nprint(funcA.__annotations__)\nprint(funcA(10.34324,['hello','bye'])) # ----> TypeError thrown\nprint(funcA(10,'Alpha')) # ----> TypeError thrown\nprint(funcA(10,['hello','bye'])) # ----> No error thrown\nprint(funcA(10,[],'Alpha')) # ----> No error thrown\n\nret_dict = {'type': list, 'contains': 'a modified list', 'docstring':'A sample method is coded'}\ndef funcB(arg1: 'a number', arg2: 'a list', arg3: 'a string' = 'My Default String')->ret_dict:\n if not isinstance(arg1, int):\n raise TypeError\n if not isinstance(arg2, list):\n raise TypeError('arg2: list')\n if arg1>len(arg2):\n raise Exception('arg1<=len(arg2)')\n print('Before change: ', arg2)\n arg2[arg1-1] = arg3;\n print('After change: ', arg2)\n return arg2\nhelp(funcB)\nprint(funcB.__annotations__)\nprint(funcB(10,['hello','bye'])) # ----> Exception thrown\nprint(funcB(1,['hello','bye'])) # ----> No error thrown","sub_path":"python/py_docstrings.py","file_name":"py_docstrings.py","file_ext":"py","file_size_in_byte":1541,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"375200459","text":"import nltk\nnltk.download('wordnet')\nnltk.download('stopwords')\nfrom nltk.corpus import stopwords\n\nfrom nltk.stem.porter import *\nporterStem = PorterStemmer()\n\ndef build(id, document):\n #tokenize\n tokens = parseWords(document)\n\n #convert to dictionary, remove duplicates\n result = {}\n for token in tokens:\n result[token] = id\n\n return result\n\ndef normalize(token):\n token = token.replace('-',' ')\n token = token.replace('.','')\n return token\n\ndef parseWords(words):\n tokens = nltk.word_tokenize(words)\n\n # convert to lowercase\n tokens = [word.lower() for word in tokens]\n\n # Normalize\n tokens = [normalize(t) for t in tokens]\n\n # remove stop words\n tokens = [t for t in tokens if t not in stopwords.words('english')]\n\n # stem\n tokens = [porterStem.stem(t) for t in tokens]\n\n return tokens\n","sub_path":"dictionary.py","file_name":"dictionary.py","file_ext":"py","file_size_in_byte":853,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"143757335","text":"# https://leetcode.com/problems/move-zeroes/\n\nclass Solution(object):\n\n # Time complexity: O(n)\n # Space complexity: O(1)\n def moveZeroes(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: void Do not return anything, modify nums in-place instead.\n \"\"\"\n zero_count = 0\n\n for i in xrange(len(nums)):\n if nums[i] == 0:\n zero_count += 1\n else:\n nums[i], nums[i - zero_count] = nums[i - zero_count], nums[i]","sub_path":"move-zeroes.py","file_name":"move-zeroes.py","file_ext":"py","file_size_in_byte":505,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"421741828","text":"#!/usr/bin/env python\n\nimport numpy as np\nimport matplotlib.pyplot as plt\n\n# Make sure that caffe is on the python path:\ncaffe_root = '/work/personal/caffe/' # this file is expected to be in {caffe_root}/examples\nimport sys\nsys.path.insert(0, caffe_root + 'python')\n\nimport caffe\n\ndef vis_square(data):\n \"\"\"Take an array of shape (n, height, width) or (n, height, width, 3)\n and visualize each (height, width) thing in a grid of size approx. sqrt(n) by sqrt(n)\"\"\"\n \n # normalize data for display\n data = (data - data.min()) / (data.max() - data.min())\n \n # force the number of filters to be square\n n = int(np.ceil(np.sqrt(data.shape[0])))\n padding = (((0, n ** 2 - data.shape[0]),\n (0, 1), (0, 1)) # add some space between filters\n + ((0, 0),) * (data.ndim - 3)) # don't pad the last dimension (if there is one)\n data = np.pad(data, padding, mode='constant', constant_values=1) # pad with ones (white)\n \n # tile the filters into an image\n data = data.reshape((n, n) + data.shape[1:]).transpose((0, 2, 1, 3) + tuple(range(4, data.ndim + 1)))\n data = data.reshape((n * data.shape[1], n * data.shape[3]) + data.shape[4:])\n \n plt.imshow(data); plt.axis('off')\n plt.savefig('visualize-filters.png')\n\n\ndef main():\n import pdb; pdb.set_trace()\n net = caffe.Net('test.prototxt',\n 'models/scratch_iter_90000.caffemodel',\n caffe.TEST)\n\n filters = net.params['conv1'][0].data\n vis_square(filters.transpose(0, 2, 3, 1))\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"Sec_5/visualize.py","file_name":"visualize.py","file_ext":"py","file_size_in_byte":1599,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"340795344","text":"import re, sys\nfrom parse.parser import Parser\nfrom parse.tokenizer import Tokenizer\nimport eval.evaluator as eval\n\n# The Tex Programming Language\n# www.github.com/Visual-mov/Tex-lang\n#\n# Copywrite(c) Ryan Danver (Visual-mov) 2019\n\nDEBUG = False\n\ndef repl(argv):\n run = True\n g_table = eval.SymbolTable()\n if len(argv)-1 > 1 and argv[1] == \"--file\":\n try:\n source = open(argv[2], 'r').read()\n tokenizer = Tokenizer(source)\n tokens = tokenizer.lex()\n if DEBUG: tokenizer.print_tokens()\n\n ast = Parser(tokens).parse()\n if DEBUG: print(str(ast) + '\\n')\n\n evaluator = eval.Evaluator(ast, g_table, False)\n evaluator.eval()\n except FileNotFoundError:\n repl_error(f\"Can not find file: \\\"{argv[2]}\\\"\")\n else:\n print(\"Tex Language REPL\")\n line = 1\n while run:\n try: \n eval.Evaluator(Parser(Tokenizer(input(\">> \").replace('\\n',''), line).lex()).parse(), g_table, True).eval()\n except KeyboardInterrupt:\n repl_error()\n line += 1\n\ndef repl_error(message=\"\"):\n print(message)\n exit()\n\nif __name__ == \"__main__\":\n repl(sys.argv)","sub_path":"src/tex-repl.py","file_name":"tex-repl.py","file_ext":"py","file_size_in_byte":1232,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"108414223","text":"# ---------------------------------------------------------\n# Copyright (c) Microsoft Corporation. All rights reserved.\n# ---------------------------------------------------------\n\nfrom typing import List\n\nfrom azure.ai.ml.entities._mixins import RestTranslatableMixin\nfrom azure.ai.ml._utils._experimental import experimental\nfrom azure.ai.ml._restclient.v2023_04_01_preview.models import (\n NotificationSetting,\n EmailMonitoringAlertNotificationSettings,\n EmailNotificationEnableType,\n)\n\n\n@experimental\nclass AlertNotification(RestTranslatableMixin):\n \"\"\"Alert notification configuration for monitoring jobs\n\n :param emails: A list of emails that will receive notifications for monitoring alerts\n :type emails: List[str]\n \"\"\"\n\n def __init__(\n self,\n *,\n emails: List[str] = None,\n ):\n self.emails = emails\n\n def _to_rest_object(\n self,\n ) -> EmailMonitoringAlertNotificationSettings:\n return EmailMonitoringAlertNotificationSettings(\n email_notification_setting=NotificationSetting(\n emails=self.emails, email_on=[EmailNotificationEnableType.JOB_FAILED]\n )\n )\n\n @classmethod\n def _from_rest_object(cls, obj: EmailMonitoringAlertNotificationSettings) -> \"AlertNotification\":\n return cls(emails=obj.email_notification_setting.emails)\n","sub_path":"sdk/ml/azure-ai-ml/azure/ai/ml/entities/_monitoring/alert_notification.py","file_name":"alert_notification.py","file_ext":"py","file_size_in_byte":1366,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"474481720","text":"\"\"\"\n\nAR Model\n\n\"\"\"\n\nfrom base_model import base_model\n\nimport numpy\nimport scipy\nimport pandas\nimport extras\nfrom sklearn import linear_model\nfrom sklearn.model_selection import TimeSeriesSplit\n\nclass AR(base_model):\n \"\"\" Parameter optimization method: scipy's minimization \"\"\"\n \n def __init__(self, p=None):\n self.p = p\n self.phi0 = numpy.random.rand(1)\n self.phi = numpy.random.rand(p)\n \n def params2vector(self):\n params = list()\n params.append(self.phi0)\n for i in range(len(self.phi)):\n params.append(self.phi[i])\n return params\n \n def vector2params(self, vector):\n self.phi0 = vector[0]\n self.phi = vector[1:]\n return self\n \n def get_X(self, ts):\n y = ts.values\n X = list()\n for i in range(len(ts)):\n if i <= self.p:\n if i == 0:\n value = [0] * self.p\n X.append(value)\n else:\n value_0 = [0] * (self.p - i)\n value_1 = y[0:i].tolist()\n value = value_0 + value_1\n X.append(value)\n else:\n value = y[i-self.p:i].tolist()\n X.append(value) \n return X\n \n def predict(self, ts):\n y = ts.values\n prediction = list()\n for i in range(len(y)):\n if i <= self.p:\n if i == 0:\n prediction.append(self.phi0)\n else:\n y_last = y[0:i]\n result = self.phi0 + numpy.dot(y_last, self.phi[0:i])\n prediction.append(result)\n else:\n y_last = y[i-self.p:i]\n result = self.phi0 + numpy.dot(y_last, self.phi)\n prediction.append(result)\n prediction = pandas.Series((v for v in prediction), index = ts.index)\n return prediction \n \n \n def fit(self, ts, error_type = 'mean_squared_error'):\n \n def f(x):\n self.vector2params(x) \n return self.calc_error(ts, error_type)\n \n x0 = self.params2vector()\n optim_params = scipy.optimize.minimize(f, x0)\n self.vector2params(vector = optim_params.x) \n self.ts = self.predict(ts) \n \n return self\n \n def forecast(self, ts, periods):\n \n def forward(y):\n y = y.values\n lon = len(y)\n if lon <= self.p:\n y_last = y[0:lon]\n result = self.phi0 + numpy.dot(y_last, self.phi[0:lon])\n else:\n y_last = y[lon-self.p:lon]\n result = self.phi0 + numpy.dot(y_last, self.phi)\n \n return result\n \n for i in range(periods): \n if i == 0:\n y = ts\n value = forward(y)\n \n value = forward(y)\n y = extras.add_next_date(y, value)\n \n return y\n \n def cross_validation(self, ts, n_splits, error_type = None):\n X = numpy.array(self.get_X(ts))\n y = numpy.array(ts.values.tolist())\n y_index = numpy.array(ts.index)\n tscv = TimeSeriesSplit(n_splits = n_splits)\n splits = tscv.split(X)\n \n error_list = list()\n for train_index, test_index in splits:\n #X_train, X_test = X[train_index], X[test_index]\n y_train, y_test = y[train_index], y[test_index]\n y_train_index, y_test_index = y_index[train_index], y_index[test_index]\n \n y_train = pandas.Series((v for v in y_train), index = y_train_index)\n y_test = pandas.Series((v for v in y_test), index = y_test_index)\n self.fit(y_train)\n error = self.calc_error(y_test, error_type)\n error_list.append(error)\n \n return error_list \n \n \n \n \nclass AR_Ridge(AR):\n \"\"\" Parameter optimization method: SciKit's Ridge linear model \"\"\"\n \n def __init__(self, p=None, alpha=0.5, copy_X=True, fit_intercept=True, max_iter=None, \n normalize=False, random_state=None, solver='auto', tol=0.001):\n self.p = p \n self.alpha = alpha\n self.copy_X = copy_X\n self.fit_intercept = fit_intercept\n self.max_iter = max_iter\n self.normalize = normalize\n self.random_state = random_state\n self.solver = solver\n self.tol = tol\n \n def fit(self, ts):\n \n X = self.get_X(ts)\n y = ts.values.tolist()\n ridge_model = linear_model.Ridge(alpha = self.alpha, copy_X = self.copy_X, \n fit_intercept = self.fit_intercept, \n max_iter = self.max_iter, \n normalize = self.normalize, \n random_state = self.random_state, \n solver = self.solver, tol = self.tol)\n ridge_model.fit(X, y)\n optim_params = list()\n optim_params.append(ridge_model.intercept_)\n optim_params = optim_params + ridge_model.coef_.tolist()\n self.vector2params(vector = optim_params)\n self.ts = self.predict(ts) \n \n return self\n \nclass AR_Ridge_2(AR):\n \"\"\" Parameter optimization method: SciKit's Ridge linear model \"\"\"\n \n def __init__(self, p=None, **kwargs):\n self.p = p\n \n def fit(self, ts, **kwargs):\n \n X = self.get_X(ts)\n y = ts.values.tolist()\n ridge_model = linear_model.Ridge(**kwargs)\n ridge_model.fit(X, y)\n optim_params = list()\n optim_params.append(ridge_model.intercept_)\n optim_params = optim_params + ridge_model.coef_.tolist()\n self.vector2params(vector = optim_params)\n self.ts = self.predict(ts) \n \n return self\n \n\nclass AR_Lasso(AR):\n \"\"\" Parameter optimization method: SciKit's Lasso linear model \"\"\"\n \n def __init__(self, p=None, alpha=0.1, copy_X=True, fit_intercept=True, max_iter=1000,\n normalize=False, positive=False, precompute=False, random_state=None,\n selection='cyclic', tol=0.0001, warm_start=False):\n self.p = p\n self.alpha = alpha\n self.copy_X = copy_X\n self.fit_intercept = fit_intercept\n self.max_iter = max_iter\n self.normalize = normalize\n self.positive = positive\n self.precompute = precompute\n self.random_state = random_state\n self.selection = selection\n self.tol = tol\n self.warm_start = warm_start\n \n def fit(self, ts):\n \n X = self.get_X(ts)\n y = ts.values.tolist()\n lasso_model = linear_model.Lasso(alpha = self.alpha, copy_X = self.copy_X, \n fit_intercept = self.fit_intercept, \n max_iter = self.max_iter, \n normalize = self.normalize,\n positive = self.positive,\n precompute = self.precompute,\n random_state = self.random_state, \n selection = self.selection, tol = self.tol,\n warm_start = self.warm_start)\n lasso_model.fit(X, y)\n optim_params = list()\n optim_params.append(lasso_model.intercept_)\n optim_params = optim_params + lasso_model.coef_.tolist()\n self.vector2params(vector = optim_params)\n self.ts = self.predict(ts) \n \n return self\n \n\n\nclass AR_ElasticNet(AR):\n \"\"\" Parameter optimization method: SciKit's Elastic Net linear model \"\"\"\n \n def __init__(self, p=None, alpha=1.0, copy_X=True, fit_intercept=True, l1_ratio=0.5,\n max_iter=1000, normalize=False, positive=False, precompute=False,\n random_state=0, selection='cyclic', tol=0.0001, warm_start=False):\n self.p = p\n self.alpha = alpha\n self.copy_X = copy_X\n self.fit_intercept = fit_intercept\n self.l1_ratio = l1_ratio\n self.max_iter = max_iter\n self.normalize = normalize\n self.positive = positive\n self.precompute = precompute\n self.random_state = random_state\n self.selection = selection\n self.tol = tol\n self.warm_start = warm_start\n \n def fit(self, ts):\n \n X = self.get_X(ts)\n y = ts.values.tolist()\n lasso_model = linear_model.ElasticNet(alpha = self.alpha, copy_X = self.copy_X, \n fit_intercept = self.fit_intercept,\n l1_ratio = self.l1_ratio,\n max_iter = self.max_iter, \n normalize = self.normalize,\n positive = self.positive,\n precompute = self.precompute,\n random_state = self.random_state, \n selection = self.selection, tol = self.tol,\n warm_start = self.warm_start)\n lasso_model.fit(X, y)\n optim_params = list()\n optim_params.append(lasso_model.intercept_)\n optim_params = optim_params + lasso_model.coef_.tolist()\n self.vector2params(vector = optim_params)\n self.ts = self.predict(ts) \n \n return self","sub_path":"pytimeseries/AR.py","file_name":"AR.py","file_ext":"py","file_size_in_byte":9730,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"437084119","text":"# from __future__ import print_function\nimport os\nimport sys\nsys.path.append('..')\nsys.path.append('../..')\nimport argparse\nimport utils\nfrom student_utils import *\n# import numpy\n\n\nimport random\nfrom ortools.constraint_solver import routing_enums_pb2\nfrom ortools.constraint_solver import pywrapcp\n\n# from pyscipopt import Model, quicksum, multidict\n# from cvxopt import matrix, solvers\n\n\"\"\"\n======================================================================\n Complete the following function.\n======================================================================\n\"\"\"\n\ndef solve(list_of_locations, list_of_homes, starting_car_location, adjacency_matrix, params=[]):\n \"\"\"\n Write your algorithm here.\n Input:\n list_of_locations: A list of locations such that node i of the graph corresponds to name at index i of the list\n list_of_homes: A list of homes\n starting_car_location: The name of the starting location for the car\n adjacency_matrix: The adjacency matrix from the input file\n Output:\n A list of locations representing the car path\n A dictionary mapping drop-off location to a list of homes of TAs that got off at that particular location\n NOTE: both outputs should be in terms of indices not the names of the locations themselves\n \"\"\"\n ##### Startup\n # SHORTHANDS\n locations = list_of_locations\n homes = list_of_homes\n\n # Find index i where the car starts\n start_index = locations.index(starting_car_location)\n\n # Convert adjacency matrix representation to graph in networkx [Return Type is (graph, msg=_)]\n graph, _ = adjacency_matrix_to_graph(adjacency_matrix)\n \n # Store number of \"vertices\" V\n V = len(locations)\n\n # Run networkx's Floyd Warshall Alg (V^3 runtime, V^2 space)\n # distance = {(source, target), dist} dictionary of shortest path distance\n # pred = {(source, target), ?} dictionary of predecessors\n predecessor, distance = nx.floyd_warshall_predecessor_and_distance(graph)\n\n ##### Calculate an approximate optimal D = len(dropoffs)\n D = random.randint(1, V)\n # D = 8\n\n ##### Find dropoff points D\n dists_to_home = []\n for source in range(V):\n cum_dist = 0\n ss_dists = distance[source]\n for home in homes:\n target = locations.index(home)\n cum_dist += ss_dists[target]\n dists_to_home.append(cum_dist)\n\n enum_dists = list(enumerate(dists_to_home))\n enum_dists.sort(key=lambda x: x[1])\n dists_to_home = [elem[0] for elem in enum_dists[:D]]\n # print(\"indices: \" + str(dists_to_home)) \n # dists_to_home.append(start_index)\n dropoff_points = dists_to_home\n \n \n\n ##### Compute the TSP on dropoffs\n induced = graph.subgraph(dropoff_points)\n induced_adj_matrix = nx.to_numpy_matrix(induced)\n # print(\"original matrix:\\n\", nx.to_numpy_matrix(graph))\n # print(\"adj matrix:\\n\", induced_adj_matrix)\n # print(\"\\n\")\n data = {}\n data['distance_matrix'] = induced_adj_matrix\n data['num_vehicles'] = 1\n data['depot'] = 0\n\n # Helper fn 1: returns total path (with last point = start point)\n def get_path(manager, routing, assignment):\n index = routing.Start(0)\n path = []\n while not routing.IsEnd(index):\n path.append(manager.IndexToNode(index))\n index = assignment.Value(routing.NextVar(index))\n path.append(path[0])\n return path\n\n # Helper fn 2: used by OR-Tools to find distances between nodes\n def distance_callback(from_index, to_index):\n from_node = manager.IndexToNode(from_index)\n to_node = manager.IndexToNode(to_index)\n return data['distance_matrix'][from_node, to_node]\n\n # Create OR-Tools' routing index manager and Routing Model\n manager = pywrapcp.RoutingIndexManager(len(data['distance_matrix']), data['num_vehicles'], data['depot'])\n routing = pywrapcp.RoutingModel(manager)\n\n transit_callback_index = routing.RegisterTransitCallback(distance_callback)\n\n # Define cost of each arc.\n routing.SetArcCostEvaluatorOfAllVehicles(transit_callback_index)\n\n # Setting first solution heuristic.\n search_parameters = pywrapcp.DefaultRoutingSearchParameters()\n search_parameters.first_solution_strategy = (routing_enums_pb2.FirstSolutionStrategy.PATH_CHEAPEST_ARC)\n\n # Solve TSP and determine path/total distance\n assignment = routing.SolveWithParameters(search_parameters)\n if assignment:\n car_path = get_path(manager, routing, assignment)\n\n # Create dropoff location dictionary\n home_indices = convert_locations_to_indices(homes, locations)\n dropoff_dictionary = {}\n # for index in car_path:\n # if index in dropoff_points:\n # x = random.choice(home_indices)\n # home_indices.remove(x)\n # dropoff_dictionary[index] = [x]\n\n # for i in dropoff_points:\n # x = random.choice(home_indices)\n # home_indices.remove(x)\n # dropoff_dictionary[dropoff_points[i]] = [x]\n # print(dropoff_dictionary)\n\n temp = []\n for i in car_path:\n temp.append(dropoff_points[i])\n\n for i in home_indices:\n d = random.choice(temp)\n if d not in dropoff_dictionary:\n dropoff_dictionary[d] = [i]\n else:\n dropoff_dictionary[d].append(i)\n # print(dropoff_dictionary)\n\n # print(\"temp:\", temp)\n\n actual_path = [temp[0]]\n for i in range(1, len(temp)):\n # print(\"going back from\", temp[i])\n prev = temp[i-1]\n curr = temp[i]\n y = [temp[i]]\n temp_dict = predecessor[prev]\n # print(temp_dict)\n while curr != prev:\n backtrack = temp_dict[curr]\n y.append(backtrack)\n curr = backtrack\n y.pop()\n # print(\"y:\",y)\n y.reverse()\n # print(\"y:\",y)\n actual_path.extend(y)\n\n # print(actual_path)\n \n\n # DEBUG COST\n # print(\"car_path:\", car_path)\n # print(\"temp:\", temp)\n # print(\"actual_path:\", actual_path)\n # print(\"# homes:\", len(homes))\n # print(\"dropoff points:\", dropoff_points)\n # print(\"# actual dropoffs:\", len(dropoff_dictionary))\n # print(\"actual dropoffs:\", dropoff_dictionary)\n # print(\"\\n\")\n\n # print(\"\\n\")\n # # for i in range(len(actual_path)-1):\n # # print(\"i:\", i)\n # # print(actual_path[i], actual_path[i+1])\n # # print(distance[actual_path[i]][actual_path[i+1]])\n # # print(\"\\n\")\n\n c, m = cost_of_solution(graph, actual_path, dropoff_dictionary)\n # print(\"cost:\", c)\n # print(m)\n\n # Return two dictionaries\n return actual_path, dropoff_dictionary \n\n\"\"\"\n======================================================================\n No need to change any code below this line\n======================================================================\n\"\"\"\n\n\"\"\"\nConvert solution with path and dropoff_mapping in terms of indices\nand write solution output in terms of names to path_to_file + file_number + '.out'\n\"\"\"\ndef convertToFile(path, dropoff_mapping, path_to_file, list_locs):\n string = ''\n for node in path:\n string += list_locs[node] + ' '\n string = string.strip()\n string += '\\n'\n\n dropoffNumber = len(dropoff_mapping.keys())\n string += str(dropoffNumber) + '\\n'\n for dropoff in dropoff_mapping.keys():\n strDrop = list_locs[dropoff] + ' '\n for node in dropoff_mapping[dropoff]:\n strDrop += list_locs[node] + ' '\n strDrop = strDrop.strip()\n strDrop += '\\n'\n string += strDrop\n utils.write_to_file(path_to_file, string)\n\ndef solve_from_file(input_file, output_directory, params=[]):\n print('Processing', input_file)\n\n input_data = utils.read_file(input_file)\n num_of_locations, num_houses, list_locations, list_houses, starting_car_location, adjacency_matrix = data_parser(input_data)\n car_path, drop_offs = solve(list_locations, list_houses, starting_car_location, adjacency_matrix, params=params)\n\n basename, filename = os.path.split(input_file)\n if not os.path.exists(output_directory):\n os.makedirs(output_directory)\n output_file = utils.input_to_output(input_file, output_directory)\n\n convertToFile(car_path, drop_offs, output_file, list_locations)\n\n\ndef solve_all(input_directory, output_directory, params=[]):\n input_files = utils.get_files_with_extension(input_directory, 'in')\n\n for input_file in input_files:\n solve_from_file(input_file, output_directory, params=params)\n\n\nif __name__==\"__main__\":\n parser = argparse.ArgumentParser(description='Parsing arguments')\n parser.add_argument('--all', action='store_true', help='If specified, the solver is run on all files in the input directory. Else, it is run on just the given input file')\n parser.add_argument('input', type=str, help='The path to the input file or directory')\n parser.add_argument('output_directory', type=str, nargs='?', default='.', help='The path to the directory where the output should be written')\n parser.add_argument('params', nargs=argparse.REMAINDER, help='Extra arguments passed in')\n args = parser.parse_args()\n output_directory = args.output_directory\n if not args.all:\n input_directory = args.input\n solve_all(input_directory, output_directory, params=args.params)\n else:\n input_file = args.input\n solve_from_file(input_file, output_directory, params=args.params)\n","sub_path":"solver.py","file_name":"solver.py","file_ext":"py","file_size_in_byte":9432,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"526541609","text":"import logging\nimport ask_sdk_core.utils as ask_utils\nimport os\nfrom ask_sdk_s3.adapter import S3Adapter\ns3_adapter = S3Adapter(bucket_name=os.environ[\"S3_PERSISTENCE_BUCKET\"])\n\nfrom ask_sdk_core.skill_builder import CustomSkillBuilder\nfrom ask_sdk_core.dispatch_components import AbstractRequestHandler\nfrom ask_sdk_core.dispatch_components import AbstractExceptionHandler\nfrom ask_sdk_core.handler_input import HandlerInput\n\nfrom ask_sdk_model import Response\n\nimport requests\nimport configparser\n\nlogger = logging.getLogger(__name__)\nlogger.setLevel(logging.INFO)\n\n\nclass LaunchRequestHandler(AbstractRequestHandler):\n \"\"\"Handler for Skill Launch.\"\"\"\n def can_handle(self, handler_input):\n # type: (HandlerInput) -> bool\n\n return ask_utils.is_request_type(\"LaunchRequest\")(handler_input)\n \n def save_solution(self, handler_input):\n \"\"\"\n \"\"\"\n \n try:\n attributes_manager = handler_input.attributes_manager\n solution_data = { \"solution\": \"You have not yet given me an anagram to solve\" }\n attributes_manager.persistent_attributes = solution_data\n attributes_manager.save_persistent_attributes()\n return True\n except:\n return False\n\n def handle(self, handler_input):\n # type: (HandlerInput) -> Response\n self.save_solution(handler_input)\n speak_output = \"Welcome to anagram solver, ask me to solve, followed by the letters in your anagram\"\n reprompt = \"Go ahead, say solve and list the letters in your anagram\"\n\n return (\n handler_input.response_builder\n .speak(speak_output)\n .ask(reprompt)\n .response\n )\n\n\nclass AnagramSolverIntentHandler(AbstractRequestHandler):\n \"\"\"Handler for Anagram Solver Intent.\"\"\"\n def can_handle(self, handler_input):\n # type: (HandlerInput) -> bool\n return ask_utils.is_intent_name(\"AnagramSolverIntent\")(handler_input)\n \n def save_solution(self, handler_input, solution):\n \"\"\"\n \"\"\"\n \n try:\n attributes_manager = handler_input.attributes_manager\n solution_data = { \"solution\": solution }\n attributes_manager.persistent_attributes = solution_data\n attributes_manager.save_persistent_attributes()\n return True\n except:\n return False\n\n def handle(self, handler_input):\n # type: (HandlerInput) -> Response\n \n slots = handler_input.request_envelope.request.intent.slots\n anagram = slots[\"characters\"].value.replace(\" \", \"\").lower()\n \n \n conf = configparser.ConfigParser()\n conf.read('conf.ini')\n\n aws_gateway_section = conf[\"aws_gateway_api_auth\"]\n anagram_solver_endpoint = aws_gateway_section[\"anagram_solver_endpoint\"]\n api_key = aws_gateway_section[\"api_key\"]\n \n \n url = \"{endpoint}?anagram={anagram}\".format(endpoint=anagram_solver_endpoint, anagram=anagram)\n headers={\"x-api-key\": api_key}\n response = requests.get(url, headers=headers)\n \n if response.status_code != 200:\n speak_output = \"Sorry, we were not able to access our dictionary at this time, please try again\"\n self.save_solution(handler_input, speak_output)\n \n if response.status_code == 200 and len(response.json()[\"solution\"]) == 0:\n speak_output = \"Sorry, we were not able to find the solution for this anagram, try another\"\n self.save_solution(handler_input, speak_output)\n \n if response.status_code == 200 and len(response.json()[\"solution\"]) > 0:\n speak_output = \"We found the following solutions, {} \".format(', '.join(response.json()[\"solution\"]))\n self.save_solution(handler_input, speak_output)\n\n return (\n handler_input.response_builder\n .speak(speak_output)\n # .ask(\"add a reprompt if you want to keep the session open for the user to respond\")\n .response\n )\n\nclass RepeatSolutionIntentHandler(AbstractRequestHandler):\n \"\"\"Handler for Repeat Solution Intent.\"\"\"\n def can_handle(self, handler_input):\n # type: (HandlerInput) -> bool\n return ask_utils.is_intent_name(\"RepeatSolutionIntent\")(handler_input)\n \n def get_previous_solution(self, handler_input):\n \"\"\"\n \"\"\"\n \n try:\n attr = handler_input.attributes_manager.persistent_attributes\n previous_solution = attr[\"solution\"]\n return previous_solution\n except:\n return False\n \n\n def handle(self, handler_input):\n # type: (HandlerInput) -> Response\n \n previous_solution = self.get_previous_solution(handler_input)\n \n speak_output = previous_solution\n\n return (\n handler_input.response_builder\n .speak(speak_output)\n # .ask(\"add a reprompt if you want to keep the session open for the user to respond\")\n .response\n )\n\nclass HelpIntentHandler(AbstractRequestHandler):\n \"\"\"Handler for Help Intent.\"\"\"\n def can_handle(self, handler_input):\n # type: (HandlerInput) -> bool\n return ask_utils.is_intent_name(\"AMAZON.HelpIntent\")(handler_input)\n\n def handle(self, handler_input):\n # type: (HandlerInput) -> Response\n speak_output = \"You can ask me to solve an anagram by saying, solve and then listing each letter or you can say repeat solution to hear an answer again\"\n\n return (\n handler_input.response_builder\n .speak(speak_output)\n .ask(speak_output)\n .response\n )\n\n\nclass CancelOrStopIntentHandler(AbstractRequestHandler):\n \"\"\"Single handler for Cancel and Stop Intent.\"\"\"\n def can_handle(self, handler_input):\n # type: (HandlerInput) -> bool\n return (ask_utils.is_intent_name(\"AMAZON.CancelIntent\")(handler_input) or\n ask_utils.is_intent_name(\"AMAZON.StopIntent\")(handler_input))\n\n def handle(self, handler_input):\n # type: (HandlerInput) -> Response\n speak_output = \"Goodbye!\"\n\n return (\n handler_input.response_builder\n .speak(speak_output)\n .response\n )\n\n\nclass SessionEndedRequestHandler(AbstractRequestHandler):\n \"\"\"Handler for Session End.\"\"\"\n def can_handle(self, handler_input):\n # type: (HandlerInput) -> bool\n return ask_utils.is_request_type(\"SessionEndedRequest\")(handler_input)\n\n def handle(self, handler_input):\n # type: (HandlerInput) -> Response\n\n # Any cleanup logic goes here.\n\n return handler_input.response_builder.response\n\n\nclass IntentReflectorHandler(AbstractRequestHandler):\n \"\"\"The intent reflector is used for interaction model testing and debugging.\n It will simply repeat the intent the user said. You can create custom handlers\n for your intents by defining them above, then also adding them to the request\n handler chain below.\n \"\"\"\n def can_handle(self, handler_input):\n # type: (HandlerInput) -> bool\n return ask_utils.is_request_type(\"IntentRequest\")(handler_input)\n\n def handle(self, handler_input):\n # type: (HandlerInput) -> Response\n intent_name = ask_utils.get_intent_name(handler_input)\n speak_output = \"You just triggered \" + intent_name + \".\"\n\n return (\n handler_input.response_builder\n .speak(speak_output)\n # .ask(\"add a reprompt if you want to keep the session open for the user to respond\")\n .response\n )\n\n\nclass CatchAllExceptionHandler(AbstractExceptionHandler):\n \"\"\"Generic error handling to capture any syntax or routing errors. If you receive an error\n stating the request handler chain is not found, you have not implemented a handler for\n the intent being invoked or included it in the skill builder below.\n \"\"\"\n def can_handle(self, handler_input, exception):\n # type: (HandlerInput, Exception) -> bool\n return True\n\n def handle(self, handler_input, exception):\n # type: (HandlerInput, Exception) -> Response\n logger.error(exception, exc_info=True)\n\n speak_output = \"Sorry, I had trouble doing what you asked. Please try again.\"\n\n return (\n handler_input.response_builder\n .speak(speak_output)\n .ask(speak_output)\n .response\n )\n\n# The SkillBuilder object acts as the entry point for your skill, routing all request and response\n# payloads to the handlers above. Make sure any new handlers or interceptors you've\n# defined are included below. The order matters - they're processed top to bottom.\n\n\nsb = CustomSkillBuilder(persistence_adapter=s3_adapter)\n\nsb.add_request_handler(LaunchRequestHandler())\nsb.add_request_handler(AnagramSolverIntentHandler())\nsb.add_request_handler(RepeatSolutionIntentHandler())\nsb.add_request_handler(HelpIntentHandler())\nsb.add_request_handler(CancelOrStopIntentHandler())\nsb.add_request_handler(SessionEndedRequestHandler())\nsb.add_request_handler(IntentReflectorHandler()) # make sure IntentReflectorHandler is last so it doesn't override your custom intent handlers\n\nsb.add_exception_handler(CatchAllExceptionHandler())\n\nlambda_handler = sb.lambda_handler()","sub_path":"lambda/lambda_function.py","file_name":"lambda_function.py","file_ext":"py","file_size_in_byte":9519,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"107233007","text":"import machine, time\n\nmdays = [0,31,29,31,30,31,30,31,31,30,31,30,31]\nrtcBase=0x4005c000\natomicBSet=0x2000\n\nprint(\"The current date is: %2.2i/%2.2i/%4.4i\" % (time.localtime()[1], time.localtime()[2], time.localtime()[0]))\nnewDate = input(\"Enter the new date (mm-dd-yy): \")\nif newDate != \"\":\n inDate = newDate.split('-')\n\n if len(inDate) != 3:\n print(\"Bad Date format\")\n elif int(inDate[0]) not in range(1,13):\n print(\"Invalid month entered (1-12)\")\n elif int(inDate[1]) not in range(1,mdays[int(inDate[0])]+1):\n print(\"invalid day entered (1-\",mdays[int(inDate[0])],\")\")\n elif int(inDate[2]) not in range(21,32):\n print(\"invalid year entered (21-31)\")\n else:\n machine.mem32[rtcBase+4] = ((2000+int(inDate[2])) << 12) | (int(inDate[0]) << 8) | int(inDate[1])\n machine.mem32[rtcBase+atomicBSet+0xc] = 0x10","sub_path":"mpython/setdate.py","file_name":"setdate.py","file_ext":"py","file_size_in_byte":863,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"266028266","text":"def LRUCache(max_size):\n \"\"\"A simple dict-based LRU cache\n The cached function must:\n - Have no kwargs\n - Have only hashable args\n - If the decorated function is passed an unhashable arg, a TypeError\n will be raised\n - Be idempotent (be without side effects)\n - Otherwise the cache could become invalid\n Usage:\n @LRUCache(max_size=50)\n def to_be_cached(foo, bar):\n ... some computation ...\n return retval\n \"\"\"\n cache = {}\n cache_keys = []\n\n def lrucache_dec(fn):\n def cached_fn(*args):\n # args is a tuple, so it can be used as a dict key\n if args in cache:\n # Set args as most-recently-used\n del cache_keys[cache_keys.index(args)]\n cache_keys.append(args)\n return cache[args]\n\n # If fn(*args) raises an exception, the cache will not be affected,\n # so no special measures need be taken.\n retval = fn(*args)\n\n # Add to the cache and set as most-recently-used\n cache[args] = retval\n cache_keys.append(args)\n\n # Prune the cache if necessary\n if len(cache_keys) > max_size:\n del cache[cache_keys[0]]\n del cache_keys[0]\n\n return retval\n return cached_fn\n return lrucache_dec\n","sub_path":"Part1/lru.py","file_name":"lru.py","file_ext":"py","file_size_in_byte":1387,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"433149025","text":"from django import forms\nfrom django.contrib.auth.forms import UserCreationForm\nfrom django.contrib.auth.models import User\nfrom django.contrib.admin import widgets\nfrom accounts.models import UserProfile\n\n\n\nclass SignupForm(UserCreationForm):\n email = forms.EmailField(required=True)\n class Meta:\n model = User\n fields = (\"username\", \"first_name\", \"last_name\", \"email\")\n\n def save(self, commit=True):\n user = super(SignupForm, self).save(commit=False)\n user.username = self.cleaned_data.get('username')\n user.first_name = self.cleaned_data.get('first_name')\n user.last_name = self.cleaned_data.get('last_name')\n user.email = self.cleaned_data.get('email')\n if commit:\n user.save()\n return user\n\n def clean_email(self):\n # Get the email\n email = self.cleaned_data.get('email')\n # Check to see if any users already exist with this email as a username.\n try:\n match = User.objects.get(email=email)\n except User.DoesNotExist:\n # Unable to find a user, this is fine\n return email\n # A user was found with this as a username, raise an error.\n raise forms.ValidationError('This email address is already exist.')\n\n\n","sub_path":"test/example/accounts/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":1276,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"89099729","text":"import argparse\nimport subprocess\n\ndef reportTo(nombre, email):\n texto = \"Reportando a {}\".format(nombre)\n\n # Say that we are sending a report\n cmd = 'say \"{}\"'.format(texto)\n subprocess.Popen(['/bin/bash', '-c', cmd])\n\n # Send the report via mail\n mailCmd = 'echo \"{}\" | mail -s \"New Report\" \"{}\"'.format(texto,email)\n subprocess.Popen(['/bin/bash', '-c', mailCmd])\n\n print(\"Sent report to mail {}\".format(email))\n\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser(description='Simple processing pipeline')\n parser.add_argument('-n', dest='nombre', default=\"Pepe\", help='your name')\n parser.add_argument('-e', dest='email', default=\"marc@faable.com\", help='your email')\n\n args = parser.parse_args()\n\n # Start the python script\n reportTo(args.nombre, args.email)","sub_path":"code.py","file_name":"code.py","file_ext":"py","file_size_in_byte":816,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"93871158","text":"# Copyright The Lightning AI team.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\nimport os\nfrom unittest import mock\n\nimport pytest\nimport torch\nfrom torch.nn.parallel.distributed import DistributedDataParallel\n\nimport lightning.pytorch as pl\nfrom lightning.fabric.plugins.environments import LightningEnvironment\nfrom lightning.fabric.utilities.imports import _TORCH_GREATER_EQUAL_2_0\nfrom lightning.pytorch import seed_everything, Trainer\nfrom lightning.pytorch.callbacks import Callback\nfrom lightning.pytorch.demos.boring_classes import BoringModel\nfrom lightning.pytorch.plugins import DoublePrecisionPlugin, HalfPrecisionPlugin, PrecisionPlugin\nfrom lightning.pytorch.strategies import DDPStrategy\nfrom tests_pytorch.helpers.datamodules import ClassifDataModule\nfrom tests_pytorch.helpers.runif import RunIf\nfrom tests_pytorch.helpers.simple_models import ClassificationModel\n\n\n@RunIf(min_cuda_gpus=2, standalone=True, sklearn=True)\ndef test_multi_gpu_model_ddp_fit_only(tmpdir):\n dm = ClassifDataModule()\n model = ClassificationModel()\n trainer = Trainer(default_root_dir=tmpdir, max_epochs=1, accelerator=\"gpu\", devices=2, strategy=\"ddp\")\n trainer.fit(model, datamodule=dm)\n\n\n@RunIf(min_cuda_gpus=2, standalone=True, sklearn=True)\ndef test_multi_gpu_model_ddp_test_only(tmpdir):\n dm = ClassifDataModule()\n model = ClassificationModel()\n trainer = Trainer(default_root_dir=tmpdir, max_epochs=1, accelerator=\"gpu\", devices=2, strategy=\"ddp\")\n trainer.test(model, datamodule=dm)\n\n\n@RunIf(min_cuda_gpus=2, standalone=True, sklearn=True)\ndef test_multi_gpu_model_ddp_fit_test(tmpdir):\n seed_everything(4321)\n dm = ClassifDataModule()\n model = ClassificationModel()\n trainer = Trainer(default_root_dir=tmpdir, max_epochs=1, accelerator=\"gpu\", devices=2, strategy=\"ddp\")\n trainer.fit(model, datamodule=dm)\n result = trainer.test(model, datamodule=dm)\n\n for out in result:\n assert out[\"test_acc\"] > 0.7\n\n\n@RunIf(skip_windows=True)\n@mock.patch(\"torch.cuda.set_device\")\n@mock.patch(\"lightning.pytorch.accelerators.cuda._check_cuda_matmul_precision\")\n@mock.patch(\"lightning.pytorch.accelerators.cuda._clear_cuda_memory\")\ndef test_ddp_torch_dist_is_available_in_setup(_, __, ___, cuda_count_1, mps_count_0, tmpdir):\n \"\"\"Test to ensure torch distributed is available within the setup hook using ddp.\"\"\"\n\n class TestModel(BoringModel):\n def setup(self, stage: str) -> None:\n assert torch.distributed.is_initialized()\n raise SystemExit()\n\n model = TestModel()\n trainer = Trainer(\n default_root_dir=tmpdir,\n fast_dev_run=True,\n strategy=DDPStrategy(process_group_backend=\"gloo\"),\n accelerator=\"gpu\",\n devices=1,\n )\n with pytest.raises(SystemExit):\n trainer.fit(model)\n\n\n@RunIf(min_cuda_gpus=2, standalone=True)\n@pytest.mark.parametrize(\"precision\", [\"16-mixed\", \"32-true\"])\ndef test_ddp_wrapper(tmpdir, precision):\n \"\"\"Test parameters to ignore are carried over for DDP.\"\"\"\n\n class WeirdModule(torch.nn.Module):\n def _save_to_state_dict(self, destination, prefix, keep_vars):\n return {\"something\": \"something\"}\n\n class CustomModel(BoringModel):\n def __init__(self):\n super().__init__()\n self.weird_module = WeirdModule()\n\n # should be skip.\n self._ddp_params_and_buffers_to_ignore = [\"something\"]\n\n class CustomCallback(Callback):\n def on_train_start(self, trainer: \"pl.Trainer\", pl_module: \"pl.LightningModule\") -> None:\n assert isinstance(trainer.strategy.model, DistributedDataParallel)\n expected = [\"something\"]\n assert (\n trainer.strategy.model.parameters_to_ignore == set(expected) if _TORCH_GREATER_EQUAL_2_0 else expected\n )\n assert trainer.strategy.model.module._ddp_params_and_buffers_to_ignore == expected\n\n model = CustomModel()\n trainer = Trainer(\n default_root_dir=tmpdir,\n fast_dev_run=True,\n precision=precision,\n strategy=\"ddp\",\n accelerator=\"gpu\",\n devices=2,\n callbacks=CustomCallback(),\n enable_progress_bar=False,\n enable_model_summary=False,\n )\n trainer.fit(model)\n\n\n@pytest.mark.parametrize(\n (\"process_group_backend\", \"device_str\", \"expected_process_group_backend\"),\n [\n pytest.param(\"foo\", \"cpu\", \"foo\"),\n pytest.param(\"foo\", \"cuda:0\", \"foo\"),\n pytest.param(None, \"cuda:0\", \"nccl\"),\n pytest.param(None, \"cpu\", \"gloo\"),\n ],\n)\ndef test_ddp_process_group_backend(process_group_backend, device_str, expected_process_group_backend):\n \"\"\"Test settings for process group backend.\"\"\"\n\n class MockDDPStrategy(DDPStrategy):\n def __init__(self, root_device, process_group_backend):\n self._root_device = root_device\n super().__init__(process_group_backend=process_group_backend)\n\n @property\n def root_device(self):\n return self._root_device\n\n strategy = MockDDPStrategy(process_group_backend=process_group_backend, root_device=torch.device(device_str))\n assert strategy._get_process_group_backend() == expected_process_group_backend\n\n\n@pytest.mark.parametrize(\n (\"strategy_name\", \"expected_ddp_kwargs\"),\n [\n (\"ddp\", {}),\n (\"ddp_find_unused_parameters_false\", {\"find_unused_parameters\": False}),\n (\"ddp_find_unused_parameters_true\", {\"find_unused_parameters\": True}),\n ],\n)\ndef test_ddp_kwargs_from_registry(strategy_name, expected_ddp_kwargs, mps_count_0):\n trainer = Trainer(strategy=strategy_name)\n assert trainer.strategy._ddp_kwargs == expected_ddp_kwargs\n\n\n@RunIf(min_cuda_gpus=2)\n@pytest.mark.parametrize(\n (\"precision_plugin\", \"expected_dtype\"),\n [\n (PrecisionPlugin(), torch.float32),\n (DoublePrecisionPlugin(), torch.float64),\n (HalfPrecisionPlugin(\"16-true\"), torch.float16),\n pytest.param(HalfPrecisionPlugin(\"bf16-true\"), torch.bfloat16, marks=RunIf(bf16_cuda=True)),\n ],\n)\n@mock.patch.dict(os.environ, {\"LOCAL_RANK\": \"1\"})\ndef test_tensor_init_context(precision_plugin, expected_dtype):\n \"\"\"Test that the module under the init-context gets moved to the right device and dtype.\"\"\"\n parallel_devices = [torch.device(\"cuda\", 0), torch.device(\"cuda\", 1)]\n expected_device = parallel_devices[1] if _TORCH_GREATER_EQUAL_2_0 else torch.device(\"cpu\")\n\n strategy = DDPStrategy(\n parallel_devices=parallel_devices, precision_plugin=precision_plugin, cluster_environment=LightningEnvironment()\n )\n assert strategy.local_rank == 1\n with strategy.tensor_init_context():\n module = torch.nn.Linear(2, 2)\n assert module.weight.device == module.bias.device == expected_device\n assert module.weight.dtype == module.bias.dtype == expected_dtype\n","sub_path":"tests/tests_pytorch/strategies/test_ddp.py","file_name":"test_ddp.py","file_ext":"py","file_size_in_byte":7335,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"56545608","text":"from collections import deque\r\n\r\ndef numSquares(n):\r\n squares = []\r\n for i in range(1, n+1):\r\n squares.append(i*i)\r\n \r\n unique = set()\r\n queue = deque([n])\r\n\r\n levels = 0\r\n\r\n while queue:\r\n levels += 1\r\n size = len(queue)\r\n for i in range(size):\r\n current = queue.popleft()\r\n for element in squares:\r\n value = current - element\r\n if value < 0:\r\n break\r\n if value == 0:\r\n return levels\r\n if value in unique:\r\n continue\r\n queue.append(value)\r\n unique.add(value)\r\n return -1","sub_path":"bfs_numsquares.py","file_name":"bfs_numsquares.py","file_ext":"py","file_size_in_byte":692,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"221967395","text":"'''\n 1904 01타일\n 알고리즘:\n 1. N에 따라 경우의 수는 피보나치 수열을 이룬다\n 2. * 주의 : 큰 수를 for문으로 돌때 나머지 연산 필요하면 해주면 메모리 초과 안난다!\n'''\nN = int(input())\ndp = [0] * 1000001\n\ndp[1] = 1\ndp[2] = 2\nfor i in range(3, N+1):\n dp[i] = (dp[i-1] + dp[i-2]) % 15746\n\nprint(dp[N])","sub_path":"1904.py","file_name":"1904.py","file_ext":"py","file_size_in_byte":364,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"211505801","text":"import tensorflow as tf\nimport numpy as np\n\nfrom tensorflow.examples.tutorials.mnist import input_data\nmnist = input_data.read_data_sets(\".\", one_hot=True, reshape=False)\n\nlearning_rate = 0.00001\nepochs = 10\nbatch_size = 128\n\n# number of samples to calculate validation and accuracy\n# decrease this if you're running out of memory\ntest_valid_size = 256\n\n# network Parameters\nn_classes = 10 # MNIST total classes (0-9 digits)\ndropout = 0.75 # dropout (probability to keep units)\n\n\nweights = {\"wc1\":tf.Variable(tf.truncated_normal([5,5,1,32])),\n \"wc2\":tf.Variable(tf.truncated_normal([5,5,32,64]),\n ),\n \"wd1\":tf.Variable(tf.truncated_normal([7*7*32,1024])),\n \"wd2\":tf.Variable(tf.truncated_normal([1024,n_classes]))}\n\nbiases = {\"wb1\":tf.zeros(32),\n \"wb2\":tf.zeros(64),\n \"wd1\":tf.zeros(1024),\n \"wd2\":tf.zeros(n_classes)}\n\nconv_1 = tf.nn.conv2d(input,weights['wc1'],strides=2,padding=\"SAME\")\nconv_1 = tf.nn.bias_add(conv_1,biases[\"wb1\"])\nconv_1 = tf.nn.max_pool(conv_1,ksize=2,strides=2,padding=\"SAME\")\nconv_2 = tf.nn.conv2d(conv_1,weights['wc2'],strides=2,padding=\"SAME\")\nconv_2 = tf.nn.bias_add(conv_2,biases[\"wb2\"])\nconv_2 = tf.nn.max_pool(conv_2,ksize=2,strides=2,padding=\"SAME\")\nfc1 = tf.reshape(conv_2,[-1,weights[\"wd1\"].get_shape().as_list()[0]])\nfc1 = tf.add(tf.matmul(fc1,weights['wd1']),biases['wd1'])\nfc1 = tf.nn.relu(fc1)\nfc1 = tf.nn.dropout(fc1,dropout)\nout = tf.add(tf.matmul(fc1,weights['wd2']),biases['wd2'])\n\nx = tf.placeholder(tf.float32, [None, 28, 28, 1])\ny = tf.placeholder(tf.float32, [None, n_classes])\nkeep_prob = tf.placeholder(tf.float32)\n\n# Model\n\n# Define loss and optimizer\ncost = tf.reduce_mean(\\\n tf.nn.softmax_cross_entropy_with_logits(logits=out, labels=y))\noptimizer = tf.train.GradientDescentOptimizer(learning_rate=learning_rate)\\\n .minimize(cost)\n\n# Accuracy\ncorrect_pred = tf.equal(tf.argmax(out, 1), tf.argmax(y, 1))\naccuracy = tf.reduce_mean(tf.cast(correct_pred, tf.float32))\n\n# Initializing the variables\ninit = tf. global_variables_initializer()\n\n# Launch the graph\nwith tf.Session() as sess:\n sess.run(init)\n\n for epoch in range(epochs):\n for batch in range(mnist.train.num_examples//batch_size):\n batch_x, batch_y = mnist.train.next_batch(batch_size)\n sess.run(optimizer, feed_dict={\n x: batch_x,\n y: batch_y,\n keep_prob: dropout})\n\n # Calculate batch loss and accuracy\n loss = sess.run(cost, feed_dict={\n x: batch_x,\n y: batch_y,\n keep_prob: 1.})\n valid_acc = sess.run(accuracy, feed_dict={\n x: mnist.validation.images[:test_valid_size],\n y: mnist.validation.labels[:test_valid_size],\n keep_prob: 1.})\n\n print('Epoch {:>2}, Batch {:>3} -'\n 'Loss: {:>10.4f} Validation Accuracy: {:.6f}'.format(\n epoch + 1,\n batch + 1,\n loss,\n valid_acc))\n\n # Calculate Test Accuracy\n test_acc = sess.run(accuracy, feed_dict={\n x: mnist.test.images[:test_valid_size],\n y: mnist.test.labels[:test_valid_size],\n keep_prob: 1.})\n print('Testing Accuracy: {}'.format(test_acc))\n\n","sub_path":"mnist.py","file_name":"mnist.py","file_ext":"py","file_size_in_byte":3313,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"510609698","text":"import db_tool\nimport DataModel\nfrom sklearn.feature_extraction.text import TfidfVectorizer\n\nsession = db_tool.Session()\nmodels = session.query_all(DataModel.JianggeWeiboWordcut)\ncorpus = []\n\nfor model in models:\n model: DataModel.JianggeWeiboWordcut\n weibo_line = model.post_text.replace(';', ' ')\n corpus.append((weibo_line))\nvectorizer = TfidfVectorizer()\ntfidf_matrix = vectorizer.fit_transform(corpus)\nwords = vectorizer.get_feature_names()\nfor i in range(len(words)):\n tuple_list = []\n for j in range(len(words)):\n word = words[j]\n tfidf_result = tfidf_matrix[i, j]\n tuple_list.append((word, tfidf_result))\n sorted_tuple_list = sorted(tuple_list, key=lambda o: o[1], reverse=True)\n # print(sorted_tuple_list[:3][0])\n # 排序使用的是元组的list,需要取出每个元素的第一个位置,组成一个新字符串的list,然后再join; 使用循环或者map函数\n result = ';'.join(list(map(lambda o: o[0], sorted_tuple_list[:3])))\n # print(result)\n new_model = DataModel.JianggeWeiboTfidfFilter()\n db_tool.model_setter(models[i], new_model)\n new_model.sid = models[i].sid\n new_model.tfidf = result\n session.db_writer(new_model)\n","sub_path":"tfidf_filter.py","file_name":"tfidf_filter.py","file_ext":"py","file_size_in_byte":1213,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"569522309","text":"\"\"\"classes for pytorch machine learning models in opensoundscape\n\nFor tutorials, see notebooks on opensoundscape.org\n\"\"\"\nfrom pathlib import Path\nimport warnings\nimport copy\nimport os\nimport types\nimport yaml\n\nimport numpy as np\nimport pandas as pd\n\nimport torch\nimport torch.nn.functional as F\n\nimport opensoundscape\nfrom opensoundscape.ml import cnn_architectures\nfrom opensoundscape.ml.utils import (\n BaseModule,\n apply_activation_layer,\n)\nfrom opensoundscape.preprocess.preprocessors import SpectrogramPreprocessor\nfrom opensoundscape.ml.loss import (\n BCEWithLogitsLoss_hot,\n CrossEntropyLoss_hot,\n ResampleLoss,\n)\nfrom opensoundscape.ml.safe_dataset import SafeDataset\nfrom opensoundscape.ml.datasets import AudioFileDataset, AudioSplittingDataset\nfrom opensoundscape.ml.cnn_architectures import inception_v3\nfrom opensoundscape.metrics import (\n predict_multi_target_labels,\n predict_single_target_labels,\n single_target_metrics,\n multi_target_metrics,\n)\nfrom opensoundscape.sample import collate_samples\nfrom opensoundscape.utils import identity\nfrom opensoundscape.logging import wandb_table\n\nfrom opensoundscape.ml.cam import CAM\nimport pytorch_grad_cam\nfrom pytorch_grad_cam.utils.model_targets import ClassifierOutputTarget\n\n\nclass CNN(BaseModule):\n \"\"\"\n Generic CNN Model with .train(), .predict(), and .save()\n\n flexible architecture, optimizer, loss function, parameters\n\n for tutorials and examples see opensoundscape.org\n\n Args:\n architecture:\n *EITHER* a pytorch model object (subclass of torch.nn.Module),\n for example one generated with the `cnn_architectures` module\n *OR* a string matching one of the architectures listed by\n cnn_architectures.list_architectures(), eg 'resnet18'.\n - If a string is provided, uses default parameters\n (including pretrained weights, `weights=\"DEFAULT\"`)\n Note: if num channels != 3, copies weights from original\n channels by averaging (<3 channels) or recycling (>3 channels)\n classes:\n list of class names. Must match with training dataset classes if training.\n single_target:\n - True: model expects exactly one positive class per sample\n - False: samples can have any number of positive classes\n [default: False]\n preprocessor_class: class of Preprocessor object\n sample_shape: tuple of height, width, channels for created sample\n [default: (224,224,3)] #TODO: consider changing to (ch,h,w) to match torchww\n\n \"\"\"\n\n def __init__(\n self,\n architecture,\n classes,\n sample_duration,\n single_target=False,\n preprocessor_class=SpectrogramPreprocessor,\n sample_shape=(224, 224, 3),\n ):\n super(CNN, self).__init__()\n\n self.name = \"CNN\"\n\n # model characteristics\n self.current_epoch = 0\n self.classes = classes\n self.single_target = single_target # if True: predict only class w max score\n self.opensoundscape_version = opensoundscape.__version__\n\n # number of samples to preprocess and log to wandb during train/predict\n self.wandb_logging = dict(\n n_preview_samples=8, # before train/predict, log n random samples\n top_samples_classes=None, # specify list of classes to see top samples from\n n_top_samples=3, # after prediction, log n top scoring samples per class\n # logs histograms of params & grads every n batches;\n watch_freq=10, # use None for no logging of params & grads\n )\n self.loss_fn = None\n self.train_loader = None\n self.scheduler = None\n\n # to use a custom DataLoader or Sampler, change these attributes\n # to the custom class (init must take same arguments)\n self.train_dataloader_cls = torch.utils.data.DataLoader\n self.inference_dataloader_cls = torch.utils.data.DataLoader\n\n ### architecture ###\n # can be a pytorch CNN such as Resnet18 or a custom object\n # must have .forward(), .train(), .eval(), .to(), .state_dict()\n # for convenience, also allows user to provide string matching\n # a key from cnn_architectures.ARCH_DICT\n num_channels = sample_shape[2]\n if type(architecture) == str:\n assert architecture in cnn_architectures.list_architectures(), (\n f\"architecture must be a pytorch model object or string matching \"\n f\"one of cnn_architectures.list_architectures() options. Got {architecture}\"\n )\n self.architecture_name = architecture\n architecture = cnn_architectures.ARCH_DICT[architecture](\n len(classes), num_channels=num_channels\n )\n else:\n assert issubclass(\n type(architecture), torch.nn.Module\n ), \"architecture must be a string or an instance of a subclass of torch.nn.Module\"\n if num_channels != 3:\n warnings.warn(\n f\"Make sure your architecture expects the number of channels in \"\n f\"your input samples ({num_channels}). \"\n f\"Pytorch architectures expect 3 channels by default.\"\n )\n self.architecture_name = str(type(architecture))\n self.network = architecture\n\n ### network device ###\n # automatically gpu (default is 'cuda:0') if available\n # can override after init, eg model.device='cuda:1'\n # network and samples are moved to gpu during training/inference\n # devices could be 'cuda:0', torch.device('cuda'), torch.device('cpu')\n if torch.cuda.is_available():\n self.device = torch.device(\"cuda\")\n else:\n self.device = torch.device(\"cpu\")\n\n ### sample loading/preprocessing ###\n # preprocessor will have attributes .sample_duration and .out_shape\n self.preprocessor = preprocessor_class(\n sample_duration=sample_duration, out_shape=sample_shape\n )\n\n ### loss function ###\n if self.single_target: # use cross entropy loss by default\n self.loss_cls = CrossEntropyLoss_hot\n else: # for multi-target, use binary cross entropy\n self.loss_cls = BCEWithLogitsLoss_hot\n\n ### training parameters ###\n # optimizer\n self.opt_net = None # don't set directly. initialized during training\n self.optimizer_cls = torch.optim.SGD # or torch.optim.Adam, etc\n\n # instead of putting \"params\" key here, we only add it during\n # _init_optimizer, just before initializing the optimizers\n # this avoids an issue when re-loading a model of\n # having the wrong .parameters() list\n self.optimizer_params = {\n # \"params\": self.network.parameters(),\n \"lr\": 0.01,\n \"momentum\": 0.9,\n \"weight_decay\": 0.0005,\n }\n\n # lr_scheduler\n self.lr_update_interval = 10 # update learning rates every # epochs\n self.lr_cooling_factor = 0.7 # multiply learning rates by # on each update\n\n ### metrics ###\n self.prediction_threshold = 0.5\n # override self.eval() to change what metrics are\n # computed and displayed during training/validation\n\n ### Logging ###\n self.log_file = None # specify a path to save output to a text file\n self.logging_level = 1 # 0 for nothing, 1,2,3 for increasing logged info\n self.verbose = 1 # 0 for nothing, 1,2,3 for increasing printed output\n\n # dictionaries to store accuracy metrics & loss for each epoch\n self.train_metrics = {}\n self.valid_metrics = {}\n self.loss_hist = {} # could add TensorBoard tracking\n\n def _log(self, message, level=1):\n txt = str(message)\n if self.logging_level >= level and self.log_file is not None:\n with open(self.log_file, \"a\") as logfile:\n logfile.write(txt + \"\\n\")\n if self.verbose >= level:\n print(txt)\n\n def _init_optimizer(self):\n \"\"\"initialize an instance of self.optimizer\n\n This function is called during .train() so that the user\n has a chance to swap/modify the optimizer before training.\n\n To modify the optimizer, change the value of\n self.optimizer_cls and/or self.optimizer_params\n prior to calling .train().\n \"\"\"\n param_dict = self.optimizer_params\n param_dict[\"params\"] = self.network.parameters()\n return self.optimizer_cls([param_dict])\n\n def _init_loss_fn(self):\n \"\"\"initialize an instance of self.loss_cls\n\n This function is called during .train() so that the user\n has a chance to change the loss function before training.\n \"\"\"\n self.loss_fn = self.loss_cls()\n\n def _set_train(self, train_df, batch_size, num_workers, raise_errors):\n \"\"\"Prepare network for training on train_df\n\n Args:\n batch_size: number of training files to load/process before\n re-calculating the loss function and backpropagation\n num_workers: parallelization (number of cores or cpus)\n raise_errors: if True, raise errors when loading samples\n if False, skip samples that throw errors\n\n Effects:\n Sets up the optimization, loss function, and network\n \"\"\"\n\n ###########################\n # Move network to device #\n ###########################\n self.network.to(self.device)\n\n ######################\n # Dataloader setup #\n ######################\n train_dataset = AudioFileDataset(train_df, self.preprocessor)\n train_dataset.bypass_augmentations = False\n\n # With \"substitute\" behavior, SafeDataset loads a new sample if\n # loading a sample raises an Exception. \"raise\" raises the Exception\n # indices of bad samples are appended to SafeDataset._invalid_indices\n invalid_sample_behavior = \"raise\" if raise_errors else \"substitute\"\n train_safe_dataset = SafeDataset(\n train_dataset, invalid_sample_behavior=invalid_sample_behavior\n )\n\n # train_loader samples batches of images + labels from training set\n self.train_loader = self.train_dataloader_cls(\n train_safe_dataset,\n batch_size=batch_size,\n num_workers=num_workers,\n shuffle=True, # SHUFFLE SAMPLES because we are training\n # use pin_memory=True when loading files on CPU and training on GPU\n pin_memory=False if self.device == torch.device(\"cpu\") else True,\n collate_fn=identity,\n )\n\n ###########################\n # Setup loss function #\n ###########################\n self._init_loss_fn()\n\n ######################\n # Optimization setup #\n ######################\n\n # Setup optimizer parameters for each network component\n # Note: we re-create bc the user may have changed self.optimizer_cls\n # If optimizer already exists, keep the same state dict\n # (for instance, user may be resuming training w/saved state dict)\n if self.opt_net is not None:\n optim_state_dict = self.opt_net.state_dict()\n self.opt_net = self._init_optimizer()\n self.opt_net.load_state_dict(optim_state_dict)\n else:\n self.opt_net = self._init_optimizer()\n\n # Set up learning rate cooling schedule\n self.scheduler = torch.optim.lr_scheduler.StepLR(\n self.opt_net,\n step_size=self.lr_update_interval,\n gamma=self.lr_cooling_factor,\n last_epoch=self.current_epoch - 1,\n )\n\n def _train_epoch(self, train_loader, wandb_session=None):\n \"\"\"perform forward pass, loss, and backpropagation for one epoch\n\n If wandb_session is passed, logs progress to wandb run\n\n Args:\n train_loader: DataLoader object to create samples\n wandb_session: a wandb session to log to\n - pass the value returned by wandb.init() to progress log to a\n Weights and Biases run\n - if None, does not log to wandb\n\n Returns: (targets, predictions, scores) on training files\n \"\"\"\n self.network.train()\n\n total_tgts = []\n total_preds = []\n total_scores = []\n batch_loss = []\n\n for batch_idx, samples in enumerate(train_loader):\n # load a batch of images and labels from the train loader\n # all augmentation occurs in the Preprocessor (train_loader)\n # we collate here rather than in the DataLoader so that\n # we can still access the AudioSamples and thier information\n batch_data = collate_samples(samples)\n batch_tensors = batch_data[\"samples\"].to(self.device)\n batch_labels = batch_data[\"labels\"].to(self.device)\n if len(self.classes) > 1: # squeeze one dimension [1,2] -> [1,1]\n batch_labels = batch_labels.squeeze(1)\n\n ####################\n # Forward and loss #\n ####################\n\n # forward pass: feature extractor and classifier\n logits = self.network(batch_tensors)\n\n # save targets and predictions\n total_scores.append(logits.detach().cpu().numpy())\n total_tgts.append(batch_labels.detach().cpu().numpy())\n\n # generate boolean predictions\n if self.single_target: # predict highest scoring class only\n batch_preds = predict_single_target_labels(scores=logits)\n else: # multi-target: predict 0 or 1 based on a fixed threshold\n batch_preds = predict_multi_target_labels(\n scores=torch.sigmoid(logits), threshold=self.prediction_threshold\n )\n total_preds.append(batch_preds.detach().int().cpu().numpy())\n\n # calculate loss\n loss = self.loss_fn(logits, batch_labels)\n\n # save loss for each batch; later take average for epoch\n\n batch_loss.append(loss.detach().cpu().numpy())\n\n #############################\n # Backward and optimization #\n #############################\n # zero gradients for optimizer\n self.opt_net.zero_grad()\n # backward pass: calculate the gradients\n loss.backward()\n # update the network using the gradients*lr\n self.opt_net.step()\n\n ###########\n # Logging #\n ###########\n # log basic train info (used to print every batch)\n if batch_idx % self.log_interval == 0:\n # show some basic progress metrics during the epoch\n N = len(train_loader)\n self._log(\n f\"Epoch: {self.current_epoch} \"\n f\"[batch {batch_idx}/{N}, {100 * batch_idx / N :.2f}%] \"\n )\n\n # Log the Jaccard score and Hamming loss, and Loss function\n epoch_loss_avg = np.mean(batch_loss)\n self._log(f\"\\tDistLoss: {epoch_loss_avg:.3f}\")\n\n # Evaluate with model's eval function\n tgts = batch_labels.int().detach().cpu().numpy()\n # preds = batch_preds.int().detach().cpu().numpy()\n scores = logits.int().detach().cpu().numpy()\n self.eval(tgts, scores, logging_offset=-1)\n\n # update learning parameters each epoch\n self.scheduler.step()\n\n # save the loss averaged over all batches\n self.loss_hist[self.current_epoch] = np.mean(batch_loss)\n\n if wandb_session is not None:\n wandb_session.log({\"loss\": np.mean(batch_loss)})\n\n # return targets, preds, scores\n total_tgts = np.concatenate(total_tgts, axis=0)\n total_preds = np.concatenate(total_preds, axis=0)\n total_scores = np.concatenate(total_scores, axis=0)\n\n return total_tgts, total_preds, total_scores\n\n def _generate_wandb_config(self):\n # create a dictinoary of parameters to save for this run\n wandb_config = dict(\n architecture=self.architecture_name,\n sample_duration=self.preprocessor.sample_duration,\n cuda_device_count=torch.cuda.device_count(),\n mps_available=torch.backends.mps.is_available(),\n classes=self.classes,\n single_target=self.single_target,\n opensoundscape_version=self.opensoundscape_version,\n )\n if \"weight_decay\" in self.optimizer_params:\n wandb_config[\"l2_regularization\"] = self.optimizer_params[\"weight_decay\"]\n else:\n wandb_config[\"l2_regularization\"] = \"n/a\"\n\n if \"lr\" in self.optimizer_params:\n wandb_config[\"learning_rate\"] = self.optimizer_params[\"lr\"]\n else:\n wandb_config[\"learning_rate\"] = \"n/a\"\n\n try:\n wandb_config[\"sample_shape\"] = self.preprocessor.out_shape\n except:\n wandb_config[\"sample_shape\"] = \"n/a\"\n\n return wandb_config\n\n def train(\n self,\n train_df,\n validation_df=None,\n epochs=1,\n batch_size=1,\n num_workers=0,\n save_path=\".\",\n save_interval=1, # save weights every n epochs\n log_interval=10, # print metrics every n batches\n validation_interval=1, # compute validation metrics every n epochs\n invalid_samples_log=\"./invalid_training_samples.log\",\n raise_errors=False,\n wandb_session=None,\n ):\n \"\"\"train the model on samples from train_dataset\n\n If customized loss functions, networks, optimizers, or schedulers\n are desired, modify the respective attributes before calling .train().\n\n Args:\n train_df:\n a dataframe of files and labels for training the model\n - either has index `file` or multi-index (file,start_time,end_time)\n validation_df:\n a dataframe of files and labels for evaluating the model\n [default: None means no validation is performed]\n epochs:\n number of epochs to train for\n (1 epoch constitutes 1 view of each training sample)\n batch_size:\n number of training files simultaneously passed through\n forward pass, loss function, and backpropagation\n num_workers:\n number of parallel CPU tasks for preprocessing\n Note: use 0 for single (root) process (not 1)\n save_path:\n location to save intermediate and best model objects\n [default=\".\", ie current location of script]\n save_interval:\n interval in epochs to save model object with weights [default:1]\n Note: the best model is always saved to best.model\n in addition to other saved epochs.\n log_interval:\n interval in batches to print training loss/metrics\n validation_interval:\n interval in epochs to test the model on the validation set\n Note that model will only update it's best score and save best.model\n file on epochs that it performs validation.\n invalid_samples_log:\n file path: log all samples that failed in preprocessing\n (file written when training completes)\n - if None, does not write a file\n raise_errors:\n if True, raise errors when preprocessing fails\n if False, just log the errors to unsafe_samples_log\n wandb_session: a wandb session to log to\n - pass the value returned by wandb.init() to progress log to a\n Weights and Biases run\n - if None, does not log to wandb\n For example:\n ```\n import wandb\n wandb.login(key=api_key) #find your api_key at https://wandb.ai/settings\n session = wandb.init(enitity='mygroup',project='project1',name='first_run')\n ...\n model.train(...,wandb_session=session)\n session.finish()\n ```\n\n Effects:\n If wandb_session is provided, logs progress and samples to Weights\n and Biases. A random set of training and validation samples\n are preprocessed and logged to a table. Training progress, loss,\n and metrics are also logged.\n Use self.wandb_logging dictionary to change the number of samples\n logged.\n \"\"\"\n\n ### Input Validation ###\n class_err = (\n \"Train and validation datasets must have same classes \"\n \"and class order as model object.\"\n )\n assert list(self.classes) == list(train_df.columns), class_err\n if validation_df is not None:\n assert list(self.classes) == list(validation_df.columns), class_err\n\n # Validation: warn user if no validation set\n if validation_df is None:\n warnings.warn(\n \"No validation set was provided. Model will be \"\n \"evaluated using the performance on the training set.\"\n )\n\n # Initialize attributes\n self.log_interval = log_interval\n self.save_interval = save_interval\n self.save_path = save_path\n\n # Initialize Weights and Biases (wandb) logging ###\n if wandb_session is not None:\n # update the run config with information about the model\n wandb_session.config.update(self._generate_wandb_config())\n\n # update the run config with training parameters\n wandb_session.config.update(\n dict(\n epochs=epochs,\n batch_size=batch_size,\n num_workers=num_workers,\n lr_update_interval=self.lr_update_interval,\n lr_cooling_factor=self.lr_cooling_factor,\n optimizer_cls=self.optimizer_cls,\n model_save_path=Path(save_path).resolve(),\n )\n )\n\n # use wandb.watch to log histograms of parameter and gradient values\n # value of None for log_freq means do not use wandb.watch()\n log_freq = self.wandb_logging[\"watch_freq\"]\n if log_freq is not None:\n wandb_session.watch(\n self.network, log=\"all\", log_freq=log_freq, log_graph=(True)\n )\n\n # log tables of preprocessed samples\n wandb_session.log(\n {\n \"Samples / training samples\": wandb_table(\n AudioFileDataset(\n train_df, self.preprocessor, bypass_augmentations=False\n ),\n self.wandb_logging[\"n_preview_samples\"],\n ),\n \"Samples / training samples no aug\": wandb_table(\n AudioFileDataset(\n train_df, self.preprocessor, bypass_augmentations=True\n ),\n self.wandb_logging[\"n_preview_samples\"],\n ),\n \"Samples / validation samples\": wandb_table(\n AudioFileDataset(\n validation_df, self.preprocessor, bypass_augmentations=True\n ),\n self.wandb_logging[\"n_preview_samples\"],\n ),\n }\n )\n\n ### Set Up Loss and Optimization ###\n self._set_train(train_df, batch_size, num_workers, raise_errors)\n self.best_score = 0.0\n self.best_epoch = 0\n\n ### Train ###\n\n for epoch in range(epochs):\n # 1 epoch = 1 view of each training file\n # loss fn & backpropogation occurs after each batch\n\n ### Training ###\n self._log(f\"\\nTraining Epoch {self.current_epoch}\")\n train_targets, _, train_scores = self._train_epoch(\n self.train_loader, wandb_session\n )\n\n ### Evaluate ###\n train_score, self.train_metrics[self.current_epoch] = self.eval(\n train_targets, train_scores\n )\n if wandb_session is not None:\n wandb_session.log({\"training\": self.train_metrics[self.current_epoch]})\n\n #### Validation ###\n if validation_df is not None and epoch % validation_interval == 0:\n self._log(\"\\nValidation.\")\n validation_scores = self.predict(\n validation_df,\n batch_size=batch_size,\n num_workers=num_workers,\n activation_layer=\"softmax_and_logit\"\n if self.single_target\n else None,\n split_files_into_clips=False,\n )\n validation_targets = validation_df.values\n validation_scores = validation_scores.values\n\n validation_score, self.valid_metrics[self.current_epoch] = self.eval(\n validation_targets, validation_scores\n )\n score = validation_score\n else: # Evaluate model w/train_score if no validation_df given\n score = train_score\n\n if wandb_session is not None:\n wandb_session.log(\n {\"validation\": self.valid_metrics[self.current_epoch]}\n )\n\n ### Save ###\n if (\n self.current_epoch + 1\n ) % self.save_interval == 0 or epoch == epochs - 1:\n self._log(\"Saving weights, metrics, and train/valid scores.\", level=2)\n\n self.save(f\"{self.save_path}/epoch-{self.current_epoch}.model\")\n\n # if this is the best score, update & save weights to best.model\n if score > self.best_score:\n self.best_score = score\n self.best_epoch = self.current_epoch\n self._log(\"Updating best model\", level=2)\n self.save(f\"{self.save_path}/best.model\")\n\n if wandb_session is not None:\n wandb_session.log({\"epoch\": epoch})\n self.current_epoch += 1\n\n ### Logging ###\n self._log(\"Training complete\", level=2)\n self._log(\n f\"\\nBest Model Appears at Epoch {self.best_epoch} \"\n f\"with Validation score {self.best_score:.3f}.\"\n )\n\n # warn the user if there were invalid samples (samples that failed to preprocess)\n invalid_samples = self.train_loader.dataset.report(log=invalid_samples_log)\n self._log(\n f\"{len(invalid_samples)} of {len(train_df)} total training \"\n f\"samples failed to preprocess\",\n level=2,\n )\n self._log(f\"List of invalid samples: {invalid_samples}\", level=3)\n\n def eval(self, targets, scores, logging_offset=0):\n \"\"\"compute single-target or multi-target metrics from targets and scores\n\n By default, the overall model score is \"map\" (mean average precision)\n for multi-target models (self.single_target=False) and \"f1\" (average\n of f1 score across classes) for single-target models).\n\n Override this function to use a different set of metrics.\n It should always return (1) a single score (float) used as an overall\n metric of model quality and (2) a dictionary of computed metrics\n\n Args:\n targets: 0/1 for each sample and each class\n scores: continuous values in 0/1 for each sample and class\n logging_offset: modify verbosity - for example, -1 will reduce\n the amount of printing/logging by 1 level\n \"\"\"\n\n # remove all samples with NaN for a prediction\n targets = targets[~np.isnan(scores).any(axis=1), :]\n scores = scores[~np.isnan(scores).any(axis=1), :]\n\n if len(scores) < 1:\n warnings.warn(\"Recieved empty list of predictions (or all nan)\")\n return np.nan, np.nan\n\n if self.single_target:\n metrics_dict = single_target_metrics(targets, scores)\n else:\n metrics_dict = multi_target_metrics(\n targets, scores, self.classes, self.prediction_threshold\n )\n\n # decide what to print/log:\n self._log(\"Metrics:\")\n if not self.single_target:\n self._log(f\"\\tMAP: {metrics_dict['map']:0.3f}\", level=1 - logging_offset)\n self._log(\n f\"\\tAU_ROC: {metrics_dict['au_roc']:0.3f} \", level=2 - logging_offset\n )\n self._log(\n f\"\\tJacc: {metrics_dict['jaccard']:0.3f} \"\n f\"Hamm: {metrics_dict['hamming_loss']:0.3f} \",\n level=2 - logging_offset,\n )\n self._log(\n f\"\\tPrec: {metrics_dict['precision']:0.3f} \"\n f\"Rec: {metrics_dict['recall']:0.3f} \"\n f\"F1: {metrics_dict['f1']:0.3f}\",\n level=2 - logging_offset,\n )\n\n # choose one metric to be used for the overall model evaluation\n if self.single_target:\n score = metrics_dict[\"f1\"]\n else:\n score = metrics_dict[\"map\"]\n\n return score, metrics_dict\n\n def save(\n self, path, save_train_loader=False, save_hooks=False, as_torch_dict=False\n ):\n \"\"\"save model with weights using torch.save()\n\n load from saved file with torch.load(path) or cnn.load_model(path)\n\n\n Note: saving and loading model objects across OpenSoundscape versions\n will not work properly. Instead, use .save_torch_dict and .load_torch_dict\n (but note that customizations to preprocessing, training params, etc will\n not be retained using those functions).\n\n For maximum flexibilty in further use, save the model with both .save() and\n .save_torch_dict()\n\n Args:\n path: file path for saved model object\n save_train_loader: retrain .train_loader in saved object\n [default: False]\n save_hooks: retain forward and backward hooks on modules\n [default: False] Note: True can cause issues when using\n wandb.watch()\n \"\"\"\n os.makedirs(Path(path).parent, exist_ok=True)\n\n # save a pickled model object; will not work across opso versions\n model_copy = copy.deepcopy(self)\n\n if not save_train_loader:\n try:\n delattr(model_copy, \"train_loader\")\n except AttributeError:\n pass\n\n if not save_hooks:\n # remove all forward and backward hooks on network.modules()\n from collections import OrderedDict\n\n for m in model_copy.network.modules():\n m._forward_hooks = OrderedDict()\n m._backward_hooks = OrderedDict()\n\n torch.save(model_copy, path)\n\n def save_torch_dict(self, path):\n \"\"\"save model to file for use in other opso versions\n\n WARNING: this does not save any preprocessing or augmentation\n settings or parameters, or other attributes such as the training\n parameters or loss function. It only saves architecture, weights,\n classes, sample shape, sample duration, and single_target.\n\n To save the entire pickled model object (recover all parameters and\n settings), use model.save() instead. Note that models saved with\n model.save() will not work across different versions of OpenSoundscape.\n\n To recreate the model after saving with this function, use CNN.from_torch_dict(path)\n\n Args:\n path: file path for saved model object\n\n Effects:\n saves a file using torch.save() containing model weights and other information\n \"\"\"\n\n # warn the user if the achirecture can't be re-created from the\n # string name (self.architecture_name)\n if not self.architecture_name in cnn_architectures.list_architectures():\n warnings.warn(\n f\"\"\"\\n The value of `self.architecture_name` ({self.architecture_name})\n is not an architecture that can be generated in OpenSoundscape. Using\n CNN.from_torch_dict on the saved file will cause an error. To fix this,\n you can use .save() instead of .save_torch_model, or change \n `self.architecture_name` to one of the architecture name strings listed by \n opensoundscape.ml.cnn_architectures.list_architectures()\n if this architecture is supported.\"\"\"\n )\n\n os.makedirs(Path(path).parent, exist_ok=True)\n\n # save just the basics, loses preprocessing/other settings\n torch.save(\n {\n \"weights\": self.network.state_dict(),\n \"classes\": self.classes,\n \"architecture\": self.architecture_name,\n \"sample_duration\": self.preprocessor.sample_duration,\n \"single_target\": self.single_target,\n \"sample_shape\": self.preprocessor.out_shape,\n },\n path,\n )\n\n @classmethod\n def from_torch_dict(cls, path):\n \"\"\"load a model saved using CNN.save_torch_dict()\n\n Args:\n path: path to file saved using CNN.save_torch_dict()\n\n Returns:\n new CNN instance\n\n Note: if you used .save() instead of .save_torch_dict(), load\n the model using cnn.load_model(). Note that the model object will not load properly\n across different versions of OpenSoundscape. To save and load models across\n different versions of OpenSoundscape, use .save_torch_dict(), but note that\n preprocessing and other customized settings will not be retained.\n \"\"\"\n model_dict = torch.load(path)\n state_dict = model_dict.pop(\"weights\")\n model = cls(**model_dict)\n model.network.load_state_dict(state_dict)\n return model\n\n def save_weights(self, path):\n \"\"\"save just the weights of the network\n\n This allows the saved weights to be used more flexibly than model.save()\n which will pickle the entire object. The weights are saved in a pickled\n dictionary using torch.save(self.network.state_dict())\n\n Args:\n path: location to save weights file\n \"\"\"\n torch.save(self.network.state_dict(), path)\n\n def load_weights(self, path, strict=True):\n \"\"\"load network weights state dict from a file\n\n For instance, load weights saved with .save_weights()\n in-place operation\n\n Args:\n path: file path with saved weights\n strict: (bool) see torch.load()\n \"\"\"\n self.network.load_state_dict(torch.load(path), strict=strict)\n\n def _init_inference_dataloader(\n self,\n samples,\n split_files_into_clips=True,\n overlap_fraction=0,\n final_clip=None,\n bypass_augmentations=True,\n batch_size=1,\n num_workers=0,\n raise_errors=False,\n ):\n \"\"\"Create DataLoader for inference\n\n During inference, we allow the user to pass any of 3 things to samples:\n - list of file paths\n - Dataframe with file as index\n - Dataframe with file, start_time, end_time of clips as index\n\n If file as index, default split_files_into_clips=True means that it will\n automatically determine the number of clips that can be created from the file\n (with overlap between subsequent clips based on overlap_fraction)\n\n Returns:\n DataLoader that creates lists of AudioSample objects\n \"\"\"\n assert type(samples) in (list, np.ndarray, pd.DataFrame), (\n \"`samples` must be either: \"\n \"(a) list or np.array of files, or DataFrame with (b) file as Index or \"\n \"(c) (file,start_time,end_time) as MultiIndex\"\n )\n\n # set up prediction Dataset, considering three possible cases:\n # (c1) user provided multi-index df with file,start_time,end_time of clips\n # (c2) user provided file list and wants clips to be split out automatically\n # (c3) split_files_into_clips=False -> one sample & one prediction per file provided\n if (\n type(samples) == pd.DataFrame\n and type(samples.index) == pd.core.indexes.multi.MultiIndex\n ): # c1\n prediction_dataset = AudioFileDataset(\n samples=samples, preprocessor=self.preprocessor\n )\n elif split_files_into_clips: # c2\n prediction_dataset = AudioSplittingDataset(\n samples=samples,\n preprocessor=self.preprocessor,\n overlap_fraction=overlap_fraction,\n final_clip=final_clip,\n )\n else: # c3\n prediction_dataset = AudioFileDataset(\n samples=samples, preprocessor=self.preprocessor\n )\n prediction_dataset.bypass_augmentations = bypass_augmentations\n\n ## Input Validation ##\n if len(prediction_dataset.classes) > 0 and list(self.classes) != list(\n prediction_dataset.classes\n ):\n warnings.warn(\n \"The columns of input samples df differ from `model.classes`.\"\n )\n\n if len(prediction_dataset) < 1:\n warnings.warn(\n \"prediction_dataset has zero samples. No predictions will be generated.\"\n )\n\n # If unsafe_behavior= \"substitute\", a SafeDataset will not fail on bad files,\n # but will provide a different sample! Later we go back and replace scores\n # with np.nan for the bad samples (using safe_dataset._invalid_indices)\n # this approach to error handling feels hacky\n # however, returning None would break the batching of samples\n # \"raise\" behavior will raise exceptions\n invalid_sample_behavior = \"raise\" if raise_errors else \"substitute\"\n\n safe_dataset = SafeDataset(\n prediction_dataset, invalid_sample_behavior=invalid_sample_behavior\n )\n\n # initialize the dataloader\n dataloader = self.inference_dataloader_cls(\n safe_dataset,\n batch_size=batch_size,\n num_workers=num_workers,\n shuffle=False, # DONT CHANGE the order of samples during inference!\n # use pin_memory=True when loading files on CPU and training on GPU\n pin_memory=False if self.device == torch.device(\"cpu\") else True,\n collate_fn=identity,\n )\n # add any paths that failed to generate a clip df to _invalid_samples\n dataloader.dataset._invalid_samples = dataloader.dataset._invalid_samples.union(\n prediction_dataset.invalid_samples\n )\n\n return dataloader\n\n def predict(\n self,\n samples,\n batch_size=1,\n num_workers=0,\n activation_layer=None,\n split_files_into_clips=True,\n overlap_fraction=0,\n final_clip=None,\n bypass_augmentations=True,\n invalid_samples_log=None,\n raise_errors=False,\n wandb_session=None,\n return_invalid_samples=False,\n ):\n \"\"\"Generate predictions on a dataset\n\n Choose to return any combination of scores, labels, and single-target or\n multi-target binary predictions. Also choose activation layer for scores\n (softmax, sigmoid, softmax then logit, or None). Binary predictions are\n performed post-activation layer\n\n Note: the order of returned dataframes is (scores, preds, labels)\n\n Args:\n samples:\n the files to generate predictions for. Can be:\n - a dataframe with index containing audio paths, OR\n - a dataframe with multi-index (file, start_time, end_time), OR\n - a list (or np.ndarray) of audio file paths\n batch_size:\n Number of files to load simultaneously [default: 1]\n num_workers:\n parallelization (ie cpus or cores), use 0 for current process\n [default: 0]\n activation_layer:\n Optionally apply an activation layer such as sigmoid or\n softmax to the raw outputs of the model.\n options:\n - None: no activation, return raw scores (ie logit, [-inf:inf])\n - 'softmax': scores all classes sum to 1\n - 'sigmoid': all scores in [0,1] but don't sum to 1\n - 'softmax_and_logit': applies softmax first then logit\n [default: None]\n split_files_into_clips:\n If True, internally splits and predicts on clips from longer audio files\n Otherwise, assumes each row of `samples` corresponds to one complete sample\n overlap_fraction: fraction of overlap between consecutive clips when\n predicting on clips of longer audio files. For instance, 0.5\n gives 50% overlap between consecutive clips.\n final_clip: see `opensoundscape.utils.generate_clip_times_df`\n bypass_augmentations: If False, Actions with\n is_augmentation==True are performed. Default True.\n invalid_samples_log: if not None, samples that failed to preprocess\n will be listed in this text file.\n raise_errors:\n if True, raise errors when preprocessing fails\n if False, just log the errors to unsafe_samples_log\n wandb_session: a wandb session to log to\n - pass the value returned by wandb.init() to progress log to a\n Weights and Biases run\n - if None, does not log to wandb\n return_invalid_samples: bool, if True, returns second argument, a set\n containing file paths of samples that caused errors during preprocessing\n [default: False]\n\n Returns:\n df of post-activation_layer scores\n - if return_invalid_samples is True, returns (df,invalid_samples)\n where invalid_samples is a set of file paths that failed to preprocess\n\n Effects:\n (1) wandb logging\n If wandb_session is provided, logs progress and samples to Weights\n and Biases. A random set of samples is preprocessed and logged to\n a table. Progress over all batches is logged. Afte prediction,\n top scoring samples are logged.\n Use self.wandb_logging dictionary to change the number of samples\n logged or which classes have top-scoring samples logged.\n\n (2) unsafe sample logging\n If unsafe_samples_log is not None, saves a list of all file paths that\n failed to preprocess in unsafe_samples_log as a text file\n\n Note: if loading an audio file raises a PreprocessingError, the scores\n for that sample will be np.nan\n\n \"\"\"\n\n # create dataloader to generate batches of AudioSamples\n dataloader = self._init_inference_dataloader(\n samples,\n split_files_into_clips=split_files_into_clips,\n overlap_fraction=overlap_fraction,\n final_clip=final_clip,\n bypass_augmentations=bypass_augmentations,\n batch_size=batch_size,\n num_workers=num_workers,\n raise_errors=raise_errors,\n )\n\n # Initialize Weights and Biases (wandb) logging\n if wandb_session is not None:\n # update the run config with information about the model\n wandb_session.config.update(self._generate_wandb_config())\n\n # update the run config with prediction parameters\n wandb_session.config.update(\n dict(\n batch_size=batch_size,\n num_workers=num_workers,\n activation_layer=activation_layer,\n )\n )\n\n # Log a table of preprocessed samples to wandb\n wandb_session.log(\n {\n \"Samples / Preprocessed samples\": wandb_table(\n dataloader.dataset.dataset,\n self.wandb_logging[\"n_preview_samples\"],\n )\n }\n )\n\n ### Prediction/Inference ###\n\n # move network to device\n self.network.to(self.device)\n self.network.eval()\n\n # initialize scores\n total_scores = []\n\n # disable gradient updates during inference\n with torch.set_grad_enabled(False):\n for i, samples in enumerate(dataloader):\n # load a batch of images and labels from the dataloader\n # we collate here rather than in the DataLoader so that\n # we can still access the AudioSamples and thier information\n batch_data = collate_samples(samples)\n batch_tensors = batch_data[\"samples\"].to(self.device)\n batch_tensors.requires_grad = False\n\n # forward pass of network: feature extractor + classifier\n logits = self.network(batch_tensors)\n\n ### Activation layer ###\n scores = apply_activation_layer(logits, activation_layer)\n\n # disable gradients on returned values\n total_scores.append(scores.detach().cpu().numpy())\n\n if wandb_session is not None:\n wandb_session.log(\n {\n \"progress\": i / len(dataloader),\n \"completed_batches\": i,\n \"total_batches\": len(dataloader),\n }\n )\n\n # aggregate across all batches\n if len(total_scores) > 0:\n total_scores = np.concatenate(total_scores, axis=0)\n # replace scores with nan for samples that failed in preprocessing\n # this feels hacky (we predicted on substitute-samples rather than\n # skipping the samples that failed preprocessing)\n total_scores[dataloader.dataset._invalid_indices, :] = np.nan\n else:\n total_scores = None\n\n # return DataFrame with same index/columns as prediction_dataset's df\n df_index = dataloader.dataset.dataset.label_df.index\n score_df = pd.DataFrame(index=df_index, data=total_scores, columns=self.classes)\n\n # warn the user if there were invalid samples (failed to preprocess)\n # and log them to a file\n invalid_samples = dataloader.dataset.report(log=invalid_samples_log)\n\n # log top-scoring samples per class to wandb table\n if wandb_session is not None:\n classes_to_log = self.wandb_logging[\"top_samples_classes\"]\n if classes_to_log is None: # pick the first few classes if none specified\n classes_to_log = self.classes\n if len(classes_to_log) > 5: # don't accidentally log hundreds of tables\n classes_to_log = classes_to_log[0:5]\n\n for i, c in enumerate(classes_to_log):\n top_samples = score_df.nlargest(\n n=self.wandb_logging[\"n_top_samples\"], columns=[c]\n )\n # note: the \"labels\" of these samples are actually prediction scores\n dataset = AudioFileDataset(\n samples=top_samples,\n preprocessor=self.preprocessor,\n bypass_augmentations=True,\n )\n table = wandb_table(\n dataset=dataset, classes_to_extract=[c], drop_labels=True\n )\n wandb_session.log({f\"Samples / Top scoring [{c}]\": table})\n\n if return_invalid_samples:\n return score_df, invalid_samples\n else:\n return score_df\n\n def generate_cams(\n self,\n samples,\n method=\"gradcam\",\n classes=None,\n target_layers=None,\n guided_backprop=False,\n split_files_into_clips=True,\n bypass_augmentations=True,\n batch_size=1,\n num_workers=0,\n ):\n \"\"\"\n Generate a activation and/or backprop heatmaps for each sample\n\n Args:\n samples: (same as CNN.predict())\n the files to generate predictions for. Can be:\n - a dataframe with index containing audio paths, OR\n - a dataframe with multi-index (file, start_time, end_time), OR\n - a list (or np.ndarray) of audio file paths\n method: method to use for activation map. Can be str (choose from below)\n or a class of pytorch_grad_cam (any subclass of BaseCAM), or None\n if None, activation maps will not be created [default:'gradcam']\n\n str can be any of the following:\n \"gradcam\": pytorch_grad_cam.GradCAM,\n \"hirescam\": pytorch_grad_cam.HiResCAM,\n \"scorecam\": pytorch_grad_cam.ScoreCAM,\n \"gradcam++\": pytorch_grad_cam.GradCAMPlusPlus,\n \"ablationcam\": pytorch_grad_cam.AblationCAM,\n \"xgradcam\": pytorch_grad_cam.XGradCAM,\n \"eigencam\": pytorch_grad_cam.EigenCAM,\n \"eigengradcam\": pytorch_grad_cam.EigenGradCAM,\n \"layercam\": pytorch_grad_cam.LayerCAM,\n \"fullgrad\": pytorch_grad_cam.FullGrad,\n \"gradcamelementwise\": pytorch_grad_cam.GradCAMElementWise,\n\n classes (list): list of classes, will create maps for each class\n [default: None] if None, creates an activation map for the highest\n scoring class on a sample-by-sample basis\n target_layers (list): list of target layers for GradCAM\n - if None [default] attempts to use architecture's default target_layer\n Note: only architectures created with opensoundscape 0.9.0+ will\n have a default target layer. See pytorch_grad_cam docs for suggestions.\n Note: if multiple layers are provided, the activations are merged across\n layers (rather than returning separate activations per layer)\n guided_backprop: bool [default: False] if True, performs guided backpropagation\n for each class in classes. AudioSamples will have attribute .gbp_maps,\n a pd.Series indexed by class name\n split_files_into_clips (bool): see CNN.predict()\n bypass_augmentations (bool): whether to bypass augmentations in preprocessing\n see CNN.predict\n batch_size: number of samples to simultaneously process, see CNN.predict()\n num_workers: parallel CPU threads for preprocessing, see CNN.predict()\n\n Returns:\n a list of cam class activation objects. see the cam class for more details\n\n See pytorch_grad_cam documentation for references to the source of each method.\n \"\"\"\n\n ## INPUT VALIDATION ##\n\n if classes is not None: # check that classes are in model.classes\n assert np.all(\n [c in self.classes for c in classes]\n ), \"`classes` must be in self.classes\"\n\n # if target_layer is None, attempt to retrieve default target layers of network\n if target_layers is None:\n try:\n target_layers = self.network.cam_target_layers\n except AttributeError as exc:\n raise AttributeError(\n \"Please specify _init_inference_dataloadertarget_layers. Models trained with older versions of Opensoundscape do not have default target layers\"\n \"For a ResNET model, try target_layers=[model.network.layer4]\"\n ) from exc\n else: # check that target_layers are modules of self.network\n for tl in target_layers:\n assert (\n tl in self.network.modules()\n ), \"target_layers must be in self.network.modules(), but {tl} is not.\"\n\n ## INITIALIZE CAMS AND DATALOADER ##\n\n # initialize cam object: `method` is either str in methods_dict keys, or the class\n methods_dict = {\n \"gradcam\": pytorch_grad_cam.GradCAM,\n \"hirescam\": pytorch_grad_cam.HiResCAM,\n \"scorecam\": pytorch_grad_cam.ScoreCAM,\n \"gradcam++\": pytorch_grad_cam.GradCAMPlusPlus,\n \"ablationcam\": pytorch_grad_cam.AblationCAM,\n \"xgradcam\": pytorch_grad_cam.XGradCAM,\n \"eigencam\": pytorch_grad_cam.EigenCAM,\n \"eigengradcam\": pytorch_grad_cam.EigenGradCAM,\n \"layercam\": pytorch_grad_cam.LayerCAM,\n \"fullgrad\": pytorch_grad_cam.FullGrad,\n \"gradcamelementwise\": pytorch_grad_cam.GradCAMElementWise,\n }\n if isinstance(method, str) and method in methods_dict:\n cam = methods_dict[method](model=self.network, target_layers=target_layers)\n elif method is None:\n cam = None\n elif issubclass(method, pytorch_grad_cam.base_cam.BaseCAM):\n cam = method(model=self.network, target_layers=target_layers)\n else:\n raise ValueError(\n f\"`method` {method} not supported. \"\n f\"Must be str from list of supported methods or a subclass of \"\n f\"pytorch_grad_cam.base_cam.BaseCAM. See docstring for details. \"\n )\n\n # initialize guided back propagation object\n if guided_backprop:\n gb_model = pytorch_grad_cam.GuidedBackpropReLUModel(\n model=self.network, use_cuda=False\n ) # TODO cuda usage - expose? use model setting?\n\n # create dataloader to load batches of samples\n dataloader = self._init_inference_dataloader(\n samples,\n split_files_into_clips=split_files_into_clips,\n overlap_fraction=0,\n final_clip=None,\n bypass_augmentations=bypass_augmentations,\n batch_size=batch_size,\n num_workers=num_workers,\n )\n\n # move model to device\n # TODO: choose cuda or not in pytorch_grad_cam methods\n self.network.to(self.device)\n self.network.eval()\n\n ## GENERATE SAMPLES ##\n\n generated_samples = []\n for i, samples in enumerate(dataloader):\n # load a batch of images and labels from the dataloader\n # we collate here rather than in the DataLoader so that\n # we can still access the AudioSamples and thier information\n batch_data = collate_samples(samples)\n batch_tensors = batch_data[\"samples\"].to(self.device)\n batch_tensors.requires_grad = False\n\n # generate class activation maps using cam object\n def target(class_name):\n \"\"\"helper for pytorch_grad_cam class syntax\"\"\"\n # first get integet position of class name in self.classes\n class_idx = list(self.classes).index(class_name)\n # then create list of class required by pytorch_grad_cam\n return [ClassifierOutputTarget(class_idx)]\n\n if cam is not None:\n if classes is None: # selects highest scoring class per sample\n batch_maps = pd.Series({None: cam(batch_tensors)})\n else: # one activation map per class\n batch_maps = pd.Series(\n {c: cam(batch_tensors, targets=target(c)) for c in classes}\n )\n\n # update the AudioSample objects to include the activation maps\n # and create guided backprop maps, one at a time\n for i, sample in enumerate(samples):\n if cam is None:\n activation_maps = None\n else:\n # extract this sample's activation maps from batch (all classes)\n activation_maps = pd.Series(\n {c: batch_maps[c][i] for c in batch_maps.index}\n )\n\n # if requested, calculate the ReLU backpropogation, which creates\n # high resolution pixel-activation levels for specific classes\n # GuidedBackpropReLUasModule does not support batching\n if guided_backprop:\n t = batch_tensors[i].unsqueeze(0) # \"batch\" with one sample\n # target_category expects the index position of the class eg 0 for\n # first class, rather than the class name\n # note: t.detach() to avoid bug,\n # see https://github.com/jacobgil/pytorch-grad-cam/issues/401\n if classes is None: # defaults to highest scoring class\n gbp_maps = pd.Series({None: gb_model(t.detach())})\n else: # one for each class\n cls_list = list(self.classes)\n gbp_maps = pd.Series(\n {\n c: gb_model(\n t.detach(), target_category=cls_list.index(c)\n )\n for c in classes\n }\n )\n else: # no guided backprop requested\n gbp_maps = None\n\n # add CAM object as sample.cam (includes activation_map and gbp_maps)\n sample.cam = CAM(\n base_image=batch_tensors[i],\n activation_maps=activation_maps,\n gbp_maps=gbp_maps,\n )\n\n # add sample to list of outputs to return\n generated_samples.append(sample)\n\n # return list of AudioSamples containing .cam attributes\n return generated_samples\n\n\ndef use_resample_loss(model):\n \"\"\"Modify a model to use ResampleLoss for multi-target training\n\n ResampleLoss may perform better than BCE Loss for multitarget problems\n in some scenarios.\n \"\"\"\n\n model.loss_cls = ResampleLoss\n\n def _init_loss_fn(self):\n \"\"\"overrides the parent method because we need to pass class frequency\n to the ResampleLoss constructor\n \"\"\"\n class_frequency = (\n torch.tensor(self.train_loader.dataset.dataset.label_df.values)\n .sum(0)\n .to(self.device)\n )\n\n # initializing ResampleLoss requires us to pass class_frequency\n self.loss_fn = self.loss_cls(class_frequency)\n\n model._init_loss_fn = types.MethodType(_init_loss_fn, model)\n\n\ndef separate_resnet_feat_clf(model):\n \"\"\"Separate feature/classifier training params for a ResNet model\n\n Args:\n model: an opso model object with a pytorch resnet architecture\n\n Returns:\n model with modified .optimizer_params and ._init_optimizer() method\n\n Effects:\n creates a new self.opt_net object that replaces the old one\n resets self.current_epoch to 0\n \"\"\"\n\n # optimization parameters for parts of the networks - see\n # https://pytorch.org/docs/stable/optim.html#per-parameter-options\n model.optimizer_params = {\n \"feature\": { # optimizer parameters for feature extraction layers\n # \"params\": self.network.feature.parameters(),\n \"lr\": 0.001,\n \"momentum\": 0.9,\n \"weight_decay\": 0.0005,\n },\n \"classifier\": { # optimizer parameters for classification layers\n # \"params\": self.network.classifier.parameters(),\n \"lr\": 0.01,\n \"momentum\": 0.9,\n \"weight_decay\": 0.0005,\n },\n }\n\n # We override the parent method because we need to pass a list of\n # separate optimizer_params for different parts of the network\n # - ie we now have a dictionary of param dictionaries instead of just a\n # param dictionary.\n def _init_optimizer(self):\n \"\"\"override parent method to pass separate parameters to feat/clf\"\"\"\n param_dict = self.optimizer_params\n # in torch's resnet classes, the classifier layer is called \"fc\"\n feature_extractor_params_list = [\n param\n for name, param in self.network.named_parameters()\n if not name.split(\".\")[0] == \"fc\"\n ]\n classifier_params_list = [\n param\n for name, param in self.network.named_parameters()\n if name.split(\".\")[0] == \"fc\"\n ]\n param_dict[\"feature\"][\"params\"] = feature_extractor_params_list\n param_dict[\"classifier\"][\"params\"] = classifier_params_list\n return self.optimizer_cls(param_dict.values())\n\n model._init_optimizer = types.MethodType(_init_optimizer, model)\n model.opt_net = None # clears existing opt_net and its parameters\n model.current_epoch = 0 # resets the epoch to 0\n # model.opt_net will be created when .train() calls ._set_train()\n\n\nclass InceptionV3(CNN):\n \"\"\"Child of CNN class for InceptionV3 architecture\"\"\"\n\n def __init__(\n self,\n classes,\n sample_duration,\n single_target=False,\n preprocessor_class=SpectrogramPreprocessor,\n freeze_feature_extractor=False,\n weights=\"DEFAULT\",\n sample_shape=(299, 299, 3),\n ):\n \"\"\"Model object for InceptionV3 architecture subclassing CNN\n\n See opensoundscape.org for exaple use.\n\n Args:\n classes:\n list of output classes (usually strings)\n sample_duration: duration in seconds of one audio sample\n single_target: if True, predict exactly one class per sample\n [default:False]\n preprocessor_class: a class to use for preprocessor object\n freeze-feature_extractor:\n if True, feature weights don't have\n gradient, and only final classification layer is trained\n weights:\n string containing version name of the pre-trained classification weights to use for\n this architecture. if 'DEFAULT', model is loaded with best available weights (note\n that these may change across versions). Pre-trained weights available for each\n architecture are listed at https://pytorch.org/vision/stable/models.html\n sample_shape: dimensions of a sample Tensor (height,width,channels)\n \"\"\"\n\n self.classes = classes\n\n architecture = inception_v3(\n len(self.classes),\n freeze_feature_extractor=freeze_feature_extractor,\n weights=weights,\n )\n\n super(InceptionV3, self).__init__(\n architecture,\n classes,\n sample_duration,\n single_target=single_target,\n preprocessor_class=preprocessor_class,\n sample_shape=sample_shape,\n )\n self.name = \"InceptionV3\"\n\n def _train_epoch(self, train_loader, wandb_session=None):\n \"\"\"perform forward pass, loss, backpropagation for one epoch\n\n need to override parent because Inception returns different outputs\n from the forward pass (final and auxiliary layers)\n\n Returns: (targets, predictions, scores) on training files\n \"\"\"\n\n self.network.train()\n\n total_tgts = []\n total_preds = []\n total_scores = []\n batch_loss = []\n\n for batch_idx, samples in enumerate(train_loader):\n # load a batch of images and labels from the train loader\n # all augmentation occurs in the Preprocessor (train_loader)\n # we collate here rather than in the DataLoader so that\n # we can still access the AudioSamples and thier information\n batch_data = collate_samples(samples)\n batch_tensors = batch_data[\"samples\"].to(self.device)\n batch_labels = batch_data[\"labels\"].to(self.device)\n # batch_labels = batch_labels.squeeze(1)\n\n ####################\n # Forward and loss #\n ####################\n\n # forward pass: feature extractor and classifier\n # inception returns two sets of outputs\n inception_outputs = self.network(batch_tensors)\n logits = inception_outputs.logits\n aux_logits = inception_outputs.aux_logits\n\n # save targets and predictions\n total_scores.append(logits.detach().cpu().numpy())\n total_tgts.append(batch_labels.detach().cpu().numpy())\n\n # generate binary predictions\n if self.single_target: # predict highest scoring class only\n batch_preds = F.one_hot(logits.argmax(1), len(logits[0]))\n else: # multi-target: predict 0 or 1 based on a fixed threshold\n batch_preds = torch.sigmoid(logits) >= self.prediction_threshold\n total_preds.append(batch_preds.int().detach().cpu().numpy())\n\n # calculate loss\n loss1 = self.loss_fn(logits, batch_labels)\n loss2 = self.loss_fn(aux_logits, batch_labels)\n loss = loss1 + 0.4 * loss2\n\n # save loss for each batch; later take average for epoch\n\n batch_loss.append(loss.detach().cpu().numpy())\n\n #############################\n # Backward and optimization #\n #############################\n # zero gradients for optimizer\n self.opt_net.zero_grad()\n # backward pass: calculate the gradients\n loss.backward()\n # update the network using the gradients*lr\n self.opt_net.step()\n\n ###########\n # Logging #\n ###########\n # log basic train info (used to print every batch)\n if batch_idx % self.log_interval == 0:\n # show some basic progress metrics during the epoch\n N = len(train_loader)\n self._log(\n f\"Epoch: {self.current_epoch} \"\n f\"[batch {batch_idx}/{N}, {100 * batch_idx / N :.2f}%] \"\n )\n\n # Log the Jaccard score and Hamming loss, and Loss function\n epoch_loss_avg = np.mean(batch_loss)\n self._log(f\"\\tDistLoss: {epoch_loss_avg:.3f}\")\n\n # Evaluate with model's eval function\n tgts = batch_labels.int().detach().cpu().numpy()\n scores = logits.int().detach().cpu().numpy()\n self.eval(tgts, scores, logging_offset=-1)\n\n if wandb_session is not None:\n wandb_session.log({\"batch\": batch_idx})\n wandb_session.log(\n {\"epoch_progress\": self.current_epoch + batch_idx / N}\n )\n\n # update learning parameters each epoch\n self.scheduler.step()\n\n # save the loss averaged over all batches\n self.loss_hist[self.current_epoch] = np.mean(batch_loss)\n\n # return targets, preds, scores\n total_tgts = np.concatenate(total_tgts, axis=0)\n total_preds = np.concatenate(total_preds, axis=0)\n total_scores = np.concatenate(total_scores, axis=0)\n\n return total_tgts, total_preds, total_scores\n\n @classmethod\n def from_torch_dict(self):\n raise NotImplementedError(\n \"Creating InceptionV3 from torch dict is not implemented.\"\n )\n\n\ndef load_model(path, device=None):\n \"\"\"load a saved model object\n\n Note: saving and loading model objects across OpenSoundscape versions\n will not work properly. Instead, use .save_torch_dict and .load_torch_dict\n (but note that customizations to preprocessing, training params, etc will\n not be retained using those functions).\n\n For maximum flexibilty in further use, save the model with both .save() and\n .save_torch_dict()\n\n Args:\n path: file path of saved model\n device: which device to load into, eg 'cuda:1'\n [default: None] will choose first gpu if available, otherwise cpu\n\n Returns:\n a model object with loaded weights\n \"\"\"\n # load the entire pickled model object from a file and\n # move the model to the desired torch \"device\" (eg cpu or cuda for gpu)\n if device is None:\n device = (\n torch.device(\"cuda:0\") if torch.cuda.is_available() else torch.device(\"cpu\")\n )\n model = torch.load(path, map_location=device)\n\n # warn the user if loaded model's opso version doesn't match the current one\n if model.opensoundscape_version != opensoundscape.__version__:\n warnings.warn(\n f\"This model was saved with an earlier version of opensoundscape \"\n f\"({model.opensoundscape_version}) and will not work properly in \"\n f\"the current opensoundscape version ({opensoundscape.__version__}). \"\n f\"To use models across package versions use .save_torch_dict and \"\n f\".load_torch_dict\"\n )\n\n # since ResampleLoss class overrides a method of an instance,\n # we need to re-change the _init_loss_fn change when we reload\n if model.loss_cls == ResampleLoss:\n use_resample_loss(model)\n\n model.device = device\n return model\n\n\ndef load_outdated_model(\n path, architecture, sample_duration, model_class=CNN, device=None\n):\n \"\"\"load a CNN saved with a version of OpenSoundscape <0.6.0\n\n This function enables you to load models saved with opso 0.4.x and 0.5.x.\n If your model was saved with .save() in a previous version of OpenSoundscape\n >=0.6.0, you must re-load the model\n using the original package version and save it's network's state dict, i.e.,\n `torch.save(model.network.state_dict(),path)`, then load the state dict\n to a new model object with model.load_weights(). See the\n `Predict with pre-trained CNN` tutorial for details.\n\n For models created with the same version of OpenSoundscape as the one\n you are using, simply use opensoundscape.ml.cnn.load_model().\n\n Note: for future use of the loaded model, you can simply call\n `model.save(path)` after creating it, then reload it with\n `model = load_model(path)`.\n The saved model will be fully compatible with opensoundscape >=0.7.0.\n\n Examples:\n ```\n #load a binary resnet18 model from opso 0.4.x, 0.5.x, or 0.6.0\n from opensoundscape import CNN\n model = load_outdated_model('old_model.tar',architecture='resnet18')\n\n #load a resnet50 model of class CNN created with opso 0.5.0\n from opensoundscape import CNN\n model_050 = load_outdated_model('opso050_pytorch_model_r50.model',architecture='resnet50')\n ```\n\n Args:\n path: path to model file, ie .model or .tar file\n architecture: see CNN docs\n (pass None if the class __init__ does not take architecture as an argument)\n sample_duration: length of samples in seconds\n model_class: class to construct. Normally CNN.\n device: optionally specify a device to map tensors onto,\n eg 'cpu', 'cuda:0', 'cuda:1'[default: None]\n - if None, will choose cuda:0 if cuda is available, otherwise chooses cpu\n\n Returns:\n a cnn model object with the weights loaded from the saved model\n \"\"\"\n if device is None:\n device = (\n torch.device(\"cuda:0\") if torch.cuda.is_available() else torch.device(\"cpu\")\n )\n\n try:\n # use torch to load the saved model object\n model_dict = torch.load(path, map_location=device)\n except AttributeError as exc:\n raise Exception(\n \"This model could not be loaded in this version of \"\n \"OpenSoundscape. You may need to load the model with the version \"\n \"of OpenSoundscape that created it and torch.save() the \"\n \"model.network.state_dict(), then load the weights with model.load_weights\"\n ) from exc\n\n if type(model_dict) != dict:\n raise ValueError(\n \"This model was saved as a complete object. Try using load_model() instead.\"\n )\n\n # get the list of classes\n if \"classes\" in model_dict:\n classes = model_dict[\"classes\"]\n elif \"labels_yaml\" in model_dict:\n classes = list(yaml.safe_load(model_dict[\"labels_yaml\"]).values())\n else:\n raise ValueError(\"Could not get a list of classes from the saved model.\")\n\n # try to construct a model object\n if architecture is None:\n model = model_class(classes=classes, sample_duration=sample_duration)\n else:\n model = model_class(\n architecture=architecture, classes=classes, sample_duration=sample_duration\n )\n\n # rename keys of resnet18 architecture from 0.4.x-0.6.0 to match pytorch resnet18 keys\n model_dict[\"model_state_dict\"] = {\n k.replace(\"classifier.\", \"fc.\").replace(\"feature.\", \"\"): v\n for k, v in model_dict[\"model_state_dict\"].items()\n }\n\n # load the state dictionary of the network, allowing mismatches\n mismatched_keys = model.network.load_state_dict(\n model_dict[\"model_state_dict\"], strict=False\n )\n print(\"mismatched keys:\")\n print(mismatched_keys)\n\n # if there's no record of single-tartet vs multitarget, it' single target from opso 0.4.x\n try:\n single_target = model_dict[\"single_target\"]\n except KeyError:\n single_target = True\n\n model.single_target = single_target\n\n warnings.warn(\n \"After loading a model, you still need to ensure that your \"\n \"preprocessing (model.preprocessor) matches the settings used to create\"\n \"the original model.\"\n )\n\n return model\n","sub_path":"opensoundscape/ml/cnn.py","file_name":"cnn.py","file_ext":"py","file_size_in_byte":74205,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"592353940","text":"# importing some useful packages\nimport matplotlib.pyplot as plt\nimport matplotlib.image as mpimg\nimport numpy as np\nimport cv2\nimport os\nimport math\n\n# Import everything needed to edit/save/watch video clips\nfrom moviepy.editor import VideoFileClip\n\ndef grayscale(img):\n \"\"\"Applies the Grayscale transform\n This will return an image with only one color channel\n but NOTE: to see the returned image as grayscale\n (assuming your grayscaled image is called 'gray')\n you should call plt.imshow(gray, cmap='gray')\"\"\"\n return cv2.cvtColor(img, cv2.COLOR_RGB2GRAY)\n # Or use BGR2GRAY if you read an image with cv2.imread()\n # return cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)\n\ndef colorselect(image, rth=200, gth=200, bth=200):\n color_select = np.copy(image)\n color_thresholds = (image[:, :, 0] < rth) | (image[:, :, 1] < gth) | (image[:, :, 2] < bth)\n color_select[color_thresholds] = [0, 0, 0]\n return color_select\n\ndef canny(img, low_threshold, high_threshold):\n \"\"\"Applies the Canny transform\"\"\"\n return cv2.Canny(img, low_threshold, high_threshold)\n\ndef gaussian_blur(img, kernel_size):\n \"\"\"Applies a Gaussian Noise kernel\"\"\"\n return cv2.GaussianBlur(img, (kernel_size, kernel_size), 0)\n\ndef region_of_interest(img, vertices):\n \"\"\"\n Applies an image mask.\n \n Only keeps the region of the image defined by the polygon\n formed from `vertices`. The rest of the image is set to black.\n `vertices` should be a numpy array of integer points.\n \"\"\"\n #defining a blank mask to start with\n mask = np.zeros_like(img) \n \n #defining a 3 channel or 1 channel color to fill the mask with depending on the input image\n if len(img.shape) > 2:\n channel_count = img.shape[2] # i.e. 3 or 4 depending on your image\n ignore_mask_color = (255,) * channel_count\n else:\n ignore_mask_color = 255\n \n #filling pixels inside the polygon defined by \"vertices\" with the fill color \n cv2.fillPoly(mask, vertices, ignore_mask_color)\n \n #returning the image only where mask pixels are nonzero\n masked_image = cv2.bitwise_and(img, mask)\n return masked_image\n\n\ndef draw_lines(img, lines, sy, color=[255, 0, 0], thickness=2):\n \"\"\"\n NOTE: this is the function you might want to use as a starting point once you want to \n average/extrapolate the line segments you detect to map out the full\n extent of the lane (going from the result shown in raw-lines-example.mp4\n to that shown in P1_example.mp4). \n \n Think about things like separating line segments by their \n slope ((y2-y1)/(x2-x1)) to decide which segments are part of the left\n line vs. the right line. Then, you can average the position of each of \n the lines and extrapolate to the top and bottom of the lane.\n \n This function draws `lines` with `color` and `thickness`. \n Lines are drawn on the image inplace (mutates the image).\n If you want to make the lines semi-transparent, think about combining\n this function with the weighted_img() function below\n \"\"\"\n avg_right_theta = 0\n avg_right_b = 0\n avg_right_m = 0\n avg_left_theta = 0\n avg_left_b = 0\n avg_left_m = 0\n num_right = 0\n num_left = 0\n try:\n for line in lines:\n x1 = line[0][0]\n y1 = line[0][1]\n x2 = line[0][2]\n y2 = line[0][3]\n # cv2.line(img, (x1, y1), (x2, y2), color, thickness) # x1,y1,x2,y2\n theta = math.atan2(y2-y1,x2-x1) #\n b = y1 - math.tan(theta)*x1\n # b2 = y2 - math.tan(theta)*x2\n if theta > 0.4:\n avg_right_theta += theta\n avg_right_b += b\n num_right += 1\n elif theta < -0.4:\n avg_left_theta += theta\n avg_left_b += b\n num_left += 1\n except TypeError:\n pass\n if num_left > 0:\n avg_left_theta /= num_left\n avg_left_m = math.tan(avg_left_theta)\n avg_left_b /= num_left\n #left_lower\n y_ll = int(sy)\n x_ll = int((sy-avg_left_b)/avg_left_m)\n # left_upper\n y_lu = int(sy/2*1.19)\n x_lu = int((sy/2*1.19-avg_left_b)/avg_left_m)\n # drawing lines\n cv2.line(img, (x_ll,y_ll),(x_lu,y_lu), [0,255,255], 4)\n if num_right > 0:\n avg_right_theta /= num_right\n avg_right_m = math.tan(avg_right_theta)\n avg_right_b /= num_right\n # right_lower\n y_rl = int(sy)\n x_rl = int((sy-avg_right_b)/avg_right_m)\n # right_upper\n y_ru = int(sy/2*1.19)\n x_ru = int((sy/2*1.19-avg_right_b)/avg_right_m)\n # drawing lines\n cv2.line(img, (x_rl,y_rl),(x_ru,y_ru), [0,255,255], 4)\n\ndef hough_lines(img, rho, theta, threshold, min_line_len, max_line_gap, sy):\n \"\"\"\n `img` should be the output of a Canny transform.\n \n Returns an image with hough lines drawn.\n \"\"\"\n lines = cv2.HoughLinesP(img, rho, theta, threshold, np.array([]), minLineLength=min_line_len, maxLineGap=max_line_gap)\n # print(\"num of lines: \",len(lines))\n line_img = np.zeros((img.shape[0], img.shape[1], 3), dtype=np.uint8)\n draw_lines(line_img, lines, sy)\n return line_img\n\n# Python 3 has support for cool math symbols.\n\ndef weighted_img(img, initial_img, α=0.8, β=1, γ=0.):\n \"\"\"\n `img` is the output of the hough_lines(), An image with lines drawn on it.\n Should be a blank image (all black) with lines drawn on it.\n \n `initial_img` should be the image before any processing.\n \n The result image is computed as follows:\n \n initial_img * α + img * β + γ\n NOTE: initial_img and img must be the same shape!\n \"\"\"\n return cv2.addWeighted(initial_img, α, img, β, γ)\n\n# printing out some stats and plotting\n# print('This image is:', type(image), 'with dimensions:', image.shape)\n# if you wanted to show a single color channel image called 'gray', for example\n# call as plt.imshow(gray, cmap='gray')\n# plt.imshow(image)\n\n# list images available for testing\n# print(os.listdir(\"test_images/\"))\n\n# TODO: Build your pipeline that will draw lane lines on the test_images\n# then save them to the test_images_output directory.\ndef process_image(image):\n # NOTE: The output you return should be a color image (3 channel) for processing video below\n # TODO: put your pipeline here,\n # you should return the final output (image where lines are drawn on lanes)\n colorfilt = colorselect(image, 190, 190, 0)\n gray = grayscale(image)\n blurred = gaussian_blur(gray,5)\n edges1 = canny(blurred,75,175)\n edges2 = canny(colorfilt,75,175)\n edges = weighted_img(edges1,edges2,1,1,0)\n #edges = canny(blurred,75,175)\n sx, sy = image.shape[1],image.shape[0]\n vertices = np.array([[(.06*sx,sy),(sx/2*.95, sy/2*1.19), (sx/2*1.06, sy/2*1.19), (.97*sx,sy)]], dtype=np.int32)\n #vertices = np.array([[(.16*sx,.9*sy),(sx/2*.95, sy/2*1.19), (sx/2*1.06, sy/2*1.19), (.86*sx,.9*sy)]], dtype=np.int32)\n masked_edges = region_of_interest(edges,vertices)\n lines = hough_lines(masked_edges,1,np.pi/180,15,70,50, sy)\n lanelines = weighted_img(lines,image)\n return lanelines\n\ndef debug_process_image():\n # NOTE: The output you return should be a color image (3 channel) for processing video below\n # TODO: put your pipeline here,\n # you should return the final output (image where lines are drawn on lanes)\n for im_name in os.listdir(\"test_images/\"):\n # reading in an image\n print(\"processing \", im_name, \"...\")\n image = mpimg.imread('test_images/{}'.format(im_name))\n ### COPY of process_image(image) function\n colorfilt = colorselect(image, 190, 190, 0)\n gray = grayscale(image)\n blurred = gaussian_blur(gray,5)\n edges1 = canny(blurred,75,175)\n edges2 = canny(colorfilt,75,175)\n edges = weighted_img(edges1,edges2,1,1,0)\n #edges = canny(blurred,75,175)\n sx, sy = image.shape[1],image.shape[0]\n vertices = np.array([[(.06*sx,sy),(sx/2*.95, sy/2*1.19), (sx/2*1.06, sy/2*1.19), (.97*sx,sy)]], dtype=np.int32)\n #vertices = np.array([[(.16*sx,.9*sy),(sx/2*.95, sy/2*1.19), (sx/2*1.06, sy/2*1.19), (.86*sx,.9*sy)]], dtype=np.int32)\n masked_edges = region_of_interest(edges,vertices)\n lines = hough_lines(masked_edges,1,np.pi/180,15,70,50, sy)\n lanelines = weighted_img(lines,image)\n ###\n for i,coords in enumerate(vertices[0]):\n cv2.line(lanelines,(vertices[0][i][0],vertices[0][i][1]),(vertices[0][(i+1)%len(vertices[0])][0],vertices[0][(i+1)%len(vertices[0])][1]),(0,0,255),2)\n mpimg.imsave(\"test_images_output/{}_01_gray.png\".format(im_name), colorfilt)\n #mpimg.imsave(\"test_images_output/{}_02_blurred.png\".format(im_name), blurred, cmap='gray')\n mpimg.imsave(\"test_images_output/{}_03_edges.png\".format(im_name), edges, cmap='gray')\n mpimg.imsave(\"test_images_output/{}_04_masked_edges.png\".format(im_name), masked_edges, cmap='gray')\n mpimg.imsave(\"test_images_output/{}_05_lines.png\".format(im_name), lines)\n mpimg.imsave(\"test_images_output/{}_06_lanelines.png\".format(im_name), lanelines)\n print(\"done processing\")\n\n# debug_process_image()\n \ndef process_video():\n for vid_name in os.listdir(\"test_videos/\"):\n white_output = 'test_videos_output/{}'.format(vid_name)\n## To speed up the testing process you may want to try your pipeline on a shorter subclip of the video\n## To do so add .subclip(start_second,end_second) to the end of the line below\n## Where start_second and end_second are integer values representing the start and end of the subclip\n## You may also uncomment the following line for a subclip of the first 5 seconds\n##clip1 = VideoFileClip(\"test_videos/solidWhiteRight.mp4\").subclip(0,5)\n clip1 = VideoFileClip(\"test_videos/{}\".format(vid_name))#.subclip(0,5)\n white_clip = clip1.fl_image(process_image) #NOTE: this function expects color images!!\n white_clip.write_videofile(white_output, audio=False)\n clip1.reader.close()\n clip1.audio.reader.close_proc()\n clip1.reader.close()\n clip1.audio.reader.close_proc()\n del clip1\n\nprocess_video()\n\n#def process_image(image):\n# # NOTE: The output you return should be a color image (3 channel) for processing video below\n# # TODO: put your pipeline here,\n# # you should return the final output (image where lines are drawn on lanes)\n# gray = grayscale(image)\n# blurred = gaussian_blur(gray,5)\n# edges = canny(blurred,75,175)\n# #edges = canny(blurred,75,175)\n# sx, sy = image.shape[1],image.shape[0]\n# vertices = np.array([[(.06*sx,sy),(sx/2*.95, sy/2*1.19), (sx/2*1.06, sy/2*1.19), (.97*sx,sy)]], dtype=np.int32)\n# #vertices = np.array([[(.16*sx,.9*sy),(sx/2*.95, sy/2*1.19), (sx/2*1.06, sy/2*1.19), (.86*sx,.9*sy)]], dtype=np.int32)\n# masked_edges = region_of_interest(edges,vertices)\n# lines = hough_lines(masked_edges,1,np.pi/180,15,70,50, sy)\n# #lines = hough_lines(masked_edges,2,np.pi/180,15,70,50, sy)\n# lanelines = weighted_img(lines,image)\n# return lanelines","sub_path":"project_01.py","file_name":"project_01.py","file_ext":"py","file_size_in_byte":11146,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"414901818","text":"#!/usr/bin/python3\n\nimport glob\nimport os\nfrom optparse import OptionParser\nfrom struct import Struct\nfrom urllib.parse import parse_qs\nfrom urllib.request import urlopen\nimport struct\nimport codecs\n\ntable = [\n 22136, 52719, 55146, 42104, \n 59591, 46934, 9248, 28891,\n 49597, 52974, 62844, 4015,\n 18311, 50730, 43056, 17939,\n 64838, 38145, 27008, 39128,\n 35652, 63407, 65535, 23473,\n 35164, 55230, 27536, 4386,\n 64920, 29075, 42617, 17294,\n 18868, 2081\n]\n\ndef tenhouHash(game):\n code_pos = game.rindex(\"-\") + 1\n code = game[code_pos:]\n if code[0] == 'x':\n a,b,c = struct.unpack(\">HHH\", bytes.fromhex(code[1:])) \n index = 0\n if game[:12] > \"2010041111gm\":\n x = int(\"3\" + game[4:10])\n y = int(game[9])\n index = x % (33 - y)\n first = (a ^ b ^ table[index]) & 0xFFFF\n second = (b ^ c ^ table[index] ^ table[index + 1]) & 0xFFFF\n return game[:code_pos] + codecs.getencoder('hex_codec')(struct.pack(\">HH\", first, second))[0].decode('ASCII')\n else:\n return game\n\np = OptionParser()\np.add_option('-d', '--directory',\n default=os.path.expanduser('~/.tenhou-game-xml'),\n help='Directory in which to store downloaded XML')\nopts, args = p.parse_args()\nif args:\n p.error('This command takes no positional arguments')\n\nsol_files = []\nsol_files.extend(glob.glob(os.path.join(\n os.path.expanduser('~'),\n '.config/chromium/*/Pepper Data/Shockwave Flash/WritableRoot/#SharedObjects/*/mjv.jp/mjinfo.sol')))\nsol_files.extend(glob.glob(os.path.join(\n os.path.expanduser('~'),\n '.config/google-chrome/*/Pepper Data/Shockwave Flash/WritableRoot/#SharedObjects/*/mjv.jp/mjinfo.sol')))\nsol_files.extend(glob.glob(os.path.join(\n os.path.expanduser('~'),\n '.macromedia/Flash_Player/#SharedObjects/*/mjv.jp/mjinfo.sol')))\n\nif not os.path.exists(opts.directory):\n os.makedirs(opts.directory)\n\nfor sol_file in sol_files:\n print(\"Reading Flash state file: {}\".format(sol_file))\n with open(sol_file, 'rb') as f:\n data = f.read()\n header = Struct('>HI10s8sI')\n magic, objlength, magic2, mjinfo, padding = header.unpack_from(data)\n o = header.size\n assert magic == 0xbf\n assert magic2 == b'TCSO\\0\\x04\\0\\0\\0\\0'\n assert mjinfo == b'\\0\\x06mjinfo'\n assert padding == 0\n slength = Struct('>H')\n stype = Struct('>B')\n vlength = Struct('>H')\n while o < len(data) - 1:\n l, = slength.unpack_from(data, o)\n o += 2\n name = data[o:o+l]\n o += l\n t, = stype.unpack_from(data, o)\n o += stype.size\n if t == 2:\n l, = vlength.unpack_from(data, o)\n o += vlength.size\n value = data[o:o+l]\n o += l + 1 # There is a trailing null byte\n elif t == 6:\n value = ''\n o += 1 # There is a trailing null byte here too\n elif t == 1:\n value = ''\n o += 2 # There's another byte here but we don't care about it.\n else:\n print(\"Unknown type {} at o={} (hex {})\".format(t, o, hex(o)))\n if name == b'logstr':\n loglines = filter(None, value.split(b'\\n'))\n\n for logline in loglines:\n logname = parse_qs(logline.decode('ASCII'))['file'][0]\n logname = tenhouHash(logname)\n target_fname = os.path.join(opts.directory, \"{}.xml\".format(logname))\n if os.path.exists(target_fname):\n print(\"Game {} already downloaded\".format(logname))\n else:\n print(\"Downloading game {}\".format(logname))\n resp = urlopen('http://e.mjv.jp/0/log/?' + logname)\n data = resp.read()\n with open(target_fname, 'wb') as f:\n f.write(data)\n","sub_path":"tenhou-download-game-xml.py","file_name":"tenhou-download-game-xml.py","file_ext":"py","file_size_in_byte":3738,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"202966872","text":"# -*- coding: utf-8 -*-\nimport random\nimport pickle\nimport numpy as np\nimport tensorflow as tf\n\ndef weight_variable(shape):\n initial = tf.truncated_normal(shape, stddev=0.1)\n return tf.Variable(initial)\n\ndef bias_variable(shape):\n initial = tf.constant(0.1, shape=shape)\n return tf.Variable(initial)\n\nclass Networks:\n def __init__(self,grph, WIDTH, HEIGHT, OP_SIZE, learning_rate = 1e-3, lmd = 0.0):\n self.x = tf.placeholder(tf.float32, shape=[None, HEIGHT * WIDTH])\n self.y_ = tf.placeholder(tf.float32, shape=[None, OP_SIZE])\n # build the graph\n hidden1 = tf.contrib.layers.fully_connected(\n inputs=self.x,\n num_outputs = 500,\n activation_fn=tf.nn.relu,\n weights_initializer=tf.random_normal_initializer())\n W_fc2 = weight_variable([500, OP_SIZE])\n b_fc2 = bias_variable([OP_SIZE])\n\n self.y_conv = tf.matmul(hidden1, W_fc2) + b_fc2\n self.prepros = tf.nn.softmax(tf.matmul(hidden1, W_fc2) + b_fc2)\n\n self.cross_entropy = tf.reduce_mean(\n tf.nn.softmax_cross_entropy_with_logits(\n labels=self.y_, logits=self.y_conv))\n optimizer = tf.train.AdamOptimizer(learning_rate)\n self.train_step = optimizer.minimize(self.cross_entropy)\n\n '''\n 以下はPG用追加分\n 引数 : self.keep_prob, 指定の関数\n\n '''\n \n log_prob = tf.log(tf.clip_by_value(self.prepros,1e-10,1.0))\n self._acts = tf.placeholder(tf.int32)\n self._advantages = tf.placeholder(tf.float32)\n indices = tf.range(0, tf.shape(log_prob)[0]) * tf.shape(log_prob)[1] + self._acts\n act_prob = tf.gather(tf.reshape(log_prob, [-1]), indices)\n actpro_b = tf.gather(tf.reshape(self.prepros, [-1]), indices)\n pg_loss = -tf.reduce_sum(tf.multiply(act_prob, tf.add(self._advantages, lmd*actpro_b)))\n # optimizer = tf.train.RMSPropOptimizer(learning_rate)\n self.pg_train = optimizer.minimize(pg_loss)\n\n","sub_path":"mlp500.py","file_name":"mlp500.py","file_ext":"py","file_size_in_byte":2163,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"132675096","text":"import sys\nimport pydicom\nimport re\nimport os\nfrom utils import write_file_metadata\n\n# list of DICOM metadata fields taht are NOT extracted because they have binary value, or bad characters, or are too long\nIGNORED_TAGS = [\"PixelData\", \"LargestImagePixelValue\", \"SmallestImagePixelValue\", \"PerFrameFunctionalGroupsSequence\",\n \"ROIContourSequence\",\n \"RedPaletteColorLookupTableData\", \"BluePaletteColorLookupTableData\", \"GreenPaletteColorLookupTableData\"]\n\nDICOM_COLLECTIONS = [\"Automated_System_For_Breast_Cancer_Biomarker_Analysis\",\n \"Combined_Imaging_and_Blood_Biomarkers_for_Breast_Cancer_Diagnosis\"]\n\nNAMESPACE_DICOM = \"labcas.dicom\"\nNAMESPACE_RADIOLOGY = \"labcas.radiology\"\n\ndef extract_metadata(dicom_filepath):\n ''' \n Metadata extractor for DICOM files.\n Will extract metadata into the file: .xmlmet.\n All metadata keys are prepended with \"_File_\" \n which will be removed before ingestion into the Solr index\n '''\n\n metadata = {}\n \n # extract metadata from file path\n _metadata = extract_metadata_from_filepath(dicom_filepath)\n for (key, value) in _metadata.items():\n metadata[key] = value\n \n # extracts metadata from DICOM header\n _metadata = extract_metadata_from_header(dicom_filepath)\n for (key, value) in _metadata.items():\n metadata[key] = value\n \n # write out metadata to file\n met_filepath = dicom_filepath + \".xmlmet\"\n write_file_metadata(metadata, met_filepath)\n\n\ndef extract_metadata_from_header(dicom_filepath):\n '''\n Extracts metadata from the DICOM header\n '''\n \n metadata = {}\n ds = pydicom.read_file(dicom_filepath)\n tag_names = ds.dir()\n \n # loop over input metadata fields\n for tag_name in tag_names:\n data_element = ds.data_element(tag_name)\n if data_element:\n if tag_name not in IGNORED_TAGS:\n #print 'key=%s --> value=%s' % (tag_name, data_element.value)\n metadata[\"_File_%s:%s\" % (NAMESPACE_DICOM, str(tag_name))] = str(data_element.value)\n\n return metadata\n\ndef extract_metadata_from_filepath(dicom_filepath):\n '''\n Creates metadata from the filepath \n based on collection specific semantics.\n '''\n \n dicom_filename = os.path.basename(dicom_filepath)\n \n for dicom_coll in DICOM_COLLECTIONS:\n if dicom_coll in dicom_filepath:\n return extract_metadata_from_filepath_bi(dicom_filename)\n \n # no match\n return {}\n\ndef get_top_dataset_name(inst, patient_number):\n \n # patient\n if inst == 'D':\n dataset_name = \"Duke patient # %s\" % patient_number\n elif inst == 'E':\n dataset_name = \"Moffitt patient # %s\" % patient_number\n elif inst == 'C':\n dataset_name = \"Case # %s (unilateral breast cancer)\" % patient_number\n elif inst == 'N':\n dataset_name = \"Case # %s (control i.e. no cancer)\" % patient_number\n else:\n dataset_name = \"Patient # %s\" % patient_number\n \n return dataset_name\n \ndef _extract_metadata_from_filepath_bi(inst, patient_number, \n image_type=None,\n image_modality=None,\n image_orientation=None,\n processing_level=None,\n bi_rads_score=None,\n lesion_number=None,\n volume_type=None,\n slice_number=None,\n total_number_of_slices=None):\n \n metadata = {}\n \n # patient\n description = get_top_dataset_name(inst, patient_number)\n \n # image type\n if image_type:\n metadata[\"_File_\"+NAMESPACE_RADIOLOGY+\":image_type\"] = image_type\n if image_type.upper() == 'MG':\n description += \" Mammography\"\n elif image_type.upper() == 'BT':\n description += \" Breast tomosynthesis\"\n elif image_type.upper() == 'TRU':\n description += \" Truth File\"\n elif image_type.upper() == 'MASK':\n description += \"Mask File\"\n \n # image modality\n if image_modality:\n metadata[\"_File_\"+NAMESPACE_RADIOLOGY+\":image_modality\"] = image_modality\n if image_modality.upper() == 'FFDM':\n description += \", Full Field Digital Mammography (FFDM)\"\n elif image_modality.upper() == 'DBT':\n description += \", Digital Breast Tomosynthesis (DBT)\"\n elif image_modality.upper() == 'SYN':\n description += \", Synthetic 2D Full Field Digital Mammography (FFDM)\"\n \n # image orientation\n if image_orientation:\n metadata[\"_File_\"+NAMESPACE_RADIOLOGY+\":image_orientation\"] = image_orientation\n if image_orientation.upper() == 'LMLO':\n description += ', Orientation: left mediolateral oblique'\n elif image_orientation.upper() == 'LCC':\n description += ', Orientation: left craniocaudal'\n elif image_orientation.upper() == 'RMLO':\n description += ', Orientation: right mediolateral oblique'\n elif image_orientation.upper() == 'RCC':\n description += ', Orientation: right craniocaudal'\n \n # processing level\n if processing_level:\n metadata[\"_File_\"+NAMESPACE_RADIOLOGY+\":processing_level\"] = processing_level\n if processing_level.upper() == \"DAT\":\n description += ', raw data'\n elif processing_level.upper() == \"PRO\":\n description += ', processed data'\n \n # BI-RADS score\n if bi_rads_score:\n metadata[\"_File_\"+NAMESPACE_RADIOLOGY+\":bi-rads_score\"] = bi_rads_score\n if bi_rads_score.upper() == '4A':\n description += \", Low suspicion for malignancy\"\n elif bi_rads_score.upper() == '4B':\n description += \", Moderate suspicion for malignancy\"\n elif bi_rads_score.upper() == '4C':\n description += \", High suspicion for malignancy\"\n elif bi_rads_score.upper() == '5':\n description += \", Highly suggestive of malignancy\"\n elif bi_rads_score.upper() == 'F':\n description += \", Not biopsied but instead presumed benign based on follow-up imaging\"\n \n # lesion number\n if lesion_number:\n metadata[\"_File_\"+NAMESPACE_RADIOLOGY+\":lesion_number\"] = lesion_number\n description += \", Lesion # %s\" % lesion_number\n \n # slide number and total number of slices\n if slice_number:\n metadata[\"_File_\"+NAMESPACE_RADIOLOGY+\":slice_number\"] = slice_number\n description += \", Slice # %s\" % slice_number\n \n if total_number_of_slices:\n metadata[NAMESPACE_RADIOLOGY+\":total_number_of_slices\"] = total_number_of_slices\n description += \" out of %s\" % total_number_of_slices\n \n # volume type\n if volume_type:\n metadata[\"_File_\"+NAMESPACE_RADIOLOGY+\":volume_type\"] = volume_type\n if volume_type == \"VOL\":\n description += \", Packed volume\"\n elif volume_type == \"UV\":\n description += \", Unpacked volume\"\n \n # long description\n metadata[\"_File_Description\"] = description\n return metadata\n\ndef extract_metadata_from_filepath_bi(filename):\n \n # match to regular expressions\n \n # Synthetic Mammograms (IMPORTANT: MUST COME BEFORE THE NEXT MATCH)\n # Format: ID_MG_SYN_VIEW.dcm\n # Example: E0001_MG_SYN_LCC.dcm\n match = re.search(\"(\\w)(\\d+)_MG_SYN_(\\w+)\\.dcm\", filename)\n if match:\n inst = match.group(1)\n patient_number = match.group(2)\n return _extract_metadata_from_filepath_bi(inst, patient_number,\n image_type=\"MG\",\n image_modality=\"SYN\",\n image_orientation=match.group(3),\n processing_level=None,\n bi_rads_score=None,\n lesion_number=None,\n volume_type=None,\n slice_number=None,\n total_number_of_slices=None)\n match = re.search(\"(\\w)(\\d+)_BT_SYN_(\\w+)\\.dcm\", filename)\n if match:\n inst = match.group(1)\n patient_number = match.group(2)\n return _extract_metadata_from_filepath_bi(inst, patient_number,\n image_type=\"BT\",\n image_modality=\"SYN\",\n image_orientation=match.group(3),\n processing_level=None,\n bi_rads_score=None,\n lesion_number=None,\n volume_type=None,\n slice_number=None,\n total_number_of_slices=None)\n\n\n \n # Mammograms\n # Format: ID_MG_DAT_VIEW.dcm ID_MG_PRO_VIEW.dcm\n # Example: E0001_MG_DAT_LCC.dcm E0001_MG_PRO_LCC.dcm\n match = re.search(\"(\\w)(\\d+)_MG_(\\w+)_(\\w+)\\.dcm\", filename)\n if match:\n inst = match.group(1)\n patient_number = match.group(2)\n return _extract_metadata_from_filepath_bi(inst, patient_number,\n image_type=\"MG\",\n image_modality=\"FFDM\",\n image_orientation=match.group(4),\n processing_level=match.group(3),\n bi_rads_score=None,\n lesion_number=None,\n volume_type=None,\n slice_number=None,\n total_number_of_slices=None)\n \n # Example: C0001_MASK_PRO_LCC.dcm\n match = re.search(\"(\\w)(\\d+)_MASK_(\\w+)_(\\w+)\\.dcm\", filename)\n if match:\n inst = match.group(1)\n patient_number = match.group(2)\n return _extract_metadata_from_filepath_bi(inst, patient_number,\n image_type=\"Mask\",\n image_modality=\"FFDM\",\n image_orientation=match.group(4),\n processing_level=match.group(3),\n bi_rads_score=None,\n lesion_number=None,\n volume_type=None,\n slice_number=None,\n total_number_of_slices=None)\n\n # Truth Files for 2D Mammograms\n \n # Biopsied lesions\n # E0100_TRU_4A_1_DAT_LCC.dcm\n # E0100_TRU_4A_1_DAT_LMLO.dcm\n # E0100_TRU_4A_1_DAT_LCC.dcm\n # E0100_TRU_4A_1_DAT_LMLO.dcm\n # E0100_TRU_4B_2_DAT_LCC.dcm\n # E0100_TRU_4B_2_DAT_LMLO.dcm\n # E0100_TRU_4A_1_DAT_LCC.dcm\n # E0100_TRU_4A_1_DAT_LMLO.dcm\n # E0100_TRU_4A_2_DAT_RCC.dcm\n # E0100_TRU_4A_2_DAT_RMLO.dcm\n match = re.search(\"(\\w)(\\d+)_TRU_(\\w\\w)_(\\d)_(\\w+)_(\\w+)\\.dcm\", filename)\n if match:\n inst = match.group(1)\n patient_number = match.group(2)\n return _extract_metadata_from_filepath_bi(inst, patient_number,\n image_type=\"Tru\",\n image_modality=\"FFDM\",\n image_orientation=match.group(6),\n processing_level=match.group(5),\n bi_rads_score=match.group(3),\n lesion_number=match.group(4),\n volume_type=None,\n slice_number=None,\n total_number_of_slices=None)\n \n # Non-biopsied findings\n # E0001_TRU_F1_DAT_LCC\n # E0001_TRU_F2_DAT_LCC\n match = re.search(\"(\\w)(\\d+)_TRU_F(\\d+)_(\\w+)_(\\w+)\\.dcm\", filename)\n if match:\n inst = match.group(1)\n patient_number = match.group(2)\n image_type_long = \"2D Truth file for non-biopsied lesion (presumed benign)\"\n return _extract_metadata_from_filepath_bi(inst, patient_number,\n image_type=\"Tru\",\n image_modality=\"FFDM\",\n image_orientation=match.group(5),\n processing_level=match.group(4),\n bi_rads_score=\"F\",\n lesion_number=match.group(3),\n volume_type=None,\n slice_number=None,\n total_number_of_slices=None)\n \n # Packed Volumes\n # Format: ID_BT_VOL_VIEW.dcm\n # Example: E0001_BT_VOL_LCC.dcm\n match = re.search(\"(\\w)(\\d+)_BT_VOL_(\\w+)\\.dcm\", filename)\n if match:\n inst = match.group(1)\n patient_number = match.group(2)\n return _extract_metadata_from_filepath_bi(inst, patient_number,\n image_type=\"BT\",\n image_modality=\"BDT\",\n image_orientation=match.group(3),\n processing_level=None,\n bi_rads_score=None,\n lesion_number=None,\n volume_type=\"VOL\",\n slice_number=None,\n total_number_of_slices=None)\n \n # Unpacked Volumes\n # Format: ID_BT_UV_SLICE-NUMBER_TOTAL-NUMBER-SLICES_VIEW.dcm\n # Example: E0001_BT_UV_002_085_LCC.dcm (2nd slice from 85 slices).\n match = re.search(\"(\\w)(\\d+)_BT_UV_(\\d+)_(\\d+)_(\\w+)\\.dcm\", filename)\n if match:\n inst = match.group(1)\n patient_number = match.group(2)\n return _extract_metadata_from_filepath_bi(inst, patient_number,\n image_type=\"BT\",\n image_modality=\"BDT\",\n image_orientation=match.group(5),\n processing_level=None,\n bi_rads_score=None,\n lesion_number=None,\n volume_type=\"UV\",\n slice_number=match.group(3),\n total_number_of_slices=match.group(4))\n\n # Truth Files for Volumes and Synthetic Mammograms\n # Example: E0001_TRU_VOL_002_LCC.dcm (2nd virtual slice in the packed volume).\n match = re.search(\"(\\w)(\\d+)_TRU_VOL_(\\d+)_(\\w+)\\.dcm\", filename)\n if match:\n inst = match.group(1)\n patient_number = match.group(2)\n return _extract_metadata_from_filepath_bi(inst, patient_number,\n image_type=\"Tru\",\n image_modality=\"BDT\",\n image_orientation=match.group(4),\n processing_level=None,\n bi_rads_score=None,\n lesion_number=None,\n volume_type=\"VOL\",\n slice_number=match.group(3),\n total_number_of_slices=None)\n\n # Example: E0001_TRU_UV_002_LCC.dcm (2nd slice image out of many unpacked slices).\n match = re.search(\"(\\w)(\\d+)_TRU_UV_(\\d+)_(\\w+)\\.dcm\", filename)\n if match:\n inst = match.group(1)\n patient_number = match.group(2)\n return _extract_metadata_from_filepath_bi(inst, patient_number,\n image_type=\"Tru\",\n image_modality=\"BDT\",\n image_orientation=match.group(4),\n processing_level=None,\n bi_rads_score=None,\n lesion_number=None,\n volume_type=\"UV\",\n slice_number=match.group(3),\n total_number_of_slices=None)\n\n\n # Truth file naming for the SYNs follows the 2D mammogram examples. \n # E0001_TRU_SYN_11_DAT_LCC.dcm\n match = re.search(\"(\\w)(\\d+)_TRU_SYN_(\\d+)_(\\w+)_(\\w+)\\.dcm\", filename)\n if match:\n inst = match.group(1)\n patient_number = match.group(2)\n image_type_long = \"2D Truth file for synthetic slice # %s\" % slice_number\n return _extract_metadata_from_filepath_bi(inst, patient_number,\n image_type=\"Tru\",\n image_modality=\"SYN\",\n image_orientation=match.group(5),\n processing_level=match.group(4),\n bi_rads_score=None,\n lesion_number=None,\n volume_type=None,\n slice_number=match.group(3),\n total_number_of_slices=None)\n \n \n # no match: return empty metadata\n return {} \n \n\nif __name__ == '__main__':\n '''\n IMPORTANT: this main program is invoked during publication of DICOM files to extract file-level metadata to .xmlmet files.\n DO NOT REMOVE!\n '''\n \n '''\n for filename in [\"E0001_MG_DAT_LCC.dcm\",\n \"E0001_MG_PRO_LCC.dcm\",\n \"E0100_TRU_4A_2_DAT_RMLO.dcm\",\n \"E0100_TRU_4A_1_DAT_LMLO.dcm\",\n \"E0001_TRU_F1_DAT_LCC.dcm\",\n \"E0001_BT_VOL_LCC.dcm\",\n \"E0001_BT_UV_002_085_LCC.dcm\",\n \"E0001_MG_SYN_LCC.dcm\",\n \"E0001_TRU_VOL_002_LCC.dcm\",\n \"E0001_TRU_UV_002_LCC.dcm\",\n \"E0001_TRU_SYN_11_DAT_LCC.dcm\",\n \"E0001_BT_SYN_RCC.dcm\",\n \"E0001_BT_SYN_RML.dcm\",\n \"C0001_MG_DAT_LCC.dcm\",\n \"C0001_MASK_PRO_LCC.dcm\",\n \"C0001_MG_DAT_RMLO.dcm\",\n ]:\n metadata = extract_metadata_from_filepath_bi(filename) \n print(metadata)\n '''\n \n dicom_filepath = sys.argv[1]\n extract_metadata( dicom_filepath )\n","sub_path":"common/src/main/python/gov/nasa/jpl/edrn/labcas/server/dicom_met_extractor.py","file_name":"dicom_met_extractor.py","file_ext":"py","file_size_in_byte":20047,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"101074088","text":"import torch\nfrom torch import nn\nfrom models.ModuleRedefinitions import Layer, ReshapeLayer, FlattenToLinearLayer\n\n\nclass MNISTGeneratorNet(torch.nn.Module):\n\n def __init__(self, ngf, nc, input_features=100):\n super(MNISTGeneratorNet, self).__init__()\n\n self.main = nn.Sequential(\n Layer(\n # Channel_in, c_out, k, s, p\n nn.ConvTranspose2d(input_features, ngf * 8, 4, 1, 0),\n nn.BatchNorm2d(ngf * 8),\n nn.LeakyReLU(0.2)\n # state size = 100 x 1024 x 4 x 4\n ),\n Layer(\n # C_in, c_out,k, s, p\n nn.ConvTranspose2d(ngf * 8, ngf * 4, 4, 2, 1),\n nn.BatchNorm2d(ngf * 4),\n nn.LeakyReLU(0.2)\n # state size = 100 x 512 x 8 x 8\n ),\n Layer(\n # C_in, c_out,k, s, p\n nn.ConvTranspose2d(ngf * 4, ngf * 2, 4, 2, 1),\n nn.BatchNorm2d(ngf * 2),\n nn.LeakyReLU(0.2)\n # state size = 100 x 256 x 16 x 16\n ),\n Layer(\n # C_in, c_out,k, s, p\n nn.ConvTranspose2d(ngf * 2, ngf, 4, 2, 1),\n nn.BatchNorm2d(ngf),\n nn.LeakyReLU(0.2)\n\n ),\n Layer(\n # C_in, c_out,k, s, p\n nn.ConvTranspose2d(ngf, nc, 4, 2, 1),\n nn.Tanh()\n )\n )\n\n def forward(self, x):\n return self.main(x)\n\n\nclass CIFARGeneratorNet(torch.nn.Module):\n\n def __init__(self, ngf, nc, input_features=100):\n super(CIFARGeneratorNet, self).__init__()\n\n main = nn.Sequential()\n\n main.add_module('flatten', FlattenToLinearLayer())\n main.add_module('project', nn.Linear(input_features, 2 * 2 * 4 * ngf))\n main.add_module('reshape', ReshapeLayer(4 * ngf, 2, 2))\n main.add_module('bn0', nn.BatchNorm2d(4 * ngf))\n main.add_module('leakyReLU0', nn.LeakyReLU(0.2))\n\n main.add_module('deconv1', nn.ConvTranspose2d(4 * ngf, 2 * ngf, kernel_size=4, stride=2, padding=1))\n main.add_module('bn1', nn.BatchNorm2d(2 * ngf))\n main.add_module('leakyReLU1', nn.LeakyReLU(0.2))\n\n main.add_module('deconv2', nn.ConvTranspose2d(2 * ngf, ngf, kernel_size=4, stride=2, padding=1))\n main.add_module('bn2', nn.BatchNorm2d(ngf))\n main.add_module('leakyReLU2', nn.LeakyReLU(0.2))\n\n main.add_module('deconv3', nn.ConvTranspose2d(ngf, ngf // 2, kernel_size=4, stride=2, padding=1))\n main.add_module('bn3', nn.BatchNorm2d(ngf // 2))\n main.add_module('leakyReLU3', nn.LeakyReLU(0.2))\n\n main.add_module('deconv4', nn.ConvTranspose2d(ngf // 2, nc, kernel_size=4, stride=2, padding=1))\n main.add_module('tanh', nn.Tanh())\n\n self.main = main\n\n def forward(self, input):\n return self.main(input)\n\n\nclass WGANGeneratorNet(torch.nn.Module):\n def __init__(self, imageSize, nc, ngf, input_features=100, n_extra_layers=0, ngpu=1):\n super(WGANGeneratorNet, self).__init__()\n self.ngpu = ngpu\n assert imageSize % 16 == 0, \"imageSize has to be a multiple of 16\"\n\n cngf, tisize = ngf // 2, 4\n while tisize != imageSize:\n cngf = cngf * 2\n tisize = tisize * 2\n\n main = nn.Sequential()\n\n main.add_module('initial-{0}-{1}-convt'.format(input_features, cngf),\n nn.ConvTranspose2d(input_features, cngf, 4, 1, 0, bias=False))\n main.add_module('initial-{0}-batchnorm'.format(cngf),\n nn.BatchNorm2d(cngf))\n main.add_module('initial-{0}-relu'.format(cngf),\n nn.ReLU(True))\n\n csize, cndf = 4, cngf\n while csize < imageSize // 2:\n main.add_module('pyramid-{0}-{1}-convt'.format(cngf, cngf // 2),\n nn.ConvTranspose2d(cngf, cngf // 2, 4, 2, 1, bias=False))\n main.add_module('pyramid-{0}-batchnorm'.format(cngf // 2),\n nn.BatchNorm2d(cngf // 2))\n main.add_module('pyramid-{0}-relu'.format(cngf // 2),\n nn.ReLU(True))\n cngf = cngf // 2\n csize = csize * 2\n\n # Extra layers\n for t in range(n_extra_layers):\n main.add_module('extra-layers-{0}-{1}-conv'.format(t, cngf),\n nn.Conv2d(cngf, cngf, 3, 1, 1, bias=False))\n main.add_module('extra-layers-{0}-{1}-batchnorm'.format(t, cngf),\n nn.BatchNorm2d(cngf))\n main.add_module('extra-layers-{0}-{1}-relu'.format(t, cngf),\n nn.ReLU(True))\n\n main.add_module('final-{0}-{1}-convt'.format(cngf, nc),\n nn.ConvTranspose2d(cngf, nc, 4, 2, 1, bias=False))\n main.add_module('final-{0}-tanh'.format(nc),\n nn.Tanh())\n self.main = main\n\n def forward(self, input):\n if isinstance(input.data, torch.cuda.FloatTensor) and self.ngpu > 1:\n output = nn.parallel.data_parallel(self.main, input, range(self.ngpu))\n else:\n output = self.main(input)\n return output\n","sub_path":"modules/GeneratorDefinitions.py","file_name":"GeneratorDefinitions.py","file_ext":"py","file_size_in_byte":5301,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"427212094","text":"import numpy as np\nimport pyutil.numeric as ut\n\n# Define dimensional matrix\n# Column order = {T_0, K, P_inf, T_inf, E, alpha, P_0}\nD = np.array([ [ 0, 1, 1, 0, 1, 0, 1], # M\n [ 0, 2,-1, 0,-1, 2,-1], # L\n [ 0,-3,-2, 0,-2,-1,-2], # T\n [ 1,-1, 0, 1, 0, 0, 0] ])# Theta\n\nN = ut.null(D)\n","sub_path":"pi_space/scratch.py","file_name":"scratch.py","file_ext":"py","file_size_in_byte":327,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"207974287","text":"import salabim as sim\r\nimport math\r\nimport random\r\nimport string\r\nimport time\r\nimport logging\r\nimport inspect\r\n\r\nimport platform\r\nPythonista=(platform.system()=='Darwin')\r\n\r\n\r\ndef test():\r\n test80()\r\n\r\ndef test80():\r\n env=sim.Environment(trace=False)\r\n class X(sim.Component):\r\n def process(self):\r\n yield self.hold(1)\r\n env.snapshot('manual/source/Pic1.png')\r\n env.animate(True)\r\n env.background_color('20%gray')\r\n \r\n sim.AnimatePolygon(spec=(100, 100, 300, 100, 200,190), text='This is\\na polygon')\r\n sim.AnimateLine(spec=(100, 200, 300, 300), text='This is a line')\r\n sim.AnimateRectangle(spec=(100, 10, 300, 30), text='This is a rectangle')\r\n sim.AnimateCircle(radius=60, x=200, y=400,text='This is a rectangle')\r\n sim.AnimatePoints(spec=(100,500, 150, 550, 180, 570, 250, 500, 300, 500), text='These are points')\r\n sim.AnimateText(text='This is a one-line text', x=100, y=600)\r\n sim.AnimateText(text='''\\\r\nMulti line text\r\n-----------------\r\nLorem ipsum dolor sit amet, consectetur\r\nadipiscing elit, sed do eiusmod tempor\r\nincididunt ut labore et dolore magna aliqua.\r\nUt enim ad minim veniam, quis nostrud\r\nexercitation ullamco laboris nisi ut\r\naliquip ex ea commodo consequat. Duis aute\r\nirure dolor in reprehenderit in voluptate\r\nvelit esse cillum dolore eu fugiat nulla\r\npariatur.\r\n\r\nExcepteur sint occaecat cupidatat non\r\nproident, sunt in culpa qui officia\r\ndeserunt mollit anim id est laborum.\r\n''', x=500, y=100)\r\n \r\n sim.AnimateImage('Pas un pipe.jpg', x=500, y=400)\r\n X()\r\n env.run(100)\r\n \r\ndef test79():\r\n env = sim.Environment(trace=True)\r\n class X(sim.Component):\r\n def process(self):\r\n yield self.hold(3)\r\n yield self.hold(5)\r\n\r\n\r\n env.reset_now(-1000)\r\n X(at=-500)\r\n env.run()\r\n\r\ndef test78():\r\n\r\n class X(sim.Component):\r\n\r\n def process(self):\r\n while True:\r\n yield self.hold(sim.Uniform(0,2)())\r\n self.enter(q)\r\n yield self.hold(sim.Uniform(0,2)())\r\n self.leave(q)\r\n\r\n env = sim.Environment(trace=False)\r\n for _ in range(15):\r\n x=X()\r\n q = sim.Queue('q')\r\n r=sim.Resource()\r\n s=sim.State()\r\n env.run(500)\r\n as_str=False\r\n d=sim.Normal(4)\r\n d1=sim.Distribution('Normal(4)')\r\n q.print_histograms(as_str=as_str)\r\n q.print_statistics(as_str=as_str)\r\n q.print_info(as_str=as_str)\r\n env.print_info(as_str=as_str)\r\n x.print_info(as_str=as_str)\r\n s.print_info(as_str=as_str)\r\n r.print_info(as_str=as_str)\r\n d.print_info(as_str=as_str)\r\n d1.print_info(as_str=as_str)\r\n\r\ndef test77():\r\n\r\n def y(self,t):\r\n if self == qa0:\r\n return 50\r\n if self == qa1:\r\n return 100\r\n if self == qa2:\r\n return 150\r\n return 600\r\n\r\n class X(sim.Component):\r\n def setup(self, i):\r\n self.i = i\r\n\r\n def animation_objects(self,id ):\r\n if id =='text':\r\n ao0 = sim.AnimateText(text=self.name(), textcolor='black')\r\n return 0, 20, ao0\r\n ao0 = sim.AnimateRectangle(spec=lambda c,t: (0,0,40 + 10 * t if c.index(q) <= 2 else 40,20), text=self.name(), fillcolor=id, textcolor='white', arg=self)\r\n return lambda c, t: 45 + 10 * t if c.index(q) <= 2 else 45, 0, ao0\r\n\r\n def process(self):\r\n while True:\r\n yield self.hold(sim.Uniform(0,2)())\r\n self.enter(q)\r\n yield self.hold(sim.Uniform(0,2)())\r\n self.leave(q)\r\n\r\n env = sim.Environment(trace=False)\r\n q = sim.Queue('q')\r\n qa0 = sim.AnimateQueue(q, x=lambda t: 100+t*10, y=y, direction='e', reverse=False, id='blue')\r\n qa1 = sim.AnimateQueue(q, x=100, y=y, direction='e', reverse=False, max_length=6, id='red')\r\n qa2 = sim.AnimateQueue(q, x=100, y=y, direction='e', reverse=True, max_length=6, id='green')\r\n qa3 = sim.AnimateQueue(q, x=100, y=200, direction='n', id='text')\r\n [X(i=i) for i in range(15)]\r\n env.animate(True)\r\n env.run(5)\r\n qa1.remove()\r\n env.run(5)\r\n\r\ndef test76():\r\n class X(sim.Component):\r\n def process(self):\r\n for i in range(100):\r\n yield self.hold(0.3)\r\n testline = ['Line'+ str(i) for i in range(i)]\r\n testanim.line = testline\r\n\r\n env = sim.Environment()\r\n env.modelname('test many')\r\n env.background_color('10%gray')\r\n# an = sim.Rectangle(spec=(0,0,400,200),x=100, y=100, text='ABCabcopqxyz\\nABCabcopqxyz \\nABCabcopqxyz\\n', text_anchor='sw', font='narrow', fontsize=40, textcolor='blue')\r\n# an = sim.Rectangle(spec=(0,0,400,200),x=100, y=400, text='ABCabcopqxyz\\nABCabcopqxyz \\nABCabcopqxyz\\n', text_anchor='nw', font='narrow', fontsize=40, textcolor='blue')\r\n\r\n# an = sim.Text(x=600, y=100, text='ABCabcopqxyz', anchor='sw', font='', fontsize=40, textcolor='blue')\r\n# an = sim.Text(x=600, y=100, text='ABCabcopqxyz', anchor='nw', font='', fontsize=40, textcolor='blue')\r\n# an = sim.Text(x=600, y=100, text='ABCabcopqxyz', anchor='e', font='', fontsize=40, textcolor='blue')\r\n\r\n for dir in ('nw', 'w','sw','s','se','e','ne','n','c'):\r\n an = sim.AnimateRectangle(spec=(-250,-250,250,250), x=300,y =300,fillcolor='', linewidth=1, linecolor='white',text='A1y'+dir, text_anchor=dir, textcolor='white', angle=lambda t:t*5)\r\n\r\n x= 600\r\n for c in 'ABCabcopqxyz':\r\n sim.AnimateText(text=c, y=100, x=x, textcolor='white',text_anchor='s')\r\n x += 10\r\n\r\n an = sim.AnimateLine(spec=(0,0,1000,0), x=500, y=100, linecolor='red')\r\n an = sim.AnimateCircle(radius=100, fillcolor=('red',100), text='Hallo', textcolor='yellow', angle =45, x=500, y=500)\r\n\r\n an=sim.AnimateText(text=('cc\\n\\nx','abc','def','','ghi'), x=300, y=300, textcolor='white', text_anchor='c')\r\n\r\n testanim=sim.AnimateText(text=('Line1', 'Line2', 'Line3', 'Line4'), x=600, y=10, text_anchor='sw', max_lines=0)\r\n\r\n X()\r\n\r\n env.animate(True)\r\n env.run()\r\n\r\n\r\ndef test75():\r\n class MyText(sim.Text):\r\n def __init__(self, my='Abc', *args, **kwargs):\r\n sim.Text.__init__(self, text=None, *args, **kwargs)\r\n self.my=my\r\n\r\n def text(self,t):\r\n return self.my + str(env.now())\r\n\r\n def anchor(self, t):\r\n if t > 50:\r\n return 'w'\r\n else:\r\n return 'e'\r\n\r\n def xx(self,t):\r\n return self.sequence_number() * 75 + 600 + t\r\n\r\n class Comp(sim.Component):\r\n def setup(self):\r\n i = self.sequence_number()\r\n sim.Rectangle(spec=sim.centered_rectangle(50, 50), y=100 + i * 75,\r\n fillcolor='orange', x=xx, arg=self)\r\n\r\n def x(self, t):\r\n return self.sequence_number() * 75 + 600 + t\r\n\r\n def process(self):\r\n yield self.cancel()\r\n\r\n class CompGenerator(sim.Component):\r\n def process(self):\r\n while True:\r\n yield self.hold(sim.Uniform(20,20)())\r\n c=Comp()\r\n\r\n env = sim.Environment()\r\n env.modelname('test')\r\n env.background_color('10%gray')\r\n env.speed(16)\r\n CompGenerator()\r\n for s in ('a', 'b', 'p', 'A','A1yp'):\r\n print(s, env.getwidth(s, font='', fontsize=20), env.getheight(font='', fontsize=20))\r\n\r\n for text_anchor in ('s','sw','w','nw','n','ne','e','se','c'):\r\n sim.Text(x=200,y=200,text=text_anchor, text_anchor=text_anchor)\r\n\r\n anpanel = sim.Rectangle(spec=(0,0,400,200),x=lambda:50, y=500, text='This is a test with\\ntwo lines\\nline three ', text_anchor='sw', font='narrow', fontsize=40, textcolor='blue')\r\n anpanel1 = MyText(x=50, y=20, my='MY')\r\n anpanel2 = sim.Rectangle(x=0, y=200, text='abcde',\r\n spec=(0,0,500,100), angle=20, xy_anchor='n')\r\n sim.Circle(x=400,y=100,radius=100, text='Circle', fontsize=30, angle=45, xy_anchor='w')\r\n sim.Line(spec=(200,750,210,700,220,730,240,730,250,700,1000,0))\r\n sim.Points(spec=(200,750,210,700,220,730,240,730,250,700,1000,0))\r\n sim.Image(spec='Cogwheel.png', x=500, y=500, anchor='c', width=lambda t:t, text='cogwheel', angle=lambda t:t)\r\n angle = 0\r\n an = sim.Rectangle(spec=(-150, -25, 150, 25), x=300, y= 125, fillcolor='red', angle=lambda t: t * 360/200,\r\n text='test', textcolor='white', text_anchor='e')\r\n sim.Line(spec=(0,0,900,0), x=100, y=700, offsetx=0, offsety=0, text='hallo', text_anchor='nw', textcolor='white', text_offsetx=0, text_offsety=0, angle=lambda t: sim.interpolate(t, 0, 200, 0, 360))\r\n\r\n\r\n env.animate(True)\r\n env.run(100)\r\n\r\n env.run()\r\n\r\ndef test74():\r\n class Comp(sim.Component):\r\n def process(self):\r\n a.tally(env.now())\r\n self.enter(stage1)\r\n yield self.hold(sim.Uniform(10,20)())\r\n\r\n self.leave()\r\n b.tally(env.now())\r\n self.enter(stage2)\r\n yield self.hold(sim.Uniform(20,30)())\r\n self.leave()\r\n\r\n class CompGenerator(sim.Component):\r\n def process(self):\r\n while True:\r\n yield self.hold(sim.Uniform(2,6)())\r\n c=Comp()\r\n\r\n env = sim.Environment()\r\n env.modelname('test')\r\n env.background_color('10%gray')\r\n stage1=sim.Queue('stage1')\r\n stage2=sim.Queue('stage2')\r\n sim.aMonitor(monitor=stage2.length, x=100, y=100,as_points=True,as_level=True,linewidth=1, vertical_scale=5, fillcolor=('blue',100))\r\n s2 = sim.aMonitor(monitor=stage2.length, x=300, y=100, linewidth=2, horizontal_scale=2)\r\n s1 = sim.aMonitor(monitor=stage1.length_of_stay, x=100, y=400, as_points=False, height=200)\r\n sim.aMonitor(stage2.length_of_stay, x=300, y=400, height=200)\r\n a = sim.Monitor(name='a')\r\n b = sim.Monitor(name='')\r\n a1=sim.aMonitor(a, x=500, y=100, vertical_scale=1, horizontal_scale=10, height=200, as_points=True)\r\n sim.aMonitor(b, x=500, y=100, vertical_scale=1, linecolor='blue', height=200, as_points=True)\r\n\r\n CompGenerator()\r\n env.animate(True)\r\n env.speed(16)\r\n\r\n env.run(100)\r\n# s2.remove()\r\n# s1.remove()\r\n env.run()\r\n\r\ndef test73():\r\n class X(sim.Component):\r\n\r\n def process(self):\r\n while True:\r\n yield self.hold(1)\r\n mon.tally(sim.Uniform(-5,50)())\r\n\r\n\r\n env=sim.Environment(trace=False)\r\n X()\r\n mon=sim.Monitor('monitor')\r\n a=mon.animate(x=500, y=300, key_scale=10, point_size=4)\r\n env.animate(True)\r\n env.run(5)\r\n a.remove()\r\n env.run()\r\n\r\ndef test72():\r\n env=sim.Environment()\r\n p = sim.CumPdf((0, 0.5, 1,0.5))\r\n p.print_info()\r\n print(p.mean())\r\n r = sim.Resource(name='resource')\r\n s = sim.State(name='state')\r\n q=sim.Queue('rij')\r\n r.name('bron')\r\n s.name('staat')\r\n as_str=False\r\n print('---')\r\n r.print_histograms(as_str=as_str)\r\n s.print_histograms(as_str=as_str)\r\n q.print_histograms(as_str=as_str)\r\n r.print_statistics(as_str=as_str)\r\n s.print_statistics(as_str=as_str)\r\n q.print_statistics(as_str=as_str)\r\n print('---')\r\n\r\n\r\ndef test71():\r\n env = sim.Environment()\r\n env.animate(True)\r\n p = (100,100, 300, 100, 300, 500)\r\n r=(400,400, 600,600)\r\n po =(800, 400, 1000, 400,1000,650)\r\n sim.Animate(line0=p, linecolor0='red', linewidth0=1)\r\n sim.Animate(line0=p, linecolor0='red', linewidth0=1, linewidth1=10, as_points=True, t1=10)\r\n sim.Animate(rectangle0=r, linecolor0='green', linewidth0=1, as_points=False, fillcolor0='', t1=10)\r\n sim.Animate(rectangle0=r, linecolor0='blue', linewidth0=10, linewidth1=10, as_points=True, t1=10)\r\n sim.Animate(polygon0=po, linecolor0='orange', as_points=False, t1=10)\r\n sim.Animate(polygon0=po, linecolor0='pink', linewidth1=10, as_points=True, t1=10)\r\n sim.Animate(rectangle0=(500,500,600,600))\r\n sim.Animate(circle0=100, x0=800,y0=300)\r\n env.run()\r\n\r\ndef test70():\r\n class X(sim.Component):\r\n def setup(self,start,durations,xs):\r\n self.start=start\r\n self.xs=xs\r\n self.durations = durations\r\n self.monitor = sim.MonitorTimestamp(name=self.name()+'.monitor',type='any', monitor=False)\r\n\r\n def process(self):\r\n yield self.hold(self.start)\r\n self.monitor.monitor(True)\r\n for x, duration in zip(self.xs, self.durations):\r\n self.monitor.tally(x)\r\n yield self.hold(duration)\r\n self.monitor.monitor(False)\r\n\r\n env=sim.Environment()\r\n x0= X(start=0, xs=(1,3,'a','7'), durations=(1,1,1,1))\r\n x1= X(start=0, xs=('a',2,5), durations=(3,3,8))\r\n env.run(20)\r\n x0.monitor.print_histograms()\r\n x1.monitor.print_histograms()\r\n m = sim.MonitorTimestamp(name='combined', merge=(x0.monitor,x1.monitor))\r\n m.print_histogram()\r\n\r\n a1=sim.Monitor(name='a1', type='int8')\r\n a1.tally(1)\r\n a1.tally(2)\r\n a1.tally(2)\r\n a1.tally(0)\r\n a2=sim.Monitor(name='a2', type='int8')\r\n a2.tally(1)\r\n a2.tally(20)\r\n a2.tally(18)\r\n a2.tally(0)\r\n a2.tally(2)\r\n a1.print_histogram()\r\n a2.print_histogram()\r\n a = sim.Monitor(name='combined', merge=(a1,a2), type='int8')\r\n a.print_histogram()\r\n\r\n\r\n\r\n\r\ndef test69():\r\n class X(sim.Component):\r\n pass\r\n\r\n sim.reset()\r\n env = sim.Environment()\r\n q=sim.Queue('q')\r\n# X().enter_sorted(q, (1,1))\r\n# X().enter_sorted(q, (0,2))\r\n# X().enter_sorted(q, (1,0))\r\n# X().enter_sorted(q, (1,3))\r\n# q.print_info()\r\n\r\n q=sim.Queue('q')\r\n X().enter_sorted(q, 'one')\r\n X().enter_sorted(q, 'two')\r\n X().enter_sorted(q, 'three')\r\n X().enter_sorted(q, 'four')\r\n q.print_info()\r\n\r\ndef test68():\r\n class X(sim.Component):\r\n\r\n def process(self):\r\n self.enter(q1).enter(q2)\r\n self.enter(q3)\r\n yield self.request(r)\r\n self.leave().enter(q2)\r\n self.leave(q2).leave().leave().enter(q1)\r\n\r\n env=sim.Environment(trace=True)\r\n q1=sim.Queue('q1')\r\n q2=sim.Queue('q2')\r\n q3=sim.Queue('q3')\r\n components = []\r\n somecomponents =[]\r\n x= [X().register(components).register(somecomponents) for _ in range(5)]\r\n\r\n r = sim.Resource().register(components)\r\n env.run()\r\n\r\n x[3].deregister(components)\r\n\r\n for c in components:\r\n print(c.name())\r\n for c in somecomponents:\r\n print(c.name())\r\n\r\ndef test67():\r\n env = sim.Environment()\r\n m = sim.Monitor('normal distribution')\r\n m.name('test')\r\n for i in range(100000):\r\n m.tally(sim.Normal(10,2)())\r\n m.print_histogram()\r\n\r\ndef test66():\r\n class Poly(sim.Animate):\r\n def __init__(self, radius, number_of_sides,*args, **kwargs):\r\n self.radius = radius\r\n self.number_of_sides = number_of_sides\r\n sim.Animate.__init__(self, polygon0=(), *args, **kwargs)\r\n\r\n def polygon(self,t):\r\n return sim.regular_polygon(radius=self.radius, number_of_sides=self.number_of_sides, initial_angle = t*1)\r\n\r\n env = sim.Environment()\r\n env.animate(True)\r\n for i in range(3,10):\r\n# sim.Animate(polygon0=sim.regular_polygon(radius=60, number_of_sides=i, initial_angle=90), x0=50+(i-3)*150, y0=300\r\n Poly(radius=60, number_of_sides=i, x0=50+(i-3)*150, y0=300)\r\n\r\n env.run()\r\n\r\ndef test65():\r\n class X(sim.Component):\r\n def process(self):\r\n while True:\r\n mt.tally('idle')\r\n yield self.hold(10)\r\n for i in range(6):\r\n st = sim.Pdf(('produce A', 'produce B', 'produce C', 'produce D', 'transport', 'store'),1)()\r\n mt.tally(st)\r\n yield self.hold(sim.Uniform(6,6)())\r\n\r\n env = sim.Environment(trace=False)\r\n mt = sim.MonitorTimestamp('Status')\r\n\r\n X()\r\n env.run(300)\r\n mt.print_histogram(values=True)\r\n\r\n\r\ndef test64():\r\n class X(sim.Component):\r\n def process(self):\r\n for i in list(range(70)):\r\n mt.tally(i)\r\n yield self.hold(2)\r\n env.main().activate()\r\n\r\n env = sim.Environment(trace=False)\r\n m = sim.Monitor('m')\r\n mt = sim.MonitorTimestamp('mt')\r\n\r\n X()\r\n env.run()\r\n m.print_histograms()\r\n for i in (0,1,1,2,3,1,1,1,10,20,300):\r\n m.tally(i)\r\n m.print_histograms()\r\n mt.print_histograms(ex0=True)\r\n\r\ndef test63():\r\n class X(sim.Component):\r\n def process(self):\r\n for i in (1,2,3,1,1,1,'1','jan','a',1,2,'2'):\r\n mt.tally(i)\r\n try:\r\n x = int(i)\r\n except:\r\n x = 1.5\r\n yield self.hold(2.1 * x)\r\n env.main().activate()\r\n\r\n env = sim.Environment(trace=True)\r\n m = sim.Monitor('m')\r\n mt = sim.MonitorTimestamp('mt')\r\n\r\n X()\r\n env.run()\r\n m.print_histogram(values=True)\r\n for i in (1,2,3,1,1,1,1.1,1.2,'1.2',0,'',' ',' 1000 ',1000,600,6.8,5,'2','1','jan','piet','x','y','b','a',1,2,'2'):\r\n m.tally(i)\r\n m.print_histogram(values=True, ex0=False)\r\n mt.print_histogram(values=True)\r\n print(mt.xduration())\r\n\r\n mt.print_histogram()\r\n\r\ndef test62():\r\n class X1(sim.Component):\r\n def process(self):\r\n yield self.hold(100)\r\n\r\n class X2(sim.Component):\r\n def process(self):\r\n yield self.request(res, fail_at=100)\r\n yield self.hold(50)\r\n\r\n class X3(sim.Component):\r\n def process(self):\r\n yield self.passivate()\r\n\r\n class X4(sim.Component):\r\n def process(self):\r\n while True:\r\n yield self.standby()\r\n\r\n class X5(sim.Component):\r\n def process(self):\r\n yield self.wait(st, fail_at=100)\r\n yield self.hold(50)\r\n\r\n class Z(sim.Component):\r\n def process(self):\r\n for i in range(20):\r\n yield self.hold(1)\r\n\r\n class Y(sim.Component):\r\n def process(self):\r\n yield self.hold(4)\r\n x1.remaining_duration(100)\r\n yield self.hold(1)\r\n x1.interrupt()\r\n x2.interrupt()\r\n x2.interrupt()\r\n x3.interrupt()\r\n x4.interrupt()\r\n x5.interrupt()\r\n yield self.hold(2)\r\n res.set_capacity(0)\r\n st.set()\r\n yield self.hold(3)\r\n x1.resume()\r\n x2.resume()\r\n x3.resume()\r\n x4.resume()\r\n x5.resume()\r\n x2.resume()\r\n\r\n env = sim.Environment(trace=True)\r\n env.suppress_trace_standby(False)\r\n x1 = X1()\r\n x1.name('abc')\r\n x2 = X2()\r\n x3 = X3()\r\n x4 = X4()\r\n x5 = X5()\r\n\r\n y = Y()\r\n z = Z()\r\n res = sim.Resource('res', capacity=0)\r\n st = sim.State('st')\r\n\r\n env.run(urgent=True)\r\n\r\ndef test61():\r\n class X(sim.Component):\r\n def process(self):\r\n yield self.request(r)\r\n yield self.hold(1)\r\n\r\n class Y(sim.Component):\r\n def process(self):\r\n yield self.request(r)\r\n yield self.hold(1)\r\n# self.cancel()\r\n a=1\r\n\r\n env = sim.Environment(trace=True)\r\n r = sim.Resource('r', capacity=2)\r\n X()\r\n Y()\r\n env.run()\r\n print(r.claimed_quantity())\r\n\r\ndef test60():\r\n class X(sim.Component):\r\n def process(self):\r\n yield self.request(r)\r\n yield self.hold(sim.Uniform(0,2)())\r\n\r\n env = sim.Environment()\r\n r = sim.Resource(name='r',capacity=1)\r\n for i in range(5):\r\n X()\r\n env.trace(True)\r\n env.run(10)\r\n occupancy = r.claimed_quantity.mean() / r.capacity.mean()\r\n r.print_statistics()\r\n env.run(urgent=True)\r\n\r\n\r\ndef test59():\r\n def do_next():\r\n global ans\r\n global min_n\r\n\r\n for an in ans:\r\n an.remove()\r\n ans = []\r\n\r\n x=10\r\n y=env.height() - 80\r\n sx= 230\r\n sy=14\r\n y -= 30\r\n fontnames = []\r\n n=0\r\n\r\n for fns, ifilename in sim.fonts():\r\n for fn in fns:\r\n fontnames.append(fn)\r\n fontnames.extend(sim.standardfonts().keys())\r\n last = ''\r\n any = False\r\n for font in sorted(fontnames, key=sim.normalize):\r\n if font != last: # remove duplicates\r\n last = font\r\n n += 1\r\n if n >= min_n:\r\n any = True\r\n ans.append(sim.Animate(text=font, x0=x, y0=y, anchor='sw', fontsize0=15, font=font))\r\n x += sx + 5\r\n if x + sx > 1024:\r\n y -= sy + 4\r\n x = 10\r\n if y<0:\r\n break\r\n min_n = n + 1\r\n if not any:\r\n env.quit()\r\n\r\n global ans\r\n global min_n\r\n\r\n env = sim.Environment()\r\n sim.AnimateButton(x=500,y=-21, width=50, xy_anchor='nw', text='Next', fillcolor='red', action=do_next)\r\n ans = []\r\n min_n = 0\r\n# sim.Animate(text='Salabim fontnames', x0=x, y0=y, fontsize0=20, anchor='sw', textcolor0='white')\r\n\r\n do_next()\r\n env.background_color('20%gray')\r\n\r\n env.animate(True)\r\n env.run()\r\n\r\ndef test58():\r\n env = sim.Environment()\r\n names = sorted(sim.colornames().keys())\r\n x=10\r\n y=env.height() - 80\r\n sx= 155\r\n sy=23\r\n sim.Animate(text='Salabim colornames', x0=x, y0=y, fontsize0=20, anchor='sw', textcolor0='white')\r\n y -= 30\r\n for name in names:\r\n if env.is_dark(name):\r\n textcolor = 'white'\r\n else:\r\n textcolor = 'black'\r\n sim.Animate(rectangle0=(x, y, x + sx, y + sy), fillcolor0=name)\r\n sim.Animate(text='' if name =='' else name, x0=x + sx / 2, y0=y + sy /2, anchor='c', textcolor0=textcolor, fontsize0=15)\r\n x += sx + 5\r\n if x + sx > 1024:\r\n y -= sy + 4\r\n x = 10\r\n\r\n env.background_color('20%gray')\r\n env.animate(True)\r\n env.run()\r\n\r\ndef test57():\r\n class X(sim.Component):\r\n def process(self):\r\n while env.now()30:\r\n env.main().activate()\r\n print('aa')\r\n self.myhold(1)\r\n yield self.hold(1)\r\n\r\n\r\n class B(sim.Component):\r\n def process(self):\r\n while True:\r\n yield self.hold(1)\r\n env = sim.Environment(trace=True)\r\n env.suppress_trace_standby(True)\r\n A()\r\n B()\r\n env.run(8)\r\n print('ready')\r\n\r\n\r\n\r\ndef test47():\r\n class Dodo(sim.Component):\r\n pass\r\n\r\n class Car(sim.Component):\r\n def setup(self, color='unknown'):\r\n self.color=color\r\n print(self.name(),color)\r\n\r\n def process(self, duration):\r\n yield self.hold(duration)\r\n yield self.activate(process='process', duration=50)\r\n\r\n def other(self):\r\n yield self.hold(1)\r\n\r\n env=sim.Environment(trace=True)\r\n Car(process=None)\r\n Car(color='red', duration=12, mode='ABC')\r\n Car(color='blue',process='other')\r\n\r\n\r\n Dodo()\r\n\r\n env.run(100)\r\n\r\n\r\ndef test46():\r\n class Y(sim.Component):\r\n pass\r\n\r\n class X(sim.Component):\r\n def process(self):\r\n x=0\r\n\r\n for i in range(10):\r\n q.add(Y())\r\n print ('q.length=', q.length())\r\n if i==3:\r\n monx.monitor(False)\r\n monx.tally(x)\r\n if i==6:\r\n monx.monitor(True)\r\n yield self.hold(1)\r\n x += 1\r\n\r\n env = sim.Environment()\r\n env.beep()\r\n monx = sim.MonitorTimestamp('monx')\r\n q = sim.Queue('q')\r\n X()\r\n\r\n env.run(20)\r\n print(monx.xt())\r\n print(q.length.xt())\r\n\r\n\r\n\r\ndef test45():\r\n def test(d, lowerbound=-sim.inf, upperbound=sim.inf):\r\n d.print_info()\r\n print('mean=', d.mean())\r\n l=[d(lowerbound, upperbound) for i in range(10000)]\r\n print('one sample', d())\r\n print('mean sampled =', sum(l)/(len(l)+1))\r\n print('-' * 79)\r\n\r\n env=sim.Environment()\r\n mon = sim.Monitor()\r\n d = sim.Cdf((5, 0, 10, 50, 15, 90, 30, 95, 60, 100))\r\n for _ in range(10000):\r\n mon.tally(d.bounded_sample(lowerbound=5, upperbound=sim.inf, number_of_retries=300))\r\n\r\n mon.print_histogram(30,-5,1)\r\n\r\n\r\ndef test44():\r\n import newqueue\r\n import newerqueue\r\n import newcomponent\r\n\r\n class X(sim.Component):\r\n def process(self):\r\n yield self.hold(10,mode='ok')\r\n if self == x1:\r\n yield self.passivate()\r\n yield self.hold(10,urgent=True)\r\n\r\n class Y(sim.Component):\r\n def setup(self, a='a'):\r\n print('a=',a)\r\n\r\n\r\n def process(self, text):\r\n print('-->',text)\r\n yield self.request((res, 4), fail_at=15)\r\n x1.activate(mode=5)\r\n\r\n\r\n env=sim.Environment(trace=True)\r\n res = sim.Resource()\r\n\r\n x0=X()\r\n x1=X(name='')\r\n x2=X(name=',')\r\n z=newcomponent.NewComponent()\r\n q0=sim.Queue()\r\n q1=newqueue.NewQueue()\r\n q2=newerqueue.NewerQueue()\r\n Y(process='process', text='Hello')\r\n q0.add(x1)\r\n q1.add(x1)\r\n q2.add(x1)\r\n\r\n env.run(50)\r\n env.print_trace_header()\r\n\r\ndef test43():\r\n def test(d):\r\n d.print_info()\r\n print('mean=', d.mean())\r\n l=[d() for i in range(10000)]\r\n print('one sample', d())\r\n print('mean sampled =', sum(l)/(len(l)+1))\r\n print('-' * 79)\r\n\r\n env=sim.Environment()\r\n\r\n test(sim.IntUniform(1,6))\r\n test(sim.Weibull(2,1))\r\n test(sim.Gamma(5,9))\r\n test(sim.Erlang(2,scale=3))\r\n test(sim.Exponential(rate=2))\r\n test(sim.Beta(32,300))\r\n test(sim.Normal(5,7))\r\n test(sim.Normal(5,7,use_gauss=True))\r\n\r\n test(sim.Distribution('Exponential(rate=2)'))\r\n test(sim.Normal(5,5))\r\n\r\ndef test42():\r\n class Rij(sim.Queue):\r\n pass\r\n\r\n class Komponent(sim.Component):\r\n pass\r\n\r\n class Reg(sim.Monitor):\r\n pass\r\n\r\n env=sim.Environment(trace=True)\r\n\r\n q1=sim.Queue('q1')\r\n q2=sim.Queue('q2')\r\n for i in range(15):\r\n c = sim.Component(name='c.')\r\n if i < 10:\r\n q1.add_sorted(c, priority=20-i)\r\n if i > 5:\r\n q2.add_sorted(c, priority=i+100)\r\n env.run(1000)\r\n del q1[1]\r\n print('length',q1.length.number_of_entries())\r\n print('length_of_stay',q1.length_of_stay.number_of_entries())\r\n\r\n q1.print_info()\r\n q2.print_info()\r\n\r\n\r\n (q1 - q2).print_info()\r\n (q2 - q1).print_info()\r\n (q1 & q2).print_info()\r\n (q1 | q2).print_info()\r\n (q2 | q1).print_info()\r\n (q1 ^ q2).print_info()\r\n q3=sim.Queue(name='q3',fill=q1)\r\n q4=sim.Queue(name='q4',fill=q1)\r\n print('before')\r\n q3.print_info()\r\n del q3[-1:-4:-1]\r\n print('after')\r\n q3.print_info()\r\n q4.pop(3)\r\n for c in q3:\r\n print(c.name(),c.count(q2),c.count(),q4.count(c),c.queues())\r\n\r\ndef test41():\r\n class Airplane(sim.Component):\r\n pass\r\n\r\n class Boat(sim.Component):\r\n pass\r\n\r\n class Car(sim.Component):\r\n pass\r\n\r\n env=sim.Environment()\r\n for i in range(2):\r\n a = Airplane(name='airplane')\r\n b = Boat(name='boat,')\r\n c = Car()\r\n print(a.name(), b.name(), c.name())\r\n\r\ndef test40():\r\n class C(sim.Component):\r\n def process(self):\r\n yield self.hold(10)\r\n\r\n class Disturber(sim.Component):\r\n def process(self):\r\n yield self.hold(5)\r\n c.passivate()\r\n yield self.hold(2)\r\n c.hold(c.remaining_duration())\r\n\r\n\r\n env=sim.Environment(trace=True)\r\n c=C(name='c')\r\n Disturber(name='disturber')\r\n env.run()\r\n\r\ndef test39():\r\n class C(sim.Component):\r\n def process(self):\r\n yield self.request(r,s='y')\r\n\r\n env=sim.Environment(trace=True)\r\n x=sim.Uniform(4)\r\n r = sim.Resource()\r\n C()\r\n env.run(4)\r\n\r\n\r\ndef test38():\r\n def animation_objects(self, value):\r\n if value=='blue':\r\n an1=sim.Animate(circle0=(40,),fillcolor0=value, linewidth0=0)\r\n else:\r\n an1=sim.Animate(rectangle0=(-40,-20,40,20), fillcolor0=value,linewidth0=0)\r\n an2=sim.Animate(text=value,textcolor0='white')\r\n return (an1,an2)\r\n\r\n class X(sim.Component):\r\n def process(self):\r\n\r\n while True:\r\n for i in ('red','green','blue','yellow','red'):\r\n letters.set(i[0])\r\n light.set(i)\r\n yield self.hold(1)\r\n\r\n class Q(sim.Queue):\r\n pass\r\n\r\n env=sim.Environment(trace=True)\r\n for i in range(3):\r\n q=Q(name='rij.')\r\n X()\r\n light=sim.State('light')\r\n light.animate()\r\n letters=sim.State('letters')\r\n letters.animate(x=100,y=100)\r\n\r\n env.animation_parameters(synced=False)\r\n env.run()\r\n\r\ndef test37():\r\n env=sim.Environment()\r\n s = sim.Monitor('s')\r\n\r\n s.tally(1)\r\n s.tally(2)\r\n s.tally(3)\r\n s.tally(0)\r\n s.tally(4)\r\n s.tally('a')\r\n\r\n print(s.x(ex0=False,force_numeric=True))\r\n\r\n\r\ndef test36():\r\n l=(1,2,3,4,5,5,'6','x','6.1')\r\n print(sim.list_to_array(l))\r\n\r\ndef test35():\r\n env=sim.Environment()\r\n sim.show_fonts()\r\n sim.fonts()\r\n\r\n\r\ndef test34():\r\n class X(sim.Component):\r\n def process(self):\r\n\r\n try:\r\n yield self.hold(-1)\r\n except sim.SalabimError:\r\n yield self.hold(1)\r\n s1.set(1)\r\n yield self.hold(1)\r\n s1.set(2)\r\n s2.set('red')\r\n yield self.hold(2)\r\n s1.set(30)\r\n\r\n class Y(sim.Component):\r\n def process(self):\r\n while True:\r\n yield self.wait((s1,'$==2'))\r\n yield self.hold(1.5)\r\n\r\n class Z(sim.Component):\r\n def process(self):\r\n while True:\r\n yield self.wait((s2,'\"$\" in (\"red\",\"yellow\")'),all=True)\r\n yield self.hold(1.5)\r\n\r\n\r\n env=sim.Environment(trace=True)\r\n env.print_info()\r\n s1=sim.State(name='s.',value=0)\r\n s2=sim.State(name='s.',value='green')\r\n s3=sim.State(name='s.')\r\n s1.name('piet')\r\n q=sim.Queue('q.')\r\n x=X()\r\n y=Y()\r\n z=Z()\r\n env.run(10)\r\n s1.print_statistics()\r\n\r\n\r\ndef test33():\r\n class X(sim.Component):\r\n def process(self):\r\n\r\n yield self.hold(1)\r\n s1.set(1)\r\n yield self.hold(1)\r\n s1.set(2)\r\n s2.set('red')\r\n yield self.hold(2)\r\n s1.set(30)\r\n\r\n class Y(sim.Component):\r\n def process(self):\r\n while True:\r\n yield self.wait((s1,lambda x, component, state: x/2>self.env.now()))\r\n yield self.hold(1.5)\r\n\r\n class Z(sim.Component):\r\n def process(self):\r\n while True:\r\n yield self.wait((s2,lambda x, component, state: x in (\"red\",\"yellow\")))\r\n yield self.hold(1.5)\r\n\r\n\r\n env=sim.Environment(trace=True)\r\n env.print_info()\r\n s1=sim.State(name='s.',value=0)\r\n s2=sim.State(name='s.',value='green')\r\n s3=sim.State(name='s.')\r\n q=sim.Queue('q.')\r\n x=X()\r\n y=Y()\r\n z=Z()\r\n env.run(10)\r\n\r\n\r\ndef test32():\r\n class X(sim.Component):\r\n def process(self):\r\n yield self.wait(go)\r\n print('X after wait')\r\n yield self.hold(10)\r\n\r\n def p1(self):\r\n print('X in p1')\r\n yield self.passivate()\r\n\r\n class Y(sim.Component):\r\n def process(self):\r\n yield self.hold(2)\r\n x.activate(keep_wait=True,at=20)\r\n\r\n\r\n\r\n\r\n env=sim.Environment(trace=True)\r\n go=sim.State()\r\n x=X()\r\n y=Y()\r\n env.run()\r\n\r\n\r\ndef test31():\r\n class X(sim.Component):\r\n def process(self):\r\n\r\n yield self.hold(1)\r\n s1.set()\r\n yield self.hold(2)\r\n s1.reset()\r\n yield self.hold(2)\r\n y.print_info()\r\n s1.trigger()\r\n\r\n class Y(sim.Component):\r\n def process(self):\r\n while True:\r\n yield self.wait(s1,(s2,'red'),(s2,'green'),s3)\r\n yield self.hold(1.5)\r\n\r\n\r\n env=sim.Environment(trace=True)\r\n env.print_info()\r\n s1=sim.State(name='s.')\r\n s2=sim.State(name='s.')\r\n s3=sim.State(name='s.')\r\n q=sim.Queue('q.')\r\n x=X()\r\n y=Y()\r\n env.run(10)\r\n print('value at ',env.now(),s1.get())\r\n print (s1.value.xduration())\r\n print(s1.value.tx())\r\n print(env)\r\n print(y)\r\n print(q)\r\n print(s1)\r\n s1.print_info()\r\n s2.print_info()\r\n\r\ndef test30():\r\n env=sim.Environment()\r\n m=sim.Monitor('m')\r\n print (m.x(ex0=True))\r\n m.tally(1)\r\n m.tally(2)\r\n m.tally(3)\r\n m.tally(0)\r\n m.tally('0')\r\n m.tally('12')\r\n m.tally('abc')\r\n print (m.x(ex0=True))\r\n\r\n\r\ndef test29():\r\n global light\r\n class Light(sim.Component):\r\n def setup(self):\r\n self.green=sim.State(name='green')\r\n\r\n def process(self):\r\n while True:\r\n yield self.hold(1)\r\n self.green.trigger(max=2)\r\n yield self.hold(1)\r\n self.green.reset()\r\n\r\n class Car(sim.Component):\r\n def process(self):\r\n while True:\r\n yield self.wait((light.green,True,1),(light.green,True,1),fail_delay=8,all=True)\r\n yield self.hold(sim.Uniform(1,3).sample())\r\n\r\n de=sim.Environment(trace=True)\r\n for i in range(10):\r\n car=Car()\r\n light=Light()\r\n de.run(10)\r\n light.green.print_statistics()\r\n print(light.green.value.xt())\r\n print(light.green.waiters())\r\n\r\n\r\ndef test28():\r\n de=sim.Environment(trace=True)\r\n wait={}\r\n for i in range(3):\r\n wait[i]=sim.Queue('wait.')\r\n\r\n\r\ndef test27():\r\n m1=sim.Monitor('m1')\r\n print (m1.mean(),m1.std(),m1.percentile(50),m1.histogram())\r\n m1.tally(10)\r\n print (m1.mean(),m1.std(),m1.percentile(50),m1.histogram())\r\n\r\n\r\ndef test26():\r\n global de\r\n class X(sim.Component):\r\n def _get_a(self):\r\n return self.a\r\n\r\n def _now(self):\r\n return self.env._now\r\n\r\n def process(self):\r\n m2.tally()\r\n yield self.hold(1)\r\n self.a=4\r\n m2.tally()\r\n m2.monitor(True)\r\n print('3',m2.xt())\r\n yield self.hold(1)\r\n self.a=20\r\n m2.tally()\r\n yield self.hold(1)\r\n self.a=0\r\n m2.tally()\r\n yield self.hold(1)\r\n m3.tally()\r\n m2.monitor(True)\r\n\r\n\r\n\r\n\r\n de=sim.Environment()\r\n m1=sim.Monitor('m1',type='uint8')\r\n print (m1.mean())\r\n m1.tally(10)\r\n m1.tally(15)\r\n m1.tally(20)\r\n m1.tally(92)\r\n m1.tally(0)\r\n m1.tally(12)\r\n m1.tally(0)\r\n print ('m1.x()',m1.x(force_numeric=False))\r\n\r\n print ('m1',m1.mean(),m1.std(),m1.percentile(50))\r\n print ('m1 ex0',m1.mean(ex0=True),m1.std(ex0=True),m1.percentile(50,ex0=True))\r\n x=X()\r\n x.a=10\r\n m2=sim.MonitorTimestamp('m2',getter=x._get_a,type='int8')\r\n print('1',m2.xt())\r\n m2.monitor(True)\r\n m2.tally()\r\n print('a',m2.xt())\r\n# m2.monitor(True)\r\n m2.tally()\r\n print('2',m2.xt())\r\n\r\n\r\n m3=sim.MonitorTimestamp('m3',getter=x._now)\r\n print(m3())\r\n\r\n de.run(10)\r\n print('4',m2.xt())\r\n print('5',m2.xduration())\r\n print(m2.mean(),m2.std(),m2.percentile(50))\r\n m1.print_histogram(10,0,10)\r\n m2.print_histogram(10,0,10)\r\n print(m3.xduration())\r\n\r\n m3.print_histogram(10,0,10)\r\n print('done')\r\n\r\n# for i in range(101):\r\n# print(i,m1.percentile(i),m2.percentile(i))\r\n m3=sim.Monitor('m3')\r\n m3.tally(1)\r\n m3.tally(3)\r\n print('xx')\r\n\r\ndef test25():\r\n de=sim.Environment()\r\n q=sim.Queue('q')\r\n c={}\r\n for i in range(8):\r\n c[i]=sim.Component(name='c.')\r\n c[i].enter(q)\r\n print(q)\r\n for c in q:\r\n c.priority(q,-c.sequence_number())\r\n print(q)\r\n\r\ndef test24():\r\n class X1(sim.Component):\r\n def process(self):\r\n print('**x1 active')\r\n yield self.request((r,2))\r\n yield self.hold(100)\r\n yield self.passivate()\r\n def p1(self):\r\n yield self.hold(0.5)\r\n yield self.activate(process=self.process())\r\n yield self.hold(100)\r\n yield self.passivate()\r\n\r\n class X2(sim.Component):\r\n def process(self):\r\n yield self.hold(1)\r\n x1.activate(at=3,keep_request=True)\r\n yield self.hold(5)\r\n x1.request(r)\r\n yield self.hold(1)\r\n x1.passivate()\r\n de.main().passivate()\r\n yield self.hold(5)\r\n x1.activate(at=20)\r\n\r\n class X3(sim.Component):\r\n def process(self):\r\n a=1\r\n yield self.hold(1)\r\n pass\r\n\r\n de=sim.Environment(trace=True)\r\n x1=X1(process='p1')\r\n x1.activate(at=0.5,process='process',urgent=True,mode='blabla')\r\n x2=X2()\r\n x3=X3()\r\n print('***name=',x3.running_process())\r\n x4=sim.Component()\r\n x3.activate(process='process')\r\n r=sim.Resource('resource')\r\n de.run(till=sim.inf)\r\n\r\ndef test1():\r\n print('test1')\r\n\r\n class X(sim.Component):\r\n def __init__(self,extra=1,*args,**kwargs):\r\n sim.Component.__init__(self,*args,**kwargs)\r\n self.extra=extra\r\n\r\n\r\n def process(self):\r\n while True:\r\n yield self.hold(1)\r\n pass\r\n\r\n def action2(self):\r\n for i in range(5):\r\n yield self.hold(25)\r\n\r\n yield self.hold(1)\r\n\r\n def actionx(self):\r\n pass\r\n\r\n class Y(sim.Component):\r\n\r\n def process(self):\r\n x[3].reactivate(process=x[3].action2(),at=30)\r\n x[4].cancel()\r\n yield self.hold(0.5)\r\n yield self.standby()\r\n yield self.activate(process=self.action2(0.3))\r\n\r\n\r\n def action2(self,param):\r\n yield self.hold(param)\r\n\r\n class Monitor(sim.Component):\r\n def process(self):\r\n while env.now()<30:\r\n yield self.standby()\r\n\r\n de=sim.Environment(trace=True)\r\n q=sim.Queue()\r\n\r\n x=[0]\r\n for i in range(10):\r\n x.append(X(name='x.',at=i*5))\r\n# x[i+1].activate(at=i*5,proc=x[i+1].action())\r\n x[i+1].enter(q)\r\n\r\n x[6].suppress_trace(True)\r\n i=0\r\n for c in q:\r\n print (c._name)\r\n i=i+1\r\n if i==4:\r\n x[1].leave(q)\r\n x[5].leave(q)\r\n x[6].leave(q)\r\n\r\n y=Y(name='y')\r\n# y.activate(at=20)\r\n env.run(till=35)\r\n\r\n# env.run(4)\r\n\r\ndef test2():\r\n de=sim.Environment()\r\n print('test2')\r\n x=[None]\r\n q=[None]\r\n for i in range(5):\r\n x.append(sim.Component(name='x.'))\r\n q.append(sim.Queue(name='q.'))\r\n y=sim.Component(name='y')\r\n x[1].enter(q[1])\r\n y.enter(q[1])\r\n x[1].enter(q[2])\r\n x[2].enter(q[2])\r\n x[2].enter(q[1])\r\n x[3].enter(q[2])\r\n q[1].print_statistics()\r\n\r\n q[2].print_statistics()\r\n q[1].union(q[2],'my union').print_statistics()\r\n\r\n q[1].difference(q[2],'my difference').print_statistics()\r\n q[1].intersect(q[2],'my intersect').print_statistics()\r\n q[1].copy('my copy').print_statistics()\r\n# q[1].move('my move').print_statistics()\r\n q[1].print_statistics()\r\n\r\n print (q[1])\r\n\r\n yy=q[1].component_with_name('y')\r\n ii=q[1].index(y)\r\n print(yy,ii)\r\n\r\n\r\ndef sample_and_print(dist,n):\r\n s=[]\r\n\r\n for i in range(n):\r\n s.append(dist.sample())\r\n print ('mean=',dist.mean(),'samples', s)\r\n\r\ndef test3():\r\n print('test3')\r\n\r\n sim.Environment(random_seed=1234567)\r\n print('string')\r\n d=sim.Distribution('Exponential (1000)')\r\n sample_and_print(d,5)\r\n sim.random_seed(1234567)\r\n sample_and_print(d,5)\r\n sim.random_seed(None)\r\n sample_and_print(d,5)\r\n\r\n print('triangular')\r\n tr=sim.Triangular(1,5,3)\r\n sample_and_print(tr,5)\r\n\r\n print('uniform')\r\n u=sim.Uniform(1,1.1)\r\n sample_and_print(u,5)\r\n print('constant')\r\n c=sim.Constant(10)\r\n sample_and_print(c,5)\r\n\r\n print('normal')\r\n n=sim.Normal(1,2)\r\n sample_and_print(n,5)\r\n sample_and_print(n,5)\r\n\r\n print('poisson')\r\n n=sim.Poisson(2)\r\n sample_and_print(n,5)\r\n sample_and_print(n,5)\r\n\r\n print('cdf')\r\n cdf=sim.Cdf((1,0,2,25,2,75,3,100))\r\n sample_and_print(cdf,5)\r\n sample_and_print(cdf,5)\r\n\r\n print('pdf list')\r\n pdf=sim.Pdf((1,2),1)\r\n sample_and_print(pdf,5)\r\n\r\n print('pdf dict')\r\n d = {1:'een', 2:'twee'}\r\n pdf=sim.Pdf(d,1)\r\n sample_and_print(pdf,5)\r\n\r\n print('pdf x')\r\n pdf=sim.Pdf((1,1,2,1))\r\n sample_and_print(pdf,5)\r\n\r\n print('pdf 1')\r\n pdf=sim.Pdf((sim.Uniform(10,20),10,sim.Uniform(20,30),80,sim.Uniform(30,40),10))\r\n sample_and_print(pdf,5)\r\n\r\n print('pdf 2')\r\n pdf=sim.Pdf((sim.Uniform(10,20),sim.Uniform(20,30),sim.Uniform(30,40)),(10,80,10))\r\n sample_and_print(pdf,5)\r\n\r\n print('pdf 3')\r\n pdf=sim.Pdf(('red','green',1000),(10,1,10))\r\n sample_and_print(pdf,5)\r\n\r\n print('pdf 4')\r\n pdf=sim.Pdf(('red',10,'green',1,1000,10))\r\n sample_and_print(pdf,5)\r\n\r\ndef test4():\r\n print('test4')\r\n class X(sim.Component):\r\n def process(self):\r\n yield self.hold(10)\r\n yield self.request(res,4)\r\n yield self.hold(20)\r\n res.requesters().print_statistics()\r\n res.claimers().print_statistics()\r\n for i in range(1):\r\n self.release(res,4)\r\n\r\n class Y(sim.Component):\r\n def process(self):\r\n yield self.hold(11)\r\n yield self.request(res,1,priority=1-self.i)\r\n if self.request_failed():\r\n pass\r\n else:\r\n yield self.hold(1)\r\n self.release(res)\r\n\r\n class Z(sim.Component):\r\n def process(self):\r\n yield self.hold(20)\r\n y[4].reschedule()\r\n res.capacity(2)\r\n\r\n de=sim.Environment()\r\n res=sim.Resource(name='res.',capacity=4)\r\n res.x=0\r\n x=X(name='x')\r\n y=[0]\r\n for i in range(6):\r\n c=Y(name='y.')\r\n c.i=i\r\n y.append(c)\r\n\r\n z=Z(name='z')\r\n env.run(till=1000)\r\n\r\ndef test5():\r\n print('test5')\r\n\r\n class X1(sim.Component):\r\n\r\n def process(self):\r\n while True:\r\n while True:\r\n yield self.request(r1,2,5,r2,greedy=True,fail_at=de.now()+6)\r\n if not self.request_failed()():\r\n break\r\n yield self.hold(1)\r\n self.release(r1,r2)\r\n yield self.passivate()\r\n class X2(sim.Component):\r\n\r\n def process(self):\r\n while True:\r\n yield self.request((r1,3),(r2,1,1))\r\n yield self.hold(1)\r\n self.release(r1)\r\n yield self.passivate()\r\n class X3(sim.Component):\r\n\r\n def process(self):\r\n while True:\r\n yield self.request(r1,r2)\r\n yield self.hold(1)\r\n self.release(r1,r2)\r\n yield self.passivate()\r\n\r\n class Y(sim.Component):\r\n\r\n# def __init__(self,*args,**kwargs):\r\n# sim.Component.__init__(self,*args,**kwargs)\r\n\r\n def process(self):\r\n yield self.hold(3)\r\n x1.cancel()\r\n yield self.hold(10)\r\n r2.capacity(1)\r\n pass\r\n\r\n\r\n\r\n de=sim.Environment(trace=True)\r\n q=sim.Queue(name='q')\r\n r1=sim.Resource(name='r1',capacity=3)\r\n r2=sim.Resource(name='r2',capacity=0)\r\n r3=sim.Resource(name='r3',capacity=1)\r\n\r\n x1=X1()\r\n x2=X2()\r\n x3=X3()\r\n\r\n\r\n y=Y(name='y')\r\n env.run(till=21)\r\n\r\ndef test6():\r\n print('test6')\r\n class X(sim.Component):\r\n def process(self):\r\n yield self.passivate()\r\n yield self.hold(1)\r\n\r\n de=sim.Environment(trace=True)\r\n x=X()\r\n print (x.status()())\r\n q=sim.Queue(name='Queue.')\r\n q.name('Rij.')\r\n print (q.name())\r\n q.clear()\r\n env.run(till=10)\r\n x.reactivate()\r\n env.run()\r\n\r\ndef test7():\r\n print('test7')\r\n\r\n class X1(sim.Component):\r\n def process(self):\r\n yield self.request(r1,5,r2,2,greedy=True,fail_at=5)\r\n yield self.passivate()\r\n\r\n\r\n class X2(sim.Component):\r\n def process(self):\r\n yield self.request(r1,8,r2)\r\n yield self.passivate()\r\n\r\n class X3(sim.Component):\r\n def process(self):\r\n yield self.request(r1,7)\r\n yield self.passivate()\r\n\r\n\r\n de=sim.Environment(trace=True)\r\n\r\n x1=X1()\r\n x2=X2()\r\n x3=X3()\r\n\r\n X4=sim.Component()\r\n\r\n r1=sim.Resource(capacity=10,anonymous=True)\r\n r2=sim.Resource()\r\n r3=sim.Resource()\r\n\r\n q={}\r\n for i in range(1,5):\r\n q[i]=sim.Queue()\r\n\r\n x1.enter(q[1])\r\n x1.enter(q[2])\r\n x1.enter(q[3])\r\n\r\n x2.enter(q[1])\r\n x3.enter(q[1])\r\n\r\n\r\n\r\n env.run(10)\r\n r2.capacity(2)\r\n env.run(20)\r\n\r\n print(sim.default_env)\r\n\r\n print(x1)\r\n print(x2)\r\n print(x3)\r\n\r\n print (q[1])\r\n print (q[2])\r\n print (q[3])\r\n print (q[4])\r\n\r\n print(r1)\r\n print(r2)\r\n print(r3)\r\n\r\n d=sim.Exponential(10)\r\n print(d)\r\n print(sim.Uniform(1,2))\r\n print(sim.Triangular(40,150,55))\r\n print(sim.Distribution('Constant(5)'))\r\n\r\n\r\n\r\ndef test8():\r\n print('test8')\r\n\r\n class AnimatePolar(sim.Animate):\r\n def __init__(self,r,*args,**kwargs):\r\n self.r=r\r\n super().__init__(*args,**kwargs)\r\n\r\n def x(self,t):\r\n tangle=sim.interpolate(t,self.t0,self.t1,0,2*math.pi)\r\n sint=math.sin(tangle)\r\n cost=math.cos(tangle)\r\n x,y=(100+self.r*cost-0*sint,100+self.r*sint+0*cost)\r\n return x\r\n\r\n def y(self,t):\r\n tangle=sim.interpolate(t,self.t0,self.t1,0,2*math.pi)\r\n sint=math.sin(tangle)\r\n cost=math.cos(tangle)\r\n x,y=(100+self.r*cost-0*sint,100+self.r*sint+0*cost)\r\n return y\r\n\r\n def angle(self,t):\r\n return sim.interpolate(t,self.t0,self.t1,0,360)\r\n\r\n def fillcolor(self,t):\r\n f=sim.interpolate(t,self.t0,self.t1,0,1)\r\n if f<0.5:\r\n return sim.colorinterpolate(f,0,0.5,sim.colorspec_to_tuple('red'),sim.colorspec_to_tuple('blue'))\r\n else:\r\n return sim.colorinterpolate(f,0.5,1,sim.colorspec_to_tuple('blue'),sim.colorspec_to_tuple('green'))\r\n\r\n def text(self,t):\r\n angle=sim.interpolate(t,self.t0,self.t1,0,360)\r\n return '{:3.0f}'.format(angle)\r\n\r\n\r\n class X(sim.Component):\r\n def slideraction(self):\r\n print ('value='+str(self.myslider.v))\r\n\r\n def process(self):\r\n\r\n AnimatePolar(r=100,text='A',t1=10)\r\n\r\n x=0\r\n for fontsize in range(8,30):\r\n sim.Animate(x0=x,y0=height-100,text='aA1',font=('Calibri,calibri'),fontsize0=fontsize)\r\n x+=fontsize*2\r\n x=0\r\n for fontsize in range(8,30):\r\n sim.Animate(x0=x,y0=height-200,text='aA1',font='CabinSketch-Bold',fontsize0=fontsize)\r\n x+=fontsize*2\r\n\r\n\r\n self.rx=sim.Animate(x0=600,y0=300,linewidth0=1,\r\n rectangle0=(-200,-200,200,200),t1=10,fillcolor0='green#7f',angle1=0)\r\n self.rx=sim.Animate(x0=500,y0=500,linewidth0=1,line0=(-500,0,500,0),t1=10,fillcolor0='black')\r\n self.rx=sim.Animate(x0=500,y0=500,linewidth0=1,line0=(0,-500,0,500),t1=10,fillcolor0='black')\r\n\r\n self.rx=sim.Animate(x0=500,y0=500,linewidth0=10,polygon0=(0,0,100,0,100,100,50,50,0,100),offsetx1=100,offsety1=100,t1=10,fillcolor0='red#7f',angle1=360)\r\n self.rx=sim.Animate(x0=600,y0=300,linewidth0=1,rectangle0=(-200,-200,200,200),t1=10,fillcolor0='blue#7f',angle1=360)\r\n\r\n# self.t1=sim.Animate(x0=500,y0=500,fillcolor0='black',\r\n# text='Test text',x1=500,y1=500,t1=25,font='CabinSketch-#Bold',fontsize0=20,anchor='ne',angle1=0,fontsize1=50)\r\n\r\n\r\n self.i1=sim.Animate(x0=250,y0=250,offsetx0=100,offsety0=100,angle0=0,angle1=360,circle0=(20,),fillcolor0=('red',0),linewidth0=2,linecolor0='blue',circle1=(20,),t1=15)\r\n\r\n# self.ry=sim.Animate(x0=500,y0=300,linewidth0=1,polygon0=(-100,-100,100,-100,0,100),t1=10,fillcolor0='blue',angle1=90)\r\n\r\n self.i1=sim.Animate(x0=500,y0=500,angle0=0,layer=1,image='salabim.png',width0=300,x1=500,y1=500,angle1=360,t1=20,anchor='center')\r\n\r\n yield self.hold(3)\r\n self.i1.update(image='Upward Systems.jpg',angle1=self.i1.angle1,t1=self.i1.t1,width0=self.i1.width0)\r\n return\r\n self.myslider=sim.AnimateSlider(x=600,y=height,width=100,height=20,vmin=5,vmax=10,v=23,resolution=1,label='Test slider',action=self.slideraction)\r\n\r\n return\r\n\r\n\r\n self.p1=sim.AnimatePolygon(\r\n x0=200,y0=200,polygon0=(-100,-100,100,-100,100,100,-100,100),\r\n t1=25,x1=100,y1=100,fillcolor1='red',linecolor0='blue',linewidth0=3)\r\n self.p2=sim.Animate(linewidth0=2,linecolor0='black',linecolor1='white',\r\n x0=100,y0=600,fillcolor0='green',polygon0=(-50,-50,50,-50,0,0),angle1=720,t1=8)\r\n self.r1=sim.Animate(layer=1,x0=500,y0=500,rectangle0=(0,0,100,100),fillcolor0='yellow',linecolor0='red',linewidth0=2,angle1=180,t1=10)\r\n self.t1=sim.Animate(x0=200,y0=200,fillcolor0='black',\r\n text='Test text',x1=100,y1=100,anchor='center',t1=25,font='courier',fontsize1=50)\r\n self.r2=sim.Animate(rectangle0=(-5,-5,5,5))\r\n\r\n i=0\r\n for s in ['ne','n','nw','e','center','w','se','s','sw']:\r\n sim.Animate(x0=200,y0=200,text=s,t0=i,t1=i+1,anchor=s,keep=False,fillcolor0='red')\r\n i=i+1\r\n\r\n self.p2=sim.Animate(x0=500,y0=500,line0=(0,0,100,100),angle1=360,t1=10,linecolor0='red',linewidth0=5)\r\n self.r2=sim.Animate(x0=300,y0=700,rectangle0=(-300,-300,300,300),fillcolor0='',linecolor0='black', linewidth0=2)\r\n self.c1=sim.Animate(x0=300,y0=700,circle0=(0,),fillcolor0='blue',circle1=(60,),t1=20)\r\n self.i1=sim.Animate(x0=500,y0=500,angle0=0,layer=1,image='BOA.png',width0=300,x1=500,y1=500,angle1=360,t1=20,anchor='center')\r\n# self.i1=sim.AnimateText(text='ABCDEF',x0=500,y0=200,angle0=0,layer=1,angle1=360,t1=20,anchor='center')\r\n yield self.hold(10)\r\n# self.t1.update(color0='white',x1=100,y1=100,t1=25)\r\n self.r1.update()\r\n self.c1.update(t1=20,radius1=0)\r\n\r\n import os\r\n\r\n de=sim.Environment(trace=True)\r\n x=X()\r\n# s='abcdefghijk'\r\n\r\n# size=getfontsize_to_fit(s,10000)\r\n# print ('--fontsize_to_fit',size)\r\n# print('--width-1=', getwidth(s,'',size-1))\r\n# print('--width =', getwidth(s,'',size))\r\n# print('--width+1=', getwidth(s,'',size+1))\r\n# assert False\r\n\r\n height=768\r\n env.animation_parameters(modelname='Salabim test')\r\n env.run(15)\r\n env.run(till=30)\r\n print('THE END')\r\n\r\n\r\ndef test9():\r\n print('test9')\r\n class X(sim.Component):\r\n def process(self):\r\n yield self.passivate(mode='One')\r\n yield self.passivate(mode='Two')\r\n yield self.passivate()\r\n yield self.hold(1)\r\n\r\n class Y(sim.Component):\r\n def process(self):\r\n while True:\r\n print('de.now()=',de.now())\r\n yield self.hold(1)\r\n print(x.mode())\r\n if self.ispassive():\r\n x.reactivate()\r\n\r\n\r\n de=sim.Environment(trace=True)\r\n x=X()\r\n y=Y()\r\n env.run(till=6)\r\n\r\n\r\ndef test10():\r\n print('test10')\r\n for s in ('blue','','black#23','#123456','#12345678',(1,2,3),(4,5,6,7),('blue',8),('blue#67',1),('#123456',23)):\r\n t=sim.colorspec_to_tuple(s)\r\n print(s,'==>',t)\r\n\r\ndef test11():\r\n class Do1(sim.Component):\r\n def process(self):\r\n while True:\r\n if q1.length()==0:\r\n yield self.passivate()\r\n print('------')\r\n for cc in q1:\r\n print(de.now(),cc.name())\r\n yield self.hold(1)\r\n\r\n class Do2(sim.Component):\r\n def process(self):\r\n\r\n c[1].enter(q1)\r\n c[2].enter(q1)\r\n if d1.ispassive():\r\n d1.reactivate()\r\n yield self.hold(till=1.5)\r\n\r\n c[3].enter(q1)\r\n c[4].enter_at_head(q1)\r\n if d1.ispassive():\r\n d1.reactivate()\r\n\r\n yield self.hold(till=20.5)\r\n for cc in q1:\r\n cc.leave(q1)\r\n if d1.ispassive():\r\n d1.reactivate()\r\n\r\n class X(sim.Component):\r\n pass\r\n\r\n de=sim.Environment(trace=True)\r\n d2=Do2()\r\n d1=Do1()\r\n\r\n q1=sim.Queue('q1')\r\n q2=sim.Queue('q2')\r\n c={}\r\n for i in range(10):\r\n c[i]=sim.Component(name='c'+str(i))\r\n c[i].enter(q2)\r\n x=q2.pop()\r\n print('x=',x)\r\n print('head of q1',q1.head())\r\n print('q1[0]',q1[0])\r\n print('tail of q1',q1.tail())\r\n print('q1[-1]',q1[-1])\r\n\r\n print('head of q2',q2.head())\r\n print('q2[0]',q2[0])\r\n print('tail of q2',q2.tail())\r\n print('q2[-1]',q2[-1])\r\n\r\n\r\n\r\n\r\n print('**c[0]=',c[0])\r\n c[0].enter(q1)\r\n c[0].set_priority(q1,10)\r\n print(q1)\r\n\r\n c[3].set_priority(q2,10)\r\n\r\n c[1].set_priority(q2,-1)\r\n c[5].set_priority(q2,10)\r\n for cx in q2:\r\n print(cx.name())\r\n for cx in reversed(q2):\r\n print(cx.name(),cx in q1)\r\n\r\n print ('--')\r\n print(q2[-1])\r\n print('---')\r\n\r\n\r\n env.run(till=100)\r\n\r\ndef test12():\r\n\r\n class X(sim.Component):\r\n def process(self):\r\n sim.Animate(text='Piet' ,x0=100,y0=100,x1=500,y1=500,t1=10)\r\n while True:\r\n print(sim.default_env())\r\n yield self.hold(1)\r\n\r\n de=sim.Environment(trace=True)\r\n env.animation_parameters(speed=1)\r\n a=sim.Environment(name='piet.')\r\n b=sim.Environment(name='piet.')\r\n c=sim.Environment(name='piet.')\r\n print(a)\r\n print(b)\r\n print(c)\r\n\r\n X(auto_start=False)\r\n X(auto_start=False)\r\n X(auto_start=False)\r\n X()\r\n env.animation_parameters(speed=0.1,video='x.mp4')\r\n env.run(4)\r\n env.run(2)\r\n env.run(4)\r\n\r\n\r\ndef test13():\r\n de=sim.Environment()\r\n q=sim.Queue()\r\n for i in range(10):\r\n c=sim.Component(name='c.')\r\n q.add(c)\r\n\r\n print(q)\r\n for c in q:\r\n print (c.name())\r\n\r\n for i in range(20):\r\n print(i,q[i].name())\r\n\r\n\r\ndef test14():\r\n class X(sim.Component):\r\n def process(self):\r\n yield self.request(*r)\r\n print(self.claimed_resources())\r\n\r\n de=sim.Environment()\r\n X()\r\n r=[sim.Resource() for i in range(10)]\r\n de.run(till=10)\r\n\r\ndef test15():\r\n d=sim.Pdf(('r',1,'c',1))\r\n d=sim.Pdf((1,2,3,4) ,1)\r\n print(d.mean())\r\n s=''\r\n for i in range(100):\r\n x=d.sample()\r\n s=s+str(x)\r\n print(s)\r\n\r\n\r\ndef test16():\r\n de=sim.Environment()\r\n env.animation_parameters()\r\n a=sim.Animate(text='Test',x0=100,y0=100,fontsize0=30,fillcolor0='red')\r\n a=sim.Animate(line0=(0,0,500,500),linecolor0='white',linewidth0=6)\r\n env.run()\r\n\r\n\r\ndef test17():\r\n def actiona():\r\n bb.remove()\r\n sl.remove()\r\n def actionb():\r\n ba.remove()\r\n\r\n de=sim.Environment()\r\n\r\n for x in range(10):\r\n for y in range(10):\r\n a=sim.Animate(rectangle0=(0,0,95,65),x0=5+x*100,y0=5+y*70,fillcolor0='blue',linewidth0=0)\r\n ba=sim.AnimateButton(x=100,y=700,text='A',action=actiona)\r\n bb=sim.AnimateButton(x=200,y=700,text='B',action=actionb)\r\n sl=sim.AnimateSlider(x=300,y=700,width=300)\r\n sim.Animate(text='Text',x0=700,y0=750,font='Times NEWRomian Italic',fontsize0=30)\r\n de.animation_parameters(animate=True)\r\n env.run(5)\r\n env.animation_parameters(animate=False)\r\n env.run(100)\r\n env.animation_parameters(animate=True,background_color='yellow')\r\n env.run(10)\r\n\r\ndef test18():\r\n for j in range(2):\r\n print('---')\r\n r=random.Random(-1)\r\n r1=random.Random(-1)\r\n d=sim.Exponential(3,r1)\r\n sim.Environment(random_seed=-1)\r\n for i in range(3):\r\n print(sim.Exponential(3,r).sample())\r\n print(sim.Exponential(3).sample())\r\n print(d.sample())\r\n\r\ndef test19():\r\n sim.show_fonts()\r\n\r\ndef test20():\r\n de=sim.Environment()\r\n y=650\r\n if Pythonista:\r\n for t in ('TimesNewRomanPSItalic-MT','Times.NewRoman. PSItalic-MT',\r\n 'TimesNewRomanPSITALIC-MT','TimesNoRomanPSItalic-MT'):\r\n sim.Animate(text=t,x0=100,y0=y,font=t,fontsize0=30,anchor='w')\r\n y=y-50\r\n else:\r\n for t in ('Times New Roman Italic','TimesNEWRoman Italic','Times No Roman Italic','timesi','TIMESI'):\r\n sim.Animate(text=t,x0=100,y0=y,font=t,fontsize0=30,anchor='w')\r\n y=y-50\r\n\r\n de.animation_parameters(animate=True)\r\n env.run()\r\n\r\n\r\ndef test21():\r\n# d=sim.Pdf((sim.Uniform(10,20),10,sim.Uniform(20,30),80,sim.Uniform(30,40),10))\r\n d=sim.Pdf((sim.Uniform(10,20),sim.Uniform(20,30),sim.Uniform(30,40)),(10,80,10))\r\n\r\n\r\n for i in range(20):\r\n print (d.sample())\r\n\r\ndef test22():\r\n\r\n class X(sim.Component):\r\n def process(self):\r\n yield self.hold(10)\r\n\r\n class Y(sim.Component):\r\n def process(self):\r\n while True:\r\n yield self.hold(1)\r\n print('status of x=',env.now(),x.status()())\r\n\r\n de=sim.Environment()\r\n x=X()\r\n Y()\r\n\r\n env.run(12)\r\n\r\ndef test23():\r\n sim.a=100\r\n for d in ('uni(12,30)','n(12)','exponentia(a)','TRI(1)','(12)','12',' ( 12, 30) ','a'):\r\n print(d)\r\n print(sim.Distribution(d))\r\n\r\n\r\nif __name__ == '__main__':\r\n test()\r\n","sub_path":"salabim_test.py","file_name":"salabim_test.py","file_ext":"py","file_size_in_byte":63785,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"307206326","text":"\"\"\"empty message\n\nRevision ID: 554425b0fa00\nRevises: baf5c508ff71\nCreate Date: 2018-03-02 15:56:38.857669\n\n\"\"\"\nfrom alembic import op\nimport sqlalchemy as sa\n\n\n# revision identifiers, used by Alembic.\nrevision = '554425b0fa00'\ndown_revision = 'baf5c508ff71'\nbranch_labels = None\ndepends_on = None\n\n\ndef upgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n with op.batch_alter_table('exec_meetings', schema=None) as batch_op:\n batch_op.add_column(sa.Column('datetime_end', sa.DateTime(), nullable=True))\n\n # ### end Alembic commands ###\n\n\ndef downgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n with op.batch_alter_table('exec_meetings', schema=None) as batch_op:\n batch_op.drop_column('datetime_end')\n\n # ### end Alembic commands ###\n","sub_path":"migrations/versions/554425b0fa00_.py","file_name":"554425b0fa00_.py","file_ext":"py","file_size_in_byte":813,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"429661948","text":"\nimport pytest\n\nimport FINE as fn\nimport numpy as np\nimport pandas as pd\n\n\n@pytest.fixture\ndef minimal_test_esM():\n \"\"\"Returns minimal instance of esM\"\"\"\n\n numberOfTimeSteps = 4\n hoursPerTimeStep = 2190\n\n # Create an energy system model instance \n esM = fn.EnergySystemModel(locations={'ElectrolyzerLocation', 'IndustryLocation'}, \n commodities={'electricity', 'hydrogen'}, \n numberOfTimeSteps=numberOfTimeSteps,\n commodityUnitsDict={'electricity': r'kW$_{el}$', 'hydrogen': r'kW$_{H_{2},LHV}$'},\n hoursPerTimeStep=hoursPerTimeStep, costUnit='1 Euro', \n lengthUnit='km', \n verboseLogLevel=1)\n\n # time step length [h]\n timeStepLength = numberOfTimeSteps * hoursPerTimeStep\n\n\n ### Buy electricity at the electricity market\n costs = pd.DataFrame([np.array([ 0.05, 0., 0.1, 0.051,]),np.array([0., 0., 0., 0.,])],\n index = ['ElectrolyzerLocation', 'IndustryLocation']).T\n revenues = pd.DataFrame([np.array([ 0., 0.01, 0., 0.,]),np.array([0., 0., 0., 0.,])],\n index = ['ElectrolyzerLocation', 'IndustryLocation']).T\n maxpurchase = pd.DataFrame([np.array([1e6, 1e6, 1e6, 1e6,]),np.array([0., 0., 0., 0.,])],\n index = ['ElectrolyzerLocation', 'IndustryLocation']).T * hoursPerTimeStep\n esM.add(fn.Source(esM=esM, name='Electricity market', commodity='electricity', \n hasCapacityVariable=False, operationRateMax = maxpurchase,\n commodityCostTimeSeries = costs, \n commodityRevenueTimeSeries = revenues, \n )) # eur/kWh\n\n ### Electrolyzers\n esM.add(fn.Conversion(esM=esM, name='Electrolyzers', physicalUnit=r'kW$_{el}$',\n commodityConversionFactors={'electricity':-1, 'hydrogen':0.7},\n hasCapacityVariable=True, \n investPerCapacity=500, # euro/kW\n opexPerCapacity=500*0.025, \n interestRate=0.08,\n economicLifetime=10))\n\n ### Hydrogen filled somewhere\n esM.add(fn.Storage(esM=esM, name='Pressure tank', commodity='hydrogen',\n hasCapacityVariable=True, capacityVariableDomain='continuous',\n stateOfChargeMin=0.33, \n investPerCapacity=0.5, # eur/kWh\n interestRate=0.08,\n economicLifetime=30))\n\n ### Hydrogen pipelines\n esM.add(fn.Transmission(esM=esM, name='Pipelines', commodity='hydrogen',\n hasCapacityVariable=True,\n investPerCapacity=0.177, \n interestRate=0.08, \n economicLifetime=40))\n\n ### Industry site\n demand = pd.DataFrame([np.array([0., 0., 0., 0.,]), np.array([6e3, 6e3, 6e3, 6e3,]),],\n index = ['ElectrolyzerLocation', 'IndustryLocation']).T * hoursPerTimeStep\n esM.add(fn.Sink(esM=esM, name='Industry site', commodity='hydrogen', hasCapacityVariable=False,\n operationRateFix = demand,\n ))\n\n return esM\n\n\n@pytest.fixture\ndef dsm_test_esM():\n \"\"\"\n Generate a simple energy system model with one node, two fixed generators and one load time series\n for testing demand side management functionality.\n \"\"\"\n # load without dsm\n now = pd.Timestamp.now().round('h')\n number_of_time_steps = 28\n #t_index = pd.date_range(now, now + pd.DateOffset(hours=number_of_timeSteps - 1), freq='h')\n t_index = range(number_of_time_steps)\n load_without_dsm = pd.Series([80.] * number_of_time_steps, index=t_index)\n\n timestep_up = 10\n timestep_down = 20\n load_without_dsm[timestep_up:timestep_down] += 40.\n\n time_shift = 3\n cheap_capacity = 100.\n expensive_capacity = 20.\n\n # set up energy model\n esM = fn.EnergySystemModel(locations={'location'},\n commodities={'electricity'},\n numberOfTimeSteps=number_of_time_steps,\n commodityUnitsDict={'electricity': r'MW$_{el}$'},\n hoursPerTimeStep=1, costUnit='1 Euro',\n lengthUnit='km',\n verboseLogLevel=2)\n esM.add(fn.Source(esM=esM, name='cheap', commodity='electricity', hasCapacityVariable=False,\n operationRateMax=pd.Series(cheap_capacity, index=t_index), opexPerOperation=25))\n esM.add(fn.Source(esM=esM, name='expensive', commodity='electricity', hasCapacityVariable=False,\n operationRateMax=pd.Series(expensive_capacity, index=t_index), opexPerOperation=50))\n esM.add(fn.Source(esM=esM, name='back-up', commodity='electricity', hasCapacityVariable=False,\n operationRateMax=pd.Series(1000, index=t_index), opexPerOperation=1000))\n\n return esM, load_without_dsm, timestep_up, timestep_down, time_shift, cheap_capacity","sub_path":"test/conftest.py","file_name":"conftest.py","file_ext":"py","file_size_in_byte":5201,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"359606067","text":"#!/usr/bin/env python\n# -*- coding:utf-8 -*-\n\n#此为最终结果 已经可以查找到有关键字的文件\n'''\ngrep -rl 'python' /root\n'''\nimport os\n\ndef init(func):\n def wrapper(*args,**kwargs):\n res = func(*args,**kwargs)\n next(res)\n return res\n return wrapper\n\n@init #生成器调用装饰器\ndef search(target):\n '''取出所有文件路径'''\n #更改为生成器\n while True:\n search_path = yield\n g=os.walk(search_path)\n for par_dir,_,files in g:\n for file in files:\n file_abs_path=r'%s\\%s'%(par_dir,file)\n # print('file_abs_path is ==>: ',file_abs_path)\n target.send(file_abs_path)\n#g=search()\n\n#d=r'D:\\code\\py\\py3\\Coursepy'\n#g.send(d)\n\n@init\ndef opener(target):\n while True:\n file_abs_path=yield\n # print('opener==>: ',file_abs_path)\n with open(file_abs_path,encoding='utf-8') as f:\n target.send((file_abs_path,f))\n # pass\n#o=opener()\n#o.__next__\n#o.send('/2.py')\n#g=search(opener()) # 将opener函数传送给search 直接在search函数里直接打开\n#g.send(d) 测试发送文件打开\n\n@init\ndef cat(target):\n '''遍历文件内容'''\n while True:\n file_abs_path,f=yield\n for line in f:\n #print(line)\n # print('file_abs_path & line : ',file_abs_path,line)\n tag=target.send((file_abs_path,line))\n if tag:\n break\n@init\ndef grep(target,pattern):\n\n while True:\n file_abs_path,line=yield tag\n tag=False\n if pattern in line:\n tag=True\n target.send(file_abs_path)\n\n@init\ndef printer():\n while True:\n file_abs_path=yield\n print(file_abs_path)\n\n#将文件路径发送给函数\nxx=r'D:\\code\\py\\py3\\Coursepy\\L05\\a\\b\\b'\nx=r'D:\\code\\py\\py3\\Coursepy\\L05\\a'\ngg=search(opener(cat(grep(printer(),'python'))))\n#print(gg)\ngg.send(x)","sub_path":"L05/yieldAnotherUse.py","file_name":"yieldAnotherUse.py","file_ext":"py","file_size_in_byte":1933,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"143978210","text":"import os\n\nos.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'\nimport tensorflow as tf\nx = tf.placeholder(tf.float32,shape=(),name='x')\ny = tf.placeholder(tf.float32,shape=(),name='y')\n\nw1 = tf.constant(0.5)\nw2 = tf.constant(0.5)\nb = tf.constant(0.75)\n\nA = tf.Variable(0,name='solution')\n\nA = x*w1 + y*w2 > b\n\nsess = tf.InteractiveSession()\n\nprint(sess.run(A, feed_dict={x: 1.0, y: 1.0}))\nprint(sess.run(A, feed_dict={x: 1.0, y: 0.0}))\nprint(sess.run(A, feed_dict={x: 0.0, y: 1.0}))\nprint(sess.run(A, feed_dict={x: 0.0, y: 0.0}))","sub_path":"machine_learning_systems/section_1/AndInTensorFlow.py","file_name":"AndInTensorFlow.py","file_ext":"py","file_size_in_byte":518,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"353470270","text":"import re\nfrom glob import glob\nfrom os.path import basename, join\n\nimport pandas as pd\nimport tabula\n\nimport tools.HelperFunction as hp\n\nclass FishermanMemberAssociation(object):\n def __init__(self, file):\n self.file = file\n self.year = int(basename(self.file)[:4])\n self.pdf = tabula.read_pdf(self.file, encoding='utf-8', stream=True, \n output_format=\"tsv\", silent=True, \n multiple_tables=True, pages=\"all\")\n\n self.col = ['association', '合計-男', '合計-女', '甲類會員-男', '甲類會員-女', \n '乙類會員-男', '乙類會員-女', '贊助會員-男', '贊助會員-女', \n '贊助會員-不分性別 (團體會員)', 'staff'] \n \n def extractRowname(self):\n cn = pd.DataFrame(self.pdf[0].iloc[5:, 0].str.findall(r\"[^A-Z\\s]+\").astype(str).str.strip(\"['']\"))\n cn.rename(columns={0: 'district'}, inplace=True)\n\n return cn.reset_index(drop=True)\n\n def extractValue(self):\n df = self.pdf[0].iloc[5:, 2:].T.reset_index(drop=True).T\n\n page = 0\n value = pd.DataFrame() \n while page < df.shape[0]:\n raw = df.iloc[page, :].tolist()\n remove_na = [' '.join(str(i).replace(\"nan\", \"\") for i in raw)]\n split = [i.split(' ') for i in remove_na]\n\n tmp = pd.DataFrame(pd.Series(split[0]), columns=['value'])\n tmp2 = tmp[tmp['value'] != ''].reset_index(drop=True)\n value = pd.concat([value, tmp2], axis=1)\n page += 1 \n \n return value.T.reset_index(drop=True)\n \n def extractTable(self):\n row = self.extractRowname()\n value = self.extractValue()\n\n table = pd.concat([row, value], axis=1)\n table.rename(columns=dict(zip(table.iloc[:, 1:], self.col)), inplace=True)\n \n return table\n\nclass DataWasher(object):\n def __init__(self, file, table):\n self.file = file\n self.year = int(basename(self.file)[:4])\n self.table = table\n \n def dirtyWork(self):\n asso = self.table[['district', 'association', 'staff']]\n asso['association'] = asso['association'].str.replace(\",\", \"\") \n asso['staff'] = asso['staff'].str.replace(\",\", \"\") \n asso.replace({'-': ''}, inplace=True)\n\n mem = self.table.drop(columns=['association', 'staff'])\n mem2 = pd.melt(mem, id_vars=['district'])\n memCol = mem2.variable.str.split('-', expand=True)\n memCol.rename(columns={0: 'member_class', 1: 'member_sex'}, inplace=True)\n\n member = pd.concat([mem2[['district', 'value']], memCol], axis=1)\n\n final = pd.merge(asso, member, how='inner', on=['district'])\n final.rename(columns={'value': 'member'}, inplace=True)\n final.insert(loc=0, column='year', value=basename(self.file)[:4])\n\n\n final['association'] = final['association'].str.replace(\",\", \"\") \n final['staff'] = final['staff'].str.replace(\",\", \"\") \n final['member'] = final['member'].str.replace(\",\", \"\") \n final.replace({'-': ''}, inplace=True)\n\n final = final[(final['district'].str.contains('臺灣地區') == False) & \n (final['district'].str.contains('金馬地區') == False) &\n (final['district'].str.contains('nan') == False) &\n (final['district'].str.contains('總計') == False) &\n (final['member_class'].str.contains('合計') == False)\n ] \n\n order = ['year', 'district', 'association', 'staff', 'member_class', 'member_sex', 'member']\n final = final[order]\n return final\n\ndef main():\n file_list = glob(\"./raw/漁會及會員數/*\")\n\n df = pd.DataFrame()\n for file in file_list:\n f = FishermanMemberAssociation(file)\n table = f.extractTable()\n\n n = DataWasher(file, table)\n final = n.dirtyWork()\n df = pd.concat([final, df]).sort_values(by=['year', 'district', 'member_class', 'member_sex'])\n \n df.rename(columns={\"year\": \"年份\", \n \"district\": \"縣市別\", \n \"association\": \"漁會數\",\n \"staff\": \"漁會員工\", \n \"member_class\": \"會員等級\", \n \"member_sex\": \"性別\",\n \"member\": \"會員人數\"}, inplace=True)\n\n df.to_csv('./results/漁會及會員數.csv', index=False)\n \nif __name__ == \"__main__\":\n main()","sub_path":"scripts/fisherman_member_association.py","file_name":"fisherman_member_association.py","file_ext":"py","file_size_in_byte":4548,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"445658088","text":"# Copyright Amazon Web Services and its Affiliates. 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# ==============================================================================\nimport math\nimport reprlib\nfrom collections import namedtuple\nfrom tensorflow.core.framework import graph_pb2\nfrom tensorflow.python.framework import dtypes\nfrom tensorflow.python.framework.ops import convert_to_tensor\nfrom tensorflow.python.framework.tensor_shape import TensorShape\nfrom tensorflow.python.platform import tf_logging as logging\nfrom tensorflow.neuron.python.neuron_cc import compile_savetemps\nfrom tensorflow.neuron.python import neff_util\n\n\ntNeuronOp = 'NeuronOp'\ntPlaceholder = 'Placeholder'\nkNeuronInferredShapes = '_aws_neuron_inferred_shapes'\nkOutputShapes = '_output_shapes'\nknExecutable = 'executable'\nknGraphDef = 'graph_def'\nknInputNames = 'input_names'\nknOutputNames = 'output_names'\nknInputDtypes = 'input_dtypes'\nknOutputDtypes = 'output_dtypes'\nknInputShapes = 'input_shapes'\nknOutputShapes = 'output_shapes'\nvInvalidAxis = -1\n\n\ndef normalize_operators(graph_def):\n gd_tensor_name_to_consumers = {}\n gd_tensor_name_to_shape = {}\n for node in graph_def.node:\n for inp in node.input:\n if inp not in gd_tensor_name_to_consumers:\n gd_tensor_name_to_consumers[inp] = []\n gd_tensor_name_to_consumers[inp].append(inp)\n if kOutputShapes in node.attr:\n for idx, shape in enumerate(node.attr[kOutputShapes].list.shape):\n tensor_name = node.name if idx == 0 else '{}:{}'.format(node.name, idx)\n gd_tensor_name_to_shape[tensor_name] = shape\n for node in graph_def.node:\n if node.op == 'StopGradient':\n node.op = 'Identity'\n elif node.op == 'FusedBatchNormV3': # can be replace by FusedBatchNorm for inference\n if node.attr['T'].type != dtypes.float32.as_datatype_enum:\n continue\n found_training_consumer = False\n for idx in range(3, 6):\n gd_tensor_name = '{}:{}'.format(node.name, idx)\n if gd_tensor_name_to_consumers.get(gd_tensor_name, False):\n found_training_consumer = True\n if not found_training_consumer:\n node.op = 'FusedBatchNorm'\n node.attr.pop('U')\n if kOutputShapes in node.attr:\n node.attr[kOutputShapes].list.shape.pop()\n elif node.op == 'AddV2':\n node.op = 'Add'\n elif node.op == 'BatchMatMulV2': # only change to BatchMatMul if no broadcast\n input0, input1 = node.input[0], node.input[1]\n if input0 not in gd_tensor_name_to_shape:\n continue\n if input1 not in gd_tensor_name_to_shape:\n continue\n shape0 = TensorShape(gd_tensor_name_to_shape[input0])\n shape1 = TensorShape(gd_tensor_name_to_shape[input1])\n if shape0.rank is not None and shape0.rank == shape1.rank and shape0[:-2] == shape1[:-2]:\n node.op = 'BatchMatMul'\n return graph_def\n\n\ndef encode_inferred_shapes(graph_def, shape_feed_dict=None):\n if shape_feed_dict is not None:\n name_to_ports = {}\n for tensor_name in shape_feed_dict.keys():\n node_name, port = tensor_name.split(':')\n port = int(port)\n if node_name not in name_to_ports:\n name_to_ports[node_name] = set()\n name_to_ports[node_name].add(port)\n for node in graph_def.node:\n if node.name in name_to_ports:\n inferred_shapes = node.attr[kNeuronInferredShapes].list\n port_set = name_to_ports[node.name]\n max_port = max(port_set)\n for port in range(max_port + 1):\n shape = inferred_shapes.shape.add()\n if port in port_set:\n for size in shape_feed_dict['{}:{}'.format(node.name, port)]:\n shape.dim.add().size = size\n for node in graph_def.node:\n if kOutputShapes in node.attr:\n output_shapes = node.attr[kOutputShapes]\n if all(TensorShape(shape).is_fully_defined() for shape in output_shapes.list.shape):\n node.attr[kNeuronInferredShapes].CopyFrom(output_shapes)\n return graph_def\n\n\ndef shape_inference_with_inputs(graph_def, sess, feed_dict):\n \"\"\"Infer tensor shapes by running inference.\n\n Args:\n graph_def: A tensorflow `GraphDef` protobuf message.\n sess: An active tensorflow Session where we can perform inference to find tensor shapes\n feed_dict: dict `{str: numpy.ndarray}` that maps tensor names to input\n numpy arrays, as used in a full inference with session.run.\n\n Returns:\n A new tensorflow `GraphDef` protobuf message that possibly has NeuronOp's attributes\n `input_shapes` and `output_shapes` filled.\n \"\"\"\n neuron_nodes = get_neuron_nodes(graph_def)\n tensor_name_map = {}\n for node in neuron_nodes:\n for port, name in enumerate(node.attr[knOutputNames].list.s):\n tensor_name_map['{}:{}'.format(node.name, port)] = name.decode()\n need_shape = []\n for node in neuron_nodes:\n input_shapes = node.attr[knInputShapes].list.shape\n output_names = node.attr[knOutputNames].list.s\n output_shapes = node.attr[knOutputShapes].list.shape\n for name, shape_proto in zip(node.input, input_shapes):\n if not TensorShape(shape_proto).is_fully_defined():\n if ':' not in name:\n name = '{}:0'.format(name)\n need_shape.append(tensor_name_map.get(name, name))\n for name, shape_proto in zip(output_names, output_shapes):\n if not TensorShape(shape_proto).is_fully_defined():\n need_shape.append(name.decode())\n need_shape = [sess.graph.get_tensor_by_name(name) for name in need_shape]\n need_shape_infer = []\n for tensor in need_shape:\n if sess.graph.is_fetchable(tensor.op):\n need_shape_infer.append(tensor)\n else:\n logging.warning('cannot infer shape for tensor {}; it is recommended '\n 'to provide its shape in shape_feed_dict'.format(tensor))\n if need_shape_infer:\n tensors_repr = reprlib.Repr()\n tensors_repr.maxlist = 8\n tensors_repr.maxother = 80\n ts_repr_str = tensors_repr.repr(need_shape_infer)\n logging.warning('running inference to find shape for {} ({} tensors)'\n .format(ts_repr_str, len(need_shape_infer)))\n need_shape_infer_np = sess.run(need_shape_infer, feed_dict)\n inferred_shapes = {ts.name: TensorShape(ts_np.shape) for ts, ts_np in zip(need_shape_infer, need_shape_infer_np)}\n for node in neuron_nodes:\n input_shapes = node.attr[knInputShapes].list.shape\n output_names = node.attr[knOutputNames].list.s\n output_shapes = node.attr[knOutputShapes].list.shape\n for idx, (name, shape_proto) in enumerate(zip(node.input, input_shapes)):\n if not TensorShape(shape_proto).is_fully_defined():\n if ':' not in name:\n name = '{}:0'.format(name)\n name = tensor_name_map.get(name, name)\n input_shapes[idx].CopyFrom(inferred_shapes[name].as_proto())\n for idx, (name, shape_proto) in enumerate(zip(output_names, output_shapes)):\n if not TensorShape(shape_proto).is_fully_defined():\n output_shapes[idx].CopyFrom(inferred_shapes[name.decode()].as_proto())\n return graph_def\n\n\ndef convert_shape_to_constant(graph_def):\n name_to_node = {node.name: node for node in graph_def.node}\n for node in graph_def.node:\n if node.op == 'Shape':\n input_name = node.input[0]\n if ':' in input_name:\n input_node_name, index = input_name.split(':')\n index = int(index)\n else:\n input_node_name = input_name\n index = 0\n input_node = name_to_node[input_node_name]\n shape_proto = input_node.attr[kNeuronInferredShapes].list.shape[index]\n shape = TensorShape(shape_proto)\n if shape.is_fully_defined():\n node.op = 'Const'\n node.input[:] = []\n dtype_enum = node.attr['out_type'].type\n node.attr['dtype'].type = dtype_enum\n node.attr.pop('T')\n node.attr.pop('out_type')\n dtype = dtypes.as_dtype(dtype_enum)\n shape_tensor = convert_to_tensor(shape.as_list(), dtype)\n tensor_proto = node.attr['value'].tensor\n tensor_proto.dtype = dtype_enum\n tensor_proto.tensor_shape.CopyFrom(shape_tensor.shape.as_proto())\n tensor_proto.tensor_content = shape_tensor.numpy().tobytes()\n return graph_def\n\n\ndef run_graph_def_pass_in_subgraphs(graph_def, graph_def_pass):\n for node in get_neuron_nodes(graph_def):\n subgraph_def = get_subgraph_def(node)\n subgraph_def = graph_def_pass(subgraph_def)\n node.attr[knGraphDef].s = subgraph_def.SerializeToString()\n return graph_def\n\n\ndef run_compiler_on_subgraphs(graph_def):\n IOTensor = namedtuple('IOTensor', 'name, dtype, shape')\n for node in get_neuron_nodes(graph_def):\n is_compilable, reason = neuron_node_is_compilable(node)\n if not is_compilable:\n logging.warning('Not fusing subgraph {} because {}'.format(node.name, reason))\n continue\n\n # get graph_def and io tensors\n subgraph_def = get_subgraph_def(node)\n inputs = []\n outputs = []\n nal = lambda key: node.attr[key].list\n zip_inputs = zip(nal(knInputNames).s, nal(knInputDtypes).type, nal(knInputShapes).shape)\n zip_outputs = zip(nal(knOutputNames).s, nal(knOutputDtypes).type, nal(knOutputShapes).shape)\n for container, tensors in zip([inputs, outputs], [zip_inputs, zip_outputs]):\n for name, dtype_enum, shape in tensors:\n name = name.decode()\n dtype = dtypes.as_dtype(dtype_enum)\n tensor = IOTensor(name, dtype, shape)\n container.append(tensor)\n\n # remove attributes that are not recognized by neuron-cc\n for sg_node in subgraph_def.node:\n sg_node.attr.pop(kNeuronInferredShapes)\n\n # setup workdir and run neuron-cc\n executable, inputs, outputs = compile_savetemps(subgraph_def, inputs, outputs, node.name)\n if executable:\n node.attr[knExecutable].s = executable\n node.attr[knInputNames].list.s[:] = [ts.name.encode() for ts in inputs]\n node.attr[knOutputNames].list.s[:] = [ts.name.encode() for ts in outputs]\n try:\n input_shuffles = [inp.shuffle for inp in inputs]\n except AttributeError:\n input_shuffles = [None for inp in inputs]\n do_input_shuffles = any(shuffle is not None for shuffle in input_shuffles)\n if do_input_shuffles:\n for shuffle in input_shuffles:\n idx_ts = node.attr['_input_shuffles'].list.tensor.add()\n idx_ts.int64_val.extend(shuffle)\n try:\n input_batch_axis = [ts.batch_axis for ts in inputs]\n output_batch_axis = [ts.batch_axis for ts in outputs]\n except AttributeError:\n pass\n else:\n input_batch_axis = [vInvalidAxis if ax is None else ax for ax in input_batch_axis]\n output_batch_axis = [vInvalidAxis if ax is None else ax for ax in output_batch_axis]\n node.attr['input_batch_axis'].list.i[:] = input_batch_axis\n node.attr['output_batch_axis'].list.i[:] = output_batch_axis\n input_args = node.attr[knInputShapes].list.shape, inputs\n output_args = node.attr[knOutputShapes].list.shape, outputs\n for args in input_args, output_args:\n for shape, ts in zip(*args):\n if [dim.size for dim in shape.dim] != ts.shape:\n for dim, size in zip(shape.dim, ts.shape):\n dim.size = size\n return graph_def\n\n\ndef neuron_node_is_compilable(node):\n reasons = []\n # skip compiling this subgraph for the following reasons\n if len(node.attr[knInputNames].list.s) == 0:\n reasons.append('it does not have inputs')\n if len(node.attr[knOutputNames].list.s) == 0:\n reasons.append('it does not have outputs')\n if any(not TensorShape(shape).is_fully_defined() for shape in node.attr[knInputShapes].list.shape):\n reasons.append('input shapes are not fully defined')\n if any(not TensorShape(shape).is_fully_defined() for shape in node.attr[knOutputShapes].list.shape):\n reasons.append('output shapes are not fully defined')\n if reasons:\n return False, ' and '.join(reasons)\n else:\n return True, None\n\n\ndef restore_compiler_failures(compiled_graph_def, original_graph_def):\n \"\"\"Restore `NeuronOp`'s that failed to compile\n \"\"\"\n neuron_op_dict = {node.name: node for node in get_neuron_nodes(compiled_graph_def)}\n restore_nodes = []\n remove_node_names = set()\n gd_tensor_name_map = {}\n all_expected_node_names = {node.name for node in compiled_graph_def.node if node.op != tNeuronOp}\n for node in get_neuron_nodes(compiled_graph_def):\n if not node.attr[knExecutable].s:\n remove_node_names.add(node.name)\n subgraph_def = get_subgraph_def(node)\n sgd_tensor_name_map = {}\n for gd_ts_name, sg_ph_name in zip(node.input, node.attr[knInputNames].list.s):\n sgd_ph_name = format_tensor_name(sg_ph_name.decode())\n op_name, ts_index = _graph_def_op_index(gd_ts_name)\n if op_name in neuron_op_dict:\n in_node = neuron_op_dict[op_name]\n if not in_node.attr[knExecutable].s:\n gd_ts_name = in_node.attr[knOutputNames].list.s[ts_index].decode()\n sgd_tensor_name_map[sgd_ph_name] = gd_ts_name\n for sg_node in subgraph_def.node:\n for idx, name in enumerate(sg_node.input):\n sg_node.input[idx] = sgd_tensor_name_map.get(name, name)\n if sg_node.op != tPlaceholder:\n restore_nodes.append(sg_node)\n all_expected_node_names.add(sg_node.name)\n for out_idx, out_name in enumerate(node.attr[knOutputNames].list.s):\n out_gd_ts_name = format_tensor_name('{}:{}'.format(node.name, out_idx))\n gd_tensor_name_map[out_gd_ts_name] = format_tensor_name(out_name.decode())\n restore_node_names = {node.name for node in restore_nodes}\n remove_node_names.update(\n node.name for node in compiled_graph_def.node if node.name in restore_node_names)\n original_node_with_control_inputs = get_node_with_control_inputs(original_graph_def)\n for node in restore_nodes:\n if node.name in original_node_with_control_inputs:\n input_names = original_node_with_control_inputs[node.name]\n for name in input_names:\n if name.split(':')[0] in all_expected_node_names:\n node.input.append(name)\n for node in compiled_graph_def.node:\n for idx, name in enumerate(node.input):\n node.input[idx] = gd_tensor_name_map.get(name, name)\n\n graph_def = graph_pb2.GraphDef()\n graph_def.node.extend(\n node for node in compiled_graph_def.node if node.name not in remove_node_names)\n graph_def.node.extend(node for node in restore_nodes)\n\n # remove illegal node names\n node_names = {node.name for node in graph_def.node}\n for node in graph_def.node:\n node.input[:] = [name for name in node.input if _graph_def_op_index(name)[0] in node_names]\n\n # preserve information for function-call operators (e. g., MapDataset)\n graph_def.library.CopyFrom(compiled_graph_def.library)\n return graph_def\n\n\ndef set_execution_plan(compiled_graph_def):\n # scan to get num neuroncores and total number of bytes of input and output tensors\n default_io_buffer_size = 128 * 1024 * 1024\n cpu_extra_ninfer = 1\n num_cores_tuple_map = {}\n mis_config = False\n neuron_nodes = list(get_neuron_nodes(compiled_graph_def))\n for node in neuron_nodes:\n num_cores_tuple = neff_util.get_cores_from_executable(node.attr[knExecutable].s)\n if num_cores_tuple is None:\n mis_config = True\n else:\n opt_num_cores, _ = num_cores_tuple\n num_cores_tuple_map[node.name] = num_cores_tuple\n total_io_bytes = 0\n for node in neuron_nodes:\n model_io_bytes = 0\n for enum, shape in zip(node.attr[knInputDtypes].list.type, node.attr[knInputShapes].list.shape):\n model_io_bytes += dtypes.as_dtype(enum).size * TensorShape(shape).num_elements()\n for enum, shape in zip(node.attr[knOutputDtypes].list.type, node.attr[knOutputShapes].list.shape):\n model_io_bytes += dtypes.as_dtype(enum).size * TensorShape(shape).num_elements()\n if node.name not in num_cores_tuple_map:\n total_io_bytes = 0\n break\n this_opt_num_cores, _ = num_cores_tuple_map[node.name]\n total_io_bytes += model_io_bytes * (this_opt_num_cores + cpu_extra_ninfer) # io size * ninfer\n max_num_duplicates = 1\n if total_io_bytes > 0:\n max_num_duplicates = math.floor(default_io_buffer_size / total_io_bytes)\n max_num_duplicates = min(max_num_duplicates, 4) # use at most 1 MLA (4 cores) by default\n max_num_duplicates = max(max_num_duplicates, 1)\n if mis_config or not num_cores_tuple_map:\n global_opt_num_cores = -1\n max_num_duplicates = 1\n else:\n global_opt_num_cores = max(opt_nc for opt_nc, _ in num_cores_tuple_map.values())\n if len(neuron_nodes) > 1:\n # if there are many NeuronOp's in the graph, then don't do any duplication\n max_num_duplicates = 1\n for node in neuron_nodes:\n if node.name in num_cores_tuple_map:\n this_opt_num_cores, _ = num_cores_tuple_map[node.name]\n else:\n this_opt_num_cores = -1\n # Minimum timeout is 10 sec\n # For big models, we arbitrarily allocate 10 sec quota per 1 GB model size.\n est_timeout = len(node.attr[knExecutable].s) / 1e8\n timeout = max(est_timeout, 10)\n # if this_opt_num_cores is smaller than actual num_cores in runtime, will enforce ninfer==1\n model_config = [global_opt_num_cores, this_opt_num_cores, max_num_duplicates, timeout]\n node.attr['model_config'].list.i[:] = model_config\n return compiled_graph_def\n\n\ndef get_neuron_nodes(graph_def):\n return [node for node in graph_def.node if node.op == tNeuronOp]\n\n\ndef get_subgraph_def(node, volatile=False):\n graph_def = graph_pb2.GraphDef()\n graph_def.ParseFromString(node.attr[knGraphDef].s)\n if volatile:\n erase_large_constants(graph_def)\n return graph_def\n\n\ndef erase_large_constants(graph_def):\n # Destroys the input graph_def! Please don't call it on a graph_def that you'll use later\n large_const_threshold = 1024\n for node in graph_def.node:\n if node.op == 'Const' and node.ByteSize() > large_const_threshold:\n tensor = node.attr['value'].tensor\n tensor.tensor_content = b''\n tensor.bool_val[:] = []\n tensor.dcomplex_val[:] = []\n tensor.double_val[:] = []\n tensor.float_val[:] = []\n tensor.half_val[:] = []\n tensor.int64_val[:] = []\n tensor.int_val[:] = []\n tensor.scomplex_val[:] = []\n tensor.string_val[:] = []\n tensor.uint32_val[:] = []\n tensor.uint64_val[:] = []\n return graph_def\n\n\ndef maybe_relax_placeholder_shapes(graph_def):\n need_relaxation = False\n for node in graph_def.node:\n if node.op == tNeuronOp:\n if any(ax != vInvalidAxis for ax in node.attr['input_batch_axis'].list.i):\n need_relaxation = True\n if need_relaxation:\n for node in graph_def.node:\n if node.op == tPlaceholder:\n dims = node.attr['shape'].shape.dim\n if dims:\n dims[0].size = -1\n return graph_def\n\n\ndef format_tensor_name(tensor_name):\n return tensor_name.split(':')[0] if tensor_name.endswith(':0') else tensor_name\n\n\ndef get_node_with_control_inputs(graph_def):\n node_with_control_inputs = {}\n for node in graph_def.node:\n control_inputs = [inp for inp in node.input if inp.startswith('^')]\n if control_inputs:\n node_with_control_inputs[node.name] = control_inputs\n return node_with_control_inputs\n\n\ndef compiled_graph_op_counts(graph_def):\n neuron_nodes = [node for node in graph_def.node if node.op == tNeuronOp]\n num_ops_on_neuron = 0\n for node in neuron_nodes:\n if node.attr['executable'].s:\n subgraph_def = get_subgraph_def(node)\n num_ops_on_neuron += len(subgraph_def.node) - len(node.attr['input_names'].list.s)\n num_ops_tfn = len(graph_def.node) + num_ops_on_neuron - len(neuron_nodes)\n return max(num_ops_tfn, 0), max(num_ops_on_neuron, 0)\n\n\ndef _graph_def_op_index(graph_def_tensor_name):\n if ':' in graph_def_tensor_name:\n op_name, value_index = graph_def_tensor_name.split(':')\n value_index = int(value_index)\n else:\n op_name, value_index = graph_def_tensor_name, 0\n if op_name.startswith('^'):\n op_name = op_name[1:]\n return op_name, value_index\n","sub_path":"python/graph_def_util.py","file_name":"graph_def_util.py","file_ext":"py","file_size_in_byte":22374,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"356518526","text":"def float_range(precision: int, min: int or float = 0, max: int or float = 1, inclusive: bool = False) -> list:\n \"\"\"Returns a list of floats of certain precision within a defined range.\"\"\"\n\n # Check that the parameters are the correct type and value.\n if type(precision) != int: raise TypeError('\\'precision\\' must be of type int.')\n elif precision < 1 or precision > 8: raise ValueError('\\'precision\\' must be between 1 and 8.')\n elif type(min) != int and type(min) != float: raise TypeError('\\'min\\' must be of type int or float.')\n elif type(max) != int and type(max) != float: raise TypeError('\\'max\\' must be of type int or float.')\n elif type(inclusive) != bool: raise TypeError('\\'inclusive\\' must be of type bool.')\n\n # Return the result of a list comprehension.\n return [float(x) / 10**precision for x in range(int(min * (10**precision)), int(max * (10**precision) + int(inclusive)))]\ndef map2range(value: int or float, inMin: int or float, inMax: int or float, outMin: int or float, outMax: int or float) -> int or float:\n \"\"\"Returns a mapped value to a new range.\"\"\"\n\n # Check that the parameters are the correct type and value.\n if type(value) != int and type(value) != float: raise TypeError('\\'value\\' must be of type int or float.')\n elif type(inMin) != int and type(inMin) != float: raise TypeError('\\'inMin\\' must be of type int or float.')\n elif type(inMax) != int and type(inMax) != float: raise TypeError('\\'inMax\\' must be of type int or float.')\n elif type(outMin) != int and type(outMin) != float: raise TypeError('\\'outMin\\' must be of type int or float.')\n elif type(outMax) != int and type(outMax) != float: raise TypeError('\\'outMax\\' must be of type int or float.')\n elif value < inMin or value > inMax: raise ValueError('\\'value\\' must be in the range of \\'inMin\\' and \\'inMax\\'.')\n\n\n # Return and map the value\n return outMin + (float(value - inMin) / float(inMax - inMin) * outMax - outMin)","sub_path":"myutils/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":1978,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"531311335","text":"# BasicNeuron\n# Richard Nguyen\n# 9 Dec 2018\n#\n# A neuron which learns, given the age and wage of a person\n# whether or not they'll buy a unnamed product (example data)\n\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\n\n# Each tuple represents a person; their age, salary, \n# and whether or not they would buy a eg. a house\nDataF = pd.read_excel(\"dataset.xlsx\",sheet_name='sheet1')\npeopleList = DataF.values\n\n# A person for which only age and salary is known\nperson = [40.0, 80000.0]\n\n# Graph boundaries\nxAXIS = 105000\nyAXIS = 105\n\nfLEARNINGSPEED = 0.02\niITERATIONS = 30000\n\n\n# Plots the cost of \ndef makeCostGraph( fAllCosts ):\n plt.plot(fAllCosts)\n\n\n# Plots the decision boundary and each person onto the scatterplot\ndef make_graph():\n plt.axis([0, yAXIS, 0, xAXIS])\n plt.grid()\n \n # Displays the neural network's decision boundary\n for i in range(0,51):\n for e in range(0, 51):\n col = \"yellow\"\n num = (i/w1Coeff * w1*2) + (e*1000/w2Coeff * w2*2) + b\n ped = neuron(num)\n \n if ped >= 0.5:\n col = \"green\"\n \n plt.scatter(i*2,2*e*1000,c=col)\n \n # Plots each person in the dataset\n for i in range(len(peopleList)):\n point = peopleList[i]\n colour = \"red\"\n\n if point[2] == 1:\n colour = \"blue\"\n\n plt.scatter(point[0], point[1], c = colour) \n \n plt.scatter(person[0], person[1], c = \"purple\")\n \n plt.show()\n\n\n# Prevents hard to work with numbers\ndef getridofe(x):\n if \"e\" in str(x):\n return 0\n else:\n return x\n\n# The sigmoid function\ndef sigmoid(x):\n return getridofe( 1.0 / (1.0 + np.exp(-x)) )\n\n# The derivative of the sigmoid function\ndef sigmoid_deriv(y):\n return sigmoid(y) * (1.0 - sigmoid(y))\n\n\n# Takes in the sum of inputs to the neuron and applies a function (sigmoid)\ndef neuron(x):\n return sigmoid(x)\n\n\n# Calculates coefficients to normalize data (to < 10)\nw1Coeff = 1.0\nw2Coeff = 1.0\nfor i in peopleList:\n while i[0]/w1Coeff > 10:\n w1Coeff *= 10\nfor e in peopleList:\n while e[1]/w2Coeff > 10:\n w2Coeff *= 10\n\n# Neuron related variables\ncostList = []\nw1 = np.random.randn()\nw2 = np.random.randn()\nb = np.random.randn()\n\n\n# Begin training the neuron\nfor i in range(iITERATIONS):\n # Chooses a random person to train with\n rand = np.random.randint(len(peopleList))\n point = peopleList[rand]\n \n inputSum = (point[0]/w1Coeff * w1) + (point[1]/w2Coeff * w2) + b\n\n # What the NN thinks the answer is\n prediction = neuron(inputSum)\n prediction = getridofe(prediction)\n #What the actual answer is\n target = point[2]\n \n # Cost Function\n cost = np.square( prediction - target )\n cost = getridofe(cost)\n\n # Weights are completely off, re-scramble weights\n if cost == 1.0:\n w1 = np.random.randn()\n w2 = np.random.randn()\n b = np.random.randn()\n \n costList.append(cost)\n\n cost_prediction_deriv = 2 * (prediction - target)\n prediction_deriv = sigmoid_deriv(inputSum)\n \n # Derivatives of inputSum with respect to ...\n inputSum_w1_deriv = point[0]/w1Coeff\n inputSum_w2_deriv = point[1]/w2Coeff\n inputSum_b_deriv = 1\n \n # Cost derivatives with respect to ...\n # Move every variable closer to f'(0) = 0 w/ respect to itself\n cost_deriv_w1 = cost_prediction_deriv * prediction_deriv * inputSum_w1_deriv\n cost_deriv_w2 = cost_prediction_deriv * prediction_deriv * inputSum_w2_deriv\n cost_deriv_b = cost_prediction_deriv * prediction_deriv * inputSum_b_deriv\n \n # With each iteration each variable gets closer to f'(0)\n w1 = w1 - (fLEARNINGSPEED * cost_deriv_w1)\n w2 = w2 - (fLEARNINGSPEED * cost_deriv_w2)\n b = b - (fLEARNINGSPEED * cost_deriv_b)\n\n\n# Now that the NN is trained, predict the missing data\ninputSum = (person[0]/w1Coeff * w1) + (person[1]/w2Coeff * w2) + b\nprediction = neuron(inputSum)\n\n\n# Display a graph regarding the cost (inaccuracy*) of the neuron \nplt.figure(1)\nmake_graph()\nplt.figure(2)\nmakeCostGraph(costList)\n\nprint(\"Probability of purchase\")\nprint( round(prediction, 6) )","sub_path":"BasicNeuron.py","file_name":"BasicNeuron.py","file_ext":"py","file_size_in_byte":4162,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"40184780","text":"# -*- coding: utf-8 -*-\n\n\nfrom django.db import models, migrations\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ]\n\n operations = [\n migrations.CreateModel(\n name='CargoMesa',\n fields=[\n ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),\n ('descricao', models.CharField(max_length=50, verbose_name='Cargo na Mesa')),\n ('unico', models.BooleanField(verbose_name='Cargo \\xdanico')),\n ],\n options={\n 'verbose_name': 'Cargo na Mesa',\n 'verbose_name_plural': 'Cargos na Mesa',\n },\n ),\n migrations.CreateModel(\n name='Coligacao',\n fields=[\n ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),\n ('nome', models.CharField(max_length=50, verbose_name='Nome')),\n ('numero_votos', models.IntegerField(null=True, verbose_name='N\\xba Votos Recebidos', blank=True)),\n ],\n options={\n 'verbose_name': 'Coliga\\xe7\\xe3o',\n 'verbose_name_plural': 'Coliga\\xe7\\xf5es',\n },\n ),\n migrations.CreateModel(\n name='ComposicaoColigacao',\n fields=[\n ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),\n ('coligacao', models.ForeignKey(to='parlamentares.Coligacao')),\n ],\n ),\n migrations.CreateModel(\n name='ComposicaoMesa',\n fields=[\n ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),\n ('cargo', models.ForeignKey(to='parlamentares.CargoMesa')),\n ],\n options={\n 'verbose_name': 'Ocupa\\xe7\\xe3o de cargo na Mesa',\n 'verbose_name_plural': 'Ocupa\\xe7\\xf5es de cargo na Mesa',\n },\n ),\n migrations.CreateModel(\n name='Dependente',\n fields=[\n ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),\n ('nome', models.CharField(max_length=50, verbose_name='Nome')),\n ('sexo', models.CharField(max_length=1, verbose_name='Sexo', choices=[(b'F', 'Feminino'), (b'M', 'Masculino')])),\n ('data_nascimento', models.DateField(null=True, verbose_name='Data Nascimento', blank=True)),\n ('cpf', models.CharField(max_length=14, null=True, verbose_name='CPF', blank=True)),\n ('rg', models.CharField(max_length=15, null=True, verbose_name='RG', blank=True)),\n ('titulo_eleitor', models.CharField(max_length=15, null=True, verbose_name='N\\xba T\\xedtulo Eleitor', blank=True)),\n ],\n options={\n 'verbose_name': 'Dependente',\n 'verbose_name_plural': 'Dependentes',\n },\n ),\n migrations.CreateModel(\n name='Filiacao',\n fields=[\n ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),\n ('data', models.DateField(verbose_name='Data Filia\\xe7\\xe3o')),\n ('data_desfiliacao', models.DateField(null=True, verbose_name='Data Desfilia\\xe7\\xe3o', blank=True)),\n ],\n options={\n 'verbose_name': 'Filia\\xe7\\xe3o',\n 'verbose_name_plural': 'Filia\\xe7\\xf5es',\n },\n ),\n migrations.CreateModel(\n name='Legislatura',\n fields=[\n ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),\n ('data_inicio', models.DateField(verbose_name='Data In\\xedcio')),\n ('data_fim', models.DateField(verbose_name='Data Fim')),\n ('data_eleicao', models.DateField(verbose_name='Data Elei\\xe7\\xe3o')),\n ],\n options={\n 'verbose_name': 'Legislatura',\n 'verbose_name_plural': 'Legislaturas',\n },\n ),\n migrations.CreateModel(\n name='Mandato',\n fields=[\n ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),\n ('tipo_causa_fim_mandato', models.IntegerField(null=True, blank=True)),\n ('data_fim_mandato', models.DateField(null=True, verbose_name='Fim do Mandato', blank=True)),\n ('votos_recebidos', models.IntegerField(null=True, verbose_name='Votos Recebidos', blank=True)),\n ('data_expedicao_diploma', models.DateField(null=True, verbose_name='Expedi\\xe7\\xe3o do Diploma', blank=True)),\n ('observacao', models.TextField(null=True, verbose_name='Observa\\xe7\\xe3o', blank=True)),\n ('coligacao', models.ForeignKey(verbose_name='Coliga\\xe7\\xe3o', blank=True, to='parlamentares.Coligacao', null=True)),\n ('legislatura', models.ForeignKey(verbose_name='Legislatura', to='parlamentares.Legislatura')),\n ],\n options={\n 'verbose_name': 'Mandato',\n 'verbose_name_plural': 'Mandatos',\n },\n ),\n migrations.CreateModel(\n name='Municipio',\n fields=[\n ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),\n ('nome', models.CharField(max_length=50, null=True, blank=True)),\n ('uf', models.CharField(blank=True, max_length=2, null=True, choices=[(b'AC', 'Acre'), (b'AL', 'Alagoas'), (b'AP', 'Amap\\xe1'), (b'AM', 'Amazonas'), (b'BA', 'Bahia'), (b'CE', 'Cear\\xe1'), (b'DF', 'Distrito Federal'), (b'ES', 'Esp\\xedrito Santo'), (b'GO', 'Goi\\xe1s'), (b'MA', 'Maranh\\xe3o'), (b'MT', 'Mato Grosso'), (b'MS', 'Mato Grosso do Sul'), (b'MG', 'Minas Gerais'), (b'PR', 'Paran\\xe1'), (b'PB', 'Para\\xedba'), (b'PA', 'Par\\xe1'), (b'PE', 'Pernambuco'), (b'PI', 'Piau\\xed'), (b'RJ', 'Rio de Janeiro'), (b'RN', 'Rio Grande do Norte'), (b'RS', 'Rio Grande do Sul'), (b'RO', 'Rond\\xf4nia'), (b'RR', 'Roraima'), (b'SC', 'Santa Catarina'), (b'SE', 'Sergipe'), (b'SP', 'S\\xe3o Paulo'), (b'TO', 'Tocantins'), (b'EX', 'Exterior')])),\n ('regiao', models.CharField(blank=True, max_length=2, null=True, choices=[(b'CO', 'Centro-Oeste'), (b'NE', 'Nordeste'), (b'NO', 'Norte'), (b'SE', 'Sudeste'), (b'SL', 'Sul'), (b'EX', 'Exterior')])),\n ],\n options={\n 'verbose_name': 'Munic\\xedpio',\n 'verbose_name_plural': 'Munic\\xedpios',\n },\n ),\n migrations.CreateModel(\n name='NivelInstrucao',\n fields=[\n ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),\n ('descricao', models.CharField(max_length=50, verbose_name='N\\xedvel de Instru\\xe7\\xe3o')),\n ],\n options={\n 'verbose_name': 'N\\xedvel Instru\\xe7\\xe3o',\n 'verbose_name_plural': 'N\\xedveis Instru\\xe7\\xe3o',\n },\n ),\n migrations.CreateModel(\n name='Parlamentar',\n fields=[\n ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),\n ('nome_completo', models.CharField(max_length=50, verbose_name='Nome Completo')),\n ('nome_parlamentar', models.CharField(max_length=50, null=True, verbose_name='Nome Parlamentar', blank=True)),\n ('sexo', models.CharField(max_length=1, verbose_name='Sexo', choices=[(b'F', 'Feminino'), (b'M', 'Masculino')])),\n ('data_nascimento', models.DateField(null=True, verbose_name='Data Nascimento', blank=True)),\n ('cpf', models.CharField(max_length=14, null=True, verbose_name='C.P.F', blank=True)),\n ('rg', models.CharField(max_length=15, null=True, verbose_name='R.G.', blank=True)),\n ('titulo_eleitor', models.CharField(max_length=15, null=True, verbose_name='T\\xedtulo de Eleitor', blank=True)),\n ('cod_casa', models.IntegerField()),\n ('numero_gab_parlamentar', models.CharField(max_length=10, null=True, verbose_name='N\\xba Gabinete', blank=True)),\n ('telefone', models.CharField(max_length=50, null=True, verbose_name='Telefone', blank=True)),\n ('fax', models.CharField(max_length=50, null=True, verbose_name='Fax', blank=True)),\n ('endereco_residencia', models.CharField(max_length=100, null=True, verbose_name='Endere\\xe7o Residencial', blank=True)),\n ('cep_residencia', models.CharField(max_length=9, null=True, verbose_name='CEP', blank=True)),\n ('telefone_residencia', models.CharField(max_length=50, null=True, verbose_name='Telefone Residencial', blank=True)),\n ('fax_residencia', models.CharField(max_length=50, null=True, verbose_name='Fax Residencial', blank=True)),\n ('endereco_web', models.CharField(max_length=100, null=True, verbose_name='HomePage', blank=True)),\n ('profissao', models.CharField(max_length=50, null=True, verbose_name='Profiss\\xe3o', blank=True)),\n ('email', models.CharField(max_length=100, null=True, verbose_name='Correio Eletr\\xf4nico', blank=True)),\n ('locais_atuacao', models.CharField(max_length=100, null=True, verbose_name='Locais de Atua\\xe7\\xe3o', blank=True)),\n ('ativo', models.BooleanField(verbose_name='Ativo na Casa?')),\n ('biografia', models.TextField(null=True, verbose_name='Biografia', blank=True)),\n ('unidade_deliberativa', models.BooleanField()),\n ('municipio_residencia', models.ForeignKey(verbose_name='Munic\\xedpio', blank=True, to='parlamentares.Municipio', null=True)),\n ('nivel_instrucao', models.ForeignKey(verbose_name='N\\xedvel Instru\\xe7\\xe3o', blank=True, to='parlamentares.NivelInstrucao', null=True)),\n ],\n options={\n 'verbose_name': 'Parlamentar',\n 'verbose_name_plural': 'Parlamentares',\n },\n ),\n migrations.CreateModel(\n name='Partido',\n fields=[\n ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),\n ('sigla', models.CharField(max_length=9, verbose_name='Sigla')),\n ('nome', models.CharField(max_length=50, verbose_name='Nome')),\n ('data_criacao', models.DateField(null=True, verbose_name='Data Cria\\xe7\\xe3o', blank=True)),\n ('data_extincao', models.DateField(null=True, verbose_name='Data Extin\\xe7\\xe3o', blank=True)),\n ],\n options={\n 'verbose_name': 'Partido',\n 'verbose_name_plural': 'Partidos',\n },\n ),\n migrations.CreateModel(\n name='SessaoLegislativa',\n fields=[\n ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),\n ('numero', models.IntegerField(verbose_name='N\\xfamero')),\n ('tipo', models.CharField(max_length=1, verbose_name='Tipo', choices=[(b'O', 'Ordin\\xe1ria'), (b'E', 'Extraordin\\xe1ria')])),\n ('data_inicio', models.DateField(verbose_name='Data In\\xedcio')),\n ('data_fim', models.DateField(verbose_name='Data Fim')),\n ('data_inicio_intervalo', models.DateField(null=True, verbose_name='In\\xedcio Intervalo', blank=True)),\n ('data_fim_intervalo', models.DateField(null=True, verbose_name='Fim Intervalo', blank=True)),\n ('legislatura', models.ForeignKey(to='parlamentares.Legislatura')),\n ],\n options={\n 'verbose_name': 'Sess\\xe3o Legislativa',\n 'verbose_name_plural': 'Sess\\xf5es Legislativas',\n },\n ),\n migrations.CreateModel(\n name='SituacaoMilitar',\n fields=[\n ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),\n ('descricao', models.CharField(max_length=50, verbose_name='Situa\\xe7\\xe3o Militar')),\n ],\n options={\n 'verbose_name': 'Tipo Situa\\xe7\\xe3o Militar',\n 'verbose_name_plural': 'Tipos Situa\\xe7\\xf5es Militares',\n },\n ),\n migrations.CreateModel(\n name='TipoAfastamento',\n fields=[\n ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),\n ('descricao', models.CharField(max_length=50, verbose_name='Descri\\xe7\\xe3o')),\n ('afastamento', models.BooleanField(verbose_name='Indicador')),\n ('fim_mandato', models.BooleanField(verbose_name='Indicador')),\n ('dispositivo', models.CharField(max_length=50, null=True, verbose_name='Dispositivo', blank=True)),\n ],\n options={\n 'verbose_name': 'Tipo de Afastamento',\n 'verbose_name_plural': 'Tipos de Afastamento',\n },\n ),\n migrations.CreateModel(\n name='TipoDependente',\n fields=[\n ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),\n ('descricao', models.CharField(max_length=50)),\n ],\n options={\n 'verbose_name': 'Tipo de Dependente',\n 'verbose_name_plural': 'Tipos de Dependente',\n },\n ),\n migrations.AddField(\n model_name='parlamentar',\n name='situacao_militar',\n field=models.ForeignKey(verbose_name='Situa\\xe7\\xe3o Militar', blank=True, to='parlamentares.SituacaoMilitar', null=True),\n ),\n migrations.AddField(\n model_name='mandato',\n name='parlamentar',\n field=models.ForeignKey(to='parlamentares.Parlamentar'),\n ),\n migrations.AddField(\n model_name='mandato',\n name='tipo_afastamento',\n field=models.ForeignKey(blank=True, to='parlamentares.TipoAfastamento', null=True),\n ),\n migrations.AddField(\n model_name='filiacao',\n name='parlamentar',\n field=models.ForeignKey(to='parlamentares.Parlamentar'),\n ),\n migrations.AddField(\n model_name='filiacao',\n name='partido',\n field=models.ForeignKey(verbose_name='Partido', to='parlamentares.Partido'),\n ),\n migrations.AddField(\n model_name='dependente',\n name='parlamentar',\n field=models.ForeignKey(to='parlamentares.Parlamentar'),\n ),\n migrations.AddField(\n model_name='dependente',\n name='tipo',\n field=models.ForeignKey(verbose_name='Tipo', to='parlamentares.TipoDependente'),\n ),\n migrations.AddField(\n model_name='composicaomesa',\n name='parlamentar',\n field=models.ForeignKey(to='parlamentares.Parlamentar'),\n ),\n migrations.AddField(\n model_name='composicaomesa',\n name='sessao_legislativa',\n field=models.ForeignKey(to='parlamentares.SessaoLegislativa'),\n ),\n migrations.AddField(\n model_name='composicaocoligacao',\n name='partido',\n field=models.ForeignKey(to='parlamentares.Partido'),\n ),\n migrations.AddField(\n model_name='coligacao',\n name='legislatura',\n field=models.ForeignKey(verbose_name='Legislatura', to='parlamentares.Legislatura'),\n ),\n ]\n","sub_path":"parlamentares/migrations/0001_initial.py","file_name":"0001_initial.py","file_ext":"py","file_size_in_byte":16064,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"359071040","text":"from io import StringIO\nfrom keyword import iskeyword\nfrom tokenize import TokenInfo\nfrom typing import Iterable, Iterator, Tuple, cast\nimport tokenize\n\nimport black\n\nfrom braces.constants import EXCEPT, INDENT, LINE_LENGTH, NEWLINES, TOKEN\n\n__all__ = (\n \"from_tokens\",\n \"into_tokens\",\n \"from_real_tokens\",\n \"into_real_tokens\",\n \"transform\",\n \"transform_back\",\n)\n\n# alright, so we are using a not-really-documented feature\n# from tokenize module here; basically, we can pass (type, value)\n# pairs instead of tokens that handle their position and so on;\n# we are going to get quite a messy output, but this can be easily\n# solved via applying some nifty formatter to the result we get.\n\nEMPTY = \"\"\n\nCOLON = \":\"\n\nSPACE = \" \"\n\nLBRACE = \"{\"\nRBRACE = \"}\"\n\nNEWLINE = \"\\n\"\n\n\nclass Token:\n def __init__(self, type: int, value: str) -> None:\n self.type = type\n self.value = value\n\n def __repr__(self) -> str:\n return f\"{self.__class__.__name__}({self.type}, {self.value!r})\"\n\n def as_tuple(self) -> Tuple[int, str]:\n return (self.type, self.value)\n\n\ndef into_real_tokens(code: str) -> Iterator[TokenInfo]:\n return tokenize.generate_tokens(StringIO(code).readline)\n\n\ndef from_real_tokens(tokens: Iterable[TokenInfo]) -> str:\n return cast(str, tokenize.untokenize(tokens))\n\n\ndef into_tokens(code: str) -> Iterator[Token]:\n for token in into_real_tokens(code):\n yield Token(token.exact_type, token.string)\n\n\ndef from_tokens(tokens: Iterable[Token]) -> str:\n return cast(str, tokenize.untokenize(token.as_tuple() for token in tokens))\n\n\nNOT_SET = -1\n\n\nclass Context:\n def __init__(self, start: int = NOT_SET, end: int = NOT_SET) -> None:\n self.start = start\n self.end = end\n\n @property\n def set(self) -> bool:\n return self.start >= 0 and self.end >= 0\n\n\ndef get_context(start: int = NOT_SET, end: int = NOT_SET) -> Context:\n return Context(start, end)\n\n\nALLOWED_KEYWORDS = {\n \"False\",\n \"True\",\n \"None\",\n \"else\",\n \"except\",\n \"finally\",\n \"lambda\",\n \"try\",\n}\n\n\ndef is_keyword(string: str) -> bool:\n return iskeyword(string) and string not in ALLOWED_KEYWORDS\n\n\ndef transform(code: str, add_lines: bool = False) -> str:\n # we are creating the list here as we need to mutate tokens\n tokens = list(into_tokens(code))\n\n braces = []\n\n previous = None\n\n level = 0\n\n # stage 1: distinguish between braces in code and dictionaries or sets\n\n for token in tokens:\n if token.type == TOKEN.LBRACE: # {\n if (\n not previous\n or previous.type in EXCEPT\n or is_keyword(previous.value)\n ):\n level += 1\n\n else:\n braces.append(token)\n\n if token.type == TOKEN.RBRACE: # }\n if level:\n level -= 1\n\n else:\n braces.append(token)\n\n previous = token\n\n contexts = []\n\n # stage 2: find matching braces\n\n for token in braces:\n if token.type == TOKEN.LBRACE: # {\n contexts.append(get_context(tokens.index(token)))\n\n else:\n for context in reversed(contexts):\n if not context.set:\n context.end = tokens.index(token)\n break\n\n else:\n raise SyntaxError(\"Unmatched braces found.\")\n\n offset = 0\n\n # stage 3: replace braces with appropriate syntax\n\n for indent, context in enumerate(contexts, 1):\n # get values from the context\n start = context.start\n end = context.end\n\n # replace \"{\" with \":\"\n token = tokens[start + offset]\n\n token.type = TOKEN.COLON\n token.value = COLON\n\n # look ahead if next token is \"\\n\" and add if it is not\n offset += 1\n\n token = tokens[start + offset]\n\n if token.type in NEWLINES:\n offset -= 1\n\n else:\n tokens.insert(start + offset, Token(TOKEN.NL, NEWLINE))\n\n # replace \"}\" with dedent\n token = tokens[end + offset]\n\n token.type = TOKEN.DEDENT\n token.value = EMPTY\n\n # insert an indent\n offset += 1\n\n tokens.insert(start + offset, Token(TOKEN.INDENT, INDENT * indent))\n\n offset = 0\n\n # stage 4: find and remove unused semicolons, adding newlines if needed\n\n for index, token in enumerate(tokens.copy()): # copying because we are going to modify tokens\n if token.type == TOKEN.SEMI:\n next = tokens[index - offset + 1]\n\n if next.type in NEWLINES:\n tokens.pop(index - offset)\n offset += 1\n\n else:\n token.type = TOKEN.NL\n token.value = NEWLINE\n\n # stage 5: create code from tokens and format it\n\n code = from_tokens(tokens)\n\n lines = len(code) - len(code.lstrip(NEWLINE)) if add_lines else 0\n\n code = NEWLINE * lines + black.format_str(\n code, mode=black.FileMode(line_length=LINE_LENGTH)\n )\n\n return code\n\n\ndef transform_back(code: str, semicolons: bool = True) -> str:\n ... # TODO: implement this, obviously, when one has time to devote into this library\n","sub_path":"braces/transform.py","file_name":"transform.py","file_ext":"py","file_size_in_byte":5193,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"112520123","text":"from copy import copy\nfrom random import randint\nimport uuid\n\nfrom databases.postgres import insert_statment, fetchone, fetchall\nfrom settings import settings\n\n\nCOLORS = settings[\"COLORS\"]\n\n\nasync def create_game(pool, code_guess=[]):\n code = code_guess or [COLORS[randint(0, len(COLORS) - 1)] for idx in range(4)]\n game_id = str(uuid.uuid4())\n\n query = \"\"\"\n INSERT INTO games_game VALUES (%(game_id)s, %(code)s, %(is_completed)s)\n \"\"\"\n parameters = dict(game_id=game_id, code=code, is_completed=False)\n await insert_statment(pool, query, parameters)\n return parameters\n\n\nasync def validate_game(pool, game_id):\n query = \"\"\"\n SELECT code, is_completed FROM games_game WHERE id = %(game_id)s\n \"\"\"\n parameters = dict(game_id=game_id)\n return await fetchone(pool, query, parameters)\n\n\nasync def save_play(pool, parameters):\n query = \"\"\"\n INSERT INTO games_play (game_id, code, black_pegs, white_pegs) \n VALUES (%(game_id)s, %(current_code)s, %(black_pegs)s, %(white_pegs)s)\n \"\"\"\n await insert_statment(pool, query, parameters)\n\n\nasync def update_finished_game(pool, game_id):\n print(game_id)\n query = \"\"\"\n UPDATE games_game SET is_completed=%(is_completed)s WHERE id=%(game_id)s\n \"\"\"\n parameters = dict(is_completed=True, game_id=game_id)\n await insert_statment(pool, query, parameters)\n\n\nasync def play_round(pool, game_id, target_code, current_code):\n aux_code1, aux_code2 = [], []\n white, black = 0, 0\n for idx, color in enumerate(current_code):\n target_color = target_code[idx]\n if color == target_code[idx]:\n black += 1\n else:\n aux_code1.append(color)\n aux_code2.append(target_color)\n for color in aux_code1:\n if color in aux_code2:\n aux_code2.remove(color)\n white += 1\n\n parameters = dict(\n game_id=game_id, current_code=current_code, white_pegs=white, black_pegs=black\n )\n await save_play(pool, parameters) \n is_completed = False\n\n if black == 4:\n await update_finished_game(pool, game_id)\n is_completed = True\n parameters.update(dict(is_completed=is_completed))\n return parameters\n\n\nasync def get_game(pool, game_id):\n query = \"\"\"\n SELECT \n gp.code, gp.white_pegs, gp.black_pegs, gg.is_completed\n FROM \n games_play gp INNER JOIN games_game gg ON gp.game_id = gg.id\n AND gp.game_id = %(game_id)s\n ORDER BY gp.id ASC\n \"\"\"\n parameters = dict(game_id=game_id)\n return await fetchall(pool, query, parameters)\n","sub_path":"mastermind/mastermind.py","file_name":"mastermind.py","file_ext":"py","file_size_in_byte":2583,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"348525394","text":"\nimport os, sys\n\n# Add the virtual Python environment site-packages directory to the path\nimport site\nsite.addsitedir('/home/django/virtualenvs/extdirect/lib/python2.5/site-packages')\n\nBASE_DIR = os.path.realpath(os.path.dirname(__file__))\nsys.path.insert(0, BASE_DIR)\n\nos.environ['DJANGO_SETTINGS_MODULE'] = 'settings'\n\nimport django.core.handlers.wsgi\n\n_application = django.core.handlers.wsgi.WSGIHandler()\n\n\ndef application(environ, start_response):\n environ['PATH_INFO'] = environ['SCRIPT_NAME'] + environ['PATH_INFO']\n return _application(environ, start_response)\n\n\n","sub_path":"apache.wsgi","file_name":"apache.wsgi","file_ext":"wsgi","file_size_in_byte":586,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"75653716","text":"from django.conf.urls import url\nfrom . import views\n\nurlpatterns = [\n url(r'^dict', views.dict, name=\"dict\"),\n url(r'^links', views.links, name=\"links\"),\n url(r'^queryDictEn', views.queryDictEn, name=\"queryDictEn\"),\n url(r'^queryDictCc', views.queryDictCc, name=\"queryDictCc\"),\n url(r'^blog$', views.blog, name=\"blog\"),\n url(r'^blog/query$', views.blog_query, name=\"blog_query\"),\n url(r'^blog/category$', views.blog_category, name=\"blog_category\"),\n url(r'^blog/add$', views.blog_add, name=\"blog_add\"),\n url(r'^blog/delete$', views.blog_delete, name=\"blog_delete\"),\n url(r'^sendMail', views.send_mail, name=\"send_mail\"),\n url(r'^push$', views.push, name=\"push\"),\n url(r'^Push$', views.Push, name=\"Push\"),\n url(r'^klu$', views.klu, name=\"klu\"),\n url(r'^klu/query$', views.klu_query, name=\"klu_query\"),\n url(r'^klu/delete$', views.klu_delete, name=\"klu_delete\"),\n url(r'^klu/add$', views.klu_add, name=\"klu_add\"),\n url(r'^klu/update$', views.klu_update, name=\"klu_update\"),\n url(r'^qingwu_links$', views.qingwu_links, name=\"qingwu_links\"),\n url(r'^qingwu_links/load$', views.qingwu_links_load, name=\"qingwu_links_load\"),\n url(r'^qingwu_links/add$', views.qingwu_links_add, name=\"qingwu_links_add\"),\n url(r'^qingwu_links/delete$', views.qingwu_links_delete, name=\"qingwu_links_delete\"),\n]\n","sub_path":"api/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1350,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"57484657","text":"# coding: utf-8 \n# @Time : 2020/3/3 下午10:53\n# @File : file_test.py\n# @Author : wenbin\n# @Software: PyCharm\n\n\n# list1 = ['床前明月光', '疑是地上霜', '举头望明月', '低头思故乡']\n# with open('test.txt', mode='r') as file:\n # for i in list1:\n # file.write(i + '\\n')\n # a = 1\n # for i in file:\n # print(i.strip('\\n'))\n # print(a)\n # a += 1\n # a = file.readline()\n # b = file.readline()\n # c = file.readline()\n # d = file.readline()\n # print(a.rstrip('\\n'))\n # print(b.rstrip('\\n'))\n # print(c.rstrip('\\n'))\n # print(d.rstrip('\\n'))f = open(\"⼩娃娃\", mode=\"r+\", encoding=\"utf-8\")\n # content = f.read()\n # f.write(\"麻花藤的最爱\")\n # print(content)\n # f.flush()\n # f.close()\n # pass\n'''\nseek(n):光标移动到n位置,注意,移动的单位是byte,所以如果是UTF-8的中⽂部分要\n是3的倍数。\n通常我们使⽤seek都是移动到开头或者结尾。\n移动到开头: seek(0)\n移动到结尾: seek(0,2) seek的第⼆个参数表⽰的是从哪个位置进⾏偏移,默认是0,表\n⽰开头,1表⽰当前位置,2表⽰结尾。\n'''\n# f = open(\"test1\", mode=\"r+\", encoding=\"utf-8\")\n# content = f.read()\n# f.write(\"\\n麻花藤的最爱\")\n# f.seek(0) # 光标移动到开头\n# print('content:', content)\n# f.seek(0, 2) # 光标移动到末尾\n# content1 = f.read()\n# print('content1:', content1)\n# f.seek(0) # 光标移动到开头\n# f.write('啦啦啦哈哈哈') # 写⼊信息. 此时光标在9 中⽂3 * 3个 = 9\n# index = f.tell()\n# print(index)\n# # 从当前光标读取到的内容\n# content_index = f.read()\n# print('从光标{}读取到的内容:{}'.format(index, content_index))\n# # 光标移动到6位置\n# f.seek(6)\n# # 打印此时光标所在位置\n# current_index = f.tell()\n# print('此时光标所在位置:{}'.format(current_index))\n# # 删除当前光标之后的所有内容\n# f.truncate(9)\n# '''\n# flush() 方法是用来刷新缓冲区的,即将缓冲区中的数据立刻写入文件,同时清空缓冲区,不需要是被动的等待输出缓冲区写入。\n# 一般情况下,文件关闭后会自动刷新缓冲区,但有时你需要在关闭前刷新它,这时就可以使用 flush() 方法。\n# '''\n# # f.flush()\n# # 关闭文件\n# f.close()\n# ⽂件修改\n# import os\n# with open(\"hello\", mode=\"r\", encoding=\"utf-8\") as f1, open(\"hello_new\", mode=\"w\", encoding=\"utf-8\") as f2:\n# content = f1.read()\n# print(content)\n# new_content = content.replace(\"冰糖葫芦\", \"⼤⽩梨\")\n# print(new_content)\n# f2.write(new_content)\n# os.remove(\"hello\") # 删除源⽂件\n# os.rename(\"hello_new\", \"hello_new1\") # 重命名新⽂件\n\n# a = 10\n# def func():\n# a = 40\n# b = 20\n# def abc():\n# print(\"哈哈\")\n# print(a, b) # 这⾥使⽤的是局部作⽤域\n# print(globals()) # 打印全局作⽤域中的内容\n# print(locals()) # 打印局部作⽤域中的内容\n#\n# func()\n# def fun1():\n# print(111)\n# def fun2():\n# print(222)\n# fun1()\n#\n#\n# fun2()\n# print(111)\n#\n#\n# # 函数的嵌套\n# def fun2():\n# print(222)\n# def fun3():\n# print(666)\n# print(444)\n# fun3()\n# print(888)\n# print(33)\n# fun2()\n# print(555)\n\n# global使用\n# a = 100\n# def func1():\n# global a # 加了个global表示该func1方法里的局部变量a被重新声明为全部变量了\n# a = 5 # 对全局变量重新赋值\n# print(a)\n#\n# func1()\n# print(a) # 此时a的值已被重新赋值为5\n#\n# # 不使用global\n# a = 100\n# def func1():\n# a = 5\n# print(a) # 5\n#\n# func1()\n# print(a) # 100\n\n# lst = [\"麻花藤\", \"刘嘉玲\", \"詹姆斯\"]\n# print(lst) # ['麻花藤', '刘嘉玲', '詹姆斯']\n# print(id(lst))\n# def func1():\n# lst.append(\"⻢云云\") # 对于可变数据类型可以直接进⾏修改不用用global来声明为全局变量在进行之后的操作\n# print(lst) # ['麻花藤', '刘嘉玲', '詹姆斯', '⻢云云']\n# print(id(lst))\n#\n#\n# func1()\n# print(lst) # ['麻花藤', '刘嘉玲', '詹姆斯', '⻢云云']\n# print(id(lst))\n\n''' \n加了nonlocal\n30\n30\n不加nonlocal\n30\n20\n'''\n# a = 10\n# def func1():\n# a = 20\n# def func2():\n# nonlocal a\n# a = 30\n# print(a)\n# func2()\n# print(a)\n#\n# func1()\n\n''' \n\n'''\na = 1\ndef fun_1():\n a = 2\n def fun_2():\n nonlocal a\n a = 3\n def fun_3():\n a = 4\n print(a)\n print(a)\n fun_3()\n print(a)\n print(a)\n fun_2()\n print(a)\n\nprint(a)\nfun_1()\nprint(a)","sub_path":"python_basis/file/file_test.py","file_name":"file_test.py","file_ext":"py","file_size_in_byte":4594,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"125107106","text":"#\n# Copyright (c) 2015-2021 Thierry Florac \n# All Rights Reserved.\n#\n# This software is subject to the provisions of the Zope Public License,\n# Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution.\n# THIS SOFTWARE IS PROVIDED \"AS IS\" AND ANY AND ALL EXPRESS OR IMPLIED\n# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS\n# FOR A PARTICULAR PURPOSE.\n#\n\n\"\"\"PyAMS_http_proxy.plugin.monitor module\n\nSmall plug-in module used for monitoring.\n\nThis plug-in doesn't do a real proxy but returns a static response defined into\nit's configuration.\n\"\"\"\n\n__docformat__ = 'restructuredtext'\n\nfrom starlette.responses import JSONResponse, Response\n\nfrom pyams_http_proxy.plugin import ProxyPlugin\nfrom pyams_http_proxy.proxy import LOGGER\n\n\nclass Monitor(ProxyPlugin):\n \"\"\"A small proxy used for service monitoring\"\"\"\n\n config_name = 'monitor'\n\n @staticmethod\n def init_plugin():\n \"\"\"Plugin global initialization\"\"\"\n LOGGER.info(\"Loaded monitoring plug-in\")\n\n @staticmethod\n def init_proxy(base_path, settings):\n \"\"\"Plugin base path initialization\"\"\"\n LOGGER.info(\"Monitoring plug-in init: %s (%s)\", base_path, settings)\n\n @staticmethod\n async def pre_handler(request, config): # pylint: disable=unused-argument\n \"\"\"Logger pre-handler\"\"\"\n return request\n\n @staticmethod\n async def post_handler(request, response, config): # pylint: disable=unused-argument\n \"\"\"Monitor post-handler\"\"\"\n content = config.get('content', None)\n factory = Response if isinstance(content, str) else JSONResponse\n return factory(status_code=config.get('status_code', 200),\n content=content,\n media_type=config.get('media_type', 'text/plain'))\n","sub_path":"src/pyams_http_proxy/plugin/monitor.py","file_name":"monitor.py","file_ext":"py","file_size_in_byte":1888,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"551085483","text":"\"\"\"在一个二维数组中,每一行都按照从左到右递增的顺序排序,\n每一列都按照从上到下递增的顺序排序。请完成一个函数,\n输入这样的一个二维数组和一个整数,判断数组中是否含有该整数。\"\"\"\n\ndef Find(target,array):\n\trows=len(array)\n\tcols=len(array[0])\n\tif rows>0 and cols>0:\n\t\trow=0\n\t\tcol=cols-1\n\t\twhile row=0:\n\t\t\tif target==array[row][col]:\n\t\t\t\treturn True\n\t\t\telif target>array[row][col]:\n\t\t\t\trow+=1\n\t\t\telse:\n\t\t\t\tcol-=1\n\treturn False\n\nif __name__=='__main__':\n\tarray=[[1,2,8,9],[2,4,9,12],[4,7,10,13],[6,8,11,15]]\n\tflag=Find(7, array)\n\tprint(flag)","sub_path":"Test一.py","file_name":"Test一.py","file_ext":"py","file_size_in_byte":630,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"277601629","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Thu Jun 27 23:12:28 2019\n\n@author: yoelr\n\"\"\"\nfrom biosteam import System\nimport biosteam as bst\nimport thermosteam as tmo\nfrom thermosteam import Stream\nfrom biorefineries.cornstover.process_settings import price, ethanol_density_kggal\nfrom biorefineries.cornstover.chemicals import cornstover_chemicals, chemical_groups\nfrom biorefineries.cornstover.tea import CornstoverTEA\nfrom biorefineries.cornstover import units\nimport thermosteam.reaction as rxn\nimport numpy as np\n\nbst.CE = 525.4\nSystem.maxiter = 400\nSystem.converge_method = 'Aitken'\nSystem.molar_tolerance = 0.01\n\nEthanol_MW = cornstover_chemicals.Ethanol.MW\nWater_MW = cornstover_chemicals.Water.MW\n\ndef Ethanol_molfrac(e):\n \"\"\"Return ethanol mol fraction in a ethanol water mixture\"\"\"\n return e/Ethanol_MW / (e/Ethanol_MW + (1-e)/Water_MW)\n\ndef find_split(IDs, flow0, flow1):\n flow0 = np.asarray(flow0)\n splits = flow0/(flow0 + np.asarray(flow1))\n thermo = tmo.settings.get_thermo()\n chemicals = thermo.chemicals\n array = np.zeros(chemicals.size)\n for ID, split in zip(IDs, splits):\n if ID in chemical_groups:\n array[chemicals.get_index(chemical_groups[ID])] = split\n else:\n array[chemicals.index(ID)] = split\n return array\n\n\n# %% Streams\n\nbst.main_flowsheet.set_flowsheet(bst.Flowsheet('cornstover'))\npretreatment_chemical_IDs = ['Acetate', 'AceticAcid', 'Arabinan', 'Ash', 'Cellulase',\n 'Ethanol', 'Extract', 'Furfural', 'Glucan', 'Glucose',\n 'GlucoseOligomer', 'Water', 'H2SO4', 'HMF', 'Lignin',\n 'Mannan', 'NH3', 'Protein', 'SolubleLignin', 'Sucrose',\n 'Xylan', 'Xylose', 'Arabinose', 'XyloseOligomer',\n 'ArabinoseOligomer', 'Mannose', 'MannoseOligomer',\n 'Galactan', 'Galactose', 'GalactoseOligomer']\npretreatment_chemicals = cornstover_chemicals.subgroup(pretreatment_chemical_IDs)\ntmo.settings.set_thermo(pretreatment_chemicals)\n\n# tmo.Stream.default_ID_number = 100\n \n# feed flow\ndry_composition = pretreatment_chemicals.kwarray(\n dict(Glucan=0.3505, Xylan=0.1953, Lignin=0.1576,\n Ash=0.0493, Acetate=0.0181, Protein=0.0310,\n Extract=0.1465, Arabinan=0.0238, Galactan=0.0143,\n Mannan=0.0060, Sucrose=0.0077)\n)\nmoisture_content = pretreatment_chemicals.kwarray(\n dict(Water=0.20)\n)\nnetflow = 104167.0\nfeedflow = netflow*(dry_composition*0.8 + moisture_content)\n\ncornstover = Stream('cornstover',\n feedflow,\n units='kg/hr',\n price=price['Feedstock'])\nwarm_process_water = Stream('warm_process_water',\n T=368.15,\n P=4.7*101325,\n Water=140000,\n units='kg/hr')\nrectifier_bottoms_product = Stream('',\n T=114+273.15,\n P=6.1*101325,\n Ethanol=18,\n Water=36629,\n Furfural=72,\n HMF=100,\n units='kg/hr')\nsulfuric_acid = Stream('sulfuric_acid',\n P=5.4*101325,\n T=294.15,\n Water=139,\n SulfuricAcid=1842,\n units='kg/hr',\n price=price['Sulfuric acid'])\nsteam = Stream('steam',\n phase='g',\n T=268+273.15,\n P=13*101325,\n Water=24534+3490,\n units='kg/hr')\nammonia = Stream('ammonia',\n Ammonia=1051,\n units='kg/hr',\n phase='l',\n price=price['Ammonia'])\ncellulase = Stream('cellulase',\n units='kg/hr',\n price=price['Enzyme'])\n\n# %% Pretreatment system\n\nU101 = units.FeedStockHandling('U101', ins=cornstover)\nU101.cost_items['System'].cost = 0\n\n# tmo.Stream.default_ID_number = 200\n\nT201 = units.SulfuricAcidTank('T201', ins=sulfuric_acid)\nM201 = units.SulfuricAcidMixer('M201', ins=(rectifier_bottoms_product, T201-0))\nM202 = bst.Mixer('M202', ins=(M201-0, warm_process_water, U101-0))\nM203 = units.SteamMixer('M203', ins=(M202-0, steam), P=5.5*101325)\nR201 = units.PretreatmentReactorSystem('R201', ins=M203-0)\nP201 = units.BlowdownDischargePump('P201', ins=R201-1)\nT202 = units.OligomerConversionTank('T202', ins=P201-0)\nF201 = units.PretreatmentFlash('F201', ins=T202-0, P=101325, Q=0)\nM204 = bst.Mixer('M204', ins=(R201-0, F201-0))\nH201 = units.WasteVaporCondenser('H201', ins=M204-0, T=99+273.15, V=0)\nM210 = units.AmmoniaMixer('M210', ins=(ammonia, warm_process_water))\nM205 = bst.Mixer('M205', ins=(F201-1, M210-0))\nT203 = units.AmmoniaAdditionTank('T203', ins=M205-0)\n\n# tmo.Stream.default_ID_number = 300\n\nH301 = units.HydrolysateCooler('H301', ins=T203-0, T=48+273.15)\nM301 = units.EnzymeHydrolysateMixer('M301', ins=(H301-0, cellulase))\n\nsulfuric_acid_over_feed = sulfuric_acid.mol/cornstover.F_mass\ndef update_sulfuric_acid_loading():\n # Also plant air\n F_mass_feed = cornstover.F_mass\n plant_air.mol[0] = 0.8 *F_mass_feed\n sulfuric_acid.mol[:] = sulfuric_acid_over_feed * F_mass_feed\n\nhydrolyzate = F201.outs[1]\nammonia_over_hydrolyzate = ammonia.mol/310026.22446428984\ndef update_ammonia_loading():\n ammonia.mol[:] = ammonia_over_hydrolyzate * hydrolyzate.F_mass\n\ncooled_hydrolyzate = H301.outs[0]\nenzyme_over_cellulose = 20/1000 * 20 # (20 g enzyme / cellulose) / (50 g cellulase / 1 L enzyme)\nwater_cellulase_mass = cellulase.imass['Water', 'Cellulase']\nwater_cellulase_to_cellulase = np.array([0.95, 0.05])\ndef update_cellulase_and_nutrient_loading():\n F_mas_cooled_hydrolyzate = cooled_hydrolyzate.F_mass\n cellulose = cornstover.imass['Glucan']\n # Note: An additional 10% is produced for the media glucose/sophorose mixture\n # Humbird (2011) pg. 37 \n water_cellulase_mass[:] = (enzyme_over_cellulose\n * water_cellulase_to_cellulase\n * cellulose * 1.1)\n DAP1.mol[:] = DAP1_over_hydrolyzate * F_mas_cooled_hydrolyzate\n DAP2.mol[:] = DAP2_over_hydrolyzate * F_mas_cooled_hydrolyzate\n CSL1.mol[:] = CSL1_over_hydrolyzate * F_mas_cooled_hydrolyzate\n CSL2.mol[:] = CSL2_over_hydrolyzate * F_mas_cooled_hydrolyzate\n \npretreatment_sys = System('pretreatment_sys',\n path=(U101, T201, M201, M202, M203,\n R201, P201, T202, F201, M204,\n H201, M210, M205, T203, T203,\n H301,\n M301))\n\n# %% Fermentation system\n\nfermentation_chemical_IDs = ['Acetate', 'AceticAcid', 'Arabinan', 'Ash', 'CO2', 'CSL',\n 'Cellobiose', 'DAP', 'Denaturant', 'Enzyme', 'Ethanol',\n 'Extract', 'Furfural', 'Glucan', 'Glucose', 'GlucoseOligomer', \n 'Glycerol', 'Water', 'H2SO4', 'HMF', 'LacticAcid', 'Lignin',\n 'Mannan', 'NH3', 'O2', 'Protein', 'SolubleLignin',\n 'SuccinicAcid', 'Sucrose', 'Xylan', 'Xylitol', 'Xylose',\n 'XyloseOligomer', 'Z_mobilis', 'Arabinose', 'Mannose',\n 'Galactan', 'Galactose', 'GalactoseOligomer',\n 'ArabinoseOligomer', 'MannoseOligomer']\n\nfermentation_chemicals = cornstover_chemicals.subgroup(fermentation_chemical_IDs)\ntmo.settings.set_thermo(fermentation_chemicals)\n\nDAP1 = Stream('DAP1',\n DAP=26,\n units='kg/hr',\n price=price['DAP'])\nDAP2 = Stream('DAP2',\n DAP=116,\n units='kg/hr',\n price=price['DAP'])\nDAP_storage = units.DAPTank('DAP_storage', ins=Stream('DAP_fresh'), outs='DAP')\n\nS301 = bst.ReversedSplitter('S301', ins=DAP_storage-0, outs=(DAP1, DAP2))\nCSL1 = Stream('CSL1',\n CSL=211,\n units='kg/hr',\n price=price['CSL'])\nCSL2 = Stream('CSL2',\n CSL=948,\n units='kg/hr',\n price=price['CSL'])\nCSL_storage = units.CSLTank('CSL_storage', ins=Stream('CSL_fresh'), outs='CSL')\n\nS302 = bst.ReversedSplitter('S302', ins=CSL_storage-0, outs=(CSL1, CSL2))\ndenaturant = Stream('denaturant',\n Octane=230.69,\n units='kg/hr',\n price=price['Denaturant'])\nstripping_water = Stream('stripping_water',\n Water=26836,\n units='kg/hr')\nDAP1_over_hydrolyzate = DAP1.mol/451077.22446428984\nDAP2_over_hydrolyzate = DAP2.mol/451077.22446428984\nCSL1_over_hydrolyzate = CSL1.mol/451077.22446428984\nCSL2_over_hydrolyzate = CSL2.mol/451077.22446428984\n\nJ1 = upstream=M301-0 - bst.Junction('J1') - Stream()\nM302 = bst.Mixer('M302', ins=(J1-0, None))\nR301 = units.SaccharificationAndCoFermentation('R301', ins=(M302-0, CSL2, DAP2))\nM303 = bst.Mixer('M303', ins=(R301-2, CSL1, DAP1))\nR302 = units.SeedTrain('R302', ins=M303-0)\nT301 = units.SeedHoldTank('T301', ins=R302-1)\nT301-0-1-M302\n\nfermentation_sys = System('fermentation_sys',\n path=(update_cellulase_and_nutrient_loading,\n J1, M302, R301, M303, R302, T301),\n recycle=M302-0)\n\n# %% Ethanol purification\n\nM304 = bst.Mixer('M304', ins=(R302-0, R301-0))\nT302 = units.BeerTank('T302')\n\n# tmo.Stream.default_ID_number = 400\n\nM401 = bst.Mixer('M401', ins=(R301-1, None))\nM401-0-T302\n\nD401 = bst.VentScrubber('D401', ins=(stripping_water, M304-0),\n gas=('CO2', 'NH3', 'O2'))\nD401-1-1-M401\n\n# Heat up before beer column\n# Exchange heat with stillage\nH401 = bst.HXprocess('H401', ins=(T302-0, None),\n fluid_type='ss', U=1.28)\n\n# Beer column\nxbot = Ethanol_molfrac(0.00001)\nytop = Ethanol_molfrac(0.50)\nD402 = bst.BinaryDistillation('D402', ins=H401-0, k=1.25,\n P=101325, y_top=ytop, x_bot=xbot,\n LHK=('Ethanol', 'Water'))\nD402.tray_material = 'Stainless steel 304'\nD402.vessel_material = 'Stainless steel 304'\nD402.BM = 2.4\nD402.boiler.U = 1.85\nP401 = bst.Pump('P401', ins=D402-1)\nP401-0-1-H401\n\n# Mix ethanol Recycle (Set-up)\nM402 = bst.Mixer('M402', ins=(D402-0, None))\n\nytop = Ethanol_molfrac(0.915)\nD403 = bst.BinaryDistillation('D403', ins=M402-0,\n P=101325, y_top=ytop, x_bot=xbot,\n k=1.25, LHK=('Ethanol', 'Water'))\nD403.tray_material = 'Stainless steel 304'\nD403.vessel_material = 'Stainless steel 304'\nD403.is_divided = True\nD403.boiler.U = 1.85\nD403.BM = 2.8\nP402 = bst.Pump('P402', ins=D403-1)\n\nJX = P402-0 - bst.Junction(\"JX\") - 0**M201\n\n# Superheat vapor for mol sieve\nH402 = bst.HXutility('H402', ins=D403-0, T=115+273.15, V=1)\n\n# Molecular sieve\nU401 = bst.MolecularSieve('U401', ins=H402-0,\n split=(2165.14/13356.04, 1280.06/1383.85),\n order=('Ethanol', 'Water'))\n\nU401-0-1-M402\n\nethanol_recycle_sys = System('ethanol_recycle_sys',\n path=(M402, D403, H402, U401),\n recycle=M402-0)\n\n# Condense ethanol product\nH403 = bst.HXutility('H403', ins=U401-1, V=0, T=350.)\n\n# IDnum_400 = tmo.Stream.default_ID_number\n\n# tmo.Stream.default_ID_number = 700\nT701 = bst.StorageTank('T701', ins=H403-0, tau=7*24,\n vessel_type='Floating roof',\n vessel_material='Carbon steel')\nP701 = bst.Pump('P701', ins=T701-0)\n\n# Storage for gasoline\nT702 = bst.StorageTank('T702', ins=denaturant, tau=7*24,\n vessel_type='Floating roof',\n vessel_material='Carbon steel')\nP702 = bst.Pump('P702', ins=T702-0)\n\n# Mix in denaturant\nethanol = Stream('ethanol', price=price['Ethanol'])\nM701 = bst.MixTank('M701', ins=(P702-0, P701-0), outs=ethanol)\nM701.line = 'Mixer'\nM701.tau = 0.05\n\ndef adjust_denaturant():\n denaturant.imol['Octane'] = 0.022*P701.outs[0].F_mass/114.232\n\nP401.BM = P402.BM = P701.BM = P702.BM = 3.1\nT701.BM = T702.BM = 1.7\n\nvent_stream = M304-0\nstripping_water_over_vent = stripping_water.mol / 21202.490455845436\ndef update_stripping_water():\n stripping_water.mol[:] = stripping_water_over_vent * vent_stream.F_mass\n\npuresys = System('purification',\n path=(M304,\n update_stripping_water,\n D401, \n M401, T302,\n H401, D402,\n H401, P401, H401,\n ethanol_recycle_sys,\n P402, H403, T701, P701,\n adjust_denaturant,\n T702, P702, M701, JX))\n\n# %% Lignin Separation\ntmo.settings.set_thermo(cornstover_chemicals)\n\nrecycled_water = tmo.Stream(Water=1,\n T=47+273.15,\n P=3.9*101325,\n units='kg/hr')\n\nsplits = [('Glucose', 19, 502),\n ('Xylose', 40, 1022),\n ('OtherSugars', 81, 2175),\n ('SugarOligomers', 60, 1552),\n ('OrganicSolubleSolids', 612, 15808),\n ('InorganicSolubleSolids', 97, 2513),\n ('Furfurals', 19, 513),\n ('OtherOrganics', 52, 1348),\n ('Glucan', 1230, 25),\n ('Xylan', 415, 8),\n ('OtherStructuralCarbohydrates', 94, 2),\n ('Lignin', 12226, 250),\n ('Protein', 3376, 69),\n ('CellMass', 925, 19),\n ('OtherInsolubleSolids', 4489, 92)]\n\n# tmo.Stream.default_ID_number = IDnum_400\n\nS401 = units.PressureFilter('S401', ins=('', recycled_water),\n moisture_content=0.35,\n split=find_split(*zip(*splits)))\nJ2 = H401-1 - bst.Junction('J2') - 0**S401\n\n# %% Waste water treatment\n\nHvap_water = cornstover_chemicals.Water.Hvap(298.15, 101325)\ncombustion = cornstover_chemicals.get_combustion_reactions()\ndef growth(reactant):\n f = cornstover_chemicals.WWTsludge.MW / getattr(cornstover_chemicals, reactant).MW\n return rxn.Reaction(f\"{f}{reactant} -> WWTsludge\", reactant, 1.)\n \norganic_groups = ['OtherSugars', 'SugarOligomers', 'OrganicSolubleSolids',\n 'Furfurals', 'OtherOrganics', 'Protein', 'CellMass']\norganics = list(sum([chemical_groups[i] for i in organic_groups],\n ('Ethanol', 'AceticAcid', 'Xylose', 'Glucose')))\norganics.remove('WWTsludge')\n\nP_sludge = 0.05/0.91/cornstover_chemicals.WWTsludge.MW\nMW = np.array([cornstover_chemicals.CH4.MW, cornstover_chemicals.CO2.MW])\nmass = np.array([0.51, 0.49])*MW\nmass /= mass.sum()\nmass *= 0.86/(0.91)\nP_ch4, P_co2 = mass/MW\ndef anaerobic_rxn(reactant):\n MW = getattr(cornstover_chemicals, reactant).MW\n return rxn.Reaction(f\"{1/MW}{reactant} -> {P_ch4}CH4 + {P_co2}CO2 + {P_sludge}WWTsludge\",\n reactant, 0.91)\n\n# TODO: Revise this with Jeremy\nanaerobic_digestion = rxn.ParallelReaction([anaerobic_rxn(i) for i in organics] + \n [rxn.Reaction(f\"H2SO4 -> H2S + 2O2\", 'H2SO4', 1.)])\n\n\n# Note, nitogenous species included here, but most of it removed in R601 digester\n# TODO: Add ammonium to reaction, make sure it can be a liquid, possibly add Henry's constant\naerobic_digestion = rxn.ParallelReaction([i*0.74 + 0.22*growth(i.reactant)\n for i in combustion\n if (i.reactant in organics)])\naerobic_digestion.X[:] = 0.96\n\nsplits = [('Ethanol', 1, 15),\n ('Water', 27158, 356069),\n ('Glucose', 3, 42),\n ('Xylose', 7, 85),\n ('OtherSugars', 13, 175),\n ('SugarOligomers', 10, 130),\n ('OrganicSolubleSolids', 182, 2387),\n ('InorganicSolubleSolids', 8, 110),\n ('Ammonia', 48, 633),\n ('AceticAcid', 0, 5),\n ('Furfurals', 5, 70),\n ('OtherOrganics', 9, 113),\n ('Cellulose', 19, 6),\n ('Xylan', 6, 2),\n ('OtherStructuralCarbohydrates', 1, 0),\n ('Lignin', 186, 64),\n ('Protein', 51, 18),\n ('CellMass', 813, 280),\n ('OtherInsolubleSolids', 68, 23)]\n\n# tmo.Stream.default_ID_number = 600\n\nwell_water = Stream('well_water', Water=1, T=15+273.15)\nM601 = bst.Mixer('M601', ins=(S401-1, '', ''))\nJ3 = H201-0 - bst.Junction('J3') - 1**M601\n\nWWTC = units.WasteWaterSystemCost('WWTC', ins=M601-0)\nR601 = units.AnaerobicDigestion('R601', ins=(WWTC-0, well_water),\n reactions=anaerobic_digestion,\n sludge_split=find_split(*zip(*splits)))\n\nair = Stream('air_lagoon', O2=51061, N2=168162, phase='g', units='kg/hr')\ncaustic = Stream('WWT_caustic', Water=2252, NaOH=2252,\n units='kg/hr', price=price['Caustic']*0.5)\n# polymer = Stream('WWT polymer') # Empty in humbird report :-/\n\nM602 = bst.Mixer('M602', ins=(R601-1, None))\n\ncaustic_over_waste = caustic.mol / 2544300.6261793654\nair_over_waste = air.mol / 2544300.6261793654\nwaste = M602-0\ndef update_aerobic_input_streams():\n F_mass_waste = waste.F_mass\n caustic.mol[:] = F_mass_waste * caustic_over_waste\n air.mol[:] = F_mass_waste * air_over_waste\n\nR602 = units.AerobicDigestion('R602', ins=(waste, air, caustic),\n outs=('evaporated_water', ''),\n reactions=aerobic_digestion)\n\nsplits = [('Ethanol', 0, 1),\n ('Water', 381300, 2241169),\n ('Glucose', 0, 2),\n ('Xylose', 1, 3),\n ('OtherSugars', 1, 7),\n ('SugarOligomers', 1, 6),\n ('OrganicSolubleSolids', 79, 466),\n ('InorganicSolubleSolids', 4828, 28378),\n ('Ammonia', 3, 16),\n ('Furfurals', 0, 3),\n ('OtherOrganics', 1, 7),\n ('CarbonDioxide', 6, 38),\n ('O2', 3, 17),\n ('N2', 5, 32),\n ('Cellulose', 0, 194),\n ('Xylan', 0, 65),\n ('OtherStructuralCarbohydrates', 0, 15),\n ('Lignin', 0, 1925),\n ('Protein', 0, 90),\n ('CellMass', 0, 19778),\n ('OtherInsolubleSolids', 0, 707)]\n\nS601 = bst.Splitter('S601', ins=R602-1, split=find_split(*zip(*splits)))\n\nS602 = bst.Splitter('S602', ins=S601-1, split=0.96)\n\nM603 = bst.Mixer('M603', ins=(S602-0, None))\nM603-0-1-M602\n\nM604 = bst.Mixer('M604', ins=(R601-2, S602-1))\n\ncentrifuge_species = ('Water', 'Glucose', 'Xylose', 'OtherSugars',\n 'SugarOligomers', 'OrganicSolubleSolids',\n 'InorganicSolubleSolids', 'Ammonia', 'Furfurals', \n 'OtherOrganics', 'CO2', 'COxSOxNOxH2S', 'Cellulose',\n 'Xylan', 'OtherStructuralCarbohydrates', 'Lignin',\n 'Protein', 'CellMass', 'OtherInsolubleSolids')\nS623_flow = np.array([7708, 0, 0, 1, 1, 13, 75, 3, 0, 1, 1, 2, 25, 8, 2, 250, 52, 1523, 92])\nS616_flow = np.array([109098, 3, 6, 13, 9, 187, 1068, 46, 5, 8, 14, 31, 1, 0, 0, 13, 3, 80, 5])\n\nS603 = bst.Splitter('S603', ins=M604-0, outs=('', 'sludge'),\n split=find_split(centrifuge_species, S616_flow, S623_flow))\nS603-0-1-M603\n\nS604 = bst.Splitter('S604', ins=S601-0, outs=('treated_water', 'waste_brine'),\n split={'Water': 0.987})\n\naerobic_digestion_sys = System('aerobic_digestion_sys',\n path=(M602, update_aerobic_input_streams, R602, S601, S602, M604, S603, M603),\n recycle=M602-0)\n\n# %% Facilities\n\n# tmo.Stream.default_ID_number = 500\n\nM501 = bst.Mixer('M501', ins=(S603-1, S401-0))\nBT = bst.facilities.BoilerTurbogenerator('BT', ins=(M501-0, R601-0), \n turbogenerator_efficiency=0.85)\nBT.outs[-1].T = 373.15\n\n# tmo.Stream.default_ID_number = 700\n\nCWP = bst.facilities.ChilledWaterPackage('CWP')\nCT = bst.facilities.CoolingTower('CT')\nCT.outs[1].T = 273.15 + 28\nwater_thermo = tmo.Thermo(tmo.Chemicals(['Water']))\n\nprocess_water_streams = (caustic,\n stripping_water,\n warm_process_water,\n steam, BT-1, CT-1)\n \nmakeup_water = Stream('makeup_water', thermo=water_thermo, price=price['Makeup water'])\n\nPWC = bst.facilities.ProcessWaterCenter('PWC',\n (S604-0, makeup_water),\n (),\n None,\n (BT-1, CT-1),\n process_water_streams)\nblowdown_mixer = bst.BlowdownMixer('blowdown_mixer', ins=(), outs=2**M601)\nJ4 = BT.outs[-1] - bst.Junction('J4') - 0**blowdown_mixer\nJ5 = CT.outs[1] - bst.Junction('J5') - 1**blowdown_mixer\n\nSubstance = tmo.Chemical.blank('Substance')\nSubstance.at_state(phase='l')\nSubstance.default()\nsubstance_thermo = tmo.Thermo(tmo.Chemicals([Substance]))\nash = Stream('ash', thermo=substance_thermo,\n price=price['Ash disposal'])\nlime = Stream('lime', thermo=substance_thermo,\n price=price['FGD lime'])\nboilerchems = Stream('boiler_chemicals', thermo=substance_thermo,\n price=price['Boiler chems'])\nemission = BT.outs[0]\ndef update_lime_boilerchems_and_ash():\n emission_ash = emission.imol['Ash']\n lime.imol['Substance'] = lime_flow = emission_ash * 0.21\n ash.imol['Substance'] = (emission_ash + lime_flow) * 1.18 # Include lime and other stuff\n boilerchems.imol['Substance'] = 0.24620/865 * lime_flow\n\nCIP = Stream('CIP', thermo=substance_thermo, flow=(126,))\nCIP_package = units.CIPpackage('CIP_package', ins=CIP, thermo=substance_thermo)\n\nplant_air = Stream('plant_air', flow=(83333,), thermo=substance_thermo)\n\nADP = bst.facilities.AirDistributionPackage('ADP', ins=plant_air, thermo=substance_thermo)\n\nFT = units.FireWaterTank('FT',\n ins=Stream('fire_water', flow=(8343,), thermo=substance_thermo),\n thermo=substance_thermo)\n\n# %% Complete system\n\ncornstover_sys = System('cornstover_sys',\n path=(pretreatment_sys, fermentation_sys,\n puresys, J2, S401, J3, M601, WWTC, R601,\n aerobic_digestion_sys, S604),\n facilities=(M501, CWP, BT, CT,\n PWC, ADP, update_lime_boilerchems_and_ash,\n CIP_package, S301, S302, DAP_storage,\n CSL_storage, FT, J4, J5, blowdown_mixer),\n facility_recycle=blowdown_mixer-0)\ncornstover_sys.products.add(ash)\nbaghouse_bags = Stream(ID='Baghouse_bags', thermo=substance_thermo, flow=(1,), price=11.1)\ncornstover_sys.feeds.add(lime)\ncornstover_sys.feeds.add(boilerchems)\ncornstover_sys.feeds.add(baghouse_bags)\nfor i in range(1): cornstover_sys.simulate()\nethanol_tea = CornstoverTEA(\n system=cornstover_sys, \n IRR=0.10, \n duration=(2007, 2037),\n depreciation='MACRS7', \n income_tax=0.35,\n operating_days=350.4,\n lang_factor=None, \n construction_schedule=(0.08, 0.60, 0.32),\n startup_months=3, \n startup_FOCfrac=1,\n startup_salesfrac=0.5,\n startup_VOCfrac=0.75,\n WC_over_FCI=0.05,\n finance_interest=0.08,\n finance_years=10,\n finance_fraction=0.4,\n OSBL_units=(WWTC, CWP, CT, PWC, ADP), # BT not included\n warehouse=0.04, \n site_development=0.09, \n additional_piping=0.045,\n proratable_costs=0.10,\n field_expenses=0.10,\n construction=0.20,\n contingency=0.10,\n other_indirect_costs=0.10, \n labor_cost=2.5e6,\n labor_burden=0.90,\n property_insurance=0.007, \n maintenance=0.03)\nethanol_tea.units.remove(BT)\nethanol_tea.units.remove(U101)\nArea700 = bst.TEA.like(System('Area700', (BT,)),\n ethanol_tea)\nArea700.labor_cost = 0\nArea700.depreciation = 'MACRS20'\nArea700.OSBL_units = (BT,)\ncornstover_tea = bst.CombinedTEA([ethanol_tea, Area700], IRR=0.10)\ncornstover_sys._TEA = cornstover_tea\nethanol.price = cornstover_tea.solve_price(ethanol, ethanol_tea)\nethanol.price = cornstover_tea.solve_price(ethanol, ethanol_tea)\nethanol_price_USDgal = ethanol.price * ethanol_density_kggal\n\n# %% Areas\n\nArea100 = bst.TEA.like(System(None, (U101,)), ethanol_tea)\nArea200 = bst.TEA.like(System(None,\n (T201, M201, R201, P201,\n T202, F201, H201, M210, T203)),\n ethanol_tea)\nArea300 = bst.TEA.like(System(None, \n (H301, M301, R301,\n R302, T301, T302)),\n ethanol_tea)\nArea400 = bst.TEA.like(System(None, \n (D401, H401, D402, P401,\n M402, D403, P402, H402,\n U401, H403, M701, S401)),\n ethanol_tea)\nArea500 = bst.TEA.like(System(None, (WWTC,)),\n ethanol_tea)\nArea600 = bst.TEA.like(System(None,\n (T701, T702, P701, P702, M701, FT,\n CSL_storage, DAP_storage)),\n ethanol_tea) \nArea800 = bst.TEA.like(System(None, (CWP, CT, PWC, ADP, CIP_package)),\n ethanol_tea)\nareas = (Area100, Area200, Area300, Area400,\n Area500, Area600, Area700, Area800)\nnumbered_areas = tuple(enumerate(areas, 1))\ninstallation_costs = {i: j.installation_cost/1e6\n for i,j in numbered_areas}\nutility_costs = {i: j.utility_cost/1e6\n for i,j in numbered_areas}\n\ndef get_utility(units, ID, attr):\n out = 0\n for i in units:\n for j in i.heat_utilities:\n if j.ID == ID:\n out += getattr(j, attr)\n return out\n\nget_rate = lambda units: sum([i.power_utility.rate\n for i in units])/1e3\n\nget_ecost = lambda units: sum([i.power_utility.cost\n for i in units])*24*350.4/1e6\n\ncooling_water_uses = {i: get_utility(j.units, 'Cooling water', 'duty')/1e6/4.184\n for i,j in numbered_areas}\n\nelectricity_uses = {i: get_rate(j.units)/41 for i,j in numbered_areas}\nelectricity_costs = {i: get_ecost(j.units) for i,j in numbered_areas}\n","sub_path":"BioSTEAM 2.x.x/biorefineries/cornstover/system.py","file_name":"system.py","file_ext":"py","file_size_in_byte":26430,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"469078105","text":"# ------------------------------------------------\n# IMPORTS ----------------------------------------\n# ------------------------------------------------\n#####\n# Python dist and 3rd party libraries\n#####\nimport os, requests, json, string, datetime, logging, time\nfrom os.path import join, dirname\nfrom weblogger import addLogEntry\nimport voiceProxySettings\nimport voiceProxyUtilities\n\nlogging_comp_name = \"fromGatewayFilter\"\n#------- From Gateway Filter Methods -----------------\n\n\ndef inputFilters(message):\n\t\n\t\n\t# Need to see if bargin is needed and if so set it\n\tmessage = setBargeIn(message)\n\t\n\t# Set the cisContext Object\n\tmessage = createCisContext(message)\n\t\n\tmessage = preFromGatewayFilter(message)\n\t\n\tmessage = fromGatewayFilter(message)\n\t\n\tmessage = postFromGatewayFilter(message)\n\t\n\treturn message\n\n\n\n\ndef preFromGatewayFilter(message):\n\t# Temp Fix for Gateway\n\tmessage = grabEntitiesIntents(message)\n\t\n\t# Conversation doesn't want intents for some reason\n\tif voiceProxySettings.REMOVE_INTENTS:\n\t\tmessage = voiceProxyUtilities.removeIntents(message)\n\n\tif voiceProxySettings.REMOVE_ENTITIES:\n\t\tmessage = voiceProxyUtilities.removeEntities(message)\n\t\t\t\t\n\treturn message\n\ndef fromGatewayFilter(message):\n\t\n\tif 'context' in message:\n\t\tif 'vgwSessionID' in message['context']:\n\t\t\tlogging.info(\"API Call -> SessionID: \" + message['context']['vgwSessionID'])\n\t\telse:\n\t\t\tlogging.info('API Call -> Serious Error, no vgwSessionID in Context')\n\t\n\t\n\tif voiceProxySettings.CHECK_INPUT_NUMBERS:\n\t\tmessage = check_numbers(message)\n\t\n\t\n\taddLogEntry(voiceProxySettings.APP_NAME_LOGGING, logging_comp_name, 'FromGatewayFilter Method', message)\n\t\n\tlogging.debug(message)\n\t\n\t\n\t# Signal for Conversation Service that messages are coming from Voice Gateway\n\tif 'context' in message:\n\t\tmessage['context']['voiceFlow'] = True\n\n\treturn message\n\ndef postFromGatewayFilter(message):\n\treturn message\n\n#------ End From Gateway Filter Methods ---------------------\n\ndef check_numbers(message):\n\t#look at the input and convert the number words to digits\n\tnum_digit ={}\n\tnum_digit[\"one\"] = \"1\"\n\tnum_digit[\"two\"] = \"2\"\n\tnum_digit[\"to\"] = \"2\"\n\tnum_digit[\"too\"] = \"2\"\n\t\n\tnum_digit[\"three\"] = \"3\"\n\tnum_digit[\"four\"] = \"4\"\n\tnum_digit[\"for\"] = \"4\"\n\t\n\tnum_digit[\"zero\"] = \"0\"\n\tnum_digit[\"five\"] = \"5\"\n\tnum_digit[\"six\"] = \"6\"\n\tnum_digit[\"seven\"] = \"7\"\n\tnum_digit[\"eight\"] = \"8\"\n\tnum_digit[\"nine\"] = \"9\"\n\t\n\tlogging.debug(\"Looking to check for numbers\\n\\n\")\n\t\n\t\n\tphrase = message['input']['text']\n\tlogging.debug(\"Spoken Message: \" + phrase)\n\tnphrase = swap_phrase(num_digit,phrase)\n\tnphrase = nphrase.rstrip()\n\tlogging.debug(\"Cleansed Message: \" + nphrase)\n\tmessage['input']['text'] = nphrase\n\treturn message\n\n\ndef swap_phrase(ssml_dict,phrase):\n\tnphrase = phrase\n\tfor ssml_key in ssml_dict:\n\t\tnphrase = nphrase.replace(ssml_key,ssml_dict[ssml_key])\n\t\n\tlogging.debug(\"Swap returning \" + nphrase)\n\treturn nphrase\n\n\ndef setBargeIn(message):\n\tif 'context' in message:\n\t\tif voiceProxySettings.BARGE_IN_ENABLED:\n\t\t\tmessage['context']['vgwAllowBargeIn'] = 'Yes'\n\t\telse:\t\t\n\t\t\tmessage['context']['vgwAllowBargeIn'] = 'No'\n\t\t\n\treturn message\n\ndef createCisContext(message):\n\tif 'context' in message:\n\t\tif 'cisContext' in message['context']:\n\t\t\treturn message\n\t\telse:\n\t\t\tmessage['context']['cisContext'] = {}\n\t\t\treturn message\n\telse:\n\t\tlogging.warn(\"No Context Object in JSON\")\n\t\treturn message\n\ndef grabEntitiesIntents(message):\n\tif 'context' in message:\n\t\tif 'soeEntities' in message['context']:\n\t\t\tmessage['entities'] = message['context']['soeEntities']\n\t\t\tmessage['context']['soeEntities'] = ''\n\t\tif 'soeIntents' in message['context']:\n\t\t\tmessage['intents'] = message['context']['soeIntents']\n\t\t\tmessage['context']['soeIntents'] = ''\n\treturn message\n\t","sub_path":"jj-voice-gateway/sample.voice.gateway/soe/python/fromGatewayFilter.py","file_name":"fromGatewayFilter.py","file_ext":"py","file_size_in_byte":3713,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"18296247","text":"from math import sqrt, sin\n\ng = 9.8\n\ndef calcula_distancia_do_projetil (v, teta, h):\n g = 9.8\n divisao_a = (v**2/2*g) \n numerador = 2*g*h\n denominador = v**2(sin(teta))**2\n d = divisao_a * (1 + sqrt(1 + numerador/denominador))* sin(2*h)\n return d \n","sub_path":"backup/user_018/ch19_2019_09_16_14_24_58_846726.py","file_name":"ch19_2019_09_16_14_24_58_846726.py","file_ext":"py","file_size_in_byte":266,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"332555897","text":"##############################################################\n# get samples through many local minimum points\n# sampling from enough time distance -> sampling時間が短く相関が強いために誤差関数は単調増加だった\n##############################################################\nimport numpy as np\nfrom scipy import linalg\nimport matplotlib.pyplot as plt\n####################### set parameters ########################\n\"\"\"\" Generate sampring by one MC-step for different beta \"\"\"\n\"\"\" Can I use sampe Theta-Matrix for differnet replicas ? \"\"\"\nnp.random.seed(0)\ndef calc_steady_prob(index_spin, x = [], theta = [[]]):\n a = -0.01 * ( x[index_spin] * np.tensordot(x, theta[index_spin, :], axes = ([0],[0])) - theta[index_spin, index_spin] * x[index_spin] )\n return np.exp(a)\n \ndef beta_power_of_prob(index_spin, beta, x = [], theta = [[]]):\n p_of_x = calc_steady_prob(index_spin, x, theta) \n if(p_of_x != 0):\n a = ( p_of_x ** beta )/( p_of_x ** beta + p_of_x ** (-beta) )\n else:\n a = 0\n return a\n\ndef gibbus_algorithm(beta,index_spin, index_replica, x = [], theta = [[]]):\n x_proposed = x\n x_proposed[index_spin] *= -1\n if( np.random.uniform(size=1) < beta_power_of_prob(index_spin, beta, x_proposed, theta) ):\n return x_proposed\n else:\n return x\n\ndef gen_sample_from_gibbus(index_spin, num_spin, num_replica, beta_min, d_beta, X = [[]], theta = [[]]):\n for index_replica in range(num_replica):\n beta = beta_min + index_replica * d_beta\n X[index_replica,:] = gibbus_algorithm(beta, index_spin, index_replica, X[index_replica,:] , theta)\n #print(\"X=\\n\", X)\n return X\n\ndef replica_exchange(index_spin, index_replica, beta, d_beta,X = [[]] ):\n x1, x2 = X[index_replica, :], X[index_replica + 1, :]\n # r = P(x_k | beta_k+1)P(x_k+1 | beta_k) / P(x_k | beta_k)P(x_k+1 | beta_k+1)\n r = beta_power_of_prob(index_spin, beta + d_beta, x1, theta) * beta_power_of_prob(index_spin, beta, x2, theta) / beta_power_of_prob(index_spin, beta, x1, theta) * beta_power_of_prob(index_spin, beta +d_beta, x2, theta)\n if(np.random.uniform(size=1) < r):\n X[index_replica, :], X[index_replica, :] = np.copy(x2), np.copy(x1)\n return X\n\ndef sum_of_xi_xj_over_num_sample(x_mc_sequence = []):\n num_sample = len(x_mc_sequence)\n return np.tensordot(x_mc_sequence, x_mc_sequence, axes = ([0],[0])) / float(len (x_mc_sequence))\n\n#################################### M A I N ########################################\nif __name__ == \"__main__\":\n num_spin, num_replica = 8, 10 # nuber of spin variable and replica\n beta_min, beta_max = 0.001, 0.01 # inverse temp of min, max\n d_beta = float(beta_max- beta_min) / num_replica\n exchange_interval = 3 # number of mc-steps between exchangings of replica index\n sampling_interval = 9\n num_sample, num_sample_est = 3000, 100 # number of sampling from true, estimated prob\n\n theta = np.arange(1, num_spin + 1)\n theta = np.tensordot(theta[:, np.newaxis], theta[: , np.newaxis], axes = ([1],[1]))\n np.fill_diagonal(theta, 0)\n theta *= 0.01\n #theta = [[0,1,0,0,0,0,0,1],\n # [1,0,1,0,0,0,0,0],\n # [0,1,0,1,0,0,0,0],\n # [0,0,1,0,1,0,0,0],\n # [0,0,0,1,0,1,0,0],\n #[0,0,0,0,1,0,1,0],\n #[0,0,0,0,0,1,0,1],\n #[1,0,0,0,0,0,1,0]]\n #theta = np.array(theta)\n theta_est = np.random.rand(num_spin,num_spin) # create same size of matrix\n x = 2 * np.array(np.random.random_integers(0,1,num_spin) - 0.5)\n X , X_est = np.concatenate(([x],[x]), axis=0), np.concatenate(([x],[x]), axis=0)\n for i in range(num_replica -2):\n X, X_est = np.concatenate((X,[x]), axis=0), np.concatenate((X_est,[x]), axis=0)\n #record sequence of MC-sampling for lagest beta(lowest temperature)\n epoc_theta = 100 # number of epoc\n ypc = 0.1 # C R U C I A L #\n #for estimation of parameter theata-atrix, sum of xi * xj\n\n # sampling from true probability\n index_spin = 0\n mean_xxT = np.zeros((num_spin, num_spin))\n for t in range(num_sample):\n if(t % sampling_interval == 0):\n X = gen_sample_from_gibbus(index_spin, num_spin, num_replica, beta_min,d_beta, X, theta)\n if(t % exchange_interval == 0):\n index_replica = np.random.randint(0, num_replica - 1 )\n beta = beta_min + d_beta * index_replica\n X = replica_exchange(index_spin, index_replica, beta, d_beta, X)\n x_L_beta = np.array( X[num_replica-1, :] ) #it must be done for all replicas\n mean_xxT = mean_xxT + np.tensordot(x_L_beta[:,np.newaxis], x_L_beta[:,np.newaxis], axes = ([1],[1]))\n index_spin = (t) % num_spin\n #print(\"X = \\n\",X)\n #print(\"mean_xxT=\\n\", mean_xxT)\n mean_xxT = ( 1.0 / num_sample) * mean_xxT\n #print(\"final\\nmean_xxT=\\n\",mean_xxT)\n \n # estimation of theta mat\n data = np.zeros(epoc_theta)\n for epoc in range(epoc_theta):\n # reset\n x = 2 * np.array(np.random.random_integers(0,1,num_spin) - 0.5)\n X_est = np.concatenate(([x],[x]), axis=0)\n for i in range(num_replica -2):\n X_est = np.concatenate((X_est,[x]), axis=0)\n \n # sampling from estimated probability\n mean_xxT_est = np.zeros((num_spin, num_spin))\n #print(\"mean_xxT_est = \\n\", mean_xxT_est)\n for t in range(num_sample_est):\n if(t % sampling_interval == 0):\n index_spin = 0\n index_spin = (t) % num_spin\n X_est = gen_sample_from_gibbus(index_spin, num_spin, num_replica, beta_min,d_beta, X_est, theta_est)\n #print(\"X_est = \\n\", X_est)\n if(t % exchange_interval == 0):\n index_replica = np.random.randint(0, num_replica - 1 ) \n beta = beta_min + d_beta * index_replica\n X_est = replica_exchange(index_spin, index_replica, beta, d_beta, X_est)\n x_L_beta = np.array( X_est[num_replica-1, :] ) \n #print(\"x_L_beta = \\n\",x_L_beta)\n A = np.tensordot(x_L_beta[:,np.newaxis], x_L_beta[:,np.newaxis], axes = ([1],[1]))\n mean_xxT_est = mean_xxT_est + A #np.tensordot(x_L_beta[:,np.newaxis], x_L_beta[:,np.newaxis], axes = ([1],[1]))\n #print(\"A = \\n\", A)\n #print(\"mean_xxT_est = \\n\", mean_xxT_est)\n mean_xxT_est = ( 1.0 / num_sample_est) * mean_xxT_est\n #print(\"mean_xxT_est = \\n\", mean_xxT_est)\n #update of tehta-mat by SGD\n #print(\"num_sample_est=\", num_sample_est, \" in roop mean_xxT_est = \\n\", mean_xxT_est)\n theta_est = theta_est - ypc * (-1) * ( mean_xxT - mean_xxT_est ) # (-1) correspond to (- beta ) \n #print(\"\\nmaean_xxT \\n= \", mean_xxT,\" maean_xxT_est \\n= \", mean_xxT_est)\n #print(\"theta \\n= \", theta,\" theta_est \\n= \", theta_est)\n data[epoc] = np.absolute( theta - theta_est ).sum()\n print(data[epoc])\n plt.plot(data)\n plt.ylabel('Error Function', fontsize='20')\n plt.xlabel('theta update-step', fontsize='20')\n plt.show()\n # maybe above process created estimated theta-matrix \n\n","sub_path":"product/test_exmcpara.py","file_name":"test_exmcpara.py","file_ext":"py","file_size_in_byte":7263,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"303697178","text":"import os\nimport math\nimport torch\nimport pandas as pd\nimport numpy as np\nfrom sklearn.model_selection import StratifiedKFold\nfrom sklearn.metrics import accuracy_score, recall_score, precision_score, f1_score, confusion_matrix, precision_recall_fscore_support, classification_report\nfrom transformers import TrainingArguments, Trainer, BertTokenizer, BertForSequenceClassification\n\ndevice = torch.device('cuda' if torch.cuda.is_available() else 'cpu')\nseed = 200\n\n\ndef load_dataframe(config, test = False):\n if test:\n path = os.getcwd() + '/data/no_test.csv' # Always testing on Norwegian dataset\n else:\n path = os.getcwd() + config[\"data_dir\"] + '.csv'\n\n X = config[\"text_column\"]\n y = config[\"target_column\"]\n\n df = pd.read_csv(path)[[X, y]]\n #df = df.sample(frac = 0.03, random_state = seed) #added to test locally w/o all data\n\n if y == \"hateful\":\n df = df[df.hateful != -1]\n df.columns = [\"text\", \"label\"]\n\n return df\n\n\ndef configure_training_set(train, config):\n '''\n Configures training data frame based on config file\n Adds Danish data to the training dataset if translator in [\"translatepy\", \"opus-mt\", \"418M\", \"1.2B\", \"cleaned\"]\n Trains on only Danish data if train_dk in config\n Undersamples to 2/3 majority class and the rest predictive class if undersample in config\n '''\n\n if config[\"translator\"] in [\"translatepy\", \"opus-mt\", \"418M\", \"1.2B\", \"cleaned\"]:\n dk = pd.read_csv(os.getcwd() + '/data/dk.csv')[[config[\"translator\"], config['target_column']]]\n\n if config[\"target_column\"] == \"hateful\":\n dk = dk[dk.hateful != -1]\n\n dk.columns = [\"text\", \"label\"]\n train = pd.concat([train, dk]).sample(frac=1, random_state=seed)\n\n if \"train_dk\" in config:\n train = dk\n\n if 'undersample' in config:\n n_positives = len(train[train[\"label\"] == 1])\n positives = train.iloc[(train[\"label\"] == 1).values]\n negatives = train.iloc[(train[\"label\"] == 0).values].sample(n=n_positives*2)\n train = pd.concat([positives, negatives]).sample(frac=1)\n\n return train\n\n\ndef encode_datasets(train_data, dev_data, test_data, config, summary = True):\n '''\n THIS FUNCTION IS ADOPTED W/ PERMISSION FROM KUMMERVOLD ET AL 2021 (https://github.com/NBAiLab/notram)\n Encodes data into tokens and creates pytorch datasets\n train_dataset: used to train the model\n dev_dataset: data on which to evaluate the loss and any model metrics at the end of each epoch.\n test_data: data to evaluate the model\n '''\n\n tokenizer = BertTokenizer.from_pretrained(config[\"model_name\"])\n\n # Preprocess data\n X_train = list(train_data[\"text\"])\n y_train = list(train_data[\"label\"])\n\n X_val = list(dev_data[\"text\"])\n y_val = list(dev_data[\"label\"])\n X_test = list(test_data[\"text\"])\n\n # X_train, X_val, y_train, y_val = train_test_split(X, y, test_size=0.2)\n X_train_tokenized = tokenizer(X_train, padding=True, truncation=True, max_length=config[\"max_seq_length\"])\n X_val_tokenized = tokenizer(X_val, padding=True, truncation=True, max_length=config[\"max_seq_length\"])\n X_test_tokenized = tokenizer(X_test, padding=True, truncation=True, max_length=config[\"max_seq_length\"])\n\n # Create torch dataset\n class Dataset(torch.utils.data.Dataset):\n def __init__(self, encodings, labels=None):\n self.encodings = encodings\n self.labels = labels\n\n def __getitem__(self, idx):\n item = {key: torch.tensor(val[idx]) for key, val in self.encodings.items()}\n if self.labels:\n item[\"labels\"] = torch.tensor(self.labels[idx])\n return item\n\n def __len__(self):\n return len(self.encodings[\"input_ids\"])\n\n train_dataset = Dataset(X_train_tokenized, y_train)\n dev_dataset = Dataset(X_val_tokenized, y_val)\n test_dataset = Dataset(X_test_tokenized)\n if summary:\n print(\n f'The dataset is imported.\\n\\nThe training dataset has {len(train_dataset)} items.\\nThe development dataset has {len(dev_dataset)} items. \\nThe test dataset has {len(test_dataset)} items')\n steps = math.ceil(len(train_dataset) / config[\"batch_size\"])\n num_warmup_steps = int(0.1 * (steps * config[\"num_epochs\"]))\n print(\n f'You are planning to train for a total of {steps} steps * {config[\"num_epochs\"]} epochs = {config[\"num_epochs\"] * steps} steps. Warmup is {num_warmup_steps}, {math.ceil(100 * num_warmup_steps / (steps * config[\"num_epochs\"]))}%. We recommend at least 10%.')\n print(\"\\n\")\n\n return train_dataset, dev_dataset, test_dataset\n\n\ndef compute_metrics(p):\n '''\n THIS FUNCTION IS ADOPTED W/ PERMISSION FROM KUMMERVOLD ET AL 2021 (https://github.com/NBAiLab/notram)\n Calculates accuracy, precision, and recall\n '''\n pred, labels = p\n pred = np.argmax(pred, axis=1)\n\n accuracy = accuracy_score(y_true=labels, y_pred=pred)\n recall = recall_score(y_true=labels, y_pred=pred)\n precision = precision_score(y_true=labels, y_pred=pred)\n f1 = f1_score(y_true=labels, y_pred=pred)\n\n return {\"accuracy\": accuracy, \"precision\": precision, \"recall\": recall, \"f1\": f1}\n\n\ndef save_model(model, config):\n '''\n Saves fine-tuned model to file specified in model_folder in config\n '''\n print(\"\\n...............................\\n\")\n print(\"Saved model to \" + config[\"model_folder\"])\n print(\"\\n...............................\\n\")\n\n try:\n torch.save(model.model, os.getcwd() + \"/\" + config[\"model_folder\"] + \"model.pth\")\n except:\n print(\"Could not save model\")\n\n\ndef load_model(config):\n '''\n Loads fine-tuned model from file specified in model_folder in config\n '''\n print(\"\\n...............................\\n\")\n print(\"Loading model from \" + config[\"model_folder\"])\n print(\"\\n...............................\\n\")\n model = torch.load(config[\"model_folder\"]+ \"model.pth\")\n\n return model\n\n\ndef fine_tune(config, train_dataset, dev_dataset, save=True):\n '''\n THIS FUNCTION IS PARTLY ADOPTED W/ PERMISSION FROM KUMMERVOLD ET AL 2021 (https://github.com/NBAiLab/notram)\n Fine-tunes model defined in config file on the train_dataset\n '''\n\n steps = round(len(train_dataset) / int(config[\"batch_size\"]))\n num_warmup_steps = round(0.1 * (steps * int(config[\"num_epochs\"])))# 10%\n\n model = BertForSequenceClassification.from_pretrained(config[\"model_name\"], num_labels=2)\n\n # Define Trainer\n args = TrainingArguments(\n report_to=\"none\",\n output_dir=\"output\",\n logging_strategy= \"no\",\n evaluation_strategy=\"no\",\n per_device_train_batch_size=config[\"batch_size\"],\n per_device_eval_batch_size=config[\"batch_size\"],\n learning_rate=config[\"init_lr\"], # The default here is linear decay to 0.\n warmup_steps=num_warmup_steps,\n num_train_epochs=config[\"num_epochs\"],\n save_steps=steps, # Only saves at the end\n seed=0,\n disable_tqdm=True, # Changed to remove statistic reportings to wandb\n )\n\n trainer = Trainer(\n model=model,\n args=args,\n train_dataset=train_dataset,\n eval_dataset=dev_dataset,\n compute_metrics=compute_metrics,\n )\n\n # Train pre-trained model\n trainer.train()\n\n print(f'The training has finished training after {config[\"num_epochs\"]} epochs.')\n if save:\n save_model(trainer, config)\n\n return trainer\n\n\ndef save_predictions(pred, config):\n '''\n Saves predictions to file pred.csv in model_folder specified in config\n '''\n print(\"\\n...............................\\n\")\n print(\"Writing predictions to file pred.csv in \" + config[\"model_folder\"])\n print(\"\\n...............................\\n\")\n try:\n np.savetxt(os.getcwd() + \"/\" + config[\"model_folder\"] + \"pred.csv\", pred, delimiter=\",\")\n except:\n print(\"Could not save predictions....\")\n print(\"..\")\n\n\ndef classify(config, trainer, test_dataset, test_data, print_eval=False, save = True):\n '''\n THIS FUNCTION IS PARTLY ADOPTED W/ PERMISSION FROM KUMMERVOLD ET AL 2021 (https://github.com/NBAiLab/notram)\n Predicts test dataset using the fine-tuned trainer\n config:\n trainer: used to predict class of test data\n test_encodings: encoded text from test dataset used to predict\n test_data: only needed when printing evaluation summary\n '''\n\n raw_pred, _, _ = trainer.predict(test_dataset)\n y_pred_bool = np.argmax(raw_pred, axis=1)\n if save:\n save_predictions(y_pred_bool, config)\n\n if print_eval:\n print(\"\\n...............................\\n\")\n print(\"Evaluations:\")\n print(\"\\n...............................\\n\")\n print(classification_report(test_data[\"label\"], y_pred_bool, digits=4))\n\n return y_pred_bool\n\n\ndef run_bert_evaluation(config):\n '''\n Evaluating the model specified in config. Either from saved pre-trained model or pre-training model from scratch\n Prints evaluations and confusion matrix\n '''\n train = load_dataframe(config)\n dev = train.sample(frac=0.2)\n test = load_dataframe(config, test=True)\n\n print(\"...........................\\n\")\n print(\"Length train: \", len(train))\n print(\"Length test: \", len(test))\n print(\"...........................\\n\")\n\n train = configure_training_set(train, config)\n\n train_dataset, dev_dataset, test_dataset = encode_datasets(train, dev, test, config)\n\n if config[\"trainOrEval\"] == \"train\":\n model = fine_tune(config, train_dataset, dev_dataset)\n elif config[\"trainOrEval\"] == \"eval\":\n model = load_model(config)\n else:\n raise Exception(\"Missing argument: trainOrEval\")\n\n y_pred_bool = classify(config, model, test_dataset, test, print_eval=True)\n cm = confusion_matrix(test[\"label\"], y_pred_bool)\n\n print(\"...........................\\n\")\n print(\"Confusion matrix:\")\n print(cm)\n print(\"...........................\\n\")\n\n\ndef run_bert_cv(config, k_fold=5, summary=True):\n '''\n Running k-fold cross-validation on the training dataset\n k default to 5\n '''\n df = load_dataframe(config)\n\n kf = StratifiedKFold(n_splits=k_fold, random_state=seed, shuffle=True)\n\n f1_macros = []\n p_macros = []\n r_macros = []\n accs = []\n cms = []\n\n folds = 1\n for train_index, val_index in kf.split(X=df[\"text\"], y=df[\"label\"]):\n train = df.iloc[train_index]\n dev = train.sample(frac=0.2)\n test = df.iloc[val_index]\n\n train = configure_training_set(train, config)\n\n train_dataset, dev_dataset, test_dataset = encode_datasets(train, dev, test, config, summary=False)\n\n trainer = fine_tune(config, train_dataset, dev_dataset, save=False)\n\n y_pred_bool = classify(config, trainer, test_dataset, test, print_eval=False, save=False)\n\n p_macro, r_macro, f_macro, support_macro \\\n = precision_recall_fscore_support(y_true=test[\"label\"], y_pred=y_pred_bool, labels=[1, 0], average='macro')\n\n acc = accuracy_score(test[\"label\"], y_pred_bool)\n\n f1_macros.append(f_macro)\n p_macros.append(p_macro)\n r_macros.append(r_macro)\n accs.append(acc)\n\n if folds == 1:\n cm = confusion_matrix(test[\"label\"], y_pred_bool)\n cms = cm\n else:\n cm = confusion_matrix(test[\"label\"], y_pred_bool)\n for i in range(0,len(cm)):\n for j in range(0,len(cms)):\n cms[i][j] += cm[i][j]\n folds += 1\n\n if summary:\n print(\"Results fold\", folds, \": \")\n print(classification_report(test[\"label\"], y_pred_bool, digits=4))\n print()\n print(\"Confusion matrix\")\n print(cm)\n\n print(cms)\n for i in range(len(cms)):\n for j in range(len(cms)):\n cms[i][j] = cms[i][j] / k_fold\n\n print(\"\\n...............................\\n\")\n print(\"Summary of \" + str(k_fold) + \"-fold CV\\n\")\n\n print(\"Accuracy:\", sum(accs) / len(accs))\n print(\"F1 macro:\", sum(f1_macros) / len(f1_macros))\n print(\"Precision macro:\", sum(p_macros) / len(p_macros))\n print(\"Recall macro:\", sum(r_macros) / len(r_macros))\n print(\"Average confusion matrix: \")\n print(cms)\n print(\"\\n...............................\\n\")\n\n return sum(accs) / len(accs), sum(f1_macros) / len(f1_macros), sum(p_macros) / len(p_macros), sum(r_macros) / len(r_macros), cms\n\n\ndef run_hyperparameter_optimization(config, search_params = {'init_lr': [5e-5, 3e-5, 2e-5], 'batch_size': [32, 16], 'num_epochs': [4, 3, 2]}):\n '''\n Hyperparameter optimization.\n Runs 5 fold cross-validation for each possible combination of hyperparameters and prints a summary of the results\n If full_optimize in config, the search corresponds to {'init_lr': [5e-5, 3e-5, 2e-5, 1e-5], 'batch_size': [32, 16, 8], 'num_epochs': [20, 15, 10, 5, 4, 3, 2]}\n If not, the search corresponds to {'init_lr': [5e-5, 3e-5, 2e-5], 'batch_size': [32, 16], 'num_epochs': [4, 3, 2]}\n '''\n max_f1 = 0\n best_f1 = []\n max_acc = 0\n best_acc = []\n\n if \"full_optimize\" in config:\n search_params = {'init_lr': [5e-5, 3e-5, 2e-5, 1e-5], 'batch_size': [32, 16, 8], 'num_epochs': [20, 15, 10, 5, 4, 3, 2]}\n if \"e\" in config:\n search_params['init_lr'] = [config['init_lr']]\n\n\n\n model = 1\n for i in range(len(search_params['init_lr'])):\n init_lr = search_params['init_lr'][i]\n for j in range(len(search_params['batch_size'])):\n batch_size = search_params['batch_size'][j]\n for k in range(len(search_params['num_epochs'])):\n num_epochs = search_params['num_epochs'][k]\n\n print(\"\\n...............................\\n\")\n print(\"Model\", model)\n print(\"Training:\", \"init_lr:\", init_lr, 'batch_size:', batch_size, 'num_epochs:', num_epochs, \"\\n\")\n\n gs_config = {'init_lr': init_lr, 'batch_size': batch_size, 'num_epochs': num_epochs, \"data_dir\": config[\"data_dir\"],\n \"target_column\": config['target_column'], 'text_column': config['text_column'],\n 'end_lr': config['end_lr'], \"max_seq_length\": config[\"max_seq_length\"], \"trainOrEval\": config[\"trainOrEval\"],\n \"translator\": config[\"translator\"], \"model_name\": config[\"model_name\"], \"model_folder\": config[\"model_folder\"]}\n\n if \"train_dk\" in config:\n gs_config[\"train_dk\"] = config[\"train_dk\"]\n if \"undersample\" in config:\n gs_config[\"undersample\"] = config[\"undersample\"]\n # Running 5 fold CV\n acc, f1, p, r, cm = run_bert_cv(gs_config, k_fold=5, summary=False)\n\n\n if acc > max_acc:\n max_acc = acc\n best_acc = [str(init_lr), str(batch_size), str(num_epochs)]\n\n if f1 > max_f1:\n max_f1 = f1\n best_f1 = [str(init_lr), str(batch_size), str(num_epochs)]\n print()\n model += 1\n print('Best model in terms of accuracy: ')\n print('Accuracy:', max_acc)\n print('init_lr:', best_acc[0], 'batch_size:', best_acc[1], 'num_epochs:', best_acc[2])\n print()\n print('Best model in terms of macro f1: ')\n print('F1 Macro:', max_f1)\n print('init_lr:', best_f1[0], 'batch_size:', best_f1[1], 'num_epochs:', best_f1[2])\n print()\n","sub_path":"bert_lib.py","file_name":"bert_lib.py","file_ext":"py","file_size_in_byte":15488,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"296459135","text":"# -*- coding: utf-8 -*-\n#使用requests库获取爬取的页面 \nimport requests\n#从bs4中导入BeautifulSoup,用于解析html页面 \nfrom bs4 import BeautifulSoup \n#导入时间,调用sleep方法,避免频繁爬取信息被频闭\nimport time\n#初始化连接对象、执行对象 \nfrom lxml import etree\nimport random\nimport re\nimport os\n#设置访问的头,伪装浏览器\nheades = [\n \"Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36\",\n \"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_2) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/35.0.1916.153 Safari/537.36\",\n \"Mozilla/5.0 (Windows NT 6.1; WOW64; rv:30.0) Gecko/20100101 Firefox/30.0\",\n \"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_2) AppleWebKit/537.75.14 (KHTML, like Gecko) Version/7.0.3 Safari/537.75.14\",\n \"Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.2; Win64; x64; Trident/6.0)\",\n 'Mozilla/5.0 (Windows; U; Windows NT 5.1; it; rv:1.8.1.11) Gecko/20071127 Firefox/2.0.0.11',\n 'Opera/9.25 (Windows NT 5.1; U; en)',\n 'Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; .NET CLR 1.1.4322; .NET CLR 2.0.50727)',\n 'Mozilla/5.0 (compatible; Konqueror/3.5; Linux) KHTML/3.5.5 (like Gecko) (Kubuntu)',\n 'Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.8.0.12) Gecko/20070731 Ubuntu/dapper-security Firefox/1.5.0.12',\n 'Lynx/2.8.5rel.1 libwww-FM/2.14 SSL-MM/1.4.1 GNUTLS/1.2.9',\n \"Mozilla/5.0 (X11; Linux i686) AppleWebKit/535.7 (KHTML, like Gecko) Ubuntu/11.04 Chromium/16.0.912.77 Chrome/16.0.912.77 Safari/535.7\",\n \"Mozilla/5.0 (X11; Ubuntu; Linux i686; rv:10.0) Gecko/20100101 Firefox/10.0 \"\n]\nresult_ip_list=[]\nip_list = []\n#获取代理\ndef get_ip_list():\n\theaders={ \n 'User-Agent':heades[random.randint(0,10)] \n }\n\tprint(\"正在获取代理列表...\")\n\turl = 'http://www.xicidaili.com/nn/'\n\thtml = requests.get(url=url, headers=headers).text\n\tsoup = BeautifulSoup(html, 'lxml')\n\tips = soup.find(id='ip_list').find_all('tr')\n\tfor i in range(1, len(ips)):\n\t\tip_info = ips[i]\n\t\ttds = ip_info.find_all('td')\n\t\tip_list.append(tds[1].text + ':' + tds[2].text)\n\tprint(\"代理列表抓取成功.\")\n\tfor ip in ip_list:\n\t\tresult_ip_list.append(\"http://\"+ip)\n\t#print(result_ip_list)\n\treturn result_ip_list\ndef get_random_ip():\n\tproxy_ip = random.choice(result_ip_list)\n\tproxies = {'http': proxy_ip}\n\treturn proxies\ndef get_info(url):\n print(url)\n headers={ \n 'User-Agent':heades[random.randint(0,10)] \n } \n #获取动态代理的ip \n proxies = get_random_ip()\n wb_data=requests.get(url, headers=headers,proxies=proxies) \n wb_data.encoding=\"utf-8\"\n html=etree.HTML(wb_data.text)\n result=\"\"\n words=html.xpath(\"/html/body/div[3]/div[2]/div/div[1]/div/div[1]/ul/li/a/text()\")\n words_means=html.xpath(\"/html/body/div[3]/div[2]/div/div[1]/div/div[1]/ul/li/span/text()\")\n for word,word_mean in zip(words,words_means):\n \tword_save=re.sub(\"[^A-Za-z]\",\"\", word)\n \tword_mean=word_mean.strip().replace(\"\\n\",\"\").replace(\"\\r\",\"\")\n \tresult+=word_save+\":\"+word_mean+\"\\n\"\n with open(\"linji.txt\",\"a\",encoding=\"utf-8\") as f:\n \tf.write(result)\n \tf.close()\ndef main():\n\turl=\"\"\n\t#四级228\n\t#六级105\n\tfor i in range(1,106):\n\t\tif i==1:\n\t\t\turl=\"https://www.hujiang.com/ciku/zuixinyingyuliujicihui/\"\n\t\t\t#url=\"https://www.hujiang.com/ciku/zuixinyingyusijicihui/\"\n\t\telse:\n\t\t\t#url=\"https://www.hujiang.com/ciku/zuixinyingyusijicihui_{0}/\".format(i)\n\t\t\turl=\"https://www.hujiang.com/ciku/zuixinyingyuliujicihui_{0}/\".format(i)\n\t\tget_info(url) \n\t\t \n#如果直接使用本文件就执行 \nif __name__=='__main__':\n\t#爬取动态代理ip\n\tget_ip_list()\n\tmain()","sub_path":"基于动态代理爬取沪江四六级英语单词/genWords.py","file_name":"genWords.py","file_ext":"py","file_size_in_byte":3687,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"241320597","text":"import sys\nsys.stdin = open(\"2263_트리의 순회.txt\", \"rt\")\ninput = lambda: sys.stdin.readline()\nsys.setrecursionlimit(10**9)\n\n\nn = int(input())\ninorder = list(map(int, input().split()))\npostorder = list(map(int, input().split()))\n\npos = [0]*(n+1)\nfor i in range(n):\n pos[inorder[i]] = i\n\n\ndef preorder(in_start, in_end, post_start, post_end):\n if in_start > in_end or post_start > post_end:\n return\n\n parent = postorder[post_end]\n print(parent, end=' ')\n left = pos[parent] - in_start\n right = in_end - pos[parent]\n\n preorder(in_start, in_start + left - 1, post_start, post_start + left - 1)\n preorder(in_end - right + 1, in_end, post_end - right, post_end - 1)\n\n\npreorder(0, n-1, 0, n-1)\n","sub_path":"BaekJoon/단계별로 풀어보기/트리/2263_트리의 순회.py","file_name":"2263_트리의 순회.py","file_ext":"py","file_size_in_byte":724,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"350347963","text":"\"\"\"\nMichael S. Emanuel\nThu Apr 26 10:59:27 2018\n\nPrime power triples\nProblem 87\n\nThe smallest number expressible as the sum of a prime square, prime cube, and prime fourth power\nis 28. In fact, there are exactly four numbers below fifty that can be expressed in such a way:\n\n28 = 2^2 + 2^3 + 2^4\n33 = 3^2 + 2^3 + 2^4\n49 = 5^2 + 2^3 + 2^4\n47 = 2^2 + 3^3 + 2^4\n\nHow many numbers below fifty million can be expressed as the sum of a\nprime square, prime cube, and prime fourth power?\n\nSolution Outline:\nLet p, q, r be three primes (not necessarilty distinct) such that\np^2 + q^3 + r^3 < M\nSince q and r both > 0, p^2 < M and p < sqrt(M)\nSince r > 0, q^3 < M - p^2 --> q < cubeRoot(M - p^2)\n# r^4 < M - p^2 - q^3 --> r < fourthRoot(M - p^2 - q^3)\n\"\"\"\n\nfrom math import ceil, sqrt\nfrom Euler.Utility import range_inc\nfrom Euler.Primes import PrimeTable\nfrom typing import List, Tuple\n\n# Type aliases\npptType = Tuple[int, Tuple[int, int, int]]\npptListType = List[pptType]\n\n\ndef findPrimePowerTriples(M: int, pt: PrimeTable) -> pptListType:\n \"\"\"Find all prime power triples with sum below threshold M\"\"\"\n # List of prime power triples\n # One entry is (n, (p, q, r))\n ppt: pptListType = []\n # Set upper bounds on three primes p, q, r\n pMax: int = ceil(M ** (1.0 / 2))\n qMax: int = ceil(M ** (1.0 / 3))\n rMax: int = ceil(M ** (1.0 / 4))\n # Primes used in loop\n p: int\n q: int\n r: int\n # Sum of p^2 + q^3 + r^3\n n: int\n # Iterate over primes p. pi is the prime index of p\n piMax: int = pt.primeIndex(pMax) - (1 if pt.isPrime(pMax) else 0)\n for pi in range_inc(piMax):\n # The prime p\n p = pt.nthPrime(pi)\n # Compute p^2 once for the loops below\n p2: int = p**2\n # Set the maximum value of q given this choice of p\n qMax = ceil((M - p2) ** (1.0 / 3))\n # Iterate over primes q. qi is the prime index of q\n qiMax: int = pt.primeIndex(qMax) - (1 if pt.isPrime(pMax) else 0)\n for qi in range_inc(qiMax):\n # The prime q\n q = pt.nthPrime(qi)\n # Compute q^3 once for the loop below\n q3: int = q**3\n # Set the maximum value of r given choices of p, q\n rMax = ceil((M - p2 - q3) ** (1.0 / 4))\n riMax: int = pt.primeIndex(rMax) - (1 if pt.isPrime(pMax) else 0)\n # Iterate over primes r. ri ins the prime index of r\n for ri in range_inc(riMax):\n # The prime r\n r = pt.nthPrime(ri)\n r4: int = r**4\n # Compute the sum n of prime powers\n n = p2 + q3 + r4\n # Append n and (p,q,r) if n below the threshold\n if n < M:\n ppt.append((n, (p, q, r)))\n return ppt\n\n\ndef main() -> int:\n # Upper bound on exploration\n M: int = 50 * 10**6\n # Upper bound on prime p (for sizing prime table)\n pMax: int = ceil(sqrt(M))\n # Build primes up to pMax\n pt: PrimeTable = PrimeTable(pMax)\n # Find primes power triples up to M\n ppt: pptListType = findPrimePowerTriples(M, pt)\n # Extract list of summands n\n ns: List[int] = [pt[0] for pt in ppt]\n # Remove duplicates from n\n ns = sorted(list(set(ns)))\n # The answer is the number of discovered prime power sums\n ans: int = len(ns)\n # Print the answer\n print(f'The answer is {ans}.')\n return ans\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"Prob087_PrimePowerTriples.py","file_name":"Prob087_PrimePowerTriples.py","file_ext":"py","file_size_in_byte":3427,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"508409529","text":"#!/usr/bin/env python3\nimport struct\nimport matplotlib.pyplot as plt\n\nPRIORITY_MASK = 0x1C000000\nPDU_FORMAT_MASK = 0x00FF0000\nPDU_SPECIFIC_MASK = 0x0000FF00 \nSOURCE_ADDRESS_MASK = 0x000000FF \nDATA_PAGE_MASK = 0x01000000 \nEXT_DATA_PAGE_MASK = 0x02000000 \nPDU1_PGN_MASK = 0x03FF0000 \nPDU2_PGN_MASK = 0x03FFFF00\n\nPRIORITY_OFFSET = 26 \nPDU_FORMAT_OFFSET = 16 \nDA_OFFSET = 8 \nPGN_OFFSET = 8\nPDU2_THRESHOLD = 240\n\nGLOBAL_SOURCE_ADDR = 0xFF\nENGINE_SA = 0\n\nCANDUMP_TIMESTAMP_ADDR = 0\nCANDUMP_CHANNEL_ADDR = 1\nCANDUMP_ID_ADDR = 2\nCANDUMP_DLC_ADDR = 3\nDATA_START_ADDR = 4\n\nPGN_EEC1 = 61444\n\nSPN190_SCALE = 0.125 #RPM/bit\nSPN190_OFFSET = 0\n\ndef main():\n spn190_times = []\n spn190_values = []\n filename = 'KWTruck.txt'\n sa_count={}\n with open(filename,'r') as f:\n for line in f:\n # We knew this data file was from Linux SocketCAN using candump.\n j1939_frame = parse_candump_line(line)\n # Add the additional results from parsing the id\n j1939_frame.update(parseJ1939id(j1939_frame['id']))\n # PGN for electronic engine control 1 messsage\n try:\n sa_count[j1939_frame[\"source_address\"]]+=1\n except KeyError: \n sa_count[j1939_frame[\"source_address\"]]=1\n if (j1939_frame['pgn'] == PGN_EEC1 and \n j1939_frame[\"source_address\"] == ENGINE_SA): \n # Unpack the engine speed data in big endian format and \n # convert to engineering values\n rpm = (struct.unpack('> PRIORITY_OFFSET\n pf = (id & PDU_FORMAT_MASK) >> PDU_FORMAT_OFFSET\n if (pf < PDU2_THRESHOLD): # See SAE J1939-21\n # PDU 1 format uses values lower than 240\n da = (id & PDU_SPECIFIC_MASK) >> DA_OFFSET\n pgn = (id & PDU1_PGN_MASK) >> PGN_OFFSET\n else: # PDU 2 format\n da = GLOBAL_SOURCE_ADDR\n pgn = (id & PDU2_PGN_MASK) >> PGN_OFFSET\n return {'source_address': sa,\n 'priority': priority,\n 'destination_address': da,\n 'pgn': pgn}\n\ndef parse_candump_line(line):\n # Strip the newline characters and white space off the ends\n # then split the string into a list based on whitespace. \n data = line.strip().split() \n # can_dump formats use parenthese to wrap the floating\n # point timestamp. We just want the numbers so use [1:-1] to slice\n time_stamp = float(data[CANDUMP_TIMESTAMP_ADDR][1:-1])\n # physical CAN channel\n channel = data[CANDUMP_CHANNEL_ADDR]\n # determine the can arbitration identifier as an integer\n can_id = int(data[CANDUMP_ID_ADDR],16)\n # Data length code is a single byte wrapped in []\n dlc = int(data[CANDUMP_DLC_ADDR][1])\n # Build the data field as a byte array\n data_bytes = b''\n for byte_string in data[DATA_START_ADDR:]:\n # Convert text into a single byte\n data_bytes += struct.pack('B',int(byte_string,16))\n #assert dlc == len(data_bytes)\n can_frame = {'id':can_id,\n 'dlc':dlc,\n 'data':data_bytes,\n 'timestamp':time_stamp,\n 'channel':channel}\n return can_frame\n\nif __name__ == '__main__':\n main()\n\n","sub_path":"05_J1939/parse_engine_speed.py","file_name":"parse_engine_speed.py","file_ext":"py","file_size_in_byte":3978,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"543029421","text":"from django.conf.urls import patterns, url\n\nfrom subdomains.tests.views import view\n\n\nurlpatterns = patterns(\n '', # prefix\n url(regex=r'^$', view=view, name='home'),\n url(regex=r'^example/$', view=view, name='example'),\n)\n","sub_path":"subdomains/tests/urls/default.py","file_name":"default.py","file_ext":"py","file_size_in_byte":233,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"288134533","text":"from svm import *\nfrom svmutil import *\nimport math\nimport random as rand\nimport pprint\nimport numpy as np\nimport matplotlib.pyplot as plt\n\ndef chunks(l, n):\n \"\"\"Yield successive n-sized chunks from l.\"\"\"\n for i in range(0, len(l), n):\n yield l[i:i + n]\n\ndef train_and_test(trainY, trainX, param, testY, testX): \n\tprob = svm_problem(trainY, trainX)\n\tm = svm_train(prob, param)\n\tp_labels, p_acc, p_vals = svm_predict(testY, testX, m)\n\treturn p_acc[0]\n\ndef unzip(l): \n\tunzipped = zip(*l)\n\treturn list(unzipped[0]), list(unzipped[1])\n\ndef combine(n, l): \n\ttmp = []\n\tfor i, el in enumerate(l): \n\t\tif(i != n): \n\t\t\ttmp += el\n\treturn tmp\n\ntestY, testX = svm_read_problem('ncrna_s.test')\ntrainY, trainX = svm_read_problem('ncrna_s.train')\n\nprint(\"Linear SVMs for C = 2^-4 to 2^8\")\nprint(\"-----------------------------------------------\")\ncosts, acc = [], []\t\nfor m in range(-4, 9): \n\tc = math.pow(2, m)\n\tcosts.append(c)\n\tparam = svm_parameter('-t 0 -h 0 -c %f -q' % c)\n\tacc.append(train_and_test(trainY, trainX, param, testY, testX))\n\nplt.xlabel(\"C\")\nplt.ylabel(\"Accuracy (%)\")\nplt.plot(costs, acc, \"-o\")\nplt.savefig(\"plot.png\")\n\n\nprint(\"\\nRBF kernel SVMs\")\nprint(\"-----------------------------------------------\")\t\nmatrix = np.empty([13, 13])\n\ntraining_set = list(zip(trainY, trainX))\nvalidation_set = list(chunks(rand.sample(training_set, 1000), 200))\n\nfor m in range(-4, 9): \n\tc = math.pow(2, m)\n\tfor n in range(-4, 9): \n\t\tgamma = math.pow(2, n)\n\n\t\tparam = svm_parameter('-t 0 -h 0 -g %f -c %f -q' % (gamma, c))\n\n\t\tv_acc = 0\n\t\tfor i, v in enumerate(validation_set): \n\t\t\tv_testY, v_testX = unzip(v)\n\t\t\tv_training_set = combine(i, validation_set)\n\t\t\tv_trainY, v_trainX = unzip(v_training_set)\n\n\t\t\tv_acc += train_and_test(v_trainY, v_trainX, param, v_testY, v_testX)\n\t\tv_acc /= 5\n\t\tmatrix[m+4, n+4] = v_acc\n\nprint(\"\\nCross Validation Accuracy Matrix\")\nprint(\"-----------------------------------------------\")\t\npprint.pprint(matrix)\n\n# index of max acc as tuple\n# idx = np.unravel_index(matrix.argmax(), matrix.shape)\nidx = zip(*np.where(matrix == np.max(matrix)))[-1]\nc_pow, gamma_pow = idx[0]-4, idx[1]-4\nc, gamma = math.pow(2, c_pow), math.pow(2, gamma_pow)\nparam = svm_parameter('-t 0 -h 0 -g %f -c %f -q' % (gamma, c))\n\nprint(\"\\n-----------------------------------------------\")\nprint(\"using C = 2^%d and gamma = 2^%d\" % (c_pow, gamma_pow))\ntrain_and_test(trainY, trainX, param, testY, testX)\n","sub_path":"proj3 - SVM/libsvm-3.22/python/ncrna.py","file_name":"ncrna.py","file_ext":"py","file_size_in_byte":2402,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"59342058","text":"from flask import Flask, redirect, url_for, request, render_template\r\nimport os\r\nimport random\r\nimport string\r\napp = Flask(__name__)\r\nallowed_characters = string.printable\r\ndefault_insults = [\r\n 'ur bad lelelelel'\r\n]\r\nvcount = 0\r\nwith open ('save_ins.txt','r') as file:\r\n try:\r\n insults = eval(file.read())\r\n except:\r\n insults = []\r\nfor x in default_insults:\r\n if not x in insults:\r\n insults.append(x)\r\n\r\n\r\n@app.route('/')\r\ndef homescreen():\r\n return render_template('index.html')\r\n\r\n@app.route('/insult/')\r\ndef giveinsult():\r\n global insults\r\n selected_insult = insults[random.randint(0,len(insults)-1)]\r\n return render_template('insultpage.html',random_insult=selected_insult)\r\n\r\n@app.route('/insult/add/')\r\ndef addinsult():\r\n global insults\r\n return render_template('addinsult.html')\r\n\r\n@app.route('/insult/add/submit/')\r\ndef newinsult():\r\n global allowed_letters\r\n global insults\r\n new_insult = request.args.get('insult')\r\n if new_insult:\r\n good_char = True\r\n if len(new_insult) > 120:\r\n return render_template('suberr.html',err_msg='Longer than 120 characters.')\r\n for char in new_insult:\r\n if not char in allowed_characters:\r\n good_char = False\r\n if not good_char:\r\n return render_template('suberr.html',err_msg='Invalid characters.')\r\n if good_char:\r\n if not (new_insult in insults) and (' ' in new_insult):\r\n insults.append(new_insult)\r\n with open ('save_ins.txt','w') as file:\r\n file.write(str(insults))\r\n return render_template('insultpage.html',random_insult=new_insult)\r\n return render_template('suberr.html',err_msg='Someone beat you to it.')\r\n if not new_insult:\r\n return render_template('suberr.html',err_msg='Put something please.')\r\n\r\n@app.after_request\r\ndef add_header(r):\r\n \"\"\"\r\n Add headers to both force latest IE rendering engine or Chrome Frame,\r\n and also to cache the rendered page for 10 minutes.\r\n \"\"\"\r\n r.headers[\"Cache-Control\"] = \"no-cache, no-store, must-revalidate\"\r\n r.headers[\"Pragma\"] = \"no-cache\"\r\n r.headers[\"Expires\"] = \"0\"\r\n r.headers['Cache-Control'] = 'public, max-age=0'\r\n return r\r\n\r\nif __name__ == '__main__':\r\n try:\r\n app.run('0.0.0.0',80,True)\r\n except:\r\n hport = int(os.environ.get('PORT', 17995))\r\n app.run('0.0.0.0',hport,False)","sub_path":"server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":2473,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"78742074","text":"import numpy as np\nimport cv2\nimport random\nimport imageio\nfrom matplotlib import pyplot as plt\n\n##cap = cv2.VideoCapture(0)\n##_, frame_old = cap.read()\n\nfilename = 'Sample.mp4'\nvid = imageio.get_reader(filename, 'ffmpeg')\n\n#alpha = alpha_min\nalpha = .9\nascending = True\n\nframe_old = vid.get_data(1)\nx,y,z = frame_old.shape\nprint(x)\nprint(y)\nprint(z)\n\ndx = round(x*.55)\noffset = round(x*.01)\n\n##while(1):\n ##_, frame = cap.read()\nfor i in range(2,len(vid)):\n frame = vid.get_data(i) \n #frame_mod[x-dx+offset:,:,:] = frame_old[x-dx:-offset,:,:].copy()\n\n # img = cv2.cvtColor(frame_mod,cv2.COLOR_BGR2GRAY)\n #img = cv2.resize(cv2.medianBlur(frame,5), None, fx=0.5, fy=0.5)\n img = cv2.cvtColor(cv2.medianBlur(frame,5), cv2.COLOR_RGB2GRAY)\n frame_mod = cv2.Canny(img, 30,100)\n\n kernel = np.ones((5,5),np.uint8)\n # frame_mod = cv2.morphologyEx(frame_mod, cv2.MORPH_CLOSE, kernel)\n # frame_mod = cv2.dilate(frame_mod,kernel,iterations = 1)\n frame_mod = cv2.morphologyEx(frame_mod, cv2.MORPH_CLOSE, kernel)\n # frame_mod = cv2.morphologyEx(frame_mod, cv2.MORPH_OPEN, kernel)\n\n cimg = cv2.cvtColor(frame_mod.copy(), cv2.COLOR_GRAY2RGB)\n \n circles = cv2.HoughCircles(img,cv2.HOUGH_GRADIENT,1,20,\n param1=50,param2=30,minRadius=30,maxRadius=60)\n print(circles)\n try:\n circles = np.uint16(np.around(circles))\n for i in circles[0,:]:\n # draw the outer circle\n cv2.circle(cimg,(i[0],i[1]),i[2],(0,255,0),2)\n # draw the center of the circle\n cv2.circle(cimg,(i[0],i[1]),2,(0,0,255),3)\n except:\n c = 1\n\n \n #cv2.addWeighted(frame_old, alpha, frame, 1 - alpha,0, frame_old) \n\n res = cv2.resize(cimg, None, fx=0.5, fy=0.5)\n #res = cv2.cvtColor(res, cv2.COLOR_RGB2BGR)\n #res = cimg.copy()\n ##res = frame_old.copy()\n\n frame_sized = cv2.resize(frame, None, fx=0.5, fy=0.5)\n# frame_sized = cv2.Canny(frame_sized,50,200)\n #frame_sized = cv2.cvtColor(frame_sized, cv2.COLOR_BGR2RGB)\n\n ##final= np.concatenate((cv2.Canny(res,100,200), cv2.Canny(frame_sized,100,200)), axis=1)\n print(frame_mod.shape)\n print(frame_old.shape)\n final = np.concatenate((res, frame_sized), axis=1)\n ##res = cv2.cvtColor(res, cv2.COLOR_BGR2RGB)\n\n \n\n\n \n ##final = res\n #cv2.imshow('frame',final)\n cv2.imshow('frame',final)\n frame_old = frame_mod;\n\n k = cv2.waitKey(5) & 0xFF\n if k == 27:\n \tbreak\n\n cv2.destroyAllWindows()\n","sub_path":"Computer-Vision/Webcam/canny2.py","file_name":"canny2.py","file_ext":"py","file_size_in_byte":2728,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"464232919","text":"import sys\ninput = sys.stdin.readline\nsys.setrecursionlimit(10 ** 7)\n\nn, m = map(int, input().split())\ns = input().strip()\nt = input().strip()\n\ndef gcd(a, b):\n if b == 0:\n return a\n else:\n return gcd(b, a % b)\n\ndef lcm(a, b):\n return (a // gcd(a, b)) * b\n\ndef cond(candidate):\n count = gcd(n, m)\n n_step = n // count\n m_step = m // count\n\n for i in range(count):\n if s[n_step * i] != t[m_step * i]:\n return False\n return True\n\ncandidate = lcm(n, m)\n\nif cond(candidate):\n print(candidate)\nelse:\n print(-1)\n","sub_path":"grand_contest/028/A.py","file_name":"A.py","file_ext":"py","file_size_in_byte":567,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"506172648","text":"#verify weixin application server URL\n\nfrom WXBizMsgCrypt import WXBizMsgCrypt\nimport xml.etree.cElementTree as ET\nimport sys\nimport verifyconfig\n\nsToken=verifyconfig.application['sToken']\nsEncodingAESKey=verifyconfig.application['sEncodingAESKey']\nsCorpID=verifyconfig.application['sCorpID']\n#verify URL return false or sEchoStr\ndef verifyURL(msgsig,timestamp,nonce,echostr):\n wxcpt=WXBizMsgCrypt(sToken,sEncodingAESKey,sCorpID)\n ret,sEchoStr=wxcpt.VerifyURL(msgsig, timestamp,nonce,echostr) \n if (ret != 0 ):\n return False\n return sEchoStr\n\n#return xml data\ndef getXmlData(msgsig,timestamp,nonce,data):\n wxcpt=WXBizMsgCrypt(sToken,sEncodingAESKey,sCorpID)\n ret,sMsg=wxcpt.DecryptMsg( data, msgsig, timestamp, nonce)\n if (ret != 0 ):\n return False\n xml_tree = ET.fromstring(sMsg)\n return xml_tree\n\n# content = xml_tree.find(\"FromUserName\").text\n","sub_path":"www/identifyURL/res.py","file_name":"res.py","file_ext":"py","file_size_in_byte":889,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"179971517","text":"\nclass Parser:\n\n def __init__(self,*files):\n\n if files is not None:\n self.local_files=files\n\n\n #TODO: import os else: self.local_path='./'\n\n self.start_time=None\n self.current_time=None\n\n\n def parse_csv(self,file=None):\n\n import csv\n from datetime import datetime\n import time\n self.current_time=None\n self.start_time=None\n self.parsed_data={}\n if file is None:\n file=self.local_files[0]\n with open(file, 'r') as f:\n print(\"opened log from\" ,file)\n reader=csv.DictReader(f)\n\n print(\"reading\")\n\n for data in reader:\n #print(data)\n time_stamp= str(data['Date_iso8601'].replace('T', ' ').split('.')[0])\n #print(timeStamp)\n try:\n ts= datetime.strptime(time_stamp,\"%Y-%m-%d %H:%M:%S\")\n except ValueError:\n print('no datetime')\n continue\n #print(type(ts))\n #print(ts.timetuple())\n self.current_time=ts\n if self.start_time is None:\n self.start_time=self.current_time\n delta_t=self.time_in_seconds(self.current_time)-self.time_in_seconds(self.start_time)\n try:\n self.parsed_data['Delta Time'].append(delta_t)\n except KeyError:\n self.parsed_data['Delta Time'] = [delta_t]\n\n for key in data:\n d_point=self.softcast((data[key]))\n\n try:\n self.parsed_data[key].append(data[key])\n\n except KeyError:\n self.parsed_data[key] = [self.softcast(data[key])]\n print(\"parsed\")\n\n\n\n\n def softcast(self,dataIn):\n try:\n dataIn = float(dataIn)\n except ValueError:\n dataIn = 't' in dataIn\n except TypeError:\n dataIn = 0\n return dataIn\n def time_in_seconds(self,dt):\n import time\n return time.mktime(dt.timetuple())\n\n def plot_logs(self,*files,save_image=False,show=True,**values):\n for file in files:\n print(file)\n self.plot_log(file,save_image=save_image,show=show,**values)\n\n\n def plot_log(self,file,save_image=False,show=True,**values):\n from matplotlib import pyplot as plt\n import numpy as np\n\n try:\n self.parse_csv(file)\n except Exception as e:\n print('---------------')\n print(e)\n print('---------------')\n print(\"failed\",str(file))\n return False\n print(\"trying to plot\")\n try:\n\n fig=plt.figure()\n #print(\"data appended\")\n ax1=fig.add_subplot(1,1,1)\n ax1.clear()\n i=0\n ax1.set_yticks(np.arange(0, 200, 5))\n #ax1.set_xticks(np.arange(0, 20000, 60))\n ax1.set_ylim(0,200)\n #ax1.set_xlim(0,100000)\n plt.grid(True)\n\n for key in values:\n ax1.plot(self.parsed_data['Delta Time'],self.parsed_data[key],label=values[key])\n\n #ax1.plot(self.parsed_data['Delta Time'],self.parsed_data['BedTemperature_C'],label='BedTemperature_C')\n ax1.legend(loc = 'upper left')\n dateLabel=self.start_time.strftime(\"%m/%d/%Y\")\n dateLabel+=\" - \"\n dateLabel+=self.current_time.strftime(\"%m/%d/%Y\")\n ax1.set_title(label=dateLabel)\n ax1.set_ylabel(\"Temperature ($^\\circ$C)\")\n ax1.set_xlabel(\"Time (s)\")\n except:\n plt.close()\n raise\n\n if save_image:\n try:\n\n plt.savefig(str(file).replace('csv','png'))\n print(\"saved image as\",str(file).replace('csv','png'))\n except Exception as e:\n print(\"!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\")\n print(e)\n print(\"!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\")\n if show:\n plt.show()\n return fig\n\ndef get_last_temp(file,tc):\n import csv\n with open(file,'r') as f:\n reader=csv.DictReader(f)\n temp=0.\n for line in reader:\n temp=float(line[tc])\n return temp\n","sub_path":"habloparse/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":4340,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"105861633","text":"import numpy as np\nimport scipy.interpolate\nimport scipy.ndimage\nimport math\nfrom scipy.signal import boxcar\nfrom scipy.signal import convolve\n\ndef smooth(x, window_len=9, window='hanning'):\n\t\"\"\"\n\tSmooth the data using a window with requested size.\n\t\n\tThis method is based on the convolution of a scaled window with the signal.\n\tThe signal is prepared by introducing reflected copies of the signal \n\t(with the window size) in both ends so that transient parts are minimized\n\tin the begining and end part of the output signal.\n\t\n\tParameters\n\t----------\n\tx : array_like\n\t\tthe input signal \n\twindow_len : int\n\t\tThe length of the smoothing window\n\twindow : str\n\t\tThe type of window from 'flat', 'hanning', 'hamming', 'bartlett', 'blackman'\n\t\t'flat' window will produce a moving average smoothing.\n\n\tReturns\n\t-------\n\tout : The smoothed signal\n\t\t\n\tExample\n\t-------\n\t>>> t=linspace(-2,2,0.1)\n\t>>> x=sin(t)+randn(len(t))*0.1\n\t>>> y=smooth(x)\n\t\n\tSee Also\n\t--------\n\tnumpy.hanning, numpy.hamming, numpy.bartlett, numpy.blackman, numpy.convolve\n\tscipy.signal.lfilter\n \n\tTODO: the window parameter could be the window itself if an array instead of a string \n\t\"\"\"\n\n\tif type(x) == type([]):\n\t\tx = np.array(x)\n\n\tif x.ndim != 1:\n\t\traise ValueError(\"smooth only accepts 1 dimension arrays.\")\n\n\tif x.size < window_len:\n\t\traise ValueError(\"Input vector needs to be bigger than window size.\")\n\tif window_len < 3:\n\t\treturn x\n\n\tif (window_len % 2) == 0:\n\t\twindow_len = window_len + 1\n\n\tif not window in ['flat', 'hanning', 'hamming', 'bartlett', 'blackman']:\n\t\traise ValueError(\n\t\t\t\"Window is on of 'flat', 'hanning', 'hamming', 'bartlett', 'blackman'\")\n\n\ts = np.r_[2*x[0]-x[window_len:1:-1], x, 2*x[-1]-x[-1:-window_len:-1]]\n\n\tif window == 'flat': # moving average\n\t\tw = np.ones(window_len, 'd')\n\telse:\n\t\tw = eval('np.'+window+'(window_len)')\n\tfrom astropy.convolution import convolve\n\ty = convolve(x, w/w.sum(), normalize_kernel=False, boundary='extend')\n\t# return the smoothed signal\n\treturn y\n\ndef blur_image(im, n, ny=None, ftype='boxcar'):\n\t\"\"\" blurs the image by convolving with a filter ('gaussian' or\n\t\t'boxcar') of\n\t\tsize n. The optional keyword argument ny allows for a different\n\t\tsize in the y direction.\n\t\"\"\"\n\tn = int(n)\n\tif not ny:\n\t\tny = n\n\telse:\n\t\tny = int(ny)\n\t# keep track of nans\n\tnan_idx = np.isnan(im)\n\tim[nan_idx] = 0\n\tif ftype == 'boxcar':\n\t\tif np.ndim(im) == 1:\n\t\t\tg = boxcar(n) / float(n)\n\t\telif np.ndim(im) == 2:\n\t\t\tg = boxcar([n, ny]) / float(n)\n\telif ftype == 'gaussian':\n\t\tx, y = np.mgrid[-n:n+1, -ny:ny+1]\n\t\tg = np.exp(-(x**2/float(n) + y**2/float(ny)))\n\t\tif np.ndim(im) == 1:\n\t\t\tg = g[n, :]\n\t\tg = g / g.sum()\n\timproc = convolve(im, g, mode='same')\n\timproc[nan_idx] = np.nan\n\treturn improc \n\ndef count_to(self, n):\n\t\"\"\"By example:\n\n\t\t# 0 1 2 3 4 5 6 7 8\n\t\tn = [0, 0, 3, 0, 0, 2, 0, 2, 1]\n\t\tres = [0, 1, 2, 0, 1, 0, 1, 0]\n\n\tThat is it is equivalent to something like this :\n\n\t\thstack((arange(n_i) for n_i in n))\n\n\tThis version seems quite a bit faster, at least for some\n\tpossible inputs, and at any rate it encapsulates a task\n\tin a function.\n\t\"\"\"\n\tif n.ndim != 1:\n\t\traise Exception(\"n is supposed to be 1d array.\")\n\n\tn_mask = n.astype(bool)\n\tn_cumsum = np.cumsum(n)\n\tret = np.ones(n_cumsum[-1]+1,dtype=int)\n\tret[n_cumsum[n_mask]] -= n[n_mask]\n\tret[0] -= 1\n\treturn np.cumsum(ret)[:-1]\n\ndef repeat_ind(self, n):\n\t\"\"\"\n\tExamples\n\t--------\n\t>>> n = [0, 0, 3, 0, 0, 2, 0, 2, 1]\n\t>>> res = repeat_ind(n)\n\t>>> res = [2, 2, 2, 5, 5, 7, 7, 8]\n\n\tThat is the input specifies how many times to repeat the given index.\n\n\tIt is equivalent to something like this :\n\n\t\thstack((zeros(n_i,dtype=int)+i for i, n_i in enumerate(n)))\n\n\tBut this version seems to be faster, and probably scales better, at\n\tany rate it encapsulates a task in a function.\n\t\"\"\"\n\tif n.ndim != 1:\n\t\traise Exception(\"n is supposed to be 1d array.\")\n\n\tn_mask = n.astype(bool)\n\tn_inds = np.nonzero(n_mask)[0]\n\tn_inds[1:] = n_inds[1:]-n_inds[:-1] # take diff and leave 0th value in place\n\tn_cumsum = np.empty(len(n)+1,dtype=int)\n\tn_cumsum[0] = 0\n\tn_cumsum[1:] = np.cumsum(n)\n\tret = np.zeros(n_cumsum[-1],dtype=int)\n\tret[n_cumsum[n_mask]] = n_inds # note that n_mask is 1 element shorter than n_cumsum\n\treturn np.cumsum(ret)\n\ndef rect(r, w, deg=0):\n\t\"\"\"\n\tConvert from polar (r,w) to rectangular (x,y)\n\tx = r cos(w)\n\ty = r sin(w)\n\t\"\"\"\n\t# radian if deg=0; degree if deg=1 \n\tif deg: w = np.pi * w / 180.0 \n\treturn r * np.cos(w), r * np.sin(w)\n\t\ndef polar(x, y, deg=0): \n\t\"\"\"\n\tConverts from rectangular coordinates to polar ones\n\n\tParameters\n\t----------\n\tx, y : array_like, list_like\n\t\tThe x and y coordinates\n\tdeg : int\n\t\tradian if deg=0; degree if deg=1\n\n\tReturns\n\t-------\n\tp : array_like\n\t\tThe polar version of x and y\t\n\t\"\"\"\n\tif deg:\n\t\treturn np.hypot(x, y), 180.0 * np.arctan2(y, x) / np.pi\n\telse:\n\t\treturn np.hypot(x, y), np.arctan2(y, x)\n\ndef spiral(self, X, Y):\n\t\"\"\"\n\tGiven an array of shape X x Y this returns the coordinates needed to step\n\tout from the centre of the array to the edge in a spiral fashion:\n\t\n\tSee Also\n\t--------\n\tSee http://stackoverflow.com/questions/398299/looping-in-a-spiral?rq=1\n\tfor original code and question/ solution(s)\n\t\"\"\"\n\tx = 0\n\ty = 0\n\tdx = 0\n\tdy = -1\n\tx_out = []\n\ty_out = []\n\tfor i in range(max(X, Y)**2):\n\t\tx_out.append(x)\n\t\ty_out.append(y)\n\t\tif x == y or (x < 0 and x == -y) or (x > 0 and x == 1-y):\n\t\t\tdx, dy = -dy, dx\n\t\tx, y = x+dx, y+dy\n\t\t\n\treturn np.array(x_out), np.array(y_out)\n\ndef bwperim(bw, n=4):\n \"\"\"\n perim = bwperim(bw, n=4)\n\n Find the perimeter of objects in binary images.\n\n A pixel is part of an object perimeter if its value is one and there\n is at least one zero-valued pixel in its neighborhood.\n\n By default the neighborhood of a pixel is 4 nearest pixels, but\n if `n` is set to 8 the 8 nearest pixels will be considered.\n\n Parameters\n ----------\n bw : A black-and-white image\n n : Connectivity. Must be 4 or 8 (default: 8)\n\n Returns\n -------\n perim : A boolean image\n \"\"\"\n\n if n not in (4,8):\n raise ValueError('mahotas.bwperim: n must be 4 or 8')\n rows,cols = bw.shape\n\n # Translate image by one pixel in all directions\n north = np.zeros((rows,cols))\n south = np.zeros((rows,cols))\n west = np.zeros((rows,cols))\n east = np.zeros((rows,cols))\n\n north[:-1,:] = bw[1:,:]\n south[1:,:] = bw[:-1,:]\n west[:,:-1] = bw[:,1:]\n east[:,1:] = bw[:,:-1]\n idx = (north == bw) & \\\n (south == bw) & \\\n (west == bw) & \\\n (east == bw)\n if n == 8:\n north_east = np.zeros((rows, cols))\n north_west = np.zeros((rows, cols))\n south_east = np.zeros((rows, cols))\n south_west = np.zeros((rows, cols))\n north_east[:-1, 1:] = bw[1:, :-1]\n north_west[:-1, :-1] = bw[1:, 1:]\n south_east[1:, 1:] = bw[:-1, :-1]\n south_west[1:, :-1] = bw[:-1, 1:]\n idx &= (north_east == bw) & \\\n (south_east == bw) & \\\n (south_west == bw) & \\\n (north_west == bw)\n return ~idx * bw\n","sub_path":"ephysiopy/common/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":7016,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"478609214","text":"def rename_cru_ts40( fn ):\n\t''' simple rename of the cru_ts40 data to the more proper naming convention. '''\n\tout_fn = fn.replace( 'cru_ts40', 'CRU-TS40' )\n\treturn os.rename( fn, out_fn )\n\t\nif __name__ == '__main__':\n\timport os, rasterio\n\timport numpy as np\n\timport multiprocessing as mp\n\n\t# list the data\n\tbase_dir = '/workspace/Shared/Tech_Projects/DeltaDownscaling/project_data/downscaled'\n\tfiles = [ os.path.join( r, fn ) for r,s,files in os.walk( os.path.join( base_dir, 'CRU-TS40' ) ) \n\t\t\t\t\tfor fn in files if fn.endswith('.tif') and 'cru_ts40' in fn ]\n\n\t# rename\n\tpool = mp.Pool( 64 )\n\tout = pool.map( rename_cru_ts40, files )\n\tpool.close()\n\tpool.join()","sub_path":"snap_scripts/downscaling_v2/OLD_downscaling_v2/update_cru_ts40_naming.py","file_name":"update_cru_ts40_naming.py","file_ext":"py","file_size_in_byte":660,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"141615600","text":"from itertools import islice\nimport json\nfrom flask import Flask, jsonify, request\nimport numpy as np\nimport redis\nimport requests\nfrom serving.flask import colorize\n\n\napp = Flask(__name__)\n\nr = redis.Redis(host=\"localhost\", port=6379, decode_responses=True)\nuser_consumed = r.get(\"user_consumed\")\nuser_consumed = json.loads(user_consumed)\n\nsparse_col_reindex = json.loads(r.get(\"sparse_col_reindex\"))\nuser_sparse_unique = json.loads(r.get(\"user_sparse_unique\"))\nitem_sparse_unique = json.loads(r.get(\"item_sparse_unique\"))\nuser_dense_unique = json.loads(r.get(\"user_dense_unique\"))\nn_items = len(item_sparse_unique)\n\n\n@app.route(\"//recommend\", methods=['POST'])\ndef api_call(algo):\n test_json = request.get_json(force=True)\n test_json_str = f\"test_json: {test_json}\"\n print(f\"{colorize(test_json_str, 'magenta', bold=True)}\")\n\n try:\n test_data = json.loads(test_json) if isinstance(\n test_json, str) else test_json\n user = test_data[\"user\"]\n n_rec = test_data[\"n_rec\"]\n except json.JSONDecodeError:\n print(\"Could not parse json file...\")\n raise\n except KeyError:\n return bad_request()\n\n reco_list = recommend(user, n_rec, algo)\n response = jsonify({f'recommend list for user ({user})': reco_list})\n return response\n\n\ndef recommend(user, n_rec, algo):\n u_consumed = set(user_consumed[user])\n count = n_rec + len(u_consumed)\n\n (user_indices,\n item_indices,\n sparse_indices,\n dense_values) = get_recommend_indices_and_values(user)\n features = []\n for ui, ii, si, dv in zip(\n user_indices, item_indices, sparse_indices, dense_values):\n features.append(\n {\"user_indices\": ui.tolist(), \"item_indices\": ii.tolist(),\n \"sparse_indices\": si.tolist(), \"dense_values\": dv.tolist()}\n )\n\n if algo.lower() in (\"youtuberanking\", \"din\"):\n u_last_interacted, u_interacted_len = get_user_last_interacted(user)\n for i, (uli, ul) in enumerate(zip(u_last_interacted, u_interacted_len)):\n features[i].update(\n {\"user_interacted_seq\": uli.tolist(),\n \"user_interacted_len\": ul.tolist()}\n )\n\n data = {\"signature_name\": \"predict\", \"instances\": features}\n response = requests.post(\n f\"http://localhost:8501/v1/models/{algo}:predict\",\n data=json.dumps(data)\n )\n\n# recos = json.loads(response.text)[\"predictions\"]\n recos = np.asarray(response.json()[\"predictions\"])\n# recos = 1 / (1 + np.exp(-recos))\n ids = np.argpartition(recos, -count)[-count:]\n rank = sorted(zip(ids, recos[ids]), key=lambda x: -x[1])\n return list(\n islice(\n ((int(rec[0]), float(rec[1])) for rec in rank\n if rec[0] not in u_consumed), n_rec\n )\n )\n\n\ndef get_recommend_indices_and_values(user):\n if isinstance(user, str):\n user = int(user)\n user_indices = np.repeat(user, n_items)\n item_indices = np.arange(n_items)\n user_sparse_part = np.tile(user_sparse_unique[user], (n_items, 1))\n item_sparse_part = item_sparse_unique\n sparse_indices = np.concatenate(\n [user_sparse_part, item_sparse_part], axis=1)[:, sparse_col_reindex]\n dense_values = np.tile(user_dense_unique[user], (n_items, 1))\n return user_indices, item_indices, sparse_indices, dense_values\n\n\ndef get_user_last_interacted(user):\n user_info = np.asarray(\n json.loads(r.hget(\"user_last_interacted\", user)), dtype=np.int32)\n length = len(user_info)\n if length < 10:\n u_last_interacted = np.zeros(10, dtype=np.int32)\n u_last_interacted[:length] = user_info\n u_last_interacted = np.tile(u_last_interacted, (n_items, 1))\n else:\n u_last_interacted = np.tile(user_info, (n_items, 1))\n u_interacted_len = np.repeat(length, n_items)\n return u_last_interacted, u_interacted_len\n\n\n@app.errorhandler(400)\ndef bad_request(error=None):\n message = {\n 'status': 400,\n 'message': f\"Bad Request: {request.url}. \"\n f\"Please provide more data information...\",\n }\n resp = jsonify(message)\n resp.status_code = 400\n return resp\n\n\n# export FLASK_APP=tf_deploy.py\n# export FLASK_ENV=development\n# flask run\nif __name__ == \"__main__\":\n app.run(debug=True, port=5000) # host=\"0.0.0.0\"\n\n","sub_path":"serving/flask/tf/tf_deploy.py","file_name":"tf_deploy.py","file_ext":"py","file_size_in_byte":4317,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"473369088","text":"from dendropy import Tree, DnaCharacterMatrix\nimport numpy as np\nimport math\n\n\ndef give_index(c):\n if c == \"A\":\n return 0\n elif c == \"C\":\n return 1\n elif c == \"G\":\n return 2\n elif c == \"T\":\n return 3\n# =======================================================================================================\ndna = 'CGCC'\n\ntips = 4 #tips number\nbr_length = 0.1\np = np.zeros((4, 4))\n\n# tree = Tree.get_from_path('/home/nehleh/0_Research/PhD/Data/tree.tre', 'newick') (3,4,(1,2)5)6;\ntree = Tree.get_from_string('((1,2)5,3,4)6;', 'newick')\n\n# internal_idx = len(tree.taxon_namespace)\n\n# print(internal_idx)\n\npartial = np.zeros((4,2*tips))\n\nfor i in range(4):\n for j in range(4):\n p[i][j] = 0.25 - 0.25* math.exp(-4*br_length/3)\n p[i][i] = 0.25 + 0.75*math.exp(-4*br_length/3)\n# pprint.pprint(p)\n\n\nfor node in tree.postorder_node_iter():\n node.index = -1\n node.annotations.add_bound_attribute(\"index\")\n\ns = tips + 1\nfor id,node in enumerate(tree.postorder_node_iter()):\n if not node.is_leaf():\n node.index = s\n s += 1\n else:\n for idx, name in enumerate(dna):\n if idx + 1 == int(node.taxon.label):\n node.index = idx+1\n break\n\n\nfor node in tree.postorder_node_iter():\n if node.is_leaf():\n i = give_index(dna[node.index-1])\n partial[i][node.index-1] = 1\n else:\n for j in range(4):\n sump = []\n for x in node.child_node_iter():\n z = 0\n for k in range(4):\n z += p[j][k] * partial[k][x.index-1]\n sump.append(z)\n partial[j][node.index-1] = np.prod(sump)\n\n\n# print(partial)\n\nll = sum(partial[:,2*tips -3] * 0.25)\n\nprint(\"likelihood = {} and log-likelihood = {} \".format(round(ll,7) , round(np.log(ll),7)))\n\n\n\n\n\n\n\n\n","sub_path":"JC69_fulltree.py","file_name":"JC69_fulltree.py","file_ext":"py","file_size_in_byte":1881,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"546188156","text":"pl_pos = 1\ncom_pos = 1\n\ndef banmen():\n print(\"・\"*(pl_pos-1) + \"P\" + \"・\"*(30-pl_pos))\n print(\"・\" * (com_pos - 1) + \"C\" + \"・\" * (30 - com_pos))\nwhile True:\n banmen()\n input(\"Enterを押すと駒が進みます\")\n pl_pos += 1\n com_pos += 2\n","sub_path":"Chapter5/list0503_3.py","file_name":"list0503_3.py","file_ext":"py","file_size_in_byte":263,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"69103802","text":"import numpy as np\n#очень трудно запомнить, но попробуй\n#[НОМЕР СТРОКИ][НОМЕР СТОЛБЦА]\n\n#\n#row or column make zero exept \ndef row_mkz(ic, jc):\n\n\tfor i in range(n_cols):\n\t\t\n\t\tif i != jc and sols[ic][i] == 0: sols[ic][i] = '-'\n\ndef col_mkz(ic, jc):\n\n\tfor i in range(n_rows):\n\t\t\n\t\tif i != ic and sols[i][jc] == 0: sols[i][jc] = '-'\n\ndef diag_mod(ib, jb, dlen):\n\n\tfor s in range(dlen):\n\n\t\tif sols[ib + s][jb - s] == '-': continue\n\n\t\tval = min(supl[ib + s], cust[jb - s])\n\n\t\tsols[ib + s][jb - s] = val\n\n\t\tsupl[ib + s] -= val\n\n\t\tcust[jb - s] -= val\n\n\t\tif supl[ib + s] == 0: row_mkz(ib + s, jb - s)\n\n\t\telif cust[jb - s] == 0: col_mkz(ib + s, jb - s)\n\n\nprce = [\n[3, 1, 2, 2, 4],\n[1, 5, 4, 9, 3],\n[5, 4, 7, 3, 2]]\n\n#поставщик\nsupl = [50, 80, 60]\n\n#клиент\ncust = [20, 35, 25, 70, 40]\n\n\nn_rows, n_cols = len(supl), len(cust)\n\nsols = [[0] * n_cols for i in range(n_rows)]\n\n#проход до побочной диагонали включительно\nfor d in range(n_cols):\n\n\tdiag_mod(0, d, min(d + 1, n_rows))\n\n#проход после побочной диагонали\nfor d in range(1, n_rows):\n\n\tdiag_mod(d, -1, min(n_rows - d, n_cols))\n\n\nprint(sols)\n# \n#until all evals are negative\n\ndef gd_prnt(lst):\n\n\tfor i in lst: print(i['stat'], i['i'], i['j'],'(' + str(sols[i['i']][i['j']]) + ')')\n\n\tup, dwn, rght, lft = '↑', '↓', '→', '←'\n\n\tnet = [[0] * n_cols for i in range(n_rows)]\n\n\tfor i in range(len(lst)):\n\n\t\tti, tj = lst[i]['i'], lst[i]['j']\n\n\t\tnet[ti][tj] = '★p+' if i == 0 else lst[i]['stat']\n\n\t\tdi, dj = lst[(i + 1) % len(lst)]['i'] - ti, lst[(i + 1) % len(lst)]['j'] - tj\n\n\t\tif abs(di) > 1:\n\n\t\t\tfor k in range(ti + np.sign(di), ti + di, np.sign(di)):\n\n\t\t\t\tnet[k][tj] = dwn if di > 0 else up\n\n\t\tif abs(dj) > 1:\n\n\t\t\tfor k in range(tj + np.sign(dj), tj + dj, np.sign(dj)):\n\n\t\t\t\tnet[ti][k] = rght if dj > 0 else lft\n\n\n\tfor k in net: print(k)\n\n\tprint('\\n') \n\ndef mk_sqnce(hst, i, j):\n\n\tbeg = hst[-1]\n\n\tif(j == '-'):\n\n\t\tlsg = np.sign(i - beg['i'])\n\n\t\tmid = [{'i': k, 'j': beg['j'], 'stat': 'n'} for k in range(beg['i'] + lsg, i, lsg)]\n\n\t\tend = {'i': i, 'j': beg['j']}\n\n\tif(i == '-'):\n\n\t\tlsg = np.sign(j - beg['j'])\n\n\t\tmid = [{'i': beg['i'], 'j': k, 'stat': 'n'} for k in range(beg['j'] + lsg, j, lsg)]\n\n\t\tend = {'i': beg['i'], 'j': j}\n\n\tif beg['stat'] == 'p+': end['stat'] = 'p-'\n\telif beg['stat'] == 'p-': end['stat'] = 'p+'\n\n\treturn mid + [end]\n\ndef is_ij_in_sq(i, j, sq):\n\n\tlog = False\n\n\tfor k in ['n', 'p+', 'p-']: log = log or {'i': i, 'j': j, 'stat': k} in sq\n\n\treturn log\n\ndef iter(hst):\n\n\tbeg = hst[0]\n\n\tend = hst[-1]\n\n\tif len(hst) > 1 and beg['i'] == end['i'] and beg['j'] == end['j']:\n\n\t\tprbl_sols.append(hst)\n\n\t\treturn\n\n\tfor i in range(n_rows):\n\n\t\tis_strt = i == beg['i'] and end['j'] == beg['j']\n\n\t\tdo_exst = sols[i][end['j']] != '-'\n\n\t\tis_not_curr = i != end['i'] \n\n\t\tif is_not_curr and (is_strt or (do_exst and not is_ij_in_sq(i, end['j'], hst))):\n\n\t\t\titer(hst + mk_sqnce(hst, i, '-'))\n\n\n\tfor j in range(n_cols):\n\n\t\tis_strt = end['i'] == beg['i'] and j == beg['j']\n\n\t\tdo_exst = sols[end['i']][j] != '-'\n\n\t\tis_not_curr = j != end['j'] \n\n\t\tif is_not_curr and (is_strt or (do_exst and not is_ij_in_sq(end['i'], j, hst))):\n\n\t\t\titer(hst + mk_sqnce(hst, '-', j))\t\t\n\nfor l in range(500):\n\n\t#<Нахождение альф и бет>\n\t#матрица и правая часть\n\tabma, b = [], []\n\n\t#заполнение матрицы\n\tfor i in range(n_rows):\n\n\t\tfor j in range(n_cols):\n\n\t\t\tif sols[i][j] != '-':\n\n\t\t\t\tabma.append([0] * (n_rows + n_cols - 1))\n\n\t\t\t\t#запись alph \n\t\t\t\tif i != 0: abma[-1][i - 1] = 1\n\n\t\t\t\t#запись beta\n\t\t\t\tabma[-1][n_rows + j - 1] = 1\n\n\t\t\t\tb.append(prce[i][j])\n\n\tab = [0] + np.linalg.solve(abma, b).tolist()\n\t#Нахождение альф и бет>\n\tprint(ab)\n\t#<Вычисление оценок>\n\tevls = []\n\n\tfor i in range(n_rows):\n\n\t\tfor j in range(n_cols):\n\n\t\t\tif sols[i][j] == '-':\n\n\t\t\t\tprint(i+1,j+1,' ',prce[i][j], ab[i], ab[n_rows + j],' ', prce[i][j] - (ab[i] + ab[n_rows + j]))\n\n\t\t\t\tevls.append({'i': i, 'j': j, 'val': prce[i][j] - (ab[i] + ab[n_rows + j])})\n\n\tevls.sort(key = lambda x: x['val'])\n\n\tif evls[0]['val'] >= 0: break\n\t#Вычисление оценок>\n\n\t#<Означенный цикл>\n\tprbl_sols = []\n\n\tstrt = {'i': evls[0]['i'], 'j': evls[0]['j'], 'stat': 'p+'}\n\n\titer([strt])\n\n\t#<Фильтрация>\n\tprbl_sols = [[y for y in x[:len(x) - 1] if y['stat'] != 'n' ] for x in prbl_sols]\n\n\tprbl_sols = [x for x in prbl_sols if len(x) % 2 == 0]\n\n\tbst_sols = []\n\n\tfor x in prbl_sols:\n\t\t\n\t\trows = [0] * n_rows\n\n\t\tcols = [0] * n_cols\n\n\t\tfor y in x:\n\t\t\t\n\t\t\trows[y['i']] += 1\n\n\t\t\tcols[y['j']] += 1\n\n\t\tfor c in rows:\n\t\t\tif c % 2 != 0: break\n\n\t\telse:\n\n\t\t\tfor c in cols:\n\n\t\t\t\tif c % 2 != 0: break\n\n\t\t\telse: bst_sols.append(x)\n\t#Фильтрация>\n\n\t#<Изменение на teta>\n\tsqnce = bst_sols[0]\n\n\tteta = min([sols[x['i']][x['j']] for x in sqnce if x['stat'] == 'p-'])\n\n\tgd_prnt(sqnce)\n\n\tfor x in sqnce:\n\t\t\n\t\tif sols[x['i']][x['j']] == '-' : sols[x['i']][x['j']] = teta\n\n\t\telif x['stat'] == 'p+': sols[x['i']][x['j']] += teta\n\n\t\telif x['stat'] == 'p-':\n\n\t\t\tsols[x['i']][x['j']] -= teta\n\n\t\t\tif sols[x['i']][x['j']] == 0: sols[x['i']][x['j']] = '-'\n\t#Изменение на teta>\n\n\tfor k in sols: print(k)\n\n\tprint('\\n')\n\nmin_val = 0\n\nfor i in range(n_rows):\n\n\tfor j in range(n_cols):\n\n\t\tif(sols[i][j] != '-'): min_val += sols[i][j] * prce[i][j]\n\nprint(min_val)\n\n","sub_path":"BACHELOR/NanoTech/potential.py","file_name":"potential.py","file_ext":"py","file_size_in_byte":5442,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"115206468","text":"from PyQt5 import QtCore, QtGui, QtWidgets\n\n\nclass Ui_Dialog1(object):\n def setupUi(self, Dialog1):\n Dialog1.setObjectName(\"Dialog1\")\n Dialog1.resize(307, 173)\n self.gridLayoutWidget = QtWidgets.QWidget(Dialog1)\n self.gridLayoutWidget.setGeometry(QtCore.QRect(30, 20, 251, 131))\n self.gridLayoutWidget.setObjectName(\"gridLayoutWidget\")\n self.gridLayout = QtWidgets.QGridLayout(self.gridLayoutWidget)\n self.gridLayout.setContentsMargins(0, 0, 0, 0)\n self.gridLayout.setObjectName(\"gridLayout\")\n self.label = QtWidgets.QLabel(self.gridLayoutWidget)\n self.label.setFrameShape(QtWidgets.QFrame.StyledPanel)\n self.label.setObjectName(\"label\")\n self.gridLayout.addWidget(self.label, 0, 0, 1, 1)\n self.spinBox = QtWidgets.QSpinBox(self.gridLayoutWidget)\n self.spinBox.setObjectName(\"spinBox\")\n self.gridLayout.addWidget(self.spinBox, 0, 1, 1, 1)\n\n self.retranslateUi(Dialog1)\n QtCore.QMetaObject.connectSlotsByName(Dialog1)\n\n def retranslateUi(self, Dialog1):\n _translate = QtCore.QCoreApplication.translate\n Dialog1.setWindowTitle(_translate(\"Dialog1\", \"Dialog1\"))\n self.label.setText(_translate(\"Dialog1\", \"set lcd Number\"))\n\n\nif __name__ == \"__main__\":\n import sys\n\n app = QtWidgets.QApplication(sys.argv)\n Dialog1 = QtWidgets.QDialog()\n dialog_ui1 = Ui_Dialog1()\n dialog_ui1.setupUi(Dialog1)\n Dialog1.show()\n sys.exit(app.exec_())\n","sub_path":"pyqt/multiUiProject/dialog1_ui.py","file_name":"dialog1_ui.py","file_ext":"py","file_size_in_byte":1495,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"469440989","text":"from mock import Mock\n\nfrom gonzo.scripts.image.create import image_create\nfrom gonzo.test_utils import assert_called_with\n\n\ndef test_image_creation(cloud_fixture):\n (get_cloud, get_hostname, create_security_group) = cloud_fixture\n cloud = get_cloud.return_value\n\n instance = Mock(name='instance')\n cloud.get_instance_by_name.return_value = instance\n\n params = Mock(instance_name='instancename', image_name='imagename')\n image_create(params)\n\n assert_called_with(\n cloud.get_instance_by_name, 'instancename', 'imagename')\n","sub_path":"tests/scripts/image/create.py","file_name":"create.py","file_ext":"py","file_size_in_byte":550,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"535799482","text":"from app.models.seccion import seccion as seccion_model\nfrom app.models.texto import texto as texto_model\n\n\nfrom core.app import app\nfrom core.functions import functions\n\nfrom .base import base\n\nfrom .head import head\nfrom .header import header\nfrom .banner import banner\nfrom .breadcrumb import breadcrumb\nfrom .footer import footer\n\nclass contacto(base):\n def __init__(self):\n super().__init__(app.idseo)\n\n def index(self):\n ret = {\"body\": []}\n self.meta(self.seo)\n url_return = functions.url_redirect(self.url)\n if url_return != \"\":\n ret[\"error\"] = 301\n ret[\"redirect\"] = url_return\n return ret\n\n h = head(self.metadata)\n ret_head = h.normal()\n if ret_head[\"headers\"] != \"\":\n return ret_head\n ret[\"body\"] += ret_head[\"body\"]\n\n he = header()\n ret[\"body\"] += he.normal()[\"body\"]\n\n ba = banner()\n ret[\"body\"] += ba.individual(\n self.seo[\"banner\"], self.metadata[\"title\"], self.seo[\"subtitulo\"]\n )[\"body\"]\n\n bc = breadcrumb()\n ret[\"body\"] += bc.normal(self.breadcrumb)[\"body\"]\n\n data = {}\n\n campos = []\n campos.append(\n {\n \"campo\": \"input\",\n \"type\": \"text\",\n \"field\": \"nombre\",\n \"title\": \"Nombre\",\n \"required\": True,\n }\n )\n campos.append(\n {\n \"campo\": \"input\",\n \"type\": \"email\",\n \"field\": \"email\",\n \"title\": \"Email\",\n \"required\": True,\n }\n )\n campos.append(\n {\n \"campo\": \"input\",\n \"type\": \"text\",\n \"field\": \"telefono\",\n \"title\": \"Teléfono\",\n \"required\": False,\n }\n )\n campos.append(\n {\n \"campo\": \"input\",\n \"type\": \"file\",\n \"field\": \"archivo\",\n \"title\": \"Archivo\",\n \"required\": False,\n }\n )\n campos.append(\n {\n \"campo\": \"textarea\",\n \"type\": \"text\",\n \"field\": \"mensaje\",\n \"title\": \"Comentario\",\n \"required\": True,\n }\n )\n\n data[\"campos\"] = campos\n\n informacion = []\n textos = texto_model.getAll({\"tipo\": 1})\n for t in textos:\n icono = \"\"\n link = \"\"\n if t[0] == 1:\n icono = \"fa-phone\"\n link = \"tel:\" + t[\"texto\"]\n elif t[0] == 2:\n icono = \"fa-envelope-o\"\n link = \"mailto:\" + t[\"texto\"]\n elif t[0] == 6:\n icono = \"fa-map-marker\"\n informacion.append(\n {\"icono\": icono, \"title\": t[\"titulo\"], \"text\": t[\"texto\"], \"url\": link}\n )\n\n data[\"informacion\"] = informacion\n data[\"texto_contacto\"] = functions.remove_tags(texto_model.getById(7)[\"descripcion\"])\n data[\"title\"] = self.seo[\"titulo\"]\n data[\"action\"] = functions.generar_url([\"enviar\"])\n\n mapa = texto_model.getById(8)\n data[\"is_mapa\"] = mapa[\"estado\"]\n data[\"lat\"] = mapa[\"mapa\"][\"lat\"]\n data[\"lng\"] = mapa[\"mapa\"][\"lng\"]\n data[\"title_map\"] = mapa[\"titulo\"]\n data[\"direccion\"] = mapa[\"mapa\"][\"direccion\"]\n\n config = app.get_config()\n data[\"googlemaps_key\"] = config[\"googlemaps_key\"]\n data[\"google_captcha\"] = config[\"google_captcha\"]\n\n ret[\"body\"].append((\"contact\", data))\n\n f = footer()\n ret[\"body\"] += f.normal()[\"body\"]\n return ret\n\n","sub_path":"app/controllers/front/themes/jycdesayunos/contacto.py","file_name":"contacto.py","file_ext":"py","file_size_in_byte":3740,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"4119571","text":"import torch\nimport numpy as np\nimport random\n\ndef cosine_similarity(embedding, valid_size=16, valid_window=100, train_on_gpu=True):\n if train_on_gpu:\n device = torch.device(\"cuda\")\n else:\n device = torch.device(\"cpu\")\n\n embed_vectors = embedding.weight\n\n # magnitude of embedding vectors, |b|\n magnitudes = embed_vectors.pow(2).sum(dim=1).sqrt().unsqueeze(0)\n\n # pick N words from our ranges (0,window) and (1000,1000+window). lower id implies more frequent\n valid_examples = np.array(random.sample(range(valid_window), valid_size // 2))\n valid_examples = np.append(valid_examples,\n random.sample(range(1000, 1000 + valid_window), valid_size // 2))\n valid_examples = torch.tensor(valid_examples, dtype=torch.long).to(device)\n\n valid_vectors = embedding(valid_examples)\n similarities = torch.mm(valid_vectors, embed_vectors.t()) / magnitudes\n\n return valid_examples, similarities\n","sub_path":"lib/common.py","file_name":"common.py","file_ext":"py","file_size_in_byte":960,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"508144493","text":"from flask import Flask, render_template, Response\nimport numpy as np\nfrom threading import Thread\nfrom azure.storage.blob import PageBlobService\nfrom azure.storage.blob import BlockBlobService\n# from flask_socketio import SocketIO, send, emit\n#from time import sleep\nfrom flask_sockets import Sockets\n# https://coderwall.com/p/q2mrbw/gevent-with-debug-support-for-flask\nfrom werkzeug.serving import run_with_reloader\nfrom werkzeug.debug import DebuggedApplication\nfrom gevent import pywsgi, sleep, Timeout\nfrom geventwebsocket.handler import WebSocketHandler\nfrom azure.storage.table import TableService, Entity, TablePermissions\n\n# from gevent import monkey\n# monkey.patch_all()\n\napp = Flask(__name__)\napp.debug = True\nsockets = Sockets(app)\n\nACCOUNT_NAME = \"stgw74e5yvuyvfs2\"\nACCOUNT_KEY = \"YU4+T41CmWSRyxuV0v1KMKAGRfaz6PXnbcZK8mjgvV3TKj3jqHvU4T0uvrcQ6YWUuLu84KRCi17vIqlhaq1dRA==\"\nCONTAINER_NAME = \"simulation\"\n\ntable_service = TableService(account_name=ACCOUNT_NAME, account_key=ACCOUNT_KEY)\n\n@app.route('/')\ndef hello_world():\n return render_template('index.html')\n\ndef stream_thread(ws):\n # ws.on_message = lambda m: print(m)\n bs = PageBlobService(account_name=ACCOUNT_NAME, account_key=ACCOUNT_KEY)\n bbs = PageBlobService(account_name=ACCOUNT_NAME, account_key=ACCOUNT_KEY) \n n = -1\n chunk = 0\n while not ws.closed:\n # message = ws.receive()\n chunk = (chunk - 1) % 10\n properties = bs.set_sequence_number(CONTAINER_NAME, \"buffer\", sequence_number_action=\"max\", sequence_number=0)\n new_n = (properties.sequence_number - 2) % 10\n if new_n == n:\n continue\n n = new_n\n data = bbs.get_blob_to_bytes(CONTAINER_NAME, \"buffer\", start_range=n * 512 * 32, end_range=(n + 1) * 512 * 32)\n ws.send(data.content[0: 8001 * 2])\n #sleep(0.2)\n\n@sockets.route('/stream')\ndef stream(ws):\n print('stream')\n thread = Thread(target=stream_thread, args=(ws, ))\n thread.start()\n while not ws.closed:\n with Timeout(0.1, False):\n message = ws.receive()\n if message is not None: \n speed = int(message) \n device = {'PartitionKey': 'engine', 'RowKey': '1', 'speed': speed * 120}\n table_service.insert_or_merge_entity('devices', device)\n sleep(1)\n\n\ndef run_server():\n if app.debug:\n application = DebuggedApplication(app)\n else:\n application = app\n\n server = pywsgi.WSGIServer(('', 5000), application,\n handler_class=WebSocketHandler)\n server.serve_forever()\n\nif __name__ == \"__main__\":\n run_with_reloader(run_server)\n","sub_path":"Simulator/flask/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2762,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"79275211","text":"import json\nimport os\nimport time\n\nfrom gym import error\n\nclass StatsRecorder(object):\n def __init__(self, directory, file_prefix):\n self.initial_reset_timestamp = None\n self.directory = directory\n self.file_prefix = file_prefix\n self.episode_lengths = []\n self.episode_rewards = []\n self.timestamps = []\n self.steps = None\n self.rewards = None\n\n self.done = None\n\n def before_step(self, action):\n if self.done:\n raise error.ResetNeeded(\"Trying to step environment which is currently done. While the monitor is active, you cannot step beyond the end of an episode. Call 'env.reset()' to start the next episode.\")\n elif self.steps is None:\n raise error.ResetNeeded(\"Trying to step an environment before reset. While the monitor is active, you must call 'env.reset()' before taking an initial step.\")\n\n def after_step(self, observation, reward, done, info):\n self.steps += 1\n self.rewards += reward\n if done:\n self.done = True\n\n def before_reset(self):\n self.done = False\n if self.initial_reset_timestamp is None:\n self.initial_reset_timestamp = time.time()\n\n def after_reset(self, observation):\n self.flush()\n\n def flush(self):\n if self.steps is not None:\n self.episode_lengths.append(self.steps)\n self.episode_rewards.append(self.rewards)\n self.timestamps.append(time.time())\n self.steps = 0\n self.rewards = 0\n\n def close(self):\n self.flush()\n\n filename = '{}.{}.stats.json'.format(self.file_prefix, os.getpid())\n path = os.path.join(self.directory, filename)\n with open(path, 'w') as f:\n json.dump({\n 'initial_reset_timestamp': self.initial_reset_timestamp,\n 'timestamps': self.timestamps,\n 'episode_lengths': self.episode_lengths,\n 'episode_rewards': self.episode_rewards,\n }, f)\n return path\n","sub_path":"gym/monitoring/stats_recorder.py","file_name":"stats_recorder.py","file_ext":"py","file_size_in_byte":2050,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"239943777","text":"import mig_util as mu\n\n\nconn_dooodb = get_conn('dooodb')\nconn_dadb = get_conn('dadb')\n\nwith conn_dooodb:\n cur = conn_dooodb.cursor()\n sql = \"select count(*) from Subject\"\n\n cur.execute(sql)\n cnt_dooo = cur.fetchone()[0]\n\nwith conn_dadb:\n cur = conn_dadb.cursor()\n sql = \"select count(*) from Subject\"\n\n cur.execute(sql)\n cnt_dadb = cur.fetchone()[0]\n\n\n\n\n\n\nwith conn_dooodb:\n cur = conn_dooodb.cursor()\n sql = \"select id, name, prof, classroom from Subject where id < 5\"\n\n cur.execute(sql)\n verify_dooo = cur.fetchall()\n\nwith conn_dadb:\n cur = conn_dadb.cursor()\n sql = \"select id, name, prof, classroom from Subject where id < 5\"\n\n cur.execute(sql)\n verify_dadb = cur.fetchall()\n\n\n\nif cnt_dooo == cnt_dadb:\n print(\"데이터의 개수가 일치합니다.\")\n \n if verify_dooo == verify_dadb:\n print(\"샘플 데이터가 일치합니다.\")\n else:\n print(\"샘플 데이터가 일치하지 않습니다.\")\n\nelse:\n print(\"데이터의 개수가 일치하지 않습니다.\")","sub_path":"mysqlverifymigwithutil.py","file_name":"mysqlverifymigwithutil.py","file_ext":"py","file_size_in_byte":1047,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"615512812","text":"#!/usr/bin/env python\n# encoding: utf-8\n\n# Created by Marcin Niedziela , ~2010\n\nimport time\nfrom tkinter import *\nimport tkinter.messagebox\n\ntry:\n import winsound\n linux = False\nexcept:\n linux = True\n\n__version__ = \"0.3\"\n__title__ = \"Alfabet Morse'a\"\n\n\nclass Morse:\n\n def __init__(self):\n self.FONT_NAME = 'sans'\n self.FONT_SIZE = 8\n self.morse_code = {\"A\": \".-\", \"B\": \"-...\", \"C\": \"-.-.\", \"D\": \"-..\",\n \"E\": \".\", \"F\": \"..-.\", \"G\": \"--.\", \"H\": \"....\",\n \"I\": \"..\", \"J\": \".---\", \"K\": \"-.-\", \"L\": \".-..\",\n \"M\": \"--\", \"N\": \"-.\", \"O\": \"---\", \"P\": \".--.\",\n \"Q\": \"--.-\", \"R\": \".-.\", \"S\": \"...\", \"T\": \"-\",\n \"U\": \"..-\", \"V\": \"...-\", \"W\": \".--\", \"X\": \"-..-\",\n \"Y\": \"-.--\", \"Z\": \"--..\", \"Ą\": \".-.-\", \"Ć\": \"-.-..\",\n \"Ę\": \"..-..\", \"Ł\": \".-..-\", \"Ń\": \"--.--\",\n \"Ó\": \"---.\", \"Ś\": \"...---...\", \"Ż\": \"--..-.\",\n \"Ź\": \"--..-\", \"1\": \".----\", \"2\": \"..---\",\n \"3\": \"...--\", \"4\": \"....-\",\n \"5\": \".....\", \"6\": \"-.....\", \"7\": \"--...\",\n \"8\": \"---..\", \"9\": \"----.\", \"0\": \"-----\",\n \".\": \".-.-.-\", \",\": \"--..--\", \"'\": \".----.\",\n \"_\": \"..--.-\", \":\": \"---...\", \"?\": \"..--..\",\n \"-\": \"-...-\", \"(\": \"-.--.\", \")\": \"-.--.-\",\n \"=\": \"-...-\", \"@\": \".--.-.\"}\n\n def center_window(self, w=300, h=200):\n # http://forum.python.org.pl/index.php?topic=380.0\n ws = root.winfo_screenwidth()\n hs = root.winfo_screenheight()\n x = (ws / 2) - (w / 2)\n y = (hs / 2) - (h / 2)\n root.geometry('%dx%d+%d+%d' % (w, h, x, y))\n\n def button(self, master, txt='', cmd=None, **options):\n return Button(master, text=txt, width=10, command=cmd,\n font=(self.FONT_NAME, self.FONT_SIZE), **options)\n\n def text(self, master, **options):\n return Text(master, height=8, width=40, font=(self.FONT_NAME, 12),\n **options)\n\n def gui(self, master=None):\n root.title(__title__ + ' ' + __version__)\n root.resizable(width=FALSE, height=FALSE)\n self.center_window(370, 340)\n root.protocol(\"WM_DELETE_WINDOW\", lambda: root.destroy())\n\n frame = Frame(master, bd=1, relief=RIDGE, width=100)\n frame2 = Frame(master, bd=1, relief=RIDGE, width=100)\n frame.grid(padx=0, pady=0)\n frame2.grid(padx=4, pady=5)\n\n self.src = self.text(frame)\n self.src.focus_set()\n self.dst = self.text(frame, state=DISABLED)\n code = self.button(frame2, \"Koduj\", lambda: self.code_decode('code'))\n decode = self.button(frame2, \"Dekoduj\",\n lambda: self.code_decode('decode'))\n graj = self.button(frame2, \"Graj\", lambda: self.play())\n quit = self.button(frame2, \"Wyjście\", lambda: root.destroy())\n\n self.src.grid(row=0, columnspan=4)\n self.dst.grid(row=1, columnspan=4)\n code.grid(row=6, column=0)\n decode.grid(row=6, column=1)\n graj.grid(row=6, column=2)\n quit.grid(row=6, column=3)\n return True\n\n def reverse_morse(self):\n morse = self.morse_code\n rev_morse = {}\n for i in morse.keys():\n rev_morse[morse[i]] = i\n return rev_morse\n\n def code_decode(self, mode=''):\n txt = self.src.get(\"1.0\", END)\n if txt:\n s = ''\n if mode == 'code':\n morse = self.morse_code\n t = tuple(txt)\n for c in t:\n if c == ' ':\n s += '/ '\n else:\n if c.upper() in morse:\n s += morse[c.upper()] + ' '\n else:\n morse = self.reverse_morse()\n for mn in txt.split(' '):\n if mn == '/':\n s += ' '\n else:\n if mn in morse:\n s += morse[mn]\n\n self.dst.config(state=NORMAL)\n self.dst.delete(\"1.0\", END)\n self.dst.insert(END, s)\n self.dst.config(state=DISABLED)\n return True\n\n def play(self):\n if linux:\n tkinter.messagebox.showinfo('Graj',\n 'Funkcja odtwarzania dostępna dla Windows')\n return False\n self.code_decode()\n str = self.dst.get(\"1.0\", END)\n for letter in str.split(' '):\n for sign in letter:\n if sign == '-':\n winsound.Beep(400, 300)\n time.sleep(0.1)\n elif sign == '.':\n winsound.Beep(400, 100)\n time.sleep(0.1)\n elif sign == '/':\n time.sleep(0.9)\n return True\n\n\nif __name__ == '__main__':\n root = Tk()\n m = Morse()\n m.gui(root)\n root.mainloop()\n","sub_path":"Python/morse/morse.py","file_name":"morse.py","file_ext":"py","file_size_in_byte":5176,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"567883236","text":"#!/usr/bin/env python\n\n# To upload a version to PyPI, run:\n#\n# python setup.py sdist upload\n#\n# If the package is not registered with PyPI yet, do so with:\n#\n# python setup.py register\n\nfrom distutils.core import setup\nimport os\nimport platform\n\nVERSION = '3.2.0'\n\n# Auto generate a __version__ package for the package to import\nwith open(os.path.join('spinapi', '__version__.py'), 'w') as f:\n f.write(\"__version__ = '%s'\\n\"%VERSION)\n\narch = platform.architecture()\n\nif arch == ('32bit', 'ELF'):\n bundled_shared_objects = ['libspinapi.so']\nelif arch == ('64bit', 'ELF'):\n bundled_shared_objects = ['libspinapi64.so']\nelse:\n bundled_shared_objects = []\n \nsetup(name='spinapi',\n version=VERSION,\n description='Python wrapper around the Spincore PulseBlaster API using ctypes.',\n author='Chris Billington',\n author_email='chrisjbillington@gmail.com',\n url='https://bitbucket.org/cbillington/spinapi/',\n license=\"BSD\",\n packages=['spinapi'],\n package_data={'spinapi': bundled_shared_objects}\n )\n","sub_path":"pypi_install_script/spinapi-3.2.0.tar/setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":1053,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"382240752","text":"import os\nimport rnnSMAP\nimport matplotlib\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport scipy\nimport imp\nimp.reload(rnnSMAP)\nrnnSMAP.reload()\n\ntrainName = 'CONUSv2f1'\nout = trainName+'_y15_Forcing_dr60'\nrootDB = rnnSMAP.kPath['DB_L3_NA']\nrootOut = rnnSMAP.kPath['OutSigma_L3_NA']\nsaveFolder = os.path.join(rnnSMAP.kPath['dirResult'], 'paperSigma')\n\ndoOpt = []\ndoOpt.append('loadData')\ndoOpt.append('plotConf')\n# doOpt.append('plotBin')\n# doOpt.append('plotProb')\n\nmatplotlib.rcParams.update({'font.size': 16})\nmatplotlib.rcParams.update({'lines.linewidth': 2})\nmatplotlib.rcParams.update({'lines.markersize': 10})\nplt.tight_layout()\n\n#################################################\n# load data\nif 'loadData' in doOpt:\n dsLst = list()\n statErrLst = list()\n statSigmaLst = list()\n statConfLst = list()\n statProbLst = list()\n\n for k in range(0, 2):\n if k == 0: # validation\n testName = 'CONUSv2f1'\n yr = [2016]\n if k == 1: # temporal test\n testName = 'CONUSv2f1'\n yr = [2017]\n # if k == 2: # spatial test\n # testName = 'CONUSv2fx2'\n # yr = [2015]\n\n predField = 'LSTM'\n targetField = 'SMAP'\n ds = rnnSMAP.classDB.DatasetPost(\n rootDB=rootDB, subsetName=testName, yrLst=yr)\n ds.readData(var='SMAP_AM', field='SMAP')\n ds.readPred(rootOut=rootOut, out=out, drMC=100, field='LSTM')\n statErr = ds.statCalError(predField='LSTM', targetField='SMAP')\n statSigma = ds.statCalSigma(field='LSTM')\n statConf = ds.statCalConf(\n predField='LSTM', targetField='SMAP', rmBias=True)\n statProb = ds.statCalProb(predField='LSTM', targetField='SMAP')\n dsLst.append(ds)\n statErrLst.append(statErr)\n statSigmaLst.append(statSigma)\n statConfLst.append(statConf)\n statProbLst.append(statProb)\n\n#################################################\n# plot confidence figure\nif 'plotConf' in doOpt:\n figTitleLst = ['(a) Validation', '(b) Temporal Test']\n fig, axes = plt.subplots(\n ncols=len(figTitleLst), figsize=(12, 6), sharey=True)\n sigmaStrLst = ['sigmaX', 'sigmaMC', 'sigma']\n legendLst = [r'$p_{x}$', r'$p_{mc}$', r'$p_{comb}$']\n for iFig in range(0, 2):\n statConf = statConfLst[iFig]\n figTitle = figTitleLst[iFig]\n plotLst = list()\n for k in range(0, len(sigmaStrLst)):\n plotLst.append(getattr(statConf, 'conf_'+sigmaStrLst[k]))\n\n _, _, out = rnnSMAP.funPost.plotCDF(\n plotLst, ax=axes[iFig], legendLst=legendLst, cLst='grbm',\n xlabel='Error Exceedance Probablity', ylabel=None, showDiff='KS')\n axes[iFig].set_title(figTitle)\n print(out['rmseLst'])\n axes[0].set_ylabel('Frequency')\n # axes[1].get_legend().remove()\n fig.tight_layout()\n fig.show()\n saveFile = os.path.join(saveFolder, 'CONUS_conf')\n fig.savefig(saveFile, dpi=100)\n fig.savefig(saveFile+'.eps')\n\n\nconf = getattr(statConfLst[1], 'conf_'+sigmaStrLst[1])\nx = rnnSMAP.funPost.flatData(conf)\ny = np.arange(len(x))/float(len(x)-1)\nnp.mean(y-x)\na=scipy.stats.kstest(x, 'uniform',mode='approx')\n","sub_path":"app/paper/paperSigma/CONUS_conf.py","file_name":"CONUS_conf.py","file_ext":"py","file_size_in_byte":3194,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"483468140","text":"\"\"\"\nThis module only exists to execute one-time scripts.\nNothing here should be referenced in or executed any other modules.\n\"\"\"\nimport simplejson as json\nfrom django.core.exceptions import ObjectDoesNotExist\nimport calculations.TxtConverter as TxtConverter\nimport calculations.AddressQueryFactory as AddressQueryFactory\nfrom calculations.AddressQueryFactory import AddressQueryFactory as Q\nimport database as db\nfrom time import time\n\ndef export_zone(model_class, zone_file, footnotes_file=None):\n footnotes_dict = {}\n if footnotes_file:\n footnotes_array = TxtConverter.txt_to_array(open(footnotes_file, 'r'), transpose=False, char_strip=[\"\\\"\"])\n for f in footnotes_array:\n footnotes_dict[f[0]] = f[1]\n\n if 'dev' in zone_file.lower():\n rule_class = 'Development'\n elif 'use' in zone_file.lower():\n rule_class = 'Use'\n else:\n print('Invalid zone_file name')\n return None\n\n txt_array =TxtConverter.txt_to_array(open(zone_file, 'r'), transpose=True, char_strip=[\"\\\"\"])\n rules_row = txt_array[0]\n for i in range(1, len(txt_array)):\n name = txt_array[i][0]\n #the same logic is used for both dev and use regs\n zone_entry_dict = {'rule_dict': {}, 'footnotes_dict': {}} #omit parent\n for j in range(1, len(rules_row)):\n working_rule_dict= {\n 'category': None,\n 'rule': None,\n 'value': None,\n 'footnotes': []\n }\n if \"\\\\\" in rules_row[j]: #backslash in rule name in txt file denotes a category\n rules_parts = rules_row[j].split(\"\\\\\")\n working_rule_dict['category'] = rules_parts[0]\n working_rule_dict['rule'] = rules_parts[1]\n else:\n working_rule_dict['rule'] = rules_row[j]\n if \"[\" in rules_row[j]: #rule-based footnotes are enclosed in [brackets]\n rule_parts = [r.strip() for r in working_rule_dict['rule'].replace(']', '').split('[')]\n working_rule_dict['rule'] = rule_parts.pop(0)\n working_rule_dict['footnotes'] += rule_parts\n curr_cell = txt_array[i][j]\n if \"(\" in curr_cell: #individual footnotes are enclosed in (parenthesis)\n value_parts = [c.strip() for c in curr_cell.replace(\")\", \"\").split(\"(\")]\n working_rule_dict['value'] = value_parts.pop(0)\n working_rule_dict['footnotes'] += value_parts\n for k, v in footnotes_dict.items(): #only add relevant footnotes to save space\n if k in working_rule_dict['footnotes']:\n zone_entry_dict['footnotes_dict'][k] = v\n else:\n working_rule_dict['value'] = curr_cell\n entry_name = (rules_row[j].split('[')).pop(0).strip()\n zone_entry_dict['rule_dict'][entry_name] = working_rule_dict\n #if model already exists, get existing one. otherwise save\n try:\n zone_model = model_class.objects.get(name=name)\n except ObjectDoesNotExist:\n zone_model = model_class(name=name)\n if 'dev' in rule_class.lower(): #decide whether to update to dev or use regs in db\n working_dict = json.loads(zone_model.development_regs)\n working_dict.update(zone_entry_dict)\n zone_model.development_regs = json.dumps(working_dict)\n else:\n working_dict = json.loads(zone_model.use_regs)\n working_dict.update(zone_entry_dict)\n zone_model.use_regs = json.dumps(working_dict)\n zone_model.save()\n print(\"Done: {0}\".format(zone_file))\n\n#make sure column1 shows use parents; column2 shows dev parents\ndef set_parent(model_class, parent_file):\n parent_array = TxtConverter.txt_to_array(open(parent_file, 'r'), transpose=False, char_strip=[\"\\\"\"])\n for p in parent_array:\n try: zone_model = model_class.objects.get(name=p[0])\n except ObjectDoesNotExist: zone_model = model_class(name=p[0])\n\n if p[1].lower() == 'none': use_parent = None\n else: use_parent = p[1]\n\n use_regs_dict = json.loads(zone_model.use_regs)\n use_regs_dict['parent'] = use_parent\n zone_model.use_regs = json.dumps(use_regs_dict)\n\n if p[2].lower() == 'none': dev_parent = None\n else: dev_parent = p[2]\n\n dev_regs_dict = json.loads(zone_model.development_regs)\n dev_regs_dict['parent'] = dev_parent\n zone_model.development_regs = json.dumps(dev_regs_dict)\n\n zone_model.save()\n print(\"{0}'s parents are: {1} in use and {2} in dev\".format(p[0], p[1], p[2]))\n\n# file_list = [\n# (\"dev regs RM.txt\", \"dev regs RM foot.txt\")]\n\n# file_list = [\n# (\"use regs CC.tsv\", 'use regs C footnotes.tsv'),\n# (\"use regs Cb.tsv\", 'use regs C footnotes.tsv'),\n# (\"use regs C.tsv\", 'use regs C footnotes.tsv'),\n# (\"dev regs CN.tsv\", 'dev regs CN footnotes.tsv'),\n# (\"dev regs CC.tsv\", 'dev regs CC footnotes.tsv'),\n# (\"dev regs C.tsv\", 'dev regs C footnotes.tsv')\n# ]\n\nfile_list = [\n ('use regs rmx.tsv', 'use regs rmx foot.tsv'),\n ('dev regs rmx.tsv', 'dev regs rmx foot.tsv')\n ]\n\n\n# import calculations.InputValidate as V\n# start = time()\n# res = V.autofill_list(\"2405 union\", \"sandiego_addresses\", \"full_addr\", \"apn\")\n# end = time()\n# print(res)\n# print(end - start)\n\n# q = Q()\n# print(q.get(\"san jose\", \"ca\", '620 n 2nd st'))\n# print(q)\n#\n# santa_clara_tests = ('23029119', '23024008', '23029096')\n# for s in santa_clara_tests:\n# print(q.get(\"santa clara\", \"ca\", apn=s)['opportunity_zone'])\n# print(q)\n#\n# print(q.get(\"san diego\", \"ca\", \"1401 national city blvd\")['opportunity_zone'])\n# print(q)\n\n# from calculations.SanDiego import SanDiego\n# sd = SanDiego()\n# cur = sd.cur\n# query = \"\"\"\n# SELECT p.apn, oz.namelsad, a.full_addr\n# FROM public.sandiego_parcels p, public.ca_opportunity_zones oz, public.sandiego_addresses a\n# WHERE\n# a.full_addr = '1401 NATIONAL CITY BLVD' AND\n# ST_Intersects(\n# ST_Transform(ST_GeomFromText(ST_AsText(ST_GeomFromGeoJSON({0})), {1}), {2}),\n# ST_GeomFromText(ST_AsText(ST_GeomFromGeoJSON(oz.geometry), 4269))\n# )\n# LIMIT 5;\n# \"\"\".format(\"p.geometry\", str(4326), str(4269))\n# cur.execute(query)\n# print(cur)\n\n\n\nprint(csv_to_dict(\"sandiego_test_data.csv\", ';'))\n\n# data = sd.get(address=\"2405 union st\")\n# geo = data['geometry']\n# print(geo)\n# g = sd.st_transform(geo, 4326, 3857)\n# print(g)\n\n","sub_path":"Scripts.py","file_name":"Scripts.py","file_ext":"py","file_size_in_byte":6516,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"25932255","text":"# Copyright (c) 2011 Benaka Moorthi\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy\n# of this software and associated documentation files (the \"Software\"), to deal\n# in the Software without restriction, including without limitation the rights\n# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n# copies of the Software, and to permit persons to whom the Software is\n# furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in\n# all copies or substantial portions of the Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n# THE SOFTWARE.\n\nimport math\nimport cairo\nfrom gi.repository import GObject, Gtk, Gdk, Pango, PangoCairo\n\nfrom srmtrainer.gedit.utility import *\n\nclass ProblemNavigator(Gtk.DrawingArea):\n\n __gtype_name__ = 'ProblemNavigator'\n \n __gsignals__ = {\n 'problem-selected': (GObject.SIGNAL_RUN_FIRST, GObject.TYPE_NONE, [object])\n }\n\n # used to expand hover/click range\n HORIZONTAL_PADDING = 5\n VERTICAL_PADDING = 3\n\n def __init__(self, titles):\n Gtk.Widget.__init__(self)\n\n self._problem_titles = titles\n\n self.space_between_buttons = 50\n self.text_button_padding = 15\n self.button_radius = 5\n self.button_color = Gdk.color_parse(\"#FFD700\")[1]\n self.text_color = Gdk.color_parse(\"#000\")[1]\n self.bg_color = None\n self.selected_problem = 0\n self._hovered_problem = None\n \n pango_ctx = self.get_pango_context()\n\n self.font_desc = Pango.FontDescription()\n self.font_desc.set_size(9 * Pango.SCALE)\n self.font_desc.set_style(Pango.Style.NORMAL)\n self.font_desc.set_variant(Pango.Variant.NORMAL)\n self.font_desc.set_weight(Pango.Weight.LIGHT)\n self.font_desc.set_stretch(Pango.Stretch.EXPANDED)\n\n self._layouts = []\n for title in self._problem_titles:\n layout = self.create_pango_layout(title)\n layout.set_width(-1)\n layout.set_height(-1)\n layout.set_ellipsize(Pango.EllipsizeMode.NONE)\n layout.set_font_description(self.font_desc)\n\n self._layouts[len(self._layouts):] = [layout]\n\n (self._first_w, self._first_h) = self._layouts[0].get_pixel_size()\n (self._last_w, self._last_h) = self._layouts[-1].get_pixel_size()\n\n self.do_resize()\n\n self.add_events(Gdk.EventMask.POINTER_MOTION_MASK | Gdk.EventMask.BUTTON_PRESS_MASK)\n self.connect('draw', self._draw)\n self.connect('motion-notify-event', self.on_mouse_over)\n self.connect('button-press-event', self.on_button_press)\n\n self.emit('problem-selected', self.selected_problem)\n\n # TODO: need to use @property for certain properties to automatically do resize\n # instead of forcing user to call do_resize()\n def do_resize(self):\n n = len(self._problem_titles)\n r = self.button_radius\n d = self.space_between_buttons\n vp = self.text_button_padding\n \n ds = (self._first_w - r) / 2\n de = (self._last_w - r) / 2\n\n w = n * r + max(0, n - 1) * d + ds + de\n \n # assumes height of every layout is the same\n h = r + 2 * vp + 2 * self._first_h\n self.set_size_request(w, h)\n \n def _draw(self, widget, ctx):\n alloc = self.get_allocation()\n r = self.button_radius\n d = self.space_between_buttons\n\n ds = (self._first_w - r) / 2\n\n ctx.set_line_width(1.0)\n\n if self.bg_color:\n ctx.set_source_rgb( \\\n self.bg_color.red / COLOR_MAX, \\\n self.bg_color.green / COLOR_MAX, \\\n self.bg_color.blue / COLOR_MAX)\n ctx.rectangle(0, 0, alloc.width, alloc.height)\n ctx.fill()\n ctx.new_path()\n\n ctx.set_source_rgb( \\\n self.button_color.red / COLOR_MAX, \\\n self.button_color.green / COLOR_MAX, \\\n self.button_color.blue / COLOR_MAX)\n\n # for every button\n for i in range(0, len(self._problem_titles)):\n xc = ds + i * (d + r) + r / 2\n yc = alloc.height / 2\n\n # draw the button\n ctx.arc(xc, yc, r, 0, 2 * math.pi)\n ctx.close_path()\n\n # if selected, fill the circle, otherwise stroke it\n if self.selected_problem == i or self._hovered_problem == i:\n ctx.fill()\n else:\n ctx.stroke()\n\n ctx.set_source_rgb( \\\n self.text_color.red / COLOR_MAX, \\\n self.text_color.green / COLOR_MAX, \\\n self.text_color.blue / COLOR_MAX)\n\n # draw the selected label above \n self._move_ctx_to_label_start(ctx, self.selected_problem, True)\n PangoCairo.layout_path(ctx, self._layouts[self.selected_problem])\n ctx.stroke()\n\n # draw the hovered label, if any\n if self._hovered_problem != None:\n self._move_ctx_to_label_start(ctx, self._hovered_problem, False)\n PangoCairo.layout_path(ctx, self._layouts[self._hovered_problem])\n ctx.stroke()\n\n def _move_ctx_to_label_start(self, ctx, i, above):\n ctx.new_path()\n \n alloc = self.get_allocation()\n r = self.button_radius\n d = self.space_between_buttons\n vp = self.text_button_padding\n\n ds = (self._first_w - r) / 2\n\n (l_w, l_h) = self._layouts[i].get_pixel_size()\n\n x = ds + i * (d + r) - (l_w - r) / 2\n y = None\n if above:\n y = 0\n else:\n y = (alloc.height + r) / 2 + vp\n\n ctx.move_to(x, y)\n\n def _button_at_pos(self, x_, y_):\n x = int(x_)\n y = int(y_)\n \n alloc = self.get_allocation()\n r = self.button_radius\n d = self.space_between_buttons\n\n ds = (self._first_w - r) / 2\n de = (self._last_w - r) / 2\n\n h_lower = (alloc.height - r) / 2 - ProblemNavigator.VERTICAL_PADDING\n h_upper = (alloc.height + r) / 2 + ProblemNavigator.VERTICAL_PADDING\n\n modded_x = (x - ds) % (r + d) - ProblemNavigator.HORIZONTAL_PADDING\n\n if y >= h_lower and y <= h_upper and \\\n x >= ds and modded_x <= r:\n return (x - ds) / (r + d)\n\n return None\n\n def on_mouse_over(self, widget, evt):\n idx = self._button_at_pos(evt.x, evt.y)\n self._set_hovered(idx)\n\n def on_button_press(self, widget, evt):\n idx = self._button_at_pos(evt.x, evt.y)\n self._set_selected(idx)\n\n def _set_selected(self, idx):\n if idx != None and idx != self.selected_problem and idx >= 0 and idx < len(self._layouts):\n self.selected_problem = idx\n\n if self._hovered_problem == self.selected_problem:\n self._hovered_problem = None\n\n self.queue_draw()\n self.emit('problem-selected', self.selected_problem)\n\n def _set_hovered(self, idx):\n if self._hovered_problem != idx and idx != self.selected_problem and \\\n (idx == None or (idx >= 0 and idx < len(self._layouts))):\n self._hovered_problem = idx\n self.queue_draw()\n\n","sub_path":"src/srmtrainer/gedit/ui/problem_navigator.py","file_name":"problem_navigator.py","file_ext":"py","file_size_in_byte":6970,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"44451447","text":"'''\npaper.data.scripts.test_db\n\nruns tests for most relevant functions of paper pipeline\n\nauthor | Immanuel Washington\n\nFunctions\n---------\nscript_test | runs script functions on test uv files\n'''\nfrom __future__ import print_function\nimport os\nimport doctest\nimport glob\nimport shutil\nfrom paper.data import dbi as pdbi\nimport add_files\nimport backup_db\nimport restore_db\nimport move_files\nimport delete_files\n\ndef script_test():\n '''\n runs tests of scripts\n '''\n print('instantiating database interface object...')\n dbi = pdbi.DataBaseInterface(configfile=os.path.expanduser('~/paperdata/test.cfg'))\n \n print('creating db...')\n dbi.create_db()\n\n print('finding files to test...')\n test_paths_str = os.path.expanduser('~/test_data/zen*.uv*')\n test_paths = glob.glob(test_paths_str)\n\n print('adding files to db...')\n source_host = 'folio'\n\n add_files.add_files(dbi, source_host, test_paths)\n add_files.update_obsnums(dbi)\n add_files.connect_observations(dbi)\n\n print('backing up db...')\n backup_db.paperbackup(dbi, db='papertest')\n\n print('dropping db...')\n dbi.drop_db(pdbi.Base)\n\n print('creating db again...')\n dbi.create_db()\n\n print('loading db...')\n restore_db(dbi, table='File')\n restore_db(dbi, table='Observation')\n add_files.update_obsnums(dbi)\n add_files.connect_observations(dbi)\n\n print('moving files...')\n #copy files first?\n dest_host = 'node16'\n dest_path = os.path.expanduser('~/test_data/')\n move_files.move_files(dbi, source_host, source_paths, dest_host, dest_path)\n\n print('deleting files...')\n source_host = dest_host\n dest_host = 'folio'\n del_dir = os.path.expanduser('~/test_data_2/')\n os.mkdir(dest_path)\n source_paths = delete_files.delete_check(source_host)\n delete_files.delete_files(dbi, source_host, source_paths, dest_host, del_dir)\n\n print('dropping db again...')\n dbi.drop_db()\n\n print('deleting backup file...')\n backup_list = sorted(glob.glob('/data4/paper/paperdata_backup/[0-9]*'), reverse=True)\n timestamp = int(backup_list[0].split('/')[-1])\n backup_file = '/data4/paper/paperdata_backup/{timestamp}/{table}_{timestamp}.json'.format(table=table, timestamp=timestamp)\n os.remove(backup_file)\n\n print('deleting copied files...')\n shutil.rmtree(del_dir)\n\n print('Script test Complete!')\n\nif __name__ == '__main__':\n script_test()\n","sub_path":"paper/data/scripts/test_db.py","file_name":"test_db.py","file_ext":"py","file_size_in_byte":2416,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"28033583","text":"import networkx as nx\nimport matplotlib.pyplot as plt\n \n\nimport numpy as np\n\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.svm import SVC\nfrom sklearn.metrics import accuracy_score,f1_score,precision_score,recall_score\n\nfrom grakel.datasets import fetch_dataset\nfrom grakel.kernels import WeisfeilerLehman, VertexHistogram\n\n# Loads the MUTAG dataset\nMUTAG = fetch_dataset(\"NCI1\", verbose=False)\nG, y = MUTAG.data, MUTAG.target\nG_train, G_test, y_train, y_test = train_test_split(G, y, test_size=0.3, random_state=11)\nX_train=np.zeros(((len(G_train)),38))\nX_test=np.zeros(((len(G_test)),38))\nfor i in range(len(G_train)):\n graphs=list(G_train[i][1].keys())\n for j in graphs:\n X_train[i,G_train[i][1][j]]+=1\nfor i in range(len(G_test)):\n graphs=list(G_test[i][1].keys())\n for j in graphs:\n X_test[i,G_test[i][1][j]]+=1\nK_train=np.dot(X_train,X_train.T)\nK_test=np.dot(X_test,X_train.T)\nSVC=SVC(kernel=\"precomputed\",C=1)\nSVC.fit(K_train,y_train)\nSVC.predict(K_train)\nprint(\"Accuracy_Train:\", accuracy_score(SVC.predict(K_train),y_train))\nprint(\"Accuracy_Test:\", accuracy_score(SVC.predict(K_test),y_test))\nprint(\"F1-Score_Train:\", f1_score(SVC.predict(K_train),y_train))\nprint(\"F1-Score_test:\", f1_score(SVC.predict(K_test),y_test))\nprint(\"Precision_train:\", precision_score(SVC.predict(K_train),y_train))\nprint(\"Precision_test:\", precision_score(SVC.predict(K_test),y_test))\nprint(\"Recall train:\", recall_score(SVC.predict(K_train),y_train))\nprint(\"Recall test:\", recall_score(SVC.predict(K_test),y_test))","sub_path":"VertexHistogram.py","file_name":"VertexHistogram.py","file_ext":"py","file_size_in_byte":1550,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"541780009","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.db import models, migrations\nimport tethys_compute.utilities\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('tethys_compute', '0005_auto_20150914_1712'),\n ]\n\n operations = [\n migrations.AlterField(\n model_name='tethysjob',\n name='extended_properties',\n field=tethys_compute.utilities.DictionaryField(default=b'', blank=True),\n preserve_default=True,\n ),\n migrations.AlterField(\n model_name='tethysjob',\n name='workspace',\n field=models.CharField(default=b'', max_length=1024),\n preserve_default=True,\n ),\n ]\n","sub_path":"tethys_compute/migrations/0006_auto_20151221_2207.py","file_name":"0006_auto_20151221_2207.py","file_ext":"py","file_size_in_byte":735,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"57741374","text":"# _*_coding=utf-8_*_\r\nimport matplotlib\r\nimport numpy as np\r\nimport matplotlib.pyplot as plt\r\n\r\ndef simple_plot():\r\n \"\"\"\r\n simple plot\r\n \"\"\"\r\n\r\n #产生数据\r\n x = np.linspace(-np.pi,np.pi,256,endpoint=True)\r\n y_sin,y_cos = np.sin(x),np.cos(x)\r\n\r\n #画背景\r\n plt.figure(figsize=(8,6),dpi=80)\r\n plt.title(\"simple wave graph\")\r\n plt.grid(True)\r\n\r\n #X轴\r\n plt.xlabel(\"axis X\")\r\n plt.xlim(-4.0,4.0)\r\n plt.xticks(np.linspace(-4,4,9,endpoint=True))\r\n\r\n #Y轴\r\n plt.ylabel(\"axis Y\")\r\n plt.ylim(-1.0, 1.0)\r\n plt.yticks(np.linspace(-1.0,1.0,9,endpoint=True))\r\n\r\n #画波形\r\n plt.plot(x,y_sin,\"r--\",linewidth=2.0,label=\"sin example\")\r\n plt.plot(x,y_cos,\"b-\",linewidth=2.0,label=\"cos example\")\r\n\r\n plt.legend(loc=\"upper left\", shadow=True)\r\n plt.show()\r\n return\r\n# simple_plot()\r\n\r\n\r\n\r\ndef simple_advanced_plot():\r\n \"\"\"\r\n simple advanced plot\r\n \"\"\"\r\n # 生成测试数据\r\n x = np.linspace(-np.pi, np.pi, 256, endpoint=True)\r\n y_cos, y_sin = np.cos(x), np.sin(x)\r\n # 生成画布,并设置标题\r\n plt.figure(figsize=(8,6),dpi=80)\r\n plt.title(\"fuza wave graph\")\r\n plt.grid(True)\r\n #画图的另外一种方式\r\n ax_1 = plt.subplot(111)\r\n ax_1.plot(x,y_cos,color=\"blue\",linewidth=2.0,linestyle=\"--\",label=\"left cos\")\r\n ax_1.legend(loc=\"upper left\", shadow=True)\r\n #设置Y轴(左边)\r\n ax_1.set_ylabel(\"left cos axis y\")\r\n ax_1.set_ylim(-1.0,1.0)\r\n ax_1.set_yticks(np.linspace(-1,1,9,endpoint=True))\r\n\r\n ax_2 = plt.twinx()\r\n ax_2.plot(x,y_sin,color=\"red\",linewidth=2.0,linestyle=\"-\",label=\"right sin\")\r\n ax_2.legend(loc=\"upper right\", shadow=True)\r\n ax_2.set_ylabel(\"right sin axis y\")\r\n ax_2.set_ylim(-2.0, 2.0)\r\n ax_2.set_yticks(np.linspace(-2,2,9,endpoint=True))\r\n\r\n ax_1.set_xlabel(\"axis x\")\r\n ax_1.set_xlim(-4.0, 4.0)\r\n ax_1.set_xticks(np.linspace(-4,4,9,endpoint=True))\r\n\r\n plt.show()\r\n return\r\n# simple_advanced_plot()\r\n\r\ndef subplot_plot():\r\n \"\"\"\r\n subplot plot\r\n \"\"\"\r\n # 子图的style列表\r\n style_list = [\"r+-\", \"g*-\", \"b.--\", \"yo-\"]\r\n\r\n # 依次画图\r\n for num in range(4):\r\n # 生成测试数据\r\n x = np.linspace(0.0, 2+num, num = 200)\r\n y = np.sin((5-num)*np.pi*x)\r\n # 子图的生成方式\r\n plt.subplot(2, 2, num+1)\r\n plt.title(\"sin%d*pi*x\" % (5-num))\r\n plt.plot(x, y, style_list[num])\r\n\r\n #图形显示\r\n plt.show()\r\n return\r\n\r\nsimple_plot()\r\n#simple_advanced_plot()\r\n#subplot_plot()\r\n","sub_path":"python_visual.py","file_name":"python_visual.py","file_ext":"py","file_size_in_byte":2540,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"247660066","text":"import torch\nimport torch.nn as nn\nimport torch.optim as optim\nfrom torch.utils.data import DataLoader\n\nfrom cbow import CBOW\nfrom datasets import WordContextDataset\n\n\ndef train(_=None,\n corpus=None,\n corpus_path=None,\n context_size=2,\n min_word=1,\n\n embed_dim=100,\n\n n_epoch=10,\n batch_size=32,\n learning_rate=0.001,\n shuffle=True,\n verbose_iterval=1):\n\n if _:\n raise Exception(\"Don't put parameters without keys. Set parameters with the key together.\")\n\n # Load data\n wcd = WordContextDataset(corpus=corpus,\n corpus_path=corpus_path,\n context_size=context_size,\n min_word=min_word)\n\n data_loader = DataLoader(wcd,\n batch_size=batch_size,\n shuffle=shuffle)\n\n # Model\n cbow = CBOW(vocab_size=wcd.vocab_size,\n embed_dim=embed_dim)\n\n # Training Parameters\n optimizer = optim.SGD(cbow.parameters(),\n lr=learning_rate)\n loss_fn = nn.NLLLoss()\n loss_list = []\n\n # Use GPU, if available.\n device = torch.device(\"cuda:0\" if torch.cuda.is_available() else \"cpu\")\n cbow.to(device)\n\n for epoch_i in range(n_epoch):\n for batch_i, (X, Y) in enumerate(data_loader):\n X, Y = X.to(device), Y.to(device)\n cbow.zero_grad()\n\n pred_log_prob = cbow(X)\n\n loss = loss_fn(pred_log_prob, Y)\n\n loss.backward()\n loss_list.append(float(loss.to('cpu').data.numpy()))\n\n optimizer.step()\n\n if epoch_i % verbose_iterval == 0:\n print(\"loss : {:.3f}\".format(loss_list[-1]))\n\n return {'wcd': wcd,\n 'cbow': cbow,\n 'loss_list': loss_list,\n 'data_loader': data_loader}\n\n\n","sub_path":"train.py","file_name":"train.py","file_ext":"py","file_size_in_byte":1899,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"232612517","text":"# -*- coding: utf-8 -*-\r\nimport unittest\r\nimport os\r\nif os.environ.get('HTTP_HOST'):\r\n hostUrl = os.environ['HTTP_HOST']\r\nelse:\r\n hostUrl = os.environ['SERVER_NAME']\r\nfrom google.appengine.api import urlfetch\r\nfrom google.appengine.ext import testbed, webapp\r\nimport urllib2, urllib, datetime\r\nfrom django.utils import simplejson as json\r\nfrom webtest import TestApp\r\nimport DataModels as models\r\nimport MusicHandlerRedo\r\n\r\nclass MusicTester(unittest.TestCase):\r\n def setUp(self):\r\n # First, create an instance of the Testbed class.\r\n self.testbed = testbed.Testbed()\r\n # Then activate the testbed, which prepares the service stubs for use.\r\n self.testbed.activate()\r\n self.testbed.init_urlfetch_stub()\r\n self.application = webapp.WSGIApplication([('/(.*)', MusicHandlerRedo.MusicHandler)], debug=True)\r\n\r\n def tearDown(self):\r\n self.testbed.deactivate()\r\n \r\n## Tests artist Eminem to see if Music Handler gives a 200 response \r\n def test_fortimeout(self):\r\n app = TestApp(self.application)\r\n response = app.get('/?artist=Eminem')\r\n self.assertEqual('200 OK', response.status)\r\n\r\n## Tests artist Eminem to see if Music Handler no errors within the JSON response \r\n def test_forJsonErrors(self):\r\n app = TestApp(self.application)\r\n response = app.get('/?artist=Eminem')\r\n artistJson = json.loads(response.body)\r\n self.assertEqual('0', artistJson['status']['error'])\r\n\r\n## Tests artist Eminem to see if the album 'recovery' exists\r\n def test_EminemForRecoveryAlbum(self):\r\n app = TestApp(self.application)\r\n response = app.get('/?artist=Eminem')\r\n artistJson = json.loads(response.body)\r\n \r\n albums = []\r\n for album in artistJson['albums']:\r\n albums.append(album['title'])\r\n \r\n self.assertTrue('Recovery' in albums)\r\n\r\n## Tests artist múm to see if Music Handler gives a 200 response \r\n def test_forUnicodeArtist(self):\r\n app = TestApp(self.application)\r\n response = app.get(u'/?artist=múm')\r\n artistJson = json.loads(response.body)\r\n self.assertEqual('0', artistJson['status']['error'])\r\n \r\n\r\n","sub_path":"backendgroovebug 1.2.3/test/test_MusicHandlerRedo.py","file_name":"test_MusicHandlerRedo.py","file_ext":"py","file_size_in_byte":2245,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"577762592","text":"from kivy.uix.screenmanager import Screen\nfrom kivy.uix.gridlayout import GridLayout\nfrom kivy.uix.label import Label\nfrom kivy.uix.button import Button\nfrom kivy.uix.popup import Popup\nfrom server import Server\n\nfrom helper.numberinput import NumberInput\n\n\nclass StrengthScreen(Screen):\n def __init__(self, sm, **kwargs):\n self.sm = sm\n super(StrengthScreen, self).__init__(**kwargs)\n self.main_grid = GridLayout(cols=1)\n back_button = Button(text=\"Back\")\n back_button.bind(on_press=self.to_main)\n\n self.main_grid.add_widget(back_button)\n\n self.create_hangboard()\n self.create_weighted_pu()\n\n self.add_widget(self.main_grid)\n\n def create_hangboard(self):\n\n self.main_grid.add_widget(Label(text=\"Hangboard\"))\n pu_grid = GridLayout(cols=5)\n labels = {x: Label(text=x.capitalize()) for x in [\"hang\", \"sets\", \"rest\", \"weight\"]}\n for k in labels:\n pu_grid.add_widget(labels[k])\n pu_grid.add_widget(Label())\n\n inputs = {\n \"hang\": NumberInput(text=\"10\"),\n \"sets\": NumberInput(text=\"5\"),\n \"rest\": NumberInput(text=\"180\"),\n \"weight\": NumberInput(),\n }\n for k in inputs:\n pu_grid.add_widget(inputs[k])\n submit = Button(text=\"Submit\")\n\n submit.bind(on_press=lambda x: self.post(\"hangboard\", inputs))\n pu_grid.add_widget(submit)\n\n self.main_grid.add_widget(pu_grid)\n\n def create_weighted_pu(self):\n self.main_grid.add_widget(Label(text=\"Weighted Pull-Ups\"))\n hang_grid = GridLayout(cols=5)\n hang_grid.add_widget(Label(text=\"Reps\"))\n hang_grid.add_widget(Label(text=\"Sets\"))\n hang_grid.add_widget(Label(text=\"Pause\"))\n hang_grid.add_widget(Label(text=\"Weight\"))\n hang_grid.add_widget(Label())\n hang_grid.add_widget(NumberInput())\n hang_grid.add_widget(NumberInput())\n hang_grid.add_widget(NumberInput())\n hang_grid.add_widget(NumberInput())\n\n submit = Button(text=\"Submit\")\n submit.bind(on_press=lambda x: print(\"Done\"))\n hang_grid.add_widget(submit)\n\n self.main_grid.add_widget(hang_grid)\n\n def to_main(self, *args):\n self.sm.current = 'menu'\n self.sm.transition.direction = 'right'\n\n def post(self, name, data):\n for k, v in data.items():\n if v.text == \"\":\n popup = Popup(title='Invalid',\n content=Label(text='Please fill in everything.'),\n size_hint=(None, None), size=(200, 200))\n popup.open()\n return False\n\n payload = {name: [data[k].text for k in data.keys()]}\n\n s = Server()\n r = s.post(payload)\n\n if r == 200:\n popup = Popup(title='Success',\n content=Label(text='Data submitted'),\n size_hint=(None, None), size=(200, 200))\n popup.open()\n return True\n return False\n","sub_path":"screens/strength.py","file_name":"strength.py","file_ext":"py","file_size_in_byte":3047,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"251219306","text":"import spacy\nimport os\nfrom spacytextblob.spacytextblob import SpacyTextBlob # noqa: F401\nimport pandas as pd\n\nfilename = \"before.csv\"\n\n# Load model and load textblob into pipeline\nnlp = spacy.load(\"en_core_web_sm\")\nnlp.add_pipe(\"spacytextblob\")\n\n# Load csv file to dataframe data\ndata = pd.read_csv(\"Conservative.csv\")\n\ndata[\"Mentioned Nouns\"] = data[\"Mentioned Nouns\"].astype(str)\ndata[\"Entities\"] = data[\"Mentioned Nouns\"]\n\ndata.drop([\"Id\", \"Date_Created_Utc\", \"Score\", \"Parent_id\", \"Link\"], axis=1, inplace=True)\n\nfor i in range(data.shape[0] - 1):\n if data.at[i, \"Body\"] == \"[removed]\" or data.at[i, \"Body\"] == \"[deleted]\":\n data.at[i, \"Sentiment-Subjectivity\"] = 0\n data.at[i, \"Sentiment-Polarization\"] = 0\n data.at[i, \"Mentioned Nouns\"] = \"\"\n\n doc = nlp(data[\"Body\"].iloc[i])\n data.at[i, \"Sentiment-Subjectivity\"] = doc._.subjectivity\n data.at[i, \"Sentiment-Polarization\"] = doc._.polarity\n\n nouns = []\n entities = []\n for ent in doc.ents:\n if ent.label_ != \"PERCENT\" and ent.label_ != \"\":\n nouns.append(ent.text)\n entities.append(ent.label_)\n\n for token in doc:\n if token.ent_type_ == \"\" and (token.pos_ == \"NOUN\" or token.pos_ == \"PRON\"):\n if token.text.lower() != \"i\" and token.text.lower() != \"me\":\n nouns.append(token.text)\n\n data.at[i, \"Mentioned Nouns\"] = \", \".join(nouns)\n data.at[i, \"Entities\"] = \", \".join(entities)\n\nif os.path.exists(filename):\n os.remove(filename)\n\ndata = data.filter([\"Body\", \"Mentioned Nouns\"], axis=1)\n\ndata.to_csv(filename, index=False)\n","sub_path":"tester.py","file_name":"tester.py","file_ext":"py","file_size_in_byte":1594,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"533196169","text":"from peewee import (\n BigIntegerField, TextField, DateTimeField, CompositeKey, IntegerField\n)\nfrom datetime import datetime\nfrom holster.enum import Enum\n\nfrom rowboat.sql import BaseModel\n\n\n@BaseModel.register\nclass CustomCommands(BaseModel):\n Types = Enum(\n 'CMD',\n 'LISTEN',\n bitmask=False,\n )\n\n ListenTypes = Enum(\n 'GuildMemberAdd',\n 'GuildMemberRemove',\n 'GuildMemberUpdate',\n 'GuildMembersChunk',\n 'GuildRoleCreate',\n 'GuildRoleUpdate',\n 'GuildRoleDelete',\n 'GuildEmojisUpdate',\n 'ChannelCreate',\n 'ChannelUpdate',\n 'ChannelDelete',\n 'VoiceStateUpdate',\n 'MessageCreate',\n 'PresenceUpdate',\n bitmask=False,\n )\n\n guild_id = BigIntegerField()\n author_id = BigIntegerField()\n\n type_ = IntegerField(db_column='type')\n listen_type_ = IntegerField(db_column='listen_type',default=0)\n\n name = TextField()\n command = TextField()\n times_used = IntegerField(default=0)\n\n created_at = DateTimeField(default=datetime.utcnow)\n\n class Meta:\n db_table = 'custom_commands'\n primary_key = CompositeKey('guild_id', 'name')\n\n @classmethod\n def create_cust(cls, plugin, event, name, cmdtype, ltype, content):\n cls.create(\n guild_id=event.guild.id,\n author_id=event.author.id,\n name=name,\n command=content,\n type_=cmdtype,\n listen_type_=ltype\n )\n","sub_path":"rowboat/models/custcommands.py","file_name":"custcommands.py","file_ext":"py","file_size_in_byte":1500,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"188062962","text":"from random import randint\n\nimport cerberus\nimport pytest\n\n\nclass TestJsonApi():\n\n def test_get_posts(self, client_json):\n num = randint(1, 100)\n res = client_json.get_resourses(path=f'/posts/{num}')\n schema = {\n \"id\": {\"type\": \"number\"},\n \"userId\": {\"type\": \"number\"},\n \"title\": {\"type\": \"string\"},\n \"body\": {\"type\": \"string\"}\n }\n v = cerberus.Validator()\n assert v.validate(res.json(), schema)\n\n @pytest.mark.parametrize('input_id, output_id',\n [(23, '23'),\n (12, '12'),\n (6, '6')])\n @pytest.mark.parametrize('input_title, output_title',\n [('title', 'title'),\n ('Cool', 'Cool'),\n ('Mool', 'Mool'),\n ('Diz', 'Diz')])\n def test_api_post_request(self, client_json, input_id, output_id, input_title, output_title):\n res = client_json.post_data(\n path=\"/posts\",\n data={'title': input_title, 'body': 'Some body about body', 'userId': input_id})\n res_json = res.json()\n assert res_json['title'] == output_title\n assert res_json['body'] == 'Some body about body'\n assert res_json['userId'] == output_id\n\n @pytest.mark.parametrize('userId', [1, 2, 3, 4, 5, 6, 7])\n def test_get_user_by_id(self, client_json, userId):\n res = client_json.get_resourses(path='/posts',\n params={'userId': userId})\n assert res.json() != [], 'Сервис прислал пустой ответ'\n\n @pytest.mark.parametrize('userId', [13, 'r', 34, 'y'])\n def test_get_user_by_id(self, client_json, userId):\n res = client_json.get_resourses(path='/posts',\n params={'userId': userId})\n assert res.json() == [], 'Ошибка фильтра'\n\n @pytest.mark.parametrize('postId', [1, 2, 3, 4, 5, 6, 7, 8, 9])\n def test_get_comments_by_post_id(self, client_json, postId):\n res = client_json.get_resourses(path='/comments',\n params={'postId': postId})\n assert res.json() != [], 'Ошибка фильтра'\n","sub_path":"api_tests/tests/test_json_placeholder_api.py","file_name":"test_json_placeholder_api.py","file_ext":"py","file_size_in_byte":2304,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"563831496","text":"import os\nimport requests\nimport yaml\nimport datetime\n\n\nclass Sports(object):\n \"\"\" Class for the 'sports' category. Handles all slackbot commands for sports. \"\"\"\n\n def __init__(self):\n \"\"\" Initializes the Sports category class. Assumes the SPORTS_API_TOKEN is in the environment.\n\n :return: None\n \"\"\"\n\n with open(os.path.join(os.path.dirname(os.path.realpath(__file__)), \"sports.yml\")) as fp:\n self._league_info = yaml.safe_load(fp)\n\n self._sport = None\n self._league = None\n self._action = None\n\n self._params = {}\n\n # Initial response for slackbot\n self._response = \"Not enough information. Please supply more.\"\n\n # Stattleship API token\n self.__api_token = os.environ.get(\"SPORTS_API_TOKEN\")\n\n # Base URL and version of Stattleship's REST API\n self._base_url = \"https://www.stattleship.com\"\n self._version = 1\n\n # Authorization headers for Stattleship's REST API\n self.__headers = {\n 'Authorization': self.__api_token,\n 'Accept': 'application/vnd.stattleship.com; version=%s' % self._version,\n 'Content-Type': 'application/json',\n }\n\n @property\n def sport(self):\n \"\"\" Get method for the sport \"\"\"\n return self._sport\n\n @sport.setter\n def sport(self, updated_sport):\n \"\"\" Set method for the sport \"\"\"\n self._sport = updated_sport\n\n @property\n def league(self):\n \"\"\" Get method for the league in a given sport \"\"\"\n return self._league\n\n @league.setter\n def league(self, updated_league):\n \"\"\" Set method for the league in a given sport \"\"\"\n self._league = updated_league\n\n @property\n def response(self):\n \"\"\" Get method for the response to the 'sports' subcommand \"\"\"\n return self._response\n\n @response.setter\n def response(self, updated_response):\n \"\"\" Set method for the response to the 'sports' subcommand \"\"\"\n self._response = updated_response\n\n def action_games(self, response_data):\n \"\"\" Handle the user command action 'sports games '\n\n :param response_data: JSON object retrieved from GET request of Stattleship\n\n :return: None\n \"\"\"\n\n # Response formatting based on the status of the game data\n if self._params[\"status\"] == \"in_progress\":\n response_str = \"Live\"\n elif self._params[\"status\"] == \"upcoming\":\n response_str = \"Upcoming\"\n else:\n response_str = \"Past\"\n\n on_date = self._params.get(\"on\", \"\")\n\n # Get the 'games' data in the JSON response\n games = response_data.get(\"games\", [])\n\n if games:\n\n # Update the response with the games retrieved from the API\n self.response = response_str + \" games for \" + self._league.upper()\n\n # Response formatting\n if on_date:\n self.response += \" on \" + on_date + \"\\n\\n\"\n else:\n self.response += \"\\n\\n\"\n\n # Loop through all fetched games\n for game in games:\n\n # If the status of the game is in_progress, we need to compare today's date with the game's date\n # This is used for data verification\n if self._params[\"status\"] == \"in_progress\":\n current_date = datetime.datetime.now().strftime(\"%Y%m%d\")\n game_date = game.get(\"started_at\")\n\n if game_date:\n game_date = game_date.split('T')[0].replace('-', '')\n\n # If the dates are not the same, skip this game in the data\n if current_date != game_date:\n continue\n\n # Get the name of the game and the score\n game_details = game.get(\"name\")\n score = game.get(\"score\")\n\n # Update the response with the data\n if game_details and score:\n self.response += game_details + \"\\nScore: \" + score + \"\\n\\n\"\n else:\n self.response = \"No \" + self._league.upper() + \" games found.\"\n\n def parse_command(self, command):\n \"\"\" Given the user's command, parse it looking for data the slackbot can handle and use.\n\n :param command: List of strings corresponding to the user's command\n\n :return: Boolean variable that is True when slackbot can successfully parse the command\n \"\"\"\n\n if len(command) < 2:\n return\n\n self._sport = command[0].strip().lower()\n self._league = self._league_info[self._sport]\n self._action = command[1].strip().lower()\n\n remaining_params = command[2:]\n\n # If the user is performing the 'games' action\n if self._action == \"games\" and len(remaining_params) >= 1:\n\n # The user must specify if they want live games, upcoming games, or ended games\n if remaining_params[0] == \"live\":\n self._params[\"status\"] = \"in_progress\"\n elif remaining_params[0] == \"ended\" or remaining_params[0] == \"upcoming\":\n self._params[\"status\"] = remaining_params[0]\n else:\n self.response = \"I don't understand the game status. Try 'live' or 'upcoming' or 'ended'.\"\n return False\n\n # Get the 'on date' parameters\n if remaining_params[1:]:\n self._params[\"on\"] = remaining_params[1]\n\n return True\n\n return False\n\n def get_response(self, command):\n \"\"\" Compute a response for the user-inputted command.\n\n :param command: List of strings corresponding to the user's command\n\n :return: The response computed by the slackbot\n \"\"\"\n\n # If we can successfully parse the command\n if self.parse_command(command):\n\n # Create REST API URL and send a GET request with the authorization headers and parameters\n url = self._base_url + \"/{}/{}/{}\".format(self._sport, self._league, self._action)\n res = requests.get(url, params=self._params, headers=self.__headers)\n\n # If the GET request was successful\n if res.status_code == requests.codes.ok:\n response_data = res.json()\n\n if self._action == \"games\":\n self.action_games(response_data)\n\n else:\n self.response = \"I don't understand that. Please try again.\"\n\n return self.response\n","sub_path":"slackbot/categories/sports/sports.py","file_name":"sports.py","file_ext":"py","file_size_in_byte":6561,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"531220214","text":"import matplotlib.pyplot as plt\nimport numpy as np\nfrom scipy.optimize import curve_fit\nfrom cuts import mc_df as df\n\n# Test fit for the cos_thet distribution of the electrons.\nangle = df.loc[(df['ptype'] == 'e') & (df['cos_thet'] < 2), 'cos_thet']\n\n\n# Function we want to fit to the data\ndef fit_function(x, A, B):\n return (A * (1 + x**2) + B / (1 - x)**2)\n\n\n# Separate function the s channel\ndef s_channel(x, A):\n return (A * (1 + x**2))\n\n\n# Separate function the s channel\ndef t_channel(x, B):\n return (B / (1 - x)**2)\n\n\n# Integrals to calculate cuts\n# Primitive of the s channel.\n\n\ndef primitive_A(x, A):\n return (A * (x**3 / 3 + x))\n\n\n# Primitive of the t channel.\ndef primitive_B(x, B):\n return (B / (1 - x))\n\n\n# Bined data.\nangle_binned, bins = np.histogram(angle, bins=np.linspace(-.9, .9, 36 * 9))\n\n# Calculate bin centers\nbincenters = (bins[1:] + bins[:-1]) / 2\n\n# fit using curve_fit\npopt, pcov = curve_fit(fit_function,\n xdata=bincenters,\n ydata=angle_binned,\n sigma=np.sqrt(angle_binned),\n p0=[100, 10])\n\n# Plotting the results\n# xvalues for the plotting\nxspace = np.linspace(-1, 1, 360, endpoint=False)\n\nif __name__ == \"__main__\":\n # the plots\n plt.hist(angle, bins=bins)\n\n plt.plot(xspace,\n fit_function(xspace, *popt),\n color='darkorange',\n linewidth=2.5,\n label=r'Fitted function')\n\n plt.plot(xspace, s_channel(xspace, popt[0]), color='b', label='s')\n plt.plot(xspace, t_channel(xspace, popt[1]), color='g', label='t')\n\n plt.ylim(0, 1.1 * max(angle_binned))\n plt.legend()\n\n# Cuts to get just the s channel electrons\nupper_cut = 0.\nlower_cut = -0.9\n\n# Efficiency of the cut, calculated by dividing the integral of the s-channel\n# function for the given interval with the integral of the over all function\n# for the given interval.\nefficiency = (\n primitive_A(upper_cut, popt[0]) - primitive_A(lower_cut, popt[0])) / (\n primitive_A(upper_cut, popt[0]) + primitive_B(upper_cut, popt[1]) -\n primitive_A(lower_cut, popt[0]) - primitive_B(lower_cut, popt[1]))\n\nc = (upper_cut**3 / 3 + upper_cut - lower_cut**3 / 3 - lower_cut)\nd = 1 / (1 - upper_cut) - 1 / (1 - lower_cut)\n\ngradient = np.array([\n c * d / (c * popt[0] + d * popt[1])**2 * popt[1],\n -c * d / (c * popt[0] + d * popt[1])**2 * popt[0]\n])\n\nerr_efficiency = np.sqrt(gradient.dot(pcov.dot(gradient)))\n\n# Calculate the s channel correction factor. As our selection is extremely\n# picky, we miss many s channel electrons so we have to correct by the ratio of\n# the s channel primitive over the whole region divided by the integral over\n# the narrow (picky) region.\n# If one works out the math, one finds that the result doesn't depend on the\n# fit parameters and is an exact calue\ns_channel_correction = 8 / \\\n (upper_cut**3 - lower_cut**3 + 3 * (upper_cut - lower_cut))\n\nif __name__ == \"__main__\":\n # Print fit parameters\n print(popt)\n # Print the efficiency\n print(\"electron s-channel efficiency:\",\n f\"{efficiency} +- {err_efficiency}\")\n plt.show()\n","sub_path":"part2/hists/cosfit.py","file_name":"cosfit.py","file_ext":"py","file_size_in_byte":3142,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"192055881","text":"from aiogram import Bot, Dispatcher, executor, types\nfrom aiogram.types import InlineQueryResultArticle, InputTextMessageContent\nimport hashlib\n\nfrom settings import TOKEN\n\nbot = Bot(TOKEN)\ndp = Dispatcher(bot)\n\nNUMBER = 0\n\n@dp.message_handler(commands=['start'])\nasync def cmd_command(message: types.Message) -> None:\n await message.answer(text='Введите число')\n\n\n@dp.message_handler()\nasync def number_handler(message: types.Message) -> None:\n global NUMBER\n try:\n NUMBER = int(message.text)\n except:\n return await message.reply('Необходимо ввести число')\n await message.reply(text=\"Ваши данные сохранены\")\n\n\n@dp.inline_handler()\nasync def inl_mode(inline_query: types.InlineQuery) -> None:\n text = InputTextMessageContent(f\"{inline_query.query} - {NUMBER}\", parse_mode='html') or 'Echo'\n result_id = hashlib.md5(inline_query.query.encode()).hexdigest()\n\n item = InlineQueryResultArticle(\n input_message_content=text,\n id=result_id,\n title='This is the description'\n )\n\n await bot.answer_inline_query(inline_query_id=inline_query.id,\n results=[item],\n cache_time=1)\n\nif __name__ == '__main__':\n executor.start_polling(dp, skip_updates=True)","sub_path":"shelmakova_bot/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1335,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"563009837","text":"#*********************\n#python imports\n#*********************\nimport os\nimport shutil\nimport glob\nimport sys\n#*********************\n#vendor imports\n#*********************\nimport requests\n\nclass Requests_Filling_Wrapper(object):\n \"\"\"\n wrapper class for file functions using http requests\n \"\"\"\n\n def stream_read_file(self,url,temp_file_dir,file_name):\n \"\"\"\n read a file by streaming it from a url,\n save to a temporary file,read into a memory and delete the file\n\n Args\n :param url: url to the json file\n :param temp_file_dir: path to the temporay file directory\n :param file_name: name.ext of the file\n Returns:\n :rtype string|byte: string or byte content of the file\n \"\"\"\n #FIELDS\n File_content=\"\"\n File_path=os.path.join(temp_file_dir,file_name)\n\n try:\n #stream the json file with HTTP request\n Request_response=get(url,stream=True)\n #check file directory path exists\n if (os.path.isdir(temp_file_dir)):\n #create the temporary file for writing\n with open(File_path,\"wb\") as File_obj:\n #read the streamed HTTP file raw content in iterated chunks\n #reading 128kb per iteration\n for File_chunk in Request_response.iter_content(chunk_size=128):\n #write the stream chunks read into the temporary file instead of holding in memory\n File_obj.write(File_chunk)\n else:\n raise Exception((\"{0} dir does not exist\").format(temp_file_dir))\n #check file path exists\n if (os.path.isfile(File_path)):\n #open the saved file\n with open(File_path,\"r+\") as File_obj:\n #read the file object\n File_content=File_obj.read()\n #delete the temporary file\n os.remove(File_path)\n #return the file content\n return File_content\n else:\n raise Exception((\"{0} file does not exist\").format(File_path))\n except Exception as e:\n Exception_message=(\"[Util_filling(Exception)]=>{0}\").format(str(e))\n raise Exception(Exception_message)\n\n def save_to_url_media_file(self,file_obj, file_name, file_type, allowed_types, save_url):\n \"\"\"\n save application media files\n \"\"\"\n\n if file_type in allowed_types:\n\n #read file\n file_read=file_obj.read()\n\n #save\n multipart_form_data={\n file_name:file_read\n }\n\n response=requests.post(save_url,files=multipart_form_data)\n\n if response.ok:\n if response.status_code!=200:\n raise Exception(\"file not saved-status:\"+response.status_code)\n else:\n raise Exception(\"error saving file\")\n else:\n raise Exception(\"media file type not allowed\")","sub_path":"neox_medipip/neox_medipip_core/core_libs/neox_lib_toolraemon/filling/requests_filling_wrapper.py","file_name":"requests_filling_wrapper.py","file_ext":"py","file_size_in_byte":3070,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"487557231","text":"class Solution:\n def countPrimeSetBits(self, L: int, R: int) -> int:\n primes = {2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31}\n ans = 0\n for x in range(L, R + 1):\n s = bin(x)\n a = s.count(\"1\")\n if a in primes:\n ans += 1\n return ans\n\n\ns = Solution()\nprint(s.countPrimeSetBits(990, 1048))\n","sub_path":"leetcode/2020/prime-number-of-set-bits-in-binary-representation.py","file_name":"prime-number-of-set-bits-in-binary-representation.py","file_ext":"py","file_size_in_byte":359,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"447083339","text":"# -*- coding: utf-8 -*-\n#\n# This file is part of Sequana software\n#\n# Copyright (c) 2018 - Sequana Development Team\n#\n# File author(s):\n# Thomas Cokelaer \n#\n# Distributed under the terms of the 3-clause BSD license.\n# The full license is in the LICENSE file, distributed with this software.\n#\n# website: https://github.com/sequana/sequana\n# documentation: http://sequana.readthedocs.io\n#\n##############################################################################\nfrom sequana.lazy import pylab\nfrom sequana.lazy import pandas as pd\nfrom sequana import logger\n\nlogger.name = __name__\n\n\n__all__ = [\"BUSCO\"]\n\n\nclass BUSCO(object):\n \"\"\"Wrapper of the BUSCO output\n\n \"BUSCO provides a quantitative measures for the assessment\n of a genome assembly, gene set, transcriptome completeness, based on\n evolutionarily-informed expectations of gene content from near-universal\n single-copy orthologs selected from OrthoDB v9.\" -- BUSCO website 2017\n\n This class reads the full report generated by BUSCO and provides some\n visualisation of this report. The information is stored in a dataframe\n :attr:`df`. The score can be retrieve with the attribute :attr:`score` in\n percentage in the range 0-100.\n\n :reference: http://busco.ezlab.org/\n \"\"\"\n def __init__(self, filename=\"full_table_testbusco.tsv\"):\n \"\"\".. rubric:: constructor\n\n :filename: a valid BUSCO input file (full table). See example in sequana\n code source (testing)\n\n \"\"\"\n self.df = pd.read_csv(filename, sep=\"\\t\", skiprows=4)\n\n def pie_plot(self, filename=None, hold=False):\n \"\"\"Plot PIE plot of the status (complete / fragment / missed)\n\n .. plot::\n :include-source:\n\n from sequana import BUSCO, sequana_data\n b = BUSCO(sequana_data(\"test_busco_full_table.tsv\"))\n b.pie_plot()\n\n \"\"\"\n if hold is False:\n pylab.clf()\n self.df.groupby('Status').count()['# Busco id'].plot(kind=\"pie\")\n pylab.ylabel(\"\")\n #pylab.title(\"Distribution Complete/Fragmented/Missing\")\n #pylab.legend()\n if filename:\n pylab.savefig(filename)\n\n def scatter_plot(self, filename=None, hold=False):\n \"\"\"Scatter plot of the score versus length of each ortholog\n\n .. plot::\n :include-source:\n\n from sequana import BUSCO, sequana_data\n b = BUSCO(sequana_data(\"test_busco_full_table.tsv\"))\n b.scatter_plot()\n\n\n Missing are not show since there is no information about contig .\n \"\"\"\n if hold is False:\n pylab.clf()\n colors = [\"green\", \"orange\", \"red\", \"blue\"]\n markers = ['o', 's', 'x', 'o']\n for i, this in enumerate([\"Complete\", \"Fragmented\", \"Duplicated\"]):\n mask = self.df.Status == this\n if sum(mask)>0:\n self.df[mask].plot(x=\"Length\", y=\"Score\", kind=\"scatter\", \n color=colors[i], ax=pylab.gca(),\n marker=markers[i], label=this)\n\n pylab.legend()\n pylab.grid()\n if filename:\n pylab.savefig(filename)\n\n def summary(self):\n \"\"\"Return summary information of the missing, completed, fragemented\n orthologs\n\n \"\"\"\n df = self.df.drop_duplicates(subset=[\"# Busco id\"])\n data = {}\n data['S'] = sum(df.Status == \"Complete\")\n data['F'] = sum(df.Status == \"Fragmented\")\n data['D'] = sum(df.Status == \"Duplicated\")\n data['C'] = data['S'] + data['D']\n data['M'] = sum(df.Status == \"Missing\")\n data['total'] = len(df)\n data['C_pc'] = data['C'] *100. / data['total']\n data['D_pc'] = data['D'] *100. / data['total']\n data['S_pc'] = data['S'] *100. / data['total']\n data['M_pc'] = data['M'] *100. / data['total']\n data['F_pc'] = data['F'] *100. / data['total']\n return data\n\n def get_summary_string(self):\n data = self.summary()\n C = data['C_pc']\n F = data[\"F_pc\"]\n D = data[\"D_pc\"]\n S = data[\"S_pc\"]\n M = data[\"M_pc\"]\n N = data[\"total\"]\n string = \"C:{:.1f}%[S:{:.1f}%,D:{:.1f}%],F:{:.1f}%,M:{:.1f}%,n:{}\"\n return string.format(C, S, D, F, M, N)\n\n def _get_score(self):\n return self.summary()[\"C_pc\"]\n score = property(_get_score)\n\n def __str__(self):\n data = self.summary()\n C = data['C']\n F = data[\"F\"]\n D = data[\"D\"]\n S = data[\"S\"]\n M = data[\"M\"]\n N = data[\"total\"]\n string = \"\"\"# BUSCO diagnostic\n\n{}\n\n {} Complete BUSCOs (C)\n {} Complete and single-copy BUSCOs (S)\n {} Complete and duplicated BUSCOs (D)\n {} Fragmented BUSCOs (F)\n {} Missing BUSCOs (M)\n {} Total BUSCO groups searched\n \"\"\"\n return string.format(self.get_summary_string(), C, S, D, F, M, N)\n","sub_path":"sequana/assembly.py","file_name":"assembly.py","file_ext":"py","file_size_in_byte":4931,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"159558699","text":"import requests\nimport re\nfrom shopvisit.random_header import RandomHeader\nfrom lxml import html\nimport threading\nfrom time import ctime,sleep\nfrom shopvisit_model import ShopvisitModel\nimport random\n\n\ncategory_urls = [\n \"https://www.tmall.com/wow/chaoshi/act/catpopup?wh_id=jksp&wh_logica=HD\",\n \"https://www.tmall.com/wow/chaoshi/act/catpopup?wh_id=spyl&wh_logica=HD\",\n \"https://www.tmall.com/wow/chaoshi/act/catpopup?wh_id=lyfs&wh_logica=HD\",\n \"https://www.tmall.com/wow/chaoshi/act/catpopup?wh_id=mrxh&wh_logica=HD\",\n \"https://www.tmall.com/wow/chaoshi/act/catpopup?wh_id=jjjd&wh_logica=HD\",\n \"https://www.tmall.com/wow/chaoshi/act/catpopup?wh_id=jtqj&wh_logica=HD\",\n \"https://www.tmall.com/wow/chaoshi/act/catpopup?wh_id=myyp&wh_logica=HD\",\n \"https://www.tmall.com/wow/chaoshi/act/category?wh_logica=HD\"\n]\n\ndef start_requests(category_url):\n randomHeader = RandomHeader()\n ip = randomHeader.random_ip()\n ua = randomHeader.random_ua()\n\n session = requests.session()\n headers = {}\n headers['User-Agent'] = ua\n headers['Host'] = 'www.tmall.com'\n proxies = {\"https\": \"http://\" + ip}\n list_urls = []\n r = session.get(category_url, headers=headers, proxies=proxies)\n list_data = r.json()\n # print(list_data)\n # 遍历分类url地址\n if \"catpopup\" in category_url:\n for cate_url in list_data['data']['cats']:\n # print(cate_url['title'] + \":\" + cate_url['link'])\n list_urls.append(\"https:\" + cate_url['link'])\n elif \"category\" in category_url:\n for cate_url in list_data['data']:\n if cate_url['name'] == \"生鲜水果\":\n for recommend in cate_url['recommends']:\n # print(recommend['name']+\":\"+\"https:\" + recommend['link'])\n list_urls.append(\"https:\" + recommend['link'])\n return list_urls\n\n\ndef parse(list_url):\n randomHeader = RandomHeader()\n ip = randomHeader.random_ip()\n ua = randomHeader.random_ua()\n\n session = requests.session()\n\n headers = {\n 'User-Agent':ua,\n 'Accept':'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',\n 'Accept-Encoding':'gzip, deflate, br',\n 'Accept-Language':'zh-CN,zh;q=0.8,en-US;q=0.5,en;q=0.3',\n 'Connection':'keep-alive',\n 'Referer':'https://chaoshi.tmall.com/',\n 'Upgrade-Insecure-Requests':'1',\n }\n proxies = {\"https\": \"http://\" + ip}\n\n # 每个列表页会进行几次跳转,获取到cookie\n headers['Host'] = 'list.tmall.com'\n res = session.get(list_url, headers=headers, allow_redirects=False, proxies=proxies)\n # res = session.get(list_url, headers=headers, allow_redirects=False)\n # sleep(1)\n headers['Host'] = 'login.taobao.com'\n res = session.get(res.headers['Location'], headers=headers, allow_redirects=False, proxies=proxies)\n # res = session.get(res.headers['Location'], headers=headers, allow_redirects=False)\n # sleep(1)\n headers['Host'] = 'pass.tmall.com'\n res = session.get(res.headers['Location'], headers=headers, allow_redirects=False, proxies=proxies)\n # res = session.get(res.headers['Location'], headers=headers, allow_redirects=False)\n cookies = res.cookies\n # sleep(1)\n headers['Host'] = 'list.tmall.com'\n res = session.get(res.headers['Location'], headers=headers, cookies=cookies, allow_redirects=False, proxies=proxies)\n # res = session.get(res.headers['Location'], headers=headers, cookies=cookies, allow_redirects=False)\n # sleep(1)\n parse_product(session, res.headers['Location'], headers, cookies, proxies)\n from_url = res.headers['Location']\n # res = session.get(res.headers['Location'], headers=headers, cookies=cookies, allow_redirects=False, proxies=proxies)\n # res = session.get(res.headers['Location'], headers=headers, cookies=cookies, allow_redirects=False)\n # print(res.content)\n # cookies = dict(cookies)\n # print(cookies)\n\ndef parse_product(session, url, header, cookie, proxy = '', from_url = ''):\n shopvisitModel = ShopvisitModel()\n if not from_url.strip():\n header['Referer'] = from_url\n res = session.get(url, headers=header, cookies=cookie, allow_redirects=False, proxies=proxy)\n # res = session.get(url, headers=header, cookies=cookie, allow_redirects=False)\n # print(res.content)\n tree = html.fromstring(res.text)\n item_nodes = tree.xpath(\"//div[@class='mainItemsList']//li[@data-itemid]\")\n # print(item_nodes)\n\n # 得到商品数据\n item = {}\n for each in item_nodes:\n url = each.xpath(\".//h3/a/@href\")[0]\n item['product_id'] = re.search(\"id=(\\d+)\", url).group(1)\n product_name = each.xpath(\".//h3/a/text()\")\n product_name = product_name[0].replace('\\n', '').replace(' ', '')\n if \"【天猫超市】\" in product_name:\n item['product_name'] = product_name.replace('【天猫超市】', '')\n else:\n item['product_name'] = product_name\n try:\n item['buy_num'] = each.xpath(\".//div[@class='item-sum']/strong/text()\")[0]\n except:\n item['buy_num'] = 0\n item['price'] = each.xpath(\".//span[@class='ui-price']/strong/text()\")[0]\n item['plat'] = 'tm'\n item['detail'] = ''\n item['from_url'] = url\n # print(item)\n insert_res = shopvisitModel.insert_item(item)\n # print(insert_res)\n secs = [15,16,17,18,19,20]\n sec = random.choice(secs)\n sleep(sec)\n # 翻页\n page_next_node = tree.xpath(\"//a[@class='page-next']/@href\")[0]\n # print(page_next_node)\n page_next_url = \"https://list.tmall.com/search_product.htm\" + page_next_node\n parse_product(session, page_next_url, header, cookie, proxy, url)\n # res = session.get(page_next_url, headers=headers, cookies=cookies, allow_redirects=False)\n # print(res.text)\n\n\n# 获取二级分类列表地址\nlist_urls = start_requests(random.choice(category_urls))\n# print(list_urls)\n\n# parse(list_urls[0])\n# 多线程执行\nif len(list_urls) > 0:\n threads = []\n for list_url in list_urls:\n t = threading.Thread(target=parse,args=(list_url,))\n t.setDaemon(True)\n threads.append(t)\n\n for t in threads:\n t.start()\n\n for t in threads:\n t.join()","sub_path":"tmall_spider.py","file_name":"tmall_spider.py","file_ext":"py","file_size_in_byte":6244,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"523815725","text":"import json\nimport logging\n\nimport requests\nfrom pyramid.httpexceptions import HTTPNotFound\nfrom pyramid.view import view_config\nfrom sqlalchemy.orm.exc import NoResultFound\n\nfrom ..auth.jwt import create_token\nfrom ..models.auth import Role, User\n\nlog = logging.getLogger(__name__)\n\n\n@view_config(route_name='oauth2-google', renderer='json', request_method='POST')\ndef google(request):\n access_token_url = 'https://accounts.google.com/o/oauth2/token'\n people_api_url = 'https://www.googleapis.com/plus/v1/people/me/openIdConnect'\n payload = dict(client_id=request.json['clientId'],\n redirect_uri=request.json['redirectUri'],\n client_secret=request.registry.settings['GOOGLE_SECRET'],\n code=request.json['code'],\n grant_type='authorization_code')\n\n # Step 1. Exchange authorization code for access token.\n r = requests.post(access_token_url, data=payload)\n token = json.loads(r.text)\n headers = {'Authorization': 'Bearer {0}'.format(token['access_token'])}\n\n # Step 2. Retrieve information about the current user.\n r = requests.get(people_api_url, headers=headers)\n profile = json.loads(r.text)\n\n try:\n user = request.db_session.query(User).filter_by(google=profile['sub']).one()\n except NoResultFound:\n user = create_user(request.db_session, profile['email'], _google=profile['sub'])\n if user is None:\n raise HTTPNotFound()\n\n token = create_token(user)\n return dict(token=token)\n\n\n@view_config(route_name='oauth2-facebook', renderer='json', request_method='POST')\ndef facebook(request):\n access_token_url = 'https://graph.facebook.com/v2.3/oauth/access_token'\n graph_api_url = 'https://graph.facebook.com/v2.3/me'\n params = {\n 'client_id': request.json['clientId'],\n 'redirect_uri': request.json['redirectUri'],\n 'client_secret': request.registry.settings['FACEBOOK_SECRET'],\n 'code': request.json['code']\n }\n\n # Step 1. Exchange authorization code for access token.\n r = requests.get(access_token_url, params=params)\n access_token = json.loads(r.text)\n\n # Step 2. Retrieve information about the current user.\n r = requests.get(graph_api_url, params=access_token)\n profile = json.loads(r.text)\n\n try:\n user = request.db_session.query(User).filter_by(facebook=profile['id']).one()\n except NoResultFound:\n user = create_user(request.db_session, profile['email'], _facebook=profile['id'])\n if user is None:\n raise HTTPNotFound()\n\n token = create_token(user)\n return dict(token=token)\n\n\n@view_config(route_name='oauth2-live', renderer='json', request_method='POST')\ndef live(request):\n body = request.body.decode(\"utf-8\")\n body = json.loads(body)\n\n access_token_url = 'https://login.live.com/oauth20_token.srf'\n profile_url = 'https://apis.live.net/v5.0/me?access_token='\n payload = {\n 'client_id': request.json['clientId'],\n 'redirect_uri': request.json['redirectUri'],\n 'client_secret': request.registry.settings['LIVE_SECRET'],\n 'code': body['code'],\n 'grant_type': 'authorization_code',\n }\n\n # Step 1. Exchange authorization code for access token.\n r = requests.post(access_token_url, data=payload)\n token = json.loads(r.text)\n\n # Step 2. Retrieve information about the current user.\n r = requests.get(profile_url + token['access_token'])\n profile = json.loads(r.text)\n\n try:\n user = request.db_session.query(User).filter_by(live=profile['id']).one()\n except NoResultFound:\n user = create_user(request.db_session, profile['emails']['account'], _live=profile['id'])\n if user is None:\n raise HTTPNotFound()\n\n token = create_token(user)\n return dict(token=token)\n\n\ndef create_user(db_session, email, _google=None, _facebook=None, _live=None):\n \"\"\"\n :type db_session: ``sqlalchemy.orm.Session``\n :return: Created or updated user\n \"\"\"\n log.info('Request to create user for email %s', email)\n try:\n user = db_session.query(User).filter_by(email=email).one()\n except NoResultFound:\n role = db_session.query(Role).filter_by(is_default=True).one()\n user = User(email, role)\n db_session.add(user)\n\n if _google is not None:\n user.google = _google\n elif _facebook is not None:\n user.facebook = _facebook\n elif _live is not None:\n user.live = _live\n\n db_session.flush()\n return user\n","sub_path":"canopus/auth/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":4519,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"593631718","text":"import tables\nimport h5py\nimport os\nimport numpy as np\nimport pickle\nfrom tqdm import tqdm\nfrom Widefield_Utils import widefield_utils\n\n\n\ndef create_analysis_dataset(tensor_directory, nested_session_list, condition_list, analysis_name, start_window, stop_window):\n\n \"\"\"\n Nested Session List Should Be The Following Structure\n Level 1 - Mouse\n Level 2 - Condition\n Level 3 - Session\n\n First Create An Intermediate HDF5 Dataset - With Trial As The First Dimension\n Then Reshape This to A h5 Dataset - With Timepoint As The First Dimension\n \"\"\"\n\n # Get Tensor Details\n indicies, image_height, image_width = widefield_utils.load_tight_mask()\n indicies, image_height, image_width = widefield_utils.downsample_mask_further(indicies, image_height, image_width)\n\n number_of_timepoints = stop_window - start_window\n\n number_of_pixels = np.shape(indicies)[1]\n print(\"Nubmer of pixels\", number_of_pixels)\n print(\"Number of timepoints\", number_of_timepoints)\n\n # Open File\n analysis_dataset_file = tables.open_file(filename=os.path.join(tensor_directory, analysis_name + \"_Trialwise_.h5\"), mode=\"w\")\n activity_dataset = analysis_dataset_file.create_earray(analysis_dataset_file.root, 'Data', tables.Float32Atom(), shape=(0, number_of_timepoints, number_of_pixels))\n metadata_dataset = analysis_dataset_file.create_earray(analysis_dataset_file.root, 'Trial_Details', tables.UInt16Atom(), shape=(0, 3))\n\n # Iterate Through Each Session\n mouse_index = 0\n session_index = 0\n\n for mouse in nested_session_list:\n learning_index = 0\n for learning_stage in mouse:\n for session in learning_stage:\n for condition in condition_list:\n\n # Get Tensor Name\n tensor_name = condition.replace(\"_onsets.npy\", \"\")\n tensor_name = tensor_name.replace(\"_onset_frames.npy\", \"\")\n\n\n\n # Open Trial Tensor\n session_trial_tensor_dict_path = os.path.join(tensor_directory, session, tensor_name)\n with open(session_trial_tensor_dict_path + \".pickle\", 'rb') as handle:\n session_trial_tensor_dict = pickle.load(handle)\n activity_tensor = session_trial_tensor_dict[\"activity_tensor\"]\n\n print(\"Mouse\", mouse_index, \"Session\", session, \"LEarning State\", learning_index, \"Tensor Name\", tensor_name, \"Activity Tensor\", np.shape(activity_tensor))\n\n # Add Data To Dataset\n for trial in activity_tensor:\n activity_dataset.append([trial])\n metadata_dataset.append([np.array([mouse_index, session_index, learning_index])])\n\n # Flush File\n analysis_dataset_file.flush()\n\n # Increment Counters\n session_index += 1\n learning_index += 1\n mouse_index += 1\n analysis_dataset_file.close()\n\n \"\"\"\n # Reshape Into Timepoint Wide Dataframe\n trialwise_file = tables.open_file(filename=os.path.join(tensor_directory, analysis_name + \"_Trialwise_.h5\"), mode=\"r\")\n trialwise_activity_dataset = trialwise_file.root['Data']\n trialwise_metadata_dataset = trialwise_file.root['Trial_Details']\n number_of_trials, number_of_timepoints, number_of_pixels = np.shape(trialwise_activity_dataset)\n\n with h5py.File(os.path.join(tensor_directory, analysis_name + \".hdf5\"), \"w\") as f:\n activity_dataset = f.create_dataset(\"Data\", (number_of_timepoints, number_of_trials, number_of_pixels), dtype=np.float32, chunks=True, compression=\"gzip\")\n metadata_dataset = f.create_dataset(\"metadata\", (number_of_trials, 4), dtype=np.uint16, chunks=True, compression=\"gzip\")\n\n for trial_index in tqdm(range(number_of_trials)):\n trial_data = trialwise_activity_dataset[trial_index]\n trial_metadata = trialwise_metadata_dataset[trial_index]\n\n # Write To Dataset\n activity_dataset[:, trial_index] = trial_data\n metadata_dataset[trial_index] = trial_metadata\n \"\"\"\n\n\n","sub_path":"Trial_Aligned_Analysis/Raw_Analysis_Pipeline/Create_Analysis_Dataset_Learning.py","file_name":"Create_Analysis_Dataset_Learning.py","file_ext":"py","file_size_in_byte":4131,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"452127643","text":"import math\nimport bpy\nimport mathutils\n\nclass TetrahedronMakerPanel(bpy.types.Panel):\n bl_space_type = \"VIEW_3D\"\n bl_region_type = \"TOOLS\"\n bl_context = \"objectmode\"\n bl_category = \"Create\"\n bl_label = \"Add Tetrahedron\"\n\n def draw(self, context):\n TheCol = self.layout.column(align=True)\n TheCol.prop(context.scene, \"make_tetrahedron_inverted\")\n TheCol.operator(\"mesh.make_tetrahedron\", text=\"Add Tetrahedron\")\n # end draw\n\n# end TetrahedronMakerPanel\n\nclass MakeTetrahedron(bpy.types.Operator):\n bl_idname = \"mesh.make_tetrahedron\"\n bl_label = \"Add Tetrahedron\"\n # add undo function\n bl_options = {\"UNDO\"} \n\n def invoke(self, context, event):\n Scale = -1 if context.scene.make_tetrahedron_inverted else 1\n Vertices = \\\n [\n mathutils.Vector((0, -1 / math.sqrt(3),0)),\n mathutils.Vector((0.5, 1 / (2 * math.sqrt(3)), 0)),\n mathutils.Vector((-0.5, 1 / (2 * math.sqrt(3)), 0)),\n mathutils.Vector((0, 0, math.sqrt(2 / 3))),\n ]\n NewMesh = bpy.data.meshes.new(\"Tetrahedron\")\n NewMesh.from_pydata \\\n (\n Vertices,\n [],\n [[0, 1, 2], [0, 1, 3], [1, 2, 3], [2, 0, 3]]\n )\n NewMesh.update()\n NewObj = bpy.data.objects.new(\"Tetrahedron\", NewMesh)\n context.scene.objects.link(NewObj)\n return {\"FINISHED\"}\n # end invoke\n\n# end MakeTetrahedron\n\ndef register() :\n \n # add operator to Blender's collection\n bpy.utils.register_class(MakeTetrahedron)\n \n # add call for custom panel \n bpy.utils.register_class(TetrahedronMakerPanel)\n \n bpy.types.Scene.make_tetrahedron_inverted = bpy.props.BoolProperty \\\n (\n name = \"Upside Down\",\n description = \"Generate the tetrahedron upside down\",\n default = False\n )\n \n# end register\n\ndef unregister() :\n bpy.utils.unregister_class(MakeTetrahedron)\n bpy.utils.unregister_class(TetrahedronMakerPanel)\n del bpy.types.Scene.make_tetrahedron_inverted\n# end unregister\n\nif __name__ == \"__main__\" :\n register()\n# end if\n","sub_path":"MakeTetrahedron.py","file_name":"MakeTetrahedron.py","file_ext":"py","file_size_in_byte":2133,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"237020959","text":"# coding=utf-8\n\"\"\"\nAuthor : g faia\nEmail : gutianfeigtf@163.com\ntime : 2016.9.12\n\nfile : ga_tsp.py\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\nUsing Genetic Algorithm to solve the TSP.\nComputer simulation.\n\"\"\"\nfrom random import randint, random\n\n\nclass TspGaOptimizer(object):\n\n def __init__(self, fixed_pop, crossover_rate,\n mutation_rate, city_list, tsp_weight, max_iter):\n\n self.fixed_pop = fixed_pop\n self.crossover_rate = crossover_rate\n self.mutation_rate = mutation_rate\n self.max_iter = max_iter\n\n if len(city_list) != len(tsp_weight):\n raise Exception(\"Invalid input.\")\n\n self.city_list = city_list\n self.tsp_weight = tsp_weight\n self.city_num = len(city_list)\n\n def duplicate_city_list(self):\n \"\"\"\n Convert the OrderedDict object to list.\n :return: list such as [[], [], ...]\n \"\"\"\n city_list = []\n temp_list = list(self.city_list.items())\n\n for tup in temp_list:\n city_list.append(list(tup))\n\n return city_list\n\n def generate_code(self):\n \"\"\"\n Generate a path code, one code is equivalent to a city path.\n :return: a number list.\n \"\"\"\n city_list = self.duplicate_city_list()\n length = self.city_num\n _code = []\n\n # Select from city list randomly.\n for i in range(length):\n cur_len = len(city_list)\n select_index = randint(0, cur_len - 1)\n _code.append(city_list[select_index][1])\n\n # Update the temp city list.\n for j in range(select_index + 1, cur_len):\n city_list[j][1] -= 1\n del city_list[select_index]\n\n return _code\n\n def generate_code_list(self):\n \"\"\"Generate the list contains codes.\"\"\"\n code_list = []\n fixed_pop = self.fixed_pop\n\n for i in range(fixed_pop):\n code_list.append(self.generate_code())\n\n return code_list\n\n def decode_to_path(self, code):\n \"\"\"\n Decode the number code to path.\n :param code: the code of path.\n :return: string path.\n \"\"\"\n city_list = self.duplicate_city_list()\n _path = []\n\n for c in code:\n _path.append(city_list[c - 1][0])\n del city_list[c - 1]\n\n return _path\n\n def generate_path_list(self):\n \"\"\"Decode the code, and generate the path list.\"\"\"\n path_list = []\n code_list = self.code_list\n\n for code in code_list:\n path_list.append(self.decode_to_path(code))\n\n return path_list\n\n def select_operator(self):\n \"\"\"Selection operator, utilize the fitness value to select.\"\"\"\n def sum_list(lis):\n value = 0\n for ind in range(len(lis)):\n value += lis[ind]\n return value\n\n def cum_list(lis):\n cum_lis = []\n for ind in range(len(lis)):\n cum_lis.append(sum_list(lis[:(ind + 1)]))\n return cum_lis\n\n eval_list = []\n path_list = self.path_list\n code_list = self.code_list\n\n for string in path_list:\n eval_list.append(self.evaluate_path(string))\n\n sum_value = sum_list(eval_list)\n cum_eval_list = cum_list(eval_list)\n\n for i in range(len(cum_eval_list)):\n cum_eval_list[i] = cum_eval_list[i] / sum_value\n\n selected_list = []\n for i in range(len(cum_eval_list)):\n rand_num = random()\n for j in range(len(cum_eval_list)):\n if rand_num < cum_eval_list[j]:\n selected_list.append(code_list[j])\n break\n else:\n pass\n\n self.code_list = selected_list\n\n def crossover_operator(self):\n \"\"\"\n Crossover operator, cross two code.\n In this implement, I choose the half cross in default.\n The crossover probability of crossover operation.\n \"\"\"\n\n def crossover(a, b):\n \"\"\"Crossover operator between two codes.\"\"\"\n if len(a) == len(b):\n # Generate the random crossover location.\n l = randint(1, len(a) - 1)\n a_front = a[:l]\n a_end = a[l:]\n b_front = b[:l]\n b_end = b[l:]\n a = a_front + b_end\n b = b_front + a_end\n return a, b\n\n code_len = len(self.code_list)\n crossover_rate = self.crossover_rate\n code_list = self.code_list\n\n if code_len % 2 == 0:\n pass\n else:\n code_len -= 1\n for i in range(int(code_len / 2)):\n crossover_rand = random()\n if crossover_rand < crossover_rate:\n code_list[2 * i], code_list[2 * i + 1] \\\n = crossover(code_list[2 * i], code_list[2 * i + 1])\n\n def mutation_operator(self):\n \"\"\"\n Mutation operator, randomly change a char in string.\n If random number is smaller than mutation rate, Code\n Will generate mutation.\n \"\"\"\n code_len = self.city_num\n code_list = self.code_list\n mutation_rate = self.mutation_rate\n\n for code in code_list:\n mutation_rand = random()\n if mutation_rand <= mutation_rate:\n selected_ind = randint(0, code_len - 1)\n selected_list = list(range(1, code_len - selected_ind + 1))\n for i in range(len(selected_list)):\n if selected_list[i] == code[selected_ind]:\n del selected_list[i]\n break\n if selected_list:\n selected_len = len(selected_list)\n selected_chr = randint(0, selected_len - 1)\n code[selected_ind] = selected_list[selected_chr]\n\n def evaluate_path(self, string):\n \"\"\"\n Evaluate the eval of path.\n :param string: path string.\n :return: the evaluated value of string.\n \"\"\"\n seq_list = []\n city_list = self.city_list\n\n for c in string:\n seq_list.append(city_list[c] - 1)\n\n length = len(seq_list)\n weight = self.tsp_weight\n value = 0\n\n for i in range(length):\n front = seq_list[i]\n end = seq_list[(i + 1) % length]\n value += weight[front][end]\n\n return 1 / value\n\n def show_best_list(self):\n \"\"\"\n Show the objects which has best fitness value.\n :return: a list contains best objects which has well fitness.\n \"\"\"\n eval_list = []\n path_list = self.path_list\n\n for string in path_list:\n eval_list.append(self.evaluate_path(string))\n\n best_fitness = 0\n eval_list_len = len(eval_list)\n best_list = []\n\n for eva in eval_list:\n if eva >= best_fitness:\n best_fitness = eva\n\n for i in range(eval_list_len):\n if eval_list[i] == best_fitness:\n best_list.append(path_list[i])\n\n return best_list, 1 / best_fitness\n\n def update_path_list(self):\n \"\"\"Update the path list.\"\"\"\n new_list = []\n\n for code in self.code_list:\n new_list.append(self.decode_to_path(code))\n\n self.path_list = new_list\n\n def optimize(self):\n \"\"\"\"\"\"\n # Initialize the initial population.\n self.code_list = self.generate_code_list()\n self.path_list = self.generate_path_list()\n\n for i in range(self.max_iter):\n\n self.select_operator()\n self.crossover_operator()\n self.mutation_operator()\n self.update_path_list()\n\n return self\n","sub_path":"intelligence_algorithm/ga_tsp.py","file_name":"ga_tsp.py","file_ext":"py","file_size_in_byte":7786,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"588495221","text":"# Create your views here.\n#coding: utf8\nfrom information.models import news\nfrom utils.util import DateUtil\nfrom utils.util import InfoUtil\nfrom django.shortcuts import render_to_response\n\n\ndef show_infomations(request, typ=None):\n page = request.GET.get('page', '1')\n if typ == 'news' or not typ:\n tomorrow = DateUtil.getTomorrow()\n if len(infs) == 0:\n InfoUtil.loadNewsInfo(tomorrow)\n infs = news.objects.filter(date=tomorrow)[int(page): int(page) + 10]\n pages = len(infs) / 10\n\n fanhui = u'明日信息 '\n for i in infs:\n a_tag = '%s ' % (i.srcurl, i.title)\n fanhui = fanhui + a_tag + ' ' + i.describe + ' '\n return render_to_response('index.html', {'iterms': infs, 'pages': pages, 'page': page})\n","sub_path":"tomorrow/information/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":814,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"590958831","text":"from toga.widgets.base import Widget\n\nclass Label(Widget):\n\n type_element = 'DIV'\n can_have_children = False\n\n #__pragma__('kwargs')\n\n def __init__(self, text, id=None, style=None, factory=None):\n super().__init__(self, id=id, style=style, enabled=True, factory=factory)\n self.text = text\n\n #__pragma__('nokwargs')\n\n @property\n def text(self):\n return self.elm.innerHTML\n\n @text.setter\n def set_text(self, text):\n if value:\n self.elm.innerHTML = text\n else:\n self.elm.innerHTML = ''\n","sub_path":"toga/widgets/label.py","file_name":"label.py","file_ext":"py","file_size_in_byte":567,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"381910055","text":"# Definition for a binary tree node.\nclass TreeNode:\n def __init__(self, x):\n self.val = x\n self.left = None\n self.right = None\n\nclass Solution:\n def minDepth(self, root):\n \"\"\"\n :type root: TreeNode\n :rtype: int\n \"\"\"\n if not root:\n return 0\n\n if root.left and root.right:\n return 1 + min(self.minDepth(root.left), self.minDepth(root.right))\n elif not root.right:\n return 1 + self.minDepth(root.left)\n else:\n return 1 + self.minDepth(root.right)\n\n\nroot = TreeNode(5)\nroot.left = TreeNode(4)\nroot.right = TreeNode(8)\n\nroot.left.left = TreeNode(11)\nroot.left.left.left = TreeNode(7)\nroot.left.left.right = TreeNode(2)\n\nroot.right.left = TreeNode(13)\nroot.right.right = TreeNode(4)\nroot.right.right.right = TreeNode(1)\n\nsingle = TreeNode(0)\n\none_two = TreeNode(1)\none_two.left = TreeNode(2)\n\ns = Solution()\nprint(s.minDepth(root))\nprint(s.minDepth(single))\nprint(s.minDepth(None))\nprint(s.minDepth(one_two))\n","sub_path":"python/min-depth-of-binary-tree.py","file_name":"min-depth-of-binary-tree.py","file_ext":"py","file_size_in_byte":1031,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"112311376","text":"import numpy as np\nimport os\nimport shutil\nimport json\nimport argparse\n\nfrom utils.data_helpers import *\n\nparser = argparse.ArgumentParser(\"Create 200 class ImageNet\")\nparser.add_argument('-d', '--destination', default='/data/sarah/200class-imagenet-256', type=str,\n help='Destination file to store new dataset')\nparser.add_argument('-s', '--source', default='/data/sarah/imagenet-256', type=str,\n help='Source file of full imagenet dataset')\nargs = parser.parse_args()\n\ndef main():\n print(\"-----Make Dataset-----\")\n if not os.path.exists(args.destination):\n print(\"Creating destination folder for new dataset\")\n os.makedirs(args.destination)\n create_200_class_imagenet(args.source, args.destination)\n print(\"Complete\")\n\nif __name__ == '__main__':\n main()\n","sub_path":"buildDataset.py","file_name":"buildDataset.py","file_ext":"py","file_size_in_byte":807,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"431423497","text":"import numpy as np\nimport scipy\nimport cv2\nfrom sklearn.neighbors import KNeighborsRegressor\nimport scipy.interpolate\nfrom scipy import sparse\nfrom scipy.sparse.linalg import spsolve\nfrom tqdm import tqdm\n\n\ndef geo_interp(lidar_image, theta_spatial=0.5, grid=5, epochs=4):\n assert (grid > 1)\n lidar_image = np.pad(lidar_image, ((grid, grid), (grid, grid)), 'edge')\n geo_dis_map = np.full((lidar_image.shape[0], lidar_image.shape[1], 2), fill_value=-1, dtype=np.float)\n geo_dis_map[:, :, 1] = lidar_image[:, :]\n\n for i in range(0, lidar_image.shape[0]):\n for j in range(0, lidar_image.shape[1]):\n if lidar_image[i][j] > 0:\n geo_dis_map[i][j][0] = 0.\n\n bias = [(-1, -1), (-1, 0), (-1, 1), (0, -1), (0, 1), (1, -1), (1, 0), (1, 1)]\n for epoch in range(epochs):\n # forward\n for i in range(1, lidar_image.shape[0] - 1):\n for j in range(1, lidar_image.shape[1] - 1):\n if lidar_image[i][j] > 0:\n continue\n min_geo_dis = 1000000.\n loc_val = -1.\n for (x, y) in bias[:4]:\n if geo_dis_map[i + x][j + y][0] != -1.:\n spatial_dis = np.sqrt(x ** 2 + y ** 2)\n geo_dis = theta_spatial * spatial_dis + geo_dis_map[i + x][j + y][0]\n if geo_dis < min_geo_dis:\n loc_val = geo_dis\n geo_dis_map[i][j][1] = geo_dis_map[i + x][j + y][1]\n geo_dis_map[i][j][0] = loc_val\n # backward\n for i in range(lidar_image.shape[0] - 2, 0, -1):\n for j in range(lidar_image.shape[0] - 2, 0, -1):\n if lidar_image[i][j] > 0:\n continue\n min_geo_dis = 1000000.\n loc_val = -1.\n for (x, y) in bias[4:8]:\n if geo_dis_map[i + x][j + y][0] != -1.:\n spatial_dis = np.sqrt(x ** 2 + y ** 2)\n geo_dis = theta_spatial * spatial_dis + geo_dis_map[i + x][j + y][0]\n if geo_dis < min_geo_dis:\n loc_val = geo_dis\n geo_dis_map[i][j][1] = geo_dis_map[i + x][j + y][1]\n geo_dis_map[i][j][0] = loc_val\n\n return geo_dis_map[grid:lidar_image.shape[0] - grid, grid:lidar_image.shape[1] - grid, 1]\n\n\ndef spatial_without_color_interp(lidar_image, grid=7, sigma_spatial=2.0):\n lidar_smooth_result = np.zeros((lidar_image.shape[0], lidar_image.shape[1]), dtype=np.uint8)\n geo_map = geo_interp(lidar_image)\n lidar_image = np.pad(lidar_image, ((grid, grid), (grid, grid)), 'edge')\n geo_map = np.pad(geo_map, ((grid, grid), (grid, grid)), 'edge')\n for i in range(grid, lidar_image.shape[0] - grid):\n for j in range(grid, lidar_image.shape[1] - grid):\n depth_slice = lidar_image[i - grid:i + grid, j - grid:j + grid]\n geo_slice = geo_map[i - grid:i + grid, j - grid:j + grid]\n if np.abs(geo_slice.max() - geo_slice.min()) < 1e-4:\n sigma_depth = 1\n else:\n sigma_depth = - np.log(geo_slice.max() - geo_slice.min())\n dep_weight = np.exp(-(depth_slice - geo_map[i][j]) ** 2 / (2 * sigma_depth ** 2))\n spa_weight = np.zeros_like(dep_weight)\n for k in range(-int(grid), int(grid + 1)):\n for l in range(-int(grid), int(grid + 1)):\n spa_weight[k][l] = np.exp(-(k ** 2 + l ** 2) / (2 * sigma_spatial ** 2))\n lidar_smooth_result[i - grid, j - grid] = np.sum(depth_slice * dep_weight * spa_weight)\n return lidar_smooth_result\n\n\ndef interpolator2d(lidar_image, kind='linear'):\n m, n = lidar_image.shape\n points = list()\n for i in range(0, lidar_image.shape[0]):\n for j in range(0, lidar_image.shape[1]):\n if lidar_image[i][j] > 0:\n points.extend([[i, j, lidar_image[i][j]]])\n if len(points) < 4:\n return np.zeros((lidar_image.shape[0], lidar_image.shape[1]), dtype=np.uint8)\n points = np.asarray(points)\n ij, d = points[:, :-1], points[:, 2]\n if kind == 'linear':\n f = scipy.interpolate.LinearNDInterpolator(ij, d, fill_value=0)\n elif kind == 'nearest':\n f = scipy.interpolate.NearestNDInterpolator(ij, d)\n elif kind == 'clough':\n f = scipy.interpolate.CloughTocher2DInterpolator(ij, d, fill_value=0)\n J, I = np.meshgrid(np.arange(n), np.arange(m))\n IJ = np.vstack([I.flatten(), J.flatten()]).T\n disparity = f(IJ).reshape(lidar_image.shape)\n return disparity\n\n\ndef barycentric(p, a, b, c):\n v0 = b - a\n v1 = c - a\n v2 = p - a\n d00 = v0.dot(v0)\n d01 = v0.dot(v1)\n d11 = v1.dot(v1)\n d20 = v2.dot(v0)\n d21 = v2.dot(v1)\n denom = d00 * d11 - d01 * d01\n v = (d11 * d20 - d01 * d21) / denom\n w = (d00 * d21 - d01 * d20) / denom\n u = 1.0 - v - w\n return u, v, w\n\n\ndef barycentric_interp(lidar_image):\n rect = (0, 0, lidar_image.shape[1], lidar_image.shape[0])\n lidar_smooth_result = np.zeros((lidar_image.shape[0], lidar_image.shape[1]), dtype=np.uint8)\n subdiv = cv2.Subdiv2D(rect)\n for i in range(0, lidar_image.shape[0]):\n index = i * lidar_image.shape[1]\n for j in range(0, lidar_image.shape[1]):\n if lidar_image[i][j] > 0:\n subdiv.insert([(j, i)])\n index += 1\n for i in range(0, lidar_image.shape[0]):\n for j in range(0, lidar_image.shape[1]):\n if lidar_image[i][j] > 0:\n lidar_smooth_result[i][j] = lidar_image[i][j]\n else:\n loc, edge, vertex = subdiv.locate((j, i))\n neighbor_point = []\n for k in range(0, 3):\n neighbor_point.extend([np.array(subdiv.getVertex(subdiv.edgeOrg(edge)[0])[0], dtype=np.int)])\n edge = subdiv.getEdge(edge, cv2.Subdiv2D_NEXT_AROUND_LEFT)\n\n valid_points = np.full(3, fill_value=False, dtype=np.bool)\n\n for k in range(0, 3):\n if 0 <= neighbor_point[k][0] < lidar_image.shape[1] and 0 <= neighbor_point[k][1] < \\\n lidar_image.shape[0]:\n valid_points[k] = True\n\n if np.all(valid_points):\n u, v, w = barycentric(np.array([j, i]), neighbor_point[0], neighbor_point[1], neighbor_point[2])\n lidar_smooth_result[i][j] = lidar_image[neighbor_point[0][1]][neighbor_point[0][0]] * u + \\\n lidar_image[neighbor_point[1][1]][neighbor_point[1][0]] * v + \\\n lidar_image[neighbor_point[2][1]][neighbor_point[2][0]] * w\n return lidar_smooth_result\n\n\ndef knn_interp(lidar_image, k=1, p=2.):\n points = list()\n values = list()\n lidar_smooth_result = np.zeros((lidar_image.shape[0], lidar_image.shape[1]), dtype=np.uint8)\n knr = KNeighborsRegressor(n_neighbors=k, p=p)\n for i in range(0, lidar_image.shape[0]):\n for j in range(0, lidar_image.shape[1]):\n if lidar_image[i][j] > 0:\n points.extend([[i, j]])\n values.extend([lidar_image[i][j]])\n\n knr.fit(points, values)\n for i in range(0, lidar_image.shape[0]):\n for j in range(0, lidar_image.shape[1]):\n if lidar_image[i][j] > 0:\n lidar_smooth_result[i][j] = lidar_image[i][j]\n else:\n lidar_smooth_result[i][j] = knr.predict([[i, j]])[0]\n\n return lidar_smooth_result\n\n\ndef grid_weight_interp(lidar_image, grid=7):\n lidar_smooth_result = np.zeros((lidar_image.shape[0], lidar_image.shape[1]), dtype=np.uint8)\n lidar_image = np.pad(lidar_image, ((grid, grid), (grid, grid)), 'edge')\n for i in range(grid, lidar_image.shape[0] - grid):\n for j in range(grid, lidar_image.shape[1] - grid):\n X = 0\n Y = 0\n for k in range(-int(grid), int(grid + 1)):\n for l in range(-int(grid), int(grid + 1)):\n if k == l == 0:\n continue\n s = 1. / np.sqrt(k ** 2 + l ** 2)\n X += s\n Y += lidar_image[i + k][j + l] * s\n lidar_smooth_result[i - grid, j - grid] = Y / X\n return lidar_smooth_result\n\n\ndef lattice(m, n, connect):\n if m * n == 1:\n return [(0, 0)], []\n N = m * n\n\n assert (connect < 2)\n\n if connect < 2:\n x = range(m)\n y = range(n)\n X, Y = np.meshgrid(x, y)\n points = np.array(list(zip(X.flatten(), Y.flatten())))\n edges = [(i, i + 1) for i in range(1, N + 1)]\n edges.extend([(i, i + m) for i in range(1, N + 1)])\n if connect == 1:\n border = np.linspace(1, N + 1, N)\n border1 = np.where((border % m - 1) > 0)\n border2 = np.where((border % m) > 0)\n border3 = border1 + m - 1\n border4 = border2 + m + 1\n edges.extend(list(zip(border1, border3)))\n edges.extend(list(zip(border2, border4)))\n edges = np.asarray(edges)\n val_ind = np.bitwise_or(np.bitwise_or(np.bitwise_or(edges[:, 0] > N, edges[:, 0] < 1), edges[:, 1] > N),\n edges[:, 1] < 1)\n for i in range(m, N, m):\n val_ind[i] = True\n val_ind = np.repeat(val_ind.reshape(-1, 1), 2, axis=1)\n marr = np.ma.MaskedArray(edges, mask=val_ind)\n edges = np.ma.compress_rows(marr)\n\n return points, edges\n\n\ndef make_weight_l2(edges, vals, val_scale, points=None, geo_scale=0, epsilon=1e-5):\n if val_scale > 0:\n val_dis = np.asarray([np.sum((vals[edges[i, 0] - 1] - vals[edges[i, 1] - 1]) ** 2) for i in range(len(edges))])\n if val_dis.max() != val_dis.min():\n val_dis = (val_dis - val_dis.min()) / (val_dis.max() - val_dis.min())\n else:\n val_scale = 0\n val_dis = np.zeros((edges.shape[0]))\n\n if geo_scale != 0:\n geo_dis = np.asarray(\n [np.sum((points[edges[i, 0] - 1] - points[edges[i, 1] - 1]) ** 2) for i in range(len(edges))])\n if geo_dis.max() != geo_dis.min():\n geo_dis = (geo_dis - geo_dis.min()) / (geo_dis.max() - geo_dis.min())\n else:\n geo_scale = 0\n geo_dis = np.zeros((edges.shape[0]))\n\n weights = np.exp(-np.add(geo_scale * geo_dis, val_scale * val_dis)) + epsilon\n return weights\n\n\ndef adjacency(edges, weights, N):\n return sparse.coo_matrix((np.append(weights, weights),\n (np.append(edges[:, 0] - 1, edges[:, 1] - 1),\n np.append(edges[:, 1] - 1, edges[:, 0] - 1))),\n shape=(N, N))\n\n\ndef sd_filter(img, lidar_image, connect=0, lamda=10, mu=500, nu=200, step=2, is_sparse=True):\n img = img / 255.\n lidar_image = lidar_image / 255.\n u0 = np.ones_like(lidar_image)\n _, edges = lattice(lidar_image.shape[0], lidar_image.shape[1], connect)\n\n N = lidar_image.shape[0] * lidar_image.shape[1]\n\n f_vals = lidar_image.transpose(1, 0).reshape(N)\n if is_sparse:\n A = np.zeros_like(f_vals)\n A[f_vals > 0] = 1\n C = sparse.coo_matrix((A, (range(0, N), range(0, N))))\n F = C @ f_vals.astype(np.float)\n else:\n C = sparse.coo_matrix((np.ones(N), (range(0, N), range(0, N))))\n F = C @ f_vals.astype(np.float)\n\n if len(img.shape) > 2 and img.shape[2] > 1:\n img = cv2.cvtColor(img, cv2.COLOR_RGB2LAB)\n\n g_vals = img.transpose(1, 0).reshape(N)\n weights_g = make_weight_l2(edges, g_vals, mu)\n g_w = adjacency(edges, weights_g, N)\n for i in tqdm(range(step), desc='sdfilter step'):\n u_vals = u0.transpose(1, 0).reshape(N)\n weights_u = make_weight_l2(edges, u_vals, nu)\n u_w = adjacency(edges, weights_u, N)\n W = g_w.multiply(u_w)\n D = sparse.coo_matrix((W.sum(axis=0).A1, (range(0, N), range(0, N))))\n L = D - W\n R = C + lamda * L\n U = spsolve(R, F)\n u = U.reshape((lidar_image.shape[1], lidar_image.shape[0])).transpose((1, 0))\n u0 = u\n return u * 255.\n\n\ndef atgv(reconstructed_lidar_image, lidar_image, gray,\n kernel=np.multiply(cv2.getGaussianKernel(5, 1), (cv2.getGaussianKernel(5, 1)).T),\n weight_scale=40., alpha1=20., alpha2=0.2,\n beta=10., gamma=0.85, l=1., step=200, min_val=1e-8, tau=1., eta_p=4., eta_q=2.):\n # self defined anisotropic diffusion\n def dx(u):\n return np.append(u[:, 1:], u[:, 0].reshape((u.shape[0], 1)), axis=1) - u\n\n def dxz(u):\n return np.append(u[:, :-1], np.zeros_like(u[:, -1].reshape((u.shape[0], 1))), axis=1) - \\\n np.append(np.zeros_like(u[:, -1].reshape((u.shape[0], 1))), u[:, :-1], axis=1)\n\n def dy(u):\n return np.append(u[1:, :], u[0, :].reshape((1, u.shape[1])), axis=0) - u\n\n def dyz(u):\n return np.append(u[:-1, :], np.zeros_like(u[-1, :].reshape((1, u.shape[1]))), axis=0) - \\\n np.append(np.zeros_like(u[-1, :].reshape((1, u.shape[1]))), u[:-1, :], axis=0)\n\n M, N = lidar_image.shape[0], lidar_image.shape[1]\n sigma = 1. / tau\n weight = np.zeros((lidar_image.shape[0], lidar_image.shape[1]))\n weight[lidar_image > 0] = weight_scale\n gray = gray / 255.\n grad_x = cv2.filter2D(gray, -1, kernel)\n grad_y = cv2.filter2D(gray, -1, kernel.transpose((1, 0)))\n abs_img = np.sqrt(grad_x ** 2 + grad_y ** 2)\n n = np.asarray(list(zip(grad_x.flatten(), grad_y.flatten())))\n norm_n = np.sqrt(np.sum(n, axis=1))\n norm_n = np.asarray(list(zip(norm_n.flatten(), norm_n.flatten())))\n norm_n[norm_n[:, 0] < min_val] = 1\n norm_n[norm_n[:, 1] < min_val] = 0\n norm_n_T = np.asarray(list(zip(norm_n[:, 1], -norm_n[:, 0])))\n W = np.exp(-beta * abs_img ** gamma)\n W[W < min_val] = min_val\n W = W.flatten()\n grad_i = W * norm_n[:, 0] ** 2 + norm_n_T[:, 0] ** 2\n grad_j = W * norm_n[:, 0] * norm_n[:, 1] + norm_n_T[:, 0] * norm_n_T[:, 1]\n grad_k = W * norm_n[:, 1] ** 2 + norm_n_T[:, 1] ** 2\n grad_i = grad_i.reshape((M, N))\n grad_j = grad_j.reshape((M, N))\n grad_k = grad_k.reshape((M, N))\n\n eta_u = (grad_i ** 2 + grad_j ** 2 + 2 * grad_k ** 2 +\n (grad_i + grad_k) ** 2 + (grad_j + grad_k) ** 2) * (alpha1 ** 2)\n eta_v = np.zeros((lidar_image.shape[0], lidar_image.shape[1], 2))\n eta_v[:, :, 0] = (alpha2 ** 2) * (grad_j ** 2 + grad_k ** 2) + 4 * alpha1 ** 2\n eta_v[:, :, 1] = (alpha2 ** 2) * (grad_i ** 2 + grad_k ** 2) + 4 * alpha1 ** 2\n p = np.zeros((M, N, 2))\n q = np.zeros((M, N, 4))\n u = reconstructed_lidar_image / 255.\n u_ = u\n v = np.zeros((M, N, 2))\n v_ = v\n\n grad_v = np.zeros((M, N, 4))\n dw = lidar_image / 255. * weight\n\n for i in tqdm(range(step), desc='tgv step'):\n if sigma < 1000:\n mu = 1 / np.sqrt(1 + 0.7 * tau * l)\n else:\n mu = 1\n u_x = dx(u_) - v_[:, :, 0]\n u_y = dy(u_) - v_[:, :, 1]\n\n du_tensor_x = grad_i * u_x + grad_k * u_y\n du_tensor_y = grad_k * u_x + grad_j * u_y\n\n p[:, :, 0] = p[:, :, 0] + alpha2 * sigma / eta_p * du_tensor_x\n p[:, :, 1] = p[:, :, 1] + alpha2 * sigma / eta_p * du_tensor_y\n\n reprojection = np.sqrt(p[:, :, 0] ** 2 + p[:, :, 1] ** 2)\n reprojection[reprojection < 10] = 10\n p[:, :, 0] = p[:, :, 0] / reprojection\n p[:, :, 1] = p[:, :, 1] / reprojection\n\n grad_v[:, :, 0] = dx(v_[:, :, 0])\n grad_v[:, :, 1] = dy(v_[:, :, 1])\n grad_v[:, :, 2] = dy(v_[:, :, 0])\n grad_v[:, :, 3] = dx(v_[:, :, 1])\n\n q = q + alpha1 * sigma / eta_q * grad_v\n\n reproject = np.sqrt(q[:, :, 0] ** 2 + q[:, :, 1] ** 2 + q[:, :, 2] ** 2 + q[:, :, 3] ** 2)\n reproject[reproject < 10] = 10\n q[:, :, 0] = q[:, :, 0] / reproject\n q[:, :, 1] = q[:, :, 1] / reproject\n q[:, :, 2] = q[:, :, 2] / reproject\n q[:, :, 3] = q[:, :, 3] / reproject\n\n u_ = u\n v_ = v\n\n div_p = dxz(grad_i * p[:, :, 0] + grad_k * p[:, :, 1]) + dyz(grad_k * p[:, :, 0] + grad_j * p[:, :, 1])\n\n tau_eta_u = tau / eta_u\n u = (u_ + tau_eta_u * (alpha2 * div_p + dw)) / (1 + tau_eta_u * weight)\n qw_x = np.append(np.zeros_like(q[:, -1, 0].reshape((q.shape[0], 1))),\n q[:, :-1, 0].reshape((q.shape[0], q.shape[1] - 1)), axis=1)\n qw_w = np.append(np.zeros_like(q[:, -1, 3].reshape((q.shape[0], 1))),\n q[:, :-1, 3].reshape((q.shape[0], q.shape[1] - 1)), axis=1)\n qn_y = np.append(np.zeros_like(q[-1, :, 1].reshape((1, q.shape[1]))),\n q[:-1, :, 1].reshape((q.shape[0] - 1, q.shape[1])), axis=0)\n qn_z = np.append(np.zeros_like(q[-1, :, 2].reshape((1, q.shape[1]))),\n q[:-1, :, 2].reshape((q.shape[0] - 1, q.shape[1])), axis=0)\n\n div_q1 = (np.append(q[:, :-1, 0].reshape((q.shape[0], q.shape[1] - 1)),\n np.zeros_like(q[:, -1, 0].reshape((q.shape[0], 1))), axis=1) - qw_x) + (\n np.append(q[:-1, :, 2].reshape((q.shape[0] - 1, q.shape[1])),\n np.zeros_like(q[-1, :, 2].reshape((1, q.shape[1]))), axis=0) - qn_z)\n div_q2 = (np.append(q[:, :-1, 3].reshape((q.shape[0], q.shape[1] - 1)),\n np.zeros_like(q[:, -1, 3].reshape((q.shape[0], 1))), axis=1) - qw_w) + (\n np.append(q[:-1, :, 1].reshape((q.shape[0] - 1, q.shape[1])),\n np.zeros_like(q[-1, :, 1].reshape((1, q.shape[1]))), axis=0) - qn_y)\n\n dq1 = grad_i * p[:, :, 0] + grad_k * p[:, :, 1]\n dq2 = grad_k * p[:, :, 0] + grad_j * p[:, :, 1]\n\n div_q = np.stack((div_q1, div_q2), axis=2)\n dq = np.stack((dq1, dq2), axis=2)\n v = v_ + tau / eta_v * (alpha2 * dq + alpha1 * div_q)\n u_ = u + mu * (u - u_)\n v_ = v + mu * (v - v_)\n\n sigma = sigma / mu\n tau = tau * mu\n\n return u * 255.\n\n\ndef g(x, K=5):\n return 1.0 / (1.0 + ((x * x) / (K * K)))\n\n\ndef c(I, K=5):\n cv = g(I[1:, :] - I[:-1, :], K)\n ch = g(I[:, 1:] - I[:, :-1], K)\n\n return cv, ch\n\n\ndef diffuse_step(cv, ch, I, l=0.24):\n dv = I[1:, :] - I[:-1, :]\n dh = I[:, 1:] - I[:, :-1]\n\n tv = l * cv * dv # vertical transmissions\n I[1:, :] -= tv\n I[:-1, :] += tv\n del (dv, tv)\n\n th = l * ch * dh # horizontal transmissions\n I[:, 1:] -= th\n I[:, :-1] += th\n del (dh, th)\n\n return I\n\n\ndef anisotropic_diffusion(I1, I2, I, N=5, l=0.24, K=5):\n I1 = I1 / 255.\n I2 = I2 / 255.\n I = I / 255.\n for i in tqdm(range(N)):\n cv1, ch1 = c(I1, K=K)\n I1 = diffuse_step(cv1, ch1, I1, l=l)\n\n cv2, ch2 = c(I2, K=K)\n I2 = diffuse_step(cv2, ch2, I2, l=l)\n cv = np.minimum(cv1, cv2)\n ch = np.minimum(ch1, ch2)\n del (cv1, ch1, cv2, ch2)\n I = diffuse_step(cv, ch, I, l=l)\n\n del (cv, ch)\n\n return I * 255.\n","sub_path":"lidar_interpolate_toolbox.py","file_name":"lidar_interpolate_toolbox.py","file_ext":"py","file_size_in_byte":19015,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"67500784","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\nimport yaml\n\nwith open('sources.yml') as f:\n sources = yaml.safe_load(f.read())\n\nconfig = {\n 'services': {\n 'demo': {},\n 'tms': {\n 'use_grid_names': True,\n 'origin': 'nw'\n }\n },\n 'layers': [],\n 'caches': {},\n 'sources': {},\n 'grids': {\n 'mercator': {\n 'base': 'GLOBAL_MERCATOR'\n }\n },\n 'globals': {}\n}\n\nfor source in sources:\n assert isinstance(source['name'], str)\n\n cache_name = source['name'] + '_cache'\n source_name = source['name'] + '_source'\n\n config['layers'].append({\n 'name': source['name'],\n 'title': source['title'],\n 'sources': [cache_name]\n })\n config['caches'][cache_name] = {\n 'grids': ['mercator'],\n 'sources': [source_name]\n }\n config['sources'][source_name] = {\n 'type': 'wms',\n 'wms_opts': {\n 'version': '1.3.0'\n },\n 'supported_srs': ['EPSG:25833'],\n 'req': {\n 'url': source['url'],\n 'layers': source['layer'],\n 'style': 'default',\n 'format': 'png',\n 'transparent': source['transparent']\n }\n }\n\nwith open('config.yml', 'w') as f:\n f.write(yaml.dump(config))\n","sub_path":"generate_config.py","file_name":"generate_config.py","file_ext":"py","file_size_in_byte":1288,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"132093975","text":"from django.shortcuts import render\nfrom ninja import Router\nfrom commerce.models import Product, Order, Item, Address, OrderStatus, ProductImage, City, Category, Merchant, Vendor, Label, User\n\ncommerce_controller=Router()\n\n\n\n@commerce_controller.get('/Product')\ndef display_products(request):\n\tProducts = list(Product.objects.values())\n\tMerchants = list(Merchant.objects.values())\n\tCategories = list(Category.objects.values())\n\tVendors = list(Vendor.objects.values())\n\tLabels = list(Label.objects.values())\n\n# return name of related data instead id\n\tfor i in range(len(Products)):\n\n\t\tfor j in range(len(Merchants)):\n\t\t\tif Products[i]['merchant_id'] == Merchants[j]['id']:\n\t\t\t\tProducts[i]['merchant_id']=Merchants[j]['name']\n\n\t\tfor j in range(len(Categories)):\n\t\t\tif Products[i]['category_id'] == Categories[j]['id']:\n\t\t\t\tProducts[i]['category_id']=Categories[j]['name']\n\n\t\tfor j in range(len(Vendors)):\n\t\t\tif Products[i]['vendor_id'] == Vendors[j]['id']:\n\t\t\t\tProducts[i]['vendor_id']=Vendors[j]['name']\n\n\t\tfor j in range(len(Labels)):\n\t\t\tif Products[i]['label_id'] == Labels[j]['id']:\n\t\t\t\tProducts[i]['label_id']=Labels[j]['name']\n\n\treturn Products\n\n\n@commerce_controller.get('/Address')\ndef display_address(request):\n\taddress = list(Address.objects.values())\n\tcities = list(City.objects.values())\n\n\tfor i in range(len(address)):\n\n\t\tfor j in range(len(cities)):\n\t\t\tif address[i]['city_id'] == cities[j]['id']:\n\t\t\t\taddress[i]['city_id']=cities[j]['name']\n\treturn address\n\n\n\n","sub_path":"commerce/controllers.py","file_name":"controllers.py","file_ext":"py","file_size_in_byte":1474,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"436025498","text":"import numpy as np \nfrom matplotlib import pyplot as plt\n\nfrom toy_auto_race.TD3 import TD3\nfrom toy_auto_race.Utils import LibFunctions as lib\n\n\nclass BaseGen:\n def __init__(self, agnet_name, sim_conf) -> None:\n self.name = agent_name\n\n def transform_obs(self, obs, pp_action):\n \"\"\"\n Transforms the observation received from the environment into a vector which can be used with a neural network.\n \n Args:\n obs: observation from env\n pp_action: [steer, speed] from pure pursuit controller\n\n Returns:\n nn_obs: observation vector for neural network\n \"\"\"\n cur_v = [obs[3]/self.max_v]\n cur_d = [obs[4]/self.max_steer]\n vr_scale = [(pp_action[1])/self.max_v]\n dr_scale = [pp_action[0]/self.max_steer]\n\n scan = obs[5:-1]\n\n nn_obs = np.concatenate([cur_v, cur_d, vr_scale, dr_scale, scan])\n\n return nn_obs\n\n\nclass BaseGenAgent:\n def __init__(self, config, name):\n self.config = config\n self.name = name\n self.env_map = None\n self.wpts = None\n\n self.path_name = 'Vehicles/%s' % self.name\n self.pind = 1\n self.target = None\n\n # history\n self.steer_history = []\n self.vel_history = []\n self.d_ref_history = []\n self.reward_history = []\n self.critic_history = []\n self.steps = 0\n\n self.max_v = config['lims']['max_v']\n self.max_d = config['lims']['max_steer']\n self.mu = config['car']['mu']\n self.m = config['car']['m']\n self.max_friction_force = 9.81 * self.m * self.mu \n\n # agent stuff \n self.state_action = None\n self.cur_nn_act = None\n self.prev_nn_act = 0\n\n n_beams = config['sim']['beams']\n self.scan_sim = ScanSimulator(n_beams, np.pi)\n self.n_beams = n_beams\n\n def init_agent(self, env_map):\n self.env_map = env_map\n \n self.scan_sim.set_check_fcn(self.env_map.check_scan_location)\n\n # self.wpts = self.env_map.get_min_curve_path()\n self.wpts = self.env_map.get_reference_path()\n\n self.prev_dist_target = lib.get_distance(self.env_map.start, self.env_map.end)\n\n return self.wpts\n\n def show_vehicle_history(self):\n plt.figure(1)\n plt.clf()\n plt.title(\"Steer History\")\n plt.ylim([-1.1, 1.1])\n # np.save('Vehicles/mod_hist', self.steer_history)\n plt.plot(self.steer_history)\n plt.plot(self.vel_history)\n plt.legend(['Steer', 'Velocity'])\n\n plt.pause(0.001)\n\n # plt.figure(3)\n # plt.clf()\n # plt.title('Rewards')\n # plt.ylim([-1.5, 4])\n # plt.plot(self.reward_history, 'x', markersize=12)\n # plt.plot(self.critic_history)\n\n def transform_obs(self, obs):\n cur_v = [obs[3]/self.max_v]\n cur_d = [obs[4]/self.max_d]\n\n th_target = lib.get_bearing(obs[0:2], self.env_map.end)\n alpha = lib.sub_angles_complex(th_target, obs[2])\n th_scale = [(alpha)*2/np.pi]\n\n scan = self.scan_sim.get_scan(obs[0], obs[1], obs[2])\n\n nn_obs = np.concatenate([cur_v, cur_d, th_scale, scan])\n\n return nn_obs\n\n def reset_lap(self):\n self.steer_history.clear()\n self.vel_history.clear()\n self.d_ref_history.clear()\n self.reward_history.clear()\n self.critic_history.clear()\n self.steps = 0\n self.pind = 1\n\n def generate_references(self, nn_action, space=None):\n v_ref = (nn_action[0] + 1) / 2 * self.max_v # change the min from -1 to 0\n d_ref = nn_action[1] * self.max_d\n\n return v_ref, d_ref\n\n\n\nclass GenVehicle(BaseGenAgent):\n def __init__(self, config, name, load=False):\n BaseGenAgent.__init__(self, config, name)\n\n state_space = 3 + self.n_beams\n self.agent = TD3(state_space, 2, 1, name)\n h_size = config['nn']['h']\n self.agent.try_load(load, h_size, path=self.path_name)\n\n def act(self, obs):\n nn_obs = self.transform_obs(obs)\n nn_action = self.agent.act(nn_obs)\n\n self.critic_history.append(self.agent.get_critic_value(nn_obs, nn_action))\n self.state_action = [nn_obs, nn_action]\n\n v_ref, d_ref = self.generate_references(nn_action, obs)\n self.steer_history.append(d_ref/self.max_d)\n self.vel_history.append(v_ref/self.max_v)\n\n self.steps += 1\n\n return [v_ref, d_ref]\n\n def add_memory_entry(self, new_reward, done, s_prime, buffer):\n self.prev_nn_act = self.state_action[1][0]\n\n nn_s_prime = self.transform_obs(s_prime)\n\n mem_entry = (self.state_action[0], self.state_action[1], nn_s_prime, new_reward, done)\n\n buffer.add(mem_entry)\n\n\n\n\"\"\"Test Vehicles\"\"\"\nclass GenTest(BaseGenAgent):\n def __init__(self, config, name):\n path = 'Vehicles/' + name + ''\n self.agent = TD3(1, 1, 1, name)\n self.agent.load(directory=path)\n\n print(f\"NN: {self.agent.actor.type}\")\n\n nn_size = self.agent.actor.l1.in_features\n n_beams = nn_size - 3\n BaseGenAgent.__init__(self, config, name)\n\n def act(self, obs):\n nn_obs = self.transform_obs(obs)\n nn_action = self.agent.act(nn_obs, noise=0)\n\n v_ref, d_ref = self.generate_references(nn_action)\n\n return [v_ref, d_ref]\n\n\n\n\n","sub_path":"toy_auto_race/NavAgents/RefGen.py","file_name":"RefGen.py","file_ext":"py","file_size_in_byte":5351,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"533740290","text":"import sys\nimport numpy as np\nfrom normalization import tokenize\nfrom helpers import ahash, normalize_array\nfrom collections import Counter\n\ndef convert_to_weights(embedding):\n if embedding.get('random_start', False):\n return None\n \n embedding_weights = np.zeros((embedding['input_dim'], embedding['embedding_dim']))\n for word,index in embedding['index_dict'].iteritems():\n embedding_weights[index,:] = embedding['word_vectors'][word]\n \n return [embedding_weights]\n\n\nclass KerasEmbeddingProcesser():\n def __init__(self, normalize=True, n_features=100000, hash_function=ahash, input_dim=None, stop_words=[]):\n self.n_features = n_features\n self.hash_function = hash_function\n self.normalize = normalize\n \n if input_dim:\n self.input_dim = input_dim + 2\n else:\n self.input_dim = self.n_features + 2\n \n if len(stop_words) > 0:\n self.stop_words = stop_words\n else:\n self.stop_words = None\n \n def _remove_stop_words(self, index_dict, stop_words):\n for w in stop_words:\n if index_dict.get(w):\n del index_dict[w]\n \n return index_dict\n \n def fit_transform(self, words, vectors):\n if self.normalize:\n vectors = normalize_array(vectors)\n \n word_vectors = dict(zip(words, vectors))\n index_dict = dict(zip(words, map(lambda x: self.hash_function(x, self.n_features), words)))\n \n if self.stop_words:\n index_dict = self._remove_stop_words(index_dict, self.stop_words)\n \n return {\n \"word_vectors\" : word_vectors,\n \"index_dict\" : index_dict,\n \"input_dim\" : self.input_dim,\n \"embedding_dim\" : vectors.shape[1]\n }\n\n\nclass ExactKerasEmbeddingProcessor():\n def fit_transform(self, words, vectors):\n word_lookup = dict(zip(words, range(1, 1 + len(words))))\n exact_hash = lambda x,s: word_lookup.get(x, 0)\n return {\n \"word_vectors\" : dict(zip(words, vectors)),\n \"index_dict\" : dict(zip(words, map(lambda w: exact_hash(w, 0), words))),\n \"input_dim\" : len(words) + 1,\n \"embedding_dim\" : vectors.shape[1],\n \"hash_function\" : exact_hash\n }\n\n\nclass RandomKerasEmbeddingProcessor():\n def fit_transform(self, data, dim, min_count=2):\n \n counter = Counter()\n for i, sent in enumerate(data):\n for tok in sent:\n counter[tok] += 1\n \n if not i % 10000:\n sys.stdout.write(\"\\r - Processed %d\" % i)\n sys.stdout.flush()\n \n words = [k for k,v in counter.iteritems() if v > min_count]\n \n word_lookup = dict(zip(words, range(1, 1 + len(words))))\n exact_hash = lambda x,s: word_lookup.get(x, 0)\n vectors = np.random.normal(0, 1, (len(words), dim))\n print\n return {\n \"word_vectors\" : dict(zip(words, vectors)),\n \"index_dict\" : dict(zip(words, map(lambda w: exact_hash(w, 0), words))),\n \"input_dim\" : len(words) + 1,\n \"embedding_dim\" : vectors.shape[1],\n \"hash_function\" : exact_hash\n }\n","sub_path":"smlib/keras_embeddings.py","file_name":"keras_embeddings.py","file_ext":"py","file_size_in_byte":3318,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"641234147","text":"from multiprocessing import Process\nimport os\nimport math\ndef calc():\n for i in range(0,40000):\n print(i)\n \nprocesses=[]\nfor i in range(1,5):\n print('reg thread %d'%i)\n processes.append(Process(target=calc))\nfor process in processes:\n process.start()\nfor process in processes:\n process.join() ","sub_path":"thread/proc.py","file_name":"proc.py","file_ext":"py","file_size_in_byte":323,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"341233376","text":"\"\"\"\nDrawing springs and masses in 2D.\n\"\"\"\n\nimport numpy as np\nimport matplotlib.pyplot as plt\n\nclass Spring:\n \"\"\"Curly spring.\"\"\"\n\n def __init__(self, x0, y0, theta, l, slant, r, w, nPoints=1000):\n \"\"\"\n Create spring.\n\n @params x0, y0: Center coordinates.\n @params theta: Angle wrt OY, in radians.\n @params l: Length.\n @params r: Radius.\n @params w: Frequency.\n \"\"\"\n\n self.x0, self.y0 = x0, y0\n self.theta = theta\n self.l = l\n self.slant = slant\n self.r = r\n self.w = w\n self.nPoints = nPoints\n\n R = np.array([\n [np.cos(self.theta), -np.sin(self.theta)],\n [np.sin(self.theta), np.cos(self.theta)]\n ])\n\n self.t = np.linspace(-1-np.pi/self.w, 1, self.nPoints)\n\n self.x = self.r * np.cos(self.w*self.t+np.pi/2)\n self.y = .5 * self.l * self.t + self.slant*np.sin(self.w*self.t+np.pi/2)\n self.z = self.r * np.sin(self.w*self.t+np.pi/2)\n\n self.x, self.y = np.dot(R, np.vstack([self.x, self.y]))\n\n self.x += self.x0\n self.y += self.y0\n\n def draw2D(self, ax=None, **kwds):\n \"\"\"\n Draw spring's projection onto XY plane.\n \"\"\"\n\n if ax is None:\n fig, ax = plt.subplots()\n\n ax.plot(self.x, self.y, **kwds)\n\n return ax\n\nif __name__=='__main__':\n\n # Spring parameters\n r = .25\n w = 4 * 2*np.pi\n slant = .15\n l = 2*np.sqrt(3)\n\n # Arrows\n arrNorm = 2.5\n arrWidth = .5\n\n mode0 = [\n arrNorm*np.array([-1/2, np.sqrt(3)/6]),\n arrNorm*np.array([0, -np.sqrt(3)/3]),\n arrNorm*np.array([1/2, np.sqrt(3)/6])\n ]\n\n mode1 = [\n arrNorm*np.array([-np.sqrt(3)/6, -1/2]),\n arrNorm*np.array([np.sqrt(3)/3,0]),\n arrNorm*np.array([-np.sqrt(3)/6, 1/2])\n ]\n\n fig, axs = plt.subplots(1,2,figsize=(20,10))\n\n for j, (ax, mode) in enumerate(zip(axs, (mode0, mode1))):\n\n # Lower\n Spring(x0=0, y0=-1, theta=-np.pi/2, l=l, slant=slant, w=w, r=r).draw2D(ax=ax, color='k', lw=2)\n\n # Left\n Spring(x0=-np.sqrt(3)/2, y0=1/2, theta=-np.pi/6, l=l, slant=slant, w=w, r=r).draw2D(ax=ax, color='k', lw=2)\n\n # Right\n Spring(x0=np.sqrt(3)/2, y0=1/2, theta=np.pi/6, l=l, slant=slant, w=w, r=r).draw2D(ax=ax, color='k', lw=2)\n\n # Masses\n top = plt.Circle((0,2), .5, edgecolor='k', facecolor='w', zorder=2, lw=2)\n left = plt.Circle((-np.sqrt(3),-1), .5, edgecolor='k', facecolor='w', zorder=2, lw=2)\n right = plt.Circle((np.sqrt(3),-1), .5, edgecolor='k', facecolor='w', zorder=2, lw=2)\n ax.add_artist(top)\n ax.add_artist(left)\n ax.add_artist(right)\n\n ax.add_artist(plt.Arrow(np.sqrt(3), -1, mode[0][0], mode[0][1], width=arrWidth, color='k'))\n ax.add_artist(plt.Arrow(0, 2, mode[1][0], mode[1][1], width=arrWidth, color='k'))\n ax.add_artist(plt.Arrow(-np.sqrt(3), -1, mode[2][0], mode[2][1], width=arrWidth, color='k'))\n\n # Text\n fsize = 40\n ax.text(0, 2, '2', color='k', size=fsize, horizontalalignment='center', verticalalignment='center')\n ax.text(-np.sqrt(3), -1, '3', color='k', size=fsize, horizontalalignment='center', verticalalignment='center')\n ax.text(np.sqrt(3), -1, '1', color='k', size=fsize, horizontalalignment='center', verticalalignment='center')\n\n ax.set_xlim(-2.5, 2.5)\n ax.set_ylim(-2.5, 3)\n\n ax.set_axis_off()\n\n plt.savefig('springs_nm_1.png')\n plt.close()\n","sub_path":"h2/springs.py","file_name":"springs.py","file_ext":"py","file_size_in_byte":3574,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"32022511","text":"#!/usr/bin/env python\n\nimport csv\nimport re\nimport argparse\nimport os\nimport subprocess\nimport logging\nimport sys\nimport annoutils\nimport pandas as np\nimport toml\nfrom cyvcf2 import VCF\n\nlogger = logging.getLogger('cpsr-validate-input')\nglobal debug\n\ndef __main__():\n\n parser = argparse.ArgumentParser(description='Verify input data for CPSR')\n parser.add_argument('pcgr_dir',help='Docker location of PCGR base directory with accompanying data directory, e.g. /data')\n parser.add_argument('input_vcf', help='VCF input file with query variants (SNVs/InDels)')\n parser.add_argument('custom_bed',help='Custom BED file indicating targeted screening loci')\n parser.add_argument('configuration_file', help='Configuration file (TOML-formatted, e.g. pcgr_conf.toml)')\n parser.add_argument('vcf_validation',type=int, default=0,choices=[0,1], help=\"Perform VCF validation with Ensembl's vcf-validator\")\n parser.add_argument('genome_assembly',help='grch37 or grch38')\n parser.add_argument('virtual_panel_id',type=int,help='virtual panel identifier')\n parser.add_argument('diagnostic_grade_only', type=int, default=0, choices=[0,1], help=\"Green virtual panels only (Genomics England PanelApp)\")\n parser.add_argument('--output_dir', dest='output_dir', help='Output directory', default='/workdir/output')\n parser.add_argument('--debug',action='store_true',default=False, help='Print full docker commands to log')\n args = parser.parse_args()\n\n global debug\n debug = args.debug\n\n ret = validate_cpsr_input(args.pcgr_dir, args.input_vcf, args.custom_bed, args.configuration_file, args.vcf_validation, args.genome_assembly, args.virtual_panel_id, args.diagnostic_grade_only, args.output_dir)\n if ret != 0:\n sys.exit(1)\n\ndef check_subprocess(command):\n if debug:\n logger.info(command)\n try:\n output = subprocess.check_output(str(command), stderr=subprocess.STDOUT, shell=True)\n if len(output) > 0:\n print (str(output.decode()).rstrip())\n except subprocess.CalledProcessError as e:\n print (e.output.decode())\n exit(0)\n\ndef is_valid_vcf(input_vcf, output_dir, logger):\n \"\"\"\n Function that reads the output file of EBIvariation/vcf-validator and reports potential errors and validation status\n \"\"\"\n\n logger.info('Validating VCF file with EBIvariation/vcf-validator')\n vcf_validation_output_file = os.path.join(output_dir, re.sub(r'(\\.vcf$|\\.vcf\\.gz$)', '.vcf_validator_output', os.path.basename(input_vcf)))\n command_v42 = 'vcf_validator --input ' + str(input_vcf) + ' > ' + str(vcf_validation_output_file)\n if input_vcf.endswith('.gz'):\n command_v42 = 'bgzip -dc ' + str(input_vcf) + ' | vcf_validator > ' + str(vcf_validation_output_file)\n check_subprocess(command_v42)\n\n\n #is_valid_vcf = -1\n validation_results = {}\n validation_results['validation_status'] = 0\n validation_results['error_messages'] = []\n if os.path.exists(vcf_validation_output_file):\n f = open(vcf_validation_output_file, 'r')\n for line in f:\n if not re.search(r' \\(warning\\)$|^Reading from ',line.rstrip()): ## ignore warnings\n if line.startswith('Line '):\n validation_results['error_messages'].append('ERROR: ' + line.rstrip())\n if 'the input file is valid' in line.rstrip(): ## valid VCF\n validation_results['validation_status'] = 1\n if 'the input file is not valid' in line.rstrip(): ## non-valid VCF\n validation_results['validation_status'] = 0\n f.close()\n if not debug:\n check_subprocess('rm -f ' + str(vcf_validation_output_file))\n else:\n err_msg = str(vcf_validation_output_file) + ' does not exist'\n return annoutils.error_message(err_msg, logger)\n\n if validation_results['validation_status'] == 0:\n error_string_42 = '\\n'.join(validation_results['error_messages'])\n validation_status = 'According to the VCF specification, the VCF file (' + str(input_vcf) + ') is NOT valid'\n err_msg = validation_status + ':\\n' + str(error_string_42)\n return annoutils.error_message(err_msg, logger)\n else:\n validation_status = 'According to the VCF specification, the VCF file ' + str(input_vcf) + ' is valid'\n logger.info(validation_status)\n return 0\n\n\ndef is_valid_custom_bed(bed_file, logger):\n \"\"\"\n Function that checks whether the custom panel (BED) adheres to the correct format\n \"\"\"\n \n \n bed_reader = csv.DictReader(open(bed_file,'r'), delimiter='\\t')\n for row in bed_reader:\n fields = len(row)\n if len(row) != 4:\n err_msg = 'BED file with custom screening regions must contain four columns: \\'Chromosome\\', \\'Start\\',\\'End\\',\\'GeneSymbol\\' - found entry containing ' + len(row) + ' columns'\n return annoutils.error_message(err_msg, logger)\n \n bed_reader = csv.DictReader(open(bed_file,'r'), delimiter='\\t', fieldnames=['Chromosome','Start','End','Symbol'])\n \n bed_dataframe = np.read_csv(bed_file, usecols = [0,1,2,3], sep=\"\\t\",names=[\"Chromosome\", \"Start\", \"End\",\"Symbol\"])\n if not bed_dataframe['Start'].dtype.kind in 'i': ## check that 'Start' is of type integer\n err_msg = '\\'Start\\' column of BED file (custom panel) contains non-integer values'\n return annoutils.error_message(err_msg, logger)\n if not bed_dataframe['End'].dtype.kind in 'i': ## check that 'End' is of type integer\n err_msg = '\\'End\\' column of BED file (custom panel) contains non-integer values'\n return annoutils.error_message(err_msg, logger)\n\n for rec in bed_reader:\n if int(rec['End']) < int(rec['Start']): ## check that 'End' is always greather than 'Start'\n err_msg = 'Detected wrongly formatted BED segment - \\'Start\\' is greater than \\'End\\' (' + str(rec['Chromosome']) + ':' + str(rec['Start']) + '-' + str(rec['End']) + ')'\n return annoutils.error_message(err_msg, logger)\n if int(rec['End']) < 1 or int(rec['Start']) < 0: ## check that 'Start' and 'End' is always non-negative\n err_msg = 'Detected wrongly formatted BED segment - \\'Start\\' or \\'End\\' is less than or equal to zero (' + str(rec['Chromosome']) + ':' + str(rec['Start']) + '-' + str(rec['End']) + ')'\n return annoutils.error_message(err_msg, logger)\n logger.info('Custom panel BED file (' + str(bed_file) + ') adheres to the correct format (gene symbols not checked)')\n\n return 0\n\n\ndef check_existing_vcf_info_tags(input_vcf, pcgr_directory, genome_assembly, logger):\n\n \"\"\"\n Function that compares the INFO tags in the query VCF and the INFO tags generated by PCGR\n If any coinciding tags, an error will be returned\n \"\"\"\n\n pcgr_infotags_desc = annoutils.read_infotag_file(os.path.join(pcgr_directory,'data',genome_assembly, 'cpsr_infotags.tsv'))\n\n vcf = VCF(input_vcf)\n logger.info('Checking if existing INFO tags of query VCF file coincide with CPSR INFO tags')\n ret = 1\n for e in vcf.header_iter():\n header_element = e.info()\n if 'ID' in header_element.keys() and 'HeaderType' in header_element.keys():\n if header_element['HeaderType'] == 'INFO':\n if header_element['ID'] in pcgr_infotags_desc.keys():\n err_msg = 'INFO tag ' + str(header_element['ID']) + ' in the query VCF coincides with a VCF annotation tag produced by CPSR - please remove or rename this tag in your query VCF'\n return annoutils.error_message(err_msg, logger)\n\n logger.info('No query VCF INFO tags coincide with CPSR INFO tags')\n return ret\n\ndef simplify_vcf(input_vcf, vcf, custom_bed, pcgr_directory, genome_assembly, virtual_panel_id, diagnostic_grade_only, output_dir, logger):\n\n \"\"\"\n Function that performs tre things on the validated input VCF:\n 1. Strip of any genotype data\n 2. If VCF have variants with multiple alternative alleles (\"multiallelic\", e.g. 'A,T'), these are decomposed into variants with a single alternative allele\n 3. Filters against predisposition loci (virtual panel id or custom target)\n 4. Final VCF file is sorted and indexed (bgzip + tabix)\n \"\"\"\n\n input_vcf_cpsr_ready = os.path.join(output_dir, re.sub(r'(\\.vcf$|\\.vcf\\.gz$)','.cpsr_ready.tmp.vcf', os.path.basename(input_vcf)))\n input_vcf_cpsr_ready_decomposed = os.path.join(output_dir, re.sub(r'(\\.vcf$|\\.vcf\\.gz$)','.cpsr_ready.vcf', os.path.basename(input_vcf)))\n input_vcf_cpsr_ready_decomposed_target = os.path.join(output_dir, re.sub(r'(\\.vcf$|\\.vcf\\.gz$)','.cpsr_ready_target.vcf', os.path.basename(input_vcf)))\n custom_bed_cpsr_ready = os.path.join(output_dir, re.sub(r'(\\.bed$)','.cpsr_ready.bed', os.path.basename(custom_bed)))\n\n multiallelic_alt = 0\n for rec in vcf:\n POS = rec.start + 1\n alt = \",\".join(str(n) for n in rec.ALT)\n if len(rec.ALT) > 1:\n logger.warning(\"Multiallelic site detected:\" + str(rec.CHROM) + '\\t' + str(POS) + '\\t' + str(rec.REF) + '\\t' + str(alt))\n multiallelic_alt = 1\n command_vcf_sample_free1 = 'egrep \\'^##\\' ' + str(input_vcf) + ' > ' + str(input_vcf_cpsr_ready)\n command_vcf_sample_free2 = 'egrep \\'^#CHROM\\' ' + str(input_vcf) + ' >> ' + str(input_vcf_cpsr_ready)\n command_vcf_sample_free3 = 'egrep -v \\'^#\\' ' + str(input_vcf) + ' | sed \\'s/^chr//\\' | egrep \\'^[0-9]\\' | sort -k1,1n -k2,2n -k4,4 -k5,5 >> ' + str(input_vcf_cpsr_ready)\n command_vcf_sample_free4 = 'egrep -v \\'^#\\' ' + str(input_vcf) + ' | sed \\'s/^chr//\\' | egrep -v \\'^[0-9]\\' | egrep \\'^[XYM]\\' | sort -k1,1 -k2,2n -k4,4 -k5,5 >> ' + str(input_vcf_cpsr_ready)\n command_vcf_sample_free5 = 'egrep -v \\'^#\\' ' + str(input_vcf) + ' | sed \\'s/^chr//\\' | egrep -v \\'^[0-9]\\' | egrep -v \\'^[XYM]\\' | sort -k1,1 -k2,2n -k4,4 -k5,5 >> ' + str(input_vcf_cpsr_ready)\n command_custom_bed1 = 'egrep -v \\'^#\\' ' + str(custom_bed) + ' | sed \\'s/^chr//\\' | egrep -v \\'^[0-9]\\' | cut -f1-4 | egrep \\'^[XYM]\\' | sort -k1,1n -k2,2n -k3,3n > ' + str(custom_bed_cpsr_ready)\n command_custom_bed2 = 'egrep -v \\'^#\\' ' + str(custom_bed) + ' | sed \\'s/^chr//\\' | egrep \\'^[0-9]\\' | cut -f1-4 | sort -k1,1 -k2,2n -k3,3n >> ' + str(custom_bed_cpsr_ready)\n\n if input_vcf.endswith('.gz'):\n command_vcf_sample_free1 = 'bgzip -dc ' + str(input_vcf) + ' | egrep \\'^##\\' > ' + str(input_vcf_cpsr_ready)\n command_vcf_sample_free2 = 'bgzip -dc ' + str(input_vcf) + ' | egrep \\'^#CHROM\\' >> ' + str(input_vcf_cpsr_ready)\n command_vcf_sample_free3 = 'bgzip -dc ' + str(input_vcf) + ' | egrep -v \\'^#\\' | sed \\'s/^chr//\\' | egrep \\'^[0-9]\\' | sort -k1,1n -k2,2n -k4,4 -k5,5 >> ' + str(input_vcf_cpsr_ready)\n command_vcf_sample_free4 = 'bgzip -dc ' + str(input_vcf) + ' | egrep -v \\'^#\\' | sed \\'s/^chr//\\' | egrep -v \\'^[0-9]\\' | egrep \\'^[XYM]\\' | sort -k1,1 -k2,2n -k4,4 -k5,5 >> ' + str(input_vcf_cpsr_ready)\n command_vcf_sample_free5 = 'bgzip -dc ' + str(input_vcf) + ' | egrep -v \\'^#\\' | sed \\'s/^chr//\\' | egrep -v \\'^[0-9]\\' | egrep -v \\'^[XYM]\\' | sort -k1,1 -k2,2n -k4,4 -k5,5 >> ' + str(input_vcf_cpsr_ready)\n\n check_subprocess(command_vcf_sample_free1)\n check_subprocess(command_vcf_sample_free2)\n check_subprocess(command_vcf_sample_free3)\n check_subprocess(command_vcf_sample_free4)\n check_subprocess(command_vcf_sample_free5)\n if not custom_bed == 'None':\n check_subprocessm(command_custom_bed1)\n check_subprocess(command_custom_bed2)\n\n if multiallelic_alt == 1:\n logger.info('Decomposing multi-allelic sites in input VCF file using \\'vt decompose\\'')\n command_decompose = 'vt decompose -s ' + str(input_vcf_cpsr_ready) + ' > ' + str(input_vcf_cpsr_ready_decomposed) + ' 2> ' + os.path.join(output_dir, 'decompose.log')\n check_subprocess(command_decompose)\n else:\n command_copy = 'cp ' + str(input_vcf_cpsr_ready) + ' ' + str(input_vcf_cpsr_ready_decomposed)\n check_subprocess(command_copy)\n\n\n if not custom_bed == 'None':\n logger.info('Limiting variant set to user-defined screening loci (custom BED)')\n if os.path.exists(custom_bed_cpsr_ready) and os.stat(custom_bed_cpsr_ready).st_size != 0:\n target_variants_intersect_cmd = \"bedtools intersect -wa -u -header -a \" + str(input_vcf_cpsr_ready_decomposed) + \" -b \" + str(custom_bed_cpsr_ready) + \" > \" + str(input_vcf_cpsr_ready_decomposed_target)\n check_subprocess(target_variants_intersect_cmd)\n else:\n logger.info('Custom BED file has a filesize of zero or does not exist')\n else:\n logger.info('Limiting variant set to cancer predisposition loci - virtual panel_id ' + str(virtual_panel_id))\n target_bed = os.path.join(pcgr_directory,'data',genome_assembly, 'virtual_panels', str(virtual_panel_id) + \".\" + genome_assembly + \".bed.gz\")\n if diagnostic_grade_only == 1 and virtual_panel_id != 0:\n target_bed = os.path.join(pcgr_directory, 'data', genome_assembly, 'virtual_panels', str(virtual_panel_id) + \".\" + genome_assembly + \".GREEN.bed.gz\")\n if os.path.exists(target_bed):\n target_variants_intersect_cmd = 'bedtools intersect -wa -u -header -a ' + str(input_vcf_cpsr_ready_decomposed) + ' -b ' + str(target_bed) + ' > ' + str(input_vcf_cpsr_ready_decomposed_target)\n check_subprocess(target_variants_intersect_cmd)\n else:\n logger.info('')\n logger.info(\"Virtual gene panel - BED file (\" + str(target_bed) + \") not found - exiting\")\n logger.info('')\n exit(1)\n \n check_subprocess('bgzip -cf ' + str(input_vcf_cpsr_ready_decomposed_target) + ' > ' + str(input_vcf_cpsr_ready_decomposed_target) + '.gz')\n check_subprocess('tabix -p vcf ' + str(input_vcf_cpsr_ready_decomposed_target) + '.gz')\n if not debug:\n check_subprocess('rm -f ' + str(input_vcf_cpsr_ready) + ' ' + str(input_vcf_cpsr_ready_decomposed) + ' ' + os.path.join(output_dir, 'decompose.log'))\n\n if os.path.exists(input_vcf_cpsr_ready_decomposed_target + '.gz') and os.path.getsize(input_vcf_cpsr_ready_decomposed_target + '.gz') > 0:\n vcf = VCF(input_vcf_cpsr_ready_decomposed_target + '.gz')\n i = 0\n for rec in vcf:\n i = i + 1\n if len(vcf.seqnames) == 0 or i == 0:\n logger.info('')\n logger.info(\"Query VCF contains NO variants within the selected cancer predisposition gene set - quitting workflow\")\n logger.info('')\n exit(1)\n\ndef validate_cpsr_input(pcgr_directory, input_vcf, custom_bed, configuration_file, vcf_validation, genome_assembly, virtual_panel_id, diagnostic_grade_only, output_dir):\n \"\"\"\n Function that reads the input files to CPSR (VCF file) and performs the following checks:\n 1. Check that VCF file is properly formatted (according to EBIvariation/vcf-validator - VCF v4.2) - optional (vcf_validation in config file)\n 2. Check that no INFO annotation tags in the query VCF coincides with those generated by CPSR\n 3. Check that if VCF have variants with multiple alternative alleles (e.g. 'A,T') run vt decompose\n 4. Check that VCF contains a single sample column \n 5. The resulting VCF file is sorted and indexed (bgzip + tabix)\n \"\"\"\n logger = annoutils.getlogger('cpsr-validate-input')\n\n if not custom_bed == 'None':\n\n valid_bed = is_valid_custom_bed(custom_bed, logger)\n\n #config_options = annoutils.read_config_options(configuration_file, pcgr_directory, genome_assembly, logger, wflow = 'cpsr')\n if not input_vcf == 'None':\n if vcf_validation == 1:\n valid_vcf = is_valid_vcf(input_vcf, output_dir, logger)\n if valid_vcf == -1:\n return -1\n else:\n logger.info('Skipping validation of VCF file - as provided by option --no_vcf_validate')\n\n tag_check = check_existing_vcf_info_tags(input_vcf, pcgr_directory, genome_assembly, logger)\n if tag_check == -1:\n return -1\n\n vcf = VCF(input_vcf)\n samples = vcf.samples\n if len(samples) > 1:\n err_msg = \"Query VCF contains more than one sample column (\" + ', '.join(samples) + \") - CPSR expects a germline VCF with a single sample column - exiting\"\n return annoutils.error_message(err_msg, logger)\n simplify_vcf(input_vcf, vcf, custom_bed, pcgr_directory, genome_assembly, virtual_panel_id, diagnostic_grade_only, output_dir, logger)\n\n return 0\n\nif __name__==\"__main__\": __main__()\n","sub_path":"src/pcgr/cpsr_validate_input.py","file_name":"cpsr_validate_input.py","file_ext":"py","file_size_in_byte":16153,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"627512272","text":"#!/usr/bin/python3.7\n# -*- coding: utf-8 -*-\n# @Time : 2019/10/31 13:21\n# @Author: Jtyoui@qq.com\nfrom jtyoui.data import reader_conf\nimport time\nimport configparser\nimport os\nimport datetime\nimport re\n\nNOW_TIME = time.localtime(time.time())\n\n\nclass ParseTime:\n\n def __init__(self, data, current_date=None, date_format='%Y-%m-%d %H:%M:%S', **kwargs):\n \"\"\"初始化数据日期\n\n :param data: 当前数据\n :param current_date: 当前日期\n :param date_format: 日期解析格式\n :param kwargs: 其他参数\n - map_path: 解析日期的映射表\n - re_path: 匹配日期的正则表\n \"\"\"\n # 加载日期的映射表和匹配日期的正则表\n self.map, self.re = None, None\n self.load_config(**kwargs)\n\n self.data = data + '\\033'\n self._decide_ten()\n # 定义当前日期\n self.localtime = current_date if current_date else time.strftime(date_format)\n\n self.format = date_format\n\n # 将当前日期标准化\n local = time.strptime(self.localtime, self.format)\n\n # 初始化当前的年月日基本信息\n self.now_year = local.tm_year\n self.now_mon = local.tm_mon\n self.now_day = local.tm_mday\n self.now_week = local.tm_wday + 1\n if current_date:\n self.now_hour = local.tm_hour\n self.now_minute = local.tm_min\n self.now_second = local.tm_sec\n else:\n self.now_hour = 0\n self.now_minute = 0\n self.now_second = 0\n\n self.reduction = True # 启动还原时分秒\n\n def load_config(self, map_path=None, re_path=None):\n \"\"\"自定义日期解析映射表和匹配日期的正则表\n\n :param map_path: 解析日期的映射表\n :param re_path: 匹配日期的正则表\n \"\"\"\n path = os.path.dirname(__file__)\n self.map = configparser.ConfigParser()\n if map_path:\n self.map.read(map_path, encoding='UTF-8')\n else:\n self.map.read(path + os.sep + 'map.ini', encoding='UTF-8')\n if re_path:\n self.re = reader_conf(re_path)\n else:\n self.re = reader_conf(path + os.sep + 're.cfg')\n\n def change_time(self, day=0, hour=0, minute=0, week=0, second=0):\n \"\"\"增加天数来修改时间\"\"\"\n add_time = datetime.timedelta(days=day, hours=hour, minutes=minute, weeks=week, seconds=second)\n if self.reduction:\n change = F'{self.now_year}-{self.now_mon}-{self.now_day} 00:00:00' # 时分秒还原到0\n self.reduction = False\n else:\n change = self.str_time()\n add = datetime.datetime.strptime(change, self.format) + add_time\n self.now_year = add.year\n self.now_mon = add.month\n self.now_day = add.day\n self.now_hour = add.hour\n self.now_minute = add.minute\n self.now_second = add.second\n self.now_week = add.isoweekday()\n\n def _analysis(self, name):\n \"\"\"分析数据获取年月日周时分秒中的有效信息\n\n :param name: 年月日时周分秒调用名字\n :return: 改变的值\n \"\"\"\n re_year = '|'.join(self.re['re_' + name])\n ls = re.search(re_year, self.data)\n if ls is not None:\n message = ls.group()\n add_year = self.map['add_' + name]\n value = add_year.get(message, 0)\n else:\n value = 0\n return int(value)\n\n def standard_time(self):\n \"\"\"标准时间化\"\"\"\n return time.strptime(self.str_time(), self.format)\n\n def str_time(self):\n \"\"\"字符串时间\"\"\"\n return self.__str__()\n\n def day(self):\n \"\"\"查询天数\"\"\"\n value = self._analysis('day')\n if value == 0:\n re_year = '|'.join(self.re['re_day'])\n change_day = re.search(re_year, self.data)\n if change_day:\n message = change_day.group()\n if message[:-1].isdigit():\n self.now_day = message[:-1]\n elif '后' in message:\n value = int(message[:message.find('天')])\n elif '前' in message:\n value = -int(message[:message.find('天')])\n self.change_time(day=value)\n\n def month(self):\n \"\"\"查询月份\"\"\"\n value = self._analysis('month')\n if value == 0:\n re_month = '|'.join(self.re['re_month'])\n change_month = re.search(re_month, self.data)\n if change_month:\n message = change_month.group()\n if '个月' in message:\n point = message[:message.find('个')]\n else:\n point = message[:message.find('月')]\n if point.isdigit():\n point = int(point)\n if '底' in message:\n self.now_mon = point + 1\n self.now_day = 1\n self.change_time(day=-1)\n elif '除' in message:\n self.now_mon = point\n self.now_day = 1\n elif '后' in message:\n value = point\n elif '前' in message:\n value = -point\n else:\n self.now_mon = point\n if value:\n mon = self.now_mon + value\n if mon == 0:\n self.now_year -= 1\n mon = 12\n if mon > 12:\n over_12_mon, mod_12 = divmod(mon, 12)\n self.now_year += over_12_mon\n self.now_mon = mod_12\n else:\n self.now_mon = mon\n\n def year(self):\n \"\"\"查询年份\"\"\"\n value = self._analysis('year')\n if value == 0:\n re_year = '|'.join(self.re['re_year'])\n change_year = re.search(re_year, self.data)\n if change_year:\n message = change_year.group()\n if message[:-1].isdigit():\n self.now_year = int(message[:-1])\n else:\n self.now_year += value\n\n def week(self):\n \"\"\"查找第几个周\"\"\"\n value = self._analysis('week')\n self.change_time(week=value)\n\n def what_week(self):\n \"\"\"查找当前周中的第几个星期\"\"\"\n ds = self.map['chinese_number']\n keys = r'星期(\\d+|' + '|'.join(ds.keys())[4:-11] + '天|日)'\n match = re.search(keys, self.data)\n if match is not None:\n value = match.group()\n point = value[2:]\n if point.isdigit():\n w = int(point)\n elif ds.get(point, None) is not None:\n w = int(ds[point])\n elif point in '天日':\n w = 7\n else:\n w = self.now_week # 暂未设置\n differ = w - self.now_week\n self.change_time(day=differ)\n\n def hour(self):\n \"\"\"查找当前的小时\"\"\"\n re_hour = '(' + '|'.join(self.re['re_hour']) + ')' + r'\\d+点'\n match = re.search(re_hour, self.data)\n if match is not None:\n value = match.group()\n add_hour = int(value[2:-1])\n point = value[:2]\n sc = int(self.map['add_hour'].get(point, 0))\n if add_hour < sc:\n if '凌晨' in value and add_hour == 12:\n add_hour = sc # 凌晨12点等于凌晨0点\n else:\n add_hour += sc\n self.change_time(hour=add_hour)\n else:\n self.reduction = False\n\n def minute(self):\n \"\"\"查找当前的分钟\"\"\"\n re_minute = '|'.join(self.re['re_minute'])\n match = re.search(re_minute, self.data)\n if match is not None:\n value = match.group()\n if '点半' in value:\n add_min = 30\n elif '分' in value:\n add_min = int(value[:-1])\n else:\n add_min = 0 # 其他情况\n self.change_time(minute=add_min)\n\n def second(self):\n \"\"\"查找当前的秒钟\"\"\"\n re_second = '|'.join(self.re['re_second'])\n match = re.search(re_second, self.data)\n if match is not None:\n value = match.group()\n if '秒' in value:\n add_second = int(value[:-1])\n self.change_time(second=add_second)\n\n def parse(self):\n \"\"\"开始解析,返回解析后的标准时间\"\"\"\n self.second()\n self.minute()\n self.hour()\n self.week()\n self.what_week()\n self.day()\n self.month()\n self.year()\n return self\n\n def find_times(self):\n \"\"\"同StringTime.find_times中的一样\"\"\"\n return [self.parse().__str__()]\n\n def _decide_ten(self):\n \"\"\"重新映射一些词语\"\"\"\n chinese_number = self.map['chinese_number']\n str_ = list()\n for data in self.data:\n if data == '周':\n # 如果又有周又有星期,不改变\n if '星期' in self.data:\n str_.append(data)\n else: # 否则将周改为星期\n str_.append(self.map['chinese_number'].get(data, data))\n elif data != '十' and data in chinese_number: # 十为特殊符号\n str_.append(self.map['chinese_number'][data])\n else:\n str_.append(data)\n if '十' in str_:\n # 判断十在每个位置上的不同意义\n for index, c in enumerate(str_):\n if c == '十':\n if str_[index - 1].isdigit() and str_[index + 1].isdigit(): # 比如:二十一实际上十可以取空,变成21\n str_[index] = ''\n elif str_[index - 1].isdigit() and (not str_[index + 1].isdigit()): # 比如:二十实际上十变成0,变成20\n str_[index] = '0'\n elif not str_[index - 1].isdigit() and str_[index + 1].isdigit(): # 比如:十三实际上十变成1,变成13\n str_[index] = '1'\n else:\n str_[index] = '10' # 其余情况十就变成10\n self.data = ''.join(str_[:-1])\n\n def __add__(self, other):\n \"\"\"两个时间对象相加\"\"\"\n pass\n\n def __mul__(self, other):\n \"\"\"两个时间对象相减\"\"\"\n pass\n\n def __str__(self):\n \"\"\"字符串格式化\"\"\"\n return F'{self.now_year}-{self.now_mon}-{self.now_day} ' \\\n F'{self.now_hour:0>2}:{self.now_minute:0>2}:{self.now_second:0>2}'\n\n\nif __name__ == '__main__':\n today = '2019-10-31 16:00:00'\n pt = ParseTime('上上个周星期天下午2点25分钟30秒', today).parse()\n print(pt) # 2019-10-20 14:25:30\n\n print('-----------------切换日期------------------')\n st = ParseTime('下周星期一下午2点半开会', today).parse()\n print(st) # 2019-11-4 14:30:00\n\n print('----------------多个时间-------------------')\n st = ParseTime('今天下午3点', today).parse()\n print(st) # 2019-10-31 15:00:00\n\n print('----------------没有时间-------------------')\n st = ParseTime('我要是不传时间呢?', today).parse()\n print(st) # 2019-10-31 16:00:00\n\n print('---------------只有天数--------------------')\n st = ParseTime('明天去哪里?', today).parse()\n print(st) # 2019-11-1 16:00:00\n\n print('---------------没有日期或者天数--------------------')\n st = ParseTime('下午2点半开会', today).parse()\n print(st) # 2019-10-31 14:30:00\n\n print('---------------*几个月以后--------------------')\n st = ParseTime('下个月1号下午3点', today).parse()\n print(st) # 2019-11-1 15:00:00\n\n print('--------------几天之后--------------')\n st = ParseTime('三天之前下午3点', today).parse()\n print(st) # 2019-10-28 15:00:00\n\n print('--------------几月底--------------')\n st = ParseTime('明年的2月底之前必须交报告', today).parse()\n print(st) # 2020-2-28 16:00:00\n\n print('--------晚上-----------')\n st = ParseTime('3月除', today).parse()\n print(st) # 2019-3-1 16:00:00\n\n print('--------下个周几-----------')\n st = ParseTime('下个周2', today).parse()\n print(st) # 2019-11-5 16:00:00\n\n print('--------几个月以后的日期--------')\n st = ParseTime('5个月后的明天', today).parse()\n print(st) # 2020-4-1 16:00:00\n\n print('------------凌晨或者半夜------------------')\n st = ParseTime('昨天凌晨3点', today).parse()\n print(st) # 2019-10-31 03:00:00\n\n print('-------------只说时间-----------------------')\n st = ParseTime('二零零七年八月二十一号下午2点半', today).parse()\n print(st) # 2007-8-21 14:30:00\n","sub_path":"jtyoui/time/parsetime.py","file_name":"parsetime.py","file_ext":"py","file_size_in_byte":12961,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"174803887","text":"from django.conf.urls import patterns, include, url\n\nfrom rest_framework import routers\n\nfrom user_management.views import (FBLogin,\n\t\t\t\t\t\t\t\t GroupViewSet,\n\t\t\t\t\t\t\t\t UserView,\n\t\t\t\t\t\t\t\t Register)\n\nrouter = routers.DefaultRouter()\nrouter.register(r'group', GroupViewSet)\n\nurlpatterns = patterns('',\n url(r'^auth/fb/login/?$', FBLogin.as_view()),\n url(r'^auth/login/?$', 'rest_framework.authtoken.views.obtain_auth_token'),\n url(r'^auth/register/?$', Register.as_view()),\n url(r'^user/(?P[^@]+@[^@]+\\.[^@/]+)/?$', UserView.as_view(), name='user-detail'),\n url(r'^', include(router.urls)),\n )\n","sub_path":"Backend/user_management/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":619,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"113388000","text":"from z3 import *\nfrom simple_test_env2 import *\nimport random\nfrom collections import namedtuple\nimport matplotlib.pyplot as plt\nimport itertools\nfrom constants import *\n\n\n# change these things to your liking:\nenv = Simple_test_env(\"RVOsplit1_15\")\nSPACE = (0,100)\nINRANGES=[(0,100)]\nTESTS = 5000\nKEEP_SPLITTING=True\nTEST = True\nNR_CUTS = 2\n\n#splits in two parts\n#parts consist out of areas, based on the cuts\n#areas consist out of one or two subareas, based on if they contain the edge of the variable space or not\n#areas are ranges\n\ndef main():\n if TEST:\n test()\n print(\"tests done; set TEST to False\")\n plot()\n\n# functions\n\ndef valid(part):\n if part==[]:\n return False\n for area in part:\n for (low,high) in area:\n if low!=high:\n for (low2,high2) in INRANGES:\n if low <= high2 and low2 <= high:\n return True\n return False\n\ndef size(areas):\n size=0\n for (low,high) in areas:\n size+=high-low\n return size\n\ndef at(areas,i):\n for (low,high) in areas:\n if i<(high-low):\n return i+low\n else:\n i-=(high-low)\n\ndef cutat(area,cuts):\n cuts.sort()\n part=[]\n lastcut=0\n for cut in cuts:\n i=cut-lastcut\n if i!=0:\n [left,right]=cutonce(area,i)\n part.append(left)\n area=right\n lastcut=cut\n part[0]=right+part[0]\n return part\n\ndef cutonce(area,i):\n for sub_i,(low,high) in enumerate(area):\n if i==0:\n return [area[:sub_i],area[sub_i:]]\n if i world.height() - 1:\n return None\n return Square(self.x,self.y+1)\n\n elif self.direction is Direction.East:\n if self.x+1 > world.width() - 1:\n print(\"end of the line\")\n return None\n return Square(self.x+1,self.y)\n\n elif self.direction is Direction.South:\n if self.y-1 < 0:\n return None\n return Square(self.x,self.y-1)\n\n elif self.direction is Direction.West:\n if self.x-1 < 0:\n return None\n return Square(self.x-1,self.y)\n\n def square_left(self):\n if self.direction is Direction.North:\n if self.x-1 < 0:\n return None\n return Square(self.x-1,self.y)\n\n elif self.direction is Direction.East:\n if self.y+1 > world.width():\n return None\n return Square(self.x,self.y +1)\n\n elif self.direction is Direction.South:\n if self.x+1 > world.height():\n return None\n return Square(self.x+1,self.y)\n\n elif self.direction is Direction.West:\n if self.y-1 < 0:\n return None\n return Square(self.x,self.y-1)\n\n def move(self, x, y):\n world.move_queue.put((self, x, y))\n\n\ndef process_move_queue():\n if not world.move_queue.empty():\n thing,x,y = world.move_queue.get()\n thing.x = x\n thing.y = y\n world.grid[x][y] = thing\n\ncreature = Creature()\n\ncall_repeatedly(.5,creature.run_turn)\ncall_repeatedly(.05, process_move_queue)","sub_path":"sim.py","file_name":"sim.py","file_ext":"py","file_size_in_byte":3714,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"284057310","text":"# Copyright 2015 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\n\"\"\"Trains and Evaluates the MNIST network using a feed dictionary.\"\"\"\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\n# pylint: disable=missing-docstring\nimport argparse\nimport os\nimport sys\nimport time\n\nfrom six.moves import xrange # pylint: disable=redefined-builtin\nimport tensorflow as tf\n\nimport input_data\nimport cnn_lstm_ctc_ocr\n\n# Basic model parameters as external flags.\nFLAGS = None\n\n# num_features = IMAGE_HEIGHT\ndef placeholder_inputs(image_width, image_height, channels):\n # [batch_size, image_width, image_height]\n images_placeholder = tf.placeholder(tf.float32, [None, image_height, image_width, channels])\n # Here we use sparse_placeholder that will generate a\n # SparseTensor required by ctc_loss op.\n labels_placeholder = tf.sparse_placeholder(tf.int32)\n # 1d array of size [image_size]\n seqlen_placeholder = tf.placeholder(tf.int32, [None])\n\n keep_prob = tf.placeholder(tf.float32) \n return images_placeholder, labels_placeholder, seqlen_placeholder, keep_prob\n\n\ndef fill_feed_dict(data_set, images_pl, labels_pl, seqlen_pl, keep_prob, all_data=False):\n images_feed, seqlen_feed, labels_feed = data_set.next_batch(FLAGS.batch_size, \n FLAGS.fake_data, \n all_data)\n images_feed = images_feed.reshape(-1, input_data.IMAGE_HEIGHT, input_data.IMAGE_WIDTH, input_data.CHANNELS)\n if all_data:\n feed_dict = {\n images_pl: images_feed,\n labels_pl: labels_feed,\n seqlen_pl: seqlen_feed,\n keep_prob: 1,\n }\n else:\n feed_dict = {\n images_pl: images_feed,\n labels_pl: labels_feed,\n seqlen_pl: seqlen_feed,\n keep_prob: 0.5,\n }\n return feed_dict\n\n\ndef do_eval(sess, dense_decoded, lastbatch_err, learning_rate, \n images_placeholder, labels_placeholder, seqlen_placeholder, \n keep_prob, data_set):\n true_count = 0 # Counts the number of correct predictions.\n\n feed_dict = fill_feed_dict(data_set, \n images_placeholder, \n labels_placeholder, \n seqlen_placeholder,\n keep_prob,\n all_data=True)\n dd, lerr, lr = sess.run([dense_decoded, lastbatch_err, learning_rate], \n feed_dict=feed_dict)\n #accuracy calculation\n for i, origin_label in enumerate(data_set.labels):\n decoded_label = [j for j in dd[i] if j != -1]\n if i < 10:\n print('seq {0} => origin:{1} decoded:{2}'.format(i, origin_label, decoded_label))\n if origin_label == decoded_label: \n true_count += 1\n #accuracy\n acc = true_count * 1.0 / len(data_set.labels)\n #print subsummary\n print(\"---- accuracy = {:.3f}, lastbatch_err = {:.3f}, learning_rate = {:.8f} ----\".format(acc, lerr, lr)) \n\n\ndef run_training():\n # Get the sets of images and labels for training, validation, and\n # test.\n data_sets = input_data.read_data_sets(FLAGS.input_data_dir, fill_labels=False)\n # Tell TensorFlow that the model will be built into the default Graph.\n with tf.Graph().as_default():\n # Generate placeholders for the images, labels and seqlens.\n #num_features\n images_placeholder, labels_placeholder, seqlen_placeholder, keep_prob = placeholder_inputs(input_data.IMAGE_WIDTH,\n input_data.IMAGE_HEIGHT,\n input_data.CHANNELS)\n # Build a Graph that computes predictions from the inference model.\n #images_lp, seqlen_lp, num_features, num_layers, hidden_units\n logits = cnn_lstm_ctc_ocr.inference(images_placeholder, \n seqlen_placeholder,\n keep_prob,\n FLAGS.hidden_units, \n FLAGS.mode,\n FLAGS.batch_size)\n # Add to the Graph the Ops for loss calculation.\n #logits, labels_lp, seqlen_lp\n loss = cnn_lstm_ctc_ocr.loss(logits, labels_placeholder, seqlen_placeholder)\n tf.summary.scalar('loss', loss)\n # global counter\n global_step = tf.Variable(0, name='global_step', trainable=False)\n # Add to the Graph the Ops that calculate and apply gradients.\n #loss, initial_learning_rate, decay_steps, decay_rate, momentum\n train_op, learning_rate = cnn_lstm_ctc_ocr.training(loss, global_step, \n FLAGS.initial_learning_rate, \n FLAGS.decay_steps, \n FLAGS.decay_rate, \n FLAGS.momentum)\n tf.summary.scalar('learning_rate', learning_rate)\n # Add the Op to compare the logits to the labels during evaluation.\n #logits, labels_lp, seqlen_lp\n dense_decoded, lerr = cnn_lstm_ctc_ocr.evaluation(logits, labels_placeholder, seqlen_placeholder)\n tf.summary.scalar('lerr', lerr)\n # Build the summary Tensor based on the TF collection of Summaries.\n summary = tf.summary.merge_all()\n\n # Add the variable initializer Op.\n init = tf.global_variables_initializer()\n # Create a saver for writing training checkpoints.\n saver = tf.train.Saver()\n # Create a session for running Ops on the Graph.\n sess = tf.Session()\n # Instantiate a SummaryWriter to output summaries and the Graph.\n summary_writer = tf.summary.FileWriter(FLAGS.log_dir, sess.graph)\n # Run the Op to initialize the variables.\n sess.run(init)\n\n # Start the training loop.\n for cur_epoch in xrange(FLAGS.max_steps):\n start_time = time.time()\n\n steps_per_epoch = data_sets.train.steps_per_epoch(FLAGS.batch_size)\n\n for step_per_epoch in xrange(steps_per_epoch):\n # Fill a feed dictionary with the actual set of images and labels\n # for this particular training step.\n #data_set, iamges_pl, labels_pl, seqlen_pl\n feed_dict = fill_feed_dict(data_sets.train,\n images_placeholder,\n labels_placeholder, \n seqlen_placeholder,\n keep_prob,\n )\n # Run one step of the model. The return values are the activations\n # from the `train_op` (which is discarded) and the `loss` Op. To\n # inspect the values of your Ops or variables, you may include them\n # in the list passed to sess.run() and the value tensors will be\n # returned in the tuple from the call.\n _, loss_value, g_step = sess.run([train_op, loss, global_step], feed_dict=feed_dict)\n\n #if g_step % 10 == 0:\n duration = time.time() - start_time\n start_time = time.time()\n print('[global:%d epoch:%d/%d step:%d/%d] loss = %.2f (%.3f sec)' % (g_step, \n cur_epoch, \n FLAGS.max_steps,\n step_per_epoch,\n steps_per_epoch, \n loss_value, \n duration))\n # Write the summaries and print an overview fairly often.\n if g_step % 100 == 0:\n # Update the events file.\n summary_str = sess.run(summary, feed_dict=feed_dict)\n summary_writer.add_summary(summary_str, g_step)\n summary_writer.flush()\n\n # Save a checkpoint and evaluate the model periodically.\n if (g_step + 1) % 500 == 0 or (g_step + 1) == FLAGS.max_steps:\n checkpoint_file = os.path.join(FLAGS.log_dir, 'model.ckpt')\n saver.save(sess, checkpoint_file, global_step=g_step)\n # Evaluate against the validation set.\n print('-------------------------- Validation Data Eval: --------------------------')\n do_eval(sess,\n dense_decoded,\n lerr,\n learning_rate,\n images_placeholder,\n labels_placeholder,\n seqlen_placeholder,\n keep_prob,\n data_sets.validation)\n\n\ndef main(_):\n if tf.gfile.Exists(FLAGS.log_dir):\n tf.gfile.DeleteRecursively(FLAGS.log_dir)\n tf.gfile.MakeDirs(FLAGS.log_dir)\n run_training()\n\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser()\n parser.add_argument(\n '--initial_learning_rate',\n type=float,\n default=1e-3,\n help='Initial learning rate.'\n )\n parser.add_argument(\n '--decay_rate',\n type=float,\n default=0.9,\n help='the learning rate\\'s decay rate.'\n )\n parser.add_argument(\n '--decay_steps',\n type=int,\n default=1000,\n help='the learning rate\\'s decay_step for optimizer.'\n )\n parser.add_argument(\n '--momentum',\n type=float,\n default=0.9,\n help='the momentum.'\n )\n parser.add_argument(\n '--max_steps',\n type=int,\n default=4000,\n help='Number of steps to run trainer.'\n )\n parser.add_argument(\n '--hidden_units',\n type=int,\n default=128,\n help='Number of units in LSTM hidden layer.'\n )\n parser.add_argument(\n '--batch_size',\n type=int,\n default=40,\n help='Batch size. Must divide evenly into the dataset sizes.'\n )\n parser.add_argument(\n '--input_data_dir',\n type=str,\n default=os.path.join(os.getenv('TEST_TMPDIR', '/Users/miles/dev/python_workspace'),\n 'ocr/dataset'),\n help='Directory to put the input data.'\n )\n parser.add_argument(\n '--log_dir',\n type=str,\n default=os.path.join(os.getenv('TEST_TMPDIR', '/Users/miles/dev/python_workspace'),\n 'ocr/tmp'),\n help='Directory to put the log data.'\n )\n parser.add_argument(\n '--fake_data',\n default=False,\n help='If true, uses fake data for unit testing.',\n action='store_true'\n )\n parser.add_argument(\n '--mode',\n default=\"train\",\n help='train|test',\n )\n\n FLAGS, unparsed = parser.parse_known_args()\n tf.app.run(main=main, argv=[sys.argv[0]] + unparsed)\n","sub_path":"cnn_lstm_ctc/cnn_lstm_ctc_ocr_feed.py","file_name":"cnn_lstm_ctc_ocr_feed.py","file_ext":"py","file_size_in_byte":11368,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"1905628","text":"#!/usr/bin/env python3\n\nimport sys\nfrom flask import Flask, render_template, request, json, jsonify\n\ndef result(data=None):\n i = 0\n ret = \"\"\"\"\n return ret\n\ndef main(connected='False', connected_as='', connected_to=''):\n ret = \"\"\"\n \n \n \n \n \n \n \n OurTubes - Add Music \n \n \n \n \n \n \n \n \"\"\"\n if connected == \"True\":\n ret += \"\"\"\n Music name \n \n Search \n \n \n \n \"\"\"\n else:\n ret += \"\"\"
Join a channel
\"\"\"\n ret += \"\"\"\n \n \"\"\"\n return ret\n","sub_path":"templates/addMusic.py","file_name":"addMusic.py","file_ext":"py","file_size_in_byte":6746,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"384673521","text":"import os\n\n\"\"\"\n Data structure:\n self.data:\n {\n 000: (user_id)\n 1: (activity_id, \"plt file name\")\n [
, , \n [trackpoint 1], [trackpoint 2], ..., [trackpoint N]]\n 2:\n [, , \n [trackpoint 1], [trackpoint 2], ..., [trackpoint N]]\n ...\n 001: (user_id)\n ...\n ...\n 181: (user_id)\n ...\n }\n \n trackpoint example:\n ['40.127951', '116.48646', '62', '39969.065474537', '2009-06-05 01:34:17']\n\n\n\n self.labels: (see txt file labeled_ids for more info)\n {\n 010:\n [[label 1], [label 2], ..., [label N]]\n 020:\n [[label 1], [label 2], ..., [label N]]\n ...\n 179:\n [[label 1], [label 2], ..., [label N]]\n }\n \n label example:\n ['2007-06-26 11:32:29', '2007-06-26 11:40:29', 'bus']\n\"\"\"\n\n\nclass Fetcher:\n\n def __init__(self):\n self.data = {}\n self.labels = {}\n\n # Main method: iterates file tree and inserts users, activities and trackpoints\n # Filters out trackpoints with more than 2500 lines (excluding headers)\n def fetch_data(self):\n user_id = ''\n activity_id = 0\n # iterations = 0 # num_user is unstable, will give some deterministic number of users close to num_users\n for root, dirs, files in os.walk(\"dataset\"):\n #if iterations == num_users + 3: # + 3 here because three first iterations are uninteresting files/dirs\n # break\n if \"Trajectory\" in dirs:\n user_id = root[-3:]\n print(\"Fetching activities and trackpoints for user with id: {}\".format(user_id))\n self.data[user_id] = {} # Create directory for each user\n\n if files: # Dataset specific, is used to identify if a user has labeled activities\n labels_filepath = os.path.join(root, files[0])\n self.add_labels_to_user(user_id, labels_filepath)\n\n # Dataset specific, skips uninteresting files at higher directory level\n if user_id and \"Trajectory\" not in dirs:\n for activity in files:\n activity_filepath = os.path.join(root, activity)\n activity_id += self.add_activities_and_trackpoints_to_user(user_id, activity_filepath, activity_id)\n #if files:\n # iterations += 1\n return self.data, self.labels\n\n # Adds label to user in self.labels, key is user id\n def add_labels_to_user(self, current_user, labels_filepath):\n self.labels[current_user] = []\n labels_file = open(labels_filepath, \"r\")\n lines = labels_file.readlines()[1:]\n for labeled_activity in lines:\n self.labels[current_user].append(labeled_activity.strip().replace(\"/\", \"-\").split(\"\\t\"))\n\n # Helper method for fetch_data\n def add_activities_and_trackpoints_to_user(self, user_id, activity_filepath, activity_id):\n activity_file = open(activity_filepath, \"r\")\n trackpoints = activity_file.readlines()[6:]\n\n # Ensures that activities with too many trackpoints don't get added\n num_trackpoints = sum(1 for trackpoint in trackpoints)\n if num_trackpoints > 2500:\n # print(\"Activity too large to be added, number of trackpoints: {}, proposed activity id: {}\"\n # .format(num_trackpoints, activity_id+1))\n return 0\n activity_id += 1\n self.data[user_id][activity_id] = []\n\n start_date = trackpoints[0].strip().split(\",\")[5]\n start_time = trackpoints[0].strip().split(\",\")[6]\n start_date_time = \"{} {}\".format(start_date, start_time)\n\n end_date = trackpoints[len(trackpoints)-1].strip().split(\",\")[5]\n end_time = trackpoints[len(trackpoints)-1].strip().split(\",\")[6]\n end_date_time = \"{} {}\".format(end_date, end_time)\n\n transportation_mode = None\n if user_id in self.labels:\n transportation_mode = self.determine_transportation(\n user_id, start_date_time, end_date_time)\n\n self.data[user_id][activity_id].append(start_date_time)\n self.data[user_id][activity_id].append(end_date_time)\n self.data[user_id][activity_id].append(transportation_mode)\n\n for trackpoint in trackpoints:\n self.add_trackpoint_to_activity(user_id, activity_id, trackpoint)\n return 1\n\n def determine_transportation(self, user, start_date_time, end_date_time):\n labeled_activities = self.labels[user]\n for activity in labeled_activities:\n label_activity_start = activity[0]\n label_activity_end = activity[1]\n transportation_mode = activity[2]\n if label_activity_start == start_date_time and label_activity_end == end_date_time:\n return \"{}\".format(transportation_mode)\n return None\n\n def add_trackpoint_to_activity(self, user_id, activity_id, trackpoint):\n trckpnt_attr = trackpoint.strip().split(\",\") # Trackpoint attributes\n lat, lon, altitude = trckpnt_attr[0], trckpnt_attr[1], trckpnt_attr[3]\n date_days, date_time_date, date_time_time = trckpnt_attr[4], trckpnt_attr[5], trckpnt_attr[6]\n date_time = \"{} {}\".format(date_time_date, date_time_time)\n relevant_attributes = [lat, lon, altitude, date_days, date_time]\n self.data[user_id][activity_id].append(relevant_attributes)\n","sub_path":"assignment_3/fetcher.py","file_name":"fetcher.py","file_ext":"py","file_size_in_byte":5862,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"206283627","text":"import numpy as np\nimport pandas as pd\nimport tensorflow as tf\nfrom tensorflow import keras\nfrom tensorflow.keras import layers\nfrom keras import preprocessing\nimport PIL\nimport matplotlib.pyplot as plt\n\nfrom keras.utils.np_utils import to_categorical\nfrom tensorflow.keras.models import Sequential\nfrom tensorflow.keras.layers import Dense, Dropout, Flatten, Conv2D, MaxPooling2D, MaxPooling3D\nfrom tensorflow.keras import utils\n\n# This checks if TF-GPU is installed\n# This portion of code was added from the source\nif tf.test.gpu_device_name():\n print('Default GPU Device: {}'.format(tf.test.gpu_device_name()))\nelse:\n print(\"Please install GPU version of TF\")\n\n# Hard Coding\n# production\n# The filepath was changed to be relative to my computer\ndir_path_images = '/home/blue/general-assembly/dsir-824/blog/sara-capstone-cuda/data/processed/melspec/'\n\nimage_size = (180,180)\nbatch_size = 64\nepochs = 10\n\n# test\n# The filepath was changed to be relative to my computer\ntest_path = '/home/blue/general-assembly/dsir-824/blog/sara-capstone-cuda/data/processed/melspec/baroque/img_150_baroque.png'\nimage = PIL.Image.open(test_path)\nwidth, height = image.size\nprint(width,height)\n\ndf_train = tf.keras.preprocessing.image_dataset_from_directory(\n dir_path_images,\n image_size=(180,180),\n validation_split=0.2,\n subset='training',\n seed=42,\n batch_size=batch_size,\n)\n\ndf_val = tf.keras.preprocessing.image_dataset_from_directory(\n dir_path_images,\n image_size=(180,180),\n validation_split=0.2,\n subset='validation',\n seed=42,\n batch_size=batch_size,\n)\n\n# I have omitted the matplotlib part to optimize speed for Command Line Execution\n\n# Get Data\ndf_train = df_train.prefetch(buffer_size=32)\ndf_val = df_val.prefetch(buffer_size=32)\n\n# Make Keras Model\ndef make_model(input_shape, num_classes):\n '''\n The function creates a CNN model that can be seen by looking at the \n model.summary(attribute)\n \n Parts of this model were changed to accept an input that is BGR\n '''\n inputs = keras.Input(shape=input_shape)\n # Image augmentation block\n x = data_augmentation(inputs)\n\n # Entry block\n x = layers.experimental.preprocessing.Rescaling(1. / 255)(x)\n x = layers.Conv2D(32, 3, strides=2, padding=\"same\")(x)\n x = layers.BatchNormalization()(x)\n x = layers.Activation(\"relu\")(x)\n x = layers.Conv2D(64, 3, padding=\"same\")(x)\n x = layers.BatchNormalization()(x)\n x = layers.Activation(\"relu\")(x)\n\n previous_block_activation = x # Set aside residual\n\n for size in [128, 256, 512, 728]:\n x = layers.Activation(\"relu\")(x)\n x = layers.SeparableConv2D(size, 3, padding=\"same\")(x)\n x = layers.BatchNormalization()(x)\n\n x = layers.Activation(\"relu\")(x)\n x = layers.SeparableConv2D(size, 3, padding=\"same\")(x)\n x = layers.BatchNormalization()(x)\n\n x = layers.MaxPooling2D(3, strides=2, padding=\"same\")(x)\n\n # Project residual\n residual = layers.Conv2D(size, 1, strides=2, padding=\"same\")(\n previous_block_activation\n )\n x = layers.add([x, residual]) # Add back residual\n previous_block_activation = x # Set aside next residual\n \n x = layers.SeparableConv2D(1024, 3, padding=\"same\")(x)\n x = layers.BatchNormalization()(x)\n x = layers.Activation(\"relu\")(x)\n\n x = layers.GlobalAveragePooling2D()(x)\n \n #if num_classes == 2:\n # activation = \"sigmoid\"\n # units = 1\n #else:\n # activation = \"softmax\"\n # units = num_classes\n activation = \"softmax\"\n units = num_classes\n\n x = layers.Dropout(0.5)(x)\n outputs = layers.Dense(units, activation=activation)(x)\n return keras.Model(inputs, outputs), x\n\n# Instantiate Model\nmodel, x = make_model(input_shape=image_size + (3,), num_classes=4)\n# The portion showing the network was removed\n\n# Set up model\n\nmodel.compile(\n #optimizer=keras.optimizers.Adam(1e-3),\n #loss='categorical_crossentropy',\n optimizer='adam',\n loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True),\n metrics=['accuracy'],\n # Activate this to run the model as python code, line by line\n # it is slower but it is useful for debugging\n #run_eagerly=True\n)\n\n# Changed number of workers to 4 threads\n# Enabled Multiprocessing\nhistory = model.fit(df_train, epochs=epochs, validation_data=df_val, workers=8, use_multiprocessing=True)","sub_path":"main/model/model-1-cnn-cuda.py","file_name":"model-1-cnn-cuda.py","file_ext":"py","file_size_in_byte":4410,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"315005167","text":"import numpy as np\nfrom sklearn.base import BaseEstimator\nfrom sklearn.linear_model._base import LinearClassifierMixin\nfrom sklearn.utils import check_X_y\n\n# La fonction logistique\nfrom scipy.special import expit\n\n\n# On hérite de `LinearClassifierMixin` qui gère toute la partie\n# prédiction pourvu qu'on renseigne les attributs `coef_`,\n# `intercept_` et `classes_` lors de l'apprentissage.\nclass LogisticRegression(BaseEstimator, LinearClassifierMixin):\n def __init__(self, max_iter=1000, tol=1e-5, fit_intercept=True):\n self.max_iter = max_iter\n self.tol = tol\n self.fit_intercept = fit_intercept\n\n def fit(self, X, y):\n # On valide `X` et `y` en transformant par exemple les\n # DataFrame ou Series Pandas en tableau Numpy\n X, y = check_X_y(X, y)\n\n # On définit les classes qui ne sont pas nécessairement les\n # entiers 0 et 1. On convertit les classes de `y` en des\n # entiers.\n self.classes_, y = np.unique(y, return_inverse=True)\n\n # On rajoute une colonne de \"1\" si on veut apprendre une\n # constante\n p = X.shape[1]\n if self.fit_intercept:\n p += 1\n X = np.column_stack((np.ones(X.shape[0]), X))\n\n it = 1\n step = self.tol + 1\n beta = np.zeros(p)\n\n while np.linalg.norm(step) > self.tol and it < self.max_iter:\n # Calcul des p_i avec la fonction logistique\n pi = ...\n\n # Calcul du gradient\n grad = ...\n\n # Calcul de la matrice hessienne\n hessian = ...\n\n # Calcul de l'incrément avec `np.linalg.solve` ou\n # `np.linalg.inv`.\n step = ...\n\n # Mis à jour de beta\n beta += ...\n\n it += 1\n\n # Stockage des paramètres appris. Attention, pour que la\n # prédiction avec la fonction `predict` marche, il faut que\n # l'attribut `coef_` soit une matrice ligne. De même,\n # l'attribut `intercept_` même si c'est un scalaire doit être\n # mis dans un tableau. Il faut également tenir compte de\n # l'option `fit_intercept`.\n self.coef_ = ...\n self.intercept_ = ...\n","sub_path":"td/TP10_Regression_logistique-enonce/src/logistic_regression.py","file_name":"logistic_regression.py","file_ext":"py","file_size_in_byte":2209,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"386370376","text":"from lxml import etree\n\nfrom bs4 import BeautifulSoup\n\nfrom polyglot.text import Text\n\nimport re\n\nimport pandas as pd\n\nimport googlemaps\n\nfrom geopy import distance as dis\n\nimport itertools\n\nfrom sklearn.feature_extraction.text import CountVectorizer\n\nimport requests\n\nimport pickle\n\npd.options.display.max_rows = 4000\n\nimport numpy as np\ndef calculate_distance(p1,p2):\n\n return dis.distance(p1,p2).km\ndef parse_response(return_json,query_name):\n\n return {\n\n \"query_name\":query_name,\n\n 'formatted_address':return_json['formatted_address'],\n\n \"lat\":return_json['geometry']['location']['lat'],\n\n \"lng\":return_json['geometry']['location']['lng'],\n\n }\ndef n_gram(string):\n\n vectorizer = CountVectorizer(ngram_range=(1, 100),token_pattern = r\"(?u)\\b\\w+\\b\")\n\n X = vectorizer.fit_transform([string])\n\n analyze = vectorizer.build_analyzer()\n\n return vectorizer.get_feature_names()\ndef query_from_geonames(candidate):\n\n resp=requests.get(\"https://www.geonames.org/search.html?q=\"+candidate+\"&country=GT\").text\n\n return \"records found for\" in resp or \"record found for\" in resp\ndef validate_place_name(string):\n\n n_grams=n_gram(string)\n\n return sum([query_from_geonames(i) for i in n_grams])\ndef walker(soup):\n\n result_list=[]\n\n if soup.name is not None:\n\n for child in soup.children:\n\n #process node\n\n #print(str(child.string))\n\n# if None != child.string:\n\n# print()\n\n# t=Text(str(child.extact()))\n\n# print(t.pos_tags)\n\n result_list.append(str(child.string))\n\n result_list+=walker(child)\n\n return result_list\nwith open('../data/NL_html','r',encoding='UTF-8') as f:\n\n soup=BeautifulSoup(f.read())\n\n for script in soup([\"script\", \"style\"]):\n\n script.decompose()\n\n #print(soup)\n\n candidate_list=list(set(walker(soup)))\nafter_filter_nl=[]\n\nname_candidate_nl=[]\n\nfor i in candidate_list:\n\n #print(i)\n\n print(re.match(r\"^(?=.*[A-Za-z])(?=.*,).*$\",i.replace('\\n',''),re.M))\n\n i=\" \".join(i.split())\n\n if re.match(r\"^(?=.*[A-Za-z])(?=.*,).*$\",i.replace('\\n',''),re.M) and len(i)<100:\n\n after_filter_nl+=[i.replace('\\n','')]\n\n elif re.match(r\"^(?=.*[A-Za-z]).*$\",i.replace('\\n',''),re.M) and len(i)<50 and len(i)>3:\n\n name_candidate_nl.append(i)\nafter_filter_nl\nwith open('../data/GT_html','r',encoding='UTF-8') as f:\n\n soup=BeautifulSoup(f.read())\n\n for script in soup([\"script\", \"style\"]):\n\n script.decompose()\n\n #print(soup)\n\n candidate_list_gt=list(set(walker(soup)))\nafter_filter_gt=[]\n\nname_candidate_gt=[]\n\nfor i in candidate_list_gt:\n\n #print(i)\n\n #print(re.match(r\"^(?=.*[A-Za-z])(?=.*,).*$\",i.replace('\\n',''),re.M))\n\n i=\" \".join(i.split())\n\n #print(i)\n\n if re.match(r\"^(?=.*[A-Za-z])(?=.*,).*$\",i.replace('\\n',''),re.M) and len(i)<100:\n\n #print(i)\n\n after_filter_gt+=[i.replace('\\n','')]\n\n elif re.match(r\"^(?=.*[A-Za-z]).*$\",i.replace('\\n',''),re.M) and len(i)<50 and len(i)>3:\n\n name_candidate_gt.append(i)\nlen([i for i in name_candidate_gt if 'Delegación' in i])\nclient=googlemaps.Client(\"AIzaSyBnB3duxMNxArGL7wu9nWp9aOtV7lKx1Ao\")\nclient.geocode('Delegación Tecún Umán',region='gt')\nclient.geocode('1 Avenida 4-38 Zona 1, Tecún Umán, San Marcos ',region='gt')\ndef query_geocode(name,region):\n\n response=client.geocode(name,region=region) \n\n if len(response)>0:\n\n return (name,response)\naddresses_list_gt_google=[query_geocode(i,region='gt') for i in after_filter_gt]\nname_list_gt_google=[query_geocode(i,region='gt') for i in name_candidate_gt]\nimport pickle\n\n\nwith open('../data/name_list_gt_google.pickle', 'wb') as f:\n\n # Pickle the 'data' dictionary using the highest protocol available.\n\n pickle.dump(name_list_gt_google, f, pickle.HIGHEST_PROTOCOL)\n\nwith open('../data/addresses_list_gt_google.pickle', 'wb') as f:\n\n # Pickle the 'data' dictionary using the highest protocol available.\n\n pickle.dump(addresses_list_gt_google, f, pickle.HIGHEST_PROTOCOL)\nname_list_gt_google=pickle.load(open('../data/name_list_gt_google.pickle','rb'))\n\naddresses_list_gt_google=pickle.load(open(\"../data/addresses_list_gt_google.pickle\",'rb'))\naddresses_list_gt=[i for i in addresses_list_gt_google if i and validate_place_name(i[0]) and not re.search(\"[\\U00010000-\\U0010ffff]\",i[0],flags=re.UNICODE)]\n\nname_list_gt=[i for i in name_list_gt_google if i and validate_place_name(i[0]) and not re.search(\"[\\U00010000-\\U0010ffff]\",i[0],flags=re.UNICODE) ]\nfor i in name_list_gt:\n\n print(i)\n[(i[0],len(i[1])) for i in addresses_list_gt]\nfrom sklearn.feature_extraction.text import TfidfVectorizer\n\nvectorizer = TfidfVectorizer(ngram_range=(1, 2))\n\nvectorizer.fit([name[0] for name in name_list_gt])\ndef plot(string):\n\n df=pd.DataFrame([vectorizer.get_feature_names(),vectorizer.transform([string]).todense()[0].tolist()[0]]).T.sort_values(1,ascending=False)\n\n df=df[df[1]==df[1].max()]\n\n df.columns=['topic','score']\n\n df['name']=string\n\n return df[0:1]\n\npd.concat(list(map(lambda x: plot(x),[name[0] for name in name_list_gt])))\nfrom fuzzywuzzy import fuzz\n\nimport collections\n\nimport math\n\n\n\ndef weight_name(name_a,name_b):\n\n df=pd.DataFrame([vectorizer.get_feature_names(),vectorizer.transform([name_b]).todense()[0].tolist()[0]]).T.sort_values(1,ascending=False)\n\n df=df[df[1]==df[1].max()]\n\n df.columns=['topic','score']\n\n #print(df['topic'].tolist())\n\n dup_ind=1/math.exp(sum([name_a.lower().count(i)*len(i.split(' ')) for i in df['topic'].tolist()]))\n\n similar_ind=1/(1+fuzz.ratio(name_a,name_b))\n\n print(dup_ind,similar_ind)\n\n return dup_ind*similar_ind\nmin_distance_list=[]\n\nfor addresses in addresses_list_gt:\n\n address_name=addresses[0]\n\n for names in name_list_gt:\n\n department_name=names[0]\n\n if len(names[1])>3:\n\n continue\n\n# if not validate_place_name(department_name):\n\n# continue\n\n #print(address_name,department_name)\n\n min_dis=999999\n\n #print(min_dis)\n\n for add_rep in addresses[1]:\n\n #print(add_rep)\n\n address_dict=parse_response(add_rep,address_name)\n\n for name_rep in names[1]:\n\n \n\n name_dict=parse_response(name_rep,department_name)\n\n print(address_dict,name_dict)\n\n dist=calculate_distance((address_dict['lat'],address_dict['lng']),(name_dict['lat'],name_dict['lng']))\n\n #print(dist)\n\n if dist0:\n\n condidates=[condidate['_source']['FULL_NAME_RO']for condidate in result['hits']['hits']]\n\n print(candidate)\n\n print(condidates)\n\n if len(condidates) >0:\n\n filtered_candidate_gt.append(candidate)\n\n except:\n\n pass\nfiltered_candidate_gt\nimport requests\n\nimport lxml\n\nfrom lxml import etree as et\ntext=requests.get(\"https://www.rodekruis.nl/wp-content/plugins/superstorefinder-wp/ssf-wp-xml.php\")\naddress_et=et.fromstring (text.text)\naddress_et.find(\"locator\")\naddress_et.tag\naddress_et\naddress_list_nl=[]\n\nfor child in address_et[5]:\n\n address_list_nl.append(child[1].text)\naddress_list_nl=list(set(address_list_nl))\nlen(address_list_nl)\ncount=0\n\nfor address in address_list_nl:\n\n address=' '.join(address.split())\n\n if sum([1 for i in after_filter_nl if address in i]):\n\n count+=1\n\n else:\n\n print(address)\ncount\nnl_se=pd.Series(after_filter_nl)\nnl_se.to_csv(\"../data/nl_se.csv\")\ngt_se=pd.Series(after_filter_gt)\ngt_se.to_csv(\"../data/gt_se.csv\")\nQI2qcmn0","sub_path":"collect_addresses_from_web/phases/extract_addresses/location_extraction.ipynb.py","file_name":"location_extraction.ipynb.py","file_ext":"py","file_size_in_byte":9198,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"289775184","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.win-amd64\\egg\\arcadeplus\\examples\\maze_depth_first.py\n# Compiled at: 2020-03-29 18:05:54\n# Size of source mod 2**32: 10929 bytes\n\"\"\"\nCreate a maze using a depth-first search maze generation algorithm.\nFor more information on this algorithm see:\nhttp://www.algosome.com/articles/maze-generation-depth-first.html\n...or search up some other examples.\n\nArtwork from http://kenney.nl\n\nIf Python and arcadeplus are installed, this example can be run from the command line with:\npython -m arcadeplus.examples.maze_depth_first\n\"\"\"\nimport random, arcadeplus, timeit, os\nNATIVE_SPRITE_SIZE = 128\nSPRITE_SCALING = 0.25\nSPRITE_SIZE = NATIVE_SPRITE_SIZE * SPRITE_SCALING\nSCREEN_WIDTH = 1000\nSCREEN_HEIGHT = 700\nSCREEN_TITLE = 'Maze Depth First Example'\nMOVEMENT_SPEED = 8\nTILE_EMPTY = 0\nTILE_CRATE = 1\nMAZE_HEIGHT = 51\nMAZE_WIDTH = 51\nMERGE_SPRITES = True\nVIEWPORT_MARGIN = 200\n\ndef _create_grid_with_cells(width, height):\n \"\"\" Create a grid with empty cells on odd row/column combinations. \"\"\"\n grid = []\n for row in range(height):\n grid.append([])\n for column in range(width):\n if column % 2 == 1 and row % 2 == 1:\n grid[row].append(TILE_EMPTY)\n elif column == 0 or row == 0 or column == width - 1 or row == height - 1:\n grid[row].append(TILE_CRATE)\n else:\n grid[row].append(TILE_CRATE)\n\n return grid\n\n\ndef make_maze_depth_first(maze_width, maze_height):\n maze = _create_grid_with_cells(maze_width, maze_height)\n w = (len(maze[0]) - 1) // 2\n h = (len(maze) - 1) // 2\n vis = [[0] * w + [1] for _ in range(h)] + [[1] * (w + 1)]\n\n def walk(x, y):\n vis[y][x] = 1\n d = [\n (\n x - 1, y), (x, y + 1), (x + 1, y), (x, y - 1)]\n random.shuffle(d)\n for xx, yy in d:\n if vis[yy][xx]:\n continue\n if xx == x:\n maze[(max(y, yy) * 2)][x * 2 + 1] = TILE_EMPTY\n if yy == y:\n maze[(y * 2 + 1)][max(x, xx) * 2] = TILE_EMPTY\n walk(xx, yy)\n\n walk(random.randrange(w), random.randrange(h))\n return maze\n\n\nclass MyGame(arcadeplus.Window):\n __doc__ = ' Main application class. '\n\n def __init__(self, width, height, title):\n super().__init__(width, height, title)\n file_path = os.path.dirname(os.path.abspath(__file__))\n os.chdir(file_path)\n self.player_list = None\n self.wall_list = None\n self.score = 0\n self.player_sprite = None\n self.physics_engine = None\n self.view_bottom = 0\n self.view_left = 0\n self.processing_time = 0\n self.draw_time = 0\n\n def setup(self):\n \"\"\" Set up the game and initialize the variables. \"\"\"\n self.player_list = arcadeplus.SpriteList()\n self.wall_list = arcadeplus.SpriteList()\n self.score = 0\n maze = make_maze_depth_first(MAZE_WIDTH, MAZE_HEIGHT)\n if not MERGE_SPRITES:\n for row in range(MAZE_HEIGHT):\n for column in range(MAZE_WIDTH):\n if maze[row][column] == 1:\n wall = arcadeplus.Sprite(':resources:images/tiles/grassCenter.png', SPRITE_SCALING)\n wall.center_x = column * SPRITE_SIZE + SPRITE_SIZE / 2\n wall.center_y = row * SPRITE_SIZE + SPRITE_SIZE / 2\n self.wall_list.append(wall)\n\n else:\n for row in range(MAZE_HEIGHT):\n column = 0\n while column < len(maze):\n while column < len(maze) and maze[row][column] == 0:\n column += 1\n\n start_column = column\n while column < len(maze) and maze[row][column] == 1:\n column += 1\n\n end_column = column - 1\n column_count = end_column - start_column + 1\n column_mid = (start_column + end_column) / 2\n wall = arcadeplus.Sprite(':resources:images/tiles/grassCenter.png', SPRITE_SCALING, repeat_count_x=column_count)\n wall.center_x = column_mid * SPRITE_SIZE + SPRITE_SIZE / 2\n wall.center_y = row * SPRITE_SIZE + SPRITE_SIZE / 2\n wall.width = SPRITE_SIZE * column_count\n self.wall_list.append(wall)\n\n self.player_sprite = arcadeplus.Sprite(':resources:images/animated_characters/female_person/femalePerson_idle.png', SPRITE_SCALING)\n self.player_list.append(self.player_sprite)\n placed = False\n while not placed:\n self.player_sprite.center_x = random.randrange(MAZE_WIDTH * SPRITE_SIZE)\n self.player_sprite.center_y = random.randrange(MAZE_HEIGHT * SPRITE_SIZE)\n walls_hit = arcadeplus.check_for_collision_with_list(self.player_sprite, self.wall_list)\n if len(walls_hit) == 0:\n placed = True\n\n self.physics_engine = arcadeplus.PhysicsEngineSimple(self.player_sprite, self.wall_list)\n arcadeplus.set_background_color(arcadeplus.color.AMAZON)\n self.view_left = 0\n self.view_bottom = 0\n print(f\"Total wall blocks: {len(self.wall_list)}\")\n\n def on_draw(self):\n \"\"\"\n Render the screen.\n \"\"\"\n arcadeplus.start_render()\n draw_start_time = timeit.default_timer()\n self.wall_list.draw()\n self.player_list.draw()\n sprite_count = len(self.wall_list)\n output = f\"Sprite Count: {sprite_count}\"\n arcadeplus.draw_text(output, self.view_left + 20, SCREEN_HEIGHT - 20 + self.view_bottom, arcadeplus.color.WHITE, 16)\n output = f\"Drawing time: {self.draw_time:.3f}\"\n arcadeplus.draw_text(output, self.view_left + 20, SCREEN_HEIGHT - 40 + self.view_bottom, arcadeplus.color.WHITE, 16)\n output = f\"Processing time: {self.processing_time:.3f}\"\n arcadeplus.draw_text(output, self.view_left + 20, SCREEN_HEIGHT - 60 + self.view_bottom, arcadeplus.color.WHITE, 16)\n self.draw_time = timeit.default_timer() - draw_start_time\n\n def on_key_press(self, key, modifiers):\n \"\"\"Called whenever a key is pressed. \"\"\"\n if key == arcadeplus.key.UP:\n self.player_sprite.change_y = MOVEMENT_SPEED\n else:\n if key == arcadeplus.key.DOWN:\n self.player_sprite.change_y = -MOVEMENT_SPEED\n else:\n if key == arcadeplus.key.LEFT:\n self.player_sprite.change_x = -MOVEMENT_SPEED\n else:\n if key == arcadeplus.key.RIGHT:\n self.player_sprite.change_x = MOVEMENT_SPEED\n\n def on_key_release(self, key, modifiers):\n \"\"\"Called when the user releases a key. \"\"\"\n if key == arcadeplus.key.UP or key == arcadeplus.key.DOWN:\n self.player_sprite.change_y = 0\n else:\n if key == arcadeplus.key.LEFT or key == arcadeplus.key.RIGHT:\n self.player_sprite.change_x = 0\n\n def on_update(self, delta_time):\n \"\"\" Movement and game logic \"\"\"\n start_time = timeit.default_timer()\n self.physics_engine.update()\n changed = False\n left_bndry = self.view_left + VIEWPORT_MARGIN\n if self.player_sprite.left < left_bndry:\n self.view_left -= left_bndry - self.player_sprite.left\n changed = True\n right_bndry = self.view_left + SCREEN_WIDTH - VIEWPORT_MARGIN\n if self.player_sprite.right > right_bndry:\n self.view_left += self.player_sprite.right - right_bndry\n changed = True\n top_bndry = self.view_bottom + SCREEN_HEIGHT - VIEWPORT_MARGIN\n if self.player_sprite.top > top_bndry:\n self.view_bottom += self.player_sprite.top - top_bndry\n changed = True\n bottom_bndry = self.view_bottom + VIEWPORT_MARGIN\n if self.player_sprite.bottom < bottom_bndry:\n self.view_bottom -= bottom_bndry - self.player_sprite.bottom\n changed = True\n if changed:\n arcadeplus.set_viewport(self.view_left, SCREEN_WIDTH + self.view_left, self.view_bottom, SCREEN_HEIGHT + self.view_bottom)\n self.processing_time = timeit.default_timer() - start_time\n\n\ndef main():\n \"\"\" Main method \"\"\"\n window = MyGame(SCREEN_WIDTH, SCREEN_HEIGHT, SCREEN_TITLE)\n window.setup()\n arcadeplus.run()\n\n\nif __name__ == '__main__':\n main()","sub_path":"pycfiles/arcadeplus-0.6.1-py3.7/maze_depth_first.cpython-37.py","file_name":"maze_depth_first.cpython-37.py","file_ext":"py","file_size_in_byte":8616,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"576966933","text":"from tkinter import *\n#from tkinter import messagebox\n#print(messagebox.showinfo(\"HI\",\"HI2\"))\n\nroot=Tk()\nmain=Frame(root)\nmain.grid()\n\none=BooleanVar()\ntwo=BooleanVar()\n\ndef toTextx():\n if one.get():\n ent1.delete(0,END)\n ent1.insert(0,\"You picked number 1\")\n if two.get():\n ent1.delete(0,END)\n ent1.insert(0,\"You picked number 2\")\n \nckb1=Checkbutton(main,\n text=\"Number 1\",\n variable=one,\n command=toTextx)\nckb1.grid()\n\nckb2=Checkbutton(main,\n text=\"Number 2\",\n variable=two,\n command=toTextx)\nckb2.grid()\n\nent1=Entry(main)\nent1.grid()\n\nroot.mainloop()\n\n","sub_path":"Python Pgms/New folder/Python/xChkBtn.pyw","file_name":"xChkBtn.pyw","file_ext":"pyw","file_size_in_byte":684,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"411812162","text":"from common import *\nfrom data import *\n\nDATA_DIR = '/root/share/project/kaggle/2019/chest/data'\n\n\nclass XrayDataset(Dataset):\n def __init__(self, split, csv, folder, mode, augment=None,):\n\n self.split = split\n self.csv = csv\n self.folder = folder\n self.mode = mode\n self.augment = augment\n\n self.df = pd.read_csv(DATA_DIR + '/%s' % csv)\n self.gb = self.df.groupby('ImageId')\n self.df['count'] = self.gb['ImageId'].transform('count')\n self.df.loc[self.df['EncodedPixels'] == '-1', 'count'] = 0\n\n self.dicom_file = get_dicom_file(DATA_DIR + '/' + folder)\n if split is None:\n uid = list(self.gb.groups.keys())\n uid.sort()\n self.uid = uid\n else:\n uid = list(np.load(DATA_DIR + '/split/%s' %\n split, allow_pickle=True))\n uid.sort()\n self.uid = uid\n\n # if 1: #\n # self.uid = self.uid[:1000]\n\n if self.mode == 'train':\n num_component = []\n for i in self.uid:\n df = self.gb.get_group(i)\n num_component.append(df['count'].values[0])\n self.num_component = np.array(num_component, np.int32)\n else:\n self.num_component = np.zeros(len(self.uid), np.int32)\n\n def __str__(self):\n if self.mode == 'train':\n\n string = ''\\\n + '\\tmode = %s\\n' % self.mode \\\n + '\\tsplit = %s\\n' % self.split \\\n + '\\tcsv = %s\\n' % self.csv \\\n + '\\tfolder = %s\\n' % self.folder \\\n + '\\tnum_component[n] = %d\\n' % (sum(self.num_component >= 1)) \\\n + '\\tnum_component[0] = %d\\n' % (sum(self.num_component == 0)) \\\n + '\\tlen = %d\\n' % len(self)\n\n if self.mode == 'test':\n string = ''\\\n + '\\tmode = %s\\n' % self.mode \\\n + '\\tsplit = %s\\n' % self.split \\\n + '\\tcsv = %s\\n' % self.csv \\\n + '\\tfolder = %s\\n' % self.folder \\\n + '\\tnum_component[n] = ?\\n' \\\n + '\\tnum_component[0] = ?\\n' \\\n + '\\tlen = %d\\n' % len(self)\n\n return string\n\n def __len__(self):\n return len(self.uid)\n\n def __getitem__(self, index):\n # print(index)\n i = self.uid[index]\n\n data = pydicom.read_file(self.dicom_file[i])\n image = data.pixel_array\n\n if self.mode == 'train':\n df = self.gb.get_group(i)\n component, num_component = gb_to_component(df)\n\n if self.mode == 'test':\n component = np.zeros((1024, 1024), np.float32)\n num_component = 0\n\n infor = Struct(\n image_id=i,\n index=index,\n #df = df,\n #is_copy = True,\n )\n\n if self.augment is None:\n return image, component, num_component, infor\n else:\n return self.augment(image, component, num_component, infor)\n\n##############################################################\n\n\n# data augmentation\ndef do_resize(image, mask, fx, fy):\n image = cv2.resize(image, dsize=None, fx=fx, fy=fy)\n mask = cv2.resize(mask, dsize=None, fx=fx, fy=fy)\n return image, mask\n\n\ndef do_center_crop(image, mask, w, h):\n height, width = image.shape\n x = (width - w)//2\n y = (height-h)//2\n\n image = image[y:y+h, x:x+w]\n mask = mask[y:y+h, x:x+w]\n return image, mask\n\n\ndef do_random_crop(image, mask, w, h):\n height, width = image.shape\n x = np.random.choice(width - w)\n y = np.random.choice(height-h)\n\n image = image[y:y+h, x:x+w]\n mask = mask[y:y+h, x:x+w]\n return image, mask\n\n\ndef do_flip(image, mask):\n image = cv2.flip(image, 1)\n mask = cv2.flip(mask, 1)\n return image, mask\n\n\ndef random_scale_rotate(image, mask):\n dangle = np.random.uniform(-5, 5)\n dscale = np.random.uniform(-0.05, 0.05, 2)\n dshift = np.random.uniform(-0.05, 0.05, 2)\n\n cos = np.cos(dangle/180*PI)\n sin = np.sin(dangle/180*PI)\n sx, sy = 1 + dscale\n tx, ty = dshift\n cx, cy = 0.5, 0.5\n\n src = np.array([[0, 0], [1, 0], [1, 1], [0, 1]], np.float32)\n src = src-dshift\n x = ((src-[cx, cy])*[cos, -sin]).sum(1)*sx + tx + cx\n y = ((src-[cx, cy])*[sin, cos]).sum(1)*sy + ty + cy\n src = np.column_stack([x, y])\n dst = np.array([[0, 0], [1, 0], [1, 1], [0, 1]])\n\n if 1:\n h, w = image.shape\n s = src*[w, h]\n d = dst*[w, h]\n s = s.astype(np.float32)\n d = d.astype(np.float32)\n transform = cv2.getPerspectiveTransform(s, d)\n image = cv2.warpPerspective(image, transform, (w, h),\n flags=cv2.INTER_LINEAR, borderMode=cv2.BORDER_CONSTANT, borderValue=(0, 0, 0))\n\n if 1:\n h, w = mask.shape\n s = src*[w, h]\n d = dst*[w, h]\n s = s.astype(np.float32)\n d = d.astype(np.float32)\n transform = cv2.getPerspectiveTransform(s, d)\n mask = cv2.warpPerspective(mask, transform, (w, h),\n flags=cv2.INTER_LINEAR, borderMode=cv2.BORDER_CONSTANT, borderValue=0)\n\n return image, mask\n\n\n##############################################################\n\ndef null_augment(image, component, num_component, infor):\n mask = component_to_mask(component)\n return image, mask, num_component, infor\n\n\ndef augment(image, component, num_component, infor):\n mask = component_to_mask(component)\n image, mask = random_scale_rotate(image, mask)\n return image, mask, num_component, infor\n\n\ndef null_collate(batch):\n batch_size = len(batch)\n\n input = []\n truth = []\n num_component = []\n infor = []\n for b in range(batch_size):\n input.append(batch[b][0])\n truth.append(batch[b][1])\n num_component.append(batch[b][2])\n infor.append(batch[b][3])\n\n input = np.stack(input).astype(np.float32)\n input = input/255\n truth = np.stack(truth).astype(np.float32)\n truth = (truth > 0.5).astype(np.float32)\n\n input = torch.from_numpy(input).unsqueeze(1).float()\n truth = torch.from_numpy(truth).unsqueeze(1).float()\n\n return input, truth, num_component, infor\n\n\nclass BalanceClassSampler(Sampler):\n\n def __init__(self, dataset, length=None):\n self.dataset = dataset\n\n if length is None:\n length = len(self.dataset)\n\n self.length = length\n\n def __iter__(self):\n pos_index = np.where(self.dataset.num_component >= 1)[0]\n neg_index = np.where(self.dataset.num_component == 0)[0]\n\n half = self.length//2 + 1\n pos = np.random.choice(pos_index, half, replace=True)\n neg = np.random.choice(neg_index, half, replace=True)\n\n l = np.stack([pos, neg]).T\n l = l.reshape(-1)\n l = l[:self.length]\n return iter(l)\n\n def __len__(self):\n return self.length\n\n##############################################################\n\n\ndef run_check_train_dataset():\n\n dataset = XrayDataset(\n mode='train',\n csv='train-rle.csv',\n folder='dicom/dicom-images-train',\n split='train_10075.npy',\n #split = 'valid_600.npy',\n #split = None,\n augment=null_augment, # None #\n )\n print(dataset)\n # exit(0)\n\n for n in range(0, len(dataset)):\n i = n # i = np.random.choice(len(dataset))\n\n image, mask, num_component, infor = dataset[i]\n if num_component == 0:\n continue\n image = cv2.cvtColor(image, cv2.COLOR_GRAY2BGR)\n\n contour = image.copy()\n contour = draw_contour_overlay(contour, mask, 2)\n mask = draw_mask_overlay(mask)\n\n # ----\n print('%05d : %s' % (i, infor.image_id))\n image_show('image', image, 0.5)\n image_show('contour', contour, 0.5)\n image_show('mask', mask, 1)\n cv2.waitKey(0)\n\n\ndef run_check_data_loader():\n\n dataset = XrayDataset(\n mode='train',\n csv='train-rle.csv',\n folder='dicom/dicom-images-train',\n split=None,\n augment=null_augment, # None #\n )\n print(dataset)\n loader = DataLoader(\n dataset,\n sampler=BalanceClassSampler(dataset),\n #sampler = SequentialSampler(dataset),\n #sampler = RandomSampler(dataset),\n batch_size=32,\n drop_last=False,\n num_workers=0,\n pin_memory=True,\n collate_fn=null_collate\n )\n\n for t, (input, truth, num_component, infor) in enumerate(loader):\n\n print('----t=%d---' % t)\n print('')\n print(infor)\n print(input.shape)\n print(truth.shape)\n print(num_component)\n print('')\n\n if 1:\n batch_size = len(infor)\n input = input.data.cpu().numpy()\n truth = truth.data.cpu().numpy()\n\n for b in range(batch_size):\n image = input[b, 0]\n mask = truth[b, 0]\n\n print(num_component[b])\n image_show_norm('mask', mask, resize=0.25)\n image_show_norm('image', image, resize=0.25)\n cv2.waitKey(0)\n\n\ndef run_check_augment():\n\n dataset = XrayDataset(\n mode='train',\n csv='train-rle.csv',\n folder='dicom/dicom-images-train',\n split=None,\n augment=augment, # null_augment, #None #augment, #\n )\n print(dataset)\n\n for t in range(len(dataset)):\n image, mask, num_component, infor = dataset[t]\n\n print('----t=%d---' % t)\n print('')\n print(infor)\n print(image.shape)\n print(mask.shape)\n print(num_component)\n print('')\n\n if num_component == 0:\n continue\n\n if 1:\n for i in range(100):\n overlay = draw_input_overlay(image)\n overlay = draw_contour_overlay(overlay, mask, thickness=5)\n\n image, mask, num_component, infor = dataset[t]\n image_show_norm('mask', mask, resize=0.25)\n image_show('image', image, resize=0.25)\n image_show('overlay', overlay, resize=0.25)\n cv2.waitKey(0)\n\n\n# main #################################################################\nif __name__ == '__main__':\n print('%s: calling main function ... ' % os.path.basename(__file__))\n\n # run_check_train_dataset()\n # run_check_data_loader()\n\n run_check_augment()\n\n print('\\nsucess!')\n","sub_path":"notebooks/drive-download-20190731T104457Z-001/20190711/dataset.py","file_name":"dataset.py","file_ext":"py","file_size_in_byte":10462,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"181242014","text":"# Final Project Code\nimport time\nimport pandas as pd\nimport numpy as np\n\nCITY_DATA = { 'chicago': 'chicago.csv',\n 'new york city': 'new_york_city.csv',\n 'washington': 'washington.csv' }\n\ncities = [\"Chicago\", \"New York City\", \"Washington\"]\nmonths = [\"January\", \"February\", \"March\", \"April\", \"May\", \"June\", \"All\"]\ndays = [\"Monday\", \"Tuesday\", \"Wednesday\", \"Thursday\", \"Friday\", \"Saturday\", \"Sunday\", \"All\"]\n\ndef get_filters():\n \"\"\"\n Asks user to specify a city, month, and day to analyze.\n\n Returns:\n (str) city - name of the city to analyze\n (str) month - name of the month to filter by, or \"all\" to apply no month filter\n (str) day - name of the day of week to filter by, or \"all\" to apply no day filter\n \"\"\"\n print('Hello! Let\\'s explore some US bikeshare data!')\n city = input('Which city, Chicago, New York City, or Washington, would you like to look at?\\n').title()\n while city not in cities:\n city = input('Error: You did not enter a valid city. Please select one of the following: Chicago, New York City, Washington, or all for no filter.\\n').title()\n\n month = input('What month would you like to filter by? January, February, March, April, May, June or if you do not want to filter by the month type all.\\n').title()\n while month not in months:\n month = input('Error: You did not enter a valid month. Please correctly type in the name of the month or all for no filter.\\n').title()\n\n day = input('What day of the week would you like to filter by? If you do not want to filter by the day type all.\\n').title()\n while day not in days:\n day = input('Error: You did not enter a valid day. Please correctly type in the day of the week or all for no filter.\\n').title()\n\n print('-'*40)\n return city, month, day\n\n\ndef load_data(city, month, day):\n \"\"\"\n Loads data for the specified city and filters by month and day if applicable.\n\n Args:\n (str) city - name of the city to analyze\n (str) month - name of the month to filter by, or \"all\" to apply no month filter\n (str) day - name of the day of week to filter by, or \"all\" to apply no day filter\n Returns:\n df - Pandas DataFrame containing city data filtered by month and day\n \"\"\"\n df = pd.DataFrame(pd.read_csv(CITY_DATA[city.lower()]))\n\n df['Start Time'] = pd.to_datetime(df['Start Time'])\n df['Month'] = df['Start Time'].dt.month\n df['Day of the Week'] = df['Start Time'].dt.weekday_name\n\n if month != 'All':\n month = months.index(month) + 1\n df = df[df['Month'] == month]\n\n if day != 'All':\n df= df[df['Day of the Week'] == day]\n\n return df\n\n\ndef time_stats(df):\n \"\"\"Displays statistics on the most frequent times of travel.\"\"\"\n\n print('\\nCalculating The Most Frequent Times of Travel...\\n')\n start_time = time.time()\n\n # display the most common month\n common_month = df[\"Month\"].mode()[0]\n print('The most common month is {} with a count of {}.'.format(months[common_month - 1], df[df['Month'] == common_month]['Month'].count()))\n\n # display the most common day of week\n common_day = df[\"Day of the Week\"].mode()[0]\n print('The most common day is {} with a count of {}.'.format(common_day, df[df['Day of the Week'] == common_day]['Day of the Week'].count()))\n\n # display the most common start hour\n common_hour = df[\"Start Time\"].dt.hour.mode()[0]\n print('The most common start hour is {} with a count of {}.'.format(common_hour, df[df[\"Start Time\"].dt.hour == common_hour]['Start Time'].count()))\n\n print(\"\\nThis took %s seconds.\" % (time.time() - start_time))\n print('-'*40)\n\n\ndef station_stats(df):\n \"\"\"Displays statistics on the most popular stations and trip.\"\"\"\n\n print('\\nCalculating The Most Popular Stations and Trip...\\n')\n start_time = time.time()\n\n # display most commonly used start station\n common_start = df['Start Station'].mode()[0]\n print('The most common start station is {} with a count of {}.'.format(common_start, df[df['Start Station'] == common_start]['Start Station'].count()))\n\n # display most commonly used end station\n common_end = df['End Station'].mode()[0]\n print('The most common end station is {} with a count of {}.'.format(common_end, df[df['End Station'] == common_end]['End Station'].count()))\n\n # display most frequent combination of start station and end station trip\n common_start_end = (df['Start Station'] + ' - ' + df['End Station']).mode()[0]\n starting_st = common_start_end.split(' - ')[0]\n ending_st = common_start_end.split(' - ')[1]\n common_start_end_count = df[(df['Start Station'] == starting_st) & (df['End Station'] == ending_st)]['Start Station'].count()\n print('The most frequent combination of start station and end station is {} with a count of {}'.format(common_start_end, common_start_end_count))\n\n print(\"\\nThis took %s seconds.\" % (time.time() - start_time))\n print('-'*40)\n\n\ndef trip_duration_stats(df):\n \"\"\"Displays statistics on the total and mean trip duration.\"\"\"\n\n print('\\nCalculating Trip Duration...\\n')\n start_time = time.time()\n\n # display total travel time\n print('The total amount of travel time is {}.'.format(df['Trip Duration'].sum(axis = 0)))\n\n # display mean travel time\n print('The average amount of travel time is {}.'.format(df['Trip Duration'].mean()))\n\n print(\"\\nThis took %s seconds.\" % (time.time() - start_time))\n print('-'*40)\n\n\ndef user_stats(df):\n \"\"\"Displays statistics on bikeshare users.\"\"\"\n\n print('\\nCalculating User Stats...\\n')\n start_time = time.time()\n\n # Display counts of user types\n user_type_count = df['User Type'].value_counts()\n for i in range(len(user_type_count)):\n print(\"The amount of {}(s) is {}.\".format(user_type_count.index.values[i], user_type_count[i]))\n print()\n\n # Display counts of gender\n gender_count = df['Gender'].value_counts()\n for i in range(len(gender_count)):\n print(\"The amount of {}s is {}.\".format(gender_count.index.values[i], gender_count[i]))\n\n # Display earliest, most recent, and most common year of birth\n print('\\nThe earliest birth year is {}.'.format(int(df['Birth Year'].min())))\n print('The most recent birth year is {}.'.format(int(df['Birth Year'].max())))\n print('The most common birth year is {}.'.format(int(df['Birth Year'].mode()[0])))\n\n print(\"\\nThis took %s seconds.\" % (time.time() - start_time))\n print('-'*40)\n\n\ndef raw_data(df):\n \"\"\"Displays 5 lines of raw data at a time until user stops\"\"\"\n multiple_of_5 = range(5, len(df.index) + 1, 5)\n counter = 0\n while True:\n for i in df.index:\n counter += 1\n print('\\nRow {}'.format(i))\n print(\"\\nStart Time: {}\".format(df[\"Start Time\"][i]))\n print(\"End Time: {}\".format(df[\"End Time\"][i]))\n print(\"Trip Duration: {}\".format(df[\"Trip Duration\"][i]))\n print(\"Start Station: {}\".format(df[\"Start Station\"][i]))\n print(\"End Station: {}\".format(df[\"End Station\"][i]))\n print(\"User Type: {}\".format(df[\"User Type\"][i]))\n print(\"Gender: {}\".format(df[\"Gender\"][i]))\n print(\"Birth Year: {}\".format(df[\"Birth Year\"][i]))\n if counter in multiple_of_5:\n next_page = input(\"\\n\\nWould you like to look at the next 5 rows of data? Enter yes or no.\\n\")\n if next_page.lower() != \"yes\":\n break\n break\n\n\ndef main():\n while True:\n city, month, day = get_filters()\n df = load_data(city, month, day)\n\n time_stats(df)\n station_stats(df)\n trip_duration_stats(df)\n user_stats(df)\n\n if_raw_data = input('\\nWould you like to look at the raw data? Enter yes or no.\\n')\n if if_raw_data.lower() == 'yes':\n raw_data(df)\n\n restart = input('\\nWould you like to restart? Enter yes or no.\\n')\n if restart.lower() != 'yes':\n break\n\n\nif __name__ == \"__main__\":\n\tmain()\n","sub_path":"bikeshare.py","file_name":"bikeshare.py","file_ext":"py","file_size_in_byte":8052,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"604848886","text":"# MIT License\n#\n# Copyright (C) The Adversarial Robustness Toolbox (ART) Authors 2020\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n# documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the\n# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit\n# persons to whom the Software is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the\n# Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n# WARRANTIES OF MERCHANTABILITY, 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 LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\nfrom __future__ import absolute_import, division, print_function, unicode_literals\n\nimport pytest\nimport logging\nimport numpy as np\n\nfrom art.defences.trainer import AdversarialTrainerFBFPyTorch\n\n\n@pytest.fixture()\ndef get_adv_trainer(framework, get_image_classifier_list):\n def _get_adv_trainer(**kwargs):\n\n if framework == \"keras\":\n trainer = None\n if framework == \"tensorflow\":\n trainer = None\n if framework == \"pytorch\":\n classifier = get_image_classifier_list()[0][0]\n trainer = AdversarialTrainerFBFPyTorch(classifier)\n if framework == \"scikitlearn\":\n trainer = None\n\n return trainer\n\n return _get_adv_trainer\n\n\n@pytest.fixture()\ndef fix_get_mnist_subset(get_mnist_dataset):\n (x_train_mnist, y_train_mnist), (x_test_mnist, y_test_mnist) = get_mnist_dataset\n n_train = 100\n n_test = 100\n yield (x_train_mnist[:n_train], y_train_mnist[:n_train], x_test_mnist[:n_test], y_test_mnist[:n_test])\n\n\ndef test_adversarial_trainer_FBF_Pytorch_fit_and_predict(get_adv_trainer, fix_get_mnist_subset):\n (x_train_mnist, y_train_mnist, x_test_mnist, y_test_mnist) = fix_get_mnist_subset\n x_test_mnist_original = x_test_mnist.copy()\n\n trainer = get_adv_trainer()\n if trainer is None:\n logging.warning(\"Couldn't perform this test because no gan is defined for this framework configuration\")\n return\n\n predictions = np.argmax(trainer.predict(x_test_mnist), axis=1)\n accuracy = np.sum(predictions == np.argmax(y_test_mnist, axis=1)) / x_test_mnist.shape[0]\n\n trainer.fit(x_train_mnist, y_train_mnist, nb_epochs=5)\n predictions_new = np.argmax(trainer.predict(x_test_mnist), axis=1)\n accuracy_new = np.sum(predictions_new == np.argmax(y_test_mnist, axis=1)) / x_test_mnist.shape[0]\n\n np.testing.assert_array_almost_equal(\n float(np.mean(x_test_mnist_original - x_test_mnist)), 0.0, decimal=0.0001,\n )\n\n np.testing.assert_array_almost_equal(accuracy, 0.32, decimal=0.001)\n np.testing.assert_array_almost_equal(accuracy_new, 0.14, decimal=0.001)\n\n\nif __name__ == \"__main__\":\n pytest.cmdline.main(\"-q -s {} --mlFramework=pytorch --durations=0\".format(__file__).split(\" \"))\n","sub_path":"toolbox/tests/defences/test_adversarial_trainer_FBF.py","file_name":"test_adversarial_trainer_FBF.py","file_ext":"py","file_size_in_byte":3363,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"308697627","text":"from django.db import models\nfrom django.contrib.auth.models import User\nfrom django.db.models.signals import post_save\nfrom django.dispatch import receiver\nfrom jsonfield import JSONField\nfrom django.contrib.postgres.fields import ArrayField\nimport json\n\nclass Player(models.Model):\n user = models.OneToOneField(User, primary_key=True)\n games = models.IntegerField(default=0)\n wins = models.IntegerField(default=0)\n losses = models.IntegerField(default=0)\n\n def __str__(self):\n return self.user.username\n\n def incr_wins(self):\n self.wins += 1\n\n def incr_losses(self):\n self.losses += 1\n\n def incr_games(self):\n self.games += 1\n\n def decr_games(self):\n self.games -= 1\n\n\nclass Game(models.Model):\n playerA = models.ForeignKey(User, related_name=\"a_set\", blank=True, null=True)\n playerB = models.ForeignKey(User, related_name=\"b_set\", blank=True, null=True)\n done = models.IntegerField(default=0)\n configA = JSONField(default={})\n configB = JSONField(default={})\n moves = models.CharField(max_length=1500, default=\"[]\")\n creationTime = models.DateTimeField(auto_now_add=True)\n lasteditTime = models.DateTimeField(auto_now=True)\n\n def __str__(self):\n game_str = 'Game '+str(self.id)\n return game_str\n\n def owner(self, player):\n if (player == self.playerA) or (player == self.playerB):\n return True\n return False\n\n def is_done(self):\n \"\"\"Check if game is over and update game state and player stats accordingly \"\"\"\n posA = [pos for sublist in self.configA.values() for pos in sublist]\n posB = [pos for sublist in self.configB.values() for pos in sublist]\n movesA = json.loads(self.moves)[::2]\n movesB = json.loads(self.moves)[1::2]\n remainsA = [pos for pos in posB if pos not in movesA]\n remainsB = [pos for pos in posA if pos not in movesB]\n\n if (len(remainsA) == 0) or (len(remainsB) == 0):\n self.done = 1\n if len(remainsA) == 0:\n player_winner = Player.objects.filter(user=self.playerA).first()\n player_loser = Player.objects.filter(user=self.playerB).first()\n else:\n player_winner = Player.objects.filter(user=self.playerB).first()\n player_loser = Player.objects.filter(user=self.playerA).first()\n player_winner.incr_wins()\n player_winner.save()\n player_loser.incr_losses()\n player_loser.save()\n\n@receiver(post_save, sender=User)\ndef create_player(sender, instance, created, **kwargs):\n \"\"\"Create a matching profile whenever a user object is created.\"\"\"\n if created:\n profile, new = Player.objects.get_or_create(user=instance)\n","sub_path":"battleshipapp/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":2857,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"421541402","text":"from typing import Any, Callable\nfrom copy import deepcopy\n\nimport numpy as np\nimport pytest\nfrom slicedimage import Tile, TileSet\n\nfrom starfish.constants import Indices, Coordinates\nfrom starfish.image import ImageStack\nfrom starfish.io import Stack\nfrom starfish.util.synthesize import synthesize\n\n\n# TODO ambrosejcarr: all fixtures should emit a stack and a codebook\n@pytest.fixture(scope='session')\ndef merfish_stack() -> Stack:\n \"\"\"retrieve MERFISH testing data from cloudfront and expose it at the module level\n\n Notes\n -----\n Because download takes time, this fixture runs once per session -- that is, the download is run only once.\n\n Returns\n -------\n Stack :\n starfish.io.Stack object containing MERFISH data\n \"\"\"\n s = Stack()\n s.read('https://s3.amazonaws.com/czi.starfish.data.public/20180607/test/MERFISH/fov_001/experiment_new.json')\n return deepcopy(s)\n\n\ndef default_tile_data_provider(hyb: int, ch: int, z: int, height: int, width: int) -> np.ndarray:\n \"\"\"\n Returns a tile of just ones for any given hyb/ch/z.\n \"\"\"\n return np.ones((height, width))\n\n\ndef default_tile_extras_provider(hyb: int, ch: int, z: int) -> Any:\n \"\"\"\n Returns None for extras for any given hyb/ch/z.\n \"\"\"\n return None\n\n\nDEFAULT_NUM_HYB = 2\nDEFAULT_NUM_CH = 3\nDEFAULT_NUM_Z = 4\nDEFAULT_HEIGHT = 30\nDEFAULT_WIDTH = 20\n\n\ndef synthetic_stack(\n num_hyb: int=DEFAULT_NUM_HYB,\n num_ch: int=DEFAULT_NUM_CH,\n num_z: int=DEFAULT_NUM_Z,\n tile_height: int=DEFAULT_HEIGHT,\n tile_width: int=DEFAULT_WIDTH,\n tile_data_provider: Callable[[int, int, int, int, int], np.ndarray]=default_tile_data_provider,\n tile_extras_provider: Callable[[int, int, int], Any]=default_tile_extras_provider\n) -> ImageStack:\n \"\"\"generate a synthetic ImageStack\n\n Returns\n -------\n ImageStack :\n imagestack containing a tensor of (2, 3, 4, 30, 20) whose values are all 1.\n\n \"\"\"\n img = TileSet(\n {Coordinates.X, Coordinates.Y, Indices.HYB, Indices.CH, Indices.Z},\n {\n Indices.HYB: num_hyb,\n Indices.CH: num_ch,\n Indices.Z: num_z,\n },\n default_tile_shape=(tile_height, tile_width),\n )\n for hyb in range(num_hyb):\n for ch in range(num_ch):\n for z in range(num_z):\n tile = Tile(\n {\n Coordinates.X: (0.0, 0.001),\n Coordinates.Y: (0.0, 0.001),\n Coordinates.Z: (0.0, 0.001),\n },\n {\n Indices.HYB: hyb,\n Indices.CH: ch,\n Indices.Z: z,\n },\n extras=tile_extras_provider(hyb, ch, z),\n )\n tile.numpy_array = tile_data_provider(hyb, ch, z, tile_height, tile_width)\n\n img.add_tile(tile)\n\n stack = ImageStack(img)\n return stack\n\n\ndef labeled_synthetic_dataset() -> Stack:\n stack, codebook = synthesize()\n return stack\n","sub_path":"starfish/test/dataset_fixtures.py","file_name":"dataset_fixtures.py","file_ext":"py","file_size_in_byte":3081,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"120193113","text":"# class name(인자):\n# property\n# def function(self,인자):\n# name.property\n# print()\n# class userinterface() 정의\n\nimport random\n\nclass game():\n intro_msg = \"가위 바위 보 게임 !! 안녕하세요\"\n input_msg = \"1.가위 2. 바위 3. 보 종료(q,Q)\"\n choice_list = ('가위','바위','보')\n confirm_msg = \"{user}를 내셨군요, 저는 {com}을 냈습니다.\"\n user = None\n com = None\n calc_result = None\n\n def start(self):\n while True:\n self.intro()\n self.user = self.get_user_input()\n self.com = random.randint(1,3)\n self.calc_result()\n self.print_confirm_msg()\n\n #게임의 흐름. 밑과 똑같지?\n\n # print_intro()\n # user = get_user_input()\n # com = random.randint(1, 3)\n # result = calc_result(user, com)\n # print_result(result)\n def intro(self):\n print(self.intro_msg)\n\n def get_user_input(self): #바로 밑에 라인 refactored.\n while True:\n input_str = input(self.input_msg)\n if input_str in ['1', '2', '3', 'q', 'Q']:\n if input_str in ['q', 'Q']:\n print(\"안녕히가세요~\")\n exit()\n # break 해버리면 바깥으로 바깥while문만 끝나지.\n else:\n return int(input_str) #여기 refactored 체크\n break # return user로 가기 위해서 break 함수 처리 하기 전과 다른점!\n else:\n print(\"잘못골랐습니다 다시 입력해주세요\")\n return user\n\n def calc_result(self):\n if self.user == self.com:\n self.result = \"draw\"\n elif self.user % 3 + 1 == self.com:\n self.result = \"lose\"\n elif self.com % 3 + 1 == self.user:\n self.result = \"win\"\n #return self.result\n def print_result(self):\n if self.result == \"win\":\n print(\"이겼습니다\")\n elif self.result == \"lose\":\n print(\"졌습니다\")\n else:\n print(\"비겼습니다\")\n def print_confirm_msg(self):\n print(self.confirm_msg.format(user = self.user, com = self.com))\n\n\nrock = game()\nrock.start()","sub_path":"dev/rock/rock_class_version.py","file_name":"rock_class_version.py","file_ext":"py","file_size_in_byte":2278,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"461967417","text":"#pylint: disable=E0401\n\"\"\"\n Basic operations for HP Norton database\n\"\"\"\n\n\nimport logging\nimport sqlite3\nfrom sqlalchemy import create_engine\nfrom sqlalchemy.orm import sessionmaker\nfrom sqlalchemy import Table\nfrom sqlalchemy import MetaData\nfrom sqlalchemy import func\nfrom sqlalchemy import exc\nimport src.db_model as db\n\nlogging.basicConfig(level=logging.INFO)\nLOGGER = logging.getLogger(__name__)\nLOGGER.info(\"HP Norton Database\")\n\nENGINE = create_engine(\"sqlite:///HPNorton.db\")\nDB_SESSION = sessionmaker(bind=ENGINE)\nSESSION = DB_SESSION()\nMETADATA = MetaData(bind=ENGINE)\nCUSTOMERS = Table(\"Customer\", METADATA, autoload=True)\n\n\ndef add_customer(\n customer_id,\n name,\n lastname,\n home_address,\n phone_number,\n email_address,\n status,\n credit_limit,\n):\n \"\"\"Adds a new customer to the HPNorton database\n\n Arguments:\n customer_id {string} -- Unique identifier for customer\n name {string} -- First name of customer\n lastname {string} -- Last name of customer\n home_address {string} -- Home address of customer\n phone_number {string} -- Phone number of customer\n email_address {string} -- Email address of customer\n status {string} -- Active / Inactive status of customer\n credit_limit {int} -- Credit limit of customer\n\n Raises:\n IntegrityError -- Raised when trying to insert a duplicate primary key.\n \"\"\"\n try:\n new_customer = db.Customer(\n customer_id=customer_id,\n name=name,\n last_name=lastname,\n home_address=home_address,\n phone_number=phone_number,\n email_address=email_address,\n status=status.lower(),\n credit_limit=credit_limit,\n )\n SESSION.add(new_customer)\n SESSION.commit()\n LOGGER.info(\"Adding record for %s\", customer_id)\n except sqlite3.IntegrityError as ex:\n LOGGER.info(ex)\n raise exc.IntegrityError\n\n\ndef search_customer(customer_id):\n \"\"\"Search for specified customer and returns their data.\n\n Arguments:\n customer_id {string} -- Unique identifier for customer.\n\n Returns:\n dictionary -- Object containing name, lase_name, email, phone_number\n for specified customer_id. Returns empty dict\n if customer not found.\n \"\"\"\n cust = {}\n select_st = CUSTOMERS.select().where(CUSTOMERS.c.customer_id == customer_id)\n query = SESSION.execute(select_st)\n for item in query:\n cust[\"customer_id\"] = item.customer_id\n cust[\"name\"] = item.name\n cust[\"lastname\"] = item.last_name\n cust[\"email\"] = item.email_address\n cust[\"phone_number\"] = item.phone_number\n cust[\"home_address\"] = item.home_address\n cust[\"status\"] = item.status\n cust[\"credit_limit\"] = item.credit_limit\n\n return cust\n\n\ndef delete_customer(customer_id):\n \"\"\"Deletes the specified customer from database.\n\n Arguments:\n customer_id {string} -- Unique identifier for customer.\n\n Returns:\n bool -- Ture if successful, False if not.\n \"\"\"\n if search_customer(customer_id) == {}:\n return False\n query = CUSTOMERS.delete().where(CUSTOMERS.c.customer_id == customer_id)\n query.execute()\n if search_customer(customer_id) == {}:\n return True\n raise Exception(\"Deletion failed\")\n\n\ndef list_active_customers():\n \"\"\"Returns an integer specifying the number of active customers\n\n Returns:\n integer -- Number of active customers\n \"\"\"\n\n return (\n SESSION.query(CUSTOMERS)\n .filter(CUSTOMERS.c.status == \"active\")\n .statement.with_only_columns([func.count()])\n .scalar()\n )\n\n\ndef update_customer_credit(customer_id, credit_limit):\n \"\"\"Update the credit limit of the specified customer.\n\n Arguments:\n customer_id {string} -- Unique identifier for customer\n credit_limit {float} -- New credit limit for customer\n\n Raises:\n ValueError -- Raises ValueError if customer_id not in database.\n\n Returns:\n bool -- Ture if successful, False if not.\n \"\"\"\n if search_customer(customer_id) == {}:\n raise ValueError\n\n SESSION.query(db.Customer).filter(\n db.Customer.customer_id == customer_id\n ).update({\"credit_limit\": credit_limit})\n return SESSION.commit()\n","sub_path":"students/douglas_klos/lesson03/assignment/sqlalchemy/src/basic_operations.py","file_name":"basic_operations.py","file_ext":"py","file_size_in_byte":4407,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"548081153","text":"from PyQt5.QtWidgets import QWidget, QLabel, QApplication, QDialog, QScrollArea, QFormLayout, QComboBox\nfrom PyQt5.QtWidgets import QHBoxLayout, QVBoxLayout,QLineEdit, QPushButton, QGroupBox, QTabWidget\nfrom PyQt5.QtCore import Qt\nfrom typeCheck import questionList, answerList\nfrom logic import Logic\nfrom personality import find, bestpartner, info, getTextfile\nimport sys\n\n\nclass StartView(QWidget):\n def __init__(self, parent = None):\n super().__init__(parent)\n self.initUI()\n\n\n def initUI(self):\n self.setWindowTitle(\"Find my key ability!\")\n self.resize(800, 600)\n self.title = QLabel(\"남들이 보는 \\n 나의 \\\"핵심 능력\\\"\")\n self.name = QLabel(\"Name : \")\n self.title.setStyleSheet('font-size : 30pt;')\n self.title.setAlignment(Qt.AlignCenter)\n self.nameEdit = QLineEdit()\n self.nameEdit.setFixedHeight(30)\n self.startButton = QPushButton(\"START!\")\n self.startButton.clicked.connect(self.startButtonClicked)\n\n top = QHBoxLayout()\n top.addWidget(self.title)\n middle = QHBoxLayout()\n middle.addWidget(self.name)\n middle.addWidget(self.nameEdit)\n bottom = QHBoxLayout()\n bottom.addStretch(1)\n bottom.addWidget(self.startButton)\n bottom.addStretch(1)\n mainLayout = QVBoxLayout()\n mainLayout.addLayout(top)\n mainLayout.addLayout(middle)\n mainLayout.addLayout(bottom)\n self.setLayout(mainLayout)\n def startButtonClicked(self):\n manual.setName(self.nameEdit.text())\n self.mainView = MainView()\n self.mainView.exec()\n self.show()\n\n\nclass MainView(QDialog):\n def __init__(self):\n super().__init__()\n self.resize(1500, 1000)\n formLayout = QFormLayout()\n scroll = QScrollArea()\n self.setWindowTitle('Question')\n self.submitButton = QPushButton('Submit')\n self.submitButton.clicked.connect(self.submitButtonClicked)\n\n self.number = ['one','two','three','four','five','six','seven','eigth','nine','ten','eleven','twelve']\n groupBox = QGroupBox(\"MBTI Test Page\")\n\n for i in range(len(questionList)):\n unit = QHBoxLayout()\n self.question = QLabel(str(i + 1) + ') ' + questionList[i])\n self.question.setAlignment(Qt.AlignCenter)\n self.question.setStyleSheet('font-size : 20pt;')\n unit.addWidget(self.question)\n self.number[i] = QComboBox()\n self.number[i].addItems([answerList[i][0], answerList[i][1]])\n self.number[i].setFixedSize(650,100)\n self.number[i].setStyleSheet('font-size : 15pt;')\n unit.addWidget(self.number[i])\n\n formLayout.addRow(unit)\n groupBox.setLayout(formLayout)\n scroll.setWidget(groupBox)\n formLayout.addWidget(self.submitButton)\n groupBox.setLayout(formLayout)\n scroll.setWidget(groupBox)\n scroll.setWidgetResizable(True)\n layout = QVBoxLayout(self)\n layout.addWidget(scroll)\n self.show()\n\n\n def submitButtonClicked(self):\n sender = self.sender()\n self.submitButton.setDisabled(True)\n selected = []\n for i in range(len(questionList)):\n selected += [self.number[i].currentText()]\n\n manual.storeTestResult(selected)\n\n self.resultView = ResultView()\n self.resultView.exec()\n self.show()\n\nclass ResultView(QDialog):\n def __init__(self):\n super().__init__()\n self.initUI()\n self.setFixedSize(1500, 600)\n\n def initUI(self):\n self.setWindowTitle('Personality Test Result')\n\n self.layout = QVBoxLayout()\n self.tabs = QTabWidget()\n self.myBestAbility = QWidget()\n self.bestPartner = QWidget()\n\n self.tabs.addTab(self.myBestAbility, 'MY Best Ability')\n self.tabs.addTab(self.bestPartner, 'Best Partner')\n\n abilityLayout = QHBoxLayout()\n characterLayout = QHBoxLayout()\n detailLayout = QHBoxLayout()\n vbox = QVBoxLayout()\n self.index = find(manual.getMyMBTI())\n self.result = QLabel(manual.getName() + '님의 핵심능력은 ' + info[self.index][\"ability\"] + '입니다.')\n self.result.setAlignment(Qt.AlignCenter)\n self.result.setStyleSheet('font-size : 30pt;')\n self.character = QLabel(info[self.index][\"character\"])\n self.character.setAlignment(Qt.AlignCenter)\n self.character.setStyleSheet('font-size : 30pt;')\n self.detail = QLabel(self.openDB(self.index))\n self.detail.setAlignment(Qt.AlignCenter)\n abilityLayout.addWidget(self.result)\n characterLayout.addWidget(self.character)\n detailLayout.addWidget(self.detail)\n vbox.addLayout(abilityLayout)\n vbox.addLayout(characterLayout)\n vbox.addLayout(detailLayout)\n self.myBestAbility.setLayout(vbox)\n\n explanationLayout = QHBoxLayout()\n bestpartnerLayout = QHBoxLayout()\n partnerdetailLayout = QHBoxLayout()\n box = QVBoxLayout()\n self.explanation = QLabel('내 능력의 소울메이트는 ')\n self.explanation.setAlignment(Qt.AlignCenter)\n self.explanation.setStyleSheet('font-size : 30pt;')\n self.partnerindex = find(bestpartner[manual.getMyMBTI()])\n self.partner = QLabel(info[self.partnerindex][\"character\"])\n self.partner.setAlignment(Qt.AlignCenter)\n self.partner.setStyleSheet('font-size : 30pt;')\n self.partnerdetail = QLabel(self.openDB(self.partnerindex))\n self.partnerdetail.setAlignment(Qt.AlignCenter)\n explanationLayout.addWidget(self.explanation)\n bestpartnerLayout.addWidget(self.partner)\n partnerdetailLayout.addWidget(self.partnerdetail)\n box.addLayout(explanationLayout)\n box.addLayout(bestpartnerLayout)\n box.addLayout(partnerdetailLayout)\n self.bestPartner.setLayout(box)\n\n self.layout.addWidget(self.tabs)\n self.setLayout(self.layout)\n\n def openDB(self, idx):\n dbfilename = getTextfile(idx)\n dbfilepath = '/home/jungmin/Git/class-03-kmujm/AD-Project/detail/' + dbfilename\n dbfilepath = dbfilepath.replace(\" \",\"\")\n fH = open(dbfilepath,'r')\n lines = fH.readlines()\n fH.close()\n self.lines = lines[0].replace(\"\\n\", \"\")\n return self.lines\n\nif __name__ == \"__main__\":\n result = ''\n manual = Logic()\n app = QApplication(sys.argv)\n startView = StartView()\n startView.show()\n sys.exit(app.exec_())\n","sub_path":"AD-Project/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":6574,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"297694383","text":"###### Objectives ######\n\n# The total number of votes cast\n# A complete list of candidates who received votes\n# The percentage of votes each candidate won\n# The total number of votes each candidate won\n# The winner of the election based on popular vote.\n\n###### Output ######\n\n# Election Results\n# -------------------------\n# Total Votes: 3521001\n# -------------------------\n# Khan: 63.000% (2218231)\n# Correy: 20.000% (704200)\n# Li: 14.000% (492940)\n# O'Tooley: 3.000% (105630)\n# -------------------------\n# Winner: Khan\n# -------------------------\n\n# Import Packages\nimport os\nimport csv\n# Set Path\ncsv_path = os.path.join(\"Resources\",\"election_data.csv\")\n#input_file = \"Resources/budget_data.csv\"\n\n#Define List\nvoter_id_list = []\ncounty_list = []\ncandidate_list = []\nunique_candidates_list = []\ncandidates_total_list = []\ntotal_per_candidate=[]\ncandidate_percent_list=[]\n\n\n#Define Variables:\n\nnumber_of_votes = 0\ncandidates_total=0\n\n# Open the csv file for reading\nwith open(csv_path,\"r\") as csvfile:\n csvreader = csv.reader(csvfile, delimiter=\",\")\n csvheader = next(csvreader)\n\n#Loop through rows of files \n for row in csvreader:\n number_of_votes +=1\n voter_id_list.append(int(row[0]))\n county_list.append(row[1])\n candidate_list.append(row[2])\n unique_candidates_list = set(candidate_list)\n unique_candidates_list=list(unique_candidates_list)\n\n #print(unique_candidates_list)\n #print(number_of_votes)\n for name in unique_candidates_list:\n #candidate_list.count(name) \n candidates_total=candidate_list.count(name)\n candidates_total_list.append(candidates_total)\n data=sorted(zip(unique_candidates_list,candidates_total_list),reverse=True,key=lambda x:x[1])\n \n#Winner of election based on popular vote\n\nwinner_vote=max(candidates_total_list)\nmax_index=candidates_total_list.index(winner_vote)\nwinner=unique_candidates_list[max_index]\n\n# Print Analysis\n\nprint(str(\"Election Results\"))\nprint(str(\"-------------------------\"))\nprint(str(\"Total Votes: \")+ str(number_of_votes) )\nprint(str(\"------------------------\"))\nfor x in data:\n print(x[0] + \": \" + str(format((x[1]/number_of_votes)*100, \".3f\")) + \"% \" + \"(\"+str(x[1])+\")\") \nprint(str(\"-------------------------\")) \nprint(\"Winner: \" + str(winner))\nprint(str(\"-------------------------\"))\n\n\n#Open text file(analysis.txt) for writing\nf = open(\"analysis.txt\", \"w\")\n\n# Write data to text file\nf.write(str(\"Election Results\"))\nf.write(str(\"\\n\") + str(\"-------------------------\"))\nf.write(str(\"\\n\") + str(\"Total Votes: \")+ str(number_of_votes) )\nf.write(str(\"\\n\") + str(\"------------------------\\n\"))\nfor x in data:\n f.write(x[0] + \": \" + str(format((x[1]/number_of_votes)*100, \".3f\")) + \"% \" + \"(\"+str(x[1])+\")\"+ str(\"\\n\")) \nf.write(str(\"-------------------------\\n\")) \nf.write(\"Winner: \" + str(winner))\nf.write(str(\"\\n\") + str(\"-------------------------\"))\n\n# Close text file\nf.close()","sub_path":"PyPoll/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2939,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"399345056","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed Jul 31 14:31:38 2019\n\n@author: Narink\n\"\"\"\n\nimport matplotlib.pyplot as plt\nimport numpy as np\n\nx=np.linspace(0,2*np.pi,400)\ny=np.sin(x**2)\ny2=np.cos(x)\n\nfig,axs=plt.subplots(2,2)\nfig.suptitle('Super Title')\n\naxs[0,0].plot(x,y,color='red')\naxs[0,1].plot(x,-y,color='green')\naxs[1,0].plot(x,y2,color='blue')\naxs[1,1].plot(x,-y2,color='cyan')\n\naxs[1,1].set_xlabel('x label')\n#plt.plot(x,y)","sub_path":"PreML/c_plot.py","file_name":"c_plot.py","file_ext":"py","file_size_in_byte":429,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"178791324","text":"from datetime import datetime\nimport cProfile\nimport functools\nimport json\nimport matplotlib.pyplot as plt\nimport numpy as np\nfrom pathCheckers.batchChecker import BatchChecker\nfrom pathCheckers.iPathChecker import IPathChecker\nfrom pathCheckers.optimalSetPathChecker import OptimalSetPathChecker\nfrom pathCheckers.polynomialPathChecker import PolynomialPathChecker\nfrom pathCheckers.naiveChecker import NaiveChecker\nfrom pathCheckers.twoFlipChecker import TwoFlipPathChecker\nfrom randomGraphGenerator import generateGraph, generateAcyclicGraph\nimport traceback\nfrom typing import List\n\nNUM_TRIES = 10\nDO_ACYCLIC = False\nOUTFILE = ''\n\ndensityStep = 0.5\nsizeStep = 1\nmaxSize = 250\n\n# densities = [i*densityStep for i in range(1, int(1.0/densityStep))] \ndensities = [0.5]\nsizes = [i*sizeStep for i in range(1, int(maxSize/sizeStep))]\n# sizes = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]\n\nevaluationList = [(density, size) for size in sizes for density in densities]\n\n# First three colors look good in black and white.\ncolors = [\"black\", \"purple\", \"orange\", \"blue\", \"green\", \"red\"]\n\ncheckers : List[IPathChecker] = [\n PolynomialPathChecker(),\n OptimalSetPathChecker()\n # NaiveChecker(),\n # TwoFlipPathChecker(),\n # BatchChecker()\n]\n\nclass attemptInfo:\n \"\"\"Stores information for a given density, size\"\"\"\n\n def __init__(self):\n self.times = []\n self.sizes = []\n \n def addTime(self,time):\n self.times += [time]\n \n def addSize(self, sze):\n self.sizes += [sze]\n \n def avgList(self, lst):\n self.avg = functools.reduce(lambda acc, n: acc + n, lst, 0)/len(lst)\n return self.avg\n \n def getAvgTime(self, median=False): \n if median:\n return self.getMedianTime()\n return self.avgList(self.times)\n\n def getAvgSizes(self):\n return self.avgList(self.sizes)\n \n def getTimes(self):\n return self.times\n\n def getMedianTime(self):\n copy = self.times\n copy.sort()\n if len(copy)%2 == 1:\n self.median = copy[int(len(copy)/2)+1]\n else:\n floor = int(len(copy)/2)\n self.median = (copy[floor] + copy[floor+1])/2\n return self.median\n\n def getSD(self):\n mean = sum(self.times) / len(self.times) \n variance = sum([((x - mean) ** 2) for x in self.times]) / len(self.times) \n standardDeviation = variance ** 0.5\n return standardDeviation\n\nclass runDetails:\n \"\"\"Stores details of this evaluation run.\"\"\"\n \n def __init__(self):\n self.size = -1\n self.density = -1\n self.checkerName = \"not specified\"\n self.numberOfTries = NUM_TRIES\n self.graphs = []\n \ndef generateGraphs(size, density, count=NUM_TRIES, acyclic=False):\n \"\"\"Generate a list of graphs with the specifications\"\"\"\n if acyclic:\n return [generateAcyclicGraph(density, size) for i in range(count)]\n \n return [generateGraph(density, size) for i in range(count)]\n\ndef getEvaluateFunction(checker: IPathChecker, numTries: int, acyclic=False):\n \"\"\"Evaluate function factory\"\"\"\n # Need to change this if. BatchChecker evaluate should take in only acyclic graphs.\n if isinstance(checker, BatchChecker):\n def evaluate(density, size, graphs=[]):\n if len(graphs)==0:\n graphs = generateGraphs(size, density, numTries, acyclic=True)\n info = attemptInfo()\n for attempt in range(numTries):\n inp = graphs[attempt]\n checker.setGraph(inp.graph)\n paths = checker.getPathsToCheck()\n info.addSize(len(paths))\n info.addTime(checker.getComputeTime())\n return info\n return evaluate\n def evaluate(density, size, graphs=[]):\n info = attemptInfo()\n if len(graphs)==0:\n graphs = generateGraphs(size, density, numTries, acyclic=acyclic)\n for attempt in range(numTries):\n inp = graphs[attempt]\n checker.setGraph(inp.graph)\n checker.setEdge(inp.newEdgeSource, inp.newEdgeSink)\n paths = checker.getPathsToCheck()\n info.addSize(len(paths))\n info.addTime(checker.getComputeTime())\n return info\n return evaluate\n\ndef plot3d(checkerName, results):\n \"\"\"Plot mesh for density, size and time.\"\"\"\n plt.clf()\n X, Y = np.meshgrid(densities, sizes)\n Z = [[results[(x, y)].getAvgTime() for x in densities] for y in sizes]\n\n fig = plt.figure()\n ax = plt.axes(projection='3d')\n ax.contour3D(X, Y, Z, 50, zdir='z')\n ax.set_xlabel('Density')\n ax.set_ylabel('Size')\n ax.set_zlabel('time')\n\n # plt.show()\n fig.savefig(\"results/result3d{}{}.pdf\".format(checkerName, datetime.utcnow()))\n plt.clf()\n\ndef plotTimeVsSize(checkerName, results, densities, scatterPoints=False,\nerrorBars=False, median=False):\n plt.clf()\n handles = []\n fig,(ax1)=plt.subplots(1,1)\n\n X = sizes\n for i in range(len(densities)):\n density = densities[i]\n try:\n Y = [results[(density, size)].getAvgTime(median) for size in sizes]\n if errorBars:\n yerr = [results[(density, size)].getSD() for size in sizes]\n ax1.errorbar(X, Y, yerr=yerr, label=\"density {}\".format(density),\n color=colors[i])\n else:\n ax1.plot(X, Y, label=\"density {}\".format(density), color=colors[i])\n if scatterPoints:\n for x in sizes:\n result = results[(density, x)]\n points = result.getTimes()\n # ax1.plot([x for point in points], points, '.', color=colors[i]) \n ax1.plot([x for point in points], points, '.', color=\"grey\") \n except:\n print(\"Exception while plotting for density {}\".format(density))\n print(traceback.print_stack())\n handles, labels = ax1.get_legend_handles_labels()\n ax1.legend(handles, labels, loc='upper left',numpoints=1)\n plt.xlabel('Number of Nodes')\n plt.ylabel('Execution Time (seconds)')\n plt.savefig(\"results/timeVsSize_{}_{}{}.pdf\".format(NUM_TRIES, checkerName, datetime.utcnow()))\n plt.clf()\n\ndef plotTimeVsSizeForChecker(checkerNames, results, density, scatterPoints=False,\nerrorBars=False):\n plt.clf()\n handles = []\n\n X = sizes\n for checkerName in checkerNames:\n try:\n Y = []\n yerr = []\n for size in sizes:\n result = results[checkerName][(density, size)]\n Y += [result.getAvgTime()]\n yerr += [result.getSD()]\n if (errorBars):\n handles += plt.errorbar(X, Y, yerr=yerr, label=checkerName)\n else:\n handles += plt.plot(X, Y, label=checkerName) \n except:\n print(\"Error for {}\".format(checkerName))\n print(traceback.print_stack())\n plt.legend(handles=handles)\n plt.xlabel('Number of Nodes')\n plt.ylabel('Execution Time (seconds)')\n if scatterPoints:\n for x in X:\n points = result.getTimes()\n plt.plot([x for point in points], points, '.')\n if errorBars:\n #TODO plot standard deviation.\n pass\n plt.savefig(\"results/timeVsSizeForChecker_{}_{}.pdf\".format(NUM_TRIES, datetime.utcnow()))\n plt.clf()\n\ndef plot(checkerName, results):\n # plot3d(checkerName, results)\n # Modify densities to plot only a subset of those computed.\n plotTimeVsSize(checkerName, results, densities, True, True)\n # plotTimeVsSize(checkerName, results, densities, False, False)\n\ndef dumpResult(results: dict, runDetails: runDetails):\n \"\"\"Write results to file.\"\"\"\n resultStringDict = {\n \"{}_{}\".format(k[0], k[1]) : v.__dict__ for k, v in results.items()\n }\n with open('results/data{}.json'.format(getFileEndString()), 'w') as outfile:\n obj = {runDetails.checkerName : resultStringDict}\n json.dump(obj, outfile)\n\ndef getFileEndString():\n return \"_{}_{}\".format(NUM_TRIES, datetime.utcnow())\n\ndef main():\n graphs = { (density, size) : generateGraphs(size, density, acyclic=DO_ACYCLIC) for\n density in densities for size in sizes }\n for checker in checkers:\n evaluateForChecker(checker, graphs)\n\ndef evaluateForChecker(checker, graphs):\n evaluate = getEvaluateFunction(checker, NUM_TRIES)\n # dictionary from (density, size) to attemptInfo\n results = { (density, size) : evaluate(density, size, graphs = graphs[(density, size)]) for \n density in densities for size in sizes }\n details = runDetails()\n details.checkerName = checker.__class__.__name__\n plot(checker.__class__.__name__, results)\n dumpResult(results, details)\n\ndef profileBatchChecker():\n \"\"\"Profile the batch checker!\"\"\"\n checker = BatchChecker()\n graphs = { (density, size) : generateGraphs(size, density, acyclic=True) for\n density in densities for size in sizes }\n evaluateForChecker(checker, graphs) \n\nif __name__==\"__main__\":\n main()\n # pr = cProfile.Profile()\n # pr.enable()\n # profileBatchChecker()\n # pr.disable()\n # pr.print_stats(sort='cumtime')","sub_path":"implementation/evaluator4_scatter.py","file_name":"evaluator4_scatter.py","file_ext":"py","file_size_in_byte":9186,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"437100866","text":"#!/usr/bin/env python\n# -*- coding=utf-8 -*-\n__author__ = \"Powen Ko, www.powenko.com\"\n\"\"\"\nMac 的使用者 如果出現 SSL Certificate Error\n請執行以下的程式,HTTPS 就能工作\n/Applications/python 3.6/Install Certificates.command\n\n====第一題========\n設定一個變數\nsna=\"中壢火車站\"\nprint 對應的資料\n\n====第2題========\n透過 sys.argv[1]\n設定sna 的文字\nsna=sys.argv[1]\n找出對應的資料\n\n====第3題========\n透過AIML 呼叫 11-UbikeData\n\n====第4題========\n透過AIML 呼叫 11-UbikeData 並帶入對應的sna\n\n \npython 11-UbikeData.py 健行\npython 11-UbikeData.py 圖書館\n\"\"\"\n\nimport json\nimport sys \ntry:\n import urllib2 as httplib # 2.x\nexcept Exception:\n import urllib.request as httplib # 3.x\n\nimport ssl\n\nsna=\"中壢火車站\"\nif len(sys.argv)>1:\n sna=sys.argv[1]\n \n\nfrom datetime import datetime\ncontext = ssl._create_unverified_context()\nurl=\"https://data.tycg.gov.tw/opendata/datalist/datasetMeta/download?id=5ca2bfc7-9ace-4719-88ae-4034b9a5a55c&rid=a1b4714b-3b75-4ff8-a8f2-cc377e4eaa0f\"\nreq=httplib.Request(url)\ntry:\n reponse = httplib.urlopen(req, context=context)\n if reponse.code==200:\n contents = reponse.read() #.decode(\"UTF-8\")\n #print(contents)\n data = json.loads(contents)\n if(len(data)>1): # 確認是否有資料\n now = datetime.now() # 現在時間\n current_time = now.strftime(\"%Y%m%d%H%M%S\") # 印出時間的格式\n #print(\"現在時間 =\", current_time)\n with open('c:\\\\桃園自行車'+str(current_time)+'.json', 'w') as f: # 處存\n json.dump(data, f)\n\n t1=data[\"retVal\"]\n for t2 in t1:\n t_sna=t1[t2][\"sna\"]\n # print(t_sna, sna,t2)\n if t_sna.find(sna)>=0:\n print(\"位置:\",t1[t2][\"sna\"],\" tot:\",t1[t2][\"tot\"],\" sbi:\",t1[t2][\"sbi\"])\nexcept: # 處理網路連線異常\n print(\"error\")\n\n","sub_path":"0408 客服機器人/1-綜合練習(LINE+AIML+HTTP)_未完成/參考資料/AIML/11-UbikeData.py","file_name":"11-UbikeData.py","file_ext":"py","file_size_in_byte":2036,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"582544911","text":"from baselines.common.vec_env.subproc_vec_env import SubprocVecEnv\nfrom baselines.common.vec_env.dummy_vec_env import DummyVecEnv\nfrom WrapPytorch import WrapPytorch\nfrom Wrappers import make_env_a2c_atari\nfrom tensorboardX import SummaryWriter\nimport os\nimport torch.optim as optim\nimport torch.nn.functional as F\nimport torch.nn as nn\nimport torch\nimport gym\nimport numpy as np\nimport os.path as osp\n\n\nclass Config(object):\n num_agents = 16\n rollout = 5\n GAMMA = 0.99\n LR = 7e-4\n entropy_loss_weight = 0.01\n value_loss_weight = 0.5\n MAX_FRAMES = int(1e7 / num_agents / rollout)\n TARGET_NET_UPDATE_FREQ = 1000\n EXP_REPLAY_SIZE = 10000\n BATCH_SIZE = 32\n\n LEARN_START = 100\n UPDATE_FREQ = 1\n device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n\n epsilon_start = 1.0\n epsilon_final = 0.01\n epsilon_decay = 30000\n epsilon_by_frame = lambda frame_idx: Config.epsilon_final + (\n Config.epsilon_start - Config.epsilon_final)*math.exp(-1. * frame_idx/Config.epsilon_decay)\n\n\n\nclass ActorCritic(nn.Module):\n def __init__(self, input_shape, num_actions):\n super(ActorCritic, self).__init__()\n\n def init_(m): return self.layer_init(m, nn.init.orthogonal_,lambda x: nn.init.constant_(x, 0),nn.init.calculate_gain('relu'))\n\n self.conv1 = init_(\n nn.Conv2d(input_shape[0], 32, kernel_size=8, stride=4))\n self.conv2 = init_(nn.Conv2d(32, 64, kernel_size=4, stride=2))\n self.conv3 = init_(nn.Conv2d(64, 32, kernel_size=3, stride=1))\n self.fc1 = init_(nn.Linear(self.feature_size(input_shape), 512))\n\n def init_(m): return self.layer_init(m, nn.init.orthogonal_,lambda x: nn.init.constant_(x, 0))\n\n self.critic_linear = init_(nn.Linear(512, 1))\n\n def init_(m): return self.layer_init(m, nn.init.orthogonal_, lambda x: nn.init.constant_(x, 0), gain=0.01)\n\n self.actor_linear = init_(nn.Linear(512, num_actions))\n\n self.train()\n\n def forward(self, inputs):\n x = F.relu(self.conv1(inputs/255.0))\n x = F.relu(self.conv2(x))\n x = F.relu(self.conv3(x))\n x = x.view(x.size(0), -1)\n\n x = F.relu(self.fc1(x))\n\n value = self.critic_linear(x)\n logits = self.actor_linear(x)\n\n return logits, value\n\n def feature_size(self, input_shape):\n return self.conv3(self.conv2(self.conv1(torch.zeros(1, *input_shape)))).view(1, -1).size(1)\n\n def layer_init(self, module, weight_init, bias_init, gain=1):\n weight_init(module.weight.data, gain=gain)\n bias_init(module.bias.data)\n return module\n\n\nclass RolloutStorage(object):\n def __init__(self, num_steps, num_processes, obs_shape, action_space, device):\n self.observations = torch.zeros(\n num_steps + 1, num_processes, *obs_shape).to(device)\n self.rewards = torch.zeros(num_steps, num_processes, 1).to(device)\n self.value_preds = torch.zeros(\n num_steps + 1, num_processes, 1).to(device)\n self.returns = torch.zeros(num_steps + 1, num_processes, 1).to(device)\n self.action_log_probs = torch.zeros(\n num_steps, num_processes, 1).to(device)\n self.actions = torch.zeros(\n num_steps, num_processes, 1).to(device, torch.long)\n self.masks = torch.ones(num_steps + 1, num_processes, 1).to(device)\n\n self.num_steps = num_steps\n self.step = 0\n\n def insert(self, current_obs, action, action_log_prob, value_pred, reward, mask):\n self.observations[self.step + 1].copy_(current_obs)\n self.actions[self.step].copy_(action)\n self.action_log_probs[self.step].copy_(action_log_prob)\n self.value_preds[self.step].copy_(value_pred)\n self.rewards[self.step].copy_(reward)\n self.masks[self.step + 1].copy_(mask)\n\n self.step = (self.step + 1) % self.num_steps\n\n def after_update(self):\n self.observations[0].copy_(self.observations[-1])\n self.masks[0].copy_(self.masks[-1])\n\n def compute_returns(self, next_value, gamma):\n self.returns[-1] = next_value\n for step in reversed(range(self.rewards.size(0))):\n self.returns[step] = self.returns[step + 1] * \\\n gamma * self.masks[step + 1] + self.rewards[step]\n\n\nclass Model(object):\n def __init__(self, env=None, config=None, log_dir='/tmp/gym'):\n super(Model, self).__init__()\n self.device = config.device\n\n self.gamma = config.GAMMA\n self.lr = config.LR\n self.target_net_update_freq = config.TARGET_NET_UPDATE_FREQ\n self.learn_start = config.LEARN_START\n self.sigma_init = 0.5\n self.num_agents = config.num_agents\n self.value_loss_weight = 0.5\n self.entropy_loss_weight = 0.001\n self.rollout = config.rollout\n self.grad_norm_max = 0.5\n\n self.num_feats = env.observation_space.shape\n self.num_feats = (self.num_feats[0] * 4, *self.num_feats[1:])\n self.num_actions = env.action_space.n\n self.env = env\n\n self.declare_networks()\n\n self.optimizer = optim.RMSprop(\n self.model.parameters(), lr=self.lr, alpha=0.99, eps=1e-5)\n\n #move to correct device\n self.model = self.model.to(self.device)\n\n self.model.train()\n\n self.rollouts = RolloutStorage(self.rollout, self.num_agents,\n self.num_feats, self.env.action_space, self.device)\n\n self.value_losses = []\n self.entropy_losses = []\n self.policy_losses = []\n\n def declare_networks(self):\n self.model = ActorCritic(self.num_feats, self.num_actions)\n\n def get_action(self, s, deterministic=False):\n logits, values = self.model(s)\n dist = torch.distributions.Categorical(logits=logits)\n\n if deterministic:\n actions = dist.probs.argmax(dim=1, keepdim=True)\n else:\n actions = dist.sample().view(-1, 1)\n\n log_probs = F.log_softmax(logits, dim=1)\n action_log_probs = log_probs.gather(1, actions)\n\n return values, actions, action_log_probs\n\n def evaluate_actions(self, s, actions):\n logits, values = self.model(s)\n\n dist = torch.distributions.Categorical(logits=logits)\n\n log_probs = F.log_softmax(logits, dim=1)\n action_log_probs = log_probs.gather(1, actions)\n\n dist_entropy = dist.entropy().mean()\n\n return values, action_log_probs, dist_entropy\n\n def get_values(self, s):\n _, values = self.model(s)\n\n return values\n\n def compute_loss(self, rollouts):\n obs_shape = rollouts.observations.size()[2:]\n action_shape = rollouts.actions.size()[-1]\n num_steps, num_processes, _ = rollouts.rewards.size()\n\n values, action_log_probs, dist_entropy = self.evaluate_actions(\n rollouts.observations[:-1].view(-1, *obs_shape),\n rollouts.actions.view(-1, 1))\n\n values = values.view(num_steps, num_processes, 1)\n action_log_probs = action_log_probs.view(num_steps, num_processes, 1)\n\n advantages = rollouts.returns[:-1] - values\n value_loss = advantages.pow(2).mean()\n\n action_loss = -(advantages.detach() * action_log_probs).mean()\n\n loss = action_loss + self.value_loss_weight * \\\n value_loss - self.entropy_loss_weight * dist_entropy\n\n return loss, action_loss, value_loss, dist_entropy\n\n def update(self, rollout):\n loss, action_loss, value_loss, dist_entropy = self.compute_loss(\n rollout)\n\n self.optimizer.zero_grad()\n loss.backward()\n torch.nn.utils.clip_grad_norm_(\n self.model.parameters(), self.grad_norm_max)\n self.optimizer.step()\n\n return value_loss.item(), action_loss.item(), dist_entropy.item()\n\n def load(self, model_path):\n self.model.load(torch.load(osp.join(model_path, \"model\")))\n self.optimizer.load(torch.load(osp.join(model_path, \"optim\")))\n\n def save(self, model_path):\n torch.save(self.model, osp.join(model_path, \"model\"))\n torch.save(self.optimizer, osp.join(model_path, \"optim\"))\n\n\nif __name__ == '__main__':\n log_dir = \"./A2C/1\"\n if not osp.exists(log_dir):\n os.makedirs(log_dir)\n env_id = \"PongNoFrameskip-v0\"\n config = Config()\n envs = [make_env_a2c_atari(env_id,1,i,log_dir) for i in range(config.num_agents)]\n envs = SubprocVecEnv(envs) if config.num_agents > 1 else DummyVecEnv(envs)\n obs_shape = envs.observation_space.shape\n obs_shape = (obs_shape[0] * 4, *obs_shape[1:])\n\n model = Model(env=envs, config=config)\n\n current_obs = torch.zeros(config.num_agents, *obs_shape,\n device=config.device, dtype=torch.float)\n\n def update_current_obs(obs):\n shape_dim0 = envs.observation_space.shape[0]\n obs = torch.from_numpy(obs.astype(np.float32)).to(config.device)\n current_obs[:, :-shape_dim0] = current_obs[:, shape_dim0:]\n current_obs[:, -shape_dim0:] = obs\n\n obs = envs.reset()\n update_current_obs(obs)\n\n model.rollouts.observations[0].copy_(current_obs)\n\n episode_rewards = np.zeros(config.num_agents, dtype=np.float)\n final_rewards = np.zeros(config.num_agents, dtype=np.float)\n\n print_step = 1\n print_threshold = 10\n\n for frame_idx in range(1, config.MAX_FRAMES+1):\n for step in range(config.rollout):\n with torch.no_grad():\n values, actions, action_log_prob = model.get_action(\n model.rollouts.observations[step])\n cpu_actions = actions.view(-1).cpu().numpy()\n obs, reward, done, _ = envs.step(cpu_actions)\n\n episode_rewards += reward\n masks = 1. - done.astype(np.float32)\n final_rewards *= masks\n final_rewards += (1. - masks) * episode_rewards\n episode_rewards *= masks\n\n rewards = torch.from_numpy(reward.astype(\n np.float32)).view(-1, 1).to(config.device)\n masks = torch.from_numpy(masks).to(config.device).view(-1, 1)\n\n current_obs *= masks.view(-1, 1, 1, 1)\n update_current_obs(obs)\n\n model.rollouts.insert(\n current_obs, actions.view(-1, 1), action_log_prob, values, rewards, masks)\n\n with torch.no_grad():\n next_value = model.get_values(model.rollouts.observations[-1])\n\n model.rollouts.compute_returns(next_value, config.GAMMA)\n\n value_loss, action_loss, dist_entropy = model.update(model.rollouts)\n\n model.rollouts.after_update()\n\n if frame_idx % 100 == 0:\n total_num_steps = (frame_idx + 1) * \\\n config.num_agents * config.rollout\n print(\"Updates {}, Num Timesteps {}, \\nMean/Median Reward {:.1f}/{:.1f}, Min/Max Reward {:.1f}/{:.1f},\\nEntropy {:.5f}, Value Loss {:.5f}, Policy Loss {:.5f}\".\n format(frame_idx, total_num_steps,\n np.mean(final_rewards),\n np.median(final_rewards),\n np.min(final_rewards),\n np.max(final_rewards), dist_entropy,\n value_loss, action_loss))\n\n model.save()\n envs.close()\n","sub_path":"src/A2C.py","file_name":"A2C.py","file_ext":"py","file_size_in_byte":11253,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"534024840","text":"import freedan\nfrom freedan import AdGroup, Keyword, ExtendedTextAd\n\n\nCAMPAIGN_ID = \"INSERT_ID_HERE\"\n\n\ndef add_adgroup_using_batch_job(path_credentials, is_debug):\n \"\"\"\n A script that will add an adgroup with keywords and ads using batch upload.\n\n :param path_credentials: str, path to your adwords credentials file\n :param is_debug: bool\n \"\"\"\n adwords_service = freedan.AdWordsService(path_credentials)\n for account in adwords_service.accounts():\n print(account)\n\n # define new adwords instances\n adgroup = AdGroup(name=\"test_adgroup_1\")\n keyword1 = Keyword(text=\"asofjna\", match_type=\"EXACT\", bid=1.0, final_url=\"https://aiosjda.de\")\n keyword2 = Keyword(text=\"asofjna\", match_type=\"PHRASE\", bid=0.5, final_url=\"https://aiosjda.de\")\n ad1 = ExtendedTextAd(headline1=\"yo\", headline2=\"yoyo\", description=\"dem boys\",\n path1=\"Yo\", path2=\"Dude\", final_url=\"https://aiosjda.de\")\n ad2 = ExtendedTextAd(headline1=\"yo\", headline2=\"yoyo\", description=\"dem boyoyoyoys\",\n path1=\"Yo\", path2=\"Dude\", final_url=\"https://aiosjda.de\")\n\n # determine temporary id for adgroup\n temp_id_helper = freedan.TempIdHelper()\n adgroup_id = temp_id_helper.temp_id\n\n # operations\n adgroup_operations = [adgroup.add_operation(campaign_id=CAMPAIGN_ID, bid=0.01, adgroup_id=adgroup_id)]\n keyword_operations = [\n keyword1.add_operation(adgroup_id=adgroup_id),\n keyword2.add_operation(adgroup_id=adgroup_id)\n ]\n ad_operations = [\n ad1.add_operation(adgroup_id=adgroup_id),\n ad2.add_operation(adgroup_id=adgroup_id)\n ]\n\n # upload\n operations = (adgroup_operations, keyword_operations, ad_operations)\n adwords_service.upload(operations, is_debug=is_debug, method=\"batch\")\n\n\nif __name__ == \"__main__\":\n adwords_credentials_path = \"adwords_credentials.yaml\"\n add_adgroup_using_batch_job(adwords_credentials_path, is_debug=True)\n","sub_path":"examples/advanced/add_adgroup_using_batch_job.py","file_name":"add_adgroup_using_batch_job.py","file_ext":"py","file_size_in_byte":2049,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"88697898","text":"import csv\nfrom sklearn.neighbors import NearestNeighbors\nimport numpy as np\nfrom sklearn.metrics import roc_auc_score, precision_recall_curve, roc_curve, auc\nimport warnings\nimport matplotlib.pyplot as plt\nimport time\nfrom sklearn.preprocessing import StandardScaler\nscalar = StandardScaler()\n\n#reachDist() calculates the reach distance of each point to MinPts around it\ndef reachDist(df, MinPts, knnDist):\n clf = NearestNeighbors(n_neighbors=MinPts)\n clf.fit(df)\n distancesMinPts, indicesMinPts = clf.kneighbors(df)\n distancesMinPts[:,0] = np.amax(distancesMinPts,axis=1)\n distancesMinPts[:,1] = np.amax(distancesMinPts,axis=1)\n distancesMinPts[:,2] = np.amax(distancesMinPts,axis=1)\n return distancesMinPts, indicesMinPts\n\n#lrd calculates the Local Reachability Density\ndef lrd(MinPts,knnDistMinPts):\n return (MinPts/np.sum(knnDistMinPts,axis=1))\n\n#Finally lof calculates LOF outlier scores\ndef lof(Ird,MinPts,dsts):\n lof=[]\n for item in dsts:\n tempIrd = np.divide(Ird[item[1:]],Ird[item[0]])\n lof.append(tempIrd.sum()/MinPts)\n return lof\n\n#For Cross Validation\ndef LOF():\n totalX = []\n totalY = []\n flag = True\n countTrain = 0\n\n with open(\"creditcard.csv\", \"rb\") as f:\n data = csv.reader(f)\n for row in data:\n if flag:\n flag = False\n continue\n if countTrain >= 228000: #test on 20% of data\n break\n countTrain += 1\n totalX.append([float(i) for i in row[:-1]])\n totalY.append(int(row[-1]))\n totalX = scalar.fit_transform(totalX)\n print (\"Data Loaded\")\n #newTotalX = np.fft.fft(totalX)\n newTotalX = totalX\n warnings.filterwarnings(\"ignore\")\n clf = NearestNeighbors(n_neighbors=5, n_jobs = -1)\n clf.fit(newTotalX)\n distances, _ = clf.kneighbors(newTotalX)\n m = 500\n reachdist, reachindices = reachDist(newTotalX, m, distances)\n irdMatrix = lrd(m, reachdist)\n lofScores = lof(irdMatrix, m, reachindices)\n Y = []\n for i in range(len(totalY)):\n if lofScores[i] > 1.44:\n Y.append(1)\n else:\n Y.append(0)\n print (\"Results\")\n auc = roc_auc_score(totalY, Y)\n print(auc)\n fpr, _, _ = roc_curve(totalY, Y)\n print (fpr[1])\n _, recall, _ = precision_recall_curve(totalY, Y)\n print (recall[1])\n return auc, fpr[1], recall[1]\n\n#Main Function to do Cross validation followed by Testing\ndef main():\n print (\"Running 4 fold CV on LOF based Anomaly detection.\")\n LOF()\n\n start_time = time.time()\n totalX = []\n totalY = []\n flag = True\n countTrain = 0\n\n print (\"\\n\\nNow testing on separate data.\")\n with open(\"creditcard.csv\", \"rb\") as f:\n data = csv.reader(f)\n for row in data:\n if flag:\n flag = False\n continue\n countTrain += 1\n if countTrain > 228000: #CV on 80% of data\n totalX.append([float(i) for i in row[:-1]])\n totalY.append(int(row[-1]))\n totalX = scalar.fit_transform(totalX)\n print (\"Data Loaded\")\n\n newTotalX = np.fft.fft(totalX)\n #newTotalX = totalX\n warnings.filterwarnings(\"ignore\")\n clf = NearestNeighbors(n_neighbors=10, n_jobs = -1)\n clf.fit(newTotalX)\n distances, _ = clf.kneighbors(newTotalX)\n m = 500\n reachdist, reachindices = reachDist(newTotalX, m, distances)\n irdMatrix = lrd(m, reachdist)\n lofScores = lof(irdMatrix, m, reachindices)\n Y = []\n for i in range(len(totalY)):\n if lofScores[i] > 1.44:\n Y.append(1)\n else:\n Y.append(0)\n print(\"%s seconds\" % (time.time() - start_time))\n print (\"Results\")\n auc = roc_auc_score(totalY, Y)\n print(\"Area under curve : \" + str(auc))\n fpr, tpr, _ = roc_curve(totalY, Y)\n print (\"False Positive Rate : \" + str(fpr[1]))\n _, recall, _ = precision_recall_curve(totalY, Y)\n print (\"Recall : \" + str(recall[1]))\n\n plt.title('Receiver Operating Characteristic')\n plt.plot(fpr, tpr, color='darkorange', label='ROC curve (area = %0.3f)' % auc)\n plt.ylabel('True Positive Rate')\n plt.xlabel('False Positive Rate')\n plt.legend(loc=\"lower right\")\n plt.show()\n\nif __name__ == '__main__':\n main()\n","sub_path":"src/NN with LOF.py","file_name":"NN with LOF.py","file_ext":"py","file_size_in_byte":4300,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"230321565","text":"import datetime\nimport transaction\n\nfrom ixiacr.models.utils import SessionKeyValue\nfrom sqlalchemy.sql import and_, or_\nfrom sqlalchemy.orm.exc import NoResultFound\nfrom ixiacr.lib import IxiaLogger\n\nixiacrlogger = IxiaLogger(__name__)\n\n\nclass SessionKeyValueStore(object):\n \"\"\" Simplifies access to key/value pairs tied to a web session.\n \"\"\"\n\n def __init__(self, db, session_id):\n \"\"\"\n :param db: database session\n :param session_id: session_id tied to user web session\n \"\"\"\n self.db = db\n self.session_id = session_id\n\n def get_value(self, key, max_age_secs=None):\n \"\"\" Return the value of a key\n\n :param key: key name\n :param max_age_secs: maximum age in seconds of value\n :returns: None if not found or age expired; should only throw on unexpected error\n \"\"\"\n terms = [SessionKeyValue.session_id == self.session_id, SessionKeyValue.name == key]\n try:\n ixiacrlogger.debug('kv_store: session_id={0} checking for key={1}'.format(\n self.session_id, key))\n\n session_key_value = self.db.query(SessionKeyValue).filter(and_(*terms)).one()\n age_secs = (datetime.datetime.now() - session_key_value.timestamp).seconds\n\n expired = None if not max_age_secs else age_secs > max_age_secs\n ixiacrlogger.debug('kv_store: found value; key={0}; age={1}; expired={2}'.format(\n key, age_secs, expired))\n\n return session_key_value.value if not expired else None\n\n except NoResultFound:\n pass\n\n return None\n\n def set_value(self, key, new_value):\n \"\"\" Sets a key to a new value\n\n :param key: key name\n :param new_value: new value\n \"\"\"\n try:\n terms = [SessionKeyValue.session_id == self.session_id, SessionKeyValue.name == key]\n kv = self.db.query(SessionKeyValue).filter(and_(*terms)).one()\n except:\n kv = SessionKeyValue()\n kv.session_id = self.session_id\n kv.name = key\n self.db.add(kv)\n\n kv.value = new_value\n kv.timestamp = datetime.datetime.now()\n\n self.db.flush()\n\n ixiacrlogger.debug('kv_store: session_id={0} set key={1}; value={2}'.format(\n self.session_id, key, new_value))\n\n def remove_value(self, key):\n \"\"\" Remove a single key/value if its been loaded\n\n :param key: key name\n \"\"\"\n try:\n terms = [SessionKeyValue.session_id == self.session_id, SessionKeyValue.name == key]\n self.db.query(SessionKeyValue).filter(and_(*terms)).delete()\n self.db.flush()\n except Exception as e:\n ixiacrlogger.exception(e)\n raise\n\n def remove_all(self):\n \"\"\" Remove all key/values for the current session or any sessions older\n \"\"\"\n\n date_threshold = datetime.datetime.now() - datetime.timedelta(days=7)\n\n terms = [or_(SessionKeyValue.session_id == self.session_id,\n (SessionKeyValue.timestamp < date_threshold))]\n try:\n ixiacrlogger.debug('kv_store: session_id={0} removing all key-values and anything older than={1}'.format(\n self.session_id, str(date_threshold)))\n\n num_rows = self.db.query(SessionKeyValue).filter(or_(*terms)).delete()\n self.db.flush()\n\n ixiacrlogger.debug('kv_store: removed {0} rows'.format(num_rows))\n\n except Exception as e:\n ixiacrlogger.exception(e)\n raise\n","sub_path":"IxiaCR/ixiacr/lib/session_key_value.py","file_name":"session_key_value.py","file_ext":"py","file_size_in_byte":3570,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"342463781","text":"'''\nMove a motor back and forth in PV_Mode for with CANopen using the TMCM1617 module\n\nCreated on 09.04.2020\n\n@author: JM\n'''\n\nif __name__ == '__main__':\n pass\n\nimport time\nfrom PyTrinamic.connections.ConnectionManager import ConnectionManager\nfrom PyTrinamic.modules.TMCM1617.TMCM_1617 import TMCM_1617\n\n\"\"\"\n Choose the right bustype before starting the script\n\"\"\"\n\nconnectionManager = ConnectionManager(\" --interface pcan_CANopen\", connectionType = \"CANopen\")\nnetwork = connectionManager.connect()\n\nnode = network.addDs402Node(TMCM_1617.getEdsFile(), 1)\nmodule = node\n\n#This function initialized the ds402StateMachine\nnode.setup_402_state_machine()\n\n#####################\n#Communication area\nobjManufacturerDeviceName = module.sdo[0x1008]\nobjManufacturerHardwareVersion = module.sdo[0x1009]\n\nprint()\nprint(\"Module name: %s\" % objManufacturerDeviceName.raw)\nprint(\"Hardware version: %s\" % objManufacturerHardwareVersion.raw)\n\n######################\n#Manufacturer specific area\n\nobjOpenloopCurrent = module.sdo[0x2004]\n\n#Limit Switches\nobjSwitchParameter = module.sdo[0x2005]\n\n#Torque Mode Settings\nobjTorque_P = module.sdo[0x2041][1]\nobjTorque_I = module.sdo[0x2041][2]\nobjPID_Torque_Error = module.sdo[0x2041][3]\nobjPID_Torque_Error_Sum = module.sdo[0x2041][4]\nobjPID_Flux_Error = module.sdo[0x2041][5]\nobjPID_Flux_Error_Sum = module.sdo[0x2041][6]\nobjPHI_E = module.sdo[0x2041][7]\n\n#Velocity Mode Settings\nobjP_Parameter = module.sdo[0x2042][1]\nobjI_Parameter = module.sdo[0x2042][2]\nobjPI_Velocity_Error = module.sdo[0x2042][3]\nobjPI_Velocity_Error_Sum = module.sdo[0x2042][4]\n\n#Position Mode Settings\nobjP_Parameter = module.sdo[0x2043][1]\nobjPID_Position_Error = module.sdo[0x2043][2]\n\n#Motor Type\nobjMotorType = module.sdo[0x2050]\n\n#Commutation Mode\nobjCommutationMode = module.sdo[0x2055]\n\n#Motor Pole Pairs\nobjMotorPolePairs = module.sdo[0x2056]\n\n#Hall Sensor Settings\nobjHallPolarity = module.sdo[0x2070][1]\nobjHallDirection = module.sdo[0x2070][2]\nobjHallInterpolation = module.sdo[0x2070][3]\nobjHallPHI_E_offset = module.sdo[0x2070][4]\n\n#ABN Encoder Settings\nobjEncoderDirection = module.sdo[0x2080][1]\nobjEncoderSteps = module.sdo[0x2080][2]\nobjEncoderInitMode = module.sdo[0x2080][3]\n\n#Motor Status Flags\nobjDeviceState = module.sdo[0x2101]\nobjOpenloopAngle = module.sdo[0x2102]\nobjEncoderCommutationAngle = module.sdo[0x2103]\nobjHallCommutationAngle = module.sdo[0x2104]\n\n\n######################\n#Profile specific area\n\nobjControlWord = module.sdo[0x6040]\nobjStatusWord = module.sdo[0x6041]\nobjModeOfOperation = module.sdo[0x6060]\nobjActualPosition = module.sdo[0x6064]\nobjTargetTorque = module.sdo[0x6071]\nobjTargetPosition = module.sdo[0x607A]\nobjAcceleration = module.sdo[0x6083]\nobjActualVelocity = module.sdo[0x606C]\nobjDesiredVelocity = module.sdo[0x60FF]\nobjVelocityActualValue = module.sdo[0x606C]\n\n\"\"\"\n Define all motor configurations for the the TMCM-1617.\n\n The configuration is based on our standard BLDC motor (QBL4208-61-04-013-1024-AT).\n If you use a different motor be sure you have the right configuration setup otherwise the script may not working.\n\"\"\"\n\nobjMotorPolePairs.raw = 4\nobjCommutationMode.raw = 3\nobjOpenloopCurrent.raw = 500\nobjEncoderSteps.raw = 16384\nobjEncoderDirection.raw = 1\nobjCommutationMode.raw = 2\n\nprint(\"##############################\")\nprint(\"MotorPoles: %d\" % objMotorPolePairs.raw)\nprint(\"Commutation Mode: %d\" % objCommutationMode.raw)\nprint(\"Encoder Steps: %d\" % objEncoderSteps.raw)\nprint(\"Encoder Direction: %d\" % objEncoderDirection.raw)\nprint(\"Encoder InitMode: %d\" % objEncoderInitMode.raw)\nprint(\"##############################\")\nprint(\"startPV-Mode...\")\ntime.sleep(2)\n\nif node.is_faulted():\n print(\"Resetting fault\")\n node.reset_from_fault() # Reset node from fault and set it to Operation Enable state \n\ndef startPV():\n\n print(\"Node state before switcHParameter write:\" + node.state)\n objSwitchParameter.raw = 3\n\n timeout = time.time() + 15\n node.state = 'READY TO SWITCH ON'\n while node.state != 'READY TO SWITCH ON':\n if time.time() > timeout:\n raise Exception('Timeout when trying to change state')\n time.sleep(0.001)\n\n print(node.state)\n\n timeout = time.time() + 15\n node.state = 'SWITCHED ON'\n while node.state != 'SWITCHED ON':\n if time.time() > timeout:\n raise Exception('Timeout when trying to change state')\n time.sleep(0.001)\n\n print(node.state)\n\n if objModeOfOperation.raw != 3:\n objModeOfOperation.raw = 3\n print(\"MODE OF OPERATION SET TO: %d\" % objModeOfOperation.raw)\n\n timeout = time.time() + 15\n node.state = 'OPERATION ENABLED'\n while node.state != 'OPERATION ENABLED':\n if time.time() > timeout:\n raise Exception('Timeout when trying to change state')\n time.sleep(0.001)\n\n print(node.state)\n\n return\n\nstartPV()\n\n'''\nConfiguration Setup for using PV_Mode\n'''\n# Setup desired_Velocity\nobjDesiredVelocity.raw = 1000\n# Setup Acceleration\nobjAcceleration.raw = 2000\n\nprint()\nprint(\"Configure parameters\")\ntime.sleep(0.2)\nprint()\nprint(\"DesiredVelocity: %d\" % objDesiredVelocity.raw)\nprint(\"Accelaration: %d\" % objAcceleration.raw)\nprint()\nprint(\"Start PV_Mode...\")\ntime.sleep(0.2)\nprint()\n\n# Tell the PV mode that it has a new DesiredVelocity\nnode.controlword = 0x000F\nnode.controlword = 0x001F\n\nprint()\ntime.sleep(3)\n\nobjDesiredVelocity.raw = -1000\nprint(\"DesiredVelocity: %d\" % objDesiredVelocity.raw)\n\n# Tell the PV mode that it has a new DesiredVelocity\nnode.controlword = 0x000F\nnode.controlword = 0x001F\n\ntime.sleep(3)\n\nobjDesiredVelocity.raw = 0\n\nnetwork.close()\nprint(\"disconnected.\")\n","sub_path":"PyTrinamic/examples/modules/TMCM_1617/TMCM_1617_CANopen_hall_PV_Mode.py","file_name":"TMCM_1617_CANopen_hall_PV_Mode.py","file_ext":"py","file_size_in_byte":6191,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"464403536","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Tue Nov 7 11:02:01 2017\n\n@author: jpelda\n\"\"\"\n\nimport configparser as cfp\n\n\nconfig = cfp.ConfigParser()\n\n\nconfig['paths_toT'] = {'import_folder': eval(\"os.path.dirname(os.getcwd()) +\\\n os.sep + 'output' + os.sep +\\\n 'TestNetworks' + os.sep +\\\n 'TestNet_2Producer_withoutMeshes'\"),\n 'import_filename': 'test_2Producer_withoutMeshes_heatgrid.npy',\n 'export_folder': 'TestNet'}\n\n\nconfig['paths_toTA'] = {'import_folder': eval(\"os.path.dirname(os.getcwd()) +\\\n os.sep + 'output' + os.sep +\\\n 'TestNetworks' + os.sep +\\\n 'TestNet_2Producer_withoutMeshes'\"),\n 'import_filename': 'TestNet_2Producer_withoutMeshes.CSV',\n 'export_folder': 'TestNetwork'}\nconfig['CSV_toTA'] = {'skiprows_nodes': 544,\n 'nrows_nodes': 13,\n 'header_nodes': 0,\n 'skiprows_pipes': 562,\n 'nrows_pipes': 11,\n 'header_pipes': 0\n }\n\n\nwith open('compareHeatgridValuesWithSTANETValues_config_2Producer_withoutMeshes.ini', 'w') as configfile:\n config.write(configfile)\n#\n#config.read('compareHeatgridValuesWithSTANETValues_config.ini')\n#print(config['paths_toT']['import_folder'])","sub_path":"test/compareHeatgridValuesWithSTANETValues_config.py","file_name":"compareHeatgridValuesWithSTANETValues_config.py","file_ext":"py","file_size_in_byte":1495,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"258225362","text":"import time\nimport threading\nimport datetime\nimport requests\nimport csv\n\nfrom log import logger\nfrom utils import mesp_dm, mesp_dm2, ngsi_dm, ngsild_dm\nfrom metrics import ConsumptionSource\n\nLOGGER = logger(__name__)\n\n\nclass GeneralSink(threading.Thread):\n def __init__(self, threadID, stype, name, q, queuelock, schema):\n threading.Thread.__init__(self)\n self.threadID = threadID\n self.stype = stype\n self.name = name\n self.q = q\n self.lock = queuelock\n self.schema = schema\n self.sink = None\n self.exitFlag = 0\n\n def process_data(self, threadName, q):\n req_bytes = dict()\n while not self.exitFlag:\n if not self.q.empty():\n self.lock.acquire()\n rawdata = self.q.get()\n self.lock.release()\n LOGGER.debug(\"{} Got data {}\".format(self.name, rawdata))\n\n # process rawdata\n LOGGER.info(\"Parsing data...\")\n\n # Get rawdata\n batches = self.schema.split(';')[:-1]\n data = rawdata['raw'].decode('utf-8').split(\";\")[:-1]\n\n # Check if they fit with the schema\n if len(batches) != len(data):\n LOGGER.debug(\"Schema and data format are not the same!\")\n continue\n\n # Re-pack all data to snapshot dict\n snapshot = {}\n for B, d in zip(batches, data):\n # snapshot[B.lower().replace(\"#\", \"_\")] = d\n snapshot[B.replace(\"#\", \"_\")] = d\n if \"score\" in rawdata:\n snapshot[\"score\"] = rawdata[\"score\"]\n else:\n snapshot[\"score\"] = 0\n if \"imgname\" in rawdata:\n snapshot[\"imgname\"] = rawdata[\"imgname\"]\n else:\n snapshot[\"imgname\"] = ''\n\n req_bytes = self.sink(snapshot)\n return req_bytes\n\n def run(self):\n LOGGER.info(\"Starting %s %s\" % (self.stype, self.name))\n self.process_data(self.name, self.q)\n LOGGER.info(\"Exiting %s %s\" % (self.stype, self.name))\n\n\nclass OrionSink(GeneralSink):\n\n def __init__(self, threadID, name, q, queuelock, url, schema, metricspath):\n GeneralSink.__init__(self, threadID, 'Orion', name, q, queuelock,\n schema)\n self.sink = self.posttoorion\n self.url = url\n self.metricspath = metricspath\n with open(self.metricspath, 'w+') as csvfile:\n writer = csv.writer(csvfile, delimiter=',', quotechar='\"',\n quoting=csv.QUOTE_MINIMAL)\n writer.writerow(['TIMESTAMP', 'UNIQUEID', 'TYPE',\n 'TRANSLATION_TIME', 'TRANSMITION_TIME',\n 'NO_REQUESTS', 'TOTAL_JSON_SIZE',\n 'VOLTAGE (V)', 'Current(mA)', 'Power(mW)'])\n\n def getfromorion_id(self, id):\n LOGGER.debug(\"get from Orion!\")\n url = self.url + '/v2/entities/' + id\n headers = {'Accept': 'application/json',\n 'X-Auth-Token': 'QGIrJsK6sSyKfvZvnsza6DlgjSUa8t'}\n # print url\n response = requests.get(url, headers=headers)\n return response.json()\n\n def getfromorion_all(self):\n LOGGER.debug(\"get from Orion!\")\n # payload = {'limit': '500'}\n url = self.url + '/v2/entities?limit=500'\n headers = {'Accept': 'application/json',\n 'X-Auth-Token': 'QGIrJsK6sSyKfvZvnsza6DlgjSUa8t'}\n # print url\n response = requests.get(url, headers=headers)\n # print response.json()\n return response.json()\n\n def post_all(self, measurments_list):\n LOGGER.debug(\"reading measurment\")\n for measurment_one in measurments_list:\n time.sleep(1)\n LOGGER.debug(measurment_one)\n LOGGER.debug(\"posting\")\n self.posttoorion(measurment_one)\n LOGGER.debug(\"done\")\n\n LOGGER.debug(\"finished\")\n\n def posttoorion(self, snapshot):\n\n LOGGER.debug('Post to Orion')\n LOGGER.info(snapshot)\n consumption = ConsumptionSource()\n # Timestampjust before the tranlation\n before_trans_tmst = datetime.datetime.now()\n # Translate on different models and post data to Orion\n translation = dict()\n # Keep time for each tranlation\n translation_time = dict()\n\n consumption.start()\n tmmesp = time.time()\n translation['mesp'] = mesp_dm(snapshot, before_trans_tmst)\n translation['mesp'] = mesp_dm2(snapshot, before_trans_tmst)\n translation_time['mesp'] = time.time() - tmmesp\n\n tmngsi = time.time()\n translation['ngsi'] = ngsi_dm(snapshot, before_trans_tmst)\n translation_time['ngsi'] = time.time() - tmngsi\n\n tmngsild = time.time()\n translation['ngsild'] = ngsild_dm(snapshot, before_trans_tmst)\n translation_time['ngsild'] = time.time() - tmngsild\n\n # LOGGER.info(\"Entity id: {}\".format(str(tmst)))\n transmition_time = dict()\n translation_size = dict()\n if self.url:\n url = self.url + '/v2/entities'\n headers = {'Accept': 'application/json'}\n sess = requests.Session()\n for t, l in translation.items():\n # Hack for ngsi-lg json objects\n if t == 'ngsild':\n url += '?options=keyValues'\n\n tnsm_time = time.time()\n for json in l:\n req = requests.Request('POST', url=url, headers=headers,\n json=json)\n preq = req.prepare()\n LOGGER.debug(\"size of request body sent for %s:\" % t)\n LOGGER.debug(len(preq.body))\n if t in translation_size:\n translation_size[t].append(len(preq.headers) +\n len(preq.body))\n else:\n translation_size[t] = [len(preq.headers) +\n len(preq.body)]\n response = sess.send(preq)\n transmition_time[t] = time.time() - tnsm_time\n LOGGER.debug(\"Response\")\n LOGGER.debug(response.text)\n\n consumption.stop()\n (v, c, p) = consumption.get()\n with open(self.metricspath, 'a+') as csvfile:\n for t in translation.keys():\n writer = csv.writer(csvfile, delimiter=',', quotechar='\"',\n quoting=csv.QUOTE_MINIMAL)\n row = [str(datetime.datetime.now()), snapshot['UNIQUEID'], t,\n translation_time[t], transmition_time[t],\n len(translation_size[t]), sum(translation_size[t]),\n v, c, p]\n writer.writerow(row)\n csvfile.flush()\n\n return translation_size\n","sub_path":"py/sink.py","file_name":"sink.py","file_ext":"py","file_size_in_byte":7095,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"222263854","text":"class Solution(object):\n def sortColors(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: void Do not return anything, modify nums in-place instead.\n \"\"\"\n i = 0\n l = -1\n r = len(nums)\n \n while i < r: \n if nums[i] == 1:\n i += 1\n elif nums[i] == 0:\n l += 1\n nums[l], nums[i] = nums[i], nums[l]\n i += 1\n elif nums[i] == 2:\n r -= 1\n nums[r], nums[i] = nums[i], nums[r]\n\n\nif __name__ == '__main__':\n l = [2, 1, 0, 0, 2, 1, 1]\n Solution().sortColors(l)\n print(l)","sub_path":"075-Sort-Colors/solution.py","file_name":"solution.py","file_ext":"py","file_size_in_byte":654,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"558991126","text":"#!/usr/bin/env python\n# (C) 2017 OpenEye Scientific Software Inc. All rights reserved.\n#\n# TERMS FOR USE OF SAMPLE CODE The software below (\"Sample Code\") is\n# provided to current licensees or subscribers of OpenEye products or\n# SaaS offerings (each a \"Customer\").\n# Customer is hereby permitted to use, copy, and modify the Sample Code,\n# subject to these terms. OpenEye claims no rights to Customer's\n# modifications. Modification of Sample Code is at Customer's sole and\n# exclusive risk. Sample Code may require Customer to have a then\n# current license or subscription to the applicable OpenEye offering.\n# THE SAMPLE CODE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n# EXPRESS OR IMPLIED. OPENEYE DISCLAIMS ALL WARRANTIES, INCLUDING, BUT\n# NOT LIMITED TO, WARRANTIES OF MERCHANTABILITY, FITNESS FOR A\n# PARTICULAR PURPOSE AND NONINFRINGEMENT. In no event shall OpenEye be\n# liable for any damages or liability in connection with the Sample Code\n# or its use.\n\n#############################################################################\n# Cut out a residue (identified by chain, residue name and number)\n#############################################################################\nimport sys\nfrom openeye import oechem\n\n\ndef SubSetRes(ifs, ofs, chainid, resname, resnum):\n adjustHCount = True\n mol = oechem.OEGraphMol()\n while oechem.OEReadMolecule(ifs, mol):\n if not oechem.OEHasResidues(mol):\n oechem.OEPerceiveResidues(mol, oechem.OEPreserveResInfo_All)\n hv = oechem.OEHierView(mol)\n res = hv.GetResidue(chainid, resname, resnum)\n if res.GetOEResidue().GetName() is None:\n oechem.OEThrow.Fatal(\"Failed to find residue\")\n atomiter = res.GetAtoms()\n member = oechem.OEIsAtomMember(atomiter)\n resmol = oechem.OEGraphMol()\n oechem.OESubsetMol(resmol, mol, member, adjustHCount)\n if chainid == \" \":\n resmol.SetTitle(\"%s %d\" % (resname, resnum))\n else:\n resmol.SetTitle(\"%s %s %d\" % (resname, chainid, resnum))\n\n oechem.OEWriteMolecule(ofs, resmol)\n\n\nif __name__ == \"__main__\":\n if len(sys.argv) < 5 or len(sys.argv) > 6:\n oechem.OEThrow.Usage(\"subsetres.py [chain] \\n\"\n \"example: subsetres.py SER A 3 dhfr.pdb out.pdb\\n\"\n \"Chain ID required if the residue has a chain ID\")\n\n resname = sys.argv[1]\n chainid = \" \"\n if len(sys.argv) == 5:\n resnum = int(sys.argv[2])\n infile = sys.argv[3]\n outfile = sys.argv[4]\n elif len(sys.argv) == 6:\n chainid = sys.argv[2]\n resnum = int(sys.argv[3])\n infile = sys.argv[4]\n outfile = sys.argv[5]\n\n ifs = oechem.oemolistream()\n if not ifs.open(infile):\n oechem.OEThrow.Fatal(\"Unable to open %s for reading\" % infile)\n ofs = oechem.oemolostream()\n if not ofs.open(outfile):\n oechem.OEThrow.Fatal(\"Unable to open %s for writing\" % outfile)\n\n SubSetRes(ifs, ofs, chainid, resname, resnum)\n","sub_path":"venv/Scripts/subsetres.py","file_name":"subsetres.py","file_ext":"py","file_size_in_byte":3055,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"22874024","text":"#!/usr/bin/env python\r\n# -*- coding:utf-8 -*-\r\n\r\nfrom bs4 import BeautifulSoup\r\n\r\n\r\ndef sel(q):\r\n print(soup.select_one(q).string)\r\n\r\n\r\nbooks_html = \"\"\"\r\n\r\n Genesis \r\n Exodus \r\n Leviticus \r\n Numbers \r\n Deuteronomy \r\n \"\"\"\r\n\r\nsoup = BeautifulSoup(books_html, \"html.parser\")\r\n\r\n# CSSセレクタで検索\r\n# sel = lambda q : print(soup.select_one(q).string)\r\nsel(\"#nu\")\r\nsel(\"li#nu\")\r\nsel(\"#bible #nu\")\r\nsel(\"#bible > #nu\")\r\nsel(\"ul#bible > li#nu\")\r\n\r\n\r\n","sub_path":"1-3/sel-books.py","file_name":"sel-books.py","file_ext":"py","file_size_in_byte":568,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"587902098","text":"from log import *\nimport GPS\nimport Arduino\nimport Server\nimport commands\n\nScript_File = [] \nScript_Running = False\ncommand_num = 0\n\n'''\nstart_script() takes a string as a paramater and parses it\ninto commands and starts the script running.\n'''\ndef start_script(script) :\n global Script_Running\n global Script_File\n\n #Script_File = (script, 'r')\n Script_File = script.splitlines()\n writeLog(LOG_DETAILS, \"New script file split: \" + Script_File[0])\n Script_Running = True\n\n'''\nThe Check() function is called by the contoller.py every\ncycle. The Check() function returns if the script has not\nbeen called. The Check() function checks if a script \ncommand is running, if not then executes the next command.\nIf the script was called and the commands are done executing\nthen Check() stops the script.\n'''\ndef Check() :\n global Script_Running\n global Script_File\n global command_num\n\n # if the script command has not been called\n if not Script_Running :\n return\n\n # if the current script command is still running\n if commands.Command_Running :\n return\n\n # if there are still more commands to execute\n if command_num < len(Script_File) :\n command = Script_File[command_num]\n commands.Execute(command)\n command_num = 1 + command_num\n\n # if there are no more commands to execute\n elif len(Script_File) == command_num - 1 :\n command_num = 0\n Script_Running = False\n writeLog(LOG_DETAILS,\"Ending script\")\n return\n","sub_path":"raspberry/script.py","file_name":"script.py","file_ext":"py","file_size_in_byte":1516,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"11610809","text":"# Importing modules\nimport threading\nfrom tkinter import *\nfrom tkinter import ttk\nfrom tkinter.ttk import *\nfrom mttkinter import mtTkinter\nfrom PIL import ImageTk, Image\nfrom Variable_Declaration import Variable\nimport guli\nimport time\n\nclass Thread_main(threading.Thread):\n def __init__(self, name):\n threading.Thread.__init__(self)\n self.name = name\n\n def run(self):\n Execute()\n\n# Default Values\nMagnetizingCurrent_Max = 30\nMagnetizingCurrent_Min = 15\nStartingToruqe_Precision = 90 \nMaxToruqe_Precision = 90\nCalculation_Combinations = 5\n\n# Lists\nMaterial_Elements = [\"M-15\", \"M-19\", \"M-22\", \"M-27\", \"M-36\", \"M-43\", \"M-45\"]\nStatorSlot_Elements = [\"Rectangular\", \"Trapezoidal\", \"Rounded\", \"Circular\"]\nRotorSlot_Elements = [\"Rectangular\", \"Trapezoidal\", \"Rounded\", \"Circular\"]\n\n# Initializing Tk\nroot = Tk() \nroot.title('Induction Motor Design Tool')\n\n# Frame\nframe_1 = LabelFrame(root, text=\"Nominal Data\")\nframe_1.grid(row=0, column=0, rowspan=3, sticky=\"snew\", padx=4)\nframe_2 = LabelFrame(root, text=\"Ratios\")\nframe_2.grid(row=2, column=1, sticky=\"snew\", padx=4)\nframe_3 = LabelFrame(root, text=\"Materials\")\nframe_3.grid(row=0, column=2, rowspan=2, sticky=\"nsew\", padx=4, pady=4)\nframe_4 = LabelFrame(root, text = \"Conditions\")\nframe_4.grid(row=2, column=2, sticky=\"nsew\", padx=4)\nframe_5 = LabelFrame(root, text=\"Power [W]/Torque [Nm]\")\nframe_5.grid(row=1, column=1, sticky=\"snew\", padx=4, pady=4)\nframe_6 = LabelFrame(root, text=\"Slot Type\")\nframe_6.grid(row=0, column=3, rowspan=3, sticky=\"snew\", padx=4, pady=4)\nframe_7 = LabelFrame(root, text=\"Write in File\")\nframe_7.grid(row=0, column=1, sticky=\"snew\", padx=4, pady=4)\n\n# Fields\n\n# Nominal Data Frame (frame_1)\nVoltage = Label(frame_1, text=\"Voltage [V]\")\nVoltage_Entry = Entry(frame_1, width=10)\n\nFrequency = Label(frame_1, text=\"Frequency [f]\")\nFrequency_Entry = Entry(frame_1, width=10)\n\nNum_Poles = Label(frame_1, text=\"Num. of Poles\")\nNum_Poles_Entry = Entry(frame_1, width=10)\n\nEta = Label(frame_1, text=\"Efficiency\")\nEta_Entry = Entry(frame_1, width=10)\n\nPowerFactor = Label(frame_1, text=\"Power Factor\")\nPowerFactor_Entry = Entry(frame_1, width=10)\n\nWinding = Label(frame_1, text=\"Winding\")\nWinding_Clicked = StringVar()\nWinding_Clicked.set(\"Delta\")\nWinding_Menu = OptionMenu(frame_1, Winding_Clicked, \"Delta\", \"Star\")\n\n# Conductivity\n\nConductivity_Label1 = Label(frame_3, text=\"Conductivity\").pack(pady=2)\nConductivity_Label2 = Label(frame_3, text=\"[Sm/mm^2]\").pack(pady=2)\nConductivity_Entry = Entry(frame_3, width=10)\nConductivity_Entry.pack(pady=2)\nConductivity_Entry.insert(0, \"57\")\n\n# Right Side\nMaterial = Label(frame_3, text=\"Core Material\")\nMaterial_Clicked = StringVar()\nMaterial_Clicked.set(Material_Elements[0])\nMaterial_Menu = OptionMenu(frame_3, Material_Clicked, *Material_Elements)\nMaterial.pack(pady=2)\nMaterial_Menu.pack(pady=2)\n\nKp = Label(frame_2, text=\"Starting Current Ratio\")\nKp_Entry = Entry(frame_2, width=10)\n\nK_Mp = Label(frame_2, text=\"Starting Torque Ratio\")\nK_Mp_Entry = Entry(frame_2, width=10)\n\nK_Mm = Label(frame_2, text=\"Maximum Torque Ratio\")\nK_Mm_Entry = Entry(frame_2, width=10)\n\n# Grid\n\n# Left Side\nVoltage.pack(pady=2, padx=2)\nVoltage_Entry.pack(pady=2)\nFrequency.pack(pady=2, padx=2)\nFrequency_Entry.pack(pady=2)\nNum_Poles.pack(pady=2, padx=2)\nNum_Poles_Entry.pack(pady=2)\nEta.pack(pady=2, padx=2)\nEta_Entry.pack(pady=2)\nPowerFactor.pack(pady=2, padx=2)\nPowerFactor_Entry.pack(pady=2)\nWinding.pack(pady=2, padx=2)\nWinding_Menu.pack(pady=2)\n\"\"\"\nVoltage.grid(row=0, column=0)\nVoltage_Entry.grid(row=0, column=1)\nFrequency.grid(row=1, column=0)\nFrequency_Entry.grid(row=1, column=1)\nNum_Poles.grid(row=2, column=0)\nNum_Poles_Entry.grid(row=2, column=1)\nEta.grid(row=3, column=0)\nEta_Entry.grid(row=3, column=1)\nPowerFactor.grid(row=4, column=0)\nPowerFactor_Entry.grid(row=4, column=1)\nWinding.grid(row=5, column=0)\nWinding_Menu.grid(row=5, column=1)\n\"\"\"\n\n# Right Side\n\nKp.pack(pady=2, padx=2)\nKp_Entry.pack(pady=2)\nK_Mp.pack(pady=2, padx=2)\nK_Mp_Entry.pack(pady=2)\nK_Mm.pack(pady=2, padx=2)\nK_Mm_Entry.pack(pady=2)\n\n# Check Boxes\n\n# Frame Condtiitons (frame_4)\nEta_Box_Var = IntVar()\nPowerFactor_Box_Var = IntVar()\nKp_Box_Var = IntVar()\nK_Mp_Box_Var = IntVar()\nK_Mm_Box_Var = IntVar()\n\nEta_Box = Checkbutton(frame_4, text=\"Efficiency\", variable = Eta_Box_Var)\nPowerFactor_Box = Checkbutton(frame_4, text=\"Power Factor\", variable = PowerFactor_Box_Var)\nKp_Box = Checkbutton(frame_4, text=\"Kp\", variable = Kp_Box_Var)\nK_Mp_Box = Checkbutton(frame_4, text=\"kMp\", variable = K_Mp_Box_Var)\nK_Mm_Box = Checkbutton(frame_4, text=\"kMm\", variable = K_Mm_Box_Var)\nPowerFactor_Box.pack(padx=4, pady=2, anchor=\"w\")\nEta_Box.pack(padx=4, pady=2, anchor=\"w\")\nKp_Box.pack(padx=4, pady=2, anchor=\"w\")\nK_Mp_Box.pack(padx=4, pady=2, anchor=\"w\")\nK_Mm_Box.pack(padx=4, pady=2, anchor=\"w\")\n\n# Radio Buttons\na=0\n\nr = IntVar()\nr.set(\"1\")\n\ndef Execute():\n Variable(Pn_Mn.get(), \n Voltage_Entry.get(), \n Frequency_Entry.get(), \n Kp_Entry.get(), \n K_Mm_Entry.get(), \n K_Mp_Entry.get(), \n Num_Poles_Entry.get(), \n Eta_Entry.get(), \n PowerFactor_Entry.get(), \n Winding_Clicked.get(),\n Material_Clicked.get(),\n Conductivity_Entry.get(),\n Eta_Box_Var.get(),\n PowerFactor_Box_Var.get(),\n Kp_Box_Var.get(),\n K_Mp_Box_Var.get(),\n K_Mm_Box_Var.get(),\n r.get(),\n StatorSlot_Clicked.get(),\n RotorSlot_Clicked.get(),\n MagnetizingCurrent_Max,\n MagnetizingCurrent_Min,\n StartingToruqe_Precision,\n MaxToruqe_Precision,\n Calculation_Combinations\n )\n\ndef Start():\n a = Thread_main(\"GUI\")\n a.start()\n flag = 1\ndef Options():\n \n global MagnetizingCurrent_Max \n global MagnetizingCurrent_Min\n global StartingToruqe_Precision\n global MaxToruqe_Precision\n global Calculation_Combinations\n \n OptionsWindow = Toplevel()\n OptionsWindow.title('Proektiranje na Asinhron Motor - Options')\n \n MagnetizingCurrent_Max_Label = Label(OptionsWindow, text=\"Maximum Magnetizing Current [%]\").grid(row=0, column=0, padx=4, pady=2, sticky=\"w\")\n MagnetizingCurrent_Max_Entry = Entry(OptionsWindow, width=10)\n MagnetizingCurrent_Max_Entry.grid(row=0, column=1, pady=2, padx=4)\n MagnetizingCurrent_Max_Entry.insert(0, MagnetizingCurrent_Max)\n MagnetizingCurrent_Max = MagnetizingCurrent_Max_Entry.get()\n \n MagnetizingCurrent_Min_Label = Label(OptionsWindow, text=\"Minimum Magnetizing Current [%]\").grid(row=1, column=0, padx=4, pady=2, sticky=\"w\") \n MagnetizingCurrent_Min_Entry = Entry(OptionsWindow, width=10)\n MagnetizingCurrent_Min_Entry.grid(row=1, column=1, pady=2, padx=4)\n MagnetizingCurrent_Min_Entry.insert(0, MagnetizingCurrent_Min) \n \n StartingToruqe_Precision_Label = Label(OptionsWindow, text=\"Starting Toruqe Accuracy [%]\").grid(row=2, column=0, padx=4, pady=2, sticky=\"w\")\n StartingToruqe_Precision_Entry = Entry(OptionsWindow, width=10)\n StartingToruqe_Precision_Entry.grid(row=2, column=1, pady=2, padx=4)\n StartingToruqe_Precision_Entry.insert(0, StartingToruqe_Precision)\n \n MaxToruqe_Precision_Label = Label(OptionsWindow, text=\"Maximum Toruqe Accuracy [%]\").grid(row=3, column=0, padx=4, pady=2, sticky=\"w\")\n MaxToruqe_Precision_Entry = Entry(OptionsWindow, width=10)\n MaxToruqe_Precision_Entry.grid(row=3, column=1, pady=2, padx=4)\n MaxToruqe_Precision_Entry.insert(0, MaxToruqe_Precision)\n \n Calculation_Combinations_Label = Label(OptionsWindow, text=\"Calculation Combinations\").grid(row=4, column=0, padx=4, pady=2, sticky=\"w\")\n Calculation_Combinations_Entry = Entry(OptionsWindow, width=10)\n Calculation_Combinations_Entry.grid(row=4, column=1, pady=2, padx=4)\n Calculation_Combinations_Entry.insert(0, Calculation_Combinations) \n \n Okey_2 = Button(OptionsWindow, text=\"OK\", command=lambda: Options_Destroy(MagnetizingCurrent_Max_Entry.get(), MagnetizingCurrent_Min_Entry.get(), StartingToruqe_Precision_Entry.get(), MaxToruqe_Precision_Entry.get(), Calculation_Combinations_Entry.get())).grid(row=5, column=1, padx=4, pady=4)\n \n \"\"\"\n eta_Precision_Label = Label(OptionsWindow, text=\"Efficiency Deviation [%]\").grid(row=4, column=0)\n eta_Precision_Entry = Entry(OptionsWindow, width=10)\n eta_Precision_Entry.grid(row=4, column=1)\n eta_Precision_Entry.insert(0, \"90\")\n \n PowerFactor_Precision_Label = Label(OptionsWindow, text=\"Power Factor Deviation [%]\").grid(row=5, column=0)\n PowerFactor_Precision_Entry = Entry(OptionsWindow, width=10)\n PowerFactor_Precision_Entry.grid(row=0, column=1)\n PowerFactor_Precision_Entry.insert(5, \"90\") \n \"\"\"\n \ndef Options_Destroy(MagnetizingCurrent_Max_Entry, MagnetizingCurrent_Min_Entry, StartingToruqe_Precision_Entry, MaxToruqe_Precision_Entry, Calculation_Combinations_Entry):\n global MagnetizingCurrent_Max\n global MagnetizingCurrent_Min\n global StartingToruqe_Precision\n global MaxToruqe_Precision\n global Calculation_Combinations\n \n MagnetizingCurrent_Max = MagnetizingCurrent_Max_Entry\n MagnetizingCurrent_Min = MagnetizingCurrent_Min_Entry\n StartingToruqe_Precision = StartingToruqe_Precision_Entry\n MaxToruqe_Precision = MaxToruqe_Precision_Entry\n Calculation_Combinations = Calculation_Combinations_Entry\n \n# Okey Buttons\n\nOkey = Button(root, text=\"OK\", command=Start).grid(row=3, column=3, padx=4, sticky=\"e\")\n\n# Frame Power/Toruqe (frame_5)\nPn_Mn = Entry(frame_5, width=7)\nPn_Mn.pack(side='left', padx=4)\nPn_Radio = Radiobutton(frame_5, text=\"Pn\", variable=r, value=1).pack(side='left')\nMn_Radio = Radiobutton(frame_5, text=\"Mn\", variable=r, value=2).pack(side='left')\n\n# Option Button\n\nOptionsButton = Button(root, text=\"Options\", command=Options).grid(row=4, column=3, padx=4, pady=4, sticky=\"e\")\n\n# Help Button\n\nHelpButton = Button(root, text=\"Help\").grid(row=4, column=0, padx=4, pady=4, sticky=\"w\")\n\n# Progress Bar\n\nglobal progress \n\nprogress = Progressbar(root, orient = HORIZONTAL, \n length = 100, mode = 'determinate')\nprogress.grid(row=3, column = 0, columnspan = 3, sticky = 'nsew', padx=3, pady=4)\n\"\"\"\ntimer = IntVar()\ntimer.set(0)\n\n#global bar\n\n#bar = guli.GuliVariable(\"bar\").setValue(0)\n\ndef UpdateBar(bar):\n progress['value'] = bar\n\n\ndef timer_callback(*args):\n global progress\n global bar\n progress['value'] = bar\n\n#time.time.trace(\"w\", timer_callback)\n\"\"\"\n# Slot Type (frame_6)\n\n# Stator Slot\nStatorSlot_Label = Label(frame_6, text=\"Stator Slot\").pack()\nStatorSlot_Clicked = StringVar()\nStatorSlot_Clicked.set(StatorSlot_Elements[0])\nStatorSlot_Menu = OptionMenu(frame_6, StatorSlot_Clicked, *StatorSlot_Elements).pack(padx=4, pady=2)\n\n## Rotor Slot\nRotorSlot_Label = Label(frame_6, text=\"Rotor Slot\").pack()\nRotorSlot_Clicked = StringVar()\nRotorSlot_Clicked.set(RotorSlot_Elements[0])\nRotorSlot_Menu = OptionMenu(frame_6, RotorSlot_Clicked, *RotorSlot_Elements).pack(padx=4, pady=2)\n\nSlot_Image = Image.open(\"images/Rectangular_Slot.png\")\nSlot_Image = Slot_Image.resize((130, 135), Image.ANTIALIAS)\nSlot_Image=ImageTk.PhotoImage(Slot_Image)\nSlot_Label = Label(frame_6, image=Slot_Image)\nSlot_Label.pack(padx=4, pady=2)\n\ndef stator_callback(*args):\n global Slot_Label\n global Slot_Image\n Slot_Label.pack_forget()\n Slot_Image = Image.open(\"images/{}\".format(StatorSlot_Clicked.get())+\"_Slot.png\")\n Slot_Image = Slot_Image.resize((130, 135), Image.ANTIALIAS)\n Slot_Image=ImageTk.PhotoImage(Slot_Image)\n Slot_Label = Label(frame_6, image=Slot_Image)\n Slot_Label.pack(padx=4, pady=2)\n\ndef rotor_callback(*args):\n global Slot_Label\n global Slot_Image\n Slot_Label.pack_forget()\n Slot_Image = Image.open(\"images/{}\".format(RotorSlot_Clicked.get())+\"_Slot.png\")\n Slot_Image = Slot_Image.resize((130, 135), Image.ANTIALIAS)\n Slot_Image=ImageTk.PhotoImage(Slot_Image)\n Slot_Label = Label(frame_6, image=Slot_Image)\n Slot_Label.pack(padx=4, pady=2)\n\nStatorSlot_Clicked.trace(\"w\", stator_callback)\nRotorSlot_Clicked.trace(\"w\", rotor_callback)\n\n# Ouptut File (frame_7)\n\nWriteCSV_Var = IntVar()\nWritePDF_Var = IntVar()\n\nWriteCSV = Checkbutton(frame_7, text=\"Write in .csv\", variable=WriteCSV_Var)\nWritePDF = Checkbutton(frame_7, text=\"Write in .pdf\", variable=WritePDF_Var)\n\nWriteCSV.pack(padx=4, pady=2, anchor=\"w\")\nWritePDF.pack(padx=4, pady=2, anchor=\"w\")\n\n\n#myButton = Button(root, text='Da', padx=100, command=Click)\n#myButton.pack()\n\nguli.GuliVariable(\"bar\").setValue(0)\n\nprint (\"NESTO\")\nwhile 1: \n try:\n progress['value'] = guli.GuliVariable(\"bar\").get()\n except ValueError:\n pass\n root.update_idletasks()\n root.update()\n\n","sub_path":"code/GUI.py","file_name":"GUI.py","file_ext":"py","file_size_in_byte":12787,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"430150860","text":"#!/usr/bin/python\n\nimport os\nimport urllib2\nimport xlsxwriter\nfrom bs4 import BeautifulSoup\n\nPETSHOP_FRESHSTEP_URL = \"http://www.petshop.ru/catalog/cats/tualety/vpityvayuschiy_napolnitel/troynaya_zaschita_vpityvayuschiy_napolnitel_1661/\"\nZOO812_FRESHSTEP_URL = \"http://zoo812.ru/products/fresh-step-trojnaya-zaschita-ot-zapaha-vpityvayuschij-napolnitel\"\nKORMKOM_FRESHSTEP_URL = \"http://www.korkom.ru/p/1955/FRESH_STEP_Trojnaya_zazchita\"\nHAPPYPET_FRESHSTEP_URL = \"http://xn----7sbgnmcfnotjrboh1ec2f.xn--p1ai/%D0%BA%D0%B0%D1%82%D0%B0%D0%BB%D0%BE%D0%B3/%D0%B4%D0%BB%D1%8F-%D0%BA%D0%BE%D1%88%D0%B5%D0%BA/%D0%BD%D0%B0%D0%BF%D0%BE%D0%BB%D0%BD%D0%B8%D1%82%D0%B5%D0%BB%D0%B8/fresh-step/74357/\"\n\nshops_list = [\"Petshop\", \"Zoo812\", \"Kormkom\", \"Happypet\"]\n\nshops_map = {\n\t\tshops_list[0]:\tPETSHOP_FRESHSTEP_URL,\n\t\tshops_list[1]:\tZOO812_FRESHSTEP_URL,\n\t\tshops_list[2]:\tKORMKOM_FRESHSTEP_URL,\n\t\tshops_list[3]:\tHAPPYPET_FRESHSTEP_URL\n\t}\n\ndef get_html(url):\n\tresponse = urllib2.urlopen(url)\n\treturn response.read()\n\n\ndef parse_html(shop_key):\n\n\thtml = get_html(shops_map[shop_key])\n\tsoup = BeautifulSoup(html, \"lxml\")\n\n\tprices = {}\n\tif shops_list[0] == shop_key:\n\t\ttype_inst = soup.find_all('div', class_='type-inst')\n\t\toffer_price = soup.find_all('span', class_='j_offer_price offer_price')\n\n\t\tfor id in range(0, len(type_inst)):\n\t\t\tprice = offer_price[id].text.strip().split()\n\t\t\tkg = float(type_inst[id].text.split()[0].replace(',', '.'))\n\t\t\tif len(price) > 2:\n\t\t\t\tprices[kg] = int(price[0] + price[1])\n\t\t\telse:\n\t\t\t\tprices[kg] = int(price[0])\n\n\telif shops_list[1] == shop_key:\n\t\tkgs = soup.find_all('div', class_='large-2 columns name')\n\t\tcosts = soup.find_all('div', class_='large-2 columns price')\n\n\t\tfor id in range(0, len(kgs)):\n\t\t\tprice = costs[id].text.strip().split()\n\t\t\tkg = float(kgs[id].text.split()[0].replace(',', '.'))\n\t\t\tif len(price) > 2:\n\t\t\t\tprices[kg] = int(price[0] + price[1])\n\t\t\telse:\n\t\t\t\tprices[kg] = int(price[0])\n\n\telif shops_list[2] == shop_key:\n\t\tproduct_info_cost = soup.find('ul', id='productInfoCost')\n\n\t\tfor price in product_info_cost.find_all('li'):\n\t\t\tkg = float(price.span.text.split()[0].replace(',', '.'))\n\t\t\tprices[kg] = int(price.find('p', class_='p2').text.split()[0])\n\telif shops_list[3] == shop_key:\n\t\tkgs = soup.find_all('div', class_='sku-weight-card sku-weight-card-nocolor')\n\t\tcosts = soup.find_all('div', class_='sku-price-card')\n\n\t\tfor id in range(0, len(kgs)):\n\t\t\tprice = costs[id].text.strip().split()\n\t\t\tkg = float(kgs[id].text.split()[0].replace(',', '.'))\n\t\t\tif len(price) > 7:\n\t\t\t\tprices[kg] = int(price[0] + price[1])\n\t\t\telse:\n\t\t\t\tprices[kg] = int(price[0])\n\telse:\n\t\treturn None\n\n\treturn prices\n\n\ndef getRowId(floatWeight):\n\n\tTRESHOLD = 0.5\n\tif abs(3.2 - floatWeight) < TRESHOLD:\n\t\treturn 1\n\telif abs(6.35 - floatWeight) < TRESHOLD:\n\t\treturn 2\n\telif abs(9.52 - floatWeight) < TRESHOLD:\n\t\treturn 3\n\telif abs(15.9 - floatWeight) < TRESHOLD:\n\t\treturn 4\n\telse:\n\t\treturn None\n\n\ndef getColId(strShop):\n\n\tif shops_list[0] == strShop:\n\t\treturn 1\n\telif shops_list[1] == strShop:\n\t\treturn 2\n\telif shops_list[2] == strShop:\n\t\treturn 3\n\telif shops_list[3] == strShop:\n\t\treturn 4\n\telse:\n\t\treturn None\n\n\ndef save_prices(price_list, path):\n\n\twb = xlsxwriter.Workbook(path)\n\tws = wb.add_worksheet(\"FreshStep\")\n\tws.set_tab_color('#8DB4E3')\n\n\theaderFmt = wb.add_format()\n\theaderFmt.set_bg_color('#538ED5')\n\theaderFmt.set_border(2)\n\theaderFmt.set_border_color(\"#FFFFFF\")\n\theaderFmt.set_align('center')\n\theaderFmt.set_align('vcenter')\n\theaderFmt.set_font_color(\"#FFFFFF\")\n\theaderFmt.set_bold()\n\n\tcornerFmt = wb.add_format()\n\tcornerFmt.set_bg_color('#FFFFFF')\n\tcornerFmt.set_border(2)\n\tcornerFmt.set_border_color(\"#FFFFFF\")\n\tcornerFmt.set_align('center')\n\tcornerFmt.set_align('vcenter')\n\tcornerFmt.set_font_color(\"#00007F\")\n\tcornerFmt.set_bold()\n\n\tweightFmt = wb.add_format()\n\tweightFmt.set_bg_color('#376091')\n\tweightFmt.set_border(2)\n\tweightFmt.set_border_color(\"#FFFFFF\")\n\tweightFmt.set_align('center')\n\tweightFmt.set_align('vcenter')\n\tweightFmt.set_font_color(\"#FFFFFF\")\n\tweightFmt.set_bold()\n\n\tgeneralFmt = wb.add_format()\n\tgeneralFmt.set_bg_color('#DBE5F1')\n\tgeneralFmt.set_align('center')\n\tgeneralFmt.set_align('vcenter')\n\tgeneralFmt.set_right(2)\n\tgeneralFmt.set_right_color(\"#FFFFFF\")\n\n\tbestPriceFmt = wb.add_format()\n\tbestPriceFmt.set_bg_color('#55FF7F')\n\tbestPriceFmt.set_align('center')\n\tbestPriceFmt.set_align('vcenter')\n\tbestPriceFmt.set_right(2)\n\tbestPriceFmt.set_right_color(\"#FFFFFF\")\n\n\tshopRowIdxConst = weightColIdxConst = 0\n\n\tws.set_column(weightColIdxConst, weightColIdxConst, 20)\n\tws.write(shopRowIdxConst, weightColIdxConst, \"FreshStep\", cornerFmt)\n\n\tpriceMtrx = {}\n\tfor kg in sorted(price_list[0][shops_list[0]].keys()):\n\t\tws.write(getRowId(kg), weightColIdxConst, str(kg) + \" kg\", weightFmt)\n\t\tfor shop in shops_list:\n\t\t\tws.write(getRowId(kg), getColId(shop), \"---\", generalFmt)\n\t\t\tpriceMtrx[(getRowId(kg), getColId(shop))] = 1000000\n\n\tfor shop in price_list:\n\t\tfor shop_key, price_value in shop.items():\n\t\t\tws.set_column(getColId(shop_key), getColId(shop_key), 20)\n\t\t\tws.write(shopRowIdxConst, getColId(shop_key), shop_key, headerFmt)\n\t\t\tfor kg, price in price_value.items():\n\t\t\t\tws.write(getRowId(kg), getColId(shop_key), str(price) + \" rub\", generalFmt)\n\t\t\t\tpriceMtrx[(getRowId(kg), getColId(shop_key))] = price\n\n\tmin_prices = {}\n\tfor row in range(1, len(price_list[0][shops_list[0]].keys())+1):\n\t\tmin = 1000000\n\t\tfor col in range(1, len(shops_list)+1):\n\t\t\tif priceMtrx[(row, col)] < min:\n\t\t\t\tmin = priceMtrx[(row, col)]\n\t\tfor col in range(1, len(shops_list)+1):\n\t\t\tif priceMtrx[(row, col)] == min:\n\t\t\t\tws.write(row, col, str(min) + \" rub\", bestPriceFmt)\n\n\twb.close()\n\n\ndef main():\n\n\tprice_list = []\n\tfor key, value in shops_map.items():\n\t\tprice_list.append({\n\t\t\tkey: parse_html(key)\n\t\t})\n\n\tsave_prices(price_list, os.path.join(os.getcwd(), \"FreshStep.xlsx\"))\n\tprint(\"ALL DONE\")\n\n\nif __name__ == '__main__':\n\tmain()\n","sub_path":"python_projects/scripts/parsing_sites/FreshStep.py","file_name":"FreshStep.py","file_ext":"py","file_size_in_byte":5861,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"480187128","text":"#-------------------------------------------------------------------------------\r\n# Name: module2\r\n# Purpose:\r\n#\r\n# Author: Азат\r\n#\r\n# Created: 28.11.2018\r\n# Copyright: (c) Азат 2018\r\n# Licence: \r\n#-------------------------------------------------------------------------------\r\n\r\n\r\nfrom tkinter import *\r\n\r\n\r\nroot = Tk()\r\n\r\nbutton1 = Button(root, text = u'1', width=8, height = 4)\r\nbutton2 = Button(root, text = u'2', width=8, height = 4)\r\nbutton3 = Button(root, text = u'3', width=8, height = 4)\r\n\r\nbutton4 = Button(root, text = u'4', width=8, height = 4)\r\nbutton5 = Button(root, text = u'5', width=8, height = 4)\r\nbutton6 = Button(root, text = u'6', width=8, height = 4)\r\n\r\nbutton7 = Button(root, text = u'7', width=8, height = 4)\r\nbutton8 = Button(root, text = u'8', width=8, height = 4)\r\nbutton9 = Button(root, text = u'9', width=8, height = 4)\r\n\r\nbutton10 = Button(root, text = u'0', width=8, height = 4)\r\nbutton16 = Button(root, text = u'.', width=8, height = 4)\r\nbutton11 = Button(root, text = u'C', width=8, height = 4)\r\n\r\nbutton12 = Button(root, text = u'+', width=8, height = 4)\r\nbutton13 = Button(root, text = u'-', width=8, height = 4)\r\nbutton14 = Button(root, text = u'*', width=8, height = 4)\r\nbutton15 = Button(root, text = u'/', width=8, height = 4)\r\n\r\nbutton17 = Button(root, text = u'=', width=50, height = 2)\r\n\r\nlabel1 = Label(root, width=50)\r\nentry1 = Entry(root, width=50, bd = 20)\r\n\r\n##entry1.place(x = '10', y = '10')\r\n##button1.place(x = '1', y = '5')\r\n##button2.place(x = '-20', y = '5')\r\n##button3.place(x = '40', y = '30')\r\n##button17.place(x = '20', y = '30')\r\n\r\nentry1.grid(row = 0, column = 0, columnspan = 5)\r\nlabel1.grid(row = 1, column = 0, columnspan = 5)\r\n\r\nbutton1.grid(row = 4, column = 0)\r\nbutton2.grid(row = 4, column = 1)\r\nbutton3.grid(row = 4, column = 2)\r\nbutton4.grid(row = 3, column = 0)\r\nbutton5.grid(row = 3, column = 1)\r\nbutton6.grid(row = 3, column = 2)\r\nbutton7.grid(row = 2, column = 0)\r\nbutton8.grid(row = 2, column = 1)\r\nbutton9.grid(row = 2, column = 2)\r\n\r\nbutton10.grid(row = 5, column = 0)\r\nbutton16.grid(row = 5, column = 1)\r\nbutton11.grid(row = 5, column = 2)\r\n\r\nbutton12.grid(row = 2, column = 3)\r\nbutton13.grid(row = 3, column = 3)\r\nbutton14.grid(row = 4, column = 3)\r\nbutton15.grid(row = 5, column = 3)\r\n\r\nbutton17.grid(row = 6, column = 0, columnspan = 4)\r\n\r\nroot.mainloop()\r\n\r\n\r\nbutton1.bind('', label1 = '1')\r\nbutton2.bind('', label1 = '2')\r\nbutton3.bind('', label1 = '3')\r\nbutton4.bind('', label1 = '4')\r\nbutton5.bind('', label1 = '5')\r\nbutton6.bind('', label1 = '6')\r\nbutton7.bind('', label1 = '7')\r\nbutton8.bind('', label1 = '8')\r\nbutton9.bind('', label1 = '9')\r\nbutton10.bind('', label1 = '0')\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n##root = Tk()\r\n##text1 = Text(root, height = 7, width = 7, font = 'Arial 14', wrap = WORD)\r\n##\r\n##text1.pack()\r\n##root.mainloop()\r\n##def leftklick(root):\r\n## print(' Вы нажали левую кнопку мыши')\r\n##def rightklick(root):\r\n## print(' Вы нажали правую кнопку мыши')\r\n##button1 = Button(root, text = u'Нажми')\r\n##button1.pack()\r\n##button1.bind('', leftklick)\r\n##button1.bind('', rightklick)\r\n##root.mainloop()\r\n\r\n##button1 = Button(root, text = 'OK', width = 25, height = 5, bg = 'black', fg = 'red', font = 'arial 14')\r\n##button1.pack()\r\n##root.mainloop()\r\n","sub_path":"Tkinter.Calck.py","file_name":"Tkinter.Calck.py","file_ext":"py","file_size_in_byte":3508,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"296206116","text":"# wx 20160908\n\n\nimport numpy as np\nimport math\nimport sympy\nimport matplotlib.pyplot as plt\nimport statsmodels.api as sm\nfrom scipy.optimize import leastsq\nimport random\nimport copy\n\n\n\ndef coarseGrain(field, coarseShape):\n rowFine = field.shape[0]\n rowRatio = sympy.S(rowFine) / coarseShape[0]\n coarseField = np.zeros((coarseShape), np.float)\n\n \"二维\"##################\n collumFine = field.shape[1]\n collumRatio = sympy.S(collumFine) / coarseShape[1]\n right = 0\n for i in range(0, coarseShape[0]):\n left = right\n right = left + rowRatio\n window_h = np.zeros((math.ceil(right) - math.floor(left)), np.float)\n\n for k in range(int(math.floor(left)), int(math.ceil(right))):\n if (k == math.floor(left)):\n window_h[k - math.floor(left)] = math.floor(left) + 1 - left\n # print(window_h[k-math.floor(left)])\n elif (k == math.ceil(right) - 1):\n window_h[k - math.floor(left)] = right + 1 - math.ceil(right)\n # print(window_h[k-math.floor(left)])\n else:\n window_h[k - math.floor(left)] = 1\n window_h.shape = 1, len(window_h)\n # print(window_h)\n top = 0\n for j in range(0, coarseShape[1]):\n bottom = top\n top = bottom + collumRatio\n\n window_v = np.zeros((math.ceil(top) - math.floor(bottom)), np.float)\n for k in range(int(math.floor(bottom)), int(math.ceil(top))):\n if (k == math.floor(bottom)):\n window_v[k - math.floor(bottom)] = math.floor(bottom) + 1 - bottom\n elif (k == math.ceil(top) - 1):\n window_v[k - math.floor(bottom)] = top + 1 - math.ceil(top)\n else:\n window_v[k - math.floor(bottom)] = 1\n # print(window_v)\n window_v.shape = len(window_v), 1\n window = window_h * window_v\n window = np.transpose(window)\n coarseField[i, j] = np.sum(\n window * field[math.floor(left):math.ceil(right), math.floor(bottom):math.ceil(top)])\n\n # print(coarseField)\n return coarseField\n\n\ndef normalize(field):\n sumField = np.sum(field)\n if (sumField > 0):\n return field / sumField\n else:\n return field\n\n\n\"通过统计矩法求一个降雨场的多重分形,计算所需的各种参数如统计矩moment,尺度兰布达,矩的阶q,以及质量指数函数tao(q)\"\n\n\ndef mutifractalAnalysis(rawfield, branch=2):\n \"首先将消除趋势波动(Detrended Fluctuation)降水场归一化\"\n field = normalize(rawfield)\n # field=rawfield\n fieldSize = field.shape[0]\n layers = np.arange(0, int(math.log(fieldSize, branch)))\n scales = branch ** layers\n print(\"layers:\", layers, \"scales:\", scales)\n q = np.linspace(-5, 5, 11)\n moment = np.zeros((len(layers), len(q)))\n\n \"求moment\"\n for i in range(0, len(layers)):\n for j in range(0, len(q)):\n distrib = coarseGrain(field, [x // scales[i] for x in field.shape]) ##################\n positiveDist = distrib[distrib > 0]\n # sum_positiveDist=np.sum(positiveDist)\n moment[i, j] = np.sum(positiveDist ** q[j])\n # print(\"distrib\",distrib,\"q[j]\",q[j],\"moment[i,j]\",moment[i,j])\n\n \"求tao(q),tao(q)就是斜率\"\n k1 = np.zeros(moment.shape[1]) # 存放斜率\n b1 = np.zeros(moment.shape[1]) # 存放截距\n R1_Squared = np.zeros(moment.shape[1]) # 存放R2\n # k2=np.zeros(positiveDist[1])\n # b2=np.zeros(positiveDist[1])\n # R2_Squared=np.zeros(moment.shape[1])\n lambd = scales\n X = np.log(lambd) / np.log(2) # log以2为底的lambda,线性最小二乘的X输入\n X = sm.add_constant(X.T) # 加上截距项\n # for i in range(0,positiveDist.shape[1]):\n # Y2=np.log(positiveDist[:,i])/np.log(2)\n # results2=sm.OLS(Y2,X).fit()\n # k2[i]=results2.params[1]\n # b2[i]=results2.params[0]\n # R2_Squared[i]=results2.rsquared\n # print(\"k2\",k2[i],\"b2\",b2[i],\"r22\",R2_Squared[i])\n for i in range(0, moment.shape[1]):\n Y1 = np.log(moment[:, i]) / np.log(2) # log以2为底的moment,线性最小二乘的X输入\n results1 = sm.OLS(Y1, X).fit() # log以2为底的moment和lambda的线性拟合\n k1[i] = results1.params[1] # 斜率\n b1[i] = results1.params[0] # 截距\n R1_Squared[i] = results1.rsquared\n print(\"k1\", k1[i], \"b1\", b1[i], \"r21\", R1_Squared[i])\n\n plotMoment_lambd(scales, q, k1, b1, moment, R1_Squared)\n plotD_q(k1, q)\n return (scales, q, k1, b1, moment, R1_Squared)\n\n\n\"勒让德变化求多重分形维谱f(a)\"\n\n\ndef legendre(rawfield, branch=2):\n field = normalize(rawfield)\n fieldSize = field.shape[0]\n layer = np.arange(0, int(math.log(fieldSize, branch)))\n scale = branch ** layer\n q = np.linspace(-5, 5, 11)\n alpha = np.zeros((len(scale), len(q)))\n f_alpha = np.zeros((len(scale), len(q)))\n a = np.zeros((len(q)))\n f = np.zeros((len(q)))\n for i in range(0, len(scale)):\n for j in range(0, len(q)):\n distrib = coarseGrain(field, [x // scale[i] for x in field.shape])\n positiveDist = distrib[distrib > 0]\n qmass = positiveDist ** q[j]\n alpha[i, j] = np.sum((qmass * np.log(positiveDist)) / np.sum(qmass))\n # f_alpha[i,j]=(q[j]*np.sum(qmass*np.log(positiveDist))-np.sum(qmass)*np.log(np.sum(qmass)))/np.sum(qmass)\n f_alpha[i, j] = q[j] * alpha[i, j] - np.log(np.sum(qmass))\n for j in range(0, len(q)):\n line1 = np.polyfit(np.log(1.0 * scale), alpha[:, j], 1)\n line2 = np.polyfit(np.log(1.0 * scale), f_alpha[:, j], 1)\n a[j] = line1[0]\n f[j] = line2[0]\n\n plotSpectrum(a, f)\n\n print(\"a:\", a, \"f:\", f)\n return (a, f)\n\n\n\"绘制log以2为底的moment和lambda的图\"\n\ndef plotMoment_lambd(scale, q, k, b, moment, rsquared, name=\"\"):\n plt.figure(1)\n lambd = scale\n x = np.log(lambd) / np.log(2)\n for j in range(0, moment.shape[1]):\n y = np.log(moment[:, j]) / np.log(2)\n plt.scatter(x, y)\n plt.plot(x, k[j] * x + b[j], \"-\")\n plt.text(x[0], y[0], 'q=' + str(q[j])[0:4], rotation=-5)\n# plt.text(x[-3], y[-3], 'q=' + str(q[j])[0:4] + ',$R^2=$' + str(rsquared[j])[0:6],rotation=-5) # 将q和r2的值显示在图上,以及显示的位置\n plt.xlim(-5, 7)\n plt.ylim(-50, 100)\n plt.xlabel(r'$Log_2[\\lambda]$')\n plt.ylabel(r'$Log_2[M(\\lambda,q)]$')\n # plt.savefig('C:/Users/xia/Desktop/20060101vs20060622vs20061025/TRMM3b43200606/'+\"momentscale20060625256\"+name+\".png\",dpi=300)\n plt.savefig('C:/Users/xia/Desktop/新实验/201003/' + \"momentscale201003303232\" + name + \".png\", dpi=300)\n # plt.close(1)\n\n\ndef plotD_q(k, q, name=\"\"):\n plt.figure(2)\n taoq = -k\n d1_taoq = (taoq[1:] - taoq[0:-1]) / (q[1:] - q[0:-1])\n for i in range(0, len(q)):\n if (q[i] != 1):\n D_q = taoq / (q[i] - 1)\n else:\n D_q = d1_taoq[i]\n # print(\"D(q):\",D_q)\n plt.plot(q, D_q, \"-o\", label=name,color='blue')\n plt.plot((list(q)[0], list(q)[-1]), (list(D_q)[0], list(D_q)[-1]),color='red')\n plt.xlabel(r'$q$')\n plt.ylabel(r'$D(q)$')\n# plt.legend(['data', 'linear', 'cubic'], loc='best')\n plt.savefig('C:/Users/xia/Desktop/新实验/201003/' + \"Dq201003303232\" + name + \".png\", dpi=300)\n # plt.close(2)\n\n\n\"绘制累积曲线图\"\n\n\ndef plotSpectrum(a, f, name=\"\"):\n plt.figure(3)\n plt.plot(a, f, '-o', label=name,color='blue')\n plt.xlabel(r'${\\alpha}$')\n plt.ylabel(r\"$f(\\alpha)$\")\n #plt.title(\"多重分形谱\")\n plt.legend()\n # plt.savefig('C:/Users/xia/Desktop/20060101vs20060622vs20061025/TRMM3b43200606/'+\"Spectrum20060625256\"+name+\".png\",dpi=300)\n plt.savefig('C:/Users/xia/Desktop/新实验/201003/' + \"Spectrum201003303232\" + name + \".png\", dpi=300)\n # plt.close(3)\n\n\n\"利用taoq和q求beta和sigma\"\n\n\n#def lognormalBetaFit(q, taoq):\n# d = 2\n# b = 2\n# d1_taoq = (taoq[1:] - taoq[0:-1]) / (q[1:] - q[0:-1])\n# print(\"taoq[1:]:\", taoq[1:], \"taoq[0:-1]:\", taoq[0:-1], \"q[1:]:\", q[1:], \"q[0:-1]:\", q[0:-1])\n# d2_taoq = (d1_taoq[1:] - d1_taoq[0:-1]) / (q[1:-1] - q[0:-2])\n# # print(\"d1_taoq[1:]:\",d1_taoq[1:],\"d1_taoq[0:-1]:\",d1_taoq[0:-1],\"q[1:-1]:\",q[1:-1],\"q[0:-2]:\",q[0:-2])\n# # print(d2_taoq)\n# for i in range(0, len(d2_taoq)):\n# if (q[i + 1] >= 1):\n# print(\"i:\", i, \"q[i+1]:\", q[i + 1], \"q[i]:\", q[i])\n# sigma2 = d2_taoq[i] / (d * np.log(b))\n# beta = 1 + d1_taoq[i] / d - sigma2 * (np.log(b) / 2) * (2 * q[i + 1] - 1)\n# # beta=1+d1_taoq[i]/d+sigma2*(np.log(b)/2)*(2*q[i+1]-1)\n# print(\"d1_taoq[i]:\", d1_taoq[i])\n# break\n# # beta=0\n# print(\"beta:\", beta, \"sigma^2:\", sigma2)\n# return beta, sigma2\n\ndef lognormalBetaFit(q, taoq):\n d = 2\n b = 2\n #gamma_alpha = 2\n #gamma_beta = 2\n #normal_sigma2 = 0.05\n d1_taoq = (taoq[1:] - taoq[0:-1]) / (q[1:] - q[0:-1])\n print(\"taoq[1:]:\", taoq[1:], \"taoq[0:-1]:\", taoq[0:-1], \"q[1:]:\", q[1:], \"q[0:-1]:\", q[0:-1])\n d2_taoq = (d1_taoq[1:] - d1_taoq[0:-1]) / (q[1:-1] - q[0:-2])\n # print(\"d1_taoq[1:]:\",d1_taoq[1:],\"d1_taoq[0:-1]:\",d1_taoq[0:-1],\"q[1:-1]:\",q[1:-1],\"q[0:-2]:\",q[0:-2])\n # print(d2_taoq)\n for i in range(0, len(d2_taoq)):\n if (q[i + 1] >= 1):\n print(\"i:\", i, \"q[i+1]:\", q[i + 1], \"q[i]:\", q[i])\n #gamma分布\n #sigma2 = (d2_taoq[i] * q[i+1]**2 * gamma_beta) / (d2_taoq[i] * q[i+1]**2 * np.log(b) - d*gamma_alpha)\n #print('sigma2:',sigma2)\n #beta = 1 + d1_taoq[i] / d - gamma_alpha * math.log((1 - sigma2 * math.log(b)),2) / gamma_beta - (sigma2 * gamma_alpha)/(q[i+1]*gamma_beta - q[i+1]*sigma2*math.log(b))\n #标准正态分布\n sigma2 = d2_taoq[i] / (d * np.log(b))\n #print('sigma2:', sigma2)\n beta=1+d1_taoq[i]/d+sigma2*(np.log(b)/2)*(2*q[i+1]-1)\n #正态分布\n #sigma2 = d2_taoq[i] / (d * normal_sigma2 * np.log(b))\n #beta = 1 + d1_taoq[i]/d + d2_taoq[i] / 2*d - d2_taoq[i]*q[i+1] / d\n print(\"d1_taoq[i]:\", d1_taoq[i])\n break\n # beta=0\n print(\"beta:\", beta, \"sigma^2:\", sigma2)\n return beta, sigma2\n\n\"利用beta和sigma求权重W,并分配给各网格,将0.25°的降水场降尺度到0.01°\"\n\n\n#def mfDownscaleField(field, beta, sigma2):\n# # n=4#8*8的\n# n = 6 # 32*32\n# b = 2\n# fieldMatrix = np.array([])\n# cascade = []\n# for i in range(0, n + 1):\n# cascade.append(np.empty((b ** i, b ** i), np.float))\n# temp1 = beta - sigma2 * np.log(2) / 2\n# temp2 = np.sqrt(sigma2)\n# # fieldN=normalize(field)#\n#\n# simfield = np.empty((32, 32))\n# for i in range(field.shape[0]):\n# for j in range(field.shape[1]):\n# cascade[0][0][0] = field[i, j]\n# for x in range(1, n + 1):\n# for y in range(0, b ** (x - 1)):\n# for z in range(0, b ** (x - 1)):\n# cascade[x][y * 2][z * 2] = cascade[x - 1][y][z] * b ** (temp1 + temp2 * random.gauss(0, 1) - 2)\n# cascade[x][y * 2][z * 2 + 1] = cascade[x - 1][y][z] * b ** (\n# temp1 + temp2 * random.gauss(0, 1) - 2)\n# cascade[x][y * 2 + 1][z * 2] = cascade[x - 1][y][z] * b ** (\n# temp1 + temp2 * random.gauss(0, 1) - 2)\n# cascade[x][y * 2 + 1][z * 2 + 1] = cascade[x - 1][y][z] * b ** (\n# temp1 + temp2 * random.gauss(0, 1) - 2)\n# simfield[:, :] = coarseGrain(cascade[n], (32, 32))\n# # print(\"simfield:\",simfield)\n# if (j == 0):\n# fieldRow = simfield.copy()\n# else:\n# fieldRow = np.hstack((fieldRow, simfield.copy()))\n# if (i == 0):\n# fieldMatrix = fieldRow.copy()\n# else:\n# fieldMatrix = np.vstack((fieldMatrix, fieldRow.copy()))\n# # np.savetxt('C:/Users/xia/Desktop/20060101vs20060622vs20061025/0607_1007/'+str(2006072010073030)+'_'+str(2)+'.'+\"txt\",fieldMatrix,fmt = '%.8f')\n# return (fieldMatrix)\n\ndef mfDownscaleField(field, beta, sigma2):\n # n=4#8*8的\n n = 6 # 32*32\n b = 2\n\n #gamma_alpha = 2\n #gamma_beta = 2\n #normal_sigma2 = 0.05\n #normal_sigma = np.sqrt(normal_sigma2)\n #normal_mu = 0\n fieldMatrix = np.array([])\n cascade = []\n for i in range(0, n + 1):\n cascade.append(np.empty((b ** i, b ** i), np.double))\n\n #标准正态分布\n temp2 = np.sqrt(sigma2)\n temp1 = beta - sigma2 * np.log(2) / 2\n\n #gamma分布\n #temp1 = beta + gamma_alpha * math.log((1-sigma2*math.log(b)),2) / gamma_beta\n #temp2 = sigma2\n #print('temp2,temp1:',temp2,temp1)\n\n #正态分布\n #temp2 = np.sqrt(sigma2)\n #temp1 = beta - temp2*normal_mu - normal_sigma2*sigma2*np.log(b) / 2\n\n simfield = np.empty((32, 32))\n for i in range(field.shape[0]):\n for j in range(field.shape[1]):\n cascade[0][0][0] = field[i, j]\n for x in range(1, n + 1):\n for y in range(0, b ** (x - 1)):\n for z in range(0, b ** (x - 1)):\n cascade[x][y * 2][z * 2] = cascade[x - 1][y][z] * b ** (temp1 + temp2 * random.gauss(0,0.05))\n cascade[x][y * 2][z * 2 + 1] = cascade[x - 1][y][z] * b ** (temp1 + temp2 * random.gauss(0,0.05))\n cascade[x][y * 2 + 1][z * 2] = cascade[x - 1][y][z] * b ** (temp1 + temp2 * random.gauss(0,0.05))\n cascade[x][y * 2 + 1][z * 2 + 1] = cascade[x - 1][y][z] * b ** (temp1 + temp2 * random.gauss(0,0.05))\n #cascade[x][y * 2][z * 2] = cascade[x - 1][y][z] * b **(temp1 + temp2 * random.lognormvariate(0.102470841488,0.897529158512))\n #cascade[x][y * 2][z * 2 + 1] = cascade[x - 1][y][z] * b **(temp1 + temp2 * random.lognormvariate(0.102470841488,0.897529158512))\n #cascade[x][y * 2 + 1][z * 2] = cascade[x - 1][y][z] * b ** (temp1 + temp2 * random.lognormvariate(0.102470841488,0.897529158512))\n #cascade[x][y * 2 + 1][z * 2 + 1] = cascade[x - 1][y][z] * b ** (temp1 + temp2 * random.lognormvariate(0.102470841488,0.897529158512))\n simfield[:, :] = coarseGrain(cascade[n], (32, 32))\n # print(\"simfield:\",simfield)\n if (j == 0):\n fieldRow = simfield.copy()\n else:\n fieldRow = np.hstack((fieldRow, simfield.copy()))\n if (i == 0):\n fieldMatrix = fieldRow.copy()\n else:\n fieldMatrix = np.vstack((fieldMatrix, fieldRow.copy()))\n # np.savetxt('C:/Users/xia/Desktop/20060101vs20060622vs20061025/0607_1007/'+str(2006072010073030)+'_'+str(2)+'.'+\"txt\",fieldMatrix,fmt = '%.8f')\n return (fieldMatrix)\n\n\ndef main():\n res = 0.25\n \"数据处理\"\n trmm3b43_1D = {}\n trmm3b43_1D = np.loadtxt('C:/Users/xia/Desktop/新实验/201003/20100330_trmm_3232.txt')\n trmm3b43 = {}\n trmm3b43[1998] = np.array(trmm3b43_1D).reshape(32, 32)\n for i in range(0, 32):\n for j in range(0, 32):\n if (trmm3b43[1998][i,j]<0):\n trmm3b43[1998][i, j]=0\n else:\n trmm3b43[1998][i, j]=trmm3b43[1998][i,j]\n\n trmm3b43NormAver_1D = {}\n trmm3b43NormAver_1D = np.loadtxt(\n 'C:/Users/xia/Desktop/新实验/200603_201003_Ave/200603_201003_LTNM_DEM_NDVIAVG_025.txt')\n trmm3b43NormAver = {}\n trmm3b43NormAver[1] = np.array(trmm3b43NormAver_1D).reshape(32, 32)\n\n GWR_1D = {}\n GWR_1D = np.loadtxt(\n 'C:/Users/xia/Desktop/新实验/200603_201003_Ave/GWR/LTNM_DEM_NDVIAVG/200603_201003_LTNM_DEM_NDVIAvg_00078125_Z.txt')\n #GWR_1D = np.loadtxt('C:/Users/xia/Desktop/新实验/2007/200702/200702_G_LTNA_NDVI_DEM.txt')\n GWR = {}\n GWR[1] = np.array(GWR_1D).reshape(1024, 1024)\n for i in range(0, 1024):\n for j in range(0, 1024):\n if (GWR[1][i,j]<0):\n GWR[1][i, j]=0\n else:\n GWR[1][i, j]=GWR[1][i,j]\n\n \"匀质化\"\n trmm3b43Detrend = {}\n trmm3b43Detrend[199801] = np.empty((32, 32),np.double)\n for i in range(0, 32):\n for j in range(0, 32):\n if (trmm3b43NormAver[1][i, j] > 0):\n trmm3b43Detrend[199801][i, j] = trmm3b43[1998][i, j] / trmm3b43NormAver[1][i, j]\n else:\n trmm3b43Detrend[199801][i, j] = 0\n\n \"多重分形过程\"\n print(\"trmm3b43Detrend:\", trmm3b43Detrend[199801])\n combinedField_1D = {}\n combinedField = np.empty((32 * 32, 32 * 32),np.double)\n \"计算奇异值α和多重分形谱f(α),实际还是用统计矩计算广义分型维度,再以勒让德变化得出的,确认具有分形特征\"\n a, f = legendre(trmm3b43Detrend[199801]) ##########################################################################################\n # a,f=legendre(trmm3b43[1998])\n # scales,q,k,b,moment,R_Squared=mutifractalAnalysis(trmm3b43[1998])\n \"从32*32到1*1,用往上聚合的方法,以广义分型维度法D(q),确认具有分形特征\"\n scales, q, k, b, moment, R_Squared = mutifractalAnalysis(trmm3b43Detrend[199801])\n \"前面都只是确认具有分形特征,所以从32*32聚合计算到1*1,\"\n \"q取-5到5是为了确认具有多重分形特征,即函数为单调凸函数\"\n\n \"计算taoq与q,得到权重β和σ\"\n taoq = -k\n beta, sigma2 = lognormalBetaFit(q, taoq)\n print(\"taoq:\", taoq, \"q:\", q)\n \"多层级联计算降水值。实际上级联的时候,只取q=1时的β和σ\"\n detrendField = mfDownscaleField(trmm3b43Detrend[199801], beta, sigma2) ##100次的时候要隐掉\n\n # detrendField=mfDownscaleField(trmm3b43[1998],beta,sigma2)\n \"循环100次,每次得到的结果单独输出,最后在main2里面批量累加求平均\"\n# for count in range(1,50):\n# detrendField = mfDownscaleField(trmm3b43Detrend[199801], beta, sigma2)\n# for i in range(0, 32):\n# for j in range(0, 32):\n# #temp1 = trmm3b43NormAver[1][i, j] * detrendField[i * 32:(i + 1) * 32, j * 32:(j + 1) * 32]\n# temp1 = GWR[1][i * 32:(i + 1) * 32, j * 32:(j + 1) * 32] * detrendField[i * 32:(i + 1) * 32,j * 32:(j + 1) * 32]\n# if (np.sum(temp1) != 0):\n# temp2 = temp1 / np.sum(temp1)\n# else:\n# temp2 = 0\n# # combinedField[i*25:(i+1)*25,j*25:(j+1)*25]=temp1*trmm3b43[1998][i,j]\n# combinedField[i * 32:(i + 1) * 32, j * 32:(j + 1) * 32] = temp2 * trmm3b43[1998][i, j] * (32 ** 2)\n# combinedField_1D = np.array(combinedField).reshape(1048576, 1)\n# np.savetxt('C:/Users/xia/Desktop/新实验/201003/20100330_gauss_no_zero_Gmf/'+str(201003303232)+ '_gauss_no_zero_Gmf'+str(count)+'.'+\"txt\",combinedField_1D,fmt = '%.8f')\n\n\n \"没有用trmm3b43Detrend[199801]\"\n##恢复异质性\n for i in range(0, 32):\n for j in range(0, 32):\n temp1 = trmm3b43NormAver[1][i, j] * detrendField[i * 32:(i + 1) * 32, j * 32:(j + 1) * 32]\n temp1=GWR[1][i*32:(i+1)*32,j*32:(j+1)*32]*detrendField[i*32:(i+1)*32,j*32:(j+1)*32]\n if (np.sum(temp1) != 0):\n temp2 = temp1 / np.sum(temp1)\n else:\n temp2 = 0\n # combinedField[i*25:(i+1)*25,j*25:(j+1)*25]=temp1*trmm3b43[1998][i,j]\n combinedField[i * 32:(i + 1) * 32, j * 32:(j + 1) * 32] = temp2 * trmm3b43[1998][i, j] * (32 ** 2)\n combinedField_1D = np.array(combinedField).reshape(1048576, 1)\n np.savetxt('C:/Users/xia/Desktop/新实验/201003/20100330_gauss_no_zero_Gmf/'+str(201003303232)+ '_gauss005_no_zero_Gmf'+ '.' + \"txt\", combinedField_1D, fmt='%.8f')\n\nmain()\n\ndef main1():\n trmm3b43 = {}\n trmm3b43[1998] = np.loadtxt('C:/Users/xia/Desktop/新实验/2006/200620_trmm_3232.txt')\n\n trmm3b43NormAver = {}\n trmm3b43NormAver[1] = np.loadtxt(\n 'C:/Users/xia/Desktop/20060101vs20060622vs20061025/20080710/0607_1007_025AVE_R.txt')\n\n GWR = {}\n GWR[1] = np.loadtxt(\n 'C:/Users/xia/Desktop/新实验/200601_201001_Avg/GWR/LTDM_DEM_NDVIMin/200601_201001_LTDM_DEM_NDVIMin_00078125_Z.txt')\n detrendField = np.empty((32 * 32, 32 * 32))\n detrendGWR = np.empty((32 * 32, 32 * 32))\n combinedField = np.loadtxt('C:/Users/xia/Desktop/20060101vs20060622vs20061025/20080710/200807103030.txt')\n for i in range(0, 32):\n for j in range(0, 32):\n if (trmm3b43[1998][i, j] == 0):\n temp1 = 0\n else:\n temp1 = combinedField[i * 30:(i + 1) * 30, j * 30:(j + 1) * 30] / trmm3b43[1998][i, j]\n if (trmm3b43NormAver[1][i, j] == 0):\n detrendField[i * 30:(i + 1) * 30, j * 30:(j + 1) * 30] = 0\n else:\n detrendField[i * 30:(i + 1) * 30, j * 30:(j + 1) * 30] = temp1 / trmm3b43NormAver[1][i, j]\n temp2 = detrendField[i * 30:(i + 1) * 30, j * 30:(j + 1) * 30] * GWR[1][i * 30:(i + 1) * 30,\n j * 30:(j + 1) * 30]\n temp3 = temp2 / np.sum(temp2) # normalizing\n detrendGWR[i * 30:(i + 1) * 30, j * 30:(j + 1) * 30] = temp3 * trmm3b43[1998][\n i, j] * 30 ** 2 # large scale forcing\n\n np.savetxt('C:/Users/xia/Desktop/20060101vs20060622vs20061025/20080710/' + str(\n 200807103030) + '_' + 'combine' + '.' + \"txt\", detrendGWR, fmt='%.8f')\n\n\ndef main2():\n Field = {}\n #Field_1D={}\n Sum_Field = 0.0\n Ave_Field = 0.0\n# Field[10] = np.loadtxt(\n# 'C:/Users/xia/Desktop/新实验/2007/200702100_gamma_no_zero_hb_n/2007023232_mf10.txt')\n# Field_1D[10] = np.array(Field[10]).reshape(1048576, 1)\n for count in range(1, 50):\n Field[count] = np.loadtxt( 'C:/Users/xia/Desktop/新实验/201003/20100330_gauss_no_zero_Gmf/' + str(201003303232)+'_gauss_no_zero_Gmf'+str(count)+ '.' + \"txt\")\n #Field_1D[count] = np.array(Field[count]).reshape(1048576, 1)\n Sum_Field += Field[count]\n Ave_Field = Sum_Field / 50\n np.savetxt('C:/Users/xia/Desktop/新实验/201003/20100330_gauss_no_zero_Gmf/' + str(201003303232) + '_gauss_no_zero_Gmf_Ave'+ '.txt',Ave_Field, fmt='%.8f')\n\n#main2()\ndef main3():\n res = 0.25\n \"数据处理\"\n trmm3b43_hb_ID = {}\n trmm3b43_hb_ID = np.loadtxt('C:/Users/xia/Desktop/新实验/200702/20070228_trmm_3232.txt')\n #trmm3b43_3232 = {}\n #trmm3b43_3232=np.zeros((1024,1),np.double)\n #for i in range(0,len(trmm3b43_hb_ID)):\n # trmm3b43_3232[int(trmm3b43_hb_ID[i][0])]=trmm3b43_hb_ID[i][1]\n\n trmm3b43 = {}\n\n trmm3b43[1998] = np.array(trmm3b43_hb_ID).reshape(32, 32)\n\n trmm3b43NormAver_1D = {}\n trmm3b43NormAver_1D = np.loadtxt(\n 'C:/Users/xia/Desktop/新实验/200602_201002_Avg/200602_201002_LTNA_DEM_NDVIMax_025.txt')\n trmm3b43NormAver = {}\n trmm3b43NormAver[1] = np.array(trmm3b43NormAver_1D).reshape(32, 32)\n GWR_1D = {}\n GWR_1D = np.loadtxt(\n 'C:/Users/xia/Desktop/新实验/200602_201002_Avg/GWR/GWR_LTNA_DEM_NDVIMax/200602_201002_LTNA_DEM_NDVIMax_00078125_Z.txt')\n GWR = {}\n GWR[1] = np.array(GWR_1D).reshape(1024, 1024)\n for i in range(0, 1024):\n for j in range(0, 1024):\n if (GWR[1][i, j] < 0):\n GWR[1][i, j] = 0\n else:\n GWR[1][i, j] = GWR[1][i, j]\n\n trmm3b43Detrend = {}\n trmm3b43Detrend[199801] = np.empty((32, 32), np.double)\n for i in range(0, 32):\n for j in range(0, 32):\n if (trmm3b43NormAver[1][i, j] > 0):\n trmm3b43Detrend[199801][i, j] = trmm3b43[1998][i, j] / trmm3b43NormAver[1][i, j]\n else:\n trmm3b43Detrend[199801][i, j] = 0\n\n \"多重分形过程\"\n print(\"trmm3b43Detrend:\", trmm3b43Detrend[199801])\n combinedField_1D = {}\n combinedField = np.empty((32 * 32, 32 * 32), np.double)\n a, f = legendre(trmm3b43Detrend[199801])\n # a,f=legendre(trmm3b43[1998])\n # scales,q,k,b,moment,R_Squared=mutifractalAnalysis(trmm3b43[1998])\n scales, q, k, b, moment, R_Squared = mutifractalAnalysis(trmm3b43Detrend[199801])\n\n taoq = -k\n beta, sigma2 = lognormalBetaFit(q, taoq)\n print(\"taoq:\", taoq, \"q:\", q)\n\n detrendField = mfDownscaleField(trmm3b43Detrend[199801], beta, sigma2)\n\n # detrendField=mfDownscaleField(trmm3b43[1998],beta,sigma2)\n \"循环100次\"\n # for count in range(1,101):\n # detrendField=mfDownscaleField(trmm3b43Detrend[199801],beta,sigma2)\n # for i in range(0,32):\n # for j in range(0,32):\n # temp1=trmm3b43NormAver[1][i,j]*detrendField[i*30:(i+1)*30,j*30:(j+1)*30]\n # temp2=temp1/np.sum(temp1)*30**2\n # combinedField[i*30:(i+1)*30,j*30:(j+1)*30]=temp2*trmm3b43[1998][i,j]\n # combinedField_1D=np.array(combinedField).reshape(921600,1)\n # np.savetxt('C:/Users/xia/Desktop/新实验/201007/'+str(2010073030)+'_Fmf_1D'+'.'+\"txt\",combinedField_1D,fmt = '%.8f')\n # #np.savetxt('C:/Users/xia/Desktop/20060101vs20060622vs20061025/201007/100/'+str(2010073030)+'_'+str(count)+'.'+\"txt\",combinedField,fmt = '%.8f')\n\n\n \"没有用trmm3b43Detrend[199801]\"\n\n for i in range(0, 32):\n for j in range(0, 32):\n temp1 = detrendField[i * 32:(i + 1) * 32, j * 32:(j + 1) * 32] * np.sum(trmm3b43Detrend[199801])\n temp2 = trmm3b43NormAver[1][i, j] * temp1\n #temp1 = detrendField[i * 32:(i + 1) * 32,j * 32:(j + 1) * 32] * np.sum(trmm3b43Detrend[199801])\n #temp2 = GWR[1][i * 32:(i + 1) * 32, j * 32:(j + 1) * 32] * temp1\n\n if (np.sum(temp2) != 0):\n temp3 = temp2 / np.sum(temp2)\n else:\n temp3 = 0\n # combinedField[i*25:(i+1)*25,j*25:(j+1)*25]=temp1*trmm3b43[1998][i,j]\n combinedField[i * 32:(i + 1) * 32, j * 32:(j + 1) * 32] = temp3 * (32 ** 2)\n combinedField_1D = np.array(combinedField).reshape(1048576, 1)\n np.savetxt('C:/Users/xia/Desktop/新实验/200702/' + str(200702283232) + '_gamma_no_zero_Nmf_new' + '.' + \"txt\",combinedField_1D,fmt='%.8f')\n\n","sub_path":"OldVersion/MF-我的理解.py","file_name":"MF-我的理解.py","file_ext":"py","file_size_in_byte":26402,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"42721814","text":"import pandas as pd\nimport numpy as np\nfrom adapted_classifier import *\nimport random\nfrom sklearn.model_selection import train_test_split, cross_val_predict\nfrom sklearn.linear_model import LinearRegression, Lasso, LassoCV, Ridge, RidgeCV,ElasticNet, MultiTaskLasso, MultiTaskElasticNetCV\nfrom sklearn.metrics import mean_squared_error, mean_absolute_error, r2_score\nfrom numpy import save\nfrom numpy import load\nimport pickle\n\nfrom adapted_classifier_visualized2 import classify as classify_vis\n\n#import the filtered data list csv\nfilt_data_files = pd.read_csv('/Volumes/Drive/ETH/Neural_Systems/b8p2male-b10o15female_aligned/filtered/filt_data_files_MinAmp0.05_PadSec0.50.csv', index_col='rec_id')\n# slice to sdr and DAQmx(to use in future perhaps) by getting rid of the third file, the .wav audio\nfilt_data_files = filt_data_files.drop('filt_DAQmxAudio', axis=1)\n\n\ntrivial_m_x = [] #\ntrivial_m_y = [] #\ntrivial_f_x = [] #\ntrivial_f_y = [] #\nclean_m_x = [] #\nclean_f_x = [] #\nclean_y = [] #\n\n#Put the S_trivial_m, S_trivial_f and S_clean together across recordings\nfor i, (rec_id, rec_id_files) in enumerate(filt_data_files.iterrows()):\n print(f'\\nProcessing recording {rec_id} ({i+1}/{filt_data_files.shape[0]})...')\n daq_file, sdr_file = rec_id_files.values\n if not np.load(daq_file).any().any():\n print('Empty.')\n continue\n male_x, male_y, female_x, female_y, clean_m, clean_f, clean_y_ = classify_vis(sdr_file,\n daq_file, 0, -1, \n show_energy_plot=False, show_framesizes=False, rec_id=rec_id,\n show_vocalization=False)\n print('Done.\\n')\n \n \n if male_x: #if S_trivial_m not empty, append it to the list\n trivial_m_x.append(male_x)\n trivial_m_y.append(male_y)\n if female_x: #if S_trivial_f not empty, append it to the list\n trivial_f_x.append(female_x)\n trivial_f_y.append(female_y)\n if clean_m: #if S_clean not empty, append it to the list\n clean_m_x.append(clean_m)\n clean_f_x.append(clean_f)\n clean_y.append(clean_y_)\n\n\nwith open('trivial_m_x', 'wb') as trivial_m_x:\n pickle.dump(trivial_m_x, trivial_m_x)\n\nwith open('trivial_m_y', 'wb') as trivial_m_y:\n pickle.dump(trivial_m_y, trivial_m_y)\n \nwith open('trivial_f_x', 'wb') as trivial_f_x:\n pickle.dump(trivial_f_x, trivial_f_x)\n\nwith open('trivial_f_y', 'wb') as trivial_f_y:\n pickle.dump(trivial_f_y, trivial_f_y)\n\nwith open('clean_m_x', 'wb') as clean_m_x:\n pickle.dump(clean_m_x, clean_m_x) \n\nwith open('clean_f_x', 'wb') as clean_f_x:\n pickle.dump(clean_f_x, clean_f_x) \n \nwith open('clean_y', 'wb') as clean_y:\n pickle.dump(clean_y, clean_y) \n\n\n\n\n\n\n","sub_path":"main/run.py","file_name":"run.py","file_ext":"py","file_size_in_byte":2666,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"166603167","text":"import json\n\n\ndef coletar_informacoes():\n \"\"\"\n\n Recebe as informações do médico que são informadas pelo\n usuário do sistema.\n \"\"\"\n nome = input('Nome: ')\n email = input('Email:')\n telefone = input('Telefone: ')\n crm = input('CRM: ')\n rg = input('RG: ')\n cpf = int(input('CPF: '))\n endereco = input('Endereço: ')\n especializacao = input('Especialização: ')\n numero = input('Número: ')\n bairro = input('Bairro: ')\n cidade = input('Cidade: ')\n uf = input('UF: ')\n planoDeSaude = input('Plano de saúde: ')\n salario = float(input('Salario Bruto: '))\n\n dados = dict(name=nome, email=email.lower(), phone=telefone, crm=crm,\n rg=rg, cpf=cpf, specialization=especializacao,\n address=endereco, number=numero, hood=bairro,\n city=cidade, state=uf, plan=planoDeSaude, salary=salario)\n return dados\n\n\ndef cadastrar_medico():\n \"\"\"\n\n Carrega o arquivo de médicos, caso ele exista, e adiciona as informações\n coletadas pela função coletar_informacoes(). Caso não exista o arquivo de\n médicos, um novo arquivo é aberto pra ser feito o cadastro dos médicos.\n \"\"\"\n try:\n with open('dados_medicos.json') as medicos:\n antigos_medicos = json.load(medicos)\n with open('dados_medicos.json', mode='w') as dados_medicos:\n antigos_medicos.append(coletar_informacoes())\n novos_medicos = json.dumps(antigos_medicos)\n dados_medicos.write(novos_medicos)\n except:\n with open('dados_medicos.json', mode='w') as dados_medicos:\n novos_medicos = [coletar_informacoes()]\n medicos = json.dumps(novos_medicos)\n dados_medicos.write(medicos)\n finally:\n print('\\nMédico cadastrado com sucesso!')\n\n\ndef listar_medicos():\n \"\"\"\n\n Carrega o arquivo de médicos e imprime o nome de cada médico cadas-\n trado. Caso não exista o arquivo, é informado que nenhum médico está cadastrado.\n Se o arquivo existir e estiver vazio, irá impimir a lista de médicos vazia.\n \"\"\"\n try:\n with open('dados_medicos.json', ) as dados_medicos:\n lista_medicos = json.load(dados_medicos)\n\n for medico in lista_medicos:\n print(\"Médico: {} | Especialização: {}\".format(medico['name'], medico['specialization']))\n print('-' * 20)\n except:\n print(\"\\nNenhum médico cadastrado!\")\n menu_medicos()\n\n\ndef remover_medico():\n \"\"\"\n\n Carrega o arquivo de médicos e pede para o usuário informar o número do\n CPF do médico que deseja remover. Caso o número do CPF informado esteja cadastrado\n no arquivo de médicos, esse médico será removido, e uma nova lista de médicos atualiza-\n da irá sobrescrever a lista desatualizada. Caso o médico não seja encontrado ou nenhum CPF\n seja informado, será exibido na tela.\n \"\"\"\n try:\n with open('dados_medicos.json') as dados_medicos:\n lista_medicos = json.load(dados_medicos)\n cpf = int(input('Qual o CPF do médico que você deseja remover?'))\n for medico in lista_medicos:\n if medico['cpf'] == cpf:\n lista_medicos.remove(medico)\n with open('dados_medicos.json', mode='w') as dados_medicos:\n medicos = json.dumps(lista_medicos)\n dados_medicos.write(medicos)\n print('Médico removido com sucesso!\\n')\n else:\n print('Médico não encontrado!\\n')\n menu_medicos()\n except:\n print('\\nNenhum CPF encontrado')\n menu_medicos()\n\n\ndef menu_medicos():\n while True:\n print(\"\\n1 - Cadastrar novo médico\\n\"\n \"2 - Listar médicos\\n\"\n \"3 - Remover médico\\n\"\n \"4 - Sair\")\n opcao = int(input('Selecione uma opção: '))\n if opcao == 1:\n cadastrar_medico()\n elif opcao == 2:\n listar_medicos()\n elif opcao == 3:\n remover_medico()\n elif opcao == 4:\n from menu_principal import menu_principal\n menu_principal()\n else:\n print(\"\\nOpção inválida!\")\n","sub_path":"medicos.py","file_name":"medicos.py","file_ext":"py","file_size_in_byte":4261,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"251020419","text":"import re, time, enchant, nltk, string\nfrom nltk.tag import StanfordNERTagger\nfrom nltk.tokenize import word_tokenize\nfrom collections import Counter\nfrom nltk.corpus import wordnet as wn\nfrom nltk.corpus import stopwords\nfrom nltk.tokenize import TweetTokenizer\n\ntweetTokenizer=TweetTokenizer()\nEN_STOPWORDS = stopwords.words('english')\n\ndictSlang={}\nwith open('../data/final_dict_slangs.txt','r') as slangFile:\n for slang in slangFile:\n slang=slang.split(':')\n dictSlang[slang[0].strip()]=slang[1].strip()\n\ndef words(text): \n return re.findall(r'\\w+', text.lower())\n\n\nWORDS = Counter(words(open('../data/corpus.txt').read()))\n\n\ndef prob(word, N=sum(WORDS.values())): \n \"Probability of `word`.\"\n return WORDS[word] / N\n\n\ndef extract_entity_names(t):\n entity_names = []\n\n if hasattr(t, 'label') and t.label:\n if t.label() == 'NE':\n entity_names.append(' '.join([child[0] for child in t]))\n else:\n for child in t:\n entity_names.extend(extract_entity_names(child))\n return entity_names\n\n\ndef named_entities(sentence):\n # print(sentence)\n sentences = nltk.sent_tokenize(sentence)\n tokenized_sentences = [word_tokenize(sentence) for sentence in sentences]\n tagged_sentences = [nltk.pos_tag(sentence) for sentence in tokenized_sentences]\n chunked_sentences = nltk.ne_chunk_sents(tagged_sentences, binary=True)\n entity_names = []\n\n for tree in chunked_sentences:\n entity_names.extend(extract_entity_names(tree))\n \n st = StanfordNERTagger('/Users/Parth/Desktop/project_docs/codes/stanford-ner-2016-10-31/classifiers/english.muc.7class.distsim.crf.ser.gz',\n '/Users/Parth/Desktop/project_docs/codes/stanford-ner-2016-10-31/stanford-ner.jar',\n encoding='utf-8')\n\n tokenized_text = word_tokenize(sentence)\n classified_text = st.tag(tokenized_text)\n\n entities_list=[]\n for entity in entity_names:\n entities_list+=entity.split()\n \n for tuple in classified_text:\n if tuple[1]!='O':\n entities_list.append(tuple[0])\n \n return list(set(entities_list))\n '''\n entities_list=[]\n for entity in entity_names:\n if ' ' in entity:\n for subentity in entity.split():\n entities_list.append(subentity)\n else:\n entities_list.append(entity)\n return list(set(entities_list))\n '''\n\ndef splitHashtag(hashtag):\n uppercase=re.compile(\"[A-Z]\")\n lowercase=re.compile(\"[a-z]\")\n digit=re.compile(\"[0-9]\")\n \n if len(hashtag)==0:\n return '#'\n if '_' in hashtag:\n return ' '.join(['#'+token for token in hashtag.split('_')])\n else:\n splittedHashtag=hashtag[0]\n for char in hashtag[1:]:\n if (uppercase.match(char)!=None and uppercase.match(splittedHashtag[-1])==None) or (digit.match(char)!=None and digit.match(splittedHashtag[-1])==None): \n splittedHashtag+=' '+char\n elif lowercase.match(char) and uppercase.match(splittedHashtag[-1])!=None and len(splittedHashtag[:-1])>0:\n splittedHashtag=splittedHashtag[:-1]+' '+splittedHashtag[-1]+char\n else:\n splittedHashtag+=char\n\n return ' '.join(['#'+token for token in splittedHashtag.split()])\n\n\ndef spellCorrect(spell,dictionary):\n\n suggestions=dictionary.suggest(spell)\n print('coming to correct',spell,suggestions)\n if len(suggestions)==0:\n return ' ' #incorrect spelling - to be removed\n probabilities={prob(suggestion):suggestion for suggestion in suggestions}\n correctSpell=probabilities[max(probabilities)]\n if(len(spell)<=4):\n return correctSpell\n setCorrectSpell=set(correctSpell)\n setSpell=set(spell)\n\n if(len(setSpell.intersection(setCorrectSpell))>=0.7*len(setCorrectSpell)):\n return correctSpell\n else:\n return ' '\n\nnotSentence=re.compile(\"^[\\?\\.\\!' ]+$\") #to eliminate sentences having only punctuations\npunctuations=['.','?','!']\npronouns=[\"I\",\"We\",\"You\",\"They\",\"He\",\"She\",\"It\"]\napostrophes=[\"n't\",\"'d\",\"'ll\",\"'s\",\"'m\",\"'ve\",\"'re\",\"na\",\"ta\"]\ndigit=re.compile(\"[0-9]\")\nrepeatedLetters=re.compile(r\"(.)\\1{2,}\")\nabbreviations=re.compile(\"^[A-Z\\.]+$\")\ndictionary=enchant.Dict(\"en_US\")\nallowedTokens=re.compile(\"#?('?[,A-Za-z0-9]+)+\")\nsentenceSeparators=[('and',' . '),('but',' . '),('because',' . '),('therefore',' . '),('yet',' . '),('except',' . '),\\\n ('then',' . '),('although',' . '),('still',' . '),('untill',' . '),('really\\?','surprise'),('really \\?','surprise')]\ninterjections=[('Ooh la la','happy'), ('oh yeah','happy'), ('oh shit','fear'), ('oh my god','surprise'), ('oh my gosh','surprise'),\\\n ('wow great','happy'), ('oh my goodness','surprise'), ('woo-hoo','happy'), ('can not wait to','excited'),\\\n ('fucking','anger'), ('fuck off','anger'), ('what the fuck','anger'), ('what the hell','anger'), ('fuck up','anger'),\\\n ('fucked up','disgust'), ('very odd','surprise'), ('shut up','anger'), ('big heart','happy'), ('bigger heart','happy'),\\\n ('big hearted','happy'), ('can not believe','surprise'), ('heart broken','sad'), ('heart break','sad'), ('blink of an eye','surprise'),\\\n ('blink of eye','surprise'), ('suddenly realised','surprise'), ('suddenly realized','surprise'), ('crush on','happy'),\\\n ('guess what','surprise'),('hats off','happy'),('break up','sad'),('broke up','sad'),('rest in peace','sad')]\ndef preprocess(tweet): #dict - dictionary of slangs\n tweet=tweet.replace('USER','').strip()\n for k,v in sentenceSeparators:\n k=\"(?0:\n #detect type of sentence\n punctuation=sentence[-1]\n while sentence[-1] in punctuations:\n sentence=sentence[:-1]\n sentence=sentence.strip()\n if punctuation not in punctuations:\n punctuation='.' \n #spell check\n sentenceTokens=[]\n for token in tweetTokenizer.tokenize(sentence):\n if len(token.strip())>0:\n sentenceTokens.append(token.strip())\n numOfCorrected=0\n correctedTokens=[]\n #print(sentenceTokens)\n if punctuation!='?':\n for index,token in enumerate(sentenceTokens):\n \n if allowedTokens.match(token)==None:\n continue\n hashWord=False\n if token[0]=='#':\n token=token[1:]\n hashWord=True\n elif (index-1)>=0 and sentenceTokens[index-1]=='#':\n hashWord=True\n \n if (token in (list(string.punctuation))) or digit.search(token)!=None:\n correctedTokens.append(token)\n else:\n #print(token)\n if (token not in pronouns+namedEntities) and abbreviations.match(token)==None and dictionary.check(token)!=True:\n token=token.lower()\n if (len(token)!=1 and len(wn.synsets(token))!=0 and token.lower() not in dictSlang) or ((index+1)0 and (correctedTokens[-1]+token).lower() in dictSlang:\n key=(correctedTokens[-1]+token).lower()\n correctedTokens[-1]=dictSlang[key]\n elif token in dictSlang:\n correctedTokens.append(dictSlang[token])\n if token in namedEntities:\n namedEntities.remove(token)\n elif token.lower() in dictSlang:\n correctedTokens.append(dictSlang[token.lower()])\n if token in namedEntities:\n namedEntities.remove(token)\n elif abbreviations.match(token)!=None or hashWord or token in namedEntities:\n correctedTokens.append(token)\n else:\n repeatedLettersMatch=repeatedLetters.search(token)\n while repeatedLettersMatch!=None:\n toBeReplaced=repeatedLettersMatch.group(0)\n replaceWith=toBeReplaced[0]+toBeReplaced[0]\n token=re.sub(toBeReplaced,replaceWith,token)\n repeatedLettersMatch=repeatedLetters.search(token)\n if dictionary.check(token):\n correctedTokens.append(token)\n else:\n token=token.lower()\n if '-' in token:\n subtokens=token.split('-')\n for subtoken in subtokens:\n if len(subtoken.strip())>0:\n if dictionary.check(subtoken):\n correctedTokens.append(subtoken)\n else:\n correctSpell=spellCorrect(subtoken,dictionary)\n if correctSpell!=' ':\n correctedTokens.append(correctSpell)\n numOfCorrected+=1\n else:\n correctSpell=spellCorrect(token,dictionary)\n if correctSpell!=' ':\n correctedTokens.append(correctSpell)\n numOfCorrected+=1\n if ' ' in correctedTokens:\n correctedTokens=list(filter(lambda a: a != ' ', correctedTokens)) \n #print(numOfCorrected,correctedTokens)\n if numOfCorrected<=(0.5*len(correctedTokens)):\n filteredSentences.append(' '.join(correctedTokens))\n sentenceType.append(punctuation)\n else:\n filteredSentences.append(sentence)\n sentenceType.append(punctuation)\n\n for index, sentence in enumerate(filteredSentences):\n for k,v in interjections:\n #k=\"[^A-Za-z]\"+k+\"[^A-Za-z]\"\n replace=re.compile(k, re.IGNORECASE)\n sentence=replace.sub(v,sentence)\n filteredSentences[index]=sentence\n\n return filteredSentences,sentenceType,namedEntities","sub_path":"codes/preprocessTweet.py","file_name":"preprocessTweet.py","file_ext":"py","file_size_in_byte":11631,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"647282719","text":"\"\"\"Plot le dFC regroupés par région anatomiques.\"\"\"\nimport os\nfrom copy import copy\n\nimport matplotlib.pyplot as plt\n\nimport numpy as np\nimport pandas as pd\n\nfrom brainpipe.system import study\nfrom brainpipe.connectivity import (remove_site_contact, dfc_summarize,\n anat_based_mean)\nfrom mne.stats import fdr_correction, bonferroni_correction\n\nfrom bct.algorithms.clustering import clustering_coef_wd\n\n\n\nst = study('DMN-CORR')\n\n###############################################################################\nsuj = 'th'\nth = 1.5\nsession = 2\ncondition = ('gamma50-150', 'lp1-10_', 'cmi')\nrm_succ_site = 'hard' # 'soft' | None\nplt_as = 'mpl' # {'mpl', 'visbrain'}\nsavefig = False\n###############################################################################\n\n# Path :\nprint('-> Get path')\ndfc_path = st.path_to_folder('dfc')\ndfc_file = st.search(suj, *condition, folder='dfc')\nxyz_path = st.path_to_folder('xyz')\nxyz_file = st.search(suj, 'bipo', folder='xyz')\nchan_path = st.path_to_folder('channels')\nchan_file = st.search(suj, 'bipo', folder='channels')\nanat_file = st.search(suj, folder='anat')\nanat_path = st.path_to_folder('anat')\nfig_path = st.path_to_folder('figure/corr_gamma')\nassert len(dfc_file) == len(xyz_file) == len(chan_file) == len(anat_file) == 1\n\n# Load the file :\nprint('-> Load files')\nxyz = np.load(os.path.join(xyz_path, xyz_file[0]))\nchannels = np.load(os.path.join(chan_path, chan_file[0]))\narch = np.load(os.path.join(dfc_path, dfc_file[0]))\ndf = pd.read_excel(os.path.join(anat_path, anat_file[0]))\ndfc = arch['dfc'].mean(-1).mean(-1)\n\n# Group DataFrame :\ndfc_r, labels, xyz_r = anat_based_mean(dfc, df, 'name_ROI', xyz)\n\n# plt.imshow(dfc_n, cmap='bwr')\n# plt.show()\n\nfrom visbrain.gui import Brain\nfrom visbrain.objects import SourceObj, BrainObj, ConnectObj\n\ns_obj = SourceObj('s', xyz_r, text=labels)\nc_obj = ConnectObj('c', xyz_r, dfc_r)\nb_obj = BrainObj('B3')\nBrain(source_obj=s_obj, connect_obj=c_obj, brain_obj=b_obj).show()\n","sub_path":"DMN-corr/02_plot/_dfc/plot_dfc_anat_ss.py","file_name":"plot_dfc_anat_ss.py","file_ext":"py","file_size_in_byte":1998,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"462280327","text":"from intcode import process\nfrom itertools import permutations\nfrom sys import maxsize\n\n\ndef run_amplifier(ram=[], inputs=iter([]), pc=0, rel_base=0):\n f = open('2019/inputs/amplifier.int')\n ram = ram if ram != [] else f.readline().rstrip().split(',')\n f.close()\n\n return process(ram, inputs, pc, automaton=True, rel_base=rel_base)\n\n\ndef amplifier_chain(phase_setting=[-1, -1, -1, -1, -1]):\n max_signal = -1\n\n for new_phase in permutations([0, 1, 2, 3, 4]):\n signals = []\n for i in range(0, len(new_phase)):\n inputs = new_phase[i], signals[i-1] if i > 0 else 0\n signal_output = next(\n run_amplifier(inputs=iter(inputs)))['output']\n signals += [signal_output]\n\n if signals[-1] > max_signal:\n max_signal = signals[-1]\n phase_setting = new_phase\n\n return max_signal, phase_setting\n\n\ndef feedback_chain(phase_setting=[-1, -1, -1, -1, -1]):\n max_signal = -maxsize - 1\n\n for new_phase in permutations([5, 6, 7, 8, 9]):\n memories = [[]] * len(new_phase)\n pcs = [0] * len(new_phase)\n rbs = [0] * len(new_phase)\n signals = [[x] for x in new_phase]\n output_signal = -maxsize - 1\n\n keep_alive = True\n while keep_alive:\n for i in range(len(new_phase)):\n vm_input = []\n\n if len(signals[i-1]) > 0:\n vm_input += signals[i-1]\n signals[i-1] = []\n\n try:\n inputs = iter(vm_input)\n result = next(run_amplifier(\n memories[i], inputs, pcs[i]), rbs[i])\n\n ram, output, pc, rb = [result[k]\n for k in ['ram', 'output', 'pc', 'rel_base']]\n\n memories[i] = ram\n pcs[i] = pc\n rbs[i] = rb\n signals[i] += [output]\n\n if i == len(new_phase) - 1:\n output_signal = output\n if output_signal > max_signal:\n max_signal = output_signal\n phase_setting = new_phase\n except:\n if i == len(new_phase) - 1:\n keep_alive = False\n\n return max_signal, phase_setting\n\n\ndef normal_mode():\n max_signal, phase_setting = amplifier_chain()\n print(\n f'\\n********************************\\nMax output signal for thrusters is {max_signal} with phase setting {phase_setting}')\n\n\ndef feedback_mode():\n max_signal, phase_setting = feedback_chain()\n print(\n f'\\n********************************\\nMax output signal for thrusters is {max_signal} with phase setting {phase_setting}')\n\n\ndef main():\n # normal_mode()\n feedback_mode()\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"2019/python/amplifier.py","file_name":"amplifier.py","file_ext":"py","file_size_in_byte":2875,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"161623191","text":"from guizero import App, PushButton, MenuBar\n\n\ndef pressed():\n print(\"button was pressed\")\n\n\ndef message(msg):\n print(msg)\n\n\ndef menuItemPressed():\n print(\"Menu bar item was pressed\")\n\n\ndef menuItemExit():\n exit()\n\n\napp = App()\n# sets icon as png\napp.icon = \"guizero.png\"\n\nbutton = PushButton(app, command=pressed, text='Press me')\nbutton_with_args = PushButton(app, command=message, text='Say hi', args=[\"hi\"])\n\n# set background color for the buttons\nbutton.bg = \"#ff0000\"\nbutton_with_args.bg = \"pink\"\n\n# set border width for the second button\nbutton_with_args.borderwidth = 8\n\n# set a menu bar\nm = MenuBar(app,\n {\n \"File\": {\n \"Close\": menuItemExit\n },\n \"Edit\": {\n \"edit1\": menuItemPressed,\n \"edit2\": menuItemPressed\n }\n })\n\napp.display()\n","sub_path":"examples/COMP490_example.py","file_name":"COMP490_example.py","file_ext":"py","file_size_in_byte":891,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"281203470","text":"#FEAR - POPULAR - PERCENTAGE OF EACH EMOTIONS\n\nFEAR_P_ANGER_PERCENTAGE = 12.86\nFEAR_P_ANT_PERCENTAGE = 8.28\nFEAR_P_DISGUST_PERCENTAGE = 11.48\nFEAR_P_FEAR_PERCENTAGE = 24.07\nFEAR_P_JOY_PERCENTAGE = 10.78\nFEAR_P_SADNESS_PERCENTAGE = 14.74\nFEAR_P_SURPRISE_PERCENTAGE = 8.02\nFEAR_P_TRUST_PERCENTAGE = 9.76\n\n\n#FEAR - NON POPULAR - PERCENTAGE OF EACH EMOTIONS\n\nFEAR_NP_ANGER_PERCENTAGE = 17.43\nFEAR_NP_ANT_PERCENTAGE = 5.09\nFEAR_NP_DISGUST_PERCENTAGE = 13.3\nFEAR_NP_FEAR_PERCENTAGE = 25.33\nFEAR_NP_JOY_PERCENTAGE = 6.25\nFEAR_NP_SADNESS_PERCENTAGE = 19.06\nFEAR_NP_SURPRISE_PERCENTAGE = 5.86\nFEAR_NP_TRUST_PERCENTAGE = 7.68\n\ninner_rule_dict = {}\n\n\ndef deviations(d):\n local_pc = 0\n local_npc = 0\n \n #anger\n angerDP = abs(FEAR_P_ANGER_PERCENTAGE - d['angerPer'])\n angerDNP = abs(FEAR_NP_ANGER_PERCENTAGE - d['angerPer'])\n if(angerDP>angerDNP):\n local_npc = local_npc + 1\n inner_rule_dict['anger'] = 0\n else:\n local_pc = local_pc + 1\n inner_rule_dict['anger'] = 1\n\n #ant\n antDP = abs(FEAR_P_ANT_PERCENTAGE - d['antPer'])\n antDNP = abs(FEAR_NP_ANT_PERCENTAGE - d['antPer'])\n if(antDP>antDNP):\n local_npc = local_npc + 1\n inner_rule_dict['ant'] = 0\n else:\n local_pc = local_pc + 1\n inner_rule_dict['ant'] = 1\n\n #disgust\n disgustDP = abs(FEAR_P_DISGUST_PERCENTAGE - d['disgustPer'])\n disgustDNP = abs(FEAR_NP_DISGUST_PERCENTAGE - d['disgustPer'])\n if(disgustDP>disgustDNP):\n local_npc = local_npc + 1\n inner_rule_dict['disgust'] = 0\n else:\n local_pc = local_pc + 1\n inner_rule_dict['disgust'] = 1\n\n #fear\n fearDP = abs(FEAR_P_FEAR_PERCENTAGE - d['fearPer'])\n fearDNP = abs(FEAR_NP_FEAR_PERCENTAGE - d['fearPer'])\n if(fearDP>fearDNP):\n local_npc = local_npc + 1\n inner_rule_dict['fear'] = 0\n else:\n local_pc = local_pc + 1\n inner_rule_dict['fear'] = 1\n\n #joy\n joyDP = abs(FEAR_P_JOY_PERCENTAGE - d['joyPer'])\n joyDNP = abs(FEAR_NP_JOY_PERCENTAGE - d['joyPer'])\n if(joyDP>joyDNP):\n local_npc = local_npc + 1\n inner_rule_dict['joy'] = 0\n else:\n local_pc = local_pc + 1\n inner_rule_dict['joy'] = 1\n\n #sadness\n sadnessDP = abs(FEAR_P_SADNESS_PERCENTAGE - d['sadnessPer'])\n sadnessDNP = abs(FEAR_NP_SADNESS_PERCENTAGE - d['sadnessPer'])\n if(sadnessDP>sadnessDNP):\n local_npc = local_npc + 1\n inner_rule_dict['sadness'] = 0\n else:\n local_pc = local_pc + 1\n inner_rule_dict['sadness'] = 1\n\n #surprise\n surpriseDP = abs(FEAR_P_SURPRISE_PERCENTAGE - d['surprisePer'])\n surpriseDNP = abs(FEAR_NP_SURPRISE_PERCENTAGE - d['surprisePer'])\n if(surpriseDP>surpriseDNP):\n local_npc = local_npc + 1\n inner_rule_dict['surprise'] = 0\n else:\n local_pc = local_pc + 1\n inner_rule_dict['surprise'] = 1\n\n #trust\n trustDP = abs(FEAR_P_TRUST_PERCENTAGE - d['trustPer'])\n trustDNP = abs(FEAR_NP_TRUST_PERCENTAGE - d['trustPer'])\n if(trustDP>trustDNP):\n local_npc = local_npc + 1\n inner_rule_dict['trust'] = 0\n else:\n local_pc = local_pc + 1\n inner_rule_dict['trust'] = 1\n\n\n if(local_npc>local_pc):\n return 0\n else:\n return 1\n","sub_path":"backend/ImproveContent/FearDominantEmotionsPercentageDeviations.py","file_name":"FearDominantEmotionsPercentageDeviations.py","file_ext":"py","file_size_in_byte":3258,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"381003599","text":"from objects.date_time import DateTime\nclass Customer(object):\n\n def __init__(self, login='', name='', address='', phone='', mobile='', email='', city='', country='', province='',\n zip_code='', reg_date=''):\n\n self.login = login\n self.name = name\n self.address = address\n self.phone = phone\n self.mobile = mobile\n self.email = email\n self.city = city\n self.country = country\n self.province = province\n self.zip_code = zip_code\n self.reg_date = DateTime(reg_date)\n\n def __str__(self):\n\n return \" Login: %s\\n Name: %s\\n Address: %s\\n Phone: %s\\n Mobile: %s\\n E-mail: %s\\n City: %s\\n Country: %s\\n \" \\\n \"Province: %s\\n Zip code: %s\\n Reg. date: %s\" % (self.login, self.name, self.address, self.phone,\n self.mobile, self.email, self.city, self.country,\n self.province, self.zip_code, self.reg_date)\n","sub_path":"objects/customer.py","file_name":"customer.py","file_ext":"py","file_size_in_byte":1041,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"503811724","text":"# __author__ = \"wyb\"\r\n# date: 2018/5/28\r\n# 定义函数获取统计一个字符串中大写字母、小写字母以及数字的个数并以字典的方式返回\r\n\r\n\r\ndef func(s):\r\n upper_number = 0\r\n lower_number = 0\r\n digit_number = 0\r\n for i in range(len(s)):\r\n if s[i].isupper():\r\n upper_number += 1\r\n if s[i].islower():\r\n lower_number += 1\r\n if s[i].isdigit():\r\n digit_number += 1\r\n return {\"upper_number\": upper_number, \"lower_number\": lower_number, \"digit_number\": digit_number}\r\n\r\n\r\nres = func(\"helloSDF 123\")\r\nprint(res)\r\n\r\n\r\n\r\n\r\n","sub_path":"python_advanced_traning/统计字符/统计字符.py","file_name":"统计字符.py","file_ext":"py","file_size_in_byte":607,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"502886370","text":"# -*- coding: utf-8 -*-\n\nfrom PyQt5.QtWidgets import *\n\nfrom actuasim.blind import BlindWidget\nfrom actuasim.valve import ValveWidget\nfrom knxnet.utils import *\n\n__author__ = \"Adrien Lescourt\"\n__copyright__ = \"HES-SO 2015, Project EMG4B\"\n__credits__ = [\"Adrien Lescourt\"]\n__version__ = \"1.0.2\"\n__email__ = \"adrien.lescourt@gmail.com\"\n__status__ = \"Prototype\"\n\n\nclass Room(QWidget):\n def __init__(self, parent=None, title=None, blind_list=None, valve_list=None):\n super(Room, self).__init__(parent)\n self.blind_list = []\n self.valve_list = []\n main_layout = QVBoxLayout()\n self.blind_list = blind_list\n self.valve_list = valve_list\n # blinds\n blind_box = QGroupBox(\"Blinds\")\n blind_box.setFixedWidth(1670)\n blind_box.setFixedHeight(380)\n blind_layout = QHBoxLayout()\n blind_box.setLayout(blind_layout)\n blind_scroll = QScrollArea(self)\n blind_scroll.setWidget(blind_box)\n for blind in blind_list:\n blind_layout.addWidget(blind)\n blind_layout.addStretch()\n blind_layout.setSpacing(0)\n # valves\n valve_box = QGroupBox(\"Valves\")\n valve_box.setFixedWidth(1670)\n valve_box.setFixedHeight(380)\n valve_layout = QHBoxLayout()\n valve_box.setLayout(valve_layout)\n valve_scroll = QScrollArea(self)\n valve_scroll.setWidget(valve_box)\n for valve in valve_list:\n valve_layout.addWidget(valve)\n valve_layout.addStretch()\n valve_layout.setSpacing(0)\n # room\n main_layout.addWidget(blind_scroll)\n main_layout.addWidget(valve_scroll)\n self.setLayout(main_layout)\n self.setWindowTitle(title)\n self.title = title\n\n @classmethod\n def from_dict(cls, title='title', room_dict=None):\n blind_list = []\n valve_list = []\n if room_dict is not None:\n for blind in room_dict['blinds']:\n addr = blind['address'].split('@')\n value = blind['value']\n blind_list.append(BlindWidget(IndividualAddress.from_str(addr[0]),\n GroupAddress.from_str(addr[1]),\n value))\n for valve in room_dict['valves']:\n addr = valve['address'].split('@')\n value = valve['value']\n valve_list.append(ValveWidget(IndividualAddress.from_str(addr[0]),\n GroupAddress.from_str(addr[1]),\n value))\n return cls(None, title, blind_list, valve_list)\n\n def get_room_dict(self):\n blinds = [{'address': blind.address_str, 'value': blind.position} for blind in self.blind_list]\n valves = [{'address': valve.address_str, 'value': valve.position} for valve in self.valve_list]\n return {'blinds': blinds, 'valves': valves}\n\n\nif __name__ == '__main__':\n import sys\n app = QApplication(sys.argv)\n room = Room()\n room.show()\n sys.exit(app.exec_())","sub_path":"src/knx/actuasim_iot/actuasim/room.py","file_name":"room.py","file_ext":"py","file_size_in_byte":3094,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"179720320","text":"#\n# Copyright 2016 The BigDL Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n#\n\nimport multiprocessing\nimport os\nimport sys\n\nimport cloudpickle\n\nfrom pytorch_lightning.utilities.seed import reset_seed\n\nfrom bigdl.nano.pytorch.plugins.ddp_subprocess import queue_dumper\nfrom bigdl.nano.pytorch.utils import TORCH_VERSION_LESS_1_10\nfrom bigdl.nano.deps.ipex.ipex_api import ipex_device, ipex_optimize\nimport torch\nimport warnings\n\n\nif __name__ == '__main__':\n temp_dir = sys.argv[1]\n\n with open(os.path.join(temp_dir, \"args.pkl\"), 'rb') as f:\n args = cloudpickle.load(f)\n\n plugin = args\n trainer = plugin.lightning_module.trainer\n plugin.mp_queue = multiprocessing.SimpleQueue()\n process_idx = int(os.environ[\"PROCESS_IDX\"])\n\n reset_seed()\n plugin.set_world_ranks(process_idx)\n # rank_zero_only.rank = plugin.global_rank\n\n plugin.init_ddp_connection(plugin.global_rank, plugin.world_size)\n\n plugin.dist.rank = plugin.global_rank\n plugin.dist.device = plugin.root_device\n\n if plugin.use_ipex and not TORCH_VERSION_LESS_1_10:\n dtype = torch.bfloat16 if plugin.enable_bf16 else None\n num_optimizers = len(plugin.lightning_module.trainer.accelerator.optimizers)\n if num_optimizers == 1:\n optimizer = plugin.lightning_module.trainer.accelerator.optimizers[0]\n ipex_optimize(plugin.model, optimizer=optimizer,\n inplace=True, dtype=dtype)\n elif num_optimizers == 0:\n plugin.model.eval()\n ipex_optimize(plugin.model, inplace=True, dtype=dtype)\n else:\n warnings.warn(f\"IPEX currently only support single optimizers, \"\n f\"but got {num_optimizers}. Skip IPEX\")\n\n if plugin.sync_batchnorm:\n plugin.model = plugin.configure_sync_batchnorm(plugin.model)\n\n plugin.configure_ddp()\n\n plugin.model_to_device()\n\n plugin.barrier()\n results = trainer.run_stage()\n\n plugin.transfer_distrib_spawn_state_on_fit_end(results)\n if plugin.global_rank == 0:\n with open(os.path.join(temp_dir,\n \"results.pkl\"), \"wb\") as f:\n results = queue_dumper(plugin.mp_queue)\n cloudpickle.dump(results, f)\n","sub_path":"python/nano/src/bigdl/nano/pytorch/plugins/worker.py","file_name":"worker.py","file_ext":"py","file_size_in_byte":2741,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"434468711","text":"import os\nimport json\nimport MeCab\n\ntagger = MeCab.Tagger(\"-Owakati\")\ntagger.parse(\"\")\n\n\ndef load_json(file_name):\n json_file = open(file_name, 'r')\n json_data = json.load(json_file)\n json_file.close()\n return json_data\n\n\ndef main():\n request = open('train/request.txt', 'w')\n response = open('train/response.txt', 'w')\n for file_name in os.listdir('./json/rest1046'):\n file_path = os.path.join('./json/rest1046', file_name)\n json_data = load_json(file_path)\n U = \"\"\n S = \"\"\n for data in json_data['turns']:\n utterance = data['utterance']\n speaker = data['speaker']\n if len(utterance) == 0:\n continue\n\n if speaker == 'U':\n U = utterance + '\\n'\n else:\n S = utterance + '\\n'\n\n if U != \"\" and S != \"\":\n request.write(tagger.parse(U))\n response.write(tagger.parse(S))\n U = S = \"\"\n\n\nif __name__ == '__main__':\n main()","sub_path":"generate_train_data.py","file_name":"generate_train_data.py","file_ext":"py","file_size_in_byte":1027,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"44913689","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\nimport sys\n\nfor caseno, line in enumerate(open(\"test.in\", \"r\").readlines()[1:]) :\n pancakes=line.strip()\n\n # Add + at end to force flip on last - if any\n pancakes = pancakes + \"+\"\n\n prec = None\n nb = 0\n for p in pancakes :\n if p != prec :\n nb += 1\n prec = p\n\n print(\"Case #%d: %s\" % (caseno+1, nb-1))\n","sub_path":"codes/CodeJamCrawler/16_0_2_neat/16_0_2_corossig_pancake.py","file_name":"16_0_2_corossig_pancake.py","file_ext":"py","file_size_in_byte":397,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"239845073","text":"# If this example is not executed from the directory containing the\n# CMOR code, please first complete the following steps:\n#\n# 1. In any directory, create 'Tables/', 'Test/' and 'CMIP6/' directories.\n#\n# 2. Download\n# https://github.com/PCMDI/cmor/blob/master/TestTables/CMIP6_Omon.json\n# and https://github.com/PCMDI/cmor/blob/master/TestTables/CMIP6_CV.json\n# to the 'Tables/' directory.\n#\n# 3. Download\n# https://github.com/PCMDI/cmor/blob/master/Test/.json\n# to the 'Test/' directory.\n\nimport cmor\nimport numpy\nimport unittest\nimport os\nimport sys\nimport tempfile\n\n\n# ==============================\n# main thread\n# ==============================\n\n\ndef run():\n unittest.main()\n\n\nclass TestCase(unittest.TestCase):\n\n def setUp(self, *args, **kwargs):\n # ------------------------------------------------------\n # Copy stdout and stderr file descriptor for cmor output\n # ------------------------------------------------------\n self.newstdout = os.dup(1)\n self.newstderr = os.dup(2)\n # --------------\n # Create tmpfile\n # --------------\n self.tmpfile = tempfile.mkstemp()\n# os.dup2(self.tmpfile[0], 1)\n# os.dup2(self.tmpfile[0], 2)\n os.close(self.tmpfile[0])\n\n def getAssertTest(self):\n f = open(self.tmpfile[1], 'r')\n lines = f.readlines()\n for line in lines:\n if line.find('Error:') != -1:\n testOK = line.strip()\n break\n f.close()\n os.unlink(self.tmpfile[1])\n return testOK\n\n def testCMIP6(self):\n try:\n\n cmor.setup(inpath='Tables', netcdf_file_action=cmor.CMOR_REPLACE)\n cmor.dataset_json(\"Test/CMOR_input_example.json\")\n\n cmor.load_table(\"CMIP6_Omon.json\")\n itime = cmor.axis(table_entry=\"time\", units='months since 2010', coord_vals=numpy.array(\n [0, 1, 2, 3, 4.]), cell_bounds=numpy.array([0, 1, 2, 3, 4, 5.]))\n ivar = cmor.variable(\n table_entry=\"masso\",\n axis_ids=[itime],\n units='kg')\n\n data = numpy.random.random(5)\n for i in range(0, 5):\n # ,time_vals=numpy.array([i,]),time_bnds=numpy.array([i,i+1]))\n cmor.write(ivar, data[i:i])\n cmor.close()\n except BaseException:\n os.dup2(self.newstdout, 1)\n os.dup2(self.newstderr, 2)\n sys.stdout = os.fdopen(self.newstdout, 'w', 0)\n sys.stderr = os.fdopen(self.newstderr, 'w', 0)\n self.assertIn('d', testOK)\n\n\nif __name__ == '__main__':\n run()\n","sub_path":"Test/test_python_CMIP6_driving.py","file_name":"test_python_CMIP6_driving.py","file_ext":"py","file_size_in_byte":2667,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"344154218","text":"BOT_NAME = \"scraper\"\n\nSPIDER_MODULES = [\"scraper.spiders\"]\nNEWSPIDER_MODULE = \"scraper.spiders\"\n\nROBOTSTXT_OBEY = False\n\nSELENIUM_DRIVER_NAME = \"chrome\"\nSELENIUM_DRIVER_EXECUTABLE_PATH = (\n \"C:\\\\Users\\\\AntonKaminsky\\\\Documents\\\\projects\\\\gthl-scraper\\\\bin\\\\chromedriver.exe\"\n)\nSELENIUM_DRIVER_ARGUMENTS = ['--headless']\n\nDOWNLOADER_MIDDLEWARES = {\n 'scrapy_selenium.SeleniumMiddleware': 800\n}\n\nITEM_PIPELINES = {\n 'scraper.pipelines.FirestoreWriterPipeline': 800,\n}\n","sub_path":"scraper/settings.py","file_name":"settings.py","file_ext":"py","file_size_in_byte":475,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"613232134","text":"# Copyright (c) 2020 Intel Corporation.\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy\n# of this software and associated documentation files (the \"Software\"), to deal\n# in the Software without restriction, including without limitation the rights\n# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n# copies of the Software, and to permit persons to whom the Software is\n# furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in\n# all copies or substantial portions of the Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\n\"\"\"EII Message Bus publisher example\n\"\"\"\n\nimport os\nimport cfgmgr.config_manager as cfg\nimport time\n\ndef py_ex_func(key, json):\n print(\"Key is {}\".format(key))\n print(\"json is {}\".format(json))\n\n\ntry:\n os.environ[\"AppName\"] = \"VideoIngestion\"\n\n # create ConfigMgr object\n ctx = cfg.ConfigMgr()\n \n # get AppCfg's obejct to get application's config('//config')\n app_cfg = ctx.get_app_config()\n print('app config is : {}'.format((app_cfg.get_dict())))\n print('loop_video is : {}'.format((app_cfg[\"ingestor\"][\"loop_video\"])))\n\n # get watch object\n watch_cfg = ctx.get_watch_obj()\n # Watching on GlobalEnv key\n watch_cfg.watch(\"/GlobalEnv/\", py_ex_func)\n # Watching on VideoAnalytics prefix\n watch_cfg.watch_prefix(\"/VideoAnalytics\", py_ex_func)\n\n # Watch the key \"//config\" for any changes,\n # py_ex_func function will be called with updated value\n watch_cfg.watch_config(py_ex_func)\n\n # Watch the key \"//interface\" for any changes,\n # py_ex_func function will be called with updated value\n watch_cfg.watch_interface(py_ex_func)\n print(\"Watching on app config & app interface for 60 seconds\")\n time.sleep(60)\n\nexcept KeyboardInterrupt:\n print('[INFO] Quitting...')\nexcept Exception as e:\n print('Error during execution: {}'.format(e))\n","sub_path":"common/libs/ConfigMgr/python/examples/sample_get_value.py","file_name":"sample_get_value.py","file_ext":"py","file_size_in_byte":2433,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"649155192","text":"import tensorflow.contrib.slim as slim\nfrom tensorflow.contrib.slim.nets import vgg\nimport tensorflow as tf\n\n#'relu1_1', 'relu2_1', 'relu3_1', 'relu4_1', 'relu5_1'\ndef get_vgg_activations(input, layers=['vgg_19/conv2/conv2_1','vgg_19/conv3/conv3_1','vgg_19/conv4/conv4_1']):\n with slim.arg_scope(vgg.vgg_arg_scope()):\n _, end_points = vgg_19(input)\n activations = [end_points[layer] for layer in layers]\n return activations\n\n#modified vgg_19 from tf.slim.nets.vgg to be reusable\ndef vgg_19(inputs,\n scope='vgg_19', reuse=tf.AUTO_REUSE):\n \"\"\"Oxford Net VGG 19-Layers version E Example.\n\n Note: All the fully_connected layers have been transformed to conv2d layers.\n To use in classification mode, resize input to 224x224.\n\n Args:\n inputs: a tensor of size [batch_size, height, width, channels].\n num_classes: number of predicted classes.\n is_training: whether or not the model is being trained.\n dropout_keep_prob: the probability that activations are kept in the dropout\n layers during training.\n spatial_squeeze: whether or not should squeeze the spatial dimensions of the\n outputs. Useful to remove unnecessary dimensions for classification.\n scope: Optional scope for the variables.\n\n Returns:\n the last op containing the log predictions and end_points dict.\n \"\"\"\n with tf.variable_scope(scope, 'vgg_19', [inputs], reuse=reuse) as sc:\n end_points_collection = sc.name + '_end_points'\n # Collect outputs for conv2d, fully_connected and max_pool2d.\n with slim.arg_scope(\n [slim.conv2d, slim.fully_connected, slim.max_pool2d],\n outputs_collections=end_points_collection):\n net = slim.repeat(\n inputs, 2, slim.conv2d, 64, [3, 3], scope='conv1')\n net = slim.max_pool2d(net, [2, 2], scope='pool1')\n net = slim.repeat(net, 2, slim.conv2d, 128, [3, 3], scope='conv2', reuse=reuse)\n net = slim.max_pool2d(net, [2, 2], scope='pool2')\n net = slim.repeat(net, 4, slim.conv2d, 256, [3, 3], scope='conv3', reuse=reuse)\n net = slim.max_pool2d(net, [2, 2], scope='pool3')\n net = slim.repeat(net, 4, slim.conv2d, 512, [3, 3], scope='conv4', reuse=reuse)\n net = slim.max_pool2d(net, [2, 2], scope='pool4')\n net = slim.repeat(net, 4, slim.conv2d, 512, [3, 3], scope='conv5', reuse=reuse)\n net = slim.max_pool2d(net, [2, 2], scope='pool5')\n # Convert end_points_collection into a end_point dict.\n end_points = slim.utils.convert_collection_to_dict(end_points_collection)\n return net, end_points\n","sub_path":"vgg19/vgg_19.py","file_name":"vgg_19.py","file_ext":"py","file_size_in_byte":2689,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"410946932","text":"# No saraksta tiek nejauši izvēlēts kāds vārds. Lietotājam burtu vietā tiek parādītas svītriņas. Lietotājam ir iespēja minēt vārda burtus, kamēr ‘karatavas’ zīmējums nav pabeigts. Ja lietotāja minētais burts ir atrodams vārdā, tad svītriņu vietā parādās atbilstošs burts, ja lietotais kļūdās, tad ‘karatavas’ zīmējums tiek papildināts, lietotājam ir iespēja kļūdīties 6 reizes. Spēle beidzās līdz lietotājs uzmin visus vārda burtus vai kļūdās 6 reizes.\n\nimport random\n\ndef revealCharacters(word, characters):\n hiddenWord = list(word)\n for i,c in enumerate(word):\n if c not in characters:\n hiddenWord[i] = \"-\"\n return \"\".join(hiddenWord)\n\ndef validateInput(character, guessedCharacters):\n if character in guessedCharacters:\n print(f\"Already tried with '{character}' - pick another!\")\n elif character.isdigit():\n print(f\"'{character}' is a digit, not a character - pick a character!\")\n elif len(character) == 0:\n print(\"Empty space is not a character - pick a character!\")\n else:\n guessedCharacters.append(character)\n return guessedCharacters\n\ndoLoopMenu = True\ndictionary = ['apple','tomato','potato','banana','pear']\ngallows = [\"\\n |--|\\n |\\n |\\n |\\n |\\n |\\n\",\n \"\\n |--|\\n O |\\n |\\n |\\n |\\n |\\n\",\n \"\\n |--|\\n O |\\n | |\\n |\\n |\\n |\\n\",\n \"\\n |--|\\n O |\\n | |\\n | |\\n |\\n |\\n\",\n \"\\n |--|\\n O |\\n | |\\n/| |\\n |\\n |\\n\",\n \"\\n |--|\\n O |\\n | |\\n/|\\ |\\n |\\n |\\n\",\n \"\\n |--|\\n O |\\n | |\\n/|\\ |\\n/ |\\n |\\n\",\n \"\\n |--|\\n O |\\n | |\\n/|\\ |\\n/ \\ |\\n |\\n\"]\n\nwhile doLoopMenu:\n print(\"Enter 1 to play hangman, 2 to add a new word, 3 to quit program\")\n choice = str(input(\"Enter number: \"))\n \n if choice == \"1\":\n doLoopGuess = True\n secretWord = random.choice(dictionary)\n mistakes = 0\n guessedCharacters = []\n while doLoopGuess:\n\n if mistakes > 6:\n print(\"You lose!\\n=========\\n\")\n break\n \n if secretWord == revealCharacters(secretWord,guessedCharacters):\n print(\"You win!\\n=========\\n\")\n break\n\n print(f\"\\n=========\\n\\nGuessed letters: {guessedCharacters}\")\n\n character = str(input(\"Enter letter: \"))\n guessedCharacters = validateInput(character,guessedCharacters) \n if character not in secretWord:\n mistakes += 1\n\n print(f\"Word: {revealCharacters(secretWord,guessedCharacters)}\")\n\n print(gallows[mistakes])\n \n elif choice == \"2\":\n word = str(input(\"Enter new word: \"))\n\n if word in dictionary:\n print(f\"Word '{word}' already exists in dictionary\")\n\n dictionary.append(word)\n print(f\"Added {word}\\n\")\n\n elif choice == \"3\":\n doLoopMenu = False\n\n else:\n print(\"Unknown command!\\n\")\n","sub_path":"pd_v04.py","file_name":"pd_v04.py","file_ext":"py","file_size_in_byte":2817,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"489520780","text":"# coding: utf-8\n\nimport os\nimport sys\nimport time\nimport signal\nimport logging\nimport os.path\nimport websockify\nimport multiprocessing\n\nfrom core.config import config\nfrom vnc2flv import flv, rfb, video\nfrom core.utils.network_utils import get_free_port\n\nlog = logging.getLogger(__name__)\n\n\nclass VNCVideoHelper:\n recorder = None\n proxy = None\n __proxy_port = None\n __filepath = None\n\n def __init__(self, host, port=5900, filename_prefix='vnc'):\n self.filename_prefix = filename_prefix\n self.dir_path = os.sep.join([config.SCREENSHOTS_DIR,\n str(self.filename_prefix)])\n if not os.path.isdir(self.dir_path):\n os.mkdir(self.dir_path)\n self.host = host\n self.port = port\n\n @staticmethod\n def _flvrec(filename, host='localhost', port=5900,\n framerate=12, keyframe=120,\n preferred_encoding=(0,),\n blocksize=32, clipping=None,\n debug=0):\n fp = file(filename, 'wb')\n pwdcache = rfb.PWDCache('%s:%d' % (host, port))\n writer = flv.FLVWriter(fp, framerate=framerate, debug=debug)\n sink = video.FLVVideoSink(\n writer,\n blocksize=blocksize, framerate=framerate, keyframe=keyframe,\n clipping=clipping, debug=debug)\n client = rfb.RFBNetworkClient(\n host, port, sink, timeout=500/framerate,\n pwdcache=pwdcache, preferred_encoding=preferred_encoding,\n debug=debug)\n log.debug('Start vnc recording to %s' % filename)\n return_code = 0\n try:\n def sigterm_handler(sig, frame):\n log.debug(\"%s %s\" % (sig, frame))\n raise SystemExit\n signal.signal(signal.SIGTERM, sigterm_handler)\n client.open()\n try:\n current_time = time.time()\n max_duration = getattr(config, \"SCREENCAST_RECORDER_MAX_DURATION\", 1800)\n while True:\n if time.time() - current_time > max_duration:\n log.warning(\"VNC recorder for {} has been stopped \"\n \"because max duration({}) was exceeded\".format(filename, max_duration))\n raise SystemExit\n client.idle()\n finally:\n client.close()\n except Exception as e:\n if isinstance(e, SystemExit):\n log.info(\"VNC recorder process({}): Got SIGTERM. stopping...\".format(filename))\n else:\n log.exception(\"Error in VNC recorder process({})\".format(filename))\n return_code = 1\n finally:\n writer.close()\n fp.close()\n exit(return_code)\n log.info('Stopped vnc recording to %s' % filename)\n\n def delete_source_video(self):\n if self.__filepath and os.path.isfile(self.__filepath):\n os.remove(self.__filepath)\n log.debug('Source video %s was deleted' % self.__filepath)\n self.delete_vnc_log()\n\n def delete_vnc_log(self):\n vnc_log = os.sep.join([self.dir_path, 'vnc_video.log'])\n if os.path.isfile(vnc_log):\n os.remove(vnc_log)\n log.debug('File %s was deleted' % vnc_log)\n\n def start_proxy(self):\n self.__proxy_port = get_free_port()\n sys.argv = [\n \"--daemon\",\n \"--wrap-mode=ignore\",\n \"--record=%s/proxy_vnc_%s.log\" % (self.dir_path, self.port),\n \"0.0.0.0:%d\" % self.__proxy_port,\n \"%s:%s\" % (self.host, self.port)\n ]\n\n self.proxy = multiprocessing.Process(\n target=websockify.websocketproxy.websockify_init\n )\n\n self.proxy.start()\n\n def get_proxy_port(self):\n return self.__proxy_port\n\n def stop_proxy(self):\n if self.proxy and self.proxy.is_alive():\n self.proxy.terminate()\n\n def start_recording(self, framerate=5, size=(800, 600)):\n sys.stderr = sys.stdout = open(os.sep.join([\n self.dir_path, 'vnc_video.log'\n ]), 'w')\n self.__filepath = os.sep.join([self.dir_path,\n str(self.filename_prefix) + '.flv'])\n\n kwargs = {\n 'framerate': framerate,\n 'clipping': video.str2clip(\"%sx%s+0-0\" % (size[0], size[1])),\n 'debug': 1\n }\n self.recorder = multiprocessing.Process(\n target=self._flvrec,\n args=(self.__filepath, self.host, self.port),\n kwargs=kwargs\n )\n self.recorder.daemon = True\n self.recorder.start()\n log.info(\n \"Started screencast recording(pid:{}) for {}:{} to {}\".format(\n self.recorder.pid, self.host, self.port, self.dir_path\n )\n )\n\n def stop_recording(self):\n if self.recorder and self.recorder.is_alive():\n self.recorder.terminate()\n log.info(\n \"Stopped screencast recording(pid:{}) for {}:{} to {}\".format(\n self.recorder.pid, self.host, self.port, self.dir_path\n )\n )\n","sub_path":"core/video.py","file_name":"video.py","file_ext":"py","file_size_in_byte":5175,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"585905188","text":"lista= ['Bia', 'Ana'] #Lista (list)\r\ntupla= ('Bia', 'Ana') #Tupla (tuple) , nao dinâmica\r\ndicionario = {'nome': 'Gabriel', 'idade': 27} #Dicionario (dict)\r\nconjunto = {'Bia', 'Joao'} #Conjunto (set)\r\n\r\n\r\nif 'Ana' in tupla:\r\n print('Ana esta dentro da tupla')\r\n\r\nprint(dicionario)\r\n\r\nprint(dicionario['nome'])\r\ndicionario['nome'] = 'Dauro'\r\ndicionario['endereco'] = 'Avenida Sao Carlos'\r\n\r\nconjunto.add('Fabio')\r\nconjunto.add('Bia') #nao adicionará, pois já existe um Gui\r\nconjunto.remove('Fabio')\r\nprint(conjunto)\r\n\r\n\r\n\r\n","sub_path":"aula6_estruturas_de_dados.py","file_name":"aula6_estruturas_de_dados.py","file_ext":"py","file_size_in_byte":529,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"494373228","text":"#!/user/bin/python\n\n# 5 test, 25 real\npreambleCount = 25\nallowedLowestIndex = 0\nnumbers = []\ninvalidNumberIndex = -1\ninvalidNumber = -1\n\ndef isValid(value, amongNumbers):\n #print(amongNumbers)\n for first in amongNumbers:\n for second in amongNumbers:\n if first + second == value:\n return True\n\n return False\n\ndef tryFindContSet(summedValue, numbers):\n startIndex = 0\n values = []\n index = startIndex\n while startIndex < len(numbers):\n values.append(numbers[index])\n if sum(values) == summedValue and len(values) > 1:\n break\n elif sum(values) > summedValue:\n startIndex += 1\n values = []\n index = startIndex\n else:\n index += 1\n return values\n\n \nwith open(\"../input.txt\", 'r') as input:\n for line in input.readlines():\n numbers.append(int(line))\n #print(numbers)\n\nvalueIndex = preambleCount\nwhile valueIndex < len(numbers):\n value = numbers[valueIndex]\n #print(\"Doing value {}\".format(value))\n if isValid(value, numbers[valueIndex-preambleCount:valueIndex]) is False:\n invalidNumberIndex = valueIndex\n invalidNumber = value\n break\n else:\n valueIndex += 1\n\ncontSet = tryFindContSet(invalidNumber, numbers[:invalidNumberIndex])\nprint(min(contSet) + max(contSet))","sub_path":"day9/part2/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1353,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"378820037","text":"def checkisPallendrome(inputText):\r\n inputText = inputText.replace(\" \", \"\")\r\n inputText = inputText.lower()\r\n testString = \"\"\r\n for i in inputText:\r\n testString = i + testString\r\n # print(\"Test String: \" + testString)\r\n\r\n if inputText in testString:\r\n return True\r\n else:\r\n return False\r\n\r\n\r\ndef tester(inputText, expected_result):\r\n actual_result = checkisPallendrome(inputText)\r\n\r\n print_text = \"The text was: \" + str(inputText) + \" | \"\r\n if expected_result == actual_result:\r\n print_text += \"Correct: \" + str(expected_result) + \" == \" + str(actual_result)\r\n else:\r\n print_text += \"Incorrect: \" + str(expected_result) + \" != \" + str(actual_result)\r\n return print_text\r\n\r\n\r\nif __name__ == \"__main__\":\r\n # Try it on these to see if it works?\r\n text0 = \"My foot is a hamburger\"\r\n text1 = \"Go hang a salami Im a lasagna hog\"\r\n text2 = \"She sells sea shells by the sea shore\"\r\n text3 = \"race car\"\r\n text4 = \"My school\"\r\n\r\n # Test it like this\r\n print(tester(text0, False))\r\n print(tester(text1, True))\r\n print(tester(text4, False))\r\n print(tester(text3, True))","sub_path":"one.py","file_name":"one.py","file_ext":"py","file_size_in_byte":1165,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"482404206","text":"#WokeDev\r\n#input grid\r\ngrid = [[6,0,4,0,0,0,9,1,0],\r\n [8,9,0,4,5,0,3,0,0],\r\n [0,0,5,0,9,0,8,4,2],\r\n [0,0,0,0,0,9,0,0,1],\r\n [3,0,0,5,0,4,0,0,6],\r\n [2,0,0,1,0,0,0,0,0],\r\n [9,5,3,0,7,0,1,0,0],\r\n [0,0,7,0,4,5,0,3,9],\r\n [0,6,2,0,0,0,5,0,8]]\r\n \r\n# [0,0,0,0,0,0,0,0,0]\r\n\r\ndef printBoard(bo): #print and layout of board \r\n for x in range(len(bo)):\r\n if x % 3 == 0 and x != 0:\r\n print(\"- - - - - - - - - - - -\")\r\n\r\n for y in range(len(bo[0])):\r\n if y % 3 == 0 and y != 0:\r\n print(\" | \", end=\"\")\r\n if y == 8:\r\n print(bo[x][y])\r\n else:\r\n print(str(bo[x][y]) + \" \", end=\"\")\r\n\r\ndef findEmpty(bo): #find 0s \r\n for x in range(len(bo)):\r\n for y in range(len(bo[0])):\r\n if bo[x][y] == 0:\r\n return (x,y)\r\n return None\r\n\r\ndef valid(bo, num, pos): #verifying \r\n #check row\r\n for x in range(len(bo[0])):\r\n if bo[pos[0]][x] == num and pos[1] !=x:\r\n return False\r\n \r\n #check column\r\n for x in range(len(bo[0])):\r\n if bo[x][pos[1]] == num and pos[0] !=x:\r\n return False\r\n \r\n #check box\r\n box_x = pos[1] // 3\r\n box_y = pos[0] // 3\r\n\r\n for x in range(box_y * 3, box_y*3 + 3):\r\n for y in range(box_x * 3, box_x*3 + 3):\r\n if bo[x][y] == num and (x,y) !=pos:\r\n return False\r\n return True\r\n\r\ndef solve(bo): #solving algorithm \r\n find = findEmpty(bo)\r\n if not find:\r\n return True\r\n else:\r\n row, col = find\r\n for x in range(1,10):\r\n if valid(bo, x, (row,col)):\r\n bo[row][col] = x\r\n if solve(bo):\r\n return True\r\n bo[row][col] = 0\r\n return False\r\n\r\nif __name__ == \"__main__\":\r\n print(\"\\nProblem:\")\r\n printBoard(grid)\r\n solve(grid)\r\n print(\"\\nSolution:\")\r\n printBoard(grid)\r\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1957,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"288671011","text":"# -*- coding: utf-8 -*-\nfrom __future__ import division\nimport time\n# π/4=4arctan1/5-arctan1/239\nnumber = int(input('please in put the No: '))\ntime1=time.time()\nnumber1 = number+10\n\n# 算到小数点后number1位\nb = 10**number1\n\n# 求含4/5的首项\nx1 = b*4//5\n# 求含1/239的首项\nx2 = b// -239\n\n# 求第一大项\nhe = x1+x2\n#设置下面循环的终点,即共计算n项\nnumber *= 2\n\n#循环初值=3,末值2n,步长=2\nfor i in range(3,number,2):\n # 求每个含1/5的项及符号\n x1 //= -25\n # 求每个含1/239的项及符号\n x2 //= -57121\n # 求两项之和\n x = (x1+x2) // i\n # 求总和\n he += x\n\n# 求出π\npai = he*4\n#舍掉后十位\npai //= 10**10\n\n############ 输出圆周率π的值\npaistring=str(pai)\nresult=paistring[0]+str('.')+paistring[1:len(paistring)]\nfo = open(\"pi.txt\",\"w\")\nfo.write(result)\nfo.close()\nprint (result)\n\ntime2=time.time()\nprint (\"used time:\"+str(time2 - time1) + 's')\n","sub_path":"pi3.py","file_name":"pi3.py","file_ext":"py","file_size_in_byte":938,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"8248916","text":"from django.conf.urls import url, patterns, include\n\nfrom . import views\n\napp_name = 'blog'\n\nurlpatterns = [\n\t#\turl(r'^$', views.IndexView.as_view()),\n\turl(r'^$', views.index),\n\turl(r'^about/$', views.about),\n url('^', include('django.contrib.auth.urls')),\n\turl(r'^(?P[0-9]+)/blog/$', views.blog, name='blog'),\n url(r'^register/', views.register),\n\turl(r'^add_post/', views.add_post, name='add_post'),\n\n\turl(r'^(?P[A-Za-z0-9]+)/blog_author/', views.blog_author, name='blog_author'),\n] ","sub_path":"dblog/blog/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":513,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"45842906","text":"\nfrom numpy import exp, pi, dot, sqrt\nfrom numpy.linalg import inv, det\nfrom matplotlib.pyplot import scatter, show, hist\n\n\ndef gaussian_anomaly_detection(data):\n rows, cols = data.shape\n mu = data.mean(axis=0)\n diff = data - mu\n cov = dot(diff.T, diff) / rows\n a = exp(-0.5 * dot(dot(diff, inv(cov)), diff.T))\n b = sqrt(pow(2 * pi, cols) * det(cov))\n res = (a / b).sum(axis=1)\n return res\n\n\nfrom sklearn.datasets import load_wine as load\nfrom sklearn.decomposition import PCA\n\n\ndata = PCA(2).fit_transform(load().data)\nres = gaussian_anomaly_detection(data)\ncolors = []\nfor x in res:\n if x < res.mean() - 2 * res.std() or x > res.mean() + 2 * res.std():\n colors.append('red')\n else:\n colors.append('green')\nscatter(data[:,0], data[:,1], c=colors)\nshow()\nhist(res, bins=100)\nshow()\n","sub_path":"GaussianAnomalyDetection.py","file_name":"GaussianAnomalyDetection.py","file_ext":"py","file_size_in_byte":826,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"259759429","text":"\n# coding: utf-8\n\n# #章节:使用元类\n# 教程地址:\n# https://www.liaoxuefeng.com/wiki/0014316089557264a6b348958f449949df42a6d3a2e542c000/0014319106919344c4ef8b1e04c48778bb45796e0335839000\n# 参考代码地址:\n# https://github.com/michaelliao/learn-python3/blob/master/samples/oop_advance/orm.py\n# https://github.com/michaelliao/learn-python3/blob/master/samples/oop_advance/use_metaclass.py\n# https://github.com/michaelliao/learn-python3/blob/master/samples/oop_advance/use_metaclass.py\n\n# In[9]:\n\n\nimport asyncio, aiomysql\nimport sys\nsysFc = 'D:\\\\python_learn\\\\sysFc'\nsys.path.append(sysFc)\nfrom logSf10 import crLog\nlogger = crLog()\n\n\n# In[2]:\n\n\n# metaclass是类的模板,所以必须从`type`类型派生:\nclass ListMetaclass(type):\n def __new__(cls, name, bases, attrs):\n attrs['add'] = lambda self, value: self.append(value)\n return type.__new__(cls, name, bases, attrs)\n\nclass Mylist(list, metaclass = ListMetaclass):\n pass\n\n\n# In[3]:\n\n\nL = Mylist()\nL2 = list()\n\n\n# In[4]:\n\n\nL.add(2)\nL.append(22)\nL\n\n\n# In[5]:\n\n\nL2.add(2)\n\n\n# In[10]:\n\n\nclass Field(object):\n #def __init__(self, name, column_type, primary_key, default):\n def __init__(self, name, column_type):\n self.name = name\n self.column_type = column_type\n# self.primary_key = primary_key\n# self.default = default\n \n def __str__(self):\n# return '<%s, %s:%s>' % ( self.__class__.__name__, self.column_type, self.name )\n return '<%s:%s>' % ( self.__class__.__name__, self.name )\n \nclass StringField(Field):\n# def __init__(self, name = None, primary_key = False, default = None, ddl = 'varchar(100)'):\n# super.__init__(name, ddl, primary_key, default)\n def __init__(self, name):\n super(StringField, self).__init__(name, 'varchar(100)')\n \nclass IntegerField(Field):\n def __init__(self, name):\n super(IntegerField, self).__init__(name, 'bigint')\n \nclass ModelMetaclass(type):\n def __new__(cls ,name, bases, attrs):\n #排除Model类本身\n if name == 'Model':\n return type.__new__(cls, name, bases, attrs)\n #获取table名称:\n #tableName = attrs.get('__table__', None) or name\n #logger.info('Found mode: %s (table: %s)' % (name, tableName))\n #获取所有的Field和主键名称\n mappings = dict()\n#self#我想在此处添加log代码,获取attrs以及attrs.items的真面目\n for k, v in attrs.items():\n if isinstance(v, Field):\n logger.info('Found mapping: %s --> %s' % (k, v))\n mappings[k] = v\n for k in mappings.keys():\n attrs.pop(k)\n attrs['__mappings__'] = mappings #保存属性和映射的关系\n #attrs['__table__'] = tableName\n attrs['__table__'] = name #假设表名和类名一致\n # 构造默认的SELECT, INSERT, UPDATE和DELETE语句:\n #attrs['__select__'] = 'select `%s`, %s from `%s`' % (primaryKey, ','.join(escaped_fields), from tableName)\n #attrs['__insert__'] = 'insert into `%s` (%s, `%s`) values (%s)' % (tableName, ','.join(escaped_fields), primaryKey, creat_args_string(len(escaped_fields) + 1))\n #attrs['__update__'] = 'update `%s` set %s where `%s` = ?' % (tableName, ','.join(map(lambda f: '`%s` = ?' % (mappings.get(f).name or f), fields)), primaryKey)\n #attrs['__delete__'] = 'delete from %s where `%s` = ? ' % (tableName, primaryKey)\n return type.__new__(cls, name, bases, attrs)\n \n\n\n# In[11]:\n\n\nclass Model(dict, metaclass=ModelMetaclass):\n\n def __init__(self, **kw):\n super(Model, self).__init__(**kw)\n #for kkw in **kw:\n # l.append(str(kkw))\n #logger.info('%s' % str(kkw))\n\n def __getatttr__(self, key):\n try:\n return self[key]\n except KeyError:\n raise AttributeError(r\"'Model' object has no attribute '%s'\" % key)\n\n def __setattr__(self, key, value):\n self[key] = value\n\n def save(self):\n fields = []\n params = []\n args = []\n for k, v in self.__mappings__.items():\n fields.append(v.name)\n params.append('?')\n print(k)\n print('++++++++++++')\n args.append(getattr(self, k, None))\n sql = 'insert into %s (%s) values (%s)' % (self.__table__, ','.join(fields), ','.join(params))\n print('SQL: %s' % sql)\n print('ARGS: %s' % str(args))\n\n\n# In[12]:\n\n\nclass User(Model):\n # 定义类的属性到列的映射\n #id = IntegerField('id')\n name = StringField('username')\n email = StringField('email')\n password = StringField('password')\n \n# 创建一个实例:\nu = User(id = 123345, name = 'Michael', email = 'test@orm.org', password = 'mypass')\n\n# 保存到数据库:\nu.save()\n\n\n# In[16]:\n\n\ngetattrs()\n\n\n# In[36]:\n\n\nu['df']='dfdf'\nu\n\n","sub_path":"codeout_webapp/exercise_lxf/metaclass0.py","file_name":"metaclass0.py","file_ext":"py","file_size_in_byte":4857,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"400737358","text":"from time import sleep\nimport copy\nfrom math import sqrt\nimport itertools as it\n\n\n\nclass Node:\n def __init__(self, state, f=0, g=0, h=0):\n self.state = state\n self.f = f\n self.g = g\n self.h = h\n\n\n\n def __repr__(self):\n return \"Node(\" + repr(self.state) + \", f=\" + repr(self.f) + \\\n \", g=\" + repr(self.g) + \", h=\" + repr(self.h) + \")\"\n\n\nnum_nodes = 0\ndepth = 0\n\ndef aStarSearch(startState, actionsF, takeActionF, goalTestF, hF):\n h = hF(startState)\n startNode = Node(state=startState, f=0 + h, g=0, h=h)\n return aStarSearchHelper(startNode, actionsF, takeActionF, goalTestF, hF, 12)\n\n\ndef aStarSearchHelper(parentNode, actionsF, takeActionF, goalTestF, hF, fmax):\n if goalTestF(parentNode.state):\n return ([parentNode.state], parentNode.g)\n ## Construct list of children nodes with f, g, and h values\n actions = actionsF(parentNode.state)\n if not actions:\n return (\"failure\", float('inf'))\n children = []\n for action in actions:\n global num_nodes\n num_nodes += 1\n (childState, stepCost) = takeActionF(parentNode.state, action)\n h = hF(childState)\n # print(\"stepCost: \", stepCost)\n g = parentNode.g + stepCost\n f = max(h + g, parentNode.f)\n childNode = Node(state=childState, f=f, g=g, h=h)\n children.append(childNode)\n while True:\n # find best child\n children.sort(key=lambda n: n.f) # sort by f value\n bestChild = children[0]\n if bestChild.f > fmax:\n return (\"failure\", bestChild.f)\n # next lowest f value\n alternativef = children[1].f if len(children) > 1 else float('inf')\n # expand best child, reassign its f value to be returned value\n result, bestChild.f = aStarSearchHelper(bestChild, actionsF, takeActionF, goalTestF,\n hF, min(fmax, alternativef))\n if result is not \"failure\": # g\n result.insert(0, parentNode.state) # /\n global depth\n depth = bestChild.f\n return (result, bestChild.f)\n\n\ndef depthLimitedSearch(state, goalState, actionsF, takeActionF, depthLimit):\n if state == goalState:\n return []\n if depthLimit == 0:\n return 'cutoff' # to signal that the depth limit was reached\n cutoffOccurred = False\n #print(\"state: \", state)\n for action in actionsF(state):\n # print('action: ', action)\n childState, throwAway = takeActionF(state, action)\n result = depthLimitedSearch(childState, goalState, actionsF, takeActionF, depthLimit - 1)\n if result == 'cutoff':\n cutoffOccurred = True\n elif result != 'failure':\n result.insert(0, childState)\n return result\n if cutoffOccurred:\n return 'cutoff'\n else:\n return 'failure'\n\n\ndef iterativeDeepeningSearch(startState, goalState, actionsF, takeActionF, maxDepth):\n for depth_l in range(maxDepth):\n result = depthLimitedSearch(startState, goalState, actionsF, takeActionF, depth_l)\n if result == 'failure':\n return 'failure'\n if result != 'cutoff':\n result.insert(0, startState)\n global depth\n depth = depth_l\n return result\n return 'cutoff'\n\n\n# return the row and column index for the location of the blank (the 0 value).\ndef findBlank_8p(state):\n x, y = 0, 0\n for position in state:\n if position == 0:\n return y, x\n x = (x + 1) % 3\n if x == 0:\n y += 1\n\n\n# returns a list of up to four valid actions that can be applied in state. Return them in\n# the order left, right, up, down, though only if each one is a valid action.\ndef actionsF_8p(state):\n output = []\n y, x = findBlank_8p(state)\n if x > 0: # room to move left\n output.append(('left', 1))\n if x < 2: # room to move right\n output.append(('right', 1))\n if y > 0: # room to move up\n output.append(('up', 1))\n if y < 2: # room to move down\n output.append(('down', 1))\n return output\n\n\n# return the state that results from applying action in state.\ndef takeActionF_8p(state, actionList):\n rstate = copy.deepcopy(state)\n y, x = findBlank_8p(state)\n # print('x: ', x, 'y: ', y)\n pos = x + y * 3\n # print('Position: ', pos)\n action = actionList[0]\n if action == 'down':\n rstate[pos], rstate[pos + 3] = state[pos + 3], state[pos]\n elif action == 'up':\n rstate[pos], rstate[pos - 3] = state[pos - 3], state[pos]\n elif action == 'left':\n rstate[pos], rstate[pos - 1] = state[pos - 1], state[pos]\n elif action == 'right':\n rstate[pos], rstate[pos + 1] = state[pos + 1], state[pos]\n return rstate, actionList[1]\n\n\ndef goalTestF_8p(state, goal):\n return state == goal\n\n\ndef h1_8p(state, goal):\n return 0\n\n\ndef h2_8p(state, goal):\n y_dist, x_dist = findDist(state, goal)\n return y_dist + x_dist\n\n\ndef h3_8p(state, goal):\n y_dist, x_dist = findDist(state, goal)\n return sqrt(y_dist**2 + x_dist**2)\n\n\ndef findDist(state, goal):\n y, x = findBlank_8p(state)\n yg, xg = findBlank_8p(goal)\n return abs(yg-y), abs(xg-x)\n\n\ndef ebf(nNodes, depth, precision=0.01):\n if nNodes == 1:\n return 1\n if nNodes < 1:\n return 0\n min = 1\n max = nNodes / depth if depth > 0 else nNodes\n b = max\n while True:\n bf = (1 - b ** (depth + 1)) / (1 - b)\n if abs(bf - nNodes) < precision:\n return b\n elif bf < nNodes:\n min = b\n b = (max + min) / 2\n elif bf > nNodes:\n max = b\n b = (min + max) / 2\n\n\ndef runExperiment(startState,goalState1, goalState2, goalState3, h_functions):\n goalStates = [goalState1, goalState2, goalState3]\n i = 0\n IDS = []\n Astar = [[]]\n tab = 0\n for goalState in goalStates:\n IDS.append(iterativeDeepeningSearch(startState, goalState, actionsF_8p, takeActionF_8p,12))\n print(goalState)\n print(\"Algorithm\\tDepth\\t\\tNodes\\t\\tEBF\")\n print(\"IDS\\t\\t{:d}\\t\\t{:d}\\t\\t{:.3f}\".format(depth, num_nodes, ebf(num_nodes, depth)))\n j = 0\n\n for hf in h_functions:\n Astar[j].append(aStarSearch(startState, actionsF_8p, takeActionF_8p,\n lambda s: goalTestF_8p(s, goalState), lambda s: hf(s, goalState)))\n print(\"A*h{:d}\\t\\t{:d}\\t\\t{:d}\\t\\t{:.3f}\".format(j+1, depth, num_nodes, ebf(num_nodes, depth)))\n j += 1\n print()\n\n\n\nif __name__ == \"__main__\":\n # print(aStarSearch([1, 2, 3, 4, 0, 5, 6, 7, 8],\n # actionsF_8p, takeActionF_8p,\n # lambda s: goalTestF_8p(s, [1, 0, 3, 4, 5, 8, 2, 6, 7]),\n # lambda s: h1_8p(s, [1, 0, 3, 4, 5, 8, 2, 6, 7])))\n startState = [1, 2, 3, 4, 0, 5, 6, 7, 8]\n goalState1 = [1, 2, 3, 4, 0, 5, 6, 7, 8]\n goalState2 = [1, 2, 3, 4, 5, 8, 6, 0, 7]\n goalState3 = [1, 0, 3, 4, 5, 8, 2, 6, 7]\n runExperiment(startState, goalState1, goalState2, goalState3, [h1_8p, h2_8p, h3_8p])\n\n\n","sub_path":"p3/Astar.py","file_name":"Astar.py","file_ext":"py","file_size_in_byte":7096,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"289685335","text":"import requests\r\nimport urllib\r\nimport json\r\nimport os\r\nword = input(\"请输入歌曲名或者歌手名:\")\r\nn=input(\"请输入希望下载歌曲排行榜多少首:\")\r\nres1 = requests.get('https://c.y.qq.com/soso/fcgi-bin/client_search_cp?&t=0&aggr=1&cr=1&catZhida=1&lossless=0&flag_qc=0&p=1&n='+n+'&w='+word)\r\n\r\njm1 = json.loads(res1.text.strip('callback()[]'))\r\njm1 = jm1['data']['song']['list']\r\nmids = []\r\nsrcs = []\r\nsongnames = []\r\nsingers = []\r\nfor j in jm1:\r\n\r\n try:\r\n mids.append(j['media_mid'])\r\n songnames.append(j['songname'])\r\n singers.append(j['singer'][0]['name'])\r\n except:\r\n print('wrong')\r\n\r\n\r\nfor n in range(0,len(mids)):\r\n res2 = requests.get('https://c.y.qq.com/base/fcgi-bin/fcg_music_express_mobile3.fcg?&jsonpCallback=MusicJsonCallback&cid=205361747&songmid='+mids[n]+'&filename=C400'+mids[n]+'.m4a&guid=6612300644')\r\n jm2 = json.loads(res2.text)\r\n vkey = jm2['data']['items'][0]['vkey']\r\n srcs.append('http://dl.stream.qqmusic.qq.com/C400'+mids[n]+'.m4a?vkey='+vkey+'&guid=6612300644&uin=0&fromtag=66')\r\nprint('For '+word+' Start download...')\r\nx = len(srcs)\r\nif os.path.exists(\"d:/music/\"):\r\n pass\r\nelse:\r\n print(\"D盘没有music文件,现在已创建用于保存歌曲\")\r\n os.makedirs(\"d:\\\\music\\\\\")\r\nfor m in range(0,x):\r\n print(str(m)+'***** '+songnames[m]+' - '+singers[m]+'.m4a *****'+' 正在下载...')\r\n try:\r\n print(srcs[m])\r\n #urllib.request.urlretrieve(srcs[m],'d:/music/'+songnames[m]+' - '+singers[m]+'.m4a')\r\n\r\n except:\r\n x = x - 1\r\n print('下载完成~')\r\nprint('For ['+word+'] 已下载 '+str(x)+'首歌曲 !保存在D盘music文件夹中')\r\n\r\n\r\n\r\n","sub_path":"QQ音乐下载.py","file_name":"QQ音乐下载.py","file_ext":"py","file_size_in_byte":1685,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"429877620","text":"#!/usr/bin/python\n\nimport time\n\nimport roslib\nroslib.load_manifest('cob_script_server')\nimport rospy\n\nimport simple_script_server\nimport script_utils\nimport sys\nsys.path.insert(0,'/home/cob/svn/cob/Tests/GO/')\nfrom ScriptUtils import *\nfrom ScriptParameter import *\ndel sys.path[0]\n\nclass GraspFromCoolerAndDeliver(ssscript):\n\n\tdef Initialize(self, servers):\n\t\tself.su = script_utils.script_utils()\n\t\tself.util = ScriptUtils(servers)\n\t\tself.sss.Init(\"tray\")\n\t\tself.sss.Init(\"torso\")\n\t\tself.sss.Init(\"arm\")\n\t\tself.sss.Init(\"sdh\")\n\t\t# Move all components to starting positions\n\t\tself.sss.Move(\"tray\",\"down\",False)\n\t\tself.sss.Move(\"sdh\",\"home\",False)\n\t\tself.sss.Move(\"torso\",\"back\",False)\n\t\tself.su.MoveLED(\"arm\",\"folded\")\n\t\tself.sss.SetLight(\"green\")\n\t\t\n\t\t\n\tdef GraspFromCooler(self): \n\t\trospy.loginfo(\"Grasping water from cooler...\")\n\n\t\t# start grasping, assuming that Care-O-bot stands right in front of the water cooler\n\t\thandle01 = self.sss.Move(\"arm\",\"pregrasp\",False)\n\t\tself.su.MoveLED(\"sdh\",\"coolerbuttonup\")\n\t\thandle01.wait()\n\n\t\t# lay finger on cooler button and get water\n\t\tself.su.MoveLED(\"arm\",\"coolerbutton\")\n\t\tself.sss.Move(\"sdh\",\"coolerbuttondown\")\n\t\tself.sss.sleep(3)\n\t\tself.sss.Move(\"sdh\",\"coolerbuttonup\")\n\t\t\n\t\t# move hand to cup and grasp it\n\t\thandle01 = self.sss.Move(\"arm\",\"coolerpregrasp\",False)\n\t\tself.sss.sleep(0.5)\n\t\tself.sss.Move(\"sdh\",\"cylclosed\")\n\t\thandle01.wait()\n\t\tself.sss.Move(\"sdh\",\"coolercupopen\")\n\t\tself.su.MoveLED(\"arm\",\"coolergrasp\")\n\t\tself.sss.Move(\"sdh\",\"coolercupclosed\")\n\n\t\t# draw hand back and place cup on tablet\n\t\tself.su.MoveLED(\"arm\",\"coolerpostgrasp\")\n\t\thandle01 = self.sss.Move(\"arm\",\"coolerpostgrasp-to-tablet\",False)\n\t\tself.sss.sleep(2)\n\t\tself.sss.Move(\"torso\",\"front\",False)\n\t\tself.sss.Move(\"tray\",\"up\")\n\t\thandle01.wait()\n\t\tself.su.MoveLED(\"arm\",\"tablet\")\n\t\tself.sss.Move(\"sdh\",\"cuprelease\")\n\n\t\t# draw hand back and fold arm\n\t\thandle01 = self.sss.Move(\"arm\",\"tablet-to-folded\",False)\n\t\tself.sss.sleep(2)\n\t\tself.sss.Move(\"sdh\",\"home\")\n\t\thandle01.wait()\n\t\treturn 0\n\t\n\tdef DriveToCooler(self):\n\t\trospy.loginfo(\"Driving to water cooler ...\")\n\n\t\t# get watercooler position from parameters\n\t\tposition_param = \"script_server/base/watercooler_mm_deg\"\n\t\tif not rospy.has_param(position_param):\n\t\t\trospy.logerr(\"parameter %s does not exist on ROS Parameter Server, aborting...\",position_param)\n\t\t\treturn -2\n\t\telse:\n\t\t\tposition = rospy.get_param(position_param)\n\t\t\thandle01 = self.sss.Move(\"torso\",\"back\",False)\n\t\t\tself.util.movePlatformWait(*position)\n\t\t\thandle01.wait()\n\t\treturn 0\n\n\tdef DeliverDrink(self):\n\t\trospy.loginfo(\"Delivering drink ...\")\n\t\t\n\t\t# drive to delivery position at the table\n\t\tposition_param = \"script_server/base/table_mm_deg\"\n\t\tif not rospy.has_param(position_param):\n\t\t\trospy.logerr(\"parameter %s does not exist on ROS Parameter Server, aborting...\",position_param)\n\t\t\treturn -2\n\t\telse:\n\t\t\tposition = rospy.get_param(position_param)\n\t\t\thandle01 = self.sss.Move(\"torso\",\"front\",False)\n\t\t\tself.util.movePlatformWait(*position)\n\t\t\thandle01.wait()\n\n\t\t# offer drink\n\t\thandle01 = self.sss.Move(\"torso\",\"left\",False)\n\t\tself.su.SpeakRandom(\"offer\")\n\t\thandle01.wait()\n\t\tself.sss.Move(\"torso\",\"right\")\n\t\tself.sss.Move(\"torso\",\"front\")\n\t\t\n\t\t# check if drink has been taken and thank user\n\t\ttaken_param = self.sss.wait_for_input()\n\t\tif taken_param == \"\\n\":\n\t\t\thandle01 = self.sss.Move(\"torso\",\"bow\",False)\n\t\t\tself.su.SpeakRandom(\"taken\")\n\t\t\thandle01.wait()\n\t\t\tself.sss.sleep(0.5)\n\t\t\t\t\n\t\t# back away and fold tablet if possible\n\t\tposition_param = \"script_server/base/watercooler_mm_deg\"\n\t\tif not rospy.has_param(position_param):\n\t\t\trospy.logerr(\"parameter %s does not exist on ROS Parameter Server, aborting...\",position_param)\n\t\t\treturn -2\n\t\telse:\n\t\t\tposition = rospy.get_param(position_param)\n\t\t\tself.util.movePlatformWait(*position)\n\t\tif taken_param == \"\\n\":\n\t\t\tself.sss.Move(\"tray\",\"down\",False)\n\t\treturn 0\n\t\t\n\tdef run(self):\n\t\tself.Initialize()\n\t\tself.DriveToCooler()\n\t\tself.GraspFromCooler()\n\t\tself.DeliverDrink()\n\t\tself.sss.Move(\"sdh\",\"coolercupopen\")\n\t\tself.su.MoveLED(\"arm\",\"coolergrasp\")\n\t\tself.sss.wait_for_input()\n\t\tself.sss.Move(\"sdh\",\"coolercupclosed\")\n\t\tself.su.MoveLED(\"arm\",\"grasp-to-tablet\")\n\t\tself.su.MoveLED(\"arm\",\"tablet-to-folded\")\n\nif __name__ == \"__main__\":\n\tservers = Servers()\n\tSCRIPT = GraspFromCoolerAndDeliver(servers)\n\tSCRIPT.Start('grasp_deliver')\n\t#SCRIPT.Initialize()\n\tSCRIPT.run()\n","sub_path":"cob_script_server/scripts/grasp_from_cooler_and_deliver.py","file_name":"grasp_from_cooler_and_deliver.py","file_ext":"py","file_size_in_byte":4363,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"484062824","text":"\nimport tensorflow as tf\nfrom layers import * \nfrom utils import *\nfrom PFCNN import PFCNN\nimport argparse\nimport math \nimport numpy as np \nimport os\n\nparser = argparse.ArgumentParser()\nparser.add_argument('--config', type=str, required=True, \n help='Config File')\nargs = parser.parse_args()\nmodule = __import__(args.config)\nFLAGS = module.FLAGS\n\ndef parse_function_scannet(example_proto):\n feature_discription = {\n 'label': tf.FixedLenFeature([], tf.string),\n 'mesh_name': tf.FixedLenFeature([], tf.string),\n 'shape': tf.FixedLenFeature([], tf.string),\n #'coord': tf.FixedLenFeature([], tf.string),\n 'normal': tf.FixedLenFeature([], tf.string),\n 'feature_channel': tf.FixedLenFeature([], tf.int64),\n 'input_feature': tf.FixedLenFeature([], tf.string),\n 'rgb': tf.FixedLenFeature([], tf.string),\n 'z': tf.FixedLenFeature([], tf.string),\n 'maxpool/offset': tf.FixedLenFeature([], tf.string),\n 'maxpool/arg': tf.FixedLenFeature([], tf.string),\n 'maxpool/indices': tf.FixedLenFeature([], tf.string),\n 'unpooling/indices': tf.FixedLenFeature([], tf.string),\n 'conv/offset': tf.FixedLenFeature([], tf.string),\n 'conv/indices': tf.FixedLenFeature([], tf.string),\n 'conv/weights': tf.FixedLenFeature([], tf.string),\n }\n return tf.parse_single_example(example_proto, feature_discription)\n\n\ndef decode_record_scannet(record, axis_num, level_num, is_training):\n maxpooling_matrix_list = []\n maxpooling_arg_list = []\n unpooling_list = []\n conv_matrix_list = []\n\n label = tf.decode_raw(record['label'], tf.int32)\n \n rgb = tf.decode_raw(record['rgb'], tf.float32)\n rgb = tf.reshape(rgb, (-1, 3))\n \n normal = tf.decode_raw(record['normal'], tf.float32)\n normal = tf.reshape(normal, (-1, 3))\n\n #coord = tf.decode_raw(record['coord'], tf.float32)\n #coord = tf.reshape(coord, (-1, 3))\n\n #center = tf.reduce_mean(coord, axis=0)\n\n if(is_training):\n theta = tf.random.uniform([], -math.pi, math.pi, dtype=tf.float32)\n rotate_M = tf.convert_to_tensor([[tf.math.cos(theta), -tf.math.sin(theta), 0],[tf.math.sin(theta), tf.math.cos(theta),0], [0, 0, 1]])\n normal = tf.matmul(normal, rotate_M)\n \n #translation = tf.convert_to_tensor([center[0] , center[1], 0])\n #coord = tf.matmul((coord - translation), rotate_M) + translation\n\n z = tf.decode_raw(record['z'], tf.float32)\n z = tf.expand_dims(z, 1)\n\n pointwise_input = tf.concat([rgb, normal, z], axis=-1)\n #pointwise_input = tf.concat([rgb, normal, coord], axis=-1)\n pointwise_input = FeatureDuplicate(pointwise_input, axis_num)\n \n mesh_name = record['mesh_name']\n label = tf.cast(label, tf.int32)\n shape_list = tf.decode_raw(record['shape'], tf.int32)\n shape_list = tf.reshape(shape_list, (-1, 4))\n\n #feature_channel = record['feature_channel']\n #feature_channel = tf.cast(feature_channel, tf.int32)\n input_feature = tf.decode_raw(record['input_feature'], tf.float32)\n #input_feature = tf.reshape(input_feature, (shape_list[0][0]*shape_list[0][1]*shape_list[0][2]*shape_list[0][3], 1))\n\n maxpooling_offset = tf.decode_raw(record['maxpool/offset'], tf.int32)\n maxpooling_arg_list = tf.decode_raw(record['maxpool/arg'], tf.int32)\n maxpooling_indices_list = tf.decode_raw(record['maxpool/indices'], tf.int32)\n unpooling_indices_list = tf.decode_raw(record['unpooling/indices'], tf.int32)\n\n conv_offset = tf.decode_raw(record['conv/offset'], tf.int32)\n conv_indices_list = tf.decode_raw(record['conv/indices'], tf.int32)\n #conv_weights_list = tf.decode_raw(record['conv/weights'], tf.float64)\n conv_weights_list = tf.decode_raw(record['conv/weights'], tf.float32)\n conv_begin = 0\n pool_begin = 0\n input_begin = 0\n\n input_local_feature = []\n\n for level_i in range(level_num):\n input_feature_leveli = tf.slice(input_feature, [input_begin], [shape_list[level_i][0] * shape_list[level_i][1] * shape_list[level_i][2]* shape_list[level_i][3]])\n input_local_feature.append(input_feature_leveli)\n input_begin += shape_list[level_i][0] * shape_list[level_i][1] * shape_list[level_i][2]* shape_list[level_i][3]\n\n conv_indices = tf.slice(conv_indices_list, [2 * conv_begin], [2 * conv_offset[level_i]])\n conv_indices = tf.cast(tf.reshape(conv_indices, (conv_offset[level_i], 2)), tf.int64)\n conv_weights = tf.slice(conv_weights_list, [conv_begin], [conv_offset[level_i]])\n conv_matrix_list.append(Conv_Matrix(shape_list[level_i][0], shape_list[level_i][1], shape_list[level_i][2], shape_list[level_i][3], conv_indices, conv_weights))\n conv_begin = conv_begin + conv_offset[level_i]\n \n for level_i in range(level_num - 1):\n maxpooling_indices = tf.slice(maxpooling_indices_list, [2 * pool_begin], [2 * maxpooling_offset[level_i]])\n maxpooling_indices = tf.cast(tf.reshape(maxpooling_indices, (maxpooling_offset[level_i], 2)), tf.int64)\n maxpooling_values = tf.ones(shape=[maxpooling_offset[level_i]], dtype=tf.float32)\n\n maxpooling_matrix_list.append(MaxPooling_Matrix(shape_list[level_i][0], shape_list[level_i + 1][0], shape_list[level_i][1], maxpooling_indices, maxpooling_values, maxpooling_arg_list[level_i]))\n\n unpooling_indices = tf.slice(unpooling_indices_list, [2 * pool_begin], [2 * maxpooling_offset[level_i]])\n unpooling_values = tf.ones(shape=[maxpooling_offset[level_i]], dtype=tf.float32)\n unpooling_indices = tf.cast(tf.reshape(unpooling_indices, (maxpooling_offset[level_i], 2)), tf.int64)\n unpooling_list.append(UnPooling_Matrix(shape_list[level_i][0], shape_list[level_i + 1][0], shape_list[level_i][1], unpooling_indices, unpooling_values))\n\n pool_begin = pool_begin + maxpooling_offset[level_i]\n #print(conv_matrix_list[0].shape)\n #print(pointwise_input.shape)\n point_grid_input = tf.sparse_tensor_dense_matmul(conv_matrix_list[0], pointwise_input, adjoint_a=False, adjoint_b=False)\n input_feature = tf.concat([tf.expand_dims(input_local_feature[0], axis=1), point_grid_input], axis=-1)\n return mesh_name, label, shape_list, input_feature, maxpooling_matrix_list, maxpooling_arg_list, conv_matrix_list, unpooling_list, input_local_feature\n\n\ndef Scannet_network(record, G_num, level_num, conv_shape, class_num, reuse, is_point_feature, feature_channel, drop_out=0):\n F_len = 64\n\n mesh_name, label, shape_list, input_tensor, maxpooling_matrix_list, maxpooling_arg_list, conv_matrix_list, unpooling_matrix_list, input_local_feature = decode_record_scannet(record, G_num, level_num, is_training=not reuse)\n grid_input = True\n\n level0_feature = Conv_ResBlock(input_tensor, conv_shape, 'level0', conv_matrix_list[0], F_len, G_num, 2, reuse, feature_channel=feature_channel, grid_input=grid_input, drop_out=drop_out)\n level1_feature = MaxPooling(level0_feature, maxpooling_matrix_list[0], maxpooling_arg_list[0])\n level1_feature = Conv_ResBlock(level1_feature, conv_shape, 'level1', conv_matrix_list[1], F_len*2, G_num, 2, reuse, drop_out=drop_out)\n\n level2_feature = MaxPooling(level1_feature, maxpooling_matrix_list[1], maxpooling_arg_list[1])\n level2_feature = Conv_ResBlock(level2_feature, conv_shape, 'level2', conv_matrix_list[2], F_len*2, G_num, 2, reuse, drop_out=drop_out)\n\n level2_unpooling = AverageUnPooling(level2_feature, unpooling_matrix_list[1])\n level1_concated = tf.concat([level1_feature, level2_unpooling], axis=1)\n level1_f = Conv_ResBlock(level1_concated, conv_shape, 'level1_concated', conv_matrix_list[1], F_len, G_num, 2, reuse, drop_out=drop_out)\n\n level0_unpooling = AverageUnPooling(level1_f, unpooling_matrix_list[0])\n concated = tf.concat([level0_feature, level0_unpooling], axis=1)\n level0_f = Conv_ResBlock(concated, conv_shape, 'level0_concated', conv_matrix_list[0], F_len, G_num, 2, reuse, drop_out=drop_out)\n\n level0_f = FeatureReduce(level0_f, G_num)\n \n logits = tf.contrib.layers.fully_connected(level0_f, class_num, activation_fn=None, reuse=reuse, scope=\"FC2\")\n \n class_freq = np.array([27058943,31580147,4774264,3489188,11780978,3990890,6459052,4220890,3569190,3114588,569066,615475,2631772,2124020,697917,368098,308121,305113,348714,5016365], dtype=np.float32)\n\n class_freq = class_freq / class_freq.sum()\n\n class_weights = 1/np.log(1.01+class_freq)\n class_weights = tf.expand_dims(class_weights, axis=-1)\n \n #mask label 0\n non_zero_mask = tf.cast(label, tf.bool)\n masked_logits = tf.boolean_mask(logits, non_zero_mask)\n masked_label = tf.boolean_mask(label, non_zero_mask)\n masked_predicted = tf.cast(tf.argmax(masked_logits, axis=1), tf.int32)\n raw_predicted = tf.cast(tf.argmax(logits, axis=1), tf.int32)\n\n label_count = tf.reduce_sum(masked_label, axis=0)\n\n output = {}\n\n output['raw_predicted'] = raw_predicted\n output['masked_label'] = masked_label\n output['masked_predicted'] = masked_predicted\n output['label_count'] = label_count\n normalized_logits = tf.nn.softmax(logits, axis=-1)\n output['normalized_logits'] = normalized_logits\n\n #v_num * 20\n #masked_label : [1...20] -> [0...19]\n masked_label_onehot = tf.one_hot(indices=masked_label-1, depth=class_num-1)\n\n #pred_label : [0...20] -> [-1...19]\n #onehot : -1 -> [0, 0, ... ,0]\n masked_pred_onehot = tf.one_hot(indices=masked_predicted-1, depth=class_num-1)\n\n loss_weights = tf.matmul(masked_label_onehot, class_weights)\n loss_weights = tf.squeeze(loss_weights)\n\n cross_entropy = tf.reduce_mean(tf.multiply(loss_weights, tf.nn.sparse_softmax_cross_entropy_with_logits(logits=masked_logits, labels=masked_label)))\n\n class_corr_sum = tf.reduce_sum(tf.multiply(masked_label_onehot, masked_pred_onehot), axis=0)\n class_corr_sum = tf.cast(class_corr_sum, tf.int32)\n\n Union = tf.reduce_sum(tf.cast(tf.cast(tf.add(masked_label_onehot, masked_pred_onehot), tf.bool), tf.int32), axis=0)\n Union = tf.cast(Union, tf.float32)\n\n #v_num * 1\n acc = tf.reduce_mean(tf.cast(tf.equal(masked_predicted, masked_label), tf.float32))\n acc = tf.expand_dims(acc, axis=0)\n \n label_sum = tf.reduce_sum(masked_label_onehot, axis=0)\n\n output['accuracy'] = acc\n output['name'] = mesh_name\n output['loss'] = cross_entropy\n output['logits'] = masked_logits\n output['predicted'] = masked_predicted\n output['vnum'] = tf.shape(logits)[0]\n output['class_corr_sum'] = class_corr_sum\n output['class_Union'] = Union\n output['label'] = label\n output['label_sum'] = label_sum\n return output\n\nclass PFCNN_Scannet(PFCNN):\n def __init__(self, FLAGS):\n super(PFCNN_Scannet, self).__init__(parse_function_scannet, Scannet_network, FLAGS)\n \n def build_dataset(self):\n train_names = []\n for i in range(self.flags.train_part):\n train_names.append(self.flags.tfrecord_path + self.flags.train_data + \"_%d.tfrecords\" % i)\n self.train_data = self.parse_dataset(train_names)\n test_names = []\n for i in range(self.flags.test_part):\n test_names.append(self.flags.tfrecord_path + self.flags.test_data + \"_%d.tfrecords\" % i)\n self.test_data = self.parse_dataset(test_names) \n\n def build_summary(self):\n super(PFCNN_Scannet, self).build_summary()\n self.test_set_mA = tf.placeholder(dtype=tf.float32, name=\"test_set_mA\")\n self.test_mA_summary = tf.summary.scalar('test_mean_accuracy', self.test_set_mA)\n\n self.test_set_IOU = tf.placeholder(dtype=tf.float32, name=\"test_set_IOU\")\n self.test_IOU_summary = tf.summary.scalar('test_mean_IOU', self.test_set_IOU)\n\n def train(self):\n config = tf.ConfigProto(allow_soft_placement=True, log_device_placement=False)\n with tf.Session(config=config) as sess:\n start_epoch = 0\n init = tf.global_variables_initializer()\n sess.run(init)\n if(self.flags.is_load_model):\n self.saver.restore(sess, self.flags.model_path)\n start_epoch = self.flags.start_epoch\n print(self.flags.model_path)\n print(\"load model success!\")\n train_writer = tf.summary.FileWriter(self.flags.summaries_dir + '/train', sess.graph)\n test_writer = tf.summary.FileWriter(self.flags.summaries_dir + '/test')\n best_acc = 0\n\n if not os.path.exists(self.flags.summaries_dir+'/ckpt'):\n os.mkdir(self.flags.summaries_dir+'/ckpt')\n if not os.path.exists(self.flags.summaries_dir+'/pred'):\n os.mkdir(self.flags.summaries_dir+'/pred')\n os.mkdir(self.flags.summaries_dir+'/logits')\n \n lr = self.flags.learning_rate\n for epoch_i in range(start_epoch, start_epoch + self.flags.epoch_num):\n if(epoch_i > 0 and epoch_i % self.flags.decay_epoch == 0 and lr>1e-4):\n lr = lr / 2\n print(\"\\nepoch \" + str(epoch_i) + \" training:\")\n print(\"learning rate: \"+ str(lr))\n train_acc_sum = 0.0\n for iter_j in range(self.flags.train_size):\n training_output, merged_sum, _ = sess.run([self.train_output, self.merged_train_summ, self.train_step], feed_dict={self.learning_rate: lr})\n train_writer.add_summary(merged_sum, iter_j + self.flags.train_size * epoch_i)\n train_acc_sum = train_acc_sum + training_output['accuracy'].sum() / len(training_output['accuracy'])\n print(\"epoch \" + str(epoch_i) + \" training acc:\" + str(train_acc_sum / self.flags.train_size) + \"\\n\")\n train_ave_acc = sess.run(self.train_acc_summary, feed_dict={self.train_set_accuracy: train_acc_sum / self.flags.train_size})\n train_writer.add_summary(train_ave_acc, epoch_i)\n if(epoch_i % self.flags.test_epoch == 0):\n test_acc_sum = 0.0\n result_list = []\n Union_list = []\n label_count_list = []\n for iter_j in range(self.flags.test_size):\n testing_output, test_summary = sess.run([self.test_output, self.merged_test_summ])\n result_list.append(testing_output['class_corr_sum'])\n Union_list.append(testing_output['class_Union'])\n label_count_list.append(testing_output['label_count'])\n test_writer.add_summary(test_summary, iter_j + self.flags.test_size * epoch_i)\n test_acc_sum = test_acc_sum + testing_output['accuracy'].sum() / len(testing_output['accuracy'])\n print(\"epoch \" + str(epoch_i) + \" testing acc:\" + str(test_acc_sum / self.flags.test_size) + \"\\n\")\n test_ave_acc = sess.run(test_acc_summary, feed_dict={test_set_accuracy: test_acc_sum / self.flags.test_size})\n test_writer.add_summary(test_ave_acc, epoch_i)\n\n result_list = np.array(result_list)\n pred_sum = np.sum(result_list, axis=0)\n \n label_count_list = np.array(label_count_list)\n label_sum = np.sum(label_count_list)\n \n class_acc = (pred_sum/label_sum)\n mean_acc = np.mean(class_acc)\n print(\"testing mean acc:\", mean_acc)\n\n Union_list = np.array(Union_list)\n Union_sum = np.sum(Union_list, axis=0)\n class_IOU = (pred_sum/Union_sum)\n mean_IOU = np.mean(class_IOU)\n print(\"testing mean IOU:\", mean_IOU)\n\n test_IOU_acc = sess.run(self.test_IOU_summary, feed_dict={self.test_set_IOU: mean_IOU})\n test_writer.add_summary(test_IOU_acc, epoch_i)\n\n test_mA_acc = sess.run(self.test_mA_summary, feed_dict={self.test_set_mA: mean_acc})\n test_writer.add_summary(test_mA_acc, epoch_i)\n\n if(test_acc_sum / self.flags.test_size >= best_acc):\n best_acc = test_acc_sum / self.flags.test_size\n self.best_saver.save(sess, self.flags.summaries_dir+'/ckpt/' + self.flags.task + '_best.ckpt', global_step=epoch_i)\n\n if(epoch_i % self.flags.save_epoch == 0):\n self.saver.save(sess, self.flags.summaries_dir+'/ckpt/' + self.flags.task + '.ckpt' , global_step=epoch_i)\n\nif __name__ == \"__main__\":\n model = PFCNN_Scannet(FLAGS)\n model.build_graph()\n model.build_summary()\n model.train()\n\n","sub_path":"PFCNN/Scannet.py","file_name":"Scannet.py","file_ext":"py","file_size_in_byte":16726,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"631296317","text":"\"\"\"This module will serve the api request.\"\"\"\n\nfrom app import app\nfrom config import client, DATABASE, COLLECTION\nfrom flask import request, Response\nimport json\nimport imp\nimport logging\nimport sys\n\n\n# Get logger\nlogging.basicConfig(level=logging.INFO,\n format='%(asctime)s [%(levelname)s] %(message)s',\n stream=sys.stdout\n )\nlogger = logging.getLogger(__name__)\n\n\n# Import the helpers module\nhelper_module = imp.load_source('*', './app/helpers.py')\n\n# Select the database and collection\ncollection = client[DATABASE][COLLECTION]\n\n\n@app.route(\"/\")\ndef get_initial_response():\n \"\"\"Welcome message for the API.\"\"\"\n # Message to the client\n message = {\n 'message': 'Welcome to the Flask 591-rent API!'\n }\n return Response(json.dumps(message, ensure_ascii=False))\n\n\n@app.route(\"/items\", methods=['GET'])\ndef fetch_items():\n \"\"\"\n Function to fetch the rent items.\n \"\"\"\n logger.info('API request: GET /items')\n try:\n query_params = request.args.to_dict()\n query = helper_module.mongo_query_generator(query_params)\n logger.info('query: {}'.format(query))\n docs = [doc for doc in collection.find(query)]\n for doc in docs:\n doc.pop('_id')\n return Response(json.dumps({'data': docs}, ensure_ascii=False), mimetype='application/json')\n except BaseException as e:\n logger.error(str(e))\n return str(e), 500\n\n\n@app.errorhandler(404)\ndef page_not_found(e):\n \"\"\"Send message to the user with notFound 404 status.\"\"\"\n logger.error('[Page not found] {}'.format(e))\n # Message to the client\n message = {\n \"err\":\n {\n \"msg\": \"This route is currently not supported. Please refer API documentation.\"\n }\n }\n return Response(json.dumps(message, ensure_ascii=False))\n","sub_path":"app/api.py","file_name":"api.py","file_ext":"py","file_size_in_byte":1869,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"177513444","text":"# -*- coding: utf8 -*-\r\n__author__ = 'Tan'\r\n\r\nimport sys\r\nimport re\r\n\r\nreload(sys)\r\nsys.setdefaultencoding(\"utf8\")\r\n\r\ndict = {u'零': 0, u'一': 1, u'二': 2, u'三': 3, u'四': 4, u'五': 5, u'六': 6, u'七': 7, u'八': 8, u'九': 9, u'十': 10, u'百': 100,\r\n u'千': 1000, u'万': 10000,\r\n u'0': 0, u'1': 1, u'2': 2, u'3': 3, u'4': 4, u'5': 5, u'6': 6, u'7': 7, u'8': 8, u'9': 9,\r\n u'壹': 1, u'贰': 2, u'叁': 3, u'肆': 4, u'伍': 5, u'陆': 6, u'柒': 7, u'捌': 8, u'玖': 9, u'拾': 10, u'佰': 100,\r\n u'仟': 1000, u'萬': 10000,\r\n u'角': 0.1, u'分': 0.01, u'元': None}\r\n\r\n\r\ndef getResultForDigit(a, encoding=\"utf-8\"):\r\n if isinstance(a, str):\r\n a = a.decode(encoding)\r\n count = 0\r\n result = 0\r\n tmp = 0\r\n flag = False\r\n while count < len(a):\r\n tmpChr = a[count]\r\n # print tmpChr\r\n if tmpChr == u'元':\r\n flag = True\r\n tmpNum = dict.get(tmpChr, None)\r\n # 如果等于1万\r\n if tmpNum == 10000:\r\n result += tmp\r\n result = result * tmpNum\r\n tmp = 0\r\n # 如果等于十或者百,千\r\n elif tmpNum >= 10:\r\n if tmp == 0:\r\n tmp = 1\r\n result += tmpNum * tmp\r\n tmp = 0\r\n # 如果等于分、角\r\n elif 1 > tmpNum > 0:\r\n if tmp == 0:\r\n tmp = 1\r\n if tmpNum == 0.01 and tmp > 10:\r\n tmp2 = tmp\r\n tmp = tmp2 / 10 * 100 + tmp2 % 10\r\n result += tmpNum * tmp\r\n tmp = 0\r\n # 如果是个位数\r\n elif tmpNum is not None:\r\n tmp = tmp * 10 + tmpNum\r\n count += 1\r\n result = result + tmp\r\n if flag == False:\r\n return result\r\n else:\r\n if result == 0:\r\n return u'元'\r\n return str(result) + u'元'\r\n\r\n\r\ndef hanzi(test_str):\r\n while 1:\r\n result = re.search(u'[〇零一二三四五六七八九十百千万壹贰叁肆伍陆柒捌玖拾佰仟萬亿元角分]{3,}', test_str)\r\n if result:\r\n result = result.group()\r\n test_str = test_str.replace(result, str(getResultForDigit(result)), 1)\r\n else:\r\n break\r\n return test_str\r\n\r\n\r\ndef wanyuan(Strl):\r\n while 1:\r\n Num = re.search(u'[\\d\\.]+万', Strl)\r\n if Num:\r\n Num0 = Num.group(0)\r\n Num1 = (int)((float)(Num0[:-1]) * 10000)\r\n Num2 = str(Num1)\r\n Strl = Strl.replace(Num0, Num2, 1)\r\n else:\r\n break\r\n return Strl\r\n\r\n\r\ndef douhao(sen):\r\n sen = sen.replace(\",\", \",\")\r\n sen = sen.replace(\" \", \"\")\r\n while 1:\r\n mm = re.search(\"\\d,\\d\", sen)\r\n if mm:\r\n mm = mm.group()\r\n sen = sen.replace(mm, mm.replace(\",\", \"\"))\r\n # print sen\r\n else:\r\n break\r\n return sen\r\n","sub_path":"gridsum/CCF/PreProcess/pretranslate.py","file_name":"pretranslate.py","file_ext":"py","file_size_in_byte":2910,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"100483919","text":"import numpy as np\nfrom sklearn.metrics.pairwise import pairwise_distances\nfrom scipy.sparse import *\n\n\n# TODO requests changes for MultivariateFilter to be used there\nclass TraceRatioLaplacian(object):\n \"\"\"\n Creates TraceRatio(similarity based) feature selection filter\n performed in unsupervised way, i.e laplacian version\n\n Parameters\n ----------\n n_selected_features : int\n Amount of features to filter\n k : int\n number of neighbours to use for knn\n t : int\n constant for kernel function calculation\n\n - Note: in laplacian case only. In fisher it uses label similarity, i.e if both samples belong to same class\n\n Notes\n -----\n For more details see `this paper `_.\n\n Examples\n --------\n >>> from ITMO_FS.filters.unsupervised.trace_ratio_laplacian import TraceRatioLaplacian\n >>> from sklearn.datasets import make_classification\n >>> x, y = make_classification(1000, 100, n_informative = 10, \\\nn_redundant = 30, n_repeated = 10, shuffle = False)\n >>> tracer = TraceRatioLaplacian(10)\n >>> print(tracer.run(x, y)[0])\n\n\n \"\"\"\n\n def __init__(self, n_selected_features, k=5, t=1):\n self.n_selected_features = n_selected_features\n self.k = k\n self.t = t\n\n def run(self, X, y):\n \"\"\"\n Fits filter\n\n Parameters\n ----------\n X : numpy array, shape (n_samples, n_features)\n The training input samples\n y : numpy array, shape (n_samples, )\n The target values\n\n Returns\n ----------\n feature_indices : numpy array\n array of feature indices in X\n\n See Also\n --------\n\n Examples\n --------\n\n \"\"\"\n\n n_samples = X.shape[0]\n Distances = pairwise_distances(X)\n Distances **= 2\n Distances_NN = np.sort(Distances, axis=1)[:, 0:self.k + 1]\n Indices_NN = np.argsort(Distances, axis=1)[:, 0:self.k + 1]\n Kernel = np.exp(-Distances_NN / self.t)\n joined_distances = np.ravel(Kernel)\n indices_axis_one = np.ravel(Indices_NN)\n indices_axis_zero = np.repeat(np.arange(n_samples), self.k + 1)\n A_within = csc_matrix((joined_distances, (indices_axis_zero, indices_axis_one)), shape=(n_samples, n_samples))\n A_within = A_within - A_within.multiply(A_within.T > A_within) + A_within.T.multiply(A_within.T > A_within)\n D_within = np.diag(np.ravel(A_within.sum(1))) # check correctness\n L_within = D_within - A_within\n A_between = D_within.dot(np.ones((n_samples, n_samples))).dot(D_within) / np.sum(D_within)\n D_between = np.diag(A_between.sum(1))\n L_between = D_between - A_between\n\n L_within = (L_within.T + L_within) / 2\n L_between = (L_between.T + L_between) / 2\n E = X.T.dot(L_within).dot(X)\n B = X.T.dot(L_between).dot(X)\n E = (E.T + E) / 2\n B = (B.T + B) / 2\n\n # we need only diagonal elements for trace calculation\n e = np.absolute(np.diag(E))\n b = np.absolute(np.diag(B))\n b[b == 0] = 1e-14\n features_indices = np.argsort(np.divide(b, e))[::-1][0:self.n_selected_features]\n lam = np.sum(b[features_indices]) / np.sum(e[features_indices])\n prev_lam = 0\n while (lam - prev_lam >= 1e-3):\n score = b - lam * e\n features_indices = np.argsort(score)[::-1][0:self.n_selected_features]\n prev_lam = lam\n lam = np.sum(b[features_indices]) / np.sum(e[features_indices])\n return features_indices, score, lam\n","sub_path":"ITMO_FS/filters/unsupervised/trace_ratio_laplacian.py","file_name":"trace_ratio_laplacian.py","file_ext":"py","file_size_in_byte":3767,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"208828648","text":"from tagbase.models import *\nfrom django.db import IntegrityError\nfrom django.db.models import Q\n\nAUTO_USERNAME = 'autorobo'\nAUTO_USERPWD = 'autorobo'\nLIKE_TAG_NAME = 'like'\n\nclass BaseTagger(object):\n def _tag(self, object, tag, user):\n# live_tag = LiveTag.objects.create(content_object=object, tag=tag, user=user)\n f = LiveTagForm({'tag': tag.id, 'user': user.id})\n t = f.save(commit=False)\n t.content_object = object\n t.save()\n return t\n\n def get_tag(self, name):\n return Tag.objects.get(name=name)\n\n\nclass FunctionTagger(BaseTagger):\n def __init__(self, tag_name):\n self.autouser, created = User.objects.get_or_create(username=AUTO_USERNAME, password=AUTO_USERPWD)\n# self.tag_obj, created = FunctionTag.objects.get_or_create(user=self.autouser, name=tag_name)\n try:\n self.tag_obj = FunctionTag.objects.get(name=tag_name)\n except FunctionTag.DoesNotExist:\n f = FunctionTagForm({'user': self.autouser.id, 'name': tag_name})\n# print f.errors.as_text()\n self.tag_obj = f.save()\n\n def tag(self, object):\n return self._tag(object, self.tag_obj, self.autouser)\n\n\nclass LikeTagger(FunctionTagger):\n def search(self, queryset, user):\n \"Get all objects which the user vote 'like'\"\n qs = queryset.filter(tags__tag=self.tag_obj, tags__voters=user)\n return qs\n\n\nclass PinTagger(FunctionTagger):\n pass\n\n\nclass TrendTagger(FunctionTagger):\n pass\n\n\nclass WordTagger(BaseTagger):\n def search(self, queryset, tag_names):\n pass\n\n\nforbidden_tags = frozenset(t.name for t in ForbiddenTag.objects.all())\nclass NounTagger(WordTagger):\n def _get_or_create_tag(self, tag_name, user):\n try:\n t = NounTag.objects.get(name=tag_name)\n except NounTag.DoesNotExist:\n t = self._create_tag(tag_name, user)\n return t\n\n def _create_tag(self, tag_name, user):\n if tag_name in forbidden_tags:\n raise ForbiddenTagError(tag_name)\n# t = NounTag.objects.create(name=tag_name, user=user)\n f = NounTagForm({'name': tag_name, 'user': user.id})\n return f.save()\n\n def bulk_tag(self, object, tag_names, user):\n for t in tag_names:\n self.tag(object, t, user)\n\n def tag(self, object, tag_name, user):\n try:\n t = NounTag.objects.get(name=tag_name)\n except NounTag.DoesNotExist:\n t = self._create_tag(tag_name, user)\n live_tag = self._tag(object, t, user)\n# live_tag.voters.add(user)\n return live_tag\n\n def search(self, queryset, tag_names):\n \"Compute an && query, get all objects tagged with given tags.\"\n for n in tag_names:\n queryset = queryset.filter(tags__tag__name=n)\n return queryset\n\n\nclass GeneralTagger(object):\n def __init__(self):\n self.like = LikeTagger(LIKE_TAG_NAME)\n self.noun = NounTagger()\n\n def search(self, queryset, tag_names, user=None):\n tag_names = set(tag_names)\n fun_names = [LIKE_TAG_NAME]\n fun_names = set(fun_names)\n if LIKE_TAG_NAME in tag_names and user:\n tag_names.remove(self.like.tag_obj.name)\n qs = self.like.search(queryset, user)\n if tag_names:\n # quere for 'like' & ('tt1' & 'tt2' & ...)\n qs = self.noun.search(qs, tag_names)\n else:\n tag_names -= fun_names\n qs = self.noun.search(queryset, tag_names)\n return qs\n\n def vote(self, live_tag_id, user):\n live_tag = LiveTag.objects.select_related().get(id=live_tag_id)\n live_tag.vote(user=user)\n return live_tag\n\n def unvote(self, live_tag_id, user):\n live_tag = LiveTag.objects.select_related().get(id=live_tag_id)\n live_tag.unvote(user=user)\n return live_tag\n\n\nclass ForbiddenTagError(Exception):\n def __init__(self, tag):\n self.tag = tag","sub_path":"tagbase/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":3966,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"473921281","text":"from nltk.tokenize import RegexpTokenizer\nfrom nltk import FreqDist\nfrom nltk import bigrams\nfrom operator import itemgetter\n\nwords= RegexpTokenizer(r'\\w+').tokenize(open(\"C://Users/baazo/Desktop/Project/python_1/sms.txt\",\"r\",encoding='utf-8').read())\nstop_words= open(\"C://Users/baazo/Desktop/Project/python_1/sms.txt\",\"r\",encoding='utf-8').read().split()\n#words=[word for word in words if word not in stop_words]\nbigrams= bigrams(words)\nliste=[]\nfor big in bigrams:\n\tif big[1] not in stop_words and big[0] not in stop_words:\n\t\tliste.append(big)\nfreqdist= FreqDist(liste)\nfor item in sorted(freqdist.items(), key=itemgetter(1), reverse=True)[:10]:\n\tprint(item)\n","sub_path":"Last_First.py","file_name":"Last_First.py","file_ext":"py","file_size_in_byte":662,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"555205343","text":"#\n# Copyright 2020 QuantRocket LLC\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nimport os\nimport pandas as pd\nfrom zipline.data import bundles\nfrom zipline.data.data_portal import DataPortal\nfrom zipline.utils.extensions import load_extensions\nfrom zipline.research.exceptions import ValidationError\nfrom zipline.research._asset import asset_finder_cache\nfrom zipline.research.bundle import _get_bundle\nfrom zipline.finance.asset_restrictions import NoRestrictions\nfrom zipline.protocol import BarData\nfrom quantrocket.zipline import get_default_bundle, get_bundle_config\nfrom trading_calendars import get_calendar\n\ndef get_data(\n dt: str,\n bundle: str = None,\n data_frequency: str = None\n ) -> BarData:\n \"\"\"\n Return a `zipline.api.BarData` object for the specified bundle (or default bundle)\n as of the specified datetime. This is the same object that is passed\n as the `data` parameter to `handle_data` and other backtest functions.\n\n Parameters\n ----------\n dt : str (YYYY-MM-DD[ HH:MM:SS]), required\n The datetime (for minute data) or date (for daily data) which the\n data object should be anchored to.\n\n bundle : str, optional\n the bundle code. If omitted, the currently active bundle (as set with\n `zipline.research.use_bundle`) will be used, or if that has not been set,\n the default bundle (as set with `quantrocket.zipline.set_default_bundle`).\n\n data_frequency : str, optional\n the data frequency. Possible choices: daily, minute. The default is\n \"daily\" for daily bundles and \"minute\" for minute bundles. Minute\n bundles also support \"daily\".\n\n Returns\n -------\n data : zipline.api.BarData\n\n Notes\n -----\n Usage Guide:\n\n * Data Object: https://qrok.it/dl/z/zipline-research-data\n\n Examples\n --------\n Get the data object for July 7, 2020 at 11 AM for the usstock minute\n bundle::\n\n data = get_data('2020-07-07 11:00:00', bundle=\"usstock-1min\")\n\n Get the data object for July 7, 2020 for a daily bundle::\n\n data = get_data('2020-07-07', bundle=\"xjpx-1d-bundle\")\n \"\"\"\n if not bundle:\n bundle = _get_bundle()\n if not bundle:\n bundle = get_default_bundle()\n if not bundle:\n raise ValidationError(\"you must specify a bundle or set a default bundle\")\n bundle = bundle[\"default_bundle\"]\n\n load_extensions(code=bundle)\n\n bundle_data = bundles.load(\n bundle,\n os.environ,\n pd.Timestamp.utcnow(),\n )\n if not data_frequency:\n config = get_bundle_config(bundle)\n data_frequency = config[\"data_frequency\"]\n\n calendar_name = bundles.bundles[bundle].calendar_name\n trading_calendar = get_calendar(calendar_name)\n\n session_minute = pd.Timestamp(dt, tz=trading_calendar.tz)\n session = session_minute.normalize().tz_localize(None).tz_localize(\"UTC\")\n\n first_session = max(bundles.bundles[bundle].start_session, trading_calendar.first_session)\n if session < first_session:\n raise ValidationError(\n f\"date cannot be earlier than {first_session.date().isoformat()} for this bundle\")\n\n if not trading_calendar.is_session(session):\n raise ValidationError(f\"requested date {session.date().isoformat()} is not in {calendar_name} calendar\")\n\n if data_frequency == \"minute\" and not trading_calendar.is_open_on_minute(session_minute):\n raise ValidationError(f\"requested time {session_minute.isoformat()} is not in {calendar_name} calendar\")\n\n if data_frequency == \"minute\":\n equity_minute_reader = future_minute_reader = bundle_data.equity_minute_bar_reader\n else:\n equity_minute_reader = future_minute_reader = None\n\n asset_finder = asset_finder_cache.get(bundle, bundle_data.asset_finder)\n asset_finder_cache[bundle] = asset_finder\n\n data_portal = DataPortal(\n asset_finder,\n trading_calendar=trading_calendar,\n first_trading_day=bundle_data.equity_minute_bar_reader.first_trading_day,\n equity_minute_reader=equity_minute_reader,\n equity_daily_reader=bundle_data.equity_daily_bar_reader,\n future_minute_reader=future_minute_reader,\n future_daily_reader=bundle_data.equity_daily_bar_reader,\n adjustment_reader=bundle_data.adjustment_reader)\n\n data = BarData(\n data_portal=data_portal,\n simulation_dt_func=lambda: session_minute,\n data_frequency=data_frequency,\n trading_calendar=trading_calendar,\n restrictions=NoRestrictions()\n )\n\n return data\n","sub_path":"zipline/research/bardata.py","file_name":"bardata.py","file_ext":"py","file_size_in_byte":5076,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"227673526","text":"\"\"\"\nThis module contains the setup.py for running the Collidium tool\n\"\"\"\nfrom setuptools import setup, find_packages\nPACKAGES = find_packages()\n\nopts = dict(name='Collidium',\n maintainer='Alyssa Goodrich, Tejas Hosangadi, Ian Kirkman, Dan White',\n maintainer_email='dkwhite@uw.edu',\n description='Seattle Construction and Traffic Accident Visualization Tool',\n long_description=(\"\"\"Collidium is a tool that allows users to visualize and\n understand the impact of construction on the occurence of traffic accidents \n in the City of Seattle. It's structered as a Jupyter notebook with \n interactive controls\"\"\"),\n url='https://github.com/tejasmhos/seattlecollision',\n license='MIT',\n author='Collidium',\n author_email='dkwhite@uw.edu',\n version='0.1',\n packages=PACKAGES,\n package_data={'seattlecollision': ['data/*', 'tests/*']},\n )\n\nif __name__ == '__main__':\n setup(**opts)\n","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":1045,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"29114572","text":"import tensorflow as tf\nimport gym\n\nnum_inputs = 6\nnum_outputs = 3\n# play with this no idea what is good here:\nnum_hidden = 4\n\nlearning_rate = 0.01\n\nX = tf.placeholder(tf.float32, shape=[None, num_inputs])\nactf = tf.nn.relu\n\ninitalizer = tf.contrib.layers.variance_scaling_initializer()\n\nhidden_layer_1 = tf.layers.dense(\n X,\n num_hidden,\n activation=actf,\n kernel_initializer=initalizer)\n\nlogits = tf.layers.dense(\n hidden_layer_1,\n num_outputs)\n\n# get an action\noutputs = tf.nn.sigmoid(logits)\n\n# slightly randomly select an action based on the probabilties\naction = tf.multinomial(outputs,num_samples=1)\n\n# tensorflow doing some calculus:\ncross_entropy = tf.nn.sigmoid_cross_entropy_with_logits(labels=outputs, logits=logits)\noptimizer = tf.train.AdamOptimizer(learning_rate)\n\n# returns a list of the gradients and vars\ngradients_and_vars = optimizer.compute_gradients(cross_entropy)\n\ngradients = []\ngradient_placeholders = []\ngradients_and_vars_feed = []\n\n# put everything togehter in a way that optimizer can understand\nfor gradient, var in gradients_and_vars:\n gradients.append(gradient)\n gradient_placeholder = tf.placeholder(tf.float32,shape=gradient.get_shape())\n gradient_placeholders.append(gradient_placeholder)\n gradients_and_vars_feed.append((gradient_placeholder,var))\n\n# train\ntraining_op = optimizer.apply_gradients(gradients_and_vars_feed)\n\n# init saver\nsaver = tf.train.Saver()\n\nenv = gym.make('Acrobot-v1')\nobservations = env.reset()\n\nwith tf.Session() as sess:\n saver.restore(sess, 'models/my-acrobot')\n\n for x in range(1000):\n env.render()\n action_val, gradients_val = sess.run([action, gradients], feed_dict={X: observations.reshape(1, num_inputs)})\n observations, reward, done, info = env.step(action_val[0][0])\n","sub_path":"play-acrobot.py","file_name":"play-acrobot.py","file_ext":"py","file_size_in_byte":1849,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"236058879","text":"from src.app_pkg.routes.common import validate_helper\nfrom src.app_pkg import app, db\nfrom src.app_pkg.forms import LoginForm\nfrom flask import render_template, request, redirect, url_for, make_response\nfrom src.app_pkg.objects.user import User\n\n################################################\n# LOGIN #\n################################################\n\n@app.route(\"/login\", methods=['GET', 'POST'])\ndef login():\n user = User(request.cookies)\n form = LoginForm()\n\n if request.method == 'POST':\n result = {}\n result = db.login(request.form['username'], request.form['password'], request.remote_addr)\n if result['status'] == 'success':\n print('login success')\n res = make_response(redirect(url_for('search')))\n res.set_cookie('token', result['token'])\n return res\n else:\n print('login fail')\n res = make_response(redirect(url_for('login')))\n res.set_cookie('token', 'none')\n return res\n else:\n return render_template('login.html', form=form, user=user)","sub_path":"application/src/app_pkg/routes/login.py","file_name":"login.py","file_ext":"py","file_size_in_byte":1125,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"26624361","text":"def solve(s, d, m):\n ans = 0\n for i in range(n - m + 1):\n if sum(s[i:m+i]) == d:\n ans += 1\n return ans\n\nif __name__ == '__main__':\n n = int(input())\n s = list(map(int, input().rstrip().split()))\n dm = input().split()\n d = int(dm[0])\n m = int(dm[1])\n\n result = solve(s, d, m)\n print(result)","sub_path":"BirthdayChocolate.py","file_name":"BirthdayChocolate.py","file_ext":"py","file_size_in_byte":337,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"39213345","text":"# Accepted.\nimport collections\nimport itertools\n\nn, m = map(int, input().split())\nnodes = list(range(1, n + 1))\nedges = collections.defaultdict(lambda: False)\n\nfor _ in range(m):\n x, y = map(int, input().split())\n edges[(x, y)] = True\n edges[(y, x)] = True\n\ndef is_complete(nodes):\n if len(nodes) == 1:\n return True\n \n pairs = list(itertools.combinations(nodes, 2))\n \n for pair in pairs:\n if not edges[pair]:\n return False\n \n return True\n\nfor n_nodes in range(1, n + 1):\n nodess = list(itertools.combinations(nodes, n_nodes))\n \n for subgraph in nodess:\n if is_complete(subgraph):\n max_clique = subgraph\n\nprint(len(max_clique))\n","sub_path":"contest/atcoder2/abc002/d1.py","file_name":"d1.py","file_ext":"py","file_size_in_byte":709,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"75777315","text":"MONGO_HOST = 'localhost'\nMONGO_PORT = 27017\nMONGO_DBNAME = 'legranddebat'\nITEM_METHODS = ['GET']\nRESOURCE_METHODS = ['GET']\n\necologie = {\n 'datasource': {\n 'projection': {'responses.formattedValue':1,'responses.questionTitle':1}\n }\n}\n\nDOMAIN = {\n 'ecologie' : ecologie,\n}\n\nALLOW_UNKNOWN = True\nMONGO_QUERY_BLACKLIST = ['']\n# {\"responses.value\":{$regex : \".*macron.*\"}}, {\"responses.questionId\":0,\"responses.value\":0,responses:{$elemMatch:{value:{$regex : \".*macron.*\"}}}}\n# http://127.0.0.1:5000/ecologie?where={\"responses.value\":{$regex : \".*macron.*\"}\n# curl -i http://127.0.0.1:5000/people\n# http://127.0.0.1:5000/ecologie?where={%22_id%22:%20%225c692f7b72f3c4c1cd3f2bc0%22}\n# http://127.0.0.1:5000/ecologie?embedded={%22responses.formattedValue%22:{%22$regex%22:%22.*macron.*%22}}\n","sub_path":"api/settings.py","file_name":"settings.py","file_ext":"py","file_size_in_byte":801,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"594658910","text":"# packages\nimport torch\nimport torch.nn as nn\nfrom torchvision.transforms import transforms\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport os\nimport cv2\nimport scipy.sparse as ss\n\n# Hyper Parameters\nEpoch = 20000\nDataSize = 364\nBatchSize = 256\nGenLR = 0.00005 # Learning Rate of Generator\nDesLR = 0.00005 # Learning Rate of Descriminator\nDataSet = []\nImgSize = (1<<6,1<<6)\ndevice = 'cuda' if torch.cuda.is_available() else 'cpu'\n\n# Data Loading\nTransComp = transforms.Compose([\n transforms.ToTensor()\n ])\nroot = './images/'\nfor filename in os.listdir(root):\n img = cv2.imread(root+filename,0)\n img = cv2.resize(img,ImgSize)\n img = np.array(img) \n DataSet.append(img)\nDataSet = np.array(DataSet) \nDataSet = TransComp(DataSet).permute(1,2,0).float()\nclass Descriminator(nn.Module):\n def __init__(self):\n super(Descriminator,self).__init__()\n self.f = nn.Sequential(\n nn.Conv2d(1,8,5,1,2),\n nn.ReLU(),\n nn.MaxPool2d(4),\n nn.Conv2d(8,16,5,1,2),\n nn.ReLU(),\n nn.MaxPool2d(2),\n nn.Conv2d(16,32,5,1,2),\n nn.ReLU(),\n nn.MaxPool2d(2)\n ) \n self.out = nn.Sequential(\n nn.Linear(32*4*4,1),\n nn.Sigmoid(),\n )\n def forward(self,x):\n x = x.unsqueeze(1).float()\n x = self.f(x)\n x = x.view(-1,32*4*4)\n x = self.out(x)\n return x\n''' \n\nclass Generator(nn.Module):\n def __init__(self):\n super(Generator,self).__init__()\n self.conv1 = nn.Sequential(\n nn.Conv2d(1,8,5,1,2),\n nn.BatchNorm2d(8),\n nn.ReLU(),\n )\n self.conv2 = nn.Sequential(\n nn.Conv2d(8,16,5,1,2),\n nn.BatchNorm2d(16),\n nn.ReLU()\n )\n self.out = nn.Sequential(\n nn.Linear(16*40*40,1*40*40),\n )\n \n def forward(self,x):\n x = self.conv1(x)\n x = self.conv2(x)\n x = x.view(-1,16*40*40)\n x = self.out(x)\n x = x.view(-1,40,40)\n return x\n'''\n\n \nif __name__ == '__main__':\n \n if not os.path.exists('./panda_draw'):\n print('first try, creating a model...')\n G = nn.Sequential(\n nn.Linear(1<<6,1<<8),\n nn.ReLU(),\n nn.Linear(1<<8,1<<10),\n nn.Sigmoid(),\n nn.Linear(1<<10,1<<12),\n nn.Sigmoid(),\n )\n D = Descriminator()\n \n G_opt = torch.optim.Adam(G.parameters(),lr=GenLR)\n D_opt = torch.optim.Adam(D.parameters(),lr=DesLR)\n epoch = 0\n else:\n checkpoint = torch.load('./panda_draw')\n G = checkpoint['G']\n D = checkpoint['D']\n G_opt = checkpoint['G_opt']\n D_opt = checkpoint['D_opt']\n epoch = checkpoint['epoch']\n print('already train %s epoch..'%epoch)\n \n \n \n G = G.cuda()\n D = D.cuda()\n \n \n for step in range(epoch+1,epoch+Epoch+1):\n index = np.random.permutation(364)[:BatchSize]\n pandas = DataSet[index]\n \n idea = np.ones((BatchSize,1<<6))\n idx = np.random.permutation(1<<6)[:1<<4]\n idea[idx] = 0\n idea = torch.from_numpy(idea)\n idea = idea.float()\n \n GenPandas = G(idea.cuda()).view(-1,1<<6,1<<6).float()\n \n IsPandasR = D(pandas.cuda())\n IsPandasG = D(GenPandas)\n \n D_loss = -torch.mean(torch.log(IsPandasR) + torch.log(1.-IsPandasG))\n G_loss = torch.mean(torch.log(1.-IsPandasG))\n \n G_opt.zero_grad()\n D_opt.zero_grad()\n D_loss.backward(retain_graph = True)\n G_loss.backward()\n D_opt.step()\n G_opt.step()\n \n if step% 100 == 0:\n print('Step : %s, D_loss: %.4f, G_loss: %.4f'%(step+epoch+1,D_loss,G_loss))\n plt.imshow(GenPandas.view(-1,1<<6,1<<6)[0].cpu().data.numpy(),cmap = 'gray')\n plt.show()\n \n torch.save({\n 'G':G,\n 'D':D,\n 'G_opt':G_opt,\n 'D_opt':D_opt,\n 'epoch':step\n },'./panda_draw')\n \n","sub_path":"panda_faces/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":4377,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"600359645","text":"import json\n\nfrom array import *\na=0\nb=0\nc=list('')\nx='a'\n\nwith open('in.json','r') as q:\n a=q.read()\n data=json.loads(a)\n m=dict(data[0])\n z=m['userId']\n\n for i in range(len(data)):\n m=dict(data[i])\n if (z==m['userId']):\n if (m['completed']==1):\n a+=1\n else:\n d={'userId':z,\n 'task_completed':a\n }\n c.append(x)\n c[b]=d\n b+=1\n a=0\n z=m['userId']\n if (m['completed']==1):\n a+=1\n d={'userId':z,\n 'task_completed':a\n }\n\n c.append(x)\n c[b]=d \nprint(c)\n\nwith open ('out.json','w') as b:\n b=json.dump(c,b,notch=3)\n \n \n \n \n","sub_path":"Practice/24/24.py","file_name":"24.py","file_ext":"py","file_size_in_byte":743,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"242955512","text":"#!/usr/bin/python2.7\n# -*- coding: utf-8 -*-\n\nimport sys, re, os, codecs, copy, pdb, collections, zipfile, json\nfrom FileUtils import *\nfrom optparse import OptionParser\nfrom sclite import *\nfrom StringIO import *\n\n# bins can be changed. \"all\" bin is added later and sums over all bins, so bins\n# must cover all possible contact list sizes from 0 to infinity and cannot overlap.\nbins = [(\"0\", 0, 0), (\"1-50\", 1, 50), (\"51-100\", 51, 100), (\"101-200\", 101, 200),\n (\"201-500\", 201, 500), (\"501-1k\", 501, 1000), (\"1000+\", 1001, float('inf'))]\n\nstats_to_print = ['nCont', 'nSpkr', 'pctSpkr', 'nUtts', 'WER', 'SER', 'cWER', 'cSER', 'cWER-L', 'cWER-F', 'prc-tag', 'rec-tok', 'F1', 'pIgnore', 'pUttTag', 'pHypTag', 'pRefTag', 'nRefTok']\n\nstats_blurb = '''\\\n# nCont = number of unique contact list lines in GRXML\n# nSpkr = number of speakers\n# pctSpkr = percent of speakers with this size contact list (!= percent of utts from speakers with this size list)\n# WER = WER over all tokens\n# SER = SER over all utts\n# cWER = WER over all tokens tagged with \\contact in ref AND appearing in GRXML\n# cSER = SER over all utts containing at least 1 token tagged with \\contact in ref and for which all \\contact tokens match to GRXML\n# cWER-L = WER over LME contacts (WER over all tokens tagged with \\contact in ref and in hyp)\n# cWER-F = WER over factory contacts (WER over all tokens tagged with \\contact in ref but not in hyp)\n# prc-tag = of tokens tagged in hyp, the percent which are aligned to tokens tagged in ref\n# prc-tok = of tokens tagged in hyp, the percent which are aligned to tokens tagged in ref and correct\n# rec-tag = of contacts tagged in ref and matched to GRXML, the percent we tag as contacts\n# rec-tok = of contacts tagged in ref and matched to GRXML, the percent we tag as contacts and get correct\n# pIgnore = percentage of utts in ref ignored because at least 1 \\contact token does not match to GRXML\n# pUttTag = percentage of utts in ref with 1 or more \\contact tags, all of which are matched to GRXML\n# pHypTag = percentage of tokens in hyp with \\contact tag\n# pRefTag = percentage of tokens in ref with \\contact tag and matched to GRXML\n# nRefTok = total number of tokens in ref\n'''\n \nusage='''computeTaggedContactWER.py [options] testdir > contact.pra\n\nCalculates contact WER stats based on tags in ref and hyp, and GRXML contact lists\n\nFor eng-USA, no flags are necessary\nFor kor-KOR, use --cjk --nolattproc --preprocess_ref'''\n\nDGN_TO_TEXT_EXECUTABLE = '/lm/scratch/paulv/scripts/dgnToText.pl'\nTSV_CONTACT_FIELDS = ['fn', 'mn', 'ln', 'nn', 'fnln', 'first_name', 'middle_name', 'last_name', 'full_name', 'nick_name', 'name', 'firstname', 'middlename', 'lastname', 'fullname', 'nickname', 'firstName', 'middleName', 'lastName', 'nickName']\n\nsys.stdout = (codecs.getwriter(encoding='utf-8'))(sys.stdout)\nsys.stderr = (codecs.getwriter(encoding='utf-8'))(sys.stderr)\n\nparser = OptionParser(usage)\nparser.add_option('--cjk', action='store_true', help=\"enable special processing for CJK (Chinese Japanese Korean)\")\nparser.add_option('--out_tsv', action='store', help='write stats to this file instead of /outputlnk/contact.tsv')\nparser.add_option('--raw', action='store_true', help='print raw (pre-adj-map) ref and hyp lines in pra')\nparser.add_option('--score_dir', action='store', help='use this score dir instead of /outputlnk/recog/score')\nparser.add_option('--pra', action='store', help='use this pra instead of /outputlnk/recog/score/all.txt-rescored.pra')\nparser.add_option('--ref', action='store', help='use this ref file instead of /outputlnk/recog/score/all.unmap.ref')\nparser.add_option('--hyp', action='store', help='use this hyp file instead of /outputlnk/recog/score/all.unmap.hyp')\nparser.add_option('--nolattproc', action='store_true', help='use pre-lattproc hyps in outputlnk/recog/txt (no RNE, etc)')\nparser.add_option('--userdata', action='store', help='use this userdata (/path/to/grxml or @contacts@/path/to.tsv) instead of looking at job.def')\nparser.add_option('--alt_ref', help=\"also print ref line from specified all.unmap.ref file in output with contact words\")\nparser.add_option('--alt_hyp', help=\"also print hyp line from specified all.unmap.hyp file in output with contact words\")\nparser.add_option('--match', action='store_true', help=\"also print matched ref names as they appear in GRXML\")\nparser.add_option('--match_report', action='store_true', help=\"instead of normal calculations, print GRXML match report\")\nparser.add_option('--preprocess_ref',action='store_true', help=\"run contact pre-processing on ref first - Korean only!\")\n\n(options, args) = parser.parse_args()\nif len(args) == 0: parser.print_help(); sys.exit(1)\n\ntest_dir = args[0]\ntsv_fn = options.out_tsv if options.out_tsv else os.path.join(test_dir, 'outputlnk/contact.tsv')\nscore_dir = options.score_dir if options.score_dir else os.path.join(test_dir, 'outputlnk/recog/score')\npra_fn = options.pra if options.pra else os.path.join(score_dir, 'all.txt-rescored.pra')\nunmap_ref_fn = options.ref if options.ref else os.path.join(score_dir, 'all.unmap.ref')\nunmap_hyp_fn = options.hyp if options.hyp else os.path.join(score_dir, 'all.unmap.hyp')\n\nif options.cjk: sys.stderr.write(\"CJK mode enabled\\n\")\nif options.match_report: sys.stderr.write(\"generating match report, use -r if viewing output with less\\n\")\n\n# figure out where we are getting contact lists from\nuserdata_string = None\nif options.userdata: userdata_string = options.userdata\nelse:\n jobdef_configdata_RE = re.compile(r'''^.*-QLMECONFIGDATA=\"'(\\S+) .*'\"$''')\n jobdef_configfile_RE = re.compile(r'''^.*-QLMECONFIGFILE=(\\S+)$''')\n f = open(os.path.join(test_dir, 'job.def'))\n for line in f:\n m = jobdef_configdata_RE.search(line)\n if m: userdata_string = m.group(1); break\n m = jobdef_configfile_RE.search(line)\n if m: userdata_string = [l for l in open(m.group(1)) if l.strip()[0] != '#'][0].split()[0]; break\n f.close()\nif not userdata_string:\n sys.stderr.write(\"Could not determine location of user data (GRXML dir or TSV file), exiting\\n\")\n sys.exit(1)\n\nsys.stderr.write(\"reading user data from %s\\n\" % userdata_string)\nif os.path.isdir(userdata_string): # grxml dir\n userdata = (None, userdata_string)\nelif re.match(r'^@(\\S+)@(/\\S+)$', userdata_string): # tsv file\n (content_type, fn) = re.findall(r'^@(\\S+)@(/\\S+)$', userdata_string)[0]\n sys.stderr.write(\"reading speaker offsets from user data TSV...\\n\")\n f = open(fn)\n header_tokens = f.readline().strip().split('\\t')\n col_dict = dict([(header_tokens[i], i) for i in range(len(header_tokens))])\n user_col = col_dict['user']\n tsv_spkr_offsets = {}\n last_spkr = None\n while True:\n offset = f.tell()\n line = f.readline()\n if not line: break\n spkr = line.split('\\t')[user_col]\n if spkr != last_spkr: tsv_spkr_offsets[spkr] = offset; last_spkr = spkr\n userdata = (content_type, f, tsv_spkr_offsets, col_dict)\nelse:\n sys.stderr.write(\"Invalid user data specification: %s\\n\" % userdata_string)\n sys.exit(1)\n \ngrxml_contactRE = re.compile(r'\\s*(?:- )?
CONTACT_NAME=\"(.*)\"', re.IGNORECASE)\nref_contactRE = re.compile(r'(\\S+)\\\\contact[^\\\\]*\\\\?(\\S+)?')\nhyp_contactRE = re.compile(r'(\\S+)\\\\contact')\ninfoRE = re.compile(' user:(\\S+) file:(\\S+)')\ndatafileRE = re.compile('datafile: (\\S+)')\n\n# Check whether name can be created by concatenating one or more tokens from trie\ndef in_trie(orig_trie, trie, string):\n if len(trie) == 0: return False\n if len(string) == 0: return '_end_' in trie\n if string[0] in trie: return in_trie(orig_trie, trie[string[0]], string[1:])\n if string[0] in orig_trie: return in_trie(orig_trie, orig_trie, string)\n return False\n \n# map from size of contact list to bin\ndef get_bin_index(num_entries):\n for i in range(len(bins)):\n if num_entries >= bins[i][1] and num_entries <= bins[i][2]: return i\n \n# read user data GRXML/TSV and store set of contact tokens for each speaker\ndef get_user_data(spkr, userdata):\n if userdata[0]: return readTSV(spkr, userdata)\n else: return readGrxml(spkr, userdata)\n \n# get user data from cached info\ndef readTSV(spkr, ud):\n (content_type, fptr, offsets, cols) = ud\n if spkr not in offsets: return ([], 0)\n f.seek(offsets[spkr])\n unique_contacts = set()\n contacts = []\n while True:\n line = f.readline().decode('utf-8')\n if not line or line == None: break\n fields = line.strip().split('\\t')\n if any([x > len(fields)-1 for x in cols.values()]): continue\n if fields[cols['user']] != spkr: break\n if fields[cols['content_type']] == content_type:\n full_dict = json.loads(fields[cols['content']])\n name_dict = dict([i for i in full_dict.items() if i[0] in TSV_CONTACT_FIELDS])\n name_str = ' '.join(['%s \"%s\"' % x for x in name_dict.items()])\n unique_contacts.add(name_str)\n if not options.cjk:\n bag_of_names = set()\n for str in name_dict.values():\n bag_of_names.update([n.lower() for n in str.split()])\n contacts.append((bag_of_names, name_str))\n else:\n contact_trie = {}\n for str in name_dict.values():\n for tok in str.split():\n curTrie = contact_trie\n for idx in range(len(tok)):\n if not tok[idx] in curTrie: curTrie[tok[idx]] = {}\n curTrie = curTrie[tok[idx]]\n if idx == len(tok) - 1: curTrie['_end_'] = None\n contacts.append((contact_trie, name_str))\n \n return (contacts, get_bin_index(len(unique_contacts)))\n \n# get user data from GRXML file\ndef readGrxml(spkr, ud):\n grxml_dir = ud[1]\n try: f = OpenFile(os.path.join(grxml_dir, \"%s.grxml\"%(spkr)), encoding='utf-8')\n except: return (None, 0)\n\n contacts = []\n unique_contacts = set()\n for line in f.readlines():\n m = grxml_contactRE.match(line)\n if not m: continue\n name = m.group(1)\n if name in unique_contacts: continue\n else: unique_contacts.add(name)\n if not options.cjk: # for non-CJK, just one bag of words for each entry\n contacts.append((set(name.lower().split()), name))\n else: # for CJK, build a trie for each entry\n contact_trie = {}\n for tok in name.lower().split():\n curTrie = contact_trie \n for idx in range(len(tok)):\n if not tok[idx] in curTrie: curTrie[tok[idx]] = {}\n curTrie = curTrie[tok[idx]]\n if idx == len(tok) - 1: curTrie['_end_'] = None\n contacts.append((contact_trie, name))\n f.close()\n return (contacts, get_bin_index(len(unique_contacts)))\n \ndef highlight(str, chars):\n out_str = u''\n for s in str:\n if s in chars: out_str += u'\\033[32m' + s + u'\\033[0m'\n else: out_str += s\n return out_str\n \n# return true if ALL contacts in ref match to a single contact list entry\ndef match_to_contact_list(ref_sent, spkr_data):\n spkr_contacts = [] if spkr_data == None else spkr_data\n matches = []\n \n if not options.cjk:\n ref_names = [r[2] for r in ref_sent if r[1]]\n for c in spkr_contacts:\n if all([name.lower() in c[0] for name in ref_names]):\n matches.append(c[1])\n \n if options.cjk:\n tmp_ref_sent = [r for r in ref_sent if r[0] != '*']\n ref_names = []\n string = u''\n for idx in range(len(tmp_ref_sent)):\n if tmp_ref_sent[idx][1]: string += tmp_ref_sent[idx][0]\n if len(string) > 0:\n # when we find the end of a contact name string, add it to list\n if not tmp_ref_sent[idx][1]:\n ref_names.append(string)\n string = ''\n elif idx == len(tmp_ref_sent)-1:\n ref_names.append(string)\n for c in spkr_contacts: # for each contact list entry\n if all([in_trie(c[0], c[0], name) for name in ref_names]): # if all names match to trie\n matches.append(c[1])\n\n if matches == []: matches = None\n \n if options.match_report:\n sys.stdout.write(\"-----------------------------------------------------------------------------------------\\n\")\n sys.stdout.write(\"USER: %s, contact list has %d entries\\n\" % (spkr.id, len(spkr_contacts)))\n sys.stdout.write(\"RAW REF: %s\\n\" % raw_ref_dict[datafile])\n if options.preprocess_ref: sys.stdout.write(\"PREPROCESSED REF: %s\\n\" % pp_ref_dict[datafile])\n sys.stdout.write(\"MAPPED REF: %s\\n\" % ' '.join(snt.ref).decode('utf-8'))\n sys.stdout.write(\"NAMES IN REF: %s\\n\" % ' '.join(ref_names))\n if matches:\n sys.stdout.write(\"GRXML MATCHES:\\n\")\n for m in matches:\n sys.stdout.write(\" %s\\n\" % m)\n elif len(spkr_contacts) == 0:\n sys.stdout.write(\"No match found, empty contact list\")\n else:\n if options.cjk:\n name_chars = list(''.join(ref_names))\n potential_matches = sorted([c[1] for c in spkr_contacts if all([x in c[1] for x in name_chars])])\n if len(potential_matches) > 0:\n sys.stdout.write(\"No match found. Potential matches (GRXML entries containing all chars in all names in ref):\\n\")\n sys.stdout.write('\\n'.join([highlight(p, name_chars) for p in potential_matches]))\n # potential_matches = sorted([c[1] for c in spkr_contacts if any([x in c[1] for x in name_chars])])\n # if len(potential_matches) > 0:\n # sys.stdout.write(\"No match found. Potential matches (GRXML entries containing any char in any name in ref):\\n\")\n # sys.stdout.write('\\n'.join([highlight(p, name_chars) for p in potential_matches]))\n else:\n sys.stdout.write(\"No match and no potential matches found. Contact list for user (%d entries):\\n\" % len(spkr_contacts))\n sys.stdout.write('\\n'.join(sorted([highlight(c[1], name_chars) for c in spkr_contacts])))\n else:\n sys.stdout.write(\"No match found\")\n sys.stdout.write('\\n')\n return False\n\n else: return matches\n \nif options.alt_ref:\n alt_ref = OpenFile(options.alt_ref, encoding='utf-8')\n alt_ref_dict = dict()\n while True:\n info = alt_ref.readline()\n if info == '\\n': continue\n if not info: break\n alt_ref_dict[infoRE.search(info).group(2)] = alt_ref.readline().strip()\n alt_ref.close()\n\nif options.alt_hyp:\n alt_hyp = OpenFile(options.alt_hyp, encoding='utf-8')\n alt_hyp_dict = dict()\n while True:\n info = alt_hyp.readline()\n if info == '\\n': continue\n if not info: break\n alt_hyp_dict[infoRE.search(info).group(2)] = alt_hyp.readline().strip()\n alt_hyp.close()\n \ndef preprocess(line):\n # for kor-KOR only!\n # copied from /lm/scratch/erik_larsson/hg/lm_tools_scripts/prefilter_ref.py\n line = re.sub(r'\\s+\\\\contact', r'\\\\contact', line) #X \\contact -> X\\contact\n line = re.sub(r'\\\\contact([^-])', r'\\\\contact \\1', line) # contactX -> contact X\n line = re.sub(u'([\\uAC00-\\uD7AF])(에게)(\\\\\\\\contact)','\\\\1\\\\3 \\\\2', line) # remove case markers from contact names\n line = re.sub(u'([\\uAC00-\\uD7AF])(한테)(\\\\\\\\contact)','\\\\1\\\\3 \\\\2', line) # remove case markers from contact names\n # XXXXX\\contact X\\contact X\\contact -> XXXX X\\contact X\\contact X\\contact\n line = re.sub(u'([\\uAC00-\\uD7AF])([\\uAC00-\\uD7AF]\\\\\\\\contact [\\uAC00-\\uD7AF]\\\\\\\\contact [\\uAC00-\\uD7AF]\\\\\\\\contact)','\\\\1 \\\\2',line)\n if line.count('contact') >= 2: line = re.sub(u'([\\uAC00-\\uD7AF]{3,})([\\uAC00-\\uD7AF]\\\\\\\\contact)','\\\\1 \\\\2',line)\n elif line.count('contact') == 1: line = re.sub(u'([\\uAC00-\\uD7AF]{4,})([\\uAC00-\\uD7AF]\\\\\\\\contact)','\\\\1 \\\\2',line)\n\n tokens = line.split()\n idx = 0\n curr_contact = \"\"\n while (idx < len(tokens)):\n t = tokens[idx]\n mth = re.search(r\"([^\\\\]+)\\\\contact(\\-\\S+){0,1}\", t)\n if (mth is not None):\n contact_name = mth.group(1)\n curr_contact += contact_name\n del tokens[idx]\n continue\n else: # not contact\n if (curr_contact != \"\"):\n tokens.insert(idx, curr_contact + \"\\\\contact\")\n curr_contact = \"\"\n idx += 1\n if (curr_contact != \"\"): tokens.insert(idx, curr_contact + \"\\\\contact\")\n \n return ' '.join(tokens)\n \n# read all.unmap.ref and store dict of ref tokens tagged as contacts ('\\contact') mapping to canonical\n# names, if present, for each sentence\nif options.preprocess_ref: print >>sys.stderr, \"preprocessing refs - for use with kor-KOR only!\"\nprint >> sys.stderr, \"reading refs...\"\nunmap_ref = OpenFile(unmap_ref_fn, encoding='utf-8') \ncanonical_ref_contacts = collections.defaultdict(dict)\ninfo = ref = None\nraw_ref_dict, pp_ref_dict = dict(), dict()\nwhile True:\n info = unmap_ref.readline()\n if info == '\\n': continue\n if not info: break\n ref = unmap_ref.readline()\n (user, file) = infoRE.findall(info)[0]\n raw_ref_dict[file] = ref.strip()\n if options.preprocess_ref: ref = preprocess(ref)\n pp_ref_dict[file] = ref.strip()\n contacts = {}\n for t in ref.split():\n m = ref_contactRE.match(t)\n if m == None: continue\n if m.group(2): contacts[m.group(1).lower()] = m.group(2).lower()\n else: contacts[m.group(1).lower()] = m.group(1).lower()\n canonical_ref_contacts[file] = contacts\nunmap_ref.close()\n\n# read hyps and store set of hyp tokens tagged with \\contact, per sentence\nraw_hyp_dict = dict()\ntagged_contacts_in_hyp = collections.defaultdict(set)\nif not options.nolattproc:\n sys.stderr.write(\"reading hyps from all.unmap.hyp...\\n\")\n unmap_hyp = OpenFile(unmap_hyp_fn, encoding='utf-8')\n info = hyp = None\n while True:\n info = unmap_hyp.readline() \n if info == '\\n': continue\n if not info: break\n hyp = unmap_hyp.readline()\n (user, file) = infoRE.findall(info)[0]\n raw_hyp_dict[file] = hyp.strip()\n contacts = [hyp_contactRE.search(t).group(1).lower() for t in hyp.split() if hyp_contactRE.search(t)]\n tagged_contacts_in_hyp[file] = set(contacts) # store bag-of-contacts per utt\n unmap_hyp.close()\nelse: \n sys.stderr.write(\"reading hyps from outputlnk/recog/txt...\\n\")\n txtdir = os.path.join(test_dir, 'outputlnk/recog/txt')\n txt_fn_RE = re.compile(r'^(?P[0-9a-f\\-]+)/(?P\\S+)\\.txt$')\n ids = []\n dgn = ''\n for zip_fn in [fn for fn in os.listdir(txtdir) if fn.endswith('.zip')]:\n zfile = zipfile.ZipFile(os.path.join(txtdir, zip_fn))\n for (user, txtid) in [m.groups() for m in [txt_fn_RE.match(fn) for fn in zfile.namelist()] if m]:\n ids.append(txtid)\n dgn += zfile.read(os.path.join(user, txtid+'.txt'))\n zfile.close()\n p = subprocess.Popen([DGN_TO_TEXT_EXECUTABLE, '-', '-'], stdin=subprocess.PIPE, stdout=subprocess.PIPE)\n utf = p.communicate(dgn)[0].decode('utf-8')\n for (id, hyp) in zip(ids, utf.splitlines()):\n raw_hyp_dict[id] = hyp.strip()\n contacts = [hyp_contactRE.search(t).group(1).lower() for t in hyp.split() if hyp_contactRE.search(t)]\n tagged_contacts_in_hyp[id] = set(contacts)\n \ndef map_contacts_cjk(contacts, ref_sent):\n '''\n Given a set of contact names and a list of [word1, word2, ... ]\n modify the Boolean values according to whether that word is in the set of \n contact names or not\n '''\n result_sent = copy.deepcopy(ref_sent)\n\n # BY THIS HACK FOR CJK WE PREVENT LATIN LETTER WORDS FROM CAUSING ALIGNMENT PROBLEMS\n ref_str = ''.join([x[0][0] for x in ref_sent])\n\n if (len(ref_str) != len(result_sent)):\n print >> sys.stderr, \"Could not align: \", ref_str\n return False\n\n # temporarily remove * to enable contact name matching for CER tests\n starIndices = []\n if '*' in ref_str:\n ref_str = ref_str.replace('*','')\n for x in range(len(result_sent)-1,-1,-1):\n if result_sent[x][0] =='*':\n result_sent.pop(x)\n starIndices.append(x)\n\n for cname in contacts:\n start_idx = 0\n idx = ref_str.find(cname, start_idx)\n while (idx >= 0):\n for i in xrange(idx, idx + len(cname)):\n result_sent[i] = (result_sent[i][0], True)\n start_idx = idx + len(cname)\n idx = ref_str.find(cname, start_idx)\n\n # restore * if we removed it above\n for x in sorted(starIndices): result_sent.insert(x, ('*', False))\n\n return result_sent\n\ncounts = collections.defaultdict(lambda: [0 for b in bins])\n\n# read through pra and compare aligned tokens, count, etc\nnum_contact_chars_skipped = 0\nprint >> sys.stderr, \"loading pra...\"\npra = praFile(pra_fn)\nout_str = \"\"\nprint >> sys.stderr, \"reading pra and user data...\"\nfor spkr in pra.speaker:\n temp_str = StringIO()\n spkr.write(temp_str)\n speaker_info = [l for l in temp_str.getvalue().split('\\n') if l != '']\n (spkr_contacts, spkr_bin) = get_user_data(spkr.id, userdata)\n if spkr_contacts == None: sys.stderr.write(\"Unable to read user data (GRXML/TSV) for speaker %s\\n\" % spkr.id)\n counts['spkrs'][spkr_bin] += 1\n out_str += speaker_info[0] + '\\n'\n for snt in spkr.sentence: # for each utterance:\n counts['tokens'][spkr_bin] += snt.wrdCount # count total/wrong ref/hyp tokens to calc WER\n counts['wrong_tokens'][spkr_bin] += snt.wrdErrCount\n if snt.wrdErrCount > 0: counts['wrong_sents'][spkr_bin] += 1\n \n counts['ref_tokens'][spkr_bin] += len([r for r in snt.ref if r != '*'])\n counts['hyp_tokens'][spkr_bin] += len([h for h in snt.hyp if h != '*'])\n counts['sents'][spkr_bin] += 1\n \n temp_str = StringIO()\n snt.write(temp_str)\n m = datafileRE.search(temp_str.getvalue())\n datafile = m.group(1)\n \n if (not options.cjk):\n # store canonical version of name (if annotated) for match to grxml. Not implemented for CJK\n ref_sent = []\n for x in snt.ref:\n t = x.decode('utf8').lower()\n if t in canonical_ref_contacts[datafile]: ref_sent.append((t, True, canonical_ref_contacts[datafile][t]))\n else: ref_sent.append((t, False))\n hyp_sent = [(t, True) if t in tagged_contacts_in_hyp[datafile] else (t, False) for t in [x.lower().decode('utf8') for x in snt.hyp]]\n else: # CJK\n ref_sent = map_contacts_cjk(canonical_ref_contacts[datafile], [(t, False) for t in [x.lower().decode('utf8') for x in snt.ref]])\n hyp_sent = map_contacts_cjk(tagged_contacts_in_hyp[datafile], [(t, False) for t in [x.lower().decode('utf8') for x in snt.hyp]])\n\n if ref_sent == False or hyp_sent == False or len(ref_sent) != len(hyp_sent):\n sys.stderr.write(\"Length mismatch between or other problem aligning ref and hyp, datafile %s\\n\" % datafile)\n if len(canonical_ref_names[datafile]) > 0:\n for x in canonical_ref_names[datafile]: num_contact_chars_skipped += len(x)\n continue\n\n sent_has_ref_contact = any([r[1] for r in ref_sent])\n sent_has_hyp_contact = any([h[1] for h in hyp_sent])\n\n if sent_has_ref_contact: counts['sents_with_contact'][spkr_bin] += 1\n counts['tagged_ref_tokens'][spkr_bin] += [r[1] for r in ref_sent].count(True)\n counts['tagged_hyp_tokens'][spkr_bin] += [h[1] for h in hyp_sent].count(True)\n counts['tagged_in_ref_and_hyp'][spkr_bin] += [r[1] and h[1] for (r, h) in zip(ref_sent, hyp_sent)].count(True)\n \n contact_list_matches = match_to_contact_list(ref_sent, spkr_contacts)\n \n # insert additional lines into PRA if requested\n sentence_info = [l for l in temp_str.getvalue().split('\\n') if l != '']\n additional_info = []\n if options.match and sent_has_ref_contact:\n if contact_list_matches:\n additional_info.append('CONTACT LIST ENTRY MATCHES:')\n for m in contact_list_matches: additional_info.append(' %s' % m.encode('utf8'))\n else: additional_info.append('CONTACT LIST ENTRY MATCHES: none')\n if options.alt_ref: additional_info.append('ALTREF: ' + alt_ref_dict[datafile].encode('utf8'))\n if options.alt_hyp: additional_info.append('ALTHYP: ' + alt_hyp_dict[datafile].encode('utf8'))\n if options.raw:\n additional_info.append('RAWREF: ' + raw_ref_dict[datafile].encode('utf8'))\n additional_info.append('RAWHYP: ' + raw_hyp_dict[datafile].encode('utf8'))\n sentence_info[4:4] = additional_info\n out_str += '\\n'.join(sentence_info) + '\\n'\n\n # bail out if no contacts in ref\n if not sent_has_ref_contact: out_str += '\\n'; continue\n \n # bail out here if ANY ref contacts were NOT matched to contact list (GRXML or TSV)\n if not contact_list_matches: out_str += '\\n'; continue\n\n counts['sents_with_match'][spkr_bin] += 1\n if snt.wrdErrCount > 0: counts['wrong_sents_with_match'][spkr_bin] += 1\n counts['matched_ref_contacts'][spkr_bin] += [r[1] for r in ref_sent].count(True)\n\n contact_eval = []\n for i in range(len(ref_sent)): # for every token in aligned hyp/ref\n if not ref_sent[i][1]: continue # if not tagged as a contact in ref, move on to next token\n\n # check whether hyp is correct, and whether recognized as a contact, and count\n if ref_sent[i][0] == hyp_sent[i][0]:\n eval_str = hyp_sent[i][0] + '\\\\CORRECT'\n if hyp_sent[i][1]: counts['lme_correct'][spkr_bin] += 1\n else: counts['factory_correct'][spkr_bin] += 1\n else:\n eval_str = hyp_sent[i][0] + '\\\\MISS(%s)'%ref_sent[i][0]\n if hyp_sent[i][1]: counts['lme_wrong'][spkr_bin] += 1\n else: counts['factory_wrong'][spkr_bin] += 1\n \n if hyp_sent[i][1]: eval_str += '-LME'\n else: eval_str += '-FACTORY'\n contact_eval.append(eval_str)\n \n if len(contact_eval) > 0: out_str += 'ContactEval: %s\\n' % ' '.join(contact_eval).encode('utf8')\n out_str += '\\n'\n\nif userdata[0]: userdata[1].close()\nif options.match_report: sys.exit()\n \n# sum over bins and create \"all\" bin\nbins.append((\"all\", None, None))\nfor s in counts: counts[s].append(sum(counts[s]))\nindices = range(len(bins))\n\ndef pct(n, d): return 100.0*n/d if d != 0 else 0.0\n\nstats = collections.defaultdict(lambda: [0 for b in bins])\nstats['nCont'] = [b[0] for b in bins]\nstats['nSpkr'] = counts['spkrs']\nstats['pctSpkr'] = [pct(stats['nSpkr'][i], stats['nSpkr'][-1]) for i in indices]\nstats['nUtts'] = counts['sents']\nstats['WER'] = [pct(counts['wrong_tokens'][i], counts['tokens'][i]) for i in indices]\nstats['SER'] = [pct(counts['wrong_sents'][i], counts['sents'][i]) for i in indices]\nstats['total_lme'] = [counts['lme_wrong'][i] + counts['lme_correct'][i] for i in indices]\nstats['total_factory'] = [counts['factory_wrong'][i] + counts['factory_correct'][i] for i in indices]\nstats['total_wrong'] = [counts['lme_wrong'][i] + counts['factory_wrong'][i] for i in indices]\nstats['cWER'] = [pct(stats['total_wrong'][i], counts['matched_ref_contacts'][i]) for i in indices]\nstats['cSER'] = [pct(counts['wrong_sents_with_match'][i], counts['sents_with_match'][i]) for i in indices]\nstats['cWER-L'] = [pct(counts['lme_wrong'][i], stats['total_lme'][i]) for i in indices]\nstats['cWER-F'] = [pct(counts['factory_wrong'][i], stats['total_factory'][i]) for i in indices]\nstats['prc-tag'] = [pct(counts['tagged_in_ref_and_hyp'][i], counts['tagged_hyp_tokens'][i]) for i in indices]\nstats['prc-tok'] = [pct(counts['lme_correct'][i], counts['tagged_hyp_tokens'][i]) for i in indices]\nstats['rec-tag'] = [pct(counts['tagged_in_ref_and_hyp'][i], counts['matched_ref_contacts'][i]) for i in indices]\nstats['rec-tok'] = [pct(counts['lme_correct'][i], counts['matched_ref_contacts'][i]) for i in indices]\nstats['F1'] = [pct(2*stats['prc-tag'][i]*stats['rec-tok'][i], stats['prc-tag'][i]+stats['rec-tok'][i])/100.0 for i in indices]\nstats['F1-tag'] = [pct(2*stats['prc-tag'][i]*stats['rec-tag'][i], stats['prc-tag'][i]+stats['rec-tag'][i])/100.0 for i in indices]\nstats['F1-tok'] = [pct(2*stats['prc-tok'][i]*stats['rec-tok'][i], stats['prc-tok'][i]+stats['rec-tok'][i])/100.0 for i in indices]\nstats['pGrxml'] = [pct(counts['matched_ref_contacts'][i], counts['tagged_ref_tokens'][i]) for i in indices]\nstats['pIgnore'] = [pct(counts['sents_with_contact'][i]-counts['sents_with_match'][i], counts['sents_with_contact'][i]) for i in indices]\nstats['pUttTag'] = [pct(counts['sents_with_match'][i], counts['sents'][i]) for i in indices]\nstats['pHypTag'] = [pct(counts['tagged_hyp_tokens'][i], counts['hyp_tokens'][i]) for i in indices]\nstats['pRefTag'] = [pct(counts['matched_ref_contacts'][i], counts['ref_tokens'][i]) for i in indices]\nstats['nRefTok'] = counts['ref_tokens']\n\nstr_stats, str_counts = {}, {}\nfor k in stats.keys():\n str_stats[k] = ['%.2f'%s for s in stats[k]] if type(stats[k][0]) == float else [str(s) for s in stats[k]]\nfor k in counts.keys():\n str_counts[k] = [str(s) for s in counts[k]]\n \ntsv = open(tsv_fn, 'w')\ntsv.write(stats_blurb)\ntsv.write('\\t'.join(stats_to_print) + '\\n')\nfor i in indices: tsv.write('\\t'.join([str_stats[s][i] for s in stats_to_print]) + '\\n')\ntsv.close()\n\nsys.stdout.write('***** WER over contacts tagged in ref and appearing in contact lists: %s (%s/%s)\\n'\n % (str_stats['cWER'][-1], str_stats['total_wrong'][-1], str_counts['matched_ref_contacts'][-1]))\nsys.stdout.write(' WER over tagged contacts recognized as \\\\contact-(first|middle|last): %s (%s/%s)\\n'\n % (str_stats['cWER-L'][-1], str_counts['lme_wrong'][-1], str_stats['total_lme'][-1]))\nsys.stdout.write(' WER over tagged contacts recognized as factory words: %s (%s/%s)\\n'\n % (str_stats['cWER-F'][-1], str_counts['factory_wrong'][-1], str_stats['total_factory'][-1]))\nsys.stdout.write(' %s%% (%s/%s) of contacts tagged in ref appear in contact lists\\n'\n % (str_stats['pGrxml'][-1], str_counts['matched_ref_contacts'][-1], str_counts['tagged_ref_tokens'][-1]))\nsys.stdout.write(' %.2f%% (%d/%d) of utterances include \\\\contact in ref\\n'\n % (pct(counts['sents_with_contact'][-1], counts['sents'][-1]), counts['sents_with_contact'][-1], counts['sents'][-1]))\nif options.cjk:\n sys.stdout.write(' Num contact chars skipped due to bad alignment: %d\\n' % (num_contact_chars_skipped))\nsys.stdout.write('\\n')\n\nsys.stdout.write(out_str.decode('utf8'))\n","sub_path":"tools/scripts/computeTaggedContactWER.py","file_name":"computeTaggedContactWER.py","file_ext":"py","file_size_in_byte":31214,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"638839249","text":"import uuid\n\nfrom dataclasses import dataclass\nfrom dataclasses import field\n\nfrom typing import List\n\nfrom core.entities import BaseEntity\n\n\n@dataclass\nclass Choice(BaseEntity):\n name: str\n text: str\n id: uuid.UUID = field(default_factory=uuid.uuid4)\n votes: int = 0\n\n @classmethod\n def from_dict(cls, other: dict):\n return cls(\n id=other.get('id'),\n name=other.get('name'),\n text=other.get('text'),\n votes=other.get('votes', 0)\n )\n\n def dict(self) -> dict:\n return {\n 'id': self.id,\n 'name': self.name,\n 'text': self.text,\n 'votes': self.votes,\n }\n\n def vote(self):\n self.votes += 1\n\n\n@dataclass\nclass Question(BaseEntity):\n name: str\n text: str\n choices: List[Choice] = field(default_factory=list)\n id: uuid.UUID = field(default_factory=uuid.uuid4)\n\n @classmethod\n def from_dict(cls, other: dict):\n return cls(\n id=other.get('id'),\n name=other.get('name'),\n text=other.get('text'),\n choices=[\n Choice.from_dict(ch)\n for ch in other.get('choices', ())\n if ch\n ]\n )\n\n def get_choice_by_id(self, uid: uuid.UUID):\n choices = tuple(filter(lambda x: str(x.id) == str(uid), self.choices))\n return choices[0] if choices else None\n\n def dict(self) -> dict:\n return {\n 'id': self.id,\n 'name': self.name,\n 'text': self.text,\n 'choices': [ch.dict() for ch in self.choices],\n }\n","sub_path":"src/core/entities/poll.py","file_name":"poll.py","file_ext":"py","file_size_in_byte":1625,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"640666241","text":"import viz\nimport random\n\nviz.go()\n\n\nbody = viz.addAvatar('leland_body.cfg')\nbody.setScale(.012, .012,.012)\nhead = viz.addFace( 'leland_head2.vzf' ) \nbody.setFace( head, 'Bip01 Head', 'Bip01 Neck' )\nbody.setEuler(180, 0, 0)\nviz.clearcolor(1,1,1)\nbody.state(1)\n\n\nvizact.onupdate(viz.PRIORITY_LINKS+1,head.setPosition,0,0.02,0.02,viz.REL_LOCAL)\nbody.setPosition(0, 0, 2)\n\ndef blink (key):\n\topen = vizact.morphTo(0,0.75,time= random.randint(0, 3)*.1)\n\tclose = vizact.morphTo(0, 0, time = random.randint(0, 3)*.1)\n\tif key == 's':\n\t\t#Animate morph target 0 to .5 in some random int from 0 to 0.3\n\t\tblink_open = head.addAction(open)\n\t\t#Animate morph target 0 to 0 in some random int from 0 to 0.3\n\t\tblink_close = head.addAction(close)\n\t\tvizact.sequence([blink_open, blink_close], viz.FOREVER)\n\n\nviz.callback(viz.KEYBOARD_EVENT, blink)","sub_path":"assets/avatars/Old Leland/morphTest.py","file_name":"morphTest.py","file_ext":"py","file_size_in_byte":829,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"381425490","text":"from behave import step\n\nfrom time import time\n\nfrom .utils import safe_get_element_text, get_page_element\nfrom .utils import expand_shadow_root, get_grid_items\n\n\ndef find_image(image, images_list):\n for check_image in images_list:\n if image in safe_get_element_text(check_image):\n return check_image.find_element_by_css_selector('strong.name')\n\n\n@step('the \"{image}\" image should be \"{state}\" within {seconds} seconds')\ndef assert_starred_unstarred_image(context, image, state, seconds):\n state = state.lower()\n if state not in ['starred', 'unstarred']:\n raise Exception('Unknown type of state')\n images_page = get_page_element(context, 'images')\n images_page_shadow = expand_shadow_root(context, images_page)\n mist_list = images_page_shadow.find_element_by_css_selector('mist-list')\n list_shadow = expand_shadow_root(context, mist_list)\n grid = list_shadow.find_element_by_css_selector('vaadin-grid')\n end_time = time() + int(seconds)\n while time() < end_time:\n starred = get_grid_items(context, grid)[0]['starred']\n if state == 'starred':\n assert starred, \"Image is not starred\"\n else:\n assert not starred, \"Image is starred\"\n return\n assert False, 'Image %s is not %s in the list after %s seconds' \\\n % (image, state, seconds)\n","sub_path":"misttests/integration/gui/steps/images.py","file_name":"images.py","file_ext":"py","file_size_in_byte":1356,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"415991277","text":"#!/usr/bin/env python\n# coding: utf-8\n\n# # Profitable App Profiles for the App Store and Google Play Markets\n# \n# Our aim in this project is to find mobile app profiles that are profitable for the App Store and Google Play markets. We're working for a company that builds Android and iOS mobile apps, and our job is to enable our team of developers to make data-driven decisions with respect to the kind of apps they build.\n# \n# At our company, We only build apps that are free to download and install, and our main source of revenue consists of in-app ads. This means our revenue for any given app is mostly influenced by the number of users who use our app — the more users that see and engage with the ads, the better.\n# \n# \n# # Opening and Exploring Data\n# \n# As of September 2018, there were approximately 2 million iOS apps available on the App Store, and 2.1 million Android apps on Google Play.\n# \n# Collecting data for over four million apps requires a significant amount of time and money, so we'll try to analyze a sample of data instead. To avoid spending resources with collecting new data ourselves, we should first try to see whether we can find any relevant existing data at no cost. Luckily, these are two data sets that seem suitable for our purpose:\n# \n# * A data set containing data about approximately 10,000 Android apps from Google Play; the data was collected in August 2018. You can download the data set directly from this [Link](https://www.kaggle.com/lava18/google-play-store-apps)\n# * A data set containing data about approximately 7,000 iOS apps from the App Store; the data was collected in July 2017. You can download the data set directly from this [Link](https://www.kaggle.com/ramamet4/app-store-apple-data-set-10k-apps)\n# \n# Lets start by opening two data sets and then continue with exploring data:\n\n# In[2]:\n\n\nfrom csv import reader\n\n### The Google Play data set ###\nopened_file = open(\"googleplaystore.csv\", encoding='utf8')\nread_file = reader(opened_file)\ngoogle = list(read_file)\ngoogle_play_store_header = google[0]\ngoogle_play_store = google[1:]\n\n### The App Store data set ###\nopened_file = open(\"AppleStore.csv\", encoding='utf8')\nfrom csv import reader\nread_file = reader(opened_file)\napple = list(read_file)\napple_store_header = apple[0]\napple_store = apple[1:]\n\n\n# To make it easier to explore the two data sets, we'll first write a function named explore_data() that we can use repeatedly to explore rows in a more readable way. We'll also add an option for our function to show the number of rows and columns for any data set.\n\n# In[3]:\n\n\ndef explore_data(dataset, start, end, rows_and_columns= False):\n dataset_slice = dataset[start:end] \n for row in dataset_slice:\n print(row)\n print('\\n') # adds a new (empty) line after each row\n\n if rows_and_columns:\n print('Number of rows:', len(dataset))\n print('Number of columns:', len(dataset[0]))\nprint(google_play_store_header)\nprint('\\n')\nexplore_data(google_play_store, 0, 3, True)\n\n\n# Now let's take a look at the App Store data set.\n\n# In[16]:\n\n\nprint(apple_store_header)\nprint('\\n')\nexplore_data(apple_store, 0, 3, True)\n\n\n# We have 7197 Apple apps in this data set, and the columns that seem interesting are: 'track_name', 'currency', 'price', 'rating_count_tot', 'rating_count_ver', and 'prime_genre'. Not all column names are self-explanatory in this case, but details about each column can be found in the data set [documentation](https://www.kaggle.com/ramamet4/app-store-apple-data-set-10k-apps/home).\n\n# # Deleting wrong Data\n# \n# The Google Play data set has a dedicated [discussion section](https://www.kaggle.com/lava18/google-play-store-apps), and we can see that [one of the discussions](https://www.kaggle.com/lava18/google-play-store-apps/discussion/66015) outlines an error for row 10472. Let's print this row and compare it against the header and another row that is correct.\n\n# In[4]:\n\n\nprint(google_play_store_header)\nprint(google_play_store[10472])\n\n\n# The row 10472 corresponds to the app Life Made WI-Fi Touchscreen Photo Frame, and we can see that the rating is 19. This is clearly off because the maximum rating for a Google Play app is 5 (as mentioned in the discussions section, this problem is caused by a missing value in the 'Category' column). As a consequence, we'll delete this row.\n\n# In[5]:\n\n\ndel google_play_store[10472]\n\n\n# In[6]:\n\n\nexplore_data(google_play_store, 10471, 10475, True)\n\n\n# # Removing Duplicate data\n\n# If we explore the Google Play data set long enough, we'll find that some apps have more than one entry. For instance, the application Instagram has four entries:\n\n# In[7]:\n\n\nunique_data = []\nduplicate = []\nfor rows in google_play_store:\n name = rows[0]\n if name in unique_data:\n duplicate.append(name)\n else:\n unique_data.append(name)\nprint(len(duplicate))\n\n\n# We have 1181 duplicate values in google-play-store data. We don't want to count certain apps more than once when we analyze data, so we need to remove the duplicate entries and keep only one entry per app. One thing we could do is remove the duplicate rows randomly, but we could probably find a better way.\n# \n# If you examine the rows we printed for the Instagram app, the main difference happens on the fourth position of each row, which corresponds to the number of reviews. The different numbers show the data was collected at different times.\n\n# In[8]:\n\n\nprint(google_play_store_header)\nfor app in google_play_store:\n name = app[0]\n if name == \"Instagram\":\n print(app)\n\n\n# We can use this information to build a criterion for removing the duplicates. The higher the number of reviews, the more recent the data should be. Rather than removing duplicates randomly, we'll only keep the row with the highest number of reviews and remove the other entries for any given app.\n\n# To remove the duplicates, we will:\n# \n# * Create a dictionary, where each dictionary key is a unique app name and the corresponding dictionary value is the highest number of reviews of that app.\n# * Use the information stored in the dictionary and create a new data set, which will have only one entry per app (and for each app, we'll only select the entry with the highest number of reviews).\n\n# In[9]:\n\n\nreviews_max = {}\nnew_google_data = []\nfor rows in google_play_store:\n name = rows[0]\n reviews = int(rows[3])\n if name not in reviews_max:\n reviews_max[name] = reviews\n elif name in reviews_max and reviews_max[name] < reviews:\n reviews_max[name] = reviews\nfor rows in google_play_store[1:]:\n name = rows[0]\n reviews = int(rows[3])\n if name in reviews_max and reviews_max[name] == reviews:\n new_google_data.append(rows)\nexplore_data(new_google_data, 1, 5, False)\n\n\n# * We start by initializing two empty lists, google_clean and already_added.\n# * We loop through the android data set, and for every iteration:\n# * We isolate the name of the app and the number of reviews.\n# * We add the current row (app) to the android_clean list, and the app name (name) to the already_added list if:\n# * The number of reviews of the current app matches the number of reviews of that app as described in the reviews_max dictionary; and\n# * The name of the app is not already in the already_added list. We need to add this supplementary condition to account for those cases where the highest number of reviews of a duplicate app is the same for more than one entry (for example, the Box app has three entries, and the number of reviews is the same). If we just check for reviews_max[name] == n_reviews, we'll still end up with duplicate entries for some apps.\n\n# In[10]:\n\n\ngoogle_clean = []\nalready_added = []\nfor rows in google_play_store:\n name = rows[0]\n reviews = int(rows[3])\n if (reviews_max[name] == reviews) and (name not in already_added):\n google_clean.append(rows)\n already_added.append(name)\nexplore_data(google_clean, 1, 5, True)\n\n\n# ## Removing non English App\n# \n# Remember we use English for the apps we develop at our company, and we'd like to analyze only the apps that are directed toward an English-speaking audience. However, if we explore the data long enough, we'll find that both data sets have apps with names that suggest they are not directed toward an English-speaking audience.\n# \n# We're not interested in keeping these apps, so we'll remove them. One way to go about this is to remove each app with a name containing a symbol that is not commonly used in English text — English text usually includes letters from the English alphabet, numbers composed of digits from 0 to 9, punctuation marks (., !, ?, ;), and other symbols (+, *, /).\n# \n# Behind the scenes, each character we use in a string has a corresponding number associated with it. For instance, the corresponding number for character 'a' is 97, character 'A' is 65, and character '爱' is 29,233. We can get the corresponding number of each character using the ord() built-in function.\n# \n# The numbers corresponding to the characters we commonly use in an English text are all in the range 0 to 127, according to the ASCII (American Standard Code for Information Interchange) system. Based on this number range, we can build a function that detects whether a character belongs to the set of common English characters or not. If the number is equal to or less than 127, then the character belongs to the set of common English characters.\n# \n# If an app name contains a character that is greater than 127, then it probably means that the app has a non-English name. Our app names, however, are stored as strings, so how could we take each individual character of a string and check its corresponding number?\n# \n# In Python, strings are indexable and iterable, which means we can use indexing to select an individual character, and we can also iterate on the string using a for loop.\n# \n# * We'll write a function that takes in a string and returns False if there's any character in the string that doesn't belong to the set of common English characters, otherwise it returns True.\n# \n# * Inside the function, iterate over the input string. For each iteration check whether the number associated with the character is greater than 127. When a character is greater than 127, the function should immediately return False — the app name is probably non-English since it contains a character that doesn't belong to the set of common English characters.\n# \n# * If the loop finishes running without the return statement being executed, then it means no character had a corresponding number over 127 — the app name is probably English, so the functions should return True.\n# \n# * We'll use the function to check whether these app names are detected as English or non-English:\n# \n# * 'Instagram'\n# * '爱奇艺PPS -《欢乐颂2》电视剧热播'\n# * 'Docs To Go™ Free Office Suite'\n# * 'Instachat 😜'\n# \n# To minimize the impact of data loss, we'll only remove an app if its name has more than three non-ASCII characters:\n\n# In[11]:\n\n\ndef english_str(st):\n non_ascii = 0\n \n for character in st:\n if ord(character) > 127:\n non_ascii += 1\n \n if non_ascii > 3:\n return False\n else:\n return True\ns = 'Instagram'\nprint(english_str(s))\ns = '爱奇艺PPS -《欢乐颂2》电视剧热播'\nprint(english_str(s))\ns = 'Docs To Go™ Free Office Suite'\nprint(english_str(s))\ns = 'Instachat 😜'\nprint(english_str(s))\n\n\n# Let's use the new function to filter out non-English apps from both data sets. Loop through each data set. If an app name is identified as English, append the whole row to a separate list.\n# \n# Explore the data sets and see how many rows you have remaining for each data set.\n\n# In[12]:\n\n\ngoogle_eng = []\napple_eng =[]\nfor rows in google_clean:\n name = rows[0]\n if english_str(name):\n google_eng.append(rows)\n \nfor rows in apple_store:\n name = rows[1]\n if english_str(name):\n apple_eng.append(rows)\nprint(google_play_store_header)\nexplore_data(google_eng, 0, 5, True)\nprint(apple_store_header)\nexplore_data(apple_eng, 0, 5, True)\n\n\n# ## Isolating Free Apps\n# \n# As we mentioned in the introduction, we only build apps that are free to download and install, and our main source of revenue consists of in-app ads. Our data sets contain both free and non-free apps, and we'll need to isolate only the free apps for our analysis. Below, we isolate the free apps for both our data sets.\n\n# In[13]:\n\n\ndef free_app(dataset, index):\n free_app = []\n for rows in dataset:\n price = rows[index]\n if (price == '0.0') or (price == '0'):\n free_app.append(rows)\n return free_app\ngoogle_free_app = free_app(google_eng, 7)\napple_free_app = free_app(apple_eng, 4)\nexplore_data(google_free_app, 1, 5, True)\nexplore_data(apple_free_app, 1, 5, True) \n\n\n# # Most Common Apps by Genre\n# ## Part 1\n# \n# So far, we spent a good amount of time on cleaning data, and:\n# \n# 1. Removed inaccurate data\n# 2. Removed duplicate app entries\n# 3. Removed non-English apps\n# 4. Isolated the free apps\n# \n# As we mentioned in the introduction, our aim is to determine the kinds of apps that are likely to attract more users because our revenue is highly influenced by the number of people using our apps.\n# \n# To minimize risks and overhead, our validation strategy for an app idea is comprised of three steps:\n# \n# 1. Build a minimal Android version of the app, and add it to Google Play.\n# 2. If the app has a good response from users, we develop it further.\n# 3. If the app is profitable after six months, we build an iOS version of the app and add it to the App Store.\n# \n# Because our end goal is to add the app on both Google Play and the App Store, we need to find app profiles that are successful on both markets. For instance, a profile that works well for both markets might be a productivity app that makes use of gamification.\n# \n# Let's begin the analysis by getting a sense of what are the most common genres for each market. For this, we'll need to build frequency tables for a few columns in our data sets.\n\n# In[17]:\n\n\ndef percent_tb(dataset, index):\n percent_dict = {}\n total = 0\n for row in dataset:\n total += 1\n genre = row[index]\n if genre in percent_dict:\n percent_dict[genre] += 1\n else:\n percent_dict[genre] = 1\n for content in percent_dict:\n proportion = percent_dict[content]/total\n percentage = proportion * 100\n percent_dict[content] = percentage\n return percent_dict\ndef descending(dataset, index):\n table = percent_tb(dataset, index)\n unsort_tb = []\n for keys in table:\n key_value_tuple = (table[keys],keys)\n unsort_tb.append(key_value_tuple)\n sort_tb = sorted(unsort_tb, reverse = True)\n for entry in sort_tb:\n print(entry[1], ':', entry[0]) \ndescending(google_free_app, 1)\nprint('\\n')\ndescending(apple_free_app, -5)\n\n\n# \n# In Apple Store: We can see that among the free English apps, more than a half (58.16%) are games. Entertainment apps are close to 8%, followed by photo and video apps, which are close to 5%. Only 3.66% of the apps are designed for education, followed by social networking apps which amount for 3.29% of the apps in our data set.\n# \n# The general impression is that App Store (at least the part containing free English apps) is dominated by apps that are designed for fun (games, entertainment, photo and video, social networking, sports, music, etc.), while apps with practical purposes (education, shopping, utilities, productivity, lifestyle, etc.) are more rare. However, the fact that fun apps are the most numerous doesn't also imply that they also have the greatest number of users — the demand might not be the same as the offer.\n# \n# Let's continue by examining the Genres and Category columns of the Google Play data set (two columns which seem to be related).\n\n# In[20]:\n\n\ndescending(google_free_app, 1) # Category\n\n\n# On Google Play: there are not that many apps designed for fun, and it seems that a good number of apps are designed for practical purposes (family, tools, business, lifestyle, productivity, etc.). However, if we investigate this further, we can see that the family category (which accounts for almost 19% of the apps) means mostly games for kids.\n\n# In[21]:\n\n\ndescending(google_free_app, -4) # Genre\n\n\n# The difference between the Genres and the Category columns is not crystal clear, but one thing we can notice is that the Genres column is much more granular (it has more categories). We're only looking for the bigger picture at the moment, so we'll only work with the Category column moving forward.\n# \n# Up to this point, we found that the App Store is dominated by apps designed for fun, while Google Play shows a more balanced landscape of both practical and for-fun apps. Now we'd like to get an idea about the kind of apps that have most users.\n\n# # Most Popular Apps by Genre on the App Store\n\n# One way to find out what genres are the most popular (have the most users) is to calculate the average number of installs for each app genre. For the Google Play data set, we can find this information in the Installs column, but for the App Store data set this information is missing. As a workaround, we'll take the total number of user ratings as a proxy, which we can find in the rating_count_tot app.\n# \n# Below, we calculate the average number of user ratings per app genre on the App Store:\n\n# In[27]:\n\n\nprime_genre = percent_tb(apple_free_app, -5)\nfor genre in prime_genre:\n total = 0\n len_genre = 0\n for row in apple_free_app:\n genre_app = row[-5]\n if genre_app == genre:\n user_rating = float(row[5])\n total += user_rating\n len_genre += 1\n average = total/len_genre\n print(genre, \":\", average)\n\n\n# On average, navigation apps have the highest number of user reviews, but this figure is heavily influenced by Waze and Google Maps, which have close to half a million user reviews together:\n\n# In[28]:\n\n\nfor app in apple_free_app:\n if app[-5] == 'Navigation':\n print(app[1], ':', app[5]) # print name and number of ratings\n\n\n# The same pattern applies to social networking apps, where the average number is heavily influenced by a few giants like Facebook, Pinterest, Skype, etc. Same applies to music apps, where a few big players like Pandora, Spotify, and Shazam heavily influence the average number.\n# \n# Our aim is to find popular genres, but navigation, social networking or music apps might seem more popular than they really are. The average number of ratings seem to be skewed by very few apps which have hundreds of thousands of user ratings, while the other apps may struggle to get past the 10,000 threshold. We could get a better picture by removing these extremely popular apps for each genre and then rework the averages, but we'll leave this level of detail for later.\n# \n# Reference apps have 74,942 user ratings on average, but it's actually the Bible and Dictionary.com which skew up the average rating:\n\n# In[29]:\n\n\nfor app in apple_free_app:\n if app[-5] == 'Reference':\n print(app[1], \":\", app[5])\n\n\n# However, this niche seems to show some potential. One thing we could do is take another popular book and turn it into an app where we could add different features besides the raw version of the book. This might include daily quotes from the book, an audio version of the book, quizzes about the book, etc. On top of that, we could also embed a dictionary within the app, so users don't need to exit our app to look up words in an external app.\n# \n# This idea seems to fit well with the fact that the App Store is dominated by for-fun apps. This suggests the market might be a bit saturated with for-fun apps, which means a practical app might have more of a chance to stand out among the huge number of apps on the App Store.\n# \n# Other genres that seem popular include weather, book, food and drink, or finance. The book genre seem to overlap a bit with the app idea we described above, but the other genres don't seem too interesting to us:\n# \n# Weather apps — people generally don't spend too much time in-app, and the chances of making profit from in-app adds are low. Also, getting reliable live weather data may require us to connect our apps to non-free APIs.\n# \n# Food and drink — examples here include Starbucks, Dunkin' Donuts, McDonald's, etc. So making a popular food and drink app requires actual cooking and a delivery service, which is outside the scope of our company.\n# \n# Finance apps — these apps involve banking, paying bills, money transfer, etc. Building a finance app requires domain knowledge, and we don't want to hire a finance expert just to build an app.\n\n# # Most Popular Apps by Genre on Google Play\n\n# For the Google Play market, we actually have data about the number of installs, so we should be able to get a clearer picture about genre popularity. However, the install numbers don't seem precise enough — we can see that most values are open-ended (100+, 1,000+, 5,000+, etc.):\n\n# In[31]:\n\n\ndescending(google_free_app, 5)\n\n\n# \n# One problem with this data is that is not precise. For instance, we don't know whether an app with 100,000+ installs has 100,000 installs, 200,000, or 350,000. However, we don't need very precise data for our purposes — we only want to get an idea which app genres attract the most users, and we don't need perfect precision with respect to the number of users.\n# \n# We're going to leave the numbers as they are, which means that we'll consider that an app with 100,000+ installs has 100,000 installs, and an app with 1,000,000+ installs has 1,000,000 installs, and so on.\n# \n# To perform computations, however, we'll need to convert each install number to float — this means that we need to remove the commas and the plus characters, otherwise the conversion will fail and raise an error. We'll do this directly in the loop below, where we also compute the average number of installs for each genre (category).\n\n# In[34]:\n\n\ng_category = percent_tb(google_free_app, 1)\nfor category in g_category:\n total = 0\n len_category = 0\n for row in google_free_app:\n category_app = row[1]\n if category_app == category:\n n_installs = row[5]\n s_ch = ['+',',']\n for ch in s_ch:\n n_installs = n_installs.replace(ch, '')\n total += float(n_installs)\n len_category += 1\n average = total/len_category\n print(category, \":\", average)\n\n\n# On average, communication apps have the most installs: 38,456,119. This number is heavily skewed up by a few apps that have over one billion installs (WhatsApp, Facebook Messenger, Skype, Google Chrome, Gmail, and Hangouts), and a few others with over 100 and 500 million installs:\n\n# In[35]:\n\n\nfor app in google_free_app:\n if app[1] == 'COMMUNICATION' and (app[5] == '1,000,000,000+'\n or app[5] == '500,000,000+'\n or app[5] == '100,000,000+'):\n print(app[0], ':', app[5])\n\n\n# If we removed all the communication apps that have over 100 million installs, the average would be reduced roughly ten times:\n\n# In[43]:\n\n\nunder_100m = []\nfor app in google_free_app:\n n_install = app[5]\n n_install = n_install.replace('+','')\n n_install = n_install.replace(',','')\n if (app[1] == 'COMMUNICATION') and (float(n_installs) < 100000000):\n under_100m.append(float(n_install))\nsum(under_100m)/len(under_100m)\n\n\n# We see the same pattern for the video players category, which is the runner-up with 24,727,872 installs. The market is dominated by apps like Youtube, Google Play Movies & TV, or MX Player. The pattern is repeated for social apps (where we have giants like Facebook, Instagram, Google+, etc.), photography apps (Google Photos and other popular photo editors), or productivity apps (Microsoft Word, Dropbox, Google Calendar, Evernote, etc.).\n# \n# Again, the main concern is that these app genres might seem more popular than they really are. Moreover, these niches seem to be dominated by a few giants who are hard to compete against.\n# \n# The game genre seems pretty popular, but previously we found out this part of the market seems a bit saturated, so we'd like to come up with a different app recommendation if possible.\n# \n# The books and reference genre looks fairly popular as well, with an average number of installs of 8,767,811. It's interesting to explore this in more depth, since we found this genre has some potential to work well on the App Store, and our aim is to recommend an app genre that shows potential for being profitable on both the App Store and Google Play.\n# \n# Let's take a look at some of the apps from this genre and their number of installs:\n\n# In[44]:\n\n\nfor app in google_free_app:\n if app[1] == 'BOOKS_AND_REFERENCE':\n print(app[0], ':', app[5])\n\n\n# The book and reference genre includes a variety of apps: software for processing and reading ebooks, various collections of libraries, dictionaries, tutorials on programming or languages, etc. It seems there's still a small number of extremely popular apps that skew the average:\n\n# In[45]:\n\n\nfor app in google_free_app:\n if app[1] == 'BOOKS_AND_REFERENCE' and (app[5] == '1,000,000,000+'\n or app[5] == '500,000,000+'\n or app[5] == '100,000,000+'):\n print(app[0], ':', app[5])\n\n\n# However, it looks like there are only a few very popular apps, so this market still shows potential. Let's try to get some app ideas based on the kind of apps that are somewhere in the middle in terms of popularity (between 1,000,000 and 100,000,000 downloads):\n\n# In[46]:\n\n\nfor app in google_free_app:\n if app[1] == 'BOOKS_AND_REFERENCE' and (app[5] == '1,000,000+'\n or app[5] == '5,000,000+'\n or app[5] == '10,000,000+'\n or app[5] == '50,000,000+'):\n print(app[0], ':', app[5])\n\n\n# This niche seems to be dominated by software for processing and reading ebooks, as well as various collections of libraries and dictionaries, so it's probably not a good idea to build similar apps since there'll be some significant competition.\n# \n# We also notice there are quite a few apps built around the book Quran, which suggests that building an app around a popular book can be profitable. It seems that taking a popular book (perhaps a more recent book) and turning it into an app could be profitable for both the Google Play and the App Store markets.\n# \n# However, it looks like the market is already full of libraries, so we need to add some special features besides the raw version of the book. This might include daily quotes from the book, an audio version of the book, quizzes on the book, a forum where people can discuss the book, etc.\n\n# # Conclusions\n# \n# In this project, we analyzed data about the App Store and Google Play mobile apps with the goal of recommending an app profile that can be profitable for both markets.\n# \n# We concluded that taking a popular book (perhaps a more recent book) and turning it into an app could be profitable for both the Google Play and the App Store markets. The markets are already full of libraries, so we need to add some special features besides the raw version of the book. This might include daily quotes from the book, an audio version of the book, quizzes on the book, a forum where people can discuss the book, etc.\n\n# In[ ]:\n\n\n\n\n","sub_path":"Play Store Apps Data Analysis.py","file_name":"Play Store Apps Data Analysis.py","file_ext":"py","file_size_in_byte":27776,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"264927135","text":"# Before running the script, create a backup of databoard/model.py\n# (mv databoard/model.py databoard/model_backup.py)\n# and move tools/model_transfer.py to databoard/model.py\n# The csv files mentionned at the beginning are obtained with the script\n# tools/export_to_csv.sh.\n# If a csv file is too big (as it might be the case for\n# submission_on_cv_folds.csv), you need to split it in different file, such as\n# submission_on_cv_fold.csv with i between 0 and 9\n# (to split files, you can use split_csv.sh)\nimport inspect\nimport base64\nimport zlib\nimport math\nimport numpy as np\nimport pandas as pd\nfrom databoard import db\nimport databoard.model\n\ndir_data = './'\ncsv1 = [['submission_file_types.csv'], ['users.csv'], ['workflows.csv'],\n ['extensions.csv'], ['score_types.csv']]\ncsv2 = [['workflow_element_types.csv'], ['submission_file_type_extensions.csv'],\n ['teams.csv'], ['problems.csv']]\ncsv3 = [['workflow_elements.csv'], ['events.csv']]\ncsv4 = [['cv_folds.csv'], ['event_admins.csv'], ['event_teams.csv'],\n ['event_score_types.csv']]\ncsv5 = [['submissions.csv']]\ncsv6 = [['submission_on_cv_fold%s.csv' % i for i in range(1, 6)],\n ['submission_files.csv'],\n ['submission_similaritys.csv'], ['submission_scores.csv']]\ncsv7 = [['user_interactions.csv'], ['submission_score_on_cv_folds.csv']]\nmeta_list_csv = [csv1, csv2, csv3, csv4, csv5, csv6, csv7]\n\n\ndef clean_data(table, table_data, remove_field):\n t_id = table_data['id']\n del table_data['id']\n removed_field = {}\n for rf in remove_field:\n removed_field[rf] = table_data[rf]\n del table_data[rf]\n t = table(**table_data)\n t.id = t_id\n return t, removed_field\n\n\ndef put_obj_not_id(table_data, db_obj_name, model):\n db_obj_id = table_data['%s_id' % db_obj_name]\n del table_data['%s_id' % db_obj_name]\n db_obj = model.query.filter_by(id=db_obj_id).one()\n table_data[db_obj_name] = db_obj\n return table_data\n\n\ndef create_table_instances(table, csv_file, db):\n data = pd.read_csv(csv_file)\n for dd in data.iterrows():\n table_data = dd[1].to_dict()\n # Change hex() in keys that contain it\n if 'hex(train_is)' in table_data.keys():\n table_data['train_is'] = table_data.pop('hex(train_is)')\n table_data['test_is'] = table_data.pop('hex(test_is)')\n elif 'hex(full_train_y_pred)' in table_data.keys():\n table_data['full_train_y_pred'] =\\\n table_data.pop('hex(full_train_y_pred)')\n table_data['test_y_pred'] = table_data.pop('hex(test_y_pred)')\n elif 'hex(valid_score_cv_bags)' in table_data.keys():\n table_data['valid_score_cv_bags'] =\\\n table_data.pop('hex(valid_score_cv_bags)')\n table_data['test_score_cv_bags'] =\\\n table_data.pop('hex(test_score_cv_bags)')\n # Deal with boolean: convert 0/1 to '0'/'1'\n # Deal with NumpyType()\n for kk, vv in table_data.items():\n try:\n if table.__table__.columns[kk].type.python_type == bool:\n table_data[kk] = str(vv)\n except NotImplementedError:\n # NumpyType\n vv = base64.b16decode(vv)\n table_data[kk] = np.loads(zlib.decompress(vv))\n if type(vv) == float:\n if math.isnan(vv):\n table_data[kk] = None\n t = None\n try:\n t = table(**table_data)\n except Exception as e:\n raise e\n if t:\n db.session.add(t)\n db.session.commit()\n table_name = table.__table__.name\n sql_c = (\"SELECT setval('%s_id_seq', \" +\n \"(SELECT MAX(id) FROM %s) +1);\") % (table_name, table_name)\n db.engine.execute(sql_c)\n\n\ndef create_tables_from_list_csv(model_module, dict_csv, dir_data, db):\n for name, obj in inspect.getmembers(model_module):\n if name in dict_csv.keys():\n print('Creating table %s' % name)\n for dd in dict_csv[name]:\n csv_file = dir_data + dd\n create_table_instances(obj, csv_file, db)\n\n\ndef list_csv_to_dict(list_csv):\n dict_csv = {}\n for list_file_csv in list_csv:\n file_csv = list_file_csv[0]\n # convert csv file name to model name\n name_csv = ''.join([dd.title()\n for dd in file_csv.split('.')[0].split('_')])\n name_csv = name_csv[:-1] # remove the s at the end\n # Deal with CVFold...\n if name_csv == 'CvFold':\n name_csv = 'CVFold'\n elif name_csv == 'SubmissionOnCvFold':\n name_csv = 'SubmissionOnCVFold'\n elif name_csv == 'SubmissionScoreOnCvFold':\n name_csv = 'SubmissionScoreOnCVFold'\n dict_csv[name_csv] = list_file_csv\n return dict_csv\n\n\nfor list_csv in meta_list_csv:\n print('*' * 80)\n print(list_csv)\n print('-' * 80)\n dict_csv = list_csv_to_dict(list_csv)\n create_tables_from_list_csv(databoard.model, dict_csv, dir_data, db)\n","sub_path":"tools/convert_to_postgres.py","file_name":"convert_to_postgres.py","file_ext":"py","file_size_in_byte":5015,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"474828002","text":"from pic16f628a import PIC16F628A\n\nA=15\nB=30\nW=0\nF=1\n\npic=PIC16F628A()\n\nsayac_id=0\ntoplam_id=2\nstatus=1\n\nsayac = pic.RAM[sayac_id]\ntoplam = pic.RAM[toplam_id]\n\npic.clrf(toplam_id)\npic.movlw(A)\npic.movwf(sayac_id)\ni = 0\n#cevrim\nwhile True:\n pic.movf(sayac_id,W)\n pic.addwf(toplam_id,F)\n pic.movlw(B)\n pic.subwf(sayac_id,W)\n print(f\"{i}.Sayac: {sayac.bits}\")\n print(f\"{i}.Toplam: {toplam.bits}\")\n print(f\"{i}.36. FR: {pic.RAM[4].bits}\\n\")\n pic.btfsc(status,2)\n i+=1\n #if pic.StatusFileRegister.get_bit(2) == 0:\n if pic.skipBTFSC:\n pic.movlw(3)\n pic.addwf(sayac_id,F)\n else:\n #sonuc\n pic.movf(toplam_id,W)\n pic.movwf(4)\n break\n\nprint(f\"Sayac: {sayac.bits}\")\nprint(f\"Toplam: {toplam.bits}\")\nprint(f\"36. FR: {pic.RAM[4].bits}\")\n","sub_path":"example_0.py","file_name":"example_0.py","file_ext":"py","file_size_in_byte":801,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"472338695","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\n\"\"\"\nCopyright (c) 2014-2018 Gonzalo Ciruelos \nCopyright (c) 2018-2023 Federico Ferri \n\"\"\"\n\nimport re\nfrom collections import namedtuple\n\n\ndef UnsupportedOperands(op, type1, type2):\n def as_type(x):\n return x if isinstance(x, type) else type(x)\n fmt = 'unsupported operand type(s) for {}: {} and {}'\n type1 = as_type(type1)\n type2 = as_type(type2)\n return TypeError(fmt.format(op, type1.__name__, type2.__name__))\n\n\nclass PitchClassRenderingOptions:\n use_unicode = True\n use_solfege = False\n\n\nclass PitchClass:\n \"\"\"\n The pitch class.\n\n The pitch class refers to all pitches that are a whole number of octaves apart.\n\n The pitch class is composed by:\n * a pitch name,\n * (optional) accidentals, up to 6.\n\n Commonly used pitch names are the 7 letters: C, D, E, F, G, A, and B.\n\n Alternatively, solfège names (Do, Re, Mi, ...) are recognized.\n \"\"\"\n\n max_accidentals = 6\n\n Info = namedtuple('Info', ('name', 'index', 'number', 'normal_accidentals', 'solfege_names'))\n\n info = {\n 'C': Info('C', 0, 0, {0, 1}, ('Do',)),\n 'D': Info('D', 1, 2, {-1, 0, 1}, ('Re',)),\n 'E': Info('E', 2, 4, {-1, 0}, ('Mi',)),\n 'F': Info('F', 3, 5, {0, 1}, ('Fa',)),\n 'G': Info('G', 4, 7, {-1, 0, 1}, ('Sol',)),\n 'A': Info('A', 5, 9, {-1, 0, 1}, ('La',)),\n 'B': Info('B', 6, 11, {-1, 0}, ('Si', 'Ti')),\n }\n\n names = tuple(info.keys())\n solfege_names_inv = {sn: info.name for info in info.values() for sn in info.solfege_names}\n all_names = names + tuple(solfege_names_inv.keys())\n\n pattern_str = '(' + '|'.join(all_names) + ')(' + \\\n '|'.join(('b{0,$MAX}', '#{0,$MAX}', '♭{0,$MAX}', '♯{0,$MAX}', '𝄫', '𝄪')) \\\n .replace('$MAX', str(max_accidentals)) + ')'\n pattern = re.compile('^' + pattern_str + '$')\n\n rendering_options = PitchClassRenderingOptions()\n\n @staticmethod\n def all(max_accidentals=-1):\n \"\"\"\n Generate all pitch classes.\n\n Depending on the `max_accidentals` parameter, it will include:\n * only \"basic\" accidentals, as found on the black keys of a piano, if `max_accidentals` is -1;\n * no accidentals, if `max_accidentals` is 0;\n * at most 1 accidental, if `max_accidentals` is 1;\n * and so on...\n \"\"\"\n if not isinstance(max_accidentals, int):\n raise TypeError('Invalid max_accidentals type')\n if max_accidentals < -1:\n raise ValueError('Invalid max_accidentals value')\n\n if max_accidentals == -1:\n for n, info in PitchClass.info.items():\n for acc in info.normal_accidentals:\n yield PitchClass(n, acc)\n else:\n for n in PitchClass.names:\n for acc in [0] + [sign * (a + 1) for a in range(max_accidentals) for sign in (-1, 1)]:\n yield PitchClass(n, acc)\n\n @staticmethod\n def parse(s):\n if isinstance(s, PitchClass):\n return s\n if not isinstance(s, str):\n raise TypeError('Invalid input type')\n\n m = PitchClass.pattern.match(s)\n if m is None:\n raise ValueError('Could not parse PitchClass: {!r}'.format(s))\n\n name = m.group(1)\n\n acc = m.group(2)\n if acc == '':\n acc = 0\n elif acc == '𝄫':\n acc = -2\n elif acc == '𝄪':\n acc = 2\n else:\n acc = len(acc) * {'b': -1, '#': 1, '♭': -1, '♯': 1}[acc[0:1]]\n\n return PitchClass(name, acc)\n\n def __init__(self, name, accidentals=None):\n \"\"\"\n Construct a pitch class from either:\n * pitch name (A, B, C, D, E, F, or G) and number of accidentals (negative for flat, positive for sharp);\n * its string representation, e.g. 'C#'.\n \"\"\"\n\n if isinstance(name, str) and accidentals is None and name not in self.all_names:\n pc = PitchClass.parse(name)\n for f in ('name', 'accidentals'):\n setattr(self, f, getattr(pc, f))\n return\n\n if not isinstance(name, str):\n raise TypeError('Invalid name type')\n if accidentals is None:\n accidentals = 0\n if not isinstance(accidentals, int):\n raise TypeError('Invalid accidentals type')\n if abs(accidentals) > PitchClass.max_accidentals:\n raise ValueError('Too many accidentals: {}'.format(accidentals))\n\n if name in PitchClass.names:\n self.name = name\n elif name in PitchClass.solfege_names_inv:\n self.name = PitchClass.solfege_names_inv[name]\n else:\n raise ValueError('Invalid pitch name: {!r}'.format(name))\n\n self.accidentals = accidentals\n\n def __lt__(self, other):\n return (PitchClass.info[self.name].number, self.accidentals) < \\\n (PitchClass.info[other.name].number, other.accidentals)\n\n def __le__(self, other):\n return self == other or self < other\n\n def __str__(self):\n return self.name_str + self.accidentals_str\n\n def __repr__(self):\n return 'PitchClass({!r})'.format(str(self))\n\n def __hash__(self):\n return hash(str(self))\n\n def __eq__(self, other):\n return str(self) == str(other)\n\n @property\n def index(self):\n return PitchClass.info[self.name].index\n\n @property\n def number(self):\n return PitchClass.info[self.name].number + self.accidentals\n\n @property\n def name_str(self):\n if PitchClass.rendering_options.use_solfege:\n return PitchClass.info[self.name].solfege_names[0]\n else:\n return self.name\n\n @property\n def accidentals_str(self):\n if self.accidentals == 0:\n return ''\n\n num = abs(self.accidentals)\n sign = self.accidentals // num\n if PitchClass.rendering_options.use_unicode:\n if num == 2:\n return {-1: '𝄫', 1: '𝄪'}[sign]\n else:\n return {-1: '♭', 1: '♯'}[sign] * num\n else:\n return {-1: 'b', 1: '#'}[sign] * num\n\n def flat(self):\n return PitchClass(self.name, self.accidentals - 1)\n\n def sharp(self):\n return PitchClass(self.name, self.accidentals + 1)\n\n def natural(self):\n return PitchClass(self.name, 0)\n\n def to_octave(self, octave):\n return Note(self, octave)\n\n @property\n def lilypond_notation(self):\n s = self.name.lower()\n for i in range(-self.accidentals):\n s += 'es'\n for i in range(self.accidentals):\n s += 'is'\n return s\n\n\nclass Note:\n \"\"\"\n The note class.\n\n A note refers to a specific pitch, and it is composed by:\n * the pitch class,\n * the octave.\n \"\"\"\n\n pattern_str = '(' + PitchClass.pattern_str + r')(\\d{1})'\n pattern = re.compile('^' + pattern_str + '$')\n\n @staticmethod\n def all(min_octave=4, max_octave=4, max_accidentals=-1):\n for octave in range(min_octave, max_octave + 1):\n for pc in PitchClass.all(max_accidentals):\n yield Note(pc, octave)\n\n @staticmethod\n def parse(s):\n if isinstance(s, Note):\n return s\n if not isinstance(s, str):\n raise TypeError('Invalid input type')\n\n m = Note.pattern.match(s)\n if m is None:\n raise ValueError('Could not parse Note: {!r}'.format(s))\n\n pc_name, *_, octave = m.groups()\n return Note(PitchClass.parse(pc_name), int(octave))\n\n number_inv_mapping = {}\n\n @staticmethod\n def from_number(number, allowed_accidentals=range(-2, 3)):\n if not Note.number_inv_mapping:\n # generate the inverse mapping once:\n for n in Note.all(0, 9, PitchClass.max_accidentals):\n if n.number not in Note.number_inv_mapping:\n Note.number_inv_mapping[n.number] = set()\n Note.number_inv_mapping[n.number].add(n)\n\n return set(n for n in Note.number_inv_mapping.get(number, [])\n if (allowed_accidentals == -1 and\n n.pitch_class.accidentals in PitchClass.info[n.pitch_class.name].normal_accidentals)\n or (allowed_accidentals != -1 and\n n.pitch_class.accidentals in allowed_accidentals))\n\n @staticmethod\n def from_midi_note(midi_note, allowed_accidentals=range(-2, 3)):\n return Note.from_number(midi_note - 12, allowed_accidentals)\n\n @staticmethod\n def from_numbers(numbers, allowed_accidentals=range(-2, 3)):\n if 1 in allowed_accidentals and -1 in allowed_accidentals:\n # need to split into two subproblems\n raise NotImplementedError\n # XXX: we assume it is either [-n,0] or [0,n] range\n # (not 100% correct and/or safe)\n m = {n: Note.from_number(n, allowed_accidentals) for n in numbers}\n import constraint\n p = constraint.Problem()\n\n for n, notes in m.items():\n p.addVariable(n, list(notes))\n\n def un(n):\n # str of unaltered note\n return n.pitch_class.name + str(n.octave)\n for n1 in m:\n for n2 in m:\n if n1 != n2:\n p.addConstraint(lambda a, b: un(a) != un(b), [n1, n2])\n\n solutions = p.getSolutions()\n\n return tuple(tuple(solution[n] for n in numbers) for solution in solutions)\n\n @staticmethod\n def from_midi_notes(midi_notes, allowed_accidentals=range(-2, 3)):\n return Note.from_numbers([n - 12 for n in midi_notes], allowed_accidentals)\n\n def __init__(self, pitch_class, octave=None):\n \"\"\"\n Construct a note from either:\n * pitch class and octave;\n * its string representation, e.g. 'C#4'\n \"\"\"\n\n if octave is None:\n n = Note.parse(pitch_class)\n for f in ('pitch_class', 'octave', 'number'):\n setattr(self, f, getattr(n, f))\n return\n\n if not isinstance(pitch_class, PitchClass):\n raise TypeError('Invalid pitch_class type')\n if not isinstance(octave, int):\n raise TypeError('Invalid octave type')\n if octave not in range(10):\n raise ValueError('Invalid octave number')\n\n self.pitch_class = pitch_class\n self.octave = octave\n self.number = self.pitch_class.number + self.octave * 12\n\n def __add__(self, other):\n if isinstance(other, Interval):\n if other.is_compound():\n from functools import reduce\n return reduce(lambda a, b: a + b, other.split(), self)\n\n assert other.size != 0\n new_index = (self.pitch_class.index + other.size -\n (1 if other.size > 0 else -1)) % len(PitchClass.names)\n new_pitch_name = PitchClass.names[new_index]\n\n new_number = self.number + other.semitones\n\n new_note_octave = self.octave + int(self.pitch_class.name in PitchClass.names[8 - other.size:])\n\n difference = new_number % 12 - PitchClass.info[new_pitch_name].number\n if difference < -PitchClass.max_accidentals:\n difference += 12\n if difference > PitchClass.max_accidentals:\n difference -= 12\n\n return Note(PitchClass(new_pitch_name, difference), new_note_octave)\n else:\n raise UnsupportedOperands('+', self, other)\n\n def __sub__(self, other):\n if isinstance(other, Interval):\n if other.is_compound():\n from functools import reduce\n return reduce(lambda a, b: a - b, other.split(), self)\n\n return self.to_octave(self.octave - 1) + other.complement()\n elif isinstance(other, Note):\n semitones = self.number - other.number\n if semitones < -1:\n raise ArithmeticError('Interval smaller than d1')\n octaves = 0\n while semitones >= 12:\n semitones -= 12\n octaves += 1\n\n size = self.pitch_class.index - other.pitch_class.index\n size += 1 if size >= 0 else -1\n size = (size + (1 if size < 0 else -1)) % 7 + 1\n\n for i in Interval.all(True):\n if i.size == size and i.semitones == semitones:\n return Interval(i.quality + str(octaves * 7 + size))\n\n raise ValueError('Interval N={} S={}'.format(size, semitones))\n else:\n raise UnsupportedOperands('-', self, other)\n\n @property\n def midi_note(self):\n return self.number + 12\n\n @property\n def frequency(self):\n from math import pow\n return 440.0 * pow(2, (self.number - Note('A4').number) / 12.)\n\n def to_octave(self, octave):\n return Note(self.pitch_class, octave)\n\n @property\n def lilypond_notation(self):\n oct_str = ''\n if self.octave < 3:\n oct_str = ',' * (3 - self.octave)\n elif self.octave > 3:\n oct_str = '\\'' * (self.octave - 3)\n return self.pitch_class.lilypond_notation.replace('b', 'es').replace('#', 'is').lower() + oct_str\n\n def __lt__(self, other):\n return (self.octave, self.pitch_class) < (other.octave, other.pitch_class)\n\n def __le__(self, other):\n return self == other or self < other\n\n def __repr__(self):\n return 'Note({!r})'.format(str(self))\n\n def __str__(self):\n return str(self.pitch_class) + str(self.octave)\n\n def __hash__(self):\n return hash(str(self))\n\n def __eq__(self, other):\n return str(self) == str(other)\n\n\nclass Interval:\n \"\"\"\n The interval class.\n\n The intervals are to be parsed in th following way:\n * the quality, (m, M, p, A, d)\n * the size.\n\n For example, 'd8', 'P1', 'A5' are valid intervals. 'P3', '5' are not.\n \"\"\"\n\n pattern_str = r'(d+|m|P|M|A+)(\\d+)'\n pattern = re.compile('^' + pattern_str + '$')\n\n intervals = {\n 'd1': -1, 'P1': 0, 'A1': 1,\n 'd2': 0, 'm2': 1, 'M2': 2, 'A2': 3,\n 'd3': 2, 'm3': 3, 'M3': 4, 'A3': 5,\n 'd4': 4, 'P4': 5, 'A4': 6,\n 'd5': 6, 'P5': 7, 'A5': 8,\n 'd6': 7, 'm6': 8, 'M6': 9, 'A6': 10,\n 'd7': 9, 'm7': 10, 'M7': 11, 'A7': 12,\n 'd8': 11, 'P8': 12, 'A8': 13,\n }\n\n quality_inverse = {\n 'P': 'P',\n 'd': 'A',\n 'A': 'd',\n 'm': 'M',\n 'M': 'm',\n }\n\n # generate double, tryply, etc... augmented/diminished intervals:\n intervals = (lambda intervals:\n dict(tuple(intervals.items()) +\n tuple((dA * k + str(sz), intervals[dA + str(sz)] + mp * (k - 1))\n for k in (2, 3)\n for sz in range(1, 9)\n for (dA, mp) in (('d', -1), ('A', 1)))))(intervals)\n quality_inverse = (lambda quality_inverse:\n dict(tuple(quality_inverse.items()) +\n tuple((dA * k, Ad * k)\n for k in (2, 3)\n for (dA, Ad) in (('d', 'A'), ('A', 'd')))))(quality_inverse)\n\n @staticmethod\n def all(include_atypical=False):\n for name in Interval.intervals:\n interval = Interval(name)\n if include_atypical or interval.semitones in range(13):\n yield Interval(name)\n\n @staticmethod\n def parse(s):\n if isinstance(s, Interval):\n return s\n if not isinstance(s, str):\n raise TypeError('Invalid input type')\n\n m = Interval.pattern.match(s)\n if m is None:\n raise ValueError('Could not parse Interval: {!r}'.format(s))\n\n quality, size = m.groups()\n return Interval(quality, int(size))\n\n def __init__(self, quality, size=None):\n \"\"\"\n Construct an interval from either:\n * quality (str) and size (int);\n * its string representation, e.g. 'd5'\n \"\"\"\n\n if size is None:\n n = Interval.parse(quality)\n for f in ('quality', 'size', 'semitones'):\n setattr(self, f, getattr(n, f))\n return\n\n if not isinstance(quality, str):\n raise TypeError('Invalid quality type')\n if quality not in Interval.quality_inverse:\n raise ValueError('Invalid interval quality')\n if not isinstance(size, int):\n raise TypeError('Invalid size type')\n if size <= 0:\n raise ValueError('Invalid interval size')\n\n self.quality = quality\n self.size = size\n self.semitones = 0\n\n # compound intervals:\n size = self.size\n while size > 8:\n size -= 7\n self.semitones += 12\n\n try:\n self.semitones += self.intervals[quality + str(size)]\n except KeyError:\n raise ValueError('Invalid interval {!r}.'.format(quality + str(size)))\n\n def __add__(self, other):\n if isinstance(other, Interval):\n n = Note('C0')\n return n + self + other - n\n else:\n raise TypeError('Cannot add {} to Interval'.format(type(other).__name__))\n\n def __sub__(self, other):\n if isinstance(other, Interval):\n if other.size > self.size:\n raise ArithmeticError('Cannot subtract a greater interval')\n n = Note('C0')\n return (n + self) - (n + other)\n else:\n raise TypeError('Cannot subtract {} from Interval'.format(type(other).__name__))\n\n def __lt__(self, other):\n return (self.size, self.semitones) < (other.size, other.semitones)\n\n def __le__(self, other):\n return self == other or self < other\n\n def __str__(self):\n return self.quality + str(self.size)\n\n def __repr__(self):\n return 'Interval({!r})'.format(str(self))\n\n def __hash__(self):\n return hash(str(self))\n\n def __eq__(self, other):\n return str(self) == str(other)\n\n def is_compound(self):\n return self.size > 8\n\n def split(self):\n \"\"\"\n Split a compound interval into simple intervals.\n The sum of splitted intervals is equal to the compound interval.\n \"\"\"\n ret = []\n i = Interval(str(self))\n while i.is_compound():\n i.size -= 7\n i.semitones -= 12\n ret.append(Interval('P8'))\n ret.append(i)\n return ret\n\n def complement(self):\n \"\"\"\n Return the complement of this interval also known as inverted interval.\n The sum of this interval plus its complement is equal to 1 octave (P8),\n except for the case of A8, for which there is no d1 interval.\n \"\"\"\n if self.is_compound():\n raise ValueError('Cannot invert a compound interval')\n else:\n n = 9 - self.size\n q = self.quality_inverse[self.quality]\n return Interval(q + str(n))\n\n def reduce(self):\n if self.size < 8:\n return self\n i = Interval(str(self))\n i.size -= 7 * ((i.size - 1) // 7)\n return i\n\n\nclass Chord:\n \"\"\"\n The chord class.\n\n Contains recipes for common chords.\n \"\"\"\n\n recipes = {\n 'maj': ('P1', 'M3', 'P5'),\n 'min': ('P1', 'm3', 'P5'),\n 'aug': ('P1', 'M3', 'A5'),\n 'dim': ('P1', 'm3', 'd5'),\n 'dom7': ('P1', 'M3', 'P5', 'm7'),\n 'min7': ('P1', 'm3', 'P5', 'm7'),\n 'maj7': ('P1', 'M3', 'P5', 'M7'),\n 'aug7': ('P1', 'M3', 'A5', 'm7'),\n 'dim7': ('P1', 'm3', 'd5', 'd7'),\n 'min7dim5': ('P1', 'm3', 'd5', 'm7'),\n 'sus2': ('P1', 'M2', 'P5'),\n 'sus4': ('P1', 'P4', 'P5'),\n 'dom7sus4': ('P1', 'P4', 'P5', 'm7'),\n 'maj7sus4': ('P1', 'P4', 'P5', 'M7'),\n 'open5': ('P1', 'P5', 'P8'),\n 'dom9': ('P1', 'M3', 'P5', 'm7', 'M9'),\n 'min9': ('P1', 'm3', 'P5', 'm7', 'M9'),\n 'maj9': ('P1', 'M3', 'P5', 'M7', 'M9'),\n 'aug9': ('P1', 'M3', 'A5', 'm7', 'M9'),\n 'dim9': ('P1', 'm3', 'd5', 'd7', 'M9'),\n 'maj6': ('P1', 'M3', 'P5', 'M6'),\n 'min6': ('P1', 'm3', 'P5', 'm6'),\n 'dom6': ('P1', 'M3', 'P5', 'm6'),\n 'min/maj6': ('P1', 'm3', 'P5', 'M6'),\n }\n\n aliases = {\n 'M': 'maj',\n 'm': 'min',\n '+': 'aug',\n '°': 'dim',\n 'sus': 'sus4',\n '7': 'dom7',\n 'm7': 'min7',\n 'M7': 'maj7',\n '+7': 'aug7',\n '7aug5': 'aug7',\n '7#5': 'aug7',\n 'm7dim5': 'min7dim5',\n '°7': 'min7dim5',\n 'ø7': 'min7dim5',\n 'm7b5': 'min7dim5',\n '7sus': 'dom7sus4',\n '7sus4': 'dom7sus4',\n 'maj7sus': 'maj7sus4',\n '9': 'dom9',\n 'm9': 'min9',\n 'M9': 'maj9',\n '+9': 'aug9',\n '°9': 'dim9',\n 'M6': 'maj6',\n 'm6': 'min6',\n '6': 'dom6',\n 'm/M6': 'min/maj6',\n }\n\n recipes_inv = {v: k for k, v in recipes.items()}\n\n RecipeInfo = namedtuple('RecipeInfo', ('known', 'name', 'inversion', 'full_name'),\n defaults=(False, '', 0, ''))\n\n @staticmethod\n def all(root=None):\n if root is None:\n roots = PitchClass.all()\n elif isinstance(root, (list, set, tuple)):\n roots = root\n elif isinstance(root, PitchClass):\n roots = [root]\n else:\n raise TypeError('Invalid root type: {}'.format(type(root)))\n for root in roots:\n for name in Chord.recipes:\n yield Chord(root, name)\n\n @staticmethod\n def parse(s):\n if isinstance(s, Chord):\n return s\n if '/' in s:\n chord, root = s.split('/')\n chord = Chord.parse(chord)\n root = PitchClass.parse(root)\n inversion = chord.pitches.index(root)\n return chord.invert(inversion)\n\n for suffix in sorted(set(Chord.recipes.keys()) | set(Chord.aliases.keys()), key=lambda x: -len(x)):\n if s.endswith(suffix):\n chord_type = suffix\n return Chord(PitchClass(s[:-len(suffix)]), chord_type)\n\n raise ValueError('Invalid chord: {!r}'.format(root))\n\n def __init__(self, root, chord_type=None):\n \"\"\"\n Construct a chord from either:\n * root (pitch class), chord type;\n * its string representation, e.g. 'C#maj7'.\n\n `chord_type` can be a string (standard recipes, e.g.: min, dim, maj7, aug9, etc...) or a list of intervals.\n\n When using exotic chord recipes, string rendering of chords will not work, and intervals will be displayed.\n \"\"\"\n\n if isinstance(root, str) and chord_type is None:\n c = Chord.parse(root)\n for f in ('root', 'intervals'):\n setattr(self, f, getattr(c, f))\n return\n\n if isinstance(root, str):\n root = PitchClass.parse(root)\n if not isinstance(root, PitchClass):\n raise TypeError('Invalid root type')\n if chord_type is None:\n chord_type = 'maj'\n if isinstance(chord_type, str):\n if chord_type in self.aliases:\n chord_type = self.aliases[chord_type]\n if chord_type not in self.recipes.keys():\n raise ValueError('Invalid chord_type value: {}.'.format(chord_type))\n chord_type = self.recipes[chord_type]\n if not isinstance(chord_type, tuple):\n raise TypeError('Invalid chord_type type: {}.'.format(type(chord_type).__name__))\n if all(isinstance(x, str) for x in chord_type):\n chord_type = tuple(Interval(x) for x in chord_type)\n if not all(isinstance(x, Interval) for x in chord_type):\n raise TypeError('Invalid chord_type element type: {}.'.format(type(chord_type).__name__))\n\n self.root = root\n self.intervals = tuple(sorted(chord_type))\n\n def __lt__(self, other):\n return (self.root, self.intervals) < (other.root, other.intervals)\n\n def __le__(self, other):\n return self == other or self < other\n\n def __repr__(self):\n return 'Chord({!r})'.format(str(self))\n\n def __str__(self):\n return self.recipe.full_name\n\n def __hash__(self):\n return hash((self.root,) + tuple(self.intervals))\n\n def __eq__(self, other):\n return self.root == other.root and self.intervals == other.intervals\n\n def __len__(self):\n return len(self.intervals)\n\n @property\n def recipe(self):\n recipe = getattr(self, '__recipe', None)\n if recipe is None:\n try:\n n, i = next(self.identify_from_intervals(self.intervals))\n s = '{}{}'.format(self.root, n)\n if i != 0:\n s += '/{}'.format((self.root.to_octave(4) + self.intervals[0]).pitch_class)\n recipe = Chord.RecipeInfo(True, n, i, s)\n except StopIteration:\n recipe = Chord.RecipeInfo(False, '', 0, '-'.join(str(i) for i in self.intervals))\n setattr(self, '__recipe', recipe)\n return recipe\n\n @property\n def pitches(self):\n return tuple(n.pitch_class for n in self.notes())\n\n def notes(self, base_octave=4):\n r = self.root.to_octave(base_octave)\n return [r + i for i in self.intervals]\n\n def invert(self, num_times=1):\n if num_times == 0:\n return self\n return Chord(self.root, self.intervals[1:] + (self.intervals[0] + Interval('P8'),)).invert(num_times - 1)\n\n @staticmethod\n def identify_from_intervals(intervals):\n intervals = tuple(sorted(intervals))\n\n def flip(interval):\n if interval.is_compound() or interval == Interval('P8'):\n r = interval.reduce()\n else:\n r = interval + Interval('P8')\n return r\n n = len(intervals)\n for mask in range(2**n):\n new_intervals = tuple(sorted(flip(interval) if mask & 2**i else interval\n for i, interval in enumerate(intervals)))\n k = tuple(str(i) for i in new_intervals)\n if k in Chord.recipes_inv:\n c = Chord(PitchClass('C'), new_intervals)\n for inversion in range(n):\n if c.invert(inversion).intervals == intervals:\n yield Chord.recipes_inv[k], inversion\n\n @staticmethod\n def identify_from_notes(notes):\n notes = tuple(sorted(notes))\n\n n = len(notes)\n for mask in range(2**n):\n new_notes = tuple(sorted(n + Interval('P8' if mask & 2**i else 'P1')\n for i, n in enumerate(notes)))\n intervals_inv = tuple(n - new_notes[0] for n in new_notes)\n for recipe, inv in Chord.identify_from_intervals(intervals_inv):\n for inversion in range(n):\n for root in notes:\n c = Chord(root.pitch_class, recipe).invert(inversion)\n cnotes = tuple(sorted(c.notes()))\n if [n.pitch_class for n in cnotes] == [n.pitch_class for n in notes]:\n yield c\n\n\nclass Scale:\n \"\"\"\n The scale class.\n\n Contains recipes for common scales, and operators for accessing the\n notes of the scale, and for checking if a scale contains specific\n notes or chords.\n \"\"\"\n\n scales = {\n 'major': ('P1', 'M2', 'M3', 'P4', 'P5', 'M6', 'M7'),\n 'natural_minor': ('P1', 'M2', 'm3', 'P4', 'P5', 'm6', 'm7'),\n 'harmonic_minor': ('P1', 'M2', 'm3', 'P4', 'P5', 'm6', 'M7'),\n 'melodic_minor': ('P1', 'M2', 'm3', 'P4', 'P5', 'M6', 'M7'),\n 'major_pentatonic': ('P1', 'M2', 'M3', 'P5', 'M6'),\n 'minor_pentatonic': ('P1', 'm3', 'P4', 'P5', 'm7'),\n # greek modes:\n 'ionian': ('P1', 'M2', 'M3', 'P4', 'P5', 'M6', 'M7'),\n 'dorian': ('P1', 'M2', 'm3', 'P4', 'P5', 'M6', 'm7'),\n 'phrygian': ('P1', 'm2', 'm3', 'P4', 'P5', 'm6', 'm7'),\n 'lydian': ('P1', 'M2', 'M3', 'A4', 'P5', 'M6', 'M7'),\n 'mixolydian': ('P1', 'M2', 'M3', 'P4', 'P5', 'M6', 'm7'),\n 'aeolian': ('P1', 'M2', 'm3', 'P4', 'P5', 'm6', 'm7'),\n 'locrian': ('P1', 'm2', 'm3', 'P4', 'd5', 'm6', 'm7'),\n }\n greek_modes = {\n 1: 'ionian',\n 2: 'dorian',\n 3: 'phrygian',\n 4: 'lydian',\n 5: 'mixolydian',\n 6: 'aeolian',\n 7: 'locrian',\n }\n greek_modes_set = set(greek_modes.values())\n\n @staticmethod\n def all(include_greek_modes=False):\n for root in PitchClass.all():\n for name in Scale.scales:\n if not include_greek_modes and name in Scale.greek_modes_set:\n continue\n yield Scale(root, name)\n\n def __init__(self, root, scale_type):\n self.recipe = None\n\n if isinstance(root, str):\n root = PitchClass(root)\n if not isinstance(root, PitchClass):\n raise TypeError('Invalid root type: {}'.format(type(root).__name__))\n\n if isinstance(scale_type, str):\n if scale_type not in self.scales:\n raise NameError('No such scale: {}'.format(scale_type))\n self.recipe = scale_type\n scale_type = self.scales[scale_type][:]\n if isinstance(scale_type, (list, tuple)):\n if all(isinstance(x, str) for x in scale_type):\n scale_type = tuple(map(Interval, scale_type))\n if not all(isinstance(x, Interval) for x in scale_type):\n raise TypeError('Scale intervals must be all of type str or all of type Interval.')\n\n self.root = root\n self.intervals = scale_type\n\n def __getitem__(self, k):\n if isinstance(k, int):\n try:\n octaves = k // len(self)\n offset = k - octaves * len(self)\n return self.root.to_octave(4 + octaves) + self.intervals[offset]\n except ValueError:\n raise IndexError('Index out of range')\n elif isinstance(k, slice):\n start = k.start or 0\n stop = k.stop or self.max_index\n step = k.step or 1\n return [self[i] for i in range(start, stop, step)]\n else:\n raise TypeError('Scale cannot be indexed by {}.'.format(type(k)))\n\n def __len__(self):\n return len(self.intervals)\n\n def __contains__(self, k):\n if isinstance(k, Note):\n return k.pitch_class in self\n elif isinstance(k, PitchClass):\n return k in self.pitches\n elif isinstance(k, Chord):\n return all(n in self for n in k.pitches)\n elif isinstance(k, (list, set, tuple)):\n return all(x in self for x in k)\n else:\n return False\n\n def __str__(self):\n if self.recipe:\n return '{} {}'.format(self.root, self.recipe)\n else:\n return '{} <{}>'.format(self.root, '-'.join(map(str, self.intervals)))\n\n def __repr__(self):\n if self.recipe:\n return 'Scale({!r}, {!r})'.format(str(self.root), self.recipe)\n else:\n return 'Scale({!r}, {!r})'.format(str(self.root), tuple(map(str, self.intervals)))\n\n def __lt__(self, other):\n return (self.root, self.intervals) < (other.root, other.intervals)\n\n def __le__(self, other):\n return self == other or self < other\n\n def __hash__(self):\n return hash((self.root,) + tuple(self.intervals))\n\n def __eq__(self, other):\n return self.root == other.root and self.intervals == other.intervals\n\n @property\n def pitches(self):\n return tuple(n.pitch_class for n in self[0:len(self)])\n\n def find_similar(self, max_levenshtein_dist=1, include_greek_modes=None):\n if include_greek_modes is None:\n include_greek_modes = self.recipe in Scale.greek_modes_set\n\n for scale in Scale.all(include_greek_modes):\n if scale == self:\n continue\n if len(self) - len(set(scale.pitches) & set(self.pitches)) <= max_levenshtein_dist:\n yield scale\n\n @staticmethod\n def identify_from_notes(notes):\n for scale in Scale.all(True):\n if notes in scale:\n yield scale\n","sub_path":"musthe/musthe.py","file_name":"musthe.py","file_ext":"py","file_size_in_byte":32864,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"43001743","text":"#!/usr/bin/python\n# -*- codding: utf-8 -*-\nimport os\nimport sys\nsys.path.append(os.path.dirname(os.path.abspath(os.path.dirname(__file__))))\nfrom common.execute_command import execute_one_parameter\n\n\n# url : https://awscli.amazonaws.com/v2/documentation/api/latest/reference/signer/get-signing-profile.html\nif __name__ == '__main__':\n \"\"\"\n\tcancel-signing-profile : https://awscli.amazonaws.com/v2/documentation/api/latest/reference/signer/cancel-signing-profile.html\n\tlist-signing-profiles : https://awscli.amazonaws.com/v2/documentation/api/latest/reference/signer/list-signing-profiles.html\n\tput-signing-profile : https://awscli.amazonaws.com/v2/documentation/api/latest/reference/signer/put-signing-profile.html\n \"\"\"\n\n parameter_display_string = \"\"\"\n # profile-name : The name of the target signing profile.\n \"\"\"\n\n add_option_dict = {}\n #######################################################################\n # setting option use\n # ex: add_option_dict[\"setting_matching_parameter\"] = \"--owners\"\n # ex: add_option_dict[\"setting_key\"] = \"owner_id\"\n\n #######################################################################\n # single parameter\n # ex: add_option_dict[\"no_value_parameter_list\"] = \"--single-parameter\"\n\n #######################################################################\n # parameter display string\n add_option_dict[\"parameter_display_string\"] = parameter_display_string\n\n execute_one_parameter(\"signer\", \"get-signing-profile\", \"profile-name\", add_option_dict)","sub_path":"signer_read_1/signing-profile_get.py","file_name":"signing-profile_get.py","file_ext":"py","file_size_in_byte":1532,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"448924212","text":"#! /usr/bin/python\n\nimport json\nimport time\nimport argparse\nimport os\nimport numpy as np\nimport subprocess\nfrom concurrent import futures\n\nimport vigra\nimport nifty\nimport z5py\nimport luigi\n\n\n# TODO multiple threads for ufd ?!\nclass NodeAssignmentTask(luigi.Task):\n path = luigi.Parameter()\n out_key = luigi.Parameter()\n config_path = luigi.Parameter()\n max_jobs = luigi.IntParameter()\n tmp_folder = luigi.Parameter()\n dependency = luigi.TaskParameter()\n # FIXME default does not work; this still needs to be specified\n time_estimate = luigi.IntParameter(default=10)\n run_local = luigi.BoolParameter(default=False)\n\n def requires(self):\n return self.dependency\n\n def run(self):\n from .. import util\n\n # copy the script to the temp folder and replace the shebang\n file_dir = os.path.dirname(os.path.abspath(__file__))\n script_path = os.path.join(self.tmp_folder, 'node_assignment.py')\n util.copy_and_replace(os.path.join(file_dir, 'node_assignment.py'), script_path)\n\n # find the number of blocks\n with open(self.config_path) as f:\n config = json.load(f)\n block_shape = config['block_shape']\n n_threads = config['n_threads']\n\n f = z5py.File(self.path)\n ds = f[self.out_key]\n shape = ds.shape\n blocking = nifty.tools.blocking([0, 0, 0], shape, block_shape)\n n_blocks = blocking.numberOfBlocks\n\n n_jobs = min(n_blocks, self.max_jobs)\n\n # prepare the job\n config_path = os.path.join(self.tmp_folder, 'node_assignment_config.json')\n with open(config_path, 'w') as f:\n json.dump({'n_threads': n_threads}, f)\n # submit the job\n command = '%s %s %i %s' % (script_path, self.tmp_folder, n_jobs, config_path)\n log_file = os.path.join(self.tmp_folder, 'logs', 'log_node_assignment')\n err_file = os.path.join(self.tmp_folder, 'error_logs', 'err_node_assignment.err')\n bsub_command = 'bsub -n %i -J nde_assignment -We %i -o %s -e %s \\'%s\\'' % (n_threads, self.time_estimate,\n log_file, err_file, command)\n if self.run_local:\n subprocess.call([command], shell=True)\n else:\n subprocess.call([bsub_command], shell=True)\n\n # wait till all jobs are finished\n if not self.run_local:\n util.wait_for_jobs('papec')\n\n # check for correct execution\n out_path = self.output().path\n success = os.path.exists(out_path)\n if not success:\n raise RuntimeError(\"Compute node assignment failed\")\n\n def output(self):\n return luigi.LocalTarget(os.path.join(self.tmp_folder, 'component_assignments.n5', 'assignments'))\n\n\ndef compute_node_assignment(tmp_folder, n_jobs, config_path):\n\n from production.util import normalize_and_save_assignments\n t0 = time.time()\n\n with open(config_path) as f:\n n_threads = json.load(f)['n_threads']\n\n with futures.ThreadPoolExecutor(n_threads) as tp:\n tasks = [tp.submit(np.load,\n os.path.join(tmp_folder, 'node_assignments_job%i.npy' % job_id))\n for job_id in range(n_jobs)]\n assignments = [t.result() for t in tasks]\n assignments = np.concatenate([ass for ass in assignments if ass.size > 0],\n axis=0)\n n_labels = int(assignments.max()) + 1\n\n # stitch the segmentation (node level)\n ufd = nifty.ufd.ufd(n_labels)\n ufd.merge(assignments)\n node_labels = ufd.elementLabeling()\n vigra.analysis.relabelConsecutive(node_labels, keep_zeros=True,\n start_label=1, out=node_labels)\n normalize_and_save_assignments(os.path.join(tmp_folder, 'component_assignments.n5'), 'assignments',\n node_labels, n_threads, offset_segment_labels=False)\n\n with open(os.path.join(tmp_folder, 'node_assignment_time.json'), 'w') as f:\n json.dump({'t': time.time() - t0}, f)\n\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser()\n parser.add_argument('tmp_folder', type=str)\n parser.add_argument('n_jobs', type=int)\n parser.add_argument('config_path', type=str)\n args = parser.parse_args()\n compute_node_assignment(args.tmp_folder, args.n_jobs, args.config_path)\n","sub_path":"deprecated/production/components/node_assignment.py","file_name":"node_assignment.py","file_ext":"py","file_size_in_byte":4394,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"313773908","text":"\"\"\"\nMetal vs non-metal classification for inorganic crystals from Materials Project.\n\"\"\"\nimport os\nimport logging\nimport deepchem\nfrom deepchem.feat import MaterialStructureFeaturizer\nfrom deepchem.splits.splitters import Splitter\nfrom deepchem.molnet.defaults import get_defaults\n\nfrom typing import List, Tuple, Dict, Optional, Any\n\nlogger = logging.getLogger(__name__)\n\nDEFAULT_DIR = deepchem.utils.data_utils.get_data_dir()\nMPMETAL_URL = 'https://deepchemdata.s3-us-west-1.amazonaws.com/datasets/mp_is_metal.tar.gz'\n\n# dict of accepted featurizers for this dataset\n# modify the returned dicts for your dataset\nDEFAULT_FEATURIZERS = get_defaults(\"feat\")\n\n# Names of supported featurizers\nfeaturizers = [\n 'CGCNNFeaturizer',\n 'SineCoulombMatrix',\n]\nDEFAULT_FEATURIZERS = {k: DEFAULT_FEATURIZERS[k] for k in featurizers}\n\n# dict of accepted transformers\nDEFAULT_TRANSFORMERS = get_defaults(\"trans\")\n\n# dict of accepted splitters\nDEFAULT_SPLITTERS = get_defaults(\"splits\")\n\n# names of supported splitters\nsplitters = ['RandomSplitter']\nDEFAULT_SPLITTERS = {k: DEFAULT_SPLITTERS[k] for k in splitters}\n\n\ndef load_mp_metallicity(\n featurizer=DEFAULT_FEATURIZERS['SineCoulombMatrix'],\n transformers: List = [DEFAULT_TRANSFORMERS['NormalizationTransformer']],\n splitter=DEFAULT_SPLITTERS['RandomSplitter'],\n reload: bool = True,\n data_dir: Optional[str] = None,\n save_dir: Optional[str] = None,\n featurizer_kwargs: Dict[str, Any] = {},\n splitter_kwargs: Dict[str, Any] = {\n 'frac_train': 0.8,\n 'frac_valid': 0.1,\n 'frac_test': 0.1\n },\n transformer_kwargs: Dict[str, Dict[str, Any]] = {\n 'NormalizationTransformer': {\n 'transform_X': True\n }\n },\n **kwargs) -> Tuple[List, Optional[Tuple], List]:\n \"\"\"Load mp formation energy dataset.\n\n Contains 106113 inorganic crystal structures from the Materials\n Project database labeled as metals or nonmetals. In benchmark\n studies, random forest models achieved a mean ROC-AUC of\n 0.9 during five-folded nested cross validation on this\n dataset.\n\n For more details on the dataset see [1]_. For more details\n on previous benchmarks for this dataset, see [2]_.\n\n Parameters\n ----------\n featurizer : MaterialStructureFeaturizer (default SineCoulombMatrix)\n A featurizer that inherits from deepchem.feat.Featurizer.\n transformers : List[Transformer]\n A transformer that inherits from deepchem.trans.Transformer.\n splitter : Splitter (default RandomSplitter)\n A splitter that inherits from deepchem.splits.splitters.Splitter.\n reload : bool (default True)\n Try to reload dataset from disk if already downloaded. Save to disk\n after featurizing.\n data_dir : str, optional (default None)\n Path to datasets.\n save_dir : str, optional (default None)\n Path to featurized datasets.\n featurizer_kwargs : Dict[str, Any]\n Specify parameters to featurizer, e.g. {\"size\": 1024}\n splitter_kwargs : Dict[str, Any]\n Specify parameters to splitter, e.g. {\"seed\": 42}\n transformer_kwargs : dict\n Maps transformer names to constructor arguments, e.g.\n {\"BalancingTransformer\": {\"transform_x\":True, \"transform_y\":False}}\n **kwargs : additional optional arguments.\n\n Returns\n -------\n tasks, datasets, transformers : tuple\n tasks : list\n Column names corresponding to machine learning target variables.\n datasets : tuple\n train, validation, test splits of data as\n ``deepchem.data.datasets.Dataset`` instances.\n transformers : list\n ``deepchem.trans.transformers.Transformer`` instances applied\n to dataset.\n\n References\n ----------\n .. [1] A. Jain*, S.P. Ong*, et al. (*=equal contributions) The Materials Project:\n A materials genome approach to accelerating materials innovation APL Materials,\n 2013, 1(1), 011002. doi:10.1063/1.4812323 (2013).\n .. [2] Dunn, A. et al. \"Benchmarking Materials Property Prediction Methods: The Matbench\n Test Set and Automatminer Reference Algorithm.\" https://arxiv.org/abs/2005.00707 (2020)\n\n Examples\n --------\n >> import deepchem as dc\n >> tasks, datasets, transformers = dc.molnet.load_mp_metallicity(reload=False)\n >> train_dataset, val_dataset, test_dataset = datasets\n >> n_tasks = len(tasks)\n >> n_features = train_dataset.get_data_shape()[0]\n >> model = dc.models.MultitaskRegressor(n_tasks, n_features)\n\n \"\"\"\n\n # Featurize\n logger.info(\"About to featurize mp metallicity dataset.\")\n my_tasks = ['is_metal'] # machine learning targets\n\n # Get DeepChem data directory if needed\n if data_dir is None:\n data_dir = DEFAULT_DIR\n if save_dir is None:\n save_dir = DEFAULT_DIR\n\n if issubclass(featurizer, MaterialStructureFeaturizer):\n featurizer = featurizer(**featurizer_kwargs)\n else:\n raise TypeError(\n \"featurizer must be a subclass of MaterialStructureFeaturizer.\")\n\n if issubclass(splitter, Splitter):\n splitter = splitter()\n else:\n raise TypeError(\"splitter must be a subclass of Splitter.\")\n\n # Reload from disk\n if reload:\n featurizer_name = str(featurizer.__class__.__name__)\n splitter_name = str(splitter.__class__.__name__)\n save_folder = os.path.join(save_dir, \"mp-metallicity-featurized\",\n featurizer_name, splitter_name)\n\n loaded, all_dataset, transformers = deepchem.utils.data_utils.load_dataset_from_disk(\n save_folder)\n if loaded:\n return my_tasks, all_dataset, transformers\n\n # First type of supported featurizers\n supported_featurizers: List[str] = [\n 'CGCNNFeaturizer',\n 'SineCoulombMatrix',\n ]\n\n # Load .tar.gz file\n if featurizer.__class__.__name__ in supported_featurizers:\n dataset_file = os.path.join(data_dir, 'mp_is_metal.json')\n\n if not os.path.exists(dataset_file):\n targz_file = os.path.join(data_dir, 'mp_is_metal.tar.gz')\n if not os.path.exists(targz_file):\n deepchem.utils.data_utils.download_url(\n url=MPMETAL_URL, dest_dir=data_dir)\n deepchem.utils.data_utils.untargz_file(\n os.path.join(data_dir, 'mp_is_metal.tar.gz'), data_dir)\n\n # Changer loader to match featurizer and data file type\n loader = deepchem.data.JsonLoader(\n tasks=my_tasks,\n feature_field=\"structure\",\n label_field=\"is_metal\",\n featurizer=featurizer)\n\n # Featurize dataset\n dataset = loader.create_dataset(dataset_file)\n\n train_dataset, valid_dataset, test_dataset = splitter.train_valid_test_split(\n dataset, **splitter_kwargs)\n\n # Initialize transformers\n transformers = [\n DEFAULT_TRANSFORMERS[t](dataset=dataset, **transformer_kwargs[t])\n if isinstance(t, str) else t(\n dataset=dataset, **transformer_kwargs[str(t.__name__)])\n for t in transformers\n ]\n\n for transformer in transformers:\n train_dataset = transformer.transform(train_dataset)\n valid_dataset = transformer.transform(valid_dataset)\n test_dataset = transformer.transform(test_dataset)\n\n if reload: # save to disk\n deepchem.utils.data_utils.save_dataset_to_disk(\n save_folder, train_dataset, valid_dataset, test_dataset, transformers)\n\n return my_tasks, (train_dataset, valid_dataset, test_dataset), transformers\n","sub_path":"deepchem/molnet/load_function/material_datasets/load_mp_metallicity.py","file_name":"load_mp_metallicity.py","file_ext":"py","file_size_in_byte":7186,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"333122884","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Thu Jul 25 14:35:29 2019\r\n\r\n@author: kim.montalibet\r\n\"\"\"\r\n\r\n\r\n\r\n### to do \r\n# rajouter les relations quand tag poste \r\n# si on ne trouve pas l'entité avec le tag -> le rajouter sur le tag lui meme\r\n\r\n\r\n##### TO DO : remplace \"_\" par une regex\r\n#regex_nul = r\"_(\\|_){0,5}\"\r\n#if re.match(regex_nul, \"_|_|_|_\"): \r\n# print(\"yes\")\r\n\r\n\r\nimport configs\r\ndir_path = configs.dir_path\r\n\r\nimport os \r\nfrom WebannoAnnotationTools.annotated_doc_class import annotated_doc\r\n\r\n\r\n# to decide \r\nfrom WebannoAnnotationTools.join_entities_with_relations import join_relations \r\n\r\n# spefific to my project -> to put in Annotation and not in Webanno annotation tools \r\nfrom WebannoAnnotationTools.replace_tag_by_relation import replace_tag_by_relation\r\nfrom WebannoAnnotationTools.add_relation_unites import add_relation_valeur_unite\r\nfrom WebannoAnnotationTools.reconcile_info_structure import add_structure_to_all_tokens\r\n\r\n\r\n#from WebannoAnnotationTools.token_to_chunk_df import token_to_chunk_df\r\nimport pandas as pd\r\nimport numpy as np \r\nfrom typing import List, Tuple\r\nimport re\r\nfrom Annotation.text_to_tsv.cleaning_and_text_processing import unlist_df\r\n\r\n\r\nlist_files = os.listdir(dir_path + \"gold_annotation/gold_dataset2/\" )\r\nfile = list_files[0]\r\n#file = \"1594890.tsv\"\r\n#file = \"\"\r\n\r\n\r\n\r\nregex_chiffre = r\"([^\\d]*)(\\d+[\\.\\d+]{0,1})([^\\d]*)\"\r\nget_nb_from_string = lambda x: re.sub(regex_chiffre, r\"\\2\", x)\r\n\r\n\r\n\r\n\r\n# load tsv file and convert into annotated doc class \r\nanno_doc = annotated_doc(dir_path + \"gold_annotation/gold_dataset2/\"+ file)\r\ntoken_df = anno_doc.token_dataframe\r\n\r\n\r\n## replace the double tag by relation for valeur / poste\r\nlayer = \"Evaluation\"\r\nlayer_relation = \"Relation_evaluation\"\r\nsource_var = \"A_Valeur\"\r\ntarget_var = \"liste_postes\"\r\nrelation_var = \"BT_webanno.custom.Evaluation\"\r\nwindow = 30\r\nanno_doc.modify_token_dataframe(lambda x: replace_tag_by_relation(x, layer, layer_relation, \r\n source_var, target_var, relation_var))\r\n\r\n## replace the double tag by relation for valeur\r\n\r\ntoken_df.Evaluation.columns\r\nlayer = \"Evaluation\"\r\nlayer_relation = \"Relation_evaluation\"\r\nsource_var = \"A_Valeur\"\r\ntarget_var = \"liste_postes\"\r\nrelation_var = \"BT_webanno.custom.Evaluation\"\r\nwindow = 30\r\nanno_doc.modify_token_dataframe(lambda x: replace_tag_by_relation(x, layer, layer_relation, \r\n source_var, target_var, relation_var))\r\n\r\ntoken_df = anno_doc.token_dataframe\r\n\r\n## replace the double tag by relation for autre sous partie\r\n\r\ntoken_df.Evaluation.columns\r\nlayer = \"Evaluation\"\r\nlayer_relation = \"Relation_evaluation\"\r\nsource_var = \"A_Valeur\"\r\ntarget_var = \"C_autre_sous_partie\"\r\nrelation_var = \"BT_webanno.custom.Evaluation\"\r\nwindow = 30\r\nanno_doc.modify_token_dataframe(lambda x: replace_tag_by_relation(x, layer, layer_relation, \r\n source_var, target_var, relation_var))\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\nchunk_df = anno_doc.chunk_df()\r\n\r\nvar_unite = (\"Evaluation\", \"type_information\")\r\nvar_valeur = (\"Evaluation\", \"A_Valeur\")\r\nvar_relation = (\"Relation_evaluation\", \"BT_webanno.custom.Evaluation\")\r\n\r\n\r\nchunk_df = add_relation_valeur_unite(chunk_df, var_unite, var_valeur, var_relation)\r\n# do the same for unité expertise \r\nvar_unite = (\"Evaluation\", \"A_Unite_expertise\")\r\nchunk_df = add_relation_valeur_unite(chunk_df, var_unite, var_valeur, var_relation)\r\n\r\n\r\n\r\n\r\n \r\npartie_var = (\"Structure\", \"zonage_macro\")\r\nsous_partie_var = (\"Structure\", \"sous_partie\")\r\nvictime_var = (\"Structure\", \"victime_concernee\") \r\n \r\nchunk_df = add_structure_to_all_tokens(chunk_df, partie_var, sous_partie_var, victime_var) \r\n\r\naction_deboutee = chunk_df[chunk_df[(\"Evaluation\", \"A_Valeur\")]==\"action_deboutee\"]\r\naction_deboutee = action_deboutee[[(\"Structure\", \"sous_partie_all\"), \r\n (\"Structure\", \"victime_all\"),\r\n (\"Evaluation\", \"A_Valeur\")]]\r\naction_deboutee.columns = action_deboutee.columns.droplevel()\r\naction_deboutee = action_deboutee.rename(columns = {\"A_Valeur\": \"valeur_tag\"})\r\n\r\n### test with dates \r\ntoken_df.Relation_structure.columns\r\ntarget_variable = (\"Structure\", \"E_evenement\")\r\nsource_variable = (\"Structure\", \"C_Date\")\r\ntarget_variable_alias = \"evenement\"\r\nsource_variable_alias = \"date\"\r\n\r\nid_relation_variable = (\"Relation_structure\", \"BT_webanno.custom.Structure\")\r\nrelation_variable = (\"Relation_structure\", \"relation_date\") \r\n\r\nlayer = target_variable[0]\r\nlayer_relation = id_relation_variable[0]\r\n\r\n\r\n\r\ndf_chrono = join_relations(chunk_df, target_variable, source_variable, \r\n id_relation_variable, \r\n relation_variable, \r\n target_variable_alias, \r\n source_variable_alias) \r\n\r\n\r\n#df_copy = chunk_df.copy(deep = True)\r\n#sub_df = df_copy[[\"id_features\", layer, layer_relation]]\r\n\r\n\r\n\r\n#### test with amounts and postes \r\n\r\ntarget_variable = (\"Evaluation\", \"liste_postes\")\r\nsource_variable = (\"Evaluation\", \"A_Valeur\")\r\nlist_other_var = [(\"Structure\", \"partie_all\"), \r\n (\"Structure\", \"sous_partie_all\"), \r\n (\"Structure\", \"victime_all\")]\r\n\r\ntarget_variable_alias = \"poste\"\r\nsource_variable_alias = \"valeur\"\r\nid_relation_variable = (\"Relation_evaluation\", \"BT_webanno.custom.Evaluation\")\r\nrelation_variable = (\"Relation_evaluation\", \"relation_evaluation\")\r\n\r\n\r\n\r\ndf_montant = join_relations(chunk_df, target_variable, source_variable, \r\n id_relation_variable, \r\n relation_variable, \r\n target_variable_alias, \r\n source_variable_alias, \r\n list_other_var) \r\n\r\n\r\n#df_montant = pd.merge(df_montant, action_deboutee, on = \"sous_partie_all\", how = \"left\")\r\n\r\ndf_append = df_montant[['poste_id', 'poste_token', 'poste_tag']]\r\ndf_append = df_append.drop_duplicates(subset = ['poste_tag'])\r\naction_deboutee[\"merge\"] = 1\r\ndf_append[\"merge\"] = 1\r\ndf_append = pd.merge(df_append, action_deboutee, on = \"merge\")\r\ndf_append.drop([\"merge\"], axis = 1, inplace = True)\r\n\r\ndf_montant = pd.concat([df_montant, df_append], axis = 0, sort = False)\r\n\r\n\r\n#### test with amounts and autre sous partie \r\n\r\ntoken_df.Evaluation.columns\r\ntarget_variable = (\"Evaluation\", \"C_autre_sous_partie\")\r\nsource_variable = (\"Evaluation\", \"A_Valeur\")\r\ntarget_variable_alias = \"autre_sp\"\r\nsource_variable_alias = \"valeur\"\r\nid_relation_variable = (\"Relation_evaluation\", \"BT_webanno.custom.Evaluation\")\r\nrelation_variable = (\"Relation_evaluation\", \"relation_evaluation\")\r\n\r\ndf_montant_sp = join_relations(chunk_df, target_variable, source_variable, \r\n id_relation_variable, \r\n relation_variable, \r\n target_variable_alias, \r\n source_variable_alias) \r\n\r\n\r\n\r\n\r\n#### test with amounts and unite\r\n\r\n\r\ntarget_variable = (\"Evaluation\", \"A_Valeur\")\r\ntarget_variable_alias = \"valeur\"\r\nsource_variable = (\"Evaluation\", \"type_information\")\r\nsource_variable_alias = \"unite\"\r\nid_relation_variable = (\"Relation_evaluation\", \"BT_webanno.custom.Evaluation\")\r\nrelation_variable = (\"Relation_evaluation\", \"relation_evaluation\")\r\n\r\ndf_montant_unite = join_relations(chunk_df, target_variable, source_variable, \r\n id_relation_variable, \r\n relation_variable, \r\n target_variable_alias, \r\n source_variable_alias) \r\n\r\n\r\n\r\ntarget_variable = (\"Evaluation\", \"A_Valeur\")\r\ntarget_variable_alias = \"valeur\"\r\nsource_variable = (\"Evaluation\", \"A_Unite_expertise\")\r\nsource_variable_alias = \"unite_exp\"\r\nid_relation_variable = (\"Relation_evaluation\", \"BT_webanno.custom.Evaluation\")\r\nrelation_variable = (\"Relation_evaluation\", \"relation_evaluation\")\r\n\r\ndf_montant_unite_exp = join_relations(chunk_df, target_variable, source_variable, \r\n id_relation_variable, \r\n relation_variable, \r\n target_variable_alias, \r\n source_variable_alias) \r\n\r\n\r\n\r\n\r\n#### test with amounts and victime concernée \r\n\r\n\r\ntarget_variable = (\"Evaluation\", \"E_victime_concernee\")\r\ntarget_variable_alias = \"victime_evaluation\"\r\nsource_variable = (\"Evaluation\", \"A_Valeur\")\r\nsource_variable_alias = \"valeur\"\r\nid_relation_variable = (\"Relation_evaluation\", \"BT_webanno.custom.Evaluation\")\r\nrelation_variable = (\"Relation_evaluation\", \"relation_evaluation\")\r\n\r\ndf_montant_victime = join_relations(chunk_df, target_variable, source_variable, \r\n id_relation_variable, \r\n relation_variable, \r\n target_variable_alias, \r\n source_variable_alias) \r\n\r\n\r\n\r\ntarget_variable = (\"Evaluation\", \"A_Valeur\")\r\ntarget_variable_alias = \"valeur\"\r\nsource_variable = (\"Evaluation\", \"A_Unite_expertise\")\r\nsource_variable_alias = \"unite_exp\"\r\nid_relation_variable = (\"Relation_evaluation\", \"BT_webanno.custom.Evaluation\")\r\nrelation_variable = (\"Relation_evaluation\", \"relation_evaluation\")\r\n\r\ndf_montant_unite_exp = join_relations(chunk_df, target_variable, source_variable, \r\n id_relation_variable, \r\n relation_variable, \r\n target_variable_alias, \r\n source_variable_alias) \r\n\r\n\r\n\r\n\r\n\r\n### join the amount variable \r\n\r\ndf_res = pd.merge(df_montant, df_montant_unite, \r\n on = [\"valeur_id\", \"valeur_token\", \"valeur_tag\"], \r\n how = \"left\")\r\n\r\ndf_res = pd.merge(df_res, df_montant_unite_exp, \r\n on = [\"valeur_id\", \"valeur_token\", \"valeur_tag\"], \r\n how = \"left\")\r\n\r\ndf_res = pd.merge(df_res, df_montant_sp, \r\n on = [\"valeur_id\", \"valeur_token\", \"valeur_tag\"], \r\n how = \"left\")\r\n\r\n\r\n\r\ndf_res = pd.merge(df_res, df_montant_victime, \r\n on = [\"valeur_id\", \"valeur_token\", \"valeur_tag\"], \r\n how = \"left\")\r\n\r\n\r\n\r\n\r\n# reconcil sous partie and autre sous partie \r\ndf_res = df_res.applymap(lambda x: np.nan if x==\"_\" else x)\r\ndf_res[\"sous_partie_rec\"] = df_res.apply(lambda x: \r\n x[\"autre_sp_tag\"] if pd.isnull(x[\"autre_sp_tag\"])==False else x[\"sous_partie_all\"], axis = 1)\r\n\r\n \r\n# reconcil victime structure and victime evaluation \r\ndf_res[\"victime_rec\"] = df_res.apply(lambda x: \r\n x[\"victime_evaluation_tag\"] if pd.isnull(x[\"victime_evaluation_tag\"])==False else x[\"victime_all\"], axis = 1)\r\n \r\ndf_res[\"victime_rec\"] = df_res[\"victime_rec\"].fillna(\"victime_1\") \r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n# replace demande deboutée par 0 and valeur nulle par 0 \r\nset(df_res.valeur_tag)\r\n#mapping_valeur = {\"demande_deboutee\": 0, \"valeur_nulle\": 0}\r\ndf_res[\"valeur_token\"] = df_res.apply(lambda x: \r\n \"0\" if x[\"valeur_tag\"] in [\"demande_deboutee\", \"valeur_nulle\", \"action_deboutee\"] \r\n else (-1 if x[\"valeur_tag\"]==\"confirmation_1ere_instance\" else x[\"valeur_token\"]),\r\n axis = 1)\r\n\r\ndf_res[\"unite_exp_tag\"] = df_res.apply(lambda x: \r\n \"echelle_1_7\" if \"/7\" in x[\"valeur_token\"] else x[\"unite_exp_tag\"], \r\n axis = 1)\r\n \r\ndf_res[\"valeur_token\"] = df_res[\"valeur_token\"].map(lambda x: x.replace('/7', \"\"))\r\n\r\n\r\n\r\n # to do : extract number only when there are number + letters \r\n#df_res[\"valeur_token\"] = df_res[\"valeur_token\"].apply(lambda x: re.search(r\"\\d+[,\\d+]{0,1}\", ))\r\n\r\n\r\n\r\n# fill missing unite with \"description\" when valeur == description else with euros \r\n\r\ndf_res[\"unite_exp_tag\"]= df_res.apply(lambda x: \r\n \"description\" if (x['valeur_tag']==\"description\")\\\r\n else x[\"unite_exp_tag\"], axis = 1)\r\n\r\ndf_res[\"unite_tag\"]= df_res.apply(lambda x: \r\n \"euros\" if ((pd.isnull(x[\"unite_tag\"])==True) and (pd.isnull(x[\"unite_exp_tag\"])==True))\\\r\n else x[\"unite_tag\"], axis = 1)\r\n\r\n\r\n### filter and reshape df res in order to have : one row par poste de préjudice, \r\n# avec les montants en euros uniquement \r\n\r\ndf_euro = df_res[df_res['unite_tag']==\"euros\"]\r\ndf_euro[\"valeur_token\"] = df_euro[\"valeur_token\"].map(lambda x: x.replace(',', \".\") if type(x)==str else x)\r\ndf_euro[\"valeur_token\"] = df_euro[\"valeur_token\"].map(lambda x: re.sub(regex_chiffre, r\"\\2\", x))\r\ndf_euro[\"valeur_token\"] = df_euro[\"valeur_token\"].astype(float)\r\n \r\ndf_euro = df_euro[[\"poste_tag\", \"valeur_token\", \"sous_partie_rec\", \"victime_rec\"]]\r\nprint(len(df_euro))\r\ndf_euro = df_euro.drop_duplicates()\r\nprint(len(df_euro))\r\n\r\n#### TO DO : check if there are some inconsistencies here \r\n\r\n\r\n\r\n## reshape df euro in order to have one row per poste (pivot table)\r\n\r\ndf_pv = pd.pivot_table(df_euro, values='valeur_token', index=['poste_tag', \"victime_rec\"],\r\n columns=['sous_partie_rec'], \r\n aggfunc=\"first\").reset_index(drop = False)\r\n\r\n\r\n\r\n## create table with expertise \r\ndf_exp = df_res[df_res['unite_exp_tag'].isin([\"echelle_1_7\", \"pourcentage\"])]\r\ndf_exp[\"valeur_token\"] = df_exp[\"valeur_token\"].map(get_nb_from_string)\r\ndf_exp[\"valeur_token\"] = df_exp[\"valeur_token\"].map(lambda x: re.sub(regex_chiffre, r\"\\2\", x))\r\ndf_exp[\"valeur_token\"] = df_exp[\"valeur_token\"].astype(float)\r\n\r\n# si plusieurs valeurs d'expertise, on retient la dernière \r\n# à modifier plus tard et créer une colonne avec une liste / un dico avec \r\n# les différentes valeurs \r\ndf_exp = df_exp[[\"poste_tag\", \"valeur_token\", \"valeur_tag\", \r\n \"unite_exp_tag\", \"valeur_id\", \"victime_rec\"]]\r\ndf_exp = df_exp.drop_duplicates()\r\ndf_exp[\"position\"] = df_exp[\"valeur_id\"].map(lambda x: \r\n int(x.split(\"-\")[0])*1000 + int(x.split(\"-\")[1]))\r\ndf_exp = df_exp.sort_values(by = \"position\", ascending = False)\r\ndf_exp = df_exp.drop_duplicates(subset = [\"poste_tag\", \"victime_rec\"], keep = \"first\")\r\ndf_exp = df_exp.drop([\"valeur_id\", \"position\", \"valeur_tag\"], axis = 1)\r\ndf_exp = df_exp.rename(columns = {\"valeur_token\": \"cotation\"})\r\n\r\n\r\n## create table with description \r\ndf_desc = df_res[df_res['unite_exp_tag'].isin([\"description\"])]\r\ndf_desc = df_desc[[\"poste_tag\", \"valeur_token\", \"victime_rec\"]]\r\ndf_desc = df_desc.drop_duplicates(subset = [\"poste_tag\", \"victime_rec\"], keep = \"first\")\r\ndf_desc = df_desc.rename(columns = {\"valeur_token\": \"description_expertise\"})\r\n\r\n\r\n\r\n\r\n# join df_pv and df_exp \r\ndf_all = pd.merge(df_pv, df_exp, on = [\"poste_tag\", \"victime_rec\"], how = \"left\")\r\ndf_all = pd.merge(df_all, df_desc, on = [\"poste_tag\", \"victime_rec\"], how = \"left\")\r\n\r\n\r\n \r\n################################################################################\r\n#### infos victimes \r\n################################################################################\r\n\r\ndf_vict = chunk_df[[\"Victimes\", \"id_features\"]]\r\ndf_vict.columns = df_vict.columns.droplevel()\r\ndf_vict = df_vict.rename(columns = {'A_id_victime': \"id\", 'B_partie_proces': \"partie_proces\", \r\n 'D_date_naissance': \"date_naissance\",\r\n 'H_etat_anterieur': \"etat_anterieur\", 'Sexe_victime': \"genre\", \r\n 'age_victime': \"age\", 'profession_victime': \"professsion\"})\r\n\r\n\r\ndf_vict[\"filter\"] = df_vict.apply(lambda x : 0 if ((x[\"id\"]==\"_\") and (x[\"partie_proces\"]!=\"_\")) else 1, axis = 1)\r\ndf_vict = df_vict[df_vict[\"filter\"] ==1]\r\ndf_vict.drop([\"filter\"], axis = 1, inplace = True)\r\n\r\n\r\ndf_vict[\"id\"] = df_vict[\"id\"].apply(lambda x: x if x!=\"_\" else \"victime_1\")\r\n\r\ndef get_filled_fields(row, list_col): \r\n list_val = [(x, row[x], row[\"token_joined\"]) for x in list_col if row[x]!=\"_\"]\r\n return list_val\r\n\r\ncol_list = ['partie_proces', 'date_naissance', 'etat_anterieur', 'genre',\r\n 'age', 'autre_role_litige', 'deces', 'lien_parente_vind',\r\n 'partiesducorps', 'professsion']\r\n\r\ndf_vict[\"col_value_list\"] = df_vict.apply(lambda x: get_filled_fields(x, col_list), axis = 1)\r\ndf_vict = df_vict[df_vict.col_value_list.apply(len) >0]\r\n\r\ndf2 = unlist_df(df_vict, \"col_value_list\", [\"id\"])\r\ndf2[\"variable\"] = df2[\"col_value_list\"].apply(lambda x : x[0])\r\ndf2[\"tag\"] = df2[\"col_value_list\"].apply(lambda x : x[1])\r\ndf2[\"token\"] = df2[\"col_value_list\"].apply(lambda x : x[2])\r\n\r\ndf2.drop([\"col_value_list\"], axis = 1, inplace = True)\r\n\r\n\r\n\r\n## pour les valeurs tokens sans unités, si /7 l'enlever et mettre l'unité en échelle 1_7\r\n### pour les valeurs qui ne sont pas des chiffres: faire un script qui rajoute les unités \r\n\r\n\r\n# valeur nulle \r\n\r\n# rajouter : la victime concernée, perte de chance, part de resp\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n# rajouter autre sous partie \r\n\r\n# rajouter sous partie \r\n\r\n\r\n# retraiter les valeurs sans les liens \r\n # questions: fait-on \r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n### here we do not take into account the desambiguation id\r\n# to imporve: \r\n # - pb in the processing of the token to chunk df: we create desamb id \r\n # for single token in order to group by :\r\n # - maybe transform these after the group by in the function in order to replace them with 0 \r\n # (replace the desamb greater than 500 by 0)\r\n \r\n","sub_path":"tests/test_process_tsv.py","file_name":"test_process_tsv.py","file_ext":"py","file_size_in_byte":16863,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"325415461","text":"\"\"\"\n=============\nEasy ensemble\n=============\n\nAn illustration of the easy ensemble method.\n\n\"\"\"\n\n# Authors: Christos Aridas\n# Guillaume Lemaitre \n# License: MIT\n\nimport matplotlib.pyplot as plt\nfrom sklearn.datasets import make_classification\nfrom sklearn.decomposition import PCA\n\nfrom imblearn.ensemble import EasyEnsemble\n\nprint(__doc__)\n\n# Generate the dataset\nX, y = make_classification(n_classes=2, class_sep=2, weights=[0.3, 0.7],\n n_informative=3, n_redundant=1, flip_y=0,\n n_features=20, n_clusters_per_class=1,\n n_samples=100, random_state=10)\n\n# Instanciate a PCA object for the sake of easy visualisation\npca = PCA(n_components=2)\n# Fit and transform x to visualise inside a 2D feature space\nX_vis = pca.fit_transform(X)\n\n# Apply Easy Ensemble\nee = EasyEnsemble(n_subsets=3)\nX_resampled, y_resampled = ee.fit_resample(X, y)\nX_res_vis = []\nfor X_res in X_resampled:\n X_res_vis.append(pca.transform(X_res))\n\n# Two subplots, unpack the axes array immediately\nf, (ax1, ax2) = plt.subplots(1, 2)\n\nax1.scatter(X_vis[y == 0, 0], X_vis[y == 0, 1], label=\"Class #0\", alpha=0.5)\nax1.scatter(X_vis[y == 1, 0], X_vis[y == 1, 1], label=\"Class #1\", alpha=0.5)\nax1.set_title('Original set')\n\nax2.scatter(X_vis[y == 0, 0], X_vis[y == 0, 1], label=\"Class #0\", alpha=0.5)\nfor iy, e in enumerate(X_res_vis):\n ax2.scatter(e[y_resampled[iy] == 1, 0], e[y_resampled[iy] == 1, 1],\n label=\"Class #1 - set #{}\".format(iy), alpha=0.5)\nax2.set_title('Easy ensemble')\n\n# make nice plotting\nfor ax in (ax1, ax2):\n ax.spines['top'].set_visible(False)\n ax.spines['right'].set_visible(False)\n ax.get_xaxis().tick_bottom()\n ax.get_yaxis().tick_left()\n ax.spines['left'].set_position(('outward', 10))\n ax.spines['bottom'].set_position(('outward', 10))\n ax.set_xlim([-6, 8])\n ax.set_ylim([-6, 6])\n ax.legend()\n\nplt.tight_layout()\nplt.show()\n","sub_path":"examples/ensemble/plot_easy_ensemble.py","file_name":"plot_easy_ensemble.py","file_ext":"py","file_size_in_byte":1978,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"521957893","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Mon Sep 11 21:19:30 2017\n\n@author: Harish\n\"\"\"\n \nmonth = 0\n#print('month',month)\n\nfor month in range(0,12):\n rem_balance = balance - monthlyPaymentRate*balance\n interest = rem_balance*(annualInterestRate/12.0)\n balance = rem_balance+interest\n #print(round(balance,2))\n #print(rem_balance, month)\n \n\nprint('Remaining balance:'+str(round(balance,2)))","sub_path":"Problem Set 2/problem1.py","file_name":"problem1.py","file_ext":"py","file_size_in_byte":434,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"42802024","text":"# --------------------------------------------------------------------------\n# Copyright (c) Microsoft Corporation. All rights reserved.\n# Licensed under the MIT License. See License.txt in the project root for\n# license information.\n# --------------------------------------------------------------------------\n\"\"\"\nFILE: sample_publish_events_using_cloud_events_1.0_schema.py\nDESCRIPTION:\n These samples demonstrate creating a list of CloudEvents and sending then as a list.\nUSAGE:\n python sample_publish_events_using_cloud_events_1.0_schema.py\n Set the environment variables with your own values before running the sample:\n 1) EVENTGRID_CLOUD_EVENT_TOPIC_KEY - The access key of your eventgrid account.\n 2) EVENTGRID_CLOUD_EVENT_TOPIC_ENDPOINT - The topic hostname. Typically it exists in the format\n \"https://..eventgrid.azure.net/api/events\".\n\"\"\"\n# [START publish_cloud_event_to_topic]\nimport os\nfrom azure.eventgrid import EventGridPublisherClient\nfrom azure.core.credentials import AzureKeyCredential\nfrom azure.core.messaging import CloudEvent\n\ntopic_key = os.environ[\"EVENTGRID_CLOUD_EVENT_TOPIC_KEY\"]\nendpoint = os.environ[\"EVENTGRID_CLOUD_EVENT_TOPIC_ENDPOINT\"]\n\ncredential = AzureKeyCredential(topic_key)\nclient = EventGridPublisherClient(endpoint, credential)\n\nclient.send([\n CloudEvent(\n type=\"Contoso.Items.ItemReceived\",\n source=\"/contoso/items\",\n data={\n \"itemSku\": \"Contoso Item SKU #1\"\n },\n subject=\"Door1\"\n )\n])\n# [END publish_cloud_event_to_topic]\n","sub_path":"sdk/eventgrid/azure-eventgrid/samples/sync_samples/sample_publish_events_using_cloud_events_1.0_schema.py","file_name":"sample_publish_events_using_cloud_events_1.0_schema.py","file_ext":"py","file_size_in_byte":1567,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"596352893","text":"\"\"\"This script provides necessary rda-base upgrade operations:\nCurrently it handles building clusterxconf from cluster.conf\n\"\"\"\n\nimport logging\nimport yaml\nimport re\nimport commands\nimport socket\nimport util\nimport os.path\nimport cluster\n\ndef _create_clusterx_skeleton():\n \"\"\"Create a basic clusterx.conf, with some values predefined.\n It returns a python object representing clusterx.conf\n \"\"\"\n clusterx_skeleton = \"\"\"%YAML 1.1\n---\nsystem:\n production_mode: true\n ha_mode: failoverd\ncluster:\nhost:\n...\n\"\"\"\n if os.path.exists(cluster.cluster_conf):\n with open(cluster.cluster_conf, 'r') as f:\n clusterx_skeleton = f.read()\n conf_obj = yaml.load(clusterx_skeleton)\n conf_obj['cluster'] = []\n conf_obj['host'] = {}\n return conf_obj\n\ndef _generate_node(conf_obj):\n \"\"\"Generate 'cluster' section in clusterx.conf\"\"\"\n nodes = commands.getoutput('grep ^node /cluster/etc/cluster.conf')\n nodestr_list = nodes.split('\\n')\n\n node_list = []\n for nodestr in nodestr_list:\n (node_number, node_type, node_name) = nodestr.split()[1:4]\n node_list.append((int(node_number), node_type, node_name))\n node_list.sort()\n\n for node_number, node_type, node_name in node_list:\n node = {}\n node['node'] = node_number\n node['hostname'] = node_name\n node['nodename'] = node_name\n if node_type == 'control':\n node['role'] = ['mgmt', 'oam']\n elif node_name == 'pl-1' or node_name == 'pl-2':\n node['role'] = ['data', 'traffic']\n else:\n node['role'] = ['traffic']\n conf_obj['cluster'].append(node)\n conf_obj['host'][node_name] = socket.gethostbyname(node_name)\n logging.info('Append node to cluster: ' + node_name)\n\ndef _generate_host(conf_obj):\n \"\"\"Generate 'host' section in clusterx.conf\"\"\"\n hosts = commands.getoutput('grep ^host /cluster/etc/cluster.conf')\n hoststr_list = hosts.split('\\n')\n\n for hoststr in hoststr_list:\n (ip, name) = hoststr.split()[2:4]\n conf_obj['host'][name] = ip\n logging.info('Add host: ' + name)\n\ndef upgrade_ece41():\n \"\"\"Upgrade from ece41 to ece50.\n These steps are required to run ONLY ONCE\n \"\"\"\n conf = _create_clusterx_skeleton()\n _generate_node(conf)\n _generate_host(conf)\n with open(cluster.cluster_conf, 'w') as f:\n yaml.dump(conf, f, default_flow_style=False, indent=4)\n\ndef _find_node_by_internal_ip(ip, conf):\n \"\"\"Find node instance inside conf by internal IP\"\"\"\n for node in conf.nodes:\n if node.internal_ip == ip:\n return node\n return None\n\ndef upgrade_ece50(): # pylint: disable=too-many-locals, too-many-statements\n \"\"\"Upgrade from ece50 (GP9) to ece15.\n The new format of clusterx.conf supports Deployment Profile.\n These steps are required to run ONLY ONCE\n \"\"\"\n from apitools import xconf\n new_conf = xconf.Xconf()\n with open(cluster.cluster_conf, 'r') as old_conf_file:\n old_conf = yaml.load(old_conf_file)\n\n if 'cluster' not in old_conf:\n return\n\n for old_node in old_conf['cluster']:\n nodename = old_node['nodename']\n hostname = old_node['hostname']\n internal_ip = old_conf['host'][nodename]\n if nodename == hostname and (nodename + '-external') in old_conf['host']:\n external_ip = old_conf['host'][nodename + '-external']\n else:\n external_ip = old_conf['host'][hostname]\n new_conf.add_node(nodename, hostname, internal_ip, external_ip)\n\n dp_control = new_conf.add_deployment_profile('DP-Control')\n dp_admin_server = new_conf.add_deployment_profile('DP-NGIN-Admin')\n dp_oam_cluster = new_conf.add_deployment_profile('DP-NGIN-BM')\n dp_traffic_cluster = new_conf.add_deployment_profile('DP-NGIN-Traffic')\n dp_datatier = new_conf.add_deployment_profile('DP-NGIN-SIP-Datatier')\n dp_mysql_mgm = new_conf.add_deployment_profile('DP-MySQL-Mgm')\n dp_mysql_server = new_conf.add_deployment_profile('DP-MySQL-Server')\n dp_mysql_data = new_conf.add_deployment_profile('DP-MySQL-Data')\n dp_mysql_lbs = new_conf.add_deployment_profile('DP-MySQL-LBS')\n dp_ss7_frontend = new_conf.add_deployment_profile('DP-SS7-FrontEnd')\n dp_ngin_lbs = new_conf.add_deployment_profile('DP-NGIN-LBS')\n dp_redis_sentinel = new_conf.add_deployment_profile('DP-Redis-Sentinel')\n dp_redis_server = new_conf.add_deployment_profile('DP-Redis-Server')\n\n dp_control.add_node_group(new_conf.nodes[0:2])\n dp_admin_server.add_node_group(new_conf.nodes[0:2])\n dp_oam_cluster.add_node_group(new_conf.nodes[0:2])\n dp_traffic_cluster.add_node_group(new_conf.nodes[2:])\n dp_datatier.add_node_group(new_conf.nodes[2:])\n dp_mysql_mgm.add_node_group(new_conf.nodes[0:2])\n dp_mysql_server.add_node_group(new_conf.nodes[2:4])\n dp_mysql_data.add_node_group(new_conf.nodes[2:4])\n dp_mysql_lbs.add_node_group(new_conf.nodes[0:2])\n dp_ss7_frontend.add_node_group(new_conf.nodes[2:4])\n dp_ngin_lbs.add_node_group(new_conf.nodes[0:2])\n\n dp_oam_cluster.host_prefixes = ['wls-oam']\n dp_traffic_cluster.host_prefixes = ['wls-traffic', 'ss7-be']\n dp_datatier.host_prefixes = ['wls-traffic-data']\n dp_mysql_mgm.host_prefixes = ['mgmd']\n dp_mysql_server.host_prefixes = ['mysqld']\n dp_mysql_data.host_prefixes = ['ndbd']\n dp_ss7_frontend.host_prefixes = ['ss7-fe']\n dp_redis_sentinel.host_prefixes = ['rdsmon']\n dp_redis_server.host_prefixes = ['rdssrv']\n\n rdsmon_list = [_find_node_by_internal_ip(y, new_conf) for (x, y)\n in sorted(old_conf['host'].iteritems())\n if x.startswith('rdsmon')]\n dp_redis_sentinel.add_node_group(rdsmon_list)\n rdssrv_list = [_find_node_by_internal_ip(y, new_conf) for (x, y)\n in sorted(old_conf['host'].iteritems())\n if x.startswith('rdssrv')]\n for i in xrange(len(rdssrv_list) / 2):\n dp_redis_server.add_node_group(rdssrv_list[ 2 * i : 2 * i + 2 ])\n\n for hostname, ipaddr in sorted(old_conf['host'].iteritems()):\n new_conf.add_host(hostname, ipaddr if ipaddr else '')\n\n if 'vip-admin-server' in old_conf['host']:\n new_conf.add_host('wls-admin-server-external',\n old_conf['host']['vip-admin-server'])\n if 'vip-internal' in old_conf['host']:\n new_conf.add_host('vip-dp-ngin-lbs',\n old_conf['host']['vip-internal'])\n\n new_conf.add_host('localhost', '127.0.0.1')\n\n new_conf.system.production_mode = old_conf['system']['production_mode']\n new_conf.system.ha_mode = old_conf['system']['ha_mode']\n\n vip_internal_lbs = __get_new_ip(old_conf['host']['vip-internal'], new_conf.hosts)\n # new_conf.add_host('vip-internal-lbs', vip_internal_lbs)\n new_conf.add_host('vip-dp-graphite-server-lbs', vip_internal_lbs)\n # add vip-dp-centrallogging-server-lbs\n vip_internal_lbs = __get_new_ip(vip_internal_lbs, new_conf.hosts)\n new_conf.add_host('vip-dp-centrallogging-server-lbs', vip_internal_lbs)\n vip_internal_lbs = __get_new_ip(vip_internal_lbs, new_conf.hosts)\n new_conf.add_host('vip-mysql-lbs', vip_internal_lbs)\n vip_internal_lbs = __get_new_ip(vip_internal_lbs, new_conf.hosts)\n new_conf.add_host('vip-dp-ngin-lbs', vip_internal_lbs)\n\n\n __upgrade_ece50geored(new_conf, old_conf)\n\n new_conf.validate()\n new_conf.conf_path = cluster.cluster_conf\n new_conf.save()\n\ndef __upgrade_ece50geored(new_conf, old_conf): # pylint: disable=too-many-locals, too-many-statements\n \"\"\"Upgrade from ece50 (GP9) to ece15 GeoRed related items.\n \"\"\"\n is_geored_system = False\n if old_conf.get('zone') and old_conf['system'].get('zone_id'):\n is_geored_system = True\n if is_geored_system:\n logging.debug('Change GeoRed zones format ....')\n new_conf['system']['zone_id'] = old_conf['system']['zone_id']\n old_zones = old_conf['zone']\n new_zones = []\n control_nodes = new_conf.deployment_profile('DP-MySQL-Mgm').node_groups[0]\n mysqld_nodes = new_conf.deployment_profile('DP-MySQL-Server').node_groups[0]\n for old_zone in old_zones:\n new_zone = {'zone_id': old_zone['zone_id'], 'DP-MySQL-Mgm': {}, 'DP-MySQL-Server': {}} # pylint: disable=line-too-long\n for key in old_zone:\n if key.startswith('sc-'):\n idx = int(re.match('sc-(.*)', key).group(1))\n nodename = control_nodes[idx - 1].nodename\n new_zone['DP-MySQL-Mgm'][nodename] = old_zone[key]\n if key.startswith('mysqld-'):\n idx = int(re.match('mysqld-(.*)', key).group(1))\n nodename = mysqld_nodes[idx - 1].nodename\n new_zone['DP-MySQL-Server'][nodename] = old_zone[key]\n new_zones.append(new_zone)\n new_conf['zones'] = new_zones\n logging.debug('Change GeoRed related hosts ...')\n vip_internal_lbs = new_conf.all_hosts()['vip-mysql-lbs']\n # new_conf.add_host('vip-mysql-lbs', vip_internal_lbs)\n if is_geored_system:\n vip_master_mysql_lbs = __get_new_ip(vip_internal_lbs, new_conf.hosts)\n new_conf.add_host('vip-master-mysql-lbs', vip_master_mysql_lbs)\n new_conf.add_host('master-mysqld-1', vip_master_mysql_lbs)\n new_conf.add_host('master-mysqld-2', vip_master_mysql_lbs)\n else:\n new_conf.add_host('vip-master-mysql-lbs', vip_internal_lbs)\n new_conf.add_host('master-mysqld-1', vip_internal_lbs)\n new_conf.add_host('master-mysqld-2', vip_internal_lbs)\n\ndef __get_new_ip(orig_ip, hosts):\n \"\"\"internal function\"\"\"\n host_ips = [y[0] for y in [x.values() for x in hosts]]\n m = re.match(r'([0-9]+\\.[0-9]+\\.[0-9]+\\.)([0-9]+)', orig_ip)\n ip_prefix = m.group(1)\n ip_postfix = int(m.group(2))\n incr_idx = 1\n new_ip = None\n while True:\n new_ip_postfix = ip_postfix + incr_idx\n if new_ip_postfix >= 255:\n raise RuntimeError('run out of address range for {0}'.format(orig_ip))\n new_ip = '%s%d' % (ip_prefix, new_ip_postfix)\n if new_ip in host_ips:\n incr_idx += 1\n else:\n break\n return new_ip\n\nif __name__ == '__main__':\n (version, verbose) = util.parse_upgrade_arguments()\n if verbose:\n level_in_console = logging.DEBUG\n else:\n level_in_console = logging.INFO\n util.init_log(filename=None, format_in_console='[%(levelname)s] %(message)s',\n level_in_console=level_in_console)\n if version == '4.1':\n upgrade_ece41()\n elif version == '5.0':\n upgrade_ece50()\n else:\n raise RuntimeError('Upgrade from version {0} is not supported!'.format(version))\n\n","sub_path":"rda-base/src/main/python/upgrade.py","file_name":"upgrade.py","file_ext":"py","file_size_in_byte":10748,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"585421220","text":"from django.db import models\nfrom django.utils.translation import gettext as _\nfrom django_postgres_extensions.models.fields import ArrayField\nfrom django.contrib.postgres.fields import JSONField\nfrom api.v1.category.models import Category\nfrom api.v1.varient.models import Varient\nfrom api.v1.accounts.models import Seller,User\nimport uuid\n\n\n\nclass Product(models.Model):\n\n id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)\n product_name = models.CharField(max_length=255)\n category_id = models.ForeignKey(Category,on_delete=models.CASCADE)\n varient_id = models.ForeignKey(Varient,default=1,on_delete=models.CASCADE)\n category_path = ArrayField(models.CharField(max_length=515), null=True, blank=True)\n category_rank = models.PositiveIntegerField(default=1)\n is_featured = models.BooleanField(_('is featured'), default=False)\n desciption = models.TextField()\n price = models.PositiveIntegerField()\n brand = models.CharField(max_length=255,default='')\n # more_prop = ArrayField(models.CharField(max_length=515), null=True, blank=True)\n image = models.FileField(upload_to='images/')\n more_prop = JSONField()\n tags = models.CharField(max_length=255,default='')\n by_seller =models.ForeignKey(Seller, on_delete=models.CASCADE)\n created_at=models.DateTimeField(auto_now_add=True)\n updated_at=models.DateTimeField(auto_now_add=True)\n insertedby = models.ForeignKey(User, on_delete=models.CASCADE)\n\n def __str__(self):\n\n return \"{}\".format(self.product_name)\n\n\n \n ","sub_path":"api/v1/products/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":1571,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"443818665","text":"from pyramid.config import Configurator\nfrom pyramid.session import UnencryptedCookieSessionFactoryConfig\n\ndef main(global_config, **settings):\n \"\"\" This function returns a Pyramid WSGI application.\n \"\"\"\n session_factory = UnencryptedCookieSessionFactoryConfig(\n settings['cookie.secret'],\n )\n config = Configurator(\n settings=settings,\n session_factory=session_factory,\n )\n config.include('velruse.providers.github')\n config.include('velruse.providers.facebook')\n\n config.scan('.views')\n return config.make_wsgi_app()\n","sub_path":"demo/demo/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":570,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"463704261","text":"\n# No other modules apart from 'socket', 'BeautifulSoup', 'requests' and 'datetime'\n# need to be imported as they aren't required to solve the assignment\n\n# Import required module/s\nimport socket\nfrom bs4 import BeautifulSoup\nimport requests\nimport datetime\n\n\n# Define constants for IP and Port address of Server\n# NOTE: DO NOT modify the values of these two constants\nHOST = '127.0.0.1'\nPORT = 24680\n\n\ndef fetchWebsiteData(url_website):\n\t\"\"\"Fetches rows of tabular data from given URL of a website with data excluding table headers.\n\n\tParameters\n\t----------\n\turl_website : str\n\t\tURL of a website\n\n\tReturns\n\t-------\n\tbs4.element.ResultSet\n\t\tAll rows of Tabular data fetched from a website excluding the table headers\n\t\"\"\"\n\t\n\tweb_page_data = ''\n\n\t##############\tADD YOUR CODE HERE\t##############\n\treq = requests.get(url_website)\n\tsoup = BeautifulSoup(req.text, 'html.parser')\n\tweb_page_data = soup.find_all(\"tr\")\n\tweb_page_data.pop(0)\n\t\n\t\n\n\t\n\n\t##################################################\n\n\treturn web_page_data\n\n\ndef fetchVaccineDoses(web_page_data):\n\t\"\"\"Fetch the Vaccine Doses available from the Web-page data and provide Options to select the respective Dose.\n\n\tParameters\n\t----------\n\tweb_page_data : bs4.element.ResultSet\n\t\tAll rows of Tabular data fetched from a website excluding the table headers\n\n\tReturns\n\t-------\n\tdict\n\t\tDictionary with the Doses available and Options to select, with Key as 'Option' and Value as 'Command'\n\t\n\tExample\n\t-------\n\t>>> url_website = \"https://www.mooc.e-yantra.org/task-spec/fetch-mock-covidpage\"\n\t>>> web_page_data = fetchWebsiteData(url_website)\n\t>>> print(fetchVaccineDoses(web_page_data))\n\t{'1': 'Dose 1', '2': 'Dose 2'}\n\t\"\"\"\n\n\tvaccine_doses_dict = {}\n\n\t##############\tADD YOUR CODE HERE\t##############\n\t\n\tvaccine_group = []\n\tfor th in web_page_data:\n\t\tvaccine_group.extend(th.find(\"td\",class_=\"dose_num\"))\n\n\n\t\n\tdict1 = sorted(set(vaccine_group))\n\tfor i in dict1:\n\t\tvaccine_doses_dict.update({i:\"Dose \"+i})\n\n\n\n\t##################################################\n\n\treturn vaccine_doses_dict\n\n\ndef fetchAgeGroup(web_page_data, dose):\n\t\"\"\"Fetch the Age Groups for whom Vaccination is available from the Web-page data for a given Dose\n\tand provide Options to select the respective Age Group.\n\n\tParameters\n\t----------\n\tweb_page_data : bs4.element.ResultSet\n\t\tAll rows of Tabular data fetched from a website excluding the table headers\n\tdose : str\n\t\tDose available for Vaccination and its availability for the Age Groups\n\n\tReturns\n\t-------\n\tdict\n\t\tDictionary with the Age Groups (for whom Vaccination is available for a given Dose) and Options to select,\n\t\twith Key as 'Option' and Value as 'Command'\n\t\n\tExample\n\t-------\n\t>>> url_website = \"https://www.mooc.e-yantra.org/task-spec/fetch-mock-covidpage\"\n\t>>> web_page_data = fetchWebsiteData(url_website)\n\t>>> print(fetchAgeGroup(web_page_data, '1'))\n\t{'1': '18+', '2': '45+'}\n\t>>> print(fetchAgeGroup(web_page_data, '2'))\n\t{'1': '18+', '2': '45+'}\n\t\"\"\"\n\n\tage_group_dict = {}\n\n\t##############\tADD YOUR CODE HERE\t##############\n\tage_group = []\n\tfor tr in web_page_data:\n\t\ttds = tr.find_all('td')\n\t\tif(tds[11].text == dose):\n\t\t\tage_group.append(str(tds[12].text))\n\tsorted_set_age_group = sorted(set(age_group))\n\n\tj = 1\n\tfor i in sorted_set_age_group:\n\t\tage_group_dict.update({str(j):i})\n\t\tj+=1\t\n \n\n\t##################################################\n\n\treturn age_group_dict\n\n\ndef fetchStates(web_page_data, age_group, dose):\n\t\"\"\"Fetch the States where Vaccination is available from the Web-page data for a given Dose and Age Group\n\tand provide Options to select the respective State.\n\n\tParameters\n\t----------\n\tweb_page_data : bs4.element.ResultSet\n\t\tAll rows of Tabular data fetched from a website excluding the table headers\n\tage_group : str\n\t\tAge Group available for Vaccination and its availability in the States\n\tdose : str\n\t\tDose available for Vaccination and its availability for the Age Groups\n\n\tReturns\n\t-------\n\tdict\n\t\tDictionary with the States (where the Vaccination is available for a given Dose, Age Group) and Options to select,\n\t\twith Key as 'Option' and Value as 'Command'\n\t\n\tExample\n\t-------\n\t>>> url_website = \"https://www.mooc.e-yantra.org/task-spec/fetch-mock-covidpage\"\n\t>>> web_page_data = fetchWebsiteData(url_website)\n\t>>> print(fetchStates(web_page_data, '18+', '1'))\n\t{\n\t\t'1': 'Andhra Pradesh', '2': 'Arunachal Pradesh', '3': 'Bihar', '4': 'Chandigarh', '5': 'Delhi', '6': 'Goa',\n\t\t'7': 'Gujarat', '8': 'Harayana', '9': 'Himachal Pradesh', '10': 'Jammu and Kashmir', '11': 'Kerala', '12': 'Telangana'\n\t}\n\t\"\"\"\n\n\tstates_dict = {}\n\n\t##############\tADD YOUR CODE HERE\t##############\n\tresult = []\n\tstate_group = []\n\tfor tr in web_page_data:\n\t\ttds = tr.find_all('td')\n\t\tif(tds[11].text == dose and tds[12].text == age_group):\n\t\t\tresult.append(tds[1].text)\n\t[state_group.append(x) for x in result if x not in state_group]\n\tsorted_set_state_group = sorted(state_group)\n\t\n\n\tj = 1\n\tfor i in sorted_set_state_group:\n\t\tstates_dict.update({str(j):i})\n\t\tj+=1\t\n\t##################################################\n\n\treturn states_dict\n\n\ndef fetchDistricts(web_page_data, state, age_group, dose):\n\t\"\"\"Fetch the District where Vaccination is available from the Web-page data for a given State, Dose and Age Group\n\tand provide Options to select the respective District.\n\n\tParameters\n\t----------\n\tweb_page_data : bs4.element.ResultSet\n\t\tAll rows of Tabular data fetched from a website excluding the table headers\n\tstate : str\n\t\tState where Vaccination is available for a given Dose and Age Group\n\tage_group : str\n\t\tAge Group available for Vaccination and its availability in the States\n\tdose : str\n\t\tDose available for Vaccination and its availability for the Age Groups\n\n\tReturns\n\t-------\n\tdict\n\t\tDictionary with the Districts (where the Vaccination is available for a given State, Dose, Age Group) and Options to select,\n\t\twith Key as 'Option' and Value as 'Command'\n\t\n\tExample\n\t-------\n\t>>> url_website = \"https://www.mooc.e-yantra.org/task-spec/fetch-mock-covidpage\"\n\t>>> web_page_data = fetchWebsiteData(url_website)\n\t>>> print(fetchDistricts(web_page_data, 'Ladakh', '18+', '2'))\n\t{\n\t\t'1': 'Kargil', '2': 'Leh'\n\t}\n\t\"\"\"\n\n\tdistricts_dict = {}\n\n\t##############\tADD YOUR CODE HERE\t##############\n\t\n\tdistricts_group = []\n\tfor tr in web_page_data:\n\t\ttds = tr.find_all('td')\n\t\tif((tds[11].text == dose and tds[12].text == age_group) and (tds[1].text) == state):\n\t\t\tdistricts_group.append(tds[2].text)\n\tsorted_districts_group=sorted(set(districts_group))\n\n\tj = 1\n\tfor i in sorted_districts_group:\n\t\tdistricts_dict.update({str(j):i})\n\t\tj+=1\t\n\n\t##################################################\n\n\treturn districts_dict\n\n\ndef fetchHospitalVaccineNames(web_page_data, district, state, age_group, dose):\n\t\"\"\"Fetch the Hospital and the Vaccine Names from the Web-page data available for a given District, State, Dose and Age Group\n\tand provide Options to select the respective Hospital and Vaccine Name.\n\n\tParameters\n\t----------\n\tweb_page_data : bs4.element.ResultSet\n\t\tAll rows of Tabular data fetched from a website excluding the table headers\n\tdistrict : str\n\t\tDistrict where Vaccination is available for a given State, Dose and Age Group\n\tstate : str\n\t\tState where Vaccination is available for a given Dose and Age Group\n\tage_group : str\n\t\tAge Group available for Vaccination and its availability in the States\n\tdose : str\n\t\tDose available for Vaccination and its availability for the Age Groups\n\n\tReturns\n\t-------\n\tdict\n\t\tDictionary with the Hosptial and Vaccine Names (where the Vaccination is available for a given District, State, Dose, Age Group)\n\t\tand Options to select, with Key as 'Option' and Value as another dictionary having Key as 'Hospital Name' and Value as 'Vaccine Name'\n\t\n\tExample\n\t-------\n\t>>> url_website = \"https://www.mooc.e-yantra.org/task-spec/fetch-mock-covidpage\"\n\t>>> web_page_data = fetchWebsiteData(url_website)\n\t>>> print(fetchHospitalVaccineNames(web_page_data, 'Kargil', 'Ladakh', '18+', '2'))\n\t{\n\t\t'1': {\n\t\t\t\t'MedStar Hospital Center': 'Covaxin'\n\t\t\t}\n\t}\n\t>>> print(fetchHospitalVaccineNames(web_page_data, 'South Goa', 'Goa', '45+', '2'))\n\t{\n\t\t'1': {\n\t\t\t\t'Eden Clinic': 'Covishield'\n\t\t\t}\n\t}\n\t\"\"\"\n\t\n\t#hospital_vaccine_names_dict = {}\n\n\t##############\tADD YOUR CODE HERE\t##############\n\t\n\thospital_group = []\n\tfor tr in web_page_data:\n\t\ttds = tr.find_all('td')\n\t\tif((tds[11].text == dose and tds[12].text == age_group) and (tds[1].text) == state and tds[2].text == district):\n\t\t\thospital_group.append(tds[0].text)\n\t\t\thospital_group.append(tds[10].text)\n\t\t\ti = 1\n\t\t\thospital_vaccine_names_dict = {str(i):{hospital_group[i]: hospital_group[i + 1] for i in range(0, len(hospital_group), 2)}}\n\t\t\ti+=1\n\n\n\t##################################################\n\n\treturn hospital_vaccine_names_dict\n\n\ndef fetchVaccineSlots(web_page_data, hospital_name, district, state, age_group, dose):\n\t\"\"\"Fetch the Dates and Slots available on those dates from the Web-page data available for a given Hospital Name, District, State, Dose and Age Group\n\tand provide Options to select the respective Date and available Slots.\n\n\tParameters\n\t----------\n\tweb_page_data : bs4.element.ResultSet\n\t\tAll rows of Tabular data fetched from a website excluding the table headers\n\thospital_name : str\n\t\tName of Hospital where Vaccination is available for given District, State, Dose and Age Group\n\tdistrict : str\n\t\tDistrict where Vaccination is available for a given State, Dose and Age Group\n\tstate : str\n\t\tState where Vaccination is available for a given Dose and Age Group\n\tage_group : str\n\t\tAge Group available for Vaccination and its availability in the States\n\tdose : str\n\t\tDose available for Vaccination and its availability for the Age Groups\n\n\tReturns\n\t-------\n\tdict\n\t\tDictionary with the Dates and Slots available on those dates (where the Vaccination is available for a given Hospital Name,\n\t\tDistrict, State, Dose, Age Group) and Options to select, with Key as 'Option' and Value as another dictionary having\n\t\tKey as 'Date' and Value as 'Available Slots'\n\t\n\tExample\n\t-------\n\t>>> url_website = \"https://www.mooc.e-yantra.org/task-spec/fetch-mock-covidpage\"\n\t>>> web_page_data = fetchWebsiteData(url_website)\n\t>>> print(fetchVaccineSlots(web_page_data, 'MedStar Hospital Center', 'Kargil', 'Ladakh', '18+', '2'))\n\t{\n\t\t'1': {'May 15': '0'}, '2': {'May 16': '81'}, '3': {'May 17': '109'}, '4': {'May 18': '78'},\n\t\t'5': {'May 19': '89'}, '6': {'May 20': '57'}, '7': {'May 21': '77'}\n\t}\n\t>>> print(fetchVaccineSlots(web_page_data, 'Eden Clinic', 'South Goa', 'Goa', '45+', '2'))\n\t{\n\t\t'1': {'May 15': '0'}, '2': {'May 16': '137'}, '3': {'May 17': '50'}, '4': {'May 18': '78'},\n\t\t'5': {'May 19': '145'}, '6': {'May 20': '64'}, '7': {'May 21': '57'}\n\t}\n\t\"\"\"\n\n\tvaccine_slots = {}\n\n\t##############\tADD YOUR CODE HERE\t##############\n\t\n\tvaccine_group = []\n\tfor tr in web_page_data:\n\t\ttds = tr.find_all('td')\n\t\tif((tds[11].text == dose and tds[12].text == age_group) and (tds[1].text) == state and tds[2].text == district) and (tds[0].text == hospital_name):\n\t\t\tvaccine_slots = {'1':{'May 15':tds[3].text},'2':{'May 16':tds[4].text},'3':{'May 17':tds[5].text},'4':{'May 18':tds[6].text},'5':{'May 19':tds[7].text},'6':{'May 20':tds[8].text},'7':{'May 21':tds[9].text}}\n\t\t\t\n\t\n\n\t##################################################\n\n\treturn vaccine_slots\n\n\ndef openConnection():\n\t\"\"\"Opens a socket connection on the HOST with the PORT address.\n\n\tReturns\n\t-------\n\tsocket\n\t\tObject of socket class for the Client connected to Server and communicate further with it\n\ttuple\n\t\tIP and Port address of the Client connected to Server\n\t\"\"\"\n\n\tclient_socket = None\n\tclient_addr = None\n\n\t##############\tADD YOUR CODE HERE\t##############\n\n\t\n\n\ts = socket.socket() # Create a socket object\n\thost = '127.0.0.1'\n\tport = 24680 \n\ts.setsockopt(socket.SOL_SOCKET,socket.SO_REUSEADDR,1) # Reserve a port for your service.\n\ts.bind((host, port)) # Bind to the port\n\n\ts.listen(5) # Now wait for client connection.\n\t\n\tclient_socket, client_addr = s.accept() # Establish connection with client.\n\tprint ('Got connection from', client_addr)\n\t\n\t\n\t##################################################\n\t\n\treturn client_socket, client_addr\n\n\n\ndef startCommunication(client_conn, client_addr, web_page_data):\n\t\"\"\"Starts the communication channel with the connected Client for scheduling an Appointment for Vaccination.\n\n\tParameters\n\t----------\n\tclient_conn : socket\n\t\tObject of socket class for the Client connected to Server and communicate further with it\n\tclient_addr : tuple\n\t\tIP and Port address of the Client connected to Server\n\tweb_page_data : bs4.element.ResultSet\n\t\tAll rows of Tabular data fetched from a website excluding the table headers\n\t\"\"\"\n\n\t##############\tADD YOUR CODE HERE\t##############\n\t\n\tclient = client_conn\n\tweb_data = web_page_data\n\tglobal no_of_attempt\n\tno_of_attempt = 1\n\n\n\t\n\t# Below are the functions for each state where each option is chosed from the user\n\n\t#function to recieve data from terminal\n\tdef recieve(client_conn):\n\t\tdata = client.recv(1024).decode('utf-8')\n\t\t\n\n\t\treturn data\n\t#fetch vaccine slots\n\tdef state6(client_conn,web_data):\n\t\tglobal vaccine_slots_selection\n\t\tglobal hospital_selected\n\t\tglobal district_selected\n\t\tglobal state_selected\n\t\tglobal age_input_vaccine\n\t\tglobal dose\n\t\tslot_input_message = \">>> Select one of the available slots to schedule the Appointment:\"\n\t\tslot_dict = fetchVaccineSlots(web_data,hospital_selected,district_selected,state_selected,age_input_vaccine,dose)\n\t\tslot_input_message = slot_input_message+\"\\n\"+str(slot_dict)\n\t\tclient_conn.send(slot_input_message.encode())\n\t\tslot = recieve(client_conn)\n\t\t\n\t\t\n\t\tif((slot == 'b') or (slot == 'B')):\n\t\t\tstate5(client_conn,web_data)\n\t\telif((slot == 'q') or (slot == \"Q\")):\n\t\t\tquit_msg = \"<<< See ya! Visit again :)\\n\"\n\t\t\tclient_conn.send(quit_msg.encode())\n\n\t\t\tclient_conn.close()\n\t\t\t\n\t\telse:\n\t\t\tif slot in slot_dict:\n\t\t\t\tslot_selected = list(slot_dict[slot].keys())[0]\n\t\t\t\t\n\t\t\t\tslot_available = slot_dict[slot][slot_selected]\n\t\t\t\ts_selected = \"<<< Selected Vaccination Appointment Date: \"+str(slot_selected)+\"\\n\"\n\t\t\t\tavailability = \"<<< Available Slots on the selected Date: \" +str(slot_available)+\"\\n\"\n\t\t\t\tprint(\"Vaccination Date selected: \",slot_selected)\n\t\t\t\tprint(\"Available Slots on that date: \",slot_available)\n\t\t\t\t\n\t\t\t\tclient_conn.send(s_selected.encode())\n\t\t\t\tclient_conn.send(availability.encode())\n\t\t\t\tif (int(slot_available) == 0):\n\t\t\t\t\tslot_unavailable = '<<< Selected Appointment Date has no available slots, select another date!\\n'\n\t\t\t\t\tclient_conn.send(slot_unavailable.encode())\n\t\t\t\t\tstate6(client_conn,web_data)\n\t\t\t\telse:\n\t\t\t\t\tslot_available = \"<<< Your appointment is scheduled. Make sure to carry ID Proof while you visit Vaccination Center!\\n\"\n\t\t\t\t\texit_message = \t\"<<< See ya! Visit again :)\"\n\t\t\t\t\tclient_conn.send(slot_available.encode())\n\t\t\t\t\tclient_conn.send(exit_message.encode())\n\t\t\t\t\tclient_conn.close()\n\n\n\t\t\t\t\t\n\t\t\telse:\n\t\t\t\tglobal no_of_attempt\n\t\t\t\tif (no_of_attempt == 1):\n\t\t\t\t\tinvalid_dose_msg = \"<<< Invalid input provided 1 time(s)! Try again.\\n\"\n\t\t\t\t\tprint(invalid_dose_msg)\n\t\t\t\t\tclient_conn.send(invalid_dose_msg.encode())\n\t\t\t\t\t\n\t\t\t\t\tno_of_attempt+=1\n\t\t\t\t\tstate6(client_conn,web_data)\n\t\t\t\t\t\n\t\t\t\t\t\n\t\t\t\telif (no_of_attempt == 2):\n\t\t\t\t\tinvalid_dose_msg = \"<<< Invalid input provided 2 time(s)! Try again.\\n\"\n\t\t\t\t\tprint(invalid_dose_msg)\n\t\t\t\t\tclient_conn.send(invalid_dose_msg.encode())\n\t\t\t\t\t\n\t\t\t\t\tno_of_attempt+=1\n\t\t\t\t\tstate6(client_conn,web_data)\n\t\t\t\telif(no_of_attempt == 3):\n\t\t\t\t\tinvalid_dose_msg = \"<<< Invalid input provided 3 time(s)! Try again.\\n\"\n\t\t\t\t\tclient_conn.send(invalid_dose_msg.encode())\n\t\t\t\t\tprint(invalid_dose_msg)\n\t\t\t\t\tquit_msg = \"<<< See ya! Visit again :)\"\n\t\t\t\t\tclient_conn.send(quit_msg.encode())\n\t\t\t\t\tprint(\"Notifying the client and closing the connection!\")\n\t\t\t\t\tclient_conn.close()\n\n\t#fetch hospital\n\n\tdef state5(client_conn,web_data):\n\t\tglobal hospital_selected\n\t\tglobal district_selected\n\t\tglobal state_selected\n\t\tglobal age_input_vaccine\n\t\tglobal dose\n\t\thospital_input_message = \">>> Select the Vaccination Center Name:\"\n\t\thospital_dict = fetchHospitalVaccineNames(web_data,district_selected,state_selected,age_input_vaccine,dose)\n\t\thospital_input_message = hospital_input_message+\"\\n\"+str(hospital_dict)+\"\\n\"\n\t\tclient_conn.send(hospital_input_message.encode())\n\t\thospital = recieve(client_conn)\n\t\t\n\t\t\n\t\tif((hospital == 'b') or (hospital == 'B')):\n\t\t\tstate4(client_conn,web_data)\n\t\telif((hospital == 'q') or (hospital == \"Q\")):\n\t\t\tquit_msg = \"<<< See ya! Visit again :)\\n\"\n\t\t\tclient_conn.send(quit_msg.encode())\n\n\t\t\tclient_conn.close()\n\t\telse:\n\t\t\tif hospital in hospital_dict:\n\t\t\t\t#hospitals = hospital_dict[hospital].keys()\n\t\t\t\thospital_selected = list(hospital_dict[hospital].keys())[0]\n\t\t\t\th_selected = \"<<< Selected Vaccination Center: \"+ str(hospital_selected)\n\t\t\t\tprint(\"Selected Vaccine Center: \",str(hospital_selected))\n\t\t\t\tclient_conn.send(h_selected.encode())\n\t\t\t\tstate6(client_conn,web_data)\n\t\t\t\t\t\n\t\t\telse:\n\t\t\t\tglobal no_of_attempt\n\t\t\t\tif (no_of_attempt == 1):\n\t\t\t\t\tinvalid_dose_msg = \"<<< Invalid input provided 1 time(s)! Try again.\\n\"\n\t\t\t\t\tprint(invalid_dose_msg)\n\t\t\t\t\tclient_conn.send(invalid_dose_msg.encode())\n\t\t\t\t\t\n\t\t\t\t\tno_of_attempt+=1\n\t\t\t\t\tstate5(client_conn,web_data)\n\t\t\t\t\t\n\t\t\t\t\t\n\t\t\t\telif (no_of_attempt == 2):\n\t\t\t\t\tinvalid_dose_msg = \"<<< Invalid input provided 2 time(s)! Try again.\\n\"\n\t\t\t\t\tprint(invalid_dose_msg)\n\t\t\t\t\tclient_conn.send(invalid_dose_msg.encode())\n\t\t\t\t\t\n\t\t\t\t\tno_of_attempt+=1\n\t\t\t\t\tstate5(client_conn,web_data)\n\t\t\t\telif(no_of_attempt == 3):\n\t\t\t\t\tinvalid_dose_msg = \"<<< Invalid input provided 3 time(s)! Try again.\\n\"\n\t\t\t\t\tclient_conn.send(invalid_dose_msg.encode())\n\t\t\t\t\tprint(invalid_dose_msg)\n\t\t\t\t\tquit_msg = \"<<< See ya! Visit again :)\"\n\t\t\t\t\tclient_conn.send(quit_msg.encode())\n\t\t\t\t\tprint(\"Notifying the client and closing the connection!\")\n\t\t\t\t\tclient_conn.close()\n\t\n\n\t#fetch district\t\n\n\tdef state4(client_conn,web_data):\n\t\tglobal district_selected\n\t\tglobal state_selected\n\t\tglobal age_input_vaccine\n\t\tglobal dose\n\t\tdistrict_input_message = \">>> Select the District:\"\n\t\tdistrict_dict = fetchDistricts(web_data,state_selected,age_input_vaccine,dose)\n\t\tdistrict_input_message = district_input_message+\"\\n\"+str(district_dict)+\"\\n\"\n\t\tclient_conn.sendall(district_input_message.encode('utf-8'))\n\t\tdistrict = recieve(client_conn)\n\t\t\n\t\t\n\t\tif((district == 'b') or (district== 'B')):\n\t\t\tstate3(client_conn,web_data)\n\t\telif((district == 'q') or (district == \"Q\")):\n\t\t\tquit_msg = \"<<< See ya! Visit again :)\"\n\t\t\tclient_conn.sendall(quit_msg.encode('utf-8'))\n\n\t\t\tclient_conn.close()\n\t\telse:\n\t\t\tif district in district_dict:\n\t\t\t\tdistrict_selected = district_dict[district]\n\t\t\t\ts_selected = \"<<< Selected District: \"+ str(district_selected)+\"\\n\"\n\t\t\t\tprint(\"District selected: \",district_selected)\n\t\t\t\tclient_conn.send(s_selected.encode())\n\t\t\t\tstate5(client_conn,web_data)\n\t\t\t\t\t\n\t\t\telse:\n\t\t\t\tglobal no_of_attempt\n\t\t\t\tif (no_of_attempt == 1):\n\t\t\t\t\tinvalid_dose_msg = \"<<< Invalid input provided 1 time(s)! Try again.\\n\"\n\t\t\t\t\tprint(invalid_dose_msg)\n\t\t\t\t\tclient_conn.send(invalid_dose_msg.encode())\n\t\t\t\t\t\n\t\t\t\t\tno_of_attempt+=1\n\t\t\t\t\tstate4(client_conn,web_data)\n\t\t\t\t\t\n\t\t\t\t\t\n\t\t\t\telif (no_of_attempt == 2):\n\t\t\t\t\tinvalid_dose_msg = \"<<< Invalid input provided 2 time(s)! Try again.\\n\"\n\t\t\t\t\tprint(invalid_dose_msg)\n\t\t\t\t\tclient_conn.send(invalid_dose_msg.encode())\n\t\t\t\t\t\n\t\t\t\t\tno_of_attempt+=1\n\t\t\t\t\tstate4(client_conn,web_data)\n\t\t\t\telif(no_of_attempt == 3):\n\t\t\t\t\tinvalid_dose_msg = \"<<< Invalid input provided 3 time(s)! Try again.\\n\"\n\t\t\t\t\tclient_conn.send(invalid_dose_msg.encode())\n\t\t\t\t\tprint(invalid_dose_msg)\n\t\t\t\t\tquit_msg = \"<<< See ya! Visit again :)\\n\"\n\t\t\t\t\tclient_conn.send(quit_msg.encode())\n\t\t\t\t\tprint(\"Notifying the client and closing the connection!\")\n\t\t\t\t\tclient_conn.close()\n\t\n\n\t#fetch state\t\n\n\tdef state3(client_conn,web_data):\n\t\tglobal state_selected\n\t\tglobal age_input_vaccine\n\t\tglobal dose\n\t\tstate_input_message = \">>> Select the State:\"\n\t\tstate_dict = fetchStates(web_data,age_input_vaccine,dose)\n\t\tstate_input_message = state_input_message+\"\\n\"+str(state_dict)+\"\\n\"\n\t\tclient_conn.send(state_input_message.encode())\n\t\tstate = recieve(client_conn)\n\t\t\n\t\t\n\t\tif((state == 'b') or (state == 'B')):\n\t\t\tstate2(client_conn,web_data)\n\t\telif((state == 'q') or (state == \"Q\")):\n\t\t\tquit_msg = \"<<< See ya! Visit again :)\\n\"\n\t\t\tclient_conn.send(quit_msg.encode())\n\n\t\t\tclient_conn.close()\n\t\telse:\n\t\t\tif state in state_dict:\n\t\t\t\tstate_selected = state_dict[state]\n\t\t\t\ts_selected = \"<<< Selected State: \"+ str(state_selected)+\"\\n\"\n\t\t\t\tprint(\"State selected: \",state_selected)\n\t\t\t\tclient_conn.send(s_selected.encode())\n\t\t\t\tstate4(client_conn,web_data)\n\t\t\t\t\t\n\t\t\telse:\n\t\t\t\tglobal no_of_attempt\n\t\t\t\tif (no_of_attempt == 1):\n\t\t\t\t\tinvalid_dose_msg = \"<<< Invalid input provided 1 time(s)! Try again.\\n\"\n\t\t\t\t\tprint(invalid_dose_msg)\n\t\t\t\t\tclient_conn.send(invalid_dose_msg.encode())\n\t\t\t\t\t\n\t\t\t\t\tno_of_attempt+=1\n\t\t\t\t\tstate3(client_conn,web_data)\n\t\t\t\t\t\n\t\t\t\t\t\n\t\t\t\telif (no_of_attempt == 2):\n\t\t\t\t\tinvalid_dose_msg = \"<<< Invalid input provided 2 time(s)! Try again.\\n\"\n\t\t\t\t\tprint(invalid_dose_msg)\n\t\t\t\t\tclient_conn.send(invalid_dose_msg.encode())\n\t\t\t\t\t\n\t\t\t\t\tno_of_attempt+=1\n\t\t\t\t\tstate3(client_conn,web_data)\n\t\t\t\telif(no_of_attempt == 3):\n\t\t\t\t\tinvalid_dose_msg = \"<<< Invalid input provided 3 time(s)! Try again.\\n\"\n\t\t\t\t\tclient_conn.send(invalid_dose_msg.encode())\n\t\t\t\t\tprint(invalid_dose_msg)\n\t\t\t\t\tquit_msg = \"<<< See ya! Visit again :)\\n\"\n\t\t\t\t\tclient_conn.send(quit_msg.encode())\n\t\t\t\t\tprint(\"Notifying the client and closing the connection!\")\n\t\t\t\t\tclient_conn.close()\n\t\n\n\t#fetch age group \n\n\tdef state2(client_conn,web_data):\n\n\t\tglobal age_input_vaccine \n\t\tglobal dose\n\t\tage_input_message = \">>> Select the Age Group:\"\n\t\tage_for_vaccination = fetchAgeGroup(web_data,dose)\n\t\t\n\t\tage_input_message = age_input_message+\"\\n\"+str(age_for_vaccination)+\"\\n\"\n\t\t\n\t\tclient_conn.sendall(age_input_message.encode('utf-8'))\n\t\tage_input = recieve(client_conn)\n\t\t\n\t\t\n\t\tif((age_input == 'b') or (age_input == 'B')):\n\t\t\tstate1(client_conn,web_data)\n\t\telif((age_input == 'q') or (age_input == \"Q\")):\n\t\t\tquit_msg = \"<<< See ya! Visit again :)\\n\"\n\t\t\tclient_conn.sendall(quit_msg.encode('utf-8'))\n\n\t\t\tclient_conn.close()\n\t\telse:\n\t\t\tif age_input in age_for_vaccination:\n\t\t\t\tage_input_vaccine = age_for_vaccination[age_input]\n\t\t\t\tprint(\"Age group selected: \",age_input_vaccine)\n\t\t\t\tdose_selected = \"<<< Selected Age Group: \"+ str(age_for_vaccination[age_input])+\"\\n\"\n\t\t\t\tclient_conn.sendall(dose_selected.encode('utf-8'))\n\t\t\t\tstate3(client_conn,web_data)\n\t\t\t\t\t\n\t\t\telse:\n\t\t\t\tglobal no_of_attempt\n\t\t\t\tif (no_of_attempt == 1):\n\t\t\t\t\tinvalid_dose_msg = \"<<< Invalid input provided 1 time(s)! Try again.\\n\"\n\t\t\t\t\tprint(invalid_dose_msg)\n\t\t\t\t\tclient_conn.sendall(invalid_dose_msg.encode('utf-8'))\n\t\t\t\t\t\n\t\t\t\t\tno_of_attempt+=1\n\t\t\t\t\tstate2(client_conn,web_data)\n\t\t\t\t\t\n\t\t\t\t\t\n\t\t\t\telif (no_of_attempt == 2):\n\t\t\t\t\tinvalid_dose_msg = \"<<< Invalid input provided 2 time(s)! Try again.\\n\"\n\t\t\t\t\tprint(invalid_dose_msg)\n\t\t\t\t\tclient_conn.sendall(invalid_dose_msg.encode('utf-8'))\n\t\t\t\t\t\n\t\t\t\t\tno_of_attempt+=1\n\t\t\t\t\tstate2(client_conn,web_data)\n\t\t\t\telif(no_of_attempt == 3):\n\t\t\t\t\tinvalid_dose_msg = \"<<< Invalid input provided 3 time(s)! Try again.\\n\"\n\t\t\t\t\tclient_conn.sendall(invalid_dose_msg.encode('utf-8'))\n\t\t\t\t\tprint(invalid_dose_msg)\n\t\t\t\t\tquit_msg = \"<<< See ya! Visit again :)\\n\"\n\t\t\t\t\tclient_conn.sendall(quit_msg.encode('utf-8'))\n\t\t\t\t\tprint(\"Notifying the client and closing the connection!\")\n\t\t\t\t\tclient_conn.close()\n\t\n\t# for selection of 1st dose date\n\n\tdef selecting_a_date(client_conn,web_data):\n\t\ttry:\n\t\t\tfirst_dose_msg = \">>> Provide the date of First Vaccination Dose (DD/MM/YYYY), for e.g. 12/5/2021\\n\"\n\t\t\tclient_conn.sendall(first_dose_msg.encode('utf-8'))\n\t\t\ttoday = datetime.date.today()\n\t\t\ttoday_date = today.strftime(\"%d/%m/%Y\")\n\t\t\tfirst_dose_date = recieve(client_conn)\n\t\t\t\n\t\t\tif ((first_dose_date == 'b') or (first_dose_date == 'B')):\n\t\t\t\t\n\t\t\t\tstate1(client_conn,web_data)\n\n\t\t\telif((first_dose_date == 'q' or first_dose_date == 'Q')):\n\t\t\t\t\n\t\t\t\t\n\t\t\t\tquit_msg = \"<<< See ya! Visit again :)\\n\"\n\t\t\t\tclient_conn.sendall(quit_msg.encode('utf-8'))\t\n\t\t\telse:\n\n\t\t\t\t\n\t\t\t\ttoday_date = today_date.split(\"/\")\n\t\t\t\tfirst_dose_date_list = first_dose_date.split(\"/\")\n\t\t\t\tf_date = datetime.datetime(int(first_dose_date_list[2]),int(first_dose_date_list[1]),int(first_dose_date_list[0]))\n\t\t\t\tl_date = datetime.datetime(int(today_date[2]),int(today_date[1]),int(today_date[0]))\n\t\t\t\tdelta = l_date - f_date\n\t\t\t\tno_of_weeks = delta.days//7\n\t\t\t\t\n\t\t\t\tif (no_of_weeks < 0):\n\t\t\t\t\t\n\t\t\t\t\tinvalid_date_msg = \"<<< Invalid Date provided of First Vaccination Dose: \"+ str(first_dose_date)+\"\\n\"\n\t\t\t\t\tclient_conn.sendall(invalid_date_msg.encode('utf-8'))\n\t\t\t\t\tselecting_a_date(client_conn,web_data)\n\t\t\t\telse:\n\n\t\t\t\t\tfirst_dose_date_msg = \"<<< Date of First Vaccination Dose provided: \"+ str(first_dose_date)+\"\\n\"\n\t\t\t\t\tclient_conn.send(first_dose_date_msg.encode())\n\t\t\t\t\tno_of_weeks_message= \"<<< Number of weeks from today: \"+ str(no_of_weeks)+\"\\n\"\n\t\t\t\t\tclient_conn.send(no_of_weeks_message.encode())\n\t\t\t\t\t\n\n\t\t\t\t\tif(no_of_weeks >= 4) and (no_of_weeks <= 8):\n\t\t\t\t\t\t\n\t\t\t\t\t\tsecond_dose = \"<<< You are eligible for 2nd Vaccination Dose and are in the right time-frame to take it.\\n\"\n\t\t\t\t\t\tclient_conn.sendall(second_dose.encode('utf-8'))\n\t\t\t\t\t\t\t\t\t\n\t\t\t\t\t\tstate2(client_conn,web_data)\n\t\t\t\t\telif(no_of_weeks > 8):\n\t\t\t\t\t\tlate_time = no_of_weeks - 8\n\t\t\t\t\t\tlate_time = str(late_time)\n\t\t\t\t\t\tgreater_second_dose_message = \"<<< You have been late in scheduling your 2nd Vaccination Dose by \"+ late_time+\" weeks\\n\"\n\n\t\t\t\t\t\tclient_conn.sendall(greater_second_dose_message.encode('utf-8'))\n\t\t\t\t\t\tstate2(client_conn,web_data)\n\t\t\t\t\telse:\n\t\t\t\t\t\tearly_week = 4 - no_of_weeks\n\t\t\t\t\t\tinvalid_second_dose_msg = \"<<< You are not eligible right now for 2nd Vaccination Dose! Try after \" + str(early_week)+\" weeks.\\n\"\n\t\t\t\t\t\t\t\n\t\t\t\t\t\tclient_conn.send(invalid_second_dose_msg.encode())\n\t\t\t\t\t\tprint(\"Notifying the client and closing the connection!\")\n\t\t\t\t\t\tquit_msg = \"<<< See ya! Visit again :)\\n\"\n\t\t\t\t\t\tclient_conn.sendall(quit_msg.encode('utf-8'))\n\t\t\t\t\t\tclient_conn.close()\n\t\t\t\n\n\t\texcept ValueError:\n\t\t\tinvalid_date = \"<<< Invalid Date provided of First Vaccination Dose:\"+ first_dose_date+\"\\n\"\n\t\t\t\n\t\t\tselecting_a_date(client_conn)\n\n\t#fetching the dose\n\tdef state1(client_conn,web_data):\n\t\tglobal dose\n\t\tdose_input_msg = \">>> Select the Dose of Vaccination:\"\n\t\t#client_conn.send(dose_input_msg.encode())\t\n\t\tvaccine_doses = fetchVaccineDoses(web_page_data)\n\t\tstring_vaccine_doses = dose_input_msg+\"\\n\"+str(vaccine_doses)\n\t\t\n\t\tclient_conn.send(string_vaccine_doses.encode())\n\t\tdose = recieve(client)\n\t\t\n\t\tif((dose == 'b') or (dose == 'B')):\n\t\t\t\n\t\t\tstate1(client_conn,web_data)\n\t\telif((dose == 'q') or (dose == \"Q\")):\n\t\t\tquit_msg = \"<<< See ya! Visit again :)\\n\"\n\t\t\tclient_conn.send(quit_msg.encode())\n\n\t\t\tclient_conn.close()\n\t\telse:\n\t\t\tif dose in vaccine_doses:\n\t\t\t\tdose_selected = \"<<< Dose selected: \"+dose+\"\\n\"\n\t\t\t\tprint(\"Dose selected: \",dose)\n\t\t\t\tclient_conn.sendall(dose_selected.encode('utf-8'))\n\t\t\t\tif (dose == '1'):\n\t\t\t\t\tstate2(client_conn,web_data)\n\t\t\t\telif(dose == '2'):\n\t\t\t\t\tselecting_a_date(client_conn,web_data)\n\t\t\t\t\t\n\t\t\telse:\n\t\t\t\tglobal no_of_attempt\n\t\t\t\tif (no_of_attempt == 1):\n\t\t\t\t\tinvalid_dose_msg = \"<<< Invalid input provided 1 time(s)! Try again.\"\n\t\t\t\t\tclient_conn.sendall(invalid_dose_msg.encode('utf-8'))\n\t\t\t\t\tprint(invalid_dose_msg)\n\t\t\t\t\tno_of_attempt+=1\n\t\t\t\t\t\n\t\t\t\t\tstate1(client_conn,web_data)\n\t\t\t\telif (no_of_attempt == 2):\n\t\t\t\t\tinvalid_dose_msg1 = \"<<< Invalid input provided 2 time(s)! Try again.\"\n\t\t\t\t\tclient_conn.sendall(invalid_dose_msg1.encode('utf-8'))\n\t\t\t\t\tprint(invalid_dose_msg1)\n\t\t\t\t\tno_of_attempt+=1\n\t\t\t\t\tstate1(client_conn,web_data)\n\t\t\t\telif(no_of_attempt == 3):\n\t\t\t\t\tinvalid_dose_msg2 = \"<<< Invalid input provided 3 time(s)! Try again.\"\n\t\t\t\t\tclient_conn.sendall(invalid_dose_msg2.encode('utf-8'))\n\t\t\t\t\tprint(invalid_dose_msg2)\n\t\t\t\t\tquit_msg = \"<<< See ya! Visit again :)\"\n\t\t\t\t\tclient_conn.sendall(quit_msg.encode('utf-8'))\n\t\t\t\t\tprint(\"Notifying the client and closing the connection!\")\n\t\t\t\t\tclient_conn.close()\n\t\n\t\t\t\t\t\n\n\tschedule_msg = \"Schedule an Appointment for Vaccination:\\n\\n\"\n\tclient_conn.sendall(schedule_msg.encode('utf-8'))\n\n\n\n\tstate1(client,web_data)\n\t\t\n\n\t\n\n\n\t##################################################\n\n\ndef stopCommunication(client_conn):\n\t\"\"\"Stops or Closes the communication channel of the Client with a message.\n\n\tParameters\n\t----------\n\tclient_conn : socket\n\t\tObject of socket class for the Client connected to Server and communicate further with it\n\t\"\"\"\n\n\t##############\tADD YOUR CODE HERE\t##############\n\t\n\tquit_msg = \"<<< See ya! Visit again :)\"\n\tclient_conn.send(quit_msg.encode())\n\n\tclient_conn.close()\n\t\n\n\t##################################################\n\n\n################# ADD UTILITY FUNCTIONS HERE #################\n## You can define any utility functions for your code. ##\n## Please add proper comments to ensure that your code is ##\n## readable and easy to understand. ##\n##############################################################\n\n\n##############################################################\n\n\nif __name__ == '__main__':\n\t\"\"\"Main function, code begins here\n\t\"\"\"\n\turl_website = \"https://www.mooc.e-yantra.org/task-spec/fetch-mock-covidpage\"\n\tweb_page_data = fetchWebsiteData(url_website)\n\tclient_conn, client_addr = openConnection()\n\tstartCommunication(client_conn, client_addr, web_page_data)\n","sub_path":"Activity_2/w6_activity2_server.py","file_name":"w6_activity2_server.py","file_ext":"py","file_size_in_byte":29312,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"266606277","text":"import numpy as np\nimport pandas as pd\nimport itertools\nfrom collections import defaultdict\nfrom sklearn.feature_selection import chi2\nimport nltk\nimport string\nimport re\nimport math\nfrom nltk.corpus import stopwords\n\n\n# Positive and negative vocabularies as seed to calculate the pointwise mantual information\n# Combined with different versions, feel free to amend them\npositive_vocab = [\n 'good', 'nice', 'great', 'awesome', 'outstanding',\n 'fantastic', 'terrific', 'like', 'love', 'fortunately', 'excellent']\nnegative_vocab = [\n 'bad', 'terrible', 'crap', 'useless', 'hate', 'poor', 'wrong', 'unfortunately',\n 'dissappointed', 'expensive']\n\n# save the scores\ndef save_txt(score_list,filename, mode='a'):\n file = open(filename, mode)\n for i in range(len(score_list)):\n file.write(str(score_list[i])+'\\n')\n file.close()\n\n\nclass buildDic:\n\n def __init__(self, train):\n \"\"\"\n ('headings are: ', [u'bathrooms', u'bedrooms', u'building_id', u'created', u'description', u'display_address', u'features', u'interest_level', u'latitude', u'listing_id', u'longitude', u'manager_id', u'photos', u'price', u'street_address'])\n \"\"\"\n self.train = train.copy()\n\n self.documents = self.train['description']\n self.documents = list(self.documents)\n self.n_docs = len(self.documents)\n\n # Preprocessing\n new_doc = []\n for description in self.documents:\n # Replace all punctuations and numbers with spaces\n regex = re.compile('[%s]' % re.escape(string.punctuation+\"123456789\"))\n description = description.lower()\n out = regex.sub(' ', description)\n new_doc.append(out)\n\n self.documents = new_doc\n\n u_dic, b_dic = self.build_dic(self.documents)\n print(b_dic)\n p_u, p_b = self.get_probobilities(u_dic, b_dic, self.n_docs)\n print(p_b)\n so = self.get_pmi(p_u, p_b)\n scores = self.calculate_score(so, self.documents)\n print(\"lines of records:\")\n print(len(scores))\n save_txt(scores, 'score.txt')\n\n\n\n # to build unigram freq dic (it means the freq of a word appearing in a document, duplicate ones do not count)\n # and bigram freq dic (it means the freq of 2 words that appear in the same document, duplicate ones will be counted)\n def build_dic(self, documents):\n u_dic = defaultdict(int)\n b_dic = defaultdict(int)\n\n for description in documents:\n\n tem_udic = defaultdict(int)\n\n filtered_words = [word for word in description.split() if word not in stopwords.words('english')]\n for word in filtered_words:\n tem_udic[word] += 1\n for key in tem_udic.keys():\n u_dic[key] += 1\n # new dic for each piece of description\n tem_udic.clear()\n\n # Remove the words with lowest freq (1) from dictionary\n u_dic_cp = u_dic.copy()\n for key, value in u_dic_cp.items():\n if value == 1:\n del u_dic[key]\n\n for description in documents:\n for word in description.split():\n tem_udic[word] += 1\n for key in tem_udic.keys():\n u_dic[key] += 1\n for second_key in tem_udic.keys():\n if key != second_key:\n b_dic[(key, second_key)] += 1\n # new dic for each piece of description\n tem_udic.clear()\n\n return u_dic, b_dic\n\n def get_probobilities(self, u_dic, b_dic, n_docs):\n\n p_u = defaultdict(float)\n p_b = defaultdict(float)\n\n for term, n in u_dic.items():\n p_u[term] = n / n_docs\n for key in list(b_dic.keys()):\n term2 = key[1]\n if term != term2:\n p_b[(term, term2)] = b_dic[(term, term2)] / n_docs\n\n return p_u, p_b\n\n # Algorithm of PMI\n def get_pmi(self, p_u, p_b):\n pmi = defaultdict(float)\n for t1 in p_u:\n for t2 in p_u:\n if t1 != t2:\n m = p_u[t1] * p_u[t2]\n pmi[(t1, t2)] = math.log2(p_b[(t1, t2)] / m)\n\n semantic_orientation = {}\n for term, n in p_u.items():\n positive_assoc = sum(pmi[(term, tx)] for tx in positive_vocab)\n negative_assoc = sum(pmi[(term, tx)] for tx in negative_vocab)\n\n #if the sum is larger then 0, positive; 0, neutral; otherwise, negative\n semantic_orientation[term] = positive_assoc - negative_assoc\n\n return semantic_orientation\n\n\n # Calculate the sentiment orientation score by summing up every words scores\n def calculate_score(self, so, documents):\n score_list = []\n for description in documents:\n score = 0.0\n for word in description.split():\n score += so[word]\n score_list.append(score)\n return score_list\n\nif __name__ == \"__main__\":\n\n train_file = './train.json'\n test_file = './test.json'\n\n # read in the training and test data\n train = pd.read_json(train_file)\n test = pd.read_json(test_file)\n\n buildDic(train)\n\n","sub_path":"SO_Score.py","file_name":"SO_Score.py","file_ext":"py","file_size_in_byte":5186,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"135009762","text":"import collections\n\n\nclass LRUCache:\n \"\"\" Simple Least Recently Used caching implementation. \"\"\"\n def __init__(self, capacity):\n self.capacity = capacity\n self.cache = collections.OrderedDict()\n\n def get(self, key):\n \"\"\" Update the order or return a fetch error. \"\"\"\n try:\n value = self.cache.pop(key)\n self.cache[key] = value\n return value\n except KeyError:\n return False\n\n def set(self, key, value):\n \"\"\" Update the order or add a new value.\n Will remove old values from the cache if we reached our maximum capacity.\"\"\"\n try:\n self.cache.pop(key)\n except KeyError:\n if len(self.cache) >= self.capacity:\n self.cache.popitem(last=False)\n self.cache[key] = value","sub_path":"watchmen/cache.py","file_name":"cache.py","file_ext":"py","file_size_in_byte":828,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"491406425","text":"import time\nimport yaml\nimport threading\n\nfrom netmiko import ConnectHandler\n\nstart_time = time.time()\n\nCOMMAND1 = 'yum updateinfo'\nCOMMAND2 = 'yum -y remove cligen\\* clixon\\* davici\\* frr\\* kea-libs kea libevent\\* libikemgmt\\* libnfmgmt\\* libnl3\\* ' \\\n 'libnlmgmt\\* libntpmgmt\\* librtnl\\* libvppmgmt\\* netgate-strongswan\\* nftables\\* nginx\\* router-plugin\\* ' \\\n 'snmp-subagent\\* tnsr\\* unbound\\* vpp\\* '\nCOMMAND3 = 'sudo yum -y remove firewalld-filesystem'\nCOMMAND4 = 'sudo yum clean all'\nCOMMAND5 = 'sudo yum -y install tnsr tnsr-config-hw.x86_64'\n\ndevices = yaml.load(open('devices.yaml'))\n\n\ndef connect_ssh(device_dict, command):\n with ConnectHandler(**device_dict) as ssh:\n ssh.enable()\n result = ssh.send_command(command)\n\n print('Connection to device {}'.format(device_dict['ip']))\n # print(result)\n\n\ndef conn_threads(function, devices, command):\n threads = []\n for device in devices:\n th = threading.Thread(target=function, args=(device, command))\n th.start()\n threads.append(th)\n\n for th in threads:\n th.join()\n\n\nconn_threads(connect_ssh, devices['routers'], COMMAND1)\nprint('1==============================================')\nconn_threads(connect_ssh, devices['routers'], COMMAND2)\nprint('2==============================================')\nconn_threads(connect_ssh, devices['routers'], COMMAND3)\nprint('3==============================================')\nconn_threads(connect_ssh, devices['routers'], COMMAND4)\nprint('4==============================================')\nconn_threads(connect_ssh, devices['routers'], COMMAND5)\nprint('5==============================================')\n\nprint(\"--- %s seconds ---\" % (time.time() - start_time))\n\n\n\n\n\n\n\n\n\n# import threading\n# import paramiko\n#\n# host = '127.0.0.1'\n# user = 'root'\n# secret = 'qwerty'\n#\n# class AllowAnythingPolicy(paramiko.MissingHostKeyPolicy):\n# def missing_host_key(self, client, hostname, key):\n# return\n#\n# client = paramiko.SSHClient()\n# client.set_missing_host_key_policy(AllowAnythingPolicy())\n# client.connect(hostname=host, username=user, password=secret, port=2251)\n#\n# def read_until_EOF(fileobj):\n# s = fileobj.readline()\n# while s:\n# print(s.strip())\n# s = fileobj.readline()\n#\n# out1 = client.exec_command('echo One;sleep 2;echo Two;sleep 1;echo Three')[1]\n# out2 = client.exec_command('echo A;sleep 1;echo B;sleep 2;echo C')[1]\n# thread1 = threading.Thread(target=read_until_EOF, args=(out1,))\n# thread2 = threading.Thread(target=read_until_EOF, args=(out2,))\n# thread1.start()\n# thread2.start()\n# thread1.join()\n# thread2.join()\n#\n# client.close()\n\n\n\n\n\n\n\n\n\n\n#\n#\n# from threading import Thread\n# import paramiko\n# import time\n#\n#\n# host = '127.0.0.1'\n# user = 'root'\n# secret = 'qwerty'\n#\n# start_time = time.time()\n# def ssh_version(port):\n# client = paramiko.SSHClient()\n# client.set_missing_host_key_policy(paramiko.AutoAddPolicy())\n# client.connect(hostname=host, username=user, password=secret, port=port)\n# stdin, stdout, stderr = client.exec_command('yum updateinfo')\n# stdin.close()\n# for line in stdout.read().splitlines():\n# print(line)\n# client.close()\n#\n# PB1 = Thread(target=ssh_version(2251))\n# PB2 = Thread(target=ssh_version(2260))\n# PB3 = Thread(target=ssh_version(2270))\n#\n# PB1.start()\n# PB2.start()\n# PB3.start()\n# PB1.join()\n# PB2.join()\n# PB3.join()\n# print(\"--- %s seconds ---\" % (time.time() - start_time))\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# # def prescript(thefile, num):\n# # with open(thefile, 'w') as f:\n# # for i in range(num):\n# # if num > 500:\n# # f.write('МногоБукв\\n')\n# # else:\n# # f.write('МалоБукв\\n')\n# #\n# #\n# # thread1 = Thread(target=prescript, args=('f1.txt', 200,))\n# # thread2 = Thread(target=prescript, args=('f2.txt', 1000,))\n# #\n# # thread1.start()\n# # thread2.start()\n# # thread1.join()\n# # thread2.join()\n#\n#\n# # import logging\n# # import threading\n# #\n# #\n# # def get_logger():\n# # logger = logging.getLogger(\"threading_example\")\n# # logger.setLevel(logging.DEBUG)\n# #\n# # fh = logging.FileHandler(\"threading.log\")\n# # fmt = '%(asctime)s - %(threadName)s - %(levelname)s - %(message)s'\n# # formatter = logging.Formatter(fmt)\n# # fh.setFormatter(formatter)\n# #\n# # logger.addHandler(fh)\n# # return logger\n# #\n# #\n# # def doubler(number, logger):\n# # \"\"\"\n# # A function that can be used by a thread\n# # \"\"\"\n# # logger.debug('doubler function executing')\n# # result = number * 2\n# # logger.debug('doubler function ended with: {}'.format(result))\n# #\n# #\n# # if __name__ == '__main__':\n# # logger = get_logger()\n# # thread_names = ['Mike', 'George', 'Wanda', 'Dingbat', 'Nina']\n# # for i in range(5):\n# # my_thread = threading.Thread(\n# # target=doubler, name=thread_names[i], args=(i, logger))\n# # my_thread.start()\n# #\n# #\n# #\n# # # import threading\n# # #\n# # #\n# # # def doubler(number):\n# # # \"\"\"\n# # # A function that can be used by a thread\n# # # \"\"\"\n# # # print(threading.currentThread().getName() + '\\n')\n# # # print(number * 2)\n# # # print()\n# # #\n# # #\n# # # if __name__ == '__main__':\n# # # for i in range(5):\n# # # my_thread = threading.Thread(target=doubler, args=(i,))\n# # # my_thread.start()\n# # #\n# #\n# #\n# #\n# # # from multiprocessing.pool import ThreadPool\n# # # import paramiko\n# # # hosts = []\n# # # hostnames = []\n# # #\n# # #\n# # # def capture_travelinfo(host):\n# # # ssh = paramiko.SSHClient()\n# # # ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())\n# # # print('Connecting to ' + host)\n# # # ssh.connect(host, username='root', password='qwerty')\n# # # print('Connected to ' + host)\n# # # stdin, stdout, stderr = ssh.exec_command('uname')\n# # # stdin.close()\n# # # ssh.close()\n# # #\n# # #\n# # # def main():\n# # # ips = open('IPs.txt')\n# # # pool = ThreadPool(5)\n# # # for ip in ips:\n# # # fields = ip.strip().split()\n# # # UNIT = [fields[0], fields[1]]\n# # # hosts.append(UNIT)\n# # # for ip in hosts:\n# # # hostnames.append(ip[1])\n# # # results = pool.map(capture_travelinfo, hostnames)\n# # # pool.close()\n# # # pool.join()\n# # # print(results)","sub_path":"Stepik_Python Programming by Python/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":6403,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"564814858","text":"#!/usr/bin/env python3\nimport numpy as np\nimport socket\nimport atexit\n\nfrom subprocess import check_output\nfrom time import time, sleep\n\nfrom pyscreenshot import grab\nfrom PIL import Image\nfrom scipy.misc import imresize\nfrom skimage.color import rgb2hsv, hsv2rgb\nfrom mss import mss\n\n\ndef grab_im(sct, monitor):\n res = sct.grab(monitor)\n im = np.frombuffer(res.rgb, dtype='uint8')\n im.resize((res.size.height, res.size.width, 3))\n return im\n\n# # Amount to reduce the height of the image by before processing\n# COLUMN_RED = 300\n# Number of leds\nNUM_LEDS = 120\n\ndef process_im(im):\n # im = imresize(im, (COLUMN_RED, NUM_LEDS)) # Reduce image\n # im = rgb2hsv(im) # Convert to HSV\n # idx_x = np.arange(NUM_LEDS)\n # idx_y = np.arange(COLUMN_RED)\n # im_sat = im[:,:,1]\n # im_val = im[:,:,2]\n # arg_y = np.argsort(im_sat, axis=0)\n # sat_w = (1-arg_y/COLUMN_RED)\n # im_val *= sat_w\n # im = hsv2rgb(im) # Convert to RGB\n im = imresize(im, (1, NUM_LEDS)) # Collapse columns\n im //= 4 # Reduce intensity\n im = im[:,:,[1,0,2]] # Convert to GRB\n return im\n\nIP = \"192.168.1.7\"\nPORT = 4242\nSSID = \"UrAWizardHarry\"\nFPS = 5\n\ndef at_home():\n try:\n return SSID in str(check_output(['iwgetid']))\n except:\n return False\n\ndef display_on():\n return True\n\ndef turn_off_leds():\n if at_home():\n sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)\n sock.sendto(np.zeros(NUM_LEDS).tobytes(), (IP, PORT))\n\natexit.register(turn_off_leds)\n\ndef frame_limiter(fps):\n period = 1/fps\n then = time()\n while True:\n then += period\n yield\n while True:\n delta = then - time()\n if delta <= 0:\n break\n sleep(delta)\n\n\ndef start_ambient():\n sct = mss()\n monitor = sct.monitors[0]\n try:\n sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)\n for _ in frame_limiter(FPS):\n row = process_im(grab_im(sct, monitor))\n sock.sendto(row.tobytes(), (IP, PORT))\n except KeyboardInterrupt as e:\n turn_off_leds()\n raise e\n except OSError as e:\n print(\"Disconnected.\")\n finally:\n sock.close()\n\ndef main():\n while True:\n while not at_home() or not display_on():\n pass\n start_ambient()\n\nif __name__ == '__main__':\n main()\n","sub_path":"utilities/.local/bin/led-ambient.py","file_name":"led-ambient.py","file_ext":"py","file_size_in_byte":2355,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"193426852","text":"\n# coding: utf-8\n\n# In[2]:\n\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport pandas as pd\nfrom mpl_toolkits.basemap import Basemap\nfrom matplotlib.collections import PatchCollection\nimport json\nimport datetime\nfrom geopy.geocoders import Nominatim\nimport matplotlib.font_manager as fm\n\nget_ipython().magic(u'matplotlib inline')\n\n\n# In[3]:\n\ndf = pd.read_csv('data.csv')\ndf['Date'] = pd.to_datetime(df['Date'])\n\n\n# In[4]:\n\nparams = {'axes.labelsize': 10,\n 'lines.markersize': 4,\n 'font.size': 18,\n 'lines.markeredgewidth':1,\n 'axes.linewidth':1.2,\n 'legend.fontsize': 7,\n 'xtick.labelsize': 10,\n 'ytick.labelsize': 10,\n 'savefig.dpi': 300,\n 'font.family': 'sans-serif',\n 'font.sans-serif': 'Tahoma',\n 'axes.color_cycle': ['b', 'r', 'purple', 'g', 'c', 'm', 'orange', 'darkblue', \\\n 'darkcyan', 'y','orangered','chartreuse','brown','deeppink','lightgreen', 'k']}\n\nplt.rcParams.update(params)\n\n\n# In[9]:\n\ngeolocator = Nominatim()\nnum_frames = 0 \nfig = plt.figure(figsize=(18,12))\nm = Basemap(projection='merc',llcrnrlat=20,urcrnrlat=50,llcrnrlon=-130,urcrnrlon=-60,lat_ts=20,resolution='i')\nm.drawmapboundary(fill_color='#EBF4FA')\nm.drawcoastlines()\nm.drawstates()\nm.drawcountries()\nm.fillcontinents()\ntitle = plt.title('Mass Shootings in America (1990-2015)', fontsize=42, y=1.04)\nfor i, iterate_date in enumerate(pd.date_range(min(df['Date']), max(df['Date']))): #there has to be a better way to do this. \n flag = False\n for j, shooting_date in df['Date'].iteritems():\n if(iterate_date.date() == shooting_date.date()):\n flag = True\n location = geolocator.geocode(df['Location'][j], timeout=25)\n relative_size = df['Total Number of Victims'][j]/np.mean(df['Total Number of Victims'])\n if relative_size > 2:\n m.plot(*m(location.longitude, location.latitude), marker='o', ms=50, alpha=0.3)\n elif relative_size < 0.5:\n m.plot(*m(location.longitude, location.latitude), marker='o', ms=13, alpha=0.4)\n else:\n m.plot(*m(location.longitude, location.latitude), marker='o', ms=relative_size*18, alpha=0.4)\n text = plt.annotate('Year: %d' % iterate_date.date().year, xy=(0.75, 0.25), xycoords='axes fraction', fontsize=30, horizontalalignment='left', verticalalignment='bottom')\n plt.savefig('/Users/harshilkamdar/gif/%s.png' % num_frames)\n text.remove()\n num_frames = num_frames + 1\n if(i%10 == 0 and flag == False):\n text = plt.annotate('Year: %d' % iterate_date.date().year, xy=(0.75, 0.25), xycoords='axes fraction', fontsize=30, horizontalalignment='left', verticalalignment='bottom')\n plt.savefig('/Users/harshilkamdar/gif/%s.png' % num_frames)\n text.remove()\n num_frames = num_frames + 1\n\n\n# In[ ]:\n\nget_ipython().system(u'ffmpeg -framerate 60 -i %d.png -s:v 1280x720 -c:v libx264 -profile:v high -crf 20 -pix_fmt yuv420p output.mp4')\nget_ipython().system(u'ffmpeg -v warning -i output.mp4 -vf \"fps=30,scale=1080:-1:flags=lanczos,palettegen\" -y \"/tmp/palette.png\"')\nget_ipython().system(u'ffmpeg -v warning -i output.mp4 -i /tmp/palette.png -lavfi \"fps=30,scale=1080:-1:flags=lanczos [x]; [x][1:v] paletteuse\" -y output.gif')\n\n","sub_path":"Map.py","file_name":"Map.py","file_ext":"py","file_size_in_byte":3338,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"437667997","text":"#!/user/bin/python\n# -* - coding:UTF-8 -*-\n\n# File Name: MyMaterial.py\n\n\n\n\n\n# 导入material模块。\nimport material\n\n# 创建材料。\nmyMaterial = myModel.Material(name='Q345')\n\n# 定义弹性材料属性,杨氏模量为2.09E11,泊松比为0.3。\nelasticProperties = (2.09E11, 0.3)\nmyMaterial.Elastic(table=(elasticProperties, ) )\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n","sub_path":"Abaqus/MyMaterial.py","file_name":"MyMaterial.py","file_ext":"py","file_size_in_byte":354,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"638491509","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.db import migrations, models\nfrom django.utils.timezone import utc\nimport datetime\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('landing', '0001_initial'),\n ]\n\n operations = [\n migrations.AlterModelOptions(\n name='flower',\n options={'verbose_name': 'Букет', 'verbose_name_plural': 'Букеты'},\n ),\n migrations.AddField(\n model_name='order',\n name='date',\n field=models.DateTimeField(default=datetime.datetime(2016, 3, 5, 15, 22, 23, 154785, tzinfo=utc)),\n ),\n ]\n","sub_path":"landing/migrations/0002_auto_20160305_1822.py","file_name":"0002_auto_20160305_1822.py","file_ext":"py","file_size_in_byte":667,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"256426305","text":"import sys\nsys.stdin = open('15681_트리와 쿼리.txt', 'r')\ninput = lambda: sys.stdin.readline().strip()\nsys.setrecursionlimit(10**9)\n\n\ndef count_node(parent):\n node_count[parent] = 1\n for child in tree[parent]:\n if not node_count[child]:\n count_node(child)\n node_count[parent] += node_count[child]\n\n\nN, R, Q = map(int, input().split())\ntree = {i+1: [] for i in range(N)}\nnode_count = [0] * (N+1)\nfor _ in range(N-1):\n U, V = map(int, input().split())\n tree[U].append(V)\n tree[V].append(U)\n\ncount_node(R)\n\nfor _ in range(Q):\n node = int(input())\n print(node_count[node])\n","sub_path":"BaekJoon/분류 안 된 문제들/트리에서의 다이나믹 프로그래밍/15681_트리와 쿼리.py","file_name":"15681_트리와 쿼리.py","file_ext":"py","file_size_in_byte":624,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"300270439","text":"import keras.backend as K\nfrom segmentation_models import FPN\nimport os\nfrom albumentations import (HorizontalFlip, ShiftScaleRotate, OneOf, Compose, RandomBrightnessContrast, RandomCrop)\nfrom keras.optimizers import Adam\nfrom keras.callbacks import ModelCheckpoint, ReduceLROnPlateau\nfrom keras.layers import Input\nimport sys\nimport argparse\nfrom losses import dice_coef, dice_loss, jaccard_coef, custom_loss, mean_iou\n\nparser = argparse.ArgumentParser()\nparser.add_argument('--path', help='Path to dataset', default='data')\nparser.add_argument('--backbone', help='Backbone name')\nargs = parser.parse_args()\n\npath = os.path.abspath(__file__)\npathes = path.split('\\\\')\nsys.path.append(os.path.abspath('\\\\'.join(pathes[:-2])))\nfrom DLUtils.seg_data_generator import SegDataGenerator\n\nTRAIN_PATH = os.path.join(args.path, 'seg_train_images')\nANNO_PATH = os.path.join(args.path, 'seg_train_annotations')\nCLASS_COLOR = {\n 'Car': [0, 0, 255],\n 'Bus': [193, 214, 0],\n 'Truck': [180, 0, 129],\n 'SVehicle': [255, 121, 166],\n 'Pedestrian': [255, 0, 0],\n 'Motorbike': [65, 166, 1],\n 'Bicycle': [208, 149, 1],\n 'Signal': [255, 255, 0],\n 'Signs': [255, 134, 0],\n 'Sky': [0, 152, 225],\n 'Building': [0, 203, 151],\n 'Natural': [85, 255, 50],\n 'Wall': [92, 136, 125],\n 'Lane': [69, 47, 142],\n 'Ground': [136, 45, 66],\n 'Sidewalk': [0, 255, 255],\n 'RoadShoulder': [215, 0, 255],\n 'Obstacle': [180, 131, 135],\n 'others': [81, 99, 0],\n 'own': [86, 62, 67]\n}\nSEED = 42\nIMG_HEIGHT, IMG_WIDTH = 256, 256\n\n\ndef strong_aug(p=0.5):\n return Compose([\n OneOf([\n ShiftScaleRotate(p=0.5, rotate_limit=10, scale_limit=0),\n HorizontalFlip(p=0.5)\n ]),\n RandomBrightnessContrast(p=0.5),\n RandomCrop(p=1, height=IMG_HEIGHT, width=IMG_WIDTH)\n ], p=p)\n\n\ndef make_aug(image, mask, p):\n augmentation = strong_aug(p=p)\n data = {'image': image, 'mask': mask}\n augmented = augmentation(**data)\n return augmented['image'], augmented['mask']\n\n\nif __name__ == '__main__':\n generator = SegDataGenerator(TRAIN_PATH, ANNO_PATH, batch_size=2, input_shape=(IMG_HEIGHT, IMG_WIDTH, 3),\n mask_shape=(IMG_HEIGHT, IMG_WIDTH, len(CLASS_COLOR)), preprocessing_function=make_aug,\n classes_colors=CLASS_COLOR, prob_aug=1)\n input_layer = Input(shape=(IMG_HEIGHT, IMG_WIDTH, 3))\n model = FPN(\n backbone_name=args.backbone,\n input_tensor=input_layer,\n encoder_weights='imagenet',\n classes=len(CLASS_COLOR),\n use_batchnorm=True,\n dropout=0.25,\n activation='softmax'\n )\n\n save_name = 'weights/' + args.backbone + '.h5'\n callbacks_list = [\n ModelCheckpoint(\n save_name,\n monitor='loss',\n verbose=1,\n save_best_only=True,\n mode='min',\n save_weights_only=True),\n ReduceLROnPlateau(\n monitor='loss',\n factor=0.2,\n patience=2,\n min_lr=1e-5)\n ]\n\n model.compile(optimizer=Adam(1e-4), loss=custom_loss, metrics=[dice_coef, jaccard_coef, mean_iou])\n\n history = model.fit_generator(generator,\n steps_per_epoch=3000,\n epochs=10,\n verbose=1,\n callbacks=callbacks_list)\n\n model_json = model.to_json()\n json_file = open('models/' + args.backbone + '.json', 'w')\n json_file.write(model_json)\n json_file.close()\n print('Model saved!')\n\n K.clear_session()\n print('Cache cleared')\n","sub_path":"train.py","file_name":"train.py","file_ext":"py","file_size_in_byte":3646,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"639231810","text":"#!/usr/bin/python\n\n\n\"\"\"\n@author: Michael Rapp (mrapp@ke.tu-darmstadt.de)\n\"\"\"\nimport logging as log\nimport os.path as path\nfrom abc import ABC, abstractmethod\nfrom timeit import default_timer as timer\n\nfrom sklearn.model_selection import KFold\n\nfrom rl.testbed.data import MetaData, load_data_set_and_meta_data, load_data_set, one_hot_encode\nfrom rl.testbed.interfaces import Randomized\nfrom rl.testbed.io import SUFFIX_ARFF, SUFFIX_XML, get_file_name\n\n\nclass DataSet:\n \"\"\"\n Stores the properties of a data set to be used for training and evaluating multi-label classifiers.\n \"\"\"\n\n def __init__(self, data_dir: str, data_set_name: str, use_one_hot_encoding: bool):\n \"\"\"\n :param data_dir: The path of the directory where the data set is located\n :param data_set_name: The name of the data set\n :param use_one_hot_encoding: True, if one-hot-encoding should be used to encode nominal attributes, False\n otherwise\n \"\"\"\n self.data_dir = data_dir\n self.data_set_name = data_set_name\n self.use_one_hot_encoding = use_one_hot_encoding\n\n\nclass CrossValidation(Randomized, ABC):\n \"\"\"\n A base class for all classes that use cross validation or a train-test split to train and evaluate a multi-label\n classifier or ranker.\n \"\"\"\n\n def __init__(self, data_set: DataSet, num_folds: int, current_fold: int):\n \"\"\"\n :param data_set: The properties of the data set to be used\n :param num_folds: The total number of folds to be used by cross validation or 1, if separate training and\n test sets should be used\n :param current_fold: The cross validation fold to be performed or -1, if all folds should be performed\n \"\"\"\n self.data_set = data_set\n self.num_folds = num_folds\n self.current_fold = current_fold\n\n def run(self):\n start_time = timer()\n num_folds = self.num_folds\n\n if num_folds > 1:\n self.__cross_validate(num_folds)\n else:\n self.__train_test_split()\n\n end_time = timer()\n run_time = end_time - start_time\n log.info('Successfully finished after %s seconds', run_time)\n\n def __cross_validate(self, num_folds: int):\n \"\"\"\n Performs n-fold cross validation.\n\n :param num_folds: The total number of cross validation folds\n \"\"\"\n current_fold = self.current_fold\n log.info('Performing ' + (\n 'full' if current_fold < 0 else ('fold ' + str(current_fold + 1) + ' of')) + ' %s-fold cross validation...',\n num_folds)\n data_set = self.data_set\n data_set_name = data_set.data_set_name\n x, y, meta_data = load_data_set_and_meta_data(data_set.data_dir, get_file_name(data_set_name, SUFFIX_ARFF),\n get_file_name(data_set_name, SUFFIX_XML))\n\n if data_set.use_one_hot_encoding:\n x, _, meta_data = one_hot_encode(x, y, meta_data)\n\n # Cross validate\n if current_fold < 0:\n first_fold = 0\n last_fold = num_folds - 1\n else:\n first_fold = current_fold\n last_fold = current_fold\n\n i = 0\n k_fold = KFold(n_splits=num_folds, random_state=self.random_state, shuffle=True)\n\n for train_indices, test_indices in k_fold.split(x, y):\n if current_fold < 0 or i == current_fold:\n log.info('Fold %s / %s:', (i + 1), num_folds)\n\n # Create training set for current fold\n train_x = x[train_indices]\n train_y = y[train_indices]\n\n # Create test set for current fold\n test_x = x[test_indices]\n test_y = y[test_indices]\n\n # Train & evaluate classifier\n self._train_and_evaluate(meta_data, train_indices, train_x, train_y, test_indices, test_x, test_y,\n first_fold=first_fold, current_fold=i, last_fold=last_fold,\n num_folds=num_folds)\n\n i += 1\n\n def __train_test_split(self):\n \"\"\"\n Trains the classifier used in the experiment on a training set and validates it on a test set.\n \"\"\"\n\n log.info('Using separate training and test sets...')\n\n # Load training data\n data_set = self.data_set\n data_dir = data_set.data_dir\n data_set_name = data_set.data_set_name\n use_one_hot_encoding = data_set.use_one_hot_encoding\n train_arff_file_name = get_file_name(data_set_name + '-train', SUFFIX_ARFF)\n train_arff_file = path.join(data_dir, train_arff_file_name)\n test_data_exists = True\n\n if not path.isfile(train_arff_file):\n train_arff_file_name = get_file_name(data_set_name, SUFFIX_ARFF)\n log.warning('File \\'' + train_arff_file + '\\' does not exist. Using \\'' +\n path.join(data_dir, train_arff_file_name) + '\\' instead!')\n test_data_exists = False\n\n train_x, train_y, meta_data = load_data_set_and_meta_data(data_dir, train_arff_file_name,\n get_file_name(data_set_name, SUFFIX_XML))\n\n if use_one_hot_encoding:\n train_x, encoder, meta_data = one_hot_encode(train_x, train_y, meta_data)\n else:\n encoder = None\n\n # Load test data\n if test_data_exists:\n test_x, test_y = load_data_set(data_dir, get_file_name(data_set_name + '-test', SUFFIX_ARFF), meta_data)\n\n if encoder is not None:\n test_x, _ = one_hot_encode(test_x, test_y, meta_data, encoder=encoder)\n else:\n log.warning('No test data set available. Model will be evaluated on the training data!')\n test_x = train_x\n test_y = train_y\n\n # Train and evaluate classifier\n self._train_and_evaluate(meta_data, None, train_x, train_y, None, test_x, test_y, first_fold=0,\n current_fold=0, last_fold=0, num_folds=1)\n\n @abstractmethod\n def _train_and_evaluate(self, meta_data: MetaData, train_indices, train_x, train_y, test_indices, test_x, test_y,\n first_fold: int, current_fold: int, last_fold: int, num_folds: int):\n \"\"\"\n The function that is invoked to build a multi-label classifier or ranker on a training set and evaluate it on a\n test set.\n\n :param meta_data: The meta data of the training data set\n :param train_indices: The indices of the training examples or None, if no cross validation is used\n :param train_x: The feature matrix of the training examples\n :param train_y: The label matrix of the training examples\n :param test_indices: The indices of the test examples or None, if no cross validation is used\n :param test_x: The feature matrix of the test examples\n :param test_y: The label matrix of the test examples\n :param first_fold: The first fold or 0, if no cross validation is used\n :param current_fold: The current fold starting at 0, or 0 if no cross validation is used\n :param last_fold: The last fold or 0, if no cross validation is used\n :param num_folds: The total number of cross validation folds or 1, if no cross validation is used\n \"\"\"\n pass\n","sub_path":"python/rl/testbed/training.py","file_name":"training.py","file_ext":"py","file_size_in_byte":7576,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"503193685","text":"# PyMsSql.py\n\nfrom SqlConnWrapper import SqlConnWrapper\nimport pymssql as mdb\nimport pandas as pd\n\n\nclass PyMsSql(SqlConnWrapper):\n \"\"\" class as the base Wrapper class for SQL data access\n\n Attributes\n ==========\n conn_str: string\n The connection string to the SQL data base\n\n Methods\n =======\n execute_query:\n Execute a input sql query and return the result\n execute_query_as_df:\n Execute a input sql query and return a Pandas data frame\n \"\"\"\n\n def __init__(self, conn_info):\n super(PyMsSql, self).__init__(conn_info)\n\n def __enter__(self):\n self.conn = mdb.connect(\n server=self.conn_info.db_host, user=self.conn_info.db_user,\n password=self.conn_info.db_pass, database=self.conn_info.db_name,\n autocommit=True\n )\n\n return self\n\n def __exit__(self, obj_type, value, traceback):\n if self.conn is not None:\n self.conn.close()\n\n def execute_query(self, query):\n\n fail_cnt = 0\n\n while True:\n try:\n with self.conn.cursor() as cur:\n cur.execute(query)\n data = cur.fetchall()\n\n return data\n except mdb.InterfaceError:\n fail_cnt += 1\n\n if fail_cnt > 10:\n return None\n\n def execute_query_as_df(self, query):\n df = pd.read_sql(sql=query, con=self.conn, parse_dates=True)\n\n return df\n","sub_path":"PythonCodeBase/SqlConnWraper/PyMsSql.py","file_name":"PyMsSql.py","file_ext":"py","file_size_in_byte":1482,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"316752477","text":"import numpy as np\nimport os\nimport six\nimport time\nimport multiprocessing\n\nimport paddle\nimport paddle.fluid as fluid\nimport paddle.fluid.profiler as profiler\n\nfrom pyramid_dnn_net import net\nfrom pyramid_dnn_net import test_net\nimport reader\n\ndef train(num_pass=300, use_cuda=False, mem_opt=False):\n dict_size = 100000\n hash_size = 100000\n print_iter = 100\n eval_iter = 1\n batch_size = 128\n cpu_num = int(os.environ.get('CPU_NUM', multiprocessing.cpu_count()))\n debug = False\n\n fluid.default_startup_program().random_seed = 1\n fluid.default_main_program().random_seed = 1\n np.random.seed = 1\n\n # construct network\n loss, pos_sim, train_program, test_program = net(hash_size=hash_size, dict_size=dict_size)\n\n # optimizer = fluid.optimizer.Adam(learning_rate=1e-4)\n optimizer = fluid.optimizer.SGD(learning_rate=1e-4)\n optimizer.minimize(loss)\n\n # memory optimize\n if mem_opt:\n fluid.memory_optimize(fluid.default_main_program())\n\n for var in train_program.blocks[0].vars:\n # if \"GRAD\" not in var and not train_program.blocks[0].var(var).is_data:\n # if not train_program.blocks[0].var(var).is_data:\n train_program.blocks[0].var(var).persistable = True\n print(var, train_program.blocks[0].var(var).persistable, train_program.blocks[0].var(var).shape)\n\n # initialize\n place = fluid.CUDAPlace(0) if use_cuda else fluid.CPUPlace()\n exe = fluid.Executor(place)\n exe.run(fluid.default_startup_program())\n\n print('startup_program', fluid.default_startup_program())\n print('train_program', train_program)\n # print('test_program', test_program)\n\n if debug:\n var_name_list = (\"cos_sim_1.tmp_0@GRAD\", \"fc_2.tmp_1@GRAD\", \"fc_2.tmp_0@GRAD\", \"softsign_2.tmp_0@GRAD\", \"reduce_sum_2.tmp_0@GRAD\", \"stack_2.tmp_0@GRAD\", \"sequence_pool_23.tmp_0@GRAD\", \"sequence_pool_23.tmp_0@GRAD\", \"embedding_23.tmp_0@GRAD\", \"PyramidHash_emb_0@GRAD@RENAME@0\", \"PyramidHash_emb_0@GRAD@RENAME@1\", \"PyramidHash_emb_0@GRAD@RENAME@2\", \"PyramidHash_emb_0@GRAD@RENAME@3\", \"PairwiseMarginLoss_0.tmp_0@GRAD\", \"cos_sim_1.tmp_0\", \"cos_sim_1.tmp_0@GRAD\", \"fc_2.tmp_1@GRAD\", \"fc_2.tmp_0@GRAD\", \"softsign_2.tmp_0@GRAD\", \"reduce_sum_2.tmp_0@GRAD\", \"stack_2.tmp_0@GRAD\", \"sequence_pool_23.tmp_0@GRAD\", \"embedding_23.tmp_0@GRAD\", \"PyramidHash_emb_0@GRAD\", \"FC_1@GRAD\", \"EmbeddingWithVSum_emb_0@GRAD\", \"fc_0.w_0@GRAD\", \"PairwiseMarginLoss_0.tmp_0\", \"PairwiseMarginLoss_0.tmp_1\")\n # var_name_list = (\"sequence_pool_23.tmp_0@GRAD\", \"embedding_23.tmp_0@GRAD\", \"PyramidHash_emb_0@GRAD@RENAME@0\", \"PyramidHash_emb_0@GRAD\", \"FC_1@GRAD\", \"EmbeddingWithVSum_emb_0@GRAD\", \"fc_0.w_0@GRAD\", \"PairwiseMarginLoss_0.tmp_0\", \"PairwiseMarginLoss_0.tmp_1\")\n for name in var_name_list:\n train_program.blocks[0].var(name).persistable = True\n print('find var', name, train_program.blocks[0].var(name).persistable)\n\n # PE\n exec_strategy = fluid.ExecutionStrategy()\n exec_strategy.use_cuda = use_cuda\n exec_strategy.allow_op_delay = True\n exec_strategy.num_threads = 1\n # exec_strategy.num_threads = int(os.environ.get('THREAD_NUM', 1)) * cpu_num - 1\n # exec_strategy.num_threads = 25\n exec_strategy.use_experimental_executor = True\n build_strategy = fluid.BuildStrategy()\n build_strategy.reduce_strategy = fluid.BuildStrategy.ReduceStrategy.AllReduce\n # build_strategy.reduce_strategy = fluid.BuildStrategy.ReduceStrategy.Reduce\n # build_strategy.optimize_strategy = fluid.BuildStrategy.OptimizeStrategy.NoLock\n # pass_builder = build_strategy._create_passes_from_strategy()\n # pass_builder.insert_pass(0, \"lock_free_optimize_pass\")\n train_exe = fluid.ParallelExecutor(\n use_cuda=use_cuda,\n loss_name=loss.name,\n main_program=train_program,\n build_strategy=build_strategy,\n exec_strategy=exec_strategy)\n\n test_exe = fluid.ParallelExecutor(\n use_cuda=use_cuda,\n main_program=test_program,\n share_vars_from=train_exe,\n )\n\n # DataFeeder\n feed_var_names = ['query_basic', 'query_phrase', 'pos_title_basic', 'pos_title_phrase', 'neg_title_basic', 'neg_title_phrase', 'label']\n feed_list = [train_program.global_block().var(var_name) for var_name in feed_var_names]\n feeder = fluid.DataFeeder(feed_list, place)\n # batch_train_reader = feeder.decorate_reader(\n # paddle.batch(reader.train_reader, batch_size=batch_size // cpu_num),\n # multi_devices=true)\n batch_train_reader = feeder.decorate_reader(\n paddle.batch(reader.train_reader, batch_size=128),\n multi_devices=True)\n\n test_feed_var_names = ['query_basic', 'query_phrase', 'pos_title_basic', 'pos_title_phrase', 'neg_title_basic', 'neg_title_phrase']\n test_feed_list = [train_program.global_block().var(var_name) for var_name in test_feed_var_names]\n test_feeder = fluid.DataFeeder(test_feed_list, place)\n\n # train\n for epoch in six.moves.xrange(num_pass):\n count = 0\n total_loss = .0\n total_time = .0\n\n read_data_start = time.time()\n for train_data in batch_train_reader():\n read_data_end = time.time()\n # print('read data: ', read_data_end - read_data_start)\n\n if count == 1 and epoch >= 1:\n # if count % eval_iter == 0:\n print('start eval')\n t2 = time.time()\n # with open('./eval_log/train_mini_data_' + str(epoch) + '_' + str(count) + '_' + str(time.time()), 'w') as f:\n with open('./eval_res/z_' + paddle.version.commit + 'sgd_nolock_result_' + str(epoch) + '_' + str(time.time()), 'w') as f:\n test_batch_reader = paddle.batch(\n reader.test_reader,\n # batch_size=cpu_num * 128)\n batch_size=1280)\n for test_data in test_batch_reader():\n qids = []\n labels = []\n data_list = []\n for one_data in test_data:\n qids.append(one_data[0])\n labels.append(int(one_data[-1][0]))\n data_list.append((one_data[1:-1]))\n predicts = test_exe.run(feed=test_feeder.feed(data_list), fetch_list=[pos_sim.name])\n scores = np.array(predicts[0])\n\n for qid, label, score in six.moves.zip(qids, labels, scores):\n f.write(str(qid) + '\\t' + str(score[0]) + '\\t' + str(label) + '\\n')\n\n print('end eval', time.time() - t2)\n\n start = time.time()\n\n\n if epoch == 0 and count == 5:\n profiler.start_profiler(\"CPU\")\n elif epoch == 0 and count == 10:\n profiler.stop_profiler(\"total\", \"/paddle/Pyramid_DNN/fluid/profile\")\n\n t1 = time.time()\n\n cost = train_exe.run(feed=train_data, fetch_list=[loss.name])\n\n total_time += time.time() - t1\n total_loss += np.array(cost[0]).mean()\n count += 1\n\n if debug:\n for name in var_name_list:\n var = np.array(fluid.executor._fetch_var(name, return_numpy=False))\n if name == \"PyramidHash_emb_0@GRAD@RENAME@0\":\n print('fetch var', name, var)\n print('check not zero', name, np.count_nonzero(var))\n\n print('fetch var', name, var)\n print('check nan var', name, np.isnan(var).any())\n print('check inf var', name, np.isinf(var).any())\n\n if count % print_iter == 0:\n print('epoch: %d, batch_id: %d, avg_cost: %s, avg_time: %f' % (epoch, count, total_loss / print_iter, float(total_time) / print_iter))\n import sys\n sys.stdout.flush()\n total_time = .0\n total_loss = .0\n\n read_data_start = time.time()\n\n # end = time.time()\n # print('train time: ', end - start)\n\n # end = time.time()\n # print('epoch time: ', end - start)\n\n\n\nif __name__ == '__main__':\n train()\n\n","sub_path":"PyramidDNN/fluid/train_test.py","file_name":"train_test.py","file_ext":"py","file_size_in_byte":8292,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"512141987","text":"import numpy as np\nimport pymc3 as pm\nimport matplotlib.pyplot as plt\n\nx = np.random.randn(100)\nw, b, s = *np.random.uniform(5,size=2), np.random.uniform(0.1)\nnoise = np.random.randn(x.shape[0])*s\ny = b + w*x + noise\n\n#plt.scatter(x, y)\n\nbasic_model = pm.Model()\n\nwith basic_model:\n weight = pm.Normal('weight', mu=2.5, sd=5)\n bias = pm.Normal('bias', mu=2.5, sd=5)\n sigma = pm.HalfNormal('sigma', sd=1)\n mu = bias + weight*x\n \n Y = pm.Normal('Y_obs', mu=mu, sd=sigma, observed=y)\n\n\nmapParams = pm.find_MAP(model=basic_model)\n\nwith basic_model:\n trace = pm.sample(draws=500, tune=100, chains=3)\n\n\n_ = pm.traceplot(trace)\n\npm.summary(trace)\n\n\nplt.scatter(x, mapParams[\"weight\"]*x + mapParams[\"bias\"]+mapParams[\"sigma\"]*noise)\nplt.scatter(x, y)\nplt.show()","sub_path":"models/Regression/linearRegression.py","file_name":"linearRegression.py","file_ext":"py","file_size_in_byte":774,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"29061624","text":"\"\"\"\nGlass brain plotting in nilearn\n===============================\n\nSee :ref:`plotting` for more plotting functionalities.\n\"\"\"\n\n\n###############################################################################\n# Retrieve the data\nfrom nilearn import datasets\n\nlocalizer_dataset = datasets.fetch_localizer_contrasts(\n [\"left vs right button press\"],\n n_subjects=2,\n get_tmaps=True)\nlocalizer_tmap_filename = localizer_dataset.tmaps[1]\n\n###############################################################################\n# demo glass brain plotting\nfrom nilearn import plotting\n\nplotting.plot_glass_brain(localizer_tmap_filename, threshold=3)\n\nplotting.plot_glass_brain(\n localizer_tmap_filename, title='plot_glass_brain',\n black_bg=True, display_mode='xz', threshold=3)\n\nplotting.show()\n","sub_path":"python/nilearn/2016/4/plot_demo_glass_brain.py","file_name":"plot_demo_glass_brain.py","file_ext":"py","file_size_in_byte":797,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"134071979","text":"guest = ['jike','lorry','miek']\nmessage1 = 'I sincerely invite '\nmessage2 = ' to have dinner with me '\n\nprint('I found a bigger table')\n\nguest.insert(0,'huang')\nguest.insert(2,'red')\nguest.append('write')\n\nfor a in guest:\n print(message1 + a + message2 )\n\nprint('Sorry, we can only invite two people')\n\n\nmessage3 = ':Sorry, we can only invite you'\n\nprint(guest)\n \nwhile len(guest) > 2:\n print(guest.pop() + message3)\nelse:\n print(guest)\n for a in guest:\n print(message1 + a + message2 )\n\nprint(guest)\n\ndel guest\n \n","sub_path":"python3/3/3_6.py","file_name":"3_6.py","file_ext":"py","file_size_in_byte":536,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"613279509","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django import forms\nfrom django.forms.formsets import BaseFormSet, formset_factory\n\n\nfrom bootstrap3.tests import TestForm\n\nRADIO_CHOICES = (\n ('1', 'Radio 1'),\n ('2', 'Radio 2'),\n)\n\nMEDIA_CHOICES = (\n ('Audio', (\n ('vinyl', 'Vinyl'),\n ('cd', 'CD'),\n )\n ),\n ('Video', (\n ('vhs', 'VHS Tape'),\n ('dvd', 'DVD'),\n )\n ),\n ('unknown', 'Unknown'),\n)\n\n\nclass ArticleForm(forms.Form):\n\n title = forms.CharField()","sub_path":"xSite/apps/xLife/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":531,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"240614455","text":"# uncompyle6 version 3.7.4\n# Python bytecode 2.4 (62061)\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.darwin-8.10.1-i386/egg/iqpp/plone/commenting/utils.py\n# Compiled at: 2007-10-06 08:08:40\nfrom Products.CMFCore.utils import getToolByName\nfrom iqpp.plone.commenting.config import ENCODING\n\ndef getMemberInfo(context, member_id, name, email):\n \"\"\"\n \"\"\"\n mtool = getToolByName(context, 'portal_membership')\n if member_id is not None:\n member_id = member_id.encode('utf-8')\n member = mtool.getMemberById(member_id)\n if name != '':\n name = name\n elif member_id != '':\n mi = mtool.getMemberInfo(member_id)\n name = mi and mi['fullname'] or member_id\n else:\n name = 'Anonymous'\n if email != '':\n email = email\n elif member_id != '':\n email = member and member.getProperty('email', '') or ''\n else:\n email = ''\n return {'name': name, 'email': email, 'is_manager': member and member.has_role('Manager')}","sub_path":"pycfiles/iqpp.plone.commenting-0.5.beta.2-py2.4/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":1056,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"513525056","text":"import model.net as net\nimport model.data_loader as data_loader\nimport numpy as np\nimport torch.nn as nn\nimport torch\n\nif __name__ == '__main__':\n\ttest_loader = data_loader.fetch_dataloader('/scidata/fruits-360/Test', batch_size=128)\n\tdevice = torch.device('cuda:1' if torch.cuda.is_available() else 'cpu')\n\tmodel = net.Net()\n\tmodel.load_state_dict(torch.load(\"model.pth\"))\n\tmodel.to(device)\n\tmodel.eval()\n\n\tcorrect, total = 0, 0\n\twith torch.no_grad():\n\t\tfor images, labels in test_loader:\n\t\t\timages, labels = images.to(device), labels.to(device)\n\n\t\t\toutputs = model(images)\n\t\t\t_, predicted = torch.max(outputs.data, 1)\n\t\t\ttotal += labels.size(0)\n\t\t\tcorrect += (predicted == labels).sum().item()\n\n\tprint('Accuracy on test data: {:.4f} %'.format(100 * correct / total))\n\n\n\n","sub_path":"DeepLearning/task1/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":772,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"567472401","text":"\"\"\"\nCircular Permuations\n\"\"\"\nimport time\nimport sys\nfrom itertools import permutations\n\n\ndef instruction_parser(single_string, set_of_guests, list_of_relationships):\n '''parses instruction to foramt (person, gain/lose, integer, person)\n and it creates guest list set'''\n words = single_string.split()\n person_A = words[0]\n person_B = words[-1][:-1] # extra slice to remove '.' at end of name\n if words[2] == 'gain':\n value = int(words[3])\n elif words[2] == 'lose':\n value = -int(words[3])\n else:\n print('parsing error')\n value = 0\n set_of_guests.add(person_A)\n list_of_relationships.append((person_A, person_B, value))\n return None # this is a subroutine, it acts directly on input list\n\n\ndef permuation_creator(set_of_guests):\n '''The itertools.permutations function is wasteful as it returns all\n possible arrangments, ignoring the mirror symetry in the problem\n A, B, C, D is the same as D, C, B, A\n and it igores that the circular symetry\n A, B, C, D is the same as B, C, D, A is the same as C, D, A, B is the same as D, A, B, C\n\n by only accepting permutations that place A at the start we remove some but\n not all of this unnecessary duplication\n we still get A, B, C, D and A, D, C, B which are the same'''\n\n all_possible_permuations = permutations(set_of_guests)\n\n all_possible_permuations_list = [] # shows the full list without placing alice at start (not actually used in code)\n shortened_permutations_list = [] # shows shortened list (is used in code)\n for perm in all_possible_permuations:\n all_possible_permuations_list.append(perm)\n if perm[0] == 'Alice':\n shortened_permutations_list.append(perm)\n return all_possible_permuations_list, shortened_permutations_list\n\n\ndef circular_guest_list_generator(single_arrangment):\n '''later on it is really handy to make a list with the first guest also\n repeated at the end, so change A, B, C, D to A, B, C, D, A\n since my permuations are tuples (which are immutable), to add A at the end I need to make a\n new list object'''\n circular_list = []\n for guest in single_arrangment:\n circular_list.append(guest)\n circular_list.append(single_arrangment[0])\n return circular_list\n\n\ndef single_guest_happiness(guestA, guestB, list_of_relationships):\n '''finds out how happy guest A will be sitting beside guest B'''\n for relationship in list_of_relationships:\n if relationship[0] == guestA:\n if relationship[1] == guestB:\n happyA_value = relationship[2]\n return happyA_value\n\n\ndef pair_relationship_finder(guest1, guest2, list_of_relationships):\n '''returns the combined happiness values when guest 1 and 2 sit beside each other'''\n happiness_guest1 = single_guest_happiness(guest1, guest2, list_of_relationships)\n happiness_guest2 = single_guest_happiness(guest2, guest1, list_of_relationships)\n sum_happiness = happiness_guest1 + happiness_guest2\n return sum_happiness\n\n\ndef happiness_calculation(single_arrangment, list_of_relationships):\n '''This function returns happiness\n it computes the total happiness of all guests at a table for 1 arrangment'''\n happiness = 0\n circular_guest_list = circular_guest_list_generator(single_arrangment)\n for guest1, guest2 in zip(circular_guest_list, circular_guest_list[1:]):\n happiness += pair_relationship_finder(guest1, guest2, list_of_relationships)\n return happiness\n\n\ndef least_happy_pair(single_arrangment, list_of_relationships):\n '''this function finds which pair of people at the table are least happy\n to be next to each other'''\n circular_guest_list = circular_guest_list_generator(single_arrangment)\n least_happy_value = 1000\n for guest1, guest2 in zip(circular_guest_list, circular_guest_list[1:]):\n current_happy = pair_relationship_finder(guest1, guest2, list_of_relationships)\n if current_happy < least_happy_value:\n least_happy_value = current_happy\n least_happy_guest_pair = (guest1, guest2)\n return least_happy_guest_pair\n\n\nif __name__ == \"__main__\":\n start_time = time.time()\n\n if len(sys.argv) != 2:\n print('Correct usage is python file.py puzzle_input.txt')\n\n else:\n relationships_list = []\n guest_set = set()\n with open(sys.argv[1], \"r\") as myfile:\n for instruction in myfile:\n instruction_parser(instruction, guest_set, relationships_list)\n\n # Part 1\n possible_arrangments, useful_arrangments = permuation_creator(guest_set)\n optimal_happiness = -10000000\n index_optimal_arrangment = 0\n for count, arrangment in enumerate(useful_arrangments):\n current_happy = happiness_calculation(arrangment, relationships_list)\n # print('the arrangment {} gives happiness value of {}'.format(arrangment, current_happy))\n if current_happy > optimal_happiness:\n optimal_happiness = current_happy\n index_optimal_arrangment = count\n best_arrangment = useful_arrangments[index_optimal_arrangment]\n print('the optiaml arrangment for part 1 is {}'.format(best_arrangment))\n print('the optimal happiness value for part 1 is {}'.format(optimal_happiness))\n\n #Part 2\n # Find most miserbale pair, then Ill sit between them\n miserable_couple = least_happy_pair(best_arrangment, relationships_list)\n print('sure arent {} and {} looking pretty miserable over there?,\\\n yeah we better save them from each other'.format(miserable_couple[0], miserable_couple[1]))\n new_opt_arrangment = []\n for guest in best_arrangment:\n new_opt_arrangment.append(guest)\n if guest == miserable_couple[0]:\n new_opt_arrangment.append('me')\n print('the optiaml arrangment for part 2 is {}'.format(new_opt_arrangment))\n\n # Update our relationship list and guest list to include me\n for guest in guest_set:\n relationships_list.append((guest, 'me', 0))\n relationships_list.append(('me', guest, 0))\n guest_set.add('me')\n\n # caluclate the new happiness value\n optimal_happiness_2 = happiness_calculation(new_opt_arrangment, relationships_list)\n print('the optimal happiness value for part 2 is {}'.format(optimal_happiness_2))\n\n end_time = time.time()\n duration = end_time - start_time\n\n print('The code took {:.2f} seconds to execute'.format(duration))\n","sub_path":"2015/Day13_part2.py","file_name":"Day13_part2.py","file_ext":"py","file_size_in_byte":6578,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"4880185","text":"#!/usr/bin/python3\n#-*- coding: utf-8 -*-\n\nimport sys\n\nfrom plane_seats import PlaneSeats, FLOOR\n\n\ndef main(input_file):\n with open(input_file, 'r') as f:\n lines = [x.strip() for x in f.readlines()]\n\n matrix_border = [[FLOOR] + list(line) + [FLOOR] for line in lines]\n border_row = [FLOOR] * (len(matrix_border[0]))\n matrix_border = [border_row] + matrix_border + [border_row]\n matrix = PlaneSeats(matrix_border)\n matrix_copy = PlaneSeats(matrix_border)\n\n print('PART 1')\n\n iterations = 0\n while True:\n # Update state\n iterations += 1\n for i in range(1, len(matrix.matrix) - 1):\n for j in range(1, len(matrix.matrix[0]) - 1):\n matrix.matrix[i][j] = matrix_copy.get_cell_next_state_star1(i, j)\n\n if matrix == matrix_copy:\n break\n \n # Swap matrices\n matrix_aux = matrix\n matrix = matrix_copy\n matrix_copy = matrix_aux\n\n print(f'Iteration that repeats a state = {iterations}')\n print(f'Occupied seats: {matrix.get_occupied_seats()}')\n print(f'Empty seats: {matrix.get_empty_seats()}, floor seats: {matrix.get_floor_seats()}')\n\n\n\nif __name__ == \"__main__\":\n main(sys.argv[1])\n","sub_path":"AdventOfCode2020/day11/day11-1.py","file_name":"day11-1.py","file_ext":"py","file_size_in_byte":1226,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"80356886","text":"from typing import List\n\nimport torch\nfrom torch import nn\nimport torch.nn.functional as F\nfrom torch.nn.utils.rnn import pack_padded_sequence, pad_packed_sequence\n\n\nclass WeightDrop(torch.nn.Module):\n def __init__(\n self,\n module: nn.Module,\n weights: List[str],\n dropout: float = 0,\n variational: bool = False,\n ):\n super().__init__()\n self.module = module\n self.weights = weights\n self.dropout = dropout\n self.variational = variational\n self._setup()\n\n def _setup(self):\n for name_w in self.weights:\n print(\"Applying weight drop of {} to {}\".format(self.dropout, name_w))\n w = getattr(self.module, name_w)\n del self.module._parameters[name_w]\n self.module.register_parameter(name_w + \"_raw\", nn.Parameter(w.data))\n\n def _setweights(self):\n for name_w in self.weights:\n raw_w = getattr(self.module, name_w + \"_raw\")\n w = None\n if self.variational:\n mask = torch.ones(raw_w.size(0), 1)\n if raw_w.is_cuda:\n mask = mask.cuda()\n mask = F.dropout(mask, p=self.dropout, training=True)\n w = mask.expand_as(raw_w) * raw_w\n else:\n w = F.dropout(\n raw_w, p=self.dropout, training=self.training\n )\n setattr(self.module, name_w, w)\n\n def forward(self, *args):\n self._setweights()\n return self.module.forward(*args)\n\n\nclass SimpleLSTM(nn.Module):\n def __init__(\n self,\n n_out: int,\n vocab_size: int,\n vectors: torch.Tensor,\n seq_len: int = 100,\n embedding_dim: int = 300,\n hidden_dim: int = 128,\n dropout: float = 0.2,\n bidirectional: bool = False,\n num_layers: int = 1,\n wdrop: float = 0,\n ) -> None:\n super().__init__()\n\n self.n_out = n_out\n self.hidden_dim = hidden_dim\n self.num_layers = num_layers\n self.seq_len = seq_len\n self.embeddings = nn.Embedding.from_pretrained(vectors)\n\n self.lstm = nn.LSTM(\n embedding_dim,\n hidden_dim,\n batch_first=True,\n num_layers=num_layers,\n bidirectional=bidirectional,\n )\n\n if wdrop:\n self.lstm = WeightDrop(self.lstm, [\"weight_hh_l0\"], dropout=wdrop)\n\n self.dropout = nn.Dropout(dropout)\n self.bidirectional = bidirectional\n self.num_directions = 2 if bidirectional else 1\n self.fc = nn.Linear(hidden_dim * self.num_directions, hidden_dim // 2)\n self.fc2 = nn.Linear(hidden_dim // 2, n_out)\n\n def _lstm_forward(self, data, lengths):\n\n embeddings = self.embeddings(data)\n packed = pack_padded_sequence(\n embeddings, lengths, batch_first=True, enforce_sorted=False\n )\n lstm, (h, c) = self.lstm(packed)\n lstm_unpacked = pad_packed_sequence(\n lstm, batch_first=True, total_length=self.seq_len\n )[0]\n return lstm_unpacked, (h, c)\n\n def forward(self, data, lengths):\n\n lstm_unpacked, (h, c) = self._lstm_forward(data, lengths)\n\n # Like output, the layers can be separated\n # using h_n.view(num_layers, num_directions, batch, hidden_size)\n h = h.view(self.num_layers, self.num_directions, -1, self.hidden_dim)\n\n # TODO: Check dimensions for multi-layer!\n if self.bidirectional:\n last_states = torch.cat([h[-1, 0], h[-1, 1]], dim=1)\n else:\n last_states = h[-1, 0]\n\n linear = self.fc(self.dropout(last_states))\n linear2 = self.fc2(self.dropout(linear))\n return linear2\n\n\nclass ConcatPoolLSTM(nn.Module):\n def __init__(\n self,\n n_out: int,\n vocab_size: int,\n vectors: torch.Tensor,\n seq_len: int = 100,\n embedding_dim: int = 300,\n hidden_dim: int = 128,\n dropout: float = 0.2,\n bidirectional: bool = False,\n num_layers: int = 1,\n ) -> None:\n super().__init__()\n\n if bidirectional:\n raise NotImplementedError(\"Does not support bidirectional yet\")\n\n self.n_out = n_out\n self.hidden_dim = hidden_dim\n self.num_layers = num_layers\n self.seq_len = seq_len\n self.embeddings = nn.Embedding.from_pretrained(vectors)\n\n self.lstm = nn.LSTM(\n embedding_dim,\n hidden_dim,\n batch_first=True,\n num_layers=num_layers,\n bidirectional=bidirectional,\n )\n\n self.dropout = nn.Dropout(dropout)\n self.bidirectional = bidirectional\n self.num_directions = 2 if bidirectional else 1\n\n self.fc = nn.Linear(self.hidden_dim * 3, self.hidden_dim // 2)\n self.fc2 = nn.Linear(self.hidden_dim // 2, self.n_out)\n\n def _lstm_forward(self, data, lengths):\n\n embeddings = self.embeddings(data)\n packed = pack_padded_sequence(\n embeddings, lengths, batch_first=True, enforce_sorted=False\n )\n lstm, (h, c) = self.lstm(packed)\n lstm_unpacked = pad_packed_sequence(\n lstm, batch_first=True, total_length=self.seq_len\n )[0]\n return lstm_unpacked, (h, c)\n\n def forward(self, data, lengths):\n lstm_unpacked, (h, c) = self._lstm_forward(data, lengths)\n\n h = h.view(self.num_layers, self.num_directions, -1, self.hidden_dim)\n h = h[-1, 0]\n\n max_pool = F.adaptive_max_pool1d(lstm_unpacked.permute(0, 2, 1), 1).view(\n -1, self.hidden_dim\n )\n avg_pool = F.adaptive_avg_pool1d(lstm_unpacked.permute(0, 2, 1), 1).view(\n -1, self.hidden_dim\n )\n\n concat = torch.cat([h, max_pool, avg_pool], dim=1)\n\n linear = self.fc(self.dropout(concat))\n linear2 = self.fc2(self.dropout(linear))\n\n return linear2\n\n\nclass SimpleCNN(nn.Module):\n def __init__(\n self,\n n_out: int,\n # vocab_size: int,\n vectors: torch.Tensor,\n # seq_len: int = 100,\n embedding_dim: int = 300,\n hidden_dim: int = 128,\n dropout: float = 0.2,\n num_filters: int = 12,\n filter_sizes: List[int] = [1, 3, 5],\n ) -> None:\n super().__init__()\n\n self.embedding_dim = embedding_dim\n self.filter_sizes = filter_sizes\n self.embeddings = nn.Embedding.from_pretrained(vectors)\n self.num_filters = num_filters\n\n self.convs = nn.ModuleList(\n [\n nn.Conv2d(1, num_filters, (K, self.embedding_dim))\n for K in self.filter_sizes\n ]\n )\n\n self.dropout = nn.Dropout(dropout)\n\n self.fc = nn.Linear(len(self.filter_sizes) * self.num_filters, n_out)\n\n def forward(self, data):\n embeddings = self.embeddings(data).unsqueeze(1)\n convs = [F.relu(conv(embeddings)).squeeze(3) for conv in self.convs]\n pooled = [F.max_pool1d(i, i.size(2)).squeeze(2) for i in convs]\n pooled = self.dropout(torch.cat(pooled, 1))\n linear = self.fc(pooled)\n return linear\n","sub_path":"models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":7166,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"526012960","text":"import xml.etree.ElementTree as ET\nfrom collections import defaultdict\nfrom knock53 import xml_parse\n\nif __name__ == '__main__':\n root = xml_parse('nlp.txt.xml')\n ch_list = defaultdict(list)\n for coref in list(root.getiterator('coreference')):\n for sen in list(coref):\n if sen.tag == 'mention':\n if sen.get('representative') == 'true':\n text_ch = sen.findtext('text')\n# print(text_ch)\n else:\n sentence = sen.findtext('sentence')\n start = sen.findtext('start')\n end = sen.findtext('end')\n text = sen.findtext('text')\n text_com = text_ch + ' ( ' + text + ' )'\n ch_list[sentence].append([start,end,text,text_com])\n# print(ch_list)\n for sen in list(root.getiterator('sentence')):\n idx = sen.get('id')\n if not(idx is None):\n str_list = []\n ch = ch_list[idx]\n# print(ch)\n for token in list(sen.getiterator('token')):\n token.get('id')\n str_list.append(token.findtext('word'))\n str_print = ' '.join(str_list)\n for change in ch:\n str_print = str_print.replace(change[2],change[3])\n print(str_print)\n# print(ch_list)\n# if word_.findtext('NER') == 'PERSON':\n# print(word_.findtext('word'))\n","sub_path":"kurosawa/chapter06/knock56.py","file_name":"knock56.py","file_ext":"py","file_size_in_byte":1451,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"1799733","text":"import requests\nfrom bs4 import BeautifulSoup\nfrom lxml import etree\nimport re\n\nmain_url = 'http://you.ctrip.com/searchsite/asks/?query=%E8%87%AA%E9%A9%BE%E6%B8%B8&isAnswered=&isRecommended=&publishDate=&PageNo=1'\npage = 0\nparams = {'kw': '司机', 'ie': 'utf-8', 'pn': page}\nheaders = {'User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.67 Safari/537.36'}\n\nresponse = requests.get(main_url, headers=headers)\nresponse.encoding = \"utf-8\"\n# print(response.url)\ncontent = response.text\n# print(response.status_code)\n# exit()\n# tree = etree.HTML(content)\n# print(tree)\n# lis = tree.xpath('//*[@id=\"thread_list\"]/li[12]/div/div[2]/div[1]/div[1]/a/@href')\n# print(lis)\n# exit(1)\n# print(content)\nsoup = BeautifulSoup(content, 'html.parser')\n# titles = soup.find_all('dt')\ntitles = soup.find_all('a', href=re.compile(r'/asks/.+.html'))\n# print(titles)\n# exit()\nfor title in titles:\n # print(title)\n print(title.get_text())\n print(title['href'])\n print(title.name)\n# print(response.status_code)\n# print(content)\n# exit()\nhrefs = []\nmain_url = 'http://wenda.so.com'\n\n# page = 0\n# while True:\n# params = {'q': u'粤通卡', 'pn': page}\n# headers = {\n# 'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_5) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/11.1.1 Safari/605.1.15'}\n# response = requests.get(main_url + '/search/', params, headers=headers)\n# time.sleep(3)\n# if response.status_code == 200:\n# html = response.text\n# tree = etree.HTML(html)\n# lis = tree.xpath(\"//li[@class='item js-normal-item']\")\n# for li in lis:\n# href = li.xpath('./div[1]/h3/a/@href')[0]\n# # print(href)\n# hrefs.append(href)\n#\n# for href in hrefs:\n# time.sleep(3)\n# print(main_url+href)\n# detail_response = requests.get(main_url + href, headers=headers)\n#\n# if detail_response.status_code == 200:\n# detail_html = detail_response.text\n# # print(detail_html)\n# detail_tree = etree.HTML(detail_html)\n#\n# question = detail_tree.xpath(\"//h2[@class='title js-ask-title']/text()\")\n# print('问题:', question)\n#\n# answers = []\n# dealed = False\n# ps = detail_tree.xpath(\"//div[@class='resolved-cnt']/p\")\n# if len(ps) > 0:\n# for p in ps:\n# answer = p.xpath('./text()')\n# answers.append(answer)\n# dealed = True\n#\n# if not dealed:\n# answer = div = detail_tree.xpath(\"//div[@class='resolved-cnt src-import']/text()\")\n# if answer:\n# answers.append(answer)\n# dealed = True\n#\n# if not dealed:\n# answers = detail_tree.xpath(\"//div[@class='resolved-cnt src-import']//text()\")\n#\n# print('答案:', answers)\n#\n# if len(tree.xpath(\"//a[@class='next']\")) == 1:\n# page += 1\n# else:\n# break\n\n","sub_path":"python/index.py","file_name":"index.py","file_ext":"py","file_size_in_byte":3212,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"348683151","text":"import os\nimport numpy as np\nimport pandas as pd\nimport tensorflow as tf\n\n\nclass Unpack(object):\n def __call__(self, sample):\n return sample['features'], sample['labels']\n \n \nclass ToFloat32(object):\n def __call__(self, feats, labels):\n feats = tf.cast(feats, tf.float32)\n return feats, labels\n \n \nclass SetValueToNewValue(object):\n def __init__(self, old_value=2**16-1, new_value=-1):\n self.old_value = old_value\n self.new_value = new_value\n \n def __call__(self, feats, labels):\n feats = tf.where(feats==self.old_value, tf.constant(self.new_value), feats)\n return feats, labels\n \n \nclass OneMinusEncoding(object):\n \"\"\" encodes labels to 1-p, p \"\"\"\n def __init__(self, n_classes):\n assert n_classes==2, 'OneMinus works only for \"binary\" classes. `n_classes` should be 2.'\n self.n_classes = n_classes\n \n def __call__(self, feats, labels):\n return feats, tf.concat([tf.ones_like(labels) - labels, labels], axis=-1)\n \n \nclass OneHotEncoding(object):\n def __init__(self, n_classes):\n self.n_classes = n_classes\n \n def __call__(self, feats, labels):\n labels_oh = tf.one_hot(tf.squeeze(labels, axis=-1), depth=self.n_classes)\n return feats, labels_oh\n\n \nclass FillNaN(object):\n def __init__(self, fill_value=-2):\n self.fill_value = fill_value\n \n def __call__(self, feats, labels): \n feats = tf.where(tf.math.is_nan(feats), tf.constant(self.fill_value, feats.dtype), feats)\n return feats, labels\n \n \nclass Normalize(object):\n def __init__(self, scaler, mean=None):\n self.scaler = scaler\n self.mean = mean\n \n def __call__(self, feats, labels):\n if self.mean is not None:\n feats = tf.math.subtract(feats, tf.convert_to_tensor(self.mean, dtype=np.float32))\n feats = tf.math.divide(feats, tf.convert_to_tensor(self.scaler, dtype=np.float32))\n return feats, labels\n \n \nclass LabelsToDict(object):\n def __init__(self, keys):\n self.keys = keys\n \n def __call__(self, feats, labels):\n assert len(self.keys) == labels.shape[0]\n labels_dict = {}\n for idx, key in enumerate(self.keys):\n labels_dict[key] = labels[idx,...]\n return {'features': feats}, labels_dict\n \n \ndef normalize_perc(ds_keys):\n feats = tf.math.divide(tf.cast(ds_keys['features'], tf.float64), ds_keys['norm_perc99'])\n ds_keys['features'] = feats\n return ds_keys\n\n\ndef normalize_meanstd(ds_keys):\n feats = tf.math.subtract(tf.cast(ds_keys['features'], tf.float64), ds_keys['norm_meanstd_mean'])\n feats = tf.math.divide(feats, ds_keys['norm_meanstd_std'])\n ds_keys['features'] = feats\n return ds_keys \n\n\ndef augment_data(features_augmentations, labels_augmentation, brightness_delta=0.1, contrast_bounds=(0.9,1.1)):\n \"\"\" Builds a function that randomly augments features in specified ways.\n param features_to_augment: List of features to augment and which operations to perform on them.\n Each element is of shape (feature, list_of_operations).\n type features_to_augment: list of (str, list of str)\n param brightness_delta: Maximum brightness change.\n type brightness_delta: float\n param contrast_bounds: Upper and lower bounds of contrast multiplier.\n type contrast_bounds: (float, float)\n \"\"\"\n def _augment_data(data, op_fn):\n return op_fn(data)\n \n def _augment_labels(labels_augmented, oper_op):\n ys = [] \n for i in range(len(labels_augmented)): \n ys.append(_augment_data(labels_augmented[i, ...], oper_op))\n return tf.convert_to_tensor(ys, dtype=labels_augmented.dtype)\n\n def _augment(features, labels):\n contrast_lower, contrast_upper = contrast_bounds\n\n flip_lr_cond = tf.random.uniform(shape=[]) > 0.5\n flip_ud_cond = tf.random.uniform(shape=[]) > 0.5\n rot90_amount = tf.random.uniform(shape=[], maxval=4, dtype=tf.int32)\n\n # Available operations\n operations = {\n 'flip_left_right': lambda x: tf.cond(flip_lr_cond, lambda: tf.image.flip_left_right(x), lambda: x),\n 'flip_up_down': lambda x: tf.cond(flip_ud_cond, lambda: tf.image.flip_up_down(x), lambda: x),\n 'rotate': lambda x: tf.image.rot90(x, rot90_amount),\n 'brightness': lambda x: tf.image.random_brightness(x, brightness_delta),\n 'contrast': lambda x: tf.image.random_contrast(x, contrast_lower, contrast_upper)\n }\n \n\n for op in features_augmentations:\n features = _augment_data(features, operations[op])\n \n for op in labels_augmentation:\n labels = _augment_labels(labels, operations[op])\n \n return features, labels\n\n return _augment\n\n\ndef _construct_norm_arrays(file_path):\n mode = os.path.basename(os.path.dirname(file_path))\n if mode == 'train': \n df = pd.read_csv('../../input-data/train_dataset.csv')\n elif mode == 'test': \n df = pd.read_csv('../../input-data/test_dataset.csv')\n elif mode == 'validation': \n df = pd.read_csv('../../input-data/validation_dataset.csv')\n\n df = df[df.chunk == os.path.basename(file_path)]\n \n perc99 = df[['norm_perc99_b0', 'norm_perc99_b1', 'norm_perc99_b2', 'norm_perc99_b3']].values\n meanstd_mean = df[['norm_meanstd_mean_b0', 'norm_meanstd_mean_b1', 'norm_meanstd_mean_b2', 'norm_meanstd_mean_b3']].values\n meanstd_std = df[['norm_meanstd_std_b0', 'norm_meanstd_std_b1', 'norm_meanstd_std_b2', 'norm_meanstd_std_b3']].values\n \n return perc99, meanstd_mean, meanstd_std\n \n\ndef npz_dir_dataset(file_dir_or_list, features, randomize=True, num_parallel=5, shuffle_size=500, filesystem=None):\n \"\"\" Creates a tf.data.Dataset from a directory containing numpy .npz files. Files are loaded\n lazily when needed. `num_parallel` files are read in parallel and interleaved together.\n :param file_dir_or_list: directory containing .npz files or a list of paths to .npz files\n :type file_dir_or_list: str | list(str)\n :param features: dict of (`field` -> `feature_name`) mappings, where `field` is the field in the .npz array\n and `feature_name` is the name of the feature it is saved to.\n :type features: dict\n :param randomize: Whether to shuffle samples returned from dataset\n :type randomize: bool, optional\n :param num_parallel: number of files to read in parallel and intereleave, defaults to 5\n :type num_parallel: int, optional\n :param shuffle_size: buffer size for shuffling file order, defaults to 500\n :type shuffle_size: int, optional\n :return: dataset containing examples merged from files\n :rtype: tf.data.Dataset\n \"\"\"\n\n files = file_dir_or_list\n\n # If dir, then list files\n if isinstance(file_dir_or_list, str):\n if filesystem is None:\n dir_list = os.listdir(file_dir_or_list)\n else:\n dir_list = filesystem.listdir(file_dir_or_list)\n \n files = [os.path.join(file_dir_or_list, f) for f in dir_list]\n\n fields = list(features.keys())\n feature_names = [features[f] for f in features]\n\n # Read one file for shape info\n file = next(iter(files))\n\n if filesystem is None:\n data = np.load(file)\n else:\n data = np.load(filesystem.openbin(file))\n\n np_arrays = [data[f] for f in fields]\n\n # Append norm arrays \n perc99, meanstd_mean, meanstd_std = _construct_norm_arrays(file)\n \n np_arrays.append(perc99)\n np_arrays.append(meanstd_mean)\n np_arrays.append(meanstd_std)\n\n # Read shape and type info\n types = tuple(arr.dtype for arr in np_arrays)\n shapes = tuple(arr.shape[1:] for arr in np_arrays)\n# print(shapes)\n\n # Create datasets\n datasets = [_npz_file_lazy_dataset(file, fields, feature_names, types, shapes, filesystem) for file in files]\n ds = tf.data.Dataset.from_tensor_slices(datasets)\n\n # Shuffle files and interleave multiple files in parallel\n if randomize:\n ds = ds.shuffle(shuffle_size)\n \n ds = ds.interleave(lambda x:x, cycle_length=num_parallel)\n\n return ds\n\n\ndef _npz_file_lazy_dataset(file_path, fields, feature_names, types, shapes, filesystem=None):\n \"\"\" Creates a lazy tf.data Dataset from a numpy file.\n Reads the file when first consumed.\n :param file_path: path to the numpy file\n :type file_path: str\n :param fields: fields to read from the numpy file\n :type fields: list(str)\n :param feature_names: feature names assigned to the fields\n :type feature_names: list(str)\n :param types: types of the numpy fields\n :type types: list(np.dtype)\n :param shapes: shapes of the numpy fields\n :type shapes: list(tuple)\n :return: dataset containing examples from the file\n :rtype: tf.data.Dataset\n \"\"\"\n\n def _generator():\n if filesystem is None:\n data = np.load(file_path)\n else:\n data = np.load(filesystem.openbin(file_path))\n\n np_arrays = [data[f] for f in fields]\n \n perc99, meanstd_mean, meanstd_std = _construct_norm_arrays(file_path)\n\n np_arrays.append(perc99)\n np_arrays.append(meanstd_mean)\n np_arrays.append(meanstd_std)\n \n # Check that arrays match in the first dimension\n n_samples = np_arrays[0].shape[0]\n assert all(n_samples == arr.shape[0] for arr in np_arrays)\n # Iterate through the first dimension of arrays\n for slices in zip(*np_arrays):\n yield slices\n\n ds = tf.data.Dataset.from_generator(_generator, types, shapes)\n\n # Converts a database of tuples to database of dicts\n def _to_dict(*features):\n return {'features': features[0], \n 'labels': [features[1], features[2], features[3]], \n 'norm_perc99': features[4], \n 'norm_meanstd_mean': [features[5]], \n 'norm_meanstd_std': features[6]}\n\n ds = ds.map(_to_dict)\n\n return ds\n\n","sub_path":"notebooks/supervised/tf_data_utils.py","file_name":"tf_data_utils.py","file_ext":"py","file_size_in_byte":10097,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"604497939","text":"from flask import Flask, request\nfrom db_pool import MongoDB\napp= Flask(__name__)\n\n@app.route('/')\ndef root():\n return 'root'\n\t\n@app.route('/sensors', methods=['POST','GET', 'PUT', 'DELETE'])\ndef sensors():\n\tif request.method == 'GET':\n\t\tMongoDB.sensor_value.insert({\"test2\":\"test2\"})\n\treturn request.method\n\nif __name__=='__main__':\n\tapp.run(host='0.0.0.0', debug= True)\n","sub_path":"server/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":375,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"593462045","text":"import event,device,packet,system_timer\nimport random,statistics_collection\n\nclass Sensor(device.Device):\n def __init__(self,AID,CWmin,CWmax,locations,RTS_enabled,suspend_enabled,AP,timer,channel):\n device.Device.__init__(self,locations,CWmin,CWmax,timer,channel)\n self.RTS_enabled,self.suspend_enabled=RTS_enabled,suspend_enabled # True or False\n # self.packet_to_send=None\n self.AID=AID\n self.AP=AP\n self.access_mode=\"Open access\" # the access mechanism is used currently\n self.next_RAW_slot,self.next_open_access=None,None # the restricted window this sensor is currently involved\n self.receiving_power=0 # mW\n self.RAW_CWmin,self.RAW_CWmax=7,15 #the contention window parameter within a RAW\n self.open_access_CWmin,self.open_access_CWmax=15,1023 #the contention window parameter in open access\n self.freezed_backoff_timer,self.freezed_backoff_stage=None,None\n self.number_of_attempts=0\n self.number_of_backoffs=0\n\n def generate_one_packet(self):\n #This function is called when the sensor is triggered by the event \n #After being triggered this sensor generates an alarm report\n print(\"A packet arrival at STA \"+str(self.AID))\n new_packet=packet.Packet(self.timer,\"Data\",self,[self.AP])\n assert self.status==\"Sleep\"\n self.status=\"Listen\"\n self.queue.append(new_packet) # push this packet into the queue\n # statistics_collection.collector.register_packet_generated()\n if self.channel_state==\"Idle\": # wait for an DIFS before tranmission\n new_event=event.Event(\"IFS expire\",self.timer.current_time+self.timer.DIFS)\n new_event.register_device(self)\n self.IFS_expire_event=new_event\n self.timer.register_event(new_event)\n # self.packet_to_send=new_packet\n\n def back_off(self):\n #This function is called when a backoff time slot has passed\n #This sensor's backoff timer is count down in this function and transmission is triggered when timer<=0\n #Output:\n #\tTrue--this sensor is still backing off\n #\tFalse--this senosr is not\n # print(\"I am backing off\")\n if (self.backoff_status==\"Off\" or not self.queue or self.status!=\"Listen\"): # backoff timer will not decrease\n return False\n assert self.channel_state==\"Idle\", \"channel is busy while back off is not turned off\"\n if self.access_mode==\"General Raw\": # calculate the expected time to transmit a data frame and get the ack\n expected_time=(self.timer.slot_time*self.backoff_timer+self.queue[0].transmission_delay()+self.timer.SIFS\n +self.timer.NDP_time)\n elif self.access_mode==\"Trigger Raw\": # calculate the expected time to transmit a PS-POLL frame and get the ACK\n expected_time=(self.timer.slot_time*self.backoff_timer+self.timer.NDP_time*2+self.timer.SIFS)\n if \"Raw\" in self.access_mode:\n # print(expected_time)\n if self.timer.current_time+expected_time>self.next_RAW_slot.end_time:\n self.backoff_status=\"Off\"\n return False\n self.backoff_timer-=1\n if self.backoff_timer<=0: # transmit this packet immediately\n if self.access_mode==\"Trigger Raw\": # transmit a ps-poll frame\n new_packet=packet.Packet(self.timer,\"NDP Ps-poll\",self,[self.AP])\n self.transmit_packet(new_packet)\n else:\n if self.RTS_enabled: # transmit a RTS frame\n new_packet=packet.Packet(self.timer,\"RTS\",self,[self.AP])\n self.transmit_packet(new_packet)\n else: # transmit the data packet\n new_packet=self.queue[0]\n self.transmit_packet(new_packet)\n self.status=\"Transmit\"\n self.packet_can_receive=None\n return False\n else:\n return True\n\n def transmission_end(self):\n #This function is called when this sensor finish a frame transmission\n # self.channel.clear_transmission_in_air(self.packet_in_air)\n if self.packet_in_air.packet_type==\"RTS\": # sensor need to wait a CTS timeout\n new_event=event.Event(\"reply timeout\",self.timer.current_time+self.timer.SIFS+\n packet.Packet(self.timer,\"CTS\",self,[self.AP]).transmission_delay()+1)\n elif self.packet_in_air.packet_type==\"Data\" or self.packet_in_air.packet_type==\"NDP Ps-poll\": \n # sensor need to wait an ACK timeout\n new_event=event.Event(\"reply timeout\",self.timer.current_time+self.timer.SIFS+\n packet.Packet(self.timer,\"NDP ACK\",self,[self.AP]).transmission_delay()+1)\n self.channel.clear_transmission_in_air(self.packet_in_air)\n new_event.register_device(self)\n self.time_out_event=new_event\n self.timer.register_event(new_event)\n self.packet_in_air=None\n self.backoff_status=\"Off\"\n self.status=\"Listen\"\n\n def reply_timeout(self):\n #This function is called when this sensor failes receiving a reply from AP\n #In this simulation, this will only happens when there is a collision\n self.backoff_stage=min(self.backoff_stage*2,self.CWmax)\n self.backoff_timer=random.randint(0,self.backoff_stage-1)\n if self.channel_state==\"Idle\" and self.NAV_expire_event==None: \n #channel is idle and no NAV need to be expired, wait for an DIFS to start backoff\n new_event=event.Event(\"IFS expire\",self.timer.current_time+self.timer.DIFS)\n new_event.register_device(self)\n self.timer.register_event(new_event)\n self.IFS_expire_event=new_event\n self.time_out_event=None\n statistics_collection.collector.register_collision()\n\n def __NAV_renew__(self,packet):\n #This function is called when receiving a packet which is not target for itself\n NAV=packet.NAV\n if self.NAV_expire_event!=None: # remove the former NAV expire event from the timer\n self.timer.remove_event(self.NAV_expire_event)\n self.NAV_expire_event=None\n if NAV!=0: # register a new NAV event in the timer\n new_event=event.Event(\"NAV expire\",self.timer.current_time+NAV+1)\n new_event.register_device(self)\n self.timer.register_event(new_event)\n self.NAV_expire_event=new_event\n else: # immediately expire the NAV\n self.NAV_expire()\n\n def NAV_expire(self):\n #This function is called when NAV has expired \n #This sensor will start its backoff timer after a DIFS\n assert self.IFS_expire_event==None\n print(\"NAV is expired at STA \"+str(self.AID))\n if self.channel_state==\"Idle\" and self.queue: # start backoff after a DIFS if queue is not \n # empty and channel is idle\n new_event=event.Event(\"IFS expire\",self.timer.current_time+self.timer.DIFS)\n new_event.register_device(self)\n self.timer.register_event(new_event)\n self.IFS_expire_event=new_event\n self.NAV_expire_event=None\n\n def IFS_expire(self):\n #This function is called when an IFS duration is expired and channel is Idle\n #After this IFS duration, the sensor will start transmission or start backoff timer\n assert self.channel_state==\"Idle\", \"IFS expired while the channel is busy STA AID is %d\" % self.AID\n self.IFS_expire_event=None\n if self.packet_to_send==None: #start backoff counter as no packet need to be sent\n self.backoff_status=\"On\"\n if self.timer.backoff_status==\"Off\": # register a backoff event\n new_event=event.Event(\"backoff\",self.timer.current_time+self.timer.slot_time)\n new_event.register_device(self)\n self.timer.register_event(new_event)\n self.timer.backoff_status=\"On\"\n print(\"backoff is on\")\n elif (self.channel_state==\"Idle\" or self.packet_to_send.packet_type==\"NDP ACK\" or\n self.packet_to_send.packet_type==\"CTS\"): # start a transmission for the pending packet\n self.transmit_packet(self.packet_to_send)\n self.packet_to_send=None\n\n\n def packet_received(self,packet):\n #This function is called when a packet is finished tranmission in the air and can be \n #received by this sensor\n #Input: \n #\tpacket--the packet can be received by this sensor\n import time\n assert self.packet_can_receive==packet\n self.packet_can_receive=None\n if self.IFS_expire_event!=None: \n #clear this event, this event may be register when channel becomes Idle, \n #EIFS is registered in the update receiving power function\n self.timer.remove_event(self.IFS_expire_event)\n self.IFS_expire_event=None\n # print(\"received a packet while a sensor has IFS event STA \"+str(self.AID))\n # exit(0)\n\n if self in packet.destination: # when this sensor is one of the receivers\n if packet.packet_type==\"NDP ACK\": # an ack has been received\n self.__received_ACK__()\n elif packet.packet_type==\"CTS\": # send the data to AP\n self.__received_CTS__()\n elif packet.packet_type==\"Beacon Frame\": \n self.__received_Beacon__(packet)\n if self.time_out_event!=None: # clear the time out event\n self.timer.remove_event(self.time_out_event)\n self.time_out_event=None\n if self.NAV_expire_event!=None: # clear the NAV expire event\n self.timer.remove_event(self.NAV_expire_event)\n self.NAV_expire_event=None\n else: # when the sensor is not the one of the receivers\n if self.time_out_event!=None: #collsion happens\n statistics_collection.collector.register_collision()\n self.backoff_stage=min(self.backoff_stage*2,self.CWmax)\n self.backoff_timer=random.randint(0,self.backoff_stage-1)\n self.timer.remove_event(self.time_out_event)\n self.time_out_event=None\n if self.suspend_enabled==True and packet.packet_type==\"Data\": # suspend the timer\n self.backoff_timer+=random.randint(0,self.backoff_stage-1-self.backoff_timer)\n self.__NAV_renew__(packet)\n return True\n\n def __received_ACK__(self):\n # This function is called when the sensor received an ACK from AP\n if self.last_packet_sent.packet_type==\"Data\":\n statistics_collection.collector.register_successful_transmission(self.queue[0],self.timer.current_time)\n statistics_collection.collector.delay_register(self.queue[0].cal_delay(self.timer.current_time))\n self.queue.pop(0)\n if self.queue and self.channel_state==\"Idle\": # wait for an DIFS to start back off\n new_event=event.Event(\"IFS expire\",self.timer.current_time+self.timer.DIFS)\n new_event.register_device(self)\n self.timer.register_event(new_event)\n self.IFS_expire_event=new_event\n self.backoff_stage=self.CWmin\n self.backoff_timer=random.randint(0,self.backoff_stage-1)\n elif not self.queue:\n self.status=\"Sleep\"\n\n def __received_CTS__(self):\n # This function is called when the sensor received an CTS from AP\n self.packet_to_send=self.queue[0]\n new_event=event.Event(\"IFS expire\",self.timer.current_time+self.timer.SIFS)\n new_event.register_device(self)\n self.timer.register_event(new_event)\n\n def __received_Beacon__(self,beacon):\n # This function is called when the sensor received a Beacon frame from AP\n self.next_RAW_slot=None\n self.next_open_access=0\n for each_RAW in beacon.RAWs:# check whether the STA is in a certain RAW\n if ((each_RAW.paged_only and self in each_RAW.paged_STAs) or \n (not each_RAW.paged_only and self in each_RAW.STAs)): # find the corresonding slot in this RAW for the sensor\n for each_slot in each_RAW.slot_list:\n if self in each_slot.STAs:\n self.next_RAW_slot=each_slot\n break\n \n self.next_open_access=max(x.end_time for x in beacon.RAWs)\n self.status=\"Sleep\"\n if self.next_RAW_slot!=None: # wake up at certain time for this RAW\n new_event=event.Event(\"Wakeup for RAW\", self.next_RAW_slot.start_time)\n new_event.register_device(self)\n self.timer.register_event(new_event)\n return True\n else: # wake up while the channel is open for access\n new_event=event.Event(\"Wakeup during open access\",self.next_open_access)\n new_event.register_device(self)\n self.timer.register_event(new_event)\n return False\n\n\n def wakeup_in_RAW(self):\n # This function is called when the sensor wakesup in a RAW\n # The first backoff timer need to be freezed and the second backoff timer with RAW_CWmin RAW_CWmax\n # Output:\n #\tTrue--the sensor has something to report\n #\tFalse--the sensor has nothing to report\n # print(\"wake up at \"+str(self.timer.current_time))\n import random\n if not self.queue: # if there is no packet buffering here\n return False\n assert self.next_RAW_slot.start_time==self.timer.current_time, \"wake up in a wrong RAW\"\n if self.next_RAW_slot.raw_type==\"General\":\n self.access_mode=\"General Raw\"\n elif self.next_RAW_slot.raw_type==\"Trigger\":\n self.access_mode=\"Trigger Raw\"\n # print(self.access_mode)\n self.status=\"Listen\"\n # use the new backoff timer value\n self.CWmin,self.CWmax=self.RAW_CWmin,self.RAW_CWmax\n self.freezed_backoff_timer=self.backoff_timer\n self.freezed_backoff_stage=self.backoff_stage\n self.backoff_timer=random.randint(0,self.CWmin)\n self.backoff_stage=self.CWmin\n if self.channel_state==\"Idle\": # start backoff after DIFS\n new_event=event.Event(\"IFS expire\",self.timer.DIFS+self.timer.current_time)\n new_event.register_device(self)\n self.timer.register_event(new_event)\n self.IFS_expire_event=new_event\n new_event=event.Event(\"Endup RAW\",self.next_RAW_slot.end_time) # end this RAW\n new_event.register_device(self)\n self.timer.register_event(new_event)\n return True\n\n def end_up_RAW(self):\n # This function is called when the sensor end up with current involved RAW\n # Output:\n #\tTrue--the sensor will wake up for the next open access period\n #\tFalse--the sensor will stay sleep\n # exit(0)\n if not self.queue: # go back to sleep mode\n self.status=\"Sleep\"\n return False\n assert self.next_open_access-self.timer.current_time>-0.0001, \"end_up_RAW function i sensor.py\"\n new_event=event.Event(\"Wakeup during open access\",self.next_open_access)\n new_event.register_device(self)\n self.timer.register_event(new_event)\n self.next_open_access=None\n self.next_RAW_slot=None\n self.status=\"Sleep\"\n if self.IFS_expire_event!=None: # clear the IFS expire event registered in this RAW\n self.timer.remove_event(self.IFS_expire_event)\n self.IFS_expire_event=None\n if self.NAV_expire_event!=None: # clear the NAV expire event registered in this RAW\n self.timer.remove_event(self.NAV_expire_event)\n self.NAV_expire_event=None\n return True\n\n def wakeup_in_open_access(self):\n # This function is called when the sensor wakes up in an open access period\n # Output:\n #\tTrue--the sensor has waken up\n #\tFalse--the sensor keeps sleep\n if not self.queue:\n return False\n self.access_mode=\"Open access\"\n self.status=\"Listen\"\n self.CWmin,self.RAW_CWmax=self.open_access_CWmin,self.open_access_CWmax\n if self.freezed_backoff_timer!=None and self.freezed_backoff_stage!=None: # recover the backoff timer\n self.backoff_timer,self.backoff_stage=self.freezed_backoff_timer,self.freezed_backoff_stage\n if self.channel_state==\"Idle\":\n new_event=event.Event(\"IFS expire\",self.timer.DIFS+self.timer.current_time)\n new_event.register_device(self)\n self.timer.register_event(new_event)\n self.IFS_expire_event=new_event\n return True","sub_path":"Hierachical/sensor.py","file_name":"sensor.py","file_ext":"py","file_size_in_byte":16620,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"432190285","text":"# by Ariel Leston\r\n# this is the server-side of an instant messenger program\r\n\r\n# importing all necessary libraries\r\nimport socket\r\nimport threading\r\n\r\n# setting up server port and IP which will just be the hosts public IP\r\nPORT = 20020\r\nSERVER = \"0.0.0.0\"\r\nADDRESS = (SERVER, PORT)\r\nFORMAT = \"utf-8\"\r\n\r\n# creating a multi-dimensional array of rooms, this is how it will filter people into specific rooms\r\n# ideally this would be done dynamically as the program needs more rooms, allowing it to make as many as it needs\r\n# but due to time limitations, I just pre-made some rooms to show proof of concept\r\nnames, room1, room2, room3, room4, room5 = [], [], [], [], [], []\r\nrooms = [room1, room2, room3, room4, room5]\r\n\r\n# creating the server socket for clients to connect to\r\nserverSocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\r\nserverSocket.bind(ADDRESS)\r\n\r\n\r\n# starting the chat loop, where server accepts connections and starts handling messages from them\r\ndef startChat():\r\n print(\"server is working on \" + str(socket.gethostbyname(socket.gethostname())))\r\n serverSocket.listen()\r\n running = True\r\n\r\n # any message sent by server and not from a client will be encrypted with this key instead, as it has no originator\r\n myKey = \"server\"\r\n\r\n # this keeps track of the next empty room, every time someone presses create room it increments by 1\r\n nextRoomSlot = 0\r\n\r\n while running:\r\n # accepts a connection\r\n clientSocket, address = serverSocket.accept()\r\n try:\r\n # send initial message to get the clients name and room number\r\n # also encrypting it in name/room>key format with vegenere cipher\r\n text = vegenereEncrypt(\"NAME/ROOM\", myKey)\r\n text += \">\" + myKey\r\n clientSocket.send(text.encode(FORMAT))\r\n\r\n # it receives a response in the same format so it splits by / and >\r\n data = clientSocket.recv(1024).decode(FORMAT)\r\n print(data)\r\n data = data.split('>')\r\n info = data[0].split('/')\r\n key = data[1]\r\n\r\n # then adds all the info to its variables for that client\r\n name = vegenereDecrypt(info[0], key)\r\n roomNumb = int(info[1])\r\n names.append(name)\r\n\r\n # it checks if the client wants an emtpy room or a specific room, and places them accordingly\r\n if roomNumb == 0:\r\n print(\"new room\")\r\n nextRoomSlot += 1\r\n print(\"making room \" + str(nextRoomSlot))\r\n roomNumb = nextRoomSlot\r\n else:\r\n print(\"joining room \" + str(roomNumb))\r\n rooms[roomNumb - 1].append(clientSocket)\r\n\r\n # then sends a confirmation message to the room showing they joined and confirming what room number\r\n print(f\"{name} has connected to server\")\r\n text = vegenereEncrypt(f\"{name} has joined room {roomNumb}\", myKey)\r\n text += '>' + myKey\r\n broadcastMessage(clientSocket, text.encode(FORMAT))\r\n text = vegenereEncrypt(\"Connection established\", myKey)\r\n text += '>' + myKey\r\n clientSocket.send(text.encode(FORMAT))\r\n\r\n # then starts a thread to handle that client\r\n thread = threading.Thread(target=handle, args=(clientSocket, address))\r\n thread.start()\r\n except:\r\n broadcastMessage(clientSocket, f\" {address} has left the room\".encode(FORMAT))\r\n clientSocket.close()\r\n\r\n print(f\"active connections = {threading.activeCount() - 1}\")\r\n\r\n\r\n# when a client sends something, the server will receive using this function and then send that message to broadcast\r\ndef handle(clientSocket, address):\r\n print(f\"now handling connection with {address}\")\r\n connected = True\r\n try:\r\n while connected:\r\n message = clientSocket.recv(1024)\r\n sender = clientSocket\r\n broadcastMessage(sender, message)\r\n except:\r\n pass\r\n print(f\"connection with {address} closed\")\r\n clientSocket.close()\r\n\r\n\r\n# this will send the given message to every user in the same room of the message sender\r\ndef broadcastMessage(sender, message):\r\n senderRoom = -1\r\n for currentRoom in rooms:\r\n for currentSocket in currentRoom:\r\n if currentSocket == sender:\r\n senderRoom = currentRoom\r\n\r\n if senderRoom is not -1:\r\n for userSocket in senderRoom:\r\n userSocket.send(message)\r\n\r\n\r\n# slightly modified vegenere cipher for encryption, works by ascii numbers and indexes\r\ndef vegenereEncrypt(text, key):\r\n loopedKey = \"\"\r\n while len(loopedKey) < len(text):\r\n for element in key:\r\n loopedKey += element\r\n loopedKeyList = list(loopedKey)\r\n textList = list(text)\r\n newText = \"\"\r\n\r\n for i in range(len(textList)):\r\n if 65 <= ord(textList[i]) <= 122:\r\n letterIndex = ord(textList[i]) - 65\r\n keyIndex = ord(loopedKeyList[i]) - 65\r\n newIndex = letterIndex + keyIndex\r\n if newIndex > 57:\r\n newIndex -= 58\r\n newLetter = chr(newIndex + 65)\r\n newText += newLetter\r\n else:\r\n newText += str(textList[i])\r\n\r\n return newText\r\n\r\n\r\n# the inverse of encrypt function to allow decyrption\r\ndef vegenereDecrypt(text, key):\r\n loopedKey = \"\"\r\n while len(loopedKey) < len(text):\r\n for element in key:\r\n loopedKey += element\r\n loopedKeyList = list(loopedKey)\r\n textList = list(text)\r\n newText = \"\"\r\n\r\n for i in range(len(textList)):\r\n if 65 <= ord(textList[i]) <= 122:\r\n letterIndex = ord(textList[i]) - 65\r\n keyIndex = ord(loopedKeyList[i]) - 65\r\n newIndex = letterIndex - keyIndex\r\n if newIndex < 0:\r\n newIndex += 58\r\n newLetter = chr(newIndex + 65)\r\n newText += newLetter\r\n else:\r\n newText += textList[i]\r\n\r\n return newText\r\n\r\n# starts\r\nstartChat()\r\n","sub_path":"testServer.py","file_name":"testServer.py","file_ext":"py","file_size_in_byte":6064,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"5940810","text":"# coding:utf-8\r\n'''\r\n这是一个生成特殊数列并保存到本地文件的模块\r\n\r\n供生成的特殊数列包括:\r\n因数数列、质数1-2数列、质因素数列、阶乘数列、斐波那契1-2数列、闰年数列\r\n一个数的全排列、分数的小数部分前n位\r\n\r\n#作者:浓眉大侠singing\r\n#联系QQ:403425608\r\n#最后更新日期:2016.05.24\r\n'''\r\nfrom itertools import product\r\n\r\ndef save(array, file_name):\r\n '''保存数列的列表转化为数列的字符串到file_name.txt文件中。\r\n 第一参数:数列的列表;\r\n 第二参数:保存的文件名.'''\r\n string = map(str, (i for i in array))\r\n string = '\\n'.join(string)\r\n file_name += '.txt'\r\n with open(file_name, 'w')as f:\r\n f.write(string)\r\n print('数列保存在%s文件中' % file_name)\r\n\r\n\r\ndef factor_generator(n, text=0):\r\n '''生成一个正整数n的所有因数(除去自身)的数列,并保存到factor.txt文件中.\r\n 第一参数指定正整数n.\r\n 第二参数决定是否保存到文本文件中,为0不保存,为1保存,默认为0.'''\r\n if n <= 0:\r\n print('参数必须为正整数')\r\n return None\r\n factor = [1]\r\n for i in range(2, int(n*0.5)+1):\r\n if n % i == 0:\r\n factor.append(i)\r\n if text == 1:\r\n save(factor, 'factor')\r\n return factor\r\n\r\n\r\ndef prime_generator_1(n, text=0):\r\n '''生成一个正整数n以内所有质数的数列,并保存到prime.txt文件中.\r\n 第一参数参数:指定质数的范围(小于n).\r\n 第二参数决定是否保存到文本文件中,为0不保存,为1保存,默认为0.''' \r\n if n <= 2:\r\n print(u'小于%d的质数不存在'%n)\r\n return None\r\n primes = set([2]) | set(range(3, n, 2))\r\n for i in xrange(3, int(n**0.5)+1):\r\n for j in xrange(i*2, n, i):\r\n primes.discard(j) \r\n if text == 1:\r\n save(primes, 'prime_1')\r\n return primes\r\n\r\n\r\ndef prime_generator_2(n, text=0):\r\n '''生成一个质数数列的前n项,并保存到prime.txt文件中.\r\n 第一参数参数:指定质数的个数.\r\n 第二参数决定是否保存到文本文件中,为0不保存,为1保存,���认为0.'''\r\n from is_sth import is_prime\r\n if n < 1:\r\n print('参数必须大于0的正整数')\r\n return None\r\n else:\r\n primes = [2]\r\n i = 3\r\n while len(primes) < n:\r\n if is_prime(i):\r\n primes.append(i)\r\n i += 2\r\n if text == 1:\r\n save(primes, 'prime_2')\r\n return primes\r\n\r\ndef prime_factor_generator(n,text=0): \r\n '''生成一个正整数n所有质因数(除去自身)的数列,并保存到prime_factor.txt文件中.\r\n 第一参数指定正整数n.\r\n 第二参数决定是否保存到文本文件中,为0不保存,为1保存,默认为0.'''\r\n from is_sth import is_prime\r\n if n<=0:\r\n print('参数必须为正整数')\r\n print('_'*80)\r\n return None\r\n prime_factor=[]\r\n for i in range(2,int(n*0.5)+1):\r\n if is_prime(i) and n%i==0:\r\n prime_factor.append(i) \r\n if text==1:save(prime_factor,'prime_factor')\r\n return prime_factor\r\n\r\ndef factorial_generator(n,text=0):\r\n '''生成一个n以内所有正整数的阶乘的数列,并保存到fractorial.txt文件中。\r\n 第一参数指定正整数的范围(小于n).\r\n 第二参数决定是否保存到文本文件中,为0不保存,为1保存,默认为0.'''\r\n if n<=1:\r\n print('参数必须大于1')\r\n return None \r\n factorial=[]\r\n i=1\r\n while i=n:break\r\n fib.append(b)\r\n if text==1:save(fib,'fibnacci_2')\r\n return fib\r\n\r\ndef leap_generator(a,b,text=0):\r\n '''生成一个公元a年到公元b年里面闰年的数列,并保存到leap.txt文件中。\r\n 第一参数起始年份;\r\n 第二参数结束年份.\r\n 第三参数决定是否保存到文本文件中,为0不保存,为1保存,默认为0.'''\r\n leap=[]\r\n for year in range(a,b+1):\r\n if year % 100 == 0 and year % 400 == 0:\r\n leap.append(year)\r\n elif year % 100 != 0 and year % 4 == 0:\r\n leap.append(year)\r\n if text==1:save(leap,'leap')\r\n return leap\r\n\r\ndef permutations_generator(n,text=0):\r\n '''生成一个正整数各位数字的全排列,并保存到permutations.txt文件中。\r\n 第一参数指定正整数n;\r\n 第二参数决定是否保存到文本文件中,为0不保存,为1保存,默认为0.'''\r\n from itertools import permutations\r\n pers=[int(''.join(i)) for i in list(permutations(str(n)))]\r\n if text == 1:\r\n save(pers, 'permutations')\r\n return pers\r\n\r\ndef decimal_digits(a, b, n):\r\n '''生成分数的小数部分前n位\r\n a:分子,b:分母,n:小数部分前n位'''\r\n i = 0\r\n dd = 0\r\n if a > b: a = a%b\r\n while i < n:\r\n a,c = divmod(a*10,b)\r\n dd += a*10**(n-i-1)\r\n a = c\r\n i += 1\r\n return dd\r\n\r\ndef circular_generator(n):\r\n '''生成一个数n的所有循环数'''\r\n circles = [n]\r\n length =len(str(n))\r\n for i in range(length-1):\r\n n = n % 10**(length-1)*10+n/10**(length-1)\r\n circles.append(n)\r\n return circles\r\n\r\n\r\n\r\n\r\ndef test():\r\n '''测试单元'''\r\n\r\n help(factor_generator)\r\n print(u'20的所有因数:')\r\n print(factor_generator(20, 0))\r\n print('_'*80)\r\n\r\n help(prime_generator_1)\r\n print(u'20以内所有质数:')\r\n print(prime_generator_1(20, 0))\r\n print('_'*80)\r\n\r\n help(prime_generator_2)\r\n print(u'质数数列前20项:')\r\n print((prime_generator_2(20, 0)))\r\n print('_'*80)\r\n \r\n help(prime_factor_generator)\r\n print(u'20以内所有质因数:')\r\n print(prime_factor_generator(20, 0))\r\n print('_'*80)\r\n \r\n help(factorial_generator)\r\n print(u'20以内所有正整数的阶乘:')\r\n print(factorial_generator(20, 0))\r\n print('_'*80)\r\n\r\n help(fib_generator_1)\r\n print(u'斐波那契数列前20项:')\r\n print(fib_generator_1(20, 0))\r\n print('_'*80)\r\n\r\n help(fib_generator_2)\r\n print(u'20以内的斐波那契数:')\r\n print(fib_generator_2(20, 0))\r\n print('_'*80)\r\n\r\n help(leap_generator)\r\n print(u'1992-2016的所有闰年')\r\n print(leap_generator(1992, 2016, 0))\r\n print('_'*80)\r\n\r\n help(permutations_generator)\r\n print(u'123的全排列')\r\n print(permutations_generator(123, 0))\r\n print('_'*80)\r\n\r\n help(decimal_digits)\r\n print(u'9/23的小数部分前100位')\r\n print(decimal_digits(9, 23, 100))\r\n print('_'*80)\r\n\r\n help(circular_generator)\r\n print(u'123的所有循环数')\r\n print(circular_generator(123))\r\n \r\nif __name__ == '__main__':\r\n test()\r\n","sub_path":"user_define_function/array_generator.py","file_name":"array_generator.py","file_ext":"py","file_size_in_byte":8122,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"620897745","text":"import pandas as pd\nimport numpy as np\n\nimport folium\nfrom folium.features import DivIcon\n\nfrom sklearn import preprocessing\n\n\ndef standardizeDF(df, measure_name):\n \"\"\"\n This function takes in a dataframe and creates and adds a column to it with the standardized value\n Therefore, it makes mean = 0 and scales the data to unit variance.\n Input: measure_name : column to be standardized\n \n \"\"\"\n name = f\"{measure_name}_standardized\"\n scaler = preprocessing.StandardScaler()\n df[name] = scaler.fit_transform(df[[measure_name]])\n return df\n\n\ndef normalizeDF(df, measure_name, min_range=0, max_range=1):\n \"\"\"\n This function takes in a dataframe and creates and adds a column to it with the normalized value\n MinMaxScaler scales all the data features in the range [0, 1] or else in the range [-1, 1] \n if there are negative values in the dataset.\n Input: measure_name : column to be normalized\n \"\"\"\n name = f\"{measure_name}_normalized\"\n # Create the Scaler object\n scaler = preprocessing.MinMaxScaler(feature_range=(min_range, max_range))\n df[name] = scaler.fit_transform(df[[measure_name]])\n return df\n\n\ndef createPropertyTypeCol(rental_df):\n \"\"\"This function adds a column called property_type_class to the dataframe \n Args:\n rental_df ([type]): [The dataframe has a column called property_type]\n\n Returns:\n [type]: [Dataframe with a more concise list of property types]\n \"\"\"\n\n # Property types Private room and Shared Room identified\n property_df = rental_df[[\"property_type\"]].copy()\n property_df.loc[\n property_df[\"property_type\"].str.contains(\"Private room|Room in\"),\n \"property_type\",\n ] = \"Private Room\"\n property_df.loc[\n property_df[\"property_type\"].str.contains(\"Shared room\"), \"property_type\"\n ] = \"Shared Room\"\n\n # Extrac the second half of all \"Entire\" property types to get the actual type such as house..\n property_df.loc[\n property_df[\"property_type\"].str.contains(\"Entire \"), \"property_type\"\n ] = (\n property_df.loc[\n property_df[\"property_type\"].str.contains(\"Entire \"), \"property_type\"\n ]\n .str.replace(\"Entire \", \"\")\n .str.capitalize()\n )\n\n rental_df[\"property_type_class\"] = property_df[\"property_type\"]\n\n return rental_df\n\n\n##############################################################################################################\n# Clean up the dataframe\n##############################################################################################################\ndef cleanRentalDF(filename):\n\n # Read the data into a dataframe\n full_df = pd.read_csv(filename)\n # select out the columns we are interested in\n rental_df = full_df[\n [\n \"id\",\n \"price\",\n \"listing_url\",\n \"host_id\",\n \"host_response_rate\",\n \"host_response_time\",\n \"host_acceptance_rate\",\n \"review_scores_communication\",\n \"review_scores_location\",\n \"review_scores_value\",\n \"review_scores_checkin\",\n \"reviews_per_month\",\n \"review_scores_cleanliness\",\n \"license\",\n \"instant_bookable\",\n \"number_of_reviews\",\n \"first_review\",\n \"last_review\",\n \"neighbourhood_cleansed\",\n \"neighbourhood_group_cleansed\",\n \"latitude\",\n \"longitude\",\n \"accommodates\",\n \"bathrooms_text\",\n \"property_type\",\n \"has_availability\",\n \"availability_30\",\n \"availability_60\",\n \"availability_90\",\n \"availability_365\",\n ]\n ].copy()\n\n # Make price a float column\n rental_df[\"price\"] = (\n rental_df[\"price\"].str.replace(\"$\", \"\").str.replace(\",\", \"\").astype(\"float64\")\n )\n\n # Change host response rate from string to float so that it is a continuous value\n # TBD Look for average for the host - should I look for nans in hosts that have multiple records and set Nan to 0 oly for hosts that have only one record?\n # Mean of their reponse rate for the rest?\n # How about impute?\n\n # Convert the response rate to float\n rental_df[\"host_response_rate_percent\"] = (\n rental_df[\"host_response_rate\"].str.replace(\"%\", \"\").astype(\"float64\")\n )\n rental_df[\"host_response_rate_percent\"] = rental_df.groupby([\"host_id\"])[\n \"host_response_rate_percent\"\n ].transform(lambda x: x.fillna(x.mean()))\n # All the values that are still Nan, we do not have any info about and so fill with zero\n rental_df[\"host_response_rate_percent\"] = rental_df[\n \"host_response_rate_percent\"\n ].fillna(0)\n rental_df = rental_df.drop(\"host_response_rate\", axis=\"columns\")\n\n # Change response time to one within a dict\n # Question should we set Nans to -0 or to a very high number ( highest rank is least reponsive)\n rank_response_time = {\n \"within an hour\": 1,\n \"within a few hours\": 2,\n \"within a day\": 3,\n \"a few days or more\": 4,\n }\n rental_df[\"host_reponse_time_rank\"] = rental_df[\"host_response_time\"].map(\n rank_response_time\n )\n rental_df[\"host_reponse_time_rank\"] = rental_df[\"host_reponse_time_rank\"].fillna(0)\n rental_df = rental_df.drop(\"host_response_time\", axis=\"columns\")\n\n # Use the same logic as host_reponse_rate for host_acceptance_rate\n rental_df[\"host_acceptance_rate_percent\"] = (\n rental_df[\"host_acceptance_rate\"].str.replace(\"%\", \"\").astype(\"float64\")\n )\n rental_df[\"host_acceptance_rate_percent\"] = rental_df.groupby([\"host_id\"])[\n \"host_acceptance_rate_percent\"\n ].transform(lambda x: x.fillna(x.mean()))\n # All the values that are still Nan, we do not have any info about and so fill with zero\n rental_df[\"host_acceptance_rate_percent\"] = rental_df[\n \"host_acceptance_rate_percent\"\n ].fillna(0)\n rental_df = rental_df.drop(\"host_acceptance_rate\", axis=\"columns\")\n\n # (‘t’ means available and ‘f’ means not available)\n # *Convert t (*true) = 1 , f (false) = 0\n\n availability_code_dict = {\n \"t\": 1,\n \"f\": 0,\n }\n\n rental_df[\"instant_bookable\"] = rental_df[\"instant_bookable\"].map(\n availability_code_dict\n )\n rental_df[\"has_availability\"] = rental_df[\"has_availability\"].map(\n availability_code_dict\n )\n\n # Question what must be done for dates not present?\n rental_df[\"first_review\"] = pd.to_datetime(rental_df[\"first_review\"])\n rental_df[\"last_review\"] = pd.to_datetime(rental_df[\"last_review\"])\n\n # Add a column for a smaller list of property types\n rental_df = createPropertyTypeCol(rental_df)\n\n return rental_df\n\n\n################################################################################################################\n# Call the cleanup function and setup a global dataframe\n################################################################################################################\nfull_df = cleanRentalDF(\"data\\listings_1.csv\")\n\n################################################################################################################\n# Create data for maps\n################################################################################################################\n\n# These are the primary fields we are interested in\ndef createSpatialData():\n rental_geo_df = full_df[\n [\n \"neighbourhood_cleansed\",\n \"neighbourhood_group_cleansed\",\n \"latitude\",\n \"longitude\",\n \"price\",\n \"has_availability\",\n \"accommodates\",\n ]\n ].copy()\n\n glow_color_list = [\n \"#befdb7\",\n \"#1B03A3\",\n \"#FEFCD7\",\n \"#a60000\",\n \"#FE019A\",\n \"#4d4dff\",\n \"#ff6ec7\",\n \"#72c100\",\n \"#ff073a\",\n \"#e2ffdc\",\n \"#c8362e\",\n \"#f3cc03\",\n \"#df00fe\",\n \"#bb9a14\",\n \"#98a2af\",\n \"#a2a2a2\",\n \"#ff3f03\",\n ]\n\n glow_group_color = dict(\n zip(\n list(rental_geo_df.groupby(\"neighbourhood_group_cleansed\").groups.keys()),\n glow_color_list,\n )\n )\n rental_geo_df[\"glow_marker_color\"] = rental_geo_df[\n \"neighbourhood_group_cleansed\"\n ].map(glow_group_color)\n\n # Create a new dataframe with average latitude an longitude per neighborhood (88 of these) and Max of the neighborhood group they belong in and max of the marker vcolor\n rental_neighborhood_df = rental_geo_df.groupby([\"neighbourhood_cleansed\"]).agg(\n {\n \"latitude\": \"mean\",\n \"longitude\": \"mean\",\n \"neighbourhood_group_cleansed\": \"max\",\n \"glow_marker_color\": \"max\",\n \"neighbourhood_cleansed\": \"count\",\n }\n )\n\n # Create the Scaler object\n scaler = preprocessing.MinMaxScaler(feature_range=(0, 50))\n rental_neighborhood_df[\"nbd_count_normalized\"] = scaler.fit_transform(\n rental_neighborhood_df[[\"neighbourhood_cleansed\"]]\n )\n\n # Group the dataframe by neighbourhood groups\n rental_grp_nbd_df = rental_geo_df.groupby([\"neighbourhood_group_cleansed\"]).agg(\n {\n \"latitude\": \"mean\",\n \"longitude\": \"mean\",\n \"glow_marker_color\": \"max\",\n \"neighbourhood_group_cleansed\": \"count\",\n }\n )\n\n # Create the Scaler object to scale the count of rentals value to between a certain range\n scaler = preprocessing.MinMaxScaler(feature_range=(0, 60))\n rental_grp_nbd_df[\"nbd_count_normalized\"] = scaler.fit_transform(\n rental_grp_nbd_df[[\"neighbourhood_group_cleansed\"]]\n )\n\n return full_df, rental_geo_df, rental_neighborhood_df, rental_grp_nbd_df\n\n\ndef get_nbdgroups():\n \"\"\"\n This function returns a dictionary of Neighborhood groups to populate a selection filter\n Input: None\n Returns: Dictionary\n \"\"\"\n nbd_groups = list(full_df.neighbourhood_group_cleansed.unique())\n nbd_groups.sort()\n return [\"All\"] + nbd_groups\n\n","sub_path":"datamanipulation_bar_sankey.py","file_name":"datamanipulation_bar_sankey.py","file_ext":"py","file_size_in_byte":10091,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"279809079","text":"import sys\nsys.path.append('../')\n\nimport pandas as pd\nimport json\nfrom collections import defaultdict\nimport copy\nimport os\n\nfrom utils import create_uri, get_cn_pos_tag\nimport conceptnet_uri as cn\n\nimport config\n\nVERSION=config.VERSION\n\nNODE_COLS=config.nodes_cols\nEDGE_COLS=config.edges_cols\n\nMOWGLI_NS=config.mowgli_ns\n\nPOS_MAPPING=config.pos_mapping\n\nPOS_REL=config.has_pos\nPOS_FORM_REL=config.has_pos_form\nIS_POS_FORM_OF_REL=config.is_pos_form_of\nWORDNET_SENSE_REL=config.wordnet_sense\n\nCUSTOM_DATASET=config.custom_dataset\n\ndata_source=config.cn_ds\n\ncn_path='../input/conceptnet/conceptnet-en.csv'\n# OUTPUT FILES\noutput_dir='../output_v%s/conceptnet' % VERSION\nnodes_file='%s/nodes_v%s.csv' % (output_dir, VERSION)\nedges_full_file='%s/edges_v%s.csv' % (output_dir, VERSION)\n\nif not os.path.exists(output_dir):\n os.makedirs(output_dir)\n\ncustom_weight=1.0\n\n### Load the data in pandas ###\ndf=pd.read_csv(cn_path, sep='\\t', header=None, converters={4: json.loads})\ndf.columns=['assertion','rel','subj','obj','metadata']\ndf.drop(columns=['assertion'])\n\n### Create nodes.csv and edges.csv ###\n#### Let's first extract the main data into temporary structures. ####\n\nnode_datasets=defaultdict(set)\nall_edges=[]\n\nfor i, row in df.iterrows():\n\n subj=row['subj']\n obj=row['obj']\n rel=row['rel']\n dataset=row['metadata']['dataset']\n weight=row['metadata']['weight']\n sentence=''\n\n node_datasets[subj].add(dataset)\n node_datasets[obj].add(dataset)\n\n other={'dataset': dataset}\n edge_data=[subj, rel, obj, data_source, weight, other]\n all_edges.append(edge_data)\n\n#### a. Prepare and store nodes ####\n\nall_nodes=[]\nfor n, datasets in node_datasets.items():\n label=cn.uri_to_label(n)\n aliases_list=[]\n aliases=','.join(aliases_list)\n mapped_pos, raw_pos=get_cn_pos_tag(n, MOWGLI_NS, POS_MAPPING)\n other={'datasets': list(datasets)}\n col=[n, label, aliases, raw_pos, data_source, other]\n all_nodes.append(col)\n\nfor raw_pos, mapped_pos in POS_MAPPING.items():\n mowgli_pos=create_uri(MOWGLI_NS, mapped_pos)\n col=[mowgli_pos, raw_pos, mapped_pos, '', '', {\"datasets\": [CUSTOM_DATASET]}]\n all_nodes.append(col)\n\n\nnodes_df = pd.DataFrame(all_nodes, columns = NODE_COLS)\nnodes_df.sort_values('id').to_csv(nodes_file, index=False, sep='\\t')\nprint('unique POS tags', nodes_df['pos'].unique())\nprint(len(nodes_df), 'nodes')\n\n#### b. Enrich and store edges ####\n\nall_edges_enriched=copy.deepcopy(all_edges)\nother={'dataset': CUSTOM_DATASET}\nfor i, row in nodes_df.iterrows():\n \n node_id=row['id']\n components=cn.split_uri(node_id)\n \n if len(components)==4:\n # add POS relations\n mapped_pos, raw_pos = get_cn_pos_tag(node_id, MOWGLI_NS, POS_MAPPING)\n edge=[node_id, create_uri(MOWGLI_NS, POS_REL), mapped_pos, data_source, custom_weight, other]\n all_edges_enriched.append(edge)\n \n le_node='/%s' % '/'.join(components[:3])\n if le_node in node_datasets.keys():\n # add pos-form relations (both-ways)\n edge=[le_node, create_uri(MOWGLI_NS, POS_FORM_REL), node_id, data_source, custom_weight, other]\n all_edges_enriched.append(edge)\n\n edge=[node_id, create_uri(MOWGLI_NS, IS_POS_FORM_OF_REL), le_node, data_source, custom_weight, other]\n all_edges_enriched.append(edge)\n \n elif len(components)>=5 and components[4]=='wn':\n # add OMW relations\n pos_node='/%s' % '/'.join(components[:4])\n if pos_node in node_datasets.keys():\n edge=[pos_node, create_uri(MOWGLI_NS, WORDNET_SENSE_REL), node_id, data_source, custom_weight, other]\n all_edges_enriched.append(edge)\n \nedges_enriched_df = pd.DataFrame(all_edges_enriched, columns = EDGE_COLS)\n\n#### c. Complement missing symmetric data ####\nall_difs=[edges_enriched_df]\nfor sym_rel in config.symmetric_rels:\n #if sym_rel!='/r/LocatedNear': continue\n \n sub_df=edges_enriched_df[edges_enriched_df.predicate==sym_rel]\n sub_df['other']=\"\"\n print(sym_rel, len(sub_df))\n \n so_df=sub_df[EDGE_COLS]\n \n os_df=sub_df[['object', 'predicate', 'subject', 'datasource', 'weight', 'other']]\n os_df.columns=EDGE_COLS\n \n the_diff=os_df.merge(so_df,indicator = True, \n how='left').loc[lambda x : x['_merge']!='both']\n \n the_diff['other']=json.dumps({'dataset': CUSTOM_DATASET})\n the_diff['other']=the_diff['other'].apply(json.loads)\n \n print(the_diff.columns)\n \n print(len(the_diff))\n print()\n all_difs.append(the_diff)\n\nall_data=pd.concat(all_difs)\nall_data=all_data[EDGE_COLS]\nall_data.sort_values(by=['subject', 'predicate','object']).to_csv(edges_full_file,\n index=False,\n sep='\\t')\n\nprint('Number of edges in the full conceptnet version', len(all_data))\n","sub_path":"attic/extraction/conceptnet.py","file_name":"conceptnet.py","file_ext":"py","file_size_in_byte":4921,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"55486680","text":"# ===========================================================================\n#\n# Copyright (c) 2013-2016 Qualcomm Technologies, Inc. \n# All Rights Reserved.\n# QUALCOMM Proprietary and Confidential.\n#\n# ===========================================================================\n\n\n\nfrom __future__ import print_function\nimport struct\nimport logging\nlogger = logging.getLogger(__name__)\nimport json\nfrom pprint import pprint\nimport os\nimport itertools\nimport math\nfrom binascii import hexlify\nfrom locators.core_dump import locate as locate_core_dump\nfrom dwarf import decode_object, Structure\nfrom dwarf import Array as darray\nfrom hansei_utils import *\nfrom targ_spec_config import *\nimport csv\nfrom summary import chip_version\nfrom cmd_db import bcm_reg_map, bcm_vcd_map\n\n\n\ntab_size = 8\ndump_error = 0 # should only be used for error that indicate dump corruption\n\n# Hardcoding BASE addresses \nvt_base_address = 0 \nbcm_status_fe = 0\nbcm_status_be = 0\nbcm_status_be_seq = 0\n\nno_regs = 0\nno_drv = 0 \nno_vcds = 0\n\nBCM_votetable = [[]]\nbcm_map_table = bcm_reg_map\nvcd_map_table= bcm_vcd_map\ndef dump(debug_data): #dump_path, memory, debug_info, fill_char):\n global dump_error, vt_base_address, bcm_status_fe, bcm_status_be\n global bcm_status_be_seq, no_regs, no_drv, no_vcds\n global BCM_votetable, bcm_map_table, vcd_map_table\n dump_error = 0\n memory = debug_data['rpm_memory']\n debug_info = debug_data['debug_info']\n fill_char = debug_data['args'].fill_char\n dump_path = debug_data['dump_path']\n target = debug_data['target'] \n bcm_json_dir = debug_data['bcm_json_dir']\n debug_data['printer'].p(\"Dumping BCM Vote table registers...\")\n \n \n \n target_ver = target+'-'+str(chip_version)\n if target_ver in targ_spec_config:\n target = target_ver\n\n vt_base_address = bcm[target]['vt_base_address']\n bcm_status_fe = bcm[target]['bcm_status_fe']\n bcm_status_be = bcm[target]['bcm_status_be']\n bcm_status_be_seq = bcm[target]['bcm_status_be_seq']\n no_regs = bcm[target]['no_regs']\n no_drv = bcm[target]['no_drv']\n no_vcds = bcm[target]['no_vcds']\n BCM_votetable = [[0 for i in range(no_drv)] for j in range(no_regs)] \n \n \n try:\n ver_data = memory.read(bcm_status_fe, 4)\n except:\n debug_data['printer'].p(\"\\tBCM registers bin is not recovered...\")\n return\n\n dump_bcm_vts(dump_path, memory, target, debug_info, fill_char,bcm_json_dir)\n \n \n if dump_error != 0:\n debug_data['printer'].p(\"\\t...Non-critical errors occured in processing dump, continuing\")\n else:\n debug_data['printer'].p(\"\\t...DONE\")\n\ndef dump_bcm_vts(dump_path, memory, target, debug_info, fill_char,bcm_json_dir):\n\n address = locate_core_dump(memory, debug_info)\n dump_type = debug_info.variables['aop_core_dump'].vartype\n aop_core_dump = decode_object('aop_core_dump', address, dump_type, memory, debug_info)\n json_file_name = os.path.join(bcm_json_dir, str(target)+\"/VCD.json\")\n\n with open(json_file_name,'r') as data_file: \n data = json.load(data_file)\n#################################################################################################################### \n \n if (check_member('global_ddr_cfg ', aop_core_dump)):\n ddr_cfg = aop_core_dump.global_ddr_cfg \n ddr_cfg = cast(ddr_cfg, 'DDRCfgType', memory, debug_info)\n else:\n try:\n ddr_cfg_address = debug_info.variables['global_ddr_cfg'].die\n except:\n ddr_file_name = os.path.join(dump_path, 'ddr_stats.txt')\n with open(ddr_file_name, 'w') as ddr_file:\n print(\"\\n !!! DDR_CFG DOES NOT EXIST !!! \\n\", file=ddr_file)\n \n try:\n #not in core dump, but elf is close enough to provide a correct pointer\n ddr_gbl_address = debug_info.variables['global_ddr_cfg'].address # FIXME: get right address by magic\n ddr_cfg = decode_object('global_ddr_cfg', ddr_gbl_address, None, memory, debug_info, die=ddr_cfg_address)\n except:\n #not correct in elf, find absolute address (very hacky)\n with open(ddr_file_name, 'w') as ddr_file:\n print(\"\\n !!! DDR_cfg DOES NOT EXIST !!! \\n\", file=ddr_file)\n #################################################################################################################### \n if (check_member('ddr_status', aop_core_dump)):\n #ddr_status in in core dump\n ddr_status = aop_core_dump.ddr_status\n ddr_status = cast(ddr_status, 'ddr_state', memory, debug_info)###################################\n else:\n try:\n freq_switch_address = debug_info.variables['ddr_status'].die###################################\n except:\n ddr_file_name = os.path.join(dump_path, 'ddr_stats.txt')\n with open(ddr_file_name, 'w') as ddr_file:\n print(\"\\n !!! DDR_STATUS DOES NOT EXIST !!! \\n\", file=ddr_file)\n return\n try:\n #not in core dump, but elf is close enough to provide a correct pointer\n ddr_status_address = debug_info.variables['ddr_status'].address # FIXME: get right address by magic\n ddr_status = decode_object('ddr_status', ddr_status_address, None, memory, debug_info, die=freq_switch_address)\n except:\n #not correct in elf, find absolute address (very hacky)\n with open(ddr_file_name, 'w') as ddr_file:\n print(\"\\n !!! DDR_STATUS DOES NOT EXIST !!! \\n\", file=ddr_file)\n #################################################################################################################### \n \n dump_path = os.path.join(dump_path, 'reqs_for_resources')\n if not os.path.exists(dump_path):\n os.makedirs(dump_path) \n bcm_file_name = os.path.join(dump_path, 'bcm_vt.txt')\n summary_file_name = os.path.join(dump_path, 'rpmh_summary.txt')\n\n with open(bcm_file_name, 'w') as bcm_file, open(summary_file_name, 'a') as summary_file:\n\n print(\"\\n\\t~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\", file=bcm_file)\n print(\"\\t| VCD | Nodes |\", file=bcm_file)\n print(\"\\t~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\", file=bcm_file)\n for x in range(0, no_vcds):\n print(\"\\t|{0:>5d}|{1:>41s}|\" .format( x, vcd_map_table[x] ), file=bcm_file)\n print(\"\\t~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\", file=bcm_file)\n\n print(\"\\n ~~BCM Status Front End~~\", file=bcm_file)\n print(\"\\n\\t~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\", file=bcm_file)\n print(\"\\t| VCD | AGG_BW | Final_CP | AGG_CP | DDR MGR Override AGG_CP | Freq_khz |\", file=bcm_file)\n print(\"\\t~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\", file=bcm_file)\n for x in range(0, no_vcds):\n address = bcm_status_fe + (0x4*x)\n fe_data = memory.read(address, 4)\n fe_status = struct.unpack('> 4 ) & 0xF)\n agg_bw = ((fe_status >> 16 ) & 0x3FFF)\n\n # if x==0: #mc\n # for x in range(0, ddr_cfg.nNumMCStates):\n # if (ddr_cfg.pMCCfg[x].clk_idx==agg_cp):\n # frq=ddr_cfg.pMCCfg[x].freq_khz\n\n # elif x==1: #shub\n # for y in range(0, ddr_cfg.nNumSHUBStates):\n # if (ddr_cfg.pSHUBCfg[y].clk_idx==agg_cp):\n # frq=ddr_cfg.pSHUBCfg[y].freq_khz\n \n \n ddr_mc_cp=hex(ddr_status.current_mc_cp) \n ddr_shub_cp=hex(ddr_status.current_shub_cp) \n \n \n \n \n flag=0\n for key, value in data.items() :\n if (data[key][\"VCD Index\"]==x) :\n if (x==0):\n v5=str(ddr_mc_cp)\n if (ddr_mc_cp!=0x0):\n flag=1\n var_print=key\n v1=hex(agg_bw)\n v2=hex(final_cp)\n v3=hex(agg_cp) \n v4=str(x)+\":\"\n for y in data[key][\"Clock Domains\"]:\n print(\"\\t|{0:3s}{1:>20s}|{2:>8s}|{3:>10s}|{4:>8s}|{5:>25s}|{6:30s}: {7:>17s}|\" .format(v4,var_print,v1,v2,v3,v5,y[\"domain\"],(str(y[\"freq\"][int(ddr_mc_cp,16)]).split(\":\")[1])[3:-2]), file=bcm_file)\n var_print=\"\" \n v1=\"\"\n v2=\"\"\n v3=\"\"\n v4=\"\" \n v5=\"\"\n \n elif (x==1):\n v5=str(ddr_shub_cp)\n if (ddr_shub_cp!=0x0):\n flag=1\n var_print=key\n v1=hex(agg_bw)\n v2=hex(final_cp)\n v3=hex(agg_cp) \n v4=str(x)+\":\"\n for y in data[key][\"Clock Domains\"]:\n print(\"\\t|{0:3s}{1:>20s}|{2:>8s}|{3:>10s}|{4:>8s}|{5:>25s}|{6:30s}: {7:>17s}|\" .format(v4,var_print,v1,v2,v3,v5,y[\"domain\"],(str(y[\"freq\"][int(ddr_shub_cp,16)]).split(\":\")[1])[3:-2]), file=bcm_file)\n var_print=\"\" \n v1=\"\"\n v2=\"\"\n v3=\"\"\n v4=\"\" \n v5=\"\" \n else:\n v5=\"NA\"\n if (agg_cp!=0):\n flag=1\n var_print=key\n v1=hex(agg_bw)\n v2=hex(final_cp)\n v3=hex(agg_cp) \n v4=str(x)+\":\"\n for y in data[key][\"Clock Domains\"]:\n print(\"\\t|{0:3s}{1:>20s}|{2:>8s}|{3:>10s}|{4:>8s}|{5:>25s}|{6:30s}: {7:>17s}|\" .format(v4,var_print,v1,v2,v3,v5,y[\"domain\"],(str(y[\"freq\"][agg_cp]).split(\":\")[1])[3:-2]), file=bcm_file)\n var_print=\"\" \n v1=\"\"\n v2=\"\"\n v3=\"\"\n v4=\"\" \n v5=\"\" \n \n if(flag==0):\n v6=str(x)+\":\"\n print(\"\\t|{0:<23s}|{1:>8s}|{2:>10s}|{3:>8s}|{4:>25s}|{5:50s}|\" .format( v6, hex(agg_bw), hex(final_cp), hex(agg_cp), \"NA\",\"\") , file=bcm_file)\n print(\"\\t~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\", file=bcm_file)\n \n \n \n print(\"\\n ~~BCM Status Back End~~\", file=bcm_file)\n print(\"\\n\\t~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\", file=bcm_file)\n print(\"\\t| VCD | Clk_dest_state | Combined_CP | SW_CP_SNAP | Written_CP | CURR_CP |\", file=bcm_file)\n print(\"\\t~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\", file=bcm_file)\n for x in range(0, no_vcds):\n address = bcm_status_be + (0x4*x)\n fe_data = memory.read(address, 4)\n fe_status = struct.unpack('> 4 ) & 0xF)\n sw_cp = ((fe_status >> 8 ) & 0xF)\n combined_cp = ((fe_status >> 12 ) & 0xF)\n clk_dest = ((fe_status >> 16 ) & 0xF)\n print(\"\\t|{0:>5d}|{1:>16s}|{2:>13s}|{3:>12s}|{4:>12s}|{5:>9s}|\" .format( x, hex(clk_dest), hex(combined_cp), hex(sw_cp), hex(written_cp), hex(curr_cp)), file=bcm_file)\n print(\"\\t~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\", file=bcm_file)\n\n print(\"\\n ~~BCM Back End Sequencer~~\", file=bcm_file)\n print(\"\\n ~~BCM Status~~\", file=summary_file)\n print(\"\\n\\t~~~~~~~~~~~~~~~~~~~~~~~~~~~~\", file=bcm_file)\n print(\"\\t| VCD | SEQ_CURR_PC | IDLE |\", file=bcm_file)\n print(\"\\t~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\", file=bcm_file)\n for x in range(0, no_vcds):\n address = bcm_status_be_seq + (0x4*x)\n fe_data = memory.read(address, 4)\n fe_status = struct.unpack('> 8 ) & 0xFF)\n print(\"\\t|{0:>5d}|{1:>8s}|{2:>10s}|\" .format( x, hex(curr_pc), hex(seq_state)), file=bcm_file)\n if seq_state:\n print(\"\\tVCD %d is Idle\" % (x) ,file=summary_file)\n else:\n print(\"\\tVCD %d is Busy\" % (x) ,file=summary_file)\n print(\"\\t~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\", file=bcm_file)\n\n print(\"\\n\\n ~~BCM Resource Summary~~\", file=bcm_file)\n #import pdb; pdb.set_trace()\n for regs in range(0,no_regs):\n if bcm_map_table[regs] == ' ':\n continue\n print('\\n\\n\\t BCM [%d] : %s ' % (regs,bcm_map_table[regs]), file=bcm_file)\n print(\"\\t\\t~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\", file=bcm_file)\n print(\"\\t\\t| DRV | ID | Valid | AB | IB |\", file=bcm_file)\n print(\"\\t\\t~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\", file=bcm_file)\n \n for drv in range(0,no_drv):\n address = vt_base_address + (0x10000*drv) + (0x4*regs) \n bcm_data = memory.read(address, 4) \n bcm_vt = struct.unpack('> 29) & 0x1 )\n vote_x = ((bcm_vt >> 14) & 0x3FFF )\n vote_y = (bcm_vt & 0x3FFF)\n if bcm_vt != 0:\n print(\"\\t\\t|{0:>10s}|{1:>4d}|{2:>7d}|{3:>8s}|{4:>8s}|\" .format((targ_spec_config[target]['drv'][drv]), drv, vote_valid, hex(vote_x),hex(vote_y) ), file=bcm_file)\n BCM_votetable[regs][drv] = [vote_valid, vote_x, vote_y]\n","sub_path":"aop_proc/core/bsp/aop/scripts/hansei/dumpers/bcm.py","file_name":"bcm.py","file_ext":"py","file_size_in_byte":14529,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"651128529","text":"#coding:utf-8\n__author__ = '613108'\n\nfrom pyquery import PyQuery as pq\nfrom threading import Thread\nfrom Queue import Queue\nimport sys,urllib2,time,random\nreload(sys)\nsys.setdefaultencoding('utf-8')\nsys.path.append(r'C:\\Users\\613108\\Desktop\\Project\\tool_self')\nimport my_proxy,My_Csv\nimport os,csv,socket,re\nsocket.setdefaulttimeout(2)\n\ndef use_proxy():\n proxy_port=my_proxy.is_proxy_exists()\n return proxy_port\n\n# 返回待抓取见面地址列表\n# href_file_path代表文件所在目录路径\n# index_title代表目标链接所有列的表头,如为最后一列,请添加\\n\ndef get_href_list(href_file_path,index_title):\n file_list=os.listdir(href_file_path)\n file_name_list=[href_file_path+'/'+item for item in file_list]\n temp_time=os.stat(file_name_list[0]).st_ctime\n temp_file_name=file_name_list[0]\n for item in file_name_list:\n # 判断是否为目录,如为目录则跳过\n if os.path.isdir(item):continue\n # 获取各文件创建时间\n file_create_time=os.stat(item).st_ctime\n if temp_time<=file_create_time:\n temp_time=file_create_time\n temp_file_name=item\n with open(temp_file_name,'r') as temp_file:\n res=temp_file.readlines()\n href_index=res[0].split(',').index(index_title)\n dict={}\n with open(temp_file_name,'r') as temp_file:\n reader=csv.reader(temp_file)\n i=0\n for row in reader:\n if i>0:\n dict[row[href_index]]=1\n i+=1\n href_list=[]\n for item in dict.items():\n href_list.append(item[0])\n return href_list\n\n# 获取sku信息,主要包括销量、颜色等等\nclass Get_productInfoDetail(Thread):\n # 对应循环1之构造函数\n # def __init__(self,href_list):\n # Thread.__init__(self)\n # self.href_list=href_list\n\n # 对应循环2之构造函数\n def __init__(self):\n Thread.__init__(self)\n\n def get_info(self):\n proxy_port=use_proxy()\n proxy=random.sample(proxy_port,1)[0]\n proxy=proxy[0]+':'+proxy[1]\n proxyHandler=urllib2.ProxyHandler({'http':r'http://%s'%proxy})\n cookies=urllib2.HTTPCookieProcessor\n opener=urllib2.build_opener(cookies,proxyHandler)\n opener.addheaders = [('User-agent', 'Mozilla/5.0 (Windows NT 6.2; WOW64; rv:22.0) Gecko/20100101 Firefox/22.0')]\n # 循环1:分割url列表,若需更换代理url将被遗弃\n # for url in self.href_list:\n # 循环2:利用queue在线程间同步数据,若需更换代理则将url put到queue,不会遗弃\n while queue_for_href_list.qsize()>0:\n url=queue_for_href_list.get()\n print('*'*60)\n print(url)\n try:\n res_temp=opener.open(url)\n src=res_temp.read()\n res_temp.close()\n except:\n queue_for_href_list.put(url)\n proxy=random.sample(proxy_port,1)[0]\n print(u'更换代理:%s:%s'%(proxy[0],proxy[1]))\n proxy=proxy[0]+':'+proxy[1]\n proxyHandler=urllib2.ProxyHandler({'http':r'http://%s'%proxy})\n opener=urllib2.build_opener(cookies,proxyHandler)\n continue\n d=pq(src)\n exp_price=d.find('.f_l.pricekt>span').text().split(':')[1]\n colors=d.find('#color_id')\n temp_for_size=len(colors)\n color=[]\n for item in colors:\n temp=pq(item).attr('title')\n color.append(temp)\n color='+'.join(color)\n sizes=d.find('.doselected')[temp_for_size:]\n size=[]\n for item in sizes:\n temp=pq(item).attr('data-sizes')\n size.append(temp)\n size='+'.join(size)\n sale=d.find('.kuc').text().split('已售 ')[1].split(' 件')[0]\n temp=d.find('.content.clearfix li')\n brand='-';sku='-';launch_date='-';sex='-'\n for item in temp:\n tt=pq(item).text()\n tt_1=tt.split(':')[0]\n tt_2=tt.split(':')[1]\n if tt_1==u'品牌':\n brand=tt_2\n elif tt_1==u'货号':\n sku=tt_2\n elif tt_1==u'上市时间':\n launch_date=tt_2\n elif tt_1==u'性别':\n sex=tt_2\n else:continue\n temp=[url,brand,sku,launch_date,sex,exp_price,color,size,sale]\n queue_for_result.put(temp)\n\n def run(self):\n self.get_info()\n\nif __name__=='__main__':\n t=time.time()\n temp=use_proxy()\n\n queue_for_href_list=Queue(0)\n queue_for_result=Queue(0)\n\n href_list=get_href_list(href_file_path=r'D:\\spider\\361du\\product_href',index_title='product_href\\n')\n for item in href_list:\n queue_for_href_list.put(item)\n\n # 配置项:线程数\n thread_count=50\n Get_productInfoDetail_thread=[]\n\n for i in range(thread_count):\n Get_productInfoDetail_thread.append(Get_productInfoDetail())\n for item in Get_productInfoDetail_thread:\n item.start()\n for item in Get_productInfoDetail_thread:\n item.join()\n\n # 结果持久化\n # 结果提取及标题处理\n result=[]\n for i in range(queue_for_result.qsize()):\n result.append(queue_for_result.get())\n title=['product_url','brand','sku','launch_date','sex','exp_price','color','size','sale']\n # 数据写入csv文件\n writer=My_Csv.Write_Csv(path=r'd:/spider/361du',name='361du_productInfoDetail',title=title,result=result)\n writer.add_title_data()\n\n print('*'*20+u'程序运行完毕,请检查数据'+'*'*20)\n\n t=time.time()-t\n print('*'*16+u'总计耗时:%f 秒'+'*'*16)%t","sub_path":"Official_store_project/361du_project/product_info_detail.py","file_name":"product_info_detail.py","file_ext":"py","file_size_in_byte":5773,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"354454141","text":"# coding: utf8\nimport smtplib \n#import email.MIMEMultipart\nimport email\nfrom email.mime.multipart import MIMEMultipart\nfrom email.mime.text import MIMEText\nfrom email.mime.base import MIMEBase\nimport os.path \n \nFrom = \"zpdsas@zplay.cn\" \nTo = \"zy_cosmos@126.com\" \nfile_name = \"legend.xlsx\" \n \nserver = smtplib.SMTP(\"smtp.exmail.qq.com\") \n\nserver.login(\"zpdsas@zplay.cn\",\"xxx\") #仅smtp服务器需要验证时 \n\n \n# 构造MIMEMultipart对象做为根容器 \nmain_msg = MIMEMultipart() \n \n# 构造MIMEText对象做为邮件显示内容并附加到根容器 \ntext_msg = MIMEText(\"邮件正文: this is a test text to text mime\") \nmain_msg.attach(text_msg) \n \n# 构造MIMEBase对象做为文件附件内容并附加到根容器 \ncontype = 'application/octet-stream' \nmaintype, subtype = contype.split('/', 1) \n \n## 读入文件内容并格式化 \ndata = open(file_name, 'rb') \nfile_msg = MIMEBase(maintype, subtype) \nfile_msg.set_payload(data.read( )) \ndata.close( ) \nemail.encoders.encode_base64(file_msg) \n \n## 设置附件头 \nbasename = os.path.basename(file_name) \nfile_msg.add_header('Content-Disposition', 'attachment', filename = basename) \nmain_msg.attach(file_msg) \n \n# 设置根容器属性 \nmain_msg['From'] = From \nmain_msg['To'] = To \nmain_msg['Subject'] = \"发送附件测试\" \nmain_msg['Date'] = email.utils.formatdate() \n\n \n# 得到格式化后的完整文本 \nfullText = main_msg.as_string( ) \n \n# 用smtp发送邮件 \ntry: \n server.sendmail(From, To, fullText) \nfinally: \n server.quit() \n","sub_path":"python/excel/send_email_with_attachment.py","file_name":"send_email_with_attachment.py","file_ext":"py","file_size_in_byte":1556,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"129591524","text":"from ccxt_data import data, pd\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom mpl_finance import candlestick_ohlc\nfrom matplotlib.collections import LineCollection\n\n# Styling the Chart.\nplt.style.use('seaborn-dark')\n\nfor param in ['figure.facecolor', 'axes.facecolor', 'savefig.facecolor']:\n plt.rcParams[param] = '#131722' # bluish dark grey\nfor param in ['text.color', 'axes.labelcolor', 'xtick.color', 'ytick.color']:\n plt.rcParams[param] = '0.9' # very light grey\n\n\nclass GridTradingSystem:\n\tdef __init__(self, symbol: str, df: pd.DataFrame, yesterdays_price: pd.DataFrame, length: int):\n\t\tself.symbol = symbol\n\t\tself.length = length\n\t\tself.df = df\n\t\tself.yesterdays_price = yesterdays_price\n\t\t\n\t\tself.levels = []\n\n\t\tself.cash, self.trade_amount, self.depot = 50, 0.0023, 0\n\n\t\tself.buy, self.buy_date = [], []\n\t\tself.sell, self.sell_date = [], []\n\t\tself.buy_levels = []\n\n\t# Calculate the Grid Levels and save them in a list.\n\tdef grid(self):\n\t\tdiff = (self.yesterdays_price['high'][0]-self.yesterdays_price['low'][0])\n\n\t\tdistance = diff/5\n\t\tstart = ((diff/2)+self.yesterdays_price['low'][0])-(distance*6)\n\n\t\tfor _ in range(11):\n\t\t\tstart += distance\n\t\t\tself.levels.append(start) \n\n\tdef strategy(self):\n\t\tfor idx, (high, low, close) in enumerate(zip(self.df['high'], self.df['low'], self.df['close'])):\n\t\t\tranges = np.arange(low, high, 0.1)\n\t\t\tfor i in range(11):\n\t\t\t\tfor r in ranges:\n\t\t\t\t\tif round(self.levels[i], 1) == round(r, 1):\n\t\t\t\t\t\tif idx > 0:\n\t\t\t\t\t\t\tif self.levels[i] < self.df['close'][idx-1]:\n\t\t\t\t\t\t\t\tif self.cash > self.trade_amount*close:\n\t\t\t\t\t\t\t\t\tself.depot += self.trade_amount\n\t\t\t\t\t\t\t\t\tself.cash -= self.trade_amount*close\n\t\t\t\t\t\t\t\t\tself.buy.append(close)\n\t\t\t\t\t\t\t\t\tself.buy_date.append(idx)\n\t\t\t\t\t\t\t\t\tself.buy_levels.append(i)\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t\telif self.levels[i] > self.df['close'][idx-1]:\n\t\t\t\t\t\t\t\tif len(self.buy_levels) > 0:\n\t\t\t\t\t\t\t\t\tif self.depot > self.trade_amount:\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\t\tfor buy_level in self.buy_levels:\n\t\t\t\t\t\t\t\t\t\t\tif buy_level < i:\n\t\t\t\t\t\t\t\t\t\t\t\tself.cash += (close*self.trade_amount)\n\t\t\t\t\t\t\t\t\t\t\t\tself.depot -= self.trade_amount\n\t\t\t\t\t\t\t\t\t\t\t\tself.sell.append(close)\n\t\t\t\t\t\t\t\t\t\t\t\tself.sell_date.append(idx)\n\n\t\t\t\t\t\t\t\t\t\t\t\tself.buy_levels.pop(self.buy_levels.index(buy_level))\n\n\t\tprint(f\"Total Balance: {self.df['close'].iloc[-1]*self.depot+self.cash}$, Depot: {self.depot}, Cash: {self.cash}$\\nTrades: {len(self.buy)+len(self.sell)}\")\n\t\t\t\t\t\t\n\n\tdef plot(self):\n\t\tgrid_length = []\n\t\tfor i in self.levels:\n\t\t\tgrid_length.append(list([i for _ in range(self.length)]))\n\n\t\tY = np.array(grid_length)\n\t\tX = np.array([_ for _ in range(self.length)])\n\n\t\tx = np.tile(X, Y.shape[0]).reshape(*Y.shape)\n\t\tv = np.stack((x,Y), axis=-1)\n\t\tc = LineCollection(v)\n\n\t\tfig, ax = plt.subplots()\n\t\tax.add_collection(c)\n\t\tax.autoscale()\n\t\tself.df.drop(columns=['date', f'Volume {self.symbol}'])\n\t\tself.df['date'] = X\n\t\tcandlestick_ohlc(ax, self.df.values, width=0.6, colorup='gray', colordown='y')\n\t\tax.grid(color='#2A3459')\n\t\tax.plot(self.buy_date, self.buy, 'v', c='g')\n\t\tax.plot(self.sell_date, self.sell, 'v', c='r')\n\n\t\tplt.show()\n\ndef main():\n\tsymbol = \"ETH/USDT\"\n\tlength = 480\n\tdf = data(symbol, length, \"3m\")\n\tyesterdays_price = data(symbol, 2, \"1d\")\n\n\tGTS = GridTradingSystem(symbol, df, yesterdays_price, length)\n\tGTS.grid()\n\tGTS.strategy()\n\tGTS.plot()\n\nif __name__ == '__main__':\n\tmain()","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":3315,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"634954769","text":"#!/usr/bin/env python3\n# -*- coding:utf-8 -*-\n#\n# @name : KITT Lite - Lite Version of KITT Framework\n# @url : https://github.com/Cisc0-gif\n# @author : Cisc0-gif\nimport os\nimport time\nimport socket\nimport requests\nimport sys\nimport random\n\ndef wait():\n wait = input('PRESS ENTER TO CONTINUE')\n\ndef runtimecheck(): #returns current runtime\n global check\n check = time.time()\n msg = str(check - start)\n return msg\n\ndef timecheck(): #returns current local time\n return time.ctime()\n\ndef logwrite(msg): #writes input to RUNTIME.log\n with open('/opt/KITT-Lite/RUNTIME.log', 'a+') as f:\n f.write(msg + '\\n')\n f.close()\n\nif len(sys.argv) != 2 or '--help' in sys.argv:\n print('KITT Lite v1.0 Python-Based Pentesting Framework')\n print('Sourced on Github and created by Cisc0-gif, Ecorp7@protonmail.com\\n')\n print(' ./KITT_lite.py --help for this menu')\n print('OSINT:')\n print(' -ds, --domainsticate Extensive Domain Enumeration')\n print(' -sh, --shodan_search Search for IP info on shodan')\n print(' -pi, --phone_infoga Search for Phone # info ')\n print('PrivEsc:')\n print(' -pe, --escalate SimpleHTTPServer w/ PrivEsc scripts on port 80')\n print('Network Cracking:')\n print(' -nc, --netcrack Network Cracking Tool Suite')\n print(' -ap, --apspoof AP Spoofing Tool')\n print(' -pd, --packdump Packet Capture Tool')\n print('IoT Exploitation:')\n print(' -hp, --homepwn IoT Exploit Tool Suite')\n print(' -pb, --pentbox HoneyPot Tool Suite')\n print(' -st, --btspoof BT Spoofer')\n print(' -bv, --btverify Rfcomm Channel Verifier')\n print(' -bs, --bluescan BT Port/MAC Scanner')\n print('Hardware Hacking:')\n print(' -mj, --mousejack Intel Keyboard/Mice Hijacker')\n print(' -gp, --gpioctl GPIO Controller (Only for RPi)')\n print('System Security:')\n print(' -sp, --sshportrand SSH Port Randomizer')\n print(' -sc, --sshautoconfig SSHD Config Buff')\n print(' -pc, --proxyconfig ProxyChains Config')\n print(' -fb, --fail2ban Fail2ban IP Jail Config')\n print(' -di, --dhcpip DHCP IP Receiver')\n print('Example:')\n print(' KITTlite --netcrack')\n sys.exit(1)\n\nshort = ['-ds', '-sh', '-pi', '-pe', '-nc', '-ap', '-pd', '-hp', '-pb', '-st', '-bv', '-bs', '-mj', '-gp', '-sp', '-sc', '-pc', '-fb', '-di']\nlong = ['--domainsticate', '--shodan_search', '--phone_infoga', '--escalate', '--netcrack', '--apspoof', '--packdump', '--homepwn', '--pentbox', '--btspoof', '--btverify', '--bluescan', '--mousejack', '--gpioctl', '--sshportrand', '--sshautoconfig', '--proxyconfig', '--fail2ban', '--dhcpip']\n\ntool = sys.argv[1]\n\nos.chdir('/opt/KITT-Lite')\n \ndef gohome():\n os.chdir('/opt/KITT-Lite')\n \nif tool == '-ds' or tool == '--domainsticate':\n try:\n os.chdir('hg')\n os.system('python3 domain_sticate.py')\n logwrite('--[+]Successfully ran domainsticate @ ' + timecheck() + '--')\n except:\n logwrite('--[*]Error running domainsticate @ ' + timecheck() + '--')\n gohome()\n\nif tool == '-sh' or tool == '--shodan_search':\n try:\n os.system('python3 shodan_search.py')\n logwrite('--[+]Successfully ran shodan_search @ ' + timecheck() + '--')\n except:\n logwrite('--[*]Error running shodan_search @ ' + timecheck() + '--')\n gohome()\n\nif tool == '-pi' or tool == '--phone_infoga':\n try:\n os.chdir('PhoneInfoga')\n os.system('python3 phoneinfoga.py')\n logwrite('--[+]Successfully ran phone_infoga @ ' + timecheck() + '--')\n except:\n logwrite('--[*]Error runnning phone_infoga @ ' + timecheck() + '--')\n gohome()\n\nif tool == '-pe' or tool == '--escalate':\n try:\n os.chdir('escalate')\n print('[*]Starting python SimpleHTTPServer on Port 80 to curl payloads')\n print('[*]Enter ^C or ^Z To Stop HTTP Server...')\n s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)\n s.connect((\"8.8.8.8\", 80))\n r = requests.get(\"http://ifconfig.me\").text\n print('[*]Private IP: ' + str(s.getsockname()[0]))\n print('[*]Public IP: ' + str(r))\n os.system(\"python -m SimpleHTTPServer 80\")\n s.close()\n logwrite('--[*]Successfully ended SimpleHTTPServer @ ' + timecheck() + '--')\n except:\n logwrite('--[*]Error running SimpleHTTPServer @ ' + timecheck() + '--')\n gohome()\n\nif tool == '-nc' or tool == '--netcrack':\n try:\n os.system('python3 network_crack.py')\n logwrite('--[+]Successfully ran network_crack @ ' + timecheck() + '--')\n except:\n logwrite('--[*]Error running network_crack @ ' + timecheck() + '--')\n gohome()\n\nif tool == '-ap' or tool == '--apspoof':\n try:\n os.chdir('AP_Spoof')\n os.system('bash setup.sh')\n logwrite('--[+]Successfully ran AP_Spoof setup.sh @ ' + timecheck() + '--')\n except:\n logwrite('--[*]Error running AP_Spoof setup.sh @ ' + timecheck() + '--')\n gohome()\n\nif tool == '-pd' or tool == '--packdump':\n try:\n os.system('bash packetdump.sh')\n logwrite('--[+]Successfully ran packetdump.sh @ ' + timecheck() + '--')\n except:\n logwrite('--[*]Error running packetdump.sh @ ' + timecheck() + '--')\n gohome()\n\nif tool == '-hp' or tool == '--homepwn':\n try:\n os.chdir('HomePWN')\n os.system('python3 homePwn.py')\n logwrite('--[+]Successfully ran HomePWN @ ' + timecheck() + '--')\n except:\n logwrite('--[*]Error running HomePWN @ ' + timecheck() + '--')\n gohome()\n\nif tool == '-pb' or tool == '--pentbox':\n try:\n os.chdir('pentbox/pentbox-1.8')\n os.system('ruby pentbox.rb')\n logwrite('--[+]Successfully ran pentbox @ ' + timecheck() + '--')\n except:\n logwrite('--[+]Error running pentbox @ ' + timecheck() + '--')\n gohome()\n\nif tool == '-st' or tool == '--btspoof':\n try:\n os.system('bash bluespoof.sh')\n logwrite('--[+]Successfully ran bluespoof @ ' + timecheck() + '--')\n except:\n logwrite('--[*]Error running bluespoof @ ' + timecheck() + '--')\n gohome()\n\nif tool == '-bv' or tool == '--btverify':\n try:\n os.system('python3 btverifier.py')\n logwrite('--[+]Successfully ran btverifier @ ' + timecheck() + '--')\n except:\n logwrite('--[*]Error running btverifier @ ' + timecheck() + '--')\n gohome()\n\nif tool == '-bs' or tool == '--bluescan':\n try:\n os.system('bash BlueScan.sh')\n logwrite('--[+]Successfully ran BlueScan @ ' + timecheck() + '--')\n except:\n logwrite('--[*]Error running BlueScan @ ' + timecheck() + '--')\n gohome()\n\nif tool == '-mj' or tool == '--mousejack':\n moj = input(\"[*]Do you want to initialize a [m]ousejack device or scan with [j]ackit?: \")\n if moj == 'M' or moj == 'm':\n try:\n print(\"[*]Insert CrazyRadio PA device...\")\n wait()\n os.chdir('mousejack/nrf-research-firmware')\n os.system('sudo make')\n os.system('sudo make install')\n os.system('dmesg')\n print(\"[+]Firmware Uploaded!\")\n logwrite('--[+]Successfully uploaded mousejack firmware to CrazyRadio PA @ ' + timecheck() + '--')\n except:\n print(\"[*]Failed to upload Firmware!\")\n logwrite('--[*]Failed to upload mouesjack firmware to CrazyRadio PA @ ' + timecheck() + '--')\n elif moj == 'J' or moj == 'j':\n try:\n print(\"[*]Insert CrazyRadio PA device w/ mousejack firmware...\")\n wait()\n os.system('jackit')\n print('[+]Scan complete!')\n logwrite('--[+]Successfully ended jackit scan @ ' + timecheck() + '--')\n except:\n print(\"[*]Error scanning with jackit\")\n logwrite('--[*]Error scanning with jackit @ ' + timecheck() + '--')\n wait()\n else:\n print(\"[*]Not an option!\")\n time.sleep(2)\n gohome()\n\nif tool == '-gp' or tool == '--gpioctl':\n try:\n os.system('python3 GPIO_CTL.py')\n logwrite('--[+]Successfully ran GPIO_CTL @ ' + timecheck() + '--')\n except:\n logwrite('--[*]Error running GPIO_CTL @ ' + timecheck() + '--')\n gohome()\n\nif tool == '-sp' or tool == '--sshportrand':\n try:\n os.chdir('sdefense')\n os.system('bash ssh_randomizer.sh')\n logwrite('--[+]Successfully ran ssh_randomizer @ ' + timecheck() + '--')\n except:\n logwrite('--[*]Error running ssh_randomizer @ ' + timecheck() + '--')\n gohome()\n\nif tool == '-sc' or tool == '--sshautoconfig':\n try:\n os.chdir('sdefense')\n os.system('bash ssh_encr7pt.sh')\n logwrite('--[+]Successfully ran ssh_encr7pt @ ' + timecheck() + '--')\n except:\n logwrite('--[*]Error running ssh_encr7pt @ ' + timecheck() + '--')\n gohome()\n\nif tool == '-pc' or tool == '--proxyconfig':\n try:\n os.chdir('sdefense')\n os.system('bash proxy_config.sh')\n logwrite('--[+]Successfully ran proxy_config @ ' + timecheck() + '--')\n except:\n logwrite('--[*]Error running proxy_config @ ' + timecheck() + '--')\n gohome()\n\nif tool == '-fb' or tool == '--fail2ban':\n try:\n ipbu = input('[*]Are you going to [B]an or [U]nban an IP?: ')\n if ipbu == 'B' or ipbu == 'b':\n ip = input('[*]Enter IP: ')\n os.system('sudo fail2ban-client set sshd banip ' + ip)\n print('[+]Banned IP ' + ip + '!')\n logwrite('--[+]Banned IP ' + ip + ' @ ' + timecheck() + '--')\n else:\n ip = input('[*]Enter IP: ')\n os.system('sudo fail2ban-client set sshd unbanip ' + ip)\n print('[+]Unbanned IP ' + ip + '!')\n logwrite('--[+]Unbanned IP ' + ip + ' @ ' + timecheck() + '--')\n except:\n logwrite('--[*]Error configuring fail2ban @ ' + timecheck() + '--')\n print('[*]Error configuring fail2ban')\n gohome()\n\nif tool == '-di' or tool == '--dhcpip':\n try:\n os.chdir('sdefense')\n os.system('bash dh_recv.sh')\n logwrite('--[+]Successfully ran dh_recv @ ' + timecheck() + '--')\n except:\n logwrite('--[*]Error running dh_recv @ ' + timecheck() + '--')\n gohome()\n\nif tool not in short or tool not in long:\n print(sys.argv[1] + ' not an option!')\n","sub_path":"KITT_lite.py","file_name":"KITT_lite.py","file_ext":"py","file_size_in_byte":10062,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"456482205","text":"from django.conf.urls import patterns, include, url\nfrom django.conf import settings\n\nfrom django.contrib import admin\nadmin.autodiscover()\n\nurlpatterns = patterns('',\n # Examples:\n url(r'^admin/', include(admin.site.urls)),\n url(r'^$', 'joins.views.home', name='home'),\n # url(r'^testhome$', 'src.views.testhome', name='testhome'),\n url(r'^(?P\\w{10})$', 'joins.views.share', name='share'),\n # url(r'^home2/$', 'lwc.views.home2', name='home'),\n # url(r'^blog/', include('blog.urls')),\n)\n\nif not settings.DEBUG:\n urlpatterns += patterns('',\n (r'^static/(?P.*)$', 'django.views.static.serve', {'document_root': settings.STATIC_ROOT}),\n )","sub_path":"src/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":682,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"498706726","text":"# -*- coding: utf-8 -*-\n# ---\n# @Institution: Automation,T&E,Turing,HQ\n# @Time: 2021/6/2\n# @File: start_all_test.py\n# @Author: pengleiyang\n# @E-mail: pengleiyang@huaqin.com\n# @Desc: car4.1自动化测试脚本\n# @update: Record important updates\n# ---\n\nimport os\nimport unittest\nimport time\nimport warnings\nimport colorsys\nimport PIL.Image as Image\nimport uiautomator2 as u2\nfrom utils.device_info_util.device_info import DeviceInfo\nfrom utils.pic_util.pic_util import PicUtil\n\n\nclass Car(unittest.TestCase):\n def setUp(self):\n support_device = 'HQ60CT3016'\n warnings.simplefilter('ignore', ResourceWarning) # 屏蔽警报信息\n print(\"测试开始\")\n print(\"获取手机设备信息!\")\n self.device = DeviceInfo()\n print(support_device)\n self.devices = self.device.check_device()[0]\n self.devices.remove(support_device)\n self.test_device = self.devices[0]\n self.d = u2.connect(self.test_device) # 连接待测设备\n self.d.unlock()\n print(\"解锁成功\")\n\n def test_car(self):\n print(\"启动cts测试应用!\")\n os.system(\"adb shell am start -n com.android.cts.verifier/com.android.cts.verifier.CtsVerifierActivity\")\n self.assertFalse(self.d.exists(text=\"Folded\") and self.d.exists(resourceId=\"com.android.cts.verifier:id/export\")\n , \"cts未在主界面,请检查\")\n for i in range(100):\n if self.d.exists(text=\"Car Dock Test\"):\n self.d(text=\"Car Dock Test\").click()\n break\n else:\n self.d.swipe(0.5, 0.9, 0.5, 0.2)\n time.sleep(2)\n if self.d.exists(resourceId=\"android:id/button1\"):\n self.d(resourceId=\"android:id/button1\").click()\n time.sleep(1)\n self.d(text=\"ENABLE CAR MODE\").click()\n toast_info = self.d.toast.get_message(5, 3, 'Not Found Toast')\n print(toast_info + '\\n')\n if 'CAR_DOCK' not in toast_info:\n raise AssertionError('Location 更新的对话框未出现')\n else:\n print('出现Location 更新的对话框')\n self.d.press(\"home\")\n time.sleep(5)\n for i in range(100):\n if self.d.exists(text=\"Car Dock Test\"):\n points = self.d(text=\"Car Dock Test\").info.get(\"bounds\")\n print(points)\n im = self.d(text=\"Car Dock Test\").screenshot()\n im.save(\"test.jpg\")\n image = Image.open('test.jpg')\n image = image.convert('RGB')\n color = PicUtil().get_dominant_color(image)\n print(color)\n # 绿色RGB值范围: 80-90,100-110, 25-35\n # 红色RGB值范围: 120-130, 62-73, 55-65\n R,G,B = color\n if 80 < int(R) < 90 and 100 < int(G) < 110 and 25 < int(B) < 35:\n print(\"测试pass!\")\n break\n else:\n self.d.swipe(0.5, 0.9, 0.5, 0.2)\n time.sleep(2)\n\n def tearDown(self):\n print(\"测试结束,测试步骤回收!\")\n self.d.app_stop_all() # 停止所有应用\n self.d.screen_off() # 锁屏\n\n\nif __name__ == '__main__':\n unittest.main()\n\n","sub_path":"testcases/car/test_car_4_1.py","file_name":"test_car_4_1.py","file_ext":"py","file_size_in_byte":3289,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"586602921","text":"#!/usr/bin/env python3\nimport math\nimport legendre\n\n\ndef main():\n f = lambda x: math.log(x + 2)\n actual_value = math.log(27) - 2\n for n in [2, 4, 8, 16]:\n int_value = legendre.gauss_quadratur(n)(f)\n error = abs(int_value - actual_value)\n print(f\"n = {n}, int = {int_value}, err={error}\")\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":358,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"623477925","text":"import re, os, time, datetime, pickle, glob\nimport numpy as np\nimport pandas as pd\nimport lightgbm as lgbm\nfrom sklearn.model_selection import StratifiedKFold\nfrom utils.misc import save_feature_importance\n\nclass LgbmModel:\n\n def __init__(self):\n self.bsts = [] # Boosters for each fold\n self.fold_info = [] # List of tuples of form (fold_num, train_ixs, val_ixs)\n\n def fit(self, train, y_tgt, params, run_params, nfolds, nfolds_to_run, metric, model_name, save_model, save_feat_importances, random_seed, feval=None):\n\n '''\n Fit lgbm booster using CV\n\n :param train:\n :param y_tgt:\n :param params:\n :param run_params:\n :param nfolds: int\n Number of CV folds\n :param nfolds_to_run:\n Number of CV folds to compute\n :param metric:\n :param model_name:\n :param save_model:\n :param save_feat_importances:\n :param random_seed:\n :param feval:\n :return:\n '''\n\n if nfolds_to_run is None:\n nfolds_to_run = nfolds\n\n # Setup CV folds\n fold_metrics = []\n feature_importance_df = pd.DataFrame()\n y_oof = np.zeros(y_tgt.size, dtype=np.float32)\n\n for fold_num, (train_ix, val_ix) in enumerate(\n StratifiedKFold(\n n_splits=nfolds,\n random_state=random_seed,\n shuffle=True,\n ).split(X=train, y=train.loc[:,'type'].values)\n ):\n self.fold_info.append((fold_num, train_ix, val_ix))\n\n if save_model:\n timestamp = datetime.datetime.fromtimestamp(time.time()).strftime('%Y-%m-%d %H:%M:%S')\n full_model_name = f'{model_name}_{timestamp}'\n print('> lgbm : Creating save dir . . .')\n model_dir = f'models/{full_model_name}'\n if not os.path.exists(model_dir):\n os.makedirs(f'models/{full_model_name}')\n\n # Train one booster per fold\n for fold_num, train_ix, val_ix in self.fold_info:\n\n if fold_num + 1 > nfolds_to_run:\n print(f'> lgbm: Done training only {nfolds_to_run} fold(s).')\n break\n\n print(f'> lgbm : Training on fold number {fold_num} . . .')\n\n x_train_fold = train.iloc[train_ix, :]\n x_val_fold = train.iloc[val_ix, :]\n \n train_data = lgbm.Dataset(data=x_train_fold, label=y_tgt[train_ix], free_raw_data=True)\n val_data = lgbm.Dataset(data=x_val_fold, label=y_tgt[val_ix], free_raw_data=False)\n\n bst = lgbm.train(\n params,\n train_data,\n valid_sets = val_data,\n # feval = feval,\n num_boost_round = run_params['num_boost_round'],\n early_stopping_rounds = run_params['early_stopping_rounds'],\n verbose_eval = run_params['verbose_eval'],\n )\n\n self.bsts.append(bst)\n\n oof_pred = bst.predict(x_val_fold)\n\n y_oof[val_ix] = oof_pred\n meanoof = np.mean(oof_pred)\n\n # OOF metric\n oof_metric = metric(\n pred=oof_pred,\n true=y_tgt[val_ix],\n types=x_val_fold.loc[:, 'type'].values,\n )\n fold_metrics.append(oof_metric)\n print(f'> lgbm : Fold metric : {oof_metric:.4f}')\n\n if save_model:\n print('> lgbm : Saving fold booster . . .')\n\n # Save fold info\n with open(f'{model_dir}/fold_info.pkl', 'wb') as h:\n pickle.dump(self.fold_info, h)\n\n bst.save_model(f'{model_dir}/bst_{fold_num:d}_metric_{oof_metric:.4f}.bst')\n\n # Feature importances\n if save_feat_importances:\n fold_importance_df = pd.DataFrame()\n fold_importance_df[\"feature\"] = train.columns\n fold_importance_df[\"importance\"] = bst.feature_importance(importance_type='split')\n fold_importance_df[\"fold\"] = fold_num + 1\n feature_importance_df = pd.concat([feature_importance_df, fold_importance_df], axis=0)\n\n print('> lgbm : CV results :')\n print(pd.Series(fold_metrics).describe())\n\n if save_feat_importances: # After saving boosters, to prevent unknown interaction between mpl and lgbm\n save_feature_importance(\n feature_importance_df=feature_importance_df,\n num_feats=100,\n relative_save_path=f'./importances/{full_model_name}.png',\n )\n\n def load(self, model_dir):\n if not os.path.exists(model_dir):\n raise NotADirectoryError(f'Cannot load from {model_dir}. Invalid directory.')\n\n # Load fold info\n with open(f'{model_dir}/fold_info.pkl', 'rb') as fold_info:\n self.fold_info = pickle.load(fold_info)\n\n # Load boosters in fold order\n bst_paths = glob.glob(f'{model_dir}/bst*')\n self.bsts = [None]*len(bst_paths)\n for bst_path in bst_paths:\n bst_num = int(re.search('bst_\\d+_', bst_path).group()[4:-1])\n print(f'Loading bst number {bst_num:d} at path {bst_path}')\n self.bsts[bst_num] = lgbm.Booster(model_file=bst_path)\n print('Done loading')\n\n def predict(self, dataset, is_train):\n '''\n Predicts using boosters from all folds. If predict sub, may use less than all available folds\n\n :param dataset: pandas df\n Train or test dataset\n :param is_train: bool\n If true will compute oof predictions. If false will compute average across folds\n :return: np array\n Predictions\n '''\n\n if not self.bsts:\n raise AssertionError('No trained lgbm boosters found. Fit or load boosters before predicting.')\n else:\n print(f'> lgbm : Found {len(self.bsts):d} boosters.')\n\n y_oof = np.zeros(dataset.shape[0])\n y_test_preds = np.zeros((dataset.shape[0], len(self.bsts)))\n\n for (fold_num, train_ixs, val_ixs), bst in zip(self.fold_info, self.bsts):\n print(f'> lgbm : Predicting fold number {fold_num} . . .')\n if is_train:\n x_val_fold = dataset.iloc[val_ixs, :]\n oof_pred = bst.predict(x_val_fold)\n y_oof[val_ixs] = oof_pred\n\n else: # Predict test values\n y_test_preds[:, fold_num] = bst.predict(dataset)\n\n if not is_train:\n return np.mean(y_test_preds, axis=1)\n else:\n return y_oof\n","sub_path":"lgbm.py","file_name":"lgbm.py","file_ext":"py","file_size_in_byte":6594,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"226323665","text":"# coding=utf-8\nimport urllib, urllib2\nimport re\nimport time, random\nimport hashlib\nimport sys\n\n# python2默认ascii编码,已经过时了\nreload(sys)\nsys.setdefaultencoding('utf-8')\n\n\nclass Translate:\n def __init__(self, key, lan1=\"AUTO\", lan2=\"AUTO\"):\n self.key = key\n self.lan1 = lan1\n self.lan2 = lan2\n self.url = \"http://fanyi.youdao.com/translate_o?smartresult=dict&smartresult=rule\"\n\n def getSalt(self):\n salt = int(time.time()*1000) + random.randint(0,10)\n return salt\n\n def getMD5(self, v):\n md5 = hashlib.md5()\n md5.update(v)\n sign = md5.hexdigest()\n return sign\n\n def getSign(self, key, salt):\n # key = key.encode()\n sign = 'fanyideskweb' + key + str(salt) + \"ebSeFb%=XZ%T[KZ)c(sy!\"\n sign = self.getMD5(sign)\n return sign\n\n def youdao(self):\n self.salt = self.getSalt()\n data = {\n \"i\": self.key,\n \"from\": self.lan1,\n \"to\": self.lan2,\n \"smartresult\": \"dict\",\n \"client\": \"fanyideskweb\",\n \"salt\": str(self.salt),\n \"sign\": self.getSign(self.key, self.salt),\n \"doctype\": \"json\",\n \"version\": \"2.1\",\n \"keyfrom\": \"fanyi.web\",\n \"action\":\"FY_BY_REALTIME\",\n \"typoResult\": \"false\"\n }\n data = urllib.urlencode(data)\n headers = {\n \"Accept\": \"application/json, text/javascript, */*; q=0.01\",\n \"Accept-Language\": \"zh-CN,zh;q=0.9\",\n \"Connection\": \"keep-alive\",\n \"Content-Length\": len(data),\n \"Content-Type\": \"application/x-www-form-urlencoded; charset=UTF-8\",\n \"Cookie\": \"OUTFOX_SEARCH_USER_ID=-391420597@10.168.1.8; JSESSIONID=aaacVRc_vIiemgTpW1krw; OUTFOX_SEARCH_USER_ID_NCOO=1920042841.903593; fanyi-ad-id=46607; fanyi-ad-closed=1; ___rl__test__cookies=1530264003877\",\n \"Host\": \"fanyi.youdao.com\",\n \"Origin\": \"http://fanyi.youdao.com\",\n \"Referer\": \"http://fanyi.youdao.com/\",\n \"User-Agent\": \"Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.87 Safari/537.36\",\n \"X-Requested-With\": \"XMLHttpRequest\"\n }\n req = urllib2.Request(url=self.url, data=data, headers=headers)\n rsp = urllib2.urlopen(req)\n html = rsp.read()\n html = re.findall(r'\"tgt\":\"([^\"]+)\"', html)\n return html[0]\n\n\n\n\n\n","sub_path":"MySite/youdao.py","file_name":"youdao.py","file_ext":"py","file_size_in_byte":2544,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"622746109","text":"'''\nhttps://leetcode.com/problems/frog-jump-ii/\n\nYou are given a 0-indexed integer array stones sorted in strictly increasing order \nrepresenting the positions of stones in a river.\n\nA frog, initially on the first stone, wants to travel to the last stone and then return to the first stone. \nHowever, it can jump to any stone at most once.\n\nThe length of a jump is the absolute difference between the position \nof the stone the frog is currently on and the position of the stone to which the frog jumps.\n\nMore formally, if the frog is at stones[i] and is jumping to stones[j], \nthe length of the jump is |stones[i] - stones[j]|.\nThe cost of a path is the maximum length of a jump among all jumps in the path.\n\nReturn the minimum cost of a path for the frog.\n\n\nInput: stones = [0,2,5,6,7]\nOutput: 5\nExplanation: The above figure represents one of the optimal paths the frog can take.\nThe cost of this path is 5, which is the maximum length of a jump.\nSince it is not possible to achieve a cost of less than 5, we return it.\n\n\nInput: stones = [0,3,9]\nOutput: 9\nExplanation: \nThe frog can jump directly to the last stone and come back to the first stone. \nIn this case, the length of each jump will be 9. The cost for the path will be max(9, 9) = 9.\nIt can be shown that this is the minimum achievable cost.\n\n\nConstraints:\n2 <= stones.length <= 105\n0 <= stones[i] <= 109\nstones[0] == 0\nstones is sorted in a strictly increasing order.\n'''\n\n\n# Ot(n) Os(1)\ndef min_cost(stones: list) -> int:\n if len(stones) == 1:\n return -1\n elif len(stones) == 2:\n return stones[1] - stones[0]\n\n min_jump = 0\n for i in range(2, len(stones)):\n min_jump = max(min_jump, stones[i] - stones[i - 2])\n return min_jump\n\n\nstones = [2]\nexp = -1\nprint(min_cost(stones) == exp)\n\nstones = [0,3]\nexp = 3\nprint(min_cost(stones) == exp)\n\nstones = [0,3,9]\nexp = 9\nprint(min_cost(stones) == exp)\n\nstones = [0,9,12]\nexp = 12\nprint(min_cost(stones) == exp)\n\nstones = [1,2,3,4]\nexp = 2\nprint(min_cost(stones) == exp)\n\nstones = [0,2,5,6,7]\nexp = 5\nprint(min_cost(stones) == exp)\n\nstones = [1,2,3,6,7,9]\nexp = 4\nprint(min_cost(stones) == exp)\n\nstones = [0,2,5,6,7,20,40,42,45,55]\nexp = 33\nprint(min_cost(stones) == exp)\n\nstones = [0,3,4,10,20]\nexp = 16\nprint(min_cost(stones) == exp)\n","sub_path":"coding_challenges_example_solutions/flog_jump/frog_jump.py","file_name":"frog_jump.py","file_ext":"py","file_size_in_byte":2278,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"99508424","text":"import pandas as pd\r\nfrom PIL import Image\r\nimport os\r\nfrom sklearn.preprocessing import LabelEncoder\r\nfrom pathlib import Path\r\nimport numpy as np\r\nfrom Constant import base_address\r\n#base_address = '/Users/User/PycharmProjects/PR-termProject/wikiart/'\r\n\r\n\r\ndef read_artist_data(base_address, filepath):\r\n \"\"\"\r\n Read artist_train.csv to view each image. \r\n :param base_address: str, absolute location for the wikiart dataset\r\n :param filepath: str, absolute location for the train/eval file to be read. \r\n \"\"\"\r\n filepath = base_address + filepath\r\n paintings_by_artist = pd.read_csv(filepath,names=['location', 'class'], header=0)\r\n paintings_by_artist['absolute_location'] = base_address+paintings_by_artist['location']\r\n paintings_by_artist = paintings_by_artist.sort_values('class')\r\n for i in range(paintings_by_artist.shape[0]):\r\n link = paintings_by_artist.iloc[i]['absolute_location']\r\n #print(link)\r\n my_file = Path(link)\r\n img = Image.open(link,'r')\r\n\r\n #img.show()\r\n\r\ndef read_artist_data_with_limit(base_address, filepath):\r\n \"\"\"\r\n Read artist_train.csv to view each image.\r\n :param base_address: str, absolute location for the wikiart dataset\r\n :param filepath: str, absolute location for the train/eval file to be read.\r\n ids,location,artist,class\r\n \"\"\"\r\n filepath = base_address + filepath\r\n paintings_by_artist = pd.read_csv(filepath,names=['location', 'class'], header=0)\r\n paintings_by_artist['absolute_location'] = base_address+paintings_by_artist['location']\r\n paintings_by_artist = paintings_by_artist.sort_values('class')\r\n for i in range(paintings_by_artist.shape[0]):\r\n link = paintings_by_artist.iloc[i]['absolute_location']\r\n #print(link)\r\n my_file = Path(link)\r\n #img = Image.open(link,'r')\r\n #img.show()\r\n\r\ndef select_impressionist_artists(filepath):\r\n \"\"\"\r\n We want to find out how many impressionist artists are present in the dataset\r\n to analyze data needs and availability.\r\n Required: Atleast 15 artists with 40 paintings each.\r\n :param filepath: absolute location of Impressionism folder.\r\n \"\"\"\r\n paintings = os.listdir(filepath)\r\n unique_artists = set()\r\n artist_paintings_count = {}\r\n\r\n for filename in paintings:\r\n s = filename.find('_')\r\n artist_name = filename[:s]\r\n unique_artists.add(artist_name)\r\n if artist_name in artist_paintings_count.keys():\r\n artist_paintings_count[artist_name] += 1\r\n else:\r\n artist_paintings_count[artist_name] = 1\r\n print(\"Total Unique Artists in the Impressionism style:\", len(unique_artists))\r\n print(\"Paintings by each artist:\", artist_paintings_count)\r\n\r\n more_than_40 = {k: v for k,v in artist_paintings_count.items() if v >= 40}\r\n more_than_30 = {k: v for k, v in artist_paintings_count.items() if v >= 30}\r\n# if limit == 30 :\r\n# return (more_than_30)\r\n# elif limit == 40 :\r\n# return (more_than_40)\r\n# print(more_than_30)\r\n print(\"{} artists with 40 paintings or more: {}\".format(len(more_than_40), more_than_40))\r\n print(\"{} artists with 30 paintings or more: {}\".format(len(more_than_30), more_than_30))\r\n\r\n\r\ndef create_dataset(filepath):\r\n \"\"\"\r\n We separate out the Impressionist era data and artists from that period. Our train, test & validation sets will\r\n be based on this subset only.\r\n Creates a CSV file with the image location, artist and class label (encoded for artists).\r\n :param filepath: str, the base location where Impressionist paintings are stored.\r\n \"\"\"\r\n paintings = os.listdir(filepath)\r\n frida_data = {}\r\n for filename in paintings:\r\n s = filename.find('_')\r\n artist_name = filename[:s]\r\n frida_data[filename] = artist_name\r\n\r\n frida = pd.DataFrame(list(frida_data.items()), columns=['location', 'artist'])\r\n le = LabelEncoder()\r\n labels = le.fit(frida['artist'])\r\n frida['class'] = le.transform(frida['artist'])\r\n frida.to_csv('./wikiart/impressionists.csv', sep=',', index=True, index_label='ids')\r\n\r\n\r\ndef make_author_mapping_file(filepath, train_file):\r\n paintings_by_artist = pd.read_csv(filepath + train_file, names=['ids', 'location', 'artist', 'class'], header=0)\r\n #print(paintings_by_artist)\r\n #print(paintings_by_artist['class'], paintings_by_artist['artist'])\r\n data = []\r\n data2 = []\r\n mapping = pd.DataFrame(np.array(paintings_by_artist['class']).reshape(-1,1))\r\n for i in range(paintings_by_artist.shape[0]):\r\n #mapping.add(mapping, paintings_by_artist.iloc[i]['artist'], fill_value=0)\r\n data.append(paintings_by_artist.iloc[i]['class'])\r\n data2.append(paintings_by_artist.iloc[i]['artist'])\r\n# mapping.append(mapping,data, data2)\r\n import csv\r\n with open (base_address+'author_mapping.csv','w') as csvfile:\r\n fieldnames =['class', 'artist']\r\n writer = csv.DictWriter(csvfile, fieldnames=fieldnames)\r\n writer.writeheader()\r\n for i in range(paintings_by_artist.shape[0]):\r\n writer.writerow({'class' : paintings_by_artist.iloc[i]['class'], 'artist':paintings_by_artist.iloc[i]['artist']})\r\n\r\ndef make_author_image_mapping(data, link):\r\n import csv\r\n with open(base_address+'author_image_mapping.csv', 'w') as csvfile:\r\n fieldnames = ['class', 'absolute_path']\r\n writer = csv.DictWriter(csvfile, fieldnames=fieldnames)\r\n writer.writeheader()\r\n for i in range(len(data)):\r\n writer.writerow({'class': data[i],\r\n 'absolute_path': link[i]})\r\n\r\n\r\n\r\n#def make_csv()\r\n\r\nif __name__ == '__main__':\r\n train_file = '/artist_train.csv'\r\n style = 'Impressionism'\r\n read_artist_data(base_address=base_address,filepath=train_file)\r\n select_impressionist_artists(base_address+style)\r\n create_dataset(base_address+style)","sub_path":"jjcheon/src/util_file.py","file_name":"util_file.py","file_ext":"py","file_size_in_byte":5918,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"539644302","text":"from collections import Counter\nfrom itertools import permutations\nimport re\n\n\nclass SantasList:\n def __init__(self, santa_list):\n self.__list = santa_list.split(\"\\n\")\n self.__vowels = [\"a\", \"e\", \"i\", \"o\", \"u\"]\n self.__naughty_strings = [\"ab\", \"cd\", \"pq\", \"xy\"]\n self.__nice_list = []\n self.__naughty_list = []\n\n def naught_or_nice(self):\n for word in self.__list:\n c = Counter(word)\n if any([ns in word for ns in self.__naughty_strings]):\n self.__naughty_list.append(word)\n elif (\n any([word[i] == word[i + 1] for i in range(len(word) - 1)])\n and sum(c[v] for v in [\"a\", \"e\", \"i\", \"o\", \"u\"]) >= 3\n ):\n self.__nice_list.append(word)\n else:\n self.__naughty_list.append(word)\n return self\n\n @property\n def length_nice_list(self):\n return len(self.__nice_list)\n\n\nclass SantasListTwo:\n def __init__(self, santa_list):\n self.__list = santa_list.split(\"\\n\")\n self.__nice_list = []\n self.__naughty_list = []\n\n def __check_word_first_test(self, word):\n for idx, letter in enumerate(word):\n if idx + 2 < len(word) and word[idx + 2] == letter:\n return True\n return False\n\n def __check_word_second_test(self, word):\n # Create a counter of all adjacent characters\n c = Counter([f\"{f}{s}\" for f, s in zip(word[:-1], word[1:])])\n if (\n # If the the most common pair appears more than once\n c.most_common(1)[0][1] > 1\n # There is more then one occurrence of the pair\n # for example aaa will return a list with a single tuple\n # whilst aabaa will return a list with 2 tuples\n and len(\n [\n (i.start(), i.end())\n for i in re.finditer(c.most_common(1)[0][0], word)\n ]\n )\n > 1\n ):\n return True\n else:\n False\n\n def naught_or_nice(self):\n for word in self.__list:\n\n if self.__check_word_first_test(word) and self.__check_word_second_test(\n word\n ):\n self.__nice_list.append(word)\n else:\n self.__naughty_list.append(word)\n return self\n\n @property\n def length_nice_list(self):\n return len(self.__nice_list)\n\n\nif __name__ == \"__main__\":\n with open(\"./input.txt\", \"r\") as f:\n list_to_check = f.read()\n\n santas_list = SantasList(list_to_check)\n santas_list.naught_or_nice()\n\n print(f\"Part 01:\\nSanta's nice list is {santas_list.length_nice_list} words long\\n\")\n\n santas_list_two = SantasListTwo(list_to_check)\n santas_list_two.naught_or_nice()\n\n print(\n f\"Part 02:\\nSanta's nice list second time is {santas_list_two.length_nice_list} words long\\n\"\n )\n","sub_path":"2015/day_05/nice.py","file_name":"nice.py","file_ext":"py","file_size_in_byte":2959,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"70289856","text":"from django.db import IntegrityError\nfrom django.test import TestCase\nfrom django.test import Client\nfrom django.test.utils import override_settings\nfrom django.contrib.auth import get_user_model\nfrom django.core.exceptions import ValidationError\nfrom django.contrib.auth.models import User\nfrom django.contrib.auth.models import Group\nfrom oauth2_provider.models import Application\nfrom users.models import Punctuation\nfrom core.models import Word\nimport json\n\n\n# Create your tests here.\n\nclass UsersApiTestCase(TestCase):\n\tdef setUp(self):\n\t\tGroup.objects.create(\n\t\t\tname = \"Sordo\")\n\t\tGroup.objects.create(\n\t\t\tname = \"Oyente\")\n\n\n\tdef test_create_user(self):\n\t\tc = Client()\n\t\tresponse = c.post('/api/v1.0/users/',\n\t\t\t{'first_name' : 'naty', \n\t\t\t 'username' : 'naty',\n\t\t\t 'email' : 'naty@gmail.com',\n\t\t\t 'password' : 'naty',\n\t\t\t 'group' : 'Oyente'})\n\t\tstatus = json.loads(response.content)['status']\n\t\tself.assertEqual('ok', status)\n\n\n\tdef test_cant_create_with_invalid_email(self):\n\t\tc = Client()\n\t\tresponse = c.post('/api/v1.0/users/',\n\t\t\t{'first_name' : 'mario', \n\t\t\t 'username' : 'mario',\n\t\t\t 'email' : 'mario',\n\t\t\t 'password' : 'mario',\n\t\t\t 'group' : 'Sordo'})\n\t\tstatus = json.loads(response.content)['status']\n\t\terror = json.loads(response.content)['error']\n\t\tself.assertEqual('error', status)\n\t\tself.assertEqual('Invalid email', error)\n\n\n\tdef test_cant_create_user_with_empty_field(self):\n\t\tc = Client()\n\t\tresponse = c.post('/api/v1.0/users/',\n\t\t\t{'first_name' : '', \n\t\t\t 'username' : 'mario',\n\t\t\t 'email' : 'mario@mario.com',\n\t\t\t 'password' : 'mario',\n\t\t\t 'group' : 'Sordo'})\n\t\tstatus = json.loads(response.content)['status']\n\t\terror = json.loads(response.content)['error']\n\t\tself.assertEqual('error', status)\n\t\tself.assertEqual('First name missing', error)\n\n\n\nclass PunctuationApiTestCase(TestCase):\n\tdef setUp(self):\n\t\tget_user_model().objects.create_user(\n\t\t\tusername = 'naty',\n\t\t\tpassword ='naty')\n\t\tget_user_model().objects.create_user(\n\t\t\tusername = 'mario',\n\t\t\tpassword='mario')\n\t\tWord.objects.create(\n\t\t\tname = \"word\",\n\t\t\tupload_cost = 5,\n\t\t\tdownload_cost = 5,\n\t\t\tchallenge_reward = 10,\n\t\t\tupload_reward = 20)\n\n\n\tdef test_create_punctuation(self):\n\t\tnaty = get_user_model().objects.get(username = 'naty')\n\n\t\tPunctuation.objects.create(\n\t\t\tuser = naty,\n\t\t\tcredit = 10)\n\n\t\tcredit = Punctuation.objects.get(user = naty).credit\n\t\tself.assertEqual(credit, 10)\n\n\n\tdef test_no_duplicate_creation(self):\n\t\tnaty = get_user_model().objects.get(username = 'naty')\n\n\t\tPunctuation.objects.create(\n\t\t\tuser = naty,\n\t\t\tcredit = 10)\n\t\t\n\t\tself.assertRaises(IntegrityError,\n\t\t\tPunctuation.objects.create,\n\t\t\tuser = naty,\n\t\t\tcredit = 10)\n\n\n\tdef test_update_punctuation_download(self):\n\t\tnaty = get_user_model().objects.get(username = 'naty')\n\t\tmario = get_user_model().objects.get(username = 'mario')\n\t\tword = Word.objects.get(name = 'word')\n\n\t\tpunctuation_n = Punctuation.objects.create(\n\t\t\tuser = naty,\n\t\t\tcredit = 3)\n\n\t\tpunctuation_m = Punctuation.objects.create(\n\t\t\tuser = mario,\n\t\t\tcredit = 10)\n\n\t\tresponse_n = punctuation_n.update(word, \"download\")\n\t\tself.assertEqual(False, response_n)\n\t\tcredit_n = Punctuation.objects.get(user = naty).credit\n\t\tself.assertEqual(credit_n, 3)\n\n\t\tresponse_m = punctuation_m.update(word, \"download\")\n\t\tself.assertEqual(True, response_m)\n\t\tcredit_m = Punctuation.objects.get(user = mario).credit\n\t\tself.assertEqual(credit_m, 5)\n\n\n\tdef test_update_punctuation_upload(self):\n\t\tnaty = get_user_model().objects.get(username = 'naty')\n\t\tmario = get_user_model().objects.get(username = 'mario')\n\t\tword = Word.objects.get(name = 'word')\n\n\t\tpunctuation_n = Punctuation.objects.create(\n\t\t\tuser = naty,\n\t\t\tcredit = 3)\n\n\t\tpunctuation_m = Punctuation.objects.create(\n\t\t\tuser = mario,\n\t\t\tcredit = 10)\n\n\t\tresponse_n = punctuation_n.update(word, \"upload\")\n\t\tself.assertEqual(False, response_n)\n\t\tcredit_n = Punctuation.objects.get(user = naty).credit\n\t\tself.assertEqual(credit_n, 3)\n\n\t\tresponse_m = punctuation_m.update(word, \"upload\")\n\t\tself.assertEqual(True, response_m)\n\t\tcredit_m = Punctuation.objects.get(user = mario).credit\n\t\tself.assertEqual(credit_m, 5)\n\n\n\tdef test_update_punctuation_challenge_success(self):\n\t\tnaty = get_user_model().objects.get(username = 'naty')\n\t\tword = Word.objects.get(name = 'word')\n\n\t\tpunctuation = Punctuation.objects.create(\n\t\t\tuser = naty,\n\t\t\tcredit = 3)\n\n\t\tresponse = punctuation.update(word, \"challenge_success\")\n\t\tself.assertEqual(True, response)\n\t\tcredit = Punctuation.objects.get(user = naty).credit\n\t\tself.assertEqual(credit, 13)\n\n\n\tdef test_update_punctuation_upload_success(self):\n\t\tnaty = get_user_model().objects.get(username = 'naty')\n\t\tword = Word.objects.get(name = 'word')\n\n\t\tpunctuation = Punctuation.objects.create(\n\t\t\tuser = naty,\n\t\t\tcredit = 3)\n\n\t\tresponse = punctuation.update(word, \"upload_success\")\n\t\tself.assertEqual(True, response)\n\t\tcredit = Punctuation.objects.get(user = naty).credit\n\t\tself.assertEqual(credit, 23)\n\n\n\n# class PunctuationsApiTestCase(TestCase):\n# \tdef setUp(self):\n# \t\tget_user_model().objects.create_user(username = \"naty\", password=\"naty\")\n# \t\tget_user_model().objects.create_user(username = \"mario\", password=\"mario\")\n# \t\tCriterion.objects.create(\n# \t\t\tname = \"criterion1\",\n# \t\t\tdescription = \"si\",\n# \t\t\tupload_cost = 10,\n# \t\t\tdownload_cost = 20,\n# \t\t\tchallenge_reward = 30)\n# \t\tCriterion.objects.create(\n# \t\t\tname = \"criterion2\",\n# \t\t\tdescription = \"si\",\n# \t\t\tupload_cost = 10,\n# \t\t\tdownload_cost = 20,\n# \t\t\tchallenge_reward = 30)\n# \t\tnaty = get_user_model().objects.get(username=\"naty\")\n# \t\tcriterion1 = Criterion.objects.get(name=\"criterion1\")\n\n# \t\tPunctuation.objects.create(\n# \t\t\tuser = naty,\n# \t\t\tcriterion = criterion1,\n# \t\t\tscore=10,\n# \t\t\tcredit=10,\n# \t\t\tfailure_rate=10)\n\n# \t\tapplication = Application.objects.create(\n# \t\t\tclient_id = \"asdf1234\",\n# \t\t\tclient_secret = \"qwerty1234\",\n# \t\t\tuser_id = 1,\n# \t\t\tauthorization_grant_type = \"password\",\n# \t\t\tclient_type = \"secret\")\n\n\n# \tdef get_token(self):\n# \t\tc = Client()\n# \t\tresponse = c.post('/o/token/',\n# \t\t\t{'client_id' : 'asdf1234',\n# \t\t\t 'client_secret' : 'qwerty1234',\n# \t\t\t 'grant_type' : 'password',\n# \t\t\t 'username' : 'naty',\n# \t\t\t 'password' : 'naty'})\n# \t\tparsed_response = json.loads(response.content)\n# \t\ttoken = parsed_response['access_token']\t\t\n# \t\treturn token\n\n\n# \tdef test_get_punctuation_created_registry(self):\n# \t\tc = Client()\n# \t\ttoken = self.get_token()\n# \t\tauth_header = {\n# \t\t\t'HTTP_AUTHORIZATION' : 'Bearer ' + token,\n# \t\t}\t\t\n# \t\tresponse = c.get('/api/v1.0/users/punctuation/',\n# \t\t\t{'username' : 'naty', 'criterion' : 'criterion1'},\n# \t\t\t**auth_header)\n\t\t\n# \t\tparsed_response = json.loads(response.content)\n# \t\tself.assertEqual('ok',parsed_response['status'])\n# \t\tself.assertEqual(10,parsed_response['data']['score'])\n\n\n# \tdef test_get_punctuation_new_registry(self):\n# \t\tCriterion.objects.create(\n# \t\t\tname = \"criterio 3\",\n# \t\t\tdescription = \"si\",\n# \t\t\tupload_cost = 10,\n# \t\t\tdownload_cost = 20,\n# \t\t\tchallenge_reward = 30)\n# \t\tc = Client()\n# \t\ttoken = self.get_token()\n# \t\tauth_header = {\n# \t\t\t'HTTP_AUTHORIZATION' : 'Bearer ' + token,\n# \t\t}\t\t\n# \t\tresponse = c.get('/api/v1.0/users/punctuation/',\n# \t\t\t{'username' : 'naty', 'criterion' : 'criterio 3'},\n# \t\t\t**auth_header)\n\t\t\n# \t\tparsed_response = json.loads(response.content)\n# \t\tself.assertEqual('ok',parsed_response['status'])\n# \t\tself.assertEqual(0,parsed_response['data']['score'])\n\n\n# \tdef test_get_punctuation_wrong_request(self):\n# \t\t\"el usuario o el criterion no existen\"\n# \t\tc = Client()\n# \t\ttoken = self.get_token()\n# \t\tauth_header = {\n# \t\t\t'HTTP_AUTHORIZATION' : 'Bearer ' + token,\n# \t\t}\t\t\n# \t\tresponse = c.get('/api/v1.0/users/punctuation/',\n# \t\t\t{'criterion' : 'no existo'},\n# \t\t\t**auth_header)\n# \t\tresponse2 = c.get('/api/v1.0/users/punctuation/',\n# \t\t\t{},\n# \t\t\t**auth_header)\n\n# \t\tparsed_response = json.loads(response.content)\n# \t\tparsed_response2 = json.loads(response2.content)\n\t\t\n# \t\tself.assertEqual('Criterion does not exists',parsed_response['error'])\n# \t\tself.assertEqual('Missing parameters, include criterion',parsed_response2['error']\n","sub_path":"users/tests.py","file_name":"tests.py","file_ext":"py","file_size_in_byte":7997,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"187203443","text":"#! /usr/bin/env python3\n\nimport os\nimport sys\nimport flask\nimport math\nimport json\nfrom flask import Flask, Response, request, g\nfrom torndb import Connection\nfrom flask.ext.restful import inputs\n\nfrom tsp_greedy import solve_tsp\nimport db_config, data_config\n\napp = Flask(__name__)\n\n# Global state of the server, this is not thread safe\n#smart_data = 'real' # 'fake_rainy', 'fake_sunny'\n#smart_data = 'fake_rainy' # 'fake_rainy', 'fake_sunny'\nsmart_data = 'fake_sunny' # 'fake_rainy', 'fake_sunny'\nverbose = True\n\n# Local functions\n#-------------------------------------------------------------------------------\ndef help_usage():\n return \"\"\"\\\nGET /api_user/route?username=john&date=YYYY-mm-dd&time={all_day, morning, afternoon}&city=Barcelona\nGET /api_admin/smart_data\nPUT /api_admin/smart_data?source={real, fake_rainy, fake_sunny}\nGET /api_admin/verbose\nPUT /api_admin/verbose?val={true, false}\n\"\"\"\n\ndef resp_plain(resp):\n return Response(resp, mimetype='text/plain; charset=utf-8')\n\ndef resp_json(resp, status):\n js = json.dumps(resp, ensure_ascii=False)\n return Response(js, status=status, mimetype='application/json; charset=utf-8')\n\ndef get_city_points(city):\n points = g.db.query(\"select * from points where city=%s\", city)\n return points\n\ndef get_user_params(username):\n user_params = g.db.query(\"select * from users where username=%s\", username)\n if user_params != []:\n user_params = user_params[0]\n return user_params\n\ndef norm_param(param, val, min_max):\n if val == None:\n return 0\n min = min_max[0]\n max = min_max[1]\n v = (val - data_config.min[param]) / (data_config.max[param] - data_config.min[param])\n return v * (max - min) + min\n\ndef req_sensor(coord, sens, radius):\n global smart_data\n if smart_data == 'fake_rainy':\n if sens == 'wind':\n return 50.0\n if sens == 'temp':\n return 20.0\n if sens == 'humidity':\n return 0.86\n if sens == 'pluviometer':\n return 12\n if sens == 'noise':\n return None\n if smart_data == 'fake_sunny':\n if sens == 'wind':\n return 6.0\n if sens == 'temp':\n return 27.0\n if sens == 'humidity':\n return 0.7\n if sens == 'pluviometer':\n return 0\n if sens == 'noise':\n return None\n if smart_data == 'real':\n pass\n\ndef req_forecast(coord, sens):\n if smart_data == 'fake_rainy':\n if sens == 'wind':\n return 54.0\n if sens == 'temp':\n return 18.5\n if sens == 'humidity':\n return 0.85\n if sens == 'p_rain':\n return 0.9\n if smart_data == 'fake_sunny':\n if sens == 'wind':\n return 7.0\n if sens == 'temp':\n return 26.0\n if sens == 'humidity':\n return 0.71\n if sens == 'p_rain':\n return 0.0\n if smart_data == 'real':\n pass\n\ndef rank_point(point, user, sensor, forecast):\n # Merge sensor and forecast data\n weather = { 'wind': 0, 'temp': 0, 'humidity': 0 }\n for p in weather:\n weather[p] =\\\n 0.3 * norm_param(p, sensor[p], (-1, 1)) +\\\n 0.7 * norm_param(p, forecast[p], (-1, 1))\n weather['rain'] =\\\n 0.3 * norm_param('pluviometer', sensor['pluviometer'], (-1, 1)) +\\\n 0.7 * norm_param('p_rain', forecast['p_rain'], (-1, 1))\n\n\n #if verbose:\n # print(weather)\n # print()\n\n # Merge user and sensor/weather data into semantic categories\n rank = {}\n rank['outdoor'] = -50 * weather['wind'] + 40 * weather['temp'] -\\\n 25 * weather['humidity'] - 200 * weather['rain'] + 10 * user['outdoor']\n rank['free'] = 10 * user['free']\n rank['crowded'] = 5 * norm_param('noise', sensor['noise'], (-1, 1)) +\\\n 10 * user['crowded']\n rank['traditional'] = 10 * user['traditional']\n\n # Normalization\n rank['outdoor'] /= 55\n rank['free'] /= 10\n rank['crowded'] /= 15\n rank['traditional'] /= 10\n\n # Cross data with point parameters\n for c in rank:\n rank[c] *= point[c]\n\n # Add point rating\n rank['rating'] = 5 * point['rating']\n\n # Compute final ranking\n r = 0\n for c in rank:\n r += rank[c]\n\n return r\n\ndef dist(n1, n2):\n return math.sqrt((n1[0] - n2[0])**2 + (n1[1] - n2[1])**2)\n\ndef gen_mat(ns):\n m = []\n for i in range(len(ns)):\n m.append([])\n for j in range(len(ns)):\n m[i].append(dist(ns[i], ns[j]))\n return m\n\ndef route(coords):\n m = gen_mat(coords)\n p = solve_tsp(m)\n return p\n\n# sensors is a pair of sensor names and tolerance radius\n# coord is a pair of longitude and latitude\ndef req_sensor_data(coord, sensors):\n res = {}\n for (sens, radius) in sensors:\n res[sens] = req_sensor(coord, sens, radius)\n\n return res\n\n# params is the names of values we want to get\n# coord is a pair of longitude and latitude\ndef req_forecast_data(coord, params):\n res = {}\n for param in params:\n res[param] = req_forecast(coord, param)\n\n return res\n\n# Database connection\n#-------------------------------------------------------------------------------\n@app.before_request\ndef connect_db():\n g.db = Connection(db_config.DB_HOST,\n db_config.DB_NAME,\n db_config.DB_USER,\n db_config.DB_PASSWD)\n\n@app.after_request\ndef close_connection(response):\n g.db.close()\n return response\n\n@app.route('/')\ndef index():\n return resp_plain(help_usage())\n\n# API routes\n#-------------------------------------------------------------------------------\n@app.route('/api_admin/smart_data', methods = ['PUT', 'GET'])\ndef api_admin_smart_data():\n global smart_data\n if request.method == 'PUT' or 'source' in request.args:\n val = request.args['source']\n if val == 'real':\n smart_data = 'real'\n elif val == 'fake_rainy':\n smart_data = 'fake_rainy'\n elif val == 'fake_sunny':\n smart_data = 'fake_sunny'\n return resp_plain(\"OK\\n\")\n\n elif request.method == 'GET':\n resp = \"Smart data source: \" + smart_data + \"\\n\"\n return resp_plain(resp)\n\n@app.route('/api_admin/verbose', methods = ['PUT', 'GET'])\ndef api_verbose_data():\n global verbose\n if request.method == 'PUT':\n val = request.args['val']\n if val == 'true':\n verbose = True\n elif val == 'false':\n verbose = False\n return resp_plain(\"OK\\n\")\n\n elif request.method == 'GET':\n resp = \"Verbose: \" + str(verbose) + \"\\n\"\n return resp_plain(resp)\n\n@app.route('/api_user/route')\ndef api_user_route():\n # Parsing input arguments\n username = request.args['username']\n date = request.args['date']\n time = request.args['time']\n city = request.args['city']\n\n date = flask.ext.restful.inputs.date(date)\n\n # Sensor names and radius acceptance\n sens_conf = [('wind', 1000), ('temp', 1000), ('humidity', 1000),\n ('pluviometer', 1000), ('noise', 200)]\n fore_param = ['wind', 'temp', 'humidity', 'p_rain']\n\n user_params = get_user_params(username)\n if user_params == []:\n return resp_json({'status': 'error', 'error': \"No such username\"}, 400)\n city_points = get_city_points(city)\n if city_points == []:\n return resp_json({'status': 'error', 'error': \"No such city\"}, 400)\n\n for point in city_points:\n coord = (point['longitude'], point['latitude'])\n sensors = req_sensor_data(coord, sens_conf)\n forecast = req_forecast_data(coord, fore_param)\n point['rank'] = rank_point(point, user_params, sensors, forecast)\n\n num_points = 5\n if time == 'all_day':\n num_points = 10\n\n points = []\n coords = []\n res_str = \"\"\n for point in sorted(city_points, key=lambda k: k['rank'], reverse=True):\n points.append(point)\n coords.append((float(point['longitude']), float(point['latitude'])))\n res_str += str(point) + \"\\n\"\n if len(points) >= num_points:\n break\n\n order = route(coords)\n for i in order:\n points[i]['num'] = i\n\n #return 'NOT YET IMPLEMENTED'\n if verbose:\n print(res_str)\n\n return resp_json({'status': 'ok', 'points': points}, 200)\n #return resp_plain(res)\n\n@app.route('/db_test')\ndef db_test():\n points = g.db.query(\"select * from points where city=%s\", \"barcelona\")\n return resp_plain(str(points[1:]))\n\n#-------------------------------------------------------------------------------\nport = os.getenv('VCAP_APP_PORT', '5000')\nif __name__ == \"__main__\":\n app.debug = True\n app.run(host='0.0.0.0', port=int(port))\n","sub_path":"hello.py","file_name":"hello.py","file_ext":"py","file_size_in_byte":8697,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"287251864","text":"import collections\nN = int(input())\nY = list(input())\nX = []\nans = 0\nfor n in range(N):\n X.append(Y.pop(0))\n X_and_Y = set(X) & set(Y)\n ans = max(ans,len(X_and_Y))\nprint(ans)\n","sub_path":"ABC/ABC_098/abc098b.py","file_name":"abc098b.py","file_ext":"py","file_size_in_byte":184,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"441561722","text":"#!/usr/bin/env python3\n#coding: utf-8\n\nimport sys\n\nfrom PyQt5 import QtWidgets, QtGui, QtChart, QtCore\nimport datetime\n\nfrom classes import table_widget\nfrom libs import ui_utils\nfrom libs import examination_util\nfrom libs import string_utils\nfrom libs import personnel_utils\nfrom libs import case_utils\nfrom libs import system_utils\nfrom libs import date_utils\nfrom libs import number_utils\n\n\n# 病歷檢驗資料 2019.08/14\nclass MedicalRecordExamination(QtWidgets.QMainWindow):\n # 初始化\n def __init__(self, parent=None, *args):\n super(MedicalRecordExamination, self).__init__(parent)\n self.parent = parent\n self.database = args[0]\n self.system_settings = args[1]\n self.patient_key = args[2]\n self.call_from = args[3]\n\n self.ui = None\n\n self._set_ui()\n self._set_signal()\n\n self.user_name = self.system_settings.field('使用者')\n self._set_permission()\n\n # 解構\n def __del__(self):\n self.close_all()\n\n # 關閉\n def close_all(self):\n pass\n\n # 設定GUI\n def _set_ui(self):\n self.ui = ui_utils.load_ui_file(ui_utils.UI_MEDICAL_RECORD_EXAMINATION, self)\n system_utils.set_css(self, self.system_settings)\n system_utils.center_window(self)\n self.table_widget_examination_item = table_widget.TableWidget(\n self.ui.tableWidget_examination_item, self.database\n )\n self.table_widget_test_result = table_widget.TableWidget(\n self.ui.tableWidget_test_result, self.database\n )\n self.table_widget_test_result.set_column_hidden([0])\n self._set_table_width()\n self._set_examination_groups()\n\n # 設定信號\n def _set_signal(self):\n self.ui.tableWidget_groups.itemSelectionChanged.connect(self._groups_changed)\n self.ui.tableWidget_examination_item.itemSelectionChanged.connect(self._examination_item_changed)\n self.ui.toolButton_add_examination.clicked.connect(self._add_examination)\n self.ui.tableWidget_test_result.doubleClicked.connect(self._open_examination)\n self.ui.toolButton_open_examination_item.clicked.connect(self._open_examination)\n\n def _set_permission(self):\n if self.call_from == '醫師看診作業':\n return\n\n if self.user_name == '超級使用者':\n return\n\n if personnel_utils.get_permission(self.database, '病歷資料', '病歷修正', self.user_name) == 'Y':\n return\n\n self.ui.toolButton_add_examination.setEnabled(False)\n\n def _set_table_width(self):\n width = [152, 152]\n self.table_widget_examination_item.set_table_heading_width(width)\n\n width = [100, 150, 150]\n self.table_widget_test_result.set_table_heading_width(width)\n\n def _set_examination_groups(self):\n examination_groups = []\n for row in examination_util.EXAMINATION_LIST:\n groups = row[0]\n if groups not in examination_groups:\n examination_groups.append(groups)\n\n row_count = len(examination_groups)\n self.ui.tableWidget_groups.setRowCount(0)\n\n column_count = self.ui.tableWidget_groups.columnCount()\n total_row = int(row_count / column_count)\n if row_count % column_count > 0:\n total_row += 1\n\n for row_no in range(0, total_row):\n self.ui.tableWidget_groups.setRowCount(\n self.ui.tableWidget_groups.rowCount() + 1\n )\n for col_no in range(0, column_count):\n index = (row_no * column_count) + col_no\n if index >= row_count:\n break\n\n self.ui.tableWidget_groups.setItem(\n row_no, col_no, QtWidgets.QTableWidgetItem(examination_groups[index])\n )\n\n self.ui.tableWidget_groups.resizeRowsToContents()\n self.ui.tableWidget_groups.setCurrentCell(0, 0)\n groups = self.ui.tableWidget_groups.selectedItems()[0].text()\n self._set_examination_items(groups)\n\n def _groups_changed(self):\n if not self.ui.tableWidget_groups.selectedItems():\n return\n\n groups = self.ui.tableWidget_groups.selectedItems()[0].text()\n self._set_examination_items(groups)\n\n def _set_examination_items(self, groups):\n examination_item_list = []\n for row in examination_util.EXAMINATION_LIST:\n if row[0] == groups:\n examination_item_list.append([row[1], row[2]])\n\n row_count = len(examination_item_list)\n self.ui.tableWidget_examination_item.setRowCount(row_count)\n for row_no, row in zip(range(len(examination_item_list)), examination_item_list):\n for col_no in range(len(row)):\n self.ui.tableWidget_examination_item.setItem(\n row_no, col_no,\n QtWidgets.QTableWidgetItem(row[col_no])\n )\n\n self.ui.tableWidget_examination_item.resizeRowsToContents()\n self.ui.tableWidget_examination_item.setCurrentCell(0, 0)\n self.ui.tableWidget_examination_item.setFocus(True)\n self._examination_item_changed()\n\n def _examination_item_changed(self):\n current_row = self.ui.tableWidget_examination_item.currentRow()\n item_name = self.ui.tableWidget_examination_item.item(current_row, 1)\n if item_name is None:\n return\n\n item_name = item_name.text()\n self._read_examination_item(item_name)\n\n def _read_examination_item(self, item_name):\n self.ui.toolButton_open_examination_item.setEnabled(True)\n if self.patient_key is None:\n self.ui.toolButton_open_examination_item.setEnabled(False)\n return\n\n sql = '''\n SELECT * FROM examination_item\n WHERE\n PatientKey = {patient_key} AND\n ExaminationItem = \"{examination_item}\"\n ORDER BY ExaminationDate\n '''.format(\n patient_key=self.patient_key,\n examination_item=item_name,\n )\n self.table_widget_test_result.set_db_data(sql, self._set_table_data)\n if self.table_widget_test_result.row_count() <= 0:\n self.ui.toolButton_open_examination_item.setEnabled(False)\n\n self._plot_chart()\n\n def _set_table_data(self, row_no, row):\n examination_item_row = [\n string_utils.xstr(row['ExaminationKey']),\n string_utils.xstr(row['ExaminationDate']),\n string_utils.xstr(row['TestResult']),\n ]\n\n for col_no in range(len(examination_item_row)):\n self.ui.tableWidget_test_result.setItem(\n row_no, col_no,\n QtWidgets.QTableWidgetItem(examination_item_row[col_no])\n )\n\n def _plot_chart(self):\n while self.ui.verticalLayout_chart.count():\n item = self.ui.verticalLayout_chart.takeAt(0)\n widget = item.widget()\n if widget is not None:\n widget.deleteLater()\n\n self._plot_test_result()\n\n def _plot_test_result(self):\n series = QtChart.QLineSeries()\n\n for row_no in range(self.ui.tableWidget_test_result.rowCount()):\n item = self.ui.tableWidget_test_result.item(row_no, 1)\n if item is None:\n continue\n\n test_result = item.text()\n try:\n series.append(row_no, number_utils.get_float(test_result))\n except:\n pass\n\n chart = QtChart.QChart()\n chart.legend().hide()\n chart.addSeries(series)\n chart.createDefaultAxes()\n chart.setTitle('檢驗結果')\n chart.setAnimationOptions(QtChart.QChart.SeriesAnimations)\n\n # axis_y = QtChart.QValueAxis()\n # chart.addAxis(axis_y, QtCore.Qt.AlignLeft)\n # series.attachAxis(axis_y)\n # axis_y.setRange(0, 200)\n #\n # axis_y = QtChart.QCategoryAxis()\n # axis_y.append('過低', 90)\n # axis_y.append('正常', 180)\n # axis_y.setLinePenColor(series.pen().color())\n # axis_y.setGridLinePen((series.pen()))\n # chart.addAxis(axis_y, QtCore.Qt.AlignRight)\n # series.attachAxis(axis_y)\n\n self.chartView = QtChart.QChartView(chart)\n self.chartView.setRenderHint(QtGui.QPainter.Antialiasing)\n\n self.chartView.setFixedWidth(1000)\n self.ui.verticalLayout_chart.addWidget(self.chartView)\n\n def _open_examination(self):\n examination_key = self.table_widget_test_result.field_value(0)\n self.parent.parent._add_tab(\n '檢驗報告登錄', self.database, self.system_settings,\n examination_key, None, None\n )\n\n def _add_examination(self):\n case_date = self.parent.medical_record['CaseDate']\n examination_key = self._get_examination_key(self.patient_key, case_date)\n\n self.parent.parent._add_tab(\n '檢驗報告登錄', self.database, self.system_settings,\n examination_key, self.patient_key, case_date\n )\n\n def _get_examination_key(self, patient_key, case_date):\n examination_key = None\n\n sql = '''\n SELECT ExaminationKey FROM examination\n WHERE\n PatientKey = {patient_key} AND\n ExaminationDate = \"{case_date}\"\n '''.format(\n patient_key=patient_key,\n case_date=case_date.date(),\n )\n rows = self.database.select_record(sql)\n if len(rows) > 0:\n examination_key = rows[0]['ExaminationKey']\n\n return examination_key\n","sub_path":"medical_record_examination.py","file_name":"medical_record_examination.py","file_ext":"py","file_size_in_byte":9604,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"183871116","text":"# -*- coding:UTF-8 -*-\nimport requests\nfrom bs4 import BeautifulSoup\nimport os\n\n# if __name__ == '__main__':\n# target = 'http://www.biqukan.com/1_1094/5403177.html'\n# req = requests.get(url=target)\n# req.encoding = \"gbk\"\n# aaa = req.text\n# bf = BeautifulSoup(aaa)\n# texts = bf.find_all('div',class_ = 'showtxt')\n# print(texts[0].text.replace('\\xa0'*8,'\\n\\n'))\n\n# if __name__ == '__main__':\n# \ttarget = 'http://www.biqukan.com/1_1094/'\n# \tserver = 'http://www.biqukan.com/'\n# \treq = requests.get(url = target)\n# \treq.encoding = 'gbk'\n# \thtml = req.text\n# \tdiv_bf = BeautifulSoup(html)\n# \tdiv = div_bf.find_all('div', class_ = 'listmain')\n# \ta_bf = BeautifulSoup(str(div[0]))\n# \ta = a_bf.find_all('a')\n# \t# print(a)\n# \tfor each in a:\n# \t\tprint(each.string, server + each.get('href'))\n\ndef load_url(chapter_name, url):\n\treq = requests.get(url)\n\treq.encoding = 'gbk'\n\thtml = req.text\n\tbf = BeautifulSoup(html)\n\ttexts = bf.find_all('div', class_ = 'showtxt')\n\ttext = texts[0].text.replace('\\xa0'*8, '\\n\\n')\n\twrite_txt(chapter_name, text)\n\tprint('write {:s} done! \\n'.format(chapter_name))\n\ndef write_txt(chapter_name, text):\n\tchapter_name = chapter_name + '.txt'\n\twith open(os.path.join(save_path,chapter_name), 'w') as f:\n\t\tf.write(text)\n\n\n\nif __name__ == '__main__':\n\tsave_path = r'./book'\n\tif not os.path.isdir(save_path):\n\t\tos.mkdir(save_path)\n\tserver = 'http://www.biqukan.com/'\n\ttarget = 'http://www.biqukan.com/1_1094/'\n\treq = requests.get(url = target)\n\treq.encoding = 'gbk'\n\thtml = req.text\n\tdiv_bf = BeautifulSoup(html)\n\tdiv = div_bf.find_all('div', class_ = 'listmain')\n\ta_bf = BeautifulSoup(str(div[0]))\n\ta = a_bf.find_all('a')\n\tfor each in a:\n\t\tload_path = server + each.get('href')\n\t\tchapter_name = each.string\n\t\tload_url(chapter_name, load_path)\n\n","sub_path":"spider/load_txt.py","file_name":"load_txt.py","file_ext":"py","file_size_in_byte":1785,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"452508648","text":"import numpy as np\nimport maxflow\nfrom skimage import io\nfrom skimage import data\nfrom skimage import color\nfrom skimage import util\nfrom skimage import filters\nfrom skimage import feature\nfrom skimage import morphology\nfrom skimage import transform\nimport skimage\nfrom pathlib import Path\nfrom scipy import ndimage\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport networkx as nx\n\ndef plot_graph_2d(graph, nodes_shape, plot_weights=True, plot_terminals=True, font_size=7):\n X, Y = np.mgrid[:nodes_shape[0], :nodes_shape[1]]\n aux = np.array([Y.ravel(), X[::-1].ravel()]).T\n positions = {i: v for i, v in enumerate(aux)}\n positions['s'] = (-1, nodes_shape[0] / 2.0 - 0.5)\n positions['t'] = (nodes_shape[1], nodes_shape[0] / 2.0 - 0.5)\n\n nxgraph = graph.get_nx_graph()\n if not plot_terminals:\n nxgraph.remove_nodes_from(['s', 't'])\n\n plt.clf()\n nx.draw(nxgraph, pos=positions)\n\n if plot_weights:\n edge_labels = {}\n for u, v, d in nxgraph.edges(data=True):\n edge_labels[(u,v)] = d['weight']\n nx.draw_networkx_edge_labels(nxgraph,\n pos=positions,\n edge_labels=edge_labels,\n label_pos=0.3,\n font_size=font_size)\n\n plt.axis('equal')\n plt.show()\n\ndef gen_edge_map(img):\n gamma = 10\n\n ver_h = np.array([[0, 0,0],\n [0,-1,0],\n [0, 1,0]])\n ver_edge_map = ndimage.convolve(img, ver_h).astype(np.float32)\n\n hor_h = np.array([[0, 0,0],\n [0,-1,1],\n [0, 0,0]])\n hor_edge_map = ndimage.convolve(img, hor_h).astype(np.float32)\n\n diag_h = np.array([[1, 0,0],\n [0,-1,0],\n [0, 0,0]])\n dia_edge_map = ndimage.convolve(img, diag_h).astype(np.float32)\n\n print(f'{ver_edge_map.min()} ---- {ver_edge_map.max()}')\n\n ver_edge_map = np.power(ver_edge_map, 2)\n hor_edge_map = np.power(hor_edge_map, 2)\n dia_edge_map = np.power(dia_edge_map, 2)\n\n print(f'{ver_edge_map.min()} bbbb {ver_edge_map.max()}')\n\n ver_edge_map = np.exp(-(ver_edge_map)/(2*gamma*gamma))\n hor_edge_map = np.exp(-(hor_edge_map)/(2*gamma*gamma))\n dia_edge_map = 1/np.sqrt(2) * np.exp(-(dia_edge_map)/(2*gamma*gamma))\n\n print(f'{ver_edge_map.min()} aaaaa {ver_edge_map.max()}')\n\ndef base_name(name): return name.split('.')[0]\n\nDIR_ROOT = 'D:\\Projects\\Oh\\data\\images\\\\trainim_LL_0428\\\\'\nDIR_IMG = f'{DIR_ROOT}trainim_LL_0428\\\\'\nDIR_ALPH_MATTE = f'{DIR_ROOT}alpha_matte\\\\'\nDIR_OUT = 'D:\\Projects\\Oh\\data\\images\\silhouette\\\\result_mate_post_processing\\\\graph_cut\\\\'\nCUR_FILE_NAME = ''\n\nfor file in Path(DIR_IMG).glob('*.*'):\n file = 'D:\\Courses\\Image Processing\\data\\MPEG7_CE-Shape-1_Part_B\\\\apple-5.gif'\n CUR_FILE_NAME = Path(file).name\n\n # if CUR_FILE_NAME not in 'image152_GapT_MWhite_LL_0417.jpg':\n # continue\n print(CUR_FILE_NAME)\n img = io.imread(file)\n matte = skimage.img_as_float(io.imread(file))\n #matte = skimage.img_as_float(io.imread(f'{DIR_ALPH_MATTE}{CUR_FILE_NAME}'))\n #matte = data.checkerboard()\n img = transform.resize(img, matte.shape)\n w, h = matte.shape[:2]\n\n g = maxflow.Graph[int]()\n nodeids = g.add_grid_nodes(matte.shape)\n\n #matte = filters.median(matte, morphology.disk(10))\n matte = skimage.img_as_float(matte)\n edge_map = feature.canny(matte)\n edge_map = morphology.binary_dilation(edge_map, morphology.square(3))\n edge_map = (1-edge_map)\n #edge_map = (filters.gaussian(edge_map,sigma=1)) > 0\n edge_map = (50*edge_map).astype(np.uint32)\n #edge_map = np.exp(edge_map)\n\n fg_map = np.zeros_like(edge_map)\n bg_map = np.zeros_like(edge_map)\n\n fg_map = matte\n fg_map = morphology.binary_erosion(matte, morphology.square(10))\n fg_map = filters.gaussian(fg_map, sigma=5)\n\n bg_map = 1 - matte\n bg_map = morphology.binary_erosion(bg_map, morphology.square(10))\n bg_map = filters.gaussian(bg_map, sigma=5)\n\n #plt.imshow(fg_map), plt.imshow(bg_map, alpha=0.4), plt.show()\n\n fg_map = np.clip(fg_map, 0.000000000001, 0.99999999999999)\n fg_map = -np.log(fg_map)\n\n bg_map = np.clip(bg_map, 0.000000000001, 0.99999999999999)\n bg_map = -np.log(bg_map)\n\n # fg_map = fg_map / (fg_map + bg_map)\n # bg_map = bg_map / (fg_map + bg_map)\n\n #plt.subplot(121);plt.imshow(img), plt.imshow(fg_map, cmap='cool', alpha=0.4), plt.imshow(bg_map, cmap='Wistia', alpha=0.4)\n #plt.subplot(122);plt.imshow(bg_map)\n #plt.show()\n\n\n print(f'fg min max {fg_map.min()}---{fg_map.max()}')\n print(f'bg min max {bg_map.min()}---{bg_map.max()}')\n\n structure = np.array([[0, 1, 0],\n [1, 0, 1],\n [0, 1, 0]])\n g.add_grid_edges(nodeids, weights=edge_map, structure=structure, symmetric=True)\n g.add_grid_tedges(nodeids, fg_map, bg_map)\n\n g.maxflow()\n sgm = g.get_grid_segments(nodeids)\n cut_mask = np.int_(sgm)\n plt.subplot(231), plt.imshow(img), plt.title('input image')\n plt.subplot(232), plt.imshow(matte, cmap='gray'), plt.title('alpha matte')\n plt.subplot(233),plt.imshow(edge_map, cmap='gray'), plt.title('edge map')\n plt.subplot(234),plt.imshow(fg_map, cmap='gray'), plt.title('-ln(alpha_matte)')\n plt.subplot(235),plt.imshow(bg_map, cmap='gray'), plt.title('-ln(1-alpha_matte)')\n plt.subplot(236),plt.imshow(cut_mask, cmap='gray'), plt.title('graph cut result')\n plt.show()\n #plt.savefig(f'{DIR_OUT}{base_name(CUR_FILE_NAME)}.png', dpi = 1000)","sub_path":"src/test_maxflow.py","file_name":"test_maxflow.py","file_ext":"py","file_size_in_byte":5597,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"619622819","text":"\nfrom keras.utils import np_utils\nfrom keras.models import Sequential, Model \nfrom keras.layers import Input, Dense , LSTM, Conv2D, Flatten, MaxPool2D, Dropout, BatchNormalization\nfrom keras.callbacks import EarlyStopping, ModelCheckpoint, TensorBoard\n\nfrom sklearn import datasets\nfrom sklearn.decomposition import PCA\nfrom sklearn.preprocessing import StandardScaler\n\nimport matplotlib.pyplot as plt \nimport numpy as np\n\nbreast_cancer = datasets.load_breast_cancer()\n\n\nx = breast_cancer.data\ny = breast_cancer.target\n\nprint(x.shape) #(569, 30) # 소수점의 향연 \nprint(y.shape) #(569,) # 1과 0의 향연\n\n\nx = x.reshape(569,1,5,6)\n\n\nfrom sklearn.model_selection import train_test_split\nx_train,x_test, y_train, y_test = train_test_split(\n \n x, y, shuffle = True , train_size = 0.8 \n)\n\n\n\n# 모델 \n\nmodel = Sequential()\nmodel.add(Conv2D(12,(1,1), activation='relu', input_shape = (1,5,6)))\nmodel.add(Dropout(0.2))\n\nmodel.add(Conv2D(12,(1,1), activation = 'relu'))\nmodel.add(Dropout(0.2))\n\nmodel.add(Dense(64, activation= 'relu'))\nmodel.add(Dropout(0.2))\n\nmodel.add(Dense(64, activation= 'sigmoid'))\nmodel.add(Dropout(0.2))\n\nmodel.add(Dense(32, activation= 'sigmoid'))\nmodel.add(Dense(10, activation= 'sigmoid'))\n\nmodel.add(Flatten())\n\n\nmodel.add(Dense(10, activation= 'sigmoid'))\n\nmodel.add(Dense(1, activation= 'sigmoid'))\n\n\n\n\n# 3. 컴파일, 훈련\n\nfrom keras.callbacks import EarlyStopping \nearly_stopping = EarlyStopping( monitor='loss', patience= 30, mode ='auto')\n\nmodel.compile(loss = 'binary_crossentropy', optimizer='adam', metrics = ['acc'])\n\nhist = model.fit(x_train,y_train, epochs= 10000, batch_size= 1, validation_split= 0.2, callbacks= [early_stopping])\n\n\n\n# 평가 및 예측 \n\n\n\nloss, acc = model.evaluate(x_test,y_test, batch_size=1)\n \n\nprint('loss :', loss)\nprint('accuracy : ', acc)\n\n'''\n\nloss : 0.18060839686209842\naccuracy : 0.9210526347160339\n\n'''","sub_path":"keras/keras84_breast_cancer_CNN.py","file_name":"keras84_breast_cancer_CNN.py","file_ext":"py","file_size_in_byte":1897,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"501160721","text":"\"\"\"_jobs file for 'cmty_block_grants' layer sde extraction.\"\"\"\nfrom trident.util import general\nfrom trident.util import geospatial\nimport pandas as pd\nfrom collections import OrderedDict\nimport logging\n\nconf = general.config\ntable = 'CMTY_BLOCK_DEV_GRANTS'\nprod_dir = conf['prod_data_dir']\nlayername = 'block_grants_datasd'\nlayer = f\"{prod_dir}/{layername}\"\n\ndtypes = OrderedDict([\n ('objectid', 'int:5'),\n ('statefp', 'str:2'),\n ('countyfp', 'str:3'),\n ('tractce', 'str:6'),\n ('blkgrpce', 'str:1'),\n ('geoid', 'str:12'),\n ('geoname', 'str:255'),\n ('low','int:5'),\n ('lowmod', 'int:5'),\n ('lmmi', 'int:5'),\n ('lowmoduniv', 'int:5'),\n ('lowmod_pct', 'float:10.6'),\n ('low_pct', 'float:10.6'),\n ('lmmi_pct', 'float:10.6'),\n ('total_pop', 'int:5'),\n ('tot_units', 'int:5'),\n ('occ_units', 'int:4'),\n ('vac_units', 'int:3')\n ])\n\ngtype = 'Polygon'\n\n\ndef sde_to_shp():\n \"\"\"SDE table to Shapefile.\"\"\"\n logging.info(f'Extracting {layername} layer from SDE.')\n df = geospatial.extract_sde_data(table=table)\n # where=\" \")\n\n logging.info(f'Processing {layername} df.')\n df = df.rename(columns={'sum_totalpop': 'total_pop',\n 'sum_totunits': 'tot_units',\n 'sum_occunits': 'occ_units',\n 'sum_vacunits': 'vac_units'})\n df = df.fillna('')\n\n logging.info(f'Converting {layername} df to shapefile.')\n geospatial.df2shp(df=df,\n folder=prod_dir,\n layername=layername,\n dtypes=dtypes,\n gtype=gtype,\n epsg=2230)\n return f'Successfully converted {layername} to shapefile.'\n","sub_path":"poseidon/dags/sde/block_grants_jobs.py","file_name":"block_grants_jobs.py","file_ext":"py","file_size_in_byte":1835,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"647045709","text":"import cv2 as cv\r\nimport numpy as np\r\n\r\ncapture = cv.VideoCapture(0)\r\nret, frame1 = capture.read()\r\nret, frame2 = capture.read()\r\n\r\nwhile capture.isOpened():\r\n diff = cv.absdiff(frame1, frame2)\r\n gray = cv.cvtColor(diff, cv.COLOR_BGR2GRAY)\r\n blur = cv.GaussianBlur(gray, (5, 5), 0)\r\n _, threshold = cv.threshold(blur, 20, 255, cv.THRESH_BINARY)\r\n dilated = cv.dilate(threshold, None, iterations=3)\r\n controus, _ = cv.findContours(dilated, cv.RETR_TREE, cv.CHAIN_APPROX_NONE)\r\n\r\n cv.drawContours(frame1, controus, -1, (23, 234, 87), 2)\r\n\r\n cv.imshow('Movement Detection', frame1)\r\n frame1 = frame2\r\n ret, frame2 = capture.read()\r\n\r\n if cv.waitKey(40) == 27:\r\n break\r\n\r\ncapture.release()\r\ncv.destroyAllWindows()","sub_path":"movement_detection.py","file_name":"movement_detection.py","file_ext":"py","file_size_in_byte":749,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"597798191","text":"# importing necessary packages for execution\r\nimport numpy as np\r\nimport pygame\r\nfrom coditation import *\r\n\r\n# Define some colors\r\nBLACK = (0, 0, 0)\r\nWHITE = (255, 255, 255)\r\n# This sets the WIDTH and HEIGHT of each grid location\r\nWIDTH = 20\r\nHEIGHT = 20\r\n# This sets the margin between each cell\r\nMARGIN = 5\r\n# Initialize pygame\r\npygame.init()\r\n\r\n# Set the HEIGHT and WIDTH of the screen\r\nWINDOW_SIZE = [580, 580]\r\nscreen = pygame.display.set_mode(WINDOW_SIZE)\r\n# Set the screen background\r\nscreen.fill(BLACK)\r\n\r\n# Set title of screen\r\npygame.display.set_caption(\"Coditation\")\r\n\r\n\r\n# to run the loop continuosly\r\ndone = False\r\n\r\n# Screen update\r\nclock = pygame.time.Clock()\r\n\r\n# -------- Main Program Loop -----------\r\nwhile not done:\r\n for event in pygame.event.get(): # User did something\r\n if event.type == pygame.QUIT: # If user clicked close\r\n done = True # Flag that we are done so we exit this loop\r\n elif event.type == pygame.MOUSEBUTTONDOWN:\r\n # User clicks the mouse. Get the position\r\n pos = pygame.mouse.get_pos()\r\n # Change the x/y screen coordinates to grid coordinates\r\n column = pos[0] // (WIDTH + MARGIN)\r\n row = pos[1] // (HEIGHT + MARGIN)\r\n # Set that location to one or zero\r\n grid[row][column] = 1 if grid[row][column]== 0 else 0\r\n # check if the key is pressed\r\n elif event.type == pygame.KEYDOWN:\r\n # setting spacebar key function\r\n if event.key==pygame.K_SPACE:\r\n Check_conditions(grid)\r\n # setting R key for reset\r\n elif event.key == pygame.K_r:\r\n grid = np.zeros((23, 23))\r\n Check_conditions(grid)\r\n\r\n # creating grid on screen\r\n for row in range(23):\r\n for column in range(23):\r\n color = WHITE\r\n if grid[row][column] == 1:\r\n color = BLACK\r\n pygame.draw.rect(screen,\r\n color,\r\n [(MARGIN + WIDTH) * column + MARGIN,\r\n (MARGIN + HEIGHT) * row + MARGIN,\r\n WIDTH,\r\n HEIGHT])\r\n\r\n # 60 frames per second\r\n clock.tick(60)\r\n\r\n # update screen\r\n pygame.display.flip()\r\n\r\n# on exit.\r\npygame.quit()","sub_path":"coditation 2nd slide.py","file_name":"coditation 2nd slide.py","file_ext":"py","file_size_in_byte":2341,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"624300240","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.shortcuts import render, redirect, HttpResponse\nfrom django.contrib import messages\nfrom models import Review, ReviewManager, Author, Book\n\n############################################ Main page ############################\ndef books(request):\n reviewLists = Review.objects.getReviewLists()\n context = {\n 'alias': request.session['alias'],\n 'first_3': reviewLists['most_recent'],\n 'otherBooks': reviewLists['all_others'],\n }\n return render(request, 'Books_app/books.html', context)\n\n\n############################################ Specific Book ############################\ndef getBook(request, bookID):\n curBook = Book.objects.get(id=bookID)\n context ={\n 'newReview':\"\", \n 'title': curBook.title,\n 'author': curBook.author.name,\n 'reviews': curBook.reviews.all().order_by('created_at'),\n 'bookID': bookID,\n }\n return render(request, 'Books_app/bookDetails.html', context)\n\n\n############################################ Reviews ############################\ndef addForm(request):\n context = {\n 'title': '',\n 'new_author': '',\n 'review': '',\n 'authors': Author.objects.all().order_by('name'),\n }\n return render(request, 'Books_app/add.html', context)\n\n##### create new review from ^\ndef addReview(request):\n results = Review.objects.validateReview(request.POST)\n\n if results['status']:\n Review.objects.createReview(request.POST, request.session['userID'])\n return redirect('/books')\n else:\n #### saves your text in case it errors out\n context = {\n 'title': request.POST['title'],\n 'new_author': request.POST['new_author'],\n 'review': request.POST['review'],\n 'authors': Author.objects.all().order_by('name'),\n }\n # for error in results['errors']:\n # messages.error(request, error)\n genErrorMessages(request, results)\n return render(request, 'Books_app/add.html', context)\n\n##### from specific book page\ndef addAditionalReview(request, bookID): \n results = Review.objects.validateReview(request.POST)\n\n if results['status']:\n Review.objects.createReview(request.POST, request.session['userID'])\n return redirect('/books')\n else:\n # for error in results['errors']:\n # messages.error(request, error)\n genErrorMessages(request, results)\n\n #### saves your text in case it errors out\n curBook = Book.objects.get(id=bookID)\n context = {\n 'newReview': request.POST['review'],\n 'title': curBook.title,\n 'author': curBook.author.name,\n 'reviews': curBook.reviews.all().order_by('-created_at'),\n 'bookID': bookID,\n }\n return render(request, 'Books_app/bookDetails.html', context)\n\n##### destroy\ndef deleteReview(request, bookID, reviewID):\n #### prevents tampering with urls to delete\n if request.session['userID'] != Review.objects.get(id=reviewID).reviewer.id or 'email' not in request.session:\n return redirect('/books/{}'.format(bookID))\n else:\n Review.objects.get(id=reviewID).delete()\n return redirect('/books/{}'.format(bookID))\n\n############################################ Helper functions ############################\ndef genErrorMessages(request, results):\n for error in results['errors']:\n messages.error(request, error)","sub_path":"Django/BeltReviewer_project/apps/Books_app/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":3517,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"213451657","text":"import numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nfrom matplotlib.ticker import Formatter\nimport datetime as dt\nimport time\n\nDATA_DIR = '../data'\n\nclass MomentumStrategy:\n def __init__(self, principal=1000000):\n # Setup dataframes\n self.prices = None\n self.dates = None\n self._load_data()\n\n # Class variables\n self.principal = principal\n self.normalize = normalize\n \n def momentum_signal(self, look_back, normalize=True):\n \"\"\"\n return: momentum signal\n \"\"\"\n price_data = prices.iloc[:, [2,4,6]].values\n delay_price = np.roll(price_data, look_back, axis=0)\n delay_price[:look_back] = np.nan\n mom_sig = (price_data - delay_price) / delay_price\n if normalize:\n mom_sig = mom_sig - mom_sig.mean(axis=1,keepdims=True)\n mom_sig = mom_sig / ((mom_sig > 0) * mom_sig).sum(axis=1, keepdims=True)\n return mom_sig \n\n def _load_data(self):\n \"\"\"\n Loads price data\n \"\"\"\n self.prices = pd.read_csv(DATA_DIR, parse_dates=[0])\n self.dates = self.prices.iloc[:,0].apply(lambda x: pd.to_datetime(x))\n\nclass MyFormatter(Formatter):\n def __init__(self, dates, fmt='%Y-%m-%d'):\n self.dates = dates\n self.fmt = fmt\n\n def __call__(self, x, pos=0):\n 'Return the label for time x at position pos'\n ind = int(x)\n if ind >= len(self.dates) or ind < 0:\n return ''\n else:\n return self.dates[ind].strftime(self.fmt)\n \ndef annual_sharpe(pnl):\n mean = pnl.mean()\n var = pnl.std()\n day_sharpe = (mean / var) * np.sqrt(390)\n year_sharpe = day_sharpe * np.sqrt(252)\n return year_sharpe\n\ndef annual_return(pnl, principal=1000000): \n ret = pnl / principal\n return np.mean(ret) * 390 * 252\n\ndef annual_volatility(pnl, principal=1000000):\n log_ret = np.log(1 + pnl / principal)\n return log_ret.std() * np.sqrt(252)\n\ndef maximum_drawdown(pnl):\n cum_pnl = np.cumsum(pnl)\n ind = np.argmax(np.maximum.accumulate(cum_pnl) - cum_pnl)\n return (np.maximum.accumulate(cum_pnl)[ind] - cum_pnl[ind]) / np.maximum.accumulate(cum_pnl)[ind]\n\ndef annual_turnover(weights):\n turnover = np.sum(np.abs(weights[1:] - weights[:-1])) / weights.shape[0]\n return turnover * 390 * 252\n\nif __name__ == '__main__':\n # Testing class\n strat = MomentumStrategy()\n\n ret1 = strat.momentum_signal(lookback=1, normalize=False)\n\n mom = momentum_signal(prices, 2100)\n pnl_mom = np.sum(mom * np.roll(ret1, -1, axis=0), axis=1) * principal\n pnl_mom = np.nan_to_num(pnl_mom)\n\n plt.style.use(\"ggplot\")\n formatter = MyFormatter(dates)\n fig, ax = plt.subplots(figsize=(11, 7))\n ax.xaxis.set_major_formatter(formatter)\n ax.plot(np.arange(pnl_mom.shape[0]), np.cumsum(pnl_mom))\n fig.autofmt_xdate()\n plt.show()\n\n print(annual_sharpe(pnl_mom))\n","sub_path":"strategies/MomentumStrategy.py","file_name":"MomentumStrategy.py","file_ext":"py","file_size_in_byte":2926,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"53544670","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sat May 26 10:24:45 2018\n\n@author: Hermethus\n\"\"\"\n\nimport tensorflow as tf\nfrom tensorflow.examples.tutorials.mnist import input_data\n\n#相关常数\nINPUT_NODE = 784\nOUTPUT_NODE = 10\n\n#神经网络参数\nLAYER1_NODE = 128\nBATCH_SIZE = 100\nLEARNING_RATE_BASE = 0.8 #基础学习率\nLEARNING_RATE_DECAY = 0.99 #学习率衰减率\nREGULARIZATION_RATE = 0.0001#模型复杂度正则化项在损失函数中的系数\n #用于抑制过拟合\nTRAINING_STEPS = 3001\n\nMOVING_AVERAGE_DECAY = 0.99 #滑动平均衰减率,滑动平均模型类的参数\n #用于控制模型更新速度\n #越大模型越趋于稳定,随训练过程增大\n\n'''\n 定义了一个辅助函数,给定神经网络的输入和所有参数,计算神经网络的\n 前向传播结果。在这里使用ReLU激活函数,定义了一个三层神经网络。\n 支持传入用于计算参数均值的类,方便测试时使用滑动平均模型\n'''\ndef inference(input_tensor,avg_class,\n weights1,biases1,weights2,biases2):\n \n #如果没有提供滑动平均类,使用参数当前值\n if avg_class == None:\n layer1 = tf.nn.relu(tf.matmul(input_tensor,weights1)+biases1)\n \n #此处不需要添加激活函数,计算损失函数时会一并计算softmax函数\n return tf.matmul(layer1,weights2)+biases2\n \n #提供了滑动平均类,则先计算滑动平均值,再计算神经网络前向传播结果\n #average函数用来调用对应参数的滑动平均值\n else:\n layer1 = tf.nn.relu(\n tf.matmul(input_tensor,avg_class.average(weights1)) +\n avg_class.average(biases1))\n return tf.matmul(layer1,avg_class.average(weights2)) + \\\n avg_class.average(biases2)\n\n#将模型的训练过程封装为一个函数\ndef train(mnist):\n x = tf.placeholder(tf.float32,[None,INPUT_NODE],name='x-input')\n y_ = tf.placeholder(tf.float32,[None,OUTPUT_NODE],name='y-input')\n \n weights1 = tf.Variable(\n tf.truncated_normal([INPUT_NODE,LAYER1_NODE],stddev=0.1))\n biases1 = tf.Variable(tf.constant(0.1,shape=[LAYER1_NODE]))\n \n weights2 = tf.Variable(\n tf.truncated_normal([LAYER1_NODE,OUTPUT_NODE],stddev=0.1))\n biases2 = tf.Variable(tf.constant(0.1,shape=[OUTPUT_NODE]))\n \n #计算神经网络的前向传播结果,使用inference函数\n y = inference(x,None,weights1,biases1,weights2,biases2)\n \n #定义用于存储训练轮数的变量,此��量不需要被训练\n global_step = tf.Variable(0,trainable=False)\n \n #给定平均衰减率和训练轮数,初始化滑动平均类\n #tf.train.ExponentialMovingAverage函数采用滑动平均的方法更新参数。\n variable_averages = tf.train.ExponentialMovingAverage(\n MOVING_AVERAGE_DECAY,global_step)\n #对所有可训练变量使用滑动平均\n variables_averages_op = variable_averages.apply(\n tf.trainable_variables())\n \n \"\"\"\n 计算使用了滑动平均之后的前向传播结果\n 滑动平均并不改变变量本身的取值,只是维护一个影子变量来记录平均值\n 要使用这个平均值时,需调用average函数\n \"\"\"\n average_y = inference(x,variable_averages,\n weights1,biases1,weights2,biases2)\n \n #计算损失函数,sparse_softmax_cross_entropy_with_logits计算交叉熵\n #第一个参数是神经网络不包含softmax的前向传播结果\n #第二个参数是正确标签\n cross_entropy = tf.nn.sparse_softmax_cross_entropy_with_logits(\n logits=y,labels=tf.argmax(y_,1))\n #计算交叉熵的平均值\n cross_entropy_mean = tf.reduce_mean(cross_entropy)\n \n #计算L2正则化损失函数\n '''\n 正则化可以帮助防止过拟合,提高模型的适用性。\n 使用规则来使尽量少的变量去拟合数据,让模型无法完美匹配所有的训练项。\n L2正则化表达式暗示着一种倾向:训练尽可能的小的权重,\n 较大的权重需要保证能显著降低原有损失C0才能保留。\n 参数表示正则化权重。\n 返回一个执行L2正则化的函数。\n '''\n regularizer = tf.contrib.layers.l2_regularizer(REGULARIZATION_RATE)\n #计算正则化损失,一般只计算矩阵部分,不计算偏置项\n regularization = regularizer(weights1) + regularizer(weights2)\n #总损失等于交叉熵和正则化损失的和,这样,模型复杂度本身会提高损失函数\n loss = cross_entropy_mean + regularization\n \n #设置指数衰减的学习率\n learning_rate = tf.train.exponential_decay(\n LEARNING_RATE_BASE,global_step,\n mnist.train.num_examples/BATCH_SIZE,LEARNING_RATE_DECAY)\n \n #优化损失函数\n train_step = tf.train.GradientDescentOptimizer(learning_rate).\\\n minimize(loss,global_step=global_step)\n \n #在训练时,每过一遍数据需要通过反向传播更新参数以及滑动平均值\n #以下两行代码用于流程控制,可以一次完成多个机制\n #也可使用train_op = tf.group(train_step,variables_averages_op)\n with tf.control_dependencies([train_step,variables_averages_op]):\n train_op = tf.no_op(name='train')\n \n #判断正确性\n correct_prediction = tf.equal(tf.argmax(average_y,1),tf.argmax(y_,1))\n #计算正确率\n accuracy = tf.reduce_mean(tf.cast(correct_prediction,tf.float32))\n \n #初始化会话,开始训练\n with tf.Session() as sess:\n tf.global_variables_initializer().run()\n \n validate_feed = {x:mnist.validation.images,\n y_:mnist.validation.labels}\n \n test_feed = {x:mnist.test.images,y_:mnist.test.labels}\n \n for i in range(TRAINING_STEPS):\n if i % 300 == 0:\n validate_acc = sess.run(accuracy,feed_dict=validate_feed)\n print(\"经过%d次训练,正确率为%g\" % (i,validate_acc))\n \n xs,ys = mnist.train.next_batch(BATCH_SIZE)\n sess.run(train_op,feed_dict={x:xs,y_:ys})\n \n #测试最终正确率\n test_acc = sess.run(accuracy,feed_dict=test_feed)\n print(\"最终正确率为%g\" % (test_acc))\n \ndef main(argv=None):\n mnist = input_data.read_data_sets('MNIST_data',one_hot=True)\n train(mnist)\n\n#Tensorflow定义的主程序入口,会调用上面的main函数\nif __name__ == '__main__':\n tf.app.run()\n","sub_path":"mnist_classification_NN_new.py","file_name":"mnist_classification_NN_new.py","file_ext":"py","file_size_in_byte":6626,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"313835880","text":"import lstm\nimport time\nimport gc\n\nif __name__ == '__main__':\n\n global_start_time = time.time()\n\n data_file_name = '../data/S&P500_1_feature.csv'\n results_file_name = '../results/S&P500_1_feature_results.txt'\n\n training_ratio = 0.8\n batch_size = 1024\n validation_split = 0.2\n target_index = -1\n iteration = 10\n\n # Window size of the LSTM network (how many days of data used)\n for window_size in [8, 16, 32, 64, 128, 256]:\n # Number of neurons used in each hidden layer\n for neuron_num in [2, 4, 8, 16, 32]:\n mid_layers = [neuron_num, neuron_num]\n # Dropout rate during training (overfit prevention)\n for dropout_rate in [0, 0.05, 0.1, 0.15, 0.2]:\n # Number of training epoch (better data fitting)\n for epochs in [32, 64, 128, 256, 512]:\n\n accuracy = []\n for itr in range(iteration):\n start_time = time.time()\n\n print('> Starting iteration #' + str(itr + 1))\n # print('> Loading data... ')\n\n x_train, y_train, x_test, y_test, y_norm = \\\n lstm.load_data(\n data_file_name,\n window_size,\n target_index,\n training_ratio)\n\n # print('> Data loaded. Compiling...')\n model = lstm.build_model(\n [x_train.shape[-1]] + mid_layers + [\n y_train.shape[-1]], dropout_rate)\n\n model.fit(\n x_train,\n y_train,\n batch_size=batch_size,\n nb_epoch=epochs,\n validation_split=validation_split)\n\n print('Learning duration (s) : ',\n time.time() - start_time)\n\n accuracy.append(\n lstm.predict_in_sample(model, x_test, y_test,\n y_norm))\n\n print(accuracy)\n print(sum(accuracy) / float(len(accuracy)))\n\n with open(results_file_name, \"a\") as file:\n file.write(\n \"Window Size: {:<6d}; Neuron Number: {:<6d}; \"\n \"Dropout Rate: {:<6.2f}; Epoch Number: \"\n \"{:<6d}; Overall Accuracy: {:<.6f}\\n\".format(\n window_size, neuron_num,\n dropout_rate, epochs,\n sum(accuracy) / float(len(accuracy))))\n\n print('Trail duration (s) : ',\n time.time() - global_start_time)\n\n gc.collect()\n","sub_path":"scripts/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2939,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"631308632","text":"from django.http import HttpResponse, HttpResponseRedirect\nfrom bambu_api.auth import AuthenticationBase\nfrom soundmachine.mobile.models import Token\nfrom logging import getLogger\n\nclass TokenAuthentication(AuthenticationBase):\n verbose_name = 'Token'\n\n def authenticate(self, request):\n if request.user.is_authenticated():\n self.user = request.user\n return True\n\n auth = request.META.get('Authorization', '') or request.META.get('HTTP_AUTHORIZATION', '')\n device = request.META.get('X-Device', '') or request.META.get('HTTP_X_DEVICE', '')\n platform = request.META.get('X-Platform', '') or request.META.get('HTTP_X_PLATFORM', '')\n\n if auth:\n try:\n token = Token.objects.get(\n key = auth,\n device = device,\n platform = platform\n )\n except Token.DoesNotExist:\n return False\n\n self.user = token.user\n return True\n\n return False\n\n def challenge(self, request):\n return HttpResponseRedirect(\n '/login/twitter/?next=%s' % request.path\n )\n","sub_path":"soundmachine/mobile/auth.py","file_name":"auth.py","file_ext":"py","file_size_in_byte":1176,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"130364759","text":"import pickle\nimport re\nimport socket\nimport threading\nimport time\nimport traceback\nimport requests\nfrom PyQt5 import QtCore, QtGui, QtWidgets\nfrom PyQt5.QtGui import QIcon, QBrush, QPixmap, QPalette\n\nfrom PyQt5.QtWidgets import *\nfrom PyQt5.QtCore import *\nfrom setuptools.msvc import winreg\nRUN_PATH = \"HKEY_CURRENT_USER\\\\Software\\\\Microsoft\\\\Windows\\\\CurrentVersion\\\\Run\"\nlft_username = ''\nlft_city = ''\n#城市选择\nfit_city_dic = {\n '合肥': 'hefei',\n '北京': 'beijing',\n '上海': 'shanghai',\n '南京':'nanjing',\n '无锡':'wuxi',\n '苏州':'suzhou',\n '芜湖': 'wuhu',\n '滁州': 'chuzhou',\n '阜阳': 'fuyang',\n '济南': 'jinan',\n '武汉': 'wuhan',\n '广州': 'guangzhou',\n '深圳': 'shenzhen',\n '西安': 'xian'\n}\nfit_city_list = [\n '苏州',\n '合肥',\n '北京',\n '上海',\n '南京',\n '无锡',\n '芜湖',\n '滁州',\n '阜阳',\n '济南',\n '武汉',\n '广州',\n '深圳',\n '西安',\n]\n# 环境变量\none_time_transport_data = 1024\n# 链接的目标ip地址\nbind_ip = '112.27.215.99'\n# 链接的目标post\nbind_port = 8410\ndef start_socket_connect():\n '''\n - 功能\n - 接受客户端的数据,请求后再返回给客户端\n - 流程\n - 建立连接\n - 向服务器发送客户端信息\n - 循环等待服务器数据,处理后再发回服务器\n - 接口\n - 上层接口\n - 字符串FREE 服务器没有数据,断开连接\n - 字典 请求参数\n - 返回给上层数据\n - req response实例\n - req(请求错误原因) 字符串\n '''\n\n client = socket.socket()\n\n try:\n ip_port = (bind_ip, bind_port)\n client.connect(ip_port)\n # 发送客户端信息\n client.send(pickle.dumps({'lft_username': lft_username, 'lft_city': lft_city}))\n recv_from_server = b''\n print('客户端开始接受服务器的信息...')\n client.settimeout(18*60) #最多18分钟\n while True:\n data = client.recv(one_time_transport_data)\n print('{} 接受的数据是->{}'.format(time.asctime(time.localtime(time.time())),data))\n if not data: # 异常情况 链接直接断开 一般不会发生\n raise ConnectionRefusedError()\n else:\n recv_from_server += data\n\n if recv_from_server == b'FREE': # 标示不需要请求参数\n print('空闲{}'.format(time.strftime('%Y-%M-%d %H:%M:%S', time.localtime(time.time()))))\n break\n elif recv_from_server.endswith(b'endendend'):\n print('接受完服务器发来的请求.开始处理...')\n recv_from_server = recv_from_server.replace(b'endendend', b'')\n params = pickle.loads(recv_from_server)\n try:\n if params['method'] == 'get':\n req = requests.get(**params['requestsparams'])\n else:\n req = requests.post(**params['requestsparams'])\n except:\n req = traceback.format_exc()\n client.sendall(pickle.dumps(req) + b'endendend')\n print('请求结果已经发给客户端了')\n\n recv_from_server = b''\n except ConnectionRefusedError:\n print('未连接上服务器或者服务器主动断开.... 1秒后重新请求')\n traceback.print_exc()\n except Exception as err:\n print('异常了', '!' * 200)\n traceback.print_exc()\n finally:\n client.close()\n print('-' * 30)\n timer = threading.Timer(30, start_socket_connect)\n timer.start()\n\n\nclass Login_Ui_MainWindow(QtWidgets.QMainWindow):\n\n def __init__(self):\n super(Login_Ui_MainWindow,self).__init__()\n self.setupUi(self)\n self.retranslateUi(self)\n\n\n\n def setupUi(self, MainWindow):\n MainWindow.setObjectName(\"MainWindow\")\n MainWindow.resize(406, 147)\n MainWindow.setWindowIcon(QIcon('D:\\\\untitled\\\\star.ico'))\n MainWindow.setStyleSheet(\"background-image:url(D:\\\\untitled\\\\star.ico)\")\n # MainWindow.setStyleSheet(\"background-color:green;\");\n\n\n self.centralWidget = QtWidgets.QWidget(MainWindow)\n self.centralWidget.setObjectName(\"centralWidget\")\n self.lineEdit = QtWidgets.QLineEdit(self.centralWidget)\n self.lineEdit.setGeometry(QtCore.QRect(170, 24, 170, 30))\n self.lineEdit.setText(\"\")\n self.lineEdit.setObjectName(\"lineEdit\")\n try:\n key = winreg.OpenKey(winreg.HKEY_CURRENT_USER,\n r'Software\\Microsoft\\Windows\\CurrentVersion\\Explorer\\Shell Folders') # 利用系统的链表\n Desktop_path = str(winreg.QueryValueEx(key, \"Desktop\")[0])\n up_desktop_path = '\\\\'.join(Desktop_path.split('\\\\')[:-1])\n with open(up_desktop_path + '\\\\zh.txt', 'r+') as fp:\n zh = fp.readlines()[0].strip()\n print(zh)\n self.lineEdit.setText(zh)\n except:\n pass\n\n # self.lineEdit_2 = QtWidgets.QLineEdit(self.centralWidget)\n # self.lineEdit_2.setGeometry(QtCore.QRect(150, 50, 200, 20))\n # self.lineEdit_2.setText(\"\")\n # # self.lineEdit_2.setEchoMode(QtWidgets.QLineEdit.Password) #是否将输入变成***\n # self.lineEdit_2.setObjectName(\"lineEdit_2\")\n\n self.comboBox_2 = QtWidgets.QComboBox(self.centralWidget)\n self.comboBox_2.setGeometry(QtCore.QRect(170, 64, 170, 30))\n self.comboBox_2.setObjectName(\"comboBox_2\")\n\n self.label = QtWidgets.QLabel(self.centralWidget)\n self.label.setGeometry(QtCore.QRect(45, 23, 95, 35))\n self.label.setTextFormat(QtCore.Qt.AutoText)\n self.label.setObjectName(\"label\")\n self.label_2 = QtWidgets.QLabel(self.centralWidget)\n self.label_2.setGeometry(QtCore.QRect(45, 63, 95, 35))\n self.label_2.setObjectName(\"label_2\")\n self.pushButton = QtWidgets.QPushButton(self.centralWidget)\n self.pushButton.setGeometry(QtCore.QRect(90, 103, 75, 30))\n self.pushButton.setObjectName(\"pushButton\")\n self.pushButton_2 = QtWidgets.QPushButton(self.centralWidget)\n self.pushButton_2.setGeometry(QtCore.QRect(210, 103, 75, 30))\n self.pushButton_2.setObjectName(\"pushButton_2\")\n MainWindow.setCentralWidget(self.centralWidget)\n\n self.pushButton.clicked.connect(self.word_get)\n self.pushButton_2.clicked.connect(self.quit_main)\n\n\n self.retranslateUi(MainWindow)\n QtCore.QMetaObject.connectSlotsByName(MainWindow)\n\n def retranslateUi(self, MainWindow):\n _translate = QtCore.QCoreApplication.translate\n MainWindow.setWindowTitle(_translate(\"MainWindow\", \"发布器\"))\n self.lineEdit.setPlaceholderText(_translate(\"MainWindow\", \"请输入乐房通手机号\"))\n # self.lineEdit_2.setPlaceholderText(_translate(\"MainWindow\", \"输入其中一个(hefei|nanjing|bozhou|shanghai)\"))\n self.comboBox_2.clear()\n #根据ip判断城市所在地\n try:\n content = requests.get('http://2019.ip138.com/ic.asp').content.decode('gbk')\n re_city = re.search('.*?省(.*?)市.*? ',content).group(1)\n if re_city in fit_city_list:\n city_index = fit_city_list.index(re_city)\n del fit_city_list[city_index]\n fit_city_list.append(re_city)\n except:\n pass\n for key in fit_city_list[::-1]:\n self.comboBox_2.addItem(key)\n\n self.label.setText(_translate(\"MainWindow\", \"乐房通账号\"))\n self.label_2.setText(_translate(\"MainWindow\", \"所在城市\"))\n self.pushButton.setText(_translate(\"MainWindow\", \"确定\"))\n self.pushButton_2.setText(_translate(\"MainWindow\", \"取消\"))\n\n def quit_main(self):\n exit()\n\n def word_get(self):\n input_username = self.lineEdit.text().strip()\n # input_city = self.lineEdit_2.text().strip()\n global lft_username,lft_city\n lft_username = input_username\n lft_city = fit_city_dic.get(self.comboBox_2.currentText())\n print(lft_username,lft_city)\n if len(lft_username)==11 and lft_city != None:\n try:\n key = winreg.OpenKey(winreg.HKEY_CURRENT_USER,\n r'Software\\Microsoft\\Windows\\CurrentVersion\\Explorer\\Shell Folders') # 利用系统的链表\n Desktop_path = str(winreg.QueryValueEx(key, \"Desktop\")[0])\n up_desktop_path = '\\\\'.join(Desktop_path.split('\\\\')[:-1])\n with open(up_desktop_path + '\\\\zh.txt', 'w+') as fp:\n fp.write(lft_username + '\\n')\n fp.write(lft_city)\n except:\n pass\n # 关闭所有窗口,也不关闭应用程序\n QApplication.setQuitOnLastWindowClosed(False)\n #关闭登陆窗口\n MainWindow.close()\n\n #设置系统托盘弹出信息\n tp.showMessage('提示', '发布器后台运行中', icon=0)\n\n # 开机自启动\n self.settings = QSettings(RUN_PATH, QSettings.NativeFormat)\n self.settings.setValue(\"MainWidget\", sys.argv[0] + ' autoxxx');\n\n #开启线程守护线程\n timer = threading.Timer(1,start_socket_connect)\n timer.start()\n else:\n if len(lft_username) != 11:\n msg = '手机号长度为11位'\n else:\n msg = '请选择城市'\n QMessageBox.warning(self,\n \"警告\",\n msg,\n QMessageBox.Yes)\n self.lineEdit.setFocus()\n\n\n\n\nclass hello_mainWindow(QtWidgets.QMainWindow):\n\n def __init__(self):\n super(hello_mainWindow,self).__init__()\n self.setupUi(self)\n self.retranslateUi(self)\n\n\n\n def setupUi(self, MainWindow):\n MainWindow.setObjectName(\"MainWindow\")\n MainWindow.resize(370, 70)\n MainWindow.setWindowIcon(QIcon('D:\\\\untitled\\\\star.ico'))\n MainWindow.setStyleSheet(\"background-image:url(D:\\\\untitled\\\\star.ico)\")\n self.centralWidget = QtWidgets.QWidget(MainWindow)\n self.centralWidget.setObjectName(\"centralWidget\")\n\n self.label = QtWidgets.QLabel(self.centralWidget)\n self.label.setGeometry(QtCore.QRect(20, 10, 310, 20))\n self.label.setTextFormat(QtCore.Qt.AutoText)\n self.label.setObjectName(\"label\")\n\n MainWindow.setCentralWidget(self.centralWidget)\n\n self.retranslateUi(MainWindow)\n QtCore.QMetaObject.connectSlotsByName(MainWindow)\n\n def retranslateUi(self, MainWindow):\n _translate = QtCore.QCoreApplication.translate\n MainWindow.setWindowTitle(_translate(\"MainWindow\", \"123\"))\n self.label.setText(_translate(\"MainWindow\", \"已完成登录,发布器运行中...可关闭此窗口\"))\n\n\n\n\n\nif __name__ == \"__main__\":\n import sys\n try:\n if len(sys.argv) == 2:\n #开机启动\n key = winreg.OpenKey(winreg.HKEY_CURRENT_USER,\n r'Software\\Microsoft\\Windows\\CurrentVersion\\Explorer\\Shell Folders') # 利用系统的链表\n Desktop_path = str(winreg.QueryValueEx(key, \"Desktop\")[0])\n up_desktop_path = '\\\\'.join(Desktop_path.split('\\\\')[:-1])\n with open(up_desktop_path + '\\\\zh.txt', 'r+') as fp:\n lines = fp.readlines()\n lft_username,lft_city = lines[0].strip(),lines[1].strip()\n timer = threading.Timer(1, start_socket_connect)\n timer.start()\n timer.join()\n else:\n #手动启动\n pass\n except:\n pass\n\n\n app = QtWidgets.QApplication(sys.argv)\n MainWindow = QtWidgets.QMainWindow()\n ui = Login_Ui_MainWindow()\n ui_hello = hello_mainWindow()\n ui.setupUi(MainWindow)\n MainWindow.show()\n\n\n # 在系统托盘处显示图标\n def quitApp():\n MainWindow.show() # w.hide() #隐藏\n re = QMessageBox.question(ui_hello, \"提示\", \"退出系统\", QMessageBox.Yes |\n QMessageBox.No, QMessageBox.No)\n if re == QMessageBox.Yes:\n # 关闭窗体程序\n QCoreApplication.instance().quit()\n # 在应用程序全部关闭后,TrayIcon其实还不会自动消失,\n # 直到你的鼠标移动到上面去后,才会消失,\n # 这是个问题,(如同你terminate一些带TrayIcon的应用程序时出现的状况),\n # 这种问题的解决我是通过在程序退出前将其setVisible(False)来完成的。\n tp.setVisible(False)\n tp = QSystemTrayIcon(MainWindow)\n tp.setIcon(QIcon('D:\\\\untitled\\\\xxx.png'))\n #设置两个选项\n a1 = QAction('&显示(Show)', triggered=ui_hello.show)\n a2 = QAction('&退出(Exit)', triggered=quitApp) # 直接退出可以用qApp.quit\n tpMenu = QMenu()\n tpMenu.addAction(a1)\n tpMenu.addAction(a2)\n tp.setContextMenu(tpMenu)\n # 不调用show不会显示系统托盘\n tp.show()\n # 信息提示\n # 参数1:标题\n # 参数2:内容\n # 参数3:图标(0没有图标 1信息图标 2警告图标 3错误图标),0还是有一个小图标\n #登陆成功的时候调用\n # tp.showMessage('tp', 'tpContent', icon=0)\n def message():\n print(\"弹出的信息被点击了\")\n tp.messageClicked.connect(message)\n def act(reason):\n # 鼠标点击icon传递的信号会带有一个整形的值,1是表示单击右键,2是双击,3是单击左键,4是用鼠标中键点击\n if reason == 2 or reason == 3:\n ui_hello.show()\n # print(\"系统托盘的图标被点击了\")\n tp.activated.connect(act)\n\n\n sys.exit(app.exec_())\n\n\n###\n","sub_path":"socketServerClient/socket_client.py","file_name":"socket_client.py","file_ext":"py","file_size_in_byte":13970,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"341886253","text":"# Author: Sheikh Rabiul Islam\n# Date: 07/18/2019\n# Purpose: AdaBoost on fully processed data\n\n#import modules\nimport pandas as pd \nimport numpy as np\nimport time\n\n#configurations\nconfig_file = 'config.txt'\nconfig = pd.read_csv(config_file,sep=',', index_col =None)\nresample_data = config.iloc[0,1] #0 or 1\nfeature_set = config.iloc[1,1] # 1 = full features, 2 = selected, 3 = domain\nattack_id = config.iloc[2,1]\ndel config\n\nprint(\"AdaBoost:\",resample_data)\nstart = time.time()\n\nfrom sklearn.ensemble import AdaBoostClassifier\n\n\nclassifier = AdaBoostClassifier(base_estimator=None, n_estimators=50, learning_rate=1.0, algorithm='SAMME.R', random_state=None)\n\n# import processed data\nf_X_train = 'data/data_fully_processed_X_train'\nf_y_train = 'data/data_fully_processed_y_train'\nf_X_test = 'data/data_fully_processed_X_test'\nf_y_test = 'data/data_fully_processed_y_test'\n\nif resample_data == 1:\n f_X_train = f_X_train + \"_resampled\"\n f_y_train = f_y_train + \"_resampled\"\n\nif feature_set == 1:\n f_X_train = f_X_train + \"_all_features\"\n f_y_train = f_y_train + \"_all_features\"\n f_X_test = f_X_test + \"_all_features\"\n f_y_test = f_y_test + \"_all_features\"\nelif feature_set == 2:\n f_X_train = f_X_train + \"_selected_features\"\n f_y_train = f_y_train + \"_selected_features\"\n f_X_test = f_X_test + \"_selected_features\"\n f_y_test = f_y_test + \"_selected_features\"\nelse:\n f_X_train = f_X_train + \"_domain_features\"\n f_y_train = f_y_train + \"_domain_features\"\n f_X_test = f_X_test + \"_domain_features\"\n f_y_test = f_y_test + \"_domain_features\" \n\n \n\nf_X_train = f_X_train + \".npy\"\nf_y_train = f_y_train + \".npy\"\nf_X_test = f_X_test + \".npy\"\nf_y_test = f_y_test + \".npy\"\n\n\nprint(f_X_train)\nprint(f_y_train)\nprint(f_X_test)\nprint(f_y_test)\n\nX_train = np.load(f_X_train)\ny_train = np.load(f_y_train)\nX_test = np.load(f_X_test)\ny_test = np.load(f_y_test)\n\n# Fitting classifier to the Training set \nclassifier.fit(X_train, y_train)\n\n# Predicting the Test set results\ny_pred = classifier.predict(X_test)\n\n#dump y_pred for future use ( to calculate percent of attack detected in case of experiment 2 where we exclude one attack from training set)\ndf_y_pred = pd.DataFrame(y_pred, columns=['y_pred'])\ndf_y_pred.to_csv(\"data/y_pred.csv\",encoding='utf-8') \n\n\n\n# Performance metrics\nfrom sklearn.metrics import confusion_matrix, accuracy_score, precision_score, roc_curve, auc, precision_recall_curve \nfrom sklearn.metrics import precision_recall_fscore_support\ncm = confusion_matrix(y_test, y_pred)\n\n#accuracy -number of instance correctly classified\nacsc = accuracy_score(y_test, y_pred) \ndf_cm = pd.DataFrame([[cm[1][1], cm[0][0],cm[0][1], cm[1][0]]], \n index=[0],\n columns=['True Positives','True Negatives', 'False Positives', 'False Negatives'])\nprint(df_cm)\n#precision, recall, fscore, support\nprecision, recall, fscore, support = precision_recall_fscore_support(y_test, y_pred,average='binary')\n\n#balanced_as = balanced_accuracy_score(y_test, y_pred)\n\nfpr, tpr, thresholds = roc_curve(y_test, classifier.predict_proba(X_test)[:,1], pos_label=1)\nroc_auc = auc(fpr,tpr) # ROC-AUC\n\n#precision recall AUC ->PRC\nprc_precision, prc_recall, prc_thresholds = precision_recall_curve(y_test, classifier.predict_proba(X_test)[:,1])\n#prc_auc = auc(prc_precision,prc_recall)\nprc_auc = ''\ndf_metrics = pd.DataFrame([[acsc, precision, recall, fscore,roc_auc]], \n index=[0],\n columns=['accuracy','precision', 'recall', 'fscore', 'ROC-AUC'])\n\nprint(df_metrics)\nend = time.time()\nprint(df_metrics.iloc[0][0],',',df_metrics.iloc[0][1],',',df_metrics.iloc[0][2],',',df_metrics.iloc[0][3],',',df_metrics.iloc[0][4],',',df_cm.iloc[0][0],',',df_cm.iloc[0][1],',',df_cm.iloc[0][2],',',df_cm.iloc[0][3],',', end-start)\n\nprint(\"Time taken:\", end-start)","sub_path":"classifier_adaboost.py","file_name":"classifier_adaboost.py","file_ext":"py","file_size_in_byte":3856,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"57508227","text":"# coding: utf-8\n\n# # Optimization Methods\n# \n# Gradient descent goes \"downhill\" on a cost function $J$. Think of it as trying to do this: \n# At each step of the training,\n# you update your parameters following a certain direction to try to get to the lowest possible point.\n#\n# To get started, run the following code to import the libraries you will need.\n\n\nimport math\n\nimport matplotlib.pyplot as plt\n\nfrom opt_testCases import *\nfrom opt_utils import compute_cost, predict, predict_dec, plot_decision_boundary, load_dataset\nfrom opt_utils import initialize_parameters, forward_propagation, backward_propagation\n\nplt.rcParams['figure.figsize'] = (7.0, 4.0) # set default size of plots\nplt.rcParams['image.interpolation'] = 'nearest'\nplt.rcParams['image.cmap'] = 'gray'\n\n\n# ## 1 - Gradient Descent\n# \n# A simple optimization method in machine learning is gradient descent (GD).\n# When you take gradient steps with respect to all $m$ examples on each step, it is also called Batch Gradient Descent.\n#\n#\n\n# GRADED FUNCTION: update_parameters_with_gd\n\ndef update_parameters_with_gd(parameters, grads, learning_rate):\n \"\"\"\n Update parameters using one step of gradient descent\n :param parameters: parameters to be updated:\n parameters['W' + str(l)] = Wl\n parameters['b' + str(l)] = bl\n :param grads: containing your gradients to update each parameters:\n grads['dW' + str(l)] = dWl\n grads['db' + str(l)] = dbl\n :param learning_rate: the learning rate, scalar\n :return:\n parameters -- python dictionary containing your updated parameters\n \"\"\"\n L = len(parameters) // 2 # number of layers in the neural networks\n # Update rule for each parameter\n for l in range(L):\n parameters[\"W\" + str(l + 1)] = parameters[\"W\" + str(l + 1)] - learning_rate * grads['dW' + str(l + 1)]\n parameters[\"b\" + str(l + 1)] = parameters[\"b\" + str(l + 1)] - learning_rate * grads['db' + str(l + 1)]\n return parameters\n\n\n# A variant of this is Stochastic Gradient Descent (SGD),\n# which is equivalent to mini-batch gradient descent where each mini-batch has just 1 example.\n# The update rule that you have just implemented does not change.\n# What changes is that you would be computing gradients on just one training example at a time,\n# rather than on the whole training set.\n# The code examples below illustrate the difference between stochastic gradient descent and (batch) gradient descent.\n# \n# - **(Batch) Gradient Descent**:\n# \n# ``` python\n# X = data_input\n# Y = labels\n# parameters = initialize_parameters(layers_dims)\n# for i in range(0, num_iterations):\n# # Forward propagation\n# a, caches = forward_propagation(X, parameters)\n# # Compute cost.\n# cost = compute_cost(a, Y)\n# # Backward propagation.\n# grads = backward_propagation(a, caches, parameters)\n# # Update parameters.\n# parameters = update_parameters(parameters, grads)\n# \n# ```\n# \n# - **Stochastic Gradient Descent**:\n# \n# ```python\n# X = data_input\n# Y = labels\n# parameters = initialize_parameters(layers_dims)\n# for i in range(0, num_iterations):\n# for j in range(0, m):\n# # Forward propagation\n# a, caches = forward_propagation(X[:,j], parameters)\n# # Compute cost\n# cost = compute_cost(a, Y[:,j])\n# # Backward propagation\n# grads = backward_propagation(a, caches, parameters)\n# # Update parameters.\n# parameters = update_parameters(parameters, grads)\n# ```\n# \n\n# In Stochastic Gradient Descent,\n# you use only 1 training example before updating the gradients.\n# When the training set is large, SGD can be faster.\n# But the parameters will \"oscillate\" toward the minimum rather than converge smoothly.\n#\n# **Note** also that implementing SGD requires 3 for-loops in total:\n# 1. Over the number of iterations\n# 2. Over the $m$ training examples\n# 3. Over the layers (to update all parameters\n\n\n# **What you should remember**:\n# - The difference between gradient descent,\n# mini-batch gradient descent and stochastic gradient descent is the number of examples\n# you use to perform one update step.\n# - You have to tune a learning rate hyper-parameter.\n# - With a well-turned mini-batch size,\n# usually it outperforms either gradient descent or stochastic gradient descent\n# (particularly when the training set is large).\n\n# ## 2 - Mini-Batch Gradient descent\n# \n# Let's learn how to build mini_batches from the training set (X, Y).\n# \n# There are two steps:\n# - **Shuffle**: Create a shuffled version of the training set (X, Y) as shown below.\n# Each column of X and Y represents a training example.\n# Note that the random shuffling is done synchronously between X and Y.\n# The shuffling step ensures that examples will be split randomly into different mini_batches.\n# \n#\n# - **Partition**: Partition the shuffled (X, Y) into mini_batches of size `mini_batch_size` (here 64).\n# Note that the number of training examples is not always divisible by `mini_batch_size`.\n# The last mini batch might be smaller, but you don't need to worry about this.\n# When the final mini-batch is smaller than the full `mini_batch_size`, it will look like this:\n#\n#\n\n# GRADED FUNCTION: random_mini_batches\n\ndef random_mini_batches(matrix_x, y, mini_batch_size=64, seed=0):\n \"\"\"\n Creates a list of random mini_batches from (matrix_x, y)\n :param matrix_x: input data, of shape (input size, number of examples)\n :param y: true \"label\" vector (1 for blue dot / 0 for red dot), of shape (1, number of examples)\n :param mini_batch_size: size of the mini_batches, integer\n :param seed: random seed\n :return:\n mini_batches -- list of synchronous (mini_batch_X, mini_batch_Y)\n \"\"\"\n np.random.seed(seed) # To make your \"random\" mini_batches the same as ours\n m = matrix_x.shape[1] # number of training examples\n mini_batches = []\n\n # Step 1: Shuffle (matrix_x, y)\n permutation = list(np.random.permutation(m))\n shuffled_X = matrix_x[:, permutation]\n shuffled_Y = y[:, permutation].reshape((1, m))\n # Step 2: Partition (shuffled_X, shuffled_Y). Minus the end case.\n num_complete_mini_batches = math.floor(\n m / mini_batch_size) # number of mini batches of size mini_batch_size in your partitioning\n for k in range(0, int(num_complete_mini_batches)):\n mini_batch_X = shuffled_X[:, k * mini_batch_size: (k + 1) * mini_batch_size]\n mini_batch_Y = shuffled_Y[:, k * mini_batch_size: (k + 1) * mini_batch_size]\n mini_batch = (mini_batch_X, mini_batch_Y)\n mini_batches.append(mini_batch)\n\n # Handling the end case (last mini-batch < mini_batch_size)\n if m % mini_batch_size != 0:\n mini_batch_X = shuffled_X[:, num_complete_mini_batches * mini_batch_size:]\n mini_batch_Y = shuffled_Y[:, num_complete_mini_batches * mini_batch_size:]\n mini_batch = (mini_batch_X, mini_batch_Y)\n mini_batches.append(mini_batch)\n return mini_batches\n\n\n# **What you should remember**:\n# - Shuffling and Partitioning are the two steps required to build mini_batches\n# - Powers of two are often chosen to be the mini-batch size, e.g., 16, 32, 64, 128.\n\n# ## 3 - Momentum\n# \n# Because mini-batch gradient descent makes a parameter update after seeing just a subset of examples,\n# the direction of the update has some variance,\n# and so the path taken by mini-batch gradient descent will \"oscillate\" toward convergence.\n# Using momentum can reduce these oscillations.\n# \n# Momentum takes into account the past gradients to smooth out the update.\n# We will store the 'direction' of the previous gradients in the variable $v$.\n# Formally, this will be the exponentially weighted average of the gradient on previous steps.\n# You can also think of $v$ as the \"velocity\" of a ball rolling downhill,\n# building up speed (and momentum) according to the direction of the gradient/slope of the hill.\n# \n#\n# GRADED FUNCTION: initialize_velocity\n\ndef initialize_velocity(parameters):\n \"\"\"\n Initializes the velocity as a python dictionary with:\n - keys: \"dW1\", \"db1\", ..., \"dWL\", \"dbL\"\n - values: numpy arrays of zeros of the same shape as the corresponding gradients/parameters.\n :param parameters: python dictionary containing your parameters.\n parameters['W' + str(l)] = Wl\n parameters['b' + str(l)] = bl\n :return:\n v -- python dictionary containing the current velocity.\n v['dW' + str(l)] = velocity of dWl\n v['db' + str(l)] = velocity of dbl\n \"\"\"\n L = len(parameters) // 2 # number of layers in the neural networks\n v = {}\n\n # Initialize velocity\n for l in range(L):\n v[\"dW\" + str(l + 1)] = np.zeros((parameters['W' + str(l + 1)].shape[0], parameters['W' + str(l + 1)].shape[1]))\n v[\"db\" + str(l + 1)] = np.zeros((parameters['b' + str(l + 1)].shape[0], parameters['b' + str(l + 1)].shape[1]))\n return v\n\n\n# GRADED FUNCTION: update_parameters_with_momentum\n\ndef update_parameters_with_momentum(parameters, grads, v, beta, learning_rate):\n \"\"\"\n Update parameters using Momentum\n :param parameters: parameters:\n parameters['W' + str(l)] = Wl\n parameters['b' + str(l)] = bl\n :param grads: your gradients for each parameters:\n grads['dW' + str(l)] = dWl\n grads['db' + str(l)] = dbl\n :param v: the current velocity:\n v['dW' + str(l)] = ...\n v['db' + str(l)] = ...\n :param beta: the momentum hyper-parameter, scalar\n :param learning_rate: the learning rate, scalar\n :return:\n parameters -- python dictionary containing your updated parameters\n v -- python dictionary containing your updated velocities\n \"\"\"\n\n L = len(parameters) // 2 # number of layers in the neural networks\n\n # Momentum update for each parameter\n for l in range(L):\n # compute velocities\n v[\"dW\" + str(l + 1)] = beta * v[\"dW\" + str(l + 1)] + (1 - beta) * grads['dW' + str(l + 1)]\n v[\"db\" + str(l + 1)] = beta * v[\"db\" + str(l + 1)] + (1 - beta) * grads['db' + str(l + 1)]\n # update parameters\n parameters[\"W\" + str(l + 1)] = parameters[\"W\" + str(l + 1)] - learning_rate * v[\"dW\" + str(l + 1)]\n parameters[\"b\" + str(l + 1)] = parameters[\"b\" + str(l + 1)] - learning_rate * v[\"db\" + str(l + 1)]\n\n return parameters, v\n\n\n# **Note** that:\n# - The velocity is initialized with zeros.\n# So the algorithm will take a few iterations to \"build up\" velocity and start to take bigger steps.\n# - If $\\beta = 0$, then this just becomes standard gradient descent without momentum. \n# \n# **How do you choose $\\beta$?**\n# \n# - The larger the momentum $\\beta$ is,\n# the smoother the update because the more we take the past gradients into account.\n# But if $\\beta$ is too big, it could also smooth out the updates too much.\n# - Common values for $\\beta$ range from 0.8 to 0.999.\n# If you don't feel inclined to tune this, $\\beta = 0.9$ is often a reasonable default.\n# - Tuning the optimal $\\beta$ for your model might need trying several values to see what works best\n# in term of reducing the value of the cost function $J$.\n\n# **What you should remember**:\n# - Momentum takes past gradients into account to smooth out the steps of gradient descent.\n# It can be applied with batch gradient descent, mini-batch gradient descent or stochastic gradient descent.\n# - You have to tune a momentum hyper-parameter $\\beta$ and a learning rate $\\alpha$.\n\n# ## 4 - Adam\n# \n# Adam is one of the most effective optimization algorithms for training neural networks.\n# It combines ideas from RMSProp (described in lecture) and Momentum.\n#\n\n# GRADED FUNCTION: initialize_adam\n\ndef initialize_adam(parameters):\n \"\"\"\n Initializes v and s as two python dictionaries with:\n - keys: \"dW1\", \"db1\", ..., \"dWL\", \"dbL\"\n - values: numpy arrays of zeros of the same shape as the corresponding gradients/parameters.\n :param parameters: parameters.\n parameters[\"W\" + str(l)] = Wl\n parameters[\"b\" + str(l)] = bl\n :return:\n v -- python dictionary that will contain the exponentially weighted average of the gradient.\n v[\"dW\" + str(l)] = ...\n v[\"db\" + str(l)] = ...\n s -- python dictionary that will contain the exponentially weighted average of the squared gradient.\n s[\"dW\" + str(l)] = ...\n s[\"db\" + str(l)] = ...\n\n \"\"\"\n L = len(parameters) // 2 # number of layers in the neural networks\n v = {}\n s = {}\n\n # Initialize v, s. Input: \"parameters\". Outputs: \"v, s\".\n for l in range(L):\n v[\"dW\" + str(l + 1)] = np.zeros((parameters[\"W\" + str(l + 1)].shape[0], parameters[\"W\" + str(l + 1)].shape[1]))\n v[\"db\" + str(l + 1)] = np.zeros((parameters[\"b\" + str(l + 1)].shape[0], parameters[\"b\" + str(l + 1)].shape[1]))\n s[\"dW\" + str(l + 1)] = np.zeros((parameters[\"W\" + str(l + 1)].shape[0], parameters[\"W\" + str(l + 1)].shape[1]))\n s[\"db\" + str(l + 1)] = np.zeros((parameters[\"b\" + str(l + 1)].shape[0], parameters[\"b\" + str(l + 1)].shape[1]))\n return v, s\n\n\n# GRADED FUNCTION: update_parameters_with_adam\n\ndef update_parameters_with_adam(parameters, grads, v, s, t, learning_rate=0.01, beta1=0.9, beta2=0.999, epsilon=1e-8):\n \"\"\"\n Update parameters using Adam\n :param parameters: parameters:\n parameters['W' + str(l)] = Wl\n parameters['b' + str(l)] = bl\n :param grads: your gradients for each parameters:\n grads['dW' + str(l)] = dWl\n grads['db' + str(l)] = dbl\n :param v: Adam variable, moving average of the first gradient, python dictionary\n :param s: Adam variable, moving average of the squared gradient, python dictionary\n :param t: the learning rate, scalar\n :param learning_rate:\n :param beta1: Exponential decay hyper-parameter for the first moment estimates\n :param beta2: Exponential decay hyper-parameter for the second moment estimates\n :param epsilon: hyper-parameter preventing division by zero in Adam updates\n :return:\n parameters -- python dictionary containing your updated parameters\n v -- Adam variable, moving average of the first gradient, python dictionary\n s -- Adam variable, moving average of the squared gradient, python dictionary\n \"\"\"\n L = len(parameters) // 2 # number of layers in the neural networks\n v_corrected = {} # Initializing first moment estimate, python dictionary\n s_corrected = {} # Initializing second moment estimate, python dictionary\n\n # Perform Adam update on all parameters\n for l in range(L):\n # Moving average of the gradients. Inputs: \"v, grads, beta1\". Output: \"v\".\n v[\"dW\" + str(l + 1)] = beta1 * v[\"dW\" + str(l + 1)] + (1 - beta1) * grads['dW' + str(l + 1)]\n v[\"db\" + str(l + 1)] = beta1 * v[\"db\" + str(l + 1)] + (1 - beta1) * grads['db' + str(l + 1)]\n\n # Compute bias-corrected first moment estimate. Inputs: \"v, beta1, t\". Output: \"v_corrected\".\n v_corrected[\"dW\" + str(l + 1)] = v[\"dW\" + str(l + 1)] / (1 - pow(beta1, t))\n v_corrected[\"db\" + str(l + 1)] = v[\"db\" + str(l + 1)] / (1 - pow(beta1, t))\n\n # Moving average of the squared gradients. Inputs: \"s, grads, beta2\". Output: \"s\".\n s[\"dW\" + str(l + 1)] = beta2 * s[\"dW\" + str(l + 1)] + (1 - beta2) * np.power(grads['dW' + str(l + 1)], 2)\n s[\"db\" + str(l + 1)] = beta2 * s[\"db\" + str(l + 1)] + (1 - beta2) * np.power(grads['db' + str(l + 1)], 2)\n\n # Compute bias-corrected second raw moment estimate. Inputs: \"s, beta2, t\". Output: \"s_corrected\".\n s_corrected[\"dW\" + str(l + 1)] = s[\"dW\" + str(l + 1)] / (1 - pow(beta2, t))\n s_corrected[\"db\" + str(l + 1)] = s[\"db\" + str(l + 1)] / (1 - pow(beta2, t))\n\n # Update parameters. Inputs: \"parameters, learning_rate, v_corrected, s_corrected, epsilon\".\n # Output: \"parameters\".\n parameters[\"W\" + str(l + 1)] = parameters[\"W\" + str(l + 1)] - learning_rate * np.divide(\n v_corrected[\"dW\" + str(l + 1)], np.sqrt(s_corrected[\"dW\" + str(l + 1)]) + epsilon)\n parameters[\"b\" + str(l + 1)] = parameters[\"b\" + str(l + 1)] - learning_rate * np.divide(\n v_corrected[\"db\" + str(l + 1)], np.sqrt(s_corrected[\"db\" + str(l + 1)]) + epsilon)\n return parameters, v, s\n\n\n# You now have three working optimization algorithms (mini-batch gradient descent, Momentum, Adam).\n# Let's implement a model with each of these optimizers and observe the difference.\n\n# ## 5 - Model with different optimization algorithms\n# \n# Lets use the following \"moons\" dataset to test the different optimization methods.\n# (The dataset is named \"moons\" because the data from each of the two classes looks a bit like a crescent-shaped moon.)\n\n\ntrain_X, train_Y = load_dataset()\n\n\n# We have already implemented a 3-layer neural network. You will train it with: \n# - Mini-batch **Gradient Descent**: it will call your function:\n# - `update_parameters_with_gd()`\n# - Mini-batch **Momentum**: it will call your functions:\n# - `initialize_velocity()` and `update_parameters_with_momentum()`\n# - Mini-batch **Adam**: it will call your functions:\n# - `initialize_adam()` and `update_parameters_with_adam()`\n\n\ndef model(matrix_x, y, layers_dims, optimizer, learning_rate=0.0007, mini_batch_size=64, beta=0.9, beta1=0.9,\n beta2=0.999, epsilon=1e-8, num_epochs=10000, print_cost=True):\n \"\"\"\n 3-layer neural network model which can be run in different optimizer modes.\n :param matrix_x: input data, of shape (2, number of examples)\n :param y: true \"label\" vector (1 for blue dot / 0 for red dot), of shape (1, number of examples)\n :param layers_dims: list, containing the size of each layer\n :param optimizer:\n :param learning_rate: the learning rate, scalar.\n :param mini_batch_size: the size of a mini batch\n :param beta: Momentum hyper-parameter\n :param beta1: Exponential decay hyper-parameter for the past gradients estimates\n :param beta2: Exponential decay hyper-parameter for the past squared gradients estimates\n :param epsilon: hyper-parameter preventing division by zero in Adam updates\n :param num_epochs: number of epochs\n :param print_cost: True to print the cost every 1000 epochs\n :return:\n parameters -- python dictionary containing your updated parameters\n \"\"\"\n # L = len(layers_dims) # number of layers in the neural networks\n costs = [] # to keep track of the cost\n t = 0 # initializing the counter required for Adam update\n seed = 10 # For grading purposes, so that your \"random\" mini_batches are the same as ours\n\n # Initialize parameters\n parameters = initialize_parameters(layers_dims)\n v = {}\n s = {}\n # Initialize the optimizer\n if optimizer == \"gd\":\n pass # no initialization required for gradient descent\n elif optimizer == \"momentum\":\n v = initialize_velocity(parameters)\n elif optimizer == \"adam\":\n v, s = initialize_adam(parameters)\n\n # Optimization loop\n for i in range(num_epochs):\n\n # Define the random mini_batches. We increment the seed to reshuffle differently the dataset after each epoch\n seed = seed + 1\n mini_batches = random_mini_batches(matrix_x, y, mini_batch_size, seed)\n\n for mini_batch in mini_batches:\n\n # Select a mini_batch\n (mini_batch_X, mini_batch_Y) = mini_batch\n\n # Forward propagation\n a3, caches = forward_propagation(mini_batch_X, parameters)\n\n # Compute cost\n cost = compute_cost(a3, mini_batch_Y)\n\n # Backward propagation\n grads = backward_propagation(mini_batch_X, mini_batch_Y, caches)\n\n # Update parameters\n if optimizer == \"gd\":\n parameters = update_parameters_with_gd(parameters, grads, learning_rate)\n elif optimizer == \"momentum\":\n parameters, v = update_parameters_with_momentum(parameters, grads, v, beta, learning_rate)\n elif optimizer == \"adam\":\n t = t + 1 # Adam counter\n parameters, v, s = update_parameters_with_adam(parameters, grads, v, s, t, learning_rate, beta1, beta2,\n epsilon)\n\n # Print the cost every 1000 epoch\n if print_cost and i % 1000 == 0:\n print(\"Cost after epoch %i: %f\" % (i, cost))\n if print_cost and i % 100 == 0:\n costs.append(cost)\n\n # plot the cost\n plt.plot(costs)\n plt.ylabel('cost')\n plt.xlabel('epochs (per 100)')\n plt.title(\"Learning rate = \" + str(learning_rate))\n plt.show()\n\n return parameters\n\n\ndef main():\n print('Gradient Descent')\n parameters, grads, learning_rate = update_parameters_with_gd_test_case()\n parameters = update_parameters_with_gd(parameters, grads, learning_rate)\n print(\"W1 = \" + str(parameters[\"W1\"]))\n print(\"b1 = \" + str(parameters[\"b1\"]))\n print(\"W2 = \" + str(parameters[\"W2\"]))\n print(\"b2 = \" + str(parameters[\"b2\"]))\n print(\"Mini Batches\")\n X_assess, Y_assess, mini_batch_size = random_mini_batches_test_case()\n mini_batches = random_mini_batches(X_assess, Y_assess, mini_batch_size)\n print(\"shape of the 1st mini_batch_X: \" + str(mini_batches[0][0].shape))\n print(\"shape of the 2nd mini_batch_X: \" + str(mini_batches[1][0].shape))\n print(\"shape of the 3rd mini_batch_X: \" + str(mini_batches[2][0].shape))\n print(\"shape of the 1st mini_batch_Y: \" + str(mini_batches[0][1].shape))\n print(\"shape of the 2nd mini_batch_Y: \" + str(mini_batches[1][1].shape))\n print(\"shape of the 3rd mini_batch_Y: \" + str(mini_batches[2][1].shape))\n print(\"mini batch sanity check: \" + str(mini_batches[0][0][0][0:3]))\n print(\"initialize_velocity\")\n parameters = initialize_velocity_test_case()\n v = initialize_velocity(parameters)\n print(\"v[\\\"dW1\\\"] = \" + str(v[\"dW1\"]))\n print(\"v[\\\"db1\\\"] = \" + str(v[\"db1\"]))\n print(\"v[\\\"dW2\\\"] = \" + str(v[\"dW2\"]))\n print(\"v[\\\"db2\\\"] = \" + str(v[\"db2\"]))\n print(\"momentum\")\n parameters, grads, v = update_parameters_with_momentum_test_case()\n parameters, v = update_parameters_with_momentum(parameters, grads, v, beta=0.9, learning_rate=0.01)\n print(\"W1 = \" + str(parameters[\"W1\"]))\n print(\"b1 = \" + str(parameters[\"b1\"]))\n print(\"W2 = \" + str(parameters[\"W2\"]))\n print(\"b2 = \" + str(parameters[\"b2\"]))\n print(\"v[\\\"dW1\\\"] = \" + str(v[\"dW1\"]))\n print(\"v[\\\"db1\\\"] = \" + str(v[\"db1\"]))\n print(\"v[\\\"dW2\\\"] = \" + str(v[\"dW2\"]))\n print(\"v[\\\"db2\\\"] = \" + str(v[\"db2\"]))\n print(\"Initialize Adam\")\n parameters = initialize_adam_test_case()\n v, s = initialize_adam(parameters)\n print(\"v[\\\"dW1\\\"] = \" + str(v[\"dW1\"]))\n print(\"v[\\\"db1\\\"] = \" + str(v[\"db1\"]))\n print(\"v[\\\"dW2\\\"] = \" + str(v[\"dW2\"]))\n print(\"v[\\\"db2\\\"] = \" + str(v[\"db2\"]))\n print(\"s[\\\"dW1\\\"] = \" + str(s[\"dW1\"]))\n print(\"s[\\\"db1\\\"] = \" + str(s[\"db1\"]))\n print(\"s[\\\"dW2\\\"] = \" + str(s[\"dW2\"]))\n print(\"s[\\\"db2\\\"] = \" + str(s[\"db2\"]))\n print(\"Adam\")\n parameters, grads, v, s = update_parameters_with_adam_test_case()\n parameters, v, s = update_parameters_with_adam(parameters, grads, v, s, t=2)\n print(\"W1 = \" + str(parameters[\"W1\"]))\n print(\"b1 = \" + str(parameters[\"b1\"]))\n print(\"W2 = \" + str(parameters[\"W2\"]))\n print(\"b2 = \" + str(parameters[\"b2\"]))\n print(\"v[\\\"dW1\\\"] = \" + str(v[\"dW1\"]))\n print(\"v[\\\"db1\\\"] = \" + str(v[\"db1\"]))\n print(\"v[\\\"dW2\\\"] = \" + str(v[\"dW2\"]))\n print(\"v[\\\"db2\\\"] = \" + str(v[\"db2\"]))\n print(\"s[\\\"dW1\\\"] = \" + str(s[\"dW1\"]))\n print(\"s[\\\"db1\\\"] = \" + str(s[\"db1\"]))\n print(\"s[\\\"dW2\\\"] = \" + str(s[\"dW2\"]))\n print(\"s[\\\"db2\\\"] = \" + str(s[\"db2\"]))\n\n\ndef train_with_model():\n # You will now run this 3 layer neural network with each of the 3 optimization methods.\n #\n # ### 5.1 - Mini-batch Gradient descent\n #\n # Run the following code to see how the model does with mini-batch gradient descent.\n # train 3-layer model\n layers_dims = [train_X.shape[0], 5, 2, 1]\n parameters = model(train_X, train_Y, layers_dims, optimizer=\"gd\")\n\n # Predict\n # predictions = predict(train_X, train_Y, parameters)\n predict(train_X, train_Y, parameters)\n\n # Plot decision boundary\n plt.title(\"Model with Gradient Descent optimization\")\n axes = plt.gca()\n axes.set_xlim([-1.5, 2.5])\n axes.set_ylim([-1, 1.5])\n plot_decision_boundary(lambda x: predict_dec(parameters, x.T), train_X, train_Y)\n\n # ### 5.2 - Mini-batch gradient descent with momentum\n #\n # Run the following code to see how the model does with momentum.\n # Because this example is relatively simple, the gains from using momemtum are small;\n # but for more complex problems you might see bigger gains.\n # train 3-layer model\n layers_dims = [train_X.shape[0], 5, 2, 1]\n parameters = model(train_X, train_Y, layers_dims, beta=0.9, optimizer=\"momentum\")\n\n # Predict\n # predictions = predict(train_X, train_Y, parameters)\n predict(train_X, train_Y, parameters)\n\n # Plot decision boundary\n plt.title(\"Model with Momentum optimization\")\n axes = plt.gca()\n axes.set_xlim([-1.5, 2.5])\n axes.set_ylim([-1, 1.5])\n plot_decision_boundary(lambda x: predict_dec(parameters, x.T), train_X, train_Y)\n\n # ### 5.3 - Mini-batch with Adam mode\n #\n # Run the following code to see how the model does with Adam.\n\n # train 3-layer model\n layers_dims = [train_X.shape[0], 5, 2, 1]\n parameters = model(train_X, train_Y, layers_dims, optimizer=\"adam\")\n\n # Predict\n # predictions = predict(train_X, train_Y, parameters)\n predict(train_X, train_Y, parameters)\n\n # Plot decision boundary\n plt.title(\"Model with Adam optimization\")\n axes = plt.gca()\n axes.set_xlim([-1.5, 2.5])\n axes.set_ylim([-1, 1.5])\n plot_decision_boundary(lambda x: predict_dec(parameters, x.T), train_X, train_Y)\n\n\nif __name__ == '__main__':\n main()\n train_with_model()\n\n# ### 5.4 - Summary\n#\n#\n# Momentum usually helps, but given the small learning rate and the simplistic dataset,\n# its impact is almost negligeable.\n# Also, the huge oscillations you see in the cost come from the fact that\n# some mini_batches are more difficult than others for the optimization algorithm.\n#\n# Adam on the other hand, clearly outperforms mini-batch gradient descent and Momentum.\n# If you run the model for more epochs on this simple dataset,\n# all three methods will lead to very good results. However, you've seen that Adam converges a lot faster.\n#\n#\n# Some advantages of Adam include:\n# - Relatively low memory requirements (though higher than gradient descent and gradient descent with momentum) \n# - Usually works well even with little tuning of hyper-parameters (except $\\alpha$)\n\n# **References**:\n# \n# - Adam paper: https://arxiv.org/pdf/1412.6980.pdf\n","sub_path":"COURSERA/Optimization+methods/Optimization+methods.py","file_name":"Optimization+methods.py","file_ext":"py","file_size_in_byte":27079,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"73518383","text":"from .my_base import * # noqa\nfrom store.models import Product\nfrom shared.store.usecases import ProductUsecase\n\n#------ 获取产品一级分类 top----\nfrom store.models import UserCategory\nfrom company.models import Company\n\n#------ 获取产品一级分类 bottom---\ndef get_first_level_cat(event, context):\n \n company_id = context.get_company_id() \n context.log(UserCategory._tree_manager.get_query_set(), 'UserCategory._tree_manager<==')\n my_qs = usercategory_model_list = UserCategory._tree_manager.get_query_set().filter(type='product', company_id=company_id)\n\n usercategory_list = my_qs.values(\n 'id', 'type', 'name', 'level', 'tree_id', 'parent_id', 'order', 'icon2')\n usercategory_map = {uc['id']: uc for uc in usercategory_list}\n\n tree = []\n sub_items_map = {}\n for item in usercategory_list:\n if item['level'] == 0:\n tree.append(item)\n context.log(tree, 'tree')\n return {'data': {'objects': tree}}\n\n\ndef get_all_cat(event, context):\n\n company_id = context.get_company_id() \n context.log(UserCategory._tree_manager.get_query_set(), 'UserCategory._tree_manager<==')\n my_qs = usercategory_model_list = UserCategory._tree_manager.get_query_set().filter(type='product', company_id=company_id)\n usercategory_list = my_qs.values(\n 'id', 'type', 'name', 'level', 'tree_id', 'parent_id', 'order', 'icon2')\n usercategory_map = {uc['id']: uc for uc in usercategory_list}\n \n tree = []\n sub_items_map = {}\n for item in usercategory_list:\n if item['level'] == 0:\n tree.append(item)\n else:\n sub_items_map[item['id']] = item\n tree = sorted(tree, key=lambda x: (x['order'], x['tree_id']))\n\n def _collect_sub_items(item):\n index = []\n sub_items = []\n for k, v in sub_items_map.items():\n if sub_items_map[k]['parent_id'] == item['id']:\n sub_items.append(v)\n index.append(k)\n for k in index:\n sub_items_map.pop(k)\n return sorted(sub_items, key=lambda x: (x['order'], x['tree_id']))\n\n def _loop(items):\n if not sub_items_map:\n return 0\n for item in items:\n item['sub_items'] = _collect_sub_items(item)\n _loop(item['sub_items'])\n\n _loop(tree)\n \n return {'data': {'objects': tree}}\n\ndef handle_my_products(json_list, context):\n \n company_id = context.get_company_id()\n product_usecase = ProductUsecase(company_id=company_id, namespace='default')\n \n for obj_dict in json_list:\n new_product = {}\n product_id = obj_dict['data']['product_id']\n \n try: \n obj_usercase = product_usecase.get(product_id)\n except:\n new_product = None\n obj_dict['data']['product'] = new_product\n continue\n else:\n parent_obj = product_usecase.get(obj_usercase.parent_id) if obj_usercase.parent_id else None\n obj_usercase.image2 = parent_obj.image2 if parent_obj else obj_usercase.image2\n d = obj_usercase.to_json()\n obj_dict['data']['product'] = dict(**d)\n \"\"\"\n for obj_dict in json_list:\n new_product = {}\n product_id = obj_dict['data']['product_id']\n obj = Product.objects.filter(id=product_id).first()\n \n if not obj: # 不存在 obj \n new_product = None\n obj_dict['data']['product'] = new_product\n continue\n else:\n if obj.user_category:\n new_product.update(category_name=obj.user_category.name)\n else:\n new_product.update(category_name=None)\n \n new_product.update(product_name=obj.name)\n # new_product.update(thumbnail=obj.image2)\n new_product.update(product_price=obj.price)\n \n ############################################################################## break 换城continue\n # overview 产品信息走的还是 Product, 不是 usecase, image2 \n obj_usercase = product_usecase.get(product_id)\n parent_obj = product_usecase.get(obj_usercase.parent_id) if obj_usercase.parent_id else None\n obj.image2 = parent_obj.image2 if parent_obj else obj_usercase.image2\n ###########################################################################3\n new_product.update(thumbnail=obj.image2)\n obj_dict['data']['product'] = new_product\n \"\"\"\n # 找不到 new_product 就把 json_list 中删掉\n list(filter(lambda d: d['data']['product'], json_list))\n return json_list\n \n\n \n@is_login\ndef load_my_products(event, context): \n rt = {\n 'data': {}\n }\n siteuser = context.get_siteuser()\n list_obj = context.get_rows('list').filter(data__siteuser_id=siteuser.id).first()\n if not list_obj:\n return {'data': {'status': 'success', 'objects': [], 'meta': {'total_count': 0}}}\n list_obj_uuid = str(list_obj.uuid)\n page_params = event.get('page_params',{})\n page_params['filters'].update(data__list=list_obj_uuid)\n \n\n # 过滤 list_product_relation 的数据\n\n qs_origin = load_items_with_qs(page_params, context)\n\n qs_res = qs_origin.get('qs_res')\n\n json_list = [obj.to_json() for obj in qs_res]\n\n res = handle_my_products(json_list, context)\n\n rt['data'].update(meta=qs_origin.get('meta'))\n rt['data'].update(objects=res)\n rt['data'].update(status='success')\n return rt\n \n \n \n \n \n \n ","sub_path":"fengfeilin/11467/__ccode/my_api.py","file_name":"my_api.py","file_ext":"py","file_size_in_byte":5542,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"481969346","text":"# #字符集\n# import re\n\n# s = 'abc,acc,adc,aec,adfc,ahc,afc'\n# r = re.findall('a[cf]c',s) #提取afc 或acc,普通字符a,c定界,元字符c,f\n# #[]里表示或。[cf] c或f.[cdf] c或d或f [^cfd]取反,不是c和d和f。[c-f]取c到f。\n \n# print(r) \n\n# 概括字符集\n# 只能匹配单一的字符(单个字母,数字)\n# \\d即 [0-9] \\D \n# \\w单词字符 '[A-Za-z0-9]和_ \\W 非单词字符 \n# \\s 空白字符 \\S 非空白字符\n# . 匹配除换行符之外其他所有的字符\n# import re\n# a = 'C0C++7Java12C#9Python67Javascript8\\n\\r &^'\n\n# # r = re.findall('.',a) \n# # print(r)\n# # # #数量词\n\n# r = re.findall('\\w{3}',a)\n# s = re.findall('[A-Za-z]{3}',a)\n# t = re.findall('[A-Za-z]{3,7}',a)\n\n# #贪婪 与 非贪婪\n# #python默认使用贪婪 按最大的匹配\n# u = re.findall('[A-Za-z]{3,7}?',a)#非贪婪 按最小的匹配\n# print(r)\n# print(s)\n# print(t)\n# print(u) \n\n# # * 对*前的字符匹配0次或无限多次\n# # + 对+前的字符匹配1次或无限多次\n# # ? 对?前的字符匹配0次或1次 与贪婪中的?是不同的\n# import re\n# a = 'pytho0python1pythonn2'\n\n# r = re.findall('python*',a)\n# s = re.findall('python+',a)\n# t = re.findall('python?',a)\n# print(r)\n# print(s)\n# print(t)\n\n# #边界匹配\n# import re \n# qq = '100000000001'\n# #4-10位数\n# r = re.findall('^\\d{4,10}$',qq) #^从字符串开头匹配 $从字符串末尾匹配\n# print(r)\n\n\n# #组\n# import re\n# a = 'PythonPythonPythonPythonPythonPython'\n# r = re.findall('(Python){2}',a)\n# print(r)\n\n#匹配模式 #函数中的第三个参数\n#re.I 忽略匹配中的大小写\n#re.S 匹配所有的字符,包括换行符\nimport re\na = 'C0C++7Java12C#\\n9Python67Javascript#8'\nr = re.findall('c#',a,re.I)\nr1 = re.findall('c#.{1}',a,re.I|re.S) # | 且\nprint(r)\nprint(r1)\n\n# #\n#re.sub \nimport re\na = 'C0C++C#7Java12C#\\n9Python6C#7JavascriptC#8'\nr = re.sub('C#','GO',a,0) #无限次替换\ns = re.sub('C#','GO',a,1) #只替换一次\nt = a.replace('C#','GO') #python内置函数\nprint(r)\nprint(s)\nprint(t)","sub_path":"simple/a4正则表达式与json/a43.py","file_name":"a43.py","file_ext":"py","file_size_in_byte":2074,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"238000993","text":"#!/usr/bin/python3\n# -*- encoding: utf-8 -*-\n\nimport json\nimport os\nfrom threading import Thread\nimport time\nfrom utils import cmd_exec\nfrom filelock import FileLock\nfrom config import DELAY_GARBAGE, UPLOAD_FOLDER, MAX_STORE_TIME\n\n\ndef get_top_images(n=10):\n with open(f\"{UPLOAD_FOLDER}/stats.json\", \"r\") as jsonFile:\n stats = json.load(jsonFile)\n count = {}\n for img in stats[\"images\"]:\n count[img] = stats[\"images\"][img][\"count\"]\n top = {k: v for k, v in sorted(count.items(), key=lambda item: item[1])[::-1][:n]}\n return top\n\nwhile True:\n dirs = os.listdir(UPLOAD_FOLDER)\n for d in dirs:\n try:\n d = f\"{UPLOAD_FOLDER}/{d}\"\n if not os.path.isfile(f\"{d}/config.json\"):\n continue\n with FileLock(f\"{d}/config.json.lock\"):\n with open(f\"{d}/config.json\", \"r\") as jsonFile:\n config = json.load(jsonFile)\n\n top = get_top_images()\n if config[\"md5_full\"] in top or \\\n time.time() < (config[\"last_submit_date\"] + MAX_STORE_TIME):\n print(config[\"md5_full\"] in top)\n print(time.time() < (config[\"last_submit_date\"] + MAX_STORE_TIME))\n continue\n else: # Remove if too old / not in top\n cmd_exec(f\"rm -rf {d}\")\n except:\n continue\n time.sleep(DELAY_GARBAGE)\n","sub_path":"backend/garbage_collector.py","file_name":"garbage_collector.py","file_ext":"py","file_size_in_byte":1397,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"596937435","text":"import html\nimport textwrap\nfrom dataclasses import dataclass\n\nfrom mitmproxy import http\nfrom mitmproxy.connection import Connection\nfrom mitmproxy.proxy import commands\nfrom mitmproxy.proxy import events\nfrom mitmproxy.proxy import layer\nfrom mitmproxy.proxy.context import Context\n\nStreamId = int\n\n\n@dataclass\nclass HttpEvent(events.Event):\n # we need stream ids on every event to avoid race conditions\n stream_id: StreamId\n\n\nclass HttpConnection(layer.Layer):\n conn: Connection\n\n def __init__(self, context: Context, conn: Connection):\n super().__init__(context)\n self.conn = conn\n\n\nclass HttpCommand(commands.Command):\n pass\n\n\nclass ReceiveHttp(HttpCommand):\n event: HttpEvent\n\n def __init__(self, event: HttpEvent):\n self.event = event\n\n def __repr__(self) -> str:\n return f\"Receive({self.event})\"\n\n\ndef format_error(status_code: int, message: str) -> bytes:\n reason = http.status_codes.RESPONSES.get(status_code, \"Unknown\")\n return (\n textwrap.dedent(\n f\"\"\"\n \n \n {status_code} {reason} \n \n \n {status_code} {reason} \n {html.escape(message)}
\n \n \n \"\"\"\n )\n .strip()\n .encode(\"utf8\", \"replace\")\n )\n","sub_path":"mitmproxy/proxy/layers/http/_base.py","file_name":"_base.py","file_ext":"py","file_size_in_byte":1310,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"76996134","text":"from flask import Flask, request\nfrom flasgger import Swagger\nfrom flasgger.utils import swag_from\nfrom flask_cors import CORS\nfrom query_dev import Time_Matters_Query\n\n\ndef main():\n \"\"\"The main function for this script.\"\"\"\n app.run(host='127.0.0.1', port=443, debug=True)\n CORS(app)\n\n\napp = Flask(__name__)\napp.config['JSON_SORT_KEYS'] = False\n\napp.config['SWAGGER'] = {\n \"title\": \"Time-Matters-API\",\n \"headers\": [\n ('Access-Control-Allow-Origin', '*'),\n ('Access-Control-Allow-Methods', \"GET, POST, PUT, DELETE, OPTIONS\"),\n ('Access-Control-Allow-Credentials', \"false\"),\n ],\n \"info\": {\n \"title\": \"Time-Matters\",\n \"description\": \"Date extractor that scores the relevance of temporal expressions found within a text (single document) or a set of texts (multiple documents).\",\n \"contact\": {\n \"responsibleOrganization\": \"ME\",\n \"responsibleDeveloper\": \"Me\",\n \"email\": \"me@me.com\",\n \"url\": \"www.me.com\",\n },\n \"termsOfService\": \"http://me.com/terms\",\n \"version\": \"0.0.1\"\n },\n \"schemes\": [\n \"https\",\n \"http\"\n ]\n}\n\nSwagger(app)\n@app.route('/Query/api/v1.0/arquivo.pt', methods=['GET'])\n@swag_from('query.yml')\ndef single_doc_bySentence():\n query_text = str(request.args.get('query_text'))\n num_of_docs = str(request.args.get('num_of_docs'))\n offset = str(request.args.get('offset'))\n search_type = str(request.args.get('search_type'))\n date_extractor = str(request.args.get('date_extractor'))\n\n json_dates = Time_Matters_Query(query_text, num_of_docs, offset, search_type, date_extractor)\n return json_dates\n\n\ndef heroku_set_permissions(heroku=True):\n import imp\n import os\n if heroku:\n path = imp.find_module('py_heideltime')[1]\n full_path = path + \"/Heideltime/TreeTaggerLinux/bin/*\"\n command = 'chmod 111 ' + full_path\n os.popen(command).read()\n\n\nif __name__== '__main__':\n\n main()","sub_path":"Time_Matters_Query/app2.py","file_name":"app2.py","file_ext":"py","file_size_in_byte":1917,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"36242830","text":"import datetime as dt\nimport logging\nimport problembot\n\n\nmodule_logger = logging.getLogger(\"problembot.whenaway\")\n\ndefaulting_channel = problembot.settings[\"module_settings\"][\"whenaway\"][\"defaulting_channel\"]\n\n\ndef debuggable(func):\n def decorated_function(*original_args, **original_kwargs):\n module_logger.debug(\"Entering \" + func.__name__)\n return_value = func(*original_args, **original_kwargs)\n module_logger.debug(\"Exiting \" + func.__name__)\n return return_value\n return decorated_function\n\n\nclass Memoize:\n def __init__(self, func):\n self.__name__ = func.__name__\n self.func = func\n self.expire = dt.datetime.now() + dt.timedelta(hours=1)\n self.cache = {}\n\n def __call__(self, *args):\n if dt.datetime.now() > self.expire:\n # If cache is greater than an hour old, clear it to prevent stale responses, then reset expiry timer\n self.cache = {}\n self.expire = dt.datetime.now() + dt.timedelta(hours=1)\n module_logger.info(\"Clearing the function response cache for %s\", self.func.__name__)\n try:\n return self.cache[args]\n except KeyError:\n self.cache[args] = self.func(*args)\n return self.cache[args]\n\n\n@debuggable\n@Memoize\ndef get_users(slack_channel):\n response = problembot.slack_client.api_call(\"channels.info\", channel=slack_channel)\n # response[\"ok\"] will be False if slack_channel was actually a group, as channels.info cannot check group info\n # In that case, we'll instead move into the groups.info call, which can see that information\n if not response[\"ok\"]:\n response = problembot.slack_client.api_call(\"groups.info\", channel=slack_channel)\n try:\n response[\"group\"][\"members\"].remove(problembot.BOT_ID)\n except ValueError:\n module_logger.warning(\"Unable to remove this bot from list of group users.\")\n module_logger.debug(\"Group members: \" + str(response[\"group\"][\"members\"]))\n return response[\"group\"][\"members\"]\n else:\n try:\n response[\"channel\"][\"members\"].remove(problembot.BOT_ID)\n except ValueError:\n module_logger.warning(\"Unable to remove this bot from list of channel users.\")\n module_logger.debug(\"Channel members: \" + str(response[\"channel\"][\"members\"]))\n return response[\"channel\"][\"members\"]\n\n\n@debuggable\ndef determine_away(slack_user):\n response = problembot.slack_client.api_call(\"users.getPresence\", user=slack_user)\n if response[\"presence\"] == \"away\":\n is_away = True\n else:\n is_away = False\n return is_away\n\n\n@debuggable\ndef post_if_present(text, slack_channel):\n \"\"\"\n \n :param text: The text of the message to be posted \n :param slack_channel: The intended channel\n :return: Boolean, String; Boolean shows whether or not the operation was successful,\n String is the final channel where the posting ended up, regardless of intended channel\n \"\"\"\n users = get_users(slack_channel)\n for user in users:\n if not determine_away(user):\n return problembot.post_message(text, slack_channel), slack_channel\n return problembot.post_message(text, defaulting_channel), defaulting_channel\n","sub_path":"modules/whenaway.py","file_name":"whenaway.py","file_ext":"py","file_size_in_byte":3277,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"549250704","text":"import copy\n\nclass A:\n\tdef __init__(self):\n\t\tself.x=10\n\t\t# self.y=20\n\t\tself.msg = 'msg'\nclass B(A):\n\tdef __init__(self):\n\t\tA.__init__(self)\n\t\tself.y=20\n\n\n\tdef __str__(self):\n\t\treturn 'x : {} y: {}'.format(self.x,self.y)\n\na=A()\nb=B()\nc=b\n# c=copy.deepcopy(b)\n# print(b)\nprint([str(i) for i in [b,c]])\nprint([id(i) for i in [b,c]])\n\nb.y=30\n\nprint('b',b)\nprint('c',c)","sub_path":"designMode/prototype_mode.py","file_name":"prototype_mode.py","file_ext":"py","file_size_in_byte":364,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"480484862","text":"#!/usr/bin/python3\n# -*- encoding:utf-8 -*-\n\nimport i3\nimport subprocess\nimport sys\n\ntable = {\n 'www': ' ',\n 'code': ' ',\n 'term': ' ',\n 'cvs': ' ',\n 'irc': ' ',\n 'music': ' ',\n 'torrent': ' ',\n 'mail': ' ',\n 'all': ' ',\n 'doc': ' '\n}\n\nif __name__ == '__main__':\n\n workspace = [ws for ws in i3.get_workspaces() if ws['focused']][0]\n\n prompt = 'Type new workspace name: 0{0}:'.format(workspace['num'])\n\n dmenu = subprocess.Popen(\n ['/usr/bin/dmenu', '-i', '-p', prompt] + sys.argv[1:],\n stdin=subprocess.PIPE,\n stdout=subprocess.PIPE\n )\n\n name = dmenu.communicate('')[0].decode().rstrip()\n\n if not len(name):\n sys.exit(0)\n\n if name in table:\n name = '{0}{1}'.format(table[name], name)\n else:\n name = '0{0} {1}'.format(workspace['num'], name)\n\n i3.command('rename workspace \"{0}\" to \"{1}:{2}\"'.format(\n workspace['name'],\n workspace['num'],\n name\n ))\n","sub_path":".config/i3/scripts/i3name.py","file_name":"i3name.py","file_ext":"py","file_size_in_byte":1003,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"634883779","text":"#!/usr/bin/env python\n# coding: utf-8\n\n# In[1]:\n\n\nimport numpy as np\nimport pandas as pd\nimport datetime\nimport string\nimport os\nimport re\nalpha = list(string.ascii_lowercase)\n\n\n# # Change the variables in this cell\n\n# In[2]:\n\n\ndate = \"20210118\"\nf5_base_dir = \"/disk1/pore_data\"\nf5_dir = \"MinION_raw_data_%s\" % date\noutput_dir = \"/disk1/pore_data/segmented/peptides\"\n\n\n# In[3]:\n\n\nmin_duration_obs = 10\nsignal_threshold = 0.7\nopen_pore_mean = 220.\nopen_pore_stdv = 35.\n\n\n# In[4]:\n\n\ntry:\n os.makedirs(os.path.join(f5_base_dir, f5_dir))\nexcept OSError:\n pass\n\n\n# In[5]:\n\n\nfor fname in os.listdir(f5_base_dir):\n if date in fname and fname.endswith(\".fast5\"):\n mv_cmd = \"\".join([\"mv \", os.path.join(f5_base_dir, fname), \" \", os.path.join(f5_base_dir, f5_dir)]) + \"/\"\n print(mv_cmd)\n get_ipython().system('{mv_cmd}')\n\n\n# # Functions for reading Google Drive spreadsheet\n\n# MinION experiments are logged on a Google spreadsheet which is read in by the following function. The example spreadsheet can be found here: https://docs.google.com/spreadsheets/d/1hTbtQS8kGk-G4-IIQnp72_jNUSjsEZTQ9N_nbM7DeZA/edit?usp=sharing . To use a different spreadsheet, the `gdrive_key` and `sheet_id` must be updated.\n\n# In[6]:\n\n\ndef import_gdrive_sheet(gdrive_key, sheet_id):\n run_spreadsheet = pd.read_csv(\"https://docs.google.com/spreadsheet/ccc?key=\" + gdrive_key + \"&output=csv&gid=\" + sheet_id)\n run_spreadsheet.Date = pd.to_datetime(run_spreadsheet.Date, format=\"%m_%d_%y\")\n return run_spreadsheet\n\ngdrive_key = \"1hTbtQS8kGk-G4-IIQnp72_jNUSjsEZTQ9N_nbM7DeZA\"\nsheet_id = \"0\"\n\nrun_spreadsheet = import_gdrive_sheet(gdrive_key, sheet_id)\n\n\n# In[7]:\n\n\ndef get_run_info(run_spreadsheet, date_yyyymmdd, runs=None):\n date = datetime.date(int(date_yyyymmdd[:4]), int(date_yyyymmdd[4:6]), int(date_yyyymmdd[6:]))\n all_runs = run_spreadsheet[[\"Date\", \"File name\"]].drop_duplicates()\n runs_on_date_ix = []\n for i, run_date, run_fname in all_runs.itertuples():\n if not isinstance(run_fname, str):\n continue\n fname_search = re.findall(r\"(\\d+)_(\\d+)_(\\d+)_(run_\\d+)\", run_fname)\n if len(fname_search) == 0 or len(fname_search[0]) < 4:\n continue\n m, d, y, run = fname_search[0]\n if len(y) == 2:\n y = \"20\" + y\n fname_date = datetime.date(int(y), int(m), int(d))\n if fname_date == date:\n runs_on_date_ix.append(i)\n runs_on_date = all_runs.loc[runs_on_date_ix]\n runs_on_date[\"Date\"] = date\n \n if runs is not None:\n runs_on_date = runs_on_date[runs_on_date[\"File name\"].isin(runs)]\n \n runs_by_date = {}\n for i in runs_on_date.index:\n start_line = i\n next_ix = list(all_runs.index).index(start_line) + 1\n if next_ix >= len(all_runs.index):\n end_line = run_spreadsheet.index[-1]\n else:\n end_line = list(all_runs.index)[next_ix] - 1\n runs_by_date[runs_on_date.loc[i, \"File name\"]] = run_spreadsheet.loc[start_line:end_line, :]\n\n formatted_coords = {}\n for run, df in runs_by_date.items():\n formatted_coords[run] = []\n for i, coords in enumerate(df.loc[:, [\"start (sec)\", \"end (sec)\"]].iterrows()):\n letter = alpha[i]\n if np.isnan(coords[1][0]):\n continue\n start = int(coords[1][0])\n if np.isnan(coords[1][1]):\n end = start + 100\n else:\n end = int(coords[1][1])\n formatted_coords[run].append({\"name\": letter, \"start\": start, \"end\": end})\n \n return runs_by_date\n\n\n# # Sort runs by flow cell\n\n# In[8]:\n\n\nruns_by_date = get_run_info(run_spreadsheet, date)\n\n\n# In[9]:\n\n\nruns_by_date_df = runs_by_date.values()\nflowcells = []\nfor df in runs_by_date_df:\n if df.iloc[0][\"Flow Cell\"] not in flowcells:\n flowcells.append(df.iloc[0][\"Flow Cell\"])\n\n\n# In[10]:\n\n\nall_f5_files = [x for x in os.listdir(os.path.join(f5_base_dir, f5_dir)) if x.endswith(\".fast5\")]\n\n\n# In[11]:\n\n\nf5_files_by_flowcell = dict.fromkeys(flowcells)\nfor flowcell in flowcells:\n f5_files_by_flowcell[flowcell] = [f5 for f5 in all_f5_files if flowcell in f5]\n\n\n# In[12]:\n\n\nprint(f5_files_by_flowcell)\n\n\n# In[13]:\n\n\nprefixes_by_flowcell = dict.fromkeys(flowcells)\nfor flowcell in flowcells:\n if f5_files_by_flowcell[flowcell]:\n prefixes_by_flowcell[flowcell] = re.findall(r\"(.*_)run_\\d+_\\d+.fast5\", f5_files_by_flowcell[flowcell][0])[0]\n\n\n# In[14]:\n\n\nprint(prefixes_by_flowcell)\n\n\n# # Generate config file(s)\n\n# Separate config files are generated for runs with separate flow cells.\n\n# In[15]:\n\n\nconfig_files_by_flowcell = dict.fromkeys(flowcells)\nfor flowcell in flowcells:\n if f5_files_by_flowcell[flowcell]:\n config_files_by_flowcell[flowcell] = \"configs/segment_%s_%s.yml\" % (date, flowcell)\n\n\n# ## Print example config file(s)\n\n# In[16]:\n\n\nfor flowcell in flowcells:\n if f5_files_by_flowcell[flowcell]:\n print(\"fast5:\")\n print(\" dir: %s/\" % os.path.join(f5_base_dir, f5_dir))\n print(\" prefix: %s\" % prefixes_by_flowcell[flowcell])\n print(\" names:\")\n for run, df in runs_by_date.items(): \n if df.iloc[0][\"Flow Cell\"] != flowcell:\n continue\n run_name = re.findall(r\"run_(\\d+)\", run)[0]\n for f5_fname in f5_files_by_flowcell[flowcell]:\n try:\n if \"run_%s\" % run_name in re.findall(r\"(run_\\d+_\\d+.fast5)\", f5_fname)[0]:\n r = re.findall(r\"(run_\\d+_\\d+.fast5)\", f5_fname)[0]\n print(\" run%s: %s\" % (run_name, r))\n except IndexError:\n pass\n print(\" run_splits:\")\n formatted_coords = {}\n for run, df in runs_by_date.items(): \n if df.iloc[0][\"Flow Cell\"] != flowcell:\n continue\n formatted_coords[run] = [] \n r = re.findall(r\"run_(\\d+)\", run)\n print(\" run%s:\" % r[0])\n mod = 0\n for i, coords in enumerate(df.loc[:, [\"start (sec)\", \"end (sec)\"]].iterrows()):\n letter = alpha[i - mod]\n if np.isnan(coords[1][0]):\n mod += 1\n continue\n else:\n start = int(coords[1][0])\n if np.isnan(coords[1][1]):\n end = start + 100\n else:\n end = int(coords[1][1])\n print(\" - name: %s\" % letter)\n print(\" start: %d\" % start)\n print(\" end: %d\" % end)\n formatted_coords[run].append({\"name\": letter, \"start\": start, \"end\": end})\n print(\"segmentation_params:\")\n print(\" out_prefix: %s\" % os.path.join(output_dir, date))\n print(\" min_duration_obs:\", min_duration_obs)\n print(\" signal_threshold:\", signal_threshold)\n print(\" signal_priors:\")\n print(\" prior_open_pore_mean:\", open_pore_mean)\n print(\" prior_open_pore_std:\", open_pore_stdv)\n\n\n# ## Write to config file(s)\n\n# In[17]:\n\n\nfor flowcell in flowcells:\n if f5_files_by_flowcell[flowcell]:\n with open(config_files_by_flowcell[flowcell], \"w+\") as f:\n f.write(\"fast5:\\n\")\n f.write(\" dir: %s\\n\" % os.path.join(f5_base_dir, f5_dir))\n f.write(\" prefix: %s\\n\" % prefixes_by_flowcell[flowcell])\n f.write(\" names:\\n\")\n for run, df in runs_by_date.items():\n if df.iloc[0][\"Flow Cell\"] != flowcell:\n continue\n run_name = re.findall(r\"run_(\\d+)\", run)[0]\n for f5_fname in f5_files_by_flowcell[flowcell]:\n try:\n if \"run_%s\" % run_name in re.findall(r\"(run_\\d+_\\d+.fast5)\", f5_fname)[0]:\n r = re.findall(r\"(run_\\d+_\\d+.fast5)\", f5_fname)[0]\n f.write(\" run%s: %s\\n\" % (run_name, r))\n except IndexError:\n pass\n f.write(\" run_splits:\\n\")\n formatted_coords = {}\n for run, df in runs_by_date.items():\n if df.iloc[0][\"Flow Cell\"] != flowcell:\n continue\n formatted_coords[run] = [] \n r = re.findall(r\"run_(\\d+)\", run)\n f.write(\" run%s:\\n\" % r[0])\n mod = 0\n for i, coords in enumerate(df.loc[:, [\"start (sec)\", \"end (sec)\"]].iterrows()):\n letter = alpha[i - mod]\n if np.isnan(coords[1][0]):\n mod += 1\n continue\n else:\n start = int(coords[1][0])\n if np.isnan(coords[1][1]):\n end = start + 100\n else:\n end = int(coords[1][1])\n f.write(\" - name: %s\\n\" % letter)\n f.write(\" start: %d\\n\" % start)\n f.write(\" end: %d\\n\" % end)\n formatted_coords[run].append({\"name\": letter, \"start\": start, \"end\": end})\n f.write(\"segmentation_params:\\n\")\n f.write(\" out_prefix: %s\\n\" % os.path.join(output_dir, date))\n f.write(\" min_duration_obs: %d\\n\" % min_duration_obs)\n f.write(\" signal_threshold: %f\\n\" % signal_threshold)\n f.write(\" signal_priors:\\n\")\n f.write(\" prior_open_pore_mean: %f\\n\" % open_pore_mean)\n f.write(\" prior_open_pore_std: %f\\n\" % open_pore_stdv)\n\n\n# # Generate ipython notebook(s)\n\n# Separate ipython notebooks are generated for runs with separate flowcells.\n\n# In[18]:\n\n\nfor flowcell in flowcells:\n if f5_files_by_flowcell[flowcell]:\n template_fname = \"experiment_TEMPLATE.ipynb\"\n notebook_fname = \"experiment_%s_%s.ipynb\" % (date, flowcell)\n with open(template_fname, \"r\") as template_nb:\n lines = template_nb.readlines()\n lines = \"\\n\".join(lines)\n lines = lines.replace(\"INSERT_DATE\", date)\n lines = lines.replace(\"INSERT_FLOWCELL\", flowcell)\n with open(notebook_fname, \"w+\") as nb:\n nb.write(lines)\n\n","sub_path":"nanopore_experiments/prep_experiment_notebook.py","file_name":"prep_experiment_notebook.py","file_ext":"py","file_size_in_byte":10270,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"602982975","text":"import struct\nimport threading\nimport queue\n\nclass Connection(object):\n\t\"\"\"Manages a single socket\"\"\"\n\n\tclass Message(object):\n\t\theader_format = '?ihi'\n\t\theader_length = struct.calcsize(header_format)\n\n\t\tdef __init__(self, id, code, body):\n\t\t\tsuper().__init__()\n\t\t\tself.id = id\n\t\t\tself.code = code\n\t\t\tself.body = body\n\n\t\tdef is_request(self):\n\t\t\treturn isinstance(self, Connection.Request)\n\n\t\tdef is_response(self):\n\t\t\treturn isinstance(self, Connection.Response)\n\n\t\tdef encode(self):\n\t\t\tbody_bytes = self.body.encode('utf-8')\n\t\t\treturn struct.pack('{}{}s'.format(self.header_format, len(body_bytes)), self.is_request(), self.id, len(body_bytes), self.code, body_bytes)\n\n\tclass Request(Message):\n\t\t\"\"\"docstring for Request\"\"\"\n\t\tdef __init__(self, connection, action, body, id = None):\n\n\t\t\tif id is None:\n\t\t\t\tsuper().__init__(connection.requests_registered, connection.guest_protocol.request_code[action], body)\n\t\t\t\tself.action = action\n\t\t\t\tconnection.requests_registered += 1\n\t\t\t\tself.answered = threading.Event()\n\t\t\telse:\n\t\t\t\tsuper().__init__(id, action, body)\n\t\t\t\tself.action = connection.visitor_protocol.action[action]\n\n\t\t\tself.connection = connection\n\t\t\tself.response = None\n\n\t\tdef respond(self, consequence, body = ''):\n\t\t\tself.response = Connection.Response(self, consequence, self.connection.visitor_protocol.response_code[consequence], body)\n\t\t\tself.connection.respond(self.response)\n\n\t\tdef answer(self, code, body):\n\t\t\tself.response = Connection.Response(self, self.connection.guest_protocol.consequence[code], code, body)\n\t\t\tself.answered.set()\n\t\t\treturn self.response\n\n\tclass Response(Message):\n\t\t\"\"\"docstring for Response\"\"\"\n\t\tdef __init__(self, request, consequence, code, body):\n\t\t\tsuper().__init__(request.id, code, body)\n\t\t\tself.request = request\n\t\t\tself.consequence = consequence\n\n\tlisten_length = 4096\n\n\tdef __init__(self, protocol, role, socket):\n\t\tsuper().__init__()\n\t\tself.protocol = protocol\n\t\tself.role = role\n\t\tself.socket = socket\n\n\t\tself.requests_registered = 0\n\t\tself.requests = dict()\n\n\t\tself.inbox = queue.Queue()\n\n\t\tself.data = bytes()\n\t\tself.receiving_request = None\n\t\tself.message_id = None\n\t\tself.message_length = None\n\t\tself.message_code = None\n\n\t@property\n\tdef visitor_protocol(self):\n\t\treturn getattr(self.protocol, self.role)\n\n\t@property\n\tdef guest_protocol(self):\n\t\treturn getattr(self.protocol, 'server' if self.role == 'client' else 'client')\n\n\tdef recv(self):\n\t\t\"\"\"Receives data on socket up to listen_length and then parses messages from it\"\"\"\n\t\tdata = self.socket.recv(self.listen_length)\n\t\tif data:\n\t\t\tself.data += data\n\n\t\t\twhile True:\n\t\t\t\tif self.message_length is None:\n\t\t\t\t\tif len(self.data) >= self.Message.header_length:\n\t\t\t\t\t\tself.receiving_request, self.message_id, self.message_length, self.message_code, self.data = struct.unpack('{}{}s'.format(self.Message.header_format, len(self.data) - self.Message.header_length), self.data)\n\t\t\t\t\telse:\n\t\t\t\t\t\tbreak\n\t\t\t\telse:\n\t\t\t\t\tif len(self.data) >= self.message_length:\n\t\t\t\t\t\tbody, self.data = struct.unpack('{}s{}s'.format(self.message_length, len(self.data) - self.message_length), self.data)\n\n\t\t\t\t\t\tif self.receiving_request:\n\t\t\t\t\t\t\tmessage = self.Request(self, self.message_code, body.decode('utf-8'), self.message_id)\n\t\t\t\t\t\telse:\n\t\t\t\t\t\t\tif self.message_id not in self.requests:\n\t\t\t\t\t\t\t\traise IOError('Response {} unexpected'.format(self.message_id))\n\t\t\t\t\t\t\telse:\n\t\t\t\t\t\t\t\tmessage = self.requests[self.message_id].answer(self.message_code, body.decode('utf-8'))\n\t\t\t\t\t\t\t\tdel self.requests[self.message_id]\n\n\t\t\t\t\t\tself.inbox.put(message)\n\n\t\t\t\t\t\tself.receiving_request = None\n\t\t\t\t\t\tself.message_id = None\n\t\t\t\t\t\tself.message_length = None\n\t\t\t\t\t\tself.message_code = None\n\t\t\t\t\telse:\n\t\t\t\t\t\tbreak\n\t\telse:\n\t\t\traise EOFError('Socket closed')\n\n\tdef request(self, action, body = ''):\n\t\t\"\"\"Creates a request for this connection\"\"\"\n\t\treturn self.Request(self, action, body)\n\n\tdef send(self, message):\n\t\t\"\"\"Sends a message on the socket.\"\"\"\n\t\tif message.is_request():\n\t\t\tif message.id in self.requests:\n\t\t\t\traise IOError('Request {} already sent'.format(id))\n\t\t\telse:\n\t\t\t\tself.requests[message.id] = message\n\n\t\tself.socket.sendall(message.encode())\n\n\tdef respond(self, response):\n\t\t\"\"\"Sends a response, called by message.respond\"\"\"\n\t\traise NotImplementedError()\n\n\tdef close(self):\n\t\tfor request in self.requests.values():\n\t\t\trequest.answered.set()","sub_path":"connection.py","file_name":"connection.py","file_ext":"py","file_size_in_byte":4329,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"651707147","text":"#!/usr/bin/env python\nfrom __future__ import print_function\n\nfrom collections import OrderedDict\nimport yaml\nimport logging\n\nimport instlException\nfrom pyinstl.utils import *\nimport aYaml\nimport svnItem\n\nimport re\n\ncomment_line_re = re.compile(r\"\"\"\n ^\n \\s*\\#\\s*\n (?P.*)\n $\n \"\"\", re.X)\n\nmap_info_extension_to_format = {\"txt\": \"text\", \"text\": \"text\",\n \"inf\": \"info\", \"info\": \"info\",\n \"yml\": \"yaml\", \"yaml\": \"yaml\",\n \"pick\": \"pickle\", \"pickl\": \"pickle\", \"pickle\": \"pickle\",\n \"props\": \"props\", \"prop\": \"props\",\n \"file-sizes\": \"file-sizes\"\n}\n\n\nclass SVNTree(svnItem.SVNTopItem):\n \"\"\" SVNTree inherits from SVNTopItem and adds the functionality\n of reading and writing itself in various text formats:\n info: produced by SVN's info command (read only)\n props: produced by SVN's proplist command (read only)\n text: SVNItem's native format (read and write)\n yaml: yaml... (read and write)\n \"\"\"\n\n def __init__(self):\n \"\"\" Initializes a SVNTree object \"\"\"\n super(SVNTree, self).__init__()\n self.read_func_by_format = {\"info\": self.read_from_svn_info,\n \"text\": self.read_from_text,\n \"yaml\": self.pseudo_read_from_yaml,\n \"props\": self.read_props,\n \"file-sizes\": self.read_file_sizes\n }\n\n self.write_func_by_format = {\"text\": self.write_as_text,\n \"yaml\": self.write_as_yaml,\n }\n self.path_to_file = None\n self.comments = list()\n\n def valid_read_formats(self):\n \"\"\" returns a list of file formats that can be read by SVNTree \"\"\"\n return self.read_func_by_format.keys()\n\n def read_info_map_from_file(self, in_file, a_format=\"guess\"):\n \"\"\" Reads from file. All previous sub items are cleared\n before reading, unless the a_format is 'props' in which case\n the properties are added to existing sub items.\n raises ValueError is a_format is not supported.\n \"\"\"\n self.path_to_file = in_file\n if a_format == \"guess\":\n _, extension = os.path.splitext(self.path_to_file)\n a_format = map_info_extension_to_format[extension[1:]]\n self.comments.append(\"Original file \" + self.path_to_file)\n if a_format in self.read_func_by_format.keys():\n with open_for_read_file_or_url(self.path_to_file) as rfd:\n logging.info(\"%s, a_format: %s\", self.path_to_file, a_format)\n if a_format not in (\"props\", \"file-sizes\"):\n self.clear_subs()\n self.read_func_by_format[a_format](rfd)\n else:\n logging.info(\"%s is not a known map_info a_format. Cannot read %s\", a_format, in_file)\n ValueError(\"Unknown read a_format \" + a_format)\n\n def read_from_svn_info(self, rfd):\n \"\"\" reads new items from svn info items prepared by iter_svn_info \"\"\"\n for item in self.iter_svn_info(rfd):\n self.new_item_at_path(*item)\n\n def read_from_text(self, rfd):\n for line in rfd:\n match = comment_line_re.match(line)\n if match:\n self.comments.append(match.group(\"the_comment\"))\n else:\n self.new_item_from_str(line)\n\n def read_from_yaml(self, rfd):\n try:\n for a_node in yaml.compose_all(rfd):\n self.read_yaml_node(a_node)\n except yaml.YAMLError as ye:\n raise instlException.InstlException(\" \".join((\"YAML error while reading file\", \"'\" + rfd.name + \"':\\n\", str(ye))), ye)\n except IOError as ioe:\n raise instlException.InstlException(\" \".join((\"Failed to read file\", \"'\" + rfd.name + \"'\", \":\")), ioe)\n\n def pseudo_read_from_yaml(self, rfd):\n \"\"\" read from yaml file without the yaml parser - much faster\n but might break is the format changes.\n \"\"\"\n yaml_line_re = re.compile(\"\"\"\n ^\n (?P\\s*)\n (?P[^:]+)\n :\\s\n (?P\n (?P[dfsx]+)\n \\s\n (?P\\d+)\n (\\s\n (?P[\\da-f]+))?\n )?\n $\n \"\"\", re.X)\n try:\n line_num = 0\n indent = -1 # so indent of first line (0) > indent (-1)\n spaces_per_indent = 4\n path_parts = list()\n for line in rfd:\n line_num += 1\n match = yaml_line_re.match(line)\n if match:\n new_indent = len(match.group('indent')) / spaces_per_indent\n if match.group('path') != \"_p_\":\n how_much_to_pop = indent - new_indent + 1\n if how_much_to_pop > 0:\n path_parts = path_parts[0: -how_much_to_pop]\n path_parts.append(match.group('path'))\n if match.group('props'): # it's a file\n # print(((new_indent * spaces_per_indent)-1) * \" \", \"/\".join(path_parts), match.group('props'))\n self.new_item_at_path(path_parts, match.group('flags'), match.group('last_rev'),\n match.group('checksum'))\n indent = new_indent\n else: # previous element was a folder\n # print(((new_indent * spaces_per_indent)-1) * \" \", \"/\".join(path_parts), match.group('props'))\n self.new_item_at_path(path_parts, match.group('flags'), match.group('last_rev'))\n else:\n if indent != -1: # first lines might be empty\n ValueError(\"no match at line \" + str(line_num) + \": \" + line)\n except Exception as unused_ex:\n print(\"exception at line:\", line_num, line)\n raise\n\n def read_props(self, rfd):\n props_line_re = re.compile(\"\"\"\n ^\n (\n Properties\\son\\s\n '\n (?P[^:]+)\n ':\n )\n |\n (\n \\s+\n svn:\n (?P[\\w\\-_]+)\n )\n $\n \"\"\", re.X)\n line_num = 0\n try:\n prop_name_to_char = {'executable': 'x', 'special': 's'}\n item = None\n for line in rfd:\n line_num += 1\n match = props_line_re.match(line)\n if match:\n if match.group('path'):\n # get_item_at_path might return None for invalid paths, mainly '.'\n item = self.get_item_at_path(match.group('path'))\n elif match.group('prop_name'):\n if item is not None:\n prop_name = match.group('prop_name')\n if prop_name in prop_name_to_char:\n item.flags += prop_name_to_char[match.group('prop_name')]\n else:\n if not item.props:\n item.props = list()\n item.props.append(prop_name)\n else:\n ValueError(\"no match at file: \" + rfd.name + \", line: \" + str(line_num) + \": \" + line)\n except Exception as ex:\n print(\"Line:\", line_num, ex)\n raise\n\n def valid_write_formats(self):\n return self.write_func_by_format.keys()\n\n def write_to_file(self, in_file, in_format=\"guess\", comments=True):\n \"\"\" pass in_file=\"stdout\" to output to stdout.\n in_format is either text, yaml, pickle\n \"\"\"\n self.path_to_file = in_file\n if in_format == \"guess\":\n _, extension = os.path.splitext(self.path_to_file)\n in_format = map_info_extension_to_format[extension[1:]]\n if in_format in self.write_func_by_format.keys():\n with write_to_file_or_stdout(self.path_to_file) as wfd:\n logging.info(\"%s, format: %s\", self.path_to_file, in_format)\n self.write_func_by_format[in_format](wfd, comments)\n else:\n logging.info(\"%s is not a known map_info format. Cannot write %s\", in_format, in_file)\n ValueError(\"Unknown write in_format \" + in_format)\n\n def write_as_text(self, wfd, comments=True):\n if comments and len(self.comments) > 0:\n for comment in self.comments:\n wfd.write(\"# \" + comment + \"\\n\")\n wfd.write(\"\\n\")\n for item in self.walk_items():\n wfd.write(str(item) + \"\\n\")\n\n def write_as_yaml(self, wfd, comments=True):\n aYaml.augmentedYaml.writeAsYaml(self, out_stream=wfd, indentor=None, sort=True)\n\n def repr_for_yaml(self):\n \"\"\" writeAsYaml(svni1, out_stream=sys.stdout, indentor=None, sort=True) \"\"\"\n retVal = OrderedDict()\n for sub_name in sorted(self.subs().keys()):\n the_sub = self.subs()[sub_name]\n if the_sub.isDir():\n retVal[the_sub.name] = the_sub.repr_for_yaml()\n else:\n ValueError(\"SVNTree does not support files in the top most directory\")\n return retVal\n\n def iter_svn_info(self, long_info_fd):\n \"\"\" Go over the lines of the output of svn info command\n for each block describing a file or directory, yield\n a tuple formatted as (path, type, last changed revision).\n Where type is 'f' for file or 'd' for directory. \"\"\"\n try:\n svn_info_line_re = re.compile(\"\"\"\n ^\n (?PPath|Last\\ Changed\\ Rev|Node\\ Kind|Revision|Checksum|Tree\\ conflict)\n :\\s*\n (?P.*)\n $\n \"\"\", re.VERBOSE)\n\n def create_info_line_from_record(a_record):\n \"\"\" On rare occasions there is no 'Last Changed Rev' field, just 'Revision'.\n So we use 'Revision' as 'Last Changed Rev'.\n \"\"\"\n revision = a_record.get(\"Last Changed Rev\", None)\n if revision is None:\n revision = a_record.get(\"Revision\", None)\n checksum = a_record.get(\"Checksum\", None)\n return a_record[\"Path\"], short_node_kind[a_record[\"Node Kind\"]], int(revision), checksum\n\n short_node_kind = {\"file\": \"f\", \"directory\": \"d\"}\n record = dict()\n line_num = 0\n for line in long_info_fd:\n line_num += 1\n if line != \"\\n\":\n the_match = svn_info_line_re.match(line)\n if the_match:\n if the_match.group('key') == \"Tree conflict\":\n raise ValueError(\n \" \".join((\"Tree conflict at line\", str(line_num), \"Path:\", record['Path'])))\n record[the_match.group('key')] = the_match.group('rest_of_line')\n else:\n if record and record[\"Path\"] != \".\": # in case there were several empty lines between blocks\n yield create_info_line_from_record(record)\n record.clear()\n if record and record[\"Path\"] != \".\": # in case there was no extra line at the end of file\n yield create_info_line_from_record(record)\n except KeyError as unused_ke:\n print(unused_ke)\n print(\"Error:\", \"line:\", line_num, \"record:\", record)\n raise\n\n def initialize_from_folder(self, in_folder):\n prefix_len = len(in_folder)+1\n for root, dirs, files in os.walk(in_folder, followlinks=False):\n for a_file in files:\n if a_file != \".DS_Store\": # temp hack, list of ignored files should be moved to a variable\n relative_path = os.path.join(root, a_file)[prefix_len:]\n self.new_item_at_path(relative_path, \"f\", 0, checksum=\"0\", create_folders=True)\n\n def read_file_sizes(self, rfd):\n for line in rfd:\n match = comment_line_re.match(line)\n if not match:\n parts = line.rstrip().split(\", \", 2)\n item = self.get_item_at_path(parts[0])\n if item:\n item.size = int(parts[1])\n else:\n print(parts[0], \"was not found\")\n\nclass WtarFilter(object):\n \"\"\" WtarFilter is passed to SVNItem.walk_items_with_filter as the filter parameter\n to match files that end with .wtar, .wtar.aa,...\n \"\"\"\n def __init__(self, base_name):\n # Regex fo find files who's name starts with the source's name and have .wtar or wtar.aa... extension\n # NOT compiled with re.VERBOSE since the file name may contain spaces\n self.wtar_file_re = re.compile(base_name + r\"\"\"\\.wtar(\\...)?$\"\"\")\n\n def __call__(self, file_item):\n match = self.wtar_file_re.match(file_item.name)\n retVal = match is not None\n return retVal\n\nif __name__ == \"__main__\":\n t = SVNTree()\n t.read_svn_info_file(sys.argv[1])\n # for item in t.walk_items():\n # print(str(item))\n","sub_path":"pyinstl/svnTree.py","file_name":"svnTree.py","file_ext":"py","file_size_in_byte":13868,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"331498341","text":"#========================================================\n#\n# Author: AM readygood@163.com\n#\n# Blog: http://www.my-blog.top\n#\n# Last modified: 2019-03-01 22:52\n#\n# Filename: recursion.py\n#\n# Description: V1.0\n#\n#========================================================\n#猴子吃桃循环定义\ndef monkey(n,s=1):\n for _ in range(n-1):\n s = (s + 1) * 2\n return s\nprint(monkey(10))\n#猴子吃桃递归定义\ndef monkey(day):\n if day == 1:\n return 1\n return (monkey(day-1)+1) * 2\nprint(monkey(10))\n#阶乘递归定义\ndef fac(num):\n if num == 1:\n return 1\n return num * fac(num - 1)\nprint(fac(5))\n#阶乘循环定义\ndef fac1(num,s=1):\n for i in range(1,num+1):\n s = s * i\n return s\nprint(fac1(5))\n","sub_path":"P17084_阿孟/a视频中的作业/chapter_02/recursion.py","file_name":"recursion.py","file_ext":"py","file_size_in_byte":748,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"375678026","text":"\"\"\" rule682_1d.py : 2D cellular automaton following rule 682, which\n takes the XOR of the neighbours of each cell.\n\"\"\"\n\nfrom ...ca.base.grid_ca.grid_ca import SquareCA\nfrom ...ca.base.grid_ca.flip_rule import MultiFlipRule\nfrom ...io import state_visualiser, state_filewriter\nfrom ...io.img_utilities import read_img, add_noise\n\nimport numpy as np\n\nimport sys\n\nL = 4\npatterns = [[[0,0,0],\n [0,1,0],\n [0,0,0]],\n [[1,1,1],\n [0,1,1],\n [0,1,1]],\n [[0,1,1],\n [0,0,1],\n [1,1,0]],\n [[1,1,0],\n [0,1,1],\n [1,1,1]],\n [[0,1,0],\n [1,0,0],\n [1,0,0]],\n [[1,0,1],\n [1,0,0],\n [1,1,0]],\n [[0,1,1],\n [0,1,0],\n [1,0,0]],\n [[0,1,1],\n [0,0,1],\n [1,1,1]],\n [[0,1,1],\n [1,0,1],\n [0,0,0]],\n [[1,1,1],\n [1,0,1],\n [1,1,1]]]\nrule = MultiFlipRule(patterns)\n\ntry:\n periodic = not (\"fixed\" in sys.argv[1:])\nexcept IndexError:\n periodic = True\n\nfilename = sys.argv[1]\ninit_values = add_noise(read_img(filename))\nprint_flag = init_values.shape[0] < 10\n\nca = SquareCA(init_values.shape[0], rule,\n init_values=init_values, is_periodic=periodic)\n\ndef run_rule():\n n = 200\n states = ca.states()\n state_visualiser.display_state_sequence(states, console_print=print_flag)\n\nrun_rule()\n","sub_path":"src/examples/ca/multi_flip_rule.py","file_name":"multi_flip_rule.py","file_ext":"py","file_size_in_byte":1516,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"440797697","text":"import argparse\nimport logging\nfrom datetime import datetime\nfrom pathlib import Path\n\nimport os\nimport torch\nimport yaml\nimport numpy as np\n\nfrom libmultilabel import data_utils\nfrom libmultilabel.model import Model\nfrom libmultilabel.utils import ArgDict, Timer, dump_log, save_top_k_predictions\nfrom libmultilabel.evaluate import evaluate\n\n\nlogging.basicConfig(level=logging.INFO, format='%(asctime)s %(levelname)s:%(message)s')\n\n\ndef get_config():\n parser = argparse.ArgumentParser(\n add_help=False,\n description='multi-label learning for text classification')\n\n # load params from config file\n parser.add_argument('-c', '--config', help='Path to configuration file')\n args, _ = parser.parse_known_args()\n config = {}\n if args.config:\n with open(args.config) as fp:\n config = yaml.load(fp, Loader=yaml.SafeLoader)\n\n # path / directory\n parser.add_argument('--data_dir', default='./data/rcv1', help='The directory to load data (default: %(default)s)')\n parser.add_argument('--result_dir', default='./runs', help='The directory to save checkpoints and logs (default: %(default)s)')\n\n # data\n parser.add_argument('--data_name', default='rcv1', help='Dataset name (default: %(default)s)')\n parser.add_argument('--train_path', help='Path to training data (default: [data_dir]/train.txt)')\n parser.add_argument('--val_path', help='Path to validation data (default: [data_dir]/valid.txt)')\n parser.add_argument('--test_path', help='Path to test data (default: [data_dir]/test.txt)')\n parser.add_argument('--val_size', type=float, default=0.2, help='Training-validation split: a ratio in [0, 1] or an integer for the size of the validation set (default: %(default)s).')\n parser.add_argument('--min_vocab_freq', type=int, default=1, help='The minimum frequency needed to include a token in the vocabulary (default: %(default)s)')\n parser.add_argument('--max_seq_length', type=int, default=500, help='The maximum number of tokens of a sample (default: %(default)s)')\n parser.add_argument('--fixed_length', action='store_true', help='Whether to pad all sequence to MAX_SEQ_LENGTH (default: %(default)s)')\n parser.add_argument('--shuffle', type=bool, default=True, help='Whether to shuffle training data before each epoch (default: %(default)s)')\n\n # train\n parser.add_argument('--seed', type=int, help='Random seed (default: %(default)s)')\n parser.add_argument('--epochs', type=int, default=10000, help='Number of epochs to train (default: %(default)s)')\n parser.add_argument('--batch_size', type=int, default=16, help='Size of training batches (default: %(default)s)')\n parser.add_argument('--optimizer', default='adam', choices=['adam', 'sgd'], help='Optimizer: SGD or Adam (default: %(default)s)')\n parser.add_argument('--learning_rate', type=float, default=0.0001, help='Learning rate for optimizer (default: %(default)s)')\n parser.add_argument('--weight_decay', type=float, default=0, help='Weight decay factor (default: %(default)s)')\n parser.add_argument('--momentum', type=float, default=0.9, help='Momentum factor for SGD only (default: %(default)s)')\n parser.add_argument('--patience', type=int, default=5, help='Number of epochs to wait for improvement before early stopping (default: %(default)s)')\n\n # model\n parser.add_argument('--model_name', default='KimCNN',help='Model to be used (default: %(default)s)')\n parser.add_argument('--init_weight', default='kaiming_uniform', help='Weight initialization to be used (default: %(default)s)')\n parser.add_argument('--activation', default='relu', help='Activation function to be used (default: %(default)s)')\n parser.add_argument('--num_filter_per_size', type=int, default=128, help='Number of filters in convolutional layers in each size (default: %(default)s)')\n parser.add_argument('--filter_sizes', type=int, nargs='+', default=[4], help='Size of convolutional filters (default: %(default)s)')\n parser.add_argument('--dropout', type=float, default=0.2, help='Optional specification of dropout (default: %(default)s)')\n parser.add_argument('--dropout2', type=float, default=0.2, help='Optional specification of the second dropout (default: %(default)s)')\n parser.add_argument('--pool_size', type=int, default=2, help='Polling size for dynamic max-pooling (default: %(default)s)')\n\n # eval\n parser.add_argument('--eval_batch_size', type=int, default=256, help='Size of evaluating batches (default: %(default)s)')\n parser.add_argument('--metrics_thresholds', type=float, nargs='+', default=[0.5], help='Thresholds to monitor for metrics (default: %(default)s)')\n parser.add_argument('--monitor_metrics', nargs='+', default=['P@1', 'P@3', 'P@5'], help='Metrics to monitor while validating (default: %(default)s)')\n parser.add_argument('--val_metric', default='P@1', help='The metric to monitor for early stopping (default: %(default)s)')\n\n # pretrained vocab / embeddings\n parser.add_argument('--vocab_file', type=str, help='Path to a file holding vocabuaries (default: %(default)s)')\n parser.add_argument('--embed_file', type=str, help='Path to a file holding pre-trained embeddings (default: %(default)s)')\n parser.add_argument('--label_file', type=str, help='Path to a file holding all labels (default: %(default)s)')\n\n # log\n parser.add_argument('--save_k_predictions', type=int, nargs='?', const=100, default=0, help='Save top k predictions on test set. k=%(const)s if not specified. (default: %(default)s)')\n parser.add_argument('--predict_out_path', help='Path to the an output file holding top 100 label results (default: %(default)s)')\n\n # others\n parser.add_argument('--cpu', action='store_true', help='Disable CUDA')\n parser.add_argument('--data_workers', type=int, default=4, help='Use multi-cpu core for data pre-processing (default: %(default)s)')\n parser.add_argument('--eval', action='store_true', help='Only run evaluation on the test set (default: %(default)s)')\n parser.add_argument('--load_checkpoint', help='The checkpoint to warm-up with (default: %(default)s)')\n parser.add_argument('-h', '--help', action='help')\n\n parser.set_defaults(**config)\n args = parser.parse_args()\n config = ArgDict(vars(args))\n return config\n\n\ndef init_env(config):\n # set a debug environment variable CUBLAS_WORKSPACE_CONFIG to \":16:8\" (may limit overall performance) or \":4096:8\" (will increase library footprint in GPU memory by approximately 24MiB).\n # https://docs.nvidia.com/cuda/cublas/index.html\n os.environ['CUBLAS_WORKSPACE_CONFIG'] = \":4096:8\"\n if config.seed is not None:\n if config.seed >= 0:\n np.random.seed(config.seed)\n torch.manual_seed(config.seed)\n torch.set_deterministic(True)\n torch.backends.cudnn.benchmark = False\n else:\n logging.warning(f'the random seed should be a non-negative integer')\n\n config.device = None\n if not config.cpu and torch.cuda.is_available():\n config.device = torch.device('cuda')\n else:\n config.device = torch.device('cpu')\n # https://github.com/pytorch/pytorch/issues/11201\n torch.multiprocessing.set_sharing_strategy('file_system')\n logging.info(f'Using device: {config.device}')\n\n config.run_name = '{}_{}_{}'.format(\n config.data_name,\n Path(config.config).stem if config.config else config.model_name,\n datetime.now().strftime('%Y%m%d%H%M%S'),\n )\n logging.info(f'Run name: {config.run_name}')\n\n return config\n\n\ndef main():\n config = get_config()\n config = init_env(config)\n datasets = data_utils.load_datasets(config)\n\n if config.eval:\n model = Model.load(config, config.load_checkpoint)\n else:\n if config.load_checkpoint:\n model = Model.load(config, config.load_checkpoint)\n else:\n word_dict = data_utils.load_or_build_text_dict(config, datasets['train'])\n classes = data_utils.load_or_build_label(config, datasets)\n model = Model(config, word_dict, classes)\n model.train(datasets['train'], datasets['val'])\n model.load_best()\n\n if 'test' in datasets:\n test_loader = data_utils.get_dataset_loader(config, datasets['test'], model.word_dict, model.classes, train=False)\n test_metrics = evaluate(model, test_loader, config.monitor_metrics)\n metric_dict = test_metrics.get_metric_dict(use_cache=False)\n dump_log(config=config, metrics=metric_dict, split='test')\n print(test_metrics)\n if config.save_k_predictions > 0:\n if not config.predict_out_path:\n config.predict_out_path = os.path.join(config.result_dir, config.run_name, 'predictions.txt')\n save_top_k_predictions(model.classes, test_metrics.get_y_pred(), config.predict_out_path, config.save_k_predictions)\n\n\nif __name__ == '__main__':\n wall_time = Timer()\n main()\n print(f'Wall time: {wall_time.time():.2f} (s)')\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":9018,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"465486184","text":"from Person import Person\n\n\nclass BabsonPerson(Person):\n next_id = 0 # class attribute\n\n # next ID number to assign\n\n def __init__(self, name):\n # initialize Person attributes\n Person.__init__(self, name)\n # new BabsonPerson attribute: a unique ID number\n self.id = BabsonPerson.next_id\n BabsonPerson.next_id += 1\n\n # sorting Babson people uses their ID number, not name!\n def __lt__(self, other):\n return self.id < other.id\n\n def speak(self, utterance):\n return self.name + \" says: \" + utterance\n\n\ndef main():\n p1 = BabsonPerson('Talal Hussain')\n p2 = BabsonPerson('Muna Salad')\n p3 = BabsonPerson('Abegail Santos')\n p4 = Person('Donald')\n print(p1, p1.id)\n print(p2, p2.id)\n print(p3, p3.id)\n # print(p4, p4.id)\n\n print(p2.speak(\"I feel good today\"))\n\n # print(p4.speak(\"No one knows how I feel today better than me!\"))\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"OOP/inheritance_example/BabsonPerson.py","file_name":"BabsonPerson.py","file_ext":"py","file_size_in_byte":960,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"502149062","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Thu May 24 15:25:07 2018\r\n\r\n@author: achyu\r\n\"\"\"\r\n\r\nimport numpy as np\r\nimport matplotlib.pyplot as plt\r\nimport pandas as pd\r\n#reading csv files\r\ndataset=pd.read_csv('Position_Salaries.csv')\r\nX=dataset.iloc[:,1:2].values\r\ny=dataset.iloc[:,-1].values\r\n#missing data handling\r\n\"\"\"from sklearn.preprocessing import Imputer\r\nimputer=Imputer(missing_values='NaN',strategy='mean',axis=0)\r\nimputer=imputer.fit(X[:,1:3])\r\nX[:,1:3]=imputer.transform(X[:,1:3])\r\n#categorical data encoding\r\nfrom sklearn.preprocessing import LabelEncoder, OneHotEncoder\r\nlabelencoder_x=LabelEncoder()\r\nX[:,0]=labelencoder_x.fit_transform(X[:,0])\r\nonehotencoder=OneHotEncoder(categorical_features=[0])\r\nX=onehotencoder.fit_transform(X).toarray()\r\nlabelencoder_y=LabelEncoder()\r\ny=labelencoder_y.fit_transform(y)\"\"\"\r\n#traing data and testing data\r\n\"\"\"from sklearn.cross_validation import train_test_split\r\nx_train,x_test,y_train,y_test=train_test_split(X,y,test_size=0.2,random_state=0)\"\"\"\r\n#feature scalin\r\n\"\"\"from sklearn.preprocessing import StandardScaler\r\nsc_x=StandardScaler()\r\nx_train=sc_x.fit_transform(x_train)\r\nx_test=sc_x.transform(x_test)\"\"\"\r\n\r\n#fitting regression to data set\r\nfrom sklearn.ensemble import RandomForestRegressor\r\nregressor=RandomForestRegressor(n_estimators=300,random_state=0)\r\nregressor.fit(X,y)\r\n#predicting result\r\ny_pred=regressor.predict(6.5)\r\n\r\n#visualizing regression result\r\nx_grid=np.arange(min(X),max(X)+0.01,0.01)\r\nx_grid=x_grid.reshape(len(x_grid),1)\r\nplt.scatter(X,y,c='r')\r\nplt.plot(x_grid,regressor.predict(x_grid),c='b')\r\nplt.title('Truth or bluff(decision tree)')\r\nplt.xlabel('levels')\r\nplt.ylabel('Salary')\r\nplt.show()\r\n\r\n","sub_path":"random_forest_regression1.py","file_name":"random_forest_regression1.py","file_ext":"py","file_size_in_byte":1681,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"3715729","text":"import warnings\r\nwarnings.filterwarnings(\"ignore\")\r\n\r\n\r\n# In[3]:\r\n\r\n\r\nimport os\r\nimport json\r\nimport datasets\r\nimport torch\r\nimport torch.nn as nn\r\nimport torch.nn.functional as F\r\nimport PIL.Image\r\nimport numpy as np\r\nimport matplotlib.pyplot as plt\r\nfrom scipy.io import loadmat\r\nfrom scipy.misc import imresize\r\n\r\n\r\n# Access PRM through [Nest](https://github.com/ZhouYanzhao/Nest)\r\n\r\n# In[4]:\r\n\r\n\r\nfrom nest import modules, run_tasks\r\n\r\n\r\ndef main():\r\n\tclass_names = modules.pascal_voc_object_categories()\r\n\timage_size = 448\r\n\t# image pre-processor\r\n\ttransformer = modules.image_transform(\r\n\t\timage_size = [image_size, image_size],\r\n\t\taugmentation = dict(),\r\n\t\tmean = [0.485, 0.456, 0.406],\r\n\t\tstd = [0.229, 0.224, 0.225])\r\n\tbackbone = modules.fc_resnet50(num_classes=14, pretrained=False)\r\n\tmodel = modules.peak_response_mapping(backbone)\r\n\t# loaded pre-trained weights\r\n\tmodel = nn.DataParallel(model)\r\n\tstate = torch.load('./snapshots/model_latest.pt')\r\n\tmodel.load_state_dict(state['model'])\r\n\tmodel = model.module.cuda()\r\n\tidx = 1\r\n\traw_img = PIL.Image.open('./data/sample%d.jpg' % idx).convert('RGB')\r\n\tinput_var = transformer(raw_img).unsqueeze(0).cuda().requires_grad_()\r\n\twith open('./data/sample%d.json' % idx, 'r') as f:\r\n\t\tproposals = list(map(modules.rle_decode, json.load(f)))\r\n\r\n\t# plt.savefig('./%d result.jpg' %idx)\r\n\tmodel = model.eval()\r\n\tconfidence = model(input_var)\r\n\tprint('Object categories in the image:')\r\n\tconfidence = model(input_var)\r\n\tfor idx in range(len(class_names)):\r\n\t\tif confidence.data[0, idx] >0:\r\n\t\t\tprint(' [class_idx: %d] %s (%.2f)' % (idx, class_names[idx], confidence[0, idx]))\r\n\r\n\tmodel = model.inference()\r\n\r\n\tvisual_cues = model(input_var)\r\n\tif visual_cues is None:\r\n\t\tprint('No class peak response detected')\r\n\telse:\r\n\t\tconfidence, class_response_maps, class_peak_responses, peak_response_maps = visual_cues\r\n\t\t_, class_idx = torch.max(confidence, dim=1)\r\n\t\tclass_idx = class_idx.item()\r\n\t\tnum_plots = 2 + len(peak_response_maps)\r\n\t\tf, axarr = plt.subplots(1, num_plots, figsize=(num_plots * 4, 4)) #表示一行四列\r\n\t\taxarr[0].imshow(imresize(raw_img, (image_size, image_size), interp='bicubic'))\r\n\t\taxarr[0].set_title('Image')\r\n\t\taxarr[0].axis('off')\r\n\t\taxarr[1].imshow(class_response_maps[0, class_idx].cpu(), interpolation='bicubic')\r\n\t\taxarr[1].set_title('Class Response Map (\"%s\")' % class_names[class_idx])\r\n\t\taxarr[1].axis('off')\r\n\t\tfor idx, (prm, peak) in enumerate(sorted(zip(peak_response_maps, class_peak_responses), key=lambda v: v[-1][-1])):\r\n\t\t\taxarr[idx + 2].imshow(prm.cpu(), cmap=plt.cm.jet)\r\n\t\t\taxarr[idx + 2].set_title('Peak Response Map (\"%s\")' % (class_names[peak[1].item()]))\r\n\t\t\taxarr[idx + 2].axis('off')\r\n\t\tplt.savefig('./test.png')\r\n\tinstance_list = model(input_var, retrieval_cfg=dict(proposals=proposals, param=(0.95, 1e-5, 0.8)))\r\n\r\n\t# visualization\r\n\tif instance_list is None:\r\n\t\tprint('No object detected')\r\n\telse:\r\n\t\t# peak response maps are merged if they select similar proposals\r\n\t\tvis = modules.prm_visualize(instance_list, class_names=class_names)\r\n\t\tf, axarr = plt.subplots(1, 3, figsize=(12, 5))\r\n\t\taxarr[0].imshow(imresize(raw_img, (image_size, image_size), interp='bicubic'))\r\n\t\taxarr[0].set_title('Image')\r\n\t\taxarr[0].axis('off')\r\n\t\taxarr[1].imshow(vis[0])\r\n\t\taxarr[1].set_title('Prediction')\r\n\t\taxarr[1].axis('off')\r\n\t\taxarr[2].imshow(vis[1])\r\n\t\taxarr[2].set_title('Peak Response Maps')\r\n\t\taxarr[2].axis('off')\r\n\t\tplt.savefig('./test2.png')\r\n\t\tplt.show()\r\nif __name__ =='__main__':\r\n main()\r\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":3498,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"205543062","text":"from emoji import emojize\nfrom random import choice\nfrom telegram import ReplyKeyboardMarkup, KeyboardButton\n\nimport settings\n\ndef get_user_emo(user_data):\n if 'emo' in user_data:\n return user_data['emo']\n else:\n user_data['emo'] = emojize(choice(settings.USER_EMOJI), use_aliases=True)\n return user_data['emo']\n\ndef get_keyboard():\n keyboard_botton_contact = KeyboardButton('Прислать контакты', request_contact=True)\n keyboard_botton_location = KeyboardButton('Прислать координаты', request_location=True)\n my_keyboard = ReplyKeyboardMarkup([['Прислать мемас', 'Сменить аватарку'],\n [keyboard_botton_contact, keyboard_botton_location]],\n resize_keyboard=True)\n return my_keyboard\n\ndef calc(operands_list, operator):\n if operator == '+':\n try:\n result = float(operands_list[0]) + float(operands_list[1])\n return result\n except ValueError:\n return None\n if operator == '-':\n try:\n result = float(operands_list[0]) - float(operands_list[1])\n return result\n except ValueError:\n return None\n if operator == '*':\n try:\n result = float(operands_list[0]) * float(operands_list[1])\n return result\n except ValueError:\n return None\n if operator == '/':\n try:\n result = float(operands_list[0]) / float(operands_list[1])\n return result\n except ValueError:\n return None\n except ZeroDivisionError:\n return 'Нельзя делить на ноль'","sub_path":"utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":1724,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"545611862","text":"\"\"\"\nStatistics Computations\n\"\"\"\nimport numpy as np\nimport scipy\n\n\nclass StatisticsManager(object):\n\n def __init__(self):\n self.true_labels = []\n self.predicted_labels = []\n self.prediction_scores = []\n self.training_times = []\n self.statistics = {\n 'accuracy' : (accuracy, self.predicted_labels),\n 'precision': (precision, self.predicted_labels),\n 'recall' : (recall, self.predicted_labels),\n 'auc' : (auc, self.prediction_scores),\n }\n\n def add_fold(self, true_labels, predicted_labels,\n prediction_scores, training_time):\n \"\"\"\n Add a fold of labels and predictions for later statistics computations\n\n @param true_labels : the actual labels\n @param predicted_labels : the predicted binary labels\n @param prediction_scores : the real-valued confidence values\n @param training_time : how long it took to train on the fold\n \"\"\"\n self.true_labels.append(true_labels)\n self.predicted_labels.append(predicted_labels)\n self.prediction_scores.append(prediction_scores)\n self.training_times.append(training_time)\n\n def get_statistic(self, statistic_name, pooled=True):\n \"\"\"\n Get a statistic by name, either pooled across folds or not\n\n @param statistic_name : one of {accuracy, precision, recall, auc}\n @param pooled=True : whether or not to \"pool\" predictions across folds\n @return statistic if pooled, or (avg, std) of statistic across folds\n \"\"\"\n if statistic_name not in self.statistics:\n raise ValueError('\"%s\" not implemented' % statistic_name)\n\n statistic, predictions = self.statistics[statistic_name]\n\n if pooled:\n predictions = np.hstack(map(np.asarray, predictions))\n labels = np.hstack(map(np.asarray, self.true_labels))\n return statistic(labels, predictions)\n else:\n stats = []\n for l, p in zip(self.true_labels, predictions):\n stats.append(statistic(l, p))\n return np.average(stats), np.std(stats)\n\ndef accuracy(labels, predictions):\n count=0.0\n for i in range(len(labels)):\n if labels[i]==predictions[i]:\n count+=1\n return count/len(labels)\n\ndef precision(labels, predictions):\n TP=0.0\n FP=0.0\n for i in range(len(labels)):\n if (labels[i]==1) and (predictions[i]==1):\n TP+=1\n if (labels[i]!=1) and (predictions[i]==1):\n FP+=1\n if TP+FP==0:\n return 0\n else:\n return TP/(TP+FP)\n\ndef recall(labels, predictions):\n TP=0.0\n FN=0.0\n for i in range(len(labels)):\n if (labels[i]==1) and (predictions[i]==1):\n TP+=1\n if (labels[i]!=-1) and (predictions[i]==-1):\n FN+=1\n return TP/(TP+FN)\n\ndef auc(labels, predictions):\n TP_rate = []\n FP_rate = []\n #thresh=0.5\n \n #need to sort the data by result\n results,labels = zip(*sorted(zip(predictions,labels),reverse=True))\n #calculation for AROC\n for thresh in results:\n TP=FP=FN=TN=0.0\n for i in range(len(labels)):\n if results[i]>thresh and labels[i]==1:\n TP+=1\n if results[i]>thresh and labels[i]==-1:\n FP+=1\n if results[i]<=thresh and labels[i]==1:\n FN+=1\n if results[i]<=thresh and labels[i]==-1:\n TN+=1\n if (FP+TN)!=0:\n FP_rate.append(FP/float(FP+TN))\n else:\n FP_rate.append(0.0)\n if (TP+FN)!=0:\n TP_rate.append(TP/float(TP+FN))\n else:\n TP_rate.append(0.0)\n \n #get the last one\n #tp,fn,fp,tn = cont_table(ROC_set,results,results[-1]*.9)\n aroc = 0 \n for p1,p2 in zip(zip(FP_rate[0:-1],TP_rate[0:-1]),zip(FP_rate[1:],TP_rate[1:])):\n aroc += (p2[0]-p1[0])*(p2[1]+p1[1])/2.0 \n \n return aroc\n","sub_path":"PA4_Yingcheng Sun/stats.py","file_name":"stats.py","file_ext":"py","file_size_in_byte":3991,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"653734729","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\n\"\"\"\n@author:knktc\n@contact:me@knktc.com\n@create:2018-08-30 09:05\n\"\"\"\n\n\"\"\"\nWrite a program to check whether a given number is an ugly number.\n\nUgly numbers are positive numbers whose prime factors only include 2, 3, 5.\n\nExample 1:\n\nInput: 6\nOutput: true\nExplanation: 6 = 2 × 3\nExample 2:\n\nInput: 8\nOutput: true\nExplanation: 8 = 2 × 2 × 2\nExample 3:\n\nInput: 14\nOutput: false \nExplanation: 14 is not ugly since it includes another prime factor 7.\nNote:\n\n1 is typically treated as an ugly number.\nInput is within the 32-bit signed integer range: [−231, 231 − 1].\n\n\"\"\"\n\n\"\"\"\n使用递归方法\n\"\"\"\n\n__author__ = 'knktc'\n__version__ = '0.1'\n\n\nclass Solution:\n def isUgly(self, num):\n \"\"\"\n :type num: int\n :rtype: bool\n \"\"\"\n if num < 2:\n return num == 1\n elif num % 2 == 0:\n return self.isUgly(num/2)\n elif num % 3 == 0:\n return self.isUgly(num/3)\n elif num % 5 == 0:\n return self.isUgly(num/5)\n else:\n return False\n\n\ndef main():\n \"\"\"\n main process\n\n \"\"\"\n s = Solution()\n\n test_cases = [\n 1,\n 2,\n 6,\n 8,\n 14\n ]\n for case in test_cases:\n\n print(\"==========\")\n print(\"input: {}\".format(case))\n print(\"output: {}\".format(s.isUgly(num=case)))\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"python/263.Ugly_Number.py","file_name":"263.Ugly_Number.py","file_ext":"py","file_size_in_byte":1424,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"43814976","text":"# -*- encoding: utf-8 -*-\n##############################################################################\n#\n# OpenERP, Open Source Management Solution\n#\n# Copyright (c) 2011-2015 Noviat nv/sa (www.noviat.com).\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 .\n#\n##############################################################################\n\nfrom openerp import models, fields, api, _\n\n\nclass account_invoice(models.Model):\n _inherit = 'account.invoice'\n\n force_encoding = fields.Boolean(\n string='Force Encoding',\n readonly=True, states={'draft': [('readonly', False)]},\n help=\"Accept the encoding of this invoice although \"\n \"it looks like a duplicate.\")\n\n def _get_dup_domain(self):\n \"\"\"\n override this method to customise customer specific\n duplicate check query\n \"\"\"\n return [\n ('type', '=', self.type),\n ('partner_id', '=', self.partner_id.id),\n ('date_invoice', '=', self.date_invoice),\n ('amount_total', '=', self.amount_total),\n ('state', 'in', ['open', 'paid']),\n ('id', '!=', self.id)]\n\n def _get_dup(self):\n \"\"\"\n override this method to customise customer specific\n duplicate check logic\n \"\"\"\n # find duplicates by date, amount\n domain = self._get_dup_domain()\n dups = self.search(domain)\n # check supplier invoice number\n if dups:\n if self.supplier_invoice_number:\n for dup in dups:\n if not dup.supplier_invoice_number \\\n or dup.supplier_invoice_number.lower() == \\\n self.supplier_invoice_number.lower():\n return dup\n return False\n return dups[0]\n return False\n\n @api.one\n @api.constrains('state')\n def _check_si_duplicate(self):\n if self.type == 'in_invoice' and not self.force_encoding \\\n and self.state not in ['draft', 'cancel']:\n dup = self._get_dup()\n if dup:\n raise Warning(_(\n \"This Supplier Invoice has already been encoded !\"\n \"\\nDuplicate Invoice: %s\")\n % dup.internal_number)\n","sub_path":"account_supplier_invoice_check_duplicates/account_invoice.py","file_name":"account_invoice.py","file_ext":"py","file_size_in_byte":2930,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"352658329","text":"import base64\nimport copy\nimport json\nfrom datetime import datetime\nfrom unittest import TestCase\n\nfrom unittest.mock import Mock, patch, ANY, MagicMock\nfrom parameterized import parameterized, param\nfrom werkzeug.datastructures import Headers\nfrom graphql import GraphQLResolveInfo\n\nfrom samcli.lib.providers.provider import GraphQLApi\nfrom samcli.local.appsync.local_appsync_service import LocalAppSyncService, Resolver\nfrom samcli.local.lambdafn.exceptions import FunctionNotFound\n\n\nclass TestApiGatewayService(TestCase):\n def setUp(self):\n self.function_name = Mock()\n self.appsync_resolver = Resolver(function_name=self.function_name, object_type=\"query\", field_name=\"foo_bar\")\n self.api_list_of_resolvers = [self.appsync_resolver]\n\n self.lambda_runner = Mock()\n self.lambda_runner.is_debugging.return_value = False\n\n self.stderr = Mock()\n self.api = GraphQLApi(resolvers=[self.appsync_resolver])\n self.api_service = LocalAppSyncService(\n self.api, self.lambda_runner, port=3000, host=\"127.0.0.1\", stderr=self.stderr\n )\n\n @patch(\"samcli.local.appsync.local_appsync_service.make_executable_schema\")\n @patch(\"samcli.local.appsync.local_appsync_service.load_schema_from_path\")\n @patch(\"samcli.local.appsync.local_appsync_service.Flask\")\n def test_create_creates_flask_app_with_url_rules(self, flask, load_schema_from_path, make_exec_schema):\n app_mock = MagicMock()\n app_mock.config = {}\n flask.return_value = app_mock\n\n self.api_service._construct_error_handling = Mock()\n\n self.api_service.create()\n\n app_mock.add_url_rule.assert_called_once_with(\n \"/graphql\",\n endpoint=\"/graphql\",\n view_func=self.api_service._request_handler,\n methods=[\"GET\", \"POST\"],\n provide_automatic_options=False,\n )\n\n def test_api_initalize_creates_default_values(self):\n self.assertEqual(self.api_service.port, 3000)\n self.assertEqual(self.api_service.host, \"127.0.0.1\")\n self.assertEqual(self.api_service.api.resolvers, self.api_list_of_resolvers)\n self.assertIsNone(self.api_service.static_dir)\n self.assertEqual(self.api_service.lambda_runner, self.lambda_runner)\n\n def test_initalize_with_values(self):\n lambda_runner = Mock()\n local_service = LocalAppSyncService(\n GraphQLApi(), lambda_runner, static_dir=\"dir/static\", port=5000, host=\"129.0.0.0\"\n )\n self.assertEqual(local_service.port, 5000)\n self.assertEqual(local_service.host, \"129.0.0.0\")\n self.assertEqual(local_service.api.resolvers, [])\n self.assertEqual(local_service.static_dir, \"dir/static\")\n self.assertEqual(local_service.lambda_runner, lambda_runner)\n\n @patch.object(LocalAppSyncService, \"_direct_lambda_resolver_event\")\n @patch(\"samcli.local.appsync.local_appsync_service.LambdaOutputParser\")\n def test_generate_resolver_fn(self, lambda_output_parser, direct_lambda_resolver_event):\n test_object = {\"foo\": \"bar\"}\n mock_logs_string = \"some logs\"\n mock_lambda_output_json = json.dumps(test_object)\n lambda_output_parser.get_lambda_output.return_value = (mock_lambda_output_json, mock_logs_string, None)\n\n stderr_mock = Mock()\n lambda_runner = Mock()\n direct_lambda_resolver_event = Mock()\n resolver = Resolver(\"foo\", \"bar\", \"foo_bar_field_name\")\n\n local_service = LocalAppSyncService(GraphQLApi(), lambda_runner, stderr=stderr_mock)\n resolver_fn = local_service._generate_resolver_fn(resolver)\n\n info = MagicMock()\n result = resolver_fn(None, info)\n\n self.assertEqual(result, test_object)\n stderr_mock.write.assert_called_once_with(mock_logs_string)\n\n # def test_request_handles_error_when_invoke_cant_find_function(self, service_error_responses_patch, request_mock):\n # not_found_response_mock = Mock()\n # self.api_service._construct_v_1_0_event = Mock()\n # self.api_service._get_current_route = MagicMock()\n # self.api_service._get_current_route.methods = []\n\n # service_error_responses_patch.lambda_not_found_response.return_value = not_found_response_mock\n\n # self.lambda_runner.invoke.side_effect = FunctionNotFound()\n # request_mock.return_value = (\"test\", \"test\")\n # response = self.api_service._request_handler()\n\n # self.assertEqual(response, not_found_response_mock)\n\n # @patch.object(LocalApigwService, \"get_request_methods_endpoints\")\n # @patch(\"samcli.local.apigw.local_apigw_service.ServiceErrorResponses\")\n # def test_request_handles_error_when_invoke_cant_find_function(self, service_error_responses_patch, request_mock):\n # not_found_response_mock = Mock()\n # self.api_service._construct_v_1_0_event = Mock()\n # self.api_service._get_current_route = MagicMock()\n # self.api_service._get_current_route.methods = []\n\n # service_error_responses_patch.lambda_not_found_response.return_value = not_found_response_mock\n\n # self.lambda_runner.invoke.side_effect = FunctionNotFound()\n # request_mock.return_value = (\"test\", \"test\")\n # response = self.api_service._request_handler()\n\n # self.assertEqual(response, not_found_response_mock)\n\n # @patch.object(LocalApigwService, \"get_request_methods_endpoints\")\n # def test_request_throws_when_invoke_fails(self, request_mock):\n # self.lambda_runner.invoke.side_effect = Exception()\n\n # self.api_service._construct_v_1_0_event = Mock()\n # self.api_service._get_current_route = Mock()\n # request_mock.return_value = (\"test\", \"test\")\n\n # with self.assertRaises(Exception):\n # self.api_service._request_handler()\n\n # @patch.object(LocalApigwService, \"get_request_methods_endpoints\")\n # @patch(\"samcli.local.apigw.local_apigw_service.ServiceErrorResponses\")\n # def test_request_handler_errors_when_parse_lambda_output_raises_keyerror(\n # self, service_error_responses_patch, request_mock\n # ):\n # parse_output_mock = Mock()\n # parse_output_mock.side_effect = LambdaResponseParseException()\n # self.api_service._parse_v1_payload_format_lambda_output = parse_output_mock\n\n # failure_response_mock = Mock()\n\n # service_error_responses_patch.lambda_failure_response.return_value = failure_response_mock\n\n # self.api_service._construct_v_1_0_event = Mock()\n # self.api_service._get_current_route = MagicMock()\n # self.api_service._get_current_route.methods = []\n\n # request_mock.return_value = (\"test\", \"test\")\n # result = self.api_service._request_handler()\n\n # self.assertEqual(result, failure_response_mock)\n\n # @patch(\"samcli.local.apigw.local_apigw_service.ServiceErrorResponses\")\n # def test_request_handler_errors_when_get_current_route_fails(self, service_error_responses_patch):\n # get_current_route = Mock()\n # get_current_route.side_effect = KeyError()\n # self.api_service._get_current_route = get_current_route\n\n # with self.assertRaises(KeyError):\n # self.api_service._request_handler()\n\n # @patch.object(LocalApigwService, \"get_request_methods_endpoints\")\n # @patch(\"samcli.local.apigw.local_apigw_service.ServiceErrorResponses\")\n # def test_request_handler_errors_when_unable_to_read_binary_data(self, service_error_responses_patch, request_mock):\n # _construct_event = Mock()\n # _construct_event.side_effect = UnicodeDecodeError(\"utf8\", b\"obj\", 1, 2, \"reason\")\n # self.api_service._get_current_route = MagicMock()\n # self.api_service._get_current_route.methods = []\n\n # self.api_service._construct_v_1_0_event = _construct_event\n\n # failure_mock = Mock()\n # service_error_responses_patch.lambda_failure_response.return_value = failure_mock\n\n # request_mock.return_value = (\"test\", \"test\")\n # result = self.api_service._request_handler()\n # self.assertEqual(result, failure_mock)\n\n # def test_get_current_route(self):\n # request_mock = Mock()\n # request_mock.return_value.endpoint = \"path\"\n # request_mock.return_value.method = \"method\"\n\n # route_key_method_mock = Mock()\n # route_key_method_mock.return_value = \"method:path\"\n # self.api_service._route_key = route_key_method_mock\n # self.api_service._dict_of_routes = {\"method:path\": \"function\"}\n\n # self.assertEqual(self.api_service._get_current_route(request_mock), \"function\")\n\n # def test_get_current_route_keyerror(self):\n # \"\"\"\n # When the a HTTP request for given method+path combination is allowed by Flask but not in the list of routes,\n # something is messed up. Flask should be configured only from the list of routes.\n # \"\"\"\n\n # request_mock = Mock()\n # request_mock.endpoint = \"path\"\n # request_mock.method = \"method\"\n\n # route_key_method_mock = Mock()\n # route_key_method_mock.return_value = \"method:path\"\n # self.api_service._route_key = route_key_method_mock\n # self.api_service._dict_of_routes = {\"a\": \"b\"}\n\n # with self.assertRaises(KeyError):\n # self.api_service._get_current_route(request_mock)\n\n\nclass TestService_construct_direct_lambda_event(TestCase):\n def setUp(self):\n self.request_mock = Mock()\n self.request_mock.headers = {}\n self.request_mock.get_json.return_value = {\"query\": \"QUERY_DATA_FOO_BAR\"}\n self.info_mock = MagicMock()\n self.info_mock.field_name = \"something\"\n self.info_mock.parent_type.name = \"something else\"\n self.info_mock.variable_values = {}\n\n self.expected_dict = {\n \"arguments\": {},\n \"identity\": {},\n \"info\": {\n \"fieldName\": \"something\",\n \"parentTypeName\": \"something else\",\n \"selectionSetGraphQL\": \"QUERY_DATA_FOO_BAR\",\n \"selectionSetList\": [],\n \"variables\": {},\n },\n \"request\": {\"headers\": {}},\n \"source\": {},\n }\n\n def test_construct_event_no_data(self):\n actual_event_str = LocalAppSyncService._direct_lambda_resolver_event(\n self.request_mock, arguments={}, info=self.info_mock\n )\n actual_event_dict = json.loads(actual_event_str)\n self.assertEqual(actual_event_dict, self.expected_dict)\n\n def test_construct_event_arguments(self):\n arguments = {\n \"foo1\": \"bar1\",\n \"bar2\": \"foo2\",\n }\n actual_event_str = LocalAppSyncService._direct_lambda_resolver_event(\n self.request_mock, arguments=arguments, info=self.info_mock\n )\n actual_event_dict = json.loads(actual_event_str)\n expected = self.expected_dict\n expected[\"arguments\"] = arguments\n self.assertEqual(actual_event_dict, self.expected_dict)\n\n def test_construct_event_selection_list(self):\n info_mock = self.info_mock\n\n field_name_one = MagicMock()\n field_name_one.name.value = \"someField\"\n field_name_two = MagicMock()\n field_name_two.name.value = \"someOtherField\"\n info_mock.field_nodes[0].selection_set.selections = [\n field_name_one,\n field_name_two,\n ]\n\n selection_set = [a for a in info_mock.field_nodes[0].selection_set.selections]\n print(\"Selection set %s\", selection_set)\n\n actual_event_str = LocalAppSyncService._direct_lambda_resolver_event(\n self.request_mock, arguments={}, info=info_mock\n )\n actual_event_dict = json.loads(actual_event_str)\n expected = self.expected_dict\n expected[\"info\"][\"selectionSetList\"] = [\"someField\", \"someOtherField\"]\n self.assertEqual(actual_event_dict, self.expected_dict)\n","sub_path":"tests/unit/local/appsync/test_local_appsync_service.py","file_name":"test_local_appsync_service.py","file_ext":"py","file_size_in_byte":11938,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"376265042","text":"import numpy as np\r\nimport time\r\nimport matplotlib.pyplot as plt\r\n\r\ndef load_label(label_file):\r\n f = open(label_file)\r\n line = f.readlines()\r\n line = [int(item.strip()) for item in line]\r\n sample_num = len(line)\r\n return line, sample_num\r\n\r\ndef load_sample(sample_file, sample_num):\r\n f = open(sample_file)\r\n line = f.readlines()\r\n file_length = int(len(line)) \r\n width = int(len(line[0])) \r\n length = int(file_length/sample_num) \r\n all_image = []\r\n\r\n for i in range(sample_num):\r\n single_image = np.zeros((length,width))\r\n count=0\r\n for j in range(length*i,length*(i+1)): \r\n single_line=line[j]\r\n for k in range(len(single_line)):\r\n if(single_line[k] == \"+\" or single_line[k] == \"#\"):\r\n single_image[count, k] = 1 \r\n count+=1 \r\n all_image.append(single_image) \r\n return all_image\r\n\r\ndef sigmoid(z):\r\n s = 1 / (1 + np.exp(-z)) \r\n return s \r\n\r\ndef model(x_train, y_train, lr = 0.5, iters = 50):\r\n w = np.random.rand(x_train.shape[1], 10)\r\n print('start y_train', y_train.shape)\r\n for iter in range(iters):\r\n error = 0\r\n for i in range(y_train.shape[0]):\r\n temp = np.squeeze(np.dot(x_train[i], w)) \r\n idx_temp = np.argmax(temp) \r\n if( idx_temp != y_train[i]):\r\n w[:,y_train[i]] += lr*x_train[i,y_train[i]]\r\n error += 1\r\n else:\r\n pass\r\n if(error == 0):\r\n break\r\n return w\r\n\r\ndef predict(w, x_test):\r\n temp =np.dot(x_test, w)\r\n y_pred = np.zeros(temp.shape[0])\r\n w = w.reshape(x_test.shape[1],10)\r\n for i in range(x_test.shape[0]): \r\n idx_max = np.argmax(temp[i])\r\n y_pred[i] = idx_max\r\n return y_pred\r\n\r\ndef plot(var, title, color, ylabel):\r\n x = np.arange(0.1, 1.1, 0.1)\r\n plt.plot(x, var, label = 'time', color=color)\r\n plt.xlabel('Percentage of Training Data')\r\n plt.title(title)\r\n plt.ylabel(ylabel)\r\n plt.tight_layout()\r\n plt.show()\r\n\r\ndef process_data(data_file, label_file):\r\n label, sample_num = load_label(label_file)\r\n data = load_sample(data_file, sample_num)\r\n new_data=[]\r\n for i in range(len(data)):\r\n new_data.append(data[i].flatten())\r\n idx = np.random.shuffle(np.arange(int(len(new_data))))\r\n return np.squeeze(np.array(new_data)[idx]), np.squeeze(np.array(label)[idx])\r\n\r\ndef acc(pred, label):\r\n count=0\r\n print(pred.shape,label.shape)\r\n for i in range(pred.shape[0]):\r\n if(pred[i]!=label[i]):\r\n count+=1\r\n acc = count/pred.shape[0]\r\n return acc\r\n\r\ndef main():\r\n train = \"../data/digitdata/trainingimages\"\r\n train_label = \"../data/digitdata/traininglabels\"\r\n test = \"../data/digitdata/testimages\"\r\n test_label = \"../data/digitdata/testlabels\"\r\n x_train, y_train = process_data(train, train_label)\r\n x_test, y_test = process_data(test, test_label)\r\n amount = int(x_train.shape[0]/10)\r\n time_consume = []\r\n test_acc = []\r\n for i in range(10):\r\n start = time.time()\r\n print('amount',amount*(i+1))\r\n w = model(x_train[0:amount*(i+1)],y_train[0:amount*(i+1)])\r\n end = time.time()\r\n y_pred_test = predict(w, x_test)\r\n accuracy = acc(np.squeeze(y_pred_test), y_test)\r\n print(\"test accuracy:{}\".format(accuracy))\r\n time_consume.append(end-start)\r\n test_acc.append(accuracy)\r\n plot(time_consume, title='DigitImage', color='blue', ylabel=\"Time(s)\")\r\n plot(test_acc, title='DigitImage', color='red', ylabel='ACC')\r\nmain()\r\n\r\n\r\n","sub_path":"code/perceptron4digit.py","file_name":"perceptron4digit.py","file_ext":"py","file_size_in_byte":3659,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"101655722","text":"\nfrom django.conf.urls import url, include\nfrom . import views\n\nurlpatterns = [\n url(r'^$', views.index, name='index'),\n url(r'^board/$', views.board, name='board'),\n url(r'^hotels/$', views.hotels, name='hotels'),\n url(r'^keynote/$', views.keynote, name='keynote'),\n url(r'^lotus/$', views.lotus, name='lotus'),\n url(r'^member-schools/$', views.memberSchools, name='memberSchools'),\n #url(r'^osu/$', views.osu, name='osu'),\n url(r'^performers/$', views.performers, name='performers'),\n url(r'^policy/$', views.policy, name='policy'),\n url(r'^schedule/$', views.schedule, name='schedule'),\n url(r'^sponsors/$', views.sponsors, name='sponsors'),\n url(r'^venue/$', views.venue, name='venue'),\n #url(r'^\\.well-known/', views.cert, name='cert'),\n #url(r'^\\.well-known/', include('letsencrypt.urls')),\n #url(r'^wow/', views.cert, name='cert'),\n #url(r'^', views.cert, name='cert'),\n #url(r'^', views.index, name='index'),\n]\n","sub_path":"main/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1038,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"347851875","text":"class Solution:\n def maximalSquare(self, matrix):\n \"\"\"\n :type matrix: List[List[str]]\n :rtype: int\n \"\"\"\n\n #define dp[i][j] the maximal ending at position (i, j).\n\n dp = [[0 for _0 in matrix[0]] for _1 in matrix]\n maxArea = 0\n for i in range(len(matrix)):\n for j in range(len(matrix[0])):\n if i == 0 or j == 0:\n dp[i][j] = int(matrix[i][j])\n elif matrix[i][j] == \"1\":\n dp[i][j] = min(dp[i - 1][j - 1], dp[i - 1][j], dp[i][j - 1]) + 1\n maxArea = max(maxArea, dp[i][j])\n\n\n for i in dp:\n print(i)\n return maxArea * maxArea\n\ns = Solution()\na = [[\"1\",\"0\",\"1\",\"0\",\"0\"],[\"1\",\"0\",\"1\",\"1\",\"1\"],[\"1\",\"1\",\"1\",\"1\",\"1\"],[\"1\",\"0\",\"0\",\"1\",\"0\"]]\nfor i in a:\n print(i)\nprint('--- result ---')\ns.maximalSquare(a)","sub_path":"python/221_maxSqr.py","file_name":"221_maxSqr.py","file_ext":"py","file_size_in_byte":874,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"85710093","text":"from common import config\nfrom service.rabbitmq_thread import get_rabbit_server\nfrom wsgi import start_app\nimport argparse\nimport logging\nimport logging.handlers\n\n\ndef parse_args():\n parser = argparse.ArgumentParser(description=\"CMPE 273 App Deployer Service\")\n parser.add_argument('--config-file', dest='config_file', default='/etc/deployer/deployer.conf')\n parser.add_argument('--paste-ini', dest='paste_file', default='/etc/deployer/deployer-paste.ini')\n return parser.parse_args()\n\n\ndef _configure_logging(conf):\n log_filename = conf.get(\"log\", \"location\")\n root_logger = logging.RootLogger\n handler = logging.handlers.RotatingFileHandler(\n log_filename, maxBytes=1024 * 1024 * 5, backupCount=5)\n formatter = logging.Formatter('%(asctime)s %(name)-12s %(levelname)-8s %(message)s', datefmt='%m-%d %H:%M')\n handler.setFormatter(formatter)\n logging.root.addHandler(handler)\n logging.root.setLevel(logging.DEBUG)\n logging.getLogger(\"pika\").setLevel(logging.WARNING)\n logging.getLogger(\"pika\").propagate = False\n\n\nif __name__ == '__main__':\n parser = parse_args()\n conf = config.get_config(parser.config_file)\n _configure_logging(conf)\n start_app(conf)\n\n","sub_path":"deployer/server/deployer/server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":1212,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"20239163","text":"import functools\nimport itertools\nimport json\nimport logging\nimport re\nimport sys\nimport warnings\nfrom json import JSONEncoder\nfrom operator import mul\nfrom typing import List, Union, Iterable, Tuple, Optional, Dict\n\nimport networkx as nx\nimport numpy as np\nfrom networkx.algorithms.approximation.clique import clique_removal\nfrom functools import reduce\nfrom pyquil import Program\nfrom pyquil.api import QuantumComputer\nfrom pyquil.gates import *\nfrom pyquil.paulis import PauliTerm, sI, is_identity\nfrom math import pi\n\nif sys.version_info < (3, 7):\n from pyquil.external.dataclasses import dataclass\nelse:\n from dataclasses import dataclass\n\nlog = logging.getLogger(__name__)\n\n\n@dataclass(frozen=True)\nclass _OneQState:\n \"\"\"\n A description of a named one-qubit quantum state.\n\n This can be used to generate pre-rotations for quantum process tomography. For example,\n X0_14 will generate the +1 eigenstate of the X operator on qubit 14. X1_14 will generate the\n -1 eigenstate. SIC0_14 will generate the 0th SIC-basis state on qubit 14.\n \"\"\"\n label: str\n index: int\n qubit: int\n\n def __str__(self):\n return f'{self.label}{self.index}_{self.qubit}'\n\n @classmethod\n def from_str(cls, s):\n ma = re.match(r'\\s*(\\w+)(\\d+)_(\\d+)\\s*', s)\n if ma is None:\n raise ValueError(f\"Couldn't parse '{s}'\")\n return _OneQState(\n label=ma.group(1),\n index=int(ma.group(2)),\n qubit=int(ma.group(3)),\n )\n\n\n@dataclass(frozen=True)\nclass TensorProductState:\n \"\"\"\n A description of a multi-qubit quantum state that is a tensor product of many _OneQStates\n states.\n \"\"\"\n states: Tuple[_OneQState]\n\n def __init__(self, states=None):\n if states is None:\n states = tuple()\n object.__setattr__(self, 'states', tuple(states))\n\n def __mul__(self, other):\n return TensorProductState(self.states + other.states)\n\n def __str__(self):\n return ' * '.join(str(s) for s in self.states)\n\n def __repr__(self):\n return f'TensorProductState[{self}]'\n\n def __getitem__(self, qubit):\n \"\"\"Return the _OneQState at the given qubit.\"\"\"\n for oneq_state in self.states:\n if oneq_state.qubit == qubit:\n return oneq_state\n raise IndexError()\n\n def __iter__(self):\n yield from self.states\n\n def __len__(self):\n return len(self.states)\n\n def states_as_set(self):\n return frozenset(self.states)\n\n def __eq__(self, other):\n if not isinstance(other, TensorProductState):\n return False\n\n return self.states_as_set() == other.states_as_set()\n\n def __hash__(self):\n return hash(self.states_as_set())\n\n @classmethod\n def from_str(cls, s):\n if s == '':\n return TensorProductState()\n return TensorProductState(tuple(_OneQState.from_str(x) for x in s.split('*')))\n\n\ndef SIC0(q):\n return TensorProductState((_OneQState('SIC', 0, q),))\n\n\ndef SIC1(q):\n return TensorProductState((_OneQState('SIC', 1, q),))\n\n\ndef SIC2(q):\n return TensorProductState((_OneQState('SIC', 2, q),))\n\n\ndef SIC3(q):\n return TensorProductState((_OneQState('SIC', 3, q),))\n\n\ndef plusX(q):\n return TensorProductState((_OneQState('X', 0, q),))\n\n\ndef minusX(q):\n return TensorProductState((_OneQState('X', 1, q),))\n\n\ndef plusY(q):\n return TensorProductState((_OneQState('Y', 0, q),))\n\n\ndef minusY(q):\n return TensorProductState((_OneQState('Y', 1, q),))\n\n\ndef plusZ(q):\n return TensorProductState((_OneQState('Z', 0, q),))\n\n\ndef minusZ(q):\n return TensorProductState((_OneQState('Z', 1, q),))\n\n\ndef zeros_state(qubits: Iterable[int]):\n return TensorProductState(_OneQState('Z', 0, q) for q in qubits)\n\n\n@dataclass(frozen=True, init=False)\nclass ExperimentSetting:\n \"\"\"\n Input and output settings for a tomography-like experiment.\n\n Many near-term quantum algorithms take the following form:\n\n - Start in a pauli state\n - Prepare some ansatz\n - Measure it w.r.t. pauli operators\n\n Where we typically use a large number of (start, measure) pairs but keep the ansatz preparation\n program consistent. This class represents the (start, measure) pairs. Typically a large\n number of these :py:class:`ExperimentSetting` objects will be created and grouped into\n a :py:class:`TomographyExperiment`.\n \"\"\"\n in_state: TensorProductState\n out_operator: PauliTerm\n\n def __init__(self, in_state: TensorProductState, out_operator: PauliTerm):\n # For backwards compatibility, handle in_state specified by PauliTerm.\n if isinstance(in_state, PauliTerm):\n warnings.warn(\"Please specify in_state as a TensorProductState\",\n DeprecationWarning, stacklevel=2)\n\n if is_identity(in_state):\n in_state = TensorProductState()\n else:\n in_state = TensorProductState([\n _OneQState(label=pauli_label, index=0, qubit=qubit)\n for qubit, pauli_label in in_state._ops.items()\n ])\n\n object.__setattr__(self, 'in_state', in_state)\n object.__setattr__(self, 'out_operator', out_operator)\n\n @property\n def in_operator(self):\n warnings.warn(\"ExperimentSetting.in_operator is deprecated in favor of in_state\",\n stacklevel=2)\n\n # Backwards compat\n pt = sI()\n for oneq_state in self.in_state.states:\n if oneq_state.label not in ['X', 'Y', 'Z']:\n raise ValueError(f\"Can't shim {oneq_state.label} into a pauli term. Use in_state.\")\n if oneq_state.index != 0:\n raise ValueError(f\"Can't shim {oneq_state} into a pauli term. Use in_state.\")\n\n pt *= PauliTerm(op=oneq_state.label, index=oneq_state.qubit)\n\n return pt\n\n def __str__(self):\n return f'{self.in_state}→{self.out_operator.compact_str()}'\n\n def __repr__(self):\n return f'ExperimentSetting[{self}]'\n\n def serializable(self):\n return str(self)\n\n @classmethod\n def from_str(cls, s: str):\n \"\"\"The opposite of str(expt)\"\"\"\n instr, outstr = s.split('→')\n return ExperimentSetting(in_state=TensorProductState.from_str(instr),\n out_operator=PauliTerm.from_compact_str(outstr))\n\n\ndef _abbrev_program(program: Program, max_len=10):\n \"\"\"Create an abbreviated string representation of a Program.\n\n This will join all instructions onto a single line joined by '; '. If the number of\n instructions exceeds ``max_len``, some will be excluded from the string representation.\n \"\"\"\n program_lines = program.out().splitlines()\n if max_len is not None and len(program_lines) > max_len:\n first_n = max_len // 2\n last_n = max_len - first_n\n excluded = len(program_lines) - max_len\n program_lines = (program_lines[:first_n] + [f'... {excluded} instrs not shown ...']\n + program_lines[-last_n:])\n\n return '; '.join(program_lines)\n\n\nclass TomographyExperiment:\n \"\"\"\n A tomography-like experiment.\n\n Many near-term quantum algorithms involve:\n\n - some limited state preparation\n - enacting a quantum process (like in tomography) or preparing a variational ansatz state\n (like in VQE)\n - measuring observables of the state.\n\n Where we typically use a large number of (state_prep, measure) pairs but keep the ansatz\n program consistent. This class stores the ansatz program as a :py:class:`~pyquil.Program`\n and maintains a list of :py:class:`ExperimentSetting` objects which each represent a\n (state_prep, measure) pair.\n\n Settings diagonalized by a shared tensor product basis (TPB) can (optionally) be estimated\n simultaneously. Therefore, this class is backed by a list of list of ExperimentSettings.\n Settings sharing an inner list will be estimated simultaneously. If you don't want this,\n provide a list of length-1-lists. As a convenience, if you pass a 1D list to the constructor\n will expand it to a list of length-1-lists.\n\n This class will not group settings for you. Please see :py:func:`group_experiments` for\n a function that will automatically process a TomographyExperiment to group Experiments sharing\n a TPB.\n \"\"\"\n\n def __init__(self,\n settings: Union[List[ExperimentSetting], List[List[ExperimentSetting]]],\n program: Program,\n qubits: List[int] = None):\n if len(settings) == 0:\n settings = []\n else:\n if isinstance(settings[0], ExperimentSetting):\n # convenience wrapping in lists of length 1\n settings = [[expt] for expt in settings]\n\n self._settings = settings # type: List[List[ExperimentSetting]]\n self.program = program\n if qubits is not None:\n warnings.warn(\"The 'qubits' parameter has been deprecated and will be removed\"\n \"in a future release of pyquil\")\n self.qubits = qubits\n\n def __len__(self):\n return len(self._settings)\n\n def __getitem__(self, item):\n return self._settings[item]\n\n def __setitem__(self, key, value):\n self._settings[key] = value\n\n def __delitem__(self, key):\n self._settings.__delitem__(key)\n\n def __iter__(self):\n yield from self._settings\n\n def __reversed__(self):\n yield from reversed(self._settings)\n\n def __contains__(self, item):\n return item in self._settings\n\n def append(self, expts):\n if not isinstance(expts, list):\n expts = [expts]\n return self._settings.append(expts)\n\n def count(self, expt):\n return self._settings.count(expt)\n\n def index(self, expt, start=None, stop=None):\n return self._settings.index(expt, start, stop)\n\n def extend(self, expts):\n return self._settings.extend(expts)\n\n def insert(self, index, expt):\n return self._settings.insert(index, expt)\n\n def pop(self, index=None):\n return self._settings.pop(index)\n\n def remove(self, expt):\n return self._settings.remove(expt)\n\n def reverse(self):\n return self._settings.reverse()\n\n def sort(self, key=None, reverse=False):\n return self._settings.sort(key, reverse)\n\n def setting_strings(self):\n yield from ('{i}: {st_str}'.format(i=i, st_str=', '.join(str(setting)\n for setting in settings))\n for i, settings in enumerate(self._settings))\n\n def settings_string(self, abbrev_after=None):\n setting_strs = list(self.setting_strings())\n if abbrev_after is not None and len(setting_strs) > abbrev_after:\n first_n = abbrev_after // 2\n last_n = abbrev_after - first_n\n excluded = len(setting_strs) - abbrev_after\n setting_strs = (setting_strs[:first_n] + [f'... {excluded} not shown ...',\n '... use e.settings_string() for all ...']\n + setting_strs[-last_n:])\n return '\\n'.join(setting_strs)\n\n def __str__(self):\n return _abbrev_program(self.program) + '\\n' + self.settings_string(abbrev_after=20)\n\n def serializable(self):\n return {\n 'type': 'TomographyExperiment',\n 'settings': self._settings,\n 'program': self.program.out(),\n }\n\n def __eq__(self, other):\n if not isinstance(other, TomographyExperiment):\n return False\n return self.serializable() == other.serializable()\n\n\nclass OperatorEncoder(JSONEncoder):\n def default(self, o):\n if isinstance(o, ExperimentSetting):\n return o.serializable()\n if isinstance(o, TomographyExperiment):\n return o.serializable()\n if isinstance(o, ExperimentResult):\n return o.serializable()\n return o\n\n\ndef to_json(fn, obj):\n \"\"\"Convenience method to save pyquil.operator_estimation objects as a JSON file.\n\n See :py:func:`read_json`.\n \"\"\"\n with open(fn, 'w') as f:\n json.dump(obj, f, cls=OperatorEncoder, indent=2, ensure_ascii=False)\n return fn\n\n\ndef _operator_object_hook(obj):\n if 'type' in obj and obj['type'] == 'TomographyExperiment':\n return TomographyExperiment([[ExperimentSetting.from_str(s) for s in settings]\n for settings in obj['settings']],\n program=Program(obj['program']))\n return obj\n\n\ndef read_json(fn):\n \"\"\"Convenience method to read pyquil.operator_estimation objects from a JSON file.\n\n See :py:func:`to_json`.\n \"\"\"\n with open(fn) as f:\n return json.load(f, object_hook=_operator_object_hook)\n\n\ndef _one_q_sic_prep(index, qubit):\n \"\"\"Prepare the index-th SIC basis state.\"\"\"\n if index == 0:\n return Program()\n\n theta = 2 * np.arccos(1 / np.sqrt(3))\n zx_plane_rotation = Program([\n RX(-pi / 2, qubit),\n RZ(theta - pi, qubit),\n RX(-pi / 2, qubit),\n ])\n\n if index == 1:\n return zx_plane_rotation\n\n elif index == 2:\n return zx_plane_rotation + RZ(-2 * pi / 3, qubit)\n\n elif index == 3:\n return zx_plane_rotation + RZ(2 * pi / 3, qubit)\n\n raise ValueError(f'Bad SIC index: {index}')\n\n\ndef _one_q_pauli_prep(label, index, qubit):\n \"\"\"Prepare the index-th eigenstate of the pauli operator given by label.\"\"\"\n if index not in [0, 1]:\n raise ValueError(f'Bad Pauli index: {index}')\n\n if label == 'X':\n if index == 0:\n return Program(RY(pi / 2, qubit))\n else:\n return Program(RY(-pi / 2, qubit))\n\n elif label == 'Y':\n if index == 0:\n return Program(RX(-pi / 2, qubit))\n else:\n return Program(RX(pi / 2, qubit))\n\n elif label == 'Z':\n if index == 0:\n return Program()\n else:\n return Program(RX(pi, qubit))\n\n raise ValueError(f'Bad Pauli label: {label}')\n\n\ndef _one_q_state_prep(oneq_state: _OneQState):\n \"\"\"Prepare a one qubit state.\n\n Either SIC[0-3], X[0-1], Y[0-1], or Z[0-1].\n \"\"\"\n label = oneq_state.label\n if label == 'SIC':\n return _one_q_sic_prep(oneq_state.index, oneq_state.qubit)\n elif label in ['X', 'Y', 'Z']:\n return _one_q_pauli_prep(label, oneq_state.index, oneq_state.qubit)\n else:\n raise ValueError(f\"Bad state label: {label}\")\n\n\ndef _local_pauli_eig_meas(op, idx):\n \"\"\"\n Generate gate sequence to measure in the eigenbasis of a Pauli operator, assuming\n we are only able to measure in the Z eigenbasis. (Note: The unitary operations of this\n Program are essentially the Hermitian conjugates of those in :py:func:`_one_q_pauli_prep`)\n\n \"\"\"\n if op == 'X':\n return Program(RY(-pi / 2, idx))\n elif op == 'Y':\n return Program(RX(pi / 2, idx))\n elif op == 'Z':\n return Program()\n raise ValueError(f'Unknown operation {op}')\n\n\ndef construct_tpb_graph(experiments: TomographyExperiment):\n \"\"\"\n Construct a graph where an edge signifies two experiments are diagonal in a TPB.\n \"\"\"\n g = nx.Graph()\n for expt in experiments:\n assert len(expt) == 1, 'already grouped?'\n expt = expt[0]\n\n if expt not in g:\n g.add_node(expt, count=1)\n else:\n g.nodes[expt]['count'] += 1\n\n for expt1, expt2 in itertools.combinations(experiments, r=2):\n expt1 = expt1[0]\n expt2 = expt2[0]\n\n if expt1 == expt2:\n continue\n\n max_weight_in = _max_weight_state([expt1.in_state, expt2.in_state])\n max_weight_out = _max_weight_operator([expt1.out_operator, expt2.out_operator])\n if max_weight_in is not None and max_weight_out is not None:\n g.add_edge(expt1, expt2)\n\n return g\n\n\ndef group_experiments_clique_removal(experiments: TomographyExperiment) -> TomographyExperiment:\n \"\"\"\n Group experiments that are diagonal in a shared tensor product basis (TPB) to minimize number\n of QPU runs, using a graph clique removal algorithm.\n\n :param experiments: a tomography experiment\n :return: a tomography experiment with all the same settings, just grouped according to shared\n TPBs.\n \"\"\"\n g = construct_tpb_graph(experiments)\n _, cliqs = clique_removal(g)\n new_cliqs = []\n for cliq in cliqs:\n new_cliq = []\n for expt in cliq:\n # duplicate `count` times\n new_cliq += [expt] * g.nodes[expt]['count']\n\n new_cliqs += [new_cliq]\n\n return TomographyExperiment(new_cliqs, program=experiments.program)\n\n\ndef _max_weight_operator(ops: Iterable[PauliTerm]) -> Union[None, PauliTerm]:\n \"\"\"Construct a PauliTerm operator by taking the non-identity single-qubit operator at each\n qubit position.\n\n This function will return ``None`` if the input operators do not share a natural tensor\n product basis.\n\n For example, the max_weight_operator of [\"XI\", \"IZ\"] is \"XZ\". Asking for the max weight\n operator of something like [\"XI\", \"ZI\"] will return None.\n \"\"\"\n mapping = dict() # type: Dict[int, str]\n for op in ops:\n for idx, op_str in op:\n if idx in mapping:\n if mapping[idx] != op_str:\n return None\n else:\n mapping[idx] = op_str\n op = functools.reduce(mul, (PauliTerm(op, q) for q, op in mapping.items()), sI())\n return op\n\n\ndef _max_weight_state(states: Iterable[TensorProductState]) -> Union[None, TensorProductState]:\n \"\"\"Construct a TensorProductState by taking the single-qubit state at each\n qubit position.\n\n This function will return ``None`` if the input states are not compatible\n\n For example, the max_weight_state of [\"(+X, q0)\", \"(-Z, q1)\"] is \"(+X, q0; -Z q1)\". Asking for\n the max weight state of something like [\"(+X, q0)\", \"(+Z, q0)\"] will return None.\n \"\"\"\n mapping = dict() # type: Dict[int, _OneQState]\n for state in states:\n for oneq_state in state.states:\n if oneq_state.qubit in mapping:\n if mapping[oneq_state.qubit] != oneq_state:\n return None\n else:\n mapping[oneq_state.qubit] = oneq_state\n return TensorProductState(list(mapping.values()))\n\n\ndef _max_tpb_overlap(tomo_expt: TomographyExperiment):\n \"\"\"\n Given an input TomographyExperiment, provide a dictionary indicating which ExperimentSettings\n share a tensor product basis\n\n :param tomo_expt: TomographyExperiment, from which to group ExperimentSettings that share a tpb\n and can be run together\n :return: dictionary keyed with ExperimentSetting (specifying a tpb), and with each value being a\n list of ExperimentSettings (diagonal in that tpb)\n \"\"\"\n # initialize empty dictionary\n diagonal_sets = {}\n # loop through ExperimentSettings of the TomographyExperiment\n for expt_setting in tomo_expt:\n # no need to group already grouped TomographyExperiment\n assert len(expt_setting) == 1, 'already grouped?'\n expt_setting = expt_setting[0]\n # calculate max overlap of expt_setting with keys of diagonal_sets\n # keep track of whether a shared tpb was found\n found_tpb = False\n # loop through dict items\n for es, es_list in diagonal_sets.items():\n trial_es_list = es_list + [expt_setting]\n diag_in_term = _max_weight_state(expst.in_state for expst in trial_es_list)\n diag_out_term = _max_weight_operator(expst.out_operator for expst in trial_es_list)\n # max_weight_xxx returns None if the set of xxx's don't share a TPB, so the following\n # conditional is True if expt_setting can be inserted into the current es_list.\n if diag_in_term is not None and diag_out_term is not None:\n found_tpb = True\n assert len(diag_in_term) >= len(es.in_state), \\\n \"Highest weight in-state can't be smaller than the given in-state\"\n assert len(diag_out_term) >= len(es.out_operator), \\\n \"Highest weight out-PauliTerm can't be smaller than the given out-PauliTerm\"\n\n # update the diagonalizing basis (key of dict) if necessary\n if len(diag_in_term) > len(es.in_state) or len(diag_out_term) > len(es.out_operator):\n del diagonal_sets[es]\n new_es = ExperimentSetting(diag_in_term, diag_out_term)\n diagonal_sets[new_es] = trial_es_list\n else:\n diagonal_sets[es] = trial_es_list\n break\n\n if not found_tpb:\n # made it through entire dict without finding any ExperimentSetting with shared tpb,\n # so need to make a new item\n diagonal_sets[expt_setting] = [expt_setting]\n\n return diagonal_sets\n\n\ndef group_experiments_greedy(tomo_expt: TomographyExperiment):\n \"\"\"\n Greedy method to group ExperimentSettings in a given TomographyExperiment\n\n :param tomo_expt: TomographyExperiment to group ExperimentSettings within\n :return: TomographyExperiment, with grouped ExperimentSettings according to whether\n it consists of PauliTerms diagonal in the same tensor product basis\n \"\"\"\n diag_sets = _max_tpb_overlap(tomo_expt)\n grouped_expt_settings_list = list(diag_sets.values())\n grouped_tomo_expt = TomographyExperiment(grouped_expt_settings_list, program=tomo_expt.program)\n return grouped_tomo_expt\n\n\ndef group_experiments(experiments: TomographyExperiment,\n method: str = 'greedy') -> TomographyExperiment:\n \"\"\"\n Group experiments that are diagonal in a shared tensor product basis (TPB) to minimize number\n of QPU runs.\n\n .. rubric:: Background\n\n Given some PauliTerm operator, the 'natural' tensor product basis to\n diagonalize this term is the one which diagonalizes each Pauli operator in the\n product term-by-term.\n\n For example, X(1) * Z(0) would be diagonal in the 'natural' tensor product basis\n ``{(|0> +/- |1>)/Sqrt[2]} * {|0>, |1>}``, whereas Z(1) * X(0) would be diagonal\n in the 'natural' tpb ``{|0>, |1>} * {(|0> +/- |1>)/Sqrt[2]}``. The two operators\n commute but are not diagonal in each others 'natural' tpb (in fact, they are\n anti-diagonal in each others 'natural' tpb). This function tests whether two\n operators given as PauliTerms are both diagonal in each others 'natural' tpb.\n\n Note that for the given example of X(1) * Z(0) and Z(1) * X(0), we can construct\n the following basis which simultaneously diagonalizes both operators::\n\n -- |0>' = |0> (|+>) + |1> (|->)\n -- |1>' = |0> (|+>) - |1> (|->)\n -- |2>' = |0> (|->) + |1> (|+>)\n -- |3>' = |0> (-|->) + |1> (|+>)\n\n In this basis, X Z looks like diag(1, -1, 1, -1), and Z X looks like diag(1, 1, -1, -1).\n Notice however that this basis cannot be constructed with single-qubit operations, as each\n of the basis vectors are entangled states.\n\n\n .. rubric:: Methods\n\n The \"greedy\" method will keep a running set of 'buckets' into which grouped ExperimentSettings\n will be placed. Each new ExperimentSetting considered is assigned to the first applicable\n bucket and a new bucket is created if there are no applicable buckets.\n\n The \"clique-removal\" method maps the term grouping problem onto Max Clique graph problem.\n This method constructs a NetworkX graph where an edge exists between two settings that\n share an nTPB and then uses networkx's algorithm for clique removal. This method can give\n you marginally better groupings in certain circumstances, but constructing the\n graph is pretty slow so \"greedy\" is the default.\n\n :param experiments: a tomography experiment\n :param method: method used for grouping; the allowed methods are one of\n ['greedy', 'clique-removal']\n :return: a tomography experiment with all the same settings, just grouped according to shared\n TPBs.\n \"\"\"\n allowed_methods = ['greedy', 'clique-removal']\n assert method in allowed_methods, f\"'method' should be one of {allowed_methods}.\"\n if method == 'greedy':\n return group_experiments_greedy(experiments)\n elif method == 'clique-removal':\n return group_experiments_clique_removal(experiments)\n\n\n@dataclass(frozen=True)\nclass ExperimentResult:\n \"\"\"An expectation and standard deviation for the measurement of one experiment setting\n in a tomographic experiment.\n\n In the case of readout error calibration, we also include\n expectation, standard deviation and count for the calibration results, as well as the\n expectation and standard deviation for the corrected results.\n \"\"\"\n\n setting: ExperimentSetting\n expectation: Union[float, complex]\n total_counts: int\n std_err: Union[float, complex] = None\n raw_expectation: Union[float, complex] = None\n raw_std_err: float = None\n calibration_expectation: Union[float, complex] = None\n calibration_std_err: Union[float, complex] = None\n calibration_counts: int = None\n\n def __init__(self, setting: ExperimentSetting,\n expectation: Union[float, complex],\n total_counts: int,\n stddev: Union[float, complex] = None,\n std_err: Union[float, complex] = None,\n raw_expectation: Union[float, complex] = None,\n raw_stddev: float = None,\n raw_std_err: float = None,\n calibration_expectation: Union[float, complex] = None,\n calibration_stddev: Union[float, complex] = None,\n calibration_std_err: Union[float, complex] = None,\n calibration_counts: int = None):\n\n object.__setattr__(self, 'setting', setting)\n object.__setattr__(self, 'expectation', expectation)\n object.__setattr__(self, 'total_counts', total_counts)\n object.__setattr__(self, 'raw_expectation', raw_expectation)\n object.__setattr__(self, 'calibration_expectation', calibration_expectation)\n object.__setattr__(self, 'calibration_counts', calibration_counts)\n\n if stddev is not None:\n warnings.warn(\"'stddev' has been renamed to 'std_err'\")\n std_err = stddev\n object.__setattr__(self, 'std_err', std_err)\n\n if raw_stddev is not None:\n warnings.warn(\"'raw_stddev' has been renamed to 'raw_std_err'\")\n raw_std_err = raw_stddev\n object.__setattr__(self, 'raw_std_err', raw_std_err)\n\n if calibration_stddev is not None:\n warnings.warn(\"'calibration_stddev' has been renamed to 'calibration_std_err'\")\n calibration_std_err = calibration_stddev\n object.__setattr__(self, 'calibration_std_err', calibration_std_err)\n\n def get_stddev(self) -> Union[float, complex]:\n warnings.warn(\"'stddev' has been renamed to 'std_err'\")\n return self.std_err\n\n def set_stddev(self, value: Union[float, complex]):\n warnings.warn(\"'stddev' has been renamed to 'std_err'\")\n object.__setattr__(self, 'std_err', value)\n\n stddev = property(get_stddev, set_stddev)\n\n def get_raw_stddev(self) -> float:\n warnings.warn(\"'raw_stddev' has been renamed to 'raw_std_err'\")\n return self.raw_std_err\n\n def set_raw_stddev(self, value: float):\n warnings.warn(\"'raw_stddev' has been renamed to 'raw_std_err'\")\n object.__setattr__(self, 'raw_std_err', value)\n\n raw_stddev = property(get_raw_stddev, set_raw_stddev)\n\n def get_calibration_stddev(self) -> Union[float, complex]:\n warnings.warn(\"'calibration_stddev' has been renamed to 'calibration_std_err'\")\n return self.calibration_std_err\n\n def set_calibration_stddev(self, value: Union[float, complex]):\n warnings.warn(\"'calibration_stddev' has been renamed to 'calibration_std_err'\")\n object.__setattr__(self, 'calibration_std_err', value)\n\n calibration_stddev = property(get_calibration_stddev, set_calibration_stddev)\n\n def __str__(self):\n return f'{self.setting}: {self.expectation} +- {self.std_err}'\n\n def __repr__(self):\n return f'ExperimentResult[{self}]'\n\n def serializable(self):\n return {\n 'type': 'ExperimentResult',\n 'setting': self.setting,\n 'expectation': self.expectation,\n 'std_err': self.std_err,\n 'total_counts': self.total_counts,\n 'raw_expectation': self.raw_expectation,\n 'raw_std_err': self.raw_std_err,\n 'calibration_expectation': self.calibration_expectation,\n 'calibration_std_err': self.calibration_std_err,\n 'calibration_counts': self.calibration_counts,\n }\n\n\ndef measure_observables(qc: QuantumComputer, tomo_experiment: TomographyExperiment,\n n_shots: int = 10000, progress_callback=None, active_reset=False,\n symmetrize_readout: Optional[str] = 'exhaustive',\n calibrate_readout: Optional[str] = 'plus-eig',\n readout_symmetrize: Optional[str] = None):\n \"\"\"\n Measure all the observables in a TomographyExperiment.\n\n :param qc: A QuantumComputer which can run quantum programs\n :param tomo_experiment: A suite of tomographic observables to measure\n :param n_shots: The number of shots to take per ExperimentSetting\n :param progress_callback: If not None, this function is called each time a group of\n settings is run with arguments ``f(i, len(tomo_experiment)`` such that the progress\n is ``i / len(tomo_experiment)``.\n :param active_reset: Whether to actively reset qubits instead of waiting several\n times the coherence length for qubits to decay to ``|0>`` naturally. Setting this\n to True is much faster but there is a ~1% error per qubit in the reset operation.\n Thermal noise from \"traditional\" reset is not routinely characterized but is of the same\n order.\n :param symmetrize_readout: Method used to symmetrize the readout errors, i.e. set\n p(0|1) = p(1|0). For uncorrelated readout errors, this can be achieved by randomly\n selecting between the POVMs {X.D1.X, X.D0.X} and {D0, D1} (where both D0 and D1 are\n diagonal). However, here we currently support exhaustive symmetrization and loop through\n all possible 2^n POVMs {X/I . POVM . X/I}^n, and obtain symmetrization more generally,\n i.e. set p(00|00) = p(01|01) = .. = p(11|11), as well as p(00|01) = p(01|00) etc. If this\n is None, no symmetrization is performed. The exhaustive method can be specified by setting\n this variable to 'exhaustive' (default value). Set to `None` if no symmetrization is\n desired.\n :param calibrate_readout: Method used to calibrate the readout results. Currently, the only\n method supported is normalizing against the operator's expectation value in its +1\n eigenstate, which can be specified by setting this variable to 'plus-eig' (default value).\n The preceding symmetrization and this step together yield a more accurate estimation of the observable. Set to `None` if no calibration is desired.\n \"\"\"\n if readout_symmetrize is not None:\n warnings.warn(\"'readout_symmetrize' has been renamed to 'symmetrize_readout'\",\n DeprecationWarning)\n symmetrize_readout = readout_symmetrize\n\n # calibration readout only works with symmetrization turned on\n if calibrate_readout is not None and symmetrize_readout is None:\n raise ValueError(\"Readout calibration only works with readout symmetrization turned on\")\n\n # Outer loop over a collection of grouped settings for which we can simultaneously\n # estimate.\n for i, settings in enumerate(tomo_experiment):\n\n log.info(f\"Collecting bitstrings for the {len(settings)} settings: {settings}\")\n\n # 1.1 Prepare a state according to the amalgam of all setting.in_state\n total_prog = Program()\n if active_reset:\n total_prog += RESET()\n max_weight_in_state = _max_weight_state(setting.in_state for setting in settings)\n for oneq_state in max_weight_in_state.states:\n total_prog += _one_q_state_prep(oneq_state)\n\n # 1.2 Add in the program\n total_prog += tomo_experiment.program\n\n # 1.3 Measure the state according to setting.out_operator\n max_weight_out_op = _max_weight_operator(setting.out_operator for setting in settings)\n for qubit, op_str in max_weight_out_op:\n total_prog += _local_pauli_eig_meas(op_str, qubit)\n\n # 2. Symmetrization\n qubits = max_weight_out_op.get_qubits()\n\n if symmetrize_readout == 'exhaustive' and len(qubits) > 0:\n bitstrings, d_qub_idx = _exhaustive_symmetrization(qc, qubits, n_shots, total_prog)\n\n elif symmetrize_readout is None and len(qubits) > 0:\n total_prog_no_symm = total_prog.copy()\n ro = total_prog_no_symm.declare('ro', 'BIT', len(qubits))\n d_qub_idx = {}\n for i, q in enumerate(qubits):\n total_prog_no_symm += MEASURE(q, ro[i])\n # Keep track of qubit-classical register mapping via dict\n d_qub_idx[q] = i\n total_prog_no_symm.wrap_in_numshots_loop(n_shots)\n total_prog_no_symm_native = qc.compiler.quil_to_native_quil(total_prog_no_symm)\n total_prog_no_symm_bin = qc.compiler.native_quil_to_executable(total_prog_no_symm_native)\n bitstrings = qc.run(total_prog_no_symm_bin)\n\n elif len(qubits) == 0:\n # looks like an identity operation\n pass\n\n else:\n raise ValueError(\"Readout symmetrization method must be either 'exhaustive' or None\")\n\n if progress_callback is not None:\n progress_callback(i, len(tomo_experiment))\n\n # 3. Post-process\n # Inner loop over the grouped settings. They only differ in which qubits' measurements\n # we include in the post-processing. For example, if `settings` is Z1, Z2, Z1Z2 and we\n # measure (n_shots, n_qubits=2) obs_strings then the full operator value involves selecting\n # either the first column, second column, or both and multiplying along the row.\n for setting in settings:\n # 3.1 Get the term's coefficient so we can multiply it in later.\n coeff = complex(setting.out_operator.coefficient)\n if not np.isclose(coeff.imag, 0):\n raise ValueError(f\"{setting}'s out_operator has a complex coefficient.\")\n coeff = coeff.real\n\n # 3.2 Special case for measuring the \"identity\" operator, which doesn't make much\n # sense but should happen perfectly.\n if is_identity(setting.out_operator):\n yield ExperimentResult(\n setting=setting,\n expectation=coeff,\n std_err=0.0,\n total_counts=n_shots,\n )\n continue\n\n # 3.3 Obtain statistics from result of experiment\n obs_mean, obs_var = _stats_from_measurements(bitstrings, d_qub_idx, setting, n_shots, coeff)\n\n if calibrate_readout == 'plus-eig':\n # 4 Readout calibration\n # 4.1 Obtain calibration program\n calibr_prog = _calibration_program(qc, tomo_experiment, setting)\n # 4.2 Perform symmetrization on the calibration program\n if symmetrize_readout == 'exhaustive':\n qubs_calibr = setting.out_operator.get_qubits()\n calibr_shots = n_shots\n calibr_results, d_calibr_qub_idx = _exhaustive_symmetrization(qc, qubs_calibr, calibr_shots, calibr_prog)\n\n else:\n raise ValueError(\"Readout symmetrization method must be either 'exhaustive' or None\")\n\n # 4.3 Obtain statistics from the measurement process\n obs_calibr_mean, obs_calibr_var = _stats_from_measurements(calibr_results, d_calibr_qub_idx, setting, calibr_shots)\n # 4.3 Calibrate the readout results\n corrected_mean = obs_mean / obs_calibr_mean\n corrected_var = ratio_variance(obs_mean, obs_var, obs_calibr_mean, obs_calibr_var)\n\n yield ExperimentResult(\n setting=setting,\n expectation=corrected_mean.item(),\n std_err=np.sqrt(corrected_var).item(),\n total_counts=n_shots,\n raw_expectation=obs_mean.item(),\n raw_std_err=np.sqrt(obs_var).item(),\n calibration_expectation=obs_calibr_mean.item(),\n calibration_std_err=np.sqrt(obs_calibr_var).item(),\n calibration_counts=calibr_shots,\n )\n\n elif calibrate_readout is None:\n # No calibration\n yield ExperimentResult(\n setting=setting,\n expectation=obs_mean.item(),\n std_err=np.sqrt(obs_var).item(),\n total_counts=n_shots,\n )\n\n else:\n raise ValueError(\"Calibration readout method must be either 'plus-eig' or None\")\n\n\ndef _ops_bool_to_prog(ops_bool: Tuple[bool], qubits: List[int]) -> Program:\n \"\"\"\n :param ops_bool: tuple of booleans specifying the operation to be carried out on `qubits`\n :param qubits: list specifying the qubits to be carried operations on\n :return: Program with the operations specified in `ops_bool` on the qubits specified in\n `qubits`\n \"\"\"\n assert len(ops_bool) == len(qubits), \"Mismatch of qubits and operations\"\n prog = Program()\n for i, op_bool in enumerate(ops_bool):\n if op_bool == 0:\n continue\n elif op_bool == 1:\n prog += Program(X(qubits[i]))\n else:\n raise ValueError(\"ops_bool should only consist of 0s and/or 1s\")\n return prog\n\n\ndef _stats_from_measurements(bs_results: np.ndarray, qubit_index_map: Dict,\n setting: ExperimentSetting, n_shots: int,\n coeff: float = 1.0) -> Tuple[float]:\n \"\"\"\n :param bs_results: results from running `qc.run`\n :param qubit_index_map: dict mapping qubit to classical register index\n :param setting: ExperimentSetting\n :param n_shots: number of shots in the measurement process\n :param coeff: coefficient of the operator being estimated\n :return: tuple specifying (mean, variance)\n \"\"\"\n # Identify classical register indices to select\n idxs = [qubit_index_map[q] for q, _ in setting.out_operator]\n # Pick columns corresponding to qubits with a non-identity out_operation\n obs_strings = bs_results[:, idxs]\n # Transform bits to eigenvalues; ie (+1, -1)\n my_obs_strings = 1 - 2 * obs_strings\n # Multiply row-wise to get operator values. Do statistics. Return result.\n obs_vals = coeff * np.prod(my_obs_strings, axis=1)\n obs_mean = np.mean(obs_vals)\n obs_var = np.var(obs_vals) / n_shots\n\n return obs_mean, obs_var\n\n\ndef ratio_variance(a: Union[float, np.ndarray],\n var_a: Union[float, np.ndarray],\n b: Union[float, np.ndarray],\n var_b: Union[float, np.ndarray]) -> Union[float, np.ndarray]:\n r\"\"\"\n Given random variables 'A' and 'B', compute the variance on the ratio Y = A/B. Denote the\n mean of the random variables as a = E[A] and b = E[B] while the variances are var_a = Var[A]\n and var_b = Var[B] and the covariance as Cov[A,B]. The following expression approximates the\n variance of Y\n\n Var[Y] \\approx (a/b) ^2 * ( var_a /a^2 + var_b / b^2 - 2 * Cov[A,B]/(a*b) )\n\n We assume the covariance of A and B is negligible, resting on the assumption that A and B\n are independently measured. The expression above rests on the assumption that B is non-zero,\n an assumption which we expect to hold true in most cases, but makes no such assumptions\n about A. If we allow E[A] = 0, then calculating the expression above via numpy would complain\n about dividing by zero. Instead, we can re-write the above expression as\n\n Var[Y] \\approx var_a /b^2 + (a^2 * var_b) / b^4\n\n where we have dropped the covariance term as noted above.\n\n See the following for more details:\n - https://doi.org/10.1002/(SICI)1097-0320(20000401)39:4<300::AID-CYTO8>3.0.CO;2-O\n - http://www.stat.cmu.edu/~hseltman/files/ratio.pdf\n - https://en.wikipedia.org/wiki/Taylor_expansions_for_the_moments_of_functions_of_random_variables\n\n :param a: Mean of 'A', to be used as the numerator in a ratio.\n :param var_a: Variance in 'A'\n :param b: Mean of 'B', to be used as the numerator in a ratio.\n :param var_b: Variance in 'B'\n \"\"\"\n return var_a / b**2 + (a**2 * var_b) / b**4\n\n\ndef _exhaustive_symmetrization(qc: QuantumComputer, qubits: List[int],\n shots: int, prog: Program) -> (np.ndarray, Dict):\n \"\"\"\n Perform exhaustive symmetrization\n\n :param qc: A QuantumComputer which can run quantum programs\n :param qubits: qubits on which the symmetrization program runs\n :param shots: number of shots in the symmetrized program\n :prog: program to symmetrize\n :return: - the equivalent of a `run` output, but with exhaustive symmetrization\n - dict keyed by qubit, valued by index of the numpy array containing\n bitstring results\n \"\"\"\n # Symmetrize -- flip qubits pre-measurement\n n_shots_symm = int(round(np.ceil(shots / 2**len(qubits))))\n if n_shots_symm * 2**len(qubits) > shots:\n warnings.warn(f\"Symmetrization increasing number of shots from {shots} to {round(n_shots_symm * 2**len(qubits))}\")\n list_bitstrings_symm = []\n for ops_bool in itertools.product([0, 1], repeat=len(qubits)):\n total_prog_symm = prog.copy()\n prog_symm = _ops_bool_to_prog(ops_bool, qubits)\n total_prog_symm += prog_symm\n # Run the experiment\n dict_qub_idx = {}\n ro = total_prog_symm.declare('ro', 'BIT', len(qubits))\n for i, q in enumerate(qubits):\n total_prog_symm += MEASURE(q, ro[i])\n # Keep track of qubit-classical register mapping via dict\n dict_qub_idx[q] = i\n total_prog_symm.wrap_in_numshots_loop(n_shots_symm)\n total_prog_symm_native = qc.compiler.quil_to_native_quil(total_prog_symm)\n total_prog_symm_bin = qc.compiler.native_quil_to_executable(total_prog_symm_native)\n bitstrings_symm = qc.run(total_prog_symm_bin)\n # Flip the results post-measurement\n bitstrings_symm = bitstrings_symm ^ ops_bool\n # Gather together the symmetrized results into list\n list_bitstrings_symm.append(bitstrings_symm)\n\n # Gather together all the symmetrized results\n bitstrings = reduce(lambda x, y: np.vstack((x, y)), list_bitstrings_symm)\n return bitstrings, dict_qub_idx\n\n\ndef _calibration_program(qc: QuantumComputer, tomo_experiment: TomographyExperiment,\n setting: ExperimentSetting) -> Program:\n \"\"\"\n Program required for calibration in a tomography-like experiment.\n\n :param tomo_experiment: A suite of tomographic observables\n :param ExperimentSetting: The particular tomographic observable to measure\n :param symmetrize_readout: Method used to symmetrize the readout errors (see docstring for\n `measure_observables` for more details)\n :param cablir_shots: number of shots to take in the measurement process\n :return: Program performing the calibration\n \"\"\"\n # Inherit any noisy attributes from main Program, including gate definitions\n # and applications which can be handy in creating simulating noisy channels\n calibr_prog = Program()\n # Inherit readout errro instructions from main Program\n readout_povm_instruction = [i for i in tomo_experiment.program.out().split('\\n') if 'PRAGMA READOUT-POVM' in i]\n calibr_prog += readout_povm_instruction\n # Inherit any definitions of noisy gates from main Program\n kraus_instructions = [i for i in tomo_experiment.program.out().split('\\n') if 'PRAGMA ADD-KRAUS' in i]\n calibr_prog += kraus_instructions\n # Prepare the +1 eigenstate for the out operator\n for q, op in setting.out_operator.operations_as_set():\n calibr_prog += _one_q_pauli_prep(label=op, index=0, qubit=q)\n # Measure the out operator in this state\n for q, op in setting.out_operator.operations_as_set():\n calibr_prog += _local_pauli_eig_meas(op, q)\n\n return calibr_prog\n","sub_path":"pyquil/operator_estimation.py","file_name":"operator_estimation.py","file_ext":"py","file_size_in_byte":44924,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"14052854","text":"import dist\nimport csv\nimport os\nimport pandas as pd\n\n\ndef get_distance_from_files(filename_a, filename_b):\n try:\n file_a = open(filename_a, 'r')\n file_b = open(filename_b, 'r')\n text_a = ' '.join(file_a.readlines())\n text_b = ' '.join(file_b.readlines())\n file_a.close()\n file_b.close()\n return dist.calc_distance(text_a, text_b)\n except Exception as error:\n print('Error: ', error)\n\n\ndef main():\n value = 0\n try:\n base_dir = os.getcwd() + '/temp'\n for dir, subdirs, files in os.walk(base_dir):\n for filename in files:\n if filename.endswith('_simple.txt'):\n if filename[:-11] + '.txt' not in files:\n print(\"The right file doesn't exist!\")\n raise FileNotFoundError\n else:\n dir_a = base_dir + '/' + filename\n dir_b = base_dir + '/' + filename[:-11] + '.txt'\n value = get_distance_from_files(dir_a, dir_b)\n except Exception as error:\n print('Error: ', error)\n\n\nif __name__ == '__main__':\n\n #main()\n df = pd.DataFrame({\n 'name': ['Raphael', 'Donatello'],\n 'mask': ['red', 'purple'],\n 'weapon': ['sai', 'bo staff']}\n )\n export = df.to_csv('res.csv', index=None, header=True)\n","sub_path":"run_compare.py","file_name":"run_compare.py","file_ext":"py","file_size_in_byte":1375,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"585163082","text":"\"\"\"\nprefix.py\n\nCreated by Diego Garcia del Rio on 2015-03-12.\nCopyright (c) 2015 Alcatel-Lucent. All rights reserved.\n\nBased on work by Thomas Morin on mac.py\nCopyright (c) 2014-2015 Orange. All rights reserved.\nCopyright (c) 2014-2015 Exa Networks. All rights reserved.\n\"\"\"\n\nfrom exabgp.protocol.ip import IP\nfrom exabgp.bgp.message.update.nlri.qualifier import RouteDistinguisher\nfrom exabgp.bgp.message.update.nlri.qualifier import Labels\nfrom exabgp.bgp.message.update.nlri.qualifier import ESI\nfrom exabgp.bgp.message.update.nlri.qualifier import EthernetTag\n\nfrom exabgp.bgp.message.update.nlri import NLRI\nfrom exabgp.bgp.message.update.nlri.evpn.nlri import EVPN\n\nfrom exabgp.bgp.message.notification import Notify\n\n\n# ------------ EVPN Prefix Advertisement NLRI ------------\n# As described here:\n# http://tools.ietf.org/html/draft-ietf-bess-evpn-prefix-advertisement-01\n\n# +---------------------------------------+\n# | RD (8 octets) |\n# +---------------------------------------+\n# |Ethernet Segment Identifier (10 octets)|\n# +---------------------------------------+\n# | Ethernet Tag ID (4 octets) |\n# +---------------------------------------+\n# | IP Prefix Length (1 octet) |\n# +---------------------------------------+\n# | IP Prefix (4 or 16 octets) |\n# +---------------------------------------+\n# | GW IP Address (4 or 16 octets) |\n# +---------------------------------------+\n# | MPLS Label (3 octets) |\n# +---------------------------------------+\n# total NLRI length is 34 bytes for IPv4 or 58 bytes for IPv6\n\n# ======================================================================= Prefix\n\n\n@EVPN.register\nclass Prefix (EVPN):\n\tCODE = 5\n\tNAME = \"IP Prefix advertisement\"\n\tSHORT_NAME = \"PrfxAdv\"\n\n\tdef __init__(self, rd, esi, etag, label, ip, iplen, gwip, packed=None,nexthop=None,action=None,addpath=None):\n\t\t'''\n\t\trd: a RouteDistinguisher\n\t\tesi: an EthernetSegmentIdentifier\n\t\tetag: an EthernetTag\n\t\tmac: a MAC\n\t\tlabel: a LabelStackEntry\n\t\tip: an IP address (dotted quad string notation)\n\t\tiplen: prefixlength for ip (defaults to 32)\n\t\tgwip: an IP address (dotted quad string notation)\n\t\t'''\n\t\tEVPN.__init__(self,packed,nexthop,action,addpath)\n\t\tself.rd = rd\n\t\tself.esi = esi\n\t\tself.etag = etag\n\t\tself.ip = ip\n\t\tself.iplen = iplen\n\t\tself.gwip = gwip\n\t\tself.label = label\n\t\tself.label = label if label else Labels.NOLABEL\n\t\tself.pack()\n\n\tdef __eq__ (self, other):\n\t\treturn \\\n\t\t\tNLRI.__eq__(self,other) and \\\n\t\t\tself.CODE == other.CODE and \\\n\t\t\tself.rd == other.rd and \\\n\t\t\tself.etag == other.etag and \\\n\t\t\tself.ip == other.ip and \\\n\t\t\tself.iplen == other.iplen\n\t\t# esi, label and gwip must not be compared\n\n\tdef __ne__ (self, other):\n\t\treturn not self.__eq__(other)\n\n\tdef __str__ (self):\n\t\treturn \"%s:%s:%s:%s:%s%s:%s:%s\" % (\n\t\t\tself._prefix(),\n\t\t\tself.rd._str(),\n\t\t\tself.esi,\n\t\t\tself.etag,\n\t\t\tself.ip,\n\t\t\t\"/%d\" % self.iplen,\n\t\t\tself.gwip,\n\t\t\tself.label\n\t\t)\n\n\tdef __hash__ (self):\n\t\t# esi, and label, gwip must *not* be part of the hash\n\t\treturn hash(\"%s:%s:%s:%s\" % (self.rd,self.etag,self.ip,self.iplen))\n\n\tdef _pack (self):\n\t\tif not self.packed:\n\t\t\tvalue = \"%s%s%s%s%s%s%s\" % (\n\t\t\t\tself.rd.pack(),\n\t\t\t\tself.esi.pack(),\n\t\t\t\tself.etag.pack(),\n\t\t\t\tchr(self.iplen),\n\t\t\t\tself.ip.pack(),\n\t\t\t\tself.gwip.pack(),\n\t\t\t\tself.label.pack(),\n\t\t\t)\n\t\t\tself.packed = value\n\t\treturn self.packed\n\n\t@classmethod\n\tdef unpack (cls, exdata):\n\t\tdata = exdata\n\n\t\t# Get the data length to understand if addresses are IPv4 or IPv6\n\t\tdatalen = len(data)\n\n\t\trd = RouteDistinguisher.unpack(data[:8])\n\t\tdata = data[8:]\n\n\t\tesi = ESI.unpack(data[:10])\n\t\tdata = data[10:]\n\n\t\tetag = EthernetTag.unpack(data[:4])\n\t\tdata = data[4:]\n\n\t\tiplen = ord(data[0])\n\t\tdata = data[1:]\n\n\t\tif datalen == (26 + 8): # Using IPv4 addresses\n\t\t\tip = IP.unpack(data[:4])\n\t\t\tdata = data[4:]\n\t\t\tgwip = IP.unpack(data[:4])\n\t\t\tdata = data[4:]\n\t\telif datalen == (26 + 32): # Using IPv6 addresses\n\t\t\tip = IP.unpack(data[:16])\n\t\t\tdata = data[16:]\n\t\t\tgwip = IP.unpack(data[:16])\n\t\t\tdata = data[16:]\n\t\telse:\n\t\t\traise Notify(3,5,\"Data field length is given as %d, but EVPN route currently support only IPv4 or IPv6(34 or 58)\" % iplen)\n\n\t\tlabel = Labels.unpack(data[:3])\n\n\t\treturn cls(rd,esi,etag,label,ip,iplen,gwip,exdata)\n","sub_path":"lib/exabgp/bgp/message/update/nlri/evpn/prefix.py","file_name":"prefix.py","file_ext":"py","file_size_in_byte":4257,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"258468580","text":"# this file will get player offensive statistics\nimport json\nimport time\nimport datetime\nfrom requests_futures.sessions import FuturesSession\nimport requests\nfrom bs4 import BeautifulSoup\nfrom lxml import html\n\nplayers = []\n\nheaders = {\n 'Accept-Encoding': 'gzip, deflate, sdch',\n 'Accept-Language': 'en-US,en;q=0.8,ru;q=0.6',\n 'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_2) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36',\n}\n\nall_player_params = (\n ('LeagueID', '00'),\n ('Season', '2016-17'),\n ('IsOnlyCurrentSeason', '0'),\n)\n\ndef retStuff(year, str):\n return (\n ('College', ''),\n ('Conference', ''),\n ('Country', ''),\n ('DateFrom', ''),\n ('DateTo', ''),\n ('Division', ''),\n ('DraftPick', ''),\n ('DraftYear', ''),\n ('GameScope', ''),\n ('Height', ''),\n ('LastNGames', '0'),\n ('LeagueID', '00'),\n ('Location', ''),\n ('Month', '0'),\n ('OpponentTeamID', '0'),\n ('Outcome', ''),\n ('PORound', '0'),\n ('PerMode', 'PerGame'),\n ('PlayerExperience', ''),\n ('PlayerOrTeam', 'Player'),\n ('PlayerPosition', ''),\n ('PtMeasureType', str),\n ('Season', year),\n ('SeasonSegment', ''),\n ('SeasonType', 'Regular Season'),\n ('StarterBench', ''),\n ('TeamID', '0'),\n ('VsConference', ''),\n ('VsDivision', ''),\n ('Weight', '')\n )\n\ndef contract_return(player_contract, year_object, information, year_string):\n year_object = information.text\n if information[\"class\"][1] == \"salary-tm\":\n player_contract.team_options.append(year_string)\n if information[\"class\"][1] == \"salary-pl\":\n player_contract.player_options.append(year_string)\n if information[\"class\"][1] == \"salary-et\":\n player_contract.player_options.append(year_string)\n\ndef findByName(name):\n # this is not good unless you are debugging something\n for player in players:\n if player.name == name:\n return player\n\n return\n\ndef findById(id):\n for player in players:\n if int(player.id) == int(id):\n return player\n return -1\n\nclass Player:\n def __init__(self, id, name, current):\n self.id = id\n self.name = name\n self.current = current\n self.offensive_seasons = []\n self.defensive_seasons = []\n self.advanced_statistics = []\n self.height = 0\n self.weight = 0\n self.position = \"\"\n self.salary = 0\n players.append(self)\n def getId(self):\n return self.id\n def getName(self):\n return self.name\n def current(self):\n return self.current\n def toJSON(self):\n return json.dumps(self, default=lambda o: o.__dict__,\n sort_keys=True, indent=4)\n def find_advanced_for_year(self, year):\n for advanced in self.advanced_statistics:\n if(advanced.year == year):\n return advanced\n return -1\n def ret_stuff(self):\n return ((self.advanced_statistics[-1].secondaryassist+self.offensive_seasons[-1].ast)*2.678245121380469)+self.offensive_seasons[-1].pts+(self.offensive_seasons[-1].reb*1.2076782265205361)+(self.offensive_seasons[-1].stl*1.2076782265205361)+(self.offensive_seasons[-1].blk*1.2076782265205361)-(self.offensive_seasons[-1].tov*1.2076782265205361)-(self.offensive_seasons[-1].pf*1.2076782265205361)\n\nclass PlayerContract:\n def __init__(self):\n self.name = \"\"\n self.team = \"\"\n self.y1 = 0\n self.y2 = 0\n self.y3 = 0\n self.y4 = 0\n self.y5 = 0\n self.y6 = 0\n self.player_options = []\n self.team_options = []\n self.early_termination = []\n self.signed_using = \"\"\n def change_team(self,start, end):\n if self.team == start:\n self.team = end\n def dumps(self):\n return \"Name \"+self.name+\" Current Year \"+self.y1\n\nclass OffensiveSeason:\n def __init__(self, playerid, year, teamid, teamabr, age, gp, gs, min, fgm, fga, fgp,\n threem, threea, threep, ftm, fta, ftp, oreb, dreb, reb, ast, stl, blk, tov, pf, pts):\n self.playerid = playerid\n self.year = year\n self.teamid = teamid\n self.teamabr = teamabr\n self.age = age\n self.gp = gp\n self.gs = gs\n self.min = min\n self.fgm = fgm\n self.fga = fga\n self.fgp = fgp\n self.threem = threem\n self.threea = threea\n self.threep = threep\n self.ftm = ftm\n self.oreb = oreb\n self.dreb = dreb\n self.reb = reb\n self.ast = ast\n self.stl = stl\n self.blk = blk\n self.tov = tov\n self.pf = pf\n self.pts = pts\n\nclass DefensiveSeason:\n def __init__(self, playerid, teamid, teamabr, age, gp, gs, min, wins, losses, win_p, offensive_rating, defensive_rating, net_rating, ast_pct, ast_to, ast_ratio, oreb_percentage, dreb_percentage, tm_tov_pct, ts_pct, usg_pct, pace, pie, year):\n self.playerid = playerid\n self.teamid = teamid\n self.teamabr = teamabr\n self.age = age\n self.gp = gp\n self.gs = gs\n self.min = min\n self.wins = wins\n self.losses = losses\n self.win_p = win_p\n self.offensive_rating = offensive_rating\n self.defensive_rating = defensive_rating\n self.net_rating = net_rating\n self.ast_pct = ast_pct\n self.ast_to = ast_to\n self.ast_ratio = ast_ratio\n self.oreb_percentage = oreb_percentage\n self.dreb_percentage = dreb_percentage\n self.tm_tov_pct = tm_tov_pct\n self.ts_pct = ts_pct\n self.usg_pct = usg_pct\n self.pace = pace\n self.pie = pie\n self.year = year\n\nclass PlayerTracking:\n def __init__(self, year, rimfgm, rimfga, rimfgp, drivepts, driveast, drivepass,\n drivepf, drivefta, passesmade, passesreceived, secondaryassist, potentialassist,\n pointscreatedbyassist, overallassist, postups, touches, postpasses, posttov,\n postpf, pullupoints, catchshootpoints, posttouchpoints, elbowtouchpoints):\n self.year = year\n self.rimfgm = rimfgm\n self.rimfga = rimfga\n self.rimfgp = rimfgp\n self.drivepts = drivepts\n self.driveast = driveast\n self.drivepass = drivepass\n self.drivepf = drivepf\n self.drivefta = drivefta\n self.passesmade = passesmade\n self.passesreceived = passesreceived\n self.secondaryassist = secondaryassist\n self.potentialassist = potentialassist\n self.pointscreatedbyassist = pointscreatedbyassist\n self.overallassist = overallassist\n self.postups = postups\n self.touches = touches\n self.postpasses = postpasses\n self.posttov = posttov\n self.postpf = postpf\n self.pullupoints = pullupoints\n self.catchshootpoints = catchshootpoints\n self.posttouchpoints = posttouchpoints\n self.elbowtouchpoints = elbowtouchpoints\n\nclass AllOfBasketball:\n\n players = []\n\n def __init__(self, years):\n\n ids = []\n\n all_basic_player_json = json.loads(requests.get('http://stats.nba.com/stats/commonallplayers', headers=headers, params=all_player_params).text)\n\n for resultSet in all_basic_player_json[\"resultSets\"]:\n for player_json in resultSet[\"rowSet\"]:\n if player_json[-1] == \"Y\":\n if int(player_json[5]) >= int(years[0].split(\"-\")[0]):\n player = Player(player_json[0], player_json[2], player_json[6])\n ids.append(player_json[0])\n\n contract_soup = BeautifulSoup(requests.get(\"https://www.basketball-reference.com/contracts/players.html\", headers=headers).text, \"html.parser\")\n\n for player_row in contract_soup.tbody.find_all('tr'):\n\n try:\n\n player_contract = PlayerContract()\n years_and_info = player_row.find_all('td')\n\n player_contract.name = years_and_info[0].a.text\n player_contract.team = years_and_info[1].a.text\n\n player_contract.change_team(\"BRK\", \"BKN\")\n player_contract.change_team(\"CHO\", \"CHA\")\n player_contract.change_team(\"PHO\", \"PHX\")\n\n contract_return(player_contract, player_contract.y1, years_and_info[2], \"Year 1\")\n contract_return(player_contract, player_contract.y2, years_and_info[3], \"Year 2\")\n contract_return(player_contract, player_contract.y3, years_and_info[4], \"Year 3\")\n contract_return(player_contract, player_contract.y4, years_and_info[5], \"Year 4\")\n contract_return(player_contract, player_contract.y5, years_and_info[6], \"Year 5\")\n contract_return(player_contract, player_contract.y6, years_and_info[7], \"Year 6\")\n\n player_contract.signed_using = years_and_info[8].text\n\n if findByName(player.name):\n findByName(player.name).salary = player_contract\n\n except (IndexError, KeyError):\n continue\n\n for year in years:\n defParams = retStuff(year, \"Defense\")\n driveParams = retStuff(year, \"Drives\")\n efficiencyParams = retStuff(year, \"Efficiency\")\n passParams = retStuff(year, \"Passing\")\n postParams = retStuff(year, \"PostTouch\")\n\n session = FuturesSession()\n\n defResponse = session.get(\"http://stats.nba.com/stats/leaguedashptstats\", headers=headers, params=defParams)\n defData = json.loads(defResponse.result().content)\n\n driveResponse = session.get(\"http://stats.nba.com/stats/leaguedashptstats\", headers=headers, params=driveParams)\n driveData = json.loads(driveResponse.result().content)\n\n efficiencyResponse = session.get(\"http://stats.nba.com/stats/leaguedashptstats\", headers=headers, params=efficiencyParams)\n efficiencyData = json.loads(efficiencyResponse.result().content)\n\n passResponse = session.get(\"http://stats.nba.com/stats/leaguedashptstats\", headers=headers, params=passParams)\n passData = json.loads(passResponse.result().content)\n\n postResponse = session.get(\"http://stats.nba.com/stats/leaguedashptstats\", headers=headers, params=postParams)\n postData = json.loads(postResponse.result().content)\n\n for player in defData[\"resultSets\"][0][\"rowSet\"]:\n advanced = PlayerTracking(year, player[11], player[12], player[13], \"\", \"\", \"\",\n \"\", \"\", \"\", \"\", \"\", \"\",\n \"\", \"\", \"\", \"\", \"\", \"\",\n \"\", \"\", \"\", \"\", \"\")\n findById(player[0]).advanced_statistics.append(advanced)\n\n for player in driveData[\"resultSets\"][0][\"rowSet\"]:\n advanced = findById(player[0]).find_advanced_for_year(year)\n advanced.drivepts = player[15]\n advanced.driveast = player[19]\n advanced.drivepass = player[17]\n advanced.drivepf = player[23]\n advanced.drivefta = player[13]\n\n for player in efficiencyData[\"resultSets\"][0][\"rowSet\"]:\n advanced = findById(player[0]).find_advanced_for_year(year)\n advanced.pullupoints = player[13]\n advanced.catchshootpoints = player[11]\n advanced.posttouchpoints = player[17]\n advanced.elbowtouchpoints = player[19]\n\n for player in passData[\"resultSets\"][0][\"rowSet\"]:\n advanced = findById(player[0]).find_advanced_for_year(year)\n advanced.passesmade = player[8]\n advanced.passesreceived = player[9]\n advanced.secondaryassist = player[12]\n advanced.potentialassist = player[13]\n advanced.pointscreatedbyassist = player[14]\n advanced.overallassist = player[10]\n for player in postData[\"resultSets\"][0][\"rowSet\"]:\n advanced = findById(player[0]).find_advanced_for_year(year)\n advanced.postups = player[7]\n advanced.touches = player[8]\n advanced.postpasses = player[17]\n advanced.posttov = player[21]\n advanced.postpf = player[23]\n\n for player in players:\n\n try:\n params = (\n ('LeagueID', '00'),\n ('PerMode', 'PerGame'),\n ('PlayerID', player.id)\n )\n\n id_param = (\n ('PlayerID', player.id),\n ('h', \"h\")\n )\n\n advanced_params = (\n ('DateFrom', ''),\n ('DateTo', ''),\n ('GameSegment', ''),\n ('LastNGames', '0'),\n ('LeagueID', '00'),\n ('Location', ''),\n ('MeasureType', 'Advanced'),\n ('Month', '0'),\n ('OpponentTeamID', '0'),\n ('Outcome', ''),\n ('PORound', '0'),\n ('PaceAdjust', 'N'),\n ('PerMode', 'PerGame'),\n ('PlayerID', player.id),\n ('PlusMinus', 'N'),\n ('Period', '0'),\n ('Rank', 'N'),\n ('Season', '2017-18'),\n ('SeasonSegment', ''),\n ('SeasonType', 'Regular Season'),\n ('ShotClockRange', ''),\n ('Split', 'yoy'),\n ('VsConference', ''),\n ('VsDivision', '')\n )\n\n session = FuturesSession()\n height_weight_pos_response = session.get(\"http://stats.nba.com/stats/commonplayerinfo\", headers=headers, params=id_param)\n response = session.get(\"http://stats.nba.com/stats/playerprofilev2\", headers=headers, params=params)\n advanced_response = session.get(\"http://stats.nba.com/stats/playerdashboardbyyearoveryear\", headers=headers, params=advanced_params)\n common_html = height_weight_pos_response.result().content\n common_data = json.loads(common_html)\n player.height = common_data[\"resultSets\"][0][\"rowSet\"][0][10]\n player.weight = common_data[\"resultSets\"][0][\"rowSet\"][0][11]\n player.position = common_data[\"resultSets\"][0][\"rowSet\"][0][14]\n\n html = response.result().content\n data = json.loads(html)\n i = data[\"resultSets\"][0]\n\n for c in i[\"rowSet\"]:\n season = OffensiveSeason(player.id, c[1], c[3], c[4], c[5], c[6], c[7], c[8], c[9], c[10],\n c[11], c[12], c[13], c[14], c[15], c[16], c[17], c[18], c[19],\n c[20], c[21], c[22], c[23], c[24], c[25], c[26])\n player.offensive_seasons.append(season)\n\n html_advanced = advanced_response.result().content\n data_advanced = json.loads(html_advanced)\n i_advanced = data_advanced[\"resultSets\"][1]\n\n for c in i_advanced[\"rowSet\"]:\n season = DefensiveSeason(player.id, c[2], c[3],\n 0, c[5], 0, c[9], c[6], c[7], c[8], c[10], c[11], c[12], c[13], c[14],\n c[15], c[16], c[17], c[19], c[21], c[22], c[23], c[24], c[1])\n player.defensive_seasons.append(season)\n\n print(\"Gathering Data...\" + player.name)\n self.players.append(player)\n time.sleep(0.2)\n break\n\n except(KeyError, IndexError, ConnectionError):\n print(\"Whoops, weird guy just appeared \"+ player.name)\n\n def get_players(self):\n return self.players\n\n def get_player_json(self, file_name):\n with open(file_name, \"w\") as f:\n json.dump([dict(ob) for ob in self.get_players()], f)\n","sub_path":"build/lib/python_nba_pack/player_stats.py","file_name":"player_stats.py","file_ext":"py","file_size_in_byte":16370,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"585394818","text":"import re\nimport pickle \nimport math\n\ndef prob_calc(content, dictionary):\n\ttotal_pos = 0\n\ttotal_neg = 0\n\ttotal_total = 0\n\tlines = content.splitlines()\n\tfor line in lines:\n\t\ttotal_total = total_total + 1\n\t\twords = line.split()\n\t\tif \"pos\" in words:\n\t\t\ttotal_pos = total_pos + 1\n\t\telif \"neg\" in words:\n\t\t\ttotal_neg = total_neg + 1\n\tprint(\"Total no of +ves : \" + str(total_pos))\n\tprint(\"Total no of -ves : \" + str(total_neg))\n\n\tvocabs = dictionary.splitlines()\n\tmodel = {}\n\tfor vocab in vocabs:\n\t\tword_pos = 0\n\t\tword_neg = 0\n\t\tword_total = 0\n\t\tfor line in lines:\n\t\t\tif vocab in line:\n\t\t\t\tif \"pos\" in line:\n\t\t\t\t\tword_pos = word_pos + 1\n\t\t\t\telif \"neg\" in line:\n\t\t\t\t\tword_neg = word_neg + 1\n\t\t\t\tword_total = word_total + 1\n\t\tmodel[vocab] = {\"pos\" : word_pos, \"neg\" : word_neg}\n\treturn {\"model\" : model, \"total_pos\" : total_pos, \"total_neg\" : total_neg, \"total_total\" : total_total}\n\ndef word_class_counter(content):\n\tlines = content.splitlines()\n\tpos = 0\n\tneg = 0\n\tfor line in lines:\n\t\twords = line.split()\n\t\tif \"pos\" in words:\n\t\t\tpos = pos + len(words) - 1\n\t\telif \"neg\" in words:\n\t\t\tneg = neg + len(words) - 1\n\tprint(\"No of words in +ve reviews : \" + str(pos))\n\tprint(\"No of words in -ve reviews : \" + str(neg))\n\treturn {\"pos\" : pos, \"neg\" : neg}\n\ndef smoother(model_and_total, pos_and_neg, content, vocabulary):\n\tvocabs = vocabulary.split()\n\twords = content.split()\n\tsmooth_res = {}\n\tfor word in words:\n\t\tif word != \"pos\" and word != \"neg\":\n\t\t\tif word in model_and_total[\"model\"]:\n\t\t\t\tres_pos = (model_and_total[\"model\"][word][\"pos\"] + 1)/(pos_and_neg[\"pos\"] + len(vocabs))\n\t\t\t\tres_neg = (model_and_total[\"model\"][word][\"neg\"] + 1)/(pos_and_neg[\"neg\"] + len(vocabs))\n\t\t\telse:\n\t\t\t\tres_pos = 1/(pos_and_neg[\"pos\"] + len(vocabs))\n\t\t\t\tres_neg = 1/(pos_and_neg[\"neg\"] + len(vocabs))\n\t\t\tsmooth_res[word] = {\"pos\" : res_pos, \"neg\" : res_neg}\n\treturn smooth_res\n\ndef cond_prob(model_and_total, pos_and_neg, content, smooth_res):\n\tcond_prob_list = {}\n\tlines = content.splitlines()\n\tfor line in lines:\n\t\tpos_cond = math.log((model_and_total[\"total_pos\"]/model_and_total[\"total_total\"])*list_mult(line, smooth_res, \"+\"), 2)\n\t\tneg_cond = math.log((model_and_total[\"total_neg\"]/model_and_total[\"total_total\"])*list_mult(line, smooth_res, \"-\"), 2)\n\t\tcond_prob_list[line] = {\"pos_cond\" : pos_cond, \"neg_cond\" : neg_cond}\n\treturn cond_prob_list\n\ndef list_mult(line, smooth_res, arg):\n\twords = line.split()\n\tprint(words)\n\tresult = 1\n\tif arg == \"+\":\n\t\tfor word in words:\n\t\t\tif word != \"pos\" and word != \"neg\":\n\t\t\t\tresult = result * smooth_res[word][\"pos\"]\n\telif arg == \"-\":\n\t\tfor word in words:\n\t\t\tif word != \"neg\" and word != \"pos\":\n\t\t\t\tresult = result * smooth_res[word][\"neg\"]\n\treturn result\n\n\nif __name__ == \"__main__\":\n\tfname = input(\"Enter name of file : \")\n\tf_obj = open(fname, \"r\")\n\tcontent = f_obj.read()\n\tdname = input(\"Enter name of dictionary : \")\n\td_obj = open(dname, \"r\")\n\tdictionary = d_obj.read()\n\tmodel_and_total = prob_calc(content, dictionary)\n\tpos_and_neg = word_class_counter(content)\n\tprint(model_and_total)\n\tprint(pos_and_neg)\n\tsmooth_result = smoother(model_and_total, pos_and_neg, content, dictionary)\n\tcond_model = cond_prob(model_and_total, pos_and_neg, content, smooth_result)\n\tcond_model_pickled = pickle.dumps(cond_model)\n\tcond_model_fname = input(\"Enter filename to save model : \")\n\tc_obj = open(cond_model_fname, \"w\")\n\tc_obj.write(str(cond_model_pickled))\n","sub_path":"q4.py","file_name":"q4.py","file_ext":"py","file_size_in_byte":3365,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"248840636","text":"from keras import backend as K\nfrom keras.models import Sequential, Model\nfrom keras.layers.merge import _Merge\nfrom keras import regularizers\nfrom keras.layers import *\nfrom keras.models import load_model\nfrom keras.optimizers import RMSprop, Adam\nfrom read_json import *\nfrom order_vector import *\nfrom functools import partial\nimport gc\nimport time\nfrom discrimination import *\n\nclass RandomWeightedAverage(_Merge):\n def _merge_function(self, inputs):\n weights = K.random_uniform((64, 1, 1,1))\n return (weights * inputs[0]) + ((1 - weights) * inputs[1])\n\nclass lstm_cond_gan(object):\n def __init__(self, history_ol=10, orderLength=8, historyLength=100,\\\n noiseLength=1,noiseLength_1 = 100,lstm_out_length=4,mini_batch_size=1,\\\n data_path=None,batch_size=64):\n self.history_ol = history_ol\n self.orderLength = orderLength\n self.historyLength = historyLength\n self.noiseLength = noiseLength\n self.noiseLength_1 = noiseLength_1\n self.lstm_out_length = lstm_out_length\n self.mini_batch_size = mini_batch_size\n self.data_path = data_path\n self.batch_size = batch_size\n self.model = None\n self.build()\n\n def gradient_penalty_loss(self,y_true, y_pred, averaged_samples, \\\n gradient_penalty_weight):\n gradients = K.gradients(y_pred, averaged_samples)[0]\n # compute the euclidean norm by squaring ...\n gradients_sqr = K.square(gradients)\n # ... summing over the rows ...\n gradients_sqr_sum = K.sum(gradients_sqr,\n axis=np.arange(1, len(gradients_sqr.shape)))\n # ... and sqrt\n gradient_l2_norm = K.sqrt(gradients_sqr_sum)\n # compute lambda * (1 - ||grad||)^2 still for each single sample\n gradient_penalty = gradient_penalty_weight * K.square(1 - gradient_l2_norm)\n # return the mean as loss over all the batch samples\n return K.mean(gradient_penalty)\n\n def w_loss(self,y_true,y_pred):\n return K.mean(y_true*y_pred)\n\n def attention_3d_block(self,inputs,SINGLE_ATTENTION_VECTOR=False):\n input_dim = int(inputs.shape[1])\n a = Permute((2, 1))(inputs)\n a = Dense(input_dim, activation='softmax')(a)\n if SINGLE_ATTENTION_VECTOR:\n a = Lambda(lambda x: K.mean(x, axis=1))(a)\n a = RepeatVector(self.history_ol)(a)\n a_probs = Permute((2, 1))(a)\n output_attention_mul = merge([inputs, a_probs], mode='mul')\n return output_attention_mul\n\n def build(self):\n # build models\n if self.model:\n return self.model\n # lstm cell, to do : attention mechanism\n history = Input(shape=(4,), \\\n name='history_full')\n history_input = Input(shape=(1,), \\\n name='history_input')\n #lstm_output = LSTM(self.lstm_out_length)(history)\n #dense_1 = Flatten()(history_input)\n #lstm_output = Dense(self.lstm_out_length)(dense_1)\n #D lstm with attention mechamism\n #lstm_output_h = LSTM(self.lstm_out_length,name='lstm_critic')(history_input)\n #lstm_output_d = Dense(self.orderLength,name='dense_critic')(lstm_output_h)\n\n\n # merge with noise\n noise_input = Input(shape=(self.noiseLength,), name='noise_input')\n noise_input_1 = Input(shape=(self.noiseLength_1,), name='noise_input_1')\n gen_input = Concatenate(axis=-1)([history_input,noise_input])\n gen_input_1 = Concatenate(axis=-1)([history,noise_input_1])\n #generator\n dropout = 0.5\n G = Sequential(name='generator')\n G.add(Dense(self.mini_batch_size * 100, input_dim=self.noiseLength+1))\n G.add(BatchNormalization())\n G.add(Activation('relu'))\n #G.add(Dense(128))\n #G.add(BatchNormalization())\n #G.add(Activation('relu'))\n #G.add(Dense(32))\n #G.add(BatchNormalization())\n #G.add(Activation('relu'))\n #G.add(Dense(8))\n #G.add(BatchNormalization())\n #G.add(Activation('relu'))\n #G.add(Dense(1))\n #G.add(BatchNormalization())\n #G.add(Activation('tanh'))\n #G.add(Reshape((int(self.mini_batch_size), 1,1)))\n G.add(Reshape((int(self.mini_batch_size), 1, 100)))\n G.add(UpSampling2D())\n G.add(Conv2DTranspose(64, 32, padding='same'))\n G.add(BatchNormalization())\n G.add(Activation('relu'))\n G.add(Dropout(dropout))\n G.add(UpSampling2D())\n G.add(Conv2DTranspose(32, 32, padding='same'))\n G.add(BatchNormalization())\n G.add(Activation('relu'))\n G.add(Conv2DTranspose(16, 32 , padding='same'))\n G.add(BatchNormalization())\n G.add(Activation('relu'))\n G.add(Conv2DTranspose(8, 32, padding='same'))\n G.add(BatchNormalization())\n G.add(Activation('relu'))\n G.add(Conv2DTranspose(4, 32, padding='same'))\n G.add(BatchNormalization())\n G.add(Activation('relu'))\n G.add(MaxPooling2D((2,2)))\n G.add(Conv2DTranspose(1, 32, padding='same'))\n G.add(Activation('tanh'))\n G.add(MaxPooling2D((2,2)))\n generator_output = G(gen_input)\n\n dropout = 0.5\n G_1 = Sequential(name='generator_1')\n G_1.add(Dense((self.orderLength-1)*self.mini_batch_size*100, \\\n input_dim=self.noiseLength_1+self.lstm_out_length))\n G_1.add(BatchNormalization())\n G_1.add(Activation('relu'))\n G_1.add(Reshape((int(self.mini_batch_size), int(self.orderLength - 1), 100)))\n G_1.add(UpSampling2D())\n G_1.add(Dropout(dropout))\n G_1.add(UpSampling2D())\n G_1.add(Conv2DTranspose(32, 32, padding='same'))\n G_1.add(BatchNormalization())\n G_1.add(Activation('relu'))\n G_1.add(Conv2DTranspose(16,32 , padding='same'))\n G_1.add(BatchNormalization())\n G_1.add(Activation('relu'))\n G_1.add(Conv2DTranspose(8, 32, padding='same'))\n G_1.add(BatchNormalization())\n G_1.add(Activation('relu'))\n G_1.add(MaxPooling2D((2,2)))\n G_1.add(Conv2DTranspose(1, 32, padding='same'))\n G_1.add(Activation('tanh'))\n G_1.add(MaxPooling2D((2,2)))\n generator_output_1 = G_1(gen_input_1)\n\n gen_output = Concatenate(axis=2)([generator_output,generator_output_1])\n\n truth_input = Input(shape=(self.mini_batch_size,self.orderLength,1),name='truth_input')\n #discriminator_input_fake = (Concatenate(axis=2)\\\n # ([Reshape((1, 1,1))(history_input), generator_output]))\n #discriminator_input_truth = Concatenate(axis=2)\\\n # ([Reshape((1, 1,1))(history_input), truth_input])\n discriminator_input_fake = gen_output\n discriminator_input_truth = truth_input\n\n #gradient penelty\n averaged_samples = RandomWeightedAverage()([discriminator_input_fake, discriminator_input_truth])\n\n #discriminator\n D = Sequential(name='discriminator')\n D.add(Conv2D(512,(3,3),padding='same', input_shape=(self.mini_batch_size, self.orderLength,1)))\n D.add(Activation('relu'))\n D.add(Conv2D(256, (3,3),padding='same'))\n D.add(Activation('relu'))\n D.add(Conv2D(128,(3,3),padding='same'))\n D.add(Activation('relu'))\n D.add(Flatten())\n D.add(Dense(1))\n #D.add(Activation('tanh'))\n self.D = D\n discriminator_output_fake = D(discriminator_input_fake)\n discriminator_output_truth = D(discriminator_input_truth)\n averaged_samples_output = D(averaged_samples)\n\n partial_gp_loss = partial(self.gradient_penalty_loss,\n averaged_samples=averaged_samples,\n gradient_penalty_weight=1)\n partial_gp_loss.__name__ = 'gradient_penalty' # Functions need names or Keras will throw an error\n\n self.gen = Model(inputs=[history_input,history,noise_input,noise_input_1], outputs= gen_output)\n self.model_truth = Model(inputs=[history_input,history,noise_input,noise_input_1,truth_input],\\\n outputs= [discriminator_output_fake,discriminator_output_truth,averaged_samples_output])\n self.model_fake = Model(inputs=[history_input,history,noise_input,noise_input_1],\\\n outputs= discriminator_output_fake)\n optimizer = Adam(0.0001, beta_1=0.5, beta_2=0.9)\n self.gen.compile(optimizer=optimizer, loss='binary_crossentropy')\n self.gen.summary()\n for layer in self.model_truth.layers:\n layer.trainable = False\n self.model_truth.get_layer(name='discriminator').trainable = True\n #self.model_truth.get_layer(name='lstm_critic').trainable = True\n #self.model_truth.get_layer(name='dense_critic').trainable = True\n self.model_truth.compile(optimizer=optimizer, \\\n loss=[self.w_loss,self.w_loss,partial_gp_loss])\n for layer in self.model_fake.layers:\n layer.trainable = True\n self.model_fake.get_layer(name='discriminator').trainable = False\n #self.model_fake.get_layer(name='lstm_critic').trainable = False\n #self.model_fake.get_layer(name='dense_critic').trainable = False\n self.model_fake.compile(optimizer=optimizer, loss=self.w_loss)\n self.model_fake.summary()\n self.model_truth.summary()\n\n def Recover_interval(self,data,ref):\n #print(np.round(ref))\n data_new = np.zeros((self.mini_batch_size,6))\n if(data.shape[1]==3):\n data_new[:,3:] =np.floor(data)\n else:\n #if(np.max(((((data[:,0]*10 + data[:,1])*10 + data[:,2])*10 + data[:,3])*10 + data[:,4])*10 + data[:,5]) < 4000):\n data_new = np.floor(data)\n #else:\n # print(\"Big Step\")\n # return None\n\n\n def normalize(data):\n for i in range(5,-1,-1):\n if(data[i]>9):\n data[i] -= 10\n if(i > 0):\n data[i-1] += 1\n if(((((data[0]*10 + data[1])*10 + data[2])*10 + data[3])*10 + data[4])*10 + data[5] > 210000):\n data = [0,0,0,0,0,0]\n return data\n\n for i in range(data_new.shape[0]):\n if(i == 0):\n data_new[i,:] = data_new[i,:] + np.round(ref)\n else:\n data_new[i,:] = data_new[i,:] + data_new[i-1,:]\n data_new[i,:] = normalize(data_new[i,:])\n return data_new\n\n\n def fit(self, train_steps=300001, buy_sell_tag=0, batch_size=64, gnr_path='gnr'):\n #self.gen = load_model('gnr_goog12_100000')\n data = np.load(self.data_path, mmap_mode='r')\n for i in range(train_steps):\n positive_y = np.ones((batch_size, 1), dtype=np.float32)\n negative_y = -positive_y\n dummy_y = np.zeros((batch_size, 1), dtype=np.float32)\n no = np.random.normal(0, 0.05 , size=[data.shape[0],batch_size, self.noiseLength])\n no_1 = np.random.uniform(-1, 1 , size=[data.shape[0],batch_size, self.noiseLength_1])\n\n for j in range(100):\n ## train/fake init\n idx = np.random.randint(0, data.shape[0])\n noise = no[idx]\n noise_1 = no_1[idx]\n orderStreams_train = np.squeeze(data[idx].copy())\n d_history = orderStreams_train[:,:self.historyLength,:]\n history = (np.squeeze(np.mean((d_history[:,:,0:1] * 10 + d_history[:,:,1:2]),1)) - 11.5)/11.5\n history_full = np.mean(self.normalize(orderStreams_train[:,:self.historyLength,6:]),1)\n truth = np.expand_dims(self.normalize(orderStreams_train[:,self.historyLength:,4:]),-1)\n d_loss = self.model_truth.train_on_batch([history,history_full,noise,noise_1,\\\n truth], [negative_y,positive_y,dummy_y])\n\n\n a_loss = self.model_fake.train_on_batch([history,history_full,noise,noise_1], positive_y)\n log_mesg = \"%d: [D_fake loss: %f,D_truth loss: %f] \" % (i, d_loss[0],d_loss[1])\n log_mesg = \"%s [A loss: %f]\" % (log_mesg, a_loss)\n with open('log_goog_new.txt','a') as f:\n f.write(log_mesg+'\\n')\n f.close()\n #print(log_mesg)\n if i % 1000 == 0:\n self.gen.save(gnr_path+'_'+str(i))\n\n def denormalize(self, normArray):\n def denormalize_one_dim(data,maxV=1, minV=0, high=1, low=-1):\n return ((((data - high) * (maxV - minV))/(high - low)) + maxV)\n\n Array = normArray.copy()\n # GooG\n maxV = [2.34,9,9,9,1,1,941.79,680]\n minV = [0.12,0,0,0,0,0,916.13,0.6]\n # Syn32\n #maxV = [1.8,9,9,9,1,1,1,2]\n #minV = [1.5,0,0,0,0,0,-1,0]\n # Syn64\n #maxV = [3.8,9,9,9,1,1,1,2]\n #minV = [3.5,0,0,0,0,0,-1,0]\n #PN\n #maxV = [46.5,9,9,9,1,1,12.68,635]\n #minV = [12.7,0,0,0,0,0,6.41,0.82]\n #PN\n #maxV = [46.5,9,9,9,1,1,12.68,635]\n #minV = [6.54,0,0,0,0,0,6.41,0.8]\n for i in range(Array.shape[2]):\n Array[:,:,i] = denormalize_one_dim(normArray[:,:,i],maxV=maxV[i],minV=minV[i])\n newArray = np.zeros((Array.shape[0],Array.shape[1],6))\n newArray[:,:,0] = Array[:,:,0]\n newArray[:,:,2:] = Array[:,:,4:]\n newArray[:,:,1] = (Array[:,:,1] * 10 + Array[:,:,2]) * 10 + Array[:,:,3]\n return newArray\n\n def normalize(self, normArray):\n def normalize_one_dim(array, maxV=1, minV=0, high=1, low=-1):\n return (high - (((high - low) * (maxV - array)) / (maxV - minV)))\n\n Array = normArray.copy()\n # GooG\n maxV = [2.34,9,9,9,1,1,941.79,680]\n minV = [0.12,0,0,0,0,0,916.13,0.6]\n # Syn32\n #maxV = [1.8,9,9,9,1,1,1,2]\n #minV = [1.5,0,0,0,0,0,-1,0]\n # Syn64\n #maxV = [3.8,9,9,9,1,1,1,2]\n #minV = [3.5,0,0,0,0,0,-1,0]\n #PN\n #maxV = [46.5,9,9,9,1,1,12.68,635]\n #minV = [12.7,0,0,0,0,0,6.41,0.82]\n #PN\n #maxV = [46.5,9,9,9,1,1,12.68,635]\n #minV = [6.54,0,0,0,0,0,6.41,0.8]\n if Array.shape[2] == 4:\n for i in range(Array.shape[2]):\n Array[:,:,i] = normalize_one_dim(normArray[:,:,i],maxV=maxV[i+4],minV=minV[i+4])\n return Array\n else:\n newArray = np.zeros((Array.shape[0],Array.shape[1],8))\n newArray[:,:,0] = Array[:,:,0]\n newArray[:,:,4:] = Array[:,:,2:]\n re = Array[:,:,1].astype(int)\n newArray[:,:,3] = re % 10\n re = re // 10\n newArray[:,:,2] = re % 10\n newArray[:,:,1] = re // 10\n for i in range(newArray.shape[2]):\n newArray[:,:,i] = normalize_one_dim(newArray[:,:,i],maxV=maxV[i],minV=minV[i])\n return newArray\n\n\n\n def predict(self,save_path='predict_goog_short_5000.npy',length=4000000,step_size=1,num_runs=1):\n def translate_time(time):\n transfered_time = []\n for _ in range(6):\n r = time % 10\n transfered_time.insert(0,r)\n time = time // 10\n return transfered_time\n\n data = np.load(self.data_path, mmap_mode='r')\n gen = load_model('gnr_goog_short_5000')\n #re = np.zeros((num_runs,length*step_size+self.historyLength,2))\n generated_orders = np.zeros((num_runs, length*step_size+self.historyLength,6))\n for j in range(num_runs):\n #history = self.normalize(data[0,0:1,:self.historyLength,:,0])\n history = np.ones((1,1))*(0-11.5)/11.5\n history_full = np.mean(self.normalize(data[0,0:1,:100,6:,0]),1)\n #generated_orders[j,:self.historyLength,:] = self.denormalize(history)\n for i in range(length):\n noise = np.random.normal(0,0.05,size=[1, self.noiseLength])\n noise_1 = np.random.uniform(-1,1,size=[1, self.noiseLength_1])\n result = np.zeros((1,1,1))\n for k in range(1):\n orderStreams = self.denormalize(np.squeeze(gen.predict([history,history_full,noise,noise_1]),-1))\n generated_orders[j,self.historyLength+ i * step_size : self.historyLength+(i+1)*step_size,2:] = orderStreams[:,:,2:]\n interval = orderStreams[0,:,:2]\n #re[j,self.historyLength + i * step_size : self.historyLength+(i+1)*step_size,:] = interval\n result[k,:,0] = np.round(interval[:,0] * interval[:,1])\n result_ave = np.mean(result,0)\n r = generated_orders[j:j+1,self.historyLength + i*step_size - 1,0] + result_ave\n generated_orders[j,self.historyLength + i * step_size : self.historyLength+(i+1)*step_size,0] = r\n history = (np.floor(generated_orders[j:j+1,self.historyLength+ (i+1)*step_size -1,0]/10000) - 11.5)/11.5\n history_full = np.mean(self.normalize(generated_orders[j:j+1,(i+1)*step_size : self.historyLength+ (i+1)*step_size,2:]),1)\n if history > 1:\n break\n if(i % 100 == 0 ):\n print(str(j)+' runs ' + str(i)+' steps')\n print(result_ave,history*11.5 + 11.5)\n np.save(save_path,generated_orders)\n #np.save('interval.npy',re)\n","sub_path":"old_code/lstm_cond_wgan_6.py","file_name":"lstm_cond_wgan_6.py","file_ext":"py","file_size_in_byte":17336,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"572689012","text":"import numpy as np\nimport cv2\nfrom scipy import interpolate\nfrom scipy import ndimage\nfrom scipy import sparse\nimport scipy.sparse.linalg as linalg # import spsolve\n\n#ffmpeg -i ./%06d.jpg will.mp4\n\n### Setup \n\ndt = 0.01\n\nimg = cv2.imread('fajar-2.jpg')\n# make image smaller to make run faster if you want\n#img = cv2.pyrDown(img)\n#img = cv2.pyrDown(img)\n\nNx = img.shape[0]\nNy = img.shape[1] \n\n\nv = np.zeros((Nx,Ny,2))\n\nx = np.linspace(0,1,Nx, endpoint=False) \ny = np.linspace(0,1,Ny, endpoint=False) \nX, Y = np.meshgrid(x,y, indexing='ij')\n\n#v[:,:,0] = -Y + 0.5\n#v[:,:,1] = X - 0.5\n\n\n#### Build necessary derivative and interpolation matrices\n\ndef build_grad(N):\n # builds N-1 x N finite difference matrix \n data = np.array([-np.ones(N), np.ones(N-1)])\n return sparse.diags(data, np.array([0, 1]), shape= (N-1,N))\n\n# gradient operators\ngradx = sparse.kron(build_grad(Nx), sparse.identity(Ny-1))\ngrady = sparse.kron(sparse.identity(Nx-1), build_grad(Ny))\n\ndef build_K(N):\n # builds N-1 x N - 1 K second defivative matrix\n data = np.array([-np.ones(N-2), 2*np.ones(N-1), -np.ones(N-2)])\n diags =np.array([-1, 0, 1])\n return sparse.diags(data, diags )\n\n# Laplacian operator . Zero dirichlet boundary conditions\n# why the hell is this reversed? Sigh.\nK = sparse.kronsum(build_K(Ny),build_K(Nx))\nKsolve = linalg.factorized(K)\n\ndef build_interp(N):\n data = np.array([np.ones(N)/2., np.ones(N-1)/2.])\n diags = np.array([0, 1])\n return sparse.diags(data, diags, shape= (N-1,N))\ninterpy = sparse.kron(sparse.identity(Nx), build_interp(Ny))\ninterpx = sparse.kron(build_interp(Nx), sparse.identity(Ny))\n\n\ndef projection_pass(vx,vy):\n # alternating projection? Not necessary. In fact stupid. but easy.\n '''\n vx[0,:] = 0\n vx[-1,:] = 0\n vy[:,0] = 0\n vy[:,-1] = 0\n '''\n vx[0,:] /= 2.\n vx[-1,:] /= 2.\n vy[:,0] /= 2.\n vy[:,-1] /= 2.\n\n div = gradx.dot(vx.flatten()) + grady.dot(vy.flatten()) #calculate divergence\n\n w = Ksolve(div.flatten())#spsolve(K, div.flatten()) #solve potential\n\n return gradx.T.dot(w).reshape(Nx,Ny-1), grady.T.dot(w).reshape(Nx-1,Ny)\n\nfor i in range(600):\n #while True: #\n v[:,:,0] += np.linalg.norm(img,axis=2) * dt * 0.001 # gravity force\n\n # interpolate onto edges\n vx = interpy.dot(v[:,:,0].flatten()).reshape(Nx,Ny-1)\n vy = interpx.dot(v[:,:,1].flatten()).reshape(Nx-1,Ny)\n # project incomperessible\n\n dvx, dvy = projection_pass(vx,vy)\n\n #interpolate change back to original grid\n v[:,:,0] -= interpy.T.dot(dvx.flatten()).reshape(Nx,Ny)\n v[:,:,1] -= interpx.T.dot(dvy.flatten()).reshape(Nx,Ny)\n\n #advect everything\n coords = np.stack( [(X - v[:,:,0]*dt)*Nx, (Y - v[:,:,1]*dt)*Ny], axis=0)\n print(coords.shape)\n print(v.shape)\n for j in range(3):\n img[:,:,j] = ndimage.map_coordinates(img[:,:,j], coords, order=5, mode='wrap')\n v[:,:,0] = ndimage.map_coordinates(v[:,:,0], coords, order=5, mode='wrap')\n v[:,:,1] = ndimage.map_coordinates(v[:,:,1], coords, order=5, mode='wrap')\n cv2.imshow('image',img)\n cv2.imwrite(f'fajar-2/{i:06}.jpg',img)\n k = cv2.waitKey(30) & 0xFF\n if k == ord(' '):\n break\n\ncv2.destroyAllWindows()\n\n\n","sub_path":"simulation.py","file_name":"simulation.py","file_ext":"py","file_size_in_byte":3185,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"316705828","text":"import json\nimport requests\nimport request_obj\nimport mylogger\n\n\ndef scenario(protocol, host, path):\n \"\"\"APIから一覧情報を取得する\n 成功した場合、True, 失敗した場合、Falseを返却する\n \"\"\"\n request1 = request_obj.RequestObj(protocol, host, path)\n request1.set_headers(\"custom-token\", \"custom-token-value\")\n request1.set_cookie(\"custom-session\", \"custom-session-value\")\n request1.set_param(\"param1\", \"value1\")\n request1.set_param(\"param2\", \"value2\")\n response = request1.exec_get(\"./data/response.json\")\n if response is None:\n return False\n else:\n return True\n","sub_path":"scenario3.py","file_name":"scenario3.py","file_ext":"py","file_size_in_byte":634,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"388762119","text":"# -*- coding: utf-8 -*-\n\nfrom django.db.models.loading import get_model\n\n\ndef create_wiki_page(id, owner, project, save=True):\n model = get_model(\"wiki\", \"WikiPage\")\n\n instance = model(\n slug=\"wikipage-{0}\".format(id),\n content=\"WikiPage {0}\".format(id),\n project=project,\n owner=owner\n )\n\n if save:\n instance.save()\n return instance\n","sub_path":"taiga/projects/wiki/tests/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":380,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"397791810","text":"from django import forms\nfrom .models import Profesor\n\nfrom django.forms.models import inlineformset_factory\n\nfrom django.forms import SelectDateWidget\n\n\n\nclass ProfesorForm(forms.ModelForm):\n \n class Meta:\n model = Profesor\n fields = ['nombre','apellidos','documento','licenciatura','telefono','roles']\n\n def __init__(self, *args, **kwargs):\n super(ProfesorForm, self).__init__(*args, **kwargs)\n for field in iter(self.fields):\n self.fields[field].widget.attrs.update({\n 'class': 'form-control'\n })\n \n\n\nclass crearprofesor(forms.ModelForm):\n class Meta:\n fields=[\n 'nombre','apellidos','documento','licenciatura','telefono','roles'\n ]\n\n labels={\n 'nombre':'Nombre','apellidos':'Apellidos','documento':'Documento','licenciatura':'licenciatura','telefono':'telefono','roles':'rolesw'\n }\n\n widgets={\n 'nombre': forms.TextInput(attrs={'class':'form-control'}),\n 'apellidos': forms.TextInput(attrs={'class':'form-control'}),\n 'documento': forms.TextInput(attrs={'class':'form-control'}),\n 'licenciatura': forms.TextInput(attrs={'class':'form-control'}),\n \n 'telefono': forms.TextInput(attrs={'class':'form-control'}),\n 'roles':forms.Select(attrs={'class':'form-control'}),\n }","sub_path":"escuelapp/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":1404,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"310949911","text":"\"\"\"\nStudent: Asaf Yosef Ben Shabat\nID: 312391774\nAssignment no. 5\nProgram: question number 2\n\"\"\"\n\n\ndef divide_number(number, list_of_dividers=[]):\n if number < 0: # in case user entered negative number\n return print(\"Error!\")\n if (number == 1 or number == 0) and len(list_of_dividers) == 0: # in case user entered \"1\" or \"0\"\n return print(number)\n if number == 1:\n list_of_dividers.reverse()\n return print(*list_of_dividers, sep=\"*\") # prints the number with *\n for i in range(2, number + 1):\n if number % i == 0:\n list_of_dividers.append(i)\n return divide_number(number // i)\n\n\nnumber = input(\"Please enter a number:\")\nwhile number.isdigit() is False: # int input validation\n number = input(\"wrong input, please enter a positive number or e for exit:\")\n if number.lower() == 'e':\n break\nelse:\n divide_number(int(number))\n","sub_path":"HomeWork_5/question2.py","file_name":"question2.py","file_ext":"py","file_size_in_byte":917,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"542230497","text":"\nfrom collections import defaultdict\n\n#this recursive function will cause maximum recursion depth error\ndef get_collatz_length_wrong(n, count = 1):\n if (n == 1):\n return count\n elif (n % 2 == 0): #if n is even\n n = n/2\n count += 1\n return get_collatz_length(n, count)\n else: #if n is odd\n n = 3 * n + 1\n count += 1\n return get_collatz_length(n, count)\n\n\n#iterative algorithm to get length of Collatz chain\ndef get_collatz_length(n):\n count = 1\n while (n != 1):\n if (n % 2 == 0): #if n is even\n n = n / 2\n else: #if n is odd\n n = 3 * n + 1\n count += 1\n #print (\"count\",count)\n return count\n\ndef get_longest_collatz_chain():\n max_length = 0\n starting_number = 0\n for x in range(1,1000000):\n #print (\"here1\")\n #cur_chain_length = 0\n #print (\"calculating chain length for\", x)\n cur_chain_length = get_collatz_length(x)\n print (\"starting number and length:\", x, cur_chain_length)\n if cur_chain_length > max_length:\n max_length = cur_chain_length\n starting_number = x\n return (starting_number, max_length)\n\nprint (get_longest_collatz_chain())\n#NOTE: THIS TAKES A COUPLE OF MINUTES TO RUN\n\n","sub_path":"EulerProjectProblem14.py","file_name":"EulerProjectProblem14.py","file_ext":"py","file_size_in_byte":1287,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"158482003","text":"import requests # requests library for get/post\nimport lxml.html # lxml library mainly for prettify()\nfrom requests import Session # Session objects for log-ins\nfrom bs4 import BeautifulSoup # Formatting tool for debug\n\nfrom config import userName # used another file to store login\nfrom config import passWord \n\ndef redirectChecker(requestObject): #function to detect redirects\n if requestObject.history:\n print(\"Request was redirected:\")\n for resp in requestObject.history:\n print(\"Here is the redirected link\")\n print(resp.status_code, resp.url)\n print(\"\")\n print(\"Here are the cookies present at said link\")\n print(resp.cookies)\n print(\"========\")\n print(\"Final destination:\")\n print(requestObject.status_code, requestObject.url)\n print(response.cookies)\n else:\n print(\"Request was not redirected\")\n\ndef divider(): #function to divide segments for debug\n print(\"============================\")\n\nURL_SITE = \"https://my.fullerton.edu/Portal/Dashboard/\" #section of sites saved as variables\nDEST_SITE = \"https://csufullerton.instructure.com/\"\n\npayload = {\n 'j_username' : userName,\n 'j_password' : passWord\n} #will be used as data variable for .post functions\n #needs tweaking; as it doesn't seem to work\n #(COULD BE MISSING POTENTIAL HIDDEN FIELDS)\n\ngenerated_LOGIN = \"initially empty\" #individual jSESSION website generated by URL_SITE\n\ndivider() \n################################################\ns = requests.Session() # creating the Session object\n\nresponse = s.get(URL_SITE) \nredirectChecker(response)\n\ngenerated_LOGIN = response.url # final redirect gives us session's unique jSESSION website\n\ndivider()\n##################################################\nlogin_post = s.post(generated_LOGIN, data=payload) # POSTing payload for logging in; doesn't seem to work though\nredirectChecker(login_post)\n\ndivider()\n###################################################\ncanvas_get = s.get(DEST_SITE) # Authentication fails...\nredirectChecker(canvas_get) # This means that the log-in fails above\n\ndivider()\n####################################################\nsoup = BeautifulSoup(canvas_get.content, 'lxml')\nprint(soup.prettify())\n\ndivider()\n#####################################################\n\n\n\n\n \n\n \n\n\n\n \n\n\n","sub_path":"loginNOselenium.py","file_name":"loginNOselenium.py","file_ext":"py","file_size_in_byte":2452,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"492780964","text":"#!/usr/bin/env python\n\"\"\"\nScript to install pipelines that can deploy the edx-mktg site.\n\"\"\"\nimport sys\nfrom os import path\n\nfrom gomatic import BuildArtifact, FetchArtifactFile, FetchArtifactTask\n\n# Used to import edxpipelines files - since the module is not installed.\nsys.path.append(path.dirname(path.dirname(path.dirname(path.abspath(__file__)))))\n\n# pylint: disable=wrong-import-position\nfrom edxpipelines import constants\nfrom edxpipelines.patterns import tasks\nfrom edxpipelines.pipelines.script import pipeline_script\nfrom edxpipelines.materials import (TUBULAR, EDX_MKTG, ECOM_SECURE)\n\n\ndef install_pipelines(configurator, config):\n \"\"\"\n Install pipelines that can deploy the edx-mktg site.\n \"\"\"\n pipeline = configurator \\\n .ensure_pipeline_group(constants.DRUPAL_PIPELINE_GROUP_NAME) \\\n .ensure_replacement_of_pipeline(constants.DEPLOY_MARKETING_PIPELINE_NAME) \\\n .ensure_material(TUBULAR()) \\\n .ensure_material(EDX_MKTG()) \\\n .ensure_material(ECOM_SECURE())\n\n pipeline.ensure_environment_variables(\n {\n 'MARKETING_REPOSITORY_VERSION': config['mktg_repository_version'],\n }\n )\n\n pipeline.ensure_encrypted_environment_variables(\n {\n 'PRIVATE_GITHUB_KEY': config['github_private_key'],\n 'PRIVATE_ACQUIA_REMOTE': config['acquia_remote_url'],\n 'PRIVATE_ACQUIA_USERNAME': config['acquia_username'],\n 'PRIVATE_ACQUIA_PASSWORD': config['acquia_password'],\n 'PRIVATE_ACQUIA_GITHUB_KEY': config['acquia_github_key']\n }\n )\n\n # Stage to fetch the current tag names from stage and prod\n fetch_tag_stage = pipeline.ensure_stage(constants.FETCH_TAG_STAGE_NAME)\n fetch_tag_stage.set_has_manual_approval()\n fetch_tag_job = fetch_tag_stage.ensure_job(constants.FETCH_TAG_JOB_NAME)\n tasks.generate_package_install(fetch_tag_job, 'tubular')\n tasks.generate_target_directory(fetch_tag_job)\n path_name = '../target/{env}_tag_name.txt'\n tasks.generate_fetch_tag(fetch_tag_job, constants.STAGE_ENV, path_name)\n tasks.generate_fetch_tag(fetch_tag_job, constants.PROD_ENV, path_name)\n\n fetch_tag_job.ensure_artifacts(\n set([BuildArtifact('target/{stage_tag}.txt'.format(stage_tag=constants.STAGE_TAG_NAME)),\n BuildArtifact('target/{prod_tag}.txt'.format(prod_tag=constants.PROD_TAG_NAME))])\n )\n\n # Stage to create and push a tag to Acquia.\n push_to_acquia_stage = pipeline.ensure_stage(constants.PUSH_TO_ACQUIA_STAGE_NAME)\n push_to_acquia_job = push_to_acquia_stage.ensure_job(constants.PUSH_TO_ACQUIA_JOB_NAME)\n # Ensures the tag name is accessible in future jobs.\n push_to_acquia_job.ensure_artifacts(\n set([BuildArtifact('target/{new_tag}.txt'.format(new_tag=constants.NEW_TAG_NAME))])\n )\n\n tasks.generate_package_install(push_to_acquia_job, 'tubular')\n tasks.generate_target_directory(push_to_acquia_job)\n\n # Create a tag from MARKETING_REPOSITORY_VERSION branch of marketing repo\n push_to_acquia_job.add_task(\n tasks.bash_task(\n # Writing dates to a file should help with any issues dealing with a job\n # taking place over two days (23:59:59 -> 00:00:00). Only the day can be\n # affected since we don't use minutes or seconds.\n # NOTE: Uses UTC\n \"\"\"\\\n echo -n \"release-$(date +%Y-%m-%d-%H.%M)\" > ../target/{new_tag}.txt &&\n TAG_NAME=$(cat ../target/{new_tag}.txt) &&\n /usr/bin/git config user.email \"admin@edx.org\" &&\n /usr/bin/git config user.name \"edx-secure\" &&\n /usr/bin/git tag -a $TAG_NAME -m \"Release for $(date +%B\\\\ %d,\\\\ %Y). Created by $GO_TRIGGER_USER.\" &&\n /usr/bin/git push origin $TAG_NAME\n \"\"\",\n new_tag=constants.NEW_TAG_NAME,\n working_dir='edx-mktg'\n )\n )\n\n # Set up Acquia remote repo and push tag to Acquia. Change new tag file to contain \"tags/\" for deployment.\n push_to_acquia_job.add_task(\n tasks.bash_task(\n \"\"\"\\\n chmod 600 ../ecom-secure/acquia/acquia_github_key.pem &&\n if [[ $(git remote) != *\"acquia\"* ]]; then\n /usr/bin/git remote add acquia $PRIVATE_ACQUIA_REMOTE ;\n fi &&\n GIT_SSH_COMMAND=\"/usr/bin/ssh -o StrictHostKeyChecking=no -i ../{ecom_secure}/acquia/acquia_github_key.pem\"\n /usr/bin/git push acquia $(cat ../target/{new_tag}.txt) &&\n echo -n \"tags/\" | cat - ../target/{new_tag}.txt > temp &&\n mv temp ../target/{new_tag}.txt\n \"\"\",\n new_tag=constants.NEW_TAG_NAME,\n ecom_secure=ECOM_SECURE().destination_directory,\n working_dir='edx-mktg'\n )\n )\n\n # Stage to backup database in stage\n backup_stage_database_stage = pipeline.ensure_stage(constants.BACKUP_STAGE_DATABASE_STAGE_NAME)\n backup_stage_database_job = backup_stage_database_stage.ensure_job(constants.BACKUP_STAGE_DATABASE_JOB_NAME)\n\n tasks.generate_package_install(backup_stage_database_job, 'tubular')\n tasks.generate_backup_drupal_database(backup_stage_database_job, constants.STAGE_ENV)\n\n # Stage to deploy to stage\n deploy_stage_for_stage = pipeline.ensure_stage(constants.DEPLOY_STAGE_STAGE_NAME)\n deploy_job_for_stage = deploy_stage_for_stage.ensure_job(constants.DEPLOY_STAGE_JOB_NAME)\n\n tasks.generate_package_install(deploy_job_for_stage, 'tubular')\n tasks.generate_target_directory(deploy_job_for_stage)\n\n # fetch the tag name\n constants.new_tag_name_artifact_params = {\n 'pipeline': constants.DEPLOY_MARKETING_PIPELINE_NAME,\n 'stage': constants.PUSH_TO_ACQUIA_STAGE_NAME,\n 'job': constants.PUSH_TO_ACQUIA_JOB_NAME,\n 'src': FetchArtifactFile('{new_tag}.txt'.format(new_tag=constants.NEW_TAG_NAME)),\n 'dest': 'target'\n }\n deploy_job_for_stage.add_task(FetchArtifactTask(**constants.new_tag_name_artifact_params))\n tasks.generate_drupal_deploy(\n deploy_job_for_stage,\n constants.STAGE_ENV,\n '{new_tag}.txt'.format(new_tag=constants.NEW_TAG_NAME)\n )\n\n # Stage to clear caches in stage\n clear_stage_caches_stage = pipeline.ensure_stage(constants.CLEAR_STAGE_CACHES_STAGE_NAME)\n clear_stage_caches_job = clear_stage_caches_stage.ensure_job(constants.CLEAR_STAGE_CACHES_JOB_NAME)\n\n tasks.generate_package_install(clear_stage_caches_job, 'tubular')\n clear_stage_caches_job.add_task(\n tasks.bash_task(\n \"\"\"\n chmod 600 ecom-secure/acquia/acquia_github_key.pem &&\n cp {ecom_secure}/acquia/acquia_github_key.pem {edx_mktg}/docroot/\n \"\"\",\n ecom_secure=ECOM_SECURE().destination_directory,\n edx_mktg=EDX_MKTG().destination_directory\n )\n )\n tasks.generate_flush_drupal_caches(clear_stage_caches_job, constants.STAGE_ENV)\n tasks.generate_clear_varnish_cache(clear_stage_caches_job, constants.STAGE_ENV)\n\n # Stage to backup database in prod\n backup_prod_database_stage = pipeline.ensure_stage(constants.BACKUP_PROD_DATABASE_STAGE_NAME)\n backup_prod_database_stage.set_has_manual_approval()\n backup_prod_database_job = backup_prod_database_stage.ensure_job(constants.BACKUP_PROD_DATABASE_JOB_NAME)\n\n tasks.generate_package_install(backup_prod_database_job, 'tubular')\n tasks.generate_backup_drupal_database(backup_prod_database_job, constants.PROD_ENV)\n\n # Stage to deploy to prod\n deploy_stage_for_prod = pipeline.ensure_stage(constants.DEPLOY_PROD_STAGE_NAME)\n deploy_job_for_prod = deploy_stage_for_prod.ensure_job(constants.DEPLOY_PROD_JOB_NAME)\n\n tasks.generate_package_install(deploy_job_for_prod, 'tubular')\n tasks.generate_target_directory(deploy_job_for_prod)\n deploy_job_for_prod.add_task(FetchArtifactTask(**constants.new_tag_name_artifact_params))\n tasks.generate_drupal_deploy(\n deploy_job_for_prod,\n constants.PROD_ENV,\n '{new_tag}.txt'.format(new_tag=constants.NEW_TAG_NAME)\n )\n\n # Stage to clear caches in prod\n clear_prod_caches_stage = pipeline.ensure_stage(constants.CLEAR_PROD_CACHES_STAGE_NAME)\n clear_prod_caches_job = clear_prod_caches_stage.ensure_job(constants.CLEAR_PROD_CACHES_JOB_NAME)\n\n tasks.generate_package_install(clear_prod_caches_job, 'tubular')\n clear_prod_caches_job.add_task(\n tasks.bash_task(\n \"\"\"\n chmod 600 ecom-secure/acquia/acquia_github_key.pem &&\n cp {ecom_secure}/acquia/acquia_github_key.pem {edx_mktg}/docroot/\n \"\"\",\n ecom_secure=ECOM_SECURE().destination_directory,\n edx_mktg=EDX_MKTG().destination_directory\n )\n )\n tasks.generate_flush_drupal_caches(clear_prod_caches_job, constants.PROD_ENV)\n tasks.generate_clear_varnish_cache(clear_prod_caches_job, constants.PROD_ENV)\n\n\nif __name__ == '__main__':\n pipeline_script(install_pipelines)\n","sub_path":"edxpipelines/pipelines/deploy_marketing_site.py","file_name":"deploy_marketing_site.py","file_ext":"py","file_size_in_byte":8929,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"151524466","text":"# Guess what?!?!?!\n# I am going to make a card game :D\nimport os\nimport random\ncls = 'os.system(\"cls\")'\n\ndef getnum():\n num = False\n while not num:\n try:\n num = int(raw_input(\"=> \"))\n return num\n except:\n print(\"Invalid number\")\n\nclass Cardset():\n\n cards = ['A', '2', '3', '4', '5', '6', '7', '8', '9', '10', 'J', 'Q', 'K']\n suits = ['H', 'C', 'D', 'S']\n names = {'A':'Ace', 'J':'Jack', 'Q':'Queen', 'K':'King',\n 'H':'Hearts', 'C':'Clubs', 'D':'Diamonds', 'S':'Spades'}\n \n cardlist = []\n for x in suits:\n for y in cards:\n cardlist.append(y+x)\n del x, y\n\n values = {}\n for x in range(len(cards)):\n if cards[x] not in ['J', 'Q', 'K']: values[cards[x]] = x + 1\n else: values[cards[x]] = 10\n\n def repr(self, card):\n s = ''\n if card[0] in self.names: s += (self.names[card[0]])\n elif card[0] not in self.names: s += (card[0])\n s += (\" of \")\n if card[1] in self.names: s += (self.names[card[1]])\n elif card[1] not in self.names: s += (card[1])\n return s\n\n def returnvalue(self, card):\n return self.values[card[0]]\n\n def checkscoreBJ(self, cardlist):\n score = 0\n aces = 0\n for x in cardlist:\n if x[0] != 'A': score += self.returnvalue(x)\n elif x[0] == 'A': aces += 1\n for x in range(aces):\n if score <= 10:\n score += 11\n elif score > 10:\n score += 1\n if (\n (\n (cardlist[0][0] == 'A') or (cardlist[1][0] == 'A')\n ) \\\n and \\\n (\n (cardlist[0] == 'JS') or (cardlist[1] == 'JS')\n )\n and \\\n (len(cardlist) == 2)\n ):\n return 'BJ'\n return score\n\n def checkscore21(self, cardlist):\n score = 0\n aces = 0\n for x in cardlist:\n if x[0] != 'A': score += self.returnvalue(x)\n elif x[0] == 'A': aces += 1\n for x in range(aces):\n if score <= 10:\n score += 11\n elif score > 10:\n score += 1\n return score\n\n def cardsets(self, num):\n self.cardlist *= num\n\n def cardshuffle(self, num):\n for x in range(num):\n random.shuffle(self.cardlist)\n\n def draw(self, ran=0):\n if ran == 1: return self.cardlist.pop(random.randint(0, len(self.cardlist)))\n return self.cardlist.pop(0)\n\n# Poker Variations \n\n##class PokerBasic(Cardset):\n##\n## ranks = ['Pair',\n## 'Two Pair',\n## 'Three of a Kind',\n## 'Straight',\n## 'Flush',\n## 'Full House',\n## 'Four of a Kind',\n## 'Straight Flush',\n## 'Royal Straight Flush']\n##\n## class Player(PokerBasic):\n##\n## hand = []\n##\n## def _draw(self):\n## self.hand.append(self.draw())\n##\n## def __init__(self):\n## if len(self.cardlist) < 10:\n## self.cardlist == []\n## for x in self.suits:\n## for y in self.cards:\n## self.cardlist.append(y+x)\n## self.cardsets(1)\n## self.cardshuffle(50)\n\n# BlackJack - 21\n\nclass G21(Cardset):\n\n turnchoices = ['Hit', 'Stand']\n CODES = {\n '00':'Successful Player hit',\n '01':'Successful Player stand',\n '0F':'Player bust',\n '10':'Computer hit?',\n '11':'Computer stand',\n '1F':'Computer bust',\n '21':'Player win',\n '22':'Computer win',\n '30':'PUSH'\n }\n\n def turn(self):\n print(\"1) Hit\\n2) Stand\")\n choice = getnum()\n if choice == 1: return self.hit()\n if choice == 2: return self.stand()\n\n def hit(self):\n self.playerhand.append(self.draw())\n if self.checkscore21(self.playerhand) > 21: return '0F'\n return '00'\n\n def stand(self):\n return '01'\n\n def aihit(self):\n self.computerhand.append(self.draw())\n\n def addcards(self):\n cardlist = []\n for x in self.suits:\n for y in self.cards:\n cardlist.append(y+x)\n self.cardlist += cardlist*6\n\n def run(self):\n # What happens if the deck is getting low?\n if len(self.cardlist) < 35:\n self.addcards()\n self.cardshuffle(40)\n # Create the player's Hands\n self.playerhand = []\n self.computerhand = []\n # These two values are for debugging, and for running the program\n # // Check the begining of the class for a definition of the codes\n code = ''\n compcode = ''\n # Each player draws two cards\n for x in range(2):\n self.playerhand.append(self.draw())\n self.computerhand.append(self.draw())\n # A Player Turn\n while True:\n eval(cls)\n print(\"Dealer shows:\")\n print(str(self.repr(self.computerhand[0])))\n print(\"\")\n print(\"Your hand:\")\n for x in self.playerhand:\n print(str(self.repr(x)))\n print(\"Total: \"+str(self.checkscore21(self.playerhand)))\n if self.checkscore21(self.playerhand) == 21: print(\"It is recommended that you stand\")\n print(\"\")\n if code == '0F': print(\"YOU BUST: \"+str(self.checkscore21(self.playerhand))); code = '22'; break\n if code == '01': break\n code = ''\n code = self.turn()\n print(\"\")\n\n # Computer (Dealer) turn\n if code == '01':\n while True:\n eval(cls)\n print(\"Your hand:\")\n for x in self.playerhand:\n print(str(self.repr(x)))\n print(\"Total: \"+str(self.checkscore21(self.playerhand)))\n print(\"\\n\")\n print(\"The dealer shows:\")\n for x in self.computerhand:\n print(str(self.repr(x)))\n print(\"Dealer Total: \"+str(self.checkscore21(self.computerhand)))\n print(\"\")\n if self.checkscore21(self.computerhand) > 21: compcode = '1F'; break\n elif self.checkscore21(self.computerhand) > self.checkscore21(self.playerhand): compcode = '11'; break\n elif self.checkscore21(self.computerhand) in range(17, 22): compcode = '11'; break\n else: raw_input(\"Please press 'Enter' to continue\"); self.aihit(); compcode = '10'\n if compcode == '1F': code = '21'\n elif (self.checkscore21(self.computerhand) > self.checkscore21(self.playerhand)): code = '22'\n elif (self.checkscore21(self.computerhand) < self.checkscore21(self.playerhand)): code = '21'\n elif (self.checkscore21(self.computerhand) == self.checkscore21(self.playerhand)): code = '30'\n\n # Return if you won, lost, or pushed\n print(\"\")\n if code == '21': print(\"Congratulations, you won!\")\n elif code == '22': print(\"Sadly, the dealer won\")\n elif code == '30': print(\"You and the dealer have pushed!\")\n return code\n\n def __init__(self):\n if len(self.cardlist) != 312:\n self.cardlist == []\n for x in self.suits:\n for y in self.cards:\n self.cardlist.append(y+x)\n self.cardsets(6)\n self.cardshuffle(40)\n# 21 Game code\ndef main():\n os.system('title Cards - 21')\n os.system('color 05')\n def ask():\n colors = {'black':'0', 'blue':'1', 'green':'2', 'aqua':'3', 'red':'4', 'purple':'5', 'yellow':'6', 'white':'7', 'gray':'8', 'light blue':'9', 'light green':'A', 'light aqua':'B', 'light red':'C', 'light purple':'D', 'light yellow':'E', 'bright white':'F'}\n r = raw_input(\"Y/N: \")\n if (r == 'Y') or (r == 'y') or (r == 'Yes') or (r == 'yes') or (r == '1'): pass\n elif (r.upper() == 'CHECK'): print(\"Win: \"+str(win)+\"\\n\"+\"Loss: \"+str(loss)+\"\\n\"+\"Tie: \"+str(tie)+\"\\n\"); ask()\n elif (r.lower() == 'cards'): print(len(G.cardlist)); ask()\n elif (r.lower() == 'cardlist'): print(G.cardlist); ask()\n elif (r == ''): print(\"Please Enter something\"); ask()\n elif (r.lower()[0:5] == 'color'):\n try:\n os.system('color 0'+colors[r[6:]])\n except:\n try:\n os.system('color 0'+r[6])\n except:\n print(\"Unrecoginized color\")\n ask()\n elif (r == 'shuffle'): G.cardshuffle(40); ask()\n elif (r.lower() == 'n') or (r.lower() == 'no') or (r.lower() == 'exit') or (r.lower() == 'quit') or (r == '0'): print(\"Thank you for playing!\"); raw_input(\"Please press 'Enter' to quit\"); quit()\n else: ask()\n print(\"To enter a selection when playing, enter the number and press 'Enter'\")\n raw_input(\"Please press 'Enter' to continue\")\n eval(cls)\n G = G21()\n win = 0\n loss = 0\n tie = 0\n while True:\n code = G.run()\n if code == '21': win += 1\n if code == '22': loss += 1\n if code == '30': tie += 1\n print(\"Would you like to play again?\")\n ask()\n\n# Menu Code\n\nclass _Menu():\n\n B21win = 0\n B21loss = 0\n B21tie = 0\n\n def header(self):\n eval(cls)\n print(\"\"\"\\\nCard Game Suite\n ~ Hondros\"\"\")\n print(\"\")\n\n def _help(self):\n self.header()\n print('''\\\n21 is a variation of the game Blackjack\nThe only difference between these games, is that\n you cannot get a Blackjack when playing 21\nPay-Out is always 1:1, not 2:1 as if you were going to get a blackjack\n\nTo navigate menus, simply type the number, and press 'Enter'\n\nAfter you play a round, you can check you stats (among other things)\n by entering the following:\n check\\t\\tCheck your win/lose/tie stats\n cards\\t\\tHow many cards are left in the deck\n cardlist\\tWhat cards are on the stack\n shuffle\\tShuffle the current cardlist\n color\\t\\tChange the color of the text (Leave blank for help)\n'''); raw_input(\"Press 'Enter' to continue\")\n\n def info(self):\n self.header()\n print('''\\\nThis game was Created by:\n Hondros (Alex Polosky)\nIf any bugs are found, or you need serious help (With this game):\n feel free to contact him at:\n alexpolosky@gmail.com\n'''); raw_input(\"Press 'Enter' to continue\")\n\n def main(self):\n os.system('title Cards - 21')\n def ask():\n colors = {'black':'0', 'blue':'1', 'green':'2', 'aqua':'3', 'red':'4', 'purple':'5', 'yellow':'6', 'white':'7', 'gray':'8', 'light blue':'9', 'light green':'A', 'light aqua':'B', 'light red':'C', 'light purple':'D', 'light yellow':'E', 'bright white':'F'}\n r = raw_input(\"Y/N: \")\n if (r == 'Y') or (r == 'y') or (r == 'Yes') or (r == 'yes') or (r == '1'): pass\n elif (r.upper() == 'CHECK'): print(\"Win: \"+str(self.B21win)+\"\\n\"+\"Loss: \"+str(self.B21loss)+\"\\n\"+\"Tie: \"+str(self.B21tie)+\"\\n\"); ask()\n elif (r.lower() == 'cards'): print(len(self.G.cardlist)); ask()\n elif (r.lower() == 'cardlist'): print(self.G.cardlist); ask()\n elif (r == ''): print(\"Please Enter something\"); ask()\n elif (r.lower()[0:5] == 'color'):\n try:\n os.system('color 0'+colors[r[6:]])\n except:\n try:\n os.system('color 0'+r[6])\n except:\n print(\"Unrecoginized color\")\n ask()\n elif (r == 'shuffle'): self.G.cardshuffle(40); ask()\n elif (r.lower() == 'n') or (r.lower() == 'no') or (r.lower() == 'exit') or (r.lower() == 'quit') or (r == '0'): print(\"Exiting Blackjack - 21\"); self.__init__(1)\n else: ask()\n eval(cls)\n if 'G' not in vars(self): self.G = G21()\n while True:\n code = self.G.run()\n if code == '21': self.B21win += 1\n if code == '22': self.B21loss += 1\n if code == '30': self.B21tie += 1\n print(\"Would you like to play again?\")\n ask()\n\n def opts(self):\n self.header()\n print(\"\"\"\\\n1) Debug\n2) Shuffle Cards\n3) Text Color\n4) Stats\n5) Go back\n\"\"\")\n choice = getnum()\n if choice == 1:\n pass\n elif choice == 2:\n try:\n G.cardshuffle(40)\n except:\n pass\n elif choice == 3:\n print(\"Choose a color:\")\n colors = {'black':'0', 'blue':'1', 'green':'2', 'aqua':'3', 'red':'4', 'purple':'5', 'yellow':'6', 'white':'7', 'gray':'8', 'light blue':'9', 'light green':'A', 'light aqua':'B', 'light red':'C', 'light purple':'D', 'light yellow':'E', 'bright white':'F'}\n for x in colors:\n print(x)\n print(\"\")\n r = raw_input(\"=> \")\n try:\n os.system('color 0'+colors[r])\n except:\n try:\n os.system('color 0'+r)\n except:\n print(\"Unrecoginized color\")\n elif choice == 4:\n print(\"Win: \"+str(self.B21win)+\"\\n\"+\"Loss: \"+str(self.B21loss)+\"\\n\"+\"Tie: \"+str(self.B21tie)+\"\\n\")\n raw_input(\"Press 'Enter' to continue\")\n \n def __init__(self, ran=0):\n os.system('title Cards')\n if ran == 0: os.system('color 05')\n choice = 0\n if ran == 0: print(\"To navigate the menu, type a number and press 'Enter'\"); raw_input(\"Press 'Enter' to continue\")\n self.header()\n print(\"\"\"\\\n1) Play Blackjack - 21\n2) Info\n3) Help\n4) Options\n5) Quit\n6) Extensive 21 help\"\"\")\n choice = getnum()\n if choice == 1: self.main()\n if choice == 2: self.info(); self.__init__(1)\n if choice == 3: self._help(); self.__init__(1)\n if choice == 4: self.opts(); self.__init__(1)\n if choice == 6: self.__init__(1)\n if choice == 5: print(\"Thank you for playing!\"); raw_input(\"Please press 'Enter' to quit\"); quit()\n\nif __name__ == \"__main__\":\n M = _Menu()\n","sub_path":"Python/Python scripts/client/games/Cards/Cards.py","file_name":"Cards.py","file_ext":"py","file_size_in_byte":14112,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"63811510","text":"import unittest\nimport numpy as np\nfrom mr_utils import view\n\nclass GSReconTestCase(unittest.TestCase):\n\n def setUp(self):\n from mr_utils.sim.ssfp import ssfp\n\n self.TR = 6e-3\n self.T1,self.T2 = 1,.8\n self.alpha = np.pi/3\n\n # To get periodic banding like we want to see, we need some serious\n # field inhomogeneity.\n dim = 256\n min_df,max_df = 0,500\n x = np.linspace(min_df,max_df,dim)\n y = np.zeros(dim)\n self.field_map,_ = np.meshgrid(x,y)\n\n # Get four phase cycled images\n self.I1 = ssfp(self.T1,self.T2,self.TR,self.alpha,self.field_map,phase_cyc=0)\n self.I2 = ssfp(self.T1,self.T2,self.TR,self.alpha,self.field_map,phase_cyc=np.pi/2)\n self.I3 = ssfp(self.T1,self.T2,self.TR,self.alpha,self.field_map,phase_cyc=np.pi)\n self.I4 = ssfp(self.T1,self.T2,self.TR,self.alpha,self.field_map,phase_cyc=3*np.pi/2)\n\n def test_gs_recon(self):\n from mr_utils.recon.ssfp import gs_recon_for_loop,gs_recon\n\n # Make sure it doesn't matter if we go pixel by pixel or do the whole\n # matrix at once\n I0 = gs_recon_for_loop(self.I1,self.I2,self.I3,self.I4)\n I1 = gs_recon(self.I1,self.I2,self.I3,self.I4)\n self.assertTrue(np.allclose(I0,I1))\n\n def test_max_magnitudes(self):\n from mr_utils.recon.ssfp import get_max_magnitudes_for_loop,get_max_magnitudes\n\n # Make sure it doesn't matter if we go pixel by pixel or do the whole\n # matrix at once\n I0 = get_max_magnitudes_for_loop(self.I1,self.I2,self.I3,self.I4)\n I1 = get_max_magnitudes(self.I1,self.I2,self.I3,self.I4)\n self.assertTrue(np.allclose(I0,I1))\n\n def test_noisy_gs_recon(self):\n from mr_utils.recon.ssfp import gs_recon,gs_recon_for_loop\n\n # Add in gaussian noise on both real,imag channels\n m,std = 0,.08\n n1 = np.random.normal(m,std,size=self.I1.shape) + 1j*np.random.normal(m,std,size=self.I1.shape)\n n2 = np.random.normal(m,std,size=self.I1.shape) + 1j*np.random.normal(m,std,size=self.I1.shape)\n n3 = np.random.normal(m,std,size=self.I1.shape) + 1j*np.random.normal(m,std,size=self.I1.shape)\n n4 = np.random.normal(m,std,size=self.I1.shape) + 1j*np.random.normal(m,std,size=self.I1.shape)\n\n I0 = gs_recon(self.I1 + n1,self.I2 + n2,self.I3 + n3,self.I4 + n4)\n I1 = gs_recon_for_loop(self.I1 + n1,self.I2 + n2,self.I3 + n3,self.I4 + n4)\n self.assertTrue(np.allclose(I0,I1))\n\n def test_gs_recon3d(self):\n from mr_utils.recon.ssfp import gs_recon,gs_recon3d\n\n # Try individually\n I0 = gs_recon(self.I1,self.I2,self.I3,self.I4)\n I0 = np.stack((I0,gs_recon(self.I1,self.I2,self.I3,self.I4)),axis=-1)\n I1 = gs_recon3d(np.stack((self.I1,self.I1),axis=-1),np.stack((self.I2,self.I2),axis=-1),np.stack((self.I3,self.I3),axis=-1),np.stack((self.I4,self.I4),axis=-1))\n self.assertTrue(np.allclose(I0,I1))\n\n\nclass GSReconKneeData(unittest.TestCase):\n\n def setUp(self):\n from mr_utils.test_data import EllipticalSignal\n\n # Load in truth data\n self.I1 = EllipticalSignal.I1()\n self.I2 = EllipticalSignal.I2()\n self.I3 = EllipticalSignal.I3()\n self.I4 = EllipticalSignal.I4()\n self.I_max_mag = EllipticalSignal.I_max_mag()\n self.CS = EllipticalSignal.CS()\n self.Id = EllipticalSignal.Id()\n self.w13 = EllipticalSignal.w13()\n self.w24 = EllipticalSignal.w24()\n self.I = EllipticalSignal.I()\n\n def test_max_magnitudes(self):\n from mr_utils.recon.ssfp import get_max_magnitudes\n\n # Make sure we both find the same maximum magnitude values\n I_max_mag_py = get_max_magnitudes(self.I1,self.I2,self.I3,self.I4)\n self.assertTrue(np.allclose(self.I_max_mag,I_max_mag_py))\n\n def test_complex_sum(self):\n from mr_utils.recon.ssfp import complex_sum\n\n CS_py = complex_sum(self.I1,self.I2,self.I3,self.I4)\n self.assertTrue(np.allclose(CS_py,self.CS))\n\n def test_direct_solution(self):\n from mr_utils.sim.ssfp import get_complex_cross_point\n\n Id_py = get_complex_cross_point(self.I1,self.I2,self.I3,self.I4)\n self.assertTrue(np.allclose(Id_py,self.Id))\n\n def test_weighted_combination(self):\n from mr_utils.recon.ssfp import compute_Iw,complex_sum,get_max_magnitudes,get_complex_cross_point\n Iw13 = self.I1*self.w13 + self.I3*(1 - self.w13)\n Iw24 = self.I2*self.w24 + self.I4*(1 - self.w24)\n\n # A little processing to get where we need to to compare weighted combs\n Id = get_complex_cross_point(self.I1,self.I2,self.I3,self.I4)\n CS = complex_sum(self.I1,self.I2,self.I3,self.I4)\n I_max_mag = get_max_magnitudes(self.I1,self.I2,self.I3,self.I4)\n mask = np.abs(Id) > I_max_mag\n Id[mask] = CS[mask]\n Iw13_py = compute_Iw(self.I1,self.I3,Id,patch_size=(5,5))\n\n self.assertTrue(np.allclose(Iw13,Iw13_py))\n\n def test_gs_recon_knee(self):\n from mr_utils.recon.ssfp import gs_recon\n\n I = gs_recon(self.I1,self.I2,self.I3,self.I4)\n self.assertTrue(np.allclose(I,self.I))\n\nif __name__ == '__main__':\n unittest.main()\n","sub_path":"mr_utils/tests/recon/test_gs_recon.py","file_name":"test_gs_recon.py","file_ext":"py","file_size_in_byte":5226,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"99918971","text":"import math\nimport pygame, sys\nfrom pygame.locals import *\n\npygame.init()\nscreen = pygame.display.set_mode((15*50,15*50),pygame.RESIZABLE ,32)\npygame.display.set_caption(\"Window\") \nfontColor = (255,0,0) \nbgColor = (200,200,0)\nmainLoop = True\n\nfullscreen = False\n\n# sounds ----------------------------------------------------------------\n#pygame.mixer.music.load(\"sounds/booooo.wav\")\n#pygame.mixer.music.play()\n\n# images ----------------------------------------------------------------\nimage_door = pygame.image.load(\"textures/door.png\").convert_alpha()\nimage_door_closed = pygame.image.load(\"textures/door_closed.png\").convert_alpha()\nimage_block = pygame.image.load(\"textures/stone1.png\").convert_alpha()\nimage_wall = pygame.image.load(\"textures/stone_wall.png\").convert_alpha()\nimage_spikes = pygame.image.load(\"textures/spikes.png\").convert_alpha()\nimage_lever = pygame.image.load(\"textures/lever.png\").convert_alpha()\nimage_lever_pushed = pygame.image.load(\"textures/lever_pushed.png\").convert_alpha()\n\n\n# classes ----------------------------------------------------------------\nclass Point:\n x = 0\n y = 0\n def __init__(self, x1, y1):\n self.x = x1\n self.y = y1\n#\nclass Player:\n x = 30\n y = 30\n speed = 50\n color = (255,255,100)\n fX = 0\n fY = 0\n groundFX = 0\n groundFY = 0\n onCeiling = False\n onGround = False\n onLeft = False\n onRight = False\n sizeX = 60\n sizeY = 60\n boxPoints = [Point(-sizeX/2,sizeY/2), Point(sizeX/2,sizeY/2), Point(-sizeX/2,-sizeY/2), Point(sizeX/2,-sizeY/2)]\n\n #DO NOT TOUCH moveByPlatform() and move() functions!!!!!!\n def moveByPlatform(self):\n for platform in map.platforms:\n for point in self.boxPoints:\n if self.x+platform.fX+point.x>platform.x and self.x+platform.fX+point.xplatform.y and self.y+platform.fY+1+point.yplatform.x and self.x+point.xplatform.y and self.y+point.y0:\n self.x += 1\n if platform.fX<0:\n self.x -= 1\n if platform.fX>0:\n self.x -= 1\n elif platform.fX<0:\n self.x += 1\n for i in range(int(math.fabs(platform.fY)+1)):\n if not self.touch():\n if platform.fY>0:\n self.y += 1\n if platform.fY<0:\n self.y -= 1\n if platform.fY>0:\n self.y -= 1\n elif platform.fY<0:\n self.y += 1\n break\n def move(self):\n self.control()\n global gravity\n self.fY += gravity\n \n self.moveByPlatform()\n\n for i in range(int(math.fabs(self.fY))):\n if not self.inBlock():\n if self.fY>0:\n self.y += 1\n self.onCeiling = False\n else:\n self.y -= 1\n self.onGround = False\n elif self.fY>0:\n self.onGround = True\n break\n elif self.fY<0:\n self.onCeiling = True\n break\n if self.fY>0:\n self.y -= 1\n elif self.fY<0:\n self.y += 1\n if self.onGround or self.onCeiling:\n self.fY = 0\n for i in range(int(math.fabs(self.fX))):\n if not self.inBlock():\n if self.fX>0:\n self.x += 1\n elif self.fX<0:\n self.x -= 1\n self.onRight = False\n self.onLeft = False\n elif self.fX>0:\n self.onRight = True\n break\n elif self.fX<0:\n self.onLeft = True\n break\n if self.fX>0:\n self.x -= 1\n elif self.fX<0:\n self.x += 1\n\n return 0\n def control(self):\n if self.blockDanger() and self.onGround:\n self.die()\n\n if keys.right:\n self.fX += 5\n if keys.left:\n self.fX -= 5\n if self.fX > self.speed:\n self.fX = self.speed\n if self.fX < -self.speed:\n self.fX = -self.speed\n if not keys.right and not keys.left:\n self.fX = 0\n if keys.up and self.onGround:\n self.fY = -100\n def cell(self, n):\n return int(math.floor(n/blockSize))\n def cellOffset(self, n):\n n = float(n)\n return n/blockSize-math.floor(n/blockSize)\n def inBlock(self):\n self.groundFX = 0\n for point in self.boxPoints:\n x = self.cell(self.x + point.x)\n y = self.cell(self.y + point.y)\n if map.blocks[y*map.sizeX+x].type==1:\n return True\n for platform in map.platforms:\n if self.x+point.x>platform.x and self.x+point.xplatform.y and self.y+point.yself.x and entity.xself.y and entity.yself.x and entity.xself.y and entity.y0 or \\\n self.blocks[ (y+1) *map.sizeX + (x) ].light>0 or \\\n self.blocks[ (y) *map.sizeX + (x-1) ].light>0 or \\\n self.blocks[ (y) *map.sizeX + (x+1) ].light>0:\n self.blocks[(y) *map.sizeX + (x)].neighbors = True\n else:\n self.blocks[(y)*map.sizeX + (x)].neighbors = False\n def lightStep(self):\n for x in range(self.startPoint.x, self.endPoint.x):\n for y in range(self.startPoint.y, self.endPoint.y):\n if self.blocks[y*map.sizeX + x].neighbors and map.blocks[ (y) *map.sizeX + (x) ].type==0:\n light = self.blocks[y*map.sizeX + x].light\n if self.blocks[ (y-1) *map.sizeX + (x) ].light > light: # and map.blocks[ (y-1) *map.sizeX + (x-1) ].type==0:\n self.blocks[y*map.sizeX + x].light = self.blocks[ (y-1) *map.sizeX + (x) ].light - 1\n if self.blocks[ (y+1) *map.sizeX + (x) ].light > light: # and map.blocks[ (y-1) *map.sizeX + (x+1) ].type==0:\n self.blocks[y*map.sizeX + x].light = self.blocks[ (y+1) *map.sizeX + (x) ].light - 1\n if self.blocks[ (y) *map.sizeX + (x-1) ].light > light: # and map.blocks[ (y+1) *map.sizeX + (x-1) ].type==0:\n self.blocks[y*map.sizeX + x].light = self.blocks[ (y) *map.sizeX + (x-1) ].light - 1\n if self.blocks[ (y) *map.sizeX + (x+1) ].light > light: # and map.blocks[ (y+1) *map.sizeX + (x+1) ].type==0:\n self.blocks[y*map.sizeX + x].light = self.blocks[ (y) *map.sizeX + (x+1) ].light - 1\n def border(self):\n self.startPoint = Point(myPlayer.cell(myPlayer.x)-self.power, myPlayer.cell(myPlayer.y)-self.power)\n self.endPoint = Point(myPlayer.cell(myPlayer.x)+self.power, myPlayer.cell(myPlayer.y)+self.power)\n if self.startPoint.x<1:\n self.startPoint.x = 1\n if self.endPoint.x>map.sizeX-1:\n self.endPoint.x = map.sizeX-1\n if self.startPoint.y<1:\n self.startPoint.y = 1\n if self.endPoint.y>map.sizeY-1:\n self.endPoint.y = map.sizeY-1\n def setLight(self):\n self.border()\n \n for block in self.blocks:\n block.light = 0\n self.blocks[myPlayer.cell(myPlayer.y)*map.sizeX + myPlayer.cell(myPlayer.x)].light = self.power\n dcx = myPlayer.cellOffset(myPlayer.x)\n #print(dcx)\n dcy = myPlayer.cellOffset(myPlayer.y)\n #print(\"start\")\n for i in range(self.power):\n timeNow = pygame.time.get_ticks()\n #print(\"1 \" + str(timeNow))\n self.setNeighbors()\n timeNow = pygame.time.get_ticks()\n #print(\"2 \" + str(timeNow))\n self.lightStep()\n #print(\"end\")\n for x in range(self.startPoint.x, self.endPoint.x):\n for y in range(self.startPoint.y, self.endPoint.y):\n if self.blocks[y*map.sizeX + x].neighbors and map.blocks[ (y) *map.sizeX + (x) ].type==0:\n light = self.blocks[y*map.sizeX + x].light\n if self.blocks[ (y-1) *map.sizeX + (x) ].light < light and map.blocks[ (y-1) *map.sizeX + (x) ].type==1: \n self.blocks[ (y-1) *map.sizeX + (x) ].light = self.blocks[y*map.sizeX + x].light - 1\n if self.blocks[ (y+1) *map.sizeX + (x) ].light < light and map.blocks[ (y+1) *map.sizeX + (x) ].type==1: \n self.blocks[ (y+1) *map.sizeX + (x) ].light = self.blocks[y*map.sizeX + x].light - 1\n if self.blocks[ (y) *map.sizeX + (x-1) ].light < light and map.blocks[ (y) *map.sizeX + (x-1) ].type==1: \n self.blocks[ (y) *map.sizeX + (x-1) ].light = self.blocks[y*map.sizeX + x].light - 1\n if self.blocks[ (y) *map.sizeX + (x+1) ].light < light and map.blocks[ (y) *map.sizeX + (x+1) ].type==1: \n self.blocks[ (y) *map.sizeX + (x+1) ].light = self.blocks[y*map.sizeX + x].light - 1\n if self.blocks[ (y-1) *map.sizeX + (x-1) ].light < light and map.blocks[ (y-1) *map.sizeX + (x-1) ].type==1: \n self.blocks[ (y-1) *map.sizeX + (x-1) ].light = self.blocks[y*map.sizeX + x].light - 1\n if self.blocks[ (y+1) *map.sizeX + (x+1) ].light < light and map.blocks[ (y+1) *map.sizeX + (x+1) ].type==1: \n self.blocks[ (y+1) *map.sizeX + (x+1) ].light = self.blocks[y*map.sizeX + x].light - 1\n if self.blocks[ (y+1) *map.sizeX + (x-1) ].light < light and map.blocks[ (y+1) *map.sizeX + (x-1) ].type==1: \n self.blocks[ (y+1) *map.sizeX + (x-1) ].light = self.blocks[y*map.sizeX + x].light - 1\n if self.blocks[ (y-1) *map.sizeX + (x+1) ].light < light and map.blocks[ (y-1) *map.sizeX + (x+1) ].type==1: \n self.blocks[ (y-1) *map.sizeX + (x+1) ].light = self.blocks[y*map.sizeX + x].light - 1\n # changing light values with offset inside cell for smooth color change\n for x in range(self.startPoint.x, self.endPoint.x):\n for y in range(self.startPoint.y, self.endPoint.y):\n #self.blocks[y*map.sizeX + x].light = 5\n if x>int(myPlayer.cell(myPlayer.x)+dcx*2-1):\n if self.blocks[y*map.sizeX + x].light>0:\n self.blocks[y*map.sizeX + x].light+=dcx\n else:\n if self.blocks[y*map.sizeX + x].light>0:\n self.blocks[y*map.sizeX + x].light+=1-dcx\n if y>int(myPlayer.cell(myPlayer.y)+dcy*2-1):\n if self.blocks[y*map.sizeX + x].light>0:\n self.blocks[y*map.sizeX + x].light+=dcy\n else:\n if self.blocks[y*map.sizeX + x].light>0:\n self.blocks[y*map.sizeX + x].light+=1-dcy\n\n if self.blocks[y*map.sizeX + x].light<0:\n self.blocks[y*map.sizeX + x].light = 0\n if self.blocks[y*map.sizeX + x].light > self.power:\n self.blocks[y*map.sizeX + x].light = self.power\n \n\n#\nclass Key:\n left = 0\n right = 0\n up = 0\n down = 0\n#\nclass Mouse:\n x = 0\n y = 0\n down = 0\n def set(self):\n (self.x, self.y) = pygame.mouse.get_pos()\n#\nclass Window:\n height = 0\n width = 0\n def __init__(self):\n self.getSize()\n def getSize(self):\n (self.width, self.height) = pygame.display.get_surface().get_size()\n# consts ----------------------------------------------------------------\nRIGHT = 1\nLEFT = 0\n# for blocks\nAIR = 0\nGROUND = 1\nSPIKES = 2\n# for exit\nEXIT = 666\n# monsters types\nGUARDIAN = 0\nHUNTER = 1\n\n\n# varaibles ----------------------------------------------------------------\ngravity = 5\nlevel = 0\nkeys = Key()\nmyPlayer = Player()\ncam = Camera(0,0,1)\nmouse = Mouse()\nwindow = Window()\nblockSize = 100\n# levels\nlevels = []\ndef startLevel(level):\n levels[level].start()\ndef makeLevels():\n def setup(self):\n def platformSetup(self):\n self.fX = 10\n self.phase = True\n def platformLoop(self):\n if self.phase:\n self.fX = 10\n else:\n self.fX = -10\n if self.x>10*blockSize and self.phase or self.x<2*blockSize and not self.phase:\n self.phase = not self.phase\n self.setPlatform(400, 700, 200, 200, platformSetup, platformLoop)\n self.setPairDoors(15*blockSize, 7*blockSize, 20*blockSize, 7*blockSize, True)\n self.setButton(5*blockSize, 8*blockSize, 1)\n self.setButton(32*blockSize, 2*blockSize, 2)\n self.setMonster(21*blockSize, 5*blockSize, GUARDIAN)\n self.load(\"level.l\")\n def loop(self):\n if self.signal == 1:\n self.doors[0].closed = False\n self.doors[1].closed = False\n self.signal = 0\n if self.signal == 2:\n myPlayer.die()\n self.signal = 0\n return 0\n levels.append(Map(100,100,5*blockSize,5*blockSize, setup, loop))\n\n\n# functions ----------------------------------------------------------------\nmap = Map()\nframes = 0\nstart = 0\nend = 0\n# main functions\ndef main():\n timeNow = pygame.time.get_ticks()\n window.getSize()\n global frames\n global start\n end = timeNow\n if end-start>=1000:\n #print(frames)\n frames = 0\n start = timeNow\n if timeNow%1==0:\n #print(\"1 \" + str(timeNow))\n play()\n timeNow = pygame.time.get_ticks()\n #print(\"2 \" + str(timeNow))\n draw()\n timeNow = pygame.time.get_ticks()\n #print(\"3 \" + str(timeNow))\n map.lightMap.setLight()\n timeNow = pygame.time.get_ticks()\n #print(\"4 \" + str(timeNow))\n frames+=1\n pygame.time.wait(1)\n# play \ndef play():\n if mouse.down:\n map.setBlock(myPlayer.cell(cam.x+mouse.x/cam.scale), myPlayer.cell(cam.y+mouse.y/cam.scale), 1)\n return 0\n# events \ndef checkEvents():\n global mouse\n global keys\n global fullscreen\n\n mouse.set()\n for event in pygame.event.get():\n if event.type==MOUSEBUTTONDOWN:\n mouse.down = True\n if event.type==MOUSEBUTTONUP:\n mouse.down = False\n if event.type==KEYDOWN:\n if event.key==K_RIGHT:\n keys.right = True\n if event.key==K_LEFT:\n keys.left = True\n if event.key==K_UP:\n keys.up = True\n if event.key==K_TAB:\n map.save(\"level.l\")\n if event.key==K_SPACE:\n myPlayer.checkDoors()\n myPlayer.checkButtons()\n if event.key==K_F11:\n if fullscreen:\n screen = pygame.display.set_mode((15*50,15*50),pygame.RESIZABLE ,32)\n else:\n screen = pygame.display.set_mode((1600,900),pygame.FULLSCREEN,32)\n fullscreen = not fullscreen\n if event.type==KEYUP:\n if event.key==K_RIGHT:\n keys.right = False\n if event.key==K_LEFT:\n keys.left = False\n if event.key==K_UP:\n keys.up = False\n if event.key == K_ESCAPE: \n mainLoop = False\n if event.type == QUIT: \n mainLoop = False\n pygame.quit()\n if event.type==VIDEORESIZE:\n screen=pygame.display.set_mode(event.dict['size'],HWSURFACE|DOUBLEBUF|RESIZABLE)\n #screen.blit(pygame.transform.scale(pic,event.dict['size']),(0,0))\n pygame.display.flip()\n# draw \ndef draw():\n global screen\n screen.fill((0,0,0))\n \n global image_wall\n image_wall = pygame.transform.scale(image_wall, (int(blockSize*cam.scale), int(blockSize*cam.scale)))\n global image_block \n image_block = pygame.transform.scale(image_block, (int(blockSize*cam.scale), int(blockSize*cam.scale)))\n global image_spikes\n image_spikes = pygame.transform.scale(image_spikes, (int(blockSize*cam.scale), int(blockSize*cam.scale)))\n\n # draw blocks\n for x in range(0, map.sizeX):\n for y in range(0, map.sizeY):\n if map.blocks[y*map.sizeX+x].type == 1:\n screen.blit(image_block, ((x*blockSize-cam.x)*cam.scale, (y*blockSize-cam.y)*cam.scale))\n else:\n screen.blit(image_wall, ((x*blockSize-cam.x)*cam.scale, (y*blockSize-cam.y)*cam.scale))\n if map.blocks[y*map.sizeX+x].danger == 1:\n screen.blit(image_spikes, ((x*blockSize-cam.x)*cam.scale, (y*blockSize-cam.y)*cam.scale))\n \n # draw objects\n for door in map.doors:\n door.draw()\n\n for platform in map.platforms:\n platform.draw()\n\n for monster in map.monsters:\n monster.draw()\n\n\n for button in map.buttons:\n button.draw()\n \n pygame.display.update()\n# set alpha channel to image\ndef setAlpha(image, value, transparentColor):\n image.set_alpha(value)\n image = image.convert()\n if transparentColor != None:\n image.set_colorkey(transparentColor)\n return image\n# main loop \nwhile mainLoop: \n checkEvents()\n main()\n \npygame.quit()\n","sub_path":"python/pygame_platformer_rougelike/lever_editor.py","file_name":"lever_editor.py","file_ext":"py","file_size_in_byte":26425,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"194507106","text":"import socket\nimport threading\nimport argparse\nimport json\nimport hashlib\n\nimport traceback\nfrom pathlib import Path\nfrom datetime import datetime\nfrom hashlib import sha256\n\nimport gc\nimport torch\n\nfrom getconfig import config, setting_info\nfrom utils import *\nfrom gpt2generator import GPT2Generator\nfrom interface import instructions\n\nparser = argparse.ArgumentParser()\n\nparser.add_argument(\n \"--host\",\n default=socket.gethostname(),\n type=str,\n required=False,\n help=\"Host for which the server connects to.\\n\",\n)\n\nparser.add_argument(\n \"--port\",\n default=49512,\n type=int,\n required=False,\n help=\"Port for the server to listen to\\n\",\n)\n\nparser.add_argument(\n \"--password\",\n default=\"\",\n type=str,\n required=False,\n help=\"Password for people to connect to the server\\n\",\n)\n\nparser.add_argument(\n \"--name\",\n default=\"DungeonServer\",\n type=str,\n required=False,\n help=\"Name of the server that people see when they try to connect to it.\\n\",\n)\n\nargs = parser.parse_args()\n\ndef encrypt_string(hash_string):\n sha_signature = \\\n hashlib.sha256(hash_string.encode()).hexdigest()\n return sha_signature\n\ndef get_generator():\n output(\n \"\\nInitializing AI Engine! (This might take a few minutes)\",\n \"loading-message\", end=\"\\n\\n\"\n )\n models = [x for x in Path('models').iterdir() if x.is_dir()]\n generator = None\n failed_env_load = False\n while True:\n try:\n transformers_pretrained = os.environ.get(\"TRANSFORMERS_PRETRAINED_MODEL\", False)\n if transformers_pretrained and not failed_env_load:\n # Keep it as a string, so that transformers library will load the generic model\n model = transformers_pretrained\n assert isinstance(model, str)\n else:\n # Convert to path, so that transformers library will load the model from our folder\n if not models:\n raise FileNotFoundError(\n 'There are no models in the models directory! You must download a pytorch compatible model!')\n if os.environ.get(\"MODEL_FOLDER\", False) and not failed_env_load:\n model = Path(\"models/\" + os.environ.get(\"MODEL_FOLDER\", False))\n elif len(models) > 1:\n output(\"You have multiple models in your models folder. Please select one to load:\", 'message')\n list_items([m.name for m in models] + [\"(Exit)\"], \"menu\")\n model_selection = input_number(len(models))\n if model_selection == len(models):\n output(\"Exiting. \", \"message\")\n exit(0)\n else:\n model = models[model_selection]\n else:\n model = models[0]\n logger.info(\"Using model: \" + str(model))\n assert isinstance(model, Path)\n generator = GPT2Generator(\n model_path=model,\n generate_num=settings.getint(\"generate-num\"),\n temperature=settings.getfloat(\"temp\"),\n top_k=settings.getint(\"top-k\"),\n top_p=settings.getfloat(\"top-p\"),\n repetition_penalty=settings.getfloat(\"rep-pen\"),\n )\n break\n except OSError:\n if len(models) == 0:\n output(\"You do not seem to have any models installed.\", \"error\")\n output(\"Place a model in the 'models' subfolder and press enter\", \"error\")\n input(\"\")\n # Scan for models again\n models = [x for x in Path('models').iterdir() if x.is_dir()]\n else:\n failed_env_load = True\n output(\"Model could not be loaded. Please try another model. \", \"error\")\n continue\n except KeyboardInterrupt:\n output(\"Model load cancelled. \", \"error\")\n exit(0)\n return generator\n\nback_log = []\nback_log_event = threading.Event()\nresult = \"\"\n\ndef new_client(s, csock, addr, event):\n recv_data = []\n recv_data_str = \"\"\n while True:\n data = csock.recv(1024)\n if not data:\n break\n recv_data.append(data.decode('utf-8'))\n recv_data_str = ''.join(recv_data)\n try:\n stitched_json = json.loads(recv_data_str)\n except ValueError:\n continue\n break\n \n if args.password != str(\"\"):\n if stitched_json[\"pass\"] != encrypt_string(args.password):\n print(str(addr) + ' -- Disconnected: Invalid Password')\n csock.close()\n return\n \n # Enter object into backlog.\n back_log.append([stitched_json, event])\n # Wait for stuff to process from backlog.\n back_log_event.set()\n event.wait()\n\n sendpacket = {\n \"result\": result\n }\n \n print(str(addr) + \" -- Serviced successfully\")\n\n csock.sendall(bytes(json.dumps(sendpacket), encoding=\"utf-8\"))\n csock.close()\n print(str(addr) + \" -- Connection closed\")\n\ndef connection_listener(s):\n print('Server started...')\n s.listen()\n\n while True:\n c, addr = s.accept()\n print(str(addr) + \" -- Connection opened\")\n client_handler = threading.Thread(target=new_client, args=(s, c, addr, threading.Event()))\n client_handler.start()\n\n\n# Start the GPT-2 Generator\n\ngenerator = get_generator()\n\n# Start the connection.\n\ns = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\ns.bind((args.host, args.port))\nconn_listener = threading.Thread(target=connection_listener, args=(s,))\nconn_listener.start()\nprint('Started conn_listener')\n\ntry:\n while True:\n # process queue\n back_log_event.wait()\n\n for i in back_log:\n result = generator.generate(context=i[0][\"context\"], prompt=i[0][\"prompt\"], temperature=i[0][\"temp\"], top_p=i[0][\"top_p\"], top_k=20, repetition_penalty=i[0][\"rep_pen\"])\n i[1].set()\n\n back_log_event.clear()\nexcept KeyboardInterrupt:\n conn_listener.join()\n s.close()\n print('Server closed...')\n","sub_path":"server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":6136,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"110839574","text":"from math import sqrt, sin, cos, tan, pi, asin\nimport matplotlib.pyplot as plt\n\n\n\ng = 9.81\nDt=0.1\n\np0x = 0\np0y = 0\n\nv0 = 500\nangle = 90\n\nv0x = 0 #remplacer par cos de l'angle\nv0y = 500 #remplacer par sin de l'angle\n\nax = 0\nay = -g\n\nx = [p0x]\ny = [p0y]\n\ni=0\n\nfor n in range(0,300):\n vtx = v0x\n vty = v0y - g*Dt\n\n ptx = p0x + v0x*Dt\n pty = p0y + v0y*Dt - (g*Dt**2)/2\n\n p0x = ptx\n p0y = pty\n v0x = vtx\n v0y = vty\n i+=1\n\n x.append(ptx)\n y.append(pty)\n\n \n \n print (\" \")\n print (\"Temps en s = \", i*Dt)\n print (\"ax= \",ax)\n print (\"ay = \",ay)\n print (\"vtx = \",vtx)\n print (\"vty = \",vty)\n print (\"ptx = \",ptx)\n print (\"pty = \",pty)\n print (\" \")\n\nplt.plot(x,y)\nplt.axhline(y=0, color = 'r')\nplt.grid()\n\n\nplt.show()\n \n\n\n\n\n \n\n","sub_path":"Main.py","file_name":"Main.py","file_ext":"py","file_size_in_byte":811,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"75653192","text":"# This file creates the endscreen #\nfrom Mixer import *\nfrom TextFile import *\n\n\nclass Endscreen:\n def __init__(self, song, status):\n color = {\n \"You Win\": (0, 255, 0),\n \"You Lose\": (255, 0, 0)\n }\n background = {\n \"You Win\": 'media/applause_background.jpg',\n \"You Lose\": 'media/boo_background.jpg'\n }\n self.screen_dim = (800, 600)\n self.display = pygame.display.set_mode(self.screen_dim)\n self.song_name = song\n self.music = Music()\n self.music.set_sound(self.song_name)\n self.status = Text(status, self.display) # Win, lose, or tie\n self.status.set_size(80)\n self.status.set_pos((400 - (self.status.get_size()[0])/2, 300 - (self.status.get_size()[1])/2))\n self.text_back = Background(color[status], (self.status.get_size()[0] + 30, self.status.get_size()[1] + 30), (400 - (self.status.get_size()[0] + 30)/2, 300 - (self.status.get_size()[1] + 30)/2), self.display)\n self.background = pygame.image.load(background[status])\n\n def run_endscreen(self):\n pygame.init()\n self.music.play(-1)\n run = True\n while run:\n for event in pygame.event.get(): # Returns all inputs and triggers into an array\n if event.type == pygame.QUIT: # If the red X was clicked\n run = False\n\n\n # Draw Sprites #\n self.display.blit(self.background, (0, 0))\n self.text_back.draw()\n self.status.draw()\n\n pygame.display.update()\n pygame.quit()\n","sub_path":"Endscreen.py","file_name":"Endscreen.py","file_ext":"py","file_size_in_byte":1596,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"498996574","text":"# -*- coding: utf-8 -*-\nimport time, json\nfrom all_config import IS_PROXY\nfrom taxer_spider import TaxerSpider\nfrom task_redis_creator import TASKS_QUEUE, db_cnn, insert_task\nfrom public_utils import get_ip\n\n\ndef get_redis_task():\n # insert_task()\n pipe = db_cnn.pipeline()\n while True:\n pipe.spop(TASKS_QUEUE)\n try:\n task = pipe.execute()[0]\n if not task:\n print('task finished!')\n break\n tasks = json.loads(task)\n\n if IS_PROXY:\n proxies = get_ip()\n print(proxies)\n else:\n proxies = None\n\n A = TaxerSpider(tasks, proxies)\n A.start()\n time.sleep(5)\n except:\n time.sleep(10)\n\n\nif __name__ == '__main__':\n pass\n get_redis_task()\n","sub_path":"tax_manager.py","file_name":"tax_manager.py","file_ext":"py","file_size_in_byte":837,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"371893313","text":"#File I/O\nimport os\nimport glob\nimport numpy as np\nimport pandas as pd\n\nfrom datetime import datetime\nimport argparse\nimport shutil\nfrom shutil import copyfile\n\n#Image processing\nimport cv2\nfrom scipy.ndimage import rotate\nimport scipy.misc\n\n#Keras Library\nfrom tensorflow.keras.models import Model\nfrom tensorflow.keras.applications.vgg16 import VGG16\nfrom tensorflow.keras.applications.vgg19 import VGG19\nfrom tensorflow.keras.applications.resnet50 import ResNet50\nfrom tensorflow.keras.layers import Dense, Dropout, Flatten\nfrom tensorflow.keras.optimizers import SGD\nfrom keras_preprocessing.image import ImageDataGenerator\nfrom tensorflow.keras.callbacks import EarlyStopping, ModelCheckpoint\n\n#Etc\nimport warnings\nwarnings.filterwarnings(\"ignore\")\n\n\n#Define parameters\nparser = argparse.ArgumentParser()\nparser.add_argument('--model', required=False, default='vgg16', help='Model Architecture')\nparser.add_argument('--weights', required=False, default='None')\nparser.add_argument('--learning-rate', required=False, type=float, default=1e-4)\nparser.add_argument('--semi-train', required=False, default=None)\nparser.add_argument('--batch-size', required=False, type=int, default=8)\nparser.add_argument('--random-split', required=False, type=int, default=1)\nparser.add_argument('--data-augment', required=False, type=int, default=0)\nargs = parser.parse_args()\n#Suffix에 사용하기 위해 위와 같은 정의를 사용합니다.\n#명령 프롬프트에서 재현시 인자값만 변경하여 모델을 재현할 수 있도록 구성합니다.\n#추후 다른 정의 없이 args.로 사용할 수 있는 것 같습니다.\n\n\n#Clear and Make train/valid, cache, subm folders\ndef _clear_dir(path):\n if os.path.exists(path):\n shutil.rmtree(path)\n os.mkdir(path)\n\n\n#Define classification model\ndef get_model():\n if args.weights == 'None':\n args.weights = None\n if args.model in ['vgg16']:\n base_model = VGG16(include_top=False, weights=args.weights, input_shape=(img_row_size, img_col_size,3))\n elif args.model in ['vgg19']:\n base_model = VGG19(include_top=False, weights=args.weights, input_shape=(img_row_size, img_col_size,3))\n elif args.model in ['resnet50']:\n base_model = ResNet50(include_top=False, weights=args.weights, input_shape=(img_row_size, img_col_size,3))\n else:\n print('# {} is not a valid value for \"--model\"'.format(args.model))\n exit()\n\n out = Flatten()(base_model.output)\n out = Dense(fc_size, activation='relu')(out)\n out = Dropout(0.5)(out)\n out = Dense(fc_size, activation='relu')(out)\n out = Dropout(0.5)(out)\n output = Dense(10, activation='softmax')(out)\n model = Model(inputs=base_model.input, outputs=output)\n\n sgd = SGD(lr=1e-4, decay=1e-6, momentum=0.9, nesterov=True)\n model.compile(optimizer=sgd, loss='categorical_crossentropy', metrics=['accuracy'])\n return model\n\n\n#Make training data & validation data (Colorinput)\ndef generate_split():\n #Make folders to save K fold data set(train/valid)\n def _generate_temp_folder(root_path):\n _clear_dir(root_path)\n for i in range(n_class):\n os.mkdir('{}/c{}'.format(root_path,i))\n\n _generate_temp_folder(temp_train_fold)\n _generate_temp_folder(temp_valid_fold)\n\n train_samples =0\n valid_samples =0\n\n for label in labels:\n files = glob.glob('input/train/{}/*jpg'.format(label))\n for fl in files:\n if np.random.randint(nfolds)!= 1:\n copyfile(fl, 'input/temp_train_fold/{}/{}'.format(label, os.path.basename(fl)))\n train_samples += 1\n else:\n copyfile(fl, 'input/temp_valid_fold/{}/{}'.format(label, os.path.basename(fl)))\n valid_samples += 1\n\n print('# {} train samples | {} valid samples'.format(train_samples, valid_samples))\n return train_samples, valid_samples\n\n\ndef crop_center(img, cropx, cropy):\n # 이미지 중간을 Crop하는 함수를 정의한다\n y,x = img.shape\n startx = x//2-(cropx//2)\n starty = y//2-(cropy//2)\n return img[starty:starty+cropy,startx:startx+cropx]\n\n\ndef preprocess(image):\n # rescale\n image /= 255.\n\n # rotate\n rotate_angle = np.random.randint(40) - 20\n image = rotate(image, rotate_angle)\n\n # translate\n rows, cols, _ = image.shape\n width_translate = np.random.randint(60) - 30\n height_translate = np.random.randint(60) - 30\n M = np.float32([[1,0,width_translate],[0,1,height_translate]])\n image = cv2.warpAffine(image,M,(cols,rows))\n\n # zoom\n width_zoom = int(img_row_size * (0.8 + 0.2 * (1 - np.random.random())))\n height_zoom = int(img_col_size * (0.8 + 0.2 * (1 - np.random.random())))\n final_image = np.zeros((height_zoom, width_zoom, 3))\n final_image[:,:,0] = crop_center(image[:,:,0], width_zoom, height_zoom)\n final_image[:,:,1] = crop_center(image[:,:,1], width_zoom, height_zoom)\n final_image[:,:,2] = crop_center(image[:,:,2], width_zoom, height_zoom)\n\n # resize\n image = cv2.resize(final_image, (img_row_size, img_col_size))\n return image\n\n\nif __name__ == \"__main__\":\n\n print('# Train Model')\n\n #Define parameters\n fc_size = 2048\n n_class = 10\n nfolds = 5\n test_nfolds = 1\n seed = 10\n img_row_size, img_col_size = 224, 224\n labels = ['c0', 'c1', 'c2', 'c3', 'c4', 'c5', 'c6', 'c7', 'c8', 'c9']\n\n suffix = 'm{}.w{}.lr{}.s{}.nf{}.semi{}.b{}.row{}col{}.rsplit{}.augment{}.d{}'.format(args.model, args.weights, args.learning_rate, seed, nfolds, args.semi_train, args.batch_size, img_row_size, img_col_size, args.random_split, args.data_augment, datetime.now().strftime(\"%Y-%m-%d-%H-%M\"))\n\n train_path = 'input/train'\n test_path = 'input/test'\n temp_train_fold = 'input/temp_train_fold'\n temp_valid_fold = 'input/temp_valid_fold'\n cache = 'cache/{}'.format(suffix)\n subm = 'subm/{}'.format(suffix)\n\n #이 구문이 있기 때문에 모델 재실행시 기존에 있던 결과들은 다 지워지므로 미리 백업할 것\n for path in [temp_train_fold, temp_valid_fold, cache, subm]:\n _clear_dir(path)\n\n datagen = ImageDataGenerator(rescale = 1./255, preprocessing_function=preprocess)\n\n #5-fold cross evaluation\n for fold in range(nfolds):\n model = get_model()\n train_samples, valid_samples = generate_split()\n\n #flow_from_directory는 하위 폴더 파일도 다 불러오는 듯함. test 폴더 안에 하위폴더가 있음. 아니면 test_genrator를 3개를 만들어야?\n train_generator = datagen.flow_from_directory(\n directory=temp_train_fold, target_size=(img_row_size, img_col_size), batch_size=args.batch_size, class_mode='categorical', seed=2018)\n valid_generator = datagen.flow_from_directory(\n directory=temp_valid_fold, target_size=(img_row_size, img_col_size), batch_size=args.batch_size, class_mode='categorical', seed=2018)\n test_generator = datagen.flow_from_directory(\n directory='input/test', target_size=(img_row_size, img_col_size), batch_size=1, class_mode=None, shuffle=False)\n\n test_id = glob.glob('{}/imgs/*.jpg'.format(test_path))\n\n weight_path = 'cache/weight.fold_{}.h5'.format(nfolds)\n\n callbacks = [EarlyStopping(monitor='val_loss', patience=3, verbose=0), ModelCheckpoint(weight_path, monitor='val_loss',\n save_best_only=True, verbose=0)]\n\n model.fit_generator(train_generator, steps_per_epoch=train_samples/args.batch_size,\n epochs=3, validation_data=valid_generator, validation_steps=valid_samples/args.batch_size,\n shuffle=True, callbacks=callbacks, verbose=1)\n\n #Predict test data (j=3이면 세번 예측해서 평균)\n for j in range(test_nfolds):\n preds = model.predict_generator(test_generator, steps=len(test_id), verbose=1)\n if j == 0:\n result = pd.DataFrame(preds, columns=labels)\n else:\n result += pd.DataFrame(preds, columns=labels)\n\n result /= test_nfolds\n result.loc[:, 'img'] = pd.Series(test_id, index=result.index)\n #result.index는 c0~c9이다?\n #loc는 컬럼명을 추출하는 판다스함수, 시리즈는 저런 형태의 데이터 구조를 만들어줌\n #현재 런을 하면 모델을 5번 만들고 모델을 만들 때마다 3번씩 테스트 데이터로 예측함.\n sub_file = '../subm/{}/f{}.csv'.format(suffix, fold)\n result.to_csv(sub_file, index=False)\n\n shutil.rmtree(temp_train_fold)\n shutil.rmtree(temp_valid_fold)\n #temp~ 폴더 안에 있는 자료를 다 지워야 다시 두번째 폴드를 시작할 수 있다.\n\n #Ensemble 5-folds\n print('# Ensemble')\n\n ensemble = 0\n for fold in range(nfolds):\n ensemble += pd.read_csv('subm/{}/f{}.csv'.format(suffix, fold), index_col=-1).values * 1. / nfolds\n ensemble = pd.DataFrame(ensemble, columns=labels)\n ensemble.loc[:, 'img'] = pd.Series(test_id, index=ensemble.index)\n sub_file = 'subm/{}/ens.csv'.format(suffix)\n ensemble.to_csv(sub_file, index=False)\n\n\n","sub_path":"statefarm_colorinput.py","file_name":"statefarm_colorinput.py","file_ext":"py","file_size_in_byte":9146,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"233686503","text":"import pygame\r\nimport sys\r\nimport random\r\n\r\nclass Snake():\r\n def __init__(self):\r\n self.length = 1\r\n self.positions = [((WIDTH/2), (HEIGHT/2))]\r\n self.colour = BLACK\r\n self.score = 0\r\n self.direction = random.choice([up, down, left, right])\r\n\r\n def get_head_position(self):\r\n return self.positions[0]\r\n\r\n def turn(self, point):\r\n if self.length > 1 and (point[0]*-1, point[1]*-1) == self.direction:\r\n return\r\n else:\r\n self.direction = point\r\n\r\n def move(self):\r\n cur = self.get_head_position()\r\n x,y = self.direction\r\n new = (((cur[0]+(x*gridsize))%WIDTH), (cur[1]+(y*gridsize))%HEIGHT)\r\n if len(self.positions) > 2 and new in self.positions[2:]:\r\n self.reset()\r\n else:\r\n self.positions.insert(0,new)\r\n if len(self.positions) > self.length:\r\n self.positions.pop()\r\n\r\n def reset(self):\r\n self.length = 1\r\n self.positions = [((WIDTH/2), (HEIGHT/2))]\r\n self.direction = random.choice([up, down, left, right])\r\n self.score = 0\r\n\r\n def draw(self,surface):\r\n for p in self.positions:\r\n r = pygame.Rect((p[0], p[1]), (gridsize,gridsize))\r\n pygame.draw.rect(surface, self.colour, r)\r\n pygame.draw.rect(surface, BLACK, r, 1)\r\n\r\n def handleMovement(self):\r\n for event in pygame.event.get():\r\n if event.type == pygame.QUIT:\r\n pygame.quit()\r\n sys.exit()\r\n elif event.type == pygame.KEYDOWN:\r\n if event.key == pygame.K_w:\r\n self.turn(up)\r\n elif event.key == pygame.K_s:\r\n self.turn(down)\r\n elif event.key == pygame.K_a:\r\n self.turn(left)\r\n elif event.key == pygame.K_d:\r\n self.turn(right)\r\n\r\nclass Food():\r\n def __init__(self):\r\n self.position = (0,0)\r\n self.colour = RED\r\n self.randomize_position()\r\n\r\n def randomize_position(self):\r\n self.position = (random.randint(0, grid_width-1)*gridsize, random.randint(0, grid_height-1)*gridsize)\r\n\r\n def draw(self, surface):\r\n r = pygame.Rect((self.position[0], self.position[1]), (gridsize, gridsize))\r\n pygame.draw.rect(surface, self.colour, r)\r\n pygame.draw.rect(surface, self.colour, r, 1)\r\n\r\ndef drawBoard(surface):\r\n for y in range(0, int(grid_height)):\r\n for x in range(0, int(grid_width)):\r\n if (x+y)%2 == 0:\r\n ss = pygame.Rect((x*gridsize, y*gridsize), (gridsize,gridsize))\r\n pygame.draw.rect(surface,LIGHT_BLUE, ss)\r\n else:\r\n fs = pygame.Rect((x*gridsize, y*gridsize), (gridsize,gridsize))\r\n pygame.draw.rect(surface, LIGHT_PURPLE, fs)\r\n\r\nWIDTH = 600\r\nHEIGHT = 480\r\n\r\nRED = (224, 18, 18)\r\nBLUE = (10, 13, 240)\r\nGREEN = (10, 240, 98)\r\nBLACK = (0, 0, 0)\r\nWHITE = (255, 255, 255)\r\nLIGHT_BLUE = (87, 175, 230)\r\nLIGHT_PURPLE = (144, 135, 245)\r\n\r\ngridsize = 20\r\ngrid_width = WIDTH/gridsize\r\ngrid_height = HEIGHT/gridsize\r\n\r\nup = (0,-1)\r\ndown = (0,1)\r\nleft = (-1,0)\r\nright = (1,0)\r\n\r\n\r\ndef main():\r\n pygame.init()\r\n\r\n clock = pygame.time.Clock()\r\n screen = pygame.display.set_mode((WIDTH, HEIGHT), 0, 32)\r\n\r\n surface = pygame.Surface(screen.get_size())\r\n surface = surface.convert()\r\n drawBoard(surface)\r\n\r\n snake = Snake()\r\n food = Food()\r\n\r\n myfont = pygame.font.SysFont(\"agencyfb\",25)\r\n\r\n while (True):\r\n clock.tick(10)\r\n snake.handleMovement()\r\n drawBoard(surface)\r\n snake.move()\r\n if snake.get_head_position() == food.position:\r\n snake.length += 1\r\n snake.score += 1\r\n food.randomize_position()\r\n snake.draw(surface)\r\n food.draw(surface)\r\n screen.blit(surface, (0,0))\r\n text = myfont.render(\"Player 1: {0}\".format(snake.score), 1, (0,0,0))\r\n screen.blit(text, (5,10))\r\n pygame.display.update()","sub_path":"singleplayer.py","file_name":"singleplayer.py","file_ext":"py","file_size_in_byte":4065,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"274353216","text":"from excel_things import open_excel\nimport re\nfile_name = 'C201_C286 Scheduling Poll (Responses).xlsx'\nxl = open_excel(file_name)\ntitles = xl[0][:]\nfor i in range(len(titles)):\n\ttitles[i] = str(titles[i]).replace('At which times can you attend office hours or help sessions?', '').strip()\n\nprint(titles)\ntimes = titles[1:-1]\nprint(repr(times))\n\n","sub_path":"schedule_office_hours.py","file_name":"schedule_office_hours.py","file_ext":"py","file_size_in_byte":345,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"29401786","text":"from dgl.data import citation_graph, rdf, knowledge_graph\nfrom sklearn.model_selection import train_test_split\n\n\ndef load_citation_dataset(name):\n m = {\n 'cora': citation_graph.CoraGraphDataset,\n 'citeseer': citation_graph.CiteseerGraphDataset,\n 'pubmed': citation_graph.PubmedGraphDataset\n }\n try:\n return m[name]()\n except KeyError:\n raise ValueError('Unknown citation dataset: {}'.format(name))\n\n\ndef load_rdf_dataset(name):\n m = {\n 'aifb': rdf.AIFBDataset,\n 'mutag': rdf.MUTAGDataset,\n 'bgs': rdf.BGSDataset,\n 'am': rdf.AMDataset\n }\n try:\n return m[name]()\n except KeyError:\n raise ValueError('Unknown RDF dataset: {}'.format(name))\n\n\ndef load_kg_dataset(name):\n m = {\n 'wn18': knowledge_graph.WN18Dataset,\n 'FB15k': knowledge_graph.FB15kDataset,\n 'FB15k-237': knowledge_graph.FB15k237Dataset\n }\n try:\n return m[name]()\n except KeyError:\n raise ValueError('Unknown knowledge graph dataset: {}'.format(name))\n\n\ndef split_idx(samples, train_size, val_size, random_state=None):\n \"\"\"将samples划分为训练集、测试集和验证集,需满足(用浮点数表示):\n\n * 0 < train_size < 1\n * 0 < val_size < 1\n * train_size + val_size < 1\n\n :param samples: list/ndarray/tensor 样本集\n :param train_size: int or float 如果是整数则表示训练样本的绝对个数,否则表示训练样本占所有样本的比例\n :param val_size: int or float 如果是整数则表示验证样本的绝对个数,否则表示验证样本占所有样本的比例\n :param random_state: int, optional 随机数种子\n :return: (train, val, test) 类型与samples相同\n \"\"\"\n train, val = train_test_split(samples, train_size=train_size, random_state=random_state)\n if isinstance(val_size, float):\n val_size *= len(samples) / len(val)\n val, test = train_test_split(val, train_size=val_size, random_state=random_state)\n return train, val, test\n","sub_path":"gnn/utils/data.py","file_name":"data.py","file_ext":"py","file_size_in_byte":2039,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"644868525","text":"from __future__ import print_function\r\nimport pickle\r\nimport os.path\r\nfrom googleapiclient.discovery import build\r\nfrom google_auth_oauthlib.flow import Flow\r\nfrom google.auth.transport.requests import Request\r\nimport glob, os\r\n\r\n\r\nusers = 0\r\nos.chdir(\"/\")\r\nfor file in glob.glob(\"*.pickle\"):\r\n user += 1\r\n\r\nSCOPES = ['https://www.googleapis.com/auth/classroom.courses']\r\n\r\ndef AddCourse(chat_id, title, subject, audience):\r\n \r\n creds = None\r\n pickleToken_path = \"AddCourse/\" + str(chat_id) + \"_token.pickle\"\r\n credentials_path = \"AddCourse/credentials.json\"\r\n\r\n if os.path.exists(pickleToken_path):\r\n with open(pickleToken_path, 'rb') as token:\r\n creds = pickle.load(token)\r\n \r\n if not creds or not creds.valid:\r\n if creds and creds.expired and creds.refresh_token:\r\n creds.refresh(Request())\r\n else:\r\n flow = Flow.from_client_secrets_file(credentials_path, SCOPES)\r\n creds = flow.run_local_server(port=users)\r\n \r\n with open(pickleToken_path, 'wb') as token:\r\n pickle.dump(creds, token)\r\n\r\n service = build('classroom', 'v1', credentials=creds)\r\n \r\n course = {\"name\": title,\r\n \"section\": subject,\r\n \"descriptionHeading\": \"\",\r\n \"description\": \"\",\r\n \"room\": audience,\r\n \"ownerId\": \"me\",\r\n \"courseState\": \"PROVISIONED\"}\r\n \r\n course = service.courses().create(body=course).execute()\r\n\r\n","sub_path":"AddCourse/AddCourse.py","file_name":"AddCourse.py","file_ext":"py","file_size_in_byte":1502,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"482225002","text":"#!/usr/bin/python\n# Copyright 2018, Kay Hayen, mailto:kay.hayen@gmail.com\n#\n# Python test originally created or extracted from other peoples work. The\n# parts from me are licensed as below. It is at least Free Software where\n# it's copied from other people. In these cases, that will normally be\n# indicated.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n#\n\nfrom __future__ import print_function\n\nimport os, sys, subprocess, shutil, hashlib\n\n# Find nuitka package relative to us.\nsys.path.insert(\n 0,\n os.path.normpath(\n os.path.join(\n os.path.dirname(os.path.abspath(__file__)),\n \"..\",\n \"..\",\n \"..\"\n )\n )\n)\n\nfrom nuitka.tools.testing.Common import (\n my_print,\n setup,\n convertUsing2to3,\n getTempDir,\n check_output\n)\nfrom nuitka.tools.testing.Valgrind import runValgrind\nfrom nuitka.tools.testing.Constructs import generateConstructCases\n\nfrom optparse import OptionParser\n\nparser = OptionParser()\n\nparser.add_option(\n \"--nuitka\",\n action = \"store\",\n dest = \"nuitka\",\n default = os.environ.get(\"NUITKA\", \"\"),\n)\n\nparser.add_option(\n \"--cpython\",\n action = \"store\",\n dest = \"cpython\",\n default = os.environ.get(\"PYTHON\", sys.executable),\n)\n\nparser.add_option(\n \"--code-diff\",\n action = \"store\",\n dest = \"diff_filename\",\n default = \"\",\n)\n\nparser.add_option(\n \"--copy-source-to\",\n action = \"store\",\n dest = \"target_dir\",\n default = \"\",\n)\n\n\noptions, positional_args = parser.parse_args()\n\nif len(positional_args) != 1:\n sys.exit(\"Error, need to give test case file name as positional argument.\")\n\ntest_case = positional_args[0]\n\nif os.path.exists(test_case):\n test_case = os.path.abspath(test_case)\n\nif options.cpython == \"no\":\n options.cpython = \"\"\n\nnuitka = options.nuitka\n\nif os.path.exists(nuitka):\n nuitka = os.path.abspath(nuitka)\nelif nuitka:\n sys.exit(\"Error, nuitka binary '%s' not found.\" % nuitka)\n\npython_version = setup(silent = True)\n\nassert os.path.exists(test_case), (test_case, os.getcwd())\n\nmy_print(\"PYTHON='%s'\" % python_version)\nmy_print(\"PYTHON_BINARY='%s'\" % os.environ[\"PYTHON\"])\nmy_print(\"TEST_CASE_HASH='%s'\" % hashlib.md5(open(test_case, \"rb\").read()).hexdigest())\n\n\nneeds_2to3 = python_version.startswith('3') and \\\n not test_case.endswith(\"32.py\") and \\\n not test_case.endswith(\"33.py\")\n\nif options.target_dir:\n shutil.copyfile(\n test_case,\n os.path.join(options.target_dir, os.path.basename(test_case))\n )\n\n\n\n# First produce two variants.\ntemp_dir = getTempDir()\n\ntest_case_1 = os.path.join(\n temp_dir,\n \"Variant1_\" + os.path.basename(test_case)\n)\ntest_case_2 = os.path.join(\n temp_dir,\n \"Variant2_\" + os.path.basename(test_case)\n)\n\ncase_1_source, case_2_source = generateConstructCases(open(test_case).read())\n\nwith open(test_case_1, 'w') as case_1_file:\n case_1_file.write(case_1_source)\n\nwith open(test_case_2, 'w') as case_2_file:\n case_2_file.write(case_2_source)\n\nif needs_2to3:\n test_case_1, needs_delete = convertUsing2to3(test_case_1)\n test_case_2, needs_delete = convertUsing2to3(test_case_2)\n\nos.environ[\"PYTHONHASHSEED\"] = '0'\n\nif nuitka:\n nuitka_id = check_output(\n \"cd %s; git rev-parse HEAD\" % os.path.dirname(nuitka),\n shell = True\n )\n nuitka_id = nuitka_id.strip()\n\n if sys.version_info > (3,):\n nuitka_id = nuitka_id.decode()\n\n my_print(\"NUITKA_COMMIT='%s'\" % nuitka_id)\n\nos.chdir(getTempDir())\n\nif nuitka:\n nuitka_call = [\n os.environ[\"PYTHON\"],\n nuitka,\n \"--python-flag=-S\",\n os.path.basename(test_case)\n ]\n nuitka_call.extend(os.environ.get(\"NUITKA_EXTRA_OPTIONS\", \"\").split())\n\n\n # We want to compile under the same filename to minimize differences, and\n # then copy te resulting files afterwards.\n shutil.copyfile(test_case_1, os.path.basename(test_case))\n\n subprocess.check_call(nuitka_call)\n\n os.rename(\n os.path.basename(test_case).replace(\".py\", \".build\"),\n os.path.basename(test_case_1).replace(\".py\", \".build\")\n )\n os.rename(\n os.path.basename(test_case).replace(\".py\", \".exe\"),\n os.path.basename(test_case_1).replace(\".py\", \".exe\")\n )\n\n shutil.copyfile(test_case_2, os.path.basename(test_case))\n\n subprocess.check_call(nuitka_call)\n\n os.rename(\n os.path.basename(test_case).replace(\".py\", \".build\"),\n os.path.basename(test_case_2).replace(\".py\", \".build\")\n )\n os.rename(\n os.path.basename(test_case).replace(\".py\", \".exe\"),\n os.path.basename(test_case_2).replace(\".py\", \".exe\")\n )\n\n if options.diff_filename:\n suffixes = [\".c\", \".cpp\"]\n\n for suffix in suffixes:\n cpp_1 = os.path.join(\n test_case_1.replace(\".py\", \".build\"),\n \"module.__main__\" + suffix,\n )\n\n if os.path.exists(cpp_1):\n break\n else:\n assert False\n\n for suffix in suffixes:\n\n cpp_2 = os.path.join(\n test_case_2.replace(\".py\", \".build\"),\n \"module.__main__\" + suffix,\n )\n if os.path.exists(cpp_2):\n break\n else:\n assert False\n\n import difflib\n open(options.diff_filename,'w').write(\n difflib.HtmlDiff().make_table(\n open(cpp_1).readlines(),\n open(cpp_2).readlines(),\n \"Construct\",\n \"Baseline\",\n True\n )\n )\n\n nuitka_1 = runValgrind(\n \"Nuitka construct\",\n \"callgrind\",\n (test_case_1.replace(\".py\", \".exe\"),),\n include_startup = True\n )\n\n nuitka_2 = runValgrind(\n \"Nuitka baseline\",\n \"callgrind\",\n (test_case_2.replace(\".py\", \".exe\"),),\n include_startup = True\n )\n\n nuitka_diff = nuitka_1 - nuitka_2\n\n my_print(\"NUITKA_COMMAND='%s'\" % \" \".join(nuitka_call), file = sys.stderr)\n my_print(\"NUITKA_RAW=%s\" % nuitka_1)\n my_print(\"NUITKA_BASE=%s\" % nuitka_2)\n my_print(\"NUITKA_CONSTRUCT=%s\" % nuitka_diff)\n\nif options.cpython:\n cpython_1 = runValgrind(\n \"CPython construct\",\n \"callgrind\",\n (os.environ[\"PYTHON\"], \"-S\", test_case_1),\n include_startup = True\n )\n cpython_2 = runValgrind(\n \"CPython baseline\",\n \"callgrind\",\n (os.environ[\"PYTHON\"], \"-S\", test_case_2),\n include_startup = True\n )\n\n cpython_diff = cpython_1 - cpython_2\n\n my_print(\"CPYTHON_RAW=%d\" % cpython_1)\n my_print(\"CPYTHON_BASE=%d\" % cpython_2)\n my_print(\"CPYTHON_CONSTRUCT=%d\" % cpython_diff)\n\nif options.cpython and options.nuitka:\n if nuitka_diff == 0:\n nuitka_gain = float(\"inf\")\n else:\n nuitka_gain = float(100 * cpython_diff) / nuitka_diff\n\n my_print(\n \"NUITKA_GAIN=%.3f\" % nuitka_gain\n )\n my_print(\n \"RAW_GAIN=%.3f\" % (\n float(100 * cpython_1) / nuitka_1\n )\n )\n my_print(\n \"BASE_GAIN=%.3f\" % (\n float(100 * cpython_2) / nuitka_2\n )\n )\n","sub_path":"tests/benchmarks/constructs/run_construct.py","file_name":"run_construct.py","file_ext":"py","file_size_in_byte":7668,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"185888200","text":"#Deberia poder sin cambiarle el nombre pero tengo otro paquete llamado visa instalado\nimport pyvisa as visa\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport math\nimport traceback\nimport sys\n\nrm = visa.ResourceManager()\n\nprint('******------ Lista de recursos -----*******')\nresources = rm.list_resources()\n# resources es una tupla de los distintos \"endpoints\"\nfor resource in resources:\n myInstrument = rm.open_resource(resource)\n idnResponse = myInstrument.query('*IDN?')\n print (\"Resourcer number: \"+str(resources.index(resource)),\"\\n\\t|-->VISA resource name: \"+str(resource))\n print(\"\\t|-->Instrument: \"+idnResponse)\n\n\n\n\ndef send_command(com):\n command=\"\"\n command = com\n lastChar = command[len(command)-1]\n if lastChar != '?':\n response = myInstrument.write(command)\n else:\n response = myInstrument.query(command)\n print('Comando ingresado:',command)\n print('Response:',response)\n return response\n \nsend_command('INST \"NA\";*OPC?')\nsend_command(\"CALC:PAR:COUN 1\")\t\nsend_command(\"CALC:PAR:DEF S21\")\nsend_command(\"FREQ:CENT 2.15E9\")\nsend_command(\"FREQ:SPAN 1E9\")\n#send_command(\"FREQ:STAR 1E9\")\n#send_command(\"FREQ:STOP 3E9\")\nsend_command(\"CALC:MARK1:ACTivate\")\nsend_command(\"CALC:MARK1 NORM\")\nsend_command(\"CALC:MARK1:X 2.15E9\")\n\n\nNUM_PUNTOS=100\n\ndb=[]\nfor x in range(0, NUM_PUNTOS):\n res=send_command(\"CALC:MARK1:Y?\")\n print(res)\n print(type(res))\n resultlist=res.split(',')\n print(resultlist)\n aux=resultlist[0].split('E+')\n aux2=float(aux[0])*math.pow(10,float(aux[1]))\n directivity=int(round(10*aux2))\n print(directivity)\n \n db.append(directivity)\n input(\"Press Enter to continue...\")\n\nr = np.arange(0, 1, 1/NUM_PUNTOS)\ntheta = 2*np.pi*r\nprint(db)\nax = plt.subplot(111, projection='polar')\nax.plot(theta, db)\nax.set_rmax(0)\nax.set_rticks(np.arange(-600,0,100)) # Less radial ticks\nax.set_rlabel_position(90) # Move radial labels away from plotted line\nax.grid(True)\n\nax.set_title(\"Radiation lobule of a patch antenna\", va='bottom')\nplt.show()\n#send_command(\"CALC:MARK:BWID:DATA?\")\n","sub_path":"reads21.py","file_name":"reads21.py","file_ext":"py","file_size_in_byte":2085,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"609744776","text":"from optuna.samplers import TPESampler, GridSampler\n\nfrom Downstreamtask.LIAR.liarconfig import liarConfig\nimport numpy as np\nimport torch.nn as nn\nimport torch\nimport time\nimport torch.optim as optim\nfrom utils import *\nfrom transformers import BertTokenizer, BertModel, AdamW, get_linear_schedule_with_warmup\nfrom Downstreamtask.LIAR.liarmodel import Bert_liar\nimport tqdm\nimport random\nimport optuna\n\nfrom torch.utils.data import Dataset, DataLoader\nfrom Downstreamtask.LIAR.liardataset import LiarDataset\n\ndef training(model, optim, criterion_cls, train_iter, epoch):\n\n model.train()\n losses = []\n label = []\n preds = []\n softmax = nn.Softmax(dim = -1)\n print('\\nTrain_Epoch:', epoch)\n for batch in tqdm.tqdm(train_iter):\n optim.zero_grad()\n input_ids = batch['input_ids'].cuda()\n attn_mask = batch['attention_mask'].cuda()\n token_type_ids = batch['token_type_ids'].cuda()\n truelabel_cls = batch['cls_label'].cuda()\n\n logits_cls = model(input_ids, attn_mask, token_type_ids)\n ## if out dim is (bs x seqlen x numclass) -> (total_words_batch x numclass)\n ## if true label is (bs x seqlen) -> (total_words_batch)\n loss_cls = criterion_cls (logits_cls.view(-1, 6), truelabel_cls.view(-1, ))\n loss = loss_cls\n losses.append(loss.item())\n #for now we are only interested in accuracy and f1 of the classification task\n label.extend(truelabel_cls.cpu().detach().numpy())\n preds_cls = softmax(logits_cls).argmax(1)\n preds.extend(preds_cls.view(-1).cpu().detach().numpy())\n\n loss.backward()\n\n optim.step()\n\n return losses, label, preds\n\ndef validation(model, criterion_cls, valid_iter, epoch):\n model.eval()\n losses = []\n label = []\n preds = []\n softmax = nn.Softmax(dim=-1)\n print('\\nValid_Epoch:', epoch)\n\n with torch.no_grad():\n for batch in tqdm.tqdm(valid_iter):\n input_ids = batch['input_ids'].cuda()\n attn_mask = batch['attention_mask'].cuda()\n token_type_ids = batch['token_type_ids'].cuda()\n truelabel_cls = batch['cls_label'].cuda()\n\n logits_cls = model(input_ids, attn_mask, token_type_ids)\n\n loss_cls = criterion_cls(logits_cls.view(-1, 6), truelabel_cls.view(-1, ))\n loss = loss_cls\n losses.append(loss.item())\n # for now we are only interested in accuracy and f1 of the classification task\n label.extend(truelabel_cls.cpu().detach().numpy())\n preds_cls = softmax(logits_cls).argmax(1)\n preds.extend(preds_cls.view(-1).cpu().detach().numpy())\n\n return losses, label, preds\n\ndef train_val(train_data, valid_data, model_path:str,trial=None, best_params=None):\n\n epochs = liarConfig.epochs\n if (best_params is not None):\n print('selecting best_params')\n lrmain = best_params['lrmain']\n drop_out = best_params['drop_out']\n elif(trial is not None):\n print('selecting for trial')\n #lrmain = trial.suggest_categorical('lrmain',[ 5e-5, 3e-5, 2e-5])\n #drop_out = trial.suggest_categorical('drop_out', [0.1])\n\n lrmain = trial.suggest_categorical('lrmain', [5e-5, 4e-5, 3e-5, 2e-5])\n drop_out = trial.suggest_categorical('drop_out', [0.0, 0.1, 0.2, 0.3])\n else:\n\n drop_out = liarConfig.drop_out\n\n train_iter = train_data\n valid_iter = valid_data\n path_1 = '../../results/model/wiki103_mlm_cls_full_epochs10/dibert_mlm_cls_103_full_text9.tar'\n path_2 = '../../results/model/wiki103_mlm_cls_pprediction_full_epochs10/dibert_mlm_cls_pprediction_103_full_text9.tar'\n\n bert_pretrained = torch.load(path_2)\n model = Bert_liar(pretrained_model= bert_pretrained, hidden_out=liarConfig.hidden_model_out, drop_out= drop_out)\n\n\n optimizer = AdamW(model.parameters(), lr=lrmain)\n\n criterion_cls = nn.CrossEntropyLoss()\n model.cuda()\n score = score_cal()\n\n for epoch in range(epochs):\n train_losses, label, preds = training(model, optimizer, criterion_cls, train_iter, epoch)\n f1, acc = f1score(label, preds, 'weighted')\n score.train_f1.append(f1)\n score.train_acc.append(acc)\n score.train_loss.append(sum(train_losses)/len(train_losses))\n print('train_weighted_f1', f1)\n print('train_acc', acc)\n\n valid_loss, valid_label, valid_preds = validation(model, criterion_cls, valid_iter, epoch)\n valid_f1, valid_acc = f1score(valid_label, valid_preds, 'weighted')\n score.valid_f1.append(valid_f1)\n score.valid_acc.append(valid_acc)\n score.valid_loss.append(sum(valid_loss) / len(valid_loss))\n\n print('valid_weighted_f1:', valid_f1)\n print('valid_acc:', valid_acc)\n\n classificationreport(valid_label, valid_preds)\n\n if(trial is None and best_params is not None):\n print('-saving model-')\n torch.save(model, 'results/full_text/dibert_LIAR_mlm_cls_pprediction_103_10_seed_'+str(4)+'_epoch_'+str(epoch+1)+'.tar')\n\n return valid_acc, score # tuning according to the last best validation accuracy\n #return sum(score.valid_acc)/len(score.valid_acc), score\n\ndef objective(train_data, valid_data, model_path, trial):\n try:\n acc, score = train_val(train_data=train_data, valid_data=valid_data, model_path=model_path, trial=trial, best_params=None)\n except:\n return 0\n return acc\n\ndef start_tuning(train_data, valid_data, model_path:str ,param_path:str, sampler='TPE'):\n if(sampler == 'TPE'):\n print('selecting tpe sampler')\n study = optuna.create_study(direction=\"maximize\", sampler=TPESampler())\n study.optimize(lambda trial: objective(train_data, valid_data,model_path, trial), n_trials=30)\n elif(sampler == 'Grid'):\n print('selecting grid search sampler')\n #search_space = {\"lrmain\": [5e-5, 3e-5, 2e-5], \"drop_out\": [0.1]}\n search_space = {\"lrmain\": [5e-5, 4e-5, 3e-5, 2e-5], \"drop_out\": [0.0, 0.1, 0.2, 0.3]}\n #search_space = {\"lrmain\": [4e-5], \"drop_out\": [0.2]}\n study = optuna.create_study(direction=\"maximize\", sampler=GridSampler(search_space))\n study.optimize(lambda trial:objective(train_data, valid_data, model_path, trial), n_trials=4 * 4 )\n elif(sampler == 'Grid_with_two_lr'):\n print('selecting grid search sampler 2lr')\n search_space = {\"lrmain\": [5e-5, 4e-5, 3e-5, 2e-5],'lrclassifier': [1e-3, 1e-2, 1e-1], \"drop_out\": [0.0, 0.1,0.2,0.3]}\n study = optuna.create_study(direction=\"maximize\", sampler=GridSampler(search_space))\n study.optimize(lambda trial: objective(train_data, valid_data, model_path, trial), n_trials=4 * 3 * 4)\n\n best_params = study.best_params\n save_json(best_params, param_path)\n return best_params, study.best_trial\n\nif __name__ == '__main__':\n param_path = 'results/full_text/params/dibert_LIAR_mlm_cls_pprediction_10_best.json'\n model_path = 'results/dibert_SCI_mlm_cls_pp_29_seed_'+str(0)+'.tar'\n\n is_tune = True\n\n\n device = torch.device(\"cuda:0\")\n\n\n train_file = 'data/train.tsv'\n test_file = 'data/test.tsv'\n valid_file = 'data/valid.tsv'\n\n train_data = LiarDataset(train_file)\n valid_data = LiarDataset(valid_file)\n test_data = LiarDataset(test_file)\n\n print(len(train_data))\n print(len(valid_data))\n\n\n train_data_loader = DataLoader(train_data, batch_size=liarConfig.batch_size)\n valid_data_loader = DataLoader(valid_data, batch_size=liarConfig.batch_size)\n\n if(is_tune == False):\n best_params = load_json(param_path)\n #best_params = {\"lrmain\": 4e-05, \"drop_out\": 0.0}\n print(best_params)\n _, score = train_val(train_data_loader, valid_data_loader, model_path, None, best_params)\n print_result(score, liarConfig.epochs)\n elif(is_tune == True):\n print(param_path)\n #train_val(train_data, valid_data, model_path=model_path)\n best_params, best_trial = start_tuning(train_data_loader, valid_data_loader, model_path, param_path, 'Grid')\n\n\n\n","sub_path":"Downstreamtask/LIAR/train_liar.py","file_name":"train_liar.py","file_ext":"py","file_size_in_byte":8032,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"528615244","text":"\nn_str = input('Enter number: ')\nif n_str.isdigit():\n n_int = int(n_str)\n if n_int == 0 or n_int < 0:\n print('Enter number > 0')\n else:\n i = 0;\n max_int = 0;\n while n_int > 0:\n if n_int % 10 == 0:\n n_int = n_int // 10\n if max_int < i:\n max_int = i\n i = 0\n # print(n_int)\n else:\n i += 1\n n_int -= 1\n print('Max int: ', max_int)\nelse:\n print('Incorrect value!')","sub_path":"lesson_1/practice_1/task_4.py","file_name":"task_4.py","file_ext":"py","file_size_in_byte":537,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"385033269","text":"import re\nimport os\nimport webapp2\n\nfrom google.appengine.ext.webapp.mail_handlers import InboundMailHandler\nfrom google.appengine.api import mail\n\nfrom webapp2 import WSGIApplication, Route\n\nroot_dir = os.path.dirname(__file__)\ntemplate_dir = os.path.join(root_dir, 'templates')\n\nfrom python.base import Handler\n\nclass LogSenderHandler(InboundMailHandler):\n def receive(self, mail_message):\n logging.info(\"from: \" + mail_message.sender)\n plaintext = mail_message.bodies(content_type='text/plain')\n for text in plaintext:\n m = \"\"\n m = text[1].decode()\n logging.info(\"message: %s\" % m)\n self.response.out.write(m)\n\napp = webapp2.WSGIApplication([\n\n Route(r'/', handler = \"python.base.Front\", name = \"front\"),\n Route(r'/home', handler = \"python.base.Home\", name = \"home\"),\n Route(r'/newest', handler = \"python.base.Newest\", name = \"newest\"),\n\n Route(r'/file1', handler = \"python.base.File1\", name = \"file1\"),\n Route(r'/file2', handler = \"python.base.File2\", name = \"file2\"),\n\n Route(r'/settings', handler = \"python.base.Settings\", name = \"settings\"),\n Route(r'/feedback', handler = \"python.base.Feedback\", name = \"feedback\"),\n\n\n Route(r'/ajaxnote', handler = \"python.base.AjaxNote\", name = \"ajaxnote\"),\n Route(r'/ajaxquestion', handler = \"python.base.AjaxQuestion\", name = \"ajaxquestion\"),\n Route(r'/ajaxcourse', handler = \"python.base.AjaxCourse\", name = \"ajaxcourse\"),\n\n\n #LOGIN/SIGNUP\n Route(r'/login', handler= \"python.login_signup.Login\", name = \"login\"),\n Route(r'/logout', handler= \"python.login_signup.Logout\", name = \"logout\"),\n\n Route(r'/signup-pw', handler= \"python.login_signup.SignupPassword\", name = \"signup-pw\"),\n Route(r'/iforgot', handler= \"python.login_signup.ChangePassword\", name = \"iforgot\"),\n\n #NOTEBOOK STUFF\n Route(r'/thenotebook', handler= \"python.notebook.TheNotebook\", name = \"thenotebook\"),\n Route(r'/newnotebook', handler= \"python.notebook.NewNoteBook\", name = \"newnotebook\"),\n Route(r'/allnotebooks', handler= \"python.notebook.AllNotebooks\", name = \"allnotebooks\"),\n Route(r'/follownb', handler= \"python.notebook.FollowNb\", name = \"follownb\"),\n\n Route(r'/editnb', handler= \"python.notebook.EditNb\", name = \"editnb\"),\n Route(r'/thenbtag', handler= \"python.notebook.TheNbTag\", name = \"thenbtag\"),\n\n #NOTE STUFF\n Route(r'/thenote', handler= \"python.note.TheNote\", name = \"thenote\"),\n Route(r'/newnote', handler= \"python.note.NewNote\", name = \"newnote\"),\n Route(r'/edit', handler= \"python.note.Edit\", name = \"edit\"),\n Route(r'/history', handler= \"python.note.History\", name = \"history\"),\n\n Route(r'/newquestion', handler= \"python.note.NewQuestion\", name = \"newquestion\"),\n\n\n LogSenderHandler.mapping()],\n debug=True)\n","sub_path":"toffee.py","file_name":"toffee.py","file_ext":"py","file_size_in_byte":2920,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"95791226","text":"start_with_Hash = 0\nwith open('input.txt','r') as f:\n\tfor line in file:\n\t\tif re.math(\"^#\",line):\n\t\t\tstarts_with_hash += 1\n\ndef get_domain(email_address):\n\treturn email_address.lower().split(\"@\")[-1]\n\nwith open('email_addresses.txt','r') as f:\n\tdomain_counts = Counter(get_domain(line.strip())\n\t\t\t\t\t\t\tfor line in f\n\t\t\t\t\t\t\tif \"@\" in line)\n\n\n","sub_path":"data-science-from-scratch/e.py","file_name":"e.py","file_ext":"py","file_size_in_byte":339,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"287978439","text":"\"\"\"preprocess data for Wordcloud\"\"\"\r\n\r\nimport unicodedata, re, os\r\nfrom dataPrep.Func_extraction import Func_extraction\r\nfrom dataPrep.Func_chunking import Func_chunking\r\nimport pandas as pd\r\nfrom timeit import default_timer as timer\r\n\r\n\r\n\"\"\"start extraction\"\"\"\r\nextractor = Func_extraction()\r\nchunker = Func_chunking()\r\n\r\n'''标题识别'''\r\n\r\nprovnames = ['内蒙古', '四川', '国家','山东','广东','新疆','江苏','四川']\r\nfor provname in provnames:\r\n path = 'D:/3policyAyc/_database/_policytxt/Raw_'+provname+'1.csv'\r\n print('开始处理{}的政策文本,文本路径:{}'.format(provname, path)+'>>>>'*7)\r\n df = pd.read_csv(path)\r\n titles = df['title'].tolist()\r\n\r\n stopdocs = []\r\n fp = open('D:/3policyAyc/_database/_auxdata/rmvs_Docs.txt', 'r', encoding='utf-8')\r\n for line in fp.readlines():\r\n stopdocs.append(line.strip('\\n'))\r\n fp.close()\r\n\r\n # 带有停用词的标题\r\n specialtits, indlist = [],[]\r\n for w in set(stopdocs):\r\n for tit in titles:\r\n if w in tit:\r\n # print(tit)\r\n specialtits.append(tit)\r\n indlist.append(titles.index(tit))\r\n\r\n # 删除含停用标题的数据\r\n raw_df = df.drop(index = indlist, axis=1)\r\n raw_df = raw_df.reset_index(drop=True)\r\n del specialtits, indlist\r\n\r\n \"\"\"start preprocessing,word segmentation, POS tagging\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\r\n print('开始执行去除停用词和分词操作,提取所有名动词、名词、形容词和专有名词'+'>>>>'*7)\r\n tic1 = timer()\r\n count = 0\r\n ptlist = raw_df['ptext'].tolist()\r\n doclen = len(ptlist)\r\n newptlist = []\r\n for doc in ptlist:\r\n newptlist.append('\\n'.join(chunker.cutwithPOS(doc, False)))\r\n count += 1\r\n print('\\r提取进度:{:.2f}%'.format(count * 100 / doclen), end='')\r\n toc1 = timer()\r\n print('分词抽取完毕!用时'+str(toc1-tic1)+'秒!')\r\n\r\n raw_df['ptext'] = newptlist\r\n # df.to_excel(r'D:\\3policyAyc\\_database\\_policytxt\\Wordlist_'+list(provnames.keys())[namenum-1]+'.xlsx')\r\n raw_df.to_csv(r'D:\\3policyAyc\\_database\\_policytxt\\Wordlist_'+provname+'_forWordCloud.csv', encoding=\"utf_8_sig\", index=False)\r\n\r\n# 合并数据\r\nimport pandas as pd\r\nprovnames = ['内蒙古', '四川', '国家','山东','广东','新疆','江苏']\r\ndfls0 = []\r\nfor prov in provnames:\r\n tempdf = pd.read_csv(r'D:\\3policyAyc\\_database\\_policytxt\\Wordlist_'+prov+'_forWordCloud.csv')\r\n dfls0.append(tempdf)\r\n# dfls0[1].drop(index=)\r\ndfall0 = pd.concat(dfls0, ignore_index=True)\r\ndfall0.to_csv(r'D:\\3policyAyc\\_database\\_policytxt\\Wordlist_allforWC.csv', encoding=\"utf_8_sig\", index=False)\r\n\r\n\r\n","sub_path":"dataPrep/preprocessingforWordcloud_main.py","file_name":"preprocessingforWordcloud_main.py","file_ext":"py","file_size_in_byte":2722,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"148175860","text":"from compute.base.Handle import Handle\nimport datetime\n\n\nclass StatsFlows(Handle):\n\n def __init__(self, start=None, target=None):\n super().__init__(target)\n self.start = start\n self.allcount = 0\n self.allips = set()\n self.alllen = 0\n self.res = []\n\n def reset(self):\n self.allcount = 0\n self.allips = set()\n self.alllen = 0\n self.res = []\n super().reset()\n\n @staticmethod\n def get_start(db, extreme='max', delta=('days', 30)):\n extreme_time = next(db.aggregate([{\n '$group': {\n '_id': 1,\n 'extreme_time': {\n '$%s' % extreme: '$starttime'\n }\n }\n }]))['extreme_time']\n param, count = delta\n if param == 'hours':\n start = extreme_time - datetime.timedelta(hours=count)\n elif param == 'days':\n start = extreme_time - datetime.timedelta(days=count)\n elif param == 'weeks':\n start = extreme_time - datetime.timedelta(weeks=count)\n else:\n raise Exception('类型 %s 不存在' % param)\n return start, extreme_time\n\n def inititem(self):\n self.seqs[self.timestr] = {\n 'ips': set(),\n 'count': 0,\n 'filelen': 0\n }\n\n def handleitem(self, item):\n self.allcount += 1\n self.allips.add(item['srcip'])\n self.alllen += int(item['filelen'])\n self.seqs[self.timestr]['ips'].add(item['srcip'])\n self.seqs[self.timestr]['count'] += 1\n self.seqs[self.timestr]['filelen'] += int(item['filelen'])\n\n def save(self, saving):\n for key, value in self.seqs.items():\n self.res.append({\n 'time': key,\n 'ips': [item for item in value['ips']],\n 'ipscount': len(value['ips']),\n 'count': value['count'],\n 'filelen': value['filelen']\n })\n self.target.insert({\n 'type': 'stats',\n 'time': self.start,\n 'data': self.res,\n 'allips': len(self.allips),\n 'allcount': self.allcount,\n 'filelen': self.alllen,\n 'createdat': datetime.datetime.now()\n })\n\n","sub_path":"compute/modules/seq_stats_flow.py","file_name":"seq_stats_flow.py","file_ext":"py","file_size_in_byte":2274,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"532411553","text":"from google.appengine.ext import db\n\nclass RegisteredVisitor(db.Model):\n \"\"\"\n Represents a text message from a user who is registering for MFA\n \"\"\"\n phone = db.PhoneNumberProperty()\n body = db.StringProperty(multiline=True)\n date = db.DateTimeProperty(auto_now_add=True)\n hash = db.StringProperty()\n","sub_path":"models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":320,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"392281170","text":"\nfrom docutils import nodes\nfrom docutils.parsers.rst import directives\nfrom docutils.parsers.rst.directives.tables import Table\n\n\nclass DocumentedListDirective(Table):\n\n option_spec = {'listobject': directives.unchanged}\n\n def run(self):\n if self.content:\n error = self.state_machine.reporter.error(\n \"\"\"The documentedlist directive does not know what to do with\n the provided content\"\"\",\n nodes.literal_block(self.block_text, self.block_text),\n line=self.lineno\n )\n return [error]\n\n # Get the list containing the documentation\n memberpath = self.options.get('listobject', None)\n if memberpath is None:\n error = self.state_machine.reporter.error(\n \"The documentedlist needs to be given the list object\"\n \"containing the documentations as the :listobject: parameter\",\n nodes.literal_block(self.block_text, self.block_text),\n line=self.lineno\n )\n return [error]\n\n try:\n modstr, memberstr = memberpath.rsplit('.', 1)\n mod = __import__(modstr, fromlist=[memberstr])\n member = getattr(mod, memberstr)\n except ImportError:\n error = self.state_machine.reporter.error(\n \"Documentedlist encountered an error importing the member \"\n \"specified by \" + memberpath,\n nodes.literal_block(self.block_text, self.block_text),\n line=self.lineno\n )\n return [error]\n\n table_headers = ['Item', 'Description']\n table_body = member\n max_cols = len(table_headers)\n\n col_widths = self.get_column_widths(max_cols)\n\n title, messages = self.make_title()\n table_node = self.build_table(table_body,\n col_widths,\n table_headers)\n self.add_name(table_node)\n if title:\n table_node.insert(0, title)\n return [table_node] + messages\n\n @staticmethod\n def build_table(table_data, col_widths, headers):\n table = nodes.table()\n tgroup = nodes.tgroup(cols=len(headers))\n table += tgroup\n\n tgroup.extend(nodes.colspec(colwidth=col_width) for\n col_width in col_widths)\n\n thead = nodes.thead()\n tgroup += thead\n\n row_node = nodes.row()\n thead += row_node\n row_node.extend(nodes.entry(h, nodes.paragraph(text=h))\n for h in headers)\n\n tbody = nodes.tbody()\n tgroup += tbody\n\n rows = []\n for row in table_data:\n trow = nodes.row()\n for cell in row:\n entry = nodes.entry()\n para = nodes.paragraph(text=unicode(cell))\n entry += para\n trow += entry\n rows.append(trow)\n tbody.extend(rows)\n\n return table\n\n\ndef setup(app):\n app.add_directive('documentedlist', DocumentedListDirective)\n return {'version': '0.1'}\n","sub_path":"documentedlist.py","file_name":"documentedlist.py","file_ext":"py","file_size_in_byte":3123,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"624971305","text":"import pandas as pd\n\npath = \"admission_detail.csv\"\n\nstart = 1\nend = 813795\n\ndf = pd.read_csv(path)\ndf.columns = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U',\n 'V', 'W', 'X', 'Y', 'Z', 'AA']\nfilex = open(\"temp.txt\",\"r+\")\n\nint = 1\nfor i in range(start,end-1):\n keyx = df.iloc[i]\n key = str(keyx[5])\n prog = (i*100)/end\n if prog > int:\n print (str(int) + \" %\")\n int += 1\n if key == \"Payment Done\":\n out = \"\"\n for x in range(27):\n out += str(keyx[x]) + \"\\t\"\n out += \"\\n\"\n resultString = filex.read()\n filex.write(out)\n\nfilex.close()\n","sub_path":"Backend/Remove_Duplicate.py","file_name":"Remove_Duplicate.py","file_ext":"py","file_size_in_byte":677,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"29897965","text":"from celery import shared_task\nfrom celery.result import AsyncResult\n\n\nfrom ortools.algorithms import pywrapknapsack_solver\n\n\n@shared_task(bind=True, track_started=True)\ndef knapsack_solver(self, capacity, values, weights):\n solver = pywrapknapsack_solver.KnapsackSolver(pywrapknapsack_solver.KnapsackSolver.KNAPSACK_MULTIDIMENSION_BRANCH_AND_BOUND_SOLVER,'test')\n\n solver.Init(values, weights, capacity)\n computed_value = solver.Solve()\n packed_items = [x for x in range(0, len(weights[0]))\n if solver.BestSolutionContains(x)]\n packed_weights = [weights[0][i] for i in packed_items]\n total_weight = sum(packed_weights)\n\n return packed_items, packed_weights, computed_value, total_weight\n\n\ndef knapsack_solver_status(task_id):\n res = AsyncResult(task_id)\n return res","sub_path":"knap_proj/knapsack/tasks.py","file_name":"tasks.py","file_ext":"py","file_size_in_byte":812,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"438761548","text":"import psycopg2\n\n# CUSTOM FUNCTIONS HERE\n\ndef executeAll(query, secArg=None):\n \"full query execution\"\n #print(\"executeAll called\")\n DB = connect()\n c = DB.cursor()\n if secArg == None:\n c.execute(query)\n else:\n c.execute(query, secArg)\n DB.commit()\n DB.close()\n return DB\n\ndef executeAllFetch(query):\n \"full query including fetch\"\n #print(\"executeAllFetch called\")\n DB = connect()\n c = DB.cursor()\n c.execute(query)\n list = c.fetchall()\n DB.close()\n return list\n\n# ORIGINAL FUNCTIONS\n\ndef connect():\n \"\"\"Connect to the PostgreSQL database. Returns a database connection.\"\"\"\n return psycopg2.connect(\"dbname=tournament\")\n\n # success\n\ndef deleteMatches():\n \"\"\"Remove all the match records from the database.\"\"\"\n query = \"DELETE from matches\"\n # print(query)\n return executeAll(query)\n\n # success\n\ndef deletePlayers():\n \"\"\"Remove all the player records from the database.\"\"\"\n query = \"DELETE FROM players\"\n #print(query)\n return executeAll(query)\n\n # success\n\ndef countPlayers():\n \"\"\"Returns the number of players currently registered.\"\"\"\n value = executeAllFetch(\"SELECT COUNT (*) FROM players\")\n # print(value)\n return value[0][0]\n\n # success\n\ndef registerPlayer(name):\n \"\"\"Adds a player to the tournament database.\n\n The database assigns a unique serial id number for the player. (This\n should be handled by your SQL database schema, not in your Python code.)\n\n Args:\n name: the player's full name (need not be unique).\n \"\"\"\n #print(\"the name is\" + name)\n query = \"\"\"\n INSERT INTO players (name)\n VALUES (%s)\"\"\"\n #print(query)\n return executeAll(query, (name,))\n\n # success\n\ndef playerStandings():\n \"\"\"Returns a list of the players and their win records, sorted by wins.\n The first entry in the list should be the player in first place, or a player\n tied for first place if there is currently a tie.\n Returns:\n A list of tuples, each of which contains (id, name, wins, matches):\n id: the player's unique id (assigned by the database)\n name: the player's full name (as registered)\n wins: the number of matches the player has won\n matches: the number of matches the player has played\n \"\"\"\n query = \"\"\"\n SELECT * FROM standings\n ORDER BY wins DESC;\"\"\"\n #print(query)\n return executeAllFetch(query)\n\n # success\n\ndef reportMatch(winner, loser):\n \"\"\"Records the outcome of a single match between two players.\n Args:\n winner: the id number of the player who won\n loser: the id number of the player who lost\n \"\"\"\n #print(\"the winner is = \" + str(winner) + \" the loser is = \" + str(loser))\n winnerLoser = winner, loser\n query = \"\"\"\n INSERT INTO matches (winner, loser)\n VALUES (%s, %s)\"\"\"\n #print(query)\n return executeAll(query, winnerLoser)\n\n # success\n\ndef swissPairings():\n \"\"\"Returns a list of pairs of players for the next round of a match.\n\n Assuming that there are an even number of players registered, each player\n appears exactly once in the pairings. Each player is paired with another\n player with an equal or nearly-equal win record, that is, a player adjacent\n to him or her in the standings.\n\n Returns:\n A list of tuples, each of which contains (id1, name1, id2, name2)\n id1: the first player's unique id\n name1: the first player's name\n id2: the second player's unique id\n name2: the second player's name\n \"\"\"\n result = executeAllFetch(\"SELECT id, name FROM standings\")\n #print(result)\n list = []\n for n in range(0, countPlayers() -1, 2):\n list.append(result[n] + result[n + 1])\n #print(list)\n return list\n","sub_path":"tournament.py","file_name":"tournament.py","file_ext":"py","file_size_in_byte":3765,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"131462682","text":"#!/usr/bin/env python\n\"\"\"\nDatabase tools.\nRequires:\npymongo\nYou need to start a mongo session first with:\nmongod --logpath /Volumes/s/G/database_mongo/log --fork --dbpath /Volumes/s/G/database_mongo/\n\"\"\"\n__updated__ = \"2017-06-23\"\n\nfrom pymongo import MongoClient\n\ndef start_mongo(dbpath,logpath,mongoexe='mongod'):\n \"\"\"\n Starts a mongo session.\n \n \"\"\"\n import subprocess\n subprocess.call([mongoexe,'--logpath', logpath, '--fork', '--dbpath', dbpath])\n return\n\n\ndef get_collection(c='mycollection'):\n from pymongo import MongoClient\n client = MongoClient()\n return client[c]\n\n\ndef get_database(collection,db='mydatabase'):\n return collection[db]\n\n\ndef insert_entry(entry,db,efilter={}):\n return db.replace_one(efilter,entry,upsert=True)\n\ndef gen_dict_extract(key, var):\n \"\"\"\n https://stackoverflow.com/questions/9807634/find-all-occurrences-of-a-key-in-nested-python-dictionaries-and-lists\n \"\"\"\n if hasattr(var,'iteritems'):\n for k, v in var.iteritems():\n if k == key:\n yield v\n if isinstance(v, dict):\n for result in gen_dict_extract(key, v):\n yield result\n elif isinstance(v, list):\n for d in v:\n for result in gen_dict_extract(key, d):\n yield result\n\n\ndef visualise_dict(d,lvl=0):\n \"\"\"\n https://stackoverflow.com/questions/15023333/simple-tool-library-to-visualize-huge-python-dict\n \"\"\"\n # go through the dictionary alphabetically \n for k in sorted(d):\n form = '{:<45} {:<15} {:<10}'\n # print the table header if we're at the beginning\n if lvl == 0 and k == sorted(d)[0]:\n print(form.format('KEY','LEVEL','TYPE'))\n print('-'*79)\n\n indent = ' '*lvl # indent the table to visualise hierarchy\n t = str(type(d[k]))\n\n # print details of each entry\n print(form.format(indent+str(k),lvl,t))\n\n # if the entry is a dictionary\n if type(d[k])==dict:\n # visualise THAT dictionary with +1 indent\n visualise_dict(d[k],lvl+1)\n \nif __name__ == \"__main__\":\n import doctest\n doctest.testmod(verbose=True)\n","sub_path":"dbtools.py","file_name":"dbtools.py","file_ext":"py","file_size_in_byte":2216,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"396268483","text":"from gluon.globals import *\nfrom gluon.sql import *\nfrom gluon.validators import *\nfrom gluon.tools import *\nfrom gluon.html import *\nfrom gluon.scheduler import Scheduler\nimport datetime\n\nif 0:\n db = DAL()\n auth = Auth()\n request = Request()\n scheduler = Scheduler(db)\n mail = auth.settings.mailer\n\n\nSTATUSES = ('assigned', 'accepted', 'rejected', 'reassigned', 'completed')\n\n\ndb.define_table('nf_task',\n Field('title', requires = IS_NOT_EMPTY()),\n Field('description', 'text'),\n Field('assignedto', 'reference auth_user'),\n Field('status', requires = IS_IN_SET(STATUSES), default = STATUSES[0]),\n Field('deadline', 'date', default = (request.now + datetime.timedelta(days = 7))),\n auth.signature)\n\n\ndb.define_table('nf_post',\n Field('task', 'reference nf_task'),\n Field('body', 'text', requires = IS_NOT_EMPTY()),\n auth.signature)\n\n\ndb.nf_task.created_on.represent = lambda v, row: prettydate(v)\ndb.nf_task.deadline.represent = lambda v, row: SPAN(prettydate(v), _class = 'overdue' if v and v < datetime.date.today() else None)\n\n\ndef fullname(user_id):\n if user_id is None:\n return 'Unknown'\n return '%(first_name)s %(last_name)s' % db.auth_user(user_id)\n\n\ndef show_status(status, row = None):\n return SPAN(status, _class = status)\n\ndb.nf_task.status.represent = show_status\n\n\ndef send_email(to, subject, message, sender):\n if mailpolicy == 'realtime':\n return send_email_realtime(to, subject, message, sender)\n else:\n return send_email_deferred(to, subject, message, sender)\n\n\ndef send_email_deferred(to, subject, message, sender):\n if not isinstance(to, list):\n to = [to]\n scheduler.queue_task(send_email_realtime, pvars = dict(to = to, subject = subject, message = message, sender = sender))\n\n\ndef send_email_realtime(to, subject, message, sender):\n if not isinstance(to, list):\n to = [to]\n mail.settings.sender = sender\n return mail.send(to = to, subject = subject, message = message)","sub_path":"models/dbnotifier.py","file_name":"dbnotifier.py","file_ext":"py","file_size_in_byte":2105,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"195899603","text":"from googleMaps import Data\r\nfrom ortools.constraint_solver import pywrapcp\r\nfrom ortools.constraint_solver import routing_enums_pb2\r\nfrom six.moves import xrange\r\nimport numpy as np\r\nimport datetime\r\nimport glob\r\nimport os\r\nfrom config import conf\r\n\r\nfrom operator import itemgetter\r\n\r\nclass Vehicle():\r\n def __init__(self, nv):\r\n self._capacity = 15\r\n self._num_vehicles = nv\r\n\r\n self._init_vehicles_locations = np.zeros([nv], dtype = int).tolist()\r\n self._end_vehicles_locations = np.zeros([nv], dtype = int).tolist()\r\n\r\n\r\n @property\r\n def capacity(self):\r\n return self._capacity\r\n\r\n @property\r\n def num_vehicles(self):\r\n return self._num_vehicles\r\n\r\n @property\r\n def init_vehicles_locations(self):\r\n return self._init_vehicles_locations\r\n\r\n @property\r\n def end_vehicles_locations(self):\r\n return self._end_vehicles_locations\r\n\r\nclass DataProblem():\r\n def __init__(self, google_maps_key, json_file_path):\r\n\r\n self._data = Data(google_maps_key, json_file_path)\r\n self._service_time = self._data.service_time\r\n\r\n\r\n list_of_files = glob.glob('./archive_data/arcdict*')\r\n latest_file = max(list_of_files, key=os.path.getctime)\r\n\r\n data_dict = np.load(latest_file)\r\n data_dict = data_dict.item()\r\n self._distance_matrix = data_dict['distance']\r\n self._time_matrix = data_dict['time']\r\n\r\n self._locations = self._data.locations\r\n self._time_windows_begin = np.asarray(self._data.jobBegin)\r\n self._time_windows_end = np.asarray(self._data.jobEnd)\r\n\r\n self._num_locations = self._data.node_number\r\n self._capacity_matrix = np.ones([self.num_locations + 1, self.num_locations + 1])\r\n\r\n @property\r\n def service_time(self):\r\n return self._service_time\r\n\r\n @property\r\n def num_locations(self):\r\n return self._num_locations\r\n\r\n @property\r\n def distance_matrix(self):\r\n return self._distance_matrix\r\n\r\n @property\r\n def time_matrix(self):\r\n return self._time_matrix\r\n\r\n @property\r\n def time_windows_begin(self):\r\n return self._time_windows_begin\r\n\r\n @property\r\n def time_windows_end(self):\r\n return self._time_windows_end\r\n\r\n @property\r\n def capacity_matrix(self):\r\n return self._capacity_matrix\r\n\r\n @property\r\n def locations(self):\r\n return self._locations\r\n\r\n\r\n\r\n\r\nclass CreateDistanceEvaluator(object):\r\n def __init__(self, data):\r\n self._distances = data.distance_matrix\r\n\r\n def distance_evaluator(self, from_node, to_node):\r\n if to_node == 0:\r\n return 0\r\n else:\r\n return self._distances[from_node, to_node]\r\n\r\n\r\nclass CreateTimeEvaluator(object):\r\n def __init__(self, data):\r\n self._times = data.time_matrix\r\n self._service_time = data.service_time\r\n\r\n def time_evaluator(self, from_node, to_node):\r\n if to_node == 0:\r\n return 0\r\n else:\r\n return self._service_time[to_node] + self._times[from_node, to_node]\r\n\r\nclass CreateCapacityEvaluator(object):\r\n def __init__(self, data):\r\n self._capacity = data.capacity_matrix\r\n\r\n def capacity_evaluator(self, from_node, to_node):\r\n return self._capacity[to_node][from_node]\r\n\r\n\r\ndef add_distance_dimension(routing, distance_evaluator, data):\r\n distance = \"Distance\"\r\n maximum_distance = 300000000\r\n routing.AddDimension(distance_evaluator, 0, maximum_distance, True, distance)\r\n\r\ndef add_capacity_dimension(routing, capacity_evaluator):\r\n capacity = 'capacity'\r\n max_capacity = 4000000\r\n routing.AddDimension(capacity_evaluator, 0, max_capacity, True, capacity)\r\n\r\ndef add_time_dimension(routing, time_evaluator, data):\r\n time_window = 'time_window'\r\n max_time = 100000000000\r\n routing.AddDimension(time_evaluator, conf.max_earliness, max_time, False, time_window)\r\n time_dimension = routing.GetDimensionOrDie(time_window)\r\n\r\n for location_idx, time_windows_begin in enumerate(data.time_windows_begin):\r\n\r\n time_windows_end = data.time_windows_end[location_idx]\r\n index = routing.NodeToIndex(location_idx)\r\n time_dimension.CumulVar(index).SetRange(int(time_windows_begin + data.service_time[location_idx]), int(time_windows_end))\r\n\r\nclass ConsolePrinter():\r\n def __init__(self, data, routing, assignment, vehicle):\r\n self._data = data\r\n self._routing = routing\r\n self._assignment = assignment\r\n self._vehicle = vehicle\r\n\r\n @property\r\n def data(self):\r\n \"\"\"Gets problem data\"\"\"\r\n return self._data\r\n\r\n @property\r\n def vehicle(self):\r\n \"\"\"Gets problem data\"\"\"\r\n return self._vehicle\r\n\r\n @property\r\n def routing(self):\r\n \"\"\"Gets routing model\"\"\"\r\n return self._routing\r\n\r\n @property\r\n def assignment(self):\r\n \"\"\"Gets routing model\"\"\"\r\n return self._assignment\r\n\r\n def print(self):\r\n total_dist = 0\r\n total_time = 0\r\n time_dimension = self.routing.GetDimensionOrDie('time_window')\r\n\r\n print('\\n-> ##### ROUTING PLAN FOR YoUR PLEASURE ##### <- \\n')\r\n print('\\n NUMBER OF JOBS -> ' + str(len(self._data.locations) - 1) + '\\n')\r\n print('\\n NUMBER OF VEHICLES -> ' + str(self.vehicle.num_vehicles - 1) + '\\n')\r\n for vehicle_id in xrange(1,self.vehicle.num_vehicles):\r\n index = self.routing.Start(vehicle_id)\r\n\r\n plan_output = 'Route for vehicle {0}:\\n'.format(vehicle_id)\r\n route_dist = 0\r\n arc_time = 0\r\n while not self.routing.IsEnd(index):\r\n\r\n node_index = self.routing.IndexToNode(index)\r\n next_node_index = self.routing.IndexToNode(self.assignment.Value(self.routing.NextVar(index)))\r\n\r\n max_time_check = self._data.time_windows_end[node_index]\r\n min_time_check = self._data.time_windows_begin[node_index]\r\n\r\n time_var = time_dimension.CumulVar(index)\r\n time_min = self.assignment.Min(time_var)\r\n\r\n if node_index != 0:\r\n d_route_dist = self._data.distance_matrix[node_index, next_node_index]\r\n d_arc_time = self._data.time_matrix[node_index, next_node_index]\r\n if next_node_index != 0:\r\n route_dist += d_route_dist\r\n arc_time += d_arc_time\r\n plan_output += ' {0} JOB({1},{2}) WIN({3},{4}) ->({5})->'.format(\r\n node_index,\r\n datetime.timedelta(seconds= int(time_min - self._data.service_time[node_index])), datetime.timedelta(seconds = int(time_min)),\r\n datetime.timedelta(seconds=int( min_time_check )), datetime.timedelta(seconds=int( max_time_check)), datetime.timedelta(seconds=int(d_arc_time)))\r\n else:\r\n plan_output += ' {0} JOB({1},{2}) WIN({3},{4}) '.format(\r\n node_index,\r\n datetime.timedelta(seconds=int(time_min - self._data.service_time[node_index])),\r\n datetime.timedelta(seconds=int(time_min)),\r\n datetime.timedelta(seconds=int(min_time_check)),\r\n datetime.timedelta(seconds=int(max_time_check)))\r\n\r\n\r\n index = self.assignment.Value(self.routing.NextVar(index))\r\n total_dist += route_dist\r\n total_time += arc_time\r\n plan_output += '\\n Distance of the route: {0}m\\n'.format(route_dist)\r\n plan_output += '\\n Total Travel Time of the route: {0} hours\\n'.format(arc_time/3600)\r\n print(plan_output)\r\n\r\n print('Total Distance of all routes: {0}m'.format(total_dist))\r\n print('Total Travel Time of all routes: {0} hours'.format(total_time/3600))\r\n\r\n\r\ndef run_optimization(iterator, print_result = False):\r\n vehicle = Vehicle(conf.number_of_vehicles - iterator)\r\n data = DataProblem(google_maps_key=conf.API_KEY, json_file_path=os.path.join(conf.json_file_path,conf.json_file_name))\r\n\r\n routing = pywrapcp.RoutingModel(data.num_locations, vehicle.num_vehicles, vehicle.init_vehicles_locations, vehicle.end_vehicles_locations )\r\n distance_evaluator = CreateDistanceEvaluator(data).distance_evaluator\r\n time_evaluator = CreateTimeEvaluator(data).time_evaluator\r\n\r\n\r\n if conf.minimize_distance:\r\n routing.SetArcCostEvaluatorOfAllVehicles(distance_evaluator)\r\n else:\r\n routing.SetArcCostEvaluatorOfAllVehicles(time_evaluator)\r\n\r\n add_time_dimension(routing, time_evaluator, data)\r\n\r\n search_parameters = pywrapcp.RoutingModel.DefaultSearchParameters()\r\n search_parameters.time_limit_ms = conf.max_time_search_limit*1000\r\n search_parameters.first_solution_strategy = (\r\n routing_enums_pb2.FirstSolutionStrategy.AUTOMATIC)\r\n\r\n search_parameters.local_search_metaheuristic = (\r\n routing_enums_pb2.LocalSearchMetaheuristic.OBJECTIVE_TABU_SEARCH)\r\n\r\n assignment = routing.SolveWithParameters(search_parameters)\r\n assignment.Value(routing.NextVar(0))\r\n\r\n if print_result:\r\n ConsolePrinter(data, routing, assignment, vehicle).print()\r\n\r\n return assignment\r\n\r\n\r\n\r\ndef main():\r\n\r\n for i in range(conf.number_of_vehicles):\r\n try:\r\n run_optimization(i, print_result=False)\r\n if i == conf.number_of_vehicles-1:\r\n run_optimization(i, print_result=True)\r\n\r\n except:\r\n run_optimization(i-1, print_result=True)\r\n break\r\n\r\n\r\nmain()","sub_path":"solver.py","file_name":"solver.py","file_ext":"py","file_size_in_byte":9657,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"586993119","text":"import random\r\nimport sys\r\n\"\"\"\r\n/* ******************************************************************\r\n ALTERNATING BIT AND GO-BACK-N NETWORK EMULATOR: VERSION 1.1 J.F.Kurose\r\n\r\n This code should be used for PA2, unidirectional or bidirectional\r\n data transfer protocols (from A to B. Bidirectional transfer of data\r\n is for extra credit and is not required). Network properties:\r\n - one way network delay averages five time units (longer if there\r\n are other messages in the channel for GBN), but can be larger\r\n - packets can be corrupted (either the header or the data portion)\r\n or lost, according to user-defined probabilities\r\n - packets will be delivered in the order in which they were sent\r\n (although some can be lost).\r\n**********************************************************************/\r\n\"\"\"\r\n\r\nBIDIRECTIONAL = False # DON'T CHANGE THIS\r\n # /* change to 1 if you're doing extra credit */\r\n # /* and write a routine called B_output */\r\n\r\n# Structures\r\n\"\"\"\r\n/* a \"msg\" is the data unit passed from layer 5 (teachers code) to layer */\r\n/* 4 (students' code). It contains the data (characters) to be delivered */\r\n/* to layer 5 via the students transport level protocol entities. */\r\n\r\n The only instance variable of the Msg class is the data field. Data is just\r\n a bytes object that represents the application data being passed to you\r\n reliable delivery transport protocol.\r\n\"\"\"\r\nclass Msg():\r\n def __init__(self):\r\n self.data = b\"\"\r\n # end def __init__()\r\n\r\n def __str__(self):\r\n return \"Message Data: \" + str(self.data)\r\n # end def __str_()\r\n# end class Msg\r\n\r\n\"\"\"\r\n/* a packet is the data unit passed from layer 4 (students code) to layer */\r\n/* 3 (teachers code). Note the pre-defined packet structure, which all */\r\n/* students must follow. */\r\n\r\n The Pkt class represents the transport layer segment used by your reliable\r\n transport protocol.\r\n The Pkt class has four attributes. seqnum is the sequence number assigned to\r\n the Pkt object, the acknum is the acknowledgement number sent in response, and\r\n the checksum is the checksum calculated for this segment. Finally, payload is\r\n where the application layer data is stored--it is a bytes object just like the\r\n field in a Msg object.\r\n\"\"\"\r\nclass Pkt():\r\n def __init__(self):\r\n self.seqnum = -1\r\n self.acknum = -1\r\n self.checksum = -1\r\n self.payload = b\"\"\r\n # end def __init__()\r\n\r\n def __str__(self):\r\n s = \"\"\r\n s += \"Seqnum: \" + str(self.seqnum) + \"\\n\"\r\n s += \"Acknum: \" + str(self.acknum) + \"\\n\"\r\n s += \"Checksum: \" + str(self.checksum) + \"\\n\"\r\n s += \"Payload: \" + str(self.payload)\r\n return s\r\n # end def __str__()\r\n# end class Pkt\r\n\r\n\"\"\"\r\n The Event class is used by the simulator to construct network events (Pkt\r\n sending, Pkt receiving, Pkt corruption, timeouts.\r\n You should not have to deal with this class directly.\r\n\"\"\"\r\nclass Event():\r\n def __init__(self):\r\n self.evtime = None\r\n self.evtype = None\r\n self.eventity = None\r\n self.pktptr = None\r\n self.prev = None\r\n self.next = None\r\n # end def __init__()\r\n\r\n def __str__(self):\r\n event_types = (\"Timer Interrupt\", \"From Layer 5\", \"From Layer 3\")\r\n entities = [\"Host A\", \"Host B\"]\r\n s = \"\"\r\n s += \"Event Type: \" + event_types[self.evtype] + \"\\n\"\r\n s += \"Event Time: \" + str(self.evtime) + \"\\n\"\r\n s += \"Event Entity: \" + entities[self.eventity] + \"\\n\"\r\n s += \"Packet: \" + str(self.pktptr)\r\n return s\r\n # end def __str__()\r\n# end class Event\r\n\r\n# /********* STUDENTS WRITE THE NEXT SEVEN ROUTINES *********/\r\n\r\n# PLEASE ALSO SEE THE STUDENT CALLABLE ROUTINES FURTHER DOWN.\r\n# You will use those functions--starttimer, stoptimer, tolayer3, tolayer5--to\r\n# implement your reliable delivery algorithm.\r\n\r\n\r\n# /* called from layer 5, passed the data to be sent to other side */\r\n# This function will be called when the simulator generates application data for\r\n# Host A to send to Host B. The input is a Msg object, the ouput should be a\r\n# Pkt object constructed to contain the application data in message, and then\r\n# sent to Layer 3 (the network layer controlled by the simulator.\r\n# Call the tolayer3() function, passing it your new Pkt.\r\n\r\ncount = -1 #total number of packets send, used for seqnum\r\ncurrentPacket = None #used to check for correct ACK (timeout may send incorrect ACK)\r\nprevPacket = None #used for reciever to detect duplicate packet, send ACK quicker\r\nprevAck = None\r\nwaiting = False #bool to see if we are currently waiting for an ACK\r\npackets = []\r\n\r\ndef A_output(message):\r\n print(\"A_output Called...\", message)\r\n sys.stdout.write(\"[Sender building new packet for transportation]\\n\")\r\n global count\r\n count += 1\r\n snum = count % 2 #alternating bit\r\n packet = Pkt()\r\n packet.seqnum = snum\r\n packet.payload = message.data\r\n # packet.checksum = len(packet.payload) + 2\r\n check = 2\r\n for i in range(0, len(packet.payload)):\r\n check = check + ord(packet.payload[i:i+1])\r\n packet.checksum = check\r\n global packets\r\n packets.append(packet)\r\n sendPacket()\r\n global waiting\r\n waiting = True\r\n\r\ndef sendPacket():\r\n global waiting\r\n global packets\r\n global lambda_\r\n if (not waiting and len(packets) > 0): #if we are not current waiting for an ACK and there are packets to send\r\n sys.stdout.write(\"[Sender sending packet to network layer]\\n\")\r\n tolayer3(A, packets[0])\r\n sys.stdout.write(\"[Starting timer for packet]\\n\")\r\n starttimer(A, lambda_) #start timer, wait for ack\r\n # waiting = True\r\n global currentPacket\r\n currentPacket = packets[0]\r\n packets.pop()\r\n\r\n# /* called from layer 3, when a packet arrives for layer 4 at A*/\r\ndef A_input(packet):\r\n global currentPacket\r\n global packets\r\n global waiting\r\n print(\"A_input Called:\\n\" + str(packet))\r\n sys.stdout.write(\"[Sender recieved packet from network layer]\\n\")\r\n if (currentPacket is not None):\r\n check = 2\r\n for i in range(0, len(packet.payload)):\r\n check = check + ord(packet.payload[i:i+1])\r\n if (check != packet.checksum):\r\n sys.stdout.write(\"[Sender recieved a corrupted packet from reciever! Discarding...]\\n\")\r\n elif (packet.seqnum == packet.acknum and currentPacket.seqnum == packet.seqnum):\r\n sys.stdout.write(\"[Sender recieved correct ACK from reciever]\\n\")\r\n sys.stdout.write(\"[Timer stopped for packet]\\n\")\r\n stoptimer(A)\r\n # packets.pop()\r\n waiting = False\r\n currentPacket = None\r\n sendPacket()\r\n else:\r\n sys.stdout.write(\"[Sender recieved incorrect ACK from reciever! Ignoring...]\\n\")\r\n else:\r\n sys.stdout.write(\"[Sender already recieved correct ACK! Ignoring...]\\n\")\r\n\r\n# /* called when A's timer goes off */\r\ndef A_timerinterrupt():\r\n print(\"A_timerinterrupt Called...\")\r\n global lambda_\r\n sys.stdout.write(\"[Timeout! Sender resending packet...]\\n\")\r\n # stoptimer(A)\r\n global currentPacket\r\n tolayer3(A, currentPacket)\r\n sys.stdout.write(\"[Starting timer for packet]\\n\")\r\n starttimer(A, lambda_)\r\n # sendPacket()\r\n\r\n# /* the following routine will be called once (only) before any other */\r\n# /* entity A routines are called. You can use it to do any initialization */\r\ndef A_init():\r\n print(\"A_init Called...\")\r\n\r\n# /* called from layer 3, when a packet arrives for layer 4 at B*/\r\n#### CHECK FOR DUPE PACKET! ####\r\ndef B_input(packet):\r\n print(\"B_input Called:\\n\" + str(packet))\r\n global prevAck\r\n global prevPacket\r\n global currentPacket\r\n sys.stdout.write(\"[Reciever recieved packet from network layer]\\n\")\r\n # check = len(packet.payload) + 2\r\n check = 2\r\n for i in range(0, len(packet.payload)):\r\n check = check + ord(packet.payload[i:i+1])\r\n\r\n if (check != packet.checksum or (packet.seqnum > 1 or packet.seqnum < 0) or packet.acknum != -1):\r\n sys.stdout.write(\"[Recieved corrupt packet! Discarding...]\\n\")\r\n # elif (currentPacket.seqnum != packet.seqnum):\r\n # sys.stdout.write(\"[Recieved wrong packet to ACK! Discarding...]\\n\")\r\n elif (prevPacket and pEquals(prevPacket, packet)):\r\n sys.stdout.write(\"[Recieved duplicate packet! Resending ACK...]\\n\")\r\n tolayer3(B, prevAck)\r\n else:\r\n toA = Pkt()\r\n toA.seqnum = packet.seqnum\r\n toA.acknum = toA.seqnum\r\n toA.payload = packet.payload\r\n toA.checksum = packet.checksum\r\n tolayer5(B, toA.payload)\r\n prevAck = toA\r\n prevPacket = packet\r\n sys.stdout.write(\"[Reciever sending back ACK]\\n\")\r\n tolayer3(B, toA)\r\n\r\ndef pEquals(p1, p2):\r\n if (p1.seqnum != p2.seqnum):\r\n return False\r\n elif (p1.payload != p2.payload):\r\n return False\r\n elif (p1.checksum != p2.checksum):\r\n return False\r\n else:\r\n return True\r\n\r\n# /* the following rouytine will be called once (only) before any other */\r\n# /* entity B routines are called. You can use it to do any initialization */\r\ndef B_init():\r\n print(\"B_init Called...\")\r\n\r\n# /* Note that with simplex transfer from a-to-B, there is no B_output() */\r\n# IGNORE THE TWO (2) FUNCTIONS BELOW\r\n# // IGNORE THIS FUNCTION\r\ndef B_output(message):\r\n pass\r\n\r\n# /* called when B's timer goes off */\r\n# // IGNORE THIS FUNCTION\r\ndef B_timerinterrupt():\r\n pass\r\n# IGNORE THE TWO (2) FUNCTIONS ABOVE\r\n\r\n\r\n\"\"\"\r\n/*****************************************************************\r\n***************** NETWORK EMULATION CODE STARTS BELOW ***********\r\nThe code below emulates the layer 3 and below network environment:\r\n - emulates the tranmission and delivery (possibly with bit-level corruption\r\n and packet loss) of packets across the layer 3/4 interface\r\n - handles the starting/stopping of a timer, and generates timer\r\n interrupts (resulting in calling students timer handler).\r\n - generates message to be sent (passed from later 5 to 4)\r\n\r\nTHERE IS NOT REASON THAT ANY STUDENT SHOULD HAVE TO READ OR UNDERSTAND\r\nTHE CODE BELOW. YOU SHOLD NOT TOUCH, OR REFERENCE (in your code) ANY\r\nOF THE DATA STRUCTURES BELOW. If you're interested in how I designed\r\nthe emulator, you're welcome to look at the code - but again, you shouldn't\r\nhave to, and you defeinitely should not have to modify\r\n******************************************************************/\r\n\"\"\"\r\n\r\nevlist = None # /* the event list */\r\n\r\n# Constants\r\n# possible events\r\nTIMER_INTERRUPT = 0\r\nFROM_LAYER5 = 1\r\nFROM_LAYER3 = 2\r\n\r\nOFF = 0\r\nON = 1\r\nA = 0\r\nB = 1\r\n\r\nTRACE = 1 # /* for my debugging */\r\nnsim = 0 # /* number of messages from 5 to 4 so far */\r\nnsimmax = 0 # /* number of msgs to generate, then stop */\r\ntime = 0.0\r\nlossprob = 0.0 # /* probability that a packet is dropped */\r\ncorruptprob = 0.0 # /* probability that one bit is packet is flipped */\r\nlambda_ = 0 # /* arrival rate of messages from layer 5 */\r\nntolayer3 = 0 # /* number sent into layer 3 */\r\nnlost = 0 # /* number lost in media */\r\nncorrupt = 0 # /* number corrupted by media*/\r\n\r\n\r\n\r\ndef main():\r\n global evlist\r\n global time\r\n global nsim\r\n eventptr = None\r\n msg2give = None\r\n pkt2give = None\r\n c = i = j = None\r\n\r\n init()\r\n A_init()\r\n B_init()\r\n\r\n while True:\r\n printevlist()\r\n eventptr = evlist\r\n print(eventptr)\r\n if eventptr == None:\r\n\r\n print(\"Simulator terminated at time \" + str(time) +\r\n \"\\n after sending \" + str(nsim) + \" msgs from layer5\\n\")\r\n return 0\r\n evlist = evlist.next\r\n if evlist != None:\r\n evlist.prev = None\r\n if TRACE >= 2:\r\n print(\"\\nEVENT time: %f,\" % (eventptr.evtime,), end = \"\")\r\n print(\" type: %d\" % (eventptr.evtype,), end = \"\")\r\n if eventptr.evtype == 0:\r\n print(\", timerinterrupt \", end = \"\")\r\n elif eventptr.evtype == 1:\r\n print(\", fromlayer5 \", end = \"\")\r\n else:\r\n print(\", fromlayer3 \", end = \"\")\r\n print(\" entity: %d\\n\" % (eventptr.eventity,), end = \"\")\r\n print()\r\n time = eventptr.evtime\r\n if nsim == nsimmax:\r\n #break\r\n pass\r\n if eventptr.evtype == FROM_LAYER5:\r\n msg2give = Msg()\r\n j = (nsim - 1) % 26\r\n for i in range(20):\r\n msg2give.data = msg2give.data + bytes([(97 + j)])\r\n if nsim < nsimmax:\r\n generate_next_arrival()\r\n nsim += 1\r\n if TRACE >= 2:\r\n print(\"MAINLOOP: data given to student: \", end = \"\")\r\n for i in range(len(msg2give.data)):\r\n print(\"%c\" % msg2give.data[i], end=\"\")\r\n print()\r\n if eventptr.eventity == A:\r\n A_output(msg2give)\r\n else:\r\n B_output(msg2give)\r\n elif eventptr.evtype == FROM_LAYER3:\r\n pkt2give = Pkt()\r\n pkt2give.seqnum = eventptr.pktptr.seqnum\r\n pkt2give.acknum = eventptr.pktptr.acknum\r\n pkt2give.checksum = eventptr.pktptr.checksum\r\n pkt2give.payload = eventptr.pktptr.payload[:]\r\n if eventptr.eventity == A:\r\n A_input(pkt2give)\r\n else:\r\n B_input(pkt2give)\r\n elif eventptr.evtype == TIMER_INTERRUPT:\r\n if eventptr.eventity == A:\r\n A_timerinterrupt()\r\n else:\r\n B_timerinterrupt()\r\n else:\r\n print(\"INTERNAL PANIC: unknown event type \\n\")\r\n print(\" Simulator terminated at time %f\\n after sending %d msgs from layer5\\n\" % (time, nsim));\r\n return\r\n# end def main()\r\n\r\ndef init():\r\n global nsim\r\n global nsimmax\r\n global lossprob\r\n global corruptprob\r\n global lambda_\r\n global TRACE\r\n global ntolayer3\r\n global nlost\r\n global ncorrupt\r\n global time\r\n\r\n print(\"----- Stop and Wait Network Simulator Version 1.1 -------- \\n\\n\")\r\n nsimmax = int(input(\"Enter the number of messages to simulate: \"))\r\n lossprob = float(input(\"Enter packet loss probability [enter 0.0 for no loss]:\"))\r\n corruptprob = float(input(\"Enter packet corruption probability [0.0 for no corruption]:\"))\r\n lambda_ = float(input(\"Enter average time between messages from sender's layer5 [ > 0.0]:\"))\r\n TRACE = int(input(\"Enter TRACE:\"))\r\n print()\r\n\r\n # If you uncomment this code and pass a fixed integer argument to the \"a\"\r\n # parameter, then you can repeat the same sequence of random events. For\r\n # testing purposes only.\r\n #random.seed(a = 9999)\r\n sum = 0.0\r\n for i in range(1000):\r\n sum = sum + random.uniform(0, 1)\r\n avg = sum/1000.0\r\n if avg < 0.25 or avg > 0.75:\r\n print(\"It is likely that random number generation on your machine\" )\r\n print(\"is different from what this emulator expects. Please take\")\r\n print(\"a look at the routine jimsrand() in the emulator code. Sorry. \\n\")\r\n sys.exit(-1)\r\n\r\n ntolayer3 = 0\r\n nlost = 0\r\n ncorrupt = 0\r\n\r\n time = 0.0\r\n generate_next_arrival()\r\n nsim += 1\r\n# end def init()\r\n\r\n\"\"\"\r\n/********************* EVENT HANDLINE ROUTINES *******/\r\n/* The next set of routines handle the event list */\r\n/*****************************************************/\r\n\"\"\"\r\n\r\ndef generate_next_arrival():\r\n if TRACE >= 2:\r\n print(\"GENERATE NEXT ARRIVAL: creating new arrival\")\r\n x = lambda_ * (random.uniform(0, 1) * 2) # /* x is uniform on [0,2*lambda] */\r\n # /* having mean of lambda */\r\n evptr = Event()\r\n evptr.evtime = time + x\r\n evptr.evtype = FROM_LAYER5\r\n if BIDIRECTIONAL and (random.uniform(0, 1) > 5):\r\n evptr.eventity = B\r\n else:\r\n evptr.eventity = A\r\n insertevent(evptr)\r\n# end def generate_next_arrival()\r\n\r\ndef insertevent(p):\r\n global evlist\r\n\r\n if TRACE >= 2:\r\n print(\"INSERTEVENT: time is %lf\" % (time,))\r\n print(\"INSERTEVENT: future time will be %lf\" % (p.evtime,))\r\n print()\r\n\r\n q = evlist # /* q points to header of list in which p struct inserted */\r\n if q is None: # /* list is empty */\r\n evlist = p\r\n p.next = None\r\n p.prev = None\r\n else:\r\n qold = q\r\n while q is not None and p.evtime > q.evtime:\r\n qold = q\r\n q = q.next\r\n if q is None: # /* end of list */\r\n qold.next = p\r\n p.prev = qold\r\n p.next = None\r\n elif q is evlist: # /* front of list */\r\n p.next = evlist\r\n p.prev = None\r\n p.next.prev = p\r\n evlist = p\r\n else:\r\n p.next = q\r\n p.prev = q.prev\r\n q.prev.next = p\r\n q.prev = p\r\n# end def insertevent()\r\n\r\ndef printevlist():\r\n print(\"--------------\\nEvent List Follows:\\n\")\r\n q = evlist\r\n while q is not None:\r\n print(\"Event time: %f, type: %d, entity: %d\\n\" % (q.evtime, q.evtype, q.eventity))\r\n q = q.next\r\n print(\"--------------\\n\")\r\n\r\n# /********************** Student-callable ROUTINES ***********************/\r\n\r\n# /* called by students routine to cancel a previously-started timer */\r\ndef stoptimer(AorB): # /* A or B is trying to stop timer */\r\n global evlist\r\n if TRACE >= 2:\r\n print(\"STOP TIMER: stopping timer at %f\\n\" % (time,))\r\n q = evlist\r\n while q is not None:\r\n if q.evtype == TIMER_INTERRUPT and q.eventity == AorB:\r\n # /* remove this event */\r\n if q.next == None and q.prev == None: # /* remove first and only event on list */\r\n evlist = None\r\n elif q.next == None: # /* end of list - there is one in front */\r\n q.prev.next = None\r\n elif q is evlist: # /* front of list - there must be event after */\r\n q.next.prev = None\r\n evlist = q.next\r\n else: # /* middle of list */\r\n q.next.prev = q.prev\r\n q.prev.next = q.next\r\n return\r\n q = q.next\r\n print(\"Warning: unable to cancel your timer. It wasn't running.\\n\")\r\n# end def stoptimer()\r\n\r\ndef starttimer(AorB, increment): # /* A or B is trying to start timer */\r\n if TRACE >= 2:\r\n print(\"START TIMER: starting timer at %f\\n\" % (time,))\r\n # /* be nice: check to see if timer is already started, if so, then warn */\r\n q = evlist\r\n while q is not None:\r\n if q.evtype == TIMER_INTERRUPT and q.eventity == AorB:\r\n print(\"Warning: attempt to start a timer that is already started\\n\")\r\n return\r\n q = q.next\r\n\r\n # /* create future event for when timer goes off */\r\n evptr = Event()\r\n evptr.evtime = time + increment\r\n evptr.evtype = TIMER_INTERRUPT\r\n evptr.eventity = AorB\r\n insertevent(evptr)\r\n# end def starttimer()\r\n\r\n# /************************** TOLAYER3 ***************/\r\n\r\ndef tolayer3(AorB, packet):\r\n global ntolayer3\r\n global nlost\r\n global ncorrupt\r\n ntolayer3 += 1\r\n\r\n # /* simulate losses: */\r\n if random.uniform(0, 1) < lossprob:\r\n nlost += 1\r\n if TRACE > 0:\r\n print(\"TOLAYER3: packet being lost\\n\")\r\n return\r\n\r\n # /* make a copy of the packet student just gave me since he/she may decide */\r\n # /* to do something with the packet after we return back to him/her */\r\n mypktptr = Pkt()\r\n mypktptr.seqnum = packet.seqnum\r\n mypktptr.acknum = packet.acknum\r\n mypktptr.checksum = packet.checksum\r\n mypktptr.payload = packet.payload[:]\r\n if TRACE >= 2:\r\n print(\"TOLAYER3: seq: %d, ack %d, check: %d \" %\r\n (mypktptr.seqnum, mypktptr.acknum, mypktptr.checksum))\r\n print(\" \", end=\"\")\r\n for i in range(len(mypktptr.payload)):\r\n print(chr(mypktptr.payload[i]), end=\"\")\r\n print()\r\n\r\n # /* create future event for arrival of packet at the other side */\r\n evptr = Event()\r\n evptr.evtype = FROM_LAYER3 # /* packet will pop out from layer3 */\r\n evptr.eventity = (AorB + 1) % 2 # /* event occurs at other entity */\r\n evptr.pktptr = mypktptr # /* save ptr to my copy of packet */\r\n # /* finally, compute the arrival time of packet at the other end.\r\n # medium can not reorder, so make sure packet arrives between 1 and 10\r\n # time units after the latest arrival time of packets\r\n # currently in the medium on their way to the destination */\r\n lasttime = time\r\n q = evlist\r\n while q is not None:\r\n if q.evtype == FROM_LAYER3 and q.eventity == evptr.eventity:\r\n lasttime = q.evtime\r\n q = q.next\r\n evptr.evtime = lasttime + 1 + (9 * random.uniform(0, 1))\r\n\r\n # /* simulate corruption: */\r\n if random.uniform(0, 1) < corruptprob:\r\n ncorrupt += 1\r\n x = random.uniform(0, 1)\r\n if x < 0.75:\r\n mypktptr.payload = b'Z' + mypktptr.payload[1::] # /* corrupt payload */\r\n elif x < 0.875:\r\n mypktptr.seqnum = 999999\r\n else:\r\n mypktptr.acknum = 999999\r\n if TRACE > 0:\r\n print(\"TOLAYER3: packet being corrupted\\n\")\r\n\r\n if TRACE >= 2:\r\n print(\" TOLAYER3: scheduling arrival on other side\\n\")\r\n insertevent(evptr)\r\n# end def tolayer3()\r\n\r\ndef tolayer5(AorB, datasent):\r\n \"\"\"\r\n AorB identifies the Host\r\n datasent is a 20 byte message\r\n \"\"\"\r\n datasent = datasent.decode()\r\n if TRACE >= 2:\r\n print(\"TOLAYER5: data received: \")\r\n print(\" \", end=\"\")\r\n for i in range(len(datasent)):\r\n print(datasent[i], end=\"\")\r\n print()\r\n# end def tolayer5()\r\n\r\n\r\nif __name__ == \"__main__\":\r\n main()\r\n","sub_path":"prog2.py","file_name":"prog2.py","file_ext":"py","file_size_in_byte":22012,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"576248832","text":"import sys\nsys.path.append('../../lib')\n\nimport utcoupe\nfrom geometry import Vec\n\n# On détermine la position des verres\npos_verres = [\n (900, 950),\n (1050, 1200),\n (900, 1450)\n ]\nfor i in range(3):\n i = pos_verres[i]\n pos_verres.append((i[0]+300, i[1]))\nfor i in range(6):\n i = pos_verres[i]\n pos_verres.append((3000-i[0], i[1]))\n\nclass Verre:\n def __init__(self, pos):\n self.pos = Vec(pos)\n self.moved = False # <=> est-ce qu'on robot adverse est passé dessus et l'a déplacé ?\n self.taken = False # <=> est-ce qu'on l'a pris ?\n\nclass Verres:\n def __init__(self):\n self.verres = []\n for i in pos_verres:\n self.verres.append(Verre(i))\n\n def pp(self):\n for verre in self.verres:\n print(verre.pos.x, verre.pos.y, verre.moved)\n\n def add_enemy_pos(self, positions):\n \"\"\" Si l'ennemi passe dans le champs des verres on suppose qu'il les a pris ou changé de place donc on dégage\n \"\"\"\n for pos in positions:\n for verre in self.verres:\n if (verre.pos-pos).norm() < utcoupe.RAYON_ENEMY:\n verre.moved = True\n","sub_path":"ia/ia/verre.py","file_name":"verre.py","file_ext":"py","file_size_in_byte":1172,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"146015734","text":"'''\nGiven the names and grades for each student in a Physics class of students, store them in a nested list and print the name(s) of any student(s) having the second lowest grade.\n\nNote: If there are multiple students with the same grade, order their names alphabetically and print each name on a new line.\n'''\n\nstudents = []\ngrades = []\nfor _ in range(int(input('> Length: '))):\n name = input('>>> Name: ')\n score = float(input('>> Grade: '))\n students.append([name, score])\n grades.append(score)\n\nsecondLowest = sorted(list(set(grades)))[1]\nprint(f'Second lowest grade: {secondLowest}')\n\nfor stu_name, stu_score in sorted(students):\n if stu_score == secondLowest:\n print(stu_name)\n","sub_path":"findSecondLowest.py","file_name":"findSecondLowest.py","file_ext":"py","file_size_in_byte":706,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"623290899","text":"# 시계열에서 시작 시간이 맞지 않을 경우 '0'으로 채운다.\nfrom sklearn.preprocessing import StandardScaler, MinMaxScaler\nfrom keras.models import Sequential, Model\nfrom keras.layers import LSTM, Dense, Input, Dropout, Conv1D, MaxPooling1D, Flatten\nimport numpy as np\nimport pandas as pd\nfrom sklearn.model_selection import train_test_split, RandomizedSearchCV\nfrom keras.callbacks import EarlyStopping\nfrom keras.wrappers.scikit_learn import KerasRegressor\nfrom sklearn.decomposition import PCA\n\nfrom keras.layers import LeakyReLU\nleaky = LeakyReLU(alpha = 0.2)\n\n#1. data\nx = pd.read_csv('./data/dacon/comp3/train_features.csv', index_col =0, header = 0)\ny = pd.read_csv('./data/dacon/comp3/train_target.csv', index_col = 0, header = 0)\ntest = pd.read_csv('./data/dacon/comp3/test_features.csv', index_col = 0, header = 0)\n\n\nx = x.drop('Time', axis =1)\ntest = test.drop('Time', axis =1)\n\n\nx = x.values\ny = y.values\nx_pred = test.values\n\nprint(x.shape) # (1050000, 4)\n\n# scaler\nscaler = StandardScaler()\nscaler.fit(x)\nx = scaler.transform(x)\nx_pred = scaler.transform(x_pred)\nprint(x_pred.shape)\n\nx = x.reshape(2800, 375*4)\nx_pred = x_pred.reshape(700, 375*4)\n\npca = PCA(n_components = 15*4)\npca.fit(x)\nx = pca.transform(x)\nx_pred = pca.transform(x_pred)\n\nx = x.reshape(-1, 15, 4)\nx_pred = x_pred.reshape(-1, 15, 4)\n\nprint(x.shape) # (2800, 375, 4)\nprint(x_pred.shape) # (700, 375, 4)\nprint(y.shape) # (2800, 4)\n\n\n\n# train_test_split\nx_train, x_test, y_train, y_test = train_test_split(x, y, random_state = 10, train_size = 0.2)\n\n\n#2. model\ndef build_model(drop = 0.2, optimizer = 'adam'):\n input1 = Input(shape=(15, 4))\n x = Conv1D(100, 2, activation = 'relu')(input1)\n x = Dropout(drop)(x)\n x = Conv1D(150, 2, activation = 'relu')(x)\n x = Dropout(drop)(x)\n x = Flatten()(x)\n x = Dense(200, activation = 'relu')(x)\n x = Dropout(drop)(x)\n x = Dense(250, activation = 'relu')(x)\n x = Dropout(drop)(x)\n x = Dense(210, activation = 'relu')(x)\n x = Dropout(drop)(x)\n x = Dense(130, activation = 'relu')(x)\n x = Dropout(drop)(x)\n x = Dense(110, activation = 'relu')(x)\n x = Dropout(drop)(x)\n x = Dense(50, activation = 'relu')(x)\n x = Dropout(drop)(x)\n x = Dense(30, activation = 'relu')(x) \n x = Dropout(drop)(x)\n output = Dense(4, activation = 'relu')(x)\n\n model = Model(inputs = input1, outputs = output)\n model.compile(loss = 'mse', optimizer = optimizer , metrics = ['mse'])\n return model\n\ndef hyper_params():\n batches = [32, 64, 128]\n epochs = [100, 200 ]\n optimizer = ['rmsprop', 'adam', 'adadelta']\n # dropout = np.linspace(0.1, 0.5, 5)\n return {'batch_size': batches, 'epochs': epochs, 'optimizer': optimizer}\n\nmodel = KerasRegressor(build_fn = build_model, verbose = 1)\n\nparams = hyper_params()\n\nsearch = RandomizedSearchCV(model, param_distributions = params, cv = 3)\n\nsearch.fit(x_train, y_train)\n\nprint('best: ', search.best_params_) \n\nscore = model.score(x_test, y_test)\nprint('score: ', score)\n\n\ny_pred = search.predict(x_pred)\ny_pred1 = search.predict(x_test)\n\n\n# 평가지표\ndef kaeri_metric(y_true, y_pred):\n '''\n y_true: dataframe with true values of X,Y,M,V\n y_pred: dataframe with pred values of X,Y,M,V\n \n return: KAERI metric\n '''\n \n return 0.5 * E1(y_true, y_pred) + 0.5 * E2(y_true, y_pred)\n\n\n### E1과 E2는 아래에 정의됨 ###\n\ndef E1(y_true, y_pred):\n '''\n y_true: dataframe with true values of X,Y,M,V\n y_pred: dataframe with pred values of X,Y,M,V\n \n return: distance error normalized with 2e+04\n '''\n \n _t, _p = np.array(y_true)[:,:2], np.array(y_pred)[:,:2]\n \n return np.mean(np.sum(np.square(_t - _p), axis = 1) / 2e+04)\n\n\ndef E2(y_true, y_pred):\n '''\n y_true: dataframe with true values of X,Y,M,V\n y_pred: dataframe with pred values of X,Y,M,V\n \n return: sum of mass and velocity's mean squared percentage error\n '''\n \n _t, _p = np.array(y_true)[:,2:], np.array(y_pred)[:,2:]\n \n \n return np.mean(np.sum(np.square((_t - _p) / (_t + 1e-06)), axis = 1))\n\nprint(kaeri_metric(y_test, y_pred1))\nprint(E1(y_test, y_pred1))\nprint(E2(y_test, y_pred1))\n\n\na = np.arange(2800, 3500)\nsubmission = pd.DataFrame(y_pred, a)\nsubmission.to_csv('./dacon/comp3/submission_2.csv', index = True, index_label= ['id'], header = ['X', 'Y', 'M', 'V'])\n'''\n\n'''","sub_path":"dacon/comp3/dacon04_search.py","file_name":"dacon04_search.py","file_ext":"py","file_size_in_byte":4441,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"169375691","text":"\"\"\"\nPlotting for helita data objects (e.g. BifrostData, EbysusData)\n\nattach methods directly to those objects, for convenience.\n\"\"\"\n\nimport numpy as np\n\nfrom .tools import (\n ImportFailed,\n NO_VALUE,\n centered_extent1D, centered_extent, make_cax,\n format_docstring,\n)\n\ntry:\n import matplotlib.pyplot as plt\nexcept ImportError:\n plt = ImportFailed('matplotlib.pyplot')\n\n\nclass Plottable3D():\n '''lots of helpful methods for plotting data from a 3D helita data object.\n Intended to be subclassed (e.g. BifrostData inherit from Plottable3D),\n rather than instantiated directly.\n Assumes the existence of many properties available to BifrostData.\n '''\n # [TODO] make a more generic HelitaData3D, then make Plottable3D a subclass of that.\n\n def _get_plottable_var_and_vals(self, var_or_vals):\n '''returns (varname, var_or_vals as an ndarray)\n if var is a string, returns (var_or_vals, self(var_or_vals))\n otherwise, returns (None, np.asanyarray(var_or_vals))\n '''\n if isinstance(var_or_vals, str):\n var = var_or_vals\n vals = self(var)\n else:\n var = None # unknown var name.\n vals = np.asanyarray(var_or_vals)\n return (var, vals)\n\n def imshow(self, var_or_vals, axes=None, *, at_x=None, at_y=None, at_z=None,\n log=False, usi_key=None, ucgs_key=None,\n coord_units='si', xcoord_transform=None, ycoord_transform=None,\n colorbar=True, cbar_label=None, kw_cbar=dict(), sca_cbar=False,\n origin=NO_VALUE, extent=NO_VALUE, flipz=False,\n interpolation='none',\n **kw__imshow):\n '''plot var.T as a 2D image.\n var_or_vals: str or ndarray\n if str, use self(var_or_vals).\n if 3D...\n if exactly one of the dimensions has length 1, infer the axes based on that.\n e.g. shape (100, 1, 50) --> plot along the x & z axes; use at_y=0.\n if none of the dimensions have length 1, must provide axes, at_x, at_y, or at_z.\n if 2D...\n must provide axes.\n axes: None, or str or tuple with length 2, contents 'x', 'y', 'z', 0, 1, or 2.\n which axes to plot. E.g. 'xz' or (0, 2) or (0, 'z').\n None --> infer from at_x, at_y, at_z, or shape of array.\n length 2 --> use axes[0] as the x axis on the plot; axes[1] as the y axis.\n at_x, at_y, at_z: None or int\n index along this axis to choose. provide at most one of these values.\n E.g., if at_y=7, then the array to plot will be var_or_vals[:, 7, :].\n log: bool, default False\n if True, take log10(abs(vals)) before plotting.\n usi_key: None or str\n if provided, convert to si via val=val*self.uni(usi_key, 'si', self.units_output)\n ucgs_key: None or str\n if provided, convert to cgs via val=val*self.uni(ucgs_key, 'cgs', self.units_output)\n coord_units: str\n units for coords of axes. 'si', 'cgs', or 'simu'.\n xcoord_transform, ycoord_transform: None or callable of one argument\n if provided, apply to xcoord and ycoord before plotting.\n xcoord and ycoord correspond to the plot x-axis & y-axis,\n e.g. if axes='xz' then xcoord <--> 'x'; ycoord <--> 'z'.\n if provided, will not include units in the label for that coordinate.\n (you should label it separately, e.g. plt.xlabel(...))\n colorbar: bool, default True\n whether to make a colorbar as well.\n if True, will use tools.make_cax to make the colorbar axis\n cbar_label: None or str\n if provided and colorbar=True, label the colorbar with this label\n kw_cbar: dict\n pass these kwargs to plt.colorbar()\n sca_cbar: bool, default False\n whether to set current axis to the colorbar axis.\n if False, instead ensure current axis is the image axis.\n flipz: bool, default False\n if True, \"flip z axis\" (only applies if one of the axes is 'z' (or 2))\n This accounts for Bifrost z coordinate being upside-down & negative.\n It changes the default extent to use -zcoords[::-1], and origin='upper'.\n origin: NO_VALUE, None, or str\n if NO_VALUE, use default of 'lower' if flipz=False, else 'upper'.\n otherwise, pass this value directly to plt.imshow.\n extent: NO_VALUE, None, or tuple\n if NO_VALUE, use default of determining extent from coordinates (& value of flipz).\n otherwise, pass this value directly to plt.imshow.\n\n additional kwargs go to plt.imshow().\n returns (result of plt.imshow(...), result of plt.colorbar()).\n (if not colorbar, instead just return result of plt.imshow().)\n '''\n # figure out the array & axes to use\n var, vals = self._get_plottable_var_and_vals(var_or_vals)\n array, axes = _get_plottable_array_and_axes(vals, axes=axes, at_x=at_x, at_y=at_y, at_z=at_z, _ndim=2)\n if usi_key is not None and ucgs_key is not None:\n raise ValueError(\"cannot provide BOTH usi_key and ucgs_key\")\n if usi_key is not None:\n array = array * self.uni(usi_key, 'si', self.units_output)\n if ucgs_key is not None:\n array = array * self.uni(ucgs_key, 'cgs', self.units_output)\n if log:\n array = np.log10(np.abs(array))\n array_to_plot = array if (axes[0] > axes[1]) else array.T # get the orientation correct.\n # get the coordinates\n xcoord, ycoord = self.get_coords(units=coord_units, axes=axes)\n if xcoord_transform is not None:\n xcoord = xcoord_transform(xcoord)\n if ycoord_transform is not None:\n ycoord = ycoord_transform(ycoord)\n if flipz and (2 in axes):\n if axes[0] == 2:\n xcoord = -xcoord[::-1]\n else: # axes[1] == 2\n ycoord = -ycoord[::-1]\n if extent is NO_VALUE:\n extent = centered_extent(xcoord, ycoord, ndim0_ok=True)\n if origin is NO_VALUE:\n origin = 'upper' if flipz else 'lower'\n # actually plot the image\n result = plt.imshow(array_to_plot, extent=extent,\n origin=origin, interpolation=interpolation,\n **kw__imshow)\n image_axis = plt.gca()\n # label the image\n xlabel = f'{_axis_to_str(axes[0])}' + (f' [{coord_units}]' if xcoord_transform is None else '')\n ylabel = f'{_axis_to_str(axes[1])}' + (f' [{coord_units}]' if ycoord_transform is None else '')\n plt.xlabel(xlabel); plt.ylabel(ylabel)\n if usi_key is not None:\n varunits = 'si'\n elif ucgs_key is not None:\n varunits = 'cgs'\n else:\n varunits = getattr(self, 'units_output', None)\n if var is None:\n var = 'var=???'\n title = var if varunits is None else f'{var} [{varunits}]'\n if log:\n title = f'log10(| {title} |)'\n plt.title(title)\n # handle the colorbar\n if colorbar:\n cax = make_cax()\n cbar = plt.colorbar(cax=cax, label=cbar_label, **kw_cbar)\n if not sca_cbar:\n plt.sca(image_axis) # set current axis to image_axis instead of colorbar.\n return result, cbar\n else:\n return result\n\n def set_defaults_alias(self, new_attr, original_attr, *, _instance=True, **defaults):\n '''set self.new_attr = f(*args, **kw), where f does self.original_attr(*args, **kw, **defaults).\n In case any kwargs appear in kw and defaults, use the ones in kw.\n\n E.g. calling self.set_defaults_alias('imshowlog', 'imshow', log=True)\n makes it so that self.imshowlog(*args, **kw) will call self.imshow(*args, **kw, log=True).\n This just affects the default kwargs; if user enters one of them it will still use that,\n e.g. self.imshowlog(*args, log=False) will call self.imshow(*args, log=False).\n\n _instance: bool, default True\n if True, assign result to this instance, only.\n if False, assign result to type(self). I.e., all instances of this type.\n '''\n @format_docstring(original_attr=original_attr, defaults=defaults)\n def _defaults_alias(self, *args, **kw):\n '''alias to self.{original_attr}, with some of the default kwargs adjusted.\n The new values of affected defaults are:\n {defaults}\n '''\n __tracebackhide__ = True\n kw_use = defaults.copy()\n kw_use.update(kw)\n return getattr(self, original_attr)(*args, **kw_use)\n if _instance:\n @format_docstring(doc=_defaults_alias.__doc__)\n def _defaults_alias_instance(*args, **kw):\n '''{doc}'''\n __tracebackhide__ = True\n return _defaults_alias(self, *args, **kw)\n setattr(self, new_attr, _defaults_alias_instance)\n else:\n setattr(type(self), new_attr, _defaults_alias)\n\n\n''' --------------------------- axis selection tools --------------------------- '''\ndef _axis_to_int(axis):\n '''convert axis (str or int) into an integer\n axis can be 'x', 'y', 'z', 0, 1, or 2.\n result will be 0, 1, or 2.\n '''\n return int({'x': 0, 'y': 1, 'z': 2}.get(axis, axis))\n\ndef _axis_to_str(axis):\n '''convert axis (str or int) into a string\n axis can be 'x', 'y', 'z', 0, 1, or 2.\n result will be 'x', 'y', or 'z'.\n '''\n return str({0: 'x', 1: 'y', 2: 'z'}.get(axis, axis))\n\ndef _axes_to_ints(axes):\n '''convert axes to tuple of ints'''\n return tuple(int(_axis_to_int(x)) for x in axes)\n\ndef _unused_axes(axes):\n '''return tuple of ints from 0, 1, 2 for axes missing from axes.'''\n return tuple(set((0,1,2)) - set(_axes_to_ints(axes)))\n\ndef _get_plottable_axes(axes=None, *, at_x=None, at_y=None, at_z=None, ndim=None):\n '''returns (tuple of integers indicating implied axes, tuple for indexing a 3D array).\n if ndim is provided, raise ValueError unless the result implies an array with ndim=ndim.\n '''\n if axes is not None:\n # ensure no conflicts between axes & at_{x}\n axes = _axes_to_ints(axes)\n if 0 in axes and at_x is not None: raise ValueError(f'incompatible axes & at_x: {axes}, {at_x}')\n if 1 in axes and at_y is not None: raise ValueError(f'incompatible axes & at_y: {axes}, {at_y}')\n if 2 in axes and at_z is not None: raise ValueError(f'incompatible axes & at_z: {axes}, {at_z}')\n # default at_{x} = 0\n axes_unused = _unused_axes(axes)\n if 0 in axes_unused and at_x is None: at_x = 0\n if 1 in axes_unused and at_y is None: at_y = 0\n if 2 in axes_unused and at_z is None: at_z = 0\n else:\n # determine which axes to use based on the at_{x} provided\n axes = []\n if at_x is None: axes.append(0)\n if at_y is None: axes.append(1)\n if at_z is None: axes.append(2)\n axes = tuple(axes)\n # ndim check\n if ndim is not None and len(axes) != ndim:\n raise ValueError(f'ndim={ndim} incompatible with axes={axes}')\n # slices calculation\n slices = []\n slices.append(slice(None) if at_x is None else at_x)\n slices.append(slice(None) if at_y is None else at_y)\n slices.append(slice(None) if at_z is None else at_z)\n slices = tuple(slices)\n return (axes, slices)\n\ndef _get_plottable_array_and_axes(array, axes=None, *, at_x=None, at_y=None, at_z=None, _ndim=None):\n '''returns (array indexed appropriately, tuple of integers indicating implied axes).\n raise ValueError if inputs are incompatible.\n\n if array is less than 3D:\n at_x, at_y, or at_z cannot be used.\n axes must be provided, and have length equal to array.ndim\n if _ndim is provided, _ndim must be equal to array.ndim\n if array.ndim == 3:\n use axes and at_x, at_y, at_z to determine which axes to use.\n if those are all None, and _ndim < 3, look for dimensions with size 1, in array.shape[:3].\n if array.ndim > 3:\n try to squeeze the array after the third dimension. If still >3d, raise ValueError.\n squeeze via np.squeeze(array, axis=tuple(range(3, array.ndim))).\n '''\n array = np.asanyarray(array)\n shape = array.shape\n if array.ndim > 3:\n try:\n array = np.squeeze(array, axis=tuple(range(3, array.ndim)))\n except ValueError: # \"cannot select an axis to squeeze out which has size not equal to one\"\n errmsg = f'array cannot be squeezed to ndim==3. array with ndim={array.ndim}, shape={shape}.'\n raise ValueError(errmsg) from None\n if array.ndim < 3:\n if at_x is not None or at_y is not None or at_z is not None:\n raise ValueError(f'at_x, at_y, or at_z provided, but array.ndim={array.ndim} < 3')\n if axes is None:\n raise ValueError(f'axes must be provided for array.ndim={array.ndim} < 3')\n if len(axes) != array.ndim:\n raise ValueError(f'axes={axes} incompatible with array.ndim={array.ndim}')\n if _ndim is not None and _ndim != array.ndim:\n raise ValueError(f'_ndim={_ndim} incompatible with array.ndim={array.ndim}')\n axes, slices = _get_plottable_axes(axes=axes)\n slices_nd = slices[:array.ndim]\n return (array[slices], axes)\n # else, array.ndim >= 3.\n if (_ndim < 3) and (axes is None) and (at_x is None) and (at_y is None) and (at_z is None):\n # try to infer axes from array.shape\n axes = []\n if shape[0] != 1: axes.append(0)\n if shape[1] != 1: axes.append(1)\n if shape[2] != 1: axes.append(2)\n axes = tuple(axes)\n if len(axes) == _ndim:\n axes, slices = _get_plottable_axes(axes=axes, ndim=_ndim)\n return (array[slices], axes)\n else:\n raise ValueError(f'cannot infer axes from array.shape={shape} and _ndim={_ndim}')\n # else, axes, at_x, at_y, or at_z are provided\n axes, slices = _get_plottable_axes(axes=axes, at_x=at_x, at_y=at_y, at_z=at_z, ndim=_ndim)\n return (array[slices], axes)\n","sub_path":"helita/sim/plotting.py","file_name":"plotting.py","file_ext":"py","file_size_in_byte":14323,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"357001836","text":"\"\"\"Contains arguments on training the model.\"\"\"\nimport logging\nimport os\nfrom argparse import ArgumentParser, Namespace\nfrom distutils.util import strtobool\nfrom enum import Enum\nfrom typing import Any, Callable, List\n\nimport torch\n\nfrom agent.config import args\nfrom agent.config import model_args\nfrom agent.evaluation import metric\n\n\nclass OptimizerType(Enum):\n ADAM: str = 'ADAM'\n ADAGRAD: str = 'ADAGRAD'\n RMSPROP: str = 'RMSPROP'\n SGD: str = 'SGD'\n\n def __str__(self) -> str:\n return self.value\n\n\nclass TrainingArgs(args.Args):\n def __init__(self, parser: ArgumentParser):\n super(TrainingArgs, self).__init__()\n\n # Bookkeeping\n parser.add_argument('--save_directory',\n default='',\n type=str,\n help='Location to save model saves and other information.')\n parser.add_argument('--experiment_name',\n default='',\n type=str,\n help='The experiment name. A directory will be created under save_directory for it.')\n parser.add_argument('--log_with_slack',\n default=False,\n type=lambda x: bool(strtobool(x)),\n help='Whether to log experiment details (starting, epoch accuracies, and ending) to a '\n 'Slack channel.')\n\n # TODO: Neither of the two following are actually used anywhere.\n parser.add_argument('--validation_metrics',\n default=[metric.Metric.RELAXED_ENVIRONMENT_ACCURACY,\n metric.Metric.SEQUENCE_ACCURACY,\n metric.Metric.CARD_ACCURACY,\n metric.Metric.EXACT_ENVIRONMENT_ACCURACY,\n metric.Metric.AGENT_DISTANCE,\n metric.Metric.SCORE],\n nargs='+',\n type=metric.Metric,\n help='The metrics to compute on the validation set each epoch.')\n parser.add_argument('--training_metrics',\n default=[metric.Metric.RELAXED_ENVIRONMENT_ACCURACY,\n metric.Metric.SEQUENCE_ACCURACY,\n metric.Metric.CARD_ACCURACY,\n metric.Metric.EXACT_ENVIRONMENT_ACCURACY,\n metric.Metric.AGENT_DISTANCE,\n metric.Metric.SCORE],\n nargs='+',\n type=metric.Metric,\n help='The metrics to compute on the training set each epoch.')\n\n # Data during training\n parser.add_argument('--proportion_of_train_for_accuracy',\n default=0.1,\n type=float,\n help='The number of training games on which to run inference every epoch to compute an '\n 'estimate of the accuracy on the training set.')\n parser.add_argument('--aggregate_examples',\n default=False,\n type=lambda x: bool(strtobool(x)),\n help='Whether to aggregate training examples during training and validation inference as a '\n 'way to improve recovery against error propagation during full game inference.')\n parser.add_argument('--batch_size',\n default=16,\n type=int,\n help='The batch size to use for training.')\n # Training process\n parser.add_argument('--initial_patience',\n default=10.,\n type=float,\n help='Initial patience.')\n parser.add_argument('--patience_update_factor',\n default=1.,\n type=float,\n help='Factor to increase patience by when performance improves.')\n parser.add_argument('--stopping_metric',\n default=metric.Metric.RELAXED_ENVIRONMENT_ACCURACY,\n type=metric.Metric,\n help='Which metric to stop on.')\n\n # Optimizer\n parser.add_argument('--optimizer',\n default=OptimizerType.ADAM,\n type=OptimizerType,\n help='The optimizer type to use.')\n parser.add_argument('--plan_prediction_learning_rate',\n default=0.0075,\n type=float,\n help='Learning rate to use for hex predictor.')\n parser.add_argument('--plan_prediction_l2_coefficient',\n default=0.000001,\n type=float,\n help='Coefficient of the L2 norm for regularization.')\n parser.add_argument('--action_generation_learning_rate',\n default=0.001,\n type=float,\n help='Learning rate to use for action predictor.')\n parser.add_argument('--action_generation_l2_coefficient',\n default=0.,\n type=float,\n help='Coefficient of the L2 norm for regularization.')\n parser.add_argument('--finetune_learning_rate',\n default=0.001,\n type=float,\n help='Learning rate to use for finetuning models.')\n parser.add_argument('--finetune_l2_coefficient',\n default=0.,\n type=float,\n help='Coefficient of the L2 norm for regularization.')\n parser.add_argument('--max_gradient',\n default=-1,\n type=float,\n help='Maximum gradient (for clipping)')\n\n # Coefficients for auxiliary losses.\n parser.add_argument('--pretrain_auxiliary_coefficient_intermediate_goal_probabilities',\n default=0.,\n type=float,\n help='The coefficient for the card reaching loss intermediate in the network.')\n parser.add_argument('--pretrain_auxiliary_coefficient_trajectory_distribution',\n default=0.,\n type=float,\n help='The coefficient for the trajectory distribution loss.')\n parser.add_argument('--pretrain_auxiliary_coefficient_final_goal_probabilities',\n default=0.,\n type=float,\n help='The coefficient for the final card prediction.')\n parser.add_argument('--pretrain_auxiliary_coefficient_obstacle_probabilities',\n default=0.,\n type=float,\n help='The coefficient of the prediction of hexes which cannot be passed through.')\n parser.add_argument('--pretrain_auxiliary_coefficient_avoid_probabilities',\n default=0.,\n type=float,\n help='The coefficient of the prediction of hexes to avoid (e.g., card it should not pick '\n 'up)')\n parser.add_argument('--finetune_auxiliary_coefficient_intermediate_goal_probabilities',\n default=0.,\n type=float,\n help='The coefficient for the card reaching loss intermediate in the network.')\n parser.add_argument('--finetune_auxiliary_coefficient_trajectory_distribution',\n default=0.,\n type=float,\n help='The coefficient for the trajectory distribution loss.')\n parser.add_argument('--finetune_auxiliary_coefficient_final_goal_probabilities',\n default=0.,\n type=float,\n help='The coefficient for the final card prediction.')\n parser.add_argument('--finetune_auxiliary_coefficient_obstacle_probabilities',\n default=0.,\n type=float,\n help='The coefficient of the prediction of hexes which cannot be passed through.')\n parser.add_argument('--finetune_auxiliary_coefficient_avoid_probabilities',\n default=0.,\n type=float,\n help='The coefficient of the prediction of hexes to avoid (e.g., card it should not pick '\n 'up)')\n parser.add_argument('--finetune_auxiliary_coefficient_implicit_actions',\n default=0.,\n type=float,\n help='The coefficient on the implicit example prediction')\n\n self._batch_size: int = None\n self._log_with_slack: bool = None\n\n self._initial_patience: float = None\n self._patience_update_factor: float = None\n\n self._plan_prediction_learning_rate: float = None\n self._plan_prediction_l2_coefficient: float = None\n\n self._action_generation_learning_rate: float = None\n self._action_generation_l2_coefficient: float = None\n\n self._finetune_learning_rate: float = None\n self._finetune_l2_coefficient: float = None\n\n self._optimizer_type: OptimizerType = None\n self._max_gradient: float = None\n\n self._proportion_of_train_for_accuracy: int = None\n\n self._save_directory: str = None\n self._experiment_name: str = None\n\n self._stopping_metric: metric.Metric = None\n\n self._validation_metrics: List[metric.Metric] = None\n self._training_metrics: List[metric.Metric] = None\n\n self._pretrain_auxiliary_coefficient_intermediate_goal_probabilities: float = None\n self._pretrain_auxiliary_coefficient_trajectory_distribution: float = None\n self._pretrain_auxiliary_coefficient_final_goal_probabilities: float = None\n self._pretrain_auxiliary_coefficient_obstacle_probabilities: float = None\n self._pretrain_auxiliary_coefficient_avoid_probabilities: float = None\n self._finetune_auxiliary_coefficient_intermediate_goal_probabilities: float = None\n self._finetune_auxiliary_coefficient_trajectory_distribution: float = None\n self._finetune_auxiliary_coefficient_final_goal_probabilities: float = None\n self._finetune_auxiliary_coefficient_obstacle_probabilities: float = None\n self._finetune_auxiliary_coefficient_avoid_probabilities: float = None\n self._finetune_auxiliary_coefficient_implicit_actions: float = None\n\n self._aggregate_examples: bool = None\n\n def log_with_slack(self) -> bool:\n self.check_initialized()\n return self._log_with_slack\n\n def get_batch_size(self) -> int:\n self.check_initialized()\n return self._batch_size\n\n def aggregate_examples(self) -> bool:\n self.check_initialized()\n return self._aggregate_examples\n\n def get_auxiliary_coefficient_avoid_probabilities(self, finetune: bool) -> float:\n self.check_initialized()\n if finetune:\n return self._finetune_auxiliary_coefficient_avoid_probabilities\n return self._pretrain_auxiliary_coefficient_avoid_probabilities\n\n def get_auxiliary_coefficient_obstacle_probabilities(self, finetune: bool) -> float:\n self.check_initialized()\n if finetune:\n return self._finetune_auxiliary_coefficient_obstacle_probabilities\n return self._pretrain_auxiliary_coefficient_obstacle_probabilities\n\n def get_auxiliary_coefficient_trajectory_distribution(self, finetune: bool) -> float:\n self.check_initialized()\n if finetune:\n return self._finetune_auxiliary_coefficient_trajectory_distribution\n return self._pretrain_auxiliary_coefficient_trajectory_distribution\n\n def get_auxiliary_coefficient_final_goal_probabilities(self, finetune: bool) -> float:\n self.check_initialized()\n if finetune:\n return self._finetune_auxiliary_coefficient_final_goal_probabilities\n return self._pretrain_auxiliary_coefficient_final_goal_probabilities\n\n def get_auxiliary_coefficient_intermediate_goal_probabilities(self, finetune: bool) -> float:\n self.check_initialized()\n if finetune:\n return self._finetune_auxiliary_coefficient_intermediate_goal_probabilities\n return self._pretrain_auxiliary_coefficient_intermediate_goal_probabilities\n\n def get_auxiliary_coefficient_implicit_actions(self) -> float:\n return self._finetune_auxiliary_coefficient_implicit_actions\n\n def get_validation_metrics(self) -> List[metric.Metric]:\n self.check_initialized()\n return self._validation_metrics\n\n def get_training_metrics(self) -> List[metric.Metric]:\n self.check_initialized()\n return self._training_metrics\n\n def get_initial_patience(self) -> float:\n self.check_initialized()\n return self._initial_patience\n\n def get_patience_update_factor(self) -> float:\n self.check_initialized()\n return self._patience_update_factor\n\n def get_max_gradient(self) -> float:\n self.check_initialized()\n return self._max_gradient\n\n def get_stopping_metric(self) -> metric.Metric:\n self.check_initialized()\n return self._stopping_metric\n\n def get_save_directory(self) -> str:\n self.check_initialized()\n\n # Create the dir if it does not exist\n full_dir: str = os.path.join(self._save_directory, self._experiment_name)\n if not os.path.exists(full_dir):\n print('Created directory: ' + full_dir)\n os.mkdir(full_dir)\n\n return full_dir\n\n def get_proportion_of_train_for_accuracy(self) -> int:\n self.check_initialized()\n return self._proportion_of_train_for_accuracy\n\n def get_experiment_name(self) -> str:\n self.check_initialized()\n return self._experiment_name\n\n def get_optimizer(self, task: model_args.Task, finetune: bool = False) -> Callable[[Any], torch.optim.Optimizer]:\n self.check_initialized()\n\n learning_rate: float = 0.\n l2_coefficient: float = 0.\n if task == model_args.Task.PLAN_PREDICTOR:\n learning_rate = self._plan_prediction_learning_rate\n l2_coefficient = self._plan_prediction_l2_coefficient\n elif task == model_args.Task.ACTION_GENERATOR:\n if finetune:\n learning_rate = self._finetune_learning_rate\n l2_coefficient = self._finetune_l2_coefficient\n else:\n learning_rate = self._action_generation_learning_rate\n l2_coefficient = self._action_generation_l2_coefficient\n\n if self._optimizer_type == OptimizerType.ADAM:\n logging.info('Adam with lr = ' + str(learning_rate) + ', weight decay = ' + str(l2_coefficient))\n return lambda params: torch.optim.Adam(params, lr=learning_rate, weight_decay=l2_coefficient)\n elif self._optimizer_type == OptimizerType.ADAGRAD:\n logging.info('Adagrad with lr = ' + str(learning_rate) + ', weight decay = ' + str(l2_coefficient))\n return lambda params: torch.optim.Adagrad(params, lr=learning_rate, weight_decay=l2_coefficient)\n elif self._optimizer_type == OptimizerType.RMSPROP:\n logging.info('RMSProp with lr = ' + str(learning_rate) + ', weight decay = ' + str(l2_coefficient))\n return lambda params: torch.optim.RMSprop(params, lr=learning_rate, weight_decay=l2_coefficient)\n elif self._optimizer_type == OptimizerType.SGD:\n logging.info('SGD with lr = ' + str(learning_rate) + ', weight decay = ' + str(l2_coefficient))\n return lambda params: torch.optim.SGD(params, lr=learning_rate, weight_decay=l2_coefficient)\n\n def interpret_args(self, parsed_args: Namespace) -> None:\n self._batch_size = parsed_args.batch_size\n self._save_directory = parsed_args.save_directory\n self._experiment_name = parsed_args.experiment_name\n\n self._log_with_slack = parsed_args.log_with_slack\n\n self._proportion_of_train_for_accuracy = parsed_args.proportion_of_train_for_accuracy\n\n self._optimizer_type = parsed_args.optimizer\n\n self._stopping_metric = parsed_args.stopping_metric\n self._validation_metrics = parsed_args.validation_metrics\n self._training_metrics = parsed_args.training_metrics\n self._max_gradient = parsed_args.max_gradient\n\n self._plan_prediction_learning_rate = parsed_args.plan_prediction_learning_rate\n self._plan_prediction_l2_coefficient = parsed_args.plan_prediction_l2_coefficient\n self._action_generation_learning_rate = parsed_args.action_generation_learning_rate\n self._action_generation_l2_coefficient = parsed_args.action_generation_l2_coefficient\n self._finetune_l2_coefficient = parsed_args.finetune_l2_coefficient\n self._finetune_learning_rate = parsed_args.finetune_learning_rate\n\n self._pretrain_auxiliary_coefficient_intermediate_goal_probabilities = \\\n parsed_args.pretrain_auxiliary_coefficient_intermediate_goal_probabilities\n self._pretrain_auxiliary_coefficient_trajectory_distribution = \\\n parsed_args.pretrain_auxiliary_coefficient_trajectory_distribution\n self._pretrain_auxiliary_coefficient_final_goal_probabilities = \\\n parsed_args.pretrain_auxiliary_coefficient_final_goal_probabilities\n self._pretrain_auxiliary_coefficient_obstacle_probabilities = \\\n parsed_args.pretrain_auxiliary_coefficient_obstacle_probabilities\n self._pretrain_auxiliary_coefficient_avoid_probabilities = \\\n parsed_args.pretrain_auxiliary_coefficient_avoid_probabilities\n self._finetune_auxiliary_coefficient_intermediate_goal_probabilities = \\\n parsed_args.finetune_auxiliary_coefficient_intermediate_goal_probabilities\n self._finetune_auxiliary_coefficient_trajectory_distribution = \\\n parsed_args.finetune_auxiliary_coefficient_trajectory_distribution\n self._finetune_auxiliary_coefficient_final_goal_probabilities = \\\n parsed_args.finetune_auxiliary_coefficient_final_goal_probabilities\n self._finetune_auxiliary_coefficient_obstacle_probabilities = \\\n parsed_args.finetune_auxiliary_coefficient_obstacle_probabilities\n self._finetune_auxiliary_coefficient_avoid_probabilities = \\\n parsed_args.finetune_auxiliary_coefficient_avoid_probabilities\n self._finetune_auxiliary_coefficient_implicit_actions = \\\n parsed_args.finetune_auxiliary_coefficient_implicit_actions\n\n self._initial_patience = parsed_args.initial_patience\n self._patience_update_factor = parsed_args.patience_update_factor\n\n self._aggregate_examples = parsed_args.aggregate_examples\n\n super(TrainingArgs, self).interpret_args(parsed_args)\n\n def __str__(self) -> str:\n str_rep: str = '***Training arguments ***' \\\n '\\n\\tSaving in directory: %r' \\\n '\\n\\tWith experiment name: %r\\n' \\\n '\\n\\tBatch size: %r' \\\n '\\n\\tProportion of training examples used to compute accuracy: %r' \\\n '\\n\\tAggregate examples? %r\\n' \\\n '\\n\\tInitial patience: %r' \\\n '\\n\\tPatience update ratio: %r' \\\n '\\n\\tStopping metric: %r\\n' % (self.get_save_directory(), self.get_experiment_name(),\n self.get_batch_size(),\n self.get_proportion_of_train_for_accuracy(),\n self.aggregate_examples(), self.get_initial_patience(),\n self.get_patience_update_factor(), self.get_stopping_metric())\n str_rep += '\\n\\tPlan prediction LR/L2: %r/%r' \\\n '\\n\\tAction generation LR/L2: %r/%r' \\\n '\\n\\tFinetuning LR/L2: %r/%r' \\\n '\\n\\tMaximum gradient: %r' \\\n '\\n\\tOptimizer: %r\\n' % (self._plan_prediction_learning_rate, self._finetune_l2_coefficient,\n self._action_generation_learning_rate,\n self._action_generation_l2_coefficient,\n self._finetune_learning_rate, self._finetune_l2_coefficient,\n self._max_gradient, self._optimizer_type)\n str_rep += '\\n\\tIntermediate goal auxiliary coefficient (pretraining/finetuning): %r/%r' \\\n '\\n\\tFinal goal auxiliary coefficient (pretraining/finetuning): %r/%r' \\\n '\\n\\tObstacle auxiliary coefficient (pretraining/finetuning): %r/%r' \\\n '\\n\\tAvoid location auxiliary coefficient (pretraining/finetuning): %r/%r' \\\n '\\n\\tTrajectory auxiliary coefficient (pretraining/finetuning): %r/%r' \\\n '\\n\\tImplicit action auxiliary coefficient: %r' % (\n self._pretrain_auxiliary_coefficient_intermediate_goal_probabilities,\n self._finetune_auxiliary_coefficient_intermediate_goal_probabilities,\n self._pretrain_auxiliary_coefficient_final_goal_probabilities,\n self._finetune_auxiliary_coefficient_final_goal_probabilities,\n self._pretrain_auxiliary_coefficient_obstacle_probabilities,\n self._finetune_auxiliary_coefficient_obstacle_probabilities,\n self._pretrain_auxiliary_coefficient_avoid_probabilities,\n self._finetune_auxiliary_coefficient_avoid_probabilities,\n self._pretrain_auxiliary_coefficient_trajectory_distribution,\n self._pretrain_auxiliary_coefficient_trajectory_distribution,\n self._finetune_auxiliary_coefficient_implicit_actions)\n\n return str_rep\n\n def __eq__(self, other) -> bool:\n return True\n","sub_path":"agent/config/training_args.py","file_name":"training_args.py","file_ext":"py","file_size_in_byte":22835,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"653984383","text":"''' Parent loaders to handle mapping and bulk loading. '''\nimport gzip\nimport json\nimport requests\nimport re\nfrom elastic.search import Search, ElasticSettings, Bulk\nimport logging\nfrom elastic.management.loaders.mapping import MappingProperties\nfrom elastic.management.loaders.analysis import Analyzer\nfrom elastic.management.loaders.exceptions import LoaderError\n\n# Get an instance of a logger\nlogger = logging.getLogger(__name__)\n\n\nclass Loader:\n ''' Base loader class. Defines methods for loading the mapping for an\n index and bulk loading data. '''\n\n KEYWORD_ANALYZER = Analyzer(\"full_name\", tokenizer=\"keyword\",\n token_filters=[\"standard\", \"lowercase\"]).analyzer\n\n def mapping(self, mapping, idx_type, meta=None, analyzer=None, **options):\n ''' Put the mapping (L{MappingProperties}) to the Elastic server. '''\n if not isinstance(mapping, MappingProperties):\n raise LoaderError(\"not a MappingProperties\")\n\n idx_name = self.get_index_name(**options)\n number_of_shards = self.get_number_of_shards(**options)\n url = ElasticSettings.url() + '/' + idx_name\n resp = requests.get(url)\n if resp.status_code == 200:\n logger.warn('WARNING: '+idx_name + ' index already exists!')\n else:\n # create index\n idx_settings = {\"settings\": {\"number_of_shards\": number_of_shards}}\n if analyzer is not None:\n idx_settings['settings'].update(analyzer)\n\n resp = requests.put(url, data=json.dumps(idx_settings))\n\n mapping_json = mapping.mapping_properties\n if meta is not None:\n mapping_json[idx_type][\"_meta\"] = meta\n\n # add mapping to index\n url += '/_mapping/' + idx_type\n resp = requests.put(url, data=json.dumps(mapping_json))\n self.mapping_json = mapping_json\n\n if(resp.status_code != 200):\n logger.warn('WARNING: '+idx_name+' mapping status: '+str(resp.status_code)+' '+str(resp.content))\n return False\n return True\n\n def bulk_load(self, idx_name, idx_type, json_data):\n ''' Bulk load documents. '''\n Bulk.load(idx_name, idx_type, json_data)\n\n def get_index_name(self, **options):\n ''' Get indexName option. '''\n if options['indexName']:\n return options['indexName'].lower()\n return self.__class__.__name__\n\n def get_number_of_shards(self, **options):\n ''' Get number of shards option. '''\n if options['shards']:\n return int(options['shards'])\n return 5\n\n def open_file_to_load(self, file_name, **options):\n ''' Open the given file. '''\n if options[file_name].endswith('.gz'):\n return gzip.open(options[file_name], 'rb')\n else:\n return open(options[file_name], 'rb')\n\n def is_str(self, column_name, idx_name, idx_type):\n ''' Looks at the mapping to determine if the type is a string. '''\n if not self.mapping_json:\n self.mapping_json = Search(idx=idx_name).get_mapping(idx_type)[idx_name]['mappings']\n try:\n map_type = self.mapping_json[idx_type][\"properties\"][column_name][\"type\"]\n except KeyError:\n return False\n if map_type == 'string':\n return True\n return False\n\n def get_index_type(self, default_type, **options):\n if options['indexType']:\n return options['indexType'].lower()\n return default_type\n\n\nclass DelimeterLoader(Loader):\n ''' Loader for files with delimited columns (comma, tab I{etc}). '''\n\n def load(self, column_names, file_handle, idx_name, idx_type='tab', delim='\\t',\n is_GFF=False, is_GTF=False, chunk=5000):\n ''' Index tab data '''\n json_data = ''\n line_num = 0\n auto_num = 1\n\n try:\n for line in file_handle:\n line = line.decode(\"utf-8\")\n if(line.startswith(\"#\")):\n continue\n parts = re.split(delim, line)\n if len(parts) != len(column_names):\n logger.warn(\"WARNING: unexpected number of columns: [\"+str(line_num+1)+'] '+line)\n continue\n\n idx_id = str(auto_num)\n json_data += '{\"index\": {\"_id\": \"%s\"}}\\n' % idx_id\n doc_data = self.parse_line(parts, column_names, idx_name, idx_type, is_GFF, is_GTF)\n json_data += json.dumps(doc_data) + '\\n'\n\n line_num += 1\n auto_num += 1\n if(line_num > chunk):\n line_num = 0\n print('.', end=\"\", flush=True)\n self.bulk_load(idx_name, idx_type, json_data)\n json_data = ''\n finally:\n self.bulk_load(idx_name, idx_type, json_data)\n logger.info('No. documents loaded: '+str(auto_num-1))\n\n def parse_line(self, parts, column_names, idx_name, idx_type, is_GFF, is_GTF):\n ''' Parse the parts that make up the line. '''\n doc_data = {}\n for idx, p in enumerate(parts):\n p = p.strip()\n\n if (is_GFF or is_GTF) and idx == len(parts)-1:\n if is_GTF:\n attrs = self._getAttributes(p, key_value_delim=' ')\n else:\n attrs = self._getAttributes(p)\n doc_data[column_names[idx]] = attrs\n continue\n\n if self.is_str(column_names[idx], idx_name, idx_type):\n if \"::\" in p:\n p = p.split('::')\n doc_data[column_names[idx]] = p\n else:\n doc_data[column_names[idx]] = p\n elif p.isdigit():\n doc_data[column_names[idx]] = int(p)\n elif self._isfloat(p):\n doc_data[column_names[idx]] = float(p)\n else:\n doc_data[column_names[idx]] = p\n return doc_data\n\n def _getAttributes(self, attrs, key_value_delim='='):\n ''' Parse the attributes column '''\n parts = re.split(';', attrs)\n attrs_arr = {}\n for p in parts:\n if(p == ''):\n continue\n at = re.split(key_value_delim, p.strip())\n if len(at) == 2:\n attrs_arr[at[0]] = at[1]\n else:\n attrs_arr[at[0]] = \"\"\n return attrs_arr\n\n def _isfloat(self, value):\n try:\n float(value)\n return True\n except ValueError:\n return False\n\n\nclass JSONLoader(Loader):\n ''' Loader for JSON data. '''\n\n def load(self, raw_json_data, idx_name, idx_type='json'):\n ''' Index raw json data '''\n json_data = ''\n line_num = 0\n try:\n for row in raw_json_data:\n row_obj = {\"index\": {}}\n if '_id' in row:\n row_obj['index'].update({\"_id\": row['_id']})\n del row['_id']\n if '_parent' in row:\n row_obj['index'].update({\"parent\": row['_parent']})\n del row['_parent']\n json_data += json.dumps(row_obj) + '\\n'\n json_data += json.dumps(row) + '\\n'\n line_num += 1\n\n if(line_num > 5000):\n line_num = 0\n print('.', end=\"\", flush=True)\n self.bulk_load(idx_name, idx_type, json_data)\n json_data = ''\n finally:\n self.bulk_load(idx_name, idx_type, json_data)\n","sub_path":"elastic/management/loaders/loader.py","file_name":"loader.py","file_ext":"py","file_size_in_byte":7599,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"346854192","text":"import os\nfrom utils.validators import validate_number_decimal\nfrom django.shortcuts import get_object_or_404, render\nfrom django.contrib.auth.decorators import user_passes_test\nfrom django.contrib import messages\n# settings de la app\nfrom django.conf import settings\nfrom django.http import HttpResponseRedirect\nfrom django.apps import apps\n\n# para los usuarios\nfrom utils.permissions import current_date, current_periodo, get_user_permission_operation, get_permissions_user, next_periodo, previous_periodo, show_periodo\nfrom datetime import datetime\n\n# controlador\nfrom controllers.SystemController import SystemController\nimport io\nfrom django.http import FileResponse\nfrom reportes.cobros.rptCobroRecibo import rptCobroRecibo\n\n\nsystem_controller = SystemController()\n\n\n@user_passes_test(lambda user: get_user_permission_operation(user, settings.MOD_LISTA_COBROS, 'lista'), 'without_permission')\ndef lista_cobros_index(request):\n permisos = get_permissions_user(request.user, settings.MOD_LISTA_COBROS)\n\n user_perfil = None\n fecha_actual = None\n lista_recibos = []\n departamento = {'departamento_id': 0}\n\n try:\n user_perfil = apps.get_model('permisos', 'UsersPerfiles').objects.get(user_id=request.user)\n fecha_actual = datetime.now()\n\n if user_perfil.perfil_id.perfil_id == settings.PERFIL_DEPARTAMENTO:\n lista_recibos = system_controller.lista_recibos_id(fecha_actual, user_perfil)\n departamento = apps.get_model('departamentos', 'Departamentos').objects.get(departamento=user_perfil.user_id.username)\n\n except Exception as ex:\n context = {\n 'type': 'warning',\n 'title': 'Lista Recibos!',\n 'description': 'Error al recuperar datos, ' + str(ex),\n 'existe_error': 1\n }\n return render(request, 'partials/_alert_resultado.html', context)\n\n # operaciones\n if 'operation_x' in request.POST.keys():\n operation = request.POST['operation_x']\n if not operation in ['', 'mostrar_recibo']:\n return render(request, 'pages/without_permission.html', {})\n\n if operation == 'mostrar_recibo':\n try:\n\n id = request.POST['id']\n periodo_recibo = ''\n # verificamos que este entre los permitidos\n permitido = 'no'\n for recibo in lista_recibos:\n if int(recibo['cobro_id']) == int(id):\n permitido = 'si'\n periodo_recibo = recibo['periodo']\n break\n\n if permitido == 'si':\n # mostramos recibo\n try:\n buffer = io.BytesIO()\n rptCobroRecibo(buffer, request.user, int(id))\n\n buffer.seek(0)\n return FileResponse(buffer, filename='recibo' + periodo_recibo + '.pdf')\n\n except Exception as ex:\n print('error al imprimir: ', str(ex))\n request.session['internal_error'] = str(ex)\n request.session.modified = True\n return render(request, 'pages/internal_error.html', {'error': str(ex)})\n else:\n context = {\n 'type': 'warning',\n 'title': 'Lista Recibos!',\n 'description': 'No puede imprimir este recibo',\n 'existe_error': 1\n }\n return render(request, 'partials/_alert_resultado.html', context)\n\n except Exception as ex:\n context = {\n 'type': 'warning',\n 'title': 'Lista Recibos!',\n 'description': 'Error al recuperar datos ' + str(ex),\n 'existe_error': 1\n }\n return render(request, 'partials/_alert_resultado.html', context)\n\n # verificamos mensajes\n if 'nuevo_mensaje' in request.session.keys():\n messages.add_message(request, messages.SUCCESS, request.session['nuevo_mensaje'])\n del request.session['nuevo_mensaje']\n request.session.modified = True\n\n # perfil de usuario\n print('asdfasd')\n context = {\n 'permisos': permisos,\n 'url_main': '',\n 'js_file': 'lista_cobros',\n 'autenticado': 'si',\n\n 'activo': settings.STATUS_ACTIVO,\n 'cobrado': settings.STATUS_COBRADO,\n 'lista_recibos': lista_recibos,\n 'departamento': departamento,\n\n 'user_perfil': user_perfil,\n\n 'module_x': settings.MOD_LISTA_COBROS,\n 'module_x2': '',\n 'module_x3': '',\n\n 'operation_x': '',\n 'operation_x2': '',\n 'operation_x3': '',\n\n 'id': '',\n 'id2': '',\n 'id3': '',\n }\n return render(request, 'calendario/lista_cobros.html', context)\n","sub_path":"src/calendario/lista_cobros.py","file_name":"lista_cobros.py","file_ext":"py","file_size_in_byte":4928,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"171137752","text":"# The football.csv file contains the results from the English Premier League. \n# The columns labeled ‘Goals’ and ‘Goals Allowed’ contain the total number of \n# goals scored for and against each team in that season (so Arsenal scored 79 goals \n# against opponents, and had 36 goals scored against them). Write a program to read the file, \n# then print the name of the team with the smallest difference in ‘for’ and ‘against’ goals.\n\nfrom csv import *\n\nwith open('football.csv') as f:\n csv_reader = reader(f, delimiter=',')\n next(csv_reader, None)\n\n min_diff = float('inf')\n min_team = ''\n\n for row in csv_reader:\n goals_for = int(row[5])\n goals_against = int(row[6])\n diff = abs(goals_for - goals_against)\n if diff < min_diff:\n min_team = row[0]\n min_diff = diff\n\n print(min_team, min_diff)\n","sub_path":"python/q8_parsing.py","file_name":"q8_parsing.py","file_ext":"py","file_size_in_byte":874,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"419107714","text":"import dash\nimport dash_bootstrap_components as dbc\nimport dash_core_components as dcc\nimport dash_html_components as html\nfrom dash.dependencies import Input, Output, State\nfrom dash_table import DataTable\nimport pandas as pd\nimport numpy as np\nimport plotly.express as px\nfrom sklearn.manifold import TSNE\n\n\ndef Header(name, app):\n title = html.H1(name, style={\"margin-top\": 5})\n logo = html.Img(\n src=app.get_asset_url(\"dash-logo.png\"), style={\"float\": \"right\", \"height\": 60}\n )\n link = html.A(logo, href=\"https://plotly.com/dash/\")\n\n return dbc.Row([dbc.Col(title, md=8), dbc.Col(link, md=4)])\n\n\nused = pd.read_csv(\"vehicles_preprocessed.csv\")\nmanufacturers = used.manufacturer.unique()\ncar_types = used.type.unique()\n\ntable_cols = [\"Features\", \"Selected Values\"]\n\n\napp = dash.Dash(external_stylesheets=[dbc.themes.BOOTSTRAP])\nserver = app.server\n\ncontrols = [\n dbc.FormGroup(\n [\n dbc.Label(\"Manufacturer\"),\n dbc.Select(\n id=\"manufacturer\",\n options=[{\"label\": x, \"value\": x} for x in manufacturers],\n value=manufacturers[0],\n ),\n ]\n ),\n dbc.FormGroup(\n [\n dbc.Label(\"Car Type\"),\n dbc.Select(\n id=\"car-type\",\n options=[{\"label\": x, \"value\": x} for x in car_types],\n value=car_types[0],\n ),\n ]\n ),\n dbc.FormGroup(\n [\n dbc.Label(\"Color By\"),\n dbc.Select(\n id=\"color\",\n options=[\n {\"label\": x, \"value\": x}\n for x in [\n \"state\",\n \"paint_color\",\n \"transmission\",\n \"model\",\n \"condition\",\n ]\n ],\n value=\"model\",\n ),\n ]\n )\n]\n\ndisplay_table = html.Div(\n [\n DataTable(\n id=\"table\",\n columns=[{\"name\": i, \"id\": i} for i in table_cols],\n style_cell={\n \"overflow\": \"hidden\",\n \"textOverflow\": \"ellipsis\",\n \"maxWidth\": 0,\n }\n ),\n dbc.Alert(\"Click on point to learn more about a car\", dismissable=True),\n ]\n)\n\napp.layout = dbc.Container(\n [\n dcc.Store(id=\"dataframe-store\"),\n Header(\"Car Features Explorer with t-SNE\", app),\n html.Hr(),\n dbc.Row(\n [\n dbc.Col(\n [\n dbc.Spinner(dcc.Graph(id=\"projection\", style={\"height\": '500px'}), spinner_style={'margin': '225px auto'}),\n dbc.Row([dbc.Col(x) for x in controls], form=True),\n dbc.Alert(\"Click on point to learn more about a car\", dismissable=True), \n ], \n md=7\n ),\n dbc.Col(\n [\n DataTable(\n id=\"table\",\n columns=[{\"name\": i, \"id\": i} for i in table_cols],\n style_cell={\n \"overflow\": \"hidden\",\n \"textOverflow\": \"ellipsis\",\n \"maxWidth\": 0,\n }\n ),\n ],\n md=5\n ),\n ]\n ),\n ],\n fluid=True,\n)\n\n\n@app.callback(\n [Output(\"projection\", \"figure\"), Output(\"dataframe-store\", \"data\")],\n [\n Input(\"manufacturer\", \"value\"),\n Input(\"car-type\", \"value\"),\n Input(\"color\", \"value\"),\n ],\n)\ndef query_and_project(manufacturer, car_type, color):\n queried = used.query(f'manufacturer == \"{manufacturer}\"').query(\n f'type == \"{car_type}\"'\n )\n\n if queried.shape[0] < 2:\n return px.scatter(title=\"Not enough datapoints\"), queried.to_json()\n\n if queried.shape[0] > 500:\n queried = queried.sample(n=500, random_state=2020)\n\n vecs = pd.get_dummies(\n queried.drop(columns=[\"id\", \"vin\", \"url\", \"region_url\", \"image_url\"])\n )\n\n reducer = TSNE(n_jobs=-1)\n projs = reducer.fit_transform(vecs)\n\n fig = px.scatter(projs, x=0, y=1, color=queried[color], title=\"t-SNE projections\")\n\n return fig, queried.to_json()\n\n\n@app.callback(\n Output(\"table\", \"data\"),\n [Input(\"projection\", \"clickData\")],\n [State(\"dataframe-store\", \"data\")],\n)\ndef update_table(click_data, df_json):\n if df_json is None or click_data is None:\n return dash.no_update\n\n df = pd.read_json(df_json)\n ix = click_data[\"points\"][0][\"pointIndex\"]\n selected = df.iloc[ix].reset_index()\n selected.columns = table_cols\n\n recs = selected.to_dict(\"records\")\n print(recs)\n\n return recs\n\n\nif __name__ == \"__main__\":\n app.run_server(debug=True)\n","sub_path":"apps/car-projections/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":4906,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"113352882","text":"#!/usr/bin/env python\n#_*_ coding:utf-8 _*_\n# Author: jiachen\n\nimport sys\nimport os\nimport json\nimport socket\n\nclass Ftp_client(object):\n '''ftp客户端类'''\n\n def __init__(self, ip, port):\n '''\n :param ip: ftp服务器ip\n :param port: ftp服务器port\n '''\n self.ip = ip\n self.port = port\n\n def create_connect(self): #创建连接方法\n '''\n :return:\n '''\n self.client = socket.socket() #声明socket类型,同时生成socket连接对象\n self.client.connect((self.ip, self.port))\n\n def check(self): #查询文件方法\n '''\n :return:\n '''\n file_num = int(self.client.recv(1024).decode()) #接收目录下文件或文件夹个数\n self.client.sendall(\"200\".encode(\"utf-8\")) #回复确认状态码\n for i in range(file_num): #循环接收文件或文件夹名称\n print(\"\\033[32;1m%s\\033[0m\" % self.client.recv(1024).decode())\n\n def client_upload(self): #上传文件方法\n '''\n :return:\n '''\n file_path = input(\"请输入要上传文件的绝对路径>>>\").strip()\n file_info = {}\n if os.path.isfile(file_path): #判断文件是否存在\n file_name = os.path.basename(file_path) #文件名\n file_size = os.path.getsize(file_path) #文件大小\n file_info[\"name\"] = file_name\n file_info[\"size\"] = file_size #生成文件信息字典{\"name\": file_name, \"size\": file_size}\n self.client.sendall(json.dumps(file_info).encode(\"utf-8\")) #发送文件信息字典\n file_info_res = self.client.recv(1024).decode() #等待接收文件信息返回值\n if file_info_res == \"200\": #收到文件信息字典\n with open(file_path, \"rb\") as f:\n self.client.sendall(f.read()) #发送文件\n upload_res = self.client.recv(1024).decode()\n if upload_res == \"200\":\n print(\"\\033[32;1m上传成功\\033[0m\")\n else:\n self.client.sendall(json.dumps(file_info).encode(\"utf-8\")) #发送无此文件状态码\n print(\"\\033[31;1m上传的文件:%s 不存在\\033[0m\" % file_path)\n\n def client_download(self): #下载文件方法\n '''\n :return:\n '''\n file_path = input(\"请输入文件保存目录的绝对路径>>>\").strip()\n if os.path.isdir(file_path): #判断路径是否存在\n self.client.sendall(\"200\".encode(\"utf-8\")) #发送路径存在状态码\n file_name = input(\"请输入要下载的文件名>>>\").strip()\n self.client.sendall(file_name.encode(\"utf-8\")) #发送要下载的文件名\n file_res = self.client.recv(1024).decode() #接收文件是否存在状态码\n if file_res == \"200\": #要下载的文件存在\n file_info = json.loads(self.client.recv(1024).decode()) #等待接收文件信息字典\n if file_info: #如果接收到文件信息字典\n self.client.sendall(\"200\".encode(\"utf-8\")) #返回接收到的状态码\n with open(os.path.join(file_path, file_name), \"wb\") as f:\n while True:\n if os.path.getsize(os.path.join(file_path, file_name)) == file_info[\"size\"]: #对比下载文件和文件实际大小\n break\n f.write(self.client.recv(1024))\n f.flush()\n self.client.sendall(\"200\".encode(\"utf-8\")) #发送下载状态码\n print(\"\\033[32;1m下载成功\\033[0m\")\n else:\n print(\"\\033[31;1m下载的文件不存在\\033[0m\")\n else:\n self.client.sendall(\"404\".encode(\"utf-8\")) #发送路径不存在状态码\n print(\"\\033[32;1m下载路径不存在\\033[0m\")\n\n def run(self): #交互方法\n '''\n :return:\n '''\n self.create_connect() #创建连接\n while True:\n username = input(\"请输入用户名>>>\").strip()\n password = input(\"请输入密码>>>\").strip()\n user_pass_dic = {\"username\": username, \"password\": password} #生成用户名、密码字典{\"username\": username,\"password\": password}\n self.client.sendall(json.dumps(user_pass_dic).encode(\"utf-8\")) #发送用户名、密码字典\n res = self.client.recv(1024).decode() #接收服务器返回\n if res == \"200\": #接收到200,发送用户名、密码字典成功\n auth_res = self.client.recv(1024).decode() #等待接收服务器用户名、密码验证结果\n if auth_res:\n self.client.sendall(\"200\".encode(\"utf-8\")) #发送已接收到认证结果\n auth_res = int(auth_res)\n if auth_res == 0: #用户认证通过\n print(\"\\033[32;1m*****认证通过*****\\033[0m\")\n while True:\n menu = self.client.recv(1024).decode() #等待接收菜单\n print(menu)\n user_choice = input(\"请选择要执行的选项>>>\").strip()\n self.client.sendall(user_choice.encode(\"utf-8\")) #发送要执行的选项\n user_choice_res = self.client.recv(1024).decode()#接收服务端回应\n if user_choice_res == \"200\":\n if user_choice == \"1\": #执行上传文件\n self.client_upload()\n elif user_choice == \"2\": #执行下载文件\n self.client_download()\n elif user_choice == \"3\": #执行查看文件\n self.check()\n elif user_choice == \"4\": #执行退出\n sys.exit()\n else:\n print(\"\\033[31;1m输入错误\\033[0m\")\n elif auth_res == 1: #用户认证不通过\n print(\"\\033[31;1m认证失败,用户名错误\\033[0m\")\n elif auth_res == 2: #用户认证不通过\n print(\"\\033[31;1m认证失败,密码错误\\033[0m\")","sub_path":"ftp_client/modules/socket_client.py","file_name":"socket_client.py","file_ext":"py","file_size_in_byte":7731,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"39040134","text":"import logging\nimport unittest\nfrom typing import Any, Callable, Optional\n\nfrom rmf_dispenser_msgs.msg import DispenserState\nfrom rmf_door_msgs.msg import DoorMode\nfrom rmf_fleet_msgs.msg import RobotMode\nfrom rmf_ingestor_msgs.msg import IngestorState\nfrom rmf_lift_msgs.msg import LiftState\nfrom rx import Observable\nfrom rx.scheduler.historicalscheduler import HistoricalScheduler\nfrom tortoise import Tortoise\n\nfrom api_server.models import (\n DispenserHealth,\n DoorHealth,\n HealthStatus,\n IngestorHealth,\n LiftHealth,\n RobotHealth,\n)\nfrom api_server.test import init_db, test_data\n\nfrom .events import RmfEvents\nfrom .health_watchdog import HealthWatchdog\n\n\nclass BaseFixture(unittest.IsolatedAsyncioTestCase):\n async def asyncSetUp(self):\n await init_db()\n\n self.scheduler = HistoricalScheduler()\n self.rmf = RmfEvents()\n self.logger = logging.Logger(\"test\")\n self.logger.setLevel(\"CRITICAL\")\n self.health_watchdog = HealthWatchdog(\n self.rmf, scheduler=self.scheduler, logger=self.logger\n )\n\n async def asyncTearDown(self):\n await Tortoise().close_connections()\n\n\nasync def check_heartbeat(\n test: BaseFixture,\n health_obs: Observable,\n source: Observable,\n factory: Callable[[str], Any],\n):\n \"\"\"\n :param health_obs: Observable[BasicHealthModel], the observable of the heartbeat events\n :param source: Observable[SourceType], the observable that should trigger heartbeat events\n :param factory: Callable[[str], SourceType], a factory function that returns an object of\n the source observable sequence type\n \"\"\"\n health = None\n\n def assign(v):\n nonlocal health\n health = v\n\n health_obs.subscribe(assign)\n\n source.on_next(factory(\"test_id\"))\n test.assertEqual(health.health_status, HealthStatus.HEALTHY)\n test.assertEqual(health.id_, \"test_id\")\n\n # it should not be dead yet\n test.scheduler.advance_by(HealthWatchdog.LIVELINESS / 2)\n test.assertEqual(health.health_status, HealthStatus.HEALTHY)\n test.assertEqual(health.id_, \"test_id\")\n\n # # it should be dead now because the time between states has reached the threshold\n test.scheduler.advance_by(HealthWatchdog.LIVELINESS / 2)\n test.assertEqual(health.health_status, HealthStatus.DEAD)\n test.assertEqual(health.id_, \"test_id\")\n\n # # it should become alive again when a new state is emitted\n source.on_next(factory(\"test_id\"))\n test.assertEqual(health.health_status, HealthStatus.HEALTHY)\n test.assertEqual(health.id_, \"test_id\")\n\n\nclass TestHealthWatchdog_DoorHealth(BaseFixture):\n async def test_heartbeat(self):\n await self.health_watchdog.start()\n await check_heartbeat(\n self, self.rmf.door_health, self.rmf.door_states, test_data.make_door_state\n )\n\n async def test_door_mode(self):\n test_cases = [\n (DoorMode.MODE_CLOSED, HealthStatus.HEALTHY),\n (DoorMode.MODE_MOVING, HealthStatus.HEALTHY),\n (DoorMode.MODE_OPEN, HealthStatus.HEALTHY),\n (DoorMode.MODE_OFFLINE, HealthStatus.UNHEALTHY),\n (DoorMode.MODE_UNKNOWN, HealthStatus.UNHEALTHY),\n (128, HealthStatus.UNHEALTHY),\n ]\n for test in test_cases:\n door_state = test_data.make_door_state(\"test_door\")\n door_state.current_mode.value = test[0]\n health = HealthWatchdog.door_mode_to_health(door_state)\n self.assertEqual(health.health_status, test[1])\n\n async def test_heartbeat_with_no_state(self):\n building_map = test_data.make_building_map()\n building_map.levels[0].doors = [test_data.make_door(\"test_door\")]\n await building_map.save()\n await self.health_watchdog.start()\n\n health: Optional[DoorHealth] = None\n\n def assign(v):\n nonlocal health\n health = v\n\n self.rmf.door_health.subscribe(assign)\n\n self.scheduler.advance_by(self.health_watchdog.LIVELINESS)\n self.assertIsNotNone(health)\n self.assertEqual(health.id_, \"test_door\")\n self.assertEqual(health.health_status, HealthStatus.DEAD)\n\n\nclass TestHealthWatchdog_LiftHealth(BaseFixture):\n async def test_heartbeat(self):\n await self.health_watchdog.start()\n self.scheduler.advance_by(1)\n await check_heartbeat(\n self, self.rmf.lift_health, self.rmf.lift_states, test_data.make_lift_state\n )\n\n async def test_heartbeat_with_no_state(self):\n \"\"\"\n Tests that a lift that never sends any state can be caught by the heartbeat watchdog.\n This also tests that the list of known lifts is automatically updated when a new\n building map comes in.\n \"\"\"\n building_map = test_data.make_building_map()\n building_map.lifts = [test_data.make_lift(\"test_lift\")]\n await building_map.save()\n await self.health_watchdog.start()\n\n health: Optional[LiftHealth] = None\n\n def assign(v):\n nonlocal health\n health = v\n\n self.rmf.lift_health.subscribe(assign)\n\n self.scheduler.advance_by(self.health_watchdog.LIVELINESS)\n self.assertIsNotNone(health)\n self.assertEqual(health.id_, \"test_lift\")\n self.assertEqual(health.health_status, HealthStatus.DEAD)\n\n async def test_lift_mode(self):\n test_cases = [\n (LiftState.MODE_HUMAN, HealthStatus.HEALTHY),\n (LiftState.MODE_AGV, HealthStatus.HEALTHY),\n (LiftState.MODE_UNKNOWN, HealthStatus.UNHEALTHY),\n (LiftState.MODE_FIRE, HealthStatus.UNHEALTHY),\n (LiftState.MODE_EMERGENCY, HealthStatus.UNHEALTHY),\n (LiftState.MODE_OFFLINE, HealthStatus.UNHEALTHY),\n (128, HealthStatus.UNHEALTHY),\n ]\n for test in test_cases:\n lift_state = test_data.make_lift_state(\"test_lift\")\n lift_state.current_mode = test[0]\n health = HealthWatchdog.lift_mode_to_health(lift_state)\n self.assertEqual(health.health_status, test[1])\n\n\nclass TestHealthWatchdog_DispenserHealth(BaseFixture):\n async def test_heartbeat(self):\n await self.health_watchdog.start()\n await check_heartbeat(\n self,\n self.rmf.dispenser_health,\n self.rmf.dispenser_states,\n test_data.make_dispenser_state,\n )\n\n async def test_heartbeat_with_no_state(self):\n await test_data.make_dispenser_state(\"test_dispenser\").save()\n await self.health_watchdog.start()\n\n health: Optional[DispenserHealth] = None\n\n def assign(v):\n nonlocal health\n health = v\n\n self.rmf.dispenser_health.subscribe(assign)\n\n self.scheduler.advance_by(self.health_watchdog.LIVELINESS)\n self.assertIsNotNone(health)\n self.assertEqual(health.id_, \"test_dispenser\")\n self.assertEqual(health.health_status, HealthStatus.DEAD)\n\n async def test_dispenser_mode_to_health(self):\n test_cases = [\n (DispenserState.IDLE, HealthStatus.HEALTHY),\n (DispenserState.BUSY, HealthStatus.HEALTHY),\n (DispenserState.OFFLINE, HealthStatus.UNHEALTHY),\n (128, HealthStatus.UNHEALTHY),\n ]\n for test in test_cases:\n dispenser_state = test_data.make_dispenser_state(\"test_dispenser\")\n dispenser_state.mode = test[0]\n health = HealthWatchdog.dispenser_mode_to_health(dispenser_state)\n self.assertEqual(health.health_status, test[1])\n\n\nclass TestHealthWatchdog_IngestorHealth(BaseFixture):\n async def test_heartbeat(self):\n await self.health_watchdog.start()\n await check_heartbeat(\n self,\n self.rmf.ingestor_health,\n self.rmf.ingestor_states,\n test_data.make_ingestor_state,\n )\n\n async def test_heartbeat_with_no_state(self):\n await test_data.make_ingestor_state(\"test_ingestor\").save()\n await self.health_watchdog.start()\n\n health: Optional[IngestorHealth] = None\n\n def assign(v):\n nonlocal health\n health = v\n\n self.rmf.ingestor_health.subscribe(assign)\n\n self.scheduler.advance_by(self.health_watchdog.LIVELINESS)\n self.assertIsNotNone(health)\n self.assertEqual(health.id_, \"test_ingestor\")\n self.assertEqual(health.health_status, HealthStatus.DEAD)\n\n async def test_ingestor_mode_to_health(self):\n test_cases = [\n (IngestorState.IDLE, HealthStatus.HEALTHY),\n (IngestorState.BUSY, HealthStatus.HEALTHY),\n (IngestorState.OFFLINE, HealthStatus.UNHEALTHY),\n (128, HealthStatus.UNHEALTHY),\n ]\n for test in test_cases:\n ingestor_state = test_data.make_ingestor_state(\"test_ingestor\")\n ingestor_state.mode = test[0]\n health = HealthWatchdog.ingestor_mode_to_health(ingestor_state)\n self.assertEqual(health.health_status, test[1])\n\n\nclass TestHealthWatchdog_RobotHealth(BaseFixture):\n async def test_heartbeat(self):\n await self.health_watchdog.start()\n\n health = None\n\n def assign(v):\n nonlocal health\n health = v\n\n self.rmf.robot_health.subscribe(assign)\n\n def factory():\n state = test_data.make_fleet_state(\"test_fleet\")\n state.robots = [test_data.make_robot_state(\"test_robot\")]\n return state\n\n robot_id = \"test_fleet/test_robot\"\n self.rmf.fleet_states.on_next(factory())\n self.assertEqual(health.health_status, HealthStatus.HEALTHY)\n self.assertEqual(health.id_, robot_id)\n\n # it should not be dead yet\n self.scheduler.advance_by(HealthWatchdog.LIVELINESS / 2)\n self.assertEqual(health.health_status, HealthStatus.HEALTHY)\n self.assertEqual(health.id_, robot_id)\n\n # # it should be dead now because the time between states has reached the threshold\n self.scheduler.advance_by(HealthWatchdog.LIVELINESS / 2)\n self.assertEqual(health.health_status, HealthStatus.DEAD)\n self.assertEqual(health.id_, robot_id)\n\n # # it should become alive again when a new state is emitted\n self.rmf.fleet_states.on_next(factory())\n self.assertEqual(health.health_status, HealthStatus.HEALTHY)\n self.assertEqual(health.id_, robot_id)\n\n async def test_heartbeat_with_no_state(self):\n await test_data.make_fleet_state(\"test_fleet\").save()\n await self.health_watchdog.start()\n\n def factory():\n state = test_data.make_fleet_state(\"test_fleet\")\n state.robots = [test_data.make_robot_state(\"test_robot\")]\n return state\n\n self.rmf.fleet_states.on_next(factory())\n\n health: Optional[RobotHealth] = None\n\n def assign(v):\n nonlocal health\n health = v\n\n self.rmf.robot_health.subscribe(assign)\n\n robot_id = \"test_fleet/test_robot\"\n self.scheduler.advance_by(self.health_watchdog.LIVELINESS)\n self.assertEqual(health.id_, robot_id)\n self.assertEqual(health.health_status, HealthStatus.DEAD)\n\n async def test_robot_mode(self):\n test_cases = [\n (RobotMode.MODE_IDLE, HealthStatus.HEALTHY),\n (RobotMode.MODE_CHARGING, HealthStatus.HEALTHY),\n (RobotMode.MODE_MOVING, HealthStatus.HEALTHY),\n (RobotMode.MODE_PAUSED, HealthStatus.HEALTHY),\n (RobotMode.MODE_WAITING, HealthStatus.HEALTHY),\n (RobotMode.MODE_GOING_HOME, HealthStatus.HEALTHY),\n (RobotMode.MODE_DOCKING, HealthStatus.HEALTHY),\n (RobotMode.MODE_EMERGENCY, HealthStatus.UNHEALTHY),\n (RobotMode.MODE_ADAPTER_ERROR, HealthStatus.UNHEALTHY),\n (128, HealthStatus.UNHEALTHY),\n ]\n for test in test_cases:\n robot_state = test_data.make_robot_state(\"test_robot\")\n robot_state.mode.mode = test[0]\n health = HealthWatchdog.robot_mode_to_health(\n \"test_fleet/test_robot\", robot_state\n )\n self.assertEqual(health.health_status, test[1])\n","sub_path":"packages/api-server/api_server/rmf_io/test_health_watchdog.py","file_name":"test_health_watchdog.py","file_ext":"py","file_size_in_byte":12188,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"38316888","text":"import random\ndef random_walk(n):\n\tx = 0\n\ty = 0\n\tfor i in range(n):\n\t\tstep = random.choice(['N','S','E','W'])\n\t\tif step == 'N':\n\t\t\ty = y + 1\n\t\telif step == 'S':\n\t\t\ty = y - 1\n\t\telif step == 'E':\n\t\t\tx = x + 1\n\t\telse:\n\t\t\tx = x - 1\n\treturn (x,y)\n\nfor i in range(25):\n\twalk = random_walk(10)\n\tprint(walk, \"distance = \", abs(walk[0] + walk[1]))\n\t\n\t\n\ndef random_walk_2(n):\n\tx, y = 0, 0\n\tfor i in range(n):\n\t\t(dx, dy) = random.choice([(0,1), (0,-1), (1,0), (-1,0)])\n\t\tx += dx\n\t\ty += dy\n\treturn (x,y)\n\nfor i in range(25):\n\twalk = random_walk_2(10)\n\tprint(walk, \"distance = \", abs(walk[0] + walk[1]))\n\t\n\n\n\n","sub_path":"20190318_random_walk.py","file_name":"20190318_random_walk.py","file_ext":"py","file_size_in_byte":596,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"259636733","text":"# -*- coding: utf-8 -*-\nfrom model.group_contact import Group_contact\n\n\n\n\n\ndef test_add_contact(app,json_contact):\n contact = json_contact\n old_contacts = app.contact.get_contact_list()\n app.contact.create_contact(contact)\n assert len(old_contacts) + 1 == app.contact.count()\n new_contacts = app.contact.get_contact_list()\n old_contacts.append(contact)\n assert sorted(old_contacts, key=Group_contact.id_or_max) == sorted(new_contacts, key=Group_contact.id_or_max)\n","sub_path":"test/test_add_contact.py","file_name":"test_add_contact.py","file_ext":"py","file_size_in_byte":485,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"437232278","text":"#!/usr/bin/env python\n\nimport errno\nfrom functools import lru_cache\nimport os\nimport stat\n\nimport fuse\nimport ipfsapi\n\nfrom . import unixfs_pb2\n\nTYPE_FILE = unixfs_pb2.Data.File\nTYPE_DIR = unixfs_pb2.Data.Directory\n\n\nclass IPFSMount(fuse.Operations):\n\n def __init__(self,\n root, # root IPFS path\n api_host='127.0.0.1', api_port=5001,\n ls_cache_size=64,\n object_data_cache_size=256, # ~256MB assuming 1MB max block size\n object_links_cache_size=256,\n ):\n api = ipfsapi.connect(api_host, api_port)\n self.root = root\n\n # trick to get lrucache use only one arg\n\n @lru_cache(maxsize=object_data_cache_size)\n def object_data(object_id):\n try:\n data = unixfs_pb2.Data()\n data.ParseFromString(api.object_data(object_id))\n return data\n except ipfsapi.exceptions.Error:\n return None\n\n @lru_cache(maxsize=object_links_cache_size)\n def object_links(object_id):\n try:\n return [\n l['Hash']\n for l in api.object_links(object_id).get('Links', [])\n ]\n except ipfsapi.exceptions.Error:\n return None\n\n @lru_cache(maxsize=ls_cache_size)\n def ls(object_id):\n return {\n entry['Name']: entry\n for entry in api.ls(object_id)['Objects'][0]['Links']\n }\n\n self._ls = ls\n self._object_data = object_data\n self._object_links = object_links\n\n def _path_type(self, path):\n data = self._object_data(path)\n if data is None:\n return None\n else:\n return data.Type\n\n def _path_size(self, path):\n data = self._object_data(path)\n if data is None:\n return None\n else:\n return data.filesize\n\n def _read_into(self, object_hash, offset, buff):\n \"\"\" Read bytes begining at `offset` from given object into\n buffer. Returns end offset of copied data. \"\"\"\n\n assert(offset >= 0)\n\n data = self._object_data(object_hash)\n size = len(buff)\n\n # missing object\n if data is None:\n return offset\n\n # only files and raw type objects contains data\n if data.Type in [unixfs_pb2.Data.Raw, unixfs_pb2.Data.File]:\n end = offset\n\n # copy data contained in this object\n d = data.Data[offset:offset+size]\n n = len(d)\n buff[0:n] = d\n end += n\n\n # copied all requested data?\n if size <= n:\n return end\n\n # descend into child objects\n block_offset = len(data.Data)\n for blocksize, child_hash in zip(\n data.blocksizes,\n self._object_links(object_hash),\n ):\n if offset + size <= block_offset:\n # current block is past requested range\n break\n elif block_offset + blocksize <= offset:\n # current block is before requested range\n pass\n else:\n end = self._read_into(\n child_hash,\n max(0, offset - block_offset),\n buff[end-offset:end-offset+blocksize],\n ) + block_offset\n\n # update offset to next block\n block_offset += blocksize\n\n return end\n\n # every other thing is empty\n return offset\n\n def open(self, path, flags):\n write_flags = (\n os.O_WRONLY |\n os.O_RDWR |\n os.O_APPEND |\n os.O_CREAT |\n os.O_EXCL |\n os.O_TRUNC\n )\n if (flags & write_flags) != 0:\n raise fuse.FuseOSError(errno.EROFS)\n elif self._path_type(self.root + path) not in (TYPE_DIR, TYPE_FILE):\n raise fuse.FuseOSError(errno.ENOENT)\n\n # we dont use file handles so return anthing\n return 0\n\n def read(self, path, size, offset, fh):\n if self._path_type(self.root + path) != TYPE_FILE:\n raise fuse.FuseOSError(errno.EISDIR)\n\n data = bytearray(size)\n n = self._read_into(self.root + path, offset, memoryview(data))\n return bytes(data[:n-offset])\n\n def readdir(self, path, fh):\n if self._path_type(self.root + path) != TYPE_DIR:\n raise fuse.FuseOSError(errno.ENOTDIR)\n\n return ['.', '..'] + list(self._ls(self.root + path).keys())\n\n def getattr(self, path, fh=None):\n if self._path_type(self.root + path) not in (TYPE_DIR, TYPE_FILE):\n raise fuse.FuseOSError(errno.ENOENT)\n\n return {\n 'st_atime': 0,\n 'st_ctime': 0,\n 'st_mtime': 0,\n 'st_gid': 0,\n 'st_uid': 0,\n 'st_mode': {\n TYPE_FILE: stat.S_IFREG,\n TYPE_DIR: stat.S_IFDIR,\n }[self._path_type(self.root + path)] |\n stat.S_IRUSR |\n stat.S_IRGRP |\n stat.S_IROTH,\n 'st_nlink': 0,\n 'st_size': self._path_size(self.root + path),\n }\n\n getxattr = None\n listxattr = None\n","sub_path":"ipfs_api_mount/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":5314,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"128291929","text":"# -*- coding: utf-8 -*-\n# author=Kai Moriguchi @Chichibu 2013.4~2014.3\n# email:a09a215@gmail.com\nfrom ccbplugintools import *\nfrom PyQt4 import QtCore, QtGui\nimport sys\ntry:\n _fromUtf8 = QtCore.QString.fromUtf8\nexcept AttributeError:\n _fromUtf8 = lambda s: s\n\nclass Ui_form(object):\n def setupUi(self, fm):\n fm_w = 700\n fm_h = 400\n margin_w = 20\n margin_h = 20\n obj_h = 25\n lab_x = 20\n lab_w = 110\n box_w = 400\n button_w = 75\n bar_w = 500\n check_w = 200\n box_x = lab_x + lab_w + margin_w\n button_x = box_x + box_w + margin_w\n bar_x = (fm_w-bar_w)/2\n check_x = (fm_w-check_w)/2\n runb_x =(fm_w-button_w)/2\n\n font = QtGui.QFont( 'Meiryo', 11 )\n fm.setObjectName(_fromUtf8(\"fm\"))\n fm.resize(fm_w, fm_h)\n fm.setFocusPolicy(QtCore.Qt.TabFocus)\n fm.setWindowTitle(_fromUtf8(\"ccbTools\"))\n icon = QtGui.QIcon()\n icon.addPixmap(QtGui.QPixmap(_fromUtf8(\":/qgis.png\")), QtGui.QIcon.Normal, QtGui.QIcon.Off)\n fm.setWindowIcon(icon)\n\n y=30\n self.analyzelabel = QtGui.QLabel(fm)\n self.analyzelabel.setGeometry(QtCore.QRect(lab_x,y,lab_w,obj_h))\n self.analyzelabel.setFont(font)\n self.analyzelabel.setToolTip(_fromUtf8(\"\"))\n self.analyzelabel.setObjectName(_fromUtf8(\"analyzelabel\"))\n\n self.analyzebox = QtGui.QComboBox(fm)\n self.analyzebox.setGeometry(QtCore.QRect(box_x, y, box_w, obj_h))\n self.analyzebox.setFont(font)\n self.analyzebox.setObjectName(_fromUtf8(\"analyzebox\"))\n\n y = y + obj_h + margin_h\n self.inputlabel_1 = QtGui.QLabel(fm)\n self.inputlabel_1.setGeometry(QtCore.QRect(lab_x,y,lab_w,obj_h))\n self.inputlabel_1.setFont(font)\n self.inputlabel_1.setToolTip(_fromUtf8(\"\"))\n self.inputlabel_1.setObjectName(_fromUtf8(\"inputlabel_1\"))\n\n self.inputbox_1 = QtGui.QComboBox(fm)\n self.inputbox_1.setGeometry(QtCore.QRect(box_x, y, box_w, obj_h))\n self.inputbox_1.setFont(font)\n self.inputbox_1.setObjectName(_fromUtf8(\"inputbox_1\"))\n\n y = y + obj_h + margin_h\n self.inputlabel_2 = QtGui.QLabel(fm)\n self.inputlabel_2.setGeometry(QtCore.QRect(lab_x,y,lab_w,obj_h))\n self.inputlabel_2.setFont(font)\n self.inputlabel_2.setToolTip(_fromUtf8(\"\"))\n self.inputlabel_2.setObjectName(_fromUtf8(\"inputlabel_2\"))\n\n self.inputbox_2 = QtGui.QComboBox(fm)\n self.inputbox_2.setGeometry(QtCore.QRect(box_x, y, box_w, obj_h))\n self.inputbox_2.setFont(font)\n self.inputbox_2.setObjectName(_fromUtf8(\"inputbox_2\"))\n\n y = y + obj_h + margin_h\n self.outputlabel = QtGui.QLabel(fm)\n self.outputlabel.setGeometry(QtCore.QRect(lab_x,y,lab_w,obj_h))\n self.outputlabel.setFont(font)\n self.outputlabel.setToolTip(_fromUtf8(\"\"))\n self.outputlabel.setObjectName(_fromUtf8(\"outputlabel\"))\n\n self.outputbox = QtGui.QLineEdit(fm)\n self.outputbox.setGeometry(QtCore.QRect(box_x, y, box_w, obj_h))\n self.outputbox.setAlignment(QtCore.Qt.AlignLeading|QtCore.Qt.AlignLeft|QtCore.Qt.AlignVCenter)\n self.outputbox.setObjectName(_fromUtf8(\"outputbox\"))\n\n self.outputbutton = QtGui.QPushButton(fm)\n self.outputbutton.setGeometry(QtCore.QRect(button_x,y,button_w,obj_h))\n self.outputbutton.setFont(font)\n self.outputbutton.setObjectName(_fromUtf8(\"outputbutton\"))\n\n y = y + obj_h + margin_h\n self.paramlabel = QtGui.QLabel(fm)\n self.paramlabel.setGeometry(QtCore.QRect(lab_x,y,lab_w,obj_h))\n self.paramlabel.setFont(font)\n self.paramlabel.setObjectName(_fromUtf8(\"paramlabel\"))\n\n self.parambox = QtGui.QLineEdit(fm)\n self.parambox.setGeometry(QtCore.QRect(box_x, y, box_w, obj_h))\n self.parambox.setAlignment(QtCore.Qt.AlignLeading|QtCore.Qt.AlignLeft|QtCore.Qt.AlignVCenter)\n self.parambox.setObjectName(_fromUtf8(\"parambox\"))\n\n y = y + obj_h + margin_h\n self.addcheck = QtGui.QCheckBox(fm)\n self.addcheck.setGeometry(QtCore.QRect(check_x,y,check_w,obj_h))\n self.addcheck.setFont(font)\n self.addcheck.setChecked(True)\n self.addcheck.setObjectName(_fromUtf8(\"addcheck\"))\n\n y = y + obj_h + margin_h\n self.runbutton = QtGui.QPushButton(fm)\n self.runbutton.setFont(font)\n self.runbutton.setGeometry(QtCore.QRect(runb_x,y,button_w,obj_h))\n self.runbutton.setObjectName(_fromUtf8(\"run\"))\n\n y = y + obj_h + margin_h\n self.progressbar = QtGui.QProgressBar(fm)\n self.progressbar.setGeometry(QtCore.QRect(bar_x,y,bar_w,obj_h))\n self.progressbar.setFont(font)\n self.progressbar.setProperty(_fromUtf8(\"value\"), 0)\n self.progressbar.setObjectName(_fromUtf8(\"progressbar\"))\n\n self.setWindowFlags(QtCore.Qt.WindowFlags(QtCore.Qt.WindowMaximizeButtonHint))\n self.retranslateUi(fm)\n self.setWindowFlags(QtCore.Qt.WindowFlags(QtCore.Qt.WindowMaximizeButtonHint))\n QtCore.QMetaObject.connectSlotsByName(fm)\n\n def retranslateUi(self, fm):\n self.analyzelabel.setText(Qtrans(\"Menu\"))\n self.inputlabel_1.setText(Qtrans(\"Input layer 1\"))\n self.inputlabel_2.setText(Qtrans(\"Input layer 2\"))\n self.outputlabel.setText(Qtrans(\"Output layer\"))\n self.outputbutton.setText(\"...\")\n\n self.paramlabel.setToolTip(Qtrans(\"delimited with ;\"))\n self.paramlabel.setText(Qtrans(\"Parameters\"))\n self.parambox.setText(\"0.999;1\")\n\n self.runbutton.setText(Qtrans(\"Run\"))\n self.addcheck.setText(Qtrans(\"Add results to project\"))\n\nimport resources\n\nif __name__ == \"__main__\":\n app = QtGui.QApplication(sys.argv)\n fm = QtGui.QWidget()\n ui = Ui_form()\n fm.show()\n sys.exit(app.exec_())\n\n","sub_path":"src/form.py","file_name":"form.py","file_ext":"py","file_size_in_byte":5875,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"35322209","text":"class roBufferEntry:\n '''\n +------+--------+----------+-----------+\n | Busy | Issued | Finished | RenameReg |\n +------+--------+----------+-----------+\n\n Branch Pred specific fields (speculative, valid) are not used here\n '''\n def __init__(self):\n self.busy = 0\n self.issued = 0 # = 1 when instruction is pushed to FU from RS\n self.finished = 0\n self.renameReg = -1 # holds dest rrf index, init to an invalid location\n def print(self):\n print(\"Busy: {}\\tIssued: {}\\tFinished: {}\\tRenameReg: {}\".format\\\n (self.busy, self.issued, self.finished, self.renameReg))\n\nclass roBuffer:\n '''\n +-------+------+--------+----------+-----------+\n | Index | Busy | Issued | Finished | RenameReg |\n +-------+------+--------+----------+-----------+\n | 0 | | | | |\n +-------+------+--------+----------+-----------+\n | 1 | | | | |\n +-------+------+--------+----------+-----------+\n | 2 | | | | |\n +-------+------+--------+----------+-----------+\n | 3 | | | | |\n +-------+------+--------+----------+-----------+\n ...\n ...\n ...\n +-------+------+--------+----------+-----------+\n | N-1 | | | | |\n +-------+------+--------+----------+-----------+\n '''\n def __init__(self, numEntries:int):\n self.entries = []\n for _ in range(numEntries):\n self.entries.extend([roBufferEntry()])\n self.head = 0\n self.tail = 0\n self.full = 0\n self.empty = 1\n self.len = numEntries\n\n def updateState(self):\n self.empty = 0\n self.full = 0\n if ((self.tail - self.head)%self.len == self.len - 1):\n self.full = 1\n elif (self.tail == self.head):\n self.empty = 1\n\n def insertEntry(self, rrfTag):\n '''\n This function is called from dispatch()\n call updateState() before calling this function and stall if ROBuffer is full,\n else carry on\n '''\n self.entries[self.tail].busy = 1\n self.entries[self.tail].issued = 0\n self.entries[self.tail].finished = 0\n self.entries[self.tail].renameReg = rrfTag\n tailIdx = self.tail\n self.tail = (self.tail + 1)%self.len\n return tailIdx # save this as InstrIdx in RS\n\n def complete(self):\n self.updateState()\n if self.empty:\n print(\"\\tNo instruction left to complete\")\n return -1\n else:\n if(self.entries[self.head].finished):\n self.entries[self.head].busy = 0\n rrfTag = self.entries[self.head].renameReg\n self.head = (self.head + 1)%self.len\n return rrfTag\n else:\n return -2 # head instr isnt finished\n\n def updateEntry(self, type:str, index):\n self.updateState()\n if self.empty:\n print(\"Reorder Buffer is empty\")\n return\n else:\n if (type == \"issued\"):\n print(\"(issued) index = \", index)\n self.entries[index].issued = 1\n elif (type == \"finished\"):\n print(\"(finished) index = \", index)\n self.entries[index].finished = 1\n return\n","sub_path":"src/reorderBuffer.py","file_name":"reorderBuffer.py","file_ext":"py","file_size_in_byte":3421,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"266341726","text":"#A program that makes a pie plot of the unique occurences value sin an array\n#Author: Jon Ishaque\n\nimport numpy as np \nimport matplotlib.pyplot as plt\n\n#create an array\npossibleCounties =['Cork','Kerry','Waterford','Limerick','Tipperary']\n\n#pick 100 randomly from possible countries with the frequency set in p\n\ncounties = np.random.choice(possibleCounties, p=[0.1, 0.3, 0.2, 0.12, 0.28], size=(100))\n\n#get the number of occurences of each county, returns a tuple of the uniqque values and how many times they appear\n#research this\nunique, counts = np.unique(counties,return_counts=True)\n\n#add to a bar plot\n\nplt.bar(unique,counts)\nplt.show()","sub_path":"Week 08 - plotting/countiesBar.py","file_name":"countiesBar.py","file_ext":"py","file_size_in_byte":642,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"9701408","text":"#! /usr/bin/env python3\nimport sys\nimport clize\n\nfrom ftools.SubCommand import SubCommandNotExists, SubCommand\n\n\nclass Main:\n def __init__(self):\n pass\n\n def run(self):\n if len(sys.argv) <= 1 or sys.argv[1] == \"--help\":\n self.help()\n else:\n script, cmd, *args = sys.argv\n self.dispatch(script, cmd, args)\n\n @staticmethod\n def dispatch(script: str, cmd: str, args: list):\n cmd = SubCommand(cmd)\n try:\n args = [script + \" \" + cmd.name] + args\n if len(cmd.clize_args) == 1:\n clize.run(*cmd.clize_args, args=args)\n else:\n clize.run(cmd.clize_args, args=args, description=cmd.doc_)\n except KeyboardInterrupt:\n print(\"\\nCtrl-c按下\")\n except SubCommandNotExists as e:\n print(e.message)\n\n @staticmethod\n def help():\n print(\"帮助:\")\n cmds = SubCommand.all_sub_commands()\n cmds.sort(key=lambda cmd: cmd.name)\n max_len = max((len(c.name) for c in cmds))\n for c in cmds:\n print('%s%s %s' %\n (c.name, ' ' * (max_len - len(c.name)), c.doc_))\n\n\nif __name__ == '__main__':\n Main().run()\n","sub_path":"ftools/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1229,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"351447913","text":"# -*- coding: utf-8; -*-\n#\n# Licensed to Crate.io Inc. (Crate) under one or more contributor license\n# agreements. See the NOTICE file distributed with this work for additional\n# information regarding copyright ownership. Crate licenses this file to\n# you under the Apache License, Version 2.0 (the \"License\"); you may not\n# use this file except in compliance with the License. You may obtain a\n# 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#\n# However, to use any modules in this file marked as \"Enterprise Features\",\n# Crate must have given you permission to enable and use such Enterprise\n# Features and you must have a valid Enterprise or Subscription Agreement\n# with Crate. If you enable or use the Enterprise Features, you represent\n# and warrant that you have a valid Enterprise or Subscription Agreement\n# with Crate. Your use of the Enterprise Features if governed by the terms\n# and conditions of your Enterprise or Subscription Agreement with Crate.\n\nimport os\nimport unittest\nfrom testutils.ports import bind_port\nfrom testutils.paths import crate_path\nfrom cr8.run_crate import CrateNode\nfrom test_jmx import JmxClient\n\nJMX_PORT = bind_port()\nJMX_OPTS = '''\n -Dcom.sun.management.jmxremote\n -Dcom.sun.management.jmxremote.port={}\n -Dcom.sun.management.jmxremote.ssl=false\n -Dcom.sun.management.jmxremote.authenticate=false\n'''\n\n\nenv = os.environ.copy()\nenv['CRATE_JAVA_OPTS'] = JMX_OPTS.format(JMX_PORT)\ncrate_layer = CrateNode(\n crate_dir=crate_path(),\n version=(4, 0, 0),\n settings={\n 'transport.tcp.port': 0,\n 'node.name': 'crate-ce',\n },\n env=env\n)\n\n\nclass CeHasNoEnterpriseModulesITest(unittest.TestCase):\n\n @classmethod\n def setUpClass(cls):\n crate_layer.start()\n\n @classmethod\n def tearDownClass(cls):\n crate_layer.stop()\n\n def test_enterprise_jmx_not_available(self):\n jmx_client = JmxClient(JMX_PORT)\n stdout, stderr = jmx_client.query_jmx(\n 'io.crate.monitoring:type=QueryStats',\n 'SelectQueryTotalCount'\n )\n\n self.assertEqual(\n stderr,\n 'MBean not found: io.crate.monitoring:type=QueryStats\\n')\n self.assertEqual(stdout, '')\n","sub_path":"blackbox/test_ce_no_enterprise.py","file_name":"test_ce_no_enterprise.py","file_ext":"py","file_size_in_byte":2556,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"504773989","text":"#!/usr/bin/env python\n\ndef update_pos(pos, move):\n if move == '>':\n pos = (pos[0], pos[1] + 1)\n elif move == '^':\n pos = (pos[0] + 1, pos[1])\n elif move == '<':\n pos = (pos[0], pos[1] - 1)\n elif move == 'v':\n pos = (pos[0] - 1, pos[1])\n else:\n raise Exception\n return pos\n\n\ndef santa(moves):\n visited = set()\n pos = (0, 0)\n visited.add(pos)\n for move in moves:\n # Parse input into coordinates\n pos = update_pos(pos, move)\n visited.add(pos)\n return len(visited)\n\n\ndef santa_robot(moves):\n visited = set()\n santa = (0, 0)\n robot = (0, 0)\n visited.add(santa)\n for i, move in enumerate(moves):\n # Parse input into coordinates\n if i % 2 == 0:\n santa = update_pos(santa, move)\n visited.add(santa)\n else:\n robot = update_pos(robot, move)\n visited.add(robot)\n return len(visited)\n\n\nwith open('../input/day3.txt', mode='r') as f:\n print(santa_robot(f.read()))\n","sub_path":"src/day3.py","file_name":"day3.py","file_ext":"py","file_size_in_byte":1026,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"403095202","text":"import discord\nfrom discord.ext import commands\nimport random\nfrom datetime import datetime\nimport config \n\nintents = discord.Intents.default()\nintents.members = True\ndescription = '''디스코드봇을 만들기 위한 샘플 코드'''\ntitle = '''\n //\\\\\n /| (' )/\\\\\\\\\n<---<< = | >()HJH \\\\\\\\\n \\\\| \\\\ _\\\\_\n //____|J\n'''\ndomain = 'https://cdn.discordapp.com/attachments'\nimage_urls = ['/883568550915223555/885067603675074580/788595ccdf65d51f.jpg',\n '/883568550915223555/884745201522999296/a807d1c33efdbc16.png',\n '/883568550915223555/883575289383378994/7946ea8b23c12cb5.jpg',\n '/883568550915223555/883568619328516167/16f2087c12d96b85.jpg'\n ]\n# 명령은 /(슬래시)로 시작함. \nbot = commands.Bot(command_prefix='/', description=description, intents=intents) \n\n@bot.event\nasync def on_ready():\n print(title)\n print(f\"{bot.user.name}님이 로그인 하셨습니다. --- \\\n Id: {bot.user.id} 로그인시간: {datetime.now()}\")\n print('-'*80)\n\n# 사용법 : /add 10 20 =>두 수의 합을 말해줌\n@bot.command(aliases=['더하기', '합'])\nasync def add(ctx, left: int, right: int):\n c = discord.Color.from_rgb(0, 0, 255)\n val = left + right\n embed=discord.Embed(\n title=\"두 수의 합\",\n description=f\"{left} + {right} = {val}\",\n url= config.cover_url,\n color=c)\n embed.set_image(url = config.cover_url)\n # embed.set_thumbnail(url = config.cover_url)\n await ctx.send(embed = embed)\n\n# 사용법 : /roll 3d10 => 10까지 수 중 3번 주사위 굴려! \n@bot.command(aliases=['주사위', '굴려'], description=\"주사위 굴리기\")\nasync def roll(ctx, dice: str):\n # 명령이 형식에 맞는 지 확인\n try:\n rolls, limit = map(int, dice.split('d'))\n except Exception:\n await ctx.send('잘못된 명령')\n return\n\n dices = []\n for r in range(rolls):\n dices.append( str(random.randint(1, limit) ))\n result = ', '.join( dices )\n await ctx.send(result)\n\n# 사용법 : /choose 1 2 3 4 5 6 \n@bot.command(aliases=['선택'], description='선택하기')\nasync def choose(ctx, *choices: str):\n val = random.choice(choices)\n embed = discord.Embed(\n title=\"선택\",\n description=f\"당신의 선택 ==> {val}\",\n url= config.cover_url,\n color=discord.Color.from_rgb(125, 125, 125))\n embed.set_thumbnail(url = domain + random.choice(image_urls))\n await ctx.send( embed= embed)\n\n# 사용법 : /repeat 100 \"아토쌤 사랑해요~\"\n@bot.command(aliases=['반복'])\nasync def repeat(ctx, times: int, content='반복내용...'):\n for i in range(times):\n await ctx.send(f\"{i+1}: {content}\")\n\nbot.run( config.TOKEN)\n\n'''\n/add 명령어 예시 플러스\n- 명령어 추가\n- 명령어 대체이름 aliases 사용\n- 리스트에서 이미지썸네일 사용 \n'''","sub_path":"강의소스/5_봇메신저/1.py","file_name":"1.py","file_ext":"py","file_size_in_byte":2917,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"363466424","text":"from typing import NamedTuple\n\nfrom rest_framework import serializers\n\nfrom document.models import DocNode\nfrom document.tree import DocCursor\nfrom reqs.models import Policy\n\n\nclass PolicySerializer(serializers.ModelSerializer):\n title_with_number = serializers.CharField(read_only=True)\n\n class Meta:\n model = Policy\n fields = (\n 'issuance',\n 'omb_policy_id',\n 'original_url',\n 'title',\n 'title_with_number',\n )\n\n\nclass TableOfContentsSerializer(serializers.ModelSerializer):\n children = serializers.SerializerMethodField()\n\n class Meta:\n model = DocNode\n fields = ('children', 'identifier', 'title')\n\n def get_children(self, instance):\n return type(self)(instance.children(), many=True).data\n\n\nclass Meta(NamedTuple):\n \"\"\"Package of all of the data needed to generate the \"meta\" field.\"\"\"\n cursor: DocCursor\n is_root: bool\n policy: Policy\n\n @property\n def node_type(self):\n return self.cursor.node_type\n\n\nclass MetaSerializer(serializers.Serializer):\n descendant_footnotes = serializers.SerializerMethodField()\n policy = serializers.SerializerMethodField()\n table_of_contents = serializers.SerializerMethodField()\n\n def serialize_doc_cursor(self, doc_cursor: DocCursor):\n serializer = type(self.context['parent_serializer'])\n return serializer(doc_cursor, context={'is_root': False}).data\n\n def to_representation(self, instance):\n \"\"\"Remove fields that don't have data.\"\"\"\n result = super().to_representation(instance)\n to_delete = {key for key, value in result.items() if value is None}\n for key in to_delete:\n del result[key]\n return result\n\n def get_descendant_footnotes(self, instance):\n \"\"\"Find all footnote nodes that are cited by this node or any of its\n descendants.\"\"\"\n if not instance.is_root and instance.node_type != 'table':\n return None\n footnotes = []\n for node in instance.cursor.walk():\n for citation in node.footnotecitations.all():\n subtree = DocCursor(instance.cursor.tree,\n citation.footnote_node.identifier)\n footnotes.append(self.serialize_doc_cursor(subtree))\n return footnotes\n\n def get_policy(self, instance):\n if instance.is_root:\n return PolicySerializer(instance.policy).data\n\n def get_table_of_contents(self, instance):\n if instance.is_root:\n only_titled = DocNode.objects.exclude(title='')\n titled_cursor = DocCursor.load_from_model(\n instance.cursor.model, queryset=only_titled)\n return TableOfContentsSerializer(titled_cursor).data\n","sub_path":"api/document/serializers/meta.py","file_name":"meta.py","file_ext":"py","file_size_in_byte":2790,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"462991737","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Tue May 14 16:57:19 2019\n\n@author: mohit\n\"\"\"\n\nimport re\nl = ['Energies_l.txt', 'AvgKE_l.txt']\n\nfor filename in l:\n filename_2 = 'new' + filename\n file = open(filename, 'r')\n newFile = open(filename_2, 'w')\n\n for line in file:\n newLine = re.sub(' +', ' ', line)\n newFile.write(newLine)\n file.close()\n newFile.close()","sub_path":"Standing_DB_analit/Hard/1_25/separatorScript.py","file_name":"separatorScript.py","file_ext":"py","file_size_in_byte":386,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"213087590","text":"import logging\n\nimport cairo \nimport wx\n\nimport chisualizer.Base as Base\n\nfrom Data import Data\n\n@Base.xml_register('DataText')\nclass DataText(Data):\n \"\"\"Visualizer for data represented as text.\"\"\"\n @classmethod\n def from_xml_cls(cls, element, parent):\n new = super(DataText, cls).from_xml_cls(element, parent)\n display_ref = element.get('display', 'hexadecimal')\n new.display = new.get_ref(display_ref)\n \n new.display_size = new.parse_element_int(element, 'display_size', 14)\n new.display_font = element.get('display_font', 'Mono')\n\n return new\n \n def instantiate(self, new_parent):\n cloned = super(DataText, self).instantiate(new_parent)\n cloned.display = self.display\n cloned.display_size = self.display_size\n cloned.display_font = self.display_font\n return cloned\n\n def draw_element_cairo(self, cr, rect, depth):\n cr.set_source_rgba(*self.get_theme().default_color())\n cr.set_line_width (1)\n cr.select_font_face(self.display_font,\n cairo.FONT_SLANT_NORMAL, cairo.FONT_WEIGHT_BOLD)\n cr.set_font_size(self.display_size)\n \n modifiers = self.display.apply(self.node)\n if 'text' in modifiers:\n text = modifiers['text']\n del modifiers['text']\n else:\n logging.warn(\"%s (%s): no 'text' in modifiers: %s\", self.path, self.__class__.__name__, modifiers)\n text = \"err\"\n cr.set_source_rgb(1, 0, 0)\n \n if 'color' in modifiers:\n color = modifiers['color']\n if type(color) is tuple:\n cr.set_source_rgba(*color)\n else:\n cr.set_source_rgba(*self.get_theme().color(color))\n del modifiers['color']\n \n if modifiers:\n logging.warn(\"%s (%s): unprocessed modifiers: %s\", self.path, self.__class__.__name__, modifiers)\n \n cr.move_to(rect.left(), rect.center_vert() + self.text_max_height / 2)\n cr.show_text(text)\n \n return []\n \n def layout_element_cairo(self, cr):\n texts = self.display.get_longest_text(self.node)\n self.text_max_width = 0\n cr.set_line_width (1)\n cr.select_font_face(self.display_font,\n cairo.FONT_SLANT_NORMAL, cairo.FONT_WEIGHT_BOLD)\n cr.set_font_size(self.display_size)\n for text in texts:\n _, _, _, _, text_width, _ = cr.text_extents(text)\n self.text_max_width = max(self.text_max_width, text_width)\n _, _, _, self.text_max_height, _, _ = cr.text_extents('X')\n return (self.text_max_width, self.text_max_height)\n \n def wx_defaultaction(self):\n self.wx_popupmenu_set(None)\n \n def wx_popupmenu_populate(self, menu):\n item = wx.MenuItem(menu, wx.NewId(), \"%s: Set\" % self.wx_prefix())\n menu.AppendItem(item)\n menu.Bind(wx.EVT_MENU, self.wx_popupmenu_set, item)\n \n super(DataText, self).wx_popupmenu_populate(menu)\n \n return True\n \n def wx_popupmenu_set(self, evt):\n curr_value = \"\"\n modifiers = self.display.apply(self.node)\n if 'text' in modifiers:\n curr_value = modifiers['text']\n \n dlg = wx.TextEntryDialog(None, self.path, 'New Value', curr_value)\n while True:\n ret = dlg.ShowModal()\n if ret != wx.ID_OK:\n return\n curr_value = dlg.GetValue()\n if self.display.set_from_text(self.node, curr_value):\n logging.info(\"Set '%s' to '%s'\" % (self.path, curr_value))\n return\n ","sub_path":"src/chisualizer/visualizers/DataText.py","file_name":"DataText.py","file_ext":"py","file_size_in_byte":3317,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"625350356","text":"from odown import app, cache\nfrom flask import render_template, request, redirect\nfrom tweets import get_tweets\nfrom sqlalchemy.sql import select\nfrom check import URLS_TO_CHECK\nfrom db_helper import get_last_entry, get_24h_statistic\n\n@app.route('/')\ndef index():\n\n\ttweets = get_tweets()\n\tresults = get_last_entry()\n\tstatus = cache.get('status')\n\tstatistic_24h = get_24h_statistic()\n\n\treturn render_template('index.html',tweets = tweets, results = results,\n\t\turls = URLS_TO_CHECK, status = status, statistic = statistic_24h)\n\n@app.route('/impressum.html')\ndef impressum():\n return render_template('impressum.html')\n\n@app.route('/status', methods=['GET', 'POST'])\ndef status():\n\tif request.method == 'GET':\n\t\treturn render_template('status.html')\n\telse:\n\t\tif request.form['pw'] == app.config['ADMIN_PASSWORD']:\n\t\t\tif request.form['status'] == 'nein':\n\t\t\t\tcache.set('status', 'nein', timeout=1000)\n\t\t\telse:\n\t\t\t\tcache.set('status', None)\n\t\treturn redirect('/')\n\n@app.errorhandler(404)\ndef internal_error(error):\n return \"Hmm. Wie haben die Seite nicht finden koennen.\", 404\n\n@app.errorhandler(500)\ndef internal_error(error):\n db.session.rollback()\n return \"Es ist bei uns ein Fehler aufgetreten\", 500","sub_path":"odown/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1207,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"228429029","text":"#!/usr/bin/env python\n\nimport sys, os, yaml, time, urllib2, atexit\nimport logging\n\nfrom helpers.etcd import Etcd\nfrom helpers.postgresql import Postgresql\nfrom helpers.ha import Ha\n\n\nlogging.basicConfig(format='%(asctime)s %(levelname)s: %(message)s', level=logging.INFO)\n\nf = open(sys.argv[1], \"r\")\nconfig = yaml.load(f.read())\nf.close()\n\netcd = Etcd(config[\"etcd\"])\npostgresql = Postgresql(config[\"postgresql\"])\nha = Ha(postgresql, etcd)\n\n# stop postgresql on script exit\ndef stop_postgresql():\n postgresql.stop()\natexit.register(stop_postgresql)\n\n# wait for etcd to be available\netcd_ready = False\nwhile not etcd_ready:\n try:\n etcd.touch_member(postgresql.name, postgresql.connection_string)\n etcd_ready = True\n except urllib2.URLError:\n logging.info(\"waiting on etcd\")\n time.sleep(5)\n\n# is data directory empty?\nif postgresql.data_directory_empty():\n # racing to initialize\n if etcd.race(\"/initialize\", postgresql.name):\n postgresql.initialize()\n etcd.take_leader(postgresql.name)\n postgresql.start()\n else:\n synced_from_leader = False\n while not synced_from_leader:\n leader = etcd.current_leader()\n if not leader:\n time.sleep(5)\n continue\n if postgresql.sync_from_leader(leader):\n postgresql.write_recovery_conf(leader)\n postgresql.start()\n synced_from_leader = True\n else:\n time.sleep(5)\nelse:\n postgresql.follow_no_leader()\n postgresql.start()\n\nwhile True:\n logging.info(ha.run_cycle())\n\n # create replication slots\n if postgresql.is_leader():\n for node in etcd.get_client_path(\"/members?recursive=true\")[\"node\"][\"nodes\"]:\n member = node[\"key\"].split('/')[-1]\n if member != postgresql.name:\n postgresql.query(\"DO LANGUAGE plpgsql $$DECLARE somevar VARCHAR; BEGIN SELECT slot_name INTO somevar FROM pg_replication_slots WHERE slot_name = '%(slot)s' LIMIT 1; IF NOT FOUND THEN PERFORM pg_create_physical_replication_slot('%(slot)s'); END IF; END$$;\" % {\"slot\": member})\n\n etcd.touch_member(postgresql.name, postgresql.connection_string)\n\n time.sleep(config[\"loop_wait\"])\n","sub_path":"governor.py","file_name":"governor.py","file_ext":"py","file_size_in_byte":2256,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"125292628","text":"'''\n1부터 N까지의 숫자에서 홀수는 더하고 짝수는 뺐을 때 최종 누적된 값을 구해보자.\n'''\nfor i in range(int(input())):\n s = 0\n for x in range(1, int(input())+1):\n if x % 2:\n s += x\n else:\n s -= x\n print(f'#{i+1} {s}')","sub_path":"swea/D2/1986.py","file_name":"1986.py","file_ext":"py","file_size_in_byte":292,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"136542639","text":"\"\"\"\nmodels/plotting.py\nparasynchrony\n2014 Brandon Mechtley\nReuman Lab, Kansas Biological Survey\n\nVarious methods for plotting attributes of a StochasticModel, including\nspectra.\n\"\"\"\n\nimport itertools\n\nimport numpy as np\n\nimport matplotlib.pyplot as pp\nimport matplotlib.colors as mplcolors\nimport matplotlib.gridspec as gridspec\n\n\ndef symlog(x):\n \"\"\"\n Signed log-scaling of input by its distance from zero. log(abs(x)) * sign(x)\n\n :param x: (float) input value.\n :return: (float) symmetrically log-scaled value.\n \"\"\"\n\n dtype = type(x) if type(x) != np.ndarray else x.dtype\n\n return np.log(abs(x) + np.finfo(dtype).eps) * np.sign(x)\n\n\ndef plot_twopane_axes(n=1, ylabels=None, yticks=None, ylimits=None):\n \"\"\"\n Set up a GridSpec for an NxN lower left triangular grid of subplots, each\n of which has two vertically stacked panes.\n\n :param n: Number of rows/columns in the grid.\n :param ylabels: (nested list) NxN list of dictionaries, where each dict has\n a 'top' and 'bottom' key, the values of which are the ylabels for the\n corresponding panes (default: None).\n :param yticks: (dict) dictionary with 'top' and 'bottom' keys indicating y\n tick values for top and bottom panes, assuming they are the same across\n all grid cells (default: None).\n :param ylimits: (dict) dictionary with 'top' and 'bottom' keys pointing to\n two-value tuples indicating lower and upper y axis limits, assuming\n they are the same across all grid cells (default: None).\n :return: (list) list of axes of instance matplotlib.Axes.\n \"\"\"\n\n fig = pp.gcf()\n gs = gridspec.GridSpec(n, n, wspace=0.25, hspace=0.25)\n axlist = [[{} for _ in range(n)] for _ in range(n)]\n\n for i, j in itertools.combinations_with_replacement(range(n), 2):\n # This is the vertically stacked grid inside the current grid cell.\n inner_grid = gridspec.GridSpecFromSubplotSpec(\n 2, 1, subplot_spec=gs[n * j + i], wspace=0, hspace=0\n )\n\n for pane_index, pane in enumerate(['top', 'bottom']):\n ax = pp.Subplot(pp.gcf(), inner_grid[pane_index])\n\n # Both panes should share the lower pane's x axis.\n if pane is 'top':\n ax.get_xaxis().set_visible(False)\n\n fig.add_subplot(ax)\n pp.sca(ax)\n\n # Set y ticks, limits, and labels if they're specified.\n if yticks[pane] is not None:\n pp.yticks(yticks[pane].values())\n ax.set_yticklabels(yticks[pane].keys())\n\n if ylimits is not None and pane in ylimits:\n pp.ylim(*ylimits[pane])\n\n if ylabels is not None:\n pp.ylabel(ylabels[i][j][pane])\n\n axlist[i][j][pane] = ax\n\n return axlist\n\n\ndef plot_cospectra(\n freqs,\n pxx,\n varnames=None,\n plotfun=None,\n axpanes=None,\n **plotargs\n):\n \"\"\"\n Make a NxN lower triangular plot of cospectra between state variables.\n\n :param freqs: (array) (F,) List of frequencies.\n :param pxx: (array) The (N,N,F) spectral matrix.\n :param varnames: (list) List of N names for the states. If None, no labels\n will be drawn (default: None).\n :param plotfun: (callable or str) Plot function to use for the spectrum. If\n None, pyplot.scatter will be used for frequency resolution F <= 8192,\n and pp.hist2d will be used for F > 8192 (default: None).\n :param axpanes: (list) nested NxN list of dictionaries where each dict has\n keys 'top' and 'bottom' that point to matplotlib.Axes instances\n corresponding to the top (magnitude) and bottom (phase) plots\n respectively. If None is specified, the axes will be created and\n returned for re-use in overlaying plots.\n :param plotargs: (dict) additional arguments to pass to plotfun.\n :return: (list) nested NxN list of dictionaries formed in the same way as\n axpanes.\n \"\"\"\n\n # Set up defaults for plotting type/parameters.\n if plotfun is None:\n # If auto, automatically determine if a plot should use scatter or\n # hist2d based on how many bins there are to plot.\n if len(freqs) > 8192:\n plotfun = pp.hist2d\n else:\n plotfun = pp.scatter\n\n if plotfun is pp.hist2d:\n plotargs.setdefault('bins', 200)\n plotargs.setdefault('normed', True)\n\n # If \"color\" is specified, make a colormap that linearly scales alpha\n # at that color. Otherwise, use the default or specified cmap. Useful\n # for overlaying multiple plots with different colors.\n if 'color' in plotargs:\n if 'cmap' not in plotargs:\n plotargs['cmap'] = mplcolors.LinearSegmentedColormap.from_list(\n 'custom_histcmap',\n [\n mplcolors.colorConverter.to_rgba(plotargs['color'], 0),\n mplcolors.colorConverter.to_rgba(plotargs['color'], 1)\n ]\n )\n\n plotargs.pop('color')\n elif plotfun is pp.scatter:\n plotargs.setdefault('alpha', 0.25)\n plotargs.setdefault('marker', '.')\n plotargs.setdefault('s', 1)\n\n # Make axes for two-pane lower left triangle grid if they aren't provided.\n n = len(pxx)\n\n if axpanes is None:\n axpanes = plot_twopane_axes(\n n=n,\n ylabels=[\n [\n dict(\n top='$\\\\log f_{%s%s}$' % (varnames[i], varnames[j]),\n bottom='$\\\\angle f_{%s%s}$' % (varnames[i], varnames[j])\n )\n for j in range(n)\n ]\n for i in range(n)\n ] if varnames is not None else None,\n yticks=dict(\n top=None,\n bottom=dict(zip(\n ['$-pi/2$', '$0$', '$pi/2$'],\n [-np.pi/2, 0, np.pi/2]\n ))\n ),\n ylimits=dict(bottom=[-np.pi, np.pi])\n )\n\n # Plot each spectral matrix component in the created/provided axes.\n for i, j in itertools.combinations_with_replacement(range(n), 2):\n # Magnitude.\n pp.sca(axpanes[i][j]['top'])\n plotfun(freqs, abs(pxx[i, j]), **plotargs)\n\n if np.sum(abs(pxx[i, j])) > 0:\n pp.yscale('log')\n\n pp.xlim(0, freqs[-1])\n\n # Phase.\n pp.sca(axpanes[i][j]['bottom'])\n plotfun(freqs, np.angle(pxx[i, j]), **plotargs)\n pp.xlim(0, freqs[-1])\n\n return axpanes\n\n\ndef plot_phase(series, varnames=None, logscale=False, plotfun=None, **plotargs):\n \"\"\"\n Make a NxN lower triangular phase-space plot that plots pairs of state\n variables as functions of each other in a two-dimensional histogram.\n\n :param series: (array) The (N,T) state trajectory.\n :param varnames: (list) N state variable names. If None, no labels will be\n drawn (default: None).\n :param logscale: (bool) Whether or not variables should be plot on a log\n scale (default: False).\n :param plotfun: (callable) Matplotlib plotting function to use for the\n plots. If None, a plotting method will automatically be chosen from\n pp.plot, pp.scatter, and pp.hist2d, based upon how many data points\n there are (default: None).\n :param plotargs: Any additional parameters to plotfun, such as bin count.\n \"\"\"\n\n # Set up defaults for plotting type/parameters.\n if plotfun is None:\n if len(series.shape) > 1 and series.shape[1] > 8192:\n plotfun = pp.hist2d\n else:\n plotfun = pp.scatter\n\n if plotfun is pp.scatter:\n plotargs.setdefault('alpha', 0.25)\n plotargs.setdefault('marker', '.')\n plotargs.setdefault('s', 1)\n elif plotfun is pp.hist2d:\n plotargs.setdefault('bins', 200)\n plotargs.setdefault('normed', True)\n\n if 'cmap' not in plotargs:\n plotargs.setdefault('color', 'green')\n\n plotargs['cmap'] = mplcolors.LinearSegmentedColormap.from_list(\n 'custom_histcmap',\n [\n mplcolors.colorConverter.to_rgba(plotargs['color'], 0),\n mplcolors.colorConverter.to_rgba(plotargs['color'], 1)\n ]\n )\n\n plotargs.pop('color')\n\n nstates, nsamples = series.shape\n\n # Plot lower left triangle grid.\n for i, j in itertools.combinations_with_replacement(range(nstates), 2):\n pp.subplot(nstates, nstates, nstates * j + i + 1)\n\n # Plot axis labels if varname are provided.\n if varnames is not None:\n if j is len(varnames) - 1:\n pp.xlabel('$%s$' % varnames[i])\n\n if i is 0:\n pp.ylabel('$%s$' % varnames[j])\n\n # Scale values.g\n xs, ys = series[i], series[j]\n if logscale:\n xs, ys = symlog(xs), symlog(ys)\n\n plotfun(xs, ys, **plotargs)\n","sub_path":"models/plotting.py","file_name":"plotting.py","file_ext":"py","file_size_in_byte":8979,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"418935715","text":"import difflib\nimport random\nimport time\n\nfrom config.log.logger import Logger\nfrom config.setup import *\nfrom google.google_sheets import GoogleSheets\nfrom google.google_drive_connector import GoogleDriveConnector\nimport pandas as pd\nfrom vk_api.bot_longpoll import VkBotEventType, VkBotLongPoll\nfrom vk_api.utils import get_random_id\nimport vk_api.vk_api\n\nfrom message_parser import MessageParser\nfrom keyboard import Keyboard\n\n\nclass VkBot:\n\n def __init__(self, group_id, token, table_name, room_list, service_account_file, vk_bot: str = \"bot\", ):\n \"\"\"Creates a new bot with parameters from the setup file\"\"\"\n self.logger = Logger('app').logger\n self.logger.info('Start of bot initialization')\n self.vk_bot = vk_bot\n self.group_id = group_id\n self.vk_session = vk_api.VkApi(token=token)\n self.long_poll = VkBotLongPoll(self.vk_session, group_id)\n self.vk = self.vk_session.get_api()\n self.master_id = GOSHA_ID\n self.admins_ids = GOSHA_ID\n self.vk_link = VK_LINK\n\n self.room_list = room_list\n self.table_name = table_name\n\n self.gs = GoogleSheets(table_name, service_account_file)\n self.gd = GoogleDriveConnector(service_account_file)\n self.keyboard = Keyboard()\n\n self.logger.info(\"Completion of bot initialization\")\n\n self.logger.info('Start of answers download')\n self.mp = MessageParser(self.vk, self.gs)\n\n self.data_to_upload = {'room': [], 'fullname': [], 'id': []}\n\n self.logger.info(\"Completion of answer download\")\n\n def write_about_exception(self, event):\n \"\"\"Sends an exception message to the user and developer.\n\n :param event: Event that caused the exception.\n :return: None.\n \"\"\"\n self.write_msg(self.master_id, 'Что-то пошло не так с командой {} от пользователя {}.'.format(event.obj.text, ' '.join(self.mp.get_full_name(event.obj.from_id))),\n self.keyboard.user_keyboard)\n\n self.write_msg(event.obj.peer_id,\n 'Что-то пошло не так, попробуйте повторить попытку позднее.', self.keyboard.user_keyboard)\n self.logger.exception('Exception:')\n\n def write_events(self, event):\n \"\"\"Specifies the type of event to write to the file.\n\n :param event: The event that you want to write to a file.\n :param time: Time when the event occurred.\n :return: None.\n \"\"\"\n\n if event.type == VkBotEventType.GROUP_JOIN:\n self.logger.info('New user group membership')\n\n elif event.type == VkBotEventType.GROUP_LEAVE:\n self.logger.info('Leaving a group')\n\n elif event.type == VkBotEventType.MESSAGE_NEW:\n self.logger.info('New incoming message: \"{}\" from user {}'.format(event.obj.text,\n ' '.join(self.mp.get_full_name(event.obj.peer_id))))\n self.logger.info(event.obj)\n\n elif event.type == VkBotEventType.MESSAGE_REPLY:\n self.logger.info('New outgoing message \"{}..\" for user {}'.format(event.obj.text[:20],\n ' '.join(self.mp.get_full_name(event.obj.peer_id))))\n\n def write_msg(self, peer_id, message, keyboard):\n \"\"\"Sends a message to the user.\n\n :param peer_id: Id of the user to send the message to.\n :param message: Text of the message to send.\n :return: None\n \"\"\"\n self.vk.messages.send(peer_id=peer_id,\n random_id=get_random_id(),\n message=message,\n keyboard=keyboard)\n\n def send_msg_about_duty(self):\n \"\"\"\"Sends a message to students who are on duty at a certain time today.\"\"\"\n self.logger.info('Duty thread is started')\n while True:\n if '19.00.00' <= time.strftime(\"%H.%M.%S\", time.localtime()) <= '19.10.00':\n rooms = self.gs.get_duty_room()\n if rooms:\n self.logger.info('Duty rooms {} detected'.format(rooms))\n\n for room in rooms:\n ids = self.gs.get_duty_ids_by_room(room)\n for id in ids:\n self.write_msg(int(id), 'Сегодня дежурит {} комната.'.format(room), self.keyboard.user_keyboard)\n\n else:\n self.logger.info('Duty rooms not detected')\n\n # if self.update_time['begin'] <= time.strftime(\"%H.%M.%S\", time.localtime()) <= self.update_time['end']:\n\n time.sleep(600)\n self.update_data()\n\n def update_data(self):\n \"\"\"Updates information from Google Sheets\"\"\"\n self.logger.info('Start of data update')\n\n self.upload_links()\n\n self.gs.update_data()\n\n self.mp.about_commandant = self.gs.get_answer_text('ABOUT_MILENA')[0]\n self.mp.about_castellan = self.gs.get_answer_text('ABOUT_MARGO')[0]\n self.mp.about_gym = self.gs.get_answer_text('ABOUT_GYM')[0]\n self.mp.about_study_room = self.gs.get_answer_text('ABOUT_STUDY_ROOM')[0]\n self.mp.about_guests = self.gs.get_answer_text('ABOUT_GUESTS')[0]\n self.mp.about_shower = self.gs.get_answer_text('ABOUT_SHOWER')[0]\n self.mp.about_laundry = self.gs.get_answer_text('ABOUT_LAUNDRY')[0]\n self.mp.about_duty = self.gs.get_answer_text('REMINDER_ABOUT_DUTY')[0]\n self.mp.question = self.gs.get_answer_text('ABOUT_STUDSOVET')[0]\n self.mp.about_bot = self.gs.get_answer_text('ABOUT_BOT')[0]\n self.mp.parting = self.gs.get_answer_text('PARTING')\n self.mp.opportunities = self.gs.get_answer_text('OPPORTUNITIES')[0]\n self.mp.rude_commands = self.gs.get_answer_text('RUDE_COMMANDS')\n self.mp.good_room = self.gs.get_answer_text('GOOD_ROOM')[0]\n self.mp.bad_room = self.gs.get_answer_text('BAD_ROOM')[0]\n self.mp.unknown_commands = self.gs.get_answer_text('UNKNOWN_COMMANDS')\n self.mp.topical = self.gs.get_answer_text('TOPICAL')[0]\n self.mp.about_invoice = self.gs.get_answer_text('ABOUT_INVOICE')[0]\n\n self.logger.info('Completion of data update')\n\n def send_answer(self, event, msg, keyboard):\n try:\n self.write_msg(event.obj.peer_id, msg, keyboard)\n except Exception:\n self.write_about_exception(event)\n self.logger.exception('Answer Exception')\n\n def upload_links(self):\n self.logger.info('Start of uploading links')\n\n if len(self.data_to_upload['room']) > 0:\n try:\n for i in range(len(self.data_to_upload['room'])):\n self.gs.add_student(self.data_to_upload['room'][i],\n self.data_to_upload['id'][i],\n self.data_to_upload['fullname'][i])\n self.write_msg(self.data_to_upload['id'][i], self.mp.good_room, self.keyboard.user_keyboard)\n\n except Exception:\n self.logger.exception('Links are not uploaded')\n\n else:\n self.logger.info('Links uploaded')\n self.data_to_upload = {'room': [], 'fullname': [], 'id': []}\n self.gs.links_dataframe = pd.DataFrame(self.gs.sheet_links.get_all_records())\n\n def get_events(self):\n self.write_msg(self.master_id, 'Бот запущен', self.keyboard.user_keyboard)\n self.logger.info('Main thread is started')\n\n for event in self.long_poll.listen():\n if event.type == VkBotEventType.MESSAGE_NEW:\n self.write_events(event)\n request = event.obj.text.upper()\n forwarded_request = event.obj.text\n is_answered = False\n\n if event.obj.peer_id == self.master_id:\n if request.startswith('НАПИШИ'):\n try:\n room = forwarded_request.split()[1]\n mes = ' '.join(forwarded_request.split()[2:])\n ids = self.gs.get_duty_ids_by_room(int(room))\n # print(ids)\n for id in ids:\n self.write_msg(int(id), mes, self.keyboard.user_keyboard)\n except Exception:\n self.write_about_exception(event)\n\n else:\n if ids:\n self.write_msg(self.master_id, 'Сделано', self.keyboard.user_keyboard)\n else:\n self.write_msg(self.master_id, 'Никого не оказалось', self.keyboard.user_keyboard)\n is_answered = True\n if request.startswith(\"ОБНОВИ\"):\n try:\n self.write_msg(self.master_id, 'Это займет некоторое время, подождите', self.keyboard.user_keyboard)\n self.update_data()\n except Exception:\n self.write_msg(self.master_id, 'Данные не обновлены, повторите попытку позднее', self.keyboard.user_keyboard)\n self.logger.exception('Information is not updated')\n else:\n self.write_msg(self.master_id, 'Данные успешно обновлены', self.keyboard.user_keyboard)\n self.logger.info('Information updated')\n\n is_answered = True\n\n if event.obj.reply_message:\n # print(difflib.SequenceMatcher(None, self.about_studsovet, event.obj.reply_message['text']).ratio())\n # print(self.about_studsovet)\n # print(event.obj.reply_message['text'])\n\n if difflib.SequenceMatcher(None, self.mp.question, event.obj.reply_message['text']).ratio() >= 0.99:\n try:\n self.write_msg(event.obj.peer_id, 'Спасибо за вопрос, я передал его.', self.keyboard.user_keyboard)\n self.write_msg(self.master_id, '{} спросил:\\n{} \\nСсылка на страницу: {}{}'.format(\n ' '.join(self.mp.get_full_name(event.obj.from_id)),\n forwarded_request,\n self.vk_link,\n event.obj.peer_id), self.keyboard.user_keyboard)\n except Exception:\n self.write_about_exception(event)\n is_answered = True\n\n elif difflib.SequenceMatcher(None, self.mp.about_duty, event.obj.reply_message['text']).ratio() >= 0.99:\n if request.isdigit() and int(request) in self.room_list:\n\n if len(self.data_to_upload['room']) == len(self.data_to_upload['id']) == len(self.data_to_upload['fullname']):\n\n self.data_to_upload['room'].append(request)\n self.data_to_upload['id'].append(event.obj.peer_id)\n self.data_to_upload['fullname'].append(' '.join(self.mp.get_full_name(event.obj.from_id)))\n\n self.logger.info('Link is added')\n\n if len(self.data_to_upload['room']) >= 5:\n self.upload_links()\n else:\n self.logger.info('Current length of links is {}. Data is not loaded'.format(len(self.data_to_upload['room'])))\n\n self.write_msg(event.obj.peer_id, 'Ты ввел корректную комнату.\\n\\nОжидай добавления в базу :)', self.keyboard.user_keyboard)\n else:\n self.write_msg(self.master_id, 'Нарушение структуры данных для загрузки', self.keyboard.user_keyboard)\n else:\n try:\n self.write_msg(event.obj.from_id, self.mp.bad_room, self.keyboard.user_keyboard)\n except Exception:\n self.write_about_exception(event)\n is_answered = True\n\n elif event.obj.reply_message['text'] == self.mp.about_invoice:\n try:\n if event.obj.attachments:\n for i in event.obj.attachments:\n\n from_id = event.obj.from_id\n name = self.mp.get_full_name(from_id)\n if i['type'] == 'doc' or i['type'] == 'photo':\n if i['type'] == 'doc':\n ext = i['doc']['ext']\n url = i['doc']['url']\n filename = \"{} {}.{}\".format(name[1], name[0], ext)\n\n else:\n url = self.mp.get_max_image_url(i['photo']['sizes'])\n filename = \"{} {}.jpg\".format(name[1], name[0])\n\n if self.gd.upload_invoice(url, filename):\n self.write_msg(from_id, \"Твой чек успешно загружен\", self.keyboard.user_keyboard)\n else:\n self.write_msg(from_id, \"Твой чек не загружен. Повтори попытку позднее\", self.keyboard.user_keyboard)\n\n except Exception:\n self.write_about_exception(event)\n self.logger.exception('Invoice is not loaded')\n is_answered = True\n\n if not is_answered:\n command = self.mp.get_msg_type(request)\n\n if command == 'duty':\n self.logger.info('Command \"Дежурство\" detected')# напоминание о дежурстве\n room = self.gs.get_room_by_id(event.obj.from_id)\n # print(room)\n if room:\n floor = room // 100\n\n if floor < 2:\n floor = 2\n\n # print(floor)\n try:\n date = self.gs.get_duty_date_by_room_number(room)\n # print('date', date)\n duty_rooms = self.gs.get_duty_room()\n # print(duty_rooms)\n # if duty_rooms:\n for room in duty_rooms:\n # print(type(room))\n # print(type(floor))\n if room // 100 == floor:\n if date:\n # print(room)\n self.write_msg(event.obj.peer_id, 'Сегодня дежурит {} комната.\\n\\n'\n 'Следующее дежурство твоей команты будет {}.'.format(room, date), self.keyboard.user_keyboard)\n is_answered = True\n else:\n # print(room)\n self.write_msg(event.obj.peer_id, 'Сегодня дежурит {} комната.\\n\\n'\n 'Следующее дежурство твоей комнаты будет в следующем месяце.'.format(room), self.keyboard.user_keyboard)\n is_answered = True\n\n except Exception:\n self.write_about_exception(event)\n if not is_answered:\n self.write_msg(event.obj.peer_id, 'Пока данных нет, но они скоро появятся!',\n self.keyboard.user_keyboard)\n else:\n try:\n self.write_msg(event.obj.peer_id, self.mp.about_duty, self.keyboard.user_keyboard)\n except Exception:\n self.write_about_exception(event)\n\n else:\n self.logger.info('Command \"{}\" detected'.format(command))\n try:\n self.send_answer(event, self.mp.get_answer_by_msg_type(command), self.keyboard.user_keyboard)\n except Exception:\n self.write_about_exception(event)\n\n #\n # elif command == 'invoice': # чек\n # self.logger.info('Command \"Чек\" detected')\n # # if event.obj.fwd_messages:\n # # from_id = event.obj.fwd_messages[0]['from_id']\n # # name = self.mp.get_full_name(from_id)\n # #\n # # # if event.obj.fwd_messages[0]['attachments'][0]['type'] == 'doc':\n # # # url = event.obj.fwd_messages[0]['attachments'][0]['doc']['url']\n # # # ext = event.obj.fwd_messages[0]['attachments'][0]['doc']['ext']\n # # #\n # # # filename = \"{} {}.{}\".format(name[1], name[0], ext)\n # # #\n # # # elif event.obj.fwd_messages[0]['attachments'][0]['type'] == 'photo':\n # # #\n # # # url = self.mp.get_max_image_url([msg['photo']['sizes'] for msg in event.obj.fwd_messages[0]['attachments']])\n # # # filename = \"{} {}.jpg\".format(name[1], name[0])\n # # #\n # # # self.gd.upload_invoice(url, filename)\n # # else:\n # self.write_msg(event.obj.peer_id, self.about_invoice, self.keyboard.user_keyboard)\n #\n elif event.type == VkBotEventType.MESSAGE_REPLY:\n self.write_events(event)\n\n elif event.type == VkBotEventType.GROUP_JOIN:\n self.write_events(event)\n","sub_path":"vkbot.py","file_name":"vkbot.py","file_ext":"py","file_size_in_byte":19326,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"607704688","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n# @Time : 2019/7/25 18:04\n# @Author : 郑帅\n# @File : test1.py\n# @Software: win10 python3.6.7\nimport datetime\nimport logging.handlers\nimport os\n\n\ndef log(msg,file_name=\"run_file\"):\n \"\"\"\n 创建一个日志对象\n \"\"\"\n # 输出日志的格式\n file_time = datetime.datetime.now().strftime(\"_%Y_%m_%d\")\n log_formatter = logging.Formatter(\n '%(asctime)s [%(filename)s %(funcName)s:%(lineno)d] %(thread)d %(levelname)s %(message)s')\n log_file = os.path.join(os.getcwd()+\"\\\\logs\", file_name+file_time+\".log\")\n my_handler = logging.handlers.RotatingFileHandler(\n log_file, mode='a',\n maxBytes=100 * 1024 * 1024,\n backupCount=4,\n encoding=\"utf-8\",\n delay=0\n )\n\n my_handler.setFormatter(log_formatter)\n my_handler.setLevel(logging.DEBUG)\n\n logger = logging.getLogger('root')\n logger.setLevel(logging.DEBUG)\n logger.addHandler(my_handler)\n\n # logger.debug out log to the console\n ch = logging.StreamHandler()\n ch.setLevel(logging.DEBUG)\n logger.addHandler(ch)\n logger.debug(msg)\n # 移除处理器\n logger.removeHandler(my_handler)\n logger.removeHandler(ch)\n\n\n\n\n","sub_path":"learn_logger/logger_fun.py","file_name":"logger_fun.py","file_ext":"py","file_size_in_byte":1216,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"338137273","text":"import os\nimport threading\nfrom functools import partial\nfrom itertools import chain\n\nimport numpy as np\nimport pandas as pd\n\nfrom pymongo import MongoClient\n\nfrom .util import tqdm_proxy, compute_parallel\nfrom .dvid import fetch_supervoxels\n\n##\n## Notes:\n##\n## The entire set of original hemibrain \"iteration-1\" adjacencies was loaded into mongo.\n## The database can be found here:\n## /groups/flyem/data/scratchspace/hemibrain/mongo-edges-indexed/\n## There's a README in there that explains how to launch a mongo server.\n## Typically, you should copy it to a fast local drive such as /scratch/= min_score, edges)]\n \n if len(edges) == 0:\n return (body, \"None of the body's edges exceed the min_score\")\n\n for e in edges:\n del e['_id']\n e['body'] = body\n \n if format == 'json':\n return edges\n else:\n # fix dtypes\n df = pd.DataFrame(edges)\n df['sv_a'] = df['sv_a'].astype(np.uint64)\n df['sv_b'] = df['sv_b'].astype(np.uint64)\n df['score'] = df['score'].astype(np.float32)\n df['resolution'] = df['resolution'].astype(np.int8)\n for col in ['za', 'ya', 'xa', 'zb', 'yb', 'xb']:\n df[col] = df[col].astype(np.int32)\n return df\n\n\ndef fetch_all_edges_for_bodies(mongo_server, dvid_server, uuid, instance, bodies, min_score=0.1,\n all_singletons=False, batch_size=100_000, processes=32):\n \"\"\"\n Fetch in batches, converting to DataFrame only after each batch.\n \"\"\"\n batch_error_dfs = []\n \n batch_dfs = []\n for batch_start in tqdm_proxy(range(0, len(bodies), batch_size)):\n batch_bodies = bodies[batch_start:batch_start+batch_size]\n\n _query_fn = partial(fetch_all_edges_from_body, mongo_server, dvid_server, uuid, instance, # body,\n min_score=min_score, is_singleton=all_singletons, format='json')\n\n edge_lists = compute_parallel(_query_fn, batch_bodies, 1000, ordered=False, processes=processes)\n\n batch_errors = [*filter(lambda e: e is not None and isinstance(e, tuple), edge_lists)]\n if batch_errors:\n batch_error_df = pd.DataFrame(batch_errors, columns=['body', 'error'])\n batch_error_df['error'] = batch_error_df['error'].astype('category')\n batch_error_dfs.append( batch_error_df )\n \n edge_lists = filter(lambda e: (e is not None) and (len(e) > 0) and not isinstance(e, tuple), edge_lists)\n edges = list(chain(*edge_lists))\n\n # fix dtypes\n df = pd.DataFrame(edges)\n df['sv_a'] = df['sv_a'].astype(np.uint64)\n df['sv_b'] = df['sv_b'].astype(np.uint64)\n df['score'] = df['score'].astype(np.float32)\n df['resolution'] = df['resolution'].astype(np.int8)\n for col in ['za', 'ya', 'xa', 'zb', 'yb', 'xb']:\n df[col] = df[col].astype(np.int32)\n\n batch_dfs.append(df)\n\n final_df = pd.concat(batch_dfs, ignore_index=True)\n \n if batch_error_dfs:\n final_error_df = pd.concat(batch_error_dfs, ignore_index=True)\n else:\n final_error_df = None\n\n return final_df, final_error_df\n","sub_path":"neuclease/edgedb.py","file_name":"edgedb.py","file_ext":"py","file_size_in_byte":6662,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"336455641","text":"\r\n'''................................................................................'''\r\nimport tensorflow as tf\r\nimport numpy as np\r\nimport pandas as pd\r\nimport time as tm\r\n#from tensorflow.contrib.data import Iterator\r\nfrom tensorflow.python.framework import dtypes\r\nfrom tensorflow.python.framework.ops import convert_to_tensor\r\n'''..................................................................................'''\r\n# parameters\r\nuser = 20 # 8 # 20\r\nantenna = 30 # 16 # 30\r\n\r\nnum_snr = 6\r\nlow_snr_db_train = 7.0\r\nhigh_snr_db_train = 14.0\r\nlow_snr_db_test = 7.0 # 8.0\r\nhigh_snr_db_test = 14.0 # 13.0\r\n\r\nlow_snr_train = 10.0 ** (low_snr_db_train/10.0)\r\nhigh_snr_train = 10.0 ** (high_snr_db_train/10.0)\r\nlow_snr_test = 10.0 ** (low_snr_db_test/10.0)\r\nhigh_snr_test = 10.0 ** (high_snr_db_test/10.0)\r\n\r\nbatch_size = 100 # 1000\r\ntrain_iter = 10000 # 1000000\r\ntest_iter = 1000\r\nfc_size = 200 # user * user * user # 200\r\nnum_of_hidden_layers = 5 # user\r\nstartingLearningRate = .0003 # 0.0003\r\ndecay_factor = 0.97 # 0.97\r\ndecay_step_size = 1000\r\n\r\nn_classes = 2 * user\r\n\r\nH = np.genfromtxt('Top06_30_20.csv', dtype=None, delimiter=',')\r\n\r\n'''..................................................................................'''\r\n\r\nsess = tf.InteractiveSession()\r\n\r\ndef constellation_alphabet(mod):\r\n if mod == 'BPSK':\r\n return np.array([[-1, 1]], np.float)\r\n elif mod == 'QPSK':\r\n return np.array([[-1, 1]], np.float)\r\n elif mod == '16QAM':\r\n return np.array([[-3, -1, 1, 3]], np.float)\r\n elif mod == '64QAM':\r\n return np.array([[-7, -5, -3, -1, 1, 3, 5, 7]], np.float)\r\n\r\nCONS_ALPHABET = constellation_alphabet('QPSK')\r\nlength_one_hot_vector = CONS_ALPHABET.shape[1]\r\n\r\n\r\ndef generate_one_hot(symbol, B, K, length_one_hot):\r\n depth_one_hot_vector = CONS_ALPHABET.shape[1]\r\n reset_symbol = symbol + np.multiply(np.ones([B, K]), (abs(np.amin(CONS_ALPHABET, 1)) + 1))\r\n one_hot_vector = tf.one_hot(reset_symbol, depth_one_hot_vector, on_value=1.0, off_value=0.0, axis=-1)\r\n one_hot_arr = sess.run(one_hot_vector)\r\n one_hot_vector_reshaped = one_hot_arr.reshape(B, K, length_one_hot)\r\n return one_hot_vector_reshaped\r\n\r\n\r\ndef hidden_layer(x,input_size,output_size,Layer_num):\r\n W = tf.Variable(tf.random_normal([input_size, output_size], stddev=0.01))\r\n w = tf.Variable(tf.random_normal([1, output_size], stddev=0.01))\r\n y = tf.matmul(x, W)+w\r\n return y\r\n\r\n\r\ndef activation_fn(x,input_size,output_size,Layer_num):\r\n y = tf.nn.relu(hidden_layer(x,input_size,output_size,Layer_num))\r\n return y\r\n\r\ndef weight_variable(shape):\r\n initial = tf.truncated_normal(shape, stddev=0.05)\r\n return tf.Variable(initial)\r\n\r\n\r\ndef bias_variable(shape):\r\n initial = tf.constant(0.1, shape=shape)\r\n return tf.Variable(initial)\r\n\r\n\r\ndef generate_data_train(B, K, N, snr_low, snr_high, H_org):\r\n # H_ = np.random.randn(B, N, K)\r\n # W_ = np.zeros([B, K, K])\r\n rand_symbol_ind = (np.random.randint(low = 0, high = CONS_ALPHABET.shape[1], size = (B*K, 1))).flatten()\r\n transmitted_symbol = (CONS_ALPHABET[:, rand_symbol_ind])\r\n\r\n x_ = transmitted_symbol.reshape(B, K)\r\n\r\n length_one_hot_vector = CONS_ALPHABET.shape[1]\r\n x_one_hot = generate_one_hot(x_, B, K, length_one_hot_vector)\r\n y_ = np.zeros([B, N])\r\n w = np.random.randn(B, N)\r\n H_ = np.zeros([B, N, K])\r\n Hy_ = x_ * 0\r\n HH_ = np.zeros([B, K, K])\r\n SNR_ = np.zeros([B])\r\n for i in range(B):\r\n SNR = np.random.uniform(low=snr_low, high=snr_high)\r\n H = H_org\r\n #H = H_[i, :, :]\r\n tmp_snr = (H.T.dot(H)).trace() / K\r\n H_[i, :, :] = H\r\n y_[i, :] = (H.dot(x_[i, :]) + w[i, :] * np.sqrt(tmp_snr) / np.sqrt(SNR))\r\n Hy_[i, :] = H.T.dot(y_[i, :])\r\n HH_[i, :, :] = H.T.dot(H_[i, :, :])\r\n SNR_[i] = SNR\r\n return y_, H_, Hy_, HH_, x_, SNR_, x_one_hot\r\n\r\n\r\n\r\nreceived_sig = tf.placeholder(tf.float32, shape=[None, 1, antenna, 1], name='input')\r\n#received_sig = tf.placeholder(tf.float32, shape=[None, user], name='input')\r\n#received_sig = tf.placeholder(tf.float32, shape=[None, antenna], name='input')\r\ntransmitted_sig = tf.placeholder(tf.float32, shape=[None, user], name='org_siganl')\r\nbatchSize = tf.placeholder(tf.int32)\r\nbatch_x_one_hot = tf.placeholder(tf.float32, shape=[None, user, length_one_hot_vector], name='one_hot_org_siganl')\r\n'''...............................................................................'''\r\n\r\n#x = tf.placeholder('float32', [None, 1, samples_num_in_segments, 1])\r\ny = tf.placeholder('int32')\r\n\r\nkeep_rate = 0.75\r\nkeep_prob = tf.placeholder(tf.float32)\r\n\r\ndef error_rate(transmitted_symbol, estimated_symbol):\r\n trasmitted_symbol_stacked = transmitted_symbol\r\n #trasmitted_symbol_stacked = tf.reshape(transmitted_symbol, tf.stack([K * batchSize]))\r\n estimated_symbol_stacked = estimated_symbol\r\n #estimated_symbol_stacked = tf.reshape(estimated_symbol, tf.stack([K * batchSize]))\r\n #t = np.ones([1, CONS_ALPHABET.size])\r\n #p1 = np.matmul(estimated_symbol_stacked, t)\r\n v1 = np.matmul(estimated_symbol_stacked, np.ones([1, CONS_ALPHABET.size]))\r\n v2 = np.matmul(np.ones([user * batch_size, 1]), CONS_ALPHABET)\r\n\r\n idxhat = np.argmin(np.square(np.abs(v1 - v2)), axis=1)\r\n\r\n idx = CONS_ALPHABET[:, idxhat]\r\n accuracy_zf = np.equal(idx.flatten(), np.transpose(trasmitted_symbol_stacked))\r\n\r\n error_zf = 1 - (np.sum(accuracy_zf) / (user * batch_size))\r\n\r\n return error_zf\r\n\r\n\r\ndef conv2d(x, W):\r\n return tf.nn.conv2d(x, W, strides=[1, 1, 1, 1], padding='VALID')\r\n\r\n\r\ndef maxpool2d(x):\r\n # size of window movement of window\r\n return tf.nn.max_pool(x, ksize=[1, 1, 5, 1], strides=[1, 1, 1, 1], padding='SAME')\r\n #return tf.nn.max_pool(x, ksize=[1, 1, 2, 1], strides=[1, 1, 2, 1], padding='VALID')\r\n\r\n\r\ndef convolutional_neural_network(x):\r\n\r\n weights = {'W_conv1': tf.Variable(tf.random_normal([1, 5, 1, 8])), # 8 filters\r\n 'W_conv2': tf.Variable(tf.random_normal([1, 5, 8, 16])),\r\n 'W_conv3': tf.Variable(tf.random_normal([1, 5, 16, 32])),\r\n 'W_conv4': tf.Variable(tf.random_normal([1, 5, 32, 32])),\r\n\r\n\r\n 'W_fc': tf.Variable(tf.random_normal([14 * 32, 20])), #([7* 32 * 41, 256])) # no of wavelet components is 7\r\n #'W_fc': tf.Variable(tf.random_normal([7 * 32 * 41, 256])), #([7* 32 * 41, 256])) # no of wavelet components is 7\r\n 'out': tf.Variable(tf.random_normal([20, 20]))}\r\n #'out': tf.Variable(tf.random_normal([200, n_classes]))}\r\n\r\n biases = {'b_conv1': tf.Variable(tf.random_normal([8])),\r\n 'b_conv2': tf.Variable(tf.random_normal([16])),\r\n 'b_conv3': tf.Variable(tf.random_normal([32])),\r\n 'b_conv4': tf.Variable(tf.random_normal([32])),\r\n\r\n 'b_fc': tf.Variable(tf.random_normal([20])),\r\n 'out': tf.Variable(tf.random_normal([20]))} # n times 32 will be the b_fc, input dimension\r\n #'out': tf.Variable(tf.random_normal([n_classes]))} # n times 32 will be the b_fc, input dimension\r\n\r\n # NETWORK 1\r\n conv_layer_1 = tf.nn.relu(conv2d(x, weights['W_conv1']) + biases['b_conv1'])\r\n conv_max_pool_layer_1 = maxpool2d(conv_layer_1)\r\n\r\n conv_layer_2 = tf.nn.relu(conv2d(conv_max_pool_layer_1, weights['W_conv2']) + biases['b_conv2'])\r\n conv_max_pool_layer_2 = maxpool2d(conv_layer_2)\r\n\r\n conv_layer_3 = tf.nn.relu(conv2d(conv_max_pool_layer_2, weights['W_conv3']) + biases['b_conv3'])\r\n conv_max_pool_layer_3 = maxpool2d(conv_layer_3)\r\n\r\n conv_layer_4 = tf.nn.relu(conv2d(conv_max_pool_layer_3, weights['W_conv4']) + biases['b_conv4'])\r\n net_1 = maxpool2d(conv_layer_4)\r\n\r\n\r\n # Fully connected layer\r\n fc = tf.reshape(net_1, [-1, 14 * 32])\r\n fc = tf.tanh(tf.matmul(fc, weights['W_fc']) + biases['b_fc'])\r\n fc = tf.nn.dropout(fc, keep_rate)\r\n\r\n output = tf.matmul(fc, weights['out']) + biases['out']\r\n\r\n return output\r\n\r\nh_final = convolutional_neural_network(received_sig)\r\n\r\nssd = tf.reduce_sum(tf.square(transmitted_sig - h_final))\r\n\r\nglobal_step = tf.Variable(0, trainable=False)\r\nlearning_rate = tf.train.exponential_decay(startingLearningRate, global_step, decay_step_size, decay_factor,\r\n staircase=True)\r\ntrain_step = tf.train.AdamOptimizer(learning_rate).minimize(ssd)\r\n\r\n\r\nval = tf.reshape(transmitted_sig, tf.stack([user * batchSize]))\r\nval_2 = tf.reshape(transmitted_sig, [user * batch_size, 1])\r\nfinal_2 = tf.reshape(h_final, [user * batch_size, 1])\r\nfinal = tf.reshape(h_final, tf.stack([user * batchSize]))\r\nrounded = tf.sign(final)\r\neq = tf.equal(rounded, val)\r\neq2 = tf.reduce_sum(tf.cast(eq, tf.int32))\r\n\r\n\r\naccuracy = ssd\r\n\r\nsess.run(tf.global_variables_initializer())\r\n\"\"\"\r\ntraining phase og the network\r\n\"\"\"\r\nfor i in range(train_iter):\r\n batch_Y, batch_H, batch_HY, batch_HH, batch_X, SNR1, one_hot = generate_data_train(batch_size, user, antenna, low_snr_train, high_snr_train, H)\r\n #batch_Y, batch_H, batch_HY, batch_HH, batch_X, SNR1, one_hot = generate_data_train(B, K, N, low_snr_train, high_snr_train, H)\r\n if i % 100 == 0:\r\n correct_bits = eq2.eval(feed_dict={received_sig: batch_Y.reshape([-1, 1, antenna, 1]), transmitted_sig: batch_X, batchSize: batch_size})\r\n train_accuracy = accuracy.eval(feed_dict={received_sig: batch_Y.reshape([-1, 1, antenna, 1]), transmitted_sig: batch_X, batchSize: batch_size})\r\n val_3, final_3 = sess.run([val_2, final_2],feed_dict={received_sig: batch_Y.reshape([-1, 1, antenna, 1]), transmitted_sig: batch_X, batchSize: batch_size})\r\n eq3 = error_rate(val_3, final_3)\r\n print(\"step %d, loss is %g, number of correct bits %d\" % (i, train_accuracy, correct_bits))\r\n print('Error_', eq3)\r\n train_step.run(feed_dict={received_sig: batch_Y.reshape([-1, 1, antenna, 1]), transmitted_sig: batch_X, batchSize: batch_size})\r\n\r\n'''\r\nW_fc_second_last_final = weight_variable([fc_size, length_one_hot_vector * user])\r\nb_second_last_final = bias_variable([length_one_hot_vector * user])\r\nh_second_last_final = tf.matmul(conv_out, W_fc_second_last_final) + b_second_last_final\r\n\r\nh_final = tf.reshape(h_second_last_final, [batchSize, user, length_one_hot_vector])\r\n\r\nfinal_output = tf.nn.softmax(h_final, axis=2)\r\n\r\nloss = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits_v2(logits=final_output, labels=batch_x_one_hot))\r\nglobal_step = tf.Variable(0, trainable=False)\r\nlearning_rate = tf.train.exponential_decay(startingLearningRate, global_step, decay_step_size, decay_factor,\r\n staircase=True)\r\ntrain_step = tf.train.AdamOptimizer(learning_rate).minimize(loss)\r\n\r\ncom_received_transmitted_sig = tf.equal(tf.argmax(final_output, 2), tf.argmax(batch_x_one_hot, 2))\r\naccuracy = tf.reduce_sum(tf.cast(com_received_transmitted_sig, 'float')) / (user * batch_size)\r\n\r\n\r\nval = tf.reshape(transmitted_sig, tf.stack([user * batchSize]))\r\nval_2 = tf.reshape(transmitted_sig, [user * batch_size, 1])\r\n'''\r\n'''\r\nfinal_2 = tf.reshape(h_final, [user * batch_size, 1])\r\nfinal = tf.reshape(h_final, tf.stack([user * batchSize]))\r\nrounded = tf.sign(final)\r\neq = tf.equal(rounded, val)\r\neq2 = tf.reduce_sum(tf.cast(eq, tf.int32))\r\n'''\r\n\r\n\r\ncost_accumulated = []\r\naccuracy_accumulated = []\r\nsess.run(tf.global_variables_initializer())\r\n\r\n# train the network\r\n\r\nfor i in range(train_iter):\r\n batch_Y, batch_H, batch_HY, batch_HH, batch_X, SNR1, one_hot = generate_data_train(batch_size, user, antenna, low_snr_train, high_snr_train, H)\r\n _, c = sess.run([train_step, loss], feed_dict={received_sig: batch_Y.reshape([-1, 1, antenna, 1]), transmitted_sig: batch_X, batchSize: batch_size, batch_x_one_hot: one_hot})\r\n #_, c = sess.run([train_step, loss], feed_dict={received_sig: batch_Y, transmitted_sig: batch_X, batchSize: batch_size, batch_x_one_hot: one_hot})\r\n ac = sess.run([accuracy], feed_dict={received_sig: batch_Y.reshape([-1, 1, antenna, 1]), transmitted_sig: batch_X, batchSize: batch_size, batch_x_one_hot: one_hot})\r\n '''\r\n val_3, final_3 = sess.run([val_2, conv_out], feed_dict={received_sig: batch_Y.reshape([-1, 1, antenna, 1]), transmitted_sig: batch_X, batchSize: batch_size})\r\n eq3 = error_rate(val_3, final_3)\r\n print('Error_', eq3)\r\n '''\r\n if i % 100 == 0:\r\n print('Training teration', i, '| ', ' Accuracy:', ac[0],'| ' ' Loss:', c)\r\n cost_accumulated.extend([c])\r\n accuracy_accumulated.extend([ac])\r\n\r\n\r\n# test the network\r\nbers = np.zeros((1, num_snr))\r\ntmp_bers = np.zeros((1, test_iter))\r\ntmp_times = np.zeros((1, test_iter))\r\ntimes = np.zeros((1, 1))\r\ntest_accuracy_accumulated = []\r\n\r\nsnr_list_db = np.linspace(low_snr_db_test, high_snr_db_test, num_snr)\r\nsnr_list = 10.0 ** (snr_list_db / 10.0)\r\n\r\nfor i_snr in range(num_snr):\r\n cur_SNR = snr_list[i_snr]\r\n print('Current SNR', cur_SNR)\r\n for i in range(test_iter):\r\n batch_Y, batch_H, batch_HY, batch_HH, batch_X, SNR1, one_hot = generate_data_train(batch_size, user, antenna, low_snr_test, high_snr_test, H)\r\n tic = tm.time()\r\n test_ac = sess.run([accuracy], feed_dict={received_sig: batch_Y.reshape([-1, 1, antenna, 1]), transmitted_sig: batch_X, batchSize: batch_size, batch_x_one_hot: one_hot})\r\n tmp_bers[0][i] = test_ac[0]\r\n toc = tm.time()\r\n tmp_times[0][i] = toc - tic\r\n if i % 100 == 0:\r\n test_ac = sess.run([accuracy], feed_dict={received_sig: batch_Y, transmitted_sig: batch_X, batchSize: batch_size, batch_x_one_hot: one_hot})\r\n print(\"Test accuracy\", test_ac)\r\n\r\n bers[0][i_snr] = np.mean(tmp_bers[0])\r\n\r\nbers = 1 - bers\r\ntimes[0][0] = np.mean(tmp_times[0]) / batch_size\r\nsnrdb_list = np.linspace(low_snr_db_test, high_snr_db_test, num_snr)\r\n\r\nprint('Average time to detect a single K bit signal is:', times)\r\nprint('snrdb_list:', snrdb_list)\r\nprint('Bit error rates are is:', bers)\r\n\r\n'''\r\nplt.figure('Bit Error Rate')\r\nplt.subplot(111)\r\nplt.semilogy(snr_db_list, bers_mmse, color='black', marker='*', linestyle='-', linewidth=1, markersize=6, label='MMSE')\r\nplt.semilogy(snr_db_list, bers_zf, color='blue', marker='d', linestyle='-', linewidth=1, markersize=5, label='ZF')\r\nplt.semilogy(snr_db_list, bers_mf, color='red', marker='x', linestyle='-', linewidth=1, markersize=6, label='MF')\r\nplt.semilogy(snr_db_list, bers_sd, color='pink', marker='o', linestyle='-', linewidth=1, markersize=6, label='SD')\r\nplt.title('BER vs SNR')\r\nplt.xlabel('average SNR(dB) per receive antenna')\r\nplt.xlim(-2, 16)\r\nplt.xscale('linear')\r\nplt.ylabel('BER')\r\nplt.ylim(0.0001, 1)\r\nplt.grid(b=True, which='major', color='#666666', linestyle='--')\r\nplt.legend(title='Detectors:')\r\nplt.show()\r\n'''","sub_path":"CNN_2D_v1.3.1.py","file_name":"CNN_2D_v1.3.1.py","file_ext":"py","file_size_in_byte":14762,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"425030411","text":"import os\nimport shutil\n\nimport installPath\nimport source\nimport downloader\nimport extractor\nimport exporter\n\n\ntempZipFile = './temp.zip'\ntempFolder = './temp'\n\ndef cleanup():\n\tif os.path.exists(tempFolder):\n\t\tshutil.rmtree(tempFolder)\n\tif os.path.exists(tempZipFile):\n\t\tos.remove(tempZipFile)\n\n\nif __name__ == \"__main__\":\n\tcleanup()\n\tinstallPath = installPath.readInstallPath()\n\twhile True:\n\t\tweburl = source.promptSourceURL()\n\t\tprovider = source.parseProviderFromURL(weburl)\n\t\tid = source.parseIdFromURL(weburl)\n\t\tscrapeurl = source.generateScrapeURL(provider, id)\n\t\t\n\t\tdownloader.scrapeZipFile(scrapeurl, tempZipFile)\n\t\textractor.extractZip(tempZipFile, tempFolder)\n\t\texporter.exportFolderToBS(tempFolder, installPath, provider, id)\n\n\t\tcleanup()\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":749,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"367279146","text":"from sklearn import svm\nimport numpy as np\n\nx = np.array([[1, 0], [0, 1], [0, -1], [-1, 0], [0, 2], [0, -2], [-2, 0]])\ny = [-1, -1, -1, 1, 1, 1, 1]\n\nclf = svm.SVC(C=1e100, kernel='poly', degree=2, coef0=1,gamma=1)\nclf.fit(x, y)\n\nalpha = clf._dual_coef_\nsv = clf.support_vectors_\nb = clf.intercept_\nprint(alpha)\nprint(sv)\nprint(b)","sub_path":"hw1/QPsolver.py","file_name":"QPsolver.py","file_ext":"py","file_size_in_byte":329,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"188290694","text":"n=int(input())\ns=list(input())\nans=0\nfor i in range(n):\n r=set(s[:i])\n l=set(s[i:])\n cnt=0\n for j in r:\n if j in l:\n cnt+=1\n ans=max(ans,cnt)\nprint(ans)","sub_path":"abc/098/b.py","file_name":"b.py","file_ext":"py","file_size_in_byte":165,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}