/delete/', SubscriptionDestroyAPIView.as_view(), name='subscription-destroy'),\n\n] + router.urls\n","repo_name":"Dinnland/DRF_hw","sub_path":"course_app/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1457,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"}
+{"seq_id":"23155084526","text":"#-*- coding:utf-8 -*-\nimport pymongo\nfrom Tokyo_logistic_topo.Tokyo_logic import TokyoTopo,ITDKkml\nclient = pymongo.MongoClient()\niii=TokyoTopo()\ncol_edge1 = client['itdkall_info']['edge_location_degree']\ncol_edge2 = client['itdkall_info']['edge_static_short_250']\n\nnode11 = client['itdkall_info']['日本第二层的点']\n# node11.drop()\n# for edge in col_edge1.find():\n# flag = node11.find_one(edge['start'])\n# if not flag:\n# node11.insert_one(edge['start'])\n# flag = node11.find_one(edge['end'])\n# if not flag:\n# node11.insert_one(edge['end'])\n# for edge in col_edge2.find():\n# flag = node11.find_one(edge['start'])\n# if not flag:\n# node11.insert_one(edge['start'])\n# flag = node11.find_one(edge['end'])\n# if not flag:\n# node11.insert_one(edge['end'])\n# print(node11.count())\nfilename_KML = './日本筛选后未处理所有点.kml'\nf=open(filename_KML,'w')\npaint = ITDKkml(f)\n#paint.setting_line(line_hight_start=40000,line_hight_end=40000,line_width=5)\npaint.setting_point(icon_path='juanjo_Router.png',point_hight=80000,point_scale=0.5)\npaint.head()\nfor node in node11.find():\n paint.draw_orig_point(longitude=node['longitude'],latitude=node['latitude'])\npaint.tail()\nf.close()\n","repo_name":"DarkFunct/topoOfJapan","sub_path":"东京逻辑布局/测试/日本点.py","file_name":"日本点.py","file_ext":"py","file_size_in_byte":1252,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"}
+{"seq_id":"4340043794","text":"from torch import nn \nfrom torchvision import models \nimport warnings\nwarnings.filterwarnings(\"ignore\")\n\n\nclass ResNet(nn.Module):\n \"\"\"A PyTorch implementation of a ResNet model.\n \n This implementation uses a pre-trained ResNet-101 model and replaces the\n final fully-connected layer with a new linear layer with 12 output units.\n \n Args:\n nn (nn.Module): A PyTorch neural network module.\n \n Attributes:\n resnet (nn.Sequential): A PyTorch Sequential container for the \n pre-trained ResNet-101 model, with the final two layers removed.\n Linear (nn.Linear): A PyTorch linear layer with 100352 input units\n and 12 output units.\n \"\"\"\n def __init__(self):\n \"\"\"Initializes the ResNet model.\n \n Initializes the resnet attribute as a PyTorch Sequential container \n for the pre-trained ResNet-101 model, with the final two layers removed.\n Initializes the Linear attribute as a PyTorch linear layer with \n 100352 input units and 12 output units.\n \"\"\"\n super().__init__()\n self.resnet = nn.Sequential(*(list(models.resnet101(pretrained=True).children())[:-2]))\n self.Linear = nn.Linear(in_features=100352, out_features=12)\n \n def forward(self, X):\n \"\"\"Forward pass of the ResNet model.\n \n Args:\n X (torch.Tensor): A batch of input data with shape \n (batch_size, num_channels, height, width).\n \n Returns:\n torch.Tensor: A batch of model output with shape \n (batch_size, num_outputs).\n \"\"\"\n X = self.resnet(X)\n X = X.view(X.shape[0], -1 )\n X = self.Linear(X)\n return X\n \n","repo_name":"bhydemi/Planting-Seedling-Classification-Project","sub_path":"plant_seedling_modular_version/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":1735,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"21"}
+{"seq_id":"25068306764","text":"#Vulnerable Code\nfrom flask import Flask, request, escape\n\napp = Flask(__name__)\n\n@app.route('/unsafe')\ndef unsafe():\n name = request.args.get('name')\n return f'Hello {name}, Welcome to Hackmansec'\n\n@app.route('/safe')\ndef safe():\n name = escape(request.args.get('name'))\n return f'Hello {name}, Welcome to Hackmansec'\n\nif __name__ == '__main__':\n app.run()\n\n","repo_name":"appsecmani/xss-challenges","sub_path":"xss.py","file_name":"xss.py","file_ext":"py","file_size_in_byte":374,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"}
+{"seq_id":"31078912793","text":"import json\njson_file_path = './test.json'\njson_data = {}\nwith open(json_file_path, 'r') as json_file:\n json_data = json.load(json_file)\n \nfor i in range(2, 9):\n print(i)\n\nprint(json_data)\njson_data['climing_list'] = []\n\njson_list = ['store_name', 'naver_category', 'address', 'naver_map_url', 'main_img_url', 'price_list', 'open_time', 'level', 'change_time']\n\nstore_name = 'test1'\nnaver_category = 'test2'\naddress = 'test3'\nnaver_map_url = 'test4'\nmain_img_url = 'test5'\nprice_list = 'test6'\nopen_time = 'test7'\nlevel = 'test8'\nchange_time = 'test9'\n\nvar_list = [store_name, naver_category, address, naver_map_url, main_img_url, price_list, open_time, level, change_time]\n\n\n# for i in range(len(json_list)):\n# json_data['climing_list'].append({json_list[i]: var_list[i]})\n\nstore_name = '100'\nnaver_category = '100'\naddress = '100'\nnaver_map_url = '100'\nmain_img_url = '100'\nprice_list = '100'\nopen_time = '100'\nlevel = '100'\nchange_time = '100'\n\ncliming_info = {'store_name': store_name, 'naver_category': naver_category, 'address': address, 'naver_map_url': naver_map_url, 'main_img_url': main_img_url, 'price_list': price_list, 'open_time': open_time, 'level': level, 'change_time': change_time}\ncliming_info2 = {'store_name': '123', 'naver_category': 'naver_category', 'address': 'address', 'naver_map_url': 'naver_map_url', 'main_img_url': 'main_img_url', 'price_list': 'price_list', 'open_time': open_time, 'level': level, 'change_time': change_time}\n\njson_data['climing_list'].append(climing_info)\njson_data['climing_list'].append(climing_info2)\n\nwith open('test.json', 'w') as f:\n json.dump(json_data, f, indent=4)","repo_name":"cowFarmer/with_wall_dev","sub_path":"center_list_crawling/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":1639,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"}
+{"seq_id":"13889083626","text":"from __future__ import division\nimport numpy as np\nimport cv2\nimport matplotlib.pyplot as plt\nimport os, os.path\nimport pandas as pd\nimport csv\nimport pickle\n\ndef chaincode(gray):\n count0 = 0\n count1 = 0\n count2 = 0\n count3 = 0\n count4 = 0\n count5 = 0\n count6 = 0\n count7 = 0\n\n img = cv2.threshold(gray, 127, 255, cv2.THRESH_BINARY)[1]\n element = cv2.getStructuringElement(cv2.MORPH_ELLIPSE,(3,3))\n done = False\n\n img =cv2.bitwise_not(img)\n original = img\n img = cv2.threshold(img, 127,255, cv2.THRESH_BINARY)[1]\n ############## Discover the first point#################################\n for i, row in enumerate(img):\n for j, value in enumerate(row):\n if value == 255:\n start_point = (i, j)\n #print(start_point, value)\n break\n else:\n continue\n break\n ###################Chain code algorithm ##########################\n directions = [0, 1, 2,\n 7, 3,\n 6, 5, 4]\n dir2idx = dict(zip(directions, range(len(directions))))\n\n change_j = [-1, 0, 1, # x or columns\n -1, 1,\n -1, 0, 1]\n\n change_i = [-1, -1, -1, # y or rows\n 0, 0,\n 1, 1, 1]\n\n border = []\n #chain = []\n chain = []\n curr_point = start_point\n for direction in directions:\n idx = dir2idx[direction]\n new_point = (start_point[0] + change_i[idx], start_point[1] + change_j[idx])\n if img[new_point] != 0: # if is ROI\n border.append(new_point)\n chain.append(direction)\n curr_point = new_point\n break\n count = 0\n\n while curr_point != start_point:\n # figure direction to start search\n b_direction = (direction + 5) % 8\n dirs_1 = range(b_direction, 8)\n dirs_2 = range(0, b_direction)\n dirs = []\n dirs.extend(dirs_1)\n dirs.extend(dirs_2)\n for direction in dirs:\n idx = dir2idx[direction]\n new_point = (curr_point[0] + change_i[idx], curr_point[1] + change_j[idx])\n # print(\"new\", new_point)\n try:\n if img[new_point] != 0: # if is ROI\n border.append(new_point)\n chain.append(direction)\n curr_point = new_point\n break\n except:\n continue\n\n if count == 20000: break\n count += 1\n\n # Getting length of list\n length = len(chain)\n# print(chain)\n i = 0\n\n # Iterating using while loop\n while i < length:\n # print(chain[i])\n if (chain[i] == 0):\n count0 = count0 + 1\n if (chain[i] == 1):\n count1 = count1 + 1\n if (chain[i] == 2):\n count2 = count2 + 1\n if (chain[i] == 3):\n count3 = count3 + 1\n if (chain[i] == 4):\n count4 = count4 + 1\n if (chain[i] == 5):\n count5 = count5 + 1\n if (chain[i] == 6):\n count6 = count6 + 1\n if (chain[i] == 7):\n count7 = count7 + 1\n i += 1\n sum = count0 + count1 + count2 + count3 + count4 + count5 + count6 + count7\n\n Avg0 = round((count0 / sum) * 100, 2)\n Avg1 = round((count1 / sum) * 100, 2)\n Avg2 = round((count2 / sum) * 100, 2)\n Avg3 = round((count3 / sum) * 100, 2)\n Avg4 = round((count4 / sum) * 100, 2)\n Avg5 = round((count5 / sum) * 100, 2)\n Avg6 = round((count6 / sum) * 100, 2)\n Avg7 = round((count7 / sum) * 100, 2)\n\n chain_output = [ Avg0 , Avg1 , Avg2 , Avg3, Avg4, Avg5, Avg6, Avg7]\n return chain_output\n\n sum = count0 + count1 + count2 + count3 + count4 + count5 + count6 + count7\n Sum_Avg = Avg0 + Avg1 + Avg2 + Avg3 + Avg4 + Avg5 + Avg6 + Avg7\n\n\ndef distance_profile(img):\n\n gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)\n (_, thresh) = cv2.threshold(gray, 170, 255, cv2.THRESH_BINARY)\n\n height, width = thresh.shape[:2]\n# print(height, width)\n tb = list()\n count1 = 0\n count2 = 0\n count3 = 0\n count4 = 0\n arr1 = []\n arr2 = []\n arr3 = []\n arr4 = []\n\n # print(\"left to right\")\n for y in range(0, height):\n for x in range(0, width):\n cp = thresh[y, x]\n if cp == 255:\n count1 += 1\n else:\n break\n \n arr1.append(count1)\n count1 = 0\n\n # print(\"right to left\")\n for y in range(0, height):\n for x in range(width - 1, 0, -1):\n cp = thresh[y, x]\n if cp == 255:\n count2 += 1\n else:\n break\n arr2.append(count2)\n count2 = 0\n\n # print(\"top to bottom\")\n for x in range(0, width):\n for y in range(0, height):\n cp = thresh[y, x]\n if cp == 255:\n count3 += 1\n else:\n break\n # print(count3)\n arr3.append(count3)\n count3 = 0\n # print(arr3)\n\n# print(\"bottom to top\")\n for x in range(0, width):\n for y in range(height - 1, 0, -1):\n cp = thresh[y, x]\n if cp == 255:\n count4 += 1\n else:\n break\n # print(count4)\n arr4.append(count4)\n count4 = 0\n# print(arr4)\n\n distance_output = [arr1, arr2, arr3, arr4]\n #print(distance_output)\n return distance_output\n plt.subplot(332), plt.imshow(img)\n plt.subplot(323), plt.plot(arr1), plt.title('left to right')\n plt.subplot(324), plt.plot(arr2), plt.title('Right to left')\n plt.subplot(325), plt.plot(arr3), plt.title('top to bottom')\n plt.subplot(326), plt.plot(arr4), plt.title('bottom to top')\n\n plt.show()\n\n\ndef density_features(img):\n #(_, img) = cv2.threshold(gray, 170, 255, cv2.THRESH_BINARY)\n countW = 0\n countB = 0\n ratio = 0\n windowCount = 0\n pixelCount = 0\n resultArray = np.array([])\n\n # window size\n windowsize_rows = 127\n windowsize_columns = 127\n pixel = []\n ratioA = []\n\n for r in range(0, img.shape[0] - windowsize_rows +1 , windowsize_rows):\n for c in range(0, img.shape[1] - windowsize_columns +1 , windowsize_columns):\n window = img[r:r + windowsize_rows, c:c + windowsize_columns]\n windowCount = windowCount + 1\n # print(\"Zone:\", windowCount)\n for i in range(window.shape[0]):\n for j in range(window.shape[1]):\n if (window[i][j] == 0).all():\n countB = countB + 1\n if (window[i][j] == 255).all():\n countW = countW + 1\n ratio = countB / (128 * 128)\n ratio = str(round(ratio, 4))\n pixel.append(countB)\n ratioA.append(ratio)\n\n\n countW = 0\n countB = 0\n ratio = 0\n \n # print(\"-----------------------Zone End------------------------\\n\")\n\n n_white_pix = np.sum(img == 255)\n# print(\"Total white pixels\", n_white_pix)\n n_black_pix = np.sum(img == 0)\n # print(\"Total black pixels\", n_black_pix)\n # print(\"foreground pixel density of zones:\", ratioA, \"\\n\")\n\n upperDivision = 0\n lowerDivision = 0\n leftDivision = 0\n rightDivision = 0\n verticalDiff = 0\n horizontalDiff = 0\n ratioA = list(map(float, ratioA))\n # upper division total pixels\n for u in range(0, 7):\n upperDivision = round(upperDivision + ratioA[u], 4)\n# print(\"upperDivision\", upperDivision)\n\n # lower division total pixels\n for l in range(8, 15):\n lowerDivision = round(lowerDivision + ratioA[l], 4)\n # print(\"lowerDivision\", lowerDivision)\n\n # left division total density\n leftDivision = round(\n ratioA[0] + ratioA[1] + ratioA[4] + ratioA[5] + ratioA[8] + ratioA[9] + ratioA[12] + ratioA[13], 4)\n # print(\"leftDivision\", leftDivision)\n\n # left division total denisty\n rightDivision = round(\n ratioA[2] + ratioA[3] + ratioA[6] + ratioA[7] + ratioA[10] + ratioA[11] + ratioA[14] + ratioA[15], 4)\n# print(\"lowerDivision\", rightDivision, \"\\n\")\n\n # Vertical density diffrence\n verticalDiff = round(upperDivision - lowerDivision, 4)\n# print(\"Vertical pixel diff:\", verticalDiff)\n\n # Horizontal density diffrence\n horizontalDiff = round(leftDivision - rightDivision, 4)\n# print(\"Horizontal pixel diff:\", horizontalDiff, \"\\n\")\n\n # get 8 zones\n eightZones = []\n\n zone1 = round(ratioA[0] + ratioA[1], 4)\n eightZones.append(zone1)\n# print(\"zone1:\", zone1)\n\n zone2 = round(ratioA[2] + ratioA[3], 4)\n eightZones.append(zone2)\n# print(\"zone2:\", zone2)\n\n zone3 = round(ratioA[4] + ratioA[5], 4)\n eightZones.append(zone3)\n # print(\"zone3:\", zone3)\n\n zone4 = round(ratioA[6] + ratioA[7], 4)\n eightZones.append(zone4)\n# print(\"zone4:\", zone4)\n\n zone5 = round(ratioA[8] + ratioA[9], 4)\n eightZones.append(zone5)\n# print(\"zone5:\", zone5)\n\n zone6 = round(ratioA[10] + ratioA[11], 4)\n eightZones.append(zone6)\n# print(\"zone6:\", zone6)\n\n zone7 = round(ratioA[12] + ratioA[13], 4)\n eightZones.append(zone7)\n# print(\"zone7:\", zone7)\n\n zone8 = round(ratioA[14] + ratioA[15], 4)\n eightZones.append(zone8)\n# print(\"zone8:\", zone8, \"\\n\")\n\n # add density features to vector\n #print(ratioA)\n resultArray = eightZones + ratioA\n resultArray.append(verticalDiff)\n resultArray.append(horizontalDiff)\n\n return resultArray\n\ndef main():\n # image path and valid extensions\n imageDir = \"D:/FYP/dataset/Segmented_essay_2\" # specify your path here\n image_path_list = []\n valid_image_extensions = [\".jpg\", \".jpeg\", \".png\", \".tif\", \".tiff\" , \".bmp\"] # specify your valid extensions here\n valid_image_extensions = [item.lower() for item in valid_image_extensions]\n\n for file in os.listdir(imageDir):\n extension = os.path.splitext(file)[1]\n if extension.lower() not in valid_image_extensions:\n continue\n image_path_list.append(os.path.join(imageDir, file))\n\n for imagePath in image_path_list:\n image = cv2.imread(imagePath)\n img = cv2.imread(imagePath)\n if img is None:\n print(\"Error loading: \" + imagePath)\n # end this loop iteration and move on to next image\n continue\n elif img is not None:\n cv2.imshow(imagePath, img)\n\n cv2.destroyAllWindows()\n #img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)\n gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)\n # wait time in milliseconds\n # this is required to show the image\n # 0 = wait indefinitely\n # exit when escape key is pressed\n key = cv2.waitKey(0)\n if key == 27: # escape\n break\n\n size = np.size(gray)\n skel = np.zeros(gray.shape,np.uint8)\n #ret,img = cv2.threshold(img,127,255,0)\n element = cv2.getStructuringElement(cv2.MORPH_ELLIPSE,(3,3))\n done = False\n\n height = width = 512\n dim = (height, width)\n img_new = cv2.resize(image, dim, interpolation=cv2.INTER_CUBIC)\n (thresh, img_new) = cv2.threshold(img_new, 128, 255, cv2.THRESH_BINARY)\n\n #method chaincode passing the image\n chain_output = chaincode(gray)\n #print(chain_output)\n distance_output = distance_profile(img)\n\n resultArray = density_features(img_new)\n dis = []\n # length = len(df)\n # # print(length)\n # for i in range(0, length):\n # # print(i)\n arr = np.array(distance_output[0] + distance_output[1] + distance_output[2]+distance_output[3])\n #arr = np.append(resultArray)\n arr = np.append(arr, resultArray)\n #print(arr)\n arr = np.append(arr,chain_output[0])\n arr = np.append(arr, chain_output[1])\n arr = np.append(arr, chain_output[2])\n arr = np.append(arr, chain_output[3])\n arr = np.append(arr, chain_output[4])\n arr = np.append(arr, chain_output[5])\n arr = np.append(arr, chain_output[6])\n arr = np.append(arr, chain_output[7])\n dis.append(arr)\n \n filename = 'NEW_DATA_FINAL_ALL_4.sav'\n loaded_model = pickle.load(open(filename, 'rb'))\n\n y_pred = loaded_model.predict(dis)\n print(y_pred)\n\n\nif __name__=='__main__':\n main()","repo_name":"BD-MF/Image-Processing-and-ML-approach-to-Sinhala-Handwritten-Character-Recognition-","sub_path":"Recognition_Module.py","file_name":"Recognition_Module.py","file_ext":"py","file_size_in_byte":12382,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"21"}
+{"seq_id":"33786776993","text":"#!/usr/bin/env python\n# encoding: utf-8\n\nimport sys\nimport logging\nimport numpy as np\nimport argparse as ap\n\nfrom glob import glob\nfrom os import path as p\nfrom LibThese import Data as d\nfrom InitialCond import Gadget as g\n\n\nclass Analyse(object):\n def __init__(self, hdf, gadget, RSelect=10., substract=True):\n # We are getting the information about the density center:\n hdf5 = d.Data(hdf)\n\n p_cg = hdf5.get(p.basename(gadget), \"timeparam\", \"x\", \"y\", \"z\")\n v_cg = hdf5.get(p.basename(gadget), \"timeparam\", \"vx\", \"vy\", \"vz\")\n\n self._time = hdf5.get(p.basename(gadget), \"timeparam\", \"time\")[0, 0]\n\n fof = hdf5.get(p.basename(gadget), \"ids\")[:, 0]\n\n # We read the Gadget file:\n _name = gadget\n gadget = g.Gadget(gadget)\n gadget._read_format1(1)\n # gadget.Part.SortById()\n\n logging.debug(\"Removing %g from %s\" % (gadget.BoxSize / 2., _name))\n\n pos = gadget.Part.NumpyPositions.copy() - np.array([gadget.BoxSize/2.]*3)\n vel = gadget.Part.NumpyVelocities.copy()\n ide = gadget.Part.NumpyIdentities\n\n tmp_r = np.sum(pos**2, axis=1)\n id_p_sort1 = np.argsort(tmp_r)\n id_p_sort1 = id_p_sort1[ tmp_r[id_p_sort1] <= RSelect ** 2. ]\n\n pos = pos[id_p_sort1]\n vel = vel[id_p_sort1]\n ide = ide[id_p_sort1]\n\n id_p_sort1 = np.argsort(ide)\n id_p_sort1 = id_p_sort1[fof]\n\n pos = pos[id_p_sort1]\n vel = vel[id_p_sort1]\n ide = ide[id_p_sort1]\n\n if substract:\n # We are correcting our center of position and velocities:\n self._p = pos - p_cg\n self._v = vel - v_cg\n # self._p = gadget.Part.NumpyPositions.copy()[fof, :] - np.array([gadget.BoxSize/2.]*3) - p_cg\n # self._v = gadget.Part.NumpyVelocities.copy()[fof, :] - v_cg\n else:\n self._p = pos\n self._v = vel\n # self._p = gadget.Part.NumpyPositions.copy()[fof, :] - np.array([gadget.BoxSize/2.]*3)\n # self._v = gadget.Part.NumpyVelocities.copy()[fof, :]\n\n gadget.Part.Release()\n del gadget, hdf5\n\n def get_r2(self):\n return np.sum(self.pos[:]**2, axis=1)\n\n def get_v2(self):\n return np.sum(self.vel[:]**2, axis=1)\n\n def get_vr(self):\n return np.sum(self.pos * self.vel, axis=1) / np.sqrt( self.get_r2() )\n\n @property\n def time(self):\n return self._time\n\n @property\n def pos(self):\n return self._p\n @pos.setter\n def pos(self, val):\n self._p = val\n\n @property\n def vel(self):\n return self._v\n @vel.setter\n def vel(self, val):\n self._v = val\n\n\nclass Object(object):\n def __init__(self, file, center, time=None, ids=None, substract=True):\n p_cg = center[:3]\n v_cg = center[3:]\n\n # We read the Gadget file:\n gadget = g.Gadget(file)\n gadget._read_format1(1)\n\n if time is not None:\n self._time = time\n else:\n self._time = gadget.time\n\n if substract:\n # We are correcting our center of position and velocities:\n self._p = gadget.Part.NumpyPositions.copy()[ids, :] - p_cg\n self._v = gadget.Part.NumpyVelocities.copy()[ids, :] - v_cg\n else:\n self._p = gadget.Part.NumpyPositions.copy()[ids, :]\n self._v = gadget.Part.NumpyVelocities.copy()[ids, :]\n\n gadget.Part.Release()\n del gadget\n\n def get_r2(self):\n return np.sum(self.pos[:]**2, axis=1)\n\n def get_v2(self):\n return np.sum(self.vel[:]**2, axis=1)\n\n def get_vr(self):\n return np.sum(self.pos * self.vel, axis=1) / np.sqrt( self.get_r2() )\n\n @property\n def time(self):\n return self._time\n\n @property\n def pos(self):\n return self._p\n @pos.setter\n def pos(self, val):\n self._p = val\n\n @property\n def vel(self):\n return self._v\n @vel.setter\n def vel(self, val):\n self._v = val\n\n\ndef CreateArgument():\n parser = ap.ArgumentParser(\n formatter_class=ap.ArgumentDefaultsHelpFormatter,\n )\n\n parser.add_argument(\n \"Gadget\",\n nargs='+',\n help=\"Gadget files to analyze.\",\n )\n\n parser.add_argument(\n \"--hdf5\",\n help=\"HDF5 files to use to get needed information.\",\n default=glob(\"Data/*.hdf5\")[-1],\n )\n\n parser.add_argument(\n \"-o\",\n \"--out\",\n type=ap.FileType(\"w\"),\n default=sys.stdout,\n )\n\n parser.add_argument(\n \"--RSelect\",\n default=10.,\n type=float,\n help=\"Maximal radius to consider.\"\n )\n\n parser.add_argument(\n \"--not-remove-dc\",\n action=\"store_false\",\n help=\"Substract density center information.\"\n )\n\n parser.add_argument(\n \"--log\",\n type=str,\n default=\"INFO\",\n help=\"Log level.\"\n )\n\n parser.add_argument(\n \"--save-txt\",\n action=\"store_true\",\n help=\"Saving in files all working particles.\"\n )\n\n args = parser.parse_args()\n args.log = getattr(logging, args.log.upper())\n\n return args\n\ndef GatherData(hdf5_file, *files):\n hdf5 = d.Data(hdf5_file)\n data = dict()\n\n for f in files:\n name = p.basename(f)\n\n data[name] = (\n hdf5.get(name, \"timeparam\", \"x\", \"y\", \"z\", \"vx\", \"vy\", \"vz\")[0],\n hdf5.get(name, \"timeparam\", \"time\")[0, 0],\n hdf5.get(name, \"ids\")[:, 0],\n f,\n )\n\n return data\n\ndef CalculateAnisotropy(center, time, ids, data, substract=True):\n calc = Object(data, center, time, ids, substract)\n\n v_r2 = calc.get_vr() ** 2\n v_t2 = calc.get_v2() - v_r2\n\n res = (calc.time, 1 - v_t2.sum() / (2.*v_r2.sum()))\n\n del calc\n return res\n\n\nif __name__ == '__main__':\n args = CreateArgument()\n logging.basicConfig(level=logging.DEBUG)\n\n centers = GatherData(args.hdf5, *args.Gadget)\n\n for f in args.Gadget:\n calc = Analyse(args.hdf5, f, RSelect=args.RSelect) #, substract=args.not_remove_dc)\n v_r2 = calc.get_vr() ** 2\n v_t2 = calc.get_v2() - v_r2\n\n logging.info(\"Doing \" + f)\n logging.debug(\"{0}\".format(calc.pos.shape))\n if args.save_txt:\n np.savetxt(\"/tmp/\" + p.basename(f) + \"2.pos\", calc.pos)\n np.savetxt(\"/tmp/\" + p.basename(f) + \"2.vel\", calc.vel)\n\n print(\n calc.time,\n 1 - v_t2.mean() / (2.*v_r2.mean()),\n # *CalculateAnisotropy(*centers[p.basename(f)], substract=args.not_remove_dc),\n file=args.out\n )\n del calc\n\n","repo_name":"ElricleNecro/LibThese","sub_path":"scripts/verif_python.py","file_name":"verif_python.py","file_ext":"py","file_size_in_byte":6721,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"}
+{"seq_id":"8472655825","text":"import pyttsx3\nimport speech_recognition as sr\nengine = pyttsx3.init('sapi5')\nvoices = engine.getProperty('voices')\n# print(voices)\nengine.setProperty('voice', voices[0].id)\n\ndef speak(audio):\n engine.say(audio)\n engine.runAndWait()\n\n# def wishMe():\n# speak(\"Hello , Sir\")\n\n# wishMe\ndef takeCommand():\n # It takes microphone input from the user and return string output\n r= sr.Recognizer()\n with sr.Microphone() as source:\n print(\"Listening....\")\n r.pause_threshold = 1\n audio = r.listen(source)\n\nt= takeCommand()\nprint(audio())","repo_name":"rajan675/Python","sub_path":"Jarvis_Python_project/speech_to_text.py","file_name":"speech_to_text.py","file_ext":"py","file_size_in_byte":568,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"}
+{"seq_id":"72793830132","text":"import os\nimport sys\nimport numpy as np\nimport pandas as pd\nimport spacy\nimport pretty_midi\nimport json\nimport tensorflow as tf\nfrom keras.layers import LSTM, Dense, concatenate, Input, Embedding, Dropout\nfrom keras.models import Model, load_model\nfrom keras.losses import CategoricalCrossentropy\nfrom keras.callbacks import ModelCheckpoint\nfrom keras.layers.core import Reshape\nfrom numpy.random import choice\n\n\ndef get_midis_and_texts(instances, dataset_dir, instrument_indexes, set):\n \"\"\"\n Extract the midis and texts from the train or test set files\n :param instances: dataframe with the song names and lyrics\n :param dataset_dir: directory of the dataset\n :param instrument_indexes: dict to be updated during this function as new instruments are encountered\n :param set: string = \"train\" or \"test\" that indicates what set to extract\n :return: [raw midis in set, lyrics for all songs in set]\n \"\"\"\n cache_path = '%s/texts_%s.json' % (cache_dir, set)\n if not os.path.exists(cache_path): # if cache doesn't exist\n midis = []\n texts = []\n failed_num = 0\n for index, row in instances.iterrows():\n artist = row[0].strip().replace(' ', '_')\n song_name = row[1].strip().replace(' ', '_')\n filename = '%s_-_%s.mid' % (artist, song_name)\n failed_text = '\\t'\n try:\n midi = pretty_midi.PrettyMIDI('%s/midi_files/%s' % (dataset_dir, filename))\n for instrument in midi.instruments:\n instrument_id = instrument.program\n if instrument_id not in instrument_indexes:\n instrument_indexes[instrument_id] = len(instrument_indexes)\n midis.append(midi)\n texts.append(row[2])\n except: # if midi is not readable\n failed_text = ' FAILED'\n failed_num += 1\n print('%d/%d%s\\t%s' % (index + 1, len(instances), failed_text, filename))\n print('FAILED = %d/%d' % (failed_num, len(instances)))\n with open(cache_path, 'w') as file:\n json.dump(texts, file)\n else:\n with open(cache_path, 'r') as file:\n texts = json.load(file)\n midis = None\n return midis, texts\n\n\ndef get_vocabulary_and_word_embeddings(texts_train, texts_test, nlp):\n \"\"\"\n Process the texts to get the word embeddings and vocabulary of the whole dataset\n :param texts_train: lyrics of the train set\n :param texts_test: lyrics of the test set\n :param nlp: the Spacy model\n :return: [dict where word->index, np.array where index->word embedding, np.array where index->word]\n \"\"\"\n if not os.path.exists('%s/word_indexes.json' % cache_dir): # if cache doesn't exist\n word_indexes = {}\n vocabulary, word_embeddings = [], []\n for texts in [texts_train, texts_test]:\n for text in texts:\n tokens = nlp(text.strip())\n for token in tokens:\n word = token.text\n if word not in vocabulary:\n word_indexes[word] = len(word_indexes)\n vocabulary.append(word)\n word_embeddings.append(token.vector.tolist())\n for file_name in ['word_indexes', 'word_embeddings', 'vocabulary']:\n with open('%s/%s.json' % (cache_dir, file_name), 'w') as file:\n json.dump(eval(file_name), file)\n else:\n structures = []\n for file_name in ['word_indexes', 'word_embeddings', 'vocabulary']:\n with open('%s/%s.json' % (cache_dir, file_name), 'r') as file:\n structures.append(json.load(file))\n word_indexes, word_embeddings, vocabulary = structures\n return word_indexes, np.array(word_embeddings), np.array(vocabulary)\n\n\ndef get_midi_embeddings():\n \"\"\"\n Extract the embedding vectors of the whole and slices midis\n :return: [np.array index->midi embedding, np.array midi_sliced_embeddings index->slice embedding,\n \"list where each entry i is a list with the slice indexes for midi i in train set\", \"same for test set\"]\n \"\"\"\n if not os.path.exists('%s/midi_embeddings.json' % cache_dir): # if cache doesn't exist\n print('train:')\n midi_vectors_train, midi_vectors_sliced_train, slice_indexes_train = get_midi_vectors(\n midis_train, instrument_indexes, texts_train)\n print('test:')\n midi_vectors_test, midi_vectors_sliced_test, slice_indexes_test = get_midi_vectors(\n midis_test, instrument_indexes, texts_test, init_slice_index=slice_indexes_train[-1][-1] + 1)\n midi_embeddings = midi_vectors_train + midi_vectors_test\n midi_sliced_embeddings = midi_vectors_sliced_train + midi_vectors_sliced_test\n\n for file_name in ['midi_embeddings', 'midi_sliced_embeddings', 'slice_indexes_train', 'slice_indexes_test']:\n with open('%s/%s.json' % (cache_dir, file_name), 'w') as file:\n json.dump(eval(file_name), file)\n else:\n structures = []\n for file_name in ['midi_embeddings', 'midi_sliced_embeddings', 'slice_indexes_train', 'slice_indexes_test']:\n with open('%s/%s.json' % (cache_dir, file_name), 'r') as file:\n structures.append(json.load(file))\n midi_embeddings, midi_sliced_embeddings, slice_indexes_train, slice_indexes_test = structures\n return np.array(midi_embeddings), np.array(midi_sliced_embeddings), slice_indexes_train, slice_indexes_test\n\n\ndef get_midi_vectors(midis, instrument_indexes, texts, init_slice_index=0):\n \"\"\"\n Extract the embedding vectors of the whole and slices midis in the train or test set\n :param midis: of train or test set\n :param instrument_indexes: computed by the method \"get_midis_and_texts\"\n :param texts: lyrics of the train or test set\n :param init_slice_index: initial slice index – only if sending test set will not be zero\n :return: [np.array of midi embeddings, np.array of midi slice embedding, slice_indexes as in get_midi_embeddings]\n \"\"\"\n num_phrases_by_song = [text.count('&') for text in texts]\n midi_vectors = []\n midi_vectors_sliced = []\n slice_indexes = [] # index of midi slice embeddings\n for i, midi in enumerate(midis):\n print('%d/%d' % (i + 1, len(midis)))\n midi_tempo = midi.estimate_tempo()\n midi_chroma = midi.get_chroma()\n instruments_presence = get_slice_instruments_presence(midi, 1, midi.get_end_time(), instrument_indexes)[0]\n total_velocity = sum(sum(midi_chroma))\n midi_semitones = [sum(semitone) / total_velocity for semitone in midi_chroma]\n midi_vector = [midi_tempo] + instruments_presence + midi_semitones\n midi_vectors.append(midi_vector)\n for midi_vector_slice in get_midi_vector_slices(midi, num_phrases_by_song[i], instrument_indexes):\n midi_vectors_sliced.append(midi_vector_slice)\n if i == 0:\n slice_indexes.append(list(range(num_phrases_by_song[i] + init_slice_index)))\n else:\n next_index = slice_indexes[-1][-1] + 1\n slice_indexes.append(list(range(next_index, next_index + num_phrases_by_song[i])))\n return midi_vectors, midi_vectors_sliced, slice_indexes\n\n\ndef get_midi_vector_slices(midi, num_slices, instrument_indexes):\n \"\"\"\n Extract slice embedding vectors for a midi file\n :param midi: raw midi to be sliced\n :param num_slices: number of equal length slices to split the midi into\n :param instrument_indexes: computed by the method \"get_midis_and_texts\"\n :return: np.array with embeddings of the midi slices\n \"\"\"\n midi_end_time = midi.get_end_time()\n slice_len = midi_end_time / num_slices\n slice_starts = [i * slice_len for i in range(num_slices)]\n slice_ends = slice_starts[1:] + [midi_end_time]\n\n slice_tempos = get_slice_tempos(midi, slice_starts, slice_ends, midi_end_time)\n slice_semitones = get_slice_semitones(midi, num_slices)\n slice_instruments_presence = get_slice_instruments_presence(midi, num_slices, midi_end_time, instrument_indexes)\n\n midi_vector_slices = []\n for i in range(num_slices):\n midi_vector_slice = [slice_tempos[i]] + slice_instruments_presence[i] + slice_semitones[i]\n midi_vector_slices.append(midi_vector_slice)\n return midi_vector_slices\n\n\ndef get_slice_tempos(midi, slice_starts, slice_ends, midi_end_time):\n \"\"\"\n Compute average tempo in each slice, weighted by the amount of time each tempo occurs in the slice\n :param midi: to slice\n :param slice_starts: start times of slices\n :param slice_ends: end times of slices\n :param midi_end_time: time where midi ends\n :return: weighted average of tempos in each slice\n \"\"\"\n tempo_starts, tempos = midi.get_tempo_changes()\n tempo_starts, tempos = list(tempo_starts), list(tempos)\n tempo_ends = tempo_starts[1:] + [midi_end_time] # for weighted average of tempos inside same slice\n slice_tempos = [[] for i in range(len(slice_starts))] # tempos in each slice\n slice_tempo_lens = [[] for i in range(len(slice_starts))] # len of tempos in each slice\n slice_id = 0\n for tempo_start, tempo_end, tempo in zip(tempo_starts, tempo_ends, tempos):\n while slice_ends[slice_id] < tempo_end: # next change is outside of slice\n slice_tempos[slice_id].append(tempo)\n slice_tempo_start = max(slice_starts[slice_id], tempo_start)\n slice_tempo_lens[slice_id].append(slice_ends[slice_id] - slice_tempo_start)\n slice_id += 1\n slice_tempos[slice_id].append(tempo)\n slice_tempo_start = max(slice_starts[slice_id], tempo_start)\n slice_tempo_lens[slice_id].append(tempo_end - slice_tempo_start)\n return [np.average(i, weights=j) for i, j in zip(slice_tempos, slice_tempo_lens)]\n\n\ndef get_slice_semitones(midi, num_slices):\n \"\"\"\n Compute average of each one of the 12 semitones in each midi\n :param midi: to slice\n :param num_slices: to split the midi into\n :return: a list with the average semitones (np.array of size 12) for each slice\n \"\"\"\n slices_chromas = np.array_split(midi.get_chroma(), num_slices, axis=1)\n slice_semitones = []\n for slice_chroma in slices_chromas:\n slice_velocity = sum(sum(slice_chroma))\n if slice_velocity == 0:\n slice_semitones.append([0] * len(slice_chroma))\n else:\n slice_semitones.append([sum(semitone) / slice_velocity for semitone in slice_chroma])\n return slice_semitones\n\n\ndef get_slice_instruments_presence(midi, num_slices, midi_end_time, instrument_indexes):\n \"\"\"\n Compute the relative amount of time each instrument sounds relative to the others\n :param midi: to slice\n :param num_slices: to split the midi into\n :param midi_end_time: time where midi ends\n :param instrument_indexes: computed by the method \"get_midis_and_texts\"\n :return: array where each entry is a list of size num_instruments with relative instrument presence in each slice\n \"\"\"\n midi_note_matrix = get_note_matrix(midi, midi_end_time, instrument_indexes)\n slices_note_matrix = np.array_split(midi_note_matrix, num_slices, axis=1)\n slice_instruments_presence = []\n for slice_note_matrix in slices_note_matrix:\n total_presence = np.sum(slice_note_matrix)\n if total_presence == 0:\n slice_instruments_presence.append([0] * len(instrument_indexes))\n else:\n slice_instruments_presence.append((np.sum(slice_note_matrix, axis=1) / total_presence).tolist())\n return slice_instruments_presence\n\n\ndef get_note_matrix(midi, midi_end_time, instrument_indexes):\n \"\"\"\n Get a matrix that indicates in each timestep which instruments are sounding\n :param midi: to slice\n :param midi_end_time: time where midi ends\n :param instrument_indexes: computed by the method \"get_midis_and_texts\"\n :return: matrix of dim [num_instruments, total midi time] with note markings for each instrument\n \"\"\"\n note_matrix = np.zeros([len(instrument_indexes), int(midi_end_time)])\n for instrument in midi.instruments:\n row = note_matrix[instrument_indexes[instrument.program]]\n for note in instrument.notes:\n row[int(note.start): int(note.end) + 1] = 1\n return note_matrix\n\n\ndef get_set(texts, midi_indexes, slices_indexes, word_indexes, nlp):\n \"\"\"\n Get a set ready to be fed into the RNN\n :param texts: lyrics of the songs in the set\n :param midi_indexes: indexes of midi embeddings in set\n :param slices_indexes: indexes of midi slice embeddings in set\n :param word_indexes: indexes of word in whole vocabulary\n :param nlp: the Spacy model\n :return: array with four elements, the indexes of [words, midis, midi slices, target classes] in the set\n \"\"\"\n x_words, x_midis, x_midis_sliced, y = [], [], [], []\n for i in range(len(texts)):\n text, midi_index = texts[i], midi_indexes[i]\n words = [token.text for token in nlp(text.strip())]\n text_word_indexes = [word_indexes[word] for word in words] # indexes of words in this text\n x_words.extend(text_word_indexes[:-1]) # shape (len(text)-1 = num of \"words in text except the last one\")\n x_midis.extend([midi_index] * (len(text_word_indexes) - 1)) # shape (len(text)-1, len(midi_vector))\n x_midis_sliced.extend(get_x_midi_sliced(words[:-1], slices_indexes[i]))\n y.extend(text_word_indexes[1:])\n return [np.array(x_words), np.array(x_midis), np.array(x_midis_sliced)], np.array(y)\n\n\ndef get_x_midi_sliced(words, slice_indexes):\n \"\"\"\n Get the indexes of midi slices in set, to be used by the method \"get_set\"\n :param words:\n :param slice_indexes:\n :return:\n \"\"\"\n x_midi_sliced = []\n midi_slice_idx = 0\n for word in words:\n x_midi_sliced.append(slice_indexes[midi_slice_idx])\n if word == '&': # end of phrase\n midi_slice_idx += 1\n return x_midi_sliced\n\n\ndef build_model(word_embeddings, midi_embeddings, lstm_lens, dense_lens, mode, slice_embeddings):\n \"\"\"\n Build the lyric generating model, employs the Adam optimizer and sparse categorical cross-entropy\n :param word_embeddings: np.array with the word embeddings\n :param midi_embeddings: np.array with the midi embeddings\n :param lstm_lens: array with the size of each lstm layer to process words and midi slices\n :param dense_lens: array with the size of each dense layer to process the concatenated vector\n :param mode: 'no midi' -> ignore midi and slices, 'simple' -> ignore slices, 'complex' -> ignore nothing\n :param slice_embeddings: np.array with the midi slice embeddings\n :return: compiled model\n \"\"\"\n # word component\n word_in = Input(shape=(1,), name='word_in')\n lstm_word = Embedding(word_embeddings.shape[0], word_embeddings.shape[1],\n trainable=False, weights=[word_embeddings], input_length=1)(word_in)\n # generate lstm layers in a loop\n for i, lstm_len in enumerate(lstm_lens):\n if i > 0: # for getting the right dimensionality\n lstm_word = Reshape(tuple([1, lstm_word.shape[1]]))(lstm_word)\n lstm_word = LSTM(lstm_len, dropout=0.1)(lstm_word)\n\n if mode != 'no midi':\n # midi component\n midi_in = Input(shape=(1,), name='midi_in')\n midi_embedding = Embedding(midi_embeddings.shape[0], midi_embeddings.shape[1],\n trainable=False, weights=[midi_embeddings], input_length=1)(midi_in)\n midi_embedding = Reshape(tuple([midi_embedding.shape[2]]))(midi_embedding)\n\n # concatenation\n if mode == 'complex':\n # midi slice component\n slice_in = Input(shape=(1,), name='slice_in')\n lstm_slice = Embedding(slice_embeddings.shape[0], slice_embeddings.shape[1],\n trainable=False, weights=[slice_embeddings], input_length=1)(slice_in)\n # generate lstm layers in a loop\n for i, lstm_len in enumerate(lstm_lens):\n if i > 0: # for getting the right dimensionality\n lstm_slice = Reshape(tuple([1, lstm_slice.shape[1]]))(lstm_slice)\n lstm_slice = LSTM(lstm_len, dropout=0.1)(lstm_slice)\n dense = concatenate([lstm_word, midi_embedding, lstm_slice])\n else:\n dense = concatenate([lstm_word, midi_embedding])\n else: # no concatenation since midi and midi slices are ignored\n dense = lstm_word\n # generate dense layers in a loop\n for dense_len in dense_lens:\n dense = Dense(dense_len)(dense)\n dense = Dropout(0.1)(dense)\n output = Dense(word_embeddings.shape[0], activation='softmax')(dense)\n if mode == 'no midi':\n model_input = word_in\n elif mode == 'simple':\n model_input = [word_in, midi_in]\n else:\n model_input = [word_in, midi_in, slice_in]\n model = Model(model_input, output, name=mode)\n model.compile(optimizer='adam', loss='sparse_categorical_crossentropy', metrics=['acc'])\n return model\n\n\ndef generate_texts(model, x_test, vocabulary, first_word_idx):\n \"\"\"\n Generate lyrics that start with a particular word, for all instances in test\n :param model: lyric generating model\n :param x_test: input for the model that corresponds to the test set\n :param vocabulary: output from the method \"get_vocabulary_and_word_embeddings\"\n :param first_word_idx: index of the first word for the generated lyrics\n :return: list with generated lyrics for each song in test set\n \"\"\"\n mode = model.name\n generated_texts = []\n prev_midi_idx = -1\n idx_range = range(len(vocabulary))\n for i in range(len(x_test[0])):\n curr_midi_idx = x_test[1][i]\n if mode == 'complex':\n midi_slice_idx = x_test[2][i]\n if prev_midi_idx != curr_midi_idx: # got to next song\n prev_midi_idx = curr_midi_idx\n if i != 0: # save text generated from last song\n text = ' '.join(generated_text)\n print(text)\n generated_texts.append(text)\n print('test song %d' % (len(generated_texts) + 1))\n word_idx = first_word_idx\n generated_text = [vocabulary[word_idx]]\n model.reset_states()\n if mode == 'no midi':\n pred_word_idxs = model.predict([[word_idx]])\n elif mode == 'simple':\n pred_word_idxs = model.predict([[word_idx], [curr_midi_idx]])\n else:\n pred_word_idxs = model.predict([[word_idx], [curr_midi_idx], [midi_slice_idx]])\n word_idx = int(choice(idx_range, 1, p=pred_word_idxs.reshape(-1)))\n generated_text.append(vocabulary[word_idx])\n text = ' '.join(generated_text)\n print(text)\n generated_texts.append(text) # append last generated text\n return generated_texts\n\n\ndef write_to_file(history, generated_texts, layer_sizes, iteration, model_name):\n \"\"\"\n Write the results to a file\n :param history: output from model.fit\n :param generated_texts: output from method \"generate_texts\"\n :param layer_sizes: to differentiate folder\n :param iteration: to differentiate folder\n :param model_name: to differentiate folder\n \"\"\"\n layers_str = '_'.join([str(i) for i in layer_sizes])\n dir_name = 'drive/My Drive/Colab results/lyric generator results/layers_%s/%s' % (layers_str, model_name)\n if not os.path.exists(dir_name):\n os.makedirs(dir_name)\n to_file = []\n header = \"epoch\"\n scores = []\n epoch = 0\n for key in history:\n header = \"%s,%s\" % (header, key)\n scores.append(history[key])\n\n to_file.append(header)\n for i in range(len(scores[0])):\n epoch += 1\n line = \"%d\" % epoch\n for j in range(len(scores)):\n line = \"%s,%s\" % (line, scores[j][i])\n to_file.append(line)\n\n with open('%s/train_results.csv' % dir_name, 'w') as file:\n for line in to_file:\n file.write(\"%s\\n\" % line)\n\n with open('%s/test_results_%d.csv' % (dir_name, iteration), 'w') as file:\n for line in generated_texts:\n file.write(\"%s\\n\" % line)\n\n# todo: run \"pip install pretty_midi\" in terminal\n# todo: run \"python -m spacy download en_core_web_md\" in terminal\n# todo: select experiment parameters:\n# base_dir = 'DL3/' # for colab\nbase_dir = '' # for pc\ntrain_subset = 0 # for speeding up debugging. select 0 for whole train set\nval_split = 0.2\n# mode = 'no midi'\nmode = 'simple'\n# mode = 'complex'\nlstm_lens = [128]\ndense_lens = [512]\nepochs = 30\nbatch_size = 256\n\ndataset_dir = '%sdataset' % base_dir\ncache_dir = '%scaches/%d' % (base_dir, train_subset)\ninstances_train = pd.read_csv('%s/lyrics_train_set.csv' % dataset_dir, header=None)\ninstances_test = pd.read_csv('%s/lyrics_test_set.csv' % dataset_dir, header=None)\n\nif train_subset > 0:\n instances_train = instances_train[:train_subset]\n\nif not os.path.exists(cache_dir):\n os.makedirs(cache_dir)\ninstrument_indexes = {}\n\nprint('loading texts and midis...')\nprint('train:')\nmidis_train, texts_train = get_midis_and_texts(instances_train, dataset_dir, instrument_indexes, 'train')\nprint('test:')\nmidis_test, texts_test = get_midis_and_texts(instances_test, dataset_dir, instrument_indexes, 'test')\n\nprint('building word embeddings...')\nnlp = spacy.load('en_core_web_md') # 300 dim embeddings\n# nlp = spacy.load('en_core_web_sm') # smaller embeddings\nword_indexes, word_embeddings, vocabulary = get_vocabulary_and_word_embeddings(texts_train, texts_test, nlp)\n\nprint('building midi embeddings...')\nmidi_embeddings, midi_sliced_embeddings, slice_indexes_train, slice_indexes_test = get_midi_embeddings()\n\ntrain_len = len(texts_train)\nmidi_indexes_train = list(range(train_len))\nmidi_indexes_test = list(range(train_len, train_len + len(texts_test)))\nval_len = int(len(texts_train) * val_split)\nprint('building train set...')\nx_train, y_train = get_set(texts_train[:-val_len], midi_indexes_train[:-val_len], slice_indexes_train[:-val_len],\n word_indexes, nlp)\nprint('building validation set...')\nx_val, y_val = get_set(texts_train[-val_len:], midi_indexes_train[-val_len:], slice_indexes_train[-val_len:],\n word_indexes, nlp)\nprint('building test set...')\nx_test, y_test = get_set(texts_test, midi_indexes_test, slice_indexes_test, word_indexes, nlp)\n\n# build model\nmodel = build_model(word_embeddings, midi_embeddings, lstm_lens, dense_lens, mode, midi_sliced_embeddings)\nmodel.summary()\ncheckpoint = ModelCheckpoint('checkpoint.h5', save_best_only=True)\nif mode == 'no midi':\n x_train_mode, x_val_mode = x_train[0], x_val[0]\nelif mode == 'simple':\n x_train_mode, x_val_mode = x_train[:-1], x_val[:-1]\nelse:\n x_train_mode, x_val_mode = x_train, x_val\nhistory = model.fit(x_train_mode, y_train, batch_size, epochs, callbacks=[checkpoint], validation_data=(x_val_mode, y_val))\nmodel = load_model('checkpoint.h5')\n\n# generate text for all the 5 test melodies, 3 times\nfirst_word_idxs = [word_indexes[word] for word in ['the', 'you', 'world']]\nfor i, first_word_idx in enumerate(first_word_idxs):\n print('iteration %d/3' % (i + 1))\n generated_texts = generate_texts(model, x_test, vocabulary, first_word_idx)\n write_to_file(history.history, generated_texts, lstm_lens, i + 1, model.name)\n\nprint('\\ndone')\n","repo_name":"jonmartz/DL3","sub_path":"LyricGenerator.py","file_name":"LyricGenerator.py","file_ext":"py","file_size_in_byte":23374,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"}
+{"seq_id":"6898801383","text":"\"\"\"\nRemoves unused imports in a file\n\nTODO:\n- Add tests\n- Handle/ignore conditional global imports\n- Handle shadowing variables\n\n\"\"\"\nfrom util import type_name\nfrom visitor import NodeVisitor\n\n\nclass Visitor(NodeVisitor):\n def __init__(self):\n self.imports = {}\n self.names = {}\n self.multi_imports = []\n self.in_trailer = 0\n\n def visit_import_name(self, node):\n name_child = node.children[1]\n type = type_name(name_child)\n if type == \"NAME\":\n name = name_child.value\n elif type == \"dotted_name\":\n name = \"\".join(\n c.value for c in name_child.children)\n elif type == \"dotted_as_name\":\n name = name_child.children[2].value\n else:\n raise Exception(\"Unknown type\", type)\n self.imports[name] = [node.parent]\n\n def visit_import_from(self, node):\n name_child = node.children[-1]\n type = type_name(name_child)\n name = \"\"\n if type == \"NAME\":\n name = name_child.value\n elif type == \"import_as_name\":\n name = name_child.children[-1].value\n elif type == \"import_as_names\":\n self.multi_imports.append(node)\n self.visit_import_as_names(name_child)\n elif type == \"RPAR\":\n prev_node = name_child.prev_sibling\n assert(type_name(prev_node) == \"import_as_names\")\n self.multi_imports.append(node)\n self.visit_import_as_names(prev_node)\n else:\n raise Exception(\"Unknown type\", type)\n if name:\n self.imports[name] = [node.parent]\n\n def visit_import_as_names(self, node):\n for child in node.children:\n type = type_name(child)\n name_child = None\n if type == \"COMMA\":\n continue\n if type == \"import_as_name\":\n name_child = child.children[-1]\n elif type == \"NAME\":\n name_child = child\n else:\n raise Exception(\"Unknown type\", type)\n if not name_child:\n continue\n name = name_child.value\n if name_child is node.children[-1]:\n self.imports[name] = [\n child.prev_sibling, child]\n else:\n self.imports[name] = [\n child, child.next_sibling]\n\n def visit_power(self, node):\n first = node.children[0]\n rest = node.children[1:]\n type = type_name(first)\n if type == \"AWAIT\":\n first = node.children[1]\n rest = node.children[2:]\n elif type == \"atom\":\n return self.generic_visit(node)\n name = first.value\n self.names[name] = node\n ended = False\n for child in rest:\n if type_name(child) != \"trailer\" or \\\n type_name(child.children[0]) != \"DOT\":\n ended = True\n if ended:\n self.generic_visit(child)\n else:\n name += \".\" + child.children[1].value\n self.names[name] = child\n\n def visit_trailer(self, node):\n is_dotted = node.children[0].value == \".\"\n if is_dotted:\n self.in_trailer += 1\n self.generic_visit(node)\n if is_dotted:\n self.in_trailer -= 1\n self.generic_visit(node)\n\n def visit_NAME(self, node):\n if self.in_trailer == 0:\n self.names[node.value] = node\n\n def visit_dotted_name(self, node):\n name = \"\"\n for child in node.children:\n name += child.value\n if type_name(child) == \"DOT\":\n continue\n self.names[name] = node\n\n def remove_import(self, node):\n if not node:\n return\n prefix = node.prefix\n if node.next_sibling:\n node.next_sibling.prefix = prefix + node.next_sibling.prefix\n node.remove()\n\n def visit_ENDMARKER(self, node):\n for name in self.imports:\n if name in self.names:\n continue\n for node in self.imports[name]:\n self.remove_import(node)\n for node in self.multi_imports:\n import_as_node = node.children[-1]\n if type_name(import_as_node) == \"RPAR\":\n import_as_node = import_as_node.prev_sibling\n if len(import_as_node.children):\n continue\n self.remove_import(node.parent)\n","repo_name":"banga/prefactor","sub_path":"visitors/remove_unused_imports.py","file_name":"remove_unused_imports.py","file_ext":"py","file_size_in_byte":4475,"program_lang":"python","lang":"en","doc_type":"code","stars":12,"dataset":"github-code","pt":"21"}
+{"seq_id":"20449568697","text":"#!/usr/bin/env python3\n\"\"\"\nLeNet-5 (Keras)\n\"\"\"\n\nimport tensorflow.keras as K\n\n\ndef lenet5(X):\n \"\"\"\n Function that builds a modified version of the LeNet-5\n architecture using keras\n \"\"\"\n initializer = K.initializers.he_normal(seed=None)\n\n conv_layer1 = K.layers.Conv2D(filters=6, kernel_size=5,\n padding='same',\n activation='relu',\n kernel_initializer=initializer)(X)\n pool_layer1 = K.layers.MaxPooling2D(\n pool_size=[2, 2],\n strides=2)(conv_layer1)\n\n conv_layer_2 = K.layers.Conv2D(filters=16, kernel_size=5,\n padding='valid',\n activation='relu',\n kernel_initializer=initializer)(pool_layer1)\n\n pool_layer2 = K.layers.MaxPooling2D(pool_size=[2, 2],\n strides=2)(conv_layer_2)\n\n flat_layer = K.layers.Flatten()(pool_layer2)\n\n fully_c_layer1 = K.layers.Dense(120, activation='relu',\n kernel_initializer=initializer)(flat_layer)\n\n fully_c_layer2 = K.layers.Dense(84, activation='relu',\n kernel_initializer=initializer)(\n fully_c_layer1)\n\n out_soft_layer = K.layers.Dense(10,\n activation='softmax',\n kernel_initializer=initializer)(\n fully_c_layer2)\n\n model = K.models.Model(X, out_soft_layer)\n model.compile(optimizer=K.optimizers.Adam(),\n loss='categorical_crossentropy',\n metrics=['accuracy'])\n return model\n","repo_name":"nildiert/holbertonschool-machine_learning","sub_path":"supervised_learning/0x07-cnn/5-lenet5.py","file_name":"5-lenet5.py","file_ext":"py","file_size_in_byte":1761,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"21"}
+{"seq_id":"31021239105","text":"from sqlalchemy import create_engine\nfrom sqlalchemy.orm import sessionmaker\n\nfrom db_setup import Category, Base, Item, User\nfrom random import randint\nengine = create_engine('sqlite:///itemcatalog.db')\n# Bind the engine to the metadata of the Base class so that the\n# declaratives can be accessed through a DBSession instance\nBase.metadata.bind = engine\n\nDBSession = sessionmaker(bind=engine)\n# A DBSession() instance establishes all conversations with the database\n# and represents a \"staging zone\" for all the objects loaded into the\n# database session object. Any change made against the objects in the\n# session won't be persisted into the database until you call\n# session.commit(). If you're not happy about the changes, you can\n# revert all of them back to the last commit by calling\n# session.rollback()\nsession = DBSession()\n\nsession.query(User).delete()\nsession.commit()\n\nsession.query(Category).delete()\nsession.commit()\n\nsession.query(Item).delete()\nsession.commit()\n\nprint(\"DELETED ALL ENTRIES!\")\nprint(\"--------------------------\")\n\ntry:\n User1 = User(name=\"Robo Barista\",\n email=\"tinnyTim@udacity.com\", picture=\"hg\")\n session.add(User1)\n session.commit()\n\n with open('data.txt', 'r+') as file:\n data = file.read().splitlines()\n\n i = 0\n while i < len(data):\n userID = randint(1, 3)\n cat = data[i]\n category = Category(user_id=userID, name=cat)\n session.add(category)\n session.commit()\n print(cat)\n while True:\n itemName = data[i+1]\n itemDescr = data[i+2]\n item = Item(name=itemName, description=itemDescr,\n user_id=userID, category_id=category.id)\n #print(cat, itemName, itemDescr)\n print('- %s' % itemName)\n session.add(item)\n session.commit()\n if data[i+3] == '-':\n i += 4\n break\n i += 2\nexcept:\n pass\nfinally:\n print(\"--------------------------\")\n\nprint(\"--------------------------\")\n","repo_name":"Temirkhanov/ItemCatalog","sub_path":"populate.py","file_name":"populate.py","file_ext":"py","file_size_in_byte":2135,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"}
+{"seq_id":"18239518491","text":"r, c = map(int, input().split())\na = [list(input()) for _ in range(r)]\nn = int(input())\nthrow = list(map(int, input().split())) # 왼쪽/오른쪽 번갈아가며\n\ndx = [0, 0, 1, -1]\ndy = [1, -1, 0, 0]\n\n\ndef dfs(x, y, check, group):\n if a[x][y] == \".\":\n return\n if check[x][y]:\n return\n check[x][y] = True\n group.append((x, y))\n for k in range(4):\n nx, ny = x + dx[k], y + dy[k]\n if 0 <= nx < r and 0 <= ny < c:\n dfs(nx, ny, check, group)\n\n\ndef simulate():\n check = [[False]*c for _ in range(r)]\n for x in range(r):\n for y in range(c):\n if a[x][y] == '.':\n continue\n if check[x][y]:\n continue\n group = []\n dfs(x, y, check, group)\n low = [-1] * c\n for gx, gy in group:\n low[gy] = max(low[gy], gx)\n a[gx][gy] = '.'\n lowest = r #이게 땅이다.\n for j in range(c):\n if low[j] == -1:\n continue\n i = low[j]\n while i < r and a[i][j] == '.':\n i += 1\n lowest = min(lowest, i-low[j]-1)\n for gx, gy in group:\n gx += lowest\n a[gx][gy] = 'x'\n check[gx][gy] = True\n\n\nfor i in range(len(throw)):\n # 홀수번째 던지기\n height = r - throw[i]\n if i % 2 == 0:\n for j in range(c):\n if a[height][j] == 'x':\n a[height][j] = '.'\n break\n\n # 짝수번째 던지기\n else:\n for j in range(c-1, -1, -1):\n if a[height][j] == 'x':\n a[height][j] = '.'\n break\n\n simulate()\n\nfor row in a:\n print(row)\n\n","repo_name":"yeonnseok/ps-algorithm","sub_path":"2019 baekjoon/Simulation/2933_mineral.py","file_name":"2933_mineral.py","file_ext":"py","file_size_in_byte":1767,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"21"}
+{"seq_id":"38271149479","text":"import boto3\r\n\r\ndef getec2details(event, context):\r\n tolist = []\r\n idlist = []\r\n fflist = []\r\n ec2client = boto3.client('ec2')\r\n response = ec2client.describe_instances(\r\n Filters=[\r\n {\r\n 'Name': 'tag-key',\r\n 'Values': ['auto_patching']}])['Reservations']\r\n # tolist = ['sri.pavan.tipirneni@spglobal.com'] #debug\r\n if len(response) != 0:\r\n for values in response:\r\n taglist = values['Instances'][0]['Tags']\r\n for keys in taglist:\r\n if keys['Key'] == 'Owner' or keys['Key'] == 'owner' or keys['Key'] == 'creatorid' or keys['Key'] == 'CreatorId':\r\n if keys['Value'] not in tolist:\r\n tolist.append(keys['Value'].lower())\r\n else:\r\n tolist.append('mi-aws-cloudcustodian@spglobal.com')\r\n for emails in tolist:\r\n if emails not in fflist:\r\n fflist.append(emails)\r\n if len(response) != 0:\r\n for data in response:\r\n if data['Instances'][0]['InstanceId'] not in idlist:\r\n idlist.append(data['Instances'][0]['InstanceId'])\r\n else:\r\n idlist.append(\"No Instances available for patching\")\r\n for add in fflist:\r\n #print (add) ## debug\r\n if add.find('@') < 0:\r\n fflist.remove(add)\r\n #print ('removed:',add) ##debug\r\n return fflist,idlist\r\n\r\ndef lambda_handler(event, context):\r\n toemaillist,instanceslist = getec2details(event, context)\r\n sescli = boto3.client('ses')\r\n print(\"Sending email to {0}\".format(toemaillist) )\r\n strTable = \"| InstanceID |
\"\r\n for values in instanceslist:\r\n strRW = \"| \"+values+\" |
\"\r\n strTable = strTable+strRW\r\n BODY_HTML = \"\"\"EC2 Patching\"\"\"+ event['processstage']+\"\"\"
Below is the list of Instances that are being patched
\"\"\"\r\n data = 'EC2 Patching has'+event['processstage']\r\n sescli.send_email(\r\n Source= 'mi-aws-cloudcustodian@spglobal.com',\r\n Destination={'ToAddresses': toemaillist},\r\n Message={\r\n 'Subject': { 'Data': data},\r\n 'Body': {'Html': {'Charset': \"UTF-8\",'Data': BODY_HTML}}})\r\n\r\n#### Invoking payload details\r\n##\"Payload\": \"{\\\"processstage\\\":\\\"starting\\\"}\"\r\n##\"Payload\": \"{\\\"processstage\\\":\\\"has ended\\\"}\"\r\n## lambda test event data\r\n# {\r\n# \"processstage\": \" has started.\"\r\n# }\r\n","repo_name":"suneeltejaa/test102","sub_path":"mailerpythonlambda.py","file_name":"mailerpythonlambda.py","file_ext":"py","file_size_in_byte":2678,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"}
+{"seq_id":"10137486061","text":"import pulp\nimport pandas as pd\n\ndataset = {1: 'woodler_data_5_sites', 2: 'woodler_data_10_sites', 3: 'woodler_data_30_sites'}[2]\nsub_tour_elimination_MTZ = False\nsub_tour_elimination_DFJ = False\ntime_limit = 60\nmip_gap = 0.05\n\ndataset_path = f\"../data/{dataset}.xlsx\"\nsites = pd.read_excel(dataset_path, sheet_name='sites')\ntrucks = pd.read_excel(dataset_path, sheet_name='trucks')\ntransit_matrix = pd.read_excel(dataset_path, sheet_name='transit_matrix')\n\nI = set(sites['Site ID'])\ntd = dict(zip(zip(transit_matrix['Origin Site ID'], transit_matrix['Dest. Site ID']), transit_matrix['Distance (KM)']))\nvc = trucks['Variable Cost (dollar/KM)'].iloc[0] # variable cost of the first truck\ndepot_id = sites[sites['Site Name'] == 'DC']['Site ID'].iloc[0]\n\n# keys of decision variables\nx_keys = [(i, j) for i in I for j in I if i != j]\n\n# Define the model\nmdl = pulp.LpProblem('woodler', sense=pulp.LpMinimize)\n\n# Add variables\nx = pulp.LpVariable.dicts(indices=x_keys, cat=pulp.LpBinary, name='x')\n\n# Add Constraints\n# Flow balance\nfor h in I:\n mdl.addConstraint(sum(x.get((i, h), 0) for i in I) == sum(x.get((h, j), 0) for j in I), name=f'c4_{h}')\n\n# Must visit every site\nfor j in I:\n mdl.addConstraint(sum(x.get((i, j), 0) for i in I) == 1, name=f'c5_{j}')\n\n# Miller–Tucker–Zemlin (MTZ) sub-tour elimination constraints\nif sub_tour_elimination_MTZ:\n u = pulp.LpVariable.dicts(indices=I, cat=pulp.LpInteger, lowBound=0, upBound=len(I)-1, name='u')\n for i, j in x_keys:\n if j != depot_id:\n mdl.addConstraint(u[i] - u[j] + 1 <= len(I) * (1 - x[i, j]), name=f'mtz_{i}_{j}')\nelse:\n u = None\n\n# Dantzig–Fulkerson–Johnson (DFJ) sub-tour elimination constraints\nif sub_tour_elimination_DFJ:\n # two-sites sub-tours\n for i, j in x_keys:\n mdl.addConstraint(x[i, j] + x.get((j, i), 0) <= 1, name=f'dfj_{i}_{j}')\n\n# Set the objective function\nvariable_cost = sum(vc * td[i, j] * x[i, j] for i, j in x_keys)\nmdl.setObjective(variable_cost)\n\n# Optimize\nstatus = mdl.solve(pulp.PULP_CBC_CMD(timeLimit=time_limit, gapRel=mip_gap))\nif pulp.LpStatus[status] == 'Optimal':\n # Retrieve the solution\n x_sol = [key for key in x_keys if x[key].value() > 0.5]\n print(f'Total Cost: {round(variable_cost.value(), 2)}')\n print(f'x_sol: {x_sol}')\n if u:\n u_sol = [(u[i].value(), i) for i in I]\n u_sol = sorted(u_sol, key=lambda t: t[0])\n path = [i for _, i in u_sol]\n print(f'Path: {path}')\nelse:\n print(f'Optimization status: {pulp.LpStatus[status]}')\n","repo_name":"mipwise/use-cases","sub_path":"woodler/scripts/woodler_single_truck_pulp.py","file_name":"woodler_single_truck_pulp.py","file_ext":"py","file_size_in_byte":2525,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"21"}
+{"seq_id":"15957682959","text":"import logging\nimport math\nfrom . import daveML\n\n###############################################################################\nclass UnitTest:\n \"\"\"A unit test class. \n \n A base class that other classes derive for unit testing.\n \n Attributes:\n FailCount: The number of failed tests.\n ClassName: A string to identify the class performing the unit test.\n \"\"\"\n\n FailCount = 0\n ClassName = \" \"\n \n def TestValue(self, actualValue, testValue, label, tol):\n \"\"\"Tests whether two values match within a tolerance. \n \n A string label is passed to identify the test. An error via logging is\n printed if the test fails.\n \n Example:\n TestValue( 2, 1+1, \"SimpleAdd\", 1e-2)\n\n Args:\n actualValue: The expected value from doing the test.\n testValue: The computed value from doing the test.\n label: A label to identify the specific test.\n tol: The tolerance for the actual and test values to match.\n \"\"\"\n if abs(actualValue - testValue) > tol:\n self.FailCount += 1\n labelStr = \"[\" + self.ClassName + \"]\" + label\n actStr = labelStr + \": Test failed. Expected: {};\".format(actualValue)\n calStr = \" Calculated: {}\".format(testValue)\n logging.error(actStr+calStr)\n \n def TestArray(self, arrayData):\n \"\"\"Performs multiple tests on an array of data. \n \n Example:\n Create a data array containing the desired value, the test value,\n the identity string, and the tolerance.\n \n checkData = (\n ( 4.0, 2.0*2.0, \"MultipleTest\", 1e-6),\n ( 16.0, 8.0+8.0, \"Add-Example\", 1e-5)\n )\n \n TestArray(checkData)\n \"\"\"\n for d in arrayData:\n self.TestValue( d[0], d[1], d[2], d[3] )\n\n###############################################################################\nclass Convert(UnitTest):\n \"\"\"A class for performing unit conversions.\n \n | unit | abbreviation |\n |:---------------|:-------------|\n | second | s |\n | minute | min |\n | inch | inch |\n | foot | ft |\n | meter | m |\n | nautical mile | nmi |\n | statute mile | smi |\n | kilometer | km |\n | centimeter | cm |\n | millimeter | mm |\n | pound force | lbf |\n | Newton | N |\n | kilogram force | kgf |\n | kilogram | kg |\n | pound mass | lbm |\n | slug | slug |\n | degree | deg |\n | radian | rad |\n | knot (nmi/hr) | kt |\n | nondimensional | nd |\n\n Attributes:\n KnotToFps: scale factor to convert knots to feet per second.\n FpsToKnot: scale factor to convert feet per second to knots.\n MinToSec: scale factor to convert minutes to seconds.\n FeetToMeter: scale factor to convert feet to meters.\n MeterToFeet: scale factor to convert meters to feet.\n NmToFeet: scale factor to convert nautical miles to feet.\n FeetToNm: scale factor to convert feet to nautical miles.\n SqMeterToSqFeet: scale factor to convert square meters to square feet.\n SqFeetToSqMeter: scale factor to convert square feet to square meters.\n PoundToNewton: scale factor to convert pounds to Newtons.\n NewtonToPound: scale factor to convert Newtons to pounds.\n SlugToKg: scale factor to convert slugs to kilograms.\n KgToSlug: scale factor to convert kilograms to slugs.\n Slugft2ToKgm2: scale factor to convert slug-ft2 to kg-m2.\n Kgm2ToSlugft2: scale factor to convert kg-m2 to slug-ft2.\n DegToRad: scale factor to convert degrees to radians.\n RadToDeg: scale factor to convert radians to degrees.\n MpsToKt: scale factor to convert meters per second to knots.\n KtToMps: scale factor to convert knots to meters per second.\n \"\"\"\n KnotToFps = 1.6878097112860893\n FpsToKnot = (1.0 / KnotToFps)\n MinToSec = 60.0\n FeetToMeter = 0.3048\n MeterToFeet = (1.0 / FeetToMeter)\n NmToFeet = 6076.115485564304\n FeetToNm = (1.0 / NmToFeet)\n SqMeterToSqFeet = (MeterToFeet*MeterToFeet)\n SqFeetToSqMeter = 1.0 / SqMeterToSqFeet\n PoundToNewton = 4.4482216152605\n NewtonToPound = 1.0 / PoundToNewton\n SlugToKg = 14.593902937\n KgToSlug = 1.0 / SlugToKg\n Slugft2ToKgm2 = 1.3558179618926\n Kgm2ToSlugft2 = 1.0 / Slugft2ToKgm2\n DegToRad = math.radians(1.0)\n RadToDeg = math.degrees(1.0)\n MpsToKt = 1.94384\n KtToMps = 0.5144444\n \n ImperialToSI = {\n \"lbf\": PoundToNewton,\n \"slug\": SlugToKg,\n \"slugft2\": Slugft2ToKgm2,\n \"ft\": FeetToMeter,\n \"ft_s\": FeetToMeter,\n \"ft2\": SqFeetToSqMeter,\n \"deg\": DegToRad,\n \"deg_s\": DegToRad,\n \"km\": 1000.0,\n \"km_s\": 1000.0,\n \"kt\": KtToMps,\n \"m\": 1,\n \"m2\": 1,\n \"nd\": 1\n }\n \n SiToImperial = {\n \"m\": MeterToFeet,\n \"m2\": SqMeterToSqFeet,\n \"rad\": RadToDeg,\n \"rad_s\": RadToDeg,\n \"m_s\": MpsToKt,\n \"n\": NewtonToPound,\n \"kg\": KgToSlug,\n \"kgm2\": Kgm2ToSlugft2,\n \"s\": 1,\n \"m->ft\": MeterToFeet,\n \"m_s->ft_s\": MeterToFeet,\n \"rad->deg\": RadToDeg,\n \"rad_s->deg_s\": RadToDeg,\n \"m_s2->ft_s2\": MeterToFeet,\n \"n->lbf\": NewtonToPound,\n \"m_s->nmi_h\": MpsToKt\n }\n \n def LogWarn(self, inUnit):\n \"\"\"Log a warning for unrecognized unit.\n \n Args:\n inUnit: unit string value not recognized.\n \"\"\"\n warnStr = units + \" not recognized in ppConvert. No conversion done.\"\n logging.warning(warnStr)\n \n def SetIC(self, inIC):\n \"\"\"Convert initial conditions to SI.\n \n Args:\n inIC: initial conditions.\n \"\"\"\n print(\"========= SetIC ==============\")\n icData = {}\n for key,value in inIC.items():\n units = value[1].lower()\n factor = 1\n if units in self.ImperialToSI:\n factor = self.ImperialToSI[units]\n elif units not in self.SiToImperial:\n self.LogWarn(units)\n icData[key] = factor * value[0]\n return icData\n \n def ToSI(self, value, inUnits):\n \"\"\"Convert a value from Imperial to SI units.\n \n Args:\n value: Imperial value to convert.\n inUnits: string value of the Imperial unit value.\n \n Returns:\n SI value.\n \"\"\"\n units = inUnits.lower()\n factor = 1\n if units in self.ImperialToSI:\n factor = self.ImperialToSI[units]\n elif units not in self.SiToImperial:\n self.LogWarn(inUnits)\n return value*factor\n \n def ToImperial(self, value, inUnits):\n \"\"\"Convert a value from SI to Imperial units.\n \n Args:\n value: SI value to convert.\n inUnits: string value of the SI unit value.\n \n Returns:\n Imperial value.\n \"\"\"\n units = inUnits.lower()\n factor = 1\n if units in self.SiToImperial:\n factor = self.SiToImperial[units]\n elif units in self.ImperialToSI:\n self.LogWarn(inUnits)\n \n convertedValue = []\n for v in value:\n convertedValue.append(v*factor)\n return convertedValue\n \n def UnitTest(self):\n \"\"\"Perform tests to check unit conversions.\"\"\"\n self.ClassName = \"Convert\"\n checkData = (\n ( 123.0, 72.876*self.KnotToFps, \"KnotToFps\", 1e-3),\n ( 78.8, 133.0*self.FpsToKnot, \"FpsToKnot\", 1e-3),\n ( 300.0, 5.0*self.MinToSec, \"MinToSec\", 1e-12),\n ( 395.9352, 1299.0*self.FeetToMeter, \"FeetToMeter\", 1e-4),\n ( 1299.0, 395.9352*self.MeterToFeet, \"MeterToFeet\", 1e-4),\n ( 3967703.4, 653.0*self.NmToFeet, \"NmToFeet\", 0.1),\n ( 653.0, 3967703.4*self.FeetToNm, \"FeetToNm\", 0.1),\n ( 10.763910, self.SqMeterToSqFeet, \"SqMeterToSqFeet\", 1e-6),\n ( 13.0, 2.92252*self.PoundToNewton, \"PoundToNewton\", 1e-4),\n ( 1.0, 0.73756215*self.Slugft2ToKgm2, \"Slugft2ToKgm2\", 1e-7),\n ( 54.864, self.FeetToMeter*180.0, \"FeetToMeters\", 1e-4),\n (1742.12598, self.MeterToFeet*531.0, \"MetersToFeet\", 1e-5),\n ( 178.5596, self.SqFeetToSqMeter*1922.0, \"SqFeetToSqMeters\", 1e-4),\n ( 4412.64, self.PoundToNewton*992.0, \"PoundsToNewtons\", 0.01),\n (21.6930872, self.Slugft2ToKgm2*16.0, \"SlugFt2ToKgM2\", 1e-6),\n (161.0256, self.ToSI(36.2,\"lbf\"), \"ToSI lbf->N\", 1e-3),\n (161.0256, self.ToSI(36.2,\"LBf\"), \"ToSI lbf->N\", 1e-3),\n (105.7538001, self.ToSI(78.0,\"slugft2\"), \"ToSI slugf2->kgm2\", 1e-6),\n (531.0, self.ToSI(1742.12598,\"ft\"), \"ToSI f->m\", 1e-5),\n (9.7536, self.ToSI(32.0,\"ft_s\"), \"ToSI fps-mps\", 1e-4),\n (140.6552, self.ToSI(1514,\"ft2\"), \"ToSI f2-m2\", 1e-4),\n (math.pi, self.ToSI(180.0,\"deg\"), \"ToSI deg->rad\", 1e-6),\n (0.25*math.pi, self.ToSI(45.0,\"deg_s\"), \"ToSI dps->rps\", 1e-6),\n (93200, self.ToSI(93.2,\"km\"), \"ToSI km->m\", 1e-6),\n (4221, self.ToSI(4.221,\"km_s\"), \"ToSI km_s->m_s\", 1e-6)\n )\n \n self.TestArray(checkData)\n \n self.ClassName = \"Convert IC\"\n icTest = {\n \"newtonTest\": [36.2, \"lbf\"],\n \"inertiaTest\": [78.0, \"slugft2\"],\n \"feetTest\": [1742.12598, \"ft\"],\n \"fpsTest\": [32.0, \"ft_s\"],\n \"ft2Test\": [1514, \"ft2\"],\n \"degTest\": [180, \"deg\"],\n \"dpsTest\": [45.0, \"deg_s\"],\n \"kmTest\": [93.2, \"km\"],\n \"kpsTest\": [4.221, \"km_s\"]\n }\n icData = self.SetIC(icTest)\n self.TestValue(161.0256, icData[\"newtonTest\"], \"lbf->N\", 1e-3)\n self.TestValue(105.7538001, icData[\"inertiaTest\"], \"slugf2->kgm2\", 1e-6)\n self.TestValue(531.0, icData[\"feetTest\"], \"f->m\", 1e-5)\n self.TestValue(9.7536, icData[\"fpsTest\"], \"fps-mps\", 1e-4)\n self.TestValue(140.6552, icData[\"ft2Test\"], \"f2-m2\", 1e-4)\n self.TestValue(math.pi, icData[\"degTest\"], \"deg->rad\", 1e-6)\n self.TestValue(0.25*math.pi, icData[\"dpsTest\"], \"dps->rps\", 1e-6)\n self.TestValue(93200, icData[\"kmTest\"], \"km->m\", 1e-6)\n self.TestValue(4221, icData[\"kpsTest\"], \"km_s->m_s\", 1e-6)\n \n self.ClassName = \"Convert ToImperial\"\n \n fa = self.ToImperial([100, 1000],\"m\")\n aa = self.ToImperial([100, 1000],\"m2\")\n da = self.ToImperial([0.5*math.pi, math.pi],\"rad\")\n dsa = self.ToImperial([1.5*math.pi],\"rad_s\")\n ka = self.ToImperial([100, 1000],\"m_s\")\n na = self.ToImperial([25, 250],\"N\")\n sa = self.ToImperial([16, 160],\"kg\")\n ga = self.ToImperial([59, 590],\"kgm2\")\n \n checkImperial = (\n (328.084, fa[0], \"m->ft\", 1e-3),\n (3280.84, fa[1], \"m->ft\", 1e-2),\n (1076.39, aa[0], \"m2->ft2\", 1e-2),\n (10763.9, aa[1], \"m2->ft2\", 0.1),\n ( 90.0, da[0], \"rad->deg\", 1e-6),\n ( 180.0, da[1], \"rad->deg\", 1e-6),\n ( 270.0, dsa[0], \"rad_s->deg_s\", 1e-6),\n (194.384, ka[0], \"m_s->knot\", 1e-3),\n (1943.84, ka[1], \"m_s->knot\", 1e-2),\n (5.62022, na[0], \"N->lbf\", 1e-5),\n (56.2022, na[1], \"N->lbf\", 1e-4),\n (1.09635, sa[0], \"kg->slug\", 1e-5),\n (10.9635, sa[1], \"kg->slug\", 1e-4),\n (43.5161664, ga[0], \"kgm2->slugft2\", 1e-7),\n (435.161664, ga[1], \"kgm2->slugft2\", 1e-6)\n )\n \n self.TestArray(checkImperial)\n \n print(\"Number of Convert failed tests: \", self.FailCount)\n\n###############################################################################\nclass Planet(UnitTest):\n \"\"\"A base class to describe planets and moons. \n \n A base class that other classes derive for defining planet characteristics.\n \n Attributes:\n GM: the gravity constant.\n J2: gravity parameter.\n Latitude: the Latitude position of the planet.\n Longitude: the Longitude of the planet.\n Altitude: the MSL altitude \n RotationRate: the rotational rate (rad/s) of the body. East rotation \n is positive.\n SemiMajor: the semi-major axis of the ellipsoid planet model.\n Flattening: the flatening parameter.\n SemiMinor: the semi-minor axis of the ellipsoid planet model. \n [Calculated]\n Eccentricity: the eccentricity. [Calculated]\n EccentricitySquared: the eccentricity squared. [Calculated]\n \"\"\"\n \n GM = 0\n J2 = 0\n \n Latitude = 0\n Longitude = 0\n Altitude = 0\n \n RotationRate = 0\n SemiMajor = 0\n Flattening = 0\n SemiMinor = 0\n Eccentricity = 0\n EccentricitySquared = 0\n \n density = 0\n temperature = 0\n pressure = 0\n speedOfSoundMps = 0\n \n def CalcSemiMinor(self):\n \"\"\"Calculate the semi-minor axis based on semi-major and flattening \n values.\n \"\"\"\n self.SemiMinor = self.SemiMajor * ( 1.0 - self.Flattening )\n \n def CalcEccentricity(self):\n \"\"\"Calculate the eccentricity given the semi-major and semi-minor \n axes.\n \"\"\"\n a = self.SemiMajor\n b = self.SemiMinor\n self.Eccentricity = (math.sqrt( a * a - b * b ) / a)\n self.EccentricitySquared = (self.Eccentricity) ** 2\n \n def LlaToPcpf(self):\n \"\"\"Convert geodetic to ECEF coordinates \"\"\"\n a = self.SemiMajor\n e2 = self.EccentricitySquared\n sinLat = math.sin( self.Latitude )\n N = a / math.sqrt( 1.0 - (e2*sinLat*sinLat) )\n\n cosLat = math.cos( self.Latitude )\n # set the planet centered, planet fixed (PCPF) x,y,z vector in meters\n x = (N + self.Altitude) * cosLat * math.cos(self.Longitude)\n y = (N + self.Altitude) * cosLat * math.sin(self.Longitude)\n z = (N*(1.0 - e2) + self.Altitude) * sinLat\n return x, y, z\n \n def PcpfToLlaZhu(self, x, y, z):\n \"\"\"Convert from ECEF coordinates to geodetic using Zhu.\n \n A closed form solution with no singularities.\n \n J. Zhu. Conversion of earth-centered earth-fixed coordinates to \n geodetic coordinates. Technical Report IEEE Log NO. T-AES/30/3/1666, \n IEEE, December 1993.\n \"\"\"\n a = self.SemiMajor\n b = self.SemiMinor\n e = self.Eccentricity\n e2 = self.EccentricitySquared\n\n assert b != 0, \"SemiMinor axis is 0\"\n ep = e * a / b\n ep2 = ep * ep\n \n r = math.sqrt( x*x + y*y )\n F = 54.0 * b*b * z*z\n G = r*r + (1.0 - e2) * z*z - e2*(a*a - b*b)\n c = e2*e2*F*r*r/(G*G*G)\n s = ( 1.0 + c + math.sqrt(c*c + 2.0*c) ) ** (1.0 / 3.0)\n P = F / ( 3.0*( (s + 1.0/s + 1.0)**2.0 )*G*G )\n Q = math.sqrt(1.0 + 2.0 * e2*e2 * P)\n r0 = (-P*e2*r/(1.0 + Q) \n + math.sqrt( 0.5*a*a*(1.0 + 1.0/Q) \n - (P*(1.0-e2)*z*z)/(Q + Q*Q) \n - 0.5*P*r*r ))\n U = math.sqrt( (r-e2*r0)**2.0 + z*z )\n V = math.sqrt( (r-e2*r0)**2.0 + (1.0 - e2)*z*z )\n z0 = (b*b*z)/(a*V)\n\n self.Latitude = math.atan((z + ep2*z0)/r)\n self.Longitude = math.atan2(y , x)\n self.Altitude = U * ( 1.0 - (b*b)/(a*V) )\n \n def PcpfToLlaOsen(self, x, y, z):\n \"\"\"Convert ECEF to geodetic using Osen.\n \n (DO NOT USE; needs debugging)\n \n Karl Osen. Accurate Conversion of Earth-Fixed Earth-Centered \n Coordinates to Geodetic Coordinates. Research Report Norwegian \n University of Science and Technology. 2017\n \"\"\"\n WGS84_INVAA = +2.45817225764733181057e-0014 # 1/(a^2)\n WGS84_EED2 = +3.34718999507065852867e-0003 # (e^2)/2\n WGS84_EEEE = +4.48147234524044602618e-0005 # e^4\n WGS84_EEEED4 = +1.12036808631011150655e-0005 # (e^4)/4\n WGS84_P1MEE = +9.93305620009858682943e-0001 # 1-(e^2)\n WGS84_P1MEEDAA = +2.44171631847341700642e-0014 # (1-(e^2))/(a^2)\n WGS84_INVCBRT2 = +7.93700525984099737380e-0001 # 1/(2^(1/3))\n WGS84_INV3 = +3.33333333333333333333e-0001 # 1/3\n WGS84_INV6 = +1.66666666666666666667e-0001 # 1/6\n \n ww = x * x + y * y\n m = ww * WGS84_INVAA\n n = z * z * WGS84_P1MEEDAA\n mpn = m + n\n p = WGS84_INV6 * (mpn - WGS84_EEEE)\n G = m * n * WGS84_EEEED4\n H = 2 * p * p * p + G\n \n C = ((H + G + 2 * math.sqrt(H * G))**WGS84_INV3) * WGS84_INVCBRT2\n assert C != 0, \"PcpfToLLaOsen C is 0\"\n i = -WGS84_EEEED4 - 0.5 * mpn\n P = p * p\n beta = WGS84_INV3 * i - C - (P / C)\n k = WGS84_EEEED4 * (WGS84_EEEED4 - mpn)\n \n # Compute left part of t\n t1 = beta * beta - k\n assert t1 >= 0, \"PcpfToLLaOsen t1 is negative. t1: {0}\".format(t1)\n t2 = math.sqrt(t1)\n t3 = t2 - 0.5 * (beta + i)\n assert t3 >= 0, \"PcpfToLLaOsen t3 is negative\"\n t4 = math.sqrt(t3)\n # Compute right part of t\n t5 = 0.5 * (beta - i)\n # t5 may accidentally drop just below zero due to numeric turbulence\n # This only occurs at latitudes close to +- 45.3 degrees\n t5 = abs(t5)\n t6 = math.sqrt(t5)\n t7 = t6 if (m < n) else -t6\n # Add left and right parts\n t = t4 + t7\n # Use Newton-Raphson's method to compute t correction\n j = WGS84_EED2 * (m - n)\n g = 2 * j\n tt = t * t\n ttt = tt * t\n tttt = tt * tt\n F = tttt + 2 * i * tt + g * t + k\n dFdt = 4 * ttt + 4 * i * t + g;\n dt = -F / dFdt\n\n # compute latitude (range -PI/2..PI/2)\n u = t + dt + WGS84_EED2\n v = t + dt - WGS84_EED2\n w = math.sqrt(ww)\n zu = z * u\n wv = w * v\n self.Latitude = math.atan2(zu, wv)\n \n # compute altitude\n assert (u*v) != 0, \"PcpfToLlaOsen (u*v) is 0\"\n invuv = 1 / (u * v)\n dw = w - wv * invuv\n dz = z - zu * WGS84_P1MEE * invuv\n da = math.sqrt(dw * dw + dz * dz)\n self.Altitude = -da if (u < 1) else da\n\n # compute longitude (range -PI..PI)\n self.Longitude = math.atan2(y, x);\n \n def AirData(self, altitude):\n pass\n \n def DynamicPressure(self, altitude, trueAirspeed):\n # get dynamic pressure: q = 1/2 rho v^2\n self.AirData(altitude) \n \n dynamicPressure = 0.5 * self.density * trueAirspeed * trueAirspeed\n \n return dynamicPressure\n \n###############################################################################\nclass Earth(Planet):\n \"\"\"An atmospheric and gravity model for Earth.\"\"\"\n def __init__(self):\n self.GM = 3.986004418e14 # GM constant in m3/s2\n self.J2 = 1.082626684e-3\n self.RotationRate = 7.292115e-5 # Earth Rotation Rate (rad/sec, East)\n \n self.SemiMajor = 6378137.0 # WGS84 defined\n self.Flattening = 1/298.257223563 # WGS84 defined\n self.CalcSemiMinor()\n self.CalcEccentricity()\n \n def AirData(self, altitude):\n \"\"\"The 1976 standard atmosphere model.\n \n U.S. Standard Atmosphere, 1976, NASA-TM-X-74335\n \n The height is geopotential height (Z) in meters above MSL. The reference \n for the [US Standard Atmosphere 1976](https://ntrs.nasa.gov/citations/19770009539). \n The refernence for the \n [pressure equation](https://en.wikipedia.org/wiki/Barometric_formula). \n\n Layer | Height (m) | Pressure (Pa) | Temperature (K) | Temperature Lapse Rate (K/m)\n :----:|-----------:|:--------------|:----------------|:----------------------------\n 0 | 0 | 101,325 | 288.15 | -0.0065\n 1 | 11,000 | 22,632.1 | 216.65 | 0\n 2 | 20,000 | 5,474.89 | 216.65 | 0.001\n 3 | 32,000 | 868.019 | 228.65 | 0.0028\n 4 | 47,000 | 110.906 | 270.65 | 0\n 5 | 51,000 | 66.9389 | 270.65 | -0.0028\n 6 | 71,000 | 3.95642 | 214.65 | -0.002\n \n Input: \n geometric altitude in meters\n Output:\n airDensity, temperature, pressure, speedOfSoundMps\n \"\"\"\n # Geopotential Alt (m) table ranges for 1976 US standard atmosphere\n # 0 1 2 3 4 5 6\n Z = [0.0, 11000.0, 20000.0, 32000.0, 47000.0, 51000.0, 71000.0]\n\n # Temperature (K) at start of air layer\n # 0 11000 20000 32000 47000 51000 71000\n T = [288.15, 216.65, 216.65, 228.65, 270.65, 270.65, 214.65]\n\n # Pressure (Pa) at start air layer\n # 0 11000 20000 32000 47000 51000 71000\n P = [101325.0, 22632.10, 5474.89, 868.02, 110.91, 66.94, 3.96]\n\n # Temperature Gradient (K/m) for the altitude ranges\n # 0 11000 20000 32000 47000 51000 71000\n TG = [-6.5e-3, 0, 1.0e-3, 2.8e-3, 0, -2.8e-3, -2.0e-3]\n \n radiusEarth = 6356766.0 # Earth radius for geopotential alt conversion\n p0 = 101325.0 # pressure at sea level (Pa)\n Rgc = 287.0528 # Gas constant (N m / kg K)\n g0 = 9.806645 # gravity at sea level (m / s^2)\n M = 0.0289644 # molar mass of Earth's air (kg/mol)\n Rstar = 8.3144598 # universal gas constant [J/(mol·K)]\n airGamma = 1.4 # gamma value for air\n \n # Convert geometric altitude to geopotential as the standard atmosphere \n # altitude layers are geopotential.\n z0 = radiusEarth * altitude / (radiusEarth + altitude)\n \n # get the index of the atmosphere layer\n i = -1\n count = 0\n for z in Z:\n if count != 0:\n if z0 < z and i == -1:\n i = count - 1\n count += 1\n \n deltaZ = z0 - Z[i] \n \n airTemperature = TG[i] * deltaZ + T[i]\n airTemperature = airTemperature if (airTemperature > 0.0) else 0\n \n airPressure = 0\n # The pressure is calculated differently depending\n # on the temperature lapse rate of the air layer. \n if abs(TG[i]) < 1e-12:\n airPressure = P[i] * math.exp( (-g0 * M * deltaZ) / (Rstar * T[i]) )\n else:\n pe = (-g0 * M) / (Rstar * TG[i])\n airPressure = P[i] * ((T[i] + TG[i] * deltaZ) / T[i])**pe\n \n airDensity = (\n (airPressure / (Rgc * airTemperature)) if (airTemperature > 0.0) else 0\n )\n \n assert airTemperature >= 0, \"temp: {}, alt: {}\".format(airTemperature, altitude)\n airSpeedOfSoundMps = math.sqrt( airGamma * Rgc * airTemperature )\n \n self.density = airDensity\n self.temperature = airTemperature\n self.pressure = airPressure\n self.speedOfSoundMps = airSpeedOfSoundMps\n \n return\n \n def GravityConstant(self):\n \"\"\"Constant gravity value for Earth \"\"\"\n return 9.80665\n \n def GravityWgs84(self, latRad, lonRad, h):\n \"\"\"The WGS-84 model of Earth gravity \"\"\"\n a = self.SemiMajor\n b = self.SemiMinor\n E = self.Eccentricity\n sinPhi = math.sin(latRad)\n sin2Phi = sinPhi**2\n N = a / math.sqrt(1 - E*E*sin2Phi)\n cosPhi = math.cos(latRad)\n cos2Phi = cosPhi**2\n Pr = (N + h) * cosPhi\n ge = 9.7803253359\n gp = 9.8321849378\n g0 = (a*ge + cos2Phi + b*gp*sin2Phi) / math.sqrt(a*a*cos2Phi + b*b*sin2Phi)\n f = (a - b) / a\n w = self.RotationRate\n m = w*w*a*a*b / self.GM\n gh = g0*(1 - 2/a * (1 + f + m - 2*f*sin2Phi)*h + (3*h*h)/(a*a))\n cosLambda = math.cos(lonRad)\n sinLambda = math.sin(lonRad)\n #Ghx = -gh * cosPhi\n GhX = -gh*cosPhi*cosLambda\n GhY = -gh*cosPhi*sinLambda\n GhZ = -gh*sinPhi\n ahc = w*w*Pr\n AhcX = ahc*cosLambda\n AhcY = ahc*sinLambda\n AhcZ = 0\n \n GhGX = GhX - AhcX\n GhGY = GhY - AhcY\n GhGZ = GhZ - AhcZ\n \n return GhGX, GhGZ, GhGZ\n \n def GravityJ2(self, x, y, z):\n \"\"\"The J2 portion of gravity \"\"\"\n r2 = x*x + y*y + z*z\n r = math.sqrt(r2)\n assert r != 0, \"Gravity J2 r is 0\"\n gmOverR3 = -self.GM / (r**3)\n j2Term = (1.5 * self.J2) * (self.SemiMajor)**2 / (r**4)\n z2 = 5.0 * z * z\n \n gx = x * gmOverR3 * (1 - j2Term*(z2 - r2))\n gy = y * gmOverR3 * (1 - j2Term*(z2 - r2))\n gz = z * gmOverR3 * (1 - j2Term*(z2 - 3*r2))\n \n return gx, gy, gz\n \n def GravityJ2SL(self, x, y, z):\n \"\"\"The J2 portion of gravity as defined by Stevens and Lewis \"\"\"\n r = math.sqrt(x*x + y*y + z*z)\n assert r != 0, \"Gravity J2 r is 0\"\n sinPsi2 = (z / r)**2\n aOverR2 = 1.5 * self.J2 * (self.SemiMajor / r)**2\n gmOverR2 = -self.GM/(r**2)\n \n gx = gmOverR2 * (1 + aOverR2 * (1.0 - 5.0*sinPsi2)) * (x / r)\n gy = gmOverR2 * (1 + aOverR2 * (1.0 - 5.0*sinPsi2)) * (y / r)\n gz = gmOverR2 * (1 + aOverR2 * (3.0 - 5.0*sinPsi2)) * (z / r)\n \n return gx, gy, gz\n \n def GravityR2(self, x, y, z):\n \"\"\"Newton gravity equation model \"\"\"\n r2 = x*x + y*y + z*z\n assert r2 != 0, \"GravityR2 r2 is 0\"\n return self.GM/r2\n \n def UnitTest(self):\n self.ClassName = \"Earth\"\n self.TestValue(6356752, self.SemiMinor, \"b\", 1)\n self.TestValue(8.18191908426e-2, self.Eccentricity, \"eccentricity\", 1e-12)\n \n # TODO: fix gravity unit tests\n #self.TestValue(9.7879, self.GravityJ2(0,0), \"gravity\", 1e-4)\n #self.TestValue(9.7848, self.GravityJ2(1000,math.radians(12.34)), \"gravity\", 1e-4)\n #self.TestValue(9.7725, self.GravityJ2(5000,math.radians(24.6621)), \"gravity\", 1e-4)\n #self.TestValue(9.72, self.GravityJ2(25000,math.radians(45.0)), \"gravity\", 1e-2)\n #self.TestValue(9.56, self.GravityJ2(75000,math.radians(65.0)), \"gravity\", 1e-2)\n \n self.ClassName = \"Earth AirData\"\n self.AirData(0)\n self.TestValue(1.225, self.density, \"density at 0m\", 1e-3)\n self.TestValue(288.15, self.temperature, \"temperature at 0m\", 1e-2)\n self.TestValue(101325, self.pressure, \"pressure at 0m\", 1)\n self.TestValue(340.294, self.speedOfSoundMps, \"speed of sound at 0m\", 0.1)\n \n self.AirData(2000)\n self.TestValue(1.00649, self.density, \"density at 2km\", 1e-3)\n self.TestValue(275.156, self.temperature, \"temperature at 2km\", 1e-2)\n self.TestValue(79505.1, self.pressure, \"pressure at 2km\", 10)\n self.TestValue(332.529, self.speedOfSoundMps, \"speed of sound at 2km\", 0.1)\n \n self.AirData(5000)\n self.TestValue(0.736116, self.density, \"density at 5km\", 1e-3)\n self.TestValue(255.676, self.temperature, \"temperature at 5km\", 1e-2)\n self.TestValue(54048.8, self.pressure, \"pressure at 5km\", 10)\n self.TestValue(320.529, self.speedOfSoundMps, \"speed of sound at 5km\", 0.1)\n \n self.AirData(12000)\n self.TestValue(0.310828, self.density, \"density at 12km\", 1e-2)\n self.TestValue(216.65, self.temperature, \"temperature at 12km\", 1e-2)\n self.TestValue(19401, self.pressure, \"pressure at 12km\", 10)\n self.TestValue(295.070, self.speedOfSoundMps, \"speed of sound at 12km\", 0.1)\n \n self.AirData(26000)\n self.TestValue(0.0336882, self.density, \"density at 26km\", 1e-3)\n self.TestValue(222.544, self.temperature, \"temperature at 26km\", 1e-2)\n self.TestValue(2188.41, self.pressure, \"pressure at 26km\", 10)\n self.TestValue(299.128, self.speedOfSoundMps, \"speed of sound at 26km\", 1.0)\n \n #self.ClassName = \"Earth AirData Density\"\n #di = 0 # air density index\n #self.TestValue(1.225, self.AirData(0)[di], \"0m\", 1e-3)\n \n #self.ClassName = \"Earth AirData Temperature\"\n #ti = 1 # temperature index\n #self.TestValue(288.15, self.AirData(0)[ti], \"0m\", 1e-2)\n #self.TestValue(275.156, self.AirData(2000)[ti], \"2km\", 1e-2)\n #self.TestValue(255.676, self.AirData(5000)[ti], \"5km\", 1e-2)\n #self.TestValue(216.65, self.AirData(12000)[ti], \"12km\", 1e-2)\n #self.TestValue(222.544, self.AirData(26000)[ti], \"26km\", 1e-2)\n \n #self.ClassName = \"Earth AirData Pressure\"\n #pi = 2 # pressure index\n #self.TestValue(101325, self.AirData(0)[pi], \"0m\", 1)\n #self.TestValue(79505.1, self.AirData(2000)[pi], \"2km\", 10)\n #self.TestValue(54048.8, self.AirData(5000)[pi], \"5km\", 10)\n #self.TestValue(19401, self.AirData(12000)[pi], \"12km\", 10)\n #self.TestValue(2188.41, self.AirData(26000)[pi], \"26km\", 1)\n \n #self.ClassName = \"Earth AirData Sound\"\n #si = 3 # speed of sound index\n #self.TestValue(340.294, self.AirData(0)[si], \"0m\", 1e-3)\n \n self.ClassName = \"Planet Olsen\"\n self.PcpfToLlaOsen(1191786.0, -5157122.0, 3562840.0)\n self.TestValue(34.123456, math.degrees(self.Latitude), \"lat\", 1e-6)\n self.TestValue(-76.987654, math.degrees(self.Longitude), \"lon\", 1e-6)\n self.TestValue(9000.0, self.Altitude, \"alt\", 1)\n \n self.ClassName = \"Planet Zhu\"\n self.PcpfToLlaZhu(1191786.0, -5157122.0, 3562840.0)\n self.TestValue(34.123456, math.degrees(self.Latitude), \"lat\", 1e-6)\n self.TestValue(-76.987654, math.degrees(self.Longitude), \"lon\", 1e-6)\n self.TestValue(9000.0, self.Altitude, \"alt\", 1)\n \n self.ClassName = \"Planet\"\n self.Latitude = math.radians(34.123456)\n self.Longitude = math.radians(-76.987654)\n self.Altitude = 9000.0\n [x, y, z] = self.LlaToPcpf()\n self.TestValue(1191786.0, x, \"X\", 1)\n self.TestValue(-5157122.0, y, \"Y\", 1)\n self.TestValue(3562840.0, z, \"Z\", 1)\n \n print(\"Number of Earth failed tests: \", self.FailCount)\n \n###############################################################################\nclass Moon(Planet):\n \"\"\"A simple gravity model of the moon.\n \n The reference for the moon parameters is [NESC Academy Presentation]\n (https://nescacademy.nasa.gov/video/02f47c99e5944e20a31931ce78fd4ea21d).\n \"\"\"\n def __init__(self):\n self.RotationRate = 2.6617072235e-6 # Moon Rotation Rate (rad/sec, East)\n self.GM = 4.90154449e12\n self.SemiMajor = 1738140.0\n self.Flattening = 1.0 / 800.98618\n self.CalcSemiMinor()\n self.CalcEccentricity()\n \n def AirData(self, altitude):\n \"\"\"No atmosphere on the moon.\"\"\"\n return\n \n def Gravity(self, altitude, latRad):\n \"\"\"Moon gravity model.\"\"\"\n r = altitude + self.SemiMajor\n gravity = self.GM/r/r\n return gravity\n \n def UnitTest(self):\n self.ClassName = \"Moon\"\n self.TestValue(1.62242, self.Gravity(0,0), \"gravity\", 1e-6)\n \n print(\"Number of Moon failed tests: \", self.FailCount)\n \n###############################################################################\nclass Mars(Planet):\n \"\"\"A gravity and atmosphere model for Mars.\n\n The reference for the [Mars atmosphere model]\n (https://www.grc.nasa.gov/WWW/K-12/airplane/atmosmrm.html). \n \"\"\"\n def __init__(self):\n self.GM = 42828.371901284e9\n self.RotationRate = 7.0882181e-5 # Mars Rotation Rate (rad/sec, East)\n self.SemiMajor = 3.396196e6\n self.J2 = 0.00195545367944545\n self.CalcSemiMinor()\n \n def AirData(self, altitude):\n \"\"\"Returns the Martian air density given the altitude.\"\"\"\n temperatureC = 0\n if altitude > 7000:\n temperatureC = -31 - 0.000998 * altitude\n else:\n temperatureC = -23.4 - 0.00222 * altitude\n\n pressureKPa = 0.699 * math.exp( -0.00009 * altitude )\n airDensity = pressurePa / (0.1921 * (temperatureC + 273.1))\n \n self.density = airDensity\n self.temperature = temperatureC\n self.pressure = pressureKPa\n self.speedOfSoundMps = 0\n \n return\n \n def Gravity(self, altitude, latRad):\n \"\"\"Martian gravity model given the altitude and latitude.\"\"\"\n marsGM = self.GM\n marsRadiusMeter = self.SemiMajor\n J2 = self.J2\n J3 = 3.14498094262035e-5\n J4 = -1.53773961526397e-5\n cosPhi = math.cos( 0.5*math.pi - latRad )\n\n r = altitude + marsRadiusMeter\n rr = marsRadiusMeter / r\n\n gravity = marsGM*(1.0 - 1.5 * J2 * ( 3.0 * cosPhi*cosPhi - 1.0 ) \n * rr*rr - 2.0 * J3 * cosPhi * ( 5.0 * cosPhi*cosPhi - 3.0 ) \n * rr*rr*rr - (5.0/8.0) * J4 * ( 35.0 * cosPhi**4\n - 30.0 * cosPhi*cosPhi + 3.0 ) * rr**4.0 ) / (r*r)\n \n return gravity\n \n def UnitTest(self):\n self.ClassName = \"Mars\"\n self.TestValue(3.724179, self.Gravity(0,0), \"gravity\", 1e-6)\n \n print(\"Number of Mars failed tests: \", self.FailCount)\n \n###############################################################################\nclass Vector3(UnitTest):\n \"\"\"A 3 component vector class\"\"\"\n def __init__(self, x, y, z):\n self.X = x\n self.Y = y\n self.Z = z\n \n # defining how to print the class\n def __str__(self):\n return \"(%s, %s, %s)\" % (self.X, self.Y, self.Z)\n \n # overloading the + to add vectors\n def __add__(self, o):\n x = self.X + o.X\n y = self.Y + o.Y\n z = self.Z + o.Z\n return Vector3(x,y,z)\n \n # overloading the - to subtract vectors\n def __sub__(self, o):\n x = self.X - o.X\n y = self.Y - o.Y\n z = self.Z - o.Z\n return Vector3(x,y,z)\n \n # overloading the ^ for cross product\n def __xor__(self, o):\n x = self.Y * o.Z - self.Z * o.Y\n y = self.Z * o.X - self.X * o.Z\n z = self.X * o.Y - self.Y * o.X\n return Vector3(x,y,z)\n \n # overloading the * to multiply scalars to a vector\n def __mul__(self, s):\n x = self.X * s\n y = self.Y * s\n z = self.Z * s\n return Vector3(x,y,z)\n \n # overloading the / to divide a vector by a scalar\n def __truediv__(self, s):\n x = self.X / s\n y = self.Y / s\n z = self.Z / s\n return Vector3(x,y,z)\n \n __rmul__ = __mul__\n \n def Set(self, x, y, z):\n self.X = x\n self.Y = y\n self.Z = z\n \n def Magnitude(self):\n magnitude = math.sqrt(self.X*self.X + self.Y*self.Y + self.Z*self.Z)\n return magnitude\n \n def UnitTest(self):\n self.ClassName = \"Vector3\"\n v1 = Vector3(21,33,19)\n self.TestValue( 21, v1.X, \"init X\", 1e-6)\n self.TestValue( 33, v1.Y, \"init Y\", 1e-6)\n self.TestValue( 19, v1.Z, \"init Z\", 1e-6)\n v2 = Vector3(21,33,19)\n v3 = Vector3(79,67,81)\n v1 = v2 + v3\n self.TestValue( 100, v1.X, \"add X\", 1e-6)\n self.TestValue( 100, v1.Y, \"add Y\", 1e-6)\n self.TestValue( 100, v1.Z, \"add Z\", 1e-6)\n v4 = Vector3(0,3,-4)\n self.TestValue( 5, v4.Magnitude(), \"magnitude\", 1e-6)\n v4.Set( 87, 16.9, -3.1 )\n self.TestValue( 87, v4.X, \"Set X\", 1e-6)\n self.TestValue( 16.9, v4.Y, \"Set Y\", 1e-6)\n self.TestValue( -3.1, v4.Z, \"Set Z\", 1e-6)\n v5 = v3 - v2\n self.TestValue( 58, v5.X, \"sub X\", 1e-6)\n self.TestValue( 34, v5.Y, \"sub Y\", 1e-6)\n self.TestValue( 62, v5.Z, \"sub Z\", 1e-6)\n v5 = v2 - v3\n self.TestValue( -58, v5.X, \"sub X\", 1e-6)\n self.TestValue( -34, v5.Y, \"sub Y\", 1e-6)\n self.TestValue( -62, v5.Z, \"sub Z\", 1e-6)\n v6 = Vector3(4,12,2)\n v7 = Vector3(13,5,7)\n v8 = v6 ^ v7\n self.TestValue( 74, v8.X, \"cross X\", 1e-6)\n self.TestValue( -2, v8.Y, \"cross Y\", 1e-6)\n self.TestValue( -136, v8.Z, \"cross Z\", 1e-6)\n v9 = 2 * v6\n self.TestValue( 8, v9.X, \"mul X\", 1e-6)\n self.TestValue( 24, v9.Y, \"mul Y\", 1e-6)\n self.TestValue( 4, v9.Z, \"mul Z\", 1e-6)\n v10 = v7 / 2\n self.TestValue( 6.5, v10.X, \"div X\", 1e-6)\n self.TestValue( 2.5, v10.Y, \"div Y\", 1e-6)\n self.TestValue( 3.5, v10.Z, \"div Z\", 1e-6)\n v11 = v10\n self.TestValue( 6.5, v11.X, \"= X\", 1e-6)\n self.TestValue( 2.5, v11.Y, \"= Y\", 1e-6)\n self.TestValue( 3.5, v11.Z, \"= Z\", 1e-6)\n \n print(\"Number of Vector3 failed tests: \", self.FailCount)\n \n###############################################################################\nclass Quaternion(UnitTest):\n \"\"\"A quaternion class for EOM.\n \n Reference for checking [quaternion rotation]\n (https://www.andre-gaschler.com/rotationconverter/). \n \n Quaternion multiplication checked [here]\n (https://www.vcalc.com/wiki/vCalc/Quaternion+Multiplication).\n \n $t=q*r=t_0 + \\mathbf{i}t_1 + \\mathbf{j}t_2 + \\mathbf{k}t_3$ \n $t_0 = q_0r_0 - q_1r_1 - q_2r_2 - q_3r_3$ \n $t_1 = q_1r_0 + q_0r_1 - q_3r_2 + q_2r_3$ \n $t_2 = q_2r_0 + q_3r_1 + q_0r_2 - q_1r_3$ \n $t_3 = q_3r_0 - q_2r_1 + q_1r_2 + q_0r_3$ \n\n System b to a -> $q_{b/a}$\n\n $u^b = q_{b/a}^{-1} * u^a * q_{b/a}$, and $q_{b/a}^{-1} = q_{a/b}$ \n $u^c = q_{c/b}^{-1} q_{b/a}^{-1} \\, u^a \\, q_{b/a} q_{c/b}$\n\n $v^{frd} = q_{\\phi}^{-1} q_{\\theta}^{-1} q_{\\psi}^{-1} \\, v^{ned} \\, q_{\\psi} q_{\\theta} q_{\\phi}$\n\n $q_{frd/ned} = q_{\\psi} q_{\\theta} q_{\\phi} = \n \\begin{matrix}\n \\cos\\frac{\\phi}{2}\\cos\\frac{\\theta}{2}\\cos\\frac{\\psi}{2} + \\sin\\frac{\\phi}{2}\\sin\\frac{\\theta}{2}\\sin\\frac{\\psi}{2}\\\\\n \\sin\\frac{\\phi}{2}\\cos\\frac{\\theta}{2}\\cos\\frac{\\psi}{2} - \\cos\\frac{\\phi}{2}\\sin\\frac{\\theta}{2}\\sin\\frac{\\psi}{2} \\\\\n \\cos\\frac{\\phi}{2}\\sin\\frac{\\theta}{2}\\cos\\frac{\\psi}{2} + \\sin\\frac{\\phi}{2}\\cos\\frac{\\theta}{2}\\sin\\frac{\\psi}{2} \\\\\n \\cos\\frac{\\phi}{2}\\cos\\frac{\\theta}{2}\\sin\\frac{\\psi}{2} - \\sin\\frac{\\phi}{2}\\sin\\frac{\\theta}{2}\\cos\\frac{\\psi}{2}\n \\end{matrix}$\n\n $q_{ned/ecf} = \n \\begin{matrix}\n \\phantom{-} \\cos\\frac{lon}{2} \\cos(\\frac{lat}{2} + 45^{\\circ}) \\\\\n \\phantom{-} \\sin\\frac{lon}{2} \\sin(\\frac{lat}{2} + 45^{\\circ}) \\\\\n -\\cos\\frac{lon}{2} \\sin(\\frac{lat}{2} + 45^{\\circ}) \\\\\n \\phantom{-} \\sin\\frac{lon}{2} \\cos(\\frac{lat}{2} + 45^{\\circ})\n \\end{matrix}$\n\n $\\omega^{frd} = q_{frd/ned}^{-1} q_{ned/ecf}^{-1} \\, \\omega^{ecf} \\, q_{ned/ecf} q_{frd/ned}$\n\n $F^{ecf} = q_{ecf/ned}^{-1} q_{ned/frd}^{-1} \\, F^{frd} \\, q_{ned/frd} q_{ecf/ned}$ \n $\\phantom{F^{ecf}} = q_{ned/ecf} q_{frd/ned} \\, F^{frd} \\, q_{frd/ned}^{-1} q_{ned/ecf}^{-1}$\n\n $v^{ecf} = q_{ecf/ned}^{-1} q_{ned/frd}^{-1} \\, v^{frd} \\, q_{ned/frd} q_{ecf/ned}$ \n $\\phantom{v^{ecf}} = q_{ned/ecf} q_{frd/ned} \\, v^{frd} \\, q_{frd/ned}^{-1} q_{ned/ecf}^{-1}$ \n\n $u^{ned} = q_{ned/frd}^{-1} \\, u^{frd} \\, q_{ned/frd}$ \n $q_{ned/frd}^{-1} = q_{frd/ned}$ \n $u^{ned} = q_{frd/ned} \\, \n \\begin{bmatrix}\n 0 \\\\\n u\n \\end{bmatrix}\n \\, q_{frd/ned}^{-1}$ \n \"\"\"\n def __init__(self, n, x, y, z):\n self.N = n\n self.X = x\n self.Y = y\n self.Z = z\n \n # defining how to print the class\n def __repr__(self):\n return \"(%s, %s, %s, %s)\" % (self.N, self.X, self.Y, self.Z)\n \n # overloading the ~ for quaternion inverse\n def __invert__(self):\n n = self.N\n x = -self.X\n y = -self.Y\n z = -self.Z\n return Quaternion(n,x,y,z)\n \n # overloading the + to add quaternions\n def __add__(self, o):\n n = self.N + o.N\n x = self.X + o.X\n y = self.Y + o.Y\n z = self.Z + o.Z\n return Quaternion(n,x,y,z)\n \n # overlaoding the * to multiply quaternions and multiple scalars and quaternions\n def __mul__(self,o):\n n=0\n x=0\n y=0\n z=0\n if isinstance(o, Quaternion):\n n = self.N*o.N - self.X*o.X - self.Y*o.Y - self.Z*o.Z\n x = self.N*o.X + self.X*o.N + self.Y*o.Z - self.Z*o.Y\n y = self.N*o.Y + self.Y*o.N + self.Z*o.X - self.X*o.Z\n z = self.N*o.Z + self.Z*o.N + self.X*o.Y - self.Y*o.X\n elif isinstance(o, Vector3):\n n = -(self.X*o.X + self.Y*o.Y + self.Z*o.Z)\n x = self.N*o.X + self.Y*o.Z - self.Z*o.Y\n y = self.N*o.Y + self.Z*o.X - self.X*o.Z\n z = self.N*o.Z + self.X*o.Y - self.Y*o.X\n else:\n n = self.N * o\n x = self.X * o\n y = self.Y * o\n z = self.Z * o\n return Quaternion(n,x,y,z)\n \n # so that scalar * quaternion is the same as quaternion * scalar\n __rmul__ = __mul__\n \n def Normalize(self):\n magnitude = math.sqrt(self.N*self.N + self.X*self.X + self.Y*self.Y + self.Z*self.Z)\n \n if magnitude != 0:\n self.N = self.N / magnitude\n self.X = self.X / magnitude\n self.Y = self.Y / magnitude\n self.Z = self.Z / magnitude\n \n def SetRollPitchYaw(self, roll, pitch, yaw):\n qroll = Quaternion( math.cos(0.5*roll) , math.sin(0.5*roll), 0.0 , 0.0)\n qpitch = Quaternion( math.cos(0.5*pitch), 0.0 , math.sin(0.5*pitch), 0.0)\n qyaw = Quaternion( math.cos(0.5*yaw) , 0.0 , 0.0 , math.sin(0.5*yaw))\n\n # ZYX rotation\n q = qyaw*qpitch*qroll\n q.Normalize()\n \n self.N = q.N\n self.X = q.X\n self.Y = q.Y\n self.Z = q.Z\n \n def SetLatLon(self, lat, lon):\n n = math.cos(0.5*lon)*math.cos(0.5*lat + 0.25*math.pi)\n x = math.sin(0.5*lon)*math.sin(0.5*lat + 0.25*math.pi)\n y = -math.cos(0.5*lon)*math.sin(0.5*lat + 0.25*math.pi)\n z = math.sin(0.5*lon)*math.cos(0.5*lat + 0.25*math.pi)\n \n q = Quaternion( n, x, y, z )\n q.Normalize()\n \n self.N = q.N\n self.X = q.X\n self.Y = q.Y\n self.Z = q.Z\n \n def SetQfrdWrtEcf(self, roll, pitch, yaw, lat, lon):\n qroll = Quaternion( math.cos(0.5*roll) , math.sin(0.5*roll), 0.0 , 0.0)\n qpitch = Quaternion( math.cos(0.5*pitch), 0.0 , math.sin(0.5*pitch), 0.0)\n qyaw = Quaternion( math.cos(0.5*yaw) , 0.0 , 0.0 , math.sin(0.5*yaw))\n\n hLon = 0.5*lon\n hLat = 0.5*lat + 0.25*math.pi\n qlon = Quaternion(math.cos(hLon), 0, 0, math.sin(hLon))\n qlat = Quaternion(math.cos(hLat), 0, -math.sin(hLat), 0)\n \n # ZYX rotation\n q = qlon*qlat*qyaw*qpitch*qroll\n \n self.N = q.N\n self.X = q.X\n self.Y = q.Y\n self.Z = q.Z\n \n def SetPlanetRotation(self, rotationAngle_rad):\n n = math.cos(0.5*rotationAngle_rad)\n z = math.sin(0.5*rotationAngle_rad)\n \n q = Quaternion(n, 0.0, 0.0, z)\n q.Normalize()\n \n self.N = q.N\n self.X = q.X\n self.Y = q.Y\n self.Z = q.Z\n \n def EulerAnglesFromQ(self):\n q0 = self.N\n q1 = self.X\n q2 = self.Y\n q3 = self.Z\n \n c11 = q0*q0 + q1*q1 - q2*q2 - q3*q3\n c12 = 2.0*(q1*q2 + q0*q3)\n c13 = 2.0*(q1*q3 - q0*q2)\n c23 = 2.0*(q2*q3 + q0*q1)\n c33 = q0*q0 - q1*q1 - q2*q2 + q3*q3\n \n roll = math.atan2(c23,c33)\n pitch = -math.asin(c13)\n yaw = math.atan2(c12,c11)\n\n return [roll, pitch, yaw] \n \n def EulerAnglesFromQold(self):\n qnn = self.N * self.N\n qxx = self.X * self.X\n qyy = self.Y * self.Y\n qzz = self.Z * self.Z\n \n img = qxx + qyy + qzz + qnn\n assert img != 0, \"EulerAnglesFromQ all elements 0 for quaternion\"\n img = 1.0 / img\n\n m11 = (qnn + qxx - qyy - qzz)*img\n m12 = 2.0*(self.X*self.Y + self.Z*self.N)*img\n m13 = 2.0*(self.X*self.Z - self.Y*self.N)*img\n m23 = 2.0*(self.Y*self.Z + self.X*self.N)*img\n m33 = (qnn - qxx - qyy + qzz)*img\n\n roll = 0\n pitch = 0\n yaw = 0\n if abs(m13) >= 1.0:\n m21 = 2.0*(self.X*self.Y - self.Z*self.N)*img\n m31 = 2.0*(self.X*self.Z + self.Y*self.N)*img;\n roll = 0.0\n halfPi = 0.5*math.pi\n pitch = -halfPi if (m13 > 0.0) else halfPi\n yaw = math.atan2(-m21, -m31/m13)\n else:\n roll = math.atan2(m23,m33) # Roll\n pitch = math.asin(-m13) # Pitch\n yaw = math.atan2(m12,m11) # Yaw\n\n return [roll, pitch, yaw]\n \n def UnitTest(self):\n self.ClassName = \"Quaternion\"\n q0 = Quaternion(4,7,8,9)\n q0i = ~q0\n self.TestValue( 4, q0i.N, \"inverse\", 1e-6)\n self.TestValue(-7, q0i.X, \"inverse\", 1e-6)\n self.TestValue(-8, q0i.Y, \"inverse\", 1e-6)\n self.TestValue(-9, q0i.Z, \"inverse\", 1e-6)\n q1 = Quaternion(2,3,4,5)\n q2 = Quaternion(8,9,10,11)\n q3 = q1 + q2\n self.TestValue(10, q3.N, \"add\", 1e-6)\n self.TestValue(12, q3.X, \"add\", 1e-6)\n self.TestValue(14, q3.Y, \"add\", 1e-6)\n self.TestValue(16, q3.Z, \"add\", 1e-6)\n q4 = q1 * q2\n self.TestValue(-106, q4.N, \"multiply\", 1e-6)\n self.TestValue(36, q4.X, \"multiply\", 1e-6)\n self.TestValue(64, q4.Y, \"multiply\", 1e-6)\n self.TestValue(56, q4.Z, \"multiply\", 1e-6)\n q5 = 7.0 * q1\n self.TestValue(14, q5.N, \"scalar multiply\", 1e-6)\n self.TestValue(21, q5.X, \"scalar multiply\", 1e-6)\n self.TestValue(28, q5.Y, \"scalar multiply\", 1e-6)\n self.TestValue(35, q5.Z, \"scalar multiply\", 1e-6)\n q6 = q2 * 10\n self.TestValue(80, q6.N, \"scalar multiply\", 1e-6)\n self.TestValue(90, q6.X, \"scalar multiply\", 1e-6)\n self.TestValue(100, q6.Y, \"scalar multiply\", 1e-6)\n self.TestValue(110, q6.Z, \"scalar multiply\", 1e-6)\n q6.SetRollPitchYaw(0.3,-0.7,3.11)\n self.TestValue(-0.0365642, q6.N, \"Euler\", 1e-6)\n self.TestValue(0.3412225, q6.X, \"Euler\", 1e-6)\n self.TestValue(0.1350051, q6.Y, \"Euler\", 1e-6)\n self.TestValue(0.9295181, q6.Z, \"Euler\", 1e-6)\n [roll, pitch, yaw] = q6.EulerAnglesFromQ()\n self.TestValue( 0.3, roll, \"EulerFromQ\", 1e-6)\n self.TestValue(-0.7, pitch, \"EulerFromQ\", 1e-6)\n self.TestValue(3.11, yaw, \"EulerFromQ\", 1e-6)\n q7 = Quaternion(0.6680766, 0.2325211, 0.1160514, 0.6972372)\n [roll, pitch, yaw] = q7.EulerAnglesFromQ()\n self.TestValue( 0.5, roll, \"EulerFromQ\", 1e-6)\n self.TestValue(-0.17, pitch, \"EulerFromQ\", 1e-6)\n self.TestValue(1.57, yaw, \"EulerFromQ\", 1e-6)\n q8 = Quaternion(6,-6,6,6)\n q8.Normalize()\n self.TestValue( 0.5, q8.N, \"Normalize\", 1e-6)\n self.TestValue(-0.5, q8.X, \"Normalize\", 1e-6)\n self.TestValue( 0.5, q8.Y, \"Normalize\", 1e-6)\n self.TestValue( 0.5, q8.Z, \"Normalize\", 1e-6)\n q9 = Quaternion(1,3,-2,7)\n q9.Normalize()\n mag = math.sqrt(1 + 9 + 4 + 49)\n self.TestValue( 1.0/mag, q9.N, \"Normalize 2\", 1e-6)\n self.TestValue( 3.0/mag, q9.X, \"Normalize 2\", 1e-6)\n self.TestValue(-2.0/mag, q9.Y, \"Normalize 2\", 1e-6)\n self.TestValue( 7.0/mag, q9.Z, \"Normalize 2\", 1e-6)\n \n print(\"Number of Quaternion failed tests: \", self.FailCount)\n \n###############################################################################\nclass Matrix3x3(UnitTest):\n A11 = 1\n A12 = 0\n A13 = 0\n \n A21 = 0\n A22 = 1\n A23 = 0\n \n A31 = 0\n A32 = 0\n A33 = 1\n \n def __mul__(self, v):\n if isinstance(v, Vector3):\n x = self.A11 * v.X + self.A12 * v.Y + self.A13 * v.Z\n y = self.A21 * v.X + self.A22 * v.Y + self.A23 * v.Z\n z = self.A31 * v.X + self.A32 * v.Y + self.A33 * v.Z\n return Vector3(x,y,z)\n elif isinstance(v, Matrix3x3):\n a11 = self.A11*v.A11 + self.A12*v.A21 + self.A13*v.A31\n a12 = self.A11*v.A12 + self.A12*v.A22 + self.A13*v.A32\n a13 = self.A11*v.A13 + self.A12*v.A23 + self.A13*v.A33\n\n a21 = self.A21*v.A11 + self.A22*v.A21 + self.A23*v.A31\n a22 = self.A21*v.A12 + self.A22*v.A22 + self.A23*v.A32\n a23 = self.A21*v.A13 + self.A22*v.A23 + self.A23*v.A33\n \n a31 = self.A31*v.A11 + self.A32*v.A21 + self.A33*v.A31\n a32 = self.A31*v.A12 + self.A32*v.A22 + self.A33*v.A32\n a33 = self.A31*v.A13 + self.A32*v.A23 + self.A33*v.A33\n \n a = Matrix3x3()\n a.SetRow1( a11, a12, a13 )\n a.SetRow2( a21, a22, a23 )\n a.SetRow3( a31, a32, a33 )\n return a\n \n else:\n a11 = self.A11 * v\n a12 = self.A12 * v\n a13 = self.A13 * v\n a21 = self.A21 * v\n a22 = self.A22 * v\n a23 = self.A23 * v\n a31 = self.A31 * v\n a32 = self.A32 * v\n a33 = self.A33 * v\n a = Matrix3x3()\n a.SetRow1( a11, a12, a13 )\n a.SetRow2( a21, a22, a23 )\n a.SetRow3( a31, a32, a33 )\n return a\n \n \n def SetRow1(self, a11, a12, a13):\n self.A11 = a11\n self.A12 = a12\n self.A13 = a13\n \n def SetRow2(self, a21, a22, a23):\n self.A21 = a21\n self.A22 = a22\n self.A23 = a23\n \n def SetRow3(self, a31, a32, a33):\n self.A31 = a31\n self.A32 = a32\n self.A33 = a33\n \n # defining how to print the class\n def __str__(self):\n row1 = \"(%s, %s, %s)\\n\" % (self.A11, self.A12, self.A13)\n row2 = \"(%s, %s, %s)\\n\" % (self.A21, self.A22, self.A23)\n row3 = \"(%s, %s, %s)\" % (self.A31, self.A32, self.A33)\n return row1+row2+row3\n \n def Determinant(self):\n d1 = self.A11*(self.A22*self.A33 - self.A23*self.A32)\n d2 = self.A12*(self.A23*self.A31 - self.A21*self.A33)\n d3 = self.A13*(self.A21*self.A32 - self.A22*self.A31)\n return d1+d2+d3\n \n def Inverse(self):\n D = self.Determinant()\n\n im = Matrix3x3()\n\n # make sure D is not 0\n if abs(D) > 1e-12:\n a11 = (self.A22*self.A33 - self.A23*self.A32)/D\n a12 = (self.A13*self.A32 - self.A12*self.A33)/D\n a13 = (self.A12*self.A23 - self.A13*self.A22)/D\n\n a21 = (self.A23*self.A31 - self.A21*self.A33)/D\n a22 = (self.A11*self.A33 - self.A13*self.A31)/D\n a23 = (self.A13*self.A21 - self.A11*self.A23)/D\n\n a31 = (self.A21*self.A32 - self.A22*self.A31)/D\n a32 = (self.A12*self.A31 - self.A11*self.A32)/D\n a33 = (self.A11*self.A22 - self.A12*self.A21)/D\n \n im.SetRow1(a11, a12, a13)\n im.SetRow2(a21, a22, a23)\n im.SetRow3(a31, a32, a33)\n \n return im\n \n def Transpose(self): \n at = Matrix3x3()\n at.SetRow1(self.A11, self.A21, self.A31)\n at.SetRow2(self.A12, self.A22, self.A32)\n at.SetRow3(self.A13, self.A23, self.A33)\n return at\n \n def QuaternionToMatrix(self, q):\n n = q.N;\n x = q.X;\n y = q.Y;\n z = q.Z;\n\n self.SetRow1( n*n + x*x - y*y - z*z, 2.0*(x*y - n*z), 2.0*(x*z + n*y) )\n self.SetRow2( 2.0*(x*y + n*z), n*n - x*x + y*y - z*z, 2.0*(y*z - n*x) )\n self.SetRow3( 2.0*(x*z - n*y), 2.0*(y*z + n*x), n*n - x*x - y*y + z*z ) \n \n def UnitTest(self):\n self.ClassName = \"Matrix3\"\n m1 = Matrix3x3()\n m1.SetRow1(1,2,3)\n m1.SetRow2(4,5,6)\n m1.SetRow3(7,3,9)\n self.TestValue(-30, m1.Determinant(), \"Determinant\", 1e-6)\n m1.SetRow1(1,2,3)\n m1.SetRow2(0,1,4)\n m1.SetRow3(5,6,0)\n self.TestValue(1, m1.Determinant(), \"Determinant\", 1e-6)\n m1 = m1.Inverse()\n self.TestValue(-24, m1.A11, \"Inverse A11\", 1e-6)\n self.TestValue( 18, m1.A12, \"Inverse A12\", 1e-6)\n self.TestValue( 5, m1.A13, \"Inverse A13\", 1e-6)\n self.TestValue( 20, m1.A21, \"Inverse A21\", 1e-6)\n self.TestValue(-15, m1.A22, \"Inverse A22\", 1e-6)\n self.TestValue( -4, m1.A23, \"Inverse A23\", 1e-6)\n self.TestValue( -5, m1.A31, \"Inverse A31\", 1e-6)\n self.TestValue( 4, m1.A32, \"Inverse A32\", 1e-6)\n self.TestValue( 1, m1.A33, \"Inverse A33\", 1e-6)\n \n m2 = Matrix3x3()\n m2.SetRow1(1,2,3)\n m2.SetRow2(4,5,6)\n m2.SetRow3(7,2,9)\n m2 = m2.Inverse()\n self.TestValue(-11/12, m2.A11, \"Inverse A11\", 1e-6)\n self.TestValue( 1/3, m2.A12, \"Inverse A12\", 1e-6)\n self.TestValue( 1/12, m2.A13, \"Inverse A13\", 1e-6)\n self.TestValue( -1/6, m2.A21, \"Inverse A21\", 1e-6)\n self.TestValue( 1/3, m2.A22, \"Inverse A22\", 1e-6)\n self.TestValue( -1/6, m2.A23, \"Inverse A23\", 1e-6)\n self.TestValue( 3/4, m2.A31, \"Inverse A31\", 1e-6)\n self.TestValue( -1/3, m2.A32, \"Inverse A32\", 1e-6)\n self.TestValue( 1/12, m2.A33, \"Inverse A33\", 1e-6)\n \n m3 = Matrix3x3()\n m3.SetRow1( 1,2,3)\n m3.SetRow2(-4,5,6)\n m3.SetRow3( 7,8.1,9)\n m4 = m3.Transpose()\n self.TestValue( 1, m3.A11, \"Transpose A11\", 1e-6)\n self.TestValue( 2, m3.A12, \"Transpose A12\", 1e-6)\n self.TestValue( 3, m3.A13, \"Transpose A13\", 1e-6)\n self.TestValue( -4, m3.A21, \"Transpose A21\", 1e-6)\n self.TestValue( 5, m3.A22, \"Transpose A22\", 1e-6)\n self.TestValue( 6, m3.A23, \"Transpose A23\", 1e-6)\n self.TestValue( 7, m3.A31, \"Transpose A31\", 1e-6)\n self.TestValue( 8.1, m3.A32, \"Transpose A32\", 1e-6)\n self.TestValue( 9, m3.A33, \"Transpose A33\", 1e-6)\n self.TestValue( 1, m4.A11, \"Transpose A11\", 1e-6)\n self.TestValue( -4, m4.A12, \"Transpose A12\", 1e-6)\n self.TestValue( 7, m4.A13, \"Transpose A13\", 1e-6)\n self.TestValue( 2, m4.A21, \"Transpose A21\", 1e-6)\n self.TestValue( 5, m4.A22, \"Transpose A22\", 1e-6)\n self.TestValue( 8.1, m4.A23, \"Transpose A23\", 1e-6)\n self.TestValue( 3, m4.A31, \"Transpose A31\", 1e-6)\n self.TestValue( 6, m4.A32, \"Transpose A32\", 1e-6)\n self.TestValue( 9, m4.A33, \"Transpose A33\", 1e-6)\n \n q = Quaternion(0.7, 0.4, 3.2, -0.87)\n q.Normalize()\n m4.QuaternionToMatrix(q)\n self.TestValue( -0.8883823, m4.A11, \"Quaternion A11\", 1e-7)\n self.TestValue( 0.3243782, m4.A12, \"Quaternion A12\", 1e-7)\n self.TestValue( 0.3248933, m4.A13, \"Quaternion A13\", 1e-7)\n self.TestValue( 0.1152238, m4.A21, \"Quaternion A21\", 1e-7)\n self.TestValue( 0.8425504, m4.A22, \"Quaternion A22\", 1e-7)\n self.TestValue( -0.5261486, m4.A23, \"Quaternion A23\", 1e-7)\n self.TestValue( -0.4444101, m4.A31, \"Quaternion A31\", 1e-7)\n self.TestValue( -0.4299857, m4.A32, \"Quaternion A32\", 1e-7)\n self.TestValue( -0.7858829, m4.A33, \"Quaternion A33\", 1e-7)\n \n m1.SetRow1(2,6,3)\n m1.SetRow2(1,1,8)\n m1.SetRow3(5,7,-6)\n \n v1 = Vector3(9,11,-4)\n v2 = m1 * v1\n self.TestValue( 72, v2.X, \"Matrix * Vector X\", 1e-7)\n self.TestValue( -12, v2.Y, \"Matrix * Vector Y\", 1e-7)\n self.TestValue( 146, v2.Z, \"Matrix * Vector Z\", 1e-7)\n \n m1.SetRow1(6,3,17)\n m1.SetRow2(-4,-0.1,7)\n m1.SetRow3(14,5,-1)\n m2.SetRow1(5,0,-6)\n m2.SetRow2(3,8,2)\n m2.SetRow3(-1,-4,-9)\n m3 = m1 * m2\n self.TestValue( 22, m3.A11, \"Matrix * Matrix A11\", 1e-7)\n self.TestValue( -44, m3.A12, \"Matrix * Matrix A12\", 1e-7)\n self.TestValue( -183, m3.A13, \"Matrix * Matrix A13\", 1e-7)\n self.TestValue( -27.3, m3.A21, \"Matrix * Matrix A21\", 1e-7)\n self.TestValue( -28.8, m3.A22, \"Matrix * Matrix A22\", 1e-7)\n self.TestValue( -39.2, m3.A23, \"Matrix * Matrix A23\", 1e-7)\n self.TestValue( 86, m3.A31, \"Matrix * Matrix A31\", 1e-7)\n self.TestValue( 44, m3.A32, \"Matrix * Matrix A32\", 1e-7)\n self.TestValue( -65, m3.A33, \"Matrix * Matrix A33\", 1e-7)\n \n m5 = m2 * 2\n self.TestValue( 10, m5.A11, \"Matrix * Scalar A11\", 1e-7)\n self.TestValue( 0, m5.A12, \"Matrix * Scalar A12\", 1e-7)\n self.TestValue( -12, m5.A13, \"Matrix * Scalar A13\", 1e-7)\n self.TestValue( 6, m5.A21, \"Matrix * Scalar A21\", 1e-7)\n self.TestValue( 16, m5.A22, \"Matrix * Scalar A22\", 1e-7)\n self.TestValue( 4, m5.A23, \"Matrix * Scalar A23\", 1e-7)\n self.TestValue( -2, m5.A31, \"Matrix * Scalar A31\", 1e-7)\n self.TestValue( -8, m5.A32, \"Matrix * Scalar A32\", 1e-7)\n self.TestValue( -18, m5.A33, \"Matrix * Scalar A33\", 1e-7)\n \n print(\"Number of Matrix3x3 failed tests: \", self.FailCount) \n \n###############################################################################\nclass Integrator(UnitTest):\n def AdamsBashforth(self, h, current, past):\n k2 = [1.5, -0.5]\n k3 = [23.0/12.0, -16.0/12.0, 5.0/12.0]\n \n x = h * (k2[0]*current.X + k2[1]*past.X)\n y = h * (k2[0]*current.Y + k2[1]*past.Y)\n z = h * (k2[0]*current.Z + k2[1]*past.Z)\n \n return [x, y, z]\n \n def RungeKutta4(self, h, Fdot, arg):\n k1 = []\n arg1 = []\n for (a, f) in zip(arg, Fdot):\n k = h*f(arg)\n k1.append(k)\n arg1.append(a + 0.5*k)\n \n k2 = []\n arg2 = []\n for (a, f) in zip(arg, Fdot):\n k = h*f(arg1)\n k2.append(k)\n arg2.append(a + 0.5*k)\n \n k3 = []\n arg3 = []\n for (a, f) in zip(arg, Fdot):\n k = h*f(arg2)\n k3.append(k)\n arg3.append(a + k)\n\n k4 = []\n for f in Fdot:\n k4.append( h*f(arg3))\n\n result = []\n for (a, kc1, kc2, kc3, kc4) in zip(arg, k1, k2, k3, k4):\n result.append(a + (kc1 + 2.0*kc2 + 2.0*kc3 + kc4) / 6.0)\n\n return result\n \n def UnitTest(self):\n self.ClassName = \"Integrator\"\n def I1p(arg):\n return (-4.0*arg[0] + 3.0*arg[1] + 6)\n\n def I2p(arg):\n return (-2.4*arg[0] + 1.6*arg[1] + 3.6)\n \n h = 0.1\n Xdot = [I1p, I2p]\n arg = [0, 0]\n T = [.1, .2, .3, .4, .5]\n I1 = [ 0.538255, 0.9684983, 1.310717, 1.581263, 1.793505]\n I2 = [0.3196263, 0.5687817, 0.7607328, 0.9063208, 1.014402]\n for (t,i1,i2) in zip(T,I1,I2):\n wOut = self.RungeKutta4(h, Xdot, arg)\n arg = wOut\n \n self.TestValue( wOut[0], i1, \"Integrator I1\", 1e-5)\n self.TestValue( wOut[1], i2, \"Integrator I2\", 1e-5)\n\n print(\"Number of Integrator failed tests: \", self.FailCount)\n\n###############################################################################\nclass SaveData(Convert):\n # data to record\n Labels = ({\n 'gePosition_ft_X': ['ft', 'm'], \n 'gePosition_ft_Y': ['ft', 'm'], \n 'gePosition_ft_Z': ['ft', 'm'],\n 'feVelocity_ft_s_X': ['ft_s', 'm_s'], \n 'feVelocity_ft_s_Y': ['ft_s', 'm_s'], \n 'feVelocity_ft_s_Z': ['ft_s', 'm_s'],\n 'altitudeMsl_ft': ['ft', 'm'], \n 'longitude_deg': ['deg', 'rad'],\n 'latitude_deg': ['deg', 'rad'],\n 'localGravity_ft_s2': ['ft_s2', 'm_s2'],\n 'eulerAngle_deg_Yaw': ['deg', 'rad'],\n 'eulerAngle_deg_Pitch': ['deg', 'rad'],\n 'eulerAngle_deg_Roll': ['deg', 'rad'],\n 'bodyAngularRateWrtEi_deg_s_Roll': ['deg_s', 'rad_s'],\n 'bodyAngularRateWrtEi_deg_s_Pitch': ['deg_s', 'rad_s'],\n 'bodyAngularRateWrtEi_deg_s_Yaw': ['deg_s', 'rad_s'],\n 'speedOfSound_ft_s': ['ft_s', 'm_s'],\n 'aero_bodyForce_lbf_X': ['lbf', 'N'], \n 'aero_bodyForce_lbf_Y': ['lbf', 'N'], \n 'aero_bodyForce_lbf_Z': ['lbf', 'N'], \n 'trueAirspeed_nmi_h': ['nmi_h', 'm_s'],\n 'eiPosition_ft_X': ['ft', 'm'],\n 'eiPosition_ft_Y': ['ft', 'm'],\n 'eiPosition_ft_Z': ['ft', 'm']\n })\n \n Metric = {}\n Imperial = {}\n \n def SiKey(self, key):\n oUnit = '_'+self.Labels[key][0]\n iUnit = '_'+self.Labels[key][1]\n siKey = key.replace(oUnit, iUnit)\n return siKey\n \n def Init(self):\n self.Clear()\n self.Metric['time'] = []\n for key in self.Labels:\n self.Imperial[key] = []\n siKey = self.SiKey(key)\n self.Metric[siKey] = []\n \n def AddTime(self, value):\n self.Metric['time'].append(value)\n return\n \n def Add(self, label, value):\n self.Metric[label].append(value)\n return\n \n def Make(self): \n for key in self.Labels:\n siKey = self.SiKey(key)\n \n units = self.Labels[key][1] + '->' + self.Labels[key][0]\n self.Imperial[key] = self.ToImperial(self.Metric[siKey],units)\n \n def Clear(self):\n self.Imperial.clear()\n self.Metric.clear()\n \n def UnitTest(self):\n self.ClassName = \"SaveData\"\n \n self.Init()\n \n self.AddTime(1)\n self.AddTime(2)\n self.AddTime(3)\n \n self.Add('gePosition_m_X', 20)\n self.Add('gePosition_m_X', 21)\n self.Add('gePosition_m_X', 22)\n self.Add('gePosition_m_Y', 50)\n self.Add('gePosition_m_Y', 55)\n self.Add('gePosition_m_Y', 60)\n self.Add('feVelocity_m_s_X', 70)\n self.Add('feVelocity_m_s_X', 71)\n self.Add('feVelocity_m_s_X', 72)\n self.Add('altitudeMsl_m', 20)\n self.Add('longitude_rad', 3.14159)\n self.Add('localGravity_m_s2', 9.81)\n self.Add('bodyAngularRateWrtEi_rad_s_Roll', 1.570796)\n self.Add('speedOfSound_m_s', 100.0)\n self.Add('aero_bodyForce_N_X', 90.0)\n self.Add('trueAirspeed_m_s', 150.0)\n \n self.Make()\n \n self.TestValue(1, self.Metric[\"time\"][0], \"time\", 0.1)\n self.TestValue(2, self.Metric[\"time\"][1], \"time\", 0.1)\n self.TestValue(3, self.Metric[\"time\"][2], \"time\", 0.1)\n \n k = 'gePosition_ft_X'\n self.TestValue(65.62, self.Imperial[k][0], k, 0.01)\n self.TestValue(68.90, self.Imperial[k][1], k, 0.01)\n self.TestValue(72.18, self.Imperial[k][2], k, 0.01)\n \n k = 'gePosition_ft_Y'\n self.TestValue(164.04, self.Imperial[k][0], k, 0.01)\n self.TestValue(180.45, self.Imperial[k][1], k, 0.01)\n self.TestValue(196.85, self.Imperial[k][2], k, 0.01)\n \n k = 'feVelocity_ft_s_X'\n self.TestValue(229.66, self.Imperial[k][0], k, 0.01)\n self.TestValue(232.94, self.Imperial[k][1], k, 0.01)\n self.TestValue(236.22, self.Imperial[k][2], k, 0.01)\n \n k = 'altitudeMsl_ft'\n self.TestValue(65.62, self.Imperial[k][0], k, 0.01)\n \n k = 'longitude_deg'\n self.TestValue(180.0, self.Imperial[k][0], k, 0.1)\n \n k = 'localGravity_ft_s2'\n self.TestValue(32.2, self.Imperial[k][0], k, 0.1)\n \n k = 'bodyAngularRateWrtEi_deg_s_Roll'\n self.TestValue(90.0, self.Imperial[k][0], k, 0.1)\n \n k = 'speedOfSound_ft_s'\n self.TestValue(328.08, self.Imperial[k][0], k, 0.01)\n \n k = 'aero_bodyForce_lbf_X'\n self.TestValue(20.23, self.Imperial[k][0], k, 0.01)\n \n k = 'trueAirspeed_nmi_h'\n self.TestValue(291.58, self.Imperial[k][0], k, 0.01)\n \n self.Clear()\n print(\"Number of RecData failed tests: \", self.FailCount)\n \n###############################################################################\nclass Simulation(SaveData):\n def __init__(self, daveFile):\n self.DaveFile = daveFile\n \n Time = 0.0\n timeStep = 0.1\n Data = {}\n IC = {}\n \n AeroModelInput = []\n AeroModel = daveML.Model()\n \n ReferenceWingSpan = 0\n ReferenceWingChord = 0\n ReferenceWingArea = 0\n \n Position = Vector3(0, 0, 0)\n \n TotalMass = 0\n TrueAirspeed = 0\n BodyVelocity = Vector3(0, 0, 0)\n BodyAccel = Vector3(0, 0, 0)\n #BodyForce = Vector3(0, 0, 0)\n BodyAngle = Vector3(0, 0, 0)\n BodyAngularRate = Vector3(0, 0, 0)\n BodyAngularAccel = Vector3(0, 0, 0)\n \n gvJx = 0\n gvJy = 0\n gvJz = 0\n gvJxz = 0\n Gamma = 0\n InertiaMatrix = Matrix3x3()\n InertiaMatrixInverse = Matrix3x3()\n \n aeroBodyForce = Vector3(0, 0, 0)\n aeroBodyMoment = Vector3(0, 0, 0)\n thrustBodyForce = Vector3(0, 0, 0)\n \n RecData = SaveData()\n RecData.Init()\n \n def AdvanceTime(self):\n self.RecData.AddTime(self.Time)\n self.Time += self.timeStep\n \n def AddAeroModelInput(self, input):\n self.AeroModelInput = input\n \n def EvaluateAeroModel(self):\n for d in self.AeroModelInput:\n self.AeroModel.Set(d, self.Data[d])\n self.AeroModel.Update()\n\n def Clear(self):\n self.Time = 0.0\n self.Data.clear()\n self.RecData.Clear()\n self.AeroModelInput.clear()\n \n def CalcAeroBodyForces(self, qS):\n # compute the aero forces in the body frame\n self.aeroBodyForce.X = ( \n qS * self.AeroModel.DataFromName(\"aeroBodyForceCoefficient_X\") \n )\n self.aeroBodyForce.Y = (\n qS * self.AeroModel.DataFromName(\"aeroBodyForceCoefficient_Y\") \n )\n self.aeroBodyForce.Z = (\n qS * self.AeroModel.DataFromName(\"aeroBodyForceCoefficient_Z\") \n )\n \n # save the aero force data\n self.RecData.Add('aero_bodyForce_N_X', self.aeroBodyForce.X)\n self.RecData.Add('aero_bodyForce_N_Y', self.aeroBodyForce.Y)\n self.RecData.Add('aero_bodyForce_N_Z', self.aeroBodyForce.Z)\n \n def CalcAeroBodyMoments(self, qS):\n # calculate the dimensional aero moments\n self.aeroBodyMoment.X = (qS * self.ReferenceWingSpan \n * self.AeroModel.DataFromName(\"aeroBodyMomentCoefficient_Roll\"))\n self.aeroBodyMoment.Y = (qS * self.ReferenceWingChord \n * self.AeroModel.DataFromName(\"aeroBodyMomentCoefficient_Pitch\"))\n self.aeroBodyMoment.Z = (qS * self.ReferenceWingSpan \n * self.AeroModel.DataFromName(\"aeroBodyMomentCoefficient_Yaw\"))\n \n def NormalizeAngle(self, value, lower, upper):\n \"\"\"Returns a value between the range lower and upper.\n \n Example: NormalizeAngle(181, -180, 180) returns -179\n \"\"\"\n angleRange = upper - lower\n rangeValue = value - lower\n return (rangeValue - (math.floor(rangeValue / angleRange) * angleRange)) + lower\n \n def SetValue(self, label, defValue = 0):\n value = 0.0\n infoStr = \"none\"\n \n if label in self.IC:\n value = self.IC[label]\n infoStr = \"[IC case]\"\n elif self.AeroModel.HasName(label):\n valueRaw = self.AeroModel.DataFromName(label)\n units = self.AeroModel.Units(label)\n value = self.ToSI(valueRaw, units)\n infoStr = \"[DML model]\"\n else:\n value = defValue\n infoStr = \"[default]\"\n print(\"++\", label, \"=\", value, infoStr)\n return value\n \n def ResetSimulation(self, ic):\n self.Clear()\n self.RecData.Init()\n \n self.AeroModel.LoadDml(self.DaveFile, False)\n \n self.IC.clear()\n self.IC = self.SetIC(ic)\n #self.IC = ic.copy()\n print(self.IC)\n \n self.timeStep = self.SetValue(\"timeStep\", 0.1)\n \n self.TotalMass = self.SetValue(\"totalMass\", 1)\n assert self.TotalMass != 0, \"TotalMass is 0\"\n \n self.ReferenceWingSpan = self.SetValue(\"referenceWingSpan\")\n self.ReferenceWingChord = self.SetValue(\"referenceWingChord\")\n self.ReferenceWingArea = self.SetValue(\"referenceWingArea\")\n \n self.AeroModel.Set(\"aeroBodyForceCoefficient_X\")\n self.AeroModel.Set(\"aeroBodyForceCoefficient_Y\")\n self.AeroModel.Set(\"aeroBodyForceCoefficient_Z\")\n\n self.AeroModel.Set(\"aeroBodyMomentCoefficient_Roll\")\n self.AeroModel.Set(\"aeroBodyMomentCoefficient_Pitch\")\n self.AeroModel.Set(\"aeroBodyMomentCoefficient_Yaw\")\n \n self.TrueAirspeed = self.SetValue(\"trueAirspeed\")\n \n angleOfAttack = self.SetValue(\"angleOfAttack\")\n angleOfSideslip = self.SetValue(\"angleOfSideslip\")\n u = self.TrueAirspeed * math.cos(angleOfAttack) * math.cos(angleOfSideslip);\n v = self.TrueAirspeed * math.sin(angleOfSideslip);\n w = self.TrueAirspeed * math.sin(angleOfAttack) * math.cos(angleOfSideslip);\n self.BodyVelocity.Set(u, v, w)\n print(\"Vuvw: \", self.BodyVelocity)\n\n self.BodyAccel.Set(0, 0, 0)\n \n # Set the rotation quaternion based on the Euler angles\n rollEulerAngle = self.SetValue(\"eulerAngle_Roll\")\n pitchEulerAngle = self.SetValue(\"eulerAngle_Pitch\")\n yawEulerAngle = self.SetValue(\"eulerAngle_Yaw\")\n self.BodyAngle.Set( rollEulerAngle, pitchEulerAngle, yawEulerAngle )\n\n # Set angular rates\n P = self.SetValue(\"eulerAngleRate_Roll\")\n Q = self.SetValue(\"eulerAngleRate_Pitch\")\n R = self.SetValue(\"eulerAngleRate_Yaw\")\n self.BodyAngularRate.Set( P, Q, R )\n \n # Set the inertia matrix\n i11 = self.SetValue(\"bodyMomentOfInertia_X\")\n i12 = -self.SetValue(\"bodyProductOfInertia_XY\")\n i13 = -self.SetValue(\"bodyProductOfInertia_XZ\")\n\n i21 = -self.SetValue(\"bodyProductOfInertia_YX\")\n i22 = self.SetValue(\"bodyMomentOfInertia_Y\")\n i23 = -self.SetValue(\"bodyProductOfInertia_YZ\")\n\n i31 = -self.SetValue(\"bodyProductOfInertia_XZ\")\n i32 = -self.SetValue(\"bodyProductOfInertia_YZ\")\n i33 = self.SetValue(\"bodyMomentOfInertia_Z\")\n\n self.InertiaMatrix.SetRow1(i11, i12, i13)\n self.InertiaMatrix.SetRow2(i21, i22, i23)\n self.InertiaMatrix.SetRow3(i31, i32, i33)\n \n self.InertiaMatrixInverse = self.InertiaMatrix.Inverse()\n \n self.gvJx = self.InertiaMatrix.A11\n self.gvJy = self.InertiaMatrix.A22\n self.gvJz = self.InertiaMatrix.A33\n self.gvJxz = self.InertiaMatrix.A13\n self.Gamma = (self.gvJx*self.gvJz) - (self.gvJxz*self.gvJxz)\n \n def Reset(self, ic):\n pass\n \n def Operate(self):\n pass\n \n def Run(self, numberOfSeconds):\n endTime = int(numberOfSeconds / self.timeStep) + 1\n for i in range(endTime):\n self.Operate()\n print(\"======done=======\")\n \n def UnitTest(self):\n self.ClassName = \"Simulation\"\n # test normalize angle between -180 and 180 (and -pi and pi)\n pi = math.pi\n for i in range(360):\n ang = i\n if ang > 179:\n ang -= 360\n self.TestValue(ang, self.NormalizeAngle(i, -180.0, 180.0), \"NormalizeAngle\", 0.001)\n \n ri = math.radians(i)\n rang = math.radians(ang)\n self.TestValue(rang, self.NormalizeAngle(ri, -pi, pi), \"NormalizeAngle\", 1e-6) \n \n print(\"Number of Simulation failed tests: \", self.FailCount)\n \n###############################################################################\nclass FlatEarth(Simulation):\n \"\"\" Flat Earth equations.\n \n Create a simulation for a flat Earth model. Singularities exist at the poles. \n Vehicle must be symmetric about the x body axis. Vehicle pitch must stay \n below $90^\\circ$.\n\n Force Equations\n ---------------\n $\\dot{U} = RV - QW - g_D \\, \\sin \\theta + \\frac{X_A + X_T}{m}$ \n $\\dot{V} = PW - RU + g_D \\, \\sin \\phi \\, \\cos \\theta + \\frac{Y_A + Y_T}{m}$ \n $\\dot{W} = QU - PV + g_D \\, \\cos \\phi \\, \\cos \\theta + \\frac{Z_A + Z_T}{m}$ \n In vector form, \n $\\dot{\\vec{v}} = \\frac{F}{m} + R_{n/b} \n \\begin{pmatrix} 0 \\\\ 0 \\\\ g_D \\end{pmatrix} - \\vec{\\omega} \\times \\vec{v}$ \n where $R_{n/b}$ is the rotation matrix from NED to body. \n $R_{n/b} = \n \\begin{bmatrix} \n 1 & 0 & 0 \\\\\n 0 & \\cos \\phi & \\sin \\phi \\\\\n 0 & -\\sin \\phi & \\cos \\phi\n \\end{bmatrix} \n \\begin{bmatrix} \n \\cos \\theta & 0 & -\\sin \\theta \\\\\n 0 & 1 & 0 \\\\\n \\sin \\theta & 0 & \\cos \\theta\n \\end{bmatrix}\n \\begin{bmatrix} \n \\cos \\psi & \\sin \\psi & 0 \\\\\n -\\sin \\psi & \\cos \\psi & 0 \\\\\n 0 & 0 & 1\n \\end{bmatrix}$ \n $R_{b/n} = [R_{n/b}]^T$ \n\n Kinematic equations\n -------------------\n $\\dot{\\phi} = P + \\tan \\theta \\, (Q \\sin \\phi + R \\cos \\phi)$ \n $\\dot{\\theta} = Q \\cos \\phi - R \\sin \\phi$ \n $\\dot{\\psi} = (Q \\sin \\phi + R \\cos \\phi) \\, / \\, \\cos \\theta$ \n In vector form, \n $\\dot{\\Phi} = H {\\omega}^b$, where $H = \n \\begin{pmatrix}\n 1 & \\sin \\phi \\tan \\theta & \\cos \\phi \\tan \\theta \\\\\n 0 & \\cos \\phi & -\\sin \\phi \\\\\n 0 & \\sin \\phi / \\cos \\theta & \\cos \\phi / \\cos \\theta\n \\end{pmatrix}$ \n\n Moment Equations\n ----------------\n $\\Gamma \\dot{P} = J_{xz} [J_x - J_y + J_z]PQ - [J_z(J_z - J_y) + J^2_{xz}]QR + l J_z + n J_{xz}$ \n $J_y \\dot{Q} = (J_z - J_x)PR - J_{xz}(P^2 - R^2) + m$ \n $\\Gamma \\dot{R} = [(J_x - J_y)J_x + J^2_{xz}]PQ - J_{xz}[J_x - J_y + J_z]QR + l J_{xz} n J_x$ \n $\\Gamma = J_x J_z - J^2_{xz}$ \n In vector form, \n $\\dot{\\omega^b_{b/i}} = J^{-1}(M^b - \\omega^b_{b/i} J \\omega^b_{b/i} )$\n\n Navigation Equations\n --------------------\n $\\dot{p_N} = U c\\theta c\\psi + V(-c\\phi s\\psi + s\\phi s\\theta c\\psi) \n + W(s\\phi s\\psi + c\\phi s\\theta c\\psi)$ \n $\\dot{p_E} = U c\\theta s\\psi + V(c\\phi c\\psi + s\\phi s\\theta s\\psi)\n + W(-s\\phi c\\psi + c\\phi s\\theta c\\psi)$ \n $\\dot{h} = U s\\theta - V s\\phi c\\theta - W c\\phi c\\theta$ \n In vector form, \n $\\dot{\\vec{p}} = R_{b/n} \\vec{v}$\n \"\"\"\n gD = 0\n mass = 0\n \n Planet = Earth()\n \n # Integrator\n Integrator = Integrator()\n \n # state values\n X = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]\n \n # state DFE\n Xdot = []\n \n # the indices of the state list\n Ui = 0\n Vi = 1\n Wi = 2\n \n ϕi = 3\n θi = 4\n ψi = 5\n \n Pi = 6\n Qi = 7\n Ri = 8\n \n Ni = 9\n Ei = 10\n Zi = 11\n \n def Udot(self, state):\n V = state[self.Vi]\n W = state[self.Wi]\n Q = state[self.Qi]\n R = state[self.Ri]\n sinθ = math.sin(state[self.θi])\n \n assert self.mass != 0.0, \"Udot mass is 0\"\n value = R*V - Q*W - self.gD*sinθ + (self.aeroBodyForce.X + self.thrustBodyForce.X) / self.mass\n return value\n \n def Vdot(self, state):\n U = state[self.Ui]\n W = state[self.Wi]\n P = state[self.Pi]\n R = state[self.Ri]\n sinϕ = math.sin(state[self.ϕi])\n cosθ = math.cos(state[self.θi])\n \n assert self.mass != 0.0, \"Vdot mass is 0\"\n value = -R*U + P*W + self.gD*sinϕ*cosθ + (self.aeroBodyForce.Y + self.thrustBodyForce.Y) / self.mass\n return value\n \n def Wdot(self, state):\n U = state[self.Ui]\n V = state[self.Vi]\n P = state[self.Pi]\n Q = state[self.Qi]\n cosϕ = math.cos(state[self.ϕi])\n cosθ = math.cos(state[self.θi])\n \n assert self.mass != 0.0, \"Wdot mass is 0\"\n value = Q*U - P*V + self.gD*cosϕ*cosθ + (self.aeroBodyForce.Z + self.thrustBodyForce.Z) / self.mass\n return value\n \n def ϕdot(self, state):\n P = state[self.Pi]\n Q = state[self.Qi]\n R = state[self.Ri]\n \n assert state[self.θi] < abs(math.radians(90.0)), \"θdot tanθ is 90\"\n tanθ = math.tan(state[self.θi])\n sinϕ = math.sin(state[self.ϕi])\n cosϕ = math.cos(state[self.ϕi])\n \n value = P + tanθ * (Q*sinϕ + R*cosϕ)\n return value\n \n def θdot(self, state):\n Q = state[self.Qi]\n R = state[self.Ri]\n cosϕ = math.cos(state[self.ϕi])\n sinϕ = math.sin(state[self.ϕi])\n \n value = Q*cosϕ - R*sinϕ\n return value\n \n def ψdot(self, state):\n Q = state[self.Qi]\n R = state[self.Ri]\n cosϕ = math.cos(state[self.ϕi])\n sinϕ = math.sin(state[self.ϕi])\n cosθ = math.cos(state[self.θi])\n \n assert cosθ != 0.0, \"ψdot cosθ is 0\"\n value = (Q*sinϕ + R*cosϕ) / cosθ\n return value\n \n def Pdot(self, state):\n P = state[self.Pi]\n Q = state[self.Qi]\n R = state[self.Ri]\n Jx = self.gvJx\n Jy = self.gvJy\n Jz = self.gvJz\n Jxz = self.gvJxz\n l = self.aeroBodyMoment.X\n n = self.aeroBodyMoment.Z\n \n assert self.Gamma != 0.0, \"Pdot Gamma is 0\"\n value = (Jxz * (Jx - Jy + Jz)*P*Q - (Jz*(Jz - Jy) + Jxz*Jxz)*Q*R + Jz*l + Jxz*n) / self.Gamma\n return value\n \n def Qdot(self, state):\n P = state[self.Pi]\n Q = state[self.Qi]\n R = state[self.Ri]\n Jx = self.gvJx\n Jy = self.gvJy\n Jz = self.gvJz\n Jxz = self.gvJxz\n m = self.aeroBodyMoment.Y\n\n assert Jy != 0.0, \"Qdot Jy is 0\"\n value = ((Jz - Jx)*P*R - Jxz*(P*P - R*R) + m) / Jy\n return value\n \n def Rdot(self, state):\n P = state[self.Pi]\n Q = state[self.Qi]\n R = state[self.Ri]\n Jx = self.gvJx\n Jy = self.gvJy\n Jz = self.gvJz\n Jxz = self.gvJxz\n l = self.aeroBodyMoment.X\n n = self.aeroBodyMoment.Z\n \n assert self.Gamma != 0.0, \"Pdot Gamma is 0\"\n value = (((Jx - Jy)*Jx + Jxz*Jxz)*P*Q - Jxz*(Jx - Jy + Jz)*Q*R + Jxz*l + Jx*n) / self.Gamma\n return value\n \n def Ndot(self, state):\n U = state[self.Ui]\n V = state[self.Vi]\n W = state[self.Wi]\n cosϕ = math.cos(state[self.ϕi])\n sinϕ = math.sin(state[self.ϕi])\n cosθ = math.cos(state[self.θi])\n sinθ = math.sin(state[self.θi])\n cosψ = math.cos(state[self.ψi])\n sinψ = math.sin(state[self.ψi])\n \n value = U*cosθ*cosψ + V*(-cosϕ*sinψ + sinϕ*sinθ*cosψ)\n + W*(sinϕ*sinψ + cosϕ*sinθ*cosψ)\n return value\n \n def Edot(self, state):\n U = state[self.Ui]\n V = state[self.Vi]\n W = state[self.Wi]\n cosϕ = math.cos(state[self.ϕi])\n sinϕ = math.sin(state[self.ϕi])\n cosθ = math.cos(state[self.θi])\n sinθ = math.sin(state[self.θi])\n cosψ = math.cos(state[self.ψi])\n sinψ = math.sin(state[self.ψi])\n \n value = U*cosθ*sinψ + V*(cosϕ*cosψ + sinϕ*sinθ*sinψ)\n + W*(-sinϕ*cosψ + cosϕ*sinθ*sinψ)\n return value\n \n def Zdot(self, state):\n U = state[self.Ui]\n V = state[self.Vi]\n W = state[self.Wi]\n cosϕ = math.cos(state[self.ϕi])\n sinϕ = math.sin(state[self.ϕi])\n cosθ = math.cos(state[self.θi])\n sinθ = math.sin(state[self.θi])\n \n value = U*sinθ - V*sinϕ*cosθ - W*cosϕ*cosθ\n return value\n \n def Reset(self, ic):\n self.ResetSimulation(ic)\n \n self.gD = self.Planet.GravityConstant()\n self.mass = self.TotalMass\n \n self.Xdot.clear()\n self.Xdot = [self.Udot, self.Vdot, self.Wdot, self.ϕdot, self.θdot, self.ψdot, \n self.Pdot, self.Qdot, self.Rdot, self.Ndot, self.Edot, self.Zdot]\n \n self.X[self.Ui] = self.BodyVelocity.X\n self.X[self.Vi] = self.BodyVelocity.Y\n self.X[self.Wi] = self.BodyVelocity.Z\n \n self.X[self.ϕi] = self.BodyAngle.X\n self.X[self.θi] = self.BodyAngle.Y\n self.X[self.ψi] = self.BodyAngle.Z\n \n self.X[self.Pi] = self.BodyAngularRate.X\n self.X[self.Qi] = self.BodyAngularRate.Y\n self.X[self.Ri] = self.BodyAngularRate.Z\n \n self.X[self.Ni] = self.Position.X\n self.X[self.Ei] = self.Position.Y\n self.X[self.Zi] = self.SetValue(\"altitudeMsl\")\n \n def Operate(self):\n # save output data\n self.RecData.Add('localGravity_m_s2', self.gD)\n self.RecData.Add('altitudeMsl_m', self.X[self.Zi])\n self.RecData.Add('eulerAngle_rad_Roll', self.X[self.ϕi])\n self.RecData.Add('eulerAngle_rad_Pitch', self.X[self.θi])\n self.RecData.Add('eulerAngle_rad_Yaw', self.NormalizeAngle(self.X[self.ψi],-math.pi,math.pi))\n self.RecData.Add('trueAirspeed_m_s', self.TrueAirspeed)\n \n # integrate the equations\n self.X = self.Integrator.RungeKutta4(self.timeStep, self.Xdot, self.X)\n \n # Now advance time and update state equations\n self.AdvanceTime()\n \n u = self.X[self.Ui]\n v = self.X[self.Vi]\n w = self.X[self.Wi]\n self.TrueAirspeed = math.sqrt(u*u + v*v + w*w)\n \n # get dynamic pressure: q = 1/2 rho v^2\n dynamicPressure = (\n self.Planet.DynamicPressure(self.X[self.Zi], self.TrueAirspeed)\n )\n\n # Get the qS factor for getting dimensional forces and moments\n qS = dynamicPressure * self.ReferenceWingArea\n\n # Compute the aerodynamic loads\n assert self.TrueAirspeed != 0, \"TrueAirspeed is 0 to model\"\n self.Data[\"trueAirspeed\"] = self.TrueAirspeed * self.MeterToFeet\n self.Data[\"bodyAngularRate_Roll\"] = self.X[self.Pi]\n self.Data[\"bodyAngularRate_Pitch\"] = self.X[self.Qi]\n self.Data[\"bodyAngularRate_Yaw\"] = self.X[self.Ri]\n self.EvaluateAeroModel()\n \n # Aero forces (Newtons) body\n self.CalcAeroBodyForces(qS)\n \n # Aero moments\n self.CalcAeroBodyMoments(qS)\n \n###############################################################################\nclass slEarthSim(Simulation):\n \"\"\"\n The software implements the oblate rotating planet EOM as derived in \n [Stevens and Lewis]\n (https://bcs.wiley.com/he-bcs/Books?action=index&itemId=0471371459&itemTypeId=BKS&bcsId=2073). \n \n Equations in LaTeX format:\n \n $\\dot{q_0} = -0.5 * (Pq_1 + Qq_2 + Rq_3)$ \n $\\dot{q_1} = 0.5 * (Pq_0 + Rq_2 - Qq_3)$ \n $\\dot{q_2} = 0.5 * (Qq_0 - Rq_1 + Pq_3)$ \n $\\dot{q_3} = 0.5 * (Rq_0 + Qq_1 - Pq_2)$ \n\n $\\dot{P_x} = V_x$ \n $\\dot{P_y} = V_y$ \n $\\dot{P_z} = V_z$ \n where $P$ and $V$ are in the ECEF frame.\n\n $\\dot{v_x} = \\frac{F_x}{m} + 2 \\omega_e V_y + g_x + P_x \\omega^2_e$ \n $\\dot{v_y} = \\frac{F_y}{m} - 2 \\omega_e V_x + g_y + P_y \\omega^2_e$ \n $\\dot{v_z} = \\frac{F_z}{m} + g_z$ \n where $\\omega_e$ is the rotation rate of Earth. The terms $g_x$, $g_y$, \n and $g_z$ are the $J_2$ gravity components in ECEF. This acceleration equation \n is in the ECEF frame.\n\n $\\Gamma \\dot{P} = J_{xz} [J_x - J_y + J_z]PQ - [J_z(J_z - J_y) + J^2_{xz}]QR \n + l J_z + n J_{xz}$ \n $J_y \\dot{Q} = (J_z - J_x)PR - J_{xz}(P^2 - R^2) + m$ \n $\\Gamma \\dot{R} = [(J_x - J_y)J_x + J^2_{xz}]PQ - J_{xz}[J_x - J_y + J_z]QR \n + l J_{xz} n J_x$ \n where $\\Gamma = J_x J_z - J^2_{xz}$ \n \"\"\"\n Planet = Earth()\n RotationAngle = 0\n EarthRotation = Quaternion(0, 0, 0, Planet.RotationRate)\n \n # Earth rotatation in body frame\n Per = 0\n Qer = 0\n Rer = 0\n \n # quaternion frame rotations\n # i = inertial frame ECI\n # e = earth centered, earth fixed ECEF\n # n = north east down NED\n # b = body forward right down FRD\n Qe2n = Quaternion(1,0,0,0)\n Qn2b = Quaternion(1,0,0,0)\n Qe2b = Quaternion(1,0,0,0)\n Qi2e = Quaternion(1,0,0,0)\n \n QforceEcf = Quaternion(0,0,0,0)\n \n # ECEF gravity components\n Gx = 0\n Gy = 0\n Gz = 0\n \n Integrator = Integrator()\n \n # state values: quaternion, position, acceleration and angular rates\n X = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]\n \n # the state differential equations\n Xdot = []\n \n # the indices of the state list\n Qni = 0\n Qxi = 1\n Qyi = 2\n Qzi = 3\n \n Xi = 4\n Yi = 5\n Zi = 6\n \n Vxi = 7\n Vyi = 8\n Vzi = 9\n \n Pi = 10\n Qi = 11\n Ri = 12\n \n def Qstate(self,state):\n q0 = state[self.Qni]\n q1 = state[self.Qxi]\n q2 = state[self.Qyi]\n q3 = state[self.Qzi]\n p = state[self.Pi] - self.Per\n q = state[self.Qi] - self.Qer\n r = state[self.Ri] - self.Rer\n return q0, q1, q2, q3, p, q, r\n def QnDot(self, state):\n q0, q1, q2, q3, p, q, r = self.Qstate(state)\n qnDot = -0.5*(q1*p + q2*q + q3*r)\n return qnDot\n def QxDot(self, state):\n q0, q1, q2, q3, p, q, r = self.Qstate(state)\n qxDot = 0.5*(q0*p + q2*r - q3*q)\n return qxDot\n def QyDot(self, state):\n q0, q1, q2, q3, p, q, r = self.Qstate(state)\n qyDot = 0.5*(q0*q - q1*r + q3*p )\n return qyDot\n def QzDot(self, state):\n q0, q1, q2, q3, p, q, r = self.Qstate(state)\n qzDot = 0.5*(q0*r + q1*q - q2*p)\n return qzDot\n \n def PxDot(self, state):\n return state[self.Vxi]\n def PyDot(self, state):\n return state[self.Vyi]\n def PzDot(self, state):\n return state[self.Vzi]\n \n def VxDot(self, state):\n w = self.Planet.RotationRate\n assert self.TotalMass != 0, \"VxDot mass is 0\"\n ax = self.QforceEcf.X / self.TotalMass\n xDot = ax + 2.0 * w * state[self.Vyi] + self.Gx + state[self.Xi] * w**2\n return xDot\n def VyDot(self, state):\n w = self.Planet.RotationRate\n assert self.TotalMass != 0, \"VyDot mass is 0\"\n ay = self.QforceEcf.Y / self.TotalMass\n yDot = ay - 2.0 * w * state[self.Vxi] + self.Gy + state[self.Yi] * w**2 \n return yDot\n def VzDot(self, state):\n assert self.TotalMass != 0, \"VzDot mass is 0\"\n az = self.QforceEcf.Z / self.TotalMass\n return (az + self.Gz)\n \n def Wstate(self, state):\n P = state[self.Pi]\n Q = state[self.Qi]\n R = state[self.Ri]\n Jx = self.gvJx\n Jy = self.gvJy\n Jz = self.gvJz\n Jxz = self.gvJxz\n Gamma = self.Gamma\n l = self.aeroBodyMoment.X\n m = self.aeroBodyMoment.Y\n n = self.aeroBodyMoment.Z\n return P, Q, R, Jx, Jy, Jz, Jxz, Gamma, l, m, n\n def Pdot(self, state):\n P, Q, R, Jx, Jy, Jz, Jxz, Gamma, l, m, n = self.Wstate(state)\n assert Gamma != 0, \"Pdot Gamma is 0\"\n pDot = (Jxz * (Jx - Jy + Jz)*P*Q - (Jz*(Jz - Jy) + Jxz*Jxz)*Q*R + Jz*l + Jxz*n) / Gamma\n return pDot\n def Qdot(self, state):\n P, Q, R, Jx, Jy, Jz, Jxz, Gamma, l, m, n = self.Wstate(state)\n assert Jy != 0.0, \"Qdot Jy is 0\"\n qDot = ((Jz - Jx)*P*R - Jxz*(P*P - R*R) + m) / Jy\n return qDot\n def Rdot(self, state):\n P, Q, R, Jx, Jy, Jz, Jxz, Gamma, l, m, n = self.Wstate(state)\n assert Gamma != 0.0, \"Rdot Gamma is 0\"\n rDot = (((Jx - Jy)*Jx + Jxz*Jxz)*P*Q - Jxz*(Jx - Jy + Jz)*Q*R + Jxz*l + Jx*n) / Gamma\n return rDot\n \n def Reset(self, ic):\n self.ResetSimulation(ic)\n \n self.RotationAngle = 0\n \n self.Planet.Latitude = self.SetValue(\"latitude\")\n self.Planet.Longitude = self.SetValue(\"longitude\")\n self.Planet.Altitude = self.SetValue(\"altitudeMsl\")\n [x, y, z] = self.Planet.LlaToPcpf()\n self.Position.X = x\n self.Position.Y = y\n self.Position.Z = z\n \n # initialize the frd/ecf quaternion\n roll = self.BodyAngle.X\n pitch = self.BodyAngle.Y\n yaw = self.BodyAngle.Z\n lat = self.Planet.Latitude\n lon = self.Planet.Longitude\n self.Qe2b.SetQfrdWrtEcf(roll , pitch , yaw, lat, lon)\n \n # transform u,v,w to ECEF velocities\n Vecf = Vector3(0,0,0)\n Vecf = self.Qe2b * self.BodyVelocity * ~self.Qe2b\n \n self.Xdot.clear()\n self.Xdot = [self.QnDot, self.QxDot, self.QyDot, self.QzDot,\n self.PxDot, self.PyDot, self.PzDot,\n self.VxDot, self.VyDot, self.VzDot,\n self.Pdot, self.Qdot, self.Rdot] \n \n self.X[self.Qni] = self.Qe2b.N\n self.X[self.Qxi] = self.Qe2b.X\n self.X[self.Qyi] = self.Qe2b.Y\n self.X[self.Qzi] = self.Qe2b.Z\n \n self.X[self.Xi] = self.Position.X\n self.X[self.Yi] = self.Position.Y\n self.X[self.Zi] = self.Position.Z\n \n self.X[self.Vxi] = Vecf.X\n self.X[self.Vyi] = Vecf.Y\n self.X[self.Vzi] = Vecf.Z\n print(\"Vecf: \", Vecf.X, Vecf.Y, Vecf.Z)\n \n self.X[self.Pi] = self.BodyAngularRate.X\n self.X[self.Qi] = self.BodyAngularRate.Y\n self.X[self.Ri] = self.BodyAngularRate.Z\n \n def Operate(self):\n # create quaternions\n \n # TODO: need a check case the Q rotations\n # set q frd/ecf (e2b) ECF to body\n self.Qe2b.N = self.X[self.Qni]\n self.Qe2b.X = self.X[self.Qxi]\n self.Qe2b.Y = self.X[self.Qyi]\n self.Qe2b.Z = self.X[self.Qzi]\n \n # set q ned/ecf (e2n) ECF to NED\n self.Qe2n.SetLatLon(self.Planet.Latitude, self.Planet.Longitude)\n \n # set q frd/ned (n2b) NED to body\n self.Qn2b = ~self.Qe2n * self.Qe2b\n \n # get the euler angles from the quaternion\n [roll, pitch, yaw] = self.Qn2b.EulerAnglesFromQ()\n \n # rotate the ECF position to ECI to get the inertial position\n self.Qi2e.SetPlanetRotation(self.RotationAngle)\n qgePosition = Quaternion( 0, self.X[self.Xi], self.X[self.Yi], self.X[self.Zi] )\n qeiPosition = self.Qi2e * qgePosition * ~self.Qi2e\n \n # save output data\n self.RecData.Add('altitudeMsl_m', self.Planet.Altitude)\n self.RecData.Add('latitude_rad', self.Planet.Latitude)\n self.RecData.Add('longitude_rad', self.Planet.Longitude)\n self.RecData.Add('gePosition_m_X', self.X[self.Xi])\n self.RecData.Add('gePosition_m_Y', self.X[self.Yi])\n self.RecData.Add('gePosition_m_Z', self.X[self.Zi])\n self.RecData.Add('eulerAngle_rad_Roll', roll)\n self.RecData.Add('eulerAngle_rad_Pitch', pitch)\n self.RecData.Add('eulerAngle_rad_Yaw', yaw)\n self.RecData.Add('trueAirspeed_m_s', self.TrueAirspeed)\n self.RecData.Add('eiPosition_m_X', qeiPosition.X)\n self.RecData.Add('eiPosition_m_Y', qeiPosition.Y)\n self.RecData.Add('eiPosition_m_Z', qeiPosition.Z)\n \n # get earth rotation in the body frame\n wEarthFrd = ~self.Qe2b * self.EarthRotation * self.Qe2b\n \n # set the Earth rotation in the body frame\n self.Per = wEarthFrd.X\n self.Qer = wEarthFrd.Y\n self.Rer = wEarthFrd.Z\n \n x = self.X[self.Xi]\n y = self.X[self.Yi]\n z = self.X[self.Zi]\n [self.Gx, self.Gy, self.Gz] = self.Planet.GravityJ2( x, y, z )\n g = Vector3(self.Gx, self.Gy, self.Gz)\n self.RecData.Add('localGravity_m_s2', g.Magnitude())\n\n # integrate the equations\n self.X = self.Integrator.RungeKutta4(self.timeStep, self.Xdot, self.X)\n \n # advance time and set up for next integration\n self.AdvanceTime()\n \n # Compute the aerodynamic loads from the DAVE-ML model\n # set the DAVE-ML model inputs\n vel = Vector3(self.X[self.Vxi], self.X[self.Vyi], self.X[self.Vzi])\n self.TrueAirspeed = vel.Magnitude()\n assert self.TrueAirspeed != 0, \"TrueAirspeed is 0 to model\"\n # calculate alpha and beta\n uvw = ~self.Qe2b * vel * self.Qe2b\n self.Data[\"angleOfAttack\"] = math.atan2(uvw.Z, uvw.X)\n self.Data[\"angleOfSideslip\"] = math.atan2(uvw.Y, math.sqrt(uvw.X**2 + uvw.Z**2))\n self.Data[\"trueAirspeed\"] = self.TrueAirspeed * self.MeterToFeet\n self.Data[\"bodyAngularRate_Roll\"] = self.X[self.Pi]\n self.Data[\"bodyAngularRate_Pitch\"] = self.X[self.Qi]\n self.Data[\"bodyAngularRate_Yaw\"] = self.X[self.Ri]\n self.EvaluateAeroModel()\n \n # get dynamic pressure: q = 1/2 rho v^2\n dynamicPressure = (\n self.Planet.DynamicPressure(self.Planet.Altitude, self.TrueAirspeed)\n )\n self.RecData.Add('speedOfSound_m_s', self.Planet.speedOfSoundMps)\n\n # Get the qS factor for getting dimensional forces and moments\n qS = dynamicPressure * self.ReferenceWingArea\n \n # compute the aero forces in the body frame\n self.CalcAeroBodyForces(qS)\n \n # rotate body forces to the ECEF frame\n self.QforceEcf = self.Qe2b * self.aeroBodyForce * ~self.Qe2b\n \n # calculate the dimensional aero moments\n self.CalcAeroBodyMoments(qS)\n \n # update the latitude, longitude and altitude from ECEF X, Y, Z position\n self.Planet.PcpfToLlaZhu(self.X[self.Xi], self.X[self.Yi], self.X[self.Zi])\n \n # rotate the earth\n self.RotationAngle = self.Planet.RotationRate * self.Time\n","repo_name":"TreyArthur/Pierpont","sub_path":"pierpont/ppont.py","file_name":"ppont.py","file_ext":"py","file_size_in_byte":94291,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"}
+{"seq_id":"12142619958","text":"# -*- coding: utf-8 -*-\n# GovHK Data.One Datasets Scraper\n# Sammy Fung \nimport scrapy\nimport re\nfrom govhk_dataone.items import GovhkDataoneItem\n\nclass DataoneSpider(scrapy.Spider):\n name = \"dataone\"\n allowed_domains = [\"gov.hk\"]\n start_urls = (\n 'http://www.gov.hk/en/theme/psi/datasets/',\n )\n\n def parse(self, response):\n #response.xpath(\"//span[contains(@class, 'dataName')]/a/text()\").extract()\n for i in response.xpath(\"//span[contains(@class, 'dataName')]/a/@href\").extract():\n yield scrapy.Request(\"http://www.gov.hk%s\"%i, callback=self.parse_dataset)\n\n def parse_dataset(self, response):\n lastUpdate = response.xpath(\"//p[contains(@id, 'lastUpdate')]/text()\")[0].extract()\n lastUpdate = re.sub('^.*date: ', '', lastUpdate)\n datasetTitle = response.xpath(\"//meta[contains(@name, 'description')]/@content\").extract()[0]\n datasetDatetime = response.xpath(\"//meta[contains(@name, 'date')]/@content\").extract()[0]\n for dataset in response.xpath(\"//tr[contains(@class, 'odd')]/td/a\"):\n item = GovhkDataoneItem()\n item['datasetUrl'] = dataset.xpath(\"@href\").extract()[0]\n item['datasetTitle'] = datasetTitle\n item['datasetType'] = dataset.xpath(\"@title\").extract()[0]\n item['lastUpdate'] = lastUpdate\n item['lastupdateDatetime'] = datasetDatetime\n item['sourceUrl'] = response.url\n yield item\n","repo_name":"sammyfung/govhk-dataone-scraper","sub_path":"govhk_dataone/govhk_dataone/spiders/dataone.py","file_name":"dataone.py","file_ext":"py","file_size_in_byte":1433,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"21"}
+{"seq_id":"43667233070","text":"\"\"\"Bad multiprocessing, without lock.\n\nThe total might be different on different runs.\n\"\"\"\nimport time\nimport multiprocessing\n\n\ndef deposit(balance):\n for i in range(100):\n time.sleep(0.01)\n balance.value = balance.value + 1\n\n\ndef withdraw(balance):\n for i in range(100):\n time.sleep(0.01)\n balance.value = balance.value - 1\n\n\nif __name__ == '__main__':\n NUM_RUNS = 20\n profit_values = []\n currency = 'gold bars'\n print('The output should always be 200 {}, but sometimes it will be wrong.'.format(currency))\n print('The program will now run {} times...'.format(NUM_RUNS))\n for _ in range(NUM_RUNS):\n balance = multiprocessing.Value('i', 200)\n d = multiprocessing.Process(target=deposit, args=(balance,))\n w = multiprocessing.Process(target=withdraw, args=(balance,))\n\n d.start()\n w.start()\n\n d.join()\n w.join()\n\n if balance.value == 200:\n print('balance value is {}'.format(balance.value))\n else:\n off_by = balance.value-200\n profit_values.append(off_by)\n print('balance value is {} (ERROR: your bank account is off by {} {})'.format(balance.value, off_by, currency))\n profit = sum(profit_values)\n print('your bank account is now off by {} {}.'.format(profit, currency))\n","repo_name":"j127/python_tutorials","sub_path":"python_multiprocess/05_multiprocessing_lock_BAD_WAY.py","file_name":"05_multiprocessing_lock_BAD_WAY.py","file_ext":"py","file_size_in_byte":1336,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"}
+{"seq_id":"32150995979","text":"\"\"\"empty message\n\nRevision ID: d5add345c871\nRevises: 62ccd4610de8\nCreate Date: 2022-09-26 06:17:25.327976\n\n\"\"\"\nfrom alembic import op\nimport sqlalchemy as sa\n\n\n# revision identifiers, used by Alembic.\nrevision = 'd5add345c871'\ndown_revision = '62ccd4610de8'\nbranch_labels = None\ndepends_on = None\n\n\ndef upgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.drop_constraint('popular_user_key', 'popular', type_='unique')\n op.drop_column('popular', 'user')\n # ### end Alembic commands ###\n\n\ndef downgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.add_column('popular', sa.Column('user', sa.VARCHAR(), autoincrement=False, nullable=False))\n op.create_unique_constraint('popular_user_key', 'popular', ['user'])\n # ### end Alembic commands ###\n","repo_name":"dcambur/FAF-191-PAD","sub_path":"game_stat/migrations/versions/d5add345c871_.py","file_name":"d5add345c871_.py","file_ext":"py","file_size_in_byte":815,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"}
+{"seq_id":"72828329654","text":"#创建一个列表\nLists = [\"country\",\"city\",\"language\",\"hello\",\"custom\",\"music\",\"book\",\"computer\",\"mountain\",\"sub\"]\n#在列表末尾添加一个元素\nLists.append(\"add\")\n#在指定位置插入一个元素\nLists.insert(0,\"river\")\n#del 删除一个元素\ndel Lists[-2]\n#pop弹出一个最后元素\nLists.pop()\n#pop弹出第五个元素\nLists.pop(4)\n#删除列表中的元素computer\nLists.remove(\"computer\")\n#打印列表\nprint(Lists)\n#获取列表的长度并打印\nprint(len(Lists))\n#按字母顺序进行��打印\nprint(sorted(Lists))\n#将列表进行永久性排序\nLists.sort()\n#逆向排序\nLists.reverse()\n#将列表输出\nprint(Lists)\n\n\n\n\n","repo_name":"leexiulian/learn-python","sub_path":"conprehensive.py","file_name":"conprehensive.py","file_ext":"py","file_size_in_byte":648,"program_lang":"python","lang":"zh","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"}
+{"seq_id":"12759953441","text":"class TrieNode:\n def __init__(self):\n self.next = {}\n self.isEnd = False \n \nclass WordFilter:\n\n def __init__(self, words: List[str]):\n self.root = TrieNode()\n self.indexMap = {word:i for i, word in enumerate(words)}\n for word in words:\n self.add(\"#\" + word, self.root)\n for i in range(len(word)):\n self.add(word[-i:] + \"#\" + word, self.root)\n \n def add(self, word, root):\n cur = root\n for ch in word:\n if ch not in cur.next:\n cur.next[ch] = TrieNode()\n cur = cur.next[ch] \n cur.isEnd = True \n \n def dfs_findLongest(self, cur, path):\n if cur.isEnd: \n return self.indexMap[\"\".join(path)]\n res = -1\n for ch in cur.next:\n path.append(ch)\n res = max(res, self.dfs_findLongest(cur.next[ch], path) )\n path.pop() \n return res \n def f(self, prefix: str, suffix: str) -> int:\n \n cur = self.root\n for ch in suffix:\n if ch not in cur.next:\n return -1\n cur = cur.next[ch]\n if \"#\" not in cur.next:\n return -1\n \n cur = cur.next[\"#\"] \n for ch in prefix: \n if ch not in cur.next:\n return -1\n cur = cur.next[ch] \n \n path = [prefix] \n return self.dfs_findLongest(cur, path)\n \n# Your WordFilter object will be instantiated and called as such:\n# obj = WordFilter(words)\n# param_1 = obj.f(prefix,suffix)\n","repo_name":"YohansHailu/competitive_programming","sub_path":"trie/prefix-and-suffix-search.py","file_name":"prefix-and-suffix-search.py","file_ext":"py","file_size_in_byte":1602,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"}
+{"seq_id":"35088769366","text":"import pandas as pd\nimport numpy as np\nfrom map_soc import soc_names\n\ndef find_frequency_by_soc(mentions_file, frequency_file, soc_frequency_file):\n print(\"reading mentions\")\n mentions_df = pd.read_csv(mentions_file, index_col=None, dtype={\"soc_code\":str, \"soc_name\":str})\n frequency_df = pd.read_csv(frequency_file, index_col=None)\n \n print(\"finding soc frequency\")\n map_df = mentions_df[[\"profession\",\"no_pos_sense\",\"soc_code\",\"soc_name\"]].dropna(subset=[\"soc_code\"]).drop_duplicates()\n merge_frequency_df = frequency_df.merge(map_df, on=[\"profession\",\"no_pos_sense\"])\n \n records = []\n years = frequency_df.columns[2:]\n\n for i in range(23):\n soc_code = str(11 + 2*i)\n soc_name = soc_names[i]\n record = [soc_code, soc_name] + merge_frequency_df.loc[merge_frequency_df.soc_code.str.contains(soc_code), years].sum().values.tolist()\n records.append(record)\n\n record = [\"100\", \"STEM\"] + merge_frequency_df.loc[merge_frequency_df.soc_code.str.match(\"(15)|(17)|(19)|(29)\") | merge_frequency_df.no_pos_sense.str.match(\"(doctor.n.04)\"), years].sum().values.tolist()\n records.append(record)\n\n soc_frequency_df = pd.DataFrame(records, columns=[\"soc_code\",\"soc_name\"] + years.tolist())\n\n print(\"saving soc frequency file\")\n soc_frequency_df.to_csv(soc_frequency_file, index=False)\n\nif __name__ == \"__main__\":\n # find_frequency_by_soc(\"data/mentions/mentions.word_filtered.sense_filtered.soc_mapped.merged.csv\", \"data/mentions/frequency.csv\", \"data/analysis_data/soc_frequency.csv\")\n # find_frequency_by_soc(\"data/mentions/mentions.word_filtered.sense_filtered.soc_mapped.merged.csv\", \"data/mentions/frequency.sample.csv\", \"data/analysis_data/soc_frequency.sample.csv\")\n # find_frequency_by_soc(\"data/mentions/mentions.word_filtered.sense_filtered.soc_mapped.merged.csv\", \"data/mentions/frequency.cutoff.csv\", \"data/analysis_data/soc_frequency.cutoff.csv\")\n find_frequency_by_soc(\"data/mentions/mentions.word_filtered.sense_filtered.soc_mapped.merged.csv\", \"data/mentions/frequency.year.csv\", \"data/analysis_data/soc_frequency.year.csv\")","repo_name":"sabyasachee/mica-profession","sub_path":"plos/src/find_frequency_by_soc.py","file_name":"find_frequency_by_soc.py","file_ext":"py","file_size_in_byte":2114,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"21"}
+{"seq_id":"69905372532","text":"'''Given the head of a linked list, return the node where the cycle begins. If there is no cycle, return null.'''\n\n# Definition for singly-linked list.\nclass ListNode:\n def __init__(self, x):\n self.val = x\n self.next = None\n\nclass Solution:\n def detectCycle(self, head: ListNode):\n # initiate fast and slow pointer both starting at head\n fast, slow = head, head\n # while there is a fast and a fast's next...\n while fast and fast.next:\n # check if a cycle exists\n fast = fast.next.next\n slow = slow.next\n # if cycle, store the value they met up at\n if slow == fast:\n break\n # no cycle so return None\n else:\n return None\n \n # now we check for the node where cycle starts\n # set another pointer to start again at the head\n pointer = head\n # move both pointer and fast one node at a time til they match\n while pointer != fast:\n pointer = pointer.next \n fast = fast.next\n # once out of that while loop, we should have the cycle starter node\n return pointer\n\n \n# Space = O(1)","repo_name":"lisamqy/algorithms","sub_path":"LinkedLists/LinkedListCycleII.py","file_name":"LinkedListCycleII.py","file_ext":"py","file_size_in_byte":1193,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"}
+{"seq_id":"41009448432","text":"from collections import deque\nimport math\nimport os\nimport random\nimport time\n\n\ndef maintain_dialog_history(history, observation, reply='',\n historyLength=1, useReplies='label_else_model',\n dict=None, useStartEndIndices=True,\n splitSentences=False):\n \"\"\"Keeps track of dialog history, up to a truncation length.\n Either includes replies from the labels, model, or not all using param 'replies'.\"\"\"\n\n def parse(txt, splitSentences):\n if dict is not None:\n if splitSentences:\n vec = [dict.txt2vec(t) for t in txt.split('\\n')]\n else:\n vec = dict.txt2vec(txt)\n return vec\n else:\n return [txt]\n\n if 'dialog' not in history:\n history['dialog'] = deque(maxlen=historyLength)\n history['episode_done'] = False\n history['labels'] = []\n\n if history['episode_done']:\n history['dialog'].clear()\n history['labels'] = []\n useReplies = 'none'\n history['episode_done'] = False\n\n if useReplies != 'none':\n if useReplies == 'model' or (useReplies == 'label_else_model' and\n len(history['labels']) == 0):\n if reply:\n history['dialog'].extend(parse(reply, splitSentences))\n elif len(history['labels']) > 0:\n r = history['labels'][0]\n history['dialog'].extend(parse(r, splitSentences))\n\n obs = observation\n if 'text' in obs:\n if useStartEndIndices:\n obs['text'] = dict.end_token + ' ' + obs['text']\n history['dialog'].extend(parse(obs['text'], splitSentences))\n\n history['episode_done'] = obs['episode_done']\n\n labels = obs.get('labels', obs.get('eval_labels', None))\n if labels is not None:\n if useStartEndIndices:\n history['labels'] = [dict.start_token + ' ' + l for l in labels]\n else:\n history['labels'] = labels\n\n return history['dialog']\n\n\ndef load_cands(path, lines_have_ids = False, cands_are_replies = False):\n \"\"\"Load global fixed set of candidate labels that the teacher provides\n every example (the true labels for a specific example are also added to\n this set, so that it's possible to get the right answer).\n \"\"\"\n if path is None:\n return None\n cands = []\n cnt = 0\n with open(path) as read:\n for line in read:\n line = line.strip().replace('\\\\n', '\\n')\n if len(line) > 0:\n cnt = cnt + 1\n # If lines are numbered we strip them of numbers.\n if cnt == 1 and line[0:2] == '1 ':\n lines_have_ids = True\n # If tabs then the label_candidates are all the replies.\n if '\\t' in line and not cands_are_replies:\n cands_are_replies = True\n cands = []\n if lines_have_ids:\n space_idx = line.find(' ')\n line = line[space_idx + 1:]\n if cands_are_replies:\n sp = line.split('\\t')\n if len(sp) > 1 and sp[1] != '':\n cands.append(sp[1])\n else:\n cands.append(line)\n else:\n cands.append(line)\n return cands\n\n\nclass Predictor(object):\n \"\"\"Provides functionality for setting up a running version of a model and\n requesting predictions from that model on live data.\n\n Note that this maintains no World state (does not use a World), merely\n providing the observation directly to the model and getting a response.\n\n This is limiting when it comes to certain use cases, but is\n \"\"\"\n\n def __init__(self, args=None, **kwargs):\n \"\"\"Initializes the predictor, setting up opt automatically if necessary.\n\n Args is expected to be in the same format as sys.argv: e.g. a list in\n the form ['--model', 'seq2seq', '-hs', 128, '-lr', 0.5].\n\n kwargs is interpreted by appending '--' to it and replacing underscores\n with hyphens, so 'dict_file=/tmp/dict.tsv' would be interpreted as\n '--dict-file /tmp/dict.tsv'.\n \"\"\"\n from parlai.core.params import ParlaiParser\n from parlai.core.agents import create_agent\n\n if args is None:\n args = []\n for k, v in kwargs.items():\n args.append('--' + str(k).replace('_', '-'))\n args.append(str(v))\n parser = ParlaiParser(True, True)\n self.opt = parser.parse_args(args)\n self.agent = create_agent(self.opt)\n\n def predict(self, observation):\n \"\"\"From a ParlAI-standard observation dict, returns a prediction from\n the model.\n \"\"\"\n if 'episode_done' not in observation:\n observation['episode_done'] = True\n self.agent.observe(observation)\n reply = self.agent.act()\n return reply\n\n\nclass Timer(object):\n \"\"\"Computes elapsed time.\"\"\"\n def __init__(self):\n self.running = True\n self.total = 0\n self.start = time.time()\n\n def reset(self):\n self.running = True\n self.total = 0\n self.start = time.time()\n return self\n\n def resume(self):\n if not self.running:\n self.running = True\n self.start = time.time()\n return self\n\n def stop(self):\n if self.running:\n self.running = False\n self.total += time.time() - self.start\n return self\n\n def time(self):\n if self.running:\n return self.total + time.time() - self.start\n return self.total\n\n\nclass TimeLogger():\n def __init__(self):\n self.timer = Timer()\n self.tot_time = 0\n\n def total_time(self):\n return self.tot_time\n\n def time(self):\n return self.timer.time()\n\n def log(self, done, total, report={}):\n self.tot_time += self.timer.time()\n self.timer.reset()\n log = {}\n log['exs'] = done\n if total > 0:\n log['%done'] = done / total\n if log[\"%done\"] > 0:\n log['time_left'] = str(int(self.tot_time / log['%done'] - self.tot_time)) + 's'\n z = '%.2f' % ( 100*log['%done'])\n log['%done'] = str(z) + '%'\n for k, v in report.items():\n if k not in log:\n log[k] = v\n text = str(int(self.tot_time)) + \"s elapsed: \" + str(log)\n return text, log\n\nclass AttrDict(dict):\n \"\"\"Helper class to have a dict-like object with dot access.\n\n For example, instead of `d = {'key': 'value'}` use\n `d = AttrDict(key='value')`.\n To access keys, instead of doing `d['key']` use `d.key`.\n\n While this has some limitations on the possible keys (for example, do not\n set the key `items` or you will lose access to the `items()` method), this\n can make some code more clear.\n \"\"\"\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n self.__dict__ = self\n\n\ndef round_sigfigs(x, sigfigs=4):\n try:\n if x == 0:\n return 0\n return round(x, -math.floor(math.log10(abs(x)) - sigfigs + 1))\n except (RuntimeError, TypeError):\n # handle 1D torch tensors\n # if anything else breaks here please file an issue on Github\n if hasattr(x, 'item'):\n return round_sigfigs(x.item(), sigfigs)\n else:\n return round_sigfigs(x[0], sigfigs)\n except (ValueError, OverflowError) as ex:\n if x in [float('inf'), float('-inf')] or x != x: # inf or nan\n return x\n else:\n raise ex\n\n\ndef flatten(teacher, context_length=-1, include_labels=True):\n \"\"\"Return a flattened version of a teacher's data where all episodes only\n have length one but contain the desired amount of context.\n\n If context_length is not -1, will use only that many past utterances.\n Default is -1. Setting it to one only uses the input text.\n\n If include_labels is True, will include a random label in past utterances.\n Default is True.\n \"\"\"\n data = []\n current = []\n episode_done = False\n context_length = context_length if context_length >= 0 else None\n context = deque(maxlen=context_length)\n try:\n while not teacher.epoch_done():\n # collect examples in episode\n while not episode_done:\n action = teacher.act()\n current.append(action)\n episode_done = action['episode_done']\n\n # build separate episodes from each example\n for ex in current:\n context.append(ex.get('text', ''))\n if len(context) != 1:\n ex['text'] = '\\n'.join(context)\n ex['episode_done'] = True\n if include_labels:\n # add labels to context\n labels = ex.get('labels', ex.get('eval_labels'))\n if labels is not None:\n context.append(random.choice(labels))\n data.append(ex)\n # reset flags and content\n episode_done = False\n current.clear()\n context.clear()\n return data\n except MemoryError as ex:\n raise MemoryError('Ran out of memory building flattened data batches. '\n 'Try using --context-length set to a small value to '\n 'limit the length of each flattened example, '\n 'disabling batch sorting / flattening by setting '\n '--batch-sort false, or switching to data streaming '\n 'using --datatype {type}:stream to read from disk '\n 'if it is supported for your dataset.')\n\n\ndef sort_data(data, key='text_label', method='spaces'):\n \"\"\"Given a list of data, sort it according to the method and key.\n\n Currently the only supported method is counting the number of spaces.\n This appeared to be reliable enough and much faster than tokenizing.\n It performs much better than just using the length of the string.\n\n Currently the only supported key is sorting by first the text, then the\n label.\n See https://arxiv.org/abs/1706.05765 for an evaluation of alternative\n approaches for machine translation.\n Sorting by the source (text) gives a good improvement in speed over random\n batching and is robust to different types of optimization.\n Breaking ties by sorting by label length gives a further improvement in\n speed but can reduce robustness with some optimization schemes.\n \"\"\"\n # TODO: support different keys and different methods\n tpls = []\n for ex in data:\n # first sort by input length\n fst = ex.get('text', '').count(' ')\n\n # then sort by target length (don't sort by eval_labels, no need)\n snd = 0\n labels = ex.get('labels', None)\n if labels is not None:\n # use average label length (probably just one answer usually)\n snd = sum(l.count(' ') for l in labels) / len(labels)\n\n tiebreaker = random.random()\n tpls.append((fst, snd, tiebreaker, ex))\n tpls.sort()\n return [e[-1] for e in tpls]\n\n\ndef make_batches(data, bsz):\n \"\"\"Return a list of lists of size bsz given a list of examples.\"\"\"\n return [data[i:i + bsz] for i in range(0, len(data), bsz)]\n\n\nclass NoLock(object):\n \"\"\"Empty `lock`. Does nothing when you enter or exit.\"\"\"\n def __enter__(self):\n return self\n def __exit__(self, exc_type, exc_value, exc_traceback):\n pass\n\n\nsingle_nolock = NoLock()\ndef no_lock():\n \"\"\"Builds a nolock for other classes to use for no-op locking.\"\"\"\n return single_nolock\n\n\nclass ProgressLogger(object):\n \"\"\"\n Throttles and display progress in human readable form.\n Default throttle speed is 1 sec\n \"\"\"\n def __init__(self, throttle=1, should_humanize=True):\n self.latest = time.time()\n self.throttle_speed = throttle\n self.should_humanize = should_humanize\n\n def humanize(self, num, suffix='B'):\n if num < 0:\n return num\n for unit in ['', 'Ki', 'Mi', 'Gi', 'Ti', 'Pi', 'Ei', 'Zi']:\n if abs(num) < 1024.0:\n return \"%3.1f%s%s\" % (num, unit, suffix)\n num /= 1024.0\n return \"%.1f%s%s\" % (num, 'Yi', suffix)\n\n def log(self, curr, total, width=40, force=False):\n \"\"\"Displays a bar showing the current progress.\"\"\"\n if curr == 0 and total == -1:\n print('[ no data received for this file ]', end='\\r')\n return\n curr_time = time.time()\n if not force and curr_time - self.latest < self.throttle_speed:\n return\n else:\n self.latest = curr_time\n\n self.latest = curr_time\n done = min(curr * width // total, width)\n remain = width - done\n\n if self.should_humanize:\n curr = self.humanize(curr)\n total = self.humanize(total)\n\n progress = '[{}{}] {} / {}'.format(\n ''.join(['|'] * done),\n ''.join(['.'] * remain),\n curr,\n total\n )\n print(progress, end='\\r')\n\n\nclass PaddingUtils(object):\n \"\"\"\n Class that contains functions that help with padding input and target tensors.\n \"\"\"\n @classmethod\n def pad_text(cls, observations, dictionary, end_idx=None, null_idx=0, dq=False, eval_labels=True, truncate=None):\n \"\"\"We check that examples are valid, pad with zeros, and sort by length\n so that we can use the pack_padded function. The list valid_inds\n keeps track of which indices are valid and the order in which we sort\n the examples.\n dq -- whether we should use deque or list\n eval_labels -- whether or not we want to consider eval labels\n truncate -- truncate input and output lengths\n \"\"\"\n def valid(obs):\n # check if this is an example our model should actually process\n return 'text' in obs and len(obs['text']) > 0\n try:\n # valid examples and their indices\n valid_inds, exs = zip(*[(i, ex) for i, ex in\n enumerate(observations) if valid(ex)])\n except ValueError:\n # zero examples to process in this batch, so zip failed to unpack\n return None, None, None, None, None, None\n\n # `x` text is already tokenized and truncated\n # sort by length so we can use pack_padded\n if any(['text2vec' in ex for ex in exs]):\n parsed_x = [ex['text2vec'] for ex in exs]\n else:\n parsed_x = [dictionary.txt2vec(ex['text']) for ex in exs]\n\n if len(parsed_x) > 0 and not isinstance(parsed_x[0], deque):\n if dq:\n parsed_x = [deque(x, maxlen=truncate) for x in parsed_x]\n elif truncate is not None and truncate > 0:\n parsed_x = [x[-truncate:] for x in parsed_x]\n\n x_lens = [len(x) for x in parsed_x]\n ind_sorted = sorted(range(len(x_lens)), key=lambda k: -x_lens[k])\n\n exs = [exs[k] for k in ind_sorted]\n valid_inds = [valid_inds[k] for k in ind_sorted]\n parsed_x = [parsed_x[k] for k in ind_sorted]\n end_idxs = [x_lens[k] for k in ind_sorted]\n\n eval_labels_avail = any(['eval_labels' in ex for ex in exs])\n labels_avail = any(['labels' in ex for ex in exs])\n if eval_labels:\n some_labels_avail = eval_labels_avail or labels_avail\n else:\n some_labels_avail = labels_avail\n\n max_x_len = max(x_lens)\n\n # pad with zeros\n if dq:\n parsed_x = [x if len(x) == max_x_len else\n x + deque((null_idx,)) * (max_x_len - len(x))\n for x in parsed_x]\n else:\n parsed_x = [x if len(x) == max_x_len else\n x + [null_idx] * (max_x_len - len(x))\n for x in parsed_x]\n xs = parsed_x\n\n\n # set up the target tensors\n ys = None\n labels = None\n y_lens = None\n if some_labels_avail:\n # randomly select one of the labels to update on (if multiple)\n if labels_avail:\n labels = [random.choice(ex.get('labels', [''])) for ex in exs]\n else:\n labels = [random.choice(ex.get('eval_labels', [''])) for ex in exs]\n # parse each label and append END\n if dq:\n parsed_y = [deque(maxlen=truncate) for _ in labels]\n for dq, y in zip(parsed_y, labels):\n dq.extendleft(reversed(dictionary.txt2vec(y)))\n else:\n parsed_y = [dictionary.txt2vec(label) for label in labels]\n if end_idx is not None:\n for y in parsed_y:\n y.append(end_idx)\n\n y_lens = [len(y) for y in parsed_y]\n max_y_len = max(y_lens)\n\n if dq:\n parsed_y = [y if len(y) == max_y_len else\n y + deque((null_idx,)) * (max_y_len - len(y))\n for y in parsed_y]\n else:\n parsed_y = [y if len(y) == max_y_len else\n y + [null_idx] * (max_y_len - len(y))\n for y in parsed_y]\n ys = parsed_y\n\n return xs, ys, labels, valid_inds, end_idxs, y_lens\n\n @classmethod\n def map_predictions(cls, predictions, valid_inds, batch_reply, observations, dictionary, end_idx, report_freq=0.1, labels=None, answers=None, ys=None):\n \"\"\"Predictions are mapped back to appropriate indices in the batch_reply\n using valid_inds.\n report_freq -- how often we report predictions\n \"\"\"\n for i in range(len(predictions)):\n # map the predictions back to non-empty examples in the batch\n # we join with spaces since we produce tokens one at a timelab\n curr = batch_reply[valid_inds[i]]\n output_tokens = []\n j = 0\n for c in predictions[i]:\n if c == end_idx and j != 0:\n break\n else:\n output_tokens.append(c)\n j += 1\n curr_pred = dictionary.vec2txt(output_tokens)\n curr['text'] = curr_pred\n\n if labels is not None and answers is not None and ys is not None:\n y = []\n for c in ys[i]:\n if c == end_idx:\n break\n else:\n y.append(c)\n answers[valid_inds[i]] = y\n elif answers is not None:\n answers[valid_inds[i]] = curr_pred\n\n if random.random() > (1 - report_freq):\n # log sometimes\n print('TEXT: ', observations[valid_inds[i]]['text'])\n print('PREDICTION: ', curr_pred, '\\n~')\n return\n\n\nclass OffensiveLanguageDetector(object):\n \"\"\"Detects offensive language using a list of offensive language and phrases\n from https://github.com/LDNOOBW.\n \"\"\"\n\n def __init__(self):\n import parlai.core.build_data as build_data\n from parlai.core.params import ParlaiParser\n from parlai.core.dict import DictionaryAgent\n self.tokenize = DictionaryAgent.split_tokenize\n\n parser = ParlaiParser(False, False)\n\n def _path():\n # Build the data if it doesn't exist.\n build()\n return os.path.join(self.datapath, 'OffensiveLanguage', 'OffensiveLanguage.txt')\n\n def build():\n version = 'v1.0'\n dpath = os.path.join(self.datapath, 'OffensiveLanguage')\n if not build_data.built(dpath, version):\n print('[building data: ' + dpath + ']')\n if build_data.built(dpath):\n # An older version exists, so remove these outdated files.\n build_data.remove_dir(dpath)\n build_data.make_dir(dpath)\n\n # Download the data.\n fname = 'OffensiveLanguage.txt'\n url = 'http://parl.ai/downloads/offensive_language/' + fname\n build_data.download(url, dpath, fname)\n\n # Mark the data as built.\n build_data.mark_done(dpath, version)\n\n self.datapath = os.path.join(parser.parlai_home, 'data')\n self.datafile = _path()\n\n # store a token trie: e.g.\n # {'2': {'girls': {'1': {'cup': {'__END__': True}}}}\n self.END = '__END__'\n self.offensive_trie = {}\n self.max_len = 1\n with open(self.datafile, 'r') as f:\n for p in f.read().splitlines():\n self.add_phrase(p)\n\n def add_phrase(self, phrase):\n \"\"\"Adds a single phrase to the trie.\"\"\"\n toks = self.tokenize(phrase)\n curr = self.offensive_trie\n for t in toks:\n if t not in curr:\n curr[t] = {}\n curr = curr[t]\n curr[self.END] = True\n self.max_len = max(self.max_len, len(toks))\n\n def add_words(self, phrase_list):\n \"\"\"Add list of custom phrases to the filter.\"\"\"\n for phrase in phrase_list:\n self.add_phrase(phrase)\n\n def check_sequence(self, toks, idx, node):\n \"\"\"Check if words from the sequence are in the trie.\n\n This checks phrases made from\n toks[i], toks[i:i+2] ... toks[i:i + self.max_len]\n \"\"\"\n right = min(idx + self.max_len, len(toks))\n for i in range(idx, right):\n if toks[i] in node:\n node = node[toks[i]]\n if self.END in node:\n return ' '.join(toks[j] for j in range(idx, i + 1))\n else:\n break\n return False\n\n def contains_offensive_language(self, text):\n \"\"\"Determines if text contains any offensive words from the list.\"\"\"\n if type(text) is str:\n toks = self.tokenize(text.lower())\n elif type(text) is list or type(text) is tuple:\n toks = text\n\n for i in range(len(toks)):\n res = self.check_sequence(toks, i, self.offensive_trie)\n if res:\n return res\n\n return None\n\ndef clip_text(text, max_len):\n if len(text) > max_len:\n begin_text = ' '.join(\n text[:math.floor(0.8 * max_len)].split(' ')[:-1]\n )\n end_text = ' '.join(\n text[(len(text) - math.floor(0.2 * max_len)):].split(' ')[1:]\n )\n if len(end_text) > 0:\n text = begin_text + ' ...\\n' + end_text\n else:\n text = begin_text + ' ...'\n return text\n\ndef display_messages(msgs, prettify=False, ignore_fields='', max_len=1000):\n \"\"\"Returns a string describing the set of messages provided\n If prettify is true, candidates are displayed using prettytable.\n ignore_fields provides a list of fields in the msgs which should not be displayed.\n \"\"\"\n lines = []\n episode_done = False\n ignore_fields = ignore_fields.split(',')\n for index, msg in enumerate(msgs):\n if msg is None or (index == 1 and 'agent_reply' in ignore_fields):\n # We only display the first agent (typically the teacher) if we\n # are ignoring the agent reply.\n continue\n if msg.get('episode_done'):\n episode_done = True\n # Possibly indent the text (for the second speaker, if two).\n space = ''\n if len(msgs) == 2 and index == 1:\n space = ' '\n # Only display rewards !=0 as they are confusing in non-RL tasks.\n if msg.get('reward', 0) != 0:\n lines.append(space + '[reward: {r}]'.format(r=msg['reward']))\n for key in msg:\n if key not in ['episode_done', 'id', 'image', 'text', 'labels', 'eval_labels', 'label_candidates', 'text_candidates', 'reward'] and key not in ignore_fields:\n line = '[' + key + ']: ' + clip_text(str(msg.get(key)), max_len)\n lines.append(space + line)\n if type(msg.get('image')) == str:\n lines.append(msg['image'])\n if msg.get('text', ''):\n text = clip_text(msg['text'], max_len)\n ID = '[' + msg['id'] + ']: ' if 'id' in msg else ''\n lines.append(space + ID + text)\n if msg.get('labels') and 'labels' not in ignore_fields:\n lines.append(space + ('[labels: {}]'.format(\n '|'.join(msg['labels']))))\n if msg.get('eval_labels') and 'eval_labels' not in ignore_fields:\n lines.append(space + ('[eval_labels: {}]'.format(\n '|'.join(msg['eval_labels']))))\n\n if msg.get('label_candidates') and 'label_candidates' not in ignore_fields:\n cand_len = len(msg['label_candidates'])\n if cand_len <= 10:\n lines.append(space + ('[label_candidates: {}]'.format(\n '|'.join(msg['label_candidates']))))\n else:\n # select five label_candidates from the candidate set,\n # can't slice in because it's a set\n cand_iter = iter(msg['label_candidates'])\n display_cands = (next(cand_iter) for _ in range(5))\n # print those cands plus how many cands remain\n lines.append(space + ('[label_candidates: {}{}]'.format(\n '|'.join(display_cands),\n '| ...and {} more'.format(cand_len - 5)\n )))\n if msg.get('text_candidates') and 'text_candidates' not in ignore_fields:\n if prettify:\n cand_len = len(msg['text_candidates'])\n cands = [c for c in msg['text_candidates'] if c is not None]\n try:\n import prettytable\n except ImportError:\n raise ImportError('Please install prettytable to \\\n display text candidates: `pip install prettytable`')\n scores = None\n if msg.get('candidate_scores') is not None:\n table = prettytable.PrettyTable(['Score', 'Text'])\n scores = msg.get('candidate_scores')\n else:\n table = prettytable.PrettyTable(['Text'])\n table.align = 'l'\n table.hrules = 1\n display_cands = []\n num_cands = 0\n for cand in cands:\n cand_max_length = 250 if scores is None else 100\n if len(cand) > cand_max_length:\n # Show beginning and end\n split = [cand[:cand_max_length], cand[cand_max_length:]]\n cand = split[0] + '\\n\\n. . .\\n\\n' + split[1][-(min(50, len(split[1]))):]\n if scores is not None:\n table.add_row([scores[num_cands], cand])\n else:\n table.add_row([cand])\n num_cands += 1\n if num_cands > 5:\n break\n\n lines.append(space + table.get_string())\n else:\n cand_len = len(msg['text_candidates'])\n if cand_len <= 10:\n lines.append(space + ('[text_candidates: {}]'.format(\n '|'.join(msg['text_candidates']))))\n else:\n # select five label_candidates from the candidate set,\n # can't slice in because it's a set\n cand_iter = iter(msg['text_candidates'])\n display_cands = (next(cand_iter) for _ in range(5))\n # print those cands plus how many cands remain\n lines.append(space + ('[text_candidates: {}{}]'.format(\n '|'.join(display_cands),\n '| ...and {} more'.format(cand_len - 5)\n )))\n if episode_done:\n lines.append('- - - - - - - - - - - - - - - - - - - - -')\n return '\\n'.join(lines)\n\n\ndef str_to_msg(txt, ignore_fields=''):\n \"\"\"Convert formatted string to ParlAI message dict.\n\n :param txt: formatted string to convert. String format is tab-separated\n fields, with colon separating field name and contents.\n :param ignore_fields: (default '') comma-separated field names to not\n include in the msg dict even if they're in the string.\n \"\"\"\n def tostr(txt):\n txt = str(txt)\n txt = txt.replace('\\\\t', '\\t')\n txt = txt.replace('\\\\n', '\\n')\n txt = txt.replace('__PIPE__', '|')\n return txt\n\n def tolist(txt):\n vals = txt.split('|')\n for v in vals:\n v = tostr(v)\n return vals\n\n def convert(key, value):\n if key == 'text' or key == 'id':\n return tostr(value)\n elif (key == 'label_candidates' or key == 'labels' or\n key == 'eval_labels' or key == 'text_candidates'):\n return tolist(value)\n elif key == 'episode_done':\n return bool(value)\n else:\n return tostr(value)\n\n if txt == '' or txt is None:\n return None\n\n msg = {}\n for t in txt.split('\\t'):\n ind = t.find(':')\n key = t[:ind]\n value = t[ind+1:]\n if key not in ignore_fields.split(','):\n msg[key] = convert(key, value)\n msg['episode_done'] = msg.get('episode_done', False)\n return msg\n\n\ndef msg_to_str(msg, ignore_fields=''):\n \"\"\"Convert ParlAI message dict to string.\n\n :param msg: dict to convert into a string.\n :param ignore_fields: (default '') comma-separated field names to not\n include in the string even if they're in the msg dict.\n \"\"\"\n def filter(txt):\n txt = str(txt)\n txt = txt.replace('\\t', '\\\\t')\n txt = txt.replace('\\n', '\\\\n')\n txt = txt.replace('|', '__PIPE__')\n return txt\n\n def add_field(name, data):\n if name == 'reward' and data == 0:\n return ''\n if name == 'episode_done' and data is False:\n return ''\n txt = ''\n if type(data) == tuple or type(data) == set or type(data) == list:\n # list entries\n for c in data:\n txt += filter(c) + \"|\"\n txt = txt[:-1]\n else:\n # single fields\n txt = filter(data)\n return name + \":\" + txt + '\\t'\n\n default_fields = ['id', 'text', 'labels', 'label_candidates',\n 'episode_done', 'reward']\n txt = \"\"\n ignore_fields = ignore_fields.split(',')\n for f in default_fields:\n if f in msg and f not in ignore_fields:\n txt += add_field(f, msg[f])\n for f in msg.keys():\n if f not in default_fields and f not in ignore_fields:\n txt += add_field(f, msg[f])\n return txt.rstrip('\\t')\n","repo_name":"XinnuoXu/DRank","sub_path":"AMT/parlai/core/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":31074,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"21"}
+{"seq_id":"26151077411","text":"from concurrent.futures import wait\nfrom pymavlink import mavutil\nimport dronekit as vehicle\nimport json\nimport redis as rd\nimport dronekit_sitl\n#connection_string = \"127.0.0.1:115200\"\n\nsitl = dronekit_sitl.start_default()\nconnection_string = sitl.connection_string()\ntry:\n uav = vehicle.connect(connection_string, timeout=30, wait_ready = True)\n db = rd.Redis(host='localhost', port=6379, db=0)\n if db:\n print(\"Database Connection: OK!\")\nexcept Exception:\n print(Exception.args)\n\nprint(uav.attitude.roll)\nprint(uav.attitude.pitch)\n\nflight_data = {\n 'att_pitch' : uav.attitude.pitch,\n 'att_roll' : uav.attitude.roll,\n 'ais' : uav.velocity[0],\n 'alt' : uav.location.global_relative_frame.alt,\n 'head' : uav.heading,\n 'lat' : uav.location.global_relative_frame.lat,\n 'lon' : uav.location.global_relative_frame.lon,\n 'mode' : uav.mode,\n 'turn' : uav.attitude.roll,\n 'vspeed' : uav.velocity[1]\n }\n\ndb_flight_data = json.dumps(flight_data)\n\n\n\ndb.set('json_data',db_flight_data)","repo_name":"SalwoX/GCSViewer","sub_path":"GCSViewer/datawriter.py","file_name":"datawriter.py","file_ext":"py","file_size_in_byte":1041,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"21"}
+{"seq_id":"24482166521","text":"def hanoi(n, i, k):\n\tif n == 1:\n\t\tprint('переложить с', i, 'на', k)\n\telse:\n\t\ttmp = 6 - i - k\n\t\thanoi(n - 1, i, tmp)\n\t\tprint('переложить', n, 'блин с', i, 'на', k)\n\t\thanoi(n - 1, tmp, k)\n\nhanoi(4, 1, 3)","repo_name":"Senbjorn/mipt_lab_2016","sub_path":"recursion/hanoi.py","file_name":"hanoi.py","file_ext":"py","file_size_in_byte":231,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"}
+{"seq_id":"10845031214","text":"import sys\ninput = sys.stdin.readline\nn, k = map(int, input().rstrip().split())\ndata = [tuple(map(int, input().rstrip().split())) for _ in range(n)]\ndata = [(0, 0)] + data\ndp = [[0] * (k + 1) for _ in range(n + 1)]\nfor i in range(1, n + 1):\n for j in range(1, k + 1):\n w, v = data[i]\n if j < w:\n dp[i][j] = dp[i - 1][j]\n else:\n dp[i][j] = max(v + dp[i - 1][j - w], dp[i - 1][j])\nprint(dp[n][k])\n","repo_name":"K1A2/algorithm_python","sub_path":"baekjoon/dynamic_programming/12865_평범한_배낭.py","file_name":"12865_평범한_배낭.py","file_ext":"py","file_size_in_byte":441,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"}
+{"seq_id":"73025998453","text":"#! /usr/bin/env python3\n\nimport argparse\nimport cv2\nimport numpy as np\n\nimport chainer\nfrom chainer import serializers\n\nimport config\nfrom ssd import SSD300\nfrom multibox import MultiBoxEncoder\nfrom voc import VOC\n\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser()\n parser.add_argument('model')\n parser.add_argument('image')\n args = parser.parse_args()\n\n model = SSD300(n_classes=20, aspect_ratios=config.aspect_ratios)\n serializers.load_npz(args.model, model)\n\n multibox_encoder = MultiBoxEncoder(\n grids=model.grids,\n steps=config.steps,\n sizes=config.sizes,\n aspect_ratios=model.aspect_ratios,\n variance=config.variance)\n\n src = cv2.imread(args.image, cv2.IMREAD_COLOR)\n\n x = cv2.resize(src, (model.insize, model.insize)).astype(np.float32)\n x -= config.mean\n x = x.transpose(2, 0, 1)\n x = x[np.newaxis]\n\n loc, conf = model(chainer.Variable(x, volatile=True))\n boxes, conf = multibox_encoder.decode(loc.data[0], conf.data[0])\n\n img = src.copy()\n nms = multibox_encoder.non_maximum_suppression(boxes, conf, 0.45, 0.01)\n for box, cls, conf in nms:\n box *= img.shape[1::-1]\n box = box.astype(int)\n\n print(\n cls + 1, conf,\n box.left, box.top, box.right, box.bottom)\n\n if conf < 0.6:\n continue\n\n cv2.rectangle(\n img,\n (box.left, box.top), (box.right, box.bottom),\n (0, 0, 255),\n 3)\n\n name = VOC.names[cls]\n (w, h), b = cv2.getTextSize(name, cv2.FONT_HERSHEY_PLAIN, 1, 1)\n cv2.rectangle(\n img,\n (box.left, box.top), (box.left + w, box.top + h + b),\n (0, 0, 255),\n -1)\n cv2.putText(\n img,\n name,\n (box.left, box.top + h),\n cv2.FONT_HERSHEY_PLAIN,\n 1,\n (255, 255, 255))\n\n print('(press \\'q\\' to exit)')\n while True:\n cv2.imshow('result', img)\n if cv2.waitKey() == ord('q'):\n break\n","repo_name":"LiuFang816/SALSTM_py_data","sub_path":"python/Hakuyume_chainer-ssd/chainer-ssd-master/predict.py","file_name":"predict.py","file_ext":"py","file_size_in_byte":2057,"program_lang":"python","lang":"en","doc_type":"code","stars":9,"dataset":"github-code","pt":"21"}
+{"seq_id":"23396235047","text":"'''\n Calculate virtual potential temperature from\n RASS virtual temperature observations\n\n RASS retrieves virtual temperature observations\n using variations in speed of sound:\n Cs ~= 20Tv^(1/2)\n\n Raul Valenzuela\n raul.valenzuela@colorado.edu\n\n'''\nimport Meteoframes as mf\nimport pandas as pd\nimport numpy as np\n\n\ndef get_thetav(case=None, Tv_array=None, hgt_array=None, homedir=None):\n '''\n Equations derived using hypsometric eq (3.29 W&H)\n and theta defintion (3.54 W&H). Method is equivalent\n to Neiman et al (1992)\n '''\n g = 9.8 # [m/s2]\n Rd = 287 # [J K-1 kg-1]\n press = get_pressure(case=case, homedir=homedir).values\n press2 = np.expand_dims(press, axis=1)\n a, _ = hgt_array.shape\n press2 = np.repeat(press2, a, axis=1).T\n\n Tv = Tv_array + 273.15 # [K]\n\n Z_1000 = 8*(press2 - 1000)\n Z = hgt_array*1000. # [m]\n f1 = (Z - Z_1000) * g\n f2 = Rd * Tv\n thetav = Tv * np.power(np.exp(f1/f2), (2/7.))\n return thetav\n\n\ndef get_pressure(case=None, homedir=None):\n from glob import glob\n\n fpath = homedir + '/SURFACE/case{}/bby*'\n surf_files = glob(fpath.format(str(case).zfill(2)))\n surf_files.sort()\n df_list = []\n for f in surf_files:\n df_list.append(mf.parse_surface(f))\n\n if len(df_list) > 1:\n df = pd.concat(df_list)\n else:\n df = df_list[0]\n\n g = pd.TimeGrouper('60T')\n dfg = df['press'].groupby(g).mean()\n return dfg\n","repo_name":"rvalenzuelar/rass_vis","sub_path":"rass_thetav.py","file_name":"rass_thetav.py","file_ext":"py","file_size_in_byte":1465,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"}
+{"seq_id":"43056156447","text":"def converter(j):\n if j == \"UUU\" or j == \"UUC\":\n return \"F\"\n if j == \"UUA\" or j == \"UUG\" or j == \"CUU\" or j == \"CUC\" or j == \"CUA\" or j == \"CUG\":\n return \"L\"\n if j == \"UCU\" or j == \"UCC\" or j == \"UCA\" or j == \"UCG\" or j == \"AGU\" or j == \"AGC\":\n return \"S\"\n if j == \"UAU\" or j == \"UCG\" or j == \"UAC\":\n return \"Y\"\n if j == \"UAA\" or j == \"UAG\" or j == \"UGA\":\n return \"STOP\"\n if j == \"UGU\" or j == \"UGC\":\n return \"C\"\n if j == \"UGG\":\n return \"W\"\n if j == \"CCU\" or j == \"CCC\" or j == \"CCA\" or j == \"CCG\":\n return \"P\"\n if j == \"CAU\" or j == \"CAC\":\n return \"H\"\n if j == \"CAA\" or j == \"CAG\":\n return \"Q\"\n if j == \"CGU\" or j == \"CGC\" or j == \"CGA\" or j == \"CGG\" or j ==\"AGA\" or j == \"AGG\":\n return \"R\"\n if j == \"AUU\" or j == \"AUC\" or j == \"AUA\":\n return \"I\"\n if j == \"AUG\":\n return \"M\"\n if j == \"ACU\" or j == \"ACC\" or j == \"ACA\" or j == \"ACG\":\n return \"T\"\n if j == \"AAU\" or j == \"AAC\":\n return \"N\"\n if j == \"AAA\" or j == \"AAG\":\n return \"K\"\n if j == \"GUU\" or j == \"GUC\" or j == \"GUA\" or j == \"GUG\":\n return \"V\"\n if j == \"GCU\" or j == \"GCC\" or j == \"GCA\" or j == \"GCG\":\n return \"A\"\n if j == \"GAU\" or j == \"GAC\":\n return \"D\"\n if j == \"GAA\" or j == \"GAG\":\n return \"E\"\n if j == \"GGU\" or j == \"GGC\" or j == \"GGA\" or j == \"GGG\":\n return \"G\"\n\ns0 = []\nwith open(\"rosalind_prot.txt\", \"r\") as f:\n for line in f.readlines():\n s0.append(line.replace('\\n', ''))\n\ns = ''.join(s0)\n#print(s)\n\nli = []\nli1 = []\n\nfor i in range(0, len(s), 3):\n li.append(s[i:i+3])\n\nz = 0\nfor j in li:\n k = converter(j)\n if k == None:\n print(k)\n print(j)\n if k == \"STOP\":\n z = 1\n if z == 0:\n li1.append(k)\n\n#print(li1)\n \ns1 = \"\".join(li1)\nprint(s1)\n\n","repo_name":"SamShapiro/PythonAndJavaFiles","sub_path":"dna_module.py","file_name":"dna_module.py","file_ext":"py","file_size_in_byte":1888,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"}
+{"seq_id":"10738832876","text":"#\n# @lc app=leetcode.cn id=455 lang=python3\n#\n# [455] 分发饼干\n#\n\n# @lc code=start\nclass Solution:\n def findContentChildren(self, g: List[int], s: List[int]) -> int:\n g_rev = sorted(g, reverse=True)\n s_rev = sorted(s, reverse=True)\n flag_g = 0\n flag_s = 0\n account = 0\n while flag_g= g_rev[flag_g]:\n flag_g += 1\n flag_s += 1\n account += 1\n else:\n flag_g += 1\n return account \n# @lc code=end\n\n","repo_name":"MaxZN/Leetcode","sub_path":"455.分发饼干.py","file_name":"455.分发饼干.py","file_ext":"py","file_size_in_byte":584,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"}
+{"seq_id":"70728834614","text":"# logistic_function_gmpy2.py: ロジスティック写像(gmpy2版)\r\nimport gmpy2\r\n\r\n# 128 bits\r\ngmpy2.get_context().precision = 128\r\nx = [gmpy2.mpfr('0.7501')]\r\nfor i in range(0, 100):\r\n x.append(4 * x[i] * (1 - x[i]))\r\n\r\n# 256 bits\r\ngmpy2.get_context().precision = 256\r\nxl = [gmpy2.mpfr('0.7501')]\r\nfor i in range(0, 100):\r\n xl.append(4 * xl[i] * (1 - xl[i]))\r\n\r\nreldiff_x = [gmpy2.reldiff(xl[i], x[i]) for i in range(len(x))]\r\n\r\nprint(' i, x[i] ')\r\nfor i in range(0, 101):\r\n if i % 10 == 0:\r\n print(f'{i:5d}, {x[i]:50.40e}, {reldiff_x[i]:5.1e}')\r\n\r\n\r\n# -------------------------------------\r\n# Copyright (c) 2021 Tomonori Kouya\r\n# All rights reserved.\r\n# -------------------------------------\r\n","repo_name":"tkouya/inapy","sub_path":"chapter04/logistic_function_gmpy2.py","file_name":"logistic_function_gmpy2.py","file_ext":"py","file_size_in_byte":766,"program_lang":"python","lang":"en","doc_type":"code","stars":12,"dataset":"github-code","pt":"21"}
+{"seq_id":"23639868342","text":"from tkinter import *\nfrom PIL import Image, ImageTk\nfrom datetime import *\nimport time\nimport pandas as pd\nfrom matplotlib.backends.backend_tkagg import FigureCanvasTkAgg\nimport matplotlib.pyplot as plt\nimport numpy as np\n\nclass Dashboard:\n def __init__(self, root):\n self.root = root\n self.root.title(\"Tableau de bord\")\n self.root.geometry(\"1366x768\")\n self.root.config(bg=\"#eff5f6\")\n \n icon = PhotoImage(file=r\"C:\\Users\\Admin\\OneDrive\\Bureau\\codePython\\gestion_python\\Image_DashBoard\\pic-icon.png\")\n self.root.iconphoto(True,icon)\n \n # En-tête\n self.entete = Frame(self.root, bg=\"#009df4\")\n self.entete.place(x=300, y=0, width=1070, height=60)\n \n self.deconnect = Button(self.entete, text=\"Deconnecter\", bg=\"#32cf8e\", font=(\"poppins\", 13, \"bold\"), bd=0, fg=\"white\", cursor=\"hand2\", activebackground=\"#32cf8e\")\n self.deconnect.place(x=925, y=15)\n \n #Menu\n self.FrameMenu = Frame(self.root, bg=\"#fff\")\n self.FrameMenu.place(x=0, y=0, width=300, height=750)\n \n self.logoImage = Image.open(r\"C:\\Users\\Admin\\OneDrive\\Bureau\\codePython\\gestion_python\\Image_DashBoard\\hyy.png\")\n photo = ImageTk.PhotoImage(self.logoImage)\n self.logo = Label(self.FrameMenu, image=photo, bg=\"#fff\")\n self.logo.image = photo\n self.logo.place(x=70, y=80) \n self.Nom = Label(self.FrameMenu, text=\"Cléason Noglo\", bg=\"#fff\", font=(\"poppins\", 13, \"bold\"))\n self.Nom.place(x=80, y=200)\n \n #Tableau de bord\n self.dashboardImage = Image.open(r\"C:\\Users\\Admin\\OneDrive\\Bureau\\codePython\\gestion_python\\Image_DashBoard\\dashboard-icon.png\")\n photo = ImageTk.PhotoImage(self.dashboardImage)\n self.dashboard = Label(self.FrameMenu, image=photo, bg=\"#fff\")\n self.dashboard.image = photo\n self.dashboard.place(x=35, y=289)\n self.dashboard_text = Button(self.FrameMenu, text=\"Tableau de bord\", bg=\"#fff\", font=(\"poppins\", 13, \"bold\"), bd=0, cursor=\"hand2\", activebackground=\"#fff\")\n self.dashboard_text.place(x=80, y=289)\n \n #Gestion\n self.gestionImage = Image.open(r\"C:\\Users\\Admin\\OneDrive\\Bureau\\codePython\\gestion_python\\Image_DashBoard\\manage-icon.png\")\n photo = ImageTk.PhotoImage(self.gestionImage)\n self.gestion = Label(self.FrameMenu, image=photo, bg=\"#fff\")\n self.gestion.image = photo\n self.gestion.place(x=35, y=340)\n self.gestion_text = Button(self.FrameMenu, text=\"Gestion\", bg=\"#fff\", font=(\"poppins\", 13, \"bold\"), bd=0, cursor=\"hand2\", activebackground=\"#fff\")\n self.gestion_text.place(x=80, y=345)\n \n \n #parametres\n self.parametreImage = Image.open(r\"C:\\Users\\Admin\\OneDrive\\Bureau\\codePython\\gestion_python\\Image_DashBoard\\settings-icon.png\")\n photo = ImageTk.PhotoImage(self.parametreImage)\n self.parametre = Label(self.FrameMenu, image=photo, bg=\"#fff\")\n self.parametre.image = photo\n self.parametre.place(x=35, y=402)\n self.parametre_text = Button(self.FrameMenu, text=\"Parametres\", bg=\"#fff\", font=(\"poppins\", 13, \"bold\"), bd=0, cursor=\"hand2\", activebackground=\"#fff\")\n self.parametre_text.place(x=80, y=402)\n \n #Quitter\n self.quitterImage = Image.open(r\"C:\\Users\\Admin\\OneDrive\\Bureau\\codePython\\gestion_python\\Image_DashBoard\\exit-icon.png\")\n photo = ImageTk.PhotoImage(self.quitterImage)\n self.quitter = Label(self.FrameMenu, image=photo, bg=\"#fff\")\n self.quitter.image = photo\n self.quitter.place(x=25, y=452)\n self.quitter_text = Button(self.FrameMenu, text=\"Quitter\", bg=\"#fff\", font=(\"poppins\", 13, \"bold\"), bd=0, cursor=\"hand2\", activebackground=\"#fff\")\n self.quitter_text.place(x=85, y=462)\n \n #Corps\n self.titre = Label(self.root, text=\"Tableau de bord\",font=(\"poppins\", 13, \"bold\"), fg=\"#0064d3\", bg=\"#eff5f6\")\n self.titre.place(x=325, y=70)\n \n #Corps1\n self.corp1 = Frame(self.root, bg=\"#fff\")\n self.corp1.place(x=328, y=110, width=1040, height=350)\n \n donnee = pd.read_excel(r\"C:\\Users\\Admin\\OneDrive\\Bureau\\codePython\\gestion_python\\Image_DashBoard\\donnee.xlsx\")\n sumlundi = sum(donnee[\"Lundi\"])\n summardi = sum(donnee[\"Mardi\"])\n summercredi = sum(donnee[\"Mercredi\"])\n sumjeudi = sum(donnee[\"Jeudi\"])\n sumvendredi = sum(donnee[\"Vendredi\"])\n sumsamedi = sum(donnee[\"Samedi\"])\n \n fig = plt.figure(figsize=(5,5), dpi=100)\n fig.set_size_inches(5, 3.5)\n \n labels = \"Lundi\", \"Mardi\", \"Mercredi\", \"Jeudi\", \"Vendredi\", \"Samedi\"\n sizes = [sumlundi, summardi, summercredi, sumjeudi, sumvendredi, sumsamedi]\n colors = [\"yellowgreen\", \"gold\", \"lightcoral\", \"lightskyblue\", \"cyan\", \"red\"]\n explode = (0.2, 0, 0, 0, 0, 0)\n \n plt.pie(sizes, explode=explode, labels=labels, colors=colors, autopct='%1.1f%%', shadow=True, startangle=140)\n \n plt.axis(\"equal\")\n \n canvasbar = FigureCanvasTkAgg(fig, master=self.root)\n canvasbar.draw()\n canvasbar.get_tk_widget().place(x=1120, y=285, anchor=CENTER)\n \n #Diagramme\n fig = plt.figure(figsize=(5, 3.5), dpi=100)\n labels = \"Lundi\", \"Mardi\", \"Mercredi\", \"Jeudi\", \"Vendredi\", \"Samedi\"\n labelpos = np.arange(len(labels))\n semainesum = [sumlundi, summardi, summercredi, sumjeudi, sumvendredi, sumsamedi]\n \n plt.bar(labelpos, semainesum, align=\"center\", alpha=1.0)\n plt.xticks(labelpos, labels)\n plt.ylabel(\"Prix\")\n plt.ylabel(\"Semaine\")\n plt.tight_layout(pad=2.2, w_pad=0.5, h_pad=0.1)\n plt.title(\"Vente de la semaine\")\n plt.xticks(rotation=30, horizontalalignment='center')\n \n for index, datapoints in enumerate(semainesum):\n plt.text(x=index, y=datapoints+0.3, s=f\"{datapoints}\", fontdict=dict(fontsize=10), ha=\"center\", va=\"bottom\")\n \n canvasbar = FigureCanvasTkAgg(fig, master=self.root)\n canvasbar.draw()\n canvasbar.get_tk_widget().place(x=600, y=285, anchor=CENTER)\n \n self.root.protocol(\"WM_DELETE_WINDOW\", self.Exit)\n \n #Corps2\n self.corp2 = Frame(self.root, bg=\"#009aa5\")\n self.corp2.place(x=328, y=495, width=310, height=220)\n \n self.totalclientImage = Image.open(r\"C:\\Users\\Admin\\OneDrive\\Bureau\\codePython\\gestion_python\\Image_DashBoard\\left-icon.png\")\n photo = ImageTk.PhotoImage(self.totalclientImage)\n self.totalclient = Label(self.corp2, image=photo, bg=\"#009aa5\")\n self.totalclient.image = photo\n self.totalclient.place(x=220, y=0)\n \n self.ntotalclient_text = Button(self.corp2, text=\"300\", bg=\"#009aa5\", fg=\"white\", font=(\"poppins\", 25, \"bold\"), bd=0, cursor=\"hand2\", activebackground=\"#fff\")\n self.ntotalclient_text.place(x=120, y=100)\n \n self.ttotalclient_text = Button(self.corp2, text=\"Total Client\", bg=\"#009aa5\", fg=\"white\", font=(\"poppins\", 15, \"bold\"), bd=0, cursor=\"hand2\", activebackground=\"#fff\")\n self.ttotalclient_text.place(x=5, y=5)\n \n #Corps3\n self.corps3 = Frame(self.root, bg=\"#e21f26\")\n self.corps3.place(x=680, y=495, width=310, height=220)\n \n self.totalemployeImage = Image.open(r\"C:\\Users\\Admin\\OneDrive\\Bureau\\codePython\\gestion_python\\Image_DashBoard\\left-icon.png\")\n photo = ImageTk.PhotoImage(self.totalemployeImage)\n self.totalemploye = Label(self.corps3, image=photo, bg=\"#e21f26\")\n self.totalemploye.image = photo\n self.totalemploye.place(x=220, y=0)\n \n self.ntotalemploye_text = Button(self.corps3, text=\"20\", bg=\"#e21f26\", fg=\"white\", font=(\"poppins\", 25, \"bold\"), bd=0, cursor=\"hand2\", activebackground=\"#fff\")\n self.ntotalemploye_text.place(x=120, y=100)\n \n self.ttotalemploye_text = Button(self.corps3, text=\"Total Employe\", bg=\"#e21f26\", fg=\"white\", font=(\"poppins\", 15, \"bold\"), bd=0, cursor=\"hand2\", activebackground=\"#fff\")\n self.ttotalemploye_text.place(x=5, y=5)\n \n #Corps4\n self.corps4 = Frame(self.root, bg=\"#ffcb1f\")\n self.corps4.place(x=1030, y=495, width=310, height=220)\n \n self.totalventeImage = Image.open(r\"C:\\Users\\Admin\\OneDrive\\Bureau\\codePython\\gestion_python\\Image_DashBoard\\earn3.png\")\n photo = ImageTk.PhotoImage(self.totalventeImage)\n self.totalvente = Label(self.corps4, image=photo, bg=\"#ffcb1f\")\n self.totalvente.image = photo\n self.totalvente.place(x=220, y=0)\n \n self.ntotalvente_text = Button(self.corps4, text=\"450.000\", bg=\"#ffcb1f\", fg=\"#000000\", font=(\"poppins\", 25, \"bold\"), bd=0, cursor=\"hand2\", activebackground=\"#fff\")\n self.ntotalvente_text.place(x=80, y=100)\n \n self.ttotalvente_text = Button(self.corps4, text=\"Total Vente\", bg=\"#ffcb1f\", fg=\"#000000\", font=(\"poppins\", 15, \"bold\"), bd=0, cursor=\"hand2\", activebackground=\"#fff\")\n self.ttotalvente_text.place(x=8, y=5)\n \n \n #Heures\n self.heureImage = Image.open(r\"C:\\Users\\Admin\\OneDrive\\Bureau\\codePython\\gestion_python\\Image_DashBoard\\time.png\")\n photo = ImageTk.PhotoImage(self.heureImage)\n self.heure = Label(self.FrameMenu, image=photo, bg=\"#fff\")\n self.heure.image = photo\n self.heure.place(x=78, y=20)\n \n self.heures_text = Label(self.FrameMenu)\n self.heures_text.place(x=115, y=15)\n self.afficher_heures()\n \n def afficher_heures(self):\n self.time = time.strftime(\"%H:%M:%S\")\n self.date = time.strftime(\"%d/%m/%Y\")\n resultat = f\"{self.date}\\n{self.time}\"\n self.heures_text.config (text=resultat, bd=0, font=(\"poppins\", 13, \"bold\"), bg=\"#fff\")\n self.heures_text.after(100, self.afficher_heures)\n \n def Exit(self):\n self.root.quit()\n\n\n\n\n\nif __name__ == \"__main__\":\n root = Tk()\n Dashboard(root)\n root.mainloop()","repo_name":"cleason/gestion_python","sub_path":"tableau.py","file_name":"tableau.py","file_ext":"py","file_size_in_byte":10116,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"}
+{"seq_id":"7900059641","text":"#--------------------------------------------------------------------\r\n# %%\r\n#\r\nimport sqlite3\r\nimport os\r\n#--------------------------------------------------------------------\r\n# Cambiar directorio\r\nos.chdir('C:\\\\Python/Diego Moisset Python/Python 287')\r\n#--------------------------------------------------------------------\r\n#--------------------------------------------------------------------\r\n# %%\r\n# Crear la tabla\r\nconexion = sqlite3.connect('bd1.db')\r\ntry:\r\n conexion.execute('''\r\n create table Articulos(\r\n Codigo integer primary key autoincrement,\r\n Descripcion text,\r\n Precio real\r\n )\r\n ''')\r\nexcept sqlite3.OperationalError:\r\n print('Ya esta creada')\r\nconexion.close()\r\n#--------------------------------------------------------------------\r\n# %%\r\n# Insertar cosas ya\r\nconexion = sqlite3.connect('bd1.db')\r\nconexion.execute('Insert into Articulos(Descripcion , Precio) values (? , ?)' , ('Naranja' , 49.90))\r\nconexion.execute('Insert into Articulos(Descripcion , Precio) values (? , ?)' , ('Manzana' , 58.36))\r\nconexion.execute('Insert into Articulos(Descripcion , Precio) values (? , ?)' , ('Banana' , 53.21))\r\nconexion.commit()\r\nconexion.close()\r\n# %%\r\n# Mostrar las filas con for\r\nconexion = sqlite3.connect('bd1.db')\r\nRaw = conexion.execute('select Codigo , Descripcion , Precio from Articulos')\r\nfor fila in Raw:\r\n print(fila)\r\nconexion.close()\r\n# %%\r\n# Consultar un articulo\r\nconexion = sqlite3.connect('bd1.db')\r\nCodigo = int(input('Ingrese el codigo'))\r\nProducto = conexion.execute('select Descripcion, Precio from Articulos where Codigo = ?' , (Codigo ,))\r\nfila = Producto.fetchone()\r\nif fila != None:\r\n print(fila)\r\nelse:\r\n print('No existe el producto')\r\nconexion.close()\r\n# %%\r\n# Recuperar varios datos de una vez\r\nconexion = sqlite3.connect('bd1.db')\r\nPrecio = float(input('Ingrese el Precio'))\r\nProductos = conexion.execute('select Descripcion, Precio from Articulos where Precio < ?' , (Precio ,))\r\nfilas = Productos.fetchall()\r\nif len(filas) > 0:\r\n for fila in filas:\r\n print(fila)\r\nelse:\r\n print('No hay articulos con precio menor al ingresado')\r\nconexion.close()\r\n# %%\r\n","repo_name":"LucasFQuirogaH/Python","sub_path":"Diego Moisset Python/SQLite3.py","file_name":"SQLite3.py","file_ext":"py","file_size_in_byte":2165,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"}
+{"seq_id":"14591168248","text":"import setuptools\n\ntry:\n with open(\"../README.md\", \"r\") as fh:\n long_description = fh.read()\nexcept FileNotFoundError:\n print(\"No Readme available\")\n long_description = \"\"\n\nsetuptools.setup(\n name=\"SitewisePyObjects-paszin\",\n version=\"0.0.1\",\n author=\"Pascal Crenzin\",\n author_email=\"pc@thullex.de\",\n description=\"Functions for this and that\",\n long_description=long_description,\n long_description_content_type=\"text/markdown\",\n url=\"https://github.com/paszin/SitewisePyObjects\",\n packages=setuptools.find_packages(),\n install_requires=[\"boto3\"],\n entry_points={\n 'console_scripts': [\n ]\n },\n classifiers=[\n \"Programming Language :: Python :: 3\",\n \"License :: OSI Approved :: MIT License\",\n \"Operating System :: OS Independent\",\n ],\n python_requires='>=3.6',\n)\n","repo_name":"paszin/SitewisePyObjects","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":857,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"21"}
+{"seq_id":"1451962952","text":"from flask import Flask, jsonify, request, render_template\nfrom flask_sqlalchemy import SQLAlchemy\nfrom sqlalchemy import MetaData, Table\nfrom sqlalchemy import create_engine\nfrom flask_migrate import Migrate\nfrom flask_cors import CORS, cross_origin\nimport datetime\nfrom flask_marshmallow import Marshmallow\n\n\n\n# DB connections\nengine = create_engine('postgresql://beobuojhegamsi:0d03035ef88099e1bd219b3772e17522354a9ac58068766ef6ac180fe38a83ec@ec2-52-3-130-181.compute-1.amazonaws.com:5432/d8gbvgrngr0fsa')\nconnection = engine.connect()\n\napp = Flask(__name__)\n# CORS(app)\n\napp.config['SQLALCHEMY_DATABASE_URI'] = 'postgresql://beobuojhegamsi:0d03035ef88099e1bd219b3772e17522354a9ac58068766ef6ac180fe38a83ec@ec2-52-3-130-181.compute-1.amazonaws.com:5432/d8gbvgrngr0fsa'\n\napp.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False\n\ndb = SQLAlchemy(app)\nmigrate = Migrate(app, db)\nma = Marshmallow(app)\nmetadata = MetaData()\n\n# schemas!\nclass Articles(db.Model):\n __tablename__ = 'articles'\n id = db.Column(db.Integer, primary_key=True)\n title = db.Column(db.String(100))\n body = db.Column(db.Text())\n date = db.Column(db.DateTime, default = datetime.datetime.now)\n def __init__(self, title,body):\n self.title = title\n self.body = body\n def __repr__(self):\n return f\"\"\n\nclass ArticleSchema(ma.Schema):\n class Meta:\n fields = ('id', 'title', 'body', 'date' )\n\narticle_schema = ArticleSchema()\narticles_schema = ArticleSchema(many=True)\n\n# API Routes!\n@app.route(\"/get\", methods = ['GET'])\n@cross_origin()\ndef get_articles():\n all_articles = Articles.query.all()\n results = articles_schema.dump(all_articles)\n return jsonify(results)\n\n@app.route(\"/get//\", methods = ['GET'])\n@cross_origin()\ndef post_details(id):\n article = Articles.query.get(id)\n return article_schema.jsonify(article)\n\n@app.route(\"/update//\", methods = ['PUT'])\n@cross_origin()\ndef update_article(id):\n article = Articles.query.get(id)\n\n title = request.json['title']\n body = request.json['body']\n\n article.title = title\n article.body = body\n\n db.session.commit()\n return article_schema.jsonify(article)\n\n@app.route(\"/delete//\", methods = ['DELETE'])\n@cross_origin()\ndef article_delete(id):\n article = Articles.query.get(id)\n db.session.delete(article)\n db.session.commit()\n\n return article_schema.jsonify(article)\n\n@app.route(\"/add\", methods = ['POST'])\n@cross_origin()\ndef add_article():\n title = request.json['title']\n body = request.json['body']\n\n articles = Articles(title, body)\n db.session.add(articles)\n db.session.commit()\n return article_schema.jsonify(articles)\n\n# beginning of template rendering page routes\n@app.route(\"/\")\n@cross_origin()\ndef homepage():\n return render_template('home.html', )\n\n@app.route(\"/articles\")\n@cross_origin()\ndef render_articles():\n return render_template('articles.html', articles = Articles.query.all() )\n\n@app.route(\"/article/\")\n@cross_origin()\ndef render_article(id):\n return render_template('article.html', articles = Articles.query.get(id))\n\n# @app.route(\"/\")\n# def helloworld():\n# return {\n# 'Hello':'World'\n# }\n\nif __name__== '__main__':\n app.run(debug=True)\n # host = '127.0.0.1', port=3000, debug=True\n # 192.168.0.4:19000","repo_name":"ErikBurdett/flaskreact-nativeapp","sub_path":"hello.py","file_name":"hello.py","file_ext":"py","file_size_in_byte":3328,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"}
+{"seq_id":"301492819","text":"from django.urls import path\n\nfrom .views import (home_page, ajax_variant, category_product, \n product_detail, addcomment, add_to_cart, remove_product_from_cart, \n remove_single_quantity_product, search, faq)\n\nurlpatterns = [\n path('', home_page, name='home_page'),\n path('ajax_variant', ajax_variant, name='ajax_variant'),\n # product\n path('search', search, name='search'),\n path('faq', faq, name='faq'),\n path('category//', \n category_product, name='category_product'),\n path('product//', \n product_detail, name='product_detail'),\n path('product/addcomment/', addcomment, name='addcomment'),\n path('addtocart/', add_to_cart, name='addtocart'),\n path('remove-product-from-cart/', remove_product_from_cart, name='remove-product-from-cart'),\n path('remove-single-quantity-product/', \n remove_single_quantity_product, \n name='remove-single-quantity-product'), \n]","repo_name":"quad400/ShopItApp","sub_path":"src/product/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1070,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"}
+{"seq_id":"74763683892","text":"print(f'{\" DESAFIO Nº 090 \":=^30}')\nprint(f'Faça um programa que leia o \\033[34mnome e média\\033[m de um aluno, guardando também'\n'\\na \\033[34msituação\\033[m em um \\033[33mdicionário\\033[m. No final, mostre o conteúdo da estrutura na tela.')\nalunos = []\ndicionário = {'Nome': '', 'Média': '' , 'Situação': ''}\n\ndicionário['Nome'] = str(input('Digite o nome do aluno: '))\ndicionário['Média'] = float(input('Digite a média do aluno: '))\nif dicionário['Média'] >= 7:\n dicionário['Situação'] = 'Aprovado'\nelse:\n dicionário['Situação'] = 'Reprovado'\n\nfor k, v in dicionário.items():\n print(f'{k} dele é {v}')","repo_name":"gustavobarretto/courses","sub_path":"python-course/PycharmProjects/pythonProject/Curso em Vídeo - Pyhon/Cursoemvideo - Exercises/#090.py","file_name":"#090.py","file_ext":"py","file_size_in_byte":638,"program_lang":"python","lang":"pt","doc_type":"code","stars":2,"dataset":"github-code","pt":"21"}
+{"seq_id":"41620116263","text":"# SET THE NAMESPACE!\nfrom django.conf.urls import url\n\nfrom vulnerability_app import views\n\napp_name = 'vulnerability_app'\nurlpatterns = [\n url(r'^register/$', views.register, name='register'),\n url(r'^user_login/$', views.user_login, name='user_login'),\n url(r'^compute_occurrences/$', views.compute_occurrences, name='compute_occurrences'),\n url(r'^monthly_report/$', views.monthly_report, name='monthly_report'),\n]\n","repo_name":"georgianaasiminei/vulnerability_mgmt","sub_path":"vulnerability_app/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":430,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"}
+{"seq_id":"74188275251","text":"import websocket, json, sys, curses, locale\n\ntry:\n import thread\nexcept ImportError:\n import _thread as thread\n\n'''\n #### Class declaration and argument handling ####\n'''\n\n#class used to track and update the yposition of the cursor in the receive message box.\nclass yPosTracker:\n def __init__(self):\n self.ypos = 1\n \n def getYpos(self):\n return self.ypos\n \n def setYpos(self, newYpos):\n self.ypos = newYpos\n\n#if there is no command argument supplied prompt user for username.\nif (len(sys.argv) != 2):\n print(\"Enter a nick/user name\")\n username = input(\">\")\nelse:\n username = sys.argv[1]\n\n'''\n #### Global Inits ####\n'''\n\n#Setting of locale\nlocale.setlocale(locale.LC_ALL, \"\")\ncode = locale.getpreferredencoding()\n\n#stdscr noecho init\nstdscr = curses.initscr()\ncurses.noecho()\ncurses.cbreak()\nstdscr.keypad(1)\n\n#get height and width of screen.\nheight, width = stdscr.getmaxyx()\n\n#calculate division between two screens\ndiv = int(round(height - (height/6)))\ndivHeight = int(round(height/6))\n\n#receive message box and send message box init.\nreceiveMessageBox = curses.newwin(div, width, 0, 0)\nsendMessageBox = curses.newwin(divHeight, width, div, 0)\n\n#init ypos tracker on the heap\nypos = yPosTracker()\n\n'''\n #### Function Declarations ####\n'''\n\n#thread main, used for synchronisly sending messages\ndef sendThread(*args):\n while(True):\n #allow echoing in the send message box and get string from top left corner.\n curses.echo()\n userMessage = sendMessageBox.getstr(1,1).decode(\"utf-8\")\n curses.noecho()\n \n #check for /exit command which will cause the program to exit.\n if(userMessage == \"/exit\"):\n ws.close()\n \n #send message through socket, clear and refresh send message box.\n sendMessage(args[0], userMessage)\n sendMessageBox.clear()\n sendMessageBox.refresh()\n\ndef sendMessage(ws, message):\n #create object dictionary for json.dumps\n object = {\n \"username\": username,\n \"message\": message\n }\n\n #package dictionary and send accross web socket.\n objectStr = json.dumps(object)\n encodedStr = str.encode(objectStr)\n ws.send(encodedStr)\n\ndef receiveMessage(window, div, message, yPosObject):\n \n #get ypos from the tracker\n ypos = yPosObject.getYpos()\n \n #render string on window and get the current cursor pos.\n window.addstr(ypos, 1, message)\n cursorY, cursorX = window.getyx()\n \n #if the cursor is below the window scroll up to get it back in\n if (cursorY > div):\n window.scroll((cursorY - div))\n \n #set new ypos and move cursor back to the sendMessageBox\n yPosObject.setYpos(cursorY + 1)\n sendMessageBox.move(1,1)\n window.refresh()\n\n\n'''\n #### Web Socket Closures ####\n'''\n\ndef on_message(ws, message):\n #load message from string create format string and pass that to receive message.\n messageObj = json.loads(message)\n message = \"{}: {}\".format(messageObj[\"username\"], messageObj[\"message\"])\n receiveMessage(receiveMessageBox, div, message, ypos)\n\ndef on_error(ws, error):\n #print the error\n print(error)\n\ndef on_close(ws):\n #return terminal to original state and exit\n curses.nocbreak()\n stdscr.keypad(0)\n curses.echo()\n curses.endwin()\n sys.exit()\n\ndef on_open(ws):\n thread.start_new_thread(sendThread, (ws, 0))\n\n'''\n #### \"Main\" function ####\n'''\n\n\nif __name__ == \"__main__\":\n ws = websocket.WebSocketApp(\"ws://localhost:8080/chat\",\n on_message = on_message,\n on_error = on_error,\n on_close = on_close)\n ws.on_open = on_open\n ws.run_forever()\n\n","repo_name":"Avynn/avynnChatServer","sub_path":"client/client2.py","file_name":"client2.py","file_ext":"py","file_size_in_byte":3738,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"}
+{"seq_id":"44105886081","text":"#temporary, manual entry - need to figure out where I'm going to get this from\n\n#just type them in\ndef get_sports():\n sports=[\n 'NFL',\n 'EPL'\n ]\n return sports\n \n\n# copy paste list from ESPN (http://espn.go.com/nfl/schedule/_/week/4)\n# edit to match format\ndef get_games():\n games=dict()\n games={\n 'August 28, 2015':[\n ['New England', 'Carolina', '7:30 PM'],\n \t ['Detroit', 'Jacksonville', '8:00 PM'],\n \t ['Tennessee', 'Kansas City', '8:00 PM']],\n 'August 29, 2015':[\n \t['Pittsburgh', 'Buffalo', '4:00 PM'],\n \t ['Atlanta', 'Miami', '7:00 PM'],\n \t ['Cleveland', 'Tampa Bay', '7:00 PM'],\n \t ['Minnesota', 'Dallas', '7:00 PM'],\n \t ['NY Jets', 'NY Giants', '7:00 PM'],\n \t ['Chicago', 'Cincinnati', '7:30 PM'],\n \t ['Washington', 'Baltimore', '7:30 PM'],\n \t ['Seattle', 'San Diego', '8:00 PM'],\n \t ['Philadelphia', 'Green Bay', '8:00 PM'],\n \t ['Indianapolis', 'St. Louis', '8:00 PM'],\n \t ['San Francisco', 'Denver', '9:00 PM']],\n \t'August 30, 2015':[\n \t ['Houston', 'New Orleans', '4:00 PM'],\n \t ['Arizona', 'Oakland', '8:00 PM']]}\n return games","repo_name":"Higg0/fanwatch","sub_path":"workspace/app/content.py","file_name":"content.py","file_ext":"py","file_size_in_byte":1197,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"}
+{"seq_id":"13926654943","text":"import json\n\n# import requests\n\n\ndef lambda_handler(event, context):\n # hello = event.get('pathParameters').get('hello')\n print(\"event\", event)\n\n httpMethod = event.get('httpMethod')\n\n if httpMethod == 'POST':\n body = json.loads(event.get('body'))\n print(\"body:\", body)\n word = body.get('hello')\n return {\n \"statusCode\": 200,\n \"headers\": {\n 'Access-Control-Allow-Origin': '*',\n 'Access-Control-Allow-Credentials': True,\n 'Content-Type': 'application/json',\n },\n \"body\": json.dumps({\n \"message\": \"hello {}\".format(word),\n # \"location\": ip.text.replace(\"\\n\", \"\")\n }),\n }\n\n\n \"\"\"Sample pure Lambda function\n\n Parameters\n ----------\n event: dict, required\n API Gateway Lambda Proxy Input Format\n\n Event doc: https://docs.aws.amazon.com/apigateway/latest/developerguide/set-up-lambda-proxy-integrations.html#api-gateway-simple-proxy-for-lambda-input-format\n\n context: object, required\n Lambda Context runtime methods and attributes\n\n Context doc: https://docs.aws.amazon.com/lambda/latest/dg/python-context-object.html\n\n Returns\n ------\n API Gateway Lambda Proxy Output Format: dict\n\n Return doc: https://docs.aws.amazon.com/apigateway/latest/developerguide/set-up-lambda-proxy-integrations.html\n \"\"\"\n\n # try:\n # ip = requests.get(\"http://checkip.amazonaws.com/\")\n # except requests.RequestException as e:\n # # Send some context about this error to Lambda Logs\n # print(e)\n\n # raise e\n\n return {\n \"statusCode\": 200,\n \"headers\": {\n 'Access-Control-Allow-Origin': '*',\n 'Access-Control-Allow-Credentials': True,\n 'Content-Type': 'application/json',\n },\n \"body\": json.dumps({\n \"message\": \"hello world\",\n # \"location\": ip.text.replace(\"\\n\", \"\")\n }),\n }\n","repo_name":"voathnak/vlim-swagger-app","sub_path":"hello_world/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":2012,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"}
+{"seq_id":"20916132971","text":"from django.test import TestCase\n\n# Create your tests here.\nclass TestViews(TestCase):\n\n def test_call_login_view_loads(self):\n \"\"\"test if there is login page following current link\"\"\"\n\n response = self.client.get('/auth/login/')\n self.assertEqual(response.status_code, 200)\n self.assertTemplateUsed(response, 'login.html')\n\n\n","repo_name":"AlexEntersis/Grabber","sub_path":"account_master/tests.py","file_name":"tests.py","file_ext":"py","file_size_in_byte":357,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"}
+{"seq_id":"70046008374","text":"from marshmallow.exceptions import ValidationError\n\n\ndef validate_integer(value, *, min_value=None, max_value=None, choices=None):\n if min_value is not None:\n if value < min_value:\n raise ValidationError(\n f'Must be greater than or equal to {min_value}.'\n )\n\n if max_value is not None:\n if value > max_value:\n raise ValidationError(\n f'Must be less than or equal to {max_value}.'\n )\n\n if choices is not None:\n if value not in choices:\n raise ValidationError(\n f'Must be one of: {\", \".join(map(repr, choices))}.'\n )\n\n\ndef validate_string(value, *, max_length=None, choices=None):\n if value == '':\n raise ValidationError('Field may not be blank.')\n\n if max_length is not None:\n if len(value) > max_length:\n raise ValidationError(\n f'Must be at most {max_length} characters long.'\n )\n\n if choices is not None:\n if value not in choices:\n raise ValidationError(\n f'Must be one of: {\", \".join(map(repr, choices))}.'\n )\n","repo_name":"CiscoSecurity/tr-05-ctim-bundle-builder","sub_path":"bundlebuilder/models/validators.py","file_name":"validators.py","file_ext":"py","file_size_in_byte":1158,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"21"}
+{"seq_id":"26489708060","text":"\"\"\"\nInterface to a neo4j database, exposing a graph interface on which we can run\nSTAG algorithms.\n\"\"\"\nimport neo4j\nfrom typing import List\nfrom functools import lru_cache\n\nfrom . import graph\n\n\nclass Neo4jGraph(graph.LocalGraph):\n \"\"\"\n Represent a neo4j database as a stag.graph.LocalGraph object.\n\n This provides 'local' access to the graph only. Given a node, we can query\n its neighbors and its degree.\n The graph does not support weighted edges, and it does not\n distinguish between edge types or directions.\n\n The neo4j ```` attributes are used as the STAG vertex ids.\n\n All methods which make calls to the database backend have a small cache of\n recent queries, meaning that consecutive queries for the same node will be\n fast.\n \"\"\"\n def __init__(self, uri: str, username: str, password: str):\n \"\"\"\n Connect to a neo4j database backend.\n\n For example, assuming that there is a Neo4j database running locally,\n the graph object can be created as follows.\n\n \\code{python}\n import stag.neo4j\n g = stag.neo4j.Neo4jGraph(\"bolt://localhost:7687\", \"neo4j\", \"password\")\n \\endcode\n\n It is also possible to connect to a remote Neo4j database by passing\n the relevant ``uri`` to the constructor.\n\n @param uri the location of the neo4j database\n @param username the neo4j username\n @param password the neo4j password\n \"\"\"\n super().__init__()\n\n ## The neo4j database driver object used to query the underlying\n # database.\n self.driver = neo4j.GraphDatabase.driver(uri, auth=(username, password))\n\n ##\n # \\cond\n # The partially-constructed adjacency list of all nodes we've queried\n # so far.\n ##\n self.adjacency_list = {}\n self.labels_cache = {}\n ##\n # \\endcond\n ##\n\n def degree(self, v):\n \"\"\"\n Equivalent to stag.neo4j.Neo4jGraph.degree_unweighted.\n \"\"\"\n return self.degree_unweighted(v)\n\n def degree_unweighted(self, v: int) -> int:\n \"\"\"Query the degree of the node with the given neo4j ID.\"\"\"\n # The degree of a node is the length of its list of neighbours\n ns = self.neighbors_unweighted(v)\n return len(ns)\n\n def neighbors(self, v: int) -> List[graph.Edge]:\n \"\"\"\n Fetch the neighbors of the node with the given Neo4j node ID.\n\n The returned stag.graph.Edge objects all have weight 1.\n \"\"\"\n return [graph.Edge(v, u, 1) for u in self.neighbors_unweighted(v)]\n\n def neighbors_unweighted(self, v: int) -> List[int]:\n \"\"\"\n Fetch the neighbors of the node with the given Neo4j node ID.\n\n Returns the Neo4j node IDs of the neighboring nodes.\n \"\"\"\n if v not in self.adjacency_list:\n with self.driver.session() as session:\n result = session.execute_read(self._neighbors_query, v)\n self.adjacency_list[v] = [x[0] for x in result]\n return self.adjacency_list[v]\n\n ##\n # \\cond\n ##\n @staticmethod\n def _neighbors_query(tx, node_id):\n # To get the neighbors of the given node, we will execute the following\n # Cypher command:\n # MATCH (n1)-[]-(n2) WHERE id(n1) = v return id(n2)\n # which finds the nodes which are a single step from the node\n # with the given node ID.\n result = tx.run(\"MATCH (n1)-[]-(n2) \"\n \"WHERE id(n1) = $node_id \"\n \"RETURN DISTINCT id(n2)\", node_id=node_id)\n return list(result.values())\n ##\n # \\endcond\n ##\n\n def query_node_labels(self, node_id: int) -> List[str]:\n \"\"\"\n Query the labels of the given node.\n\n For example, using the Neo4j movie database example, you can query\n whether a given node represents a person or a movie as follows.\n\n \\code{python}\n >>> import stag.neo4j\n >>> g = stag.neo4j.Neo4jGraph(\"bolt://localhost:7687\", \"neo4j\", \"password\")\n >>> labels = g.query_node_labels(0)\n ['Movie']\n >>> labels = g.query_node_labels(1)\n ['Person']\n \\endcode\n\n \"\"\"\n if node_id not in self.labels_cache:\n with self.driver.session() as session:\n result = session.execute_read(self._labels_query, node_id)\n self.labels_cache[node_id] = [x[0] for x in result]\n return self.labels_cache[node_id]\n\n ##\n # \\cond\n ##\n @staticmethod\n def _labels_query(tx, node_id: int):\n # To get the neighbors of the given node, we will execute the following\n # Cypher command:\n # MATCH (n1)-[]-(n2) WHERE id(n1) = v return id(n2)\n # which finds the nodes which are a single step from the node\n # with the given node ID.\n result = tx.run(\"MATCH (n1) \"\n \"WHERE id(n1) = $node_id \"\n \"RETURN DISTINCT labels(n1)\", node_id=node_id)\n return result.values()[0]\n ##\n # \\endcond\n ##\n\n def query_id(self, property_name: str, property_value: str) -> int:\n \"\"\"\n Find the Neo4j ID of a node with the given property.\n\n For example, using the Neo4j movie database example you can find the\n Neo4j node corresponding to a given movie as follows.\n \n \\code{python}\n import stag.neo4j\n g = stag.neo4j.Neo4jGraph(\"bolt://localhost:7687\", \"neo4j\", \"password\")\n node_id = g.query_id(\"title\", \"Avatar\")\n \\endcode\n\n This will make a query to the database to find a node with the given\n property.\n This query will be slow unless the database has an index for\n ``property_name``.\n For more information, see the Neo4j documentation on\n [creating an index](https://neo4j.com/docs/cypher-manual/current/indexes-for-search-performance/).\n\n @param property_name the node property to query\n @param property_value the value of the node property to search for\n @return the Neo4j node ID of a node with the given property value.\n Returns None if there is no node in the dataabase with the\n requested property.\n \"\"\"\n with self.driver.session() as session:\n result = session.execute_read(self._id_query, property_name, property_value)\n return result\n\n ##\n # \\cond\n ##\n @staticmethod\n def _id_query(tx, property_name, property_value):\n result = tx.run(f'MATCH (n1 {{{property_name}: \"{property_value}\"}}) '\n \"RETURN id(n1) \"\n \"LIMIT 1\")\n result = result.single()\n if result is None:\n return None\n else:\n return result[0]\n ##\n # \\endcond\n ##\n\n def query_property(self, id: int, property_name: str) -> str:\n \"\"\"\n Find the requested property of a Neo4j node.\n\n For example, using the Neo4j movie database example, you can find the\n title of a movie node as follows.\n\n \\code{python}\n import stag.neo4j\n g = stag.neo4j.Neo4jGraph(\"bolt://localhost:7687\", \"neo4j\", \"password\")\n title = g.query_property(1, \"title\")\n \\endcode\n\n @param id the Neo4j node ID to query\n @param property_name the name of the property to query\n @return the value of the requested property on the given node. Returns\n None if the requested property is not set on the requested node,\n or if the node id does not exist.\n \"\"\"\n with self.driver.session() as session:\n result = session.execute_read(self._property_query, id, property_name)\n return result\n\n @lru_cache(maxsize=1024)\n def vertex_exists(self, v: int) -> bool:\n with self.driver.session() as session:\n result = session.execute_read(self._exists_query, v)\n return result\n\n ##\n # \\cond\n ##\n @staticmethod\n def _exists_query(tx, id: int):\n result = tx.run('MATCH (n1) '\n f\"WHERE id(n1) = {id} \"\n \"RETURN n1 \"\n \"LIMIT 1\")\n result = result.single()\n if result is None:\n return False\n else:\n return True\n ##\n # \\endcond\n ##\n\n ##\n # \\cond\n ##\n @staticmethod\n def _property_query(tx, node_id, property_name):\n result = tx.run(\"MATCH (n1) \"\n f\"WHERE id(n1) = {node_id} \"\n f\"RETURN (n1.{property_name}) \"\n \"LIMIT 1\")\n result = result.single()\n if result is None:\n return None\n else:\n return result[0]\n\n def __del__(self):\n # When the graph object it destroyed, close the connection to the backing\n # database.\n self.driver.close()\n ##\n # \\endcond\n ##\n","repo_name":"staglibrary/stagpy","sub_path":"stag/neo4j.py","file_name":"neo4j.py","file_ext":"py","file_size_in_byte":8983,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"21"}
+{"seq_id":"1310646316","text":"#!/usr/bin/env python3\n\nimport http.server, socketserver, ui, console, iServer\n\n# Read the README.MD first before using this script!\n\nPORT = 80\n\nHandler = http.server.SimpleHTTPRequestHandler\nHandler.extensions_map.update({\n '.webapp': 'application/x-web-app-manifest+json',\n});\n\nhttpd = socketserver.TCPServer((\"\", PORT), Handler)\n\nprint(\"Serving at port \", PORT)\nhttpd.serve_forever()\n","repo_name":"takyzoo/iServer","sub_path":"startserver.py","file_name":"startserver.py","file_ext":"py","file_size_in_byte":390,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"}
+{"seq_id":"2519115451","text":"from shutil import copyfile\nfrom gurobipy import *\n\ndef runModel(CAB, allowedTime, CABID):\n status = ['ERROR', 'LOADED', 'OPTIMAL', 'INFEASIBLE', 'INF_OR_UNBD', 'UNBOUNDED', 'CUTOFF', 'ITERATION_LIMIT', 'NODE_LIMIT', 'TIME_LIMIT', 'SOLUTION_LIMIT', 'INTERRUPTED', 'NUMERIC', 'SUBOPTIMAL', 'INPROGRESS', 'USER_OBJ_LIMIT']\n try:\n # Create a new model\n model = Model(\"My Model\")\n model.setParam('TimeLimit', allowedTime)\n\n # Create price(p) values for each bid with j index\n p = dict()\n for j in range(CAB.numberOfBids):\n p[str(j)] = CAB.bidList[j].priceOfBid\n\n\n # Create u values for each item with i index which represent number of avaiable units for item i\n u = dict()\n for i in range(CAB.numberOfItems):\n u[str(i)] = CAB.itemList[i].numberOfUnits\n\n # Create cost(c) values for each item with i index\n c = dict()\n for i in range(CAB.numberOfItems):\n c[str(i)] = CAB.itemList[i].costOfItem\n\n # Create quantity values for each subbid of bids with j, k index\n q = dict()\n for j in range(CAB.numberOfBids):\n for k in range(CAB.bidList[j].numberOfSubBids):\n q[str(j) + \"_\" + str(k)] = CAB.bidList[j].listOfSubBids[k].quantity\n\n # Create x variables with j index\n # x is binary that represent whether x(j) bid satisfied(1) or not(0)\n x = dict()\n for j in range(CAB.numberOfBids):\n x[str(j)] = model.addVar(vtype=GRB.BINARY, name=\"x\"+str(j))\n\n\n # Create y variables with i, j, k indexes\n # y is a natural number that represent how many units of item i are taken by k'th subbid of ...\n #... bid j if it is satisfied\n y = dict()\n for i in range(CAB.numberOfItems):\n for j in range(CAB.numberOfBids):\n for k in range(CAB.bidList[j].numberOfSubBids):\n varIndex = str(i) + \"_\" + str(j) + \"_\" + str(k)\n y[varIndex] = model.addVar(vtype=GRB.INTEGER, lb=0, name=\"y\" + varIndex)\n\n model.update()\n\n #objective function first part sum of (price of bid*is bid accepted)\n obj = LinExpr(None)\n for j in range(CAB.numberOfBids):\n obj.addTerms(p[str(j)], x[str(j)])\n\n # objective function second part sum of (cost of each item*is bid accepted and it is in subbid)\n for i in range(CAB.numberOfItems):\n for j in range(CAB.numberOfBids):\n for k in range(CAB.bidList[j].numberOfSubBids):\n if i in CAB.bidList[j].listOfSubBids[k].listOfItems:\n varIndex = str(i) + \"_\" + str(j) + \"_\" + str(k)\n obj.addTerms(-1*c[str(i)], y[varIndex])\n\n # Set objective\n model.setObjective(obj, GRB.MAXIMIZE)\n\n #constrains the sum of the requested quantity of item i by all subbids with the number of available units of item i.\n for i in range(CAB.numberOfItems):\n dummyExp = LinExpr(None)\n for j in range(CAB.numberOfBids):\n for k in range(CAB.bidList[j].numberOfSubBids):\n if i in CAB.bidList[j].listOfSubBids[k].listOfItems:\n varIndex = str(i) + \"_\" + str(j) + \"_\" + str(k)\n dummyExp.addTerms(1, y[varIndex])\n model.addConstr(dummyExp.__le__(u[str(i)]), \"c1\"+str(i))\n\n #constrains the sum of the quantities for each item inside a subbid to be equal to the requested ...\n #... quantity in that subbid if bid j is satisfied, otherwise y(i, j, k) values are cleared to 0.\n for j in range(CAB.numberOfBids):\n for k in range(CAB.bidList[j].numberOfSubBids):\n dummyExp = LinExpr(None)\n for i in range(CAB.numberOfItems):\n if i in CAB.bidList[j].listOfSubBids[k].listOfItems:\n varIndex = str(i) + \"_\" + str(j) + \"_\" + str(k)\n dummyExp.addTerms(1, y[varIndex])\n\n dummyExp.addTerms(-1*q[str(j)+\"_\"+str(k)], x[str(j)])\n model.addConstr(dummyExp.__eq__(0), \"c2\" + str(j) + \"_\" + str(k))\n\n # constraints y(i, j, k) value is set to 0 if item i is not requested by the kth subbid of the jth bid.\n for i in range(CAB.numberOfItems):\n for j in range(CAB.numberOfBids):\n for k in range(CAB.bidList[j].numberOfSubBids):\n if i not in CAB.bidList[j].listOfSubBids[k].listOfItems:\n dummyExp = LinExpr(None)\n varIndex = str(i) + \"_\" + str(j) + \"_\" + str(k)\n dummyExp.addTerms(1, y[varIndex])\n model.addConstr(dummyExp.__eq__(0), \"c3\" + varIndex)\n\n open('gurobi.log', 'w')\n model.optimize()\n objVal = model.objVal\n runTime = model.Runtime\n statusCode = model.Status\n gap = model.MIPGap\n copyfile('gurobi.log', 'log/CAB_' + str(CABID) + '.log')\n model.write('sol/CAB_' + str(CABID) + '.sol')\n model.write('lp/CAB_' + str(CABID) + '.lp')\n model.write('mst/CAB_' + str(CABID) + '.mst')\n model.write('mps/CAB_' + str(CABID) + '.mps')\n return objVal, runTime, status[statusCode], gap\n\n\n except GurobiError as e:\n print('Error code ' + str(e.errno) + \": \" + str(e))\n\n except AttributeError:\n print('Encountered an attribute error ')\n","repo_name":"ezdinaslanci/CABS","sub_path":"Model.py","file_name":"Model.py","file_ext":"py","file_size_in_byte":5465,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"21"}
+{"seq_id":"6322210643","text":"from sqlite3 import Cursor\nfrom urllib import request\nfrom flask import Flask ,jsonify, render_template, request\nfrom config import config\nfrom flask_mysqldb import MySQL\nfrom validar import *\nimport smtplib\nfrom email.message import EmailMessage\n\n\n# Inicializar el app \napp = Flask(__name__)\n\nconexion = MySQL(app)\n\n#########################REGISTRAR LIGA ################################\n\n# Listar todos los usuarios dentro de la herramienta\n@app.route('/registrarliga', methods = ['POST','GET'])\ndef registra_liga():\n \n try:\n ligas = tipo(request.json['tipo'])\n if ligas == True:\n cursor = conexion.connection.cursor()\n sql=\"\"\"INSERT INTO liga (NOMBRE_LIGA,TIPO,COSTO) VALUES ('{0}','{1}','{2}')\"\"\".format(request.json['liga'],request.json['tipo'],request.json['costo'])\n cursor.execute(sql)\n conexion.connection.commit() # confirmaci\n return jsonify({'mensaje': \"Liga Ingresada\"}) \n else:\n return jsonify({'mensaje': \"Tipo de Liga no existente\"})\n except Exception as ex:\n return jsonify({'mensaje': \"ERROR 0003 \"}) \n\n######################Invitar#############################\n\n@app.route('/Invitar', methods = ['POST'])\ndef registra_usuario_Invitado():\n try:\n\n email_subject = \"Invitacion al Torneo\" \n sender_email_address = \"your_email@gmail.com\" \n receiver_email_address = \"receiver_email@address.com\" \n email_smtp = \"smtp.gmail.com\" \n email_password = \"your_email_password\" \n\n# Create an email message object \n message = EmailMessage() \n\n# Configure email headers \n message['Subject'] = email_subject \n message['From'] = sender_email_address \n message['To'] = receiver_email_address \n\n# Set email body text \n message.set_content(\"Hello from Python!\") \n\n# Set smtp server and port \n server = smtplib.SMTP(email_smtp, '587') \n\n# Identify this client to the SMTP server \n server.ehlo() \n\n# Secure the SMTP connection \n server.starttls() \n\n# Login to email account \n server.login(sender_email_address, email_password) \n\n# Send email \n server.send_message(message) \n\n# Close connection to server \n server.quit()\n\n return jsonify({'mensaje': \"usuario invitado\"}) \n except Exception as ex:\n return jsonify({'mensaje': \"ERROR 0003\"}) \n\n\n#def listar_usuario():\n # return render_template('auth/login.html')\n\n\n######################Obtener Equipos#############################\n\n@app.route('/registrarliga/obtenerequipos', methods = ['GET'])\ndef listar_equipo():\n try:\n cursor = conexion.connection.cursor()\n sql=\"SELECT * FROM EQUIPO\"\n cursor.execute(sql)\n datos=cursor.fetchall()\n equipos =[]\n for fila in datos:\n equipo={'ID_EQUIPO':fila[0],'NOMBRE':fila[1]}\n equipos.append(equipo)\n return jsonify({'usuarios':equipos, 'mensaje': \"equipos creados\"}) \n except Exception as ex:\n return jsonify({'mensaje': \"registros no encontrados\"}) \n\n\ndef pagina_no_encontrada(error):\n return \" La pagina no existe \",404\n\n##########################Administrar Grupos################################\n@app.route('/registrar/grupo', methods = ['POST','GET'])\ndef registra_grupo():\n try:\n curso = leer_grupo(request.json['nombre'])\n if curso != None:\n return jsonify({'mensaje': \"Grupo ya creado\"}) \n else:\n cursor = conexion.connection.cursor()\n sql=\"\"\"INSERT INTO grupo_estado (NOMBRE) VALUES ('{0}')\"\"\".format(request.json['nombre'])\n cursor.execute(sql)\n conexion.connection.commit() # confirmaci\n return jsonify({'mensaje': \"Grupo registrado\"}) \n except Exception as ex:\n return jsonify({'mensaje': \"ERROR 0003 \"}) \n\n\n\ndef leer_grupo(codigo):\n try:\n cursor = conexion.connection.cursor()\n sql = \"SELECT NOMBRE FROM grupo_estado WHERE NOMBRE = '{0}'\".format(codigo)\n cursor.execute(sql)\n datos = cursor.fetchone()\n if datos != None:\n curso = {'codigo': datos[0]}\n return curso\n else:\n return None\n except Exception as ex:\n raise ex\n\n\ndef pagina_no_encontrada(error):\n return \" La pagina no existe \",404\n\n\n\n########################OBTENER LIGAS ###################################\n\n\n# Listar todos los usuarios dentro de la herramienta\n@app.route('/registrarliga/ligas', methods = ['GET'])\ndef listar_ligas():\n try:\n cursor = conexion.connection.cursor()\n sql=\"SELECT NOMBRE_LIGA, TIPO, COSTO FROM LIGA\"\n cursor.execute(sql)\n datos=cursor.fetchall()\n ligas =[]\n for fila in datos:\n liga={'NOMBRE_LIGA':fila[0],'TIPO':fila[1],'COSTP':fila[2]}\n ligas.append(liga)\n return jsonify({'usuarios':ligas, 'mensaje': \"ligas creados\"}) \n except Exception as ex:\n return jsonify({'mensaje': \"usuarios no encontrados\"}) \n\ndef pagina_no_encontrada(error):\n return \" La pagina no existe \",404\n\n\n######################REGISTRAR UN USUARIO################################\n@app.route('/registrar', methods = ['POST'])\ndef registra_usuario():\n try:\n correo = '{0}'.format(request.json['correo'])\n email = is_valid_email(correo)\n if email == True:\n cursor = conexion.connection.cursor()\n sql=\"\"\"INSERT INTO usuario (CORREO,NOMBRE, APELLIDO, CONTRASEÑA, ROL_ID_ROL) VALUES ('{0}','{1}','{2}','{3}','{4}')\"\"\".format(request.json['correo'],request.json['nombre'],request.json['apellido'],request.json['contraseña'],request.json['rol'])\n cursor.execute(sql)\n conexion.connection.commit() # confirmaci\n return jsonify({'mensaje': \"usuario registrado\"}) \n else:\n return jsonify({'mensaje': \"formato de correo incorrecto\"}) \n\n except Exception as ex:\n return jsonify({'mensaje': \"ERROR 0003 \"}) \n\n####################REGISTRAR UN EQUIPO#######################################\n@app.route('/registrar/equipo', methods = ['POST','GET'])\ndef registra_equipo():\n try:\n curso = leer_equipo(request.json['nombre'])\n if curso != None:\n return jsonify({'mensaje': \"Equipo ya creado\"}) \n else:\n cursor = conexion.connection.cursor()\n sql=\"\"\"INSERT INTO equipo (NOMBRE) VALUES ('{0}')\"\"\".format(request.json['nombre'])\n cursor.execute(sql)\n conexion.connection.commit() # confirmaci\n return jsonify({'mensaje': \"equipo registrado\"}) \n except Exception as ex:\n return jsonify({'mensaje': \"ERROR 0003 \"}) \n\n\n\ndef leer_equipo(codigo):\n try:\n cursor = conexion.connection.cursor()\n sql = \"SELECT NOMBRE FROM equipo WHERE NOMBRE = '{0}'\".format(codigo)\n cursor.execute(sql)\n datos = cursor.fetchone()\n if datos != None:\n curso = {'codigo': datos[0]}\n return curso\n else:\n return None\n except Exception as ex:\n raise ex\n\n##################RELACIÓN GRUPO EQUIPO########################\n@app.route('/registrar/relaciónequipo', methods = ['POST','GET'])\ndef relación_equipo():\n try:\n curso = leer_equipo1(request.json['equipo'])\n curso1 = leer_grupo1(request.json['grupo'])\n if curso == None and curso1 == None:\n return jsonify({'mensaje': \"EQUIPO O GRUPO NO EXISTE\"}) \n else:\n cursor = conexion.connection.cursor()\n sql=\"\"\"INSERT INTO relacion_grupo (EQUIPO_ID_EQUIPO,GRUPO_ID_GRUPO) VALUES ('{0}','{1}')\"\"\".format(request.json['equipo'],request.json['grupo'])\n cursor.execute(sql)\n conexion.connection.commit() # confirmaci\n return jsonify({'mensaje': \"relacion de equipo creada ya\"}) \n except Exception as ex:\n return jsonify({'mensaje': \"ERROR 0005 \"}) \n\n\n\ndef leer_equipo1(codigo):\n try:\n cursor = conexion.connection.cursor()\n sql = \"SELECT * FROM equipo WHERE ID_EQUIPO = '{0}'\".format(codigo)\n cursor.execute(sql)\n datos = cursor.fetchone()\n if datos != None:\n curso = {'codigo': datos[0]}\n return curso\n else:\n return None\n except Exception as ex:\n raise ex\n\n\ndef leer_grupo1(codigo):\n try:\n cursor = conexion.connection.cursor()\n sql = \"SELECT * FROM grupo_estado WHERE ID_GRUPO = '{0}'\".format(codigo)\n cursor.execute(sql)\n datos = cursor.fetchone()\n if datos != None:\n curso = {'codigo': datos[0]}\n return curso\n else:\n return None\n except Exception as ex:\n raise ex\n\n\n\n\n\ndef pagina_no_encontrada(error):\n return \" La pagina no existe \",404\n\n\n###########################DETENER EL SERVIDOR##################################\ndef shutdown_server():\n func = request.environ.get('werkzeug.server.shutdown')\n if func is None:\n raise RuntimeError('Not running with the Werkzeug Server')\n func()\n\n@app.route('/shutdown', methods=['POST'])\ndef shutdown():\n shutdown_server()\n return 'Server shutting down...'\n\n\n\n\n\nif __name__ == '__main__':\n app.config.from_object(config['development'])\n app.register_error_handler(404, pagina_no_encontrada)\n app.run()","repo_name":"eschats/Quinela_V2","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":9520,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"}
+{"seq_id":"30202949174","text":"#THIS IS GOING TO BE THE MARKET INTERFACE\n# can use volume to confirm a price movement.\n\nfrom yahoo_finance import Share\nimport numpy as np\n\n\n\nclass polynomial():\n\n\tdef __init__(self, array_of_coefficients):\n\n\t\tself.array_of_coefficients = array_of_coefficients\n\n\t\tself.degree = len(array_of_coefficients) - 1\n\n\n\tdef __str__(self):\n\n\t\tstring = ''\n\n\t\tfor i in range(0,len(self.array_of_coefficients)):\n\t\t\tstring = string + str(\"%.3f\" % self.array_of_coefficients[i]) + 'x^(' + str(self.degree - i) + ')'\n\n\t\t\tif (i < len(self.array_of_coefficients) -1):\n\t\t\t\tstring = string + ' + '\n\n\t\treturn string\n\n\tdef out(self, x):\n\n\t\ty = 0\n\n\t\tfor i in range(0, len(self.array_of_coefficients)):\n\t\t\ty = y + self.array_of_coefficients[i] * (x ** (self.degree - i))\n\n\t\treturn y\n\n\tdef derivative(self, order = 1):\n\n\n\t\thigher_order_coefficients = self.array_of_coefficients\n\n\t\tfor j in range(0,order):\n\n\t\t\tarray_of_coefficients = []\n\n\t\t\tfor i in range(0, len(higher_order_coefficients) - 1):\n\n\t\t\t\tarray_of_coefficients.append(higher_order_coefficients[i] * (len(higher_order_coefficients) - 1 - i))\n\n\t\t\thigher_order_coefficients = array_of_coefficients\n\n\t\treturn polynomial(array_of_coefficients)\n\t\t\n\n\t\t\n\ndef bestFit(array_of_points, order = 2):\n\n\ty_vector = np.zeros(order + 1)\n\n\n\tfor a in range(0, len(y_vector)):\n\n\t\tfor b in range(0, len(array_of_points)):\n\n\t\t\ty_vector[a] = y_vector[a] + (array_of_points[b][1] * (array_of_points[b][0] ** (order - a)))\n\n\tM = np.empty([order + 1, order + 1])\n\n\tfor i in range(0, order + 1):\n\n\t\tfor j in range(0, order + 1):\n\n\t\t\tM[i][j] = 0\n\t\t\t\n\t\t\tfor k in range(0, len(array_of_points)):\n\n\t\t\t\tM[i][j] = M[i][j] + array_of_points[k][0] ** ((2*order) - (i + j))\n\n\tM_inverse = np.linalg.inv(M)\n\n\t#make it also return the variance for this bestFit\n\n\treturn polynomial(np.dot(M_inverse, y_vector))\n\ndef hardFit(array_of_prices_and_times):\n\n\t#array_of_prices_and_times should be like [[time1,price1], [time2, price2], [time3,price3]]\n\t# parameter is a set of points... an array of 2d arrays.\n\n\tpolynomial_degree = len(array_of_prices_and_times) - 1\n\n\tM = np.empty([polynomial_degree + 1, polynomial_degree + 1])\n\n\t# include handling for linearly dependent funcitons.... det(M) = 0 matrices...\n\n\tprices = np.zeros(len(array_of_prices_and_times))\n\n\tfor i in range(0,len(array_of_prices_and_times)):\n\n\t\tprices[i] = array_of_prices_and_times[i][1]\n\n\t\tfor j in range(0,len(array_of_prices_and_times)):\n\t\t\tM[i][j] = array_of_prices_and_times[i][0] ** (polynomial_degree - j)\n\n\n\n\tM_inverse = np.linalg.inv(M)\n\n\tabc = np.dot(M_inverse, prices)\n\n\treturn polynomial(abc)\n\n\n\n\t# use matrices to solve a system of equations and this gives you the polynomial.\n\t#[x^2, x, 1] dot [a, b , c] = y1\n\t#[x^2, x, 1]\n\t#[]\n\n\n\n\n\treturn function\n\n","repo_name":"adamjts/tradingModules","sub_path":"functions.py","file_name":"functions.py","file_ext":"py","file_size_in_byte":2733,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"}
+{"seq_id":"18403581599","text":"from itertools import accumulate; from math import floor,ceil; import operator; import random; import string; from bisect import *; from collections import deque, defaultdict, Counter, OrderedDict; from functools import reduce,cache; from heapq import *; import unittest; from typing import List,Optional; from functools import cache; from operator import lt, gt; from sortedcontainers import SortedList\nfrom binary_tree_tester import *; from a_linked_list import make_linked_list\ndef get_sol(): return Solution()\n# https://www.youtube.com/watch?v=rY9ejIY9Osw\nclass TreeNode:\n def __init__(self, val=0, left=None, right=None):\n self.val = val\n self.left = left\n self.right = right\nclass Solution:\n # O(n)\n def buildTree(self, inorder: List[int], postorder: List[int]) -> Optional[TreeNode]:\n def build(l,r):\n nonlocal i\n if l==r:\n return TreeNode(postorder[i])\n\n nodeVal=postorder[i]\n node=TreeNode(nodeVal)\n mid=idx[nodeVal]\n if mid+1<=r:\n i-=1\n node.right=build(mid+1,r)\n if mid-1>=l:\n i-=1\n node.left=build(l,mid-1)\n return node\n\n n=len(inorder)\n i=n-1\n idx={x:i for i,x in enumerate(inorder)}\n return build(0,n-1)\n# time: n\n# https://leetcode.com/problems/construct-binary-tree-from-preorder-and-inorder-traversal/discuss/565412/Detailed-Python-Walkthrough-from-an-O(n2)-solution-to-O(n).-Faster-than-99.77\nclass Solution3:\n def buildTree(self, inorder: List[int], postorder: List[int]) -> TreeNode:\n self.post_idx=len(postorder)-1\n idx ={}\n for i,val in enumerate(inorder):\n idx[val]=i\n def construct(in_start,in_end):\n if in_start>in_end:\n return None\n\n node = TreeNode(postorder[self.post_idx])\n pos = idx[postorder[self.post_idx]]\n self.post_idx -= 1\n\n\n node.right = construct(pos+1, in_end)\n node.left = construct(in_start, pos-1)\n\n return node\n\n\n return construct(0, len(inorder)-1)\n\nclass Solution2:\n def buildTree(self, inorder: List[int], postorder: List[int]) -> TreeNode:\n self.post_idx=len(postorder)-1\n\n def construct(in_start,in_end):\n if in_start>in_end:\n return None\n\n node = TreeNode(postorder[self.post_idx])\n self.post_idx -= 1\n\n for i in range(in_start, in_end+1):\n if inorder[i]==node.val:\n pos=i\n break\n\n node.right = construct(pos+1, in_end)\n node.left = construct(in_start, pos-1)\n\n return node\n\n\n return construct(0, len(inorder)-1)\n\nclass Tester(unittest.TestCase):\n def test01(self):\n self.assertEqual('3,9,20,null,null,15,7',ser(get_sol().buildTree([9,3,15,20,7], [9,15,7,20,3])))\n def test02(self):\n self.assertEqual('-1',ser(get_sol().buildTree([-1],[-1])))\n def test03(self):\n self.assertEqual('1,null,2',ser(get_sol().buildTree([1,2], [2,1])))\n def test04(self):\n self.assertEqual('2,1',ser(get_sol().buildTree([1,2], [1,2])))\n def test05(self):\n self.assertEqual('4,3,null,null,2,1',ser(get_sol().buildTree([3,1,2,4], [1,2,3,4])))\n","repo_name":"afzalsiddique/problem-solving","sub_path":"Problem_Solving_Python/leetcode/lc106.py","file_name":"lc106.py","file_ext":"py","file_size_in_byte":3356,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"21"}
+{"seq_id":"36799665853","text":"from threading import Timer\nimport time\n\n\ndef run(n):\n print(\"hello %s\" % n)\n print(time.time() - time1)\n\n\nt = Timer(5, run, (2,)) # 线程定时器, Thread衍生类\ntime1 = time.time()\nt.start()\n# t.cancel() # 在等待时间内可以取消执行\n","repo_name":"diaoyuqiang/python","sub_path":"threading_/threading_Timer.py","file_name":"threading_Timer.py","file_ext":"py","file_size_in_byte":256,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"}
+{"seq_id":"26650021300","text":"import math\nfrom .abc import BasePausedInterface\nfrom . import menu_interface\nfrom .widgets import Button, Slider\n\nvolumes_names = [\"block\"]\n\nclass SoundsInterface(BasePausedInterface):\n title_text = \"Sounds :\"\n\n def __init__(self, game):\n self.superior = menu_interface.MenuInterface\n self.reset_button = Button(game, 0.5, math.ceil(len(volumes_names) / 2 + 2), self.reset, \"Reset\")\n super().__init__(game)\n\n def reload_widgets(self):\n self.global_volume_slider = Slider(self.game, 0.5, 1, \"Global volume\",\n self.on_slider_change, self.game.sound_manager.volumes[\"global\"])\n self.widgets = [self.global_volume_slider]\n for i, volume_name in enumerate(volumes_names):\n self.widgets.append(Slider(self.game, i % 2, i//2+2, volume_name,\n self.on_slider_change, self.game.sound_manager.volumes[volume_name]))\n\n self.widgets.append(self.reset_button)\n\n def reset(self):\n self.game.sound_manager.reset_volume()\n self.reload_widgets()\n\n def on_slider_change(self, slider, value):\n if slider is self.global_volume_slider:\n self.game.sound_manager.change_volume(\"global\", value)\n else:\n index = self.widgets.index(slider) - 1\n self.game.sound_manager.change_volume(volumes_names[index], value)\n","repo_name":"AlphaNow37/PyCraft","sub_path":"code_src/interfaces/paused_interfaces/sounds_interface.py","file_name":"sounds_interface.py","file_ext":"py","file_size_in_byte":1403,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"21"}
+{"seq_id":"15548932164","text":"import requests\nimport random\nimport sys, os\nfrom django.core.management.base import BaseCommand, CommandError\nfrom watcher.models import Listing\nfrom urllib.parse import urlencode\n\nfrom bs4 import BeautifulSoup\nfrom collections import namedtuple\nfrom watcher.models import ListingURL\n\ndirname = os.path.dirname(os.path.abspath(__file__))\nwith open(os.path.join(dirname,'user_agents.txt'), 'r') as f:\n user_agents = [line.strip() for line in f.readlines()]\n\n\nclass Command(BaseCommand):\n help = \"Closes the specified poll for voting\"\n\n def add_arguments(self, parser):\n # parser.add_argument('poll_id', nargs='+', type=int)\n pass\n\n def handle(self, *args, **options):\n params = {\"postal\": 11206, \"search_distance\": 6, \"s\": 0}\n\n base_url = \"https://newyork.craigslist.org/search/zip?\"\n\n paramstr = urlencode(params)\n full_url = base_url + paramstr\n r = requests.get(\n full_url, headers={\"User-Agent\": random.sample(user_agents, 1)[0]}\n )\n\n if not r.ok:\n raise Exception(\n \"Received error code {} from {}\\n{}\".format(\n r.status_code, full_url, r.content\n )\n )\n\n try:\n soup = BeautifulSoup(r.content, \"lxml\")\n links_html = soup.find_all(\"a\", {\"class\": \"result-title hdrlnk\"})\n listing_urls = [\n ListingURL(url=link.get(\"href\"), title=link.text, scraped=False)\n for link in links_html\n ]\n\n count = 0\n already_scraped = set([lurl.url for lurl in ListingURL.objects.all()])\n for listing_url in listing_urls:\n if listing_url.url in already_scraped:\n continue\n listing_url.save()\n count += 1\n\n sys.stderr.write(\"Found {} new URLs.\".format(count))\n except Exception as e:\n raise (e)\n","repo_name":"vpatov/craigwatch","sub_path":"craigwatch/watcher/management/commands/crawl.py","file_name":"crawl.py","file_ext":"py","file_size_in_byte":1938,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"}
+{"seq_id":"40404139246","text":"import time\nimport pigpio\nimport binascii\nimport datetime, time\nimport os, sys\nimport sqlite3\nimport uploadCSV\nimport i2cMux\nimport math\n\ni2cMuxAddress = 0x75\nadcAddress = 0x16\nVREF = 3.3\nFS = 0.5 * VREF\nopAmpGain = 101.0\ncurrent = 100 / 1000000.0\n#offset = - 3.40\noffset = 0\ntwoToTheTwentyFour = 16777216 # 2^24\n\n\ndef resistancetotemp(resistance):\n a = 0.00392 #standard coeff\n r0 = 100 #resistance at 0C\n \n numer = (resistance/r0) -1\n temper = numer/a\n #derived from equation: RTemp=R0(1+(a*temperature))\n return temper\n\ndef convertADC(adcReading):\n #print binascii.hexlify(adcReading)\n #print int(binascii.hexlify(adcReading), 16)\n mask = 0xFFFFFF\n inputShifted = int(binascii.hexlify(adcReading), 16) >> 6\n maskedOutput = mask & inputShifted\n #6 bit shift, 6 byte mask?\n #print(maskedOutput)\n voltageAcrossRTD = float(float(maskedOutput) / float(twoToTheTwentyFour)) #fpr 24 bit adc\n toVoltage = (voltageAcrossRTD * FS) / opAmpGain\n #print(\"FS: \" + str(FS))\n #print(voltageAcrossRTD)\n #print(\"ADC Voltage: \" + str(toVoltage))\n RTDResistance = (toVoltage / current) + offset\n #temperature = CVD_equation(RTDResistance)\n temperature=resistancetotemp(RTDResistance)\n print(\"Raw Temperature: \" + str(temperature) + \"C\")\n return temperature\n\ndef getChannel(channel):\n returnValue = 0xA0\n if channel == 1:\n returnValue |= 0b10000\n elif channel == 2:\n returnValue |= 0b11000\n elif channel == 3:\n returnValue |= 0b10001\n elif channel == 4:\n returnValue |= 0b11001\n return returnValue\n\ndef getChannelString(channel):\n if channel == \"1\":\n return \"ADC 1\"\n elif channel == \"2\":\n return \"ADC 2\"\n elif channel == \"3\":\n return \"ADC 3\"\n elif channel == \"4\":\n return \"ADC 4\"\n elif channel == \"5\":\n return \"I2C 1\"\n elif channel == \"6\":\n return \"I2C 2\"\n\ndef readADC(channel, dictionaryData):\n convertedChannel = getChannel(int(channel))\n print(adcAddress)\n print(\"readADC.py:readADC, channel: \" + str(channel))\n print(\"Converted channel: \" + str(convertedChannel) + \" Hex: \" + str(hex(convertedChannel)))\n temperature = 0\n temp=0\n numcount=0\n try:\n try:\n if pi.connected:\n print(\"Pigpio readADC already connected.\")\n except:\n pi = pigpio.pi()\n handle = pi.i2c_open(1, adcAddress)\n time.sleep(.02)\n #print handle\n #print(\"Try Writing...\")\n pi.i2c_write_byte(handle, convertedChannel)\n time.sleep(0.2)\n #print(\"Try Reading...\")\n (count, data) = pi.i2c_read_device(handle, 4)\n time.sleep(0.2)\n #print(\"Count: \" + str(count))\n #print(binascii.hexlify(data))\n #print int(data, 16)\n temperature = convertADC(data)\n gain = dictionaryData['gain' + channel]\n offset = dictionaryData['offset' + channel]\n print(\"Gain: \" + str(gain) + \"; Offset: \" + str(offset))\n for x in range(0,5):\n temp=convertADC(data)\n temp= (float(temp) - float(offset)) * float(gain)\n if(temp>1):\n temperature=temperature+temp\n numcount=numcount+1\n if(numcount>0):\n temperature=temperature/numcount\n #temperature = (float(temperature))\n pi.i2c_close(handle)\n time.sleep(0.1)\n except Exception as e:\n print(e)\n #os.system(\"sudo reboot\")\n os.system(\"python /home/pi/Documents/DataLogger/_software/restartI2C.py\")\n #print(\"END\")\n finally:\n if pi.connected:\n pi.stop()\n print(\"Adjusted Temperature: \" + str(temperature) + \"C\")\n return temperature\n\n# For tempData Table\n# Checks if a record with 'system' already exists. If not, INSERT, otherwise UPDATE\ndef checkIfChannelDataExists(channel):\n returnValue = False\n inputType = getChannelString(channel)\n conn = sqlite3.connect('/home/pi/Documents/DataLogger/_database/temperatures.db')\n cur = conn.cursor()\n statement = \"SELECT * FROM tempData WHERE inputType LIKE '\" + inputType + \"'\"\n #print(statement)\n cur.execute(statement)\n rows = cur.fetchall()\n #print(len(rows))\n if len(rows) > 0:\n returnValue = True\n #for line in rows:\n # print(line)\n conn.close()\n return returnValue\n\n# table 2 => TEMP\n# table 1 => DATA STORAGE\ndef insertIntoDatabase(channel, data, table = \"2\"):\n os.environ['TZ'] = 'America/Los_Angeles'\n time.tzset()\n dateNow = datetime.datetime.now()\n timeNow = dateNow.time()\n #print(dateNow)\n #print(timeNow)\n dictionaryData = uploadCSV.getAllDictionaries()\n system = dictionaryData['system'] #\"RPI_001\"\n inputType = getChannelString(channel)\n tempDataExistsForChannel = checkIfChannelDataExists(channel)\n conn = sqlite3.connect('/home/pi/Documents/DataLogger/_database/temperatures.db')\n statement = \"\"\n if table == \"1\":\n statement = \"INSERT INTO dataTable (system, inputType, data, date, time) VALUES ('\" + system + \"','\" + inputType + \"','\" + str(data) + \"','\" + str(dateNow) + \"','\" + str(timeNow) + \"')\"\n else:\n if tempDataExistsForChannel == True:\n statement = \"UPDATE tempData SET system = '\" + system + \"', data = '\" + str(data) + \"', date = '\" + str(dateNow) + \"', time = '\" + str(timeNow) + \"' WHERE inputType = '\" + inputType + \"'\"\n else:\n statement = \"INSERT INTO tempData (system, inputType, data, date, time) VALUES ('\" + system + \"','\" + inputType + \"','\" + str(data) + \"','\" + str(dateNow) + \"','\" + str(timeNow) + \"')\"\n print (\"Inserting Channel \" + channel + \" data: \" + data)\n #print(statement)\n conn.execute(statement)\n conn.commit()\n conn.close()\n\n####------------------------------------------------------- MAIN\n\ndef main():\n \"\"\"This is the main function. It takes 1 argument:\n Ex: python readADC.py 1\\t Writes to dataTable in database\n Ex: python readADC.py 2\\t Writes to tempTable in database\"\"\"\n # channel min\n # channel max\n # channel units\n # channel interval\n # channel upload ftp link\n #configureI2CMux()\n \n args = sys.argv\n i2cMux.readI2CMux(1)\n dictionaryData = uploadCSV.getAllDictionaries()\n count=0\n if len(args) > 2:\n table = args[1]\n channel = args[2]\n temperature = readADC(channel, dictionaryData)\n tempFormatted = \"{0:.2f}\".format(temperature)\n print(\"ADC Reading, Channel #\" + str(channel) + \": \" + \"\\n\" + tempFormatted)\n # Insert data into database\n #print(\"Inserting into database: \" + tempFormatted + \"for channel \" + channel)\n if(tempFormatted > 0):\n insertIntoDatabase(channel, tempFormatted, table)\n \n # If full day reached (12:00am), generate text file from database data and\n # upload to FTP (if file is uploaded daily)\n\nmain()\n","repo_name":"icenginc/DataLogger","sub_path":"_software/readADC.py","file_name":"readADC.py","file_ext":"py","file_size_in_byte":6914,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"}
+{"seq_id":"10049348123","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n# @File: cao.py\n# @Author: dell\n# @Date: 2020/9/2 17:07\n# @Desc: \n# @Project: licode\n# @Source: PyCharm\n\nimport re\nimport time\n\nimport paramiko\n\n\nclass Demo:\n\n def __init__(self):\n self._transport = None\n self._channel = None\n self._count = 0\n\n def transport_connect(self, info):\n self._transport = paramiko.Transport((info[0], info[1]))\n self._transport.start_client()\n self._transport.auth_password(info[2], info[3])\n\n self._channel = self._transport.open_session()\n self._channel.get_pty()\n\n self._channel.invoke_shell()\n\n return self._transport, self._channel\n\n def transport_disconnect(self):\n if self._channel:\n self._channel.close()\n if self._transport:\n self._transport.close()\n\n def send(self, cmd, channel, max_time=100):\n # command = cmd\n self._count += 1\n cmd += \"\\r\"\n p = re.compile(r'\\[root.*?\\]#')\n result = ''\n self._channel.send(cmd)\n # self._channel.settimeout(max_time)\n while max_time > 0:\n time.sleep(0.2)\n ret = self._channel.recv(65535)\n ret = ret.decode(\"utf-8\")\n result += ret\n print(ret)\n if len(p.findall(result)) == 2 and self._count == 1:\n break\n if len(p.findall(result)) == 1 and self._count > 1:\n break\n max_time -= 1\n return result\n\n @staticmethod\n def send_middle(cmd, channel):\n cmd += \"\\n\"\n channel.send(cmd)\n time.sleep(0.5)\n ret = channel.recv(65535)\n ret = ret.decode('utf-8')\n print(\"%s cmd output is : \" % cmd + ret)\n return ret\n\n\nif __name__ == '__main__':\n ip_info = ['172.28.37.110', 9622, 'root', \"ruijie\"]\n transport = Demo()\n channel = transport.transport_connect(ip_info)[1]\n transport.send('cd vdbench', channel)\n transport.send('ls -l', channel)\n\n cmd_write = \"dd if=/dev/urandom of=/home/gejian/test2.log bs=1M count=1000\"\n\n cmd_cksum = \"cksum /home/gejian/test2.log | awk '{print $1}'\"\n\n transport.send(cmd_write, channel)\n transport.send(cmd_cksum, channel)\n # input_pwd = \"Are you sure you want to continue connecting (yes/no)?\"\n #\n # tmp1 = transport.send_middle(\"/opt/java/zookeeper/bin/zkCli.sh\", channel)\n # if \"zk: localhost:2181(CONNECTING)\" in tmp1:\n # tmp2 = transport.send_middle(\"get /pos/cluster/nodes/1\", channel)\n\n transport.transport_disconnect()\n","repo_name":"freechenh/licode","sub_path":"day07/cao.py","file_name":"cao.py","file_ext":"py","file_size_in_byte":2566,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"}
+{"seq_id":"23784964169","text":"import RPi.GPIO as GPIO\nimport board\nimport adafruit_dht\nimport sys\nsys.path.insert(1,'./i2clibraries')\nfrom i2c_hmc5883l import *\nfrom i2c_adxl345 import *\nfrom i2c_itg3205 import *\nfrom time import *\nimport drivers\nimport time\n\ndhtDevice = adafruit_dht.DHT22(board.D14)\ntemperature_c = dhtDevice.temperature\ntemperature_f = temperature_c * (9/5) + 32\nhumidity = dhtDevice.humidity\nledPin = 20 # define the ledPin\nsensorPin = 21 # define the sensorPin\n\ndisplay =drivers.Lcd()\n\nhmc5883l = i2c_hmc5883l(1)\n#i = 1\n\nhmc5883l.setContinuousMode ()\nhmc5883l.setDeclination (2,4)\n\nadxl345 = i2c_adxl345(1)\n\nitg3205 = i2c_itg3205(1)\n\n\nprint ('Program is starting...')\nGPIO.setwarnings(False)\nGPIO.setmode(GPIO.BCM) # Numbers GPIOs by GPIO\nGPIO.setup(ledPin, GPIO.OUT) # Set ledPin's mode is output\nGPIO.setup(sensorPin, GPIO.IN)\n\nwhile True:\n try:\n display.lcd_clear()\n (itgready, dataready) = itg3205.getInterruptStatus ()\n temperature_c = dhtDevice.temperature\n if dataready:\n temp = itg3205.getDieTemperature ()\n (x, y, z) = itg3205.getDegPerSecAxes ()\n print (\"Temp:\" + str (temp ))\n print (\"X:\" + str (x ))\n print (\"Y:\" + str (y ))\n print (\"Z:\" + str (z ))\n print (\"\")\n display.lcd_display_string((\"Xg:\" + str (x )) , 1)\n display.lcd_display_string((\"Yg:\" + str (y )) , 2)\n time.sleep(2)\n display.lcd_display_string((\"Zg:\" + str (z )) , 1)\n if GPIO.input(sensorPin)==GPIO.HIGH:\n GPIO.output(ledPin,GPIO.HIGH)\n print('led on...')\n print(\"Temp:{:.1f}F/{:.1f}C Humidity:{}%\".format(temperature_f,temperature_c,humidity))\n print (adxl345)\n temp= \"temp: \" + str(temperature_c)\n hum= \"humid: \" + str(humidity)\n display.lcd_display_string(temp, 1)\n display.lcd_display_string(hum, 2)\n time.sleep(2)\n (xacc, yacc, zacc) = adxl345.getAxes()\n display.lcd_display_string((\"Xa:\" + str (xacc )) , 1)\n display.lcd_display_string((\"Ya:\" + str (yacc )) , 2)\n time.sleep(2)\n display.lcd_display_string((\"Za:\" + str (zacc )) , 1)\n else: \n GPIO.output(ledPin,GPIO.LOW)\n print ('led off...')\n (xcom, ycom, zcom) = hmc5883l.getAxes()\n print(hmc5883l)\n display.lcd_display_string((\"Xc:\" + str (xcom )) , 1)\n display.lcd_display_string((\"Yc:\" + str (ycom )) , 2)\n time.sleep(2)\n display.lcd_display_string((\"Zc:\" + str (zcom )) , 1)\n sleep(2)\n\n except RuntimeError as error:\n # Errors happen fairly often, DHT's are hard to read, just keep going\n print(error.args[0])\n time.sleep(2.0)\n continue\n except Exception as error:\n dhtDevice.exit()\n raise error\n\n time.sleep(2.0) \nif __name__ =='__main__':\n setup()\n try:\n loop()\n except KeyboardInterrupt:\n\n GPIO.cleanup()\n","repo_name":"Arissa97/home","sub_path":"mylib/sensorINT.py","file_name":"sensorINT.py","file_ext":"py","file_size_in_byte":3047,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"}
+{"seq_id":"74415473653","text":"import os\nfrom pathlib import Path\nimport re\nimport subprocess\nimport dbus\nfrom .log_utils import get_logger\n\n\nclass CheckError(Exception):\n pass\n\n\ndef check_running_graphical_session():\n return subprocess.run(\n \"xhost\",\n shell=True,\n stdout=subprocess.DEVNULL,\n stderr=subprocess.DEVNULL\n ).returncode == 0\n\n\ndef is_ac_power_connected():\n\n for power_source_path in Path(\"/sys/class/power_supply/\").iterdir():\n\n try:\n\n with open(power_source_path / \"type\", 'r') as f:\n if f.read().strip() != \"Mains\":\n continue\n\n with open(power_source_path / \"online\", 'r') as f:\n if f.read(1) == \"1\":\n return True\n\n except IOError:\n continue\n\n return False\n\n\ndef is_pat_available():\n return subprocess.run(\n \"grep -E '^flags.+ pat( |$)' /proc/cpuinfo\",\n shell=True, stdout=subprocess.DEVNULL\n ).returncode == 0\n\n\ndef get_active_renderer():\n\n if _is_gl_provider_nvidia():\n return \"nvidia\"\n else:\n return \"integrated\"\n\n\ndef is_module_available(module_name):\n\n return subprocess.run(\n f\"modinfo -n {module_name}\",\n shell=True, stdout=subprocess.DEVNULL\n ).returncode == 0\n\ndef is_module_loaded(module_name):\n\n return subprocess.run(\n f\"lsmod | grep -E \\\"^{module_name}\\\"\",\n shell=True, stdout=subprocess.DEVNULL\n ).returncode == 0\n\ndef get_current_display_manager():\n\n if not os.path.isfile(\"/etc/systemd/system/display-manager.service\"):\n raise CheckError(\"No display-manager.service file found\")\n\n dm_service_path = os.path.realpath(\"/etc/systemd/system/display-manager.service\")\n dm_service_filename = os.path.split(dm_service_path)[-1]\n dm_name = os.path.splitext(dm_service_filename)[0]\n\n return dm_name\n\n\ndef using_patched_GDM():\n\n folder_path_1 = \"/etc/gdm/Prime\"\n folder_path_2 = \"/etc/gdm3/Prime\"\n\n return os.path.isdir(folder_path_1) or os.path.isdir(folder_path_2)\n\ndef check_offloading_available():\n\n try:\n out = subprocess.check_output(\n \"xrandr --listproviders\", shell=True, text=True, stderr=subprocess.PIPE).strip()\n except subprocess.CalledProcessError as e:\n raise CheckError(f\"Cannot list xrandr providers:\\n{e.stderr}\") from e\n\n for line in out.splitlines():\n if re.search(\"^Provider [0-9]+:\", line) and \"name:NVIDIA-G0\" in line:\n return True\n return False\n\n\ndef is_xorg_intel_module_available():\n return os.path.isfile(\"/usr/lib/xorg/modules/drivers/intel_drv.so\")\n\ndef is_xorg_amdgpu_module_available():\n return os.path.isfile(\"/usr/lib/xorg/modules/drivers/amdgpu_drv.so\")\n\n\ndef is_login_manager_active():\n return _is_service_active(\"display-manager\")\n\n\ndef is_daemon_active():\n return _is_service_active(\"optimus-manager\")\n\n\ndef is_bumblebeed_service_active():\n return _is_service_active(\"bumblebeed\")\n\n\ndef _is_gl_provider_nvidia():\n\n try:\n out = subprocess.check_output(\n \"__NV_PRIME_RENDER_OFFLOAD=0 glxinfo\",\n shell=True, text=True, stderr=subprocess.PIPE).strip()\n except subprocess.CalledProcessError as e:\n raise CheckError(f\"Cannot run glxinfo: {e.stderr}\") from e\n\n for line in out.splitlines():\n if \"server glx vendor string: NVIDIA Corporation\" in line:\n return True\n return False\n\n\ndef _is_service_active(service_name):\n\n logger = get_logger()\n\n try:\n system_bus = dbus.SystemBus()\n except dbus.exceptions.DBusException:\n logger.warning(\n \"Cannot communicate with the DBus system bus to check status of %s.\"\n \" Is DBus running ? Falling back to bash commands\", service_name)\n return _is_service_active_bash(service_name)\n else:\n return _is_service_active_dbus(system_bus, service_name)\n\ndef _is_service_active_dbus(system_bus, service_name):\n\n systemd = system_bus.get_object(\"org.freedesktop.systemd1\", \"/org/freedesktop/systemd1\")\n\n try:\n unit_path = systemd.GetUnit(\"%s.service\" % service_name, dbus_interface=\"org.freedesktop.systemd1.Manager\")\n except dbus.exceptions.DBusException:\n return False\n\n optimus_manager_interface = system_bus.get_object(\"org.freedesktop.systemd1\", unit_path)\n properties_manager = dbus.Interface(optimus_manager_interface, 'org.freedesktop.DBus.Properties')\n state = properties_manager.Get(\"org.freedesktop.systemd1.Unit\", \"SubState\")\n\n return state == \"running\"\n\n\ndef _is_service_active_bash(service_name):\n\n return subprocess.run(\n f\"systemctl is-active {service_name}\", shell=True\n ).returncode == 0\n","repo_name":"Askannz/optimus-manager","sub_path":"optimus_manager/checks.py","file_name":"checks.py","file_ext":"py","file_size_in_byte":4670,"program_lang":"python","lang":"en","doc_type":"code","stars":2118,"dataset":"github-code","pt":"21"}
+{"seq_id":"37448940302","text":"import sys\r\nline = sys.stdin.readline\r\n\r\nn,m=map(int,line().split())\r\n\r\np=[int(line()) for _ in range(m)]\r\n\r\np.sort(reverse=True)\r\n\r\nanswer=[0]*m\r\n\r\nfor i,j in enumerate(p):\r\n answer[i]=j*(min(i+1,n))\r\n\r\nmax_p=answer.index(max(answer))\r\nprint(p[max_p],answer[max_p])\r\n","repo_name":"sunsu2737/algorithm","sub_path":"VSP/S1246.py","file_name":"S1246.py","file_ext":"py","file_size_in_byte":271,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"}
+{"seq_id":"41134988217","text":"# -*- coding: utf-8 -*-\n\n\"\"\"\nAuthor: XXM\ndate: 2020/8/18 20:51\ndesc: \n\"\"\"\n# PySide2 引入线程类和信号\nfrom PySide2.QtCore import QThread, Signal # 注意区别就在于这里的信号是 Signal,和 PyQt5 不一样,而线程类是一样的\nfrom multiprocessing import Pool\nimport time, threading\n\n\nclass NewThread(QThread):\n signal = Signal(object) # 自定义信号,其中 object 为信号承载数据的类型\n\n def __init__(self, parent=None):\n super().__init__()\n self.x = 0 # 线程中自定义变量\n\n # 线程内可自定义其他函数\n def custom_function(self):\n # self.kit.appendPlainText(str(self.x))\n self.x += 1\n time.sleep(0.4)\n # QThread.msleep(1000)\n\n # new_thread = NewThread()\n\n # 通过 new_thread.start() 调用此 run() 函数\n def run(self):\n for _ in range(300):\n self.custom_function()\n self.signal.emit(self.x) # 发射信号\n\n\nif __name__ == '__main__':\n new_thread = NewThread()\n\n new_thread.start() # 为线程分配资源,让它执行\n\n # 下面两个都是停止执行,但我一般用第二个\n new_thread.wait()\n new_thread.terminate()\n","repo_name":"wo-woa/tools","sub_path":"useful/kit/NewThreadKit.py","file_name":"NewThreadKit.py","file_ext":"py","file_size_in_byte":1196,"program_lang":"python","lang":"zh","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"}
+{"seq_id":"23442239511","text":"import json\nimport os.path\nimport time\n\nfrom bunch import Bunch\nfrom watchdog.events import PatternMatchingEventHandler\nfrom watchdog.observers import Observer\n\nclass SettingsChangeHandler(PatternMatchingEventHandler):\n def __init__(self, *args, **kwargs):\n self.settings = kwargs.get(\"settings\")\n del(kwargs[\"settings\"])\n super().__init__(*args, **kwargs)\n for path in kwargs.get(\"patterns\"):\n self.update(path)\n \n def update(self, path):\n with open(path) as conf:\n self.settings.update(json.load(conf))\n\n def on_modified(self, event):\n print(\"Settings modified on disk, reloading\")\n self.update(event.src_path)\n \nclass Settings(Bunch):\n def __init__(self, settings_path):\n super().__init__()\n event_handler = SettingsChangeHandler(settings=self, patterns=[settings_path])\n self.observer = Observer()\n self.observer.schedule(event_handler, os.path.abspath(os.path.join(settings_path, os.pardir)), recursive=False)\n self.observer.start()\n \n def stop(self):\n self.observer.stop()\n\n def join(self):\n self.observer.join()\n","repo_name":"ptone/remote-live-config","sub_path":"python-live-read-example/settings.py","file_name":"settings.py","file_ext":"py","file_size_in_byte":1170,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"}
+{"seq_id":"24376005676","text":"# Import packages.\nimport allel\nimport numpy as np\nimport numcodecs\nimport pandas as pd\nimport sys\nimport zarr\n\n### sys.argv[1] = chromosome ###\n### sys.argv[2] = window size ###\n\n\n# Define a function to load genotyope and positions arrays.\ndef load_callset_pos(prefix, chrom):\n # Intialize the file path.\n path = '../vcf_data/zarr_data/{0}_chr{1}.zarr'.format(prefix, chrom)\n # Load the zarr array.\n zarr_array = zarr.open_group(path, mode='r')\n # Extract the genotype callset.\n callset = zarr_array['{0}/calldata/GT'.format(chrom)]\n # Load the positions.\n pos = allel.SortedIndex(zarr_array['{0}/variants/POS'.format(chrom)])\n return callset, pos\n\n# Define a function to calculate alternative allele frequencies.\ndef calc_alt_freqs(gt):\n # If there are no altenative alleles...\n if (gt.count_alleles().shape[1] == 1):\n # Calculate alternative allele frequencies.\n alt_freqs = gt.count_alleles().to_frequencies()[:, 0] - 1\n # Else...\n else:\n # Calculate alternative allele frequencies.\n alt_freqs = gt.count_alleles().to_frequencies()[:, 1]\n return alt_freqs\n\n# Define a function to calculate alternative allele frequencies for the archaics\ndef calc_arc_alt_freqs(arc_gt):\n # Compute the frequency for each site.\n raw_freqs = np.nansum(arc_gt, axis=2).flatten() / 2\n # Set missing data to Nan\n alt_freqs = np.where(raw_freqs == -1, np.nan, raw_freqs)\n return alt_freqs\n\n# Define a function to count the number of archaic specific derived snps.\ndef count_arc_der_sites(gt, pop_dicc):\n # Calculate alternative allele frequencies.\n afr_alt_freq = calc_alt_freqs(gt.take(pop_dicc['AFR'], axis=1))\n ooa_alt_freq = calc_alt_freqs(gt.take(pop_dicc['OOA'], axis=1))\n alt_alt_freq = calc_arc_alt_freqs(gt.take(pop_dicc['ALT'], axis=1))\n cha_alt_freq = calc_arc_alt_freqs(gt.take(pop_dicc['CHA'], axis=1))\n vin_alt_freq = calc_arc_alt_freqs(gt.take(pop_dicc['VIN'], axis=1))\n den_alt_freq = calc_arc_alt_freqs(gt.take(pop_dicc['DEN'], axis=1))\n anc_freq = calc_alt_freqs(gt.take([-1], axis=1))\n # Polarize the samples.\n afr_der_freq = np.where(anc_freq == 1, np.abs(afr_alt_freq - 1), afr_alt_freq)\n ooa_der_freq = np.where(anc_freq == 1, np.abs(ooa_alt_freq - 1), ooa_alt_freq)\n alt_der_freq = np.where(anc_freq == 1, np.abs(alt_alt_freq - 1), alt_alt_freq)\n cha_der_freq = np.where(anc_freq == 1, np.abs(cha_alt_freq - 1), cha_alt_freq)\n vin_der_freq = np.where(anc_freq == 1, np.abs(vin_alt_freq - 1), vin_alt_freq)\n den_der_freq = np.where(anc_freq == 1, np.abs(den_alt_freq - 1), den_alt_freq)\n # Intialize conditions.\n c_hum = (afr_der_freq < 0.01) & (ooa_der_freq > 0)\n c_den = (den_der_freq == 1)\n c_not_den = (den_der_freq != 1)\n c_alt = (alt_der_freq == 1)\n c_not_alt = (alt_der_freq != 1)\n c_cha = (cha_der_freq == 1)\n c_not_cha = (cha_der_freq != 1)\n c_vin = (vin_der_freq == 1)\n c_not_vin = (vin_der_freq != 1)\n c_nea = c_alt | c_cha | c_vin\n c_not_nea = c_not_alt & c_not_cha & c_not_vin\n # Determine the archaic specific sites.\n den_only_idx = np.where(c_hum & c_not_nea & c_den)[0]\n nea_only_idx = np.where(c_hum & c_not_den & c_nea)[0]\n return [den_only_idx.size, nea_only_idx.size]\n\n# Define a function to count the number of archaic specific ancestral snps.\ndef count_arc_anc_sites(gt, pop_dicc):\n # Calculate alternative allele frequencies.\n afr_alt_freq = calc_alt_freqs(gt.take(pop_dicc['AFR'], axis=1))\n ooa_alt_freq = calc_alt_freqs(gt.take(pop_dicc['OOA'], axis=1))\n alt_alt_freq = calc_arc_alt_freqs(gt.take(pop_dicc['ALT'], axis=1))\n cha_alt_freq = calc_arc_alt_freqs(gt.take(pop_dicc['CHA'], axis=1))\n vin_alt_freq = calc_arc_alt_freqs(gt.take(pop_dicc['VIN'], axis=1))\n den_alt_freq = calc_arc_alt_freqs(gt.take(pop_dicc['DEN'], axis=1))\n anc_freq = calc_alt_freqs(gt.take([-1], axis=1))\n # Polarize the samples.\n afr_der_freq = np.where(anc_freq == 1, np.abs(afr_alt_freq - 1), afr_alt_freq)\n ooa_der_freq = np.where(anc_freq == 1, np.abs(ooa_alt_freq - 1), ooa_alt_freq)\n alt_der_freq = np.where(anc_freq == 1, np.abs(alt_alt_freq - 1), alt_alt_freq)\n cha_der_freq = np.where(anc_freq == 1, np.abs(cha_alt_freq - 1), cha_alt_freq)\n vin_der_freq = np.where(anc_freq == 1, np.abs(vin_alt_freq - 1), vin_alt_freq)\n den_der_freq = np.where(anc_freq == 1, np.abs(den_alt_freq - 1), den_alt_freq)\n # Intialize conditions.\n c_hum = ((1 - afr_der_freq) < 0.01) & ((1 - ooa_der_freq) > 0)\n c_den = (den_der_freq == 0)\n c_not_den = (den_der_freq != 0)\n c_alt = (alt_der_freq == 0)\n c_not_alt = (alt_der_freq != 0)\n c_cha = (cha_der_freq == 0)\n c_not_cha = (cha_der_freq != 0)\n c_vin = (vin_der_freq == 0)\n c_not_vin = (vin_der_freq != 0)\n c_nea = c_alt | c_cha | c_vin\n c_not_nea = c_not_alt & c_not_cha & c_not_vin\n # Determine the archaic specific sites.\n den_only_idx = np.where(c_hum & c_not_nea & c_den)[0]\n nea_only_idx = np.where(c_hum & c_not_den & c_nea)[0]\n return [den_only_idx.size, nea_only_idx.size]\n\n# Define a function to compute archaic snp denisty.\ndef tgp_arc_snp_denisty(chromosome, window_size):\n # Load in the meta information as a pandas dataframe.\n tgp_meta_df = pd.read_csv(\n '../meta_data/tgp_mod.txt', sep='\\t',\n names=['IND', 'POP', 'SUPERPOP'],\n )\n # Intialize a dictionary to store all sample indicies.\n samp_idx_dicc = {\n 'ALT': np.array([2347]), 'CHA': np.array([2348]),\n 'VIN': np.array([2349]), 'DEN': np.array([2350]),\n }\n # Append the dictionary with sample AFR and OOA indicies.\n samp_idx_dicc['AFR'] = tgp_meta_df[tgp_meta_df['SUPERPOP'] == 'AFR'].index.values\n samp_idx_dicc['OOA'] = tgp_meta_df[tgp_meta_df['SUPERPOP'] != 'AFR'].index.values\n # Extract the genotype callset and positions.\n callset, all_pos = load_callset_pos('tgp_mod_arc_anc', chromosome)\n # Load the windows data frame.\n qc_windows_df = pd.read_csv('../windowing/tgp/{0}kb_nonoverlapping_variant_windows.csv.gz'.format(window_size))\n # Subset the the windows for the chromosome.\n chr_qc_windows_df = qc_windows_df[qc_windows_df['CHR'] == chromosome]\n # Extract the start and stop positions.\n chr_starts = chr_qc_windows_df['START'].values\n chr_stops = chr_qc_windows_df['STOP'].values\n # Determine the number of windows.\n n_windows = chr_qc_windows_df.shape[0]\n # Intialize a results matrix to store the results.\n results_mat = np.empty((n_windows, 4))\n # For every window...\n for wind in range(n_windows):\n # Locate the window.\n wind_loc = all_pos.locate_range(chr_starts[wind], chr_stops[wind])\n # Compute the number of derived and ancestral archaic snps.\n c_der = count_arc_der_sites(\n gt=allel.GenotypeArray(callset[wind_loc]), pop_dicc=samp_idx_dicc,\n )\n c_anc = count_arc_anc_sites(\n gt=allel.GenotypeArray(callset[wind_loc]), pop_dicc=samp_idx_dicc,\n )\n # Append the results matrix\n results_mat[wind, :] = np.array(c_der+c_anc)\n # Compile the results file name.\n results_file = f'chr{chromosome}_{window_size}kb.csv.gz'\n # Export the the results matrix.\n np.savetxt(\n './tgp/windows/'+results_file,\n results_mat, fmt='%d', delimiter=',', newline='\\n',\n )\n return\n\n# Compute the archaic allele density.\ntgp_arc_snp_denisty(\n chromosome=int(sys.argv[1]),\n window_size=int(sys.argv[2]),\n)\n","repo_name":"David-Peede/MUC19","sub_path":"arc_snp_density/tgp_arc_snp_density_windows.py","file_name":"tgp_arc_snp_density_windows.py","file_ext":"py","file_size_in_byte":7508,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"}
+{"seq_id":"23522952785","text":"from PIL import Image, ImageDraw\nimport random as rd\n\nrd.seed(0)\n\n\ndef draw_rectangle(draw, color):\n x = rd.randint(11, 21)\n y = rd.randint(11, 21)\n draw.rectangle((x - 5, y - 5, x + 5, y + 5), fill=color)\n\n\ndef generate_scene(path, idx):\n img = Image.new('RGB', (32, 32))\n draw = ImageDraw.Draw(img)\n\n draw_rectangle(draw, \"blue\")\n\n img.save(f\"simple/images/{path}/{str(idx) + '.png'}\")\n\n\nfor i in range(20000):\n generate_scene(\"train\", i)\n\nfor i in range(5000):\n generate_scene(\"test\", i)\n\nfor i in range(5000):\n generate_scene(\"val\", i)","repo_name":"356255531/ulgie_translation","sub_path":"data/gen.py","file_name":"gen.py","file_ext":"py","file_size_in_byte":569,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"}
+{"seq_id":"37223986278","text":"import seaborn as sns\nimport pandas as pd\nimport matplotlib.pyplot as plt\n\ndf = sns.load_dataset('titanic')\nprint(df.head())\nprint(df.describe())\nprint(df.info())\ntrain_df = df[:800]\ntest_df = df[800:]\nprint(len(train_df))\nprint(len(test_df))\nprint(train_df[['pclass', 'survived']].groupby(['pclass'], as_index=False).mean().sort_values(by='survived',\n ascending=False))\nprint(train_df[['sex', 'survived']].groupby(['sex'], as_index=False).mean().sort_values(by='survived', ascending=False))\nprint(train_df[['parch', 'survived']].groupby(['parch'], as_index=False).mean().sort_values(by='survived',\n ascending=False))\nprint(train_df[['sibsp', 'survived']].groupby(['sibsp'], as_index=False).mean().sort_values(by='survived',\n ascending=False))\n\nsns.histplot(data=train_df, x='age', bins=20, hue='survived')\na = sns.FacetGrid(train_df, col='survived')\na.map(plt.hist, 'age', bins=20)\n\na = sns.FacetGrid(train_df, col='survived', row='pclass')\na.map(plt.hist, 'age', bins=20)\n\nplt.show()\n\nnames = train_df.columns\nprint(names)\n\ntrain_df = train_df.drop(names[4:], axis=1)\nprint(train_df.head())\n\ntest_df = test_df.drop(names[4:], axis=1)\nprint(test_df.head())\n\nprint(train_df.isnull().sum())\nprint(test_df.isnull().sum())\n\ntrain_df.fillna(train_df.mean()[['age']], inplace=True)\ntest_df.fillna(test_df.mean()[['age']], inplace=True)\n\nprint(train_df.isnull().sum())\nprint(test_df.isnull().sum())\n\n# 성별 인코딩\nmap_dict = {'female': 0, 'male': 1}\ntrain_df['sex'] = train_df['sex'].map(map_dict).astype(int)\ntest_df['sex'] = test_df['sex'].map(map_dict).astype(int)\n\n\n# 나이 분류\ndef function1(x):\n if x < 20:\n return 1\n elif x < 40:\n return 2\n elif x < 60:\n return 3\n else:\n return 4\n\n\ntrain_df['age'] = train_df['age'].apply(function1)\ntest_df['age'] = test_df['age'].apply(function1)\n\nprint(train_df.head())\nprint(test_df.head())\n\nfrom sklearn.tree import DecisionTreeClassifier\n\nX_train = train_df.drop(['survived'], axis=1)\nY_train = train_df['survived']\nX_test = test_df.drop(['survived'], axis=1)\nY_test = test_df['survived']\n\nprint(X_train.head())\nprint(Y_train.head())\n\n# 모델 생성 및 학습\ndecision_tree = DecisionTreeClassifier()\ndecision_tree.fit(X_train, Y_train)\n\n# 모델 정확도 검증\nprint(decision_tree.score(X_train, Y_train))\nprint(decision_tree.score(X_test, Y_test))\n\n# 실제 값 예측값 비교 구현\nY_pred = decision_tree.predict(X_test)\nprint(Y_pred)\nprint(Y_test)\nprint(len(Y_pred))\nprint(len(Y_test))\n\nY_test_list = list(Y_test)\nprint(Y_pred[0])\nprint(Y_test_list[0])\n\ntotal = 0\nfor i in range(len(Y_pred)):\n if Y_pred[i] == Y_test_list[i]:\n total += 1\n else:\n pass\nprint(total)\nprint(total / len(Y_pred))\n\nfrom sklearn.tree import export_graphviz\n\nexport_graphviz(\n decision_tree,\n out_file='titanic.dot',\n feature_names=['pclass', 'sex', 'age'],\n class_names=['Unsurvived', 'Survived'],\n filled=True\n)\n\nimport graphviz\nf = open('titanic.dot')\ndot_graph = f.read()\ndot = graphviz.Source(dot_graph)\ndot.format = 'png'\ndot.render(filename='titanic_tree')\nprint(dot)\n\n","repo_name":"badjiyoon/da_study","sub_path":"KimJiYoon/Part2/CH05/CH05_23.py","file_name":"CH05_23.py","file_ext":"py","file_size_in_byte":3361,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"}
+{"seq_id":"16820683293","text":"from flask import Blueprint, request, render_template, redirect, url_for, flash\nfrom flask_login import current_user\nfrom models.follow import Follow\nfrom models.user import User\n\nfollows_blueprint = Blueprint('follows', __name__, template_folder='templates')\n\n\n@follows_blueprint.route('//create')\ndef create(id):\n if id == current_user.id:\n flash(u'you cannot follow yourself -.-', 'warning')\n return redirect(request.referrer)\n\n user = User.get_or_none(User.id == id)\n if not user:\n flash(u'that user does not exist :(', 'danger')\n return redirect(request.referrer)\n\n if user.is_followed:\n flash(u'you are already following that user', 'danger')\n return redirect(request.referrer)\n\n new_follow = Follow(fan_id=current_user.id, idol_id=id)\n if not new_follow.save():\n flash(u'sorry, could not process the request:(', 'danger')\n return redirect(request.referrer)\n\n flash(u'Followed successfully!!', 'success')\n return redirect(request.referrer)\n\n\n@follows_blueprint.route('//delete')\ndef delete(id):\n user = User.get_or_none(User.id == id)\n\n if not user:\n flash(u'sorry that user does not exist.', 'danger')\n return redirect(url_for('users.index'))\n\n if not user.is_followed:\n flash(u'sorry, you are not currently following that user, so no need to unfollow.', 'warning')\n return redirect(url_for('users.index'))\n\n follow = Follow.get_or_none(\n Follow.fan_id == current_user.id, Follow.idol_id == id)\n\n if not follow.delete_instance(recursive=True):\n flash(\n f'database shows no instance of you following {user.username}', 'danger')\n return redirect(request.referrer)\n\n flash('Unfollowed successfully', 'success')\n return redirect(request.referrer)\n\n\n@follows_blueprint.route('//show/following')\ndef show_idols(id):\n\n idols = [user.idol for user in Follow.select().where(\n Follow.fan_id == current_user.id)]\n return render_template('follows/idols.html', idols=idols)\n\n\n@follows_blueprint.route('//show/followers')\ndef show_fans(id):\n fans = [user.fan for user in Follow.select().where(\n Follow.idol_id == current_user.id)]\n return render_template('follows/fans.html', fans=fans)\n","repo_name":"shenyang44/nextagram-python","sub_path":"instagram_web/blueprints/follows/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2283,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"21"}
+{"seq_id":"20449071047","text":"#!/usr/bin/env python3\n\"\"\"\n2. Initialize Multinormal class\n\"\"\"\n\nimport numpy as np\n\n\nclass MultiNormal:\n \"\"\"\n Multinormal Class\n \"\"\"\n\n def __init__(self, data):\n \"\"\" Constructor method\n Args:\n data - is a numpy.ndarray of shape (d, n) containing\n the data set:\n n is the number of data points\n d is the number of dimensions in each data point\n \"\"\"\n\n if (not type(data) == np.ndarray) or (len(data.shape) != 2):\n raise TypeError(\"data must be a 2D numpy.ndarray\")\n n = data.shape[1]\n if n < 2:\n raise ValueError(\"data must contain multiple data points\")\n self.mean_cov(data)\n\n def mean_cov(self, X):\n \"\"\" Calculates the mean and covariance of a data set\n Args:\n X - is a numpy.ndarray of shape (n, d) containing the data set\n n: is the number of data points\n d: is the number of dimensions in each data point\n Returns:\n mean - is a numpy.ndarray of shape (1, d) containing the mean\n of the data set\n cov - is a numpy.ndarray of shape (d, d) containing the covariance\n matrix of the data set\n \"\"\"\n d = X.shape[0]\n n = X.shape[1]\n self.mean = np.mean(X, axis=1).reshape(d, 1)\n X = X - self.mean\n self.cov = ((np.dot(X, X.T)) / (n - 1))\n\n def pdf(self, x):\n \"\"\" Calculates the PDF at a data point\n Args:\n x is a numpy.ndarray of shape (d, 1) containing the data point\n whose PDF should be calculated\n Returns:\n The value of the PDF\n \"\"\"\n\n if (not type(x) == np.ndarray):\n raise TypeError(\"x must be a numpy.ndarray\")\n d = self.cov.shape[0]\n if (len(x.shape) != 2 or x.shape[1] != 1 or x.shape[0] != d):\n raise ValueError(\"x must have the shape ({}, 1)\".format(d))\n\n x_m = x - self.mean\n pdf = (1 / (np.sqrt((2 * np.pi)**d * np.linalg.det(self.cov)))\n * np.exp(-(np.linalg.solve(self.cov, x_m).T.dot(x_m)) / 2))\n\n return float(pdf)\n","repo_name":"nildiert/holbertonschool-machine_learning","sub_path":"math/0x06-multivariate_prob/multinormal.py","file_name":"multinormal.py","file_ext":"py","file_size_in_byte":2175,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"21"}
+{"seq_id":"37636610931","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.db import models, migrations\nfrom django.conf import settings\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n migrations.swappable_dependency(settings.AUTH_USER_MODEL),\n ]\n\n operations = [\n migrations.CreateModel(\n name='BrandName',\n fields=[\n ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),\n ('name', models.CharField(max_length=250, verbose_name=b'\\xd0\\x91\\xd1\\x80\\xd0\\xb5\\xd0\\xbd\\xd0\\xb4')),\n ],\n options={\n 'verbose_name': '\\u0411\\u0440\\u0435\\u043d\\u0434\\u044b',\n 'verbose_name_plural': '\\u0411\\u0440\\u0435\\u043d\\u0434',\n },\n bases=(models.Model,),\n ),\n migrations.CreateModel(\n name='CodeCpa',\n fields=[\n ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),\n ('shop', models.CharField(max_length=500, verbose_name=b'\\xd0\\x9d\\xd0\\xb0\\xd0\\xb7\\xd0\\xb2\\xd0\\xb0\\xd0\\xbd\\xd0\\xb8\\xd0\\xb5', blank=True)),\n ('code', models.CharField(max_length=1000, verbose_name=b'\\xd0\\x9a\\xd0\\xbe\\xd0\\xb4 \\xd0\\xbc\\xd0\\xb0\\xd0\\xb3\\xd0\\xb0\\xd0\\xb7\\xd0\\xb8\\xd0\\xbd\\xd0\\xb0')),\n ],\n options={\n 'verbose_name': '\\u041a\\u043e\\u0434\\u044b \\u043c\\u0430\\u0433\\u0430\\u0437\\u0438\\u043d\\u043e\\u0432',\n 'verbose_name_plural': '\\u041a\\u043e\\u0434 \\u043c\\u0430\\u0433\\u0430\\u0437\\u0438\\u043d\\u0430',\n },\n bases=(models.Model,),\n ),\n migrations.CreateModel(\n name='Email',\n fields=[\n ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),\n ('email', models.CharField(max_length=250, null=True, verbose_name=b'Email_name', blank=True)),\n ],\n options={\n },\n bases=(models.Model,),\n ),\n migrations.CreateModel(\n name='Item',\n fields=[\n ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),\n ('name', models.CharField(max_length=250, verbose_name=b'\\xd0\\x9d\\xd0\\xb0\\xd0\\xb7\\xd0\\xb2\\xd0\\xb0\\xd0\\xbd\\xd0\\xb8\\xd0\\xb5 \\xd1\\x84\\xd0\\xbe\\xd1\\x82\\xd0\\xbe\\xd0\\xb3\\xd1\\x80\\xd0\\xb0\\xd1\\x84\\xd0\\xb8\\xd0\\xb9', blank=True)),\n ('urlback', models.URLField(max_length=1000, verbose_name=b'\\xd0\\xa1\\xd1\\x81\\xd1\\x8b\\xd0\\xbb\\xd0\\xba\\xd0\\xb0 \\xd0\\xbd\\xd0\\xb0 \\xd0\\xba\\xd0\\xbe\\xd0\\xbd\\xd1\\x82\\xd0\\xb5\\xd0\\xbd\\xd1\\x82')),\n ('url', models.URLField(max_length=1000, verbose_name=b'\\xd0\\xa1\\xd1\\x81\\xd1\\x8b\\xd0\\xbb\\xd0\\xba\\xd0\\xb0')),\n ('public', models.IntegerField(default=0, verbose_name=b'\\xd0\\xa1\\xd1\\x82\\xd0\\xb0\\xd1\\x82\\xd1\\x83\\xd1\\x81 \\xd0\\xbf\\xd1\\x83\\xd0\\xb1\\xd0\\xbb\\xd0\\xb8\\xd0\\xba\\xd0\\xb0\\xd1\\x86\\xd0\\xb8\\xd0\\xb8')),\n ('date', models.DateTimeField(auto_now_add=True)),\n ('user', models.ForeignKey(to=settings.AUTH_USER_MODEL)),\n ],\n options={\n 'verbose_name': 'Items',\n 'verbose_name_plural': 'Item',\n },\n bases=(models.Model,),\n ),\n migrations.CreateModel(\n name='Photo',\n fields=[\n ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),\n ('image', models.ImageField(upload_to=b'image', verbose_name=b'\\xd0\\xa4\\xd0\\xbe\\xd1\\x82\\xd0\\xbe\\xd0\\xb3\\xd1\\x80\\xd0\\xb0\\xd1\\x84\\xd0\\xb8\\xd1\\x8f', blank=True)),\n ('status', models.IntegerField(default=1, verbose_name=b'\\xd0\\xa1\\xd1\\x82\\xd0\\xb0\\xd1\\x82\\xd1\\x83\\xd1\\x81 \\xd1\\x84\\xd0\\xbe\\xd1\\x82\\xd0\\xbe\\xd0\\xb3\\xd1\\x80\\xd0\\xb0\\xd1\\x84\\xd0\\xb8\\xd0\\xb8')),\n ('item', models.ForeignKey(related_name='items', to='item.Item')),\n ],\n options={\n 'verbose_name': '\\u0424\\u043e\\u0442\\u043e\\u0433\\u0440\\u0430\\u0444\\u0438\\u0438',\n 'verbose_name_plural': '\\u0424\\u043e\\u0442\\u043e\\u0433\\u0440\\u0430\\u0444\\u0438\\u044f',\n },\n bases=(models.Model,),\n ),\n migrations.CreateModel(\n name='RelatedPhotos',\n fields=[\n ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),\n ('photo_additional', models.ForeignKey(related_name='photo_additional', to='item.Photo')),\n ('photo_general', models.ForeignKey(related_name='photo_general', to='item.Photo')),\n ],\n options={\n },\n bases=(models.Model,),\n ),\n migrations.CreateModel(\n name='SavedTag',\n fields=[\n ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),\n ('date', models.DateTimeField(auto_now_add=True)),\n ],\n options={\n },\n bases=(models.Model,),\n ),\n migrations.CreateModel(\n name='Subs',\n fields=[\n ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),\n ('sub_to_user', models.ForeignKey(related_name='subs', to=settings.AUTH_USER_MODEL)),\n ('user', models.ForeignKey(related_name='user', to=settings.AUTH_USER_MODEL)),\n ],\n options={\n },\n bases=(models.Model,),\n ),\n migrations.CreateModel(\n name='Tag',\n fields=[\n ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),\n ('url', models.URLField(max_length=1000, verbose_name=b'\\xd0\\xa1\\xd1\\x81\\xd1\\x8b\\xd0\\xbb\\xd0\\xba\\xd0\\xb0', blank=True)),\n ('url_raw', models.URLField(default=b'', max_length=1000, verbose_name=b'\\xd0\\xa1\\xd1\\x81\\xd1\\x8b\\xd0\\xbb\\xd0\\xba\\xd0\\xb0 \\xd0\\xb1\\xd0\\xb5\\xd0\\xb7 \\xd0\\xba\\xd0\\xbe\\xd0\\xb4\\xd0\\xb0', blank=True)),\n ('x_position', models.CharField(max_length=250, verbose_name=b'\\xd0\\x9f\\xd0\\xbe\\xd0\\xb7\\xd0\\xb8\\xd1\\x86\\xd0\\xb8\\xd1\\x8f X')),\n ('y_position', models.CharField(max_length=250, verbose_name=b'\\xd0\\x9f\\xd0\\xbe\\xd0\\xb7\\xd0\\xb8\\xd1\\x86\\xd0\\xb8\\xd1\\x8f Y')),\n ('z_position', models.IntegerField(default=0, verbose_name=b'\\xd0\\x9f\\xd0\\xbe\\xd0\\xb7\\xd0\\xb8\\xd1\\x86\\xd0\\xb8\\xd1\\x8f Z')),\n ('brand_name', models.ForeignKey(related_name='tags', to='item.BrandName')),\n ('photo', models.ForeignKey(related_name='photos', to='item.Photo')),\n ],\n options={\n 'verbose_name': '\\u041c\\u0435\\u0442\\u043a\\u0438',\n 'verbose_name_plural': '\\u041c\\u0435\\u0442\\u043a\\u0430',\n },\n bases=(models.Model,),\n ),\n migrations.CreateModel(\n name='UserProfile',\n fields=[\n ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),\n ('sex', models.IntegerField(default=0, verbose_name=b'\\xd0\\x9f\\xd0\\xbe\\xd0\\xbb')),\n ('image', models.ImageField(upload_to=b'image', null=True, verbose_name=b'\\xd0\\xa4\\xd0\\xbe\\xd1\\x82\\xd0\\xbe \\xd0\\xbf\\xd0\\xbe\\xd0\\xbb\\xd1\\x8c\\xd0\\xb7\\xd0\\xbe\\xd0\\xb2\\xd0\\xb0\\xd1\\x82\\xd0\\xb5\\xd0\\xbb\\xd1\\x8f', blank=True)),\n ('phone', models.CharField(max_length=250, verbose_name=b'\\xd0\\x9d\\xd0\\xbe\\xd0\\xbc\\xd0\\xb5\\xd1\\x80 \\xd1\\x82\\xd0\\xb5\\xd0\\xbb\\xd0\\xb5\\xd1\\x84\\xd0\\xbe\\xd0\\xbd\\xd0\\xb0', blank=True)),\n ('link', models.URLField(max_length=1000, verbose_name=b'\\xd0\\xa1\\xd1\\x81\\xd1\\x8b\\xd0\\xbb\\xd0\\xba\\xd0\\xb0', blank=True)),\n ('description', models.CharField(max_length=150, verbose_name=b'\\xd0\\x9e\\xd0\\xbf\\xd0\\xb8\\xd1\\x81\\xd0\\xb0\\xd0\\xbd\\xd0\\xb8\\xd0\\xb5', blank=True)),\n ('pp', models.IntegerField(null=True, verbose_name=b'\\xd0\\xa6\\xd0\\xb5\\xd0\\xbd\\xd0\\xb0 product placement', blank=True)),\n ('email', models.CharField(max_length=250, verbose_name=b'Email \\xd0\\xb4\\xd0\\xbb\\xd1\\x8f \\xd0\\xbe\\xd1\\x82\\xd0\\xbf\\xd1\\x80\\xd0\\xb0\\xd0\\xb2\\xd0\\xba\\xd0\\xb8 \\xd0\\xb4\\xd0\\xb0\\xd0\\xbd\\xd0\\xbd\\xd1\\x8b\\xd1\\x85', blank=True)),\n ('link_shop', models.URLField(max_length=1000, verbose_name=b'\\xd0\\xa1\\xd1\\x81\\xd1\\x8b\\xd0\\xbb\\xd0\\xba\\xd0\\xb0 \\xd0\\xbd\\xd0\\xb0 \\xd0\\xbc\\xd0\\xb0\\xd0\\xb3\\xd0\\xb0\\xd0\\xb7\\xd0\\xb8\\xd0\\xbd', blank=True)),\n ('bank_account_owner', models.CharField(max_length=500, verbose_name=b'\\xd0\\x92\\xd0\\xbb\\xd0\\xb0\\xd0\\xb4\\xd0\\xb5\\xd0\\xbb\\xd0\\xb5\\xd1\\x86 \\xd0\\xb1\\xd0\\xb0\\xd0\\xbd\\xd0\\xba\\xd0\\xbe\\xd0\\xb2\\xd1\\x81\\xd0\\xba\\xd0\\xbe\\xd0\\xb3\\xd0\\xbe \\xd0\\xb0\\xd0\\xba\\xd0\\xba\\xd0\\xb0\\xd1\\x83\\xd0\\xbd\\xd1\\x82\\xd0\\xb0', blank=True)),\n ('bank_account_number', models.IntegerField(null=True, verbose_name=b'\\xd0\\x9d\\xd0\\xbe\\xd0\\xbc\\xd0\\xb5\\xd1\\x80 \\xd1\\x81\\xd1\\x87\\xd0\\xb5\\xd1\\x82\\xd0\\xb0', blank=True)),\n ('country', models.CharField(max_length=150, verbose_name=b'\\xd0\\xa1\\xd1\\x82\\xd1\\x80\\xd0\\xb0\\xd0\\xbd\\xd0\\xb0', blank=True)),\n ('bank_code', models.IntegerField(null=True, verbose_name=b'\\xd0\\x9a\\xd0\\xbe\\xd0\\xb4 \\xd0\\xb1\\xd0\\xb0\\xd0\\xbd\\xd0\\xba\\xd0\\xb0', blank=True)),\n ('bank_name', models.CharField(max_length=250, verbose_name=b'\\xd0\\x9d\\xd0\\xb0\\xd0\\xb7\\xd0\\xb2\\xd0\\xb0\\xd0\\xbd\\xd0\\xb8\\xd0\\xb5 \\xd0\\xb1\\xd0\\xb0\\xd0\\xbd\\xd0\\xba\\xd0\\xb0', blank=True)),\n ('wmr', models.IntegerField(null=True, verbose_name=b'Webmoney', blank=True)),\n ('yandex', models.IntegerField(null=True, verbose_name=b'\\xd0\\xaf\\xd0\\xbd\\xd0\\xb4\\xd0\\xb5\\xd0\\xba\\xd1\\x81 \\xd0\\x94\\xd0\\xb5\\xd0\\xbd\\xd1\\x8c\\xd0\\xb3\\xd0\\xb8', blank=True)),\n ('zip_code', models.CharField(max_length=250, verbose_name=b'\\xd0\\x9f\\xd0\\xbe\\xd1\\x87\\xd1\\x82\\xd0\\xbe\\xd0\\xb2\\xd1\\x8b\\xd0\\xb9 \\xd0\\xb8\\xd0\\xbd\\xd0\\xb4\\xd0\\xb5\\xd0\\xba\\xd1\\x81', blank=True)),\n ('city', models.CharField(max_length=250, verbose_name=b'\\xd0\\x93\\xd0\\xbe\\xd1\\x80\\xd0\\xbe\\xd0\\xb4', blank=True)),\n ('address', models.CharField(max_length=500, verbose_name=b'\\xd0\\x90\\xd0\\xb4\\xd1\\x80\\xd0\\xb5\\xd1\\x81', blank=True)),\n ('status_pay', models.IntegerField(default=0, verbose_name=b'\\xd0\\xa1\\xd0\\xbf\\xd0\\xbe\\xd1\\x81\\xd0\\xbe\\xd0\\xb1 \\xd0\\xbe\\xd0\\xbf\\xd0\\xbb\\xd0\\xb0\\xd1\\x82\\xd1\\x8b')),\n ('user', models.ForeignKey(related_name='profile', to=settings.AUTH_USER_MODEL, unique=True)),\n ],\n options={\n },\n bases=(models.Model,),\n ),\n migrations.AddField(\n model_name='savedtag',\n name='tag',\n field=models.ForeignKey(related_name='tag', to='item.Tag'),\n preserve_default=True,\n ),\n migrations.AddField(\n model_name='savedtag',\n name='user',\n field=models.ForeignKey(related_name='usertags', to=settings.AUTH_USER_MODEL),\n preserve_default=True,\n ),\n ]\n","repo_name":"makarowdmitry/tp","sub_path":"item/migrations/0001_initial.py","file_name":"0001_initial.py","file_ext":"py","file_size_in_byte":11286,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"}
+{"seq_id":"18380044011","text":"import hashlib\nimport json\nimport logging\nimport os\nimport socket\nimport ssl\nimport threading\nimport zlib\nfrom datetime import date\nfrom itertools import cycle\nfrom random import randint, sample, choice, getrandbits\nfrom stat import S_IFLNK, S_IFREG, S_IRWXU, S_IRWXG, S_IRWXO\nfrom string import ascii_letters, digits\nfrom struct import pack\nfrom sys import getsizeof\nfrom time import mktime, localtime, sleep, time\n\nimport wazuh_testing.data.syscollector as syscollector\nimport wazuh_testing.data.winevt as winevt\nimport wazuh_testing.wazuh_db as wdb\nfrom wazuh_testing import TCP\nfrom wazuh_testing import is_udp, is_tcp\nfrom wazuh_testing.tools.monitoring import wazuh_unpack, Queue\nfrom wazuh_testing.tools.remoted_sim import Cipher\nfrom wazuh_testing.tools.utils import retry, get_random_ip, get_random_string\n\n_data_path = os.path.join(os.path.dirname(os.path.realpath(__file__)), '..', 'data')\n\nos_list = [\"debian7\", \"debian8\", \"debian9\", \"debian10\", \"ubuntu12.04\",\n \"ubuntu14.04\", \"ubuntu16.04\", \"ubuntu18.04\", \"mojave\", \"solaris11\"]\nagent_count = 1\n\n\nclass Agent:\n \"\"\"Class that allows us to simulate an agent registered in a manager.\n This simulated agent allows sending-receiving messages and commands. In order to simulate\n syscollector, FIM, FIM Integrity, rootcheck, hostinfo, winevt and logcollector modules the following classes have\n been created: GeneratorSyscollector, GeneratorFIM, GeneratorIntegrityFIM, Rootcheck,\n GeneratorHostinfo, GeneratorWinevt, Logcollector.\n Args:\n manager_address (str): Manager IP address.\n cypher (str, optional): Cypher method. It can be [aes, blowfish]. Default aes.\n os (str, optional): Agent operating system. Default None for choosing randomly.\n rootcheck_sample (str, optional): File where are sample rootcheck messages.\n id (str, optional): ID of the agent. Specify only if it already exists.\n name (str, optional): Agent name. Specify only if it already exists.\n key (str, optional): Client key. Specify only if it already exists.\n version (str, optional): Wazuh agent version. Default v3.12.0.\n labels (dict, optional): Wazuh agent labels. Each dict key will be a new label.\n fim_eps (int, optional): Set the maximum event reporting throughput. Events are messages that will produce an\n alert.\n fim_integrity_eps (int, optional): Set the maximum database synchronization message throughput.\n authd_password (str), optional: Password for registration if needed.\n registration_address (str, optional): Manager registration IP address.\n retry_enrollment (bool, optional): retry then enrollment in case of error.\n logcollector_msg_number (bool, optional): insert in the logcollector message the message number.\n custom_logcollector_message (str): Custom logcollector message to be sent by the agent.\n Attributes:\n id (str): ID of the agent.\n name (str): Agent name.\n key (str): Agent key. Used for creating an encryption_key.\n long_version (str): Agent version in format x.y.z\n short_version (str): Agent version in format x.y\n cypher (str): Encryption method for message communication.\n os (str): Agent operating system.\n fim_eps (int): Fim's maximum event reporting throughput. Default `1000`.\n fim_integrity_eps (int): Fim integrity's maximum event reporting throughput. Default `100`.\n syscollector_eps (int): Syscollector's maximum event reporting throughput. Default `100`.\n rootcheck_eps (int): Rootcheck's maximum event reporting throughput. Default `100`.\n hostinfo_eps (int): Hostinfo's maximum event reporting throughput. Default `100`.\n winevt_eps (float): Winevt's maximum event reporting throughput. Default `100`.\n logcollector_eps (float): Logcollector's maximum event reporting throughput. Default `100`.\n sca_eps (float): sca_label's maximum event reporting throughput. Default `100`.\n manager_address (str): Manager IP address.\n encryption_key (bytes): Encryption key used for encrypt and decrypt the message.\n keep_alive_event (bytes): Keep alive event (read from template data according to OS and parsed to an event).\n keep_alive_raw_msg (string): Keep alive event in plain text.\n merged_checksum (string): Checksum of agent's merge.mg file.\n startup_msg (bytes): Startup event sent before the first keep alive event.\n authd_password (str): Password for manager registration.\n rootcheck_sample (str): File where are sample rootcheck messages.\n rootcheck (Rootcheck): Object to simulate rootcheck message events.\n fim (GeneratorFIM): Object to simulate FIM message events.\n fim_integrity (GeneratorIntegrityFIM): Object to simulate FIM integrity message events.\n modules (dict): Agent modules with their associated configuration info.\n sha_key (str): Shared key between manager and agent for remote upgrading.\n upgrade_exec_result (int): Upgrade result status code.\n send_upgrade_notification (boolean): If True, it will be sent the upgrade status message after \"upgrading\".\n upgrade_script_result (int): Variable to mock the upgrade script result. Used for simulating a remote upgrade.\n stop_receive (int): Flag to determine when to activate and deactivate the agent event listener.\n stage_disconnect (str): WPK process state variable.\n rcv_msg_limit (int): max elements for the received message queue.\n rcv_msg_queue (monitoring.Queue): Queue to store received messages in the agent.\n disable_all_modules (boolean): Disable all simulated modules for this agent.\n rootcheck_frequency (int): frequency to run rootcheck scans. 0 to continuously send rootcheck events.\n syscollector_frequency (int): frequency to run syscollector scans. 0 to continuously send syscollector events.\n keepalive_frequency (int): frequency to send keepalive messages. 0 to continuously send keepalive messages.\n sca_frequency (int): frequency to run sca_label scans. 0 to continuously send sca_label events.\n syscollector_batch_size (int): Size of the syscollector type batch events.\n fixed_message_size (int): Fixed size of the agent modules messages in KB.\n registration_address (str): Manager registration IP address.\n \"\"\"\n def __init__(self, manager_address, cypher=\"aes\", os=None, rootcheck_sample=None, id=None, name=None, key=None,\n version=\"v4.3.0\", fim_eps=100, fim_integrity_eps=100, sca_eps=100, syscollector_eps=100, labels=None,\n rootcheck_eps=100, logcollector_eps=100, authd_password=None, disable_all_modules=False,\n rootcheck_frequency=60.0, rcv_msg_limit=0, keepalive_frequency=10.0, sca_frequency=60,\n syscollector_frequency=60.0, syscollector_batch_size=10, hostinfo_eps=100, winevt_eps=100,\n fixed_message_size=None, registration_address=None, retry_enrollment=False,\n logcollector_msg_number=None, custom_logcollector_message=''):\n self.id = id\n self.name = name\n self.key = key\n if version is None:\n version = \"v3.13.2\"\n self.long_version = version\n ver_split = version.replace(\"v\", \"\").split(\".\")\n self.short_version = f\"{'.'.join(ver_split[:2])}\"\n self.labels = labels\n self.cypher = cypher\n self.os = os\n self.fim_eps = fim_eps\n self.fim_integrity_eps = fim_integrity_eps\n self.syscollector_eps = syscollector_eps\n self.rootcheck_eps = rootcheck_eps\n self.logcollector_eps = logcollector_eps\n self.winevt_eps = winevt_eps\n self.sca_eps = sca_eps\n self.hostinfo_eps = hostinfo_eps\n self.rootcheck_frequency = rootcheck_frequency\n self.sca_frequency = sca_frequency\n self.keepalive_frequency = keepalive_frequency\n self.syscollector_frequency = syscollector_frequency\n self.manager_address = manager_address\n self.registration_address = manager_address if registration_address is None else registration_address\n self.encryption_key = \"\"\n self.keep_alive_event = \"\"\n self.keep_alive_raw_msg = \"\"\n self.merged_checksum = 'd6e3ac3e75ca0319af3e7c262776f331'\n self.startup_msg = \"\"\n self.authd_password = authd_password\n self.sca = None\n self.logcollector = None\n self.syscollector_batch_size = syscollector_batch_size\n self.rootcheck_sample = rootcheck_sample\n self.rootcheck = None\n self.hostinfo = None\n self.winevt = None\n self.fim = None\n self.fim_integrity = None\n self.syscollector = None\n self.modules = {\n 'keepalive': {'status': 'enabled', 'frequency': self.keepalive_frequency},\n 'fim': {'status': 'enabled', 'eps': self.fim_eps},\n 'fim_integrity': {'status': 'disabled', 'eps': self.fim_integrity_eps},\n 'syscollector': {'status': 'disabled', 'frequency': self.syscollector_frequency,\n 'eps': self.syscollector_eps},\n 'rootcheck': {'status': 'disabled', 'frequency': self.rootcheck_frequency, 'eps': self.rootcheck_eps},\n 'sca': {'status': 'disabled', 'frequency': self.sca_frequency, 'eps': self.sca_eps},\n 'hostinfo': {'status': 'disabled', 'eps': self.hostinfo_eps},\n 'winevt': {'status': 'disabled', 'eps': self.winevt_eps},\n 'logcollector': {'status': 'disabled', 'eps': self.logcollector_eps},\n 'receive_messages': {'status': 'enabled'},\n }\n self.sha_key = None\n self.upgrade_exec_result = None\n self.send_upgrade_notification = False\n self.upgrade_script_result = 0\n self.stop_receive = 0\n self.stage_disconnect = None\n self.retry_enrollment = retry_enrollment\n self.rcv_msg_queue = Queue(rcv_msg_limit)\n self.fixed_message_size = fixed_message_size * 1024 if fixed_message_size is not None else None\n self.logcollector_msg_number = logcollector_msg_number\n self.custom_logcollector_message = custom_logcollector_message\n self.setup(disable_all_modules=disable_all_modules)\n\n def update_checksum(self, new_checksum):\n self.keep_alive_raw_msg = self.keep_alive_raw_msg.replace(self.merged_checksum, new_checksum)\n self.keep_alive_event = self.create_event(self.keep_alive_raw_msg)\n self.merged_checksum = new_checksum\n\n def setup(self, disable_all_modules):\n \"\"\"Set up agent: os, registration, encryption key, start up msg and activate modules.\"\"\"\n self.set_os()\n\n if self.id is None and self.name is None and self.key is None:\n self.set_name()\n self.register()\n elif any([self.id, self.name, self.key]) and not all([self.id, self.name, self.key]):\n raise ValueError(\"All the parameters [id, name, key] have to be specified together\")\n\n self.create_encryption_key()\n self.create_keep_alive()\n self.create_hc_startup()\n self.initialize_modules(disable_all_modules)\n\n def set_os(self):\n \"\"\"Pick random OS from a custom os list.\"\"\"\n if self.os is None:\n self.os = os_list[agent_count % len(os_list) - 1]\n\n def set_wpk_variables(self, sha=None, upgrade_exec_result=None, upgrade_notification=False, upgrade_script_result=0,\n stage_disconnect=None):\n \"\"\"Set variables related to wpk simulated responses.\n Args:\n sha (str): Shared key between manager and agent for remote upgrading.\n upgrade_exec_result (int): Upgrade result status code.\n upgrade_notification (boolean): If True, it will be sent the upgrade status message after \"upgrading\".\n upgrade_script_result (int): Variable to mock the upgrade script result. Used for simulating a remote\n upgrade.\n stage_disconnect (str): WPK process state variable.\n \"\"\"\n self.sha_key = sha\n self.upgrade_exec_result = upgrade_exec_result\n self.send_upgrade_notification = upgrade_notification\n self.upgrade_script_result = upgrade_script_result\n self.stage_disconnect = stage_disconnect\n\n def set_name(self):\n \"\"\"Set a random agent name.\"\"\"\n random_string = ''.join(sample(f\"0123456789{ascii_letters}\", 16))\n self.name = f\"{agent_count}-{random_string}-{self.os}\"\n\n def _register_helper(self):\n \"\"\"Helper function to enroll an agent.\"\"\"\n sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n context = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT)\n context.check_hostname = False\n context.verify_mode = ssl.CERT_NONE\n try:\n ssl_socket = context.wrap_socket(sock, server_hostname=self.registration_address)\n ssl_socket.connect((self.registration_address, 1515))\n\n if self.authd_password is None:\n event = f\"OSSEC A:'{self.name}'\\n\".encode()\n else:\n event = f\"OSSEC PASS: {self.authd_password} OSSEC A:'{self.name}'\\n\".encode()\n\n ssl_socket.send(event)\n recv = ssl_socket.recv(4096)\n registration_info = recv.decode().split(\"'\")[1].split(\" \")\n\n self.id = registration_info[0]\n self.key = registration_info[3]\n finally:\n ssl_socket.close()\n sock.close()\n\n logging.debug(f\"Registration - {self.name}({self.id}) in {self.registration_address}\")\n\n def register(self):\n \"\"\"Request to register the agent in the manager.\n In addition, it sets the agent id and agent key with the response data.\n \"\"\"\n if self.retry_enrollment:\n retries = 20\n while retries >= 0:\n try:\n self._register_helper()\n except Exception:\n retries -= 1\n sleep(6)\n else:\n break\n else:\n raise ValueError(f\"The agent {self.name} was not correctly enrolled.\")\n else:\n self._register_helper()\n\n @staticmethod\n def wazuh_padding(compressed_event):\n \"\"\"Add the Wazuh custom padding to each event sent.\n Args:\n compressed_event (bytes): Compressed event with zlib.\n Returns:\n bytes: Padded event.\n Examples:\n >>> wazuh_padding(b'x\\\\x9c\\\\x15\\\\xc7\\\\xc9\\\\r\\\\x00 \\\\x08\\\\x04\\\\xc0\\\\x96\\\\\\\\\\\\x94\\\\xcbn0H\\\\x03\\\\xda\\\\x7f\n \\\\x8c\\\\xf3\\\\x1b\\\\xd9e\\\\xec\\\\nJ[\\\\x04N\\\\xcf\\\\xa8\\\\xa6\\\\xa8\\\\x12\\\\x8d\\\\x08!\\\\xfe@}\\\\xb0\n \\\\xa89\\\\xe6\\\\xef\\\\xbc\\\\xfb\\\\xdc\\\\x07\\\\xb7E\\\\x0f\\\\x1b)\n b'!!!!!!!!x\\\\x9c\\\\x15\\\\xc7\\\\xc9\\\\r\\\\x00 \\\\x08\\\\x04\\\\xc0\\\\x96\\\\\\\\\\\\x94\\\\xcbn0H\\\\x03\\\\xda\\\\x7f\\\\x8c\\\\xf3\n \\\\x1b\\\\xd9e\\\\xec\\\\nJ[\\\\x04N\\\\xcf\\\\xa8\\\\xa6\\\\xa8\\\\x12\\\\x8d\\\\x08!\\\\xfe@}\\\\xb0\\\\xa89\\\\xe6\\\\xef\\\\xbc\\\\xfb\n \\\\xdc\\\\x07\\\\xb7E\\\\x0f\\\\x1b'\n \"\"\"\n padding = 8\n extra = len(compressed_event) % padding\n if extra > 0:\n padded_event = (b'!' * (padding - extra)) + compressed_event\n else:\n padded_event = (b'!' * padding) + compressed_event\n return padded_event\n\n def create_encryption_key(self):\n \"\"\"Generate encryption key (using agent metadata and key).\"\"\"\n agent_id = self.id.encode()\n name = self.name.encode()\n key = self.key.encode()\n sum1 = (hashlib.md5((hashlib.md5(name).hexdigest().encode()\n + hashlib.md5(agent_id).hexdigest().encode())).hexdigest().encode())\n sum1 = sum1[:15]\n sum2 = hashlib.md5(key).hexdigest().encode()\n key = sum2 + sum1\n self.encryption_key = key\n\n @staticmethod\n def compose_event(message):\n \"\"\"Compose event from raw message.\n Returns:\n bytes: Composed event.\n Examples:\n >>> compose_event('test')\n b'6ef859712d8b215d9daf071ff67aaa62555551234567891:5555:test'\n \"\"\"\n message = message.encode()\n random_number = b'55555'\n global_counter = b'1234567891'\n split = b':'\n local_counter = b'5555'\n msg = random_number + global_counter + split + local_counter + split + message\n msg_md5 = hashlib.md5(msg).hexdigest()\n event = msg_md5.encode() + msg\n return event\n\n def encrypt(self, padded_event):\n \"\"\"Encrypt event using AES or Blowfish encryption.\n Args:\n padded_event (bytes): Padded event.\n Returns:\n bytes: Encrypted event.\n Examples:\n >>> agent.encrypt(b'!!!!!!!!x\\\\x9c\\\\x15\\\\xc7\\\\xc9\\\\r\\\\x00 \\\\x08\\\\x04\\\\xc0\\\\x96\\\\\\\\\\\\x94\\\\xcbn0H\\\\x03\\\\xda\n \\\\x7f\\\\x8c\\\\xf3\\\\x1b\\\\xd9e\\\\xec\\\\nJ[\\\\x04N\\\\xcf\\\\xa8\\\\xa6\\\\xa8\\\\x12\\\\x8d\\\\x08!\\\\xfe@}\n \\\\xb0\\\\xa89\\\\xe6\\\\xef\\\\xbc\\\\xfb\\\\xdc\\\\x07\\\\xb7E\\\\x0f\\\\x1b')\n b\"\\\\xf8\\\\x8af[\\\\xfc'\\\\xf6j&1\\\\xd5\\\\xe1t|\\\\x810\\\\xe70G\\\\xe3\\\\xbc\\\\x8a\\\\xdbV\\\\x94y\\\\xa3A\\\\xb5q\\\\xf7\n \\\\xb52<\\\\x9d\\\\xc8\\\\x83=o1U\\\\x1a\\\\xb3\\\\xf1\\\\xf5\\\\xde\\\\xe0\\\\x8bV\\\\xe99\\\\x9ej}#\\\\xf1\\\\x99V\\\\x12NP^T\n \\\\xa0\\\\rYs\\\\xa2n\\\\xe8\\\\xa5\\\\xb1\\\\r[>> create_event('test message')\n b'!005!#AES:\\\\xab\\\\xfa\\\\xcc2;\\\\x87\\\\xab\\\\x7fUH\\\\x03>_J\\\\xda=I\\\\x96\\\\xb5\\\\xa4\\\\x89\\\\xbe\\\\xbf`\\\\xd0\\\\xad\n \\\\x03\\\\x06\\\\x1aN\\\\x86 \\\\xc2\\\\x98\\\\x93U\\\\xcc\\\\xf5\\\\xe3@%\\\\xabS!\\\\xd3\\\\x9d!\\\\xea\\\\xabR\\\\xf9\\\\xd3\\\\x0b\\\\\n xcc\\\\xe8Y\\\\xe31*c\\\\x17g\\\\xa6M\\\\x0b&\\\\xc0>\\\\xc64\\\\x815\\\\xae\\\\xb8[bg\\\\xe3\\\\x83\\\\x0e'\n \"\"\"\n # Compose event\n event = self.compose_event(message)\n # Compress\n compressed_event = zlib.compress(event)\n # Padding\n padded_event = self.wazuh_padding(compressed_event)\n # Encrypt\n encrypted_event = self.encrypt(padded_event)\n # Add headers\n headers_event = self.headers(self.id, encrypted_event)\n\n return headers_event\n\n def receive_message(self, sender):\n \"\"\"Agent listener to receive messages and process the accepted commands.\n Args:\n sender (Sender): Object to establish connection with the manager socket and receive/send information.\n \"\"\"\n while self.stop_receive == 0:\n if is_tcp(sender.protocol):\n try:\n rcv = sender.socket.recv(4)\n if len(rcv) == 4:\n data_len = wazuh_unpack(rcv)\n buffer_array = sender.socket.recv(data_len)\n if data_len != len(buffer_array):\n continue\n else:\n continue\n except MemoryError:\n logging.critical(f\"Memory error, trying to allocate {data_len}.\")\n return\n except Exception:\n return\n else:\n buffer_array, client_address = sender.socket.recvfrom(65536)\n index = buffer_array.find(b'!')\n if index == 0:\n index = buffer_array[1:].find(b'!')\n buffer_array = buffer_array[index + 2:]\n if self.cypher == \"aes\":\n msg_remove_header = bytes(buffer_array[5:])\n msg_decrypted = Cipher(msg_remove_header, self.encryption_key).decrypt_aes()\n else:\n msg_remove_header = bytes(buffer_array[1:])\n msg_decrypted = Cipher(msg_remove_header, self.encryption_key).decrypt_blowfish()\n try:\n padding = 0\n while msg_decrypted:\n if msg_decrypted[padding] == 33:\n padding += 1\n else:\n break\n msg_remove_padding = msg_decrypted[padding:]\n msg_decompress = zlib.decompress(msg_remove_padding)\n msg_decoded = msg_decompress.decode('ISO-8859-1')\n self.process_message(sender, msg_decoded)\n except zlib.error:\n logging.error(\"Corrupted message from the manager. Continuing.\")\n\n def stop_receiver(self):\n \"\"\"Stop Agent listener.\"\"\"\n self.stop_receive = 1\n\n def process_message(self, sender, message):\n \"\"\"Process agent received messages.\n If the message contains reserved words, then it will be proceed as command.\n Args:\n sender (Sender): Object to establish connection with the manager socket and receive/send information.\n message (str): Decoder message in ISO-8859-1 format.\n \"\"\"\n msg_decoded_list = message.split(' ')\n self.rcv_msg_queue.put(message)\n if '#!-req' in msg_decoded_list[0]:\n self.process_command(sender, msg_decoded_list)\n elif '#!-up' in msg_decoded_list[0]:\n kind, checksum, name = msg_decoded_list[1:4]\n if kind == 'file' and \"merged.mg\" in name:\n self.update_checksum(checksum)\n elif '#!-force_reconnect' in msg_decoded_list[0]:\n sender.reconnect(self.startup_msg)\n\n def process_command(self, sender, message_list):\n \"\"\"Process agent received commands through the socket.\n Args:\n sender (Sender): Object to establish connection with the manager socket and receive/send information.\n message_list (list): Message split by white spaces.\n Raises:\n ValueError: if 'sha1' command and sha_key Agent value is not defined.\n ValueError: if execution result is not configured in the Agent.\n ValueError: if command is not recognized.\n \"\"\"\n\n req_code = message_list[1]\n\n if 'com' in message_list:\n \"\"\"Examples:\n ['12d95abf04334f90f8dc3140031b3e7b342680000000130:5489:#!-req', '81d15486', 'com', 'close',\n 'wazuh_agent_v4.2.0_linux_x86_64.wpk']\n ['dff5324c331a37d56978f7f034f2634e599120000000130:5490:#!-req', '81d15487', 'com', 'sha1',\n 'wazuh_agent_v4.2.0_linux_x86_64.wpk']\n ['8c0e7a8d75fea76016040ce436f9fb41193290000000130:5491:#!-req', '81d15488', 'com', 'upgrade',\n 'wazuh_agent_v4.2.0_linux_x86_64.wpk', 'upgrade.sh']\n \"\"\"\n com_index = message_list.index('com')\n command = message_list[com_index + 1]\n\n elif 'upgrade' in message_list:\n \"\"\"Examples:\n ['5e085e566814750136f3926f758349cb232030000000130:5492:#!-req', '81d15489', 'upgrade',\n '{\"command\":\"clear_upgrade_result\",\"parameters\":{}}']\n \"\"\"\n com_index = message_list.index('upgrade')\n json_command = json.loads(message_list[com_index + 1])\n command = json_command['command']\n elif 'getconfig' in message_list:\n \"\"\"Examples:\n ['ececac937b8e5dead15e9096e8bd5215214970000000002:3090:#!-req', 'c2b2c9e3', 'agent', 'getconfig', 'client']\n \"\"\"\n command = 'getconfig'\n elif 'getstate' in message_list:\n \"\"\"Examples:\n ['ececac937b8e5dead15e9096e8bd5215214970000000002:3090:#!-req', 'c2b2c9e3', 'logcollector', 'getstate']\n \"\"\"\n command = 'getstate'\n else:\n return\n\n logging.debug(f\"Processing command: {message_list}\")\n\n if command in ['lock_restart', 'open', 'write', 'close', 'clear_upgrade_result']:\n if command == 'lock_restart' and self.stage_disconnect == 'lock_restart':\n self.stop_receive = 1\n elif command == 'open' and self.stage_disconnect == 'open':\n self.stop_receive = 1\n elif command == 'write' and self.stage_disconnect == 'write':\n self.stop_receive = 1\n elif command == 'close' and self.stage_disconnect == 'close':\n self.stop_receive = 1\n elif command == 'clear_upgrade_result' and self.stage_disconnect == 'clear_upgrade_result':\n self.stop_receive = 1\n else:\n if self.short_version < \"4.1\" or command == 'lock_restart':\n sender.send_event(self.create_event(f'#!-req {req_code} ok '))\n else:\n sender.send_event(self.create_event(f'#!-req {req_code} '\n f'{{\"error\":0, \"message\":\"ok\", \"data\":[]}} '))\n elif command == 'getconfig':\n response_json = '{\"client\":{\"config-profile\":\"centos8\",\"notify_time\":10,\"time-reconnect\":60}}'\n sender.send_event(self.create_event(f'#!-req {req_code} ok {response_json}'))\n elif command == 'getstate':\n response_json = '{\"error\":0,\"data\":{\"global\":{\"start\":\"2021-02-26, 06:41:26\",\"end\":\"2021-02-26 08:49:19\"}}}'\n sender.send_event(self.create_event(f'#!-req {req_code} ok {response_json}'))\n elif command == 'sha1':\n # !-req num ok {sha}\n if self.sha_key:\n if command == 'sha1' and self.stage_disconnect == 'sha1':\n self.stop_receive = 1\n else:\n if self.short_version < \"4.1\":\n sender.send_event(self.create_event(f'#!-req {req_code} '\n f'ok {self.sha_key}'))\n else:\n sender.send_event(self.create_event(f'#!-req {req_code} {{\"error\":0, '\n f'\"message\":\"{self.sha_key}\", \"data\":[]}}'))\n else:\n raise ValueError('WPK SHA key should be configured in agent')\n\n elif command == 'upgrade':\n if self.upgrade_exec_result:\n if command == 'upgrade' and self.stage_disconnect == 'upgrade':\n self.stop_receive = 1\n else:\n if self.short_version < \"4.1\":\n sender.send_event(self.create_event(f'#!-req {req_code} ok {self.upgrade_exec_result}'))\n else:\n sender.send_event(self.create_event(f'#!-req {req_code} {{\"error\":0, '\n f'\"message\":\"{self.upgrade_exec_result}\", \"data\":[]}}'))\n if self.send_upgrade_notification:\n message = 'Upgrade was successful' if self.upgrade_script_result == 0 else 'Upgrade failed'\n status = 'Done' if self.upgrade_script_result == 0 else 'Failed'\n upgrade_update_status_message = {\n 'command': 'upgrade_update_status',\n 'parameters': {\n 'error': self.upgrade_script_result,\n 'message': message,\n 'status': status,\n }\n }\n sender.send_event(self.create_event(\"u:upgrade_module:\" +\n json.dumps(upgrade_update_status_message)))\n else:\n raise ValueError(f'Execution result should be configured in agent')\n else:\n raise ValueError(f'Unrecognized command {command}')\n\n def create_hc_startup(self):\n \"\"\"Set the agent startup event.\"\"\"\n msg = \"#!-agent startup \"\n self.startup_msg = self.create_event(msg)\n\n def create_keep_alive(self):\n \"\"\"Set the keep alive event from keepalives operating systemd data.\"\"\"\n with open(os.path.join(_data_path, 'keepalives.txt'), 'r') as fp:\n line = fp.readline()\n while line:\n if line.strip(\"\\n\") == self.os:\n msg = fp.readline()\n line = fp.readline()\n while line and line.strip(\"\\n\") not in os_list:\n msg = msg + line\n line = fp.readline()\n break\n line = fp.readline()\n try:\n msg = msg.replace(\"\", self.long_version)\n msg = msg.replace(\"\", self.merged_checksum)\n except UnboundLocalError:\n logging.critical(\"Error creating keep alive for the agent. Check if the OS is in the keepalives.txt\")\n\n if self.labels:\n msg_as_list = msg.split('\\n')\n for key, value in self.labels.items():\n msg_as_list.insert(1, f'\"{key}\":{value}')\n msg = '\\n'.join(msg_as_list)\n\n logging.debug(f\"Keep alive message = {msg}\")\n\n self.keep_alive_event = self.create_event(msg)\n self.keep_alive_raw_msg = msg\n\n def initialize_modules(self, disable_all_modules):\n \"\"\"Initialize and enable agent modules.\n Args:\n disable_all_modules (boolean): True to disable all modules, False to leave the default ones enabled.\n \"\"\"\n for module in ['syscollector', 'rootcheck', 'fim', 'fim_integrity', 'receive_messages', 'keepalive']:\n if disable_all_modules:\n self.modules[module]['status'] = 'disabled'\n\n if self.modules['syscollector']['status'] == 'enabled':\n self.init_syscollector()\n if self.modules['rootcheck']['status'] == 'enabled':\n self.init_rootcheck()\n if self.modules['fim']['status'] == 'enabled':\n self.init_fim()\n if self.modules['fim_integrity']['status'] == 'enabled':\n self.init_fim_integrity()\n if self.modules['hostinfo']['status'] == 'enabled':\n self.init_hostinfo()\n if self.modules['winevt']['status'] == 'enabled':\n self.init_winevt()\n if self.modules['sca']['status'] == 'enabled':\n self.init_sca()\n if self.modules['logcollector']['status'] == 'enabled':\n self.init_logcollector()\n\n def init_logcollector(self):\n \"\"\"Initialize logcollector module.\"\"\"\n if self.logcollector is None:\n self.logcollector = Logcollector(enable_msg_number=self.logcollector_msg_number,\n custom_logcollector_message=self.custom_logcollector_message)\n\n def init_sca(self):\n \"\"\"Initialize init_sca module.\"\"\"\n if self.sca is None:\n self.sca = SCA(self.os)\n\n def init_syscollector(self):\n \"\"\"Initialize syscollector module.\"\"\"\n if self.syscollector is None:\n self.syscollector = GeneratorSyscollector(self.name, self.syscollector_batch_size)\n\n def init_rootcheck(self):\n \"\"\"Initialize rootcheck module.\"\"\"\n if self.rootcheck is None:\n self.rootcheck = Rootcheck(os=self.os, agent_name=self.name, agent_id=self.id,\n rootcheck_sample=self.rootcheck_sample)\n\n def init_fim(self):\n \"\"\"Initialize fim module.\"\"\"\n if self.fim is None:\n self.fim = GeneratorFIM(self.id, self.name, self.short_version)\n\n def init_fim_integrity(self):\n \"\"\"Initialize fom integrity module.\"\"\"\n if self.fim_integrity is None:\n self.fim_integrity = GeneratorIntegrityFIM(self.id, self.name, self.short_version)\n\n def init_hostinfo(self):\n \"\"\"Initialize hostinfo module.\"\"\"\n if self.hostinfo is None:\n self.hostinfo = GeneratorHostinfo()\n\n def init_winevt(self):\n \"\"\"Initialize winevt module.\"\"\"\n if self.winevt is None:\n self.winevt = GeneratorWinevt(self.name, self.id)\n\n def get_agent_info(self, field):\n agent_info = wdb.query_wdb(f\"global get-agent-info {self.id}\")\n\n if len(agent_info) > 0:\n field_value = agent_info[0][field]\n else:\n field_value = \"Not in global.db\"\n return field_value\n\n def get_agent_version(self):\n return self.get_agent_info('version')\n\n def get_connection_status(self):\n \"\"\"Get agent connection status of global.db.\n Returns:\n str: Agent connection status (connected, disconnected, never_connected)\n \"\"\"\n return self.get_agent_info('connection_status')\n\n @retry(AttributeError, attempts=10, delay=5, delay_multiplier=1)\n def wait_status_active(self):\n \"\"\"Wait until agent status is active in global.db.\n Raises:\n AttributeError: If the agent is not active. Combined with the retry decorator makes a wait loop\n until the agent is active.\n \"\"\"\n status = self.get_connection_status()\n\n if status == 'active':\n return\n raise AttributeError(f\"Agent is not active yet: {status}\")\n\n def set_module_status(self, module_name, status):\n \"\"\"Set module status.\n Args:\n module_name (str): Module name.\n status (str): Module status.\n \"\"\"\n self.modules[module_name]['status'] = status\n\n def set_module_attribute(self, module_name, attribute, value):\n \"\"\"Set module attribute.\n Args:\n module_name (str): Module name.\n attribute (str): Attribute name to change.\n value: Attribute value.\n \"\"\"\n self.modules[module_name][attribute] = value\n\n\nclass GeneratorSyscollector:\n \"\"\"This class allows the generation of syscollector events.\n Create events of different syscollector event types Network, Process, Port, Packages, OS, Hardware and Hotfix.\n In order to change messages events it randomized different fields of templates specified by .\n In order to simulate syscollector module, it send a set of the same syscollector type messages,\n which size is specified by `batch_size` attribute. Example of syscollector message:\n d:syscollector:{\"type\":\"network\",\"ID\":18,\"timestamp\":\"2021/03/26 00:00:00\",\"iface\":{\"name\":\"O977Q1F55O\",\n \"type\":\"ethernet\",\"state\":\"up\",\"MAC\":\"08:00:27:be:ce:3a\",\"tx_packets\":2135,\"rx_packets\":9091,\"tx_bytes\":210748,\n \"rx_bytes\":10134272,\"tx_errors\":0,\"rx_errors\":0,\"tx_dropped\":0,\"rx_dropped\":0,\"MTU\":1500,\"IPv4\":\n {\"address\":[\"10.0.2.15\"],\"netmask\":[\"255.255.255.0\"],\"broadcast\":[\"10.0.2.255\"],\n \"metric\":100,\"gateway\":\"10.0.2.2\",\"DHCP\":\"enabled\"}}}\n Args:\n agent_name (str): Name of the agent.\n batch_size (int): Number of messages of the same type\n \"\"\"\n def __init__(self, agent_name, batch_size):\n self.current_batch_events = -1\n self.current_batch_events_size = 0\n self.list_events = ['network', 'port', 'hotfix',\n 'process', 'packages', 'OS', 'hardware']\n self.agent_name = agent_name\n self.batch_size = batch_size\n self.syscollector_tag = 'syscollector'\n self.syscollector_mq = 'd'\n self.current_id = 1\n\n def format_event(self, message_type):\n \"\"\"Format syscollector message of the specified type.\n Args:\n message_type (str): Syscollector event type.\n Returns:\n str: the generated syscollector event message.\n \"\"\"\n message = syscollector.SYSCOLLECTOR_HEADER\n if message_type == 'network':\n message += syscollector.SYSCOLLECTOR_NETWORK_EVENT_TEMPLATE\n elif message_type == 'process':\n message += syscollector.SYSCOLLECTOR_PROCESS_EVENT_TEMPLATE\n elif message_type == 'port':\n message += syscollector.SYSCOLLECTOR_PORT_EVENT_TEMPLATE\n elif message_type == 'packages':\n message += syscollector.SYSCOLLECTOR_PACKAGES_EVENT_TEMPLATE\n elif message_type == 'OS':\n message += syscollector.SYSCOLLECTOR_OS_EVENT_TEMPLATE\n elif message_type == 'hardware':\n message += syscollector.SYSCOLLECTOR_HARDWARE_EVENT_TEMPLATE\n elif message_type == 'hotfix':\n message += syscollector.SYSCOLLECTOR_HOTFIX_EVENT_TEMPLATE\n elif 'end' in message_type:\n message += '}'\n\n today = date.today()\n timestamp = today.strftime(\"%Y/%m/%d %H:%M:%S\")\n\n fields_to_replace = [\n ('', self.agent_name), ('', f\"{self.current_id}\"),\n ('', get_random_string(10)),\n ('', timestamp), ('', message_type)\n ]\n\n for variable, value in fields_to_replace:\n message = message.replace(variable, value)\n\n self.current_id += 1\n\n message = f\"{self.syscollector_mq}:{self.syscollector_tag}:{message}\"\n\n return message\n\n def generate_event(self):\n \"\"\"Generate syscollector event.\n The event types are selected sequentially, creating a number of events of the same type specified\n in `bath_size`.\n Returns:\n str: generated event with the desired format for syscollector\n \"\"\"\n if self.current_batch_events_size == 0:\n self.current_batch_events = (self.current_batch_events + 1) % len(self.list_events)\n self.current_batch_events_size = self.batch_size\n\n if self.list_events[self.current_batch_events] not in ['network', 'port', 'process'] \\\n or self.current_batch_events_size > 1:\n event = self.list_events[self.current_batch_events]\n else:\n event = self.list_events[self.current_batch_events] + '_end'\n\n self.current_batch_events_size = self.current_batch_events_size - 1\n return self.format_event(event)\n\n\nclass SCA:\n \"\"\"This class allows the generation of sca_label events.\n Create sca events, both summary and check.\n Args:\n os (str): Agent operative system.\n \"\"\"\n def __init__(self, os):\n self.last_scan_id = 0\n self.os = os\n self.count = 0\n self.sca_mq = 'p'\n self.sca_label = 'sca'\n self.started_time = int(time())\n\n def get_message(self):\n \"\"\"Alternatively creates summary and check SCA messages.\n Returns:\n str: an sca_label message formatted with the required header codes.\n \"\"\"\n if self.count % 100 == 0:\n msg = self.create_sca_event('summary')\n else:\n msg = self.create_sca_event('check')\n self.count += 1\n\n msg = msg.strip('\\n')\n\n sca_msg = f\"{self.sca_mq}:{self.sca_label}:{msg}\"\n\n return sca_msg\n\n def create_sca_event(self, event_type):\n \"\"\"Create sca_label event of the desired type.\n Args:\n event_type (str): Event type summary or check.\n Returns:\n dict: SCA event.\n \"\"\"\n event_data = dict()\n event_data['type'] = event_type\n event_data['scan_id'] = self.last_scan_id\n self.last_scan_id += 1\n\n def create_summary_sca_event(event_data):\n event_data['name'] = f\"CIS Benchmark for {self.os}\"\n event_data['policy_id'] = f\"cis_{self.os}_linux\"\n event_data['file'] = f\"cis_{self.os}_linux.yml\"\n event_data['description'] = 'This provides prescriptive guidance for establishing a secure configuration.'\n event_data['references'] = 'https://www.cisecurity.org/cis-benchmarks'\n total_checks = randint(0, 900)\n passed_checks = randint(0, total_checks)\n failed_checks = randint(0, total_checks - passed_checks)\n invalid_checks = total_checks - failed_checks - passed_checks\n event_data['passed'] = passed_checks\n event_data['failed'] = failed_checks\n event_data['invalid'] = invalid_checks\n event_data['total_checks'] = total_checks\n event_data['score'] = 20\n event_data['start_time'] = self.started_time\n self.started_time = int(time() + 1)\n event_data['end_time'] = self.started_time\n event_data['hash'] = getrandbits(256)\n event_data['hash_file'] = getrandbits(256)\n event_data['force_alert'] = '1'\n\n return event_data\n\n def create_check_sca_event(event_data):\n event_data['type'] = 'check'\n event_data['id'] = randint(0, 9999999999)\n event_data['policy'] = f\"CIS Benchmark for {self.os}\"\n event_data['policy_id'] = f\"cis_{self.os}_policy\"\n event_data['check'] = {}\n event_data['check']['id'] = randint(0, 99999)\n event_data['check']['title'] = 'Ensure root is the only UID 0 account'\n event_data['check']['description'] = 'Any account with UID 0 has superuser privileges on the system'\n event_data['check']['rationale'] = 'This access must be limited to only the default root account'\n event_data['check']['remediation'] = 'Remove any users other than root with UID 0'\n event_data['check']['compliance'] = {}\n event_data['check']['compliance']['cis'] = '6.2.6'\n event_data['check']['compliance']['cis_csc'] = '5.1'\n event_data['check']['compliance']['pci_dss'] = '10.2.5'\n event_data['check']['compliance']['hipaa'] = '164.312.b'\n event_data['check']['compliance']['nist_800_53'] = 'AU.14,AC.7'\n event_data['check']['compliance']['gpg_13'] = '7.8'\n event_data['check']['compliance']['gdpr_IV'] = '35.7,32.2'\n event_data['check']['compliance']['tsc'] = 'CC6.1,CC6.8,CC7.2,CC7.3,CC7.4'\n event_data['check']['rules'] = 'f:/etc/passwd -> !r:^# && !r:^\\\\\\\\s*\\\\\\\\t*root: && r:^\\\\\\\\w+:\\\\\\\\w+:0:\\\"]'\n event_data['check']['condition'] = 'none'\n event_data['check']['file'] = '/etc/passwd'\n event_data['check']['result'] = choice(['passed', 'failed'])\n\n return event_data\n\n if event_type == 'summary':\n event_data = create_summary_sca_event(event_data)\n elif event_type == 'check':\n event_data = create_check_sca_event(event_data)\n\n return json.dumps(event_data)\n\n\nclass Rootcheck:\n \"\"\"This class allows the generation of rootcheck events.\n Creates rootcheck events by sequentially repeating the events of a sample file file.\n Args:\n agent_name (str): Name of the agent.\n agent_id (str): Id of the agent.\n rootcheck_sample (str, optional): File with the rootcheck events that are going to be used.\n \"\"\"\n def __init__(self, os, agent_name, agent_id, rootcheck_sample=None):\n self.os = os\n self.agent_name = agent_name\n self.agent_id = agent_id\n self.rootcheck_tag = 'rootcheck'\n self.rootcheck_mq = '9'\n self.messages_list = []\n self.message = cycle(self.messages_list)\n self.rootcheck_path = \"\"\n self.rootcheck_sample = rootcheck_sample\n self.setup()\n\n def setup(self):\n \"\"\"Initialized the list of rootcheck messages, using `rootcheck_sample` and agent information.\"\"\"\n if self.rootcheck_sample is None:\n self.rootcheck_path = os.path.join(_data_path, 'rootcheck.txt')\n else:\n self.rootcheck_path = os.path.join(_data_path, self.rootcheck_sample)\n\n with open(self.rootcheck_path) as fp:\n line = fp.readline()\n while line:\n if not line.startswith(\"#\"):\n msg = \"{0}:{1}:{2}\".format(self.rootcheck_mq, self.rootcheck_tag, line.strip(\"\\n\"))\n self.messages_list.append(msg)\n line = fp.readline()\n\n def get_message(self):\n \"\"\"Returns a rootcheck message, informing when rootcheck scan starts and ends.\n Returns:\n str: a Rootcheck generated message\n \"\"\"\n message = next(self.message)\n if message == 'Starting rootcheck scan.':\n logging.debug(f\"Scan started - {self.agent_name}({self.agent_id}) \"\n f\"- rootcheck({self.rootcheck_path})\")\n if message == 'Ending rootcheck scan.':\n logging.debug(f\"Scan ended - {self.agent_name}({self.agent_id}) \"\n f\"- rootcheck({self.rootcheck_path})\")\n\n return message\n\n\nclass Logcollector:\n \"\"\"This class allows the generation of logcollector events.\"\"\"\n def __init__(self, enable_msg_number=None, custom_logcollector_message=''):\n self.logcollector_tag = 'syslog'\n self.logcollector_mq = 'x'\n # Those variables were added only in logcollector module to perform EPS test that need numbered messages.\n self.message_counter = 0\n self.enable_msg_number = enable_msg_number\n self.custom_logcollector_message = custom_logcollector_message\n\n def generate_event(self):\n \"\"\"Generate logcollector event\n Returns:\n str: a Logcollector generated message\n \"\"\"\n if not self.custom_logcollector_message:\n log = 'Mar 24 10:12:36 centos8 sshd[12249]: Invalid user random_user from 172.17.1.1 port 56550'\n else:\n log = self.custom_logcollector_message\n\n if self.enable_msg_number:\n message_counter_info = f\"Message number: {self.message_counter}\"\n message = f\"{self.logcollector_mq}:{self.logcollector_tag}:{log}:{message_counter_info}\"\n self.message_counter = self.message_counter + 1\n else:\n message = f\"{self.logcollector_mq}:{self.logcollector_tag}:{log}\"\n\n return message\n\n\nclass GeneratorIntegrityFIM:\n \"\"\"This class allows the generation of fim_integrity events.\n Args:\n agent_id (str): The id of the agent.\n agent_name (str): The name of the agent.\n agent_version (str): The version of the agent.\n \"\"\"\n def __init__(self, agent_id, agent_name, agent_version):\n self.agent_id = agent_id\n self.agent_name = agent_name\n self.agent_version = agent_version\n self.integrity_mq = \"5\"\n self.event_type = None\n self.fim_generator = GeneratorFIM(self.agent_id, self.agent_name, self.agent_version)\n\n def format_message(self, message):\n \"\"\"Format FIM integrity message.\n Args:\n message (str): Integrity fim event.\n \"\"\"\n return '{0}:[{1}] ({2}) any->syscheck:{3}'.format(self.integrity_mq, self.agent_id, self.agent_name, message)\n\n def generate_message(self):\n \"\"\"Generate integrity FIM message according to `event_type` attribute.\n Returns:\n str: an IntegrityFIM formatted message\n \"\"\"\n data = None\n if self.event_type in [\"integrity_check_global\", \"integrity_check_left\", \"integrity_check_right\"]:\n id = int(time())\n data = {\"id\": id,\n \"begin\": self.fim_generator.random_file(),\n \"end\": self.fim_generator.random_file(),\n \"checksum\": self.fim_generator.random_sha1()}\n\n if self.event_type == \"integrity_clear\":\n id = int(time())\n data = {\"id\": id}\n\n if self.event_type == \"state\":\n timestamp = int(time())\n self.fim_generator.generate_attributes()\n attributes = self.fim_generator.get_attributes()\n data = {\"path\": self.fim_generator._file,\n \"timestamp\": timestamp,\n \"attributes\": attributes}\n\n message = json.dumps({\"component\": \"syscheck\", \"type\": self.event_type, \"data\": data})\n formatted_message = self.format_message(message)\n return formatted_message\n\n def get_message(self, event_type=None):\n \"\"\"Generate a random kind of integrity FIM message according to `event_type` attribute.\n Returns:\n str: an IntegrityFIM formatted message\n \"\"\"\n if event_type is not None:\n self.event_type = event_type\n else:\n self.event_type = choice([\"integrity_check_global\", \"integrity_check_left\", \"integrity_check_right\",\n \"integrity_clear\", \"state\"])\n\n return self.generate_message()\n\n\nclass GeneratorHostinfo:\n \"\"\"This class allows the generation of hostinfo events.\n Creates hostinfo events, randomizing an open port detection template event on a host.\n It randomizes the host, as well as the ports and their protocol. The number of open ports of the event is a\n random number from 1 to 10. Example of hostinfo message:\n 3:/var/log/nmap.log:Host: 95.211.24.108 (), open ports: 43270 (udp) 37146 (tcp) 19885 (tcp)\n \"\"\"\n def __init__(self):\n self.hostinfo_mq = 3\n self.hostinfo_basic_template = 'Host: (), open ports: '\n self.protocols_list = ['udp', 'tcp']\n self.localfile = '/var/log/nmap.log'\n\n def generate_event(self):\n \"\"\"\"Generates an arbitrary hostinfo message\n Returns:\n str: an hostinfo formatted message\n \"\"\"\n number_open_ports = randint(1, 10)\n host_ip = get_random_ip()\n message_open_port_list = ''\n for _ in range(number_open_ports):\n message_open_port_list += fr\"{randint(1,65535)} ({choice(self.protocols_list)}) \"\n\n message = self.hostinfo_basic_template.replace('', host_ip)\n message += message_open_port_list\n message = fr\"{self.hostinfo_mq}:{self.localfile}:{message}\"\n\n return message\n\n\nclass GeneratorWinevt:\n \"\"\"This class allows the generation of winevt events.\n Create events of the different winevt channels: System, Security, Application, Windows-Defender and Sysmon.\n It uses template events (`data/winevt.py`) for which the `EventID` field is randomized. Message structure:\n f:EventChannel:{\"Message\":\"\",\"Event\":\"\"}\n Args:\n agent_name (str): Name of the agent.\n agent_id (str): ID of the agent.\n \"\"\"\n def __init__(self, agent_name, agent_id):\n self.agent_name = agent_name\n self.agent_id = agent_id\n self.winevent_mq = 'f'\n self.winevent_tag = 'Eventchannel'\n self.winevent_sources = {\n 'system': winevt.WINEVT_SYSTEM,\n 'security': winevt.WINEVT_SECURITY,\n 'windows-defender': winevt.WINEVT_WINDOWS_DEFENDER,\n 'application': winevt.WINEVT_APPLICATION,\n 'sysmon': winevt.WINEVT_SYSMON\n }\n\n self.current_event_key = None\n self.next_event_key = cycle(self.winevent_sources.keys())\n\n def generate_event(self, winevt_type=None):\n \"\"\"Generate Windows event.\n Generate the desired type of Windows event (winevt). If no type of winvt message is provided,\n all winvt message types will be generated sequentially.\n Args:\n winevt_type (str): Winevt type message `system, security, application, windows-defender, sysmon`.\n Returns:\n str: an windows event generated message.\n \"\"\"\n self.current_event_key = next(self.next_event_key)\n\n eventchannel_raw_message = self.winevent_sources[self.current_event_key]\n eventchannel_raw_message = eventchannel_raw_message.replace(\"\", str(randint(0, 10*5)))\n\n winevent_msg = f\"{self.winevent_mq}:{self.winevent_tag}:{eventchannel_raw_message}\"\n\n return winevent_msg\n\n\nclass GeneratorFIM:\n \"\"\"This class allows the generation of FIM events.\n Args:\n agent_id (str): The id of the agent.\n agent_name (str): The name of the agent.\n agent_version (str): The version of the agent.\n \"\"\"\n def __init__(self, agent_id, agent_name, agent_version):\n self.agent_id = agent_id\n self.agent_name = agent_name\n self.agent_version = agent_version\n self.file_root = '/root/'\n self._file = self.file_root + 'a'\n self._size = 0\n self._mode = S_IFREG | S_IRWXU\n self._uid = 0\n self._gid = 0\n self._md5 = 'xxx'\n self._sha1 = 'xxx'\n self._sha256 = 'xxx'\n self._uname = 'root'\n self._gname = 'root'\n self._mdate = int(mktime(localtime()))\n self._permissions = \"rw-r--r--\"\n self._inode = 0\n self._checksum = \"f65b9f66c5ef257a7566b98e862732640d502b6f\"\n self.syscheck_tag = 'syscheck'\n self.syscheck_mq = 8\n self.default_file_length = 10\n self.max_size = 1024\n self.users = {0: 'root', 1000: 'Dave', 1001: 'Connie'}\n self.max_timediff = 3600\n self.max_inode = 1024\n self.baseline_completed = 0\n self.event_mode = None\n self.event_type = None\n\n def random_file(self):\n \"\"\"Initialize file attribute.\n Returns:\n str: the new randomized file for the instance\n \"\"\"\n self._file = self.file_root + ''.join(sample(ascii_letters + digits, self.default_file_length))\n return self._file\n\n def random_size(self):\n \"\"\"Initialize file size with random value\n Returns:\n str: the new randomized file size for the instance\n \"\"\"\n self._size = randint(-1, self.max_size)\n return self._size\n\n def random_mode(self):\n \"\"\"Initialize module attribute with `S_IFREG` or `S_IFLNK`\n Returns:\n self._mode: the new randomized file mode for the instance\n \"\"\"\n self._mode = choice((S_IFREG, S_IFLNK))\n\n if self._mode == S_IFLNK:\n self._mode |= S_IRWXU | S_IRWXG | S_IRWXO\n self._md5 = 'xxx'\n self._sha1 = 'xxx'\n else:\n s = sample((S_IRWXU, S_IRWXG, S_IRWXO), 2)\n self._mode |= s[0] | s[1]\n\n return self._mode\n\n def random_uid(self):\n \"\"\"Initialize uid attribute with random value.\n Returns:\n str: the new randomized file uid for the instance\n \"\"\"\n self._uid = choice(list(self.users.keys()))\n self._uname = self.users[self._uid]\n return self._uid, self._uname\n\n def random_gid(self):\n \"\"\"Initialize gid attribute with random value.\n Returns:\n str: the new randomized gid for the instance,\n str: the new randomized gname for the instance.\n \"\"\"\n self._gid = choice(list(self.users.keys()))\n self._gname = self.users[self._gid]\n return self._gid, self._gname\n\n def random_md5(self):\n \"\"\"Initialize md5 attribute with random value.\n Returns:\n str: the new randomized md5 for the instance.\n \"\"\"\n if self._mode & S_IFREG == S_IFREG:\n self._md5 = ''.join(sample('0123456789abcdef' * 2, 32))\n\n return self._md5\n\n def random_sha1(self):\n \"\"\"Initialize sha1 attribute with random value.\n Returns:\n str: the new randomized sha1 for the instance.\n \"\"\"\n if self._mode & S_IFREG == S_IFREG:\n self._sha1 = ''.join(sample('0123456789abcdef' * 3, 40))\n\n return self._sha1\n\n def random_sha256(self):\n \"\"\"Initialize sha256 attribute with random value.\n Returns:\n str: the new randomized sha256 for the instance.\n \"\"\"\n if self._mode & S_IFREG == S_IFREG:\n self._sha256 = ''.join(sample('0123456789abcdef' * 4, 64))\n\n return self._sha256\n\n def random_time(self):\n \"\"\"Initialize time attribute with random value.\n Returns:\n str: the new randomized mdate for the instance.\n \"\"\"\n self._mdate += randint(1, self.max_timediff)\n return self._mdate\n\n def random_inode(self):\n \"\"\"Initialize inode attribute with random value.\n Returns:\n str: the new randomized inode for the instance.\n \"\"\"\n self._inode = randint(1, self.max_inode)\n return self._inode\n\n def generate_attributes(self):\n \"\"\"Initialize GeneratorFIM attributes\"\"\"\n self.random_file()\n self.random_size()\n self.random_mode()\n self.random_uid()\n self.random_gid()\n self.random_md5()\n self.random_sha1()\n self.random_sha256()\n self.random_time()\n self.random_inode()\n self._checksum = self.random_sha1()\n\n def check_changed_attributes(self, attributes, old_attributes):\n \"\"\"Returns attributes that have changed. \"\"\"\n changed_attributes = []\n if attributes[\"size\"] != old_attributes[\"size\"]:\n changed_attributes.append(\"size\")\n if attributes[\"perm\"] != old_attributes[\"perm\"]:\n changed_attributes.append(\"permission\")\n if attributes[\"uid\"] != old_attributes[\"uid\"]:\n changed_attributes.append(\"uid\")\n if attributes[\"gid\"] != old_attributes[\"gid\"]:\n changed_attributes.append(\"gid\")\n if attributes[\"user_name\"] != old_attributes[\"user_name\"]:\n changed_attributes.append(\"user_name\")\n if attributes[\"group_name\"] != old_attributes[\"group_name\"]:\n changed_attributes.append(\"group_name\")\n if attributes[\"inode\"] != old_attributes[\"inode\"]:\n changed_attributes.append(\"inode\")\n if attributes[\"mtime\"] != old_attributes[\"mtime\"]:\n changed_attributes.append(\"mtime\")\n if attributes[\"hash_md5\"] != old_attributes[\"hash_md5\"]:\n changed_attributes.append(\"md5\")\n if attributes[\"hash_sha1\"] != old_attributes[\"hash_sha1\"]:\n changed_attributes.append(\"sha1\")\n if attributes[\"hash_sha256\"] != old_attributes[\"hash_sha256\"]:\n changed_attributes.append(\"sha256\")\n\n return changed_attributes\n\n def get_attributes(self):\n \"\"\"Return GeneratorFIM attributes.\n Returns:\n dict: instance attributes.\n \"\"\"\n attributes = {\n \"type\": \"file\", \"size\": self._size,\n \"perm\": self._permissions, \"uid\": str(self._uid),\n \"gid\": str(self._gid), \"user_name\": self._uname,\n \"group_name\": self._gname, \"inode\": self._inode,\n \"mtime\": self._mdate, \"hash_md5\": self._md5,\n \"hash_sha1\": self._sha1, \"hash_sha256\": self._sha256,\n \"checksum\": self._checksum\n }\n return attributes\n\n def format_message(self, message):\n \"\"\"Format FIM message.\n Args:\n message (str): FIM message.\n Returns:\n str: generated message with the required FIM header.\n \"\"\"\n if self.agent_version >= \"3.12\":\n formated_message = f\"{self.syscheck_mq}:({self.agent_id}) any->syscheck:{message}\"\n else:\n # If first time generating. Send control message to simulate\n # end of FIM baseline.\n if self.baseline_completed == 0:\n self.baseline_completed = 1\n formated_message = f\"{self.syscheck_mq}:{self.syscheck_tag}:syscheck-db-completed\"\n else:\n formated_message = f\"{self.syscheck_mq}:{self.syscheck_tag}:{message}\"\n\n return formated_message\n\n def generate_message(self):\n \"\"\"Generate FIM event based on `event_type` and `agent_version` attribute.\n Returns:\n str: generated message with the required FIM header.\n \"\"\"\n if self.agent_version >= \"3.12\":\n if self.event_type == \"added\":\n timestamp = int(time())\n self.generate_attributes()\n attributes = self.get_attributes()\n data = {\"path\": self._file, \"mode\": self.event_mode,\n \"type\": self.event_type, \"timestamp\": timestamp,\n \"attributes\": attributes}\n elif self.event_type == \"modified\":\n timestamp = int(time())\n self.generate_attributes()\n attributes = self.get_attributes()\n self.generate_attributes()\n old_attributes = self.get_attributes()\n changed_attributes = self.check_changed_attributes(attributes, old_attributes)\n data = {\"path\": self._file, \"mode\": self.event_mode,\n \"type\": self.event_type, \"timestamp\": timestamp,\n \"attributes\": attributes,\n \"old_attributes\": old_attributes,\n \"changed_attributes\": changed_attributes}\n else:\n timestamp = int(time())\n self.generate_attributes()\n attributes = self.get_attributes()\n data = {\"path\": self._file, \"mode\": self.event_mode,\n \"type\": self.event_type, \"timestamp\": timestamp,\n \"attributes\": attributes}\n\n message = json.dumps({\"type\": \"event\", \"data\": data})\n\n else:\n self.generate_attributes()\n message = f'{self._size}:{self._mode}:{self._uid}:{self._gid}:{self._md5}:{self._sha1}:{self._uname}:' \\\n f'{self._gname}:{self._mdate}:{self._inode} {self._file}'\n\n formatted_message = self.format_message(message)\n return formatted_message\n\n def get_message(self, event_mode=None, event_type=None):\n \"\"\"Get FIM message. If no parameters are provided, it is randomly selected among the possible values\n Args:\n event_mode (str): Event mode `real-time, whodata, scheduled`.\n event_type (str): Event type `added, modified, deleted`.\n Returns:\n str: generated message.\n \"\"\"\n if event_mode is not None:\n self.event_mode = event_mode\n else:\n self.event_mode = choice([\"real-time\", \"whodata\", \"scheduled\"])\n\n if event_type is not None:\n self.event_type = event_type\n else:\n self.event_type = choice([\"added\", \"modified\", \"deleted\"])\n\n generated_message = self.generate_message()\n\n return generated_message\n\n\nclass Sender:\n \"\"\"This class sends events to the manager through a socket.\n Attributes:\n manager_address (str): IP of the manager.\n manager_port (str, optional): port used by remoted in the manager.\n protocol (str, optional): protocol used by remoted. TCP or UDP.\n socket (socket): sock_stream used to connect with remoted.\n Examples:\n To create a Sender, you need to create an agent first, and then, create the sender. Finally, to send messages\n you will need to use both agent and sender to create an injector.\n >>> import wazuh_testing.tools.agent_simulator as ag\n >>> manager_address = \"172.17.0.2\"\n >>> agent = ag.Agent(manager_address, \"aes\", os=\"debian8\", version=\"4.2.0\")\n >>> sender = ag.Sender(manager_address, protocol=TCP)\n \"\"\"\n def __init__(self, manager_address, manager_port='1514', protocol=TCP):\n self.manager_address = manager_address\n self.manager_port = manager_port\n self.protocol = protocol.upper()\n self.socket = None\n self.connect()\n\n def connect(self):\n if is_tcp(self.protocol):\n self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n self.socket.connect((self.manager_address, int(self.manager_port)))\n if is_udp(self.protocol):\n self.socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)\n\n def reconnect(self, event):\n if is_tcp(self.protocol):\n self.socket.shutdown(socket.SHUT_RDWR)\n self.socket.close()\n self.connect()\n if event:\n self.send_event(event)\n\n def send_event(self, event):\n if is_tcp(self.protocol):\n length = pack('>> import wazuh_testing.tools.agent_simulator as ag\n >>> manager_address = \"172.17.0.2\"\n >>> agent = ag.Agent(manager_address, \"aes\", os=\"debian8\", version=\"4.2.0\")\n >>> sender = ag.Sender(manager_address, protocol=TCP)\n >>> injector = ag.Injector(sender, agent)\n >>> injector.run()\n \"\"\"\n\n def __init__(self, sender, agent, limit=None):\n self.sender = sender\n self.agent = agent\n self.limit_msg = limit\n self.thread_number = 0\n self.threads = []\n for module, config in self.agent.modules.items():\n if config[\"status\"] == \"enabled\":\n self.threads.append(\n InjectorThread(self.thread_number, f\"Thread-{self.agent.id}{module}\", self.sender,\n self.agent, module, self.limit_msg))\n self.thread_number += 1\n\n def run(self):\n \"\"\"Start the daemon to send and receive messages for all the threads.\"\"\"\n for thread in range(self.thread_number):\n self.threads[thread].daemon = True\n self.threads[thread].start()\n\n def stop_receive(self):\n \"\"\"Stop the daemon for all the threads.\"\"\"\n for thread in range(self.thread_number):\n self.threads[thread].stop_rec()\n sleep(2)\n if is_tcp(self.sender.protocol):\n self.sender.socket.shutdown(socket.SHUT_RDWR)\n self.sender.socket.close()\n\n def wait(self):\n for thread in range(self.thread_number):\n self.threads[thread].join()\n\n\nclass InjectorThread(threading.Thread):\n \"\"\"This class creates a thread who will create and send the events to the manager for each module.\n Attributes:\n thread_id (int): ID of the thread.\n name (str): name of the thread. It is composed as Thread-{agent.id}{module}.\n sender (Sender): sender used to connect to the sockets and send messages.\n agent (Agent): agent owner of the injector and the sender.\n module (str): module used to send events (fim, syscollector, etc).\n stop_thread (int): 0 if the thread is running, 1 if it is stopped.\n limit_msg (int): Maximum amount of message to be sent.\n \"\"\"\n def __init__(self, thread_id, name, sender, agent, module, limit_msg=None):\n super(InjectorThread, self).__init__()\n self.thread_id = thread_id\n self.name = name\n self.sender = sender\n self.agent = agent\n self.totalMessages = 0\n self.module = module\n self.stop_thread = 0\n self.limit_msg = limit_msg\n\n def keep_alive(self):\n \"\"\"Send a keep alive message from the agent to the manager.\"\"\"\n sleep(10)\n logging.debug(\"Startup - {}({})\".format(self.agent.name, self.agent.id))\n self.sender.send_event(self.agent.startup_msg)\n self.sender.send_event(self.agent.keep_alive_event)\n start_time = time()\n frequency = self.agent.modules[\"keepalive\"][\"frequency\"]\n eps = 1\n if 'eps' in self.agent.modules[\"keepalive\"]:\n frequency = 0\n eps = self.agent.modules[\"keepalive\"][\"eps\"]\n while self.stop_thread == 0:\n # Send agent keep alive\n logging.debug(f\"KeepAlive - {self.agent.name}({self.agent.id})\")\n self.sender.send_event(self.agent.keep_alive_event)\n self.totalMessages += 1\n if frequency > 0:\n sleep(frequency - ((time() - start_time) % frequency))\n else:\n logging.debug('Merged checksum modified to force manager overload')\n new_checksum = str(getrandbits(128))\n self.agent.update_checksum(new_checksum)\n if self.totalMessages % eps == 0:\n sleep(1.0 - ((time() - start_time) % 1.0))\n\n def run_module(self, module):\n \"\"\"Send a module message from the agent to the manager.\n Args:\n module (str): Module name\n \"\"\"\n module_info = self.agent.modules[module]\n eps = module_info['eps'] if 'eps' in module_info else 1\n frequency = module_info[\"frequency\"] if 'frequency' in module_info else 1\n\n sleep(10)\n start_time = time()\n if frequency > 1:\n batch_messages = eps * 0.5 * frequency\n else:\n batch_messages = eps\n\n if module == 'hostinfo':\n self.agent.init_hostinfo()\n module_event_generator = self.agent.hostinfo.generate_event\n elif module == 'rootcheck':\n self.agent.init_rootcheck()\n module_event_generator = self.agent.rootcheck.get_message\n batch_messages = len(self.agent.rootcheck.messages_list) * eps\n elif module == 'syscollector':\n self.agent.init_syscollector()\n module_event_generator = self.agent.syscollector.generate_event\n elif module == 'fim_integrity':\n self.agent.init_fim_integrity()\n module_event_generator = self.agent.fim_integrity.get_message\n elif module == 'fim':\n module_event_generator = self.agent.fim.get_message\n elif module == 'sca':\n self.agent.init_sca()\n module_event_generator = self.agent.sca.get_message\n elif module == 'winevt':\n self.agent.init_winevt()\n module_event_generator = self.agent.winevt.generate_event\n elif module == 'logcollector':\n self.agent.init_logcollector()\n module_event_generator = self.agent.logcollector.generate_event\n else:\n raise ValueError('Invalid module selected')\n\n # Loop events\n while self.stop_thread == 0:\n sent_messages = 0\n while sent_messages < batch_messages:\n event_msg = module_event_generator()\n if self.agent.fixed_message_size is not None:\n event_msg_size = getsizeof(event_msg)\n dummy_message_size = self.agent.fixed_message_size - event_msg_size\n char_size = getsizeof(event_msg[0]) - getsizeof('')\n event_msg += 'A' * (dummy_message_size//char_size)\n\n # Add message limitiation\n if self.limit_msg:\n if self.totalMessages >= self.limit_msg:\n self.stop_thread = 1\n break\n\n event = self.agent.create_event(event_msg)\n self.sender.send_event(event)\n self.totalMessages += 1\n sent_messages += 1\n if self.totalMessages % eps == 0:\n sleep(1.0 - ((time() - start_time) % 1.0))\n\n if frequency > 1:\n sleep(frequency - ((time() - start_time) % frequency))\n\n def run(self):\n \"\"\"Start the thread that will send messages to the manager.\"\"\"\n # message = \"1:/var/log/syslog:Jan 29 10:03:41 master sshd[19635]:\n # pam_unix(sshd:session): session opened for user vagrant by (uid=0)\n # uid: 0\"\n logging.debug(f\"Starting - {self.agent.name}({self.agent.id})({self.agent.os}) - {self.module}\")\n if self.module == \"keepalive\":\n self.keep_alive()\n elif self.module == \"receive_messages\":\n self.agent.receive_message(self.sender)\n else:\n self.run_module(self.module)\n\n def stop_rec(self):\n \"\"\"Stop the thread to avoid sending any more messages.\"\"\"\n if self.module == \"receive_messages\":\n self.agent.stop_receiver()\n else:\n self.stop_thread = 1\n\n\ndef create_agents(agents_number, manager_address, cypher='aes', fim_eps=100, authd_password=None, agents_os=None,\n agents_version=None, disable_all_modules=False):\n \"\"\"Create a list of generic agents\n This will create a list with `agents_number` amount of agents. All of them will be registered in the same manager.\n Args:\n agents_number (int): total number of agents.\n manager_address (str): IP address of the manager.\n cypher (str): cypher used for the communications. It may be aes or blowfish.\n fim_eps (int, optional): total number of EPS produced by FIM.\n authd_password (str, optional): password to enroll an agent.\n agents_os (list, optional): list containing different operative systems for the agents.\n agents_version (list, optional): list containing different version of the agent.\n disable_all_modules (boolean): Disable all simulated modules for this agent.\n Returns:\n list: list of the new virtual agents.\n \"\"\"\n global agent_count\n # Read client.keys and create virtual agents\n agents = []\n for agent in range(agents_number):\n agent_os = agents_os[agent] if agents_os is not None else None\n agent_version = agents_version[agent] if agents_version is not None else None\n\n agents.append(Agent(manager_address, cypher, fim_eps=fim_eps, authd_password=authd_password,\n os=agent_os, version=agent_version, disable_all_modules=disable_all_modules))\n\n agent_count = agent_count + 1\n\n return agents\n\n\ndef connect(agent, manager_address='localhost', protocol=TCP, manager_port='1514'):\n \"\"\"Connects an agent to the manager\n Args:\n agent (Agent): agent to connect.\n manager_address (str): address of the manager. It can be an IP or a DNS.\n protocol (str): protocol used to connect with the manager. Defaults to 'TCP'.\n manager_port (str): port used to connect with the manager. Defaults to '1514'.\n \"\"\"\n sender = Sender(manager_address, protocol=protocol, manager_port=manager_port)\n injector = Injector(sender, agent)\n injector.run()\n agent.wait_status_active()\n return sender, injector\n","repo_name":"wazuh/wazuh-qa","sub_path":"deps/wazuh_testing/wazuh_testing/tools/agent_simulator.py","file_name":"agent_simulator.py","file_ext":"py","file_size_in_byte":76339,"program_lang":"python","lang":"en","doc_type":"code","stars":29,"dataset":"github-code","pt":"21"}
+{"seq_id":"7996751612","text":"from django.core.exceptions import ObjectDoesNotExist\nfrom django.http import HttpResponseRedirect\nfrom django.urls import reverse\n\nfrom Base.base_group_views import ManagerRequiredView\nfrom Papers.services import PaperInfoService, SpecificationService\n\nfrom ..services import StagingSpecificationService, ReferencePDFService\n\n\nclass TestSpecPageView(ManagerRequiredView):\n def dispatch(self, request, *args, **kwargs):\n \"\"\"Redirect to the assessment preparation page if the Papers database is already populated.\"\"\"\n paper_info = PaperInfoService()\n if paper_info.is_paper_database_populated():\n return HttpResponseRedirect(reverse(\"prep_landing\"))\n return super().dispatch(request, *args, **kwargs)\n\n def build_context(self, page_name):\n context = super().build_context()\n spec = StagingSpecificationService()\n\n show_alert = False\n try:\n the_valid_spec = SpecificationService.get_the_spec()\n if not spec.compare_spec(the_valid_spec):\n show_alert = True\n except ObjectDoesNotExist:\n # no valid spec - nothing to do yet.\n pass\n\n context.update(\n {\n \"long_name\": spec.get_long_name(),\n \"short_name\": spec.get_short_name(),\n \"slugged_short_name\": spec.get_short_name_slug(),\n \"curr_page\": page_name,\n \"questions\": [i for i in range(spec.get_n_questions())],\n \"completed\": spec.get_progress_dict(),\n \"show_alert\": show_alert,\n }\n )\n\n return context\n\n\nclass TestSpecPDFView(TestSpecPageView):\n def build_context(self, page_name):\n context = super().build_context(page_name)\n spec = StagingSpecificationService()\n ref = ReferencePDFService()\n if ref.is_there_a_reference_pdf():\n thumbnails = ref.create_page_thumbnail_list()\n context.update(\n {\n \"thumbnails\": thumbnails,\n \"num_pages\": spec.get_n_pages(),\n }\n )\n\n return context\n","repo_name":"plomgrading/plom","sub_path":"plom_server/SpecCreator/views/base.py","file_name":"base.py","file_ext":"py","file_size_in_byte":2149,"program_lang":"python","lang":"en","doc_type":"code","stars":10,"dataset":"github-code","pt":"21"}
+{"seq_id":"5431632254","text":"def solution(ingredient):\n ans = 0\n 재료 = []\n \n for i in ingredient:\n 재료.append(i)\n if 재료[-4:] == [1, 2, 3, 1]:\n ans += 1\n for _ in range(4):\n 재료.pop()\n return ans\n \n ","repo_name":"hanwool77/codingtest","sub_path":"프로그래머스/unrated/133502. 햄버거 만들기/햄버거 만들기.py","file_name":"햄버거 만들기.py","file_ext":"py","file_size_in_byte":258,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"}
+{"seq_id":"70436795254","text":"# Solution for task: https://www.codewars.com/kata/59a2a3ba5eb5d4e609000055/\n\ndef find_array(arr1: list, arr2: list) -> list:\n \n new_arr = list()\n \n for i in arr2:\n if i < len(arr1):\n new_arr.append(arr1[i])\n\n return new_arr\n","repo_name":"ZaytsevNS/python_codewars","sub_path":"7KYU/find_array.py","file_name":"find_array.py","file_ext":"py","file_size_in_byte":258,"program_lang":"python","lang":"en","doc_type":"code","stars":11,"dataset":"github-code","pt":"21"}
+{"seq_id":"26835187452","text":"import numpy as np\nimport torch\nfrom torch.utils.data import Dataset\nfrom torchvision import datasets\nfrom torchvision.transforms import ToTensor\nimport matplotlib.pyplot as plt\nimport os\n\n# OMP 에러 해결\nos.environ['KMP_DUPLICATE_LIB_OK']='True'\n\n# 데이터 다운로드\n# -> 다운로드 값이 True여도 루트 경로에 파일이 있으면, 다운로드 하지 않는다!\n# -> 따라서 루트값이 바뀌면 계속 다운로드하니, 루트값을 고정하는 것이 중요\ntraining_data = datasets.FashionMNIST(\n root='data',\n train=True,\n download=True,\n transform=ToTensor()\n)\n\ntest_data = datasets.FashionMNIST(\n root='data',\n train=False,\n download=True,\n transform=ToTensor()\n)\n\n# 데이터 시각화\n# -> 해당 이미지들은 28x28 이미지이며, 바이너리 파일이어서 한 줄로 쭉 이어져 있다\nimg_size = 28\nnum_images = 5\n\nwith open('./data/FashionMNIST/raw/train-images-idx3-ubyte', 'rb') as f:\n _ = f.read(16) # 17바이트부터 이미지 데이터여서 16바이트는 날린다\n buf = f.read(img_size*img_size*num_images)\n data = np.frombuffer(buf, dtype=np.uint8).astype(float)\n data = data.reshape(num_images, img_size, img_size, 1)\n image = np.asarray(data[1]).squeeze()\n plt.imshow(image, 'gray')\n plt.show()\n\nwith open('data/FashionMNIST/raw/train-labels-idx1-ubyte', 'rb') as f:\n _ = f.read(8)\n buf = f.read(num_images)\n labels = np.frombuffer(buf, dtype=np.uint8).astype(np.int64)\n print(labels[1]) # loss구하려면 라벨이 숫자여야하므로, 라벨은 전부 숫자로 되어있다.\n# plt.title(f'{labels[0]}')\n# plt.show()\n\n# 라벨 목록\nlabels_map = {\n 0: \"T-Shirt\",\n 1: \"Trouser\",\n 2: \"Pullover\",\n 3: \"Dress\",\n 4: \"Coat\",\n 5: \"Sandal\",\n 6: \"Shirt\",\n 7: \"Sneaker\",\n 8: \"Bag\",\n 9: \"Ankle Boot\",\n}\n\nfigure = plt.figure(figsize=(8, 8))\ncols, rows = 3, 3\n\n# for i in range(1, cols*rows+1):\n# sample_idx = torch.randint(len(training_data), size=(1, )).item()\n# img, label = training_data[sample_idx]\n# figure.add_subplot(rows, cols, i)\n# plt.title(labels_map[label])\n# plt.axis('off')\n# plt.imshow(img.squeeze(), cmap='gray')\n# plt.show()\n# exit()","repo_name":"NoirCade/MS-AI-School","sub_path":"48일차/fashion_mnist.py","file_name":"fashion_mnist.py","file_ext":"py","file_size_in_byte":2221,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"}
+{"seq_id":"23110314941","text":"import numpy as np\nimport tensorflow as tf\n\n\ndef discount_rewards(rewards, gamma=0.99):\n \"\"\" take 1D float array of rewards and compute discounted rewards \"\"\"\n discounted = np.zeros_like(rewards)\n running_add = 0\n for t in reversed(range(0, len(rewards))):\n running_add = running_add * gamma + rewards[t]\n discounted[t] = running_add\n\n return discounted\n\n\ndef reset_grad_buffer(grad_buffer):\n if type(grad_buffer) is not np.ndarray:\n grad_buffer = np.array(grad_buffer)\n\n grad_buffer *= 0\n return grad_buffer\n\n\ndef step_model(model, sess, xs, action):\n \"\"\"\n This function uses our model to produce a new state\n when given a previous state and action.\n \"\"\"\n pred = sess.run(model.pred_state, feed_dict={\n model.prev_state: np.reshape(np.hstack([xs[-1][0], np.array(action)]), [1, 5])\n })\n reward = pred[:, 4]\n obs = pred[:, 0:4]\n obs[:, 0] = np.clip(obs[:, 0], -2.4, 2.4)\n obs[:, 2] = np.clip(obs[:, 2], -0.4, 0.4)\n p_done = np.clip(pred[:, 5], 0, 1)\n done = (p_done > 0.1 or len(xs) >= 300)\n\n return obs, reward, done\n\n\ndef train(env, policy, model, model_batch_size, real_batch_size, max_episodes=5000):\n xs, ys, rs, ds = [], [], [], []\n running_reward = None\n reward_sum = 0\n episode_num = 1\n real_episodes = 1\n batch_size = real_batch_size\n\n draw_from_model = False # When set to True, will use model for observations\n train_model = True # Whether to train the model\n train_policy = False # Whether to train the policy\n switch_point = 1\n\n p_state = None\n next_states_all = None\n\n with tf.Session() as sess:\n sess.run(tf.global_variables_initializer())\n rendering = False\n obs = env.reset()\n # x = obs\n grad_buffer = sess.run(policy.tvars)\n grad_buffer = reset_grad_buffer(grad_buffer)\n\n while episode_num < max_episodes:\n # Start displaying environment once performance is acceptably high\n if rendering or (reward_sum / batch_size > 150 and not draw_from_model):\n env.render()\n rendering = True\n\n x = np.reshape(obs, [1, 4])\n prob = sess.run(policy.probability, feed_dict={policy.observations: x})\n action = 1 if np.random.uniform() < prob else 0\n\n xs.append(x)\n y = 1 if action == 0 else 0\n ys.append(y)\n\n if draw_from_model:\n obs, reward, done = step_model(model, sess, xs, action)\n else:\n obs, reward, done, _ = env.step(action)\n\n reward_sum += reward\n rs.append(reward) # record reward (has to be done after we call step() to get reward for previous action)\n ds.append(done * 1)\n\n if done:\n if not draw_from_model:\n real_episodes += 1\n\n episode_num += 1\n\n # stack together all inputs, hidden states, action gradients,\n # and rewards for this episode\n epx = np.vstack(xs)\n epy = np.vstack(ys)\n epr = np.vstack(rs)\n epd = np.vstack(ds)\n xs, ys, rs, ds = [], [], [], [] # reset memory\n\n if train_model:\n actions = np.array([np.abs(y - 1) for y in epy][:-1])\n prev_states = epx[:-1, :]\n prev_states = np.hstack([prev_states, actions])\n next_states = epx[1:, :]\n rewards = np.array(epr[1:, :])\n dones = np.array(epd[1:, :])\n next_states_all = np.hstack([next_states, rewards, dones])\n feed_dict = {\n model.prev_state: prev_states,\n model.true_obs: next_states,\n model.true_done: dones,\n model.true_reward: rewards\n }\n loss, p_state, _ = sess.run([model.loss, model.pred_state, model.update_op], feed_dict)\n\n if train_policy:\n discounted_epr = discount_rewards(epr).astype('float32')\n discounted_epr -= np.mean(discounted_epr)\n discounted_epr /= np.std(discounted_epr)\n grads_t = sess.run(policy.new_grads, feed_dict={\n policy.observations: epx,\n policy.input_y: epy,\n policy.advantage: discounted_epr\n })\n\n # If gradients become too large, end training process\n if np.sum(grads_t[0] == grads_t[0]) == 0:\n print('Gradients too large!')\n break\n\n for i, grad in enumerate(grads_t):\n grad_buffer[i] += grad\n\n if switch_point + batch_size == episode_num:\n switch_point = episode_num\n\n if train_policy:\n sess.run(policy.update_grads, feed_dict={\n policy.w1_grad: grad_buffer[0],\n policy.w2_grad: grad_buffer[1]\n })\n grad_buffer = reset_grad_buffer(grad_buffer)\n\n if running_reward is None:\n running_reward = reward_sum\n else:\n running_reward = running_reward * 0.99 + reward_sum * 0.01\n\n if not draw_from_model:\n print('World Perf: Episode %i Reward %f action: %i mean reward %f' %\n (real_episodes, reward_sum / real_batch_size, action,\n running_reward / real_batch_size))\n\n if reward_sum / batch_size > 200:\n break\n\n reward_sum = 0\n\n # Once the model has been trained on 100 episodes,\n # we start alternating between training the policy\n # from the model and training the model from the\n # real environment.\n if episode_num > 100:\n draw_from_model = not draw_from_model\n train_model = not train_model\n train_policy = not train_policy\n\n if draw_from_model:\n obs = np.random.uniform(-0.1, 0.1, [4]) # Generate reasonable starting point\n batch_size = model_batch_size\n else:\n obs = env.reset()\n batch_size = real_batch_size\n\n print('Num real episodes:', real_episodes)\n\n return p_state, next_states_all\n","repo_name":"markmo/dltemplate","sub_path":"src/rl/survey_of_methods/model_based/util.py","file_name":"util.py","file_ext":"py","file_size_in_byte":6761,"program_lang":"python","lang":"en","doc_type":"code","stars":57,"dataset":"github-code","pt":"21"}
+{"seq_id":"24250804922","text":"import numpy as np\nimport torch\nimport os\nimport argparse\nimport time\nimport math\nimport copy\nimport ast\nimport random\n\n\ndef make_directory(dirpath):\n os.makedirs(dirpath,exist_ok=True)\n\ndef experiment_argparser():\n parser = argparse.ArgumentParser()\n parser.add_argument('--lra', default=1e-3, type=float, help='learning rate actor')\n parser.add_argument('--lrc', default=1e-3, type=float, help='learning rate critic')\n parser.add_argument(\"-o\", \"--odir\", type=str, default=None, help=\"output directory\")\n parser.add_argument(\"-d\", \"--debug\", action=\"store_true\", help=\"debug\")\n parser.add_argument(\"-p\",'--policy' ,type=str, default='GaussianML', help=\"policy type to use\")\n parser.add_argument(\"-u\",'--num_updates', type=float, default=1e4, help=\"number of gradient updates\")\n parser.add_argument(\"-g\",\"--gamma\", type=float, default=0.99, help=\"discount factor\")\n parser.add_argument(\"-N\", type=int, default=15000, help=\"Batch Size\")\n parser.add_argument(\"-V\", '--num-env', type=int, default=1, help=\"Num Env\")\n parser.add_argument(\"-s\",'--save_interval', type=float, default=1e3, help=\"Model Save Interval\")\n parser.add_argument(\"-l\",'--log_interval', type=int, default=50, help=\"Log Interval\")\n parser.add_argument(\"-E\",'--env', type=str, default=\"BipedalWalker-v2\", help=\"Environment to use\")\n parser.add_argument(\"-co\", \"--console\", action=\"store_true\", help=\"log to console\")\n parser.add_argument('--tau', type=float, default=0.98, metavar='G',help='gae (default: 0.97)')\n parser.add_argument('--l2_pen', type=float, default=1e-3, metavar='G',help='l2 regularization regression (default: 1e-3)')\n parser.add_argument('--max_kl', type=float, default=1e-2, metavar='G',help='max kl value (default: 1e-2)')\n parser.add_argument('--seed', type=int, default=543, metavar='N',help='random seed (default: 543). -1 indicates no seed')\n parser.add_argument('--damping', type=float, default=1e-1, metavar='G',help='damping (default: 1e-1)')\n parser.add_argument('-a','--alg',type=str, default='TRPO', metavar='G',help='algorithm to use')\n parser.add_argument('-b','--backend',type=str, default='numpy', metavar='G',help='backend to use for Jacobian')\n parser.add_argument(\"--nk\", type=str,default=None, help=\"kwargs for actor and critic nets\")\n parser.add_argument('--nt',type=str,nargs='+',default=['GaussianML','Value'], help=\"which network architecture to use\")\n parser.add_argument(\"--run\", type=int,default=0, help=\"indicates what run number if running multiple of same experiment\")\n parser.add_argument(\"--rstat\", action=\"store_true\", help=\"use running stats to normalize states (used in Schulman's TRPO)\")\n\n return parser\n\ndef train_params_from_args(args):\n experiment_config = {'gamma' : args.gamma,\n 'alg' : args.alg,\n 'tau' : args.tau,\n 'max_kl' : args.max_kl,\n 'l2_pen' : args.l2_pen,\n 'lr_actor' : args.lra,\n 'lr_critic' : args.lrc,\n 'damping' : args.damping,\n 'backend' : args.backend,\n 'num_env' : args.num_env,\n 'ac_kwargs': get_kwargs(args.nk),\n 'ac_types': {'actor':args.nt[0],'critic':args.nt[1]},\n 'debug' : args.debug,\n 'policy' : args.policy,\n 'running_stat' : args.rstat,\n 'seed' : args.seed if args.seed != -1 else random.randint(0,1e8), # make a random seed\n 'num_updates' : int(args.num_updates),\n 'N' : args.N,\n 'env' : args.env,\n 'console' : args.console,\n 'run' : args.run,\n 'odir' : args.odir if args.odir is not None else 'out/experiment_%s' % time.strftime(\"%Y.%m.%d_%H.%M.%S\"),\n 'save_interval' : int(args.save_interval)}\n\n return experiment_config\n\n\ndef run_config_from_args(args):\n experiment_config = {'backend' : args.backend,\n 'debug' : args.debug,\n 'console' : args.console,\n 'odir' : args.odir if args.odir is not None else 'out/experiment_%s' % time.strftime(\"%Y.%m.%d_%H.%M.%S\"),\n 'save_interval' : int(args.save_interval)}\n\n return experiment_config\n\n\n\ndef get_kwargs(arg_str):\n if arg_str is not None:\n kwargs = ast.literal_eval(arg_str)\n return kwargs\n return {}\n\n\ndef run_training(train_config):\n import os\n import logging\n logger = logging.getLogger(__name__)\n import gym\n import json\n import time\n\n import sampler\n import algorithm\n import model\n import environment\n import policy\n #############################\n # SETUP\n episode_results_path = os.path.join(train_config['odir'],'episode_results_run_%d.npy' % train_config['run'])\n\n make_directory(train_config['odir'])\n with open(os.path.join(train_config['odir'],'train_config_run_%d.json' % train_config['run']), 'w') as fp:\n json.dump(train_config, fp, sort_keys=True, indent=4)\n\n log_level = logging.DEBUG if train_config['debug'] else logging.INFO\n if not train_config['console']:\n logging.basicConfig(filename=os.path.join(train_config['odir'],'log_run_%d.log' % train_config['run']),\n level=log_level,\n format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',)\n else:\n logging.basicConfig(level=log_level)\n\n ###############################\n # MAKE NET AND POLICY\n env = gym.make(train_config['env'])\n num_inputs = env.observation_space.shape[0]\n num_actions = env.action_space.shape[0]\n if train_config['seed'] is not None:\n random.seed(train_config['seed'])\n ts = random.randint(1,1e8)\n torch.manual_seed(ts)\n\n log_str = '\\r\\n###################################################\\r\\n' + \\\n '\\tEnvironment: %s\\r\\n' % train_config['env'] + \\\n '\\tAlgorithm: %s\\r\\n' % train_config['alg'] + \\\n '\\tPolicy Class: %s\\r\\n' % train_config['policy'] + \\\n '\\tNetwork Types: (%s,%s)\\r\\n' % (train_config['ac_types']['actor'],train_config['ac_types']['critic']) + \\\n '\\tNetwork Params: %s \\r\\n' % str(train_config['ac_kwargs']) + \\\n '\\tN, Total Updates, Save Interval: (%d,%d,%d) \\r\\n' % (train_config['N'],train_config['num_updates'],train_config['save_interval']) + \\\n '###################################################'\n logger.info(log_str)\n\n actor_net = getattr(model,train_config['ac_types']['actor'])(num_inputs, num_actions,**train_config['ac_kwargs'])\n critic_net = getattr(model,train_config['ac_types']['critic'])(num_inputs,**train_config['ac_kwargs'])\n plc = None\n try:\n plc_class = getattr(policy,train_config['policy'])\n plc = plc_class(actor_net)\n except AttributeError as e:\n raise RuntimeError('Algorithm \"%s\" not found' % train_config['policy'])\n\n ###############################\n # CREATE ENVIRONMENT AND RUN\n algo = None\n try:\n algo_class = getattr(algorithm,train_config['alg'])\n algo = algo_class(plc,critic_net,train_config)\n except AttributeError as e:\n raise RuntimeError('Algorithm \"%s\" not found' % train_config['alg'])\n\n smp = sampler.BatchSampler(plc,**train_config)\n episode_results = np.array([]).reshape((0,6))\n cur_update = 0\n finished_episodes = 0\n smp.reset()\n samples_per_update = train_config['N'] * train_config['num_env']\n start = time.time()\n while cur_update < train_config['num_updates']:\n batch,crs,trs,els = smp.sample()\n algo.update(batch)\n\n # save episode results\n for i,(cr,tr,el) in enumerate(zip(crs,trs,els)):\n finished_episodes += 1\n total_samples = cur_update * samples_per_update\n # stores: total_updates, total_episodes, total_samples, current_episode_length, current_total_reward, current_cumulative_reward\n episode_results = np.concatenate((episode_results,np.array([cur_update,finished_episodes,total_samples,el,tr,cr],ndmin=2)),axis=0)\n np.save(episode_results_path, episode_results)\n logger.info('Update Number: %06d, Finished Episode: %04d --- Length: %.3f, TR: %.3f, CDR: %.3f'% (cur_update,finished_episodes,el,tr,cr))\n\n # checkpoint\n if cur_update % train_config['save_interval'] == 0:\n plc.save_model(os.path.join(train_config['odir'],'model_update_%06d_run_%d.pt' % (cur_update,train_config['run'])))\n cur_update += 1\n\n end = time.time()\n print(end - start)\n","repo_name":"ceisenach/torchkit","sub_path":"utils/experiment.py","file_name":"experiment.py","file_ext":"py","file_size_in_byte":8833,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"21"}
+{"seq_id":"15870419356","text":"import pandas as pd\nimport glob\nfrom pandas import Series,DataFrame\n\npath ='/home/rock19/Desktop/Algo_Project/allCSV' \n\nallFiles = glob.glob(path + \"/*.csv\")\nframe = pd.DataFrame()\nlist_ = []\n\nfor file_ in allFiles:\n df = pd.read_csv(file_,index_col=None, header=0)\n list_.append(df)\n\nframe = pd.concat(list_)\n\nframe.to_csv(\"/home/rock19/Desktop/Algo_Project/census.csv\")\n\n","repo_name":"iamblizzard/literacy-prediction-in-india","sub_path":"script.py","file_name":"script.py","file_ext":"py","file_size_in_byte":379,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"21"}
+{"seq_id":"29036357956","text":"\"\"\"\nThe one parameter exponential family distributions used by GLM.\n\"\"\"\n# TODO: quasi, quasibinomial, quasipoisson\n# see http://www.biostat.jhsph.edu/~qli/biostatistics_r_doc/library/stats/html/family.html\n# for comparison to R, and McCullagh and Nelder\n\nimport numpy as np\nfrom scipy import special\n\nfrom . import links as L # noqa N812\nfrom . import varfuncs as V # noqa N812\n\nFLOAT_EPS = np.finfo(float).eps\n\n\nclass Family:\n \"\"\"\n The parent class for one-parameter exponential families.\n\n Parameters\n ----------\n link : a link function instance\n Link is the linear transformation function.\n See the individual families for available links.\n variance : a variance function\n Measures the variance as a function of the mean probabilities.\n See the individual families for the default variance function.\n\n See Also\n --------\n :ref:`links`\n\n \"\"\"\n\n # TODO: change these class attributes, use valid somewhere...\n valid = [-np.inf, np.inf]\n\n links = []\n\n def _setlink(self, link):\n \"\"\"\n Helper method to set the link for a family.\n\n Raises a ValueError exception if the link is not available. Note that\n the error message might not be that informative because it tells you\n that the link should be in the base class for the link function.\n\n See glm.GLM for a list of appropriate links for each family but note\n that not all of these are currently available.\n \"\"\"\n # TODO: change the links class attribute in the families to hold\n # meaningful information instead of a list of links instances such as\n # [,\n # ,\n # ]\n # for Poisson...\n self._link = link\n if not isinstance(link, L.Link):\n raise TypeError(\"The input should be a valid Link object.\")\n if hasattr(self, \"links\"):\n validlink = link in self.links\n validlink = max([isinstance(link, _) for _ in self.links])\n if not validlink:\n errmsg = \"Invalid link for family, should be in %s. (got %s)\"\n raise ValueError(errmsg % (repr(self.links), link))\n\n def _getlink(self):\n \"\"\"\n Helper method to get the link for a family.\n \"\"\"\n return self._link\n\n # link property for each family is a pointer to link instance\n link = property(_getlink, _setlink, doc=\"Link function for family\")\n\n def __init__(self, link, variance):\n self.link = link()\n self.variance = variance\n\n def starting_mu(self, y):\n r\"\"\"\n Starting value for mu in the IRLS algorithm.\n\n Parameters\n ----------\n y : array\n The untransformed response variable.\n\n Returns\n -------\n mu_0 : array\n The first guess on the transformed response variable.\n\n \"\"\"\n return (y + y.mean()) / 2.0\n\n def weights(self, mu):\n r\"\"\"\n Weights for IRLS steps\n\n Parameters\n ----------\n mu : array-like\n The transformed mean response variable in the exponential family\n\n Returns\n -------\n w : array\n The weights for the IRLS steps\n\n \"\"\"\n return 1.0 / (self.link.deriv(mu) ** 2 * self.variance(mu))\n\n def deviance(self, endog, mu, freq_weights=1.0, scale=1.0):\n r\"\"\"\n The deviance function evaluated at (endog,mu,freq_weights,mu).\n\n Deviance is usually defined as twice the loglikelihood ratio.\n\n Parameters\n ----------\n endog : array-like\n The endogenous response variable\n mu : array-like\n The inverse of the link function at the linear predicted values.\n freq_weights : array-like\n 1d array of frequency weights. The default is 1.\n scale : float, optional\n An optional scale argument. The default is 1.\n\n Returns\n -------\n Deviance : array\n The value of deviance function defined below.\n\n \"\"\"\n raise NotImplementedError\n\n def resid_dev(self, endog, mu, freq_weights=1.0, scale=1.0):\n \"\"\"\n The deviance residuals\n\n Parameters\n ----------\n endog : array\n The endogenous response variable\n mu : array\n The inverse of the link function at the linear predicted values.\n freq_weights : array-like\n 1d array of frequency weights. The default is 1.\n scale : float, optional\n An optional argument to divide the residuals by scale. The default\n is 1.\n\n Returns\n -------\n Deviance residuals.\n\n \"\"\"\n raise NotImplementedError\n\n def fitted(self, lin_pred):\n \"\"\"\n Fitted values based on linear predictors lin_pred.\n\n Parameters\n -----------\n lin_pred : array\n Values of the linear predictor of the model.\n dot(X,beta) in a classical linear model.\n\n Returns\n --------\n mu : array\n The mean response variables given by the inverse of the link\n function.\n \"\"\"\n fits = self.link.inverse(lin_pred)\n return fits\n\n def predict(self, mu):\n \"\"\"\n Linear predictors based on given mu values.\n\n Parameters\n ----------\n mu : array\n The mean response variables\n\n Returns\n -------\n lin_pred : array\n Linear predictors based on the mean response variables. The value\n of the link function at the given mu.\n \"\"\"\n return self.link(mu)\n\n def loglike(self, endog, mu, freq_weights=1.0, scale=1.0):\n \"\"\"\n The log-likelihood function in terms of the fitted mean response.\n\n Parameters\n ----------\n `endog` : array\n Usually the endogenous response variable.\n `mu` : array\n Usually but not always the fitted mean response variable.\n freq_weights : array-like\n 1d array of frequency weights. The default is 1.\n scale : float\n The scale parameter. The default is 1.\n\n Returns\n -------\n llf : float\n The value of the loglikelihood evaluated at\n (endog,mu,freq_weights,scale) as defined below.\n \"\"\"\n raise NotImplementedError\n\n def resid_anscombe(self, endog, mu):\n \"\"\"\n The Anscome residuals.\n\n See also\n --------\n statsmodels.families.family.Family docstring and the `resid_anscombe`\n for the individual families for more information.\n \"\"\"\n raise NotImplementedError\n\n\nclass Poisson(Family):\n \"\"\"\n Poisson exponential family.\n\n Parameters\n ----------\n link : a link instance, optional\n The default link for the Poisson family is the log link. Available\n links are log, identity, and sqrt. See statsmodels.family.links for\n more information.\n\n Attributes\n ----------\n Poisson.link : a link instance\n The link function of the Poisson instance.\n Poisson.variance : varfuncs instance\n\n \"\"\"\n\n links = [L.log, L.identity, L.sqrt]\n variance = V.mu\n valid = [0, np.inf]\n safe_links = [\n L.Log,\n ]\n\n def __init__(self, link=L.log):\n self.variance = Poisson.variance\n self.link = link()\n\n def _clean(self, x):\n \"\"\"\n Helper function to trim the data so that is in (0,inf)\n\n \"\"\"\n return np.clip(x, FLOAT_EPS, np.inf)\n\n def resid_dev(self, endog, mu, scale=1.0):\n r\"\"\"Poisson deviance residual\n\n Parameters\n ----------\n endog : array-like\n Endogenous response variable\n mu : array-like\n Fitted mean response variable\n scale : float, optional\n An optional argument to divide the residuals by scale. The default\n is 1.\n\n Returns\n -------\n resid_dev : array\n Deviance residuals as defined below\n\n \"\"\"\n endog_mu = self._clean(endog / mu)\n return (\n np.sign(endog - mu)\n * np.sqrt(2 * (endog * np.log(endog_mu) - (endog - mu)))\n / scale\n )\n\n def deviance(self, endog, mu, freq_weights=1.0, scale=1.0):\n r\"\"\"\n Poisson deviance function\n\n Parameters\n ----------\n endog : array-like\n Endogenous response variable\n mu : array-like\n Fitted mean response variable\n freq_weights : array-like\n 1d array of frequency weights. The default is 1.\n scale : float, optional\n An optional scale argument. The default is 1.\n\n Returns\n -------\n deviance : float\n The deviance function at (endog,mu,freq_weights,scale) as defined\n below.\n\n \"\"\"\n endog_mu = self._clean(endog / mu)\n return 2 * np.sum(endog * freq_weights * np.log(endog_mu)) / scale\n\n def loglike(self, endog, mu, freq_weights=1.0, scale=1.0):\n r\"\"\"\n The log-likelihood function in terms of the fitted mean response.\n\n Parameters\n ----------\n endog : array-like\n Endogenous response variable\n mu : array-like\n Fitted mean response variable\n freq_weights : array-like\n 1d array of frequency weights. The default is 1.\n scale : float, optional\n The scale parameter, defaults to 1.\n\n Returns\n -------\n llf : float\n The value of the loglikelihood function evaluated at\n (endog,mu,freq_weights,scale) as defined below.\n\n \"\"\"\n loglike = np.sum(\n freq_weights * (endog * np.log(mu) - mu - special.gammaln(endog + 1))\n )\n return scale * loglike\n\n def resid_anscombe(self, endog, mu):\n r\"\"\"\n Anscombe residuals for the Poisson exponential family distribution\n\n Parameters\n ----------\n endog : array-like\n Endogenous response variable\n mu : array-like\n Fitted mean response variable\n\n Returns\n -------\n resid_anscombe : array\n The Anscome residuals for the Poisson family defined below\n\n \"\"\"\n return (3 / 2.0) * (endog ** (2 / 3.0) - mu ** (2 / 3.0)) / mu ** (1 / 6.0)\n\n\nclass QuasiPoisson(Family):\n \"\"\"\n QuasiPoisson exponential family.\n\n Parameters\n ----------\n link : a link instance, optional\n The default link for the Poisson family is the log link. Available\n links are log, identity, and sqrt. See statsmodels.family.links for\n more information.\n\n Attributes\n ----------\n Poisson.link : a link instance\n The link function of the Poisson instance.\n Poisson.variance : varfuncs instance\n\n \"\"\"\n\n links = [L.log, L.identity, L.sqrt]\n variance = V.mu\n valid = [0, np.inf]\n safe_links = [\n L.Log,\n ]\n\n def __init__(self, link=L.log):\n self.variance = Poisson.variance\n self.link = link()\n\n def _clean(self, x):\n \"\"\"\n Helper function to trim the data so that is in (0,inf)\n\n \"\"\"\n return np.clip(x, FLOAT_EPS, np.inf)\n\n def resid_dev(self, endog, mu, scale=1.0):\n r\"\"\"Poisson deviance residual\n\n Parameters\n ----------\n endog : array-like\n Endogenous response variable\n mu : array-like\n Fitted mean response variable\n scale : float, optional\n An optional argument to divide the residuals by scale. The default\n is 1.\n\n Returns\n -------\n resid_dev : array\n Deviance residuals as defined below\n\n \"\"\"\n endog_mu = self._clean(endog / mu)\n return (\n np.sign(endog - mu)\n * np.sqrt(2 * (endog * np.log(endog_mu) - (endog - mu)))\n / scale\n )\n\n def deviance(self, endog, mu, freq_weights=1.0, scale=1.0):\n r\"\"\"\n Poisson deviance function\n\n Parameters\n ----------\n endog : array-like\n Endogenous response variable\n mu : array-like\n Fitted mean response variable\n freq_weights : array-like\n 1d array of frequency weights. The default is 1.\n scale : float, optional\n An optional scale argument. The default is 1.\n\n Returns\n -------\n deviance : float\n The deviance function at (endog,mu,freq_weights,scale) as defined\n below.\n\n \"\"\"\n endog_mu = self._clean(endog / mu)\n return 2 * np.sum(endog * freq_weights * np.log(endog_mu)) / scale\n\n def loglike(self, endog, mu, freq_weights=1.0, scale=1.0): # noqa ARG002\n r\"\"\"\n The log-likelihood function in terms of the fitted mean response.\n\n Returns NaN for QuasiPoisson\n\n Returns\n -------\n None: not applicable for QuasiPoisson\n \"\"\"\n return np.nan\n\n def resid_anscombe(self, endog, mu):\n r\"\"\"\n Anscombe residuals for the Poisson exponential family distribution\n\n Parameters\n ----------\n endog : array-like\n Endogenous response variable\n mu : array-like\n Fitted mean response variable\n\n Returns\n -------\n resid_anscombe : array\n The Anscome residuals for the Poisson family defined below\n\n \"\"\"\n return (3 / 2.0) * (endog ** (2 / 3.0) - mu ** (2 / 3.0)) / mu ** (1 / 6.0)\n\n\nclass Gaussian(Family):\n \"\"\"\n Gaussian exponential family distribution.\n\n Parameters\n ----------\n link : a link instance, optional\n The default link for the Gaussian family is the identity link.\n Available links are log, identity, and inverse.\n See statsmodels.family.links for more information.\n\n Attributes\n ----------\n Gaussian.link : a link instance\n The link function of the Gaussian instance\n Gaussian.variance : varfunc instance\n \"\"\"\n\n links = [L.log, L.identity, L.inverse_power]\n variance = V.constant\n safe_links = links\n\n def __init__(self, link=L.identity):\n self.variance = Gaussian.variance\n self.link = link()\n\n def resid_dev(self, endog, mu, scale=1.0):\n \"\"\"\n Gaussian deviance residuals\n\n Parameters\n -----------\n endog : array-like\n Endogenous response variable\n mu : array-like\n Fitted mean response variable\n scale : float, optional\n An optional argument to divide the residuals by scale. The default\n is 1.\n\n Returns\n -------\n resid_dev : array\n Deviance residuals as defined below\n\n \"\"\"\n\n return (endog - mu) / np.sqrt(self.variance(mu)) / scale\n\n def deviance(self, endog, mu, freq_weights=1.0, scale=1.0):\n \"\"\"\n Gaussian deviance function\n\n Parameters\n ----------\n endog : array-like\n Endogenous response variable\n mu : array-like\n Fitted mean response variable\n freq_weights : array-like\n 1d array of frequency weights. The default is 1.\n scale : float, optional\n An optional scale argument. The default is 1.\n\n Returns\n -------\n deviance : float\n The deviance function at (endog,mu,freq_weights,scale)\n as defined below.\n\n \"\"\"\n return np.sum(freq_weights * (endog - mu) ** 2) / scale\n\n def loglike(self, endog, mu, freq_weights=1.0, scale=1.0):\n \"\"\"\n The log-likelihood in terms of the fitted mean response.\n\n Parameters\n ----------\n endog : array-like\n Endogenous response variable\n mu : array-like\n Fitted mean response variable\n freq_weights : array-like\n 1d array of frequency weights. The default is 1.\n scale : float, optional\n Scales the loglikelihood function. The default is 1.\n\n Returns\n -------\n llf : float\n The value of the loglikelihood function evaluated at\n (endog,mu,freq_weights,scale) as defined below.\n\n \"\"\"\n if isinstance(self.link, L.Power) and self.link.power == 1:\n # This is just the loglikelihood for classical OLS\n nobs2 = endog.shape[0] / 2.0\n SSR = np.sum((endog - self.fitted(mu)) ** 2, axis=0)\n llf = -np.log(SSR) * nobs2\n llf -= (1 + np.log(np.pi / nobs2)) * nobs2\n return llf\n else:\n return np.sum(\n freq_weights\n * (\n (endog * mu - mu**2 / 2) / scale\n - endog**2 / (2 * scale)\n - 0.5 * np.log(2 * np.pi * scale)\n )\n )\n\n def resid_anscombe(self, endog, mu):\n \"\"\"\n The Anscombe residuals for the Gaussian exponential family distribution\n\n Parameters\n ----------\n endog : array\n Endogenous response variable\n mu : array\n Fitted mean response variable\n\n Returns\n -------\n resid_anscombe : array\n The Anscombe residuals for the Gaussian family defined below\n\n \"\"\"\n return endog - mu\n\n\nclass Gamma(Family):\n \"\"\"\n Gamma exponential family distribution.\n\n Parameters\n ----------\n link : a link instance, optional\n The default link for the Gamma family is the inverse link.\n Available links are log, identity, and inverse.\n See statsmodels.family.links for more information.\n\n Attributes\n ----------\n Gamma.link : a link instance\n The link function of the Gamma instance\n Gamma.variance : varfunc instance\n \"\"\"\n\n links = [L.log, L.identity, L.inverse_power]\n variance = V.mu_squared\n safe_links = [\n L.Log,\n ]\n\n def __init__(self, link=L.inverse_power):\n self.variance = Gamma.variance\n self.link = link()\n\n def _clean(self, x):\n \"\"\"\n Helper function to trim the data so that is in (0,inf)\n\n \"\"\"\n return np.clip(x, FLOAT_EPS, np.inf)\n\n def deviance(self, endog, mu, freq_weights=1.0, scale=1.0): # noqa ARG002\n r\"\"\"\n Gamma deviance function\n\n Parameters\n -----------\n endog : array-like\n Endogenous response variable\n mu : array-like\n Fitted mean response variable\n freq_weights : array-like\n 1d array of frequency weights. The default is 1.\n scale : float, optional\n An optional scale argument. The default is 1.\n\n Returns\n -------\n deviance : float\n Deviance function as defined below\n\n \"\"\"\n endog_mu = self._clean(endog / mu)\n return 2 * np.sum(freq_weights * ((endog - mu) / mu - np.log(endog_mu)))\n\n def resid_dev(self, endog, mu, scale=1.0): # noqa ARG002\n r\"\"\"\n Gamma deviance residuals\n\n Parameters\n -----------\n endog : array-like\n Endogenous response variable\n mu : array-like\n Fitted mean response variable\n scale : float, optional\n An optional argument to divide the residuals by scale. The default\n is 1.\n\n Returns\n -------\n resid_dev : array\n Deviance residuals as defined below\n\n \"\"\"\n endog_mu = self._clean(endog / mu)\n return np.sign(endog - mu) * np.sqrt(\n -2 * (-(endog - mu) / mu + np.log(endog_mu))\n )\n\n def loglike(self, endog, mu, freq_weights=1.0, scale=1.0):\n r\"\"\"\n The log-likelihood function in terms of the fitted mean response.\n\n Parameters\n ----------\n endog : array-like\n Endogenous response variable\n mu : array-like\n Fitted mean response variable\n freq_weights : array-like\n 1d array of frequency weights. The default is 1.\n scale : float, optional\n The default is 1.\n\n Returns\n -------\n llf : float\n The value of the loglikelihood function evaluated at\n (endog,mu,freq_weights,scale) as defined below.\n\n \"\"\"\n return (\n -1.0\n / scale\n * np.sum(\n (\n endog / mu\n + np.log(mu)\n + (scale - 1) * np.log(endog)\n + np.log(scale)\n + scale * special.gammaln(1.0 / scale)\n )\n * freq_weights\n )\n )\n\n # in Stata scale is set to equal 1 for reporting llf\n # in R it's the dispersion, though there is a loss of precision vs.\n # our results due to an assumed difference in implementation\n\n def resid_anscombe(self, endog, mu):\n r\"\"\"\n The Anscombe residuals for Gamma exponential family distribution\n\n Parameters\n ----------\n endog : array\n Endogenous response variable\n mu : array\n Fitted mean response variable\n\n Returns\n -------\n resid_anscombe : array\n The Anscombe residuals for the Gamma family defined below\n\n \"\"\"\n return 3 * (endog ** (1 / 3.0) - mu ** (1 / 3.0)) / mu ** (1 / 3.0)\n\n\nclass Binomial(Family):\n \"\"\"\n Binomial exponential family distribution.\n\n Parameters\n ----------\n link : a link instance, optional\n The default link for the Binomial family is the logit link.\n Available links are logit, probit, cauchy, log, and cloglog.\n See statsmodels.family.links for more information.\n\n Attributes\n ----------\n Binomial.link : a link instance\n The link function of the Binomial instance\n Binomial.variance : varfunc instance\n\n \"\"\"\n\n links = [L.logit, L.probit, L.cauchy, L.log, L.cloglog, L.identity]\n variance = V.binary # this is not used below in an effort to include n\n\n # Other safe links, e.g. cloglog and probit are subclasses\n safe_links = [L.Logit, L.CDFLink]\n\n def __init__(self, link=L.logit): # , n=1.):\n # TODO: it *should* work for a constant n>1 actually, if freq_weights\n # is equal to n\n self.n = 1\n # overwritten by initialize if needed but always used to initialize\n # variance since endog is assumed/forced to be (0,1)\n self.variance = V.Binomial(n=self.n)\n self.link = link()\n\n def starting_mu(self, y):\n r\"\"\"\n The starting values for the IRLS algorithm for the Binomial family.\n A good choice for the binomial family is :math:`\\mu_0 = (Y_i + 0.5)/2`\n \"\"\"\n return (y + 0.5) / 2\n\n def initialize(self, endog, freq_weights): # noqa ARG002\n \"\"\"\n Initialize the response variable.\n\n Parameters\n ----------\n endog : array\n Endogenous response variable\n\n Returns\n --------\n If `endog` is binary, returns `endog`\n\n If `endog` is a 2d array, then the input is assumed to be in the format\n (successes, failures) and\n successes/(success + failures) is returned. And n is set to\n successes + failures.\n \"\"\"\n # if not np.all(np.asarray(freq_weights) == 1):\n # self.variance = V.Binomial(n=freq_weights)\n if endog.ndim > 1 and endog.shape[1] > 1:\n y = endog[:, 0]\n # overwrite self.freq_weights for deviance below\n self.n = endog.sum(1)\n return y * 1.0 / self.n, self.n\n else:\n return endog, np.ones(endog.shape[0])\n\n def deviance(self, endog, mu, freq_weights=1, scale=1.0, axis=None): # noqa ARG002\n r\"\"\"\n Deviance function for either Bernoulli or Binomial data.\n\n Parameters\n ----------\n endog : array-like\n Endogenous response variable (already transformed to a probability\n if appropriate).\n mu : array\n Fitted mean response variable\n freq_weights : array-like\n 1d array of frequency weights. The default is 1.\n scale : float, optional\n An optional scale argument. The default is 1.\n\n Returns\n --------\n deviance : float\n The deviance function as defined below\n\n \"\"\"\n if np.shape(self.n) == () and self.n == 1:\n one = np.equal(endog, 1)\n return -2 * np.sum(\n (one * np.log(mu + 1e-200) + (1 - one) * np.log(1 - mu + 1e-200))\n * freq_weights,\n axis=axis,\n )\n\n else:\n return 2 * np.sum(\n self.n\n * freq_weights\n * (\n endog * np.log(endog / mu + 1e-200)\n + (1 - endog) * np.log((1 - endog) / (1 - mu) + 1e-200)\n ),\n axis=axis,\n )\n\n def resid_dev(self, endog, mu, scale=1.0):\n r\"\"\"\n Binomial deviance residuals\n\n Parameters\n -----------\n endog : array-like\n Endogenous response variable\n mu : array-like\n Fitted mean response variable\n scale : float, optional\n An optional argument to divide the residuals by scale. The default\n is 1.\n\n Returns\n -------\n resid_dev : array\n Deviance residuals as defined below\n\n \"\"\"\n\n mu = self.link._clean(mu)\n if np.shape(self.n) == () and self.n == 1:\n one = np.equal(endog, 1)\n return (\n np.sign(endog - mu)\n * np.sqrt(-2 * np.log(one * mu + (1 - one) * (1 - mu)))\n / scale\n )\n else:\n return (\n np.sign(endog - mu)\n * np.sqrt(\n 2\n * self.n\n * (\n endog * np.log(endog / mu + 1e-200)\n + (1 - endog) * np.log((1 - endog) / (1 - mu) + 1e-200)\n )\n )\n / scale\n )\n\n def loglike(self, endog, mu, freq_weights=1, scale=1.0):\n r\"\"\"\n The log-likelihood function in terms of the fitted mean response.\n\n Parameters\n ----------\n endog : array-like\n Endogenous response variable\n mu : array-like\n Fitted mean response variable\n freq_weights : array-like\n 1d array of frequency weights. The default is 1.\n scale : float, optional\n Not used for the Binomial GLM.\n\n Returns\n -------\n llf : float\n The value of the loglikelihood function evaluated at\n (endog,mu,freq_weights,scale) as defined below.\n\n \"\"\"\n\n if np.shape(self.n) == () and self.n == 1:\n return scale * np.sum(\n (endog * np.log(mu / (1 - mu) + 1e-200) + np.log(1 - mu)) * freq_weights\n )\n else:\n y = endog * self.n # convert back to successes\n return scale * np.sum(\n (\n special.gammaln(self.n + 1)\n - special.gammaln(y + 1)\n - special.gammaln(self.n - y + 1)\n + y * np.log(mu / (1 - mu))\n + self.n * np.log(1 - mu)\n )\n * freq_weights\n )\n\n def resid_anscombe(self, endog, mu):\n \"\"\"\n The Anscombe residuals\n\n Parameters\n ----------\n endog : array-like\n Endogenous response variable\n mu : array-like\n Fitted mean response variable\n\n Returns\n -------\n resid_anscombe : array\n The Anscombe residuals as defined below.\n\n References\n ----------\n Anscombe, FJ. (1953) \"Contribution to the discussion of H. Hotelling's\n paper.\" Journal of the Royal Statistical Society B. 15, 229-30.\n\n Cox, DR and Snell, EJ. (1968) \"A General Definition of Residuals.\"\n Journal of the Royal Statistical Society B. 30, 248-75.\n\n \"\"\"\n cox_snell = lambda x: ( # noqa E731 - skip \"don't use lambda\"\n special.betainc(2 / 3.0, 2 / 3.0, x) * special.beta(2 / 3.0, 2 / 3.0)\n )\n return np.sqrt(self.n) * (\n (cox_snell(endog) - cox_snell(mu))\n / (mu ** (1 / 6.0) * (1 - mu) ** (1 / 6.0))\n )\n","repo_name":"pysal/spglm","sub_path":"spglm/family.py","file_name":"family.py","file_ext":"py","file_size_in_byte":28703,"program_lang":"python","lang":"en","doc_type":"code","stars":27,"dataset":"github-code","pt":"21"}
+{"seq_id":"15350781381","text":"import argparse\nimport json\nimport pylab as plt\n\ndef parse_args():\n parser = argparse.ArgumentParser(description=\"Takes experiment results and combines them in a plot\")\n parser.add_argument(\n \"json\",\n type=str,\n nargs=\"+\",\n help=\"One or more json experiments\",\n )\n return parser.parse_args()\n\ndef generate_plot(output_file, experiments):\n \"\"\" \n Plot the experiment results on a the 2 by 2 square\n containing the unit circle. Show how many points fell\n inside v.s. outside of the circle.\n \"\"\"\n\n # Split the results into inside v.s. outside\n within = [ e for e in experiments if e['x']**2 + e['y']**2 <= 1 ]\n outside = [ e for e in experiments if e['x']**2 + e['y']**2 > 1 ]\n\n\n # clear things for fresh plot\n ax = plt.gca()\n ax.cla() \n\n # Set plot bounds\n ax.set_xlim((-1, 1))\n ax.set_ylim((-1, 1))\n\n # plots: inside and outside the circle\n plt.scatter(\n [ e['x'] for e in within ],\n [ e['y'] for e in within ],\n c=\"red\"\n )\n\n plt.scatter(\n [ e['x'] for e in outside ],\n [ e['y'] for e in outside ],\n c=\"blue\"\n )\n\n # bounding circle\n c = plt.Circle( (0,0), 1, color='black', fill=False)\n ax.add_artist(c)\n\n # write to disk\n plt.savefig(output_file)\n\n\nif __name__ == '__main__':\n args = parse_args()\n output_file=\"out.png\"\n generate_plot(\n output_file=output_file, \n experiments=[ json.loads(s) for s in args.json ]\n )\n print(\"Done\")\n","repo_name":"Skin1215/aaw-contrib-jupyter-notebooks","sub_path":"mapreduce-pipeline/generate_plot/compile_plot.py","file_name":"compile_plot.py","file_ext":"py","file_size_in_byte":1517,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"21"}
+{"seq_id":"15445853967","text":"import multiprocessing\nimport asyncio\nimport sys\nimport logging\nimport typing\n\nimport psutil\n\nfrom . import config\n\nif typing.TYPE_CHECKING:\n from multiprocessing.connection import Connection\n from multiprocessing.managers import Namespace\n\nlogger = logging.getLogger(__name__)\n\nProcessType = typing.Callable[\n ['Connection', config.ConfigurationType, 'Namespace'],\n typing.Coroutine[typing.Any, None, None],\n]\n\nNO_CPU_PERCENT: float = 1000001.0\n\n\nclass Processes:\n \"\"\"\n This class is used to store the processes that are used by the tunnel.\n \"\"\"\n\n children: typing.List[\n typing.Tuple['Connection', multiprocessing.Process, psutil.Process]\n ]\n process: ProcessType\n cfg: config.ConfigurationType\n ns: 'Namespace'\n\n def __init__(\n self, process: ProcessType, cfg: config.ConfigurationType, ns: 'Namespace'\n ) -> None:\n self.children = []\n self.process = process # type: ignore\n self.cfg = cfg\n self.ns = ns\n\n for i in range(cfg.workers):\n self.add_child_pid()\n\n def add_child_pid(self):\n own_conn, child_conn = multiprocessing.Pipe()\n task = multiprocessing.Process(\n target=Processes.runner,\n args=(self.process, child_conn, self.cfg, self.ns),\n )\n task.start()\n logger.debug('ADD CHILD PID: %s', task.pid)\n self.children.append(\n (typing.cast('Connection', own_conn), task, psutil.Process(task.pid))\n )\n\n def best_child(self) -> 'Connection':\n best: typing.Tuple[float, 'Connection'] = (NO_CPU_PERCENT, self.children[0][0])\n missingProcesses: typing.List[int] = []\n for i, c in enumerate(self.children):\n try:\n if c[2].status() == 'zombie': # Bad kill!!\n raise psutil.ZombieProcess(c[2])\n percent = c[2].cpu_percent()\n except (psutil.ZombieProcess, psutil.NoSuchProcess) as e:\n # Process is missing...\n logger.warning('Missing process found: %s', e)\n try:\n c[0].close() # Close pipe to missing process\n except Exception:\n logger.debug('Could not close handle for %s', e.pid)\n try:\n c[1].kill()\n c[1].close()\n except Exception:\n logger.debug('Could not close process %s', e.pid)\n\n missingProcesses.append(i)\n continue\n\n logger.debug('PID %s has %s', c[2].pid, percent)\n\n if percent < best[0]:\n best = (percent, c[0])\n\n # If we have a missing process, try to add it back\n if missingProcesses:\n logger.debug('Regenerating missing processes: %s', len(missingProcesses))\n # Regenerate childs and recreate new proceeses for requests...\n # Remove missing processes\n self.children[:] = [\n child\n for i, child in enumerate(self.children)\n if i not in missingProcesses\n ]\n # Now add new children\n for (\n _\n ) in (\n missingProcesses\n ): # wee need to add as many as we removed, that is the len of missingProcesses\n self.add_child_pid()\n\n # Recheck best if all child were missing\n if best[0] == NO_CPU_PERCENT:\n return self.best_child()\n\n return best[1]\n\n def stop(self) -> None:\n # Try to stop running childs\n for i in self.children:\n try:\n i[2].kill()\n except Exception as e:\n logger.info('KILLING child %s: %s', i[2], e)\n\n @staticmethod\n def runner(\n proc: ProcessType,\n conn: 'Connection',\n cfg: config.ConfigurationType,\n ns: 'Namespace',\n ) -> None:\n if cfg.use_uvloop:\n try:\n import uvloop\n\n if sys.version_info >= (3, 11):\n with asyncio.Runner(loop_factory=uvloop.new_event_loop) as runner:\n runner.run(proc(conn, cfg, ns))\n else:\n uvloop.install()\n asyncio.run(proc(conn, cfg, ns))\n except ImportError:\n logger.warning('uvloop not found, using default asyncio')\n else:\n asyncio.run(proc(conn, cfg, ns))\n","repo_name":"Future998/openuds","sub_path":"tunnel-server/src/uds_tunnel/processes.py","file_name":"processes.py","file_ext":"py","file_size_in_byte":4481,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"21"}
+{"seq_id":"72985048692","text":"from flask import Flask, escape, request\nimport hashlib\nfrom netease import NetEaseService\nfrom nlp import NLP\nimport sqlite3\n\nservice = NetEaseService()\nnlp = NLP()\napp = Flask(__name__)\n\nsqlite_conn = sqlite3.connect(\"data.db\")\nsqlite_c = sqlite_conn.cursor()\n\n\n@app.route('/api/ping')\ndef hello():\n return {\"message\": \"pong\"}\n\n\n@app.route(\"/api/songs/\")\ndef get_song(song_id):\n return \"\"\n\n@app.route(\"/api/songs//lyrics\")\ndef get_lyrics(song_id):\n result = []\n if nlp.cache_exists(song_id):\n result = nlp.analyze_lyrics(None, song_id)\n else:\n lines = service.get_song_lyrics(song_id)\n print(lines)\n parsed_lines = nlp.parse_lrc(lines)\n result = nlp.analyze_lyrics(parsed_lines, song_id)\n return {\"lyrics\": result}\n\n@app.route(\"/api/playlists\")\ndef get_playlists():\n return {\"playlists\": service.get_my_playlists()}\n\n@app.route(\"/api/playlists/\")\ndef get_playlist(playlist_id):\n return {\"id\": playlist_id, \"songs\": service.get_playlist(playlist_id)}\n\n@app.route(\"/api/user/login\", methods = [\"POST\"])\ndef login():\n username = request.form.get(\"username\")\n password = request.form.get(\"password\")\n md5pass = hashlib.md5(password.encode(\"utf-8\")).hexdigest()\n resp = service.autologin(username, md5pass)\n if resp:\n return {\"message\": \"Login successful\"}, 202\n else:\n return {\"message\": \"Login failed\"}, 401\n\n@app.route(\"/api/user\")\ndef login_status():\n return service.login_status()\n\n@app.route(\"/api/today\")\ndef today_review():\n pass\n\n@app.route(\"/api/glossary\", methods = [\"GET\"])\ndef get_glossary(word):\n result = sqlite_c.execute(\"SELECT word, timestamp FROM glossary ORDER BY timestamp DESC\").fetch_all()\n \n resp = {\"glossary\": []}\n\n for row in result:\n word, timestamp = row\n resp[\"glossary\"].append({\n \"word\": word,\n \"timestamp\": timestamp\n })\n \n return resp\n\n@app.route(\"/api/glossary\", methods = [\"POST\"])\ndef add_to_glossary():\n word = request.form.get(\"word\")\n assert(isinstance(word, str))\n result = sqlite_c.execute(\"INSERT INTO glossary(word, timestamp) VALUES(?, ?)\", (word, int(time.time())))\n return {\"message\": \"success\"}, 202\n\n@app.route(\"/api/glossary/\", methods = [\"DELETE\"])\ndef remove_glossary(word):\n result = sqlite_c.execute(\"DELETE FROM glossary WHERE word=?\", (word, ))\n return {\"message\": \"success\"}, 202\n\n@app.route(\"/api/definition/\")\ndef get_definition(word):\n rank = nlp.freq_db.get(word, -1)\n quick_translation = nlp.translation_db.get(word, [])\n full_definition = nlp.full_dict_db.get(word, \"Not available\")\n \n count = sqlite_c.execute(\"SELECT COUNT(*) FROM glossary WHERE word=?\", (word, )).fetchone()[0]\n\n return {\n \"rank\": rank,\n \"translation\": quick_translation,\n \"definition\": full_definition,\n \"in_glossary\": (count == 1)\n }\n\nif __name__ == \"__main__\":\n app.run(host='0.0.0.0')","repo_name":"zhao-xuan/LinguoMusic","sub_path":"backend/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":3015,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"}
+{"seq_id":"73025883893","text":"try:\n from collections import OrderedDict # 2.7\nexcept ImportError:\n from sqlalchemy.util import OrderedDict\n\nimport logging\n\nfrom pylons import config\nfrom ckan import plugins as p\nfrom ckan.lib import helpers as h\nimport re\nimport simplejson as json\n\nREDACTED_REGEX = re.compile(\n r'^(\\[\\[REDACTED).*?(\\]\\])$'\n)\n\nREDACTED_TAGS_REGEX = re.compile(\n r'\\[\\[/?REDACTED(-EX\\sB\\d)?\\]\\]'\n)\n\nPARTIAL_REDACTION_REGEX = re.compile(\n r'\\[\\[REDACTED-EX B[\\d]\\]\\](.*?\\[\\[/REDACTED\\]\\])'\n)\n\nlog = logging.getLogger(__name__)\n\n\ndef get_reference_date(date_str):\n \"\"\"\n Gets a reference date extra created by the harvesters and formats it\n nicely for the UI.\n\n Examples:\n [{\"type\": \"creation\", \"value\": \"1977\"}, {\"type\": \"revision\", \"value\": \"1981-05-15\"}]\n [{\"type\": \"publication\", \"value\": \"1977\"}]\n [{\"type\": \"publication\", \"value\": \"NaN-NaN-NaN\"}]\n\n Results\n 1977 (creation), May 15, 1981 (revision)\n 1977 (publication)\n NaN-NaN-NaN (publication)\n \"\"\"\n try:\n out = []\n for date in h.json.loads(date_str):\n value = h.render_datetime(date['value']) or date['value']\n out.append('{0} ({1})'.format(value, date['type']))\n return ', '.join(out)\n except (ValueError, TypeError):\n return date_str\n\n\ndef get_responsible_party(value):\n \"\"\"\n Gets a responsible party extra created by the harvesters and formats it\n nicely for the UI.\n\n Examples:\n [{\"name\": \"Complex Systems Research Center\", \"roles\": [\"pointOfContact\"]}]\n [{\"name\": \"British Geological Survey\", \"roles\": [\"custodian\", \"pointOfContact\"]},\n {\"name\": \"Natural England\", \"roles\": [\"publisher\"]}]\n\n Results\n Complex Systems Research Center (pointOfContact)\n British Geological Survey (custodian, pointOfContact); Natural England (publisher)\n \"\"\"\n if not value:\n return None\n\n formatted = {\n 'resourceProvider': p.toolkit._('Resource Provider'),\n 'pointOfContact': p.toolkit._('Point of Contact'),\n 'principalInvestigator': p.toolkit._('Principal Investigator'),\n }\n\n try:\n out = []\n parties = h.json.loads(value)\n for party in parties:\n roles = [formatted[role] if role in formatted.keys() else p.toolkit._(role.capitalize()) for role in\n party['roles']]\n out.append('{0} ({1})'.format(party['name'], ', '.join(roles)))\n return '; '.join(out)\n except (ValueError, TypeError):\n pass\n return value\n\n\ndef get_common_map_config():\n \"\"\"\n Returns a dict with all configuration options related to the common\n base map (ie those starting with 'ckanext.spatial.common_map.')\n \"\"\"\n namespace = 'ckanext.spatial.common_map.'\n return dict([(k.replace(namespace, ''), v) for k, v in config.iteritems() if k.startswith(namespace)])\n\n\ndef strip_if_string(val):\n \"\"\"\n :param val: any\n :return: str|None\n \"\"\"\n if isinstance(val, (str, unicode)):\n val = val.strip()\n if '' == val:\n val = None\n return val\n\n\ndef get_export_map_json(map_filename):\n \"\"\"\n Reading json export map from file\n :param map_filename: str\n :return: obj\n \"\"\"\n import os\n\n map_path = os.path.join(os.path.dirname(__file__), 'export_map', map_filename)\n\n if not os.path.isfile(map_path):\n log.warn(\"Could not find %s ! Please create it. Use samples from same folder\", map_path)\n map_path = os.path.join(os.path.dirname(__file__), 'export_map', 'export.catalog.map.sample.json')\n\n with open(map_path, 'r') as export_map_json:\n json_export_map = json.load(export_map_json, object_pairs_hook=OrderedDict)\n\n return json_export_map\n\n\ndef detect_publisher(extras):\n \"\"\"\n Detect publisher by package extras\n :param extras: dict\n :return: str\n \"\"\"\n publisher = None\n\n if 'publisher' in extras and extras['publisher']:\n publisher = strip_if_string(extras['publisher'])\n\n for i in range(1, 6):\n key = 'publisher_' + str(i)\n if key in extras and extras[key] and strip_if_string(extras[key]):\n publisher = strip_if_string(extras[key])\n return publisher\n\n\ndef is_redacted(value):\n \"\"\"\n Checks if value is valid POD v1.1 [REDACTED-*]\n :param value: str\n :return: bool\n \"\"\"\n return isinstance(value, (str, unicode)) and REDACTED_REGEX.match(value)\n\n\ndef get_validator(schema_type=\"federal-v1.1\"):\n \"\"\"\n Get POD json validator object\n :param schema_type: str\n :return: obj\n \"\"\"\n import os\n from jsonschema import Draft4Validator, FormatChecker\n\n schema_path = os.path.join(os.path.dirname(__file__), 'pod_schema', schema_type, 'dataset.json')\n with open(schema_path, 'r') as schema:\n schema = json.loads(schema.read())\n return Draft4Validator(schema, format_checker=FormatChecker())\n\n\ndef uglify(key):\n \"\"\"\n lower string and remove spaces\n :param key: string\n :return: string\n \"\"\"\n if isinstance(key, (str, unicode)):\n return \"\".join(key.lower().split()).replace('_', '').replace('-', '')\n return key\n\n\ndef get_extra(package, key, default=None):\n \"\"\"\n Retrieves the value of an extras field.\n \"\"\"\n return packageExtraCache.get(package, key, default)\n\n\nclass PackageExtraCache:\n def __init__(self):\n self.pid = None\n self.extras = {}\n pass\n\n def store(self, package):\n import sys, os\n\n try:\n self.pid = package.get('id')\n\n current_extras = package.get('extras')\n new_extras = {}\n for extra in current_extras:\n if 'extras_rollup' == extra.get('key'):\n rolledup_extras = json.loads(extra.get('value'))\n for k, value in rolledup_extras.iteritems():\n if isinstance(value, (list, tuple)):\n value = \", \".join(map(unicode, value))\n new_extras[uglify(k)] = value\n else:\n value = extra.get('value')\n if isinstance(value, (list, tuple)):\n value = \", \".join(map(unicode, value))\n new_extras[uglify(extra['key'])] = value\n\n self.extras = new_extras\n except Exception as e:\n exc_type, exc_obj, exc_tb = sys.exc_info()\n filename = os.path.split(exc_tb.tb_frame.f_code.co_filename)[1]\n log.error(\"%s : %s : %s : %s\", exc_type, filename, exc_tb.tb_lineno, unicode(e))\n raise e\n\n def get(self, package, key, default=None):\n if self.pid != package.get('id'):\n self.store(package)\n return strip_if_string(self.extras.get(uglify(key), default))\n\n\npackageExtraCache = PackageExtraCache()\n","repo_name":"LiuFang816/SALSTM_py_data","sub_path":"python/GSA_ckanext-datajson/ckanext-datajson-master/ckanext/datajson/helpers.py","file_name":"helpers.py","file_ext":"py","file_size_in_byte":6902,"program_lang":"python","lang":"en","doc_type":"code","stars":9,"dataset":"github-code","pt":"21"}
+{"seq_id":"73202267891","text":"import argparse\nimport version\nimport settings\nimport sys\nimport init\n_LOGGER = settings.get_logger()\n\ndef setup_arguments_parser():\n parser = argparse.ArgumentParser(description='Valid arguments for dracoctl')\n actions = parser.add_subparsers(help='Valid arguments for dracoctl', dest='action')\n\n # Version parser\n version_help = \"Display dracoctl version\"\n actions.add_parser('version', help=version_help)\n\n # Init parser\n init_parser = actions.add_parser('init', help='Init the draco pipeline folder with default files')\n init_parser.add_argument('--dir', help='Directory to start the pipeline folder')\n return parser\n\n\ndef dispatch_version():\n version.show_version()\n\n\ndef dispatch_init(args):\n init.init_test_folder(args)\n\n\ndef main():\n parser = setup_arguments_parser()\n args = parser.parse_args()\n if args.action == 'version':\n dispatch_version()\n\n if args.action == 'init':\n dispatch_init(args)\n\nif __name__ == \"__main__\":\n sys.exit(main())\n","repo_name":"dinocloud/draco","sub_path":"cli/draco.py","file_name":"draco.py","file_ext":"py","file_size_in_byte":1011,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"}
+{"seq_id":"72645398452","text":"\"\"\"Author: Brandon Trabucco, Copyright 2019\"\"\"\r\n\r\n\r\nimport tensorflow as tf\r\nfrom mineral.relabelers.relabeler import Relabeler\r\n\r\n\r\nclass SubgoalTestingRelabeler(Relabeler):\r\n \r\n def __init__(\r\n self,\r\n *args,\r\n observation_selector=(lambda x: x[\"proprio_observation\"]),\r\n order=2,\r\n threshold=0.1,\r\n penalty=(-1.0),\r\n **kwargs\r\n ):\r\n Relabeler.__init__(self, *args, **kwargs)\r\n self.observation_selector = observation_selector\r\n self.order = order\r\n self.threshold = threshold\r\n self.penalty = penalty\r\n\r\n def relabel(\r\n self,\r\n observations,\r\n actions,\r\n rewards,\r\n terminals\r\n ):\r\n induced_observations = [\r\n self.observation_selector(x)\r\n for x in observations[\"induced_observations\"]]\r\n\r\n cumulative_distances = 0.0\r\n for lower_observation in induced_observations:\r\n error = lower_observation[:, 1:, ...] - actions\r\n cumulative_distances += tf.linalg.norm(\r\n tf.reshape(error, [tf.shape(error)[0], tf.shape(error)[1], -1]),\r\n ord=self.order, axis=(-1))\r\n\r\n test_passed_condition = cumulative_distances < self.threshold\r\n tested_rewards = tf.where(\r\n test_passed_condition,\r\n rewards,\r\n rewards + self.penalty)\r\n\r\n rewards = tf.where(\r\n self.get_relabeled_mask(rewards), tested_rewards, rewards)\r\n return (\r\n observations,\r\n actions,\r\n rewards,\r\n terminals)\r\n","repo_name":"brandontrabucco/mineral","sub_path":"mineral/relabelers/subgoal_testing_relabeler.py","file_name":"subgoal_testing_relabeler.py","file_ext":"py","file_size_in_byte":1609,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"21"}
+{"seq_id":"18271900807","text":"\"\"\"Module that contains Axis class (usable for both x and y axis)\n\"\"\"\nfrom typing import Optional\n\nimport numpy as np\n\nfrom shellplot.utils import (\n array_like,\n difference_round,\n is_datetime,\n numpy_1d,\n round_down,\n round_up,\n timedelta_round,\n to_datetime,\n to_numeric,\n tolerance_round,\n)\n\n\nclass Axis:\n \"\"\"Enables mapping from data to display / plot coordinates.\n\n We loosely follow the sklearn transformer api:\n\n >>> axis = Axis()\n >>> axis = x_axis.fit(x_data)\n >>> x_display = x_axis.transform(x_data)\n\n where `x_data` and `x_display` correspond to data and display coordinates,\n respectively.\n\n When calling `.fit`, we will automatically determine 'reasonable' axis\n limits and tick labels. Note that these can also be set by the user.\n \"\"\"\n\n def __init__(\n self,\n display_length: int = 20,\n label: Optional[str] = None,\n limits: Optional[array_like] = None,\n ticks: Optional[array_like] = None,\n ticklabels: Optional[array_like] = None,\n nticks: Optional[int] = None,\n ):\n \"\"\"Instantiate a new Axis.\n\n Parameters\n ----------\n display_length : int, optional\n Length of axis, in characters, default 20\n label : Optional[str], optional\n Axis label, default None\n limits : Optional[array_like], optional\n Axis limits, default None (auto-generated)\n ticklabels : Optional[array_like], optional\n Labels for axis ticks, default None (auto-generated, as ticks)\n ticks : Optional[array_like], optional\n Where the axis ticks should be, default None (auto-generated)\n nticks : Optional[int], optional\n Number of axis ticks, default None (auto-generated)\n \"\"\"\n self.display_max = display_length - 1\n self._is_datetime = False # whether or not we are a datetime axis\n self._scale = None\n\n self.label = label\n self.limits = limits\n self.nticks = nticks\n self.ticks = ticks\n self.ticklabels = ticklabels\n\n # -------------------------------------------------------------------------\n # Properties that can be set / modified by the user\n # -------------------------------------------------------------------------\n\n @property\n def label(self):\n return self._label\n\n @label.setter\n def label(self, label):\n self._label = label\n\n @property\n def limits(self):\n return self._limits\n\n @limits.setter\n def limits(self, limits):\n self._limits = limits\n if limits is not None: # new limits need to update scale and ticks\n self._limits = to_numeric(limits)\n self._set_scale()\n self._reset_ticks()\n\n @property\n def nticks(self):\n if self._nticks is None:\n self._nticks = self._auto_nticks()\n return self._nticks\n\n @nticks.setter\n def nticks(self, nticks):\n self._reset_ticks()\n self._nticks = nticks\n\n @property\n def ticks(self):\n if self._ticks is None:\n self._ticks = self._auto_ticks()\n return self._ticks\n\n @ticks.setter\n def ticks(self, ticks):\n self._reset_ticks()\n self._ticks = numpy_1d(ticks)\n\n @property\n def ticklabels(self):\n if self._ticklabels is None:\n self._ticklabels = self._auto_ticklabels()\n return self._ticklabels\n\n @ticklabels.setter\n def ticklabels(self, ticklabels):\n if ticklabels is not None:\n if len(ticklabels) != len(self.ticks):\n raise ValueError(\"Len of tick labels must equal len of ticks!\")\n if is_datetime(ticklabels):\n ticklabels = np.datetime_as_string(ticklabels)\n self._ticklabels = numpy_1d(ticklabels)\n\n # -------------------------------------------------------------------------\n # Public methods: fit, transform and generate ticks\n # -------------------------------------------------------------------------\n\n def fit(self, x):\n \"\"\"Fit axis to get conversion from data to plot scale\"\"\"\n self._is_datetime = is_datetime(x)\n x = to_numeric(x)\n\n if self.limits is None:\n self._limits = self._auto_limits(x)\n\n self._set_scale()\n return self\n\n def transform(self, x):\n \"\"\"Transform data to the plot coordinates\"\"\"\n x = to_numeric(x)\n x_scaled = self._scale * (x - self.limits[0]).astype(float)\n x_display = np.around(x_scaled).astype(int)\n return np.ma.masked_outside(x_display, 0, self.display_max)\n\n def fit_transform(self, x):\n \"\"\"Fit axis and transform data to the plot coordinates\"\"\"\n self = self.fit(x)\n return self.transform(x)\n\n def generate_display_ticks(self):\n \"\"\"Generate display tick locations and labels\"\"\"\n display_ticks = self.transform(self.ticks)\n within_display = np.logical_and(\n display_ticks >= 0, display_ticks <= self.display_max\n )\n display_labels = self.ticklabels[within_display]\n display_ticks = display_ticks[within_display]\n\n return zip(display_ticks, display_labels)\n\n # -------------------------------------------------------------------------\n # Private methods: Auto scaling & ticks\n # -------------------------------------------------------------------------\n\n def _set_scale(self):\n self._scale = self.display_max / float(self.limits[1] - self.limits[0])\n\n def _auto_limits(self, x, margin=0.25):\n \"\"\"Automatically find good axis limits\"\"\"\n x_max, x_min = x.max(), x.min()\n\n max_difference = margin * (x_max - x_min)\n ax_min = difference_round(x_min, round_down, max_difference)\n ax_max = difference_round(x_max, round_up, max_difference)\n\n return ax_min, ax_max\n\n def _auto_nticks(self):\n \"\"\"Automatically find number of ticks that fit display\"\"\"\n max_ticks = int(1.5 * self.display_max ** 0.3) + 1\n ticks = np.arange(max_ticks, max_ticks - 2, -1)\n remainders = np.remainder(self.display_max, ticks)\n return ticks[np.argmin(remainders)] + 1\n\n def _auto_ticks(self):\n \"\"\"Automatically find good axis ticks\"\"\"\n if self.limits is None:\n raise ValueError(\"Please fit axis or set limits first!\")\n elif not self._is_datetime:\n return self._auto_numeric_ticks()\n else:\n return self._auto_datetime_ticks()\n\n def _auto_numeric_ticks(self, tol=0.05):\n step, precision = tolerance_round(\n (self.limits[1] - self.limits[0]) / (self.nticks - 1),\n tol=tol,\n )\n return np.around(\n np.arange(self.limits[0], self.limits[1] + step, step), precision\n )[: self.nticks]\n\n def _auto_datetime_ticks(self):\n axis_td = to_datetime(np.array(self.limits, dtype=\"timedelta64[ns]\"))\n limits_delta = axis_td[1] - axis_td[0]\n unit = timedelta_round(limits_delta)\n n_units = limits_delta / np.timedelta64(1, unit)\n td_step = np.timedelta64(int(n_units / (self.nticks - 1)), unit)\n\n return np.arange(\n np.datetime64(axis_td[0], unit),\n np.datetime64(axis_td[1], unit) + td_step,\n td_step,\n )[: self.nticks]\n\n def _auto_ticklabels(self):\n if self._is_datetime:\n return np.datetime_as_string(self.ticks)\n else:\n return self.ticks\n\n def _reset_ticks(self):\n self._ticks = None\n self._ticklabels = None\n","repo_name":"CDonnerer/shellplot","sub_path":"src/shellplot/axis.py","file_name":"axis.py","file_ext":"py","file_size_in_byte":7603,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"21"}
+{"seq_id":"6810991627","text":"from decimal import Decimal as d\nfrom time import strftime, gmtime\nfrom Order import *\n\n\nclass Usuario: # de aca se heredan 3 tipos de usuarios\n def __init__(self, username, nombre, apellido, nacimiento):\n self.username = username\n self.nombre = nombre\n self.apellido = apellido\n self._nacimiento = nacimiento # YYYY-MM-DD\n self.mercados = []\n\n @property\n def nacimiento(self):\n return self._nacimiento\n\n @nacimiento.setter\n def nacimiento(self, value):\n # se usa para no ingresar fechas afuera de 1900 o 2017\n try:\n año = value[0:4]\n mes = value[5:7]\n dia = value[8:]\n int(mes)\n int(dia)\n año_actual = strftime(\"%Y\", gmtime())\n mes_actual = strftime(\"%m\", gmtime())\n dia_actual = strftime(\"%d\", gmtime())\n if int(año) >= 1900 and int(año) < int(año_actual):\n self._nacimiento = value\n elif int(año) == int(año_actual):\n if int(mes) < int(mes_actual):\n self._nacimiento = value\n elif int(mes) == int(mes_actual):\n if int(dia) <= int(dia_actual):\n self._nacimiento = value\n else:\n print(\"La fecha debe estar entre 1900 y 2017\")\n\n if int(mes) > 12 or int(mes) < 1:\n print(\"Mes no valido\")\n self._nacimiento = \"\"\n if int(dia) > 31 or int(dia) < 1:\n print(\"Dia no valido\")\n self._nacimiento = \"\"\n except:\n print(\"Formato no valido\")\n self._nacimiento = \"\"\n\n def agregar_mercado(self, mercado):\n self.mercados.append(mercado)\n if mercado.divisa_compraventa not in self.balance_currencies.keys():\n self.balance_currencies.update({mercado.divisa_compraventa :\n d(\"50000\")})\n # se agregan los 50.000\n else:\n self.balance_currencies[mercado.divisa_compraventa] += d(\"50000\")\n if mercado.moneda_de_cambio not in self.balance_currencies.keys():\n self.balance_currencies.update({mercado.moneda_de_cambio :\n d(\"50000\")})\n else:\n self.balance_currencies[mercado.moneda_de_cambio] += d(\"50000\")\n\n def determinar_edad(self):\n año = self.nacimiento[0:4]\n mes = self.nacimiento[5:7]\n dia = self.nacimiento[8:]\n año_actual = strftime(\"%Y\", gmtime())\n mes_actual = strftime(\"%m\", gmtime())\n dia_actual = strftime(\"%d\", gmtime())\n diferencia = int(año_actual) - int(año)\n if int(mes_actual) < int(mes):\n return diferencia - 1\n elif int(mes_actual) > int(mes):\n return diferencia\n else:\n if int(dia_actual) < int(dia):\n return diferencia - 1\n else:\n return diferencia\n\n def __str__(self):\n imprimir = \"Usuario: \" + self.username + \". Nombre: \" + self.nombre \\\n + \". Apellido: \" + self.apellido\n return imprimir\n\n\nclass Underaged(Usuario):\n def __init__(self, username, nombre, apellido, nacimiento):\n Usuario.__init__(self, username, nombre, apellido, nacimiento)\n\n def agregar_mercado(self, mercado):\n # solo agrega el mercado, no se le agrega nada al saldo porque no tiene\n self.mercados.append(mercado)\n\n\nclass Trader(Usuario):\n def __init__(self, username, nombre, apellido, nacimiento):\n Usuario.__init__(self, username, nombre, apellido, nacimiento)\n self.balance_currencies = {\"DCC\": d(\"300000\")}\n self.orders_realizadas = [] # lista de ids\n\n def generar_balance(self): # agregar al diccionario de balances a\n # partir de los mercados registrados\n for mercado in self.mercados:\n currency1 = mercado.ticker[0:3]\n currency2 = mercado.ticker[3:]\n if currency1 not in self.balance_currencies.keys():\n self.balance_currencies.update({currency1: d(\"0\")})\n if currency2 not in self.balance_currencies.keys():\n self.balance_currencies.update({currency2: d(\"0\")})\n\n def ingresar_ask(self, usuario, mercado, divisa_venta, moneda_de_cambio):\n tiempo_actual = strftime(\"%Y-%m-%d\", gmtime())\n nuevo_ask = Ask(usuario, mercado, divisa_venta, moneda_de_cambio,\n tiempo_actual)\n mercado.orders.append(nuevo_ask)\n mercado.asks.append(nuevo_ask)\n mercado.asks_activos.append(nuevo_ask)\n if mercado.moneda_de_cambio not in usuario.balance_currencies.keys():\n usuario.balance_currencies.update({mercado.moneda_de_cambio :\n d(\"0\")})\n return nuevo_ask\n\n def ingresar_bid(self, usuario, mercado, divisa_compra, moneda_de_cambio):\n tiempo_actual = strftime(\"%Y-%m-%d\", gmtime())\n nuevo_bid = Bid(usuario, mercado, divisa_compra, moneda_de_cambio,\n tiempo_actual)\n mercado.orders.append(nuevo_bid)\n mercado.bids.append(nuevo_bid)\n mercado.bids_activos.append(nuevo_bid)\n if mercado.divisa_compraventa not in usuario.balance_currencies.keys():\n usuario.balance_currencies.update({mercado.divisa_compraventa:\n d(\"0\")})\n return nuevo_bid\n\n def transferir_dinero(self, cantidad, usuario_destino, mercado):\n divisa = mercado.ticker[0:3]\n if d(self.balance_currencies[divisa]) - d(cantidad) < 0:\n print(\"No tienes dinero suficiente para realizar la transferencia.\")\n return\n self.balance_currencies[divisa] = d(self.balance_currencies[divisa]) -\\\n d(str(cantidad))\n if divisa not in usuario_destino.balance_currencies.keys():\n usuario_destino.balance_currencies.update({divisa: d(\"0\")})\n\n usuario_destino.balance_currencies[divisa] = d(usuario_destino.\n balance_currencies[\n divisa]) + \\\n d(cantidad) * \\\n d(\"0.95\")\n mercado.comisiones[divisa] = d(mercado.comisiones[divisa]) + \\\n d(cantidad) * d(\"0.05\")\n\n\nclass Investor(Trader):\n def __init__(self, username, nombre, apellido, nacimiento):\n Trader.__init__(self, username, nombre, apellido, nacimiento)\n\n def desplegar_balance_historico(self, lista_orders):\n for order in lista_orders:\n if order.usuario.username == self.username:\n if order.ejecutada:\n if isinstance(order, Ask):\n perdida = d(order.divisa_venta)\n ganancia = (d(order.divisa_venta) *\n d(order.moneda_de_cambio) *\n order.mercado.determinar_tasa(self))\n print(\"Con la order\", order.id, \"el dia\",\n order.match_time, \"ganaste\", str(ganancia),\n order.mercado.moneda_de_cambio, \"y perdiste\",\n str(perdida), order.mercado.divisa_compraventa)\n elif isinstance(order, Bid):\n ganancia = d(order.divisa_compra) * \\\n order.mercado.determinar_tasa(self)\n perdida = d(order.divisa_compra) *\\\n d(order.moneda_de_cambio)\n print(\"Con la order\", order.id, \"el dia\",\n order.match_time, \"ganaste\", str(ganancia),\n order.mercado.moneda_de_cambio, \"y perdiste\",\n str(perdida), order.mercado.divisa_compraventa)\n\n\ndef identificarse(lista_usuarios):\n while True: # manejo de errores\n registro = input(\"Ingrese\\n1 si ya tiene una cuenta registrada\\n2 \"\n \"si quiere registrar una nueva cuenta\\n\")\n if registro != \"1\" and registro != \"2\":\n print(\"Opcion invalida\")\n else:\n break\n if registro == str(2):\n usuario_actual = agregar_usuario(lista_usuarios)\n return usuario_actual\n elif registro == str(1):\n valido = False\n while not valido:\n usuario_ingreso = input(\"Ingrese su nombre de usuario registrado \"\n \"(0 para registrarse): \")\n if usuario_ingreso == \"0\":\n usuario_actual = identificarse(lista_usuarios)\n return usuario_actual\n for usuario in lista_usuarios:\n if usuario.username == usuario_ingreso:\n valido = True\n usuario_actual = usuario\n if not valido:\n print(\"El usuario no está registrado.\")\n print(\"\\nSu saldo es el siguiente:\")\n if isinstance(usuario_actual, Trader):\n for symbol, saldo in usuario_actual.balance_currencies.items():\n print(symbol, saldo)\n return usuario_actual\n\n\ndef agregar_usuario(lista_usuarios):\n existe = False\n nuevo_username = input(\"Ingresa tu nombre de usuario: \")\n for usuario in lista_usuarios:\n if usuario.username == nuevo_username:\n existe = True\n print(\"El nombre de usuario ya existe. Elige otro.\")\n nuevo_usuario = agregar_usuario(lista_usuarios)\n return nuevo_usuario\n nuevo_nombre = input(\"Ingresa tu nombre: \")\n nuevo_apellido = input(\"Ingresa tu apellido: \")\n nuevo_usuario = Usuario(nuevo_username, nuevo_nombre, nuevo_apellido, \"\")\n while nuevo_usuario.nacimiento == \"\":\n nuevo_nacimiento = input(\"Ingresa tu fecha de nacimiento \"\n \"(Formato 1990-10-24): \")\n nuevo_usuario.nacimiento = nuevo_nacimiento\n if nuevo_usuario.determinar_edad() < 18:\n del nuevo_usuario\n nuevo_usuario = Underaged(nuevo_username, nuevo_nombre, nuevo_apellido,\n nuevo_nacimiento)\n else:\n del nuevo_usuario\n nuevo_usuario = Trader(nuevo_username, nuevo_nombre, nuevo_apellido,\n nuevo_nacimiento)\n nuevo_usuario.balance_currencies[\"DCC\"] = d(\"100000\")\n lista_usuarios.append(nuevo_usuario)\n return nuevo_usuario\n","repo_name":"mesantamaria/Advanced-programming-Homeworks","sub_path":"Tareas/T01/User.py","file_name":"User.py","file_ext":"py","file_size_in_byte":10700,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"}
+{"seq_id":"70947390772","text":"from industry import IndustryPrimaryOrganic, TileLocationChecks\n\nindustry = IndustryPrimaryOrganic(id='sheep_farm',\n prod_cargo_types=['LVST', 'WOOL'],\n prob_in_game='4',\n prob_random='11',\n prod_multiplier='[12, 14]',\n map_colour='168',\n location_checks=dict(cluster=[72, 4]),\n spec_flags='bitmask(IND_FLAG_PLANT_FIELDS_PERIODICALLY, IND_FLAG_PLANT_FIELDS_WHEN_BUILT)',\n prospect_chance='0.75',\n name='string(STR_IND_SHEEPFARM)',\n nearby_station_name='string(STR_STATION_SHEEP_FOLD)',\n fund_cost_multiplier='45')\n\nindustry.economy_variations['FIRS'].enabled = True\n\nindustry.add_tile(id='sheep_farm_tile_1',\n location_checks=TileLocationChecks(disallow_coast=True,\n disallow_industry_adjacent=True))\n\nspriteset_ground = industry.add_spriteset(\n type='empty'\n)\nspriteset_ground_overlay = industry.add_spriteset(\n type='empty'\n)\nspriteset_1 = industry.add_spriteset(\n sprites=[(10, 10, 64, 52, -31, -21)],\n)\nspriteset_2 = industry.add_spriteset(\n sprites=[(80, 10, 64, 52, -31, -19)],\n)\nspriteset_3 = industry.add_spriteset(\n sprites=[(150, 10, 64, 52, -31, -21)],\n)\nspriteset_4 = industry.add_spriteset(\n sprites=[(220, 10, 64, 52, -31, -21)],\n)\nspriteset_5 = industry.add_spriteset(\n sprites=[(290, 10, 64, 52, -31, -21)],\n)\n\nindustry.add_spritelayout(\n id='sheep_farm_spritelayout_1',\n ground_sprite=spriteset_ground,\n ground_overlay=spriteset_ground_overlay,\n building_sprites=[spriteset_1],\n terrain_aware_ground=True\n)\nindustry.add_spritelayout(\n id='sheep_farm_spritelayout_2',\n ground_sprite=spriteset_ground,\n ground_overlay=spriteset_ground_overlay,\n building_sprites=[spriteset_2],\n terrain_aware_ground=True\n)\nindustry.add_spritelayout(\n id='sheep_farm_spritelayout_3',\n ground_sprite=spriteset_ground,\n ground_overlay=spriteset_ground_overlay,\n building_sprites=[spriteset_3],\n terrain_aware_ground=True\n)\nindustry.add_spritelayout(\n id='sheep_farm_spritelayout_4',\n ground_sprite=spriteset_ground,\n ground_overlay=spriteset_ground_overlay,\n building_sprites=[spriteset_4],\n terrain_aware_ground=True\n)\nindustry.add_spritelayout(\n id='sheep_farm_spritelayout_5',\n ground_sprite=spriteset_ground,\n ground_overlay=spriteset_ground_overlay,\n building_sprites=[spriteset_5],\n terrain_aware_ground=True\n)\n\nindustry.add_industry_layout(\n id='sheep_farm_industry_layout_1',\n layout=[(0, 0, 'sheep_farm_tile_1', 'sheep_farm_spritelayout_3'),\n (1, 0, 'sheep_farm_tile_1', 'sheep_farm_spritelayout_2'),\n (1, 2, 'sheep_farm_tile_1', 'sheep_farm_spritelayout_4'),\n (3, 0, 'sheep_farm_tile_1', 'sheep_farm_spritelayout_1'),\n (3, 1, 'sheep_farm_tile_1', 'sheep_farm_spritelayout_5'),\n ]\n)\nindustry.add_industry_layout(\n id='sheep_farm_industry_layout_2',\n layout=[(0, 0, 'sheep_farm_tile_1', 'sheep_farm_spritelayout_2'),\n (0, 1, 'sheep_farm_tile_1', 'sheep_farm_spritelayout_1'),\n (0, 2, 'sheep_farm_tile_1', 'sheep_farm_spritelayout_4'),\n (2, 0, 'sheep_farm_tile_1', 'sheep_farm_spritelayout_3'),\n (2, 2, 'sheep_farm_tile_1', 'sheep_farm_spritelayout_5'),\n ]\n)\n","repo_name":"EmperorJake/XIS","sub_path":"src/industries/sheep_farm.py","file_name":"sheep_farm.py","file_ext":"py","file_size_in_byte":3611,"program_lang":"python","lang":"en","doc_type":"code","stars":13,"dataset":"github-code","pt":"21"}
+{"seq_id":"33789913625","text":"def make_full_name(first, last):\n \"\"\"\n This function takes two arguments: first and last, which represent a person's first name and last name respectively\n\n Returns a single string ' '\n \"\"\"\n full_name = first + ' ' + last\n return full_name\n\n\nfull = make_full_name('Tony', 'Macaroni')\nprint(full)\n","repo_name":"MassStreetDataSchool/survival-python","sub_path":"06 Functions/return_values_1.py","file_name":"return_values_1.py","file_ext":"py","file_size_in_byte":345,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"21"}
+{"seq_id":"72872706612","text":"import unittest\nimport numpy as np\nimport synthetics as syn\nimport attributes as att\n\n\n\ndef suite():\n suite = unittest.TestSuite()\n suite.addTest(SimpleTests('test_asdec'))\n suite.addTest(SimpleTests('test_duration'))\n suite.addTest(SimpleTests('test_rapps'))\n suite.addTest(HigherStatsTests('test_signal_kurtosis'))\n suite.addTest(HigherStatsTests('test_signal_skew'))\n suite.addTest(HigherStatsTests('test_KurtoF'))\n suite.addTest(AutoCorTests('test_peaks'))\n\n return suite\n \n \nclass SimpleTests(unittest.TestCase):\n \n def setUp(self):\n self.npts = 3000\n self.dt = 0.01\n self.poly_coefs = [0.05, -0.75, 0.1, 1.0]\n self.tr = syn.gen_sweep_poly(self.dt, self.npts, self.poly_coefs)\n \n def test_asdec(self):\n imax_fraction = 0.2\n max_amp = 300\n tr, modulation = syn.modulate_trace_triangle(self.tr, imax_fraction, \n max_amp)\n AsDec = att.get_AsDec(tr)\n self.assertAlmostEqual(AsDec, imax_fraction / (1-imax_fraction), 2)\n\n def test_duration(self):\n Duration = att.get_Duration(self.tr)\n self.assertAlmostEqual(Duration, (self.npts-1) * self.dt)\n\n def test_rapps(self):\n imax_fraction = 0.5\n max_amp = 300\n tr, modulation = syn.modulate_trace_triangle(self.tr, imax_fraction, \n max_amp)\n RappMaxMean, RappMaxMedian, RappMaxStd = att.get_RappStuff(tr)\n self.assertTrue(RappMaxMean > 2)\n self.assertAlmostEqual(RappMaxMedian, RappMaxMean, 1)\n\n\nclass HigherStatsTests(unittest.TestCase):\n\n def setUp(self):\n self.npts = 300000\n self.dt = 0.01\n self.amp = 100.0\n self.tr = syn.gen_gaussian_noise(self.dt, self.npts, self.amp)\n self.KurtoEnv, self.KurtoSig, self.SkewnessEnv, self.SkewnessSig = \\\n att.get_KurtoSkew(self.tr)\n\n def test_signal_kurtosis(self):\n self.assertAlmostEqual(self.KurtoSig, 3.0, 1)\n\n def test_signal_skew(self):\n self.assertAlmostEqual(self.SkewnessSig, 0.0, 1)\n\n def test_KurtoF(self):\n ES, KurtoF = att.get_freq_band_stuff(self.tr)\n self.assertAlmostEqual(np.mean(KurtoF), 3.0, 1)\n\nclass AutoCorTests(unittest.TestCase):\n\n def setUp(self):\n self.npts = 3000\n self.dt = 0.01\n self.sig_npts = 100\n self.sig_amp = 5\n self.n_sig = 3\n self.tr = syn.gen_repeat_signal(self.dt, self.npts, self.sig_npts,\n self.sig_amp, self.n_sig)\n self.CorrPeakNumber, self.INTRATIO = att.get_CorrStuff(self.tr)\n\n def test_peaks(self):\n self.assertEqual(self.CorrPeakNumber, 3)\n\nif __name__ == '__main__':\n\n unittest.TextTestRunner(verbosity=2).run(suite())\n","repo_name":"hibertclement/eqdiscrim","sub_path":"eqdiscrim/test_attributes.py","file_name":"test_attributes.py","file_ext":"py","file_size_in_byte":2822,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"}
+{"seq_id":"35663339825","text":"# 숫자카드.py\n\nimport sys\nsys.stdin = open(\"구간합_input.txt\", \"r\")\n\nT = int(input())\n\nfor test_case in range(1, T + 1):\n N, M = map(int, input().split())\n arr = list(map(int, input().split()))\n\n min = 987654321\n max = -987654321\n for i in range(N-M+1):\n sum = 0\n for j in range(M):\n sum += arr[i+j]\n if sum > max : max = sum\n if sum < min : min = sum\n\n print(\"#{0} {1}\".format(test_case, max - min))","repo_name":"gogumasitda/TIL","sub_path":"algorithm/01.15/day2/구간합.py","file_name":"구간합.py","file_ext":"py","file_size_in_byte":464,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"21"}
+{"seq_id":"36363237560","text":"############### Blackjack Project #####################\n\nimport random\nimport os\nfrom art import logo\n\ndef clear(): os.system('cls') #on Windows System\nclear()\n\ndef draw_card():\n cards = [11, 2, 3, 4, 5, 6, 7, 8, 9, 10, 10, 10, 10] \n pick = random.choice(cards)\n return pick\n\ndef calculate_score(cards):\n if sum(cards) == 21 and len(cards) == 2:\n return 0 \n\n if 11 in cards and sum(cards) > 21:\n cards.remove(11)\n cards.append(1)\n return sum(cards)\n\ndef compare(user_score, computer_score):\n if user_score > 21 and computer_score > 21:\n return \"You both lose. Game over!\"\n \n if user_score == computer_score:\n return \"It's a draw.\"\n elif computer_score == 0:\n return \"Computer has BlackJack! You lose!\"\n elif user_score == 0:\n return \"You have BlackJack! You win!\"\n elif computer_score > 21:\n return \"Computer Bust! You Win!\"\n elif user_score > 21:\n return \"Bust! You lose!\"\n elif user_score > computer_score:\n return \"You Win!\"\n else:\n return \"You lose.\"\n\ndef game_start():\n\n print(logo)\n \n user_cards = []\n computer_cards = []\n is_game_over = False\n \n for space in range(2):\n user_cards.append(draw_card())\n computer_cards.append(draw_card())\n \n while not is_game_over:\n user_score = calculate_score(user_cards)\n computer_score = calculate_score(computer_cards)\n print(f\" Your cards are {user_cards}, Your score is {user_score}.\")\n print(f\" Computer draws: {computer_cards[0]}\")\n \n if user_score == 0 or computer_score == 0 or user_score > 21:\n is_game_over = True\n else:\n user_should_deal = input(\"Would you like to draw another card. Type 'y' or 'n': \")\n if user_should_deal == \"y\":\n user_cards.append(draw_card())\n else:\n is_game_over = True\n \n while computer_score != 0 and computer_score <17:\n computer_cards.append(draw_card())\n computer_score = calculate_score(computer_cards)\n print(f\" Your final hand is: {user_cards}, Your final score is: {user_score}\")\n print(f\" Computers final hand is: {computer_cards}, Computer final score is: {computer_score}\")\n print(compare(user_score, computer_score))\n \n\nwhile input(\"Would you like to play blackjack? Type 'y' or 'n': \") == \"y\":\n clear()\n game_start()\n\n\n","repo_name":"MorEnergy/BlackJack-Game","sub_path":"BlackJack Game.py","file_name":"BlackJack Game.py","file_ext":"py","file_size_in_byte":2255,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"}
+{"seq_id":"30494633940","text":"#FIGlet, named after Frank, Ian, and Glen’s letters, is a program from the early 1990s for making large letters\r\n# out of ordinary text, a form of ASCII art:\r\n\r\n#Among the fonts supported by FIGlet are those at figlet.org/examples.html.\r\n#FIGlet has since been ported to Python as a module called pyfiglet.\r\n#In a file called figlet.py, implement a program that:\r\n\r\n#Expects zero or two command-line arguments:\r\n#Zero if the user would like to output text in a random font.\r\n#Two if the user would like to output text in a specific font, in which case the first of the two should be -f or --font,\r\n# and the second of the two should be the name of the font.\r\n#Prompts the user for a str of text.\r\n#Outputs that text in the desired font.\r\n#If the user provides two command-line arguments and the first is not -f or --font or the second is not the name of a font,\r\n# the program should exit via sys.exit with an error message.\r\n\r\nimport random\r\nimport sys\r\nfrom pyfiglet import Figlet\r\n\r\nfiglet = Figlet()\r\nf = figlet.getFonts() # assign f a list of available fonts\r\n\r\nif sys.argv[2] not in f:\r\n sys.exit(\"Incorrect command-line arguments\")\r\n\r\nelif len(sys.argv) == 1: # ==1 beacuse first argument, sys.argv[0] will be figlet.py so its supposed to be only 1\r\n r = random.choice(f) \r\n figlet.setFont(font=r) # set a random font\r\nelif sys.argv[1] == \"--font\" or sys.argv[1] == \"-f\":\r\n figlet.setFont(font=sys.argv[2]) # the third argument aka sys.argv[2] is the fonts name\r\nelse:\r\n sys.exit(\"Incorrect command-line arguments\")\r\nstr = input(\"Input: \")\r\nprint(\"Output:\",figlet.renderText(str)) #output str in the random chosen font\r\n\r\n\r\n\r\n\r\n#if the user provides two command-line arguments and the first is not -f or --font or the second is not the name of a font","repo_name":"rodrigobivarazevedo/Python1","sub_path":"libraries/fiflet.py","file_name":"fiflet.py","file_ext":"py","file_size_in_byte":1855,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"}
+{"seq_id":"25876807702","text":"\n\nimport torch\nfrom torch import Tensor\n\n\nclass NeuralSort (torch.nn.Module):\n def __init__(self, tau=1.0, hard=False):\n super(NeuralSort, self).__init__()\n self.hard = hard\n self.tau = tau\n\n def forward(self, scores: Tensor):\n \"\"\"\n scores: elements to be sorted. Typical shape: batch_size x n x 1\n \"\"\"\n scores = scores.unsqueeze(-1)\n bsize = scores.size()[0]\n dim = scores.size()[1]\n one = torch.cuda.FloatTensor(dim, 1).fill_(1)\n\n A_scores = torch.abs(scores - scores.permute(0, 2, 1))\n B = torch.matmul(A_scores, torch.matmul(\n one, torch.transpose(one, 0, 1)))\n scaling = (dim + 1 - 2 * (torch.arange(dim) + 1)\n ).type(torch.cuda.FloatTensor)\n C = torch.matmul(scores, scaling.unsqueeze(0))\n\n P_max = (C-B).permute(0, 2, 1)\n sm = torch.nn.Softmax(-1)\n P_hat = sm(P_max / self.tau)\n\n if self.hard:\n P = torch.zeros_like(P_hat, device='cuda')\n b_idx = torch.arange(bsize).repeat([1, dim]).view(dim, bsize).transpose(\n dim0=1, dim1=0).flatten().type(torch.cuda.LongTensor)\n r_idx = torch.arange(dim).repeat(\n [bsize, 1]).flatten().type(torch.cuda.LongTensor)\n c_idx = torch.argmax(P_hat, dim=-1).flatten() # this is on cuda\n brc_idx = torch.stack((b_idx, r_idx, c_idx))\n\n P[brc_idx[0], brc_idx[1], brc_idx[2]] = 1\n P_hat = (P-P_hat).detach() + P_hat\n return P_hat\n","repo_name":"ermongroup/neuralsort","sub_path":"pytorch/neuralsort.py","file_name":"neuralsort.py","file_ext":"py","file_size_in_byte":1541,"program_lang":"python","lang":"en","doc_type":"code","stars":124,"dataset":"github-code","pt":"21"}
+{"seq_id":"4225917850","text":"import os\nimport firebase_admin\nfrom firebase_admin import credentials, storage\n\n# Obtenez le chemin absolu du fichier JSON\ncurrent_directory = os.path.dirname(os.path.abspath(__file__))\nprint(current_directory)\njson_path = os.path.join(current_directory, \"airneis-bfec3-firebase-adminsdk-muxxs-b5021cd036.json\")\n\ncred = credentials.Certificate(json_path)\nfirebase_admin.initialize_app(cred, {'storageBucket': 'gs://airneis-bfec3.appspot.com'}, force_firebase_install=True)\n\nbucket = storage.bucket()\n\ndef list_files_with_directory(path):\n blobs = bucket.list_blobs(prefix=path)\n for blob in blobs:\n relative_path = os.path.relpath(blob.name, path)\n print(f\"Lien : gs://{bucket.name}/{blob.name}\")\n print(f\"Répertoire d'origine : {os.path.dirname(relative_path)}\")\n print(\"-\" * 50)\n\nroot_directory = 'images'\nlist_files_with_directory(root_directory)\n","repo_name":"Azurhys/airneis","sub_path":"web/Utile/Gs_to_Url.py","file_name":"Gs_to_Url.py","file_ext":"py","file_size_in_byte":886,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"}
+{"seq_id":"28020358406","text":"import tensorflow as tf\nimport numpy as np\n\n\nclass BatchedDataset(object):\n def __init__(self, raw_data, batch_size, num_steps, forever=False):\n raw_data = np.array(raw_data)\n data_len = len(raw_data)\n batch_len = data_len // batch_size\n self.data = np.reshape(raw_data[0 : batch_size * batch_len],\n [batch_size, batch_len])\n self.epoch_size = (batch_len - 1) // num_steps\n self.num_steps = num_steps\n self.batch_size = batch_size\n self.forever = forever\n\n def generator(self):\n i = 0\n while True:\n x = self.data[:, i*self.num_steps:(i+1)*self.num_steps]\n y = self.data[:, (i*self.num_steps + 1):((i+1)*self.num_steps+1)]\n yield x, y\n i += 1\n if i == self.epoch_size:\n if self.forever:\n i = 0\n else:\n break\n\ndef file_sequence_generator(filename, batch_size, num_steps, forever=False):\n with open(filename) as fp:\n data = [int(x) for x in fp.readlines()]\n\n batched_dset = BatchedDataset(data, batch_size, num_steps, forever=forever)\n return batched_dset.generator\n\ndef create_tf_dataset(filename, batch_size, num_steps, forever=False):\n return tf.data.Dataset.from_generator(file_sequence_generator(filename, batch_size, num_steps,\n forever=forever),\n (tf.int64, tf.int64),\n (tf.TensorShape([batch_size, num_steps]),\n tf.TensorShape([batch_size, num_steps])))\n\n\ndef oneshot_input_fn(dset):\n iterator = dset.make_one_shot_iterator()\n x, y = iterator.get_next()\n return {'tokens': x}, y\n\nif __name__ == \"__main__\":\n ds = create_tf_dataset(\"data/processed/jokes.dat\", batch_size=32, num_steps=50, forever=False)\n value = ds.make_one_shot_iterator().get_next()\n init_op = tf.global_variables_initializer()\n with tf.Session() as sess:\n sess.run(init_op)\n x = sess.run(value)\n print(x)\n\n","repo_name":"kjchavez/jokes","sub_path":"jokes/models/input.py","file_name":"input.py","file_ext":"py","file_size_in_byte":2159,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"}
+{"seq_id":"1867231706","text":"# 집합의 표현\nimport sys\nsys.setrecursionlimit(10**6)\ninput = sys.stdin.readline\n\nn, m = map(int, input().split())\nparents = [i for i in range(n+1)]\n\ndef find(x):\n if x != parents[x]:\n parents[x] = find(parents[x])\n return parents[x]\n\ndef union(x, y):\n x = find(x)\n y = find(y)\n if x < y:\n parents[y] = x\n else:\n parents[x] = y\n \nfor _ in range(m):\n cal, a, b = map(int, input().split())\n if cal == 0:\n union(a, b)\n else:\n if find(a) == find(b):\n print('YES')\n else:\n print('NO')\n","repo_name":"watchstep/TIS-python","sub_path":"BAEKJOON/gold4/1717.py","file_name":"1717.py","file_ext":"py","file_size_in_byte":523,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"}
+{"seq_id":"32755186202","text":"\nclass MetricGroup:\n\n def __init__(self, metrics):\n for attr in metrics:\n setattr(self, attr, 0)\n\nclass SimpleMetricGroup:\n\n def __init__(self, metrics):\n for attr in metrics:\n setattr(self, attr, 0)\n\nclass IterMetrics:\n\n metrics = ['iter_index', 'recall', 'viterbi_recall', 'logprobs', 'alpha', 'rb_score', 'zipf_p', 'zipf_L', 'zipf_alpha',\n 'zipf_rules_p','zipf_rules_alpha', 'zipf_rules_L', 'ave_entropy',\n 'ave_confus', 'logprob_joint_tree', 'logprob_conditional_tree', 'max_depth_by_sent_len'\n ,'surprisal', 'joint_surprisal', 'conditional_tree_surprisal', 'rule_complexity', 'accu_ave_tree_depth',\n 'ave_lb_length', 'ave_rb_length', 'ave_max_lb_length', 'ave_max_rb_length', 'surprisal_variance',\n 'viterbi_logprob_joint_tree', 'viterbi_joint_surprisal' , 'viterbi_ave_lb_length', 'viterbi_ave_rb_length',\n 'viterbi_max_depth_by_sent_len', 'viterbi_rb_score', 'viterbi_accu_ave_tree_depth',\n 'viterbi_ave_max_lb_length', 'viterbi_ave_max_rb_length', 'viterbi_rule_complexity', 'ave_span_length',\n 'ave_max_span_length', 'grammar_tree_joint_logporb',\n 'joint_surprisal_var', 'grammar_tree_joint_surprisal',\n 'grammar_logprob', 'grammar_surprisal']\n\n def __init__(self, iter_index=0):\n self.iter_index = iter_index\n self.iter_metrics = [MetricGroup(self.metrics)]\n\n def spawn_iter(self):\n iter_index = self.iter_index + 1\n new_metric = MetricGroup(self.metrics)\n new_metric.iter_index = iter_index\n\n return new_metric\n\n @property\n def last_iter(self):\n return self.iter_metrics[-1]\n\n @last_iter.setter\n def last_iter(self, metric_group:MetricGroup):\n self.iter_metrics.append(metric_group)\n self.iter_index = metric_group.iter_index\n\nclass SimpleIterMetrics:\n\n metrics = ['iter_index', 'batch_index', 'viterbi_recall', 'logprobs', 'rb_score', 'vm_nopunc', 'vm_withpunc',\n 'vas', 'sparsity', 'alpha', 'viterbi_upper', 'dev_logprobs', 'dev_vas' ]\n\n def __init__(self):\n self.batch_metrics = [SimpleMetricGroup(self.metrics)]\n self.best_batch_per_metric = {}\n for m in self.metrics:\n self.best_batch_per_metric[m] = self.batch_metrics[-1]\n self.burn_in_iters = 5\n\n def spawn_batch(self, batch_index=0, iter_index=0):\n new_metric = SimpleMetricGroup(self.metrics)\n new_metric.batch_index = batch_index\n new_metric.iter_index = iter_index\n return new_metric\n\n @property\n def last_batch(self):\n return self.batch_metrics[-1]\n\n @last_batch.setter\n def last_batch(self, metric_group:SimpleMetricGroup):\n self.batch_metrics.append(metric_group)\n self._update_best_metric_batch(metric_group)\n\n def _update_best_metric_batch(self, metric_group:SimpleMetricGroup):\n if metric_group.iter_index > self.burn_in_iters:\n for m in self.metrics:\n current_best = self.best_batch_per_metric[m]\n if getattr(metric_group, m) > getattr(current_best, m):\n self.best_batch_per_metric[m] = metric_group\n else:\n return\n\n def write_out_last(self, fn):\n vals = []\n for name in self.metrics:\n vals.append(str(getattr(self.last_batch, name)))\n string = '\\t'.join(vals)\n fn.write(string+'\\n')\n fn.flush()\n","repo_name":"lifengjin/acl_flow","sub_path":"scripts/metric_groups.py","file_name":"metric_groups.py","file_ext":"py","file_size_in_byte":3502,"program_lang":"python","lang":"en","doc_type":"code","stars":9,"dataset":"github-code","pt":"21"}
+{"seq_id":"28962345388","text":"\nimport os\nimport tysoc_bindings\nimport pytysoc\n\nimport numpy as np\nimport tensorflow as tf\nimport tf_util\nimport load_policy\n\n_policyFn = load_policy.load_policy( 'experts/Ant-v2.pkl' )\n\n_agent = tysoc_bindings.PyCoreAgent( 'walker1', [0,0,0.75], 'mjcf', 'ant' )\n_terrainGen = tysoc_bindings.PyStaticTerrainGen( 'terrainGen0' ) \n_terrainGen.createPrimitive( 'plane',\n [200,10,0.1],\n [0,0,0],\n [0,0,0],\n [.2,.3,.4],\n 'chessboard' )\n\n_scenario = tysoc_bindings.PyScenario()\n_scenario.addAgent( _agent )\n_scenario.addTerrainGen( _terrainGen )\n\n_runtime = pytysoc.createRuntime( physicsBackend = pytysoc.BACKENDS.PHYSICS.MUJOCO,\n renderingBackend = pytysoc.BACKENDS.RENDERING.GLVIZ,\n workingDir = pytysoc.PATHS.WORKING_DIR )\n\n_simulation = _runtime.createSimulation( _scenario )\n_simulation.initialize()\n\n_visualizer = _runtime.createVisualizer( _scenario )\n_visualizer.initialize()\n\n_actionDim = _agent.getActionDim()\nprint( 'actionSpaceDim: ', _actionDim )\n\n_running = False\n\nwith tf.Session() :\n tf_util.initialize()\n\n while _visualizer.isActive() :\n\n # press key P to start simulation (sorry, forgot to map keys in python)\n if _visualizer.checkSingleKeyPress( 15 ) :\n _running = not _running\n\n if _running :\n _obsMap = _simulation.getDictOfVectorizedSimData()\n _observation = np.concatenate( [ _obsMap['qpos'].flat[2:],\n _obsMap['qvel'].flat,\n np.clip( _obsMap['comForcesExt'], -1, 1 ).flat ] )\n \n _action = _policyFn( _observation[None,:] )\n _agent.setActions( _action )\n \n _simulation.step()\n\n _visualizer.render()\n","repo_name":"wpumacay/loco-bullet","sub_path":"_legacy/examples/python/ant_sample.py","file_name":"ant_sample.py","file_ext":"py","file_size_in_byte":1918,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"}
+{"seq_id":"32491891694","text":"import boto3\n\ndef lambda_handler(event, context):\n phone = event['phone']\n client = boto3.resource('dynamodb')\n table = client.Table('DrackerUser')\n item = table.get_item(\n Key={\n 'phone': phone\n }\n )\n try:\n data = item['Item']\n except:\n data = None\n \n return data","repo_name":"raghavbhasin97/Dracker","sub_path":"iOS App V2/API/API/users/user/GET/user_data.py","file_name":"user_data.py","file_ext":"py","file_size_in_byte":326,"program_lang":"python","lang":"en","doc_type":"code","stars":22,"dataset":"github-code","pt":"21"}
+{"seq_id":"11774733042","text":"#!/usr/bin/env python\n# -*- coding:utf-8 -*-\n# Author: Donny You(youansheng@gmail.com)\n# Loss Manager for Image Classification.\n\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport torch\n\nfrom loss.modules.cls_modules import FCCELoss, FCCenterLoss\nfrom loss.modules.det_modules import FRLoss, SSDMultiBoxLoss, YOLOv3Loss, SSDFocalLoss\nfrom loss.modules.pose_modules import OPMseLoss\nfrom loss.modules.seg_modules import FSCELoss, FSOhemCELoss, FSAuxCELoss, FSAuxEncCELoss, FSAuxOhemCELoss\nfrom utils.tools.logger import Logger as Log\n\n\nCLS_LOSS_DICT = {\n 'fc_ce_loss': FCCELoss,\n 'fc_center_loss': FCCenterLoss\n}\n\nDET_LOSS_DICT = {\n 'ssd_multibox_loss': SSDMultiBoxLoss,\n 'ssd_focal_loss': SSDFocalLoss,\n 'yolov3_det_loss': YOLOv3Loss,\n 'fr_loss': FRLoss\n}\n\nPOSE_LOSS_DICT = {\n 'op_mse_loss': OPMseLoss,\n}\n\nSEG_LOSS_DICT = {\n 'fs_ce_loss': FSCELoss,\n 'fs_ohemce_loss': FSOhemCELoss,\n 'fs_auxce_loss':FSAuxCELoss,\n 'fs_auxencce_loss': FSAuxEncCELoss,\n 'fs_auxohemce_loss': FSAuxOhemCELoss\n}\n\n\nclass LossManager(object):\n def __init__(self, configer):\n self.configer = configer\n\n def _parallel(self, loss):\n if self.configer.get('network', 'loss_balance') and len(range(torch.cuda.device_count())) > 1:\n from extensions.parallel.data_parallel import DataParallelCriterion\n loss = DataParallelCriterion(loss)\n\n return loss\n\n def get_cls_loss(self, loss_type=None):\n key = self.configer.get('loss', 'loss_type') if loss_type is None else loss_type\n if key not in CLS_LOSS_DICT:\n Log.error('Loss: {} not valid!'.format(key))\n exit(1)\n\n loss = CLS_LOSS_DICT[key](self.configer)\n return self._parallel(loss)\n\n def get_seg_loss(self, loss_type=None):\n key = self.configer.get('loss', 'loss_type') if loss_type is None else loss_type\n if key not in SEG_LOSS_DICT:\n Log.error('Loss: {} not valid!'.format(key))\n exit(1)\n\n loss = SEG_LOSS_DICT[key](self.configer)\n return self._parallel(loss)\n\n def get_det_loss(self, loss_type=None):\n key = self.configer.get('loss', 'loss_type') if loss_type is None else loss_type\n if key not in DET_LOSS_DICT:\n Log.error('Loss: {} not valid!'.format(key))\n exit(1)\n\n loss = DET_LOSS_DICT[key](self.configer)\n return self._parallel(loss)\n\n def get_pose_loss(self, loss_type=None):\n key = self.configer.get('loss', 'loss_type') if loss_type is None else loss_type\n if key not in POSE_LOSS_DICT:\n Log.error('Loss: {} not valid!'.format(key))\n exit(1)\n\n loss = POSE_LOSS_DICT[key](self.configer)\n return self._parallel(loss)\n\n","repo_name":"donnyyou/PyTorchCV","sub_path":"loss/loss_manager.py","file_name":"loss_manager.py","file_ext":"py","file_size_in_byte":2811,"program_lang":"python","lang":"en","doc_type":"code","stars":45,"dataset":"github-code","pt":"21"}
+{"seq_id":"72527355254","text":"\"\"\"\n=============================================\npairwiseGlobalAlignment_sequenceIdentities.py\n=============================================\n\nPT-BR:\nScript para realizar alinhamento global par-a-par. O input consiste de um arquivo multifasta. O argumento --identity configura o limite mínimo de identidade para que duas sequencias sejam consideradas redundantes. As saidas consistem de arquivo tabulares indicando a identidade de sequencias entre cada par e um arquivo fasta de sequencias não-redundantes. O programa utiliza EMBOSS (needle) para realizar os alinhamentos.\n\nEN:\nScript to perform global alignments. The input consists of a multifasta file. The --identity argument sets the minimum identity for two strings be considered redundant. The outputs consist of tabular files indicating the sequence identity between each pair and a fasta file with non-redundant sequences. The script uses EMBOSS (needle) to perform the alignments.\n\nType python3 pairwiseGlobalAlignment_sequenceIdentities.py -help to see the instructions.\n\n\"\"\"\n\nprint(__doc__)\n\nusage = \"\\n\\tUSAGE: python3 pairwiseGlobalAlignmentParallel_sequenceIdentities.py [options]\\n\\n\\\n\t*** Argumentos obrigatorios:\\n\\\n\t\t--sequences (arquivo de sequencias para alinhamentos)\\n\\\n\t\t--cpus (numero de CPUs para executar alinhamentos)\\n\\n\\\n\t\t--identity (limite de identidade. Pares de sequencias com valor de identidade maior ou igual ao especificado serao consideradas redundantes.)\\n\\n\\\n\t*** Argumento opcionais:\\n\\\n\t\t--ids (para realizar alinhamento somente das sequencias especificadas na lista de identificadores)\\n\\\n\t\t--dna2protein (quando possuir sequencia de nucleotideos e quiser alinha-las como proteína)\\n\\n\\\n\t*** Modulos obrigatorios:\\n\\\n\t\tformataFasta_17Mar2020.py\\n\\\n\t\textraiSeqFastaIDs_24Mar2020.py\\n\\n\"\n\n\n#realizar alinhamento global par a par de sequencias para obter identidade\n#Vou usar o EMBOSS (ferramenta needle) para isso.\n\n#export PATH=$PATH:/home/tuliomorgan/doutorado/programas/EMBOSS-6.6.0/emboss\n\ndef loopAlinhamento(cpus, fasta_selected, cutoff_identidade):\n\timport sys, re, subprocess\n\n\t## -- teste para saber o se needle esta configurado no sistema -- ##\n\tneedle = subprocess.Popen(['which', 'needle'],stdout=subprocess.PIPE, stderr=subprocess.PIPE)\n\tcase = needle.communicate() # communicate() returns a tuple (stdoutdata, stderrdata)\n\tif case[0]:\n\t\tprint ('\\nFerramenta Needle do pacote EMBOSS encontrada com sucesso.\\n')\n\telse:\n\t\tprint (\"ERRO: Ferramenta Needle não encontrada. Obtenha o pacote EMBOSS em http://emboss.open-bio.org/html/adm/ch01s01.html ou configure a variavel de ambiente PATH para o diretorio que contem o executável needle.\\n\")\n\t\texit()\n\n\t### -- iniciar subrotina de alinhamentos -- ##\n\n\t# lista com os valores de identidade de cada par, mas abaixo do vlaores de cutoff de identidade. Ja adicionei o cabecalho\n\tresultados_sequencias_nao_redundantes = ['query\\tsubject\\tidentidade(%)']\n\t# lista com os valores de identidade de cada par, mas maior ou igual do vlaores de cutoff de identidade. Ja adicionei o cabecalho\n\tresultados_sequencias_Redundantes = ['query\\tsubject\\tidentidade(%)']\n\n\t# criar um dicionario com todas as sequenicas do dataset. Vai ser util quando for recuperar as sequencias qeu devem ser mantidas no dataset, pois vou removendo-as da lista fasta_selected a medida que geramos os arquivos chunkID\n\tlist_all_sequences = []\n\tfor elemento in fasta_selected:\n\t\tlist_all_sequences.append(elemento)\n\n\t# didionario de proteinas main. Como vou remove-las do dataset (para ela nao ser alinahda novamente com outras em outros loops), vamos criar um dicionario para salva-las e adiciona-las novamente na saida script.\n\tdict_proteinas_main = {}\n\n\t#dicionario com os tamanhos das sequencias. Vai ser util quando for calcular a %identidade\n\tdict_lengths = {}\n\n\t# enquanto houver 2 ou mais sequencias no arquivo fasta, alinhamentos devem ser conduzidos.\n\twhile len(fasta_selected) >= 2:\n\t\t\n\t\t# definir proteina principal (vai ser alinhada contra todas as demais).\n\t\tproteinMain = fasta_selected[0] # primeiro elemento de 'fasta_selected'. Eh a proteina mais longa do dataset (uma vez que foram organizadas por tamanho com o 'orderSequencesBySize'.\n\t\t\n\t\tfile = open('temp_proteinMain_alinhar.fasta', 'w')\n\t\t# salva o ID e a sequencia da proteina Main\n\t\tfile.writelines(proteinMain)\n\t\tfile.close()\n\n\t\t# remove a proteina principal do dicionario 'fasta_selected'. Nao devo alinhar ela com ela mesma.\n\t\tfasta_selected.remove(proteinMain)\n\n\t\t# adiciona-la no dicionario de proteinas Main\n\t\tproteinMain = proteinMain.split('\\n')\n\t\tdict_proteinas_main[proteinMain[0]] = proteinMain[1]\n\n\t\t# quebrar a lista 'fasta_selected' em numero de arquivos de acordo com o numero de processadores requisitados.\n\t\t# primeiro avalia se o numero de sequencias é maior ou igual ao numero de cpus requisitados. Caso contrario, adequa o numero de cpus ao numero de sequencias.\n\t\tif len(fasta_selected) <= int(cpus):\n\t\t\tcpus = len(fasta_selected)\n\n\t\t# elimina arquivos gerados do loop de alinhamento anterior.\n\t\tsubprocess.run(['rm temp_*_chunkID*'], shell = True, stdout = subprocess.PIPE, stderr=subprocess.PIPE)\n\n\t\t# criacao dos arquivos de sequencias para alinhamento com a proteina main. Serao criados numero de aquivos igual ao numero de cpus requisitados, de modo que os alinhamentos sejam executados em paralelo.\t\t\n\t\tcomprimento_original_fasta_selected = len(fasta_selected)\n\t\t\n\t\tnSplit = 1\n\t\twhile nSplit <= int(cpus) and len(fasta_selected) != 0:\n\t\t\tif comprimento_original_fasta_selected % int(cpus) != 0 : # significa que nao vamos ter mesmo nuemro de sequenicas em todos os arquivos. O ultimo arquivo deve ficar com menos.\n\t\t\t\tnumSeqEachFile = comprimento_original_fasta_selected//(int(cpus)-1)\n\t\t\t\tnumSeqEachFile_resto = comprimento_original_fasta_selected % (int(cpus)-1)\n\t\t\telse:\n\t\t\t\tnumSeqEachFile = comprimento_original_fasta_selected//int(cpus)\n\t\t\t\tnumSeqEachFile_resto = False\n\n\t\t\tfile = open('temp_sequences_chunkID'+str(nSplit), 'w')\n\n\t\t\tif len(fasta_selected) == 1: # se so houver 1 sequencia na variavel ou se sobrou somente 1, salva-la em um arquivo\n\t\t\t\tfile.writelines(fasta_selected[0]+'\\n')\n\t\t\t\tseq_id = fasta_selected[0].split('\\n')[0].lstrip('>')\n\t\t\t\ttamanho = len(fasta_selected[0].split('\\n')[1])\n\t\t\t\tdict_lengths[seq_id] = tamanho\n\t\t\t\tdel fasta_selected[0]\n\t\t\t\tfile.close()\n\n\t\t\t# a variavel \"numSeqEachFile\" é o numero de sequencias em cada arquivo fasta. Vai entrar nesse if se nao houver numSeqEachFile_resto\n\t\t\telif nSplit <= int(cpus) and not numSeqEachFile_resto:\n\t\t\t\twhile numSeqEachFile:\n\t\t\t\t\tfile.writelines(fasta_selected[0]+'\\n')\n\t\t\t\t\tseq_id = fasta_selected[0].split('\\n')[0].lstrip('>')\n\t\t\t\t\ttamanho = len(fasta_selected[0].split('\\n')[1])\n\t\t\t\t\tdict_lengths[seq_id] = tamanho\n\t\t\t\t\tdel fasta_selected[0]\n\t\t\t\t\tnumSeqEachFile -= 1\n\t\t\t\tfile.close()\n\t\t\t\tnSplit += 1\n\n\t\t\telif nSplit < int(cpus) and numSeqEachFile_resto: # essa sao todas as iteracoes para salvar as sequencias quando temos sequenicas de resto.\n\t\t\t\twhile numSeqEachFile:\n\t\t\t\t\tfile.writelines(fasta_selected[0]+'\\n')\n\t\t\t\t\tseq_id = fasta_selected[0].split('\\n')[0].lstrip('>')\n\t\t\t\t\ttamanho = len(fasta_selected[0].split('\\n')[1])\n\t\t\t\t\tdict_lengths[seq_id] = tamanho\n\t\t\t\t\tdel fasta_selected[0]\n\t\t\t\t\tnumSeqEachFile -= 1\n\t\t\t\tfile.close()\n\t\t\t\tnSplit += 1\n\n\t\t\telif nSplit == int(cpus) and numSeqEachFile_resto: # essa eh a ultima iterecao para salvar os arquivos de resto\n\t\t\t\twhile numSeqEachFile_resto:\n\t\t\t\t\tprint(fasta_selected)\n\t\t\t\t\tfile.writelines(fasta_selected[0]+'\\n')\n\t\t\t\t\tseq_id = fasta_selected[0].split('\\n')[0].lstrip('>')\n\t\t\t\t\ttamanho = len(fasta_selected[0].split('\\n')[1])\n\t\t\t\t\tdict_lengths[seq_id] = tamanho\n\t\t\t\t\tdel fasta_selected[0]\n\t\t\t\t\tnumSeqEachFile_resto -= 1\n\t\t\t\tfile.close()\n\t\t\t\tnSplit += 1\n\n\t\t# chamada da funcao de alinhamento global par a par. A proteina main sera alinhada com cada proteina de cada arquivo fasta gerado no bloco anterior.\n\t\tchunkid = 1\n\t\tchildProcess = []\n\t\twhile chunkid <= cpus:\n\n\t\t\tnomeOutput = 'temp_align_sequences_chunkID'+str(chunkid)\n\t\t\tnomeSequencesAlinhar = 'temp_sequences_chunkID'+str(chunkid) # nomes dos aruqivos gerados no while anterior\n\n\t\t\twith open(nomeOutput, 'w') as exonerateOutput:\n\n\t\t\t\tneedle_cline = subprocess.Popen(['needle', '-asequence', 'temp_proteinMain_alinhar.fasta', '-bsequence',nomeSequencesAlinhar, '-gapopen', str(10), '-gapextend', str(0.5), '-outfile',nomeOutput],stdout = subprocess.PIPE, stderr=subprocess.PIPE)\n\t\t\t\tchildProcess.append(needle_cline) # ... e adiciona o comando em uma lista de processos\n\t\t\t\tchunkid += 1\n\n\t\tfor needleCall in childProcess: # para cada processo da lista 'childProcess' em execucao...\n\t\t\tneedleCall.wait() # ... informa para aguardar sua finalizacao. Dessa forma, os processos serao executados paralelamente.\n\n\t\tsubprocess.run(['cat temp_align_sequences_chunkID* > temp_all_alignments'], shell = True, stdout = subprocess.PIPE, stderr = subprocess.PIPE) # concatena os resultados de alinhamentos.\n\n\t\t# traneferir os resultados de alinhamentos para uma variavel do programa.\n\t\tfile = open('temp_all_alignments', 'r')\n\t\talinhamentos = file.readlines()\n\t\tfile.close()\n\n\t\t# analisar a identidade entre as sequencias.\n\t\tidsProteinasManter = []\n\t\tfor linha in alinhamentos:\n\t\t\t# Nesse for, tambem recuperar o comprimento das sequencias alinhadas (tamanho_seq_1 & tamanho_seq_2). Calcular a %identidade considerando o tamanho da menor sequencia. Pode ser que ela seja completamente englobado pela outra (com 100% de identidade). Nesse caso, se pegar somente o tamanho da maior sequencia, a %identidade nao da 100% (mesmo a sequencia menor sendo totalmente englobada pela maior).\n\t\t\tif linha.startswith('# 1:'): # id da sequencia proteinMain.\n\t\t\t\tlinhaSplit = linha.split()\n\t\t\t\tproteinaPrincipal = linhaSplit[2]\n\t\t\t\ttamanho_seq_1 = len(proteinMain[1]) # sequencia 'main'\n\n\t\t\telif linha.startswith('# 2:'): # id da sequencia que alinhou com proteinMain.\n\t\t\t\tlinhaSplit = linha.split()\n\t\t\t\tproteinaAlinhada = linhaSplit[2] # esse ID fica truncado pelo Needle (quebra no espaco em branco e pega o primeiro campo)\n\t\t\t\t\n\t\t\t\t# para recuperar o tamanho da sequencia 2, devemos busca-la do dicionario dict_lengths\n\t\t\t\tfor chave in dict_lengths.keys():\n\t\t\t\t\tchaveSplit = chave.split(' ')\n\t\t\t\t\tif chave == proteinaAlinhada: # o ID proteinaAlinhada fica truncado pelo Needle (quebra no espaco em branco e pega o primeiro campo)\n\t\t\t\t\t\ttamanho_seq_2 = dict_lengths[chave]\n\t\t\t\t\t\tbreak\n\t\t\t\t\telif chaveSplit[0] == proteinaAlinhada:\n\t\t\t\t\t\ttamanho_seq_2 = dict_lengths[chave]\n\t\t\t\t\t\tbreak\n\n\t\t\t# selecionar os IDs de proteinas nao redundantes. Essas irao para um novo loop de alinhamento.\n\t\t\telif linha.startswith('# Identity:'):\n\t\t\t\tidentidade = ''.join(re.findall(r'(?<=\\()[ 0-9]+.[0-9]+(? tamanho_seq_2:\n\t\t\t\t\tidentidade_menor_seq = (numero_matches/tamanho_seq_2)*100\n\t\t\t\telif tamanho_seq_1 < tamanho_seq_2:\n\t\t\t\t\tidentidade_menor_seq = (numero_matches/tamanho_seq_1)*100\n\t\t\t\t#nao precisa testar tamanho_seq_1 == tamanho_seq_2 pois se isso ocorrer a identidade fornecida pela needle esta eh a certa.\n\t\t\t\n\t\t\t\t# se verdadeiro, significa que a sequencia menor foi englobado pela maior. Podemos remove-lo do dataset.\n\t\t\t\tif identidade_menor_seq == 100:\n\t\t\t\t\t#print('proteina descartar (englobada)',proteinaAlinhada)\n\t\t\t\t\tresultados_sequencias_Redundantes.append(proteinaPrincipal+'\\t'+proteinaAlinhada+'\\t'+str(\"{:.2f}\".format(identidade_menor_seq)))\n\n\t\t\t\telif float(identidade) < cutoff_identidade*100: # se verdadeiro, as sequencias NAO sao consideradas redundantes.\n\t\t\t\t\t#print('proteina manter',proteinaAlinhada)\n\t\t\t\t\tidsProteinasManter.append(proteinaAlinhada)\n\t\t\t\t\t# salvar o resultado de indentidade para as duas sequencias alinhadas\n\t\t\t\t\tresultados_sequencias_nao_redundantes.append(proteinaPrincipal+'\\t'+proteinaAlinhada+'\\t'+identidade)\n\t\t\t\telse:\n\t\t\t\t\t#print('proteina descartar',proteinaAlinhada)\n\t\t\t\t\tresultados_sequencias_Redundantes.append(proteinaPrincipal+'\\t'+proteinaAlinhada+'\\t'+identidade)\n\t\t\n\t\t# salva as sequencias nao redundantes em um novo dicionario\n\t\tnew_fasta_selected = []\n\t\tfor ids in idsProteinasManter:\n\t\t\tfor elemento in list_all_sequences:\n\t\t\t\tID = str(elemento.split('\\n')[0].lstrip('>'))\n\t\t\t\tif ids == ID:\n\t\t\t\t\tnew_fasta_selected.append(elemento)\n\t\t\t\t\tbreak\n\t\t\t\t# o needle faz truncagem de IDs, reportando apenas os caracteres ate o primeiro espaco em branco\n\t\t\t\tID = ID.split(' ')[0]\n\t\t\t\tif ids == ID:\n\t\t\t\t\tnew_fasta_selected.append(elemento)\n\t\t\t\t\tbreak\n\t\t\n\t\t# substitui o novo fasta_selected (com as sequencias nao redundantes comparadas com a proteinaMain) com o nome fasta_select, e volta para o while do inicio do script para selecionar nova proteinMain.\n\t\tfasta_selected = new_fasta_selected\n\n\t\tif len(fasta_selected) == 1: #so sobrou uma sequencia no 'fasta_selected' e essa sequencia eh boa, pois seu ID foi mantido ate aqui (nao eh redundante)\n\t\t\t# adiciona-la no dicionario de proteinas Main\n\t\t\tfasta_selected = ''.join(fasta_selected)\n\t\t\tdict_proteinas_main[fasta_selected.split('\\n')[0]] = fasta_selected.split('\\n')[1]\n\t\t\tbreak # quebra o \"while len(fasta_selected) >= 2\"\n\n\treturn dict_proteinas_main, resultados_sequencias_nao_redundantes, resultados_sequencias_Redundantes\n\t\n### -- uso do script de forma independente, nao como modulo de outro script -- ###\n\nif __name__ == '__main__':\n\timport sys\n\tif len(sys.argv) < 4:\n\t\tprint(usage)\n\t\texit()\n\n\telse:\n\t\ttraduz = False\n\n\t\tif 'dna2protein' in sys.argv:\n\t\t\tsys.argv.remove('dna2protein')\n\t\t\ttraduz = True\n\n\t\tif '--sequences' in sys.argv:\t\n\t\t\targSequences = sys.argv.index('--sequences')+1\n\t\t\tfile = open(sys.argv[argSequences])\n\t\t\tarq_fasta = file.readlines()\n\t\t\tfile.close()\n\t\t\t\n\t\t\timport orderSequencesBySize #formata o arquivo multifasta e ordena por tamanho\n\t\t\treverse = False # ordenar as sequencias da maior para menor.\n\t\t\tfasta_selected = orderSequencesBySize.orderBySize(arq_fasta, reverse)\n\n\t\telse:\n\t\t\tprint(usage)\n\t\t\texit()\n\n\t\tif '--cpus' in sys.argv: # numero de divisoes que serao aplicadas ao dataset. Isso pertimite executar alinhamentos em paralelo.\n\t\t\targcpus = sys.argv.index('--cpus')+1\n\t\t\tcpus = int(sys.argv[argcpus])\n\t\telse:\n\t\t\tprint(usage)\n\t\t\texit()\n\n\t\tif '--identity' in sys.argv: # limite de identidade (inclusive) para considerar duas sequencias redundantes.\n\t\t\targIdentity = sys.argv.index('--identity')+1\n\t\t\tcutoff_identidade = float(sys.argv[argIdentity])\n\t\telse:\n\t\t\tprint(usage)\n\t\t\texit()\n\n\t\tif '--ids' in sys.argv:\n\t\t\targIDS = sys.argv.index('--ids')+1\n\t\t\tfile = open(sys.argv[argIDS], 'r')\n\t\t\tlista_ids = file.readlines()\n\t\t\tfile.close()\n\t\t\t\n\t\t\timport extraiSeqFastaIDs_24Mar2020\n\t\t\tfasta_selected = extraiSeqFastaIDs_24Mar2020.ExtraiSeqFastaIDs(lista_ids, fasta_selected)\n\n\t\telse:\n\t\t\tlista_ids = None\n\n\t\tif traduz:#se o argumento 'dna2protein' foi passado para o programa, fazemos a traducao da sequencia de DNA para depois realizar o alinhemnto global par a par.\n\n\t\t\tfrom Bio.Seq import Seq\n\t\t\ttranslated_fasta_selected = {}\n\t\t\tfor chave in fasta_selected.keys():\n\t\t\t\tsequence = fasta_selected[chave]\n\t\t\t\tsequence = Seq(sequence) #transformar a sequencia j (uma string) em um objeto 'Seq' e salvar na variavel seq.\n\t\t\t\tprotein_raw = str(sequence.translate()) #a variavel seq eh um objeto Seq e podemos aplicar a funcao translate. Apos, a traducao em aminoacidos, obtem-se resulado com a sequencia de aminoacidos e outras coisas (p.e. [Seq('TLYIKMVCLSLSEERGYIEALSVW*', HasStopCodon(ExtendedIUPACProtein(), '*'))]). Mas como quero imprimir somente a sequencia de aminoacidos, transformamos a variavel em string. Muito facil\n\t\t\t\ttranslated_fasta_selected[chave+' [translated]'] = protein_raw\n\n\t\t\tfasta_selected = translated_fasta_selected\n\n\t\t#chamada da funcao loopAlinhamento.\n\t\tdict_proteinas_main, resultados_sequencias_nao_redundantes, resultados_sequencias_Redundantes = loopAlinhamento(cpus, fasta_selected, cutoff_identidade)\n\t\t\n\t\t#### ----- para imprimir a chave e o valor (sequencia) devemos fazer um loop ----- #####\n\t\tfile = open('fasta_selected_sem_redundanciaMP.fasta','w')\n\t\tfor chave in dict_proteinas_main.keys():\n\t\t\tfile.writelines(chave+'\\n'+dict_proteinas_main[chave]+'\\n')\t\t\n\t\tfile.close()\n\n\t\t### --- imprimir os valores de identidade para sequenicas consideradas NAO redundantes --- ###\n\t\tfile = open('identidade_sequencias_nao_redundantes.txt','w')\n\t\tfor elemento in resultados_sequencias_nao_redundantes:\n\t\t\tfile.writelines(elemento+'\\n')\t\t\t\n\t\tfile.close()\n\n\t\t### --- imprimir os valores de identidade para sequenicas consideradas Redundantes --- ###\n\t\tfile = open('identidade_sequencias_redundantes.txt','w')\n\t\tfor elemento in resultados_sequencias_Redundantes:\n\t\t\tfile.writelines(elemento+'\\n')\t\t\t\n\t\tfile.close()\n","repo_name":"TulioMorgan/python_scripts","sub_path":"biological_sequence_manipulation/pairwiseGlobalAlignment_sequenceIdentities.py","file_name":"pairwiseGlobalAlignment_sequenceIdentities.py","file_ext":"py","file_size_in_byte":16891,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"}
+{"seq_id":"37449456782","text":"# 문제가 개편되었습니다. 이로 인해 함수 구성이나 테스트케이스가 변경되어, 과거의 코드는 동작하지 않을 수 있습니다.\r\n# 새로운 함수 구성을 적용하려면 [코드 초기화] 버튼을 누르세요. 단, [코드 초기화] 버튼을 누르면 작성 중인 코드는 사라집니다.\r\nfrom itertools import *\r\ndef solution(brown, red):\r\n brsum=[]\r\n for i in range(1,brown+red+1):\r\n if (brown+red)%i==0 and (brown+red)/i>=i:\r\n brsum.append([int((brown+red)/i),i])\r\n \r\n \r\n answer=[]\r\n for i in brsum:\r\n if i[0]*i[1]==brown+red and (i[0]-2)*(i[1]-2)==red :\r\n answer=list(i)\r\n break\r\n return answer","repo_name":"sunsu2737/algorithm","sub_path":"programmers/카펫.py","file_name":"카펫.py","file_ext":"py","file_size_in_byte":723,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"}
+{"seq_id":"11047440432","text":"class Max_Heap:\n def max_heapify(self, arr, n, i):\n largest = i\n left = 2 * i + 1\n right = 2 * i + 2\n\n # Check if left child is larger than root\n if left < n and arr[left] > arr[largest]:\n largest = left\n\n # Check if right child is larger than largest\n if right < n and arr[right] > arr[largest]:\n largest = right\n\n # If the largest element is not the root, swap them\n if largest != i:\n arr[i], arr[largest] = arr[largest], arr[i]\n # Recursively max heapify the affected subtree\n self.max_heapify(arr, n, largest)\n\n def delete_max(self, arr):\n # If the heap is empty, return None\n if len(arr) == 0:\n return None\n # If the heap has only one element, remove and return it\n if len(arr) == 1:\n return arr.pop(0)\n # If the heap has more than one element, remove the root (which is the maximum) and fix the heap property\n else:\n max = arr[0]\n arr[0] = arr.pop()\n self.max_heapify(arr, len(arr), 0)\n return max\n\n def insert_node(self, arr, value):\n arr.append(value)\n i = len(arr)-1\n # If the value is bigger than its parent, swap it with its parent until it reaches its correct position\n while i > 0 and arr[(i-1)//2] < value:\n arr[(i-1)//2], arr[i] = arr[i], arr[(i-1)//2]\n i = (i-1)//2\n return arr\n\n def build_maxheap(self,arr):\n n = len(arr)\n # Starting from the last non-leaf node, perform max_heapify on each node to create a max heap\n for i in range(n//2-1 ,-1 ,-1):\n self.max_heapify(arr, n, i)\n\n def print_heap(self, arr):\n print(*arr)\n\n\narr = [20,45,12,89,36,52,41,96,87]\nheap = Max_Heap()\nheap.build_maxheap(arr)\nprint(\"Max heap:-\")\nheap.print_heap(arr)\nprint('deleted max value')\nheap.delete_max(arr)\nheap.print_heap(arr)\nprint()\n\n\n\nclass Min_Heap:\n\n def min_heapify(self, arr, n, i):\n smallest = i\n left = 2 * i + 1\n right = 2 * i + 2\n\n # Check if left child is smaller than root\n if left < n and arr[left] < arr[smallest]:\n smallest = left\n\n # Check if right child is smaller than largest\n if right < n and arr[right] < arr[smallest]:\n smallest = right\n\n # If the smallest element is not the root, swap them\n if smallest != i:\n arr[i], arr[smallest] = arr[smallest], arr[i]\n # Recursively min heapify the affected subtree\n self.min_heapify(arr, n, smallest)\n\n def delete_min(self, arr):\n # If the heap is empty, return None\n if len(arr) == 0:\n return None\n # If the heap has only one element, remove and return it\n if len(arr) == 1:\n return arr.pop(0)\n # If the heap has more than one element, remove the root (which is the minimum) and fix the heap property\n else:\n min = arr[0]\n arr[0] = arr.pop()\n self.min_heapify(arr,0)\n return min\n\n def insert_node(self, arr, value):\n arr.append(value)\n i = len(arr)-1\n # If the value is smaller than its parent, swap it with its parent until it reaches its correct position\n while i > 0 and arr[(i-1)//2] > arr[i]:\n arr[(i-1)//2], arr[i] = arr[i], arr[(i-1)//2]\n i = (i-1)//2\n return arr\n\n def build_minheap(self,arr):\n n = len(arr)\n # Starting from the last non-leaf node, perform min_heapify on each node to create a min heap\n for i in range(n//2-1, -1, -1):\n self.min_heapify(arr, n, i)\n\n def print_heap(self, arr):\n print(arr)\n\n\narr = [20,45,12,89,36,52,41,96,87]\nheap = Min_Heap()\nheap.build_minheap(arr)\nprint(\"Min Heap:-\")\nheap.print_heap(arr)\n\n\nclass HeapSort:\n\n def build_heap(self, arr):\n n = len(arr)\n # Start from the last non-leaf node and work backwards\n for i in range(n//2 - 1, -1, -1):\n # Perform max heapify on each node or heapify each non-leaf\n self.max_heapify(arr, n, i)\n\n def max_heapify(self, arr, n, i):\n largest = i\n left = 2 * i + 1\n right = 2 * i + 2\n\n # Check if left child is larger than root\n if left < n and arr[left] > arr[largest]:\n largest = left\n\n # Check if right child is larger than largest\n if right < n and arr[right] > arr[largest]:\n largest = right\n\n # If the largest element is not the root, swap them\n if largest != i:\n arr[i], arr[largest] = arr[largest], arr[i]\n # Recursively max heapify the affected subtree\n self.max_heapify(arr, n, largest)\n\n def heapsort(self, arr):\n n = len(arr)\n self.build_heap(arr)\n\n # Swap the root (largest element) with the last element, then max heapify the remaining heap and while\n # running loop each sorted one will be at the end of array\n for i in range(n-1, -1, -1):\n arr[i], arr[0] = arr[0], arr[i]\n self.max_heapify(arr, i, 0)\n\n return arr\n\narr = [12, 36, 20, 87, 45, 52, 41, 96, 89]\nprint(\"Heap sort:-\")\nprint(arr)\na = HeapSort()\n\nprint(a.heapsort(arr))","repo_name":"subashkj005/Data_Structure","sub_path":"Week 3/Heap/Heap.py","file_name":"Heap.py","file_ext":"py","file_size_in_byte":5295,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"21"}
+{"seq_id":"44311482608","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Tue Jul 12 23:37:58 2022\r\n\r\n@author: User\r\n\"\"\"\r\n\r\nfrom statistics import mode\r\nimport pandas as pd\r\nimport numpy as np\r\nimport json\r\nimport time as time\r\nimport matplotlib.pyplot as plt\r\nfrom alphabet_detector import AlphabetDetector\r\n\r\nad = AlphabetDetector()\r\n\r\ndef make_list(string):\r\n list =[]\r\n list1 = string.split(\",\")\r\n for i in range(len(list1)):\r\n list1[i] = list1[i].strip()\r\n # list2 = string.split()\r\n\r\n list.append(string)\r\n if len(list1)>1:\r\n list = list +list1\r\n # if len(list2)>1:\r\n # list = list +list2 \r\n \r\n\r\n \r\n return list\r\n\r\ndef make_list_space(string):\r\n list =[]\r\n list1 = string.split(\" \")\r\n for i in range(len(list1)):\r\n list1[i] = list1[i].strip()\r\n # list2 = string.split()\r\n\r\n list.append(string)\r\n if len(list1)>1:\r\n list = list +list1\r\n # if len(list2)>1:\r\n # list = list +list2 \r\n \r\n\r\n \r\n return list\r\n\r\n\r\ndef dict_load(path):\r\n a_file = open(\"{0}.json\".format(path), \"r\")\r\n\r\n dict_ = json.load(a_file)\r\n\r\n a_file.close()\r\n return dict_\r\n\r\n\r\n\r\n \r\ndef search_dict_lower(string,country_dict_l,OG_names_dict_l,alt_name_dict_l,country_codes_l):\r\n search_results= []\r\n\r\n \r\n #check if the string has no \"alphabetical charachter\"\r\n temp_bol = False\r\n for i in range (len(string)):\r\n temp_bol = temp_bol + string[i].isalpha()\r\n \r\n if np.logical_not(temp_bol):\r\n search_results.append(\"Error\")\r\n return search_results[-1]\r\n \r\n \r\n DICTS = [country_dict_l,OG_names_dict_l,alt_name_dict_l]\r\n \r\n string_list = make_list(string) #separated by ,\r\n string_list_space = make_list_space(string) #separated by \" \"\r\n\r\n for i in range (len(string_list)): #go through the list seperated by \",\"\r\n for j in range (len(DICTS)):\r\n try: \r\n temp = DICTS[j][\"{0}\".format(string_list[i]).lower()]\r\n search_results.append(temp)\r\n except:\r\n continue\r\n \r\n \r\n if len(search_results) ==0:\r\n\r\n \r\n for i in range (len(string_list_space)): #go through the list seperated by \" \"\r\n for j in range (len(DICTS)):\r\n try: \r\n temp = DICTS[j][\"{0}\".format(string_list_space[i]).lower()]\r\n search_results.append(temp)\r\n except:\r\n continue\r\n \r\n \r\n if len(search_results) ==0:\r\n \r\n for i in range (len(string_list)): #Check wether the string contains the alpha 2 code or not\r\n try: \r\n temp = country_codes_l[string_list[i].upper()]\r\n search_results.append(string_list[i].upper())\r\n print(\"test\",string_list[i])\r\n\r\n except:\r\n continue\r\n \r\n for i in range (len(string_list_space)): #Check wether the string contains the alpha 2 code or not\r\n try: \r\n temp = country_codes_l[string_list_space[i].upper()]\r\n search_results.append(string_list_space[i].upper())\r\n print(\"test\",string_list_space[i])\r\n except:\r\n continue \r\n \r\n \r\n if len(search_results) ==0: #see whether it has cyrillic or cjk charachters\r\n for i in range (len(string_list)):\r\n if ad.is_cyrillic(u\"{0}\".format(string_list[i]).lower()):\r\n search_results.append(\"RU\")\r\n if ad.is_cjk(u\"{0}\".format(string_list[i]).lower()):\r\n search_results.append(\"JP\")\r\n \r\n\r\n \r\n if len(search_results) ==0: #if didnt find anything else\r\n\r\n search_results.append(\"Error\")\r\n \r\n \r\n return search_results[-1]\r\n \r\n\r\nstring = \"New York\"\r\n\r\n\r\n#load dictionaries\r\ncountry_dict =dict_load(\"Country_Names_dict\")\r\n\r\nOG_names_dict =dict_load(\"Original_Names_dict\")\r\n\r\nalt_name_dict = dict_load(\"Alternative_Names_exp\")\r\n\r\n\r\n#Case Insensitive\r\ncountry_dict_l = {k.lower(): v for k, v in country_dict.items()}\r\nOG_names_dict_l = {k.lower(): v for k, v in OG_names_dict.items()}\r\nalt_name_dict_l = {k.lower(): v for k, v in alt_name_dict.items()}\r\n\r\n#Alpha-2 code of countries\r\ncountry_codes_l = {v: k for k, v in country_dict_l.items()}\r\n\r\n\r\nCountry_Code = search_dict_lower(string,country_dict_l,OG_names_dict_l,alt_name_dict_l,country_codes_l)\r\n\r\nprint(Country_Code)","repo_name":"Danial-Vahabli/Twitter_Location_to_Country_Code","sub_path":"Location_Finder_Dict_Function.py","file_name":"Location_Finder_Dict_Function.py","file_ext":"py","file_size_in_byte":4588,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"}
+{"seq_id":"6181897378","text":"#!/usr/bin/env python3\n\nimport sys\nimport io\nimport re\n\ninput_stream = io.TextIOWrapper(sys.stdin.buffer, encoding='utf-8')\n\nstop_words = set()\n\nfor line in sys.stdin:\n try:\n article_id, text = line.strip().split('\\t', 1)\n except ValueError as e:\n continue\n text = re.sub(r'[^A-Za-z\\\\s\\s]','',text).lower() \n words = set(re.split(\"\\W*\\s+\\W*\", text, flags=re.UNICODE))\n\n for word in words:\n print(word, 1, sep='\\t')\n\n\n\n\n\n","repo_name":"Anastassiya08/BigData_course","sub_path":"HW/hw2/112/mapper.py","file_name":"mapper.py","file_ext":"py","file_size_in_byte":463,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"}
+{"seq_id":"39272555954","text":"from cx_Freeze import setup, Executable\nimport os\n\nPYTHON_INSTALL_DIR = os.path.dirname(os.path.dirname(os.__file__))\nos.environ['TCL_LIBRARY'] = os.path.join(PYTHON_INSTALL_DIR, 'tcl', 'tcl8.6')\nos.environ['TK_LIBRARY'] = os.path.join(PYTHON_INSTALL_DIR, 'tcl', 'tk8.6')\n\n# On appelle la fonction setup\n\nbuildOptions = dict(\n packages = [],\n excludes = [],\n include_files=[os.path.join(PYTHON_INSTALL_DIR, 'DLLs') +'/tcl86t.dll', os.path.join(PYTHON_INSTALL_DIR, 'DLLs') + '/tk86t.dll']\n)\n\nsetup(\n name = \"salut\",\n version = \"0.1\",\n description = \"Ce programme vous dit bonjour\",\n options = dict(build_exe = buildOptions),\n executables = [Executable(\"main.py\")],\n)\n","repo_name":"darckoune/fm_assistant","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":690,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"21"}
+{"seq_id":"38305603080","text":"import json\nimport requests\n\ndef movie(moviename):\n key = '6c03f71a8d18d6a277d47cba0d7c2eb6'\n api = 'http://v.juhe.cn/movie/index'\n params = 'title=%s&smode=0&key=%s&' % (moviename, key)\n url = api + '?' + params\n response = requests.get(url=url)\n json_data = json.loads(response.text)\n result = json_data.get('result')\n response = []\n for mov in result:\n movie = {}\n movie['rating'] = mov.get('rating')\n movie['genres'] = mov.get('genres')\n movie['title'] = mov.get('title')\n movie['actors'] = mov.get('actors')\n movie['simple_plot'] = mov.get('plot_simple')\n movie['year'] = movie.get('year')\n response.append(movie)\n return response\n","repo_name":"ruan1998/djtest","sub_path":"thirdparty/juhe.py","file_name":"juhe.py","file_ext":"py","file_size_in_byte":722,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"}
+{"seq_id":"19594995955","text":"import numpy as np\r\nfrom itertools import permutations\r\n\r\ng = np.array([[7, 5, 8], [3, 13, 9], [5, 8, 2]])\r\nt = 20\r\n\r\nfor p in permutations(g.flatten()):\r\n g_ = np.array(p).reshape(g.shape)\r\n if (g_.sum(axis=0) == t).all():\r\n print('\\n'.join(['\\t'.join(map(str, r)) for r in g_.tolist()]))\r\n break\r\n","repo_name":"datheia/segmentle-solver","sub_path":"segmentle_solver.py","file_name":"segmentle_solver.py","file_ext":"py","file_size_in_byte":319,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"}
+{"seq_id":"40396440554","text":"import pandas as pd\nimport statsmodels.api as sm\nimport numpy as np\nfrom loguru import logger\n\n\nclass MomentumUtils:\n @staticmethod\n def return_Nm(data: pd.DataFrame, n: int = 6, col_name='close') -> pd.Series:\n return data[col_name] / data[col_name].shift(n * 22) - 1\n\n @staticmethod\n def wgt_return_Nm(data: pd.DataFrame, n: int = 6, change_per_col_name='change_percentage',\n turnover_rate_col_name='turnover_rate') -> pd.Series:\n data['product'] = data[change_per_col_name] * data[turnover_rate_col_name]\n data['wgt_return_nm'] = data['product'].rolling(window=n * 22).mean()\n return data['wgt_return_nm']\n\n @staticmethod\n def exp_wgt_return_Nm(data: pd.DataFrame, n: int = 6) -> pd.Series:\n pass\n\n @staticmethod\n def HAlpha(data: pd.DataFrame, n=60, stock_return_col_name='change', bench_return_col_name='bench_change') -> float:\n X = data.tail(n)[stock_return_col_name]\n X = sm.add_constant(X)\n y = data.tail(n)[bench_return_col_name]\n model = sm.OLS(y, X).fit()\n halpha = model.params['const']\n return halpha\n\n @staticmethod\n def add_ret_Nd(data: pd.DataFrame, n: int = 22, close_col: str = 'close') -> pd.DataFrame:\n data[f'ret_{n}d'] = (data['close'] / data['close'].shift(n) - 1) * 100\n return data\n\n @staticmethod\n def add_ret_Nds(data: pd.DataFrame, ns: [int] = None, close_col: str = 'close') -> pd.DataFrame:\n for n in ns:\n data = MomentumUtils.add_ret_Nd(data, n, close_col)\n return data\n\n @staticmethod\n def add_wgt_ret_Nd(data: pd.DataFrame, n: int = 22, daily_ret_col: str = 'ret_1d',\n wgt_col: str = 'weight') -> pd.DataFrame:\n data[f'wgt_ret_{n}d'] = (\n (data[daily_ret_col] * data[wgt_col]).rolling(window=n).sum() /\n data[wgt_col].rolling(window=n).sum()\n )\n return data\n\n @staticmethod\n def add_wgt_ret_Nds(data: pd.DataFrame, ns: [int] = None, daily_ret_col: str = 'ret_1d',\n wgt_col: str = 'weight') -> pd.DataFrame:\n for n in ns:\n data = MomentumUtils.add_wgt_ret_Nd(data, n, daily_ret_col, wgt_col)\n return data\n\n @staticmethod\n def add_exp_wgt_ret_Nd(data: pd.DataFrame, n: int = 22, daily_ret_col: str = 'ret_1d',\n wgt_col: str = 'weight') -> pd.DataFrame:\n d = np.ceil(n / 22) * 4\n time_weights = np.array([np.exp(-x / d) for x in range(n)])\n\n def exp_wgt_rolling_sum(series):\n return sum(series * time_weights)\n\n data[f'exp_wgt_ret_{n}d'] = np.array([\n np.nan if i < n - 1 else\n (np.sum(data[daily_ret_col].iloc[i - n + 1:i + 1].values\n * data[wgt_col].iloc[i - n + 1:i + 1].values\n * time_weights)) /\n (np.sum(data[wgt_col].iloc[i - n + 1:i + 1].values\n * time_weights))\n for i in range(len(data))\n ])\n return data\n\n @staticmethod\n def add_exp_wgt_ret_Nds(data: pd.DataFrame, ns: [int] = None, daily_ret_col: str = 'ret_1d',\n wgt_col: str = 'weight') -> pd.DataFrame:\n for n in ns:\n data = MomentumUtils.add_exp_wgt_ret_Nd(data, n, daily_ret_col, wgt_col)\n return data\n","repo_name":"openhe-hub/open-quant-data","sub_path":"open_quant_data/stat/MomentumUtils.py","file_name":"MomentumUtils.py","file_ext":"py","file_size_in_byte":3350,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"}
+{"seq_id":"35400797","text":"import math\n\nfrom objects.lazer import Lazer\nfrom objects.object import Object\n\n\n\nclass PlayerShip(Object):\n RADIUS = 40\n SPEED = 20\n DIAGONAL_SPEED = SPEED * math.sqrt(0.5)\n LIVES = 3\n INVULNERABILITY_FRAMES = 120\n COOLDOWN = 5\n\n def __init__(self, id, point):\n self.id = id\n self.lives = PlayerShip.LIVES\n self.invulnerability_frames_left = 0\n self.cooldown = 0\n super().__init__(point, PlayerShip.RADIUS)\n\n def move_in_direction(self, x_mul, y_mul):\n if abs(x_mul) + abs(y_mul) == 0:\n return\n elif abs(x_mul) + abs(y_mul) == 1:\n self.move(PlayerShip.SPEED * x_mul, PlayerShip.SPEED * y_mul)\n else:\n self.move(PlayerShip.DIAGONAL_SPEED * x_mul, PlayerShip.DIAGONAL_SPEED * y_mul)\n\n def update(self):\n from server.engine import Engine\n self.point.y += Engine.CURRENT_SPEED\n if self.invulnerability_frames_left > 0:\n self.invulnerability_frames_left -= 1\n if self.cooldown > 0:\n self.cooldown -= 1\n\n def hit(self):\n self.lives -= 1\n if self.lives == 0:\n super().hit()\n else:\n self.invulnerability_frames_left = PlayerShip.INVULNERABILITY_FRAMES\n\n def fire(self):\n if self.cooldown == 0:\n self.cooldown = PlayerShip.COOLDOWN\n return Lazer(self, True, 20, self.id)\n","repo_name":"tudorvaran/university","sub_path":"vgd/objects/player_ship.py","file_name":"player_ship.py","file_ext":"py","file_size_in_byte":1407,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"21"}
+{"seq_id":"9146304455","text":"from mushroom_rl.algorithms.agent import Agent\nfrom mushroom_rl.environments import Atari\nimport time\nfrom utils_rl import GymRenderer, make_deterministic, extract_game_name\nfrom parsers import rendering_parser as parser\nfrom collections import namedtuple\nimport json\nfrom utils import load_agent\n\ndef run_exp(agent, env, args):\n if args.no_display:\n renderer = None\n else:\n if args.record and args.video_title is None:\n args.video_title = args.agent_path.split(\"/\")[-1].replace(\".zip\", \"\")\n renderer = GymRenderer(env, record=args.record, title=args.video_title)\n\n for i in range(1): # only 1 life\n total_r = 0\n state = env.reset()\n n_steps = 0\n while True:\n action = agent.draw_action(state)\n state, reward, done, _ = env.step(action)\n total_r += reward\n n_steps += 1\n if renderer is not None:\n renderer.render()\n time.sleep(0.01)\n if done:\n print(\"Done\")\n break\n print(\"Total reward: \" + str(total_r))\n if renderer is not None:\n renderer.close_recorder()\n\n\nif __name__ == '__main__':\n args = parser.parse_args()\n\n game_name = extract_game_name(args.agent_path)\n with open(f'configs/{game_name}_config.json', 'r') as f:\n data = f'{json.load(f)}'.replace(\"'\", '\"')\n config = json.loads(data, object_hook=lambda d: namedtuple('X', d.keys())(*d.values()))\n\n env = Atari(config.game_name, config.width, config.height, ends_at_life=True,\n history_length=config.history_length, max_no_op_actions=30)\n make_deterministic(args.seed, env)\n\n\n # agent_f = f\"{arguments.algo}_{arguments.act_f}_{arguments.game}_s{arguments.seed}_e{arguments.epoch}.zip\"\n print(f\"Using agent from {args.agent_path}\")\n agent = load_agent(args.agent_path)\n\n run_exp(agent, env, args)\n","repo_name":"k4ntz/MOC","sub_path":"render_agent.py","file_name":"render_agent.py","file_ext":"py","file_size_in_byte":1922,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"21"}
+{"seq_id":"22762745426","text":"import random\nimport time\n\nfrom celery import shared_task\nfrom django.contrib.auth import get_user_model\nfrom faker import Faker\n\nfrom accounts.models import ForumUser\nfrom music.models import ForumCategory, ForumComment\n\n\n@shared_task\ndef mine_bitcoin():\n time.sleep(random.randint(1, 10))\n\n\n@shared_task\ndef normalize_email_task(filter):\n query_set = ForumUser.objects.filter(**filter)\n if query_set:\n for user in query_set:\n print(\"working with user: {user.email}\")\n user.save()\n else:\n print(\"Empty data\")\n\n\nfake = Faker()\n\n\n@shared_task\ndef fake_data(number):\n for i in range(0, number):\n fake_name = fake.name()\n fake_desc = fake.sentence(nb_words=70)\n cat_item = ForumCategory.objects.get_or_create(name=fake_name, description=fake_desc)\n cat_item.save()\n\n for i in range(0, number):\n fake_first_name = fake.first_name()\n fake_last_name = fake.last_name()\n fake_email = fake.email()\n user_item = ForumUser.objects.get_or_create(\n email=fake_email, first_name=fake_first_name, last_name=fake_last_name\n )\n user_item.set_password(\"12345\")\n user_item.save()\n\n for i in range(0, number):\n fake_uuid = fake.UUID.v4()\n fake_desc = fake.sentence(nb_words=70)\n comments_item = ForumComment.objects.get_or_create(author=get_user_model(), messages=fake_uuid, text=fake_desc)\n comments_item.save()\n","repo_name":"LeroyGorn/musician_hub","sub_path":"src/music/tasks.py","file_name":"tasks.py","file_ext":"py","file_size_in_byte":1467,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"}
+{"seq_id":"19158409049","text":"import logging\nfrom src.components import Splitter, Joiner\n\nlogger = logging.getLogger('root')\n\n\nclass MetricPipeline:\n def __init__(self,\n metric_app_pipeline,\n app_ids,\n config,\n AidServiceConnection=None):\n \"\"\"\n Responsible for processing the data for one metric.\n\n Depending on the Metric, different class inheriting from this one\n should be created. Only thing changed should be the components\n for processing values changed. Overwrite methods _setup_models\n and _setup_decisionmakers with logic pertaining to the metric.\n\n The following is replicated for each appID for given metric:\n\n /- AppPipelineMetric ------i\n / I\n Splitter --- AppPipelineMetric ----- Joiner\n I /\n I___ AppPipelineMetric_____/\n \"\"\"\n self._AidServiceConnection = AidServiceConnection\n self._entrypoint = Splitter(process=lambda values: values)\n self._metric = metric_app_pipeline.metric\n self._metric_pipeline = {\n appID: metric_app_pipeline(config, appID, AidServiceConnection)\n for appID in app_ids\n }\n self._exitpoint = Joiner(\n process=lambda values:\n {appID: values[appID] for appID in app_ids}\n )\n self.link_metric_pipeline(app_ids)\n self.input = self._entrypoint.input\n self.output = self._exitpoint.output\n\n def link_metric_pipeline(self, app_ids):\n for appID in app_ids:\n self._entrypoint.get_output(appID).connect(\n self._metric_pipeline[appID].input)\n self._metric_pipeline[appID].output.connect(\n self._exitpoint.get_input(appID))\n\n @property\n def metric(self):\n return self._metric\n\n @property\n def metric_pipeline(self):\n self._metric_pipeline\n\n def __repr__(self):\n \"\"\"Use repr(self) for DEBUG, ERROR, CRITICAL logging levels.\"\"\"\n return 'MetricPipeline {} - BaseClass: '.format(self.metric)\n\n def __str__(self):\n \"\"\"Use str(self) for INFO, WARNING logging levels.\"\"\"\n return 'MetricPipeline {}: '.format(self.metric)\n","repo_name":"navid-data-analytics/Navid-ai-project-team-work","sub_path":"src/pipeline/MetricPipeline.py","file_name":"MetricPipeline.py","file_ext":"py","file_size_in_byte":2312,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"}
+{"seq_id":"8458549463","text":"# -*- coding: utf-8 -*-\nimport utils\n\ndef index(): return dict(message=\"hello from opforms.py\")\n\n\n\n# Smart Grid for operattions documents/forms\n\n# @auth.requires_membership('admin')\n@auth.requires_login()\ndef grid():\n\n # import json\n\n branch_ids = []\n row = db(db.org_access.auth_user_id == auth.user_id ).select().first()\n if row:\n if row['pos_id'] is not None: db.point_of_sale._common_filter = lambda q: db.point_of_sale.id == row['pos_id']\n else: \n if row['branch_id'] > -1: db.point_of_sale._common_filter = lambda q: db.point_of_sale.branch_id == row['branch_id']\n else: \n if row['region_id'] > -1: \n for i in db(db.branch.region_id == r['region_id']):\n branch_ids.append(i) \n db.point_of_sale._common_filter = lambda q: db.point_of_sale.branch_id in branch_ids\n last_nos = {}\n for r in db(db.point_of_sale).select():\n last_nos[r.id] = db(db.AAP.pos_id == r.id).select(db.AAP.doc_number.max().with_alias('max_no')).first()['max_no']\n last_nos[r.id] = utils.NextSequence(last_nos[r.id])\n\n title = request.vars['title']\n action = ''\n \n if any(x in request.args for x in ['new', 'edit']):\n response.view = 'opforms/edit_AAP.html'\n action = request.args(1)\n\n tablename = request.args(0)\n if not tablename in db.tables: raise HTTP(403)\n grid = SQLFORM.grid(db[tablename], args=[tablename], deletable=False, editable=True, searchable=dict(parent=True, child=True))\n return dict(grid=grid, title=title, action=action, last_nos=last_nos)\n","repo_name":"jeffplata/nfabsm","sub_path":"controllers/opforms.py","file_name":"opforms.py","file_ext":"py","file_size_in_byte":1618,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"}
+{"seq_id":"21823806303","text":"from rest_framework import permissions\nfrom dashboard.models import Course, Learner, CourseLearner\n\nclass OwnerOrEnrolledRead(permissions.BasePermission):\n\n def has_permission(self, request, view):\n course_id = view.kwargs.get('course_pk')\n\n course = Course.objects.filter(id=course_id)\n if not course:\n return False\n if course[0].owner == request.user:\n return True\n\n\n if request.method in permissions.SAFE_METHODS:\n self.message = 'You are not registered in this Course.'\n\n learner = Learner.objects.filter(user = request.user)\n if not learner:\n return False\n\n return CourseLearner.objects.filter(course=course_id, learner=learner[0]).exists()\n else:\n self.message = 'You don\\'t have the permisstion to do this operation in this classroom.'\n return False","repo_name":"Abdelrahman-Farah/elms-backend","sub_path":"quiz_base/permissions.py","file_name":"permissions.py","file_ext":"py","file_size_in_byte":904,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"}
+{"seq_id":"21129565816","text":"\"\"\"\n 新增model2,用于求最小距离和\n 2019.5.29 by EE526\n 可以当做一种新的聚类算法\n\"\"\"\nfrom model import Situation, Model, Model2\nimport numpy as np\nimport math\nimport matplotlib.pyplot as plt\nfrom scipy.optimize import linear_sum_assignment\n\n\ndef max_assign(plane_list, target_list, superiority):\n \"\"\"\n 求最大收益\n :param plane_list: 飞机序列\n :param target_list: 目标序列\n :param superiority: 广义矩阵\n :return: 最优方案和最优值\n \"\"\"\n max_val = np.max(superiority)\n cost = max_val - superiority\n (row_ind, col_ind) = linear_sum_assignment(cost)\n best_row = []\n for i in row_ind:\n best_row.append(plane_list[i])\n best_col = []\n for i in col_ind:\n best_col.append(target_list[i])\n best_val = superiority[row_ind, col_ind].sum()\n best_plan = np.asarray([best_row, best_col])\n return best_plan, best_val\n\n\n\ndef min_assign(plane_list, target_list, superiority):\n \"\"\"\n 求最小距离和\n :param plane_list: 飞机序列\n :param target_list: 目标序列\n :param superiority: 广义矩阵\n :return: 最优方案和最优值\n \"\"\"\n cost = superiority\n (row_ind, col_ind) = linear_sum_assignment(cost)\n best_row = []\n for i in row_ind:\n best_row.append(plane_list[i])\n best_col = []\n for i in col_ind:\n best_col.append(target_list[i])\n best_val = superiority[row_ind, col_ind].sum()\n best_plan = np.asarray([best_row, best_col])\n return best_plan, best_val\n\n\nif __name__ == \"__main__\":\n num_plane = 4\n num_target = 40\n # 随机生成态势信息\n pm = np.random.random([num_plane, 2])*500.0\n pm[:, 1] = 0\n am = np.linspace(30, 120, num_plane)\n vm = np.random.randint(1, 3, [num_plane]) * 0.3\n m_num = np.random.randint(10, 12, [num_plane])\n #print(\"导弹数量\", m_num)\n pn = np.random.random([num_target, 2])*500.0+100\n pn[1:4, 1] = 600.0\n an = np.linspace(70, 200, num_target)\n vn = np.random.randint(1, 2, [num_target]) * 0.1\n priority = np.random.randint(1, 2, [num_target], dtype=int)\n #print(\"priority\", priority)\n\t\n situ = Situation(pm, am, vm, m_num, pn, an, vn, priority) # 模型初始化,类封装\n m = Model2() # 选取模型2,求最短距离,注意在下面要调用min_assign\n (plane_list, target_list, superiority) = m.get_matrix(situ)\n print(plane_list)\n print(target_list)\n #print(superiority)\n\n (best_plan, best_val) = min_assign(plane_list, target_list, superiority)\n print(\"方案\")\n print(best_plan)\n print(best_val)\n \"\"\"\n 画图\n \"\"\"\n #print(\"飞机位置\", pm)\n plt.rcParams['font.sans-serif'] = ['SimHei']\n plt.rcParams['axes.unicode_minus'] = False\n plt.scatter(pm[:, 0], pm[:, 1], color='r', label='无人机位置')\n plt.scatter(pn[:, 0], pn[:, 1], color='g', label='目标位置')\n plt.legend(loc='upper right')\n plt.quiver(pm[:, 0], pm[:, 1], np.cos(am/360*2*np.pi), np.sin(am/360*2*math.pi))\n plt.quiver(pn[:, 0], pn[:, 1], np.cos(an/360*2*math.pi), np.sin(an/360*2*math.pi))\n for i in range(best_plan.shape[1]):\n plt.plot([pm[best_plan[0, i], 0], pn[best_plan[1, i], 0]],\n [pm[best_plan[0, i], 1], pn[best_plan[1, i], 1]], color='y')\n plt.show()\n\n\n\n\n\n","repo_name":"Sherhang/MyStudy","sub_path":"Python/匈牙利算法/求最短距离/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":3303,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"21"}
+{"seq_id":"36683573434","text":"import json\nimport os\nimport io\nimport paramiko\nimport concurrent.futures\n\ndef threaded(func):\n def wrapper(*args, **kwargs):\n with concurrent.futures.ThreadPoolExecutor() as executor:\n try:\n result = executor.submit(func, *args, **kwargs)\n except Exception as e:\n print(f\"Exception occurred in 'executor.submit' on '@threaded' decorator: {e}\")\n return result\n return wrapper\n\n@threaded\ndef deploy(vps_info, username, command, ssh_key):\n try:\n ssh_client = paramiko.SSHClient()\n ssh_client.set_missing_host_key_policy(paramiko.AutoAddPolicy())\n\n if ssh_key:\n pkey = paramiko.RSAKey.from_private_key(io.StringIO(ssh_key))\n try:\n ssh_client.connect(vps_info['address'], port=vps_info['port'], pkey=pkey, username=username, timeout=5)\n except Exception as e:\n print(f\"SSH error by KEY auth: {e.message}\")\n\n else:\n try:\n ssh_client.connect(vps_info['address'], port=vps_info['port'], password=vps_info['pwd'], username=username, timeout=5)\n except Exception as e:\n print(f\"SSH error by PASSWORD auth: {e.message}\")\n\n except Exception as e:\n print(e.message)\n\n stdin, stdout, stderr = ssh_client.exec_command(command)\n for line in stdout:\n print(line)\n \n \nif __name__ == '__main__':\n\n vps_list_file = os.environ[\"VPS_LIST_FILE\"]\n deploy_command_file = os.environ[\"DEPLOY_COMMAND\"]\n ssh_key = os.environ[\"SSH_KEY\"]\n username = os.environ[\"USERNAME\"]\n \n\n try:\n with open(vps_list_file, 'r') as f:\n vps_list = json.load(f)\n except:\n print(f\"Error reading VPS list file: {vps_list_file}\")\n\n try:\n if os.path.isfile(deploy_command_file):\n with open(deploy_command_file, 'r') as f:\n deploy_command = f.read()\n except:\n print(\"Error reading deploy commands\")\n\n with concurrent.futures.ThreadPoolExecutor() as executor:\n try:\n future_list = [(executor.submit(deploy, vps_info, username, deploy_command, ssh_key), vps_info, id) for id, vps_info in enumerate(vps_list)]\n except Exception as e:\n print(f\"Exception occurred in 'future_list' list comprehension: {e}\")\n \n for future, vps_info, id in future_list:\n try:\n result = future.result()\n\n except Exception as e:\n # Captura qualquer exceção lançada pela função deploy\n print(f\"[!] Error on thread id: {id}, VPS: {vps_info['address']}:{vps_info['port']}, Erro: {e}\")\n \n if not result.exception():\n print(f\"[OK] Command execution on VPS: {vps_info['address']}:{vps_info['port']}, Thread id: {id}, {result}\")\n else:\n print(f\"[!] Erro on VPS: {vps_info['address']}:{vps_info['port']}, Thread id: {id}, {result}\")\n","repo_name":"usrbinbrain/sshugger","sub_path":"entrypoint.py","file_name":"entrypoint.py","file_ext":"py","file_size_in_byte":2934,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"21"}
+{"seq_id":"3201708253","text":"import tensorflow as tf\r\nimport cv2 as cv\r\nimport os\r\nimport numpy as np\r\n\r\n\r\nIMAGE_HIGTH = 54\r\nIMAGE_WIDTH = 96\r\nIMAGE_CHANNELS = 3\r\n\r\nBATCH_SIZE = 10\r\n\r\n# train_data\\\r\n# cartoon\\\r\n# 1.jpg\r\n# 2.jpg\r\n# .\r\n# .\r\n# real\\\r\n# 1.jpg\r\n# 2.jpg\r\n# .\r\n# .\r\n\r\n\r\ndef get_path(path):\r\n path_list = []\r\n name_list = os.listdir(path)\r\n for name in name_list:\r\n path_list.append(path+'\\\\'+name)\r\n return name_list, path_list\r\n\r\n\r\n# 生成整数型属性(图像标签)\r\ndef _int64_feature(value):\r\n return tf.train.Feature(int64_list=tf.train.Int64List(value=[value]))\r\n\r\n\r\n# 生成字符串型属性(图像矩阵数据)\r\ndef _bytes_feature(value):\r\n return tf.train.Feature(bytes_list=tf.train.BytesList(value=[value]))\r\n\r\n\r\n# 生成 tfrecord 模型\r\ndef generate_tfrecords(path, tf_path):\r\n recordfilenum = 0\r\n bestnum = 1000 # 每个 tfrecord 存放图片的个数\r\n best_counter = 0 # 第几个图片\r\n tfrecord_p = tf_path + '\\\\' + ('train.tfrecord-%.2d' % recordfilenum)\r\n tfrecord_writer = tf.python_io.TFRecordWriter(tfrecord_p)\r\n class_name, class_path = get_path(path)\r\n\r\n for index, class_label in enumerate(class_name):\r\n img_name, img_path = get_path(class_path[index])\r\n print(class_label)\r\n for i in range(len(img_path)):\r\n best_counter += 1\r\n if best_counter % 100 == 0:\r\n print(\"已经处理\", best_counter, \"个\")\r\n if best_counter % bestnum == 0:\r\n recordfilenum += 1\r\n tfrecord_p = tf_path + '\\\\' + ('train.tfrecord-%.2d' % recordfilenum)\r\n tfrecord_writer = tf.python_io.TFRecordWriter(tfrecord_p)\r\n\r\n img = cv.imread(img_path[i], 1)\r\n img1 = cv.resize(img, (IMAGE_WIDTH, IMAGE_HIGTH), 0, 0, cv.INTER_LINEAR)\r\n img1 = img1 / 255.0\r\n img_raw = img1.tostring()\r\n example = tf.train.Example(features=tf.train.Features(feature={\r\n 'label': _int64_feature(index),\r\n 'image_raw': _bytes_feature(img_raw)\r\n }))\r\n tfrecord_writer.write(example.SerializeToString())\r\n tfrecord_writer.close()\r\n\r\n\r\n# 读取tfrecords\r\ndef read_tfrecords(path):\r\n files = tf.train.match_filenames_once(path)\r\n filename_sqeue = tf.train.string_input_producer(files, shuffle=True)\r\n reader = tf.TFRecordReader()\r\n _, serialized_example = reader.read(filename_sqeue)\r\n features = tf.parse_single_example(serialized_example,\r\n features={\r\n 'label': tf.FixedLenFeature([], tf.int64),\r\n 'image_raw': tf.FixedLenFeature([], tf.string)\r\n })\r\n image = tf.decode_raw(features['image_raw'], tf.float64)\r\n label = features['label']\r\n imaged = tf.reshape(image, [IMAGE_HIGTH, IMAGE_WIDTH, IMAGE_CHANNELS])\r\n imaged = imaged * 255.0\r\n\r\n min_after_dequeue = 1000\r\n capacity = min_after_dequeue + BATCH_SIZE * 3\r\n image_batch0, label_batch0 = tf.train.shuffle_batch(\r\n [imaged, label], batch_size=BATCH_SIZE,\r\n capacity=capacity, min_after_dequeue=min_after_dequeue)\r\n\r\n with tf.Session() as sess:\r\n sess.run((tf.global_variables_initializer(), tf.local_variables_initializer()))\r\n coord = tf.train.Coordinator()\r\n threads = tf.train.start_queue_runners(sess=sess, coord=coord)\r\n\r\n num = 0\r\n for i in range(10):\r\n image_batch, label_batch = sess.run([image_batch0, label_batch0])\r\n label_one_hot = np.zeros((BATCH_SIZE, 2), dtype=float)\r\n for j in range(len(label_batch)):\r\n label_one_hot[j, label_batch[j]] = 1.0\r\n print(label_one_hot[j])\r\n cv.imwrite(r'l:\\ver'+'\\\\'+str(label_one_hot[j])+'_'+str(num)+'.jpg', image_batch[j])\r\n num += 1\r\n # print(sess.run([image,label,high,width]))\r\n\r\n coord.request_stop()\r\n coord.join(threads)\r\n\r\n\r\ndef main():\r\n orig_path = r'L:\\train_data' # 图像数据原始地址\r\n tfrecord_path = r\"L:\\train_tfrecords\" # 保存的 tfrecord 路径\r\n generate_tfrecords(orig_path, tfrecord_path) # 生成 tfrecord 模型\r\n \r\n # tfrcord 路径\r\n tfrecord_files = r\"L:\\train_tfrecords\\train.tfrecord-*\"\r\n # read_tfrecords(tfrecord_files)\r\n\r\n\r\nif __name__ == \"__main__\":\r\n main()\r\n","repo_name":"shangranli/video_label","sub_path":"generate_tfrecords.py","file_name":"generate_tfrecords.py","file_ext":"py","file_size_in_byte":4647,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"}
+{"seq_id":"72966499572","text":"# encoding=UTF-8\n\nimport threading\nimport time\nimport sys\nimport traceback\nimport select\nimport inspect\nimport logging\n\nfrom websocket_abnf import ABNF\nfrom websocket_exceptions import *\nfrom websocket_core import WebSocket, getdefaulttimeout, logger\n\nclass WebSocketApp(object):\n\n def __init__(self, url, header = [],\n on_open = None, on_message = None, on_error = None,\n on_close = None, on_ping = None, on_pong = None,\n on_cont_message = None,\n keep_running = True, get_mask_key = None, cookie = None,\n subprotocols = None):\n \"\"\"\n url: websocket url.\n header: custom header for websocket handshake.\n on_open: callable object which is called at opening websocket.\n this function has one argument. The arugment is this class object.\n on_message: callbale object which is called when received data.\n on_message has 2 arguments.\n The 1st arugment is this class object.\n The passing 2nd arugment is utf-8 string which we get from the server.\n on_error: callable object which is called when we get error.\n on_error has 2 arguments.\n The 1st arugment is this class object.\n The passing 2nd arugment is exception object.\n on_close: callable object which is called when closed the connection.\n this function has one argument. The arugment is this class object.\n on_cont_message: callback object which is called when recieve continued frame data.\n on_message has 3 arguments.\n The 1st arugment is this class object.\n The passing 2nd arugment is utf-8 string which we get from the server.\n The 3rd arugment is continue flag. if 0, the data continue to next frame data\n keep_running: a boolean flag indicating whether the app's main loop should\n keep running, defaults to True\n get_mask_key: a callable to produce new mask keys, see the WebSocket.set_mask_key's\n docstring for more information\n subprotocols: array of available sub protocols. default is None.\n \"\"\"\n self.url = url\n self.header = header\n self.cookie = cookie\n self.on_open = on_open\n self.on_message = on_message\n self.on_error = on_error\n self.on_close = on_close\n self.on_ping = on_ping\n self.on_pong = on_pong\n self.on_cont_message = on_cont_message\n self.keep_running = keep_running\n self.get_mask_key = get_mask_key\n self.sock = None\n self.last_ping_tm = 0\n self.subprotocols = subprotocols\n\n def send(self, data, opcode = ABNF.OPCODE_TEXT):\n if not self.sock or self.sock.send(data, opcode) == 0:\n raise WebSocketConnectionClosedException()\n\n def close(self):\n self.keep_running = False\n if self.sock:\n self.sock.close()\n\n def _send_ping(self, interval, event):\n while not event.wait(interval):\n self.last_ping_tm = time.time()\n if self.sock:\n self.sock.ping()\n\n def _callback(self, callback, *args):\n if callback:\n try:\n callback(self, *args)\n except Exception as e:\n logger.error(e)\n if logger.isEnabledFor(logging.DEBUG):\n _, _, tb = sys.exc_info()\n traceback.print_tb(tb)\n\n def _get_close_args(self, data):\n if not self.on_close or len(inspect.getargspec(self.on_close).args):\n return []\n\n if data and len(data) >= 2:\n code = 256 * data[0] + data[1]\n reason = data[2:].decode('utf-8')\n return [code, reason]\n\n return [None, None]\n\n def run_forever(self, sockopt = None, sslopt = None, ping_interval = 0, ping_timeout = None,\n http_proxy_host = None, http_proxy_port = None, http_no_proxy = None, http_proxy_auth = None):\n if not ping_timeout or ping_timeout <= 0:\n ping_timeout = None\n if sockopt is None:\n sockopt = []\n if sslopt is None:\n sslopt = {}\n if self.sock:\n raise WebSocketException('socket is already opened')\n thread = None\n close_frame = None\n\n try:\n self.sock = WebSocket(self.get_mask_key, sockopt = sockopt, sslopt = sslopt,\n fire_cont_frame = self.on_cont_message and True or False)\n self.sock.settimeout(getdefaulttimeout())\n self.sock.connect(self.url, header = self.header, cookie = self.cookie,\n http_proxy_host = http_proxy_host, http_proxy_port = http_proxy_port,\n http_no_proxy = http_no_proxy, http_proxy_auth = http_proxy_auth,\n subprotocols = self.subprotocols)\n self._callback(self.on_open)\n\n if ping_interval:\n event= threading.Event()\n thread = threading.Thread(target = self._send_ping, args = (ping_interval, event))\n thread.setDeamon(True)\n thread.start()\n\n while self.sock.connected:\n r, w, e = select.select((self.sock.sock, ), (), (), ping_timeout)\n if not self.keep_running:\n break\n if ping_timeout and self.last_ping_tm and time.time() - self.last_ping_tm > ping_timeout:\n self.last_ping_tm = 0\n raise WebSocketTimeoutException()\n\n if r:\n op_code, frame = self.sock.recv_data_frame(True)\n if op_code == ABNF.OPCODE_CLOSE:\n close_frame = frame\n break\n elif op_code == ABNF.OPCODE_PING:\n self._callback(self.on_ping, frame.data)\n elif op_code == ABNF.OPCODE_PONG:\n self._callback(self.on_pong, frame.data)\n elif op_code == ABNF.OPCODE_CONT and self.on_cont_message:\n self._callback(self.on_cont_message, frame.data, frame.fin)\n else:\n data = frame.data\n if frame.opcode == ABNF.OPCODE_TEXT:\n data = data.decode('utf-8')\n self._callback(self.on_message, data)\n except Exception as e:\n self._callback(self.on_error, e)\n finally:\n if thread:\n event.set()\n thread.join()\n self.keep_running = False\n self.sock.close()\n tmpdata = close_frame.data if close_frame else None\n self._callback(self.on_close, *self._get_close_args(tmpdata))\n self.sock = None\n","repo_name":"gnaggnoyil/okcoin-libinterface","sub_path":"websocket_app.py","file_name":"websocket_app.py","file_ext":"py","file_size_in_byte":6861,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"21"}
+{"seq_id":"19479237272","text":"import sqlite3 as sql\r\n\r\nsehirler=[\"Adana\", \"Adıyaman\", \"Afyonkarahisar\", \"Ağrı\", \"Aksaray\", \"Amasya\", \"Ankara\", \"Antalya\", \"Ardahan\", \"Artvin\", \"Aydın\", \"Balıkesir\", \"Bartın\", \"Batman\", \"Bayburt\", \"Bilecik\", \"Bingöl\", \"Bitlis\", \"Bolu\", \"Burdur\", \"Bursa\", \"Çanakkale\", \"Çankırı\", \"Çorum\", \"Denizli\", \"Diyarbakır\", \"Düzce\", \"Edirne\", \"Elazığ\", \"Erzincan\", \"Erzurum\", \"Eskişehir\", \"Gaziantep\", \"Giresun\", \"Gümüşhane\", \"Hakkâri\", \"Hatay\", \"Iğdır\", \"Isparta\", \"İstanbul\", \"İzmir\", \"Kahramanmaraş\", \"Karabük\", \"Karaman\", \"Kars\", \"Kastamonu\", \"Kayseri\", \"Kilis\", \"Kırıkkale\", \"Kırklareli\", \"Kırşehir\", \"Kocaeli\", \"Konya\", \"Kütahya\", \"Malatya\", \"Manisa\", \"Mardin\", \"Mersin\", \"Muğla\", \"Muş\", \"Nevşehir\", \"Niğde\", \"Ordu\", \"Osmaniye\", \"Rize\", \"Sakarya\", \"Samsun\", \"Şanlıurfa\", \"Siirt\", \"Sinop\", \"Sivas\", \"Şırnak\", \"Tekirdağ\", \"Tokat\", \"Trabzon\", \"Tunceli\", \"Uşak\", \"Van\", \"Yalova\", \"Yozgat\", \"Zonguldak\"]\r\n\r\ndb=sql.connect(r\"C:\\Users\\LENOVO\\Desktop\\python_kurs\\grup0041\\bahadir\\kütüphane4.db\")#veri tabanını oluşturuduk\r\nkostebek=db.cursor() #veri tabanına işleme için gerekli komut\r\n\r\n\r\n\r\n\r\nfor i in sehirler:\r\n kostebek.execute(f\"\"\"\r\nINSERT INTO sehirler(adi) VALUES ('{i}');\"\"\")\r\n\r\ndb.commit()\r\nkostebek.close()\r\ndb.close()\r\n\r\nprint(\"kayıt başarılı...\")\r\n\r\n","repo_name":"Bsamur/python_uygulama_ornekleri","sub_path":"NİYAZİ HOCA ÖRNEK.py","file_name":"NİYAZİ HOCA ÖRNEK.py","file_ext":"py","file_size_in_byte":1308,"program_lang":"python","lang":"jv","doc_type":"code","stars":1,"dataset":"github-code","pt":"21"}
+{"seq_id":"6550252702","text":"# Import required libraries\nimport sys\nimport RPi.GPIO as GPIO\nimport time\n\nclass SevSegDisp():\n \n\n# print(str(get_counter()))\n# toDisplay= str(get_counter()) # numbers and digits to display\n def __init__(self):\n print(\"initializing ssd\")\n self.toDisplay = \"0000\"\n\n self.delay = 0.005 # delay between digits refresh\n\n# --------------------------------------------------------------------\n# PINS MAPPING AND SETUP\n# selDigit activates the 4 digits to be showed (0 is active, 1 is unactive)\n# display_list maps segments to be activated to display a specific number inside the digit\n# digitDP activates Dot led\n# --------------------------------------------------------------------\n\n self.selDigit = [14,15,18,23]\n# Digits: 1, 2, 3, 4\n\n self.display_list = [24,25,8,7,1,12,16] # define GPIO ports to use\n#disp.List ref: A ,B ,C,D,E,F ,G\n\n self.digitDP = 20\n#DOT = GPIO 20\n \n # DIGIT map as array of array ,\n #so that arrSeg[0] shows 0, arrSeg[1] shows 1, etc\n self.arrSeg = [[0,0,0,0,0,0,1],\\\n [1,0,0,1,1,1,1],\\\n [0,0,1,0,0,1,0],\\\n [0,0,0,0,1,1,0],\\\n [1,0,0,1,1,0,0],\\\n [0,1,0,0,1,0,0],\\\n [0,1,0,0,0,0,0],\\\n [0,0,0,1,1,1,1],\\\n [0,0,0,0,0,0,0],\\\n [0,0,0,0,1,0,0]]\n \n self.ssd_GPIO = GPIO\n\n def gpio_init(self):\n# Use BCM GPIO references instead of physical pin numbers\n self.ssd_GPIO.setmode(self.ssd_GPIO.BCM)\n\n # Set all pins as output\n self.ssd_GPIO.setwarnings(False)\n for pin in self.display_list:\n self.ssd_GPIO.setup(pin,self.ssd_GPIO.OUT) # setting pins for segments\n for pin in self.selDigit:\n self.ssd_GPIO.setup(pin,self.ssd_GPIO.OUT) # setting pins for digit selector\n self.ssd_GPIO.setup(self.digitDP,self.ssd_GPIO.OUT) # setting dot pin\n self.ssd_GPIO.setwarnings(True)\n\n self.ssd_GPIO.output(self.digitDP,0) # DOT pin\n\n# --------------------------------------------------------------------\n# MAIN FUNCTIONS\n# splitToDisplay(string) split a string containing numbers and dots in\n# an array to be showed\n# showDisplay(array) activates DIGITS according to array. An array\n# element to space means digit deactivation\n# --------------------------------------------------------------------\n\n def showDisplay(self, digit):\n for i in range(0, 4): #loop on 4 digits selectors (from 0 to 3 included)\n sel = [0,0,0,0]\n sel[i] = 1\n self.ssd_GPIO.output(self.selDigit, sel) # activates selected digit\n \n# print(\"Digit:\", digit)\n \n if digit[i].replace(\".\", \"\") == \".\": # space disables digit\n self.ssd_GPIO.output(self.display_list,0)\n continue\n numDisplay = int(digit[i].replace(\".\", \"\"))\n self.ssd_GPIO.output(self.display_list, self.arrSeg[numDisplay]) # segments are activated according to digit mapping\n if digit[i].count(\".\") == 0:\n self.ssd_GPIO.output(self.digitDP,1)\n else:\n self.ssd_GPIO.output(self.digitDP,0)\n time.sleep(self.delay)\n\n def splitToDisplay (self, toDisplay): # splits string to digits to display\n \n# print(\"toDisplay:\", toDisplay)\n \n arrToDisplay=list(toDisplay)\n for i in range(len(arrToDisplay)):\n if arrToDisplay[i] == \".\": arrToDisplay[(i-1)] = arrToDisplay[(i-1)] + arrToDisplay[i] # dots are concatenated to previous array element\n while \".\" in arrToDisplay: arrToDisplay.remove(\".\") # array items containing dot char alone are removed\n \n# print(\"ArrToDisplay:\", arrToDisplay)\n \n return arrToDisplay\n\n # --------------------------------------------------------------------\n # MAIN LOOP\n # persistence of vision principle requires that digits are powered\n # on and off at a specific speed. So main loop continuously calls\n # showDisplay function in an infinite loop to let it appear as\n # stable numbers display\n # --------------------------------------------------------------------\n\n def SSD_show(self, displayvar):\n try:\n self.gpio_init()\n if displayvar is None or displayvar == \"\":\n print(\"Displayvar is None\")\n displayvar = \"0000\"\n print(\"Displayvar:\", displayvar)\n while True:\n self.showDisplay(self.splitToDisplay(displayvar))\n time.sleep(0.01)\n \n \n except KeyboardInterrupt:\n print('interrupted!')\n self.ssd_GPIO.cleanup()\n sys.exit()\n #copytest1\n\n\n","repo_name":"PaulAtiksh16/Cense","sub_path":"static/ssd_folder/seg4DigitDisplay.py","file_name":"seg4DigitDisplay.py","file_ext":"py","file_size_in_byte":4631,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"}
+{"seq_id":"5268628926","text":"import torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport torch.optim as optim\n\n\n# lstm = nn.LSTM(3, 3) # Input dim is 3, output dim is 3\n# inputs = [torch.randn(1, 3) for _ in range(5)]\n# # print(inputs)\n# hidden = (torch.rand(1, 1, 3), torch.rand(1, 1, 3))\n# # for i in inputs:\n# # out, hidden = lstm(i.view(1, 1, 3), hidden)\n\n# out, hidden = lstm(torch.cat(inputs).view(-1, 1, 3), hidden)\n\n# print(\"hidded:\", hidden)\n# print(\"Out:\", out)\n\ntraining_data = [\n \"A lovely day, isn’t it\".split(),\n \"Do I have to\".split(),\n \"Can I help you\".split(),\n \"How are things going\".split(),\n \"Any thing else\".split(),\n \"Are you kidding\".split(),\n \"Are you sure\".split(),\n \"Do you understand me\".split(),\n \"Are you done\".split(),\n \"Can I ask you something\".split(),\n \"Can you please repeat that\".split(),\n \"Did you get it\".split(),\n]\n\n# print(training_data)\n\nword_to_ix = {}\nfor sent in training_data:\n for word in sent:\n if word not in word_to_ix: # word has not been assigned an index yet\n word_to_ix[word] = len(word_to_ix) # Assign each word with a unique index\nprint(\"len(word_to_ix):\", len(word_to_ix))\n\n# print(HOTVECTOR)\ndef prepare_sequence(seq, to_ix=word_to_ix):\n idxs = [to_ix[w] for w in seq]\n return torch.tensor(idxs, dtype=torch.long)\n\n# print(prepare_sequence(training_data[2]))\n\nEMBEDDING_DIM = HIDDEN_DIM = len(word_to_ix)\nclass LSTMTagger(nn.Module):\n def __init__(self, embedding_dim, hidden_dim, vocab_size):\n super(LSTMTagger, self).__init__()\n self.hidden_dim = hidden_dim\n self.embedding_dim = embedding_dim\n self.word_embeddings = nn.Embedding(vocab_size, embedding_dim)\n self.rnn = nn.GRU(embedding_dim, hidden_dim)\n\n def forward(self, sentence):\n embeds = self.word_embeddings(sentence)\n lstm_out, _ = self.rnn(embeds.view(-1, 1, self.embedding_dim))\n return lstm_out\n\nmodel = LSTMTagger(EMBEDDING_DIM, HIDDEN_DIM, len(word_to_ix))\nloss_function = nn.CrossEntropyLoss()\noptimizer = optim.SGD(model.parameters(), lr=0.1)\nMODEL_PATH = \"./lstm_wordprediction.pt\"\ntry:\n model.load_state_dict(torch.load(MODEL_PATH))\n print(\"Model parameters were loaded from:\", MODEL_PATH)\nexcept:\n pass\n\nwith torch.no_grad():\n inputs = prepare_sequence(training_data[0], word_to_ix)\n print(\"inputs.shape:\", inputs.shape)\n output = model(inputs[:-1]) # Feed the model of N-1 words and expect the last word\n print(\"Expected word index:\", inputs[-1])\n print(\"Output word index:\", output[-1].argmax(1))\n\nfor epoch in range(300):\n for sentence in training_data:\n model.zero_grad()\n sentence_in = prepare_sequence(sentence, word_to_ix)\n\n sentence_out = model(sentence_in[:-1]) # input 0 to N-1 words, and train the model to generate 1 to N\n labels = sentence_in[1:]\n loss = loss_function(sentence_out.view(len(sentence_out),-1), labels) # Train the model to generate 1 to N\n loss.backward()\n optimizer.step()\n print(f\"loss: {loss:>7f}\")\n\ntorch.save(model.state_dict(), MODEL_PATH)\n\nwith torch.no_grad():\n correctSeq = 0\n for sentence in training_data:\n inputs = prepare_sequence(sentence, word_to_ix)\n output = model(inputs[:-1]) # Feed the model of N-1 words and expect the last word\n # print(\"Expected word index:\", inputs[-1].argmax(0))\n # print(\"Output word index:\", output[-1].argmax(1))\n correctSeq +=1 if inputs[-1] == output[-1].argmax(1) else 0\n print(\"Accuracy:\", correctSeq / len(training_data))\n\n","repo_name":"mmbahnasy/NeuralNetworkTutorial","sub_path":"lstm.py","file_name":"lstm.py","file_ext":"py","file_size_in_byte":3571,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"}
+{"seq_id":"15627095490","text":"import logging\nimport os\nfrom posixpath import join\nimport subprocess\n\nfrom opp import subcommands\n\nlogger = logging.getLogger(__name__)\npull_parser = subcommands.add_parser('pull')\npull_parser.add_argument('repository',\n help='/ path. e.g.: bencord0/opp')\npull_parser.add_argument('--mirror', '-m',\n default='https://github.com',\n help='Base url to pull from')\npull_parser.add_argument('--path', default=None,\n help='directory to clone the repostoy too')\n\ndef pull(args):\n logger.info('pull: {}'.format(args))\n\n path = args.path or args.repository\n if os.path.exists(path):\n os.chdir(path)\n subprocess.check_call(['git', 'pull'])\n\n else:\n clone_command = [\n 'git', 'clone', join(args.mirror, args.repository), path]\n subprocess.check_call(clone_command)\n","repo_name":"bencord0/opp","sub_path":"opp/commands/pull.py","file_name":"pull.py","file_ext":"py","file_size_in_byte":916,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"}
+{"seq_id":"73586202292","text":"import os\nfrom pathlib import Path\nimport urllib.parse\n\nimport pyodbc\nfrom dotenv import load_dotenv, find_dotenv\n\nload_dotenv()\n\ndefault_mssql_driver = None\nfor available_driver in pyodbc.drivers():\n if available_driver.find('SQL SERVER'):\n default_mssql_driver = available_driver\n\n\ndef get_project_root() -> Path:\n return Path(os.path.dirname(os.path.abspath(__file__)))\n\n\nPROJECT_ROOT = get_project_root()\n\n\n# Validation of configs\ndef is_valid():\n for validator in VALIDATORS: # Validators found at bottom of file\n validator()\n\n\ndef validate_able_to_find_dotenv_file():\n if find_dotenv() == '':\n raise NotConfiguredCorrectlyError(\n f'No .env file found. Refer to Readme.md for proper configuration. '\n f'Locations looked at started here {__file__}'\n )\n\n\n# Settings that effect behavior\ndef get_authorization_usage_status() -> bool:\n use_auth = os.getenv('USE_AUTH', True)\n if use_auth in ['False', 'false', '0']:\n return False\n return bool(use_auth)\n\n\ndef get_testing_status() -> bool:\n testing = os.getenv('CI', False)\n if testing is False:\n return False\n if testing.lower() in ['false', '0']:\n return False\n return bool(testing)\n\n\n# Settings that effect locations\ndef get_mssql_uri() -> str:\n user = os.getenv('MSSQL_USER', None)\n password = os.getenv('MSSQL_PASSWORD', None)\n server = os.getenv('MSSQL_SERVER', 'production')\n database = os.getenv('MSSQL_DATABASE', 'custom')\n driver = urllib.parse.quote_plus(os.getenv('MSSQL_DRIVER', default_mssql_driver))\n return f'mssql+pyodbc://{user}:{password}@{server}/{database}?driver={driver}'\n\n\ndef validate_mssql_uri() -> None:\n database_uri = get_mssql_uri().lower()\n if r'mssql+pyodbc://none:none' in database_uri:\n raise NotConfiguredCorrectlyError(f'MSSQL url .env variables not set correctly please refer to Readme.md')\n if 'production' in database_uri and get_testing_status():\n raise NotConfiguredCorrectlyError(\n 'Set Database to something other than production. Tests remove all data in the database'\n )\n\n\ndef get_logging_folder() -> Path:\n logging_folder = os.getenv('LOGGING_FOLDER', PROJECT_ROOT)\n return Path(logging_folder)\n\n\ndef get_load_file_save_location() -> Path:\n save_location = os.getenv('BATCH_LOAD_FILE_SAVE_LOCATION', PROJECT_ROOT)\n return Path(save_location)\n\n\ndef get_connect_remittance_hot_folder() -> Path:\n hot_folder = os.getenv('CONNECT_REMITTANCE_HOT_FOLDER', PROJECT_ROOT)\n return Path(hot_folder)\n\n\ndef get_email_host_and_port() -> dict:\n host = os.getenv('EMAIL_HOST', 'mailhog')\n port = 1025 if host in ('mailhog', '127.0.0.1') else 25\n http_port = 8025\n return {'host': host, 'port': port, 'http_port': http_port}\n\n\ndef get_import_je_save_location() -> Path:\n save_location = os.getenv('IMPORT_JE_SAVE_LOCATION', PROJECT_ROOT)\n return Path(save_location)\n\n\n# HTTP Settings\ndef get_flask_secret_key():\n secret_key = os.getenv('FLASK_SECRET_KEY', b'\\x91\\x909\\x1aO\\x12a\\xd6N\\x14(\\x9c\\x93[6E')\n return secret_key\n\n\ndef validate_flask_secret_key():\n testing = get_testing_status()\n secret_key = get_flask_secret_key()\n unsecure_flask_key = b'\\x95\\x907\\x1aO\\x12a\\xd6N\\x14(\\x9c\\x93[6E'\n if not testing and secret_key == unsecure_flask_key:\n raise NotConfiguredCorrectlyError(f'Set a secure flask key when in production. Please refer to Readme.md')\n \n\ndef get_url_prefix():\n prefix = os.getenv('URL_PREFIX', '/')\n if prefix[0] != '/':\n prefix = '/' + prefix\n if prefix[-1] != '/':\n prefix = prefix + '/'\n return prefix\n\n\ndef get_url_root():\n url_root = os.getenv('URL_ROOT', 'http://127.0.0.1')\n if url_root[-1] == '/':\n return url_root[:-1]\n return url_root\n\n\ndef validate_url_root():\n url_root = get_url_root()\n http_part = url_root[:8]\n if 'https://' not in http_part and 'http://' not in http_part:\n raise NotConfiguredCorrectlyError(\n f'The URL root should include either http:// or https:// at the beginning. Current value is {url_root}'\n )\n testing = get_testing_status()\n if not testing and ('127.0.0.1' in url_root or '0.0.0.0' in url_root):\n raise NotConfiguredCorrectlyError(f'Url root must be specified in production. Current value is {url_root}')\n\n\nVALIDATORS = [\n validate_able_to_find_dotenv_file,\n validate_mssql_uri,\n validate_flask_secret_key,\n validate_url_root,\n]\n\n\nclass NotConfiguredCorrectlyError(ValueError):\n pass\n","repo_name":"daniel-butler/guide","sub_path":"example_config.py","file_name":"example_config.py","file_ext":"py","file_size_in_byte":4558,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"}
+{"seq_id":"99560074","text":"from Controller import Controller\nfrom model import ModelManager, Models\nfrom FileDialogController import FileDialogController\nfrom view.FileDialogView import FileDialogView\nimport Smelted_Settings\nfrom gi.repository import GObject, Gtk\nimport os\nimport math\n\n\nclass MainInterfaceController(Controller):\n\n\tmelted_telnet_controller = None\n\tmain_controller = None\n\tfile_dialog_controller = None\n\n\tplaylist_list_store = None\n\tunit_list_store = None\n\tend_event_list_store = None\n\n\tend_event_list_items = None\n\n\tunit_tree_view = None\n\tplaylist_tree_view = None\n\n\tin_slider_view = None\n\tout_slider_view = None\n\tin_slider_label_view = None\n\tout_slider_label_view = None\n\n\trefreshing_clips = False\n\n\tprogress_label = None\n\n\tdef __init__(self, main_controller, melted_telnet_controller):\n\t\tself.main_controller = main_controller\n\t\tself.melted_telnet_controller = melted_telnet_controller\n\n\tdef on_view_added(self, view):\n\t\tself.view.window.set_title(Smelted_Settings.program_title)\n\t\tself.playlist_list_store = self.view.builder.get_object(\"playlist_list_store\")\n\t\tself.unit_list_store = self.view.builder.get_object(\"unit_list_store\")\n\t\tself.unit_tree_view = self.view.builder.get_object(\"unit_tree_view\")\n\t\tself.playlist_tree_view = self.view.builder.get_object(\"playlist_tree_view\")\n\t\tself.progress_label = self.view.builder.get_object(\"progress_label\")\n\n\t\tself.in_slider_view = self.view.builder.get_object(\"in_slider\")\n\t\tself.out_slider_view = self.view.builder.get_object(\"out_slider\")\n\n\t\tself.in_slider_label_view = self.view.builder.get_object(\"in_slider_label\")\n\t\tself.out_slider_label_view = self.view.builder.get_object(\"out_slider_label\")\n\n\t\t# create combo box column on playlist tree view, should be moved to view if time allows\n\t\tend_event_list_store = Gtk.ListStore(str)\n\t\tself.end_event_list_items = [\"Stop\", \"Loop\", \"Continue\", \"Pause\"]\n\t\tfor item in self.end_event_list_items:\n\t\t\tend_event_list_store.append([item])\n\n\t\trenderer_combo = Gtk.CellRendererCombo()\n\t\trenderer_combo.set_property(\"editable\", True)\n\t\trenderer_combo.set_property(\"model\", end_event_list_store)\n\t\trenderer_combo.set_property(\"text-column\", 0)\n\t\trenderer_combo.set_property(\"has-entry\", False)\n\t\trenderer_combo.connect(\"edited\", self.on_combo_changed)\n\n\t\tcolumn_combo = Gtk.TreeViewColumn(\"Unit Ended Event\", renderer_combo, text=1)\n\t\tself.unit_tree_view.append_column(column_combo)\n\n\t\tModelManager.register_on_model_added_callback(self.refresh_clips, ModelManager.MODEL_CLIP)\n\t\tModelManager.register_on_model_added_callback(self.add_unit, ModelManager.MODEL_UNIT)\n\t\tModelManager.register_on_model_list_emptied_callback(self.remove_units, ModelManager.MODEL_UNIT)\n\n\t\tModelManager.register_on_attribute_changed_callback(self.update_seek_progress, Models.Clip.CLIP_PROGRESS)\n\n\tdef add_file_handler(self, paths):\n\t\tif len(paths) > 0:\n\t\t\tpath = paths[0]\n\t\t\tself.melted_telnet_controller.append_clip_to_queue(Smelted_Settings.current_unit, path)\n\t\t\tself.main_controller.get_units_controller().find_clips_on_unit(Smelted_Settings.current_unit)\n\t\telse:\n\t\t\tprint(\"No file selected\")\n\n\tdef play_handler(self):\n\t\tself.melted_telnet_controller.play_clip(Smelted_Settings.current_unit)\n\n\tdef pause_handler(self):\n\t\tself.melted_telnet_controller.pause_clip(Smelted_Settings.current_unit)\n\n\tdef stop_handler(self):\n\t\tself.melted_telnet_controller.stop_clip(Smelted_Settings.current_unit)\n\n\tdef next_clip_handler(self):\n\t\tself.melted_telnet_controller.next_clip(Smelted_Settings.current_unit)\n\n\tdef previous_clip_handler(self):\n\t\tself.melted_telnet_controller.previous_clip(Smelted_Settings.current_unit)\n\n\tdef remove_clip(self):\n\t\tmodel, list_iter = self.playlist_tree_view.get_selection().get_selected()\n\t\tif list_iter is None:\n\t\t\treturn\n\t\tfor item in model.get_path(list_iter):\n\t\t\tself.melted_telnet_controller.remove_clip(Smelted_Settings.current_unit, item)\n\t\t\tself.main_controller.get_units_controller().find_clips_on_unit(Smelted_Settings.current_unit)\n\n\tdef new_activated_handler(self):\n\t\tself.main_controller.get_units_controller().clean_units()\n\n\tdef loop_handler(self, active):\n\t\tif active:\n\t\t\tself.melted_telnet_controller.loop_clip(Smelted_Settings.current_unit)\n\t\telse:\n\t\t\tself.melted_telnet_controller.stop_looping_clip(Smelted_Settings.current_unit)\n\n\tdef seek_bar_button_release_handler(self, percent):\n\t\tself.melted_telnet_controller.goto_position_clip(Smelted_Settings.current_unit, percent)\n\n\tdef import_playlist_button_clicked(self):\n\t\tfile_dialog_controller = FileDialogController()\n\t\tFileDialogView(file_dialog_controller)\n\t\tfile_dialog_controller.show_open_dialog(self.main_controller.get_playlist_file_controller().import_playlist)\n\n\tdef export_playlist_button_clicked(self):\n\t\tfile_dialog_controller = FileDialogController()\n\t\tFileDialogView(file_dialog_controller)\n\t\tfile_dialog_controller.show_save_dialog(self.main_controller.get_playlist_file_controller().export_playlist)\n\n\tdef add_unit_button_clicked(self):\n\t\tself.melted_telnet_controller.create_melted_unit()\n\t\tself.main_controller.get_units_controller().find_existing_units()\n\n\tdef unit_tree_view_cursor_changed(self, index):\n\t\tSmelted_Settings.current_unit = \"U\" + str(index)\n\t\tself.refresh_clips()\n\n\tdef playlist_tree_view_cursor_changed(self, index):\n\t\tclip = None\n\n\t\tclip_list = ModelManager.get_models(ModelManager.MODEL_CLIP)\n\t\tfor clip_candidate in clip_list:\n\t\t\tif str(index) == clip_candidate.index and Smelted_Settings.current_unit == clip_candidate.unit:\n\t\t\t\tclip = clip_candidate\n\t\t\t\tbreak\n\n\t\tif clip:\n\t\t\ttotal_seconds_in = math.floor(float(clip.clip_in) / float(clip.fps))\n\t\t\ttotal_seconds_out = math.floor(float(clip.clip_out) / float(clip.fps))\n\n\t\t\tlabel_text_in = self.convert_total_seconds_to_time(total_seconds_in)\n\t\t\tlabel_text_out = self.convert_total_seconds_to_time(total_seconds_out)\n\n\t\t\tGObject.idle_add(self.update_label_text, self.out_slider_label_view, label_text_out)\n\t\t\tGObject.idle_add(self.update_label_text, self.in_slider_label_view, label_text_in)\n\n\t\t\tGObject.idle_add(self.update_slider, self.out_slider_view, int(clip.calculated_length), int(clip.clip_out))\n\t\t\tGObject.idle_add(self.update_slider, self.in_slider_view, int(clip.calculated_length), int(clip.clip_in))\n\n\tdef in_slider_change_value_handler(self, value):\n\t\tclip = self.get_clip_by_playlist_cursor()\n\t\tif clip:\n\t\t\tif value > int(clip.length):\n\t\t\t\tvalue = clip.length\n\t\t\tclip.clip_in = str(value)\n\t\t\ttotal_seconds_in = math.floor(int(value) / float(clip.fps))\n\t\t\tlabel_text_in = self.convert_total_seconds_to_time(total_seconds_in)\n\t\t\tGObject.idle_add(self.update_label_text, self.in_slider_label_view, label_text_in)\n\n\tdef out_slider_change_value_handler(self, value):\n\t\tclip = self.get_clip_by_playlist_cursor()\n\t\tif clip:\n\t\t\tif value > int(clip.length):\n\t\t\t\tvalue = clip.length\n\t\t\tclip.clip_out = str(value)\n\t\t\ttotal_seconds_out = math.floor(int(value) / float(clip.fps))\n\t\t\tlabel_text_out = self.convert_total_seconds_to_time(total_seconds_out)\n\t\tGObject.idle_add(self.update_label_text, self.out_slider_label_view, label_text_out)\n\n\tdef get_clip_by_playlist_cursor(self):\n\t\tmodel, list_iter = self.playlist_tree_view.get_selection().get_selected()\n\t\tif list_iter is not None:\n\t\t\tindex = model.get_path(list_iter)[0]\n\n\t\t\tclip_list = ModelManager.get_models(ModelManager.MODEL_CLIP)\n\t\t\tfor clip_candidate in clip_list:\n\t\t\t\tif str(index) == clip_candidate.index and Smelted_Settings.current_unit == clip_candidate.unit:\n\t\t\t\t\treturn clip_candidate\n\t\t\t\t\tbreak\n\t\treturn None\n\n\tdef check_playlist_order_changed(self):\n\t\tif self.view.dragged_playlist():\n\t\t\tindex = 0\n\t\t\tfor item in self.playlist_list_store:\n\t\t\t\tif index != item[1]:\n\t\t\t\t\tself.melted_telnet_controller.change_clip_index(Smelted_Settings.current_unit, item[1], index)\n\t\t\t\t\tself.main_controller.get_units_controller().find_clips_on_unit(Smelted_Settings.current_unit)\n\t\t\t\t\tbreak\n\t\t\t\tindex += 1\n\n\tdef on_combo_changed(self, widget, path, text):\n\t\tself.unit_list_store[path][1] = text\n\t\tif text == self.end_event_list_items[0]:\n\t\t\tself.melted_telnet_controller.clip_end_event(Smelted_Settings.current_unit, \"stop\")\n\t\t\tself.main_controller.get_units_controller().get_unit_by_name(Smelted_Settings.current_unit).end_of_file = \"stop\"\n\t\telif text == self.end_event_list_items[1]:\n\t\t\tself.melted_telnet_controller.clip_end_event(Smelted_Settings.current_unit, \"loop\")\n\t\t\tself.main_controller.get_units_controller().get_unit_by_name(Smelted_Settings.current_unit).end_of_file = \"loop\"\n\t\telif text == self.end_event_list_items[2]:\n\t\t\tself.melted_telnet_controller.clip_end_event(Smelted_Settings.current_unit, \"continue\")\n\t\t\tself.main_controller.get_units_controller().get_unit_by_name(Smelted_Settings.current_unit).end_of_file = \"continue\"\n\t\telif text == self.end_event_list_items[3]:\n\t\t\tself.melted_telnet_controller.clip_end_event(Smelted_Settings.current_unit, \"pause\")\n\t\t\tself.main_controller.get_units_controller().get_unit_by_name(Smelted_Settings.current_unit).end_of_file = \"pause\"\n\n\tdef update_seek_progress(self, clip):\n\t\tfor item in self.playlist_list_store:\n\t\t\tif int(clip.index) == item[1]:\n\t\t\t\tGObject.idle_add(self.update_list_model_item, self.playlist_list_store, int(item[1]), \"#ADD8E6\", 2)\n\t\t\telse:\n\t\t\t\tGObject.idle_add(self.update_list_model_item, self.playlist_list_store, int(item[1]), \"#FFFFFF\", 2)\n\n\t\ttotal_seconds = math.floor(int(clip.progress) / float(clip.fps))\n\t\tlabel_text = self.convert_total_seconds_to_time(total_seconds)\n\n\t\tGObject.idle_add(self.update_label_text, self.progress_label, label_text)\n\t\tGObject.idle_add(self.update_slider, self.view.slider, int(clip.length), int(clip.progress))\n\n\tdef set_in(self):\n\t\tclip = self.get_clip_by_playlist_cursor()\n\t\tif clip:\n\t\t\tself.melted_telnet_controller.set_clip_in_point(Smelted_Settings.current_unit, clip.clip_in, clip.index)\n\n\tdef set_out(self):\n\t\tclip = self.get_clip_by_playlist_cursor()\n\t\tif clip:\n\t\t\tself.melted_telnet_controller.set_clip_out_point(Smelted_Settings.current_unit, clip.clip_out, clip.index)\n\n\tdef convert_total_seconds_to_time(self, total_seconds):\n\t\tminutes = int(math.floor(total_seconds / 60))\n\t\tseconds = int(total_seconds % 60)\n\n\t\tif seconds < 10:\n\t\t\tseconds = \"0\" + str(seconds)\n\n\t\treturn str(minutes) + \":\" + str(seconds)\n\n\tdef clear_list_model(self, store):\n\t\tstore.clear()\n\n\tdef update_list_model(self, store, data):\n\t\tstore.append(data)\n\n\tdef update_list_model_item(self, store, item_index, content, column):\n\t\tstore[item_index][column] = content\n\n\tdef update_label_text(self, label, text):\n\t\tlabel.set_text(text)\n\n\tdef update_slider(self, slider, length, value):\n\t\tslider.set_range(0, length)\n\t\tslider.get_adjustment().set_value(value)\n\n\t# could optimise this, clears list on every new clip added\n\tdef refresh_clips(self, clip=None):\n\t\tGObject.idle_add(self.clear_list_model, self.playlist_list_store)\n\t\tclips = ModelManager.get_models(ModelManager.MODEL_CLIP)\n\t\tclip_index = 0\n\t\tfor clip in clips:\n\t\t\tif clip.unit == Smelted_Settings.current_unit:\n\t\t\t\tGObject.idle_add(self.update_list_model, self.playlist_list_store, [os.path.basename(clip.path), int(clip.index), \"#FFFFFF\"])\n\t\t\t\tclip_index += 1\n\n\tdef update_eof_combo(self, index, type, column):\n\t\tGObject.idle_add(self.update_list_model_item, self.unit_list_store, index, type, column)\n\n\tdef remove_units(self):\n\t\tGObject.idle_add(self.clear_list_model, self.unit_list_store)\n\n\tdef add_unit(self, unit):\n\t\tGObject.idle_add(self.update_list_model, self.unit_list_store, [\"Unit \" + str(unit.unit_name)[1], \"Pause\"])","repo_name":"gamernetwork/smelted","sub_path":"controller/MainInterfaceController.py","file_name":"MainInterfaceController.py","file_ext":"py","file_size_in_byte":11386,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"21"}
+{"seq_id":"12482498771","text":"from glotnet.config import Config\nimport os\n\ndef test_config_to_json():\n\n config = Config()\n file_dir = '/tmp/json_dump/config.json'\n os.makedirs(file_dir, exist_ok=True)\n config.to_json(filepath=os.path.join(file_dir, 'config.json'))\n\n\ndef test_config_from_json():\n\n config = Config()\n file_dir = '/tmp/json_dump/config.json'\n filepath = os.path.join(file_dir, 'config.json')\n os.makedirs(file_dir, exist_ok=True)\n config.to_json(filepath=filepath)\n\n # filepath = 'config/config.json'\n config = Config.from_json(filepath=filepath)\n\n\n","repo_name":"ljuvela/GlotNet","sub_path":"test/test_trainer/test_config.py","file_name":"test_config.py","file_ext":"py","file_size_in_byte":567,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"21"}
+{"seq_id":"19098072435","text":"from django.shortcuts import render,redirect\nfrom .models import *\n\ndef instructions(request):\n if request.method=='GET':\n return render(request,'cryptober/instructions.html')\n else:\n name = request.POST.get('name').strip()\n email = request.POST.get('email')\n Response.objects.create(name=name,email=email)\n return redirect(name+'/questions/1')\n\ndef questions(request,team,id):\n try:\n response = Response.objects.get(name=team)\n # print(\"GOT IT\",len(response.input1))\n prev_inputs = eval('response.input'+id)\n prev_inputs = eval(prev_inputs)\n # print(type(prev_inputs))\n if request.method=='GET':\n return render(request,'cryptober/question'+id+'.html',{'inputs':prev_inputs,'team':team})\n else:\n if len(prev_inputs)<5:\n query = request.POST.get('query',None).strip().split()\n # print(type())\n query,output = eval('func'+id+'(query)')\n if output==-6942069:\n return render(request,'cryptober/error.html')\n query.append(output)\n prev_inputs.append(query)\n if id=='1':\n response.input1 = prev_inputs\n elif id=='2':\n response.input2 = prev_inputs\n elif id=='3':\n response.input3 = prev_inputs\n elif id=='4':\n response.input4 = prev_inputs\n elif id=='5':\n response.input5 = prev_inputs\n response.save()\n return render(request,'cryptober/question'+str(id)+'.html',{'inputs':prev_inputs,'team':team})\n except:\n return render(request,'cryptober/error.html')\n\n#Logic: This program prints the difference of cube\n#of number having maximum absolute value and minimum absolute value.\ndef func1(a):\n if len(a)!=5:\n return -6942069\n minv=int(a[0])\n maxv=int(a[0])\n for i in a:\n if i.isdigit():\n i=int(i)\n minv=min(minv,abs(i))\n maxv=max(maxv,abs(i))\n else:\n return -6942069\n return a,(maxv*maxv*maxv-minv*minv*minv)\n\n#Logic: Print no. of characters that have count more than 1\ndef func2(query):\n if len(query)!=1:\n return -6942069\n query = query[:1]\n count = [0] * 256\n for i in query[0]:\n count[ord(i)] += 1\n k = 0\n cnt=0\n for i in count:\n if int(i) > 1:\n cnt=cnt+1\n return query,cnt\n\n# Logic:A Dynamic Programming based Python program for edit\n# distance problem :\n# minimum number of edits (operations) required to convert ‘str1’ into ‘str2’.\n#allowed operations:\n#Insert\n#Remove\n#Replace\ndef func3(query):\n if len(query)<2:\n return -6942069\n query = query[:2]\n str1 = query[0]\n str2 = query[1]\n m = len(str1)\n n = len(str2)\n dp = [[0 for x in range(n+1)] for x in range(m+1)]\n for i in range(m+1):\n for j in range(n+1):\n if i == 0:\n dp[i][j] = j\n elif j == 0:\n dp[i][j] = i\n elif str1[i-1] == str2[j-1]:\n dp[i][j] = dp[i-1][j-1]\n else:\n dp[i][j] = 1 + min(dp[i][j-1],\n\t\t\t\t\t\t\t\tdp[i-1][j],\n\t\t\t\t\t\t\t\tdp[i-1][j-1])\n return query,dp[m][n]\n\n# Logic:Dynamic programming Python implementation of LIS problem\n# lis returns length of the longest increasing subsequence\n# in arr of size n\ndef func4(arr):\n if len(arr)!=7:\n return -6942069\n n = len(arr)\n for i in range(n):\n arr[i] = int(arr[i])\n lis = [1]*n\n for i in range (1 , n):\n for j in range(0 , i):\n if arr[i] > arr[j] and lis[i]< lis[j] + 1 :\n lis[i] = lis[j]+1\n maximum = 0\n for i in range(n):\n\t maximum = max(maximum , lis[i])\n return arr,maximum\n\n# LOGIC:Python program to print diffrence between sum of even array indices and\n#sum of odd array indices\ndef func5(a):\n if len(a)!=5:\n return -6942069\n for i in range(len(a)):\n a[i] = int(a[i])\n sumodd=0\n sumeven=0\n for i in range(0,len(a)):\n if(i%2==0):\n sumeven+=a[i]\n else:\n sumodd+=a[i]\n return a,sumeven-sumodd\n","repo_name":"m0bi5/ISTE-NITK_Website","sub_path":"cryptober/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":4266,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"}
+{"seq_id":"5448105816","text":"# Create a list of integer elements\ninteger_list = [1, 2, 3, 4, 5]\n\n# Use a loop to change the type of elements to float\nfloat_list = [float(num) for num in integer_list]\n\n# Print the resulting float list\nprint(float_list)\n\n# Prompt the user to enter a number 'n'\nn = int(input(\"Enter a number (n) to print Fibonacci numbers up to n: \"))\n\n# Initialize the first two Fibonacci numbers\na, b = 0, 1\n\n# Print the first Fibonacci number (0)\nprint(a)\n\n# Print Fibonacci numbers up to 'n'\nwhile b <= n:\n print(b)\n a, b = b, a + b\n\n\n# Prompt the user to enter a number\nj = int(input(\"Enter a number to calculate its factorial: \"))\n\n# Initialize the result to 1\nresult = 1\n\n# Calculate the factorial of the entered number\nfor i in range(1, j + 1):\n result *= i\n\n# Print the factorial result\nprint(f\"{j}! = {result}\")\n","repo_name":"kolyasalubov/UA-12-10-23.PythonFundamentals","sub_path":"Muzyka/HW5/HW5.py","file_name":"HW5.py","file_ext":"py","file_size_in_byte":817,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"21"}
+{"seq_id":"74991456371","text":"# This program is free software; you can redistribute it and/or modify\n# it under the terms of the GNU General Public License as published by\n# the Free Software Foundation; either version 2 of the License, or\n# (at your option) any later version.\n\nimport os\nimport importlib\nimport sys\nimport shutil\n\nfrom quodlibet.util.modulescanner import ModuleScanner\nfrom quodlibet.util.importhelper import get_importables, load_dir_modules\n\nfrom tests import TestCase, mkdtemp\n\n\nclass TModuleScanner(TestCase):\n\n def setUp(self):\n self.d = mkdtemp(\"ql-mod\")\n spec = importlib.machinery.ModuleSpec(\"qlfake\", None)\n sys.modules[\"qlfake\"] = importlib.util.module_from_spec(spec)\n\n def tearDown(self):\n del sys.modules[\"qlfake\"]\n shutil.rmtree(self.d)\n\n def _create_mod(self, name, package=None):\n if package is not None:\n base = os.path.join(self.d, package)\n else:\n base = self.d\n return open(os.path.join(base, name), \"wb\")\n\n def _create_pkg(self, name):\n base = os.path.join(self.d, name)\n os.mkdir(base)\n return open(os.path.join(base, \"__init__.py\"), \"wb\")\n\n def test_importables(self):\n self.failUnlessEqual(list(get_importables(self.d)), [])\n h = self._create_mod(\"foo.py\")\n h.close()\n self.failUnlessEqual(list(get_importables(self.d))[0],\n (\"foo\", h.name, [h.name]))\n\n def test_importables_ignore_init(self):\n h = self._create_mod(\"foo7.py\")\n h.close()\n self._create_mod(\"__init__.py\").close()\n self.failUnlessEqual(list(get_importables(self.d))[0],\n (\"foo7\", h.name, [h.name]))\n\n def test_importables_package(self):\n h = self._create_pkg(\"foobar\")\n self.failUnlessEqual(list(get_importables(self.d))[0],\n (\"foobar\", os.path.dirname(h.name), [h.name]))\n h.close()\n\n def test_importables_package_deps(self):\n h = self._create_pkg(\"foobar3\")\n h2 = self._create_mod(\"sub.py\", \"foobar3\")\n name, path, deps = list(get_importables(self.d))[0]\n self.failUnlessEqual(name, \"foobar3\")\n self.failUnlessEqual(path, os.path.dirname(h.name))\n self.failUnlessEqual(set(deps), {h.name, h2.name})\n h2.close()\n h.close()\n\n def test_load_dir_modules(self):\n h = self._create_mod(\"x.py\")\n h.write(b\"test=42\\n\")\n h.close()\n mods = load_dir_modules(self.d, \"qlfake\")\n self.failUnlessEqual(len(mods), 1)\n self.failUnlessEqual(mods[0].test, 42)\n\n def test_load_dir_modules_packages(self):\n h = self._create_pkg(\"somepkg2\")\n h2 = self._create_mod(\"sub.py\", \"somepkg2\")\n h2.write(b\"test=456\\n\")\n h2.close()\n h.write(b\"from .sub import *\\nmain=654\\n\")\n h.close()\n mods = load_dir_modules(self.d, \"qlfake\")\n self.failUnlessEqual(len(mods), 1)\n self.failUnlessEqual(mods[0].test, 456)\n\n def test_scanner_add(self):\n self._create_mod(\"q1.py\").close()\n self._create_mod(\"q2.py\").close()\n s = ModuleScanner([self.d])\n self.failIf(s.modules)\n removed, added = s.rescan()\n self.failIf(removed)\n self.failUnlessEqual(set(added), {\"q1\", \"q2\"})\n self.failUnlessEqual(len(s.modules), 2)\n self.failUnlessEqual(len(s.failures), 0)\n\n def test_unimportable_package(self):\n self._create_pkg(\"_foobar\").close()\n s = ModuleScanner([self.d])\n self.failIf(s.modules)\n removed, added = s.rescan()\n self.failIf(added)\n self.failIf(removed)\n\n def test_scanner_remove(self):\n h = self._create_mod(\"q3.py\")\n h.close()\n s = ModuleScanner([self.d])\n s.rescan()\n os.remove(h.name)\n try:\n os.remove(h.name + \"c\")\n except OSError:\n pass\n removed, added = s.rescan()\n self.failIf(added)\n self.failUnlessEqual(removed, [\"q3\"])\n self.failUnlessEqual(len(s.modules), 0)\n self.failUnlessEqual(len(s.failures), 0)\n\n def test_scanner_error(self):\n h = self._create_mod(\"q4.py\")\n h.write(b\"1syntaxerror\\n\")\n h.close()\n s = ModuleScanner([self.d])\n removed, added = s.rescan()\n self.failIf(added)\n self.failIf(removed)\n self.failUnlessEqual(len(s.failures), 1)\n self.failUnless(\"q4\" in s.failures)\n\n def test_scanner_add_package(self):\n h = self._create_pkg(\"somepkg\")\n h2 = self._create_mod(\"sub.py\", \"somepkg\")\n h2.write(b\"test=123\\n\")\n h2.close()\n h.write(b\"from .sub import *\\nmain=321\\n\")\n h.close()\n s = ModuleScanner([self.d])\n removed, added = s.rescan()\n self.failUnlessEqual(added, [\"somepkg\"])\n self.failUnlessEqual(s.modules[\"somepkg\"].module.main, 321)\n self.failUnlessEqual(s.modules[\"somepkg\"].module.test, 123)\n","repo_name":"quodlibet/quodlibet","sub_path":"tests/test_util_modulescanner.py","file_name":"test_util_modulescanner.py","file_ext":"py","file_size_in_byte":4976,"program_lang":"python","lang":"en","doc_type":"code","stars":1306,"dataset":"github-code","pt":"21"}
+{"seq_id":"19158347179","text":"\"\"\"ArmaPredictor class implementing Autoregressive Moving Average model.\"\"\"\nfrom src.models import Predictor\nfrom src.utils.measures import measure_time_metric\nfrom src.utils.running_functions import running_mean_fast\nfrom statsmodels.tsa.seasonal import seasonal_decompose\nfrom statsmodels.tsa.arima_model import ARMA\nfrom prometheus_client import Gauge\nimport src.utils.constants as constants\nimport pandas as pd\nimport numpy as np\nimport logging\nimport math\n\noutput_prometheus = Gauge('ArmaPredictor_output', 'appIDs',\n ['app_id', 'metric_name'])\n\nlogger = logging.getLogger('root')\n\n\nclass ArmaPredictor(Predictor):\n \"\"\"\n An ArmaPredictor object is an instance of ARMA forecasting model.\n\n The component is a predictor that takes dataframe on the input,\n and once a certain history threshold is filled it starts to predict\n future values. The threshold is set in model_configuration dictionary\n with 'history_size' integer value.\n \"\"\"\n\n @staticmethod\n def add_whitenoise(history):\n logger.debug('Adding whitenoise to the signal.')\n whitenoise = np.random.normal(\n loc=0, scale=0.1, size=(history.shape[0], 1))\n abs_of_whitenoise = np.abs(whitenoise)\n history += abs_of_whitenoise\n logger.debug('Whitenoise added to the signal.')\n return history\n\n def __init__(self,\n model_configuration,\n app_id=None,\n predict_interval=7,\n metric=None):\n \"\"\"\n Construct a new Predictor instance.\n\n Arguments:\n - model_configuration: dictionary containing model_configuration\n where key 'history_size' defines model capacity and 'arma_order'\n defines dictionary with appid to parameter mapping\n - app_id: integer, self-explainatory\n - predict_interval: integer, number of days taken by the model while\n training\n\n \"\"\"\n self._app_id = app_id\n self._predict_interval = predict_interval\n self._interval_index = predict_interval\n self._order = model_configuration['arma_order'].get(app_id, (1, 0))\n self._window_size = model_configuration['seasonality_period']\n logger.debug(\n repr(self) + ' Creating ArmaPredictor object {}'.format(app_id))\n Predictor.__init__(self, model_configuration, app_id, metric)\n logger.debug(\n repr(self) + ' Setting initial configuration of the model')\n self._is_trained = False\n self.build_model = ARMA\n self.not_empty = lambda x: np.sum(x[-5:]) != 0\n logger.debug(repr(self) + ' ArmaPredictor {} created'.format(app_id))\n\n @measure_time_metric\n def _run(self, incoming_df):\n \"\"\"\n Run is called each time a dataframe is pushed into the component.\n\n Arguments:\n - incoming_df: pandas dataframe containing 'time' and 'value' columns\n\n Returns:\n - result: a tuple containing:\n prediction - a forecast if predicted otherwise None\n rate_of_change - float, predicted change in slope\n given as percentage\n current_time - time extracted from last date_package\n\n \"\"\"\n current_time = self._preprocess(incoming_df)\n self._update_model(incoming_df)\n if self.is_trained:\n logger.debug(repr(self) + 'Model is trained, starting prediction.')\n logger.debug(repr(self) + 'current_time: {}'.format(current_time))\n prediction = self._predict()\n logger.debug(repr(self) + 'prediction: {}'.format(prediction))\n rate_of_change = self._postprocess(prediction, current_time)\n logger.debug(\n repr(self) + 'rate_of_change: {}'.format(rate_of_change))\n result = (prediction, rate_of_change, current_time)\n else:\n logger.debug(\n repr(self) + 'Model is not trained, sending mock result.')\n result = (None, None, current_time)\n logger.debug(repr(self) + str(result))\n return result\n\n def _update_model(self, incoming_df):\n \"\"\"\n Update history and fit ARMA to the series if possible.\n\n Arguments:\n - incoming_df: pandas dataframe containing 'time' and 'value' columns\n \"\"\"\n logger.debug(\n repr(self) + 'Updating history with {}'.format(incoming_df))\n self.history.append(incoming_df)\n if self.filled(self.history):\n logger.debug(repr(self) + 'Model history is full, proceeding.')\n self.preprocessed_history = self._preprocess_model_history()\n if self.not_empty(self.preprocessed_history):\n logger.debug(repr(self) + 'Data is not empty, proceeding.')\n self.model = self._prepare_model()\n self._is_trained = True\n logger.debug(repr(self) + 'Set is_trained flag to True.')\n\n def _preprocess_model_history(self):\n \"\"\"\n Preprocess model history in a way it is feedable to ARMA model.\n\n Returns:\n - preprocessed_history: np.array with time and value for each datapoint\n \"\"\"\n logger.debug(repr(self) + 'Start preprocessing.')\n history_df = pd.concat(self.history)\n logger.debug(repr(self) + 'History deque has been concatenated.')\n history_df = history_df[['time', 'value']]\n history_df.set_index('time', inplace=True)\n preprocessed_history = np.asarray(history_df).astype(np.float)\n logger.debug(repr(self) + 'History converted to numpy array.')\n self._raw_history = self.add_whitenoise(preprocessed_history)\n decomposed_signal = seasonal_decompose(\n list(preprocessed_history), freq=self._window_size)\n half_window = math.floor(self._window_size / 2)\n assert half_window == 3, half_window\n assert isinstance(half_window, int), type(half_window)\n preprocessed_signal = decomposed_signal.trend[half_window:-half_window]\n preprocessed_signal = running_mean_fast(preprocessed_signal,\n self._window_size)\n logger.debug(\n repr(self) +\n 'History decomposed to {}'.format(preprocessed_signal))\n logger.debug(\n repr(self) + 'Preprocessed signal shape {} (should be 150!)'.\n format(preprocessed_signal.shape))\n logger.debug(\n repr(self) +\n 'Returning preprocessed signal: {}'.format(preprocessed_signal))\n return preprocessed_signal\n\n def _prepare_model(self):\n \"\"\"\n Prepare model for forecast.\n\n Arguments:\n - preprocessed_history: np.array with time and value for each datapoint\n\n Returns:\n - model: ARMA model fit to provided history\n \"\"\"\n try:\n logger.debug(\n repr(self) + 'Fitting preprocessed_history to the model.')\n model = self.build_model(self.preprocessed_history, self.order)\n model = model.fit(disp=0)\n logger.debug(repr(self) + 'Model fit correctly.')\n except Exception:\n logger.warning(\n repr(self) +\n 'The model with whitenoise did not fit, use (1,0)')\n model = self.build_model(self._raw_history, (1, 0))\n model = model.fit(disp=0)\n logger.debug(repr(self) + 'Model fit correctly.')\n return model\n\n def _predict(self):\n \"\"\"\n Forecast next X days, X is defined by self.predict_interval field.\n\n Returns:\n - forecast: pandas dataframe containing 'time' and 'value' columns\n \"\"\"\n logger.debug(repr(self) + 'Starting prediction.')\n forecast, _, __ = self.model.forecast(steps=self.predict_interval)\n logger.debug(repr(self) + 'Success, prediction {}'.format(forecast))\n return forecast\n\n def _postprocess(self, prediction, current_time):\n \"\"\"\n Send relevant log to prometheus.\n\n Arguments:\n - prediction: forecast, if predicted otherwise None\n\n Returns:\n - rate: float, predicted change in slope given as percentage\n \"\"\"\n logger.debug(repr(self) + 'Start post-processing of the output')\n last_forecasted_value = np.mean(prediction)\n logger.debug(\n repr(self) +\n 'Last forecasted value: {}'.format(last_forecasted_value))\n last_known_value = np.mean(\n self.preprocessed_history[self.interval_index:])\n logger.debug(\n repr(self) + 'Last known value: {}'.format(last_known_value))\n rate = self._calculate_change_rate(last_known_value,\n last_forecasted_value)\n logger.debug(repr(self) + 'Calculated rate: {}'.format(rate))\n rate = abs(rate)\n logger.debug(repr(self) + 'Absolute value of rate: {}'.format(rate))\n output_prometheus.labels(self.app_id, self.metric).set(rate)\n logger.debug(repr(self) + 'Rate sent to prometheus {}'.format(rate))\n output = {\n 'time_model': current_time,\n 'rate_of_change': rate,\n 'app_id_model': self.app_id\n }\n logger.debug(\n repr(self) + 'Output of the ArmaPredictor: {}'.format(output))\n return rate\n\n def _calculate_change_rate(self, known_value, forecasted_value):\n \"\"\"\n Calculate rate of change for known and forecasted signal.\n\n Arguments:\n - known_value: float, last value for history timeseries\n - forecasted_value: float, last value for forecasted signal\n\n Returns:\n result: float, rate of change given as percentage (between 0. - 100.)\n \"\"\"\n logger.debug(\n repr(self) + 'If last known value is 0, substitute it to 1')\n known_value = 1 if known_value == 0 else known_value\n logger.debug(\n str(self) + 'Forecasted value {}'.format(forecasted_value))\n logger.debug(str(self) + 'Last known value {}'.format(known_value))\n difference = forecasted_value - known_value\n result = float((difference) * constants.CONVERT_PERCENT / known_value)\n logger.debug(\n repr(self) + 'Percentage rate of change {}'.format(result))\n return result\n\n def _preprocess(self, incoming_df):\n \"\"\"Extract time from the input signal.\"\"\"\n logger.debug(repr(self) + 'Starting _run method.')\n current_time = incoming_df.reset_index(drop=True).time[0]\n logger.debug(repr(self) + 'current_time: {}'.format(current_time))\n return current_time\n\n @property\n def is_trained(self):\n \"\"\"Boolean flag showing if an object was trained.\"\"\"\n return self._is_trained\n\n @property\n def predict_interval(self):\n \"\"\"The interval we make decision upon.\"\"\"\n return self._predict_interval\n\n @property\n def interval_index(self):\n return self._predict_interval\n\n @property\n def order(self):\n return self._order\n\n @property\n def window_size(self):\n return self._window_size\n\n def __repr__(self):\n \"\"\"Use repr(self) for DEBUG, ERROR, CRITICAL logging levels.\"\"\"\n return '{} - Order {} - Predict_interval {}: '.format( #noqa\n self.app_id, self.order, self.predict_interval)\n\n def __str__(self):\n \"\"\"Use str(self) for INFO, WARNING logging levels.\"\"\"\n return '{}: '.format(self.app_id)\n","repo_name":"navid-data-analytics/Navid-ai-project-team-work","sub_path":"src/models/ArmaPredictor.py","file_name":"ArmaPredictor.py","file_ext":"py","file_size_in_byte":11539,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"}
+{"seq_id":"25908746240","text":"from hashlib import new, sha256\nimport time\n\nMAX_NONCE = 100000000\n\n\ndef SHA256(text):\n return sha256(text.encode(\"ascii\")).hexdigest()\n\n\ndef mine(block_number, transactions, previous_hash, prefix_zeros):\n prefix_str = \"0\" * prefix_zeros\n\n for nonce in range(MAX_NONCE):\n nonce += 1\n text = str(block_number) + transactions + prev_hash + str(nonce)\n new_hash = SHA256(text)\n if new_hash.startswith(prefix_str):\n print(f\"\\nYay!! Successfully mined bitcoins with nonce value:{nonce} \")\n return new_hash\n\n raise BaseException(f\"Couldn't findcorrect Hash after trying {MAX_NONCE} times\")\n\n\nif __name__ == \"__main__\":\n transactions = \"\"\"\n Rohan->Mohan->20,\n Chandan->Chaman->45\n \"\"\"\n prev_hash = \"0000000xa036944e29568a66bd0cff17edbe0381544208feacf9a66b65as68wqe4551vvfb54gf1set70der58feacf965as645asd5et\"\n\n difficulty = 10\n\n start = time.time() ##?Gives Current Time\n print(\"\\nMining Started\")\n new_hash = mine(5, transactions, prev_hash, difficulty)\n total_time = str(time.time() - start)\n print(f\"\\nMining Ends. Time Taken = {total_time} seconds\")\n\n print(\"\\n\")\n print(new_hash)\n print(\"\\n\")\n","repo_name":"spiderxm/python-programs","sub_path":"abstrxtinfinity/bitcoin_mining.py","file_name":"bitcoin_mining.py","file_ext":"py","file_size_in_byte":1195,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"21"}
+{"seq_id":"21305809060","text":"from django.conf.urls import url\n\nfrom . import views\n\n\nurlpatterns = [\n url(r'^$', views.index, name='index'),\n url(r'^(?P.+?)/catagory$', views.catagory, name='catagory'),\n url(r'^(?P.+?)/sub_catagory$', views.sub_catagory, name='sub_catagory'),\n url(r'^(?P.+?)/sub_sub_catagory$', views.sub_sub_catagory, name='sub_sub_catagory'),\n url(r'^(?P[0-9]+)/single$', views.single, name='single'),\n url(r'^(?P[0-9]+)/single2$', views.single2, name='single2'),\n url(r'^(?P[0-9]+)/blog1234$', views.blog1234, name='blog1234'),\n url(r'^category1_c26/$', views.category1_c26, name='category1_c26'),\n url(r'^sub_category1_c27/$', views.sub_category1_c27, name='sub_category1_c27'),\n url(r'^sub_category2_c28/$', views.sub_category2_c28, name='sub_category2_c28'),\n url(r'^sub_category1_c27905b/$', views.sub_category1_c27905b, name='sub_category1_c27905b'),\n url(r'^order8/$', views.order815d, name='order815d'),\n url(r'^order16/$', views.ordera5cc, name='ordera5cc'),\n url(r'^order21/$', views.order, name='order'),\n url(r'^password_recovery/$', views.password_recovery, name='password_recovery'),\n url(r'^search/$', views.search, name='search'),\n url(r'^subscr/$', views.subscr, name='subscr'),\n url(r'^login2/$', views.login1234, name='login1234'),\n url(r'^login15/$', views.login842d, name='login842d'),\n url(r'^login9/$', views.login52ea, name='login52ea'),\n url(r'^login1/$', views.loginfd9a, name='loginfd9a'),\n url(r'^login14/$', views.login546a, name='login546a'),\n url(r'^create_account/$', views.create_account, name='create_account'),\n url(r'^blog2/$', views.blog, name='blog'),\n url(r'^blog7/$', views.blog905b, name='blog905b'),\n url(r'^blog10/$', views.blogcd64, name='blogcd64'),\n url(r'^blog12/$', views.blogf80d, name='blogf80d'),\n url(r'^about_us/$', views.about_us, name='about_us'),\n url(r'^delievery/$', views.delievery, name='delievery'),\n url(r'^legal_notice/$', views.legal_notice, name='legal_notice'),\n url(r'^dialog_index/$', views.dialog_index, name='dialog_index'),\n url(r'^default/$', views.default, name='default'),\n url(r'^(?P[0-9]+)/add/$', views.add, name='add'),\n url(r'^show/$', views.show, name='show'),\n url(r'^(?P[0-9]+)/remove/$', views.remove, name='remove'),\n url(r'^empty/$', views.empty, name='empty'),\n url(r'^thankyou/$', views.thankyou, name='thankyou'),\n url(r'^(?P[0-9]+)/remove_single/$', views.remove_single, name='remove_single'),\n\n \n] \n","repo_name":"ritz1302/giftwebsite","sub_path":"giftwebsite/tohfa/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":2610,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"}
+{"seq_id":"37561465785","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed Mar 9 15:37:11 2022\n\n@author: soyrl\n\"\"\"\n\n#https://stackoverflow.com/questions/50655738/how-do-i-resolve-a-tesseractnotfounderror\nimport pytesseract \n# Set the path to Tesseract OCR executable\npytesseract.pytesseract.tesseract_cmd = 'C:\\\\Program Files\\\\Tesseract-OCR\\\\tesseract.exe'\n\nimport cv2\nimport numpy as np\nimport os\nimport pydicom as dicom\nimport time\nimport warnings\n\nwarnings.filterwarnings(\"ignore\") # Ignore warnings in the code\n\nstart=time.time()\n\npath_images=\"C:/Users/soyrl/Desktop/ocr/\" #Path to DICOM slices\n\n#Path to save line with nodule id\npath_to_save=\"C:/Users/soyrl/Desktop/ocr_images/\"\n\n#Create this folder if it does not exist\nif not os.path.exists(path_to_save):\n os.mkdir(path_to_save)\n\n#Settings and characters that can be used to recognize the nodule id\ncustom_config = r'-c tessedit_char_whitelist=L0123456789 --oem 1 --psm 6'\nL_nod_names=['L01','L02','L03','L04','L05','L06','L07','L08','L09','L10']\nnod_names=['01','02','03','04','05','06','07','08','09','10']\n\n#Initialize empty lists to be filled below with nodules and slices with errors\nfinal_class={}\nerrors=[]\n\nfor file in os.listdir(path_images): #Loop through all DICOM slices\n\n path=path_images+file #Get the path of the current DICOM slice\n \n dicom_file_final=dicom.dcmread(path) #Read it\n img=dicom_file_final.pixel_array #Load pixel data\n \n img2=cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) #Convert to grayscale\n \n thresh = cv2.threshold(img2,150,255,cv2.THRESH_BINARY)[1] #Get a thresholded image with only nodules\n\n thresh=thresh[0:30,:] #Get first lines/rows of the image with the nodule id number\n \n #if this line contains a nodule id (it is not empty) \n if (len(np.unique(thresh[0:30,50:150]))>1 and \n len(np.where(thresh[0:30,50:150]==255)[0])>2):#and '5' in file.split('.')[4]:#'138' in file: #0,120\n \n print(file) #Print the file name/slice that contains the nodule id\n cv2.imwrite(path_to_save+str(file)+'.png',thresh) #Save yellow mask - range from 0-255\n \n \n #Get contours for each object and create a rectangle around them\n contours = cv2.findContours(thresh, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)\n contours = contours[0] if len(contours) == 2 else contours[1]\n ymin=1024\n ymax=0\n xmin=1024\n xmax=0\n \n Lclass=[]\n others=[]\n \n for cntr in contours:\n x,y,w,h = cv2.boundingRect(cntr)\n if xxmax:\n xmax=x+w\n if y+h>ymax:\n ymax=y+h\n cv2.rectangle(img, (x-1, y-1), (x+w+1, y+h+1), (0, 0, 255), 1) #last argument thickness - was 2\n \n #Ensure that we are on the limits of the image\n if y-10<0:\n new_y=0\n else:\n new_y=y-10\n \n character=img[new_y:y+h+10,x-10:x+w+10,:] #extract part of the image with the characters\n character = cv2.resize(character, (50, 50)) #resize image with the characters\n character2=cv2.cvtColor(character, cv2.COLOR_BGR2GRAY) #convert to gray\n\n #Use pytesseract for OCR\n if len(pytesseract.image_to_string(character2, config=custom_config))!=0:\n for elem in pytesseract.image_to_string(character2, config=custom_config).split('\\n'):\n if elem in L_nod_names:\n Lclass.append(elem)\n elif elem in nod_names:\n others.append(elem)\n\n #Just a check to confirm that we didn't miss characters\n if len(others)>len(Lclass):\n final_class[file.split('.')[4]]=others\n \n if Lclass in final_class.values() and len(Lclass)==1 and len(others)!=0:\n for oelem in others:\n if oelem not in list(final_class.values())[:-11]: \n final_class[file.split('.')[4]]=oelem\n \n else:\n print('ERROR in {}'.format(file.split('.')[4]))\n errors.append(file.split('.')[4])\n \n elif Lclass!=[] and file.split('.')[4] not in final_class:\n final_class[file.split('.')[4]]=Lclass\n \n \n print(\"\\n\") \n \n \n# Define a new list to store the modified values \nnew_value=[] \n\n# Loop over the values of final_class dictionary\nfor slice_elem in list(final_class.values()):\n if isinstance(slice_elem, list):\n temp_list=[]\n for elem in slice_elem:\n if elem not in temp_list and 'L'+elem not in temp_list:\n if 'L' not in elem :\n elem='L'+elem\n temp_list.append(elem)\n else:\n temp_list.append(elem)\n\n # Append the modified list to the new_value list \n new_value.append(temp_list)\n \n else:\n # If the value is not a list, modify it and append as a list to new_value\n if 'L' not in slice_elem :\n slice_elem='L'+slice_elem\n new_value.append(list([slice_elem]))\n else:\n new_value.append(list([slice_elem]))\n\n# Update the values of final_class dictionary with the modified values in new_value \nfor index,value in enumerate(new_value):\n final_class[list(final_class.items())[index][0]]=value\n\n# Convert the sublists in new_value to single values, if possible\nif isinstance(new_value[0],list):\n new_value=[elem[0] for elem in new_value]\n\n# Define a list to store the unique nodules \nnodules=[]\n# Get the unique values from new_value and store in nodules list\nfor unique in np.unique(new_value):\n for elem in unique:\n if elem not in nodules and elem.isdigit():\n nodules.append(elem)\n\nnodules.sort() # Sort the nodules list\n\nnod_num=[1,2,3,4,5,6,7,8,9,10] # Define the expected nodule ids\n\n# Convert the nodules to integer values\nfor index,val in enumerate(nodules):\n nodules[index]=int(val[-2:]) \n \npos_errors=[] # Define a list to store the missing nodule ids\n# Check for missing nodule ids\nfor miss_val in nod_num:\n if miss_val not in nodules:\n pos_errors.append(miss_val)\n \n# Print the missing nodules information\nif len(pos_errors)==1:\n print(\"Slices {} may contain nodule with id {}\".format(errors,pos_errors[0]))\nelse:\n print(\"Slices with errors are {} and nodule ids that they might contain are {}\".format(errors,pos_errors))\n \n \nend=time.time()\nprint(\"Total time to run: {} sec\".format(end-start)) \n ","repo_name":"nsourlos/OCR_Siemens_AI_Rad_Companion","sub_path":"ocr_red_color.py","file_name":"ocr_red_color.py","file_ext":"py","file_size_in_byte":7004,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"}
+{"seq_id":"20305433207","text":"def match(str):\n opo1=[]\n opo2=[]\n opo3=[]\n clo1=[]\n clo2=[]\n clo3=[]\n for i in range(0,len(str)):\n l=str[i]\n if l == \"(\" :\n opo1=opo1 + [\"(\"]\n elif l == \"{\" :\n opo2=opo2 + [\"{\"]\n elif l == \"<\" :\n opo3=opo3 + [\"<\"]\n elif l == \")\" :\n clo1=clo1 + [\")\"]\n elif l == \"}\" :\n clo2=clo2 + [\"}\"]\n else:\n clo3=clo3 + [\">\"]\n i=i+1\n if len(opo1)==len(clo1) and len(opo2)==len(clo2) and len(opo3)==len(clo3) :\n return True\n else:\n return False\n\ns=input(\"enter a string\")\nd=match(s)\nprint(d)\n","repo_name":"Aishuav01/Retry","sub_path":"me.py","file_name":"me.py","file_ext":"py","file_size_in_byte":542,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"}
+{"seq_id":"14575464028","text":"import os\nimport shutil\nfrom distutils.dir_util import copy_tree\n\nimport utils\n\n\ndef append_to_file_after_line_last_occurence(fname, after, what):\n with open(fname, 'r', encoding='utf-8') as f:\n text = f.readlines()\n already_exists = [idx for idx, s in enumerate(text) if what in s]\n if already_exists:\n return\n index_after = utils.get_last_nth_occurence_of_list_element(text, after, 1)\n if not index_after:\n index_header_end = utils.get_last_nth_occurence_of_list_element(text, ' \" in out[i] and (out[i+1] != 'xxxx'):\n if cnt != 1:\n fout.write(\"\\n\")\n fout.write(str(cnt) + '\\n' + out[i] + '\\n')\n cnt += 1; \n if (not IsNum(out[i].strip())) and (\"-->\" not in out[i]) and (out[i] != 'xxxx'):\n fout.write(out[i] + '\\n')\n i += 1\n fp.close(); fout.close(); \n\n# -------------------- Driver Code -------------------- #\n# clean('test1.txt', 'test1_cleaned.txt')\n","repo_name":"Peepow2/ComProgYear1","sub_path":"Homework (1-2564)/Homework8/Clean function template.py","file_name":"Clean function template.py","file_ext":"py","file_size_in_byte":2322,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"}
+{"seq_id":"26638422190","text":"import sys\n\nscript_fmt = \"\"\"#!/bin/bash\n\n#PBS -l nodes=1:ppn=16\n#PBS -l pmem=4gb\n#PBS -l walltime=48:00:00\n#PBS -q batch\n#PBS -j oe\ncd %s/runs/seq/\n%s/build/arakawa.x -f %s/data/seq/%s,%s/data/seq/%s -o %s.%s.k%d.out -k %d\n\"\"\"\n\n\ndef gen_4m(seq_4mx2):\n for k in [0, 1, 2, 3, 4, 5, 6]:\n script_name = \"seq4Mx2.acs.k\" + str(k) + \".pbs\"\n with open(script_name, \"w\") as f:\n script_str = script_fmt % (arakawa_path, arakawa_path,\n arakawa_path, seq_4mx2[0],\n arakawa_path, seq_4mx2[1],\n 'seq4Mx2', 'acs', k, k)\n f.write(script_str)\n f.write(\"\\n\")\n\n\ndef gen_script(seq_big, prefix):\n for k in [0, 1, 2, 3, 4, 5, 6]:\n script_name = prefix + \".acs.k\" + str(k) + \".pbs\"\n with open(script_name, \"w\") as f:\n script_str = script_fmt % (arakawa_path, arakawa_path,\n arakawa_path, seq_big[0],\n arakawa_path, seq_big[1],\n prefix, 'acs', k, k)\n f.write(script_str)\n f.write(\"\\n\")\n\n\nif __name__ == '__main__':\n arakawa_path = sys.argv[1]\n seq_4mx2 = ['NC_000962.3.fasta', 'NC_000913.3.fasta']\n seq_big = ['NT_033779.4.fasta', 'NC_019478.1.fasta']\n droso = ['NT_033779.5.fasta', 'NT_033778.4.fasta']\n # gen_4m(seq_4mx2)\n # gen_script(seq_big, \"seqbig\")\n gen_script(droso, \"droso\")\n","repo_name":"AluruLab/alfred","sub_path":"scripts/seq_scripts.py","file_name":"seq_scripts.py","file_ext":"py","file_size_in_byte":1511,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"}
+{"seq_id":"33597000101","text":"class Solution(object):\n def moveZeroes(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: None Do not return anything, modify nums in-place instead.\n \"\"\"\n l, r = 0, 0\n \n while r < len(nums):\n if nums[r] != 0: # move the nonzero to the front\n nums[l], nums[r] = nums[r], nums[l]\n l += 1\n r += 1\n ","repo_name":"tinatran079/leetcode","sub_path":"move-zeroes/move-zeroes.py","file_name":"move-zeroes.py","file_ext":"py","file_size_in_byte":414,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"}
+{"seq_id":"13358298210","text":"from datetime import datetime\nfrom aiogram import Bot, types\nfrom aiogram.dispatcher import Dispatcher\nfrom aiogram.utils import executor\n\nimport re\n\nfrom keyboards import kb_whois, inline_kb_whois\n\nimport whois\n\nimport os\n\nbot = Bot(token = os.getenv('TOKEN'))\ndp = Dispatcher(bot)\n\nasync def startup_on(_):\n print('Бот в вышел в онлайн')\n\n@dp.message_handler(commands='start')\n@dp.message_handler(regexp='\\s*@torrentxok_testbot\\s*/start\\s*')\nasync def command_start(message : types.Message):\n try:\n start_message ='''\nПривет)\nЭто бот, который отправляет Whois-запросы\n\nОн позволяет отслеживать домены, которые вы добавите,\nи выводить информацию о домене!\n\nОбновление информации добавленных доменов происходит один раз в день\n\nТакже возможно настроить систему оповещений\n\nИнструкцию по командам, которые есть у бота, \\\nможно просмотреть по запросу:\n/help\n\nСписок команд доступен по запросу:\n/commands'''\n await bot.send_message(message.from_user.id, start_message, reply_markup=kb_whois)\n \n except:\n await message.reply(f'Ошибка! Напишите боту (@{(await bot.get_me()).username}) в личные сообщения')\n\n@dp.message_handler(commands='help')\n@dp.message_handler(regexp='\\s*@torrentxok_testbot\\s*/help\\s*')\nasync def command_list(message : types.Message):\n try:\n help_message = '''\nДоступные команды :\n\n/commands - просмотреть список доступных запросов\n\nШаблоны:\n\n/find { your domain } - Выполняет whois-запрос и выводит информацию о домене\n\n/add { your domain } - Добавляет домен для отслеживания\n\n/delete { your domain } - Удаляет ранее добавленный домен\n\n/list - Просмотр добавленных доменов\n\nВместо { your domain } вставьте имя домена, который хотите проверить\n(без {} и без http)'''\n await bot.send_message(message.from_user.id, help_message, reply_markup=kb_whois)\n except:\n await message.reply('Общение с ботом в ЛС!')\n\n@dp.message_handler(commands='commands')\n@dp.message_handler(regexp='\\s*@torrentxok_testbot\\s*/commands\\s*')\nasync def command_whois(message : types.Message):\n commands_message = '''\nИнструкция по доступным командым:\n/help\n\nКоманды: '''\n await bot.send_message(message.from_user.id, commands_message, reply_markup=inline_kb_whois)\n\n\n #await message.reply(message.text)\n@dp.message_handler(regexp='\\s*@torrentxok_testbot\\s*/find\\s*\\w*\\s*') \n@dp.message_handler(regexp='\\s*/find\\s*\\w*\\s*')\nasync def find_domain(message : types.Message):\n domain_name = message.text[message.text.find('find')+4:].strip()\n if len(domain_name.split())!=1:\n await bot.send_message(message.from_user.id, 'Неверное имя домена!\\nИнструкция по использованию бота:\\n/help')\n else:\n try:\n #информация о домене\n whois_find_domain = whois.whois(domain_name)\n print(whois_find_domain)\n if type(whois_find_domain['creation_date']) == list:\n creation_date = str(whois_find_domain['creation_date'][1])[:11].strip().split('-')\n elif type(whois_find_domain['creation_date']) == datetime:\n creation_date = str(whois_find_domain['creation_date'])[:11].strip().split('-')\n creation_date_year = creation_date[0]\n creation_date_month = creation_date[1]\n creation_date_day = creation_date[2]\n\n if type(whois_find_domain['expiration_date']) == list:\n expiration_date = str(whois_find_domain['expiration_date'][1])[:11].strip().split('-')\n elif type(whois_find_domain['expiration_date']) == datetime:\n expiration_date = str(whois_find_domain['expiration_date'])[:11].strip().split('-')\n expiration_date_year = expiration_date[0]\n expiration_date_month = expiration_date[1]\n expiration_date_day = expiration_date[2]\n\n whois_info = f'''\nDomain : {whois_find_domain['domain_name']}\nCreation date : {creation_date_day}.{creation_date_month}.{creation_date_year}\nExpiration date : {expiration_date_day}.{expiration_date_month}.{expiration_date_year}\n'''\n await bot.send_message(message.from_user.id, whois_info)\n except:\n await bot.send_message(message.from_user.id, 'Произошла ошибка!\\nПопробуйте еще раз или введите другое имя домена\\n\\nИнструкция доступна по запросу:\\n/help' )\n\n\nexecutor.start_polling(dp, skip_updates=True, on_startup=startup_on)","repo_name":"torrentxok/whois-telegram-bot","sub_path":"bot_telegram.py","file_name":"bot_telegram.py","file_ext":"py","file_size_in_byte":5146,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"}
+{"seq_id":"10772011247","text":"\"\"\"\nCubic spline planner\nAuthor: Atsushi Sakai(@Atsushi_twi)\n\nAdapted by Aaron\n\"\"\"\nimport math\nimport numpy as np\nimport bisect\nimport pdb\n\nclass Spline:\n \"\"\"\n Cubic Spline class\n \"\"\"\n\n def __init__(self, x, y):\n self.b, self.c, self.d, self.w = [], [], [], []\n\n self.x = x\n self.y = y\n\n self.nx = len(x) # dimension of x\n h = np.diff(x)\n\n # calc coefficient c\n self.a = [iy for iy in y]\n\n # calc coefficient c\n A = self.__calc_A(h)\n B = self.__calc_B(h)\n self.c = np.linalg.solve(A, B)\n # print(self.c1)\n\n # calc spline coefficient b and d\n for i in range(self.nx - 1):\n self.d.append((self.c[i + 1] - self.c[i]) / (3.0 * h[i]))\n tb = (self.a[i + 1] - self.a[i]) / h[i] - h[i] * \\\n (self.c[i + 1] + 2.0 * self.c[i]) / 3.0\n self.b.append(tb)\n\n def calc(self, t):\n \"\"\"\n Calc position\n if t is outside of the input x, return None\n \"\"\"\n\n if t < self.x[0]:\n return None\n elif t > self.x[-1]:\n return None\n\n i = self.__search_index(t)\n dx = t - self.x[i]\n result = self.a[i] + self.b[i] * dx + \\\n self.c[i] * dx ** 2.0 + self.d[i] * dx ** 3.0\n\n return result\n\n def calcd(self, t):\n \"\"\"\n Calc first derivative\n if t is outside of the input x, return None\n \"\"\"\n\n if t < self.x[0]:\n return None\n elif t > self.x[-1]:\n return None\n \n # i = np.argmin(np.abs(t-np.array(self.x)))-1\n \n i = self.__search_index(t)\n dx = t - self.x[i]\n result = self.b[i] + 2.0 * self.c[i] * dx + 3.0 * self.d[i] * dx ** 2.0\n \n return result\n\n def calcdd(self, t):\n \"\"\"\n Calc second derivative\n \"\"\"\n\n if t < self.x[0]:\n return None\n elif t > self.x[-1]:\n return None\n\n i = self.__search_index(t)\n dx = t - self.x[i]\n result = 2.0 * self.c[i] + 6.0 * self.d[i] * dx\n return result\n \n def calcddd(self, t):\n \"\"\"\n Calc third derivative\n \"\"\"\n \n if t < self.x[0]:\n return None\n elif t > self.x[-1]:\n return None\n\n i = self.__search_index(t)\n dx = t - self.x[i]\n result = 6.0 * self.d[i]\n return result\n\n def __search_index(self, x):\n \"\"\"\n search data segment index\n \"\"\"\n return bisect.bisect(self.x, x) - 1\n\n def __calc_A(self, h):\n \"\"\"\n calc matrix A for spline coefficient c\n \"\"\"\n A = np.zeros((self.nx, self.nx))\n A[0, 0] = 1.0\n for i in range(self.nx - 1):\n if i != (self.nx - 2):\n A[i + 1, i + 1] = 2.0 * (h[i] + h[i + 1])\n A[i + 1, i] = h[i]\n A[i, i + 1] = h[i]\n\n A[0, 1] = 0.0\n A[self.nx - 1, self.nx - 2] = 0.0\n A[self.nx - 1, self.nx - 1] = 1.0\n # print(A)\n return A\n\n def __calc_B(self, h):\n \"\"\"\n calc matrix B for spline coefficient c\n \"\"\"\n B = np.zeros(self.nx)\n for i in range(self.nx - 2):\n B[i + 1] = 3.0 * (self.a[i + 2] - self.a[i + 1]) / \\\n h[i + 1] - 3.0 * (self.a[i + 1] - self.a[i]) / h[i]\n return B\n\n\nclass Spline2D:\n \"\"\"\n 2D Cubic Spline class\n \"\"\"\n\n # Compute and store for a fixed set of s values along the path\n # the corresponding s, x(s), y(s), x'(s), y'(s) values for later use\n # Store points at intervals of ds path length\n def __init__(self, x, y, ds=0.005):\n self.s = self.__calc_s(x, y)\n self.sx = Spline(self.s, x)\n self.sy = Spline(self.s, y)\n self.ds = ds\n self.end = np.max(self.s)\n self.PointTangent = np.array([[ds*i, self.calc_position(ds*i)[0], self.calc_position(ds*i)[1], self.sx.calcd(ds*i), self.sy.calcd(ds*i)] for i in range(0,int(self.end/ds))])\n \n def __calc_s(self, x, y):\n dx = np.diff(x)\n dy = np.diff(y)\n self.ds = np.hypot(dx, dy)\n s = [0]\n s.extend(np.cumsum(self.ds))\n return s\n\n # Given a particular s, find x(s), y(s)\n def calc_position(self, s):\n \"\"\"\n calc position\n \"\"\"\n x = self.sx.calc(s)\n y = self.sy.calc(s)\n\n return x, y\n\n # Note that are using signed curvature here\n def calc_curvature(self, s):\n \"\"\"\n calc curvature\n \"\"\"\n dx = self.sx.calcd(s)\n ddx = self.sx.calcdd(s)\n dy = self.sy.calcd(s)\n ddy = self.sy.calcdd(s)\n k = (ddy * dx - ddx * dy) / ((dx ** 2 + dy ** 2)**(3 / 2))\n return k\n\n # Given s, compute gamma(s)\n def calc_yaw(self, s):\n \"\"\"\n calc yaw\n \"\"\"\n dx = self.sx.calcd(s)\n dy = self.sy.calcd(s)\n yaw = math.atan2(dy, dx)\n # if (dx == 0):\n # if dy > 0:\n # yaw = math.pi/2\n # elif dy < 0:\n # yaw = -math.pi/2\n # else:\n # yaw = math.atan(dy/dx)\n # if (dx < 0):\n # yaw = yaw + math.pi\n return yaw\n \n # Given s, compute d/ds gamma(s)\n def calc_yawPrime(self, s):\n dx = self.sx.calcd(s)\n ddx = self.sx.calcdd(s)\n dy = self.sy.calcd(s)\n ddy = self.sy.calcdd(s)\n yawPrime = (ddy * dx - ddx * dy) / (dx ** 2 + dy ** 2)\n return yawPrime\n \n # Given s, compute d/ds K(s)\n def calc_curvaturePrime(self, s):\n dx = self.sx.calcd(s)\n ddx = self.sx.calcdd(s)\n dddx = self.sx.calcddd(s)\n dy = self.sy.calcd(s)\n ddy = self.sy.calcdd(s)\n dddy = self.sy.calcddd(s)\n \n firstTerm = (dddy * dx - dddx * dy) / (dx**2 + dy**2)**(3/2)\n secondTerm = 3 * (dx * ddy - ddx * dy) * (dx * ddx + dy * ddy) / (dx**2 + dy**2)**(5/2)\n \n return firstTerm - secondTerm\n \n # Compute the unit normal and non-unit tangent vector at given point\n def calcTangentNormal(self, s):\n dx = self.sx.calcd(s)\n dy = self.sy.calcd(s)\n r = np.sqrt(dx**2 + dy**2)\n nx = - dy / r\n ny = dx / r\n # Return tangent, normal\n return np.array([dx, dy]), np.array([nx, ny])\n \n # Convert from s, y to x1, y1\n def calcXY(self, s, y):\n x0, y0 = self.calc_position(s)\n \n # Compute normal vector\n dx = self.sx.calcd(s)\n dy = self.sy.calcd(s)\n r = np.sqrt(dx**2 + dy**2)\n nx = - dy / r\n ny = dx / r\n \n x1 = x0 + y * nx\n y1 = y0 + y * ny\n \n return x1, y1\n \n # Convert from x1, y1 to s, y\n # eps = 1e-4, maxIter = 100\n def calcSY(self, x1, y1):\n # maxIter = 10, shrink=0.9, startSize = 5\n # Compute the point which minimizes distance from x1, y1 to x0, y0 \n # Potentially refine by repeating process for increasingly\n # narrow windows or by making inner product between point - center\n # and tangent 0\n point = np.array([x1, y1])\n sVals = self.PointTangent[:,0]\n centers = self.PointTangent[:,1:3]\n dists = np.sqrt(np.sum(np.square(point - centers), axis=1))\n ind = np.argmin(dists)\n s = sVals[ind]\n # Make it positive displacement if aligned with normal and negative\n # else\n \n # Compute normal vector\n dx = self.sx.calcd(s)\n dy = self.sy.calcd(s)\n r = np.sqrt(dx**2 + dy**2)\n nx = - dy / r\n ny = dx / r\n \n # Should be equivalent to just doing np.dot and not using dists[ind]\n y = dists[ind] * np.sign(np.dot(np.array([nx, ny]), point-centers[ind])) \n \n # count = 0\n # while count < maxIter:\n # dists = np.sqrt(np.sum(np.square(point - centers), axis=1))\n # ind = np.argmin(dists)\n # s = sVals[ind]\n # y = dists[ind]\n \n # pdb.set_trace()\n \n # windowSize = shrink**count * min(self.end/2, startSize)\n # PointTangent = np.array([[val, self.calc_position(val)[0], self.calc_position(val)[1], self.sx.calcd(val), self.sy.calcd(val)] for val in np.linspace(s-windowSize/2, s+windowSize/2)])\n # sVals = PointTangent[:,0]\n # centers = PointTangent[:,1:3]\n # count += 1\n # print('count', count)\n # print('s', s)\n # print('y', y)\n # print('x, y',self.calcXY(s, y))\n \n # count = 0\n # inner = 1\n # while abs(inner) > eps and count < maxIter:\n # estNormal = point - np.array(self.calc_position(s))\n # tangent = [self.sx.calcd(s), self.sy.calcd(s)]\n # # Use normalized inner product\n # inner = np.dot(estNormal, tangent) / np.linalg.norm(estNormal) / np.linalg.norm(tangent)\n \n # dx = self.sx.calcd(s)\n # dy = self.sy.calcd(s)\n # r = np.sqrt(dx**2 + dy**2)\n # nx = - dy / r\n # ny = dx / r\n # y = np.dot(np.array([nx, ny]), estNormal)\n # s += inner # Move in direction of inner product\n # s = max(0, min(s, self.end)) # Make sure remains in bounds\n # count += 1\n \n return s, y\n\ndef calc_spline_course(x, y, ds=0.1):\n sp = Spline2D(x, y)\n s = list(np.arange(0, sp.s[-1], ds))\n\n rx, ry, ryaw, rk = [], [], [], []\n for i_s in s:\n ix, iy = sp.calc_position(i_s)\n rx.append(ix)\n ry.append(iy)\n ryaw.append(sp.calc_yaw(i_s))\n rk.append(sp.calc_curvature(i_s))\n\n return rx, ry, ryaw, rk, s\n\ndef fit_path(path, ds = 0.1):\n x = path[:,0]\n y = path[:,1]\n sp = Spline2D(x, y)\n s = np.arange(0, sp.s[-1], ds)\n\n new_path = []\n for i_s in s:\n ix, iy = sp.calc_position(i_s)\n new_path.append((ix, iy))\n return new_path\n\n\ndef main(): # pragma: no cover\n print(\"Spline 2D test\")\n import matplotlib.pyplot as plt\n # x = [-2.5, 0.0, 2.5, 5.0, 7.5, 3.0, -1.0]\n # y = [0.7, -6, 5, 6.5, 0.0, 5.0, -2.0]\n \n path = np.load('path.npy')\n \n x = path[:,0]\n y = path[:,1]\n \n plt.figure()\n plt.title('Original path')\n plt.scatter(x, y)\n \n ds = 0.1 # [m] distance of each interpolated points\n\n sp = Spline2D(x, y)\n s = np.arange(0, sp.s[-1], ds)\n\n rx, ry, ryaw, rk = [], [], [], []\n for i_s in s:\n ix, iy = sp.calc_position(i_s)\n rx.append(ix)\n ry.append(iy)\n ryaw.append(sp.calc_yaw(i_s))\n rk.append(sp.calc_curvature(i_s))\n\n plt.subplots(1)\n plt.plot(x, y, \"xb\", label=\"input\")\n plt.plot(rx, ry, \"-r\", label=\"spline\")\n plt.grid(True)\n plt.axis(\"equal\")\n plt.xlabel(\"x[m]\")\n plt.ylabel(\"y[m]\")\n \n # Plot the trajectory with dx, dy overlaid as quiver field\n # sVals = np.linspace(0, sp.end, endpoint=False)\n # xVals = [sp.calc_position(s)[0] for s in sVals]\n # yVals = [sp.calc_position(s)[1] for s in sVals]\n # dxVals = [sp.sx.calcd(s) for s in sVals]\n # dyVals = [sp.sy.calcd(s) for s in sVals]\n # plt.quiver(xVals, yVals, dxVals, dyVals, scale=1)\n \n plt.legend()\n\n plt.subplots(1)\n plt.plot(s, [np.rad2deg(iyaw) for iyaw in ryaw], \"-r\", label=\"yaw\")\n plt.grid(True)\n plt.legend()\n plt.xlabel(\"line length[m]\")\n plt.ylabel(\"yaw angle[deg]\")\n\n plt.subplots(1)\n plt.plot(s, rk, \"-r\", label=\"curvature\")\n plt.grid(True)\n plt.legend()\n plt.xlabel(\"line length[m]\")\n plt.ylabel(\"curvature [1/m]\")\n\n plt.show()\n\n plt.subplots(1)\n plt.title('Plotting the numerical derivative components')\n sVals = np.linspace(0, sp.end, int(sp.end/sp.ds), endpoint=False)\n xVals = [sp.calc_position(s)[0] for s in sVals]\n yVals = [sp.calc_position(s)[1] for s in sVals]\n dxVals = [sp.sx.calcd(s) for s in sVals]\n dyVals = [sp.sy.calcd(s) for s in sVals]\n plt.scatter(sVals, dxVals, label='dx')\n plt.scatter(sVals, dyVals, label='dy')\n plt.xlabel('s')\n plt.legend()\n\n # Note that should choose a point that is not too far from path otherwise no \n # guarantees since mapping only local\n \n s = np.random.uniform(0, sp.end)\n y = np.random.uniform(0, 0.5)\n x1, y1 = sp.calcXY(s,y)\n print('s','y', s, y)\n print('x1','y1', x1, y1)\n print('after invert: s, y', sp.calcSY(*sp.calcXY(s,y)))\n print('after invert: x1, y1', sp.calcXY(*sp.calcSY(x1,y1)))\n pdb.set_trace()\n\n# if __name__ == '__main__':\n# main()","repo_name":"sarahz916/RRT-LMPC","sub_path":"make_demos/cubic_spline_planner.py","file_name":"cubic_spline_planner.py","file_ext":"py","file_size_in_byte":12616,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"}
+{"seq_id":"37516405591","text":"from .model import Model\nimport torch\nfrom torch import from_numpy\nimport numpy as np\nfrom torch.optim.adam import Adam\nfrom torch.optim.lr_scheduler import LambdaLR\nfrom Common.utils import explained_variance, mean_of_list\n\n\nclass Brain:\n def __init__(self, **config):\n self.config = config\n self.n_workers = self.config[\"n_workers\"]\n self.epsilon = self.config[\"clip_range\"]\n self.device = torch.device(\"cuda\") if torch.cuda.is_available() else torch.device(\"cpu\")\n\n self.policy = Model(self.config[\"state_shape\"], self.config[\"n_actions\"]).to(self.device)\n\n self.optimizer = Adam(self.policy.parameters(), lr=self.config[\"lr\"])\n self.schedule_fn = lambda step: max(1.0 - float(step / self.config[\"total_iterations\"]), 0)\n self.scheduler = LambdaLR(self.optimizer, lr_lambda=self.schedule_fn)\n\n def get_actions_and_values(self, state, batch=False):\n if not batch:\n state = np.expand_dims(state, 0)\n state = from_numpy(state).to(self.device)\n with torch.no_grad():\n dist, value, action_prob = self.policy(state)\n action = dist.sample()\n log_prob = dist.log_prob(action)\n return action.cpu().numpy(), value.cpu().numpy().squeeze(), log_prob.cpu().numpy(), action_prob.cpu().numpy()\n\n def choose_mini_batch(self, states, actions, returns, advs, values, log_probs):\n full_batch_size = len(states)\n states = torch.ByteTensor(states).to(self.device)\n actions = torch.ByteTensor(actions).to(self.device)\n advs = torch.Tensor(advs).to(self.device)\n returns = torch.Tensor(returns).to(self.device)\n values = torch.Tensor(values).to(self.device)\n log_probs = torch.Tensor(log_probs).to(self.device)\n\n indices = np.random.randint(0, full_batch_size, (self.n_workers, self.config[\"batch_size\"]))\n\n for idx in indices:\n yield states[idx], actions[idx], returns[idx], advs[idx], values[idx], log_probs[idx]\n\n @mean_of_list\n def train(self, states, actions, rewards, dones, values, log_probs, next_values):\n returns = self.get_gae(rewards, values, next_values, dones)\n values = np.concatenate(values)\n advs = returns - values\n advs = (advs - advs.mean()) / (advs.std() + 1e-8)\n\n pg_losses, v_losses, entropies, kls, norms = [], [], [], [], []\n for epoch in range(self.config[\"n_epochs\"]):\n for state, action, q_value, adv, old_value, old_log_prob in self.choose_mini_batch(states,\n actions,\n returns,\n advs,\n values,\n log_probs):\n dist, value, _ = self.policy(state)\n entropy = dist.entropy().mean()\n new_log_prob = dist.log_prob(action)\n ratio = (new_log_prob - old_log_prob).exp()\n actor_loss = self.compute_ac_loss(ratio, adv)\n\n clipped_value = old_value + torch.clamp(value.squeeze() - old_value, -self.epsilon, self.epsilon)\n clipped_v_loss = (clipped_value - q_value).pow(2)\n unclipped_v_loss = (value.squeeze() - q_value).pow(2)\n critic_loss = 0.5 * torch.max(clipped_v_loss, unclipped_v_loss).mean()\n\n total_loss = critic_loss + actor_loss - self.config[\"ent_coeff\"] * entropy\n norm = self.optimize(total_loss)\n\n approxkl = 0.5 * (new_log_prob - old_log_prob).pow(2).mean() # http://joschu.net/blog/kl-approx.html\n\n pg_losses.append(actor_loss.item())\n v_losses.append(critic_loss.item())\n entropies.append(entropy.item())\n kls.append(approxkl.item())\n norms.append(norm.item())\n\n return pg_losses, v_losses, entropies, kls, norms, explained_variance(values, returns)\n\n def schedule_lr(self):\n self.scheduler.step()\n\n def schedule_clip_range(self, iter):\n self.epsilon = max(1.0 - float(iter / self.config[\"total_iterations\"]), 0) * self.config[\"clip_range\"]\n\n def optimize(self, loss):\n self.optimizer.zero_grad()\n loss.backward()\n if self.config[\"clip_grad_norm\"][\"do\"]:\n grad_norm = torch.nn.utils.clip_grad_norm_(self.policy.parameters(),\n self.config[\"clip_grad_norm\"][\"max_grad_norm\"])\n self.optimizer.step()\n return grad_norm\n\n def get_gae(self, rewards, values, next_values, dones):\n gamma = self.config[\"gamma\"]\n lam = self.config[\"lambda\"]\n\n returns = [[] for _ in range(self.n_workers)]\n extended_values = np.zeros((self.n_workers, self.config[\"rollout_length\"] + 1))\n for worker in range(self.n_workers):\n extended_values[worker] = np.append(values[worker], next_values[worker])\n gae = 0\n for step in reversed(range(self.config[\"rollout_length\"])):\n delta = rewards[worker][step] + \\\n gamma * (extended_values[worker][step + 1]) * (1 - dones[worker][step]) \\\n - extended_values[worker][step]\n gae = delta + gamma * lam * (1 - dones[worker][step]) * gae\n returns[worker].insert(0, gae + extended_values[worker][step])\n\n return np.concatenate(returns)\n\n def compute_ac_loss(self, ratio, adv):\n new_r = ratio * adv\n clamped_r = torch.clamp(ratio, 1 - self.epsilon, 1 + self.epsilon) * adv\n loss = torch.min(new_r, clamped_r)\n loss = -loss.mean()\n return loss\n\n def set_from_checkpoint(self, checkpoint):\n self.policy.load_state_dict(checkpoint[\"current_policy_state_dict\"])\n self.optimizer.load_state_dict(checkpoint[\"optimizer_state_dict\"])\n self.scheduler.load_state_dict(checkpoint[\"scheduler_state_dict\"])\n\n def set_to_eval_mode(self):\n self.policy.eval()\n","repo_name":"alirezakazemipour/Mario-PPO","sub_path":"Brain/brain.py","file_name":"brain.py","file_ext":"py","file_size_in_byte":6331,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"21"}
+{"seq_id":"42608201593","text":"#!/usr/bin/python\n# -*- coding: utf-8 -*-\n\n## General Command\n # outdir = \"/home/sgupta755/gitfolder/Debugging/output\"\n # indir = \"/home/sgupta755/gitfolder/Debugging/predictions\"\n # assembly_dir = \"/home/sgupta755/gitfolder/Debugging/assemblies\"\n # piler_cr_converter = \"/home/sgupta755/gitfolder/Team1-FunctionalAnnotation/CRISPRFileToGFF_1.pl\"\n# python FunctionalAnnotationPipeline.py -i /home/sgupta755/gitfolder/Team1-FunctionalAnnotation/sample_output -o /home/sgupta755/gitfolder/Team1-FunctionalAnnotation/functional_output -a /home/sgupta755/gitfolder/Team1-FunctionalAnnotation/assemblies -c FAmodule/CRISPRFileToGFF_1.pl\n\n# Each tool will have their own functions\n\nimport argparse\nimport os\nimport re\nimport subprocess\nimport time\nfrom FAmodule.signalp_script_func import signalP\nfrom FAmodule.eggScript import getFile\nfrom FAmodule.tmhmm import tmhmm, converttogff\nfrom FAmodule.pilercr_module import piler_cr_module\nfrom FAmodule.vfdb_module import vfdb_module\nfrom FAmodule.GFF_merger import GFF_Merge\nimport multiprocessing as mp\nimport time\nfrom tqdm import tqdm\n\n# USearch Clustering\n\n\n\ndef usearch_command(sample, path, outputpath = \".\", pid = 0.97):\n # Running usearch command\n try:\n os.mkdir(os.path.join(outputpath, sample))\n except:\n print(\"Folder already made\")\n cmd = \"cat \"+ path + \"> \" + \"ClusterFaa\"\n # cmd = cmd.split()\n os.system(cmd)\n command = \"usearch -cluster_fast \" + \"ClusterFaa\" + \" -id \"+str(pid)+\" -centroids \" + os.path.join(outputpath) + \"/Centroids.fasta -uc \" + os.path.join(outputpath, sample) + \"/Clusters.uc\"\n command = command.split()\n subprocess.check_output(command)\n os.system(\"rm CLusterFaa\")\n\n\ndef usearch_multi_runner(dirpath=\".\", output2 = \".\", pid=0.97):\n # Running usearch on multiple\n faainputs = []\n for root, dirs, files in os.walk(dirpath, topdown=False):\n for name in files:\n if re.search(pattern=\".faa\", string=root + name) and re.search(pattern=\"uniq\", string=root + name):\n faainputs.append(os.path.join(root, name))\n faainputs = list(zip(faainputs, dirs))\n # print(dirs)\n # for dir in dirs:\n # print(dir)\n patho = \"\"\n for fi, isolate in faainputs:\n patho += fi + \" \"\n usearch_command(\"\", patho, output2, pid)\n print(\"USearch clustering done\")\n\ndef rgi_2_gff(temp_file):\n with open(temp_file, encoding='latin-1') as f:\n lines = f.readlines()\n del lines[0]\n out_content = '##gff-version 3\\n'\n for line in lines:\n items = [l for l in line.replace(' ', '\\t').split('\\t') if l]\n out_content += items[0] + '\\t'\n out_content += 'RGI-CARD\\tAntibiotic resistant genes\\t'\n start, end = items[2],items[4]\n out_content += '{}\\t{}\\t'.format(start, end)\n out_content += '.\\t.\\t.\\t'\n out_content += ';'.join(items[8:-2])\n out_content += '\\n'\n out_content = out_content[:-1]\n with open(\"%s.gff\"%(temp_file), 'w') as f:\n f.write(out_content)\n\ndef card_rgi_runner(indir, outdir):\n \"\"\"\n\n :param indir: Input directory\n :param outdir: Output directory\n :return: None. Just runs the command.\n \"\"\"\n print(outdir)\n try:\n os.mkdir(os.path.join(outdir, \"database\"))\n print(f\"{os.path.join(outdir, 'database')} created\")\n except:\n print(\"Folder already exists\")\n # try:\n # os.chdir(os.path.join(outdir, \"database\"))\n # except:\n print(\"Already there\")\n if not os.path.exists(os.path.join(outdir, \"database\", 'card.json')):\n print(f\"wget -P {os.path.join(outdir, 'database')} https://card.mcmaster.ca/latest/data\")\n subprocess.check_output([\"wget\", \"-P\",os.path.join(outdir, \"database\"),\"https://card.mcmaster.ca/latest/data\"])\n print(f\"tar -xvf {os.path.join(outdir, 'database', 'data')} -C {os.path.join(outdir, 'database')}\")\n subprocess.check_output([\"tar\", \"-xvf\", os.path.join(outdir,\"database\",\"data\"), \"-C\",os.path.join(outdir, \"database\")])\n subprocess.call([\"rgi\", \"load\", \"--card_json\", os.path.join(outdir, \"database\", \"card.json\")])\n try:\n os.mkdir(os.path.join(outdir))\n except:\n print(\"Already made\")\n\n inputsfile = []\n for root, dirs, files in os.walk(indir, topdown=False):\n for name in files:\n if re.search(pattern=\".fasta\", string=root + name) and not re.search(pattern=\".fai\", string=root + name):\n inputsfile.append(os.path.join(root, name))\n isolates = [f for f in os.listdir(os.path.join(indir))]\n inputs = list(zip(inputsfile, isolates))\n\n for ins, isos in inputs:\n print(f\"Running card-rgi main for {isos} where assembly file is in {ins}\")\n start = time.time()\n try:\n os.mkdir(os.path.join(outdir, \"CardOutput\", isos))\n except:\n print(\"Folder already exists\")\n command = \"rgi main -i \"+os.path.join(ins)+\" -o \"+os.path.join(outdir,\"CARD\"+isos)+\" -n 6\"\n command = command.split()\n subprocess.check_output(command)\n stop = time.time()\n rgi_2_gff(os.path.join(outdir,\"CARD\"+isos+\".txt\"))\n print(f\"Time taken for {isos} is {stop-start}s\")\n # os.chdir(os.path.join(outdir))\n # subprocess.check_output([\"rm\", \"-r\", \"contigs*\"])\n # subprocess.check_output([\"rm\", \"-r\", \"*json\"])\n return None\n\n\ndef tmhmm_runner(indir, outdir):\n tmhmm(indir, outdir)\n converttogff(outdir)\n return None\n \n# TODO: merge command function\n\ndef main():\n # warnings.filterwarnings(\"ignore\")\n # Calling argparse and creating the parser class object\n\n parser = argparse.ArgumentParser(description=\"Parser for functional annotation\")\n parser.add_argument(\"-i\", metavar=\"Absolute path of the directory containing the isolates\", type=str, required=True)\n parser.add_argument(\"-o\", metavar=\"Relative output directory path\",\n help=\"Path for output directory. If it does not exist it \"\n \"will be created.\", type=str, required=True)\n parser.add_argument(\"-a\", metavar=\"Absolute path of assembly fastq files\", type=str, required=True) # Required for pilerCR and CARD-RGI\n parser.add_argument(\"-c\", metavar=\"Perl GFF Converter for CRISPR\", type=str, required=True)\n parser.add_argument(\"-p\", metavar=\"Percentage of identity\", type=float, default=0.97)\n \n args = parser.parse_args()\n \n currentdirectory = os.getcwd()\n #\n try:\n os.mkdir(os.path.join(currentdirectory, args.o))\n except:\n print(\"Folder already exists\")\n \n \n\n # Input directory and output directory\n indir = args.i\n outdir = args.o\n assembly_dir = args.a\n piler_cr_converter = args.c\n\n # outdir = \"/home/sgupta755/gitfolder/Debugging/output\"\n # indir = \"/home/sgupta755/gitfolder/Debugging/predictions\"\n # assembly_dir = \"/home/sgupta755/gitfolder/Debugging/assemblies\"\n # piler_cr_converter = \"/home/sgupta755/gitfolder/Team1-FunctionalAnnotation/CRISPRFileToGFF_1.pl\"\n \n if not os.path.exists(outdir):\n os.makedirs(outdir)\n\n t1 = time.time()\n \n if not os.path.exists(os.path.join(outdir, \"CardRGI\")):\n os.mkdir(os.path.join(outdir, \"CardRGI\"))\n if not os.path.exists(os.path.join(outdir, \"VFDB\")):\n os.mkdir(os.path.join(outdir, \"VFDB\"))\n if not os.path.exists(os.path.join(outdir, \"pilerCR\")):\n os.mkdir(os.path.join(outdir, \"pilerCR\"))\n if not os.path.exists(os.path.join(outdir, \"signalP\")):\n os.mkdir(os.path.join(outdir, \"signalP\"))\n if not os.path.exists(os.path.join(outdir, \"eggNOG-mapper\")):\n os.mkdir(os.path.join(outdir, \"eggNOG-mapper\"))\n if not os.path.exists(os.path.join(outdir, \"tmhmm\")):\n os.mkdir(os.path.join(outdir, \"tmhmm\"))\n\n vfdb_module(input_dir=indir, output_dir=os.path.join(outdir, \"VFDB\"))\n piler_cr_module(assembly_dir, os.path.join(outdir, \"pilerCR\"), piler_cr_converter)\n t3 = time.time()\n signalP(mypath = indir, path = os.path.join(outdir, \"signalP\"))\n print(f\"Time taken for signalP is {time.time()-t3}s\")\n\n # card_rgi_runnerp = mp.Process(target=card_rgi_runner, args=(assembly_dir, os.path.join(outdir, \"CardRGI\")))\n getfilep = mp.Process(target=getFile, args=(indir, os.path.join(outdir, \"eggNOG-mapper\")))\n tmhmm_runnerp = mp.Process(target=tmhmm_runner, args=(indir, os.path.join(outdir, \"tmhmm\")))\n processes = [tmhmm_runnerp, getfilep]\n for p in processes:\n p.start()\n \n for p in processes:\n p.join()\n try:\n os.mkdir(os.path.join(outdir, \"FinalResults\"))\n except:\n print(\"File already made\")\n GFF_Merge(outdir, os.path.join(outdir, \"FinalResults\"), indir)\n t2 = time.time()\n print(f\"Total time taken is {t2-t1}s\")\n\n # Clean up\n os.system(\"rm -r \" + os.path.join(outdir, \"CardRGI\"))\n os.system(\"rm -r \" + os.path.join(outdir, \"VFDB\"))\n os.system(\"rm -r \" + os.path.join(outdir, \"pilerCR\"))\n os.system(\"rm -r \" + os.path.join(outdir, \"signalP\"))\n os.system(\"rm -r \" + os.path.join(outdir, \"eggNOG-mapper\"))\n os.system(\"rm -r \" + os.path.join(outdir, \"tmhmm\"))\n os.system(\"rm -r TMH*\")\n os.system(\"rm -r *.gff\")\n os.system(\"rm -r \" + \"TMHMM*\")\n \nif __name__ == \"__main__\":\n main()\n","repo_name":"Hanuphant/Webserver_Computational_Genomics","sub_path":"backend/scripts/FunctionalAnnotationPipeline.py","file_name":"FunctionalAnnotationPipeline.py","file_ext":"py","file_size_in_byte":9253,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"}
+{"seq_id":"19868526007","text":"count = 0\n\ndef isOk(arr,n):\n \n for i in range(n):\n if arr[i] == arr[n]:\n \n return False\n if abs(n - i) == abs(arr[n]-arr[i]):\n \n return False\n return True \n\ndef nQueen(arr,n):\n \n global count \n if n == N:\n count += 1\n return\n for i in range(N):\n arr[n] = i\n \n if isOk(arr,n):\n \n nQueen(arr,n+1)\n arr[n] = 0 \n \n\nN = int(input())\narr = [-1 for _ in range(N)]\n\nnQueen(arr,0)\nprint(count)\n","repo_name":"cocorig/challenge100-codingtest-study","sub_path":"wlwl1011/BOJ/heybob/4회/9663.py","file_name":"9663.py","file_ext":"py","file_size_in_byte":517,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"21"}
+{"seq_id":"21449444475","text":"# -*- coding: utf-8 -*-\n'''\nManage dingtalk messages.\n'''\nimport time\nimport json\nimport urllib.parse\nfrom ..util.conf import get_config\nfrom ..util.api import client\n\n\ndef get_pc_link(link, pc_slide='true'):\n '''\n 获取pc跳转url\n '''\n pc_slide = 'true' if pc_slide == 'true' else 'false'\n pc_link = 'dingtalk://dingtalkclient/page/link?pc_slide=%s&url=%s'\\\n % (pc_slide, urllib.parse.quote(link))\n return pc_link\n\n\nclass Message(dict):\n def as_msg(self):\n msg = {'msgtype': self.msgtype}\n msg[self.msgtype] = dict(self)\n return msg\n\n\nclass TextMessage(Message):\n msgtype = 'text'\n\n def __init__(self, content):\n self['content'] = content\n\n\nclass ImageMessage(Message):\n msgtype = 'image'\n\n def __init__(self, media_id):\n self['media_id'] = media_id\n\n\nclass VoiceMessage(Message):\n msgtype = 'voice'\n\n def __init__(self, media_id, duration=None):\n self['media_id'] = media_id\n if duration:\n self['duration'] = duration\n\n\nclass FileMessage(Message):\n msgtype = 'file'\n\n def __init__(self, media_id):\n self['media_id'] = media_id\n\n\nclass LinkMessage(Message):\n msgtype = 'link'\n\n def __init__(self, messageUrl, picUrl, title, text):\n self['messageUrl'] = messageUrl\n self['picUrl'] = picUrl\n self['title'] = title\n self['text'] = text\n\n\nclass OAMessage(Message):\n msgtype = 'oa'\n\n def __init__(self, message_url, head, body,\n pc_message_url):\n self['message_url'] = message_url\n self['head'] = head\n self['body'] = body\n if pc_message_url is not None:\n self['pc_message_url'] = pc_message_url\n\n\nclass MarkdownMessage(Message):\n msgtype = 'markdown'\n\n def __init__(self, title, text):\n self['title'] = title\n self['text'] = text\n\n\nclass ActionCardMessage(Message):\n msgtype = 'action_card'\n optional_fields = ['single_title', 'single_url=None',\n 'btn_orientation', 'btn_json_list']\n\n def __init__(self, title, markdown,\n single_title=None, single_url=None,\n btn_orientation=None, btn_json_list=None):\n self['title'] = title\n self['markdown'] = markdown\n for field_name in self.optional_fields:\n if locals().get(field_name) is not None:\n self[field_name] = locals()[field_name]\n\n\ndef corpconversation_asyncsend(agent_id=None, msg=None,\n userid_list=None, dept_id_list=None, to_all_user=False):\n '''\n 发送企业通知消息\n\n Param\n '''\n if agent_id is None:\n agent_id = get_config().get('agent_id')\n if not (agent_id and msg):\n raise Exception(\"Both agent_id and msg must be provided.\")\n if isinstance(userid_list, list):\n userid_list = ','.join(userid_list)\n if isinstance(dept_id_list, list):\n userid_list = ','.join(dep_id_list)\n params = {k: v for k, v in dict(agent_id=agent_id,\n userid_list=userid_list,\n dept_id_list=dept_id_list,\n to_all_user=to_all_user).items() if v}\n if isinstance(msg, Message):\n msg = msg.as_msg()\n params['msg'] = json.dumps(msg)\n resp = client.call('POST',\n '/topapi/message/corpconversation/asyncsend_v2',\n data=params)\n return resp.json()\n\n\ndef corpconversation_asyncsendbycode(agent_id=None, msg=None,\n userid_list=None, dept_id_list=None,\n to_all_user=False, code=None):\n '''\n 通过用户授权码发送企业通知消息\n '''\n if agent_id is None:\n agent_id = get_config().get('agent_id')\n if not (agent_id and msg and code):\n raise Exception(\"All of agent_id, msg and code must be provided.\")\n if isinstance(userid_list, list):\n userid_list = ','.join(userid_list)\n if isinstance(dept_id_list, list):\n userid_list = ','.join(dep_id_list)\n params = {k: v for k, v in dict(agent_id=agent_id,\n userid_list=userid_list,\n dept_id_list=dept_id_list,\n to_all_user=to_all_user,\n code=code).items() if v}\n params['msgtype'] = msg.msgtype\n params['msgcontent'] = json.dumps(dict(msg))\n resp = client.call('POST',\n '/topapi/message/corpconversation/asyncsendbycode',\n data=params)\n return resp.json()\n\n\ndef corpconversation_getsendprogress(agent_id=None, task_id=None):\n '''\n 获取企业通知消息的发送进度\n '''\n if agent_id is None:\n agent_id = get_config().get('agent_id')\n if not (agent_id and task_id):\n raise Exception(\"Both agent_id and task_id must be provided.\")\n params = {'agent_id': agent_id,\n 'task_id': task_id}\n resp = client.call('POST',\n '/topapi/message/corpconversation/getsendprogress',\n data=params)\n return resp.json()\n\n\ndef corpconversation_getsendresult(agent_id=None, task_id=None):\n '''\n 获取企业通知消息的发送结果\n '''\n if agent_id is None:\n agent_id = get_config().get('agent_id')\n if not (agent_id and task_id):\n raise Exception(\"Both agent_id and task_id must be provided.\")\n params = {'agent_id': agent_id,\n 'task_id': task_id}\n resp = client.call('POST',\n '/topapi/message/corpconversation/getsendresult',\n data=params)\n return resp.json()\n","repo_name":"socrateslee/dingle","sub_path":"dingle/dingtalk/message.py","file_name":"message.py","file_ext":"py","file_size_in_byte":5693,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"}
+{"seq_id":"32166165062","text":"\"\"\"empty message\n\nRevision ID: 490d6ca57fb0\nRevises: \nCreate Date: 2020-02-18 22:57:18.757064\n\n\"\"\"\nfrom alembic import op\nimport sqlalchemy as sa\n\n\n# revision identifiers, used by Alembic.\nrevision = '490d6ca57fb0'\ndown_revision = None\nbranch_labels = None\ndepends_on = None\n\n\ndef upgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.add_column('questions', sa.Column('recieve_user_image_url', sa.String(length=1024), nullable=True))\n op.add_column('questions', sa.Column('send_user_image_url', sa.String(length=1024), nullable=True))\n op.drop_column('questions', 'profile_image_url')\n op.drop_column('questions', 'answer_image_url')\n # ### end Alembic commands ###\n\n\ndef downgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.add_column('questions', sa.Column('answer_image_url', sa.VARCHAR(length=1024), nullable=True))\n op.add_column('questions', sa.Column('profile_image_url', sa.VARCHAR(length=1024), nullable=True))\n op.drop_column('questions', 'send_user_image_url')\n op.drop_column('questions', 'recieve_user_image_url')\n # ### end Alembic commands ###\n","repo_name":"kkp6421/flask-question","sub_path":"migrations/versions/490d6ca57fb0_.py","file_name":"490d6ca57fb0_.py","file_ext":"py","file_size_in_byte":1147,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"}
+{"seq_id":"20761329021","text":"print(\"\\n==========================================\")\r\nprint(\" METODE REGULA-FALSI\")\r\nprint(\" Nama : Wahyu Harry Saputra Sembiring\")\r\nprint(\" NIM : 2009106049\")\r\nprint(\" Kelas : Informatika A 2020\")\r\nprint(\"==========================================\\n\")\r\n\r\ndef f(x):\r\n return 2.71828183-5*x**2\r\na = int(input(\"Masukkan selang pertama : \"))\r\nb = int(input(\"Masukkan selang kedua : \"))\r\nn = int(input(\"Masukkan jumlah iterasi : \"))\r\nif f(a) * f(b) > 0:\r\n print(\"Kesalahan Regula-Falsi\")\r\nelse:\r\n k=1\r\n while(k<=n):\r\n c=(a*f(b)-b*f(a))/(f(b)-f(a))\r\n if f(a) * f(c) < 0:\r\n b=c\r\n else:\r\n a=c\r\n print(\"Akar = \", c, \"pada iterasi = \", k)\r\n k = k+1\r\n\r\n# x**3-x-2","repo_name":"wahyusaputra073/Metode-Numerik","sub_path":"MetodeRegulaFalsi.py","file_name":"MetodeRegulaFalsi.py","file_ext":"py","file_size_in_byte":730,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"}
+{"seq_id":"32042745087","text":"\nimport random\nimport time\nglobal Current_Level_XP\nglobal Next_Level_XP\n\nOut_Of_Combat = 1\nHealth = 100\nGold = 0\nLevel = 1\nNext_Level_XP = 100\nCurrent_Level_XP = 0\nx=1\n\ndef Coin_Choice():\n #Subroutine which Carries out a coin flipping Choice, either heads or tails to check if it is valid.\n Choice_Made = 1\n while Choice_Made == 1:\n \n #Takes the input and applies to choice variable and makes lowercase.\n Choice = input()\n Choice = Choice.lower()\n\n #Checks to see if choice is heads or tails. If not then a new answer\n #must be entered.\n if Choice != 'heads' and Choice != 'tails':\n print(\"Please input either heads or tails.\")\n elif Choice == \"heads\":\n print(\"You chose heads\")\n Choice_Made = 2\n else:\n print(\"You chose tails\")\n Choice_Made = 3\n\n #Returns the value for Choice_Made\n return Choice_Made\n \ndef Battle_First_Turn():\n print(\"\")\n print('''A battle is about to start, a coin must be flipped to decide the first turn.\nWhat face of the coin will it land on?''')\n print(\"\")\n #Generates a value as if flipping a coin heads = 2 tails = 3\n Coin_Flip = random.randint(2,3)\n \n #Gathers Choice_Made from Coin_Choice()\n Choice_Made = Coin_Choice()\n\n #If Coin_Made is the same as the face the appropriate phrase is applied.\n if Choice_Made == 2:\n Face_Win = \"Heads!\"\n Face_Fail = \"Tails\"\n else:\n Face_Win = \"Tails!\"\n Face_Fail = \"Heads\"\n\n #If the Choice made is the same as the Face that landed after the coin flip the player gets first turn.\n #Otherwise the enemy gets first turn.\n if Choice_Made == Coin_Flip:\n print(\"The coin landed on...\", end='')\n time.sleep(1)\n print(Face_Win)\n time.sleep(0.5)\n print(\"\")\n print(\"You get the first turn!\")\n First_Turn = 1\n else:\n print(\"The coin landed on...\", end='')\n time.sleep(1)\n print(Face_Fail)\n time.sleep(0.5)\n print(\"\")\n print(\"The enemy gets the first turn!\")\n First_Turn = 0\n return First_Turn\n \ndef Battle():\n global Health\n global Stamina\n global Kill_timer\n global Enemy_Damage\n Kill_timer = 0\n Health = 100\n Stamina = 200\n Enemy_Health = 100\n Valid_Turn = 0\n \n #Checks if player gets first turn.\n First_Turn = Battle_First_Turn()\n\n#States if health is stil higher than 0 then battle continues. \n while Enemy_Health > 1 or Health > 1:\n Kill_timer = Kill_timer + 1\n \n#If first turn is platyers...\n if First_Turn == 1:\n \n#Asks user what he / she wants to do.\n print(\"\")\n print(\"What would you like to do?\")\n print(\"1.Attack\")\n print(\"2.Run\")\n print(\"3.Skip Turn\")\n print(\"\")\n \n#Makes sure the data entered is valid.\n while First_Turn == 1:\n Battle_Choice = input()\n if Battle_Choice != \"1\" and Battle_Choice != \"2\" and Battle_Choice != \"3\":\n print(\"please input either 1, 2 or 3\")\n Valid_Turn = 0\n \n#Data is valid and will use the 1st option.\n#Sets an amount to hit enemy and takes damage off.\n#If the damage is above 15 a critical hit message will appear.\n elif Battle_Choice == \"1\":\n print(\"\")\n print(\"Which attack do you want to use?\")\n print(\"1.Basic : One hit taking 20 stamina\")\n print(\"2.Flurry : Three Consecutive hits taking 150 Stamina\")\n Attack_Choice = input()\n if Attack_Choice == \"1\":\n if Stamina < 20:\n print(\"You dont have enough stamina\")\n \n else:\n Enemy_Damage = random.randint(1,30)\n Stamina = Stamina - 20\n Enemy_Health = Enemy_Health - Enemy_Damage\n print(\"\")\n Damage_Calculator()\n if Enemy_Health < 1:\n Enemy_Health = 0\n print(\"You Won the Battle!\")\n Loot_Generator()\n return\n if Stamina < 0:\n First_Turn = 2\n First_Turn = 2\n Valid_Turn = 1\n \n elif Attack_Choice == \"2\":\n if Stamina < 150:\n print(\"You dont have enough stamina\")\n \n else:\n Enemy_Damage = random.randint(1,30)\n Enemy_Health = Enemy_Health - Enemy_Damage\n time.sleep(0.5)\n Damage_Calculator()\n\n Enemy_Damage = random.randint(1,20)\n Enemy_Health = Enemy_Health - Enemy_Damage\n time.sleep(0.5)\n Damage_Calculator()\n \n Enemy_Damage = random.randint(1,30)\n Enemy_Health = Enemy_Health - Enemy_Damage\n time.sleep(0.5)\n Damage_Calculator()\n \n Stamina = Stamina - 150\n \n if Enemy_Health < 1:\n Enemy_Health = 0\n print(\"You Won the Battle!\")\n Loot_Generator()\n return\n First_Turn = 2\n Valid_Turn = 1\n \n elif Attack_Choice != \"1\" or Attack_Choice != \"1\":\n print(\"Please select a skill with either 1 or 2\")\n \n \n elif Battle_Choice == \"2\":\n Run_Chance = random.randint(1,100)\n if Run_Chance < 30:\n print(\"You managed to escape\")\n return\n else:\n Trip_Loss = random.randint(1,10)\n print(\"You fell and lost \", Trip_Loss, \" Health! and continued to battle.\")\n Health = Health - Trip_Loss\n First_Turn = 2\n\n Valid_Turn = 1\n\n elif Battle_Choice == \"3\":\n print(\"\")\n print(\"You skip your turn\")\n print(\"\")\n First_Turn = 2\n\n \n#Enemy attack\n else:\n print(\"\")\n Enemy_Hit = random.randint(0,20)\n print(\"The enemy attacks hitting \",Enemy_Hit , \"!\", end = \"\")\n Health = Health - Enemy_Hit\n Stamina = Stamina + random.randint(1,10)\n if Enemy_Hit > 15:\n print(\"CRITICAL HIT!\")\n print(\"\")\n print(\"\")\n if Health < 1:\n Health = 0\n print(\"You have died...\")\n return \n else:\n First_Turn = 1\n time.sleep(1)\n Valid_Turn = 1\n\n if Stamina > 200:\n Stamina = 200\n \n \n#Displays player and enemy health and player stamina after every move. \n if Valid_Turn == 1:\n print(\" \")\n print(\"\")\n print(\"Your Health : \", Health, \"/ 100\")\n print(\"Your Stamina : \", Stamina, \"/ 200\")\n print(\"Enemy Health :\", Enemy_Health, \"/ 100\")\n print(\"\")\n \ndef Damage_Calculator():\n print(\"You attack hitting \", Enemy_Damage, \"!\", end = '')\n if Enemy_Damage > 15:\n print(\" CRITICAL HIT!\")\n print(\"\")\n time.sleep(1)\n Valid_Turn = 1\n else:\n print(\"\")\n print(\"\")\n\n#Generates loot and xp depending on player performance.\ndef Loot_Generator():\n global Gold_Gained\n global Gold\n Gold_Gained = 1000 // Kill_timer\n print(\"You have gained \", Gold_Gained, \" gold.\")\n Gold = Gold + Gold_Gained\n Loot = [\"Sword of awesome\", \"Health potion x 2\", \"Nothing\"]\n Loot_Randomiser = random.randint(0,2)\n print(\"Loot: \", Loot[Loot_Randomiser])\n\ndef XP_Generator():\n global Current_Level_XP\n global Level\n global Next_Level_XP\n \n Current_Level_XP = Current_Level_XP + (10 * Kill_timer)\n\n if Current_Level_XP >= Next_Level_XP:\n Previous_Level_XP = Current_Level_XP\n Next_Level_XP = (Previous_Level_XP)*5\n Level = Level + 1\n return\n\n\nprint(\"To use this game, type any of these commands\")\nprint(\"\")\nprint(\"Fight: Starts a battle!\")\nprint(\"Info: Shows player information (Only out of battle)\")\nprint(\"\")\n \nwhile Out_Of_Combat == 1:\n O_of_C_Command = input().lower()\n x = x + 1\n \n#Starts a fight\n if O_of_C_Command =='fight':\n Battle()\n if Health > 0:\n XP_Generator()\n print(\"\")\n Out_Of_Combat = 1\n\n \n elif O_of_C_Command == \"info\":\n print(\"Health: \", Health)\n print(\"Gold: \", Gold,\" Level:\", Level, \" XP: \", Current_Level_XP , \" / \", Next_Level_XP)\n \n\n elif O_of_C_Command == \"secret\":\n print(\"I\", end=\"\")\n time.sleep(0.1)\n print(\" a\", end=\"\")\n time.sleep(0.1)\n print(\"m \", end=\"\")\n time.sleep(0.1)\n print(\"A\", end=\"\")\n time.sleep(0.1)\n print(\"W\", end=\"\")\n time.sleep(0.1)\n print(\"E\", end=\"\")\n time.sleep(0.1)\n print(\"S\", end=\"\")\n time.sleep(0.1)\n print(\"O\", end=\"\")\n time.sleep(0.1)\n print(\"M\", end=\"\")\n time.sleep(0.1)\n print(\"E\", end=\"\")\n time.sleep(0.1)\n print(\"!\")\n time.sleep(0.1)\n\n elif O_of_C_Command == \"regen health\":\n Health = Health + 100\n if Health > 100:\n Health = 100\n print(\" Your Health is now \", Health)\n","repo_name":"JGooch95/Project-Combat-Scene","sub_path":"Project_Combat_Scene.py","file_name":"Project_Combat_Scene.py","file_ext":"py","file_size_in_byte":10340,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"}
+{"seq_id":"25239073432","text":"class EvaluteDivision:\n\n def __init__(self) -> None:\n self.graph = {}\n\n\n def build_equation_value(self, denomirator , numerator, value):\n\n if denomirator in self.graph:\n self.graph[denomirator].append((numerator, value))\n else:\n self.graph[denomirator]=[(numerator, value)]\n\n def find_paths(self, denomirator , numerator):\n\n if denomirator not in self.graph or numerator not in self.graph:\n return -1.0\n\n q = [(denomirator, 1.0)]\n\n visited = set()\n\n while q:\n cur_item, cur_product = q.pop(0)\n\n if cur_item == numerator:\n return cur_product\n\n visited.add(cur_item)\n\n for neighbour, cur_value in self.graph[cur_item]:\n if neighbour not in visited:\n q.append((neighbour, cur_product*cur_value))\n\n return -1\n\n\n def read_input(self, equations, values, quries):\n\n for equation, value in zip(equations, values):\n denomirator , numerator = equation\n self.build_equation_value(denomirator , numerator, value)\n self.build_equation_value(numerator, denomirator , 1/value)\n print(self.graph)\n for query in quries:\n denomirator , numerator = query\n print(self.find_paths(denomirator , numerator))\n\n\n\nED = EvaluteDivision()\nED.read_input([[\"a\",\"b\"],[\"b\",\"c\"],[\"bc\",\"cd\"]], [1.5,2.5,5.0], [[\"a\",\"c\"],[\"c\",\"b\"],[\"bc\",\"cd\"],[\"cd\",\"bc\"]])\n\"\"\"\n3.75\n0.4\n5.0\n0.2\n\"\"\"\n\n\n# soution -2 :\n# class Solution:\n# def calcEquation(self, equations: List[List[str]], values: List[float], queries: List[List[str]]) -> List[float]:\n\n# graph = {}\n \n# def build_graph(equations, values):\n# def add_edge(f, t, value):\n# if f in graph:\n# graph[f].append((t, value))\n# else:\n# graph[f] = [(t, value)]\n \n# for vertices, value in zip(equations, values):\n# f, t = vertices\n# add_edge(f, t, value)\n# add_edge(t, f, 1/value)\n \n# def find_path(query):\n# b, e = query\n \n# if b not in graph or e not in graph:\n# return -1.0\n \n# q = collections.deque([(b, 1.0)])\n# visited = set()\n \n# while q:\n# front, cur_product = q.popleft()\n# if front == e:\n# return cur_product\n# visited.add(front)\n# for neighbor, value in graph[front]:\n# if neighbor not in visited:\n# q.append((neighbor, cur_product*value))\n \n# return -1.0\n \n# build_graph(equations, values)\n# return [find_path(q) for q in queries]\n ","repo_name":"trinath503/Algorithms-And-DataStructures-Python","sub_path":"Graphs/evaluate-division.py","file_name":"evaluate-division.py","file_ext":"py","file_size_in_byte":2906,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"21"}
+{"seq_id":"32575878790","text":"from odoo import http\nfrom odoo.http import request\n\nfrom odoo.addons.sale.controllers.variant import VariantController\n\n\nclass WebsiteSaleVariantController(VariantController):\n @http.route(\n [\"/sale/get_combination_info_minimal_price\"],\n type=\"json\",\n auth=\"public\",\n methods=[\"POST\"],\n website=True,\n )\n def get_combination_info_minimal_price(self, product_template_ids, **kw):\n \"\"\"Special route to use website logic in get_combination_info override.\n This route is called in JS by appending _website to the base route.\n \"\"\"\n\n res = []\n templates = request.env[\"product.template\"].sudo().browse(product_template_ids)\n for template in templates.filtered(lambda t: t.is_published):\n cheaper_variant = template.product_variant_ids.sorted(\n key=lambda p: p._get_combination_info_variant().get(\"price\")\n )[:1]\n res.append(\n {\n \"id\": template.id,\n \"price\": cheaper_variant._get_combination_info_variant().get(\n \"price\"\n ),\n \"distinct_prices\": self._compute_has_distinct_variant_price(\n template\n ),\n }\n )\n\n return res\n\n def _compute_has_distinct_variant_price(self, template):\n if template.product_variant_count > 1:\n prices = template.product_variant_ids.mapped(\"price\")\n if len(prices) > 1:\n return True\n return False\n","repo_name":"nguyenductamlhp/servermns","sub_path":"addons/e-commerce/website_sale_product_minimal_price/controllers/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1593,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"}
+{"seq_id":"20608077035","text":"import os\nimport gc\nimport random\nimport botocore\nimport boto3\nimport requests\nimport multiprocessing\nimport multiprocessing.dummy\n\nrequests.exceptions.ReadTimeout\nrequests.exceptions.ConnectionError\nbotocore.exceptions.ClientError\n\nMAX_RETRIES = 10\n\n#s3 = boto.connect_s3()\ns3C = boto3.client('s3', endpoint_url='http://radosgw.helium:7480/')\n\nclass DirectoryUploader:\n def __init__(self, path, bucketname):\n self.path = path\n self.bucketname = bucketname\n\n def on_item(self, args):\n root, dirs, files = args\n print(root)\n for file in files:\n for x in range(0, MAX_RETRIES):\n try:\n self.on_file(root, dirs, file)\n except (requests.exceptions.ReadTimeout, botocore.exceptions.ClientError, requests.exceptions.ConnectionError):\n print('retrying')\n continue\n except TypeError:\n print('TypeError, retrying')\n continue\n except FileNotFoundError:\n break\n else:\n break\n else:\n print('Failed to handle {}'.format(file))\n return root\n\n def on_file(self, root, dirs, file):\n key = os.path.join(root,file).lstrip('./')\n print('\\t' + key)\n try:\n resp = s3C.head_object(Bucket=self.bucketname, Key=key)\n except botocore.exceptions.ClientError:\n resp = None\n #print(repr(resp))\n \"\"\"\n try:\n if resp is None or resp['ResponseMetadata']['HTTPStatusCode'] != 200:\n s3C.upload_file(key, Bucket=self.bucketname, Key=key)\n finally:\n s3C.put_object_acl(ACL='public-read', Bucket=self.bucketname, Key=key)\n \"\"\"\n if resp is None or resp['ResponseMetadata']['HTTPStatusCode'] != 200:\n s3C.upload_file(key, Bucket=self.bucketname, Key=key,\n ExtraArgs={'ACL': 'public-read'})\n\n def do(self):\n with multiprocessing.Pool(100) as p:\n for dir_ in p.imap(self.on_item, os.walk(self.path)):\n if random.randint(0, 10000):\n gc.collect()\n print(dir_)\n #for dir_ in map(self.on_item, os.walk(self.path)):\n # print(dir_)\n\nDirectoryUploader('.', 'octodonfr').do()\n","repo_name":"progval/ceph-scripts","sub_path":"masto_up.py","file_name":"masto_up.py","file_ext":"py","file_size_in_byte":2369,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"}
+{"seq_id":"25339800483","text":"\"\"\"\nURL mappings for the artifacts app\n\"\"\"\nfrom django.urls import path, include\nfrom rest_framework.routers import DefaultRouter\nfrom artifacts import views\n\napp_name = 'artifacts'\n\nrouter = DefaultRouter()\nrouter.register(app_name, views.ArtifactsViewSet,\n basename=app_name)\n\nurlpatterns = [\n path('', include(router.urls))\n]\n","repo_name":"samKenpachi011/bwhistory-app-api","sub_path":"app/artifacts/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":347,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"}
+{"seq_id":"41482414987","text":"import socket\nimport vgamepad as vg\nimport threading\n\n\nHOST = '192.168.199.1'\n\nPORT1 = 62221\nPORT2 = 62222\ngamepad = vg.VX360Gamepad()\n\ndef receive_wheel():\n with socket.socket(socket.AF_INET, socket.SOCK_DGRAM) as s:\n s.bind((HOST, PORT1))\n print(\"Listening Wheel\")\n while True:\n wheel, addr = s.recvfrom(128)\n Wheel = int.from_bytes(wheel, 'little', signed = True) \n print(Wheel)\n gamepad.left_joystick(x_value = Wheel, y_value = 2048)\n gamepad.update()\n\ndef receive_pad():\n with socket.socket(socket.AF_INET, socket.SOCK_DGRAM) as s:\n s.bind((HOST, PORT2))\n print(\"Listening Pad\")\n\n while True:\n # get the throttle\n throttle, addr = s.recvfrom(128)\n # get the break\n breaking, addr = s.recvfrom(128)\n Throttle = int.from_bytes(throttle, 'little', signed = False) \n Breaking = int.from_bytes(breaking, 'little', signed = True) \n print(Throttle)\n print(Breaking)\n gamepad.right_trigger(Throttle)\n gamepad.left_trigger(Breaking)\n gamepad.update()\n\n\nif __name__ == '__main__':\n threading.Thread(target = receive_pad).start()\n threading.Thread(target = receive_wheel).start()\n","repo_name":"huroy5518/project_group17_pc","sub_path":"socket_conn.py","file_name":"socket_conn.py","file_ext":"py","file_size_in_byte":1304,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"}
+{"seq_id":"7787953809","text":"import os\n\npwd_path = os.path.abspath(os.path.dirname(os.path.dirname(__file__)))\n# os.path.dirname(path)--去掉文件名,返回目录\n# _file_--表示当前文件的完整路径\n# os.path.abspath(__file__)--返回当前完整路径\n# print(pwd_path) E:\\NLP\\nlp-beginner-finish-master\\task1\nclass LrConfig(object):\n # 训练模型用到的路径\n dataset_path = os.path.join(pwd_path + '/data' + \"/train.txt\")\n stopwords_path = os.path.join(pwd_path + '/data' + \"/stopwords.txt\")\n tfidf_model_save_path = os.path.join(pwd_path + '/model' + \"/tfidf_model.m\")\n categories_save_path = os.path.join(pwd_path + '/data' + '/label.txt') # 分类类别数据\n lr_save_dir = os.path.join(pwd_path + '/model' + \"/checkpoints\")\n lr_save_path = os.path.join(lr_save_dir, 'best_validation')\n # 变量\n num_epochs = 100 # 总迭代轮次\n num_classes = 2 # 类别数\n print_per_batch = 10 # 每多少轮输出一次结果\n","repo_name":"Scottyoung99/CCF-BDCI-2020-QA-matching-in-Real-Estate","sub_path":"Machine Learning/config/lr_config.py","file_name":"lr_config.py","file_ext":"py","file_size_in_byte":950,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"}
+{"seq_id":"17105156347","text":"\nfrom multiprocessing.sharedctypes import Value\nimport re\nimport os\nimport sys\nimport json\nimport uuid\nimport pickle\n\nimport humanize\nimport datetime\nimport inspect\nimport logging\nfrom time import time\nfrom functools import wraps\nfrom datetime import datetime\nfrom typing import Tuple, Callable, Union, Dict, List, Optional\nfrom .utils import (\n get_params, parse_time, random_string, get_format_groups, \n get_next_format_group, get_function_name,\n)\nfrom .backends import Backend\n\n# Dictionary are not hashable and the python hash is not consistent\n# between runs so we have to use an external dictionary hashing package\n# else we will not be able to load the saved caches.\nfrom dict_hash import sha256, Hashable\n\nlog_levels = {\n \"debug\":logging.DEBUG,\n \"info\":logging.INFO,\n \"warn\":logging.WARN,\n \"warning\":logging.WARNING,\n \"error\":logging.ERROR,\n \"critical\":logging.CRITICAL,\n \"crit\":logging.CRITICAL,\n}\n\ndef cache(function):\n \"\"\"Cache with default parameters\"\"\"\n return Cache()(function)\n\n\nclass Cache:\n def __init__(\n self,\n cache_path: Union[str, Tuple[str], List[str], Dict[str, str]] = \"{cache_dir}/{function_name}/{_hash}.pkl\",\n args_to_ignore: Tuple[str] = (),\n cache_dir: Optional[str] = None,\n validity_duration: Union[int, str] = -1,\n use_source_code: bool = True,\n use_approximated_hash: bool = False,\n log_level: str = \"critical\",\n log_format: str = '%(asctime)-15s [%(levelname)s]: %(message)s',\n backup_path: Optional[str] = None,\n backup: bool = True,\n optional_path_keys: Optional[List[str]] = None,\n dump_kwargs:dict = {},\n load_kwargs:dict = {},\n enable_cache_arg_name: Optional[str] = None,\n capture_enable_cache_arg_name: bool = True,\n ):\n \"\"\"\n Cache the results of a function (or method).\n\n Example:\n ```\n from cache_decorator import Cache\n @Cache()\n def test(x):\n return 2 * x\n ```\n\n Arguments\n ---------\n cache_path: Union[str, Tuple[str], List[str], Dict[str, str]] = \"{cache_dir}/{function_name}/{_hash}.pkl\",\n Where to save the caches.\n It's a string format and the available variables are\n `cache_dir` the directory specified in the other argument.\n `function_name` the name of the cached function.\n `args_to_ignore` which arguments can be ignored form the input.\n `args` the name of the arguments (both positional and keyword).\n `defaults` the default values of the positional arguments.\n `kwonlydefaults` the default values of the kwarguments.\n `source` if `use_source_code` is setted to true, it's the string \n with the source code of the function to cache.\n `_hash` it's the hash of the parameters (excluded the ignored ones),\n this is computed only if it's present in `cache_path` so\n it's possible to cache functions which take non-hashable arguments.\n Moreover, you can use any argument passed to the function.\n Example:\n ```\n from cache_decorator import Cache\n @Cache(\"{cache_dir}/{x}/{y}.pkl)\n def test(x, y):\n return x * y\n ```\n The extension used in the format string determines the serialization method.\n The available ones are `.json .json.gz .json.bz .json.lzma .pkl .pkl.gz .pkl.bz \n .pkl.lzma .pkl.zip .npy .npz .csv .csv.gz .csv.bz2 .csv.zip .csv.xz .xlsx`\n This can also be used to make multiple arguments use the same cache:\n Example:\n ```\n from cache_decorator import Cache\n @Cache(\"{cache_dir}/{x}.pkl)\n def test(x, y):\n return x * y\n ```\n In this case the cache will be used watching only the `x` variable and\n the `y` is ignored. so `test(1, 2)` and `test(1, 10000)` will use the same\n cache (even if that's not right!). This can be used to save human readable \n partial results, in any other cases you should use the `_hash`.\n args_to_ignore: Tuple[str] = (),\n Which arguments to ignore when computing the hash.\n cache_dir: str = None,\n The folder where to save the caches. If not specified it read the value of\n the enviornment variable `CACHE_DIR`. If even this is empty it defaults to\n \"./cache\". This value is substituted in the `cache_path` argument if present.\n validity_duration: Union[int, str] = None,\n If not None, the cache will be recomputed after the specified ammount of time.\n This is done by saving a json with the same name of the cache plus `_time.json` which contains the \n computation epoch.\n If `validity_duration` is specified and a cache does not have it's json file, it's considered invalid.\n The given time must be an integer in seconds or a string in the format (\\d+[smhdw]) to specify \n a given ammount of s(econds), m(inutes), h(ours), d(ays), w(eeks). \n use_source_code: bool = True,\n If in the computing of the hash the must also use the sourcecode of the cached function.\n use_approximated_hash: bool = False,\n `dict_hash` exposes an `use_approximation` arg that allows for faster\n hashes at the cost of less precision because it only hashes part\n of the big parameters like big dataframes of numpy arrays.\n log_level: str = \"critical\",\n Set the logger level to the wanted level. The usable levels are:\n [\"debug\", \"info\", \"warning\", \"error\", \"critical\"]\n Alternatively a reference to the logger can be obtained with\n `logging.getLogger(\"cache.\" + function.__name__)`\n so it possible to fully customize it, like set the level and add filehandlers.\n Example:\n ```\n import logging\n from cache_decorator import Cache\n @Cache()\n def test(x):\n return 2 * x\n logger = logging.getLogger(\"cache.test\")\n logger.setLevel(logging.DEBUG)\n ```\n log_format: str = '%(asctime)-15s[%(levelname)s]: %(message)s'\n Formatting of the default logger on stderr. Informations on how the formatting works can be found at\n https://docs.python.org/3/library/logging.html . Moreover, as explained in the log_level, you can get\n a referfence to the logger and fully customize it.\n backup_path: str = None,\n If the serialization fails, the decorator will try to save the computed result as a pickle.\n This parameter is the formatter for the path where to save the backup result.\n If it's None, it will use the same path of the cache and append `_backup.pkl` at the end.\n This will never overwrite any file, so if a file at the current path is present, a random path will be\n generated.\n For this reason in the formatter you can use any variable such as {cache_dir}, {cache_path}, or the arguments\n of the function. Moreover, there is also another two additional parameters, {_date} which is the date of the backup, and {_rnd} which is a random string that will \n guarantee that no file has the same name. \n backup: bool = True,\n If the cache should backup the result to a .pkl in case of exception during the serializzation.\n This flag is mainly for debug pourpouses.\n optional_path_keys: Optional[List[str]] = None\n This argument can be used only if the cache_path is a Dict, otherwise we will raise an\n exception. Otherwise, if the cache_path is a Dict, this is the list of keys that are\n optional to dump and/or load. This is used to cache results with possibly\n missing keys.\n enable_cache_arg_name: Optional[str] = None,\n This paramer specify the name of a boolean argument that, if given\n to the cached function, will enable or disable the caching \n dynamically. If the argument is not passed the cache will be \n enabled by default. This argument, if passed, will automatically be\n added to the `args_to_ignore` so that it doesn't ruin the caching.\n Currently, this can **only** be a kwarg, in future releases I will\n implement it also for args.\n capture_enable_cache_arg_name: bool = True,\n If this parameter is set, the cache will capture the enable cache arg\n and NOT pass it to the decorated function.\n \"\"\"\n self.log_level = log_level\n self.log_format = log_format\n self.args_to_ignore = list(args_to_ignore)\n self.use_source_code = use_source_code\n self.validity_duration = parse_time(validity_duration)\n self.use_approximated_hash = use_approximated_hash\n\n self.cache_path = cache_path\n self.is_backup_enabled = backup\n self.backup_path = backup_path\n self.cache_dir = cache_dir or os.environ.get(\"CACHE_DIR\", \"./cache\")\n\n self.load_kwargs, self.dump_kwargs = load_kwargs, dump_kwargs\n self.enable_cache_arg_name = enable_cache_arg_name\n self. capture_enable_cache_arg_name = capture_enable_cache_arg_name\n\n self.optional_path_keys = optional_path_keys\n\n if self.optional_path_keys is None:\n self.optional_path_keys = list()\n else:\n if not isinstance(self.cache_path, dict):\n raise ValueError((\n \"The argument `optional_path_keys` with value '{}' has no \"\n \"meaning if the `cache_path` isn't a dict. `cache_path`='{}'\"\n ).format(self.optional_path_keys, self.cache_path))\n\n self._check_path_sanity(cache_path)\n\n def _check_path_sanity(self, path: Union[str, Tuple[str], List[str], Dict[str, str]]):\n \"\"\"Check that at least one backend exists that can handle the given path.\n This is just a quality of life check to raise an exception early and not\n after the computation is done.\"\"\"\n test_bk = Backend({}, {})\n if isinstance(path, str):\n if not test_bk.support_path(path):\n raise ValueError((\n \"There is not backend that can support the path '{}'. \"\n \"The available extensions are '{}'.\"\n ).format(path, test_bk.get_supported_extensions()))\n elif isinstance(path, list) or isinstance(path, tuple):\n for sub_path in path:\n self._check_path_sanity(sub_path)\n elif isinstance(path, dict):\n for arg, sub_path in path.items():\n self._check_path_sanity(sub_path)\n \n missing_keys = set(self.optional_path_keys) - set(path.keys())\n if len(missing_keys) != 0:\n raise ValueError((\n \"The `cache_path` dictionary is missing some keys defined in \"\n \"the `optional_path_keys` arg. Specifically: {}\"\n ).format(missing_keys))\n else:\n raise ValueError((\n \"Sorry, the path '{}' is not in one of the supported formats.\"\n \"We support a string, a list, tuple, or dict of paths.\"\n ).format(path)\n )\n\n @staticmethod\n def store(obj, path: str) -> None:\n \"\"\"Store an object at a path, this automatically choose the correct backend.\n \n Arguments\n ---------\n obj: Object,\n The object to store\n path: str,\n Where to store the file, based on its extension it will choose the correct backend.\n \"\"\"\n dirname = os.path.dirname(os.path.abspath(path))\n if dirname != \"\":\n os.makedirs(dirname, exist_ok=True)\n Backend({}, {}).dump(obj, path)\n\n @staticmethod\n def load(path: str):\n \"\"\"\n Load an object from a file, this automatically choose the correct backend.\n \n Arguments\n ---------\n path: str,\n The path to the file to load file, based on its extension it will choose the correct backend.\n\n Returns\n -------\n The loaded object.\n \"\"\"\n return Backend({}, {}).load({}, path)\n\n @staticmethod\n def compute_path(function: Callable, *args, **kwargs) -> str:\n \"\"\"Return the path that a file would have if the given function\n woule be called with the given arguments.\n\n \"\"\"\n # If we are dealing with a cached function then unpack it:\n if \"__cached_function\" not in dir(function):\n raise ValueError(\"You cannot compuite the path of a function which is not decorated with the Cache decorator.\")\n\n instance = getattr(function, \"__cacher_instance\")\n function = getattr(function, \"__cached_function\")\n\n return instance._get_formatted_path(args, kwargs, function_info=instance._compute_function_info(function))\n\n\n def _compute_function_info(self, function: Callable):\n function_args_specs = inspect.getfullargspec(function)\n\n function_info = {\n # Name of the function\n \"function_name\": get_function_name(function),\n # Arguments names\n \"args\": function_args_specs.args or [],\n \"defaults\": function_args_specs.defaults or [],\n \"kwonlydefaults\": function_args_specs.kwonlydefaults or {},\n \"args_to_ignore\": self.args_to_ignore,\n }\n\n if self.use_source_code:\n # Get the sourcode of the funciton\n # This will be used in the hash so that old\n # Caches will not be loaded\n function_info[\"source\"] = \"\".join(\n inspect.getsourcelines(function)[0]\n )\n\n return function_info\n\n def _backup(self, result, path, exception, args, kwargs):\n \"\"\"This function handle the backupping of the data when an the serialization fails.\"\"\"\n\n # Check if it's a structured path\n if isinstance(path, list) or isinstance(path, tuple):\n return self._backup(result, path[0], exception, args, kwargs)\n \n elif isinstance(path, dict):\n return self._backup(result, next(path.values()), exception, args, kwargs)\n\n date = datetime.now().strftime(\"%Y_%m_%d_%H_%M_%S\")\n # Ensure that the we won't overwrite anything\n while True:\n # Generate a new random value\n rnd = random_string(40) # hardcoded length but if they are enough for git it's enough for us.\n backup_path = self._get_formatted_path(\n args, kwargs, \n formatter=self.backup_path,\n extra_kwargs={\n \"_date\":date, \n \"_rnd\":rnd,\n \"cache_path\":self._get_formatted_path(args, kwargs),\n }\n )\n # Check for the existance\n if os.path.exists(backup_path):\n # If the file exists and the rnd var is not used\n # we force it so we don't get stuck in the loop.\n if \"{_rnd}\" not in self.backup_path:\n self.backup_path += \"{_rnd}\"\n continue\n break\n\n # Inform the user about hte problem\n self.logger.critical(\n \"Couldn't save the result of the function '%s'. \"\n \"Saving the result as a pickle at:\\n%s\"\n \"\\nThe file was gonna be written at:\\n%s\\n\", \n self.function_info[\"function_name\"], backup_path, path\n )\n # Backup the result\n dirname = os.path.dirname(backup_path)\n if dirname != \"\":\n os.makedirs(dirname, exist_ok=True)\n\n with open(backup_path, \"wb\") as f:\n pickle.dump(result, f)\n # Re-raise the exception\n exception.backup_path = backup_path\n exception.path = path\n exception.result = result\n return exception\n\n def _get_metadata_path(self, path):\n return path + \".metadata\"\n\n def _is_cache_enabled(self, args, kwargs, inner_self = None):\n # if enable_cache_arg_name is not defined, then forward\n if self.enable_cache_arg_name is None:\n return True, args, kwargs\n\n # if the arg is in the kwargs, ez, pop the value and retrun\n if self.enable_cache_arg_name in kwargs:\n if self.capture_enable_cache_arg_name:\n cache_enabled = kwargs.pop(self.enable_cache_arg_name, True)\n else:\n cache_enabled = kwargs[self.enable_cache_arg_name]\n return cache_enabled, args, kwargs\n\n # Normalize args and kwargs\n params = get_params(self.function_info, args, kwargs)\n\n # TODO!: implement this\n # # if it was in the args, we need to remove it from there \n # if self.enable_cache_arg_name in params:\n # cache_enabled = kwargs.pop(self.enable_cache_arg_name, True)\n # return cache_enabled, args, kwargs\n\n # Add the self if we are in a method\n if inner_self is not None:\n params[\"self\"] = inner_self\n\n # otherwise it's either an attribute or method call we should resolve\n\n # Get the name of the base element and the attributes chain\n root, *attrs = self.enable_cache_arg_name.strip(\"()\").split(\".\")\n\n # This means that the parameter was setted but the arg wasn't passed\n # so we should default to true\n if root not in params:\n return True, args, kwargs\n\n # Get the params to use for the attributes chain\n root = params[root]\n \n # Follow the attributes chain\n for attr in attrs: \n root = getattr(root, attr)\n\n # Check if we have to call the function or not\n if inspect.isfunction(root) or inspect.ismethod(root) or inspect.isbuiltin(root):\n root = root()\n\n return root, args, kwargs\n\n def _load(self, path):\n\n # Check if it's a structured path\n if isinstance(path, list) or isinstance(path, tuple):\n result = []\n for p in path:\n cache = self._load(p)\n\n if cache is None:\n return None\n\n result.append(cache)\n\n if isinstance(path, tuple):\n result = tuple(result)\n return result\n\n elif isinstance(path, dict):\n result = {}\n for key, p in path.items():\n cache = self._load(p)\n\n # if we couldn't load the cache\n if cache is None:\n # and it's optional it's fine, go on loading the other ones\n if key in self.optional_path_keys:\n continue\n # else it's an error and we cannot load the required data\n # therefore the cache is invalid\n else:\n return None\n\n result[key] = cache\n return result\n\n # Check if the cache exists and is readable\n if not os.path.isfile(path):\n self.logger.info(\"The cache at path '%s' does not exists.\", path)\n return None\n\n self.logger.info(\"Loading cache from %s\", path)\n\n metadata_path = self._get_metadata_path(path)\n\n # Load the metadata if present\n if os.path.isfile(metadata_path):\n self.logger.info(\"Loading the metadata file at '%s'\", metadata_path)\n with open(metadata_path, \"r\") as f:\n metadata = json.load(f)\n else:\n self.logger.info(\"The metadata file at '%s' do not exists.\", metadata_path)\n # TODO: do we need to to more stuff?\n metadata = {}\n\n # Check if the cache is still valid\n if self.validity_duration is not None:\n enlapsed_time = time() - metadata.get(\"creation_time\", float(\"-inf\"))\n if enlapsed_time > self.validity_duration:\n try:\n os.remove(path)\n except:\n pass\n return None \n\n # actually load the values\n return Backend(self.load_kwargs, self.dump_kwargs).load(metadata.get(\"backend_metadata\", {}), path)\n\n def _check_return_type_compatability(self, result, path):\n # Check if it's a structured path\n if isinstance(path, list) or isinstance(path, tuple):\n assert isinstance(result,list) or isinstance(result,tuple)\n assert len(result) == len(path)\n elif isinstance(path, dict):\n assert isinstance(result, dict)\n required_keys = set(path.keys()) - set(self.optional_path_keys)\n missing_keys = required_keys - set(result.keys())\n if len(missing_keys) != 0:\n raise ValueError((\n \"The result of the cached function has keys '{}' that does \"\n \"not match with the required ones '{}'\"\n ).format(result.keys(), required_keys))\n\n extra_keys = set(result.keys()) - set(path.keys())\n if len(extra_keys) != 0:\n raise ValueError((\n \"The result of the cached function has keys '{}' that does \"\n \"not appear in the defined path. In particular the the \"\n \"extra keys are '{}'\"\n ).format(result.keys(), extra_keys))\n return \n\n def _dump(self, args, kwargs, result, path, start_time, end_time):\n # Check if it's a structured path\n if isinstance(path, list) or isinstance(path, tuple):\n for r, p in zip(result, path):\n self._dump(args, kwargs, r, p, start_time, end_time)\n return \n elif isinstance(path, dict):\n for key in result.keys():\n self._dump(args, kwargs, result[key], path[key], start_time, end_time)\n return \n \n\n # Dump the file\n self.logger.info(\"Saving the cache at %s\", path)\n dirname = os.path.dirname(path)\n if dirname != \"\":\n os.makedirs(dirname, exist_ok=True)\n dump_start_time = time()\n backend_metadata = Backend(self.load_kwargs, self.dump_kwargs).dump(result, path) or {}\n dump_end_time = time()\n\n # Compute the metadata\n metadata = {\n # When the cache was created\n \"creation_time\": start_time,\n \"creation_time_human\": datetime.fromtimestamp(\n start_time\n ).strftime(\"%Y-%m-%d %H:%M:%S\"),\n\n # How much the function took to compute the result\n \"time_delta\":end_time - start_time,\n \"time_delta_human\":humanize.precisedelta(end_time - start_time),\n\n # How much time it took to serialize the result and save it to a file\n \"file_dump_time\":dump_end_time - dump_start_time,\n \"file_dump_time_human\":humanize.precisedelta(\n dump_end_time - dump_start_time\n ),\n\n # How big is the serialized result\n \"file_dump_size\":os.path.getsize(path),\n \"file_dump_size_human\":humanize.naturalsize(os.path.getsize(path)),\n\n # The arguments used to load and dump the file\n \"load_kwargs\":self.load_kwargs,\n \"dump_kwargs\":self.dump_kwargs,\n\n # Informations about the function\n \"function_name\":self.function_info[\"function_name\"],\n \"function_file\":\"%s:%s\"%(\n self.decorated_function.__code__.co_filename,\n self.decorated_function.__code__.co_firstlineno\n ),\n \"args_to_ignore\":self.function_info[\"args_to_ignore\"],\n \"source\":self.function_info.get(\"source\", None),\n\n # The data reserved for the backend to corretly serialize and \n # de-serialize the values\n \"backend_metadata\":backend_metadata,\n }\n\n params = {}\n for key, val in get_params(self.function_info, args, kwargs).items():\n if key in self.args_to_ignore:\n continue\n\n try:\n # Check if it's json serializable\n json.dumps(val)\n params[key] = val\n except:\n pass\n\n\n metadata[\"parameters\"] = params\n\n metadata_path = self._get_metadata_path(path)\n self.logger.info(\"Saving the cache meta-data at %s\", metadata_path)\n with open(metadata_path, \"w\") as f:\n json.dump(metadata, f, indent=4)\n\n\n def _decorate_function(self, function: Callable) -> Callable:\n # wraps to support pickling\n @wraps(function)\n def wrapped(*args, **kwargs):\n cache_enabled, args, kwargs = self._is_cache_enabled(args, kwargs)\n \n # if the cache is not enabled just forward the call\n if not cache_enabled:\n self.logger.info(\"The cache is disabled\")\n result = function(*args, **kwargs)\n self._check_return_type_compatability(result, self.cache_path)\n return result\n\n # Get the path\n path = self._get_formatted_path(args, kwargs)\n\n # Try to load the cache\n result = self._load(path)\n # if we got a result, reutrn it\n if result is not None:\n return result\n \n self.logger.info(\"Computing the result for %s %s\", args, kwargs)\n # otherwise compute the result\n start_time = time()\n result = function(*args, **kwargs)\n end_time = time()\n\n # Save the result\n try:\n self._check_return_type_compatability(result, path)\n self._dump(args, kwargs, result, path, start_time, end_time)\n except Exception as e:\n if self.is_backup_enabled:\n raise self._backup(result, path, e, args, kwargs)\n raise e\n\n return result\n\n # add a reference to the cached function so we can unpack\n # The caching if needed\n setattr(wrapped, \"__cached_function\", function)\n setattr(wrapped, \"__cacher_instance\", self)\n return wrapped\n\n def _decorate_method(self, function: Callable) -> Callable:\n # wraps to support pickling\n @wraps(function)\n def wrapped(self, *args, **kwargs):\n cache_enabled, args, kwargs = self._is_cache_enabled(args, kwargs, inner_self=self)\n \n # if the cache is not enabled just forward the call\n if not cache_enabled:\n self.logger.info(\"The cache is disabled\")\n result = function(self, *args, **kwargs)\n self._check_return_type_compatability(result, self.cache_path)\n return result\n\n # Get the path\n path = self._get_formatted_path(args, kwargs, inner_self=self)\n\n # Check that the self is actually hashable\n if not issubclass(self, Hashable):\n raise ValueError(\"Could not has self of class `{}` because it doesn't implement Hashable (from dict_hash).\".format(self.__class__.__name__))\n\n # Try to load the cache\n result = self._load(path)\n # if we got a result, reutrn it\n if result is not None:\n return result\n \n self.logger.info(\"Computing the result for %s %s\", args, kwargs)\n # otherwise compute the result\n start_time = time()\n result = function(*args, **kwargs)\n end_time = time()\n\n # Save the result\n try:\n self._check_return_type_compatability(result, path)\n self._dump(args, kwargs, result, path, start_time, end_time)\n except Exception as e:\n if self.is_backup_enabled:\n raise self._backup(result, path, e, args, kwargs)\n raise e\n\n return result\n\n # add a reference to the cached function so we can unpack\n # The caching if needed\n setattr(wrapped, \"__cached_function\", function)\n setattr(wrapped, \"__cacher_instance\", self)\n return wrapped\n\n def _get_formatted_path(self, args, kwargs, formatter=None, function_info=None, extra_kwargs=None, inner_self=None) -> str:\n \"\"\"Compute the path adding and computing the needed arguments.\"\"\" \n formatter = formatter or self.cache_path\n\n if isinstance(formatter, list):\n return [\n self._get_formatted_path(args, kwargs, f)\n for f in formatter\n ]\n\n if isinstance(formatter, tuple):\n return tuple([\n self._get_formatted_path(args, kwargs, f)\n for f in formatter\n ])\n\n elif isinstance(formatter, dict):\n return {\n key:self._get_formatted_path(args, kwargs, v)\n for key, v in formatter.items()\n }\n\n extra_kwargs = extra_kwargs or {}\n\n function_info = function_info or self.function_info\n params = get_params(function_info, args, kwargs)\n groups = get_format_groups(formatter)\n groups_set = {match.str_match for match in groups}\n\n if \"_hash\" in groups_set:\n data = {\"params\": params, \"function_info\": function_info}\n\n if inner_self is not None: \n data[\"self\"] = inner_self\n\n params[\"_hash\"] = sha256(data, use_approximation=self.use_approximated_hash)\n\n self.logger.debug(\"Got parameters %s\", params)\n\n format_args = {\n **params,\n **function_info,\n **extra_kwargs,\n \"cache_dir\":self.cache_dir,\n }\n\n new_formatter = \"\"\n old_formatter = formatter\n # Handle the composite paths\n while len(old_formatter) != 0:\n new_match, formatter_remainder = get_next_format_group(old_formatter)\n\n # there are no more matches just append the remainder\n if new_match is None:\n new_formatter += formatter_remainder\n break\n \n # check if we should call the value or not\n if new_match.str_match.endswith(\"()\"):\n new_match.str_match = new_match.str_match[:-2]\n # Get the name of the base element and the attributes chain\n root, *attrs = new_match.str_match.split(\".\")\n # Get the params to use for the attributes chain\n root = format_args[root]\n\n # Follow the attributes chain\n for attr in attrs: \n root = getattr(root, attr)\n\n # Check if we have to call the function or not\n if inspect.isfunction(root) or inspect.ismethod(root) or inspect.isbuiltin(root):\n root = root()\n\n sub = str(root)\n else:\n sub = \"{\" + new_match.str_match + \"}\"\n\n new_formatter += old_formatter[:new_match.start]\n new_formatter += sub\n old_formatter = formatter_remainder\n\n path = new_formatter.format(\n **format_args,\n )\n self.logger.debug(\"Calculated path %s\", path)\n return path\n\n def _fix_docs(self, function: Callable, wrapped: Callable) -> Callable:\n # Copy the doc of decoreated function\n wrapped.__doc__ = function.__doc__\n # Copy the name of the function and add the suffix _cached\n wrapped.__name__ = get_function_name(function) + \"_cached\"\n return wrapped\n\n def decorate(self, function: Callable) -> Callable:\n self.function_info = self._compute_function_info(function)\n self.decorated_function = function\n\n if inspect.ismethod(function):\n wrapped = self._decorate_method(function)\n else:\n wrapped = self._decorate_function(function)\n\n wrapped = self._fix_docs(function, wrapped)\n return wrapped\n\n def __call__(self, function):\n self.logger = logging.getLogger(__name__ + \".\" + get_function_name(function))\n # Do not re-initialize loggers if we have to cache multiple functions\n # with the same name\n if not self.logger.hasHandlers():\n handler = logging.StreamHandler(sys.stderr)\n handler.setFormatter(logging.Formatter(self.log_format))\n self.logger.addHandler(handler)\n\n if self.log_level.lower() not in log_levels:\n raise ValueError(\"The logger level {} is not a supported one. The available ones are {}\".format(\n self.log_level.lower(),\n list(log_levels.keys())\n ))\n self.logger.setLevel(log_levels[self.log_level.lower()])\n\n return self.decorate(function)\n","repo_name":"zommiommy/cache_decorator","sub_path":"cache_decorator/cache.py","file_name":"cache.py","file_ext":"py","file_size_in_byte":33235,"program_lang":"python","lang":"en","doc_type":"code","stars":21,"dataset":"github-code","pt":"21"}
+{"seq_id":"28387427911","text":"# -*- encoding: utf-8 -*-\n# Author: hushukai\n\nimport os\n\nfrom util import check_or_makedirs\nfrom config import CHAR_IMGS_DIR, CHAR_TFRECORDS_DIR\nfrom config import CHAR_IMAGE_PATHS_FILE, CHAR_TFRECORDS_PATHS_FILE\n\n\ndef extract_annotation(imgs_dir=None, tfrecords_dir=None, dest_file=None):\n assert [imgs_dir, tfrecords_dir].count(None) == 1\n \n check_or_makedirs(os.path.dirname(dest_file))\n with open(dest_file, \"w\", encoding=\"utf-8\") as fw:\n if imgs_dir is not None:\n for root, dirs, files_list in os.walk(imgs_dir):\n if len(files_list) > 0:\n for file_name in files_list:\n if file_name.lower()[-4:] in (\".gif\", \".jpg\", \".png\"):\n image_path = os.path.join(root, file_name)\n fw.write(image_path + \"\\n\")\n \n elif tfrecords_dir is not None:\n assert os.path.exists(tfrecords_dir)\n for file in os.listdir(tfrecords_dir):\n if file.endswith(\".tfrecords\"):\n file_path = os.path.join(tfrecords_dir, file)\n fw.write(file_path + \"\\n\")\n\n\ndef main():\n # extract_annotation(imgs_dir=CHAR_IMGS_DIR, dest_file=CHAR_IMAGE_PATHS_FILE)\n extract_annotation(tfrecords_dir=CHAR_TFRECORDS_DIR, dest_file=CHAR_TFRECORDS_PATHS_FILE)\n\n\nif __name__ == '__main__':\n print(\"Done !\")\n","repo_name":"yufish/Chinese-ancient-book-recognition-HSK","sub_path":"recog_with_components/extract_data.py","file_name":"extract_data.py","file_ext":"py","file_size_in_byte":1392,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"21"}
+{"seq_id":"27006327941","text":"# import turtle\r\n\r\nfrom turtle import Turtle, Screen #From the module import attribute(class)\r\n\r\n\r\n#Draw turtle graphics\r\ntimmy = Turtle() #Object = attribute\r\ntimmy.shape(\"turtle\")\r\ntimmy.color(\"DarkRed\")\r\n#Move turtle\r\ntimmy.forward(100)\r\n\r\n\r\n#Create a screen\r\nmy_screen = Screen()\r\n# print(my_screen.canvheight)\r\nmy_screen.title(\"#100 Days of Code: Day16 Turtle Graphics\")\r\nmy_screen.exitonclick()\r\n\r\nprint(timmy)","repo_name":"Vincent-Muchiri/Python-Programming","sub_path":"Turtle.py","file_name":"Turtle.py","file_ext":"py","file_size_in_byte":416,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"}
+{"seq_id":"35108414832","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Thu Dec 10 13:34:54 2020\n\n@author: merel\n\"\"\"\n\nimport numpy as np\nimport matplotlib.pyplot as plt\n\n#%%\n#5.2.1 Opdracht: Extra argumenten\n\n# Rechte lijn\ndef f(x,a,b):\n return a+b*x\n\n# Sinus\ndef g(x,amp,freq,offset):\n return offset + amp*np.sin(freq*x)\n\n#Polynoom\ndef h(x,y,b,c):\n return b*x**2 + c*y**3 \n\n## Simpele plotfunctie\n# plot functie \"func\" over range \"x\"\n# extra argumenten worden doorgegeven met *args\ndef my_plot(x,func,*args):\n plt.plot(x,func(x,*args))\n plt.show()\n \n## Gebruik:\nx_arr = np.linspace(-5.,5.)\n#%%\ndef f(farg, *args, **kwargs):\n print(\"Het formele argument is\", farg)\n print(\"De extra argumenten zijn:\")\n for arg in args:\n print(arg)\n print(\"De keyword argumenten zijn:\")\n for key in kwargs:\n print(\" de key\",key,\"met argument\",kwargs[key])\n if key == 'my_name':\n print(\"Mijn naam is\", kwargs[key])\n \n## Aanroepen van bovenstaande functie:\nf(\"Aap\", \"Noot\", \"Mies\", arg4=\"Wim\", my_name=\"Zus\", arg5=\"Merel\")\n# in bovenstaande aanroep zijn:\n# Formeel argument \"Aap\"\n# Extra argumenten \"Noot\" en \"Mies\"\n# Keyword argumenten \"Wim\" bij keyword arg4, en \"Zus\" bij my_name\n#%%\n#5.4.1 Opdracht: Argumenten aan functies sturen\ndef f(a,b,c):\n print(\"a:\",a)\n print(\"b:\",b)\n print(\"c:\",c)\n\"\"\" \n# Normaal aanroepen:\nf(\"Aap\",\"Noot\",\"Mies\")\n\n# Met *args\nargs = (\"Noot\",\"Mies\")\nf(\"Aap\",*args)\n\n# Met **kwargs\nkwargs = {\"c\" : \"Noot\",\"b\" : \"Mies\"} # Dit is een nieuw type object: dictionary\nf(\"Aap\",**kwargs)\n\"\"\"\n# Mix van beide, let op de volgorde!\nargs = (\"Mies\",)\nkwargs = {\"c\" : \"Noot\"}\nf(\"Aap\",*args,**kwargs)\n\n#%%\n#5.4.2 Opdracht: Plotten\n\ndef h(x,y):\n z = x*y\n return z \n\nk = h(x_arr,3)\n\nsig_x = [0,0.05,0.05,0.05,0.05,0.05]\nsig_y = [0.03] *6\n \n\ndef my_plot(x,y, xlabel, ylabel,xerror=None, yerror=None, xrange=None, yrange=None,title=None, save=None):\n plt.xlim(xrange)\n plt.ylim(yrange)\n plt.xlabel(xlabel)\n plt.ylabel(ylabel)\n plt.title(title)\n plt.errorbar(x,y, xerr = xerror, yerr = yerror)\n if save == None:\n plt.show()\n elif type(save) == str:\n plt.savefig(save + \".png\")\n else:\n print(\"Save moet een string zijn\")\n\n\nx_arr = [0,1,2,3,4,5] \nx_arr = np.array(x_arr)\n\n\ns = my_plot(x_arr,k,\"x-as\",\"y-as\",sig_x,sig_y,(0, 7),(0, 7),\"Hoi\") \n\n#%%\n#5.4.3 Opdracht: Machtreeksen\n\nx = np.arange(0,5)\nA_n = np.arange(0,10) \n\ndef MachtReeks(x, A_n, y_0 = 0, x_0 = 0):\n result = y_0\n for n in range(len(A_n)): \n result += A_n[n]*(x-x_0)**n\n plt.plot(x,result) \n plt.show()\n return result\n \n \nresultaat = MachtReeks(x,A_n,2,4)\nprint(resultaat) \n \n#plt.plot(x,resultaat) \n#plt.show() \n\n\n#%%\n\n\n\n","repo_name":"mereldv/DataPyRepo","sub_path":"Week5/Week5.py","file_name":"Week5.py","file_ext":"py","file_size_in_byte":2716,"program_lang":"python","lang":"nl","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"}
+{"seq_id":"23550114391","text":"import datetime\nimport json\nimport logging\n\nimport tiktoken\n\nfrom datatypes.chat_context import ChatContext\nfrom datatypes.gpt_response import GptResponse\nfrom datatypes.user_message import UserMessage\n\n\nquery_template = \"\"\"\\\n- The date and time when sending this message is: {curr_date}.\n- You are in a room with the following human(s) {human_names!s}.\n- You will be supplied with a part of the recent conversation history (as working memory) and the current prompt.\n- As you don't have too much working memory you are encouraged to save important information in your long term memory \nusing the commands given to you. \n- You can only execute one command at a time, so you will have to plan your next steps carefully and remember them. \n- If you can, try to answer questions on your own. \n- Avoid executing the same command twice in a row.\n\nYour general task is to help the human(s). Specifically your general goals and tasks include:\n{ai_goals}\n\nYou can execute the following commands as desired: Every answer of yours has to be a JSON object invoking exactly one of those functions:\n----BEGIN COMMANDS----\n{commands}\n----BEGIN COMMANDS----\nThe result of invoking a functionality will be given back to you.\n\nAlso, you have access to the following storage keys: {memory_keys} \n\nWe have the following conversation history (with #{n_history} entries total). \nYou should incorporate the following information for your answer if useful:\n----BEGIN Conversation History----\n{history}\n----END Conversation History----\n\nThe result of the last command of yours was:\n{current_prompt}\nAdditional Information provided (if any): \n{additional_info}\n\n\nTo remind you:\nYour plan was: `{plan}`!\nYour next planned steps were:\n{next_steps}!\n\n---- Your Instructions ----\nAlways consider your next steps carefully step by step and execute them one by one. Add the remaining \nsteps you would have to do to achieve the plan to your response in the template given below. Don't put the next\nsteps into an answer directly but put it in the json structure in the key `steps`. Use the plan to store overarching \ninformation on what we are going to do.\n\n*ALWAYS* respond with a JSON object in the following exact format (given as template):\n----BEGIN TEMPLATE---\n{base_command}\n----END TEMPLATE---\n\"\"\"\n\n\ndef conversation_history_to_str(history: list[tuple[int, str, str]]) -> str:\n return \"\\n\".join(\n [\n f\"----BEGIN History Entry #{i}----\\n{user}: {msg}\\n----END History Entry #{i}----\"\n for i, user, msg in history\n ]\n )\n\n\ndef generate_gpt_query(ctx: ChatContext, logger: logging.Logger) -> str:\n \"\"\"\n Generates a query / prompt for GPT-3\n :param ctx:\n :param logger:\n :return:\n \"\"\"\n from gpt_commands import GPT_COMMANDS\n\n storage = [*ctx.key_storage_backend.list()]\n pos = len(ctx.message_history)\n conversations = []\n if len(ctx.message_history) > 1:\n for i in reversed(ctx.message_history[:-1]):\n conversations.append(\n (\n pos,\n i.user if isinstance(i, UserMessage) else \"assistant\",\n i.user_response\n if isinstance(i, UserMessage)\n else json.dumps(i.dict()),\n )\n )\n conversations_str = conversation_history_to_str(conversations)\n n_tokens = count_tokens(\n text=conversations_str, model=ctx.settings.model, logger=logger\n )\n if n_tokens > ctx.settings.max_token_len_history:\n conversations = conversations[:-1]\n break\n pos -= 1\n\n # reverse again to be in chronological order\n conversations = [*reversed(conversations)]\n\n conversations_str = conversation_history_to_str(conversations)\n\n command_str = \"\"\n for command_name, command in GPT_COMMANDS.items():\n if command_name in ctx.settings.allowed_commands:\n command_str += f\"- `{command_name}` - ({command.description()})\\n\"\n if command.arguments():\n command_str += \"Args:\\n\"\n for name, typ, help_text, required in command.arguments():\n command_str += (\n f\" {name} ({typ.__name__}) - {help_text}\"\n f' ({\"required\" if required else \"optional\"}\\n'\n )\n else:\n command_str += \"No args.\\n\"\n\n # current context if available (when it is not the first message)\n if len(ctx.message_history) > 0 and ctx.message_history[-1]:\n additional_info = (\n ctx.message_history[-1].additional_info\n if ctx.message_history[-1].additional_info\n else \"None\"\n )\n current_prompt = (\n f\"User ({ctx.active_user}): \" + ctx.message_history[-1].user_response\n )\n\n else:\n additional_info = \"None\"\n current_prompt = \"None\"\n\n if len(ctx.message_history) >= 2:\n msg: GptResponse = ctx.message_history[-2]\n plan = msg.plan if msg.plan else \"None\"\n next_steps = msg.steps[1:] if msg.steps and len(msg.steps) > 1 else [\"None\"]\n else:\n plan = \"Come up with a plan on fulfilling the goals.\"\n next_steps = [\"Initiate the conversation with the human(s).\"]\n\n template = query_template.format(\n ai_name=ctx.bot_name,\n human_names=ctx.users,\n memory_keys=storage if storage else \"None\",\n n_history=len(ctx.message_history),\n history=conversations_str,\n commands=command_str,\n curr_date=datetime.datetime.now().strftime(\"%d/%m/%Y at %H:%M:%S\"),\n base_command='{\"command\": \"the_command\", \"arguments\": {\"the\":\"parameters\", ... }, '\n '\"plan\": \"the effect you want to achieve with your current execution steps\", '\n '\"steps\": [\"details\", \"of\", \"steps\", \"you\", \"want\", \"to\", \"do\"]}',\n # example_command=json.dumps({'command': 'ask_human',\n # 'arguments': {'information': 'Hello human! How can I help you?'},\n # 'plan': 'I want to know what to the human needs.',\n # 'critic': 'Maybe they don\\'t need anything.'}),\n current_prompt=current_prompt,\n additional_info=additional_info,\n plan=plan,\n next_steps='-'+'\\n- '.join(next_steps),\n ai_goals='-'+'-\\n- '.join(ctx.settings.default_ai_tasks),\n )\n\n return template\n\n\ndef count_tokens(text: str, model: str, logger: logging.Logger) -> int:\n \"\"\"Count the (approximated) number of tokens of a text for a specific model.\n if the models tokenizer is not available, it will estimate the number of tokens\n by dividing the length of the text by 4 (estimation)\n Parameters:\n text: the text to count the tokens for\n model: the model to count the tokens for\n logger: the logger to log warnings to\n Returns:\n the (maybe estimated) number of tokens\n \"\"\"\n # To get the tokenizer corresponding to a specific model in the OpenAI API:\n try:\n enc = tiktoken.encoding_for_model(model)\n return len(enc.encode(text))\n except Exception as e:\n logger.warning(\n f\"Could not get tokenizer for model `{model}`: `{e}`. Will estimate tokens.\"\n )\n return len(text) // 4 + 1\n","repo_name":"Mereep/assistant-gpt","sub_path":"src/utils/query.py","file_name":"query.py","file_ext":"py","file_size_in_byte":7342,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"37"}
+{"seq_id":"24288064618","text":"def combination(arr, r):\n for i in range(len(arr)):\n if r == 1:\n yield [arr[i]]\n else:\n for next in combination(arr[i+1:], r-1):\n yield [arr[i]] + next\n\nN, M = map(int, input().split())\nboard = []\nhome, chicken = [], []\nfor i in range(N):\n board.append(list(map(int, input().split())))\n for j in range(N):\n if board[i][j] == 1:\n home.append((i, j))\n elif board[i][j] == 2:\n chicken.append((i, j))\n \nnCr = combination(chicken, M) #가능한 치킨집 조합\nresult, ans = 0, 1e9\n\nfor c in nCr:\n c.sort()\n for x,y in home:\n minimum = 1e9\n for i,j in c:\n d = abs(x-i) + abs(y-j)\n if minimum > d:\n minimum = d\n\n result += minimum\n ans = min(ans, result)\n result = 0\nprint(ans)","repo_name":"Yuunhye/Problem_Solving","sub_path":"Baekjoon/Samsung/15686 치킨 배달.py","file_name":"15686 치킨 배달.py","file_ext":"py","file_size_in_byte":851,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"}
+{"seq_id":"7781732417","text":"import pandas\nimport csv\nimport pickle\nimport numpy\nimport time\nfrom sklearn.feature_extraction.text import TfidfVectorizer\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.linear_model import LogisticRegression\n\nclass SentimentAnalysis():\n def __init__(self):\n self.filepath = \"polls/module/data/\"\n self.modelFile = \"tf_idf_model.pkl\"\n self.preproFile = None\n self.model = None\n self.keyword = None\n self.media = None\n self.MEDIA_MUSINSA = \"musinsa\"\n self.MEDIA_INSTAGRAM = \"instagram\"\n self.CATEGORY = ['color','price','size','None']\n self.months = [\"01\",\"02\",\"03\",\"04\",\"05\",\"06\",\"07\",\"08\",\"09\",\"10\",\"11\",\"12\"]\n self.yearlist = []\n\n self.load_model()\n\n ##키워드설정\n def set_keyword(self,keyword):\n self.keyword = keyword\n\n def get_keyword(self):\n return self.keyword\n \n ##매체설정\n def set_media(self,media):\n self.media = media\n\n ##전처리 파일 선택\n if self.media == self.MEDIA_INSTAGRAM:\n self.preproFile = \"preprocessed_instagram.csv\"\n self.date_pattern = \"%s-%s-\"\n elif self.media == self.MEDIA_MUSINSA:\n self.preproFile = \"preprocessed_musinsa.csv\"\n self.date_pattern = \"%s.%s.\"\n \n def get_media(self):\n return self.media\n\n ##현재 저장되어있는 리뷰 연도리스트 반환\n def get_year_list(self):\n filepath = self.filepath+self.preproFile\n now = time.localtime() ##현재날짜\n\n for year in range(now.tm_year,now.tm_year-3,-1): ##현재 연도로부터 3년간 데이터 존재하는지 \n df = pandas.read_csv(filepath,encoding='utf-8',index_col=False)\n df = df[df['keyword'] == self.keyword]\n df = df.dropna(how=\"any\")\n pattern = str(year)\n df = df.ix[df['date'].str.startswith(pattern),:]\n if(len(df) != 0):\n self.yearlist.append(year)\n return self.yearlist \n\n ##감정분석 학습 모델 로드\n def load_model(self):\n with open(self.filepath+self.modelFile,'rb') as f:\n self.model = pickle.load(f)\n\n ##긍/부정 예측\n def predict_sentiment_month(self,year,month,detailed=\"no\"):\n month = str(month)\n if len(month) == 1: \n month = \"0\"+month\n if month not in self.months : raise Exception\n \n ##날짜 패턴 설정\n pattern = self.date_pattern % (year,month)\n\n ##전처리 데이터 불러오고 필터링\n data = pandas.read_csv(self.filepath+self.preproFile,encoding='utf-8',index_col=False)\n data = data[data['keyword']==self.keyword]\n if detailed != \"no\":\n data = data[data['category']==detailed]\n data = data.dropna(how=\"any\")\n data = data.ix[data['date'].str.startswith(pattern),:]\n review_data = [str(review) for review in data['text']]\n\n result = {\"pos\":0, \"neg\":0}\n\n ##예외처리\n if len(review_data) == 0:\n return result\n\n ##긍/부정 예측\n pred = self.model.predict(review_data)\n ##probability = numpy.max(self.model.predict_proba(example))*100\n \n ##긍/부정 카운트 \n for sentiment in pred:\n if sentiment == 1:\n result[\"pos\"] = result[\"pos\"] + 1\n elif sentiment == -1:\n result[\"neg\"] = result[\"neg\"] + 1\n\n return result\n \nif __name__ == '__main__':\n analysis = SentimentAnalysis()\n analysis.set_keyword('맨투맨')\n analysis.set_media(analysis.MEDIA_MUSINSA)\n for month in analysis.months:\n l = analysis.predict_sentiment_month(\"2018\",month)\n print(\"%2s - %s\" % (month,l))\n print() \n","repo_name":"lee02g29/GraduationWork","sub_path":"polls/module/sentimentAnalysis.py","file_name":"sentimentAnalysis.py","file_ext":"py","file_size_in_byte":3793,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"}
+{"seq_id":"6844695056","text":"from abc import ABCMeta, abstractmethod\n\n\nclass BaseSequence(object, metaclass=ABCMeta):\n\n _water = 18.0153\n\n def __init__(self, name, seq):\n \"\"\"\n :param seq: the sequence\n :type seq: string\n \"\"\"\n self.name = name\n self._sequence = seq\n\n @property\n def alphabet(self):\n return self._alphabet\n\n @property\n def sequence(self):\n return self._sequence\n\n\n def __len__(self):\n \"\"\"\n :return: the length of this sequence (number of bases or aa)\n :rtype: integer\n \"\"\"\n return len(self._sequence)\n\n\n def to_fasta(self):\n \"\"\"\n :return: a string in fasta format of this sequence\n :rtype: basestring\n \"\"\"\n id_ = self.name.replace(' ', '_')\n fasta = '>{}\\n'.format(id_)\n start = 0\n while start < len(self._sequence):\n end = start + 80\n fasta += self._sequence[start: end + 1] + '\\n'\n start = end\n return fasta\n\n\n def _one_strand_molec_weight(self, seq):\n \"\"\"\n helper function to compute the mw of the seq\n :param seq: the seq (nucleic or proteic) to compute the mw\n :type seq: string\n :return: mw of seq\n :rtype: float\n \"\"\"\n return sum([self._weight_table[base] for base in seq]) - (len(seq) - 1) * self._water\n\n\n @abstractmethod\n def molecular_weight(self):\n \"\"\"\n tihis method is abstract and must be implemented in child classes\n :return: The molecular weight\n :rtype: float\n \"\"\"\n pass\n\n\nclass Mutable(object):\n\n\n def mutate(self, pos, base):\n \"\"\"\n mutate the sequence replace the base at pos with base\n :param pos: the position of the base to mutate (starting count = 0)\n :type pos: integer\n :param base: the base to replace with it must be a char belonging to the alphabet\n :type base: string (one char)\n :return:\n \"\"\"\n if base not in self._alphabet:\n raise ValueError(\"base must be {}\".format(', '.join([\"'{}'\".format(c) for c in self._alphabet])))\n if pos < 0 or pos > len(self._sequence):\n raise ValueError(\"pos must be > 0 and < {}\".format(len(self._sequence)))\n head = self._sequence[0:pos]\n tail = self._sequence[pos+1:]\n self._sequence = head + base + tail\n\n\nclass NonMutableDNASequence(BaseSequence):\n\n _weight_table = {'A': 347.2212, 'C': 323.1965, 'G': 363.2206, 'T': 322.2085}\n _alphabet = 'ACGT'\n\n def molecular_weight(self):\n \"\"\"\n :return: The molecular weight\n :rtype: float\n \"\"\"\n direct_weight = self._one_strand_molec_weight(self._sequence)\n rev_comp = self.rev_comp()\n rev_comp_weight = self._one_strand_molec_weight(rev_comp.sequence)\n return direct_weight + rev_comp_weight\n\n\n def rev_comp(self):\n \"\"\"\n :return: a new sequence representing the reverse complement\n :rtype: :class:`Sequence` object\n \"\"\"\n rev = self.sequence[::-1]\n table = str.maketrans(self._alphabet, self._alphabet[::-1])\n rev_comp = str.translate(rev, table)\n return self.__class__(self.name + '_reverse', rev_comp)\n\n\nclass MutableDNASequence(NonMutableDNASequence, Mutable):\n\n pass\n\n\nclass NonMutableAASequence(BaseSequence):\n\n _weight_table = {'A': 89.0932, 'C': 121.1582, 'E': 147.1293,\n 'D': 133.1027, 'G': 75.0666, 'F': 165.1891,\n 'I': 131.1729, 'H': 155.1546, 'K': 146.1876,\n 'M': 149.2113, 'L': 131.1729, 'O': 255.3134,\n 'N': 132.1179, 'Q': 146.1445, 'P': 115.1305,\n 'S': 105.0926, 'R': 174.201, 'U': 168.0532,\n 'T': 119.1192, 'W': 204.2252, 'V': 117.1463,\n 'Y': 181.1885}\n\n _alphabet = ''.join(_weight_table.keys())\n\n def molecular_weight(self):\n \"\"\"\n :return: The molecular weight\n :rtype: float\n \"\"\"\n return super()._one_strand_molec_weight(self.sequence)\n\n\nclass MutableAASequence(NonMutableAASequence, Mutable):\n\n pass","repo_name":"C3BI-pasteur-fr/python-solutions-1","sub_path":"source/_static/code/multi_inheritance.py","file_name":"multi_inheritance.py","file_ext":"py","file_size_in_byte":4156,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"}
+{"seq_id":"30302667900","text":"\n\"\"\"\nFunctions for various latitude/longitude operations.\n\nWhile pyproj is a great package, it doesn't seem to be able to handle\nEaast-North-Up (ENU) coordinate systems. Among other things, this module\ncan.\n\n\"\"\"\n\nimport numpy as np\nimport pyproj\n\n\ndef rot_matrix_ecef2enu(lam, phi):\n \"\"\"\n Define the rotation matrix to go from ECEF coordinates to ENU.\n\n This doesn't seem to be in the package pyproj, so we'll define it here.\n Typically, you won't need to call this function.\n\n Parameters\n ----------\n lam : numeric\n The longitude of the center of the ENU system.\n phi : numeric\n The longitude of the center of the ENU system.\n\n Returns\n -------\n numpy array\n A 3x3 numpy array defining the rotation matrix.\n\n \"\"\"\n # Make the matrix below a little easier to type by defining a few variables:\n sLam = np.sin(lam)\n cLam = np.cos(lam)\n sPhi = np.sin(phi)\n cPhi = np.cos(phi)\n\n rotMatrix = np.array([[-sLam, cLam, 0],\n [-sPhi*cLam, -sPhi*sLam, cPhi],\n [cPhi*cLam, cPhi*sLam, sPhi]])\n\n return rotMatrix\n\n\ndef lla2enu(lats, lons, alts, center=None):\n \"\"\"\n Convert lat, lon, alt to ENU (East North Up) coordinates.\n\n If no center is given, use the average lat/lon/alt of input. This is the\n sister function to :func:`enu2lla`\n\n Parameters\n ----------\n lats : array-like\n The latitudes of the data\n lons : array-like\n The longitudes of the data\n alts : array-like\n The altitudes of the data (in km)\n center : three element array-like\n The lat, lon, alt of the center of the ENU coordinate system. If none\n is given, then then average of each input is used.\n\n Returns\n -------\n numpy record array\n An `n` element numpy record array, where `n` is the number of elements\n in lats/lons/alts. The record arrays has the fields `x`, `y`, and `z`.\n\n Examples\n --------\n\n Find the Cartesian location of a point located at a lat, lon of\n (34.681, -86.530) and a altitude of 1.1 km in a coordinate system\n centered at lat, lon = (34.726, -86.639) and 100 meters above the surface.\n But, remember, heights should be in kilometers and arguments are array-like\n (i.e., no scalars)::\n\n center_coord = (34.726, -86.639, 0.1)\n xyz = lla2enu([34.681], [-86.530], [1.1], center=center_coord)\n\n For a sanity check, convert back to x,y,z using the sister function\n func:`enu2lla`::\n\n lla = enu2lla(xyz.x, xyz.y, xyz.z, center=center_coord)\n\n \"\"\"\n\n # Start by defining the projections for the conversion:\n ecefProj = pyproj.Proj(proj='geocent', ellps='WGS84', datum='WGS84')\n llaProj = pyproj.Proj(proj='latlong', ellps='WGS84', datum='WGS84')\n\n # Define the transform:\n lla2ecef_xform = pyproj.Transformer.from_proj(llaProj, ecefProj)\n\n # First, convert to ECEF\n ecef = np.array(lla2ecef_xform.transform(lons, lats, np.array(alts)*1e3))\n\n # Next, convert the center:\n if center is None:\n center = (np.mean(lats), np.mean(lons), np.mean(alts)*1e3)\n\n centerEcef = np.array(lla2ecef_xform.transform(center[1], center[0], center[2]*1e3))\n\n # Now, we convert ECEF to ENU...\n\n # Start by finding the vector pointing from the origin to the point(s) of interest\n vec = (ecef.transpose() - centerEcef).transpose()\n\n # Now, we construct the rotation matrix at the origin:\n lam = np.radians(center[1])\n phi = np.radians(center[0])\n\n # Get the rotation matrix:\n rotMatrix = rot_matrix_ecef2enu(lam, phi)\n\n # Finally, transform ECEF to ENU\n enu = rotMatrix.dot(vec)/1e3 # return in km\n\n # Return as an numpy record array\n return np.core.records.fromarrays(enu, names='x,y,z')\n\n\ndef enu2lla(x, y, z, center):\n \"\"\"\n Convert from ENU (East North Up) coordinates to latitude/longitude/altitude.\n\n This is the sister function to :func:`lla2enu`\n\n Parameters\n ----------\n x : array-like\n The east-west (x) coordinates of the data in kilometers.\n y : array-like\n The north-south (y) coordinates of the data in kilometers.\n z : array-like\n The up-down (z) coordinates of the data in kilometers.\n center : three element array-like\n The lat/lon/alt of the center of the ENU coordinate system.\n Altitude is in kilometers; lat/lon in degrees.\n\n Returns\n -------\n numpy record array\n An `n` element numpy record array, where `n` is the number of elements\n in x/y/z. The record arrays has the fields `lat`, `lon`, and `alt`.\n All values are in kilometers.\n\n Examples\n --------\n\n Find the lat/lon/altitude of a point that is 10 km east, 5 km south, and\n 1 km above the Cartesian coordinate system centered at\n lat, lon = (34.726, -86.639) and 100 meters above the surface. But,\n remember, heights should be in kilometers and arguments are array-like\n (i.e., no scalars)::\n\n center_coord = (34.726, -86.639, 0.1)\n lla = enu2lla([10], [-5], [1], center=center_coord)\n\n For a sanity check, convert back to x,y,z using the sister function\n func:`lla2enu`::\n\n xyz = lla2enu(lla.lat, lla.lon, lla.alt, center=center_coord)\n\n \"\"\"\n\n # Start by defining the projections for the conversion:\n ecefProj = pyproj.Proj(proj='geocent', ellps='WGS84', datum='WGS84')\n llaProj = pyproj.Proj(proj='latlong', ellps='WGS84', datum='WGS84')\n\n # Define the transform:\n lla2ecef_xform = pyproj.Transformer.from_proj(llaProj, ecefProj)\n\n # Take the center point and convert to ECEF, but convert km to m\n centerEcef = lla2ecef_xform.transform(center[1], center[0], center[2]*1e3)\n\n # Now, convert the ENU coordinates to a \"delta\" ECEF. This is the offset\n # (in ECEF coordinates) of the points from the center. To do so, get the\n # the rotation matrix, and apply the inverse\n # (since it's a rotation matrix, the inverse is the transpose).\n\n rotMatrix = rot_matrix_ecef2enu(np.radians(center[1]), np.radians(center[0])).T\n ecefDelta = rotMatrix.dot([x, y, z])*1e3 # again, convert to m\n\n # Now, translate the vector of points to the ECEF of the center:\n ecefVec = (ecefDelta.transpose() + centerEcef).transpose()\n\n # Convert these to LLA:\n lla = np.array(lla2ecef_xform.transform(ecefVec[0, :],\n ecefVec[1, :],\n ecefVec[2, :],\n direction='INVERSE'))\n\n # Now, we want to return this as a record array, but convert the alt to km:\n dtype = [('lon', np.float), ('lat', np.float), ('alt', np.float)]\n lla = np.core.records.fromarrays([lla[0], lla[1], lla[2]/1e3],\n dtype=dtype)\n\n return lla\n","repo_name":"pbitzer/pyltg","sub_path":"pyltg/utilities/latlon.py","file_name":"latlon.py","file_ext":"py","file_size_in_byte":6831,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"37"}
+{"seq_id":"70687189226","text":"import numpy as np\nimport os\nimport sys\nimport tensorflow as tf\nfrom matplotlib import pyplot as plt\nfrom PIL import Image\nimport cv2\nimport pytesseract\nimport matplotlib.patches as patches\nfrom utilities import allow_needed_values as anv \nfrom utilities import do_image_conversion as dic\nimport cv2\n\nMODEL_NAME = 'numplate'\nPATH_TO_CKPT = MODEL_NAME + '/graph-200000/frozen_inference_graph.pb'\nPATH_TO_LABELS = 'object-detection.pbtxt'\nNUM_CLASSES = 1\n\n\ndetection_graph = tf.Graph()\nwith detection_graph.as_default():\n od_graph_def = tf.GraphDef()\n with tf.gfile.GFile(PATH_TO_CKPT, 'rb') as fid:\n serialized_graph = fid.read()\n od_graph_def.ParseFromString(serialized_graph)\n tf.import_graph_def(od_graph_def, name='')\n\n\n\ndef load_image_into_numpy_array(image):\n (im_width, im_height) = image.size\n return np.array(image.getdata()).reshape(\n (im_height, im_width, 3)).astype(np.uint8)\n\n\nPATH_TO_TEST_IMAGES_DIR = 'png_tesseract/test_motion'\nTEST_IMAGE_PATHS = [ os.path.join(PATH_TO_TEST_IMAGES_DIR, 'image{}.jpg'.format(i)) for i in range(1, 14) ]\nIMAGE_SIZE = (12, 8)\nTEST_DHARUN=os.path.join('numplate')\ncount = 0\n\n\nwith detection_graph.as_default():\n with tf.Session(graph=detection_graph) as sess:\n image_tensor = detection_graph.get_tensor_by_name('image_tensor:0')\n detection_boxes = detection_graph.get_tensor_by_name('detection_boxes:0')\n detection_scores = detection_graph.get_tensor_by_name('detection_scores:0')\n detection_classes = detection_graph.get_tensor_by_name('detection_classes:0')\n num_detections = detection_graph.get_tensor_by_name('num_detections:0')\n it = 0\n #video = cv2.VideoWriter('png_tesseract/data/output2.avi', 0, 1, (1280, 720))\n out = cv2.VideoWriter('png_tesseract/data/output.avi',cv2.VideoWriter_fourcc(*'DIVX'), 8, (1280, 720))\n for image_path in TEST_IMAGE_PATHS:\n image = Image.open(image_path) \n print(image_path)\n image_np = load_image_into_numpy_array(image)\n image_np_expanded = np.expand_dims(image_np, axis=0)\n (boxes, scores, classes, num) = sess.run(\n [detection_boxes, detection_scores, detection_classes, num_detections],\n feed_dict={image_tensor: image_np_expanded})\n #print(\"Number of detections : \", num)\n ymin = boxes[0,0,0]\n xmin = boxes[0,0,1]\n ymax = boxes[0,0,2]\n xmax = boxes[0,0,3]\n (im_width, im_height) = image.size\n (xminn, xmaxx, yminn, ymaxx) = (int(xmin * im_width), int(xmax * im_width), int(ymin * im_height), int(ymax * im_height))\n print(\"Plate detected: \", (xminn, xmaxx, yminn, ymaxx))\n \n \n \n \n \n out.write(image_np)\n \n \n plt.imshow(image_np)\n plt.show()\n it = it+1\n \n\n cropped_image = tf.image.crop_to_bounding_box(image_np, int(yminn), int(xminn),int(ymaxx - yminn), int(xmaxx - xminn))\n img_data = sess.run(cropped_image)\n count = 0\n filename = dic.yo_make_the_conversion(img_data, count)\n pytesseract.tesseract_cmd = 'Users/laishawadhwa/models/research/object_detection/tessdata/'\n text = pytesseract.image_to_string(Image.open(filename),lang=None) \n print('CHARCTER RECOGNITION : ',anv.catch_rectify_plate_characters(text))\n\n cv2.rectangle(image_np, (xminn, yminn), (xmaxx, ymaxx), (0, 255, 0) , 2)\n y = xminn - 15 if xminn - 15 > 15 else yminn + 15\n cv2.putText(image_np,text, (xminn - 145 , yminn -50),cv2.FONT_HERSHEY_SIMPLEX, 3, (0, 0, 255), 3)\n print(\"Text Detected:\", text)\n plt.imshow(img_data)\n out.release()\n \n","repo_name":"laishawadhwa/Vehicle-Number-plate-extraction","sub_path":"test_anpr.py","file_name":"test_anpr.py","file_ext":"py","file_size_in_byte":3553,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"37"}
+{"seq_id":"73778300267","text":"from reportlab.pdfgen import canvas\nfrom reportlab.platypus import Paragraph, Frame\nfrom reportlab.lib.enums import TA_JUSTIFY\nfrom reportlab.lib.units import cm\nfrom reportlab.lib.colors import toColor\nfrom reportlab.lib.pagesizes import A4, LETTER, landscape\n\nfrom reportlab.lib.styles import getSampleStyleSheet, ParagraphStyle\n\nfrom django.http.response import HttpResponse\nfrom django.template import Context, loader\nfrom django.utils.translation import ugettext as _\n\nfrom ..core.templatetags.markup import markdown\n\nfrom xhtml2pdf.document import pisaStory\n\nA4_FORMAT = \"a4\"\nLETTER_FORMAT = \"letter\"\n\nSHORT_SIDE = \"short\"\nLONG_SIDE = \"long\"\nFRONT_SIDE = \"front\"\n\nBACK_ORDER_CHOICE = {\n SHORT_SIDE: (),\n LONG_SIDE: (),\n}\n\nPAGE_SIZES_CHOICE = {\n A4_FORMAT: landscape(A4),\n LETTER_FORMAT: landscape(LETTER),\n}\n\n\ndef get_position(print_format, side):\n w, h = PAGE_SIZES_CHOICE[print_format]\n x1 = 1\n x2 = 0.5*(w/cm)+1\n y1 = 1.5\n y2 = 11.5\n\n if side == FRONT_SIDE:\n return (\n (x1, y2),\n (x2, y2),\n (x1, y1),\n (x2, y1)\n )\n elif side == LONG_SIDE:\n return (\n (x1, y1),\n (x2, y1),\n (x1, y2),\n (x2, y2)\n )\n elif side == SHORT_SIDE:\n return (\n (x2, y2),\n (x1, y2),\n (x2, y1),\n (x1, y1)\n )\n else:\n raise ValueError(\"Unknown back_side value {0}\".format(side))\n\n\nSIZE = (12.5, 8)\nTOP_HEIGHT = 2\n\n\ndef draw_story_front(c, story, positions, position=0, counter=0):\n c.saveState()\n pos = positions[position]\n size = SIZE\n c.translate(pos[0]*cm, pos[1]*cm)\n c.setStrokeColorRGB(0.2, 0.5, 0.3)\n c.rect(0, 0, size[0]*cm, size[1]*cm, fill=0)\n c.line(0, (SIZE[1]-TOP_HEIGHT)*cm, size[0]*cm, (SIZE[1]-TOP_HEIGHT)*cm)\n\n stylesheet = getSampleStyleSheet()\n normal_style = stylesheet['Normal']\n # Color\n try:\n color = toColor(story.color)\n except ValueError:\n color = toColor(\"#ffffff\")\n\n c.setFillColor(color)\n c.setStrokeColorRGB(0, 0, 0, alpha=0.1)\n c.rect(0.3*cm, (SIZE[1] - TOP_HEIGHT + 0.3)*cm, 15, (TOP_HEIGHT-0.6)*cm,\n fill=1)\n\n # theme\n p = Paragraph(u\"{0}\".format(story.theme),\n normal_style)\n p.wrap(SIZE[0]*cm, 2*cm)\n p.drawOn(c, 1.1*cm, (SIZE[1]-TOP_HEIGHT+0.4)*cm)\n\n # Point\n if story.points >= 0:\n txt = \"{0:.0f}\".format(story.points)\n circle_color = toColor(\"#BBBBBB\")\n txt_color = \"white\"\n else:\n txt = _(\"n/a\")\n circle_color = toColor(\"#888888\")\n txt_color = \"black\"\n c.setFillColor(circle_color)\n rad = 0.6\n c.setStrokeColorRGB(0, 0, 0, alpha=0.5)\n c.circle((SIZE[0]-rad - 0.3)*cm, (SIZE[1] - TOP_HEIGHT/2)*cm, rad*cm,\n fill=1)\n p = Paragraph(\n u\"{1}\".format(\n txt_color, txt\n ), normal_style)\n p.wrap(rad*2*cm, 2*cm)\n p.drawOn(c, (SIZE[0]-(rad*2)-0.29)*cm, (SIZE[1] - TOP_HEIGHT/2 + 0.05)*cm)\n c.setStrokeColorRGB(0, 0, 0, alpha=1.0)\n\n # Code\n p = Paragraph(u\"{0}\".format(story.code), normal_style)\n p.wrap(5*cm, 2*cm)\n p.drawOn(c, 1.1*cm, (SIZE[1]-TOP_HEIGHT+1.5)*cm)\n\n # Description\n found = False\n font_size = 15\n leading = 20\n while not found:\n style = ParagraphStyle(name='Custom',\n parent=normal_style,\n fontSize=font_size,\n leading=leading,\n rightIndent=20,\n leftIndent=10,\n spaceBefore=0,\n spaceAfter=0,\n alignment=TA_JUSTIFY)\n # print the html version of the story text\n t = loader.get_template(\"backlog/user_story_text.html\")\n text = t.render(Context({\n 'story': story,\n 'request': {\n 'LANGUAGE_CODE': \"en\"\n }\n }))\n p = Paragraph(text, style)\n a_w = SIZE[0]*cm\n a_h = (SIZE[1]-TOP_HEIGHT)*cm\n w, h = p.wrap(a_w, a_h) # find required space\n if w <= a_w and h <= a_h:\n p.drawOn(c, 0, (SIZE[1]-TOP_HEIGHT)*cm - h - 0.1*cm)\n found = True\n else:\n font_size -= 1\n leading -= 1\n # raise ValueError(\"Not enough room\")\n # print order\n c.setStrokeColorRGB(0, 0, 0, alpha=0.2)\n p = Paragraph(u\"{0}\".format(\n counter), normal_style)\n p.wrap(0.5*cm, 0.5*cm)\n p.drawOn(c, 0.2*cm, 0.1*cm)\n\n c.restoreState()\n\n\ndef draw_story_back(c, story, positions, position=0):\n c.saveState()\n pos = positions[position]\n size = SIZE\n c.translate(pos[0]*cm, pos[1]*cm)\n c.setStrokeColorRGB(0.2, 0.3, 0.5)\n c.rect(0, 0, size[0]*cm, size[1]*cm, fill=0)\n\n stylesheet = getSampleStyleSheet()\n normal_style = stylesheet['Normal']\n\n # Code\n p = Paragraph(u\"{0}\".format(story.code), normal_style)\n p.wrap(5*cm, 2*cm)\n p.drawOn(c, 1.1*cm, (SIZE[1]-TOP_HEIGHT+1.5)*cm)\n\n # Draw acceptance criteria\n html = u\"\"\"\n {0}
\n \"\"\".format(markdown(story.acceptances))\n context = pisaStory(html)\n f = Frame(0, 0, size[0]*cm, (size[1]-TOP_HEIGHT/2)*cm, showBoundary=1)\n f.addFromList(context.story, c)\n c.restoreState()\n\n\ndef generate_pdf(stories, file_name,\n print_side=LONG_SIDE, print_format=A4_FORMAT):\n response = HttpResponse(content_type='application/pdf')\n response['Content-Disposition'] = \\\n 'attachment; filename=\"{0}\"'.format(file_name)\n\n # Create the PDF object, using the response object as its \"file.\"\n c = canvas.Canvas(response, PAGE_SIZES_CHOICE[print_format])\n c.setAuthor(\"backlogman.com\")\n c.setTitle(\"User story printing\")\n c.setSubject(\"Stories\")\n i = 0\n front = True\n front_positions = get_position(print_format, FRONT_SIDE)\n back_position = get_position(print_format, print_side)\n story_per_page = len(front_positions)\n counter = 0\n while i < len(stories) or front:\n m = divmod(i, story_per_page)[1]\n if i < len(stories):\n story = stories[i]\n if front:\n counter += 1\n draw_story_front(c, story, front_positions, m, counter)\n else:\n draw_story_back(c, story, back_position, m)\n i += 1\n if m == story_per_page-1:\n if front:\n front = False\n i -= 4\n else:\n front = True\n if i < len(stories):\n c.showPage()\n\n c.showPage()\n c.save()\n return response\n","repo_name":"dsaradini/facile_backlog","sub_path":"facile_backlog/backlog/pdf.py","file_name":"pdf.py","file_ext":"py","file_size_in_byte":6868,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"37"}
+{"seq_id":"18040808614","text":"from typing import List, Mapping, MutableMapping, Optional, Tuple, Union\n\nimport numpy as np\nimport xarray as xr\n\nfrom starfish.core.types import ArrayLike, Axes, Coordinates, Number\n\n\ndef _get_axes_names(ndim: int) -> Tuple[List[Axes], List[Coordinates]]:\n \"\"\"Get needed axes and coordinates given the number of dimensions. The axes and coordinates are\n returned in the order expected for binary masks. For instance, the first axis/coordinate\n should be the first index into the mask.\n\n Parameters\n ----------\n ndim : int\n Number of dimensions.\n Returns\n -------\n axes : List[Axes]\n Axes.\n coords : List[Coordinates]\n Coordinates.\n \"\"\"\n if ndim == 2:\n axes = [Axes.Y, Axes.X]\n coords = [Coordinates.Y, Coordinates.X]\n elif ndim == 3:\n axes = [Axes.ZPLANE, Axes.Y, Axes.X]\n coords = [Coordinates.Z, Coordinates.Y, Coordinates.X]\n else:\n raise TypeError('expected 2- or 3-D image')\n\n return axes, coords\n\n\ndef _normalize_pixel_ticks(\n pixel_ticks: Optional[Union[\n Mapping[Axes, ArrayLike[int]],\n Mapping[str, ArrayLike[int]]]],\n) -> MutableMapping[Axes, ArrayLike[int]]:\n \"\"\"Given pixel ticks in a mapping from an axis or a string representing an axis, return a\n mapping from an axis. The mapping may also not be present (i.e., None), in which an empty\n dictionary is returned.\n \"\"\"\n\n normalized_pixel_ticks = {}\n for axis, axis_data in (pixel_ticks or {}).items():\n if isinstance(axis_data, xr.DataArray):\n normalized_pixel_ticks[Axes(axis)] = axis_data.data\n else:\n normalized_pixel_ticks[Axes(axis)] = axis_data\n\n return normalized_pixel_ticks\n\n\ndef _normalize_physical_ticks(\n physical_ticks: Union[\n Mapping[Coordinates, ArrayLike[Number]],\n Mapping[str, ArrayLike[Number]]],\n) -> Mapping[Coordinates, ArrayLike[Number]]:\n \"\"\"Given physical coordinate ticks in a mapping from a coordinate or a string representing a\n coordinate, return a mapping from a coordinate.\n \"\"\"\n\n normalized_physical_ticks = {}\n for coord, coord_data in physical_ticks.items():\n if isinstance(coord_data, xr.DataArray):\n normalized_physical_ticks[Coordinates(coord)] = coord_data.data\n else:\n normalized_physical_ticks[Coordinates(coord)] = coord_data\n\n return normalized_physical_ticks\n\n\ndef _ticks_equal(\n left: Mapping,\n right: Mapping,\n) -> bool:\n \"\"\"Given two sets of tick marks, return True if the two contain the same keys, and contain the\n same data for each key. This works for both pixel ticks and physical ticks.\n \"\"\"\n if left.keys() != right.keys():\n return False\n for key in left.keys():\n if not np.all(left[key] == right[key]):\n return False\n\n return True\n","repo_name":"spacetx/starfish","sub_path":"starfish/core/morphology/util.py","file_name":"util.py","file_ext":"py","file_size_in_byte":2881,"program_lang":"python","lang":"en","doc_type":"code","stars":220,"dataset":"github-code","pt":"37"}
+{"seq_id":"4025809154","text":"from django.core.mail import send_mail\nfrom django import forms\nfrom ..models import Contact\nfrom django.core.exceptions import ValidationError\nimport re\nfrom django.utils.translation import gettext as _\nfrom django.conf import settings\n\ndef CheckMail(value):\n if not re.match(r\"[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\\.[a-zA-Z0-9-.]+\", value):\n raise ValidationError('メールアドレスの形式が違います')\n\n\nclass ContactForm(forms.ModelForm):\n\n class Meta:\n model = Contact\n fields = ('name', 'mail', 'text',)\n labels = {\n 'name': \"Name \",\n 'mail': \"Mail \",\n 'text': \"Contact \",\n }\n\n # メール送信\n def SendContactMail(self):\n mail = self.cleaned_data['mail']\n name = self.cleaned_data['name']\n text = self.cleaned_data['text']\n subject = \"問い合わせ\"\n message = \"---以下問い合わせ内容---\"\n message += \"\\n\\n\"\n message += \"名前:\" + name + \"\\n\\n\"\n message += \"連絡先:\" + mail + \"\\n\\n\"\n message += \"内容:\" + text + \"\\n\\n\"\n from_email = getattr(settings, \"MAIL_ADDR_FROM\", None)\n recipient_list = [\n getattr(settings, \"MAIL_ADDR_TO\", None)\n ]\n\n send_mail(subject, message, from_email, recipient_list)\n\n # メールチェック\n def clean_mail(self):\n mail = self.cleaned_data['mail']\n if mail:\n if not re.match(r\"[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\\.[a-zA-Z0-9-.]+\", mail):\n raise ValidationError(\n _(\"メールアドレス形式が正しくありません。\"),\n code=\"mail format error\"\n )\n return mail\n","repo_name":"ryunoooosuke/MySite","sub_path":"myprofile/Form/contactForm.py","file_name":"contactForm.py","file_ext":"py","file_size_in_byte":1722,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"}
+{"seq_id":"20375088560","text":"from pkglib.scripts import run_setup_command\nfrom pkglib.setuptools.command.pyuninstall import pyuninstall\n\nUSAGE = \"\"\"\\\nusage: %(script)s [options] package_name\n or: %(script)s --help\n\"\"\"\n\n\ndef main(argv=None, **kw):\n run_setup_command(pyuninstall, usage=USAGE, argv=argv, **kw)\n\nif __name__ == '__main__':\n main()\n","repo_name":"man-group/pkglib","sub_path":"pkglib/pkglib/scripts/pyuninstall.py","file_name":"pyuninstall.py","file_ext":"py","file_size_in_byte":324,"program_lang":"python","lang":"en","doc_type":"code","stars":39,"dataset":"github-code","pt":"37"}
+{"seq_id":"36365938720","text":"# TO-DO: Complete the selection_sort() function below \ndef selection_sort( arr ):\n # loop through n-1 elements\n for i in range(0, len(arr) - 1):\n cur_index = i\n smallest_index = cur_index\n # TO-DO: find next smallest element\n # (hint, can do in 3 loc) \n for smallest_index in range(i+1, len(arr) ):\n if arr[cur_index] > arr[smallest_index]:\n cur_index = smallest_index\n # TO-DO: swap\n temp = arr[i]\n arr[i] = arr[cur_index]\n arr[cur_index] = temp\n\n return arr\n\n\n# TO-DO: implement the Bubble Sort function below\n#1 compare first two items\n#2 if the left > right, swap (1st item is sorted, everything else is not)\n#3 next two items, repeat above step\ndef bubble_sort( arr ):\n for i in range(0, len(arr) - 1): #outer for loop\n for j in range(0, len(arr) - 1 - i): #inner for loop\n if arr[j] > arr[j+1]: #compare item with item on right\n arr[j], arr[j+1] = arr[j+1], arr[j] \n #if item on left > item on right, swap\n return arr\n\n\n\n\n# STRETCH: implement the Count Sort function below\ndef count_sort( arr, maximum=-1 ):\n\n return arr","repo_name":"cocoitali/Sorting","sub_path":"src/iterative_sorting/iterative_sorting.py","file_name":"iterative_sorting.py","file_ext":"py","file_size_in_byte":1179,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"}
+{"seq_id":"36525167833","text":"#!/usr/bin/env python\n# coding: utf-8\n\n# In[1]:\n\n\n# Dependencies\nimport pandas as pd\nimport numpy as np\nimport plotly\nimport plotly.express as px\nimport matplotlib\n\n\n# In[2]:\n\n\n# Store filepath in a variable\n# Please note to that you need to change this path if different from the actual path \n\nfile_one = \"../Resources/CO2Emission.csv\"\nfile_two = \"../Resources/CO2GDP.csv\"\nfile_three = \"../Resources/CO2POP.csv\"\nfile_four = \"../Resources/Countries2.csv\"\nfile_five = \"../Resources/allcountries.csv\"\n\n\n# In[3]:\n\n\n# Read our Data file with the pandas library\n# Not every CSV requires an encoding, but be aware this can come up\n\n# CO2 emission \nfile_one_df = pd.read_csv(file_one, encoding=\"ISO-8859-1\")\n\n# CO2 emission per GDP\nfile_two_df = pd.read_csv(file_two, encoding=\"ISO-8859-1\")\n\n# CO2 emission per capita\nfile_three_df = pd.read_csv(file_three, encoding=\"ISO-8859-1\")\n\n# Map data\nallcountries_df = pd.read_csv(file_five, encoding=\"ISO-8859-1\")\n\nCountries_df = pd.read_csv(file_four, encoding=\"ISO-8859-1\")\n\n\n# In[4]:\n\n\n# Show just the header\nallcountries_df\n\n\n# In[5]:\n\n\n# Show just the header\n\nfile_two_df.head()\n\n\n# In[6]:\n\n\n# Show just the header\nfile_three_df.head()\n\n\n# In[7]:\n\n\nfile_one_df.count()\n\n\n# In[8]:\n\n\nfile_two_df.count()\n\n\n# In[9]:\n\n\n# Clean up the input files by dropping row with no data\n\nfile_one_df = file_one_df.dropna(0,how='any')\n\nfile_two_df = file_two_df.dropna(0,how='any')\n\nfile_three_df = file_three_df.dropna(0,how='any')\n\n\n# In[10]:\n\n\n# Test number of rows\n\nfile_one_df.count()\n\n\n# In[11]:\n\n\n# Name of the desired coulumns in the csv files\n\ncolumns = [\n \"1991\",\n \"1992\",\n \"1993\",\n \"1994\",\n \"1995\",\n \"1996\",\n \"1997\",\n \"1998\",\n \"1999\",\n \"2000\",\n \"2001\",\n \"2002\",\n \"2003\",\n \"2004\",\n \"2005\",\n \"2006\",\n \"2007\",\n \"2008\",\n \"2009\",\n \"2010\",\n \"2011\",\n \"2012\",\n \"2013\",\n \"2014\",\n \"2015\",\n \"2016\",\n \"2017\",\n \"2018\",\n \"2019\" \n]\n\n# Creat data frame for Canada. df_1, df_2, df_3 represent CO2, CO2/GDP, and CO2/Pop\nCanada_df_1 = file_one_df.loc[file_one_df[\"Region/Country/Economy\"] == \"Canada\", columns]\nCanada_df_2 = file_two_df.loc[file_two_df[\"Region/Country/Economy\"] == \"Canada\", columns]\nCanada_df_3 = file_three_df.loc[file_three_df[\"Region/Country/Economy\"] == \"Canada\", columns]\n\n# Creat data frame for US. df_1, df_2, df_3 represent CO2, CO2/GDP, and CO2/Pop\nUS_df_1 = file_one_df.loc[file_one_df[\"Region/Country/Economy\"] == \"United States\", columns]\nUS_df_2 = file_two_df.loc[file_two_df[\"Region/Country/Economy\"] == \"United States\", columns]\nUS_df_3 = file_three_df.loc[file_three_df[\"Region/Country/Economy\"] == \"United States\", columns]\n\n# Creat data frame for UK. df_1, df_2, df_3 represent CO2, CO2/GDP, and CO2/Pop\nUK_df_1 = file_one_df.loc[file_one_df[\"Region/Country/Economy\"] == \"United Kingdom\", columns]\nUK_df_2 = file_two_df.loc[file_two_df[\"Region/Country/Economy\"] == \"United Kingdom\", columns]\nUK_df_3 = file_three_df.loc[file_three_df[\"Region/Country/Economy\"] == \"United Kingdom\", columns]\n\n\n# Creat data frame for Germany. df_1, df_2, df_3 represent CO2, CO2/GDP, and CO2/Pop\nGermany_df_1 = file_one_df.loc[file_one_df[\"Region/Country/Economy\"] == \"Germany\", columns]\nGermany_df_2 = file_two_df.loc[file_two_df[\"Region/Country/Economy\"] == \"Germany\", columns]\nGermany_df_3 = file_three_df.loc[file_three_df[\"Region/Country/Economy\"] == \"Germany\", columns]\n\n\n# Creat data frame for Japan. df_1, df_2, df_3 represent CO2, CO2/GDP, and CO2/Pop\nJapan_df_1 = file_one_df.loc[file_one_df[\"Region/Country/Economy\"] == \"Japan\", columns]\nJapan_df_2 = file_two_df.loc[file_two_df[\"Region/Country/Economy\"] == \"Japan\", columns]\nJapan_df_3 = file_three_df.loc[file_three_df[\"Region/Country/Economy\"] == \"Japan\", columns]\n\n\n# Creat data frame for Italy. df_1, df_2, df_3 represent CO2, CO2/GDP, and CO2/Pop\nItaly_df_1 = file_one_df.loc[file_one_df[\"Region/Country/Economy\"] == \"Italy\", columns]\nItaly_df_2 = file_two_df.loc[file_two_df[\"Region/Country/Economy\"] == \"Italy\", columns]\nItaly_df_3 = file_three_df.loc[file_three_df[\"Region/Country/Economy\"] == \"Italy\", columns]\n\n\n# Creat data frame for France. df_1, df_2, df_3 represent CO2, CO2/GDP, and CO2/Pop\nFrance_df_1 = file_one_df.loc[file_one_df[\"Region/Country/Economy\"] == \"France\", columns]\nFrance_df_2 = file_two_df.loc[file_two_df[\"Region/Country/Economy\"] == \"France\", columns]\nFrance_df_3 = file_three_df.loc[file_three_df[\"Region/Country/Economy\"] == \"France\", columns]\n\n\n# Creat data frame for China. df_1, df_2, df_3 represent CO2, CO2/GDP, and CO2/Pop\nChina_df_1 = file_one_df.loc[file_one_df[\"Region/Country/Economy\"] == \"People's Rep. of China\", columns]\nChina_df_2 = file_two_df.loc[file_two_df[\"Region/Country/Economy\"] == \"People's Rep. of China\", columns]\nChina_df_3 = file_three_df.loc[file_three_df[\"Region/Country/Economy\"] == \"People's Rep. of China\", columns]\n\n\n\n# Creat data frame for Russia. df_1, df_2, df_3 represent CO2, CO2/GDP, and CO2/Pop\nRussia_df_1 = file_one_df.loc[file_one_df[\"Region/Country/Economy\"] == \"Russian Federation\", columns]\nRussia_df_2 = file_two_df.loc[file_two_df[\"Region/Country/Economy\"] == \"Russian Federation\", columns]\nRussia_df_3 = file_three_df.loc[file_three_df[\"Region/Country/Economy\"] == \"Russian Federation\", columns]\n\nCanada_df_1\n\n\n# In[12]:\n\n\n# Test the data frames\n# Canada_df_2.head()\n# UK_df_3.head() \n# Germany_df.head() \n# Japan_df.head() \nChina_df_3.head() \n# France_df.head() \n# China_df.head() \n# Russia_df.head() \n# US_df.head()\n# Canada_df_1.head()\n\n\n# In[13]:\n\n\n# Change the name of rows to give them an appropriate name \n\n\nCanada_df_1_New = Canada_df_1.rename(index = {0:'CO2Emission'})\nCanada_df_2_New = Canada_df_2.rename(index = {0:'CO2/GDP'})\nCanada_df_3_New = Canada_df_3.rename(index = {0:'CO2/POP'})\n\nUS_df_1_New = US_df_1.rename(index = {3:'CO2Emission'})\nUS_df_2_New = US_df_2.rename(index = {3:'CO2/GDP'})\nUS_df_3_New = US_df_3.rename(index = {3:'CO2/POP'})\n\nUK_df_1_New = UK_df_1.rename(index = {37:'CO2Emission'})\nUK_df_2_New = UK_df_2.rename(index = {37:'CO2/GDP'})\nUK_df_3_New = UK_df_3.rename(index = {37:'CO2/POP'})\n\nGermany_df_1_New = Germany_df_1.rename(index = {18:'CO2Emission'})\nGermany_df_2_New = Germany_df_2.rename(index = {18:'CO2/GDP'})\nGermany_df_3_New = Germany_df_3.rename(index = {18:'CO2/POP'})\n\nJapan_df_1_New = Japan_df_1.rename(index = {7:'CO2Emission'})\nJapan_df_2_New = Japan_df_2.rename(index = {7:'CO2/GDP'})\nJapan_df_3_New = Japan_df_3.rename(index = {7:'CO2/POP'})\n\nItaly_df_1_New = Italy_df_1.rename(index = {23:'CO2Emission'})\nItaly_df_2_New = Italy_df_2.rename(index = {23:'CO2/GDP'})\nItaly_df_3_New = Italy_df_3.rename(index = {23:'CO2/POP'})\n\nFrance_df_1_New = France_df_1.rename(index = {17:'CO2Emission'})\nFrance_df_2_New = France_df_2.rename(index = {17:'CO2/GDP'})\nFrance_df_3_New = France_df_3.rename(index = {17:'CO2/POP'})\n\nChina_df_1_New = China_df_1.rename(index = {119:'CO2Emission'})\nChina_df_2_New = China_df_2.rename(index = {119:'CO2/GDP'})\nChina_df_3_New = China_df_3.rename(index = {119:'CO2/POP'})\n\n\n\nRussia_df_1_New = Russia_df_1.rename(index = {57:'CO2Emission'})\nRussia_df_2_New = Russia_df_2.rename(index = {57:'CO2/GDP'})\nRussia_df_3_New = Russia_df_3.rename(index = {57:'CO2/POP'})\n\nChina_df_3_New\n\n\n# In[14]:\n\n\n# Transpose the dataframes\n\n\nCanada_df_1=Canada_df_1_New.T\nCanada_df_2=Canada_df_2_New.T\nCanada_df_3= Canada_df_3_New.T\n\nUS_df_1= US_df_1_New.T\nUS_df_2= US_df_2_New.T\nUS_df_3= US_df_3_New.T\n\nUK_df_1= UK_df_1_New.T\nUK_df_2= UK_df_2_New.T\nUK_df_3= UK_df_3_New.T\n\n\nGermany_df_1= Germany_df_1_New.T\nGermany_df_2= Germany_df_2_New.T\nGermany_df_3= Germany_df_3_New.T\n\nJapan_df_1= Japan_df_1_New.T\nJapan_df_2= Japan_df_2_New.T\nJapan_df_3= Japan_df_3_New.T\n\nItaly_df_1= Italy_df_1_New.T\nItaly_df_2= Italy_df_2_New.T\nItaly_df_3= Italy_df_3_New.T\n\nFrance_df_1= France_df_1_New.T\nFrance_df_2= France_df_2_New.T\nFrance_df_3= France_df_3_New.T\n\nChina_df_1= China_df_1_New.T\nChina_df_2= China_df_2_New.T\nChina_df_3= China_df_3_New.T\n\nRussia_df_1 = Russia_df_1_New.T\nRussia_df_2 = Russia_df_2_New.T\nRussia_df_3 = Russia_df_3_New.T\n\n\nChina_df_3\n\n\n# In[15]:\n\n\n# Combine all the information of a country into a single dataframe of the name of that Country \n\nframes = [Canada_df_1, Canada_df_2, Canada_df_3]\nCanada = pd.concat([Canada_df_1, Canada_df_2, Canada_df_3], axis=1)\n\n\nframes = [US_df_1, US_df_2, US_df_3]\nUS = pd.concat([US_df_1, US_df_2, US_df_3], axis=1)\n\n\nframes = [UK_df_1, UK_df_2, UK_df_3]\nUK = pd.concat([UK_df_1, UK_df_2, UK_df_3], axis=1)\n\nframes = [Germany_df_1, Germany_df_2, Germany_df_3]\nGermany = pd.concat([Germany_df_1, Germany_df_2, Germany_df_3], axis=1)\n\nframes = [Japan_df_1, Japan_df_2, Japan_df_3]\nJapan = pd.concat([Japan_df_1,Japan_df_2, Japan_df_3], axis=1)\n\nframes = [Italy_df_1, Italy_df_2, Italy_df_3]\nItaly = pd.concat([Italy_df_1,Italy_df_2, Italy_df_3], axis=1)\n\nframes = [France_df_1, France_df_2, France_df_3]\nFrance = pd.concat([France_df_1,France_df_2, France_df_3], axis=1)\n\nframes = [China_df_1, China_df_2, China_df_3]\nChina = pd.concat([China_df_1,China_df_2, China_df_3], axis=1)\n\nframes = [Russia_df_1, Russia_df_2, Russia_df_3]\nRussia = pd.concat([Russia_df_1,Russia_df_2, Russia_df_3], axis=1)\n\nRussia\n\n\n# In[16]:\n\n\nCanada['CO2Emission'] = Canada['CO2Emission'].astype(float)\nCanada['CO2/GDP'] = Canada['CO2/GDP'].astype(float)\nCanada['CO2/POP'] = Canada['CO2/POP'].astype(float)\n\nUS['CO2Emission'] = US['CO2Emission'].astype(float)\nUS['CO2/GDP'] = US['CO2/GDP'].astype(float)\nUS['CO2/POP'] = US['CO2/POP'].astype(float)\n\nUK['CO2Emission'] = UK['CO2Emission'].astype(float)\nUK['CO2/GDP'] = UK['CO2/GDP'].astype(float)\nUK['CO2/POP'] = UK['CO2/POP'].astype(float)\n\nGermany['CO2Emission'] = Germany['CO2Emission'].astype(float)\nGermany['CO2/GDP'] = Germany['CO2/GDP'].astype(float)\nGermany['CO2/POP'] = Germany['CO2/POP'].astype(float)\n\nJapan['CO2Emission'] = Japan['CO2Emission'].astype(float)\nJapan['CO2/GDP'] = Japan['CO2/GDP'].astype(float)\nJapan['CO2/POP'] = Japan['CO2/POP'].astype(float)\n\n\nFrance['CO2Emission'] = France['CO2Emission'].astype(float)\nFrance['CO2/GDP'] = France['CO2/GDP'].astype(float)\nFrance['CO2/POP'] = France['CO2/POP'].astype(float)\n\nChina['CO2Emission'] = China['CO2Emission'].astype(float)\nChina['CO2/GDP'] = China['CO2/GDP'].astype(float)\nChina['CO2/POP'] = China['CO2/POP'].astype(float)\n\nRussia['CO2Emission'] = Russia['CO2Emission'].astype(float)\nRussia['CO2/GDP'] = Russia['CO2/GDP'].astype(float)\nRussia['CO2/POP'] = Russia['CO2/POP'].astype(float)\n\nItaly['CO2Emission'] = Italy['CO2Emission'].astype(float)\nItaly['CO2/GDP'] = Italy['CO2/GDP'].astype(float)\nItaly['CO2/POP'] = Italy['CO2/POP'].astype(float)\n\n\n# In[17]:\n\n\n# Split each country's dataframe to two dataframes of before and after Paris agreemnets\n\nCanada_before = Canada.iloc[:24,:] \nCanada_after = Canada.iloc[25:,:]\n\nUS_before = US.iloc[:24,:] \nUS_after = US.iloc[25:,:]\n\nUK_before = UK.iloc[:24,:] \nUK_after = UK.iloc[25:,:]\n\nGermany_before = Germany.iloc[:24,:] \nGermany_after = Germany.iloc[25:,:]\n\nJapan_before = Japan.iloc[:24,:] \nJapan_after = Japan.iloc[25:,:]\n\nItaly_before = Italy.iloc[:24,:] \nItaly_after = Italy.iloc[25:,:]\n\nFrance_before = France.iloc[:24,:] \nFrance_after = France.iloc[25:,:]\n\nRussia_before = Russia.iloc[:24,:] \nRussia_after = Russia.iloc[25:,:]\n\nChina_before = China.iloc[:24,:] \nChina_after = China.iloc[25:,:]\n\n\n# In[18]:\n\n'''\n Now, you can calculate the statistics of Total, and before and after Paris agreemnet of each country. \n\n For example \n Canada.mean() gives you the mean of CO2 emission, CO2/GDP, and CO2/POP for the period of 1991-2019\n Canada_before.mean() gives you the mean of CO2 emission, CO2/GDP, and CO2/POP for the period of 1991-2015\n Canada_after.mean() gives you the mean of CO2 emission, CO2/GDP, and CO2/POP for the period of 2016-2019\n\n'''\n\n\nCanada_after.mean()\n\n\n# \n\n# In[19]:\n\n\nFrance_before.mean()\n\n\n# In[20]:\n\n\n# df = px.data.gapminder().query(\"year==2007\")\n\ndf = Countries_df\n\nfig = px.scatter_geo(df, locations=\"iso_alpha\", color=\"continent \",\n hover_name=\"country \", size=\"pop\",\n animation_frame=\"year \",\n projection=\"equirectangular\")\nfig.show()\n\n\n# In[21]:\n\n\nplotly.offline.plot(fig, filename='C:/Users/aragh\\Desktop/canada_offline.html')\n\n\n# In[22]:\n\n\ndf = allcountries_df\n\nfigemission = px.scatter_geo(df, locations=\"isoalpha\", color=\"continent\",\n hover_name=\"country\", size=\"co2emission\",\n animation_frame=\"year\",color_continuous_scale=px.colors.cyclical.IceFire,size_max=15, \n projection=\"equirectangular\")\nfigemission.show()\nplotly.offline.plot(figemission, filename='../Graphic/emission_offline.html')\n\n\n# In[23]:\n\n\ndf = allcountries_df\n\nfigGDP = px.scatter_geo(df, locations=\"isoalpha\", color=\"country\",\n hover_name=\"country\", size=\"co2/gdp\",\n animation_frame=\"year\",\n projection=\"equirectangular\")\nfigGDP.show()\nplotly.offline.plot(figGDP, filename='../Graphic/GDP_offline.html')\n\n\n# In[24]:\n\n\ndf = allcountries_df\n\nfigPOP = px.scatter_geo(df, locations=\"isoalpha\", color=\"country\",\n hover_name=\"country\", size=\"co2/pop\",\n animation_frame=\"year\",\n projection=\"equirectangular\")\nfigPOP.show()\nplotly.offline.plot(figPOP, filename='../Graphic/POP_offline.html')\n\n\n# In[25]:\n\n\ndf = allcountries_df\n\nfigemission1 = px.choropleth(df, locations=\"isoalpha\", color=\"co2emission\", hover_name=\"country\", animation_frame=\"year\",\n range_color=[1000,6000])\nfigemission1.show()\nplotly.offline.plot(figemission1, filename='../Graphic/emission1_offline.html')\n\n\n# In[26]:\n\n\ndf = allcountries_df\n\nfigcountries = px.choropleth(df, locations=\"isoalpha\", color=\"country\", hover_name=\"country\", \n range_color=[1000,6000])\nfigcountries.show()\n\nplotly.offline.plot(figcountries, filename='../Graphic/countries_offline.html')\n\n\n# In[41]:\n\n\ndf = allcountries_df\n\nfigtrend = px.line(df, x=\"year\", y=\"co2emission\", color=\"continent\", line_group=\"country\", hover_name=\"country\",\n line_shape=\"spline\", render_mode=\"svg\")\n\nfigtrend.update_layout(\n hoverlabel=dict(\n bgcolor=\"white\",\n font_size=16,\n font_family=\"Rockwell\"\n )\n)\n\nfigtrend.show()\nplotly.offline.plot(figtrend, filename='../Graphic/Trend')\n\n\n# In[40]:\n\n\ndf = allcountries_df\n\nfig = px.scatter(df, x=\"co2emission\", y=\"co2/gdp\", animation_frame=\"year\", animation_group=\"country\",\n size=\"co2emission\", color=\"continent\", hover_name=\"country\", facet_col=\"continent\",\n log_x=True, size_max=45, range_x=[100,10000], range_y=[0,3])\nfig.show()\nplotly.offline.plot(fig, filename='../Graphic/Group')\n\n","repo_name":"monicawwwesome/Climate-change-CO2-emission-and-GDP","sub_path":"Project_1.py","file_name":"Project_1.py","file_ext":"py","file_size_in_byte":14733,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"}
+{"seq_id":"4046479048","text":"# HTTP server for HNCP\nimport json\nfrom flask import Flask, render_template, request, redirect, send_from_directory\n\nfrom protocol_translation import proto_trans\nimport sys\n\n\n\n#for login after: pip3 install flask-login flask-sqlalchemy\n#from flask_sqlalchemy import SQLAlchemy\n#from flask_login import LoginManager, UserMixin, login_user, logout_user, login_required\n#from flask_login import current_user\n\nimport file_mngmt as fm\nimport rule_managment as rule_mngmt \nfrom rule_managment import default_rule\n\n\n\napp = Flask(__name__, static_url_path='')\n#openssl req -x509 -newkey rsa:4096 -nodes -out cert.pem -keyout key.pem -days 365\n#if __name__ == \"__main__\":\n# app.run(ssl_context=('cert.pem', 'key.pem'))\n\nservers = {'http_server':'00:1b:21:d3:1f:62','gW_Server': 'b8:27:eb:e6:70:f1'}\nignored_mac = ['ff:ff:ff:ff:ff:ff']\ndef net_topology():\n home_net_topo = {\n \"type\": \"NetworkGraph\",\n \"label\": \"Home Network\",\n \"protocol\": \"OpenFlow\",\n \"version\": \"1.3\",\n \"nodes\": [],\n \"links\": []\n\n }\n\n nodes = []\n for dev in joined_dev_info:\n node = {\n \"id\": dev['mac'].lower(),\n \"label\": dev['name'],\n \"properties\": {\n \"ip\": dev['ip'],\n \"gateway\": False\n }\n }\n nodes.append(node)\n\n links = []\n for policy in net_policy:\n if not(policy['from_mac'].lower() in joined_dev_macs and \\\n policy['to_mac'].lower() in joined_dev_macs): \n continue\n print(\"source \", policy['from_mac'])\n print(\"target\", policy['to_mac'])\n \n link = {\n \"source\": policy['from_mac'].lower(),\n \"target\": policy['to_mac'].lower(),\n \"cost\": 1,\n \"properties\": {\n \"tx\": 0.900,\n \"rx\": 0.497,\n \"bitrate\": \"100 mbit/s\",\n \"type\": \"ethernet\",\n \"protocols\": policy['service']['service_name']\n }\n }\n links.append(link)\n print(links) \n\n home_net_topo['nodes'] = nodes\n home_net_topo['links'] = links\n with open('static/home_net.json','w') as fd:\n json.dump(home_net_topo, fd)\n\n@app.route('/')\ndef root():\n return 'hellow world!'\n\n@app.route('/home')\n#@login_required\ndef home():\n global dev_info\n dev_info = fm.get_dhcp_leases()\n\n\n # request learned mac from faucet promethous 192.168.5.8:9244\n global joined_dev_macs\n joined_dev_macs = fm.get_faucet_macs()\n print('joined_dev_macs OK')\n\n # add dev IP and hostname\n global joined_dev_info \n joined_dev_info = fm.get_dev_info(joined_dev_macs, dev_info)\n print('joined_dev_info OK')\n\n # get faucet.yaml file\n global faucet_yaml\n faucet_yaml = fm.get_faucet_yaml()\n print('faucet_yaml OK')\n\n blocked_dev = fm.get_blocked_devs(joined_dev_macs)\n blocked_dev_info = fm.get_dev_info(blocked_dev, dev_info)\n\n\n # get faucet policy\n # let's make it static at first \n global net_policy\n net_policy = get_faucet_policy(faucet_yaml['acls']['wifi_acl'])\n\n return render_template('index.html', joined_dev=joined_dev_info, \n blocked_dev=blocked_dev_info, net_policy= net_policy )\n\n#Allow DHCP service for this device\n@app.route('/join', methods=['post'])\n#@login_required\ndef join():\n rule_mngmt.add_join_rules(request.form['mac'], faucet_yaml['acls']['wifi_acl'])\n\n fm.set_faucet_yaml(faucet_yaml)\n\n return redirect('/home')\n\n\n@app.route('/delete_policy', methods=['POST'])\n#@login_required\ndef network_policy():\n delete_faucet_rule( int(request.form['rule_id']) )\n fm.set_faucet_yaml(faucet_yaml)\n# return 'Rule is deleted successfully!'\n args={\"parag\":\"Rule is deleted successfully!\",\"link\":\"http://192.168.5.3:5000/home\", \"btn_value\":\"Home\"} \n return render_template('done.html', args=args )\n\n\n@app.route('/new_policy', methods=['GET'])\n#@login_required\ndef new_policy():\n args = {}\n args['local_devs_list'] = joined_dev_info\n args['services_dict'] = proto_trans['tp_proto']\n\n return render_template('new_policy.html', args = args)\n\n\n@app.route('/add_policy', methods=['POST'])\n#@login_required\ndef add_policy():\n acl_to = acl_from = faucet_yaml['acls']['wifi_acl'] \n port_no = int(request.form['service'])\n\n if(port_no not in proto_trans['tp_proto'].keys()):\n args={\"parag\":\"Service is not supported.\",\n \"link\":\"http://192.168.5.3:5000/home\", \"btn_value\":\"Home\"} \n return render_template('done.html', args=args )\n\n if request.form['to_entity'].lower() == servers['http_server']:\n acl_to = faucet_yaml['acls']['port3_acl']\n\n rule_mngmt.add_rule(request.form['from_entity'], \n request.form['to_entity'], port_no, \n acl_from, acl_to)\n fm.set_faucet_yaml(faucet_yaml)\n\n args={\"parag\":\"Rule is added successfully!\",\"link\":\"http://192.168.5.3:5000/home\", \"btn_value\":\"Home\"} \n return render_template('done.html', args=args )\n\n\n@app.route('/reset', methods=['GET'])\n#@login_required\ndef reset_faucet_config():\n fm.reset_faucet_config()\n return redirect('/home')\n\n@app.route('/show_topo', methods=['GET'])\n#@login_required\ndef show_topology():\n net_topology()\n return render_template('home_net_topo.html')\n\n@app.route('/static/')\n#@login_required\ndef static_files(path):\n return send_from_directory('static',path)\n\n\n@app.errorhandler(404)\ndef not_found(error):\n return 'Try again, error!'\n\n\ndef delete_faucet_rule(rule_id):\n\n wifi_acl_list = faucet_yaml['acls']['wifi_acl']\n copy_acl_list = []\n for i in range(0, len(wifi_acl_list) ) :\n rule = wifi_acl_list[i]['rule']\n if rule['rule_id'] == rule_id: \n continue \n copy_acl_list.append(wifi_acl_list[i])\n\n faucet_yaml['acls']['wifi_acl'] = copy_acl_list\n\n\n\n\ndef check_rev_rule(srcs, dsts, protos, rule):\n # check if rule is rev of an existing one\n is_dhcp, is_rev = rule_mngmt.is_dhcp_rule(rule)\n for idx in range(0, len(srcs['dl_src'])):\n if srcs['dl_src'][idx] == rule['dl_dst'] and \\\n ( is_dhcp or dsts['dl_dst'][idx] == rule['dl_src']) and \\\n protos['dl_type'][idx] == rule['dl_type'] and \\\n protos['nw_proto'][idx] == rule['nw_proto'] and \\\n srcs['tp_src'][idx] == rule['tp_dst'] and \\\n dsts['tp_dst'][idx] == rule['tp_src']:\n return True, idx\n return False, -1\n\n\ndef get_faucet_policy(acl_list):\n\n policy = []\n srcs = {'dl_src':[], 'nw_src':[], 'tp_src':[]}\n dsts = {'dl_dst':[],'nw_dst':[], 'tp_dst':[]}\n protos = {'dl_type':[], 'nw_proto':[]}\n \n for idx in range(0, len(acl_list)): \n \n rule = rule_mngmt.update_rule(acl_list[idx]['rule']) \n \n is_reverse, r_id = check_rev_rule(srcs,dsts,protos, rule) \n rule_id = idx if r_id == -1 else r_id \n \n acl_list[idx]['rule']['rule_id'] = rule_id\n\n srcs['dl_src'].append(rule['dl_src'])\n dsts['dl_dst'].append(rule['dl_dst'])\n srcs['tp_src'].append(rule['tp_src']) \n dsts['tp_dst'].append(rule['tp_dst'])\n protos['dl_type'].append(rule['dl_type'])\n protos['nw_proto'].append(rule['nw_proto'])\n \n if is_reverse:\n continue\n\n from_host = fm.get_dev_info(rule['dl_src'], dev_info)['name']\n to_host = fm.get_dev_info(rule['dl_dst'], dev_info)['name']\n\n service = {'service_name': rule_mngmt.get_rule_service_name(rule), \n 'actions': rule['actions']['allow']}\n new_policy = {'from_mac': rule['dl_src'],\n 'from_host': from_host,\n 'to_mac': rule['dl_dst'],\n 'to_host': to_host,\n 'from_ip': rule ['nw_src'],\n 'to_ip': rule['nw_dst'],\n 'service': service, \n 'idx': rule_id,\n 'is_rev': is_reverse \n }\n policy.append(new_policy)\n return policy\n\n\n\n\n","repo_name":"alshaboti/flaskapponly","sub_path":"admin_flask_server.py","file_name":"admin_flask_server.py","file_ext":"py","file_size_in_byte":7858,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"}
+{"seq_id":"8608097721","text":"from djangoplicity.customsearch.exporter import ExcelExporter\nfrom djangoplicity.customsearch.models import CustomSearch\nfrom django.conf import settings\n\nfrom celery.task import task\nfrom django.core.mail import EmailMessage\nfrom tempfile import NamedTemporaryFile\nimport os\n\n\n@task\ndef export_search(search_id, email, searchval=None, ordering=None, ordering_direction=None):\n '''\n Export a given search to file and email to the given address\n '''\n search = CustomSearch.objects.get(pk=search_id)\n\n # Rename the / from the search name if any\n prefix = search.name.replace('/', '-')\n\n # Generate a temporary file\n f = NamedTemporaryFile(prefix=prefix + '-', suffix='.xls', delete=False)\n\n (search, qs, searchval, _error, header, _o, _ot) = search.get_results_queryset(\n searchval=searchval,\n ordering=ordering,\n ordering_direction=ordering_direction)\n\n exporter = ExcelExporter(f, header=[ (x[1], None) for x in header ])\n\n for row in search.layout.data_table(qs):\n exporter.writerow(row['values'])\n exporter.save(f)\n f.close()\n\n # Send the export file as attachment\n email = EmailMessage('Custom Search export ready: \"%s\"' % search.name,\n '', settings.DEFAULT_FROM_EMAIL, [email])\n email.attach_file(f.name)\n email.send()\n\n # Remove the temporary file\n os.remove(f.name)\n","repo_name":"djangoplicity/djangoplicity-customsearch","sub_path":"djangoplicity/customsearch/tasks.py","file_name":"tasks.py","file_ext":"py","file_size_in_byte":1384,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"}
+{"seq_id":"30531280238","text":"#!/usr/bin/env python3\r\nimport os\r\nimport sys\r\n\r\nif __name__ == \"__main__\" and len(sys.argv) != 3:\r\n print('This script is designed to reverse complement of One || a file || \\',\\' separated || All DNA sequence/s')\r\n print(\"Usage:\\n\\tpython3 \"+ sys.argv[0] + ' \\n')\r\n print('\\tInstructions: \\n\\t\\t\\t\\tThis is a ID, if you want only one sequence get reversed and '\r\n 'complemented\\n\\t\\t\\tThis is a file contains all of id you want to reversed and '\r\n 'complemented\\n\\t\\t<0>\\t\\t\\t\\tMeans reverse and complement all of your fasta file.')\r\n print('\\n\\tAll <0> are mutually exclusive.')\r\n exit()\r\n\r\nfa = sys.argv[1]\r\nname = sys.argv[2]\r\n\r\n\r\ndef openfile(path: str):\r\n lines = []\r\n with open(path, 'r', encoding='utf-8') as f_open:\r\n file_lines = f_open.read().split('\\n')\r\n for line in file_lines:\r\n if len(line) == 0 or '#' == line[0]:\r\n continue\r\n lines.append(line)\r\n return lines\r\n\r\n\r\ndef block_cacher_v2(lines: list, separator_first: str):\r\n file_blocks = []\r\n block = []\r\n for line in lines:\r\n if len(line) == 0:\r\n continue\r\n if line.startswith(separator_first):\r\n if len(block) > 0:\r\n file_blocks.append(block)\r\n block = [line]\r\n continue\r\n block.append(line)\r\n if len(block) > 0:\r\n file_blocks.append(block)\r\n return file_blocks\r\n\r\n\r\ndef rcDNA(inSeq: str):\r\n seqDick = {\r\n 'A': 'T',\r\n 'C': 'G',\r\n 'T': 'A',\r\n 'G': 'C',\r\n 'N': 'N'\r\n }\r\n l = [seqDick[i] for i in inSeq[::-1]]\r\n return ''.join(l)\r\n\r\n\r\ndick = {b[0][1:]: ''.join(b[1:]) for b in block_cacher_v2(openfile(fa), '>')}\r\nwantedl = []\r\nif name != '0' and os.path.exists(name):\r\n n = [n for n in openfile(name) if n in dick]\r\n for k in dick:\r\n if k not in n:\r\n wantedl.append('>'+k+'\\n'+dick[k])\r\n if k in n:\r\n wantedl.append('>'+k+'_reversedComplement\\n'+rcDNA(dick[k]))\r\n with open('.'.join(fa.split('.')[:-1])+f'.{str(len(n))}Seq.reversed.fa', 'w')as f:\r\n f.write('\\n'.join(wantedl)+'\\n')\r\nif not os.path.exists(name) and name == '0':\r\n for k in dick:\r\n wantedl.append('>'+k+'_reversedComplement\\n'+rcDNA(dick[k]))\r\n with open('.'.join(fa.split('.')[:-1])+'.all.reversed.fa', 'w')as f:\r\n f.write('\\n'.join(wantedl)+'\\n')\r\nif not os.path.exists(name) and name != '0':\r\n for k in dick:\r\n if k not in name:\r\n wantedl.append('>' + k + '\\n' + dick[k])\r\n if k in name:\r\n wantedl.append('>' + k + '_reversedComplement\\n' + rcDNA(dick[k]))\r\n with open('.'.join(fa.split('.')[:-1])+f'.{name}.reversed.fa', 'w')as f:\r\n f.write('\\n'.join(wantedl)+'\\n')\r\nelif not os.path.exists(name) and name != '0' and name not in dick:\r\n print('Input Error Check Your Data!')\r\n","repo_name":"Toney823/YXK_Usefull_Tools","sub_path":"faRC.py","file_name":"faRC.py","file_ext":"py","file_size_in_byte":2965,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"37"}
+{"seq_id":"37455784088","text":"#-*- coding:utf-8 -*-\nimport asyncio\nimport dc_api\nimport base64\nimport json\nfrom core import *\nfrom flask import Flask, render_template, request\nfrom bs4 import BeautifulSoup,Tag\n\nloop = asyncio.get_event_loop()\napp = Flask(__name__)\ngallerys=[]\nwith open(\"gallerys.json\", \"r\", encoding=\"utf-8\") as f:\n gallerys = list(json.load(f).items())\nwith open(\"gallerys_miner_digital_it.json\", \"r\", encoding=\"utf-8\") as f:\n gallerys_miner_digital_it = list(json.load(f).items())\nwith open(\"gallerys_miner_game.json\", \"r\", encoding=\"utf-8\") as f:\n gallerys_miner_game = list(json.load(f).items())\n\n@app.route(\"/\")\ndef index():\n global gallerys\n global gallerys_miner_game\n global gallerys_miner_digital_it\n board = str(request.args.get(\"board\", \"None\"))\n search = str(request.args.get(\"search\", \"None\"))\n tgallerys = []\n sgallerys = None\n\n if \"game\" in board:\n sgallerys = gallerys_miner_game\n elif \"digital\" in board or \"it\" in board:\n sgallerys = gallerys_miner_digital_it\n else:\n sgallerys = gallerys\n\n if search != \"None\":\n for item in sgallerys:\n if search in item[0]:\n tgallerys.append(item)\n else:\n tgallerys = sgallerys\n return render_template('/index.html', gallerys=tgallerys)\n \n# 공군갤 airforce\n# 야갤 baseball_new10\n# 싱벙갤 singlebungle1472\n# 그림갤 drawing\n@app.route('/board')\ndef board():\n # return \"hi\"\n page = int(request.args.get(\"page\", 1))\n board = str(request.args.get(\"board\", \"airforce\"))\n recommend = int(request.args.get(\"recommend\",0))\n ret = loop.run_until_complete(async_index(page, board, recommend))\n return render_template('/board.html', datas=ret, page=page, board=board, recommend=recommend)\n\n \n@app.route(\"/read\")\ndef read():\n pid = int(request.args.get(\"pid\", 0))\n board = str(request.args.get(\"board\", \"airforce\"))\n data, comments, images = loop.run_until_complete(async_read(pid, board))\n # Parse soup, for image replation\n soup=BeautifulSoup(data[\"html\"],'html.parser')\n idx = 0\n for i in soup.find_all(\"img\", \"lazy\"):\n src = \"data:image/png;base64,\" + images[idx]\n i[\"src\"] = src\n idx += 1\n\n data[\"html\"] = str(soup)\n return render_template('/read.html', data=data, comments=comments, images=images, board=board)\n\n\n\nif __name__ == '__main__':\n\n app.run(debug=True, host=\"0.0.0.0\", port=8080)\n \n \n\n","repo_name":"mirusu400/dcinside-web-mirror","sub_path":"index.py","file_name":"index.py","file_ext":"py","file_size_in_byte":2434,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"}
+{"seq_id":"41344816781","text":"from Lista import datos\r\nfrom Lista import Lista_Datos\r\n\r\nlistar=Lista_Datos()\r\n\r\ndef nuevoContacto():\r\n print(\"Ingrese nombre:\")\r\n nombre=input(\">\")\r\n print(\"Ingrese apellido\")\r\n apellido=input(\">\")\r\n print(\"Ingrese numero de telefono\")\r\n telefono=input(\">\")\r\n existe=listar.existe(telefono)\r\n while existe==True:\r\n print(\"Este numero ya existe, ingrese otro\")\r\n print(\"Ingrese numero de telefono\")\r\n telefono=input(\">\")\r\n existe=listar.existe(telefono)\r\n \r\n nuevo=datos(nombre,apellido,telefono)\r\n listar.agregar(nuevo)\r\n print(\"Contacto agregado satisfactoriamente\")\r\n print(\"\")\r\n \r\n \r\ndef buscarContacto():\r\n print(\"Ingrese numero para la busqueda\")\r\n telefono=input(\">\")\r\n buscar=listar.buscar(telefono)\r\n if buscar==False:\r\n print(\"Contacto inexistente\")\r\n print(\"¿Desea agregarlo? S/N\")\r\n agre=input(\">\")\r\n if agre==\"S\" or agre==\"s\":\r\n nuevoContacto()\r\n\r\ndef agenda():\r\n listar.mostrarAgenda()\r\n \r\nprint(\"Bienvenido\")\r\nprint(\"Seleccione la opción a realizar:\")\r\n\r\nop=0\r\ntry:\r\n while op!=\"4\":\r\n \r\n print(\"1. Ingresar nuevo contacto\")\r\n print(\"2. Buscar Contacto\")\r\n print(\"3. Visualizar agenda\")\r\n print(\"4. Salir\")\r\n op=input(\">\")\r\n if op==\"1\":\r\n nuevoContacto()\r\n if op==\"2\":\r\n buscarContacto()\r\n if op==\"3\":\r\n agenda()\r\n \r\nexcept Exception:\r\n print(\"Error\")\r\n \r\nprint(\"Gracias, vuelve pronto\")","repo_name":"Noel1903/-IPC2-Practica2_201900822","sub_path":"Practica2.py","file_name":"Practica2.py","file_ext":"py","file_size_in_byte":1594,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"}
+{"seq_id":"16129171040","text":"import os\nfrom enum import Enum\n\nfrom sqlalchemy import create_engine, text\n\nDB_URL = os.getenv(\"DB_URL\", \"sqlite:///silly_bot.sqlite\")\nengine = create_engine(DB_URL, echo=True, future=True)\n\n\nclass Sender(str, Enum):\n USER = \"USER\"\n BOT = \"BOT\"\n\n\ndef find_greeting() -> str:\n with engine.connect() as conn:\n query = \"SELECT bot_replies FROM greetings ORDER BY RANDOM() LIMIT 1\"\n result = conn.execute(text(query))\n return result.all()[0][0]\n\n\ndef find_fallback() -> str:\n with engine.connect() as conn:\n query = \"SELECT bot_replies FROM fallbacks ORDER BY RANDOM() LIMIT 1\"\n result = conn.execute(text(query))\n return result.all()[0][0]\n\n\ndef find_reply(prompt: str) -> str:\n with engine.connect() as conn:\n query = \"SELECT bot_replies FROM dialogues WHERE user_says LIKE :prompt ORDER BY RANDOM() LIMIT 1\"\n result = conn.execute(text(query), {\"prompt\": prompt.lower().strip()})\n try:\n return result.all()[0][0]\n except IndexError:\n return find_fallback()\n\n\ndef record_message(*, chat_id: str, sender: Sender, message: str) -> None:\n with engine.connect() as conn:\n conn.execute(\n text(\n \"INSERT INTO messages (chat_id, time, sender, text) VALUES (:chat_id, STRFTIME ('%s', 'now'), :sender, :text)\"\n ),\n [{\"chat_id\": chat_id, \"sender\": sender, \"text\": message}],\n )\n conn.commit()\n\n\ndef get_transcript(chat_id: str) -> list[dict]:\n with engine.connect() as conn:\n query = \"SELECT DATETIME(time, 'unixepoch') AS time, sender, text FROM messages WHERE chat_id = :chat_id ORDER BY time\"\n result = conn.execute(text(query), {\"chat_id\": chat_id})\n return result.all()\n","repo_name":"kindly-ai/assignment-platform-engineer","sub_path":"backend/db.py","file_name":"db.py","file_ext":"py","file_size_in_byte":1767,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"}
+{"seq_id":"36627595121","text":"import json\nimport requests\nimport datetime\nfrom dotmap import DotMap\nfrom APICalls.config import get_config_from_json\nimport pandas as pd\nimport logging\nlogging.basicConfig(level=logging.INFO)\n\nclass TMDBRequests():\n\n def __init__(self):\n self.keys = get_config_from_json('..//Keys//keys.json')\n self.api_key = self.keys.tmdb_key.api_key\n self.language = 'en'\n self.debug = True\n\n try:\n self.manualMovies = pd.read_excel(\"..//Database//manual_movies.xlsx\",header=0)\n self.manualIncl = self.manualMovies['inclusions'].dropna()\n self.manualExcl = self.manualMovies['exclusions'].dropna()\n\n except Exception as ex:\n print(ex)\n self.manualMovies =pd.DataFrame()\n logging.info(\"Couldn't find manual movie files. Creating new empty one\")\n\n try:\n self.movie_titles = pd.read_csv(\"..//Database//movie_titles.csv\",index_col=0, escapechar='/')\n logging.info(\"Found existing movie titles. Checking for manual and new TMDB pull data...\")\n except Exception as ex:\n self.movie_titles = self.createCombinedTMDB()\n logging.info(\"Couldn't find movie_titles file. Initializing new file from latest TMDB pull\")\n\n def getMovieGenres(self):\n path = \"https://api.themoviedb.org/3/genre/movie/list?api_key={}&language=en-US\".format(self.api_key)\n\n response = requests.get(path)\n movieGenres_dict = response.json()\n movieGenres = pd.DataFrame(movieGenres_dict['genres'])\n return movieGenres\n\n def getPopularMovies(self, pages):\n popularMovies=pd.DataFrame()\n\n logging.info(\"Extracting popular movies\")\n for page in range (1,pages+1):\n path = \"https://api.themoviedb.org/3/movie/popular?api_key={}&language=en-US&page={}\".format(self.api_key, page)\n response = requests.get(path)\n popularMovies_dict = response.json()\n popularMovies = popularMovies.append(popularMovies_dict['results'],ignore_index=True)\n\n foreign_lang_idx = popularMovies[popularMovies['original_language'] != 'en'].index\n popularMovies.drop(foreign_lang_idx, inplace=True)\n\n popularMovies['tmdbCategory'] = 'popular'\n return popularMovies\n\n def getNowPlayingMovies(self, pages):\n nowPlayingMovies=pd.DataFrame()\n\n logging.info(\"Extracting now playing movies\")\n for page in range (1,pages+1):\n path = \"https://api.themoviedb.org/3/movie/now_playing?api_key={}&language=en-US&page={}\".format(self.api_key, page)\n response = requests.get(path)\n nowPlayingMovies_dict = response.json()\n nowPlayingMovies = nowPlayingMovies.append(nowPlayingMovies_dict['results'],ignore_index=True)\n nowPlayingMovies['tmdbCategory'] = 'nowPlaying'\n\n foreign_language_idx = nowPlayingMovies[nowPlayingMovies['original_language'] != 'en'].index\n nowPlayingMovies.drop(foreign_language_idx, inplace=True)\n\n return nowPlayingMovies\n\n def getTopRatedMovies(self, pages):\n topRatedMovies = pd.DataFrame()\n\n for page in range(1, pages + 1):\n path = \"https://api.themoviedb.org/3/movie/top_rated?api_key={}&language=en-US&page={}\".format(self.api_key,\n page)\n response = requests.get(path)\n topRatedMovies_dict = response.json()\n topRatedMovies = topRatedMovies.append(topRatedMovies_dict['results'], ignore_index=True)\n topRatedMovies['tmdbCategory'] = 'topRated'\n\n foreign_language_idx = topRatedMovies[topRatedMovies['original_language'] != 'en'].index\n topRatedMovies.drop(foreign_language_idx, inplace=True)\n\n return topRatedMovies\n\n def getUpcomingMovies(self, pages):\n upcomingMovies = pd.DataFrame()\n\n logging.info(\"Extracting upcoming movies\")\n for page in range(1, pages + 1):\n path = \"https://api.themoviedb.org/3/movie/upcoming?api_key={}&language=en-US&page={}\".format(self.api_key,\n page)\n response = requests.get(path)\n upcomingMovies_dict = response.json()\n upcomingMovies = upcomingMovies.append(upcomingMovies_dict['results'], ignore_index=True)\n\n foreign_lang_idx = upcomingMovies[upcomingMovies['original_language'] != 'en'].index\n upcomingMovies.drop(foreign_lang_idx,inplace=True)\n upcomingMovies['tmdbCategory'] = 'upcoming'\n\n return upcomingMovies\n\n def getUniqueTitles(self):\n '''Add titles from manual list while checking against duplicates'''\n logging.info(\"Getting unique titles from manual list\")\n\n unique_from_tmdb = [title for title in self.manualIncl if title not in self.tmdbPull.title.values]\n unique_titles = [title for title in unique_from_tmdb if title not in self.movie_titles.title.values]\n logging.info(\"{} unique titles found in manual search\".format(len(unique_titles)))\n\n return unique_titles\n\n def manualAdds(self):\n\n # get unique titles checking against current DB and against latest TMDB Pull\n unique_titles = self.getUniqueTitles()\n\n # get TMDB data for unique manual additions\n manualData = pd.DataFrame()\n for title in unique_titles:\n try:\n path= \"https://api.themoviedb.org/3/search/movie?api_key={}&query={}\".format(self.api_key, title)\n response = requests.get(path)\n response_dict = response.json()\n manualData = manualData.append(response_dict['results'][0],ignore_index=True)\n manualData['tmdbCategory']='manual'\n logging.info(\"Received metadata from TMDB for {}\".format(title))\n except Exception as ex:\n logging.warning(\"Did not find {} on TMDB\".format(title))\n print(ex)\n\n\n #add manual titles with TMDB data to existing DB\n additions = 0\n for index, row in manualData.iterrows():\n if self.movie_titles.empty:\n logging.info(\"Initialize all titles first\")\n else:\n self.movie_titles = self.movie_titles.append(row, ignore_index=True).reset_index(drop=True)\n additions += 1\n logging.info(\"{} added to database from manual list\".format(row.title))\n\n\n\n logging.info(\"{} movies added manually with TMDB Data\".format(additions))\n\n def newTMDBAdds(self):\n '''Check against current database for duplicates'''\n try:\n logging.info(\"Checking for duplicates against current database\")\n new_adds = 0\n\n for index, row in self.tmdbPull.iterrows():\n if row.title not in self.movie_titles['title'].values:\n new_adds+=1\n self.movie_titles = self.movie_titles.append(row,ignore_index=False).reset_index(drop=True)\n logging.info(\"{} was not found in existing DB so adding it.\".format(row.title))\n if new_adds == 0:\n logging.info(\"No new titles found in TMDB search\")\n else:\n logging.info(\"Total of {} new titles found and added in TMDB search\".format(new_adds))\n logging.info(\"Existing DB saved and updated with {} new titles and {} total titles\".format(new_adds,self.movie_titles.shape[0]))\n except Exception as ex:\n print(ex)\n logging.info(\"No existing database was found. Created new file with {} titles\".format(self.movie_titles.shape[0]))\n\n def createCombinedTMDB(self):\n self.tmdbPull = pd.DataFrame()\n popularMovies = self.getPopularMovies(pages=4)\n topRatedMovies = self.getTopRatedMovies(pages=4)\n upcomingMovies = self.getUpcomingMovies(pages=4)\n nowPlayingMovies = self.getNowPlayingMovies(pages=4)\n self.tmdbPull = self.tmdbPull.append([popularMovies,\n topRatedMovies,\n upcomingMovies,\n nowPlayingMovies],\n ignore_index=True)\n self.tmdbPull.reset_index(drop=True,inplace=True)\n\n logging.info(\"{} movies extracted from TMDB Curated Lists\".format(self.tmdbPull.shape[0]))\n return self.tmdbPull\n\n def dropDuplicates(self):\n unique_df = self.movie_titles.drop_duplicates(subset=['title'], keep='first')\n self.movie_titles = unique_df.reset_index(drop=True)\n logging.info(\"{} remain after duplicates rationalization\".format(self.movie_titles.shape[0]))\n\n def removeExclusions(self):\n df = self.movie_titles\n\n idx_drop = df[df['title'].isin(self.manualExcl)].index\n result_df = df.drop(idx_drop, inplace = False)\n\n self.movie_titles = result_df.reset_index(drop=True)\n logging.info(\"{} remain after exclusions\".format(self.movie_titles.shape[0]))\n\n def updateCategories(self):\n df = self.movie_titles\n curr_d = datetime.datetime.now()\n\n for index, row in df.iterrows():\n try:\n rel_date = datetime.datetime.strptime(str(row.release_date),'%Y-%m-%d')\n if rel_date > curr_d:\n logging.info('Updating category for {}'.format(row.title))\n df.at[index, 'tmdbCategory'] = 'upcoming'\n except Exception as ex:\n logging.info(\"One of titles did not have correct release date string\")\n continue\n\n self.movie_titles = df\n\n def updateMovieTitles(self,manualList=None):\n '''Gets data from TMDB for 4 categories - popular, top rated, upcoming and now playing and also checks with manual list\n Combines TMDB data into master allTitles dataframe and saves to file '''\n\n #Creates TMDB Pull list from latest search\n self.createCombinedTMDB()\n\n #Adding from manual data if not duplicates\n self.manualAdds()\n\n # Adding from new TMDB Pull data if not duplicates\n self.newTMDBAdds()\n\n # Remove duplicates\n self.dropDuplicates()\n\n #remove exclusions\n self.removeExclusions()\n\n # update categories for upcoming films\n self.updateCategories()\n\n self.movie_titles['content_type'] = \"movie\"\n self.movie_titles.to_csv(\"..//Database//movie_titles.csv\")\n\nif __name__ == '__main__':\n TMDB = TMDBRequests()\n TMDB.updateMovieTitles()\n\n\n","repo_name":"tactycHQ/Gemini2","sub_path":"Application/movies.py","file_name":"movies.py","file_ext":"py","file_size_in_byte":10675,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"}
+{"seq_id":"40977744661","text":"from flask import Flask\n\nfrom hooks.plugins.redis_backend import RedisBackend\nfrom hooks.plugins.zustand import create\n\napp = Flask(__name__)\n\nRedisBackend.use(\"localhost\", 6379)\n\nuse_bear_store = create(\n {\n \"bears\": \"🐻\",\n },\n lambda set, get: (\n {\n \"increase_bears\": lambda: set(\n lambda state: {**state, \"bears\": state[\"bears\"] + \"🐻\"}\n ),\n }\n ),\n)\n\nincrease_bears = use_bear_store(lambda state: state.increase_bears)\n\n\n@app.route(\"/\")\ndef get_bears():\n increase_bears()\n return use_bear_store(lambda state: state.bears)\n\n\nif __name__ == \"__main__\":\n app.run(debug=True, host=\"0.0.0.0\", port=9999)\n","repo_name":"amitassaraf/python-hooks","sub_path":"examples/hooks-in-apis/api/bears_app.py","file_name":"bears_app.py","file_ext":"py","file_size_in_byte":685,"program_lang":"python","lang":"en","doc_type":"code","stars":37,"dataset":"github-code","pt":"37"}
+{"seq_id":"30995466639","text":"import tensorflow as tf\nfrom tensorflow.python.client import timeline\nfrom tensorflow.python.tools.optimize_for_inference_lib import optimize_for_inference\nimport numpy as np\nimport time\nimport argparse\nimport os\n\n\ndef run():\n X = tf.placeholder(tf.float32, shape=(None, 1024), name=\"Placeholder_X\")\n # dense layer\n dense = tf.layers.dense(X, 1024, \n kernel_initializer=tf.glorot_uniform_initializer(),\n bias_initializer=tf.glorot_uniform_initializer())\n \n\n # Generate some dummy data\n np.random.seed(42)\n x_train = np.random.rand(args.batch_size, 1024).astype(np.float32)\n\n session_conf = tf.ConfigProto(\n intra_op_parallelism_threads=args.intra,\n inter_op_parallelism_threads=args.inter)\n\n with tf.Session(config=session_conf) as sess:\n sess.run(tf.global_variables_initializer())\n for _ in range(10):\n s = time.time()\n y = sess.run(dense, feed_dict={\"Placeholder_X:0\": x_train})\n e = time.time()\n print(f\"Time(ms): {(e-s)*1000}\")\n print(y.shape)\n\n \nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser()\n parser.add_argument(\"--batch_size\", type=int, help=\"batch size\", default=4000)\n parser.add_argument(\"--inter\", type=int, default=0)\n parser.add_argument(\"--intra\", type=int, default=0)\n args = parser.parse_args()\n\n run()\n","repo_name":"imzhuhl/ml_workloads","sub_path":"tensorflow1/test/dense.py","file_name":"dense.py","file_ext":"py","file_size_in_byte":1418,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"}
+{"seq_id":"16416293472","text":"# Libraries\nseed = 2023\nimport random\nimport pandas as pd\nimport numpy as np\n\nfrom surprise import KNNWithZScore, Dataset, Reader\nfrom surprise.model_selection import train_test_split\n\nfrom surprise import Dataset, Reader, KNNWithZScore\nfrom surprise.model_selection import train_test_split\n\n\ndef get_business_city(df_business, df_review_f, business_id, should_print = False):\n try:\n city = df_business[df_business[\"business_id\"] == business_id][\"city\"].tolist()[0]\n business_in_city = df_business[df_business[\"city\"] == city][\"business_id\"].tolist()\n df_city = df_review_f[df_review_f['business_id'].isin(business_in_city)]\n df_city = df_city[[\"user_id\",\"business_id\", \"stars\"]]\n \n if should_print:\n print(city)\n print(\"Num. reviews\", df_city.shape[0])\n print(\"-------------------\")\n return df_city\n except:\n return pd.DataFrame()\n\ndef get_knn_city(df_business, df_review_f, user_id, business_id, should_print = False):\n df_city = get_business_city(df_business, df_review_f, business_id, should_print)\n \n try:\n # Load data \n if df_city.shape[0] >= 5:\n reader = Reader(rating_scale=(1, 5))\n data = Dataset.load_from_df(df_city, reader)\n\n # Split data\n trainset, testset = train_test_split(data, test_size=0.2, random_state=seed)\n\n knn = KNNWithZScore(k = 2, sim_options={'name': 'pearson', 'user_based':True}, random_state=seed, verbose=False)\n knn.fit(trainset)\n \n return knn\n else: \n return None\n except:\n return None\n \ndef get_user_friends(df, df_user_friends, user_id, should_print = False):\n friends_set = df_user_friends[df_user_friends['user_id'] == user_id]\n if friends_set.shape[0] == 0:\n return pd.DataFrame()\n else:\n friends_set = friends_set[\"friends\"].tolist()[0]\n friends_set = set(friends_set)\n\n df_friends = df.copy()\n df_friends = df_friends[df_friends['user_id'].isin(friends_set)]\n \n if should_print:\n print(\"Friends information\")\n print(df_friends.describe())\n print(\"-------------------\")\n return df_friends\n\ndef get_knn_friends(df, df_user_friends, user_id, business_id, should_print = False):\n df_friends = get_user_friends(df, df_user_friends, user_id, should_print) \n \n try:\n # Load data \n if df_friends.shape[0] >= 5:\n reader = Reader(rating_scale=(1, 5))\n data = Dataset.load_from_df(df_friends, reader)\n\n # Split data\n trainset, testset = train_test_split(data, test_size=0.2, random_state=seed)\n\n knn = KNNWithZScore(k = 2, sim_options={'name': 'pearson', 'user_based':True}, random_state=seed, verbose=False)\n knn.fit(trainset)\n \n return knn\n else: \n return None\n except:\n return None\n\ndef get_weights(city_successful, friends_successful):\n # Order: SVD, KNN, KNN_City, KNN_Friends\n # 4 Cases according to the booleans\n \n if city_successful and friends_successful:\n return [0.25, 0.5, 0.2, 0.05]\n elif city_successful and not friends_successful:\n return [0.3, 0.5, 0.2, 0.0]\n elif not city_successful and friends_successful:\n return [0.3, 0.6, 0.0, 0.1]\n else:\n return [0.4, 0.6, 0.0, 0.0]\n\n# Make hybrid predictions\ndef hybrid_predict(svd, knn, df, df_user_friends, df_business, df_review_f, user_id, business_id, should_print = False):\n knn_city = get_knn_city(df_business, df_review_f, user_id, business_id, should_print) \n knn_friends = get_knn_friends(df, df_user_friends, user_id, business_id, should_print)\n city_successful = knn_city is not None\n friends_successful = knn_friends is not None\n \n svd_prediction = svd.predict(user_id, business_id).est\n knn_prediction = knn.predict(user_id, business_id).est\n knn_city_prediction = 0\n knn_friends_prediction = 0\n\n if city_successful:\n knn_city_prediction = knn_city.predict(user_id, business_id).est\n\n if friends_successful:\n knn_friends_prediction = knn_friends.predict(user_id, business_id).est\n\n if should_print:\n print(\"SVD:\", svd_prediction)\n print(\"KNN:\", knn_prediction)\n print(\"KNN City:\", \"There is not enough information to create a recommendation model.\" if not city_successful else knn_city_prediction)\n print(\"KNN Friends:\", \"There is not enough information to create a recommendation model.\" if not friends_successful else knn_friends_prediction)\n print(\"-------------------\")\n \n models_predictions = [svd_prediction, knn_prediction, knn_city_prediction, knn_friends_prediction]\n weights = get_weights(city_successful, friends_successful)\n \n hybrid_prediction = np.dot(weights, models_predictions)\n \n return hybrid_prediction\n\nasync def get_top_n(svd, knn, df, df_user_friends, df_business, df_review_f, user_id, n):\n print(\"User:\", user_id)\n \n # Get all businesses the user has not reviewed\n all_businesses = set(df['business_id'].unique())\n reviewed_businesses = set(df[df['user_id'] == user_id]['business_id'].unique())\n unreviewed_businesses = all_businesses - reviewed_businesses\n print(\"Total business:\", len(unreviewed_businesses))\n \n unreviewed_businesses = list(unreviewed_businesses)\n num_business = len(unreviewed_businesses)\n num_sample = int(num_business * 0.01)\n unreviewed_businesses = random.sample(unreviewed_businesses, num_sample)\n \n # Make predictions for unreviewed businesses and sort by prediction\n predictions = []\n for business_id in unreviewed_businesses:\n prediction = hybrid_predict(svd, knn, df, df_user_friends, df_business, df_review_f, user_id, business_id, False)\n predictions.append((business_id, prediction))\n #print((business_id, prediction))\n predictions.sort(key=lambda x: x[1], reverse=True)\n\n # Get top n recommended businesses and their predictions\n top_n = predictions[:n]\n top_n_businesses = [x[0] for x in top_n]\n top_n_predictions = [x[1] for x in top_n]\n top_n_percentage = [str(round(x/5*100, 2))+\"%\" for x in top_n_predictions]\n\n # Create DataFrame with business ids and predictions\n df_top_n = pd.DataFrame({'business_id': top_n_businesses, 'prediction': top_n_predictions, 'percentage': top_n_percentage})\n df_top_n = pd.merge(df_top_n, df_business, on='business_id')\n return df_top_n\n","repo_name":"SergioZona/Taller2_SR_202310","sub_path":"app/backend/src/recommendation_systems/model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":6564,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"}
+{"seq_id":"40951753980","text":"#!/usr/bin/env python\n# *-* coding: utf-8 *-*\n\nimport unittest\nfrom test_mathfunc import TestMathFunc\n\nif __name__ == \"__main__\":\n\tsuite=unittest.TestSuite()\n\n\ttests=[TestMathFunc(\"test_multi\"), TestMathFunc(\"test_minus\"), TestMathFunc(\"test_add\")]\n\tsuite.addTests(tests)\n\n\t#suite1 = test_mathfunc.TheTestSuite()\n\t#suite1 = test_strfunc.TheTestSuite()\n\t\n\t#suite1.AddTest(test_mathfunc.TestMathFunc('test_add'))\n\t#suite2.AddTest(test_strfunc.TestStrFunc('test_lower'))\n\t#suite=unittest.TestSuite(suite1, suite2)\n\n\trunner = unittest.TextTestRunner(verbosity=2)\n\n\trunner.run(suite)\n","repo_name":"VeinFu/python_notes","sub_path":"unittest/test_suite.py","file_name":"test_suite.py","file_ext":"py","file_size_in_byte":580,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"}
+{"seq_id":"32042172537","text":"__all__ = [\n 'load_script_args_from_config_file',\n 'parse_script_args',\n 'set_logging'\n]\n\nimport argparse\nimport io\nimport json\nimport logging\nimport os\n\nfrom oasis_utils import OasisException\n\n\ndef load_script_args_from_config_file(script_args_metadict, config_file_path):\n \"\"\"\n Returns a script arguments dict from a JSON config file.\n \"\"\"\n di = script_args_metadict\n\n cfp = config_file_path if os.path.isabs(config_file_path) else os.path.abspath(config_file_path)\n cfd = os.path.dirname(cfp)\n\n if cfp.endswith('json'):\n try:\n with io.open(cfp, 'r', encoding='utf-8') as f:\n args = json.load(f)\n except (IOError, TypeError, ValueError) as e:\n raise OasisException('Error parsing script resources config file {}: {}'.format(cfp, str(e)))\n\n try:\n map(\n lambda arg: args.update({arg: os.path.join(cfd, args[arg])}) if arg.endswith('path') and args[arg] else None,\n args\n )\n\n invalid_paths = dict(\n (path_key, args[path_key]) for path_key in\n filter(lambda arg: arg in di and arg.endswith('path') and di[arg]['preexists'] and args[arg] and not os.path.exists(args[arg]), args)\n )\n if invalid_paths:\n raise OasisException('Error parsing script resources config file: paths {} are invalid'.format(invalid_paths))\n except OSError as e:\n raise OasisException('Error parsing script resources config file: {}'.format(str(e)))\n elif cfp.endswith('yaml') or cfp.endswith('yml'):\n raise OasisException('Error parsing script resources config file: YAML file not supported')\n\n return args\n\n\ndef parse_script_args(script_args_metadict, desc=None):\n \"\"\"\n Parses script arguments using a script arguments meta dict, constructs and\n returns an args dictionary.\n \"\"\"\n parser = argparse.ArgumentParser(description=desc)\n\n di = script_args_metadict\n\n try:\n non_bools = filter(lambda arg: di[arg]['type'] != bool, di)\n map(\n lambda arg: parser.add_argument(\n '--{}'.format(di[arg]['name']),\n '-{}'.format(di[arg]['flag']),\n type=di[arg]['type'],\n required=di[arg]['required_on_command_line'],\n help=di[arg]['help_text']\n ),\n non_bools\n )\n\n bools = filter(lambda arg: arg not in non_bools, di)\n map(\n lambda arg: (\n parser.add_argument(\n '--{}'.format(di[arg]['name']),\n dest=di[arg]['dest'],\n action='store_true',\n default=(True if di[arg]['default'] else False),\n help=di[arg]['help_text']\n ),\n parser.add_argument(\n '--no-{}'.format(di[arg]['name']),\n dest=di[arg]['dest'],\n action='store_false',\n help=di[arg]['help_text']\n ),\n ),\n bools\n )\n\n args = vars(parser.parse_args())\n\n map(\n lambda arg: args.update({arg: os.path.abspath(args[arg])}) if arg.endswith('path') and args[arg] else None,\n args\n )\n\n invalid_paths = dict(\n (path_key, args[path_key]) for path_key in\n filter(lambda arg: arg in di and arg.endswith('path') and di[arg]['preexists'] and args[arg] and not os.path.exists(args[arg]), args)\n )\n if invalid_paths:\n raise OasisException('Error parsing script args: paths {} are invalid'.format(invalid_paths))\n except (KeyError, argparse.ArgumentError, argparse.ArgumentTypeError, OSError) as e:\n raise OasisException(e)\n\n return args\n\n\ndef set_logging(\n level=logging.INFO,\n fmt='%(asctime)s - %(levelname)s - %(message)s',\n filename=None,\n filemode='w',\n stream=None\n):\n \"\"\"\n Sets up and returns a logger.\n \"\"\"\n try:\n logging.basicConfig(\n level=level,\n format=fmt,\n filename=filename,\n filemode='w',\n stream=stream\n )\n except (OSError, IOError) as e:\n raise OasisException(e)\n\n return logging.getLogger()\n","repo_name":"jariou/omdk","sub_path":"utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":4305,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"}
+{"seq_id":"17134701013","text":"import numpy as np\nimport sklearn.datasets\nfrom sklearn.feature_selection import mutual_info_classif\nfrom sklearn.feature_selection import mutual_info_regression\n\nfrom context import vfs\nfrom vfs import mi_frame\n\n\n\"\"\"\nThis script compares our MI implementation against a established one from\nthe sklearn library, by computing the traditional singledim I(X,Y) for X,Y\nextracted from an arbitrary dataset.\n\nNotice that sklearn functions are not deterministic, hence their results are\naveraged for a number of runs.\n\"\"\"\n\n\nif __name__ == '__main__':\n\n # Load dataframe and fetch column names for arbitary feature and target\n df = sklearn.datasets.load_iris(as_frame=True).frame\n feature = df.columns[0]\n target = df.columns[-1]\n\n # Computing MI using scikit methods\n ff = df[feature].values.reshape(-1,1)\n yy = df[target].values\n mi_clasif = np.array([mutual_info_classif(ff, yy, n_neighbors=5) for __ in range(20)])\n mi_regres = np.array([mutual_info_regression(ff, yy, n_neighbors=5) for __ in range(20)])\n\n # Computing MI using our implementation\n mi_ours = mi_frame(df)([feature], [target])\n\n # Display, using standard deviation in %\n std = lambda arr : round((arr.std() / (arr.std()+arr.mean())) * 100)\n print(f\"\"\"@@ Comparing our MI approach to a baseline (singledimensional):\n \\rScikit classif: {mi_clasif.mean().round(3)} (stddev={std(mi_clasif)}%)\n \\rScikit regression: {mi_regres.mean().round(3)} (stddev={std(mi_regres)}%)\n \\rOur MI: {mi_ours}\\\n \"\"\"\n )\n","repo_name":"pabsan-0/vfs2","sub_path":"scripts/mi_baseline.py","file_name":"mi_baseline.py","file_ext":"py","file_size_in_byte":1534,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"}
+{"seq_id":"15349834905","text":"## @package HTTP--Chat.base Base module.\n## @file base.py Implementation of @ref HTTP--Chat.base\n#\n\nimport logging\nimport sys\n\n\n## Base of all objects.\n#\nclass Base(object):\n\n ## Log prefix to use.\n LOG_PREFIX = 'my'\n\n ## Logger.\n @property\n def logger(self):\n \"\"\"Logger.\"\"\"\n return self._logger\n\n ## Constructor.\n def __init__(self):\n \"\"\"Contructor.\"\"\"\n self._logger = logging.getLogger(\n '%s.%s' % (\n self.LOG_PREFIX,\n self.__module__,\n ),\n )\n\n ## Equality operator.\n # @arg other (object) other object.\n # @returns (bool) True if equal.\n #\n def __eq__(self, other):\n\n if type(self) is not type(other):\n return NotImplemented\n\n sup = super(Base, self)\n # python-3\n if hasattr(sup, '__eq__'):\n return sup.__eq__(other)\n else:\n return True\n\n\n## Setup logging system.\n# @returns (logger) program logger.\n#\ndef setup_logging(stream=None, level=logging.INFO):\n logger = logging.getLogger(Base.LOG_PREFIX)\n logger.propagate = False\n logger.setLevel(level)\n\n try:\n if stream is not None:\n h = logging.StreamHandler(stream)\n else:\n h = logging.StreamHandler(sys.stdout)\n h.setLevel(logging.DEBUG)\n h.setFormatter(\n logging.Formatter(\n fmt=(\n '%(asctime)-15s '\n '[%(levelname)-7s] '\n '%(name)s::%(funcName)s:%(lineno)d '\n '%(message)s'\n ),\n ),\n )\n logger.addHandler(h)\n except IOError:\n logging.warning('Cannot initialize logging', exc_info=True)\n\n return logger\n","repo_name":"maxim-mat/HTTP-Chat","sub_path":"base.py","file_name":"base.py","file_ext":"py","file_size_in_byte":1764,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"}
+{"seq_id":"13997090329","text":"import random\nimport re\nimport os\nfrom pyjokes import pyjokes\npattern1 = re.compile(r\"\\bname\\b\")\npattern2 = re.compile(r\"\\bjoke\\b\")\nmy_list = []\nwith open(\"mybot.txt\", mode=\"r\") as my_file:\n my_bot = my_file.readlines()\n for sentence in my_bot:\n my_list.append(sentence.strip())\n\nclear = lambda: os.system('cls')\nclear()\nuser_name = input(\"Enter your Name: \").capitalize()\n\nmessage = \"None\"\nprint(f\"Pybot: Hi {user_name}! How may I assist you?\")\nwhile message.upper() != \"BYE\":\n message = input(f\"{user_name}: \")\n if pattern1.search(message):\n print(\"Pybot: Hello, My Name is Pybot!\")\n elif pattern2.search(message):\n print(f\"Pybot: {pyjokes.get_joke('en')}\")\n elif message.upper() == \"BYE\":\n print(f\"Here's my last Joke{pyjokes.get_joke('en')}\")\n else:\n print(f\"Pybot: {my_list[random.randrange(my_list.__len__())]}\")\n\n","repo_name":"JohnEdrick/PythonChatBot","sub_path":"PythonBot.py","file_name":"PythonBot.py","file_ext":"py","file_size_in_byte":876,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"37"}
+{"seq_id":"38124690253","text":"from libraries.Corte_audio import Corte_audio\n\nimport os\nimport numpy as np\n\n\nclass Kaggle_audios(Corte_audio):\n BASE_FOLDER = \"/kaggle/input/musicnet-dataset/musicnet/musicnet/\"\n path_wav = \"_data/\"\n path_csv = \"_labels/\"\n\n BASE_INSTRUMENTS = [1, 7, 41, 42, 43, 44, 61, 69, 71, 72, 74]\n\n def __init__(self, config_time: int = 5, train: bool = True):\n super().__init__(config_time=config_time)\n group_to_use = \"test\"\n if train:\n group_to_use = \"train\"\n\n base_path = os.getcwd().split(\"musicnet\")[0] + \"musicnet\"\n base_path = \"\" # usar para cuando se trabaja desde jupyter\n self.path_wav = base_path + self.BASE_FOLDER + group_to_use + self.path_wav\n self.path_csv = base_path + self.BASE_FOLDER + group_to_use + self.path_csv\n\n print(self.path_wav)\n print(self.path_csv )\n self.file_wav = os.listdir(self.path_wav)\n\n def leer_path_data_label(self, id: int = 0):\n audio_usar = self.path_wav + self.file_wav[id]\n resource_read = audio_usar.split(\".\")[0].split(\"/\")[-1]\n label_usar = self.path_csv + resource_read + \".csv\"\n return audio_usar, label_usar, resource_read\n\n def leer_data_label(self, id: int = 0):\n audio_usar, label_usar, resource_read = self.leer_path_data_label(id)\n\n muestras_wav, instrumentos, rate = self.split_data(audio_usar, label_usar)\n return (muestras_wav, instrumentos, rate, resource_read)\n\n def __correcion_instrumentos(self, instrumentos):\n for id, usado_list in enumerate(instrumentos):\n instrumentos_usados = [0 for _ in self.BASE_INSTRUMENTS]\n for usado in usado_list:\n i = self.BASE_INSTRUMENTS.index(usado)\n instrumentos_usados[i] = 1\n instrumentos[id] = instrumentos_usados\n return instrumentos\n\n def __correccion_data(self, muestras_wav):\n c = [0 for _ in range(len(muestras_wav[-2]) - len(muestras_wav[-1]))]\n muestras_wav[-1] = np.array(muestras_wav[-1].tolist() + c)\n return muestras_wav\n\n def read_data(self, limit=None, show_info:bool = True):\n all_data = list()\n all_label = list()\n rate = None\n\n partial = len(self.file_wav)\n if limit is not None:\n if limit <= 0:\n limit = 1\n if limit > partial:\n limit = partial\n partial = len(self.file_wav[:limit])\n\n if show_info:\n print(\"\\t\\t\", \"*\" * 20, end=\"\")\n for i in range(partial):\n if show_info:\n print(\"\\t\\t\", \"*\" * 10)\n muestras_wav, instrumentos, rate, resource_read = self.leer_data_label(i)\n if show_info:\n print(\"\\t\\tReading: id:\", f\"{i}/{partial}\", \" - file:\", resource_read, \" - len before:\", len(all_data))\n # print(resource_read + \".wav\", len(muestras_wav), type(muestras_wav))\n # print(resource_read + \".csv\", len(instrumentos), type(instrumentos))\n\n all_data += self.__correccion_data(muestras_wav)\n all_label += self.__correcion_instrumentos(instrumentos)\n\n try:\n if i % 100 == 0:\n print(\"\\n\\t\", end=\"\")\n print(\".\", end=\" \")\n except:\n print()\n\n all_label = np.array(all_label)\n all_data = np.array(all_data)\n\n if show_info:\n print(\"*\"*30)\n\n return all_data, all_label, rate\n","repo_name":"wisrovi/TFM2022","sub_path":"libraries/Kaggle_audios.py","file_name":"Kaggle_audios.py","file_ext":"py","file_size_in_byte":3487,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"37"}
+{"seq_id":"842046301","text":"import RPi.GPIO as GPIO\nimport warnings\n\n#warnings.simplefilter('ignore')\n#GPIO.setmode(GPIO.BCM)\n#GPIO.cleanup()\n#warnings.resetwarnings()\n\n#変数宣言\nCENTER_LED = 13 #GPIOナンバー\nRED_LED = 26 #GPIOナンバー\nGREEN_LED = 19 #GPIOナンバー\nBLUE_LED = 6 #GPIOナンバー\n\ntry:\n GPIO.setmode(GPIO.BCM)\n #GPIO.cleanup()\n GPIO.setup(CENTER_LED ,GPIO.OUT)\n GPIO.setup(RED_LED ,GPIO.OUT)\n GPIO.setup(GREEN_LED ,GPIO.OUT)\n GPIO.setup(BLUE_LED ,GPIO.OUT)\n\n #GPIO.cleanup()\n\n GPIO.output(CENTER_LED ,GPIO.HIGH)\n GPIO.output(RED_LED ,GPIO.LOW)\n GPIO.output(GREEN_LED ,GPIO.LOW)\n GPIO.output(BLUE_LED ,GPIO.LOW)\n\nfinally:\n print('except')\n GPIO.cleanup()\n","repo_name":"ksaplabo-org/ksapDoorOpener","sub_path":"py/deleteligth.py","file_name":"deleteligth.py","file_ext":"py","file_size_in_byte":724,"program_lang":"python","lang":"ja","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"}
+{"seq_id":"74938187308","text":"import numpy as np\n\n\ndef load_dataset(file_name, delimiter=','):\n \"\"\"\n 加载CSV或TSV数据集\n 输入参数\n file_name:CSV文件名,delimiter:分隔符\n 输出参数\n data:数据集\n \"\"\"\n fr = open(file_name).readlines()\n data = np.mat([list(line.strip(\"\\n\").split(delimiter)) for line in fr])\n return data\n\n\ndef get_discrete_dataset(data_set, feat_idx, value):\n \"\"\"\n 统计给定离散特征取值的数据集\n 输入参数\n data_set:数据集,feat_idx:给定的特征序号, value:值\n 输出参数\n sub_data:数据集子集\n \"\"\"\n sub_data = data_set[np.nonzero(data_set[:, feat_idx] == value)[0], :]\n return sub_data\n\n\ndef train(data_set, feature_list, use_smoothing=False):\n \"\"\"\n 训练朴素贝叶斯模型\n 输入参数\n data_set:数据集,feature_list:特征名称列表, use_smoothing:使用拉普拉斯平滑\n 输出参数\n prob:各个特征的条件概率模型,feat_value:各个特征的取值\n \"\"\"\n n, d = data_set.shape\n feat_value = {} # 每个特征的取值\n prob = [] # 条件概率模型\n for idx in range(d):\n # 不重复的特征取值\n feat_value[feature_list[idx]] = sorted(set(data_set[:, idx].T.tolist()[0]))\n\n num_class = len(feat_value.get(feature_list[-1]))\n c_class = np.zeros(num_class)\n for c in range(num_class):\n c_class[c] = len(get_discrete_dataset(data_set, -1, feat_value.get(feature_list[-1])[c]))\n if use_smoothing:\n c_class += 1\n p_class = c_class / (n if not use_smoothing else (n + num_class))\n\n # 计算条件概率\n # 先计算各个属性的条件概率\n for idx in range(d - 1):\n num_feat_value = len(feat_value.get(feature_list[idx]))\n p = np.zeros((num_class, num_feat_value))\n for c in range(num_class):\n sub_data = get_discrete_dataset(data_set, -1, feat_value.get(feature_list[-1])[c])\n for v in range(len(feat_value.get(feature_list[idx]))):\n p[c][v] = float((1 if use_smoothing else 0) +\n len(get_discrete_dataset(sub_data, idx, feat_value.get(\n feature_list[idx])[v]))) / (\n len(sub_data) + (num_feat_value if use_smoothing else 0))\n prob.append(p)\n # 最后加上类别的概率\n prob.append(p_class)\n return prob, feat_value\n\n\ndef classify(prob, feat_value, feature_list, test_set):\n \"\"\"\n 对测试数据集进行分类\n 输入参数\n prob:各个特征的条件概率模型,feat_value:各个��征的取值,feature_list:特征名称列表, test_set:测试集\n 输出参数\n y_hat:预测输出\n \"\"\"\n num_class = len(prob[-1])\n class_value = feat_value.get(feature_list[-1])\n n, d = test_set.shape\n y_hat = []\n for i in range(n):\n likelihood = prob[-1].copy()\n for j in range(d):\n this_feat_value = feat_value.get(feature_list[j])\n feat_idx = this_feat_value.index(test_set[i, j])\n for c in range(num_class):\n likelihood[c] *= prob[j][c][feat_idx]\n y_hat.append(class_value[np.argmax(likelihood)])\n\n return y_hat\n\n\ndef main():\n # 加载数据\n data = load_dataset(\"../data/weather_nominal.csv\")\n feature_list = ['outlook', 'temperature', 'humidity', 'windy', 'play']\n # 测试数据\n # 书上的例子\n test = np.mat([['sunny', 'cool', 'high', 'TRUE', 'no']])\n test_x = test[:, 0: -1]\n test_y = test[:, -1]\n # 训练模型\n model, feat_value = train(data, feature_list)\n\n y_hat = classify(model, feat_value, feature_list, test_x)\n print(y_hat)\n print(y_hat == test_y)\n\n # 使用训练集测试\n test_x = data[:, 0: -1]\n test_y = data[:, -1].squeeze()\n y_hat = classify(model, feat_value, feature_list, test_x)\n print('天气问题结果:')\n print('训练集上的分类正确率: {:.2%}'.format(np.mean(y_hat == test_y)))\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"imcyx/UESTC-CYXBackup","sub_path":"模式识别/参考课件/086437-01/ML-Python/ch4bayes/naive_bayes_demo.py","file_name":"naive_bayes_demo.py","file_ext":"py","file_size_in_byte":4085,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"}
+{"seq_id":"9798094542","text":"from tkinter import *\nfrom tkinter import ttk\nimport os\nfrom PIL import ImageTk, Image\nimport execute\nimport functions\nimport cv2\nimport operations\nimport objeto\nimport sys\n\nclass PdiApp:\n def __init__(self, Pdi):\n self.atual = 0\n self.path = \"images/\"\n self.path_lines = \"lines_images/\"\n self.path_texture = \"images_texture/\"\n self.path_proc = \"proc_image/\"\n self.path_proc_g = \"proc_g_image/\"\n self.path_resultado_asm = \"resultado_asm/\"\n self.first_amostra = False\n self.images_lines = []\n self.formas = []\n self.texts = []\n self.proc_texts = []\n self.proc_g_texts = []\n self.forma_align = []\n self.forma_align_generalizada = []\n self.amostra_center = []\n self.euclidian_flag = False\n self.proc_flag = False\n self.proc_g_flag = False\n self.pontos_flag = False\n self.amostras_flag = False\n self.marcador = \"\"\n self.e1 = \"\"\n self.target_proc = 0\n self.proc_distancia = 0\n self.magnitude = 0\n self.norm_mean = []\n self.norm_estimate = []\n self.text_autovalores = []\n self.text_autovetores = []\n self.forma_corrigida = []\n self.form_autovetores = []\n self.form_autovalores = []\n self.formas_alinhadas = []\n self.resultado_final = []\n self.k = 0\n\n menubar = Menu(Pdi)\n Pdi.config(menu=menubar)\n Pdi.title(\"PDI - Interface Gráfica - ASM\")\n Pdi.geometry('1280x720')\n\n menu = Menu(menubar)\n menu2 = Menu(menubar)\n menu3 = Menu(menubar)\n\n menubar.add_cascade(label='Arquivo', menu=menu)\n menubar.add_cascade(label='Operações', menu=menu2)\n menubar.add_cascade(label='Busca', menu=menu3)\n\n #Funções\n def Sair():\n Pdi.destroy()\n sys.exit()\n \n def line_images():\n i=0\n for forma in self.formas:\n self.images_lines.append(\"image\" + str(i) + \".jpg\")\n i += 1\n \n def next_forma():\n if self.atual < (len(self.formas)-1):\n self.atual += 1\n self.canvas.delete(self.canvas_image)\n if self.euclidian_flag:\n show_img(0)\n show_euclidian()\n elif self.pontos_flag:\n show_img(0)\n show_pontos()\n elif self.amostras_flag:\n show_img_amostras()\n show_amostras()\n else:\n show_img(1)\n\n def back_forma():\n if self.atual > 0:\n self.atual -= 1\n self.canvas.delete(self.canvas_image)\n if self.euclidian_flag:\n show_img(0)\n show_euclidian()\n elif self.pontos_flag:\n show_img(0)\n show_pontos()\n elif self.amostras_flag:\n show_img_amostras()\n show_amostras()\n else:\n show_img(1)\n\n\n def buttons():\n self.next_button = Button(Pdi, text = \"Próxima\", command = next_forma, anchor = W, justify=CENTER, \n font=\"Arial 10 bold\")\n self.back_button = Button(Pdi, text = \"Anterior\", command = back_forma, anchor = W, justify=CENTER, \n font=\"Arial 10 bold\")\n self.next_button.configure(height=2,width = 10, activebackground = \"grey\", relief = RAISED)\n self.back_button.configure(height=2,width = 10, activebackground = \"grey\", relief = RAISED)\n self.back_window = self.canvas.create_window(650, 600, anchor=NW, window=self.back_button)\n self.next_window = self.canvas.create_window(850, 600, anchor=NW, window=self.next_button)\n \n def show_img(i):\n self.canvas.delete(self.marcador)\n img = ImageTk.PhotoImage(Image.open(self.path_lines + self.images_lines[self.atual]))\n self.label = Label(image=img)\n self.label.image = img\n self.canvas_image = self.canvas.create_image(80, 0, anchor=NW, image=self.label.image)\n self.marcador = self.canvas.create_text(300, 655,fill=\"black\",font=\"Arial 15 bold\",\n text=str(self.atual+1)+ \"/\" + str(len(self.formas)), anchor=W)\n if i == 1:\n buttons()\n\n def show_img_amostras():\n self.canvas.delete(self.marcador)\n img = ImageTk.PhotoImage(Image.open(self.path_texture + self.images_lines[self.atual]))\n self.label = Label(image=img)\n self.label.image = img\n self.canvas_image = self.canvas.create_image(80, 0, anchor=NW, image=self.label.image)\n self.marcador = self.canvas.create_text(300, 655,fill=\"black\",font=\"Arial 15 bold\",\n text=str(self.atual+1)+ \"/\" + str(len(self.formas)), anchor=W)\n \n \n\n def Plot():\n self.formas = execute.Plotar(self.path)\n line_images()\n self.canvas = Canvas(Pdi, width = 1366, height = 800, background=\"white\") \n #canvas.grid(row = 0, column = 2)\n self.canvas.pack()\n show_img(1)\n \n\n def show_euclidian():\n self.pontos_flag = False\n self.amostras_flag = False\n for text in self.texts:\n self.canvas.delete(text)\n self.label.text = \"Distância Euclidiana entre os pontos:\"\n i=0\n k = 60\n self.texts.append(self.canvas.create_text(650, 40,fill=\"black\",font=\"Arial 15 bold\",\n text=self.label.text, anchor=W))\n for distancia in self.formas[self.atual].euclidiana:\n k += 30\n self.texts.append(self.canvas.create_text(650, k,fill=\"black\",font=\"Arial 12 bold\",\n text=\"Distância ponto \" + str(i) + \" e \" + str(i+1) + \": \" + str(distancia), anchor=W))\n i+=1\n self.euclidian_flag = True\n \n def show_pontos():\n self.euclidian_flag = False\n self.amostras_flag = False\n for text in self.texts:\n self.canvas.delete(text)\n self.label.text = \"Coordenadas dos pontos da face(x,y):\"\n i=0\n k = 60\n self.texts.append(self.canvas.create_text(650, 40,fill=\"black\",font=\"Arial 15 bold\",\n text=self.label.text, anchor=W))\n for ponto in self.formas[self.atual].pontos:\n k += 30\n self.texts.append(self.canvas.create_text(650, k,fill=\"black\",font=\"Arial 12 bold\",\n text=\"Ponto \" + str(i) + \": \" + str(ponto), anchor=W))\n i+=1\n self.pontos_flag = True\n\n def show_amostras():\n self.pontos_flag = False\n self.euclidian_flag = False\n for text in self.texts:\n self.canvas.delete(text)\n self.label.text = \"Amostras de textura dos pontos(x,y):\"\n i=0\n k = 60\n self.texts.append(self.canvas.create_text(600, 40,fill=\"black\",font=\"Arial 15 bold\",\n text=self.label.text, anchor=W))\n for amostra in self.formas[self.atual].amostra:\n k += 30\n self.texts.append(self.canvas.create_text(600, k,fill=\"black\",font=\"Arial 10 bold\",\n text=\"Ponto \" + str(i) + \": \" + str(amostra), anchor=W))\n i+=1\n self.amostras_flag = True\n \n\n def do_proc():\n if self.e1.get() != \"\":\n self.target_proc = int(self.e1.get())\n #x2 = self.e2.get()\n if((self.target_proc > 0) and (self.target_proc <= len(self.formas)) and (self.target_proc != (self.atual+1))):\n self.nw.destroy()\n formas_aux = self.formas\n [distancia, forma_align] = execute.plot_procrustes(formas_aux, self.path_lines, self.atual, self.target_proc-1)\n openNewImage_proc(distancia, forma_align)\n\n else:\n Label(self.nw, text =\"Valor Inválido! Tente novamente\").pack()\n\n \n def openNewImage_proc(distancia, alinhado): \n self.nw = Toplevel(Pdi) \n self.nw.title(\"PDI - Distância Procrustes\") \n self.nw.geometry(\"1200x700\") \n #text=IntVar()\n self.canvas_proc = Canvas(self.nw, width = 1366, height = 800, background=\"white\") \n self.canvas_proc.pack()\n img = ImageTk.PhotoImage(Image.open(self.path_proc + \"image_procrustes.jpg\"))\n label = Label(image=img)\n label.image = img\n self.canvas_image_proc = self.canvas_proc.create_image(80, 0, anchor=NW, image=label.image)\n self.proc_text = self.canvas_proc.create_text(650, 40,fill=\"black\",font=\"Arial 15 bold\",\n text=\"Procrustes sobre a imagem \" + str(self.atual+1) + \" em relação a imagem \" + str(self.target_proc) + \":\", anchor=W)\n self.proc_text2 = self.canvas_proc.create_text(650, 70,fill=\"black\",font=\"Arial 12 bold\",\n text=\"Distância: \" + str(distancia), anchor=W)\n self.proc_text3 = self.canvas_proc.create_text(650, 100,fill=\"black\",font=\"Arial 12 bold\",\n text=\"Forma alinhada: \", anchor=W)\n i=0\n k=90\n for ponto in alinhado:\n k += 30\n self.proc_texts.append(self.canvas_proc.create_text(650, k,fill=\"black\",font=\"Arial 12 bold\",\n text=\"Ponto \" + str(i) + \": \" + str(ponto), anchor=W))\n i+=1\n self.proc_flag = True\n\n def openNewImage_proc_generalizada(alinhado): \n self.nw_g = Toplevel(Pdi) \n self.nw_g.title(\"PDI - Distância Procrustes Generalizada\") \n self.nw_g.geometry(\"1200x700\") \n #text=IntVar()\n self.canvas_proc_g = Canvas(self.nw_g, width = 1366, height = 800, background=\"white\") \n self.canvas_proc_g.pack()\n img = ImageTk.PhotoImage(Image.open(self.path_proc_g + \"image_procrustes_g.jpg\"))\n label = Label(image=img)\n label.image = img\n self.canvas_image_proc_g = self.canvas_proc_g.create_image(80, 0, anchor=NW, image=label.image)\n self.proc_g_text_g = self.canvas_proc_g.create_text(650, 40,fill=\"black\",font=\"Arial 15 bold\",\n text=\"Procrustes Generalizado - Forma média\", anchor=W)\n\n self.proc_g_text2 = self.canvas_proc_g.create_text(650, 70,fill=\"black\",font=\"Arial 12 bold\",\n text=\"Forma alinhada: \", anchor=W)\n i=0\n k=90\n for ponto in alinhado:\n k += 30\n self.proc_g_texts.append(self.canvas_proc_g.create_text(650, k,fill=\"black\",font=\"Arial 12 bold\",\n text=\"Ponto \" + str(i) + \": \" + str(ponto), anchor=W))\n i+=1\n self.proc_g_flag = True\n \n\n def openNewWindow_proc():\n self.nw = Toplevel(Pdi) \n self.nw.title(\"Distância Procrustes\") \n self.nw.geometry(\"400x100\") \n #text=IntVar()\n Label(self.nw, text =\"Digite o número referente da imagem a ser comparada com a atual:\").pack()\n self.e1 = Entry(self.nw)\n self.e1.pack()\n button1 = Button(self.nw, text='Calcular a distância', command=do_proc)\n button1.pack()\n \n\n def show_procrustes_generalized():\n forma_aux = objeto.Forma()\n forma_aux = self.formas\n #print(\"\\n\\nANTES\")\n #print(self.formas[0].pontos)\n self.formas_alinhadas, self.forma_align_generalizada, self.norm_estimate, self.norm_mean, self.magnitude, self.form_autovetores, self.form_autovalores = execute.plot_procrustes_generalizada(forma_aux, self.path_lines)\n #print(\"FORM_AUTOVALORES\", self.form_autovalores)\n #print(\"FORM_AUTOVETORES\", self.form_autovetores)\n #self.amostra_center = execute.amostra_forma(self.forma_align_generalizada, self.k)\n #print(\"\\n\\nDEPOIS\")\n #print(self.formas[0].pontos)\n openNewImage_proc_generalizada(self.forma_align_generalizada)\n\n def show_amostras_textura():\n if not self.first_amostra:\n #MUDAR\n self.tw = Toplevel(Pdi) \n self.tw.title(\"Amostras de textura\") \n self.tw.geometry(\"400x100\") \n Label(self.tw, text =\"Digite o valor do parâmetro da textura:\").pack()\n self.e2 = Entry(self.tw)\n self.e2.pack()\n button2 = Button(self.tw, text='Gerar amostras', command=do_texturas)\n button2.pack()\n else:\n show_amostras()\n show_img_amostras()\n\n def do_texturas():\n if self.e2.get() != \"\":\n self.k = int(self.e2.get())\n self.text_autovalores, self.text_autovetores = execute.plot_amostras(self.formas, self.path_lines, self.k)\n self.tw.destroy()\n self.first_amostra = True\n show_amostras()\n show_img_amostras()\n else:\n Label(self.tw, text =\"Valor Inválido! Tente novamente\").pack()\n\n\n def show_procrustes():\n openNewWindow_proc()\n\n def openNewImage_resultado_asm(alinhado): \n self.nw_g = Toplevel(Pdi) \n self.nw_g.title(\"PDI - Resultado do ASM\") \n self.nw_g.geometry(\"1200x700\") \n #text=IntVar()\n self.canvas_proc_g = Canvas(self.nw_g, width = 1366, height = 800, background=\"white\") \n self.canvas_proc_g.pack()\n img = ImageTk.PhotoImage(Image.open(self.path_resultado_asm + \"resultado.jpg\"))\n label = Label(image=img)\n label.image = img\n self.canvas_image_proc_g = self.canvas_proc_g.create_image(80, 0, anchor=NW, image=label.image)\n self.proc_g_text_g = self.canvas_proc_g.create_text(650, 40,fill=\"black\",font=\"Arial 15 bold\",\n text=\"Resultado ASM para a forma 1\", anchor=W)\n\n self.proc_g_text2 = self.canvas_proc_g.create_text(650, 70,fill=\"black\",font=\"Arial 12 bold\",\n text=\"Forma alinhada: \", anchor=W)\n i=0\n k=90\n for ponto in alinhado:\n k += 30\n self.proc_g_texts.append(self.canvas_proc_g.create_text(650, k,fill=\"black\",font=\"Arial 12 bold\",\n text=\"Ponto \" + str(i) + \": \" + str(ponto), anchor=W))\n i+=1\n #self.proc_g_flag = True\n \n def show_etapa_de_busca():\n self.resultado_final = execute.etapa_de_busca(self.forma_align_generalizada,self.text_autovalores, self.text_autovetores, self.k , self.norm_mean, self.magnitude, self.form_autovalores, self.form_autovetores, self.formas)\n openNewImage_resultado_asm(self.resultado_final)\n \n \n menu.add_command(label='Ler arquivo', command=Plot)\n menu.add_command(label='Sair', command=Sair)\n menu2.add_command(label='Mostrar coordenadas', command=show_pontos)\n menu2.add_command(label='Distância Euclidiana', command=show_euclidian)\n menu2.add_command(label='Distância Procrustes', command=show_procrustes)\n menu2.add_command(label='Distância Procrustes Generalizada', command=show_procrustes_generalized)\n menu2.add_command(label='Gerar Amostras de Textura', command=show_amostras_textura)\n menu3.add_command(label='Etapa de busca', command=show_etapa_de_busca)\n \n\nPdi = Tk()\nPdiApp(Pdi)\nPdi.mainloop()","repo_name":"PedroLucca/ASM","sub_path":"tk.py","file_name":"tk.py","file_ext":"py","file_size_in_byte":16046,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"}
+{"seq_id":"25873461845","text":"# Constants for birdwatch camera and server service\n\nDEFAULT_MQTT_HOST = \"192.168.1.1\"\n\nDEFAULT_TOPIC = \"birdwatch\"\nDEBUG_SUBTOPIC = \"/debug\"\nVIDEO_SUBTOPIC = \"/video\"\nIR_LEDS_SUBTOPIC = \"/ir_leds\"\nSHUTDOWN_CAMERA = \"/shutdown_camera\"\nIR_LED_PINS = [2, 3, 4, 17]\n\nVIDEO_RECORDING_SECONDS = 30\n\nMAX_SHUTDOWN_CAMERA_CONFIRMATION_SECONDS = 5\n\nLOGGING_PREFIX_CAMERA = \"Camera\"\nLOGGING_PREFIX_SERVER = \"Server\"\n\nDEFAULT_CAMERA_TMP_PATH = \"/tmp\"\nDEFAULT_SERVER_STORAGE_PATH = \"/samba/public\"\n","repo_name":"elias-lange/birdwatch","sub_path":"scripts/birdwatch_constants.py","file_name":"birdwatch_constants.py","file_ext":"py","file_size_in_byte":486,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"37"}
+{"seq_id":"18770194111","text":"# 두개의 리스트를 반복을 돌리는데, 한쪽의 리스트는 해당 인덱스를 계속 유지해야 하는 경우\n# for와 while을 사용해서 구현한다\n\na = [1,2,3]\nb = [1,2,3,4,5]\nresult = []\n\nindex = 0\nfor i in range(len(a)) : \n # b의 반복은 1회만 시행\n # 그러므로 기존의 인덱스가 보존되어야 하는 상태\n ## while의 탈출조건으로 b의 인덱스 조회보다 index가 리스트의 크기보다\n ## 작은지를 먼저 확인해야함\n while index < len(b) and a[i] >= b[index] :\n result.append(b[index])\n index += 1 \nprint(result)\n","repo_name":"ykiseong303/ProblemSolving","sub_path":"Baekjoon_python/pointing_loop.py","file_name":"pointing_loop.py","file_ext":"py","file_size_in_byte":611,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"}
+{"seq_id":"5361687368","text":"\"\"\"\ntag: 数组;哈希表;字符串;排序\n1604. 警告一小时内使用相同员工卡大于等于三次的人\nhttps://leetcode.cn/problems/alert-using-same-key-card-three-or-more-times-in-a-one-hour-period/\n\"\"\"\nfrom collections import defaultdict\n\n\nclass Solution0:\n def alertNames(self, keyName: List[str], keyTime: List[str]) -> List[str]:\n keyName_defaultDict = defaultdict(list)\n for n, t in zip(keyName, keyTime):\n keyName_defaultDict[n].append(t)\n\n def check(times: List[str]):\n times.sort()\n if len(times) < 3:\n return False\n for i in range(0, len(times) - 2):\n left, right = times[i], times[i + 2]\n left_hour, left_min = left.split(':')\n right_hour, right_min = right.split(':')\n if right_hour == left_hour or int(right_hour) - 1 == int(\n left_hour) and right_min <= left_min:\n return True\n return False\n\n res = []\n for name, times in dict(keyName_defaultDict).items():\n if check(times):\n res.append(name)\n return sorted(res)\n\n\nclass Solution1:\n \"\"\" 官解 \"\"\"\n def alertNames(self, keyName: List[str], keyTime: List[str]) -> List[str]:\n timeMap = defaultdict(list)\n for name, time in zip(keyName, keyTime):\n hour, minute = int(time[:2]), int(time[3:])\n timeMap[name].append(hour * 60 + minute)\n\n ans = []\n for name, times in timeMap.items():\n times.sort()\n if any(t2 - t1 <= 60 for t1, t2 in zip(times, times[2:])):\n ans.append(name)\n ans.sort()\n return ans\n","repo_name":"ZhangRui111/AwesomeAlgorithm","sub_path":"leetcode/medium/1604.py","file_name":"1604.py","file_ext":"py","file_size_in_byte":1726,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"}
+{"seq_id":"43227068861","text":"from flask_app import app\nfrom flask import render_template, redirect, session, request\nfrom flask_app.models.ninjas import Ninjas\nfrom flask_app.models.dojos import Dojos\n\n@app.route(\"/ninjas/\")\ndef new_ninjas():\n dojos = Dojos.get_all()\n return render_template(\"ninjas.html\", dojos = dojos)\n\n\n\n@app.route(\"/ninjas/create/\", methods = [\"POST\"])\ndef create_ninja():\n data = {\n \"first_name\" : request.form[\"first_name\"],\n \"last_name\" : request.form[\"last_name\"],\n \"age\" : request.form[\"age\"],\n \"dojo_id\" : request.form[\"dojos\"]\n }\n new_ninja_id = Ninjas.new_ninja(data)\n return redirect(\"/\")\n\n","repo_name":"debughunt/Python-full-crud","sub_path":"dojos_and_ninjas_crud/flask_app/controllers/ninjas_controller.py","file_name":"ninjas_controller.py","file_ext":"py","file_size_in_byte":638,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"}
+{"seq_id":"17082714013","text":"#!/usr/bin/env python3\n\n'''\nAn example of a Label with wrapping at 200 pixels and a left-justification of\nthe layout.\n'''\n\nimport tkinter\n\nclass Label(tkinter.Tk):\n def __init__(self):\n tkinter.Tk.__init__(self)\n self.title(\"Label\")\n self.geometry(\"200x200\")\n\n label = tkinter.Label(text=\"This is an example of a Label widget within a Window container.\")\n label.config(justify=tkinter.LEFT)\n label.config(wrap=200)\n label.pack(fill=tkinter.BOTH, expand=1)\n\nif __name__ == \"__main__\":\n application = Label()\n application.mainloop()\n","repo_name":"hasanmoudud/python-tkinter-examples","sub_path":"label.py","file_name":"label.py","file_ext":"py","file_size_in_byte":589,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"}
+{"seq_id":"9383186188","text":"#Download data from google trends and Yahoo Finance\r\nfrom earningsurprise_crawl import earningsurprise_crawl\r\nfrom sentiment_crawl import sentiment_crawl\r\n\r\nimport numpy as np\r\nimport pandas as pd\r\n#Get tickers - union of earningsurprise and sentiment\r\nsentdex=sentiment_crawl()\r\nsentdex.to_csv('sentdex.csv')\r\nearnings_surprise=earningsurprise_crawl()\r\nearnings_surprise.to_csv('earnings_surprise.csv')\r\n\r\nearnings_surprise['%Surprise']=earnings_surprise['%Surprise'].astype(float)\r\nearnings_surprise.sort_values(by='%Surprise',ascending=False,inplace=True)\r\nsentdex.drop(0,inplace=True)\r\nTicker_1=list(sentdex['Ticker'])\r\nTicker_2=list(earnings_surprise['Ticker'])\r\nTickers=list(set(Ticker_1).union(set(Ticker_2)))\r\n\r\n\r\n#download Yahoo Finance data\r\nimport pandas_datareader as web\r\n'''\r\nremove_list=[]\r\nstock_data={}\r\nfor ticker in Tickers:\r\n try:\r\n stock_data[ticker]=web.get_data_yahoo(ticker,start='2018-01-01',end='2018-02-08')\r\n except:\r\n print(ticker,'failed!')\r\n remove_list.append(ticker)\r\n\r\nstock_data=pd.concat(stock_data.values(), axis=1, keys=stock_data.keys())\r\nstock_data.to_csv('stockdata.csv')\r\n\r\nremove_list=['MHFI','NILE','LGF.A','SONO','DPS','MON','COL','CBG','ARG','GAS','TYC','CVC','MJN','PCP','EMC','JDSU','SPOT']\r\nfor item in remove_list:\r\n Tickers.remove(item)\r\n'''\r\n#Download google trends\r\n\r\nfrom pytrends.request import TrendReq\r\npytrends = TrendReq(hl='en-US',tz=360)\r\nimport time\r\nfrom random import randint\r\n\r\nGtrends=pd.DataFrame([])\r\nfor ticker in Tickers:\r\n try:\r\n pytrends.build_payload(ticker, cat=0, timeframe='today 1-m', geo='', gprop='')\r\n interest_over_time_df = pytrends.interest_over_time()\r\n time.sleep(randint(5, 10))\r\n Gtrends=pd.concat([Gtrends,interest_over_time_df[ticker]],axis=1)\r\n except:\r\n print(\"This ticker\",ticker,\"failed!\")\r\n\r\nGtrends.to_csv('Google_trends.csv')\r\n\r\n# stock_data['return']=np.log(stock_data['Adj Close']/stock_data['Adj Close'].shift(1))\r\n","repo_name":"VickieCao/MSCF-FCIII-Project","sub_path":"Trends and market data.py","file_name":"Trends and market data.py","file_ext":"py","file_size_in_byte":1985,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"37"}
+{"seq_id":"33116515569","text":"from node import Node\nfrom linkedlist import LinkedList\n\nn1 = Node(\"satu\")\nn2 = Node(\"dua\")\nn3 = Node(\"tiga\")\n\nll = LinkedList()\nll.append(n1)\nll.append(n2)\nll.append(n3)\nprint(ll)\nprint(ll.graphs())\n\n\"\"\"\n$ python list_all_nodes.py\nnodes=3\nsatu --> dua --> tiga\n\"\"\"\n","repo_name":"dudung/python","sub_path":"src/stepin/intermediate/linked_list/list_all_nodes.py","file_name":"list_all_nodes.py","file_ext":"py","file_size_in_byte":266,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"}
+{"seq_id":"24649124557","text":"import math\n\ndef starting_items():\n monkeys = []\n with open(\"inputs/11input.txt\") as f:\n info = f.read().splitlines()\n for line in info:\n line = line.strip().rstrip(\":\") \n if line.startswith(\"M\"):\n monkey = []\n elif line.startswith(\"S\"):\n stolen_items = line[16:].split(\",\")\n for stolen_item in stolen_items:\n monkey.append(stolen_item)\n monkeys.append(monkey)\n return monkeys\n\nmonkeys = starting_items()\nactivity = {0:0, 1:0, 2:0, 3:0, 4:0, 5:0, 6:0, 7:0}\n\ndef moving_items(monkeys, turns):\n\n with open(\"inputs/11input.txt\") as f:\n info = f.read().splitlines()\n item_moving = []\n\n for line in info:\n line = line.strip().rstrip(\":\")\n\n if line.startswith(\"M\"):\n i = int(line[7:])\n current_monkey = monkeys[i]\n\n if line.startswith(\"O\"):\n for j, holding_item in enumerate(current_monkey):\n operation = line[21:].split(\" \")\n if operation[1] == \"old\":\n operation[1] = holding_item\n if operation[0] == \"*\":\n holding_item = math.floor((int(holding_item) * int(operation[1])) / 3)\n monkeys[i][j] = holding_item\n if operation[0] == \"+\":\n holding_item = math.floor((int(holding_item) + int(operation[1])) / 3)\n monkeys[i][j] = holding_item\n\n if line.startswith(\"T\"):\n test = line[19:]\n\n if line.startswith(\"I\"):\n if len(current_monkey) > 0:\n activity[i] += len(current_monkey)\n while len(current_monkey) > 0:\n if current_monkey[-1] % int(test) == 0:\n item_moving.append([current_monkey.pop(), True])\n else:\n item_moving.append([current_monkey.pop(), False])\n\n if line.startswith(\"If t\"):\n k = len(item_moving) - 1\n while k >=0:\n direction = int(line[25:])\n if item_moving[k][1] is True:\n monkeys[direction].append(item_moving[k][0])\n item_moving.pop(k)\n k -=1\n\n if line.startswith(\"If f\"):\n k = len(item_moving) - 1\n while k >=0:\n direction = int(line[26:])\n if item_moving[k][1] is False:\n monkeys[direction].append(item_moving[k][0])\n item_moving.pop(k)\n k -=1\n\n if turns < 20:\n moving_items(monkeys, turns= turns + 1) \n else:\n print(activity) \n\nmoving_items(monkeys, 1)\n","repo_name":"MegginS/AdventofCode","sub_path":"day_11.py","file_name":"day_11.py","file_ext":"py","file_size_in_byte":2875,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"}
+{"seq_id":"40925184847","text":"import pytest\nimport task_9_1a\nimport sys\n\nsys.path.append(\"..\")\n\nfrom pyneng_common_functions import check_function_exists, check_function_params\n\n# Checking that the test is called via pytest ... and not python ...\nfrom _pytest.assertion.rewrite import AssertionRewritingHook\n\nif not isinstance(__loader__, AssertionRewritingHook):\n print(f\"Tests should be called using this expression:\\npytest {__file__}\\n\\n\")\n\n\ndef test_function_created():\n \"\"\"\n Checking that the function has been created\n \"\"\"\n check_function_exists(task_9_1a, \"generate_access_config\")\n\n\ndef test_function_params():\n \"\"\"\n Checking names and number of parameters\n \"\"\"\n check_function_params(\n function=task_9_1a.generate_access_config,\n param_count=3,\n param_names=[\"intf_vlan_mapping\", \"access_template\", \"psecurity\"],\n )\n\n\ndef test_function_return_value():\n \"\"\"\n Function check\n \"\"\"\n template_psecurity = [\n \"switchport port-security maximum 2\",\n \"switchport port-security violation restrict\",\n \"switchport port-security\",\n ]\n access_vlans_mapping = {\n \"FastEthernet0/12\": 10,\n \"FastEthernet0/14\": 11,\n \"FastEthernet0/16\": 17,\n }\n template_access_mode = [\n \"switchport mode access\",\n \"switchport access vlan\",\n \"switchport nonegotiate\",\n \"spanning-tree portfast\",\n \"spanning-tree bpduguard enable\",\n ]\n correct_return_value_without_psecurity = [\n \"interface FastEthernet0/12\",\n \"switchport mode access\",\n \"switchport access vlan 10\",\n \"switchport nonegotiate\",\n \"spanning-tree portfast\",\n \"spanning-tree bpduguard enable\",\n \"interface FastEthernet0/14\",\n \"switchport mode access\",\n \"switchport access vlan 11\",\n \"switchport nonegotiate\",\n \"spanning-tree portfast\",\n \"spanning-tree bpduguard enable\",\n \"interface FastEthernet0/16\",\n \"switchport mode access\",\n \"switchport access vlan 17\",\n \"switchport nonegotiate\",\n \"spanning-tree portfast\",\n \"spanning-tree bpduguard enable\",\n ]\n correct_return_value_with_psecurity = [\n \"interface FastEthernet0/12\",\n \"switchport mode access\",\n \"switchport access vlan 10\",\n \"switchport nonegotiate\",\n \"spanning-tree portfast\",\n \"spanning-tree bpduguard enable\",\n \"switchport port-security maximum 2\",\n \"switchport port-security violation restrict\",\n \"switchport port-security\",\n \"interface FastEthernet0/14\",\n \"switchport mode access\",\n \"switchport access vlan 11\",\n \"switchport nonegotiate\",\n \"spanning-tree portfast\",\n \"spanning-tree bpduguard enable\",\n \"switchport port-security maximum 2\",\n \"switchport port-security violation restrict\",\n \"switchport port-security\",\n \"interface FastEthernet0/16\",\n \"switchport mode access\",\n \"switchport access vlan 17\",\n \"switchport nonegotiate\",\n \"spanning-tree portfast\",\n \"spanning-tree bpduguard enable\",\n \"switchport port-security maximum 2\",\n \"switchport port-security violation restrict\",\n \"switchport port-security\",\n ]\n\n return_value = task_9_1a.generate_access_config(\n access_vlans_mapping, template_access_mode\n )\n assert return_value != None, \"The function returns None\"\n assert (\n type(return_value) == list\n ), f\"The function should return a list, instead it returns a {type(return_value).__name__}\"\n assert (\n correct_return_value_without_psecurity == return_value\n ), \"The function returns an incorrect value when called with psecurity == None\"\n return_value_with_psecurity = task_9_1a.generate_access_config(\n access_vlans_mapping, template_access_mode, template_psecurity\n )\n assert (\n correct_return_value_with_psecurity == return_value_with_psecurity\n ), \"The function returns an incorrect value when called with psecurity\"\n","repo_name":"natenka/pyneng-examples-exercises-en","sub_path":"exercises/09_functions/test_task_9_1a.py","file_name":"test_task_9_1a.py","file_ext":"py","file_size_in_byte":4045,"program_lang":"python","lang":"en","doc_type":"code","stars":108,"dataset":"github-code","pt":"37"}
+{"seq_id":"6260534815","text":"\nfrom leonardo.utils.settings import dotdict, get_conf_from_module, merge\nfrom leonardo.utils.widgets import (find_widget_class, get_all_widget_classes,\n get_grouped_widgets, load_widget_classes,\n get_htmltext_widget, render_region)\n\n__all__ = ('dotdict', 'get_conf_from_module', 'get_leonardo_modules',\n 'merge', 'find_widget_class', 'get_all_widget_classes',\n 'get_grouped_widgets',)\n\n\ndef is_leonardo_module(mod):\n \"\"\"returns True if is leonardo module\n \"\"\"\n\n if hasattr(mod, 'default') \\\n or hasattr(mod, 'leonardo_module_conf'):\n return True\n for key in dir(mod):\n if 'LEONARDO' in key:\n return True\n return False\n","repo_name":"django-leonardo/django-leonardo","sub_path":"leonardo/utils/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":760,"program_lang":"python","lang":"en","doc_type":"code","stars":97,"dataset":"github-code","pt":"37"}
+{"seq_id":"36825802386","text":"sh = input('Enter Hours: ')\nsr = input('Enter Rate: ')\nfh = float(sh)\nfr = float(sr)\n#print(fh, fr)\nif fh > 40:\n #print('Overtime')\n regular = fh * fr\n otp = (fh - 40) * (fr * 0.5)\n #print(regular, otp)\n xp = regular + otp\nelse :\n #print('Regular')\n xp = fh * fr\nprint('Pay:',xp)","repo_name":"colloso999/Python","sub_path":"Chapter3_ConditionalExecution/Ex_03_01/Ex_03_01.py","file_name":"Ex_03_01.py","file_ext":"py","file_size_in_byte":286,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"37"}
+{"seq_id":"33345332280","text":"# problem statement - https://leetcode.com/problems/first-missing-positive/description/\n\ndef firstMissingPositive(self, A: List[int]) -> int:\n n = len(A);\n\n # looping\n i = 0;\n\n for i in range(n):\n \n while(A[i] > 0 and A[i] <= n and A[i] != i+1):\n element = A[i];\n correctIdx = A[i]-1;\n temp = A[correctIdx];\n A[correctIdx] = element;\n A[i] = temp;\n if(element == temp):\n break;\n \n for i in range(n):\n if(A[i] != i+1):\n return i+1;\n\n return n+1;\n\n # TC - O(n). -> maximum number of swaps - n only\n # SC - O(1)","repo_name":"anshikaCSE007/DSA","sub_path":"Arrays/Hard-type/FirstMissingPos.py","file_name":"FirstMissingPos.py","file_ext":"py","file_size_in_byte":716,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"}
+{"seq_id":"73572569067","text":"from django.urls import path\nfrom . import views\n\napp_name = \"userprofile\"\n\nurlpatterns = [\n # 用户页面\n path(\"user_page/\", views.user_page, name=\"user_page\"),\n # 用户登录\n path(\"login/\", views.user_login, name=\"login\"),\n # 用户退出\n path(\"logout/\", views.user_logout, name=\"logout\"),\n # 用户注册\n path(\"register/\", views.user_register, name=\"register\"),\n # 邮箱验证\n path('activate///', views.ActivateView.as_view(), name='activate'),\n]\n","repo_name":"xieweicong/course_evaluation","sub_path":"mysite/userprofile/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":503,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"37"}
+{"seq_id":"41077941785","text":"def count_zero_grads(optimizer):\n zero_params = 0\n all_params = 0\n\n for param_group in optimizer.param_groups:\n for param in param_group['params']:\n all_params += param.numel()\n zero_params += (param.grad == 0).sum().detach().cpu().numpy()\n \n return zero_params / all_params\n","repo_name":"timothyxp/effective_pipelines","sub_path":"utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":319,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"37"}
+{"seq_id":"73455307307","text":"import os, struct\nfrom array import array as pyarray\nfrom numpy import append, array, int8, uint8, zeros\n\ndef load_mnist(dataset=\"training\", digits=None, path=None, asbytes=False,\n selection=None, return_labels=True, return_indices=False):\n \"\"\"\n Loads MNIST files into a 3D numpy array.\n\n You have to download the data separately from [MNIST]_. It is recommended\n to set the environment variable ``MNIST`` to point to the folder where you\n put the data, so that you don't have to select path. On a Linux+bash setup,\n this is done by adding the following to your ``.bashrc``::\n\n export MNIST=/path/to/mnist\n\n Parameters\n ----------\n dataset : str\n Either \"training\" or \"testing\", depending on which dataset you want to\n load.\n digits : list\n Integer list of digits to load. The entire database is loaded if set to\n ``None``. Default is ``None``.\n path : str\n Path to your MNIST datafiles. The default is ``None``, which will try\n to take the path from your environment variable ``MNIST``. The data can\n be downloaded from http://yann.lecun.com/exdb/mnist/.\n asbytes : bool\n If True, returns data as ``numpy.uint8`` in [0, 255] as opposed to\n ``numpy.float64`` in [0.0, 1.0].\n selection : slice\n Using a `slice` object, specify what subset of the dataset to load. An\n example is ``slice(0, 20, 2)``, which would load every other digit\n until--but not including--the twentieth.\n return_labels : bool\n Specify whether or not labels should be returned. This is also a speed\n performance if digits are not specified, since then the labels file\n does not need to be read at all.\n return_indicies : bool\n Specify whether or not to return the MNIST indices that were fetched.\n This is valuable only if digits is specified, because in that case it\n can be valuable to know how far\n in the database it reached.\n\n Returns\n -------\n images : ndarray\n\t\tImage data of shape ``(N, rows, cols)``, where ``N`` is the number of\n\t\timages. If neither labels nor inices are returned, then this is returned\n\t\tdirectly, and not inside a 1-sized tuple.\n labels : ndarray\n\t\tArray of size ``N`` describing the labels. Returned only if\n\t\t``return_labels`` is `True`, which is default.\n indices : ndarray\n The indices in the database that were returned.\n\n Examples\n --------\n Assuming that you have downloaded the MNIST database and set the\n environment variable ``$MNIST`` point to the folder, this will load all\n images and labels from the training set:\n\n >>> images, labels = ag.io.load_mnist('training') # doctest: +SKIP\n\n Load 100 sevens from the testing set:\n\n >>> sevens = ag.io.load_mnist('testing', digits=[7], selection=slice(0, 100), return_labels=False) # doctest: +SKIP\n\n \"\"\"\n\n # The files are assumed to have these names and should be found in 'path'\n files = {\n 'training': ('train-images-idx3-ubyte', 'train-labels-idx1-ubyte'),\n 'testing': ('t10k-images-idx3-ubyte', 't10k-labels-idx1-ubyte'),\n }\n\n if path is None:\n try:\n path = os.environ['MNIST']\n except KeyError:\n raise ValueError(\"Unspecified path requires environment variable $MNIST to be set\")\n\n try:\n images_fname = os.path.join(path, files[dataset][0])\n labels_fname = os.path.join(path, files[dataset][1])\n except KeyError:\n raise ValueError(\"Data set must be 'testing' or 'training'\")\n\n # We can skip the labels file only if digits aren't specified and labels aren't asked for\n if return_labels or digits is not None:\n flbl = open(labels_fname, 'rb')\n magic_nr, size = struct.unpack(\">II\", flbl.read(8))\n labels_raw = pyarray(\"b\", flbl.read())\n flbl.close()\n\n fimg = open(images_fname, 'rb')\n magic_nr, size, rows, cols = struct.unpack(\">IIII\", fimg.read(16))\n images_raw = pyarray(\"B\", fimg.read())\n fimg.close()\n\n if digits:\n indices = [k for k in range(size) if labels_raw[k] in digits]\n else:\n indices = range(size)\n\n if selection:\n indices = indices[selection]\n N = len(indices)\n\n images = zeros((N, rows, cols), dtype=uint8)\n\n if return_labels:\n labels = zeros((N), dtype=int8)\n for i, index in enumerate(indices):\n images[i] = array(images_raw[ indices[i]*rows*cols : (indices[i]+1)*rows*cols ]).reshape((rows, cols))\n if return_labels:\n labels[i] = labels_raw[indices[i]]\n\n if not asbytes:\n images = images.astype(float)/255.0\n\n ret = (images,)\n if return_labels:\n ret += (labels,)\n if return_indices:\n ret += (indices,)\n if len(ret) == 1:\n return ret[0] # Don't return a tuple of one\n else:\n return ret\n","repo_name":"tgy/mnist-em-bmm-gmm","sub_path":"mnist.py","file_name":"mnist.py","file_ext":"py","file_size_in_byte":4873,"program_lang":"python","lang":"en","doc_type":"code","stars":11,"dataset":"github-code","pt":"37"}
+{"seq_id":"75197547253","text":"t = int(input())\nfor tc in range(1, t + 1):\n n, m = map(int, input().split())\n arr = list(map(int, input().split()))\n min_value = int(1e9)\n max_value = 0\n\n for i in range(n - m + 1):\n temp = 0\n for j in range(i, i + m):\n temp += arr[j]\n if temp < min_value:\n min_value = temp\n\n if temp > max_value:\n max_value = temp\n\n answer = max_value - min_value\n print(f\"#{tc} {answer}\")","repo_name":"keeeeeey/baekjoon_algorithm","sub_path":"00.SSAFY_ALGORITHM/수업시간 문제풀이/구간합.py","file_name":"구간합.py","file_ext":"py","file_size_in_byte":457,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"}
+{"seq_id":"33880975504","text":"import numpy as np\nimport os\nimport h5py\nimport torch\nimport pickle\nimport nibabel as nib\nfrom datetime import datetime\n\nfrom torch.utils.data import DataLoader\n\nfrom model import SR_q_DL\nfrom utils import init_device_seed, load_args_test\nfrom dataset import TestDataset\nfrom preprocess import get_vals_vecs\n\nif __name__ == '__main__':\n args = load_args_test()\n device = init_device_seed(1234, args.cuda_visible)\n vals, vecs, dif_indexes_0, dif_indexes_lr = get_vals_vecs()\n output_dir = \"./result/\" + datetime.now().strftime(\"%Y-%m-%d %H_%M_%S\")\n\n test_list = os.listdir(\"./data/test_h5\")\n model = SR_q_DL(36, 288).to(device)\n checkpoint = torch.load('./model/model_dict', map_location=device)\n model.load_state_dict(checkpoint['state_dict'])\n model.eval()\n\n for idx, subject in enumerate(test_list):\n hf = h5py.File(f\"./data/test_h5/{subject}/data.h5\", \"r\")\n lr_vol = hf[\"lr\"]\n mask_index = hf[\"mask_index\"]\n hr_e_vol = np.zeros((288, 144+8, 174+8, 144+8), dtype=np.float32)\n\n dataset = TestDataset(lr_vol, mask_index)\n test_loader = DataLoader(dataset, batch_size=args.batch_size)\n\n for idx, (lr, mask) in enumerate(test_loader):\n lr = lr.to(device, dtype=torch.float32)\n hr_e = model(lr).detach().cpu().numpy()\n \n for batch_idx in range(mask.shape[0]):\n x, y, z = mask[batch_idx]\n hr_e_vol[:, x*2:x*2+2, y*2:y*2+2, z*2:z*2+2] = hr_e[batch_idx]\n print(f'\\r{idx}/{len(test_loader)}', end='')\n\n dwi_b0 = hf[\"hr_b0\"]\n np.clip(hr_e_vol, 0, 1, out=hr_e_vol)\n for dif in range(288):\n hr_e_vol[dif] *= dwi_b0\n\n hr_vol = np.empty((288, 145, 174, 145), dtype=np.float32)\n hr_vol[:, :-1, :, :-1] = hr_e_vol[:, 4:-4, 4:-4, 4:-4]\n hr_vol = np.transpose(hr_vol, (1, 2, 3, 0))\n\n with open(f\"./data/test_h5/{subject}/header\", \"rb\") as f:\n dwi_header = pickle.load(f)\n\n os.makedirs(f'{output_dir}/{subject}', exist_ok=True)\n ni_img = nib.Nifti1Image(hr_vol, None, header=dwi_header)\n nib.save(ni_img, f'{output_dir}/{subject}/data.nii.gz')","repo_name":"Snailpong/dwi_angular","sub_path":"test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":2182,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"}
+{"seq_id":"1359147016","text":"''' model for personalized email search\n'''\nimport torch\nimport torch.nn as nn\nfrom others.logging import logger\n\nclass ExaminationModel(nn.Module):\n ''' examination model that learns the propensity of examing each position\n '''\n g_max_relevance_pos = 10\n g_max_datetime_pos = 50\n\n def __init__(self, embedding_size, dropout=0.0):\n super(ExaminationModel, self).__init__()\n self.embedding_size = embedding_size // 2\n # response_requested, importance, is_read, flag_status, email_class\n # conversation_hash, subject_prefix_hash\n # embeddings for query discrete features\n self.relevance_pos_emb = nn.Embedding(\n self.g_max_relevance_pos + 1,\n self.embedding_size,\n padding_idx=0)\n self.datetime_pos_emb = nn.Embedding(\n self.g_max_datetime_pos + 1,\n self.embedding_size,\n padding_idx=0)\n self.mlp_layer = nn.Linear(2 * self.embedding_size, self.embedding_size)\n self.final_layer = nn.Linear(self.embedding_size, 1)\n self.dropout_layer = nn.Dropout(p=dropout)\n\n def forward(self, batch_rel_pos, batch_time_pos):\n \"\"\" batch_rel_pos: batch_size, max_doc_count(50) relevance position\n batch_time_pos: batch_size, max_doc_count(50) datetime position\n \"\"\"\n # cut position -1 to 0\n batch_rel_pos = torch.clamp(batch_rel_pos, min=0, max=self.g_max_relevance_pos)\n batch_time_pos = torch.clamp(batch_time_pos, min=0, max=self.g_max_datetime_pos)\n doc_mask = batch_rel_pos.ne(0) | batch_time_pos.ne(0)\n # documents that are shown in either window\n hidden0 = torch.cat([self.relevance_pos_emb(batch_rel_pos), \\\n self.datetime_pos_emb(batch_time_pos)], dim=-1)\n # batch_size, max_doc_count, 2*embedding_size\n hidden1 = torch.tanh(self.mlp_layer(hidden0))\n hidden1 = self.dropout_layer(hidden1)\n final_output = torch.tanh(self.final_layer(hidden1))\n final_output = final_output.squeeze(-1) * doc_mask.float()\n # batch_size, max_doc_count\n return final_output\n\n def initialize_parameters(self, logger=None):\n if logger:\n logger.info(\"ExaminationModel initialization started.\")\n # embeddings for query discrete features\n nn.init.normal_(self.relevance_pos_emb.weight)\n nn.init.normal_(self.datetime_pos_emb.weight)\n\n for name, p in self.named_parameters():\n if \"W1.weight\" in name:\n if logger:\n logger.info(\" {} ({}): Xavier normal init.\".format(\n name, \",\".join([str(x) for x in p.size()])))\n nn.init.xavier_normal_(p)\n elif \"W1.bias\" in name:\n if logger:\n logger.info(\" {} ({}): constant (0) init.\".format(\n name, \",\".join([str(x) for x in p.size()])))\n nn.init.constant_(p, 0)\n if logger:\n logger.info(\"ExaminationModel initialization finished.\")\n","repo_name":"kepingbi/EmailSearch","sub_path":"models/examination_model.py","file_name":"examination_model.py","file_ext":"py","file_size_in_byte":3047,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"}
+{"seq_id":"74426233651","text":"__author__ = 'AH0137307'\nfrom operator import attrgetter\n\n\nclass MasterUtils(object):\n\n @classmethod\n def adjust_version_instants(cls, now, from_time, to_time, documents):\n for doc in documents:\n from_instant = doc.get_version_from_instant()\n if from_instant is None:\n doc.set_version_from_instant(from_time)\n copy = documents[:]\n copy = sorted(copy, key=attrgetter('version_from_instant'))\n latest_document_version_to = copy[-1].version_to_instant()\n prev_document = None\n for doc in copy:\n if latest_document_version_to is None:\n doc.set_version_to_instant(to_time)\n if prev_document is not None:\n prev_document.set_version_to_instant(doc.get_version_from_instant())\n else:\n doc.set_version_to_instant(latest_document_version_to)\n prev_document = doc\n doc.set_correction_from_instant(now)\n doc.set_correction_to_instant(None)\n return copy\n\n @classmethod\n def map_to_unique_ids(cls, documents):\n return map(lambda x: x.get_unique_id(), documents)\n","repo_name":"tylerrbowen/sample","sub_path":"utils/master_utils.py","file_name":"master_utils.py","file_ext":"py","file_size_in_byte":1172,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"}
+{"seq_id":"72163982772","text":"r\"\"\"DDGK: Learning Graph Representations for Deep Divergence Graph Kernels.\n\n===============================\nThis is the implementation of the WWW 2019 paper,\n[DDGK: Learning Graph Representations for Deep Divergence Graph Kernels]\n(https://ai.google/research/pubs/pub47867).\n\nThe included code creates a Deep Divergence Graph Kernel as introduced in the\npaper. The implementation makes use of the data sets collected here.\n\nA distributed version of this implementation is necessary for large data sets.\n------\nIf you find Deep Divergence Graph Kernels useful in your research, we ask that\nyou cite the following paper:\n> Al-Rfou, R., Zelle, D., Perozzi, B., (2019).\n> DDGK: Learning Graph Representations for Deep Divergence Graph Kernels.\n> In _The Web Conference_.\nExample execution\n------\n# From google-research/\npython3 -m graph_embedding.ddgk.main --data_set=${ds} --working_dir=~/tmp\n\nWhere ${ds} is a data set as formatted [here]\n(https://ls11-www.cs.tu-dortmund.de/staff/morris/graphkerneldatasets)\n\"\"\"\nimport networkx as nx\nimport numpy as np\nimport tensorflow.compat.v1 as tf\nfrom tf_slim import training as contrib_training\n\n\ndef MutagHParams():\n class HParams(object):\n def __init__(self):\n # The size of node embeddings.\n self.embedding_size=4\n # The number of layers in the DNN.\n self.num_dnn_layers=4\n # The window to average for scoring loss and accuracy calculation.\n self.score_window=10\n # The adam learning rate\n self.learning_rate=.01\n # The steps for training.\n self.train_num_epochs=600\n # The steps for node mapping and scoring.\n self.score_num_epochs=600\n # The embedding similarity loss for node mapping.\n self.node_embedding_loss_coefficient=.5\n # The label preserving loss for node mapping.\n self.node_label_loss_coefficient=.5\n # The number of node labels.\n self.num_node_labels=7\n # The label preserving loss for indicent edges.\n self.incident_label_loss_coefficient=.0\n # The number of edge labels.\n self.num_edge_labels=4\n return HParams()\n\n\ndef AdjMatrixAccuracy(logits, labels):\n predictions = tf.cast(tf.greater(tf.sigmoid(logits), .5), tf.float64)\n accuracies = tf.cast(tf.equal(predictions, labels), tf.float64)\n\n return tf.reduce_mean(accuracies) # Report accuracy per edge\n\n\ndef LogitsFromProb(prob):\n return tf.log(tf.clip_by_value(prob, 1e-12, 1.0))\n\n\ndef ProbFromCounts(counts):\n return counts / tf.clip_by_value(\n tf.reduce_sum(counts, axis=1, keepdims=True), 1e-9, 1e9)\n\n\ndef AdjMatrixLoss(logits, labels):\n losses = tf.nn.sigmoid_cross_entropy_with_logits(labels=labels, logits=logits)\n return tf.reduce_mean(losses) # Report loss per edge\n\n\ndef NodesLabels(graph, num_labels):\n # labels size is (graph_num_node, 1)\n labels = [graph.node[n]['label'] for n in graph.nodes()]\n # labels size is (graph_num_node, num_labels)\n labels = tf.one_hot(labels, num_labels, dtype=tf.float64)\n return ProbFromCounts(labels)\n\n\ndef NodesEmbeddings(graph):\n # embeddings size is (graph_num_node, D) where D is the size of embeddings\n embeddings = [graph.node[n]['embedding'] for n in graph.nodes()]\n assert len(set(map(len, embeddings))) == 1, 'Some embeddings have different size'\n return tf.convert_to_tensor(embeddings, dtype=tf.float64)\n\n\ndef EdgesLabels(graph, num_labels):\n labels = np.zeros((graph.number_of_nodes(), num_labels))\n\n for i, n in enumerate(graph.nodes()):\n for u, v in graph.edges(n):\n labels[i, graph[u][v]['label']] += 1.0\n\n return ProbFromCounts(labels)\n\n\ndef NodeLabelLoss(source, source_node_prob, target, num_labels):\n # source_labels size is (source_num_node, num_labels)\n source_labels = NodesLabels(source, num_labels)\n\n # target_labels size is (target_num_node, num_labels)\n target_labels = NodesLabels(target, num_labels)\n # We take the log because the result of the multiplication is already a\n # probability.\n logits = LogitsFromProb(tf.matmul(source_node_prob, source_labels))\n losses = tf.nn.softmax_cross_entropy_with_logits_v2(\n labels=target_labels, logits=logits)\n\n # Report error per node.\n return tf.reduce_mean(losses)\n\n\ndef NodeEmbeddingLoss(source, source_node_prob, target):\n # source_embeddings size is (source_num_node, D) and is normalized\n source_embeddings = tf.linalg.l2_normalize(NodesEmbeddings(source), axis=1)\n\n # target_embeddings size is (target_num_node, D) and is normalized\n target_embeddings = tf.linalg.l2_normalize(NodesEmbeddings(target), axis=1)\n\n predicted_embeddings = tf.matmul(source_node_prob, source_embeddings)\n\n # The reduction is actually a mean\n return tf.cast(tf.losses.cosine_distance(predicted_embeddings, target_embeddings, axis=1, reduction=tf.losses.Reduction.SUM_OVER_BATCH_SIZE), tf.float64)\n\n\ndef EdgeLabelLoss(source, source_node_prob, target, num_labels):\n source_labels = EdgesLabels(source, num_labels)\n target_labels = EdgesLabels(target, num_labels)\n\n logits = LogitsFromProb(tf.matmul(source_node_prob, source_labels))\n losses = tf.nn.softmax_cross_entropy_with_logits_v2(\n labels=target_labels, logits=logits)\n\n return tf.reduce_mean(losses)\n\n\ndef Encode(source, ckpt_prefix, hparams):\n '''Encode a source graph using an auto-encoder.\n The trained parameters are saved to file'''\n tf.logging.set_verbosity(tf.logging.ERROR)\n tf.reset_default_graph()\n\n g = tf.Graph()\n session = tf.Session(graph=g)\n\n with g.as_default(), session.as_default():\n A = nx.adjacency_matrix(source, weight=None)\n\n # We want to predict the neighbours (y) for a single node (x)\n x = tf.one_hot(\n list(source.nodes()), source.number_of_nodes(), dtype=tf.float64)\n y = tf.convert_to_tensor(A.todense(), dtype=tf.float64)\n\n # Create an autoencoder for the source graph\n layer = tf.layers.dense(x, hparams.embedding_size, use_bias=False)\n for _ in range(hparams.num_dnn_layers):\n layer = tf.layers.dense(\n layer, hparams.embedding_size * 4, activation=tf.nn.tanh)\n logits = tf.layers.dense(\n layer, source.number_of_nodes(), activation=tf.nn.tanh)\n\n loss = AdjMatrixLoss(logits, y)\n\n train_op = contrib_training.create_train_op(\n loss,\n tf.train.AdamOptimizer(hparams.learning_rate),\n summarize_gradients=False)\n\n # Initialize all variables\n session.run(tf.global_variables_initializer())\n\n for _ in range(hparams.train_num_epochs):\n session.run(train_op)\n\n # Save the trained params of the autoencoder\n tf.train.Saver(tf.trainable_variables()).save(session, ckpt_prefix)\n\n\ndef Score(source, target, ckpt_prefix, hparams, return_attention=False):\n '''Calculate a divergence score of 'target' from 'source'.\n 'source' must have been encoded with Encode before.\n Both are networkx graphs, the encoding is saved to file.\n '''\n tf.logging.set_verbosity(tf.logging.ERROR)\n tf.reset_default_graph()\n\n g = tf.Graph()\n session = tf.Session(graph=g)\n\n with g.as_default(), session.as_default():\n A = nx.adjacency_matrix(target, weight=None) # Sparse adjacency matrix\n\n # We want to predict the neighbours (y) for a single node (x)\n x = tf.one_hot(\n list(target.nodes()), target.number_of_nodes(), dtype=tf.float64)\n y = tf.convert_to_tensor(A.todense(), dtype=tf.float64)\n\n # Create the structure and trainable variables for the first attention layer\n with tf.variable_scope('attention'):\n attention = tf.layers.dense(x, source.number_of_nodes(), use_bias=False)\n source_node_prob = tf.nn.softmax(attention)\n\n # Build the source graph encoder structure (same as in the Encode function)\n layer = tf.layers.dense(\n source_node_prob, hparams.embedding_size, use_bias=False)\n for _ in range(hparams.num_dnn_layers):\n layer = tf.layers.dense(\n layer, hparams.embedding_size * 4, activation=tf.nn.tanh)\n logits = tf.layers.dense(\n layer, source.number_of_nodes(), activation=tf.nn.tanh)\n\n # Create the structure and trainable variables for the reverse attention layer\n with tf.variable_scope('attention_reverse'):\n attention_reverse = tf.layers.dense(logits, target.number_of_nodes())\n target_neighbors_pred = tf.nn.sigmoid(attention_reverse)\n target_neighbors_prob = ProbFromCounts(target_neighbors_pred)\n\n loss = AdjMatrixLoss(attention_reverse, y)\n\n if hparams.node_label_loss_coefficient:\n nodes_label_loss = NodeLabelLoss(source, source_node_prob, target,\n hparams.num_node_labels)\n loss += nodes_label_loss * hparams.node_label_loss_coefficient\n\n if hparams.node_embedding_loss_coefficient:\n nodes_loss = NodeEmbeddingLoss(source, source_node_prob, target)\n loss += nodes_loss * hparams.node_embedding_loss_coefficient\n\n if hparams.incident_label_loss_coefficient:\n edge_loss = EdgeLabelLoss(source, source_node_prob, target,\n hparams.num_edge_labels)\n loss += edge_loss * hparams.incident_label_loss_coefficient\n\n vars_to_restore = tf.get_collection(\n tf.GraphKeys.GLOBAL_VARIABLES, scope='(?!attention)')\n vars_to_train = tf.get_collection(\n tf.GraphKeys.TRAINABLE_VARIABLES, scope='attention')\n\n train_op = contrib_training.create_train_op(\n loss,\n tf.train.AdamOptimizer(hparams.learning_rate),\n variables_to_train=vars_to_train,\n summarize_gradients=False)\n\n session.run(tf.global_variables_initializer())\n\n tf.train.Saver(vars_to_restore).restore(session, ckpt_prefix)\n\n losses = []\n\n for _ in range(hparams.score_num_epochs):\n losses.append(session.run([train_op, loss])[1])\n\n if return_attention:\n return losses[-hparams.score_window:], session.run(source_node_prob)\n else:\n return losses[-hparams.score_window:]\n","repo_name":"disi-unibo-nlp/ddegk","sub_path":"src/ddgk/model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":9783,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"21"}
+{"seq_id":"33841381219","text":"class Solution:\n def lengthOfLongestSubstring(self, s: str) -> int:\n char_set = set()\n l = 0\n res = 0\n\n for r in range(len(s)):\n\n # while the rightmost found character exists as a duplicate in the set, keep removing from the left until it's removed.\n # note that all elements to the left of the duplicate character will have to be removed in order to preserve the \"subsequence-ness\"\n while s[r] in char_set:\n char_set.remove(s[l])\n l += 1\n\n # this will take care of both cases of adding newly found character and adding back the duplicate character after all (one) occurence has been removed\n char_set.add(s[r])\n\n # set res to the gap between r and l\n res = max(res, r - l + 1)\n\n return res","repo_name":"rajdeep-biswas/Note-and-Code","sub_path":"Leetcode/3. Longest Substring Without Repeating Characters.py","file_name":"3. Longest Substring Without Repeating Characters.py","file_ext":"py","file_size_in_byte":835,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"}
+{"seq_id":"17018651235","text":"from ml.base import Estimator\nfrom ml.knn import KNN\nfrom ml.distances import EuclideanSq\nimport numpy as np\n\n\nclass KMeans(Estimator):\n def __init__(self, k: int, distance=EuclideanSq(), max_iter=300, tol=1e-4, *args, **kwargs):\n super().__init__(*args, **kwargs)\n self.k = k\n self.distance = distance\n self.max_iter = max_iter\n self.tol = tol\n self.knn = KNN(1, distance, 'vote', *args, **kwargs)\n self.means = None\n\n def fit(self, x: np.ndarray, _=None):\n feat_size = x.shape[-1]\n self.means = x[np.random.permutation(x.shape[0])[:self.k]]\n prev_means = self.means\n\n assignment = [[] for _ in range(self.k)]\n for i in range(self.max_iter):\n x_clusters = self.assign_clusters(x)\n for j, c in enumerate(x_clusters):\n assignment[c].append(x[j])\n self.means = np.asarray([np.mean(v, axis=0) for v in assignment])\n\n if np.linalg.norm(self.means - prev_means) <= self.tol:\n break\n\n def assign_clusters(self, x: np.ndarray):\n self.knn.fit(self.means, np.asarray([j for j in range(self.k)]))\n return self.knn.predict(x)\n\n def predict(self, x: np.ndarray) -> np.ndarray:\n return self.assign_clusters(x)\n\n\ndef test():\n from sklearn.cluster import KMeans as Standard\n\n x = np.random.rand(50, 16) * 10\n kmeans = KMeans(k=4, max_iter=100, random_state=42)\n standard = Standard(n_clusters=4, init='random', max_iter=100, random_state=42)\n\n kmeans.fit(x)\n standard.fit(x)\n\n x_test = np.random.rand(10, 16)\n assert np.allclose(kmeans.predict(x_test), standard.predict(x_test))\n","repo_name":"tjysdsg/ml","sub_path":"ml/kmeans.py","file_name":"kmeans.py","file_ext":"py","file_size_in_byte":1679,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"}
+{"seq_id":"24019422052","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.db import models, migrations\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('api', '0031_auto_20150618_1400'),\n ]\n\n operations = [\n migrations.CreateModel(\n name='RecommendedTell',\n fields=[\n ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),\n ('type', models.CharField(default=b'Hobby', max_length=255, verbose_name='Type', db_index=True, choices=[(b'Hobby', b'Hobby'), (b'Mind', b'Mind'), (b'Passion', b'Passion')])),\n ('contents', models.TextField(verbose_name='Contents', db_index=True)),\n ('photo', models.CharField(max_length=255, verbose_name='Photo', db_index=True)),\n ('inserted_at', models.DateTimeField(auto_now_add=True, verbose_name='Inserted At', db_index=True)),\n ('updated_at', models.DateTimeField(auto_now=True, verbose_name='Updated At', db_index=True)),\n ],\n options={\n 'ordering': ('-id',),\n 'db_table': 'api_recommended_tells',\n 'verbose_name': 'Recommended Tell',\n 'verbose_name_plural': 'Recommended Tells',\n },\n ),\n ]\n","repo_name":"mahendrakalkura/tellecast","sub_path":"api/migrations/0032_recommendedtell.py","file_name":"0032_recommendedtell.py","file_ext":"py","file_size_in_byte":1321,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"}
+{"seq_id":"18750413968","text":"#!/usr/bin/env python3\n# https://leetcode.com/problems/combination-sum/\n\nimport unittest\nfrom typing import List\n\n\nclass Solution:\n # pylint: disable=R0913\n def __combinationSum(self, candidates, target, path, total, index, combos):\n if total == target:\n combos.append(path.copy())\n return\n inner = path.copy()\n partial = 0\n while partial <= target - total and index < len(candidates):\n self.__combinationSum(\n candidates, target, inner, total + partial, index + 1, combos\n )\n inner.append(candidates[index])\n partial += candidates[index]\n\n def combinationSum(\n self, candidates: List[int], target: int\n ) -> List[List[int]]:\n combos: List[List[int]] = []\n self.__combinationSum(candidates, target, [], 0, 0, combos)\n return combos\n\n\nclass TestCode(unittest.TestCase):\n @staticmethod\n def cmp_to_key(mycmp): # pragma: no cover\n class K:\n def __init__(self, obj, *_):\n self.obj = obj\n\n def __lt__(self, other):\n return mycmp(self.obj, other.obj) < 0\n\n def __gt__(self, other):\n return mycmp(self.obj, other.obj) > 0\n\n def __eq__(self, other):\n return mycmp(self.obj, other.obj) == 0\n\n def __le__(self, other):\n return mycmp(self.obj, other.obj) <= 0\n\n def __ge__(self, other):\n return mycmp(self.obj, other.obj) >= 0\n\n def __ne__(self, other):\n return mycmp(self.obj, other.obj) != 0\n\n return K\n\n @staticmethod\n def deep_comparator(list1, list2): # pragma: no cover\n if len(list1) < len(list2):\n return -1\n if len(list1) > len(list2):\n return 1\n for list1i, list2i in zip(list1, list2):\n if list1i < list2i:\n return -1\n if list1i > list2i:\n return 1\n return 0\n\n def test_example(self):\n candidates = [2, 3, 6, 7]\n expected = [[7], [2, 2, 3]]\n combos = Solution().combinationSum(candidates, 7)\n for listed in combos:\n listed.sort()\n combos = sorted(\n combos, key=TestCode.cmp_to_key(TestCode.deep_comparator)\n )\n self.assertEqual(len(expected), len(combos))\n i = 0\n while i < len(expected):\n self.assertEqual(len(expected[i]), len(combos[i]))\n j = 0\n while j < len(expected[i]):\n self.assertEqual(expected[i][j], int(combos[i][j]))\n j += 1\n i += 1\n","repo_name":"altermarkive/training","sub_path":"algorithms/code/leetcode/lc039_combination_sum/lc039_combination_sum.py","file_name":"lc039_combination_sum.py","file_ext":"py","file_size_in_byte":2669,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"21"}
+{"seq_id":"70113538932","text":"import os, os.path as osp\nimport sys\nimport random\nimport numpy as np\nimport torch\nimport copy\nimport trimesh\n\nfrom airobot import log_info, log_warn, log_debug, log_critical\n\nfrom rndf_robot.utils import util\nfrom rndf_robot.opt.optimizer import OccNetOptimizer\n\n\ndef infer_relation_intersection(mc_vis, parent_optimizer, child_optimizer, parent_target_desc, child_target_desc, \n parent_pcd, child_pcd, parent_query_points, child_query_points, opt_visualize=False, visualize=False,\n *args, **kwargs):\n out_parent_feat = parent_optimizer.optimize_transform_implicit(parent_pcd, ee=True, return_score_list=True, return_final_desc=True, target_act_hat=parent_target_desc, visualize=opt_visualize)\n parent_feat_pose_mats, best_parent_idx, desc_dist_parent, desc_parent = out_parent_feat\n\n parent_feat_pose_mat = parent_feat_pose_mats[best_parent_idx]\n child_query_points = util.transform_pcd(parent_query_points, parent_feat_pose_mats[best_parent_idx])\n child_optimizer.set_query_points(child_query_points)\n\n # now we want to do the same thing relative to the child objects\n out_child_feat = child_optimizer.optimize_transform_implicit(child_pcd, ee=False, return_score_list=True, return_final_desc=True, target_act_hat=child_target_desc, visualize=opt_visualize)\n child_feat_pose_mats, best_child_idx, desc_dist_child, desc_child = out_child_feat\n\n child2parent_feat_pose_mat = child_feat_pose_mats[best_child_idx]\n parent2child_feat_pose_mat = np.linalg.inv(child2parent_feat_pose_mat)\n child_feat_pose_mat = np.matmul(parent2child_feat_pose_mat, parent_feat_pose_mat)\n transformed_child_feat_pose_mat = np.matmul(child2parent_feat_pose_mat, child_feat_pose_mat)\n\n if visualize:\n util.meshcat_frame_show(mc_vis, 'scene/parent_feat_pose', parent_feat_pose_mat)\n util.meshcat_frame_show(mc_vis, 'scene/child_feat_pose', child_feat_pose_mat)\n util.meshcat_frame_show(mc_vis, 'scene/transformed_child_feat_pose', transformed_child_feat_pose_mat)\n \n # finally, the relative pose we should execute is here\n relative_transformation = child_feat_pose_mats[best_child_idx]\n return relative_transformation\n\n\ndef filter_parent_child_pcd(pf_pcd, cf_pcd):\n # filter out some noisy points\n\n # pf_inliers = np.where(pf_pcd[:, 2] > 0.025)[0]\n # pf_pcd = pf_pcd[pf_inliers]\n\n # pf_mean = np.mean(pf_pcd, axis=0)\n # pf_inliers = np.where(np.linalg.norm(pf_pcd[:, :-1] - pf_mean[:-1], 2, 1) < 0.2)[0]\n # pf_pcd = pf_pcd[pf_inliers]\n\n pf_mean = np.mean(pf_pcd, axis=0)\n pf_inliers = np.where(np.linalg.norm(pf_pcd - pf_mean, 2, 1) < 0.2)[0]\n pf_pcd = pf_pcd[pf_inliers]\n\n cf_mean = np.mean(cf_pcd, axis=0)\n cf_inliers = np.where(np.linalg.norm(cf_pcd - cf_mean, 2, 1) < 0.2)[0]\n # cf_inliers = np.where(np.linalg.norm(cf_pcd - cf_mean, 2, 1) < 0.1)[0]\n cf_pcd = cf_pcd[cf_inliers]\n return pf_pcd, cf_pcd\n\n\ndef keypoint_offset(cf_pcd, offset=0.025, type='bottom'):\n assert type in ['bottom', 'top', 'mean'], 'Invalid keypoint offset type!'\n keypoint_trans = np.mean(cf_pcd, axis=0)\n\n # this assumes top/bottom are aligned with the z-axis! \n if type == 'bottom':\n keypoint_trans[2] = np.min(cf_pcd[:, 2])\n keypoint_trans[2] -= offset\n elif type == 'top':\n keypoint_trans[2] = np.max(cf_pcd[:, 2])\n keypoint_trans[2] += offset\n\n return keypoint_trans\n\n\ndef create_target_descriptors(parent_model, child_model, pc_demo_dict, target_desc_fname, \n cfg, query_scale=0.025, opt_iterations=650, \n scale_pcds=False, manual_kp_adjustment=False,\n alignment_rounds=3, target_rounds=1, pc_reference='parent', \n skip_alignment=False, n_demos='all', manual_target_idx=-1,\n add_noise=False, interaction_pt_noise_std=0.01, \n use_keypoint_offset=False, keypoint_offset_params=None,\n visualize=False, mc_vis=None):\n \"\"\"\n Create a .npz file containing information about a relational multi-object\n task. Will create target pose descriptors for parent object and child\n object, and save the set of query points that should be used at test \n time to infer poses of local part geometry for both parent and child\n object\n\n Args:\n parent_model (VNNOccNet): Parent NDF model, with weights loaded\n child_model (VNNOccNet): Child NDF model, with weights loaded\n pc_demo_dict (dict): Keys: ['parent', 'child'], values are dicts. Lower-level\n dicts with keys: ['demo_final_pcds'], values are final point clouds from\n the demonstrations for parent/child object, respectively\n target_desc_fname (str): Name of file to save descriptors to\n cfg (yacs.CfgNode): Contains config params for OccNetOptimizers\n query_scale (float): Scale of Gaussian distributed query points at origin\n opt_iterations (int): Number of OccNetOptimizer iterations to use\n scale_pcds (bool): If True, apply a larger scaling to the point clouds in the\n demos to encourage some intersections between the bounding boxes\n manual_kp_adjustment (bool): If True, will allow for manual keypoint position \n adjustment\n alignment_rounds (int): Number of full rounds to go through all the demos, for \n a randomly selected target demo\n target_rounds (int): Number of times to select a random target demo\n pc_reference (str): 'parent' or 'child', which object to use in alignment\n skip_alignment (bool): If True, don't perform alignment of the orientations,\n just use the estimated positions using our intersection heuristic\n n_demos (str or int): If 'all' use all, else use the integer number\n interaction_pt_noise_std (float): Standard deviation of noise to add for \n noisy keypoint position experiment\n use_keypoint_offset (bool): If True, don't use the bounding box intersection method.\n Instead, use a manually specified offset relative to a point on the object\n keypoint_offset_params (dict): Contains keyword arguments for passing to the\n function which initializes the keypoint position using an offset from one \n of the points on the object.\n visualize (bool): If True, use meshcat to visualize what's going on while building\n target descriptors. meshcat.Visualizer handler must be passed in if using visualization\n mc_vis (meshcat.Visualzer): meshcat handler\n \"\"\"\n assert not (visualize and (mc_vis is None)), 'mc_vis cannot be None if visualize=True'\n\n target_desc_folder = '/'.join(target_desc_fname.split('/')[:-2])\n if osp.exists(target_desc_fname):\n import datetime\n import shutil\n nowstr = datetime.datetime.now().strftime(\"%m-%d-%Y_%H-%M-%S\")\n # save a copy of the current target desc before we overwrite it\n backup_desc_folder = '/'.join(target_desc_fname.split('/')[:-1])\n backup_desc_folder = osp.join(backup_desc_folder, nowstr) \n util.safe_makedirs(backup_desc_folder)\n log_warn(f'\\n\\n[create_target_descriptors] \\nFilename: {target_desc_fname} already exists! \\n\\nSaving to folder: {backup_desc_folder} as a backup before overwriting\\n\\n')\n\n backup_desc_fname = osp.join(backup_desc_folder, target_desc_fname.split('/')[-1])\n shutil.copy(target_desc_fname, backup_desc_fname) \n\n assert osp.exists(backup_desc_fname), f'Something went wrong with backing up the descriptors to path: {backup_desc_fname}!'\n\n # initialize set of world frame query points with specified variance\n parent_query_points = np.random.normal(scale=query_scale, size=(500, 3))\n child_query_points = copy.deepcopy(parent_query_points)\n\n # create optimizers that will be used for alignment\n parent_optimizer = OccNetOptimizer(\n parent_model,\n query_pts=parent_query_points,\n query_pts_real_shape=parent_query_points,\n opt_iterations=opt_iterations,\n cfg=cfg.OPTIMIZER)\n\n child_optimizer = OccNetOptimizer(\n child_model,\n query_pts=child_query_points,\n query_pts_real_shape=child_query_points,\n opt_iterations=opt_iterations,\n cfg=cfg.OPTIMIZER)\n\n pc_demo_dict['parent']['query_pts'] = []\n pc_demo_dict['child']['query_pts'] = []\n\n # one heuristic we used for creating keypoint labels is to estimate where\n # the bounding boxes of the two shapes intersect\n # another is to use a fixed offset away from a known task-specific point,\n # such as the bottom of the bottle\n # here, we are running this for each demo to get a candidate keypoint\n\n # prepare list of keypoint translations\n trans_list = []\n valid_targets = []\n\n visualize_bounding_box_intersection = False # can set to true for extra visualizations\n n_demos = len(pc_demo_dict['parent']['demo_final_pcds']) if n_demos == 'all' else n_demos\n demo_idxs = np.random.permutation(len(pc_demo_dict['parent']['demo_final_pcds']))[:n_demos]\n for i in range(len(pc_demo_dict['parent']['demo_final_pcds'])):\n pf_pcd = pc_demo_dict['parent']['demo_final_pcds'][i]\n cf_pcd = pc_demo_dict['child']['demo_final_pcds'][i]\n\n # # scale these up a little bit\n if scale_pcds:\n pf_mean, cf_mean = np.mean(pf_pcd, axis=0), np.mean(cf_pcd, axis=0)\n pf_pcd -= pf_mean; pf_pcd *= 1.25; pf_pcd += pf_mean\n cf_pcd -= cf_mean; cf_pcd *= 1.25; cf_pcd += cf_mean\n\n # get rid of some outlier artifacts that sometimes show up\n pf_pcd, cf_pcd = filter_parent_child_pcd(pf_pcd, cf_pcd)\n\n if visualize:\n util.meshcat_pcd_show(mc_vis, cf_pcd, color=[0, 0, 255], name=f'scene/{i}/final_pcds_child_{i}')\n util.meshcat_pcd_show(mc_vis, pf_pcd, color=[255, 0, 0], name=f'scene/{i}/final_pcds_parent_{i}')\n\n if len(valid_targets) > 0:\n print('Got at least one valid target, continuing')\n continue\n\n # get bounding boxes and estimate a point where they intersect\n pbb = trimesh.PointCloud(pf_pcd).bounding_box_oriented\n cbb = trimesh.PointCloud(cf_pcd).bounding_box_oriented\n\n pbb_pts = pbb.sample_volume(1000)\n cbb_pts = cbb.sample_volume(1000)\n\n pbb_mask = pbb.contains(cbb_pts)\n cbb_mask = cbb.contains(pbb_pts)\n\n bb_pts = np.concatenate([pbb_pts[cbb_mask], cbb_pts[pbb_mask]], axis=0)\n\n if bb_pts.shape[0] > 4:\n fine_grained_bb = trimesh.PointCloud(bb_pts).bounding_box_oriented.to_mesh()\n\n intersection_trans = fine_grained_bb.centroid\n\n interaction_noise = None\n if add_noise:\n interaction_noise = np.random.normal(scale=interaction_pt_noise_std)\n log_warn(f'Adding interaction noise! Value: {interaction_noise}')\n intersection_trans = copy.deepcopy(intersection_trans) + interaction_noise\n\n if use_keypoint_offset:\n intersection_trans = keypoint_offset(cf_pcd, **keypoint_offset_params)\n\n if visualize_bounding_box_intersection:\n util.meshcat_pcd_show(mc_vis, bb_pts, color=[0, 255, 0], name=f'scene/{i}/final_pcds_bb_pts_{i}')\n util.meshcat_pcd_show(mc_vis, pf_pcd, color=[255, 0, 0], name=f'scene/{i}/final_pcds_parent_{i}')\n util.meshcat_pcd_show(mc_vis, cf_pcd, color=[0, 0, 255], name=f'scene/{i}/final_pcds_child_{i}')\n util.meshcat_trimesh_show(mc_vis, f'scene/{i}/final_bb_pts_bb_{i}', fine_grained_bb, opacity=0.4)\n\n sph = trimesh.creation.uv_sphere(0.005).apply_translation(intersection_trans)\n util.meshcat_trimesh_show(mc_vis, f'scene/{i}/intersection_trans', sph, (255, 0, 0))\n\n delta = 0.0025\n if manual_kp_adjustment:\n log_info(f'Manual keypoint adjustment for reference query points')\n kp_trans = copy.deepcopy(intersection_trans)\n kp_trans_original = copy.deepcopy(kp_trans)\n while True:\n adj_key = input('Press \"w/s to adjust x, a/d to adjust y, and q/e to adjust z\\nPress z to restart\\nPress x to exit \\n')\n\n if adj_key not in ['w', 's', 'a', 'd', 'q', 'e', 'z', 'x']:\n log_info(f'Unrecognized key: {adj_key}')\n continue\n\n if adj_key == 'x':\n break\n \n if adj_key == 'z':\n kp_trans = copy.deepcopy(kp_trans_original)\n \n adj_x = 0.0 if adj_key not in ['w', 's'] else delta\n adj_x = -1.0 * adj_x if adj_key == 'w' else adj_x\n\n adj_y = 0.0 if adj_key not in ['a', 'd'] else delta\n adj_y = -1.0 * adj_y if adj_key == 'a' else adj_y\n\n adj_z = 0.0 if adj_key not in ['q', 'e'] else delta\n adj_z = -1.0 * adj_z if adj_key == 'q' else adj_z\n \n adj_vec = np.array([adj_x, adj_y, adj_z])\n\n kp_trans = kp_trans + adj_vec\n sph = trimesh.creation.uv_sphere(0.005).apply_translation(kp_trans)\n util.meshcat_trimesh_show(mc_vis, f'scene/{i}/keypoint_trans', sph, (0, 255, 0))\n \n intersection_trans = kp_trans\n\n trans_list.append(intersection_trans)\n\n # translate the query points to this position\n demo_parent_qp = parent_query_points + intersection_trans\n demo_child_qp = child_query_points + intersection_trans\n\n pc_demo_dict['parent']['query_pts'].append(demo_parent_qp)\n pc_demo_dict['child']['query_pts'].append(demo_child_qp)\n\n valid_targets.append(i)\n\n if visualize_bounding_box_intersection:\n util.meshcat_pcd_show(mc_vis, demo_parent_qp, color=[255, 255, 0], name=f'scene/{i}/translate_parent_qp_{i}')\n util.meshcat_pcd_show(mc_vis, demo_child_qp, color=[0, 255, 255], name=f'scene/{i}/translate_child_qp_{i}')\n\n else:\n pc_demo_dict['parent']['query_pts'].append(None)\n pc_demo_dict['child']['query_pts'].append(None)\n trans_list.append(None)\n log_warn(f'No bounding box intersection for demo number: {i}')\n\n if visualize:\n parent_optimizer.setup_meshcat(mc_vis)\n child_optimizer.setup_meshcat(mc_vis)\n parent_target_desc_list = []\n child_target_desc_list = []\n\n if add_noise:\n valid_targets = [random.sample(valid_targets, 1)[0]] # cycle through the demos for the noise experiment\n else:\n if manual_target_idx < 0:\n valid_targets = [0] # Just use the first demonstration (arbitray choice!)\n else:\n assert manual_target_idx < len(valid_targets), 'Manually specified demonstration index too large for number of (valid) demos!'\n valid_targets = [manual_target_idx]\n\n parent_descriptor_variance_list = []\n child_descriptor_variance_list = []\n\n # loop through all as the targets\n for target_idx in valid_targets:\n # target_idx = valid_targets[-2]\n parent_pcd_target = pc_demo_dict['parent']['demo_final_pcds'][target_idx]\n child_pcd_target = pc_demo_dict['child']['demo_final_pcds'][target_idx]\n\n #########################################################################\n\n parent_pcd_target, child_pcd_target = filter_parent_child_pcd(parent_pcd_target, child_pcd_target)\n\n #########################################################################\n\n # qp == query points\n # set up torch tensors with query points and initial positions\n qp_target = torch.from_numpy(pc_demo_dict['parent']['query_pts'][target_idx]).float().reshape((1, -1, 3)).cuda()\n qp_target_frame_pose = np.eye(4); qp_target_frame_pose[:-1, -1] = trans_list[target_idx]\n qp_target_np = qp_target.detach().cpu().numpy().reshape(-1, 3)\n\n qp_target_c = torch.from_numpy(pc_demo_dict['child']['query_pts'][target_idx]).float().reshape((1, -1, 3)).cuda()\n qp_target_c_frame_pose = np.eye(4); qp_target_c_frame_pose[:-1, -1] = trans_list[target_idx]\n qp_target_c_np = qp_target_c.detach().cpu().numpy().reshape(-1, 3)\n\n # get target descriptors that correspond to these query points\n parent_target_desc = parent_optimizer.get_pose_descriptor(parent_pcd_target, qp_target_frame_pose)\n parent_target_desc_orig = parent_target_desc.clone().detach()\n\n child_target_desc = child_optimizer.get_pose_descriptor(child_pcd_target, qp_target_c_frame_pose)\n child_target_desc_orig = child_target_desc.clone().detach()\n\n if skip_alignment:\n parent_target_desc_list.append(parent_target_desc.detach())\n child_target_desc_list.append(child_target_desc.detach())\n log_warn('\\n\\nSkipping alignment between demos! Just using the pose descriptor interaction point\\n\\n')\n continue\n\n sz = parent_target_desc_orig.size()\n\n # prepare list of final descriptors to average (updates on each iter based on if new loss is better than old loss)\n parent_last_outdesc = [None] * len(pc_demo_dict['parent']['demo_final_pcds'])\n parent_last_outloss = [np.inf] * len(pc_demo_dict['parent']['demo_final_pcds'])\n\n child_last_outdesc = [None] * len(pc_demo_dict['child']['demo_final_pcds'])\n child_last_outloss = [np.inf] * len(pc_demo_dict['child']['demo_final_pcds'])\n \n if visualize:\n util.meshcat_pcd_show(mc_vis, parent_pcd_target, color=[255, 0, 0], name=f'scene/{target_idx}/final_pcds_parent_{target_idx}')\n util.meshcat_pcd_show(mc_vis, child_pcd_target, color=[0, 0, 255], name=f'scene/{target_idx}/final_pcds_child_{target_idx}')\n util.meshcat_pcd_show(mc_vis, qp_target_np, color=[0, 0, 0], name='scene/qp_target')\n util.meshcat_frame_show(mc_vis, 'scene/qp_target_frame', qp_target_frame_pose)\n util.meshcat_pcd_show(mc_vis, qp_target_c_np, color=[50, 0, 50], name='scene/qp_target_c')\n util.meshcat_frame_show(mc_vis, 'scene/qp_target_c_frame', qp_target_c_frame_pose)\n\n if n_demos == 1:\n parent_target_desc_list.append(parent_target_desc)\n child_target_desc_list.append(child_target_desc)\n log_warn('\\n\\nUsing just 1 demo! Breaking before alignment!\\n\\n')\n break\n\n if skip_alignment:\n parent_target_desc_list = parent_target_desc_list[:n_demos]\n child_target_desc_list = child_target_desc_list[:n_demos]\n log_warn('\\n\\nskip_alignment set to True! Breaking before alignment!\\n\\n')\n break\n\n for it in range(alignment_rounds):\n \n for idx in demo_idxs:\n print(f'\\n\\nAligning demo number: {idx} to target demo number: {target_idx}\\n\\n')\n parent_pcd = pc_demo_dict['parent']['demo_final_pcds'][idx]\n child_pcd = pc_demo_dict['child']['demo_final_pcds'][idx]\n\n parent_pcd, child_pcd = filter_parent_child_pcd(parent_pcd, child_pcd)\n\n if idx == target_idx:\n if it < 1:\n parent_last_outdesc[idx] = parent_target_desc_orig\n child_last_outdesc[idx] = child_target_desc_orig\n continue\n else:\n print('Updating original target idx')\n pass\n\n if pc_reference == 'parent':\n # optimize each\n parent_out_tf, parent_out_best_idx, parent_out_losses, parent_out_descs = parent_optimizer.optimize_transform_implicit(parent_pcd, target_act_hat=parent_target_desc, return_score_list=True, return_final_desc=True, visualize=visualize)\n\n if parent_out_losses[parent_out_best_idx] < parent_last_outloss[idx]:\n print(f'Parent Target: {target_idx}, Updating best loss {idx}: last: {parent_last_outloss[idx]:.5f}, new: {parent_out_losses[parent_out_best_idx]:.5f}')\n parent_last_outloss[idx] = parent_out_losses[parent_out_best_idx]\n parent_last_outdesc[idx] = parent_out_descs[parent_out_best_idx].view(sz)\n\n parent_out_tf_best = parent_out_tf[parent_out_best_idx]\n parent_out_qp = util.transform_pcd(parent_query_points, parent_out_tf_best)\n\n child_out_desc = child_optimizer.get_pose_descriptor(child_pcd, parent_out_tf_best).detach()\n child_last_outdesc[idx] = child_out_desc\n\n out_child_sanity = child_optimizer.optimize_transform_implicit(child_pcd, target_act_hat=child_target_desc, return_score_list=True, return_final_desc=True, visualize=visualize)\n\n if visualize:\n util.meshcat_frame_show(mc_vis, f'scene/out_{idx}_tf_best_parent', parent_out_tf_best)\n util.meshcat_pcd_show(mc_vis, parent_out_qp, color=[255, 0, 255], name=f'scene/out_{idx}_qp_parent')\n else:\n # optimize each\n child_out_tf, child_out_best_idx, child_out_losses, child_out_descs = child_optimizer.optimize_transform_implicit(child_pcd, target_act_hat=child_target_desc, return_score_list=True, return_final_desc=True, visualize=visualize)\n\n if child_out_losses[child_out_best_idx] < child_last_outloss[idx]:\n print(f'Parent Target: {target_idx}, Updating best loss {idx}: last: {child_last_outloss[idx]:.5f}, new: {child_out_losses[child_out_best_idx]:.5f}')\n child_last_outloss[idx] = child_out_losses[child_out_best_idx]\n child_last_outdesc[idx] = child_out_descs[child_out_best_idx].view(sz)\n\n child_out_tf_best = child_out_tf[child_out_best_idx]\n child_out_qp = util.transform_pcd(child_query_points, child_out_tf_best)\n\n parent_out_desc = parent_optimizer.get_pose_descriptor(parent_pcd, child_out_tf_best).detach()\n parent_last_outdesc[idx] = parent_out_desc\n\n out_parent_sanity = parent_optimizer.optimize_transform_implicit(parent_pcd, target_act_hat=parent_target_desc, return_score_list=True, return_final_desc=True, visualize=visualize)\n\n if visualize:\n util.meshcat_frame_show(mc_vis, f'scene/out_{idx}_tf_best_child', child_out_tf_best)\n util.meshcat_pcd_show(mc_vis, child_out_qp, color=[255, 0, 255], name=f'scene/out_{idx}_qp_child')\n\n # get new target descriptor\n if it < 1:\n parent_target_stack = torch.stack([parent_target_desc, parent_target_desc_orig] + parent_last_outdesc, 0)\n child_target_stack = torch.stack([child_target_desc, child_target_desc_orig] + child_last_outdesc, 0)\n else:\n parent_target_stack = torch.stack([parent_target_desc] + parent_last_outdesc, 0)\n child_target_stack = torch.stack([child_target_desc] + child_last_outdesc, 0)\n\n parent_target_desc = torch.mean(parent_target_stack, 0).detach()\n child_target_desc = torch.mean(child_target_stack, 0).detach()\n\n parent_var = torch.var(parent_target_stack, 0).mean().detach().item()\n child_var = torch.var(child_target_stack, 0).mean().detach().item()\n parent_descriptor_variance_list.append(parent_var)\n child_descriptor_variance_list.append(child_var)\n\n parent_target_desc_list.append(parent_target_desc)\n child_target_desc_list.append(child_target_desc)\n \n # take an average over the full set to get the final target descriptors for parent and child objects\n parent_overall_target_desc = torch.mean(torch.stack(parent_target_desc_list, 0), 0)\n child_overall_target_desc = torch.mean(torch.stack(child_target_desc_list, 0), 0)\n\n parent_descriptor_variance = np.asarray(parent_descriptor_variance_list)\n child_descriptor_variance = np.asarray(child_descriptor_variance_list)\n\n print(f'Done! Saving to {target_desc_fname}')\n np.savez(\n target_desc_fname,\n parent_overall_target_desc=parent_overall_target_desc.detach().cpu().numpy(),\n child_overall_target_desc=child_overall_target_desc.detach().cpu().numpy(),\n parent_query_points=parent_query_points,\n parent_descriptor_variance=parent_descriptor_variance,\n child_descriptor_variance=child_descriptor_variance,\n add_noise=add_noise,\n interaction_pt_noise_std=interaction_pt_noise_std,\n interaction_pt_noise_value=interaction_noise\n )\n","repo_name":"anthonysimeonov/relational_ndf","sub_path":"src/rndf_robot/eval/relation_tools/multi_ndf.py","file_name":"multi_ndf.py","file_ext":"py","file_size_in_byte":25096,"program_lang":"python","lang":"en","doc_type":"code","stars":24,"dataset":"github-code","pt":"21"}
+{"seq_id":"34279603743","text":"from play import play\n\n\ndef test_play():\n message = {\n \"response\": \"move\",\n \"move\": 26,\n \"message\": 'message'\n }\n msg = {\n 'request': 'play',\n 'lives': 3,\n 'errors': [],\n 'state': {\n 'players': ['ali', 'mehdi'],\n 'current': 0,\n 'board': [[28, 35], [27, 36]]}\n }\n\n play(msg, 'minimax')\n play(msg, 'random')\n","repo_name":"mehdiatigui/othello-IA","sub_path":"tests/test_play.py","file_name":"test_play.py","file_ext":"py","file_size_in_byte":406,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"}
+{"seq_id":"21117040999","text":"import numpy as np\nimport matplotlib.pyplot as plt\nimport seaborn as sns\n\n\ndef draw_heatmap(matrix):\n \"\"\"\n Draw the heatmap of the matrix.\n \"\"\"\n plt.style.use(\"ggplot\")\n sns.heatmap(matrix)\n plt.show()\n\n\ndef print_confusion_matrix(matrix, label_dictionary):\n \"\"\"\n Print out the confusion matrix formatted with labels\n \"\"\"\n values = \"\\t\".join(label_dictionary.values())\n print(f\"*\\t{values}\")\n for i in label_dictionary:\n row = \"\\t\".join([str(col) for col in matrix[i]])\n print(f\"{label_dictionary[i]}\\t{row}\")\n\n\ndef print_metrics(stats):\n \"\"\"\n Print out the the Precision, Recall and F1 of the stats\n \"\"\"\n print(\"Category\\tPrecision\\tRecall\\tF1\")\n for name, stat in stats.items():\n print(f\"{name}\\t{round(stat['precision']*100, 2)}%\\t{round(stat['recall']*100, 2)}%\\t\"\n f\"{round(stat['f1']*100, 2)}%\")\n\n\ndef calculate_confusion_matrix(predicted, label, label_dictionary):\n confusion_matrix = np.zeros((len(label_dictionary), len(label_dictionary)))\n for pred, lab in zip(predicted, label):\n for p, l in zip(pred, lab):\n confusion_matrix[p][l] += 1\n return confusion_matrix\n\n\ndef calculate_fscore_from_metrics(stats):\n fscore = lambda x: 0 if x[\"precision\"] + x[\"recall\"] == 0 \\\n else 2 * x[\"precision\"] * x[\"recall\"] / (x[\"precision\"] + x[\"recall\"])\n for _, stat in stats.items():\n stat[\"precision\"] = 0 if stat[\"tp\"] + stat[\"fp\"] == 0 else stat[\"tp\"] / (stat[\"tp\"] + stat[\"fp\"])\n stat[\"recall\"] = 0 if stat[\"tp\"] + stat[\"fn\"] == 0 else stat[\"tp\"] / (stat[\"tp\"] + stat[\"fn\"])\n stat[\"f1\"] = fscore(stat)\n stats[\"MICRO AVG\"] = {\n \"precision\": sum([stat[\"tp\"] for (name, stat) in stats.items()\n if name not in [\"MICRO AVG\", \"MACRO AVG\"]]) /\n sum([stat[\"tp\"] + stat[\"fp\"] for (name, stat) in stats.items()\n if name not in [\"MICRO AVG\", \"MACRO AVG\"]]),\n \"recall\": sum([stat[\"tp\"] for (name, stat) in stats.items()\n if name not in [\"MICRO AVG\", \"MACRO AVG\"]]) /\n sum([stat[\"tp\"] + stat[\"fn\"] for (name, stat) in stats.items()\n if name not in [\"MICRO AVG\", \"MACRO AVG\"]])}\n stats[\"MICRO AVG\"][\"f1\"] = fscore(stats[\"MICRO AVG\"])\n stats[\"MACRO AVG\"] = {\n \"precision\": np.mean([stat[\"precision\"] for (name, stat) in stats.items() if name not in [\"MICRO AVG\", \"MACRO AVG\"]]),\n \"recall\": np.mean([stat[\"recall\"] for (name, stat) in stats.items() if name not in [\"MICRO AVG\", \"MACRO AVG\"]])\n }\n stats[\"MACRO AVG\"][\"f1\"] = fscore(stats[\"MACRO AVG\"])\n return stats\n\n\ndef calculate_metrics_from_confusion_matrix(confusion_matrix, label_dictionary):\n stats = {k: {'tp': 0, 'fp': 0, 'fn': 0} for k in label_dictionary.values()}\n for i, row in enumerate(confusion_matrix):\n stats[label_dictionary[i]]['tp'] = row[i]\n stats[label_dictionary[i]]['fp'] = sum(row) - row[i]\n for j, col in enumerate(row):\n if i != j:\n stats[label_dictionary[j]][\"fn\"] += col\n return stats\n\n\ndef calculate_metrics_from_data(predicted, label, label_dictionary):\n stats = {k: {'tp': 0, 'fp': 0, 'fn': 0} for k in label_dictionary.values()}\n for pred, lab in zip(predicted, label):\n for p, l in zip(pred, lab):\n if p == l:\n stats[label_dictionary][l]['tp'] += 1\n else:\n stats[label_dictionary][p]['fp'] += 1\n stats[label_dictionary][l]['fn'] += 1\n return stats\n\n\ndef calculate_fscore(label_dictionary, **kwargs):\n if \"label\" in kwargs and \"predicted\" in kwargs:\n stats = calculate_metrics_from_data(kwargs[\"predicted\"], kwargs[\"label\"], label_dictionary)\n elif \"confusion_matrix\" in kwargs:\n stats = calculate_metrics_from_confusion_matrix(kwargs[\"confusion_matrix\"], label_dictionary)\n else:\n raise ValueError(\"The calculate_fscore function expects label and predicted data or \"\n \"confusion matrix as parameter.\"\n \"\\nExample: calculate_fscore(label_dictionary, confusion_matrix=confusion_matrix)\"\n \"\\nor: calculate_fscore(label_dictionary, label=label, predicted=predicted)\")\n return calculate_fscore_from_metrics(stats)\n\n\ndef calculate_and_print_metrics(predicted, label, label_dictionary, draw_matrix):\n confusion_matrix = calculate_confusion_matrix(predicted, label, label_dictionary)\n stats = calculate_fscore(label_dictionary, confusion_matrix=confusion_matrix)\n if draw_matrix:\n draw_heatmap(confusion_matrix)\n else:\n print_confusion_matrix(confusion_matrix, label_dictionary)\n print_metrics(stats)\n return confusion_matrix, stats\n","repo_name":"GKingA/tuw-inf-germeval2021","sub_path":"metrics.py","file_name":"metrics.py","file_ext":"py","file_size_in_byte":4810,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"}
+{"seq_id":"10415150468","text":"import pytest\nfrom unittest.mock import patch\nfrom io import BytesIO\nimport os\nimport tempfile\nfrom cryptography.hazmat.primitives.asymmetric import rsa\nfrom cryptography.hazmat.backends import default_backend\nfrom cryptography.hazmat.primitives import serialization\nfrom cryptography.exceptions import InvalidSignature\nimport nacl.utils\nimport nacl.secret\nimport nacl.pwhash\nfrom cryp_to_go import core\n\nSIZE_BUFFER_A = 1200\n\n\n@pytest.fixture\ndef content_a():\n return 'IDDQD\\n'.encode() * 200\n\n\n@pytest.fixture\ndef buffer_a(content_a):\n content = content_a\n buffer = BytesIO()\n buffer.write(content)\n total_size = buffer.tell()\n assert total_size == SIZE_BUFFER_A\n return buffer\n\n\ndef test_get_unenc_block_size():\n # if block_size == chunk size, it must be chunk_size - 40\n assert core.get_unenc_block_size(core.CHUNK_SIZE) == core.CHUNK_SIZE - 40\n # try chunk size 100 and block size 2000. That's 20 blocks of 60 unencrypted\n with patch('cryp_to_go.core.CHUNK_SIZE', 100):\n assert core.get_unenc_block_size(2000) == SIZE_BUFFER_A\n # impossible task: read block size not alignable with chunk size\n with patch('cryp_to_go.core.CHUNK_SIZE', 100):\n with pytest.raises(ValueError):\n core.get_unenc_block_size(150)\n\n\ndef test_hexlify():\n assert b'foo\\0' == core.unhexlify(core.hexlify(b'foo\\0'))\n assert 'abacadae' == core.hexlify(core.unhexlify('abacadae'))\n\n\ndef test_get_chunk_nonce():\n base = nacl.utils.random(nacl.secret.SecretBox.NONCE_SIZE)\n assert core._get_chunk_nonce(base, 0) != core._get_chunk_nonce(base, 1)\n assert core._get_chunk_nonce(base, 0) == core._get_chunk_nonce(base, 0)\n assert core._get_chunk_nonce(base, 0) == base\n assert core._get_chunk_nonce(base, 1) != base\n assert len(core._get_chunk_nonce(base, 1)) == len(base)\n\n\ndef test_read_in_chunks(content_a, buffer_a):\n buffer = buffer_a\n content = content_a\n # read with different chunk sizes\n for chunk_size in [None, 10, 100, 10000]:\n buffer.seek(0)\n chunks = [x for x in core._read_in_chunks(buffer, chunk_size=chunk_size)]\n assert all(len(x) == chunk_size for x in chunks[:-1])\n assert sum(len(x) for x in chunks) == SIZE_BUFFER_A\n assert b''.join(chunks) == content\n # try different read_total\n buffer.seek(0)\n chunks = [x for x in core._read_in_chunks(buffer, chunk_size=100, read_total=80)]\n assert len(chunks) == 1\n assert len(chunks[0]) == 80\n assert buffer.tell() == 80\n assert b''.join(chunks) == content[:80]\n buffer.seek(0)\n chunks = [x for x in core._read_in_chunks(buffer, chunk_size=100, read_total=250)]\n assert len(chunks) == 3\n assert len(chunks[0]) == 100\n assert len(chunks[1]) == 100\n assert len(chunks[2]) == 50\n assert buffer.tell() == 250\n assert b''.join(chunks) == content[:250]\n buffer.seek(0)\n chunks = [x for x in core._read_in_chunks(buffer, chunk_size=10000, read_total=250)]\n assert len(chunks) == 1\n assert len(chunks[0]) == 250\n assert buffer.tell() == 250\n assert b''.join(chunks) == content[:250]\n\n\ndef test_sign_verify(content_a, buffer_a):\n content, buffer = content_a, buffer_a\n # succeed unlimited read\n buffer.seek(0)\n key_sign = core.CryptoHandler.create_random(enable_signature_key=True).key_sign\n signature = core.sign_stream(key_sign, buffer)\n buffer.seek(0)\n core.verify_stream(key_sign, buffer, signature)\n # repeat, should create same signature\n buffer.seek(0)\n assert signature == core.sign_stream(key_sign, buffer)\n # try different sign key\n buffer.seek(0)\n sign_key_2 = core.CryptoHandler.create_random(enable_signature_key=True).key_sign\n signature_2 = core.sign_stream(sign_key_2, buffer)\n assert signature_2 != signature\n # use wrong signature\n buffer.seek(0)\n assert not core.verify_stream(key_sign, buffer, signature_2)\n buffer.seek(0)\n assert not core.verify_stream(sign_key_2, buffer, signature)\n # succeed limited read\n buffer.seek(0)\n signature_3 = core.sign_stream(key_sign, buffer, read_total=600)\n buffer.seek(0)\n core.verify_stream(key_sign, buffer, signature_3, read_total=600)\n # check if signature differs\n assert signature_3 != signature\n buffer.seek(0)\n # read wrong size -> fail\n assert not core.verify_stream(key_sign, buffer, signature_3, read_total=599)\n\n\ndef _touch_temp_file():\n fd, path = tempfile.mkstemp()\n os.close(fd)\n return path\n\n\ndef test_inflate_string():\n test_str = 'abcdefgh'\n inflated = core.inflate_string(test_str)\n assert inflated[:8] == b'abcdefgh'\n assert inflated[8] == 0\n assert len(inflated) > 30\n test_str = 'abcdefgh' * 10\n inflated = core.inflate_string(test_str)\n assert inflated[:80] == b'abcdefgh' * 10\n assert inflated[80] == 0\n assert len(inflated) > 90\n\n\ndef test_deflate_string():\n test_str = 'abcdefgh'\n inflated = core.inflate_string(test_str)\n assert core.deflate_string(inflated) == test_str\n test_str = 'abcdefgh' * 10\n inflated = core.inflate_string(test_str)\n assert core.deflate_string(inflated) == test_str\n\n\n@pytest.fixture()\ndef path_asym_keys():\n # generate a keypair\n asym_key = rsa.generate_private_key(\n backend=default_backend(),\n public_exponent=65537,\n key_size=2048\n )\n path_private_key = _touch_temp_file()\n with open(path_private_key, 'wb') as f_out:\n f_out.write(\n asym_key.private_bytes(\n serialization.Encoding.PEM,\n serialization.PrivateFormat.PKCS8,\n serialization.NoEncryption()\n )\n )\n path_public_key = _touch_temp_file()\n with open(path_public_key, 'wb') as f_out:\n f_out.write(\n asym_key.public_key().public_bytes(\n serialization.Encoding.OpenSSH,\n serialization.PublicFormat.OpenSSH\n )\n )\n return path_private_key, path_public_key\n\n\nclass TestAsymKey:\n\n def test_constructors(self, path_asym_keys):\n path_privkey, path_pubkey = path_asym_keys\n privkey = core.AsymKey.privkey_from_pemfile(path_privkey)\n pubkey = core.AsymKey.from_pubkey_file(path_pubkey)\n assert privkey.key is not None\n assert pubkey.key is not None\n with open(path_pubkey, 'r') as f_in:\n pubkey_2 = core.AsymKey.from_pubkey_string(f_in.read())\n assert pubkey_2.key.public_numbers() == pubkey.key.public_numbers()\n assert pubkey.key.public_numbers() == privkey.key.public_key().public_numbers()\n\n def test_encrypt_decrypt(self, path_asym_keys):\n path_privkey, path_pubkey = path_asym_keys\n privkey = core.AsymKey.privkey_from_pemfile(path_privkey)\n pubkey = core.AsymKey.from_pubkey_file(path_pubkey)\n assert privkey.decrypt(pubkey.encrypt(b'foobar')) == b'foobar'\n\n\nclass TestDerivedKeySetup:\n\n def test_general(self):\n dks = core.KeyDerivationSetup.create_default(enable_signature_key=True)\n # override defaults for faster tests\n dks.ops = nacl.pwhash.argon2i.OPSLIMIT_MIN\n dks.mem = nacl.pwhash.argon2i.MEMLIMIT_MIN\n password_1 = b'supersecret_1'\n password_2 = b'supersecret_2'\n derived_keys = dks.generate_keys(password_1)\n derived_keys_1b = dks.generate_keys(password_1)\n assert derived_keys.key_enc == derived_keys_1b.key_enc\n assert derived_keys.key_sign == derived_keys_1b.key_sign\n assert dks.to_dict() == core.KeyDerivationSetup.from_dict(dks.to_dict()).to_dict()\n derived_keys_2 = dks.generate_keys(password_2)\n assert derived_keys_2.key_enc != derived_keys.key_enc\n assert derived_keys_2.key_sign != derived_keys.key_sign\n assert derived_keys.key_enc != derived_keys.key_sign\n # create with a different salt\n dks2 = core.KeyDerivationSetup.create_default(enable_signature_key=False)\n # override defaults for faster tests\n dks2.ops = nacl.pwhash.argon2i.OPSLIMIT_MIN\n dks2.mem = nacl.pwhash.argon2i.MEMLIMIT_MIN\n assert dks2.generate_keys(password_1).key_enc != derived_keys.key_enc\n # serialize and deserialize\n dks3 = core.KeyDerivationSetup.from_dict(dks.to_dict())\n assert dks3.generate_keys(password_1).key_enc == derived_keys.key_enc\n\n\nclass TestCryptoHandler:\n\n def test_init(self):\n # no signature key\n handler = core.CryptoHandler.create_random(enable_signature_key=False)\n assert len(handler.key_enc)\n assert handler.key_sign is None\n # with signature key\n handler = core.CryptoHandler.create_random(enable_signature_key=True)\n assert len(handler.key_enc)\n assert handler.key_sign is not None and len(handler.key_sign)\n handler2 = core.CryptoHandler(handler.key_enc, handler.key_sign)\n assert handler.key_enc == handler2.key_enc\n assert handler.key_sign == handler2.key_sign\n\n def test_de_encrypt(self, buffer_a, content_a):\n # no signature key\n handler = core.CryptoHandler.create_random(enable_signature_key=False)\n buffer_a.seek(0)\n buffer_out = BytesIO()\n for chunk in handler.encrypt_stream(buffer_a):\n buffer_out.write(chunk)\n buffer_out.seek(0)\n assert b''.join(handler.decrypt_stream(buffer_out)) == content_a\n assert handler.signature is None\n # use signature key\n buffer_a.seek(0)\n buffer_out = BytesIO()\n for chunk in handler.encrypt_stream(buffer_a):\n buffer_out.write(chunk)\n buffer_out.seek(0)\n assert b''.join(handler.decrypt_stream(buffer_out)) == content_a\n assert handler.signature is None\n # create signature\n buffer_a.seek(0)\n buffer_out = BytesIO()\n with handler.create_signature():\n for chunk in handler.encrypt_stream(buffer_a):\n buffer_out.write(chunk)\n buffer_out.seek(0)\n assert b''.join(handler.decrypt_stream(buffer_out)) == content_a\n assert handler.signature is None\n\n def test_signature(self, buffer_a, content_a):\n # no signature key\n handler = core.CryptoHandler.create_random(enable_signature_key=False)\n buffer_a.seek(0)\n buffer_out = BytesIO()\n with handler.create_signature():\n for chunk in handler.encrypt_stream(buffer_a):\n buffer_out.write(chunk)\n signature = handler.signature\n assert signature is None\n # use signature key\n handler = core.CryptoHandler.create_random(enable_signature_key=True)\n buffer_a.seek(0)\n buffer_out_1 = BytesIO()\n with handler.create_signature():\n for chunk in handler.encrypt_stream(buffer_a):\n buffer_out_1.write(chunk)\n signature_1 = handler.signature\n assert signature_1 is not None\n buffer_a.seek(0)\n buffer_out_2 = BytesIO()\n with handler.create_signature():\n for chunk in handler.encrypt_stream(buffer_a, read_total=SIZE_BUFFER_A - 100):\n buffer_out_2.write(chunk)\n signature_2 = handler.signature\n assert signature_2 is not None\n assert signature_1 != signature_2\n with handler.verify_signature(signature_1):\n buffer_out_1.seek(0)\n decrypted_1 = b''.join(handler.decrypt_stream(buffer_out_1))\n assert decrypted_1 == content_a\n with handler.verify_signature(signature_2):\n buffer_out_2.seek(0)\n decrypted_2 = b''.join(handler.decrypt_stream(buffer_out_2))\n assert decrypted_2 == content_a[:SIZE_BUFFER_A - 100]\n with pytest.raises(InvalidSignature):\n # wrong signature\n with handler.verify_signature(signature_1):\n buffer_out_2.seek(0)\n b''.join(handler.decrypt_stream(buffer_out_2))\n\n def test_decrypt_info(self, content_a, buffer_a, path_asym_keys):\n privkey = core.AsymKey.privkey_from_pemfile(path_asym_keys[0])\n pubkey = core.AsymKey.from_pubkey_file(path_asym_keys[1])\n # no signature key\n handler = core.CryptoHandler.create_random(enable_signature_key=False)\n buffer_a.seek(0)\n buffer_out = BytesIO()\n with handler.create_signature():\n for chunk in handler.encrypt_stream(buffer_a):\n buffer_out.write(chunk)\n decrypt_info = handler.to_decrypt_info(pubkey)\n buffer_out.seek(0)\n with handler.decryptor_from_info(decrypt_info, privkey) as handler_decrypt:\n assert b''.join(handler_decrypt.decrypt_stream(buffer_out)) == content_a\n # with signature key, same usage, automatic checks\n handler = core.CryptoHandler.create_random(enable_signature_key=True)\n buffer_a.seek(0)\n buffer_out = BytesIO()\n with handler.create_signature():\n for chunk in handler.encrypt_stream(buffer_a):\n buffer_out.write(chunk)\n decrypt_info = handler.to_decrypt_info(pubkey)\n buffer_out.seek(0)\n with handler.decryptor_from_info(decrypt_info, privkey) as handler_decrypt:\n assert b''.join(handler_decrypt.decrypt_stream(buffer_out)) == content_a\n # wrong signature\n buffer_a.seek(0)\n buffer_out = BytesIO()\n with handler.create_signature():\n for chunk in handler.encrypt_stream(buffer_a, read_total=SIZE_BUFFER_A - 100):\n buffer_out.write(chunk)\n with pytest.raises(InvalidSignature):\n buffer_out.seek(0)\n with handler.decryptor_from_info(decrypt_info, privkey) as handler_decrypt:\n assert b''.join(handler_decrypt.decrypt_stream(buffer_out)) == content_a[:SIZE_BUFFER_A - 100]\n\n def test_de_encrypt_snippets(self, buffer_a, content_a):\n handler = core.CryptoHandler.create_random(enable_signature_key=False)\n assert handler.decrypt_snippet(handler.encrypt_snippet(content_a)) == content_a\n assert handler.signature is None\n # use signature key\n handler = core.CryptoHandler.create_random(enable_signature_key=True)\n enc = handler.encrypt_snippet(content_a)\n signature = handler.signature\n assert signature is not None\n assert handler.decrypt_snippet(enc, signature=signature) == content_a\n # wrong signature - re-encrypting uses different nonces\n enc_anew = handler.encrypt_snippet(content_a)\n with pytest.raises(InvalidSignature):\n handler.decrypt_snippet(enc_anew, signature=signature)\n","repo_name":"matthiashuschle/cryp-to-go","sub_path":"tests/test_core.py","file_name":"test_core.py","file_ext":"py","file_size_in_byte":14587,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"}
+{"seq_id":"34272015252","text":"#\n# Main program \n# This way to join Flask and PyQt5 was found on \n# https://maxinterview.com/code/how-to-run-flask-with-pyqt5-F1F2886B120537C/\n#\nimport sys\ntry:\n from PyQt5.QtGui import QGuiApplication\n from PyQt5.QtQml import QQmlApplicationEngine\n from PyQt5.QtCore import QTimer\nexcept ImportError:\n from PySide2.QtGui import QGuiApplication\n from PySide2.QtQml import QQmlApplicationEngine\n from PySide2.QtCore import QTimer\nfrom time import strftime, localtime\nfrom flask import Flask, render_template\nfrom threading import Thread\nfrom queue import Queue\nfrom security import Security\n\n\nclass MainWindow(QGuiApplication):\n\n main_timer = None\n \n def __init__(self, *args, **kwargs):\n super(MainWindow, self).__init__(*args, **kwargs)\n\n self.engine = QQmlApplicationEngine()\n self.engine.quit.connect(self.quit)\n self.engine.load('main.qml')\n\n self.main_timer = QTimer()\n self.main_timer.timeout.connect(self.read_sensors)\n self.main_timer.start(100)\n\n self.security = Security()\n\n self.engine.rootContext().setContextProperty('security', self.security)\n\n def update_time(self):\n # Pass the current time to QML.\n curr_time = strftime(\"%H:%M:%S\", localtime())\n self.engine.rootObjects()[0].setProperty('currTime', curr_time)\n\n def read_sensors(self):\n \"\"\"\n this code must be replaced\n if not self.in_queue.empty():\n data = self.in_queue.get_nowait()\n if type(data) is str:\n self.ui.label.setText(data)\n \"\"\"\n\n pass\n\n\nif __name__ == \"__main__\":\n app = MainWindow(sys.argv)\n q = Queue()\n app_ = Flask(__name__)\n setattr(app_, \"out_queue\", q)\n setattr(app, \"in_queue\", q)\n\n# setting our root\n @app_.route('/')\n def index():\n return render_template('index.html')\n\n @app_.route('/message/')\n def message(msg):\n app_.out_queue.put(msg)\n return 'Ok'\n\n # Flask parameters\n kwargs = {'host': '0.0.0.0', 'port': 5000, 'threaded': True, 'use_reloader': False, 'debug': False}\n # Run Flask in another thread\n flaskThread = Thread(target=app_.run, daemon=True, kwargs=kwargs).start()\n\n if 'PyQt5' in sys.modules:\n sys.exit(app.exec())\n else:\n sys.exit(app.exec_())\n","repo_name":"marcotcal/domus","sub_path":"gui/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2330,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"}
+{"seq_id":"21406708270","text":"import pygame\nimport os\nimport sys\n\n\n\ndef load_image(name, colorkey=None):\n fullname = os.path.join('data', name)\n # если файл не существует, то выходим\n if not os.path.isfile(fullname):\n print(f\"Файл с изображением '{fullname}' не найден\")\n sys.exit()\n image = pygame.image.load(fullname)\n if colorkey is not None:\n image = image.convert()\n if colorkey == -1:\n colorkey = image.get_at((0, 0))\n image.set_colorkey(colorkey)\n else:\n image = image.convert_alpha()\n return image\n\n\npygame.init()\npygame.mouse.set_visible(False)\nscreen = pygame.display.set_mode((700, 700))\nrunning = True\nimage = load_image('arrow.png')\ncoords = None, None\nwhile running:\n screen.fill((0, 0, 0))\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n running = False\n if event.type == pygame.MOUSEMOTION:\n coords = event.pos\n if coords[0] and pygame.mouse.get_focused():\n screen.blit(image, coords)\n pygame.display.flip()\npygame.quit()","repo_name":"dariapotapova/pygame-5","sub_path":"1.py","file_name":"1.py","file_ext":"py","file_size_in_byte":1108,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"}
+{"seq_id":"8499795056","text":"import simtk.openmm as mm\nimport simtk.unit as unit\nfrom openmmplumed import PlumedForce\nimport numpy as np\nimport unittest\n\n\nclass TestTorchForce(unittest.TestCase):\n\n def testForce(self):\n # Create a System that applies a force based on the distance between two atoms.\n\n numParticles = 4\n system = mm.System()\n positions = np.empty((numParticles, 3))\n for i in range(numParticles):\n system.addParticle(1.0)\n positions[i] = [i, 0.1*i, -0.3*i]\n script = '''\n d: DISTANCE ATOMS=1,3\n BIASVALUE ARG=d\n '''\n force = PlumedForce(script)\n system.addForce(force)\n integ = mm.LangevinIntegrator(300.0, 1.0, 1.0)\n context = mm.Context(system, integ, mm.Platform.getPlatformByName('Reference'))\n context.setPositions(positions)\n\n # Compute the forces and energy.\n\n state = context.getState(getEnergy=True, getForces=True)\n delta = positions[0] - positions[2] \n dist = np.sqrt(np.sum(delta**2))\n zero = np.zeros(3)\n self.assertAlmostEqual(dist, state.getPotentialEnergy().value_in_unit(unit.kilojoules_per_mole))\n self.assertTrue(np.allclose(-delta/dist, state.getForces(asNumpy=True)[0]))\n self.assertTrue(np.allclose(zero, state.getForces(asNumpy=True)[1]))\n self.assertTrue(np.allclose(delta/dist, state.getForces(asNumpy=True)[2]))\n self.assertTrue(np.allclose(zero, state.getForces(asNumpy=True)[3]))\n\n\nif __name__ == '__main__':\n unittest.main()","repo_name":"openmm/openmm-plumed","sub_path":"python/tests/TestPlumedForce.py","file_name":"TestPlumedForce.py","file_ext":"py","file_size_in_byte":1544,"program_lang":"python","lang":"en","doc_type":"code","stars":44,"dataset":"github-code","pt":"21"}
+{"seq_id":"72722368374","text":"from direction import Direction\n\n\nclass Interface:\n def __init__(self, game=None):\n self.game = game\n\n @staticmethod\n def get_user_input():\n print(\"Move which direction? ('wasd' or 'hjkl' keys)\")\n value = input().strip().lower()\n if value in ['w', 'k']:\n return Direction.UP\n\n if value in ['d', 'l']:\n return Direction.RIGHT\n\n if value in ['s', 'j']:\n return Direction.DOWN\n\n if value in ['a', 'h']:\n return Direction.LEFT\n\n def __str__(self):\n output = f\"MOVES: {self.game.player.moves}\\n\"\n for row_index in range(self.game.board.height):\n for column_index in range(self.game.board.width):\n output += \" \" + str(self.game.board.rows[row_index][column_index])\n output += \"\\n\"\n return output\n\n def show(self):\n print(self)","repo_name":"kevinelong/sokoban","sub_path":"interface.py","file_name":"interface.py","file_ext":"py","file_size_in_byte":893,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"}
+{"seq_id":"38173053423","text":"\"\"\"Модуль с реализованными сортировками\"\"\"\n\n\"\"\"\nСортирует массив алгоритмом простых вставок.\n\"\"\"\ndef insert_sort(arr):\n n = len(arr)\n\n for i in range(1, n):\n key = arr[i]\n j = i - 1\n while j >= 0 and key < arr[j]:\n arr[j + 1] = arr[j]\n j -= 1\n arr[j + 1] = key\n\n\n\"\"\"Сортирует массив алгоритмом быстрой сортировки\"\"\"\ndef quick_sort(arr, start, end):\n \"\"\"В данной реализации берем первый и последний индексы подмассива, который должен быть отсортирован\"\"\"\n if start >= end:\n return\n\n i = start\n j = end\n p = arr[start + (end - start) // 2]\n\n while i <= j:\n while arr[i] < p:\n i += 1\n while arr[j] > p:\n j -= 1\n if i <= j:\n temp = arr[i]\n arr[i] = arr[j]\n arr[j] = temp\n\n i += 1\n j -= 1\n\n \"\"\"Рекурсивный вызов функции\"\"\"\n if start < j:\n quick_sort(arr, start, j)\n if end > i:\n quick_sort(arr, i, end)\n\n\"\"\"Вспомогательная функция, записывает отсортированный подмассив в оригинальный массив\"\"\"\ndef merge(arr, low, mid, high):\n buff = [None] * (high + 1 - low)\n\n h = 0\n i = low\n j = mid + 1\n\n while i <= mid and j <= high:\n if arr[i] <= arr[j]:\n buff[h] = arr[i]\n i += 1\n else:\n buff[h] = arr[j]\n j += 1\n h += 1\n\n if i > mid:\n for k in range(j, high + 1):\n buff[h] = arr[k]\n h += 1\n else:\n for k in range(i, mid + 1):\n buff[h] = arr[k]\n h += 1\n\n for k in range(0, high - low + 1):\n arr[low + k] = buff[k]\n\n\n\"\"\"Сортирует массив алгоритмом сортировки слиянием\"\"\"\ndef merge_sort(arr, low, high):\n if low < high:\n mid = (low + high) // 2\n merge_sort(arr, low, mid)\n merge_sort(arr, mid + 1, high)\n merge(arr, low, mid, high)\n","repo_name":"sashanord/First_lab","sub_path":"My_sortes.py","file_name":"My_sortes.py","file_ext":"py","file_size_in_byte":2241,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"}
+{"seq_id":"42950662805","text":"def conta_palavras(teste):\n with open(teste, 'r') as arquivo:\n conteudo = arquivo.read()\n junta = conteudo.split()\n separa = '\\t'.join(junta)\n\n with open('dados.tsv', 'w') as arquivo2:\n arquivo2.writelines(separa)\n \nprint(conta_palavras('dados.csv'))","repo_name":"gabriellaec/desoft-analise-exercicios","sub_path":"backup/user_374/ch86_2020_04_29_23_14_23_203584.py","file_name":"ch86_2020_04_29_23_14_23_203584.py","file_ext":"py","file_size_in_byte":285,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"}
+{"seq_id":"19903103356","text":"# Initialize a new pygame application\n # any color background\n # handle simple events\nimport pygame\nfrom Button import *\n\n# initializing pygame\npygame.init()\n\ndisp = pygame.display.set_mode((800, 600))\ndisp.fill((70, 50, 150))\n\n# create a new rectangle object\n # any size, location, color\n # set_color() RGB\nshape = pygame.Rect(50, 50, 80, 20)\n# draw rectangle with color on disp \n\n##pygame.draw.rect(disp, (200, 200, 200), shape)\n\nmyButton = Button(disp)\n\n# ctrate block object\ngameClock = pygame.time.Clock()\n\nwhile (True):\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n exit()\n myButton.eventResponse(event)\n myButton.draw() \n \n pygame.display.update()\n gameClock.tick(20)\n \n\n","repo_name":"kgarza101/Python","sub_path":"W7/pygame2.py","file_name":"pygame2.py","file_ext":"py","file_size_in_byte":772,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"}
+{"seq_id":"71069758134","text":"import os, sys\nfrom typing import *\nimport torch\nimport random\n\ndef detach(\n batch_dict: Dict[int, List[torch.Tensor]] = None, \n k_shot:int = None, \n k_query:int = None\n ) -> Tuple[Dict[int, List[torch.Tensor]]]:\n sample_len = len(batch_dict[list(batch_dict.keys())[0]])\n \n if k_shot + k_query > sample_len:\n raise ValueError(f\"Many data to unpack. Since #sample in support set: k_shot and #sample \\\n in query set k_query must satisfy the condition: k_shot + k_query == #sample \\\n in a batch per task.\")\n elif k_shot + k_query < sample_len:\n raise UserWarning(f\"the #sample in support set: k_shot and #sample in query set: k_query \\\n totally are less than the #sample available in batch task dict. The redundant samples are \\\n used in automatically used in query set.\")\n \n support_dct = {\n _cls : batch_dict[_cls][:k_shot] for _cls in batch_dict\n }\n \n query_dct = {\n _cls : batch_dict[_cls][k_shot:] for _cls in batch_dict\n }\n \n return (support_dct, query_dct)\n\ndef maml_detach(\n batch_dict: Dict[int, List[torch.Tensor]] = None, \n k_shot:int = None, \n k_query:int = None,\n task:int = None\n ) -> Tuple[torch.Tensor]:\n \n support_dct, query_dct = detach(\n batch_dict=batch_dict,\n k_shot=k_shot,\n k_query=k_query\n )\n \n if not isinstance(task, int):\n raise ValueError(f\"task arg must be integer type but found {type(task)} instead\")\n elif task not in batch_dict.keys():\n raise Exception(f\"Found no task {task} in batch dict\")\n \n tasks = list(batch_dict.keys())\n \n support_x, support_y, query_x, query_y = [], [], [], []\n for _task in tasks:\n support_x.extend(support_dct[_task])\n query_x.extend(query_dct[_task])\n if _task == task:\n support_y.extend([1]*k_shot)\n query_y.extend([1]*k_query)\n else:\n support_y.extend([0]*k_shot)\n query_y.extend([0]*k_query)\n \n # shuf_sp_lst, shuf_qr_lst = list(range(len(support_x))), list(range(len(query_x)))\n # random.shuffle(shuf_sp_lst)\n # random.shuffle(shuf_qr_lst)\n \n # support_x = torch.stack(support_x)[torch.tensor(shuf_sp_lst)]\n # support_y = torch.FloatTensor(support_y)[torch.tensor(shuf_sp_lst)]\n # query_x = torch.stack(query_x)[torch.tensor(shuf_qr_lst)]\n # query_y = torch.FloatTensor(query_y)[torch.tensor(shuf_qr_lst)]\n \n support_x = torch.stack(support_x)\n support_y = torch.FloatTensor(support_y)\n query_x = torch.stack(query_x)\n query_y = torch.FloatTensor(query_y)\n \n return (support_x, support_y, query_x, query_y)\n\ndef single_task_detach(\n batch_dict: Dict[int, List[torch.Tensor]] = None, \n k_shot:int = None, \n k_query:int = None,\n task:int = None\n ):\n \n support_dct, query_dct = detach(\n batch_dict=batch_dict,\n k_shot=k_shot,\n k_query=k_query\n )\n \n if not isinstance(task, int):\n raise ValueError(f\"task arg must be integer type but found {type(task)} instead\")\n elif task not in batch_dict.keys():\n raise Exception(f\"Found no task {task} in batch dict\")\n \n support_x, support_y, query_x, query_y = [], [], [], []\n \n support_x.extend(support_dct[task])\n support_y.extend([task]*len(support_dct[task]))\n query_x.extend(query_dct[task])\n query_y.extend([task]*len(query_dct[task]))\n \n support_x = torch.stack(support_x)\n support_y = torch.LongTensor(support_y)\n query_x = torch.stack(query_x)\n query_y = torch.LongTensor(query_y)\n \n return (support_x, support_y, query_x, query_y)","repo_name":"KhoiDOO/PyMel","sub_path":"pymel/dataset/utils/helper/detach.py","file_name":"detach.py","file_ext":"py","file_size_in_byte":3686,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"21"}
+{"seq_id":"9115883065","text":"\"\"\"Test FractionalBrownianMotion.\"\"\"\n# flake8: noqa\nimport pytest\n\nfrom stochastic.continuous import FractionalBrownianMotion\n\n\ndef test_fractional_brownian_motion_str_repr(hurst, t):\n instance = FractionalBrownianMotion(hurst, t)\n assert isinstance(repr(instance), str)\n assert isinstance(str(instance), str)\n\ndef test_fractional_brownian_motion_sample(hurst, t, n, zero, threshold):\n instance = FractionalBrownianMotion(hurst, t)\n s = instance.sample(n, zero)\n assert len(s) == n + int(zero)\n","repo_name":"timothyyu/ml_monorepo","sub_path":"stochastic/tests/continuous/test_fractional_brownian_motion.py","file_name":"test_fractional_brownian_motion.py","file_ext":"py","file_size_in_byte":512,"program_lang":"python","lang":"en","doc_type":"code","stars":59,"dataset":"github-code","pt":"21"}
+{"seq_id":"70449226614","text":"#!/usr/bin/env python\n\nimport rospy\nimport optim\nfrom percepto_msgs.srv import GetCritique\n\n\nclass BlockOptimizationWrapper(object):\n \"\"\"Wraps a GetCritique call and provides multiple GetCritique services\n corresponding to blocks of the base GetCritique server.\n \"\"\"\n\n def __init__(self):\n interface_info = rospy.get_param('~interface')\n self.interface = optim.CritiqueInterface(**interface_info)\n\n self.servers = []\n block_info = dict(rospy.get_param('~blocks'))\n self.current_params = {}\n self.blocks = {}\n for b_name, b_info in block_info.iteritems():\n params = b_info['parameters']\n init = b_info['initial']\n\n # Add all parameters to current param dict\n if b_name in self.blocks:\n raise RuntimeError('Block %s repeated!'% b_name)\n self.blocks[b_name] = params\n\n for param, ival in zip(params, init):\n if param in self.current_params:\n raise RuntimeError('Parameter %s repeated!' % param)\n self.current_params[param] = ival\n\n rospy.loginfo('Block %s with params %s init %s',\n b_name, str(params), str(init))\n\n def cb(req):\n return self.block_callback(block=b_name,\n values=req.input,\n names=req.names)\n topic = '~get_%s_critique' % b_name\n self.servers.append(rospy.Service(topic, GetCritique, cb))\n\n def block_callback(self, block, values, names):\n if len(names) == 0:\n names = self.blocks[block]\n\n block_params = self.blocks[block]\n if any([(n not in block_params) for n in names]):\n rospy.logerr('Received parameters %s not in block %s consisting of %s',\n str(names), block, str(block_params))\n return None\n\n for n, v in zip(names, values):\n self.current_params[n] = v\n\n return self.get_critique()\n\n def get_critique(self):\n n = self.current_params.keys()\n x = [self.current_params[ni] for ni in n]\n return self.interface.raw_call(x)\n\n\nif __name__ == '__main__':\n rospy.init_node('block_optimization_wrapper')\n wrapper = BlockOptimizationWrapper()\n try:\n rospy.spin()\n except rospy.ROSInterruptException:\n pass\n","repo_name":"Humhu/percepto","sub_path":"optim/nodes/BlockOptimizationWrapper.py","file_name":"BlockOptimizationWrapper.py","file_ext":"py","file_size_in_byte":2432,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"21"}
+{"seq_id":"12262370860","text":"from flask import request, jsonify, make_response\n\nfrom app import app\nfrom ..services import consultar_cidade, consultar_cidade_id, consultar_tempo\nfrom ..db_services import listar_tempo_data, listar_tempo_max, listar_cidade_id\nfrom ..entity import CidadeEntity, TempoEntity\nfrom ..schemas import CidadeSchema\nfrom ..utils import tratamento_tempo, checar_tempo, tratamento_media\n\n\n@app.route('/analise', methods=['GET'])\ndef analise():\n di = request.args.get('data_inicial')\n df = request.args.get('data_final')\n dados = {'maiorTemperatura': {}, 'mediaPrecipitacao': []}\n if di is not None and df is not None:\n tp = listar_tempo_max(data_final=df, data_inicial=di)\n tc = listar_tempo_data(data_inicial=di, data_final=df)\n media = tratamento_media(tc)\n dados['maiorTemperatura'] = {'cidade': tp.cidade.nome,'temperatura': tp.max_temp, 'data': tp.data}\n dados['mediaPrecipitacao'] = media\n return make_response(jsonify(dados), 200)\n elif di is None and df is not None:\n return make_response({'message': 'Data inicial é parametro obrigatório!'})\n elif df is None and di is not None:\n return make_response({'message': 'Data final é parametro obrigatório!'})\n else:\n return make_response({'message': 'Data inicial e Data final são parametros obrigatórios!'})\n","repo_name":"bsgabrielsilva/testea","sub_path":"app/views/analise_view.py","file_name":"analise_view.py","file_ext":"py","file_size_in_byte":1345,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"}
+{"seq_id":"19787890569","text":"import pyttsx3 #pip install pyttsx3\r\nimport speech_recognition as sr #pip install speechRecognition\r\nimport datetime\r\nimport wikipedia #pip install wikipedia\r\nimport webbrowser\r\nimport os\r\nimport requests \r\nimport time\r\n\r\nengine = pyttsx3.init('sapi5')\r\nvoices = engine.getProperty('voices')\r\n# print(voices[1].id)\r\nengine.setProperty('voice', voices[0].id)\r\n\r\n#to speak\r\ndef speak(audio):\r\n engine.say(audio)\r\n engine.runAndWait()\r\n\r\nWarning=0\r\n#for greeting\r\ndef wishMe():\r\n hour = int(datetime.datetime.now().hour)\r\n if hour>=0 and hour<12:\r\n speak(\"Good Morning!\")\r\n\r\n elif hour>=12 and hour<18:\r\n speak(\"Good Afternoon!\") \r\n\r\n else:\r\n speak(\"Good Evening!\") \r\n\r\n speak(\"I am Jarvis Sir. Please tell me how may I help you\") \r\n\r\n#for process response data\r\ndef create_weather_report(data): \r\n report = \"Weather Report:\\n\" \r\n city = data[\"name\"] \r\n report += f\"City: {city}\\n\" \r\n temperature = data[\"main\"][\"temp\"]\r\n warning=int(temperature) \r\n print(warning)\r\n report += f\"Temperature: {temperature}°C\\n\" \r\n humidity = data[\"main\"][\"humidity\"] \r\n report += f\"Humidity: {humidity}%\\n\" \r\n wind_speed = data[\"wind\"][\"speed\"] \r\n report += f\"Wind Speed: {wind_speed} m/s\\n\" \r\n li=[]\r\n li.append(report)\r\n li.append(temperature)\r\n return li\r\n\r\n#for weather\r\ndef get_hourly_weather_data():\r\n api_key = \"15efa7eab9601230f35e572077b8d6f9\" \r\n city_id = \"524901\" \r\n data = get_weather_data(api_key, city_id) \r\n report = create_weather_report(data) \r\n speak(report[0]) \r\n if(report[1]<10):\r\n speak(\"please wear the sweater and gloves sir climate too cold\")\r\n elif(report[1]>30):\r\n speak(\"Sir climate is too hot kindly i request to drink lots of water and take more liquid foods sir stay hydrated and healthy\")\r\n else:\r\n speak(\"Climate is good make a vacation sir and enjoy the outdoor\")\r\n\r\n#to get weather data \r\ndef get_weather_data(api_key, city_id): \r\n api_url = \"http://api.openweathermap.org/data/2.5/weather\" \r\n params = { \r\n \"id\": city_id, \r\n \"units\": \"metric\", \r\n \"appid\": api_key \r\n } \r\n response = requests.get(api_url, params=params) \r\n data = response.json() \r\n return data \r\n\r\n#for process the command\r\ndef takeCommand():\r\n #It takes microphone input from the user and returns string output\r\n\r\n r = sr.Recognizer()\r\n with sr.Microphone() as source:\r\n print(\"Listening...\")\r\n r.pause_threshold = 1\r\n audio = r.listen(source)\r\n\r\n try:\r\n print(\"Recognizing...\") \r\n query = r.recognize_google(audio, language='en-in')\r\n print(f\"User said: {query}\\n\")\r\n\r\n except Exception as e:\r\n # print(e) \r\n print(\"Say that again please...\") \r\n return \"None\"\r\n return query\r\n\r\n\r\nif __name__ == \"__main__\":\r\n wishMe()\r\n while True:\r\n \r\n query = takeCommand().lower()\r\n\r\n # Logic for executing tasks based on query\r\n if \"wikipedia\" in query:\r\n speak('Searching Wikipedia...')\r\n query = query.replace(\"wikipedia\",\"\")\r\n results = wikipedia.summary(query, sentences=2)\r\n speak(\"According to Wikipedia\")\r\n print(results)\r\n speak(results)\r\n\r\n elif 'open youtube' in query:\r\n webbrowser.open(\"youtube.com\")\r\n\r\n elif 'open google' in query:\r\n webbrowser.open(\"google.com\")\r\n\r\n elif 'open stackoverflow' in query:\r\n webbrowser.open(\"stackoverflow.com\") \r\n\r\n\r\n elif 'play music' in query:\r\n music_dir = 'D:\\motivationalsongs'\r\n songs = os.listdir(music_dir)\r\n print(songs) \r\n os.startfile(os.path.join(music_dir, songs[0]))\r\n\r\n elif 'the time' in query:\r\n strTime = datetime.datetime.now().strftime(\"%H:%M:%S\") \r\n speak(f\"Sir, the time is {strTime}\")\r\n elif 'the climate' in query:\r\n get_hourly_weather_data()\r\n elif 'stop' in query:\r\n speak(\"bye take care sir............\")\r\n break\r\n","repo_name":"Energy-level/2023_projects","sub_path":"VoiceAssistant/jarvis.py","file_name":"jarvis.py","file_ext":"py","file_size_in_byte":4140,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"}
+{"seq_id":"74546084532","text":"from collections import Counter\n\ndef count_letter(s, k):\n result = {}\n for l in s:\n result[l] = 1 + result.get(l, 0)\n print(result)\n\n result_k = []\n sorted_value = sorted(result.values(), reverse=True)\n target = sorted_value[k-1]\n for key, element in result.items():\n if element >= target:\n result_k.append([key, element])\n print(result_k)\n\ndef count_counter(s):\n c = Counter(s)\n print(c.most_common(2))\n\nif __name__ == \"__main__\":\n s = \"hhhyeser\"\n count_letter(s, 2)\n count_counter(s)","repo_name":"yuzhecd/al_py","sub_path":"HashTable/letter_count.py","file_name":"letter_count.py","file_ext":"py","file_size_in_byte":549,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"}
+{"seq_id":"18203445592","text":"class Solution:\n def findLadders(self, beginWord: str, endWord: str, wordList: List[str]) -> List[List[str]]:\n wordSet = set(wordList)\n if endWord not in wordList:\n return []\n\n # {\"hit\": [\"hot\"], \"hot\": [\"dot\", \"lot\"], ...}\n graph: Dict[str, List[str]] = collections.defaultdict(list)\n\n # Build graph from beginWord -> endWord.\n if not self._bfs(beginWord, endWord, wordSet, graph):\n return []\n\n ans = []\n\n self._dfs(graph, beginWord, endWord, [beginWord], ans)\n return ans\n\n def _bfs(self, beginWord: str, endWord: str, wordSet: Set[str], graph: Dict[str, List[str]]) -> bool:\n q1 = {beginWord}\n q2 = {endWord}\n backward = False\n\n while q1 and q2:\n for word in q1:\n wordSet.discard(word)\n for word in q2:\n wordSet.discard(word)\n # Always expand the smaller queue\n if len(q1) > len(q2):\n q1, q2 = q2, q1\n backward = not backward\n q = set()\n reachEndWord = False\n for parent in q1:\n for child in self._getChildren(parent, wordSet, q2):\n if child in wordSet or child in q2:\n q.add(child)\n if backward:\n graph[child].append(parent)\n else:\n graph[parent].append(child)\n if child in q2:\n reachEndWord = True\n if reachEndWord:\n return True\n q1 = q\n\n return False\n\n def _getChildren(self, parent: str, wordSet: Set[str], q2) -> List[str]:\n children = []\n s = list(parent)\n\n for i, cache in enumerate(s):\n for c in string.ascii_lowercase:\n if c == cache:\n continue\n s[i] = c\n child = ''.join(s)\n if child in wordSet or child in q2:\n children.append(child)\n s[i] = cache\n\n return children\n\n def _dfs(self, graph: Dict[str, List[str]], word: str, endWord: str, path: List[str], ans: List[List[str]]) -> None:\n if word == endWord:\n ans.append(path.copy())\n return\n\n for child in graph.get(word, []):\n path.append(child)\n self._dfs(graph, child, endWord, path, ans)\n path.pop()\n","repo_name":"walkccc/LeetCode","sub_path":"solutions/0126. Word Ladder II/0127-2.py","file_name":"0127-2.py","file_ext":"py","file_size_in_byte":2096,"program_lang":"python","lang":"en","doc_type":"code","stars":756,"dataset":"github-code","pt":"21"}
+{"seq_id":"20901827725","text":"import torch\nfrom torch.autograd import Variable\nimport render_pytorch\nimport image\nimport camera\nimport material\nimport light\nimport shape\nimport numpy as np\n\nresolution = [256, 256]\nposition = Variable(torch.from_numpy(np.array([0, 0, -5], dtype=np.float32)))\nlook_at = Variable(torch.from_numpy(np.array([0, 0, 0], dtype=np.float32)))\nup = Variable(torch.from_numpy(np.array([0, 1, 0], dtype=np.float32)))\nfov = Variable(torch.from_numpy(np.array([45.0], dtype=np.float32)))\nclip_near = Variable(torch.from_numpy(np.array([0.01], dtype=np.float32)))\nclip_far = Variable(torch.from_numpy(np.array([10000.0], dtype=np.float32)))\ncam = camera.Camera(position = position,\n look_at = look_at,\n up = up,\n cam_to_world = None,\n fov = fov,\n clip_near = clip_near,\n clip_far = clip_far,\n resolution = resolution)\nmat_grey=material.Material(\\\n diffuse_reflectance=torch.from_numpy(np.array([0.5,0.5,0.5],dtype=np.float32)))\nmaterials=[mat_grey]\nvertices=Variable(torch.from_numpy(\\\n np.array([[-1.7,1.0,0.0], [1.0,1.0,0.0], [-0.5,-1.0,0.0]],dtype=np.float32)))\nindices=torch.from_numpy(np.array([[0,1,2]],dtype=np.int32))\nshape_triangle=shape.Shape(vertices,indices,None,None,0)\nlight_vertices=Variable(torch.from_numpy(\\\n np.array([[-1,-1,-9],[1,-1,-9],[-1,1,-9],[1,1,-9]],dtype=np.float32)))\nlight_indices=torch.from_numpy(\\\n np.array([[0,1,2],[1,3,2]],dtype=np.int32))\nshape_light=shape.Shape(light_vertices,light_indices,None,None,0)\nshapes=[shape_triangle,shape_light]\nlight_intensity=torch.from_numpy(\\\n np.array([30,30,30],dtype=np.float32))\nlight=light.Light(1,light_intensity)\nlights=[light]\nargs=render_pytorch.RenderFunction.serialize_scene(\\\n cam,materials,shapes,lights,resolution,4,1)\n\n# To apply our Function, we use Function.apply method. We alias this as 'render'.\nrender = render_pytorch.RenderFunction.apply\nimg = render(0, *args)\nimage.imwrite(img.data.numpy(), 'test/results/test_single_triangle_camera/target.exr')\ntarget = Variable(torch.from_numpy(image.imread('test/results/test_single_triangle_camera/target.exr')))\n\nposition = Variable(torch.from_numpy(np.array([0, 0, -3], dtype=np.float32)),\n requires_grad=True)\nlook_at = Variable(torch.from_numpy(np.array([-0.5, -0.5, 0], dtype=np.float32)),\n requires_grad=True)\n\noptimizer = torch.optim.Adam([position, look_at], lr=5e-2)\nfor t in range(200):\n cam = camera.Camera(position = position,\n look_at = look_at,\n up = up,\n cam_to_world = None,\n fov = fov,\n clip_near = clip_near,\n clip_far = clip_far,\n resolution = resolution)\n args=render_pytorch.RenderFunction.serialize_scene(cam,materials,shapes,lights,resolution,4,1)\n\n optimizer.zero_grad()\n # Forward pass: render the image\n img = render(t+1, *args)\n image.imwrite(img.data.numpy(), 'test/results/test_single_triangle_camera/iter_{}.png'.format(t))\n loss = (img - target).pow(2).sum()\n print('loss:', loss.item())\n\n loss.backward()\n print('position.grad:', position.grad)\n print('look_at.grad:', look_at.grad)\n\n optimizer.step()\n print('position:', position)\n print('look_at:', look_at)\n\nfrom subprocess import call\ncall([\"ffmpeg\", \"-framerate\", \"24\", \"-i\",\n \"test/results/test_single_triangle_camera/iter_%d.png\",\n \"-vb\", \"20M\",\n \"test/results/test_single_triangle_camera/out.mp4\"])","repo_name":"BachiLi/delta_ray","sub_path":"test/test_single_triangle_camera.py","file_name":"test_single_triangle_camera.py","file_ext":"py","file_size_in_byte":3684,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"}
+{"seq_id":"4228077832","text":"#Verifica si los elementos de una lista están en una matriz o arroja las coordenadas de un elemento a buscar\ndef ubicarElementos(matriz, elementoabuscar, elementos):\n coordenadas = []\n for fila in range(len(matriz)):\n for columna in range(len(matriz[fila])):\n elemento = matriz[fila][columna]\n if elementos is not None:\n if elemento in elementos:\n return False\n elif elementoabuscar is not None:\n if elemento == elementoabuscar:\n coordenadas.append((fila, columna))\n if coordenadas:\n return coordenadas\n return True\n \n#_____________________________________________________________________________________________\n\n","repo_name":"JabCol/AlgoritmoMinimax","sub_path":"funciones.py","file_name":"funciones.py","file_ext":"py","file_size_in_byte":744,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"}
+{"seq_id":"12400157869","text":"#==========================================================================\r\n# Program: Device.py ---- CLASS ---\r\n# Author: Jorge E. Rodriguez\r\n# Date Created: Jan-21-2018\r\n# Date Last Modified: Feb-20-2018\r\n# Summary: This is Class to for the Device\r\n#==========================================================================\r\n\r\n#***************************************************************\r\n# ==================== Libraries Required =============*\r\n#***************************************************************\r\n\r\nimport os\r\nfrom threading import Thread\r\nimport sys\r\nimport math\r\nimport datetime\r\nimport time\r\nimport random\r\nimport tkinter\r\nimport tkinter.messagebox\r\nimport tkinter.filedialog\r\nfrom tkinter import * # Importing the Tkinter (tool box) library\r\nfrom tkinter import ttk\r\nif sys.version_info < (3,0): \r\n import Tkinter as tkinter \r\n import tkMessageBox as mbox \r\n import Tkinter.font as tkfont\r\nelse: \r\n import tkinter \r\n import tkinter.messagebox as mbox \r\n import tkinter.font as tkfont\r\n#import PyPDF2\r\n\r\n\r\ntry:\r\n from odbc_connector import *\r\n Is_ODBC_Available = True\r\nexcept:\r\n print (\"********************************************************************************** \\n\")\r\n print (\"*** NO ODBC Library Found, please download it in order to access the Databases *** \\n\")\r\n print (\"********************************************************************************** \\n\")\r\n Is_ODBC_Available = False\r\n sys.exit(1)\r\n\r\n#*******************************************************\r\n#============= READING VARIABLES TABLE ================*\r\n#*******************************************************\r\ntry:\r\n from Utils import *\r\n Utils = Class_Utils()\r\n Utils.Get_Values()\r\n #------- DNS NAME ---------\r\n ODBC_DSN_name = Utils.Get_ODBC_Name()\r\n Windows_Scaling = Utils.Get_Windows_Scaling()\r\n #--------------------------\r\nexcept:\r\n #------- DNS NAME ---------\r\n ODBC_DSN_name = \"BV\"\r\n Windows_Scaling = 1.0\r\n #--------------------------\r\n\r\n#print (Windows_Scaling)\r\n\r\ntry:\r\n from Calendar_Jorge import *\r\n Is_Calendar_Available = True\r\nexcept:\r\n print (\"********************************************************************************** \\n\")\r\n print (\"*** NO Calendar Library Found, please download it in order to access the Databases *** \\n\")\r\n print (\"********************************************************************************** \\n\")\r\n Is_Calendar_Available = False \r\n\r\ntry:\r\n from Country import *\r\n Is_Country_Available = True\r\n Country = Class_Country(ODBC_DSN_name,Windows_Scaling)\r\nexcept:\r\n print (\"********************************************************************************** \\n\")\r\n print (\"*** NO Country Library Found, please download it in order to access the Databases *** \\n\")\r\n print (\"********************************************************************************** \\n\")\r\n Is_Country_Available = False \r\n\r\ntry:\r\n from Region import *\r\n Is_Region_Available = True\r\n Region = Class_Region(ODBC_DSN_name,Windows_Scaling)\r\nexcept:\r\n print (\"********************************************************************************** \\n\")\r\n print (\"*** NO Region Library Found, please download it in order to access the Databases *** \\n\")\r\n print (\"********************************************************************************** \\n\")\r\n Is_Region_Available = False \r\n\r\ntry:\r\n from Facility import *\r\n Is_Facility_Available = True\r\n Location = []\r\n Facility = Class_Facility(ODBC_DSN_name,Windows_Scaling,Location)\r\nexcept:\r\n print (\"********************************************************************************** \\n\")\r\n print (\"*** NO Facility Library Found, please download it in order to access the Databases *** \\n\")\r\n print (\"********************************************************************************** \\n\")\r\n Is_Facility_Available = False \r\n\r\ntry:\r\n from Sites import *\r\n Is_Sites_Available = True\r\n Sites = Class_Sites(ODBC_DSN_name,Windows_Scaling)\r\nexcept:\r\n print (\"********************************************************************************** \\n\")\r\n print (\"*** NO Sites Library Found, please download it in order to access the Databases *** \\n\")\r\n print (\"********************************************************************************** \\n\")\r\n Is_Sites_Available = False \r\n\r\ntry:\r\n from Circuits import *\r\n Is_Circuit_Available = True\r\n Location = []\r\n Circuit = Class_Circuits(ODBC_DSN_name,Windows_Scaling,Location)\r\nexcept:\r\n print (\"********************************************************************************** \\n\")\r\n print (\"*** NO Circuits Library Found, please download it in order to access the Databases *** \\n\")\r\n print (\"********************************************************************************** \\n\")\r\n Is_Circuit_Available = False \r\n\r\ntry:\r\n from ICMP import *\r\n Is_ICMP_Available = True\r\n Location = []\r\n ICMP = Class_ICMP(ODBC_DSN_name,Windows_Scaling,Location)\r\nexcept:\r\n print (\"********************************************************************************** \\n\")\r\n print (\"*** NO ICMP Library Found, please download it in order to access the Databases *** \\n\")\r\n print (\"********************************************************************************** \\n\")\r\n Is_ICMP_Available = False \r\n\r\ntry:\r\n from LocalPointOfContacts import *\r\n Is_LocalPointOfContacts_Available = True\r\n Location = []\r\n LocalPointOfContacts = Class_LocalPointOfContacts(ODBC_DSN_name,Windows_Scaling,Location)\r\nexcept:\r\n print (\"********************************************************************************** \\n\")\r\n print (\"*** NO Local Point Of Contacts Library Found, please download it in order to access the Databases *** \\n\")\r\n print (\"********************************************************************************** \\n\")\r\n Is_LocalPointOfContacts_Available = False \r\n\r\ntry:\r\n from Logging import *\r\n Is_logging_Available = True\r\n Parameter = []\r\n Parameter = ['Device','OPEN Window'] \r\n Logging = Class_Logging(ODBC_DSN_name,Parameter)\r\n Logging.Log(Parameter)\r\nexcept:\r\n print (\"********************************************************************************** \\n\")\r\n print (\"*** NO Logging Library Found, please download it in order to access the Databases *** \\n\")\r\n print (\"********************************************************************************** \\n\")\r\n Is_logging_Available = False\r\n\r\n\r\n#*************************************************************\r\n# ==================== Libraries Required =============*\r\n#*************************************************************\r\n\r\nclass Class_Device:\r\n\r\n def __init__(self,DSN_Name,Windows_Scaling,Location): \r\n self.ODBC_name = DSN_Name\r\n self.db = ODBC(self.ODBC_name)\r\n self.version = self.db.Get_Version()\r\n self.DeviceWindowExist = False\r\n self.DeviceCalendarInstalledDateExist = False\r\n self.DeviceCalendarActivatedDateExist = False\r\n self.DeviceCalendarDisconnectedDateExist = False\r\n self.DeviceCalendarExpirationDateExist = False\r\n self.Username = os.getlogin()\r\n self.date = \"\"\r\n self.Windows_Scaling = Windows_Scaling\r\n self.Selection = 'none'\r\n self.GetPasswordWindowsExists = False\r\n self.Go_To_Location = False\r\n if (len(Location) > 0):\r\n self.Init_Country = Location[0]\r\n self.Init_Region = Location[1]\r\n self.Init_Facility = Location[2]\r\n self.Init_Site = Location[3]\r\n self.Go_To_Location = True\r\n\r\n def treeview_sort_column(self,tv, col, reverse):\r\n #print('sorting %s!' % col)\r\n l = [(tv.set(k, col), k) for k in tv.get_children('')]\r\n l.sort(reverse=reverse)\r\n\r\n # rearrange items in sorted positions\r\n for index, (val, k) in enumerate(l):\r\n #print('Moving Index:%r, Value:%r, k:%r' % (index, val, k))\r\n tv.move(k, '', index)\r\n\r\n # reverse sort next time\r\n tv.heading(col, command=lambda: self.treeview_sort_column(tv, col, not reverse))\r\n \r\n\r\n def IPFormatCheck(self,ip_str):\r\n if len(ip_str.split()) == 1:\r\n ipList = ip_str.split('.')\r\n if len(ipList) == 4:\r\n for i, item in enumerate(ipList):\r\n try:\r\n ipList[i] = int(item)\r\n except:\r\n return False\r\n if not isinstance(ipList[i], int):\r\n return False\r\n if max(ipList) < 256:\r\n return True\r\n else:\r\n return False\r\n else:\r\n return False\r\n else:\r\n return False\r\n\r\n#****************************************************************************************\r\n#---------------------------- SCREEN SELECTION SECTION ------------------------*\r\n#****************************************************************************************\r\n \r\n def Clean_Screen(self,option,option2):\r\n # Setup Buttons\r\n\r\n #self.DeviceBusinessUnitPowerCheckbutton.select()\r\n #print (self.varpower.get())\r\n self.data_ready = False\r\n if (option == 'country'): ## The option are country,region and Device\r\n self.ComboBoxRegionID.set(\"\")\r\n self.ComboBoxRegionID['state'] = DISABLED\r\n self.ComboBoxFacilityID.set(\"\")\r\n self.ComboBoxFacilityID['state'] = DISABLED\r\n self.ComboBoxSitesID.set(\"\")\r\n self.ComboBoxSitesID['state'] = DISABLED\r\n self.ButtonDeviceOK['state'] = DISABLED # Due to Edit\r\n if (option2 != 'country-combo'):\r\n self.ComboBoxCoutryID.set(\"\")\r\n self.ComboBoxRegionID['state'] = DISABLED\r\n self.ComboBoxFacilityID['state'] = DISABLED\r\n self.ComboBoxSitesID['state'] = DISABLED\r\n if (Is_Region_Available):\r\n self.ButtonRegionAdd['state'] = DISABLED\r\n self.ButtonRegionRefresh['state'] = DISABLED\r\n if (Is_Facility_Available):\r\n self.ButtonFacilityAdd['state'] = DISABLED\r\n self.ButtonFacilityRefresh['state'] = DISABLED\r\n if (Is_Sites_Available):\r\n self.ButtonSitesAdd['state'] = DISABLED\r\n self.ButtonSitesRefresh['state'] = DISABLED\r\n\r\n if (option == 'region'):\r\n self.ComboBoxFacilityID.set(\"\")\r\n self.ComboBoxFacilityID['state'] = DISABLED\r\n self.ComboBoxSitesID.set(\"\")\r\n self.ComboBoxSitesID['state'] = DISABLED\r\n self.ButtonDeviceOK['state'] = DISABLED # Due to Edit\r\n if (option2 != 'region-combo'):\r\n self.ComboBoxRegionID.set(\"\")\r\n if (Is_Facility_Available):\r\n self.ButtonFacilityAdd['state'] = DISABLED\r\n self.ButtonFacilityRefresh['state'] = DISABLED\r\n if (Is_Sites_Available):\r\n self.ButtonSitesAdd['state'] = DISABLED\r\n self.ButtonSitesRefresh['state'] = DISABLED\r\n\r\n if (option == 'facility'):\r\n self.ComboBoxSitesID.set(\"\")\r\n self.ComboBoxSitesID['state'] = DISABLED\r\n self.ButtonDeviceOK['state'] = DISABLED # Due to Edit\r\n if (option2 != 'facility-combo'):\r\n self.ComboBoxFacilityID.set(\"\")\r\n if (Is_Sites_Available):\r\n self.ButtonSitesAdd['state'] = DISABLED\r\n self.ButtonSitesRefresh['state'] = DISABLED\r\n\r\n if (option2 == 'sites-combo'):\r\n if (self.Selection != 'edit'):\r\n self.ButtonDeviceAdd['state'] = ACTIVE\r\n if (self.Selection == 'edit'):\r\n self.ButtonDeviceOK['state'] = ACTIVE # Due to Edit\r\n else:\r\n self.ButtonDeviceAdd['state'] = DISABLED\r\n\r\n if (self.Selection != 'edit'):\r\n self.ButtonDeviceEdit['state'] = DISABLED\r\n self.ButtonDeviceRemove['state'] = DISABLED\r\n self.ButtonDeviceOK['state'] = DISABLED\r\n self.ButtonDeviceCancel['state'] = DISABLED\r\n self.ButtonDeviceCircuits['state'] = DISABLED\r\n self.ButtonDevicePing64['state'] = DISABLED\r\n self.ButtonDevicePing1500['state'] = DISABLED\r\n #self.ButtonDeviceContacts['state'] = DISABLED\r\n self.ButtonDeviceICMP['state'] = DISABLED\r\n self.ButtonDeviceLocalPointOfContacts['state'] = DISABLED\r\n\r\n # Create Progress Bar\r\n self.progress['maximum'] = 100\r\n self.progress['value'] = 0\r\n\r\n # Setup Labels and Entry\r\n self.DeviceIDFrameEntry['state'] = 'normal'\r\n self.DeviceIDFrameEntry.delete(0,END)\r\n self.DeviceIDFrameEntry['state'] = 'readonly'\r\n\r\n self.DeviceDescriptionFrameEntry['state'] = 'normal'\r\n self.DeviceDescriptionFrameEntry.delete(0,END)\r\n self.DeviceDescriptionFrameEntry['state'] = 'readonly'\r\n\r\n # Setup Labels and Entry\r\n self.DeviceIDFrameEntry['state'] = 'normal'\r\n self.DeviceIDFrameEntry.delete(0,END)\r\n self.DeviceIDFrameEntry['state'] = 'readonly'\r\n \r\n self.DeviceDescriptionFrameEntry['state'] = 'normal'\r\n self.DeviceDescriptionFrameEntry.delete(0,END)\r\n self.DeviceDescriptionFrameEntry['state'] = 'readonly'\r\n\r\n self.DeviceComboBoxTypeID.current(0)\r\n self.DeviceComboBoxTypeID['state'] = DISABLED\r\n\r\n self.DeviceComboBoxModelID.current(0)\r\n self.DeviceComboBoxModelID['state'] = DISABLED\r\n\r\n self.DeviceComboBoxStatus.current(0)\r\n self.DeviceComboBoxStatus['state'] = DISABLED\r\n\r\n self.DeviceButtonInstalledDate['state'] = DISABLED\r\n self.DeviceButtonActivatedDate['state'] = DISABLED\r\n self.DeviceButtonDisconnectedDate['state'] = DISABLED\r\n self.DeviceButtonExpirationDate['state'] = DISABLED\r\n\r\n\r\n self.DeviceIPAddressFrameEntry['state'] = 'normal'\r\n self.DeviceIPAddressFrameEntry.delete(0,END)\r\n self.DeviceIPAddressFrameEntry['state'] = 'readonly'\r\n\r\n # Setup Labels and Button Calendars Installed, Activated, Disconnected\r\n self.DeviceInstalledDateFrameEntry['state'] = 'normal'\r\n self.DeviceInstalledDateFrameEntry.delete(0,END)\r\n self.DeviceInstalledDateFrameEntry['state'] = 'readonly'\r\n\r\n self.DeviceContractNoFrameEntry['state'] = 'normal'\r\n self.DeviceContractNoFrameEntry.delete(0,END)\r\n self.DeviceContractNoFrameEntry['state'] = 'readonly'\r\n\r\n self.DeviceExpirationDateFrameEntry['state'] = 'normal'\r\n self.DeviceExpirationDateFrameEntry.delete(0,END)\r\n self.DeviceExpirationDateFrameEntry['state'] = 'readonly'\r\n\r\n self.DeviceActivatedDateFrameEntry['state'] = 'normal'\r\n self.DeviceActivatedDateFrameEntry.delete(0,END)\r\n self.DeviceActivatedDateFrameEntry['state'] = 'readonly'\r\n\r\n self.DeviceSerialNoFrameEntry['state'] = 'normal'\r\n self.DeviceSerialNoFrameEntry.delete(0,END)\r\n self.DeviceSerialNoFrameEntry['state'] = 'readonly'\r\n\r\n self.DeviceMACAddressFrameEntry['state'] = 'normal'\r\n self.DeviceMACAddressFrameEntry.delete(0,END)\r\n self.DeviceMACAddressFrameEntry['state'] = 'readonly'\r\n\r\n self.DeviceDisconnectedDateFrameEntry['state'] = 'normal'\r\n self.DeviceDisconnectedDateFrameEntry.delete(0,END)\r\n self.DeviceDisconnectedDateFrameEntry['state'] = 'readonly'\r\n\r\n self.DeviceOutSourceCostFrameEntry['state'] = 'normal'\r\n self.DeviceOutSourceCostFrameEntry.delete(0,END)\r\n self.DeviceOutSourceCostFrameEntry['state'] = 'readonly'\r\n\r\n self.DeviceMaintenanceCostFrameEntry['state'] = 'normal'\r\n self.DeviceMaintenanceCostFrameEntry.delete(0,END)\r\n self.DeviceMaintenanceCostFrameEntry['state'] = 'readonly'\r\n\r\n self.DeviceNotesFrameEntry['state'] = 'normal'\r\n self.DeviceNotesFrameEntry.delete(0,END)\r\n self.DeviceNotesFrameEntry['state'] = 'readonly'\r\n\r\n\r\n ##############################\r\n\r\n self.DeviceNATIPAddressFrameEntry['state'] = 'normal'\r\n self.DeviceNATIPAddressFrameEntry.delete(0,END)\r\n self.DeviceNATIPAddressFrameEntry['state'] = 'readonly'\r\n \r\n self.DeviceMgmtIPAddressFrameEntry['state'] = 'normal'\r\n self.DeviceMgmtIPAddressFrameEntry.delete(0,END)\r\n self.DeviceMgmtIPAddressFrameEntry['state'] = 'readonly'\r\n \r\n self.DeviceComboBoxICMPCapable.current(0)\r\n self.DeviceComboBoxICMPCapable['state'] = DISABLED\r\n\r\n self.DeviceComboBoxICMPMonitor.current(0)\r\n self.DeviceComboBoxICMPMonitor['state'] = DISABLED\r\n\r\n self.DeviceLastICMPDateFrameEntry['state'] = 'normal'\r\n self.DeviceLastICMPDateFrameEntry.delete(0,END)\r\n self.DeviceLastICMPDateFrameEntry['state'] = 'readonly'\r\n\r\n self.DeviceLastICMPStatusFrameEntry['state'] = 'normal'\r\n self.DeviceLastICMPStatusFrameEntry.delete(0,END)\r\n self.DeviceLastICMPStatusFrameEntry['state'] = 'readonly'\r\n\r\n self.DeviceLastCMDBStatusFrameEntry['state'] = 'normal'\r\n self.DeviceLastCMDBStatusFrameEntry.delete(0,END)\r\n self.DeviceLastCMDBStatusFrameEntry['state'] = 'readonly'\r\n \r\n ##############################\r\n\r\n #------------------------------- Deleting Tree View --------\r\n x = self.DeviceTreeview.get_children()\r\n if x != '()': # checks if there is something in the first row\r\n for child in x:\r\n #print (child)\r\n self.DeviceTreeview.delete(child)\r\n #------------------------------- Deleting Tree View --------\r\n\r\n def Display_Screen(self,curItem): \r\n # Create Progress Bar\r\n self.Get_Type_Model_and_Satus()\r\n self.progress['maximum'] = 100\r\n self.progress['value'] = 0\r\n\r\n '''\r\n self.DeviceTablePriaryKeyArray[i],\r\n #self.DeviceTableDeviceDescriptionArray[i], \r\n #self.DeviceTableCountryIDArray[i],\r\n #self.DeviceTableRegionIDArray[i],\r\n #self.DeviceTableFacilityIDArray[i],\r\n #self.DeviceTableSiteIDArray[i],\r\n self.DeviceTableDeviceTypeIDArray[i],\r\n self.DeviceTableIP4AddressArray[i],\r\n #self.DeviceTableIP6AddressArray[i],\r\n self.DeviceTableContractNoArray[i],\r\n self.DeviceTableOutsourceCostArray[i],\r\n self.DeviceTableMaintenanceCostArray[i],\r\n self.DeviceTableStatusArray[i],\r\n #self.DeviceTableMonthlyCostArray[i],\r\n self.DeviceTableDateInstalledArray[i],\r\n #self.DeviceTableDayInstalledArray[i],\r\n #self.DeviceTableMonthInstalledArray[i],\r\n #self.DeviceTableYearInstalledArray[i],Get_Type\r\n self.DeviceTableDateActivatedArray[i],\r\n #self.DeviceTableDayActivatedArray[i],\r\n #self.DeviceTableMonthActivatedArray[i],\r\n #self.DeviceTableYearActivatedArray[i],\r\n self.DeviceTableDisconectedDateArray[i],\r\n #self.DeviceTableDayDisconectedArray[i],\r\n #self.DeviceTableMonthDisconectedArray[i],\r\n #self.DeviceTableYearDisconectedArray[i],\r\n self.DeviceTableExpirationDateArray[i],\r\n #self.DeviceTableDayExpirationArray[i],\r\n #self.DeviceTableMonthExpirationArray[i],\r\n #self.DeviceTableYearExpirationArray[i],\r\n self.DeviceTableSerilaNoArray[i],\r\n self.DeviceTableExecutedByArray[i],\r\n #self.DeviceTableNotesArray[i],\r\n self.DeviceTableDeviceModelIDArray[i],\r\n #self.DeviceTableMACAddressArray[i]\r\n '''\r\n # Setup Labels and Entry\r\n self.DeviceIDFrameEntry['state'] = 'normal'\r\n self.DeviceIDFrameEntry.delete(0,END)\r\n self.DeviceIDFrameEntry.insert(0,self.DeviceTablePriaryKeyArray[curItem])\r\n self.DeviceIDFrameEntry['state'] = 'readonly'\r\n \r\n self.DeviceDescriptionFrameEntry['state'] = 'normal'\r\n self.DeviceDescriptionFrameEntry.delete(0,END)\r\n self.DeviceDescriptionFrameEntry.insert(0,self.DeviceTableDeviceDescriptionArray[curItem])\r\n self.DeviceDescriptionFrameEntry['state'] = 'readonly'\r\n\r\n # Find Type in the Array\r\n i = 0\r\n self.DeviceComboBoxTypeID.current(i)\r\n while (i < len(self.DeviceTypeIDArray)):\r\n if (self.DeviceTableDeviceTypeIDArray[curItem]== self.DeviceTypeIDArray[i]):\r\n self.DeviceComboBoxTypeID.current(i)\r\n i = i + len(self.DeviceTypeIDArray) \r\n else:\r\n i = i + 1\r\n # find Model in the Array\r\n i = 0\r\n self.DeviceComboBoxModelID.current(i)\r\n while (i < len(self.DeviceModelIDArray)):\r\n if (self.DeviceTableDeviceModelIDArray[curItem]== self.DeviceModelIDArray[i]):\r\n self.DeviceComboBoxModelID.current(i)\r\n i = i + len(self.DeviceModelIDArray) \r\n else:\r\n i = i + 1 # find Status in the Array\r\n i = 0\r\n while (i < len(self.DeviceStatusValues)):\r\n if (self.DeviceTableStatusArray[curItem]== self.DeviceStatusValues[i]):\r\n self.DeviceComboBoxStatus.current(i)\r\n i = i + len(self.DeviceStatusValues) \r\n else:\r\n i = i + 1\r\n\r\n self.DeviceButtonInstalledDate['state'] = DISABLED\r\n self.DeviceButtonActivatedDate['state'] = DISABLED\r\n self.DeviceButtonDisconnectedDate['state'] = DISABLED\r\n self.DeviceButtonExpirationDate['state'] = DISABLED\r\n\r\n\r\n self.DeviceIPAddressFrameEntry['state'] = 'normal'\r\n self.DeviceIPAddressFrameEntry.delete(0,END)\r\n self.DeviceIPAddressFrameEntry.insert(0,self.DeviceTableIP4AddressArray[curItem])\r\n self.DeviceIPAddressFrameEntry['state'] = 'readonly'\r\n\r\n # Setup Labels and Button Calendars Installed, Activated, Disconnected\r\n self.DeviceInstalledDateFrameEntry['state'] = 'normal'\r\n self.DeviceInstalledDateFrameEntry.delete(0,END)\r\n if (self.DeviceTableDateInstalledArray[curItem] == None):\r\n self.DeviceInstalledDateFrameEntry.insert(0,\" \")\r\n else:\r\n self.DeviceInstalledDateFrameEntry.insert(0,self.DeviceTableDateInstalledArray[curItem])\r\n self.DeviceInstalledDateFrameEntry['state'] = 'readonly'\r\n\r\n self.DeviceContractNoFrameEntry['state'] = 'normal'\r\n self.DeviceContractNoFrameEntry.delete(0,END)\r\n if (self.DeviceTableContractNoArray[curItem] == None):\r\n self.DeviceContractNoFrameEntry.insert(0,\" \")\r\n else:\r\n self.DeviceContractNoFrameEntry.insert(0,self.DeviceTableContractNoArray[curItem])\r\n self.DeviceContractNoFrameEntry['state'] = 'readonly'\r\n\r\n self.DeviceExpirationDateFrameEntry['state'] = 'normal'\r\n self.DeviceExpirationDateFrameEntry.delete(0,END)\r\n if (self.DeviceTableExpirationDateArray[curItem] == None):\r\n self.DeviceExpirationDateFrameEntry.insert(0,\" \")\r\n else:\r\n self.DeviceExpirationDateFrameEntry.insert(0,self.DeviceTableExpirationDateArray[curItem])\r\n self.DeviceExpirationDateFrameEntry['state'] = 'readonly'\r\n\r\n self.DeviceActivatedDateFrameEntry['state'] = 'normal'\r\n self.DeviceActivatedDateFrameEntry.delete(0,END)\r\n if (self.DeviceTableDateActivatedArray[curItem] == None):\r\n self.DeviceActivatedDateFrameEntry.insert(0,\" \")\r\n else:\r\n self.DeviceActivatedDateFrameEntry.insert(0,self.DeviceTableDateActivatedArray[curItem])\r\n self.DeviceActivatedDateFrameEntry['state'] = 'readonly'\r\n\r\n self.DeviceSerialNoFrameEntry['state'] = 'normal'\r\n self.DeviceSerialNoFrameEntry.delete(0,END)\r\n if (self.DeviceTableSerilaNoArray[curItem] == None):\r\n self.DeviceSerialNoFrameEntry.insert(0,\" \")\r\n else:\r\n self.DeviceSerialNoFrameEntry.insert(0,self.DeviceTableSerilaNoArray[curItem])\r\n self.DeviceSerialNoFrameEntry['state'] = 'readonly'\r\n\r\n self.DeviceMACAddressFrameEntry['state'] = 'normal'\r\n self.DeviceMACAddressFrameEntry.delete(0,END)\r\n if (self.DeviceTableMACAddressArray[curItem] == None):\r\n self.DeviceMACAddressFrameEntry.insert(0,\" \")\r\n else:\r\n self.DeviceMACAddressFrameEntry.insert(0,self.DeviceTableMACAddressArray[curItem])\r\n self.DeviceMACAddressFrameEntry['state'] = 'readonly'\r\n\r\n self.DeviceDisconnectedDateFrameEntry['state'] = 'normal'\r\n self.DeviceDisconnectedDateFrameEntry.delete(0,END)\r\n if (self.DeviceTableDisconectedDateArray[curItem] == None):\r\n self.DeviceTableDisconectedDateArray.insert(0,\" \")\r\n else:\r\n self.DeviceDisconnectedDateFrameEntry.insert(0,self.DeviceTableDisconectedDateArray[curItem])\r\n self.DeviceDisconnectedDateFrameEntry['state'] = 'readonly'\r\n\r\n self.DeviceOutSourceCostFrameEntry['state'] = 'normal'\r\n self.DeviceOutSourceCostFrameEntry.delete(0,END)\r\n self.DeviceOutSourceCostFrameEntry.insert(0,str(self.DeviceTableOutsourceCostArray[curItem]))\r\n self.DeviceOutSourceCostFrameEntry['state'] = 'readonly'\r\n\r\n self.DeviceMaintenanceCostFrameEntry['state'] = 'normal'\r\n self.DeviceMaintenanceCostFrameEntry.delete(0,END)\r\n self.DeviceMaintenanceCostFrameEntry.insert(0,str(self.DeviceTableMaintenanceCostArray[curItem]))\r\n self.DeviceMaintenanceCostFrameEntry['state'] = 'readonly'\r\n\r\n self.DeviceNotesFrameEntry['state'] = 'normal'\r\n self.DeviceNotesFrameEntry.delete(0,END)\r\n self.DeviceNotesFrameEntry.insert(0,self.DeviceTableNotesArray[curItem])\r\n self.DeviceNotesFrameEntry['state'] = 'readonly'\r\n\r\n\r\n ##############################\r\n \r\n self.DeviceNATIPAddressFrameEntry['state'] = 'normal'\r\n self.DeviceNATIPAddressFrameEntry.delete(0,END)\r\n self.DeviceNATIPAddressFrameEntry.insert(0,self.DeviceTableNATIP4AddressArray[curItem])\r\n self.DeviceNATIPAddressFrameEntry['state'] = 'readonly'\r\n \r\n self.DeviceMgmtIPAddressFrameEntry['state'] = 'normal'\r\n self.DeviceMgmtIPAddressFrameEntry.delete(0,END)\r\n self.DeviceMgmtIPAddressFrameEntry.insert(0,self.DeviceTableManagementIP4AddressArray[curItem])\r\n self.DeviceMgmtIPAddressFrameEntry['state'] = 'readonly'\r\n \r\n if (self.DeviceTableICMPCapableArray[curItem] == \"YES\"):\r\n self.DeviceComboBoxICMPCapable.current(1)\r\n else:\r\n self.DeviceComboBoxICMPCapable.current(0)\r\n self.DeviceComboBoxICMPCapable['state'] = DISABLED\r\n\r\n if (self.DeviceTableMonitorviaICMPArray[curItem] == \"YES\"):\r\n self.DeviceComboBoxICMPMonitor.current(1)\r\n else:\r\n self.DeviceComboBoxICMPMonitor.current(0)\r\n self.DeviceComboBoxICMPMonitor['state'] = DISABLED\r\n\r\n self.DeviceLastICMPDateFrameEntry['state'] = 'normal'\r\n self.DeviceLastICMPDateFrameEntry.delete(0,END)\r\n self.DeviceLastICMPDateFrameEntry.insert(0,self.DeviceTableLastSuccessICMPArray[curItem])\r\n self.DeviceLastICMPDateFrameEntry['state'] = 'readonly'\r\n\r\n self.DeviceLastICMPStatusFrameEntry['state'] = 'normal'\r\n self.DeviceLastICMPStatusFrameEntry.delete(0,END)\r\n self.DeviceLastICMPStatusFrameEntry.insert(0,self.DeviceTableLastICMPStatusArray[curItem])\r\n self.DeviceLastICMPStatusFrameEntry['state'] = 'readonly'\r\n\r\n self.DeviceLastCMDBStatusFrameEntry['state'] = 'normal'\r\n self.DeviceLastCMDBStatusFrameEntry.delete(0,END)\r\n self.DeviceLastCMDBStatusFrameEntry.insert(0,self.DeviceTableLastUpdatedCMDBDateArray[curItem])\r\n self.DeviceLastCMDBStatusFrameEntry['state'] = 'readonly'\r\n \r\n ##############################\r\n\r\n\r\n def Enable_Screen(self,option):\r\n # This function is used when the ADD button is selected\r\n\r\n #self.DeviceBusinessUnitPowerCheckbutton.select()\r\n #print (self.varpower.get())\r\n\r\n if (Is_Country_Available):\r\n self.ButtonCountryAdd['state'] = DISABLED\r\n self.ButtonCountryRefresh['state'] = DISABLED\r\n if (Is_Region_Available):\r\n self.ButtonRegionAdd['state'] = DISABLED\r\n self.ButtonRegionRefresh['state'] = DISABLED\r\n if (Is_Facility_Available):\r\n self.ButtonFacilityAdd['state'] = DISABLED\r\n self.ButtonFacilityRefresh['state'] = DISABLED\r\n if (Is_Sites_Available):\r\n self.ButtonSitesAdd['state'] = DISABLED\r\n self.ButtonSitesRefresh['state'] = DISABLED\r\n\r\n \r\n self.ButtonDeviceAdd['state'] = DISABLED\r\n self.ButtonDeviceEdit['state'] = DISABLED\r\n self.ButtonDeviceRemove['state'] = DISABLED\r\n self.ButtonDeviceOK['state'] = ACTIVE\r\n self.ButtonDeviceCancel['state'] = ACTIVE\r\n self.ButtonDeviceCircuits['state'] = DISABLED\r\n self.ButtonDevicePing64['state'] = DISABLED\r\n self.ButtonDevicePing1500['state'] = DISABLED\r\n #self.ButtonDeviceContacts['state'] = DISABLED\r\n self.ButtonDeviceICMP['state'] = DISABLED\r\n self.ButtonDeviceLocalPointOfContacts['state'] = DISABLED\r\n\r\n # Create Progress Bar\r\n self.progress['maximum'] = 100\r\n self.progress['value'] = 0\r\n\r\n # Setup Labels and Entry\r\n if (option == 'add'): #<----------------------------------- ADD Button\r\n self.ComboBoxCoutryID['state'] = DISABLED\r\n self.ComboBoxRegionID['state'] = DISABLED\r\n self.ComboBoxFacilityID['state'] = DISABLED\r\n self.ComboBoxSitesID['state'] = DISABLED\r\n\r\n self.Get_Type_Model_and_Satus()\r\n self.DeviceIDFrameEntry['state'] = 'normal'\r\n self.DeviceIDFrameEntry.delete(0,END)\r\n\r\n self.DeviceDescriptionFrameEntry['state'] = 'normal'\r\n self.DeviceDescriptionFrameEntry.delete(0,END)\r\n\r\n # Calendars:\r\n self.DeviceButtonInstalledDate['state'] = ACTIVE\r\n self.DeviceButtonActivatedDate['state'] = ACTIVE\r\n self.DeviceButtonDisconnectedDate['state'] = ACTIVE\r\n self.DeviceButtonExpirationDate['state'] = ACTIVE\r\n\r\n self.DeviceComboBoxTypeID['state'] = DISABLED\r\n self.DeviceComboBoxModelID['state'] = DISABLED\r\n self.DeviceComboBoxStatus['state'] = DISABLED\r\n\r\n self.DeviceInstalledDateFrameEntry['state'] = 'normal'\r\n self.DeviceInstalledDateFrameEntry.delete(0,END)\r\n self.DeviceInstalledDateFrameEntry['state'] = 'readonly'\r\n \r\n self.DeviceActivatedDateFrameEntry['state'] = 'normal'\r\n self.DeviceActivatedDateFrameEntry.delete(0,END)\r\n self.DeviceActivatedDateFrameEntry['state'] = 'readonly'\r\n \r\n self.DeviceDisconnectedDateFrameEntry['state'] = 'normal'\r\n self.DeviceDisconnectedDateFrameEntry.delete(0,END)\r\n self.DeviceDisconnectedDateFrameEntry['state'] = 'readonly'\r\n\r\n self.DeviceExpirationDateFrameEntry['state'] = 'normal'\r\n self.DeviceExpirationDateFrameEntry.delete(0,END)\r\n self.DeviceExpirationDateFrameEntry['state'] = 'readonly'\r\n\r\n self.DeviceComboBoxTypeID['state'] = 'readonly'\r\n self.DeviceComboBoxModelID['state'] = 'disabled'\r\n self.DeviceComboBoxStatus['state'] = 'readonly'\r\n\r\n self.DeviceIPAddressFrameEntry['state'] = 'normal'\r\n self.DeviceIPAddressFrameEntry.delete(0,END)\r\n self.DeviceIPAddressFrameEntry.insert(0,'0.0.0.0')\r\n\r\n self.DeviceInstalledDateFrameEntry['state'] = 'readonly'\r\n self.DeviceInstalledDateFrameEntry.delete(0,END)\r\n\r\n self.DeviceContractNoFrameEntry['state'] = 'normal'\r\n self.DeviceContractNoFrameEntry.delete(0,END)\r\n\r\n self.DeviceExpirationDateFrameEntry['state'] = 'readonly'\r\n self.DeviceExpirationDateFrameEntry.delete(0,END)\r\n\r\n self.DeviceActivatedDateFrameEntry['state'] = 'readonly'\r\n self.DeviceActivatedDateFrameEntry.delete(0,END)\r\n\r\n self.DeviceSerialNoFrameEntry['state'] = 'normal'\r\n self.DeviceSerialNoFrameEntry.delete(0,END)\r\n\r\n self.DeviceMACAddressFrameEntry['state'] = 'normal'\r\n self.DeviceMACAddressFrameEntry.delete(0,END)\r\n\r\n self.DeviceDisconnectedDateFrameEntry['state'] = 'readonly'\r\n self.DeviceDisconnectedDateFrameEntry.delete(0,END)\r\n\r\n self.DeviceOutSourceCostFrameEntry['state'] = 'normal'\r\n self.DeviceOutSourceCostFrameEntry.delete(0,END)\r\n\r\n self.DeviceMaintenanceCostFrameEntry['state'] = 'normal'\r\n self.DeviceMaintenanceCostFrameEntry.delete(0,END)\r\n\r\n self.DeviceNotesFrameEntry['state'] = 'normal'\r\n self.DeviceNotesFrameEntry.delete(0,END)\r\n\r\n ##############################\r\n \r\n self.DeviceNATIPAddressFrameEntry['state'] = 'normal'\r\n self.DeviceNATIPAddressFrameEntry.delete(0,END)\r\n self.DeviceNATIPAddressFrameEntry.insert(0,'0.0.0.0')\r\n \r\n self.DeviceMgmtIPAddressFrameEntry['state'] = 'normal'\r\n self.DeviceMgmtIPAddressFrameEntry.delete(0,END)\r\n self.DeviceMgmtIPAddressFrameEntry.insert(0,'0.0.0.0')\r\n \r\n self.DeviceComboBoxICMPCapable.current(1)\r\n self.DeviceComboBoxICMPCapable['state'] = ACTIVE\r\n\r\n self.DeviceComboBoxICMPMonitor.current(0)\r\n self.DeviceComboBoxICMPMonitor['state'] = ACTIVE\r\n\r\n self.DeviceLastICMPDateFrameEntry['state'] = 'normal'\r\n self.DeviceLastICMPDateFrameEntry.delete(0,END)\r\n self.DeviceLastICMPDateFrameEntry.insert(0,'Never')\r\n self.DeviceLastICMPDateFrameEntry['state'] = 'readonly'\r\n\r\n self.DeviceLastICMPStatusFrameEntry['state'] = 'normal'\r\n self.DeviceLastICMPStatusFrameEntry.delete(0,END)\r\n self.DeviceLastICMPStatusFrameEntry.insert(0,'Never')\r\n self.DeviceLastICMPStatusFrameEntry['state'] = 'readonly'\r\n\r\n self.DeviceLastCMDBStatusFrameEntry['state'] = 'normal'\r\n self.DeviceLastCMDBStatusFrameEntry.delete(0,END)\r\n self.DeviceLastCMDBStatusFrameEntry.insert(0,'Never')\r\n self.DeviceLastCMDBStatusFrameEntry['state'] = 'readonly'\r\n \r\n ##############################\r\n\r\n\r\n if (option == 'edit'): #<----------------------------------- EDIT Button\r\n self.ComboBoxCoutryID['state'] = ACTIVE\r\n self.ComboBoxRegionID['state'] = ACTIVE\r\n self.ComboBoxFacilityID['state'] = ACTIVE\r\n self.ComboBoxSitesID['state'] = ACTIVE\r\n\r\n #self.Get_Type_Model_and_Satus() # <------------------ I might have to modified it\r\n self.DeviceIDFrameEntry['state'] = 'readonly'\r\n self.DeviceDescriptionFrameEntry['state'] = 'normal'\r\n # Calendars:\r\n self.DeviceButtonInstalledDate['state'] = ACTIVE\r\n self.DeviceButtonActivatedDate['state'] = ACTIVE\r\n self.DeviceButtonDisconnectedDate['state'] = ACTIVE\r\n self.DeviceButtonExpirationDate['state'] = ACTIVE\r\n\r\n self.DeviceInstalledDateFrameEntry['state'] = 'readonly' \r\n self.DeviceActivatedDateFrameEntry['state'] = 'readonly'\r\n self.DeviceDisconnectedDateFrameEntry['state'] = 'readonly'\r\n self.DeviceExpirationDateFrameEntry['state'] = 'readonly'\r\n\r\n self.DeviceComboBoxTypeID['state'] = 'readonly'\r\n self.DeviceComboBoxModelID['state'] = 'disabled'\r\n self.DeviceComboBoxStatus['state'] = 'readonly'\r\n\r\n self.DeviceIPAddressFrameEntry['state'] = 'normal'\r\n self.DeviceInstalledDateFrameEntry['state'] = 'readonly'\r\n self.DeviceContractNoFrameEntry['state'] = 'normal'\r\n self.DeviceExpirationDateFrameEntry['state'] = 'readonly'\r\n self.DeviceActivatedDateFrameEntry['state'] = 'readonly'\r\n self.DeviceSerialNoFrameEntry['state'] = 'normal'\r\n self.DeviceMACAddressFrameEntry['state'] = 'normal'\r\n self.DeviceDisconnectedDateFrameEntry['state'] = 'readonly'\r\n self.DeviceOutSourceCostFrameEntry['state'] = 'normal'\r\n self.DeviceMaintenanceCostFrameEntry['state'] = 'normal'\r\n self.DeviceNotesFrameEntry['state'] = 'normal'\r\n\r\n\r\n ##############################\r\n\r\n self.DeviceNATIPAddressFrameEntry['state'] = 'normal' \r\n self.DeviceMgmtIPAddressFrameEntry['state'] = 'normal'\r\n self.DeviceComboBoxICMPCapable['state'] = ACTIVE\r\n self.DeviceComboBoxICMPMonitor['state'] = ACTIVE\r\n self.DeviceLastICMPDateFrameEntry['state'] = 'readonly'\r\n self.DeviceLastICMPStatusFrameEntry['state'] = 'readonly'\r\n self.DeviceLastCMDBStatusFrameEntry['state'] = 'readonly'\r\n \r\n ##############################\r\n \r\n \r\n def Disable_Screen(self):\r\n # This function is used when the entry was added.modified to the Database\r\n\r\n #self.DeviceBusinessUnitPowerCheckbutton.select()\r\n #print (self.varpower.get())\r\n\r\n self.ComboBoxCoutryID['state'] = 'readonly'\r\n self.ComboBoxRegionID['state'] = 'readonly'\r\n self.ComboBoxFacilityID['state'] = 'readonly'\r\n self.ComboBoxSitesID['state'] = 'readonly'\r\n if (Is_Country_Available):\r\n self.ButtonCountryAdd['state'] = ACTIVE\r\n self.ButtonCountryRefresh['state'] = ACTIVE\r\n if (Is_Region_Available):\r\n self.ButtonRegionAdd['state'] = ACTIVE\r\n self.ButtonRegionRefresh['state'] = ACTIVE\r\n if (Is_Facility_Available):\r\n self.ButtonFacilityAdd['state'] = ACTIVE\r\n self.ButtonFacilityRefresh['state'] = ACTIVE\r\n if (Is_Sites_Available):\r\n self.ButtonSitesAdd['state'] = ACTIVE\r\n self.ButtonSitesRefresh['state'] = ACTIVE\r\n \r\n self.ButtonDeviceAdd['state'] = ACTIVE\r\n self.ButtonDeviceEdit['state'] = DISABLED\r\n self.ButtonDeviceRemove['state'] = DISABLED\r\n self.ButtonDeviceOK['state'] = DISABLED\r\n self.ButtonDeviceCancel['state'] = DISABLED # ACTIVE\r\n self.ButtonDeviceCircuits['state'] = DISABLED\r\n self.ButtonDevicePing64['state'] = DISABLED\r\n self.ButtonDevicePing1500['state'] = DISABLED\r\n #self.ButtonDeviceContacts['state'] = DISABLED\r\n self.ButtonDeviceICMP['state'] = DISABLED\r\n self.ButtonDeviceLocalPointOfContacts['state'] = DISABLED\r\n\r\n # Create Progress Bar\r\n self.progress['maximum'] = 100\r\n self.progress['value'] = 0\r\n\r\n # Setup Labels and Entry\r\n self.DeviceIDFrameEntry['state'] = 'readonly' \r\n self.DeviceDescriptionFrameEntry['state'] = 'readonly'\r\n self.DeviceComboBoxTypeID['state'] = 'readonly'\r\n self.DeviceComboBoxModelID['state'] = 'readonly'\r\n self.DeviceComboBoxStatus['state'] = 'readonly'\r\n self.DeviceIPAddressFrameEntry['state'] = 'readonly'\r\n self.DeviceInstalledDateFrameEntry['state'] = 'readonly'\r\n self.DeviceContractNoFrameEntry['state'] = 'readonly'\r\n self.DeviceExpirationDateFrameEntry['state'] = 'readonly'\r\n self.DeviceActivatedDateFrameEntry['state'] = 'readonly'\r\n self.DeviceSerialNoFrameEntry['state'] = 'readonly'\r\n self.DeviceMACAddressFrameEntry['state'] = 'readonly'\r\n self.DeviceDisconnectedDateFrameEntry['state'] = 'readonly'\r\n self.DeviceOutSourceCostFrameEntry['state'] = 'readonly'\r\n self.DeviceMaintenanceCostFrameEntry['state'] = 'readonly'\r\n self.DeviceNotesFrameEntry['state'] = 'readonly'\r\n # Calendars:\r\n self.DeviceButtonInstalledDate['state'] = DISABLED\r\n self.DeviceButtonActivatedDate['state'] = DISABLED\r\n self.DeviceButtonDisconnectedDate['state'] = DISABLED\r\n self.DeviceButtonExpirationDate['state'] = DISABLED\r\n\r\n self.DeviceComboBoxTypeID['state'] = DISABLED\r\n self.DeviceComboBoxModelID['state'] = DISABLED\r\n self.DeviceComboBoxStatus['state'] = DISABLED\r\n\r\n ##############################\r\n\r\n self.DeviceNATIPAddressFrameEntry['state'] = 'readonly' \r\n self.DeviceMgmtIPAddressFrameEntry['state'] = 'readonly'\r\n self.DeviceComboBoxICMPCapable['state'] = DISABLED\r\n self.DeviceComboBoxICMPMonitor['state'] = DISABLED\r\n self.DeviceLastICMPDateFrameEntry['state'] = 'readonly'\r\n self.DeviceLastICMPStatusFrameEntry['state'] = 'readonly'\r\n self.DeviceLastCMDBStatusFrameEntry['state'] = 'readonly'\r\n \r\n ##############################\r\n\r\n \r\n\r\n def Collect_Screen(self):\r\n # This function is used when the ADD button is selected\r\n\r\n self.CountryID = self.CountryIDArray[self.ComboBoxCoutryID.current()]\r\n self.RegionID = self.RegionIDArray[self.ComboBoxRegionID.current()]\r\n self.FacilityID = self.FacilityIDArray[self.ComboBoxFacilityID.current()]\r\n self.SitesID = self.SitesIDArray[self.ComboBoxSitesID.current()]\r\n \r\n self.DeviceID = self.DeviceIDFrameEntry.get()\r\n self.DeviceDescription = self.DeviceDescriptionFrameEntry.get() \r\n\r\n # Calendars:\r\n self.DeviceButtonInstalledDate['state'] = ACTIVE\r\n self.DeviceButtonActivatedDate['state'] = ACTIVE\r\n self.DeviceButtonDisconnectedDate['state'] = ACTIVE\r\n self.DeviceButtonExpirationDate['state'] = ACTIVE\r\n\r\n self.DeviceInstalledDate = self.DeviceInstalledDateFrameEntry.get() \r\n if (len(self.DeviceInstalledDate) > 0):\r\n self.DeviceInstalledDate = str(self.DeviceInstalledData['month_selected']) + '/' + str(self.DeviceInstalledData['day_selected']) + '/' + str(self.DeviceInstalledData['year_selected'])\r\n self.DeviceInstalledMonth = self.DeviceInstalledData['month_selected']\r\n self.DeviceInstalledDay = self.DeviceInstalledData['day_selected']\r\n self.DeviceInstalledYear = self.DeviceInstalledData['year_selected']\r\n else:\r\n self.DeviceInstalledDate = \"\"\r\n self.DeviceInstalledMonth = \"0\"\r\n self.DeviceInstalledDay = \"0\"\r\n self.DeviceInstalledYear = \"0\"\r\n\r\n self.DeviceActivatedDate = self.DeviceActivatedDateFrameEntry.get() \r\n if (len(self.DeviceActivatedDate) > 0):\r\n self.DeviceActivatedDate = str(self.DeviceActivatedData['month_selected']) + '/' + str(self.DeviceActivatedData['day_selected']) + '/' + str(self.DeviceActivatedData['year_selected'])\r\n self.DeviceActivatedMonth = self.DeviceActivatedData['month_selected']\r\n self.DeviceActivatedDay = self.DeviceActivatedData['day_selected']\r\n self.DeviceActivatedYear = self.DeviceActivatedData['year_selected']\r\n else:\r\n self.DeviceActivatedDate = \"\"\r\n self.DeviceActivatedMonth = \"0\"\r\n self.DeviceActivatedDay = \"0\"\r\n self.DeviceActivatedYear = \"0\"\r\n\r\n self.DeviceDisconnectedDate = self.DeviceDisconnectedDateFrameEntry.get() \r\n if (len(self.DeviceDisconnectedDate) > 0):\r\n self.DeviceDisconnectedDate = str(self.DeviceDisconnectedData['month_selected']) + '/' + str(self.DeviceDisconnectedData['day_selected']) + '/' + str(self.DeviceDisconnectedData['year_selected'])\r\n self.DeviceDisconnectedMonth = self.DeviceDisconnectedData['month_selected']\r\n self.DeviceDisconnectedDay = self.DeviceDisconnectedData['day_selected']\r\n self.DeviceDisconnectedYear = self.DeviceDisconnectedData['year_selected']\r\n else:\r\n self.DeviceDisconnectedDate = \"\"\r\n self.DeviceDisconnectedMonth = \"0\"\r\n self.DeviceDisconnectedDay = \"0\"\r\n self.DeviceDisconnectedYear = \"0\"\r\n\r\n self.DeviceExpirationDate = self.DeviceExpirationDateFrameEntry.get() \r\n if (len(self.DeviceExpirationDate) > 0):\r\n self.DeviceExpirationDate = str(self.DeviceExpirationData['month_selected']) + '/' + str(self.DeviceExpirationData['day_selected']) + '/' + str(self.DeviceExpirationData['year_selected'])\r\n self.DeviceExpirationMonth = self.DeviceExpirationData['month_selected']\r\n self.DeviceExpirationDay = self.DeviceExpirationData['day_selected']\r\n self.DeviceExpirationYear = self.DeviceExpirationData['year_selected']\r\n else:\r\n self.DeviceExpirationDate = \"\"\r\n self.DeviceExpirationMonth = \"0\"\r\n self.DeviceExpirationDay = \"0\"\r\n self.DeviceExpirationYear = \"0\"\r\n \r\n self.DeviceTypeID = self.DeviceTypeIDArray[self.DeviceComboBoxTypeID.current()] \r\n self.DeviceModelID = self.DeviceModelIDArray[self.DeviceComboBoxModelID.current()]\r\n self.DeviceStatus = self.DeviceStatusValues[self.DeviceComboBoxStatus.current()]\r\n self.DeviceIPAddress = self.DeviceIPAddressFrameEntry.get() \r\n self.DeviceContract = self.DeviceContractNoFrameEntry.get()\r\n self.DeviceSerialNo = self.DeviceSerialNoFrameEntry.get()\r\n self.DeviceMACAddress = self.DeviceMACAddressFrameEntry.get()\r\n if (len(self.DeviceOutSourceCostFrameEntry.get()) > 0):\r\n self.DeviceOutSourceCost = float(self.DeviceOutSourceCostFrameEntry.get())\r\n else:\r\n self.DeviceOutSourceCost = 0\r\n if (len(self.DeviceMaintenanceCostFrameEntry.get()) > 0): \r\n self.DeviceMaintenanceCost = float(self.DeviceMaintenanceCostFrameEntry.get())\r\n else:\r\n self.DeviceMaintenanceCost = 0\r\n self.DeviceNotes = self.DeviceNotesFrameEntry.get()\r\n\r\n\r\n self.DeviceTableNATIP4Address = self.DeviceNATIPAddressFrameEntry.get() \r\n self.DeviceTableManagementIP4Address = self.DeviceMgmtIPAddressFrameEntry.get()\r\n self.DeviceTableICMPCapable = self.DeviceICMPValues[self.DeviceComboBoxICMPCapable.current()]\r\n self.DeviceTableMonitorviaICMP = self.DeviceICMPValues[self.DeviceComboBoxICMPMonitor.current()]\r\n self.DeviceTableLastSuccessICMP = self.DeviceLastICMPDateFrameEntry.get()\r\n self.DeviceTableLastICMPStatus = self.DeviceLastICMPStatusFrameEntry.get()\r\n self.DeviceTableLastUpdatedCMDBDate = self.DeviceLastCMDBStatusFrameEntry.get() \r\n # self.DeviceTableLastUpdatedCMDBDay\r\n # self.DeviceTableLastUpdatedCMDBMonth\r\n # self.DeviceTableLastUpdatedCMDBYear\r\n\r\n\r\n#****************************************************************************************\r\n#---------------------------- SCREEN SELECTION SECTION ------------------------*\r\n#****************************************************************************************\r\n\r\n\r\n#****************************************************************************************\r\n#---------------------------- COUNTRY SELECTION SECTION ------------------------*\r\n#****************************************************************************************\r\n\r\n def Display_Country_Window(self): \r\n if Is_logging_Available:\r\n Parameter = []\r\n Parameter = ['Device','Country Window'] \r\n Logging.Log(Parameter)\r\n\r\n Country.Display_Country_Window()\r\n\r\n def on_country_combo_changed(self,event):\r\n #print (event)\r\n self.Clean_Screen('country','country-combo')\r\n if self.db.Connect():\r\n # SQL Querry to the Device Table\r\n sql = \"\"\"\r\n SELECT * FROM Region\r\n WHERE Country_ID = '%s'\r\n \"\"\" % (self.CountryIDArray[self.ComboBoxCoutryID.current()])\r\n #print (sql)\r\n if (Is_Region_Available):\r\n self.ButtonRegionAdd['state'] = ACTIVE\r\n self.ButtonRegionRefresh['state'] = ACTIVE\r\n if (self.db.Execute(sql)):\r\n #print (\"found it\")\r\n i = 0\r\n self.progress['maximum'] = len(self.db.results)\r\n self.RegionIDArray = []\r\n self.RegionNameArray = []\r\n while (i < len(self.db.results)):\r\n num = i + 1\r\n self.RegionIDArray.append(self.db.results[i][2].strip())\r\n self.RegionNameArray.append(self.db.results[i][3].strip())\r\n i = i + 1\r\n self.progress['value'] = i\r\n self.ComboBoxRegionID['values'] = self.RegionNameArray\r\n if (len(self.RegionNameArray)== 0):\r\n self.ComboBoxRegionID['state'] = DISABLED\r\n self.ComboBoxFacilityID['state'] = DISABLED\r\n else:\r\n self.ComboBoxRegionID['state'] = 'readonly'\r\n self.ComboBoxRegionID.set(\"\")\r\n self.ComboBoxFacilityID.set(\"\")\r\n else:\r\n mbox.showerror(master=self.DeviceFrame,title='Device',\r\n message = 'No Records found')\r\n else:\r\n mbox.showerror(master=self.DeviceFrame,title='Device',\r\n message = '*** ERROR *** - THE ODBC Connection was NOT Succesful, \\r\\n'\r\n + 'Please make sure the ODBC DSN Name mathes: ['\r\n + self.ODBC_name + \"]\")\r\n\r\n \r\n def on_Country_Table_Refresh(self):\r\n if Is_logging_Available:\r\n Parameter = []\r\n Parameter = ['Device','Country Refresh'] \r\n Logging.Log(Parameter)\r\n\r\n if self.db.Connect(): \r\n self.CountryIDArray = []\r\n self.CountryNameArray = [] \r\n\r\n # SQL Querry to the Device Table\r\n self.progress['maximum'] = 100\r\n self.progress['value'] = 0\r\n if (self.Selection == 'cancel_edit'):\r\n sql = \"\"\"\r\n SELECT * FROM Country\r\n WHERE Country_ID = '%s'\r\n \"\"\" % (self.CountryID_Pre)\r\n else:\r\n sql = \"\"\" SELECT * FROM COUNTRY ORDER BY Country_Name ASC \"\"\"\r\n if (self.db.Execute(sql)):\r\n self.sql_querry = True\r\n i = 0\r\n self.progress['maximum'] = len(self.db.results)\r\n while (i < len(self.db.results)):\r\n num = i + 1\r\n self.CountryIDArray.append(self.db.results[i][0].strip())\r\n self.CountryNameArray.append(self.db.results[i][1].strip())\r\n i = i + 1\r\n self.progress['value'] = i\r\n self.ComboBoxCoutryID['values'] = self.CountryNameArray\r\n if (len(self.CountryNameArray)== 0):\r\n self.ComboBoxCoutryID['state'] = DISABLED\r\n else:\r\n #self.ComboBoxCoutryID['state'] = 'readonly'\r\n #self.ComboBoxCoutryID.set(\"\")\r\n self.Clean_Screen('country','all')\r\n else:\r\n mbox.showerror(master=self.DeviceFrame,title='Device',\r\n message = 'No Country Records found')\r\n self.sql_querry = False\r\n ##self.db.Disconnect()\r\n else:\r\n mbox.showerror(master=self.DeviceFrame,title='Device',\r\n message = '*** ERROR *** - THE ODBC Connection was NOT Succesful, \\r\\n'\r\n + 'Please make sure the ODBC DSN Name mathes: ['\r\n + self.ODBC_name + \"]\")\r\n \r\n\r\n#**************************************************************************************\r\n#---------------------------- COUNTRY SELECTION SECTION ------------------------*\r\n#**************************************************************************************\r\n\r\n#***************************************************************************************\r\n#---------------------------- REGION SELECTION SECTION ------------------------*\r\n#***************************************************************************************\r\n \r\n def Display_Region_Window(self): \r\n if Is_logging_Available:\r\n Parameter = []\r\n Parameter = ['Device','Region Window'] \r\n Logging.Log(Parameter)\r\n\r\n Region.Display_Region_Window()\r\n\r\n def on_region_combo_changed(self,event):\r\n self.Clean_Screen('region','region-combo')\r\n if self.db.Connect():\r\n # SQL Querry to the Device Table\r\n sql = \"\"\"\r\n SELECT * FROM Facility\r\n WHERE Country_ID = '%s' AND Region_ID = '%s'\r\n ORDER BY Facility_Name ASC\r\n \"\"\" % (self.CountryIDArray[self.ComboBoxCoutryID.current()],self.RegionIDArray[self.ComboBoxRegionID.current()])\r\n '''\r\n if (self.Selection == 'cancel_edit'):\r\n sql = \"\"\"\r\n SELECT * FROM Region\r\n WHERE Country_ID = '%s' AND Region_ID = '%s'\r\n ORDER BY Facility_Name ASC\r\n \"\"\" % (self.CountryID_Pre,self.RegionID_Pre)\r\n else:\r\n sql = \"\"\"\r\n SELECT * FROM Region\r\n WHERE Country_ID = '%s'\r\n ORDER BY Facility_Name ASC\r\n \"\"\" % (self.CountryIDArray[self.ComboBoxCoutryID.current()])\r\n '''\r\n #print (sql)\r\n if (Is_Facility_Available):\r\n self.ButtonFacilityAdd['state'] = ACTIVE\r\n self.ButtonFacilityRefresh['state'] = ACTIVE\r\n if (self.db.Execute(sql)):\r\n #print (\"found it\")\r\n self.sql_querry = True\r\n i = 0\r\n self.progress['maximum'] = len(self.db.results)\r\n self.FacilityIDArray = []\r\n self.FacilityNameArray = []\r\n while (i < len(self.db.results)):\r\n num = i + 1\r\n self.FacilityIDArray.append(self.db.results[i][3].strip())\r\n self.FacilityNameArray.append(self.db.results[i][4].strip())\r\n i = i + 1\r\n self.progress['value'] = i\r\n self.ComboBoxFacilityID['values'] = self.FacilityNameArray\r\n if (len(self.FacilityNameArray)== 0):\r\n self.ComboBoxFacilityID['state'] = DISABLED\r\n else:\r\n self.ComboBoxFacilityID['state'] = 'readonly'\r\n self.ComboBoxFacilityID.set(\"\")\r\n else:\r\n mbox.showerror(master=self.DeviceFrame,title='Device',\r\n message = 'No Records found')\r\n self.sql_querry = False\r\n else:\r\n mbox.showerror(master=self.DeviceFrame,title='Device',\r\n message = '*** ERROR *** - THE ODBC Connection was NOT Succesful, \\r\\n'\r\n + 'Please make sure the ODBC DSN Name mathes: ['\r\n + self.ODBC_name + \"]\")\r\n\r\n def on_Region_Table_Refresh(self):\r\n if Is_logging_Available:\r\n Parameter = []\r\n Parameter = ['Device','Region Refresh'] \r\n Logging.Log(Parameter)\r\n\r\n self.Clean_Screen('region','all')\r\n if self.db.Connect():\r\n # SQL Querry to the Device Table\r\n if (self.Selection == 'cancel_edit'):\r\n sql = \"\"\"\r\n SELECT * FROM Region\r\n WHERE Country_ID = '%s' AND Region_ID = '%s'\r\n ORDER BY Region_Name ASC\r\n \"\"\" % (self.CountryID_Pre,self.RegionID_Pre)\r\n else:\r\n sql = \"\"\"\r\n SELECT * FROM Region\r\n WHERE Country_ID = '%s'\r\n ORDER BY Region_Name ASC\r\n \"\"\" % (self.CountryIDArray[self.ComboBoxCoutryID.current()])\r\n #print (sql)\r\n if (self.db.Execute(sql)):\r\n #print (\"found it\")\r\n self.sql_querry = True\r\n i = 0\r\n self.progress['maximum'] = len(self.db.results)\r\n self.RegionIDArray = []\r\n self.RegionNameArray = []\r\n while (i < len(self.db.results)):\r\n num = i + 1\r\n self.RegionIDArray.append(self.db.results[i][2].strip())\r\n self.RegionNameArray.append(self.db.results[i][3].strip())\r\n i = i + 1\r\n self.progress['value'] = i\r\n self.ComboBoxRegionID['values'] = self.RegionNameArray\r\n if (len(self.RegionNameArray)== 0):\r\n self.ComboBoxRegionID['state'] = DISABLED\r\n self.ComboBoxFacilityID['state'] = DISABLED\r\n else:\r\n self.ComboBoxRegionID['state'] = 'readonly'\r\n self.ComboBoxRegionID.set(\"\")\r\n if (Is_Region_Available):\r\n self.ButtonRegionAdd['state'] = 'active'\r\n self.ButtonRegionRefresh['state'] = 'active' \r\n else:\r\n mbox.showerror(master=self.DeviceFrame,title='Device',\r\n message = 'No Records found')\r\n self.sql_querry = False\r\n else:\r\n mbox.showerror(master=self.DeviceFrame,title='Device',\r\n message = '*** ERROR *** - THE ODBC Connection was NOT Succesful, \\r\\n'\r\n + 'Please make sure the ODBC DSN Name mathes: ['\r\n + self.ODBC_name + \"]\")\r\n \r\n#*************************************************************************************\r\n#---------------------------- REGION SELECTION SECTION ------------------------*\r\n#*************************************************************************************\r\n\r\n\r\n#***************************************************************************************\r\n#---------------------------- FACILITY SELECTION SECTION ----------------------*\r\n#***************************************************************************************\r\n \r\n def Display_Facility_Window(self):\r\n if Is_logging_Available:\r\n Parameter = []\r\n Parameter = ['Device','Facility Windows'] \r\n Logging.Log(Parameter)\r\n\r\n Facility.Display_Facility_Window()\r\n\r\n def on_facility_combo_changed(self,event):\r\n self.Clean_Screen('facility','facility-combo')\r\n if self.db.Connect():\r\n # SQL Querry to the Device Table\r\n sql = \"\"\"\r\n SELECT * FROM Sites\r\n WHERE Country_ID = '%s' AND Region_ID = '%s' AND Facility_ID = '%s'\r\n \"\"\" % (self.CountryIDArray[self.ComboBoxCoutryID.current()],self.RegionIDArray[self.ComboBoxRegionID.current()],\r\n self.FacilityIDArray[self.ComboBoxFacilityID.current()])\r\n #print (sql)\r\n if (Is_Sites_Available):\r\n self.ButtonSitesAdd['state'] = ACTIVE\r\n self.ButtonSitesRefresh['state'] = ACTIVE\r\n if (self.db.Execute(sql)):\r\n self.SitesIDArray = []\r\n self.SitesNameArray = []\r\n i = 0\r\n while (i < len(self.db.results)):\r\n num = i + 1\r\n self.SitesIDArray.append(self.db.results[i][4].strip())\r\n self.SitesNameArray.append(self.db.results[i][5].strip())\r\n i = i + 1\r\n self.progress['value'] = i\r\n self.ComboBoxSitesID['values'] = self.SitesNameArray\r\n if (len(self.SitesNameArray)== 0):\r\n self.ComboBoxSitesID['state'] = DISABLED\r\n else:\r\n self.ComboBoxSitesID['state'] = 'readonly'\r\n self.ComboBoxSitesID.set(\"\")\r\n else:\r\n mbox.showerror(master=self.DeviceFrame,title='Device',\r\n message = 'No Records found')\r\n else:\r\n mbox.showerror(master=self.DeviceFrame,title='Device',\r\n message = '*** ERROR *** - THE ODBC Connection was NOT Succesful, \\r\\n'\r\n + 'Please make sure the ODBC DSN Name mathes: ['\r\n + self.ODBC_name + \"]\")\r\n\r\n def on_Facility_Table_Refresh(self):\r\n if Is_logging_Available:\r\n Parameter = []\r\n Parameter = ['Device','Facility Refresh'] \r\n Logging.Log(Parameter)\r\n\r\n self.Clean_Screen('facility','all')\r\n if self.db.Connect():\r\n # SQL Querry to the Device Table\r\n if (self.Selection == 'cancel_edit'):\r\n sql = \"\"\"\r\n SELECT * FROM Facility\r\n WHERE Country_ID = '%s' AND Region_ID = '%s' AND Facility_ID = '%s'\r\n ORDER BY Facility_Name ASC\r\n \"\"\" % (self.CountryID_Pre,self.RegionID_Pre,self.FacilityID_Pre)\r\n else:\r\n sql = \"\"\"\r\n SELECT * FROM Facility\r\n WHERE Country_ID = '%s' AND Region_ID = '%s'\r\n ORDER BY Facility_Name ASC\r\n \"\"\" % (self.CountryIDArray[self.ComboBoxCoutryID.current()],\r\n self.RegionIDArray[self.ComboBoxRegionID.current()])\r\n #print (sql)\r\n if (self.db.Execute(sql)):\r\n #print (\"found it\")\r\n self.sql_querry = True\r\n i = 0\r\n self.progress['maximum'] = len(self.db.results)\r\n self.FacilityIDArray = []\r\n self.FacilityNameArray = []\r\n while (i < len(self.db.results)):\r\n num = i + 1\r\n self.FacilityIDArray.append(self.db.results[i][3].strip())\r\n self.FacilityNameArray.append(self.db.results[i][4].strip())\r\n i = i + 1\r\n self.progress['value'] = i\r\n self.ComboBoxFacilityID['values'] = self.FacilityNameArray\r\n if (len(self.FacilityNameArray)== 0):\r\n self.ComboBoxFacilityID['state'] = DISABLED\r\n self.ComboBoxSiteID['state'] = DISABLED\r\n else:\r\n self.ComboBoxFacilityID['state'] = 'readonly'\r\n self.ComboBoxFacilityID.set(\"\")\r\n if (Is_Facility_Available):\r\n self.ButtonFacilityAdd['state'] = 'active'\r\n self.ButtonFacilityRefresh['state'] = 'active' \r\n else:\r\n mbox.showerror(master=self.DeviceFrame,title='Device',\r\n message = 'No Records found')\r\n self.sql_querry = False\r\n else:\r\n mbox.showerror(master=self.DeviceFrame,title='Device',\r\n message = '*** ERROR *** - THE ODBC Connection was NOT Succesful, \\r\\n'\r\n + 'Please make sure the ODBC DSN Name mathes: ['\r\n + self.ODBC_name + \"]\")\r\n \r\n#*************************************************************************************\r\n#---------------------------- FACILITY SELECTION SECTION ------------------------*\r\n#*************************************************************************************\r\n\r\n\r\n#***************************************************************************************\r\n#---------------------------- SITES SELECTION SECTION ------------------------*\r\n#***************************************************************************************\r\n \r\n def Display_Sites_Window(self): \r\n if Is_logging_Available:\r\n Parameter = []\r\n Parameter = ['Device','Sites Window'] \r\n Logging.Log(Parameter)\r\n\r\n Sites.Display_Sites_Window()\r\n\r\n def on_sites_combo_changed(self,event):\r\n self.Clean_Screen('sites','sites-combo')\r\n if self.db.Connect():\r\n # SQL Querry to the Device Table\r\n sql = \"\"\"\r\n SELECT * FROM Devices\r\n WHERE Country_ID = '%s' AND Region_ID = '%s' AND Facility_ID = '%s' AND Site_ID = '%s'\r\n ORDER BY Status desc, Device_Type_ID ASC, Device_Model_ID ASC, Device_ID ASC\r\n \"\"\" % (self.CountryIDArray[self.ComboBoxCoutryID.current()],self.RegionIDArray[self.ComboBoxRegionID.current()],\r\n self.FacilityIDArray[self.ComboBoxFacilityID.current()],self.SitesIDArray[self.ComboBoxSitesID.current()])\r\n #print (sql)\r\n if (Is_Sites_Available):\r\n self.ButtonSitesAdd['state'] = ACTIVE\r\n self.ButtonSitesRefresh['state'] = ACTIVE\r\n if ((self.db.Execute(sql)) and (self.Selection != 'edit')):\r\n #------------------------------- Deleting Tree View --------\r\n #x = self.DeviceTreeview.get_children()\r\n #if x != '()': # checks if there is something in the first row\r\n # for child in x:\r\n # #print (child)\r\n # self.DeviceTreeview.delete(child)\r\n #------------------------------- Deleting Tree View --------\r\n #-------------- Initializing Arrays ----------------------\r\n self.DeviceTablePriaryKeyArray = [] # Device ID\r\n self.DeviceTableDeviceDescriptionArray = [] \r\n self.DeviceTableCountryIDArray = [] \r\n self.DeviceTableRegionIDArray = []\r\n self.DeviceTableFacilityIDArray = []\r\n self.DeviceTableSiteIDArray = []\r\n self.DeviceTableDeviceTypeIDArray = []\r\n self.DeviceTableIP4AddressArray = []\r\n self.DeviceTableIP6AddressArray = []\r\n self.DeviceTableContractNoArray = []\r\n self.DeviceTableOutsourceCostArray = []\r\n self.DeviceTableMaintenanceCostArray = []\r\n self.DeviceTableStatusArray = []\r\n self.DeviceTableMonthlyCostArray = []\r\n self.DeviceTableDateInstalledArray = []\r\n self.DeviceTableDayInstalledArray = []\r\n self.DeviceTableMonthInstalledArray = []\r\n self.DeviceTableYearInstalledArray = []\r\n self.DeviceTableDateActivatedArray = []\r\n self.DeviceTableDayActivatedArray = []\r\n self.DeviceTableMonthActivatedArray = []\r\n self.DeviceTableYearActivatedArray = []\r\n self.DeviceTableDisconectedDateArray = []\r\n self.DeviceTableDayDisconectedArray = []\r\n self.DeviceTableMonthDisconectedArray = []\r\n self.DeviceTableYearDisconectedArray = []\r\n self.DeviceTableExpirationDateArray = []\r\n self.DeviceTableDayExpirationArray = []\r\n self.DeviceTableMonthExpirationArray = []\r\n self.DeviceTableYearExpirationArray = []\r\n self.DeviceTableSerilaNoArray = []\r\n self.DeviceTableExecutedByArray = []\r\n self.DeviceTableNotesArray = []\r\n self.DeviceTableDeviceModelIDArray = []\r\n self.DeviceTableMACAddressArray = []\r\n self.DeviceTableNATIP4AddressArray = [] \r\n self.DeviceTableManagementIP4AddressArray = []\r\n self.DeviceTableLastSuccessICMPArray = []\r\n self.DeviceTableLastICMPStatusArray = []\r\n self.DeviceTableICMPCapableArray = []\r\n self.DeviceTableMonitorviaICMPArray = []\r\n self.DeviceTableLastUpdatedCMDBDateArray = []\r\n self.DeviceTableLastUpdatedCMDBDayArray = []\r\n self.DeviceTableLastUpdatedCMDBMonthArray = []\r\n self.DeviceTableLastUpdatedCMDBYearArray = []\r\n self.DeviceTableArrayColumns = []\r\n self.results = []\r\n self.DeviceTableArratRowsTemp = []\r\n\r\n\r\n self.DeviceTableArrayColumns = (\r\n 'Device ID',\r\n 'Device Description',\r\n 'Country ID', \r\n 'Region ID',\r\n 'Facility ID',\r\n 'Site ID',\r\n 'Device Type ID',\r\n 'IP4 Address',\r\n 'IP6 Address',\r\n 'Contract No',\r\n 'OutSource Cost',\r\n 'Maintenance Cost',\r\n 'Status',\r\n 'Monthly Cost',\r\n 'Date Installed',\r\n 'Day Installed',\r\n 'Month Installed',\r\n 'Year Installed',\r\n 'Date Activated',\r\n 'Day Activated',\r\n 'Month Activated',\r\n 'Year Activated',\r\n 'Disconnect Date',\r\n 'Day Disconnect',\r\n 'Month Disconnect',\r\n 'Year Disconnect',\r\n 'Expiration Date',\r\n 'Day Expiration',\r\n 'Month Expiration',\r\n 'Year Expiration',\r\n 'Serial No',\r\n 'Executed by UserID',\r\n 'Notes',\r\n 'Device Model ID',\r\n 'MAC Address',\r\n 'NAT IP4 Address', \r\n 'Management IP4 Address',\r\n 'Last Success ICMP',\r\n 'Last ICMP Status',\r\n 'ICMP Capable',\r\n 'Monitor via ICMP',\r\n 'Last Updated CMDB Date',\r\n 'Last Updated CMDB Day',\r\n 'Last Updated CMDB Month',\r\n 'Last Updated CMDB Year'\r\n )\r\n\r\n\r\n '''\r\n 0 Device_ID CHAR(50) NOT NULL PRIMARY KEY,\r\n 1 Device_Description CHAR(100) NOT NULL,\r\n 2 Country_ID CHAR(20) NOT NULL, \r\n 3 Region_ID CHAR(20) NOT NULL,\r\n 4 Facility_ID CHAR(20) NOT NULL,\r\n 5 Site_ID CHAR(20) NOT NULL,\r\n 6 Device_Type_ID CHAR(30) NOT NULL,\r\n 7 IP4_Address CHAR(20),\r\n 8 IP6_Address CHAR(200),\r\n 9 Contract_No CHAR(20),\r\n 10 OutSource_Cost FLOAT,\r\n 11 Maintenance_Cost FLOAT,\r\n 12 Status CHAR(20),\r\n 13 Monthly_Cost FLOAT,\r\n 14 Date_Installed CHAR(20),\r\n 15 Day_Installed INT,\r\n 16 Month_Installed INT,\r\n 17 Year_Installed INT,\r\n 18 Date_Activated CHAR(20),\r\n 19 Day_Activated INT,\r\n 20 Month_Activated INT,\r\n 21 Year_Activated INT,\r\n 22 Disconnect_Date CHAR(20),\r\n 23 Day_Disconnect INT,\r\n 24 Month_Disconnect INT,\r\n 25 Year_Disconnect INT,\r\n 26 Expiration_Date CHAR(20),\r\n 27 Day_Expiration INT,\r\n 28 Month_Expiration INT,\r\n 29 Year_Expiration INT,\r\n 30 Serial_No CHAR(100),\r\n 31 Executed_by_UserID CHAR(20),\r\n 32 Notes CHAR(200),\r\n 33 Device_Model_ID CHAR(30),\r\n 34 MAC_Address CHAR(20)\r\n 35 NAT_IP4_Address CHAR(20), <----- NEW as March 5th 2018 \r\n 36 Management_IP4_Address CHAR(20),\r\n 37 Last_Success_ICMP CHAR(50),\r\n 38 Last_ICMP_Status CHAR(50),\r\n 39 ICMP_Capable CHAR(10),\r\n 40 Monitor_via_ICMP CHAR(10),\r\n 41 Last_Updated_CMDB_Date CHAR(50),\r\n 42 Last_Updated_CMDB_Day INT,\r\n 43 Last_Updated_CMDB_Month INT,\r\n 44 Last_Updated_CMDB_Year INT)\"\"\"\r\n '''\r\n #-------------- Initializing Arrays ---------------------- \r\n i = 0\r\n self.data_ready = True\r\n while (i < len(self.db.results)):\r\n self.DeviceTablePriaryKeyArray.append(self.db.results[i][0].strip())\r\n self.DeviceTableDeviceDescriptionArray.append(self.db.results[i][1].strip())\r\n self.DeviceTableCountryIDArray.append(self.db.results[i][2].strip())\r\n self.DeviceTableRegionIDArray.append(self.db.results[i][3].strip())\r\n self.DeviceTableFacilityIDArray.append(self.db.results[i][4].strip())\r\n self.DeviceTableSiteIDArray.append(self.db.results[i][5].strip())\r\n self.DeviceTableDeviceTypeIDArray.append(self.db.results[i][6].strip())\r\n if ((self.db.results[i][7]) == None):\r\n self.DeviceTableIP4AddressArray.append(\"0.0.0.0\")\r\n #self.DeviceTableIP4AddressArray.append(self.db.results[i][7])\r\n else:\r\n self.DeviceTableIP4AddressArray.append(self.db.results[i][7].strip())\r\n if ((self.db.results[i][8]) == None):\r\n self.DeviceTableIP6AddressArray.append(self.db.results[i][8])\r\n else:\r\n self.DeviceTableIP6AddressArray.append(self.db.results[i][8].strip())\r\n if ((self.db.results[i][9]) == None):\r\n self.DeviceTableContractNoArray.append(self.db.results[i][9])\r\n else: \r\n self.DeviceTableContractNoArray.append(self.db.results[i][9].strip())\r\n \r\n if (self.db.results[i][10] == None):\r\n self.DeviceTableOutsourceCostArray.append(0.0)\r\n else:\r\n self.DeviceTableOutsourceCostArray.append(self.db.results[i][10])\r\n \r\n if (self.db.results[i][11] == None):\r\n self.DeviceTableMaintenanceCostArray.append(0.0)\r\n else:\r\n self.DeviceTableMaintenanceCostArray.append(self.db.results[i][11])\r\n self.DeviceTableStatusArray.append(self.db.results[i][12].strip())\r\n if (self.db.results[i][13] == None):\r\n self.DeviceTableMonthlyCostArray.append(0.0)\r\n else:\r\n self.DeviceTableMonthlyCostArray.append(self.db.results[i][13])\r\n if (((self.db.results[i][14]) == None) or (self.db.results[i][15] == 0)):\r\n self.DeviceTableDateInstalledArray.append(\"\")\r\n self.DeviceTableDayInstalledArray.append(0)\r\n self.DeviceTableMonthInstalledArray.append(0)\r\n self.DeviceTableYearInstalledArray.append(0)\r\n else:\r\n self.DeviceTableDateInstalledArray.append(self.db.results[i][14].strip())\r\n self.DeviceTableDayInstalledArray.append(self.db.results[i][15])\r\n self.DeviceTableMonthInstalledArray.append(self.db.results[i][16])\r\n self.DeviceTableYearInstalledArray.append(self.db.results[i][17])\r\n if (((self.db.results[i][18]) == None) or (self.db.results[i][19] == 0)):\r\n self.DeviceTableDateActivatedArray.append(\"\")\r\n self.DeviceTableDayActivatedArray.append(0)\r\n self.DeviceTableMonthActivatedArray.append(0)\r\n self.DeviceTableYearActivatedArray.append(0)\r\n else:\r\n self.DeviceTableDateActivatedArray.append(self.db.results[i][18].strip())\r\n self.DeviceTableDayActivatedArray.append(self.db.results[i][19])\r\n self.DeviceTableMonthActivatedArray.append(self.db.results[i][20])\r\n self.DeviceTableYearActivatedArray.append(self.db.results[i][21])\r\n if (((self.db.results[i][22]) == None) or (self.db.results[i][23] == 0)):\r\n self.DeviceTableDisconectedDateArray.append(\"\")\r\n self.DeviceTableDayDisconectedArray.append(0)\r\n self.DeviceTableMonthDisconectedArray.append(0)\r\n self.DeviceTableYearDisconectedArray.append(0)\r\n else:\r\n self.DeviceTableDisconectedDateArray.append(self.db.results[i][22].strip())\r\n self.DeviceTableDayDisconectedArray.append(self.db.results[i][23])\r\n self.DeviceTableMonthDisconectedArray.append(self.db.results[i][24])\r\n self.DeviceTableYearDisconectedArray.append(self.db.results[i][25])\r\n if (((self.db.results[i][26]) == None) or (self.db.results[i][27] == 0)):\r\n self.DeviceTableExpirationDateArray.append(\"\")\r\n self.DeviceTableDayExpirationArray.append(0)\r\n self.DeviceTableMonthExpirationArray.append(0)\r\n self.DeviceTableYearExpirationArray.append(0)\r\n else:\r\n self.DeviceTableExpirationDateArray.append(self.db.results[i][26].strip())\r\n self.DeviceTableDayExpirationArray.append(self.db.results[i][27])\r\n self.DeviceTableMonthExpirationArray.append(self.db.results[i][28])\r\n self.DeviceTableYearExpirationArray.append(self.db.results[i][29])\r\n if ((self.db.results[i][30]) == None):\r\n self.DeviceTableSerilaNoArray.append(self.db.results[i][30])\r\n else:\r\n self.DeviceTableSerilaNoArray.append(self.db.results[i][30].strip())\r\n self.DeviceTableExecutedByArray.append(self.db.results[i][31].strip())\r\n if ((self.db.results[i][32]) == None):\r\n self.DeviceTableNotesArray.append(\" \")\r\n #self.DeviceTableNotesArray.append(self.db.results[i][32])\r\n else:\r\n self.DeviceTableNotesArray.append(self.db.results[i][32].strip())\r\n if ((self.db.results[i][33]) == None):\r\n self.DeviceTableDeviceModelIDArray.append(self.db.results[i][33])\r\n else:\r\n self.DeviceTableDeviceModelIDArray.append(self.db.results[i][33].strip())\r\n if ((self.db.results[i][34]) == None):\r\n self.DeviceTableMACAddressArray.append(self.db.results[i][34])\r\n else:\r\n self.DeviceTableMACAddressArray.append(self.db.results[i][34].strip())\r\n\r\n ###################\r\n if ((self.db.results[i][35]) == None):\r\n self.DeviceTableNATIP4AddressArray.append(\"0.0.0.0\")\r\n else:\r\n self.DeviceTableNATIP4AddressArray.append(self.db.results[i][35].strip())\r\n \r\n if ((self.db.results[i][36]) == None):\r\n self.DeviceTableManagementIP4AddressArray.append(\"0.0.0.0\")\r\n else:\r\n self.DeviceTableManagementIP4AddressArray.append(self.db.results[i][36].strip())\r\n\r\n if ((self.db.results[i][37]) == None):\r\n self.DeviceTableLastSuccessICMPArray.append(\"Never\")\r\n else:\r\n self.DeviceTableLastSuccessICMPArray.append(self.db.results[i][37].strip())\r\n\r\n if ((self.db.results[i][38]) == None):\r\n self.DeviceTableLastICMPStatusArray.append(\"Never\")\r\n else:\r\n self.DeviceTableLastICMPStatusArray.append(self.db.results[i][38].strip())\r\n\r\n if ((self.db.results[i][39]) == None): # this field I toggle between YES / NO on Double Click on ICMP Menu\r\n self.DeviceTableICMPCapableArray.append(\"YES\")\r\n else:\r\n self.DeviceTableICMPCapableArray.append(self.db.results[i][39].strip())\r\n\r\n if ((self.db.results[i][40]) == None): \r\n self.DeviceTableMonitorviaICMPArray.append(\"NO\")\r\n else:\r\n self.DeviceTableMonitorviaICMPArray.append(self.db.results[i][40].strip())\r\n\r\n if ((self.db.results[i][41]) == None): \r\n self.DeviceTableLastUpdatedCMDBDateArray.append(\"Never\")\r\n else:\r\n self.DeviceTableLastUpdatedCMDBDateArray.append(self.db.results[i][41].strip())\r\n\r\n if ((self.db.results[i][42]) == None): \r\n self.DeviceTableLastUpdatedCMDBDayArray.append(0)\r\n else:\r\n self.DeviceTableLastUpdatedCMDBDayArray.append(self.db.results[i][42])\r\n\r\n if ((self.db.results[i][43]) == None): \r\n self.DeviceTableLastUpdatedCMDBMonthArray.append(0)\r\n else:\r\n self.DeviceTableLastUpdatedCMDBMonthArray.append(self.db.results[i][43])\r\n\r\n if ((self.db.results[i][44]) == None): \r\n self.DeviceTableLastUpdatedCMDBYearArray.append(0)\r\n else:\r\n self.DeviceTableLastUpdatedCMDBYearArray.append(self.db.results[i][44])\r\n \r\n i = i + 1\r\n i = 0\r\n while (i < len(self.DeviceTablePriaryKeyArray)):\r\n num = i + 1\r\n tags = self.DeviceTableStatusArray[i] # To use in the futire\r\n item = [\r\n self.DeviceTablePriaryKeyArray[i],\r\n self.DeviceTableDeviceDescriptionArray[i], \r\n self.DeviceTableDeviceTypeIDArray[i],\r\n self.DeviceTableDeviceModelIDArray[i],\r\n self.DeviceTableIP4AddressArray[i],\r\n self.DeviceTableOutsourceCostArray[i],\r\n self.DeviceTableMaintenanceCostArray[i], \r\n self.DeviceTableDateInstalledArray[i],\r\n self.DeviceTableDateActivatedArray[i],\r\n self.DeviceTableDisconectedDateArray[i],\r\n self.DeviceTableStatusArray[i],\r\n self.DeviceTableContractNoArray[i],\r\n self.DeviceTableExpirationDateArray[i],\r\n self.DeviceTableSerilaNoArray[i],\r\n self.DeviceTableExecutedByArray[i],\r\n ]\r\n self.DeviceTableArrayRowsTemp = [\r\n self.DeviceTablePriaryKeyArray[i],\r\n self.DeviceTableDeviceDescriptionArray[i],\r\n self.DeviceTableCountryIDArray[i],\r\n self.DeviceTableRegionIDArray[i],\r\n self.DeviceTableFacilityIDArray[i],\r\n self.DeviceTableSiteIDArray[i],\r\n self.DeviceTableDeviceTypeIDArray[i],\r\n self.DeviceTableIP4AddressArray[i],\r\n self.DeviceTableIP6AddressArray[i],\r\n self.DeviceTableContractNoArray[i],\r\n self.DeviceTableOutsourceCostArray[i],\r\n self.DeviceTableMaintenanceCostArray[i],\r\n self.DeviceTableStatusArray[i],\r\n self.DeviceTableMonthlyCostArray[i],\r\n self.DeviceTableDateInstalledArray[i],\r\n self.DeviceTableDayInstalledArray[i],\r\n self.DeviceTableMonthInstalledArray[i],\r\n self.DeviceTableYearInstalledArray[i],\r\n self.DeviceTableDateActivatedArray[i],\r\n self.DeviceTableDayActivatedArray[i],\r\n self.DeviceTableMonthActivatedArray[i],\r\n self.DeviceTableYearActivatedArray[i],\r\n self.DeviceTableDisconectedDateArray[i],\r\n self.DeviceTableDayDisconectedArray[i],\r\n self.DeviceTableMonthDisconectedArray[i],\r\n self.DeviceTableYearDisconectedArray[i],\r\n self.DeviceTableExpirationDateArray[i],\r\n self.DeviceTableDayExpirationArray[i],\r\n self.DeviceTableMonthExpirationArray[i],\r\n self.DeviceTableYearExpirationArray[i],\r\n self.DeviceTableSerilaNoArray[i],\r\n self.DeviceTableExecutedByArray[i],\r\n self.DeviceTableNotesArray[i],\r\n self.DeviceTableDeviceModelIDArray[i],\r\n self.DeviceTableMACAddressArray[i],\r\n self.DeviceTableNATIP4AddressArray[i],\r\n self.DeviceTableManagementIP4AddressArray[i],\r\n self.DeviceTableLastSuccessICMPArray[i],\r\n self.DeviceTableLastICMPStatusArray[i],\r\n self.DeviceTableICMPCapableArray[i],\r\n self.DeviceTableMonitorviaICMPArray[i],\r\n self.DeviceTableMonitorviaICMPArray[i],\r\n self.DeviceTableLastUpdatedCMDBDayArray[i],\r\n self.DeviceTableLastUpdatedCMDBMonthArray[i],\r\n self.DeviceTableLastUpdatedCMDBYearArray[i]\r\n ]\r\n self.results.append(self.DeviceTableArrayRowsTemp)\r\n\r\n self.DeviceTreeview.insert('', END, text='%3d'%num, values=item, tags=tags)\r\n i = i + 1\r\n self.ButtonDeviceAdd['state'] = ACTIVE\r\n self.ButtonDeviceEdit['state'] = DISABLED\r\n self.ButtonDeviceRemove['state'] = DISABLED\r\n self.ButtonDeviceOK['state'] = DISABLED\r\n self.ButtonDeviceCancel['state'] = DISABLED\r\n self.ButtonDeviceCircuits['state'] = DISABLED\r\n self.ButtonDevicePing64['state'] = DISABLED\r\n self.ButtonDevicePing1500['state'] = DISABLED\r\n #self.ButtonDeviceContacts['state'] = DISABLED\r\n self.ButtonDeviceICMP['state'] = DISABLED\r\n self.ButtonDeviceLocalPointOfContacts['state'] = DISABLED\r\n \r\n else:\r\n if (self.Selection != 'edit'):\r\n mbox.showerror(master=self.DeviceFrame,title='Device',\r\n message = 'No Records found')\r\n else:\r\n mbox.showerror(master=self.DeviceFrame,title='Device',\r\n message = '*** ERROR *** - THE ODBC Connection was NOT Succesful, \\r\\n'\r\n + 'Please make sure the ODBC DSN Name mathes: ['\r\n + self.ODBC_name + \"]\")\r\n\r\n def on_Sites_Table_Refresh(self):\r\n if Is_logging_Available:\r\n Parameter = []\r\n Parameter = ['Device','Sites Refresh'] \r\n Logging.Log(Parameter)\r\n\r\n self.Clean_Screen('sites','all')\r\n if self.db.Connect():\r\n # SQL Querry to the Device Table\r\n if (self.Selection == 'cancel_edit'):\r\n sql = \"\"\"\r\n SELECT * FROM Sites\r\n WHERE Country_ID = '%s' AND Region_ID = '%s' AND Facility_ID = '%s' AND Site_ID = '%s'\r\n \"\"\" % (self.CountryID_Pre,self.RegionID_Pre,self.FacilityID_Pre,self.SitesID_Pre)\r\n else:\r\n sql = \"\"\"\r\n SELECT * FROM Sites\r\n WHERE Country_ID = '%s' AND Region_ID = '%s' AND Facility_ID = '%s'\r\n \"\"\" % (self.CountryIDArray[self.ComboBoxCoutryID.current()],self.RegionIDArray[self.ComboBoxRegionID.current()],\r\n self.FacilityIDArray[self.ComboBoxFacilityID.current()])\r\n #print (sql)\r\n if (self.db.Execute(sql)):\r\n #print (\"found it\")\r\n self.sql_querry = True\r\n i = 0\r\n self.progress['maximum'] = len(self.db.results)\r\n self.SitesIDArray = []\r\n self.SitesNameArray = []\r\n while (i < len(self.db.results)):\r\n num = i + 1\r\n self.SitesIDArray.append(self.db.results[i][4].strip())\r\n self.SitesNameArray.append(self.db.results[i][5].strip())\r\n i = i + 1\r\n self.progress['value'] = i\r\n self.ComboBoxSitesID['values'] = self.SitesNameArray\r\n if (len(self.SitesNameArray)== 0):\r\n self.ComboBoxSitesID['state'] = DISABLED\r\n else:\r\n self.ComboBoxSitesID['state'] = 'readonly'\r\n self.ComboBoxSitesID.set(\"\")\r\n else:\r\n mbox.showerror(master=self.DeviceFrame,title='Device',\r\n message = 'No Records found')\r\n self.ComboBoxSitesID['state'] = DISABLED\r\n self.sql_querry = False\r\n else:\r\n mbox.showerror(master=self.DeviceFrame,title='Device',\r\n message = '*** ERROR *** - THE ODBC Connection was NOT Succesful, \\r\\n'\r\n + 'Please make sure the ODBC DSN Name mathes: ['\r\n + self.ODBC_name + \"]\")\r\n \r\n#*************************************************************************************\r\n#---------------------------- SITES SELECTION SECTION ------------------------*\r\n#*************************************************************************************\r\n \r\n def on_DeviceWindow_quit(self):\r\n if (self.DeviceWindowExist):\r\n self.DeviceWindowExist = False\r\n self.db.Disconnect()\r\n if Is_logging_Available:\r\n Parameter = []\r\n Parameter = ['Device','CLOSE Window'] \r\n Logging.Log(Parameter)\r\n self.DeviceWindow.destroy()\r\n\r\n def on_Device_Table_Refresh(self): # I need to do more research on this call.\r\n if Is_logging_Available:\r\n Parameter = []\r\n Parameter = ['Device','Device Refresh'] \r\n Logging.Log(Parameter)\r\n self.on_country_combo_changed(\"event\")\r\n \r\n def Call_Button_Device_Add(self):\r\n #-- reset the progess bar --\r\n if Is_logging_Available:\r\n Parameter = []\r\n Parameter = ['Device','ADD Button'] \r\n Logging.Log(Parameter)\r\n self.Enable_Screen('add')\r\n self.Selection = 'add'\r\n\r\n def Call_Button_Device_Edit(self):\r\n if Is_logging_Available:\r\n Parameter = []\r\n Parameter = ['Device','EDIT Button'] \r\n Logging.Log(Parameter)\r\n self.progress['maximum'] = 100\r\n self.progress['value'] = 0\r\n self.Selection = 'edit'\r\n self.CountryID_Pre = self.CountryIDArray[self.ComboBoxCoutryID.current()]\r\n self.RegionID_Pre = self.RegionIDArray[self.ComboBoxRegionID.current()]\r\n self.FacilityID_Pre = self.FacilityIDArray[self.ComboBoxFacilityID.current()]\r\n self.SitesID_Pre = self.SitesIDArray[self.ComboBoxSitesID.current()]\r\n self.Enable_Screen('edit')\r\n # ----- Installed Date ---------------------\r\n self.DeviceInstalledData = {}\r\n if (self.Selection == 'edit'):\r\n self.DeviceInstalledDateName = self.DeviceInstalledDateFrameEntry.get()\r\n curItem = self.DeviceTreeview.focus() \r\n dic = self.DeviceTreeview.item(curItem)\r\n curItem = int(dic.get('text')) - 1\r\n if (len(self.DeviceInstalledDateName) > 0):\r\n if (self.DeviceTableDateInstalledArray[curItem] != 0):\r\n self.DeviceInstalledData['day_selected'] = self.DeviceTableDayInstalledArray[curItem]\r\n self.DeviceInstalledData['month_selected'] = self.DeviceTableMonthInstalledArray[curItem]\r\n self.DeviceInstalledData['year_selected'] = self.DeviceTableYearInstalledArray[curItem]\r\n # ----- Activated Date ---------------------\r\n self.DeviceActivatedDateName = self.DeviceActivatedDateFrameEntry.get()\r\n curItem = self.DeviceTreeview.focus() \r\n dic = self.DeviceTreeview.item(curItem)\r\n curItem = int(dic.get('text')) - 1\r\n self.DeviceActivatedData = {}\r\n if (len(self.DeviceActivatedDateName) > 0):\r\n if (self.DeviceTableDateActivatedArray[curItem] != 0):\r\n self.DeviceActivatedData['day_selected'] = self.DeviceTableDayActivatedArray[curItem]\r\n self.DeviceActivatedData['month_selected'] = self.DeviceTableMonthActivatedArray[curItem]\r\n self.DeviceActivatedData['year_selected'] = self.DeviceTableYearActivatedArray[curItem]\r\n #print (\"Day, Month, Year\")\r\n #print (self.DeviceActivatedData['day_selected'])\r\n #print (self.DeviceActivatedData['month_selected'])\r\n #print (self.DeviceActivatedData['year_selected'])\r\n # ----- Disconnected Date ---------------------\r\n self.DeviceDisconnectedData = {}\r\n if (self.Selection == 'edit'):\r\n self.DeviceDisconnectedDateName = self.DeviceDisconnectedDateFrameEntry.get()\r\n curItem = self.DeviceTreeview.focus() \r\n dic = self.DeviceTreeview.item(curItem)\r\n curItem = int(dic.get('text')) - 1\r\n if (len(self.DeviceDisconnectedDateName) > 0):\r\n if (self.DeviceTableDisconectedDateArray[curItem] != 0):\r\n self.DeviceDisconnectedData['day_selected'] = self.DeviceTableDayDisconectedArray[curItem]\r\n self.DeviceDisconnectedData['month_selected'] = self.DeviceTableMonthDisconectedArray[curItem]\r\n self.DeviceDisconnectedData['year_selected'] = self.DeviceTableYearDisconectedArray[curItem]\r\n # ----- Expiration Date ---------------------\r\n self.DeviceExpirationData = {}\r\n if (self.Selection == 'edit'):\r\n self.DeviceExpirationDateName = self.DeviceExpirationDateFrameEntry.get()\r\n curItem = self.DeviceTreeview.focus() \r\n dic = self.DeviceTreeview.item(curItem)\r\n curItem = int(dic.get('text')) - 1\r\n if (len(self.DeviceExpirationDateName) > 0):\r\n if (self.DeviceTableExpirationDateArray[curItem] != 0):\r\n self.DeviceExpirationData['day_selected'] = self.DeviceTableDayExpirationArray[curItem]\r\n self.DeviceExpirationData['month_selected'] = self.DeviceTableMonthExpirationArray[curItem]\r\n self.DeviceExpirationData['year_selected'] = self.DeviceTableYearExpirationArray[curItem]\r\n\r\n #-------------- Using a Password Question to make sure it was the intent to be deleted ---------------\r\n def Remove_Device_From_DB(self):\r\n if Is_logging_Available:\r\n Parameter = []\r\n Parameter = ['Device','REMOVE Button'] \r\n Logging.Log(Parameter)\r\n if self.db.Connect():\r\n self.progress['maximum'] = 100\r\n self.progress['value'] = 0\r\n self.Selection = 'remove'\r\n #self.DeviceID = self.DeviceIDFrameEntry.get()\r\n PrimaryKey = (self.DeviceID)\r\n if (mbox.askyesnocancel(master=self.DeviceFrame,title='Device',message = 'Are you Sure you want to Remove it?')):\r\n #PrimaryKey = (self.CountryID+\"-\"+self.RegionID+\"-\"+self.DeviceID)\r\n #print (PrimaryKey)\r\n sql = \"\"\"\r\n SELECT * FROM Devices\r\n WHERE Device_ID = '%s'\r\n \"\"\" % (PrimaryKey) \r\n if (self.db.Execute(sql)):\r\n sql = \"DELETE FROM Devices WHERE Device_ID = '%s'\" % (PrimaryKey)\r\n if (self.db.Add_Move_Change_Data(sql)):\r\n #self.db.Disconnect()\r\n mbox.showwarning(master=self.DeviceFrame,title='Device',\r\n message = '*** The Device ID you entered was Removed ***')\r\n else:\r\n #self.db.Disconnect()\r\n mbox.showerror(master=self.DeviceFrame,title='Device',\r\n message = '*** The Device ID you entered was NOT Removed ***') \r\n self.on_sites_combo_changed(\"event\")\r\n self.Disable_Screen()\r\n else:\r\n mbox.showerror(master=self.DeviceFrame,title='Device',\r\n message = '*** The Device ID you try to Remove Does not exist Anymore ***')\r\n else:\r\n mbox.showerror(master=self.DeviceFrame,title='Device',\r\n message = '*** ERROR *** - THE ODBC Connection was NOT Succesful, \\r\\n'\r\n + 'Please make sure the ODBC DSN Name mathes: ['\r\n + self.ODBC_name + \"]\")\r\n\r\n def try_login(self):\r\n self.GetPasswordWindowsExists = True \r\n if self.password_guess.get() == \"BeCareful\":\r\n self.GetPasswordWindow.destroy()\r\n self.Remove_Device_From_DB()\r\n self.GetPasswordWindowsExists = False\r\n else:\r\n mbox.showerror(master=self.GetPasswordWindow,title='Username and Password',\r\n message = '*** ERROR *** - Please Enter a Valid Information')\r\n self.GetPasswordWindow.destroy()\r\n self.GetPasswordWindowsExists = False\r\n \r\n def try_login_Enter(self,event):\r\n self.try_login()\r\n \r\n def on_GetPasswordWindow_quit(self):\r\n self.GetPasswordWindowsExists = False\r\n self.GetPasswordWindow.destroy()\r\n\r\n def Get_Usernanme_and_Password(self):\r\n if not self.GetPasswordWindowsExists:\r\n self.password = \"\"\r\n self.username = \"\"\r\n self.GetPasswordWindowsExists = True\r\n self.GetPasswordWindow = Tk()\r\n self.GetPasswordWindow.resizable(width=FALSE, height=FALSE)\r\n self.GetPasswordWindow.protocol(\"WM_DELETE_WINDOW\", self.on_GetPasswordWindow_quit)\r\n self.GetPasswordWindow.title(\"Log-In\")\r\n self.GetPasswordWindow.geometry(\"200x150\")\r\n #Creating the username & password entry boxes\r\n self.username_text = Label(self.GetPasswordWindow, text=\"Username:\")\r\n self.username_guess = Entry(self.GetPasswordWindow)\r\n self.password_text = Label(self.GetPasswordWindow, text=\"Password:\")\r\n self.password_guess = Entry(self.GetPasswordWindow, show=\"*\")\r\n self.password_guess.bind('',self.try_login_Enter)\r\n self.attempt_login = Button(self.GetPasswordWindow,text=\"Login\", command = self.try_login) \r\n self.username_text.pack()\r\n self.username_guess.pack()\r\n self.password_text.pack()\r\n self.password_guess.pack()\r\n self.attempt_login.pack()\r\n self.GetPasswordWindow.mainloop()\r\n \r\n #-------------- Using a Password Question to make sure it was the intent to be deleted