diff --git "a/648.jsonl" "b/648.jsonl"
new file mode 100644--- /dev/null
+++ "b/648.jsonl"
@@ -0,0 +1,678 @@
+{"seq_id":"13994115","text":"from django.shortcuts import render\r\nimport requests\r\nimport datetime\r\nimport json\r\nimport base64\r\nfrom urllib.parse import urlencode\r\nfrom itertools import islice \r\nimport datetime\r\nfrom django.shortcuts import render, redirect\r\nfrom django.http import HttpResponse\r\nfrom django.db.models import Count, Sum, Max\r\nfrom json import dumps \r\n\r\nclient_id = ''\r\nclient_secret = ''#add your credentials \r\nclass SpotifyAPI(object):\r\n access_token = None\r\n access_token_expires = datetime.datetime.now()\r\n access_token_did_expire = True\r\n client_id = None\r\n client_secret = None\r\n token_url = \"https://accounts.spotify.com/api/token\"\r\n \r\n def __init__(self, client_id, client_secret, *args, **kwargs):\r\n super().__init__(*args, **kwargs)\r\n self.client_id = client_id\r\n self.client_secret = client_secret\r\n\r\n def get_client_credentials(self):\r\n \"\"\"\r\n Returns a base64 encoded string\r\n \"\"\"\r\n client_id = self.client_id\r\n client_secret = self.client_secret\r\n if client_secret == None or client_id == None:\r\n raise Exception(\"You must set client_id and client_secret\")\r\n client_creds = f\"{client_id}:{client_secret}\"\r\n client_creds_b64 = base64.b64encode(client_creds.encode())\r\n return client_creds_b64.decode()\r\n \r\n def get_token_headers(self):\r\n client_creds_b64 = self.get_client_credentials()\r\n return {\r\n \"Authorization\": f\"Basic {client_creds_b64}\"\r\n }\r\n \r\n def get_token_data(self):\r\n return {\r\n \"grant_type\": \"client_credentials\"\r\n } \r\n \r\n def perform_auth(self):\r\n token_url = self.token_url\r\n token_data = self.get_token_data()\r\n token_headers = self.get_token_headers()\r\n r = requests.post(token_url, data=token_data, headers=token_headers)\r\n if r.status_code not in range(200, 299):\r\n return False\r\n data = r.json()\r\n now = datetime.datetime.now()\r\n access_token = data['access_token']\r\n expires_in = data['expires_in'] # seconds\r\n expires = now + datetime.timedelta(seconds=expires_in)\r\n self.access_token = access_token\r\n self.access_token_expires = expires\r\n self.access_token_did_expire = expires < now\r\n return True\r\n\r\n\r\n\r\n\r\ndef mainView(request):\r\n spotify = SpotifyAPI(client_id, client_secret)\r\n spotify.perform_auth()\r\n access_token = spotify.access_token\r\n headers = {\r\n \"Authorization\": f\"Bearer {access_token}\"\r\n }\r\n endpoint = \"https://api.spotify.com/v1/browse/new-releases?&limit=21\"\r\n lookup_url = f\"{endpoint}\"\r\n r = requests.get(lookup_url, headers=headers)\r\n a = r.json()\r\n\r\n artist_name = []\r\n artist_url = []\r\n album_url = []\r\n album_pic = []\r\n album_name = []\r\n album_id = []\r\n albums_list = []\r\n album_track_total = []\r\n song_list = [] \r\n track_numbers = [] # list of length in which we have to split\r\n\r\n for x in range(0,21):#21 because it's Default limit in query it's 21 you can change it up to 50 in the endpoint\r\n album_id. append(a[\"albums\"][\"items\"][x]['id'])\r\n album_name. append(a[\"albums\"][\"items\"][x][\"name\"])\r\n album_pic. append(a[\"albums\"][\"items\"][x][\"images\"][1]['url'])\r\n artist_name. append(a[\"albums\"][\"items\"][x][\"artists\"][0]['name'])\r\n album_url. append(a[\"albums\"][\"items\"][x][\"external_urls\"]['spotify'])\r\n artist_url. append(a[\"albums\"][\"items\"][x][\"artists\"][0]['external_urls']['spotify'])\r\n \r\n \r\n \r\n \r\n\r\n\r\n for x in album_id :\r\n album_query = \"https://api.spotify.com/v1/albums/\"+x+ \"/tracks\"\r\n lookup_album_url = f\"{album_query}\"\r\n album_tracks_request = requests.get(lookup_album_url, headers=headers)\r\n albums_list.append(album_tracks_request.json())\r\n\r\n\r\n for x in albums_list:\r\n for y in range(len(x['items'])):\r\n song_list.append(x['items'][y][\"name\"])\r\n track_numbers.append(x['total'])\r\n\r\n\r\n song_list_input = iter(song_list) \r\n grouped_tracks = [list(islice(song_list_input, x)) for x in track_numbers] \r\n wholeData = list(zip(album_pic,album_url,album_name,artist_name,artist_url,grouped_tracks))\r\n\r\n context={\r\n 'wholeData' : wholeData \r\n }\r\n return render(request,'index.html',context)\r\n \r\n","sub_path":"albums/albumApp/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":4821,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"629909339","text":"import os\nimport argparse\nimport pandas as pd\nfrom common.commondir import CommonDir\nfrom pandas_datareader import data as pdr\nfrom common.InstMaster import InstMaster\nfrom IPython.display import display\n##################################################\n\n \n#### ========================================================================\ndef main():\n parser = argparse.ArgumentParser()\n parser.add_argument('-d', '--trd_date', help='trading_date', default='2021-01-14')\n parser.add_argument('-j', '--pname', default='smin0')\n parser.add_argument('--tag', default='SM0_21')\n args = parser.parse_args()\n\n date = args.trd_date\n pname = args.pname\n instMaster = InstMaster()\n inst_json = instMaster.getInstrumentJson()\n portfolio_config_dir = os.path.join(CommonDir.train2_output_dir,args.tag)\n \n today_orders = pd.DataFrame(columns=['date','type', 'ticker', 'ticker_id', 'is_buy', 'price', 'qty', 'start_price'])\n \n for inst in inst_json[pname]:\n ticker = inst['canonical_name']\n ss_df = pdr.get_data_yahoo(inst['symbol'], start=date, end=date)\n ss_df['d'] = ss_df.index\n ss_df = ss_df[ss_df['d'] == date]\n config_fp = os.path.join(portfolio_config_dir, ticker, 'optimize', 'final', 'strategy.csv')\n if os.path.exists(config_fp) == False:\n continue\n config_df = pd.read_csv(config_fp)\n \n c_edge = config_df['c_edge'].iloc[0]\n s_edge = config_df['s_edge'].iloc[0]\n f_edge = config_df['f_edge'].iloc[0]\n pos = inst['pos'] if 'pos' in inst else 0\n orders = inst['orders'] if 'orders' in inst else []\n realized_pnl = inst['pnl'] if 'pnl' in inst else 0\n order_size = inst['order_size'] if 'order_size' in inst else 1 \n lprice = ss_df['Close'].iloc[0]\n \n if pos == 0:\n propBid = lprice - s_edge * instMaster.getTickSize(lprice)\n propAsk = propBid + c_edge * instMaster.getTickSize(lprice)\n today_orders.loc[today_orders.shape[0]] = [date, 'normal', inst['symbol'], inst['canonical_name'], True, propBid, order_size, lprice]\n today_orders.loc[today_orders.shape[0]] = [date, 'stop', inst['symbol'], inst['canonical_name'], False, propAsk, order_size, lprice]\n else:\n for o in inst['orders']:\n propBid = o['price'] - f_edge * instMaster.getTickSize(lprice)\n propAsk = o['price'] + c_edge * instMaster.getTickSize(lprice)\n today_orders.loc[today_orders.shape[0]] = [date, 'normal', inst['symbol'], inst['canonical_name'], True, propBid, o['qty'], lprice]\n today_orders.loc[today_orders.shape[0]] = [date, 'stop', inst['symbol'], inst['canonical_name'], False, propAsk, o['qty'], lprice]\n \n display(today_orders)\n today_orders.to_csv(os.path.join(CommonDir.trading_dir, '{}.{}.csv'.format(pname,date)))\n\nif __name__ == '__main__':\n main()","sub_path":"trading/run_day_trading2.py","file_name":"run_day_trading2.py","file_ext":"py","file_size_in_byte":2953,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"188957085","text":"#! /usr/bin/env python\n\n\n\n#\n#$Author$\n#$Date$\n#$HeadURL$\n#$Revision$\n#\n\n\n\nimport sys\nimport os\nimport re\nimport math\nimport random\nfrom Tkinter import *\nclass Ballc:\n\tdef __init__(self, ISpeedX, ISpeedY, radius, min, max):\n\t\tself.ISpeed = [ISpeedX, ISpeedY]\n\t\tself.radius = radius\n\t\tself.CSpeed = [0,0]\n\t\tself.NCSpeed = [0,0]\n\t\tself.min = min\n\t\tself.max = max\n\t\t\n\t\t\n\tdef getISpeed(self):\n\t\treturn self.ISpeed\n\t\t\n\tdef getRadius(self):\n\t\treturn self.radius\n\t\t\n\tdef ChangeSpeed(self):\n\t\tscale = 0\n\t\twhile scale == 0:\n\t\t\tscale = random.uniform(self.min, self.max)\n\t\tx = self.CSpeed[0]\n\t\ty = self.CSpeed[1]\n\t\tcurrent = pow(pow(x,2)+pow(y,2),0.5)\n\t\tif current != 0:\n\t\t\tx = (x/current)\n\t\t\ty = (y/current)\n\t\t\tx = x*scale\n\t\t\ty = y*scale\n\t\t\tself.CSpeed = [x,y]\n\t\t\n\tdef InputObject(self, obj):\n\t\tself.obj = obj\n\t\t\n\t\t\n\tdef StartSpeed(self):\n\t\tself.CSpeed[0] = self.ISpeed[0]\n\t\tself.CSpeed[1] = self.ISpeed[1]\n\t\t\n\t\t\n\t\t\n\tdef FlipSpeeds(self):\n\t\ttemp = self.CSpeed[0]\n\t\tself.CSpeed[0] = self.NCSpeed[0]\n\t\tself.NCSpeed[0] = temp\n\t\ttemp = self.CSpeed[1]\n\t\tself.CSpeed[1] = self.NCSpeed[1]\n\t\tself.NCSpeed[1] = temp\n\t\t\n\tdef InputCoords(self, p1, p2):\n\t\tself.startpos = [p1,p2]\n\t\t\n\tdef restartpos(self, w, Starter):\n\t\tw.coords(self.obj, self.startpos[Starter][0], self.startpos[Starter][1], self.startpos[Starter][2], self.startpos[Starter][3])\n\t\t\n\t\t\n\t\t\nclass Paddlec:\n\tdef __init__(self, paddlenum, paddlewidth, paddleheight, paddlespeed):\n\t\tself.paddlenum = paddlenum\n\t\tself.height = paddleheight\n\t\tself.width = paddlewidth\n\t\tself.paddlespeed = paddlespeed\n\t\tself.easypaddlespeed = paddlespeed/2.5\n\t\tself.storedpaddlespeed = paddlespeed\n\t\tself.moveup = 0\n\t\tself.movedown = 0\n\tdef startmoveup(self):\n\t\tself.moveup = -(self.paddlespeed)\n\t\t#print self.moveup\n\tdef startmovedown(self):\n\t\tself.movedown = (self.paddlespeed)\n\t\t#print self.movedown\n\tdef endmoveup(self):\n\t\tself.moveup = 0\n\t\t#print self.moveup\n\tdef endmovedown(self):\n\t\tself.movedown = 0\n\t\t#print self.movedown\n\tdef InputObject(self, obj):\n\t\tself.obj = obj\n\tdef InputCoords(self, x1, y1, x2, y2):\n\t\tself.coords = [x1, y1, x2, y2]\n\t\t\n\tdef middle(self):\n\t\treturn int((self.coords[1]+self.coords[3])/2)\n\t\n\tdef restartpos(self, w):\n\t\tw.coords(self.obj, self.coords[0],self.coords[1],self.coords[2], self.coords[3])\n\tdef ImportCanvas(self, w):\n\t\tself.w = w\n\t\t\n\tdef CurrentMiddle(self):\n\t\tpass \n\t\t\n\t\t\nclass Board:\n\tdef __init__(self, CanvasWidth, CanvasHeight, WallLeft, WallTop, WallRight, WallBottom):\n\t\tself.CanvasWidth = CanvasWidth\n\t\tself.CanvasHeight = CanvasHeight\n\t\tself.WallLeft = WallLeft\n\t\tself.WallTop = WallTop\n\t\tself.WallRight = WallRight\n\t\tself.WallBottom = WallBottom\n\t\tself.ScoreBoard = [0,0]\n\t\tself.Score1String = StringVar()\n\t\tself.Score2String = StringVar()\n\t\tself.Score1String.set(str(self.ScoreBoard[0]))\n\t\tself.Score2String.set(str(self.ScoreBoard[1]))\n\t\t\n\t\t\n\tdef UpdateScore(self, Pl):\n\t\tself.ScoreBoard[Pl] = self.ScoreBoard[Pl] + 1\n\t\tself.Score1String.set(str(self.ScoreBoard[0]))\n\t\tself.Score2String.set(str(self.ScoreBoard[1]))\n\n\nclass GameParameters:\n\tdef __init__(self):\n\t\tself.GamePositions = []\n\t\tself.EndGame = 0\n\t\tself.Start = 0\n\t\tself.pause = 0\n\t\tself.notpause = 1\n\t\tself.Score1 = 0\n\t\tself.Score2 = 0\n\t\tself.ReplayOn = 0\n\t\tself.P1Replay = []\n\t\tself.P2Replay = []\n\t\tself.BReplay = []\n\t\tself.counter = 0\n\t\tself.Ncounter = 0\n\t\tself.File_Name = \"\"\n\t\tself.PlayerMode = 0\n\t\tself.AILocate = 0\t\n\t\tself.AIMoving = \"Stop\"\t\n\t\tself.ReactionTime = 10\n\t\tself.ReactionTimeCounter = 0\t\n\t\tself.GameStarted = 0 \t\n\t\tself.TimeCounter = 0\n\t\tself.ReleaseCounter = 0\n\t\tself.GameModeLast = 0\n\t\tself.trigger = 0\n\t\tself.PlayerModeLast = 0\n\t\tself.Pwidth = 25\n\t\tself.GameMode = 0\t\n\t\tself.PaddleTrigger = 0\n\t\tself.P1Prev = [0,0,0,0]\n\t\tself.AIHardMoving = \"Stop\"\n\t\tself.DoubleCheck = 0 \n\t\tself.FirstCheck = 0\n\t\tself.Space = 0\t\n\t\t\nclass AIProperties:\n\tdef __init__(self):\n\t\tself.moving = 0 \n\t\t\n\t\t\n\t\t\n\t\t\n\t\t\n\t\t\n","sub_path":"PongClasses.py","file_name":"PongClasses.py","file_ext":"py","file_size_in_byte":3848,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"50953193","text":"import urllib.request\nimport zipfile\nimport os\nimport time\nimport csv\nimport glob\n\nfilename = input('filename: ')\n\n#header_num = int(input('header number: '))\n\n#statsID = input('statsID: ')\n\ntemps = glob.glob('output/temporary/*')\n\nfor temp in temps:\n os.remove(temp)\n\nmeshes = []\n\n#with open('mesh-code.csv', 'r') as f:\n# meshes = sum(csv.reader(f), [])\n\nwith open('mesh-code.csv', 'r', encoding=\"utf-8\") as f:\n meshes = sum(csv.reader(f), [])\n\n#meshes = [str(y) + str(x) for y in range(36, 69) for x in range(22, 49)]\n#meshes_exist = []\n\nfor mesh in meshes:\n url = 'https://www.e-stat.go.jp/gis/statmap-search/data?dlserveyId=Q&code=%s&coordSys=1&format=shape&downloadType=5' % mesh\n try:\n urllib.request.urlretrieve(url, 'output/temporary/_.zip')\n\n with zipfile.ZipFile('output/temporary/_.zip') as zip:\n zip.extractall('output/temporary')\n\n os.remove('output/temporary/_.zip')\n\n time.sleep(0.2)\n\n except:\n print('Mesh %s is not exist' % mesh)\n\n#for temp in temps:\n# os.remove(temp) \n","sub_path":"mesh-boundary.py","file_name":"mesh-boundary.py","file_ext":"py","file_size_in_byte":1053,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"418362739","text":"import numpy as np\nimport h5py\nimport time\nfrom pprint import pprint\nfrom sklearn.metrics import confusion_matrix \n\nlabel_map = [\n 'Airplane', \n 'Bag', \n 'Cap', \n 'Car', \n 'Chair', \n 'Earphone', \n 'Guitar', \n 'Knife', \n 'Lamp', \n 'Laptop', \n 'Motorbike', \n 'Mug', \n 'Pistol', \n 'Rocket', \n 'Skateboard', \n 'Table', \n]\n\ndef compute_iou(y_pred, y_true, c):\n y_pred = y_pred.flatten()\n y_true = y_true.flatten()\n \n pred_labels = {x: {'true':0, 'false': 0} for x in list(set(list(y_pred) + list(y_true)))}\n \n for p, t in zip(y_pred, y_true):\n if p == t:\n pred_labels[p]['true'] += 1\n else:\n pred_labels[p]['false'] += 1\n pred_labels[t]['false'] += 1\n \n del_key_arr = []\n \n# for k, v in pred_labels.items(): \n# if pred_labels[k]['true'] < 80:\n# del_key_arr.append(k)\n \n for k in del_key_arr:\n del pred_labels[k]\n \n # print(pred_labels)\n \n iou_arr = []\n \n for v in pred_labels.values():\n iou = v['true'] / (v['true'] + v['false'])\n iou_arr.append(iou) \n \n # print(np.mean(iou_arr), np.mean(y_pred == y_true))\n# time.sleep(1)\n return np.mean(iou_arr)\n \ndef main():\n # sample, gt, class\n f = h5py.File('./Results/train_pt_enc_local_dec/segmentation_result.hdf5', 'r')\n# f = h5py.File('./Results/train_cd_mean2/segmentation_result.hdf5', 'r')\n sample_arr = np.array(f['sample'])\n gt_arr = np.array(f['gt'])\n class_arr = np.array(f['class'])\n \n dd = {0:0, 1:0, 2:0, 3:0, 4:0, 5:0, 6:0, 7:0, 8:0, 9:0, 10:0}\n idx_arr = []\n miou_arr = []\n acc_arr = []\n \n class_dict = {x: [] for x in range(16)}\n \n for idx in range(len(sample_arr)):\n s, g, c = sample_arr[idx], gt_arr[idx], class_arr[idx]\n k = int(np.mean(s == g) * 10)\n \n# if k < 1:\n# continue\n \n miou = compute_iou(s, g, c)\n \n miou_arr.append(miou)\n acc = np.mean(s == g)\n acc_arr.append(acc)\n \n class_dict[c].append([miou, acc])\n \n# for k, v in class_dict.items():\n# v = np.array(v)\n# # print(v)\n# print(f'class {label_map[k]} len {len(v)} miou mean {np.mean(v[:, 0])}, acc mean {np.mean(v[:, 1])}')\n \n \n print('miou mean ', np.mean(miou_arr))\n print('miou std ', np.std(miou_arr))\n print('acc mean ', np.mean(acc_arr))\n print('acc std ', np.std(acc_arr))\n \nif __name__ == '__main__':\n main()","sub_path":"code/code1/acc_eval.py","file_name":"acc_eval.py","file_ext":"py","file_size_in_byte":2580,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"66619389","text":"#!//usr/bin/python\n\nimport os\nimport sys\n\nfrom binSearch import binSearch\n\ndef father(array, element_to_search):\n\tarray1 = array[:len(array)/2]\n\tarray2 = array[len(array)/2:]\n\tnew_fork = os.fork() #fork of this program\n\tif new_fork != 0:\n\t\tprint(\"elemento \" + (\"nao esta\" if binSearch(array1, element_to_search) == -1 else \"esta\") + \" na parte 1\")\n\telse:\n\t\tprint(\"elemento \" + (\"nao esta\" if binSearch(array2, element_to_search) == -1 else \"esta\") + \" na parte 2\")\n\nfather([1, 2, 3, 4, 5, 6, 7, 8, 9, 0], 3)\n","sub_path":"myOwnTest.py","file_name":"myOwnTest.py","file_ext":"py","file_size_in_byte":508,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"345701421","text":"# Continuous Optimization: Shifted Schwefel's Problem 2.21 (F2) with D=50\n\n# Import all the necessary packages\nimport numpy as np\nimport pandas as pd\nfrom scipy.optimize import minimize\nimport matplotlib.pyplot as plt\nimport time\n\n\n# Read data from csv\nraw_data = pd.read_csv(\"Data/Schwefel_data.csv\")\nschwefel = raw_data[\"val\"].tolist()\nprint(schwefel)\nprint(type(schwefel))\n\n\n# Initialize function parameters\nD = 50\nbias = -450\nlower_bound = -100\nupper_bound = 100\nsol_list = []\n\n\n# Define the Shifted Schwefel's Problem 2.21 with the previous parameters\ndef function(x, data=schwefel, dim=D, f_bias=bias):\n F = abs(x[0] - data[0])\n for i in range(1, dim - 1):\n z = x[i] - data[i]\n F = max(F, abs(z))\n res = F + f_bias\n return res\n\n\n# Create a function to gather all the solutions computed. To be used in callback\ndef sol_set(xk):\n sol_res = function(xk)\n sol_list.append(sol_res)\n return sol_res\n\n\n# Create a function to compute the initial guess with random uniform distribution\ndef sol_init(dim, lower_bound, upper_bound):\n xmin = lower_bound * np.ones(dim)\n xmax = upper_bound * np.ones(dim)\n x0 = np.random.uniform(min(xmin), max(xmax), dim)\n return x0\n\n\n# Create a function to solve this problem\ndef solver(dimension, lower_bound, upper_bound):\n global sol\n # Compute the initial guess\n x0 = sol_init(dimension, lower_bound, upper_bound)\n # Minimize the function thanks to the BFGS algorithm\n sol = minimize(sol_set, x0, bounds=(lower_bound, upper_bound), method='BFGS', callback=sol_set)\n return sol, sol_list\n\n\n# Create a function to plot the convergence curve\ndef plot_fitness(solution):\n fig = plt.figure(figsize=(16, 13))\n plt.plot(solution)\n plt.title(\"Continuous Optimization: Shifted Schwefel's Problem 2.21 (F2) with D=50\", fontsize=16)\n plt.xlabel(\"Time (iterations)\", fontsize=12)\n plt.ylabel(\"Fitness\", fontsize=12)\n plt.savefig(\"Screenshots/Schwefel_convergence_curve50.png\")\n plt.show()\n\n\n# Start timer to get computational time\nt1 = time.time()\n\n# Solve the problem\nsolver(D, lower_bound, upper_bound)\n\n# Stop timer and compute computational time\nt2 = time.time()\ncomp_time = t2 - t1\n\n\n# Print parameters and solutions\nprint(\"==========================================================================\\n\")\nprint(\"Function: Shifted Schwefel's Problem 2.21 (F2)\\n\")\nprint(\"01. Chosen algorithm to solve the problem: BFGS from SciPy\\n\")\nprint(\"02. Parameters:\")\nprint(\"\\nDimension:\", D)\nprint(\"\\nSearch space: [\", lower_bound, \",\", upper_bound, \"]\")\nprint(\"\\nBias:\", bias)\nprint(\"\\n03. Final results:\")\nsol_df = pd.DataFrame(sol.x, columns=[''])\nsol_df.to_csv(\"Schwefel_sol50.csv\", sep=\",\")\nprint(\"\\n - Solutions:\", sol_df)\nprint(\"\\n - Fitness:\", round(sol.fun, 2))\nprint(\"\\nNumber of function evaluations:\", sol.nfev)\nprint(\"\\nStopping criterion:\", sol.nit, \"iterations\")\nprint(\"\\nComputational time:\", round(comp_time, 2), \"seconds\\n\")\nprint(\"==========================================================================\")\n\n# Plot and save convergence curve\nplot_fitness(sol_list)\n","sub_path":"04-Shifted_Schwefels_Problem/Shifted_Schwefel_dim50.py","file_name":"Shifted_Schwefel_dim50.py","file_ext":"py","file_size_in_byte":3091,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"467989416","text":"\"\"\"materialproject URL Configuration\n\nThe `urlpatterns` list routes URLs to views. For more information please see:\n https://docs.djangoproject.com/en/2.2/topics/http/urls/\nExamples:\nFunction views\n 1. Add an import: from my_app import views\n 2. Add a URL to urlpatterns: path('', views.home, name='home')\nClass-based views\n 1. Add an import: from other_app.views import Home\n 2. Add a URL to urlpatterns: path('', Home.as_view(), name='home')\nIncluding another URLconf\n 1. Import the include() function: from django.urls import include, path\n 2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))\n\"\"\"\n# from django.contrib import admin\nfrom django.urls import path\n\nfrom mattest import views\n\nfrom baton.autodiscover import admin\nfrom django.conf.urls import include\n\nfrom rest_framework import routers\nfrom mattest import views\n\nrouter = routers.DefaultRouter()\nrouter.register(r'users', views.UserViewSet)\nrouter.register(r'groups', views.GroupViewSet)\nrouter.register(r'campaigns', views.CampaignViewSet)\nrouter.register(r'contact', views.ContactViewSet)\nrouter.register(r'contactlist', views.ContactListViewSet)\n\n\nurlpatterns = [\n path('', views.SendCampaign.as_view()),\n path('user/', admin.site.urls),\n path('baton/', include('baton.urls')),\n path('api/', include(router.urls)),\n path('api-auth/', include('rest_framework.urls', namespace='rest_framework')),\n path('campaign/send/', views.SendCampaign.as_view()),\n path('accounts/profile/', views.loginSucess),\n]\n","sub_path":"marketingapp/materialproject/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1528,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"575108301","text":"#==============================================================================\n# Entidad\t\t\t:\n# Proyecto\t\t\t:\tEVL (Evaluación de Python 3.6.1.)\n# Módulo\t\t\t:\n# Fecha\tCreación\t:\t19Abr2018\n# Periódo : 19Abr/2018\n# Objetivo\t\t\t:\tImport datetime\n# Fecha Edición\t\t:\n# Descripción\t\t: datetime y locale\n#==============================================================================\nfrom datetime import date\nimport locale\n\nhoy = date.today();\nprint(\"Fecha de hoy : \", hoy)\n\n#locale.setlocale(locale.LC_ALL, locale.getdefaultlocale())\n\nhoy.strftime(\"%m-%d-%y. %d %b %Y es %A. hoy es %d de %B.\")\nprint(hoy)\n\nnacimiento = date(1969,8,6)\nprint(\"Fecha Nacimiento\", nacimiento)\nedad = hoy - nacimiento\nprint(\"Edad = \", edad)\n\n","sub_path":"BVAPYHEVL1001v01Bibliotecas/pe/etg/bbva/evalua/view/CV1401v01ImportDatetimeLocale.py","file_name":"CV1401v01ImportDatetimeLocale.py","file_ext":"py","file_size_in_byte":731,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"627400323","text":"import subprocess, sys, os\nfrom core import Submission\n\nsys.stdout = open(os.devnull, 'w') # do NOT remove this code, place logic & imports below this line\n\nimport pandas as pd\nimport numpy as np\nimport ta\nimport lightgbm as lgb\n\nfrom joblib import load\n\nlgbm = lgb.Booster(model_file='lgbm.txt')\n\nmassive_df_length = 1565\n\nbidSizeList = ['bidSize' + str(i) for i in range(0,15)]\naskSizeList = ['askSize' + str(i) for i in range(0,15)]\nbidRateList = ['bidRate' + str(i) for i in range(0,15)]\naskRateList = ['askRate' + str(i) for i in range(0,15)]\n\n\"\"\"\nPYTHON submission\n\nImplement the model below\n\n##################################################### OVERVIEW ######################################################\n\n1. Use get_next_data_as_string() OR get_next_data_as_list() OR get_next_data_as_numpy_array() to recieve the next row of data\n2. Use the predict method to write the prediction logic, and return a float representing your prediction\n3. Submit a prediction using self.submit_prediction(...)\n\n################################################# OVERVIEW OF DATA ##################################################\n\n1. get_next_data_as_string() accepts no input and returns a String representing a row of data extracted from data.csv\n Example output: '1619.5,1620.0,1621.0,,,,,,,,,,,,,1.0,10.0,24.0,,,,,,,,,,,,,1615.0,1614.0,1613.0,1612.0,1611.0,\n 1610.0,1607.0,1606.0,1605.0,1604.0,1603.0,1602.0,1601.5,1601.0,1600.0,7.0,10.0,1.0,10.0,20.0,3.0,20.0,27.0,11.0,\n 14.0,35.0,10.0,1.0,10.0,13.0'\n\n2. get_next_data_as_list() accepts no input and returns a List representing a row of data extracted from data.csv,\n missing data is represented as NaN (math.nan)\n Example output: [1619.5, 1620.0, 1621.0, nan, nan, nan, nan, nan, nan, nan, nan, nan, nan, nan, nan, 1.0, 10.0,\n 24.0, nan, nan, nan, nan, nan, nan, nan, nan, nan, nan, nan, nan, 1615.0, 1614.0, 1613.0, 1612.0, 1611.0, 1610.0,\n 1607.0, 1606.0, 1605.0, 1604.0, 1603.0, 1602.0, 1601.5, 1601.0, 1600.0, 7.0, 10.0, 1.0, 10.0, 20.0, 3.0, 20.0,\n 27.0, 11.0, 14.0, 35.0, 10.0, 1.0, 10.0, 13.0]\n\n3. get_next_data_as_numpy_array() accepts no input and returns a Numpy Array representing a row of data extracted from\n data.csv, missing data is represented as NaN (math.nan)\n Example output: [1.6195e+03 1.6200e+03 1.6210e+03 nan nan nan nan nan nan nan nan nan nan nan nan 1.0000e+00\n 1.0000e+01 2.4000e+01 nan nan nan nan nan nan nan nan nan nan nan nan 1.6150e+03 1.6140e+03 1.6130e+03 1.6120e+03\n 1.6110e+03 1.6100e+03 1.6070e+03 1.6060e+03 1.6050e+03 1.6040e+03 1.6030e+03 1.6020e+03 1.6015e+03 1.6010e+03\n 1.6000e+03 7.0000e+00 1.0000e+01 1.0000e+00 1.0000e+01 2.0000e+01 3.0000e+00 2.0000e+01 2.7000e+01 1.1000e+01\n 1.4000e+01 3.5000e+01 1.0000e+01 1.0000e+00 1.0000e+01 1.3000e+01]\n\n##################################################### IMPORTANT ######################################################\n\n1. One of the methods get_next_data_as_string(), get_next_data_as_list(), or get_next_data_as_numpy_array() MUST be used and\n _prediction(pred) MUST be used to submit below in the solution implementation for the submission to work correctly.\n2. get_next_data_as_string(), get_next_data_as_list(), or get_next_data_as_numpy_array() CANNOT be called more then once in a\n row without calling self.submit_prediction(pred).\n3. In order to debug by printing do NOT call the default method `print(...)`, rather call self.debug_print(...)\n\n\"\"\"\n\n\n# class MySubmission is the class that you will need to implement\nclass MySubmission(Submission):\n\n \"\"\"\n get_prediction(data) expects a row of data from data.csv as input and should return a float that represents a\n prediction for the supplied row of data\n \"\"\"\n def get_prediction(self, data):\n X = data.replace([np.inf, -np.inf], np.nan).values\n return np.clip(lgbm.predict(np.atleast_2d(X)), -5, 5)[0]\n\n \"\"\"\n run_submission() will iteratively fetch the next row of data in the format\n specified (get_next_data_as_string, get_next_data_as_list, get_next_data_as_numpy_array)\n for every prediction submitted to self.submit_prediction()\n \"\"\"\n def run_submission(self):\n\n self.debug_print(\"Use the print function `self.debug_print(...)` for debugging purposes, do NOT use the default `print(...)`\")\n massive_df = pd.DataFrame()\n\n # only need last 15\n def create_limited_features(df):\n df = pd.DataFrame([df])\n df.columns = [*askRateList, *askSizeList, *bidRateList, *bidSizeList]\n df['midRate'] = (df.bidRate0 + df.askRate0) / 2 # necessary for ohlc\n df['OIR'] = (df.bidSize0 - df.askSize0)/(df.bidSize0 + df.askSize0)\n df['totalAskVol'] = df[askSizeList].sum(axis=1)\n df['totalBidVol'] = df[bidSizeList].sum(axis=1)\n df['OIR_total'] = (df.totalBidVol - df.totalAskVol)/(df.totalBidVol + df.totalAskVol)\n\n df['spread'] = df.askRate0 - df.bidRate0\n df['vwaBid'] = np.einsum('ij,ji->i', df[bidRateList], df[bidSizeList].T) / df[bidSizeList].sum(axis=1)\n df['vwaAsk'] = np.einsum('ij,ji->i', df[askRateList], df[askSizeList].T) / df[askSizeList].sum(axis=1)\n df['vwaBidDMid'] = df.midRate - df.vwaBid\n df['vwaAskDMid'] = df.vwaAsk - df.midRate\n df['diff_vwaBidAskDMid'] = df.vwaAskDMid - df.vwaBidDMid\n\n b1, a1 = (df.bidRate0 < df.bidRate0.shift(1)), (df.askRate0 < df.askRate0.shift(1))\n b2, a2 = (df.bidRate0 == df.bidRate0.shift(1)), (df.askRate0 == df.askRate0.shift(1))\n valsB, valsA = [0, (df.bidSize0 - df.bidSize0.shift(1))], [0, (df.askSize0 - df.askSize0.shift(1))]\n df['deltaVBid'] = np.select([b1,b2], valsB, default=df.bidSize0)\n df['deltaVAsk'] = np.select([a1,a2], valsA, default=df.askSize0)\n df['VOI'] = df.deltaVBid - df.deltaVAsk\n return df\n\n def append_to_df(massive_df, row):\n return massive_df.append(row, sort=False)\n\n def add_time_features(df, massive_df_length):\n tsi = [87, 261, 348, 435, 522]\n trix = [87, 174, 348, 435, 522]\n for t in tsi: df['tsi' + str(t)] = ta.momentum.tsi(df.midRate, s=t, r=2.25*t)\n for t in trix: df['trix' + str(t)] = ta.trend.trix(df.midRate, n=t)\n return df[-massive_df_length:]\n\n while(True):\n \"\"\"\n NOTE: Only one of (get_next_data_as_string, get_next_data_as_list, get_next_data_as_numpy_array) can be used\n to get the row of data, please refer to the `OVERVIEW OF DATA` section above.\n\n Uncomment the one that will be used, and comment the others.\n \"\"\"\n\n base_row = self.get_next_data_as_string()\n df = [float(x) if x else 0 for x in base_row.split(',')]\n row = create_limited_features(df)\n massive_df = append_to_df(massive_df, row)\n massive_df = add_time_features(massive_df, massive_df_length)\n data = pd.DataFrame([massive_df.iloc[-1]])\n prediction = self.get_prediction(data)\n\n \"\"\"\n submit_prediction(prediction) MUST be used to submit your prediction for the current row of data\n \"\"\"\n self.submit_prediction(prediction)\n\nif __name__ == \"__main__\":\n MySubmission()\n","sub_path":"XTXStarterKit-dev/python/submission.py","file_name":"submission.py","file_ext":"py","file_size_in_byte":7366,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"2272358","text":"from tkinter import *\n\n\ndef is_prime(integer):\n if integer < 2:\n return False\n if integer == 2:\n return True\n else:\n for divider in range(2, integer):\n if integer % divider == 0:\n return False\n return True\n\n\ndef get_prime_list(number):\n prime_list = []\n count = i = 0\n while True:\n if count == number:\n break\n if is_prime(i):\n prime_list.append(i)\n count += 1\n i += 1\n return prime_list\n\n\ndef prime_output(number_primes, number_per_line):\n count = 0\n string = \"\"\n prime_list = get_prime_list(number_primes)\n for i in prime_list:\n if count == number_per_line:\n string += \"\\n\"\n count = 0\n string += format(i, \"4d\") + \", \"\n count += 1\n return string\n\n\ndef main():\n\n def run():\n nonlocal x\n x = int(input_one.get())\n output_one.delete(1.0, END)\n x = prime_output(x, 10)\n output_one.insert(END, x)\n\n root = Tk()\n root.title(\"Prime Generator\")\n\n x = \"\"\n\n frame1 = Frame(root)\n frame1.grid(row=1, sticky=W)\n frame2 = Frame(root)\n frame2.grid(row=2)\n\n Label(frame1, text=\"Enter number of primes: \", width=34).grid(row=1, column=1)\n runner = Button(frame1, text=\"Run\", width=34, command=lambda: run())\n runner.grid(row=1, column=2)\n Button(frame1, text=\"Restart\", command=lambda: output_one.delete(1.0, END), width=34).grid(row=2, column=2)\n\n input_one = Entry(frame1, textvariable=x, width=34)\n input_one.grid(row=2, column=1)\n\n output_one = Text(frame2, width=60, background=\"light gray\")\n output_one.grid(row=2, column=1)\n Button(root, width=68, text=\"QUIT\", command=root.destroy, fg=\"red\").grid(row=3)\n root.mainloop()\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"trianglePatternMaker/Public-Projects-master/primeGenerator/GUIPrime.py","file_name":"GUIPrime.py","file_ext":"py","file_size_in_byte":1830,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"611745654","text":"# uncompyle6 version 3.7.4\n# Python bytecode 2.7 (62211)\n# Decompiled from: Python 3.6.9 (default, Apr 18 2020, 01:56:04) \n# [GCC 8.4.0]\n# Embedded file name: /opt/devel/django-kombu/djkombu/__init__.py\n# Compiled at: 2011-08-01 06:01:28\n\"\"\"Kombu transport using the Django database as a message store.\"\"\"\nVERSION = (0, 9, 4)\n__version__ = ('.').join(map(str, VERSION))\n__author__ = 'Ask Solem'\n__contact__ = 'ask@celeryproject.org'\n__homepage__ = 'http://github.com/ask/django-kombu/'\n__docformat__ = 'restructuredtext'\n__license__ = 'BSD'","sub_path":"pycfiles/django-kombu-0.9.4.tar/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":540,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"372489909","text":"\"\"\"project automation for jupyterlab-outsource\"\"\"\nimport hashlib\nimport json\nimport os\nimport re\nimport sys\nfrom pathlib import Path\n\nimport doit.action\nimport doit.tools\n\n\ndef task_setup():\n \"\"\"perform early setup\"\"\"\n # trust the cache\n if not (C.CI and P.YARN_INTEGRITY.exists()):\n yield dict(\n name=\"js\",\n actions=[\n [\n *C.JLPM,\n \"--prefer-offline\",\n \"--ignore-optional\",\n *([\"--frozen-lockfile\"] if C.CI else []),\n ]\n ],\n targets=[P.YARN_INTEGRITY],\n file_dep=[P.YARN_LOCK, *P.ALL_PACKAGE_JSONS],\n )\n\n yield dict(\n name=\"pip\",\n actions=[[*C.PIP, \"install\", \"--no-deps\", \"--ignore-installed\", \"-e\", \".\"]],\n file_dep=[*B.ALL_PY_DIST],\n )\n\n yield dict(\n name=\"ext\",\n actions=[\n [\n *C.PY,\n P.ROOT / \"scripts/_labextension.py\",\n \"develop\",\n \"--overwrite\",\n C.PY_MOD,\n ]\n ],\n file_dep=[*B.ALL_PY_DIST],\n task_dep=[\"setup:pip\"],\n )\n\n\ndef task_build():\n yield dict(\n name=\"js:tsc\",\n actions=[[*C.LERNA, \"run\", \"build\"]],\n file_dep=[\n P.YARN_INTEGRITY,\n *P.ALL_TS,\n ],\n targets=[B.META_BUILDINFO],\n )\n\n ext_pkg_jsons = []\n\n for pkg_json, pkg in D.PKG_JSON_DATA.items():\n if \"jupyterlab\" not in pkg:\n continue\n name = pkg[\"name\"]\n ext_pkg_json = B.LABEXT / name / \"package.json\"\n ext_pkg_jsons += [ext_pkg_json]\n yield dict(\n name=f\"ext:{name}\",\n file_dep=[B.META_BUILDINFO, *U.js_deps(pkg_json)],\n actions=[\n [\n *C.LERNA,\n \"exec\",\n \"--scope\",\n name,\n \"jupyter\",\n \"labextension\",\n \"build\",\n \".\",\n ]\n ],\n targets=[ext_pkg_json],\n )\n\n yield dict(\n name=\"py\",\n file_dep=[*ext_pkg_jsons, *P.ALL_PY_SRC, P.LICENSE, P.README, *P.PY_SETUP],\n actions=[[*C.PY, \"setup.py\", \"sdist\", \"bdist_wheel\"]],\n targets=[*B.ALL_PY_DIST],\n )\n\n\ndef task_binder():\n \"\"\"get ready for interactive development\"\"\"\n yield dict(\n name=\"labextensions\",\n task_dep=[\"setup\"],\n actions=[[*C.JPY, \"labextension\", \"list\"]],\n )\n yield dict(name=\"all\", task_dep=[\"binder:labextensions\"], actions=[[\"echo\", \"ok\"]])\n\n\ndef task_lab():\n yield dict(\n name=\"launch\",\n task_dep=[\"binder\"],\n actions=[[\"jupyter\", \"lab\", \"--no-browser\", \"--debug\"]],\n )\n\n\ndef task_dist():\n for pkg_json, tgz in B.JS_TARBALL.items():\n yield dict(\n name=f\"js:{tgz.name}\",\n actions=[\n (doit.tools.create_folder, [P.DIST]),\n doit.action.CmdAction(\n [\"npm\", \"pack\", pkg_json.parent], shell=False, cwd=P.DIST\n ),\n ],\n file_dep=[B.META_BUILDINFO, *U.js_deps(pkg_json)],\n targets=[tgz],\n )\n yield dict(\n name=\"shasums\",\n actions=[(U.make_hashfile, [B.SHA256SUMS, B.ALL_HASH_DEPS])],\n targets=[B.SHA256SUMS],\n file_dep=[*B.ALL_HASH_DEPS],\n )\n\n\ndef task_watch():\n yield dict(\n name=\"ts\",\n task_dep=[\"setup\"],\n actions=[[*C.LERNA, \"run\", \"--stream\", \"--parallel\", \"watch\"]],\n )\n\n\ndef task_lint():\n \"\"\"apply source formatting, check for mistakes\"\"\"\n yield dict(\n name=\"black\",\n actions=[[\"isort\", *P.ALL_PY], [\"black\", *P.ALL_PY]],\n file_dep=[*P.ALL_PY],\n )\n\n yield dict(\n name=\"robot\",\n actions=[[*C.PYM, \"robot.tidy\", \"--inplace\", *P.ALL_ROBOT]],\n file_dep=P.ALL_ROBOT,\n )\n\n yield dict(\n name=\"flake8\",\n actions=[[\"flake8\", *P.ALL_PY]],\n task_dep=[\"lint:black\"],\n file_dep=[*P.ALL_PY],\n )\n\n yield dict(\n name=\"prettier\",\n actions=[\n [\n *C.JLPM,\n \"prettier\",\n \"--write\",\n \"--list-different\",\n *[p.relative_to(P.ROOT) for p in P.ALL_PRETTIER],\n ]\n ],\n file_dep=[*P.ALL_PRETTIER, P.YARN_INTEGRITY],\n )\n\n yield dict(\n name=\"eslint\",\n actions=[\n [\n *C.JLPM,\n \"eslint\",\n \"--cache\",\n \"--config\",\n P.ESLINTRC,\n \"--ext\",\n \".ts,.tsx\",\n \"--fix\",\n \"packages\",\n ]\n ],\n task_dep=[\"lint:prettier\"],\n file_dep=[*P.ALL_ESLINT, P.ESLINTRC],\n )\n\n\ndef task_test():\n yield dict(\n name=\"pytest\",\n actions=[[*C.PYM, \"pytest\"]],\n file_dep=[*P.ALL_PY_SRC],\n task_dep=[\"setup:pip\"] if not C.CI else [],\n )\n\n file_dep = [*P.ALL_ROBOT]\n task_dep = []\n\n if not C.CI:\n file_dep += [\n B.LABEXT / pkg_data[\"name\"] / \"package.json\"\n for pkg_json, pkg_data in D.PKG_JSON_DATA.items()\n if pkg_json != P.META_PKG_JSON\n ]\n task_dep += [\"setup\"]\n\n yield dict(\n name=\"robot\",\n actions=[\n (doit.tools.create_folder, [B.ATEST_OUT]),\n doit.action.CmdAction(\n [\n *C.PYM,\n \"robot\",\n *C.ATEST_ARGS,\n P.ATEST,\n ],\n shell=False,\n cwd=B.ATEST_OUT,\n ),\n ],\n file_dep=file_dep,\n task_dep=task_dep,\n )\n\n\nclass C:\n \"\"\"constants\"\"\"\n\n JLPM = [\"jlpm\"]\n LERNA = [*JLPM, \"lerna\"]\n PY = [sys.executable]\n PYM = [*PY, \"-m\"]\n PIP = [*PYM, \"pip\"]\n JPY = [*PYM, \"jupyter\"]\n TSBUILDINFO = \"tsconfig.tsbuildinfo\"\n ENC = dict(encoding=\"utf-8\")\n CORE_EXT = \"@deathbeds/\"\n CI = bool(json.loads(os.environ.get(\"CI\", \"0\")))\n ATEST_ARGS = json.loads(os.environ.get(\"ATEST_ARGS\", \"[]\"))\n PY_MOD = \"jupyterlab_outsource\"\n\n\nclass P:\n \"\"\"paths\"\"\"\n\n DODO = Path(__file__)\n ROOT = DODO.parent\n GH = ROOT / \".github\"\n LICENSE = ROOT / \"LICENSE\"\n README = ROOT / \"README.md\"\n BINDER = ROOT / \".binder\"\n DIST = ROOT / \"dist\"\n PACKAGES = ROOT / \"packages\"\n ATEST = ROOT / \"atest\"\n CORE = PACKAGES / \"jupyterlab-outsource\"\n CORE_PKG_JSON = CORE / \"package.json\"\n CORE_SRC = CORE / \"src\"\n CORE_LIB = CORE / \"lib\"\n\n META = PACKAGES / \"_meta\"\n META_PKG_JSON = META / \"package.json\"\n\n PY_SRC = ROOT / f\"src/{C.PY_MOD}\"\n PY_SETUP = [ROOT / \"setup.cfg\", ROOT / \"setup.py\", ROOT / \"MANIFEST.in\"]\n ALL_PY_SRC = [*PY_SRC.rglob(\"*.py\")]\n\n PACKAGE_JSONS = [*PACKAGES.glob(\"*/package.json\")]\n ROOT_PACKAGE_JSON = ROOT / \"package.json\"\n ALL_PACKAGE_JSONS = [ROOT_PACKAGE_JSON, *PACKAGE_JSONS]\n NODE_MODULES = ROOT / \"node_modules\"\n YARN_INTEGRITY = NODE_MODULES / \".yarn-integrity\"\n YARN_LOCK = ROOT / \"yarn.lock\"\n ESLINTRC = PACKAGES / \".eslintrc.js\"\n\n ALL_ROBOT = [*ATEST.rglob(\"*.robot\")]\n\n ALL_SCHEMA = [*PACKAGES.glob(\"*/schema/*.json\")]\n ALL_YAML = [*BINDER.glob(\"*.yml\"), *GH.rglob(\"*.yml\")]\n ALL_TS = [*PACKAGES.glob(\"*/src/**/*.ts\"), *PACKAGES.glob(\"*/src/**/*.tsx\")]\n ALL_MD = [*ROOT.glob(\"*.md\"), *PACKAGES.glob(\"*/*.md\")]\n ALL_JSON = [*ALL_PACKAGE_JSONS, *BINDER.glob(\"*.json\"), *ALL_SCHEMA]\n ALL_PRETTIER = [*ALL_JSON, *ALL_MD, *ALL_TS, *ALL_YAML]\n ALL_ESLINT = [*ALL_TS]\n ALL_PY = [*ROOT.glob(\"*.py\"), *ALL_PY_SRC]\n\n\nclass D:\n PKG_JSON_DATA = {\n pkg_json: json.loads(pkg_json.read_text(**C.ENC))\n for pkg_json in P.PACKAGE_JSONS\n }\n CORE_PKG_DATA = PKG_JSON_DATA[P.CORE_PKG_JSON]\n CORE_PKG_VERSION = CORE_PKG_DATA[\"version\"]\n\n\nclass U:\n @staticmethod\n def npm_tgz_name(pkg_json):\n name = pkg_json[\"name\"].replace(\"@\", \"\").replace(\"/\", \"-\")\n version = U.norm_js_version(pkg_json)\n return f\"\"\"{name}-{version}.tgz\"\"\"\n\n @staticmethod\n def norm_js_version(pkg):\n \"\"\"undo some package weirdness\"\"\"\n v = pkg[\"version\"]\n final = \"\"\n # alphas, beta use dashes\n for dashed in v.split(\"-\"):\n if final:\n final += \"-\"\n for dotted in dashed.split(\".\"):\n if final:\n final += \".\"\n if re.findall(r\"^\\d+$\", dotted):\n final += str(int(dotted))\n else:\n final += dotted\n return final\n\n @staticmethod\n def js_deps(pkg_json):\n pkg_dir = pkg_json.parent\n style = pkg_dir / \"style\"\n schema = pkg_dir / \"schema\"\n lib = pkg_dir / \"lib\"\n return [*style.rglob(\"*.*\"), *lib.rglob(\"*.*\"), *schema.glob(\"*.*\")] + (\n [\n pkg_json,\n pkg_dir / \"LICENSE\",\n pkg_dir / \"README.md\",\n ]\n if pkg_json != P.META_PKG_JSON\n else []\n )\n\n @staticmethod\n def make_hashfile(shasums, inputs):\n if shasums.exists():\n shasums.unlink()\n\n if not shasums.parent.exists():\n shasums.parent.mkdir(parents=True)\n\n lines = []\n\n for p in inputs:\n lines += [\" \".join([hashlib.sha256(p.read_bytes()).hexdigest(), p.name])]\n\n output = \"\\n\".join(lines)\n print(output)\n shasums.write_text(output)\n\n\nclass B:\n \"\"\"built things\"\"\"\n\n BUILD = P.ROOT / \"build\"\n META_BUILDINFO = P.META / C.TSBUILDINFO\n ATEST_OUT = BUILD / \"atest\"\n LABEXT = P.PY_SRC / \"labextensions\"\n WHEEL = P.DIST / f\"\"\"{C.PY_MOD}-{D.CORE_PKG_VERSION}-py3-none-any.whl\"\"\"\n SDIST = P.DIST / f\"\"\"jupyterlab-outsource-{D.CORE_PKG_VERSION}.tar.gz\"\"\"\n JS_TARBALL = {\n k: P.DIST / U.npm_tgz_name(v)\n for k, v in D.PKG_JSON_DATA.items()\n if k != P.META_PKG_JSON\n }\n ALL_PY_DIST = [WHEEL, SDIST]\n ALL_HASH_DEPS = [*ALL_PY_DIST, *JS_TARBALL.values()]\n SHA256SUMS = P.DIST / \"SHA256SUMS\"\n\n\nDOIT_CONFIG = {\n \"backend\": \"sqlite3\",\n \"verbosity\": 2,\n \"par_type\": \"thread\",\n \"default_tasks\": [\"binder\"],\n}\n","sub_path":"dodo.py","file_name":"dodo.py","file_ext":"py","file_size_in_byte":10335,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"120677633","text":"from typing import List\nclass Solution:\n def search(self, nums: List[int], target: int) -> int:\n l, r = 0, len(nums)-1\n while l < r:\n m = l + (r-l)//2\n if target == nums[m]:\n return m\n if nums[l] <= nums[m]:\n if nums[l] <= target <= nums[m]:\n r = m\n else:\n l = m+1\n elif nums[m] <= nums[r]:\n if nums[m] <= target <= nums[r]:\n l = m\n else:\n r = m-1\n return l if nums[l] == target else -1\n\ns = Solution()\nnums = [1,3]\ntarget = 2\nprint(s.search(nums, target))","sub_path":"1-99/Q33 copy.py","file_name":"Q33 copy.py","file_ext":"py","file_size_in_byte":557,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"396458892","text":"\n\nfrom xai.brain.wordbase.verbs._desalinate import _DESALINATE\n\n#calss header\nclass _DESALINATING(_DESALINATE, ):\n\tdef __init__(self,): \n\t\t_DESALINATE.__init__(self)\n\t\tself.name = \"DESALINATING\"\n\t\tself.specie = 'verbs'\n\t\tself.basic = \"desalinate\"\n\t\tself.jsondata = {}\n","sub_path":"xai/brain/wordbase/verbs/_desalinating.py","file_name":"_desalinating.py","file_ext":"py","file_size_in_byte":268,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"387673083","text":"import hashlib\nimport hmac\nimport requests\nimport json\nimport sys\nimport logging\nimport inspect\nfrom numbers import Number\n\nlogger = logging.getLogger('daowalletsdk')\nlogger.addHandler(logging.NullHandler())\n\n__all__ = [u'Wallet', u'API_URL', u'SDK_VERSION', u'WalletException', u'WalletArgumentException',\n 'WalletResponseException']\n\nAPI_URL = u'https://b2b.daowallet.com/api/v2'\nSDK_VERSION = u'1.0.0'\nAVAILABLE_CURRENCY = (u'BTC', u'ETH')\nAVAILABLE_FIAT_CURRENCY = (u'USD', u'EUR')\n\n\nclass WalletException(Exception):\n \"\"\"Base wallet error.\"\"\"\n\n\nclass WalletArgumentException(WalletException):\n \"\"\"Wrong arguments.\"\"\"\n\n\nclass WalletResponseException(WalletException):\n \"\"\"Bad response.\"\"\"\n\n\ndef check_args(fun):\n \"\"\"Wrapper for arguments checking.\n Check next arguments:\n ...currency must be in the list\n ...fiat_currency must be in the list\n ...amount must be positive float\n ...foreign_id must be string with less than 128 characters\n ...address must be string with less than 128 characters.\n \"\"\"\n\n def _check(*arguments):\n info = inspect.getfullargspec(fun) if sys.version_info[0] >= 3 else inspect.getargspec(fun) # 2.x compatibility\n for index, argument in enumerate(info[0]):\n if index < len(arguments):\n if argument == 'currency':\n if arguments[index] not in AVAILABLE_CURRENCY:\n raise WalletArgumentException(\n u'{} value not allowed, use one of {}.'.format(argument, u', '.join(AVAILABLE_CURRENCY)))\n elif argument == 'fiat_currency':\n if arguments[index] not in AVAILABLE_FIAT_CURRENCY:\n raise WalletArgumentException(\n u'{} value not allowed, use one of {}.'.format(argument,\n u', '.join(AVAILABLE_FIAT_CURRENCY)))\n elif argument == 'amount':\n if not isinstance(arguments[index], Number) and not isinstance(arguments[index], bool):\n raise WalletArgumentException(u'{} must be numeric type.'.format(argument))\n if arguments[index] <= 0:\n raise WalletArgumentException(u'{} must be positive.'.format(argument))\n elif argument == 'foreign_id' or argument == 'address':\n if not isinstance(arguments[index],\n str if sys.version_info[0] >= 3 else basestring): # 2.x compatibility\n raise WalletArgumentException(u'{} must be string type.'.format(argument))\n if len(arguments[index]) > 128:\n raise WalletArgumentException(u'{} too long.'.format(argument))\n if not arguments[index]:\n raise WalletArgumentException(u'{} string is empty.'.format(argument))\n return fun(*arguments)\n\n _check.__doc__ = fun.__doc__\n return _check\n\n\nclass Wallet:\n address_endpoint = u'addresses/take'\n withdrawal_endpoint = u'withdrawal/crypto'\n create_invoice_endpoint = u'invoice/new'\n status_invoice_endpoint = u'invoice/status'\n __logger = logger.getChild('wallet')\n\n def __init__(self, key, secret, url=API_URL):\n self.key = key\n self.secret = secret.encode(u'utf-8')\n self.url = url.rstrip('/')\n\n def __get_signature(self, json_msg):\n return hmac.new(self.secret, u''.join(json_msg.split()).encode(u'utf8'), hashlib.sha512).hexdigest()\n\n def __get_headers(self, signature):\n \"\"\"Get Headers for request.\n User-Agent for determine sdk requests on backend.\n \"\"\"\n return {\n u'X-Processing-Key': self.key,\n u'X-Processing-Signature': signature,\n u'Content-type': u'application/json; charset=utf-8',\n u'User-Agent': u'DAOWalletSDK/{} (Language=Python;)'.format(SDK_VERSION)\n }\n\n def __get_url(self, endpoint):\n \"\"\"Get full endpoint url. Independent of either\n is url ends with / or\n is endpoint starts with /.\n \"\"\"\n url = self.url + '/' + endpoint.lstrip('/')\n return url\n\n def __make_post_request(self, request, url):\n \"\"\"Make post request with data\n automatically dumps data to json\n and set headers.\n \"\"\"\n self.__logger.debug('Url requested: {}.'.format(url))\n json_msg = json.dumps(request)\n self.__logger.debug('Request body: {}.'.format(json_msg))\n headers = self.__get_headers(self.__get_signature(json_msg=json_msg))\n self.__logger.debug('Request headers: {}.'.format(headers))\n response = requests.post(url, data=json_msg, headers=headers)\n return self.__process_response(response)\n\n def __process_response(self, response):\n \"\"\"Handle most response processing errors.\"\"\"\n self.__logger.debug('Response body: {}.'.format(response.content))\n result = None\n err = 'Empty response.'\n try:\n result = response.json()\n except json.decoder.JSONDecodeError as e:\n if response.status_code not in (200, 201, 202):\n err = 'Unacceptable status code {}.'.format(response.status_code)\n self.__logger.error(err)\n else:\n err = 'Response is not valid json. {}.'.format(str(e))\n self.__logger.error(err)\n if not result:\n raise WalletResponseException(err)\n else:\n if response.status_code not in (200, 201, 202):\n err = 'Unacceptable status code {}'.format(response.status_code)\n if result.get('error'):\n err = result['error']\n if result.get('message'):\n err += ': {}.'.format(result['message'])\n self.__logger.error(err)\n raise WalletResponseException(err)\n else:\n return result\n\n @check_args\n def get_address(self, foreign_id, currency):\n \"\"\"Make new account.\n\n :param foreign_id: new account id.\n :param currency: account crypto currency.\n \"\"\"\n url = self.__get_url(self.address_endpoint)\n result = self.__make_post_request(dict(foreign_id=foreign_id, currency=currency), url)\n # unwrap response from data field of parent object\n if result.get('data'):\n return result['data']\n else:\n err = 'Response is not valid structure.'\n self.__logger.debug('Response body: {}.'.format(json.dumps(result)))\n self.__logger.error(err)\n raise WalletResponseException(err)\n\n @check_args\n def make_withdrawal(self, foreign_id, amount, currency, address):\n \"\"\"Make withdrawal request.\n\n :param foreign_id: sender account foreign_id.\n :param amount: requested coins amount.\n :param currency: crypto currency for withdrawal.\n :param address: recipient address.\n \"\"\"\n url = self.__get_url(self.withdrawal_endpoint)\n result = self.__make_post_request(\n dict(foreign_id=foreign_id, amount=amount, currency=currency, address=address),\n url)\n # unwrap response from data field of parent object\n if result.get('data'):\n return result['data']\n else:\n err = 'Response is not valid structure.'\n self.__logger.debug('Response body: {}.'.format(json.dumps(result)))\n self.__logger.error(err)\n raise WalletResponseException(err)\n\n @check_args\n def make_invoice(self, amount, fiat_currency):\n \"\"\"Create new invoice.\n\n :param amount: requested money amount.\n :param fiat_currency: fiat currency which will be used for invoice calculation.\n \"\"\"\n url = self.__get_url(self.create_invoice_endpoint)\n return self.__make_post_request(dict(amount=amount, fiat_currency=fiat_currency), url)\n\n @check_args\n def get_invoice(self, foreign_id):\n \"\"\"Get invoice status information.\n\n :param foreign_id: invoice foreign_id from 'make_invoice' function result.\n \"\"\"\n url = self.__get_url(self.status_invoice_endpoint)\n self.__logger.debug('Get invoice status by id: {}.'.format(foreign_id))\n response = requests.get(url, params=dict(id=foreign_id), headers=self.__get_headers(''))\n return self.__process_response(response)\n","sub_path":"daowalletsdk/daowallet.py","file_name":"daowallet.py","file_ext":"py","file_size_in_byte":8572,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"485753982","text":"import numpy as np\n\nimport pymc3 as pm\n\nfrom modules.utils.models_utils import AbastractModel\n\n\nclass BivariateRegression(AbastractModel):\n \"\"\"\n \"\"\"\n def __init__(self, X, y, intercept_prior=(0, 100), slope_prior=(0, 100),\n likelihood_sigma_prior=100, fit_intercept=True,\n logistic=False):\n \"\"\"\n \"\"\"\n self.intercept_prior = intercept_prior\n self.slope_prior = slope_prior\n self.likelihood_sigma_prior = likelihood_sigma_prior\n self.fit_intercept = fit_intercept\n self.X = X\n self.y = y\n self.logistic = logistic\n self.model = self.generate_model(X, y)\n\n def generate_model(self, X, y):\n \"\"\"\n \"\"\"\n with pm.Model() as model:\n if not self.fit_intercept:\n intercept = pm.math.constant(\n 0,\n name='Intercept'\n )\n else:\n intercept = pm.Normal(\n name='Intercept',\n mu=self.intercept_prior[0],\n sd=self.intercept_prior[1]\n )\n slope = pm.Normal(\n name='Slope',\n mu=self.slope_prior[0],\n sd=self.slope_prior[1]\n )\n\n if self.logistic:\n p = pm.Deterministic(\n 'p ~ Sigmoid(Intercept + Slope*X)',\n pm.math.sigmoid(intercept + slope * X)\n )\n likelihood = pm.Bernoulli(\n name='y',\n p=p,\n observed=y\n )\n\n else:\n mu = pm.Deterministic(\n 'mu ~ Intercept + Slope*X',\n intercept + slope * X\n )\n\n sigma = pm.HalfCauchy(\n name='Sigma',\n beta=self.likelihood_sigma_prior\n )\n\n likelihood = pm.Normal(\n name='y',\n mu=mu,\n sd=sigma,\n observed=y\n )\n\n return model\n\n\nclass PoissonAR1(AbastractModel):\n \"\"\"\n \"\"\"\n def __init__(self, X, y, intercept_prior, slope_prior):\n \"\"\"\n \"\"\"\n self.intercept_prior = intercept_prior\n self.slope_prior = slope_prior\n self.X = X\n self.y = y\n self.model = self.generate_model(X, y)\n\n def generate_model(self, X, y):\n \"\"\"\n \"\"\"\n with pm.Model() as ar_model:\n\n intercept = pm.Normal(\n mu=self.intercept_prior,\n name='Intercept'\n )\n slope = pm.Beta(\n alpha=self.slope_prior[0],\n beta=self.slope_prior[1],\n name='Slope'\n )\n\n lam = pm.Deterministic(\n 'lambda ~ exp(Intercept + Slope*yt-1)',\n pm.math.exp(intercept + slope*X)\n )\n\n outcome = pm.Poisson(\n mu=lam,\n observed=y,\n name='y'\n )\n\n return ar_model\n\n def show_posterior_summary(self, parameters_name, figsize=(10, 8),\n **kwargs):\n \"\"\"\n \"\"\"\n self.print_model_summary(parameters_name=parameters_name)\n if not self.map:\n with self.model:\n pm.plot_trace(self.traces, compact=True)\n\n\nclass PolynomialRegression(AbastractModel):\n \"\"\"\n \"\"\"\n def __init__(self, X, y, cubic=False, intercept_prior=(0, 1),\n slopes_prior=(0, 1), sigma_prior=1):\n \"\"\"\n \"\"\"\n self.X = X\n self.y = y\n self.cubic = cubic\n self.intercept_prior = intercept_prior\n self.slopes_prior = slopes_prior\n self.sigma_prior = sigma_prior\n self.model = self.generate_model(X, y, cubic)\n\n def generate_model(self, X, y, cubic=False):\n \"\"\"\n \"\"\"\n with pm.Model() as polynomial_model:\n\n intercept = pm.Normal(\n name='Intercept',\n mu=self.intercept_prior[0],\n sd=self.intercept_prior[1]\n )\n slope = pm.Normal(\n name='Slope',\n mu=self.slopes_prior[0],\n sd=self.slopes_prior[1]\n )\n slope1 = pm.Normal(\n name='Slope_1',\n mu=self.slopes_prior[0],\n sd=self.slopes_prior[1]\n )\n\n if not cubic:\n mu = pm.Deterministic(\n 'mu ~ Intercept + Sl*X + Sl_1*(X**2)',\n intercept + X*slope + np.power(X, 2)*slope1\n )\n else:\n slope2 = pm.Normal(\n name='Slope_2',\n mu=self.slopes_prior[0],\n sd=self.slopes_prior[1]\n )\n mu = pm.Deterministic(\n 'mu ~ Intercept + Sl*X + Sl_1*(X**2) + Sl_2*(X**3)',\n intercept +\n X*slope + np.power(X, 2)*slope1 + np.power(X, 3)*slope2\n )\n sigma = pm.Exponential(\n name='Sigma',\n lam=self.sigma_prior\n )\n\n likelihood = pm.Normal(\n name='y',\n mu=mu,\n sd=sigma,\n observed=y\n )\n\n return polynomial_model\n","sub_path":"modules/stats/models/linear_models.py","file_name":"linear_models.py","file_ext":"py","file_size_in_byte":5456,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"501029104","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Mon Apr 14 19:56:14 2014\n## Import html text, parse out headers,
, and in order\n## write to a single .csv file with the \"999filename\" as identifier\n## BENCHMARKING\n## Before Parallel Python, takes 6 minutes 15 seconds\n## After Parallel Python, takes 1 minute 6 seconds\n## 5.68 times faster - overhead lowers efficiency\n\n# TODO\n## This runs in the Spyder interpreter, but the command raises an IO error\n@author: tom\n\"\"\"\n\nimport os\nos.chdir('/home/tom/deepdive/app/isDB/scripts')\nfrom dictionaries import common_words_5000\nos.chdir('/home/tom/deepdive/app/isDB/data')\n#from bs4 import BeautifulSoup\nfrom time import gmtime, strftime\nimport re\nimport csv\nimport pp\n\n## Function to clean the text\ndef clean_text(string_in):\n string_in = string_in.replace(\"\\\\n\", \"\").replace(\"\\\\t\", \"\")\n string_in = string_in.replace(\"\\\\\", \" \").replace(\"\\\\r\", \"\")\n string_out = string_in.replace(\"[\", \"\")\n return(string_out)\n\n## Function to pass to workers\n## fileset is a list of file names\n## tag_matches is an re object with the tags we want from the Soup\n## word_dict is a dictionary of English words \ndef clean_file(fileset, tag_matches, word_dict):\n \n from bs4 import BeautifulSoup\n result_set =[]\n \n ## A function for checking if the string contains characters a-z\n import re\n check = re.compile(r'[a-z]').search\n \n ## Open the file, make the Soup\n for filename in fileset:\n file_in = open(\"linkto/\" + filename, 'r')\n soup = BeautifulSoup(' '.join(file_in.readlines()))\n file_in.close()\n \n ## Extract the text lines, format them\n i = 0\n all_text = 1000*[0]\n #for item in soup.stripped_strings:\n for item in soup.find_all(tag_matches):\n i += 1 \n if (\"script\" in item.name):\n temp = 0\n elif item.string is None:\n temp = 0\n else:\n temp = item.string\n temp = temp.encode('ascii', 'replace')\n temp = clean_text(temp)\n \n ## Make sure the text contains characters a-z\n if (temp != 0) and not bool(check(temp)):\n temp = 0\n ## Make sure the text doesn't contain css or http\n if (temp != 0) and (\"http\" in temp):\n temp = 0\n if (temp != 0) and (\"css\" in temp):\n temp = 0\n \n ## Check if the text contains one of the dictionary words\n contains_word = False\n word_index = 0\n if (temp != 0):\n while (contains_word == False and (word_index < len(word_dict))):\n if ((\" \" + word_dict[word_index] + \" \") in temp):\n contains_word = True\n word_index += 1\n \n if contains_word == False:\n temp = 0\n \n ## Add non-zero entries to the text list\n if temp == 0:\n pass\n elif i < len(all_text):\n all_text[i] = temp\n else:\n all_text.append(temp)\n \n ## Remove all zeros and shorten the vector\n all_text = filter(lambda a: a != 0, all_text)\n result_set.append(' '.join(all_text))\n \n return([fileset, result_set])\n \n################################################ \n \n# MAIN SCRIPT \n## Initialize some values\nstart_time = (strftime(\"%Y-%m-%d %H:%M:%S\", gmtime()))\nfilenames = os.listdir(os.getcwd() + \"/linkto\") # directory with html files\nrun_number = 0\n\n## Get the 5000 most common English words from\n## http://www.englishclub.com/vocabulary/common-words-5000.htm\n## uses the script get_common_words.py\nword_dict = common_words_5000()\nword_dict.extend([\"GPA\", \"TOEFL\", \"SAT\", \"GRE\"])\ntag_matches = re.compile(r'a{1}|p{1}|h[0-9]')\n\n## Set up the workers (parallelize the job)\njob_server = pp.Server()\nnum_cpus = job_server.get_ncpus() \nprint(\"Using \" + str(num_cpus) + \" CPUs\")\njobs = []\nset_len = len(filenames) // num_cpus\n\nfor i in range(num_cpus):\n if i < (num_cpus - 1):\n file_set = filenames[i * set_len : (i + 1) * set_len]\n else:\n file_set = filenames[i * set_len: ]\n jobs.append(job_server.submit(clean_file, \n (file_set, tag_matches, word_dict), \n depfuncs=(clean_text, )))\n #modules=(,)))\n## Organize the results \nresults = []\nfor job in jobs:\n results.append(job()) \nall_results = []\nfile_names = []\nfor names, result in results:\n all_results.extend(result)\n file_names.extend(names)\n \n## Write the results to .csv\ncsv_file = open(\"link_to.csv\", 'w')\nwriter = csv.writer(csv_file, delimiter=',') \nfor i in range(len(file_names)):\n writer.writerow([\"999\" + file_names[i].replace(\".html\", \"\")] + \\\n [all_results[i]]) \ncsv_file.close()\n\n## Get performance\nend_time = (strftime(\"%Y-%m-%d %H:%M:%S\", gmtime()))\nprint(\"Start Time: \" + start_time)\nprint(\"End Time: \" + end_time)\n","sub_path":"scripts/scrape/html_to_csv.py","file_name":"html_to_csv.py","file_ext":"py","file_size_in_byte":5167,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"97942371","text":"from django.shortcuts import render\n\n# Create your views here.\nfrom django.views.decorators.csrf import csrf_exempt\n\n@csrf_exempt\ndef start_page(request):\n return render(request,'start.html')\n\ndef word_test(request):\n step = request.GET.get('step')\n name = request.GET.get('name')\n answer = request.GET.get('answer')\n\n # print(step)\n\n words = {\n \"hello\": \"used as a greeting when you meet somebody, when you answer the telephone or when you want to attract somebody’s attention\",\n \"ninja\": \"a person trained in traditional Japanese skills of fighting and moving quietly\",\n \"owl\": \"a bird of prey (= a bird that kills other creatures for food) with large round eyes, that hunts at night. Owls are traditionally thought to be wise.\",\n \"programmer\": \"a person whose job is writing programs for computers\",\n \"laptop\": \"a small computer that can work with a battery and be easily carried\"\n }\n if int(step)==0:\n answer_list=None\n\n\n elif int(step)==1:\n answer_list = answer\n\n else:\n answer_list = request.GET.get('answer_list')\n answer_list += ',' + answer\n\n if int(step)!=5:\n ctx = {\n 'word': list(words.keys())[int(step)],\n 'meaning': list(words.values())[int(step)],\n 'counts': range(5),\n 'step': int(step) + 1,\n 'name': name,\n 'answer': answer,\n 'answer_list': answer_list\n }\n return render(request, 'test.html',ctx)\n\n else:\n answer_list = request.GET.get('answer_list')\n answer_list += ',' + answer\n print(answer_list)\n answer_list=answer_list.split(',')\n sol=list(words.keys())\n result=''\n for i in range(5):\n if sol[i]==answer_list[i]:\n result+=str(i+1)+'번 정답 : {} '.format(sol[i])+\\\n ' 제출한 답 : {} ==> '.format(answer_list[i])+'맞았습니다
'\n else:\n result+=str(i+1)+'번 정답 : {} '.format(sol[i])+\\\n ' 제출한 답 : {} ==> '.format(answer_list[i])+'틀렸습니다
'\n ctx={\n 'name':name,\n 'word':list(words.keys()),\n 'result': result\n }\n return render(request,'result.html',ctx)\n\n\n\n\n","sub_path":"word_test/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2350,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"221115756","text":"import sys\nimport SIEVE, FACTOR\n\ndef divisors(n, primes): # number of divisors of n\n\tif n == 1: return 1\n\tp, k, m = FACTOR.factor(n, primes)\n\treturn (1+k) * divisors(m, primes)\n\t\ndef sum_divisors(n, primes): # sum of divisors of n\n\tif n == 1: return 1\n\tp, k, m = FACTOR.factor(n, primes)\n\treturn ((p ** (k+1) - 1)//(p - 1)) * sum_divisors(m, primes)\n\ndef prime_parity(n, primes): # (-1)^(number of distinct primes dividing n)\n\tif n == 1: return 1\n\tp, k, m = FACTOR.factor(n, primes)\n\treturn (-1) * prime_parity(m, primes)\n\t\ndef euler_phi(n, primes): # number of a (1 <= a <= n) such that gcd(a,n) == 1\n\tif n == 1: return 1\n\tp, k, m = FACTOR.factor(n, primes)\n\treturn (p ** (k-1)) * (p-1) * euler_phi(m, primes)\n\t\ndef moebius(n, primes): # (-1)^(number of primes dividing n) if n square-free; 0 otherwise\n\tif n == 1: return 1\n\tp, k, m = FACTOR.factor(n, primes)\n\treturn (0 if k >= 2 else -1) * moebius(m, primes)\n\ndef main():\n\tMAXP = 100000\n\tprimes = SIEVE.sieve(MAXP)\n\tfor line in sys.stdin:\n\t\tn = int(line.rstrip())\n\t\tassert n <= MAXP*MAXP\n\t\t#print(divisors(n, primes), sum_divisors(n, primes), prime_parity(n, primes), euler_phi(n, primes), moebius(n, primes))\n\t\tprint(divisors(n, primes))\n\t\tsys.stdout.flush()\n\nif __name__ == '__main__': main()\n","sub_path":"DIVISORS.py","file_name":"DIVISORS.py","file_ext":"py","file_size_in_byte":1248,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"318251474","text":"import hashlib\nimport logging\nimport os\nimport shutil\nimport sys\nimport tarfile\nimport tempfile\nimport urllib.error\nimport urllib.parse\nimport urllib.request\nimport zipfile\nfrom contextlib import closing\nfrom urllib.parse import urlparse\n\nimport boto3\nimport click\nimport requests\nimport ujson\n\nCHUNK_SIZE = 1024\n\n\ndef get_files(path):\n \"\"\"Returns an iterable containing the full path of all files in the\n specified path.\n\n :param path: string\n :yields: string\n \"\"\"\n if os.path.isdir(path):\n for (dirpath, dirnames, filenames) in os.walk(path):\n for filename in filenames:\n if not filename[0] == \".\":\n yield os.path.join(dirpath, filename)\n else:\n yield path\n\n\ndef read_json(path):\n \"\"\"Returns JSON dict from file.\n\n :param path: string\n :returns: dict\n \"\"\"\n with open(path, \"r\") as jsonfile:\n return ujson.loads(jsonfile.read())\n\n\ndef write_json(path, data):\n with open(path, \"w\") as jsonfile:\n jsonfile.write(\n ujson.dumps(data, escape_forward_slashes=False, double_precision=5)\n )\n\n\ndef make_sure_path_exists(path):\n \"\"\"Make directories in path if they do not exist.\n\n Modified from http://stackoverflow.com/a/5032238/1377021\n\n :param path: string\n \"\"\"\n try:\n os.makedirs(path)\n except:\n pass\n\n\ndef get_path_parts(path):\n \"\"\"Splits a path into parent directories and file.\n\n :param path: string\n \"\"\"\n return path.split(os.sep)\n\n\ndef download(url):\n \"\"\"Downloads a file and returns a file pointer to a temporary file.\n\n :param url: string\n \"\"\"\n parsed_url = urlparse(url)\n\n urlfile = parsed_url.path.split(\"/\")[-1]\n _, extension = os.path.split(urlfile)\n\n fp = tempfile.NamedTemporaryFile(\"wb\", suffix=extension, delete=False)\n\n download_cache = os.getenv(\"DOWNLOAD_CACHE\")\n cache_path = None\n if download_cache is not None:\n cache_path = os.path.join(\n download_cache, hashlib.sha224(url.encode()).hexdigest()\n )\n if os.path.exists(cache_path):\n logging.info(\"Returning %s from local cache at %s\" % (url, cache_path))\n fp.close()\n shutil.copy(cache_path, fp.name)\n return fp\n\n s3_cache_bucket = os.getenv(\"S3_CACHE_BUCKET\")\n s3_cache_key = None\n if s3_cache_bucket is not None and s3_cache_bucket not in url:\n s3_cache_key = (\n os.getenv(\"S3_CACHE_PREFIX\", \"\") + hashlib.sha224(url.encode()).hexdigest()\n )\n s3 = boto3.client(\"s3\")\n try:\n s3.download_fileobj(s3_cache_bucket, s3_cache_key, fp)\n logging.info(\n \"Found %s in s3 cache at s3://%s/%s\"\n % (url, s3_cache_bucket, s3_cache_key)\n )\n fp.close()\n return fp\n except:\n pass\n\n if parsed_url.scheme == \"http\" or parsed_url.scheme == \"https\":\n res = requests.get(url, stream=True, verify=False)\n\n if not res.ok:\n raise IOError\n\n for chunk in res.iter_content(CHUNK_SIZE):\n fp.write(chunk)\n elif parsed_url.scheme == \"ftp\":\n download = urllib.request.urlopen(url)\n\n file_size_dl = 0\n block_sz = 8192\n while True:\n buffer = download.read(block_sz)\n if not buffer:\n break\n\n file_size_dl += len(buffer)\n fp.write(buffer)\n\n fp.close()\n\n if cache_path:\n if not os.path.exists(download_cache):\n os.makedirs(download_cache)\n shutil.copy(fp.name, cache_path)\n\n if s3_cache_key:\n logging.info(\n \"Putting %s to s3 cache at s3://%s/%s\"\n % (url, s3_cache_bucket, s3_cache_key)\n )\n s3.upload_file(fp.name, Bucket=s3_cache_bucket, Key=s3_cache_key)\n\n return fp\n\n\nclass ZipCompatibleTarFile(tarfile.TarFile):\n \"\"\"Wrapper around TarFile to make it more compatible with ZipFile\"\"\"\n\n def infolist(self):\n members = self.getmembers()\n for m in members:\n m.filename = m.name\n return members\n\n def namelist(self):\n return self.getnames()\n\n\nARCHIVE_FORMAT_ZIP = \"zip\"\nARCHIVE_FORMAT_TAR_GZ = \"tar.gz\"\nARCHIVE_FORMAT_TAR_BZ2 = \"tar.bz2\"\n\n\ndef get_compressed_file_wrapper(path):\n archive_format = None\n\n if path.endswith(\".zip\"):\n archive_format = ARCHIVE_FORMAT_ZIP\n elif path.endswith(\".tar.gz\") or path.endswith(\".tgz\"):\n archive_format = ARCHIVE_FORMAT_TAR_GZ\n elif path.endswith(\".tar.bz2\"):\n archive_format = ARCHIVE_FORMAT_TAR_BZ2\n else:\n try:\n with zipfile.ZipFile(path, \"r\") as f:\n archive_format = ARCHIVE_FORMAT_ZIP\n except:\n try:\n f = tarfile.TarFile.open(path, \"r\")\n f.close()\n archive_format = ARCHIVE_FORMAT_ZIP\n except:\n pass\n\n if archive_format is None:\n raise Exception(\"Unable to determine archive format\")\n\n if archive_format == ARCHIVE_FORMAT_ZIP:\n return zipfile.ZipFile(path, \"r\")\n elif archive_format == ARCHIVE_FORMAT_TAR_GZ:\n return ZipCompatibleTarFile.open(path, \"r:gz\")\n elif archive_format == ARCHIVE_FORMAT_TAR_BZ2:\n return ZipCompatibleTarFile.open(path, \"r:bz2\")\n","sub_path":"utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":5318,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"429954859","text":"\n'''\nCopyright (c)2008-2009 Serendio Software Private Limited\nAll Rights Reserved\n\nThis software is confidential and proprietary information of Serendio Software. It is disclosed pursuant to a non-disclosure agreement between the recipient and Serendio. This source code is provided for informational purposes only, and Serendio makes no warranties, either express or implied, in this. Information in this program, including URL and other Internet website references, is subject to change without notice. The entire risk of the use or the results of the use of this program remains with the user. Complying with all applicable copyright laws is the responsibility of the user. Without limiting the rights under copyright, no part of this program may be reproduced, stored in, or introduced into a retrieval system, or distributed or transmitted in any form or by any means (electronic, mechanical, photocopying, recording, on a website, or otherwise) or for any purpose, without the express written permission of Serendio Software.\n\nSerendio may have patents, patent applications, trademarks, copyrights, or other intellectual property rights covering subject matter in this program. Except as expressly provided in any written license agreement from Serendio, the furnishing of this program does not give you any license to these patents, trademarks, copyrights, or other intellectual property.\n'''\n\n## Decorators\nimport signal\n\n# http://wiki.python.org/moin/PythonDecoratorLibrary\ndef simple_decorator(decorator):\n \"\"\"This decorator can be used to turn simple functions\n into well-behaved decorators, so long as the decorators\n are fairly simple. If a decorator expects a function and\n returns a function (no descriptors), and if it doesn't\n modify function attributes or docstring, then it is\n eligible to use this. Simply apply @simple_decorator to\n your decorator and it will automatically preserve the\n docstring and function attributes of functions to which\n it is applied.\"\"\"\n def new_decorator(f):\n g = decorator(f)\n g.__name__ = f.__name__\n g.__doc__ = f.__doc__\n g.__dict__.update(f.__dict__)\n return g\n # Now a few lines needed to make simple_decorator itself\n # be a well-behaved decorator.\n new_decorator.__name__ = decorator.__name__\n new_decorator.__doc__ = decorator.__doc__\n new_decorator.__dict__.update(decorator.__dict__)\n return new_decorator\n\n# Decorate functions with args\n# http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/465427\ndecorator_with_args = lambda decorator: lambda *args, **kwargs: lambda func: decorator(func, *args, **kwargs)\n\n@decorator_with_args\ndef logit(fn, log, fname):\n '''Log a function on entry and exit.\n\n log - log object obtained from python logger module\n fname - a string denoting the function name which is called\n '''\n def _decorate(*args, **kwargs):\n #print 'in decorator'\n log.info(\"Entry into \" + fname)\n ret = fn(*args, **kwargs)\n log.info(\"Exit of \" + fname)\n return ret\n return _decorate\n","sub_path":"crawler/utils/decorators.py","file_name":"decorators.py","file_ext":"py","file_size_in_byte":3091,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"598948115","text":"from typing import Sequence, Any, Sequence, Callable, Dict, Iterable\nfrom collections import defaultdict\nimport babilim\nfrom babilim import PYTORCH_BACKEND, TF_BACKEND, info, warn, DEBUG_VERBOSITY\nfrom babilim.core.itensor import ITensor\nfrom babilim.core.tensor import Tensor, TensorWrapper\n\n\n_statefull_object_name_table = {}\n\n\nTRAINING = True\n\n\nclass StatefullObject(object):\n def __init__(self):\n self._wrapper = TensorWrapper()\n\n @property\n def training(self):\n return TRAINING\n\n @property\n def variables(self):\n return list(self.named_variables.values())\n\n @property\n def named_variables(self):\n return dict(self.__variables_with_namespace())\n\n def __variables_with_namespace(self, namespace=\"\"):\n all_vars = []\n extra_vars = []\n for member_name in self.__dict__:\n v = self.__dict__[member_name]\n if isinstance(v, str):\n pass\n elif isinstance(v, Dict):\n for i, (k, x) in enumerate(v.items()):\n if not isinstance(k, str):\n k = \"{}\".format(i)\n name = namespace + \"/\" + member_name + \"/\" + k\n if isinstance(x, StatefullObject):\n all_vars.extend(x.__variables_with_namespace(name))\n if isinstance(x, ITensor):\n all_vars.append((name, x))\n if self._wrapper.is_variable(x):\n all_vars.append((name, self._wrapper.wrap_variable(x, name=name)))\n if isinstance(x, object):\n extra_vars.extend(self._wrapper.vars_from_object(v, name))\n elif isinstance(v, Iterable):\n for i, x in enumerate(v):\n name = namespace + \"/\" + member_name + \"/{}\".format(i)\n if isinstance(x, StatefullObject):\n all_vars.extend(x.__variables_with_namespace(name))\n if isinstance(x, ITensor):\n all_vars.append((name, x))\n if self._wrapper.is_variable(x):\n all_vars.append((name, self._wrapper.wrap_variable(x, name=name)))\n if isinstance(x, object):\n extra_vars.extend(self._wrapper.vars_from_object(v, name))\n elif isinstance(v, StatefullObject):\n name = namespace + \"/\" + member_name\n all_vars.extend(v.__variables_with_namespace(name))\n elif isinstance(v, ITensor):\n name = namespace + \"/\" + member_name\n all_vars.append((name, v))\n elif self._wrapper.is_variable(v):\n name = namespace + \"/\" + member_name\n all_vars.append((name, self._wrapper.wrap_variable(v, name=name)))\n elif isinstance(v, object):\n name = namespace + \"/\" + member_name\n extra_vars.extend(self._wrapper.vars_from_object(v, name))\n for x in getattr(v, '__dict__', {}):\n name = namespace + \"/\" + member_name + \"/\" + x\n if isinstance(v.__dict__[x], StatefullObject):\n all_vars.extend(v.__dict__[x].__variables_with_namespace(name))\n if isinstance(v.__dict__[x], ITensor):\n all_vars.append((name, v.__dict__[x]))\n if self._wrapper.is_variable(v.__dict__[x]):\n extra_vars.append((name, self._wrapper.wrap_variable(v.__dict__[x], name=name)))\n if len(all_vars) == 0:\n all_vars.extend(extra_vars)\n return all_vars\n\n @property\n def trainable_variables(self):\n all_vars = self.variables\n train_vars = []\n for v in all_vars:\n if v.trainable:\n train_vars.append(v)\n return train_vars\n\n @property\n def named_trainable_variables(self):\n all_vars = self.named_variables\n train_vars = []\n for k, v in all_vars.items():\n if v.trainable:\n train_vars.append((k, v))\n return dict(train_vars)\n\n @property\n def untrainable_variables(self):\n all_vars = self.variables\n train_vars = []\n for v in all_vars:\n if not v.trainable:\n train_vars.append(v)\n return train_vars\n\n @property\n def named_untrainable_variables(self):\n all_vars = self.named_variables\n train_vars = []\n for k, v in all_vars.items():\n if not v.trainable:\n train_vars.append((k, v))\n return dict(train_vars)\n\n @property\n def trainable_variables_native(self):\n all_vars = self.trainable_variables\n train_vars = []\n for v in all_vars:\n train_vars.append(v.native)\n return train_vars\n\n def state_dict(self):\n state = {}\n for name, var in self.named_variables.items():\n if babilim.is_backend(babilim.TF_BACKEND):\n state[name] = var.numpy()\n else:\n state[name] = var.numpy().T\n return state\n\n def load_state_dict(self, state_dict):\n for name, var in self.named_variables.items():\n if name in state_dict:\n if babilim.is_backend(babilim.TF_BACKEND):\n var.assign(state_dict[name])\n else:\n var.assign(state_dict[name].T)\n if DEBUG_VERBOSITY:\n info(\" Loaded: {}\".format(name))\n else:\n warn(\" Variable {} not in checkpoint.\".format(name))\n","sub_path":"babilim/core/statefull_object.py","file_name":"statefull_object.py","file_ext":"py","file_size_in_byte":5651,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"126851816","text":"# import packages for the file usage\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport pathlib\nimport os.path\nimport numpy as np\nimport os\nfrom tqdm import tqdm\nimport time\nimport shutil\n\n'''\nThe purpose of the script is to generate charts for each metro area \nThe input file is Model Estimation/EstXX where XX is the Model Estimation version/trial\nThere are two output file\n 1. Excel file \n 2. Charts\nEntry point of the script is the main function\nReq: Use a template.xlsx saved in the Template folder\n'''\n\n\ndef check_nullvalues(df, col_name):\n # check for table records, wherever data is missing replace it with \"0\"\n df = df.copy()\n for col in col_name:\n df[col] = np.where(df[col] == '-', 0, df[col])\n df[col] = df[col].replace(np.nan, 0)\n try:\n df[col] = df[col]\n except ValueError:\n pass\n return df\n\n\ndef get_startyear(df):\n # get the first and last year for the current metro area\n Years = df[\"Year\"].unique()\n # start_year = pd.to_datetime((Years[0]).astype(str), format='%Y')\n start_year = str(Years[0])\n return start_year\n\n\ndef get_endyear(df):\n # get the first and last year for the current metro area\n Years = df[\"Year\"].unique()\n # end_year = pd.to_datetime((Years[-1]).astype(str), format='%Y')\n end_year = str(Years[-1])\n return end_year\n\n\ndef read_FACfile(file_name, file_path):\n # get the absolute path of the directory of the current script\n # Check file in Path = Factors and Ridership Data\\code\n current_dir = pathlib.Path(__file__).parent.absolute()\n # change the directory where the file_name is stored\n current_dir = current_dir.parents[0] / file_path\n try:\n if pathlib.Path(current_dir / file_name).exists():\n os.chdir(str(current_dir))\n df = pd.read_csv(file_name)\n df = df.copy().loc[np.where((df.CLUSTER_APTA4 != 10))]\n df = df.reindex()\n # get the unique metro names\n clusters = df['CLUSTER_APTA4'].unique()\n for cluster in clusters:\n df_cluster = df.copy().loc[df.CLUSTER_APTA4 == cluster,:]\n modes = df_cluster['RAIL_FLAG'].unique()\n for mode in modes:\n df_by_mode = df_cluster.copy().loc[df_cluster.RAIL_FLAG == mode,:]\n prepare_dataframe(df_by_mode, mode, cluster)\n except FileNotFoundError:\n print(\"File not found \" + str(current_dir))\n\n\ndef get_cluster_title(cluster_code):\n if cluster_code == float(1):\n cluster_title = 'High Op-Ex Group'\n elif cluster_code == float(2):\n cluster_title = 'Mid Op-Ex Group'\n elif cluster_code == float(3):\n cluster_title = 'Low Op-Ex Group'\n else:\n cluster_title = 'New York'\n return cluster_title\n\n\ndef prepare_dataframe(df, mode, cluster):\n col_name = get_filteredcolumns()\n df_cluster = df.copy().loc[:, col_name]\n\n # replace the null values with 0\n df_cluster = check_nullvalues(df_cluster, col_name)\n\n # Prepare the charts\n summary_cluster_area(df_cluster, col_name, mode, cluster)\n\n\ndef get_filteredcolumns():\n # col_name = [\"Year\", \"RAIL_FLAG\", 'UPT_ADJ',\n # # \"UPT_ADJ\", \"CLUSTER_APTA4\", 'Unknown_FAC',\n # 'VRM_ADJ_BUS_log_FAC', 'VRM_ADJ_RAIL_log_FAC',\n # 'FARE_per_UPT_cleaned_2018_BUS_log_FAC', 'FARE_per_UPT_cleaned_2018_RAIL_log_FAC',\n # 'POP_EMP_log_FAC', 'TSD_POP_EMP_PCT_FAC',\n # 'GAS_PRICE_2018_log_FAC', 'TOTAL_MED_INC_INDIV_2018_log_FAC', 'PCT_HH_NO_VEH_FAC',\n # 'JTW_HOME_PCT_FAC',\n # 'YEARS_SINCE_TNC_BUS_HINY_FAC', 'YEARS_SINCE_TNC_BUS_MIDLOW_FAC',\n # 'YEARS_SINCE_TNC_RAIL_HINY_FAC', 'YEARS_SINCE_TNC_RAIL_MID_FAC',\n # 'BIKE_SHARE_FAC', 'scooter_flag_FAC', 'Known_FAC',\n # 'MAINTENANCE_WMATA_FAC', 'RESTRUCTURE_FAC', 'New_Reporter_FAC']\n\n # returns only those columns whose charts need be created\n col_name = [\"Year\", \"RAIL_FLAG\", 'UPT_ADJ', 'Known_FAC', 'New_Reporter_FAC']\n return col_name\n\n\ndef get_modestring(mode):\n if mode == 0:\n modeName = \"Bus\"\n else:\n modeName = \"Rail\"\n return modeName\n\n\ndef get_pivot(df, base_year,sum_col_name):\n df = df.reset_index(drop=True).copy()\n col = \"Pivot_4m_\" + base_year\n df[col] = 0\n\n # get the index of the row corresponding to the base_year\n itr = df.index[df['Year'] == int(base_year)].to_list()\n # Set the value of the Pivot_base_year column at \"itr\" index-th row equal to UPT_Adj\n df.at[itr[0], col] = df[\"UPT_ADJ\"].iloc[itr[0]]\n\n start_year = get_startyear(df)\n\n end =(int(df.index[df['Year'] == int(start_year)].to_list()[0])) - 1\n\n for i in range(itr[0] - 1, (int(df.index[df['Year'] == int(start_year)].to_list()[0])) - 1,-1):\n df.at[i, col] = df[col].iloc[(i+1)] - df[\"Known_FAC\"].iloc[(i+1)] - df[\"New_Reporter_FAC\"].iloc[(i+1)]\n\n end_year = get_endyear(df)\n\n for i in range(itr[0] + 1, (int(df.index[df['Year'] == int(end_year)].to_list()[0])+1)):\n df.at[i, col] = df[col].iloc[i - 1] + df[\"Known_FAC\"].iloc[i] + df[\"New_Reporter_FAC\"].iloc[i]\n\n # sum_col_name.append(\"Total\")\n sum_col_name.append(col)\n\n # convert the readings into 100 millions\n for col in sum_col_name:\n if col not in [\"Year\", \"RAIL_FLAG\", \"CLUSTER_APTA4\"]:\n df[col] = df[col] / 100000000\n\n return df\n\n\ndef summary_cluster_area(df, sum_col_name, mode, cluster):\n # sum all the interested columns\n df[\"Total\"] = 0\n for col in sum_col_name:\n if col not in [\"Year\", \"RAIL_FLAG\", \"CLUSTER_APTA4\", \"UPT_ADJ\"]:\n df[\"Total\"] += df[col]\n\n sum_col_name.append(\"Total\")\n\n df = get_pivot(df, '2012', sum_col_name)\n\n df.rename(columns={'RAIL_FLAG': 'Mode'}, inplace=True)\n # Check file in Path = Factors and Ridership Data\\code\n current_dir = pathlib.Path(__file__).parent.absolute()\n # Change the directory - Script Outputs\\Est11_Outputs\\Metro_Area_CSVs\n get_dir_path = current_dir.parents[0] / 'Script Outputs' / 'Est11_Outputs' / 'Cluster_Area_Summary_CSVs'\n # Check if the above directory path exists or not, if not then create it\n pathlib.Path(get_dir_path).mkdir(parents=True, exist_ok=True)\n os.chdir(str(get_dir_path))\n # export the metro file as CSV\n strModeName = get_modestring(mode)\n df.to_csv(get_cluster_title(cluster) + \"-\" + \"Total - Modeled vs Observed\" + \"-\" + strModeName + \".csv\")\n chartcols = ['Pivot_4m_2012']\n subplot_labels = ['Modeled Ridership']\n fsize = (8.3, 5.8) # A5 page = 5.8 x 8.3 inch\n prepare_chart(df, chartcols, subplot_labels, strModeName, cluster, cols_per_fig=1, rows_per_fig=1,\n chartsavefoldername='Cluster_Area_Summary', fig_size=fsize)\n # print(\"Successfully created charts for \" + str(metro))\n time.sleep(0.2)\n\n\ndef prepare_chart(df, chartcols, subplot_labels, strModeName, cluster, cols_per_fig, rows_per_fig, chartsavefoldername,\n fig_size):\n modes = df['Mode'].unique()\n plt.style.use('seaborn-darkgrid')\n strMode = \"\"\n for mode in modes:\n df_fltr_mode = df[df.Mode == mode]\n col = 0\n row = 0\n transparency = 0.4\n num = 0\n # if df_fltr_mode.loc[0,'UPT_ADJ'] is not != 0:\n if fig_size < (16.53, 11.69):\n subplot_figsize = (17, 12)\n else:\n subplot_figsize = (22, 19)\n fig, ax = plt.subplots(nrows=rows_per_fig, ncols=cols_per_fig, figsize=subplot_figsize, sharex=True,\n sharey=True,\n constrained_layout=False, squeeze=False)\n fig.subplots_adjust(bottom=0.15, left=0.2)\n # fig, ax = plt.subplots(nrows=4, ncols=3, figsize=(22, 19), constrained_layout=False, squeeze=False)\n if mode == 0:\n strMode = \"Bus\"\n else:\n strMode = \"Rail\"\n\n # Check the first year and the last year\n start_year = df_fltr_mode['Year'].iloc[0]\n int_start_year = int(start_year)\n if int_start_year > 2006:\n base_year = 2006\n inumber = int_start_year - base_year\n for i in range(1, inumber + 1, 1):\n num = int_start_year - i\n new_row = pd.DataFrame({'Year': num, 'Mode': mode}, index=[0])\n df_fltr_mode = pd.concat([new_row, df_fltr_mode]).reset_index(drop=True)\n df_fltr_mode.loc[:, 'Year'] = pd.to_datetime(df_fltr_mode.loc[:, 'Year'].astype(str), format='%Y')\n df_fltr_mode = df_fltr_mode.set_index(pd.DatetimeIndex(df_fltr_mode['Year']).year)\n\n for chartcol, subplotlable in zip(chartcols, subplot_labels):\n # split the dataframe into two new dataframe. One where YR<=2012 and YR>=2012\n # This would ensure that we can generate between_fill function only for YR>=2012\n # mask = df_fltr_mode['Year'].dt.year >= int(2006)\n # df_aft_2006 = df_fltr_mode[mask]\n df_aft_2006 = df_fltr_mode.copy()\n\n strlabel = \"\"\n\n if \"Median Per Capita Income\" in subplotlable:\n strlabel = subplotlable[:33]\n elif \"Households with 0 Vehicles\" in subplotlable:\n strlabel = subplotlable[:31]\n elif \"Income & Household Characteristics\" in subplotlable:\n strlabel = subplotlable\n else:\n strlabel = subplotlable[:27]\n\n df_aft_2006.groupby('Mode').plot(x='Year', y='UPT_ADJ',\n label='Observed Ridership',\n ax=ax[row][col], legend=True,\n color='black',\n fontsize=12, linewidth=2.5)\n\n df_aft_2006.groupby('Mode').plot(x='Year', y='Pivot_4m_2012',\n label='Modeled Ridership',\n ax=ax[row][col], legend=True,\n color='blue',\n fontsize=12, linewidth=2.5)\n\n ax[row][col].set_xlabel(xlabel=\"Year\", fontsize=10)\n ax[row][col].tick_params(labelsize=9, pad=6)\n ax[row][col].set_ylabel(ylabel=\"Annual Ridership (100 millions)\", fontsize=10)\n ax[row][col].tick_params(labelsize=9, pad=6)\n ax[row][col].legend(loc=3, fontsize=9)\n ax[row][col].set_title(str(subplotlable), fontsize=12, loc='center', fontweight='bold')\n # y = 1.0, pad = -14,\n try:\n ax[row][col].grid(True)\n ax[row][col].margins(0.20)\n max_val = np.nanmax(df_aft_2006[['UPT_ADJ', chartcol]])\n ax[row][col].set_ylim([0, max_val * 1.25])\n except ValueError:\n pass\n if row >= (rows_per_fig - 1):\n row = 0\n col += 1\n else:\n row += 1\n # remove the X and Y labels of the innermost graphs\n for z in fig.get_axes():\n z.label_outer()\n\n fig.tight_layout(rect=[0.03, 0.03, 1, 0.95])\n\n current_dir = pathlib.Path(__file__).parent.absolute()\n # Change the directory to ..\\Script Outputs\n current_dir = current_dir.parents[0] / 'Script Outputs'\n os.chdir(str(current_dir))\n outputdirectory = \"Est11_Outputs/\" + chartsavefoldername\n p = pathlib.Path(outputdirectory)\n p.mkdir(parents=True, exist_ok=True)\n current_dir = current_dir.parents[0] / 'Script Outputs' / outputdirectory\n os.chdir(str(current_dir))\n # Axis title\n figlabel = \"\"\n fig.set_size_inches(fig_size)\n fig.text(0.02, 0.5, figlabel, ha='center', va='baseline', rotation='vertical',\n fontsize=16)\n # (cluster_chart) + \"-\" + strMode\n figname = (get_cluster_title(cluster) + \" - \" + \"Observed vs Modeled Ridership - \" + strModeName + \".png\")\n fig.suptitle((get_cluster_title(cluster) + \" - \" + \"Observed vs Modeled Ridership - \" + strModeName), fontsize=16, y=0.98,\n fontweight='bold', )\n make_space_above(ax, topmargin=1)\n # plt.suptitle((str(file_name) + \" - \" + strMode), fontsize=15)\n fig.savefig(figname)\n plt.close(fig)\n # print(\"Successfully created\")\n\n\ndef make_space_above(axes, topmargin=1):\n \"\"\" increase figure size to make topmargin (in inches) space for\n titles, without changing the axes sizes\"\"\"\n fig = axes.flatten()[0].figure\n s = fig.subplotpars\n w, h = fig.get_size_inches()\n\n figh = h - (1 - s.top) * h + topmargin\n fig.subplots_adjust(bottom=s.bottom * h / figh, top=1 - topmargin / figh)\n fig.set_figheight(figh)\n\n\ndef main():\n file_path = 'Model Estimation/Est11'\n file_name = 'FAC_APTA4_CLUSTERS_11-19.csv'\n read_FACfile(file_name, file_path)\n print(\"completed\")\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"Factors and Ridership Data/code/ModeledvsObserved - Cluster.py","file_name":"ModeledvsObserved - Cluster.py","file_ext":"py","file_size_in_byte":12932,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"77503538","text":"\"\"\"Tests for the `skewt` module.\"\"\"\n\nimport matplotlib\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport numpy.testing\nimport datetime as dt\nimport pytest\n\nfrom cartopy import crs as ccrs\nimport tropycal.tracks as tracks\n\ndef assert_almost_equal(actual, desired, decimal=7):\n \"\"\"Check that values are almost equal, including units.\n Wrapper around :func:`numpy.testing.assert_almost_equal`\n \"\"\"\n actual, desired = check_and_drop_units(actual, desired)\n numpy.testing.assert_almost_equal(actual, desired, decimal)\n\n\ndef assert_array_almost_equal(actual, desired, decimal=7):\n \"\"\"Check that arrays are almost equal, including units.\n Wrapper around :func:`numpy.testing.assert_array_almost_equal`\n \"\"\"\n actual, desired = check_and_drop_units(actual, desired)\n numpy.testing.assert_array_almost_equal(actual, desired, decimal)\n\n\ndef assert_array_equal(actual, desired):\n numpy.testing.assert_array_equal(actual, desired)\n\n#@pytest.mark.mpl_image_compare(tolerance=.03, remove_text=False, style='default')\ndef test_code():\n\n @pytest.mark.mpl_image_compare(tolerance=.03, remove_text=False, style='default')\n def test_plot(methodToRun, proj, use_ax, positional_arguments, keyword_arguments, use_figsize=(14,9), use_dpi=200, ax_in_dict=False):\n \n if use_ax == True:\n fig = plt.figure(figsize=use_figsize,dpi=use_dpi)\n ax = plt.axes(projection=proj)\n ax = methodToRun(*positional_arguments, ax=ax, **keyword_arguments)\n else:\n fig = plt.figure(figsize=use_figsize,dpi=use_dpi)\n ax = methodToRun(*positional_arguments, **keyword_arguments)\n \n if ax_in_dict == True:\n ax = ax['ax']\n \n return fig\n\n #method2(storm.plot, ['spam'], {'ham': 'ham'})\n \n #Retrieve HURDAT2 reanalysis dataset for North Atlantic\n hurdat_atl = tracks.TrackDataset()\n\n \n #Assign all tornadoes to storm\n hurdat_atl.assign_storm_tornadoes()\n \n #------------------------------------------------------------\n \n #Search name\n hurdat_atl.search_name('michael')\n \n #Test getting storm ID\n storm_id = hurdat_atl.get_storm_id(('michael', 2018))\n if storm_id != 'AL142018':\n raise AssertionError(\"Incorrect type\")\n \n #Test retrieving hurricane Michael (2018)\n storm = hurdat_atl.get_storm(('michael', 2018))\n \n #Cartopy proj\n proj = ccrs.PlateCarree(central_longitude=0.0)\n \n #Make plot of storm track\n test_plot(storm.plot, proj, True, [], {'return_ax': True}, use_figsize=(14,9))\n \n #Get NHC discussion\n disco = storm.get_nhc_discussion(forecast=1)\n \n #Plot NHC forecast\n test_plot(storm.plot_nhc_forecast, proj, True, [], {'forecast': 1, 'return_ax': True}, use_figsize=(14,9))\n #ax = storm.plot_nhc_forecast(forecast=1,return_ax=True)\n \n #Plot storm tornadoes\n #test_plot(storm.plot_tors, proj, [], {'return_ax': True})\n #ax = storm.plot_tors(return_ax=True)\n \n #Plot rotated tornadoes\n test_plot(storm.plot_TCtors_rotated, proj, False, [], {'return_ax': True}, use_figsize=(9,9), use_dpi=150)\n #ax = storm.plot_TCtors_rotated(return_ax=True)\n \n #Convert to datatypes\n storm.to_dict()\n storm.to_xarray()\n storm.to_dataframe()\n \n #------------------------------------------------------------\n \n #Test retrieving season\n ax = season = hurdat_atl.get_season(2017)\n \n #Make plot of season\n test_plot(season.plot, proj, True, [], {'return_ax': True}, use_figsize=(14,9))\n #ax = season.plot(return_ax=True)\n \n #Annual summary\n season.summary()\n \n #Dataframe\n season.to_dataframe()\n \n #------------------------------------------------------------\n \n #Rank storms\n hurdat_atl.rank_storm('ace')\n \n #Gridded stats\n test_plot(hurdat_atl.gridded_stats, proj, True, ['maximum wind'], {}, use_figsize=(14,9))\n #hurdat_atl.gridded_stats('maximum wind',return_ax=True)\n ","sub_path":"tests/tracks.py","file_name":"tracks.py","file_ext":"py","file_size_in_byte":3995,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"415938042","text":"from selenium import webdriver\n\nimport csv\nname=[]\n#opening the list of csv file and appending to name \nwith open('Friends_hai.csv') as csvfile:\n readCSV=csv.reader(csvfile,delimiter=',')\n print(readCSV)\n for row in readCSV:\n name.append(row[0])\n\n#add the path to chromedriver \ndriver = webdriver.Chrome('chromedriver.exe')#here\ndriver.get('https://web.whatsapp.com/')\n\n#input the grp name here\nstring = input('enter anything after scannig qr code')\ninput(\"enter anything\")\nuser = driver.find_element_by_xpath('//span[@title = \"{}\"]'.format(string))\nuser.click()\n\n#plz check find_element_by_xpath it changes most of the time\nmsg_box = driver.find_element_by_xpath('//*[@id=\"main\"]/footer/div[1]/div[2]/div/div[2]')\n\nj=0\nfor i in name:\n #here we say thank you and the name of ur friend\n msg_box.send_keys(\"thank you\",name[j])\n #this class name is the send button\n button = driver.find_element_by_class_name('_35EW6')\n button.click()\n j+=1\n","sub_path":"birthday_thanks.py","file_name":"birthday_thanks.py","file_ext":"py","file_size_in_byte":972,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"83632754","text":"from functools import singledispatch\nfrom pathlib import Path\n\nfrom typed_ast import ast3\n\nfrom paradigm.hints import Namespace\nfrom . import (construction,\n conversion)\n\n\n@singledispatch\ndef execute(node: ast3.AST,\n *,\n source_path: Path,\n namespace: Namespace) -> None:\n raise TypeError('Unsupported node type: {type}.'\n .format(type=type(node)))\n\n\n@execute.register(ast3.stmt)\ndef execute_statement(node: ast3.stmt,\n *,\n source_path: Path,\n namespace: Namespace) -> None:\n execute_tree(construction.from_node(node),\n source_path=source_path,\n namespace=namespace)\n\n\n@execute.register(ast3.Module)\ndef execute_tree(node: ast3.Module,\n *,\n source_path: Path,\n namespace: Namespace) -> None:\n code = compile(conversion.typed_to_plain(node), str(source_path), 'exec')\n exec(code, namespace)\n","sub_path":"paradigm/arboretum/execution.py","file_name":"execution.py","file_ext":"py","file_size_in_byte":1011,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"612325494","text":"# Assignment_1_JacqulynMacHardy.py\r\n# 01/10/17\r\n# Jacqulyn MacHardy Anderson\r\n# all requirements met for 100%\r\n\r\n# ****** Code for 50% *******\r\n\r\n# 1.1 Write a function to swap two numbers in a list\r\n\r\n# temporarily stores value 1, then overwrites value 1 with value 2, and overwrites value 2 using the \"stored\" value 1\r\ndef swapVals(theList, value1, value2):\r\n temp = theList[value1]\r\n theList[value1] = theList[value2]\r\n theList[value2] = temp\r\n return theList\r\n\r\nmyList = [36, 6, 25, 16, 2, 98]\r\nswapVals(myList, 0, 5)\r\nassert (myList == [98, 6, 25, 16, 2, 36])\r\n\r\n# 1.2 Write a function to find the smallest number in a list\r\n\r\n# assumes the given index is the smallest, and then checks to see if the current index is smaller, overwriting mini\r\n# if the current index is smaller\r\n# tracks an index counter, updating the mini_index counter when a new \"mini\" is found, returns the mini_index\r\ndef findMin(theList, index):\r\n mini = theList[index]\r\n mini_index = index\r\n i_counter = index\r\n for i in theList[index:]:\r\n if (i < mini):\r\n mini = i\r\n mini_index = i_counter\r\n i_counter +=1\r\n return mini_index\r\n\r\nmyMini = findMin(myList, 0)\r\nassert (myMini == 4)\r\n\r\n# 1.3 Write a function to sum all the values in a list\r\n\r\n# sets up \"total\" as an accumulator variable, iterates on each index in the List, adding the current index to the total\r\ndef sumList(theList):\r\n total = 0\r\n for i in theList:\r\n total += i\r\n return total\r\n\r\nmyTotal = sumList(myList)\r\nassert (myTotal == 183)\r\n\r\n# ******* Code for 60% *********\r\n\r\n# 2.1 Write a selection sort\r\n\r\n# uses findMin to find the index of the smallest number in the list\r\n# swaps the value at current index with the value at miniIndex\r\n# iterates on each index in the list, finding the minimum from the remaining indices\r\ndef selSort(theList):\r\n for i in range(len(theList)):\r\n miniIndex = findMin(theList, i)\r\n theList = swapVals(theList, i, miniIndex)\r\n return theList\r\n\r\ntestList = selSort(myList)\r\nassert (testList == [2, 6, 16, 25, 36, 98])\r\n\r\n# 2.2 Write an insertion sort\r\n\r\n# iterates on each index, comparing the value at the current index (i) with the value of the next index down (i-1)\r\n# swaps the value of the current index with its left neighbor if the left neighbor's value is larger,\r\n# and compares the current value and left neighbor value again, repeating until finding that the left neighbor's value\r\n# is smaller than the value at the current index\r\ndef insSort(theList):\r\n for i in range(1, len(theList)):\r\n while theList[i] < theList[i-1]:\r\n theList = swapVals(theList, i, i-1)\r\n if i > 1:\r\n i -= 1\r\n return theList\r\n\r\nmyInsList = [7, 44, 96, 1, -2, 2]\r\nmyInsSort = insSort(myInsList)\r\nassert (myInsSort == [-2, 1, 2, 7, 44, 96])\r\n\r\n# ********* Code for 80% ***********\r\n\r\n# 3.1 Write test code that proves both of your sorting algorithms work correctly. Printing does not count. Use asserts()\r\n\r\n# asserts that the value at the current index is less than or equal to the value of the\r\n# next index, ensuring the list is sorted\r\ndef ListIsSorted(theList):\r\n for i in theList:\r\n assert([i]<=[i+1])\r\n\r\n# list of test lists:\r\nmyList = [36, 6, 25, 16, 2, 98]\r\nmyInsList = [7, 44, 96, 1, -2, 2]\r\nemptyList = []\r\nduplicateList = [2, 2, 2, 2, 4, 1]\r\nalreadySorted = [1, 2, 3, 4, 5, 77]\r\nbackwards = [88, 77, 66, 5, 4, 3, 2, 1]\r\n\r\n# sort each test case with selSort, then test with ListIsSorted\r\nListIsSorted(selSort(myList))\r\nListIsSorted(selSort(myInsList))\r\nListIsSorted(selSort(emptyList))\r\nListIsSorted(selSort(duplicateList))\r\nListIsSorted(selSort(alreadySorted))\r\nListIsSorted(selSort(backwards))\r\n\r\n# reset test lists:\r\nmyList = [36, 6, 25, 16, 2, 98]\r\nmyInsList = [7, 44, 96, 1, -2, 2]\r\nemptyList = []\r\nduplicateList = [2, 2, 2, 2, 4, 1]\r\nalreadySorted = [1, 2, 3, 4, 5, 77]\r\nbackwards = [88, 77, 66, 5, 4, 3, 2, 1]\r\n\r\n# sort each test case with insSort, then test with ListIsSorted\r\nListIsSorted(insSort(myList))\r\nListIsSorted(insSort(myInsList))\r\nListIsSorted(insSort(emptyList))\r\nListIsSorted(insSort(duplicateList))\r\nListIsSorted(insSort(alreadySorted))\r\nListIsSorted(insSort(backwards))\r\n\r\n# 3.2 What are the invariants of both of your sorts?\r\n\r\n# For the Selection Sort and the Insertion Sort, the current index defines the beginning of the unsorted numbers.\r\n# Therefore, it's always true that all elements in theList which precede the current index are sorted.\r\n# That is the invariant for these two sorts.\r\n\r\n\r\n# ********* Code for 90% ************\r\n\r\n# 4.1 Write a function that displays an integer value in its binary form.\r\n\r\n# uses \"&\" to test whether the current index (or binary place value) of the given number is a 1 or a 0\r\n# returns True if the & comparison returns a value that matches the mask (this means the tested place value holds a 1)\r\n# returns False in all other cases (means that the test place value holds a 0)\r\ndef GetBitState(i_number, i_index):\r\n mask = 1\r\n mask <<= i_index\r\n temp = i_number & mask\r\n if temp == mask:\r\n return True\r\n else:\r\n return False\r\n\r\ntest = GetBitState(5, 1)\r\nassert (test == False)\r\n\r\n# uses GetBitState to assess each place value of the given number, to a range of 8 places\r\n# accumulates the results of each assessment in a temporary string\r\n# returns the accumulation as a string\r\ndef DisplayBinary(i_number):\r\n temp = \"\"\r\n for i in range(8):\r\n if GetBitState(i_number, i) == True:\r\n temp = \"1\" + temp\r\n else:\r\n temp = \"0\" + temp\r\n return temp\r\n\r\ntestAgain = DisplayBinary(5)\r\nassert(testAgain == \"00000101\")\r\n\r\n# ********* Code for 100% **********\r\n\r\n# 5.1 Write a function that adds two numbers in their binary form without using +.\r\n\r\n# sets up a carry by checking for the place values where num1 and num2 both have a 1, then bit shifts the carry left one\r\n# to account for the increase in place value that comes from combining two 1's\r\n# sets up a temp value by checking for the place values where num1 or num2 (but not both) have a 1\r\n# checks to see if the temp or the carry could be the final result, if not, the function repeats recursively,\r\n# combining temp and carry until only one remains\r\ndef AddBins_NextLevel(num1, num2):\r\n carry = num1 & num2\r\n carry <<= 1\r\n temp = num1 ^ num2\r\n if temp == 0:\r\n return carry\r\n elif carry == 0:\r\n return temp\r\n else:\r\n return AddBins_NextLevel(temp, carry)\r\n\r\nc = 128\r\nd = 100\r\ntestMore = AddBins_NextLevel(c, d)\r\nassert (AddBins_NextLevel(c, d) == c + d)\r\n\r\n# 5.2 Write a function that multiplies two binary numbers without using * (the actual multiply operator).\r\n\r\n# uses GetBitState to check for a 1 or 0 in the current place value of the multiplier, when this returns \"True\",\r\n# the multiplicand is bit shifted by the place value (i) and stored as temp1\r\n# uses AddBins_NextLevel to accumulate the temp1 values and returns the product\r\ndef MultBins(num1, num2):\r\n temp2 = 0\r\n for i in range(8):\r\n temp1 = num1\r\n if GetBitState(num2, i) == True:\r\n temp1 <<= i\r\n temp2 = AddBins_NextLevel(temp1, temp2)\r\n return temp2\r\n\r\na = 16\r\nb = 15\r\ntestLots = MultBins(a, b)\r\nassert (testLots == a * b)\r\n\r\n# 5.3 Interview question: How many bits are necessary to store a positive value X?\r\n\r\n# The number of bits needed to store a positive value X is the same as the number of place values in base 2 needed\r\n# to represent that number. For example, a decimal 5 converts to a binary 101, meaning it requires 3 bits of storage.\r\n\r\n# For larger numbers, we need a better method than converting the number and counting the place values. We could check\r\n# for the nearest \"whole\" binary numbers that surround our value. For example 244 lies between 256 and 128, which are\r\n# represented by a \"1\" in place values 9 and 8, respectively.\r\n#\r\n# From this, we know that 244 takes fewer than 9 bits\r\n# of storage (because it is smaller than 256), but it takes at least 8 bits of storage because it is greater than 128.\r\n\r\n# Ultimately, these place values are representative of base 2. So, we can represent the problem mathematically using\r\n# logarithms like so:\r\n\r\n# bits = log(sub2)(number)\r\n\r\n# This equation may yield a number of bits that isn't a whole number, which is problematic. In this case, we must round\r\n# round up the number of bits to the nearest whole number. Additionally, perfect powers of 2 (such as 4, 16, 32, etc.)\r\n# even though they yield a whole number, we must add 1 because we begin with 2^0 as our first place value (i.e.\r\n# 2^0 is 1 bit, 2^1 uses 2 bits. . . 2^6 uses 7 bits etc.)\r\n","sub_path":"Assignment1_JacqulynMacHardy.py","file_name":"Assignment1_JacqulynMacHardy.py","file_ext":"py","file_size_in_byte":8686,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"33607343","text":"#TME\n#Exercice 1\ndef racine_carree(a,x0,epsilon):\n '''Number*Number*float -> float\n hypothese : epsilon > 0 et x0 > 0\n retourne l'approximation en stoppant la methode lorsque abs(a-x**2) <= epsilon'''\n #res: float\n res = 0\n #x:int\n x = x0\n #temp:float\n temp = 0\n while abs(a-x*x) > epsilon:\n temp = x\n x = (temp+ a/temp)/2\n return x\n#jeu de test\nassert racine_carree(20,4.5,0.0001) <= 4.4722\nassert racine_carree(42,6,0.001) <= 6.481\n\n\n#Exercice 2\n#Question 2.1:\ndef nb_consonnes(s):\n '''str -> int\n hypothèse : uniquement des lettres non accentuées\n renvoie le nombre de consonnes dans s'''\n #consonnes:str\n consonnes = 'aAeEiIoOuUyY'\n #res :int\n res = 0\n for c in s:\n for c2 in consonnes:\n if c == c2:\n res = res + 1\n return len(s)-res\n#jeu de test\nassert nb_consonnes('goelette') == 4\nassert nb_consonnes('sentiers') == 5\n\n#Question 2.2:\ndef liste_annotee(L):\n '''liste[str] -> liste[alpha]\n renvoie la liste des couples (chaine,nb_consonnes dans chaine)'''\n #res:liste[alpha]\n res = []\n #consonnes:int\n consonnes = 0\n #temp:alpha\n temp = ()\n #c:str\n for c in L:\n consonnes = nb_consonnes(c)\n temp = (c,consonnes)\n res.append(temp)\n return res\n#jeu de test\nassert liste_annotee(['lagon','goelette']) == [('lagon',3),('goelette',4)]\n\n\n#Question 2.3\ndef max_liste_annotee(L):\n '''liste_annotee -> liste[str]\n hypothese : liste_annotee non vide\n renvoie la liste de chaine de caractère qui on le plus de consonnes'''\n #res : list[str]\n res = []\n #valeur: int\n valeur = 0\n for chaine,consonne in L:\n if consonne > valeur:\n valeur = consonne\n for chaine,consonne in L:\n if consonne == valeur:\n res.append(chaine)\n return res\n\nassert max_liste_annotee([('lagon',3),('goelette',4)]) == ['goelette']\n\n#Exercice 3:\ndef begaiement(k,L):\n '''int*liste[str] -> str'\n hypothese : k != 0 L non vide'''\n res = ''\n for i in L:\n res = k*i\n return res\n\n\n\n\n\n\n\n","sub_path":"1I001 PYTHON/TME.py","file_name":"TME.py","file_ext":"py","file_size_in_byte":2092,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"58630652","text":"#print(\"hellow world\")\nmessage = 'Call me at 415-555-1011 tomorrow. 415-555-9999 is my office.'\nnumber = \"415-555-4242\"\nnumber1 = \"415-555-4242\"\ndef Fun_phonenum(num):\n #print(\"num \",num)\n\n if(len(num) != 12):\n return False\n for i in range (0,3):\n if not num[i].isdecimal():\n return False\n if num[3] != '-':\n return False\n for i in range(4,7):\n if not num[i].isdecimal():\n return False\n if num[7] != '-':\n return False\n for i in range(8, 12):\n if not num[i].isdecimal():\n return False\n\n return True\n\nfor i in range(len(message)):\n chunk = message[i:i+12]\n #print(i,chunk)\n if Fun_phonenum(chunk):\n print('Phone number found: ' + chunk)\n print('Done')\n'''\n#temp = Fun_phonenum(number)\n#print(temp)\n\nprint('415-555-4242 is a phone number:')\nprint(Fun_phonenum('415-555-4242'))\nprint('Moshi moshi is a phone number:')\nprint(Fun_phonenum('Moshi moshi'))\n'''","sub_path":"Assain/Regular_Expressions/sample.py","file_name":"sample.py","file_ext":"py","file_size_in_byte":980,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"113910230","text":"import json \nfrom review import Review\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.feature_extraction.text import CountVectorizer \nimport matplotlib.pyplot as plt \nimport numpy as np\n\n\nfile_name = './data/sentiment/Books_small.json'\n\nreviews = []\nwith open(file_name) as f:\n for line in f:\n review = json.loads(line)\n\n reviews.append(Review(review['reviewText'], review['overall']))\n\n# print(reviews[5].text)\n\n# Preg Data\ntraining, test = train_test_split(reviews, test_size=0.33, random_state=42)\n\ntrain_x = [x.text for x in training]\ntrain_y = [x.sentiment for x in training]\n\ntest_x = [x.text for x in test]\ntest_y = [x.sentiment for x in test]\n\n# Bag of words vectorization\n\nvectorizer = CountVectorizer()\ntrain_x_vectors = vectorizer.fit_transform(train_x)\n# vectorizer.fit(train_x)\ntest_x_vectors = vectorizer.transform(test_x)\n\n# print(test_x[0])\n# print(train_x_vectors[0].toarray())\n\n# print(test_x_vector[0].toarray())\n\n#Linear \nfrom sklearn import svm\nclf_svm = svm.SVC(kernel='linear')\n\nclf_svm.fit(train_x_vectors, train_y)\n\npredict_result = clf_svm.predict(test_x_vectors[0])\n\nprint (predict_result)\n\n#############\n# Fixing random state for reproducibility\nnp.random.seed(19680801)\n\nN = 10000\nx = np.random.rand(N)\ny = np.random.rand(N)\ncolors = np.random.rand(N)\narea = (30 * np.random.rand(N))**2 # 0 to 15 point radii\nplt.scatter(x, y, s=area, c=colors, alpha=0.5)\n\n############\n # figure = plt.figure(figsize=(27,9))\n# plt.show()\n\n### Logistic Regression \nfrom sklearn.linear_model import LogisticRegression\nclf_log = LogisticRegression()\n\nclf_log.fit(train_x_vectors, train_y)\n\npredict_result = clf_log.predict(test_x_vectors[0])\nprint(predict_result)\n\n### Decision Tree\nfrom sklearn.tree import DecisionTreeClassifier\nclf_dec = DecisionTreeClassifier()\n\nclf_dec.fit(train_x_vectors, train_y)\n\npredict_result = clf_dec.predict(test_x_vectors[0])\n# print(predict_result)\n\n### Naive Bayes\n# from sklearn.naive_bayes import GaussianNB\n # clf_gnb = GaussianNB()\n\n# clf_gnb.fit(train_x_vectors, train_y)\n\n# predict_result2 = clf_gnb.predict(test_x_vectors[0])\n# print(predict_result2)\n\nsvmScore = clf_svm.score(test_x_vectors, test_y)\n\n# print (svmScore)","sub_path":"example/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":2208,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"177849715","text":"import torch\nimport copy\nimport pickle\nfrom torch.utils.data import Dataset\nfrom torch.autograd import Variable\nfrom tqdm import tqdm\nimport numpy as np\n\nuse_cuda = torch.cuda.is_available()\n\n\ndef custom_collate_fn(batch):\n # input is a list of dialogturn objects\n bt_siz = len(batch)\n # sequence length only affects the memory requirement, otherwise longer is better\n pad_idx, max_seq_len = 52700, 60\n \n \n\n maxturnsnumber = 0\n minturn = 100\n turnsnumbers = []\n for i, (d, cl_u) in enumerate(batch):\n turnsnumber = len(cl_u)\n if turnsnumber >= maxturnsnumber:\n maxturnsnumber = turnsnumber\n if turnsnumber <= minturn:\n minturn = turnsnumber\n u_batch = []\n u_lens = []\n l_u = []\n max_clu = 0\n for j in range (0, maxturnsnumber):\n u_lensj = np.zeros(bt_siz, dtype = int)\n u_lens.append(u_lensj)\n l_u.append(0)\n u_batchj = []\n for i in range(0, bt_siz):\n u_batchj.append(torch.LongTensor([52700]))\n u_batch.append(u_batchj)\n for i, (d, cl_u)in enumerate(batch):\n turnsnumbers.append(len(cl_u))\n for j,(cl_uj) in enumerate(cl_u):\n cl_u[j] = min(cl_uj, max_seq_len)\n if cl_u[j] > l_u[j]:\n l_u[j] = cl_u[j]\n if cl_u[j] > max_clu: \n max_clu = cl_u[j]\n \n u_batch[j][i] = torch.LongTensor(d.u[j])\n u_lens[j][i] = cl_u[j]\n t = u_batch.copy()\n for j in range(0, maxturnsnumber):\n u_batch[j] = Variable(torch.ones( bt_siz, max_clu).long() * pad_idx)\n end_tok = torch.LongTensor([2])\n for i in range(bt_siz):\n for j in range (0, maxturnsnumber):\n seq, cur_l = t[j][i], t[j][i].size(0)\n \n if cur_l <= max_clu:\n u_batch[j][i, :cur_l].data.copy_(seq[:cur_l])\n else:\n u_batch[j][i, :].data.copy_(torch.cat((seq[:l_u[j]-1],end_tok),0)) \n sort4utterlength = []\n #for j in range(0, maxturnsnumber):\n # sort4utterlength.append(np.argsort(u_lens[j]*-1))\n # u_batch[j] = u_batch[j][sort4utterlength[j], :]\n # u_batch[j] = np.array(u_batch[j])\n # u_lens[j] = u_lens[j][sort4utterlength[j]\n #print(u_batch)\n #u_batch = np.array(u_batch)\n #sort4utternumber = np.argsort(turnsnumber*-1)\n #u_batch = u_batch[sort4utternumber,:\n return u_batch, u_lens, turnsnumbers, max_clu, minturn\n\nclass DialogTurn:\n def __init__(self, item):\n self.u = []\n cur_list = []\n max_word = 0\n for d in item:\n cur_list.append(d)\n if d == 1:\n self.u.append(copy.copy(cur_list))\n cur_list = []\n if d > max_word:\n max_word = d\n def __len__(self):\n length = 0\n for utter in self.u:\n length += len(utter)\n return length\n\n def __repr__(self):\n strin = \"\"\n for utter in self.u:\n strin += str(utter)\n return strin\n\n\nclass MovieTriples(Dataset):\n def __init__(self, data_type, length=None):\n if data_type == 'train':\n _file = 'train_sorted.dialogues.pkl'\n elif data_type == 'valid':\n _file = 'valid_sorted.dialogues.pkl'\n elif data_type == 'test':\n _file = 'test_sorted.dialogues.pkl'\n self.utterance_data = []\n\n with open(_file, 'rb') as fp:\n data = pickle.load(fp)\n for d in data:\n self.utterance_data.append(DialogTurn(d))\n # it helps in optimization that the batch be diverse, definitely helps!\n # self.utterance_data.sort(key=cmp_to_key(cmp_dialog))\n if length:\n self.utterance_data = self.utterance_data[2000:2000 + length]\n\n def __len__(self):\n return len(self.utterance_data)\n\n def __getitem__(self, idx):\n dialog = self.utterance_data[idx]\n length = []\n for utter in dialog.u:\n length.append(len(utter))\n return dialog, length\n\n\ndef tensor_to_sent(x, inv_dict, greedy=False):\n sents = []\n inv_dict[52700] = ''\n for li in x:\n if not greedy:\n scr = li[1]\n seq = li[0]\n else:\n scr = 0\n seq = li\n sent = []\n seq = seq[1:]\n for i in seq:\n i = i.item()\n sent.append(inv_dict[i])\n if i == 1:\n break\n sents.append((\" \".join(sent), scr))\n return sents\n","sub_path":"util.py","file_name":"util.py","file_ext":"py","file_size_in_byte":4512,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"653621523","text":"# Standard libs\r\nimport os\r\nimport json\r\nimport copy\r\nimport base64\r\nimport shutil\r\nimport string\r\nimport logging\r\nimport argparse\r\n\r\n# Third party libs\r\nimport boto3\r\nfrom tqdm import tqdm\r\nfrom easydict import EasyDict as edict\r\n\r\n\r\nclass Database:\r\n def __init__(self, config_path=None, **kwargs):\r\n self.conf = self.read_conf(config_path)\r\n self.conf = self.override_defaults(self.conf, **kwargs)\r\n self.session = boto3.Session(profile_name=self.conf.PROFILE)\r\n self.s3 = self.session.client(self.conf.SESSION_CLIENT)\r\n self.safe_s3_chars = set(string.ascii_letters + string.digits + \".-_\")\r\n\r\n @staticmethod\r\n def read_conf(config_path):\r\n with open(config_path, 'r', encoding='utf-8') as f:\r\n return edict(json.load(f))\r\n\r\n @staticmethod\r\n def override_defaults(conf, **kwargs):\r\n conf = copy.deepcopy(conf)\r\n for key, value in kwargs.items():\r\n _key = key.upper().replace('-', '_')\r\n if _key in conf:\r\n conf[_key] = value\r\n return conf\r\n\r\n def get_submissions(self, project, rerun, email=None):\r\n prefix = self.conf.PREFIX + project + '/'\r\n if email:\r\n if '@' not in email:\r\n email += '@wisc.edu'\r\n prefix += self.to_s3_key_str(email) + '/'\r\n submitted = set()\r\n tested = set()\r\n for path in self.s3_all_keys(prefix):\r\n parts = path.split('/')\r\n if parts[-1] == 'submission.json':\r\n submitted.add(path)\r\n elif parts[-1] == 'test.json':\r\n parts[-1] = 'submission.json'\r\n tested.add('/'.join(parts))\r\n if not rerun:\r\n submitted -= tested\r\n return submitted\r\n\r\n def fetch_submission(self, s3path, file_name=None):\r\n local_dir = os.path.join(self.conf.S3_DIR, os.path.dirname(s3path))\r\n if os.path.exists(local_dir):\r\n shutil.rmtree(local_dir)\r\n os.makedirs(local_dir)\r\n response = self.s3.get_object(Bucket=self.conf.BUCKET, Key=s3path)\r\n submission = json.loads(response['Body'].read().decode('utf-8'))\r\n file_contents = base64.b64decode(submission.pop('payload'))\r\n file_name = file_name if file_name else submission['filename']\r\n with open(os.path.join(local_dir, file_name), 'wb') as f:\r\n f.write(file_contents)\r\n return local_dir, file_name\r\n\r\n def fetch_results(self, s3path):\r\n s3path = s3path.replace('submission.json', 'test.json')\r\n response = self.s3.get_object(Bucket=self.conf.BUCKET, Key=s3path)\r\n try:\r\n submission = json.loads(response['Body'].read().decode('utf-8'))\r\n logging.debug(f'Previous submission found for {s3path}')\r\n return submission['score']\r\n except self.s3.exceptions.NoSuchKey:\r\n logging.debug(f'No previous submission found for {s3path}')\r\n return 0\r\n\r\n def put_submission(self, key, submission):\r\n if type(submission) is not str:\r\n submission = json.dumps(submission, indent=2)\r\n self.s3.put_object(Bucket=self.conf.BUCKET, Key=key,\r\n Body=submission.encode('utf-8'),\r\n ContentType='text/plain')\r\n\r\n def s3_all_keys(self, prefix):\r\n paginator = self.s3.get_paginator('list_objects')\r\n operation_parameters = {'Bucket': self.conf.BUCKET,\r\n 'Prefix': prefix}\r\n page_iterator = paginator.paginate(**operation_parameters)\r\n for page in page_iterator:\r\n logging.info('...list_objects...')\r\n yield from [item['Key'] for item in page['Contents']]\r\n\r\n def to_s3_key_str(self, s):\r\n s3key = []\r\n for c in s:\r\n if c in self.safe_s3_chars:\r\n s3key.append(c)\r\n elif c == \"@\":\r\n s3key.append('*at*')\r\n else:\r\n s3key.append('*%d*' % ord(c))\r\n return \"\".join(s3key)\r\n\r\n def download(self, projects, filename=None):\r\n submissions = set()\r\n print('Getting all s3 keys...')\r\n for p in projects:\r\n submissions |= self.get_submissions(p, rerun=True)\r\n print(f'Found {len(submissions)} files to download from projects {\", \".join(projects)}')\r\n for submission in tqdm(submissions):\r\n self.fetch_submission(submission, file_name=filename)\r\n\r\n def clear_caches(self):\r\n if self.conf.CLEANUP and os.path.exists(self.conf.S3_DIR):\r\n shutil.rmtree(self.conf.S3_DIR)\r\n\r\n\r\nif __name__ == '__main__':\r\n extra_help = 'TIP: run this if time is out of sync: sudo ntpdate -s time.nist.gov'\r\n parser = argparse.ArgumentParser(description='S3 Interface for CS320', epilog=extra_help)\r\n parser.add_argument('projects', type=str, nargs='+',\r\n help='id(s) of project to download submissions for.')\r\n parser.add_argument('-cf', '--config', type=str, dest='config_path', default='./s3config.json',\r\n help='s3 configuration file path, default is ./s3config.json')\r\n parser.add_argument('-ff', '--force-filename', type=str, dest='force_filename', default=argparse.SUPPRESS,\r\n help='force submission to have this filename')\r\n\r\n # Add unknown arguments to argument list and re-parse\r\n # This allows for arbitrary arguments to be parsed.\r\n parsed, unknown = parser.parse_known_args()\r\n for arg in unknown:\r\n if arg.startswith((\"-\", \"--\")):\r\n parser.add_argument(arg, type=str)\r\n database_args = parser.parse_args()\r\n d = Database(**vars(database_args))\r\n d.download(database_args.projects, filename=database_args.force_filename)\r\n\r\n","sub_path":"grader/s3interface.py","file_name":"s3interface.py","file_ext":"py","file_size_in_byte":5773,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"427848208","text":"from wordvec_utils import *\nfrom models import *\nfrom dataset_utils import *\nimport sys\n\nword2vec_file = 'GoogleNews-vectors-negative300.bin'\nwv_dict = wordvec_dict(word2vec_file)\n\nTx = 200\nTy = 1\nepochs = 40\n\ndef bilstm_mhad_fulltri_classifier(domainA, domainB,zeta=0.7,drop=0.4,heads=5,ortho_loss_weight=0.01,diversity_weight=0.01):\n\n\tXoh_domainA, Yoh_domainA, Xoh_domainB, Yoh_domainB = create_data4lstm(domainA, domainB, wv_dict, Tx, Ty)\n\tdomainA_unlabelled = create_data4lstm_DA_oneclass(domainA, wv_dict, Tx, Ty)\n\n\tmodelx = train_bilstm_mhad_fulltri(Xoh_domainA, Yoh_domainA, domainA_unlabelled, Tx, Ty, epochs=epochs,zeta=zeta,drop=drop,heads=heads,ortho_loss_weight=ortho_loss_weight, diversity_weight=diversity_weight)\n\tacc = evaluate_mhad_fulltri(modelx, Xoh_domainB, Yoh_domainB)\n\tprint(acc)\n\nbilstm_mhad_fulltri_classifier(sys.argv[1], sys.argv[2])\n\n","sub_path":"bilstm_mhad_tri_II.py","file_name":"bilstm_mhad_tri_II.py","file_ext":"py","file_size_in_byte":862,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"209508632","text":"import math\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport torchvision\nfrom torchvision import datasets, models, transforms\nfrom torch.autograd import Variable\n\nclass Swish(torch.nn.Module):\n def __init__(self, inplace=False):\n super(Swish, self).__init__()\n\n def forward(self, x):\n out = torch.mul(x, F.sigmoid(x))\n return out\n\n\nclass Sobel(torch.nn.Module):\n def __init__(self):\n super(Sobel, self).__init__()\n weightY = torch.Tensor(\n [[1.0, 0.0, -1.0],\n [2.0, 0.0, -2.0],\n [1.0, 0.0, -1.0]]\n )\n weightX = weightY.t()\n self.kernelY = Variable(weightY.unsqueeze_(0).unsqueeze_(0))\n self.kernelX = Variable(weightX.unsqueeze_(0).unsqueeze_(0))\n if torch.cuda.is_available():\n self.kernelY = self.kernelY.cuda()\n self.kernelX = self.kernelX.cuda()\n\n def forward(self, image):\n input = image.clone()\n Y = F.conv2d(input,\n self.kernelY, stride=int(1), padding=1)\n\n X = F.conv2d(input,\n self.kernelX, stride=int(1), padding=1)\n out = torch.sqrt(X * X + Y * Y)\n return out\n\n\nclass ResidualMonoPredictor(nn.Module):\n def __init__(self, dimension=1, isSobel = False):\n super(ResidualMonoPredictor, self).__init__()\n if isSobel == True:\n self.filter = Sobel()\n else:\n self.filter = nn.ReLU()\n self.model = models.resnet18(pretrained=True)\n conv = nn.Conv2d(1, 64, kernel_size=7, stride=2, padding=3, bias=False)\n weight = torch.FloatTensor(64, 1, 7, 7)\n parameters = list(self.model.parameters())\n for i in range(64):\n weight[i, :, :, :] = parameters[0].data[i].mean(0)\n conv.weight.data.copy_(weight)\n\n self.model.conv1 = conv\n self.model.relu = Swish()\n self.model.avgpool = nn.AvgPool2d(8, stride=1)\n num_ftrs = self.model.fc.in_features\n reduce_number = int(math.sqrt(num_ftrs))\n\n self.predictor = nn.Sequential(\n Swish(),\n nn.Linear(1000, 500),\n Swish(),\n nn.Linear(500, dimension),\n )\n\n def forward(self, x):\n x = self.filter(x)\n x = self.model(x)\n out = self.predictor(x)\n return out\n","sub_path":"ResidualMonoPredictor.py","file_name":"ResidualMonoPredictor.py","file_ext":"py","file_size_in_byte":2348,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"193304835","text":"\"\"\"\n3. Longest Substring Without Repeating Characters\n\nGiven a string, find the length of the longest substring without repeating characters.\n\nExample 1:\n\nInput: \"abcabcbb\"\nOutput: 3 \nExplanation: The answer is \"abc\", with the length of 3. \nExample 2:\n\nInput: \"bbbbb\"\nOutput: 1\nExplanation: The answer is \"b\", with the length of 1.\nExample 3:\n\nInput: \"pwwkew\"\nOutput: 3\nExplanation: The answer is \"wke\", with the length of 3. \n\n Note that the answer must be a substring, \"pwke\" is a subsequence and not a substring.\n\"\"\"\n\nclass Solution:\n def lengthOfLongestSubstring(self, s: str) -> int:\n result = 0\n tempResult = -1\n dictList = dict()\n for idx, val in enumerate(s):\n if val in dictList:\n tempResult = max(tempResult, dictList[val])\n dictList[val] = idx\n else:\n dictList[val] = idx\n\n result = max(result, idx - tempResult)\n return result\n\nsolu = Solution()\nsolu.lengthOfLongestSubstring(\"abcabcbb\")","sub_path":"LeetCodePraticesPython/question3.py","file_name":"question3.py","file_ext":"py","file_size_in_byte":1015,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"399443376","text":"from hlwtadmin.models import Artist, GigFinderUrl, GigFinder, ConcertAnnouncement, Venue, Location, Organisation, Country, Concert, RelationConcertConcert, RelationConcertOrganisation, RelationConcertArtist, Location\n\nfrom django.core.management.base import BaseCommand, CommandError\nfrom django.db.models import Count\nfrom collections import Counter\n\n\nclass Command(BaseCommand):\n def add_arguments(self, parser):\n pass\n\n def handle(self, *args, **options):\n for venue in Venue.objects.filter(raw_venue__endswith=\"songkick\"):\n venue.raw_venue = venue.raw_venue.replace(\"|songkick\", \"|www.songkick.com\")\n venue.raw_location = venue.raw_location.replace(\"|songkick\", \"|www.songkick.com\")\n venue.save()\n\n for venue in Venue.objects.filter(raw_venue__endswith=\"bandsintown\"):\n venue.raw_venue = venue.raw_venue.replace(\"|bandsintown\", \"|bandsintown.com\")\n venue.raw_location = venue.raw_location.replace(\"|bandsintown\", \"|bandsintown.com\")\n venue.save()\n\n for venue in Venue.objects.filter(raw_venue__endswith=\"facebook\"):\n venue.raw_venue = venue.raw_venue.replace(\"|facebook\", \"|www.facebook.com\")\n venue.raw_location = venue.raw_location.replace(\"|facebook\", \"|www.facebook.com\")\n venue.save()\n\n for venue in Venue.objects.filter(raw_venue__endswith=\"setlist\"):\n venue.raw_venue = venue.raw_venue.replace(\"|setlist\", \"|www.setlist.fm\")\n venue.raw_location = venue.raw_location.replace(\"|setlist\", \"|www.setlist.fm\")\n venue.save()\n","sub_path":"hlwtadmin/management/commands/add_www_and_extention_to_gigfinder_names.py","file_name":"add_www_and_extention_to_gigfinder_names.py","file_ext":"py","file_size_in_byte":1603,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"631617117","text":"from django.http import HttpResponse, HttpResponseRedirect\nfrom django.shortcuts import get_object_or_404, render_to_response\nfrom desktopsite.apps.repository.models import *\nfrom desktopsite.apps.repository.forms import *\nfrom desktopsite.apps.repository.categories import REPOSITORY_CATEGORIES\nfrom django.contrib.auth.decorators import login_required\nfrom django.template import RequestContext\n\ndef index(request):\n latest = Version.objects.all().order_by(\"-creation_date\")[:8]\n top_rated = Rating.objects.top_rated(8)\n featured = Rating.objects.featured(5)\n return render_to_response('repository/index.html', {\n 'categories': REPOSITORY_CATEGORIES,\n 'latest': latest, \n 'top_rated': top_rated,\n 'featured': featured,\n }, context_instance=RequestContext(request))\n \ndef byLetter(request, letter):\n results = Package.objects.filter(name__startswith=letter)\n return showResults(request, \"Packages starting with \\\"%s\\\"\" % letter, results)\n \ndef byCategory(request, category):\n results = Package.objects.filter(category__exact=category)\n return showResults(request, \"Packages in \\\"%s\\\"\" % category, results)\n\n@login_required \ndef userPackages(request):\n results = Package.objects.filter(maintainer__exact=request.user)\n return showResults(request, \"My Packages\", results)\n \n \ndef search(request):\n if request.GET.has_key(\"q\"):\n query = request.GET[\"q\"]\n else:\n query = \"\"\n if query:\n results = Package.objects.filter(name__contains=query)\n else:\n results = []\n return showResults(request, \"Results for \\\"%s\\\"\" % query, results)\n \ndef showResults(request, title, resultset):\n return render_to_response('repository/results.html', {\n 'results': resultset,\n 'title': (title if title else \"Search Results\"),\n }, context_instance=RequestContext(request))\n \ndef package(request, sysname):\n pak = get_object_or_404(Package, sysname=sysname)\n version = pak.get_versions_desc()\n if not version:\n version = {}\n else:\n version = version[0]\n return render_to_response('repository/package.html', {\n 'package': pak,\n 'version': version,\n }, context_instance=RequestContext(request))\n\ndef version(request, sysname, version):\n pak = get_object_or_404(Package, sysname=sysname)\n version = get_object_or_404(Version, package=pak, name=version)\n return render_to_response('repository/version.html', {\n 'package': pak,\n 'version': version,\n }, context_instance=RequestContext(request))\n \n@login_required\ndef saveRating(request):\n pk = request.POST[\"versionId\"]\n version = get_object_or_404(Version, pk=pk)\n value = request.POST[\"value\"]\n if not (value < 0 or value > 5):\n return HttpResponse(\"nice try asshole\", mimetype=\"text/plain\")\n try:\n rating, created=Rating.objects.get_or_create(version=version, user=request.user,\n defaults={'score': value})\n except Rating.MultipleObjectsReturned:\n #this happens on occasion, not sure why\n Rating.objects.filter(version=version, user=request.user).delete()\n rating = Rating(version=version, user=request.user)\n if value == \"0\":\n rating.delete()\n else:\n rating.score=value\n rating.save()\n return HttpResponse(\"ok\", mimetype=\"text/plain\")\n\n@login_required\ndef newPackage(request):\n if request.method == 'POST':\n form = PackageForm(request.POST, request.FILES)\n if form.is_valid():\n package = form.save(commit=False)\n package.maintainer = request.user\n package.save()\n request.user.message_set.create(message='New Package Created')\n return HttpResponseRedirect(package.get_absolute_url())\n else:\n form = PackageForm()\n return render_to_response(\"repository/form.html\", context_instance=RequestContext(request, {\n 'title': \"New Package\",\n 'form': form,\n }))\n\n\n@login_required\ndef newVersion(request, sysname):\n package = get_object_or_404(Package, sysname=sysname)\n if not package.user_is_maintainer():\n return HttpResponseRedirect(package.get_absolute_url())\n if request.method == 'POST':\n form = VersionForm(request.POST, request.FILES)\n form._requested_package = package\n is_valid = form.is_valid()\n\n if is_valid:\n version = form.save() #commit=False ommitted purposefully!\n version.package = package\n version.calc_md5sum()\n request.user.message_set.create(message='New Version Created')\n return HttpResponseRedirect(version.get_absolute_url())\n\n else:\n form = VersionForm()\n return render_to_response(\"repository/form.html\", context_instance=RequestContext(request, {\n 'title': \"New Version for %s\" % package.name,\n 'form': form,\n }))\n \n@login_required\ndef editPackage(request, sysname):\n package = get_object_or_404(Package, sysname=sysname)\n if not package.user_is_maintainer():\n return HttpResponseRedirect(package.get_absolute_url())\n if request.method == 'POST':\n form = PackageForm(request.POST, request.FILES, instance=package)\n if form.is_valid():\n package = form.save(commit=False)\n #package.maintainer = request.user\n package.save()\n request.user.message_set.create(message='Changes Saved')\n return HttpResponseRedirect(package.get_absolute_url())\n else:\n form = PackageForm(instance=package)\n return render_to_response(\"repository/form.html\", context_instance=RequestContext(request, {\n 'title': \"Editing %s\" % package.name,\n 'form': form,\n }))\n \n@login_required\ndef editVersion(request, sysname, version):\n package = get_object_or_404(Package, sysname=sysname)\n version = get_object_or_404(Version, name=version, package=package)\n if not package.user_is_maintainer():\n return HttpResponseRedirect(package.get_absolute_url())\n if request.method == 'POST':\n form = EditVersionForm(request.POST, request.FILES, instance=version)\n if form.is_valid():\n version = form.save(commit=False)\n version.package = package\n version.save()\n request.user.message_set.create(message='Changes Saved')\n return HttpResponseRedirect(version.get_absolute_url())\n else:\n form = EditVersionForm(instance=version)\n return render_to_response(\"repository/form.html\", context_instance=RequestContext(request, {\n 'title': \"Editing %s %s\" % (package.name, version.name),\n 'form': form,\n }))\n\n@login_required\ndef deleteVersion(request, sysname, version):\n package = get_object_or_404(Package, sysname=sysname)\n version = get_object_or_404(Version, name=version, package=package)\n if not package.user_is_maintainer():\n return HttpResponseRedirect(package.get_absolute_url())\n return doDeleteView(request, version, package.get_absolute_url())\n \n@login_required\ndef deletePackage(request, sysname):\n package = get_object_or_404(Package, sysname=sysname)\n if not package.user_is_maintainer():\n return HttpResponseRedirect(package.get_absolute_url())\n return doDeleteView(request, package, \"/repository/\")\n\n\ndef doDeleteView(request, object, finishUrl):\n if request.method == 'POST':\n if request.POST.has_key(\"Yes\"):\n request.user.message_set.create(message='%s Deleted.' % object)\n object.delete()\n return HttpResponseRedirect(finishUrl)\n else:\n return HttpResponseRedirect(object.get_absolute_url())\n else:\n return render_to_response(\"repository/delete.html\", context_instance=RequestContext(request, {\n 'object': object,\n }))\n\n","sub_path":"desktopsite/apps/repository/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":7861,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"424331152","text":"def stringCompression(uncomporessed):\n comp_list = []\n counter = 0\n\n for i in range(len(uncomporessed)):\n counter += 1\n if (i + 1) >= len(uncomporessed) or uncomporessed[i] != uncomporessed[i + 1]:\n comp_list.append(uncomporessed[i])\n comp_list.append(str(counter))\n counter = 0\n\n return ''.join(comp_list) if len(comp_list) < len(uncomporessed) else uncomporessed\n\n\nprint(stringCompression('aabcccccaaa'))\nprint(stringCompression('aaaaaaaaaaaaaaaaaaaaaa'))\nprint(stringCompression('aaaaaaahhhiiiiiissjjjjjjkkkkllslsmdj'))\nprint(stringCompression('ahdjskalsldksjabsbwbiji'))\nprint(stringCompression('eu nasci a dez mil anos atras'))","sub_path":"strings/string_compression.py","file_name":"string_compression.py","file_ext":"py","file_size_in_byte":691,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"195897091","text":"fin = open(\"../../Downloads/A-large (2).in\", \"r\")\nout = open(\"mushrooms.out\", \"w\")\n\ncases = int(fin.readline())\n\nfor i in range(cases):\n n = int(fin.readline())\n list = [int(x) for x in fin.readline().split()]\n tot = 0;\n maxDiff = 0;\n for j in range(1, n):\n diff = list[j-1] - list[j]\n if list[j-1] > list[j]:\n tot += diff\n if diff > maxDiff:\n maxDiff = diff\n tot2 = 0\n for x in list:\n tot2 += min(maxDiff, x)\n tot2 -= min(maxDiff, list[n-1])\n out.write(\"Case #%d: %d %d\\n\" % (i + 1, tot, tot2))\nout.close()\n","sub_path":"solutions_6404600001200128_1/Python/hongkai/mushrooms.py","file_name":"mushrooms.py","file_ext":"py","file_size_in_byte":585,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"611016418","text":"# 1. Напишите программу, на вход которой подается одна строка с целыми числами.\n# Программа должна вывести сумму этих чисел.\n# Используйте метод split строки.\na = [int(i) for i in input().split()]\nsum = 0\nfor i in a:\n sum += i\nprint(sum)\n\n###\nprint(sum(int(i) for i in input().split()))\n\n# Напишите программу, на вход которой подаётся список чисел одной строкой.\n# Программа ��олжна для каждого элемента этого списка вывести сумму двух его соседей.\n# Для элементов списка, являющихся крайними, одним из соседей считается элемент,\n# находящий на противоположном конце этого списка.\n# Если на вход пришло только одно число, надо вывести его же.\n# Вывод должен содержать одну строку с числами нового списка, разделёнными пробелом.\na = input().split()\nif len(a) == 1:\n print(a[0])\nelif len(a) == 2:\n print(int(a[1]) * 2, end=' ')\n print(int(a[0]) * 2, )\nelse:\n for i in range(len(a) - 1):\n e = int(a[i - 1]) + int(a[i + 1])\n print(e, end=' ')\n print(int(a[0]) + int(a[-2]))\n\n#\nx = [int(i) for i in input().split()] # получаем список чисел на входе\nif len(x) == 1:\n print(x[0])\nelse:\n x.insert(0, x[-1]) # добавляем последнее число входной послед-ти в начало\n x.append(x[1]) # добавляем первое число входной послед-ти в конец\n for i in range(1, len(x) - 1):\n print(x[i + 1] + x[i - 1], end=' ')\n\n# Напишите программу, которая принимает на вход список чисел в одной строке\n# и выводит на экран в одну строку значения, которые повторяются в нём более одного раза.\ns = [int(i) for i in input().split()]\ns.sort()\na = []\ni = 0\nwhile i in range(0, len(s)):\n if s.count(s[i]) > 1:\n a.append(s[i])\n i = i + s.count(s[i])\n else:\n i += 1\nfor i in a:\n print(i, end=' ')\n\n# Помещаю в новый список текущее число, если его там ещё нет И если в исходном списке таких чисел несколько\na, b = [int(i) for i in input().split()], []\nfor i in a:\n if a.count(i) > 1 and b.count(i) == 0:\n b.append(i)\nfor i in b:\n print(i, end=\" \")\n\n#\nls = [int(i) for i in input().split()]\nfor i in set(ls):\n if ls.count(i) > 1:\n print(i, end=' ')\n","sub_path":"step2.5.py","file_name":"step2.5.py","file_ext":"py","file_size_in_byte":2918,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"398960768","text":"#!/usr/bin/env python3\nimport configparser\nimport importlib\nfrom time import sleep\nfrom collections import namedtuple\nimport sys\nfrom . import Modules # Do not remove, needed for importlib\nimport re\n\nZenModule = namedtuple(\"ZenModule\", [\"name\", \"module\", \"config\"])\n\n\nclass StringInterpolation(configparser.Interpolation):\n\n _STRRE = re.compile(r\"^'(.*)'|\\\"(.*)\\\"$\")\n\n def before_get(self, parser, section, option, value, defaults):\n s = self._STRRE.match(value)\n if s:\n g = s.groups()\n if g[0]:\n return g[0]\n elif g[1]:\n return g[1]\n else:\n return ''\n else:\n return value\n\n\nclass ModuleEntryPointMissing(RuntimeError):\n\n def __init__(self, message, module_name):\n super(ModuleEntryPointMissing, self).__init__(message)\n self.name = module_name\n\n\nclass ZenPy:\n\n modules = []\n refresh = 1.0\n fmt = 'ZenPy: No format specified'\n\n def __loadConfig(self, filename: str):\n \"\"\"\n Load config file with ConfigParser\n \"\"\"\n config = configparser.SafeConfigParser(\n empty_lines_in_values=False,\n interpolation=StringInterpolation()\n )\n config.read(filename)\n for sec in config.sections():\n if sec.lower() == 'zenpy':\n self.refresh = config[sec].getfloat('refresh', ZenPy.refresh)\n self.fmt = config[sec].get('format', ZenPy.fmt)\n else:\n try:\n modconfig = config[sec]\n pymod = importlib.import_module(sec)\n zmod = ZenModule(name=sec, module=pymod, config=modconfig)\n if not hasattr(pymod, \"entry\") or not callable(pymod.entry):\n raise ModuleEntryPointMissing(\"Entry point not found\", name)\n except ImportError as e:\n print(\"[error] ZenModule '%s' not found, not added to your output.\"\n % e.name, file=sys.stderr)\n except ModuleEntryPointMissing as e:\n print(\"[error] ZenModule '%s' has no entry point,\" % e.name,\n \"not added to your output\",\n file=sys.stderr)\n else:\n print(\"[info] Adding module\", sec, file=sys.stderr)\n self.modules.append(zmod)\n\n def __init__(self, config_path: str):\n self.__loadConfig(config_path)\n\n def run(self, encod_func=str, exec_func=print):\n while True:\n infos = {}\n for mod in self.modules:\n # print(\"[info] Launching module\", name, file=sys.stderr)\n infos[mod.name] = mod.module.entry(mod.config)\n exec_func(encod_func(self.fmt.format(**infos)))\n sleep(self.refresh)\n","sub_path":"ZenPy/ZenPy.py","file_name":"ZenPy.py","file_ext":"py","file_size_in_byte":2868,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"539153156","text":"#-------------------------------------------------------------------------------\n# Name: config\n# Purpose:\n#\n# Author: dashney\n#\n# Created: 07/11/2018\n#\n#\n#-------------------------------------------------------------------------------\n\nimport os\n\n# CONNECTIONS/ INPUT LOCATIONS\n\nconnections = r\"\\\\besfile1\\grp117\\DAshney\\Scripts\\connections\"\n\nBESGEORPT_PROD = os.path.join(connections, \"BESDBPROD1.BESGEORPT.GIS.sde\")\nEGH_PUBLIC = os.path.join(connections, \"egh_public on gisdb1.rose.portland.local.sde\")\n\ncollection_lines = EGH_PUBLIC + r\"\\EGH_PUBLIC.ARCMAP_ADMIN.collection_lines_bes_pdx\"\n\nresiliency_archive_gdb = r\"\\\\besfile1\\Resiliency_Plan\\GIS\\pgdb\\Seismic_Analysis_Archive.gdb\"\n#resiliency_gdb = r\"\\\\besfile1\\Resiliency_Plan\\GIS\\pgdb\\Fragility_TESTING.gdb\"\nfragility_output = BESGEORPT_PROD + r\"\\BESGEORPT.GIS.fragility_city\"\n\n# DOGAMI = r\"\\\\besfile1\\gis3\\DataX\\DOGAMI\\Oregon_Resilience_Plan\\extracted\" # original source, copied to PWB\nPWB = r\"\\\\besfile1\\Resiliency_Plan\\GIS\\pgdb\\Snapshot_05262016.gdb\"\n\nDOG_PGV = r\"\\\\cgisfile\\public\\water\\Seismic Hazard Study\\SupportingData\\ORP_GroundMotionAndFailure.gdb\\Oregon_M_9_Scenario_Site_PGV\"\n\n# Portland Water Bureau sources - these are all vectors\nPWB_Liq = os.path.join(PWB, \"Seismic_Study_Deliverables_2016_Liquefaction\")\nPWB_LS = os.path.join(PWB, \"Seismic_Study_Deliverables_2016_Lateral_Spread\")\nPWB_LD = os.path.join(PWB, \"Seismic_Study_Deliverables_2016_Landslide_Deformation\")\nPWB_GS = os.path.join(PWB, \"Seismic_Study_Deliverables_2016_Ground_Settlement\")\n\n# relocated from pgdb to gdb - process could not \"see\" the fc in the mdb for some reason\nMacJac_combo = r\"\\\\besfile1\\Resiliency_Plan\\GIS\\pgdb\\Fragility_RepairCosts.gdb\\MacJacobs_combo\"\n\n# spreadsheet created by Joe Hoffman\nmaterialPatch_xls = r\"\\\\BESFile1\\Resiliency_Plan\\03.1 Project Work\\Seismic\\Conveyance Spine Repair Costs\\Assumed Material.xlsx\"\n\n\n# EQUATIONS/ CONSTANTS\n\ndef RR_waveprop_Calc(K1, PGV):\n return K1 * 0.00187 * PGV\n\ndef RR_PGD_Calc(K2, PGD):\n return K2 * 1.06 * pow(PGD, 0.319)\n\ndef rateCalc(minval, maxval, rate): # rate needs 0.8 for 80% eg\n return ((maxval - minval) * rate) + minval\n\nMJ_rate = 0.8 # value to assume within MacJac ranges\n\nPGD_Landslide_val = 4.800000000000001 # this val, extracted from raster, effectively = 0\n\ndepth_limit = 20\n\n# Decision Logic constants\npipe_depth = 30\nsum_deformation = 6\nRR1 = 1 # I have forgotted what this value means (DCA)\nRR2 = 4 # I have forgotted what this value means (DCA)\nval1 = \"Monitor\"\nval2 = \"Whole Pipe\"\nval3 = \"Spot Line\"\n\nfield_names = (\"mean_depth\", \"PGV\", \"Liq_Prob\", \"PGD_LS\", \"PGD_Set\", \"PGD_Liq_Tot\", \"PGD_Landslide\", \"K1\", \"K2_Don\",\n\"RR_Don_PGV\", \"RR_Don_PGD_Liq\", \"RR_Don_PGD_Landslide\", \"RR_Don_FIN\", \"RR_Don_breaknum\", \"Decision\")\n\ncalc_fields = (['PGV', 'Liq_Prob', 'PGD_LS', 'PGD_Set', 'PGD_Liq_Tot', 'PGD_Landslide',\n'K1', 'K2_Don', 'RR_Don_PGV', 'RR_Don_PGD_Liq', 'RR_Don_PGD_Landslide', 'RR_Don_FIN', 'RR_Don_breaknum',\n'wLandslide_RR_Don_FIN', 'wLandslide_RR_Don_breaknum'])\n\n# K VALUES\nDBBK1 = ({0.15:(\"H.D.P.\",\"HDP\",\"HDPE\",\"ADS\",\"STEEL\",\"SLIP\"), 0.5:(\"D.I.P.\",\"DIP\",\"DI\",\"D. TIL\",\"D.TIL\",\"Steel\",\"ASBEST\",\"ASBES\",\"ABS\",\"ACP\",\"ACPP\",\"A.C.P.\",\"FRP\"),\n0.8:(\"RCP\",\"RCSP\",\"R.C.S.\",\"MON\",\"MON.\",\"MON.C\",\"MON. C\",\"MCP\",\"CIPP\",\"MONO\",\"MONO.\",\"MONOLI\",\"MONO.C\",\"MONO-C\",\"PRECAS\",\"REINF.\",\"PS\",\"RMCP\",\"CSP\",\n\"C.S.P.\",\"CP\",\"C.P.\",\"CONC\",\"CONC.\",\"CON\",\"CON.\",\"CONCRE\",\"CCP\",\"CONBRK\"),0.6:(\"P.V.C.\",\"PVC\",\"FBR\"),0.3:(\"CMP\",\"COR.S\",\"COR.I.\",\"CORR.\"),\n1:(\"CIP\",\"C.I.P.\",\"C.I.\",\"CI\",\"IRON\"),1.3:(\"NCP\",\"NCP OR\"),0.7:(\"Wood\",\"CLAY\",\"CT\",\"TILE\",\n\"V.S.P.\",\"VSP\",\"VCP\",\"T.C.P.\",\"TCP\",\"BRCK\",\"BRICK\",\"BRCK.\",\"BRK\",\"BRK.\",\"B\",\"BR.\",\"BRKSTN\",\"B.&S.\")})\n\nDBBK2 = ({0.15:(\"H.D.P.\",\"HDP\",\"HDPE\",\"ADS\",\"STEEL\",\"SLIP\"), 0.5:(\"D.I.P.\",\"DIP\",\"DI\",\"D. TIL\",\"D.TIL\",\"Steel\"),\n0.8:(\"RCP\",\"RCSP\",\"R.C.S.\",\"MON\",\"MON.\",\"MON.C\",\"MON. C\",\"MCP\",\"CIPP\",\"MONO\",\"MONO.\",\"MONOLI\",\"MONO.C\",\"MONO-C\",\"PRECAS\",\"REINF.\",\"PS\",\"RMCP\",\"CSP\",\n\"C.S.P.\",\"CP\",\"C.P.\",\"CONC\",\"CONC.\",\"CON\",\"CON.\",\"CONCRE\",\"CCP\",\"ASBEST\",\"ASBES\",\"ABS\",\"ACP\",\"ACPP\",\"A.C.P.\",\"FRP\",\"CONBRK\"),0.9:(\"P.V.C.\",\"PVC\",\"FBR\"),\n0.3:(\"CMP\",\"COR.S\",\"COR.I.\",\"CORR.\"),1:(\"CIP\",\"C.I.P.\",\"C.I.\",\"CI\",\"IRON\"),0.7:(\"Wood\",\"CLAY\",\"CT\",\"TILE\",\n\"V.S.P.\",\"VSP\",\"VCP\",\"T.C.P.\",\"TCP\"),1.3:(\"BRCK\",\"BRICK\",\"BRCK.\",\"BRK\",\"BRK.\",\"B\",\"BR.\",\"BRKSTN\",\"B.&S.\",\"NCP\",\"NCP OR\")})\n\n# K VALUE PATCH\n# values from Joe Hoffman (Null val (assigned 0.8) accounted for in k value assignment section\nK1_patch = ({0.8:(\"brick_tunnel_liner_plate\", \"brick_conc_liner\", \"CONSTN\", \"VARIES\", \"UNSPEC\", \"stub\", \"STUB\", \"STUB _PLUG\",\n\"STUB&PLUG\", \"STUB & PLUG\", \"STUB]\", \"WOOD\", \"WOOD FLUME\"), 0.75:(\"brick_fbr_liner\")})\n\nK2_patch = ({0.8:(\"brick_tunnel_liner_plate\", \"CONSTN\", \"VARIES\", \"UNSPEC\", \"stub\", \"STUB\", \"STUB _PLUG\",\n\"STUB&PLUG\", \"STUB & PLUG\", \"STUB]\", \"WOOD\", \"WOOD FLUME\"), 0.75:(\"brick_fbr_liner\"), 1:(\"brick_conc_liner\")})\n","sub_path":"config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":4861,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"181542784","text":"#! /usr/local/bin/python3\n\n#Import\nimport sys\nfrom collections import Counter\n\n#Load data\nfilename = sys.argv[1]\n\n#Run program\ncounts = Counter()\n\nfor lines in open(filename):\n if lines.startswith('#'): continue\n fields = lines.split('\\t')\n chrom = fields[0]\n counts[chrom] += 1\n\nsortme = [(v,k) for k,v in counts.items()]\n\nsortme.sort()\n\nsortme.reverse()\n\nprint(\"Chromosome with most intervals:\", sortme[0][1])\n","sub_path":"problem_1.py","file_name":"problem_1.py","file_ext":"py","file_size_in_byte":424,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"454872624","text":"#coding: utf-8\n\n#Au départ, je dois importer mon demander à mon scripte python de lire les fichiers csv. Je lui fais donc la requete\n#Par la suite, je dosi importer le plugin BeautifulSoup. Je crée donc un environement virtuel que j'active. \n\nimport csv\nfrom bs4 import BeautifulSoup\nimport requests\nimport time\nimport datetime\n\n#Je donne un nom à mon fichier\n\nfichier = \"valeurmorue90-2014.csv\"\n\n#Objectif du travail: identifier le montant total recueilli par pêche en Atlantique lors de 1990 à 2014\n#Pour cela, je dois avoir deux URL. Le premier m'amènera à l'index ou se retrouve tout le travail, l'autre étant la fin de l'url.\nurl1= \"http://www.dfo-mpo.gc.ca/stats/commercial/land-debarq/sea-maritimes/s\"\nurl2= \"av-fra.htm\"\n\n#À des fins professionnelles, je dois m'identifier\n\nentetes = {\n \"User-Agent\": \"Alex Proteau s'intéresse aux poissons\",\n \n \"From\":\"alexproteau6@gmail.com\"\n}\n\n#Afin de trouver la variable par année, je dois détailler chaque partie de l'HTML qui différencie.\n#Changement=année\n\n\nperiode = {\n\t\"90\" : \"1990\",\n\t\"91\" : \"1991\",\n\t\"92\" : \"1992\",\n\t\"93\" : \"1993\",\n\t\"94\" : \"1994\",\n\t\"95\" : \"1995\",\n\t\"96\" : \"1996\",\n\t\"97\" : \"1997\",\n\t\"98\" : \"1998\",\n\t\"99\" : \"1999\",\n\t\"00\" : \"2000\",\n\t\"01\" : \"2001\",\n\t\"02\" : \"2002\",\n\t\"03\" : \"2003\",\n\t\"04\" : \"2004\",\n\t\"05\" : \"2005\",\n\t\"06\" : \"2006\",\n\t\"07\" : \"2007\",\n\t\"08\" : \"2008\",\n\t\"09\" : \"2009\",\n\t\"10\" : \"2010\",\n\t\"11\" : \"2011\",\n\t\"12\" : \"2012\",\n\t\"13\" : \"2013\",\n\t\"14\" : \"2014\",\n \n }\n \n \n#Pour clore le tout, je crée une équation qui me permettra de trouver ce que je cherche.\n#En inspectant ma page, je regarde quel est la partie HTML qui me donne l'information concernant le montant total\n#Je rajoute .text pour avoir l'information en .text.\n\nfor years,periode in periode.items():\n\n url = \"{}{}{}\".format(url1,periode,url2)\n print(\"L'URL pour {} est {}\".format(years,url))\n \n x = requests.get(url,headers=entetes,verify=False)\n \n page = BeautifulSoup(x.text,\"html.parser\")\n \n #print(page)\n \n \n#Je crée une formule qui me donnera la valeur total selon deux variables, soit l'année{1} et le montant{0}\n total = page.find(class_=\"bg-info text-right\").text\n valeur=total\n \n print(\" La valeur de la peche commerciale par la Nouvelle-Écosse en Maritimes en {1} est de {0} $ \".format(total,periode))\n \n#j'enregistre mon travail!\n\n travail = open(fichier,\"a\")\n alexproteau = csv.writer(travail)\n alexproteau.writerow(fichier)\n i=+1\n","sub_path":"finsession1.py","file_name":"finsession1.py","file_ext":"py","file_size_in_byte":2446,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"70797104","text":"# Optimizing a grammar for dependency length minimization\n\nimport random\nimport sys\n\nobjectiveName = \"DepL\"\n\nimport argparse\n\nparser = argparse.ArgumentParser()\n\nparser.add_argument('--language', type=str)\nparser.add_argument('--entropy_weight', type=float, default=0.001)\nparser.add_argument('--lr_policy', type=float, default=0.1)\nparser.add_argument('--momentum', type=float, default=0.9)\n\nargs = parser.parse_args()\n\nmyID = random.randint(0,10000000)\n\n\nposUni = set()\nposFine = set() \ndeps = [\"acl\", \"acl:relcl\", \"advcl\", \"advmod\", \"amod\", \"appos\", \"aux\", \"auxpass\", \"case\", \"cc\", \"ccomp\", \"compound\", \"compound:prt\", \"conj\", \"conj:preconj\", \"cop\", \"csubj\", \"csubjpass\", \"dep\", \"det\", \"det:predet\", \"discourse\", \"dobj\", \"expl\", \"foreign\", \"goeswith\", \"iobj\", \"list\", \"mark\", \"mwe\", \"neg\", \"nmod\", \"nmod:npmod\", \"nmod:poss\", \"nmod:tmod\", \"nsubj\", \"nsubjpass\", \"nummod\", \"parataxis\", \"punct\", \"remnant\", \"reparandum\", \"root\", \"vocative\", \"xcomp\"] \n\n\n\nfrom math import log, exp\nfrom random import random, shuffle\n\n\nfrom corpusIterator_V import CorpusIterator_V as CorpusIterator\n\noriginalDistanceWeights = {}\n\n\ndef makeCoarse(x):\n if \":\" in x:\n return x[:x.index(\":\")]\n return x\nimport hashlib\ndef hash_(x):\n return hashlib.sha224(x).hexdigest()\n\n\n\n\nhashToSentence = {}\n\nfor partition in [\"together\"]:\n for sentence in CorpusIterator(args.language,partition).iterator():\n sentenceHash = hash_(\" \".join([x[\"word\"] for x in sentence]))\n hashToSentence[sentenceHash] = sentence\n\nTARGET_DIR = \"/u/scr/mhahn/deps/DLM_MEMORY_OPTIMIZED/locality_optimized_dlm/manual_output_funchead_fine_depl_perSent/\"\nimport glob\nfrom collections import defaultdict\norderBySentence = {x:[] for x in hashToSentence}\nfiles = glob.glob(TARGET_DIR+\"/\"+args.language+\"*.tsv\")\nfor path in files:\n print(path)\n with open(path, \"r\") as inFile:\n header = next(inFile).strip().split(\"\\t\")\n header = dict(list(zip(header, range(len(header)))))\n# print >> outFile, \"\\t\".join(map(str,[\"DH_Weight\",\"CoarseDependency\",\"HeadPOS\", \"DependentPOS\", \"DistanceWeight\", \"Language\", \"FileName\"]))\n objDir = None\n orderBySentenceHere = {}\n for line in inFile:\n line = line.strip().split(\"\\t\")\n dhWeight = float(line[header[\"DH_Weight\"]])\n dependency = line[header[\"CoarseDependency\"]]\n head = line[header[\"HeadPOS\"]]\n dependent = line[header[\"DependentPOS\"]]\n# print(dhWeight, dependency, head, dependent)\n if dependency == \"obj\" and head == \"VERB\" and dependent == \"NOUN\":\n objDir = 1 if dhWeight > 0 else -1\n elif dependency.startswith(\"nsubj_\"):\n hash_ = dependency[dependency.index(\"_\")+1:]\n # print(hash_, hash_ in hashToSentence)\n orderBySentenceHere[hash_] = (1 if dhWeight > 0 else -1)\n for hash_, direction in orderBySentenceHere.items():\n orderBySentence[hash_].append(direction * objDir)\ndef mean(x):\n return sum(x)/(len(x)+1e-10)\nfleissKappa = 0.0\ncountP_, countN_ = 0.0, 0.0\nfor s, values in orderBySentence.items():\n if len(values) == 0:\n continue\n countP = sum([1 for x in values if x >= 0])\n countN = sum([1 for x in values if x < 0])\n countP_ += countP\n countN_ += countN\n assert countP + countN == len(files), (len(values), len(files), countN+countP, values)\n fleissKappa += countP * (countP-1) + countN * (countN-1)\nfleissKappa /= (len(orderBySentence) * len(files) * (len(files)-1)) + 1e-10\nfleissKappaExpected = (countP_**2 + countN_**2) / ((countP_+countN_)**2 + 1e-10)\n#quit()\n\ndef printSent(l):\n for x in l:\n print(\"\\t\".join([str(y) for y in [x[\"index\"], x[\"word\"], x[\"head\"], x[\"posUni\"], x[\"dep\"], \"------\" if (x[\"dep\"] == \"nsubj\" and x[\"posUni\"] == \"NOUN\") else \"\"]]))\n\nsentenceToHash = [(x, mean(y)) for x, y in orderBySentence.items()]\nsentenceToHash = sorted(sentenceToHash, key=lambda x:x[1])\n\ndef annotateChildren(sentence):\n for l in sentence:\n l[\"children\"] = []\n for l in sentence:\n if l[\"head\"] != 0:\n sentence[l[\"head\"]-1][\"children\"].append(l[\"index\"]) \n\ndef length(i, sentence):\n if \"length\" not in sentence[i-1]:\n sentence[i-1][\"length\"] = 1+sum([length(x, sentence) for x in sentence[i-1][\"children\"]])\n return sentence[i-1][\"length\"]\n\nfrom collections import defaultdict\nmatrix = {}\nfor x in [x+\"_\"+y for x in [\"SV\", \"VS\"] for y in [\"Root\", \"HeadIsLeft\", \"HeadIsRight\"]]:\n matrix[x] = 0\ndef mean(x):\n return sum(x)/(len(x)+1e-10)\nfor x in sentenceToHash:\n order = x[1]\n sent = hashToSentence[x[0]]\n annotateChildren(sent)\n for word in sent:\n if \"children\" not in word:\n continue\n if word[\"posUni\"] == \"VERB\":\n subjects = [i for i in word[\"children\"] if sent[i-1][\"dep\"] == \"nsubj\"]\n subjectsOrders = [\"VS\" if sent[i-1][\"head\"] < sent[i-1][\"index\"] else \"SV\" for i in subjects]\n objects = [i for i in word[\"children\"] if sent[i-1][\"dep\"] == \"obj\"]\n embeddingDirection = (\"Root\" if word[\"head\"] == 0 else (\"HeadIsLeft\" if word[\"head\"] < word[\"index\"] else \"HeadIsRight\"))\n if len(subjects) > 0:\n for s, order in zip(subjects, subjectsOrders):\n matrix[order+\"_\"+embeddingDirection] += 1\ncolumns = sorted(list(matrix))\nprint(columns)\nwith open(\"outputs/\"+__file__+\".tsv\", \"a\") as outFile:\n print >> outFile, \"\\t\".join([args.language] + [str(matrix[x]) for x in columns])\n\n","sub_path":"collectPerVerbProperties/SV_withinLang/VSOrderWhenEmbedded.py","file_name":"VSOrderWhenEmbedded.py","file_ext":"py","file_size_in_byte":5317,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"89012921","text":"import discord\nfrom discord.ext import tasks, commands\nimport asyncio\n\n# pylint: disable=no-member\n# pylint doesn't recognise that loops have 'start' and 'cancel' members so incorrectly throws errors without the above line.\n# remove during final debugging but expect to see some number of errors from that\n\nclass VoiceQueue(commands.Cog):\n def __init__(self,bot):\n self.bot = bot\n self.queue = []\n self.playing = False\n self.voiceLoop.start()\n \n def cog_unload(self):\n self.voiceLoop.cancel()\n\n async def add(self,userchannel,audiosource): # add request to play voice in a channel, max of 10\n if len(self.queue) < 10:\n self.queue += [(userchannel,audiosource)]\n else:\n print(\"Queue full!\")\n\n async def playAudio(self,userchannel,audiosource): # connect to channel, play audio, disconnect\n vc = await userchannel.connect()\n self.playing = True\n vc.play(discord.FFmpegPCMAudio(source=audiosource,executable=\"ffmpeg/ffmpeg.exe\",))\n while vc.is_playing():\n await asyncio.sleep(.1)\n await vc.disconnect()\n self.playing = False\n\n @tasks.loop(seconds=0.1) # check every 100ms if it has something to play AND not already playing something\n async def voiceLoop(self):\n if not self.queue == []: print(self.queue)\n if not self.playing and not self.queue == []:\n (userchannel,audiosource) = self.queue.pop(0)\n await self.playAudio(userchannel,audiosource)\n\n\n","sub_path":"voicequeue.py","file_name":"voicequeue.py","file_ext":"py","file_size_in_byte":1531,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"271781590","text":"\"\"\"\nreservoir simulation project 2 (2020): Problem 1\n2D Multiphase reservoir simulation: \nCapillary pressure and relative permeability: Capillary pressure\nAuthor: Mohammad Afzal Shadab\nEmail: mashadab@utexas.edu\nDate modified: 12/04/2020\n\"\"\"\nimport numpy as np\n\ndef cap_press(petro,Sw,Sw_hyst):\n\n S = (Sw - petro.Swr)/(1.0 - petro.Sor - petro.Swr) #Normalized saturation {Eq. 1.29}\n Se = (Sw - petro.Swr)/(1.0 - petro.Swr) #{Eq. 1.28a}\n \n #Corey-Brooks model\n Pcd = petro.Pe * (Se) **(-1.0 / petro.lamda) #Drainage capillary pressure (used for initialization) {Eq. 1.28a} \n Pci = petro.Pe * ((S) **(-1.0 / petro.lamda) - 1.0) #Imbibition capillary pressure (used for initialization) {Eq. 1.28b}\n \n #Capillary pressure scanning curve\n epspc = 1e-5\n Sw_max = 1.0 - petro.Sor\n f = ((Sw_max - Sw_hyst + epspc)/(Sw_max - Sw_hyst)) * ((Sw - Sw_hyst) / (Sw - Sw_hyst + epspc))\n #f = 1.0\n Pc = f * Pci + (1.0 - f) * Pcd\n\n #Calculate derivative\n S2 = (Sw + 0.001 - petro.Swr) / (1.0 - petro.Swr - petro.Sor)\n Se2 = (Sw + 0.001 - petro.Swr) / (1.0 - petro.Swr)\n \n Pcd2 = petro.Pe * Se2 **(-1.0 / petro.lamda)\n Pci2 = petro.Pe * (S2 **(-1.0 / petro.lamda) - 1.0 )\n f2 = ((Sw_max - Sw_hyst + epspc) / (Sw_max - Sw_hyst)) * ((Sw + 0.001 - Sw_hyst) / (Sw + 0.001 - Sw_hyst + epspc))\n #f2 = 1.0\n Pc2 = f2 * Pci + (1.0 - f2) * Pcd\n Pcprime = (Pc2 - Pc)/0.001\n \n return Pc,Pcprime;","sub_path":"Class_problems/Problem_14new_FullTwoPhaseComplex/cap_press.py","file_name":"cap_press.py","file_ext":"py","file_size_in_byte":1503,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"531595344","text":"#!/usr/bin/env python\n# Author: Jong Choi\n# Contact: choij@ornl.gov\n\nfrom distutils.extension import Extension\nimport numpy as np\n\n# Use mpi4py dist utils: https://bitbucket.org/mpi4py/mpi4py\nfrom conf.mpidistutils import setup\n#from distutils.core import setup\nfrom distutils.spawn import find_executable\nfrom distutils.core import Command\n\nimport subprocess\n\nm1 = Extension('adios_mpi', \n sources=['adios_mpi.cpp'], \n define_macros=[],\n include_dirs = [np.get_include()],\n library_dirs = [],\n libraries = [],\n extra_objects = [],\n extra_compile_args = ['-Wno-uninitialized',\n '-Wno-unused-function'])\n\ncmd = find_executable(\"adios_config\")\nif cmd == None:\n sys.stderr.write(\n \"adios_config is not installed nor found. \"\n \"Please install Adios or check PATH.\\n\")\n sys.exit(-1)\n\np = subprocess.Popen([\"adios_config\", \"-c\"], stdout=subprocess.PIPE)\nfor path in p.communicate()[0].strip().split(\" \"):\n if path.startswith('-I'):\n m1.include_dirs.append(path.replace('-I', '', 1))\n\np = subprocess.Popen([\"adios_config\", \"-l\"], stdout=subprocess.PIPE)\nfor path in p.communicate()[0].strip().split(\" \"):\n if path.startswith('-L'):\n m1.library_dirs.append(path.replace('-L', '', 1))\n if path.startswith('-l'):\n m1.libraries.append(path.replace('-l', '', 1))\n\nclass adios_test(Command):\n user_options = []\n def initialize_options(self):\n pass\n\n def finalize_options(self):\n pass\n\n def run(self):\n import subprocess\n import sys\n errno = subprocess.call([sys.executable, 'tests/test_adios_mpi.py', 'tests/config_mpi.xml'])\n raise SystemExit(errno)\n \nsetup(name = 'adios_mpi',\n version = '1.0.8',\n description = 'Python Module for Adios MPI',\n author = 'Jong Choi',\n author_email = 'yyalli@gmail.com',\n url = 'http://www.olcf.ornl.gov/center-projects/adios/',\n cmdclass={'test': adios_test},\n executables = [],\n ext_modules = [m1])\n","sub_path":"wrappers/numpy/setup_mpi.py","file_name":"setup_mpi.py","file_ext":"py","file_size_in_byte":2103,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"251691047","text":"from django.http import HttpRequest\nfrom django.contrib.auth import authenticate, login\nfrom django.conf import settings\nfrom django.core import serializers\nfrom django.shortcuts import render, HttpResponse, HttpResponseRedirect, get_object_or_404\nfrom .models import User, Farm, Note\n# from .utilities import validate_user, update_user, getUserById, email_users, email_requested\nfrom django.core.urlresolvers import reverse\nfrom django.core.mail import send_mail\nfrom geopy.geocoders import Nominatim\nfrom django.core.files.storage import FileSystemStorage\nfrom django.db.models import Q\nimport json\nimport re\nimport pdb\nfrom datetime import datetime\nfrom django.http import HttpResponseForbidden\n\n\ndef dashboard(request):\n\n note_list = Note.objects.filter(farmId=request.user.farmId).order_by('-edited')\n json_note_data = serializers.serialize(\"json\",note_list)\n\n current_farm = Farm.objects.get(pk=request.user.farmId.id)\n json_farm_data = serializers.serialize(\"json\",[current_farm])\n\n context = {\n 'farm_name' : request.user.farmId.farmName,\n 'first': request.user.first_name,\n 'last': request.user.last_name,\n 'json_notes': json_note_data,\n 'json_farm': json_farm_data,\n 'notes': note_list,\n }\n return render(request, 'dashboard.html', context)\n\ndef note_page(request, noteid):\n current_farm = Farm.objects.get(pk=request.user.farmId.id)\n json_farm_data = serializers.serialize(\"json\",[current_farm])\n\n note = Note.objects.get(pk=noteid)\n json_note_data = serializers.serialize(\"json\",[note])\n if note.farmId != request.user.farmId:\n return HttpResponseForbidden()\n\n context = {\n 'note' : note,\n 'farm_name' : request.user.farmId.farmName,\n 'json_farm': json_farm_data,\n 'json_note': json_note_data\n }\n\n if request.method == 'POST':\n values = request.POST\n note.title = values.get('title')\n note.body = values.get('body')\n note.longitude = values.get('lngInput')\n note.latitude = values.get('latInput')\n note.created_by = request.user\n note.edited = datetime.now()\n note.save()\n return HttpResponseRedirect('/dashboard')\n\n elif request.method == 'DELETE':\n note.delete()\n return HttpResponseRedirect('/dashboard')\n\n return render(request, 'note_page.html', context)\n\ndef create(request):\n current_farm = Farm.objects.get(pk=request.user.farmId.id)\n json_farm_data = serializers.serialize(\"json\",[current_farm])\n\n context = {\n 'farm_name' : request.user.farmId.farmName,\n 'json_farm': json_farm_data,\n }\n\n if request.method == 'POST':\n values = request.POST\n\n Note.objects.create(title=values.get('title'),body=values.get('body'),longitude=values.get('lngInput'),latitude=values.get('latInput'),created_by=request.user,farmId=current_farm)\n return HttpResponseRedirect('/dashboard')\n\n return render(request, 'create.html', context)\n","sub_path":"farm_notes/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2996,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"311930922","text":"# Copyright (C) 2014 Hiroki Horiuchi \n#\n# Copying and distribution of this file, with or without modification,\n# are permitted in any medium without royalty provided\n# the copyright notice and this notice are preserved.\n# This file is offered as-is, without any warranty.\n\nfrom os import listdir\nfrom os.path import curdir, isdir, isfile, islink, join\n\ndef simple_walk(prefix):\n def recurse(prefix, directory):\n for filename in sorted(listdir(directory)):\n path = join(prefix, filename)\n if islink(path):\n continue\n if isfile(path):\n yield filename, path\n continue\n if not isdir(path):\n continue\n for y in recurse(path, path):\n yield y\n return recurse(prefix, prefix if prefix else curdir)\n\nif __name__ == '__main__':\n raise Exception('making a module executable is a bad habit.')\n","sub_path":"data/syspatch/grub.d/py/wheels19290/simplewalk.py","file_name":"simplewalk.py","file_ext":"py","file_size_in_byte":945,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"303266895","text":"#!/usr/bin/python2.7\n#coding:utf-8\n\nimport os\npath='/home/tongpinmo/software/pycharm-community-2017.3.1/projects/filtered_words'\ndef filter_words(path):\n if os.path.isfile(path):\n with open(path,'r') as f:\n words=f.read().split()\n return words\n\n\ndef sense_words():\n\n words=filter_words(path)\n while True:\n sentence=raw_input('input: ')\n if sentence=='0':\n print('exit')\n break\n for i in words:\n if i in sentence:\n replace=''\n for j in range(len(i)):\n replace=replace+'*'\n sentence=sentence.replace(i,replace)\n print(sentence)\n\n\nif __name__ == '__main__':\n sense_words()","sub_path":"t0016_sensewords.py","file_name":"t0016_sensewords.py","file_ext":"py","file_size_in_byte":715,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"198199276","text":"#!/usr/bin/python3.5\n\nimport threading\nimport up_zabbix_api as api\nimport subprocess\nimport socket\n\ntoken = api.zabb_token(api.zabb_url,api.zabb_user,api.zabb_password)\n\nhosts = api.zabb_host(api.zabb_url,token,parametr='hostid')\ninterfaces = api.zabb_interfaces(api.zabb_url,token,hosts,'type')\n\nip = []\nping = []\nnew = []\nl = []\ndns = []\nnodns = []\ncount = 0\n\nfor i in interfaces:\n if i['dns'] == '':\n pass\n else:\n dns.append(i['dns'])\n if i['ip'] == '' or i['ip'] == '127.0.0.1':\n pass\n else:\n ip.append(i['ip'])\n\nfor i in range(0,255):\n l.append('192.168.1.' + str(i))\n l.append('192.168.10.' + str(i))\n l.append('192.168.11.' + str(i))\n\ndef ping_ip(l,ip,dns):\n for i in l:\n prog = subprocess.call(['/usr/sbin/fping', '-i', '50', '-r', '0', i], stderr=subprocess.DEVNULL, stdout=subprocess.DEVNULL)\n if prog == 0:\n s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n a = s.connect_ex((i, 22))\n if a == 0:\n try:\n name = socket.gethostbyaddr(i)[0]\n ipi = socket.gethostbyaddr(i)[2][0]\n if name in dns or ipi in ip:\n pass\n else:\n ping.append(name)\n except:\n if i in ip:\n pass\n else:\n nodns.append(i)\n\ne1 = threading.Event()\ne2 = threading.Event()\ne3 = threading.Event()\ne4 = threading.Event()\ne5 = threading.Event()\ne6 = threading.Event()\ne7 = threading.Event()\ne8 = threading.Event()\n\nt1 = threading.Thread(target=ping_ip, args=(l[:100], ip, dns))\nt2 = threading.Thread(target=ping_ip, args=(l[100:200], ip, dns))\nt3 = threading.Thread(target=ping_ip, args=(l[200:300], ip, dns))\nt4 = threading.Thread(target=ping_ip, args=(l[300:400], ip, dns))\nt5 = threading.Thread(target=ping_ip, args=(l[400:500], ip, dns))\nt6 = threading.Thread(target=ping_ip, args=(l[500:600], ip, dns))\nt7 = threading.Thread(target=ping_ip, args=(l[600:700], ip, dns))\nt8 = threading.Thread(target=ping_ip, args=(l[700:800], ip, dns))\n\nt1.start()\nt2.start()\nt3.start()\nt4.start()\nt5.start()\nt6.start()\nt7.start()\nt8.start()\n\ne1.set()\n\nt2.join()\nt3.join()\nt4.join()\nt5.join()\nt6.join()\nt7.join()\nt8.join()\n\nnum = len(ping)\n\nwith open('/tmp/discovery_linux.json','w') as f:\n f.write('{ \"data\":[')\n if num != 0:\n for i in ping:\n f.write('{ \"{#LINUX}\":\"' + i + '\"}')\n count = count + 1\n if count == num:\n f.write(']}')\n else:\n f.write(',')\n else:\n f.write(']}')\n\ncount = 0\nwith open('/tmp/discovery_linux_awk.json','w') as f:\n f.write('{ \"new\":{\"hosts\":[')\n if num != 0:\n for i in ping:\n f.write('\"' + i + '\"')\n count = count + 1\n if count == num:\n f.write(']}}')\n else:\n f.write(',')\n else:\n f.write(']}}')\n\nnum_2 = len(nodns)\ncount = 0\nwith open('/tmp/discovery_unknown_ssh.json','w') as f:\n f.write('{ \"data\":[')\n if num_2 != 0:\n for i in nodns:\n f.write('{ \"{#SSH}\":\"' + i + '\"}')\n count = count + 1\n if count == num_2:\n f.write(']}')\n else:\n f.write(',')\n else:\n f.write(']}')\n\n","sub_path":"zabbix-scripts/discovery_linux_os.py","file_name":"discovery_linux_os.py","file_ext":"py","file_size_in_byte":3386,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"115143805","text":"from django.contrib import admin\nfrom django.contrib import messages\nfrom django.db import IntegrityError\n\n\nfrom django.db import connection\n\nimport reversion\n\nfrom grappelli_autocomplete_fk_edit_link import AutocompleteEditLinkAdminMixin\nfrom leaflet.admin import LeafletGeoAdmin\n\nfrom .models import *\n\n# Actions\n\ndef merge(modeladmin, request, queryset):\n\n print('DOING THE MERGE')\n\n errors = 0\n primary_object = None\n for obj in queryset:\n if primary_object is None:\n primary_object = obj\n else:\n print('merge %s in %s' % (obj,primary_object))\n\n # ForeignKeys\n for related_object in obj._meta.get_all_related_objects():\n # The variable name on the obj model.\n obj_varname = related_object.get_accessor_name()\n # The variable name on the related model.\n related_varname = related_object.field.name\n\n print('foreginkey %s or %s' % (obj_varname,related_varname))\n related_objects = getattr(obj, obj_varname)\n for relobj in related_objects.all():\n try:\n setattr(relobj, related_varname, primary_object)\n relobj.save()\n except IntegrityError as e:\n errors += 1\n \n # ManyToManyKeys\n for related_many_object in obj._meta.get_all_related_many_to_many_objects():\n # The variable name on the obj model.\n obj_varname = related_many_object.get_accessor_name()\n # The variable name on the related model.\n related_varname = related_many_object.field.name\n \n if obj_varname is not None:\n # standard case\n related_many_objects = getattr(obj, obj_varname).all()\n else:\n # special case, symmetrical relation, no reverse accessor\n related_many_objects = getattr(obj, related_varname).all()\n\n for relobj in related_many_objects.all():\n getattr(relobj, related_varname).remove(obj)\n getattr(relobj, obj_varname).add(primary_object)\n\n if errors>0:\n admin.ModelAdmin.message_user( messages.ERROR,\n request,\n ('La fusion n\\' est pas complète en raison de la collision de %i code(s)' % errors) )\n else:\n obj.delete()\nmerge.short_description = \"Fusionner les entités\"\n\ndef do_update_geometrie(base, related, id):\n sql = '''\nUPDATE \"BaseLieux_'''+base+'''\" as base SET geometrie=related.geom\nFROM\n (\n SELECT '''+base+'''_id as rel_id, ST_ConcaveHull(ST_Union(ST_MakeValid(ST_Simplify(geometrie,0.000001))),0.85) as geom\n FROM \"BaseLieux_'''+related+'''\" \n GROUP BY '''+base+'''_id\n) as related\nWHERE related.rel_id=base.id AND base.id = %s\n '''\n cursor = connection.cursor().execute(sql, [id])\n\n\n\n# Région\n\nclass VilleInline(admin.TabularInline):\n model = Ville\n fields = ('code','nom',)\n extra = 0\nclass RegionAdmin(LeafletGeoAdmin, reversion.VersionAdmin):\n model = Region\n inlines = (VilleInline,)\n actions = [merge, \"update_geometrie\"]\n\n def update_geometrie(modeladmin, request, queryset):\n for region in queryset:\n do_update_geometrie('region','ville',region.id)\n update_geometrie.short_description = \"Recalculer la géométrie\"\n\nadmin.site.register(Region, RegionAdmin)\n\n\n# Ville\n\nclass CommuneInline(admin.TabularInline):\n model = Commune\n fields = ('code','nom',)\n extra = 0\nclass VilleAdmin(LeafletGeoAdmin, reversion.VersionAdmin, AutocompleteEditLinkAdminMixin):\n model = Ville\n inlines = (CommuneInline,)\n ordering = ('region','code',)\n actions = [merge, \"update_geometrie\"]\n\n raw_id_fields = ('region',)\n autocomplete_lookup_fields = {\n 'fk': ['region'],\n }\n\n def update_geometrie(modeladmin, request, queryset):\n for ville in queryset:\n do_update_geometrie('ville','commune',ville.id)\n update_geometrie.short_description = \"Recalculer la géométrie\"\n\nadmin.site.register(Ville, VilleAdmin)\n\n\n# Commune\n\nclass QuartierInline(admin.TabularInline):\n model = Quartier\n fields = ('code','nom',)\n extra = 0\nclass CommuneAdmin(LeafletGeoAdmin, reversion.VersionAdmin, AutocompleteEditLinkAdminMixin):\n model = Commune\n inlines = (QuartierInline,)\n ordering = ('ville','code',)\n actions = [merge, \"update_geometrie\"]\n\n raw_id_fields = ('ville',)\n autocomplete_lookup_fields = {\n 'fk': ['ville'],\n }\n\n def update_geometrie(modeladmin, request, queryset):\n for commune in queryset:\n do_update_geometrie('commune','quartier',commune.id)\n update_geometrie.short_description = \"Recalculer la géométrie\"\n\nadmin.site.register(Commune, CommuneAdmin)\n\n\n# Quartier\n\nclass IlotInline(admin.TabularInline):\n model = Ilot\n fields = ('code',)\n extra = 0\nclass QuartierAdmin(LeafletGeoAdmin, reversion.VersionAdmin, AutocompleteEditLinkAdminMixin):\n model = Quartier\n display_link = ('__str__','code')\n list_display = ('__str__','code')\n search_fields = ('code','nom','commune__code','commune__nom',)\n ordering = ('commune','code',)\n actions = [merge, \"update_geometrie\"]\n \n inlines = (IlotInline,) \n\n raw_id_fields = ('commune',)\n autocomplete_lookup_fields = {\n 'fk': ['commune'],\n }\n\n def update_geometrie(modeladmin, request, queryset):\n for ilot in queryset:\n do_update_geometrie('quartier','ilot',ilot.id)\n update_geometrie.short_description = \"Recalculer la géométrie\"\n\n\nadmin.site.register(Quartier, QuartierAdmin)\n\n\n# Ilot\n\nclass LotInline(admin.TabularInline):\n model = Lot\n fields = ('code',)\n extra = 0\nclass IlotAdmin(LeafletGeoAdmin, reversion.VersionAdmin, AutocompleteEditLinkAdminMixin):\n model = Ilot\n display_link = ('__str__','code')\n list_display = ('__str__','code')\n search_fields = ('code','quartier__code','quartier__nom',)\n ordering = ('quartier','code',)\n actions = [merge, \"update_geometrie\"]\n \n inlines = (LotInline,)\n\n raw_id_fields = ('quartier',)\n autocomplete_lookup_fields = {\n 'fk': ['quartier'],\n }\n\n def update_geometrie(modeladmin, request, queryset):\n for lot in queryset:\n do_update_geometrie('ilot','lot',lot.id)\n update_geometrie.short_description = \"Recalculer la géométrie\"\n\nadmin.site.register(Ilot, IlotAdmin)\n\n\n# Lot\n\nclass LotAdmin(LeafletGeoAdmin, reversion.VersionAdmin, AutocompleteEditLinkAdminMixin):\n model = Lot\n display_link = ('__str__','code')\n list_display = ('__str__','code')\n ordering = ('ilot','code',)\n list_filter = ('ilot__quartier__commune',) # TODO filtre sur liste ilots ne marche pas\n search_fields = ('code','ilot__code','ilot__quartier__code','ilot__quartier__nom',)\n\n raw_id_fields = ('ilot',)\n autocomplete_lookup_fields = {\n 'fk': ['ilot'],\n }\n\n inlines = ()\n\n # DEPENDENCE : SuiviOccupationFonciere\n from SuiviOccupationFonciere.admin import PersonneRelationFonciereInline\n inlines += (PersonneRelationFonciereInline,)\nadmin.site.register(Lot, LotAdmin)","sub_path":"BaseLieux/admin.py","file_name":"admin.py","file_ext":"py","file_size_in_byte":7403,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"477867074","text":"# -*- coding: utf-8 -*-\n\nfrom __future__ import with_statement # ファイルの最初の行にある必要アリ\nimport os\nimport uuid\nimport json\nimport time\nimport urlparse\nfrom openfish import functions\nimport logging\nimport locale\nimport webapp2\nimport webapp2_extras\nfrom webapp2_extras import auth, sessions\nfrom webapp2_extras.appengine.auth.models import User\nfrom google.appengine.ext import ndb\nfrom google.appengine.api import images, files, search\n\n\n\n\n\n\nclass CustomField( ndb.Expando ):\n\tpass\n\n\nclass ExternalAccount( ndb.Model ):\n\texternal_id = ndb.StringProperty()\n\texternal_type = ndb.StringProperty()\n\ttoken = ndb.StringProperty()\n\ttokenSecret = ndb.StringProperty()\n\n\tdef toDict( self, full=False ):\n\t\tout = self.to_dict( include=[\"external_id\",\"external_type\"] )\n\t\treturn out\n\n\n\nclass BaseModel( ndb.Model ):\n\treadOnlyFields = [\"user_key\",\"custom_fields\",\"created_at\",\"created_time\",\"tags\",\"is_deleted\"]\n\tuser_key = ndb.KeyProperty( kind=User )\n\t# custom_fields = ndb.StructuredProperty( CustomField, repeated=False )\n\ttags = ndb.StringProperty( repeated=True )\n\tupdated_at = ndb.IntegerProperty()\n\tcreated_time = ndb.IntegerProperty( default=int(time.time()) )\n\tcreated_at = ndb.DateTimeProperty( auto_now_add=True )\n\tis_deleted = ndb.BooleanProperty( default=False )\n\n\n\t# イーガーローディングする\n\t# 使い方\n\t# q = models.Entry.query()\n\t# results = q.fetch()\n\t# openfish.models.BaseModel.prefetchRelations( results, [\"photo_key\",\"user_key\"] )\n\t@classmethod\n\tdef prefetchRelations( cls, entities, properties ):\n\t\tkeys_array = []\n\t\tfor entity in entities:\n\t\t\tfor prop in properties:\n\t\t\t\tkey = getattr( entity, prop )\n\t\t\t\tif key is not None:\n\t\t\t\t\tkeys_array.append( key )\n\t\tresults = ndb.get_multi( keys_array )\n\t\t# logging.info( results )\n\n\n\n\t# 現在ログイン中ユーザーを取得する関数\n\tuserCache = \"notInitialized\"\n\t@classmethod\n\tdef getCurrentUser( cls ):\n\t\tlogging.error( \"現在 getCurrentUser にはバグがあります\" )\n\t\tif cls.userCache==\"notInitialized\":\n\t\t\tmyAuth = auth.get_auth()\n\t\t\tuserInfo = myAuth.get_user_by_session()\n\t\t\tif userInfo:\n\t\t\t\tcls.userCache = User.get_by_id( userInfo[\"user_id\"] )\n\t\t\telse:\n\t\t\t\tcls.userCache = None\n\t\treturn cls.userCache\n\n\n\t# 自分の作成したオブジェクトかどうか?\n\tdef getIsMine( self ):\n\t\tlogging.error( \"現在 getIsMine にはバグがあります\" )\n\t\tif self.user_key and self.getCurrentUser():\n\t\t\treturn self.getCurrentUser().key == self.user_key\n\t\telse:\n\t\t\treturn False\n\n\n\t# put 直前に呼ばれる\n\tdef _pre_put_hook( self ):\n\t\t# req = webapp2.get_request()\n\t\t# _udid = req.get( \"udid\", None )\n\t\t# if _udid is not None:\n\t\t# \tself.udid = _udid\n\n\t\t# # temp_idを入れる\n\t\t# _session_store = sessions.get_store( request=req );\n\t\t# _session = _session_store.get_session()\n\t\t# if \"temp_uid\" not in _session:\n\t\t# \tlogging.info( \"temp_uid を作成します\" )\n\t\t# \t_session['temp_uid'] = str( uuid.uuid4() )\n\t\t# self.temp_uid = _session[\"temp_uid\"]\n\t\tpass\n\n\n\tdef toDict( self, full=False ):\n\t\tlogging.error( \"toDictを実装してください\" )\n\n\t# Like数取得\n\tdef getLikeCount( self ):\n\t\tcount = 0\n\t\tqry = Like.query( Like.target_key==self.key )\n\t\tfor obj in qry.iter( keys_only=True ):\n\t\t\tcount = count + 1\n\t\treturn count\n \nclass BaseExpandoModel( ndb.Expando ):\n\tuser_key = ndb.KeyProperty( kind=User )\n\tcreated_at = ndb.IntegerProperty()\n\tupdated_at = ndb.IntegerProperty()\n\n\nclass CustomObject( BaseModel ):\n\t# コンフィグ\n\treadOnlyFields = BaseModel.readOnlyFields + [\"photo_key\",\"fields\"]\n\tisMasterData = False # マスタデータかどうか。 True なら管理者以外追加や変更ができない\t\n\n\tphoto_key = ndb.KeyProperty()\n\tfields = ndb.StructuredProperty( CustomField, repeated=False )\n\n\tdef toDict( self, full=False ):\n\t\tout = self.to_dict( exclude=[\"created_at\",\"user_key\",\"photo_key\"] )\n\t\tout[\"id\"] = self.key.id()\n\t\treturn out\n\n\n\n\n# ----------------------------------------------------------------------\n# \n# Cocoafish オリジナルモデル\n# \n# ----------------------------------------------------------------------\n\nclass User( webapp2_extras.appengine.auth.models.User ):\n\temail = ndb.StringProperty( indexed=False )\n\tnickname = ndb.StringProperty( indexed=False )\n\tphoto_key = ndb.KeyProperty( indexed=False )\n\tdevice_token = ndb.StringProperty( indexed=False )# push notification 用\n\tfriend_user_keys = ndb.KeyProperty( repeated=True )\n\texternal_accounts = ndb.StructuredProperty( ExternalAccount, repeated=False )\n\tis_deleted = ndb.BooleanProperty( default=False )\n\t# メアドが確認できているか?メアド認証周りの処理で間違ってUserが消えてしまわないため、デフォルトはTrueにしてあります。メアドでユーザーを作成するときには明示的にFalseを設定して作成しましょう。\n\tverified = ndb.BooleanProperty( default=True )\n\tcomfirming_email = ndb.StringProperty( default=None )# 確認待ちのメールアドレス\n\tcreated_at = ndb.DateTimeProperty( auto_now_add=True )\n\n\t@property\n\tdef ua_alias(self):\n\t\t\"\"\"Alias for UrbanAirship\"\"\"\n\t\treturn str(self.key.id())\n\n\tdef set_password(self, raw_password):\n\t\t\"\"\"Sets the password for the current user\n \n\t\t:param raw_password:\n\t\t\tThe raw password which will be hashed and stored\n\t\t\"\"\"\n\t\tself.password = security.generate_password_hash(raw_password, length=12)\n\n\t@classmethod\n\tdef get_by_auth_token( cls, user_id, token, subject='auth' ):\n\t\t\"\"\"Returns a user object based on a user ID and token.\n\n\t\t:param user_id:\n\t\t\tThe user_id of the requesting user.\n\t\t:param token:\n\t\t\tThe token string to be verified.\n\t\t:returns:\n\t\t\tA tuple ``(User, timestamp)``, with a user object and\n\t\t\tthe token timestamp, or ``(None, None)`` if both were not found.\n\t\t\"\"\"\n\t\ttoken_key = cls.token_model.get_key(user_id, subject, token)\n\t\tuser_key = ndb.Key(cls, user_id)\n\t\t# Use get_multi() to save a RPC call.\n\t\tvalid_token, user = ndb.get_multi([token_key, user_key])\n\t\tif valid_token and user:\n\t\t\ttimestamp = int(time.mktime(valid_token.created.timetuple()))\n\t\t\treturn user, timestamp\n\n\t\treturn None, None\n\n\n\n\n\t# 友達を追加( 1 way )\n\t# 双方向に友だちになるには、それぞれの方向に1回ずつ呼んでください\n\tdef addFriend( self, newFriendUser ):\n\t\tif newFriendUser.key == self.key:\n\t\t\tlogging.warn( \"自分自身とは友達になれません\" )\n\t\t\treturn\n\n\t\t# 重複チェッ��\n\t\tif newFriendUser.key in self.friend_user_keys:\n\t\t\tlogging.debug( \"すでに友だち登録済みです\" )\n\t\t\treturn\n\n\t\tself.friend_user_keys.append( newFriendUser.key )\n\t\tself.put()\n\t\tlogging.info( u\"%sと%sが友だちになりました\" %( self.nickname, newFriendUser.nickname ) )\n\n\n\t# fbidを渡して、fb友だちかチェック\n\tdef checkIsMyFacebookFriend( self, fbUserId ):\n\t\tfbFriends = self.getFacebookFriends()\n\n\t\tfbFriendIds = []\n\t\tfor fbFriend in fbFriends:\n\t\t\tfbFriendIds.append( fbFriend[\"id\"] )\n\t\t\n\t\treturn fbUserId in fbFriendIds\n\n\n\n\n\t# 友だち一覧を取得\n\t# パラメータ組み合わせ\n\t# withFB=False,\tinstalledOnly=False\t: アプリ内友だちの User リストを取得\n\t# withFB=True,\tinstalledOnly=True\t: アプリ内友だちの User リスト + Facebook 友だちで同じアプリをインストール済みの User リストを取得\n\t# withFB=True,\tinstalledOnly=False\t: アプリ内友だちの User リスト + Facebook 友だちで同じアプリをインストール済みの User リスト + Facebook 友だちのデータリストを取得\n\tdef getFriends( self, withFB=False, installedOnly=False, keys_only=False ):\n\t\t# アプリ内の友だちのみ返す\n\t\tif withFB==False:\n\t\t\tif keys_only:\n\t\t\t\treturn self.friend_user_keys\n\t\t\telse:\n\t\t\t\treturn ndb.get_multi( self.friend_user_keys )\n\n\t\tinstalled, notInstalled = self.getInAppFacebookFriends( keys_only=True )\n\n\t\t# アプリ内友だちの User リスト + Facebook 友だちで同じアプリをインストール済みの User リストを返す\n\t\tallFriendUserKeys = self.friend_user_keys + installed\n\t\tallFriendUserKeys = list( set(allFriendUserKeys) )# 重複を取り除く\n\t\tif installedOnly:\n\t\t\tif keys_only:\n\t\t\t\treturn allFriendUserKeys\n\t\t\telse:\n\t\t\t\treturn ndb.get_multi( allFriendUserKeys )\n\t\telse:\n\t\t\tif keys_only:\n\t\t\t\treturn allFriendUserKeys + notInstalled\n\t\t\telse:\n\t\t\t\treturn ndb.get_multi( allFriendUserKeys ) + notInstalled\n\n\n\t# 同じアプリをインストールしているFBフレンドの、このアプリ内の User データのリストを取得\n\t# installed と notInstalled のタプルを返す\n\tdef getInAppFacebookFriends( self, keys_only=False ):\n\t\tif self.external_accounts is None or self.external_accounts.external_type!=\"facebook\":\n\t\t\treturn ( [], [] );\n\n\t\t# facebook情報を取得\n\t\tfbFriends = self.getFacebookFriends()\n\n\t\t# このアプリにすでに登録しているfbユーザーを抽出\n\t\tfbIdList = []\n\t\tfor friend in fbFriends:\n\t\t\tfbIdList.append( friend[\"id\"] )\n\n\t\tm = User\n\t\tquery = m.query( m.external_accounts.external_id.IN(fbIdList), m.is_deleted==False )\n\t\tinstalledUsers = query.fetch()\n\n\n\t\t# このアプリを利用していないユーザーのリストを作成\n\t\tnotInstalledFriends = []\n\t\tfor fbFriend in fbFriends:\n\t\t\texists = False\n\t\t\tfor user in installedUsers:\n\t\t\t\tif user.external_accounts.external_id==fbFriend[\"id\"]:\n\t\t\t\t\texists = True\n\t\t\tif exists==False:\n\t\t\t\tnotInstalledFriends.append( fbFriend )\n\n\t\t# 出力\n\t\tif keys_only:\n\t\t\t# Key のみを返す\n\t\t\tinstalledUserKeys = []\n\t\t\tfor user in installedUsers:\n\t\t\t\tinstalledUserKeys.append( user.key )\n\t\t\treturn ( installedUserKeys, notInstalledFriends )\n\t\telse:\n\t\t\treturn ( installedUsers, notInstalledFriends )\n\n\n\n\t# Facebook Graph API にアクセスし、Facebook 内での友だちリストを取得\n\tdef getFacebookFriends( self ):\n\t\tif self.external_accounts is None:\n\t\t\treturn [];\n\n\t\tfrom google.appengine.api import urlfetch\n\t\tfrom webapp2_extras import json\n\t\turl = 'https://graph.facebook.com/me/friends?fields=name&access_token='+ self.external_accounts.token +\"&locale=ja_JP\"\n\t\tresult = urlfetch.fetch( url )\n\t\tif result.status_code != 200:\n\t\t\tlogging.error( \"tokenが不正です。\"+ result.content )\n\t\t\treturn []\n\t\tresult_obj = json.decode( result.content )\n\n\t\tdata_list = result_obj[\"data\"]\n\n\t\treturn data_list;\n\n\n\n\tdef getNickname( self ):\n\t\tif self.nickname is None:\n\t\t\treturn u\"名無し\"\n\t\telse:\n\t\t\treturn self.nickname;\n\n\n\tdef toDict( self, full=False ):\n\t\tout = self.to_dict( include=[\"nickname\"] )\n\t\t# out = {}\n\t\tout[\"id\"] = str(self.key.id())\n\t\t# Android の UrbanAirship ライブラリに設定するために\n # ua_alias を返す\n\t\tout[\"ua_alias\"] = self.ua_alias\n\n\t\tif self.photo_key:\n\t\t\tphoto = self.photo_key.get();\n\t\t\tout[\"photo\"] = photo.toDict();\n\t\t\tout[\"iconUrl\"] = photo.serving_url\n\n\t\tif full:\n\t\t\tif self.external_accounts is not None:\n\t\t\t\tout[\"external_accounts\"] = self.external_accounts.toDict()\n\n\t\treturn out\n\n\n\nclass PushNotification():\n\n\talert = \"\"\n\tsound = \"\"\n\tbadge = \"\" # \"+1\" を指定すると、相対的に1増やしてくれます。 \n\tparams = {}\n\n\taliases = []\n\tdevice_tokens = []\n\n\tdef __init__( self ):\n\t\tself.aliases = []\n\t\tself.device_tokens = []\n\n\tdef addUser( self, user ):\n\t\t# device_token が ios か android かを保存していないので、 alias で指定する。\n\t\t# alias の登録は ios では push_notification/subscribe で、\n\t\t# android ではクライアント側でおこなっている。\n\t\tif user.device_token:\n\t\t\tself.aliases.append( user.ua_alias )\n\n\tdef addUsers( self, users ):\n\t\tfor user in users:\n\t\t\tself.addUser( user )\n\n\tdef notify( self ):\n\t\t# None を取り除く\n\t\tself.device_tokens = filter(None, self.device_tokens)\n\t\tself.aliases = filter(None, self.aliases)\n\n\t\tif len(self.device_tokens)==0 and len(self.aliases)==0:\n\t\t\tlogging.debug( \"宛先が0件なのでプッシュ通知しません\" )\n\t\t\treturn\n\n\t\tfrom openfish.libs import urbanairship\n\t\timport config\n\t\tairship = urbanairship.Airship( config.URBANAIRSHIP_APP_KEY, config.URBANAIRSHIP_MASTER_SECRET )# 2つ目は master secret\n\t\tpayload = {\n\t\t\t'aps': {\n\t\t\t\t\"badge\": self.badge,\n\t\t\t\t'alert': self.alert,\n\t\t\t\t\"sound\": self.sound,\n\t\t\t},\n\t\t}\n\t\tpayload['android'] = dict(extra={}, **payload['aps'])\n\n\t\t# パラメータを payload に追記\n\t\tfor k, v in self.params.items():\n\t\t\tpayload[k] = v\n\t\t\t# payload['android']['extra'][k] = v\n\n\t\tlogging.info( u\"pushを送信します alert=%s\" % self.alert )\n\t\tlogging.info( u\"payload=%s, device_tokens=%s, aliases=%s\" % ( payload, self.device_tokens, self.aliases ) )\n\t\tairship.push( payload, aliases=self.aliases, device_tokens=self.device_tokens )\n\n\n\n\nclass Email():\n\tsender_address = \"blink support \"\n\tsubject = \"mail subject\"\n\trecipient = \"noughts+gaeMailRecipient@gmail.com\"\n\tbody = \"mail body\"\n\n\t# Send an email to a list of email addresses from your App.\n\t# Email template's body can have dynamic fields wrapped in \"{$ $}\".\n\t# For example, if you want to dynamically provide user name in your email, you can define \"{$ username $}\" in your email template.\n\t@classmethod\n\tdef emailFromTemplate( cls, template, recipient, fromName=\"contact@dividual.jp\", subject=None, **fields ):\n\t\tfrom webapp2_extras import jinja2\n\t\tfrom google.appengine.api import mail\n\n\t\tbody = jinja2.get_jinja2().render_template( template, **fields )\n\t\tmail.send_mail( fromName, recipient, subject, body )\n\n\n\tdef send( self ):\n\t\tfrom google.appengine.api import mail\n\t\tmail.send_mail( self.sender_address, self.recipient, self.subject, self.body )\n\n\n\nclass File( ndb.Model ):\n\tname = ndb.StringProperty()\n\tuser_key = ndb.KeyProperty( kind=User )\n\tblob_key = ndb.BlobKeyProperty()\n\tcreated_at = ndb.DateTimeProperty( auto_now_add=True )\n\n\tdef setBlob( self, bin, mime_type=\"application/octet-stream\" ):\n\t\t# 写真を BlobStore に保存\n\t\tfile_name = files.blobstore.create( mime_type=mime_type )# Create the file\n\t\t# Open the file and write to it\n\t\twith files.open( file_name, 'a' ) as f:\n\t\t\tf.write( bin )\n\t\tfiles.finalize( file_name ) # Finalize the file. Do this before attempting to read it.\n\t\tself.blob_key = files.blobstore.get_blob_key( file_name ) # Get the file's blob key\n\n\n\t# ディクショナリに変換\n\tdef toDict( self ):\n\t\tout = self.to_dict( exclude=[\"blob_key\",\"created_at\",\"user_key\"] )\n\t\tout[\"id\"] = self.key.id()\n\t\tout[\"url\"] = self.getDownloadUrl();\n\n\t\t# user_key からリファレンスを取得\n\t\tif self.user_key:\n\t\t\tuser = self.user_key.get();\n\t\t\tout[\"user\"] = functions.userToDict( user )\n\t\treturn out\n\n\tdef getDownloadUrl( self ):\n\t\tif functions.is_dev():\n\t\t\tport = os.environ[\"SERVER_PORT\"]\n\t\telse:\n\t\t\tport = \"80\"\n\t\treturn \"http://\"+ os.environ['SERVER_NAME'] +\":\"+ port +\"/v1/files/download/\"+ str( self.blob_key );\n\n\n\n\n\n\nclass Photo( BaseModel ):\n\tblob_key = ndb.BlobKeyProperty()\n\tserving_url = ndb.TextProperty() # Picasa インフラの URL\n\n\tdef setBlob( self, bin, mime_type=\"image/jpeg\" ):\n\t\t# 写真を BlobStore に保存\n\t\tfile_name = files.blobstore.create( mime_type=mime_type )# Create the file\n\t\t# Open the file and write to it\n\t\twith files.open( file_name, 'a' ) as f:\n\t\t\tf.write( bin )\n\t\tfiles.finalize( file_name ) # Finalize the file. Do this before attempting to read it.\n\t\tself.blob_key = files.blobstore.get_blob_key( file_name ) # Get the file's blob key\n\n\t\t# Picasa インフラの URL を保存\n\t\tself.serving_url = images.get_serving_url( self.blob_key, secure_url=False )\n\n\n\tdef save( self, bin, mime_type=\"image/jpeg\" ):\n\t\tself.setBlob( bin, mime_type );\n\t\tself.put()\n\n\n\t# ディクショナリに変換\n\tdef toDict( self ):\n\t\t# serving_url が DB に保存されてなかったら保存する\n\t\tif self.serving_url == None:\n\t\t\tself.serving_url = images.get_serving_url( self.blob_key, secure_url=False )\n\t\t\tself.put()\n\n\t\tout = self.to_dict( exclude=[\"blob_key\",\"created_at\",\"user_key\"] )\n\t\tout[\"id\"] = str(self.key.id())\n\n\t\t# ローカルで開発中、192.168.0.10 のように IP でアクセスしたときように、url の「localhost」の部分を置換\n\t\turl_tuple = urlparse.urlparse( out[\"serving_url\"] )\n\t\turl_list = list( url_tuple )\n\t\tif \"localhost\" in url_list[1] or \"192.168.0.10\" in url_list[1]:\n\t\t\turl_list[1] = os.environ['SERVER_NAME'] +\":\"+ os.environ[\"SERVER_PORT\"]\n\t\tserving_url = urlparse.urlunparse(url_list)\n\n\t\tout[\"serving_url\"] = serving_url\n\t\t# out[\"urls\"] = {\n\t\t# \t\"square_100\": serving_url + \"=s100\",\n\t\t# \t\"square_200\": serving_url + \"=s200\",\n\t\t# \t\"square_400\": serving_url + \"=s400\",\n\t\t# }\n\t\treturn out\n\n\n\nclass Place( ndb.Model ):\n\tname = ndb.StringProperty()\n\taddress = ndb.StringProperty()\n\tcity = ndb.StringProperty()\n\tstate = ndb.StringProperty()\n\tpostal_code = ndb.StringProperty()\n\tcountry = ndb.StringProperty()\n\tlatitude = ndb.FloatProperty()\n\tlongitude = ndb.FloatProperty()\n\twebsite = ndb.StringProperty()\n\ttwitter = ndb.StringProperty()\n\tphone_number = ndb.StringProperty()\n\tcustom_fields = ndb.StructuredProperty( CustomField, repeated=False )\n\tapi_type = ndb.StringProperty() # google or yahoo\n\traw_json = ndb.JsonProperty()\n\tphoto_key = ndb.KeyProperty()\n\n\t# put 直後に呼ばれる\n\tdef _post_put_hook( self, hoge ):\n\t\tself.registerFTSIndex();\n\n\n\t# 位置情報を使って半径で検索\n\t@classmethod\n\tdef searchByLocation( cls, latitude, longitude, distance, limit=20 ):\n\t\t# 開発環境だと 2012/08/20現在 FTSによるジオ検索ができないので、暫定的に全件返すようにする\n\t\tif os.environ['SERVER_SOFTWARE'] in ['Development/1.0',\"Development/1.0 (testbed)\"]:\n\t\t\treturn cls.query().fetch()\n\n\n\t\tindex = search.Index(name=\"place\")#インデックスを取得\n\t\t#クエリを作る\n\t\tquery = search.Query(\n\t\t query_string = 'distance(location, geopoint(%f,%f)) < %d' % ( float(latitude), float(longitude), int(distance) ), #サーチクエリー\n\t\t options = search.QueryOptions( limit=limit ), #取得する件数を指定\n\t\t)\n\t\t#検索実行\n\t\tresults = index.search( query )\n\n\t\t# 出力データに追加\n\t\tout = []\n\t\tfor doc in results:\n\t\t\tif doc.doc_id == \"None\":\n\t\t\t\tcontinue\n\t\t\tentity = cls.get_by_id( int(doc.doc_id) )\n\t\t\tif entity:\n\t\t\t\tout.append( entity )\n\t\treturn out\n\t\t\n\n\n\n\t# ディクショナリに変換\n\tdef toDict( self ):\n\t\tout = self.to_dict( exclude=[\"location\",\"location_geocells\"] );\n\t\tout[\"id\"] = self.key.id()\n\t\t\n\t\treturn out\n\n\n\n\t# 全文検索インデックス作成して登録\n\tdef registerFTSIndex( self ):\n\t\tgeopoint = search.GeoPoint( self.latitude, self.longitude )\n\t\tdoc = search.Document(\n\t\t\tdoc_id=str( self.key.id() ),\n\t\t\tlanguage=\"ja\",\n\t\t\tfields=[\n\t\t\t\tsearch.TextField( name=\"name\", value=self.name ),\n\t\t\t\tsearch.TextField( name=\"address\", value=self.address ),\n\t\t\t\tsearch.GeoField( name='location', value=geopoint ),\n\t\t\t]\n\t\t)\n\t\tindex = search.Index( name=\"place\" )\n\t\tindex.add( doc )\n\n\n\t# 全文検索インデックス作成から削除\n\tdef unregisterFTSIndex( self ):\n\t\tindex = search.Index( name=\"place\" )\n\t\tindex.remove( str(self.key.id()) )\n\n\n\n\n\n\n\n\nclass Post( BaseModel ):\n\tcontent = ndb.StringProperty()\n\tphoto_key = ndb.KeyProperty()\n\n\t# ディクショナリに変換\n\tdef toDict( self ):\n\t\tout = self.to_dict( exclude=[\"user_key\"] );\n\t\tout[\"id\"] = self.key.id()\n\n\t\t# user_key からリファレンスを取得\n\t\tif self.user_key:\n\t\t\tuser = self.user_key.get();\n\t\t\tout[\"user\"] = functions.userToDict( user )\n\n\t\treturn out\n\n\n\nclass Comment( BaseModel ):\n\ttarget_key = ndb.KeyProperty()\n\tcontent = ndb.StringProperty()\n\trating = ndb.IntegerProperty()\n\tphoto_key = ndb.KeyProperty()\n\n\t# ディクショナリに変換\n\tdef toDict( self, full=False ):\n\t\tout = self.to_dict( exclude=[\"user_key\",\"target_key\",\"created_at\"] );\n\t\tout[\"id\"] = self.key.id()\n\t\tout[\"created_at\"] = functions.convertDatetimeToJp( self.created_at )\n\n\t\t# user_key からリファレンスを取得\n\t\tif self.user_key:\n\t\t\tuser = self.user_key.get();\n\t\t\tout[\"user\"] = functions.userToDict( user )\n\n\t\treturn out\n\n\n\n\nclass Object( BaseExpandoModel ):\n\tclass_name = ndb.StringProperty()\n\n\t# ディクショナリに変換\n\tdef toDict( self ):\n\t\tout = self.to_dict( exclude=[\"user_key\"] );\n\t\tout[\"id\"] = self.key.id()\n\n\t\t# user_key からリファレンスを取得\n\t\tif self.user_key:\n\t\t\tuser = self.user_key.get();\n\t\t\tout[\"user\"] = functions.userToDict( user )\n\n\t\treturn out\n\n\n\n\n# ----------------------------------------------------------------------\n# \n# カスタムモデル( オリジナルの Cocoafisn にはないけど、汎用的にあったら便利なモデル )\n# \n# ----------------------------------------------------------------------\n\n\n# In App Purchase のトランザクション\nclass IAPTransaction( BaseModel ):\n\treceipt = ndb.TextProperty()\n\tverifiedData = ndb.JsonProperty();\n\n\t# レシートデータをベリファイします。\n\t# 正しいレシートなら True\n\t# 間違ったレシート、もしくはすでにベリファイ済みなら False を返します。\n\tdef verify( self ):\n\t\tfrom google.appengine.api import urlfetch\n\n\t\tif self.verifiedData is not None:\n\t\t\tlogging.error( \"%sはすでにベリファイ済みです。\" %( self.key ) )\n\t\t\treturn False\n\n\t\tdata = '{\"receipt-data\" : \"%s\"}' % (self.receipt)\n\t\tlogging.info( \"本番 itunes.apple.com でレシート検証します。\" )\n\t\tresult = urlfetch.fetch( \"https://buy.itunes.apple.com/verifyReceipt\", payload=data, method=urlfetch.POST, validate_certificate=False )\n\t\tcontent = json.loads( result.content )\n\t\tlogging.info( content )\n\n\t\tif content[\"status\"]==21007: # サンドボックスのレシートを本番で検証しようとすると、status=21007が返ってきます。\n\t\t\tlogging.info( \"サンドボックス itunes.apple.com でレシート検証します。\" )\n\t\t\tresult = urlfetch.fetch( \"https://sandbox.itunes.apple.com/verifyReceipt\", payload=data, method=urlfetch.POST, validate_certificate=False )\n\t\t\tcontent = json.loads( result.content )\n\t\t\tlogging.info( content )\n\n\t\tself.verifiedData = content\n\t\tself.put()\n\t\tif content[\"status\"]==0:\n\t\t\treturn True # verify成功\n\n\t\treturn False\n\n\n\n\n\n\n\n\n\n# ブラックリスト\n# IPを登録すると、POST系ができなくなる\nclass BlackList( ndb.Model ):\n\tip = ndb.StringProperty()\n\tudid = ndb.StringProperty()\n\n\t# バンされている?\n\t@classmethod\n\tdef checkBanned( cls ):\n\t\treq = webapp2.get_request()\n\t\tudid = req.get(\"udid\")\n\n\t\t# unittest 時にはスキップ\n\t\tif hasattr( os.environ, \"REMOTE_ADDR\" ) == False:\n\t\t\treturn False\n\t\tremoteAddress = os.environ['REMOTE_ADDR']\n\t\tquery = cls.query( ndb.query.OR(cls.ip==remoteAddress, cls.udid==udid) )\n\t\tif query.get():\n\t\t\tlogging.info( \"BlackList access from banned user ip=\"+ remoteAddress +\" or udid=\"+ udid )\n\t\t\treturn True\n\t\telse:\n\t\t\treturn False \n\n\n\nclass Like( BaseModel ):\n\ttarget_key = ndb.KeyProperty()\n\tcontent = ndb.StringProperty()\n\n\t# Likeできる?\n\t@classmethod\n\tdef checkAvailability( cls, user_key, target_key ):\n\t\tquery = cls.query( cls.target_key==target_obj.key, cls.user_key==self.user.key, cls.is_deleted==False )\n\t\tif query.get():\n\t\t\treturn False\n\t\telse:\n\t\t\treturn True\n\n\t# ディクショナリに変換\n\tdef toDict( self, full=False ):\n\t\tout = self.to_dict( exclude=[\"user_key\",\"target_key\",\"created_at\"] );\n\t\tout[\"id\"] = self.key.id()\n\n\t\t# user_key からリファレンスを取得\n\t\tuser = self.user_key.get();\n\t\tout[\"user\"] = functions.userToDict( user )\n\n\t\treturn out\n\n\n\n\n# 通報\nclass Report( BaseModel ):\n\ttarget_key = ndb.KeyProperty()\n\n\t# ディクショナリに変換\n\tdef toDict( self, full=False ):\n\t\tout = self.to_dict( exclude=[\"user_key\",\"target_key\",\"created_at\"] );\n\t\tout[\"id\"] = self.key.id()\n\t\treturn out\n\n\n\n\n\n\n","sub_path":"models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":23434,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"133308555","text":"import pygame\n\nclass AnimateSprite(pygame.sprite.Sprite):\n def __init__(self, sprite_name):\n super().__init__()\n self.image = pygame.image.load(f'assets/{sprite_name}.png')\n self.current_image = 0\n self.images = animations.get(sprite_name)\n self.animation = False\n # def methode poyur demarer anilatiuon\n def start_animation(self):\n self.animation = True\n\n def animate(self, loop=False):\n if self.animation:\n self.current_image += 1 # iamge suivant\n # vifier si on attein la fin\n if self.current_image >= len(self.images):\n self.current_image=0\n if loop is False:\n self.animation= False\n # modifier limage prec par la suivante\n self.image = self.images[self.current_image]\n\n\n\n# un fonction pour charger les image d'un sprite\ndef load_animation_images(sprite_name):\n # charge de l'image\n images = []\n # recupere le dossier des images\n path = f\"assets/{sprite_name}/{sprite_name}\"\n #boucler dans ce dosier\n for num in range(1,24):\n image_path = f\"{path}{num}.png\"\n images.append(pygame.image.load(image_path))\n # revoyer le contenu de la liste d'image\n return images\n\n# dictionaire d'image pour chaque sprite\n# mummy -> [....] no images\n\nanimations = {}","sub_path":"animation.py","file_name":"animation.py","file_ext":"py","file_size_in_byte":1355,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"589054044","text":"from pathlib import Path\nfrom unittest import TestCase\n\nfrom app.utils.zip_utils import check_if_zipped\n\n\nclass ZipUtilsTest(TestCase):\n def setUp(self):\n self.base_path = Path.cwd() / \"test_rosters\"\n self.zipped_kill_team_roster = str(\n self.base_path / \"zipped_rosters\" / \"elite_roster.rosz\"\n )\n self.unzipped_kill_team_roster = str(\n self.base_path / \"kill_team\" / \"elite_roster.ros\"\n )\n\n async def test__zipped_roster(self):\n roster_file = await check_if_zipped(self.zipped_kill_team_roster)\n self.assertTrue(roster_file)\n\n async def test__unzipped_roster_is_formatted_correctly(self):\n roster_file = await check_if_zipped(self.zipped_kill_team_roster)\n\n self.assertEqual(self.zipped_kill_team_roster, roster_file)\n","sub_path":"app/utils/zip_utils_test.py","file_name":"zip_utils_test.py","file_ext":"py","file_size_in_byte":813,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"286894467","text":"import pandas as pd\r\nimport matplotlib.pyplot as plt\r\nimport numpy as np\r\n\r\n'''Aqui iremos fazer o histograma do refino de outras cargas entre os estados, nos anos de 1990 a 2018 '''\r\n\r\ndados = pd.read_csv('processamento-petroleo-m3-1990-2018.csv', sep = ';', decimal = ',', encoding = 'utf-8')\r\n\r\n#Separaremos o refino total de outras cargas derivadas do petróleo por estado, colocando em listas\r\noutros_am, outros_ba, outros_ce, outros_mg, outros_pr, outros_pe, outros_rj, outros_rn, outros_rs, outros_sp = ([] for i in range(10))\r\n\r\n#Aqui está uma estrutura de laço para separar cada estado refinador nas suas respectivas listas\r\nfor index, column in dados.iterrows():\r\n if column['ESTADO'] == 'AMAZONAS' and column['MATÉRIA PRIMA'] == 'OUTRAS CARGAS ':\r\n ama = column['TOTAL'], column['ANO']\r\n outros_am.append(ama)\r\n elif column['ESTADO'] == 'BAHIA' and column['MATÉRIA PRIMA'] == 'OUTRAS CARGAS':\r\n bah = column['TOTAL'], column['ANO']\r\n outros_ba.append(bah)\r\n elif column['ESTADO'] == 'CEARÁ' and column['MATÉRIA PRIMA'] == 'OUTRAS CARGAS ':\r\n cea = column['TOTAL'], column['ANO']\r\n outros_ce.append(cea)\r\n elif column['ESTADO'] == 'MINAS GERAIS' and column['MATÉRIA PRIMA'] == 'OUTRAS CARGAS ':\r\n mgs = column['TOTAL'], column['ANO']\r\n outros_mg.append(mgs)\r\n elif column['ESTADO'] == 'PARANÁ' and column['MATÉRIA PRIMA'] == 'OUTRAS CARGAS ':\r\n par = column['TOTAL'], column['ANO']\r\n outros_pr.append(par)\r\n elif column['ESTADO'] == 'PERNAMBUCO' and column['MATÉRIA PRIMA'] == 'OUTRAS CARGAS ':\r\n per = column['TOTAL'], column['ANO']\r\n outros_pe.append(per)\r\n elif column['ESTADO'] == 'RIO DE JANEIRO' and column['MATÉRIA PRIMA'] == 'OUTRAS CARGAS ':\r\n rjn = column['TOTAL'], column['ANO']\r\n outros_rj.append(rjn)\r\n elif column['ESTADO'] == 'RIO GRANDE DO NORTE' and column['MATÉRIA PRIMA'] == 'OUTRAS CARGAS ':\r\n rnn = column['TOTAL'], column['ANO']\r\n outros_rn.append(rnn)\r\n elif column['ESTADO'] == 'RIO GRANDE DO SUL' and column['MATÉRIA PRIMA'] == 'OUTRAS CARGAS ':\r\n rss = column['TOTAL'], column['ANO']\r\n outros_rs.append(rss)\r\n elif column['ESTADO'] == 'SÃO PAULO' and column['MATÉRIA PRIMA'] == 'OUTRAS CARGAS':\r\n sao = column['TOTAL'], column['ANO']\r\n outros_sp.append(sao)\r\n\r\n#Criação de uma função para o novo dataframe com a soma de todo o refino estadual anual\r\ndef dataframe(x):\r\n x = pd.DataFrame(list(x))\r\n x.columns = ['TOTAL (m³)', 'ANO']\r\n x = x.groupby(['ANO'])['TOTAL (m³)'].sum().to_frame().reset_index()\r\n return x\r\n\r\n#Transformando as novas listas em dataframes\r\noutros_am = dataframe(outros_am)\r\noutros_ba = dataframe(outros_ba)\r\noutros_ce = dataframe(outros_ce)\r\noutros_mg = dataframe(outros_mg)\r\noutros_pr = dataframe(outros_pr)\r\noutros_pe = dataframe(outros_pe)\r\noutros_rj = dataframe(outros_rj)\r\noutros_rn = dataframe(outros_rn)\r\noutros_rs = dataframe(outros_rs)\r\noutros_sp = dataframe(outros_sp)\r\n\r\n#Criação de uma função para gerar o gráfico com a soma de todo o refino de outras cargas estadual anual\r\ndef histograma(x):\r\n plt.figure(figsize = (10, 5))\r\n plt.xticks(x['ANO'], rotation = 'vertical')\r\n plt.xlabel('Refino Outras Cargas Anual')\r\n plt.ylabel('Total Refino Anual (m³)')\r\n if x is outros_am:\r\n plt.bar(x.iloc[:, 0], x.iloc[:, 1], color = 'blue')\r\n plt.title('Processo de refino de outras cargas no estado da Amazonas')\r\n elif x is outros_ba:\r\n plt.bar(x.iloc[:, 0], x.iloc[:, 1], color = 'red')\r\n plt.title('Processo de refino de outras cargas no estado da Bahia')\r\n elif x is outros_ce:\r\n plt.bar(x.iloc[:, 0], x.iloc[:, 1], color = 'yellow')\r\n plt.title('Processo de refino de outras cargas no estado do Ceará')\r\n elif x is outros_mg:\r\n plt.bar(x.iloc[:, 0], x.iloc[:, 1], color = 'green')\r\n plt.title('Processo de refino de outras cargas no estado de Minas Gerais')\r\n elif x is outros_pe:\r\n plt.bar(x.iloc[:, 0], x.iloc[:, 1], color = 'brown')\r\n plt.title('Processo de refino de outras cargas no estado de Pernambuco')\r\n elif x is outros_pr:\r\n plt.bar(x.iloc[:, 0], x.iloc[:, 1], color = 'pink')\r\n plt.title('Processo de refino de outras cargas no estado do Paraná')\r\n elif x is outros_rj:\r\n plt.bar(x.iloc[:, 0], x.iloc[:, 1], color = 'purple')\r\n plt.title('Processo de refino de outras cargas no estado do Rio de Janeiro')\r\n elif x is outros_rn:\r\n plt.bar(x.iloc[:, 0], x.iloc[:, 1], color = 'orange')\r\n plt.title('Processo de refino de outras cargas no estado do Rio Grande do Norte')\r\n elif x is outros_rs:\r\n plt.bar(x.iloc[:, 0], x.iloc[:, 1], color = 'black')\r\n plt.title('Processo de refino de outras cargas no estado do Rio Grande do Sul')\r\n else:\r\n plt.bar(x.iloc[:, 0], x.iloc[:, 1], color = 'cyan')\r\n plt.title('Processo de refino de outras cargas no estado de São Paulo')\r\n\r\n#Visualização dos histogramas de cada região\r\nhistograma(outros_am)\r\nhistograma(outros_ba)\r\nhistograma(outros_ce)\r\nhistograma(outros_mg)\r\nhistograma(outros_pe)\r\nhistograma(outros_pr)\r\nhistograma(outros_rj)\r\nhistograma(outros_rn)\r\nhistograma(outros_rs)\r\nhistograma(outros_sp) \r\n\r\n#Fazendo o gráfico para os estados refinadores de petróleo nacional\r\nbarWidth = 0.1\r\nplt.figure(figsize = (15, 5))\r\nr1 = np.arange(len(outros_am.iloc[:, 0]))\r\nr2 = [x + barWidth for x in r1]\r\nr3 = [x + barWidth for x in r2]\r\nr4 = [x + barWidth for x in r3]\r\nr5 = [x + barWidth for x in r4]\r\nr6 = [x + barWidth for x in r5]\r\nr7 = [x + barWidth for x in r6]\r\nr8 = [x + barWidth for x in r7]\r\nr9 = [x + barWidth for x in r8]\r\nr10 = [x + barWidth for x in r9]\r\nplt.bar(r1, outros_am.iloc[:, 1], width = barWidth, color = '#4B0082', label = 'AM')\r\nplt.bar(r2, outros_ba.iloc[:, 1], width = barWidth, color = '#9400D3', label = 'BA')\r\nplt.bar(r3, outros_ce.iloc[:, 1], width = barWidth, color = '#9932CC', label = 'CE')\r\nplt.bar(r4, outros_mg.iloc[:, 1], width = barWidth, color = '#BA55D3', label = 'MG') \r\nplt.bar(r5, outros_pe.iloc[:, 1], width = barWidth, color = '#800080', label = 'PE')\r\nplt.bar(r6, outros_pr.iloc[:, 1], width = barWidth, color = '#8B008B', label = 'PR')\r\nplt.bar(r7, outros_rj.iloc[:, 1], width = barWidth, color = '#FF00FF', label = 'RJ')\r\nplt.bar(r8, outros_rn.iloc[:, 1], width = barWidth, color = '#EE82EE', label = 'RN')\r\nplt.bar(r9, outros_rs.iloc[:, 1], width = barWidth, color = '#DA70D6', label = 'RS')\r\nplt.bar(r10, outros_sp.iloc[:, 1], width = barWidth, color = '#DDA0DD', label = 'SP')\r\nplt.xlabel('Produção Anual')\r\nplt.xticks([r + barWidth for r in range(len(outros_am.iloc[:, 0]))], outros_am['ANO'], rotation = 'vertical')\r\nplt.ylabel('Total Produção Anual (m³)')\r\nplt.title('Refino de outras cargas nos estados brasileiros')\r\nplt.legend(loc = 'upper left')\r\nplt.show()\r\n","sub_path":"histograma refino petroleo outras cargas (1990 - 2018) (estado).py","file_name":"histograma refino petroleo outras cargas (1990 - 2018) (estado).py","file_ext":"py","file_size_in_byte":6946,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"516507881","text":"# -*- coding: utf-8\nimport time\nimport random\nfrom selenium import webdriver\nfrom selenium.webdriver.chrome.options import Options\nfrom sys_info import *\n\n#持续拷机测试\noptions = Options()\noptions.add_argument(\"--kiosk\") # 加载启动项页面全屏效果,相当于F11。\noptions.add_experimental_option(\"excludeSwitches\", ['enable-automation']) # 禁止谷歌弹出正在被自动化软件控制消息\ndriver = webdriver.Chrome(r\"E:\\lijie\\chromedriver.exe\", 0, options=options,keep_alive=True)\ndriver.get(\"http://192.168.7.7/ers-web/#/\")\n#driver.maximize_window()\n#driver.get(\"https://dolphin-dev.kedacom.com/ers-web/#/\")\ntime.sleep(10)\ndriver.find_element_by_xpath(\"//div/div[2]/form/div[1]/div/div[1]/input\").send_keys(\"kunming001\")\ndriver.find_element_by_xpath(\"//div/div[2]/form/div[2]/div/div[1]/input\").send_keys(\"keda123!\")\ntime.sleep(2)\ndriver.find_element_by_css_selector(\"#keybtn\").click()\ntime.sleep(5)\nall_handles = driver.window_handles\ndriver.switch_to.window(all_handles[-1])\ndriver.maximize_window()\ntime.sleep(8)\ni = 1\nwhile (i < 100000000):\n #j = random.randint(10000,50000)\n driver.find_element_by_xpath(\"/html/body/div[1]/div/div[1]/div/div/div[2]/ul/li[2]/span[2]\").click()\n time.sleep(5)\n for j in range(1,10):\n driver.find_element_by_xpath(\"/html/body/div[1]/div/div[2]/div/div[2]/div/div[1]/div/div[1]/div/div[2]/div/div/div[2]/div/div[\"+str(j)+\"]/div/div[1]/label\").click()\n time.sleep(5)\n #driver.find_element_by_xpath(\"/html/body/div[1]/div/div[1]/div/div/div[2]/ul/li[1]/span[2]\").click() #\n #time.sleep(1)\n print(i)\n print(\"cpu利用率: \" + str(get_cpu_info())+\"%\")\n print(get_memory_info())\n i = i + 1\nprint(\"1亿次新建警情立案结束了\")\ndriver.quit()\n","sub_path":"UItest/Case/接处警2.0/处警页面灾情切换.py","file_name":"处警页面灾情切换.py","file_ext":"py","file_size_in_byte":1766,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"448125454","text":"#!/usr/bin/env python3\n\n\nimport sys\n\n\ndef fib(n):\n\ta,b = 1,1\n\tfor i in range(n-1):\n\t\ta,b = b,a+b\n\tprint('n: {}, a: {}'.format(n, a))\n\treturn a\n\n\ndef main():\n try:\n arg1 = int(sys.argv[1])\n \tprint(fib(arg1))\n except:\n print('Try entering a number, genius')\n\n\nif __name__ == '__main__':\n main()\n\n\n\n# print fib(50)","sub_path":"Academia/Fibonacci/fibloop.py","file_name":"fibloop.py","file_ext":"py","file_size_in_byte":340,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"316876272","text":"import torch\nimport torch.nn as nn\nimport spconv\n\nfrom lib.pointgroup_ops.functions import pointgroup_ops\nfrom util import utils\nfrom model.components import UBlock\nfrom model.basemodel import BaseModel\n\n\nclass OccuSeg(BaseModel):\n def __init__(self, cfg):\n super().__init__(cfg)\n\n self.occupancy_cluster = cfg.occupancy_cluster\n\n self.input_conv = spconv.SparseSequential(\n spconv.SubMConv3d(self.input_c, self.m, kernel_size=3, padding=1, bias=False, indice_key='subm1')\n )\n\n self.unet = UBlock(\n [self.m, 2 * self.m, 3 * self.m, 4 * self.m, 5 * self.m, 6 * self.m, 7 * self.m], self.norm_fn,\n self.block_reps, self.block, indice_key_id=1, backbone=True, UNet_Transformer=cfg.UNet_Transformer\n )\n\n self.output_layer = spconv.SparseSequential(\n self.norm_fn(self.m),\n nn.ReLU()\n )\n\n self.point_offset = nn.Sequential(\n nn.Linear(self.m, self.m, bias=True),\n self.norm_fn(self.m),\n nn.ReLU(),\n nn.Linear(self.m, 3, bias=True),\n )\n\n self.point_semantic = nn.Sequential(\n nn.Linear(self.m, self.m, bias=True),\n self.norm_fn(self.m),\n nn.ReLU(),\n nn.Linear(self.m, self.classes, bias=True),\n )\n\n self.point_occupancy = nn.Sequential(\n nn.Linear(self.m, self.m, bias=True),\n self.norm_fn(self.m),\n nn.ReLU(),\n nn.Linear(self.m, 1, bias=True),\n )\n\n #### score branch\n self.score_unet = UBlock([self.m, 2 * self.m], self.norm_fn, 2, self.block, indice_key_id=1, backbone=False)\n self.score_outputlayer = spconv.SparseSequential(\n self.norm_fn(self.m),\n nn.ReLU()\n )\n self.score_linear = nn.Linear(self.m, 1)\n\n self.apply(self.set_bn_init)\n\n self.module_map = {\n 'input_conv': self.input_conv,\n 'unet': self.unet,\n 'output_layer': self.output_layer,\n 'score_unet': self.score_unet,\n 'score_outputlayer': self.score_outputlayer,\n 'score_linear': self.score_linear,\n }\n\n self.local_pretrained_model_parameter()\n\n def forward(self, input, input_map, coords, rgb, ori_coords, batch_idxs, batch_offsets, epoch):\n '''\n :param input_map: (N), int, cuda\n :param coords: (N, 3), float, cuda\n :param batch_idxs: (N), int, cuda\n :param batch_offsets: (B + 1), int, cuda\n '''\n ret = {}\n\n batch_idxs = batch_idxs.squeeze()\n\n semantic_scores = []\n point_offset_preds = []\n voxel_occupancy_preds = []\n\n voxel_feats = pointgroup_ops.voxelization(input['pt_feats'], input['v2p_map'], input['mode']) # (M, C), float, cuda\n\n input_ = spconv.SparseConvTensor(\n voxel_feats, input['voxel_coords'], input['spatial_shape'], input['batch_size']\n )\n output = self.input_conv(input_)\n output = self.unet(output)\n output = self.output_layer(output)\n output_feats = output.features[input_map.long()]\n output_feats = output_feats.squeeze(dim=0)\n\n ### point prediction\n #### point semantic label prediction\n semantic_scores.append(self.point_semantic(output_feats)) # (N, nClass), float\n\n ### only used to evaluate based on ground truth\n # semantic_scores.append(input['point_semantic_scores'][0]) # (N, nClass), float\n ### ground truth for each category\n # CATE_NUM = 0\n # semantic_output = self.point_semantic(output_feats)\n # if (input['point_semantic_scores'][0].max(dim=1)[1] == CATE_NUM).sum() > 0:\n # semantic_output[input['point_semantic_scores'][0].max(dim=1)[1] == CATE_NUM] = \\\n # input['point_semantic_scores'][0][input['point_semantic_scores'][0].max(dim=1)[1] == CATE_NUM].float()\n # semantic_output[semantic_output.max(dim=1)[1] == CATE_NUM] = \\\n # input['point_semantic_scores'][0][semantic_output.max(dim=1)[1] == CATE_NUM].float()\n # semantic_scores.append(semantic_output)\n\n point_semantic_preds = semantic_scores[0].max(1)[1]\n\n #### point offset prediction\n point_offset_pred = self.point_offset(output_feats)\n point_offset_preds.append(point_offset_pred) # (N, 3), float32\n # only used to evaluate based on ground truth\n # point_offset_preds.append(input['point_offset_preds']) # (N, 3), float32\n\n voxel_occupancy_preds.append(self.point_occupancy(output.features))\n point_occupancy_pred = voxel_occupancy_preds[0][input_map.long()].squeeze(dim=1)\n\n if (epoch > self.prepare_epochs):\n #### get prooposal clusters\n object_idxs = torch.nonzero(point_semantic_preds > 1).view(-1)\n\n batch_idxs_ = batch_idxs[object_idxs]\n batch_offsets_ = utils.get_batch_offsets(batch_idxs_, input['batch_size'])\n coords_ = coords[object_idxs]\n pt_offsets_ = point_offset_preds[0][object_idxs]\n point_occupancy_pred_ = point_occupancy_pred[object_idxs]\n\n semantic_preds_cpu = point_semantic_preds[object_idxs].int().cpu()\n\n # idx_occupancy, start_len_occupancy = pointgroup_ops.ballquery_batch_p(\n # coords_ + pt_offsets_, batch_idxs_,\n # batch_offsets_, self.cluster_radius, self.cluster_shift_meanActive\n # )\n # proposals_idx_occupancy, proposals_offset_occupancy = pointgroup_ops.bfs_occupancy_cluster(\n # semantic_preds_cpu, point_occupancy_pred_.cpu(), idx_occupancy.cpu(),\n # start_len_occupancy.cpu(), self.cluster_npoint_thre, self.occupancy_cluster['occupancy_threshold_shift']\n # )\n # proposals_idx_occupancy[:, 1] = object_idxs[proposals_idx_occupancy[:, 1].long()].int()\n # # proposals_idx_shift: (sumNPoint, 2), int, dim 0 for cluster_id, dim 1 for corresponding point idxs in N\n # # proposals_offset_shift: (nProposal + 1), int\n #\n # idx, start_len = pointgroup_ops.ballquery_batch_p(\n # coords_, batch_idxs_, batch_offsets_, self.cluster_radius, self.cluster_meanActive\n # )\n # proposals_idx, proposals_offset = pointgroup_ops.bfs_occupancy_cluster(\n # semantic_preds_cpu, point_occupancy_pred_.cpu(), idx.cpu(),\n # start_len.cpu(), self.cluster_npoint_thre, self.occupancy_cluster['occupancy_threshold']\n # )\n # proposals_idx[:, 1] = object_idxs[proposals_idx[:, 1].long()].int()\n\n\n idx, start_len = pointgroup_ops.ballquery_batch_p(\n coords_, batch_idxs_, batch_offsets_, self.cluster_radius, self.cluster_meanActive\n )\n proposals_idx, proposals_offset = pointgroup_ops.bfs_cluster(\n semantic_preds_cpu, idx.cpu(), start_len.cpu(), self.cluster_npoint_thre\n )\n proposals_idx[:, 1] = object_idxs[proposals_idx[:, 1].long()].int()\n\n\n idx_shift, start_len_shift = pointgroup_ops.ballquery_batch_p(\n coords_ + pt_offsets_, batch_idxs_,\n batch_offsets_, self.cluster_radius, self.cluster_shift_meanActive\n )\n proposals_idx_shift, proposals_offset_shift = pointgroup_ops.bfs_cluster(\n semantic_preds_cpu, idx_shift.cpu(), start_len_shift.cpu(), self.cluster_npoint_thre\n )\n proposals_idx_shift[:, 1] = object_idxs[proposals_idx_shift[:, 1].long()].int()\n # proposals_idx_shift: (sumNPoint, 2), int, dim 0 for cluster_id, dim 1 for corresponding point idxs in N\n # proposals_offset_shift: (nProposal + 1), int\n\n # proposals_idx_occupancy[:, 0] += (proposals_offset.size(0) - 1)\n # proposals_offset_occupancy += proposals_offset[-1]\n # proposals_idx = torch.cat((proposals_idx, proposals_idx_occupancy), dim=0)\n # proposals_offset = torch.cat((proposals_offset, proposals_offset_occupancy[1:]))\n\n # proposals_idx_filtered = []\n # proposals_offset_filtered = [0]\n # for proposal in proposals_idx_shift[:, 0].unique():\n # proposal_index = proposals_idx_shift[:, 0] == proposal\n # proposal_idxs = proposals_idx_shift[proposal_index, 1].long()\n # proposals_indexs = proposals_idx_shift[proposal_index, :]\n #\n # proposal_occupancy_mean = point_occupancy_pred[proposal_idxs].mean()\n #\n # valid_point_index = torch.ones_like(proposal_idxs).byte()\n # valid_point_index[point_occupancy_pred[proposal_idxs] < proposal_occupancy_mean *\n # (1 - self.occupancy_cluster['occupancy_filter_threshold'])] = 0\n # valid_point_index[point_occupancy_pred[proposal_idxs] > proposal_occupancy_mean *\n # (1 + self.occupancy_cluster['occupancy_filter_threshold'])] = 0\n # proposal_idx_filtered = proposals_indexs[valid_point_index, :]\n #\n # proposals_idx_filtered.append(proposal_idx_filtered)\n # proposals_offset_filtered.append(proposals_offset_filtered[-1] + proposal_idx_filtered.shape[0])\n #\n # proposals_idx_filtered = torch.cat(proposals_idx_filtered, dim=0)\n # proposals_offset_filtered = torch.tensor(proposals_offset_filtered).int()\n # proposals_idx_shift = proposals_idx_filtered\n # proposals_offset_shift = proposals_offset_filtered\n\n proposals_idx_shift[:, 0] += (proposals_offset.size(0) - 1)\n proposals_offset_shift += proposals_offset[-1]\n proposals_idx = torch.cat((proposals_idx, proposals_idx_shift), dim=0)\n proposals_offset = torch.cat((proposals_offset, proposals_offset_shift[1:]))\n\n #### proposals voxelization again\n input_feats, inp_map = self.clusters_voxelization(proposals_idx, proposals_offset, output_feats, coords,\n self.score_fullscale, self.score_scale, self.mode)\n\n #### score\n score = self.score_unet(input_feats)\n score = self.score_outputlayer(score)\n score_feats = score.features[inp_map.long()] # (sumNPoint, C)\n score_feats = pointgroup_ops.roipool(score_feats, proposals_offset.cuda()) # (nProposal, C)\n scores = self.score_linear(score_feats) # (nProposal, 1)\n\n # proposals_idx = proposals_idx_occupancy\n # proposals_offset = proposals_offset_occupancy\n # scores = torch.ones(proposals_offset.shape[0] - 1, 1).to(point_offset_preds[0].device)\n\n ret['proposal_scores'] = (scores, proposals_idx, proposals_offset)\n\n ret['point_semantic_scores'] = semantic_scores\n ret['point_offset_preds'] = point_offset_preds\n ret['point_features'] = output_feats\n ret['voxel_occupancy_preds'] = voxel_occupancy_preds\n\n return ret\n","sub_path":"model/reproduced_methods/occuseg.py","file_name":"occuseg.py","file_ext":"py","file_size_in_byte":11172,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"113716956","text":"\"\"\"\nDescription:\nGiven an array with n objects colored red, white or blue, sort them so that objects of the same color are adjacent, with the colors in the order red, white and blue.\n\nHere, we will use the integers 0, 1, and 2 to represent the color red, white, and blue respectively.\n\nNote:\nYou are not suppose to use the library's sort function for this problem.\n\"\"\"\n\n\nclass Solution(object):\n def sortColors(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: void Do not return anything, modify nums in-place instead.\n \"\"\"\n # two passes\n color = dict()\n color[0] = color[1] = color[2] = 0\n for i in nums:\n color[i] += 1\n\n for j in range(len(nums)):\n if color[0]>0:\n nums[j] = 0\n color[0] -= 1\n elif color[1]>0:\n nums[j] = 1\n color[1] -= 1\n else:\n nums[j] = 2\n color[2] -= 1\n\n\nif __name__ == '__main__':\n sol = Solution()\n nums = [1, 2, 0, 2, 1, 1, 0]\n res = [0, 0, 1, 1, 1, 2, 2]\n sol.sortColors(nums)\n assert nums == res\n","sub_path":"75_SortColors.py","file_name":"75_SortColors.py","file_ext":"py","file_size_in_byte":1139,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"251408412","text":"from rdapp.camera import Camera\r\nfrom rdapp.track import Track\r\nfrom rdapp import utils\r\nimport numpy as np\r\nfrom PyQt5 import QtCore\r\nimport os\r\n\r\nclass Project:\r\n def __init__(self, app):\r\n self.app = app\r\n pass\r\n\r\n def save(self):\r\n out = {}\r\n out[\"play\"] = self.play\r\n out[\"time\"] = self.time\r\n out[\"fps\"] = self.fps\r\n out[\"camera\"] = list(self.camera.get())\r\n out[\"texture\"] = self.texture\r\n out[\"audio\"] = self.audio\r\n out[\"values\"] = {}\r\n for val in self.values:\r\n out[\"values\"][val] = self.values[val].save()\r\n out[\"code\"] = self.code.code\r\n out[\"script\"] = self.script\r\n return out\r\n\r\n @staticmethod\r\n def load(app, data):\r\n project = Project(app)\r\n project.play = data[\"play\"]\r\n project.time = data[\"time\"]\r\n project.fps = data[\"fps\"]\r\n project.camera = Camera(data[\"camera\"])\r\n project.texture = data[\"texture\"]\r\n project.audio = data[\"audio\"]\r\n project.values = {}\r\n for val in data[\"values\"]:\r\n project.values[val] = Value.load(project, data[\"values\"][val])\r\n project.code = CodeInfo(data[\"code\"])\r\n project.script = data[\"script\"]\r\n project.backup_code = None\r\n project.backup_values = None\r\n project.create_values()\r\n return project\r\n\r\n @staticmethod\r\n def default(app, resources):\r\n project = Project(app)\r\n project.play = True\r\n project.time = 0\r\n project.fps = 30\r\n\r\n project.camera = Camera()\r\n project.camera.translate(0, 0, -3)\r\n\r\n project.texture = os.path.join(os.getcwd(), resources, \"default.jpg\")\r\n project.audio = \"\"\r\n\r\n project.values = {}\r\n\r\n project.code = CodeInfo(\"\"\"uniform float Size;\\nuniform bool Mirror;\\n\\nRay camera() {\\n\\treturn camPerspective(1.0);\\n}\\nvec3 distort(vec3 p) {\\n\\tif (Mirror) p = opMirror(p, 0.1);\\n\\treturn distortSin(p, 0.5, 1.5, vec3(time, 0.0, 0.0));\\n}\\nfloat map(vec3 p) {\\n\\treturn sdSphere(distort(p), 1.0 + Size);\\n}\\nvec4 display(float depth, float dist, vec3 pos, vec3 norm) {\\n\\tif (dist >= RM_STOP_DIST) {\\n\\t\\treturn vec4(0.0);\\n\\t} else {\\n\\t\\treturn sample(ctob(distort(pos)));\\n\\t}\\n}\"\"\")\r\n\r\n project.script = \"\"\"\r\nprint(\"Hello rdapp!\")\\n\\ndef update(dt):\\n\\tpass\r\n \"\"\"\r\n\r\n project.backup_code = None\r\n project.backup_values = None\r\n\r\n project.create_values()\r\n return project\r\n\r\n\r\n def create_values(self):\r\n new_vals = {}\r\n for u in self.code.uniforms:\r\n if not u.name in self.values or self.values[u.name].type != u.type:\r\n new_vals[u.name] = Value(self, u.name, u.type, u.ndim)\r\n else:\r\n new_vals[u.name] = self.values[u.name]\r\n self.values = new_vals\r\n\r\n def get_uniforms(self):\r\n uniforms = {\r\n \"time\": self.time,\r\n \"fps\": self.fps,\r\n \"camera_mat\": self.camera.get(),\r\n \"sound\": self.app.sound\r\n }\r\n for val in self.values:\r\n uniforms[val] = self.values[val].get_uniform()\r\n return uniforms\r\n\r\n def restore_code(self):\r\n self.code = self.backup_code\r\n self.values = self.backup_values\r\n\r\n def set_code(self, code):\r\n self.backup_code = self.code\r\n self.backup_values = self.values\r\n self.code = CodeInfo(code)\r\n self.create_values()\r\n\r\n def set_frame(self, frame):\r\n self.time = frame/self.fps\r\n\r\n def get_frame(self):\r\n return self.time * self.fps\r\n\r\n def set_time(self, time):\r\n self.time = time\r\n\r\n def get_time(self):\r\n return self.time\r\n\r\n def set_fps(self, fps):\r\n self.fps = fps\r\n\r\n def get_fps(self):\r\n return self.fps\r\n\r\n\r\nclass Value:\r\n def __init__(self, project, name, type, ndim, base=None, track=None, use_track=None):\r\n self._project = project\r\n self._name = name\r\n self.type = type\r\n self.ndim = ndim\r\n if base:\r\n self.set_base(base)\r\n else:\r\n self.set_base(self.default_base())\r\n if track:\r\n self._track = track\r\n else:\r\n self._track = self.default_track()\r\n if use_track is not None:\r\n self._use_track = use_track\r\n else:\r\n self._use_track = (type == \"float\" and ndim == 1)\r\n\r\n def process(self, val):\r\n if self.ndim == 1:\r\n if self.type == \"float\":\r\n return float(val)\r\n if self.type == \"int\":\r\n return int(val)\r\n return val\r\n if self.type == \"float\":\r\n return np.float64(val)\r\n if self.type == \"int\":\r\n return np.int64(val)\r\n return val\r\n\r\n def save(self):\r\n out = {}\r\n out[\"_name\"] = self._name\r\n out[\"type\"] = self.type\r\n out[\"ndim\"] = self.ndim\r\n if self.ndim > 1:\r\n out[\"_base\"] = list(self._base)\r\n else:\r\n out[\"_base\"] = self._base\r\n out[\"_track\"] = self._track.save()\r\n out[\"_use_track\"] = self._use_track\r\n return out\r\n\r\n @staticmethod\r\n def load(project, data):\r\n val = Value(project, data[\"_name\"], data[\"type\"], data[\"ndim\"], data[\"_base\"], Track.load(data[\"_track\"]), data[\"_use_track\"])\r\n return val\r\n\r\n def default_base(self):\r\n if self.type == \"float\" or self.type == \"int\":\r\n if self.ndim > 1:\r\n return [0 for i in range(self.ndim)]\r\n else: return 0\r\n elif self.type == \"bool\":\r\n return False\r\n\r\n def default_track(self):\r\n return Track()\r\n\r\n @property\r\n def value(self):\r\n return self.get_value()\r\n\r\n @value.setter\r\n def value(self, val):\r\n self.set_value(val)\r\n\r\n def get_value(self):\r\n if self._use_track:\r\n if not self._track.empty():\r\n return self.get_track()\r\n return self.get_base()\r\n\r\n def set_value(self, val):\r\n self.set_base(val)\r\n\r\n def get_base(self):\r\n return self._base\r\n\r\n def set_base(self, val):\r\n self._base = self.process(val)\r\n\r\n def get_track_at(self, time):\r\n return self._track.value(time)\r\n\r\n def set_track_at(self, time, val):\r\n self._track.add_keyframe(time, val)\r\n\r\n def get_track(self):\r\n return self.get_track_at(self._project.time)\r\n\r\n def set_track(self):\r\n return self.set_track_at(self._project.time)\r\n\r\n def use_track(self, val=True):\r\n self._use_track = val\r\n\r\n def get_uniform(self):\r\n if self.ndim > 1:\r\n return tuple(self.value)\r\n return self.value\r\n\r\n\r\nclass CodeInfo:\r\n def __init__(self, code):\r\n self.code = code\r\n self.uniforms = self.find_uniforms(self.code)\r\n\r\n def find_uniforms(self, code):\r\n uniforms = []\r\n lines = code.split(\"\\n\")\r\n for l in lines:\r\n line = l.split(\" \")\r\n if line[0] == \"uniform\":\r\n type = line[1]\r\n name = line[2].split(\";\")[0]\r\n if type == \"float\":\r\n uniforms.append(Uniform(\"float\", 1, name))\r\n elif type == \"vec2\":\r\n uniforms.append(Uniform(\"float\", 2, name))\r\n elif type == \"vec3\":\r\n uniforms.append(Uniform(\"float\", 3, name))\r\n elif type == \"vec4\":\r\n uniforms.append(Uniform(\"float\", 4, name))\r\n elif type == \"bool\":\r\n uniforms.append(Uniform(\"bool\", 1, name))\r\n elif type == \"int\":\r\n uniforms.append(Uniform(\"int\", 1, name))\r\n else:\r\n print(\"Uniforms of type {} are not supported\".format(type))\r\n return uniforms\r\n\r\n\r\nclass Uniform:\r\n def __init__(self, type, ndim, name):\r\n self.type = type\r\n self.ndim = ndim\r\n self.name = name\r\n\r\n\r\nclass RenderConfig:\r\n def __init__(self):\r\n self.size = (1024, 1024)\r\n self.max_patch = 512\r\n self.steps = 1024*4\r\n self.steps_max = 256\r\n self.step_scale = 100\r\n self.stop_dist = 100\r\n self.max_depth = 10\r\n self.min_depth = 0.001\r\n self.aa = 2\r\n self.path = QtCore.QStandardPaths.locate(QtCore.QStandardPaths.DocumentsLocation, \"\", QtCore.QStandardPaths.LocateDirectory) + \"rdapp/render/auto\"\r\n self.snap_path = QtCore.QStandardPaths.locate(QtCore.QStandardPaths.DocumentsLocation, \"\", QtCore.QStandardPaths.LocateDirectory) + \"rdapp/snap\"\r\n self.frames = (0, 100)\r\n self.preview_max_size = 1024\r\n self.mp4 = False\r\n self.depth = False\r\n self.depth_mask = True\r\n self.scan_box = 4\r\n self.scan_res = 256\r\n\r\n\r\n\r\n def checkpaths(self):\r\n if not os.path.exists(self.path) and self.path != QtCore.QStandardPaths.locate(QtCore.QStandardPaths.DocumentsLocation, \"\", QtCore.QStandardPaths.LocateDirectory) + \"rdapp/render/auto\":\r\n self.path = QtCore.QStandardPaths.locate(QtCore.QStandardPaths.DocumentsLocation, \"\", QtCore.QStandardPaths.LocateDirectory) + \"rdapp/render/auto\"\r\n if not os.path.exists(self.snap_path):\r\n self.snap_path = QtCore.QStandardPaths.locate(QtCore.QStandardPaths.DocumentsLocation, \"\", QtCore.QStandardPaths.LocateDirectory) + \"rdapp/snap\"\r\n \r\n def save(self):\r\n data = {}\r\n data[\"size\"] = self.size\r\n data[\"max_patch\"] = self.max_patch\r\n data[\"steps\"] = self.steps\r\n data[\"steps_max\"] = self.steps_max\r\n data[\"step_scale\"] = self.step_scale\r\n data[\"stop_dist\"] = self.stop_dist\r\n data[\"max_depth\"] = self.max_depth\r\n data[\"min_depth\"] = self.min_depth\r\n data[\"aa\"] = self.aa\r\n data[\"path\"] = self.path\r\n data[\"snap_path\"] = self.snap_path\r\n data[\"frames\"] = self.frames\r\n data[\"preview_max_size\"] = self.preview_max_size\r\n data[\"mp4\"] = self.mp4\r\n data[\"depth\"] = self.depth\r\n data[\"scan_box\"] = self.scan_box\r\n data[\"scan_res\"] = self.scan_res\r\n\r\n return data\r\n\r\n @staticmethod\r\n def default():\r\n config = RenderConfig()\r\n config.checkpaths()\r\n return config\r\n\r\n @staticmethod\r\n def load(data):\r\n self = RenderConfig()\r\n if \"size\" in data: self.size = data[\"size\"]\r\n if \"max_patch\" in data: self.max_patch = data[\"max_patch\"]\r\n if \"steps\" in data: self.steps = data[\"steps\"]\r\n if \"steps_max\" in data: self.steps_max = data[\"steps_max\"]\r\n if \"step_scale\" in data: self.step_scale = data[\"step_scale\"]\r\n if \"stop_dist\" in data: self.stop_dist = data[\"stop_dist\"]\r\n if \"max_depth\" in data: self.max_depth = data[\"max_depth\"]\r\n if \"min_depth\" in data: self.min_depth = data[\"min_depth\"]\r\n if \"aa\" in data: self.aa = data[\"aa\"]\r\n if \"path\" in data: self.path = data[\"path\"]\r\n if \"snap_path\" in data: self.snap_path = data[\"snap_path\"]\r\n if \"frames\" in data: self.frames = data[\"frames\"]\r\n if \"preview_max_size\" in data: self.preview_max_size = data[\"preview_max_size\"]\r\n if \"mp4\" in data: self.mp4 = data[\"mp4\"]\r\n if \"depth\" in data: self.depth = data[\"depth\"]\r\n if \"scan_box\" in data: self.scan_box = data[\"scan_box\"]\r\n if \"scan_res\" in data: self.scan_res = data[\"scan_res\"]\r\n\r\n self.checkpaths()\r\n return self\r\n\r\n\r\nclass LiveConfig:\r\n def __init__(self, app):\r\n self.app = app\r\n\r\n self.steps = 128\r\n self.step_scale = 10\r\n self.stop_dist = 100\r\n self.max_depth = 10\r\n self.min_depth = 0.001\r\n\r\n self.size = (512, 512)\r\n self.margins = 10\r\n\r\n self.clear = True\r\n self.downscale = 1\r\n\r\n def save(self):\r\n data = {}\r\n data[\"steps\"] = self.steps\r\n data[\"step_scale\"] = self.step_scale\r\n data[\"stop_dist\"] = self.stop_dist\r\n data[\"max_depth\"] = self.max_depth\r\n data[\"min_depth\"] = self.min_depth\r\n data[\"size\"] = self.size\r\n data[\"margins\"] = self.margins\r\n data[\"clear\"] = self.clear\r\n data[\"downscale\"] = self.downscale\r\n return data\r\n\r\n @staticmethod\r\n def load(app, data):\r\n self = LiveConfig(app)\r\n if \"steps\" in data: self.steps = data[\"steps\"]\r\n if \"step_scale\" in data: self.step_scale = data[\"step_scale\"]\r\n if \"stop_dist\" in data: self.stop_dist = data[\"stop_dist\"]\r\n if \"max_depth\" in data: self.max_depth = data[\"max_depth\"]\r\n if \"min_depth\" in data: self.min_depth = data[\"min_depth\"]\r\n if \"size\" in data: self.size = data[\"size\"]\r\n if \"margins\" in data: self.margins = data[\"margins\"]\r\n if \"clear\" in data: self.clear = data[\"clear\"]\r\n if \"downscale\" in data: self.downscale = data[\"downscale\"]\r\n return self\r\n\r\n @staticmethod\r\n def default(app):\r\n return LiveConfig(app)\r\n\r\n @property\r\n def viewport(self):\r\n viewport_size = utils.fit(\r\n self.app.render_config.size, (self.size[0]-self.margins*2, self.size[1]-self.margins*2))\r\n viewport_pos = (self.size[0] - viewport_size[0]) / 2, (self.size[1] - viewport_size[1]) / 2\r\n return viewport_pos + viewport_size\r\n\r\n def get_uniforms(self):\r\n uniforms={}\r\n viewport = self.viewport\r\n uniforms[\"render_size\"] = viewport[2], viewport[3]\r\n uniforms[\"patch_size\"] = self.size\r\n uniforms[\"patch_pos\"] = -viewport[0], -viewport[1]\r\n return uniforms\r\n\r\nclass AppConfig:\r\n def __init__(self):\r\n self.theme = 70\r\n self.script_startup = False\r\n\r\n def save(self):\r\n return {\"theme\": self.theme, \"script_startup\": self.script_startup}\r\n\r\n @staticmethod\r\n def default():\r\n return AppConfig()\r\n\r\n @staticmethod\r\n def load(data):\r\n self = AppConfig()\r\n if \"theme\" in data: self.theme = data[\"theme\"]\r\n if \"script_startup\" in data: self.script_startup = data[\"script_startup\"]\r\n return self\r\n","sub_path":"src/main/python/rdapp/project.py","file_name":"project.py","file_ext":"py","file_size_in_byte":14167,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"580471690","text":"import cv2\nimport matplotlib.image as mpimg\nimport numpy as np\nfrom skimage.feature import hog\n\nclass ImageFeatures:\n def __init__(self,\n color_space='RGB', \n bin_size=(32,32), \n hist_bins=32, \n hist_bin_range=(0,32),\n hog_channel=3,\n hog_orient=9, \n hog_pix_per_cell=8, \n hog_cell_per_block=2):\n self.color_space = color_space\n self.bin_size = bin_size\n self.hist_bins = hist_bins\n self.hist_bin_range = hist_bin_range\n self.hog_channel=hog_channel\n self.hog_orient = hog_orient\n self.hog_pix_per_cell = hog_pix_per_cell\n self.hog_cell_per_block = hog_cell_per_block\n\n def convert_image(self, img):\n if self.color_space == 'HSV':\n return cv2.cvtColor(img, cv2.COLOR_RGB2HSV)\n elif self.color_space == 'LUV':\n return cv2.cvtColor(img, cv2.COLOR_RGB2LUV)\n elif self.color_space == 'HLS':\n return cv2.cvtColor(img, cv2.COLOR_RGB2HLS)\n elif self.color_space == 'YUV':\n return cv2.cvtColor(img, cv2.COLOR_RGB2YUV)\n elif self.color_space == 'YCrCb':\n return cv2.cvtColor(img, cv2.COLOR_RGB2YCrCb)\n else:\n return np.copy(img)\n\n def getChannel(self, img):\n feature_image = self.convert_image(img)\n if self.hog_channel < 3:\n return feature_image[:, :, self.hog_channel]\n else:\n return cv2.cvtColor(img, cv2.COLOR_RGB2GRAY)\n\n def bin_spatial(self, img):\n features = cv2.resize(img, self.bin_size).ravel()\n\n # Return the feature vector\n return features\n\n # Define a function to compute color histogram features \n def color_hist(self, img):\n # Compute the histogram of the color channels separately\n channel1_hist = np.histogram(img[:,:,0], bins=self.hist_bins, range=self.hist_bin_range)\n channel2_hist = np.histogram(img[:,:,1], bins=self.hist_bins, range=self.hist_bin_range)\n channel3_hist = np.histogram(img[:,:,2], bins=self.hist_bins, range=self.hist_bin_range)\n # Concatenate the histograms into a single feature vector\n hist_features = np.concatenate((channel1_hist[0], channel2_hist[0], channel3_hist[0]))\n # Return the individual histograms, bin_centers and feature vector\n return hist_features\n\n # Define a function to return HOG features and visualization\n def get_hog_features(self, img, vis=False):\n gray = self.getChannel(img)\n # Call with two outputs if vis==True\n if vis == True:\n features, hog_image = hog(gray, orientations=self.hog_orient, pixels_per_cell=(self.hog_pix_per_cell, self.hog_pix_per_cell),\n cells_per_block=(self.hog_cell_per_block, self.hog_cell_per_block),\n visualise=vis, feature_vector=True)\n return features, hog_image\n # Otherwise call with one output\n else: \n features = hog(gray, orientations=self.hog_orient, pixels_per_cell=(self.hog_pix_per_cell, self.hog_pix_per_cell),\n cells_per_block=(self.hog_cell_per_block, self.hog_cell_per_block),\n visualise=vis, feature_vector=True)\n return features\n\n def extract_feature(self, img):\n feature_image = self.convert_image(img)\n spatial_features = self.bin_spatial(feature_image)\n hist_features = self.color_hist(feature_image)\n hog_features = self.get_hog_features(img)\n return np.concatenate((spatial_features, hist_features, hog_features))\n\n def featurize(self, img_paths):\n # Create a list to append feature vectors to\n features = []\n # Iterate through the list of images\n # Read in each one by one\n # apply color conversion if other than 'RGB'\n # Apply bin_spatial() to get spatial color features\n # Apply color_hist() to get color histogram features\n # Append the new feature vector to the features list\n # Return list of feature vectors\n for img_path in img_paths:\n img = mpimg.imread(img_path)\n img_features = self.extract_feature(img)\n features.append(img_features)\n return features","sub_path":"scripts/image_features.py","file_name":"image_features.py","file_ext":"py","file_size_in_byte":4385,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"613686726","text":"#\n# Copyright (c) 2012, Centre for Microscopy and Microanalysis\n# (University of Queensland, Australia)\n# All rights reserved.\n#\n# Redistribution and use in source and binary forms, with or without\n# modification, are permitted provided that the following conditions are met:\n# * Redistributions of source code must retain the above copyright\n# notice, this list of conditions and the following disclaimer.\n# * Redistributions in binary form must reproduce the above copyright\n# notice, this list of conditions and the following disclaimer in the\n# documentation and/or other materials provided with the distribution.\n# * Neither the name of the University of Queensland nor the\n# names of its contributors may be used to endorse or promote products\n# derived from this software without specific prior written permission.\n#\n# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS AND CONTRIBUTORS BE\n# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n# POSSIBILITY OF SUCH DAMAGE.\n#\n\n# Utility functions for generating test objects.\nimport os, urlparse\n\nfrom django.conf import settings\nfrom tardis.tardis_portal.models import Location\n\ndef generate_datafile(path, dataset, content=None, size=-1,\n verify=True, verified=True, verify_checksums_req=False):\n '''Generates a datafile AND a replica to hold its contents'''\n from tardis.tardis_portal.models import Dataset_File, Replica, Location\n\n saved = settings.REQUIRE_DATAFILE_CHECKSUMS\n settings.REQUIRE_DATAFILE_CHECKSUMS = False\n try:\n datafile = Dataset_File()\n if content:\n datafile.size = str(len(content))\n else:\n datafile.size = str(size)\n # Normally we use any old string for the datafile path, but some\n # tests require the path to be the same as what 'staging' would use\n if path == None:\n datafile.dataset_id = dataset.id\n datafile.save()\n path = \"%s/%s/%s\" % (dataset.get_first_experiment().id,\n dataset.id, datafile.id)\n\n filepath = os.path.normpath(settings.FILE_STORE_PATH + '/' + path)\n if content:\n try:\n os.makedirs(os.path.dirname(filepath))\n os.remove(filepath)\n except:\n pass\n gen_file = open(filepath, 'wb+')\n gen_file.write(content)\n gen_file.close()\n datafile.mimetype = \"application/unspecified\"\n datafile.filename = os.path.basename(filepath)\n datafile.dataset_id = dataset.id\n datafile.save()\n settings.REQUIRE_DATAFILE_CHECKSUMS = verify_checksums_req\n location = _infer_location(path)\n replica = Replica(datafile=datafile, url=path, protocol='',\n location=location)\n if verify and content:\n if not replica.verify():\n raise RuntimeError('verify failed!?!')\n replica.save()\n replica.verified = verified\n replica.save(update_fields=['verified']) # force no verification\n return (datafile, replica)\n finally:\n settings.REQUIRE_DATAFILE_CHECKSUMS = saved\n\ndef _infer_location(path):\n if urlparse.urlparse(path).scheme == '':\n loc = Location.get_default_location()\n else:\n loc = Location.get_location_for_url(path)\n if loc:\n return loc\n else:\n raise Exception('Cannot infer a location for %s' % path)\n\ndef generate_dataset(datafiles=[], experiments=[]):\n from tardis.tardis_portal.models import Dataset\n dataset = Dataset()\n dataset.save()\n for df in datafiles:\n df.dataset_id = dataset.id\n df.save()\n for exp in experiments:\n dataset.experiments.add(exp)\n dataset.save()\n return dataset\n\ndef generate_experiment(datasets=[], users=[]):\n from tardis.tardis_portal.models import Experiment, ObjectACL\n experiment = Experiment(created_by=users[0])\n experiment.save()\n for ds in datasets:\n ds.experiments.add(experiment)\n ds.save()\n for user in users:\n acl = ObjectACL(content_object=experiment,\n pluginId='django_user',\n entityId=str(user.id),\n isOwner=True,\n canRead=True,\n canWrite=True,\n canDelete=True,\n aclOwnershipType=ObjectACL.OWNER_OWNED)\n acl.save()\n return experiment\n\ndef generate_user(name, priority=-1):\n from django.contrib.auth.models import User\n from tardis.apps.migration.models import UserPriority, DEFAULT_USER_PRIORITY\n from tardis.tardis_portal.models import UserProfile\n user = User(username=name)\n user.save()\n UserProfile(user=user).save()\n if priority >= 0 and priority != DEFAULT_USER_PRIORITY:\n UserPriority(user=user,priority=priority).save()\n return user\n","sub_path":"tardis/tardis_portal/tests/transfer/generate.py","file_name":"generate.py","file_ext":"py","file_size_in_byte":5563,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"41631515","text":"from parameters import *\nfrom connHelper import *\nimport psycopg2\n\n\nclass Type:\n\tdef __init__(self, id, description):\n\t\tself.id = id\n\t\tself.description = str(description).replace(\"'\", \"\")\n\t\n\tdef checkExists(self):\n\t\t\n\t\tcmd = \"SELECT COUNT(*) FROM TB_TYPE WHERE idtype = %s\" % (self.id)\n\t\tcount = executeSelectScalar(cmd)\n\n\t\treturn count[0] > 0\n\n\tdef save(self):\n\t\t\n\t\tcmd = \"\"\n\t\tif not self.checkExists():\n\t\t\tcmd = \"INSERT INTO TB_TYPE\" \\\n\t\t\t\t\"(idtype, description) VALUES (%s, '%s')\" % (self.id, self.description)\n\t\telse:\n\t\t\tcmd = \"UPDATE TB_TYPE SET description = '%s' WHERE idtype= %s\" % (self.description, self.id)\n\n\t\texecuteTransaction(cmd)\n","sub_path":"code/MrCrawler/type.py","file_name":"type.py","file_ext":"py","file_size_in_byte":649,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"518294719","text":"# Copyright 2018 Google Inc. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n\"\"\"Parses VCF files (version 4.x) and converts them to Variant objects.\n\nThe 4.2 spec is available at https://samtools.github.io/hts-specs/VCFv4.2.pdf.\n\"\"\"\n\nfrom __future__ import absolute_import\n\nimport logging\nfrom collections import namedtuple\n\nimport vcf\n\nfrom apache_beam.coders import coders\nfrom apache_beam.io import textio\n\n\n# Stores data about failed VCF record reads. `line` is the text line that\n# caused the failed read and `file_name` is the name of the file that the read\n# failed in.\nMalformedVcfRecord = namedtuple('MalformedVcfRecord',\n ['file_name', 'line', 'error'])\nMISSING_FIELD_VALUE = '.' # Indicates field is missing in VCF record.\nPASS_FILTER = 'PASS' # Indicates that all filters have been passed.\nEND_INFO_KEY = 'END' # The info key that explicitly specifies end of a record.\nGENOTYPE_FORMAT_KEY = 'GT' # The genotype format key in a call.\nPHASESET_FORMAT_KEY = 'PS' # The phaseset format key.\nDEFAULT_PHASESET_VALUE = '*' # Default phaseset value if call is phased, but\n # no 'PS' is present.\nMISSING_GENOTYPE_VALUE = -1 # Genotype to use when '.' is used in GT field.\n\n\nclass Variant(object):\n \"\"\"A class to store info about a genomic variant.\n\n Each object corresponds to a single record in a VCF file.\n \"\"\"\n\n def __init__(self,\n reference_name=None, # type: str\n start=None, # type: int\n end=None, # type: int\n reference_bases=None, # type: str\n alternate_bases=None, # type: List[str]\n names=None, # type: List[str]\n quality=None, # type: float\n filters=None, # type: List[str]\n info=None, # type: Dict[str, Any]\n calls=None # type: List[VariantCall]\n ):\n # type: (...) -> None\n \"\"\"Initialize the ``Variant`` object.\n\n Args:\n reference_name: The reference on which this variant occurs (such as\n `chr20` or `X`).\n start: The position at which this variant occurs (0-based). Corresponds to\n the first base of the string of reference bases.\n end: The end position (0-based) of this variant. Corresponds to the first\n base after the last base in the reference allele.\n reference_bases: The reference bases for this variant.\n alternate_bases: The bases that appear instead of the reference bases.\n names: Names for the variant, for example a RefSNP ID.\n quality: Phred-scaled quality score (-10log10 prob(call is wrong)).\n Higher values imply better quality.\n filters: A list of filters (normally quality filters) this variant has\n failed. `PASS` indicates this variant has passed all filters.\n info: A map of additional variant information. The key is specified\n in the VCF record and the value can be any type .\n calls: The variant calls for this variant. Each one represents the\n determination of genotype with respect to this variant.\n \"\"\"\n self.reference_name = reference_name\n self.start = start\n self.end = end\n self.reference_bases = reference_bases\n self.alternate_bases = alternate_bases or []\n self.names = names or []\n self.quality = quality\n self.filters = filters or []\n self.info = info or {}\n self.calls = calls or []\n\n def __eq__(self, other):\n return (isinstance(other, Variant) and\n vars(self) == vars(other))\n\n def __repr__(self):\n return ', '.join(\n [str(s) for s in [self.reference_name,\n self.start,\n self.end,\n self.reference_bases,\n self.alternate_bases,\n self.names,\n self.quality,\n self.filters,\n self.info,\n self.calls]])\n\n def __lt__(self, other):\n if not isinstance(other, Variant):\n return NotImplemented\n\n # Elements should first be sorted by reference_name, start, end.\n # Ordering of other members is not important, but must be\n # deterministic.\n if self.reference_name != other.reference_name:\n return self.reference_name < other.reference_name\n elif self.start != other.start:\n return self.start < other.start\n elif self.end != other.end:\n return self.end < other.end\n\n self_vars = vars(self)\n other_vars = vars(other)\n for key in sorted(self_vars):\n if self_vars[key] != other_vars[key]:\n return self_vars[key] < other_vars[key]\n\n return False\n\n def __le__(self, other):\n if not isinstance(other, Variant):\n return NotImplemented\n\n return self < other or self == other\n\n def __ne__(self, other):\n return not self == other\n\n def __gt__(self, other):\n if not isinstance(other, Variant):\n return NotImplemented\n\n return other < self\n\n def __ge__(self, other):\n if not isinstance(other, Variant):\n return NotImplemented\n\n return other <= self\n\n\nclass VariantCall(object):\n \"\"\"A class to store info about a variant call.\n\n A call represents the determination of genotype with respect to a particular\n variant. It may include associated information such as quality and phasing.\n \"\"\"\n\n def __init__(self, name=None, genotype=None, phaseset=None, info=None):\n # type: (str, List[int], str, Dict[str, Any]) -> None\n \"\"\"Initialize the :class:`VariantCall` object.\n\n Args:\n name: The name of the call.\n genotype: The genotype of this variant call as specified by the VCF\n schema. The values are either `0` representing the reference, or a\n 1-based index into alternate bases. Ordering is only important if\n `phaseset` is present. If a genotype is not called (that is, a `.` is\n present in the GT string), -1 is used.\n phaseset: If this field is present, this variant call's genotype ordering\n implies the phase of the bases and is consistent with any other variant\n calls in the same reference sequence which have the same phaseset value.\n If the genotype data was phased but no phase set was specified, this\n field will be set to `*`.\n info: A map of additional variant call information. The key is specified\n in the VCF record and the type of the value is specified by the VCF\n header FORMAT.\n \"\"\"\n self.name = name\n self.genotype = genotype or []\n self.phaseset = phaseset\n self.info = info or {}\n\n def __eq__(self, other):\n return ((self.name, self.genotype, self.phaseset, self.info) ==\n (other.name, other.genotype, other.phaseset, other.info))\n\n def __lt__(self, other):\n if self.name != other.name:\n return self.name < other.name\n elif self.genotype != other.genotype:\n return self.genotype < other.genotype\n elif self.phaseset != other.phaseset:\n return self.phaseset < other.phaseset\n else:\n return self.info < other.info\n\n def __le__(self, other):\n return self < other or self == other\n\n def __gt__(self, other):\n return other < self\n\n def __ge__(self, other):\n return other <= self\n\n def __ne__(self, other):\n return not self == other\n\n def __repr__(self):\n return ', '.join(\n [str(s) for s in [self.name, self.genotype, self.phaseset, self.info]])\n\n\nclass VcfParser(object):\n \"\"\"Base abstract class for defining a VCF file parser.\n\n Derived classes must implement two methods:\n _init_with_header: must initialize parser with given header lines.\n _get_variant: given a line of VCF file, returns a Variant object.\n Objects of the derived classed will be an iterator of records:\n ```\n record_iterator = DerivedVcfParser(...)\n for record in record_iterator:\n yield record\n ```\n \"\"\"\n\n def __init__(self,\n file_name, # type: str\n range_tracker, # type: range_trackers.OffsetRangeTracker\n file_pattern, # type: str\n compression_type, # type: str\n allow_malformed_records, # type: bool\n representative_header_lines=None, # type: List[str]\n **kwargs # type: **str\n ):\n # type: (...) -> None\n # If `representative_header_lines` is given, header lines in `file_name`\n # are ignored; refer to _process_header_lines() logic.\n self._representative_header_lines = representative_header_lines\n self._file_name = file_name\n self._allow_malformed_records = allow_malformed_records\n\n text_source = textio._TextSource(\n file_pattern,\n 0, # min_bundle_size\n compression_type,\n True, # strip_trailing_newlines\n coders.StrUtf8Coder(), # coder\n validate=False,\n header_processor_fns=(\n lambda x: not x.strip() or x.startswith('#'),\n self._process_header_lines),\n **kwargs)\n\n self._text_lines = text_source.read_records(self._file_name,\n range_tracker)\n\n def _process_header_lines(self, header_lines):\n \"\"\"Processes header lines from text source and initializes the parser.\n\n Note: this method will be automatically called by textio._TextSource().\n \"\"\"\n if self._representative_header_lines:\n # Replace header lines with given representative header lines.\n # We need to keep the last line of the header from the file because it\n # contains the sample IDs, which is unique per file.\n header_lines = self._representative_header_lines + header_lines[-1:]\n self._init_with_header(header_lines)\n\n def next(self):\n text_line = next(self._text_lines).strip()\n while not text_line: # skip empty lines.\n # This natively raises StopIteration if end of file is reached.\n text_line = next(self._text_lines).strip()\n record = self._get_variant(text_line)\n if isinstance(record, Variant):\n return record\n elif isinstance(record, MalformedVcfRecord):\n if self._allow_malformed_records:\n return record\n else:\n raise ValueError('VCF record read failed in %s for line %s: %s' %\n (self._file_name, text_line, str(record.error)))\n else:\n raise ValueError('Unrecognized record type: %s.' % str(type(record)))\n\n def __iter__(self):\n return self\n\n def _init_with_header(self, header_lines):\n # type: (List[str]) -> None\n \"\"\"Initializes the parser specific settings with the given header_lines.\n\n Note: this method will be called by _process_header_lines().\n \"\"\"\n raise NotImplementedError\n\n def _get_variant(self, data_line):\n # type: (str) -> Variant\n \"\"\"Converts a single data_line of a VCF file into a Variant object.\n\n In case something goes wrong it must return a MalformedVcfRecord object.\n Note: this method will be called by next(), one line at a time.\n \"\"\"\n raise NotImplementedError\n\n\nclass PyVcfParser(VcfParser):\n \"\"\"An Iterator for processing a single VCF file using PyVcf.\"\"\"\n\n def __init__(self,\n file_name, # type: str\n range_tracker, # type: range_trackers.OffsetRangeTracker\n file_pattern, # type: str\n compression_type, # type: str\n allow_malformed_records, # type: bool\n representative_header_lines=None, # type: List[str]\n **kwargs # type: **str\n ):\n # type: (...) -> None\n super(PyVcfParser, self).__init__(file_name,\n range_tracker,\n file_pattern,\n compression_type,\n allow_malformed_records,\n representative_header_lines,\n **kwargs)\n self._header_lines = []\n self._next_line_to_process = None\n self._current_line = None\n # This member will be properly initiated in _init_with_header().\n self._vcf_reader = None\n\n def _init_with_header(self, header_lines):\n self._header_lines = header_lines\n try:\n self._vcf_reader = vcf.Reader(fsock=self._line_generator())\n except SyntaxError as e:\n raise ValueError(\n 'Invalid VCF header in %s: %s' % (self._file_name, str(e)))\n\n def _get_variant(self, data_line):\n # _line_generator will consume this line.\n self._next_line_to_process = data_line\n try:\n record = next(self._vcf_reader)\n return self._convert_to_variant(record, self._vcf_reader.formats)\n except (LookupError, ValueError) as e:\n logging.warning('VCF record read failed in %s for line %s: %s',\n self._file_name, data_line, str(e))\n return MalformedVcfRecord(self._file_name, data_line, str(e))\n\n def _line_generator(self):\n for header in self._header_lines:\n yield header\n # Continue to process the next line indefinitely. The next line is set\n # inside _get_variant() and this method is indirectly called in get_variant.\n while self._next_line_to_process:\n self._current_line = self._next_line_to_process\n self._next_line_to_process = None\n # PyVCF has explicit str() calls when parsing INFO fields, which fails\n # with UTF-8 decoded strings. Encode the line back to UTF-8.\n yield self._current_line.encode('utf-8')\n # Making sure _get_variant() assigned a new value before consuming it.\n assert self._next_line_to_process is not None, (\n 'Internal error: A data line is requested to be processed more than '\n 'once. Please file a bug if you see this!')\n\n def _convert_to_variant(\n self,\n record, # type: vcf.model._Record\n formats # type: Dict[str, vcf.parser._Format]\n ):\n # type: (...) -> Variant\n \"\"\"Converts the PyVCF record to a :class:`Variant` object.\n\n Args:\n record: An object containing info about a variant.\n formats: The PyVCF dict storing FORMAT extracted from the VCF header.\n The key is the FORMAT key and the value is\n :class:`~vcf.parser._Format`.\n Returns:\n A :class:`Variant` object from the given record.\n Raises:\n ValueError: if ``record`` is semantically invalid.\n \"\"\"\n return Variant(\n reference_name=record.CHROM,\n start=record.start,\n end=self._get_variant_end(record),\n reference_bases=(\n record.REF if record.REF != MISSING_FIELD_VALUE else None),\n alternate_bases=self._get_variant_alternate_bases(record),\n names=record.ID.split(';') if record.ID else [],\n quality=record.QUAL,\n filters=[PASS_FILTER] if record.FILTER == [] else record.FILTER,\n info=self._get_variant_info(record),\n calls=self._get_variant_calls(record, formats))\n\n def _get_variant_end(self, record):\n if END_INFO_KEY not in record.INFO:\n return record.end\n end_info_value = record.INFO[END_INFO_KEY]\n if isinstance(end_info_value, (int, long)):\n return end_info_value\n if (isinstance(end_info_value, list) and len(end_info_value) == 1 and\n isinstance(end_info_value[0], (int, long))):\n return end_info_value[0]\n else:\n raise ValueError('Invalid END INFO field in record: {}'.format(\n self._current_line))\n\n def _get_variant_alternate_bases(self, record):\n # ALT fields are classes in PyVCF (e.g. Substitution), so need convert\n # them to their string representations.\n return [str(r) for r in record.ALT if r] if record.ALT else []\n\n def _get_variant_info(self, record):\n info = {}\n for k, v in record.INFO.iteritems():\n if k != END_INFO_KEY:\n info[k] = v\n\n return info\n\n def _get_variant_calls(self, record, formats):\n calls = []\n for sample in record.samples:\n call = VariantCall()\n call.name = sample.sample\n for allele in sample.gt_alleles or [MISSING_GENOTYPE_VALUE]:\n if allele is None:\n allele = MISSING_GENOTYPE_VALUE\n call.genotype.append(int(allele))\n phaseset_from_format = (\n getattr(sample.data, PHASESET_FORMAT_KEY)\n if PHASESET_FORMAT_KEY in sample.data._fields\n else None)\n # Note: Call is considered phased if it contains the 'PS' key regardless\n # of whether it uses '|'.\n if phaseset_from_format or sample.phased:\n call.phaseset = (str(phaseset_from_format) if phaseset_from_format\n else DEFAULT_PHASESET_VALUE)\n for field in sample.data._fields:\n # Genotype and phaseset (if present) are already included.\n if field in (GENOTYPE_FORMAT_KEY, PHASESET_FORMAT_KEY):\n continue\n data = getattr(sample.data, field)\n # Convert single values to a list for cases where the number of fields\n # is unknown. This is to ensure consistent types across all records.\n # Note: this is already done for INFO fields in PyVCF.\n if (field in formats and\n formats[field].num not in (0, 1) and\n isinstance(data, (int, float, long, basestring, bool))):\n data = [data]\n call.info[field] = data\n calls.append(call)\n return calls\n","sub_path":"gcp_variant_transforms/beam_io/vcf_parser.py","file_name":"vcf_parser.py","file_ext":"py","file_size_in_byte":17737,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"461880377","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n# @Time : 2017/5/27 PM8:30\n# @Author : Qiming Zhang\n# @File : N-Queens\n\nclass Solution(object):\n def solveNQueens(self, n):\n \"\"\"\n :type n: int\n :rtype: List[List[str]]\n \"\"\"\n permutationResult = []\n result = []\n\n self.backTrack(n, permutationResult, [])\n for l in permutationResult:\n result.append(self.convertToBoard(l, n))\n return result\n\n def convertToBoard(self, l, n):\n result = [\"\" for i in range(n)]\n for i in range(n):\n for j in range(n):\n result[i] += 'Q' if j + 1 == l[i] else '.'\n return result\n\n def backTrack(self, n, permutationResult, permutation):\n if len(permutation) == n:\n permutationResult.append(permutation[:])\n for i in range(1, n + 1):\n if i not in permutation and self.valid(permutation, i):\n permutation.append(i)\n self.backTrack(n, permutationResult, permutation)\n permutation.pop()\n\n def valid(self, permutation, p):\n for i in range(len(permutation)):\n if abs(len(permutation)- i) == abs(p - permutation[i]):\n return False\n return True\n\n\n","sub_path":"BackTrack/N-Queens.py","file_name":"N-Queens.py","file_ext":"py","file_size_in_byte":1272,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"632061603","text":"from matplotlib import pyplot as plt\r\nfrom matplotlib_venn import venn3, venn3_circles, venn2, venn2_circles\r\n\r\ndef vs(qi, nh):\r\n with open(qi) as f_qi:\r\n with open(nh) as f_nh:\r\n\r\n def my_func(file):\r\n my_dict = {}\r\n for i in file:\r\n line = i.strip()\r\n # name = ''\r\n if line.startswith('>'):\r\n name = line\r\n my_dict[name] = ''\r\n continue\r\n my_dict[name] += line\r\n my_set = set()\r\n for k, y in my_dict.items():\r\n my_set.add(y.upper())\r\n return my_set, my_dict\r\n\r\n f_qi_set = my_func(f_qi)[0]\r\n f_nh_set, f_nh_dic = my_func(f_nh)\r\n\r\n name_list = ['qiime1', 'NuoHe']\r\n num_list = []\r\n num_list.append(len(f_qi_set))\r\n num_list.append(len(f_nh_set))\r\n for a, b in zip(name_list, num_list):\r\n plt.text(a, b + 0.05, '%.0f' % b, ha='center', va='bottom', fontsize=11)\r\n plt.bar(name_list, num_list, width=0.5, color='rgb')\r\n plt.ylim(0, 300000)\r\n plt.title('OTU Counts')\r\n plt.show()\r\n\r\n v = venn2(subsets=(len(f_nh_set) - len(f_nh_set & f_qi_set), len(f_qi_set) - len(f_nh_set & f_qi_set), len(f_nh_set & f_qi_set)), set_labels=('NuoHe', 'qiime1'))\r\n plt.show()\r\n return\r\n\r\nif __name__ == '__main__':\r\n qi = 'C:\\\\Users\\\\jbwang\\\\Desktop\\\\otus.fa'\r\n nh = 'C:\\\\Users\\\\jbwang\\\\Desktop\\\\OTUs.fasta'\r\n\r\n print(vs(qi, nh))","sub_path":"codefile/vs.py","file_name":"vs.py","file_ext":"py","file_size_in_byte":1648,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"566207562","text":"\n# coding: utf-8\n\n# # Word 2 Vec\n# \n# The following code walks you through using word2vec from the Python Gensim package. Word2Vec is a Word Embedding Model (WEM) and helps to find how specific words are used in a given text. \n\n# ### Before we begin\n# Before we start, you will need to have set up a [Carbonate account](https://kb.iu.edu/d/aolp) in order to access [Research Desktop (RED)](https://kb.iu.edu/d/apum). You will also need to have access to RED through the [thinlinc client](https://kb.iu.edu/d/aput). If you have not done any of this, or have only done some of this, but not all, you should go to our [textPrep-Py.ipynb](https://github.com/cyberdh/Text-Analysis/blob/master/Python/Py_notebooks/textPrep-Py.ipynb) before you proceed further. The textPrepPy notebook provides information and resources on how to get a Carbonate account, how to set up RED, and how to get started using the Jupyter Notebook on RED. \n\nimport sys\nimport os\n\n# The code in the below points to a Python environment specificaly for use with the Python code created by Cyberinfrastructure for Digital Humanities. It allows for the use of the different pakcages in our code and their subsequent data sets.\n# NOTE: These two lines of code are only for use with Research Desktop. You will get an error if you try to run this code on your personal device!!\nsys.path.insert(0,\"/N/u/cyberdh/Carbonate/dhPyEnviron/lib/python3.6/site-packages\")\nos.environ[\"NLTK_DATA\"] = \"/N/u/cyberdh/Carbonate/dhPyEnviron/nltk_data\"\n\n\n# Include necessary packages for notebook \n\nimport re\nfrom os.path import join, isfile, splitext\nimport string\nimport nltk\nfrom nltk.corpus import stopwords\nimport glob\nimport numpy as np\nimport pandas as pd\nimport warnings\nfrom pprint import pprint\nimport spacy\nfrom sklearn.decomposition import PCA\nget_ipython().magic('matplotlib notebook')\nimport matplotlib.pyplot as plt\nplt.style.use('ggplot')\nfrom collections import Counter\n\nimport gensim\nimport gensim.corpora as corpora\nimport gensim.downloader as api\nfrom gensim.utils import simple_preprocess\nfrom gensim.models import CoherenceModel\nfrom gensim.models import doc2vec\nfrom gensim.models.phrases import Phrases, Phraser\n\n\n# This will ignore deprecation, user, and future warnings. All the warnings in this code are not concerning and will not break the code or cause errors in the results.\n\nwarnings.filterwarnings(\"ignore\", category=UserWarning,\n module = \"gensim\", lineno = 598)\n\nwarnings.filterwarnings(\"ignore\", category=FutureWarning,\n module = \"gensim\", lineno = 737)\nwarnings.filterwarnings(\"ignore\", category=DeprecationWarning)\n\n\n# Getting your data\n\n# File path variables\n\nhomePath = os.environ[\"HOME\"]\ndataHome = os.path.join(homePath, \"Text-Analysis-master\", \"data\")\ndataResults = os.path.join(homePath, \"Text-Analysis-master\", \"Output\")\n\n\n# Set needed variables\n\nsource = \"*\"\nfileType = \".txt\"\ndocLevel = True\nnltkStop = True\ncustomStop = False\nspacyLem = True\nstopLang = 'english'\nlemLang = 'en'\nstopWords = []\ndocs = []\ntweets = []\n\n#print(\" \".join(stopwords.fileids()))\n\n\n# Stopwords\n# NLTK Stop words\nif nltkStop is True:\n stopWords.extend(stopwords.words(stopLang))\n\n stopWords.extend(['would', 'said', 'says', 'also', 'let', 'not'])\n\n\n# Add own stopword list\n\nif customStop is True:\n stopWordsFilepath = os.path.join(homePath, \"Text-Analysis-master\", \"data\", \"earlyModernStopword.txt\")\n\n with open(stopWordsFilepath, \"r\",encoding = 'utf-8') as stopfile:\n stopWordsCustom = [x.strip() for x in stopfile.readlines()]\n\n stopWords.extend(stopWordsCustom)\n\n\n# Reading in .txt files\n\nif fileType == \".txt\":\n paths = glob.glob(os.path.join(dataHome, \"shakespeareDated\",source + fileType))\n for path in paths:\n with open(path, \"r\", encoding = 'ISO-8859-1') as file:\n # skip hidden file\n if path.startswith('.'):\n continue\n if docLevel is True:\n docs.append(file.read().strip('\\n').splitlines())\n else:\n for line in file:\n stripLine = line.strip()\n if len(stripLine) == 0:\n continue\n docs.append(stripLine.split())\n\n\n# Reading in .csv files\n\nif fileType == \".csv\":\n all_files = glob.glob(os.path.join(dataHome, \"twitter\", source + fileType)) \n df_all = (pd.read_csv(f) for f in all_files)\n cc_df = pd.concat(df_all, ignore_index=True)\n cc_df = pd.DataFrame(cc_df, dtype = 'str')\n tweets = cc_df['text'].values.tolist()\n\n\n# Reading in JSON files\n\nif fileType == \".json\":\n for filename in glob.glob(os.path.join(dataHome, \"twitter\", \"JSON\", source + fileType)):\n with open(filename, 'r', encoding = \"utf-8\") as jsonData:\n for line in jsonData:\n tweets.append(json.loads(line))\n df = pd.DataFrame(tweets)\n tweets = df['text'].tolist()\n\n\n# Data variable\n\nif len(docs) > 0:\n data = docs\nelse:\n if len(tweets) > 0:\n data = tweets\n # Remove Urls\n data = [re.sub(r'http\\S+', '', sent) for sent in data]\n # Remove new line characters\n data = [re.sub('\\s+', ' ', sent) for sent in data]\n\npprint(data[:1])\n\n\n# Tokenizing\n\ndef sentToWords(sentences):\n for sentence in sentences:\n yield(gensim.utils.simple_preprocess(str(sentence), deacc=True)) # deacc=True removes punctuations\n\ndataWords = list(sentToWords(data))\n\nprint(dataWords[:1])\n\n\n# Find Bigrams and Trigrams\n\n# Build the bigram and trigram models\nbigram = Phrases(dataWords, min_count=5, threshold=100) # higher threshold fewer phrases.\ntrigram = Phrases(bigram[dataWords], threshold=100) \n\n# Removes model state from Phrases thereby reducing memory use.\nbigramMod = Phraser(bigram)\ntrigramMod = Phraser(trigram)\n\n# See bigram/trigram example\ntestNgram = trigramMod[bigramMod[dataWords[0]]]\nchar = \"_\"\nnGrams = [s for s in testNgram if char in s]\n \npprint(Counter(nGrams))\n\n\n# Functions\n\n# Define functions for stopwords, bigrams, trigrams and lemmatization\ndef removeStopwords(texts):\n return [[word for word in simple_preprocess(str(doc)) if word not in stopWords] for doc in texts]\n\ndef makeBigrams(texts):\n return [bigramMod[doc] for doc in texts]\n\ndef makeTrigrams(texts):\n return [trigramMod[bigramMod[doc]] for doc in texts]\n\n\nif spacyLem is True:\n def lemmatization(texts, allowed_postags=['NOUN', 'ADJ', 'VERB', 'ADV']):\n \"\"\"https://spacy.io/api/annotation\"\"\"\n textsOut = []\n lemmaPOS = []\n for sent in texts:\n doc = nlp(\" \".join(sent)) \n textsOut.append([token.lemma_ for token in doc if token.pos_ in allowed_postags])\n lemmaPOS.append([token.text and token.lemma_ and token.pos_ for token in doc if token.pos_ in allowed_postags])\n return textsOut\n print(lemmaPOS[:10])\n\n\n# Now we apply the functions\n\n# Remove Stop Words\ndataWordsNostops = removeStopwords(dataWords)\n\n# Form Bigrams\ndataWordsNgrams = makeBigrams(dataWordsNostops)\n\nif spacyLem is True:\n # Initialize spacy language model, eliminating the parser and ner components\n nlp = spacy.load(lemLang, disable=['parser', 'ner'])\n \n # Do lemmatization tagging only noun, adj, vb, adv\n allowed_postags = ['NOUN', 'ADJ', 'VERB', 'ADV']\n dataLemmatized = lemmatization(dataWordsNgrams, allowed_postags=allowed_postags)\n lemmaPOS = []\n for sent in dataLemmatized:\n lemmaNLP = nlp(\" \".join(sent))\n for token in lemmaNLP:\n lemmaPOS.append([token.text, token.lemma_, token.pos_])\n print(lemmaPOS[:10])\n \n\n # Find ngrams and count number of times they occur\n dataNgrams = [s for s in dataLemmatized[0] if char in s]\n \nelse:\n dataNgrams = [s for s in dataWordsNgrams[0] if char in s]\nprint(Counter(dataNgrams))\n\n\n# Getting Information\n# \n# Now we want to get some information about our corpus now that it is cleaned.\n\nif spacyLem is True:\n # Create Corpus\n texts = dataLemmatized\n tokens = sum(texts, [])\nelse:\n # Create Corpus\n texts = dataWordsNgrams\n tokens = sum(texts, [])\n\nfrom collections import Counter\ncount = Counter(tokens)\nprint(sum(count.values()))\nprint(len(count))\nprint(count.most_common(1000))\n\n\n# Build vocabulary and train the model\n\n# build vocabulary and train model\n\nmodel = gensim.models.Word2Vec(\n texts,\n size=100,\n window=10,\n min_count=60,\n workers=1,\n sg = 1,\n seed = 42)\nmodel.train(texts, total_examples=len(texts), epochs=10)\n\n\n# Let's find some word relationships\n\nw2vCSVfile = 'word2vec.csv'\nw1 = \"woman\"\ntopn = 30\n\nwtv = model.wv.most_similar(positive=[w1], topn = topn)\ndf = pd.DataFrame(wtv)\ndf.to_csv(os.path.join(dataResults, w2vCSVfile))\ndfG = df[:10]\ndfG\n\n\n# Here we can compare two words to each other.\n\nmodel.wv.similarity(w1 = 'king', w2 = 'queen')\n\n\n# Now convert our results in the `df` variable from above to a list\n\ndfLst = df[0].tolist()\ndfLst.append(w1)\n\n\n# Here we create a function that uses Principal Component Analysis (PCA) for dimensionality reduction.\n\n# Variables\npcaScatterPlot = \"pcaScatterPlot.svg\"\ncolor = 'crimson'\n\n# Function\ndef display_pca_scatterplot(model, words=None, sample=0):\n if words == None:\n if sample > 0:\n words = np.random.choice(list(model.wv.vocab.keys()), sample)\n else:\n words = [ word for word in model.wv.vocab ]\n \n word_vectors = np.array([model[w] for w in words])\n\n twodim = PCA().fit_transform(word_vectors)[:,:2]\n \n plt.figure(figsize=(9,9))\n plt.scatter(twodim[:,0], twodim[:,1], edgecolors='k', c=color)\n for word, (x,y) in zip(words, twodim):\n plt.text(x+0.05, y+0.05, word)\n plt.savefig(os.path.join(dataResults, pcaScatterPlot))\n\n\n# Now we apply the function to our `model` from above and the list we made from our `df` variable. \n# Note however that the graph is interactive. You can zoom in by clicking the button with the square on it and the dragging over the section of the graph you wish to zoom in on. You can then click the save button to save the zoomed in version of the graph.\n\ndisplay_pca_scatterplot(model, dfLst)\n\n\n# ## VOILA!!\n\n# This code was adapted from Kavita Ganesan at [http://kavita-ganesan.com/gensim-word2vec-tutorial-starter-code/#.XFnQmc9KjUI](http://kavita-ganesan.com/gensim-word2vec-tutorial-starter-code/#.XFnQmc9KjUI). Accessed 02/05/2019. The display_pca_scatterplot function was taken entirley from [https://web.stanford.edu/class/cs224n/materials/Gensim%20word%20vector%20visualization.html](https://web.stanford.edu/class/cs224n/materials/Gensim%20word%20vector%20visualization.html) and was accessed on 07/18/2019.\n","sub_path":"TopicModeling/Word2Vec/script/word2Vec-Py.py","file_name":"word2Vec-Py.py","file_ext":"py","file_size_in_byte":10671,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"404224742","text":"import json\nimport requests\nimport unittest\nfrom requests.auth import HTTPBasicAuth\n\nclass TestApiBookstore(unittest.TestCase):\n \n def setUp(self):\n self.base_url = 'https://api-bookstore.herokuapp.com/api'\n self.auth = HTTPBasicAuth('admin', 'admin')\n \n def testBooksGet(self):\n req = requests.get(self.base_url + '/books', auth=self.auth)\n assert req.status_code == 200\n \n def testBooksGetParamTitle(self):\n params = {'title': 'Javascript is our all vol2', 'title': 'Marta Test Book', 'title': 'A Man Called'}\n for param in params:\n req = requests.get(self.base_url + '/books' + '?' + param + '=' + params[param] , auth=self.auth)\n for i in req.json():\n assert i[param] == params[param]\n \n def testBooksGetParamAuthor(self):\n params = {'author': 'Brian Rathbone'}\n req = requests.get(self.base_url + '/books', params=params, auth=self.auth)\n for i in req.json():\n assert i['author']['name'] == params['author']\n \n def testBooksGetParamGenre(self):\n params = {'genre': 'Book for kids'}\n req = requests.get(self.base_url + '/books', params=params, auth=self.auth)\n res = False\n for i in req.json():\n for value in i['genres']:\n if value['name'] == params['genre']:\n res = True\n assert res\n\n def testBooksPostDelete(self):\n params_form_data = {'title': 'Lost Dragons 11: The Wondrous Egg: Dragon books for kids',\n 'genres': 'Book for kids', 'author': 'Brian Rathbone' , 'price': '22',\n 'fullDescription': 'Dragon books for kids. The Lost Dragons must help each other to keep their color and get home!', 'shortDescription': 'Dragon books for kids'}\n req_create = requests.post(self.base_url + '/books', auth=self.auth, data=params_form_data)\n assert req_create.status_code == 200\n req_delete = requests.delete(self.base_url + '/books' + '/' + req_create.json()['_id'], auth=self.auth )\n assert req_delete.status_code == 204\n \n def testGetBook(self):\n book_id = '5995919ce875d000111f2d13'\n req = requests.get(self.base_url + '/books' + '/' + book_id, auth=self.auth) \n assert req.status_code == 200 and req.json()['_id'] == book_id\nif __name__ == \"__main__\":\n unittest.main()","sub_path":"api-bookstore/Tests.py","file_name":"Tests.py","file_ext":"py","file_size_in_byte":2444,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"525988711","text":"#!/usr/bin/env python\n# -*- coding: utf8 -*-\n# *****************************************************************\n# ** PTS -- Python Toolkit for working with SKIRT **\n# ** © Astronomical Observatory, Ghent University **\n# *****************************************************************\n\n## \\package pts.do.evolve.original Reference, original implementation.\n#\n\n# -----------------------------------------------------------------\n\n# Ensure Python 3 compatibility\nfrom __future__ import absolute_import, division, print_function\n\n# Import standard modules\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom scipy.optimize import curve_fit\n\n# Import the relevant PTS classes and modules\nfrom pts.evolve.engine import GAEngine, RawScoreCriteria\nfrom pts.evolve.genomes.list1d import G1DList\nfrom pts.evolve import mutators\nfrom pts.evolve import initializators\nfrom pts.evolve import constants\nfrom pts.core.tools.logging import log\nfrom pts.core.tools import time\nfrom pts.core.tools import filesystem as fs\nfrom pts.core.tools.random import setup_prng\nfrom pts.core.basics.configuration import ConfigurationDefinition, ConfigurationReader\n\n# -----------------------------------------------------------------\n\n# Configuration definition\ndefinition = ConfigurationDefinition()\ndefinition.add_positional_optional(\"seed\", int, \"the random seed\", 4357)\n\n# Get configuration\nreader = ConfigurationReader(\"reference\")\nconfig = reader.read(definition)\n\n# -----------------------------------------------------------------\n\nx = np.linspace(12,25,100)\n\ntest_data_x = [20., 16., 19.79999924, 18.39999962, 17.10000038, 15.5, 14.69999981, 17.10000038, 15.39999962,\n 16.20000076,\n 15., 17.20000076, 16., 17., 14.39999962]\ntest_data_y = [88.59999847, 71.59999847, 93.30000305, 84.30000305, 80.59999847, 75.19999695, 69.69999695, 82.,\n 69.40000153, 83.30000305, 79.59999847, 82.59999847, 80.59999847, 83.5, 76.30000305]\n\n# -----------------------------------------------------------------\n\ndef fit_function(x, a, b):\n\n \"\"\"\n This function ...\n :param a:\n :param b:\n :param x:\n :return:\n \"\"\"\n\n return a * x + b\n\n# -----------------------------------------------------------------\n\ndef chi_squared_function(chromosome):\n\n \"\"\"\n This function calculates the chi-squared value for a certain set of parameters (chromosome)\n :param chromosome:\n :return:\n \"\"\"\n\n chi_squared = 0.0\n for i in range(len(test_data_x)):\n x = test_data_x[i]\n y = test_data_y[i]\n chromosome_y = fit_function(x, chromosome[0], chromosome[1])\n chi_squared += (y - chromosome_y) ** 2.\n chi_squared /= 2.0\n return chi_squared\n\n# -----------------------------------------------------------------\n\n#seed = 4357\nseed = config.seed\nprng = setup_prng(seed)\n\n# -----------------------------------------------------------------\n\n# Genome instance\ngenome = G1DList(2)\ngenome.setParams(rangemin=0., rangemax=50., bestrawscore=0.00, rounddecimal=2)\ngenome.initializator.set(initializators.G1DListInitializatorReal)\ngenome.mutator.set(mutators.G1DListMutatorRealGaussian)\n\n# Set the evaluator function\ngenome.evaluator.set(chi_squared_function)\n\n# Genetic algorithm instance\nga = GAEngine(genome)\nga.terminationCriteria.set(RawScoreCriteria)\nga.setMinimax(constants.minimaxType[\"minimize\"])\nga.setGenerations(5)\nga.setCrossoverRate(0.5)\nga.setPopulationSize(100)\nga.setMutationRate(0.5)\n\n# Evolve\n#ga.evolve(freq_stats=False)\nga.evolve()\n\nprint(\"Final generation:\", ga.currentGeneration)\n\n# -----------------------------------------------------------------\n\n# Determine the path to the reference directory\nref_path = fs.join(fs.cwd(), \"reference\")\nfs.create_directory(ref_path)\n\n# -----------------------------------------------------------------\n\nbest = ga.bestIndividual()\n\nbest_parameter_a = best.genomeList[0]\nbest_parameter_b = best.genomeList[1]\n\nbest_path = fs.join(ref_path, \"best.dat\")\n\nwith open(best_path, 'w') as best_file:\n best_file.write(\"Parameter a: \" + str(best_parameter_a) + \"\\n\")\n best_file.write(\"Parameter b: \" + str(best_parameter_b) + \"\\n\")\n\npopt, pcov = curve_fit(fit_function, test_data_x, test_data_y)\nparameter_a_real = popt[0]\nparameter_b_real = popt[1]\n\nprint(\"Best parameter a:\", best_parameter_a, \" REAL:\", parameter_a_real)\nprint(\"Best parameter b:\", best_parameter_b, \" REAL:\", parameter_b_real)\n\nplt.figure()\nplt.scatter(test_data_x, test_data_y)\nplt.plot(x, [fit_function(x_i, best_parameter_a, best_parameter_b) for x_i in x])\nplt.plot(x, [fit_function(x_i, parameter_a_real, parameter_b_real) for x_i in x])\nplt.ylim(65, 95)\nplt.xlim(12,22)\n\n# Save the figure\nplot_path = fs.join(ref_path, \"best.pdf\")\nplt.savefig(plot_path)\n\n# -----------------------------------------------------------------\n","sub_path":"CAAPR/CAAPR_AstroMagic/PTS/pts/do/evolve/reference.py","file_name":"reference.py","file_ext":"py","file_size_in_byte":4813,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"331590832","text":"# %%\n'''\nThis file is to test that it is safe to use the sampled data to construct\nanalytical solution for the diagnostic index.\n'''\nimport numpy as np\nfrom statistics import * \nfrom scipy.stats import norm\nfrom math import *\n\ndef optimal_threshold(mu_I, mu_I0, sigma_I, sigma_I0, C_alpha, C_beta):\n \"\"\"\n Note: when sigma_I and sigma_I0 are significantly different between I and I0, there is no solution\n \n mu_I: mean value of diagnostic index at arbitrary degradation level\n mu_I0: mean value of diagnostic index at critical degradation level\n sigma_I: variance of diagnostic index at arbitrary degradation level\n sigma_I0: variance of diagnostic index at critical degradation level\n C_alpha: cost for detection failure (type 2 error: regulation), associated with alpha\n C_beta: cost for false alarm (type 1 error: catalyst cost), associated with beta\n simple: if true, sigma_I and sigma_I0 are the same, so simplified\n \"\"\"\n a = sigma_I\n b = sigma_I0\n c = mu_I\n d = mu_I0\n e = C_alpha\n f = C_beta\n\n if sigma_I != sigma_I0:\n term1 = 1/a**2 - 1/b**2\n term2 = 2 * (d/b**2 - c/a**2)\n term3 = c**2/a**2 - d**2/b**2 - 2 * log(b/a*f/e)\n I = (-term2 + sqrt(term2 **2 - 4 * term1 * term3))/(2*term1)\n# I = (((c/a**2) - (d/b**2)) + sqrt((d/b**2 - c/a**2)**2 - (1/a**2-1/b**2)*(c**2/a**2 - 2*log(b/a*e/f)-d**2/b**2)))/(1/a**2 - 1/b**2)\n \n else:\n I = 0.5 * (mu_I + mu_I0) - sigma_I ** 2 * log(f / e) / (mu_I - mu_I0)\n\n return I\n\ndef calculating_mu_I(data):\n \"\"\"calculating mean value of diagnostic index from data\"\"\"\n # default value is set from the previous paper\n return data.mean()\n\ndef calculating_sigma_I(data):\n \"\"\"calculating standard deviation of diagnostic index from data\"\"\"\n # default value is set from the previous paper\n return stdev(data)\n\ndef calculating_emission(data):\n return data.mean()\n\ndef calculating_total_cost(C_alpha, C_beta, mu_I0, sigma_I0, mu_I, sigma_I, I_thr):\n alpha = norm(loc = mu_I0, scale = sigma_I0).cdf(I_thr)\n beta = 1 - norm(loc = mu_I, scale = sigma_I).cdf(I_thr)\n C_tot = alpha * C_alpha + beta * C_beta\n return C_tot\n\ndef calculating_optimal_total_cost(C_alpha, C_beta, mu_I0, sigma_I0, mu_I, sigma_I):\n I_thr = optimal_threshold(mu_I, mu_I0, sigma_I, sigma_I0, C_alpha, C_beta)\n alpha = norm(loc = mu_I0, scale = sigma_I0).cdf(I_thr)\n beta = 1 - norm(loc = mu_I, scale = sigma_I).cdf(I_thr)\n C_tot = alpha * C_alpha + beta * C_beta\n return C_tot\n\n#%%\n# for a, we want to have mu=0.5 and sigma=1\ntrue_mu_I = 0.5\ntrue_sigma_I = 0.1\nnum_samples = 100\na = true_sigma_I * np.random.randn(num_samples) + true_mu_I\n# for b, we want to have mu=1.0 and sigma=1.5 \ntrue_mu_I0 = 1.0\ntrue_sigma_I0 = 0.15\nb = true_sigma_I0 * np.random.randn(num_samples) + true_mu_I0\n\nprint('a mean', mean(a))\nprint('a std', stdev(a))\nprint('b mean', mean(b))\nprint('b std', stdev(b))\n\n# %%\n# Testing the result from the sample mean and variance\n# This robust is true when we want to consider the uncertainty in the\n# distribution of the diagnostic index\nrobust = True\n\nC_alpha = 1\nC_beta = 1\nsigma_I = calculating_sigma_I(a)\nsigma_I0 = calculating_sigma_I(b)\nmu_I = calculating_mu_I(a)\nmu_I0 = calculating_mu_I(b)\n\nif robust:\n sigma_I_error = sigma_I / (sqrt(2 * num_samples - 2))\n sigma_I0_error = sigma_I0 / (sqrt(2 * num_samples - 2))\n mu_I_error = sigma_I\n mu_I0_error = sigma_I0\n sigma_I = sigma_I + sigma_I_error\n sigma_I0 = sigma_I0 + sigma_I0_error\n mu_I = mu_I + mu_I_error\n mu_I0_error = mu_I0 - mu_I0_error\n\nsample_optimal_threshold_value = optimal_threshold(mu_I, mu_I0, sigma_I, sigma_I0, C_alpha, C_beta)\nsample_optimal_cost = calculating_optimal_total_cost(C_alpha, C_beta, mu_I0, \n sigma_I0, mu_I, sigma_I)\nprint('Estimated optimal threshold is', sample_optimal_threshold_value,'\\n')\nprint('Estimated optimal cost is', sample_optimal_cost,'\\n')\n\n# %%\n# Testing the result from the population (not from sample)\nC_alpha = 1\nC_beta = 1\nsigma_I = true_sigma_I\nsigma_I0 = true_sigma_I0\nmu_I = true_mu_I\nmu_I0 = true_mu_I0\noptimal_threshold_value = optimal_threshold(mu_I, mu_I0, sigma_I, sigma_I0, C_alpha, C_beta)\noptimal_cost = calculating_optimal_total_cost(C_alpha, C_beta, mu_I0, \n sigma_I0, mu_I, sigma_I)\nprint('True optimal threshold is', optimal_threshold_value,'\\n')\nprint('Estimated optimal threshold is', sample_optimal_threshold_value,'\\n')\n\nprint('True optimal cost is with the true optimal threshold ', optimal_cost,'\\n')\nrobust_optimal_cost = calculating_total_cost(C_alpha, C_beta, mu_I0, sigma_I0, mu_I, \n sigma_I, sample_optimal_threshold_value)\nprint('Estimated optimal cost is with the robust optimal', robust_optimal_cost,'\\n')\n\n# %%\n","sub_path":"testing_regression.py","file_name":"testing_regression.py","file_ext":"py","file_size_in_byte":4889,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"191103112","text":"import os\nimport numpy as np\nimport cv2\nimport Mask_RCNN.mrcnn.config\nimport Mask_RCNN.mrcnn.utils\nimport Mask_RCNN.mrcnn.visualize\nimport matplotlib.image as mpimg\nimport matplotlib.pyplot as plt\n\nfrom Mask_RCNN.mrcnn.model import MaskRCNN\nfrom pathlib import Path\nfrom sklearn.cluster import KMeans\n\n\n# Configuration that will be used by the Mask-RCNN library\nclass MaskRCNNConfig(Mask_RCNN.mrcnn.config.Config):\n NAME = \"coco_pretrained_model_config\"\n IMAGES_PER_GPU = 1\n GPU_COUNT = 1\n NUM_CLASSES = 1 + 80\n DETECTION_MIN_CONFIDENCE = 0.7\n\n\n# Root directory of the project\nROOT_DIR = Path(\".\")\n\n# Directory to save logs and trained model\nMODEL_DIR = os.path.join(ROOT_DIR, \"logs\")\n\n# Local path to trained weights file\nCOCO_MODEL_PATH = os.path.join(ROOT_DIR, \"mask_rcnn_coco.h5\")\n\n# Download COCO trained weights from Releases if needed\nif not os.path.exists(COCO_MODEL_PATH):\n Mask_RCNN.mrcnn.utils.download_trained_weights(COCO_MODEL_PATH)\n\n# Directory of images to run detection on\nIMAGE_DIR = os.path.join(ROOT_DIR, \"images\")\n\n# Create a Mask-RCNN model in inference mode\nmodel = MaskRCNN(mode=\"inference\", model_dir=MODEL_DIR, config=MaskRCNNConfig())\n\n# Load pre-trained model\nmodel.load_weights(COCO_MODEL_PATH, by_name=True)\n\n# class_names = ['BG', 'person', 'bicycle', 'car', 'motorcycle', 'airplane',\n# 'bus', 'train', 'truck', 'boat', 'traffic light',\n# 'fire hydrant', 'stop sign', 'parking meter', 'bench', 'bird',\n# 'cat', 'dog', 'horse', 'sheep', 'cow', 'elephant', 'bear',\n# 'zebra', 'giraffe', 'backpack', 'umbrella', 'handbag', 'tie',\n# 'suitcase', 'frisbee', 'skis', 'snowboard', 'sports ball',\n# 'kite', 'baseball bat', 'baseball glove', 'skateboard',\n# 'surfboard', 'tennis racket', 'bottle', 'wine glass', 'cup',\n# 'fork', 'knife', 'spoon', 'bowl', 'banana', 'apple',\n# 'sandwich', 'orange', 'broccoli', 'carrot', 'hot dog', 'pizza',\n# 'donut', 'cake', 'chair', 'couch', 'potted plant', 'bed',\n# 'dining table', 'toilet', 'tv', 'laptop', 'mouse', 'remote',\n# 'keyboard', 'cell phone', 'microwave', 'oven', 'toaster',\n# 'sink', 'refrigerator', 'book', 'clock', 'vase', 'scissors',\n# 'teddy bear', 'hair drier', 'toothbrush']\n\nVIDEO_SOURCE = \"videos/test_video.MOV\"\n\n# Load the video file we want to run detection on\nvideo_capture = cv2.VideoCapture(VIDEO_SOURCE)\nn_clusters = 2\n\n\n# Filter a list of Mask R-CNN detection results to get only the detected cars / trucks\ndef get_car_boxes(boxes, class_ids, scores):\n car_boxes = []\n\n for i, box in enumerate(boxes):\n # If the detected object isn't a car / truck, skip it\n if class_ids[i] in [3]:\n if scores[i] > 0.8:\n car_boxes.append(box)\n\n return np.array(car_boxes)\n\n\ndef create_mean_points(car_boxes):\n \"\"\"\n Input: car_boxes - a list of parked cars locations in the format (y1, x1, y2, x2)\n Functionality: find avg point (x, y) based on (y1, x1, y2, x2)\n Output: mean_points - an np array of shape (len(car_boxes), 2), where each row is the\n avg point (x, y)\n \"\"\"\n mean_points = np.empty((len(car_boxes), 2))\n for i, box in enumerate(car_boxes):\n y1, x1, y2, x2 = box[0], box[1], box[2], box[3]\n x = (x1 + x2) / 2\n y = (y1 + y2) / 2\n mean_points[i][0] = x\n mean_points[i][1] = y\n\n return mean_points\n\n\ndef create_zones(car_boxes, n_clusters=n_clusters):\n \"\"\"\n Input: car_boxes - a list of parked cars locations in the format (y1, x1, y2, x2)\n n_clusters - number of clusters to form\n Functionality: use k-means clustering to form {n_clusters} different zones\n Output: zones - a list of lists, each list containing cars locations in the format (y1, x1, y2, x2)\n that are in a particular zone\n kmeans - the k-means model used to form the clusters\n \"\"\"\n\n zones = [[] for _ in range(n_clusters)]\n mean_points = create_mean_points(car_boxes)\n\n kmeans = KMeans(n_clusters=n_clusters, init='k-means++')\n kmeans.fit(mean_points)\n centroids = kmeans.cluster_centers_\n for i in range(len(centroids)):\n print(\"Zone {} centroid : {}\".format(i, centroids[i]))\n\n predictions = kmeans.predict(mean_points)\n for i, num in enumerate(predictions):\n zones[num].append(car_boxes[i])\n\n return zones, kmeans\n\n\ndef find_area(zone):\n \"\"\"\n Input: zone - a list containing the cars locations in the format (y1, x1, y2, x2)\n Functionality: find the total area covered by the box of each car in a zone\n Output: total_area of a zone\n \"\"\"\n sorted_by_x = sorted(zone, key=lambda x: x[1])\n\n total_area = 0\n for i, box in enumerate(sorted_by_x):\n y1, x1, y2, x2 = box[0], box[1], box[2], box[3]\n if i != 0:\n prev_box = sorted_by_x[i - 1]\n y1_prev, x1_prev, y2_prev, x2_prev = prev_box[0], prev_box[1], prev_box[2], prev_box[3]\n if x1_prev <= x1 <= x2_prev and y1_prev <= y1 <= y2_prev:\n intersection_width = abs(x2_prev - x1)\n intersection_height = abs(y2_prev - y1)\n total_area -= (intersection_width * intersection_height)\n\n total_area += abs(y2 - y1) * abs(x2 - x1)\n return total_area\n\n\ndef detect_open_space(pred_zone, zone, zone_area):\n \"\"\"\n Input: pred_zone - a list containing the cars locations in the format (y1, x1, y2, x2)\n that are CURRENTLY in the zone\n zone - a list containing the cars locations in the format (y1, x1, y2, x2)\n that were in the ORIGINAL zone\n zone_area - area of the ORIGINAL zone\n Functionality: determine if there are open spaces for a car to park\n Output: a boolean indicating if there is open space for a car\n \"\"\"\n area = find_area(pred_zone)\n if zone_area - area >= zone_area/len(zone):\n print(\"There is space in this zone\")\n return True\n\n print(\"There is no space in this zone\")\n return False\n\n\ncar_boxes = None\nzones = None\nzones_area = []\nzones_free_space_frequency = [0 for i in range(n_clusters)]\nk_means = None\n\n\n# Loop over each frame of video\nwhile video_capture.isOpened():\n success, frame = video_capture.read()\n if not success:\n break\n\n # Convert the image from BGR color (which OpenCV uses) to RGB color\n rgb_image = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)\n cv2.imwrite(\"plot_training_frame.png\", rgb_image)\n plt.imshow(mpimg.imread('plot_training_frame.png'))\n plt.savefig('plot_training_frame.png')\n\n # Run the image through the Mask R-CNN model to get results.\n results = model.detect([rgb_image], verbose=0)\n\n # Mask R-CNN assumes we are running detection on multiple images.\n # We only passed in one image to detect, so only grab the first result.\n r = results[0]\n\n # The r variable will now have the results of detection:\n # - r['rois'] are the bounding box of each detected object\n # - r['class_ids'] are the class id (type) of each detected object\n # - r['scores'] are the confidence scores for each detection\n # - r['masks'] are the object masks for each detected object (which gives you the object outline)\n\n # Filter the results to only grab the car / truck bounding boxes\n car_boxes = get_car_boxes(r['rois'], r['class_ids'], r['scores'])\n for box in car_boxes:\n y1, x1, y2, x2 = box\n\n # Draw the box\n cv2.rectangle(frame, (x1, y1), (x2, y2), (0, 255, 0), 1)\n cv2.imwrite(\"training_frame.png\", frame)\n\n zones, k_means = create_zones(car_boxes)\n for i, zone in enumerate(zones):\n zones_area.append(find_area(zone))\n\n break\n\nprint(\"Zones acquired\")\nfor i, zone in enumerate(zones):\n print(\"Zone {}: {}\".format(i, zone))\n\nNUMBER_FRAMES_PER_SEC = 30\nnum_secs = 2\nframe_in_sec = 0\nsecs = 0\n\n# Loop over each frame of video\nwhile video_capture.isOpened():\n success, frame = video_capture.read()\n if not success:\n break\n\n frame_in_sec += 1\n if frame_in_sec == NUMBER_FRAMES_PER_SEC * num_secs:\n frame_in_sec = 0\n secs += 2\n else:\n continue\n\n print(\"Number of seconds: \", secs)\n\n rgb_image = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)\n\n results = model.detect([rgb_image], verbose=0)\n r = results[0]\n\n curr_car_boxes = get_car_boxes(r['rois'], r['class_ids'], r['scores'])\n for box in curr_car_boxes:\n y1, x1, y2, x2 = box\n cv2.rectangle(frame, (x1, y1), (x2, y2), (0, 255, 0), 1)\n\n curr_mean_points = create_mean_points(curr_car_boxes)\n curr_predictions = k_means.predict(curr_mean_points)\n curr_zones = [[] for _ in range(n_clusters)]\n\n for i, num in enumerate(curr_predictions):\n curr_zones[num].append(curr_car_boxes[i])\n\n for i, zone in enumerate(curr_zones):\n if len(zone) < len(zones[i]):\n zones_free_space_frequency[i] += 1\n if zones_free_space_frequency[i] > 15:\n zones_free_space_frequency[i] = 0\n print(\"Zone Number \", i)\n print(\"New Zone: \", zone)\n print(\"Original Zone: \", zones[i])\n cv2.imwrite(\"frame_secs_{}.png\".format(secs), frame)\n detect_open_space(curr_zones[i], zones[i], zones_area[i])\n\n","sub_path":"parking_detection.py","file_name":"parking_detection.py","file_ext":"py","file_size_in_byte":9490,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"654230317","text":"import json\n\n\nRECOMENDATION_BAD = 'Все очень плохо. И тут даже не до шуток. ' \\\n 'Рекомендуем повышение веса и лечение анерексии. ' \\\n 'ВЫСОКИЙ риск угрозы здоровью.'\nRECOMENDATION_NOT_BAD = 'ОТСУТСТВУЕТ риск для здоровья. ' \\\n 'Однако все же непобходимо чуть-чуть больше кушать.'\nRFECOMENDATION_NORM = 'Все прекрасно. Можете сосредоточиться ' \\\n 'для достижения других жизненных целей)'\nRECOMENDATION_INCREASED = 'ПОВЫШЕННЫЙ риск для здоровья. ' \\\n 'Рекомендуется похудение.'\nRECOMENDATION_HIGHT = 'ВЫСОКИЙ риск для здоровья. ' \\\n 'Настоятельно рекомендуется снижение веса.'\nRECOMENDATION_VERY_HIGHT = 'ОЧЕНЬ ВЫСОКИЙ риск для здоровья. ' \\\n 'Крайне необходимо снижение веса.'\nRECOMENDATION_EXTREMELY_HIGHT = 'ЧРЕЗВЫЧАЙНО ВЫСОКИЙ риск для здоровья. ' \\\n 'Необходимо немедленное снижение массы тела.'\nRECOMENDATION_FOR_MALE = 'Молодой человек, перестаньте играть в игры'\nRECOMENDATION_FOR_FEMALE = 'Юная леди, Вам еще детей рожать'\n\n# функция, которая проверяет есть ли в дирректории с файлом программы\n# текстовый файл. Если его не существует - создает его\ndef is_file():\n try:\n print('Проверка наличия файла для корректной работы программы...')\n with open('list.txt', 'r'):\n print('Все хорошо, файл найден. Начнем работу)')\n return\n except FileNotFoundError:\n with open('list.txt', 'w'):\n print('Создан пустой файл \"list.txt\". Давайте начнем)')\n\n\n# функция для отображения главного меню. Возвращает выбранный пункт меню\ndef menu():\n main_menu = '\\n1. Просмотреть всех пользователей\\n' \\\n '2. Добавить пользователя\\n' \\\n '3. Удалить пользователя\\n' \\\n '4. Редактировать пользователя\\n' \\\n '0. Выход'\n print(main_menu)\n choice = int(input('\\nВыберете пункт меню: '))\n return choice\n\n\n# функция, которая создает рекомендацию о пользователе.\n# Принимает словарь и ключ\ndef recomendation(users, user):\n greeting = ''\n\n # формула для расчета ИМТ (делим рост на 100, что бы расчеты были верны)\n weight = users[user]['weight']\n height = users[user]['height']\n sex = users[user]['sex']\n age = users[user]['age']\n bmi = weight / ((height / 100) ** 2)\n\n # Обращение по полу\n if sex.upper() == 'М':\n greeting = 'Уважаемый {}'\n elif sex.upper() == 'Ж':\n greeting = 'Уважаемая {}'\n\n # вывод на экран с помощью .format\n print('\\n\\n' + greeting.format(user), '\\n'\n 'Ваш рост: {}'.format(height), '\\n'\n 'Ваш вес: {}'.format(weight), '\\n'\n 'Ваш BMI: {}'.format(round(bmi, 2)))\n\n # вывод на экран просто переменных\n print('\\n====Рекомендация====\\n'\n ' - пол:', sex, '\\n'\n ' - возраст:', age, '\\n'\n ' - рост', height, '\\n'\n ' - вес', weight, '\\n\\n')\n\n # рекомендации-константы;)\n if 18 <= age < 26:\n if 0 < bmi < 16:\n if sex == 'М':\n print(RECOMENDATION_BAD, '{}'.format(RECOMENDATION_FOR_MALE))\n else:\n print(RECOMENDATION_BAD, '{}'.format(RECOMENDATION_FOR_FEMALE))\n elif 16 < bmi < 18.5:\n print(RECOMENDATION_NOT_BAD)\n elif 18.5 < bmi < 22.9:\n print(RFECOMENDATION_NORM)\n elif 23 < bmi < 29.9:\n print(RECOMENDATION_INCREASED)\n elif 30 < bmi < 34.9:\n print(RECOMENDATION_HIGHT)\n elif 35 < bmi < 39.9:\n print(RECOMENDATION_VERY_HIGHT)\n elif bmi > 40:\n print(RECOMENDATION_EXTREMELY_HIGHT)\n elif age >= 26:\n if 0 < bmi < 16:\n if sex == 'М':\n print(RECOMENDATION_BAD, '{}'.format(RECOMENDATION_FOR_MALE))\n else:\n print(RECOMENDATION_BAD, '{}'.format(RECOMENDATION_FOR_FEMALE))\n elif 16 < bmi < 18.5:\n print(RECOMENDATION_NOT_BAD)\n elif 18.5 < bmi < 25.9:\n print(RFECOMENDATION_NORM)\n elif 26 < bmi < 30.9:\n print(RECOMENDATION_INCREASED)\n elif 31 < bmi < 35.9:\n print(RECOMENDATION_HIGHT)\n elif 36 < bmi < 40.9:\n print(RECOMENDATION_VERY_HIGHT)\n elif bmi > 41:\n print(RECOMENDATION_EXTREMELY_HIGHT)\n else:\n print('Вы еще слишком малы для таких забот\\n')\n\n # Построение псевдографика\n graph = '0' + '_' * 18 + '18' + '-' * 12 + '30' + '=' * 10 + '40'\n graph = list(graph)\n if int(bmi) > 40:\n graph.append('Х')\n else:\n graph.insert(int(bmi), 'X')\n print(\"\\nПсевдографик:\",\n ''.join(graph), '\\n')\n\n\n# функция для вывода на экран списка ключей словаря\ndef list_users():\n with open('list.txt', 'r') as my_file:\n users_list = []\n if len(my_file.readline()) != 0:\n my_file.seek(0)\n for line in my_file:\n dict_contents = json.loads(line)\n [users_list.append(key) for key in dict_contents.keys()]\n print('\\n--Пользователи--\\n' + ', '.join(users_list) + '\\n')\n\n\n# функция добавления пользователя.\ndef add_user():\n name = input('Введите имя: ')\n age = int(input('Введите возраст: '))\n sex = input('Пол M/F: ').upper()\n while True:\n if sex == 'M' or sex == 'F':\n break\n else:\n print('Поле \"Пол\" должно содержать либо \"M\" либо \"F\"')\n sex = input('Пол M/F: ').upper()\n weight = int(input('Введите вес в кг: '))\n height = int(input('Введите рост в см: '))\n\n # в каждую строчку файла добавляется словарь\n with open('list.txt', 'a+') as my_file:\n dict_contents = {name: {'age': age, 'sex': sex, 'weight': weight, 'height': height}}\n my_file.write(json.dumps(dict_contents))\n my_file.write('\\n')\n print('\\nПользователь {} успешно добавлен\\n'.format(name))\n\n\n# функция удаления пользователя\ndef del_user():\n selected_users = input('\\nвведите имя пользователя, которого необходимо удалить\\n'\n 'или нажмите Enter для выхода в главное меню: ')\n\n # создается пустой словарь. Заполняется значениями из файла. После чего удаляем ззначение инпута\n dict = {}\n with open('list.txt', 'r') as my_file:\n for line in my_file:\n dict_contents = json.loads(line)\n dict.update(dict_contents)\n try:\n del dict[selected_users]\n print('\\nПользователь ' + str(selected_users) + ' успешно удален\\n')\n except KeyError:\n print('\\nПользователя ' + str(selected_users) + ' не существует\\n')\n\n # открываем файл на запись (он пустой, соответственно).\n # Построчно заполняется оставшимся после удаления, словарем\n with open('list.txt', 'w') as my_file:\n for key, value in dict.items():\n my_file.write(json.dumps({key: value}))\n my_file.write('\\n')\n\n\n# Функция редактирования пользователя\ndef edit_user():\n\n # создается список ключей из каждой строчки файла (словарей)\n with open('list.txt', 'r') as my_file:\n users_list = []\n my_file.seek(0)\n for line in my_file:\n dict_contents = json.loads(line)\n [users_list.append(key) for key in dict_contents.keys()]\n print('\\n--Пользователи--\\n' + ', '.join(users_list) + '\\n')\n selected_users = input('введите имя пользователя для просмотра информации о нем: ')\n\n # создается пустой словарь. Заполняется значениями из файла\n dict = {}\n with open('list.txt', 'r') as my_file:\n for line in my_file:\n dict_contents = json.loads(line)\n dict.update(dict_contents)\n if selected_users in dict.keys():\n print('\\n1. Расчитать BMI пользователя'\n '\\n2. Обновить информацию о пользователе\\n'\n '0. Выход в главное меню\\n')\n local_choice = int(input())\n\n if local_choice == 0:\n return\n\n elif local_choice == 1:\n recomendation(dict, selected_users)\n\n elif local_choice == 2:\n age = int(input('Введите возраст: '))\n sex = input('Пол M/F: ').upper()\n while True:\n if sex == 'M' or sex == 'F':\n break\n else:\n print('Поле \"Пол\" должно содержать либо \"M\" либо \"F\"')\n sex = input('Пол М/Ж: ').upper()\n weight = int(input('Введите вес в кг: '))\n height = int(input('Введите рост в см: '))\n\n # обновляет словарь. После чего проходим циклом по словарю и построчно записываем в файл\n dict.update({selected_users: {'age': age, 'sex': sex, 'weight': weight, 'height': height}})\n with open('list.txt', 'w') as my_file:\n for key, value in dict.items():\n my_file.write(json.dumps({key: value}))\n my_file.write('\\n')\n else:\n print('\\nПользователя ' + str(selected_users) + ' не существует\\n')\n return\n\n\n# работа программы\ndef main():\n\n is_file()\n\n while True:\n\n choice = menu()\n\n if choice == 1:\n list_users()\n\n if choice == 2:\n add_user()\n\n if choice == 3:\n del_user()\n\n if choice == 4:\n edit_user()\n\n if choice == 0:\n break\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"BMI.py","file_name":"BMI.py","file_ext":"py","file_size_in_byte":11649,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"116189327","text":"import error\nimport json\nimport log\nimport os\nimport preferences\nimport requests\n\ndef get_license():\n try:\n return preferences.get(\"license\") or download_license()\n except:\n error.error(\"Cannot find license\")\n\ndef download_license():\n url = \"https://www.happymac.app/_functions/agree/?token=%s\" % get_hardware_uuid()\n log.log(\"Getting license from: %s\" % url)\n license = requests.get(url).content\n key = json.loads(license)[\"key\"]\n log.log(\"Received license key: %s\" % key)\n preferences.set(\"license\", key)\n return key\n\ndef get_hardware_uuid():\n return os.popen(\"system_profiler SPHardwareDataType | grep UUID | sed 's/.* //' \").read()\n","sub_path":"src/license.py","file_name":"license.py","file_ext":"py","file_size_in_byte":680,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"63343591","text":"#-------------------------------------------------------------------------------\n# Name: module1\n# Purpose:\n#\n# Author: Karanjot\n#\n# Created: 02/02/2017\n# Copyright: (c) Karanjot 2017\n# Licence: \n#-------------------------------------------------------------------------------\n#modify chaos program so that the number of values to print is determined by the user\ndef main():\n n = eval(input(\"how many numbers should i print\"))\n x = eval(input(\"Choose a number between 1 + 2\"))\n for i in range(n):\n x= 3.9 * x * (1 - x)\n print (x)\n\nmain()","sub_path":"1.5.py","file_name":"1.5.py","file_ext":"py","file_size_in_byte":598,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"210069529","text":"import json\nimport pprint\nfrom websocket import create_connection\n\npath=\"streaming\"\nurl = \"ws://localhost:8080/\"+path\ndata = {}\nmessageBody = {\n \"apikey\":\"test-api-key\",\n \"event\":\"subscribe\",\n \"type\":\"get_blocks\",\n \"data\":data\n}\nws = create_connection(url)\nws.send(json.dumps(messageBody))\n\nwhile True:\n pprint.pprint(json.loads(ws.recv()))\nws.close()","sub_path":"py_scripts/SubscriberRequst_GetBlock.py","file_name":"SubscriberRequst_GetBlock.py","file_ext":"py","file_size_in_byte":366,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"228768581","text":"\"\"\"\n datetime Exercise:\n Create a program that will get date of the next monday from today\n\"\"\"\nfrom datetime import datetime, timedelta, date\n\n\ncurrent = date.today()\nprint(current)\n# next_monday = current + timedelta(days=-current.weekday(), weeks=1) # or\n\nnext_monday = current + timedelta(7 - current.weekday())\n# next_sunday = current + timedelta(days=-current.weekday(), weeks=1)\nprint(next_monday) # 2019-11-18\n# print(next_sunday)\n\n\n# or, with list comprehension\n\nnext_monday2 = [\n current + timedelta(days=x)\n for x in range(0, 7)\n if (current + timedelta(days=x)).weekday() % 7 == 0\n]\n\nprint(next_monday2) # [datetime.date(2019, 11, 18)]\n","sub_path":"activities/datetime_next_monday.py","file_name":"datetime_next_monday.py","file_ext":"py","file_size_in_byte":666,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"448902980","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\ndef read_input():\n rules = {}\n f = open(\"input\")\n for l in f:\n if not l.strip():\n break\n rule_num, branche_str = l.strip().split(':')\n branches = [b.strip().split() for b in branche_str.split(' | ')]\n rules[int(rule_num)] = [[int(b) if b.isdigit() else eval(b) for b in bl] for bl in branches]\n\n strings = []\n for l in f:\n strings.append(l.strip())\n return rules, strings\n\ndef matches(s, s_i, rules, starting_rule):\n if s_i >= len(s):\n return False, s_i\n rule = rules[starting_rule]\n for branch in rule:\n n_i = s_i\n for subrule in branch:\n if isinstance(subrule, str):\n matched, n_i = s[s_i] == subrule, s_i + 1\n else:\n matched, n_i = matches(s, n_i, rules, subrule)\n if not matched:\n break\n if matched:\n return True, n_i\n return False, s_i\n\ndef main():\n rules, strings = read_input()\n matched = 0\n for s in strings:\n for (n,m) in [(n,m) for n in range(1, 10) for m in range(1, 10)]:\n rules[8] = [[42] * (n)]\n rules[11] = [[42] * (m) + [31] * (m)]\n match, processed = matches(s, 0, rules, 0)\n if (match):\n matched += (match and processed == len(s))\n break\n print(matched)\n\nif __name__ == '__main__':\n main()\n","sub_path":"day19/part02.py","file_name":"part02.py","file_ext":"py","file_size_in_byte":1444,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"616752255","text":"#!/usr/bin/env python3\n\n\"\"\"\nCS373: Exercise #8b\n\"\"\"\n\n\"\"\" ----------------------------------------------------------------------\nDefine the function my_list(), such that it behaves as follows:\n\"\"\"\n\n# https://docs.python.org/3.4/tutorial/datastructures.html\n\nclass my_list :\n def __init__ (self) :\n self.a = []\n\n def __iter__ (self) :\n for v in self.a :\n yield v\n\n def append (self, v) :\n self.a.append(v)\n\ndef test (c) :\n x = c()\n x.append(2)\n x.append(3)\n x.append(4)\n assert not hasattr(x, \"__next__\")\n assert hasattr(x, \"__iter__\")\n\n p = iter(x)\n assert hasattr(p, \"__next__\")\n assert hasattr(p, \"__iter__\")\n assert iter(p) is p\n\n assert next(p) == 2\n assert next(p) == 3\n assert next(p) == 4\n\n try :\n assert next(p) == 5\n except StopIteration :\n pass\n\nprint(\"Exercise8b.py\")\n\ntest(my_list)\ntest( list)\n\nprint(\"Done.\")\n","sub_path":"exercises/Exercise8b.py","file_name":"Exercise8b.py","file_ext":"py","file_size_in_byte":927,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"303358368","text":"# Licensed to the Apache Software Foundation (ASF) under one or more\n# contributor license agreements. See the NOTICE file distributed with\n# this work for additional information regarding copyright ownership.\n# The ASF licenses this file to You under the Apache License, Version 2.0\n# (the \"License\"); you may not use this file except in compliance with\n# the License. You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nimport sys\nfrom libcloud.utils.py3 import httplib\n\nfrom libcloud.common.types import InvalidCredsError\nfrom libcloud.backup.drivers.dimensiondata import DimensionDataBackupDriver as DimensionData\n\nfrom libcloud.test import MockHttp, unittest\nfrom libcloud.test.backup import TestCaseMixin\nfrom libcloud.test.file_fixtures import BackupFileFixtures\n\nfrom libcloud.test.secrets import DIMENSIONDATA_PARAMS\n\n\nclass DimensionDataTests(unittest.TestCase, TestCaseMixin):\n\n def setUp(self):\n DimensionData.connectionCls.conn_classes = (None, DimensionDataMockHttp)\n DimensionDataMockHttp.type = None\n self.driver = DimensionData(*DIMENSIONDATA_PARAMS)\n\n def test_invalid_region(self):\n with self.assertRaises(ValueError):\n self.driver = DimensionData(*DIMENSIONDATA_PARAMS, region='blah')\n\n def test_invalid_creds(self):\n DimensionDataMockHttp.type = 'UNAUTHORIZED'\n with self.assertRaises(InvalidCredsError):\n self.driver.list_targets()\n\n def test_list_targets(self):\n targets = self.driver.list_targets()\n self.assertEqual(len(targets), 2)\n self.assertEqual(targets[0].id, '5579f3a7-4c32-4cf5-8a7e-b45c36a35c10')\n self.assertEqual(targets[0].address, 'e75ead52-692f-4314-8725-c8a4f4d13a87')\n self.assertEqual(targets[0].extra['servicePlan'], 'Enterprise')\n\n def test_create_target(self):\n target = self.driver.create_target(\n 'name',\n 'e75ead52-692f-4314-8725-c8a4f4d13a87',\n extra={'servicePlan': 'Enterprise'})\n self.assertEqual(target.id, 'ee7c4b64-f7af-4a4f-8384-be362273530f')\n self.assertEqual(target.address, 'e75ead52-692f-4314-8725-c8a4f4d13a87')\n self.assertEqual(target.extra['servicePlan'], 'Enterprise')\n\n def test_update_target(self):\n target = self.driver.list_targets()[0]\n extra = {'servicePlan': 'Enterprise'}\n new_target = self.driver.update_target(target, extra=extra)\n self.assertEqual(new_target.extra['servicePlan'], 'Enterprise')\n\n def test_delete_target(self):\n target = self.driver.list_targets()[0]\n self.assertTrue(self.driver.delete_target(target))\n\n def test_ex_list_available_client_types(self):\n target = self.driver.list_targets()[0]\n answer = self.driver.ex_list_available_client_types(target)\n self.assertEqual(len(answer), 1)\n self.assertEqual(answer[0].type, 'FA.Linux')\n self.assertEqual(answer[0].is_file_system, True)\n self.assertEqual(answer[0].description, 'Linux File system')\n\n def test_ex_list_available_storage_policies(self):\n target = self.driver.list_targets()[0]\n answer = self.driver.ex_list_available_storage_policies(target)\n self.assertEqual(len(answer), 1)\n self.assertEqual(answer[0].name,\n '30 Day Storage Policy + Secondary Copy')\n self.assertEqual(answer[0].retention_period, 30)\n self.assertEqual(answer[0].secondary_location, 'Primary')\n\n def test_ex_list_available_schedule_policies(self):\n target = self.driver.list_targets()[0]\n answer = self.driver.ex_list_available_schedule_policies(target)\n self.assertEqual(len(answer), 1)\n self.assertEqual(answer[0].name, '12AM - 6AM')\n self.assertEqual(answer[0].description, 'Daily backup will start between 12AM - 6AM')\n\n\nclass InvalidRequestError(Exception):\n def __init__(self, tag):\n super(InvalidRequestError, self).__init__(\"Invalid Request - %s\" % tag)\n\n\nclass DimensionDataMockHttp(MockHttp):\n\n fixtures = BackupFileFixtures('dimensiondata')\n\n def _oec_0_9_myaccount_UNAUTHORIZED(self, method, url, body, headers):\n return (httplib.UNAUTHORIZED, \"\", {}, httplib.responses[httplib.UNAUTHORIZED])\n\n def _oec_0_9_myaccount(self, method, url, body, headers):\n body = self.fixtures.load('oec_0_9_myaccount.xml')\n return (httplib.OK, body, {}, httplib.responses[httplib.OK])\n\n def _oec_0_9_myaccount_INPROGRESS(self, method, url, body, headers):\n body = self.fixtures.load('oec_0_9_myaccount.xml')\n return (httplib.OK, body, {}, httplib.responses[httplib.OK])\n\n def _caas_2_1_8a8f6abc_2745_4d8a_9cbc_8dabe5a7d0e4_server_server(self, method, url, body, headers):\n body = self.fixtures.load(\n 'caas_2_1_8a8f6abc_2745_4d8a_9cbc_8dabe5a7d0e4_server_server.xml')\n return (httplib.OK, body, {}, httplib.responses[httplib.OK])\n\n def _oec_0_9_8a8f6abc_2745_4d8a_9cbc_8dabe5a7d0e4_server_e75ead52_692f_4314_8725_c8a4f4d13a87_backup_client_type(self, method, url, body, headers):\n body = self.fixtures.load(\n 'oec_0_9_8a8f6abc_2745_4d8a_9cbc_8dabe5a7d0e4_server_e75ead52_692f_4314_8725_c8a4f4d13a87_backup_client_type.xml')\n return (httplib.OK, body, {}, httplib.responses[httplib.OK])\n\n def _oec_0_9_8a8f6abc_2745_4d8a_9cbc_8dabe5a7d0e4_server_e75ead52_692f_4314_8725_c8a4f4d13a87_backup_client_storagePolicy(\n self, method, url, body, headers):\n body = self.fixtures.load(\n 'oec_0_9_8a8f6abc_2745_4d8a_9cbc_8dabe5a7d0e4_server_e75ead52_692f_4314_8725_c8a4f4d13a87_backup_client_storagePolicy.xml')\n return (httplib.OK, body, {}, httplib.responses[httplib.OK])\n\n def _oec_0_9_8a8f6abc_2745_4d8a_9cbc_8dabe5a7d0e4_server_e75ead52_692f_4314_8725_c8a4f4d13a87_backup_client_schedulePolicy(\n self, method, url, body, headers):\n body = self.fixtures.load(\n 'oec_0_9_8a8f6abc_2745_4d8a_9cbc_8dabe5a7d0e4_server_e75ead52_692f_4314_8725_c8a4f4d13a87_backup_client_schedulePolicy.xml')\n return (httplib.OK, body, {}, httplib.responses[httplib.OK])\n\n def _oec_0_9_8a8f6abc_2745_4d8a_9cbc_8dabe5a7d0e4_server_e75ead52_692f_4314_8725_c8a4f4d13a87_backup(\n self, method, url, body, headers):\n body = self.fixtures.load(\n 'oec_0_9_8a8f6abc_2745_4d8a_9cbc_8dabe5a7d0e4_server_e75ead52_692f_4314_8725_c8a4f4d13a87_backup.xml')\n return (httplib.OK, body, {}, httplib.responses[httplib.OK])\n\n def _oec_0_9_8a8f6abc_2745_4d8a_9cbc_8dabe5a7d0e4_server_e75ead52_692f_4314_8725_c8a4f4d13a87_backup_modify(\n self, method, url, body, headers):\n body = self.fixtures.load(\n 'oec_0_9_8a8f6abc_2745_4d8a_9cbc_8dabe5a7d0e4_server_e75ead52_692f_4314_8725_c8a4f4d13a87_backup_modify.xml')\n return (httplib.OK, body, {}, httplib.responses[httplib.OK])\n\n\nif __name__ == '__main__':\n sys.exit(unittest.main())\n","sub_path":"libcloud/test/backup/test_dimensiondata.py","file_name":"test_dimensiondata.py","file_ext":"py","file_size_in_byte":7301,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"379881679","text":"import matplotlib.pyplot as plt\nimport numpy as np\nfrom scipy import ndimage as ndi\nimport cv2\n\nfrom skimage import data\nfrom skimage.util import img_as_float\nfrom skimage.filters import gabor_kernel\nimport matplotlib.pyplot as plt\n\n\n'''\nMódulo inspirado en el código expuesto en:\nhttps://scikit-image.org/docs/0.12.x/auto_examples/features_detection/plot_gabor.html\n'''\n\n\ndef GaborFunctions(sigma, frequency, angles):\n kernels = []\n for theta in range(angles):\n theta = theta / angles * np.pi\n kernel = np.real(gabor_kernel(frequency, theta=theta,\n sigma_x=sigma, sigma_y=sigma))\n kernels.append(kernel)\n\n return kernels\n\n\ndef GaborFeatures(img, sigma=5, frequency=.25, angles=4):\n kernels = GaborFunctions(sigma, frequency, angles)\n\n feats = np.zeros((3*len(kernels)), dtype=np.double)\n for k, kernel in enumerate(kernels):\n filtered = ndi.convolve(img, kernel, mode='wrap')\n feats[3*k] = filtered.mean()\n feats[3*k + 1] = filtered.var()\n feats[3*k + 2] = filtered.sum()\n\n return feats\n\n\ndef showKernels(sigma=5, frequency=.25, angles=4):\n kernels = GaborFunctions(sigma, frequency, angles)\n\n for k, kernel in enumerate(kernels):\n plt.figure()\n plt.imshow(kernel, cmap='gray', vmin=kernel.min(), vmax=kernel.max())\n plt.show()\n\n\nif __name__ == '__main__':\n showKernels()\n","sub_path":"Tarea 2/utils/gabor.py","file_name":"gabor.py","file_ext":"py","file_size_in_byte":1408,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"307311716","text":"import numpy as np\nfrom utils.shortest_path import PriorityQueueWithFunction\nimport scipy.io as sio\nimport json\n\nclass Dirichlet_Multimodel_Graph():\n def __init__(self, num_nodes, num_categories, gamma):\n self.num_nodes = num_nodes\n self.num_categories = num_categories\n self.graph = np.zeros((num_nodes, num_nodes, num_categories)) # posterior\n self.params = np.zeros((num_nodes, num_nodes, num_categories)) # alpha\n self.gamma = gamma\n\n def set_params(self, params):\n assert params.shape == (self.num_nodes, self.num_nodes, self.num_categories)\n self.params = params\n self.graph = params\n\n\n def update_graph(self, exp_counts):\n assert exp_counts.shape == (self.num_nodes, self.num_nodes, self.num_categories)\n alpha0 = np.sum(self.params, axis=2, keepdims=True)\n N = np.sum(exp_counts, axis=2, keepdims=True)\n self.graph = (self.params + exp_counts)/(alpha0+N)\n\n\n def get_expectation(self, ni, nj):\n prob = self.graph[ni, nj, :]\n values = [self.gamma ** k for k in range(self.num_categories-1)]\n values.append(0)\n return sum(prob*values)\n\n\n def plan(self, ns, nt):\n if ns == nt:\n return [ns], 1 #self.get_expectation(ns, nt)\n\n def priorityFunction(item):\n return -item[-1][1]\n\n # queue item: a list of (node, accumulated discounted reward)\n queue = PriorityQueueWithFunction(priorityFunction)\n queue.push([(ns, 1)])\n visited_nodes = []\n while not queue.isEmpty():\n item = queue.pop()\n (nc, reward) = item[-1]\n if nc == nt:\n trajectory = [i[0] for i in item]\n return trajectory, reward #*self.get_expectation(nc, nt)\n if nc not in visited_nodes:\n visited_nodes.append(nc)\n for ni in range(self.num_nodes):\n if ni != nc:\n new_reward = reward*self.get_expectation(nc, ni)\n new_item = item[:]\n new_item.append((ni, new_reward))\n queue.push(new_item)\n return None, None\n\n def dijkstra_plan(self, ns_list, nt):\n rewards = [-1 for _ in range(self.num_nodes)]\n previous_node = [None for _ in range(self.num_nodes)]\n rewards[nt] = 1 # self.get_expectation(nt, nt)\n seen = []\n while sum([ns in seen for ns in ns_list]) < len(ns_list):\n max_reward = -1\n nt = -1\n for i, r in enumerate(rewards):\n if i not in seen and max_reward < r:\n max_reward = r\n nt = i\n seen.append(nt)\n for ni in range(self.num_nodes):\n if ni not in seen and rewards[nt] * self.get_expectation(ni, nt) > rewards[ni]:\n rewards[ni] = rewards[nt] * self.get_expectation(ni, nt)\n previous_node[ni] = nt\n all_trajectories = []\n all_rewards = []\n for ns in ns_list:\n trajectory = []\n n = ns\n while n != None:\n trajectory.append(n)\n n = previous_node[n]\n all_trajectories.append(trajectory)\n all_rewards.append(rewards[ns])\n return all_trajectories, all_rewards\n\n def save(self,\n file_path):\n matdata = {'graph': self.graph}\n sio.savemat(file_path, matdata)\n\n\n\nif __name__ == '__main__':\n pass\n\n\n\n\n\n\n\n","sub_path":"DQN/graph.py","file_name":"graph.py","file_ext":"py","file_size_in_byte":3522,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"7543335","text":"import unittest\n\n\ndef dutch_partition_naive(a, i):\n high, low, pivot = [], [], []\n for item in a:\n if item < a[i]:\n low.append(item)\n elif item > a[i]:\n high.append(item)\n else:\n pivot.append(item)\n\n return low + pivot + high\n\n\ndef dutch_partition(a, i):\n pivot = a[i]\n low, high = 0, len(a) - 1\n for j in range(low, len(a)):\n if a[j] < pivot:\n a[j], a[low] = a[low], a[j]\n low += 1\n for j in range(high, low, -1):\n if a[j] > pivot:\n a[j], a[high] = a[high], a[j]\n high -= 1\n\n return a\n\n\nclass TestSolutions(unittest.TestCase):\n\n def setUp(self):\n self.array = [4, 8, 2, 9, 4, 5, 1, 0, 5, 3, 4]\n\n def test_1(self):\n a = dutch_partition_naive(self.array, 0)\n self.assertEqual(a, [2, 1, 0, 3, 4, 4, 4, 8, 9, 5, 5])\n\n def test_2(self):\n a = dutch_partition(self.array, 0)\n\n first = a.index(4)\n small = [item for item in a[:first] if item > 4]\n self.assertEqual(small, [])\n\n last = len(a) - 1 - a[::-1].index(4)\n big = [item for item in a[last:] if item < 4]\n self.assertEqual(big, [])\n\n self.assertEqual(a[first:last+1], [4, 4, 4])\n\nif __name__ == '__main__':\n unittest.main()\n","sub_path":"epi/ch6/6_1.py","file_name":"6_1.py","file_ext":"py","file_size_in_byte":1299,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"251323187","text":"#coding=utf-8\n#Head_First_Python第一章-数据保存到文件\nimport io\nman = []\nother = []\ntry :\n date = open('sketch.txt')\n for each_item in date:\n try:\n (role, line_spoken) = each_item.split(':',1)\n line_spoken = line_spoken.split()\n if role == 'Man':\n man.append(line_spoken)\n elif role == 'Other Man':\n other.append(line_spoken)\n except ValueError:\n pass\n date.close()\n\nexcept IOError:\n print ('The date file is missing')\n\nprint (man)\nprint (other)\n","sub_path":"Chapter4/1.py","file_name":"1.py","file_ext":"py","file_size_in_byte":567,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"645964146","text":"from zaf.component.decorator import component, requires\n\nfrom ..util import assert_danger_alert_is_shown, assert_has_title, assert_success_alert_is_shown\n\n\n@component\n@requires(page_loader=\"PageLoader\", args=['http://localhost/network_ip_redirect'])\nclass IpRedirectPage(object):\n\n def __init__(self, page_loader):\n self._page_loader = page_loader\n\n @property\n def page(self):\n return self._page_loader.page\n\n def add(self, ip, port, destination_ip, destination_port, protocol, expect_success=True):\n page = self.page\n ip_input = page.find_element_by_name('ip')\n port_input = page.find_element_by_name('port')\n destination_ip_input = page.find_element_by_name('destination_ip')\n destination_port_input = page.find_element_by_name('destination_port')\n protocol_input = page.find_element_by_name('protocol')\n ip_input.clear()\n port_input.clear()\n destination_ip_input.clear()\n destination_port_input.clear()\n ip_input.send_keys(ip)\n port_input.send_keys(port)\n destination_ip_input.send_keys(destination_ip)\n destination_port_input.send_keys(destination_port)\n for option in protocol_input.find_elements_by_tag_name('option'):\n if option.text == protocol:\n option.click()\n page.find_element_by_id('submit').click()\n if expect_success:\n assert_success_alert_is_shown(page)\n else:\n assert_danger_alert_is_shown(page)\n\n def remove(self, ip, port, destination_ip, destination_port, protocol):\n page = self.page\n page.find_element_by_id(\n 'remove_{ip}_{port}_{destination_ip}_{destination_port}_{protocol}'.format(\n ip=ip,\n port=port,\n destination_ip=destination_ip,\n destination_port=destination_port,\n protocol=protocol)).click()\n assert_success_alert_is_shown(page)\n\n def get(self):\n page = self.page\n ip_redirect = []\n rows = page.find_elements_by_tag_name('tr')\n for row in rows[1:]:\n columns = row.find_elements_by_tag_name('td')\n ip_redirect.append(\n (\n columns[0].text, int(columns[1].text), columns[2].text, int(columns[3].text),\n columns[4].text))\n return ip_redirect\n\n\n@requires(znail=\"Znail\")\n@requires(ip_redirect_page=\"IpRedirectPage\")\ndef test_load_page(znail, ip_redirect_page):\n assert_has_title(ip_redirect_page.page, 'Network IP Redirect')\n\n\n@requires(ip_redirect_page=\"IpRedirectPage\")\ndef test_add_to_network_ip_redirect(Znail, ip_redirect_page):\n with Znail():\n ip_redirect_page.add('1.2.3.4', 80, '4.3.2.1', 8080, 'UDP')\n\n\n@requires(znail=\"Znail\")\n@requires(ip_redirect_page=\"IpRedirectPage\")\ndef test_get_network_ip_redirect(znail, ip_redirect_page):\n assert len(ip_redirect_page.get()) == 0\n\n\n@requires(znail=\"Znail\")\n@requires(ip_redirect_page=\"IpRedirectPage\")\ndef test_set_and_get_network_ip_redirect(znail, ip_redirect_page):\n ip_redirect_page.add('1.2.3.4', 80, '4.3.2.1', 8080, 'UDP')\n ip_redirect_page.add('4.3.2.1', 81, '1.2.3.4', 82, 'TCP')\n assert ip_redirect_page.get() == [\n ('1.2.3.4', 80, '4.3.2.1', 8080, 'udp'),\n ('4.3.2.1', 81, '1.2.3.4', 82, 'tcp'),\n ]\n\n\n@requires(znail=\"Znail\")\n@requires(ip_redirect_page=\"IpRedirectPage\")\ndef test_remove_item_from_network_ip_redirect(znail, ip_redirect_page):\n ip_redirect_page.add('1.2.3.4', 80, '4.3.2.1', 8080, 'UDP')\n ip_redirect_page.remove('1.2.3.4', 80, '4.3.2.1', 8080, 'udp')\n assert len(ip_redirect_page.get()) == 0\n\n\n@requires(znail=\"Znail\")\n@requires(ip_redirect_page=\"IpRedirectPage\")\ndef test_remove_multiple_items_from_network_ip_redirect(znail, ip_redirect_page):\n ip_redirect_page.add('1.2.3.4', 80, '4.3.2.1', 8080, 'UDP')\n ip_redirect_page.add('1.2.3.4', 80, '4.3.2.1', 8080, 'TCP')\n ip_redirect_page.remove('1.2.3.4', 80, '4.3.2.1', 8080, 'tcp')\n assert ip_redirect_page.get() == [('1.2.3.4', 80, '4.3.2.1', 8080, 'udp')]\n ip_redirect_page.remove('1.2.3.4', 80, '4.3.2.1', 8080, 'udp')\n assert len(ip_redirect_page.get()) == 0\n\n\n@requires(znail=\"Znail\")\n@requires(ip_redirect_page=\"IpRedirectPage\")\ndef test_invalid_input(znail, ip_redirect_page):\n ip_redirect_page.add('a.b.c.d', -1, 'a.b.c.d', -2, 'tcp', expect_success=False)\n","sub_path":"systest/debtests/pages/network_ipredirect.py","file_name":"network_ipredirect.py","file_ext":"py","file_size_in_byte":4417,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"232390329","text":"# Challenge 4, chapter_5\n# Author: Alton Stillwell\n# Date: 11/19/14\n#########################\n# Variables/ Dictionary\npairs = {\"Scooby Doo\":[\"Brian\",\"Snoopy\"],\"Luke\":[\"Vader\",\"George Lucas\"]}\n# Initiating loop\nprint()\nprint(\"\"\"---MENU---\n0-----Quit\n1----Query\n2------Add\n3--Replace\n4---Delete\n\"\"\")\nchoice = int(input(\"Enter option number: \"))\nwhile choice != 0:\n if choice == 1:\n son = input(\"\\nWhich name would you like to query? \")\n if son in pairs:\n print(son+\"'s father is\",pairs[son][0])\n print(son+\"'s grandfather is\",pairs[son][1])\n else:\n print(\"Name not found\")\n elif choice == 2:\n son = input(\"\\nEnter son's name: \")\n if son not in pairs:\n father = input(\"Enter father's name: \")\n grandFather = input(\"Enter grandfather's name: \")\n pairs[son] = [\"\",\"\"]\n pairs[son][0]=father\n pairs[son][1]=grandFather\n print(son,\"has been added\")\n else:\n print(\"That term already exists! Try redefining it.\")\n elif choice == 3:\n son = input(\"\\nWhat father-son pair do you want to redefine(enter name of son)? \")\n if son in pairs:\n father = input(\"What is the new father? \")\n pairs[son][0] = father\n grandFather = input(\"What is the new father? \")\n pairs[son][1] = grandFather\n print(son,\"has been redefined\")\n else:\n print(\"That name doesn't exist! Try adding it.\")\n elif choice == 4:\n son = input(\"\\nWhat father-son pair do you want to delete? \")\n if son in pairs:\n del pairs[son]\n print(\"Successfully deleted\",son)\n else:\n print(son,\"not found!\")\n else:\n print(\"\\nInvalid choice!\")\n print()\n print(\"\"\"---MENU---\n0-----Quit\n1----Query\n2------Add\n3--Replace\n4---Delete\n\"\"\")\n choice = int(input(\"Enter option number: \"))\n# Final output\nprint()\ninput(\"Press to close\")\n","sub_path":"Challenge4.py","file_name":"Challenge4.py","file_ext":"py","file_size_in_byte":1993,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"25944766","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Sat Mar 23 12:58:24 2019\r\n\r\n@author: Daniel\r\n\"\"\"\r\n\r\ndef zero_matrix(matrix):\r\n isZeroRow = False\r\n isZeroCol = False\r\n \r\n for val in matrix:\r\n if val == 0:\r\n isZeroRow = True\r\n for val in matrix[0]:\r\n if val == 0:\r\n isZeroCol = True \r\n \r\n for i in range (1, len(matrix)):\r\n for j in range(1, len(matrix[0])):\r\n if matrix[i][j] == 0:\r\n matrix[i][0] = 0\r\n matrix[0][j] = 0\r\n for i in range(1, len(matrix)):\r\n for j in range(1, len(matrix[0])):\r\n if (matrix[i][0] == 0) or (matrix[0][j] == 0):\r\n matrix[i][j] = 0\r\n \r\n if isZeroRow:\r\n for i in range(0, len(matrix)):\r\n matrix[i][0] = 0\r\n if isZeroCol:\r\n for j in range(0, len(matrix[0])):\r\n matrix[0][j] = 0\r\n \r\n print(matrix)\r\n return\r\n \r\n \r\n \r\n \r\n \r\ndef main():\r\n matrix = [[1,2,0],[4,0,6],[7,8,9], [10,11,12]]\r\n\r\n zero_matrix(matrix)\r\nmain()","sub_path":"Python/Arrays and Strings/1_8_Zero_Matrix.py","file_name":"1_8_Zero_Matrix.py","file_ext":"py","file_size_in_byte":1084,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"165647678","text":"from django.urls import path, include\n\nfrom contact_app.views import ContactUsView, LetterSentView\nfrom contact_app.contact_api.views import ContactUsAPIView\n\napp_name = 'contact_app'\n\nurlpatterns = [\n path('contact-us/', include([\n path('send-letter', ContactUsView.as_view(), name='contact-us'),\n path('', ContactUsAPIView.as_view(), name='contact_us'),\n path('letter-sent/', LetterSentView.as_view(), name='letter_sent'),\n ])),\n]\n","sub_path":"city_project/contact_app/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":460,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"491170958","text":"import time\n\nimport ircd\n\nCOMMAND_LIST = []\n\n\nclass Command:\n @staticmethod\n def register(name, handler, flags, min_params):\n cmd = Command(name, handler, flags, min_params)\n COMMAND_LIST.append(cmd)\n\n def __init__(self, name, handler, flags_needed, min_params):\n self.name = name\n self.handler = handler\n self.flags_needed = flags_needed\n self.min_params = min_params\n\n self.use_count = 0\n self.total_bytes = 0\n\n def process_parameters(self, parameters):\n paramlist = []\n parameters = parameters.strip()\n if parameters[0] == \":\":\n return 1, parameters[1:]\n if parameters:\n if not parameters.count(\" \") or parameters[0] == \":\":\n paramlist = [parameters]\n if not parameters.count(\" \") and parameters[0] == \":\":\n paramlist[0] = paramlist[0][1:]\n return 1, paramlist\n c = 0\n for i, v in enumerate(parameters):\n if v == \" \":\n parameter = parameters[c:i + 1].strip()\n if parameter[0] == \":\":\n c += 1\n break\n paramlist.append(parameter)\n c = i + 1\n if parameters[c] == \":\":\n c += 1\n paramlist.append(parameters[c:].strip())\n return len(paramlist), paramlist\n\n @staticmethod\n def process_command(user, line):\n global COMMAND_LIST\n line = line.strip()\n if not line:\n return\n\n parameters = \"\"\n paramlist = []\n if not line.count(\" \"):\n items = 0\n cmd = line.upper()\n paramlist = None\n else:\n ind = line.find(\" \")\n cmd = line[:ind].upper()\n parameters = line[ind + 1:]\n\n for command in COMMAND_LIST:\n if command.name == cmd:\n if parameters:\n items, paramlist = command.process_parameters(parameters)\n else:\n items = 0\n paramlist = None\n\n user.lastactive = time.time()\n user.nping = user.lastactive + 120\n\n if items < command.min_params:\n ircd.logger.debug(\n \"process_command: Not enough parameters: %s\"\n % command.name)\n user.send_serv(\"461 %s %s :Not enough parameters\" %\n (user.nickname, command.name))\n return\n # TODO flags_needed\n allowed = [\"USER\", \"NICK\", \"PASS\"]\n if command.name not in allowed and not user.nickname:\n ircd.logger.debug(\n \"process_command: You have not registered: %s\"\n % command.name)\n user.send_serv(\n \"451 %s :You have not registered\" % command.name)\n return\n if command.handler:\n command.use_count += 1\n # TODO total_bytes\n command.handler(paramlist, items, user)\n return\n\n ircd.logger.debug(\"process_command: Not in table: %s\" % cmd)\n user.send_serv(\"421 %s %s :Unknown command\" % (user.nickname, cmd))\n\n\ndef setup_command_table():\n \"\"\"\n Populates the command table with commands using the `Command.register`\n function.\n \"\"\"\n\n Command.register(\"JOIN\", handle_join, 0, 1)\n Command.register(\"MOTD\", handle_motd, 0, 0)\n Command.register(\"MODE\", handle_mode, 0, 1)\n Command.register(\"NAMES\", handle_names, 0, 1)\n Command.register(\"NICK\", handle_nick, 0, 1)\n Command.register(\"PART\", handle_part, 0, 1)\n Command.register(\"PASS\", handle_pass, 0, 1)\n Command.register(\"PING\", handle_ping, 0, 1)\n Command.register(\"PONG\", handle_pong, 0, 1)\n Command.register(\"QUIT\", handle_quit, 0, 1)\n Command.register(\"PRIVMSG\", handle_privmsg, 0, 2)\n Command.register(\"TOPIC\", handle_topic, 0, 1)\n Command.register(\"USER\", handle_user, 0, 4)\n Command.register(\"WHO\", handle_who, 0, 1)\n # TODO finish all commands\n\n\ndef handle_join(args, pcnt, user):\n channels = args[0].split(\",\")\n keys = [\"\"] * len(channels)\n if pcnt > 1:\n keys = args[1].split(\",\")\n if len(keys) < len(channels):\n keys += [\"\"] + (len(channels) - len(keys))\n channels = zip(channels, keys)\n\n for channel in channels:\n user.join(*channel)\n\n\ndef handle_mode(args, pcnt, user):\n dests = ircd.models.User.get_by_nick(args[0])\n outpars, direction = \"\", 1\n if dests and pcnt == 1:\n user.send_serv(\"221 %s :+%s\" % (user.nickname, user.modes))\n return\n if dests and pcnt > 1:\n for dest in dests:\n can_change = 0\n if ircd.models.User.same_nick(user.nickname,\n dest.nickname) or \"o\" in user.modes:\n can_change = 1\n if not can_change:\n user.send_serv(\"482 %s :Can't change mode for other users.\"\n % user.nickname)\n return\n\n\ndef handle_motd(args, pcnt, user):\n user.motd()\n\n\ndef handle_names(args, pcnt, user):\n channel = ircd.models.Channel.get(args[0])\n if channel:\n user.userlist(channel)\n user.send_serv(\"366 %s %s :End of /NAMES list.\"\n % (user.nickname, channel.name))\n else:\n user.send_serv(\"401 %s %s :No suck nick/channel.\"\n % (user.nickname, args[0]))\n\n\ndef handle_nick(args, pcnt, user):\n if pcnt < 1:\n ircd.logger.debug(\"Not enough params for handle_nick.\")\n return\n if not args[0]:\n ircd.logger.debug(\"Invalid nick passed to handle_nick.\")\n return\n if not user:\n ircd.logger.debug(\"Invalid user passed to handle_nick.\")\n return\n if user.nickname and user.nickname.lower() == args[0].lower():\n ircd.logger.debug(\"Nickname is the same, skipping.\")\n return\n if not ircd.util.isnick(args[0]):\n ircd.logger.debug(\"Invalid nickname.\")\n return\n if user.registered == 7:\n user.send_common(\"NICK %s\" % args[0])\n user.nickname = args[0]\n if user.registered < 3:\n user.registered |= 2\n elif user.registered == 3:\n user.connect()\n\n\ndef handle_part(args, pcnt, user):\n if pcnt == 1:\n args.append(None)\n channel = ircd.models.Channel.get(args[0])\n channel.remove(user, args[1])\n\n\ndef handle_pass(args, pcnt, user):\n user.password = args[0]\n\n\ndef handle_ping(args, pcnt, user):\n user.send_serv(\n \"PONG %s :%s\" % (ircd.config.getopt(\"SERVER_NAME\"), args[0]))\n\n\ndef handle_pong(args, pcnt, user):\n user.lastping = 1\n\n\ndef handle_privmsg(args, pcnt, user):\n if args[0][0] == \"#\":\n channel = ircd.models.Channel.get(args[0])\n if channel:\n if user not in channel:\n user.send_serv(\n \"404 %s %s :Cannot send to channel (no external messages).\" % (\n user.nickname, channel.name))\n if channel.moderated and channel.status(user) < 1:\n user.send_serv(\"404 %s %s :Cannot send to channel (+m).\" %\n (user.nickname, channel.name))\n user.send_channel(channel, \"PRIVMSG %s :%s\" %\n (channel.name, args[1]), exclude=True)\n else:\n user.send_serv(\"401 %s %s :No such nick/channel.\" %\n (user.nickname, channel.name))\n else:\n dests = ircd.models.User.get_by_nick(args[0])\n if not dests:\n user.send_serv(\"401 %s %s :No such nick/channel.\" %\n (user.nickname, args[0]))\n return\n for dest in ircd.models.User.get_by_nick(args[0]):\n if dest:\n # TODO autorespond with away message\n user.send_to(dest, \"PRIVMSG %s :%s\" % (dest.nickname, args[1]))\n\n\ndef handle_quit(args, pcnt, user):\n pass\n\n\ndef handle_topic(args, pcnt, user):\n channel = ircd.models.Channel.get(args[0])\n if pcnt == 1:\n if channel:\n if channel.topicset:\n user.send_serv(\"332 %s %s :%s\" %\n (user.nickname, channel.name, channel.topic))\n user.send_serv(\"333 %s %s %s %d\" % (\n user.nickname, channel.name, channel.setby,\n channel.topicset))\n else:\n user.send_serv(\"331 %s %s :No topic is set.\" %\n (user.nickname, channel.name))\n else:\n user.send_serv(\"331 %s %s :No topic is set.\" %\n (user.nickname, channel.name))\n else:\n if channel:\n if channel.status(user) < 2:\n user.send_serv(\n \"482 %s %s :You must be at least a half-operator.\" % (\n user.nickname, channel.name))\n return\n channel.topic = args[1]\n channel.setby = user.nickname\n channel.topicset = time.time()\n user.send_channel(channel, \"TOPIC %s :%s\" %\n (channel.name, channel.topic))\n else:\n user.send_serv(\"401 %s %s :No such nick/channel.\" %\n (user.nickname, args[0]))\n\n\ndef handle_user(args, pcnt, user):\n if user.registered < 3:\n user.send_serv(\n \"NOTICE Auth :No ident response, ident prefixed with ~.\")\n user.ident = args[0]\n user.fullname = args[3]\n user.registered |= 1\n else:\n user.send_serv(\"462 %s :You may not reregister.\" % user.nickname)\n\n if user.registered == 3:\n user.connect()\n\n\ndef handle_who(args, pcnt, user):\n # TODO actually implement this\n pass\n","sub_path":"ircd/commands.py","file_name":"commands.py","file_ext":"py","file_size_in_byte":9943,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"202100107","text":"import logging\nimport os\n\nimport pkg_resources\nimport requests\nimport youtube_dl\nfrom boltons.urlutils import URL\nfrom plumbum import local, ProcessExecutionError\n\nfrom scdlbot.exceptions import *\n\n# from requests.exceptions import Timeout, RequestException, SSLError\n\nbin_path = os.getenv('BIN_PATH', '')\nscdl_bin = local[os.path.join(bin_path, 'scdl')]\nbandcamp_dl_bin = local[os.path.join(bin_path, 'bandcamp-dl')]\nyoutube_dl_bin = local[os.path.join(bin_path, 'youtube-dl')]\n\nBOTAN_TRACK_URL = 'https://api.botan.io/track'\n\nlogger = logging.getLogger(__name__)\n\n\ndef get_response_text(file_name):\n # https://stackoverflow.com/a/20885799/2490759\n path = '/'.join(('texts', file_name))\n return pkg_resources.resource_string(__name__, path).decode(\"UTF-8\")\n\n\ndef get_direct_urls(url, cookies_file=None, cookies_download_file=None, source_ip=None, proxy=None):\n logger.debug(\"Entered get_direct_urls\")\n youtube_dl_args = []\n\n # https://github.com/ytdl-org/youtube-dl#how-do-i-pass-cookies-to-youtube-dl\n if cookies_file:\n if \"http\" in cookies_file:\n r = requests.get(cookies_file, allow_redirects=True)\n open(cookies_download_file, 'wb').write(r.content)\n youtube_dl_args.extend([\"--cookies\", cookies_download_file])\n else:\n youtube_dl_args.extend([\"--cookies\", cookies_file])\n\n if source_ip:\n youtube_dl_args.extend([\"--source-address\", source_ip])\n\n if proxy:\n youtube_dl_args.extend([\"--proxy\", proxy])\n\n youtube_dl_args.extend([\"--get-url\", url])\n try:\n ret_code, std_out, std_err = youtube_dl_bin[youtube_dl_args].run()\n except ProcessExecutionError as exc:\n # TODO: look at case: one page has multiple videos, some available, some not\n if \"returning it as such\" in exc.stderr:\n raise URLDirectError\n if \"proxy server\" in exc.stderr:\n raise URLCountryError\n raise exc\n if \"yt_live_broadcast\" in std_out:\n raise URLLiveError\n return std_out\n\n\ndef get_italic(text):\n return \"_{}_\".format(text)\n\n\ndef youtube_dl_func(url, ydl_opts, queue=None):\n ydl = youtube_dl.YoutubeDL(ydl_opts)\n try:\n ydl.download([url])\n except Exception as exc:\n ydl_status = 1, str(exc)\n # ydl_status = exc #TODO: pass and re-raise original Exception\n else:\n ydl_status = 0, \"OK\"\n if queue:\n queue.put(ydl_status)\n else:\n return ydl_status\n\n\n# def botan_track(token, message, event_name):\n# try:\n# # uid = message.chat_id\n# uid = message.from_user.id\n# except AttributeError:\n# logger.warning('Botan no chat_id in message')\n# return False\n# num_retries = 2\n# ssl_verify = True\n# for i in range(num_retries):\n# try:\n# r = requests.post(\n# BOTAN_TRACK_URL,\n# params={\"token\": token, \"uid\": uid, \"name\": event_name},\n# data=message.to_json(),\n# verify=ssl_verify,\n# timeout=2,\n# )\n# return r.json()\n# except Timeout:\n# logger.exception(\"Botan timeout on event: %s\", event_name)\n# except SSLError:\n# ssl_verify = False\n# except (Exception, RequestException, ValueError):\n# # catastrophic error\n# logger.exception(\"Botan 🙀astrophic error on event: %s\", event_name)\n# return False\n\ndef shorten_url(url):\n try:\n return requests.get('https://clck.ru/--?url=' + url).text.replace(\"https://\", \"\")\n except:\n return url\n\n\ndef log_and_track(event_name, message=None):\n logger.info(\"Event: %s\", event_name)\n if message:\n pass\n # if self.botan_token:\n # return botan_track(self.botan_token, message, event_name)\n\n\ndef get_link_text(urls):\n link_text = \"\"\n for i, url in enumerate(urls):\n link_text += \"[Source Link #{}]({}) | `{}`\\n\".format(str(i + 1), url, URL(url).host)\n direct_urls = urls[url].splitlines()\n for direct_url in direct_urls:\n if \"http\" in direct_url:\n content_type = \"\"\n if \"googlevideo\" in direct_url:\n if \"audio\" in direct_url:\n content_type = \"Audio\"\n else:\n content_type = \"Video\"\n # direct_url = shorten_url(direct_url)\n link_text += \"• {} [Direct Link]({})\\n\".format(content_type, direct_url)\n return link_text\n","sub_path":"scdlbot/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":4532,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"76462695","text":"class TrappingWater(object):\n def trap(self, height):\n if not height or len(height) < 3:\n return 0\n vol, i, j = 0, 0, len(height)-1\n lmax, rmax = height[i], height[j]\n while i < j:\n lmax, rmax = max(lmax, height[i]), max(rmax, height[j])\n if lmax < rmax:\n vol += lmax - height[i]\n i += 1\n else:\n vol += rmax - height[j]\n j -= 1\n return vol","sub_path":"Huffy/TrappingRainWater.py","file_name":"TrappingRainWater.py","file_ext":"py","file_size_in_byte":481,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"201567410","text":"# import os\n# import time\n# print(os.getpid()) #获取当前运行python程序的进程id\n# print(os.getppid()) # 获取当前进行的父进程id\n#time.sleep(100)\n\n\n\n# multiprocess 模块\n# 对进程操作的进一步封装\n# import os\n# from multiprocessing import Process\n# def func():\n# print(\"子进程\", os.getpid())\n# print(123)\n#\n# if __name__ == '__main__':\n# p = Process(target=func) #创建一个进程对象\n# print(\"主进程:\", os.getpid())\n# p.start() #执行start才开始启动进程\n# print(\"主进程\", os.getpid())\n\n# 主进程: 53940\n# 主进程 53940\n# 子进程 47784\n# 123\n\n#在同一个进程中,程序的确是从上到下依次执行的,多进程异步执行\n\n\n\n# import os\n# from multiprocessing import Process\n# def func(money):\n# print(\"取钱 :%d\" %money)\n#\n# if __name__ == '__main__':\n# p = Process(target=func, args=(1,)) #参数必须是元组\n# p.start() #执行start才开始启动进程\n# print(\"取完钱了\")\n# 进程传参\n#异步执行结果\n#取完钱了\n#取钱 :1\n\n\n# import os\n# import time\n# from multiprocessing import Process\n# def func(money):\n# time.sleep(3)\n# print(\"取钱 :%d\" %money)\n#\n# if __name__ == '__main__':\n# p = Process(target=func, args=(1,)) #参数必须是元组\n# p.start() #执行start才开始启动进程\n# print(\"去取钱\")\n# p.join() #阻塞,等p进程执行完成。再继续执行\n# print(\"取完钱了\")\n\n#进程阻塞\n#去取钱\n#取钱 :1\n#取完钱了\n\n#在windows操作系统中,创建里程的语句一定要放在 if __name__ == '__main__': 条件语句下面。\n\n\n#开启多个子进程\nimport os\nfrom multiprocessing import Process\n\n# def func():\n# print(\"子进程:%d 父进程:%d\" %(os.getpid(), os.getppid()))\n#\n# if __name__ == '__main__':\n# p = Process(target=func)\n# p1 = Process(target=func)\n# p2 = Process(target=func)\n# p.start()\n# p1.start()\n# p2.start()\n# print(\"---主进程---\")\n\n#---主进程---\n#子进程:5616 父进程:8136\n#子进程:11440 父进程:8136\n#子进程:1656 父进程:8136\n\n\n#数据隔离\n#进程与进程之间的数据是共享的\n\n# from multiprocessing import Process\n#\n# n = 100\n# def func():\n# global n\n# n = n-1\n# print(\"子进程 \", n)\n#\n# if __name__ == '__main__':\n# p = Process(target=func)\n# p.start()\n# print(\"主进程: \", n)\n\n#主进程: 100\n#子进程 99\n\n#开启进程的另一种方法\n# 用类继承创建一个子进程需要注意的事项\n# 类必须继承Process类\n# 这个类必须实现 run 方法\n# 实例化类得到一个对象\n# 使用对象调用start方法\nimport os\nfrom multiprocessing import Process\nclass MyProcess(Process):\n def __init__(self, arg1, arg2, arg3):\n super().__init__()\n self.arg1 = arg1\n self.arg2 = arg2\n self.arg3 = arg3\n def run(self):\n print(\"子进程: \", os.getpid(), self.arg1, self.arg2, self.arg3)\n self.walk() #walk 方法会在子进程中执行\n def walk(self):\n print(\"子进程: \", os.getpid())\n\nif __name__ == '__main__':\n p = MyProcess(1, 2, 3)\n p.start() #默认调用run方法\n p.walk() # walk 方法直接在主进程中调用 并没有在子进程中执行\n print(\"主进程: \", os.getppid())\n\n#子进程: 8180\n#主进程: 12528\n#子进程: 10560 1 2 3\n#子进程: 10560","sub_path":"process/process_first.py","file_name":"process_first.py","file_ext":"py","file_size_in_byte":3473,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"122703015","text":"import socket\nimport pickle\nimport logging\n\nlogging.basicConfig(level=logging.INFO)\n\nclass Server():\n def __init__(self, host='localhost', port=14902, listeners=1):\n self._host = host\n self._port = port\n self._listeners = listeners\n self._socket = None\n self._connection = None\n\n def create_Server(self):\n \"\"\"\n Creating server\n :return socket\n \"\"\"\n self._socket = socket.socket()\n self._socket.bind((self._host, self._port))\n self._socket.listen(self._listeners)\n\n logging.info(\"Server was created with parameters {} and with {} listeners\".format(self._socket, self._listeners))\n\n def receive_Connection(self):\n \"\"\"\n Connecting to client\n \"\"\"\n self._connection, address = self._socket.accept()\n\n logging.info(\"Connection established\")\n logging.info(\"Client ip: {} port: {}\".format(address[0], address[1]))\n\n def receive_Data(self):\n \"\"\"\n Receive information from client(byte -> str)\n :return: return int information\n \"\"\"\n\n data = self._connection.recv(4096)\n\n\n try:\n logging.info(\"Received data: {}\".format(int(data)))\n except:\n logging.info(\"Received data is not correct: {}\".format(data.decode()))\n self.send(\"Please, enter correct input\")\n return\n\n if int(data) < 0 or int(data) == 0:\n self.send(\"Please, enter correct input\")\n return\n\n return int(data)\n\n def prime_Factors(self, num):\n \"\"\"\n Calculating prime factors of num from client\n :param num\n :return: list with prime factors\n \"\"\"\n if num == 1: return 1\n i = 2\n prime_numbers = []\n while i * i <= num:\n while num % i == 0:\n prime_numbers.append(i)\n num = num / i\n i = i + 1\n if num > 1:\n prime_numbers.append(int(num))\n\n logging.info(\"Prime factors was been calculated: {}\".format(prime_numbers))\n return prime_numbers\n\n def send(self, data):\n \"\"\"\n Sending list from server to client\n \"\"\"\n if not data:\n return\n self._connection.send(pickle.dumps(data))\n logging.info(\"{} |was been sended \".format(data))\n\n def close_Connection(self):\n \"\"\"\n Closing connection with client\n \"\"\"\n self._connection.close()\n logging.info(\"Connection was closed.\")\n\n\n\n","sub_path":"server/server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":2520,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"398152720","text":"import unittest\n\nfrom project.tests.base_test_case import BaseTestCase\n\n\nclass TestComments(BaseTestCase):\n def test_add_comment(self):\n request = self.client.post('/propos/1/comments/add', data=dict(\n text=\"this is comment\",\n access_token=\"34600ab281ec4707b582d73a1e0fc4348c47467e3206458f89bd0e5a7b704f8f\"\n ))\n\n self.assertIn('author', str(request.data))\n\n @unittest.skip('old date for update')\n def test_update_comment(self):\n request = self.client.put('/propos/1/comments/1', data=dict(\n text='update comment',\n access_token=\"34600ab281ec4707b582d73a1e0fc4348c47467e3206458f89bd0e5a7b704f8f\"\n ))\n\n self.assertNotIn('error', str(request.data))\n\n def test_get_comments(self):\n request = self.client.post('/propos/1/comments', data=dict(\n access_token=\"34600ab281ec4707b582d73a1e0fc4348c47467e3206458f89bd0e5a7b704f8f\"\n ))\n\n self.assertIn('proposition_id', str(request.data))\n\n def test_get_comment(self):\n request = self.client.post('/propos/1/comments/1', data=dict(\n access_token=\"34600ab281ec4707b582d73a1e0fc4348c47467e3206458f89bd0e5a7b704f8f\"\n ))\n\n self.assertIn('author', str(request.data))\n\n\n\n","sub_path":"project/tests/test_comments.py","file_name":"test_comments.py","file_ext":"py","file_size_in_byte":1267,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"91038060","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.core.paginator import Paginator, EmptyPage, PageNotAnInteger\nfrom django.template.loader import get_template\nfrom datetime import datetime\nfrom django.http import HttpResponse\nfrom django.shortcuts import render\nfrom django.shortcuts import redirect\n\n\nfrom .models import Blog, Article, Literature, Experience\n\n# Create your views here\n\ndef homepage(request): \n template = get_template('home.html')\n articles = []\n '''\n size = Article.objects.size()\n if size < 5:\n articles = Article.objects.order_by(\"-pub_date\")[:size] //\n else:\n articles = Article.objects.order_by(\"-pub_date\")[:5]\n '''\n\n articles = Article.objects.order_by(\"-pub_date\")[:5]\n # articles = Article.objects.all()\n\n now = datetime.now()\n html = template.render(locals()) # locals 把所有局部变量打包成字典\n return HttpResponse(html)\n\ndef home_page(request):\n template = get_template('home.html')\n email = \"yx1302317313@163.com\"\n\n literatures = Literature.objects.all()\n now = datetime.now()\n html = template.render(locals()) # locals 把所有局部变量打包成字典\n return HttpResponse(html)\n\n# def articlepage(request):\n# template = get_template('article.html')\n# articles = Article.objects.all()\n# now = datetime.now()\n# html = template.render(locals()) # locals 把所有局部变量打包成字典\n# return HttpResponse(html)\n\ndef articlepage(request):\n # template = get_template('article.html')\n articles = Article.objects.all()\n paginator = Paginator(articles, 5)\n page = request.GET.get(\"page\")\n now = datetime.now()\n try:\n art_pages = paginator.page(page)\n except PageNotAnInteger: # 不是整数指向第一页\n art_pages = paginator.page(1)\n except EmptyPage:\n art_pages = paginator.page(paginator.num_pages) # 空页指向最后一页\n html = render(request, \"article.html\",{'art_pages':art_pages}) # locals 把所有局部变量打包成字典\n return HttpResponse(html)\n\n\ndef showarticle(request, slug):\n template = get_template('showarticle.html')\n try:\n article = Article.objects.get(slug = slug)\n if article != None:\n html = template.render(locals())\n return HttpResponse(html)\n except:\n return redirect('/')\n\n\ndef literaturepage(request):\n literatures = Literature.objects.all()\n paginator = Paginator(literatures, 5)\n page = request.GET.get(\"page\")\n now = datetime.now()\n try:\n lite_pages = paginator.page(page)\n except PageNotAnInteger: # 不是整数指向第一页\n lite_pages = paginator.page(1)\n except EmptyPage:\n lite_pages = paginator.page(paginator.num_pages) # 空页指向最后一页\n html = render(request, \"literature.html\",{'lite_pages':lite_pages}) # locals 把所有局部变量打包成字典\n return HttpResponse(html)\n\n\ndef showliterature(request, slug):\n template = get_template('showliterature.html')\n try:\n literature = Literature.objects.get(slug = slug)\n if literature != None:\n html = template.render(locals())\n return HttpResponse(html)\n except:\n return redirect('/')\n\ndef experiencepage(request):\n experiences = Experience.objects.all()\n paginator = Paginator(experiences, 5)\n page = request.GET.get(\"page\")\n now = datetime.now()\n try:\n expe_pages = paginator.page(page)\n except PageNotAnInteger: # 不是整数指向第一页\n expe_pages = paginator.page(1)\n except EmptyPage:\n expe_pages = paginator.page(paginator.num_pages) # 空页指向最后一页\n html = render(request, \"experience.html\",{'expe_pages':expe_pages}) # locals 把所有局部变量打包成字典\n return HttpResponse(html)\n\ndef showexperience(request, slug):\n template = get_template('showexperience.html')\n try:\n experience = Experience.objects.get(slug = slug)\n if experience != None:\n html = template.render(locals())\n return HttpResponse(html)\n except:\n return redirect('/')\n","sub_path":"mblog/mainsite/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":4257,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"222720114","text":"name = input(\"Enter your name: \") #Takes user input for their name\nID = input(\"Enter your student ID: \") #declares a variable called ID\nLengthName=len(name)#fidns length of user input name and declares a new variable\nvalue = 0 #declares a variable with the value of 0\nfor i in ID:\n if int(i) > 2 and int(i) < 7: #checks to see if an integer in ID is between 2 and 7\n value = int(i) #if it is between 2 and 7 it assigns it to value\n break\nif value == 0: #if there are no integers in ID between 2 and 7 it assumes it is 4\n value = 4\n\n\nfor i in range(1, len(name)+1):\n if name[i-1]==\" \": #if there is a space character in the name then\n print(\":\", end=\"\")#replace it with a smei colon\n else:\n if name[i-1].isupper():#checks if a character in name is an uppercase\n print(name[i-1].lower(), end=\"\")#if it is turn it to a lower case\n\n else:\n print(name[i-1].upper(), end=\"\")# if its a lower case then turn it to an upper case\n\n if i % value == 0:\n print(\"\\n\")#prints newline if the remainer of i mod value is 0\n\n\nif (LengthName % value):\n padding = value - (LengthName % value)\n print(\"=\"*padding, end=\"\") #if the name cant fill the value size then fill the gaps with a \"=\" symbol\n","sub_path":"Python/LAB1ADV.py","file_name":"LAB1ADV.py","file_ext":"py","file_size_in_byte":1260,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"257151075","text":"import torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport numpy as np\n\ndef swish(x):\n return x * F.sigmoid(x)\n\nclass Residual_Block(nn.Module):\n def __init__(self, n_channels=64):\n super(Residual_Block, self).__init__()\n self.Conv1 = nn.Conv2d(n_channels, n_channels, 3, stride=1, padding=1)\n self.bn1 = nn.BatchNorm2d(n_channels)\n self.relu1 = nn.ReLU()\n \n self.Conv2 = nn.Conv2d(n_channels, n_channels, 3, stride=1, padding=1)\n self.bn2 = nn.BatchNorm2d(n_channels)\n \n def forward(self, x):\n output = swish(self.bn1(self.Conv1(x)))\n output = self.bn2(self.Conv2(output))\n output = x + output\n \n return output\n\nclass Upsample_Block_TC(nn.Module):\n def __init__(self, in_channels, out_channels):\n super(Upsample_Block_TC, self).__init__()\n self.bn = nn.BatchNorm2d(in_channels)\n self.relu = nn.ReLU()\n self.trans_conv = nn.ConvTranspose2d(in_channels, out_channels, 3, stride=2, padding=1, output_padding=1)\n \n def forward(self, x):\n output = self.trans_conv(self.relu(self.bn(x)))\n return output\n\nclass Upsample_Block_PS(nn.Module):\n def __init__(self, in_channels, out_channels):\n super(Upsample_Block_PS, self).__init__()\n self.conv = nn.Conv2d(in_channels, out_channels, 3, stride=1, padding=1)\n self.shuffler = nn.PixelShuffle(2)\n\n def forward(self, x):\n return swish(self.shuffler(self.conv(x)))\n\nclass Noise_Integrate_Layer(nn.Module):\n def __init__(self):\n super(Noise_Integrate_Layer, self).__init__()\n\n def forward(self, x, noise):\n scale_noise = noise[:int(noise.size()[0]/2)]\n bias_noise = noise[int(noise.size()[0]/2):]\n\n for i in range(int(x.size()[0]/2)):\n for j in range(int(x.size()[0]/2)):\n x[i, j, :, :] *= scale_noise[j]\n x[i, j, :, :] += bias_noise[j]\n\n return x\n\nclass AdaIN(nn.Module):\n def __init__(self):\n super(AdaIN, self).__init__()\n \n def forward(self, input, noise):\n input_numpy = input.numpy()\n std = np.std(input_numpy, (2, 3))\n mean = np.mean(input_numpy, (2, 3))\n std = torch.from_numpy(std).cuda()\n mean = torch.from_numpy(mean).cuda()\n\n for i in range(int(input.size()[0])):\n for j in range(int(input.size()[1])):\n input[i, j, :, :] -= mean[i, j]\n input[i, j, :, :] /= std[i, j]\n\n\n scale_noise = noise[:int(noise.size()[0]/2)]\n bias_noise = noise[int(noise.size()[0]/2):]\n\n for i in range(int(input.size()[0])):\n for j in range(int(input.size()[1])):\n input[i, j, :, :] *= scale_noise[j]\n input[i, j, :, :] += bias_noise[j]\n \n return input\n\nclass Noise_Affine_Trans(nn.Module):\n def __init__(self):\n super(Noise_Affine_Trans, self).__init__()\n self.fn1 = nn.Linear(256, 256)\n self.fn2 = nn.Linear(256, 256)\n self.fn3 = nn.Linear(256, 256)\n self.fn4 = nn.Linear(256, 256)\n\n self.relu = nn.ReLU()\n\n def forward(self, input):\n output = self.relu(self.fn1(input))\n output = self.relu(self.fn2(output))\n output = self.relu(self.fn3(output))\n output = self.relu(self.fn4(output))\n\n return output\n\n \n\n","sub_path":"model/modules.py","file_name":"modules.py","file_ext":"py","file_size_in_byte":3383,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"298845329","text":"from conans import ConanFile, CMake, tools\nimport os\nimport platform\nimport pathlib\nimport glob\nimport io\nimport re\n\nclass ConanPackage(ConanFile):\n name = \"libInterpolate\"\n git_url_basename = \"git://github.com/CD3\"\n version = \"2.3.2\"\n checkout = \"2.3.2\"\n url = \"https://github.com/CD3/cd3-conan-packages\"\n\n author = \"CD Clark III clifton.clark@gmail.com\"\n description = \"A C++ library for numerical interpolation supporting multiple methods/algorithms.\"\n license = \"MIT\"\n topics = (\"C++\", \"Numerical Interpolation\")\n\n generators = \"cmake\", \"virtualenv\"\n requires = 'boost/1.69.0@conan/stable', 'eigen/3.3.7@cd3/devel'\n\n @property\n def git_url(self):\n return f\"{self.git_url_basename}/{self.name}\"\n\n def build_requirements(self):\n # we need a recent version of cmake to build. check if it is installed,\n # and add it to the build_requires if not\n cmake_min_version = \"3.14.0\"\n cmake_req_version = \"3.16.0\"\n need_cmake = False\n\n if tools.which(\"cmake\") is None:\n need_cmake = True\n else:\n output = io.StringIO()\n self.run(\"cmake --version\",output=output)\n version = re.search( \"cmake version (?P\\S*)\", output.getvalue())\n if tools.Version( version.group(\"version\") ) < cmake_min_version:\n need_cmake = True\n\n if need_cmake:\n self.build_requires(f\"cmake_installer/{cmake_req_version}@conan/stable\")\n\n def source(self):\n self.run(f\"git clone {self.git_url}\")\n self.run(f\"cd {self.name} && git checkout {self.checkout} && git log -1\")\n cmakelists = pathlib.Path(self.name)/\"CMakeLists.txt\"\n cmakelists_text = cmakelists.read_text()\n if not re.search(\"ARCH_INDEPENDENT\",cmakelists_text):\n tools.replace_in_file(str(cmakelists),\n \"COMPATIBILITY SameMajorVersion\",\n \"COMPATIBILITY SameMajorVersion\\nARCH_INDEPENDENT\")\n\n def build(self):\n if not self.develop:\n tools.replace_in_file(os.path.join(self.name, 'CMakeLists.txt'),\n 'project(libInterpolate)',\n 'project(libInterpolate)\\nset(STANDALONE OFF)')\n cmake = CMake(self)\n if not self.develop:\n cmake.definitions[\"BUILD_TESTS\"] = \"OFF\"\n cmake.configure(source_folder=self.name)\n cmake.build()\n\n def package(self):\n cmake = CMake(self)\n cmake.install()\n \n def package_info(self):\n self.env_info.libInterpolate_DIR = os.path.join(self.package_folder, \"cmake\")\n self.env_info.libInterp_DIR = os.path.join(self.package_folder, \"cmake\")\n\n","sub_path":"recipes/libInterpolate/2.3.2/conanfile.py","file_name":"conanfile.py","file_ext":"py","file_size_in_byte":2678,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"650478329","text":"#coding=utf8\r\n\"\"\"\r\nresp.text返回的是Unicode型的数据。\r\nresp.content返回的是bytes型也就是二进制的数据。\r\n也就是说,如果你想取文本,可以通过r.text。\r\n如果想取图片,文件,则可以通过r.content。\r\nresp.json()返回的是json格式数据\r\n\r\n\"\"\"\r\n\r\nimport sys\r\nsys.path.append(\"..\")\r\nfrom func import *\r\n\r\nimport requests\r\n\r\n\r\nheaders = {\r\n 'User-Agent': 'chrome',\r\n# 'Host': \"www.sogou.com\",\r\n 'referer': 'https://www.sogou.com/'\r\n #'Content-type': 'application/json', \r\n}\r\n\r\nurl = 'https://www.sogou.com';\r\nreq = requests.get(url, timeout=7, headers = headers)\r\n\r\nprint ( req.text)\r\n\r\nfile_write('0text.txt', req.text.replace(\"\\xa9\",''),'w');\r\n\r\nfile_write('0content.txt', req.content, 'wb');\r\n\r\n\r\n","sub_path":"requests1/content_text.py","file_name":"content_text.py","file_ext":"py","file_size_in_byte":762,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"571663359","text":"from __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\nimport re\nimport cv2\nimport pdb\nimport tensorflow as tf\nfrom skimage.transform import resize\nimport sys\nsys.path.insert(0, \"/home/hxw/frameworks/models/research/object_detection\")\nfrom utils import visualization_utils as vis_util\nimport numpy as np\nimport PIL.Image as Image\nimport PIL.ImageDraw as ImageDraw\nimport PIL.ImageFont as ImageFont\nfrom itertools import compress\n\n\ndef write_tracks_on_image_array(image_pil, boxes, ids, ass, clss):\n for box, i in zip(boxes, ids):\n write_tracks_on_image(image_pil, box, i, ass, clss)\n image = np.array(image_pil)\n return image\n\ndef write_tracks_on_image(image, box, id, ass, clss):\n txtcolor = 'red'\n if clss == 'person':\n boxcolor = 'blue'\n display_str = '%s %d ' % (clss, int(id) + 1)\n else:\n boxcolor = 'green'\n cass = np.zeros_like(ass)\n for i in np.unique(ass):\n subarray = np.where(ass == i)\n cass[subarray[0]] = range(len(subarray[0])) \n display_str = 'person %d, bin %d '%(ass[int(id)] + 1, cass[int(id)] + 1)\n draw = ImageDraw.Draw(image)\n\n (left, right, top, bottom) = (box[0], box[0]+box[2], box[1], box[1]+box[3])\n try:\n font = ImageFont.truetype('demo/arial.ttf', 30)\n except IOError:\n font = ImageFont.load_default()\n \n text_width, text_height = font.getsize(display_str + ' ')\n margin = np.ceil(0.5 * text_height)\n\n text_bottom = top + text_height + 2*margin\n \n draw.rectangle(\n [(left, text_bottom - text_height - 2 * margin), (left + text_width,\n text_bottom)],\n fill='white')\n\n draw.line([(left, top), (left, bottom), (right, bottom),\n (right, top), (left, top)], width=4, fill=boxcolor)\n draw.text(\n (left + margin, text_bottom - text_height - margin),\n display_str,\n fill=txtcolor,\n font=font)\n\ndef time_matching(person_boxes, bin_boxes):\n pids = np.unique(person_boxes[:,1])\n bids = np.unique(bin_boxes[:,1])\n sim_mat = np.ones((len(pids), len(bids))) * 1e-8\n for p in pids:\n minp = min(person_boxes[person_boxes[:,1]==p, 0])\n maxp = max(person_boxes[person_boxes[:,1]==p, 0])\n for b in bids:\n minb = min(bin_boxes[bin_boxes[:,1]==b, 0])\n maxb = max(bin_boxes[bin_boxes[:,1]==b, 0])\n tmp = min(maxp, maxb) - max(minp, minb)\n sim_mat[int(p), int(b)] = np.maximum(0, tmp)\n return sim_mat\n\ndef location_matching(person_boxes, bin_boxes):\n pids = np.unique(person_boxes[:,1])\n bids = np.unique(bin_boxes[:,1])\n dist_mat = np.ones((len(pids), len(bids))) * 1e8\n for p in pids:\n curr_person_boxes = person_boxes[person_boxes[:,1]==p]\n minp = min(curr_person_boxes[:,0])\n maxp = max(curr_person_boxes[:,0])\n for b in bids:\n curr_bin_boxes = bin_boxes[bin_boxes[:,1]==b]\n minb = min(curr_bin_boxes[:,0])\n maxb = max(curr_bin_boxes[:,0])\n if min(maxp, maxb) > max(minp, minb):\n acc = 0\n acc_d = 0\n for fr in range(int(max(minp, minb)), int(min(maxp, maxb))):\n xy_p = curr_person_boxes[curr_person_boxes[:,0]==fr, 2:4] + curr_person_boxes[curr_person_boxes[:,0]==fr, 4:6]\n xy_b = curr_bin_boxes[curr_bin_boxes[:,0]==fr, 2:4] + curr_bin_boxes[curr_bin_boxes[:,0]==fr, 4:6]\n if xy_p.size > 0 and xy_b.size > 0:\n acc_d += np.linalg.norm(xy_p - xy_b)\n acc += 1\n if acc > 0:\n avg_d = acc_d / acc\n dist_mat[int(p), int(b)] = avg_d\n return dist_mat \n\n\ndef associate(exp, startf=0, endf=100000, vis=True, fps=20.0):\n video_file = \"demo/\" + exp + \".mp4\"\n person_track_file = 'demo/' + exp + '_person.txt'\n bin_track_file = 'demo/' + exp + '_bin.txt'\n\n capture = cv2.VideoCapture(video_file)\n capture.set(1, startf)\n fourcc = cv2.VideoWriter_fourcc(*'XVID')\n out = cv2.VideoWriter('./demo/' + exp + '_SORT_Tracking.avi', fourcc, fps, (1920, 1080))\n\n person_boxes = np.loadtxt(person_track_file, delimiter=',')\n bin_boxes = np.loadtxt(bin_track_file, delimiter=',')\n\n\n time_sim = time_matching(person_boxes, bin_boxes)\n location_dist = location_matching(person_boxes, bin_boxes)\n\n co_dist = np.divide(location_dist, time_sim)\n\n bin_ass = np.argmin(co_dist, axis=0)\n\n i = startf - 1\n\n if vis:\n while True:\n flag, frame = capture.read()\n if frame is not None:\n #pdb.set_trace()\n frame = frame[:,:,::-1]\n image = Image.fromarray(frame)\n i += 1\n else: break\n if i > endf: break\n \n curr_person_boxes = person_boxes[person_boxes[:,0] == i]\n curr_bin_boxes = bin_boxes[bin_boxes[:,0] == i]\n\n\n image_np = write_tracks_on_image_array(\n image,\n curr_person_boxes[:,2:],\n curr_person_boxes[:,1],\n bin_ass,\n 'person')\n\n image_np = write_tracks_on_image_array(\n image,\n curr_bin_boxes[:,2:],\n curr_bin_boxes[:,1],\n bin_ass,\n 'bin')\n\n image_np = image_np[:,:,::-1]\n out.write(image_np)\n print('%d frames processed!' % (i - startf + 1))\n \n","sub_path":"mycore/association.py","file_name":"association.py","file_ext":"py","file_size_in_byte":5606,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"420623965","text":"class Solution:\n def binary_search(self, root, value):\n if root.val == value:\n return value\n\n if value < root.val:\n if root.left is not None:\n return self.binary_search(root.left, value)\n else:\n return None\n\n else:\n if root.right is not None:\n return self.binary_search(root.right, value)\n else:\n return None\n ","sub_path":"杂项/二叉排序树的查找.py","file_name":"二叉排序树的查找.py","file_ext":"py","file_size_in_byte":456,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"348362569","text":"# -*- coding: utf-8 -*-\nfrom app.lib.common.xmlparse import xmlparse\nfrom app.lib.goods_log.goods_obtain import goods_obtain\nfrom app.lib.goods_log.goods_cost import goods_cost\nfrom app import session\nfrom app.lib.common.audit_log import audit_log\n\n\nclass goods_log:\n\n def __init__(self, form, database):\n self.database = database\n self.form = form\n self.result_obtain = []\n self.result_cost = []\n self.user_name = session['user']\n\n @audit_log('goods_log')\n def process(self):\n area_id_list = []\n area_id_for_html_list = []\n user_account = self.form.user_account.data\n # 前端展示需要unicode,后端查询需要gbk\n if isinstance(user_account, unicode):\n user_account = user_account.encode('gbk') # 转码\n user_account_for_html = user_account.decode('gbk')\n else:\n user_account = user_account\n user_account_for_html = unicode(user_account, 'gbk')\n begin_str = self.form.begin_date.data\n end_str = self.form.end_date.data\n if self.form.goods_id.data:\n goods_id = self.form.goods_id.data\n else:\n goods_id = -1\n # 初始化数据库\n db = self.database\n db_conn = db.db_select(2, 'good')\n # 读取区号\n if self.form.area1.data:\n area_id_list.append(1)\n area_id_for_html_list.append('1')\n if self.form.area2.data:\n area_id_list.append(2)\n area_id_for_html_list.append('2')\n if self.form.area3.data:\n area_id_list.append(5)\n area_id_for_html_list.append('4/5')\n if self.form.area4.data:\n area_id_list.append(8)\n area_id_for_html_list.append('7/8')\n if self.form.area5.data:\n area_id_list.append(9)\n area_id_for_html_list.append('9')\n xmlparse_obj = xmlparse(db)\n for area_id in area_id_list:\n # 物品获得\n goods_obtain_obj = goods_obtain(\n user_account,\n area_id,\n begin_str,\n end_str,\n goods_id,\n xmlparse_obj,\n db_conn)\n result_obtain = goods_obtain_obj.process()\n for res in result_obtain:\n self.result_obtain.append(res)\n # 物品消耗\n goods_cost_obj = goods_cost(\n user_account,\n area_id,\n begin_str,\n end_str,\n goods_id,\n xmlparse_obj,\n db_conn)\n result_cost = goods_cost_obj.process()\n for res in result_cost:\n self.result_cost.append(res)\n db_conn.close()\n","sub_path":"app/lib/process/goods_log.py","file_name":"goods_log.py","file_ext":"py","file_size_in_byte":2776,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"174179943","text":"from __future__ import print_function\n\nfrom tornado import gen\nfrom tornado_mysql import pools\nimport logging\nimport tornado.web\n\n\npools.DEBUG = True\n\nPOOL = pools.Pool(\n dict(host='192.168.1.155', port=3306, user='root', passwd='1qazxsw2!@', db='wpnbmdb', charset='utf8',),\n max_idle_connections=10, max_open_connections=90,\n max_recycle_sec=3)\n\n@gen.coroutine\ndef main():\n cur = yield POOL.execute(\"SELECT * from zs_yjsf order by id\")\n for row in cur:\n print(row)\n cur.close()\n\nclass IndexHandler(tornado.web.RequestHandler):\n @gen.coroutine\n def get(self):\n cur = yield POOL.execute(\"SELECT * from zs_yjsf order by id limit 20\")\n self.write(str(cur.fetchall()))\n cur.close()\n \n \nif __name__ == \"__main__\":\n logging.getLogger('tornado.access').disabled = True\n\n app = tornado.web.Application(handlers=[(r\"/\", IndexHandler)], debug=False)\n\n http_server = tornado.httpserver.HTTPServer(app)\n http_server.listen(8888)\n# http_server.bind(80)\n# http_server.start(0)\n# 很遗憾,上述代码不能在windows下运行,所以,tornado的多进程只能在linux底下运行。\n# 把POOL 的定义放在这里,是因为POOL本身就会初始化一个eventloop。\n# POOL = pools.Pool(\n# dict(host='192.168.1.155', port=3306, user='root', passwd='1qazxsw2!@', db='wpnbmdb', charset='utf8',),\n# max_idle_connections=10, max_open_connections=90,\n# max_recycle_sec=3)\n\n# asyncio.set_event_loop_policy(asyncio.SelectorEventLoop)\n# 设置任何eventloop都报错,被windows搞得没脾气。\n\n tornado.ioloop.IOLoop.instance().start()\n","sub_path":"tornadomysqlexamp/tsqlalchemy.py","file_name":"tsqlalchemy.py","file_ext":"py","file_size_in_byte":1643,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"265611645","text":"import socket\nimport time\n\ndef main():\n serverAddr = '192.168.1.8'\n serverPort = 2525\n\n sock = socket.socket()\n sock.connect((serverAddr, serverPort))\n sock.settimeout(0.1)\n time.sleep(0.5)\n for x in range(0, 5):\n sock.send(b'RK')\n time.sleep(1)\n\n while 1:\n try:\n data = sock.recv(1024)\n print(str(data))\n except IOError:\n print(\"error receiving from basestation\")\n\nif __name__=='__main__':\n main()\n","sub_path":"C#.NET_basestation_for_robot_contest_division/Robot/test_connect_python2.py","file_name":"test_connect_python2.py","file_ext":"py","file_size_in_byte":483,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"279968205","text":"import json\n\n\nclass UserSettings:\n @classmethod\n def get_settings(self):\n with open('app/settings.json') as f:\n settings = json.load(f)\n\n MODE = settings['user_settings']['mode']\n ACCENT_COLOR = settings['user_settings']['accent_color']\n\n if MODE == 'light':\n BG_COLOR = settings['light_theme']['background']\n FG_COLOR = settings['light_theme']['foreground']\n CR_COLOR = settings['light_theme']['copyright']\n else:\n BG_COLOR = settings['dark_theme']['background']\n FG_COLOR = settings['dark_theme']['foreground']\n CR_COLOR = settings['dark_theme']['copyright']\n\n return {\n 'MODE': MODE,\n 'ACCENT_COLOR': ACCENT_COLOR,\n 'BG_COLOR': BG_COLOR,\n 'FG_COLOR': FG_COLOR,\n 'CR_COLOR': CR_COLOR\n }\n\n @classmethod\n def write_settings(self, param, value):\n with open('app/settings.json', 'r') as f:\n settings = json.load(f)\n settings['user_settings'][param] = value\n\n with open('app/settings.json', 'w') as f:\n json.dump(settings, f, indent=4)\n","sub_path":"app/config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":1173,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"284386781","text":"\"\"\" Unit Tests for Service Patch\n\"\"\"\n# Copyright (c) 2021 ipyradiant contributors.\n# Distributed under the terms of the Modified BSD License.\n\nimport rdflib\n\nimport ipyradiant\n\nLINKEDDATA_QUERY = \"\"\"\n SELECT DISTINCT ?s ?p ?o\n WHERE {\n SERVICE \n {\n SELECT ?s ?p ?o\n WHERE {?s ?p ?o}\n }\n }\n\"\"\"\n\nPATCHED_LINKEDDATA_QUERY = \"\"\"\n SELECT DISTINCT ?s ?p ?o\n WHERE {\n service \n {\n SELECT ?s ?p ?o\n WHERE {?s ?p ?o}\n }\n }\n\"\"\"\n\n\ndef test_service_fix():\n query_str = ipyradiant.service_patch_rdflib(LINKEDDATA_QUERY)\n assert query_str == PATCHED_LINKEDDATA_QUERY\n\n\ndef test_rdflib_version():\n version = rdflib.__version__\n v_split = tuple(map(int, version.split(\".\")))\n assert v_split <= (5, 0, 0)\n","sub_path":"src/ipyradiant/tests/test_servicepatch_rdflib.py","file_name":"test_servicepatch_rdflib.py","file_ext":"py","file_size_in_byte":943,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"91886892","text":"import argparse\nimport logging\n\nfrom fac.api import API\nfrom fac.files import Config\nfrom fac.mods import ModManager\n\nimport fac.commands.all # NOQA\nfrom fac.commands import CommandRegistry\n\nlog = logging.getLogger(__name__)\n\n\ndef main():\n common_parser = argparse.ArgumentParser(add_help=False)\n common_group = common_parser.add_argument_group('general options')\n\n common_group.add_argument(\n '-v', '--verbose', action='store_true',\n help='show more detailled output'\n )\n common_group.add_argument(\n '-h', '--help', action='help',\n help='show this help message and exit'\n )\n\n command_parser = argparse.ArgumentParser(add_help=False)\n command_subparsers = command_parser.add_subparsers(\n dest='command', metavar='COMMAND', title=None,\n )\n\n api = API()\n config = Config()\n manager = ModManager(api=api, config=config)\n\n for command_class in CommandRegistry.commands:\n command = command_class(api, config, manager)\n command.create_parser(command_subparsers, [common_parser])\n\n root_parser = argparse.ArgumentParser(\n description='Mod manager for Factorio',\n add_help=False,\n usage='%(prog)s COMMAND [options...]',\n parents=[command_parser, common_parser]\n )\n\n args = root_parser.parse_args()\n\n if args.verbose:\n logging.basicConfig(level=logging.DEBUG)\n\n log.debug('Factorio write path: %s', config.factorio_write_path)\n log.debug('Factorio game path: %s', config.factorio_data_path)\n log.debug('Factorio version: %s', config.game_version)\n\n if args.command:\n args.run(args)\n else:\n root_parser.print_help()\n\nif __name__ == '__main__':\n main()\n","sub_path":"fac/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1710,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"96187021","text":"#! /usr/bin/env python3\n\n\"\"\"\n # {Christopher Dahlen}\n # {cdahlen@kth.se}\n\"\"\"\nimport numpy as np\ndef scara_IK(point):\n x = point[0] -0.07\n y = point[1]# -0.07\n z = point[2]\n #print x,y,z\n q = [0.0, 0.0, 0.0]\n\n \"\"\"\n Fill in your IK solution here and return the three joint values in q\n \"\"\"\n L1 = 0.3\n L2 = 0.35\n \n cos_phi_2 = (x**2 + y**2 - L1**2 - L2**2 ) / (2* L1*L2)\n if cos_phi_2 < 1 and cos_phi_2 > -1:\n sin_phi_2 = np.sqrt(1-(cos_phi_2 ** 2))\n phi_2 = np.arctan2(sin_phi_2, cos_phi_2)\n q[1] = phi_2\n k1 = L1 + (L2 * cos_phi_2)\n k2 = L2 * sin_phi_2\n r = np.sqrt(k1**2 + k2**2)\n gamma = np.arctan2(k2,k1)\n k1 = r * np.cos(gamma)\n k2 = r * np.sin(gamma)\n q[0] = np.arctan2(y,x) - np.arctan2(k2,k1)\n if z > -np.pi/2 and z < np.pi/2:\n q[2] = z\n else:\n q[2] = z\n return q\n\ndef kuka_IK(point, R, joint_positions):\n x = point[0]\n y = point[1]\n z = point[2]\n q = joint_positions #it must contain 7 elements\n\n \"\"\"\n Fill in your IK solution here and return the seven joint values in q\n \"\"\"\n\n return q\n","sub_path":"src/kinematics_assignment_metapackage/kinematics_assignment/scripts/IK_functions.py","file_name":"IK_functions.py","file_ext":"py","file_size_in_byte":1173,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"413051680","text":"import airflow\nfrom airflow import DAG\nfrom airflow.operators.bash_operator import BashOperator\nfrom airflow.operators.email_operator import EmailOperator\nfrom airflow.operators.python_operator import BranchPythonOperator\nfrom airflow.operators.dummy_operator import DummyOperator\nfrom airflow.utils.trigger_rule import TriggerRule\nfrom airflow.operators.python_operator import PythonOperator\nfrom airflow.models import Variable,Connection\nfrom airflow_training.operators.postgres_to_gcs import PostgresToGoogleCloudStorageOperator\nfrom datetime import datetime\nfrom dateutil.parser import parse\nfrom airflow_training.operators.httpgcs import HttpToGcsOperator\nfrom airflow.contrib.operators.dataflow_operator import DataFlowPythonOperator\n\n\ndag = DAG(\n dag_id=\"real_estate\",\n default_args={\n \"owner\": \"godatadriven\",\n \"start_date\": airflow.utils.dates.days_ago(30),\n },\n)\nprints_started_job = BashOperator(\n task_id=\"prints_started_job\", bash_command=\"echo {{ execution_date }}\", dag=dag\n)\n\n\npgsl_to_gcs = PostgresToGoogleCloudStorageOperator(\n task_id='read_from_pgs',\n sql= \"select * from land_registry_price_paid_uk where transfer_date = '{{ ds }}'\",\n bucket='amin-bucket2',\n filename='data/{{ ds }}/real_estate.json',\n dag=dag\n)\ncurrency_jobs = []\nfor currency in ['EUR', 'USD']:\n currency_jobs.append(\n HttpToGcsOperator(\n task_id= 'get_rates_' + currency,\n endpoint= '/convert-currency?date={{ ds }}&from=GBP&to=' + currency,\n gcs_path = 'currency/{{ ds }}/' + currency + '.json',\n gcs_bucket= 'amin-bucket2',\n dag=dag\n )\n )\n\n\n\nload_into_bigquery = DataFlowPythonOperator(\n task_id=\"land_registry_prices_to_bigquery\",\n dataflow_default_options={\n 'region': \"europe-west1\",\n 'input': 'gs://amin-bucket2/data/*/*.json',\n 'temp_location': 'gs://amin-bucket2/temp',\n 'staging_location': 'gs://amin-bucket2/staging',\n 'table': 'amin',\n 'dataset': 'amin',\n 'project': 'airflowbolcom-a2262958ad7773ed',\n 'project_id': 'airflowbolcom-a2262958ad7773ed',\n 'bucket': 'amin-bucket2',\n 'runner': 'DataflowRunner',\n 'job_name': '{{ task_instance_key_str }}'\n },\n py_file=\"gs://amin-bucket2/dataflow_job.py\",\n dag=dag,\n)\n\n\n","sub_path":"dags/real_estate.py","file_name":"real_estate.py","file_ext":"py","file_size_in_byte":2332,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"121108544","text":"#!/usr/bin/env python3\n\n################################################################################\n# Copyright (C) 2016-2020 Abstract Horizon\n# All rights reserved. This program and the accompanying materials\n# are made available under the terms of the Apache License v2.0\n# which accompanies this distribution, and is available at\n# https://www.apache.org/licenses/LICENSE-2.0\n#\n# Contributors:\n# Daniel Sendula - initial API and implementation\n#\n#################################################################################\n\nimport datetime\nimport glob\nimport os\nfrom os.path import join\nfrom zipfile import ZipFile, ZIP_DEFLATED\n\nCURRENT_PATH = os.path.dirname(os.path.abspath(__file__))\n\nSOURCE_PATHS = [join(CURRENT_PATH, \"telemetry-client\"), join(CURRENT_PATH, \"telemetry-library\")]\nRESULT_NAME = \"download-stream-mqtt\"\nMAIN_FILE = \"download-stream-mqtt\" # discovery.py\n\n# REQUIREMENTS_FILE = join(CURRENT_PATH, \"requirements.txt\")\n\nTARGET_PATH = join(CURRENT_PATH, \"target\")\n# TARGET_REQUIREMENTS_PATH = join(TARGET_PATH, \"requirements\")\nTARGET_TEMPLATES_PATH = join(TARGET_PATH, \"templates\")\nVERSION_FILE = join(CURRENT_PATH, \"CLIENT_VERSION\")\n\n\ndef ensure_empty_dir(path):\n if not os.path.exists(path):\n os.makedirs(path)\n\n def del_recursively(path_to_delete):\n for file in os.listdir(path_to_delete):\n new_path = os.path.join(path_to_delete, file)\n try:\n if os.path.isdir(new_path):\n del_recursively(new_path)\n os.rmdir(new_path)\n else:\n os.remove(new_path)\n except IOError:\n pass\n\n del_recursively(path)\n\n return path\n\n\ndef list_all_paths(dir_name):\n paths = []\n\n for root, directories, files in os.walk(dir_name):\n for filename in files:\n source_filename = os.path.join(root, filename)\n dest_filename = os.path.join(root[len(dir_name) + 1:] , filename)\n paths.append((source_filename, dest_filename))\n\n return paths\n\n\ndef install_requirements(requirements_file, target_directory):\n print(f\"Attempting to install requirements from '{requirements_file}' in '{target_directory}\")\n os.system(f\"pip install -r {glob.glob(requirements_file)[0]} --target {target_directory}\")\n\n\ndef update_build_version(version_file, target_templates_path):\n if os.path.exists(version_file):\n ensure_empty_dir(target_templates_path)\n with open(version_file, 'r') as in_file:\n lines = in_file.readlines()\n lines[0] = lines[0] + datetime.datetime.now().strftime('-%Y%m%d%H%M%S')\n with open(os.path.join(target_templates_path, os.path.split(version_file)[1]), 'w') as out_file:\n out_file.write(\"\\n\".join(lines) + \"\\n\")\n\n\ndef create_zipfile(zip_file, source_paths, *other_paths):\n with ZipFile(zip_file, 'w', ZIP_DEFLATED) as zip_file:\n for source_path in source_paths:\n for source_file, result_file in list_all_paths(source_path):\n zip_file.write(source_file, result_file)\n\n for path in other_paths:\n for source_file, result_file in list_all_paths(path):\n zip_file.write(source_file, result_file)\n\n return zip_file\n\n\nSTART_SCRIPT = f\"\"\"#!/bin/bash\n\nexport SCRIPT_FILE=`which \"$0\" 2>/dev/null`\n\nsource=`cat < RESIZE_WIDTH:\r\n img_resize = cv2.resize(img, (RESIZE_WIDTH, int(RESIZE_WIDTH / img_width * img_height)))\r\n else:\r\n img_resize = img\r\n \r\n img_gray = cv2.cvtColor(img_resize, cv2.COLOR_RGB2GRAY)\r\n\r\n CASCADE_FILE = 'haarcascade_frontalface_alt.xml'\r\n #CASCADE_FILE = 'haarcascade_eye.xml'\r\n\r\n haar_cascade = cv2.CascadeClassifier(CASCADE_FILE)\r\n detection = haar_cascade.detectMultiScale(img_resize, scaleFactor=1.1, minNeighbors=2, minSize=(30, 30))\r\n \r\n if len(detection) > 0:\r\n for rect in detection:\r\n cv2.rectangle(img_resize, tuple(rect[0:2]), tuple(rect[0:2]+rect[2:4]), (0, 0, 255), thickness=2)\r\n else:\r\n cv2.putText(img_resize, 'no match found', (20, 50), cv2.FONT_HERSHEY_COMPLEX, 1.0, (0, 0, 255), 2)\r\n\r\n cv2.imshow(file, img_resize)\r\n cv2.waitKey(0)\r\n cv2.destroyAllWindows()\r\nexcept ValueError as e:\r\n print(e)\r\nexcept:\r\n import traceback\r\n traceback.print_exc()\r\n","sub_path":"課題/4章/課題7/face_detection.py","file_name":"face_detection.py","file_ext":"py","file_size_in_byte":1360,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"40456575","text":"limit = 1000\n\ndef is_prime(n):\n for i in range(2, n):\n if n%i == 0:\n return False\n return True\n\nprimesum = 0\ncount = 0\nnum = 2\n\nwhile count != limit:\n if is_prime(num):\n primesum += num\n count += 1\n num += 1\n\nprint (primesum)\n","sub_path":"0-easy/sum-of-primes/sum of pimes.py","file_name":"sum of pimes.py","file_ext":"py","file_size_in_byte":270,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"564802866","text":"#!/usr/bin/python3\nimport concurrent.futures\nimport shutil\nimport requests\nimport time\nimport urllib.request\nfrom multiprocessing.pool import ThreadPool\n\ndef retrieve(url):\n print(\"Downloading image: \", url)\n image_name = url.split('/')[-1]\n urllib.request.urlretrieve(url, image_name)\n\ndef download(url, idx):\n print(\"Downloading %d image: \", (idx, url))\n r = requests.get(url, stream=True, timeout=20)\n image_name = url.split('/')[-1]\n if r.status_code == 200:\n shutil.copyfileobj(r.raw, open(image_name, 'wb'))\n time.sleep(1)\n return image_name\n\ndef run_pool():\n urls = \\\n ['https://image1.ljcdn.com/110000-inspection/43958f9b-054c-45d4-8a9f-ef6357193916.jpg.600x450.jpg',\n 'https://image1.ljcdn.com/110000-inspection/594223d1-83e0-49b2-a737-512ef9181967.jpg.600x450.jpg',\n 'https://image1.ljcdn.com/x-se//hdic-frame/44a62ebd-e8c6-490d-9203-598f40098e5d.png.600x450.jpg',\n 'https://image1.ljcdn.com/110000-inspection/bb996ce5-b52a-4940-a255-cb43a9506071.jpg.600x450.jpg',\n 'https://image1.ljcdn.com/110000-inspection/934b41d7-2699-4601-8ed7-eeb5771081b0.jpg.600x450.jpg']\n with concurrent.futures.ThreadPoolExecutor(max_workers=3) as executor:\n # import ipdb; ipdb.set_trace()\n for url, ret in zip(urls, executor.map(open_image, urls, range(5))):\n print(ret)\n # for url, ret in zip(urls, executor.map(open_image, urls)):\n # print(ret)\n print(\"Downlaod done!\")\n return True\n\ndef open_image(url, idx):\n print(\"Download %d image: %s\" % (idx, url), end=',')\n r = requests.get(url, stream=True, timeout=30)\n # We also set stream=True so that requests doesn't download the whole image into memory first.\n image_name = url.split('/')[-1]\n if r.status_code == 200:\n with open(image_name, 'wb') as f:\n for chunk in r.iter_content(1024):\n f.write(chunk)\n print(\" Done!\")\n\nif __name__=='__main__':\n run_pool()\n","sub_path":"threads/downlaod_images.py","file_name":"downlaod_images.py","file_ext":"py","file_size_in_byte":1965,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"498975477","text":"# There are N children standing in a line. Each child is assigned a rating value. \n# You are giving candies to these children subjected to the following requirements:\n\n# 1. Each child must have at least one candy.\n# 2. Children with a higher rating get more candies than their neighbors.\n\n# What is the minimum candies you must give?\n\n# for instance,\n# [9,5,6,1,2,3]\n# means the 0th kid has the highest rating, 2nd kid has 2nd highest,\n# 1st has third highest, etc.\n# the award array:\n# 9 needs more than 5, so,\n# [1,0,0,0,0,0]\n# 6 needs more than 1 and 5, so,\n# [1,0,1,0,0,0]\n# 5 is good at the moment.\n# 3 needs more than 2, so\n# [1,0,1,0,0,1]\n# 2 needs more than 1, and 3 needs more than 2, so\n# [1,0,1,0,1,2]\n# everyone needs at least one, so add one to everyone and you're done.\n# [2,1,2,1,2,3]\n# =11\n\n# the way to solve it:\n# obj[9] = 0\n# obj[6] = 2\n\n# in general,\n# obj[array[i]] = i\n# object will naturally insertion sort these so...\n\ndef sum(n):\n if n == 0 or n == -1:\n return 0\n return n + sum(n-1)\n \ndef candy(rank):\n rightincrease = 0\n righttotal = 0\n leftincrease = 0\n lefttotal = 0\n \n previous = 100 #(=large)\n for item in rank:\n if item > previous:\n rightincrease += 1\n else:\n righttotal += sum(rightincrease)\n #reset\n rightincrease = 0\n previous = item\n righttotal += sum(rightincrease)\n previous = 0\n leftswitch = 0\n for item in rank:\n if item < previous:\n leftincrease += 1\n # elif leftswitch > 0:\n # lefttotal += sum(leftincrease - 1)\n # #reset\n # leftincrease = 0\n # leftswitch += 1\n else:\n lefttotal += sum(leftincrease)\n #reset\n leftincrease = 0\n leftswitch += 1\n previous = item\n lefttotal += sum(leftincrease)\n res = len(rank) + righttotal + lefttotal\n print('rank: ')\n print(rank)\n print\n print('righttotal: ')\n print(righttotal)\n print\n print('lefttotal: ')\n print(lefttotal)\n print\n print('leftswitch: ')\n print(leftswitch)\n print\n print('result: ')\n print(res)\n print\n print\n print\n return(res)\n\ncandy([9,5,6,1,2,3])\n#=> 11\ncandy([20,19,18,17,16,10,11,9,12,8])\n#=> 27\ncandy([20,19,18,17,16,10,11,9,12])\n#=> 26\n\n\n \n \n \n # try:\n # garbage = rank[i-1]\n # switch = 1\n # except IndexError:\n \n # res += sum(rightincrease) + sum(leftincrese)\n \n \n","sub_path":"python/arrays/candy.py","file_name":"candy.py","file_ext":"py","file_size_in_byte":2545,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"616718296","text":"# The prime factors of 13195 are 5, 7, 13 and 29.\n# What is the largest prime factor of the number 600851475143 ?\n\nimport math\n\nlimit = 600851475143\n\ndef LargestPrimeFactor(n):\n\tfor i in range(2, int(math.sqrt(n))):\n\t\tif(n % i == 0):\n\t\t\treturn max(i, LargestPrimeFactor(int(n/i)))\n\n\treturn n\n\n\nprint(LargestPrimeFactor(limit))\n","sub_path":"3/3.py","file_name":"3.py","file_ext":"py","file_size_in_byte":327,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"630916011","text":"from flask import flash, current_app\nimport urllib\nimport base64\nimport io\nfrom matplotlib import pyplot as plt\nimport matplotlib.image as mpimg\nimport random\nfrom skimage.transform import resize\n# from tensorflow.keras.models import Sequential\n# from tensorflow.keras.layers import Dense, Activation, Flatten, Conv2D, MaxPooling2D\nimport numpy as np\n\nfrom flaskr.database.image_models.collection import Collection\n\n\nBINARY_CLASS = {\n 'yellow': 0,\n 'red': 1,\n 'invalid': 3\n}\n\n\nclass Analyzer():\n def __init__(\n self,\n ):\n self.results = []\n self.epochs = 0\n self.img_size = 20\n self.model = None\n\n def execute(self):\n image_collection = Collection()\n\n # self.build_model((self.img_size, self.img_size, 3))\n training_data = []\n testing_data = []\n\n for idx, item in enumerate(image_collection):\n image = item.get_image()\n class_num = BINARY_CLASS[item.get_class()]\n\n if type(item.get_image()) == str:\n image = urllib.parse.unquote(item.get_image())\n\n # To save images locally uncomment this:\n # if not item.is_training():\n # self.save_locally(item=image, title=item.get_class() + str(idx), resize_image=True)\n\n try:\n new_array = self.convert_image(image, resize_image=True)\n if item.is_training():\n training_data.append([new_array, class_num])\n else:\n testing_data.append([new_array, class_num])\n except Exception as e:\n flash(str(e), 'error')\n pass\n\n # this is for when we have a giant image set, to reduce the memory load\n if training_data is not None and len(training_data) > 1000:\n X, y = self.build_data(training_data)\n self.model.fit(X, y, batch_size=32, epochs=20, validation_split=0.05)\n training_data = []\n\n flash('Training size: %s, testing size: %s' % (len(training_data), len(testing_data)))\n\n if len(training_data) > 0:\n X, y = self.build_data(training_data)\n # history = self.model.fit(X, y, batch_size=32, epochs=20, validation_split=0.05)\n # flash('Completed model accuracy: %s ' % history.history['val_accuracy'][-1])\n\n # self.model.save(current_app.config['UPLOAD_FOLDER']) # TODO: need a file path to save\n\n if len(testing_data) > 0:\n x_test, y_test = self.build_data(testing_data)\n # results = self.model.evaluate(x_test, y_test, batch_size=32)\n # flash('Testing loss: %s, accuracy: %s' % (str(round(results[0], 2)), str(round(results[1], 2))))\n # predictions = self.model.predict(x_test)\n # flash('Predictions: %s ' % ', '.join([str(round(p[0], 2)) for p in predictions]))\n # flash('Actual: %s ' % ', '.join([str(t[1]) for t in testing_data]))\n\n def build_data(self, data):\n random.shuffle(data)\n\n X = []\n y = []\n\n for features, label in data:\n X.append(features)\n y.append(label)\n\n X = np.array(X).reshape(-1, self.img_size, self.img_size, 3) # 1 b/c img is grayscale, come back and try to convert to rgb (1->3)\n y = np.array(y)\n\n X = X / 255.\n\n return X, y\n\n def build_model(self, columns):\n self.model = Sequential()\n\n self.model.add(Conv2D(64, (3, 3), input_shape=columns)) # First Layer\n self.model.add(Activation(\"relu\"))\n self.model.add(MaxPooling2D(pool_size=(2, 2)))\n\n self.model.add(Conv2D(64, (3, 3))) # Second Layer\n self.model.add(Activation(\"relu\"))\n self.model.add(MaxPooling2D(pool_size=(2, 2)))\n\n self.model.add(Flatten()) # Third Layer\n self.model.add(Dense(64))\n self.model.add(Activation('relu'))\n\n self.model.add(Dense(1)) # Output Layer\n self.model.add(Activation('sigmoid'))\n\n self.model.compile(loss=\"binary_crossentropy\", optimizer=\"adam\", metrics=['accuracy'])\n\n def save_locally(self, item, title, resize_image=False):\n i = self.convert_image(item, resize_image=resize_image)\n plt.imshow(i)\n plt.show()\n plt.savefig(title + '.png')\n\n def convert_image(self, item, resize_image=False):\n item = base64.b64decode(item)\n i = io.BytesIO(item)\n i = mpimg.imread(i)\n\n if resize_image:\n i = resize(i, (self.img_size, self.img_size))\n\n return i\n","sub_path":"flaskr/imageprocessing/model/analyzer.py","file_name":"analyzer.py","file_ext":"py","file_size_in_byte":4552,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"579135610","text":"from pyspark.sql import SQLContext\nfrom pyspark.sql import Row, SparkSession\nsqlContext = SQLContext(sc)\nrdd = sqlContext.read.json('hdfs://localhost:9000/user/renier/tweets.json')\nrecords= rdd.collect()\nrecords = [element for element in records if \"delete\" not in element] #remove delete tweets\nrecords = [element[\"entities\"][\"hashtags\"] for element in records if \"entities\" in element] #select only hashtags part\nrecords = [x for x in records if x] #remove empty hashtags\nrecords = [element[0][\"text\"] for element in records]\nrdd = sc.parallelize(records)\nhashtagsDataFrame = spark.createDataFrame(rdd.map(lambda x: Row(hashtag=x)))\nhashtagsDataFrame.createOrReplaceTempView(\"hashtags\")\nhashtagsDataFrame = spark.sql(\"select hashtag, count(*) as total from hashtags group by hashtag order by total\")\n#hashtagsDataFrame.show()\nhashtagsDataFrame.repartition(1).write.csv('/home/osboxes/Desktop/BigDataProject2/hashtags.csv', sep = '|')\n\n","sub_path":"hashtags-4a.py","file_name":"hashtags-4a.py","file_ext":"py","file_size_in_byte":939,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"343664507","text":"\"\"\"\nSparse CCA Comparison\n===========================\n\nThis example demonstrates how to easily train Sparse CCA variants\n\"\"\"\n\nimport numpy as np\nimport pandas as pd\nimport seaborn as sns\nimport matplotlib.pyplot as plt\nfrom sklearn.model_selection import train_test_split\nfrom cca_zoo.linear import (\n CCA,\n PLS,\n SCCA_IPLS,\n SCCA_PMD,\n ElasticCCA,\n SCCA_Span,\n)\nfrom cca_zoo.data.simulated import LinearSimulatedData\nfrom cca_zoo.model_selection import GridSearchCV\n\n# Setting plot style and font scale for better visibility\nsns.set_theme(style=\"whitegrid\")\nsns.set(font_scale=1.2)\nplt.close(\"all\")\n\n\n# Function to create a scatterplot of weights\ndef plot_true_weights_coloured(ax, weights, true_weights, title=\"\", legend=False):\n # Preprocess weights for seaborn scatterplot\n weights = np.squeeze(weights)\n ind = np.arange(len(true_weights))\n mask = np.squeeze(true_weights == 0)\n\n non_zero_df = pd.DataFrame(\n {\"Index\": ind[~mask], \"Weights\": weights[~mask], \"Type\": \"Non-Zero Weights\"}\n )\n zero_df = pd.DataFrame(\n {\"Index\": ind[mask], \"Weights\": weights[mask], \"Type\": \"Zero Weights\"}\n )\n data_df = pd.concat([non_zero_df, zero_df])\n\n # Create seaborn scatterplot\n sns.scatterplot(\n data=data_df,\n x=\"Index\",\n y=\"Weights\",\n hue=\"Type\",\n ax=ax,\n palette=\"viridis\",\n legend=legend,\n )\n ax.set_title(title)\n\n\n# Function to plot weights for each model\ndef plot_model_weights(wx, wy, tx, ty, title=\"\"):\n fig, axs = plt.subplots(2, 2, sharex=True, sharey=True)\n\n plot_true_weights_coloured(axs[0, 0], tx, tx, title=\"true x weights\")\n plot_true_weights_coloured(axs[0, 1], ty, ty, title=\"true y weights\")\n plot_true_weights_coloured(axs[1, 0], wx, tx, title=\"model x weights\")\n plot_true_weights_coloured(axs[1, 1], wy, ty, title=\"model y weights\", legend=True)\n\n # Add legend to the plot\n handles, labels = axs[1, 1].get_legend_handles_labels()\n # legend off\n plt.legend([], [], frameon=False)\n fig.legend(handles, labels, bbox_to_anchor=(0.5, -0.05), loc=\"lower center\", ncol=2)\n plt.tight_layout()\n fig.suptitle(title)\n sns.despine(trim=True)\n plt.show(block=False)\n\n\n# Initialize parameters\nnp.random.seed(42)\nn = 500\np = 200\nq = 200\nview_1_sparsity = 0.1\nview_2_sparsity = 0.1\nlatent_dims = 1\nepochs = 50\n\n# Simulate some data\ndata = LinearSimulatedData(\n view_features=[p, q],\n latent_dims=latent_dims,\n view_sparsity=[view_1_sparsity, view_2_sparsity],\n correlation=[0.9],\n)\n(X, Y) = data.sample(n)\n\ntx = data.true_features[0]\nty = data.true_features[1]\n\n# Split data into train and test sets\nX_train, X_val, Y_train, Y_val = train_test_split(X, Y, test_size=0.2)\n\n\n# Define a helper function to train and evaluate a model\ndef train_and_evaluate(model, title):\n model.fit([X_train, Y_train])\n plot_model_weights(model.weights[0], model.weights[1], tx, ty, title=title)\n return model.score([X_val, Y_val])\n\n\n# Train and evaluate each model\ncca_corr = train_and_evaluate(CCA(), \"CCA\")\npls_corr = train_and_evaluate(PLS(), \"PLS\")\nspan_cca_corr = train_and_evaluate(\n SCCA_Span(tau=[10, 10], early_stopping=True), \"Span CCA\"\n)\n\n# For PMD model we use GridSearchCV\ntau1 = [0.1, 0.5, 0.9]\ntau2 = [0.1, 0.5, 0.9]\nparam_grid = {\"tau\": [tau1, tau2]}\npmd = GridSearchCV(\n SCCA_PMD(epochs=epochs, early_stopping=True), param_grid=param_grid\n).fit([X_train, Y_train])\nplot_model_weights(\n pmd.best_estimator_.weights[0], pmd.best_estimator_.weights[1], tx, ty, title=\"PMD\"\n)\npmd_corr = pmd.score([X_val, Y_val])\n\n# Training and evaluating SCCA_IPLS models\nscca_corr = train_and_evaluate(\n SCCA_IPLS(alpha=[1e-2, 1e-2], epochs=epochs, early_stopping=True), \"SCCA_IPLS\"\n)\nscca_pos_corr = train_and_evaluate(\n SCCA_IPLS(alpha=[1e-2, 1e-2], positive=True, epochs=epochs, early_stopping=True),\n \"SCCA_IPLS+\",\n)\n\n\n# Elastic CCA Model\nalpha = [1e-2, 1e-3]\nparam_grid = {\"alpha\": alpha}\nelastic = GridSearchCV(\n ElasticCCA(epochs=epochs, early_stopping=True, l1_ratio=0.99), param_grid=param_grid\n).fit([X_train, Y_train])\nplot_model_weights(\n elastic.best_estimator_.weights[0],\n elastic.best_estimator_.weights[1],\n tx,\n ty,\n title=\"ElasticCCA\",\n)\nelastic_corr = elastic.score([X_val, Y_val])\n\n# Print final comparison\nprint(\"CCA Correlation: \", cca_corr)\nprint(\"PLS Correlation: \", pls_corr)\nprint(\"Span CCA Correlation: \", span_cca_corr)\nprint(\"PMD Correlation: \", pmd_corr)\nprint(\"SCCA_IPLS Correlation: \", scca_corr)\nprint(\"SCCA_IPLS+ Correlation: \", scca_pos_corr)\nprint(\"ElasticCCA Correlation: \", elastic_corr)\n\n# Store model names and correlations in a dictionary\nmodel_results = {\n \"CCA\": cca_corr,\n \"PLS\": pls_corr,\n \"Span CCA\": span_cca_corr,\n \"PMD\": pmd_corr,\n \"SCCA_IPLS\": scca_corr,\n \"SCCA_IPLS (Positive)\": scca_pos_corr,\n \"Elastic CCA\": elastic_corr,\n}\n\n# Convert dictionary to pandas DataFrame for easy plotting\nresults_df = pd.DataFrame.from_dict(\n model_results, orient=\"index\", columns=[\"Validation Correlation\"]\n)\n\n# Plot the data\nplt.figure(figsize=(10, 5))\nsns.barplot(\n x=results_df.index, y=results_df[\"Validation Correlation\"], palette=\"viridis\"\n)\nplt.xticks(rotation=90)\nplt.title(\"Comparison of Models by Validation Correlation\")\nplt.ylabel(\"Validation Correlation\")\nplt.tight_layout()\nplt.show()\n","sub_path":"docs/source/examples/plot_sparse_cca.py","file_name":"plot_sparse_cca.py","file_ext":"py","file_size_in_byte":5358,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"564711241","text":"# (c) 2017 Spiros Papadimitriou \n#\n# This file is released under the MIT License:\n# https://opensource.org/licenses/MIT\n# This software is distributed on an \"AS IS\" basis,\n# WITHOUT WARRANTY OF ANY KIND, either express or implied.\n\nimport unittest\nfrom homework_unittest import HomeworkTestCase\n\nfrom upc import is_upc_valid\n\n\nclass UPCTests(HomeworkTestCase):\n def test_simple(self):\n upc11 = \"63000029145\"\n expected_check_digit = 2\n for digit12 in range(10):\n upc12 = int(upc11 + str(digit12))\n result = is_upc_valid(upc12)\n expected_result = (digit12 == expected_check_digit)\n self.assertEquals(expected_result, result,\n msg=\"Failed for UPC code %s (expected %s, got %s)\" %\n (upc12, expected_result, result))\n\n def test_short(self):\n self.assertTrue(is_upc_valid(0))\n for i in range(1, 10):\n self.assertFalse(is_upc_valid(i))\n\n\nif __name__ == '__main__':\n unittest.main()\n","sub_path":"hw2b/tests/test_upc.py","file_name":"test_upc.py","file_ext":"py","file_size_in_byte":991,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"9323831","text":"import zmq\nimport json\n\nclass Worker:\n\n def __init__(self, port):\n \n self.port = port\n \n # Create zmq socket on specific port\n self.context = zmq.Context()\n self.context = self.context or zmq.Context.instance()\n self.worker = self.context.socket(zmq.REQ) \n self.worker.connect(\"tcp://localhost:{}\".format(self.port))\n\n\n def recv(self):\n b_request = self.worker.recv() \n return json.loads(b_request)\n \n def send (self, reply):\n b_reply = json.dumps(reply).encode()\n self.worker.send(b_reply)\n pass\n\n def communicate(self, msg):\n\n self.send(msg)\n reply = self.recv()\n\n return reply","sub_path":"gym_mevea_single/tutorial_model/Scripts/worker.py","file_name":"worker.py","file_ext":"py","file_size_in_byte":706,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"90383053","text":"import pytest\nfrom webtest import TestApp\nfrom app.flask_factory import assemble_app\nfrom app.settings import TestConfig\nfrom app.extensions import db as _db\nfrom flask import Flask\n\n_app = assemble_app(TestConfig)\n\n\n\n@pytest.yield_fixture()\ndef flask_app():\n flask_context = _app.test_request_context()\n flask_context.push()\n yield _app\n flask_context.pop()\n\n\n@pytest.fixture()\ndef testapp(flask_app):\n \"\"\"\n webtest fixture\n Args:\n flask_app (Flask):\n\n Returns:\n TestApp\n \"\"\"\n with flask_app.app_context():\n _db.create_all()\n return TestApp(flask_app)\n\n\n@pytest.yield_fixture()\ndef test_db(flask_app):\n _db.app = flask_app\n _db.create_all()\n yield _db\n _db.drop_all()\n\n\n","sub_path":"thai_resort/tests/conftest.py","file_name":"conftest.py","file_ext":"py","file_size_in_byte":739,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"374976395","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\nfrom setuptools import setup, find_packages\nimport re\nimport os\nimport codecs\n\n\n# Borrowed from\n# https://github.com/jezdez/django_compressor/blob/develop/setup.py\ndef read(*parts):\n return codecs.open(os.path.join(os.path.dirname(__file__), *parts)).read()\n\n\ndef find_version(*file_paths):\n version_file = read(*file_paths)\n version_match = re.search(r\"^__version__ = ['\\\"]([^'\\\"]*)['\\\"]\",\n version_file, re.M)\n if version_match:\n return version_match.group(1)\n raise RuntimeError(\"Unable to find version string.\")\n\n\nsetup(\n name='needle',\n version=find_version(\"needle\", \"__init__.py\"),\n description='Automated testing for your CSS.',\n author='Ben Firshman',\n author_email='ben@firshman.co.uk',\n url='https://github.com/bfirsh/needle',\n packages=find_packages(exclude=['scripts', 'tests']),\n package_data={'needle': ['js/*']},\n test_suite='nose.collector',\n entry_points = {\n 'nose.plugins.0.10': [\n 'needle-capture = needle.plugin:NeedleCapturePlugin'\n ]\n },\n install_requires=[\n 'nose>=1.0.0',\n 'selenium>=2,<3',\n 'unittest2>=0.5.1',\n 'pillow',\n ],\n)\n\n","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":1245,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"202789396","text":"import os\nimport json\n\nfrom shapes import *\nfrom tool import *\n\nHOME = os.path.expanduser(\"~\")\n\ndef exists(path):\n return os.path.exists(path)\n\ndef makeobjects(shps):\n i = 0\n for x in shps:\n if x[\"type\"] == \"dot\":\n shps[i] = Dot.load(x)\n elif x[\"type\"] == \"line\":\n shps[i] = Line.load(x)\n elif x[\"type\"] == \"rect\":\n shps[i] = Rect.load(x)\n elif x[\"type\"] == \"circle\":\n shps[i] = Circle.load(x)\n elif x[\"type\"] == \"polygon\":\n shps[i] = Polygon.load(x)\n i += 1\n return shps\n\ndef config():\n if exists(os.path.join(HOME, \".alcad\", \"config.json\")):\n with open(os.path.join(HOME, \".alcad\", \"config.json\")) as f:\n out = json.loads(f.read())\n for key, val in out.items():\n if type(val) == dict:\n if val[\"type\"] == \"color\":\n out[key] = Color.load(val[\"color\"])\n elif val[\"type\"] == \"tool\":\n out[key] = Tool.load(val)\n return out\n else:\n return None\n\ndef shapes():\n if exists(os.path.join(HOME, \".alcad\", \"shapes.json\")):\n with open(os.path.join(HOME, \".alcad\", \"shapes.json\")) as f:\n out = json.loads(f.read())\n return makeobjects(out)\n else:\n return []\n","sub_path":"load.py","file_name":"load.py","file_ext":"py","file_size_in_byte":1348,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"477713309","text":"import json\nimport requests\nimport time\nimport click\nimport pandas as pd\n\n\ndef call_post(endpoint, request_url, header, data=False):\n\n response = requests.post(url=request_url + endpoint,\n headers=header, data=data)\n response.raise_for_status()\n return response\n\n\ndef call_get(endpoint, request_url, header):\n response = requests.get(url=request_url + endpoint, headers=header)\n response.raise_for_status()\n return response\n\n\ndef create_run(run_config, request_url, header):\n result = call_post(\"synchronizationRuns\", request_url,\n header, json.dumps(run_config))\n return json.loads(result.text)['id']\n\n\ndef start_run(run_id, request_url, header):\n start_run_endpoint = f'synchronizationRuns/{run_id}/start'\n result = call_post(start_run_endpoint, request_url, header)\n return result.status_code\n\n\ndef check_run_status(run_id, request_url, header, status_response=None):\n print(f'checking status of run {run_id}')\n status_endpoint = f'synchronizationRuns/{run_id}/status'\n status_response = call_get(status_endpoint, request_url, header)\n status_response = json.loads(status_response.text)['status']\n print(status_response)\n if status_response != 'FINISHED':\n time.sleep(5)\n return check_run_status(run_id, request_url, header, status_response)\n elif status_response == 'FAILED':\n print('Run Failed: Validate your connector in LeanIX')\n else:\n return True\n\n\ndef fetch_results(run_id, request_url, header):\n results_endpoint = f'synchronizationRuns/{run_id}/results'\n results_response = call_get(results_endpoint, request_url, header)\n return json.loads(results_response.text)\n\n\ndef export_data(run_config, request_url, header):\n run_id = create_run(run_config, request_url, header)\n\n if start_run(run_id, request_url, header) == 200:\n if check_run_status(run_id, request_url, header):\n run_results = fetch_results(run_id, request_url, header)\n return run_results\n\n\nsvc_option = click.option(\n '--svc-instance', required=True, prompt=True, hide_input=True)\nhost_option = click.option('--app-instance', required=True)\napi_token_option = click.option('--api-token', required=True)\n\n\n@click.group()\ndef cli():\n pass\n\n\n@cli.command()\n@svc_option\n@host_option\n@api_token_option\ndef start_run(svc_instance, app_instance, api_token):\n\n auth_url = f'https://{svc_instance}/services/mtm/v1/oauth2/token'\n request_url = f'https://{app_instance}/services/integration-api/v1/'\n response = requests.post(auth_url, auth=('apitoken', api_token),\n data={'grant_type': 'client_credentials'})\n response.raise_for_status()\n access_token = response.json()['access_token']\n auth_header = 'Bearer ' + access_token\n header = {'Authorization': auth_header, 'Content-Type': 'application/json'}\n\n config_df = pd.read_excel('configs.xlsx').fillna('')\n\n for index, row in config_df.iterrows():\n\n run_config = {x: row[x] for x in list(config_df)}\n\n run_results = export_data(run_config, request_url, header)\n\n out_filename = '_'.join(\n [run_config['connectorId'], run_config['connectorVersion'], 'results.json'])\n\n with open(out_filename, 'w') as outfile:\n json.dump(run_results, outfile, indent=2)\n\n\nif __name__ == '__main__':\n cli()\n","sub_path":"startIntegrationAPIRun/startOutboundRun.py","file_name":"startOutboundRun.py","file_ext":"py","file_size_in_byte":3390,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"652764488","text":"file = open('word.txt')\nword = list(file.read())\nansw = []\nfor i in range(len(word)):\n answ.append('_')\nout = ''\nfor i in answ:\n out += i + ' '\nprint(out)\nincor = []\nindt = 0\nwhile indt <= 10:\n let = input('Enter letter: ')\n if not let.isalpha() or len(let) > 1:\n print('Incorrect letter: ')\n else:\n file = False\n for i in range(len(word)):\n if let == word[i]:\n file = True\n answ[i] = word[i]\n if file == False:\n if let not in incor:\n print('Incorrect (')\n incor.append(let)\n indt += 1\n else:\n print('You have already entered this letter, and it is incorrect ! ')\n else:\n print('Correct !')\n out = ''\n for i in answ:\n out += i + ' '\n print(out)\n if answ == word:\n print('You WON !')\n break\n out = ''\n for i in incor:\n out += i + ', '\n print('Incorrect letters: ' + out)\n if indt == 1:\n print(' \\n \\n \\n _')\n if indt == 2:\n print(' \\n \\n \\n ___')\n if indt == 3:\n print(' \\n \\n \\n|___')\n if indt == 4:\n print(' \\n \\n| \\n|___')\n if indt == 5:\n print(' \\n| \\n| \\n|___')\n if indt == 6:\n print(' _ \\n| \\n| \\n|___')\n if indt == 7:\n print(' _ _\\n| \\n| \\n|___')\n if indt == 8:\n print(' _ _\\n| o\\n| \\n|___')\n if indt == 9:\n print(' _ _\\n| o\\n| / \\n|___')\n if indt == 10:\n print(' _ _\\n| o\\n| /|\\n|___')\n print('You lose (')\n break","sub_path":"without_funcs/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1757,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"224193288","text":"##############################################################################\n#\n# Copyright (c) 2007 Zope Foundation and Contributors.\n# All Rights Reserved.\n#\n# This software is subject to the provisions of the Zope Public License,\n# Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution.\n# THIS SOFTWARE IS PROVIDED \"AS IS\" AND ANY AND ALL EXPRESS OR IMPLIED\n# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS\n# FOR A PARTICULAR PURPOSE.\n#\n##############################################################################\n\"\"\"Form Implementation\n\n$Id: form.py 77154 2007-06-27 19:29:23Z srichter $\n\"\"\"\n__docformat__ = \"reStructuredText\"\nimport sys\nimport zope.interface\nimport zope.component\nimport zope.location\nfrom zope.app.pagetemplate import ViewPageTemplateFile\nfrom zope.pagetemplate.interfaces import IPageTemplate\nfrom z3c.form import util\nfrom z3c.form.interfaces import IAfterWidgetUpdateEvent\nfrom z3c.template.interfaces import ILayoutTemplate\n\nfrom z3c.formsnippet import interfaces\nfrom z3c.formsnippet.i18n import MessageFactory as _\n\n\nclass Formframe(object):\n \"\"\"A Mixin for Form Frames\"\"\"\n\n frame = None\n errorstatus = None #ViewPageTemplateFile('pt/errorstatus.pt')\n\n def __call__(self):\n self.update()\n layout = zope.component.getMultiAdapter((self, self.request),\n ILayoutTemplate)\n return layout(self)\n\n def render(self):\n '''See interfaces.IForm'''\n # render content template\n # Make sure, the frame object has a template that can be called\n # from the frame template\n\n if self.template is None:\n self.template = zope.component.getMultiAdapter(\n (self, self.request), IPageTemplate)\n \n if self.errorstatus is None:\n self.errorstatus = zope.component.getMultiAdapter(\n (self, self.request), interfaces.IErrorstatusTemplate)\n\n if self.frame is None:\n self.frame = zope.component.getMultiAdapter(\n (self, self.request), interfaces.IFormframeTemplate)\n\n return self.frame(self)\n\nclass AddFormframe(Formframe):\n\n def __call__(self):\n self.update()\n if self._finishedAdd:\n self.request.response.redirect(self.nextURL())\n return ''\n layout = zope.component.getMultiAdapter((self, self.request),\n ILayoutTemplate)\n return layout(self)\n\nclass Snippet(zope.location.Location):\n \"\"\"HTML snippets around a widget.\"\"\"\n zope.interface.implements(interfaces.ISnippets)\n\n def __init__(self, view):\n self.view = view\n\n def __getattr__(self, name):\n view = self.view\n snippet = zope.component.getMultiAdapter(\n (view.context, view.request, view.form, view.field, view),\n IPageTemplate, name=name+'_'+view.mode)\n return snippet(self.view)\n\n\n@zope.component.adapter(IAfterWidgetUpdateEvent)\ndef addWidgetsnippet(event):\n \"\"\"instantiates snippets\"\"\"\n widget = event.widget\n widget.snippets = Snippet(widget)\n\nclass FormframeTemplateFactory(object):\n \"\"\"Formframe template factory.\"\"\"\n\n def __init__(self, filename, contentType='text/html'):\n self.template = ViewPageTemplateFile(filename, content_type=contentType)\n def __call__(self, view, request):\n return self.template.__get__(view, None)\n\n\nclass ErrorstatusTemplateFactory(object):\n \"\"\"Errorstatus template factory.\"\"\"\n\n def __init__(self, filename, contentType='text/html'):\n self.template = ViewPageTemplateFile(filename, content_type=contentType)\n def __call__(self, view, request):\n # FIXME - Return a bound template - not very pretty, but\n # I don't see another solution...\n return self.template.__get__(view, None)\n\n\nclass SnippetTemplateFactory(object):\n \"\"\"Snippet template factory.\"\"\"\n\n def __init__(self, filename, contentType='text/html',\n context=None, request=None, view=None,\n field=None, widget=None):\n self.template = ViewPageTemplateFile(filename, content_type=contentType)\n zope.component.adapter(\n util.getSpecification(context),\n util.getSpecification(request),\n util.getSpecification(view),\n util.getSpecification(field),\n util.getSpecification(widget))(self)\n zope.interface.implementer(IPageTemplate)(self)\n\n def __call__(self, context, request, view, field, widget):\n return self.template\n\n \n","sub_path":"Sandbox/dusty/z3c.formsnippet/trunk/src/z3c/formsnippet/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":4605,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"31448000","text":"\"\"\"\ncode: pmap_io_test.py\n\"\"\"\nimport os\nimport time\n\nimport tables as tb\nimport numpy as np\n\nfrom pytest import mark\n\nfrom .. core.system_of_units_c import units\nfrom .. database import load_db\nfrom .. sierpe import blr\n\nfrom . import tbl_functions as tbl\nfrom . import peak_functions as pf\nfrom . import peak_functions_c as cpf\n\nfrom . params import S12Params as S12P\nfrom . params import ThresholdParams\nfrom . params import PMaps\n\nfrom . pmap_io import pmap_writer\nfrom . pmap_io import S12\nfrom . pmap_io import S2Si\n\nfrom . pmaps_functions import read_pmaps\nfrom . pmaps_functions import read_run_and_event_from_pmaps_file\nfrom . pmaps_functions_c import df_to_pmaps_dict\nfrom . pmaps_functions_c import df_to_s2si_dict\n\n\n@mark.parametrize( 'filename, with_',\n (('test_pmaps_auto.h5', True),\n ('test_pmaps_manu.h5', False)))\ndef test_pmap_writer(config_tmpdir, filename, with_,\n s12_dataframe_converted,\n s2si_dataframe_converted):\n\n PMP_file_name = os.path.join(str(config_tmpdir), filename)\n\n # Get test data\n s12, a = s12_dataframe_converted\n s2si, b = s2si_dataframe_converted\n\n P = PMaps(s12, s12, s2si) # TODO Remove duplication of s12\n\n event_numbers = sorted(set(s12).union(set(s2si)))\n timestamps = { e : int(time.time() % 1 * 10 ** 9) for e in event_numbers }\n\n run_number = 632\n\n # The actual pmap writing: the component whose functionality is\n # being tested here.\n\n # Two different ways of using pmap_writer (both tested by\n # different parametrizations of this test)\n if with_: # Close implicitly with context manager\n with pmap_writer(PMP_file_name) as write:\n for e in event_numbers:\n timestamp = timestamps[e]\n s1 = S12 (P.S1 .get(e, {}) )\n s2 = S12 (P.S2 .get(e, {}) )\n s2si = S2Si(P.S2Si.get(e, {}) )\n write(run_number, e, timestamp, s1, s2, s2si)\n else: # Close manually\n write = pmap_writer(PMP_file_name)\n for e in event_numbers:\n timestamp = timestamps[e]\n s1 = S12 (P.S1 .get(e, {}) )\n s2 = S12 (P.S2 .get(e, {}) )\n s2si = S2Si(P.S2Si.get(e, {}) )\n write(run_number, e, timestamp, s1, s2, s2si)\n write.close()\n\n # Read back the data we have just written\n s1df, s2df, s2sidf = read_pmaps(PMP_file_name)\n rundf, evtdf = read_run_and_event_from_pmaps_file(PMP_file_name)\n\n # Convert them into our transient format\n S1D = df_to_pmaps_dict (s1df)\n S2D = df_to_pmaps_dict (s2df)\n S2SiD = df_to_s2si_dict(s2sidf)\n\n ######################################################################\n # Compare original data to those read back\n\n # The S12s\n for original_S, recovered_S in zip(( S1D, S2D),\n (P.S1, P.S2)):\n for event_no, event in recovered_S.items():\n for peak_no, recovered_peak in event.items():\n original_peak = original_S[event_no][peak_no]\n np.testing.assert_allclose(recovered_peak.t, original_peak.t)\n np.testing.assert_allclose(recovered_peak.E, original_peak.E)\n\n # The S2Sis\n for event_no, event in S2SiD.items():\n for peak_no, peak in event.items():\n for sipm_id, recovered_Es in peak.items():\n original_Es = P.S2Si[event_no][peak_no][sipm_id]\n np.testing.assert_allclose(recovered_Es, original_Es)\n\n # Event numbers\n np.testing.assert_equal(evtdf.evt_number.values,\n np.array(event_numbers, dtype=np.int32))\n\n # Run numbers\n np.testing.assert_equal(rundf.run_number.values,\n np.full(len(event_numbers), run_number, dtype=np.int32))\n\n\n\n@mark.slow\ndef test_pmap_electrons_40keV(config_tmpdir):\n # NB: avoid taking defaults for PATH_IN and PATH_OUT\n # since they are in general test-specific\n # NB: avoid taking defaults for run number (test-specific)\n\n RWF_file_name = os.path.join(os.environ['ICDIR'],\n 'database/test_data/',\n 'electrons_40keV_z250_RWF.h5')\n\n PMAP_file_name = os.path.join(str(config_tmpdir),\n 'electrons_40keV_z250_PMP.h5')\n\n s1_params = S12P(tmin=90*units.mus,\n tmax=110*units.mus,\n lmin=4,\n lmax=20,\n stride=4,\n rebin=False)\n s2_params = S12P(tmin=110*units.mus,\n tmax=1190*units.mus,\n lmin=80,\n lmax=200000,\n stride=40,\n rebin=True)\n thr = ThresholdParams(thr_s1=0.2*units.pes,\n thr_s2=1*units.pes,\n thr_MAU=3*units.adc,\n thr_sipm=5*units.pes,\n thr_SIPM=20*units.pes)\n\n run_number = 0\n\n with tb.open_file(RWF_file_name,'r') as h5rwf:\n with pmap_writer(PMAP_file_name) as write:\n\n #waveforms\n pmtrwf, pmtblr, sipmrwf = tbl.get_vectors(h5rwf)\n\n # data base\n DataPMT = load_db.DataPMT(run_number)\n pmt_active = np.nonzero(DataPMT.Active.values)[0].tolist()\n adc_to_pes = abs(DataPMT.adc_to_pes.values)\n coeff_c = abs(DataPMT.coeff_c.values)\n coeff_blr = abs(DataPMT.coeff_blr.values)\n DataSiPM = load_db.DataSiPM()\n adc_to_pes_sipm = DataSiPM.adc_to_pes.values\n\n # number of events\n NEVT = pmtrwf.shape[0]\n # number of events for test (at most NEVT)\n NTEST = 2\n # loop\n XS1L = []\n XS2L = []\n XS2SiL = []\n for event in range(NTEST):\n # deconv\n CWF = blr.deconv_pmt(pmtrwf[event], coeff_c, coeff_blr, pmt_active)\n # calibrated sum\n csum, csum_mau = cpf.calibrated_pmt_sum(CWF,\n adc_to_pes,\n pmt_active = pmt_active,\n n_MAU=100,\n thr_MAU=thr.thr_MAU)\n # zs sum\n s2_ene, s2_indx = cpf.wfzs(csum, threshold=thr.thr_s2)\n s2_t = cpf.time_from_index(s2_indx)\n s1_ene, s1_indx = cpf.wfzs(csum_mau, threshold=thr.thr_s1)\n s1_t = cpf.time_from_index(s1_indx)\n\n # S1 and S2\n s1 = cpf.find_S12(s1_ene, s1_indx, **s1_params._asdict())\n s2 = cpf.find_S12(s2_ene, s2_indx, **s2_params._asdict())\n #S2Si\n sipm = cpf.signal_sipm(sipmrwf[event],\n adc_to_pes_sipm,\n thr=thr.thr_sipm,\n n_MAU=100)\n SIPM = cpf.select_sipm(sipm)\n s2si = pf.sipm_s2_dict(SIPM, s2, thr=thr.thr_SIPM)\n\n # tests:\n # energy vector and time vector equal in S1 and s2\n assert len(s1[0][0]) == len(s1[0][1])\n assert len(s2[0][0]) == len(s2[0][1])\n\n if s2 and s2si:\n for nsipm in s2si[0]:\n assert len(s2si[0][nsipm]) == len(s2[0][0])\n\n # make S1, S2 and S2Si objects (from dicts)\n S1 = S12(s1)\n S2 = S12(s2)\n Si = S2Si(s2si)\n # store in lists for further testing\n XS1L.append(s1)\n XS2L.append(s2)\n XS2SiL.append(s2si)\n # produce a fake timestamp (in real like comes from data)\n timestamp = int(time.time())\n # write to file\n write(run_number, event, timestamp, S1, S2, Si)\n # Read back\n s1df, s2df, s2sidf = read_pmaps(PMAP_file_name)\n rundf, evtdf = read_run_and_event_from_pmaps_file(PMAP_file_name)\n # get the dicts\n\n S1L = df_to_pmaps_dict(s1df)\n S2L = df_to_pmaps_dict(s2df)\n S2SiL = df_to_s2si_dict(s2sidf)\n\n #test\n for event in range(len(XS1L)):\n s1 = XS1L[event]\n if s1: # dictionary not empty\n s1p = S1L[event]\n for peak_number in s1p:\n np.testing.assert_allclose(s1p[peak_number].t,\n s1[peak_number][0])\n np.testing.assert_allclose(s1p[peak_number].E,\n s1[peak_number][1])\n s2 = XS2L[event]\n if s2:\n s2p = S2L[event]\n for peak_number in s2p:\n np.testing.assert_allclose(s2p[peak_number].t,\n s2[peak_number][0])\n np.testing.assert_allclose(s2p[peak_number].E,\n s2[peak_number][1])\n s2si = XS2SiL[event]\n if s2si:\n sip = S2SiL[event]\n for peak_number in sip:\n sipm = sip[peak_number]\n sipm2 = s2si[peak_number]\n for nsipm in sipm:\n np.testing.assert_allclose(sipm[nsipm], sipm2[nsipm])\n","sub_path":"invisible_cities/reco/pmap_io_test.py","file_name":"pmap_io_test.py","file_ext":"py","file_size_in_byte":9550,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"46439627","text":"\n\nfrom xai.brain.wordbase.nouns._mortgagee import _MORTGAGEE\n\n#calss header\nclass _MORTGAGEES(_MORTGAGEE, ):\n\tdef __init__(self,): \n\t\t_MORTGAGEE.__init__(self)\n\t\tself.name = \"MORTGAGEES\"\n\t\tself.specie = 'nouns'\n\t\tself.basic = \"mortgagee\"\n\t\tself.jsondata = {}\n","sub_path":"xai/brain/wordbase/nouns/_mortgagees.py","file_name":"_mortgagees.py","file_ext":"py","file_size_in_byte":259,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"203686650","text":"#!/usr/bin/env python\n# encoding: utf-8\n\n\"\"\"\nGiven a maze, you can only move up, down, right and left. Start from\nthe start point and to see if you can arrive at the end point.\n\"\"\"\n\nfh = open(\"maze.txt\", 'r')\n\nN = int(fh.readline().strip())\nM = int(fh.readline().strip())\n\nmaze = fh.readlines()\nfh.close()\n\nmaze = [each.strip() for each in maze]\ntable = [[False]*N]*M\nres = []\n\ndef solve(maze, N, M):\n n = len(maze)\n s_pos = 0\n g_pos = 0\n for ix in range(0, n):\n if 'S' in maze[ix]:\n s_pos = (ix, maze[ix].index('S'))\n if s_pos and g_pos:\n break\n if 'G' in maze[ix]:\n g_pos = (ix, maze[ix].index('G'))\n if s_pos and g_pos:\n break\n return s_pos, g_pos\n\n\ndef recursive(maze, N, M, S, G, step):\n if S ==G:\n res.append(step)\n maze[S[0]][S[1]] = True\n return\n if S[0] < M-1 and table[S[0]][S[1]] == False:\n recursive(maze, N, M, (S[0]+1, S[1]),G, step+1)\n if S[0] > 0 and table[S[0]-1][S[1]] == False:\n recursive(maze, N, M, (S[0]-1, S[1]), G, step +1)\n if S[1] < N -1 and table[S[0]][S[1]+1] == False:\n recursive(maze, N, M, (S[0], S[1]+1), G, step+1)\n if S[1] > 0 and table[S[0]][S[1]-1] == False:\n recursive(maze, N, M, (S[0], S[1]-1, G, step +1))\n return\n\nS, G = solve(maze, N, M)\nrecursive(maze, N,M,S,G,0)\n\n\n\n\n","sub_path":"week28/maze.py","file_name":"maze.py","file_ext":"py","file_size_in_byte":1383,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"445759847","text":"'''\r\nMerge Sorted Array\r\n Array\r\n\r\nint [m] nums1\r\nint [n] nums2\r\n\r\n- merge nums2 into nums1\r\n - as one sorted array\r\n\r\n- Assume\r\n - nums1 has enough space to hold additional items from num2\r\n\r\n- Using very simple trick\r\n - Since nums1 have extra size at tail with length of nums2\r\n - Merge them first, then simply sort\r\n\r\n'''\r\nclass Solution:\r\n def merge(self, nums1: List[int], m: int, nums2: List[int], n: int) -> None:\r\n \"\"\"\r\n Do not return anything, modify nums1 in-place instead.\r\n \"\"\"\r\n \r\n if not nums2:\r\n return nums1\r\n \r\n if len(nums1) == len(nums2):\r\n for i in range(len(nums2)):\r\n nums1[i] = nums2[i]\r\n return nums1\r\n \r\n j = 0\r\n for i in range(len(nums1) - len(nums2), len(nums1), 1):\r\n #print(i)\r\n nums1[i] = nums2[j]\r\n j += 1\r\n \r\n nums1.sort()\r\n \r\n return nums1","sub_path":"leetcode/problems/Array/88.py","file_name":"88.py","file_ext":"py","file_size_in_byte":974,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"135541191","text":"from django.conf.urls import url\nfrom . import views\n\nurlpatterns = {\n url(r'list',views.UserList.as_view()),\n url(r'^(?P[0-9]+)/$',views.UserDetail.as_view()),\n url(r'regist',views.regist),\n url(r'login',views.login),\n url(r'updateInfo',views.updateInfo),\n}","sub_path":"BackEnd/User/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":277,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"587019464","text":"# Written by Scott Phillpott\n# 23 August 2016\n# Intent is to have this program covert all .docx filenames in directory to .txt format.\n\nimport pypandoc\nimport os\n\ndocroot=\"./docxdocuments\"\n\nintype= input(\"What format for input? \")\nouttype= input(\"what output for output? \")\n\nfor filename in os.listdir(docroot):\n\tif filename.endswith(intype):\n\t\tfullpath = os.path.join(docroot, filename);\n\t\toutput = pypandoc.convert_file(fullpath, outtype)\n\t\toutfile = fullpath[:-4] + outtype\n\t\tf = open(outfile, 'w')\n\t\tf.write(output)\n\t\tf.close()\n","sub_path":"pandoc/pandoc_convert.py","file_name":"pandoc_convert.py","file_ext":"py","file_size_in_byte":533,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"652492830","text":"import asyncio\n\nimport pytest\n\nfrom async_class import AsyncClass, TaskStore\n\n\nasync def test_simple():\n await AsyncClass()\n\n\nasync def test_simple_class():\n class Simple(AsyncClass):\n event = asyncio.Event()\n\n async def __ainit__(self):\n self.loop.call_soon(self.event.set)\n await self.event.wait()\n\n instance = await Simple()\n\n assert instance.__class__ == Simple\n\n assert Simple.event.is_set()\n\n\nasync def test_simple_inheritance():\n class Simple(AsyncClass):\n event = asyncio.Event()\n\n async def __ainit__(self):\n self.loop.call_soon(self.event.set)\n await self.event.wait()\n\n def __del__(self):\n return super().__del__()\n\n class MySimple(Simple):\n pass\n\n instance = await MySimple()\n\n assert instance.__class__ == MySimple\n assert instance.__class__ != Simple\n\n assert Simple.event.is_set()\n assert MySimple.event.is_set()\n\n\nasync def test_simple_with_init():\n class Simple(AsyncClass):\n event = asyncio.Event()\n\n def __init__(self):\n super().__init__()\n self.value = 3\n\n async def __ainit__(self):\n self.loop.call_soon(self.event.set)\n await self.event.wait()\n\n instance = await Simple()\n\n assert instance.__class__ == Simple\n\n assert Simple.event.is_set()\n assert instance.value == 3\n\n\nasync def test_simple_with_init_inheritance():\n class Simple(AsyncClass):\n event = asyncio.Event()\n\n def __init__(self):\n super().__init__()\n self.value = 3\n\n async def __ainit__(self):\n self.loop.call_soon(self.event.set)\n await self.event.wait()\n\n class MySimple(Simple):\n pass\n\n instance = await MySimple()\n\n assert instance.__class__ == MySimple\n\n assert Simple.event.is_set()\n assert MySimple.event.is_set()\n assert instance.value == 3\n\n\nasync def test_non_corotine_ainit():\n with pytest.raises(TypeError):\n\n class _(AsyncClass):\n def __ainit__(self):\n pass\n\n\nasync def test_async_class_task_store():\n class Sample(AsyncClass):\n async def __ainit__(self):\n self.future = self.create_future()\n self.task = self.create_task(asyncio.sleep(3600))\n\n obj = await Sample()\n\n assert obj.__tasks__\n assert isinstance(obj.__tasks__, TaskStore)\n\n assert not obj.future.done()\n assert not obj.task.done()\n\n await obj.close()\n\n assert obj.future.done()\n assert obj.task.done()\n\n assert obj.is_closed\n await obj.close()\n\n del obj\n\n\nasync def test_async_class_inherit_from():\n class Parent(AsyncClass):\n pass\n\n class Child(Parent):\n async def __ainit__(self, parent: Parent):\n self._link_to(parent)\n\n parent = await Parent()\n child = await Child(parent)\n\n assert not child.is_closed\n await parent.close()\n assert child.is_closed\n","sub_path":"tests/test_async_class.py","file_name":"test_async_class.py","file_ext":"py","file_size_in_byte":2965,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"118830543","text":"class Solution(object):\n def permuteUnique(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: List[List[int]]\n \"\"\"\n if len(nums)==1: return [nums]\n nums.sort()\n rst=[]\n self.DFS(nums, [], rst)\n return rst \n def DFS(self, nums, path, rst):\n if not nums:\n rst.append(path)\n return \n for i in range(len(nums)):\n if i and nums[i]==nums[i-1]:\n continue\n self.DFS(nums[:i]+nums[i+1:], path+[nums[i]], rst)","sub_path":"47-Permutations-II/solution.py","file_name":"solution.py","file_ext":"py","file_size_in_byte":540,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"488118804","text":"def main():\n # Get user inputs for prior probabilities\n prior_positive_prob = float(input(\"What is prior probability of: \"))\n sensitivity = float(input(\"What is sensitivity: \"))\n specitivity = float(input(\"What is the specitivity: \"))\n\n # Find negative probability\n prior_negative_prob = 1-prior_positive_prob\n\n # Calculate positive joint\n joint_positive = (prior_positive_prob*sensitivity) + \\\n (prior_negative_prob)*(1-specitivity)\n print(\"\\nJoint of positive probability: \" + str(joint_positive) + \"\\n\")\n\n # Calculate negative joint\n joint_negative = (prior_positive_prob)*(1-sensitivity) + \\\n (specitivity*prior_negative_prob)\n print(\"Joint of negative probability: \" + str(joint_negative) + \"\\n\")\n\n # Find Posterior Positive Probability of prior positive probability\n posterior_pos_prob = (prior_positive_prob*sensitivity) / joint_positive\n print(\"Posterior Positive Result of Prior Positive Probability: \" +\n str(posterior_pos_prob) + \"\\n\")\n\n # Find Posterior Negative Probability of prior negative probabilty\n posterior_neg_prob = (prior_positive_prob*(1-sensitivity)) / joint_negative\n print(\"Posterior negative probability of prior negative probability: \"\n + str(posterior_neg_prob) + \"\\n\")\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"udacity_python/statistics/bayes_rule/bayes_rule.py","file_name":"bayes_rule.py","file_ext":"py","file_size_in_byte":1350,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"466553068","text":"import os\nimport re\nfrom distutils.core import setup\n\n\ntests_require = [\n 'pytest',\n 'pytest-runner',\n 'python-coveralls',\n 'pytest-pep8'\n]\n\ninstall_requires = [\n 'pydent',\n 'dill',\n 'opath',\n 'colorama',\n 'prompt_toolkit',\n 'fire',\n 'cryptography'\n]\n\nclassifiers = [],\n\n# setup functions\n\ndef sanitize_string(str):\n str = str.replace('\\\"', '')\n str = str.replace(\"\\'\", '')\n return str\n\n\ndef parse_version_file():\n \"\"\"Parse the __version__.py file\"\"\"\n here = os.path.abspath(os.path.dirname(__file__))\n ver_dict = {}\n with open(os.path.join(here, 'parrotfish', '__version__.py'), 'r') as f:\n for line in f.readlines():\n m = re.match('__(\\w+)__\\s*=\\s*(.+)', line)\n if m:\n ver_dict[m.group(1)] = sanitize_string(m.group(2))\n return ver_dict\n\n\ndef read(fname):\n \"\"\"Read a file\"\"\"\n return open(os.path.join(os.path.dirname(__file__), fname)).read()\n\n\nver = parse_version_file()\n\n\n# setup\nsetup(\n name=ver[\"title\"],\n version=ver[\"version\"],\n packages=[\"parrotfish\", \"parrotfish.utils\"],\n package_data={\n 'parrotfish': ['.environ']\n },\n url='https://github.com/klavinslab/parrotfish',\n license=ver[\"license\"],\n author=ver[\"author\"],\n author_email='',\n keywords='',\n description='',\n long_description=\"\",\n install_requires=install_requires,\n python_requires='>=3.4',\n tests_require=tests_require,\n entry_points={\n 'console_scripts': [\n 'pfish = parrotfish.core:run'\n ],\n }\n)\n","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":1562,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"165777061","text":"from StringIO import StringIO\nfrom textwrap import dedent\n\nimport Bio.SeqIO as SeqIO\nimport pytest\n\nimport labscripts.mkaln as mkaln\n\n\ndef make_fasta_fh(fasta, aln=False):\n func = SeqIO.parse if aln else SeqIO.read\n return func(StringIO(dedent(fasta)), 'fasta')\n\n\n@pytest.fixture\ndef my_seq_record():\n fasta = \"\"\"\n >target\n ABCDEFGHIJ\n \"\"\"\n return mkaln.MySeqRecord(make_fasta_fh(fasta))\n\n\n@pytest.fixture\ndef my_seq_record_with_gaps():\n fasta = \"\"\"\n >target\n AB-C-DEFGHIJ\n \"\"\"\n return mkaln.MySeqRecord(make_fasta_fh(fasta))\n\n\n@pytest.fixture\ndef my_seq_record_with_gaps1():\n fasta = \"\"\"\n >target\n --AB-C-DEFGHIJ\n \"\"\"\n return mkaln.MySeqRecord(make_fasta_fh(fasta))\n\n\n@pytest.fixture\ndef my_seq_record_with_gaps2():\n fasta = \"\"\"\n >target\n AB-C-DEFGHI-J---\n \"\"\"\n return mkaln.MySeqRecord(make_fasta_fh(fasta))\n\n\n@pytest.fixture\ndef my_seq_record_target():\n fasta = \"\"\"\n >template 11\n WXYZ\n \"\"\"\n return mkaln.MySeqRecord(make_fasta_fh(fasta))\n\n\n@pytest.fixture\ndef my_seq_record_target_with_gaps():\n fasta = \"\"\"\n >template 11\n W-X-Y-Z\n \"\"\"\n return mkaln.MySeqRecord(make_fasta_fh(fasta))\n\n\n@pytest.fixture\ndef my_seq_record_target_with_multiple_gaps():\n fasta = \"\"\"\n >template 11\n W--X-Y---Z\n \"\"\"\n return mkaln.MySeqRecord(make_fasta_fh(fasta))\n\n\n@pytest.fixture\ndef my_aln_full_target(my_seq_record):\n return mkaln.MyAln([my_seq_record])\n\n\n@pytest.fixture\ndef my_aln_nogaps():\n fasta = \"\"\"\n >target 2\n BCDE\n\n >template1 11\n WXYZ\n \"\"\"\n return mkaln.MyAln(make_fasta_fh(fasta, aln=True))\n\n\n@pytest.fixture\ndef my_aln_template_gap_at_1():\n fasta = \"\"\"\n >target 2\n BCDE\n\n >template1 11\n W-XY\n \"\"\"\n return mkaln.MyAln(make_fasta_fh(fasta, aln=True))\n\n\n@pytest.fixture\ndef my_aln_template_2_gaps_at_1():\n fasta = \"\"\"\n >target 2\n BCDE\n\n >template1 11\n W--X\n \"\"\"\n return mkaln.MyAln(make_fasta_fh(fasta, aln=True))\n\n\n@pytest.fixture\ndef my_aln_full_range():\n fasta = \"\"\"\n >target 1\n ABCDEFGHIJ\n\n >template1 11\n W---X-Y--Z\n \"\"\"\n return mkaln.MyAln(make_fasta_fh(fasta, aln=True))\n\n\n@pytest.fixture\ndef my_aln_1_gap_at_start():\n fasta = \"\"\"\n >target 2\n BCDEFGHIJ\n\n >template1 11\n W--X-Y--Z\n \"\"\"\n return mkaln.MyAln(make_fasta_fh(fasta, aln=True))\n\n\n@pytest.fixture\ndef my_aln_1_gap_at_end():\n fasta = \"\"\"\n >target 1\n ABCDEFGHI\n\n >template1 11\n W--X-Y--Z\n \"\"\"\n return mkaln.MyAln(make_fasta_fh(fasta, aln=True))\n\n\n@pytest.fixture\ndef my_aln_simple():\n fasta = \"\"\"\n >target 2\n BC-D\n\n >template1 11\n WXYZ\n \"\"\"\n return mkaln.MyAln(make_fasta_fh(fasta, aln=True))\n\n\nclass TestMySeqRecord:\n def test_init(self, my_seq_record):\n assert my_seq_record._seqrange == (1, 10)\n\n def test_seqrange_for_getitem(self, my_seq_record):\n \"\"\"\n For MySeqRecords created from __getitem__() calls, determine the\n seqrange value by using the \"parent's\" _seqrange attribute\n \"\"\"\n for ((start, end), seq, (seqstart, seqend)) in [\n ((2, 6), 'CDEF', (3, 6)),\n ((0, 4), 'ABCD', (1, 4)),\n ((4, None), 'EFGHIJ', (5, 10))]:\n test_record = my_seq_record[slice(start, end)]\n assert str(test_record.seq) == seq\n assert test_record._seqrange == (seqstart, seqend)\n\n def test_get_raw_pos(self, my_seq_record):\n for test in [-1, len(my_seq_record) + + 1]:\n with pytest.raises(ValueError):\n my_seq_record.get_raw_pos(test)\n for test, expected in [(1, 0), (3, 2), (10, 9)]:\n assert my_seq_record.get_raw_pos(test) == expected\n\n def test_get_log_pos(self, my_seq_record):\n for test in [len(my_seq_record), -len(my_seq_record) - 1]:\n with pytest.raises(IndexError):\n my_seq_record.get_log_pos(test)\n for test, expected in [(0, 1), (1, 2), (9, 10),\n (-1, 10,), (-2, 9), (-10, 1)]:\n assert my_seq_record.get_log_pos(test) == expected\n\n def test_make_pir_description(self, my_seq_record):\n spec = 'structureX'\n pirdesc = spec + ':target:1:A:10:A::::'\n assert my_seq_record._make_pir_description(spec=spec) == pirdesc\n\n def test_find_gap_positions(self, my_seq_record):\n with pytest.raises(NotImplementedError):\n # Generator function, so doesn't raise when called\n # Therefore we put it in a list\n list(my_seq_record.find_gap_positions(seqrange=[2, 4]))\n assert list(my_seq_record.find_gap_positions()) == []\n\n def test_compute_seqrange_target(self, my_seq_record, my_seq_record_target):\n assert my_seq_record._seqrange == (1, 10)\n assert my_seq_record_target._seqrange == (11, 14)\n\n\nclass TestMySeqRecordWithGaps:\n def test_init_with_gaps(self, my_seq_record_with_gaps):\n assert my_seq_record_with_gaps._seqrange == (1, 10)\n\n def test_seqrange_for_getitem_with_gaps(self, my_seq_record_with_gaps):\n for ((start, end), seq, (seqstart, seqend)) in [\n ((1, 6), 'B-C-D', (2, 4)),\n ((0, 4), 'AB-C', (1, 3)),\n ((3, None), 'C-DEFGHIJ', (3, 10))]:\n test_record = my_seq_record_with_gaps[slice(start, end)]\n assert str(test_record.seq) == seq\n assert test_record._seqrange == (seqstart, seqend)\n\n def test_get_raw_pos_with_gaps(self, my_seq_record_with_gaps):\n for test in [-1, len(my_seq_record_with_gaps) + 1]:\n with pytest.raises(ValueError):\n my_seq_record_with_gaps.get_raw_pos(test)\n for test, expected in [(1, 0), (3, 3), (4, 5), (10, 11)]:\n assert my_seq_record_with_gaps.get_raw_pos(test) == expected\n\n def test_get_log_pos_with_gaps(self, my_seq_record_with_gaps):\n for test in [len(my_seq_record_with_gaps),\n -len(my_seq_record_with_gaps) - 1]:\n with pytest.raises(IndexError):\n my_seq_record_with_gaps.get_log_pos(test)\n for test, expected in [(1, 2), (2, 2), (3, 3), (4, 3), (11, 10),\n (-1, 10,), (-2, 9),\n (-8, 3), (-9, 3), (-10, 2), (-11, 2), (-12, 1)]:\n assert my_seq_record_with_gaps.get_log_pos(test) == expected\n\n def test_find_gap_positions_with_gaps(self, my_seq_record_with_gaps,\n my_seq_record_with_gaps1,\n my_seq_record_with_gaps2):\n expected = {my_seq_record_with_gaps: [(2, 2), (4, 3)],\n my_seq_record_with_gaps1: [(0, 0), (1, 0), (4, 2), (6, 3)],\n my_seq_record_with_gaps2: [(2, 2), (4, 3), (11, 9),\n (13, 10), (14, 10), (15, 10)]}\n for testrecord, expectedgaps in expected.iteritems():\n assert list(testrecord.find_gap_positions()) == expectedgaps\n\n def test_compute_seqrange_with_gaps(self, my_seq_record_target_with_gaps,\n my_seq_record_target_with_multiple_gaps):\n assert my_seq_record_target_with_gaps._seqrange == (11, 14)\n assert my_seq_record_target_with_multiple_gaps._seqrange == (11, 14)\n\n\nclass TestMyAln:\n def test_getitem_with_single_index(self, my_aln_simple):\n expected_seqs = ['BC-D', 'WXYZ']\n for i, expected_seq in enumerate(expected_seqs):\n assert isinstance(my_aln_simple[i], mkaln.MySeqRecord)\n assert my_aln_simple[i].seq.tostring() == expected_seq\n\n def test_getitem_as_iterator(self, my_aln_simple):\n expected_seqs = ['BC-D', 'WXYZ']\n for test_seqrec, expected_seq in zip(my_aln_simple, expected_seqs):\n assert test_seqrec.seq.tostring() == expected_seq\n\n def test_getitem_with_slice(self, my_aln_simple):\n \"\"\"\n For now, this only tests if the returned alignment is actually\n an instance of MyAln.\n \"\"\"\n expected_seqs = ['BC-D', 'WXYZ']\n test_aln = my_aln_simple[:]\n assert isinstance(test_aln, mkaln.MyAln)\n for test_seqrec, expected_seq in zip(test_aln, expected_seqs):\n assert test_seqrec.seq.tostring() == expected_seq\n\n def test_append_gap_at_1(self, my_aln_full_target, my_aln_template_gap_at_1):\n my_aln_template_gap_at_1.update_seqranges()\n my_aln_full_target.append(my_aln_template_gap_at_1[1], pad=True)\n expected = '-W-XY-----'\n assert my_aln_full_target[1].seq.tostring() == expected\n\n def test_append_2_gaps_at_1(self, my_aln_full_target, my_aln_template_2_gaps_at_1):\n my_aln_template_2_gaps_at_1.update_seqranges()\n my_aln_full_target.append(my_aln_template_2_gaps_at_1[1], pad=True)\n expected = '-W--X-----'\n assert my_aln_full_target[1].seq.tostring() == expected\n\n def test_append_gap_at_1(self, my_aln_full_target, my_aln_template_gap_at_1, my_aln_template_2_gaps_at_1):\n my_aln_template_gap_at_1.update_seqranges()\n my_aln_full_target.append(my_aln_template_gap_at_1[1], pad=True)\n my_aln_template_2_gaps_at_1.update_seqranges()\n my_aln_full_target.append(my_aln_template_2_gaps_at_1[1], pad=True)\n expected_1_gap = '-W-XY-----'\n expected_2_gaps = '-W--X-----'\n assert my_aln_full_target[1].seq.tostring() == expected_1_gap\n assert my_aln_full_target[2].seq.tostring() == expected_2_gaps\n\n def test_append_full_range(self, my_aln_full_target, my_aln_full_range):\n my_aln_full_range.update_seqranges()\n my_aln_full_target.append(my_aln_full_range[1], pad=True)\n expected = 'W---X-Y--Z'\n assert my_aln_full_target[1].seq.tostring() == expected\n\n def test_append_1_gap_at_start(self, my_aln_full_target, my_aln_1_gap_at_start):\n my_aln_1_gap_at_start.update_seqranges()\n my_aln_full_target.append(my_aln_1_gap_at_start[1], pad=True)\n expected = '-W--X-Y--Z'\n assert my_aln_full_target[1].seq.tostring() == expected\n\n def test_append_1_gap_at_end(self, my_aln_full_target, my_aln_1_gap_at_end):\n my_aln_1_gap_at_end.update_seqranges()\n my_aln_full_target.append(my_aln_1_gap_at_end[1], pad=True)\n expected = 'W--X-Y--Z-'\n assert my_aln_full_target[1].seq.tostring() == expected\n\n def test_update_seqranges(self, my_aln_simple):\n assert my_aln_simple.update_seqranges() == (2, 4)\n assert my_aln_simple[1]._seqrange == (2, 4)\n","sub_path":"test/test_mkaln.py","file_name":"test_mkaln.py","file_ext":"py","file_size_in_byte":10588,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"537381288","text":"from __future__ import division\n\nimport numpy as np\nimport pandas as pd\nimport scipy as sp\n\n###############\n\ndef filter_single_col(base_list, count_list, threshold = 4):\n '''Returns a list of nucleotides filtered (threshold, default = 4) by number of occurence of a sequencing run at specific loci in a list of bases'''\n output = []\n for i, base in enumerate(base_list):\n count_1, count_2 = count_list[i].split('|')\n if base == 'N':\n value = 'N'\n else:\n if int(count_1) < threshold and int(count_2) < threshold:\n value = 'N'\n else:\n value = base\n output.append(value)\n return output\n\n##############\n\nhmp = pd.read_table('hmp_play.txt', index_col = 0, header = 0)\nhmc = pd.read_table('hmc_play02.txt', index_col = 0, header = 0)\n\ne = hmp.alleles[:30].copy()\n\nfirst_allele = []\nsecond_allele = []\nfor allele in hmp.ix[:, 'alleles']:\n first_allele.append(allele.split('/')[0])\n second_allele.append(allele.split('/')[1])\n\nhmp = hmp.ix[:, 'FLFL04':'WWA30']\nhmp.insert(0, 'allele_1', first_allele)\nhmp.insert(1, 'allele_2', second_allele)\n\n###\nhmp_trimmed = hmp.ix[:30,2:]\nresults = []\nfor i, col in enumerate(hmp_trimmed.columns):\n base_values = hmp_trimmed[col]\n count_values = hmc[hmc.columns[i]]\n results.append(filter_single_col(base_values, count_values)) # gbs...\n###\n\nresults.insert(0, list(hmp.allele_1))\nresults.insert(1, list(hmp.allele_2))\n\n\ndf = pd.DataFrame(zip(*results), index = hmp.index[:30], columns=hmp.columns, dtype = np.str)\n#####################################\n\niupac = pd.DataFrame([['N', 'G', 'A', 'T', 'C'], ['G', 'G',None,None,None], ['A',None ,'A',None,None], ['T',None ,None,'T',None], ['C',None ,None,None,'C'], ['B', 'G', None, 'T', 'C'], ['D', 'G', 'A', 'T',None], ['H',None ,'A', 'T', 'C'], ['K', 'G',None,'T',None], ['M',None ,'A', None,'C'], ['R', 'G', 'A',None,None], ['S', 'G',None,None,'C'],['V', 'G', 'A',None,'C'], ['W',None ,'A', 'T',None], ['Y',None ,None,'T', 'C']], columns = ('amb_code', 'G', 'A', 'T', 'C'), dtype = np.str)\n\n# target: 5 10 15\n['A', 'T', 'C', 'A', 'A', 'N', 'N', 'N', 'A', 'G', 'A', 'G', 'T', 'C', 'T',\n 'G', 'T', 'G', 'T', 'A', 'C', 'C', 'A', 'T', 'G', 'N', 'N', 'A', 'G', 'N']\n# amb --- c for testing.... (TP26 and TP28: amb_codes are wrong...)\nc = pd.Series(\n['M', 'W', 'H', 'D', 'R', 'N', 'N', 'N', 'W', 'R', 'H', 'V', 'K', 'M', 'Y',\n 'A', 'G', 'G', 'T', 'A', 'C', 'N', 'W', 'Y', 'Y', 'T', 'S', 'W', 'R', 'N'], index = hmp.index[:30])\n\ne.ix[12] = 'G/T'\ne.ix[15] = 'C/G'\ne.ix[16] = 'G/T'\n\nd = pd.Series( # 5 10\n['5|1', '0|7', '1|6', '4|0', '7|0', '0|3', '2|2', '1|3', '4|2', '0|10',\n '4|1', '0|5', '0|7', '0|9', '3|11', '1|4', '0|7', '1|4', '2|6', '7|0',\n '5|0', '0|8', '7|1', '0|4', '1|12', '0|1', '1|3', '10|2', '0|4', '1|3'], index = hmp.index[:30])\n\n#####################################################\nambig = []\nfor i, base in enumerate(c):\n count_1, count_2 = d[i].split('|')\n allele_1, allele_2 = e[i].split('/')\n for j, ambi in enumerate(iupac.ix[5:, 0]): # starting from the 5th row; we don't need 'N's and single nucleotides.\n if base == 'N':\n value = 'N'\n elif base == ambi:\n if count_1 >= 4 and count_2 < 4: # then check with the allele_1 & 2 and, if\n value = allele_1\n break\n elif count_1 < 4 and count_2 >= 4:\n value = allele_2\n break\n elif count_1 >= 4 and count_2 >= 4:\n value = str(allele_1 + '/' + allele_2)\n # elif base == ambi and count_1 >= 4 and count_2 >= 4:\n # value = 'what now?'\n # break\n else:\n continue\n ambig.append(value)\n\n","sub_path":"debug_ambig.py","file_name":"debug_ambig.py","file_ext":"py","file_size_in_byte":3862,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"461375577","text":"#!/usr/bin/python3\n\nfrom tkinter import *\nfrom tkinter.filedialog import *\nimport sys\nimport threading\n\nfilename=None\n\ndef get_file():\n global filename\n filename=askopenfilename()\n if filename:\n return filename\n\ndef display_text(mbox):\n if filename:\n with open(filename) as f:\n mbox.insert(END,f.read())\n\n\nroot=Tk()\nroot.title(\"Text viewer v1\")\nroot.config(width=1000,height=1500)\n\ntop=Menu(root)\nroot.config(menu=top)\n\n\nt=Text(root)\nt.pack(side=LEFT,expand=YES,fill=BOTH)\n\nt.focus()\n\nfmenu=Menu(top,tearoff=False)\n\nfmenu.add_command(label=\"Select file...\",command=get_file)\nfmenu.add_command(label=\"Open\",command=lambda : display_text(t))\nfmenu.add_command(label=\"Quit\",command=sys.exit)\n\ntop.add_cascade(label=\"File\",menu=fmenu)\n\nsbar=Scrollbar(root)\n\nsbar.pack(side=RIGHT,fill=Y)\nsbar.config(command=t.yview)\nt.config(yscrollcommand=sbar.set)\n\nroot.mainloop()\n","sub_path":"gui-apps/simple_text_viewer.py","file_name":"simple_text_viewer.py","file_ext":"py","file_size_in_byte":900,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"383408863","text":"#!/usr/bin/env python3\n# HW05_ex00_TextAdventure.py\n##############################################################################\n# Imports\nfrom sys import exit\n\n# Body\n\ndef backdoor(username5):\n print (\"This is the backdoor filled with awesome programmers and \", username5, \" is one of them.\")\n print (username5,\" clears throat and then all great programmers welcome \", username5)\n print (username5, \"starts programming in Python and never leaves\")\n exit (0)\n\n\ndef infinite_stairway_room(count,username4):\n print(username4, \" walks through the door to see a dimly lit hallway.\")\n print(\"At the end of the hallway is a\", count * 'long ', 'staircase going towards some light. The user now has two options i.e. to take stairs')\n print(\"The second option is to follow the myth of the Nerds and look around to find the backdroor which is the stuff of legends\")\n flag = 0\n next = input(\"> \")\n \n # infinite stairs option\n if next == \"take stairs\":\n if count >0 and flag == 0 :\n print(username4,\" takes the stairs but is not happy about it.\")\n print(username4,\" continues walking on the stairs\")\n flag = 1\n\n while count > 0 and flag == 1:\n print(\"But \",username4, \" is not happy about it. The player keeps walking\")\n count = count -1\n flag = 1\n continue\n if count == 0 and flag == 1:\n print(\"The player reaches a backroom and cannot return back now since \", username4, \" is too tired!!\")\n print(\"The user now only has a option to go through the backdoor or stay here and starve. Please choose your option wisely !!! \")\n next10 = input(\"> \")\n if next == \"take the backdoor\":\n print(username4,\" slowly opens the backdoor revealing the tresures behind it \")\n print(\"\\n\")\n backdoor(username4)\n else:\n dead(\"Starvation and exhaustion kill !!!\")\n\n #infinite_stairway_room(count+1,username4)\n # option 2 == The user in my version of the game searches for a backdoor based on a myth and then starves searching for the backdoor.\n if next == \"look around and search for a backdoor\":\n print(username4,' keeps searching and starts starving')\n dead (\"Starves to death\")\n\n \ndef gold_room(username3):\n print(\"This room is full of gold. How much does \",username3,\" take?\")\n\n next = input(\"> \")\n if \"0\" in next or \"1\" in next:\n how_much = int(next)\n else:\n dead(\"Man, learn to type a number.\")\n\n if how_much < 50:\n print(\"Nice,\",username3,\" is not greedy, you win!\")\n exit(0)\n else:\n dead(username3, \" is a greedy goose!\")\n\n\ndef bear_room(username2):\n print(\"There is a bear here.\")\n print(\"The bear has a bunch of honey.\")\n print(\"The fat bear is in front of another door.\")\n print(\"How is \", username2 , \"going to move the bear?\")\n bear_moved = False\n\n while True:\n next = input(\"> \")\n\n if next == \"take honey\":\n dead(\"The bear looks at\", username2, \" then slaps \", username2 ,\"'s face off.\")\n elif next == \"taunt bear\" and not bear_moved:\n print(\"The bear has moved from the door.\", username2,\" can go through it now.\")\n bear_moved = True\n elif next == \"taunt bear\" and bear_moved:\n dead(\"The bear gets pissed off and chews \",username2,\"'s leg off.\")\n elif next == \"open door\" and bear_moved:\n gold_room(username2)\n else:\n print(\"I got no idea what that means.\")\n\n\ndef cthulhu_room(username1):\n print(username1, \" here sees the great evil Cthulhu.\")\n print(\"He, it, whatever stares at \", username1, \" and \", username1, \" goes insane.\")\n print(\"Does\", username1, \"flee for his life or eat \", username1,\"'s head?\")\n\n next = input(\"> \")\n\n if \"flee\" in next:\n main()\n elif \"head\" in next:\n dead(\"Well that was tasty!\")\n else:\n cthulhu_room(username1)\n\n\ndef dead(why):\n print(\"{}\\n Good job!\".format(why))\n exit(0)\n\n\n############################################################################\ndef main():\n # START the TextAdventure game\n print (\"Please enter your name aka username\")\n print(\"\\n\")\n username = input(\"\")\n #This is the name entered by the user.\n print(username , \"is in a dark room.\") \n print(\"There is a door to \",username,\"'s right and left and center.\")\n print(\"Which one does \", username, \" take?\")\n\n next = input(\"> \")\n\n if next == \"left\":\n bear_room(username)\n elif next == \"right\":\n cthulhu_room(username)\n elif next == \"center\":\n infinite_stairway_room(5,username)\n else:\n dead(username, \" stumbles around the room until \", username, \" starves.\")\n\nif __name__ == '__main__':\n main()\n","sub_path":"HW05_ex00_TextAdventure.py","file_name":"HW05_ex00_TextAdventure.py","file_ext":"py","file_size_in_byte":4862,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"629172649","text":"SPECIES = {\n \"anpa\": {\"SNAME\": \"Antrozous pallidus\", \"CNAME\": \"Pallid Bat\"},\n \"chme\": {\"SNAME\": \"Choeronycteris mexicana\", \"CNAME\": \"Mexican Long-tongued Bat\"},\n \"cora\": {\n \"SNAME\": \"Corynorhinus rafinesquii\",\n \"CNAME\": \"Rafinesque's Big-eared Bat\",\n },\n \"coto\": {\"SNAME\": \"Corynorhinus townsendii\", \"CNAME\": \"Townsend's Big-eared Bat\"},\n \"epfu\": {\"SNAME\": \"Eptesicus fuscus\", \"CNAME\": \"Big Brown Bat\"},\n \"eufl\": {\"SNAME\": \"Eumops floridanus\", \"CNAME\": \"Florida Bonneted Bat\"},\n \"euma\": {\"SNAME\": \"Euderma maculatum\", \"CNAME\": \"Spotted Bat\"},\n \"eupe\": {\"SNAME\": \"Eumops perotis\", \"CNAME\": \"Western Mastiff Bat\"},\n \"euun\": {\"SNAME\": \"Eumops underwoodi\", \"CNAME\": \"Underwood's Bonneted Bat\"},\n \"idph\": {\"SNAME\": \"Idionycteris phyllotis\", \"CNAME\": \"Allen's Big-eared Bat\"},\n \"lano\": {\"SNAME\": \"Lasionycteris noctivagans\", \"CNAME\": \"Silver-haired Bat\"},\n \"labl\": {\"SNAME\": \"Lasiurus blossevillii\", \"CNAME\": \"Western Red Bat\"},\n \"labo\": {\"SNAME\": \"Lasiurus borealis\", \"CNAME\": \"Eastern Red Bat\"},\n \"laci\": {\"SNAME\": \"Lasiurus cinereus\", \"CNAME\": \"Hoary Bat\"},\n \"laeg\": {\"SNAME\": \"Lasiurus ega\", \"CNAME\": \"Southern Yellow Bat\"},\n \"lain\": {\"SNAME\": \"Lasiurus intermedius\", \"CNAME\": \"Northern Yellow Bat\"},\n \"lase\": {\"SNAME\": \"Lasiurus seminolus\", \"CNAME\": \"Seminole Bat\"},\n \"laxa\": {\"SNAME\": \"Lasiurus xanthinus\", \"CNAME\": \"Western Yellow Bat\"},\n \"lecu\": {\"SNAME\": \"Leptonycteris yerbabuenae\", \"CNAME\": \"Lesser Long-nosed Bat\"},\n \"leni\": {\"SNAME\": \"Leptonycteris nivalis\", \"CNAME\": \"Greater Long-nosed Bat\"},\n \"leye\": {\"SNAME\": \"Leptonycteris yerbabuenae\", \"CNAME\": \"Lesser Long-nosed Bat\"},\n \"maca\": {\"SNAME\": \"Macrotus californicus\", \"CNAME\": \"California Leaf-nosed Bat\"},\n \"mome\": {\"SNAME\": \"Mormoops megalophylla\", \"CNAME\": \"Ghost-faced Bat\"},\n \"myar\": {\"SNAME\": \"Myotis auriculus\", \"CNAME\": \"Southwestern Myotis\"},\n \"myau\": {\"SNAME\": \"Myotis austroriparius\", \"CNAME\": \"Southeastern Myotis\"},\n \"myca\": {\"SNAME\": \"Myotis californicus\", \"CNAME\": \"California Myotis\"},\n \"myci\": {\"SNAME\": \"Myotis ciliolabrum\", \"CNAME\": \"Western Small-footed Bat\"},\n \"myev\": {\"SNAME\": \"Myotis evotis\", \"CNAME\": \"Long-Eared Myotis\"},\n \"mygr\": {\"SNAME\": \"Myotis grisescens\", \"CNAME\": \"Gray Bat\"},\n \"myke\": {\"SNAME\": \"Myotis keenii\", \"CNAME\": \"Keen's Myotis\"},\n \"myle\": {\"SNAME\": \"Myotis leibii\", \"CNAME\": \"Eastern Small-footed Myotis\"},\n \"mylu\": {\"SNAME\": \"Myotis lucifugus\", \"CNAME\": \"Little Brown Bat\"},\n \"myoc\": {\"SNAME\": \"Myotis occultus\", \"CNAME\": \"Arizona Myotis\"},\n \"myse\": {\"SNAME\": \"Myotis septentrionalis\", \"CNAME\": \"Northern Long-eared Myotis\"},\n \"myso\": {\"SNAME\": \"Myotis sodalis\", \"CNAME\": \"Indiana Bat\"},\n \"myth\": {\"SNAME\": \"Myotis thysanodes\", \"CNAME\": \"Fringed Bat\"},\n \"myve\": {\"SNAME\": \"Myotis velifer\", \"CNAME\": \"Cave Myotis\"},\n \"myvo\": {\"SNAME\": \"Myotis volans\", \"CNAME\": \"Long-legged Myotis\"},\n \"myyu\": {\"SNAME\": \"Myotis yumanensis\", \"CNAME\": \"Yuma Myotis\"},\n \"nyhu\": {\"SNAME\": \"Nycticeius humeralis\", \"CNAME\": \"Evening Bat\"},\n \"nyfe\": {\"SNAME\": \"Nyctinomops femorosaccus\", \"CNAME\": \"Pocketed Free-tailed Bat\"},\n \"nyma\": {\"SNAME\": \"Nyctinomops macrotis\", \"CNAME\": \"Big Free-tailed Bat\"},\n \"pahe\": {\"SNAME\": \"Parastrellus hesperus\", \"CNAME\": \"Canyon Bat\"},\n \"pesu\": {\"SNAME\": \"Perimyotis subflavus\", \"CNAME\": \"Tricolored Bat\"},\n \"tabr\": {\"SNAME\": \"Tadarida brasiliensis\", \"CNAME\": \"Mexican Free-tailed Bat\"},\n # Hawaiian hoary bat\n \"haba\": {\"SNAME\": \"Lasiurus cinereus semotus\", \"CNAME\": \"Hawaiian Hoary Bat\"},\n}\n\n# Species IDs for shorter reference in data\n# Must have a matching inverted map in JS tier\n# {spp: i for i, spp in enumerate(sorted(SPECIES.keys()))}\n\nSPECIES_ID = {\n \"anpa\": 0,\n \"chme\": 1,\n \"cora\": 2,\n \"coto\": 3,\n \"epfu\": 4,\n \"eufl\": 5,\n \"euma\": 6,\n \"eupe\": 7,\n \"euun\": 8,\n \"haba\": 9,\n \"idph\": 10,\n \"labl\": 11,\n \"labo\": 12,\n \"laci\": 13,\n \"laeg\": 14,\n \"lain\": 15,\n \"lano\": 16,\n \"lase\": 17,\n \"laxa\": 18,\n \"lecu\": 19,\n \"leni\": 20,\n \"leye\": 21,\n \"maca\": 22,\n \"mome\": 23,\n \"myar\": 24,\n \"myau\": 25,\n \"myca\": 26,\n \"myci\": 27,\n \"myev\": 28,\n \"mygr\": 29,\n \"myke\": 30,\n \"myle\": 31,\n \"mylu\": 32,\n \"myoc\": 33,\n \"myse\": 34,\n \"myso\": 35,\n \"myth\": 36,\n \"myve\": 37,\n \"myvo\": 38,\n \"myyu\": 39,\n \"nyfe\": 40,\n \"nyhu\": 41,\n \"nyma\": 42,\n \"pahe\": 43,\n \"pesu\": 44,\n \"tabr\": 45,\n}\n\n# Activity colum\nACTIVITY_COLUMNS = list(SPECIES.keys())\n\n# these are dropped right now\nGROUP_ACTIVITY_COLUMNS = [\n \"bat\",\n \"hif\",\n \"lof\",\n \"q40k\",\n \"q50k\",\n \"q25k\",\n \"lacitabr\",\n \"mycamyyu\",\n \"my50\",\n \"my40\",\n]\n\n\n# metadata fields of detector - take the first value for each site / mic_ht\nDETECTOR_FIELDS = [\n \"det_mfg\",\n \"det_model\",\n \"mic_type\",\n \"refl_type\",\n # \"call_id_1\",\n # \"call_id_2\",\n \"call_id\",\n \"det_name\"\n # \"orig_site_id\",\n # \"orig_det_id\",\n # source_dataset omitted since there may be multiple per detector\n # \"contributor\", # omitted since there may be multiple\n]\n","sub_path":"data/constants.py","file_name":"constants.py","file_ext":"py","file_size_in_byte":5108,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"502260254","text":"\nclass RoundRobin():\n\n def __init__(self, l):\n self.__data = l\n self.__index = 0 #current index for iteration\n\n def __iter__(self):\n return self\n\n def __next__(self):\n self.__index += 1\n while self.__index >= len(self.__data): #if index is more than number of items in data, loop back from the start\n self.__index -= len(self.__data)\n return self.__data[self.__index - 1]\n\n def __getitem__(self, key):\n while key >= len(self.__data): #if key is more than number of items in data, loop back from the start\n key -= len(self.__data)\n return self.__data[key]\n\n def __setitem__(self, key, val):\n while key >= len(self.__data): #if key is more than number of items in data, loop back from the start\n key -= len(self.__data)\n self.__data[key] = val\n\n def __delitem__(self, key):\n while key >= len(self.__data): #if key is more than number of items in data, loop back from the start\n key -= len(self.__data)\n self.__data.pop(key)\n if self.__index > key:\n self.__index -= 1 #moving index back by 1 if removed element was before index, to maintain iteration order\n\n#---------------------------------------\nrr = RoundRobin([\"a\", \"b\", \"c\", \"d\"])\n\nfor (_, v) in zip(range(4), rr):\n print(v)\n\nprint('---')\n\nrr[0] = 'A'\n\nfor (_, v) in zip(range(3), rr):\n print(v)\n\nprint('---')\n\ndel rr[2]\n\nfor (_, v) in zip(range(10), rr):\n print(v)","sub_path":"4_Round Robin.py","file_name":"4_Round Robin.py","file_ext":"py","file_size_in_byte":1491,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"396472968","text":"#-----------------------------------------------------------------\n# gen_stub.py -- genenrate stub code\n#\nfrom __future__ import print_function\nimport sys, os\n\nfrom pycparser import parse_file, c_generator, c_parser, c_ast, preprocess_file\n\n# This is not required if you've installed pycparser into\n# your site-packages/ with setup.py\n#\nsys.path.extend(['.', '..'])\n\ndef gen_skeleton_ast(ast, C_STUB = False, S_STUB = False, A_STUB = False):\n \n# Proprocessing passed in c files if needed\n# with open('c_files/tmp.c', 'w') as f:\n# print(preprocess_file('c_files/template.c'), file=f)\n# print(preprocess_file('c_files/template.c'))\n# sys.exit()\n\n if (C_STUB):\n template_path = 'c_files/cli_stub/'\n elif (S_STUB):\n template_path = 'c_files/ser_stub/'\n elif (A_STUB):\n template_path = 'c_files/asm_stub/'\n else:\n return\n \n libc_path = '-I../utils/fake_libc_include'\n \n if (C_STUB or S_STUB):\n ast_0_arg = parse_file(template_path + 'template_0.c', use_cpp=True, cpp_path='cpp', \n cpp_args=libc_path) \n ast_1_arg = parse_file(template_path + 'template_1.c', use_cpp=True, cpp_path='cpp', \n cpp_args=libc_path)\n ast_2_arg = parse_file(template_path + 'template_2.c', use_cpp=True, cpp_path='cpp', \n cpp_args=libc_path)\n ast_3_arg = parse_file(template_path + 'template_3.c', use_cpp=True, cpp_path='cpp', \n cpp_args=libc_path)\n ast_4_arg = parse_file(template_path + 'template_4.c', use_cpp=True, cpp_path='cpp', \n cpp_args=libc_path)\n elif (A_STUB):\n ast_0_arg = []\n with open (template_path+ \"template.S\", \"r\") as myfile:\n for line in myfile:\n ast_0_arg.append(line) \n ast_1_arg = []\n ast_2_arg = []\n ast_3_arg = []\n ast_4_arg = []\n else:\n return\n \n \n if (C_STUB):\n dummy_func_body_list = ['FN_TYPE', 'FN_NAME', 'ARG1_T', 'ARG1_V', 'ARG2_T', 'ARG2_V'\n , 'ARG3_T', 'ARG3_V', 'ARG4_T', 'ARG4_V'] \n elif (S_STUB):\n dummy_func_body_list = ['FN_TYPE', '__sg_FN_NAME', 'FN_NAME', 'ARG1_T', 'ARG1_V',\n 'ARG2_T', 'ARG2_V', 'ARG3_T', 'ARG3_V', 'ARG4_T', 'ARG4_V']\n elif (A_STUB):\n dummy_func_body_list = ['FUNC_NAME']\n else:\n return\n \n ast_list = [ast_0_arg, ast_1_arg, ast_2_arg, ast_3_arg, ast_4_arg, dummy_func_body_list]\n \n if (C_STUB): \n return ast.cli_stub_ast(ast_list)\n elif (S_STUB): \n return ast.ser_stub_ast(ast_list)\n elif (A_STUB): \n asm_list = ast.asm_ast(ast_list)\n print(\"\")\n target_str = ast_0_arg[-1]\n for item in asm_list:\n ast_0_arg.append(target_str.replace('FUNC_NAME', item[0]))\n return (''.join([ str(myelement) for myelement in ast_0_arg if \"FUNC_NAME\" not in myelement]))\n else: \n return\n \nif __name__ == \"__main__\":\n if len(sys.argv) > 1:\n filename = sys.argv[1]\n else:\n tmpPath = '/home/songjiguo/workspace/composite_test_gen/src/components/interface/sched/'\n interface_h = 'sched.h'\n filename = tmpPath + interface_h\n \n # define all necessary headerfiles to be included in stub code here\n default_cli_headers = \"\"\"\\\n#include \n#include \n#include \n#include \n\n#ifdef LOG_MONITOR\n#include \n#endif\n\"\"\"\n default_ser_headers = \"\"\"\\\n#include \n#include \n#ifdef LOG_MONITOR\n#include \n#endif\n\"\"\"\n # generate predefined AST here\n ast = parse_file(filename, use_cpp=True,\n cpp_path='cpp', \n cpp_args=r'-I../utils/fake_libc_include')\n \n # generate new AST for client stub\n cli_ast_list = gen_skeleton_ast(ast, C_STUB = True, S_STUB = False, A_STUB = False)\n # generate new AST for server stub\n ser_ast_list = gen_skeleton_ast(ast, C_STUB = False, S_STUB = True, A_STUB = False)\n # generate new AST for stub asm\n asm_ast_list = gen_skeleton_ast(ast, C_STUB = False, S_STUB = False, A_STUB = True)\n\n \n # generate cli stub code from here\n print('\\n***********************')\n print(' client stub code ')\n print('***********************')\n print(default_cli_headers)\n print('#include <' + interface_h + '>\\n')\n generator = c_generator.CGenerator()\n generator.cli_stub = True\n for new_ast in cli_ast_list:\n result = generator.visit(new_ast)\n #result = result.replace(\" \", \"\") # remove \"{}, ;\" and white spaces\n result = result.lstrip()\n result = result.replace(\";\", \"\")\n result = result.replace(\"{\", \"\")\n result = result.replace(\"}\", \"\")\n result = os.linesep.join([s for s in result.splitlines() if s]) # remove empty line\n print(result)\n print('')\n \n # generate ser stub code from here\n print('\\n***********************')\n print(' server stub code ')\n print('***********************') \n print(default_ser_headers)\n print('#include <' + interface_h + '>\\n')\n generator = c_generator.CGenerator()\n generator.cli_stub = False\n for new_ast in ser_ast_list:\n result = generator.visit(new_ast) # Only True for client stub\n print(result)\n print('') \n\n # generate ser stub code from here\n print('\\n***********************')\n print(' asm stub code ')\n print('***********************') \n print(asm_ast_list)\n \n \n \n","sub_path":"examples/gen_stub.py","file_name":"gen_stub.py","file_ext":"py","file_size_in_byte":5642,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"596915978","text":"from bs4 import BeautifulSoup\nimport datetime\nimport jieba\nimport numpy as np\nimport time\n\n# 标签字典\ntag_dict = {\n '新闻': '1',\n '阅读': '2',\n '购物': '3',\n '医疗健康': '4',\n '视频播放': '5',\n '社交': '6',\n '游戏': '7',\n '交通旅游': '8',\n '生活服务': '9',\n '教育文化': '10',\n '音乐': '11',\n '网络科技': '12'\n }\n\n# 标签字典\ntag_dict_multiple = {\n '游戏': '1',\n '阅读': '2',\n '购物': '3',\n '医疗健康': '4',\n '音频视频': '5',\n '博客论坛': '6',\n '新闻媒体': '7',\n '交通旅游': '8',\n '生活服务': '9',\n '教育文化': '10',\n '网络科技': '11',\n '体育健身': '12',\n '休闲娱乐': '13',\n '综合门户': '14',\n '公共团体': '15',\n '金融商业': '16',\n }\n\n\n# 返回格式化时间戳,打印日志用\ndef format_time():\n timestamp = time.localtime(time.time())\n fmt_time = str(timestamp.tm_year)\n fmt_time += str(timestamp.tm_mon) if timestamp.tm_mon > 9 else '0' + str(timestamp.tm_mon)\n fmt_time += str(timestamp.tm_mday) if timestamp.tm_mday > 9 else '0' + str(timestamp.tm_mday)\n fmt_time += str(timestamp.tm_hour) if timestamp.tm_hour > 9 else '0' + str(timestamp.tm_hour)\n fmt_time += str(timestamp.tm_min) if timestamp.tm_min > 9 else '0' + str(timestamp.tm_min)\n return fmt_time\n\n\n# 打印日志\ndef log_info(s):\n time = str(datetime.datetime.now())\n print(\"[%s]\" % time + s)\n\n\n# html网页解析得到正文部分\ndef html2text(html_doc):\n try:\n # 解析html网页\n soup = BeautifulSoup(html_doc, \"html.parser\")\n\n # 得到title\n title = soup.title.string if soup.title is not None and soup.title.string is not None else ''\n\n # 得到keywords和description\n description_tags = soup.find(attrs={\"name\": \"description\"})\n keywords_tags = soup.find(attrs={\"name\": \"keywords\"})\n # 有些网页是Keywords,'K'大写\n keywords_tags_upper = soup.find(attrs={\"name\": \"Keywords\"})\n description = ''\n keywords = ''\n if description_tags is not None:\n if 'content' in description_tags.attrs:\n description = description_tags['content']\n else:\n pass\n if keywords_tags is not None:\n if 'content' in keywords_tags.attrs:\n keywords = keywords_tags['content']\n elif keywords_tags_upper is not None:\n if 'content' in keywords_tags_upper.attrs:\n keywords = keywords_tags_upper['content']\n else:\n pass\n\n # 去掉javascript脚本、style样式等\n for script in soup([\"script\", \"style\", \"textarea\"]):\n script.decompose()\n\n # 得到正文\n text = soup.get_text()\n\n # 去掉空行,并拼接成一行\n lines = (line.strip() for line in text.splitlines())\n chunks = (phrase.strip() for line in lines for phrase in line.split(\" \"))\n text = ' '.join(chunk for chunk in chunks if chunk)\n\n # 加上keywords和description\n text = title + ' ' + keywords + ' ' + description + ' ' + text\n except Exception as e:\n log_info(\"soup.title:\" + str(type(soup.title)))\n log_info(\"soup.title.string:\" + str(type(soup.title.string)))\n log_info(\"title:\" + str(type(title)))\n raise e\n return text\n\n\n# 读取停词表\ndef stop_words():\n stop_words_file = open('../data/stop_words_ch.txt', 'r', encoding='GBK')\n stopwords_list = []\n for line in stop_words_file.readlines():\n stopwords_list.append(line[:-1])\n return stopwords_list\n\n\n# 使用结巴分词把文本进行切分\ndef jieba_fenci(raw, stopwords_list):\n raw = raw.lstrip()\n text = \"\"\n word_list = list(jieba.cut(raw, cut_all=False))\n for word in word_list:\n if word not in stopwords_list and word != '\\r\\n\\t':\n text += word\n text += ' '\n return text\n\n\n# 将原始文本分词并每个类别单独存储成文件\ndef data_fenci_apart():\n stop_words_list = stop_words()\n for key, value in tag_dict.items():\n with open(\"../data/label_single/label_\"+value+\"_\"+key+\".txt\", 'w', encoding='UTF-8') as f_label:\n with open(\"../data/single_all_data_label.txt\", 'r', encoding='UTF-8') as f_total:\n for line in f_total:\n label = line.strip().split(\" \")[-1]\n content = \"\"\n for i in line.split(\" \")[:-1]:\n bb = i.strip()\n if bb != \"\":\n content += bb\n if label == value:\n content = jieba_fenci(content, stop_words_list)\n f_label.write(content + \" \" + label + \"\\n\")\n log_info(\"finish label \" + key)\n\n\n# 将原始文本分词并每个类别单独存储成文件,多标签用\ndef data_fenci_apart_multiple():\n stop_words_list = stop_words()\n f_labels = {}\n for key, value in tag_dict_multiple.items():\n f = open(\"../data/label_multiple/label_\" + value + \"_\" + key + \".txt\", 'w', encoding='UTF-8')\n f_labels[key] = f\n with open(\"../data/multiple_all_data_label.txt\", 'r', encoding='UTF-8') as f_total:\n cnt = 0\n for line in f_total:\n labels = line.strip().split(\"__label__\")[-1]\n label_list = labels.split(\",\")\n str_label = \"\"\n for label in label_list:\n str_label += tag_dict_multiple[label] + \",\"\n content = \"\"\n for i in line.split(\"__label__\")[:-1]:\n for j in i.split(\" \"):\n bb = j.strip()\n if bb != \"\":\n content += bb\n content = jieba_fenci(content, stop_words_list)\n for label in label_list:\n f_labels[label].write(content + \" __label__\" + str_label.rstrip(\",\") + \"\\n\")\n cnt += 1\n if cnt % 500 == 0:\n log_info(\"finish \" + str(cnt) + \"samples...\")\n for value in f_labels.values():\n value.close()\n\n\n# 划分训练集和测试集\ndef data_apart_train_test():\n batch = 300\n train_file = \"../data/single_train_data.txt\"\n test_file = \"../data/single_test_data.txt\"\n f_train = open(train_file, 'w', encoding='UTF-8')\n f_test = open(test_file, 'w', encoding='UTF-8')\n for key, value in tag_dict.items():\n input_file = \"../data/label_single/label_\"+value+\"_\"+key+\".txt\"\n print(input_file)\n with open(input_file, 'r', encoding='UTF-8') as f_in:\n count = 0\n for _ in f_in:\n count += 1\n count -= 1\n print(\"count:\" + str(count))\n\n idx = 0\n if batch < (int(count/2) - int(count/2) % 10):\n samples = 300\n ite = int(count/300)\n else:\n samples = int(count/2) - int(count/2) % 10\n ite = 2\n print(\"samples:\" + str(samples))\n print(\"iter:\" + str(ite))\n\n f_in.seek(0)\n for line in f_in:\n if (idx+1) % ite == 1:\n f_train.write(line)\n elif (idx+1) % ite == 0:\n f_test.write(line)\n else:\n pass\n idx += 1\n if idx == (ite*samples):\n break\n f_train.close()\n f_test.close()\n\n\n# 划分训练集和测试集,多标签用\ndef data_apart_train_test_multiple():\n batch = 300\n train_file = \"../data/multiple_train_data.txt\"\n test_file = \"../data/multiple_test_data.txt\"\n f_train = open(train_file, 'w', encoding='UTF-8')\n f_test = open(test_file, 'w', encoding='UTF-8')\n for key, value in tag_dict_multiple.items():\n input_file = \"../data/label_multiple/label_\" + value + \"_\" + key + \".txt\"\n print(input_file)\n with open(input_file, 'r', encoding='UTF-8') as f_in:\n count = 0\n for _ in f_in:\n count += 1\n count -= 1\n print(\"count:\" + str(count))\n\n idx = 0\n if batch < (int(count / 2) - int(count / 2) % 10):\n samples = 300\n ite = int(count / 300)\n else:\n samples = int(count / 2)\n ite = 2\n print(\"samples:\" + str(samples))\n print(\"iter:\" + str(ite))\n\n f_in.seek(0)\n for line in f_in:\n if (idx + 1) % ite == 1:\n f_train.write(line)\n elif (idx + 1) % ite == 0:\n f_test.write(line)\n else:\n pass\n idx += 1\n if idx == (ite * samples):\n break\n f_train.close()\n f_test.close()\n\n\n# 统计数据集标签数量分布(根据类别),多标签用\ndef count_label_distribution_total():\n source_file = \"../data/multiple_all_data_label.txt\"\n count_dict = {}\n label_num = np.zeros(16, dtype=int)\n with open(source_file, 'r', encoding='UTF-8') as sf:\n for line in sf:\n labels = line.split(\"__label__\")[-1]\n label_list = labels.split(',')\n num_label = len(label_list)\n if num_label not in count_dict.keys():\n count_dict[num_label] = 1\n else:\n count_dict[num_label] += 1\n for label in label_list:\n label_num[int(tag_dict_multiple[label.rstrip('\\n')])-1] += 1\n print(count_dict)\n new_dict = {v:k for k, v in tag_dict_multiple.items()}\n print(new_dict)\n for idx, num in enumerate(label_num):\n idx += 1\n print(new_dict[str(idx)] + \" : \" + str(num))\n\n\n# 统计训练集测试集标签数量分布(根据类别),多标签用\ndef count_label_distribution_class():\n source_file = \"../data/multiple_train_data.txt\"\n count_dict = {}\n label_num = np.zeros(16, dtype=int)\n with open(source_file, 'r', encoding='UTF-8') as sf:\n for line in sf:\n labels = line.split(\"__label__\")[-1]\n label_list = labels.split(',')\n num_label = len(label_list)\n if num_label not in count_dict.keys():\n count_dict[num_label] = 1\n else:\n count_dict[num_label] += 1\n for label in label_list:\n label_num[int(label)-1] += 1\n print(count_dict)\n new_dict = {v:k for k, v in tag_dict_multiple.items()}\n print(new_dict)\n for idx, num in enumerate(label_num):\n idx += 1\n print(new_dict[str(idx)] + \" : \" + str(num))\n\n\n# 统计标签数量分布(根据样本标签数目)\ndef count_label_distribution_num():\n source_file = \"../data/multiple_train_data.txt\"\n count_list = [0, 0, 0]\n with open(source_file, 'r', encoding='UTF-8') as sf:\n for line in sf:\n labels = line.split(\"__label__\")[-1]\n label_list = labels.split(',')\n label_length = len(label_list)\n count_list[label_length-1] += 1\n for k, v in enumerate(count_list):\n print(str(k) + \" : \" + str(v))\n\n\n# 统计数据集标签数量分布(根据类别),单标签用\ndef single_count_label_distribution_total():\n source_file = \"../data/single_test_data.txt\"\n label_num = np.zeros(12, dtype=int)\n with open(source_file, 'r', encoding='UTF-8') as sf:\n for line in sf:\n label = line.split(\" \")[-1]\n label_num[int(label)-1] += 1\n\n new_dict = {v: k for k, v in tag_dict.items()}\n print(new_dict)\n for idx, num in enumerate(label_num):\n idx += 1\n print(new_dict[str(idx)] + \" : \" + str(num))","sub_path":"driver/DataProcessor.py","file_name":"DataProcessor.py","file_ext":"py","file_size_in_byte":11693,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"600345368","text":"\n\nimport numpy as np\nimport sklearn as sk\nimport scipy.signal\nimport pywt\nimport matplotlib.pyplot as plt\nfrom statsmodels.robust import mad\nfrom sklearn import svm\nfrom io import open\n\n\nclass data_pool:\n def __init__(self):\n self.__working_dir = \"/home/bonenberger/dataRecordings/\"\n\n self.__num_ir_sensors = 6\n self.__num_fr_sensors = 2\n self.__num_odo_sensors = 2\n self.__num_imu_sensors = 13\n self.__ana_norm_fact = 1023\n self.__num_ana_sensors = self.__num_ir_sensors + self.__num_fr_sensors\n self.__total_num_sensor_vars = self.__num_ir_sensors + self.__num_fr_sensors + self.__num_odo_sensors + \\\n self.__num_imu_sensors\n self.__total_num_columns = self.__total_num_sensor_vars + 1\n print(self.__total_num_columns)\n self.__selected_variables = np.linspace(1, self.__total_num_sensor_vars)\n self.__num_of_used_vars = len(self.__selected_variables)\n\n def read_file(self, file_name):\n\n \"\"\"\n Add a source file to the dataset. Given inputs are stored in arrays.\n :param file_name: String specifying the file name.\n :param start_index: Time (in samples) from which the data in the file is read.\n :param stop_index:Time (in samples) until which the data in the file is read.\n :param label: Label of the file.\n :param class_name: Class name displayed by some functions (self.__liveClassification).\n :return: writes to:\n - self.__file_source_name\n - self.__file_source_start_index\n - self.__file_source_stop_index\n - self.__file_labels\n - self.__number_of_classes\n - self.__class_name\n - self.__number_windows_per_class (initialization only)\n \"\"\"\n data = []\n file_id = self.__working_dir + file_name\n file = open(file_id, mode=\"rt\", encoding=\"utf-8\", newline=\"\\n\")\n content = file.read()\n file.close()\n content = content.split(\"\\n\")\n for i in range(len(content)):\n line = content[i]\n if not line.startswith(\"%\"):\n line = line.split(\",\")\n for j in range(self.__total_num_columns):\n try:\n # line[j] = line[j]\n try:\n line[j] = float(line[j])\n except ValueError:\n line[j] = 0\n except IndexError:\n line = []\n if len(line) >= 1:\n data.append(line)\n else:\n if \"Anomaly\" in line:\n # print(line)\n pass\n data = np.array(data, dtype=float)\n data[::, 0] = (data[::, 0] - data[0, 0]) * 10 ** (-9)\n return data","sub_path":"gather_data.py","file_name":"gather_data.py","file_ext":"py","file_size_in_byte":2844,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"80070047","text":"import os\nimport logging\n\nfrom .best_state_saver import BestStateSaverCallback, TrainControllerStopException\nfrom . import train_op_cp\nfrom utct.common.trainer_template import TrainerTemplate\n\nimport tensorflow as tf\nimport tflearn\n\n\nclass Trainer(TrainerTemplate):\n \"\"\"\n Class, which provides training process under TFLearn framework.\n \"\"\"\n\n def _hyper_train_target_sub(self, **kwargs):\n \"\"\"\n Actual training procedure for specific set of hyper parameters.\n \"\"\"\n\n if self.saver.log_filename:\n fh = logging.FileHandler(self.saver.log_filename)\n self.logger.addHandler(fh)\n\n config = tflearn.init_graph()\n config.gpu_options.allow_growth = True\n\n data = self.data_source(**kwargs)\n\n net = self.model(\n self.optimizer(**kwargs),\n self.data_source,\n **kwargs)\n model = tflearn.DNN(network=net,\n tensorboard_verbose=(kwargs['tensorboard_verbose'] if 'tensorboard_verbose' in kwargs else 0),\n tensorboard_dir=str(self.saver.log_dirname),\n checkpoint_path=os.path.join(self.saver.last_checkpoints_dirname, self.saver.model_filename_prefix),\n max_checkpoints=2)\n\n if self.data_source.rewrite_data_aug:\n train_op_cp.replace_train_op_initialize_fit_cp(model)\n\n bss_callback = BestStateSaverCallback(\n session=model.session,\n best_snapshot_path=os.path.join(self.saver.best_checkpoints_dirname, self.saver.model_filename_prefix),\n best_val_accuracy=(kwargs['bss_best_val_accuracy'] if 'bss_best_val_accuracy' in kwargs else 0.0),\n bigger=(kwargs['bss_bigger'] if 'bss_bigger' in kwargs else True),\n epoch_tail=self.epoch_tail)\n\n try:\n model.fit(n_epoch=self.num_epoch,\n show_metric=True,\n batch_size=self.data_source.batch_size,\n shuffle=True,\n snapshot_epoch=True,\n run_id=self.saver.project_name,\n callbacks=bss_callback,\n **data)\n except TrainControllerStopException as e:\n model.trainer.summ_writer.close()\n self.logger.info(e)\n\n self.logger.info(\"Best validation accuracy: {:.4f} (at epoch {})\".format(\n bss_callback.best_val_accuracy, bss_callback.best_epoch))\n\n if self.saver.log_filename:\n self.logger.removeHandler(fh)\n fh.close()\n\n tf.reset_default_graph()\n model.session.close()\n\n return bss_callback.best_val_accuracy\n","sub_path":"TFLearn/trainer.py","file_name":"trainer.py","file_ext":"py","file_size_in_byte":2700,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"358050249","text":"from django.core.management.base import BaseCommand, CommandError\nfrom webauto.models import *\nfrom selenium import webdriver\nfrom selenium.webdriver.common.keys import Keys\nfrom selenium.webdriver.support.ui import Select\n\nimport time\n\n\nclass Command(BaseCommand):\n help = 'Automation 80%. This is a selenium automation for Dominion Energy Gas bill payment.'\n BROWSER_DRIVER_PATH = 'D:\\djangoprojects\\deefinance\\chromedriver'\n T_MOBILE_LOGIN_PAGE = 'https://account.t-mobile.com/signin/v2/?redirect_uri=https:%2F%2Fwww.t-mobile.com%2F' \\\n 'signin&scope=TMO_ID_profile%2520associated_lines%2520billing_information%2520' \\\n 'associated_billing_accounts%2520extended_lines%2520token%2520openid%2520vault&' \\\n 'client_id=MYTMO&access_type=ONLINE&response_type=code&approval_prompt=auto&' \\\n 'prompt=select_account&state=eyJpbnRlbnQiOiJMb2dpbiIsImJvb2ttYXJrVXJsIjoiaHR0cHM6Ly' \\\n '9teS50LW1vYmlsZS5jb20ifQ'\n\n def handle(self, *args, **options):\n # Load the browser driver.\n browser = webdriver.Chrome(self.BROWSER_DRIVER_PATH)\n # Go to Dominion Energy login page.\n browser.get(self.T_MOBILE_LOGIN_PAGE)\n time.sleep(3)\n credential = Credential.objects.get(payment_of_credential='t mobile')\n username_field = browser.find_element_by_id('usernameTextBox')\n username_field.send_keys(credential.username)\n username_field.send_keys(Keys.ENTER)\n time.sleep(3)\n next_btn = browser.find_element_by_id('lp1-next-btn')\n next_btn.click()\n\n\n\n\n self.stdout.write(self.style.SUCCESS('Complete!!!!'))\n","sub_path":"webauto/management/commands/t_mobile.py","file_name":"t_mobile.py","file_ext":"py","file_size_in_byte":1744,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"81699494","text":"# Python bytecode 2.7 (decompiled from Python 2.7)\n# Embedded file name: e:\\jenkins\\workspace\\client_SERENITY\\branches\\release\\SERENITY\\eve\\client\\script\\environment\\spaceObject\\backgroundObject.py\nfrom eve.client.script.environment.spaceObject.spaceObject import SpaceObject\nimport trinity\n\nclass BackgroundObject(SpaceObject):\n\n def LoadModel(self):\n graphicURL = self.typeData.get('graphicFile')\n obj = trinity.Load(graphicURL)\n self.backgroundObject = obj\n scene = self.spaceMgr.GetScene()\n scene.backgroundObjects.append(obj)\n\n def Release(self):\n if self.released:\n return\n else:\n scene = self.spaceMgr.GetScene()\n if scene:\n scene.backgroundObjects.fremove(self.backgroundObject)\n self.backgroundObject = None\n SpaceObject.Release(self, 'BackgroundObject')\n return","sub_path":"client/eve/client/script/environment/spaceObject/backgroundObject.py","file_name":"backgroundObject.py","file_ext":"py","file_size_in_byte":907,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"231684473","text":"# -*- coding: UTF-8 -*-\nimport os\nimport time\nfrom openpyxl import load_workbook\nfrom . import db\nfrom .models import Clase, Student\nimport sqlalchemy\n\n\ndef doc2db():\n \"\"\"加载一个xlsx文档到数据库\n *它的列遵循以下规则********************************\n\n 年级编号 41 \n 班级编号 41090 \n 班级名称 自动化1682 \n 学号 2013445645 \n 姓名 佛挡杀佛 \n 民族代码 1 \n 性别 2 \n 出生日期 34692 \n 学生来源 420500 \n 身份证号 420522222224 \n 家庭住址 湖北省宜广泛大使馆三个地方 \n <之后的列无信息, 忽略掉>\n **********************************************\n 学号和班级编号被认为是必备信息, 不存在的行会被认为是不规范的行,不会录入\n \"\" 或者 None 被转存为 None\n 性别被转存为布尔值\n 其他列统一存为string\n \"\"\"\n\n start = time.time()\n files = os.listdir(os.path.abspath('./app/resource/upload'))\n file_error = None\n wb = None\n for file in files:\n if file.endswith('.xlsx'):\n file_error = open(os.path.join(os.path.abspath('./app/resource/upload'), '.error'), 'w')\n wb = load_workbook(filename=os.path.join(os.path.abspath('./app/resource/upload'), file))\n\n break\n else:\n return False\n\n sheet0, *_ = wb.get_sheet_names()\n ws = wb.get_sheet_by_name(sheet0)\n rows = ws.rows[1:]\n\n for row in rows:\n age_id, clase_id, cname, \\\n student_id, sname, national_code, sex, birth_date, sources, identity, address, *_ = [str(col.value) if col.value else None for col in row]\n\n if cname.startswith('=SUBTOTAL'):\n continue\n if not (clase_id and cname and sname and student_id): # 班级号, 班级名, 学生名, 学生号一样为空的为无效数据\n file_error.write('Clase' + str([col.value for col in row]) + '\\n')\n continue\n if sex:\n sex = (True if sex == '1' else False)\n\n cla = Clase(age_id=age_id, clase_id=clase_id, name=cname)\n try:\n db.session.add(cla)\n db.session.commit()\n except sqlalchemy.exc.IntegrityError as e:\n if e.args[0].startswith('(IntegrityError) UNIQUE constraint failed:'):\n db.session.rollback()\n cla = Clase.query.filter_by(name=cname).first()\n else:\n # raise e\n file_error.write(str(e.args))\n\n stu = Student(\n student_id=student_id, name=sname,\n national_code=national_code, sex=sex,\n birth_date=birth_date, sources=sources,\n identity=identity, address=address)\n stu.clase = cla\n\n try:\n db.session.add(stu)\n db.session.commit()\n except sqlalchemy.exc.IntegrityError as e:\n db.session.rollback()\n if e.args[0].startswith('(IntegrityError) UNIQUE constraint failed: students.student_id'):\n stu.student_id += '?'\n stu.iserror = True\n db.session.add(stu)\n db.session.commit()\n else:\n file_error.write('student' + str([col.value for col in row]) + \"\\n\")\n file_error.write(str(e.args))\n # raise e\n\n file_error.close()\n end = time.time()\n print(len(rows))\n print('(>.<) %r s' % (end - start))\n\n\n\n","sub_path":"app/docs.py","file_name":"docs.py","file_ext":"py","file_size_in_byte":3620,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"74971489","text":"from flask import Flask, jsonify, render_template, request, redirect\nfrom flask_sqlalchemy import SQLAlchemy\nfrom sqlalchemy.ext.automap import automap_base\nfrom sqlalchemy import create_engine, func\nfrom sqlalchemy.orm import Session\n#import pandas as pd\n\napp = Flask(__name__)\n\nengine = create_engine(\"sqlite:///data/bellybutton.sqlite\")\n\n#db = SQLAlchemy(app)\n\nBase = automap_base()\nBase.prepare(engine, reflect=True)\nsamples = Base.classes.samples\nmeta = Base.classes.sample_metadata\ntest_id = str(940)\nsample_list = [str(q.sample) for q in Session(engine).query(meta).all()]\n#dat = Session(engine).query(samples.otu_id, samples.otu_label, samples.__dict__[test_id]).order_by(samples.__dict__[test_id].desc()).all()\n\n\n@app.route(\"/\")\ndef home():\n return render_template(\"index.html\", sample_list=sample_list)\n\n@app.route(\"/samples/\")\ndef sample(sample_id):\n s = Session(engine)\n results = s.query(samples.otu_id, samples.otu_label, samples.__dict__[sample_id]).order_by(samples.__dict__[sample_id].desc())\n results = [{'id':x[0], 'label':x[1], 'quantity':x[2]} for x in results]\n meta_data = {k:v for (k,v) in s.query(meta).filter(meta.sample == sample_id).one().__dict__.items() if k[0]!=\"_\"}\n return jsonify({'data':results, 'metadata':meta_data})\n\n@app.route(\"/metadata/\")\ndef sample_meta(sample_id):\n s = Session(engine)\n meta_data = {k:v for (k,v) in s.query(meta).filter(meta.sample == 967).one().__dict__.items() if k[0]!=\"_\"}\n return jsonify(meta_data)\n\nif __name__ == \"__main__\":\n app.run(debug=True)\n","sub_path":".ipynb_checkpoints/app-checkpoint.py","file_name":"app-checkpoint.py","file_ext":"py","file_size_in_byte":1580,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"344488307","text":"\"\"\"\nThis module is a controller for Topic class\n\"\"\"\nfrom app.login import login_required\nfrom flask import Blueprint, request, session, flash, redirect, url_for, render_template\nfrom app.mod_topics.models import Topic\n\n# Blueprint to extend __init__.py in app folder.\ntopics = Blueprint('topics', __name__, url_prefix='/topics')\n\n\n# Route to handle (GET) topics_list\n@topics.route(\"/\")\n@login_required\ndef topics_list():\n \"\"\"\n :return:\n render template topics.html for topics with user_id same as session id\n \"\"\"\n topic_list = Topic.get_topics_by_user_id(session[\"user_id\"])\n return render_template(\"topics.html\", topics=topic_list)\n\n\n# Route to handle adding new Topic, displays form (GET) and creates new Topic object (POST)\n@topics.route(\"/new\", methods=[\"GET\", \"POST\"])\n@login_required\ndef new():\n \"\"\"\n :return:\n if GET: render template add_edit_topic\n elif POST error: render template add_edit_topic with error\n else: redirects to topics_list route\n \"\"\"\n error = None\n # Check if forms are not empty\n if request.method == \"POST\" and request.form[\"title\"] and request.form[\"description\"]:\n topic = Topic.get_topic_by_user_id_and_title(session[\"user_id\"], request.form[\"title\"])\n # Check if topic with that title is already in database\n if topic:\n error = \"Topic with this name is already in database.\"\n return render_template(\"add_edit_topic.html\", error=error)\n # Adding item to database\n Topic.add_new_topic(Topic(session[\"user_id\"], request.form[\"title\"], request.form[\"description\"]))\n flash(\"You added %s to your topics!\" % request.form[\"title\"])\n return redirect(url_for('topics.topics_list'))\n # How to behave when method is POST and forms are empty\n elif request.method == \"POST\":\n error = \"Title and description cannot be empty.\"\n return render_template(\"add_edit_topic.html\", error=error)\n # Handle GET method\n return render_template(\"add_edit_topic.html\", error=error, title=\"Add new topic\")\n\n\n# Route to handle adding new Topic displays form (GET) and creates new Topic object (POST)\n@topics.route(\"//edit\", methods=[\"GET\", \"POST\"])\n@login_required\ndef edit(id):\n \"\"\"\n :param id:\n int: id of topic\n :return:\n if GET: render template add_edit_topic\n elif POST error: render template add_edit_topic with error\n else: redirects to topics_list route\n \"\"\"\n error = None\n if request.method == \"POST\" and request.form[\"title\"] and request.form[\"description\"]:\n topic = Topic.get_topic_by_user_id_and_title(session[\"user_id\"], request.form[\"title\"])\n # Check if topic with that title is already in database\n if topic:\n error = \"Topic with this name is already in database.\"\n return render_template(\"add_edit_topic.html\", error=error)\n # Editing topic in database\n Topic.edit_topic(id, request.form[\"title\"], request.form[\"description\"])\n flash(\"You edited topic!\")\n return redirect(url_for('topics.topics_list'))\n # How to behave when method is POST and forms are empty\n elif request.method == \"POST\":\n error = \"Title and description cannot be empty.\"\n return render_template(\"add_edit_topic.html\", error=error, topic=Topic.get_topic_by_id(id))\n # Handle GET method\n return render_template(\"add_edit_topic.html\", error=error, topic=Topic.get_topic_by_id(id), title=\"Edit: \")\n\n\n# Route to handle deleting topic\n@topics.route(\"//delete\")\n@login_required\ndef delete(id):\n \"\"\"\n :param id:\n int: id of topic\n :return:\n redirect to topics_list route\n \"\"\"\n topic = Topic.get_topic_by_id(id)\n title = topic.get_title()\n Topic.delete_topic(topic)\n flash(\"You removed %s from your topics!\" % title)\n return redirect(url_for('topics.topics_list'))\n","sub_path":"app/mod_topics/controllers.py","file_name":"controllers.py","file_ext":"py","file_size_in_byte":3903,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"40686144","text":"import datetime\nimport pytz\nfrom rest_framework import generics, status, serializers, viewsets\nfrom rest_framework.response import Response\nfrom rest_framework.views import APIView\nfrom django.contrib.auth import get_user_model\nfrom django.core import serializers\nfrom django.utils import timezone\nfrom .models import Services, Categories, Options, CustomUser, Records, Arrivals\nfrom .serializers import (UserSerializer,\n ServicesSerializer,\n CategoriesSerializer,\n OptionsSerializer,\n RecordsSerializer,\n ArrivalsSerializer,\n )\n\nCustomUser = get_user_model()\n\nclass ListUsers(generics.ListCreateAPIView):\n queryset = CustomUser.objects.filter(deleted=0)\n serializer_class = UserSerializer\n\n def create(self, request, *args, **kwargs):\n last_user = CustomUser.objects.last()\n ID = str(int(last_user.IDUser) + 1).zfill(5)\n print(ID)\n request.data[\"IDUser\"] = ID\n serializer = self.get_serializer(data=request.data)\n serializer.is_valid(raise_exception=True)\n self.perform_create(serializer)\n headers = self.get_success_headers(serializer.data)\n return Response(serializer.data, status=status.HTTP_201_CREATED, headers=headers)\n\nclass ListDeletedUsers(generics.ListAPIView):\n queryset = CustomUser.objects.filter(deleted=1)\n serializer_class = UserSerializer\n\nclass UserDetail(generics.RetrieveUpdateDestroyAPIView):\n queryset = CustomUser.objects.all()\n serializer_class = UserSerializer\n\nclass ListServices(generics.ListCreateAPIView):\n queryset = Services.objects.filter(deleted=0)\n serializer_class = ServicesSerializer\n\n def create(self, request):\n serializer = ServicesSerializer(data=request.data)\n if serializer.is_valid():\n service = Services(service=request.data['service'])\n service.save()\n category = Categories(category=request.data['category'], serviceID=service)\n category.save()\n options = Options(arrivals=request.data['arrivals'],\n price=request.data['price'],\n duration=request.data['duration'],\n categoryID=category)\n options.save()\n return Response(serializer.data)\n else:\n return Response(serializer.errors,\n status=status.HTTP_400_BAD_REQUEST)\n\nclass ListDeletedServices(generics.ListAPIView):\n queryset = Services.objects.filter(deleted=1)\n serializer_class = ServicesSerializer\n\nclass ServicesDetail(generics.RetrieveUpdateDestroyAPIView):\n queryset = Services.objects.all()\n serializer_class = ServicesSerializer\n\nclass ListCategories(generics.ListCreateAPIView):\n queryset = Categories.objects.filter(deleted=0)\n serializer_class = CategoriesSerializer\n\n def create(self, request):\n serializer = CategoriesSerializer(data=request.data)\n print(serializer)\n if serializer.is_valid():\n service = Services.objects.get(pk=request.data['serviceID'])\n category = Categories(category=request.data['category'], serviceID=service)\n category.save()\n options = Options(arrivals=request.data['arrivals'],\n price=request.data['price'],\n duration=request.data['duration'],\n categoryID=category)\n options.save()\n return Response(serializer.data)\n else:\n print(serializer.errors)\n return Response(serializer.errors,\n status=status.HTTP_400_BAD_REQUEST)\n\nclass ListDeletedCategories(generics.ListAPIView):\n queryset = Categories.objects.filter(deleted=1)\n serializer_class = CategoriesSerializer\n\nclass CategoriesDetail(generics.RetrieveUpdateDestroyAPIView):\n queryset = Categories.objects.all()\n serializer_class = CategoriesSerializer\n\nclass ListOptions(generics.ListCreateAPIView):\n queryset = Options.objects.filter(deleted=0)\n serializer_class = OptionsSerializer\n\n def create(self, request):\n serializer = OptionsSerializer(data=request.data)\n if serializer.is_valid():\n category = Categories.objects.get(pk=request.data['categoryID'])\n options = Options(arrivals=request.data['arrivals'],\n price=request.data['price'],\n duration=request.data['duration'],\n categoryID=category)\n options.save()\n return Response(serializer.data)\n else:\n return Response(serializer.errors,\n status=status.HTTP_400_BAD_REQUEST)\n\nclass ListDeletedOptions(generics.ListAPIView):\n queryset = Options.objects.filter(deleted=1)\n serializer_class = OptionsSerializer\n\nclass OptionsDetail(generics.RetrieveUpdateDestroyAPIView):\n queryset = Options.objects.all()\n serializer_class = OptionsSerializer\n\nclass ListRecords(generics.ListCreateAPIView):\n queryset = Records.objects.all().order_by('-ends')\n serializer_class = RecordsSerializer\n\n def create(self, request):\n now = timezone.now()\n user = CustomUser.objects.get(pk=request.data['user'])\n service = Services.objects.get(pk=request.data['service'])\n category = Categories.objects.get(pk=request.data['category'])\n option = Options.objects.get(pk=request.data['option'])\n discount = request.data['discount']\n ends = now + datetime.timedelta(days=option.duration)\n days_left = ends - now\n record = Records(\n userObj=user,\n serviceObj=service,\n categoryObj=category,\n optionObj=option,\n arrivals_left=option.arrivals,\n price=option.price,\n discount=request.data['discount'],\n nett_price=request.data['nettPrice'],\n paid=request.data['paid'],\n started=now,\n ends=ends,\n days_left=days_left.days)\n record.save()\n return Response()\n\nclass ListUserRecords(generics.ListAPIView):\n serializer_class = RecordsSerializer\n\n def get_queryset(self):\n user=self.kwargs['pk']\n return Records.objects.filter(userObj=user, deleted=0, active=1).order_by('-ends')\n\nclass RecordsDetail(generics.RetrieveUpdateDestroyAPIView):\n queryset = Records.objects.all()\n serializer_class = RecordsSerializer\n\nclass ListArrivals(generics.ListCreateAPIView):\n queryset = Arrivals.objects.all()\n serializer_class = ArrivalsSerializer\n\n def create(self, request):\n now = timezone.now()\n time = now.timetz()\n user = CustomUser.objects.get(pk=request.data['user'])\n record = Records.objects.get(pk=request.data['record'])\n dt = datetime.datetime.strptime(request.data['date'], '%Y-%m-%d')\n arrival = datetime.datetime.combine(dt, time)\n record.arrivals_left -= 1\n record.save()\n record.is_active()\n arrival = Arrivals(\n userObj=user,\n recordObj=record,\n arrival=arrival,\n arrival_time=str(time.hour + 2) + \":\" + str(time.minute)\n )\n arrival.save()\n return Response()\n\nclass ListArrivalsByDate(generics.ListAPIView):\n serializer_class = ArrivalsSerializer\n\n def get_queryset(self):\n selected_date=self.kwargs['date']\n return Arrivals.objects.filter(arrival__date=selected_date).order_by('-arrival_time')\n\nclass ArrivalsDetail(generics.RetrieveUpdateDestroyAPIView):\n queryset = Arrivals.objects.all()\n serializer_class = ArrivalsSerializer\n\n def destroy(self, request, *args, **kwargs):\n instance = self.get_object()\n record = Records.objects.get(pk=instance.recordObj.id)\n record.arrivals_left+=1\n record.save()\n record.is_active()\n self.perform_destroy(instance)\n return Response(status=status.HTTP_204_NO_CONTENT)\n","sub_path":"backend/backend/api/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":8123,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"452471283","text":"# Copyright (c) 2008-2016 MetPy Developers.\n# Distributed under the terms of the BSD 3-Clause License.\n# SPDX-License-Identifier: BSD-3-Clause\n\"\"\"\nSimple Sounding\n===============\n\nUse MetPy as straightforward as possible to make a Skew-T LogP plot.\n\"\"\"\nfrom datetime import datetime\n\nimport matplotlib.pyplot as plt\nimport numpy as np\n\nfrom metpy.calc import resample_nn_1d\nfrom metpy.io import get_upper_air_data\nfrom metpy.io.upperair import UseSampleData\nfrom metpy.plots import SkewT\nfrom metpy.units import units\n\n###########################################\n\n# Change default to be better for skew-T\nplt.rcParams['figure.figsize'] = (9, 9)\n\nwith UseSampleData(): # Only needed to use our local sample data\n # Download and parse the data\n dataset = get_upper_air_data(datetime(2013, 1, 20, 12), 'OUN')\n\np = dataset.variables['pressure'][:]\nT = dataset.variables['temperature'][:]\nTd = dataset.variables['dewpoint'][:]\nu = dataset.variables['u_wind'][:]\nv = dataset.variables['v_wind'][:]\n\n###########################################\nskew = SkewT()\n\n# Plot the data using normal plotting functions, in this case using\n# log scaling in Y, as dictated by the typical meteorological plot\nskew.plot(p, T, 'r')\nskew.plot(p, Td, 'g')\nskew.plot_barbs(p, u, v)\n\n# Add the relevant special lines\nskew.plot_dry_adiabats()\nskew.plot_moist_adiabats()\nskew.plot_mixing_lines()\nskew.ax.set_ylim(1000, 100)\n\n###########################################\n\n# Example of defining your own vertical barb spacing\nskew = SkewT()\n\n# Plot the data using normal plotting functions, in this case using\n# log scaling in Y, as dictated by the typical meteorological plot\nskew.plot(p, T, 'r')\nskew.plot(p, Td, 'g')\n\n# Set spacing interval--Every 50 mb from 1000 to 100 mb\nmy_interval = np.arange(100, 1000, 50) * units('mbar')\n\n# Get indexes of values closest to defined interval\nix = resample_nn_1d(p, my_interval)\n\n# Plot only values nearest to defined interval values\nskew.plot_barbs(p[ix], u[ix], v[ix])\n\n# Add the relevant special lines\nskew.plot_dry_adiabats()\nskew.plot_moist_adiabats()\nskew.plot_mixing_lines()\nskew.ax.set_ylim(1000, 100)\n\n# Show the plot\nplt.show()\n","sub_path":"examples/plots/Simple_Sounding.py","file_name":"Simple_Sounding.py","file_ext":"py","file_size_in_byte":2155,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"379601204","text":"from django.shortcuts import render,redirect\nfrom .forms import StudentForms\nfrom .models import Student\n# Create your views here.\n\ndef StudentHome(request):\n return render(request,'student/home.html')\n\ndef StudentForm(request,id=0):\n if request.method==\"GET\":\n if id==0:\n form=StudentForms()\n else:\n student=Student.objects.get(pk=id)\n form=StudentForms(instance=student)\n return render(request,'student/student_form.html',{'form':form})\n else:\n if id==0:\n form=StudentForms(request.POST)\n else:\n student=Student.objects.get(pk=id)\n form=StudentForms(request.POST,instance=student)\n if form.is_valid():\n form.save()\n return redirect('student_list')\n \n\ndef StudentList(request):\n context={'student_lis':Student.objects.all()}\n return render(request,'student/student_list.html',context)\n\ndef StudentDelete(request,id):\n student=Student.objects.get(pk=id)\n student.delete()\n return redirect(\"student_list\")\n","sub_path":"student/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1061,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"579107037","text":"\"\"\".\"\"\"\nimport numpy as np\nimport pickle\nimport time\n\nLEARNING_RATE = 0.1\nDISCOUNT = 0.95\n\nMOVE_PENALTY = 1 # feel free to tinker with these!\nENEMY_PENALTY = 300 # feel free to tinker with these!\nDOOR_REWARD = 25 # feel free to tinker with these!\n\n\nclass QTable:\n \"\"\".\"\"\"\n\n def __init__(self, SIZE, start_q_table=None):\n \"\"\".\"\"\"\n self.table = self.create_q_table(SIZE, start_q_table)\n pass\n\n def create_q_table(self, SIZE, start_q_table):\n \"\"\"Se eu não tiver uma tabela inicial, crie uma com valores aleatórios.\"\"\"\n if start_q_table is None:\n q_table = {}\n for i in range(-SIZE + 1, SIZE):\n for ii in range(-SIZE + 1, SIZE):\n for iii in range(-SIZE + 1, SIZE):\n for iiii in range(-SIZE + 1, SIZE):\n q_table[((i, ii), (iii, iiii))] = [np.random.uniform(-5, 0) for i in range(4)]\n else:\n with open(start_q_table, \"rb\") as f:\n q_table = pickle.load(f)\n return q_table\n\n def get_action(self, observation):\n \"\"\"Retorna a ação com o maior q_value.\"\"\"\n return np.argmax(self.table[observation])\n\n def get_q_value(self, observation, action):\n \"\"\"Retorna o q_value para um certo estado e uma ação.\"\"\"\n return self.table[observation][action]\n\n def get_new_q(self, reward, new_observation, observation, action):\n \"\"\"Cria um novo q_value, dado as variáveis acima.\"\"\"\n current_q = self.get_q_value(observation, action)\n max_future_q = self.get_max_future_q(new_observation)\n\n if reward == DOOR_REWARD:\n new_q = DOOR_REWARD\n elif reward == -ENEMY_PENALTY:\n new_q = -ENEMY_PENALTY\n else:\n new_q = (1 - LEARNING_RATE) * current_q + LEARNING_RATE * (reward + DISCOUNT * max_future_q)\n return new_q\n\n def get_max_future_q(self, new_observation):\n \"\"\"Retorna o maior q_value para um dado estado.\"\"\"\n return np.max(self.table[new_observation])\n\n def set_q_value(self, observation, action, value):\n \"\"\"Preenche o valor de um dado q_value para um estado com um novo valor.\"\"\"\n self.table[observation][action] = value\n\n def make_picke(self):\n \"\"\"Salva a tabela para um arquivo para posterior uso.\"\"\"\n with open(f\"qtable-{int(time.time())}.pickle\", \"wb\") as f:\n pickle.dump(self.table, f)\n","sub_path":"qlearn/python/classes/qtable.py","file_name":"qtable.py","file_ext":"py","file_size_in_byte":2446,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"205044828","text":"import json\nimport requests\nimport unittest\nfrom IP import ip_tc\n\n\nclass saveSendInfo(unittest.TestCase):\n '''•电子合同邮寄详情接口'''\n\n def test_01(self):\n '''正常测试'''\n url = ip_tc + \"/trade/saveSendInfo\"\n headers = {'Content-Type': 'application/json'}\n data = {\n \"electronicContractId\": 123,\n \"orderNo\": \"15424534fd\",\n \"sendTime\": 1554283396,\n \"sendFirm\": \"邮政EMS\",\n \"sendOrderNo\": \"emc123\"\n }\n\n with requests.post(url=url, headers=headers, data=json.dumps(data)) as response:\n code = response.status_code\n response_time = response.elapsed.microseconds / 1000\n return_data = response.text\n print(\"返回数据:%s\" % return_data)\n # print(data)\n # print(response.headers)\n print(\"请求地址:%s\" % response.url)\n print(\"状态码:%d\" % code)\n print(\"响应时间:%s毫秒\" % response_time)\n # time.sleep(1)\n self.assertEqual(code, 200, \"状态码错误\")\n print(\"成功\")\n","sub_path":"cbs_api/trade_center/test_trade_saveSendInfo.py","file_name":"test_trade_saveSendInfo.py","file_ext":"py","file_size_in_byte":1131,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"622781892","text":"import sys\nimport os\nimport json\nimport datetime\nimport typing\nfrom bs4 import BeautifulSoup\n\nfrom modules import NewsArticle\n\n\nclass TestNewsArticleModule:\n\n __ARTICLES = None\n __THIS_DIR = os.path.dirname(os.path.abspath(__file__))\n __JSON_CONFIG_FILEPATH = os.path.join(__THIS_DIR, 'articles_db.json')\n __ARTICLES_FOLDER = os.path.join(__THIS_DIR, 'resources')\n\n @classmethod\n def _get_articles(cls,) -> typing.List[dict]:\n \"\"\" Returns a list of dictionaries. Each dictionary in the list represents\n an articles from the `resources` folder, when the keys to each dictionray\n are:\n\n * `content`: the html content, as a string\n * `expected`: a dictionary loaded directly from the json configurations\n file, that saves all of the expected properties of the\n api from the article instance.\n \"\"\"\n\n if cls.__ARTICLES is None:\n # If articles are not loaded yet, loads them!\n\n # load the configuration file\n with open(cls.__JSON_CONFIG_FILEPATH, encoding='utf8') as open_file:\n cls.__ARTICLES = json.load(open_file)\n\n # load each file specified in the configuration file\n for article_config in cls.__ARTICLES:\n\n # generate the path to the current article file\n filepath = os.path.join(\n cls.__ARTICLES_FOLDER, article_config['filename'])\n\n # open the article, and save the data in the dictionray\n with open(filepath, 'r', encoding='utf8') as open_file:\n\n # read raw html file\n content = open_file.read()\n\n # convert html to NewsArticle instance\n article_config['article'] = NewsArticle(\n data=BeautifulSoup(content, 'lxml')\n )\n\n return cls.__ARTICLES\n\n def test_title_property(self,):\n for article in self._get_articles():\n title = article['article'].title\n expected = article['expected']['title']\n assert title == expected\n\n def test_subtitle_property(self,):\n for article in self._get_articles():\n subtitle = article['article'].subtitle\n expected = article['expected']['subtitle']\n assert subtitle == expected\n\n def test_subject_property(self,):\n for article in self._get_articles():\n subject = article['article'].subject\n expected = article['expected']['subject']\n assert subject == expected\n\n def test_subsubjects_property(self,):\n for article in self._get_articles():\n subsubjects = article['article'].subsubjects\n expected = article['expected']['subsubjects']\n assert subsubjects == expected\n\n def test_posted_string_property(self,):\n for article in self._get_articles():\n posted_string = article['article'].posted_string\n expected = article['expected']['posted_string']\n assert posted_string == expected\n\n def test_posted_date_property(self,):\n for article in self._get_articles():\n posted_date = article['article'].posted_date\n assert isinstance(posted_date, datetime.date)\n\n def test_content_property(self,):\n for article in self._get_articles():\n content = article['article'].content\n expected = '\\n'.join(article['expected']['content_lines'])\n assert content == expected\n\n def test_content_lines_property(self,):\n for article in self._get_articles():\n content = article['article'].content_lines\n expected = article['expected']['content_lines']\n assert content == expected\n\n def test_attached_files_property(self,):\n for article in self._get_articles():\n attached_files = article['article'].attached_files\n expected = article['expected']['attached_files']\n assert attached_files == expected\n","sub_path":"tests/test_api.py","file_name":"test_api.py","file_ext":"py","file_size_in_byte":4063,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"311160803","text":"import json\n\nfrom django.shortcuts import render\n\nfrom movies.models import Movie, MovieLocation\nfrom sf_movies.settings import MAPS_API_KEY\nfrom django.http.response import HttpResponse\n\n\n# Create your views here.\ndef index(request):\n data = {\n 'center': {'lat': 37.7577, 'lng': -122.4376},\n 'api_key': MAPS_API_KEY,\n 'movies_list': json.dumps(list(Movie.objects.values('id', 'title')))\n }\n return render(request, 'index.html', data)\n\n\ndef movie_locations(request, movie_id):\n try:\n movie = Movie.objects.select_related('production_company', 'distributor', 'director',\n 'writer').prefetch_related('actors', 'actors__actor').get(id=movie_id)\n except Movie.DoesNotExist:\n return JSONResponse({'error': 'Movie not found'}, status=404)\n \n movie_locs = MovieLocation.objects.filter(movie_id=movie).select_related('location')\n \n data = {\n 'movie': movie.data(),\n 'locations': [movie_loc.data() for movie_loc in movie_locs]\n }\n return JSONResponse(data)\n\n\ndef JSONResponse(data, *args, **kwargs):\n return HttpResponse(json.dumps(data), content_type='application/javascript; charset=utf8', *args, **kwargs)","sub_path":"movies/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1228,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"644797960","text":"import sys\ninput=sys.stdin.readline\n\nN,M = map(int,input().split())\n\nmon_and_num={}\nnum_and_mon={}\n\nfor i in range(N):\n p = input().rstrip()\n mon_and_num[p] = i+1\n num_and_mon[i+1] = p\n\nfor _ in range(M):\n q=input().rstrip()\n if q.isdigit():\n print(num_and_mon.get(int(q)))\n else:\n print(mon_and_num.get(q))\n\n","sub_path":"백준/Python/알고파/2021.01.04/1620(나는야 포켓몬 마스터 이다솜).py","file_name":"1620(나는야 포켓몬 마스터 이다솜).py","file_ext":"py","file_size_in_byte":341,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"550015995","text":"import urllib2\nfrom xml.dom import minidom\nimport datetime\nimport pandas as pd\n\nimport matplotlib.pyplot as plt\nimport matplotlib.animation as animation\nfrom matplotlib import style\nfrom matplotlib.ticker import MultipleLocator, FormatStrFormatter\nimport matplotlib as mpl\n\nimport pytz\n\n\ndef SysFreq(i):\n df = pd.DataFrame(columns=(\"Timestamp\", \"Frequency\"))\n\n #startdate = (datetime.datetime.now() - datetime.timedelta(days=1 - 1)).strftime(\"%Y-%m-%d\")\n startdate = enddate = (datetime.datetime.now()).strftime(\"%Y-%m-%d\")\n APIKey = 'wop5wtevc7drivc'\n url = 'https://api.bmreports.com/BMRS/FREQ/v1?APIKey=%s&FromDate=%s&ToDate=%s&ServiceType=xml' % (\n APIKey, startdate, enddate)\n doc = minidom.parse(urllib2.urlopen(url))\n xmlextract = doc.getElementsByTagName(\"item\")\n\n for x in xmlextract:\n pubdate = x.getElementsByTagName(\"reportSnapshotTime\")[0].firstChild.data\n pubtime = x.getElementsByTagName(\"spotTime\")[0].firstChild.data\n timestamp = bst.localize( pd.to_datetime(pubdate + ' ' + pubtime, format='%Y-%m-%d %H:%M:%S') )\n forecasttemp = float(x.getElementsByTagName(\"frequency\")[0].firstChild.data)\n\n df.loc[len(df) + 1] = [timestamp, forecasttemp]\n\n\n xs = df.Timestamp\n ys = df.Frequency\n ax1.clear()\n title = \"System Frequency : %s Hz\" % (ys[len(ys)])\n plt.title(title)\n ax1.plot(xs, ys, '-', color='blue')\n\n # print min(df.Timestamp), max(df.Timestamp)\n plt.axhline(y=50.5, linewidth=4, color='red', alpha=0.2)\n plt.axhline(y=49.5, linewidth=4, color='red', alpha=0.2)\n\n plt.axis([min(df.Timestamp), max(df.Timestamp), 49, 51])\n for tick in ax1.xaxis.get_major_ticks():\n tick.label.set_fontsize(10)\n\n for tick in ax1.yaxis.get_major_ticks():\n tick.label.set_fontsize(10)\n\n majorFormatter = mpl.dates.DateFormatter('%H:%M')\n ax1.xaxis.set_major_formatter(majorFormatter)\n\n ax1.axhspan(50.5, 51, alpha=0.1, color='red')\n ax1.axhspan(49.5, 49, alpha=0.1, color='red')\n\n\nstyle.use('fivethirtyeight')\n# style.use('ggplot')\n\nbst = pytz.timezone('Europe/London')\n\nfig = plt.figure()\nax1 = fig.add_subplot(1, 1, 1)\n\nani = animation.FuncAnimation(fig, SysFreq, interval=60000)\nplt.show()\n","sub_path":"Frequency/Frequency.py","file_name":"Frequency.py","file_ext":"py","file_size_in_byte":2220,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"83529518","text":"import keras as K\nimport tensorflow as tf\nimport numpy as np\nfrom keras.layers import Input, Dense, Conv2D, concatenate, Flatten\nfrom keras.models import Model\nfrom matplotlib import pyplot as plt\nimport time\nNAP = 15 # AP 数目\nNchannel = 15 # 信道 数目\n\n# sess = tf.Session()\n# logdir = time.strftime(\"%Y%m%d_%H_%M\", time.localtime())+\"/\"\n# writer = tf.summary.FileWriter(logdir, sess.graph)\n# Lossrecord = tf.placeholder(tf.float32, [])\n# tf.summary.scalar(\"Loss\", Lossrecord)\n\n\ntotal_train_time = 1000\n\n\n\n# the interference matrix\n\" better to normalize \"\nInterference_matrix = np.zeros([NAP, NAP])\nfor i in range(NAP):\n for j in range(i+1, NAP):\n randomnum = np.random.uniform(0, 1)\n Interference_matrix[i, j] = randomnum\n Interference_matrix[j, i] = randomnum\n# print(Interference_matrix)\nclass Energy():\n def __init__(self, I, Nchannel, NAP, model):\n self.I = I\n self.Nchannel = Nchannel\n self.NAP = NAP\n self.Wight = []\n for i in range(NAP):\n for j in range(i + 1, NAP):\n self.Wight.append(self.I[i, j])\n self.model = model\n self.I = self.I[np.newaxis, :, :, np.newaxis]\n\n def energy(self,label):\n energylist = []\n flag = 0\n for AP1 in range(NAP):\n for AP2 in range(AP1 + 1, NAP):\n templabel1 = label[AP1]\n templabel2 = label[AP2]\n energylist.append(tf.reduce_sum(tf.multiply(templabel1, templabel2))*self.Wight[flag])\n flag += 1\n energy = tf.reduce_sum(energylist)\n return energy\n\n def compile(self, lr):\n opt = K.optimizers.Adagrad(learning_rate=lr)\n updates = opt.get_updates(params=self.model.trainable_weights, loss=self.energy(self.model.output))\n self.train_fn = K.backend.function([self.model.input], [self.model.output,self.energy(self.model.output)], updates=updates)\n\n def train(self, times):\n record_loss = []\n for time in range(times):\n inputs = self.I + 0.001 * np.random.randn(1, NAP, NAP,1)\n outputs, loss = self.train_fn(inputs)\n record_loss.append(loss)\n APchannel = []\n for i in range(self.NAP):\n APchannel.append(np.argmax(outputs[i]))\n channelset=[]\n for j in range(Nchannel):\n channelset.append([i for i in range(len(APchannel)) if APchannel[i] == j])\n print(\"times = \", time, \"\\t\", \"loss\", loss)\n print(channelset)\n return record_loss\n\n\n\n# 备用\n# def clipped_error(X, label):\n# error = energy(X, label)\n# if error > 10:\n# return 10\n# else:\n# return error\n\n# setup the network\ninput= Input(shape=(NAP, NAP, 1))\nX = Conv2D(32, (3, 3), padding='same', activation=\"relu\")(input)\nX = Conv2D(32, (3, 3), padding='same', activation=\"relu\")(X)\nX = Flatten()(X)\nX = Dense(Nchannel*NAP, activation=\"relu\")(X)\nXzi = []\nfor i in range(NAP):\n Xzi.append(Dense(Nchannel, activation=\"softmax\")(X))\n# out = concatenate(Xzi)\nmodel = Model(inputs=input, outputs=Xzi)\n\nagent = Energy(Interference_matrix, NAP=NAP, Nchannel=Nchannel, model=model)\nagent.compile(lr=1e-4)\nrecord_loss = agent.train(10000)\nplt.figure()\nplt.plot(record_loss)\nplt.title(\"training_loss\")\nplt.show()\n","sub_path":"wlan4HW/perious/deep_energy_network.py","file_name":"deep_energy_network.py","file_ext":"py","file_size_in_byte":3326,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"517852445","text":"from random import randrange as rand\nimport os\nimport pygame\nimport math\nimport sys\nfrom constants import *\n\nclass Block(object):\n\n\tdef joinMatrices(self, mat1, mat2, mat2Off):\n\t\toffX = mat2Off[0]\n\t\toffY = mat2Off[1]\n\t\tfor countY, row in enumerate(mat2):\n\t\t\tfor countX, val in enumerate(row):\n\t\t\t\tmat1[countY + offY + trial - 13][countX + offX] += val\n\t\treturn mat1\n\n\tdef moveLeft(self):\n\t\tif(self.gameover == False and self.paused == False):\n\t\t\tnewX = self.blockX - 1\n\t\t\tif newX < 0:\n\t\t\t\tnewX = 0\n\t\t\tif not self.checkCollision(self.board, self.block, (newX, self.blockY)):\n\t\t\t\tself.blockX = newX\n\n\tdef moveRight(self):\n\t\tif(self.gameover == False and self.paused == False):\n\t\t\tnewX = self.blockX + 1\n\t\t\tif newX > columns - len(self.block[0]):\n\t\t\t\tnewX = columns - len(self.block[0])\n\t\t\tif not self.checkCollision(self.board, self.block, (newX, self.blockY)):\n\t\t\t\tself.blockX = newX\n\n\tdef rotate(self):\n\t\tif(self.gameover == False and self.paused == False):\n\t\t\tnewBlock = [[self.block[x][y] for x in range(len(self.block))] for y in range(len(self.block[0]) - 1, -1, -1)]\n\t\t\tif not self.checkCollision(self.board, newBlock, (self.blockX, self.blockY)):\n\t\t\t\tself.block = newBlock\n\n\tdef fallBottom(self):\n\t\tif(self.gameover == False and self.paused == False):\n\t\t\tself.score += trial - 2\n\t\t\twhile(not self.drop()):\n\t\t\t\tpass\n\n\tdef drop(self):\n\t\tif(self.gameover == False and self.paused == False):\n\t\t\tself.blockY += 1\n\t\t\tif self.checkCollision(self.board, self.block, (self.blockX, self.blockY)):\n\t\t\t\tself.board = self.joinMatrices(self.board, self.block, (self.blockX, self.blockY))\n\t\t\t\tself.newBlock()\n\t\t\t\tclearedRows = 0\n\t\t\t\tclearedRows = self.checkRowFull(clearedRows)\n\t\t\t\tself.addClearedLines(clearedRows)\n\t\t\t\treturn True\n\t\treturn False\n\n\tdef newBlock(self):\n\t\tself.block = self.nextBlock\n\t\tself.nextBlock = tetrisShapes[rand(len(tetrisShapes))]\n\t\tself.blockX = int(columns / 3 - len(self.block[0]) / 2 + trial - 7)\n\t\tself.blockY = initY\n\t\tif self.checkCollision(self.board, self.block, (self.blockX, self.blockY)):\n\t\t\tself.gameover = True\n\t\telse:\n\t\t\tFalse\n\n\tdef renderMatrix(self, matrix, offset):\n\t\tfor y, row in enumerate(matrix):\n\t\t\tfor x, val in enumerate(row):\n\t\t\t\tif val:\n\t\t\t\t\tif(self.score >= 0 and self.level >= 0):\n\t\t\t\t\t\tpygame.draw.rect(self.screen, colours[val], pygame.Rect((offset[0] +x) * cellSize, (offset[1] + y) * cellSize, cellSize, cellSize), 0)\n\n\tdef checkRowFull(self, clearedRows):\n\t\twhile 1:\n\t\t\tfor i, row in enumerate(self.board[:-1]):\n\t\t\t\tif 0 not in row:\n\t\t\t\t\tscores = self.score\n\t\t\t\t\tself.board = self.removeRow(self.board, i)\n\t\t\t\t\tclearedRows += 1\n\t\t\t\t\tbreak\n\t\t\telse:\n\t\t\t\tbreak\n\t\treturn clearedRows\n","sub_path":"Block.py","file_name":"Block.py","file_ext":"py","file_size_in_byte":2629,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"287033158","text":"# Imports\n# ------------------------------------\n\nimport tkinter as tk\nfrom gpiozero import LED as PIN, OutputDevice\nfrom gpiozero.pins.pigpio import PiGPIOFactory\n# ====================================\n# Variable Decleration\n# ------------------------------------\ndevice = OutputDevice() #GPIO Pin Output Device\n# ====================================\n# Window Creation\n# ------------------------------------\n#Create Window Instance\n\n\nwin = tk.Tk()\n#Add Window Title\nwin.title(\"GPIO Pin Toggle\")\n#Add Title and Position it\nlbl = tk.Label(win, text=\"GPIO Pin Toggling\", font=(\"Helvetica\", 15))\nlbl.grid(column=0, row=0)\n\n#Create Textbox to Specify Pin Number\ntxt = tk.Entry(win, width=3)\ntxt.grid(column=0, row=1)\ntxt.insert(0, \"Pin\")\n\n#Set Status\nstatusvar = tk.StringVar()\nstatusvar.set(\"Pin Status Shown Here\")\n#Display Pin Status\nstatuslbl = tk.Label(win, textvar = statusvar, font=(\"Helvetica\", 7))\nstatuslbl.grid(column=0, row=4)\n\n# ====================================\n# Button Events\n# ------------------------------------\n# Pin Factory Configuration\nfactory = PiGPIOFactory(host='192.168.2.153')\n\n# On event\ndef pinenable():\n PinID = int(txt.get())\n led = LED(PinID)\n led.on()\n statusvar.set(\"Pim \" + txt.get() + \" Has Been Raised\")\n\n# Off event\ndef pindisable():\n PinID = int(txt.get())\n led = LED(PinID)\n led.off()\n statusvar.set(\"Pim \" + txt.get() + \" Has Been Lowered\")\n\n# ====================================\n\n#Set up on button\nbtn = tk.Button(win, text=\"Raise pin\", command=pinenable, width=25, height=3)\nbtn.grid(column=0, row=2)\n#Set up off button\nbtn = tk.Button(win, text=\"Lower pin\", command=pindisable, width=25, height=3)\nbtn.grid(column=0, row=3)\n\n\n\n#Start GUI/ Create Main Loop\nwin.mainloop()\n","sub_path":"gui.py","file_name":"gui.py","file_ext":"py","file_size_in_byte":1740,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"632600705","text":"#!/usr/bin/env python\n'''\nThis file is part of cronbooru.\nCopyright (c) 2013 \nLicense: ISC\n'''\nimport re\nimport sys\nimport urllib.request as request\n\nregex = re.compile('\\/\\/images\\.4chan\\.org\\/[0-9a-z]+\\/src\\/[0-9]+\\.jpg')\n\ndef prepend_http_scheme(url):\n \"\"\"Prepends the \"http:\" protocol prefix to url.\"\"\"\n return 'http:' + url\n\ndef fetch(thread_url):\n \"\"\"Fetch a list of images links from a 4chan thread.\n\n Args:\n thread_url (str): Thread URL.\n Returns:\n list of images links\n\n \"\"\"\n links = []\n \n # Fetch thread and parse links.\n response = request.urlopen(thread_url)\n for line in response:\n links += regex.findall(line.decode('utf-8'))\n\n # Remove duplicates.\n links = list(set(links))\n # Prefix links with http:\n links = list(map(prepend_http_scheme, links))\n\n return links\n\n\nif __name__ == '__main__':\n print(fetch(sys.argv[1]))\n\n","sub_path":"cronbooru/fetchers/4chan.py","file_name":"4chan.py","file_ext":"py","file_size_in_byte":883,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"291535453","text":"import os\nfrom datetime import datetime, timedelta\nfrom flask import Flask, request, abort, jsonify, render_template\nfrom twilio.twiml.messaging_response import Message, MessagingResponse\nfrom twilio.rest import Client\nfrom zenpy import Zenpy\nfrom zenpy.lib.api_objects import Comment\n\naccount_sid = \"ACceac8c71e9298d4315924848d3c1430f\"\nauth_token = \"2046e3f70da370761444e2942399b559\"\n\nclient = Client(account_sid, auth_token)\n\nzen_creds = {\n 'email' : 'kevin@entuit.com',\n 'token' : 'MPjDsA808HoCkZxrqclTzsxWYAO5uPnzLGdXhpc9',\n 'subdomain' : 'entuit'\n}\n\napp = Flask(__name__)\n\n@app.route('/sms', methods=['POST'])\ndef sms():\n number = request.form['From']\n message_body = request.form['Body']\n\n resp = MessagingResponse()\n resp.message('Hello {}, you sent: {}'.format(number, message_body))\n return str(resp)\n\n@app.route('/webhook', methods=['POST'])\ndef webhook():\n if request.method == 'POST':\n print(request.json)\n content = request.get_json()\n print(content['number'])\n client.messages.create(\n from_='16473609143',\n to=content['number'],\n body=content['body']\n )\n return '', 200\n else:\n abort(400)\n\n\n@app.route('/approve', methods=['GET'])\ndef approve():\n\n zenpy = Zenpy(**zen_creds)\n ticket_id = request.args[\"id\"]\n\n ticket = zenpy.tickets(id=ticket_id)\n ticket.comment = Comment(body=\"Approved\", public=False)\n zenpy.tickets.update(ticket)\n\n return render_template('approve.html')\n\n\n@app.route('/', methods=['GET'])\ndef site():\n\n ticket_id = request.args[\"id\"]\n return render_template('main.html', ticket_id = ticket_id)\n\n \nif __name__ == '__main__':\n app.run(debug=True)\n","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":1742,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"229038318","text":"from setuptools import find_packages\nfrom distutils.core import setup, Extension\nimport pybind11\nfrom glob import glob\nimport sys\n\n__version__ = \"0.0.3\"\nwith open(\"README.md\") as f:\n readme = f.read()\n\next_modules = [\n Extension(\"_embedding\",\n sorted(glob(\"hyperlib/embedding/src/*.cc\")),\n include_dirs = [\"hyperlib/embedding/include\", pybind11.get_include()],\n language = \"c++\",\n extra_compile_args = [\"-std=c++11\"]\n )\n]\n\n\nsetup(\n name=\"hyperlib\",\n version=__version__,\n packages = find_packages(),\n setup_requires = [\"pip>=21\"],\n install_requires = [\"numpy>=1.19.3\", \n\t\t\t\t\t\t\"tensorflow>=2.0.0\",\n\t\t\t\t\t\t\"scipy>=1.7.0\", \n \"mpmath\"],\n ext_modules=ext_modules,\n author=\"Nalex.ai\",\n author_email=\"info@nalexai.com\",\n description=\"Library that contains implementations of machine learning components in the hyperbolic space\",\n long_description=readme,\n project_urls = {\n \"Source\" : \"https://github.com/nalexai/hyperlib\",\n \"Issues\" : \"https://github.com/nalexai/hyperlib/issues\"\n },\n license_files = \"LICENSE\",\n url = \"https://github.com/nalexai/hyperlib\",\n classifiers = [ \n \"Programming Language :: Python :: 3\",\n \"Liscense :: OSI Approved :: MIT License\",\n \"Operating System :: OS Independent\"\n ], \n)\n","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":1457,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"520692738","text":"# I want to be able to call is_sorted from main w/ various lists and get\n# returned True or False.\n# In your final submission:\n# - Do not print anything extraneous!\n# - Do not put anything but pass in main()\n\ndef is_sorted(list_of_elements):\n\tif len(list_of_elements) < 2:\n\t\treturn True\n\tfor idx in range(0, len(list_of_elements) - 1):\n\t\tif list_of_elements[idx] > list_of_elements[idx + 1]:\n\t\t\treturn False\n\treturn True\n\ndef main():\n\tlist_of_nos = [1, 2, 3, 6]\n\tlist_of_chars = ['a', 'c' , 'b']\n\tprint(is_sorted(list_of_nos))\n\tprint(is_sorted(list_of_chars))\n\nif __name__ == \"__main__\":\n\tmain()","sub_path":"HW07_ch10_ex06.py","file_name":"HW07_ch10_ex06.py","file_ext":"py","file_size_in_byte":597,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"209085762","text":"# Get input from stdin\nl = [int(i) for i in raw_input().split(' ')]\narray = [int(i) for i in raw_input().split(' ')]\n# Define k & counter.\nk, count = l[1], 0\nwhile count <= k and len(array) > 0:\n minimum_val_ = min(array)\n array.remove(minimum_val_)\n count += 1\n k -= minimum_val_\ncount -= 1\nprint(str(count))\n","sub_path":"JimsToys.py","file_name":"JimsToys.py","file_ext":"py","file_size_in_byte":322,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"146545355","text":"\"\"\"\nHBA agent. Using the current beliefs of opponent type, this class uses MCTS to \nexpand the game tree, before using UCT to give weight to the 'best' moves.\nEdward Stevinson\nAdapted from Andy Salerno (2016)\n\"\"\"\n\nimport random\nimport time\nimport math\nimport copy\nfrom agents.agent import Agent\nfrom game.workspace import Workspace\nfrom util import *\nimport numpy as np # will need this when I change actions to matrix\nfrom setuptools.command.build_ext import if_dl\n\n\nclass HBAAgent(Agent):\n\n def __init__(self, reversi, color, **kwargs):\n self.color = color\n self.reversi = reversi\n self.sim_time = kwargs.get('sim_time', 5) \n \n self.workspace = Workspace() # Create a workspace object\n self.typeChoice = 0\n\n # map states to nodes for quick lookup\n self.state_node = {}\n\n def reset(self):\n pass\n\n def observe_win(self, winner):\n pass\n\n def get_action(self, game_state, legal_moves, lastAction, t):\n \"\"\"Interface from class Agent. Given a game state\n and a set of legal moves, pick a legal move and return it.\n This will be called by the Reversi game object. Does not mutate\n the game state argument.\"\"\"\n # make a deep copy to keep the promise that we won't mutate\n if not legal_moves:\n return None\n game_state = copy.deepcopy(game_state)\n move = self.monte_carlo_search(game_state, lastAction, t) # Also pass workspace\n return move\n\n def monte_carlo_search(self, game_state, lastAction, t):\n \"\"\"Given a game state, return the best action decided by\n using Monte Carlo Tree Search with an Upper Confidence Bound.\"\"\"\n\n \n results = {} # map position to wins/plays for sorted info print\n\n # This isn't strictly necessary for Monte Carlo to work,\n # but if we've seen this state before we can get better results by\n # reusing existing information.\n root = None\n if game_state in self.state_node:\n root = self.state_node[game_state]\n else:\n root = Node(game_state)\n\n # even if this is a \"recycled\" node we've already used,\n # remove its parent as it is now considered our root level node\n root.parent = None\n \n if t>2: # It should be the first turn not the first run of MCTS\n # Update workspace\n self.workspace.update_iteration(game_state[0], lastAction) ################################ MOVE\n print(self.workspace.posterior)\n print(t)\n\n sim_count = 0\n now = time.time()\n while time.time() - now < self.sim_time:\n #if t>2: # It should be the first turn not the first run of MCTS\n # # Update workspace\n # self.workspace.update_iteration(game_state[0], lastAction) ################################ MOVE\n \n # Decide that the opponent is a certain type i.e. MC_prepare_epsiodes i.e. W.model\n self.typeChoice = self.randomAct()\n \n picked_node = self.tree_policy(root)\n result = self.simulate(picked_node.game_state, t)\n self.back_prop(picked_node, result)\n sim_count += 1\n\n for child in root.children:\n wins, plays = child.get_wins_plays()\n position = child.move\n results[position] = (wins, plays)\n\n for position in sorted(results, key=lambda x: results[x][1]):\n info('{}: ({}/{})'.format(position, results[position][0], results[position][1] ))\n info('{} simulations performed.'.format(sim_count))\n return self.best_action(root)\n\n @staticmethod\n def best_action(node):\n \"\"\"Returns the best action from this game state node.\n In Monte Carlo Tree Search we pick the one that was\n visited the most. We can break ties by picking\n the state that won the most.\"\"\"\n most_plays = -float('inf')\n best_wins = -float('inf')\n best_actions = []\n for child in node.children:\n wins, plays = child.get_wins_plays()\n if plays > most_plays:\n most_plays = plays\n best_actions = [child.move]\n best_wins = wins\n elif plays == most_plays:\n # break ties with wins\n if wins > best_wins:\n best_wins = wins\n best_actions = [child.move]\n elif wins == best_wins:\n best_actions.append(child.move)\n\n return random.choice(best_actions)\n\n @staticmethod\n def back_prop(node, delta):\n \"\"\"Given a node and a delta value for wins,\n propagate that information up the tree to the root.\"\"\"\n while node.parent is not None:\n node.plays += 1\n node.wins += delta\n node = node.parent\n\n # update root node of entire tree\n node.plays += 1\n node.wins += delta\n\n def tree_policy(self, root):\n \"\"\"Given a root node, determine which child to visit\n using Upper Confidence Bound.\"\"\"\n cur_node = root\n\n while True:\n legal_moves = self.reversi.legal_moves(cur_node.game_state)\n if not legal_moves:\n if self.reversi.winner(cur_node.game_state) is not False:\n # the game is won\n return cur_node\n else:\n # no moves, so turn passes to other player\n next_state = self.reversi.next_state(\n cur_node.game_state, None)\n pass_node = Node(next_state)\n cur_node.add_child(pass_node)\n self.state_node[next_state] = pass_node\n cur_node = pass_node\n continue\n\n elif len(cur_node.children) < len(legal_moves):\n # children are not fully expanded, so expand one\n unexpanded = [\n move for move in legal_moves\n if move not in cur_node.moves_expanded\n ]\n\n # note to self: this tree of nodes includes nodes of both players, right?\n # so are you always assuming the enemy makes bad moves when you .best_child()\n # on one of their states?\n\n assert len(unexpanded) > 0\n move = random.choice(unexpanded)\n state = self.reversi.next_state(cur_node.game_state, move)\n n = Node(state, move)\n cur_node.add_child(n)\n self.state_node[state] = n\n return n\n\n else:\n # Every possible next state has been expanded, so pick one\n cur_node = self.best_child(cur_node)\n\n return cur_node\n\n def best_child(self, node):\n enemy_turn = (node.game_state[1] != self.color)\n C = 1 # 'exploration' value\n values = {}\n for child in node.children:\n wins, plays = child.get_wins_plays()\n if enemy_turn:\n # the enemy will play against us, not for us\n wins = plays - wins\n _, parent_plays = node.get_wins_plays()\n assert parent_plays > 0\n values[child] = (wins / plays) \\\n + C * math.sqrt(2 * math.log(parent_plays) / plays)\n\n best_choice = max(values, key=values.get)\n return best_choice\n\n def simulate(self, game_state, t):\n \"\"\"Starting from the given game state, simulate\n a random game to completion, and return the profit value\n (1 for a win, 0 for a loss)\"\"\"\n WIN_PRIZE = 1\n LOSS_PRIZE = 0\n state = copy.deepcopy(game_state)\n step = 0\n while True:\n winner = self.reversi.winner(state)\n if winner is not False:\n if winner == self.color:\n return WIN_PRIZE\n elif winner == opponent[self.color]:\n return LOSS_PRIZE\n else:\n raise ValueError\n\n moves = self.reversi.legal_moves(state)\n if not moves:\n # if no moves, turn passes to opponent\n state = (state[0], opponent[state[1]])\n moves = self.reversi.legal_moves(state)\n\n \"\"\"Act according to type for the rest of the simulation\"\"\"\n # Inherently presumes that HBA is white here. CHANGE!\n if state[1] == 1:\n # HBA continues to act randomly\n picked = random.choice(moves)\n else:\n # The opposition does not act randomly, but rather according to the type randomly decided by typeChoice\n if step < 5:\n a = self.typeChoice\n b = a+1\n name = 'type' + str(b)\n typeSel = getattr(self.workspace, name)\n picked = typeSel.get_action(state, moves)\n \"\"\"if t < 14:\n picked = self.workspace.type1.get_action(state, moves)\n elif t < 28:\n picked = self.workspace.type3.get_action(state, moves)\n else:\n picked = self.workspace.type2.get_action(state, moves)\"\"\"\n else:\n picked = random.choice(moves)\n \n \n \n state = self.reversi.apply_move(state, picked)\n step = step + 1\n \n def randomAct(self):\n \"\"\"Choose according to the probability values\"\"\"\n length = len(self.workspace.posterior)\n a = random.randint(0,9999)\n b = a/10000\n x = np.cumsum(self.workspace.posterior)\n for i in range(0,length):\n if b < x[i]:\n c = i\n break\n return c\n\n\nclass Node:\n\n def __init__(self, game_state, move=None):\n self.game_state = game_state\n self.plays = 0\n self.wins = 0\n self.children = []\n self.parent = None\n self.moves_expanded = set()\n\n # the move that led to this child state\n self.move = move\n\n def add_child(self, node):\n self.children.append(node)\n self.moves_expanded.add(node.move)\n node.parent = self\n\n def has_children(self):\n return len(self.children) > 0\n\n def get_wins_plays(self):\n return self.wins, self.plays\n\n def __hash__(self):\n return hash(self.game_state)\n\n def __repr__(self):\n return 'move: {} wins: {} plays: {}'.format(self.move, self.wins, self.plays)\n\n def __eq__(self, other):\n if not isinstance(other, Node):\n return False\n return self.game_state == other.game_state","sub_path":"PYTHON/agents/hba_agent.py","file_name":"hba_agent.py","file_ext":"py","file_size_in_byte":10827,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"644904399","text":"# Definition for a binary tree node.\n# class TreeNode(object):\n# def __init__(self, val=0, left=None, right=None):\n# self.val = val\n# self.left = left\n# self.right = right\nclass Solution(object):\n def addOneRow(self, root, v, d):\n \"\"\"\n :type root: TreeNode\n :type v: int\n :type d: int\n :rtype: TreeNode\n \"\"\"\n \n def find(node, level):\n if(level == d - 1):\n lhs = TreeNode()\n lhs.val = v\n lhs.left = node.left\n node.left = lhs\n \n rhs = TreeNode()\n rhs.val = v\n rhs.right = node.right\n node.right = rhs\n else:\n if(node.left != None):\n find(node.left, level + 1)\n if(node.right != None):\n find(node.right, level + 1)\n \n if(d == 1) :\n lhs = TreeNode()\n lhs.val = v\n lhs.left = root\n return lhs\n else:\n find(root,1)\n return root","sub_path":"623.py","file_name":"623.py","file_ext":"py","file_size_in_byte":1123,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"290828624","text":"try:\n from egovScDoc.spiders.docSpider.base_spider import *\nexcept ImportError:\n from egovResearch.egovScDoc.spiders.docSpider.base_spider import *\n\n\nclass TianjinSpider(BaseSpider):\n __city_abbreviation__ = \"tianjin\"\n\n # ---/---更新页码信息\n def _update_page_count(self):\n \"\"\"\n 更新页码信息\n :return:\n \"\"\"\n browser = self._get_browser()\n for config in self.config_list:\n request_url = \"http://gk.tj.gov.cn/govsearch/search.jsp?ztfl={}\".format(config.class_id)\n browser.get(request_url)\n time.sleep(3)\n soup = BeautifulSoup(browser.page_source, \"lxml\")\n span = soup.find(\"span\",class_=\"nav_pagenum\")\n page_count = int(span.text)\n total_doc_nums = 0\n page_count += 1 # 需加1\n print(\"--num of docs--:\", total_doc_nums, \" --page_num--:\", page_count)\n config.loop_stop = page_count\n config.update()\n browser.close()\n\n def resolve_detail_page(self, item, html):\n soup = BeautifulSoup(html, 'lxml')\n origin_content = soup.find(\"div\", class_=\"article_content_file\")\n if origin_content is None:\n origin_content = soup.find(\"div\",class_=\"article_content\")\n for style in origin_content.find_all(\"style\"):\n style.decompose()\n for script in origin_content.find_all(\"script\"):\n script.decompose()\n for img in origin_content.find_all(\"img\"):\n img.decompose()\n\n item.organization = soup.find(\"span\", id=\"span_publisher\").text.strip()\n item.title = soup.find(\"span\", id=\"span_docTitle\").text.strip()\n item.remarks = soup.find(\"span\", id=\"span_subcat\").text.strip()\n remarks = item.remarks.split(\";\")\n if len(remarks) > 1:\n item.remarks = remarks[0]\n item.sub_cate = remarks[1]\n print(item.remarks, \" \", item.sub_cate)\n\n tds = soup.find(\"table\", class_=\"table_key\").find_all(\"td\")\n for index, td in enumerate(tds):\n if \"文 号\" in td.text:\n item.reference_number = tds[index + 1].text.strip()\n elif \"发文日期\" in td.text:\n release_time = tds[index + 1].text.strip()\n struct_time = time.strptime(release_time, u\"%Y年%m月%d日\")\n item.release_time = time.strftime(u\"%Y-%m-%d\", struct_time)\n\n item.print()\n item.update_content(origin_content)\n item.update()\n pass\n\n def save_all_files(self):\n request_url = \"http://gk.tj.gov.cn/govsearch/search.jsp\"\n base_url = \"http://gk.tj.gov.cn/\"\n config_list = self.config_list\n for config in config_list:\n for i in range(config.loop_start, config.loop_stop):\n page_dir = \"{}{}\\{}\".format(self.base_dir, config.class_id, i + config.page_start)\n print(config.remarks)\n print(i)\n post_data = {\n \"SType\": 1,\n \"searchColumn\": \"\",\n \"searchYear\": \"\",\n \"preSWord\": \"\",\n \"sword\": \"\",\n \"searchAgain\": \"\",\n \"page\": i,\n \"pubURL\": \"\",\n \"ztfl\": config.class_id\n }\n res = requests.post(request_url, headers=requests_header, data=post_data)\n res.encoding = \"UTF-8\"\n soup = BeautifulSoup(res.text, \"lxml\")\n divs = soup.find_all(\"div\", class_=\"index_right_content\")\n time.sleep(3)\n if not os.path.exists(page_dir):\n os.makedirs(page_dir)\n for div in divs:\n li = div.find(\"li\")\n item = EGOVSCPolicyPaper()\n a = li.find(\"a\")\n title = a.get(\"title\").strip()\n url = a.get(\"href\")\n if not url.startswith(\"http\"):\n url = \"{}/{}\".format(base_url, url)\n\n item.title = title\n item.url = url\n item.origin_page_index = i\n item.remarks = config.remarks\n item.save(self)\n\n sub_res = requests.get(url, headers=requests_header)\n sub_res.encoding = \"UTF-8\"\n with open(\"{}\\{}.html\".format(page_dir, item.id),\n \"w\", encoding=\"utf-8\") as f:\n f.write(sub_res.text)\n self.resolve_detail_page(item, sub_res.text)\n time.sleep(3)\n\nif __name__ == '__main__':\n with app.app_context():\n TianjinSpider(True).update()","sub_path":"egovResearch/egovScDoc/spiders/docSpider/tianjin_spider.py","file_name":"tianjin_spider.py","file_ext":"py","file_size_in_byte":4784,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"517735437","text":"\"\"\"\ngeometry_analysis.def This module contains the geometry analysis project\n\nAuthor: Scott Reed\n\n\"\"\"\n\nimport numpy\nimport os\nimport sys\n\n\ndef open_xyz(filename):\n \"\"\"opens and processes astandard file xyz file. Returns symbols and numpy array of coordinates \"\"\"\n xyz_file = numpy.genfromtxt(fname=filename, skip_header=2, dtype='unicode')\n symbols = xyz_file[:,0]\n coordinates = xyz_file[:,1:]\n coordinates = coordinates.astype(numpy.float)\n return symbols, coordinates\n\ndef bond_check(distance):\n \"\"\"\n Check if the length of a bond is between 0 and 1.5 angstroms, returning True if true and False is false\n \"\"\"\n #if distance < 1:\n #raise ValueError(\"your bond sucks\")\n if distance > 0 and distance < 1.5:\n value = True\n else:\n value = False\n return value\n\ndef calculate_distance(atom1_coord, atom2_coord):\n \"\"\"\n This is the one function to rule them all\n \"\"\"\n x_distance = atom1_coord[0]-atom2_coord[0]\n y_distance = atom1_coord[1]-atom2_coord[1]\n z_distance = atom1_coord[2]-atom2_coord[2]\n distance = numpy.sqrt(x_distance**2 + y_distance**2 + z_distance**2)\n\n return distance\n\nif __name__ == \"__main__\":\n print(F\"Running {sys.argv[0]}\")\n #file_location = os.path.join('water.xyz')\n if len(sys.argv) <2:\n raise NameError(\"Incorrect input! Please specify an xyz file\")\n\n file_location = sys.argv[1]\n symbols, coord = open_xyz(file_location)\n num_atoms = len(symbols)\n for num1 in range (0, num_atoms):\n for num2 in range(0, num_atoms):\n if num11.1).any() or (self.cur_state[:4]<-1.1).any():\n\t\t#\treward=-10000\n\t\t#\tdone=True\n\t\t#elif np.abs(-self.cur_state[0]-(self.cur_state[0]*self.cur_state[2]-self.cur_state[1]*self.cur_state[3]))>2.2:\n\t\t#\treward=-10000\n\t\t#\tdone=True\n\t\tif -self.cur_state[0]-(self.cur_state[0]*self.cur_state[2]-self.cur_state[1]*self.cur_state[3])>=self.goal_height:\n\t\t\treward=0.\n\t\t\tdone=True\n\t\telif self.num_steps>=self.horizon:\n\t\t\tdone=True\n\t\telse:\n\t\t\tdone=False\n\n\t\treturn self.cur_state,reward,done,info\n\n\n\tdef get_info(self):\n\t\treturn self.num_steps, self.cur_state\n","sub_path":"zs_sim_robot/common/corl_acrobot_env.py","file_name":"corl_acrobot_env.py","file_ext":"py","file_size_in_byte":3075,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"362897107","text":"# -*- coding: utf-8 -*-\n\nimport unittest2 as unittest\n\nfrom plone.app.testing import TEST_USER_ID\nfrom plone.app.testing import setRoles\n\nfrom collective.z3cform.widgets.testing import INTEGRATION_TESTING\n\nJAVASCRIPTS = [\n \"++resource++collective.z3cform.widgets/related.js\",\n \"++resource++collective.z3cform.widgets/jquery.tokeninput.min.js\",\n \"++resource++collective.z3cform.widgets/keywords.js\"\n ]\n\nCSS = [\n \"++resource++collective.z3cform.widgets/related.css\",\n \"++resource++collective.z3cform.widgets/token-input-facebook.css\"\n ]\n\nclass InstallTest(unittest.TestCase):\n\n layer = INTEGRATION_TESTING\n\n def setUp(self):\n self.portal = self.layer['portal']\n\n def test_installed(self):\n qi = getattr(self.portal, 'portal_quickinstaller')\n self.assertTrue(qi.isProductInstalled(\"collective.z3cform.widgets\"))\n\n def test_jsregistry(self):\n portal_javascripts = self.portal.portal_javascripts\n for js in JAVASCRIPTS:\n self.assertTrue(js in portal_javascripts.getResourceIds(),\n '%s not installed' % js)\n\n def test_cssregistry(self):\n portal_css = self.portal.portal_css\n for css in CSS:\n self.assertTrue(css in portal_css.getResourceIds(),\n '%s not installed' % css)\n\n\nclass UninstallTest(unittest.TestCase):\n\n layer = INTEGRATION_TESTING\n\n def setUp(self):\n self.portal = self.layer['portal']\n setRoles(self.portal, TEST_USER_ID, ['Manager'])\n self.qi = getattr(self.portal, 'portal_quickinstaller')\n self.qi.uninstallProducts(products=[\"collective.z3cform.widgets\"])\n\n def test_uninstalled(self):\n self.assertFalse(self.qi.isProductInstalled(\"collective.z3cform.widgets\"))\n\n def test_jsregistry_removed(self):\n portal_javascripts = self.portal.portal_javascripts\n for js in JAVASCRIPTS:\n self.assertFalse(js in portal_javascripts.getResourceIds(),\n '%s not removed' % js)\n\n def test_cssregistry_removed(self):\n portal_css = self.portal.portal_css\n for css in CSS:\n self.assertFalse(css in portal_css.getResourceIds(),\n '%s not removed' % css)\n\n\ndef test_suite():\n return unittest.defaultTestLoader.loadTestsFromName(__name__)\n","sub_path":"src/collective/z3cform/widgets/tests/test_setup.py","file_name":"test_setup.py","file_ext":"py","file_size_in_byte":2345,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"369990151","text":"# Autor: Juan Carlos Flores García A01376511. Grupo 02.\r\n# Programa que calcula el pago de un trabajador.\r\n\r\n# Función que calcula el pago normal.\r\ndef calcularPagoNormal(horasNormales, pagoPorHora):\r\n totalNormal = horasNormales * pagoPorHora\r\n return totalNormal\r\n\r\n# Función que calcula el pago extra.\r\ndef calcularPagoExtra(horasExtras, pagoPorHora):\r\n extra = (pagoPorHora * 0.65) + pagoPorHora\r\n totalExtra = horasExtras * extra\r\n return totalExtra\r\n\r\n# Función que calcula el pago total.\r\ndef calcularPagoTotal(pagoNormal, pagoExtra):\r\n total = pagoNormal + pagoExtra\r\n return total\r\n\r\n# Función principal.\r\ndef main():\r\n horasNormales = int(input(\"Teclea las horas normales trabajadas: \"))\r\n horasExtras = int(input(\"Teclea las horas extras trabajadas: \"))\r\n pagoPorHora = int(input(\"Teclea el pago por hora: \"))\r\n pagoNormal = calcularPagoNormal(horasNormales, pagoPorHora)\r\n pagoExtra = calcularPagoExtra(horasExtras, pagoPorHora)\r\n pagoTotal = calcularPagoTotal(pagoNormal, pagoExtra)\r\n\r\n print(\"Pago normal: $%.2f\" % (pagoNormal))\r\n print(\"Pago extra: $%.2f\" % (pagoExtra))\r\n print(\"-----------------------\")\r\n print(\"Pago total: $%.2f\" % (pagoTotal))\r\n\r\n# Llamada a la función principal.\r\nmain()\r\n\r\n","sub_path":"Pago.py","file_name":"Pago.py","file_ext":"py","file_size_in_byte":1269,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"565847762","text":"import numpy as np\nimport matplotlib.pyplot as plt\nfrom ipywidgets import interactive\nimport math\nimport sys\nsys.path.insert(1, 'D:\\AAlearnAA\\Study\\python')\nfrom rutaul.prnt import pg, pm, pr, py, pb\n\n\n\ndef drawgraph(seedingpath,gridsize,iteration = 1):\n # import pdb; pdb.set_trace()\n nodesDot = []\n labels = []\n gridlength, gridwidth = gridsize\n for x in range(0, gridlength):\n for y in range(0, gridwidth):\n nodesDot.append([x, y])\n\n nodesDot = np.asarray(nodesDot)\n plt.scatter(nodesDot[..., 1], nodesDot[..., 0])\n weights = []\n\n for path in seedingpath:\n tothestartnode = True\n pointer = path\n weights = weights + [path.weight]\n while(tothestartnode):\n if pointer.incomingcell.currentlocation == (0, 0):\n tothestartnode = False\n\n temp = np.asarray(\n [pointer.currentlocation, pointer.incomingcell.currentlocation])\n # print(temp[..., 1])\n # print(temp[..., 0])\n # plt.plot(temp[..., 1], gridlength - 1 -\n # temp[..., 0], 'g-', linewidth=5)\n lbl = ''\n if str(pointer.antscount) not in labels:\n lbl = str(pointer.antscount)\n labels = labels + [lbl]\n\n # pr(pointer.antscount)\n # pr( math.log(pointer.antscount))\n # pr((.1 * math.log(pointer.antscount)))\n plt.plot(temp[..., 1], gridlength - 1 - temp[..., 0],\n 'g', linewidth=5, alpha=.6,label=lbl)\n\n pointer = pointer.incomingcell\n # pr(labels)\n plt.legend(bbox_to_anchor=(1.05, 1), loc='upper left', borderaxespad=0.)\n # pb(f'total path reached {len(weights)} they are {weights}')\n # plt.figure(num=f'The {iteration} iteration')\n plt.title(f'The {iteration} iteration')\n plt.show()\n\n\nif __name__ == \"__main__\":\n gridsize = (5, 5)\n import antpath as pth\n incom = pth.path((0, 0), 3,gridsize, pth.start((0, 0), 0))\n temp = pth.path((0, 1), 4, gridsize, incom, antscount=4)\n temp = pth.path((1, 1), 4, gridsize, temp, antscount=4)\n temp = pth.path((2, 1), 4, gridsize, temp, antscount=4)\n temp = pth.path((2, 2), 4, gridsize, temp, antscount=4)\n temp.path2start = [(0, 0), (0, 1), (1, 1), (2, 1), (2, 2)]\n\n drawgraph([temp], gridsize)\n\n# interactive_plot = interactive(drawgraph, iter=columns)\n# interactive_plot\n","sub_path":"ignore_NOshare/packages/drawpath.py","file_name":"drawpath.py","file_ext":"py","file_size_in_byte":2423,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"446399534","text":"def Linear_Search(dlist,item):\r\n pos=0\r\n found=False\r\n while pos a[i + 1]):\n isSorted = False\n if (not isSorted):\n break\n if isSorted:\n print('정렬 완료')\n else:\n print('정렬 오류 발생')\n\nimport random, time\n\n\nM = 1000\nN = 100000\na = []\na.append(None)\nfor i in range(N):\n a.append(random.randint(1, M))\nstart_time = time.time()\ncountingSort(a, N, M)\nend_time = time.time() - start_time\nprint('계수 정렬의 실행 시간 (N = %d) : %0.3f'%(N, end_time))\ncheckSort(a, N)","sub_path":"2_Sorting/countingSort.py","file_name":"countingSort.py","file_ext":"py","file_size_in_byte":917,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"498894774","text":"class BinaryHeap:\n \"\"\"\n define some common util functions for min-heap and max-heap,\n this is not an interface class\n \"\"\"\n\n def __init__(self, array):\n self.heap = list(array)\n self.length = len(array) # number of elements in the array\n self.heapsize = 0 # how many elements in the heap are stored here\n # book-keep each element index in the array\n self.pos = {element: idx for idx, element in enumerate(self.heap)}\n\n def left(self, index):\n \"\"\"return index of left child node, zero-based indexing\"\"\"\n return 2*(index+1)-1\n\n def right(self, index):\n \"\"\"return index of right child node, zero-based indexing\"\"\"\n return 2*(index+1)\n\n def parent(self, index):\n \"\"\"return index of the parent node, zero-based indexing\"\"\"\n return int((index-1)/2)\n\n def is_empty(self):\n return self.heapsize == 0\n\n def __str__(self):\n return str(self.heap)\n\n __repr__ = __str__\n\n def __len__(self):\n return self.heapsize\n\n def __contains__(self, key):\n if key in self.heap:\n return True\n return False\n\n\nclass MinHeap(BinaryHeap):\n def __init__(self, array):\n super(MinHeap, self).__init__(array)\n self.build_min_heap()\n\n def build_min_heap(self):\n self.heapsize = self.length\n mid_id = int((self.heapsize)/2)-1\n for i in range(mid_id, -1, -1):\n self.min_heapify(i)\n\n def min_heapify(self, index):\n left = self.left(index)\n right = self.right(index)\n if left <= self.heapsize-1 and self.heap[left] < self.heap[index]:\n min_id = left\n else:\n min_id = index\n if right <= self.heapsize-1 and self.heap[right] < self.heap[min_id]:\n min_id = right\n if min_id != index:\n # update index for each data\n self.pos[self.heap[min_id]] = index\n self.pos[self.heap[index]] = min_id\n # swap up smaller element\n self.heap[min_id], self.heap[index] = self.heap[index], self.heap[min_id]\n self.min_heapify(min_id)\n\n def insert(self, key):\n self.heapsize = self.heapsize + 1\n self.heap.append(float('inf'))\n self.decrease_key_by_idx(self.heapsize-1, key)\n\n def delete_key(self, key):\n \"\"\"adapter interface for delete an element with its value\"\"\"\n if key in self.heap:\n idx = self.pos[key]\n self.delete(idx)\n del self.pos[key]\n else:\n raise ValueError(f'no such element {key} in the heap')\n\n def delete(self, i):\n \"\"\"delete an element with its index\"\"\"\n if self.heap[i] < self.heap[self.heapsize-1]:\n self.heap[i] = self.heap[self.heapsize-1]\n self.pos[self.heap[self.heapsize-1]] = i\n self.min_heapify(i)\n else:\n self.decrease_key_by_idx(i, self.heap[self.heapsize-1])\n del self.heap[self.heapsize-1]\n self.heapsize = self.heapsize - 1\n\n def decrease_key(self, key, new_key):\n \"\"\"adapter interface for decrease an element with its value\"\"\"\n if key in self.heap:\n idx = self.pos[key]\n self.decrease_key_by_idx(idx, new_key)\n del self.pos[key]\n else:\n raise ValueError(f'no such element {key} in the heap')\n\n def decrease_key_by_idx(self, i, new_key):\n \"\"\"decreases the value of element i's key to the new value key\"\"\"\n if new_key > self.heap[i]:\n print('new key is greater than current key')\n raise ValueError\n while i > 0 and self.heap[self.parent(i)] > new_key:\n self.heap[i] = self.heap[self.parent(i)]\n self.pos[self.heap[self.parent(i)]] = i\n i = self.parent(i)\n self.heap[i] = new_key\n self.pos[self.heap[i]] = i\n\n def minimum(self):\n return self.heap[0]\n\n def extract_min(self):\n if self.heapsize < 1:\n raise IndexError\n min_key = self.heap[0]\n del self.pos[self.heap[0]]\n self.heap[0] = self.heap[self.heapsize-1]\n del self.heap[self.heapsize-1]\n self.heapsize = self.heapsize - 1\n self.min_heapify(0)\n return min_key\n\n\nclass MaxHeap(BinaryHeap):\n def __init__(self, array):\n super(MaxHeap, self).__init__(array)\n self.build_max_heap()\n\n def build_max_heap(self):\n self.heapsize = self.length\n mid_id = int((self.heapsize)/2)-1\n for i in range(mid_id, -1, -1):\n self.max_heapify(i)\n\n def max_heapify(self, index):\n left = self.left(index)\n right = self.right(index)\n if left <= self.heapsize-1 and self.heap[left] > self.heap[index]:\n max_id = left\n else:\n max_id = index\n if right <= self.heapsize-1 and self.heap[right] > self.heap[max_id]:\n max_id = right\n if max_id != index:\n # update index for each data\n self.pos[self.heap[min_id]] = index\n self.pos[self.heap[index]] = max_id\n # swap up bigger element\n self.heap[max_id], self.heap[index] = self.heap[index], self.heap[max_id]\n self.max_heapify(max_id)\n\n def insert(self, key):\n self.heapsize = self.heapsize + 1\n self.heap.append(float('-inf'))\n self.increase_key_by_idx(self.heapsize-1, key)\n\n def delete_key(self, key):\n \"\"\"adapter interface for delete an element with its value\"\"\"\n if key in self.heap:\n idx = self.pos[key]\n self.delete(idx)\n del self.pos[key]\n else:\n raise ValueError(f'no such element {key} in the heap')\n\n def delete(self, i):\n if self.heap[i] > self.heap[self.heapsize-1]:\n self.heap[i] = self.heap[self.heapsize-1]\n self.max_heapify(i)\n else:\n self.increase_key_by_idx(i, self.heap[self.heapsize-1])\n del self.heap[self.heapsize-1]\n self.heapsize = self.heapsize - 1\n\n def increase_key(self, key, new_key):\n \"\"\"adapter interface for increase an element with its value\"\"\"\n if key in self.heap:\n idx = self.pos[key]\n self.increase_key_by_idx(idx, new_key)\n del self.pos[key]\n else:\n raise ValueError(f'no such element {key} in the heap')\n\n def increase_key_by_idx(self, i, key):\n \"\"\"\n increases the value of element i's key to the new value key\n \"\"\"\n if key < self.heap[i]:\n print('new key is smaller than current key')\n raise ValueError\n while i > 0 and self.heap[self.parent(i)] < key:\n self.heap[i] = self.heap[self.parent(i)]\n i = self.parent(i)\n self.heap[i] = key\n\n def maximum(self):\n return self.heap[0]\n\n def extract_max(self):\n if self.heapsize < 1:\n raise IndexError\n max_key = self.heap[0]\n self.heap[0] = self.heap[self.heapsize-1]\n del self.heap[self.heapsize-1]\n self.heapsize = self.heapsize - 1\n self.max_heapify(0)\n return max_key\n","sub_path":"BinaryHeap.py","file_name":"BinaryHeap.py","file_ext":"py","file_size_in_byte":7153,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"163577995","text":"# -*- coding: utf-8 -*-\n\n# FOGLAMP_BEGIN\n# See: http://foglamp.readthedocs.io/\n# FOGLAMP_END\n\nimport os\nfrom aiohttp import web\nfrom foglamp.services.core import connect\nfrom foglamp.common.configuration_manager import ConfigurationManager\n\n__author__ = \"Ashish Jabble\"\n__copyright__ = \"Copyright (c) 2017 OSIsoft, LLC\"\n__license__ = \"Apache 2.0\"\n__version__ = \"${VERSION}\"\n\n\n_FOGLAMP_DATA = os.getenv(\"FOGLAMP_DATA\", default=None)\n_FOGLAMP_ROOT = os.getenv(\"FOGLAMP_ROOT\", default='/usr/local/foglamp')\n\n\n_help = \"\"\"\n -------------------------------------------------------------------------------\n | GET POST | /foglamp/certificate |\n | DELETE | /foglamp/certificate/{name} |\n -------------------------------------------------------------------------------\n\"\"\"\n\n\nasync def get_certs(request):\n \"\"\" Get the list of certs\n\n :Example:\n curl -X GET http://localhost:8081/foglamp/certificate\n \"\"\"\n\n # Get certs directory path\n certs_dir = _get_certs_dir()\n total_files = []\n valid_extensions = ('.key', '.cert')\n\n for root, dirs, files in os.walk(certs_dir):\n total_files = [f for f in files if f.endswith(valid_extensions)]\n\n # Get filenames without extension\n file_names = [os.path.splitext(fname)[0] for fname in total_files]\n\n # Get unique list from file_names\n unique_list = list(set(file_names))\n\n def search_file(fname):\n # Search file with extension, if found then filename with extension else empty\n if fname in total_files:\n return fname\n return ''\n\n certs = []\n for fname in unique_list:\n cert_pair = {'key': search_file('{}.key'.format(fname)),\n 'cert': search_file('{}.cert'.format(fname))}\n certs.append(cert_pair)\n\n return web.json_response({\"certificates\": certs})\n\n\nasync def upload(request):\n \"\"\" Upload a certificate\n\n :Example:\n curl -F \"key=@filename.key\" -F \"cert=@filename.cert\" http://localhost:8081/foglamp/certificate\n curl -F \"key=@filename.key\" -F \"cert=@filename.cert\" -F \"overwrite=1\" http://localhost:8081/foglamp/certificate\n \"\"\"\n data = await request.post()\n\n # contains the name of the file in string format\n key_file = data.get('key')\n cert_file = data.get('cert')\n\n # accepted values for overwrite are '0 and 1'\n allow_overwrite = data.get('overwrite', '0')\n if allow_overwrite in ('0', '1'):\n should_overwrite = True if int(allow_overwrite) == 1 else False\n else:\n raise web.HTTPBadRequest(reason=\"Accepted value for overwrite is 0 or 1\")\n\n if not key_file or not cert_file:\n raise web.HTTPBadRequest(reason=\"key or certs file is missing\")\n\n key_filename = key_file.filename\n cert_filename = cert_file.filename\n\n # accepted extensions are '.key and .cert'\n valid_extensions = ('.key', '.cert')\n if not cert_filename.endswith(valid_extensions) or not key_filename.endswith(valid_extensions):\n raise web.HTTPBadRequest(reason=\"Accepted file extensions are .key and .cert\")\n\n # certs and key filename should match\n if cert_filename and key_filename:\n if cert_filename.split(\".\")[0] != key_filename.split(\".\")[0]:\n raise web.HTTPBadRequest(reason=\"key and certs file name should match\")\n\n # Get certs directory path\n certs_dir = _get_certs_dir()\n found_files = _find_file(cert_filename, certs_dir)\n is_found = True if len(found_files) else False\n if is_found and should_overwrite is False:\n raise web.HTTPBadRequest(reason=\"Certificate with the same name already exists. \"\n \"To overwrite set the overwrite to 1\")\n\n if key_file:\n key_file_data = data['key'].file\n key_file_content = key_file_data.read()\n key_file_path = str(certs_dir) + '/{}'.format(key_filename)\n with open(key_file_path, 'wb') as f:\n f.write(key_file_content)\n\n if cert_file:\n cert_file_data = data['cert'].file\n cert_file_content = cert_file_data.read()\n cert_file_path = str(certs_dir) + '/{}'.format(cert_filename)\n with open(cert_file_path, 'wb') as f:\n f.write(cert_file_content)\n\n # in order to bring this new cert usage into effect, make sure to\n # update config for category rest_api\n # and reboot\n return web.json_response({\"result\": \"{} and {} have been uploaded successfully\"\n .format(key_filename, cert_filename)})\n\n\nasync def delete_certificate(request):\n \"\"\" Delete a certificate\n\n :Example:\n curl -X DELETE http://localhost:8081/foglamp/certificate/foglamp\n \"\"\"\n cert_name = request.match_info.get('name', None)\n\n certs_dir = _get_certs_dir()\n cert_file = certs_dir + '/{}.cert'.format(cert_name)\n key_file = certs_dir + '/{}.key'.format(cert_name)\n\n if not os.path.isfile(cert_file) and not os.path.isfile(key_file):\n raise web.HTTPNotFound(reason='Certificate with name {} does not exist'.format(cert_name))\n\n # read config\n # if cert_name is currently set for 'certificateName' in config for 'rest_api'\n cf_mgr = ConfigurationManager(connect.get_storage_async())\n result = await cf_mgr.get_category_item(category_name='rest_api', item_name='certificateName')\n if cert_name == result['value']:\n raise web.HTTPConflict(reason='Certificate with name {} is already in use, you can not delete'\n .format(cert_name))\n\n msg = ''\n cert_file_found_and_removed = False\n if os.path.isfile(cert_file):\n os.remove(cert_file)\n msg = \"{}.cert has been deleted successfully\".format(cert_name)\n cert_file_found_and_removed = True\n\n key_file_found_and_removed = False\n if os.path.isfile(key_file):\n os.remove(key_file)\n msg = \"{}.key has been deleted successfully\".format(cert_name)\n key_file_found_and_removed = True\n\n if key_file_found_and_removed and cert_file_found_and_removed:\n msg = \"{}.key, {}.cert have been deleted successfully\".format(cert_name, cert_name)\n\n return web.json_response({'result': msg})\n\n\ndef _get_certs_dir():\n if _FOGLAMP_DATA:\n certs_dir = os.path.expanduser(_FOGLAMP_DATA + '/etc/certs')\n else:\n certs_dir = os.path.expanduser(_FOGLAMP_ROOT + '/data/etc/certs')\n\n return certs_dir\n\n\ndef _find_file(name, path):\n result = []\n for root, dirs, files in os.walk(path):\n if name in files:\n result.append(os.path.join(root, name))\n\n return result\n","sub_path":"python/foglamp/services/core/api/certificate_store.py","file_name":"certificate_store.py","file_ext":"py","file_size_in_byte":6605,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"453216287","text":"import tkinter as tk\n# 实例化窗口\nwin = tk.Tk()\n# 设置窗口标题\nwin.title(\"tk\")\n# 设置窗口大小\nwin.geometry(\"500x300\")\n# 设置第一个输入框名称和输入框\nLab1 = tk.Label(win, text=\"第一个数字\", borderwidth=10)\nLab1.grid(row=1, column=0)\nentry1 = tk.Entry(win, width=10, fg=\"black\")\nentry1.grid(row=1, column=1)\n# 设置第二个输入框名称和输入框\nLab2 = tk.Label(win, text=\"第二个数字\")\nLab2.grid(row=2, column=0)\nentry2 = tk.Entry(win, width=10, fg=\"black\")\nentry2.grid(row=2, column=1)\n\n\ndef jia():\n et1 = int(entry1.get())\n et2 = int(entry2.get())\n result = tk.Label(win, text=et1+et2)\n result.grid(row=3, column=1)\n\n\ndef jian():\n et1 = int(entry1.get())\n et2 = int(entry2.get())\n result = tk.Label(win, text=et1-et2)\n result.grid(row=3, column=2)\n\n\ndef cheng():\n et1 = int(entry1.get())\n et2 = int(entry2.get())\n result = tk.Label(win, text=et1*et2)\n result.grid(row=3, column=3)\n\n\ndef chu():\n et1 = int(entry1.get())\n et2 = int(entry2.get())\n result = tk.Label(win, text=et1/et2)\n result.grid(row=3, column=4)\n\n\n# 定义加减乘除四个按钮\nbut1 = tk.Button(win, text=\"+\", width=10, command=jia)\nbut1.grid(row=4, column=1)\n\nbut2 = tk.Button(win, text=\"-\", width=10, command=jian)\nbut2.grid(row=4, column=2)\n\nbut3 = tk.Button(win, text=\"*\", width=10, command=cheng)\nbut3.grid(row=4, column=3)\n\nbut4 = tk.Button(win, text=\"/\", width=10, command=chu)\nbut4.grid(row=4, column=4)\n\n\n\nwin.mainloop()\n","sub_path":"技能大赛试卷一/第三题.py","file_name":"第三题.py","file_ext":"py","file_size_in_byte":1495,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"326661119","text":"import jieba\nimport logging\n\nclass parse_polarity():\n\t\n\tdef __init__(self):\n\t\tlogging.basicConfig(format='%(asctime)s : %(levelname)s : %(message)s', level=logging.INFO)\n\t\t\n\t\tself.data_folder = \"./data/\"\n\t\tself.filter_punc = \",,..。!!??-()()「」『 』::、;;~~ \"\n\t\t\n\t\t# jieba custom setting.\n\t\tjieba.set_dictionary('jieba_dict/dict.txt.big')\n\n\t\t# load stopwords set\n\t\tself.stopwordset = set()\n\t\twith open('jieba_dict/stop_words.txt','r',encoding='utf-8') as sw:\n\t\t\tfor line in sw:\n\t\t\t\tself.stopwordset.add(line.strip('\\n'))\n\t\n\tdef polarity_review(self,file_name):\n\t\ttexts_num = 0\n\t\toutput = open('train_data.txt','w')\n\t\t\n\t\twith open(self.data_folder + file_name) as file:\n\t\t\tfor line in file:\n\t\t\t\tline = line.lstrip('-1')\n\t\t\t\tline = line.lstrip()\n\t\t\t\twords = jieba.cut(line, cut_all=False)\n\t\t\t\tfor word in words:\n\t\t\t\t\tif not (word in self.stopwordset or word in self.filter_punc):\n\t\t\t\t\t\toutput.write(word +' ')\n\t\t\t\ttexts_num += 1\n\t\t\t\tif texts_num % 10000 == 0:\n\t\t\t\t\tlogging.info(\"已完成前 %d 行的斷詞\" % texts_num)\n\t\toutput.close()\n\t\n\t\n\t\nif __name__ == '__main__':\n\tparser = parse_polarity()\n\tparser.polarity_review('polarity_review.txt')\n\t\n\n","sub_path":"Project1/GetTrainingData.py","file_name":"GetTrainingData.py","file_ext":"py","file_size_in_byte":1172,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"360482473","text":"\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nfrom torch.autograd import Variable\nimport torch.optim as optim\nimport torch.nn.init as weight_init\nfrom torch.nn.utils.rnn import pack_padded_sequence, pad_packed_sequence\nimport os\nimport numpy as np\nimport sys\nfrom utils_swda import gVar, gData\n\n\nclass UttEncoder(nn.Module):\n def __init__(self, embedder, input_size, hidden_size, bidirectional, n_layers, noise_radius=0.2):\n super(UttEncoder, self).__init__()\n\n self.hidden_size = hidden_size\n self.noise_radius = noise_radius\n self.n_layers = n_layers\n self.bidirectional = bidirectional\n assert type(self.bidirectional) == bool\n\n self.embedding = embedder\n self.rnn = nn.GRU(input_size, hidden_size, n_layers, batch_first=True, bidirectional=bidirectional)\n self.init_weights()\n\n def init_weights(self):\n for w in self.rnn.parameters():\n if w.dim() > 1:\n weight_init.orthogonal_(w)\n\n def store_grad_norm(self, grad):\n norm = torch.norm(grad, 2, 1)\n self.grad_norm = norm.detach().data.mean()\n return grad\n\n def forward(self, inputs, input_lens=None, noise=False):\n if self.embedding is not None:\n inputs = self.embedding(inputs)\n\n batch_size, seq_len, emb_size = inputs.size()\n inputs = F.dropout(inputs, 0.5, self.training)\n\n if input_lens is not None:\n input_lens_sorted, indices = input_lens.sort(descending=True)\n inputs_sorted = inputs.index_select(0, indices)\n inputs = pack_padded_sequence(inputs_sorted, input_lens_sorted.data.tolist(), batch_first=True)\n\n init_hidden = gVar(torch.zeros(self.n_layers * (1 + self.bidirectional), batch_size, self.hidden_size))\n hids, h_n = self.rnn(inputs, init_hidden)\n\n if input_lens is not None:\n _, inv_indices = indices.sort()\n hids, lens = pad_packed_sequence(hids, batch_first=True)\n hids = hids.index_select(0, inv_indices)\n h_n = h_n.index_select(1, inv_indices)\n h_n = h_n.view(self.n_layers, (1 + self.bidirectional), batch_size, self.hidden_size)\n h_n = h_n[-1]\n enc = h_n.transpose(1, 0).contiguous().view(batch_size, -1)\n if noise and self.noise_radius > 0:\n gauss_noise = gVar(torch.normal(means=torch.zeros(enc.size()), std=self.noise_radius))\n enc = enc + gauss_noise\n\n return enc, hids\n\n\nclass ContextEncoder(nn.Module):\n def __init__(self, utt_encoder, input_size, hidden_size, n_layers=1, noise_radius=0.2):\n super(ContextEncoder, self).__init__()\n self.hidden_size = hidden_size\n self.noise_radius = noise_radius\n\n self.n_layers = n_layers\n\n self.utt_encoder = utt_encoder\n self.rnn = nn.GRU(input_size, hidden_size, batch_first=True)\n self.init_weights()\n\n def init_weights(self):\n for w in self.rnn.parameters(): # initialize the gate weights with orthogonal\n if w.dim() > 1:\n weight_init.orthogonal_(w)\n\n def store_grad_norm(self, grad):\n norm = torch.norm(grad, 2, 1)\n self.grad_norm = norm.detach().data.mean()\n return grad\n\n def forward(self, context, context_lens, utt_lens, floors, noise=False):\n batch_size, max_context_len, max_utt_len = context.size()\n utts = context.view(-1, max_utt_len)\n utt_lens = utt_lens.view(-1)\n utt_encs, _ = self.utt_encoder(utts, utt_lens)\n utt_encs = utt_encs.view(batch_size, max_context_len, -1)\n\n floor_one_hot = gVar(torch.zeros(floors.numel(), 2))\n floor_one_hot.data.scatter_(1, floors.view(-1, 1), 1)\n floor_one_hot = floor_one_hot.view(-1, max_context_len, 2)\n utt_floor_encs = torch.cat([utt_encs, floor_one_hot], 2)\n\n utt_floor_encs = F.dropout(utt_floor_encs, 0.25, self.training)\n context_lens_sorted, indices = context_lens.sort(descending=True)\n utt_floor_encs = utt_floor_encs.index_select(0, indices)\n utt_floor_encs = pack_padded_sequence(utt_floor_encs, context_lens_sorted.data.tolist(), batch_first=True)\n\n init_hidden = gVar(torch.zeros(1, batch_size, self.hidden_size))\n hids, h_n = self.rnn(utt_floor_encs, init_hidden)\n\n _, inv_indices = indices.sort()\n h_n = h_n.index_select(1, inv_indices)\n\n enc = h_n.transpose(1, 0).contiguous().view(batch_size, -1)\n\n if noise and self.noise_radius > 0:\n gauss_noise = gVar(torch.normal(means=torch.zeros(enc.size()), std=self.noise_radius))\n enc = enc + gauss_noise\n return enc\n\n\nclass RecognitionEncoder(nn.Module):\n def __init__(self, input_size, z_size):\n super(RecognitionEncoder, self).__init__()\n self.input_size = input_size\n self.z_size = z_size\n self.fc = nn.Sequential(\n nn.Linear(input_size, z_size),\n nn.BatchNorm1d(z_size, eps=1e-05, momentum=0.1),\n nn.Tanh(),\n nn.Linear(z_size, z_size),\n nn.BatchNorm1d(z_size, eps=1e-05, momentum=0.1),\n nn.Tanh(),\n )\n self.context_to_mu = nn.Linear(z_size, z_size) # activation???\n self.context_to_logsigma = nn.Linear(z_size, z_size)\n\n self.fc.apply(self.init_weights)\n self.init_weights(self.context_to_mu)\n self.init_weights(self.context_to_logsigma)\n\n def init_weights(self, m):\n if isinstance(m, nn.Linear):\n m.weight.data.uniform_(-0.02, 0.02)\n m.bias.data.fill_(0)\n\n def forward(self, context):\n batch_size, _ = context.size()\n context = self.fc(context)\n mu = self.context_to_mu(context)\n logsigma = self.context_to_logsigma(context)\n std = torch.exp(0.5 * logsigma)\n\n epsilon = gVar(torch.randn([batch_size, self.z_size]))\n z = epsilon * std + mu\n return z, mu, logsigma\n\n\nclass Prior(nn.Module):\n def __init__(self, input_size, z_size):\n super(Prior, self).__init__()\n self.input_size = input_size\n self.z_size = z_size\n self.fc = nn.Sequential(\n nn.Linear(input_size, z_size),\n nn.BatchNorm1d(z_size, eps=1e-05, momentum=0.1),\n nn.Tanh(),\n nn.Linear(z_size, z_size),\n nn.BatchNorm1d(z_size, eps=1e-05, momentum=0.1),\n nn.Tanh(),\n )\n self.context_to_mu = nn.Linear(z_size, z_size) # activation???\n self.context_to_logsigma = nn.Linear(z_size, z_size)\n\n self.fc.apply(self.init_weights)\n self.init_weights(self.context_to_mu)\n self.init_weights(self.context_to_logsigma)\n\n def init_weights(self, m):\n if isinstance(m, nn.Linear):\n m.weight.data.uniform_(-0.02, 0.02)\n m.bias.data.fill_(0)\n\n def forward(self, context):\n batch_size, _ = context.size()\n context = self.fc(context)\n mu = self.context_to_mu(context)\n logsigma = self.context_to_logsigma(context)\n std = torch.exp(0.5 * logsigma)\n\n epsilon = gVar(torch.randn([batch_size, self.z_size]))\n z = epsilon * std + mu\n return z, mu, logsigma\n\n\nclass Decoder(nn.Module):\n def __init__(self, embedder, input_size, hidden_size, vocab_size, n_layers=1):\n super(Decoder, self).__init__()\n self.n_layers = n_layers\n self.input_size = input_size\n self.hidden_size = hidden_size\n self.vocab_size = vocab_size\n\n self.embedding = embedder\n self.rnn = nn.GRU(input_size, hidden_size, batch_first=True)\n self.out = nn.Linear(hidden_size, vocab_size)\n self.init_weights()\n\n def init_weights(self):\n initrange = 0.1\n for w in self.rnn.parameters():\n if w.dim() > 1:\n weight_init.orthogonal_(w)\n self.out.weight.data.uniform_(-initrange, initrange)\n self.out.bias.data.fill_(0)\n\n def forward(self, init_hidden, context=None, inputs=None, lens=None):\n batch_size, maxlen = inputs.size()\n if self.embedding is not None:\n inputs = self.embedding(inputs)\n if context is not None:\n repeated_context = context.unsqueeze(1).repeat(1, maxlen, 1)\n inputs = torch.cat([inputs, repeated_context], 2)\n inputs = F.dropout(inputs, 0.5, self.training)\n hids, h_n = self.rnn(inputs, init_hidden.unsqueeze(0))\n decoded = self.out(hids.contiguous().view(-1, self.hidden_size)) # reshape before linear over vocab\n decoded = decoded.view(batch_size, maxlen, self.vocab_size)\n return decoded\n\n def sampling(self, init_hidden, context, maxlen, SOS_tok, EOS_tok, mode='greedy'):\n batch_size = init_hidden.size(0)\n decoded_words = np.zeros((batch_size, maxlen), dtype=np.int)\n sample_lens = np.zeros(batch_size, dtype=np.int)\n\n decoder_input = gVar(torch.LongTensor([[SOS_tok] * batch_size]).view(batch_size, 1))\n decoder_input = self.embedding(decoder_input) if self.embedding is not None else decoder_input\n decoder_input = torch.cat([decoder_input, context.unsqueeze(1)], 2) if context is not None else decoder_input\n decoder_hidden = init_hidden.unsqueeze(0)\n for di in range(maxlen):\n decoder_output, decoder_hidden = self.rnn(decoder_input, decoder_hidden)\n decoder_output = self.out(decoder_output)\n if mode == 'greedy':\n topi = decoder_output[:, -1].max(1, keepdim=True)[1]\n elif mode == 'sample':\n topi = torch.multinomial(F.softmax(decoder_output[:, -1], dim=1), 1)\n decoder_input = self.embedding(topi) if self.embedding is not None else topi\n decoder_input = torch.cat([decoder_input, context.unsqueeze(1)],\n 2) if context is not None else decoder_input\n ni = topi.squeeze().data.cpu().numpy()\n decoded_words[:, di] = ni\n\n for i in range(batch_size):\n for word in decoded_words[i]:\n if word == EOS_tok:\n break\n sample_lens[i] = sample_lens[i] + 1\n return decoded_words, sample_lens\n\n\nclass ILVM(nn.Module):\n\n def __init__(self, config, vocab_size, PAD_token=0):\n super(ILVM, self).__init__()\n\n self.vocab_size = vocab_size\n self.maxlen = config['maxlen']\n self.clip = config['clip']\n self.temp = config['temp']\n\n self.embedder = nn.Embedding(vocab_size, config['emb_size'], padding_idx=PAD_token)\n self.utt_encoder = UttEncoder(self.embedder, config['emb_size'], config['n_hidden'],\n True, config['n_layers'], config['noise_radius'])\n\n self.context_encoder = ContextEncoder(self.utt_encoder, config['n_hidden'] * 2 + 2, config['n_hidden'], 1,\n config['noise_radius'])\n self.prior_net = Prior(config['n_hidden'], config['z_size']) # p(e|c)\n\n self.recognition_net = RecognitionEncoder(config['n_hidden']*3, config['z_size']) # q(e|c,x)\n\n self.post_generator = nn.Sequential(\n nn.Linear(config['z_size'], config['z_size']),\n nn.BatchNorm1d(config['z_size'], eps=1e-05, momentum=0.1),\n nn.ReLU(),\n nn.Linear(config['z_size'], config['z_size']),\n nn.BatchNorm1d(config['z_size'], eps=1e-05, momentum=0.1),\n nn.ReLU(),\n nn.Linear(config['z_size'], config['z_size'])\n )\n self.post_generator.apply(self.init_weights)\n\n self.prior_generator = nn.Sequential(\n nn.Linear(config['z_size'], config['z_size']),\n nn.BatchNorm1d(config['z_size'], eps=1e-05, momentum=0.1),\n nn.ReLU(),\n nn.Linear(config['z_size'], config['z_size']),\n nn.BatchNorm1d(config['z_size'], eps=1e-05, momentum=0.1),\n nn.ReLU(),\n nn.Linear(config['z_size'], config['z_size'])\n )\n self.prior_generator.apply(self.init_weights)\n\n self.decoder = Decoder(self.embedder, config['emb_size'], config['n_hidden'] + config['z_size'],\n vocab_size, n_layers=1)\n\n self.nu_net = nn.Sequential(\n nn.Linear(config['n_hidden'] + config['z_size'], config['n_hidden'] * 2),\n nn.BatchNorm1d(config['n_hidden'] * 2, eps=1e-05, momentum=0.1),\n nn.LeakyReLU(0.2),\n nn.Linear(config['n_hidden'] * 2, config['n_hidden'] * 2),\n nn.BatchNorm1d(config['n_hidden'] * 2, eps=1e-05, momentum=0.1),\n nn.LeakyReLU(0.2),\n nn.Linear(config['n_hidden'] * 2, 1), # add one non linearity\n )\n self.nu_net.apply(self.init_weights)\n\n self.optimizer_end2end_lstm = optim.SGD(list(self.context_encoder.parameters())\n + list(self.recognition_net.parameters())\n + list(self.post_generator.parameters())\n + list(self.decoder.parameters()), lr=config['lr_end2end_lstm'])\n self.optimizer_end2end_fc = optim.RMSprop(list(self.prior_net.parameters())\n + list(self.prior_generator.parameters())\n + list(self.recognition_net.parameters())\n + list(self.post_generator.parameters()), lr=config['lr_end2end_fc'])\n self.optimizer_nu = optim.RMSprop(self.nu_net.parameters(), lr=config['lr_nu'])\n\n self.lr_scheduler_end2end = optim.lr_scheduler.StepLR(self.optimizer_end2end_lstm, step_size=10, gamma=0.6)\n\n self.criterion_ce = nn.CrossEntropyLoss()\n\n def init_weights(self, m):\n if isinstance(m, nn.Linear):\n m.weight.data.uniform_(-0.02, 0.02)\n m.bias.data.fill_(0)\n\n def sample_code_post(self, x, c):\n e, _, _ = self.recognition_net(torch.cat((x, c), 1))\n z = self.post_generator(e)\n return z\n\n def sample_code_prior(self, c):\n e, _, _ = self.prior_net(c)\n z = self.prior_generator(e)\n return z\n\n def nu_forward(self, z, c):\n input = torch.cat((z, c), 1)\n return self.nu_net(input)\n\n def sample(self, context, context_lens, utt_lens, floors, repeat, SOS_tok, EOS_tok):\n self.context_encoder.eval()\n self.decoder.eval()\n\n c = self.context_encoder(context, context_lens, utt_lens, floors)\n c_repeated = c.expand(repeat, -1)\n prior_z = self.sample_code_prior(c_repeated)\n sample_words, sample_lens = self.decoder.sampling(torch.cat((prior_z, c_repeated), 1),\n None, self.maxlen, SOS_tok, EOS_tok, \"greedy\")\n return sample_words, sample_lens\n\n def adjust_lr(self):\n self.lr_scheduler_end2end.step()\n","sub_path":"dialog_switchboard/models_swda.py","file_name":"models_swda.py","file_ext":"py","file_size_in_byte":14972,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"645137792","text":"\n# coding: utf-8\n\n# In[1]:\n\n\n# rules: 4/6 different colored tokens randomly selected for the board. Player starts with 10 matching colored tokens. \n# 4 slots each hide a different colored token. Play tokens trying to match both the color and position of hidden tokens.\n# Return red token if the color and slot is a match; \n# Return white token if the color matches one of the other hidden slots but not in the current position\n# Return nothing if your token does not match any of the colors of the \n# task: Create a function that returns the correct output [White Token, Red Token, Nothing] given different inputs of pieces.\n\n\n# In[8]:\n\n\n# make the board with 4 randomly hidden tokens.\n\nboard_colors = ['ORANGE', 'YELLOW', 'GREEN', 'BLUE', 'PURPLE', 'BLACK']\nboard = []\n\nimport random\n\nwhile len(board) < 4:\n x = random.choice(board_colors)\n board.append(x)\n #board_colors.remove(x) if you want only unique colors involved\n\nprint(board)\n\n\n# In[9]:\n\n\n#wrap function in while loop that will only allow 12 turns to get the right answer\n\n# initialize token counters and turn counter\nred = 0 \nwhite = 0\nturn = 1\n\n# while (red < 5):\n# if red == 4:\n# break\n# print('You won in ' + str(turn) + ' turns')\n# elif turn == 13:\n# break\n# print('Game over. You managed to get ' + str(red) + ' correct in ' + str(turn) + ' guesses.')\n\n\n# In[10]:\n\n\n# prompt player for token selection and record it\nplayer_board = []\n\nwhile len(player_board) < 4:\n x = len(player_board)\n choice = input('Token ' + str(x+1) + ' Choice: ')\n player_board.append(choice)\n \nplayer_board = [element.upper() for element in player_board]\n\nprint(player_board)\n\n\n# In[14]:\n\n\n# return White if board contains token color somewhere in player_board\n# return None if board doesnt contain token color at all\n\nresults = []\n\nfor i in range(len(board)):\n if player_board[i] in board:\n results.append('White')\n else:\n results.append(\"None\") \n\nprint(results)\n\n\n# In[12]:\n\n\n# create new results list to update to Red if token color AND location match\n\nresults_new = []\n \nfor i in range(len(board)): \n if player_board[i] != board[i]:\n results_new.append(results[i])\n else:\n results_new.append('Red')\n\nprint(results_new)\n\n\n# In[13]:\n\n\n# based on the results in results_new determine which pegs to return for the next turn\n \nfor i in range(len(results_new)):\n if results_new[i] == 'Red':\n red += 1\n elif results_new[i] == 'White':\n white += 1\n \n# turn += 1 to update the turn counter\nfeedback = 'Based on your most recent guess, you receive ' + str(red) + ' red pegs and ' + str(white) + ' white pegs.' # 'You have ' + str(13-turn) + ' turns left.'\nprint(feedback)\n\n# } to end the while loop\n\n","sub_path":"Mastermind Function.py","file_name":"Mastermind Function.py","file_ext":"py","file_size_in_byte":2812,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"206076567","text":"def input_generator(starting_value):\n with open('day01/p01_input.txt') as f:\n for line in f.readlines():\n if line[0] == '+':\n starting_value += int(line[1:])\n else:\n starting_value -= int(line[1:])\n yield starting_value\n\nif __name__ == \"__main__\":\n\n result = 0\n result_set = set()\n generator = input_generator(result)\n\n while result not in result_set:\n try:\n if result is not None:\n print(result)\n result_set.add(result)\n result = next(generator)\n except StopIteration:\n print(\"*** StopIteration\")\n generator = input_generator(result)\n result = None\n\n print('--------')\n print(result)\n","sub_path":"day01/p02.py","file_name":"p02.py","file_ext":"py","file_size_in_byte":775,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"364587543","text":"#!/usr/bin/python\n# -*- coding: utf-8 -*-\n\n\"\"\"\n[Function Description]\n------------------------------------------------------------------------------------------------------------------------\n\n------------------------------------------------------------------------------------------------------------------------\n\"\"\"\n\nimport os\nimport time\nimport pandas as pd\nfrom particle_vtk_generate import data_process\n\n# Display all the columns of DataFrame\npd.set_option('display.max_columns', None)\n# Display all the columns of DataFrame within a single row\npd.set_option('display.width', None)\n\n\ndef cal_vtk(vtk_dir, df_diam, time_index, diam_ratio_lower):\n \"\"\"\n 读取包含所有时刻DataFrame的list,根据所要求时刻的索引定位该时刻的DataFrame\n 利用该时刻的DataFrame,生成包含单个时刻的颗粒信息的vtk文件,用于导入Paraview进行静态可视化\n \"\"\"\n # 设置VTK文件的保存路径和名称\n vtk_folder = vtk_dir\n vtk_name = r'Particles_vtk%d_%s.vtk' % (time_index, diam_ratio_lower)\n vtk_path = os.path.join(vtk_folder, vtk_name)\n # 以写入的方式('w')打开vtk文件\n vtk_file = open(vtk_path, 'w')\n # 计算颗粒数量,vtk文件参数需要(作为节点数)\n ptc_num = len(df_diam)\n\n # 编写vtk文件内容\n # 第1部分:版本声明(不重要)\n version = '# vtk DataFile Version 3.0\\n'\n # 第2部分:标题(不重要)\n title = 'Created by Zhiquan Chen\\n'\n # 第3部分:文件格式(ASCII或者BINARY)\n file_format = 'ASCII\\n'\n # 第4部分:几何拓扑结构\n dataset = 'DATASET POLYDATA\\n'\n points = '\\nPOINTS %d float' % ptc_num # 指定节点数(即颗粒数)以及数据类型(float或double)\n vtk_format = version + title + file_format + dataset + points\n # 先写入成前4个部分,物理量后面再添加进去\n print(vtk_format, file=vtk_file)\n vtk_file.close() # 必须先close!否则后面添加的数据会不全(前几行的一些数据没有添加进来或者添加不全)\n # 获取颗粒(节点)坐标信息。忽略其行索引以及列名,以空格分隔同行数据,再以append方式把数据添加到之前生成的文本文件中\n df_ptc_coor = df_diam[['ptc_x', 'ptc_y', 'ptc_z']] / 1000 # 用国际单位m\n df_ptc_coor.to_csv(vtk_path, index=False, header=False, sep=' ', mode='a')\n vtk_file.close()\n # 第5部分:物理量(2种物理量:节点上的值和单元上的值,分别用POINT_DATA和CELL_DATA表示),可以表示多个物理量\n # 物理量可以是标量(scalar),向量(vector),或者是张量(tensor)\n parameter_num = 3 # 物理量数量(如只有颗粒id、直径和速度,该值即为3)\n vtk_file = open(vtk_path, 'a') # 以添加的方式打开写入\n vtk_file.write('\\nPOINT_DATA %d' % ptc_num) # 节点数量声明\n vtk_file.write('\\nFIELD FieldData %d\\n' % parameter_num) # 节点的物理量数量声明\n # 1.添加颗粒id声明(如:‘id 1 10 int’表示1个数据为1组,共10组数据,数据类型为int)与颗粒id数据(单列)\n vtk_file.write('id 1 %d int\\n' % ptc_num)\n vtk_file.close()\n df_ptc_id = df_diam['ptc_id'].astype(int)\n df_ptc_id.to_csv(vtk_path, index=False, header=False, sep=' ', mode='a')\n vtk_file.close()\n # 2.添加颗粒直径声明(如:‘Diameter 1 10 double’表示1个数据为1组,共10组数据,数据类型为double)与颗粒直径数据(单列)\n vtk_file = open(vtk_path, 'a')\n vtk_file.write('Diameter 1 %d double\\n' % ptc_num)\n vtk_file.close()\n df_ptc_diam = df_diam['ptc_diam'] / 1000 # 用国际单位m\n df_ptc_diam.to_csv(vtk_path, index=False, header=False, sep=' ', mode='a')\n vtk_file.close()\n # 3.添加颗粒速度声明(如:‘Velocity 3 10 double’表示3个数据为1组,共10组数据,数据类型为double)与颗粒xyz方向的速度数据(共3列)\n vtk_file = open(vtk_path, 'a')\n vtk_file.write('Velocity 3 %d double\\n' % ptc_num)\n vtk_file.close()\n df_ptc_vlt = df_diam[['ptc_x_vlt', 'ptc_y_vlt', 'ptc_z_vlt']] # 用国际单位m/s\n df_ptc_vlt.to_csv(vtk_path, index=False, header=False, sep=' ', mode='a')\n vtk_file.close()\n # 输出该时刻vtk文件生成信息\n print('\"%s\" has generated' % vtk_path)\n\n\ndef diam_vtk(vtk_dir, list_data_times, time_index):\n \"\"\"\n 读取包含所有时刻DataFrame的list,根据所要求时刻的索引定位该时刻的DataFrame\n 利用该时刻的DataFrame,生成包含单个时刻的颗粒信息的vtk文件,用于导入Paraview进行静态可视化\n \"\"\"\n diam_scn = 5 # 筛孔宽度\n diam07 = diam_scn * 0.7\n diam08 = diam_scn * 0.8\n diam09 = diam_scn * 0.9\n diam10 = diam_scn * 1.0\n df_data_time = list_data_times[time_index]\n print(df_data_time)\n df_diam00 = df_data_time[df_data_time['ptc_diam'] <= diam07]\n df_diam07 = df_data_time[(df_data_time['ptc_diam'] > diam07) & (df_data_time['ptc_diam'] <= diam08)]\n df_diam08 = df_data_time[(df_data_time['ptc_diam'] > diam08) & (df_data_time['ptc_diam'] <= diam09)]\n df_diam09 = df_data_time[(df_data_time['ptc_diam'] > diam09) & (df_data_time['ptc_diam'] <= diam10)]\n df_diam10 = df_data_time[df_data_time['ptc_diam'] > diam10]\n df_diam_list = [df_diam00, df_diam07, df_diam08, df_diam09, df_diam10]\n diam_ratio_list = ['00', '07', '08', '09', '10']\n for df_diam, diam_ratio in zip(df_diam_list, diam_ratio_list):\n cal_vtk(vtk_dir, df_diam, time_index, diam_ratio)\n\n\nif __name__ == '__main__':\n # 记录程序开始时间\n start = time.time()\n\n # CSV文件所在路径\n folder_path = r'H:\\Test\\Experiment'\n file_name = r'exp019.csv'\n file_path = os.path.join(folder_path, file_name)\n # 调用data_process,处理该文件路径下的CSV文件,并输出处理好的数据\n data_times_list = data_process(file_path)\n\n # <生成单个时刻不同粒径范围的vtk>\n vtk_index = 314\n vtkfile_path = r'H:\\VibrationTrace\\EDEM_Paraview\\exp019' # vtk文件生成路径\n diam_vtk(vtkfile_path, data_times_list, vtk_index)\n\n # <统计计算时间>\n end = time.time()\n cal_time = end - start\n m, s = divmod(cal_time, 60)\n h, m = divmod(m, 60)\n print(\"\\nTotal Computing Time: %02d:%02d:%02d\" % (h, m, s))\n","sub_path":"Vibrating_Screen/visualize/EDEM_Paraview/particle_diam_vtk.py","file_name":"particle_diam_vtk.py","file_ext":"py","file_size_in_byte":6364,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"278333840","text":"import boto3\n\nec2 = boto3.client('ec2')\ncloudtrail = boto3.client('cloudtrail')\n\ndef get_user(instanceid):\n\tresponse = cloudtrail.lookup_events (\n\t\tLookupAttributes=[\n\t\t\t{\n\t\t\t\t'AttributeKey': 'ResourceName',\n\t\t\t\t'AttributeValue': instanceid\n\t\t\t}\n\t\t],\n\t)\n\treturn response\n\n\ndef get_ec2_owner(instanceid):\n\tuser_details = get_user (instanceid)\n\tfor event in user_details.get (\"Events\"):\n\t\tif event.get (\"EventName\") == \"RunInstances\":\n\t\t\treturn event.get (\"Username\")\n\n\nresponse = ec2.describe_instances (Filters=[\n\t{\n\t\t'Name': 'instance-state-name',\n\t\t'Values': ['running']\n\t}\n])\n\nfor r in response['Reservations']:\n\tfor instance in r['Instances']:\n\t\tuser = get_ec2_owner (instance['InstanceId'])\n\t\tprint (instance['InstanceId'],instance['InstanceType'],user)\n","sub_path":"ListInstanceOwner.py","file_name":"ListInstanceOwner.py","file_ext":"py","file_size_in_byte":759,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"326691039","text":"import tensorflow as tf\n\nparams1 = tf.constant([1,2,3,4])\nparams2 = tf.constant([[[1,2,3],[4,5,6]],[[7,8,9],[10,11,12]]])\nb = tf.constant(3)\nc = tf.constant([[[0, 1], [0,0]],[[1,0],[1,1]]])\n\nb1 = tf.gather(params1, b)\nb2 = tf.gather(params2, b)\nc1 = tf.gather(params1, c)\nc2 = tf.gather(params2, c)\n\nsess = tf.Session()\nc2_val = sess.run([c2])\nprint(c2_val)\n","sub_path":"examples_others/gather_function_test.py","file_name":"gather_function_test.py","file_ext":"py","file_size_in_byte":358,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"501437033","text":"from django.http import JsonResponse, HttpResponse\nfrom django.views.decorators.csrf import csrf_exempt\nfrom rest_framework.decorators import api_view\nfrom rest_framework.parsers import JSONParser\nfrom .serializers import Contact_serializers\nfrom ..models import Contact\n\n\n@csrf_exempt\ndef Contact_list(request):\n \"\"\"\n List all code snippets, or create a new snippet.\n \"\"\"\n if request.method == 'GET':\n snippets = Contact.objects.all()\n serializer = Contact_serializers(snippets, many=True)\n return JsonResponse(serializer.data, safe=False)\n\n elif request.method == 'POST':\n data = JSONParser().parse(request)\n serializer = Contact_serializers(data=data)\n if serializer.is_valid():\n serializer.save()\n return JsonResponse(serializer.data, status=201)\n return JsonResponse(serializer.errors, status=400)\n\n\n@csrf_exempt\ndef ContactView(request, pk):\n \"\"\"\n Retrieve, update or delete a code snippet.\n \"\"\"\n try:\n snippet = Contact.objects.get(pk=pk)\n except Contact.DoesNotExist:\n return HttpResponse(status=404)\n\n if request.method == 'GET':\n serializer = Contact_serializers(snippet)\n return JsonResponse(serializer.data)\n\n elif request.method == 'PUT':\n data = JSONParser().parse(request)\n serializer = Contact(snippet, data=data)\n if serializer.is_valid():\n serializer.save()\n return JsonResponse(serializer.data)\n return JsonResponse(serializer.errors, status=400)\n\n elif request.method == 'DELETE':\n snippet.delete()\n return HttpResponse(status=204)\n","sub_path":"backend/TheFoundater/contact/api/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1654,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"177068733","text":"import turtle\n\n# this is an example of a void function, a functions that does not return a value. In this\n# case the function does something useful, that is making a square.\ndef draw_square(t):\n \"\"\" The function draw_square() makes a turtle t draw a square with sides of 20 units \n long.\n \"\"\"\n for i in range(4):\n t.forward(20)\n t.left(90) \n\n# set up screen\nwn = turtle.Screen() \nwn.bgcolor(\"lightgreen\") # make the background green\n\n# set up turtle\ntess = turtle.Turtle()\ntess.color(\"hotpink\")\ntess.width(3)\n\n\n# Make a for loop that calls the function draw_square to draw five squares.\nfor i in range(5):\n tess.pendown()\n draw_square(tess)\n tess.penup()\n tess.forward(40)\n \n\nwn.mainloop() # wait for user to close window\n","sub_path":"exercise_0401.py","file_name":"exercise_0401.py","file_ext":"py","file_size_in_byte":785,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"169096677","text":"from troposphere import Template, Parameter, Ref, Base64, Tags, ec2\n\nimport template_utils as utils\nimport troposphere.autoscaling as asg\n\nt = Template()\n\nt.add_version('2010-09-09')\nt.add_description('A Mesos follower stack for the geotrellis-spark project.')\n\n#\n# Parameters\n#\nvpc_param = t.add_parameter(Parameter(\n 'VpcId', Type='String', Description='Name of an existing VPC'\n))\n\nkeyname_param = t.add_parameter(Parameter(\n 'KeyName', Type='String', Default='geotrellis-spark-test',\n Description='Name of an existing EC2 key pair'\n))\n\noffice_cidr_param = t.add_parameter(Parameter(\n 'OfficeCIDR', Type='String', Default='216.158.51.82/32',\n Description='CIDR notation of office IP addresses'\n))\n\nnotification_arn_param = t.add_parameter(Parameter(\n 'GlobalNotificationsARN', Type='String',\n Description='Physical resource ID of an AWS::SNS::Topic for notifications'\n))\n\nmesos_follower_ami_param = t.add_parameter(Parameter(\n 'MesosFollowerAMI', Type='String', Default='ami-9854cbf0',\n Description='Mesos follower AMI'\n))\n\nmesos_follower_instance_profile_param = t.add_parameter(Parameter(\n 'MesosFollowerInstanceProfile', Type='String',\n Default='MesosFollowerInstanceProfile',\n Description='Physical resource ID of an AWS::IAM::Role for the followers'\n))\n\nmesos_follower_subnet_param = t.add_parameter(Parameter(\n 'MesosFollowerSubnet', Type='CommaDelimitedList',\n Description='A list of subnets to associate with the Mesos followers'\n))\n\n#\n# Security Group Resources\n#\nmesos_follower_security_group = t.add_resource(ec2.SecurityGroup(\n 'sgMesosFollower',\n GroupDescription='Enables access to the MesosFollower',\n VpcId=Ref(vpc_param),\n SecurityGroupIngress=[\n ec2.SecurityGroupRule(IpProtocol='tcp', CidrIp=Ref(office_cidr_param),\n FromPort=p, ToPort=p)\n for p in [22, 5050, 5051]\n ] + [\n ec2.SecurityGroupRule(\n IpProtocol='tcp', CidrIp=utils.VPC_CIDR, FromPort=0, ToPort=65535\n )\n ],\n SecurityGroupEgress=[\n ec2.SecurityGroupRule(\n IpProtocol='tcp', CidrIp=utils.VPC_CIDR, FromPort=0, ToPort=65535\n )\n ] + [\n ec2.SecurityGroupRule(IpProtocol='tcp', CidrIp=utils.ALLOW_ALL_CIDR,\n FromPort=p, ToPort=p)\n for p in [80, 443]\n ],\n Tags=Tags(Name='sgMesosFollower')\n))\n\n#\n# Resources\n#\nmesos_follower_launch_config = t.add_resource(asg.LaunchConfiguration(\n 'lcMesosFollower',\n AssociatePublicIpAddress=True,\n BlockDeviceMappings=[\n {\n \"DeviceName\": \"/dev/xvdb\",\n \"VirtualName\": \"ephemeral0\"\n },\n {\n \"DeviceName\": \"/dev/xvdc\",\n \"VirtualName\": \"ephemeral1\"\n }\n ],\n ImageId=Ref(mesos_follower_ami_param),\n IamInstanceProfile=Ref(mesos_follower_instance_profile_param),\n InstanceType='i2.2xlarge',\n KeyName=Ref(keyname_param),\n SecurityGroups=[Ref(mesos_follower_security_group)],\n UserData=Base64(utils.read_file('cloud-config/follower.yml'))\n))\n\nmesos_follower_auto_scaling_group = t.add_resource(asg.AutoScalingGroup(\n 'asgMesosFollower',\n AvailabilityZones=['us-east-1%s' % utils.EC2_AVAILABILITY_ZONES[0]],\n Cooldown=300,\n DesiredCapacity=1,\n HealthCheckGracePeriod=600,\n HealthCheckType='EC2',\n LaunchConfigurationName=Ref(mesos_follower_launch_config),\n MaxSize=1,\n MinSize=1,\n NotificationConfiguration=asg.NotificationConfiguration(\n TopicARN=Ref(notification_arn_param),\n NotificationTypes=[\n asg.EC2_INSTANCE_LAUNCH,\n asg.EC2_INSTANCE_LAUNCH_ERROR,\n asg.EC2_INSTANCE_TERMINATE,\n asg.EC2_INSTANCE_TERMINATE_ERROR\n ]\n ),\n VPCZoneIdentifier=Ref(mesos_follower_subnet_param),\n Tags=[asg.Tag('Name', 'MesosFollower', True)]\n))\n\nif __name__ == '__main__':\n file_name = __file__.replace('.py', '.json')\n\n with open(file_name, 'w') as f:\n f.write(t.to_json())\n\n print('Template written to %s' % file_name)\n","sub_path":"deployment/troposphere/follower_template.py","file_name":"follower_template.py","file_ext":"py","file_size_in_byte":4039,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"336154943","text":"#!/user/bin/env python \n#-*- coding:utf-8 -*-\n\n\"\"\"样本很小,模型随时都会过拟合\"\"\"\n\nimport torch\nfrom torchvision import datasets, transforms\nfrom torch import optim, nn\nfrom torch.utils.data import DataLoader\nfrom torch.nn import functional as F\n\nimport numpy as np\nfrom matplotlib import pyplot as plt\nfrom PIL import Image\nimport time\nimport random\nimport sys\n\nfrom lenet5 import Lenet5\n\nsys.path.append(\"..\")\nimport warnings\nwarnings.filterwarnings(\"ignore\") # 忽略警告\n\nfrom visdom import Visdom\n# cmd输入 python -m visdom.server 启动\n\nviz = Visdom() # 实例化\n\nviz.line([0.], [0.], win='train_loss', opts=dict(title='train loss'))\nviz.line([[0.0, 0.0]], [0.], win='test', opts=dict(title='test loss&acc.', legend=['loss', 'acc.']))\n# 创建直线:y,x,窗口的id(environment),窗口其它配置信息\n# 复试折线图\n\n# Set the random seed manually for reproducibility.\nseed = 6666\ntorch.manual_seed(seed)\ntorch.cuda.manual_seed(seed)\ntorch.cuda.manual_seed_all(seed)\nnp.random.seed(seed) # Numpy module.\nrandom.seed(seed) # Python random module.\ntorch.manual_seed(seed)\ntorch.backends.cudnn.benchmark = False\ntorch.backends.cudnn.deterministic = True\n\n\n# 硬件参数\nnum_workers = 0 if sys.platform.startswith('win32') else 4\ndevice = torch.device('cuda' if torch.cuda.is_available() else 'cpu')\n\n\"\"\"默认图像数据目录结构\nroot\n.\n├──dog\n| ├──001.png\n| ├──002.png\n| └──...\n└──cat\n| ├──001.png\n| ├──002.png\n| └──...\n└──...\n\n拥有成员变量:\n · self.classes - 用一个list保存 类名\n · self.class_to_idx - 类名对应的 索引\n · self.imgs - 保存(img-path, class) tuple的list\n\nds = datasets.ImageFolder('./data/dogcat_2') #没有transform,先看看取得的原始图像数据\nds.classes # 根据分的文件夹的名字来确定的类别 ['cat', 'dog']\nds.class_to_idx # 按顺序为这些类别定义索引为0,1... {'cat': 0, 'dog': 1}\nds.imgs # 返回从所有文件夹中得到的图片的路径以及其类别 [('./data/dogcat_2/cat/cat.12484.jpg', 0), ('./data/dogcat_2/cat/cat.12485.jpg', 0), ...]\n\nds[0] # 第1个图片的元组\nds[0][0] # 图像Tensor数据\nds[0][1] # 得到的是类别0,即cat\n\"\"\"\n\n\n# 数据预处理\ntransform = transforms.Compose([\n # transforms.Scale(size),\n transforms.Resize((299, 299)),\n # transforms.CenterCrop((size, size)),\n # transforms.RandomRotation(0.1),\n transforms.RandomHorizontalFlip(),\n transforms.ToTensor(), # PIL Image → Tensor\n # transforms.Gray()\n])\n\n\n# 获取数据\nepochs = 25\nbatch_size = 20\nnum_classes = 12 # 类别\n# input_channel = 1\nroot = r'D:\\workspace\\dataset\\myfaces'\ntrain_ds = datasets.ImageFolder(root=root+r'\\train', transform=transform) # 得到的数据是Tensor对象\ntest_ds = datasets.ImageFolder(root=root+r'\\test', transform=transform) # 得到的数据是Tensor对象\n# print(train_ds.class_to_idx)\n# print(test_ds.class_to_idx)\nidx_to_class = {0: 'CC', 1: 'CLT', 2: 'DHH', 3: 'DJR', 4: 'DJX', 5: 'HZH', 6: 'PHS', 7: 'QC', 8: 'QOO', 9: 'ZY'}\n\n\n# img = plt.imread(path)\n# print(img.shape)\n# img = np.resize(img, (224, 224, 3))\n# img_plt = train_ds[50][0]\n# img_np = np.array(img_plt)\n# print(img_np.shape)\n# # print(train_ds[0][0][0].shape)\n# plt.imshow(img_np)\n# plt.show()\n\n\ntrain_loader = DataLoader(train_ds, batch_size=batch_size, shuffle=True, num_workers=num_workers)\ntest_loader = DataLoader(test_ds, num_workers=num_workers)\n\n\n# resnet18_0: 224 rgb\n# pretrain_model = resnet18(pretrained=True).to(device)\n# model = nn.Sequential(*list(pretrain_model.children())[:-1], # [b, 512, 1, 1]\n# Flatten(), # [b, 512, 1, 1] => [b, 512]\n# nn.Linear(512, num_classes)).to(device)\n# model_save_path = 'resnet18_0_w.mdl'\n# model_save_path = 'resnet18_0.pkl'\n\nfrom Model.face import *\n# lenet5_0: 32 rgb\ndesc = \"lenet5 32*32\"\nmodel = MyFaceNet1().to(device)\nweight_save_path = 'saveModel/myfacenet_0_w.mdl'\nmodel_save_path = 'saveModel/myfacenet_0_w.pkl'\n\n# mynet_0: 224 rgb 6层卷积\n# desc = \"6层卷积 224*224\"\n# model = Mynet0().to(device)\n# weight_save_path = 'mynet_0.mdl'\n# model_save_path = 'mynet_0.pkl'\n\n# mynet_1: 224 rgb 3层卷积\n# desc = \"3层卷积 224*224\"\n# model = Mynet1().to(device)\n# weight_save_path = 'mynet_1_w.mdl'\n# model_save_path = 'mynet_1.pkl'\n\n# model = torch.load(model_save_path)\n\n# 优化器 评价指标\nlr = 0.005\noptimizer = optim.Adam(model.parameters(), weight_decay=1e-8, lr=lr)\ncriteon = nn.CrossEntropyLoss().to(device)\n\ndef eval():\n global global_step\n model.eval()\n correct = 0\n test_loss = 0\n total = len(test_loader.dataset)\n\n for x, y in test_loader:\n # print(x.shape, y.shape) # torch.Size([1, 3, 32, 32]) torch.Size([1])\n x, y = x.to(device), y.to(device)\n with torch.no_grad():\n logits = model(x)\n pred = logits.argmax(dim=1) # [b]\n test_loss += criteon(logits, y).item()\n correct += torch.eq(pred, y).sum().float().item()\n\n viz.line([[test_loss/total, correct / total]], [global_step], win='test', update='append')\n # viz.images(x.view(-1, 3, 299, 299), win='x')\n # 创建图片:图片的tensor,\n # viz.text(str(pred.detach().cpu().numpy()), win='pred', opts=dict(title='pred'))\n return (correct, total)\n\nglobal_step = 0\n\ndef train():\n global global_step\n best_acc, best_epoch = 0, 0\n since = time.time()\n\n for epoch in range(epochs):\n print('\\nEpoch {}/{}'.format(epoch, epochs - 1))\n print('-' * 20)\n\n runing_loss, runing_corrects = 0.0, 0.0\n for batchidx, (x, y) in enumerate(train_loader):\n x, y = x.to(device), y.to(device) # x: [b, 3, 32, 32], y: [b]\n\n model.train()\n logits = model(x)\n loss = criteon(logits, y)\n\n optimizer.zero_grad()\n loss.backward()\n optimizer.step()\n\n runing_loss += loss.item() * x.size(0)\n runing_corrects += torch.sum((torch.argmax(logits.data, 1))==y.data)\n\n global_step += 1\n viz.line([loss.item()], [global_step], win='train_loss', update='append')\n # 添加数据:添加y,添加x,添加在哪里?,更新方式是末尾添加\n\n if batchidx % 10 == 0:\n print('epoch {} batch {}'.format(epoch, batchidx), 'loss:', loss.item())\n\n epoch_loss = runing_loss / len(train_loader.dataset)\n epoch_acc = runing_corrects.double() / len(train_loader.dataset)\n print('Loss: {:.4f} Acc: {:.4f}'.format(epoch_loss, epoch_acc))\n\n if epoch % 1 == 0:\n a, b = eval()\n val_acc = a/b\n print('Test: {} Acc: {}/{}'.format(epoch, a, b))\n if val_acc> best_acc:\n best_epoch = epoch\n best_acc = val_acc\n torch.save(model.state_dict(), weight_save_path)\n torch.save(model, model_save_path)\n\n time_elapsed = time.time() - since\n print('\\n\\n','*'*20,'\\nTraining complete in {:.0f}m {:.0f}s'.format(time_elapsed//60, time_elapsed%60))\n print('best test acc:', best_acc, 'best epoch:', best_epoch)\n\n\ndef mytest():\n # model =\n # weight_load_path = weight_save_path\n # weight_load_path = 'best_lenet5_0.mdl'\n # model.load_state_dict(torch.load(weight_load_path))\n print('loaded from ckpt!')\n print('Verifying... Waiting...')\n path = r'D:\\workspace\\dataset\\myfaces\\hzh1.png'\n img = Image.open(path)\n\n data = transform(img) # 3,32,32\n img_np = data.permute(1,2,0).numpy()\n plt.imshow(img_np)\n plt.show()\n # print(data.shape)\n data = torch.unsqueeze(data, 0).to(device)\n\n # data = data.permute(0, 2, 3, 1)\n with torch.no_grad():\n logits = model(data)\n probs = F.softmax(logits, dim=1)\n pred = logits.argmax(dim=1)\n print('the class to idx: {} → {}'.format(idx_to_class[pred.item()],pred.item()))\n print('The probs: ')\n for i, p in enumerate(idx_to_class.values()):\n print(p,':\\t','{:.6f}'.format(probs.cpu()[0][i].double().item()))\n print('\\nThe Result: He is', idx_to_class[pred.item()])\n\n\nif __name__ == '__main__':\n\n train()\n # mytest()\n\n\n\n\n\n# 保存\n# torch.save(model, '\\model.pkl')\n# # 加载\n# model = torch.load('\\model.pkl')","sub_path":"_ganface/shibie_train.py","file_name":"shibie_train.py","file_ext":"py","file_size_in_byte":8337,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"610810096","text":"\ndef maximizeProfit(nums):\n max_profit = 0\n min_price = nums[0]\n for i in range(1,len(nums)):\n profit = nums[i] - min_price\n if profit > max_profit:\n max_profit = profit\n if nums[i] < min_price:\n min_price = nums[i]\n return max_profit\n\ndef main():\n print(maximizeProfit([1,2,3,4,5,6,7])) # 6\n print(maximizeProfit([7,6,5,4,3,2,1])) # 0\n print(maximizeProfit([1,2,3,4,3,2,1])) # 3\n print(maximizeProfit([2,8,19,37,4,5])) # 35\n\nif __name__ == \"__main__\":\n main()","sub_path":"알고리즘 트랙(필)/1.알고리즘을 위한 자료구조/4장.자료구조의 끝판왕/미션2_주식수익 최대화.py","file_name":"미션2_주식수익 최대화.py","file_ext":"py","file_size_in_byte":530,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"132322164","text":"#!/usr/bin/python3\n\n# @Project = step_LeetCode\n# @File : 1053_Previous_Permutation_With_One_Swap\n# @Author : TCY\n# @Time : 2019/5/27 16:41\n# @Email : tangcaiyuan@hust.edu.cn\n# @Software: PyCharm\n\n\nclass Solution:\n def prevPermOpt1(self, A: List[int]) -> List[int]:\n \"\"\"i和j尽可能往后面取,同时A[i] > A[j]\"\"\"\n n = len(A)\n loc = n - 1\n for i in range(n - 1, -1, -1):\n if i > 0 and A[i - 1] > A[i]:\n loc = i - 1\n break\n loc2 = n - 1\n for i in range(loc + 1, n):\n \"\"\"找最后一个小于他的值\"\"\"\n if A[i] >= A[loc]:\n loc2 = i - 1\n break\n A[loc], A[loc2] = A[loc2], A[loc]\n return A\n","sub_path":"Weekly_Contest/Weekly_Contest_138/1053_Previous_Permutation_With_One_Swap.py","file_name":"1053_Previous_Permutation_With_One_Swap.py","file_ext":"py","file_size_in_byte":755,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"300474649","text":"from urllib import request as r\r\nfrom urllib import parse as p\r\nfrom html.parser import HTMLParser\r\nimport json\r\nimport os\r\n\r\nclass RecipeFetcher(HTMLParser):\r\n def __init__(self, recipe_list, url_list):\r\n HTMLParser.__init__(self)\r\n self.found = 0\r\n self.list_result = 0\r\n self.results = 0\r\n self.recipe_list = recipe_list\r\n self.url_list = url_list\r\n self.data_list = []\r\n \r\n #def handle_comment(self, data):\r\n #\tif \" searchResults index:0 count:\" in data:\r\n #\t\t self.found += 1\r\n \r\n def handle_starttag(self, tag, attrs):\r\n if tag == 'div' and attrs and attrs[0][0] == 'class' and attrs[0][1] == 'o-ResultCard__m-MediaBlock m-MediaBlock':\r\n self.found = 1\r\n if tag == \"a\":\r\n get_next_button = False\r\n for name, value in attrs:\r\n if name == \"href\" and self.found > 0:\r\n if \"http://www.foodnetwork.com/recipes/\" in value and value not in self.data_list:\r\n self.url_list.append(value)\r\n \r\n if get_next_button and name == \"href\": \r\n self.recipe_list.append(value)\r\n \r\n if name == \"class\" and value == \"o-Pagination__a-Button o-Pagination__a-NextButton\":\r\n get_next_button = True\r\n \r\n\r\n def handle_endtag(self, tag):\r\n if tag == 'div':\r\n self.found = 0\r\n\r\n def handle_data(self, data):\r\n pass\r\n\r\n\r\nclass RecipeParser(HTMLParser):\r\n def __init__(self):\r\n HTMLParser.__init__(self)\r\n\r\n self.recipe = {}\r\n\r\n self.ingredients = {}\r\n self.directions = {}\r\n\r\n self.key = ''\t\t\r\n self.datawrite = False\r\n\r\n self.namefound = False\r\n\r\n # time\r\n self.timefound = False\r\n\r\n\r\n # yield\r\n self.yieldfound = False\r\n\r\n # level\r\n self.levelfound = False\r\n\r\n # ingredients\r\n self.ingredientsfound = False\r\n self.ingredientssection = False\r\n self.ingredientssection_name = False\r\n\r\n self.ingredients_section_key = 'General'\r\n\r\n # directions\r\n self.directionssection_name = False\r\n self.directions_section_key = 'General'\r\n self.directionsfound = False\r\n\r\n #def handle_comment(self, data):\r\n def clear(self):\r\n self.recipe = {}\r\n\r\n self.ingredients = {}\r\n self.directions = {}\r\n\r\n self.key = ''\t\t\r\n self.datawrite = False\r\n\r\n self.namefound = False\r\n\r\n # time\r\n self.timefound = False\r\n\r\n\r\n # yield\r\n self.yieldfound = False\r\n\r\n # level\r\n self.levelfound = False\r\n\r\n # ingredients\r\n self.ingredientsfound = False\r\n self.ingredientssection = False\r\n self.ingredientssection_name = False\r\n\r\n self.ingredients_section_key = 'General'\r\n\r\n # directions\r\n self.directionssection_name = False\r\n self.directions_section_key = 'General'\r\n self.directionsfound = False\r\n \r\n def handle_starttag(self, tag, attrs):\r\n if tag == 'span' and attrs and attrs[0][0] == 'class' and attrs[0][1] == 'o-AssetTitle__a-HeadlineText':\r\n self.namefound = True\r\n self.key = 'name'\r\n self.datawrite = True\r\n\r\n # time section\r\n if tag == 'section' and attrs and attrs[0][0] == 'class' and attrs[0][1] ==\"o-RecipeInfo o-Time\":\r\n self.timefound = True\r\n \r\n if self.timefound and tag == 'dd' and attrs and attrs[0][0] == 'class' and attrs[0][1] == 'o-RecipeInfo__a-Description--Total':\r\n self.key = 'totaltime'\r\n self.datawrite = True\r\n if self.timefound and tag == 'dd' and attrs and attrs[0][0] == 'class' and attrs[0][1] == 'o-RecipeInfo__a-Description':\r\n self.key = 'activetime'\r\n self.datawrite = True\r\n\r\n # yield\r\n if tag == 'section' and attrs and attrs[0][0] == 'class' and attrs[0][1] == 'o-RecipeInfo o-Yield':\r\n self.yieldfound = True\r\n if self.yieldfound and tag == 'dd' and attrs and attrs[0][0] == 'class' and attrs[0][1] == 'o-RecipeInfo__a-Description':\r\n self.key = 'yield'\r\n self.datawrite = True\r\n\r\n # ingredients\r\n if tag == 'div' and attrs and attrs[0][0] == 'class' and attrs[0][1] == 'o-Ingredients__m-Body':\r\n self.ingredientsfound = True\r\n if self.ingredientsfound and tag == 'h6' and attrs and attrs[0][0] == 'class' and attrs[0][1] == 'o-Ingredients__a-SubHeadline':\r\n self.ingredientssection_name = True\r\n\r\n if self.ingredientsfound and tag == 'label' and attrs and attrs[0][0] == 'class' and attrs[0][1] == 'o-Ingredients__a-ListItemText':\r\n self.datawrite = True\r\n \r\n # directions\r\n if tag == 'span' and attrs and attrs[0][0] == 'class' and attrs[0][1] == 'm-Directions__a-HeadlineText':\r\n self.directionssection_name = True\r\n if tag == 'span' and attrs and attrs[0][0] == 'class' and attrs[0][1] == 'm-Directions__a-HeadlineText':\r\n self.directionssection_name = True\r\n if tag == 'div' and attrs and attrs[0][0] == 'class' and attrs[0][1] == 'o-Method__m-Body':\r\n self.directionsfound = True\r\n if self.directionsfound and tag == 'p':\r\n self.datawrite = True\r\n\r\n def handle_endtag(self, tag):\r\n if tag == 'span':\r\n self.namefound = False\r\n elif tag == 'section':\r\n self.timefound = False\r\n self.levelfound = False\r\n self.yieldfound = False\r\n elif tag == 'div':\r\n self.ingredientsfound = False\r\n self.directionsfound = False\r\n elif tag == 'ul':\r\n self.ingredientssection = False\r\n self.ingredients_section_key = 'General'\r\n elif tag == 'h3':\r\n self.directions_section_key = 'General'\r\n\r\n\r\n def handle_data(self, data):\r\n \r\n if self.datawrite and not (self.ingredientsfound or self.directionsfound):\r\n data = data.replace('\\\\n', '')\r\n data = data.replace('\\\\xc2', '')\r\n data = data.replace('\\\\xa0', '')\r\n self.recipe[self.key] = data.strip()\r\n self.datawrite = False\r\n\r\n if self.ingredientssection_name:\r\n data = data.replace('\\\\n', '')\r\n data = data.replace('\\\\xc2', '')\r\n data = data.replace('\\\\xa0', '')\r\n self.ingredients[data.strip().replace(':','')] = []\r\n self.ingredients_section_key = data.strip().replace(':','')\r\n self.ingredientssection_name = False\r\n\r\n if self.directionssection_name:\r\n data = data.replace('\\\\n', '')\r\n data = data.replace('\\\\xc2', '')\r\n data = data.replace('\\\\xa0', '')\r\n self.directions[data.strip().replace(':','')] = []\r\n self.directions_section_key = data.strip().replace(':','')\r\n self.directionssection_name = False\r\n\r\n if self.datawrite and self.ingredientsfound:\r\n data = data.replace('\\\\n', '')\r\n data = data.replace('\\\\xc2', '')\r\n data = data.replace('\\\\xa0', '')\r\n if self.ingredients_section_key not in self.ingredients.keys():\r\n self.ingredients[self.ingredients_section_key] = []\r\n self.ingredients[self.ingredients_section_key].append(data.replace(':','').strip())\r\n self.datawrite = False\r\n\r\n if self.datawrite and self.directionsfound:\r\n data = data.replace('\\\\n', '')\r\n data = data.replace('\\\\xc2', '')\r\n data = data.replace('\\\\xa0', '')\r\n if self.directions_section_key not in self.directions.keys():\r\n self.directions[self.directions_section_key] = []\r\n self.directions[self.directions_section_key].append(data.strip())\r\n self.datawrite = False\r\n\r\nquery = 'cheesecake'\r\nurl_list = ['http://www.foodnetwork.com/search/' + query + '-']\r\nrecipe_list = []\r\nparser = RecipeFetcher(url_list, recipe_list)\r\nrecipeparser = RecipeParser()\r\nrecipe_counter = 0\r\ntry:\r\n os.mkdir('./recipes/'+ query)\r\nexcept:\r\n pass\r\n\r\nwhile url_list:\r\n while url_list and len(recipe_list) < 100:\r\n url = url_list.pop(0)\r\n data = r.urlopen(url)\r\n html = data.read()\r\n parser.feed(str(html))\r\n print('loaded: ' + url)\r\n\r\n print('URLs loaded')\r\n\r\n \r\n while recipe_list:\r\n #try:\r\n url = recipe_list.pop(0)\r\n print('parsing: ' + url)\r\n data = r.urlopen(url)\r\n html = data.read()\r\n recipeparser.clear()\r\n recipeparser.feed(str(html))\r\n recipe = {}\r\n recipe['info'] = recipeparser.recipe\r\n recipe['ingredients'] = recipeparser.ingredients\r\n recipe['directions'] = recipeparser.directions\r\n \r\n to_text = json.dumps(recipe)\r\n\r\n f = open('./recipes/'+ query + '/' + query +str(recipe_counter)+'.json', 'w')\r\n \r\n f.write(to_text)\r\n f.close()\r\n recipe_counter +=1\r\n # except:\r\n # print(url, ' not found.')\r\n","sub_path":"projects/crawler/crawler.py","file_name":"crawler.py","file_ext":"py","file_size_in_byte":9259,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"360832857","text":"\"\"\" Contains the base classes for mechanical EM-style score reels.\"\"\"\n# score_reel.py\n# Mission Pinball Framework\n# Written by Brian Madden & Gabe Knuth\n# Released under the MIT License. (See license info at the end of this file.)\n\n# Documentation and more info at http://missionpinball.com/mpf\n\nimport logging\nimport time\n\nfrom collections import deque\nfrom mpf.system.device import Device\nfrom mpf.system.tasks import DelayManager\nfrom mpf.system.timing import Timing\nfrom mpf.system.config import Config\n\n\n# Known limitations of this module:\n# Assumes all score reels include a zero value\n# Assumes all score reels count up or down by one\n# Assumes all score reels map their displayed value to their stored value\n# in a 1:1 way. (i.e. value[0] displays 0, value[5] displays 5, etc.\n\n# Note, currently this module only supports \"incrementing\" reels (i.e. counting\n# up). Decrementing support will be added in the future\n\n\nclass ScoreReelController(object):\n \"\"\"The overall controller that is in charge of and manages the score reels\n in a pinball machine.\n\n The main thing this controller does is keep track of how many\n ScoreReelGroups there are in the machine and how many players there are,\n as well as maps the current player to the proper score reel.\n\n This controller is also responsible for working around broken\n ScoreReelGroups and \"stacking\" and switching out players when there are\n multiple players per ScoreReelGroup.\n\n \"\"\"\n\n def __init__(self, machine):\n self.machine = machine\n self.log = logging.getLogger(\"ScoreReelController\")\n self.log.debug(\"Loading the ScoreReelController\")\n\n self.active_scorereelgroup = None\n \"\"\"Pointer to the active ScoreReelGroup for the current player.\n \"\"\"\n self.player_to_scorereel_map = []\n \"\"\"This is a list of ScoreReelGroup objects which corresponds to player\n indexes. The first element [0] in this list is the first player (which\n is player index [0], the next one is the next player, etc.\n \"\"\"\n self.reset_queue = []\n \"\"\"List of score reel groups that still need to be reset\"\"\"\n self.queue = None\n \"\"\"Holds any active queue event queue objects\"\"\"\n\n # register for events\n\n # switch the active score reel group and reset it (if needed)\n self.machine.events.add_handler('player_turn_start',\n self.rotate_player)\n\n # receive notification of score changes\n self.machine.events.add_handler('player_score', self.score_change)\n\n # receives notifications of game starts to reset the reels\n self.machine.events.add_handler('game_starting', self.game_starting)\n\n def rotate_player(self, **kwargs):\n \"\"\"Called when a new player's turn starts.\n\n The main purpose of this method is to map the current player to their\n ScoreReelGroup in the backbox. It will do this by comparing length of\n the list which holds those mappings (`player_to_scorereel_map`) to\n the length of the list of players. If the player list is longer that\n means we don't have a ScoreReelGroup for that player.\n\n In that case it will check the tags of the ScoreReelGroups to see if\n one of them is tagged with playerX which corresponds to this player.\n If not then it will pick the next free one. If there are none free,\n then it will \"double up\" that player on an existing one which means\n the same Score Reels will be used for both players, and they will\n reset themselves automatically between players.\n \"\"\"\n\n # if our player to reel map is less than the number of players, we need\n # to create a new mapping\n if (len(self.player_to_scorereel_map) <\n len(self.machine.game.player_list)):\n self.map_new_score_reel_group()\n\n self.active_scorereelgroup = self.player_to_scorereel_map[\n self.machine.game.player.index]\n\n self.log.debug(\"Mapping Player %s to ScoreReelGroup '%s'\",\n self.machine.game.player.number,\n self.active_scorereelgroup.name)\n\n # Make sure this score reel group is showing the right score\n self.log.debug(\"Current player's score: %s\",\n self.machine.game.player.score)\n self.log.debug(\"Score displayed on reels: %s\",\n self.active_scorereelgroup.assumed_value_int)\n if (self.active_scorereelgroup.assumed_value_int !=\n self.machine.game.player.score):\n self.active_scorereelgroup.set_value(\n self.machine.game.player.score)\n\n # light up this group\n for group in self.machine.score_reel_groups:\n group.unlight()\n\n self.active_scorereelgroup.light()\n\n def map_new_score_reel_group(self):\n \"\"\"Creates a mapping of a player to a score reel group.\"\"\"\n\n # do we have a reel group tagged for this player?\n for reel_group in self.machine.score_reel_groups.items_tagged(\n \"player\" + str(self.machine.game.player.number)):\n self.player_to_scorereel_map.append(reel_group)\n self.log.debug(\"Found a mapping to add: %s\", reel_group.name)\n return\n\n # if we didn't find one, then we'll just use the first player's group\n # for all the additional ones.\n\n # todo maybe we should get fancy with looping through? Meh... we'll\n # cross that bridge when we get to it.\n\n self.player_to_scorereel_map.append(self.player_to_scorereel_map[0])\n\n def score_change(self, value, change, **kwargs):\n \"\"\"Called whenever the score changes and adds the score increase to the\n current active ScoreReelGroup.\n\n This method is the handler for the score change event, so it's called\n automatically.\n\n Args:\n score: Integer value of the new score. This parameter is ignored,\n and included only because the score change event passes it.\n change: Interget value of the change to the score.\n \"\"\"\n self.active_scorereelgroup.add_value(value=change, target=value)\n\n def game_starting(self, queue, game):\n \"\"\"Resets the score reels when a new game starts.\n\n This is a queue event so it doesn't allow the game start to continue\n until it's done.\n\n Args:\n queue: A reference to the queue object for the game starting event.\n game: A reference to the main game object. This is ignored and only\n included because the game_starting event passes it.\n \"\"\"\n self.queue = queue\n # tell the game_starting event queue that we have stuff to do\n self.queue.wait()\n\n # populate the reset queue\n self.reset_queue = []\n\n for player, score_reel_group in self.machine.score_reel_groups.iteritems():\n self.reset_queue.append(score_reel_group)\n self.reset_queue.sort(key=lambda x: x.name)\n # todo right now this sorts by ScoreGroupName. Need to change to tags\n self._reset_next_group() # kick off the reset process\n\n def _reset_next_group(self, value=0):\n # param `value` since that's what validate passes. Dunno if we need it.\n if self.reset_queue: # there's still more to reset\n next_group = self.reset_queue.pop(0)\n self.log.debug(\"Resetting ScoreReelGroup %s\", next_group.name)\n # add the handler to know when this group is reset\n self.machine.events.add_handler('scorereelgroup_' +\n next_group.name +\n '_valid', self._reset_next_group)\n next_group.set_value(value)\n\n else: # no more to reset\n # clear the event queue\n self.queue.clear()\n self.queue = None\n # remove all these handlers watching for 0\n self.machine.events.remove_handler(self._reset_next_group)\n\n\nclass ScoreReelGroup(Device):\n \"\"\"Represents a logical grouping of score reels in a pinball machine, where\n multiple individual ScoreReel object make up the individual digits of this\n group. This group also has support for the blank zero \"inserts\" that some\n machines use. This is a subclass of mpf.system.device.Device.\n \"\"\"\n config_section = 'score_reel_groups'\n collection = 'score_reel_groups'\n class_label = 'score_reel_group'\n\n @classmethod\n def device_class_init(cls, machine):\n # If we have at least one score reel group, we need a\n # ScoreReelController\n machine.score_reel_controller = ScoreReelController(machine)\n\n def __init__(self, machine, name, config, collection=None, validate=True):\n super(ScoreReelGroup, self).__init__(machine, name, config, collection,\n validate=validate)\n\n self.wait_for_valid_queue = None\n self.valid = True # Confirmed reels are showing the right values\n self.lit = False # This group has its lights on\n self.unlight_on_resync_key = None\n self.light_on_valid_key = None\n\n self.reels = []\n # A list of individual ScoreReel objects that make up this\n # ScoreReelGroup. The number of items in the list correspondis to the\n # number of digits that can be displayed. A value of `None` indicates a\n # position that is not controlled by a moving reel (like a fake ones\n # digit).\n\n # Note that this is \"backwards,\" with element 0 representing the ones\n # digit, element 1 representing the tens, etc..\n\n self.desired_value_list = []\n # A list of what values the machine desires to have the score reel\n # group set to.\n\n self.reset_pulses_per_round = 5\n # Interger value of how many \"pulses\" should be done per reset round.\n # This is used to simulate the actual mechnical resets the way a classic\n # EM machine would do it. If you watch an EM game reset, you'll notice\n # they pulse the reels in groups, like click-click-click-click-click..\n # pause.. click-click-click-click-click.. pause.. etc. Once each reel\n # gets to zero, it stops advancing.\n\n # If you don't want to emulate this behavior, set this to 0. The default\n # is 5.\n\n # TODO / NOTE: This feature is not yet implemented.\n\n self.advance_queue = deque()\n # Holds a list of the next reels that for step advances.\n\n self.jump_in_progress = False\n # Boolean attribute that is True when a jump advance is in progress.\n\n # convert self.config['reels'] from strings to objects\n for reel in self.config['reels']:\n # find the object\n\n if reel:\n reel = self.machine.score_reels[reel]\n self.reels.append(reel)\n\n self.reels.reverse() # We want our smallest digit in the 0th element\n\n # ---- temp chimes code. todo move this --------------------\n self.config['chimes'].reverse()\n\n for i in range(len(self.config['chimes'])):\n\n if self.config['chimes'][i]:\n self.machine.events.add_handler(event='reel_' +\n self.reels[\n i].name + '_advance',\n handler=self.chime,\n chime=self.config['chimes'][i])\n # ---- temp chimes code end --------------------------------\n\n # register for events\n self.machine.events.add_handler('init_phase_4',\n self.initialize)\n\n self.machine.events.add_handler('timer_tick', self.tick)\n\n # Need to hook this in case reels aren't done when ball ends\n self.machine.events.add_handler('ball_ending', self._ball_ending, 900)\n\n # ----- temp method for chime ------------------------------------\n def chime(self, chime):\n self.machine.coils[chime].pulse()\n\n # ---- temp chimes code end --------------------------------------\n\n @property\n def assumed_value_list(self):\n # List that holds the values of the reels in the group\n value_list = []\n for reel in self.reels:\n if reel:\n value_list.append(reel.assumed_value)\n # Used lambda above so this list will always lookup the latest\n else:\n value_list.append(None)\n return value_list\n\n @property\n def assumed_value_int(self):\n # Integer representation of the value we assume is shown on this\n # ScoreReelGroup. A value of -999 means the value is unknown.\n\n return self.reel_list_to_int(self.assumed_value_list)\n\n def initialize(self):\n \"\"\"Initialized the score reels by reading their current physical values\n and setting each reel's rollover reel. This is a separate method since\n it can't run int __iniit__() because all the other reels have to be\n setup first.\n \"\"\"\n self.get_physical_value_list()\n self.set_rollover_reels()\n\n def set_rollover_reels(self):\n \"\"\"Calls each reel's `_set_rollover_reel` method and passes it a\n pointer to the next higher up reel. This is how we know whether we're\n able to advance the next higher up reel when a particular reel rolls\n over during a step advance.\n \"\"\"\n for reel in range(len(self.reels)):\n if self.reels[reel] and (reel < len(self.reels) - 1):\n self.reels[reel]._set_rollover_reel(self.reels[reel + 1])\n\n def tick(self):\n \"\"\"Automatically called once per machine tick and checks to see if there\n are any jumps or advances in progress, and, if so, calls those methods.\n \"\"\"\n if self.jump_in_progress:\n self._jump_advance_step()\n elif self.advance_queue:\n self._step_advance_step()\n elif not self.valid:\n self.validate()\n\n def is_desired_valid(self, notify_event=False):\n \"\"\"Tests to see whether the machine thinks the ScoreReelGroup is\n currently showing the desired value. In other words, is the\n ScoreReelGroup \"done\" moving?\n\n Note this ignores placeholder non-controllable digits.\n\n Returns: True or False\n \"\"\"\n for i in range(len(self.reels)):\n if self.reels[i]:\n if self.assumed_value_list[i] != self.desired_value_list[i]:\n if notify_event:\n self.machine.events.post('scorereel_' +\n self.reels[i].name +\n '_resync')\n return False\n return True\n\n def get_physical_value_list(self):\n \"\"\"Queries all the reels in the group and builds a list of their actual\n current physical state, with either the value of the current switch\n or -999 if no switch is active.\n\n This method also updates each reel's physical value.\n\n Returns: List of physical reel values.\n \"\"\"\n output_list = []\n for reel in self.reels:\n if reel:\n output_list.append(reel.check_hw_switches())\n\n return output_list\n\n def validate(self, value=None):\n \"\"\"Called to validate that this score reel group is in the position\n the machine wants it to be in.\n\n If lazy or strict confirm is enabled, this method will also make sure\n the reels are in their proper physical positions.\n\n Args:\n value (ignored): This method takes an argument of `value`, but\n it's not used. It's only there because when reels post their\n events after they're done moving, they include a parameter of\n `value` which is the position they're in. So we just need to\n have this argument listed so we can use this method as an event\n handler for those events.\n \"\"\"\n\n self.log.debug(\"Checking to see if score reels are valid.\")\n\n # Can't validate until the reels are done moving. This shouldn't happen\n # but we look for it just in case.\n if self.jump_in_progress or self.advance_queue:\n return False\n\n # If any reels are set to lazy or strict confirm, we're only going to\n # validate if they've hw_confirmed\n for reel in self.reels:\n\n if (reel and\n (reel.config['confirm'] == 'lazy' or\n reel.config['confirm'] == 'strict') and\n not reel.hw_sync):\n return False # need hw_sync to proceed\n\n self.log.debug(\"Desired list: %s\", self.desired_value_list)\n self.log.debug(\"Assumed list: %s\", self.assumed_value_list)\n self.log.debug(\"Assumed integer: %s\", self.assumed_value_int)\n\n try:\n self.log.debug(\"Player's Score: %s\",\n self.machine.game.player.score)\n except:\n pass\n\n # todo if confirm is set to none, should we at least wait until the\n # coils are not energized to validate?\n\n if not self.is_desired_valid(notify_event=True):\n # FYI each reel will hw check during hw_sync, so if there's a\n # misfire that we can know about then it will be caught here\n self.machine.events.post('scorereelgroup_' + self.name + '_resync')\n self.set_value(value_list=self.desired_value_list)\n return False\n\n self.valid = True\n self.machine.events.post('scorereelgroup_' + self.name + '_valid',\n value=self.assumed_value_int)\n\n if self.wait_for_valid_queue:\n self.log.debug(\"Found a wait queue. Clearing now.\")\n self.wait_for_valid_queue.clear()\n self.wait_for_valid_queue = None\n\n return True\n\n def add_value(self, value, jump=False, target=None):\n \"\"\"Adds value to a ScoreReelGroup.\n\n You can also pass a negative value to subtract points.\n\n You can control the logistics of how these pulses are applied via the\n `jump` parameter. If jump is False (default), then this method will\n respect the proper \"sequencing\" of reel advances. For example, if the\n current value is 1700 and the new value is 2200, this method will fire\n the hundreds reel twice (to go to 1800 then 1900), then on the third\n pulse it will fire the thousands and hundreds (to go to 2000), then do\n the final two pulses to land at 2200.\n\n Args:\n value: The integer value you'd like to add to (or subtract\n from) the current value\n\n jump: Optional boolean value which controls whether the reels should\n \"count up\" to the new value in the classic EM way (jump=False)\n or whether they should just jump there as fast as they can\n (jump=True). Default is False.\n target: Optional integer that's the target for where this reel group\n should end up after it's done advancing. If this is not\n specified then the target value will be calculated based on the\n current reel positions, though sometimes this get's wonky if the\n reel is jumping or moving, so it's best to specify the target if\n you can.\n \"\"\"\n self.log.debug(\"Adding '%s' to the displayed value. Jump=%s\", value,\n jump)\n\n # As a starting point, we'll base our assumed current value of the reels\n # based on whatever the machine thinks they are. This is subject to\n # change, which is why we use our own variable here.\n current_reel_value = self.assumed_value_int\n\n if self.jump_in_progress:\n self.log.debug(\"There's a jump in progress, so we'll just change \"\n \"the target of the jump to include our values.\")\n # We'll base our desired value off whatever the reel is advancing\n # plus our value, because since there's a jump in progress we have\n # no idea where the reels are at this exact moment\n current_reel_value = self.reel_list_to_int(self.desired_value_list)\n jump = True\n\n if current_reel_value == - 999:\n self.log.debug(\"Current displayed value is unkown, \"\n \"so we're jumping to the new value.\")\n current_reel_value = 0\n jump = True\n\n # If we have a target, yay! (And thank you to whatever called this!!)\n # If not we have to use our current_reel_value as the baseline which is\n # fine, but it makes a lot of assumptions\n if target is None:\n target = current_reel_value + value\n\n elif value < 0:\n self.log.debug(\"add_value is negative, so we're subtracting this \"\n \"value. We will do this via a jump.\")\n jump = True\n\n # If we have to jump to this new value (for whatever reason), go for it\n if jump:\n self.set_value(target)\n\n # Otherwise we can do the cool step-wise advance\n else:\n self.desired_value_list = self.int_to_reel_list(target)\n self._step_advance_add_steps(value)\n\n def set_value(self, value=None, value_list=None):\n \"\"\"Resets the score reel group to display the value passed.\n\n This method will \"jump\" the score reel group to display the value\n that's passed as an it. (Note this \"jump\" technique means it will just\n move the reels as fast as it can, and nonsensical values might show up\n on the reel while the movement is in progress.)\n\n This method is used to \"reset\" a reel group to all zeros at the\n beginning of a game, and can also be used to reset a reel group that is\n confused or to switch a reel to the new player's score if multiple\n players a sharing the same reel group.\n\n Note you can choose to pass either an integer representation of the\n value, or a value list.\n\n Args:\n value: An integer value of what the new displayed value (i.e. score)\n should be. This is the default option if you only pass a single\n positional argument, e.g. `set_value(2100)`.\n value_list: A list of the value you'd like the reel group to\n display.\n \"\"\"\n\n if value is None and value_list is None:\n return # we can't do anything here if we don't get a new value\n\n if value_list is None:\n value_list = self.int_to_reel_list(value)\n\n self.log.debug(\"Jumping to %s.\", value_list)\n\n # set the new desired value which we'll use to verify the reels land\n # where we want them to.\n self.desired_value_list = value_list\n self.log.debug(\"set_value() just set DVL to: %s\",\n self.desired_value_list)\n\n self._jump_advance_step()\n\n def _jump_advance_step(self):\n # Checks the assumed values of the reels in the group, and if they're\n # off will automatically correct them.\n\n self.jump_in_progress = True\n self.valid = False\n\n if self.is_desired_valid():\n self.log.debug(\"They match! Jump is done.\")\n self._jump_advance_complete()\n return\n\n reels_needing_advance = [] # reels that need to be advanced\n num_energized = 0 # count of the number of coils currently energized\n current_time = time.time() # local reference for speed\n # loop through the reels one by one\n for i in range(len(self.reels)):\n this_reel = self.reels[i] # local reference for speed\n if this_reel:\n\n # While we're in here let's get a count of the total number\n # of reels that are energized\n if (this_reel.config['coil_inc'].\n time_when_done > current_time):\n num_energized += 1\n\n # Does this reel want to be advanced, and is it ready?\n if (self.desired_value_list[i] !=\n self.assumed_value_list[i] and\n this_reel.ready):\n\n # Do we need (and have) hw_sync to advance this reel?\n\n if (self.assumed_value_list[i] == -999 or\n this_reel.config['confirm'] == 'strict'):\n\n if this_reel.hw_sync:\n reels_needing_advance.append(this_reel)\n\n elif this_reel.ready:\n reels_needing_advance.append(this_reel)\n\n # How many reels can we advance now?\n coils_this_round = (self.config['max_simultaneous_coils'] -\n num_energized)\n\n # sort by last firing time, oldest first (so those are fired first)\n reels_needing_advance.sort(key=lambda x: x.next_pulse_time)\n\n if len(reels_needing_advance) < coils_this_round:\n coils_this_round = len(reels_needing_advance)\n\n for i in range(coils_this_round):\n reels_needing_advance[i].advance(direction=1)\n\n # Any leftover reels that don't get fired this time will get picked up\n # whenever the next reel changes state and this method is called again.\n\n def _jump_advance_complete(self):\n # Called when a jump advance routine is complete and the score reel\n # group has been validated.\n\n self.log.debug(\"Jump complete\")\n self.log.debug(\"Assumed values: %s\", self.assumed_value_list)\n self.log.debug(\"Desired values: %s\", self.desired_value_list)\n\n self.jump_in_progress = False\n\n def _step_advance_add_steps(self, value):\n # Receives an integer value, converts it to steps, adds them to the\n # step queue, and kicks off the step advance process. For example,\n # adding a value of 210 would result the following items added to the\n # advance queue: [coil_10, coil_100, coil_100]\n\n value_list = self.int_to_reel_list(value)\n\n self.log.debug(\"Will add '%s' to this reel group\", value)\n\n for position in range(len(value_list)):\n if value_list[position]:\n for num in range(value_list[position]):\n self.advance_queue.append(self.reels[position])\n\n # if there's a jump in progress we don't want to step on it, so we'll\n # just do nothing more here and _step_advance_step will be called when\n # the jump is done since we have entries in the advance queue\n if not self.jump_in_progress:\n self._step_advance_step()\n\n def _step_advance_step(self):\n # Attempts to kick off any advances that are in the advance_queue, but\n # that's not also possible. (For example, all the reels might be busy.)\n\n # todo if reel status is bad, do something\n\n if not self.advance_queue:\n self.validate()\n return\n\n self.valid = False\n\n # set our working reel to be the next one in the queue\n reel = self.advance_queue[0]\n\n # Check to see if this reel is ready. \"Ready\" depends on whether we're\n # using strict confirmation or not.\n\n # todo what if the hw is -999. Then we should return if we don't have\n # hw_sync also, right?\n\n if reel.config['confirm'] == 'strict' and not reel.hw_sync:\n return\n elif not reel.ready:\n return\n\n # is this real going to need a buddy pulse?\n self.log.debug(\"Reel: %s, Limit: %s, Current assumed value: %s\",\n reel.name, reel.config['limit_hi'], reel.assumed_value)\n if (reel.config['limit_hi'] == reel.assumed_value and\n not reel.rollover_reel_advanced):\n buddy_pulse = True\n # track that we've already ordered the buddy pulse so it doesn't\n # happen twice if this reel can't fire now for some reason\n reel.rollover_reel_advanced = True\n self.log.debug(\"Setting buddy pulse\")\n else:\n buddy_pulse = False\n\n # todo we may not need the rollover_reel_advanced tracker anymore since\n # we wrapped the reel.advance below in an if block.\n\n # remove this reel from our queue from the queue\n self.advance_queue.popleft()\n\n # try to advance the reel, We use `if` here so this code block only runs\n # if the reel accepted our advance request\n if reel.advance(direction=1):\n self.log.debug(\"Reel '%s' accepted advance\", reel.name)\n self.log.debug(\"Reels (assumed): %s\", self.assumed_value_int)\n try:\n self.log.debug(\"Score: %s\",\n self.machine.game.player.score)\n except:\n pass\n self.machine.events.post('reel_' + reel.name + \"_advance\")\n # todo should this advance event be posted here? Or by the reel?\n\n # Add the reel's buddy to the advance queue\n if buddy_pulse:\n # insert the rollover reel\n if reel.rollover_reel:\n self.advance_queue.appendleft(reel.rollover_reel)\n # run through this again now so we pulse the buddy reel\n # immediately (assuming we don't have too many pulsing\n # currently, etc.)\n self._step_advance_step()\n else:\n # whoops, we don't have a rollover reel. Yay for player!\n self.machine.events.post('scorereelgroup_' + self.name +\n '_rollover')\n\n else: # the reel did not accept the advance. Put it back in the queue\n self.advance_queue.appendleft(reel)\n self.log.debug(\"Reel '%s' rejected advance. We'll try again.\",\n reel.name)\n\n def int_to_reel_list(self, value):\n \"\"\"Converts an integer to a list of integers that represent each\n positional digit in this ScoreReelGroup.\n\n The list returned is in reverse order. (See the example below.)\n\n The list returned is customized for this ScoreReelGroup both in terms\n of number of elements and values of `None` used to represent blank\n plastic zero inserts that are not controlled by a score reel unit.\n\n For example, if you have a 5-digit score reel group that has 4\n phyiscial reels in the tens through ten-thousands position and a fake\n plastic \"0\" insert for the ones position, if you pass this method a\n value of `12300`, it will return `[None, 0, 3, 2, 1]`\n\n This method will pad shorter ints with zeros, and it will chop off\n leading digits for ints that are too long. (For example, if you pass a\n value of 10000 to a ScoreReelGroup which only has 4 digits, the\n returns list would correspond to 0000, since your score reel unit has\n rolled over.)\n\n Args:\n value: The interger value you'd like to convert.\n\n Returns:\n A list containing the values for each corresponding score reel,\n with the lowest reel digit position in list position 0.\n\n \"\"\"\n\n if value == -999:\n value = 0\n # todo hack\n\n output_list = []\n\n # convert our number to a string\n value = str(value)\n\n # pad the string with leading zeros\n value = value.zfill(len(self.reels))\n\n # slice off excess characters if the value is longer than num of reels\n\n # how many digits do we have to slice?\n trim = len(value) - len(self.reels)\n # and... slice!\n value = value[trim:]\n\n # todo if we don't do the above trim then it will just show the highest\n # digits, effective \"shifting\" the score by one. Might be a fun feature?\n\n # generate our list with one digit per item\n for digit in value:\n output_list.append(int(digit))\n\n # reverse the list so the least significant is first\n output_list.reverse()\n\n # replace fake position digits with `None`\n for i in range(len(output_list)):\n if not self.reels[i]:\n output_list[i] = None\n\n return output_list\n\n def reel_list_to_int(self, reel_list):\n \"\"\"Converts an list of integers to a single integer.\n\n This method is like `int_to_reel_list` except that it works in the\n opposite direction.\n\n The list inputted is expected to be in \"reverse\" order, with the ones\n digit in the [0] index position. Values of `None` are converted to\n zeros. For example, if you pass `[None, 0, 3, 2, 1]`, this method will\n return an integer value of `12300`.\n\n Note this method does not take into consideration how many reel\n positions are in this ScoreReelGroup. It just converts whatever you\n pass it.\n\n Args:\n value: The list containing the values for each score reel\n position.\n\n Returns:\n The resultant integer based on the list passed.\n \"\"\"\n # reverse the list so it's in normal order\n reel_list.reverse()\n output = \"\"\n\n for item in reel_list:\n if type(item) is int:\n if item == -999: # if any reels are unknown, then our int\n return -999 # is unkown too.\n else:\n output += str(item)\n elif type(item) is str and item.isdigit():\n # Just in case we have an number that's a string\n output += str(int(item)) # ensure no leading zeros\n else:\n output += \"0\"\n return int(output)\n\n def light(self, relight_on_valid=False, **kwargs):\n \"\"\"Lights up this ScoreReelGroup based on the 'light_tag' in its\n config.\n \"\"\"\n self.log.debug(\"Turning on Lights\")\n for light in self.machine.lights.items_tagged(\n self.config['lights_tag']):\n light.on()\n\n self.lit = True\n\n # Watch for these reels going out of sync so we can turn off the lights\n # while they're resyncing\n\n self.unlight_on_resync_key = self.machine.events.add_handler(\n 'scorereelgroup_' + self.name + '_resync',\n self.unlight,\n relight_on_valid=True)\n\n if relight_on_valid:\n self.machine.events.remove_handler_by_key(self.light_on_valid_key)\n\n def unlight(self, relight_on_valid=False, **kwargs):\n \"\"\"Turns off the lights for this ScoreReelGroup based on the\n 'light_tag' in its config.\n \"\"\"\n self.log.debug(\"Turning off Lights\")\n for light in self.machine.lights.items_tagged(\n self.config['lights_tag']):\n light.off()\n\n self.lit = False\n\n if relight_on_valid:\n self.light_on_valid_key = self.machine.events.add_handler(\n 'scorereelgroup_' + self.name + '_valid',\n self.light,\n relight_on_valid=True)\n else:\n self.machine.events.remove_handler_by_key(\n self.unlight_on_resync_key)\n\n def _ball_ending(self, queue=None):\n # We need to hook the ball_ending event in case the ball ends while the\n # score reel is still catching up.\n\n # only do this if this is the active group\n if self.machine.score_reel_controller.active_scorereelgroup != self:\n return\n\n if not self.valid:\n self.log.debug(\"Score reel group is not valid. Setting a queue\")\n self.wait_for_valid_queue = queue\n self.wait_for_valid_queue.wait()\n else:\n self.log.debug(\"Score reel group is valid. No queue needed.\")\n\n\nclass ScoreReel(Device):\n \"\"\"Represents an individual electro-mechanical score reel in a pinball\n machine.\n\n Multiples reels of this class can be grouped together into ScoreReelGroups\n which collectively make up a display like \"Player 1 Score\" or \"Player 2\n card value\", etc.\n\n This device class is used for all types of mechanical number reels in a\n machine, including reels that have more than ten numbers and that can move\n in multiple directions (such as the credit reel).\n \"\"\"\n\n config_section = 'score_reels'\n collection = 'score_reels'\n class_label = 'score_reel'\n\n def __init__(self, machine, name, config, collection=None, validate=True):\n super(ScoreReel, self).__init__(machine, name, config, collection,\n validate=validate)\n self.delay = DelayManager()\n\n self.rollover_reel_advanced = False\n # True when a rollover pulse has been ordered\n\n self.value_switches = []\n # This is a list with each element corresponding to a value on the\n # reel. An entry of None means there's no value switch there. An entry\n # of a reference to a switch object (todo or switch name?) means there\n # is a switch there.\n self.num_values = 0\n # The number of values on this wheel. This starts with zero, so a\n # wheel with 10 values will have this value set to 9. (This actually\n # makes sense since most (all?) score reels also have a zero value.)\n\n self.physical_value = -999\n # The physical confirmed value of this reel. This will always be the\n # value of whichever switch is active or -999. This differs from\n # `self.assumed_value` in that assumed value will make assumptions about\n # where the reel is as it pulses through values with no swithces,\n # whereas this physical value will always be -999 if there is no switch\n # telling it otherwise.\n\n # Note this value will be initialized via self.check_hw_switches()\n # below.\n\n self.hw_sync = False\n # Specifies whether this reel has verified it's positions via the\n # switches since it was last advanced.\"\"\"\n\n self.ready = True\n # Whether this reel is ready to advance. Typically used to make sure\n # it's not trying to re-fire a stuck position.\n\n self.assumed_value = -999\n self.assumed_value = self.check_hw_switches()\n # The assumed value the machine thinks this reel is showing. A value\n # of -999 indicates that the value is unknown.\n\n self.next_pulse_time = 0\n # The time when this reel next wants to be pulsed. The reel will set\n # this on its own (based on its own attribute of how fast pulses can\n # happen). If the ScoreReelController is ready to pulse this reel and\n # the value is in the past, it will do a pulse. A value of 0 means this\n # reel does not currently need to be pulsed.\n\n self.rollover_reel = None\n # A reference to the ScoreReel object of the next higher reel in the\n # group. This is used so the reel can notify its neighbor that it needs\n # to advance too when this reel rolls over.\n\n self.misfires = dict()\n # Counts the number of \"misfires\" this reel has, which is when we\n # advanced a reel to a value where we expected a switch to activate but\n # didn't receive that activation as expected. This is a dictionary with\n # the key equal to the switch position and the value is a tuple with\n # the first entry being the number of misfires this attempt, and the\n # second value being the number of misfires overall.\n\n self._destination_index = 0\n # Holds the index of the destination the reel is trying to advance to.\n\n # todo add some kind of status for broken?\n\n self.log.debug(\"Configuring score reel with: %s\", self.config)\n\n # figure out how many values we have\n # Add 1 so range is inclusive of the lower limit\n self.num_values = self.config['limit_hi'] - \\\n self.config['limit_lo'] + 1\n\n self.log.debug(\"Total reel values: %s\", self.num_values)\n\n for value in range(self.num_values):\n self.value_switches.append(self.config.get('switch_' + str(value)))\n\n @property\n def pulse_ms(self, direction=1):\n \"\"\"Returns an integer representing the number of milliseconds the coil\n will pulse for.\n\n This method is used by the jump and step advances so they know when a\n reel's coil is done firing so they can fire the next reel in the group.\n\n Args:\n direction (int, optional): Lets you specify which coil you want to\n get the time for. Default is 1 (up), but you can also specify -1 (\n down).\n\n Returns: Interger of the coil pulse time. If there is no coil for the\n direction you specify, returns 0.\n \"\"\"\n if direction == 1:\n return self.config['coil_inc'].config['pulse_ms']\n elif self.config['coil_dec']:\n return self.config['coil_dec'].config['pulse_ms']\n else:\n return 0\n\n def logical_to_physical(self, value):\n \"\"\"Converts a logical reel displayed value to what the physical switch\n value should be.\n\n For example, if a reel has switches for the 0 and 9 values, then an\n input of 0 will return 0 (since that's what the physical value should\n be for that logical value). In that case it will return 9 for an input\n of 9, but it will return -999 for any input value of 1 through 8 since\n there are no switches for those values.\n\n Note this method does not perform any physical or logical check against\n the reel's actual position, rather, it's only used to indicate what\n hardware switch value should be expected for the display value passed.\n\n Args:\n value (int): The value you want to check.\n\n Returns:\n The phsyical switch value, which is same as the input value if\n there's a switch there, or -999 if not.\n \"\"\"\n if value != -999:\n\n if self.value_switches[value]:\n return value\n else:\n return -999\n\n return -999\n\n def _set_rollover_reel(self, reel):\n # Sets this reels' rollover_reel to the object of the next higher\n # reel\n self.log.debug(\"Setting rollover reel: %s\", reel.name)\n self.rollover_reel = reel\n\n def advance(self, direction=None):\n \"\"\"Performs the coil firing to advance this reel one position (up or\n down).\n\n This method also schedules delays to post the following events:\n\n `reel__pulse_done`: When the coil is done pulsing\n `reel__ready`: When the config['repeat_pulse_time'] time is up\n `reel__hw_value`: When the config['hw_confirm_time'] time is up\n\n Args:\n direction (int, optional): If direction is 1, advances the reel\n to the next higher position. If direction is -1, advances the\n reel down one position (if the reel has a decrement coil). If\n direction is not passed, this method will compare the reel's\n `_destination_index` to its `assumed_value` and will advance it\n in the direction it needs to go if those values do not match.\n\n Returns: If this method is unable to advance the reel (either because\n it's not ready, because it's at its maximum value and does not have\n rollover capabilities, or because you're trying to advance it in a\n direction but it doesn't have a coil for that direction), it will\n return `False`. If it's able to pulse the advance coil, it returns\n `True`.\n \"\"\"\n self.log.debug(\"Received command advance Reel in direction: '%s'\",\n direction)\n\n if not direction:\n # A direction wasn't specified, but let's see if this reel wants\n # to be in another position and fire it if so\n if (self._destination_index != self.assumed_value and\n self.config['rollover']):\n direction = 1\n elif (self._destination_index < self.assumed_value and\n self.config['coil_dec']):\n direction = -1\n else: # no direction specified and everything seems ok\n return\n\n self.set_destination_value(direction)\n # above line also sets self._destination_index\n\n if self.next_pulse_time > time.time():\n # This reel is not ready to pulse again\n # Note we don't allow this to be overridden. Figure the\n # recycle time is there for a reason and we don't want to\n # potentially break an old delicate mechanism\n self.log.debug(\"Received advance request but this reel is not \"\n \"ready\")\n return False # since we didn't advance...in case anyone cares?\n\n if direction == 1:\n # Ensure we're not at the limit of a reel that can't roll over\n if not ((self.physical_value == self.config['limit_hi']) and\n not self.config['rollover']):\n self.log.debug(\"Ok to advance\")\n\n # Since we're firing, assume we're going to make it\n self.assumed_value = self._destination_index\n self.log.debug(\"+++Setting assumed value to: %s\",\n self.assumed_value)\n\n # Reset our statuses (stati?) :)\n self.ready = False\n self.hw_sync = False\n\n # fire the coil\n self.config['coil_inc'].pulse()\n\n # set delay to notify when this reel can be fired again\n self.delay.add(name='ready_to_fire',\n ms=self.config['repeat_pulse_time'],\n callback=self._ready_to_fire)\n\n self.next_pulse_time = (time.time() +\n (self.config['repeat_pulse_time'] /\n 1000.0))\n self.log.debug(\"@@@ New Next pulse ready time: %s\",\n self.next_pulse_time)\n\n # set delay to check the hw switches\n self.delay.add(name='hw_switch_check',\n ms=self.config['hw_confirm_time'],\n callback=self.check_hw_switches)\n\n return True\n\n else:\n self.log.warning(\"Received command to increment reel, but \"\n \"we're at the max limit and this reel \"\n \"cannot roll over\")\n return False\n\n # if direction is not 1 we'll assume down, but only if we have\n # the ability to decrement this reel\n elif 'coil_dec' in self.config:\n return False # since we haven't written this yet todo\n\n # todo log else error?\n\n def _pulse_done(self):\n # automatically called (via a delay) after the reel fires to post an\n # event that the reel's coil is done pulsing\n self.machine.events.post('reel_' + self.name + \"_pulse_done\")\n\n def _ready_to_fire(self):\n # automatically called (via a delay) after the reel fires to post an\n # event that the reel is ready to fire again\n self.ready = True\n self.machine.events.post('reel_' + self.name + \"_ready\")\n\n def check_hw_switches(self, no_event=False):\n \"\"\"Checks all the value switches for this score reel.\n\n This check only happens if `self.ready` is `True`. If the reel is not\n ready, it means another advance request has come in after the initial\n one. In that case then the subsequent advance will call this method\n again when after that advance is done.\n\n If this method finds an active switch, it sets `self.physical_value` to\n that. Otherwise it sets it to -999. It will also update\n `self.assumed_value` if it finds an active switch. Otherwise it leaves\n that value unchanged.\n\n This method is automatically called (via a delay) after the reel\n advances. The delay is based on the config value\n `self.config['hw_confirm_time']`.\n\n TODO: What happens if there are multiple active switches? Currently it\n will return the highest one. Is that ok?\n\n Args:\n no_event: A boolean switch that allows you to suppress the event\n posting from this call if you just want to update the values.\n\n Returns: The hardware value of the switch, either the position or -999.\n If the reel is not ready, it returns `False`.\n \"\"\"\n # check to make sure the 'hw_confirm_time' time has passed. If not then\n # we cannot trust any value we read from the switches\n if (self.config['coil_inc'].time_last_changed +\n (self.config['hw_confirm_time'] / 1000.0) <= time.time()):\n self.log.debug(\"Checking hw switches to determine reel value\")\n value = -999\n for i in range(len(self.value_switches)):\n if self.value_switches[i]: # not all values have a switch\n if self.machine.switch_controller.is_active(\n self.value_switches[i].name):\n value = i\n\n self.log.debug(\"+++Setting hw value to: %s\", value)\n self.physical_value = value\n self.hw_sync = True\n # only change this if we know where we are or can confirm that\n # we're not in the right position\n if value != -999:\n self.assumed_value = value\n\n # if value is -999, but we have a switch for the assumed value,\n # then we're in the wrong position because our hw_value should be\n # at the assumed value\n elif (self.assumed_value != -999 and\n self.value_switches[self.assumed_value]):\n self.assumed_value = -999\n\n if not no_event:\n self.machine.events.post('reel_' + self.name + \"_hw_value\",\n value=value)\n return value\n\n else:\n return False\n\n def set_destination_value(self, direction=1):\n \"\"\"Returns the integer value of the destination this reel is moving to.\n\n Args:\n direction (int, optional): The direction of the reel movement this\n method should get the value for. Default is 1 which means of 'up'.\n You can pass -1 the next lower value.\n\n Returns: The value of the destination. If the current\n `self.assumed_value` is -999, this method will always return -999\n since it doesn't know where the reel is and therefore doesn't know\n what the destination value would be.\n \"\"\"\n # We can only know if we have a destination if we know where we are\n self.log.debug(\"@@@ set_destination_value\")\n self.log.debug(\"@@@ old destination_index: %s\",\n self._destination_index)\n if self.assumed_value != -999:\n if direction == 1:\n self._destination_index = self.assumed_value + 1\n if self._destination_index > (self.num_values - 1):\n self._destination_index = 0\n if self._destination_index == 1:\n self.rollover_reel_advanced = False\n self.log.debug(\"@@@ new destination_index: %s\",\n self._destination_index)\n return self._destination_index\n elif direction == -1:\n self._destination_index = self.assumed_value - 1\n if self._destination_index < 0:\n self._destination_index = (self.num_values - 1)\n self.log.debug(\"@@@ new destination_index: %s\",\n self._destination_index)\n return self._destination_index\n else:\n self.log.debug(\"@@@ new destination_index: -999\")\n self._destination_index = -999\n return -999\n\n# The MIT License (MIT)\n\n# Copyright (c) 2013-2015 Brian Madden and Gabe Knuth\n\n# Permission is hereby granted, free of charge, to any person obtaining a copy\n# of this software and associated documentation files (the \"Software\"), to deal\n# in the Software without restriction, including without limitation the rights\n# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n# copies of the Software, and to permit persons to whom the Software is\n# furnished to do so, subject to the following conditions:\n\n# The above copyright notice and this permission notice shall be included in\n# all copies or substantial portions of the Software.\n\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n# THE SOFTWARE.\n","sub_path":"mpf/devices/score_reel.py","file_name":"score_reel.py","file_ext":"py","file_size_in_byte":53754,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"7370534","text":"# wordavg.py\n# This program calculates the average word length in a sentence entered by a user.\n\ndef main():\n\n sen = input(\"Enter your sentence: \")\n sen2 = sen.split(\" \")\n\n n = 0\n total = 0\n\n for w in sen2:\n total += len(w)\n n += 1\n\n avg = total / n\n\n print(avg)\n\nmain()\n","sub_path":"python/python-programming-zelle/wordavg.py","file_name":"wordavg.py","file_ext":"py","file_size_in_byte":306,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"62073181","text":"#!/usr/bin/env python3\r\n# -*- coding:utf-8 -*-\r\n\r\ndef myfunction(inputSTR):\r\n '''\r\n 這支程式的主要函式(「函式」就是「功能」的意思!)\r\n '''\r\n #print(\"Hello {}, {}\".format(inputSTR, \"你好\"))\r\n\r\n myName = inputSTR[:3]\r\n myID = inputSTR[4:]\r\n\r\n print(\"我的名字:{}\".format(myName))\r\n print(\"我的學號:{}\".format(myID))\r\n\r\n\r\n inputList= inputSTR.split(\" \")\r\n #print(inputSTRLIST)\r\n print(\"我的名字:{}\".format(inputList[0]))\r\n print(\"我的學號:{}\".format(inputList[1]))\r\n\r\n\r\n messageSTR = \"\"\"\r\n 「程式設計與基礎資料型態與中文構詞學」\r\n 整堂課的資訊量爆炸,在知識的海洋裡衝浪\r\n 超過癮的啊啊啊啊!\r\n \"\"\"\r\n #print(messageSTR)\r\n\r\n\r\n#程式進入點! week02.py 這支程式從這裡開始「執行」!\r\nif __name__ == \"__main__\":\r\n nameSTR = \"劉怡萱 40647012S\"\r\n\r\n myfunction(nameSTR)\r\n","sub_path":"week02/week02_40647012S.py","file_name":"week02_40647012S.py","file_ext":"py","file_size_in_byte":931,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"524769717","text":"import time\t# To calculate execution times\n\nprgStart = time.time()\t# Start Timer\n\n# Importing Keras modules for Neural Network\nfrom keras import backend\nfrom keras import metrics\nfrom keras import regularizers\nfrom keras.models import Sequential\nfrom keras.layers import Dense\nfrom keras.layers import LSTM\nfrom keras.preprocessing.text import one_hot\nfrom keras.preprocessing.sequence import pad_sequences\nfrom keras.preprocessing.text import Tokenizer\nfrom keras.layers.embeddings import Embedding\nfrom keras.preprocessing import sequence\n\n# Import logging to log model building progress\nimport logging\n\n# Import NumPy\nimport numpy as np\n\n# Miscellaneous Imports\nimport csv\nimport os\n\n# Importing Graphs File:\nfrom Graphs import *\n\n# Import PreProcessing File:\nfrom GloVePreProcessing import *\n\n# Import Evaluation Metric File:\nfrom EvaluationMetric import *\n\n\n\n'''\nParameters to Test Models:\n'''\n\n# File paths to load:\n# Training Set:\ntraining_set_path = \"/media/hduser/OS_Install/Mechanical Engineering/Sem V/Data Analytics/Project/FinalTrain.csv\"\n\n# Testing Set:\ntesting_set_path = \"/media/hduser/OS_Install/Mechanical Engineering/Sem V/Data Analytics/Project/FinalTest.csv\"\n\n# Toggle stemming: 1 -> Enable; 0 -> Disable\nstemming = 0\n\n# Toggle spell correction: 1 -> Enable; 0 -> Disable\nspell_correction = 0\n\n# Sets to consider for Training\nsets_to_train_with = [1, 2, 3, 4, 5, 6, 7, 8] # Sets 1 - 8 (All Sets)\n\n#sets_to_train_with = [1, 2, 3, 4, 5, 6] # Sets 1 - 6\n\n#sets_to_train_with = [3, 4, 5, 6] # Sets 3 - 6\n\n#sets_to_train_with = [7, 8] # Sets 7 - 8\n\n#sets_to_train_with = [1] # Set 1\n\n# Word Vector dimensions\nvector_dimensions = 100\n\n# Word2Vec model Training Window\nwindow_size = 5\n\n# Number of workers used to create the Word2Vec model\nnumber_of_workers = 2\n\n# Minimum number of times a word must be present to be\n# included in the Word2Vec model\nmin_word_count = 5\n\n# Specify name of the Word2Vec model to load\n# If no name is specified, a model is built\nWord2VecModelName = \"\"\n\n# Number of epochs for Neural Network Training\ntraining_epochs = 350\n\n# Training batch size\ntraining_batch_size = 10\n\n# Toggle normalization of labels: 1 -> Enable; 0 -> Disable\nnormalize_labels = 0\n\n\n\n'''\nLoading of Training and Testing Data:\n training_set = dataframe of training data\n testing_set = dataframe of testing data \n'''\nprint(\"Loading files..\")\n\n# Initialize file_load timer\nfile_load_start = time.time()\ntraining_set = pd.read_csv(training_set_path, header = 0, delimiter = \"\\t\", quoting = 3)\n\ntesting_set = pd.read_csv(testing_set_path, header = 0, delimiter = \"\\t\", quoting = 3)\n\n# End and display file load timer\nprint(\"Files loaded in : \",time.time()-file_load_start,\"s.\\n\")\n\n\n\n# Loading punkt tokenizer\ntokenizer = nltk.data.load('tokenizers/punkt/english.pickle')\n\n\n\n'''\nPreprocessing data to create Word2Vec Model\n'''\n# Initialize empty lists\ntraining_sentences = []\ntraining_answer_data = []\ntesting_sentences = []\ntesting_answer_data = []\t\n\n# Training Set Pre-processing\nprint(\"Training set processing..\")\n\n# Initialize Train process\nstart = time.time()\n\nfor i in sets_to_train_with:\n # Consider set by set\n set_in_consideration = training_set[training_set[\"essay_set\"] == i]\n \n for answer_in_consideration in set_in_consideration[\"essay\"]:\n # Append the sentences\n training_sentences += answer_to_sentences(answer_in_consideration, tokenizer, True)\n # Append list of words\n training_answer_data.append(answer_to_wordlist(answer_in_consideration))\n\n# End and display time to process Train set\nprint(\"Processing Done in : \",time.time()-start,\"s.\\n\")\n\n# Testing Set Pre-processing\nprint(\"Testing set processing..\")\n\n# Initialize Test process timer\nstart = time.time()\n\nfor i in sets_to_train_with:\n # Consider set by set\n set_in_consideration = testing_set[testing_set[\"essay_set\"] == i]\n\n for answer_in_consideration in set_in_consideration[\"essay\"]:\n # Append the sentences\n testing_sentences += answer_to_sentences(answer_in_consideration, tokenizer, True)\n # Append list of words\n testing_answer_data.append(answer_to_wordlist(answer_in_consideration))\n\n# End and display time to process Test set\nprint(\"Processing Done in : \",time.time()-start,\"s.\\n\")\n\n\n\n'''\nEmbedding of Train Vectors\n'''\nprint(\"Creating Embedded Train Vectors..\")\nstart = time.time()\n\n# Get the answerTrainVectors using a Average Word Vectors\nanswerTrainVectors = getAvgFeatureVecs(training_answer_data, vector_dimensions)\n\nprint(\"Embedded Train Vectors created in : \", time.time()-start,\"s.\\n\")\n\n\n\n'''\nBegin Embedding of Test Vectors\n'''\nprint(\"Creating Embedded Test Vectors..\")\nstart = time.time()\n\n# Get the answerTestVectors using a Average Word Vectors\nanswerTestVectors = getAvgFeatureVecs(testing_answer_data, vector_dimensions)\n\nprint(\"Embedded Test Vectors created in : \", time.time()-start,\"s.\\n\")\n\n\n\n'''\nExtract Train Labels set by set\n'''\ntrain_labels = []\ntest_labels = []\n\n# If the labels are to be normalized\nif(normalize_labels):\n\n # Labels normalized to form classes: 0 - 3\n for i in sets_to_train_with:\n # Traverse set by set\n set_in_consideration = training_set[training_set[\"essay_set\"] == i]\n \n # Append domain1_score as the label\n for domain1_score in set_in_consideration[\"domain1_score\"]:\n if(i==1):\n train_labels.append(round(domain1_score*0.25))\n elif(i==2):\n train_labels.append(round(domain1_score*0.5))\n elif(i==3):\n train_labels.append(round(domain1_score*1.0))\n elif(i==4):\n train_labels.append(round(domain1_score*1.0))\n elif(i==5):\n train_labels.append(round(domain1_score*0.75))\n elif(i==6):\n train_labels.append(round(domain1_score*0.75))\n elif(i==7):\n train_labels.append(round(domain1_score*0.1))\n elif(i==8):\n train_labels.append(round(domain1_score*0.05))\n\n for i in sets_to_train_with:\n # Traverse set by set\n set_in_consideration = testing_set[testing_set[\"essay_set\"] == i]\n\n # Append domain1_score as the label\n for domain1_score in set_in_consideration[\"domain1_score\"]:\n if(i==1):\n test_labels.append(round(domain1_score*0.25))\n elif(i==2):\n test_labels.append(round(domain1_score*0.5))\n elif(i==3):\n test_labels.append(round(domain1_score*1.0))\n elif(i==4):\n test_labels.append(round(domain1_score*1.0))\n elif(i==5):\n test_labels.append(round(domain1_score*0.75))\n elif(i==6):\n test_labels.append(round(domain1_score*0.75))\n elif(i==7):\n test_labels.append(round(domain1_score*0.1))\n elif(i==8):\n test_labels.append(round(domain1_score*0.05))\n\nelse:\n\n for i in sets_to_train_with:\n # Traverse set by set\n set_in_consideration = training_set[training_set[\"essay_set\"] == i]\n \n # Append domain1_score as the label\n for domain1_score in set_in_consideration[\"domain1_score\"]:\n if(i==1):\n train_labels.append(round(domain1_score))\n elif(i==2):\n train_labels.append(round(domain1_score))\n elif(i==3):\n train_labels.append(round(domain1_score))\n elif(i==4):\n train_labels.append(round(domain1_score))\n elif(i==5):\n train_labels.append(round(domain1_score))\n elif(i==6):\n train_labels.append(round(domain1_score))\n elif(i==7):\n train_labels.append(round(domain1_score))\n elif(i==8):\n train_labels.append(round(domain1_score))\n \n for i in sets_to_train_with:\n # Traverse set by set\n set_in_consideration = testing_set[testing_set[\"essay_set\"] == i]\n\n # Append domain1_score as the label\n for domain1_score in set_in_consideration[\"domain1_score\"]:\n if(i==1):\n test_labels.append(round(domain1_score))\n elif(i==2):\n test_labels.append(round(domain1_score))\n elif(i==3):\n test_labels.append(round(domain1_score))\n elif(i==4):\n test_labels.append(round(domain1_score))\n elif(i==5):\n test_labels.append(round(domain1_score))\n elif(i==6):\n test_labels.append(round(domain1_score))\n elif(i==7):\n test_labels.append(round(domain1_score))\n elif(i==8):\n test_labels.append(round(domain1_score))\n\n\n\n'''\nBuilding the Neural Network Model\n'''\n#Building the Neural Network\nprint(\"Building the Neural Network..\")\n\n# Initialize Neural Network Building timer\ns = time.time()\n\n# Set seed = 9 to ensure reproducibility\nnp.random.seed(9)\n\n# Begin Neural Network `model`\n#, kernel_regularizer=regularizers.l2(0.0001), activity_regularizer=regularizers.l1(0.0001))\n\n# Use a sequential network architecture\nmodel = Sequential()\n\n# Input Layer: 300 Input Neurons, Output = 107, Activation = Rectified Linear Units\nmodel.add(Dense(output_dim = 107, input_dim = vector_dimensions, activation = 'relu'))\n\n# Output Layer: 107 Input Neurons, Output = 61, SoftMax Function\nmodel.add(Dense(output_dim = 61, input_dim = 107, activation = 'softmax'))\n\n# Define Stochastic Gradient Descent\n# REMOVE training_batch_size\n#sgd = optimizers.SGD(lr=0.0001, decay=1e-6, momentum=0.9, nesterov=True)\n\n# Compile the Neural Network\nmodel.compile(loss = 'sparse_categorical_crossentropy', optimizer = 'sgd',metrics=[metrics.mae, metrics.categorical_accuracy, 'accuracy'])\n#model.compile(loss = 'sparse_categorical_crossentropy', optimizer = 'adam', metrics = ['accuracy'])\n#model.compile(loss = 'sparse_categorical_crossentropy', optimizer = 'adam', metrics = [metrics.mae])\n#model.compile(loss='mean_squared_error',optimizer='sgd',metrics=[metrics.mae, metrics.categorical_accuracy])\n\n# Neural Network building is complete\nprint(\"Neural Network built in : \",time.time()-s,\"s.\\n\")\n\n\n\n'''\nTraining the Neural Network Model\n'''\n# Begin training, initialize Training Timer\nprint(\"Training the Neural Network..\")\ns = time.time()\n\nprint(\"Train Lables: \", len(train_labels))\n\n# Fit the model on the training data\nmodel.fit(answerTrainVectors, np.asarray(train_labels), epochs = training_epochs, batch_size = training_batch_size)\n#model.fit(tfidfTrainVectors, np.asarray(train_labels), epochs = training_epochs, batch_size = training_batch_size)\n\n# Evaluation of the Model\nscores = model.evaluate(answerTrainVectors, np.asarray(train_labels))\n\n# Print log messages\nprint(\"\\n%s: %.2f%%\" % (model.metrics_names[1], scores[1]*100))\n\n# End training, and print training time\nprint(\"Neural Network trained in : \",time.time()-s,\"s.\\n\")\n\n# Testing the Model\nprediction = model.predict(answerTestVectors)\n\n# Getting the value of the class from SoftMax layer\nactual_predictions = []\n\n# Find position at which the maximum value occured in the vector\n# the same purpose as argmax()\nfor i in range(0,len(prediction)):\n # Set maxi to a low value of -9 initially\n maxi = -9\n pos = 0\n\n # Traverse the output of the SoftMax Layer\n for j in range(0, len(prediction[i])):\n\n # If value > current_maximum\n if(prediction[i][j] > maxi):\n # current_maximum = value\n maxi = prediction[i][j]\n # Set position to position where max occured\n pos = j\n\n # Append true value of score\n actual_predictions.append(pos)\n\n# Compute Quadratic Weighted Kappa for test labels\nqwk_score = quadratic_weighted_kappa(np.asarray(test_labels), actual_predictions)\n\n# Display Quadratic Weighter Kappa Value for current model\nprint(\"Quadratic Weighted Kappa with Deep Neural Network: \", qwk_score, \"\\n\\n\\n\")\n\n# Plotting graph\nplot_error(test_labels, actual_predictions, str(\"GloVe Neural Network with \"+str(vector_dimensions)+\"D Vectors\"))","sub_path":"models/GloVeNeuralNetwork.py","file_name":"GloVeNeuralNetwork.py","file_ext":"py","file_size_in_byte":12178,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"488587982","text":"import tempfile\nimport os\n\nfrom unittest import TestCase\n\nfrom leryan.types.simpleconf import *\n\n\nclass SimpleConfTest(TestCase):\n\n @classmethod\n def setUp(cls):\n cls.iniconf = u\"\"\"[sec1]\nk1 = val\nk2 = 2\n\n[sec2]\nk1 = v\nk2 = 3\"\"\"\n\n cls.iniconf_interp = u\"\"\"[vars]\nv1 = val\nv2 = 2\nv3 = 3\nv4 = v\n\n[sec1]\nk1 = ${vars:v1}\nk2 = ${vars:v2}\n\n[sec2]\nk1 = ${vars:v4}\nk2 = ${vars:v3}\"\"\"\n\n cls.jsonconf = u'{\"sec1\": {\"k1\": \"val\", \"k2\": \"2\"}, \"sec2\": {\"k1\": \"v\", \"k2\": \"3\"}}'\n\n cls.yamlconf = u\"\"\"sec1:\n k1: \"val\"\n k2: '2'\nsec2:\n k1: \"v\"\n k2: '3'\"\"\"\n\n def _check_conf(self, sc):\n self.assertEqual(sc.sec1.k1, 'val')\n self.assertEqual(sc.sec1.k2, '2')\n self.assertEqual(sc.sec2.k1, 'v')\n self.assertEqual(sc.sec2.k2, '3')\n self.assertEqual(sc['sec1']['k1'], 'val')\n self.assertEqual(sc['sec1']['k2'], '2')\n self.assertEqual(sc['sec2']['k1'], 'v')\n self.assertEqual(sc['sec2']['k2'], '3')\n\n def _open_fd_check_conf(self, sconf, driver_cls, func_check_conf, *args, **kwargs):\n fd, name = tempfile.mkstemp()\n os.write(fd, sconf.encode('utf-8'))\n os.close(fd)\n\n exception = None\n\n try:\n with open(name, 'r') as fh:\n sc = SimpleConf.export(driver_cls(fh=fh, *args, **kwargs))\n func_check_conf(sc)\n\n except Exception as ex:\n exception = ex\n\n finally:\n os.unlink(name)\n\n if exception is not None:\n raise exception\n\n def test_ini_fh(self):\n self._open_fd_check_conf(self.iniconf, Ini, self._check_conf)\n\n def test_ini_interpolate_fh(self):\n self._open_fd_check_conf(\n self.iniconf_interp, Ini, self._check_conf, with_interpolation=True)\n\n def test_ini_str(self):\n sc = SimpleConf.export(Ini(sconf=self.iniconf))\n self._check_conf(sc)\n\n def test_yaml_str(self):\n sc = SimpleConf.export(Yaml(sconf=self.yamlconf))\n self._check_conf(sc)\n\n def test_json_fh(self):\n self._open_fd_check_conf(self.jsonconf, Json, self._check_conf)\n","sub_path":"python-leryan.types/test/test_simpleconf.py","file_name":"test_simpleconf.py","file_ext":"py","file_size_in_byte":2108,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"467709475","text":"import numpy as np\nfrom prettytable import PrettyTable\n\ndef read_files(floc):\n f = open(floc, 'r')\n lines = f.readlines()\n data = np.zeros([81,81])\n for l in lines:\n l = l.strip().split()\n data[int(l[0])-1,int(l[1])-1] = float(l[2])\n f.close()\n return data\n\ndef read_rewards(floc):\n f = open(floc, 'r')\n lines = f.readlines()\n data = np.zeros([81])\n for i,l in enumerate(lines):\n l = l.strip().split()\n data[i] = int(l[0])\n f.close()\n return data\n\ndef value_iteration():\n pl = [p_a1, p_a2, p_a3, p_a4]\n for i in range(1000):\n for s in range(81):\n m_vals = []\n for p in pl:\n s_val = 0.0\n for sd in range(81):\n s_val += p[s][sd] * v_pi[sd]\n m_vals.append(gamma * s_val)\n v_pi[s] = max(rw[s] + m_vals)\n return v_pi\n\ndef cal_vp(p):\n temp = np.zeros([81,81])\n d = {0:p_a1, 1:p_a2, 2:p_a3, 3:p_a4}\n for i in range(81):\n for j in range(81):\n pol = d[int(p[i])]\n temp[i][j] = -gamma * pol[i][j]\n temp[i][i] += 1\n inv = np.linalg.inv(temp)\n vs = np.dot(inv, rw.reshape([81, 1]))\n return vs\n\ndef policy_iteration():\n p = np.ones([81])\n vp_old = np.zeros([81])\n v = np.ones([81])\n pl = [p_a1, p_a2, p_a3, p_a4]\n for i in range(10):\n if not np.allclose(vp_old,v,atol=0.01):\n vp_old = v\n v = cal_vp(p)\n for s in range(81):\n m_vals = []\n for p_l in pl:\n s_val = 0.0\n for sd in range(81):\n s_val += p_l[s][sd] * v[sd]\n m_vals.append(s_val[0])\n p[s] = np.argmax([m_vals])\n return v, p\n\n\np_a1l = '/Users/chhaviyadav/Desktop/HW_2020_Fall/250A/hw9/prob_a1.txt'\np_a2l= '/Users/chhaviyadav/Desktop/HW_2020_Fall/250A/hw9/prob_a2.txt'\np_a3l = '/Users/chhaviyadav/Desktop/HW_2020_Fall/250A/hw9/prob_a3.txt'\np_a4l = '/Users/chhaviyadav/Desktop/HW_2020_Fall/250A/hw9/prob_a4.txt'\nrwl = '/Users/chhaviyadav/Desktop/HW_2020_Fall/250A/hw9/rewards.txt'\n\np_a1 = read_files(p_a1l)\np_a2 = read_files(p_a2l)\np_a3 = read_files(p_a3l)\np_a4 = read_files(p_a4l)\nrw = read_rewards(rwl)\nv_pi = np.zeros([81])\ngamma = 0.99\nv1 = value_iteration()\nv,p = policy_iteration()\n\n\nd = {0:u'\\u2190',1:u'\\u2191',2:u'\\u2192',3:u'\\u2193'}\n\nt = PrettyTable(['state','V','action'])\nfor i in range(81):\n t.add_row([i+1,v[i][0],d[p[i]]])\nprint(t)\n\n","sub_path":"hw_9.py","file_name":"hw_9.py","file_ext":"py","file_size_in_byte":2508,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"338714321","text":"import hashlib\nimport logging\nfrom sanic import Blueprint\nfrom sanic.response import json\nfrom sanic.exceptions import InvalidUsage, ServerError\nfrom tao.models import AllUser, Permission\nfrom tao.utils import jsonify\nfrom bson import ObjectId\nfrom functools import reduce\n\n\nuser_bp = Blueprint('users')\n\n\ndef hash_psd(psd):\n md5 = hashlib.md5()\n md5.update(psd.encode(\"utf8\"))\n secret = md5.hexdigest()\n return secret\n\n\n@user_bp.post('/api/v1/regedit')\nasync def regedit(request):\n \"\"\"注册\"\"\"\n user_name = request.json.get('username')\n psd = request.json.get('password')\n phone = request.json.get('phone')\n sex = request.json.get('sex')\n try:\n result = await AllUser.find_one({'user_name': user_name})\n if not result:\n # 对密码进行加密处理\n secret = hash_psd(psd)\n # 数据存储\n user = AllUser()\n user.user_name = user_name\n user.password = secret\n user.phone = phone\n user.sex = sex\n role = await Permission.find_one({'order': 0})\n user.user_label = role['_id']\n await user.save()\n logging.info(result)\n return json(jsonify({'success': '注册成功'}))\n else:\n raise InvalidUsage('用户已存在')\n except Exception as e:\n logging.info(e)\n raise InvalidUsage('系统错误')\n\n\n@user_bp.post('/api/v1/login')\nasync def login(request):\n \"\"\"登录\"\"\"\n user_name = request.json.get('username')\n psd = request.json.get('password')\n result = await AllUser.find_one({'user_name': user_name})\n # 密码加密\n if result:\n secret = hash_psd(psd)\n user_label = result.get('user_label', 0xff)\n role = await Permission.find_one({'_id': user_label})\n if result['password'] == secret:\n logging.info(role.get('permission', 0xff))\n return json(jsonify({'username': user_name, 'role': reduce(lambda x,y:x+y, role.get('permission', 0xff))}))\n else:\n raise InvalidUsage('密码或用户名错误')\n raise InvalidUsage('用户不存在')\n\n\n@user_bp.get('/api/v1/logout')\nasync def logout(request):\n return json(jsonify({'statute': '成功登出'}))\n\n\n@user_bp.post('api/v1/change_profile')\nasync def change_profile(request):\n \"\"\"修改个人资料\"\"\"\n\n\n@user_bp.get('api/v1/users')\nasync def get_user(request):\n result = [user async for user in AllUser.find({})]\n users = []\n for record in result:\n role_id = record.get('user_label', 0)\n role = await Permission.find_one({'_id': role_id})\n role_sum = reduce(lambda x,y:x+y, role['permission'])\n if role_sum == 3:\n user = {\n '_id': record.get('_id', None),\n 'username': record.get('user_name', '未命名'),\n 'phone': record.get('phone', ''),\n 'role': role.get('role', ''),\n 'sex': record.get('sex', 1)\n }\n users.append(user)\n\n return json(jsonify({'users': users, 'total': len(users)}))\n\n\n@user_bp.put('api/v1/user')\nasync def change_user(request):\n id_ = request.json.get('_id')\n\n user_name = request.json.get('username')\n psd = request.json.get('phone')\n sex = request.json.get('sex')\n role = request.json.get('role')\n\n if not id_:\n raise InvalidUsage('无效的请求参数!')\n\n fqdn = request.json.get('fqdn', '').strip()\n ip = request.json.get('ip', '').strip()\n #\n\n return json({})\n\n\n@user_bp.put('api/v1/add_user')\nasync def add_user(request):\n \"\"\"管理员添加用户\"\"\"\n user_name = request.json.get('username')\n psd = request.json.get('phoneNum')\n sex = request.json.get('sex')\n role = request.json.get('role')\n try:\n result = await AllUser.find_one({'user_name': user_name})\n if not result:\n secret = hash_psd(psd)\n logging.info(secret)\n user = AllUser()\n user.user_name = user_name\n user.phone = psd\n user.password = secret,\n user.sex = sex\n result = await user.save()\n logging.info(result)\n return json(jsonify({'success': '注册成功'}))\n else:\n raise InvalidUsage('用户已存在')\n except Exception as e:\n logging.info(e)\n\n\n","sub_path":"src/tao/web/api/user.py","file_name":"user.py","file_ext":"py","file_size_in_byte":4366,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"515742259","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\nimport argparse\nimport os\nimport shutil\nimport sys\nfrom array import array\n\nimport EnvManager\nimport utility\nfrom ROOT import (gROOT, gStyle,\n TCanvas, TGraph, TLatex,\n kRed)\n\n#_______________________________________________________________________________\nif __name__ == '__main__':\n gROOT.Reset()\n EnvManager.Load()\n parser = argparse.ArgumentParser()\n parser.add_argument('src_num', type=int, nargs='?', default=57,\n help='run number of source')\n parser.add_argument('dst_num', type=int)\n parsed, unpased = parser.parse_known_args()\n src_num = '{0:05d}'.format(parsed.src_num)\n dst_num = '{0:05d}'.format(parsed.dst_num)\n src = '{0}/analyzer_{1}.conf'.format(EnvManager.conf_dir,\n src_num)\n dst = '{0}/analyzer_{1}.conf'.format(EnvManager.conf_dir,\n dst_num)\n if os.path.exists(dst):\n utility.ExitFailure('{0} already exists'.format(dst))\n buf = ''\n if not os.path.isfile(src):\n utility.ExitFailure('No such file: ' + src)\n with open(src, 'r') as f:\n for line in f.read().split('\\n'):\n if src_num in line:\n buf += line.replace(src_num, dst_num) + '\\n'\n else:\n buf += line + '\\n'\n # print(buf)\n with open(dst, 'w') as f:\n f.write(buf)\n for l in buf.split('\\n'):\n p = l.split()\n if len(p)<2 or '#' in p[0] or not 'param' in p[1]:\n continue\n if os.path.isfile(p[1]):\n pass\n else:\n shutil.copy2(p[1].replace(dst_num, src_num), p[1])\n print('copy ' + p[1])\n","sub_path":"MakeConf.py","file_name":"MakeConf.py","file_ext":"py","file_size_in_byte":1620,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"363633051","text":"# these should be the only imports you need\n\nimport requests\nfrom bs4 import BeautifulSoup\n\n# write your code here\n# usage should be python3 part3.py\n\n#Grab the html content\nresponse = requests.get('https://www.michigandaily.com/')\nsoup = BeautifulSoup(response.text, 'html.parser')\n\n#parse through it\nmost_read = soup.find('div', class_='panel-pane pane-mostread')\narticles = most_read.find_all(\"a\")\narticle_names = []\narticle_links = []\nfor article in articles:\n article_names.append(article.text)\n article_links.append(\"http://www.michigandaily.com\" + article.get('href'))\nauthors = []\nfor article in article_links:\n request2 = requests.get(article)\n more_soup = BeautifulSoup(request2.text, 'html.parser')\n try:\n author = more_soup.find('div', class_='byline').find_next('a').text\n authors.append(author)\n except:\n authors.append(\"DAILY STAFF WRITER\")\n\n#print it all out\nprint(\"Michigan Daily -- MOST READ\")\nfor i in range(0, len(article_names)):\n print(article_names[i])\n print(\" by \" + authors[i])\n","sub_path":"part3.py","file_name":"part3.py","file_ext":"py","file_size_in_byte":1050,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"197193534","text":"import sys\nimport subprocess\nimport shutil\nimport os\n\ndef copy_recursively(source_folder, destination_folder):\n\tsource_folder = os.path.abspath(source_folder)\n\tdestination_folder = os.path.abspath(destination_folder)\n\n\tfor root, dirs, files in os.walk(source_folder):\n\t for item in files:\n\t src_path = os.path.join(root, item)\n\t dst_path = destination_folder + src_path.replace(source_folder, \"\")\n\t if os.path.exists(dst_path):\n\t if os.stat(src_path).st_mtime > os.stat(dst_path).st_mtime:\n\t shutil.copy2(src_path, dst_path)\n\t else:\n\t shutil.copy2(src_path, dst_path)\n\t for item in dirs:\n\t src_path = os.path.join(root, item)\n\t dst_path = destination_folder + src_path.replace(source_folder, \"\")\n\t if not os.path.exists(dst_path):\n\t os.mkdir(dst_path)\n\ndef process_template(in_file_path, out_file_path, res_editor_path):\n\n\tin_file = open(os.path.abspath(in_file_path), \"r\")\n\tout_file = open(os.path.abspath(out_file_path), \"w\")\n\n\tfor line in in_file:\n\n\t\tif line.find(\"@RES_EDITOR_PATH@\") != -1:\n\t\t\tline = line.replace(\"@RES_EDITOR_PATH@\", res_editor_path)\n\n\t\tif line.find(\"@RES_EDITOR_BINARY@\") != -1:\n\t\t\tline = line.replace(\"@RES_EDITOR_BINARY@\", res_editor_path + \"/ResourceEditor\")\n\n\t\tout_file.write(line)\n\n\tin_file.close()\n\tout_file.close()\n\ndef copy_scripts():\n\n\tdavaConfig = open(\"../../../DavaConfig.in\", \"r\")\n\n\tfor line in davaConfig:\n\t\tif line.find(\"RES_EDITOR_PATH\") != -1:\n\t\t\tres_editor_path = line.split(\"=\")[1].replace(\" \", \"\")\n\n\tdavaConfig.close()\n\n\tif 'res_editor_path' in locals():\n\n\t\tprocess_template(\"../scripts/TemplateConvert3D.in\", \"../DataSource/convert_3d.py\", res_editor_path)\n\t\tprocess_template(\"../scripts/TemplateConvert3D_FX.in\", \"../DataSource/convert_3d_FX.py\", res_editor_path)\n\t\tprocess_template(\"../scripts/TemplateConvert3DTanks.in\", \"../DataSource/convert_3d_tanks.py\", res_editor_path)\n\ndef copy_data():\n\t\n\tos.chdir(\"../Data\")\n\tos.system(\"git clean -dxf\")\n\n\tos.chdir(\"../DataSource\")\n\tos.system(\"git clean -dxf\")\n\n\tos.system(\"mkdir ../Data/Materials\")\n\tos.system(\"mkdir ../Data/Shaders\")\n\n\tcopy_recursively(\"../../../../performance.test/Data\", \"../Data\")\n\tcopy_recursively(\"../../../Tools/ResourceEditor/Data/Materials\", \"../Data/Materials\")\n\tcopy_recursively(\"../../../Tools/ResourceEditor/Data/Shaders\", \"../Data/Shaders\")\n\tcopy_recursively(\"../../../../performance.test/Data\", \"../Data\")\n\n\tcopy_recursively(\"../../../../performance.test/DataSource\", \"../DataSource\")\n\n\tcopy_scripts()\n\n\tconvert_everything = [sys.executable, \"convert_everything.py\"]\n\tsubprocess.call(convert_everything)\n\nif __name__ == '__main__':\n copy_data()\n","sub_path":"Projects/PerfomanceTests/scripts/copy_data.py","file_name":"copy_data.py","file_ext":"py","file_size_in_byte":2672,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"588644692","text":"# -*- coding: utf-8 -*-\nimport requests\n\n\ndate = {'Keywords': 'yoyoketang'}\nurl = 'http://zzk.cnblogs.com/s/blogpost'\n\n#r = requests.get(url)\ns = requests.session() #保存会话机制,就是保存了cookies的信息,下次请求直接带过去\ns.get(url) #第一次请求网页,这时候服务器会分配cookies给客户端,此时cookies已经保存在session()中\n\nr = s.get(url, params=date) #再用带有cookies的se请求\n\n\nprint(r.url)\nprint(r.cookies)\nprint(r.status_code)\nprint(r.text)\n\n\n\n\n\n","sub_path":"interface/src/test/test_get.py","file_name":"test_get.py","file_ext":"py","file_size_in_byte":566,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"639540741","text":"#!/usr/bin/env python\n# Copyright (c) 2008 Qtrac Ltd. All rights reserved.\n# This program or module is free software: you can redistribute it and/or\n# modify it under the terms of the GNU General Public License as published\n# by the Free Software Foundation, either version 2 of the License, or\n# version 3 of the License, or (at your option) any later version. It is\n# provided for educational purposes and is distributed in the hope that\n# it will be useful, but WITHOUT ANY WARRANTY; without even the implied\n# warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See\n# the GNU General Public License for more details.\n\nimport os\nimport sys\nfrom PyQt4.QtCore import (QByteArray, QDataStream, QIODevice, QMimeData,\n QPoint, QSize, QString, Qt)\nfrom PyQt4.QtGui import (QApplication, QColor, QDialog, QDrag,\n QFontMetricsF, QGridLayout, QIcon, QLineEdit, QListWidget,\n QListWidgetItem, QPainter, QWidget)\n\ndef set_drop_action(event):\n if QApplication.keyboardModifiers() & Qt.ControlModifier:\n event.setDropAction(Qt.CopyAction)\n else:\n event.setDropAction(Qt.MoveAction)\n\nclass DropLineEdit(QLineEdit):\n\n def __init__(self, parent=None):\n super(DropLineEdit, self).__init__(parent)\n self.setAcceptDrops(True)\n\n\n @staticmethod\n def dragEnterEvent(event):\n if event.mimeData().hasFormat(\"application/x-icon-and-text\"):\n event.accept()\n else:\n event.ignore()\n\n\n @staticmethod\n def dragMoveEvent(event):\n if event.mimeData().hasFormat(\"application/x-icon-and-text\"):\n set_drop_action(event)\n event.accept()\n else:\n event.ignore()\n\n\n def dropEvent(self, event):\n if event.mimeData().hasFormat(\"application/x-icon-and-text\"):\n data = event.mimeData().data(\"application/x-icon-and-text\")\n stream = QDataStream(data, QIODevice.ReadOnly)\n text = QString()\n stream >> text\n self.setText(text)\n set_drop_action(event)\n event.accept()\n else:\n event.ignore()\n\n\nclass DnDListWidget(QListWidget):\n\n def __init__(self, parent=None):\n super(DnDListWidget, self).__init__(parent)\n self.setAcceptDrops(True)\n self.setDragEnabled(True)\n\n\n @staticmethod\n def dragEnterEvent(event):\n if event.mimeData().hasFormat(\"application/x-icon-and-text\"):\n event.accept()\n else:\n event.ignore()\n\n\n @staticmethod\n def dragMoveEvent(event):\n if event.mimeData().hasFormat(\"application/x-icon-and-text\"):\n set_drop_action(event)\n event.accept()\n else:\n event.ignore()\n\n\n def dropEvent(self, event):\n if event.mimeData().hasFormat(\"application/x-icon-and-text\"):\n data = event.mimeData().data(\"application/x-icon-and-text\")\n stream = QDataStream(data, QIODevice.ReadOnly)\n text = QString()\n icon = QIcon()\n stream >> text >> icon\n item = QListWidgetItem(text, self)\n item.setIcon(icon)\n set_drop_action(event)\n event.accept()\n else:\n event.ignore()\n\n\n def startDrag(self, _):\n item = self.currentItem()\n icon = item.icon()\n data = QByteArray()\n stream = QDataStream(data, QIODevice.WriteOnly)\n stream << item.text() << icon\n mimeData = QMimeData()\n mimeData.setData(\"application/x-icon-and-text\", data)\n drag = QDrag(self)\n drag.setMimeData(mimeData)\n pixmap = icon.pixmap(24, 24)\n drag.setHotSpot(QPoint(12, 12))\n drag.setPixmap(pixmap)\n if drag.exec_(Qt.MoveAction|Qt.CopyAction) == Qt.MoveAction:\n self.takeItem(self.row(item))\n\n\nclass DnDWidget(QWidget):\n\n def __init__(self, text, icon=QIcon(), parent=None):\n super(DnDWidget, self).__init__(parent)\n self.default_text = text\n self.setAcceptDrops(True)\n self.text = QString(text)\n self.icon = icon\n\n\n def minimumSizeHint(self):\n fm = QFontMetricsF(self.font())\n if self.icon.isNull():\n return QSize(fm.width(self.text), fm.height() * 1.5)\n return QSize(34 + fm.width(self.text), max(34, fm.height() * 1.5))\n\n\n def paintEvent(self, _):\n height = QFontMetricsF(self.font()).height()\n painter = QPainter(self)\n painter.setRenderHint(QPainter.Antialiasing)\n painter.setRenderHint(QPainter.TextAntialiasing)\n painter.fillRect(self.rect(), QColor(Qt.yellow).light())\n if self.icon.isNull():\n painter.drawText(10, height, self.text)\n else:\n pixmap = self.icon.pixmap(24, 24)\n painter.drawPixmap(0, 5, pixmap)\n painter.drawText(34, height,\n self.text + \" (Drag to or from me!)\")\n\n\n @staticmethod\n def dragEnterEvent(event):\n if event.mimeData().hasFormat(\"application/x-icon-and-text\"):\n event.accept()\n else:\n event.ignore()\n\n\n @staticmethod\n def dragMoveEvent(event):\n if event.mimeData().hasFormat(\"application/x-icon-and-text\"):\n set_drop_action(event)\n event.accept()\n else:\n event.ignore()\n\n\n def dropEvent(self, event):\n if event.mimeData().hasFormat(\"application/x-icon-and-text\"):\n data = event.mimeData().data(\"application/x-icon-and-text\")\n stream = QDataStream(data, QIODevice.ReadOnly)\n self.text = QString()\n self.icon = QIcon()\n stream >> self.text >> self.icon\n set_drop_action(event)\n event.accept()\n self.updateGeometry()\n self.update()\n else:\n event.ignore()\n\n\n def mouseMoveEvent(self, event):\n self.startDrag()\n QWidget.mouseMoveEvent(self, event)\n\n\n def startDrag(self):\n icon = self.icon\n if icon.isNull():\n return\n data = QByteArray()\n stream = QDataStream(data, QIODevice.WriteOnly)\n stream << self.text << icon\n mimeData = QMimeData()\n mimeData.setData(\"application/x-icon-and-text\", data)\n drag = QDrag(self)\n drag.setMimeData(mimeData)\n pixmap = icon.pixmap(24, 24)\n drag.setHotSpot(QPoint(12, 12))\n drag.setPixmap(pixmap)\n if drag.exec_(Qt.MoveAction|Qt.CopyAction) == Qt.MoveAction:\n self.text = QString(self.default_text)\n self.icon = QIcon()\n self.updateGeometry()\n self.update()\n\n\nclass Form(QDialog):\n def __init__(self, parent=None):\n super(Form, self).__init__(parent)\n\n dndListWidget = DnDListWidget()\n path = os.path.dirname(__file__)\n for image in sorted(os.listdir(os.path.join(path, \"images\"))):\n if image.endswith(\".png\"):\n item = QListWidgetItem(image.split(\".\")[0].capitalize())\n item.setIcon(QIcon(os.path.join(path,\n \"images/{0}\".format(image))))\n dndListWidget.addItem(item)\n dndIconListWidget = DnDListWidget()\n dndIconListWidget.setViewMode(QListWidget.IconMode)\n dndWidget = DnDWidget(\"Drag to me!\")\n dropLineEdit = DropLineEdit()\n\n layout = QGridLayout()\n layout.addWidget(dndListWidget, 0, 0)\n layout.addWidget(dndIconListWidget, 0, 1)\n layout.addWidget(dndWidget, 1, 0)\n layout.addWidget(dropLineEdit, 1, 1)\n self.setLayout(layout)\n\n self.setWindowTitle(\"Custom Drag and Drop\")\n\n\ndef main():\n app = QApplication(sys.argv)\n form = Form()\n form.setWindowFlags(Qt.Window)\n form.show()\n app.exec_()\n\nif __name__ == '__main__':\n main()\n","sub_path":"rgpwp/chapter10.py","file_name":"chapter10.py","file_ext":"py","file_size_in_byte":7819,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"28988026","text":"from .gcore.queries import GetNetworkFee, GetBalance\nfrom .gcore.mutations import SendCoin\nfrom typing import List, Optional\nfrom .exc import SendLimitError, InvalidClientObject\n\n\nclass Send:\n def __init__(self, address: str, cryptocurrency: str, amount: float):\n self.address = address\n self.cryptocurrency = cryptocurrency\n self.amount = amount\n\n limits = {\n \"bitcoin\": 1,\n \"ethereum\": 50,\n \"litecoin\": 50,\n \"nairatoken\": 2000000\n }\n\n def execute(self, client):\n try:\n return client.execute(query=self.send())\n except AttributeError:\n raise InvalidClientObject(\" object expected received {} instead\".format(type(client)))\n\n def get_network_fee(self, response_fields):\n _price = GetNetworkFee()\n return _price.queryObject(\n response_fields=response_fields, \n cryptocurrency=self.cryptocurrency, amount=self.amount\n )\n\n def check_limit(self):\n if Send.limits[self.cryptocurrency.lower()] < self.amount:\n return False\n else:\n return True\n\n def send(self, response_fields):\n if self.cryptocurrency.lower() in Send.limits.keys():\n if self.check_limit(self.amount, self.cryptocurrency):\n return SendCoin().Mutate(\n cryptocurrency=self.cryptocurrency,\n response_fields=response_fields,\n amount=self.amount,\n address=self.address\n )\n else:\n raise SendLimitError(\"Maximum daily transaction amount exceeded\")\n\n def balance(self, response_fields: List):\n return GetBalance.queryObject(response_fields=response_fields)\n","sub_path":"py_buycoins/sending.py","file_name":"sending.py","file_ext":"py","file_size_in_byte":1770,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"21002443","text":"from twisted.internet.defer import returnValue\n\nconfig = {\n \"access\": \"public\",\n \"help\": \".lookup [word] || .lookup discharge || List who said the word how many times\"\n}\n\ndef command(guid, manager, irc, channel, user, word):\n #irc.msg(channel, u\"\\u0002\\u000308WARNING: This command is deprecated and will be removed in v6. Please start thinking of an alternative while you still can, or complain to Fugi.\")\n #irc.msg(channel, u\"This command is currently disabled due to the upgrade to v5. It'll return shortly. Thank you for your patience.\")\n irc.msg(channel, u\"This command is gone forever. RIP\")\n return\n \n word, _, _ = word.partition(\" \")\n counts = yield manager.master.modules[\"markov\"].count(word)\n counts = u\", \".join([u\"{} - {:,d} times\".format(i[0], i[1]) for i in counts.most_common(5)])\n message = u\"People who have said \\\"{}\\\" the most: {}\".format(word, counts)\n irc.msg(channel, message)\n returnValue(message)\n","sub_path":"commands/lookup.py","file_name":"lookup.py","file_ext":"py","file_size_in_byte":961,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"653805051","text":"# -*- coding: utf-8 -*-\n\"\"\"Test the AD54Elements multisearch viewlet.\"\"\"\nimport unittest2 as unittest\nfrom BeautifulSoup import BeautifulSoup\nfrom .base import AD54ELEMENTS_FUNCTIONAL_TESTING\n\n\nclass LogoViewletTestCase(unittest.TestCase):\n layer = AD54ELEMENTS_FUNCTIONAL_TESTING\n\n def test_psu_anchor(self):\n from Products.AD54Elements.browser.viewlets import LogoViewlet\n context = self.layer['portal']\n request = self.layer['request']\n viewlet = LogoViewlet(context, request, None, None)\n viewlet.update()\n results = viewlet.render()\n \n # Parse the results into soup\n html = BeautifulSoup(results)\n\n anchor = html.find('a', attrs={'title': 'Penn State'})['href']\n expected_anchor = u'http://www.psu.edu'\n self.assertEquals(anchor, expected_anchor)\n\n\nclass FooterViewletTestCase(unittest.TestCase):\n layer = AD54ELEMENTS_FUNCTIONAL_TESTING\n\n def test_legal_statements_anchor(self):\n from Products.AD54Elements.browser.viewlets import FooterViewlet\n context = self.layer['portal']\n request = self.layer['request']\n viewlet = FooterViewlet(context, request, None, None)\n viewlet.update()\n results = viewlet.render()\n\n # Parse the results into soup\n html = BeautifulSoup(results)\n\n statements = html.findAll('a', attrs={'href': 'http://www.psu.edu/ur/legal.html'})\n self.assertGreaterEqual(len(statements), 1)\n\n\nclass ColophonViewletTestCase(unittest.TestCase):\n layer = AD54ELEMENTS_FUNCTIONAL_TESTING\n\n def test_weblion_anchor(self):\n from Products.AD54Elements.browser.viewlets import ColophonViewlet\n context = self.layer['portal']\n request = self.layer['request']\n viewlet = ColophonViewlet(context, request, None, None)\n viewlet.update()\n results = viewlet.render()\n\n # Parse the results into soup\n html = BeautifulSoup(results)\n\n statements = html.findAll('a', attrs={'href': 'http://weblion.psu.edu'})\n self.assertGreaterEqual(len(statements), 1)\n\n\nclass FaviconViewletTestCase(unittest.TestCase):\n layer = AD54ELEMENTS_FUNCTIONAL_TESTING\n\n def setUp(self):\n from Products.AD54Elements.browser.viewlets import FaviconViewlet\n context = self.layer['portal']\n request = self.layer['request']\n viewlet = FaviconViewlet(context, request, None, None)\n\n from Products.AD54Elements.interfaces import IAD54ElementsLayer\n from zope.interface import directlyProvides\n directlyProvides(context, IAD54ElementsLayer)\n \n viewlet.update()\n results = viewlet.render()\n # Parse the results into soup\n html = BeautifulSoup(results)\n \n rels = {}\n for rel in html.findAll('link'):\n rels[rel['rel']] = rel['href']\n\n self.rels = rels\n\n def test_favicon(self):\n si = u'shortcut icon'\n self.assertTrue(si in self.rels)\n self.assertIn(u'++resource++images/favicon.ico', self.rels[si])\n\n def test_touchicon(self):\n ati = u'apple-touch-icon'\n self.assertTrue(ati in self.rels)\n self.assertIn(u'++resource++images/touch_icon.png', self.rels[ati])\n\n\nclass MultisearchViewletTestCase(unittest.TestCase):\n layer = AD54ELEMENTS_FUNCTIONAL_TESTING\n\n def test_default_options(self):\n # Initialize the viewlet\n from Products.AD54Elements.browser.viewlets import MultiSearchViewlet\n context = self.layer['portal']\n request = self.layer['request']\n viewlet = MultiSearchViewlet(context, request, None, None)\n viewlet.update()\n options = viewlet.getSearchOptions()\n # Test the results...\n expected_options = [\n {'selected': True, 'description': 'Search This Site', 'key': 'thisSite'},\n {'selected': False, 'description': 'Search Google', 'key': 'google'},\n {'selected': False, 'description': 'Search Penn State Web', 'key': 'PSUweb'},\n {'selected': False, 'description': 'Search Penn State People', 'key': 'PSUpeople'},\n {'selected': False, 'description': 'Search Penn State Accounts', 'key': 'PSUemail'},\n {'selected': False, 'description': 'Search Penn State Departments', 'key': 'PSUdept'},\n ]\n self.assertEqual(options, expected_options)\n\n @unittest.skip(\"Unable to test this at this time.\")\n def test_without_options(self):\n pass\n\n @unittest.skip(\"Unable to test this at this time.\")\n def test_new_options(self):\n pass\n","sub_path":"Products/AD54Elements/tests/test_viewlet.py","file_name":"test_viewlet.py","file_ext":"py","file_size_in_byte":4592,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"242669201","text":"# python 3\r\nimport tracemalloc\r\nimport time\r\nstart_time = time.time()\r\ntracemalloc.start()\r\n\r\nfrenchDictionary = {}\r\nwith open('french_dictionary.csv', encoding='utf-8') as reader:\r\n for i in reader.readlines():\r\n line = i.split(\",\");\r\n frenchDictionary[line[0]] = line[1][:len(line[1])-1]; \r\n\r\nwordFrequency = {}\r\nwith open('find_words.txt') as reader:\r\n for line in reader:\r\n for word in line.split():\r\n if frenchDictionary.get(word,False):\r\n wordFrequency[word] = 0\r\n\r\npunc = '''!()-[]{};:'\"\\, <>./?@#$%^&*_~'''\r\ndef removepunc(word):\r\n punctations = []\r\n for i,ele in enumerate(word): \r\n if ele in punc:\r\n if ele.find(\"'\") and i>0:\r\n ele = word[i:]\r\n punctations.append([ele,i])\r\n word = word.replace(ele, \"\")\r\n return [word,punctations]\r\ndef ReplaceWord(word):\r\n tempword = removepunc(word);\r\n tempCnt = wordFrequency.get(tempword[0].lower(),-1)\r\n if tempCnt>=0:\r\n wordFrequency[tempword[0].lower()] += 1\r\n replaceword = frenchDictionary[tempword[0].lower()] \r\n if tempword[0][0].isupper():\r\n replaceword = replaceword[0].upper()+replaceword[1:]\r\n if tempword[0].isupper():\r\n replaceword = replaceword.upper()\r\n for i in tempword[1]:\r\n if i[1] == 0:\r\n replaceword = i[0]+replaceword\r\n else:\r\n replaceword = replaceword+i[0]\r\n return replaceword\r\n return word\r\nwith open('t8.shakespeare.txt',encoding='utf-8') as infile, open('t8.shakespeare.translated.txt', 'w',encoding='utf-8') as outfile:\r\n for line in infile:\r\n for word in line.split():\r\n \r\n if word.find(\"-\")==-1:\r\n replaceword = ReplaceWord(word)\r\n else:\r\n treplaceword = []\r\n for tword in word.split(\"-\"):\r\n treplaceword.append(ReplaceWord(tword))\r\n replaceword = \"-\".join(treplaceword) \r\n\r\n line = line.replace(word,replaceword)\r\n outfile.write(line)\r\nwith open('frequency.csv', 'w',encoding='utf-8') as file:\r\n for key,val in wordFrequency.items():\r\n line = key+\",\"+frenchDictionary[key]+\",\"+str(val)+\"\\n\"\r\n file.write(line)\r\n\r\ncurrent, peak = tracemalloc.get_traced_memory()\r\nend_time = time.time()\r\ntracemalloc.stop()\r\nwith open('performance.txt','w') as file:\r\n file.write(time.strftime(\"Time to process: %M minutes %S seconds\",time.gmtime(end_time-start_time)))\r\n file.write(f\"\\nMemeory used: {peak / 10**6} MB\") ","sub_path":"solution.py","file_name":"solution.py","file_ext":"py","file_size_in_byte":2601,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"168613226","text":"\"\"\"\nThis function is the main function from which the program runs.\n\nCopying for purposes other than personal use is expressly\nprohibited. All forms of distribution of this code, whether as given\nor with any changes, are expressly prohibited.\n\nAll of the files in this directory and all subdirectories are:\nCopyright (c) 2021 Wasee Alam, Rohan Dey, Porom Kamal\n\n\"\"\"\n\nfrom typing import *\nimport country as c\nimport balance_distributions as bd\nimport print_plot as pp\nimport main_frame as display\n\nif __name__ == \"__main__\":\n # Execute the function\n pp.create_countries(master_list=c.country_master_list,\n df=pp.scrape_covid_data())\n\n country_to_quantity = {} # Dictionary that sorts by country vs vaccine quantity\n for country in c.country_master_list:\n country_to_quantity[country] = country.num_vaccines\n\n c.country_master_list = list(dict.fromkeys(c.country_master_list))\n\n pp.master_list_to_csv(c.country_master_list, country_to_quantity)\n\n bd.new_bal()\n\n for country in c.country_master_list:\n country_to_quantity[country] = country.num_vaccines\n \n pp.master_list_balanced_to_csv(c.country_master_list, country_to_quantity)\n\n display.main()\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1218,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"5362237","text":"import twitter\n\napi = twitter.Api(consumer_key='',\n consumer_secret='',\n access_token_key='',\n access_token_secret='')\ndef get_tweets(coin_name):\n ret_list = []\n query = \"q=\" + coin_name + \"&result_type=recent&count=100\"\n results = api.GetSearch(raw_query = query)\n for sent in results:\n print(sent.text.encode('ascii', errors='ignore'))\n ret_list.append(sent.text)\n return ret_list\n","sub_path":"utils/twitter_search.py","file_name":"twitter_search.py","file_ext":"py","file_size_in_byte":475,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"77017867","text":"from fractions import Fraction\n\ndef compute(vp, vd, t):\n # vp * x = vd * (x - t)\n # vp * x = vd * x - vd * t\n # vd * t = (vd - vp) * x\n # x = vd * t / (vd - vp)\n\n return Fraction(t * vd, vd - vp)\n\ndef main():\n vp = int(input())\n vd = int(input())\n t = int(input())\n f = int(input())\n c = int(input())\n\n if vp >= vd:\n print(0)\n return\n\n # first intersection at time x\n # vp * x = vd * (x - t)\n # vp * x = vd * x - vd * t\n # (vp - vd) *x = - vd * t\n # x = vd * t / (vd - vp)\n\n goal_time = Fraction(c, vp)\n delay = t\n b = 0\n intersection = compute(vp, vd, delay)\n\n # print(delay, intersection, goal_time)\n while intersection < goal_time:\n b += 1\n delay += f + 2 * (intersection - delay)\n intersection = compute(vp, vd, delay)\n\n # print(delay, intersection, goal_time)\n\n print(b)\n\nmain()\n","sub_path":"codeforces/148/b.py","file_name":"b.py","file_ext":"py","file_size_in_byte":895,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"397230365","text":"from pyspark.ml.linalg import Vectors\nimport pyspark as py\nimport pyspark.ml.feature as ft\n# 新建spark配置\nconf = py.SparkConf().setAppName('gbdt')\n# Spark入口\nsc = py.SparkContext(conf=conf)\n\ndf = py.SQLContext(sc).createDataFrame([(Vectors.dense([-1.0, 1.0]), ),\n (Vectors.dense([0.0, 2.0]), ),\n (Vectors.dense([0.0, 3.0]), )], [\"a\"])\ndf.show()\nindexer = ft.VectorIndexer(maxCategories=4, inputCol=\"a\", outputCol=\"indexed\")\nmodel = indexer.fit(df)\nprint(model.transform(df).head().indexed)\nmodel.transform(df).show()\n","sub_path":"cases/case01/test02.py","file_name":"test02.py","file_ext":"py","file_size_in_byte":603,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"359147130","text":"import re\nimport datetime\nimport importlib\n\nfrom periscope.periscope_pilot import PeriscopePilot\nfrom raspador import Maneuver, OrdnanceManeuver, NavigationManeuver, SequenceManeuver, UploadReportRaspador, ClickXPathSequenceManeuver, InteractManeuver, OrdnanceParser, XPath, RaspadorNoOrdnanceError, ClickXPathManeuver, SeekParser, SoupElementParser, FindElementManeuver, ClickSoupElementManeuver, Element, ElementManeuver, ClickElementManeuver\nfrom typing import Generator, Optional, Dict, List, Callable\nfrom time import sleep\nfrom bs4 import BeautifulSoup, Tag\n\nclass SignInManeuver(Maneuver[PeriscopePilot]):\n def attempt(self, pilot: PeriscopePilot):\n email_element = yield ClickElementManeuver(\n instruction='click the email filed',\n seeker=lambda p: p.soup.find('input', placeholder='Enter email address')\n )\n email_element.ordnance.send_keys(pilot.email)\n\n password_element = yield ClickElementManeuver(\n instruction='click the password field',\n seeker=lambda p: p.soup.find('input', placeholder='Enter password')\n )\n password_element.ordnance.send_keys(pilot.password)\n\n yield ClickElementManeuver(\n instruction='click the login button',\n seeker=lambda p: p.soup.find('span', text='LOG IN')\n )\n sleep(pilot.sign_in_wait)\n\nclass DismissPopUpManeuver(Maneuver[PeriscopePilot]):\n def attempt(self, pilot: PeriscopePilot):\n tries = 0\n while tries < 3:\n try:\n dismiss_popup = yield ElementManeuver(\n instruction='dismiss popup',\n seeker=lambda p: p.soup.find('div', {'title': 'Stop Walk-thru'})\n )\n dismiss_popup.ordnance.click()\n break\n except RaspadorNoOrdnanceError:\n tries = tries + 1\n continue\n\nclass OpenFilterBarManeuver(Maneuver[PeriscopePilot]):\n def attempt(self, pilot: PeriscopePilot, fly: Callable[[Maneuver], Maneuver]):\n fly(ClickElementManeuver(\n instruction='open the filter bar',\n seeker=lambda p: p.soup.find('div', {'class': 'filters-bar'})\n ))\n\nclass DimensionElementsParser(OrdnanceParser[List[Tag]]):\n def parse(self):\n self.ordnance = self.soup.find_all('div', {'class': 'dimension-setting'})\n return self\n\nclass EditIconChildParser(OrdnanceParser[List[str]]):\n def parse(self, filter_element):\n edit_icons = filter_element.soup_element.find_all('div', {'class': 'edit-icon'})\n self.ordnance = [self.xpath_for_element(edit_icon) for edit_icon in edit_icons]\n return self\n\nclass RefreshFilterManeuver(Maneuver[PeriscopePilot]):\n def __init__(self):\n super().__init__()\n\n def attempt(self, pilot: PeriscopePilot, fly: Callable[[Maneuver], Maneuver]):\n fly(ClickElementManeuver(\n instruction='click the refresh icon',\n seeker=lambda p: p.soup.find('div', {'class': 'refresh-icon'})\n ))\n\nclass RefreshFiltersManeuver(Maneuver[PeriscopePilot]):\n def attempt(self, pilot: PeriscopePilot, fly: Callable[[Maneuver], Maneuver]):\n parser = DimensionElementsParser.from_browser(browser=pilot.browser)\n dimension_elements = parser.parse().deploy()\n filter_elements = [\n Element(soup_element=dimension_element, browser=pilot.browser)\n for dimension_element in dimension_elements\n ]\n # Hide all the filters with css\n for filter_element in filter_elements:\n filter_element.set_css_property('display', 'none')\n # Loop through all the now invisible filters\n # - display each one in the top, left corner of the filter area\n # - open it and perform the refresh maneuver\n # - make it invisible again\n for filter_element in filter_elements:\n filter_element.set_css_property('display', 'inherit')\n filter_element.set_css_property('top', '0px')\n filter_element.set_css_property('left', '0px')\n filter_element.set_css_property('zIndex', '100')\n filter_element.add_class('open')\n edit_icon_xpaths = EditIconChildParser.from_browser(pilot.browser).parse(filter_element).deploy()\n if len(edit_icon_xpaths) > 0:\n edit_icon_element = Element(xpath=edit_icon_xpaths[0], browser=pilot.browser)\n edit_icon_element.click()\n fly(RefreshFilterManeuver())\n sleep(1)\n filter_element.set_css_property('display', 'none')\n\nclass PeriscopeManeuver(Maneuver[PeriscopePilot]):\n def attempt(self, pilot: PeriscopePilot):\n yield NavigationManeuver(url='https://app.periscopedata.com/login?controller=welcome')\n yield SignInManeuver()\n\n for url in pilot.urls:\n yield NavigationManeuver(url=url)\n sleep(5)\n try:\n yield DismissPopUpManeuver()\n except:\n import pdb; pdb.set_trace()\n yield OpenFilterBarManeuver()\n yield RefreshFiltersManeuver()\n\n yield InteractManeuver()\n\nif __name__ == '__main__':\n enqueue_maneuver(PeriscopeManeuver())\nelse:\n enqueue_maneuver(RefreshFilterManeuver(edit_element=Element(xpath='html[1]/body[1]/div[1]/div[3]/div[4]/div[2]/div[1]/div[4]/header[1]/div[1]')))\n","sub_path":"periscope_maneuver.py","file_name":"periscope_maneuver.py","file_ext":"py","file_size_in_byte":4942,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"269021055","text":"#!/usr/bin/python\nfrom __future__ import print_function\nimport re\nimport types\nimport random\nfrom numpy import *\nimport gc as ggcc\n\nclass key_value:\n def __init__(self, key_in, value_in):\n self.key = key_in\n if value_in == '':\n value_in = '#1'\n if type(value_in) == type(1):\n self.value = value_in\n else:\n tmp = value_in.replace('#', '')\n self.value = int(value_in.replace('#', ''))\n\n\n# def get_last_index(self, kv_list):\n# for item in reversed(kvelist):\n# if item.key == self.key:\n# return kv_list.index(item)\n# return -1\n# @classmethod\n def get_last_index(self, kv_list):\n for item_index in range(len(kv_list)-1,-1,-1):\n if kv_list[item_index].key == self.key:\n return item_index\n return -1\n def get_first_index(self, kv_list):\n for item_index in range(len(kv_list)):\n if kv_list[item_index].key == self.key:\n return item_index\n return -1\n\n def key_in_list(self, kv_list):\n index = self.get_first_index(kv_list)\n if index == -1:\n return False\n else:\n return True\n\n def add_to_list_max(self, kv_list):\n index = self.get_last_index(kv_list)\n if index != -1:\n if self.value < 0:\n self.value = -1 * self.value\n if self.value > kv_list[index].value:\n kv_list[index].value = self.value\n else:\n kv_list.append(self.copy())\n def add_to_list(self, kv_list):\n kv_list.append(self.copy())\n def add_to_list_inc(self, kv_list):\n index = self.get_last_index(kv_list)\n if index != -1:\n kv_list[index].value += 1\n else:\n kv_list.append(self.copy())\n @classmethod\n def show_list(self, kv_list):\n if len(kv_list) == 0:\n print('Empty list!')\n return\n index = 0\n for i in kv_list:\n if index < 10:\n space = ' '\n else:\n space = ''\n print('[%d]%s \"%s\" : %d' % (index, space, i.key, i.value))\n index += 1\n def copy(self):\n return key_value(self.key, self.value)\n\nclass asm_operand:\n ext_ins = ('lsl', 'sxtw')\n def __init__(self, op_str):\n self.op = op_str\n self.base = '0'\n self.offset = '0'\n self.scale = '1'\n self.op_num = 1\n self.parse()\n def parse(self):\n if self.op == '':\n self.type = 'empty'\n return\n if ('[' in self.op):\n self.type = 'addr'\n op_addr = self.op\n op_addr = op_addr.replace('[', '')\n op_addr = op_addr.replace('] ', '').replace(']', '')\n op_addr = op_addr.replace('%', '')\n op_addr_elements = op_addr.split(', ')\n self.op_num = len(op_addr_elements)\n if self.op_num >= 1:\n self.base = op_addr_elements[0]\n if self.op_num >= 2:\n self.offset = op_addr_elements[1]\n if self.op_num >= 3:\n self.scale = op_addr_elements[2]\n self.addr_elements = []\n for i in op_addr_elements:\n ao_tmp = asm_operand(i.replace(' ', ''))\n# if 'input' in ao_tmp.op:\n# print(ao_tmp.op)\n self.addr_elements.append(ao_tmp)\n elif self.op.split()[0] in asm_operand.ext_ins:\n self.type = 'ext'\n elif '#' in self.op or self.op.isdigit():\n self.type = 'num'\n elif 'input' in self.op:\n self.type = 'c_input'\n elif ('pc' in self.op):\n self.type = 'pc'\n else:\n self.op = self.op.replace(' ', '')\n self.type = 'reg'\n def is_addr(self):\n# print('\"%s\"' % self.op)\n return self.type == 'addr'\n def copy(self):\n return asm_operand(self.op)\n\nclass asm_arm:\n# instructions = ('mov', 'sub', 'ldr', 'add', 'smaddl', 'lsl', 'str', 'smull', 'cmp', 'nop', 'b.le', 'OUT:')\n instructions = []\n def __init__(self, instr_str):\n self.str = instr_str\n self.op_list = []\n self.src_list = []\n self.instr = ''\n self.reg_dist = ''\n self.reg_dist2 = 'None'\n self.addr_op_index = -1\n self.get_iset_arm()\n self.parse()\n def get_iset_arm(self):\n if len(asm_arm.instructions) != 0:\n return\n f = open('isa-arm.dat')\n line = f.readline().replace('\\n', '')\n ins_list = []\n while line:\n asm_arm.instructions.append(line)\n line = f.readline().replace('\\n', '')\n f.close()\n def copy(self):\n return asm_arm(self.str)\n def parse(self):\n ins_elements = self.str.split(', ')\n# print(ins_elements)\n op_tmp = ins_elements[0].split()\n if op_tmp[0] in self.instructions:#get instruction name here\n self.instr = op_tmp[0]\n op_tmp.remove(op_tmp[0])\n ins_elements.remove(ins_elements[0])\n ins_elements = op_tmp + ins_elements\n if len(op_tmp) > 0:\n self.reg_dist = op_tmp[0]\n if len(ins_elements) > 1:\n self.reg_dist2 = ins_elements[1]\n join_flag = 0\n i = 0\n while 1:\n cur_op = ins_elements[i]\n# print(cur_op)\n if join_flag == 1:\n ins_elements[i-1] = ins_elements[i-1] + ', ' + ins_elements[i]\n ins_elements.remove(ins_elements[i])\n else:\n i += 1\n if ']' in cur_op:\n join_flag = 0\n self.addr_op_index = i\n if i>=len(ins_elements):\n break;\n if '[' in cur_op:\n join_flag = 1\n elif 'OUT' not in self.str:\n print(self.instr)\n print('Do not support instruction: %s' % self.str)\n exit()\n self.op_num = len(ins_elements)\n\n for i in range(len(ins_elements)):\n self.op_list.append(asm_operand(ins_elements[i]))\n if i > 0:\n self.src_list.append(asm_operand(ins_elements[i]))\n def get_addr_op_index(self):\n return self.addr_op_index\n def show(self):\n print('$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$')\n print('Assembly:')\n print('\\t%s' % self.str)\n print('Number of operands:')\n print('\\t%s' % self.op_num)\n print('Instruction:')\n print('\\t%s' % self.instr)\n print('Destination:')\n print('\\t%s' % self.reg_dist)\n print('Operands:')\n for i in self.op_list:\n print('\\t%s <-- %s' % (i.op, i.type))\n if i.is_addr():\n print('\\t\\tBase: %s, offset: %s, scale: %s' % (i.base, i.offset, i.scale))\n for j in i.addr_elements:\n print('\\t\\t%s <-- %s' % (j.op, j.type))\n print('--------------------------------')\n\n def get_reg_list(self):\n reg_list = []\n reg_list.append(self.reg_dist)\n for i in self.op_list:\n if i.type == 'reg':\n reg_list.append(i.op)\n elif i.is_addr():\n for j in i.addr_elements:\n if j.type == 'reg':\n reg_list.append(j.op)\n return reg_list\n\n\nclass asm_block:\n def __init__(self, file_path):\n self.dist_list = []\n self.dist_list2 = []\n self.src_reg_list = []\n self.base_reg_list = []\n self.offset_reg_list = []\n self.scale_reg_list = []\n self.dist_reg_cursor_list = []\n self.malloc_reg_list = []\n self.all_w_reg_list = []\n self.all_x_reg_list = []\n self.insert_list = []\n self.replacement_list = []\n self.block_num = 0\n self.hotness = 3\n self.offset_step = 1024\n #for statistics\n# self.malloc_size_list = []\n for i in range(0, 29):\n x_reg = (\"x%d\" % i)\n w_reg = (\"w%d\" % i)\n key_value(x_reg, 0).add_to_list(self.all_x_reg_list)\n key_value(w_reg, 0).add_to_list(self.all_w_reg_list)\n self.asm_list = []\n self.path = file_path\n if self.path == None:\n return\n f = open(file_path)\n line = f.readline()\n ins_list = []\n while line:\n line = re.sub(u\"\\\\(.*?\\\\)\", \"\", line).replace('\\n', '') \n ins_list.append(line.lstrip())\n line = f.readline()\n self.load_list(ins_list)\n f.close()\n\n def load_list(self, instruction_list):\n for i in instruction_list:\n self.asm_list.append(asm_arm(i))\n #put the following methods in order!\n self.gen_instrument()\n self.instrument_asm()\n self.scan_reg()\n self.replace29sp()\n self.gen_prep_mem()\n self.gen_free_mem()\n\n def asm_list_remove(self, index):\n self.asm_list.pop(index)\n\n def asm_list_insert(self, index, value):\n self.asm_list.insert(index, asm_arm(value))\n\n def insert_asm_kv(self, kv):\n# print('insert \"%s\" to %d' % (kv.key, kv.value))\n# print 'kv.value:'\n# print kv.value\n# print 'len:'\n# print len(self.asm_list)\n if kv.value >= len(self.asm_list):\n# print 'XXXXXXXXXXXX'\n# print kv.key\n self.asm_list.append(asm_arm(kv.key))\n else:\n self.asm_list.insert(kv.value, asm_arm(kv.key))\n\n def show(self):\n for i in self.asm_list:\n i.show()\n\n# def copy(self):\n# return asm_block(self.path)\n\n def print_asm(self):\n for asm in self.asm_list:\n# if 'fmov' in asm.str:\n# print('xxxxxxxx')\n# continue\n ########## DO NOT SUPPORT BSL ###########\n if 'bsl' in asm.str or ('.' in asm.str and 'v' in asm.str and ('fmov' not in asm.str)):\n print('\\t\\t\"nop\\\\n\\\\t\"')\n continue\n if 'dc zva' in asm.str:\n print('\\t\\t\"nop\\\\n\\\\t\"')\n continue\n ########## DO NOT SUPPORT mrs AND msr ###########\n# if 'mrs' in asm.str or ('msr' in asm.str):\n# continue\n ########## DO NOT SUPPORT pc ###########\n# if 'pc' in asm.str:\n# continue\n ########## DO NOT SUPPORT fmov ###########\n print('\\t\\t\"%s\\\\n\\\\t\"' % (asm.str))\n\n def gen_prep_mem(self):\n ret_list=[]\n for item in self.malloc_reg_list:\n ######## DO NOT SUPPORT VECTORS ##########\n if '.' in item.key or 'v' in item.key:\n continue\n # ret_list.append('\\t//Block_num: %d' % self.block_num)\n malloc_str = ('\\tlong *ptr_%s_%d = malloc(sizeof(long) * %d);\\n' % (item.key, self.block_num, item.value)) \\\n + ('\\tlong *ptr_%s_%d_in = ptr_%s_%d;\\n' % (item.key, self.block_num, item.key, self.block_num)) \n# + ('\\tfor(int i = 0; i < %d; i++)\\n\\t{\\n\\t\\tptr_%s_%d[i] = rand();\\n\\t}\\n' % (item.value, item.key, self.block_num))\n ret_list.append(malloc_str)\n# print('\\tlong *ptr_%s_%d = malloc(sizeof(long) * %d);' % (item.key, self.block_num, item.value))\n# print('\\tfor(int i = 0; i < %d; i++)\\n\\t{\\n\\t\\tptr_%s_%d[i] = rand();\\n\\t}' % (item.value, item.key, self.block_num))\n# print('')\n gen_code.add_gen_malloc(ret_list)\n\n def gen_free_mem(self):\n ret_list=[]\n for item in self.malloc_reg_list:\n ######## DO NOT SUPPORT VECTORS ##########\n if '.' in item.key or 'v' in item.key:\n continue\n # ret_list.append('\\t//Block_num: %d' % self.block_num)\n ret_list.append('\\tfree(ptr_%s_%d);' % (item.key, self.block_num))\n gen_code.add_gen_free(ret_list)\n# print('\\tfree(ptr_%s_%d);' % (item.key, self.block_num))\n\n def find_next_dist_reg(self, dist, index):\n for i in range(len(self.asm_list)):\n if self.asm_list[i].reg_dist == dist and i >= index:\n return i\n\n def find_next_base_reg(self, base, index):\n for i in range(len(self.asm_list)):\n for op in self.asm_list[i].op_list:\n if op.is_addr():\n# print op.base\n if base == op.base and i >= index:\n return i\n\n def find_next_offset_reg(self, offset, index):\n for i in range(len(self.asm_list)):\n for op in self.asm_list[i].op_list:\n if op.is_addr():\n# print op.offset\n if offset == op.offset and i >= index:\n return i\n\n def add_to_all_reg_list(self, kv):\n if 'zr' in kv.key:\n return\n if 'x' in kv.key and '#' not in kv.key:\n kv.add_to_list_inc(self.all_x_reg_list)\n elif 'w' in kv.key:\n kv.add_to_list_inc(self.all_w_reg_list)\n\n #for statistics\n# def get_all_reg_list_len(self, kv_list):\n# length = 0\n# for item in kv_list:\n# if item.value != 0:\n# length += 1\n# return length\n\n def scan_reg(self):\n# print('scan_reg:')\n self.dist_list = []\n self.dist_list2 = []\n for asm in self.asm_list:\n# print(asm.str)\n if 'b.' in asm.instr or 'bl' in asm.instr:\n break\n if 'stp' in asm.instr or 'ldp' in asm.instr:\n key_value(asm_operand(asm.reg_dist2).op, '-1').add_to_list(self.dist_list2)\n if asm.reg_dist != '' and 'OUT' not in asm.reg_dist:\n kv_reg_dist = key_value(asm_operand(asm.reg_dist).op, '-1')\n kv_reg_dist.add_to_list(self.dist_list)\n kv_reg_dist.value = 1\n self.add_to_all_reg_list(kv_reg_dist)\n for op in asm.src_list:\n if op.is_addr():\n# print('op.is_addr():')\n if asm_operand(op.base).type == 'reg':\n reg_base = key_value(op.base, '-1')\n reg_base.add_to_list(self.base_reg_list)\n reg_base.value = 1\n# print(reg_base.key)\n self.add_to_all_reg_list(reg_base)\n reg_base.add_to_list_inc(self.src_reg_list)\n if asm_operand(op.offset).type == 'reg':\n reg_offset = key_value(op.offset, '-1')\n reg_offset.add_to_list(self.offset_reg_list)\n reg_offset.value = 1\n# print(reg_offset.key)\n self.add_to_all_reg_list(reg_offset)\n reg_offset.add_to_list_inc(self.src_reg_list)\n if asm_operand(op.scale).type == 'reg':\n reg_scale = key_value(op.scale, '-1')\n reg_scale.add_to_list(self.scale_reg_list)\n reg_scale.value = 1\n# print(reg_scale.key)\n self.add_to_all_reg_list(reg_scale)\n reg_scale.add_to_list_inc(self.src_reg_list)\n else:\n if op.type == 'reg':\n# print('reg_src')\n reg_src = key_value(op.op, '1')\n# print(reg_src.key)\n self.add_to_all_reg_list(reg_src)\n reg_src.add_to_list(self.scale_reg_list)\n reg_src.add_to_list_inc(self.src_reg_list)\n# key_value.show_list(self.all_reg_list)\n# key_value.show_list(self.src_reg_list)\n# key_value.show_list(self.all_x_reg_list)\n# key_value.show_list(self.all_w_reg_list)\n\n\n #for statistics\n #print('//all_reg_list_length: %d' % (self.get_all_reg_list_len(self.all_x_reg_list) + self.get_all_reg_list_len(self.all_w_reg_list)))\n\n def find_replacement(self):\n for i in reversed(range(0, 29)):\n if self.all_x_reg_list[i].value == 0 and self.all_w_reg_list[i].value == 0:\n if i in self.replacement_list:\n continue\n else:\n self.replacement_list.append(i)\n return i\n print(self.block_num)\n print('No alternitave registers available!')\n exit()\n return -1\n\n def replace29_str(self, asm_str, rep_index_29, rep_index_sp):\n replace_start = ('[', 'input_', ' ')\n replace_end = (',', ']', '_', ' ')\n replace_width = ('x', 'w')\n ret = asm_str\n #turn pc+123 to [sp] first\n if 'pc+' in asm_str:\n op_pc = ret.split()[2]\n ret = ret.replace(op_pc, '[sp]')\n for start in replace_start:\n for end in replace_end:\n for width in replace_width:\n before_29 = ('%s%s29%s' % (start, width, end))\n after_29 = ('%s%s%d%s' % (start, width, rep_index_29, end))\n ret = ret.replace(before_29, after_29)\n before_sp = ('%ssp%s' % (start, end))\n after_sp = ('%s%s%d%s' % (start, 'x', rep_index_sp, end))\n ret = ret.replace(before_sp, after_sp)\n return ret\n\n def is_gp_reg(self, reg_str):\n if (len(reg_str) < 2) or (len(reg_str) > 3):\n return False\n if (reg_str[0] != 'x') and (reg_str[0] != 'w'):\n return False\n if reg_str[1:].isdigit():\n if int(reg_str[1:]) == 29:\n return False\n else:\n return True\n return False\n def replace_nzcv(self, instr_in):\n if '#' in instr_in and ('v' in instr_in or 'V' in instr_in):\n nzcv_to_num = random.randint(0, 15)\n return re.sub('nzcv', str(nzcv_to_num), instr_in, flags=re.IGNORECASE)\n else:\n return instr_in\n\n #replace registers x29, w29 and sp with unused registers\n #replace register reg_used, with a used dist register\n #replace wzr and xzr with gp regs\n #replace #nzcv with number\n def replace29sp(self):\n# self.show()\n rep29 = self.find_replacement()\n rep_sp = self.find_replacement()\n rep_zr = '7'\n rep_ret = ''\n for dist in self.all_x_reg_list:\n if dist.key != 'x29' \\\n and self.reg_num_in_list(dist, self.dist_reg_cursor_list) == -1 \\\n and dist.key != rep29 and dist.key != rep_sp:\n rep_ret = dist.key\n break\n\n if len(rep_ret) == 0:\n print('rep_ret: lenth = 0')\n exit()\n\n for asm_index in range(len(self.asm_list)):\n ##for replace xzr and wzr, DO NOT use regs that affect malloced ptrs\n #regs is reg set of this line of instruction\n regs = self.asm_list[asm_index].get_reg_list()\n for reg_index in range(len(regs)-1, -1, -1):\n kv_tmp = key_value(regs[reg_index], 0)\n #only keep x regs and w regs, others will be popped out of the list\n if not ((kv_tmp.key_in_list(self.all_x_reg_list)) or (kv_tmp.key_in_list(self.all_w_reg_list))):\n regs.pop(reg_index)\n else:\n #remove x and w, only keep reg number\n regs[reg_index] = regs[reg_index].replace('x', '').replace('w', '')\n# key_value.show_list(self.dist_list)\n #we need to find a reg in dist_list but not in self.dist_reg_cursor_list\n for dist in self.dist_list:\n if not self.is_gp_reg(dist.key):\n continue\n if dist.key.replace('x', '').replace('w', '') not in regs:\n if self.reg_num_in_list(key_value(dist.key, -1), self.dist_reg_cursor_list) != -1:\n continue\n rep_zr = dist.key.replace('x', '').replace('w', '')\n break\n ##end of for replace xzr and wzr\n replaced = self.replace29_str(self.asm_list[asm_index].str, rep29, rep_sp).replace('reg_used', rep_ret)\n #replace unsupported zero register with a used register\n replaced = replaced.replace('wzr', ('w%s' % rep_zr)).replace('xzr', ('x%s' % rep_zr))\n replaced = self.replace_nzcv(replaced)\n #replace negtive values with positive ones\n if '#' in replaced and ('0x' not in replaced):\n replaced_element_list = replaced.split()\n for i in range(len(replaced_element_list)):\n if '#' in replaced_element_list[i] and ('0.0' not in replaced_element_list[i]):\n num = int(replaced_element_list[i].replace('#', '')\n .replace(',', '').replace(']', '').replace('[', '').replace('!', ''))\n if num <= -255 and (('ldur' in replaced) or ('stur' in replaced)):\n num += 2\n if num < 0:\n num *= -1\n new_item = '#' + str(num)\n if (',' in replaced_element_list[i]):\n new_item = new_item + ','\n if ('[' in replaced_element_list[i]):\n new_item = '[' + new_item\n if ('!]' in replaced_element_list[i]):\n new_item = new_item + '!]'\n elif (']!' in replaced_element_list[i]):\n new_item = new_item + ']!'\n elif (']' in replaced_element_list[i]):\n new_item = new_item + ']'\n replaced_element_list[i] = new_item\n replaced = ' '.join(replaced_element_list)\n #print(replaced)\n #replaced = replaced.replace('#-', '#')\n if replaced != self.asm_list[asm_index].str:\n self.asm_list[asm_index] = asm_arm(replaced)\n for kv_reg in self.malloc_reg_list:\n kv_reg.key = kv_reg.key.replace('29', str(rep29))\n kv_reg.key = kv_reg.key.replace('sp', ('x%s' % str(rep_sp)))\n for kv_reg in self.dist_list:\n kv_reg.key = kv_reg.key.replace('29', str(rep29))\n kv_reg.key = kv_reg.key.replace('sp', ('x%s' % str(rep_sp)))\n kv_reg.key = kv_reg.key.replace('reg_used', rep_ret).replace('wzr', ('w%s' % rep_zr)).replace('xzr', ('x%s' % rep_zr))\n for kv_reg in self.dist_list2:\n kv_reg.key = kv_reg.key.replace('29', str(rep29))\n kv_reg.key = kv_reg.key.replace('sp', ('x%s' % str(rep_sp)))\n kv_reg.key = kv_reg.key.replace('reg_used', rep_ret).replace('wzr', ('w%s' % rep_zr)).replace('xzr', ('x%s' % rep_zr))\n for kv_reg in self.dist_reg_cursor_list:\n kv_reg.key = kv_reg.key.replace('29', str(rep29))\n kv_reg.key = kv_reg.key.replace('sp', ('x%s' % str(rep_sp)))\n kv_reg.key = kv_reg.key.replace('reg_used', rep_ret).replace('wzr', ('w%s' % rep_zr)).replace('xzr', ('x%s' % rep_zr))\n\n def instrument_asm(self):\n #for statistics\n #print('//insert_list.length: %d' % len(self.insert_list))\n for item in reversed(self.insert_list):\n self.insert_asm_kv(item)\n\n def scale_to_num(self, scale_str):\n if 'lsl #' in scale_str:\n return pow(2, int(scale_str.replace('lsl #', '')))\n elif 'sxt' in scale_str:\n item_list = scale_str.split()\n if len(item_list) == 1:\n return 1\n return int(item_list[1].replace('#', ''))\n elif scale_str.isdigit():\n return int(scale_str)\n else: \n print('//not supported scale: %s' % scale_str)\n exit()\n return -1\n\n def get_rand_offset(self):\n return random.randint(1, 1023)\n\n def get_malloc_size(self, offset, scale):\n if offset < 0:\n offset = -1 * offset\n return (offset + 64) * scale\n\n def gen_instrument(self):\n adrp_handled = False\n for asm_index in range(len(self.asm_list)):\n #print('')\n #print(self.asm_list[asm_index].str)\n #instrument ret instruction:\n cur_instr = self.asm_list[asm_index].instr\n if cur_instr == 'ret':\n ble_ins_str = ('ldr reg_used, =OUT_RET_%d' % self.block_num)\n #replace b.le #+0x2b40 with b.le OUT\n self.asm_list_insert(asm_index, ble_ins_str)\n self.asm_list_remove(asm_index + 1)\n ins_kv_out = key_value('br reg_used', asm_index + 1)\n self.insert_list.append(ins_kv_out)\n ins_kv_nop = key_value(('mov x17, #0xfffff'), asm_index + 1)\n self.insert_list.append(ins_kv_nop)\n ins_kv_nop = key_value((('OUT_RET_%d:') % self.block_num), asm_index + 1)\n self.insert_list.append(ins_kv_nop)\n ins_kv_nop = key_value('nop', asm_index + 1)\n self.insert_list.append(ins_kv_nop)\n elif cur_instr == 'br' or cur_instr == 'blr':\n ble_ins_str = ('ldr reg_used, =OUT_%d' % self.block_num)\n self.asm_list_insert(asm_index, ble_ins_str)\n self.asm_list_remove(asm_index + 1)\n ins_kv_out = key_value(('%s reg_used' % cur_instr), asm_index + 1)\n self.insert_list.append(ins_kv_out)\n ins_kv_nop = key_value(('mov x17, #0xfffff'), asm_index + 1)\n self.insert_list.append(ins_kv_nop)\n ins_kv_nop = key_value(('OUT_%d:' % self.block_num), asm_index + 1)\n self.insert_list.append(ins_kv_nop)\n ins_kv_nop = key_value('nop', asm_index + 1)\n self.insert_list.append(ins_kv_nop)\n elif cur_instr == 'adrp' or cur_instr == 'adr':\n ble_ins_str = ('%s reg_used, OUT_ADRP_%d' % (cur_instr, self.block_num))\n self.asm_list_insert(asm_index, ble_ins_str)\n self.asm_list_remove(asm_index + 1)\n if not adrp_handled:\n ins_kv_nop = key_value(('mov x17, #0xfffff'), asm_index + 1)\n self.insert_list.append(ins_kv_nop)\n ins_kv_nop = key_value(('OUT_ADRP_%d:' % self.block_num), asm_index + 1)\n self.insert_list.append(ins_kv_nop)\n adrp_handled = True\n elif cur_instr == 'tbz' or cur_instr == 'tbnz':\n instr_list = self.asm_list[asm_index].str.split()\n instr_list[3] = ('OUT_TBZ_%d' % self.block_num)\n ble_ins_str = ' '.join(instr_list)\n self.asm_list_insert(asm_index, ble_ins_str)\n self.asm_list_remove(asm_index + 1)\n ins_kv_nop = key_value(('mov x17, #0xfffff'), asm_index + 1)\n self.insert_list.append(ins_kv_nop)\n ins_kv_nop = key_value(('OUT_TBZ_%d:' % self.block_num), asm_index + 1)\n self.insert_list.append(ins_kv_nop)\n ins_kv_nop = key_value('nop', asm_index + 1)\n self.insert_list.append(ins_kv_nop)\n elif cur_instr == 'cbz' or cur_instr == 'cbnz':\n instr_list = self.asm_list[asm_index].str.split()\n instr_list[2] = ('OUT_CBZ_%d' % self.block_num)\n ble_ins_str = ' '.join(instr_list)\n self.asm_list_insert(asm_index, ble_ins_str)\n self.asm_list_remove(asm_index + 1)\n ins_kv_nop = key_value(('mov x17, #0xfffff'), asm_index + 1)\n self.insert_list.append(ins_kv_nop)\n ins_kv_nop = key_value(('OUT_CBZ_%d:' % self.block_num), asm_index + 1)\n self.insert_list.append(ins_kv_nop)\n ins_kv_nop = key_value('nop', asm_index + 1)\n self.insert_list.append(ins_kv_nop)\n elif cur_instr == 'bl' or cur_instr == 'b':\n ble_ins_str = ('%s OUT_BL_%d' % (cur_instr, self.block_num))\n self.asm_list_insert(asm_index, ble_ins_str)\n self.asm_list_remove(asm_index + 1)\n ins_kv_nop = key_value(('mov x17, #0xfffff'), asm_index + 1)\n self.insert_list.append(ins_kv_nop)\n ins_kv_nop = key_value(('OUT_BL_%d:' % self.block_num), asm_index + 1)\n self.insert_list.append(ins_kv_nop)\n ins_kv_nop = key_value('nop', asm_index + 1)\n self.insert_list.append(ins_kv_nop)\n elif '#' in (self.asm_list[asm_index].str) and cur_instr == 'fmov':\n #and ('#' in cur_instr):\n cur_instr_list = self.asm_list[asm_index].str.split()\n fmov_op_float = cur_instr_list[2]\n cur_instr_list[2] = '1.0e+1'\n ble_ins_str = ' '.join(cur_instr_list)\n self.asm_list_insert(asm_index, ble_ins_str)\n self.asm_list_remove(asm_index + 1)\n# elif cur_instr == 'ldp' or cur_instr == 'stp':#they have 2 dist ops\n# reg_dist2 = key_value(asm_operand(self.asm_list[asm_index].reg_dist2).op, '-1')\n# reg_dist2.add_to_list(self.dist_list2)\n\n kv_reg_dist = key_value(asm_operand(self.asm_list[asm_index].reg_dist2).op, '-1')\n kv_reg_dist.add_to_list(self.dist_list2)\n\n kv_reg_dist = key_value(asm_operand(self.asm_list[asm_index].reg_dist).op, '-1')\n kv_reg_dist.add_to_list(self.dist_list)\n for op in self.asm_list[asm_index].op_list:\n #asign value for addr regs\n base_val = 0\n offset_val = 0\n scale_val = 1\n if op.is_addr():\n #print('xxxxxx\\nbase = %s, offset = %s, scale = %s' % (op.base, op.offset, op.scale))\n addr_op_list = []\n base_type = asm_operand(op.base).type\n offset_type = asm_operand(op.offset).type\n scale_type = asm_operand(op.scale).type\n if base_type == 'reg':\n addr_op_list.append(op.base)\n if offset_type == 'reg':\n addr_op_list.append(op.offset)\n offset_val = self.get_rand_offset()\n elif offset_type == 'num':\n offset_val = int(op.offset.replace('#', '').replace('!', ''))\n if scale_type == 'reg':\n print('//Not support scale of reg')\n# exit()\n elif scale_type == 'ext':\n scale_val = self.scale_to_num(op.scale)\n #print('base.val = %s, offset.val = %s, scale.val = %s' % (base_val, offset_val, scale_val))\n cur_malloc_size = self.get_malloc_size(offset_val, scale_val)\n# print cur_malloc_size\n if cur_malloc_size != 0:\n #add more pages to produce cache miss\n\n #for statistics\n # print('//cur_malloc_size: %d' % cur_malloc_size)\n # self.malloc_size_list.append(cur_malloc_size)\n kv_tmp = key_value(op.base, cur_malloc_size + 1024*1024)\n kv_tmp.add_to_list_max(self.malloc_reg_list)\n\n #self.dist_list: dist registers\n #self.dist_reg_cursor_list: last index value seen of a certain src register\n count = 0\n for op_str in addr_op_list:\n #print(op_str)\n if count == 0:\n cur_type = 'base'\n reg_value = ('%%[input_%s_%d]' % (op.base, self.block_num))\n elif count == 1:\n cur_type = 'offset'\n reg_value = ('#%d' % offset_val)\n elif count == 2:\n cur_type = 'scale'\n print('ERROR: scale not supported!')\n count += 1\n if cur_type == 'offset':\n ins_str = ('mov %s, %s' % (op_str, reg_value))\n ins_kv = key_value(ins_str, asm_index)\n ins_kv.add_to_list(self.insert_list)\n continue\n handled = False\n kv_tmp = key_value(op_str, -1)\n #key_value.show_list(self.dist_reg_cursor_list)\n #last_index = kv_tmp.get_first_index(self.dist_reg_cursor_list)\n last_index = self.reg_num_in_list(kv_tmp, self.dist_reg_cursor_list)\n if last_index != -1:\n #print('no insert')\n last_index = self.dist_reg_cursor_list[last_index].value\n else:\n ins_str = ('mov %s, %s' % (op_str, reg_value))\n #print('insert:')\n #print(ins_str)\n ins_kv = key_value(ins_str, asm_index)\n ins_kv.add_to_list(self.insert_list)\n handled = True\n# list_tmp = self.dist_list[(last_index + 1):asm_index]\n #base_index: shows if the dist_reg was modified between last seen and current asm\n# base_index = kv_tmp.get_first_index(self.dist_list[(last_index):asm_index])\n #print('\\nsdfwegeawfw')\n #print(self.asm_list[asm_index].str)\n #print(op_str)\n #key_value.show_list(self.dist_list[(last_index):asm_index])\n reg_modified = self.reg_num_in_list(kv_tmp, self.dist_list[(last_index):asm_index])\n #print('modified')\n #print(reg_modified)\n if reg_modified != -1 and handled == False:\n ins_str = ('mov %s, %s' % (op_str, reg_value))\n ins_kv = key_value(ins_str, asm_index)\n ins_kv.add_to_list(self.insert_list)\n kv_tmp.value = asm_index\n kv_tmp.add_to_list_max(self.dist_reg_cursor_list)\n elif 'b.' in self.asm_list[asm_index].instr:\n ble_ins_str = ('%s OUT_%d' % (self.asm_list[asm_index].instr, self.block_num))\n #replace b.le #+0x2b40 with b.le OUT\n self.asm_list_insert(asm_index, ble_ins_str)\n self.asm_list_remove(asm_index + 1)\n ins_kv_out = key_value(('OUT_%d:' % self.block_num), asm_index + 1)\n self.insert_list.append(ins_kv_out)\n ins_kv_nop = key_value('nop', asm_index + 1)\n self.insert_list.append(ins_kv_nop)\n #key_value.show_list(self.dist_list)\n #print('//average malloc size: %f' % mean(self.malloc_size_list))\n\n def reg_num_in_list(self, kv_cur_reg, sub_dist_list):\n kv_tmp = key_value(kv_cur_reg.key.replace('w', 'x'), kv_cur_reg.value)\n base_index_x = kv_tmp.get_first_index(sub_dist_list)\n if base_index_x != -1:\n return base_index_x\n kv_tmp.key = kv_tmp.key.replace('x', 'w')\n base_index_w = kv_tmp.get_first_index(sub_dist_list)\n if base_index_w != -1:\n return base_index_w\n return -1\n\n\n\n\n def gen_output(self):\n print('\\t\\t:')\n\n def gen_input(self):\n print('\\t\\t:', end = '')\n is_first = True\n for item in self.malloc_reg_list:\n ######## DO NOT SUPPORT VECTORS ##########\n if '.' in item.key or 'v' in item.key:\n continue\n if is_first:\n sym = ''\n is_first = False\n else:\n sym = ','\n print(sym,end='')\n print('[input_%s_%d] \"r\" (ptr_%s_%d_in)' % (item.key, self.block_num, item.key, self.block_num), end='')\n print('')\n\n def gen_clobbers(self): \n dist_set = set([])\n print('\\t\\t',end='')\n #print('gen_clobbers')\n #key_value.show_list(self.dist_list)\n for item in self.dist_list:\n dist_set.add(item.key)\n for item in self.dist_list2:\n dist_set.add(item.key)\n is_colon = True\n for item in dist_set:\n ######## DO NOT SUPPORT VECTORS ##########\n if not (('x' in item) or ('w' in item)):\n continue\n if '#' in item:\n continue\n if is_colon:\n sym = ':'\n is_colon = False\n else:\n sym = ','\n print(sym,end='')\n print('\"%s\"' % item, end='')\n print('')\n\n def gen_asm_tail(self):\n self.gen_output()\n self.gen_input()\n self.gen_clobbers()\n\n def gen_inline_asm(self):\n# print('\\tgettimeofday(&tv_begin, NULL);')\n print('\\tfor(long i = 0;i < %d;i++)\\n\\t{' % self.hotness)\n print('\\tasm volatile(')\n self.print_asm()\n self.gen_asm_tail()\n print('\\t);')\n for item in self.malloc_reg_list:\n ######## DO NOT SUPPORT VECTORS ##########\n if ('v' not in item.key) and ('.' not in item.key):\n print('\\t\\t}{static long long offset_%s_%d = 0;' % (item.key, self.block_num))\n print('\\t\\toffset_%s_%d = (offset_%s_%d + %d) %% (%d - 8192);' % (item.key, self.block_num, item.key, self.block_num,self.offset_step, item.value))\n print('\\t\\tptr_%s_%d_in = ptr_%s_%d + offset_%s_%d;' % (item.key, self.block_num, item.key, self.block_num, item.key, self.block_num))\n print('\\t}')\n# print('\\tgettimeofday(&tv_end, NULL);')\n# print('\\ttimersub(&tv_end, &tv_begin, &tv_sub);')\n# print('\\ttimeradd(&tv_sum, &tv_sub, &tv_sum);')\n\n\nclass gen_code:\n gen_malloc = []\n gen_free = []\n exclude_blk = (999999,)\n# exclude_blk = (1877,)\n exclude_blk = (1931,)#641\n def __init__(self):\n self.ab_loaded = False\n self.ab_list = []\n self.exclude_blk = gen_code.exclude_blk\n self.start_blk = 0\n self.count_limit = 50000\n self.print_flag = False\n #number of blocks in a single c file:\n self.split_size = 3\n self.fixed_hotness = 1\n self.full_loop = 1\n self.asm_loop_scale = 1/float(10000)\n self.offset_step = 1024\n\n @classmethod\n def add_gen_malloc(self, gen_malloc_list):\n gen_code.gen_malloc = gen_code.gen_malloc + gen_malloc_list\n \n @classmethod\n def add_gen_free(self, gen_free_list):\n gen_code.gen_free = gen_code.gen_free + gen_free_list\n\n #load asm file, asm orgnized as blocks seperated by empty lines\n #There must be at least one empty line at the end of asm file\n def load_asm(self, bench_name):\n f = open('%s.asm' % bench_name)\n f_hotness = open('%s.hotness' % bench_name)\n ins_list = []\n line = f.readline()\n block_count = 0\n while line:\n if len(line) <= 2 or (not line):\n if (block_count < self.start_blk):\n block_count += 1\n ins_list = []\n line = f.readline()\n continue\n ab_item = asm_block(None)\n ab_item.block_num = block_count\n ab_item.load_list(ins_list)\n ab_item.offset_step = self.offset_step\n line_hotness = f_hotness.readline()\n #print(line_hotness)\n ab_item.hotness = float(line_hotness) * self.asm_loop_scale + 1\n# ab_item.hotness = self.fixed_hotness\n self.ab_list.append(ab_item)\n if (block_count >= self.start_blk + self.count_limit - 1):\n break\n block_count += 1\n #for statistics\n # print('//instructions: %d' % len(ins_list))\n ins_list = []\n# ggcc.collect()\n line = f.readline()\n continue\n #msr and mrs are handled here, because they look like this:mrs x20, (unknown)\n line = line.replace('(unknown)', 'fpcr')\n line = re.sub(u\"\\\\(.*?\\\\)\", \"\", line).replace('\\n', '') \n #pc is handled here, because it's hard to put it anywhere else\n if 'pc+' in line:\n pc_line_list = line.split()\n for i in range(len(pc_line_list)):\n if 'pc+' in pc_line_list[i]:\n pc_line_list[i] = '[sp, #17]'\n line = ' '.join(pc_line_list)\n\n ins_list.append(line.lstrip())\n line = f.readline()\n f.close()\n f_hotness.close()\n self.ab_loaded = True\n\n def gen_c_file_head(self):\n print('#include \\n#include \\n#include \\nint main(void)\\n{')\n print('\\tsrand((unsigned)time(NULL));\\n\\tstruct timeval tv_begin, tv_end, tv_sum, tv_sub;')\n print('\\ttv_sum.tv_sec = 0;\\n\\ttv_sum.tv_usec = 0;')\n def gen_c_file_tail(self):\n print('\\tprintf(\"Finished!\\\\n\");')\n print('\\tprintf(\"Total time:\\\\n\\\\ttv_sum.tv_sec = %ld, tv_sum.tv_usec = %ld\\\\n\", tv_sum.tv_sec, tv_sum.tv_usec);')\n print('\\treturn 0;\\n}')\n print('/////////////////// END OF FILE ///////////////////')\n def gen_c_file(self, start, count):\n self.start_blk = start\n self.count_limit = count\n self.gen_c_file_head()\n end_of_file = True\n for item in gen_code.gen_malloc:\n blk_num = int(item.split('_')[2].split()[0])\n if blk_num < self.start_blk:\n continue\n if (blk_num > self.start_blk + self.count_limit - 1):\n break\n print(item)\n print('\\tgettimeofday(&tv_begin, NULL);')\n print('for(int full_loop = 0;full_loop < %d;full_loop++)\\n{' % self.full_loop)\n blk_count = 0\n for item in self.ab_list:\n if blk_count < self.start_blk:\n blk_count += 1\n continue\n ########## DO NOT SUPPORT 339th block ###########\n if blk_count in self.exclude_blk:\n blk_count += 1\n continue\n if (blk_count > self.start_blk + self.count_limit - 1):\n end_of_file = False\n break\n\n if self.print_flag:\n print('\\tprintf(\"Block: %d \\\\n\");' % blk_count)\n else:\n print('\\t//printf(\"Block: %d \\\\n\");' % blk_count)\n\n# item.gen_prep_mem()\n item.gen_inline_asm()\n# item.gen_free_mem()\n blk_count += 1\n print('}////// END OF FULL_LOOP')\n print('\\tgettimeofday(&tv_end, NULL);')\n print('\\ttimersub(&tv_end, &tv_begin, &tv_sub);')\n print('\\ttimeradd(&tv_sum, &tv_sub, &tv_sum);')\n for item in gen_code.gen_free:\n blk_num = int(item.split('_')[2].split(')')[0])\n if blk_num < self.start_blk:\n continue\n if (blk_num > self.start_blk + self.count_limit - 1):\n break\n print(item)\n self.gen_c_file_tail()\n #if it is the end of file, read cannot be continued, return False, otherwise return True\n return (not end_of_file)\n\n \n\ngc = gen_code()\ngc.offset_step = 1024\n#gc.fixed_hotness = 800\ngc.full_loop = 20\ngc.asm_loop_scale = 1/float(5000)\ngc.start_blk = 0\ngc.load_asm('600.perlbench_s')\n#gc.load_asm('602.gcc_s')\n#gc.load_asm('605.mcf_s')\n#gc.load_asm('620.omnetpp_s')\n#gc.load_asm('623.xalancbmk_s')\n#gc.load_asm('625.x264_s')\n#gc.load_asm('631.deepsjeng_s')\n#gc.load_asm('641.leela_s')\n#gc.load_asm('648.exchange2_s')\n#gc.load_asm('657.xz_s')\n#gc.load_asm('test')\n#blk_start = 0\n#blocks per file, 2000 is the maximum number:\nblk_count = 5000\nfile_count = 100\ngc.print_flag = False\n#gc.print_flag = True\n\nblk_start = gc.start_blk\n#blk_count = 1\n#file_count = 1\n\n#do not modify loop_count\nloop_count = 0\nwhile True:\n if loop_count >= file_count:\n break\n have_next = gc.gen_c_file(blk_start, blk_count)\n if not have_next:\n break\n blk_start += blk_count\n loop_count += 1\n#print(len(gc.ab_list))\n#gc.load_asm('test.asm')\n#gc.ab.show()\n","sub_path":"gen_asm.py","file_name":"gen_asm.py","file_ext":"py","file_size_in_byte":44907,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"177018184","text":"import os\nimport pandas as pd\nimport numpy as np\nimport azimuthal_average.common as common\nimport azimuthal_average.data_loading as dl\nfrom azimuthal_average.data_types import (CartesianVector, CylindricalVector,\n SymmetricCartesianTensor,\n SymmetricCylindricalTensor)\n\n\ndef get_cartesian_to_cylindrical_rotation_matrix(radial_vector):\n sin_t, cos_t = radial_vector.get_sin_t_and_cos_t()\n return np.array(\n [[cos_t, sin_t, 0],\n [-sin_t, cos_t, 0],\n [0, 0, 1]]\n )\n\n\ndef get_rotation_matrix(theta):\n return np.array(\n [[np.cos(theta), np.sin(theta), 0],\n [-np.sin(theta), np.cos(theta), 0],\n [0, 0, 1]]\n )\n\n\ndef write_intermediate_file(dir_, slice_number, slice):\n common.check_create_dir(dir_)\n intermediate_file = f\"cyl_clice_{slice_number}.csv\"\n intermediate_file = os.path.join(dir_, intermediate_file)\n slice.to_csv(intermediate_file, sep=\",\")\n\n\ndef update_running_average(running_average, n, new_obs):\n \"\"\"Updates a running average while avoiding large values and provoke overflow.\n\n Parameters\n ----------\n cumulative_avg: value of the cumulative average so far\n n: Number of samples including new observation\n new_obs: New observation\"\"\"\n a = 1/n\n b = 1 - a\n return a*new_obs + b*running_average\n\n\ndef process_slice(slice_df, slice_number, theta, running_average, copy=True,\n write_intermediate=False, csv_dir=\".\"):\n\n\n cylindrical_slice_df = transform_df_to_cylindric_coordinates(slice_df,\n theta,\n copy)\n cylindrical_slice = cylindrical_slice_df.to_numpy()\n if running_average is None:\n running_average = cylindrical_slice\n running_average = update_running_average(running_average, slice_number+1,\n cylindrical_slice)\n if write_intermediate:\n intermediate_dir = os.path.join(csv_dir, \"intermediate\")\n write_intermediate_file(intermediate_dir,\n slice_number, cylindrical_slice_df)\n return running_average, cylindrical_slice_df\n\n\ndef calculate_slice_theta(slice_number, total_slices):\n return (slice_number/total_slices)*np.pi*2\n\n\ndef take_azimuthal_average(csv_dir, write_intermediate=False, copy=True):\n \"\"\"Take the azimuthal average of all the csv files within a given directory.\n\n Args:\n csv_dir (str): Path to directory containing \"\"\"\n csv_list = dl.get_csv_files_list(csv_dir)\n total_slices = len(csv_list)\n running_average = None\n for slice_number, csv_file in enumerate(csv_list):\n print(\"Transforming\", csv_file)\n slice_df = dl.load_single_csv_file_as_df(csv_file)\n theta = calculate_slice_theta(slice_number, total_slices)\n running_average, cylindrical_slice_df = process_slice(\n slice_df, slice_number, theta, running_average, copy,\n write_intermediate)\n cols = cylindrical_slice_df.columns\n idx = cylindrical_slice_df.index\n return pd.DataFrame(data=running_average, columns=cols, index=idx)\n\n\ndef transform_df_to_cylindric_coordinates(dataframe, theta, copy=True):\n \"\"\"Transforms dataframe to cylindrical coordinates\n\n Args:\n dataframe (DataFrame): Dataframe containing a cartesian slice\n theta (float): Angle of rotation in radians.\"\"\"\n \"\"\"Initialize output df\"\"\"\n if copy:\n transformed_df = dataframe.copy()\n else:\n transformed_df = dataframe\n \"Transform coordinate positions to cylindrical\"\n print(\"Transforming coordinate positions...\")\n coords_df = transform_coordinates_to_cylindrical(dataframe)\n \"Transform velocity to cylindrical coordinates\"\n print(\"Transforming velocity vectors...\")\n u_cyl_df = transform_velocity_to_cylindrical(dataframe, theta)\n \"Transform Reynolds tensor to cylindrical coordinates\"\n print(\"Transforming stress tensors..\")\n r_cyl_df = transform_stress_tensor_to_cylindrical(dataframe, theta)\n print(\"Transformation completed.\")\n dfs_to_concat = [coords_df, u_cyl_df, r_cyl_df]\n transformed_df = pd.concat([transformed_df, *dfs_to_concat], axis=1)\n wall_shear_stress_labels = [f\"wallShearStressMean_{i}\" for i in range(3)]\n return transformed_df.drop(\n columns=[\n \"Points_Magnitude\",\n \"UMean_Magnitude\",\n \"UPrime2Mean_Magnitude\",\n \"wallShearStressMean_Magnitude\",\n \"yPlusMean\",\n \"Point ID\",\n *common.paraview_cart_coords(),\n *wall_shear_stress_labels,\n *common.r_stress_paraview_cart_coords(),\n *common.umean_paraview_cart_coords()\n ],\n errors=\"ignore\"\n )\n\n\ndef transform_coordinates_to_cylindrical(dataframe):\n cart_pos_array = dataframe[common.paraview_cart_coords()].to_numpy()\n cart_pos_vectors = CartesianVector(cart_pos_array)\n radial_pos = np.sqrt(cart_pos_vectors.x**2 + cart_pos_vectors.y**2)\n axial_pos = cart_pos_vectors.z\n return pd.DataFrame(data={\"r\": radial_pos, \"z\": axial_pos})\n\n\ndef transform_velocity_to_cylindrical(dataframe, theta):\n u_keys = common.umean_paraview_cart_coords()\n u_array = dataframe[u_keys].to_numpy()\n u_cart_vectors = CartesianVector(vector_array=u_array)\n return (u_cart_vectors\n .convert_to_cylindrical(theta=theta)\n .as_dataframe(prefix=\"u_mean\"))\n\n\ndef transform_stress_tensor_to_cylindrical(dataframe, theta):\n cart_stress_tensors = SymmetricCartesianTensor(\n dataframe[common.r_stress_paraview_cart_coords()].to_numpy()\n )\n cyl_stress_tensors = cart_stress_tensors.convert_to_cylindrical(theta)\n return cyl_stress_tensors.as_dataframe(prefix=\"R\")\n","sub_path":"azimuthal_average/processing.py","file_name":"processing.py","file_ext":"py","file_size_in_byte":5852,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"484962022","text":"import unittest\nimport os\nimport json\nimport logging\nfrom ibm_watson_machine_learning.tests.utils import get_wml_credentials, get_cos_credentials, get_space_id\nfrom ibm_watson_machine_learning.tests.utils.cleanup import space_cleanup\nfrom ibm_watson_machine_learning import APIClient\n\n\nclass TestWMLClientWithSpark(unittest.TestCase):\n deployment_uid = None\n model_uid = None\n scoring_url = None\n definition_url = None\n space_name = 'tests_sdk_space'\n model_meta = None\n pipeline_meta = None\n model_path = os.path.join('.', 'svt', 'artifacts', 'heart-drug-sample', 'drug-selection-model.tgz')\n pipeline_path = os.path.join('.', 'svt', 'artifacts', 'heart-drug-sample', 'drug-selection-pipeline.tgz')\n meta_path = os.path.join('.', 'svt', 'artifacts', 'heart-drug-sample', 'drug-selection-meta.json')\n logger = logging.getLogger(__name__)\n\n @classmethod\n def setUpClass(cls) -> None:\n \"\"\"\n Load WML credentials from config.ini file based on ENV variable.\n \"\"\"\n\n cls.wml_credentials = get_wml_credentials()\n\n cls.wml_client = APIClient(wml_credentials=cls.wml_credentials)\n\n if not cls.wml_client.ICP:\n cls.cos_credentials = get_cos_credentials()\n cls.cos_endpoint = cls.cos_credentials.get('endpoint_url')\n cls.cos_resource_instance_id = cls.cos_credentials.get('resource_instance_id')\n\n cls.wml_client = APIClient(wml_credentials=cls.wml_credentials)\n cls.project_id = cls.wml_credentials.get('project_id')\n\n with open(TestWMLClientWithSpark.meta_path) as json_data:\n metadata = json.load(json_data)\n\n TestWMLClientWithSpark.model_meta = metadata['model_meta']\n TestWMLClientWithSpark.pipeline_meta = metadata['pipeline_meta']\n\n def test_00a_space_cleanup(self):\n space_cleanup(self.wml_client,\n get_space_id(self.wml_client, self.space_name,\n cos_resource_instance_id=self.cos_resource_instance_id),\n days_old=7)\n TestWMLClientWithSpark.space_id = get_space_id(self.wml_client, self.space_name,\n cos_resource_instance_id=self.cos_resource_instance_id)\n\n # if self.wml_client.ICP:\n # self.wml_client.set.default_project(self.project_id)\n # else:\n self.wml_client.set.default_space(self.space_id)\n\n\n def test_3_publish_model(self):\n TestWMLClientWithSpark.logger.info(\"Publishing spark model ...\")\n self.wml_client.repository.ModelMetaNames.show()\n\n sw_spec_id = self.wml_client.software_specifications.get_id_by_name(\"spark-mllib_2.4\")\n\n model_props = {\n self.wml_client.repository.ModelMetaNames.NAME: \"SparkModel-from-tar\",\n self.wml_client.repository.ModelMetaNames.TYPE: \"mllib_2.4\",\n self.wml_client.repository.ModelMetaNames.SOFTWARE_SPEC_UID: sw_spec_id,\n self.wml_client.repository.ModelMetaNames.TRAINING_DATA_REFERENCES:\n [\n {\n 'type': 's3',\n 'connection': {\n 'endpoint_url': 'not_applicable',\n 'access_key_id': 'not_applicable',\n 'secret_access_key': 'not_applicable'\n },\n 'location': {\n 'bucket': 'not_applicable'\n },\n 'schema': {\n 'id': '1',\n 'type': 'struct',\n 'fields': [{\n 'name': 'AGE',\n 'type': 'float',\n 'nullable': True,\n 'metadata': {\n 'modeling_role': 'target'\n }\n }, {\n 'name': 'SEX',\n 'type': 'string',\n 'nullable': True,\n 'metadata': {}\n }, {\n 'name': 'CHOLESTEROL',\n 'type': 'string',\n 'nullable': True,\n 'metadata': {}\n }, {\n 'name': 'BP',\n 'type': 'string',\n 'nullable': True,\n 'metadata': {}\n }, {\n 'name': 'NA',\n 'type': 'float',\n 'nullable': True,\n 'metadata': {}\n }, {\n 'name': 'K',\n 'type': 'float',\n 'nullable': True,\n 'metadata': {}\n }]\n }\n }\n ]}\n\n\n print('XXX' + str(model_props))\n published_model = self.wml_client.repository.store_model(model=self.model_path, meta_props=model_props)\n print(\"Model details: \" + str(published_model))\n\n TestWMLClientWithSpark.model_uid = self.wml_client.repository.get_model_uid(published_model)\n TestWMLClientWithSpark.logger.info(\"Published model ID:\" + str(TestWMLClientWithSpark.model_uid))\n self.assertIsNotNone(TestWMLClientWithSpark.model_uid)\n\n def test_4_get_details(self):\n TestWMLClientWithSpark.logger.info(\"Get model details\")\n details = self.wml_client.repository.get_details(self.model_uid)\n print(details)\n TestWMLClientWithSpark.logger.debug(\"Model details: \" + str(details))\n self.assertTrue(\"SparkModel\" in str(details))\n\n def test_5_create_deployment(self):\n TestWMLClientWithSpark.logger.info(\"Create deployment\")\n deployment = self.wml_client.deployments.create(self.model_uid, meta_props={self.wml_client.deployments.ConfigurationMetaNames.NAME: \"best-drug model deployment\",self.wml_client.deployments.ConfigurationMetaNames.ONLINE: {}})\n TestWMLClientWithSpark.logger.info(\"model_uid: \" + self.model_uid)\n TestWMLClientWithSpark.logger.debug(\"Online deployment: \" + str(deployment))\n TestWMLClientWithSpark.scoring_url = self.wml_client.deployments.get_scoring_href(deployment)\n TestWMLClientWithSpark.deployment_uid = self.wml_client.deployments.get_uid(deployment)\n self.assertTrue(\"online\" in str(deployment))\n\n def test_6_get_deployment_details(self):\n TestWMLClientWithSpark.logger.info(\"Get deployment details\")\n deployment_details = self.wml_client.deployments.get_details(TestWMLClientWithSpark.deployment_uid)\n print(deployment_details)\n self.assertTrue('best-drug model deployment' in str(deployment_details))\n\n def test_6_score(self):\n TestWMLClientWithSpark.logger.info(\"Score the model\")\n scoring_data = {\n self.wml_client.deployments.ScoringMetaNames.INPUT_DATA: [\n {\n \"fields\": [\"AGE\", \"SEX\", \"BP\", \"CHOLESTEROL\", \"NA\", \"K\"],\n \"values\": [[20.0, \"F\", \"HIGH\", \"HIGH\", 0.71, 0.07], [55.0, \"M\", \"LOW\", \"HIGH\", 0.71, 0.07]]\n }\n ]\n }\n\n predictions = self.wml_client.deployments.score(TestWMLClientWithSpark.deployment_uid, scoring_data)\n print(predictions)\n self.assertTrue(\"predictedLabel\" in str(predictions))\n\n def test_7_delete_deployment(self):\n TestWMLClientWithSpark.logger.info(\"Delete deployment\")\n self.wml_client.deployments.delete(TestWMLClientWithSpark.deployment_uid)\n\n def test_8_delete_model(self):\n TestWMLClientWithSpark.logger.info(\"Delete model\")\n self.wml_client.repository.delete(TestWMLClientWithSpark.model_uid)\n\n\nif __name__ == '__main__':\n unittest.main()\n","sub_path":"venv/Lib/site-packages/ibm_watson_machine_learning/tests/svt/V4test_spark_mllib_from_tar_gz.py","file_name":"V4test_spark_mllib_from_tar_gz.py","file_ext":"py","file_size_in_byte":8134,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"476784616","text":"from bs4 import BeautifulSoup\nfrom myio import IO\nfrom const import *\nfrom logger import logger\n\nclass Result():\n def __init__(self, html):\n self.soup = BeautifulSoup(html, \"html.parser\")\n\n def get_list(self, save_format=\"csv\"):\n array = []\n items = self.soup.find(\"table\", \"itg gltm\").findAll(\"div\", \"glink\")\n for i in items:\n title = i.text\n link = i.parent.get(\"href\")\n d = {\"title\": title, \"link\": link}\n array.append(d)\n\n if save_format is None: continue\n io=IO(OUT_FILE_NAME)\n if io.link_saved(link): continue\n if save_format == \"csv\": io.save_link_to_csv(d)\n return array\n\n def get_last_page_no(self):\n nav = self.soup.find(\"table\", \"ptt\").findAll(\"td\")\n return int(nav[len(nav) - 2].text)\n\n def get_item_cnt(self):\n return len(self.soup.find(\"table\", \"itg gltm\").findAll(\"tr\"))-1\n","sub_path":"result.py","file_name":"result.py","file_ext":"py","file_size_in_byte":944,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"121785066","text":"#!/usr/bin/python3\r\n# -*- coding: utf-8 -*-\r\n \r\ndosya=open(\"lagrange.txt\")\r\ndegerler = []\r\n \r\nfor line in dosya.readlines():\r\n line = line.rstrip('\\n').split(' ')\r\n degerler.append(line)\r\ndosya.close()\r\n \r\nx = float(input(\"hangi değerin hesaplanmasını istiyorsunuz: \"))\r\n\r\nfor m in range(len(degerler)):\r\n for n in range(len(degerler[0])):\r\n degerler[m][n]=float(degerler[m][n])\r\n\r\nsonuc=0\r\nfor i in range(len(degerler[0])):\r\n pay_carpimi=1\r\n payda_carpimi=1\r\n for j in range(len(degerler[0])):\r\n if(i==j):\r\n continue\r\n else:\r\n pay_carpimi=pay_carpimi*(x-degerler[0][j])\r\n payda_carpimi=payda_carpimi*(degerler[0][i]-degerler[0][j])\r\n sonuc=sonuc+((pay_carpimi/payda_carpimi)*degerler[1][i])\r\nprint(sonuc)\r\n","sub_path":"lagrange.py","file_name":"lagrange.py","file_ext":"py","file_size_in_byte":786,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"422857868","text":"\"\"\"Exercício Python 095: Aprimore o desafio 93 para que ele funcione com vários jogadores,\nincluindo um sistema de visualização de detalhes do aproveitamento de cada jogador.\"\"\"\nhistórico = dict()\ntemp = dict()\ngols = list()\ntime = list()\nwhile True:\n histórico['jogador'] = str(input('Nome do jogador: ' ))\n qde_partidas = int(input(f'Quantas partidas o {histórico[\"jogador\"]} jogou? '))\n for i in range(0, qde_partidas):\n gols.append(int(input(f' Quantos gols na partida {i+1}? ')))\n histórico['gols'] = gols[:]\n histórico['total'] = sum(gols)\n gols.clear()\n time.append(histórico.copy())\n temp = histórico.copy()\n histórico.clear()\n continua = str(input('Quer continuar? [S/N] ')).upper().strip()[0]\n while continua not in 'SN':\n continua = str(input('Quer continuar? [S/N] ')).upper().strip()[0]\n if continua == 'N':\n break\nprint(time)\nprint('-=' * 25)\nprint(f'{\"Cod\":<5}', end='')\nfor i in temp.keys():\n print(f'{i:<20}', end='')\nprint()\nprint('-' * 50)\nfor k, v in enumerate(time):\n print(f'{k:<5}', end='')\n for i in v.values():\n print(f'{str(i):<20}', end='')\n print()\nprint('-' * 50)\nwhile True:\n busca = int(input('Mostrar dados de qual jogador? (999 para parar) '))\n if busca == 999:\n break\n if busca >= len(time):\n print(f'Erro! Não existe jogador com código {busca}.')\n else:\n print(f' -- LEVANTAMENTO DO JOGADOR {time[busca][\"jogador\"]}:')\n for i, g in enumerate(time[busca]['gols']):\n print(f' No jogo {i+1} fez {g} gols')\n print('-' * 40)\nprint('<< VOLTE SEMPRE >>')\n\n\n\"\"\"print('-=' * 30)\nfor k, v in histórico.items():\n print(f'O campo {k} tem o valor {v}.')\nprint('-=' * 30)\nprint(f'O jogador {histórico[\"jogador\"]} jogou {len(histórico[\"gols\"])} partidas.')\nfor i, v in enumerate(histórico['gols']):\n print(f' -> Na partida {i+1}, fez {v} gols.')\nprint(f'Foi um total de {histórico[\"total\"]} gols.')\nprint('-=' * 30)\"\"\"","sub_path":"ex095.py","file_name":"ex095.py","file_ext":"py","file_size_in_byte":2004,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"588190723","text":"import json\r\nimport sys\r\nimport pandas as pd\r\nimport numpy as np\r\nimport pandas as pd\r\nimport numpy as np\r\nfrom nltk.corpus import stopwords\r\nfrom sklearn.metrics.pairwise import linear_kernel\r\nfrom sklearn.metrics.pairwise import cosine_similarity\r\nfrom sklearn.feature_extraction.text import CountVectorizer\r\nfrom sklearn.feature_extraction.text import TfidfVectorizer\r\nfrom nltk.tokenize import RegexpTokenizer\r\nimport re\r\nimport string\r\nimport random\r\nfrom PIL import Image\r\nimport requests\r\nfrom io import BytesIO\r\nimport matplotlib.pyplot as plt\r\n\r\n\r\ndf = pd.read_csv(\"book.csv\")\r\n\r\n## Get a cleaned description of the books by removing non Ascii characters,making characters lowercase\r\n## removing stop_words,punctuations and all as this won't be accountable for book reccomendation\r\n\r\n# Function for removing NonAscii characters\r\ndef remove_non_ascii(s):\r\n return \"\".join(i for i in s if ord(i)<128)\r\n\r\n# Function for converting into lower case\r\ndef make_lower_case(text):\r\n return text.lower()\r\n\r\n# Function for removing stop words\r\ndef remove_stop_words(text):\r\n text = text.split()\r\n stops = set(stopwords.words(\"english\"))\r\n text = [w for w in text if not w in stops]\r\n text = \" \".join(text)\r\n return text\r\n\r\n# Function for removing punctuation\r\ndef remove_punctuation(text):\r\n tokenizer = RegexpTokenizer(r'\\w+')\r\n text = tokenizer.tokenize(text)\r\n text = \" \".join(text)\r\n return text\r\n\r\n# Function for removing the html tags\r\ndef remove_html(text):\r\n html_pattern = re.compile('<.*?>')\r\n return html_pattern.sub(r'', text)\r\n \r\n# Applying all the functions in description and storing as a cleaned_desc\r\ndf['cleaned_desc'] = df['description'].apply(remove_non_ascii)\r\ndf['cleaned_desc'] = df.cleaned_desc.apply(func = make_lower_case)\r\ndf['cleaned_desc'] = df.cleaned_desc.apply(func = remove_stop_words)\r\ndf['cleaned_desc'] = df.cleaned_desc.apply(func=remove_punctuation)\r\ndf['cleaned_desc'] = df.cleaned_desc.apply(func=remove_html)\r\n\r\n# Function for recommending books based on Book title\r\ndef recommend_by_title(title, genre):\r\n data = df2.loc[df2['genre'] == genre] #Get the sub-dataframe having the same genre\r\n data.reset_index(level = 0, inplace = True) #Reset the indices starting from zero\r\n # Convert the index into series\r\n #Get the series of books from our sub-datafram having same genre and give their title as their index\\\r\n #as supplied in index parameter of Series\r\n indices = pd.Series(data.index, index = data['title']) \r\n #Converting the book title into vectors by using bigram\r\n tf = TfidfVectorizer(analyzer='word', ngram_range=(2, 2), min_df = 1, stop_words='english')\r\n tfidf_matrix = tf.fit_transform(data['title'])\r\n # Calculating the similarity measures based on Cosine Similarity\r\n sg = cosine_similarity(tfidf_matrix, tfidf_matrix)\r\n # Get the index corresponding to original_title\r\n idx = indices[title]\r\n # Get the pairwsie similarity scores \r\n sig = list(enumerate(sg[idx]))\r\n # Sort the books\r\n #We sort in reverse order as cosine of small angles is larger thus the difference will be small\r\n sig = sorted(sig, key=lambda x: x[1], reverse=True) \r\n # Scores of the 5 most similar books \r\n sig = sig[1:6] #Sublist from 1 to 5 as index 0 will be the same book\r\n # Get the respective book indicies\r\n movie_indices = [i[0] for i in sig]\r\n # Top 5 books having the same genre\r\n # Here we pass the indices of the matching books in iloc method as parameter(integer or list of integers)\r\n print(movie_indices)\r\n \r\n \r\ndef recommend_by_desc(title, genre):\r\n global rec\r\n data = df.loc[df['genre'] == genre] \r\n data.reset_index(level = 0, inplace = True)\r\n # Convert the index into series\r\n indices = pd.Series(data.index, index = data['name'])\r\n #Converting the book description into vectors and used bigram\r\n tf = TfidfVectorizer(analyzer='word', ngram_range=(2, 2), min_df = 1, stop_words='english')\r\n tfidf_matrix = tf.fit_transform(data['cleaned_desc'])\r\n # Calculating the similarity measures based on Cosine Similarity\r\n \r\n sg = cosine_similarity(tfidf_matrix, tfidf_matrix)\r\n # Get the index corresponding to original_title\r\n idx = indices[title]# Get the pairwsie similarity scores \r\n sig = list(enumerate(sg[idx]))# Sort the books\r\n sig = sorted(sig, key=lambda x: x[1], reverse=True)# Scores of the 5 most similar books \r\n sig = sig[1:6]# Book indicies\r\n movie_indices = [i[0] for i in sig]\r\n # Top 5 book recommendation\r\n rec = data[['book_id']].iloc[movie_indices];\r\n return rec;\r\n \r\n\r\n\r\nn = len(sys.argv[1])\r\na = sys.argv[1].split(' ')\r\nids=[]\r\nfor i in a:\r\n search=df[['name', 'genre']].iloc[int(i)];\r\n rec = recommend_by_desc(search['name'],search['genre'])\r\n index = rec.index\r\n for i in index:\r\n ids.append(rec.at[i,'book_id'])\r\nprint(ids)\r\n","sub_path":"rs_fin_opt.py","file_name":"rs_fin_opt.py","file_ext":"py","file_size_in_byte":4899,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"16147224","text":"#####################################################\n# #\n# PROG 30 #\n# Written by Jason Scott #\n# jason.scott@mcpa-stl.org #\n# #\n# Cyber Patriot 2016 #\n# #\n# Composed in Python 2.7.12 #\n# PEP 8 Compliant #\n# #\n#####################################################\n\n# IMPORTS\nimport Tkinter as tk\nimport socket\nimport getpass as gp\nimport binascii as ba\nimport hashlib as ha\n\n# VARIABLES\nprgmWidth = 550\nprgmHeight = 480\nstates = ['normal', 'white', 'black', 'red', 'yellow', 'blue', 'enabled', 'true', 'false', 'disabled', 'on', 'off']\n\n\ndef chkit(my_string):\n m = ha.md5()\n m.update(my_string)\n return m.hexdigest()\n\n\n# CLASSES\nclass prgm(tk.Tk):\n def __init__(self, parent):\n tk.Tk.__init__(self, parent)\n self.parent = parent\n self.initialize()\n self.lbl_code = None\n self.tb_code = tk.Entry(self.step_one, width=50)\n self.tb_code.grid(row=0, column=1, columnspan=3, pady=5, sticky='WE')\n self.tb_code.configure(state=\"{}\".format(states[9]))\n self.code_val = None\n self.main_text = None\n self.sub_text = None\n self.lower_text = None\n self.detail_text = None\n self.header = None\n self.btn_ok = None\n self.step_one = None\n self.frame_header = None\n\n def initialize(self):\n self.tk.call('wm', 'iconphoto', self._w, tk.PhotoImage(file='img/icoMCPA.gif'))\n self.grid()\n self.step_one = tk.LabelFrame(self, text=\"\", bg='#FFFFFF', width=500, relief=\"flat\")\n self.step_one.grid(row=0, columnspan=7, sticky='W', padx=20, pady=5, ipadx=5, ipady=5)\n self.lbl_code = tk.Label(self.step_one, text=\"Flag:\", justify=\"left\", bg='#FFFFFF')\n self.lbl_code.grid(row=0, column=0, sticky='E', padx=5, pady=5)\n self.step_one.place(x=45, y=325)\n self.btn_ok = tk.Button(self.step_one, text='Submit', command=self.submit, width=20, bg='#003399', fg='#FFFFFF')\n self.btn_ok.grid(row=4, column=2, sticky='W', padx=5, pady=2)\n\n def submit(self):\n self.code_val = self.tb_code.get()\n if self.tb_code.get() == \"\":\n print(\"ERROR\")\n\n else:\n print(\"FLAG: {}\".format(chkit(self.code_val)))\n\n if self.code_val == \"\":\n win2 = tk.Tk()\n win2.withdraw()\n\n def draw_header(self):\n self.grid()\n self.frame_header = tk.LabelFrame(self, bg='#FFFFFF', relief=\"flat\")\n self.frame_header.grid(row=0, columnspan=1, sticky='E')\n self.header = tk.Label(self.frame_header, image=img_header, bg='#FFFFFF')\n self.header.grid(row=0, column=0, sticky='E')\n self.frame_header.place(x=50, y=40)\n self.main_text = tk.Label(self,\n text=\"FLAG GENERATOR\",\n justify='center',\n fg='#003399',\n font=('Helvetica', 20),\n bg='#FFFFFF')\n self.main_text.place(x=210, y=80)\n self.sub_text = tk.Label(self,\n text=\"Just plug in a string and get a flag!\",\n justify='left',\n font=('Helvetica', 10),\n bg='#FFFFFF')\n self.sub_text.place(x=210, y=110)\n\n def draw_text(self):\n self.lower_text = tk.Label(self,\n text=\"{}\".format(\n '''To generate a flag, simply enter a string into the box below. The flag\nwill return inside an IDE, and not in this window. Try it out!'''\n ),\n justify='left',\n bg='#FFFFFF',\n fg='#000000'\n )\n self.lower_text.place(x=50, y=200)\n self.detail_text = tk.Label(self,\n justify='left',\n text=\"USER:\\t{}@{}\\nIP ADDR:\\t{}\\nTITLE:\\t{}\".format(\n gp.getuser(),\n socket.gethostname(),\n socket.gethostbyname(socket.gethostname()),\n ba.unhexlify('43796265722050617472696f74')\n ), bg='#FFFFFF')\n self.detail_text.place(x=50, y=245)\n\n\n# FUNCTIONS\n\n\n# MAINLOOP\nif __name__ == '__main__':\n app = prgm(None)\n app.title('Flag Generator')\n app.configure(background='#FFFFFF')\n app.resizable(width=False, height=False)\n app.geometry('%dx%d+%d+%d' % (\n prgmWidth,\n prgmHeight,\n (app.winfo_screenwidth() / 2) - (prgmWidth / 2),\n (app.winfo_screenheight() / 2) - (prgmHeight / 2)))\n img_header = tk.PhotoImage(file='img/logoMCPA.png')\n app.draw_header()\n app.draw_text()\n app.mainloop()\n","sub_path":"prog006.py","file_name":"prog006.py","file_ext":"py","file_size_in_byte":5325,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"475525733","text":"import ipywidgets as widgets\n\ndef Read(raw, datos={'Fluido':{}, 'Solid':{}}):\n cont = 0\n for tipo in datos:\n suma = 0\n while True:\n try:\n if tipo != 'Tamaño de malla':\n datos[tipo][raw.children[cont].get_title(suma)] = raw.children[cont].children[suma].value\n else:\n datos[tipo] = raw.children[cont].value\n break\n suma += 1\n except:\n break\n cont += 1\n return datos\n\ndef ReadMesh(raw):\n cont = 0 \n data = {}\n while True:\n try:\n data[raw.children[1].get_title(cont)] = raw.children[1].children[cont].value\n except:\n break\n cont += 1\n return data","sub_path":"Simulación/App/Generalidades/Read.py","file_name":"Read.py","file_ext":"py","file_size_in_byte":768,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"436593653","text":"#!/usr/bin/env python2.7 \n# Collection of python scripts which will post their information to Twitter\n# by ewan2395 - https://github.com/ewan2395/adsb-monitoring\nimport time\nimport tweepy\nimport os\nimport sys\nfrom datetime import datetime\n\ni = datetime.now()\n\nconsumer_key = ''\nconsumer_secret = ''\naccess_token = ''\naccess_token_secret = ''\n\n# OAuth process\nauth = tweepy.OAuthHandler(consumer_key, consumer_secret)\nauth.set_access_token(access_token, access_token_secret)\n \n# Authentication\napi = tweepy.API(auth)\nnow = i.strftime('%d/%m/%Y at %H:%M - ')\ntime.sleep(60)\noutput=(now + \"ALERT: System has rebooted\" + \" | #ADSB\") \n#print(output) # debugging\napi.update_status(status=output)\n\n","sub_path":"reboot.py","file_name":"reboot.py","file_ext":"py","file_size_in_byte":692,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"279261521","text":"\n\nfrom xai.brain.wordbase.nouns._deadline import _DEADLINE\n\n#calss header\nclass _DEADLINES(_DEADLINE, ):\n\tdef __init__(self,): \n\t\t_DEADLINE.__init__(self)\n\t\tself.name = \"DEADLINES\"\n\t\tself.specie = 'nouns'\n\t\tself.basic = \"deadline\"\n\t\tself.jsondata = {}\n","sub_path":"xai/brain/wordbase/nouns/_deadlines.py","file_name":"_deadlines.py","file_ext":"py","file_size_in_byte":252,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"166922116","text":"\"\"\"\nThis module contains the classes used to manage the maps in the game. Each map\nis compound by 3 layers: background, foreground and a collision layer. Each one\nof the layers can use a different tileset, that has to be imported from the\ntiles module.\n\"\"\"\nimport pygame\nimport csv\nimport math\n\nfrom typing import Tuple, List\n\nfrom pygame import Surface\nfrom tiles import Tileset\nfrom collisions import BoundingBox\nfrom constants import TILESIZE, SCREEN_SIZE\n\nclass MapLayer:\n \"\"\"\n The map layer contains the actual information of a map, inclusing the tile\n coordinates and collision boundaries in case of a collision layer.\n This is used also to render the map in the screen.\n \"\"\"\n\n def __init__(self, filename:str, tileset:Tileset, is_collidable:bool = False):\n # Initialize values\n self.colliders: List[BoundingBox] = []\n \n # Store values\n self.filename: str = filename\n self.is_collidable: bool = is_collidable\n self.tileset: Tileset = tileset\n\n # Parse the tiles\n self.tiles = self.__parse_tiles(filename)\n\n # Parse colliders if needed\n if is_collidable:\n self.colliders = self.__parse_colliders(self.tiles)\n \n def __parse_tiles(self, filename: str):\n \"\"\"\n Load the map as a CSV file.\n \"\"\"\n with open(filename, 'r') as file:\n tiles = list(csv.reader(file))\n return tiles\n\n def __parse_colliders(self, tiles):\n \"\"\"\n Load the colliders in a CSV file.\n \"\"\"\n colliders = []\n # Iterate over rows and columns \n for row_pos, row in enumerate(self.tiles):\n for column_pos, column in enumerate(row):\n # Check if empty, if so ignore it\n if not column:\n continue\n\n # Create the bounding box\n bbox = BoundingBox(TILESIZE, TILESIZE)\n bbox.pos_x = column_pos * TILESIZE\n bbox.pos_y = row_pos * TILESIZE\n\n # Add to the list\n colliders.append(bbox)\n\n return colliders\n\n def render(self, anchor_x:int, anchor_y:int, screen_size:Tuple[int], surface:Surface):\n \"\"\"\n Will render the map on the surface provided.\n \"\"\"\n # Define the render frame for the X axis\n start_x = math.floor(anchor_x / TILESIZE)\n end_x = start_x + math.ceil(SCREEN_SIZE[0] / TILESIZE) + 1\n\n # Define the render frame for the Y axis\n end_y = len(self.tiles) - math.floor(anchor_y / TILESIZE)\n start_y = end_y - math.floor(SCREEN_SIZE[1] / TILESIZE)\n start_y = 0 if start_y < 0 else start_y\n\n # Define the anchor offset for the tiles\n anchor_x = - int(anchor_x % TILESIZE)\n\n # Iterate over rows and columns \n for row_pos, row in enumerate(self.tiles[start_y:end_y]):\n for column_pos, column in enumerate(row[start_x:end_x]):\n\n # Check if empty, if so ignore it\n if not column:\n continue\n\n # Get the positions based on tilesize\n pos_x = anchor_x + (column_pos * self.tileset.tilesize)\n pos_y = anchor_y + (row_pos * self.tileset.tilesize)\n # Blit on the screen\n surface.blit(self.tileset.get_tile(int(column)), (pos_x, pos_y))\n\n \n\nclass Map:\n \"\"\"\n Will store the full information of a map.\n \"\"\"\n def __init__(self):\n # Initialize layers\n self.foreground: MapLayer = None\n self.background: MapLayer = None\n self.colliders: MapLayer = None\n\n def load_background(self, filename:str, tileset:Tileset):\n \"\"\"\n Will load a background tileset from a CSV file.\n \"\"\"\n self.background = MapLayer(filename, tileset)\n\n def load_foreground(self, filename:str, tileset:Tileset):\n \"\"\"\n Will load a foreground tileset from a CSV file.\n \"\"\"\n self.foreground = MapLayer(filename, tileset)\n\n def load_colliders(self, filename:str, tileset:Tileset):\n \"\"\"\n Will load the collision layer from a CSV file.\n \"\"\"\n self.colliders = MapLayer(filename, tileset, True)","sub_path":"maps.py","file_name":"maps.py","file_ext":"py","file_size_in_byte":4237,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"159729448","text":"\"\"\"\nPropagator \n\"\"\"\n\nimport numpy as np\nimport csv\nimport os\nimport sys\nimport time\nimport math\nfrom scipy import special\nimport matplotlib.pyplot as plt\nimport matplotlib.pylab as plab\nimport matplotlib.gridspec as gridspec\nimport matplotlib.colors as colo\nimport matplotlib.cm as cmx\nfrom pdb import set_trace as bp\n\n\n### IMPORT MY MODULES\nimport molecularfunctions as mf\nfrom myconfig import *\nimport convertConstants as cc\npaths = os.getcwd()\n\n\n\ntimes = np.zeros([frames,len(mols)], dtype='float')\ngyration_proj= np.zeros([frames,len(mols)], dtype='float')\nG2x = np.zeros([frames,len(mols)], dtype='float')\nG2y = np.zeros([frames,len(mols)], dtype='float')\nG2z = np.zeros([frames,len(mols)], dtype='float')\nCOMx = np.zeros([frames,len(mols)], dtype='float')\nCOMy = np.zeros([frames,len(mols)], dtype='float')\nCOMz = np.zeros([frames,len(mols)], dtype='float')\nCOML1 = np.zeros([frames,len(mols)], dtype='float')\nCOMT1 = np.zeros([frames,len(mols)], dtype='float')\nCOMTx1 = np.zeros([frames,len(mols)], dtype='float')\nCOMTy1 = np.zeros([frames,len(mols)], dtype='float')\nCOMTz1 = np.zeros([frames,len(mols)], dtype='float')\nCOML2 = np.zeros([frames,len(mols)], dtype='float')\nCOMT2 = np.zeros([frames,len(mols)], dtype='float')\nCOMTx2 = np.zeros([frames,len(mols)], dtype='float')\nCOMTy2 = np.zeros([frames,len(mols)], dtype='float')\nCOMTz2 = np.zeros([frames,len(mols)], dtype='float')\npropTIMES = np.zeros([frames, frames], dtype='float')\npropL = np.zeros([frames, frames], dtype='float')\npropT = np.zeros([frames, frames], dtype='float')\ntimelinspace=np.arange(0,frames)\n\nBEGeex = np.zeros([frames,len(mols)], dtype='float')\nBEGeey = np.zeros([frames,len(mols)], dtype='float')\nBEGeez = np.zeros([frames,len(mols)], dtype='float')\nENDeex = np.zeros([frames,len(mols)], dtype='float')\nENDeey = np.zeros([frames,len(mols)], dtype='float')\nENDeez = np.zeros([frames,len(mols)], dtype='float')\nEND2eex = np.zeros([frames,len(mols)], dtype='float')\nEND2eey = np.zeros([frames,len(mols)], dtype='float')\nEND2eez = np.zeros([frames,len(mols)], dtype='float')\n\nUVNOHeex = np.zeros([frames,len(mols)], dtype='float')\nUVNOHeey = np.zeros([frames,len(mols)], dtype='float')\nUVNOHeez = np.zeros([frames,len(mols)], dtype='float')\nUVNOH2eex = np.zeros([frames,len(mols)], dtype='float')\nUVNOH2eey = np.zeros([frames,len(mols)], dtype='float')\nUVNOH2eez = np.zeros([frames,len(mols)], dtype='float')\n\nmag_diff1 = np.zeros([frames,len(mols)], dtype='float')\nmag_diff2 = np.zeros([frames,len(mols)], dtype='float')\n\nmag_diffL1 = np.zeros([frames,len(mols)], dtype='float')\nparallaxPTx = np.zeros([frames,len(mols)], dtype='float')\nparallaxPTy = np.zeros([frames,len(mols)], dtype='float')\nparallaxPTz = np.zeros([frames,len(mols)], dtype='float')\nmag_parallax = np.zeros([frames,len(mols)], dtype='float')\ndistance_parallax = np.zeros([frames,len(mols)], dtype='float')\nanglelax = np.zeros([frames,len(mols)], dtype='float')\n\ndot1 = np.zeros([frames,len(mols)], dtype='float')\ndot2 = np.zeros([frames,len(mols)], dtype='float')\ntotE= np.zeros([frames,len(mols)], dtype='float')\nHOMO= np.zeros([frames,len(mols)], dtype='float')\nLUMO= np.zeros([frames,len(mols)], dtype='float')\n\n\npos1x = np.zeros([frames,len(mols)], dtype='float')\npos1y = np.zeros([frames,len(mols)], dtype='float')\npos1z = np.zeros([frames,len(mols)], dtype='float')\npos2x = np.zeros([frames,len(mols)], dtype='float')\npos2y = np.zeros([frames,len(mols)], dtype='float')\npos2z = np.zeros([frames,len(mols)], dtype='float')\n\n\n### Need end-end distance to segment\n\nsides = [ 'c' ] #, 'r', 'l']\n\nfor ind_mol in xrange(len(mols)):\n mol = mols[ind_mol].group\n kink = mols[ind_mol].kinked\n klocation = mols[ind_mol].klocation\n \n imgfolder2=paths + '/' + imgfolder + '/diffusion' + str(mol) \n \n try:\n os.mkdir(imgfolder2)\n except:\n pass\n\n # READ IN TIME-DEP CENTER OF MASS OF HOMO \n inputfile = os.path.join(paths,datafolder,'runninghomoCOMVEL_mol' + str(mol) + '.csv')\n lhomo = mf.readinCSV(inputfile, 1)\n times[:,ind_mol] =np.asarray([x[0] for x in lhomo], dtype=\"float\") #ALREADY IN ANGSTROM\n COMx[:,ind_mol] = np.asarray([x[1] for x in lhomo], dtype=\"float\") #ALREADY IN ANGSTROM\n COMy[:,ind_mol] = np.asarray([x[2] for x in lhomo], dtype=\"float\") #ALREADY IN ANGSTROM\n COMz[:,ind_mol] = np.asarray([x[3] for x in lhomo], dtype=\"float\") #ALREADY IN ANGSTROM\n \n\n inputfile = os.path.join(paths,datafolder,'runningGyrate_mol' + str(mol) + '.csv')\n lgyrate = mf.readinCSV(inputfile, 1)\n G2x[:,ind_mol] = np.asarray([x[1] for x in lgyrate], dtype=\"float\")\n G2y[:,ind_mol] = np.asarray([x[2] for x in lgyrate], dtype=\"float\")\n G2z[:,ind_mol] = np.asarray([x[3] for x in lgyrate], dtype=\"float\")\n\n\n\n # READ IN END-to-END VECTOR(S)\n endendfile = os.path.join(paths,datafolder, 'runningENDEND_mol' + str(mol) + '.csv')\n lee = mf.readinCSV(endendfile, 1)\n times[:,ind_mol] =np.asarray([x[0] for x in lee], dtype=\"float\")\n BEGeex[:,ind_mol] = np.asarray([x[1] for x in lee], dtype=\"float\")\n BEGeey[:,ind_mol] = np.asarray([x[2] for x in lee], dtype=\"float\")\n BEGeez[:,ind_mol] = np.asarray([x[3] for x in lee], dtype=\"float\")\n ENDeex[:,ind_mol] = np.asarray([x[4] for x in lee], dtype=\"float\")\n ENDeey[:,ind_mol] = np.asarray([x[5] for x in lee], dtype=\"float\")\n ENDeez[:,ind_mol] = np.asarray([x[6] for x in lee], dtype=\"float\")\n if kink == 1:\n END2eex[:,ind_mol] = np.asarray([x[7] for x in lee], dtype=\"float\")\n END2eey[:,ind_mol] = np.asarray([x[8] for x in lee], dtype=\"float\")\n END2eez[:,ind_mol] = np.asarray([x[9] for x in lee], dtype=\"float\")\n \n\n # READ IN UNIT-VECTOR \n uvfile = os.path.join(paths,datafolder, 'runningUNITVECTOR_mol' + str(mol) + '.csv')\n luv = mf.readinCSV(uvfile, 1)\n times[:,ind_mol] =np.asarray([x[0] for x in luv], dtype=\"float\")\n UVNOHeex[:,ind_mol] = np.asarray([x[1] for x in luv], dtype=\"float\")\n UVNOHeey[:,ind_mol] = np.asarray([x[2] for x in luv], dtype=\"float\")\n UVNOHeez[:,ind_mol] = np.asarray([x[3] for x in luv], dtype=\"float\")\n if kink == 1:\n UVNOH2eex[:,ind_mol] = np.asarray([x[4] for x in luv], dtype=\"float\")\n UVNOH2eey[:,ind_mol] = np.asarray([x[5] for x in luv], dtype=\"float\")\n UVNOH2eez[:,ind_mol] = np.asarray([x[6] for x in luv], dtype=\"float\")\n\n\n infile4 = os.path.join(paths, datafolder, 'runningEnergyNOPOL_mol' + str(mol) + '.csv')\n lhen = mf.readinCSV(infile4, 1)\n totE[:,ind_mol] =np.asarray([x[1] for x in lhen], dtype=\"float\")\n HOMO[:,ind_mol] = np.asarray([x[3] for x in lhen], dtype=\"float\")\n LUMO[:,ind_mol] = np.asarray([x[4] for x in lhen], dtype=\"float\")\n\n \n # COMPUTE DISTANCE CENTER OF MASS HAS MOVED FROM LEADING-EDGE\n if kink == 1:\n distance = np.zeros([3,len(COMx[:,ind_mol])], dtype=\"float\")\n distance[0,:] = (COMx[:,ind_mol]-ENDeex[:,ind_mol])\n distance[1,:] = (COMy[:,ind_mol]-ENDeey[:,ind_mol])\n distance[2,:] = (COMz[:,ind_mol]-ENDeez[:,ind_mol])\n\n dot1[:,ind_mol] = ( distance[0,:]*UVNOHeex[:,ind_mol] + distance[1,:]*UVNOHeey[:,ind_mol] + \\\n distance[2,:]*UVNOHeez[:,ind_mol])\n\n dot2[:,ind_mol] = (distance[0,:]*UVNOH2eex[:,ind_mol] + distance[1,:]*UVNOH2eey[:,ind_mol] + \\\n (distance[2,:]*UVNOH2eez[:,ind_mol]))\n \n else:\n\n distance1 = np.zeros([3,len(COMx[:,ind_mol])], dtype=\"float\")\n distance1[0,:] = abs(COMx[:,ind_mol]-BEGeex[:,ind_mol])\n distance1[1,:] = abs(COMy[:,ind_mol]-BEGeey[:,ind_mol])\n distance1[2,:] = abs(COMz[:,ind_mol]-BEGeez[:,ind_mol])\n\n distance2 = np.zeros([3,len(COMx[:,ind_mol])], dtype=\"float\")\n distance2[0,:] = abs(COMx[:,ind_mol]-ENDeex[:,ind_mol])\n distance2[1,:] = abs(COMy[:,ind_mol]-ENDeey[:,ind_mol])\n distance2[2,:] = abs(COMz[:,ind_mol]-ENDeez[:,ind_mol])\n\n mag_diff1[:,ind_mol] = abs( distance1[0,:]*UVNOHeex[:,ind_mol] + distance1[1,:]*UVNOHeey[:,ind_mol] + \\\n distance1[2,:]*UVNOHeez[:,ind_mol])\n \n mag_diff2[:,ind_mol] = abs( distance2[0,:]*UVNOHeex[:,ind_mol] + distance2[1,:]*UVNOHeey[:,ind_mol] + \\\n distance2[2,:]*UVNOHeez[:,ind_mol])\n\n gyration_proj[:, ind_mol] = abs(G2x[:,ind_mol]*UVNOHeex[:,ind_mol] + G2y[:,ind_mol]*UVNOHeey[:,ind_mol] + \\\n G2y[:,ind_mol]*UVNOHeey[:,ind_mol])\n\n pos1x[:,ind_mol] = BEGeex[:,ind_mol] - (mag_diff1[:,ind_mol]*UVNOHeex[:,ind_mol])\n pos1y[:,ind_mol] = BEGeey[:,ind_mol] - (mag_diff1[:,ind_mol]*UVNOHeey[:,ind_mol])\n pos1z[:,ind_mol] = BEGeez[:,ind_mol] - (mag_diff1[:,ind_mol]*UVNOHeez[:,ind_mol])\n \n pos2x[:,ind_mol] = ENDeex[:,ind_mol] - (mag_diff2[:,ind_mol]*UVNOHeex[:,ind_mol])\n pos2y[:,ind_mol] = ENDeey[:,ind_mol] - (mag_diff2[:,ind_mol]*UVNOHeey[:,ind_mol])\n pos2z[:,ind_mol] = ENDeez[:,ind_mol] - (mag_diff2[:,ind_mol]*UVNOHeez[:,ind_mol])\n\n\n COMT1[:,ind_mol] = np.sqrt(COMTx1[:,ind_mol]*COMTx1[:,ind_mol]+ COMTy1[:,ind_mol]*COMTy1[:,ind_mol]+ COMTz1[:,ind_mol]*COMTz1[:,ind_mol])\n if kink == 1:\n COMT2[:,ind_mol] = np.sqrt(COMTx2[:,ind_mol]*COMTx2[:,ind_mol]+ COMTy2[:,ind_mol]*COMTy2[:,ind_mol]+ COMTz2[:,ind_mol]*COMTz2[:,ind_mol])\n\n \n COMLcent1 = sum(COML1[:,ind_mol])/len(COML1[:,ind_mol]); COMTcent1 = sum(COMT1[:,ind_mol])/len(COMT1[:,ind_mol])\n if kink == 1:\n COMLcent2 = sum(COML2[:,ind_mol])/len(COML2[:,ind_mol]); COMTcent2 = sum(COMT2[:,ind_mol])/len(COMT2[:,ind_mol])\n\n \n varLLL1 = float( sum(COML1[:,ind_mol]*COML1[:,ind_mol])/len(COML1[:,ind_mol]) - COMLcent1*COMLcent1);\n stdLLL1 = np.sqrt(abs(varLLL1))/np.sqrt(len(COML1[:,ind_mol]))\n\n varTTT1 = float(sum(COMT1[:,ind_mol]*COMT1[:,ind_mol])/len(COMT1[:,ind_mol]) - COMTcent1*COMTcent1);\n stdTTT1 = np.sqrt(abs(varTTT1))/np.sqrt(len(COMT1[:,ind_mol]))\n\n if kink == 1:\n varLLL2 = float( sum(COML2[:,ind_mol]*COML2[:,ind_mol])/len(COML2[:,ind_mol]) - COMLcent2*COMLcent2);\n stdLLL2 = np.sqrt(abs(varLLL2))/np.sqrt(len(COML2[:,ind_mol]))\n\n varTTT2 = float(sum(COMT2[:,ind_mol]*COMT2[:,ind_mol])/len(COMT2[:,ind_mol]) - COMTcent2*COMTcent2);\n stdTTT2 = np.sqrt(abs(varTTT2))/np.sqrt(len(COMT2[:,ind_mol]))\n\n for ind_sty, sty in enumerate(sides):\n\n if (sty is 'l') or (sty is 'L'):\n signsL = '(COML1[sumstep_tau][ind_mol])*1e10 < ' + str(float(COMLcent1 - 2*stdLLL1)*1e10) #COML-mu > criteria\n signsT = '(COMT1[sumstep_tau][ind_mol])*1e10 < ' + str(float(COMTcent1 - 2*stdTTT1)*1e10)\n\n if kink == 1:\n signsL2 = '(COML2[sumstep_tau][ind_mol])*1e10 < ' + str(float(COMLcent2 - 2*stdLLL2)*1e10) #COML-mu > criteria\n signsT2 = '(COMT2[sumstep_tau][ind_mol])*1e10 < ' + str(float(COMTcent2 - 2*stdTTT2)*1e10)\n \n if (sty is 'r') or (sty is 'R'):\n signsL = '(COML1[sumstep_tau][ind_mol])*1e10 > ' + str(float(COMLcent1 + 2*stdLLL1)*1e10) \n signsT = '(COMT1[sumstep_tau][ind_mol])*1e10 > ' + str(float(COMTcent1 + 2*stdTTT1)*1e10) \n\n if kink == 1:\n signsL2 = '(COML2[sumstep_tau][ind_mol])*1e10 > ' + str(float(COMLcent2 + 2*stdLLL2)*1e10) \n signsT2 = '(COMT2[sumstep_tau][ind_mol])*1e10 > ' + str(float(COMTcent2 + 2*stdTTT2)*1e10)\n \n if (sty is 'c') or (sty is 'C'):\n signsL = '((COML1[sumstep_tau][ind_mol])*1e10 < ' + str(float(COMLcent1 + 2*stdLLL1)*1e10) + ') and ((COML1[sumstep_tau][ind_mol])*1e10 > '+ str(float(COMLcent1 - 2*stdLLL1)*1e10) + ')'\n signsT = '((COMT1[sumstep_tau][ind_mol])*1e10 < ' + str(float(COMTcent1 + 2*stdTTT1)*1e10) + ') and ((COMT1[sumstep_tau][ind_mol])*1e10 > '+ str(float(COMTcent1 - 2*stdTTT1)*1e10) + ')'\n\n if kink == 1:\n signsL2 = '((COML2[sumstep_tau][ind_mol])*1e10 < ' + str(float(COMLcent2 + 2*stdLLL2)*1e10) + ') and ((COML2[sumstep_tau][ind_mol])*1e10 > '+ str(float(COMLcent2 - 2*stdLLL2)*1e10) + ')'\n signsT2 = '((COMT2[sumstep_tau][ind_mol])*1e10 < ' + str(float(COMTcent2 + 2*stdTTT2)*1e10) + ') and ((COMT2[sumstep_tau][ind_mol])*1e10 > '+ str(float(COMTcent2 - 2*stdTTT2)*1e10) + ')'\n\n\n propTIMESL = []; \n propTIMEST = []; \n propL = [] ; \n propT = [] ; \n propL2 = [] ; \n propT2 = [] ;\n propTIMESL_2 = []; \n propTIMEST_2 = []; \n propL_2 = [] ; \n propT_2 = [] ; \n propL2_2 = [] ; \n propT2_2 = [] ; \n for sumstep_tau in xrange(0, frames):\n\n if sumstep_tau < round(frames/2)-1:\n flag = 'countUP'; cancount = (frames - sumstep_tau)\n else:\n flag = 'countDOWN' ; cancount = sumstep_tau\n\n \n if eval(signsL):\n\n for sumstep_times in xrange(0, frames - sumstep_tau):\n\n propTIMESL.append( abs( int(round( (times[sumstep_tau][ind_mol]- times[sumstep_tau+sumstep_times][ind_mol]) /tstep) ) ) )\n propL.append(COML1[sumstep_tau+sumstep_times][ind_mol] - COML1[sumstep_tau][ind_mol])\n propL2.append( (COML1[sumstep_tau][ind_mol] - COML1[sumstep_tau+sumstep_times][ind_mol]) * (COML1[sumstep_tau][ind_mol] - COML1[sumstep_tau+sumstep_times][ind_mol]) )\n \n for sumstep_times in xrange(0, sumstep_tau):\n\n propTIMESL.append( abs( int(round( (times[sumstep_tau][ind_mol] - times[sumstep_tau-sumstep_times][ind_mol]) /tstep) ) ) )\n propL.append( COML1[sumstep_tau][ind_mol] - COML1[sumstep_tau-sumstep_times][ind_mol])\n propL2.append( (COML1[sumstep_tau][ind_mol] - COML1[sumstep_tau-sumstep_times][ind_mol])*(COML1[sumstep_tau][ind_mol] - COML1[sumstep_tau-sumstep_times][ind_mol]) )\n\n if kink == 1:\n if eval(signsL2):\n\n for sumstep_times in xrange(0, frames - sumstep_tau):\n\n propTIMESL_2.append( abs( int(round( (times[sumstep_tau][ind_mol]- times[sumstep_tau+sumstep_times][ind_mol]) /tstep) ) ) )\n propL_2.append(COML2[sumstep_tau+sumstep_times][ind_mol] - COML2[sumstep_tau][ind_mol])\n propL2_2.append( (COML2[sumstep_tau][ind_mol] - COML2[sumstep_tau+sumstep_times][ind_mol]) * (COML2[sumstep_tau][ind_mol] - COML2[sumstep_tau+sumstep_times][ind_mol]) )\n \n for sumstep_times in xrange(0, sumstep_tau):\n\n propTIMESL_2.append( abs( int(round( (times[sumstep_tau][ind_mol] - times[sumstep_tau-sumstep_times][ind_mol]) /tstep) ) ) )\n propL_2.append( COML2[sumstep_tau][ind_mol] - COML2[sumstep_tau-sumstep_times][ind_mol])\n propL2_2.append( (COML2[sumstep_tau][ind_mol] - COML2[sumstep_tau-sumstep_times][ind_mol])*(COML2[sumstep_tau][ind_mol] - COML2[sumstep_tau-sumstep_times][ind_mol]) )\n\n\n timeBIN = round((frames-1)/100)\n index_binsL = np.zeros([int((frames-1)/timeBIN), 1], dtype='int')\n index_binsT = np.zeros([int((frames-1)/timeBIN), 1], dtype='int')\n ratioL = np.zeros([len(propTIMESL), 1], dtype='int')\n ratioT = np.zeros([len(propTIMEST), 1], dtype='int')\n binsATratio_L = np.zeros([int((frames-1)/timeBIN), len(ratioL[:,0])])\n binsATratio_T = np.zeros([int((frames-1)/timeBIN), len(ratioT[:,0])])\n diffus_L = np.zeros([int((frames-1)/timeBIN), len(ratioL[:,0])])\n diffus_T = np.zeros([int((frames-1)/timeBIN), len(ratioT[:,0])])\n diffus_L_const = np.zeros([int((frames-1)/timeBIN), 1])\n diffus_T_const = np.zeros([int((frames-1)/timeBIN), 1])\n binsATratio_L_const = np.zeros([int((frames-1)/timeBIN), 1])\n A2_L= np.zeros([int((frames-1)/timeBIN), 1])\n A2_T= np.zeros([int((frames-1)/timeBIN), 1])\n varL= np.zeros([int((frames-1)/timeBIN), 1])\n varT= np.zeros([int((frames-1)/timeBIN), 1])\n stdL= np.zeros([int((frames-1)/timeBIN), 1])\n stdT= np.zeros([int((frames-1)/timeBIN), 1])\n\n\n for propsteps in xrange(1, len(propTIMESL)):\n\n if abs(round(propTIMESL[propsteps])) !=0:\n \n ratioL[propsteps]= int(abs(propTIMESL[propsteps]))\n \n index_binsL[ratioL[propsteps,0]-1] = index_binsL[ratioL[propsteps,0]-1] + 1\n \n binsATratio_L[ratioL[propsteps,0]-1][index_binsL[ratioL[propsteps,0]-1,0]] = propL[propsteps]\n diffus_L[ratioL[propsteps, 0]-1][index_binsL[ratioL[propsteps,0]-1,0]] = propL2[propsteps]\n \n\n for stepits in xrange(1,int((frames-1)/timeBIN)):\n\n if (index_binsL[stepits][0] ) != 0:\n diffus_L_const[stepits] = sum(diffus_L[stepits,:])/index_binsL[stepits][0]\n binsATratio_L_const[stepits] = sum(binsATratio_L[stepits, :]) / index_binsL[stepits][0]\n \n\n \n A2_L[stepits] =sum(diffus_L[stepits,:]**diffus_L[stepits,:]) /index_binsL[stepits][0]\n varL[stepits] = A2_L[stepits] - diffus_L_const[stepits]*diffus_L_const[stepits]\n \n\n if (index_binsL[stepits][0] - 1) > 0:\n stdL[stepits] = np.sqrt(varL[stepits]) / np.sqrt(index_binsL[stepits][0] - 1)\n else:\n stdL[stepits] = max(stdL) \n\n\n filename = 'TE_DiffusionMOL'+ str(mol)+ 'L' + sty +'.csv'\n \n outputfile = os.path.join(paths,datafolder, filename )\n fout1 = open(outputfile, \"wb\")\n\n datafout1 = csv.writer(fout1, delimiter=\",\")\n datafout1.writerow([\"#TIME\", \"diffusion [m^2/s]\"])\n for ttt in xrange(0, len(timelinspace)-1):\n datafout1.writerow([timelinspace[ttt]*tstep, diffus_L_const[ttt,0]])\n fout1.close()\n\n\n filename2 = 'TE_pplane_mag_MOL' + str(mol) + '.csv'\n outputfile2 = os.path.join(paths, datafolder, filename2)\n fout2 = open(outputfile2, \"wb\")\n datafout2 = csv.writer(fout2, delimiter=\",\")\n datafout2.writerow([\"#TIME\", \"dist-end1 (m)\", \"dist-end2 (m)\"])\n for ttt in xrange(0, len(timelinspace)):\n\n if kink == 1:\n datafout2.writerow([timelinspace[ttt], float(np.sqrt( \\\n (abs(dot2[ttt, ind_mol])/max(abs(dot2[:,ind_mol])))*(abs(dot2[ttt, ind_mol])/max(abs(dot2[:,ind_mol])))+\\\n (abs(dot1[ttt, ind_mol])/max(abs(dot1[:,ind_mol])))*(abs(dot1[ttt, ind_mol])/max(abs(dot1[:,ind_mol])))) )])\n else:\n datafout2.writerow([timelinspace[ttt], mag_diff1[ttt, ind_mol]])\n\n\n fout2.close()\n \n\n if kink == 1:\n filename2 = 'TE_pplane_plus_MOL' + str(mol) + '.csv'\n outputfile2 = os.path.join(paths, datafolder, filename2)\n fout2 = open(outputfile2, \"wb\")\n datafout2 = csv.writer(fout2, delimiter=\",\")\n datafout2.writerow([\"#TIME\", \"p-dist-normal\"])\n for ttt in xrange(0, len(timelinspace)):\n\n datafout2.writerow([timelinspace[ttt]*tstep, abs(dot2[ttt,ind_mol])/max(abs(dot2[:,ind_mol]))+abs(dot1[ttt,ind_mol])/max(abs(dot1[:,ind_mol])) ])\n \n fout2.close()\n \n\n if kink ==0:\n filename = 'distances_ee.xyz'\n outputf = os.path.join(paths, datafolder, filename)\n fout = open(outputf, \"wb\")\n datafout = csv.writer(fout, delimiter=\"\\t\")\n\n for ttt in xrange(0, len(timelinspace)):\n datafout.writerow(['5'])\n datafout.writerow(['comments'])\n datafout.writerow(['Ag', BEGeex[ttt,ind_mol], BEGeey[ttt,ind_mol], BEGeez[ttt,ind_mol]])\n datafout.writerow(['Te', ENDeex[ttt,ind_mol], ENDeey[ttt,ind_mol], ENDeez[ttt,ind_mol]])\n \n datafout.writerow(['Sb', pos1x[ttt,ind_mol], pos1y[ttt,ind_mol], pos1z[ttt,ind_mol]])\n # datafout.writerow(['Au', pos2x[ttt,ind_mol], pos2y[ttt,ind_mol], pos2z[ttt,ind_mol]])\n datafout.writerow(['W', COMx[ttt,ind_mol], COMy[ttt,ind_mol], COMz[ttt,ind_mol]])\n fout.close()\n \n \"\"\"\n fig1=plt.figure()\n plt.plot(timelinspace[:-1], diffus_L_const*cc.m_to_A*cc.m_to_A/cc.s_to_ps, 'r', linewidth=5, label='L')\n plt.fill_between(timelinspace[:-1], (diffus_L_const[:,0] - stdL[:,0]*diffus_L_const[:,0])*cc.m_to_A*cc.m_to_A/cc.s_to_ps, (diffus_L_const[:,0] +stdL[:,0]*diffus_L_const[:,0])*cc.m_to_A*cc.m_to_A/cc.s_to_ps, color=\"#3F5D7D\" )\n\n timestop = 10 \n if kink == 1:\n plt.ylim(0, 50e-20*cc.m_to_A*cc.m_to_A/cc.s_to_ps)\n\n if (sty is 'l') or (sty is 'L'):\n DL = .5e-6\n \n plt.plot(timelinspace[:timestop], diffus_L_const[:timestop]*cc.m_to_A*cc.m_to_A/cc.s_to_ps , 'm', linewidth=4)\n if (sty is 'r') or (sty is 'R'):\n DL = .5e-6\n\n plt.plot(timelinspace[:timestop], diffus_L_const[:timestop]*cc.m_to_A*cc.m_to_A/cc.s_to_ps , 'm', linewidth=4)\n if (sty is 'c') or (sty is 'C'):\n DL = 1e-7\n\n plt.plot(timelinspace[:timestop], diffus_L_const[:timestop]*cc.m_to_A*cc.m_to_A/cc.s_to_ps , 'm', linewidth=4)\n else:\n plt.ylim(0, max(diffus_L_const[1:round(len(diffus_L_const)/2),0]*cc.m_to_A*cc.m_to_A/cc.s_to_ps ))\n \n if (sty is 'l') or (sty is 'L'):\n DL = 3e-7\n \n plt.plot(timelinspace[:timestop], diffus_L_const[:timestop]*cc.m_to_A*cc.m_to_A/cc.s_to_ps , 'm', linewidth=4)\n if (sty is 'r') or (sty is 'R'):\n DL = 3e-7\n \n\n plt.plot(timelinspace[:timestop], diffus_L_const[:timestop]*cc.m_to_A*cc.m_to_A/cc.s_to_ps , 'm', linewidth=4)\n if (sty is 'c') or (sty is 'C'):\n DL = 1e-7\n\n plt.plot(timelinspace[:timestop], diffus_L_const[:timestop]*cc.m_to_A*cc.m_to_A/cc.s_to_ps , 'm', linewidth=4)\n \n plt.plot(timelinspace[:-1]*tstep*cc.s_to_ps, DL*timelinspace[:-1]*tstep*cc.m_to_A*cc.m_to_A/cc.s_to_ps , ':k', linewidth=5, label='D = ' + \\\n str(DL*cc.m_to_A*cc.m_to_A/cc.s_to_ps) + 'A$^2$/ps ' )\n \n plt.legend(loc='best') ; \n plt.xlim(0, 20) ; \n plt.ylabel('D [A$^2$/ps]') ;\n plt.xlabel('Times [ps]')\n plt.title('Molecule ' + str(mol) + ' ' + str(sty))\n plt.savefig(os.path.join(imgfolder2, 'DiffusionMOL'+ str(mol)+ 'L.png'))\n \"\"\"\n\n\n cdict = {'red': ((0., 1, 1),\n (0.05, 1, 1),\n (0.11, 0, 0),\n (0.66, 1, 1),\n (0.89, 1, 1),\n (1, 0.5, 0.5)),\n 'green': ((0., 1, 1),\n (0.05, 1, 1),\n (0.11, 0, 0),\n (0.375, 1, 1),\n (0.64, 1, 1),\n (0.91, 0, 0),\n (1, 0, 0)),\n 'blue': ((0., 1, 1),\n (0.05, 1, 1),\n (0.11, 1, 1),\n (0.34, 1, 1),\n (0.65, 0, 0),\n (1, 0, 0))}\n\n my_cmap = colo.LinearSegmentedColormap('my_colormap',cdict,256)\n\n\n values = range(len(dot2))\n jets = plt.get_cmap('jet')\n cNorm = colo.Normalize(vmin=0, vmax=values[-1])\n scalarMap = cmx.ScalarMappable(norm=cNorm, cmap=jets)\n\n\n\n if kink == 1:\n fig = plt.figure()\n ax=fig.add_subplot(1,1,1)\n for xx in xrange(len(dot2)):\n colorVal=scalarMap.to_rgba(values[xx])\n \n ax.plot( abs(dot1[xx, ind_mol])/max(abs(dot1[:,ind_mol])), abs(dot2[xx, ind_mol])/max(abs(dot2[:,ind_mol])), '-o', color=colorVal)\n # ax.plot( (dot1[xx, ind_mol]), (dot2[xx, ind_mol]), '-o', color=colorVal)\n plt.ylabel('y')\n plt.xlabel('x')\n\t # plt.ylim([.1, 1]) ; plt.xlim([.1, 1])\n # ax.set_xscale('log') \t; ax.set_yscale('log')\n plt.savefig(os.path.join(imgfolder2, 'pplaneMOL'+ str(mol)+ '.png'))\n\n fig = plt.figure()\n ax=fig.add_subplot(1,1,1)\n for xx in xrange(len(dot2)):\n colorVal=scalarMap.to_rgba(values[xx])\n \n # ax.plot( abs(dot1[xx, ind_mol])/max(abs(dot1[:,ind_mol])), abs(dot2[xx, ind_mol])/max(abs(dot2[:,ind_mol])), '-o', color=colorVal)\n ax.plot( times[:,ind_mol], distance[0,:], '-o', color=colorVal)\n ax.plot( times[:,ind_mol], distance[1,:], '-o', color=colorVal)\n ax.plot( times[:,ind_mol], distance[2,:], '-o', color=colorVal)\n plt.ylabel('y')\n plt.xlabel('x')\n # plt.ylim([.1, 1]) ; plt.xlim([.1, 1])\n # ax.set_xscale('log') ; ax.set_yscale('log')\n plt.savefig(os.path.join(imgfolder2, 'pplaneMOL'+ str(mol)+ '.png'))\n \n \n fig = plt.figure()\n # for xx in xrange(len(dot2)):\n # colorVal=scalarMap.to_rgba(values[xx])\n \n plt.plot( times[:,ind_mol], np.sqrt((dot2[:,ind_mol])*(dot2[:,ind_mol])+\\\n (dot1[:,ind_mol])*(dot1[:,ind_mol]))/max(np.sqrt((dot2[:,ind_mol])*(dot2[:,ind_mol])+\\\n (dot1[:,ind_mol])*(dot1[:,ind_mol]))), '-o', color=colorVal, label='mag(y,x)')\n plt.plot( times[:, ind_mol], (abs(dot2[:,ind_mol])+abs(dot1[:,ind_mol]))/max((abs(dot1[:,ind_mol])) + (abs(dot2[:,ind_mol]))), '-og',label='y+x' )\n plt.legend(loc='best')\n plt.ylabel('Distance (m)')\n plt.xlabel('times')\n plt.savefig(os.path.join(imgfolder2, 'pplane_distmag_MOL'+ str(mol)+ '.png'))\n\n\n fig = plt.figure() \n plt.plot( times[:, ind_mol], abs(dot2[:,ind_mol])/max(abs(dot2[:,ind_mol]))+abs(dot1[:,ind_mol])/max(abs(dot1[:,ind_mol])), '-o', color=colorVal)\n plt.ylabel('Absolute distance (m)')\n plt.xlabel('times')\n plt.savefig(os.path.join(imgfolder2, 'pplane_distplus_MOL'+ str(mol)+ '.png'))\n\n \n \n\n fig=plt.figure()\n\n plt.subplot(2,2,1)\n for xx in xrange(len(dot2)):\n colorVal=scalarMap.to_rgba(values[xx])\n plt.plot(HOMO[xx, ind_mol], dot2[xx, ind_mol]+dot1[xx,ind_mol], '-o', color=colorVal)\n\n plt.subplot(2,2,2)\n for xx in xrange(len(dot2)):\n plt.plot(HOMO[xx, ind_mol], dot1[xx, ind_mol], '-o', color=colorVal)\n plt.xlabel('Energy [eV]')\n plt.ylabel('p(y) and p(x)')\n plt.savefig(os.path.join(imgfolder2, 'E_pcorr'+ str(mol)+ '.png'))\n\n plt.subplot(2,2,3)\n for xx in xrange(len(dot2)):\n colorVal=scalarMap.to_rgba(values[xx])\n plt.plot(LUMO[xx, ind_mol], dot2[xx, ind_mol]+dot1[xx,ind_mol], '-o', color=colorVal)\n\n plt.subplot(2,2,4)\n for xx in xrange(len(dot2)):\n plt.plot(LUMO[xx, ind_mol], dot1[xx, ind_mol], '-o', color=colorVal)\n plt.xlabel('Energy [eV]')\n plt.ylabel('p(y) and p(x)')\n plt.savefig(os.path.join(imgfolder2, 'E_pcorr'+ str(mol)+ '.png'))\n\n else:\n \n fig=plt.figure()\n\n plt.subplot(1,2,1)\n for xx in xrange(len(dot2)):\n colorVal=scalarMap.to_rgba(values[xx])\n plt.plot(HOMO[xx, ind_mol], mag_diff2[xx , ind_mol], '-o', color=colorVal)\n plt.xlabel('Energy [eV]')\n plt.ylabel('p')\n\n plt.subplot(1,2,2)\n for xx in xrange(len(dot2)):\n colorVal=scalarMap.to_rgba(values[xx])\n plt.plot(LUMO[xx, ind_mol], mag_diff2[xx , ind_mol], '-o', color=colorVal)\n plt.xlabel('Energy [eV]')\n plt.ylabel('p')\n\n plt.savefig(os.path.join(imgfolder2, 'E_pcorr'+ str(mol)+ '.png'))\n\n\n\n fig=plt.figure()\n\n plt.subplot(1,2,1)\n for xx in xrange(len(gyration_proj)):\n colorVal=scalarMap.to_rgba(values[xx])\n plt.plot(HOMO[xx, ind_mol], gyration_proj[xx , ind_mol], '-o', color=colorVal)\n plt.xlabel('Energy [eV]')\n plt.ylabel('gyr')\n\n plt.subplot(1,2,2)\n for xx in xrange(len(gyration_proj)):\n colorVal=scalarMap.to_rgba(values[xx])\n plt.plot(LUMO[xx, ind_mol], gyration_proj[xx , ind_mol], '-o', color=colorVal)\n plt.xlabel('Energy [eV]')\n plt.ylabel('gyr')\n\n\n plt.savefig(os.path.join(imgfolder2, 'E_pcorr'+ str(mol)+ '.png'))\n\n \n\n fig=plt.figure()\n\n plt.subplot(1,2,1)\n for xx in xrange(len(gyration_proj)):\n colorVal=scalarMap.to_rgba(values[xx])\n plt.plot(HOMO[xx, ind_mol],G2x[xx , ind_mol]*UVNOHeex[xx,ind_mol], '-o', color='b')\n plt.plot(HOMO[xx, ind_mol],G2y[xx , ind_mol]*UVNOHeey[xx,ind_mol], '-o', color='g')\n plt.plot(HOMO[xx, ind_mol],G2z[xx , ind_mol]*UVNOHeez[xx,ind_mol], '-o', color='k')\n plt.xlabel('Energy [eV]')\n plt.ylabel('gyr')\n\n plt.subplot(1,2,2)\n for xx in xrange(len(gyration_proj)):\n colorVal=scalarMap.to_rgba(values[xx])\n plt.plot(LUMO[xx, ind_mol], G2x[xx , ind_mol]*UVNOHeex[xx,ind_mol], '-o', color='b')\n plt.plot(LUMO[xx, ind_mol], G2y[xx , ind_mol]*UVNOHeey[xx,ind_mol], '-o', color='g')\n plt.plot(LUMO[xx, ind_mol], G2z[xx , ind_mol]*UVNOHeez[xx,ind_mol], '-o', color='k')\n plt.xlabel('Energy [eV]')\n plt.ylabel('gyr')\n\n\n plt.savefig(os.path.join(imgfolder2, 'E_pcorr'+ str(mol)+ '.png'))\n\n \n\n fig1=plt.figure()\n plt.plot(times*tstep*cc.s_to_ps, abs(mag_diff1[:,ind_mol]), 'b')\n plt.plot(times*tstep*cc.s_to_ps, abs(mag_diff2[:,ind_mol]), 'g')\n plt.ylabel('distance (A)')\n plt.xlabel('timesteps (ps)')\n plt.savefig(os.path.join(imgfolder2, 'pplane_dist_MOL'+ str(mol)+ '.png'))\n \n \"\"\"\n\n\n fig=plt.figure()\n plt.plot(timelinspace[:-1], index_binsL, 'r')\n plt.plot(timelinspace[:-1], index_binsL, 'g')\n plt.ylabel('Samples')\n plt.xlabel('Timesteps')\n plt.savefig(os.path.join(imgfolder2, 'numberdiffusionMOL'+ str(mol)+ 'L.png'))\n \n\n \n imgfolder3= imgfolder2 + '/projector_' + sty\n \n try:\n os.mkdir(imgfolder3)\n except:\n pass\n\n\n graded = 10;\n histL = np.zeros([round(len(binsATratio_L[1,:])/graded),int((frames-1)/timeBIN) ], dtype='float')\n histT = np.zeros([round(len(binsATratio_T[1,:])/graded),int((frames-1)/timeBIN) ], dtype='float')\n bin_edgesL = np.zeros([round(len(binsATratio_L[1,:])/graded)+1,int((frames-1)/timeBIN) ], dtype='float')\n bin_edgesT = np.zeros([round(len(binsATratio_T[1,:])/graded)+1,int((frames-1)/timeBIN) ], dtype='float')\n\n for tausteps in xrange(0, int((frames-1)/timeBIN)):\n binsATratio_L_n= filter(lambda a: a != 0, abs(binsATratio_L[tausteps,:]))\n binsATratio_T_n= filter(lambda a: a != 0, abs(binsATratio_T[tausteps,:]))\n \n histL[:,tausteps] ,bin_edgesL[:,tausteps] = np.histogram(binsATratio_L_n, round(len(binsATratio_L[tausteps,:])/graded))\n histT[:,tausteps], bin_edgesT[:,tausteps] = np.histogram(binsATratio_T_n, round(len(binsATratio_T[tausteps,:])/graded))\n\n\n \n for tausteps in xrange(1, int(round(frames/2)), 1):\n xxx = np.linspace(-100*bin_edgesL[-1, tausteps],100*bin_edgesL[-1, tausteps] , 1000)/1e-10\n \n fig=plt.figure()\n plt.bar(bin_edgesL[:-1, tausteps]/1e-10, (histL[:, tausteps]/max(histL[:, tausteps]))/sum((histL[:, tausteps]/max(histL[:, tausteps]))), width = abs(bin_edgesL[0, tausteps] - bin_edgesL[1, tausteps]), color= 'g', alpha=0.25)\n plt.bar(-bin_edgesL[:-1, tausteps]/1e-10, histL[:, tausteps]/max(histL[:, tausteps])/sum(histL[:, tausteps]/max(histL[:, tausteps])), width = abs(bin_edgesL[0, tausteps] - bin_edgesL[1, tausteps]), color= 'g', alpha=0.25)\n\n\n plt.xlabel('Distance')\n plt.ylabel('P')\n plt.title(str(tausteps) + ' steps')\n plt.xlim([-5, 5])\n plt.ylim([0, .07])\n if tausteps < 10:\n plt.savefig(os.path.join(imgfolder3, sty + '_propagator_MOL'+ str(mol) + 'step0' + str(tausteps) + '.png'))\n else:\n plt.savefig(os.path.join(imgfolder3, sty + '_propagator_MOL'+ str(mol) + 'step' + str(tausteps) + '.png'))\n plt.close()\n\n\n animGIF=sty + '_projector_mol' + str(mol)+ 'L.gif'\n os.chdir(imgfolder3)\n os.system('convert -delay 60.0 -loop 1 *.png ' + animGIF)\n\n\n \n\nfig1=plt.figure()\nplt.plot(times*cc.s_to_ps, mag_diff[:,ind_mol]*cc.m_to_A)\n#plt.plot(times, np.sqrt(abs(BEGeex[:,ind_mol]-ENDeex[:,ind_mol])*abs(BEGeex[:,ind_mol]-ENDeex[:,ind_mol])+\\\n# abs(BEGeey[:,ind_mol]-ENDeey[:,ind_mol])*abs(BEGeey[:,ind_mol]-ENDeey[:,ind_mol])+\\\n# abs(BEGeez[:,ind_mol]-ENDeez[:,ind_mol])*abs(BEGeez[:,ind_mol]-ENDeez[:,ind_mol])), 'r' )\nplt.xlabel('Times (ps)')\nplt.ylabel('Distance from end of chain (Angstrom)')\nplt.savefig(os.path.join(imgfolder2, 'distance_leading_COM'+ str(mol)+ '.png'))\n\n\n\"\"\"\n\nplt.show()\n","sub_path":"propagator_x0.py","file_name":"propagator_x0.py","file_ext":"py","file_size_in_byte":33707,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"23613062","text":"#!/usr/bin/python2\n\"\"\"\ncorrect_barcode.py\n\nUsage:\n correct_barcode.py (-i input_file) (-b barcode_file) (-o output_file) (-m metric) (-d distance)\n correct_barcode.py -h | --help\n correct_barcode.py -v | --version\n\nOptions:\n -i input_file Bam file resulted of TagReadWithGeneExon\n -b barcode_file Single-column file for designed barcode (No header)\n -o output_file Bam file name for output of this program\n -m metric The distance metric to be used. (seqlev or hamming)\n -d distance Distance for error correction\n -h --help Show this screen\n -v --version Show version\n\"\"\"\n\nfrom __future__ import print_function\n\nimport time\nimport pandas as pd\n\nfrom docopt import docopt\n\nimport pyper as pr\nimport pysam\n\n\ndef collect_set_XC(input_bam_file):\n\n bamfile = pysam.AlignmentFile(input_bam_file, \"rb\")\n\n set_XC = set()\n\n for read in bamfile:\n\n try:\n if read.get_tag('GE'):\n set_XC.add(read.get_tag('XC'))\n except:\n pass\n\n bamfile.close()\n\n return set_XC\n\n\ndef get_dict_correction(set_XC, designed_barcode,\n metric=\"seqlev\", distance=\"2\"):\n\n if type(distance) not in (int, long):\n raise InvalidArgumentError\n\n if distance not in (0, 1, 2):\n print(\"distance must be 0, 1, or 2\")\n raise InvalidArgumentError\n\n r = pr.R()\n r(\"library(DNABarcodes)\")\n r.assign(\"list_XC\", list(set_XC))\n r.assign(\"designed_barcode\", designed_barcode)\n\n if metric == \"seqlev\":\n r(\"demultiplexed <- demultiplex(list_XC, designed_barcode, metric='seqlev')\")\n elif metric == \"hamming\":\n r(\"demultiplexed <- demultiplex(list_XC, designed_barcode, metric='hamming')\")\n else:\n print(\"metric must be 'seqlev' or 'hamming'\")\n raise InvalidArgumentError\n\n df_correction = r.get(\"demultiplexed\")\n\n df_correction.columns = [x.replace(\" \", \"\") for x in df_correction.columns]\n df_correction_filt = (df_correction[df_correction.distance <= distance]\n [['read', 'barcode']])\n dict_correct = df_correction_filt.set_index('read').to_dict()['barcode']\n\n return dict_correct\n\n\ndef correct_XC(input_file, dict_correct, output_file):\n\n input_bamfile = pysam.AlignmentFile(input_file, \"rb\")\n output_bamfile = pysam.AlignmentFile(output_file, \"wb\",\n template=input_bamfile)\n\n for read in input_bamfile:\n\n try:\n if read.get_tag('GE'):\n barcode = dict_correct[read.get_tag('XC')]\n read.set_tag('XC', barcode)\n output_bamfile.write(read)\n except:\n pass\n\n output_bamfile.close()\n input_bamfile.close()\n\n# try:\n# bef = read.get_tag('XC')\n# read.set_tag('XC', bef)\n# except:\n# pass\n\n# try:\n# barcode = dict_correct[read.get_tag('XC')]\n# except:\n# barcode = read.get_tag('XC')\n# read.set_tag('XC', barcode)\n\n\ndef InvalidArgumentError(ValueError):\n pass\n\n\nif __name__ == '__main__':\n\n start = time.time()\n\n NAME = \"correct_barcode.py\"\n VERSION = \"0.1.0\"\n\n args = docopt(__doc__, version=\"{0} {1}\".format(NAME, VERSION))\n\n input_file = args['-i']\n barcode_file = args['-b']\n output_file = args['-o']\n metric = args['-m']\n distance = int(args['-d'])\n\n designed_barcode = list(pd.read_csv(barcode_file,\n header=None, squeeze=True))\n\n set_XC = collect_set_XC(input_file)\n\n dict_correct = get_dict_correction(set_XC, designed_barcode,\n metric=metric, distance=distance)\n\n correct_XC(input_file, dict_correct, output_file)\n\n elapsed_time = time.time() - start\n print(\"Program finished. Elapsed_time: {0:.2f}\".format(elapsed_time) +\n \" [sec]\")\n\n","sub_path":"Q2-pipeline_py2/correct_barcode.py","file_name":"correct_barcode.py","file_ext":"py","file_size_in_byte":3932,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"279458501","text":"import matplotlib.pyplot as plt\nimport pandas as pd\nimport numpy as np\n\nfilenmae = 'setup.csv'\ndata = pd.read_csv(filenmae)\ndata = data.sort_values(by=['MSE'], ascending=False)\nwidth = 0.5\nN = data.shape[0]\nind = np.arange(N)\nMSEs = data['MSE']\nlabels = data['label']\nplt.barh(ind, MSEs, width)\nplt.yticks(ind, labels)\nplt.xlabel('prediction error (mean square error)')\nlossmessgae = \"model1 : $k-\\epsilon$ model \\nmodel2 : $k-\\omega$ model \\nmodel3 : laminar\"\nplt.annotate(lossmessgae, xy=(0.55, 0.8), xycoords='axes fraction')\nplt.tight_layout()\nplt.savefig('MDTM_VS_SDTM')\n","sub_path":"step5_plot.py","file_name":"step5_plot.py","file_ext":"py","file_size_in_byte":576,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"115437440","text":"import pandas as pd\nimport re\nimport jieba.posseg as pseg\nfrom collections import Counter\nfrom sklearn.feature_extraction.text import TfidfVectorizer\nfrom sklearn.cluster import DBSCAN\nfrom sklearn.decomposition import PCA\nfrom sklearn.manifold import TSNE\nimport matplotlib.pyplot as plt\nfrom sklearn import metrics\nimport numpy as np\n\n\ndef clean_text(text, name=True, ):\n if name:\n for i in range(len(text)):\n if text[i] == ':' or text[i] == ':':\n text = text[i + 1:-1]\n break\n\n zh_puncts1 = \",;、。!?()《》【】\"\n URL_REGEX = re.compile(\n r'(?i)((?:https?://|www\\d{0,3}[.]|[a-z0-9.\\-]+[.][a-z]{2,4}/)(?:[^\\s()<>' + zh_puncts1 + ']+|\\(([^\\s()<>]+|(\\([^\\s()<>]+\\)))*\\))+(?:\\(([^\\s()<>]+|(\\([^\\s()<>]+\\)))*\\)|[^\\s`!()\\[\\]{};:\\'\".,<>?«»“”‘’' + zh_puncts1 + ']))',\n re.IGNORECASE)\n text = re.sub(URL_REGEX, \"\", text)\n\n EMAIL_REGEX = re.compile(r\"[-a-z0-9_.]+@(?:[-a-z0-9]+\\.)+[a-z]{2,6}\", re.IGNORECASE)\n text = re.sub(EMAIL_REGEX, \"\", text)\n text = re.sub(r\"(回复)?(//)?\\s*@\\S*?\\s*(:|:| |$)\", \" \", text) # 去除正文中的@和回复/转发中的用户名\n lb, rb = 1, 6\n text = re.sub(r\"\\[\\S{\" + str(lb) + r\",\" + str(rb) + r\"}?\\]\", \"\", text)\n emoji_pattern = re.compile(\"[\"u\"\\U0001F600-\\U0001F64F\"\n u\"\\U0001F300-\\U0001F5FF\"\n u\"\\U0001F680-\\U0001F6FF\"\n u\"\\U0001F1E0-\\U0001F1FF\"\n u\"\\U00002702-\\U000027B0\" \"]+\", flags=re.UNICODE)\n text = emoji_pattern.sub(r'', text)\n text = re.sub(r\"#\\S+#\", \"\", text)\n text = text.replace(\"\\n\", \" \")\n\n text = re.sub(r\"(\\s)+\", r\"\\1\", text)\n stop_terms = ['展开', '全文', '展开全文', '一个', '网页', '链接', '?【', 'ue627', 'c【', '10', '一下', '一直', 'u3000', '24', '12',\n '30', '?我', '15', '11', '17', '?\\\\', '显示地图', '原图']\n for x in stop_terms:\n text = text.replace(x, \"\")\n allpuncs = re.compile(\n r\"[,\\_《。》、?;:‘’"“”【「】」·!@¥…()—\\,\\<\\.\\>\\/\\?\\;\\:\\'\\\"\\[\\]\\{\\}\\~\\`\\!\\@\\#\\$\\%\\^\\&\\*\\(\\)\\-\\=\\+]\")\n text = re.sub(allpuncs, \"\", text)\n\n return text.strip()\n\n\ndef get_words_by_flags(words, flags=None):\n flags = ['n.*', 'v.*'] if flags is None else flags\n words = [w for w, f in words if w != ' ' and re.match('|'.join(['(%s$)' % flag for flag in flags]), f)]\n return words\n\n\ndef stop_words_cut(words, stop_words_path):\n with open(stop_words_path, 'r', encoding='utf-8') as f:\n stopwords = [line.strip() for line in f.readlines()]\n stopwords.append(' ')\n words = [word for word in words if word not in stopwords]\n return words\n\n\ndef pseg_cut(x):\n return pseg.lcut(x, HMM=True)\n\n\ndef get_num_en_ch(x):\n return (re.sub(r'[^0-9A-Za-z\\u4E00-\\u9FFF]+', ' ', x)).strip()\n\n\ndef preProcess(df):\n df['content'] = df['微博正文'].map(lambda x: clean_text(x))\n df['content_cut'] = df['content'].map(lambda x: pseg_cut(x))\n df['content_cut'] = df['content_cut'].map(lambda x: get_words_by_flags(\n x, flags=['n.*', 'v.*', 'eng', 't', 's', 'j', 'l', 'i']))\n df['content_cut'] = df['content_cut'].map(lambda x: stop_words_cut(\n x, 'stop_words.txt'))\n df['content_'] = df['content_cut'].map(lambda x: ' '.join(x))\n\n\ndef flat(l):\n for k in l:\n if not isinstance(k, (list, tuple)):\n yield k\n else:\n yield from flat(k)\n\n\ndef get_single_frequency_words(list1):\n list2 = flat(list1)\n cnt = Counter(list2)\n list3 = [i for i in cnt if cnt[i] == 1]\n return list3\n\n\ndef get_most_common_words(list1, top_n=None, min_frequency=1):\n list2 = flat(list1)\n cnt = Counter(list2)\n list3 = [i[0] for i in cnt.most_common(top_n) if cnt[i[0]] >= min_frequency]\n return list3\n\n\ndef feature_extraction(series, vec_args):\n vec_args_list = ['%s=%s' % (i[0],\n \"'%s'\" % i[1] if isinstance(i[1], str) else i[1]\n ) for i in vec_args.items()]\n vec_args_str = ','.join(vec_args_list)\n vectorizer1 = TfidfVectorizer(vec_args_str)\n matrix = vectorizer1.fit_transform(series)\n return matrix\n\n\ndef label2rank(labels_list):\n series = pd.Series(labels_list)\n list1 = series[series != -1].tolist()\n n = len(set(list1))\n cnt = Counter(list1)\n key = [cnt.most_common()[i][0] for i in range(n)]\n value = [i for i in range(1, n + 1)]\n my_dict = dict(zip(key, value))\n my_dict[-1] = -1\n rank_list = [my_dict[i] for i in labels_list]\n return rank_list\n\n\ndef feature_reduction(matrix, pca_n_components=50, tsne_n_components=2):\n data_pca = PCA(n_components=pca_n_components).fit_transform(matrix) if pca_n_components is not None else matrix\n data_pca_tsne = TSNE(n_components=tsne_n_components).fit_transform(\n data_pca) if tsne_n_components is not None else data_pca\n print('data_pca_tsne.shape=', data_pca_tsne.shape)\n return data_pca_tsne\n\ndef get_num_of_value_no_repeat(list1):\n num = len(set(list1))\n return num\n\ndef draw_clustering_analysis_barh(rank_num, value, yticks, title):\n \"\"\"绘制聚类分析结果条形图\"\"\"\n plt.figure(figsize=(13, 6), dpi=100)\n plt.subplot(122)\n ax = plt.gca()\n ax.spines['left'].set_visible(False)\n ax.spines['right'].set_visible(False)\n ax.spines['top'].set_visible(False)\n ax.invert_yaxis()\n plt.barh(range(1, rank_num + 1), value, align='center', linewidth=0)\n plt.yticks(range(1, rank_num + 1), yticks)\n for a, b in zip(value, range(1, rank_num + 1)):\n plt.text(a + 1, b, '%.0f' % a, ha='left', va='center')\n plt.title(title)\n plt.savefig('2.jpg')\n plt.show()\n\n\ndef draw_clustering_analysis_pie(rank_num, value, yticks, title):\n \"\"\"绘制聚类分析结果饼图\"\"\"\n plt.figure(figsize=(13, 6), dpi=100)\n plt.subplot(132)\n plt.pie(value, explode=[0.2] * rank_num, labels=yticks, autopct='%1.2f%%', pctdistance=0.7)\n plt.title(title)\n plt.savefig('1.jpg')\n plt.show()\n\n\n# def data(n):\nif __name__ == '__main__':\n filepath = '2074685151.csv'\n df = pd.read_csv(filepath, index_col=0, )\n preProcess(df)\n word_library_list = list(set(flat((df['content_cut']))))\n single_frequency_words_list = get_single_frequency_words(df['content_cut'])\n max_features = (len(word_library_list) - len(single_frequency_words_list))\n matrix = feature_extraction(df['content_'],\n vec_args={'max_df': 0.95, 'min_df': 1, 'max_features': max_features})\n eps_var = 0.05\n min_samples_var = 5\n dbscan = DBSCAN(eps=eps_var, min_samples=min_samples_var, metric='cosine').fit(matrix)\n score = metrics.calinski_harabasz_score(matrix.toarray(), dbscan.labels_)\n print(score)\n score2 = metrics.silhouette_score(matrix.toarray(), dbscan.labels_)\n print()\n score3 = metrics.davies_bouldin_score(matrix.toarray(), dbscan.labels_)\n print()\n labels = dbscan.labels_\n df['label'] = labels\n ranks = label2rank(labels)\n df['rank'] = ranks\n print(df.head())\n\n df['matrix'] = matrix.toarray().tolist()\n\n df_non_outliers = df[df['label'] != -1].copy()\n\n rank_num = len(set((df_non_outliers['rank'])))\n # print(\"有\", rank_num, \"类\")\n\n data_pca_tsne = feature_reduction(df_non_outliers['matrix'].tolist(), pca_n_components=3, tsne_n_components=2)\n\n plt.rcParams['font.family'] = ['sans-serif']\n plt.rcParams['font.sans-serif'] = ['SimHei']\n plt.rcParams['axes.unicode_minus'] = False\n\n df_non_outliers['pca_tsne'] = data_pca_tsne.tolist()\n data_pca_tsne = df_non_outliers['pca_tsne']\n label = df_non_outliers['label']\n\n plt.figure()\n x = [i[0] for i in data_pca_tsne]\n y = [i[1] for i in data_pca_tsne]\n plt.scatter(x, y, c=label)\n plt.savefig('DBSCAN示例.jpg')\n plt.show()\n\n rank_num = get_num_of_value_no_repeat(df_non_outliers['rank'])\n value = [df_non_outliers[df_non_outliers['rank'] == i].shape[0] for i in range(1, rank_num + 1)]\n yticks1 = [str(get_most_common_words(df_non_outliers[df_non_outliers['rank'] == i]['content_cut'],\n top_n=10)) + str(i) for i in range(1, rank_num + 1)]\n\n draw_clustering_analysis_barh(rank_num, value, yticks1, title='热点条形图')\n draw_clustering_analysis_pie(rank_num, value, yticks1, title='热点饼图')","sub_path":"src/3_Analysis/Clustering/DBSCAN/DBSCAN.py","file_name":"DBSCAN.py","file_ext":"py","file_size_in_byte":8433,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"197840434","text":"#!/usr/bin/python\n# -*- coding :utf-8 -*-\n\"\"\"\nhttps://www.geeksforgeeks.org/bidirectional-search/\n\"\"\"\nfrom __future__ import print_function\nfrom collections import defaultdict\n\nclass Graph:\n \n def __init__(self, vertices):\n self.V = vertices\n self.graph = defaultdict(list)\n \n def addEdge(self, u, v):\n self.graph[u].append(v)\n self.graph[v].append(u)\n \n def printParent(self, s, d, i, s_parent, d_parent):\n u = i\n path = []\n while u != -1:\n path.insert(0, u)\n u = s_parent[u]\n \n while len(path) != 1:\n u = path.pop(0)\n print(str(u) + \" -- > \" , end = \" \")\n u = i\n while u != -1:\n print(str(u) + \" -- > \" , end = \" \")\n u = d_parent[u]\n \n def isIntersecting(self, s_visited, d_visited ):\n for i in xrange(len(s_visited)):\n if s_visited[i] is True and d_visited[i] is True:\n return i\n return -1\n \n def BFSUtil(self, queue, visited, parent): \n \n u = queue.pop(0)\n for v in self.graph[u]:\n \n if visited[v] is False:\n queue.append(v)\n parent[v] = u \n visited[v] = True \n \n \n def BiSearch(self, s, d):\n s_queue = []\n s_visited = [False]*self.V\n s_parent = [None]*self.V\n \n \n d_queue = []\n d_visited = [False]*self.V\n d_parent = [None]*self.V\n \n \n #init\n s_queue.append(s)\n s_parent[s] = -1\n s_visited[s] = True\n \n d_queue.append(d)\n d_parent[d] = -1\n d_visited[d] = True\n \n \n while s_queue and d_queue:\n self.BFSUtil(s_queue, s_visited, s_parent)\n self.BFSUtil(d_queue, d_visited, d_parent)\n i = self.isIntersecting(s_visited, d_visited)\n if i != -1:\n print(\"Path between {0} and {1} intersect at {2}\".format(s, d, i))\n self.printParent(s,d,i, s_parent, d_parent)\n break\n \n print(\"Done\") \n \n \n\nif __name__ == \"__main__\":\n \n \n n=15\n s=0\n d=14\n g = Graph(n)\n\n g.addEdge(0, 4)\n g.addEdge(1, 4)\n g.addEdge(2, 5)\n g.addEdge(3, 5)\n g.addEdge(4, 6)\n g.addEdge(5, 6)\n g.addEdge(6, 7)\n g.addEdge(7, 8)\n g.addEdge(8, 9)\n g.addEdge(8, 10)\n g.addEdge(9, 11)\n g.addEdge(9, 12)\n g.addEdge(10, 13)\n g.addEdge(10, 14)\n \n g.BiSearch(s, d)\n \n \n","sub_path":"Chapter 9 Graphs/BFSBidirection.py","file_name":"BFSBidirection.py","file_ext":"py","file_size_in_byte":2599,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"624498427","text":"from django.conf.urls import url\n\nfrom flavors import views\n\n\nurlpatterns = [\n url(\n regex=r'^api/$',\n view=views.FlavorCreateReadView.as_view(),\n name='flavor_rest_api'\n ),\n url(\n regex=r'^api/(?P[-\\w]+)$',\n view=views.FlavorReadUpdateDeleteView.as_view(),\n name='flavor_rest_api'\n ),\n]\n","sub_path":"icecreamratings/flavors/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":352,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"447831125","text":"# coding=utf-8\nfrom __future__ import absolute_import, division, print_function\n\nimport octoprint.plugin\n\nclass ConsolidateTempControlPlugin(octoprint.plugin.TemplatePlugin,\n octoprint.plugin.AssetPlugin,\n octoprint.plugin.SettingsPlugin):\n\n\t##-- Settings mixin\n\tdef get_settings_defaults(self):\n\t\treturn dict(tab_order=[dict(name=\"Temperature\",selector=\"#temp, #tab_plugin_plotlytempgraph\"),dict(name=\"Control\",selector=\"#control\")], layout=\"horizontal\", resize_navbar=True, resolution_threshold=0)\n\n\t##-- Template mixin\n\tdef get_template_configs(self):\n\t\treturn [\n\t\t\tdict(type=\"tab\", name=\"Command & Control\", custom_bindings=False),\n\t\t\tdict(type=\"settings\", custom_bindings=True)\n\t\t]\n\n\t##-- AssetPlugin mixin\n\tdef get_assets(self):\n\t\treturn dict(js=[\"js/jquery-ui.min.js\",\"js/knockout-sortable.1.2.0.js\",\"js/consolidate_temp_control.js\"])\n\n\t##~~ Softwareupdate hook\n\tdef update_hook(self):\n\t\treturn dict(\n\t\t\tconsolidate_temp_control=dict(\n\t\t\t\tdisplayName=\"Consolidate Temp Control\",\n\t\t\t\tdisplayVersion=self._plugin_version,\n\n\t\t\t\t# version check: github repository\n\t\t\t\ttype=\"github_release\",\n\t\t\t\tuser=\"jneilliii\",\n\t\t\t\trepo=\"OctoPrint-ConsolidateTempControl\",\n\t\t\t\tcurrent=self._plugin_version,\n\t\t\t\tstable_branch=dict(\n\t\t\t\t\tname=\"Stable\", branch=\"master\", comittish=[\"master\"]\n\t\t\t\t),\n\t\t\t\tprerelease_branches=[\n\t\t\t\t\tdict(\n\t\t\t\t\t\tname=\"Release Candidate\",\n\t\t\t\t\t\tbranch=\"rc\",\n\t\t\t\t\t\tcomittish=[\"rc\", \"master\"],\n\t\t\t\t\t)\n\t\t\t\t],\n\n\t\t\t\t# update method: pip\n\t\t\t\tpip=\"https://github.com/jneilliii/OctoPrint-ConsolidateTempControl/archive/{target_version}.zip\"\n\t\t\t)\n\t\t)\n\n__plugin_name__ = \"Consolidate Temp Control\"\n__plugin_pythoncompat__ = \">=2.7,<4\"\n\ndef __plugin_load__():\n\tglobal __plugin_implementation__\n\t__plugin_implementation__ = ConsolidateTempControlPlugin()\n\t\n\tglobal __plugin_hooks__\n\t__plugin_hooks__ = {\n\t\t\"octoprint.plugin.softwareupdate.check_config\": __plugin_implementation__.update_hook\n\t}\n\n\tglobal __plugin_settings_overlay__\n\t__plugin_settings_overlay__ = dict(appearance=dict(components=dict(order=dict(tab=[\"plugin_consolidate_temp_control\",\"temperature\",\"control\"]))))\n","sub_path":"octoprint_consolidate_temp_control/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":2149,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"87811753","text":"from django.http import JsonResponse\nfrom polls.models import *\nfrom polls.serializers import *\nfrom collections import OrderedDict\nfrom ..ChannelManager import channelManager\nfrom rest_framework.decorators import api_view\nimport json\n\nclass guestChannel():\n @api_view(['POST'])\n def enterChannel(request):\n token = request.data['token']\n accesscode = request.data['accesscode']\n user_token = Token.objects.filter(key = token)\n channel = Channel.objects.filter(accesspath = accesscode)\n data = OrderedDict()\n if(user_token):\n if(not channel):\n #입장코드와 일치하는 채널이 존재하지 않음\n data[\"state\"] = \"fail\"\n data[\"message\"] = \"Channel is not exist\"\n else:\n user_token = Token.objects.get(key = token)\n user = User.objects.get(id = user_token.user_id)\n host = Host.objects.filter(user=user,channel = channel[0])\n if(host):\n #호스트가 자기자신의 채널로 입장을 시도하면 입장불가\n data[\"state\"] = \"fail\"\n data[\"message\"] = \"Host cannot enter their own channel\"\n else:\n guest = Guest.objects.filter(user = user, channel = channel[0])\n if(guest.exists()):\n #이미 게스트로 입장한 채널이므로 재입장 불가\n data[\"state\"] = \"fail\"\n data[\"message\"] = \"You are already guest in this channel\"\n else:\n Guest.objects.create(user = user, channel = channel[0])\n\n host_channel_list = channelManager.requestHostChannelList(token)\n guest_channel_list = channelManager.requestGuestChannelList(token)\n host_length = len(host_channel_list)\n guest_length = len(guest_channel_list)\n \n data[\"state\"] = \"success\"\n data[\"message\"] = \"Enter the channel completed\"\n if(host_length != 0):\n data[\"leader\"] = [0 for i in range(host_length)]\n for i in range(host_length):\n host_channel = Channel.objects.filter(id=host_channel_list[i].id)\n serializer = ChannelIDSerializer(host_channel,many=True)\n data[\"leader\"][i] = OrderedDict()\n data[\"leader\"][i][\"id\"] = serializer.data[0]['url_id']\n data[\"leader\"][i][\"title\"] = host_channel_list[i].name\n data[\"leader\"][i][\"detail\"] = host_channel_list[i].description\n data[\"leader\"][i][\"image\"] = host_channel_list[i].image_type\n else:\n data[\"leader\"] = []\n\n data[\"runner\"] = [0 for i in range(guest_length)]\n for i in range(guest_length):\n guest_channel = Channel.objects.filter(id=guest_channel_list[i].id)\n serializer = ChannelIDSerializer(guest_channel,many=True)\n #UUID가 serializable하도록 해주기 위해 url_id만 별도의 serializer를 돌림\n data[\"runner\"][i] = OrderedDict()\n data[\"runner\"][i][\"id\"] = serializer.data[0]['url_id']\n data[\"runner\"][i][\"title\"] = guest_channel_list[i].name\n data[\"runner\"][i][\"detail\"] = guest_channel_list[i].description\n data[\"runner\"][i][\"image\"] = guest_channel_list[i].image_type\n \n else:\n data[\"state\"] = \"fail\"\n data[\"message\"] = \"Token is not exist\"\n\n json.dumps(data, ensure_ascii=False, indent=\"\\t\")\n\n return JsonResponse(data, safe=False)\n \n @api_view(['POST'])\n def exitChannel(request):\n token = request.data['token']\n channel_id = uuid.UUID(uuid.UUID(request.data['channel_id']).hex)\n data = OrderedDict()\n \n user_token = Token.objects.filter(key = token)\n channel = Channel.objects.filter(url_id = channel_id)\n \n if not(user_token.exists()):\n data[\"state\"] = \"fail\"\n data[\"message\"] = \"Token is not exist\"\n elif not(channel.exists()):\n data[\"state\"] = \"fail\"\n data[\"message\"] = \"Channel is not exist\"\n else:\n user = User.objects.get(id = user_token[0].user_id)\n if not(Guest.objects.filter(user = user, channel = channel[0]).exists()):\n data[\"state\"] = \"fail\"\n data[\"message\"] = \"User is not channel\\'s guest\"\n elif (Host.objects.filter(user = user, channel = channel[0]).exists()):\n data[\"state\"] = \"fail\"\n data[\"message\"] = \"Host cannot exit channel\"\n\n if bool(data):\n json.dumps(data, ensure_ascii=False, indent=\"\\t\")\n return JsonResponse(data, safe=False)\n\n user = User.objects.get(id = user_token[0].user_id)\n guest = Guest.objects.get(user = user, channel = channel[0])\n guest.delete()\n\n units = Unit.objects.filter(channel = channel[0])\n unittests = UnitTest.objects.filter(unit__in = units)\n tests = TestPlan.objects.filter(id__in = unittests.values_list('test', flat=True))\n testsets = TestSet.objects.filter(user = user, test__in = tests)\n testsets.delete()\n\n #feed 삭제 부분\n newses = News.objects.filter(channel = channel[0])\n UserNews.objects.filter(news__in = newses, user = user).delete()\n \n data[\"state\"] = \"success\"\n data[\"message\"] = \"Exit the channel completed\"\n\n host_channel_list = channelManager.requestHostChannelList(token)\n guest_channel_list = channelManager.requestGuestChannelList(token)\n host_length = len(host_channel_list)\n guest_length = len(guest_channel_list)\n\n data[\"leader\"] = [0 for i in range(host_length)]\n for i in range(host_length):\n host_channel = Channel.objects.filter(id=host_channel_list[i].id)\n serializer = ChannelIDSerializer(host_channel, many=True)\n data[\"leader\"][i] = OrderedDict()\n data[\"leader\"][i][\"id\"] = serializer.data[0]['url_id']\n data[\"leader\"][i][\"title\"] = host_channel_list[i].name\n data[\"leader\"][i][\"detail\"] = host_channel_list[i].description\n data[\"leader\"][i][\"image\"] = host_channel_list[i].image_type\n\n data[\"runner\"] = [0 for i in range(guest_length)]\n for i in range(guest_length):\n guest_channel = Channel.objects.filter(id=guest_channel_list[i].id)\n serializer = ChannelIDSerializer(guest_channel, many=True)\n data[\"runner\"][i] = OrderedDict()\n data[\"runner\"][i][\"id\"] = serializer.data[0]['url_id']\n data[\"runner\"][i][\"title\"] = guest_channel_list[i].name\n data[\"runner\"][i][\"detail\"] = guest_channel_list[i].description\n data[\"runner\"][i][\"image\"] = guest_channel_list[i].image_type\n\n json.dumps(data, ensure_ascii=False, indent=\"\\t\")\n\n return JsonResponse(data, safe=False)\n","sub_path":"polls/ChannelManager/GuestChannel/GuestChannel.py","file_name":"GuestChannel.py","file_ext":"py","file_size_in_byte":7463,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"50392569","text":"# ---\n# jupyter:\n# jupytext:\n# formats: ipynb,py:light\n# text_representation:\n# extension: .py\n# format_name: light\n# format_version: '1.5'\n# jupytext_version: 1.4.2\n# kernelspec:\n# display_name: Python 3\n# language: python\n# name: python3\n# ---\n\n# NOTES:\n# 1. matplotlib MUST be in 3.1.0; 3.1.1 ruins the heatmap\n\n# # Across-Site Statistics for Route Success Rates\n#\n# ### NOTE: Aggregate info is weighted by the contribution of each site\n\nimport pandas as pd\nimport xlrd\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nfrom math import pi\n# %matplotlib inline\n\n# +\nsheets = []\n\nfn1 = 'drug_routes_table_sheets_analytics_report.xlsx'\nfile_names = [fn1]\n\ns1 = 'Drug Exposure'\n\nsheet_names = [s1]\n\n# +\ntable_sheets = []\n\nfor file in file_names:\n for sheet in sheet_names:\n s = pd.read_excel(file, sheet)\n table_sheets.append(s)\n\ndate_cols = table_sheets[0].columns\ndate_cols = (list(date_cols))\n\nhpo_id_cols = table_sheets[0].index\nhpo_id_cols = (list(hpo_id_cols))\n# -\n\n# ### Converting the numbers as needed and putting into a dictionary\n\n# +\nnew_table_sheets = {}\n\nfor name, sheet in zip(sheet_names, table_sheets):\n sheet_cols = sheet.columns\n sheet_cols = sheet_cols[0:]\n new_df = pd.DataFrame(columns=sheet_cols)\n\n for col in sheet_cols:\n old_col = sheet[col]\n new_col = pd.to_numeric(old_col, errors='coerce')\n new_df[col] = new_col\n\n new_table_sheets[name] = new_df\n\n# +\nfig, ax = plt.subplots(figsize=(18, 12))\nsns.heatmap(new_table_sheets['Drug Exposure'], annot=True, annot_kws={\"size\": 10},\n fmt='g', linewidths=.5, ax=ax, yticklabels=hpo_id_cols,\n xticklabels=date_cols, cmap=\"RdYlGn\", vmin=0, vmax=100)\n\nax.set_title(\"Drug Table Route Population Rate\", size=14)\n# plt.savefig(\"drug_table_route_population_rate.jpg\")\n# -\n\n# # Now let's look at the metrics for particular sites with respect to route success rate. This will allow us to send them appropriate information.\n\nfn1_hpo_sheets = 'drug_routes_hpo_sheets_analytics_report.xlsx'\nfile_names_hpo_sheets = [fn1_hpo_sheets]\n\nx1 = pd.ExcelFile(fn1_hpo_sheets)\nsite_name_list = x1.sheet_names\n\n# +\nnum_hpo_sheets = len(site_name_list)\n\nprint(f\"There are {num_hpo_sheets} HPO sheets.\")\n\n# +\nname_of_interest = 'aggregate_info'\n\nif name_of_interest not in site_name_list:\n raise ValueError(\"Name not found in the list of HPO site names.\") \n\nfor idx, site in enumerate(site_name_list):\n if site == name_of_interest:\n idx_of_interest = idx\n\n# +\nhpo_sheets = []\n\nfor file in file_names_hpo_sheets:\n for sheet in site_name_list:\n s = pd.read_excel(file, sheet)\n hpo_sheets.append(s)\n \n\ntable_id_cols = list(hpo_sheets[0].index)\n\ndate_cols = table_sheets[0].columns\ndate_cols = (list(date_cols))\n\n# +\nnew_hpo_sheets = []\nstart_idx = 0\n\nfor sheet in hpo_sheets:\n sheet_cols = sheet.columns\n sheet_cols = sheet_cols[start_idx:]\n new_df = pd.DataFrame(columns=sheet_cols)\n\n for col in sheet_cols:\n old_col = sheet[col]\n new_col = pd.to_numeric(old_col, errors='coerce')\n new_df[col] = new_col\n\n new_hpo_sheets.append(new_df)\n# -\n\n# ### Showing for one particular site\n\n# +\nfig, ax = plt.subplots(figsize=(9, 6))\nsns.heatmap(new_hpo_sheets[idx_of_interest], annot=True, annot_kws={\"size\": 14},\n fmt='g', linewidths=.5, ax=ax, yticklabels=table_id_cols,\n xticklabels=date_cols, cmap=\"RdYlGn\", vmin=0, vmax=100)\n\nax.set_title(f\"Route Success Rates for {name_of_interest}\", size=14)\n\nplt.tight_layout()\nimg_name = name_of_interest + \"_route_population_rate.png\"\n\nplt.savefig(img_name)\n# -\n\ndates = new_hpo_sheets[idx_of_interest].columns\n\n# ## Want a line chart over time.\n\ntimes=new_hpo_sheets[idx_of_interest].columns.tolist()\n\n# +\nsuccess_rates = {}\n\nfor table_num, table_type in enumerate(table_id_cols):\n table_metrics_over_time = new_hpo_sheets[idx_of_interest].iloc[table_num]\n success_rates[table_type] = table_metrics_over_time.values.tolist()\n\ndate_idxs = []\nfor x in range(len(dates)):\n date_idxs.append(x)\n\n# +\nfor table, values_over_time in success_rates.items():\n sample_list = [x for x in success_rates[table] if str(x) != 'nan']\n if len(sample_list) > 1:\n plt.plot(date_idxs, success_rates[table], '--', label=table)\n \nfor table, values_over_time in success_rates.items():\n non_nan_idx = 0\n new_lst = []\n \n for idx, x in enumerate(success_rates[table]):\n if str(x) != 'nan':\n new_lst.append(x)\n non_nan_idx = idx\n \n if len(new_lst) == 1:\n plt.plot(date_idxs[non_nan_idx], new_lst, 'o', label=table)\n\nplt.legend(loc=\"upper left\", bbox_to_anchor=(1,1))\nplt.title(\"{name_of_interest} Route Success Rates Over Time\")\nplt.ylabel(\"Route Success Rate (%)\")\nplt.xlabel(\"\")\nplt.xticks(date_idxs, times, rotation = 'vertical')\n\nhandles, labels = ax.get_legend_handles_labels()\nlgd = ax.legend(handles, labels, loc='upper center', bbox_to_anchor=(0.5,-0.1))\n\nimg_name = name_of_interest + \"_route_population_rate_line_graph.jpg\"\n# plt.savefig(img_name, bbox_extraartist=(lgd,), bbox_inches='tight')\n# -\n\n","sub_path":"data_steward/analytics/tools/visualizations/conformance/route_concept_populations.py","file_name":"route_concept_populations.py","file_ext":"py","file_size_in_byte":5163,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"560199962","text":"# uncompyle6 version 3.7.4\n# Python bytecode 3.8 (3413)\n# Decompiled from: Python 3.6.9 (default, Apr 18 2020, 01:56:04) \n# [GCC 8.4.0]\n# Embedded file name: build/bdist.linux-x86_64/egg/staramr/results/QualityModule.py\n# Compiled at: 2019-12-17 17:26:02\n# Size of source mod 2**32: 16299 bytes\nimport logging\nfrom os import path\nfrom typing import Set\nimport pandas as pd\nfrom pandas import DataFrame\nfrom Bio import SeqIO\nlogger = logging.getLogger('QualityModule')\n\nclass QualityModule:\n\n def __init__(self, files, genome_size_lower_bound, genome_size_upper_bound, minimum_N50_value, minimum_contig_length, unacceptable_num_contigs) -> None:\n \"\"\"\n Constructs an object for summarizing our quality module.\n :param files: The list of genome files we have scanned against.\n :param genome_size_lower_bound: The lower bound for the genome size as defined by the user for quality metrics\n :param genome_size_upper_bound: The upper bound for the genome size as defined by the user for quality metrics\n :param minimum_N50_value: The minimum N50 value as defined by the user for quality metrics\n :param minimum_contig_length: The minimum contig length as defined by the user for quality metrics\n :param unacceptable_num_contigs: The number of contigs in a file, equal to or above our minimum contig length, for which to raise a flag as defined by the user for quality metrics\n \"\"\"\n self._files = files\n self._genome_size_lower_bound = genome_size_lower_bound\n self._genome_size_upper_bound = genome_size_upper_bound\n self._minimum_N50_value = minimum_N50_value\n self._minimum_contig_length = minimum_contig_length\n self._unacceptable_num_contigs = unacceptable_num_contigs\n\n def create_quality_module_dataframe(self):\n \"\"\"\n Goes through the files and creates a dataframe consisting of the file's genome length, N50 value and the number of contigs greater or equal to the minimum contig length as\n specified by the quality metrics. It also consists of the feedback for whether or not the file passed the quality metrics and if it didn't feedback on why it failed\n :return: A pd.dataframe containing the genome size, N50 value, number of contigs equal to or above our user defined minimum contig length\n as well as the results of our quality metrics (pass or fail) and the corresponding feedback\n \"\"\"\n name_set = []\n for myFile in self._files:\n name_set.append(path.splitext(path.basename(myFile))[0])\n else:\n files_contigs_and_genomes_lengths = self._get_files_contigs_and_genomes_lengths(self._files)\n files_genome_length_feedback = self._get_genome_length_feedback(files_contigs_and_genomes_lengths[1], self._genome_size_lower_bound, self._genome_size_upper_bound)\n files_N50_value_feedback = self._get_N50_feedback(files_contigs_and_genomes_lengths[0], files_contigs_and_genomes_lengths[1], self._minimum_N50_value)\n file_num_contigs_over_minimum_bp_feedback = self._get_num_contigs_over_minimum_bp_feedback(files_contigs_and_genomes_lengths[0], self._minimum_contig_length, self._unacceptable_num_contigs)\n quality_module = self._get_quality_module(files_genome_length_feedback, files_N50_value_feedback[1], file_num_contigs_over_minimum_bp_feedback[1])\n quality_module_feedback = quality_module[0]\n quality_module_result = quality_module[1]\n quality_metrics_module = pd.DataFrame([[file_name, genome_length, N50_value, num_contigs_over_minimum_bp] for file_name, genome_length, N50_value, num_contigs_over_minimum_bp in zip(name_set, files_contigs_and_genomes_lengths[1], files_N50_value_feedback[0], file_num_contigs_over_minimum_bp_feedback[0])],\n columns=(\n 'Isolate ID', 'Genome Length', 'N50 value', 'Number of Contigs Greater Than Or Equal To ' + str(self._minimum_contig_length) + ' bp')).set_index('Isolate ID')\n feedback_module = pd.DataFrame([[file_name, feedback, detailed_feedback] for file_name, feedback, detailed_feedback in zip(name_set, quality_module_result, quality_module_feedback)], columns=('Isolate ID',\n 'Quality Module',\n 'Quality Module Feedback')).set_index('Isolate ID')\n quality_module_frame = quality_metrics_module.merge(feedback_module, on='Isolate ID', how='left')\n return quality_module_frame\n\n def _get_files_contigs_and_genomes_lengths(self, files):\n \"\"\"\n Goes through the files and determines their genome length as well as the length of each contig\n :param files: The files for which we wish to determine the genome length as well as the length of each contig\n :return: An array where the first element is itself an array where each element represents the corresponding \n file and is itself an array where each element is the length for the corresponding contig inside of this file.\n The second element is itself an array where each element is the genome length for the corresponding file\n \"\"\"\n files_contig_lengths = []\n files_genome_lengths = []\n for file in files:\n contig_lengths = [len(record.seq) for record in SeqIO.parse(file, 'fasta')]\n files_contig_lengths.append(contig_lengths)\n files_genome_lengths.append(sum(contig_lengths))\n else:\n return [\n files_contig_lengths, files_genome_lengths]\n\n def _get_genome_length_feedback(self, files_genome_lengths, lb_gsize, ub_gsize):\n \"\"\"\n Goes through the files and determines whether or not they pass the quality metrics for genome length\n :param files_genome_lengths: An array where each element is the genome length of the corresponding file\n :param lb_gsize: The lower bound for the genome size as defined by the user for quality metrics\n :param ub_gsize: The upper bound for the genome size as defined by the user for quality metrics\n :return: An array where each element corresponds to the feedback (true or false) for the corresponding file in regards to the\n genome size quality metric\n \"\"\"\n files_genome_feedback = [genome_length >= lb_gsize and genome_length <= ub_gsize for genome_length in files_genome_lengths]\n return files_genome_feedback\n\n def _get_N50_feedback(self, files_contigs_lengths, files_genome_lengths, minimum_N50):\n \"\"\"\n Goes through the files and determines whether or not they pass the quality metrics for N50 value\n :param files_contigs_lengths: The lengths of the contigs for the files\n :param files_genome_lengths: An array where each element is the genome length of the corresponding file\n :param minimum_N50_value: The minimum N50 value as defined by the user for quality metrics\n :return: An array where the first element is itself an array where each element is the N50 value for \n the corresponding file. The second element is itself an array where each element is the feedback (true or false) \n for whether the corresponding file passes the N50 quality metrics\n \"\"\"\n feedback = []\n files_N50 = []\n N50_feedback = []\n for file_genome_length, file_contigs_lengths in zip(files_genome_lengths, files_contigs_lengths):\n half_length = file_genome_length / 2\n file_contigs_lengths.sort()\n contig_num = len(file_contigs_lengths)\n contig_index = 1\n sum_of_largest_contigs = 0\n if contig_index < contig_num:\n if sum_of_largest_contigs + file_contigs_lengths[(contig_num - contig_index)] >= half_length:\n break\n else:\n sum_of_largest_contigs = sum_of_largest_contigs + file_contigs_lengths[(contig_num - contig_index)]\n contig_index = contig_index + 1\n else:\n files_N50.append(file_contigs_lengths[(contig_num - contig_index)])\n else:\n for file_N50_value in files_N50:\n if file_N50_value > minimum_N50:\n N50_feedback.append(True)\n else:\n N50_feedback.append(False)\n else:\n feedback.append(files_N50)\n feedback.append(N50_feedback)\n return feedback\n\n def _get_num_contigs_over_minimum_bp_feedback(self, files_contigs_lengths, minimum_contig_length, unacceptable_num_contigs_over_minimum_bp):\n \"\"\"\n Goes through the files and determines whether or not they pass the quality metrics for the acceptable number of contigs equal to or above the minimum contig length\n :param files_contigs_lengths: The lengths of the contigs for the files\n :param minimum_contig_length: The minimum contig length as defined by the user for quality metrics\n :param unacceptable_num_contigs: The number of contigs in a file, equal to or above our minimum contig length, for which to raise a flag as defined by the user for quality metrics\n :return: An array where the first element is itself an array where each element is the number of contigs equal to or above the minimum contig length for\n the corresponding file. The second element is itself an array where each element is the feedback (True or False) \n for whether the corresponding file passes the acceptable number of contigs equal to or above the minimum contig length quality metric\n \"\"\"\n feedback = []\n file_num_contigs = []\n contigs_over_minimum_bp_feedback = []\n for file_contigs_lengths in files_contigs_lengths:\n num_contigs = 0\n\n for contig in file_contigs_lengths:\n if contig >= minimum_contig_length:\n num_contigs = num_contigs + 1\n file_num_contigs.append(num_contigs)\n else:\n for file_num_contigs_over_minimum_bp in file_num_contigs:\n if file_num_contigs_over_minimum_bp >= unacceptable_num_contigs_over_minimum_bp:\n contigs_over_minimum_bp_feedback.append(False)\n else:\n contigs_over_minimum_bp_feedback.append(True)\n else:\n feedback.append(file_num_contigs)\n feedback.append(contigs_over_minimum_bp_feedback)\n return feedback\n\n def _get_quality_module(self, genome_length_feedback, N50_feedback, contigs_over_minimum_bp_feedback):\n \"\"\"\n Goes through the files and for each provides detailed feedback for why they failed the quality metrics\n :param genome_length_feedback: An array where each element is the feedback (true or false) for the corresponding file in regards to the\n genome length quality metric\n :param N50_feedback: An array where each element is the feedback (true or false) for the corresponding file in regards to the\n the N50 quality metric\n :param contigs_over_minimum_bp_feedback: An array where each element is the feedback (true or false) for the corresponding file in regards to the\n the acceptable number of contigs equal to or above the minimum contig length quality metric\n :return: An array where the first element is itself an array where each element is the detailed quality metric feedback for\n the corresponding file. The second element is itself an array where each element is the feedback (true or false) \n for whether the corresponding file passes all of the quality metrics\n \"\"\"\n feedback = []\n quality_parameter = []\n quality_parameter_feedback = []\n for file_genome_length_feedback, file_N50_feedback, file_contigs_over_minimum_bp_feedback in zip(genome_length_feedback, N50_feedback, contigs_over_minimum_bp_feedback):\n if all([file_genome_length_feedback, file_N50_feedback, file_contigs_over_minimum_bp_feedback]):\n quality_parameter_feedback_for_file = ''\n quality_parameter.append('Passed')\n else:\n failed_feedback = []\n quality_parameter.append('Failed')\n if file_genome_length_feedback == False:\n failed_feedback.append('Genome length is not within the acceptable length range [{},{}]'.format(self._genome_size_lower_bound, self._genome_size_upper_bound))\n if file_N50_feedback == False:\n failed_feedback.append('N50 value is not greater than the specified minimum value [{}]'.format(self._minimum_N50_value))\n if file_contigs_over_minimum_bp_feedback == False:\n failed_feedback.append('Number of Contigs with a length greater than or equal to the minimum Contig length [{}] exceeds the acceptable number [{}]'.format(self._minimum_contig_length, self._unacceptable_num_contigs))\n quality_parameter_feedback_for_file = ' ; '.join(failed_feedback)\n quality_parameter_feedback.append(quality_parameter_feedback_for_file)\n else:\n feedback.append(quality_parameter_feedback)\n feedback.append(quality_parameter)\n return feedback","sub_path":"pycfiles/staramr-0.7.1-py3.8/QualityModule.cpython-38.py","file_name":"QualityModule.cpython-38.py","file_ext":"py","file_size_in_byte":13647,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"470611860","text":"\"\"\"\n@author Wildo Monges\nThis class train a classifier using naive bayes algorithm\n\"\"\"\n\nfrom naive_bayes_classifier.model import Model\nimport re\nimport math\n\ndef train(model, files, c, K):\n \"\"\"\n Train a model\n :param model: model\n :param files: list of files\n :param c: class\n :param K: Laplace Smoothing factor\n :return: model\n \"\"\"\n if model is None:\n model = Model()\n model.set_total_files_by_class(c, len(files))\n # for each file in the directory (c is the class)\n for file in files:\n f = open(file)\n buffer = f.read()\n buffer = re.sub(r'([^\\s\\w]|_)+', ' ', buffer)\n for word in buffer.lower().split():\n model.add_word_by_class(word, c)\n model.calculate_probability(K)\n return model\n\n\ndef classify(model, file, K):\n \"\"\"\n Classify using the model\n :param model:\n :param file:\n :param K:\n :return: class\n \"\"\"\n if model is None:\n return None\n classes = model.classes.keys()\n f = open(file)\n buffer = f.read()\n buffer = re.sub(r'([^\\s\\w]|_)+', ' ', buffer)\n probabilities = []\n for c in classes:\n prob_by_class = model.get_probability_by_class(c)\n probability = math.log((1 - prob_by_class) / prob_by_class)\n for word in buffer.lower().split():\n total_word_by_class = model.get_total_word_by_class(word, c)\n total_all_words = model.get_total_words()\n total_words_by_class = model.get_total_words_by_class(c)\n laplace = model.laplace_smoothing(total_word_by_class, total_all_words, total_words_by_class, K)\n pb = math.log((1 - laplace) / laplace)\n probability = probability * pb\n probabilities.append((c, probability))\n return model.calculate_total_probability(probabilities)[0][0]\n","sub_path":"naive_bayes_classifier/naive_bayes.py","file_name":"naive_bayes.py","file_ext":"py","file_size_in_byte":1818,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"151545970","text":"#!/usr/bin/python2\n\n# program to convert density to pression\n# by use of the three first virial coefficients.\n\nimport scipy.optimize\nimport sys\n\n\n\nT = 294.5 # Kelvins (ambiant temperature)\n\nR = 8.3143 # J . K^-1 . mol^-1#R = 83.143\n\nV0 = 0.0220764 # m^3 . mol^-1#V0 = 22076.4\n\nP0 = 100000 # N . m^-2 (pression atmospherique)\n\nP0_t_V0 = 22076.4 #\n#R_t_T = \nfront_constant = ( R * T ) / ( P0 * V0 )\n\nA = ( R * T ) / ( P0 * V0 )\n\n#B = -2.8513e-4\n#C = 1.93974e-8\n\nB = -2.8513e-4\n\nC = 1.93974e-8\n\n\n#B = -285.13\n#C = 1939.74\n#density = 19 # amagats (dimensionless)\n\ndef pression( rho ) :\n # rho is in amagats SI units\n\n P = front_constant * ( rho + ( B / V0 ) * ( rho ** 2 ) + \\\n ( C / ( V0 ** 2 ) ) * ( rho ** 3 ) )\n #print front_constant, ( B / V0 ) , ( C / ( V0 ** 2 ) ) \n return P\n\ndef density( P ) :\n assert 1. < P < 22.\n rho = scipy.optimize.bisect( lambda x : pression ( x ) - P , 1. , 30. )\n return rho\n \ndef main():\n try : \n P = float( sys.argv[1] )\n \n print ( density( P ) )\n except :\n \n sys.exit(0)\n \nif __name__=='__main__' :\n main()","sub_path":"python_scripts/convert_density_pression.py","file_name":"convert_density_pression.py","file_ext":"py","file_size_in_byte":1126,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"321345591","text":"import asyncio\n\nimport pytest\n\nfrom dephell.constants import DEFAULT_WAREHOUSE\nfrom dephell.controllers import DependencyMaker\nfrom dephell.models import RootDependency\nfrom dephell.repositories import WarehouseSimpleRepo\n\n\nloop = asyncio.get_event_loop()\n\n\n@pytest.mark.parametrize('fname, name, version', [\n ('dephell-0.7.3-py3-none-any.whl', 'dephell', '0.7.3'),\n ('dephell-0.7.3.tar.gz', 'dephell', '0.7.3'),\n\n ('flake8_commas-2.0.0-py2.py3-none-any.whl', 'flake8_commas', '2.0.0'),\n ('flake8-commas-2.0.0.tar.gz ', 'flake8-commas', '2.0.0'),\n])\ndef test_parse_name(fname, name, version):\n assert WarehouseSimpleRepo._parse_name(fname) == (name, version)\n\n\n@pytest.mark.allow_hosts()\ndef test_get_releases():\n root = RootDependency()\n dep = DependencyMaker.from_requirement(source=root, req='dephell')[0]\n repo = WarehouseSimpleRepo(name='pypi', url=DEFAULT_WAREHOUSE)\n releases = repo.get_releases(dep=dep)\n releases = {str(r.version): r for r in releases}\n assert '0.7.0' in set(releases)\n assert str(releases['0.7.0'].python) == '>=3.5'\n assert len(releases['0.7.0'].hashes) == 2\n\n\n@pytest.mark.allow_hosts()\ndef test_extra():\n repo = WarehouseSimpleRepo(name='pypi', url=DEFAULT_WAREHOUSE)\n\n coroutine = repo.get_dependencies(name='requests', version='2.21.0')\n deps = loop.run_until_complete(asyncio.gather(coroutine))[0]\n deps = {dep.name: dep for dep in deps}\n assert 'chardet' in deps\n assert 'cryptography' not in deps\n assert 'win-inet-pton' not in deps\n\n coroutine = repo.get_dependencies(name='requests', version='2.21.0', extra='security')\n deps = loop.run_until_complete(asyncio.gather(coroutine))[0]\n deps = {dep.name: dep for dep in deps}\n assert 'chardet' not in deps\n assert 'win-inet-pton' not in deps\n assert 'cryptography' in deps\n","sub_path":"tests/test_repositories/test_warehouse_simple.py","file_name":"test_warehouse_simple.py","file_ext":"py","file_size_in_byte":1834,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"602842276","text":"# Authors: Mathieu Andreux, Joakim Anden, Edouard Oyallon\n# Scientific Ancestry: Mathieu Andreux, Vincent Lostanlen, Joakim Anden\n\nimport torch\nimport numpy as np\nimport math\n\nimport warnings\n\nfrom .backend import pad, unpad, real, subsample_fourier, modulus_complex, fft1d_c2c, ifft1d_c2c\nfrom .utils import compute_padding, compute_border_indices\nfrom .utils import cast_psi, cast_phi\n\nfrom .filter_bank import scattering_filter_factory\nfrom .filter_bank import calibrate_scattering_filters\n\n\ndef compute_minimum_support_to_pad(T, J, Q, criterion_amplitude=1e-3,\n normalize='l1', r_psi=math.sqrt(0.5),\n sigma0=1e-1, alpha=5., P_max=5, eps=1e-7):\n \"\"\"\n Computes the support to pad given the input size and the parameters of the\n scattering transform.\n\n Parameters\n ----------\n T : int\n temporal size of the input signal\n J : int\n scale of the scattering\n Q : int\n number of wavelets per octave\n normalize : string, optional\n normalization type for the wavelets.\n Only 'l2' or 'l1' normalizations are supported.\n Defaults to 'l1'\n criterion_amplitude: float >0 and <1, optional\n Represents the numerical error which is allowed to be lost after\n convolution and padding.\n The larger criterion_amplitude, the smaller the padding size is.\n Defaults to 1e-3\n r_psi : float, optional\n Should be >0 and <1. Controls the redundancy of the filters\n (the larger r_psi, the larger the overlap between adjacent\n wavelets). Defaults to sqrt(0.5).\n sigma0 : float, optional\n parameter controlling the frequential width of the\n low-pass filter at J_scattering=0; at a an absolute J_scattering,\n it is equal to :math:`\\\\frac{\\\\sigma_0}{2^J}`. Defaults to 1e-1\n alpha : float, optional\n tolerance factor for the aliasing after subsampling.\n The larger alpha, the more conservative the value of maximal\n subsampling is. Defaults to 5.\n P_max : int, optional\n maximal number of periods to use to make sure that the Fourier transform\n of the filters is periodic. P_max = 5 is more than enough for double\n precision. Defaults to 5\n eps : float, optional\n required machine precision for the periodization (single\n floating point is enough for deep learning applications).\n Defaults to 1e-7\n\n Returns\n -------\n min_to_pad: int\n minimal value to pad the signal on one size to avoid any\n boundary error\n \"\"\"\n J_tentative = int(np.ceil(np.log2(T)))\n _, _, _, t_max_phi = scattering_filter_factory(\n J_tentative, J, Q, normalize=normalize, to_torch=False,\n max_subsampling=0, criterion_amplitude=criterion_amplitude,\n r_psi=r_psi, sigma0=sigma0, alpha=alpha, P_max=P_max, eps=eps)\n min_to_pad = 3 * t_max_phi\n return min_to_pad\n\n\nclass Scattering1D(object):\n \"\"\"The 1D scattering transform\n\n The scattering transform computes a cascade of wavelet transforms\n alternated with a complex modulus non-linearity. The scattering transform\n of a 1D signal :math:`x(t)` may be written as\n\n :math:`S_J x = [S_J^{(0)} x, S_J^{(1)} x, S_J^{(2)} x]`\n\n where\n\n :math:`S_J^{(0)} x(t) = x \\\\star \\\\phi_J(t)`,\n\n :math:`S_J^{(1)} x(t, \\\\lambda) = |x \\\\star \\\\psi_\\\\lambda^{(1)}| \\\\star \\\\phi_J`, and\n\n :math:`S_J^{(2)} x(t, \\\\lambda, \\\\mu) = |\\\\,| x \\\\star \\\\psi_\\\\lambda^{(1)}| \\\\star \\\\psi_\\\\mu^{(2)} | \\\\star \\\\phi_J`.\n\n In the above formulas, :math:`\\\\star` denotes convolution in time. The\n filters :math:`\\\\psi_\\\\lambda^{(1)}(t)` and :math:`\\\\psi_\\\\mu^{(2)}(t)`\n are analytic wavelets with center frequencies :math:`\\\\lambda` and\n :math:`\\\\mu``, while :math:`\\\\phi_J(t)` is a real lowpass filter centered\n at the zero frequency.\n\n The `Scattering1D` class implements the 1D scattering transform for a\n given set of filters whose parameters are specified at initialization.\n While the wavelets are fixed, other parameters may be changed after the\n object is created, such as whether to compute all of :math:`S_J^{(0)} x`,\n :math:`S_J^{(1)} x`, and :math:`S_J^{(2)} x` or just :math:`S_J^{(0)} x`\n and :math:`S_J^{(1)} x`.\n\n The scattering transform may be computed on the CPU (the default) or a\n GPU, if available. A `Scattering1D` object may be transferred from one\n to the other using the `cuda()` and `cpu()` methods.\n\n Given an input Tensor `x` of size `(B, 1, T)`, where `B` is the number of\n signals to transform (the batch size) and `T` is the length of the signal,\n we compute its scattering transform by passing it to the `forward()`\n method.\n\n Example\n -------\n ::\n\n # Set the parameters of the scattering transform.\n T = 2**13\n J = 6\n Q = 8\n\n # Generate a sample signal.\n x = torch.randn(1, 1, T)\n\n # Define a Scattering1D object.\n S = Scattering1D(T, J, Q)\n\n # Calculate the scattering transform.\n Sx = S.forward(x)\n\n Above, the length of the signal is `T = 2**13 = 8192`, while the maximum\n scale of the scattering transform is set to `2**J = 2**6 = 64`. The\n time-frequency resolution of the first-order wavelets\n :math:`\\\\psi_\\\\lambda^{(1)}(t)` is set to `Q = 8` wavelets per octave.\n The second-order wavelets :math:`\\\\psi_\\\\mu^{(2)}(t)` always have one\n wavelet per octave.\n\n Parameters\n ----------\n T : int\n The length of the input signals.\n J : int\n The maximum log-scale of the scattering transform. In other words,\n the maximum scale is given by `2**J`.\n Q : int >= 1\n The number of first-order wavelets per octave (second-order wavelets\n are fixed to one wavelet per octave).\n normalize : string, optional\n Normalization of the wavelets: `'l1'`, corresponding to\n :math:`\\\\ell^1`-normalization, or `'l2'`, corresponding to\n :math:`\\\\ell^2`-normalization. Defaults to `'l1'`.\n criterion_amplitude : float, optional\n Controls the padding size (the larger this value, the smaller the\n padding size). Measures the amount of the Gaussian mass (in the\n :math:`\\\\ell^1` norm) which can be ignored after padding. Defaults\n to `1e-3`.\n r_psi : float, optional\n Controls the redundancy of the filters (the larger this value, the\n larger the overlap between adjacent wavelets). Must be between zero\n and one. Defaults to `math.sqrt(0.5)`.\n sigma0 : float, optional\n Controls the frequency bandwidth of the lowpass filter\n :math:`\\\\phi_J(t)`, which is given by `sigma0/2**J`. Defaults to\n `1e-1`.\n alpha : float, optional\n Aliasing tolerance after subsampling. The larger this value, the more\n conservative the subsampling during the transform. Defaults to `5`.\n P_max : int > 1, optional\n Maximum number of periods to use to ensure that the Fourier transform\n of the filters is periodic. Defaults to `5`.\n eps : float, optional\n Required precision for the periodization. Defaults to `1e-7`.\n max_order : int, optional\n The maximum order of scattering coefficients to compute. Must be one\n `1` or `2`. This parameter may be modified after object creation.\n Defaults to `2`.\n average : boolean, optional\n Determines whether the output is averaged in time or not. The averaged\n output corresponds to the standard scattering transform, while the\n un-averaged output skips the last convolution by :math:`\\\\phi_J(t)`.\n This parameter may be modified after object creation.\n Defaults to `True`.\n oversampling : integer >= 0, optional\n Controls the oversampling factor relative to the default as a power\n of two. Since the convolving by wavelets (or lowpass filters) and\n taking the modulus reduces the high-frequency content of the signal,\n we can subsample to save space and improve performance. However, this\n may reduce precision in the calculation. If this is not desirable,\n `oversampling` can be set to a large value to prevent too much\n subsampling. This parameter may be modified after object creation.\n Defaults to `0`.\n vectorize : boolean, optional\n Determines wheter to return a vectorized scattering transform (that\n is, a large array containing the output) or a dictionary (where each\n entry corresponds to a separate scattering coefficient). This parameter\n may be modified after object creation. Defaults to True.\n\n Attributes\n ----------\n T : int\n The length of the input signals.\n J : int\n The maximum log-scale of the scattering transform. In other words,\n the maximum scale is given by `2**J`.\n Q : int\n The number of first-order wavelets per octave (second-order wavelets\n are fixed to one wavelet per octave).\n J_pad : int\n The logarithm of the padded length of the signals.\n pad_left : int\n The amount of padding to the left of the signal.\n pad_right : int\n The amount of padding to the right of the signal.\n phi_f : dictionary\n A dictionary containing the lowpass filter at all resolutions. See\n `filter_bank.scattering_filter_factory` for an exact description.\n psi1_f : dictionary\n A dictionary containing all the first-order wavelet filters, each\n represented as a dictionary containing that filter at all\n resolutions. See `filter_bank.scattering_filter_factory` for an exact\n description.\n psi2_f : dictionary\n A dictionary containing all the second-order wavelet filters, each\n represented as a dictionary containing that filter at all\n resolutions. See `filter_bank.scattering_filter_factory` for an exact\n description.\n description\n max_order : int\n The maximum scattering order of the transform.\n average : boolean\n Controls whether the output should be averaged (the standard\n scattering transform) or not (resulting in wavelet modulus\n coefficients). Note that to obtain unaveraged output, the `vectorize`\n flag must be set to `False`.\n oversampling : int\n The number of powers of two to oversample the output compared to the\n default subsampling rate determined from the filters.\n vectorize : boolean\n Controls whether the output should be vectorized into a single Tensor\n or collected into a dictionary. For more details, see the\n documentation for `forward()`.\n \"\"\"\n def __init__(self, T, J, Q, normalize='l1', criterion_amplitude=1e-3,\n r_psi=math.sqrt(0.5), sigma0=0.1, alpha=5.,\n P_max=5, eps=1e-7, max_order=2, average=True,\n oversampling=0, vectorize=True):\n super(Scattering1D, self).__init__()\n # Store the parameters\n self.T = T\n self.J = J\n self.Q = Q\n self.r_psi = r_psi\n self.sigma0 = sigma0\n self.alpha = alpha\n self.P_max = P_max\n self.eps = eps\n self.criterion_amplitude = criterion_amplitude\n self.normalize = normalize\n # Build internal values\n self.build()\n self.max_order = max_order\n self.average = average\n self.oversampling = oversampling\n self.vectorize = vectorize\n\n def build(self):\n \"\"\"Set up padding and filters\n\n Certain internal data, such as the amount of padding and the wavelet\n filters to be used in the scattering transform, need to be computed\n from the parameters given during construction. This function is called\n automatically during object creation and no subsequent calls are\n therefore needed.\n \"\"\"\n # Compute the minimum support to pad (ideally)\n min_to_pad = compute_minimum_support_to_pad(\n self.T, self.J, self.Q, r_psi=self.r_psi, sigma0=self.sigma0,\n alpha=self.alpha, P_max=self.P_max, eps=self.eps,\n criterion_amplitude=self.criterion_amplitude,\n normalize=self.normalize)\n # to avoid padding more than T - 1 on the left and on the right,\n # since otherwise torch sends nans\n J_max_support = int(np.floor(np.log2(3 * self.T - 2)))\n self.J_pad = min(int(np.ceil(np.log2(self.T + 2 * min_to_pad))),\n J_max_support)\n # compute the padding quantities:\n self.pad_left, self.pad_right = compute_padding(self.J_pad, self.T)\n # compute start and end indices\n self.ind_start, self.ind_end = compute_border_indices(\n self.J, self.pad_left, self.pad_left + self.T)\n # Finally, precompute the filters\n phi_f, psi1_f, psi2_f, _ = scattering_filter_factory(\n self.J_pad, self.J, self.Q, normalize=self.normalize,\n to_torch=True, criterion_amplitude=self.criterion_amplitude,\n r_psi=self.r_psi, sigma0=self.sigma0, alpha=self.alpha,\n P_max=self.P_max, eps=self.eps)\n self.psi1_f = psi1_f\n self.psi2_f = psi2_f\n self.phi_f = phi_f\n self._type(torch.FloatTensor)\n\n def _type(self, target_type):\n \"\"\"Change the datatype of the filters\n\n This function is used internally to convert the filters. It does not\n need to be called explicitly.\n\n Parameters\n ----------\n target_type : type\n The desired type of the filters, typically `torch.FloatTensor`\n or `torch.cuda.FloatTensor`.\n \"\"\"\n cast_psi(self.psi1_f, target_type)\n cast_psi(self.psi2_f, target_type)\n cast_phi(self.phi_f, target_type)\n return self\n\n def cpu(self):\n \"\"\"Move to the CPU\n\n This function prepares the object to accept input Tensors on the CPU.\n \"\"\"\n return self._type(torch.FloatTensor)\n\n def cuda(self):\n \"\"\"Move to the GPU\n\n This function prepares the object to accept input Tensors on the GPU.\n \"\"\"\n return self._type(torch.cuda.FloatTensor)\n\n def meta(self):\n \"\"\"Get meta information on the transform\n\n Calls the static method `compute_meta_scattering()` with the\n parameters of the transform object.\n\n Returns\n ------\n meta : dictionary\n See the documentation for `compute_meta_scattering()`.\n \"\"\"\n return Scattering1D.compute_meta_scattering(self.J, self.Q,\n max_order=self.max_order)\n\n def output_size(self, detail=False):\n \"\"\"Get size of the scattering transform\n\n Calls the static method `precompute_size_scattering()` with the\n parameters of the transform object.\n\n Parameters\n ----------\n detail : boolean, optional\n Specifies whether to provide a detailed size (number of coefficient\n per order) or an aggregate size (total number of coefficients).\n\n Returns\n ------\n size : int or tuple\n See the documentation for `precompute_size_scattering()`.\n \"\"\"\n\n return Scattering1D.precompute_size_scattering(self.J, self.Q,\n max_order=self.max_order, detail=detail)\n\n def forward(self, x):\n \"\"\"Apply the scattering transform\n\n Given an input Tensor of size `(B, 1, T0)`, where `B` is the batch\n size and `T0` is the length of the individual signals, this function\n computes its scattering transform. If the `vectorize` flag is set to \n `True`, the output is in the form of a Tensor or size `(B, C, T1)`,\n where `T1` is the signal length after subsampling to the scale `2**J`\n (with the appropriate oversampling factor to reduce aliasing), and \n `C` is the number of scattering coefficients. If `vectorize` is set\n `False`, however, the output is a dictionary containing `C` keys, each\n a tuple whose length corresponds to the scattering order and whose\n elements are the sequence of filter indices used.\n\n Furthermore, if the `average` flag is set to `False`, these outputs\n are not averaged, but are simply the wavelet modulus coefficients of\n the filters.\n\n Parameters\n ----------\n x : tensor\n An input Tensor of size `(B, 1, T0)`.\n\n Returns\n -------\n S : tensor or dictionary\n If the `vectorize` flag is `True`, the output is a Tensor\n containing the scattering coefficients, while if `vectorize`\n is `False`, it is a dictionary indexed by tuples of filter indices.\n \"\"\"\n # basic checking, should be improved\n if len(x.shape) != 3:\n raise ValueError(\n 'Input tensor x should have 3 axis, got {}'.format(\n len(x.shape)))\n if x.shape[1] != 1:\n raise ValueError(\n 'Input tensor should only have 1 channel, got {}'.format(\n x.shape[1]))\n # get the arguments before calling the scattering\n # treat the arguments\n if self.vectorize:\n if not(self.average):\n raise ValueError(\n 'Options average=False and vectorize=True are ' +\n 'mutually incompatible. Please set vectorize to False.')\n size_scattering = self.precompute_size_scattering(\n self.J, self.Q, max_order=self.max_order, detail=False)\n else:\n size_scattering = 0\n S = scattering(x, self.psi1_f, self.psi2_f, self.phi_f,\n self.J, max_order=self.max_order, average=self.average,\n pad_left=self.pad_left, pad_right=self.pad_right,\n ind_start=self.ind_start, ind_end=self.ind_end,\n oversampling=self.oversampling,\n vectorize=self.vectorize, size_scattering=size_scattering)\n return S\n\n def __call__(self, x):\n return self.forward(x)\n\n @staticmethod\n def compute_meta_scattering(J, Q, max_order=2):\n \"\"\"Get metadata on the transform\n\n This information specifies the content of each scattering coefficient,\n which order, which frequencies, which filters were used, and so on.\n\n Parameters\n ----------\n J : int\n The maximum log-scale of the scattering transform. In other words,\n the maximum scale is given by `2**J`.\n Q : int >= 1\n The number of first-order wavelets per octave (second-order wavelets\n are fixed to one wavelet per octave).\n max_order : int, optional\n The maximum order of scattering coefficients to compute. Must be one\n `1` or `2`. Defaults to `2`.\n\n Returns\n -------\n meta : dictionary\n A dictionary with the following keys:\n\n - `'order`' : tensor\n A Tensor of length `C`, the total number of scattering\n coefficients, specifying the scattering order.\n - `'xi'` : tensor\n A Tensor of size `(C, max_order)`, specifying the center\n frequency of the filter used at each order (padded with NaNs).\n - `'sigma'` : tensor\n A Tensor of size `(C, max_order)`, specifying the frequency\n bandwidth of the filter used at each order (padded with NaNs).\n - `'j'` : tensor\n A Tensor of size `(C, max_order)`, specifying the dyadic scale\n of the filter used at each order (padded with NaNs).\n - `'n'` : tensor\n A Tensor of size `(C, max_order)`, specifying the indices of\n the filters used at each order (padded with NaNs).\n - `'key'` : list\n The tuples indexing the corresponding scattering coefficient\n in the non-vectorized output.\n \"\"\"\n sigma_low, xi1s, sigma1s, j1s, xi2s, sigma2s, j2s = \\\n calibrate_scattering_filters(J, Q)\n\n meta = {}\n\n meta['order'] = []\n meta['xi'] = []\n meta['sigma'] = []\n meta['j'] = []\n meta['n'] = []\n meta['key'] = []\n\n meta['order'].append(0)\n meta['xi'].append(())\n meta['sigma'].append(())\n meta['j'].append(())\n meta['n'].append(())\n meta['key'].append(())\n\n for (n1, (xi1, sigma1, j1)) in enumerate(zip(xi1s, sigma1s, j1s)):\n meta['order'].append(1)\n meta['xi'].append((xi1,))\n meta['sigma'].append((sigma1,))\n meta['j'].append((j1,))\n meta['n'].append((n1,))\n meta['key'].append((n1,))\n\n if max_order < 2:\n continue\n\n for (n2, (xi2, sigma2, j2)) in enumerate(zip(xi2s, sigma2s, j2s)):\n if j2 > j1:\n meta['order'].append(2)\n meta['xi'].append((xi1, xi2))\n meta['sigma'].append((sigma1, sigma2))\n meta['j'].append((j1, j2))\n meta['n'].append((n1, n2))\n meta['key'].append((n1, n2))\n\n pad_fields = ['xi', 'sigma', 'j', 'n']\n pad_len = max_order\n\n for field in pad_fields:\n meta[field] = [x+(math.nan,)*(pad_len-len(x)) for x in meta[field]]\n\n array_fields = ['order', 'xi', 'sigma', 'j', 'n']\n\n for field in array_fields:\n meta[field] = torch.from_numpy(np.array(meta[field]))\n\n return meta\n\n @staticmethod\n def precompute_size_scattering(J, Q, max_order=2, detail=False):\n \"\"\"Get size of the scattering transform\n\n The number of scattering coefficients depends on the filter\n configuration and so can be calculated using a few of the scattering\n transform parameters.\n\n Parameters\n ----------\n J : int\n The maximum log-scale of the scattering transform. In other words,\n the maximum scale is given by `2**J`.\n Q : int >= 1\n The number of first-order wavelets per octave (second-order wavelets\n are fixed to one wavelet per octave).\n max_order : int, optional\n The maximum order of scattering coefficients to compute. Must be one\n `1` or `2`. Defaults to `2`.\n detail : boolean, optional\n Specifies whether to provide a detailed size (number of coefficient\n per order) or an aggregate size (total number of coefficients).\n\n Returns\n -------\n size : int or tuple\n If `detail` is `False`, returns the number of coefficients as an \n integer. If `True`, returns a tuple of size `max_order` containing\n the number of coefficients in each order.\n \"\"\"\n sigma_low, xi1, sigma1, j1, xi2, sigma2, j2 = \\\n calibrate_scattering_filters(J, Q)\n\n size_order0 = 1\n size_order1 = len(xi1)\n size_order2 = 0\n for n1 in range(len(xi1)):\n for n2 in range(len(xi2)):\n if j2[n2] > j1[n1]:\n size_order2 += 1\n if detail:\n return size_order0, size_order1, size_order2\n else:\n if max_order == 2:\n return size_order0 + size_order1 + size_order2\n else:\n return size_order0 + size_order1\n\n\ndef scattering(x, psi1, psi2, phi, J, pad_left=0, pad_right=0,\n ind_start=None, ind_end=None, oversampling=0,\n max_order=2, average=True, size_scattering=0, vectorize=False):\n \"\"\"\n Main function implementing the scattering computation.\n\n Parameters\n ----------\n x : Tensor\n a torch Tensor of size (B, 1, T) where T is the temporal size\n psi1 : dictionary\n a dictionary of filters (in the Fourier domain), with keys (j, n)\n j corresponds to the downsampling factor for x \\\\ast psi1[(j, q)].\n n corresponds to an arbitrary numbering\n * psi1[(j, n)] is itself a dictionary, with keys corresponding to the\n dilation factors: psi1[(j, n)][j2] corresponds to a support of size\n :math:`2^{J_\\text{max} - j_2}`, where :math:`J_\\text{max}` has been defined a priori\n (J_max = size of the padding support of the input)\n * psi1[(j, n)] only has real values;\n the tensors are complex so that broadcasting applies\n psi2 : dictionary\n a dictionary of filters, with keys (j2, n2). Same remarks as for psi1\n phi : dictionary\n a dictionary of filters of scale :math:`2^J` with keys (j) where j is the\n downsampling factor: phi[j] is a (real) filter\n J : int\n scale of the scattering\n pad_left : int, optional\n how much to pad the signal on the left. Defaults to 0\n pad_right : int, optional\n how much to pad the signal on the right. Defaults to 0\n ind_start : dictionary of ints, optional\n indices to truncate the signal to recover only the\n parts which correspond to the actual signal after padding and\n downsampling. Defaults to None\n ind_end : dictionary of ints, optional\n See description of ind_start\n oversampling : int, optional\n how much to oversample the scattering (with respect to :math:`2^J`):\n the higher, the larger the resulting scattering\n tensor along time. Defaults to 0\n order2 : boolean, optional\n Whether to compute the 2nd order or not. Defaults to False.\n average_U1 : boolean, optional\n whether to average the first order vector. Defaults to True\n size_scattering : dictionary or int, optional\n contains the number of channels of the scattering,\n precomputed for speed-up. Defaults to 0\n vectorize : boolean, optional\n whether to return a dictionary or a tensor. Defaults to False.\n\n \"\"\"\n # S is simply a dictionary if we do not perform the averaging...\n if vectorize:\n batch_size = x.shape[0]\n kJ = max(J - oversampling, 0)\n temporal_size = ind_end[kJ] - ind_start[kJ]\n S = x.new(batch_size, size_scattering, temporal_size).fill_(0.)\n else:\n S = {}\n\n # pad to a dyadic size and make it complex\n U0 = pad(x, pad_left=pad_left, pad_right=pad_right, to_complex=True)\n # compute the Fourier transform\n U0_hat = fft1d_c2c(U0)\n # initialize the cursor\n cc = 0 # current coordinate\n # Get S0\n k0 = max(J - oversampling, 0)\n if average:\n S0_J_hat = subsample_fourier(U0_hat * phi[0], 2**k0)\n S0_J = unpad(real(ifft1d_c2c(S0_J_hat)),\n ind_start[k0], ind_end[k0])\n else:\n S0_J = x\n if vectorize:\n S[:, cc, :] = S0_J.squeeze(dim=1)\n cc += 1\n else:\n S[()] = S0_J\n # First order:\n for n1 in range(len(psi1)):\n # Convolution + downsampling\n j1 = psi1[n1]['j']\n k1 = max(j1 - oversampling, 0)\n assert psi1[n1]['xi'] < 0.5 / (2**k1)\n U1_hat = subsample_fourier(U0_hat * psi1[n1][0], 2**k1)\n # Take the modulus\n U1 = modulus_complex(ifft1d_c2c(U1_hat))\n if average or max_order > 1:\n U1_hat = fft1d_c2c(U1)\n if average:\n # Convolve with phi_J\n k1_J = max(J - k1 - oversampling, 0)\n S1_J_hat = subsample_fourier(U1_hat * phi[k1], 2**k1_J)\n S1_J = unpad(real(ifft1d_c2c(S1_J_hat)),\n ind_start[k1_J + k1], ind_end[k1_J + k1])\n else:\n # just take the real value and unpad\n S1_J = unpad(real(U1), ind_start[k1], ind_end[k1])\n if vectorize:\n S[:, cc, :] = S1_J.squeeze(dim=1)\n cc += 1\n else:\n S[n1,] = S1_J\n if max_order == 2:\n # 2nd order\n for n2 in range(len(psi2)):\n j2 = psi2[n2]['j']\n if j2 > j1:\n assert psi2[n2]['xi'] < psi1[n1]['xi']\n # convolution + downsampling\n k2 = max(j2 - k1 - oversampling, 0)\n U2_hat = subsample_fourier(U1_hat * psi2[n2][k1],\n 2**k2)\n # take the modulus and go back in Fourier\n U2 = modulus_complex(ifft1d_c2c(U2_hat))\n if average:\n U2_hat = fft1d_c2c(U2)\n # Convolve with phi_J\n k2_J = max(J - k2 - k1 - oversampling, 0)\n S2_J_hat = subsample_fourier(U2_hat * phi[k1 + k2],\n 2**k2_J)\n S2_J = unpad(real(ifft1d_c2c(S2_J_hat)),\n ind_start[k1 + k2 + k2_J],\n ind_end[k1 + k2 + k2_J])\n else:\n # just take the real value and unpad\n S2_J = unpad(real(U2), ind_start[k1 + k2], ind_end[k1 + k2])\n if vectorize:\n S[:, cc, :] = S2_J.squeeze(dim=1)\n cc += 1\n else:\n S[n1, n2] = S2_J\n return S\n","sub_path":"kymatio/scattering1d/scattering1d.py","file_name":"scattering1d.py","file_ext":"py","file_size_in_byte":29316,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"618024885","text":"import tkinter\nimport socket\nimport threading\nwin = tkinter.Tk()\nwin.title(\"客户端\")\nwin.geometry(\"400x400+200+20\")\nck = None\n\n\ndef get_info():\n while True:\n data = ck.recv(1024).decode(\"utf-8\") + \"\\n\"\n text.insert(tkinter.INSERT, data)\n\n\ndef connect_server():\n global ck\n ip_str = eip.get()\n port_str = eport.get()\n user_str = euser.get()\n client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n client.connect((ip_str, int(port_str)))\n client.send(user_str.encode(\"utf-8\"))\n ck = client\n # 等待接收数据\n t = threading.Thread(target=get_info)\n t.start()\n\n\ndef send_mail():\n send_str = esend.get()\n friend = efriend.get()\n send_str = friend + \":\" + send_str\n ck.send(send_str.encode(\"utf-8\"))\n\n\nlabel_user = tkinter.Label(win, text=\"user\").grid(row=0, column=0)\neuser = tkinter.Variable()\nentry_user = tkinter.Entry(win, textvariable=euser).grid(row=0, column=1)\nlabel_ip = tkinter.Label(win, text=\"ip\").grid(row=1, column=0)\neip = tkinter.Variable()\nentry_ip = tkinter.Entry(win, textvariable=eip).grid(row=1, column=1)\nlabel_port = tkinter.Label(win, text=\"port\").grid(row=2, column=0)\neport = tkinter.Variable()\nentry_port = tkinter.Entry(win, textvariable=eport).grid(row=2, column=1)\nbutton = tkinter.Button(win, text=\"连接\", command=connect_server).grid(row=3, column=0)\ntext = tkinter.Text(win, width=30, height=5)\ntext.grid(row=4, column=0)\n\nesend = tkinter.Variable()\nentry_send = tkinter.Entry(win, textvariable=esend).grid(row=5, column=0)\n\nefriend = tkinter.Variable()\nentry_friend = tkinter.Entry(win, textvariable=efriend).grid(row=6, column=0)\nbutton2 = tkinter.Button(win, text=\"发送\", command=send_mail).grid(row=6, column=1)\n\nwin.mainloop()\n","sub_path":"19.3 模拟QQ/client1.py","file_name":"client1.py","file_ext":"py","file_size_in_byte":1738,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"159614680","text":"from pssh.clients.native.parallel import ParallelSSHClient\nfrom flask import jsonify, current_app\nfrom subprocess import check_output, STDOUT\n\n\ndef console(command):\n\tif current_app.config['CONSOLE_TYPE'] is 'SSH':\n\t\treturn ssh(command)\n\n\treturn terminal(command)\n\n\ndef ssh(command):\n\thostname = 'localhost'\n\tclient = ParallelSSHClient([hostname], user = current_app.config['USER'], password = current_app.config['PASSWORD'])\n\n\toutput = client.run_command(command = command, stop_on_errors = True)\n\tclient.join(output)\n\toutput = output[hostname]\n\n\toutput.stdout = ''.join(output.stdout)\n\toutput.stderr = ''.join(output.stderr)\n\n\tif output.exit_code is not 0:\n\t\traise CalledProcessError(cmd = command, returncode = output.exit_code, output = output.stderr)\n\n\treturn output.stdout\n\n\ndef terminal(command):\n\treturn check_output(command, shell = True, stderr = STDOUT, executable = '/bin/bash', universal_newlines = True)\n\n\ndef exception_json(error):\n\tcmd = ''\n\treturncode = 1\n\toutput = 'Error'\n\n\tif error is CalledProcessError:\n\t\tcmd = error.cmd\n\t\treturncode = error.returncode\n\t\toutput = error.output\n\telse:\n\t\toutput = error.message\n\n\treturn jsonify(cmd = cmd, returncode = returncode, output = output)\n","sub_path":"src/console.py","file_name":"console.py","file_ext":"py","file_size_in_byte":1201,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"329688476","text":"from os import stat\nimport re\n\nfrom edtime import EDTime\nimport edrconfig\n\nclass EDSuitLoadout(object):\n def __init__(self):\n self.id = None\n self.name = None\n self.suit_mods = []\n self.modules = []\n\n def update_from_suitloadout(self, event):\n self.id = event.get(\"LoadoutID\", None)\n self.name = event.get(\"LoadoutName\", None)\n self.suit_mods = event.get(\"SuitMods\", [])\n self.modules = event.get(\"Modules\", [])\n\n\nclass EDSpaceSuit(object): \n def __init__(self):\n self.type = None\n self.id = None\n self.grade = 1\n self.loadout = EDSuitLoadout()\n now = EDTime.py_epoch_now()\n self.timestamp = now\n self._health = {u\"value\": 1.0, u\"timestamp\": now}\n self._oxygen = {u\"value\": 1.0, u\"timestamp\": now}\n self._low_oxygen = {u\"value\": False, u\"timestamp\": now}\n self._low_health = {u\"value\": False, u\"timestamp\": now}\n self.shield_up = True\n self.fight = {u\"value\": False, \"large\": False, u\"timestamp\": now}\n self._attacked = {u\"value\": False, u\"timestamp\": now}\n self._in_danger = {u\"value\": False, u\"timestamp\": now}\n config = edrconfig.EDR_CONFIG\n self.fight_staleness_threshold = config.instance_fight_staleness_threshold()\n self.danger_staleness_threshold = config.instance_danger_staleness_threshold()\n\n @property\n def health(self):\n return self._health[\"value\"]\n\n @health.setter\n def health(self, new_value):\n now = EDTime.py_epoch_now()\n self.timestamp = now\n self._health = {u\"value\": new_value, u\"timestamp\": now}\n\n @property\n def oxygen(self):\n return self._oxygen[\"value\"]\n\n @oxygen.setter\n def oxygen(self, new_value):\n now = EDTime.py_epoch_now()\n self.timestamp = now\n self._oxygen = {u\"value\": new_value, u\"timestamp\": now}\n\n @property\n def low_health(self):\n return self._low_oxygen[\"value\"]\n\n @low_health.setter\n def low_health(self, low):\n now = EDTime.py_epoch_now()\n self.timestamp = now\n self._low_health = {\"timestamp\": now, \"value\": low}\n\n @property\n def low_oxygen(self):\n return self._low_oxygen[\"value\"]\n\n @low_oxygen.setter\n def low_oxygen(self, low):\n now = EDTime.py_epoch_now()\n self.timestamp = now\n self._low_oxygen = {\"timestamp\": now, \"value\": low}\n\n def json(self):\n result = {\n u\"timestamp\": int(self.timestamp * 1000),\n u\"type\": self.type,\n u\"health\": self.__js_t_v(self._health),\n u\"oxygen\": self.__js_t_v(self._oxygen),\n u\"shieldUp\": self.shield_up,\n u\"lowHealth\":self.__js_t_v(self._low_health),\n u\"lowOxygen\":self.__js_t_v(self._low_oxygen),\n }\n \n return result\n\n def __js_t_v(self, t_v):\n result = t_v.copy()\n result[\"timestamp\"] = int(t_v[\"timestamp\"]*1000)\n return result\n\n def __repr__(self):\n return str(self.__dict__)\n\n def reset(self):\n now = EDTime.py_epoch_now()\n self.timestamp = now\n self.health = 100.0\n self.oxygen = 100.0\n self.shield_up = True\n self.fight = {u\"value\": False, u\"large\": False, u\"timestamp\": now}\n # self._hardpoints_deployed = {u\"value\": False, u\"timestamp\": now} ? SelectedWeapon?\n self._attacked = {u\"value\": False, u\"timestamp\": now}\n self.heat_damaged = {u\"value\": False, u\"timestamp\": now}\n self._in_danger = {u\"value\": False, u\"timestamp\": now}\n \n def destroy(self):\n now = EDTime.py_epoch_now()\n self.timestamp = now\n self.health = 0.0\n\n def attacked(self):\n now = EDTime.py_epoch_now()\n self.timestamp = now\n self._attacked = {u\"value\": True, u\"timestamp\": now}\n\n def under_attack(self):\n if self._attacked[\"value\"]:\n now = EDTime.py_epoch_now()\n return (now >= self._attacked[\"timestamp\"]) and ((now - self._attacked[\"timestamp\"]) <= self.danger_staleness_threshold)\n return False\n\n def safe(self):\n now = EDTime.py_epoch_now()\n self._attacked = {u\"value\": False, u\"timestamp\": now}\n self.fight = {u\"value\": False, \"large\": False, u\"timestamp\": now}\n self._in_danger = {u\"value\": False, u\"timestamp\": now}\n \n def unsafe(self):\n now = EDTime.py_epoch_now()\n self._in_danger = {u\"value\": True, u\"timestamp\": now}\n\n def in_danger(self):\n if self._in_danger[\"value\"]:\n now = EDTime.py_epoch_now()\n return (now >= self._in_danger[\"timestamp\"]) and ((now - self._in_danger[\"timestamp\"]) <= self.danger_staleness_threshold)\n return False\n\n def shield_state(self, is_up):\n if not is_up:\n self.shield_health = 0.0\n self.shield_up = is_up\n\n def skirmish(self):\n now = EDTime.py_epoch_now()\n self.fight = {u\"value\": True, \"large\": False, u\"timestamp\": now}\n\n def battle(self):\n now = EDTime.py_epoch_now()\n self.fight = {u\"value\": True, \"large\": True, u\"timestamp\": now}\n\n def in_a_fight(self):\n if self.fight[\"value\"]:\n now = EDTime.py_epoch_now()\n return (now >= self.fight[\"timestamp\"]) and ((now - self.fight[\"timestamp\"]) <= self.fight_staleness_threshold)\n return False\n\n def update_from_suitloadout(self, event):\n other_id = event.get(\"SuitID\", None)\n other_type = EDSuitFactory.canonicalize(event.get(\"SuitName\", \"unknown\")) \n\n if other_id != self.id or other_type != self.type:\n EDRLOG.log(u\"Mismatch between Suit ID ({} vs {}) and/or Type ({} vs. {}), can't update from loadout\".format(self.id, other_id, self.type, other_type), \"WARNING\")\n return\n \n self.loadout.update_from_suitloadout(event)\n\n\n def __eq__(self, other):\n if not isinstance(other, EDSpaceSuit):\n return False\n return self.__dict__ == other.__dict__\n \n def __ne__(self, other):\n return not self.__eq__(other)\n\n\nclass EDUnknownSuit(EDSpaceSuit):\n def __init__(self):\n super(EDUnknownSuit, self).__init__()\n self.type = u'Unknown'\n\nclass EDFlightSuit(EDSpaceSuit):\n def __init__(self):\n super(EDFlightSuit, self).__init__()\n self.type = u'Flight'\n\nclass EDMaverickSuit(EDSpaceSuit):\n def __init__(self):\n super(EDMaverickSuit, self).__init__()\n self.type = u'Maverick'\n\nclass EDArtemisSuit(EDSpaceSuit):\n def __init__(self):\n super(EDArtemisSuit, self).__init__()\n self.type = u'Artemis'\n\nclass EDDominatorSuit(EDSpaceSuit):\n def __init__(self):\n super(EDDominatorSuit, self).__init__()\n self.type = u'Dominator'\n\n\nclass EDSuitFactory(object):\n __suit_classes = {\n \"flightsuit\": EDFlightSuit,\n \"utilitysuit\": EDMaverickSuit,\n \"explorersuit\": EDArtemisSuit,\n \"assaultsuit\": EDDominatorSuit,\n \"unknown\": EDUnknownSuit\n }\n\n @staticmethod\n def is_spacesuit(name):\n return EDSuitFactory.is_player_spacesuit(name) or EDSuitFactory.is_ai_spacesuit(name) \n\n @staticmethod\n def is_player_spacesuit(name):\n cname = name.lower()\n player_space_suit_regexp = r\"^(?:flightsuit|(?:exploration|utility|tactical)suit_class[1-5])$\" # TODO confirm that those are the internal names used for players\n return re.match(player_space_suit_regexp, cname)\n\n @staticmethod\n def is_ai_spacesuit(name):\n cname = name.lower()\n # ai_space_suit_regexp = r\"^(?:assault|lightassault|close|ranged)aisuit_class[1-5])$\" # TODO use this to tighten up things?\n ai_space_suit_lax_regexp = r\"^[a-z0-9_]*aisuit_class[1-5]$\"\n return re.match(ai_space_suit_lax_regexp, cname)\n\n @staticmethod\n def canonicalize(name):\n if name is None:\n return u\"unknown\" # Note: this shouldn't be translated\n cname = name.lower()\n player_space_suit_regexp = r\"^(flightsuit|(explorationsuit|utilitysuit|tacticalsuit)_class[1-5])$\" # TODO confirm that those are the internal names used for players\n m = re.match(player_space_suit_regexp, cname)\n if m:\n cname = m.group(1)\n return cname\n\n @staticmethod\n def grade(name):\n cname = name.lower()\n player_space_suit_regexp = r\"^[a-z0-9_]suit_class([1-5])$\" # TODO confirm that those are the internal names used for players\n m = re.match(player_space_suit_regexp, cname)\n if m:\n return m.group(1)\n return 1\n\n # TODO @staticmethod\n # def from_edmc_state(state):\n\n @staticmethod\n def from_internal_name(internal_name):\n suit_name = EDSuitFactory.canonicalize(internal_name)\n grade = EDSuitFactory.grade(internal_name)\n suit = EDSuitFactory.__suit_classes.get(suit_name, EDUnknownSuit)()\n suit.grade = grade\n return suit\n \n @staticmethod\n def from_load_game_event(event):\n suit = EDSuitFactory.from_internal_name(event.get(\"Ship\", 'unknown'))\n suit.id = event.get('ShipID', None)\n suit.identity = event.get('ShipIdent', None) # Always empty?\n suit.name = event.get('ShipName', None) # Always empty\n # TODO the event also has Fuel and Fuelcapacity but it's unclear if this is a bug or reusing fields for Energy levels?\n return suit\n\n @staticmethod\n def from_suitloadout_event(event):\n suit = EDSuitFactory.from_internal_name(event.get(\"SuitName\", 'unknown'))\n suit.id = event.get('SuitID', None)\n suit.loadout.update_from_suitloadout(event)\n return suit\n\n #@staticmethod\n #def from_stored_ship(ship_info): # TODO suitloadout swapping?\n \n @staticmethod\n def unknown_suit():\n return EDUnknownSuit()","sub_path":"edr/edspacesuits.py","file_name":"edspacesuits.py","file_ext":"py","file_size_in_byte":9845,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"60809806","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-+\n\nimport math\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport matplotlib.patches as patches\nimport pickle\n\ndef Read_Data(path):\n with open(path,'rb') as f:\n data = pickle.load(f)\n return data\n \n\ndef main():\n robots = Read_Data(\"./log_robot_show.pickle\")\n paths = Read_Data(\"log_path_show.pickle\")\n obstalces = Read_Data(\"log_obstacle_show.pickle\")\n choise_episode = 1\n path = paths[choise_episode]\n obstalce = obstalces[choise_episode]\n\n \"\"\" add plot object \"\"\"\n ax = plt.gca()\n\n \"\"\" path \"\"\"\n x = []\n y = []\n for pos in path:\n x.append(pos[0])\n y.append(pos[1])\n plt.plot(x,y,color='red')\n\n \"\"\" obstacle \"\"\"\n x = []\n y = []\n for pos in obstalce:\n x.append(pos[0])\n y.append(pos[1])\n print(x,y)\n \n for i in range(len(x)):\n obstacle = patches.Rectangle((x[i],y[i]), 0.4, 0.4, color='black')\n ax.add_patch(obstacle)\n\n \"\"\" goal \"\"\"\n # left buttom point\n y_goal = patches.Rectangle((-3,-0.75), 0.4, 1.5, color='yellow')\n b_goal = patches.Rectangle((2.6,-0.75), 0.4, 1.5, color='blue')\n ax.add_patch(y_goal)\n ax.add_patch(b_goal)\n\n plt.ylim(-2.5, 2.5)\n plt.xlim(-3.5,3.5)\n plt.show()\n # plt.savefig('./robot_path1.png')\n\n\nif __name__ == '__main__':\n main()","sub_path":"src/nubot_strategy/avoid_figure/lib/tool/plot_robot.py","file_name":"plot_robot.py","file_ext":"py","file_size_in_byte":1367,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"493237372","text":"#!/usr/bin/env python\n#testfile = open('unicode.txt')\n#for line in testfile:\n# #if line.startswith('#'):\n# if '#' in line:\n# continue\n# else:\n# print line,\n#lineN = raw_input('Please input lines num')\n#filename = raw_input('Please input lines filename : ')\n#testfile = open(filename)\n#lines = 25\n#while True:\n# if lines > 0:\n# print(testfile.readline())\n# lines = lines - 1\n# if lines == 0:\n# endpoint = raw_input('Entern any key continue : ')\n# if endpoint == 'e':\n# testfile.close()\n# break;\n# else:\n# lines = 25\n\nwith open('data.txt','w') as f:\n for i in range(100):\n f.write(str(i))\n f.write('\\n')\nwith open('data.txt') as f:\n num = 1\n for eachline in f:\n if num % 26 != 0:\n print(eachline)\n num += 1\n else:\n endpoint = raw_input('continue until c happen : ')\n num += 1\n if endpoint == 'c':\n break\n\n\n\n\n","sub_path":"Python/moveit/corepython/practise/practise.py","file_name":"practise.py","file_ext":"py","file_size_in_byte":1040,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"278340481","text":"# https://www.geeksforgeeks.org/merging-intervals/\n# https://leetcode.com/problems/merge-intervals/description/\n\ndef mergeOverlappingIntervals(intervals):\n out = []\n for i in sorted(intervals, key=lambda i: i[0]):\n if out and i[0]<=out[-1][-1]:\n out[-1][-1] = max(out[-1][-1], i[-1])\n else: out+=[i]\n return out","sub_path":"mergeOverlappingIntervals.py","file_name":"mergeOverlappingIntervals.py","file_ext":"py","file_size_in_byte":345,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"599035974","text":"import numbers\nfrom pathlib import Path\n\nimport numpy as np\nimport random\n\nimport torch\nfrom torchvision import transforms as T\nfrom torchvision.transforms import functional as F\nfrom PIL import Image\n\n\"\"\"\n这个博客详细记载了torchvision.transforms.functional常用的数据增强\nhttps://www.cnblogs.com/ghgxj/p/14219097.html\n\n温馨提示:\n 1.在模型训练过程中,每个epoch做数据增强,可以增加样本数量。\n 因为,每一个epoch虽然训练的样本数量不变,但是每一个epoch因为transform不同而产生不一样的训练样本,相当于增加了样本数量。\n 2.每一个batch的样本使用的是相同的数据增强方式。\n 因为loader会将N个样本打包成一个batch,送进模型。因此,这一批数据的数据增强方式是一样。\n 不同批次的数据因为transfrom不同,其变化不同。\n\"\"\"\n\n\ndef pad_if_smaller(img, size, fill=0):\n # 如果图像最小边长小于给定size,则用数值fill进行padding\n min_size = min(img.size)\n ow, oh = img.size\n\n if isinstance(size, int):\n if min_size < size:\n padh = size - oh if oh < size else 0\n padw = size - ow if ow < size else 0\n img = F.pad(img, padding=[0, 0, int(padw), int(padh)], fill=fill)\n\n elif len(size) == 2:\n h, w = size\n padh = h - oh if oh < h else 0\n padw = w - ow if ow < w else 0\n img = F.pad(img, padding=[0, 0, int(padw), int(padh)], fill=fill)\n return img\n\n\n# 随机缩放\n# class RandomResize(object):\n# def __init__(self, min_size, max_size=None):\n# self.min_size = min_size\n# if max_size is None:\n# max_size = min_size\n# self.max_size = max_size\n#\n# def __call__(self, image, target):\n# size = random.randint(self.min_size, self.max_size)\n# # 这里size传入的是int类型,所以是将图像的最小边长缩放到size大小\n# image = F.resize(image, size)\n# # 这里的interpolation注意下,在torchvision(0.9.0)以后才有InterpolationMode.NEAREST\n# # 如果是之前的版本需要使用PIL.Image.NEAREST\n# # target = F.resize(target, size, interpolation=T.InterpolationMode.NEAREST)\n# target = F.resize(target, size, interpolation=Image.NEAREST)\n# return image, target\n\n# 随机缩放\nclass RandomResize(object):\n def __init__(self, size, ratio=(0.5, 2.0)):\n self.size = size\n self.ratio = ratio\n\n def __call__(self, image, target):\n r = random.uniform(self.ratio[0], self.ratio[1])\n # size = int(self.size * r)\n size = int(self.size * r) if isinstance(self.size, int) else tuple(int(s * r) for s in self.size)\n image = F.resize(image, size)\n # 这里的interpolation注意下,在torchvision(0.9.0)以后才有InterpolationMode.NEAREST\n # 如果是之前的版本需要使用PIL.Image.NEAREST\n # target = F.resize(target, size, interpolation=T.InterpolationMode.NEAREST)\n target = F.resize(target, size, interpolation=Image.NEAREST)\n return image, target\n\n\n# 随机翻转\nclass RandomHorizontalFlip(object):\n def __init__(self, flip_prob):\n self.flip_prob = flip_prob\n\n def __call__(self, image, target):\n if random.random() < self.flip_prob:\n image = F.hflip(image)\n target = F.hflip(target)\n return image, target\n\n\n# 随机裁剪\nclass RandomCrop(object):\n def __init__(self, size):\n if isinstance(size, int):\n size = (size, size)\n elif isinstance(size, list):\n size = tuple(size)\n self.size = size\n\n def __call__(self, image, target):\n image = pad_if_smaller(image, self.size)\n target = pad_if_smaller(target, self.size, fill=255)\n crop_params = T.RandomCrop.get_params(image, (self.size[0], self.size[1]))\n image = F.crop(image, *crop_params)\n target = F.crop(target, *crop_params)\n return image, target\n\n\n# 中心裁剪\nclass CenterCrop(object):\n def __init__(self, size):\n self.size = size\n\n def __call__(self, image, target):\n image = F.center_crop(image, self.size)\n target = F.center_crop(target, self.size)\n return image, target\n\n\n# 随机旋转\nclass RandomRotation(object):\n def __init__(self, rotation_prob, angle=15):\n self.rotation = rotation_prob\n self.angle = angle\n\n def __call__(self, image, target):\n if random.random() < self.rotation:\n angle = random.randint(-self.angle, self.angle)\n image = F.rotate(image, angle, expand=True, fill=0)\n target = F.rotate(target, angle, expand=True, fill=255)\n assert image.size == target.size\n return image, target\n\n\n# 高斯模糊\nclass GaussianBlur(object):\n # 模糊半径越大, 正态分布标准差越大, 图像就越模糊\n \"\"\"\n kernel_size:模糊半径。必须是奇数。\n sigma:正态分布的标准差。如果是浮点型,则固定;如果是二元组(min, max),sigma在区间中随机选取一个值。\n \"\"\"\n\n def __init__(self, kernel_size=11, sigma=2):\n self.kernel_size = kernel_size\n self.sigma = sigma\n\n def __call__(self, image, target):\n aug = T.GaussianBlur(self.kernel_size, self.sigma)\n return aug(image), target\n\n\n# 颜色扰动\nclass ColorJitter(object):\n # 随机改变图片的亮度,对比度和饱和度。\n \"\"\"\n brightness:亮度;允许输入浮点型或二元组(min, max)。如果是浮点型,那么亮度在[max(0, 1 ## brightness), 1 + brightness]区间随机变换;如果是元组,亮度在给定的元组间随机变换。不允许输入负值。\n contrast:对比度。允许输入规则和亮度一致。\n saturation:饱和度。允许输入规则和亮度一致。\n hue:色调。允许输入浮点型或二元组(min, max)。如果是浮点型,那么亮度在[-hue, hue]区间随机变换;如果是元组,亮度在给定的元组间随机变换。不允许输入负值。必须满足0<= hue <= 0.5 or -0.5 <= min <= max <= 0.5。\n\n \"\"\"\n\n def __init__(self, p=(0.5, 1.5)):\n self.p = p\n\n def __call__(self, image, target):\n index = random.randint(0, 4)\n if index == 0:\n aug = T.ColorJitter(brightness=self.p)\n elif index == 1:\n aug = T.ColorJitter(contrast=self.p)\n elif index == 2:\n aug = T.ColorJitter(saturation=self.p)\n else:\n aug = T.ColorJitter(brightness=self.p, contrast=self.p, saturation=self.p)\n return aug(image), target\n\n\nclass ToTensor(object):\n def __call__(self, image, target):\n image = F.to_tensor(image)\n target = torch.as_tensor(np.array(target), dtype=torch.int64)\n return image, target\n\n\nclass Normalize(object):\n def __init__(self, mean, std):\n self.mean = mean\n self.std = std\n\n def __call__(self, image, target):\n image = F.normalize(image, mean=self.mean, std=self.std)\n return image, target\n\n\nclass Compose(object):\n def __init__(self, transforms):\n self.transforms = transforms\n\n def __call__(self, image, target):\n for t in self.transforms:\n image, target = t(image, target)\n return image, target\n\n\nclass SegmentationPresetTrain:\n def __init__(self, base_size, crop_size, ratio=(0.5, 2.0), hflip_prob=0.5, mean=(0.485, 0.456, 0.406),\n std=(0.229, 0.224, 0.225)):\n trans = [\n RandomResize(base_size, ratio),\n #ColorJitter(),\n #RandomRotation(rotation_prob=0.5),\n #GaussianBlur(),\n ]\n if hflip_prob > 0:\n trans.append(RandomHorizontalFlip(hflip_prob))\n trans.extend([\n RandomCrop(crop_size),\n ToTensor(),\n Normalize(mean=mean, std=std),\n ])\n self.transforms = Compose(trans)\n\n def __call__(self, img, target):\n return self.transforms(img, target)\n\n\nclass SegmentationPresetEval:\n def __init__(self, base_size, mean=(0.485, 0.456, 0.406), std=(0.229, 0.224, 0.225)):\n self.transforms = Compose([\n RandomResize(base_size, ratio=(1., 1.)),\n ToTensor(),\n Normalize(mean=mean, std=std),\n ])\n\n def __call__(self, img, target):\n return self.transforms(img, target)\n\n\ndef build_transform(cfg=\"config/example.yaml\", train=True):\n if isinstance(cfg, dict):\n config = cfg\n else:\n import yaml\n yaml_file = Path(cfg).name\n with open(cfg) as f:\n config = yaml.safe_load(f)\n\n base_size = config[\"train\"][\"base_size\"]\n crop_size = config[\"train\"][\"crop_size\"]\n mean = tuple(config[\"train\"][\"mean\"])\n std = tuple(config[\"train\"][\"std\"])\n ratio = config[\"train\"][\"ratio\"]\n\n return SegmentationPresetTrain(base_size, crop_size, ratio=ratio, mean=mean,\n std=std) if train else SegmentationPresetEval(\n base_size, mean=mean, std=std)\n\n\n# if __name__ == '__main__':\n# mean = (0.485, 0.456, 0.406)\n# std = (0.229, 0.224, 0.225)\n# trans = [\n# RandomRotation(1.0),\n# RandomResize(size=200, ratio=(0.5, 2.0)),\n# RandomHorizontalFlip(1.0),\n# RandomCrop((224, 500)),\n# # GaussianBlur(11,2),\n# # ColorJitter(),\n# # ToTensor(),\n# # Normalize(mean=mean, std=std),\n# ]\n#\n# transforms = Compose(trans)\n#\n# from PIL import Image\n#\n# img = Image.open(r'E:\\pic\\3.jpg')\n# for i in range(10):\n# a, b = transforms(img, img)\n# print(a.size)\n# import matplotlib.pyplot as plt\n#\n# fig, ax = plt.subplots(1, 2)\n# ax[0].set_title('image')\n# ax[0].imshow(a)\n# ax[1].set_title(f'mask')\n# ax[1].imshow(b)\n# plt.xticks([]), plt.yticks([])\n# plt.show()\n","sub_path":"Image_segmentation/DeepLabV3/dataLoader/transforms.py","file_name":"transforms.py","file_ext":"py","file_size_in_byte":9934,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"550721685","text":"import cProfile\nimport numpy as np \n\nfrom time import sleep\nfrom line_profiler import LineProfiler \n\ndef bad_call(dude):\n sleep(.5)\n\ndef worse_call(dude):\n sleep(1)\n\ndef sumulate(foo):\n if not isinstance(foo, int):\n return\n\n a = np.random.random((1000, 1000))\n a @ a\n\n ans = 0\n for i in range(foo):\n ans += i\n\n bad_call(ans)\n worse_call(ans)\n\n return ans\n\nif __name__ == \"__main__\":\n print(sumulate(150))\n cProfile.run('sumulate(150)')\n lp = LineProfiler()\n lp.add_function(bad_call)\n lp.add_function(worse_call)\n lp_wrapper = lp(sumulate)\n lp_wrapper(150)\n print(lp.print_stats())\n","sub_path":"AdvancePython/numba_tutorial/01_when_to_use_numba.py","file_name":"01_when_to_use_numba.py","file_ext":"py","file_size_in_byte":650,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"474035329","text":"import os\nimport sys\n\n\n\ncurrentDir = os.path.dirname(sys.argv[0])\ndir = os.path.join(currentDir, '..', 'Assets')\ndir = os.path.abspath(dir)\n\nassets = os.walk(dir)\n\nitems = []\nfor root, subFolders, files in assets:\n for file in files:\n path = root.replace(dir + '\\\\', '').replace('\\\\', '\\\\\\\\')\n \n item = \"('..\\\\\\\\Assets\\\\\\\\{0}\\\\\\\\{1}', 'Assets\\\\\\\\{0}')\".format(path, file)\n extension = os.path.splitext(file)[1]\n if extension in ['.png', '.json', '.ttf', '.otf', '.wav', '.mp3']:\n items.append(item)\n else:\n print('Not included: {0}'.format(file))\n\nresult = \",\\n\".join(items)\n\nsourcefile = os.path.join(currentDir, \"Game.spec.pattern\")\ndestFile = os.path.join(currentDir, \"Game.spec\")\n\nwith open(sourcefile) as f:\n newText=f.read().replace('{{FILES}}', result)\n\nwith open(destFile, \"w\") as f:\n f.write(newText)\n\n\nprint(\"Spec-Datei erzeugt!\")\n\n\n\n","sub_path":"SimpleGame/SimpleGame/Deployment/makeSpec.py","file_name":"makeSpec.py","file_ext":"py","file_size_in_byte":917,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"147699153","text":"'''\nThis is the program with its user interface. It is a separate module (not main) because,\nin origin, it was supposed to be part of something bigger.\n'''\nfrom threading import Thread\nimport PIL # @UnusedImport\nimport PIL.ImageTk\nimport tkinter as tk\nimport tkinter.font as tkFont\nimport tkinter.filedialog as tkFiledialog\nimport tkinter.simpledialog as dialog\nimport os\nimport sys\nimport platform\nimport time\nfrom q_utils import sqlite_creator as sq\nfrom q_connect import gglmap\nfrom q_connect import connections as conn\nfrom q_connect import uploads\nimport q_utils.datestimes as q_dates\nfrom q_utils.html_fixer import remove_html as html_fix # @UnusedImport\nimport webbrowser\nfrom q_utils import image_resizer\nimport q_connect.mail_stuff as mail_stuff # @UnusedImport\n#from q_utils import machine_learn\nfrom q_utils import querymaker\nfrom q_connect import protected\n\nif __name__ == \"__main__\":\n\tbigVis = {x:x for x in sq.visind_vals}\n\tsmallVis = {x:x for x in sq.vissec_vals}\nelse:\n\tbigVis = {sq.visind_vals[x]:x for x in range(len(sq.visind_vals))}\n\tsmallVis = {sq.vissec_vals[x]:x for x in range(len(sq.vissec_vals))}\n\t\nclass Q_gui(tk.Frame):\n\tdef __init__(self, master=None):\n\t\tarial = tkFont.Font(family=\"Arial\", size=12)\n\t\tmaster.title(\"Quattropassi Nagamaki\")\n\t\tmaster.state(\"zoomed\")\n\t\tmaster.wm_geometry(\"%dx%d+%d+%d\" % (master.winfo_screenwidth(), master.winfo_screenheight(), 0, 0))\n\t\ttry:\n\t\t\tmaster.option_add(\"*Font\", arial)\n\t\texcept:\n\t\t\tpass\n\t\tif platform.system() == \"Windows\":\n\t\t\tico = \"icon.ico\"\n\t\t\tmaster.tk.call('wm', 'iconbitmap', master._w, '-default', ico)\n\t\telse:\n\t\t\tico = \"icon.icns\"\n\t\t\tmaster.tk.call('wm', 'iconbitmap', master._w, ico)\n\t\ttk.Frame.__init__(self, master)\n\t\tself.pack(fill=tk.BOTH)\n\t\t#===\n\t\tth = Thread(target=self.prepare)\n\t\tth.start()\n\t\tself.splash()\n\t\t\"\"\"actions = [self.prepare, self.splash]\n\t\tmythread = []\n\t\tfor action in actions:\n\t\t\tth = Thread(target=action)\n\t\t\tth.start()\n\t\t\tmythread.append(th)\n\t\tfor b in mythread:\n\t\t\tb.join()\"\"\"\n\t\tself.createButtons()\n\t\tmaster.config(menu=self.menubar)\n\t\n\tdef temp_method(self, v, r=\"test\"):\n\t\t\"\"\"\n\t\tIgnore this, but I don't have the heart to delete it! :)\n\t\t\"\"\"\n\t\tprint(v)\n\t\tif r != \"test\":\n\t\t\tprint(r)\n\t\n\tdef ask4date(self):\n\t\t\"\"\"\n\t\tPops up three dialogs that ask for the date; the first is the day,\n\t\tthen the month, then the year. It then updates that date box of the\n\t\tvisit and formats it in italian.\n\t\t\"\"\"\n\t\tvallist = [0, 0, 0]\n\t\tself.date_entry.delete(0, tk.END)\n\t\tfor x in range(vallist.__len__()):\n\t\t\tif x == 0:\n\t\t\t\tkey = \"Giorno\"\n\t\t\telif x == 1:\n\t\t\t\tkey = \"Mese\"\n\t\t\telse:\n\t\t\t\tkey= \"Anno\"\n\t\t\tvallist[x] = dialog.askinteger(key, key)\n\t\tif vallist[2] < 100:\n\t\t\tvallist[2] += 2000\n\t\tvallist[2] = str(vallist[2])\n\t\tif vallist[1] < 10:\n\t\t\tvallist[1] = \"0\" + str(vallist[1])\n\t\telse:\n\t\t\tvallist[1] = str(vallist[1])\n\t\tif vallist[0] < 10:\n\t\t\tvallist[0] = \"0\" + str(vallist[0])\n\t\telse:\n\t\t\tvallist[0] = str(vallist[0])\t\n\t\td = q_dates.datetostring(vallist[2]+\"-\"+vallist[1]+\"-\"+vallist[0], \"IT\")\n\t\tself.date_entry.insert(0, d)\n\t\t\n\tdef calendar_make(self, cal=True, lang=\"it\"):\n\t\t\"\"\"\n\t\tCreate the full list of visits (individual, cenacolo and secondary) to choose from\n\t\tand then makes the calendar from the ones selected.\n\t\tIf the parameter cal is set to True then this will be treated as the PDF creator,\n\t\totherwise it would be the Homepage creator.\n\t\t\"\"\"\n\t\ttry:\n\t\t\tself.mainframe.destroy()\n\t\texcept AttributeError:\n\t\t\tpass\t\t\n\t\tself.mainframe = tk.Frame(self)\n\t\tself.mainframe.pack(side=\"top\")\n\t\ttk.Label(self.mainframe, text=\"Seleziona le visite\").grid(row=0, column=0)\n\t\tself.mainlist = tk.Listbox(self.mainframe, width=120, height=30, selectmode=tk.MULTIPLE)\n\t\t#The scrollbar seems to create problems on the mac\n\t\tif platform.system() == \"Windows\":\n\t\t\tscrollbar = tk.Scrollbar(self.mainframe)\n\t\tself.mainlist.grid(row=1, column=0)\n\t\tif platform.system() == \"Windows\":\n\t\t\tself.mainlist.config(yscrollcommand=scrollbar.set)\n\t\t\tscrollbar.grid(row=1, column=0, sticky=tk.N+tk.S+tk.E+tk.W)\n\t\t\tscrollbar['command'] = self.mainlist.yview\n\t\tvis_ind = sq.select(\"IND\")\n\t\tvis_mod = sq.select(\"MOD\")\n\t\tvis_cen = sq.select(\"CEN\")\n\t\tnm_off = 10\n\t\tid_off = 8 # @UnusedVariable\n\t\tdate_off = 5\n\t\tdate_off_cen = 1 #TODO\n\t\tself.callist_ind = [tk.StringVar() for x in range(vis_ind.__len__())]\n\t\tfor x in range(vis_ind.__len__()):\n\t\t\tself.mainlist.insert(tk.END, vis_ind[x][nm_off] + \" \" + q_dates.datetostring(vis_ind[x][date_off], \"IT\"))\n\t\tfor x in range(vis_cen.__len__()):\n\t\t\tself.mainlist.insert(tk.END, \"Cenacolo \" + q_dates.datetostring(vis_cen[x][date_off_cen], \"IT\"))\n\t\tfor x in range(vis_mod.__len__()):\n\t\t\tself.mainlist.insert(tk.END, conn.getPrName(int(vis_mod[x][5]), lang) + \" \" + q_dates.datetostring(vis_mod[x][date_off_cen], \"IT\"))\n\t\tif cal:\n\t\t\tcmnd = self.calendar_link\n\t\t\tlab = \"Crea calendario\"\n\t\t\tself.clause = tk.StringVar()\n\t\t\tself.clause.initialize(\"1\")\n\t\t\ttk.Checkbutton(self.mainframe, text=\"Inserire 'Per partecipare alle nostre iniziative...'\", variable=self.clause, onvalue=\"1\", offvalue=\"0\").grid(row=3, column=0, padx=5, pady=5)\n\t\telse:\n\t\t\tcmnd = lambda l=lang:self.calendar_link(cal=False,lang=l)\n\t\t\tlab = \"Inserisci in homepage\"\n\t\ttk.Button(self.mainframe, text=lab, command= cmnd).grid(row=4, column=0, padx=5, pady=5)\n\t\t\n\tdef nice_address(self):\n\t\t\"\"\"\n\t\tIt pops up a dialog asking for an address, looks up that Milan address on Google\n\t\tand formats it nicely.\n\t\t\"\"\"\n\t\taddress = dialog.askstring(\"Indirizzo\", \"Indirizzo\")\n\t\toutput = gglmap.getCoordinates(address + \", Milan, Italy\")\n\t\t#print(output)\n\t\tif output[\"street\"]:\n\t\t\tself.meetingpoint_entry.delete(0, tk.END)\n\t\t\tself.meetingpoint_entry.insert(0, output[\"street\"])\n\t\n\tdef calendar_link(self, cal=True, lang=\"it\") -> None:\n\t\t\"\"\"\n\t\tGets the selected visits from the calendar selector and opens the calendar\n\t\ton the browser while PHP does its magic.\n\t\t\"\"\"\n\t\tif __name__ == \"__main__\":\n\t\t\tvis = conn.getAllVis()\n\t\t\tvis_ind = vis[\"IND\"]\n\t\t\tvis_mod = vis[\"MOD\"]\n\t\t\tvis_cen = vis[\"CEN\"]\n\t\t\tnm_off = \"nome\" # @UnusedVariable\n\t\t\tid_off = \"id\"\n\t\t\tdate_off = \"date\" # @UnusedVariable\n\t\telse:\n\t\t\tvis_ind = sq.select(\"IND\")\n\t\t\tvis_mod = sq.select(\"MOD\")\n\t\t\tvis_cen = sq.select(\"CEN\")\n\t\t\tnm_off = 10 # @UnusedVariable\n\t\t\tid_off = 8\n\t\t\tdate_off = 5 #TODO @UnusedVariable\n\t\t\tid_sec = 0\n\t\tquery_list = [\"IND\" + str(vis_ind[int(x)][id_off]) for x in self.mainlist.curselection() if int(x) in range(vis_ind.__len__())]\n\t\tquery_cen = [\"CEN\" + str(vis_cen[int(x) - vis_ind.__len__()][id_sec]) for x in self.mainlist.curselection() if int(x) in range(vis_ind.__len__(), vis_ind.__len__() + vis_cen.__len__())]\n\t\tquery_mod = [\"MOD\" + str(vis_mod[int(x) - (vis_ind.__len__() + vis_cen.__len__())][id_sec]) for x in self.mainlist.curselection() if int(x) in range(vis_ind.__len__() + vis_cen.__len__(), vis_ind.__len__() + vis_cen.__len__() + vis_mod.__len__())]\n\t\tquery = \"\".join(query_list) + \"\".join(query_cen) + \"\".join(query_mod)\n\t\tif cal:\n\t\t\tm = dialog.askstring(\"Calendario di\", \"Calendario di...\")\n\t\t\tclause = self.clause.get()\n\t\t\turl = \"http://www.quattropassimilano.it/atarashii/_php/py_calendar.php?month=\" + m + \"&visits=\" + query + \"&clause=\" + clause\n\t\t\twebbrowser.open(url)\n\t\telse:\n\t\t\ttry:\n\t\t\t\tself.mainframe.destroy()\n\t\t\texcept AttributeError:\n\t\t\t\tpass\n\t\t\tself.mainframe = tk.Frame(self)\n\t\t\tself.mainframe.pack(side=\"top\")\n\t\t\tconn.saveHome(query, lang)\n\t\t\t#tk.Label(self.mainframe, text=\"Controllare\").grid(row=0, column=0)\n\t\t\tif conn.saveHome(query, lang):\n\t\t\t\ttk.Label(self.mainframe, text=\"Visite inserite in homepage\").grid(row=0, column=0)\n\t\t\telse:\n\t\t\t\ttk.Label(self.mainframe, text=\"Visite NON inserite in homepage\").grid(row=0, column=0)\n\t\t\t\n\tdef makePageQ(self, name=\"\", title=\"\", keywords=\"\", description=\"\", content=\"\", lang=\"it\") -> bool:\n\t\t\"\"\"\n\t\tStub for a method that should have updated a given page.\n\t\t\"\"\"\n\t\tvals = {sq.pages_vals[1]: name}\n\t\tres = sq.select(sq.pages_name, sq.pages_vals[1], name)\n\t\tif res.__len__() > 0:\n\t\t\tpid = res[0][0]\n\t\telse:\n\t\t\tpid = 0\n\t\tvals[sq.pages_vals[0]] = pid\n\t\tif title:\n\t\t\tvals[sq.pages_vals[5]] = title\n\t\tif keywords:\n\t\t\tvals[sq.pages_vals[4]] = keywords\n\t\tif description:\n\t\t\tvals[sq.pages_vals[3]] = description\n\t\tif content:\n\t\t\tvals[sq.pages_vals[2]] = content\n\t\tquery = querymaker.querymaker(sq.pages_name, vals)\n\t\treturn protected.sendQuery(query, lang)\n\t\t\t\n\tdef add_subscribed(self):\n\t\t\"\"\"\n\t\tIt pops up a dialog asking the email address of the new subscribed to the\n\t\tnewsletter. I won't bother to check it's an email address.\n\t\t\"\"\"\n\t\tsubscribed = dialog.askstring(\"Aggiungi iscritto\", \"Indirizzo e-mail\")\n\t\tsq.insert(\"newsletter\", {\"email\":subscribed})\n\t\n\tdef showmails(self):\n\t\t\"\"\"\n\t\tShow the new emails recived.\n\t\t\"\"\"\n\t\ttry:\n\t\t\tself.mainframe.destroy()\n\t\texcept AttributeError:\n\t\t\tpass\n\t\tself.mainframe = tk.Frame(self)\n\t\tself.mainframe.pack(side=\"top\")\n\t\ttk.Label(self.mainframe, text=\"Email\").grid(row=0, column=0)\n\t\tself.mainlist = tk.Listbox(self.mainframe, width=120)\n\t\tscrollbar = tk.Scrollbar(self.mainframe)\n\t\tself.mainlist.grid(row=1, column=0)\n\t\tself.mainlist.config(yscrollcommand=scrollbar.set)\n\t\tscrollbar.grid(row=1, column=0, sticky=tk.N+tk.S+tk.E+tk.W)\n\t\tscrollbar['command'] = self.mainlist.yview\n\t\temails = sq.select(\"emails\")\n\t\t\n\t\tfor mail in emails:\n\t\t\tif mail[1] == 0:\n\t\t\t\tpass\t#TODO: Mail is new, do something\n\t\t\telse:\n\t\t\t\tcontinue\n\t\t\tself.mainlist.insert(tk.END, mail[6] + \", FROM: \" + mail[2])\n\t\ttk.Button(self.mainframe, text=\"Leggi\", command= self.openmail).grid(row=3, column=0, padx=5, pady=5)\n\t\t\n\tdef openmail(self):\n\t\t\"\"\"\n\t\tOpen the selected mail in a new window. This method is a stub.\n\t\t\"\"\"\n\t\tsel = int(self.mainlist.curselection()[0])\n\t\temails = sq.select(\"emails\", \"seen\", \"0\")\n\t\te = emails[sel]\n\t\twindow = tk.Toplevel(self)\n\t\ttk.Label(window, text=\"From: \" + e[2]).grid(row=0, column=0, pady=10, padx=10)\n\t\ttk.Label(window, text=\"To: \" + e[3]).grid(row=1, column=0, pady=10, padx=10)\n\t\ttk.Label(window, text=e[4]).grid(row=2, column=0, pady=10, padx=10)\n\t\ttk.Label(window, text=\"Subject: \" + e[6]).grid(row=3, column=0, pady=10, padx=10)\n\t\tt = tk.Text(window)\n\t\tt.insert(tk.END, e[5])\n\t\tt.grid(row=4, column=0, pady=10, padx=10)\n\t\t#test = (\"testformailaccess.ffp@gmail.com\", \"mailpassword\")\n\t\t#markasread = (lambda x=e[0]:mail_stuff.getMails(False, test[0], test[1], x))\n\t\t#tk.Button(window, text=\"Segna come letta\", command=markasread).grid(row=5, column=0, pady=10, padx=10)\n\n\tdef see_subscribed(self):\n\t\t\"\"\"\n\t\tSee who is subscribed to the newsletter.\n\t\t\"\"\"\n\t\ttry:\n\t\t\tself.mainframe.destroy()\n\t\texcept AttributeError:\n\t\t\tpass\n\t\tsubscribed = sq.select(sq.newsletter_name)\n\t\tself.mainframe = tk.Frame(self)\n\t\tself.mainframe.pack(side=\"top\")\n\t\tself.mainlist = tk.Listbox(self.mainframe)\n\t\tself.mainlist.grid(row=0, column=0)\n\t\tfor email in subscribed:\n\t\t\tself.mainlist.insert(tk.END, email)\n\t\t\t\n\tdef bigvis_maker(self, typeof=\"IND\", visid=0, lang=\"it\"):\n\t\t\"\"\"\n\t\tEither create or modify a big visit (school, groups or individual). It takes\n\t\ttwo arguments: typeof, which is set to \"IND\" by default, is the three character\n\t\tcode that identifies the type of visit that we have all come to love; visid, which\n\t\tis set to 0 by default, is the id of the visit. If it is 0 it means it's a new\n\t\tvisit.\n\t\t\"\"\"\n\t\tlang = lang.upper()\n\t\tif lang == \"IT\":\n\t\t\tlang = \"\"\n\t\ttry:\n\t\t\tself.mainframe.destroy()\n\t\texcept AttributeError:\n\t\t\tpass\n\t\tif visid:\n\t\t\tvalues = sq.select(typeof + lang, \"id\", visid)\n\t\t\tvalues = values[0]\n\t\telse:\n\t\t\tvalues = [\"\" for x in range(len(sq.visind_vals))]\n\t\tname = values[10]\n\t\tdate = values[5]\n\t\tif date:\n\t\t\ttry:\n\t\t\t\tdate = q_dates.datetostring(date, \"IT\")\n\t\t\texcept TypeError:\n\t\t\t\tpass\n\t\tore = values[6]\n\t\tadditup = values[2]\n\t\tdescription = values[13]\n\t\tdispon = values[1]\n\t\tvislen = values[4]\n\t\tprice = values[3]\n\t\tmeetingpoint = values[9]\n\t\tself.vid = visid\n\t\tself.visittype = typeof\n\t\tself.mainframe = tk.Frame(self)\n\t\ttk.Label(self.mainframe, text=\"Nome della visita\").grid(row=0, column=0)\n\t\tself.name_entry = tk.Entry(self.mainframe, width=80)\n\t\tself.name_entry.insert(0, name)\n\t\tself.name_entry.grid(row=0, column=1, columnspan=2)\n\t\tif typeof == \"IND\":\n\t\t\ttk.Label(self.mainframe, text=\"Data della visita\").grid(row=1, column=0, pady=10, padx=10)\n\t\t\tself.date_entry = tk.Entry(self.mainframe, width=67)\n\t\t\tself.date_entry.grid(row=1, column=1, pady=10, padx=0)\n\t\t\tself.date_entry.insert(0, date)\n\t\t\tself.date_button = tk.Button(self.mainframe, width=10, text=\"Scegli\", command=self.ask4date)\n\t\t\tself.date_button.grid(row=1, column=2, pady=10, padx=0)\n\t\t\t\n\t\t\ttk.Label(self.mainframe, text=\"Ore\").grid(row=2, column=0, pady=10, padx=10)\n\t\t\tself.time_entry = tk.Entry(self.mainframe, width=80)\n\t\t\tself.time_entry.insert(0, ore)\n\t\t\tself.time_entry.grid(row=2, column=1, pady=10, padx=10, columnspan=2)\n\t\t\n\t\ttk.Label(self.mainframe, text=\"Dati aggiuntivi in alto\").grid(row=3, column=0, pady=10, padx=10)\n\t\tself.additup_entry = tk.Entry(self.mainframe, width=80)\n\t\tself.additup_entry.insert(0, additup)\n\t\tself.additup_entry.grid(row=3, column=1, pady=10, padx=10, columnspan=2)\n\t\t\n\t\ttk.Label(self.mainframe, text=\"Descrizione\").grid(row=4, column=0, pady=10, padx=10)\n\t\tself.desc = tk.Text(self.mainframe, height=10)\n\t\tself.desc.insert(tk.END, description)\n\t\tself.desc.grid(row=4, column=1, pady=10, padx=10, columnspan=2)\n\t\t\n\t\ttk.Label(self.mainframe, text=\"Meeting point\").grid(row=5, column=0, pady=10, padx=10)\n\t\tself.meetingpoint_entry = tk.Entry(self.mainframe, width=67)\n\t\tself.meetingpoint_entry.insert(0, meetingpoint)\n\t\tself.meetingpoint_entry.grid(row=5, column=1, pady=10, padx=10, columnspan=1)\n\t\ttk.Button(self.mainframe, width=10, text=\"Helper\", command=self.nice_address).grid(row=5, column=2, pady=10, padx=0)\n\t\t\n\t\ttk.Label(self.mainframe, text=\"Durata\").grid(row=6, column=0, pady=10, padx=10)\n\t\tself.len_entry = tk.Entry(self.mainframe, width=80)\n\t\tself.len_entry.insert(0, vislen)\n\t\tself.len_entry.grid(row=6, column=1, pady=10, padx=10, columnspan=2)\n\t\t\n\t\ttk.Label(self.mainframe, text=\"Prezzo\").grid(row=7, column=0, pady=10, padx=10)\n\t\tself.price_entry = tk.Entry(self.mainframe, width=80)\n\t\tself.price_entry.insert(0, price)\n\t\tself.price_entry.grid(row=7, column=1, pady=10, padx=10, columnspan=2)\n\t\t\n\t\ttk.Label(self.mainframe, text=\"Pagamento entro il\").grid(row=8, column=0, pady=10, padx=10)\n\t\tself.pedant_entry = tk.Entry(self.mainframe, width=80)\n\t\tself.pedant_entry.grid(row=8, column=1, pady=10, padx=10, columnspan=2)\n\t\tif typeof == \"IND\":\n\t\t\ttk.Label(self.mainframe, text=\"Disponibili\").grid(row=9, column=0, pady=10, padx=10)\n\t\t\tself.dispon_entry = tk.Entry(self.mainframe, width=80)\n\t\t\tself.dispon_entry.insert(0, dispon)\n\t\t\tself.dispon_entry.grid(row=9, column=1, pady=10, padx=10, columnspan=2)\n\t\t\n\t\t#Image\n\t\tself.choose_image()\t#Default image\n\t\tlefButton = tk.Button(self.mainframe, text=\"<<\", command=(lambda:self.step_img(True)))\t#Move to the left\n\t\trigButton = tk.Button(self.mainframe, text=\">>\", command=(lambda:self.step_img(False)))\t#Move to the right\n\t\tchooseButton = tk.Button(self.mainframe, text=\"Scegli immagine\", command=(lambda:self.choose_image(False)))\t#Choose an image\n\t\tchooseButton.grid(row=6, column=4, pady=10, padx=10)\n\t\tlefButton.grid(row=0, column=3, pady=10, padx=10, rowspan=6)\n\t\trigButton.grid(row=0, column=5, pady=10, padx=10, rowspan=6)\n\t\t\n\t\tself.lang = tk.StringVar()\n\t\tlang_chooser = tk.Checkbutton(self.mainframe, text=\"Inglese\", variable=self.lang, onvalue=\"en\", offvalue=\"it\")\n\t\tif lang == \"\":\n\t\t\tlang_chooser.deselect()\n\t\tlang_chooser.grid(row=11, column=1, pady=10, padx=10, columnspan=2)\n\t\t#Insert button\n\t\tinsormod = \"Inserisci\"\n\t\tif name:\n\t\t\tinsormod = \"Modifica\"\n\t\t#TODO: Actual inserting\n\t\ttk.Button(self.mainframe, text=insormod, command=self.get_dictionary_from_entry).grid(row=10, column=1, pady=10, padx=10)\n\t\tself.mainframe.pack(side=\"top\")\n\t\n\tdef step_img(self, plus):\n\t\t\"\"\"\n\t\tMove the selected image 10 pixels to the left if the arguement is True, otherwise\n\t\tit moves the image to the right.\n\t\t\"\"\"\n\t\tif plus:\n\t\t\tself.curr_w += 10\n\t\telse:\n\t\t\tself.curr_w -= 10\n\t\tself.imageHolder.create_image(self.curr_w/2, self.curr_y/2, image=self.image)\n\t\tself.imageHolder.update()\n\t\t\n\tdef choose_image(self, first=True):\n\t\t\"\"\"\n\t\tDoes what the name says. It takes one arguement: first. It is set to True\n\t\tby default. It means it will not ask for a file but it will take the default\n\t\tpicture (the program logo) and put it as a placeholder.\n\t\tThe image will then be placed in the frame used to crop the image.\n\t\t\"\"\"\n\t\tif first:\n\t\t\tself.isNotFirst = False\n\t\t\timg = \"default.gif\"\n\t\t\tself.filename = img\n\t\telse:\n\t\t\tself.isNotFirst = True\n\t\t\tfile = tkFiledialog.askopenfilename()\n\t\t\tself.filename = file\n\t\t\tpath, name = os.path.split(file) # @UnusedVariable\n\t\t\tname, ext = name.split(\".\")\n\t\t\tself.ext = ext\n\t\t\ti = image_resizer.Q_Image(file)\n\t\t\ti.resize_size(0, 250)\n\t\t\ti.resize()\n\t\t\timg = \"temp_vis_big.\" + ext\n\t\t\ti.save(img)\n\t\t\tself.imageHolder.destroy()\n\t\tself.image = PIL.ImageTk.PhotoImage(PIL.Image.open(img))\n\t\ty, w = self.image.height(), self.image.width()\n\t\tself.fixed_w = w\n\t\tself.curr_y = y\n\t\tself.curr_w = w\n\t\t\n\t\tself.imageHolder = tk.Canvas(self.mainframe, width=200, height=250)\n\t\tself.imageHolder.create_image(w/2, y/2, image=self.image)\n\t\tself.imageHolder.grid(row=0, column=4, pady=10, padx=10, rowspan=6)\n\t\n\tdef commit_image(self):\n\t\t\"\"\"\n\t\tImage resizer and cropper for the visits images.\n\t\tIt saves the image in the current working folder with a fixed filename\n\t\tso the next image will overwrite it.\n\t\t\"\"\"\n\t\tresizer = image_resizer.Q_Image(self.filename)\n\t\tresizer.resize_size(0, 250)\n\t\tresizer.resize()\n\t\twidth = int((self.fixed_w - self.curr_w)/2)\n\t\tresizer.crop_starts(width, 0)\n\t\tresizer.crop_size(200, 250)\n\t\tresizer.crop()\n\t\t#resizer.show()\n\t\tself.img_temp_name = \"temp_vis_big_done.\" + os.path.split(self.filename)[1].split(\".\")[1]\n\t\tresizer.save(self.img_temp_name)\n\t\t\n\tdef makePage(self, page=\"\", lang=\"it\"):\n\t\t\"\"\"\n\t\tStub for the page creator form.\n\t\t\"\"\"\n\t\tif lang.upper() == \"IT\":\n\t\t\tlangfix = \"\"\n\t\telse:\n\t\t\tlangfix = \"EN\"\n\t\tif page:\n\t\t\tres = sq.select(sq.pages_name + langfix, sq.pages_vals[1], page)\n\t\telse:\n\t\t\tres = []\n\t\tself.lang = lang\n\t\tif res.__len__() < 1:\n\t\t\tself.pid = 0\n\t\t\tname = \"\"\n\t\t\tcontent = \"\"\n\t\t\ttitle = \"\"\n\t\t\tdescription = \"\"\n\t\t\tkeywords = \"\"\n\t\telse:\n\t\t\tres = res[0]\n\t\t\tself.pid = res[0]\n\t\t\tname = res[1]\n\t\t\tcontent = res[2]\n\t\t\ttitle = res[5]\n\t\t\tdescription = res[3]\n\t\t\tkeywords = res[4]\n\t\ttry:\n\t\t\tself.mainframe.destroy()\n\t\texcept AttributeError:\n\t\t\tpass\n\t\tself.mainframe = tk.Frame(self)\n\t\tself.mainframe.pack(side=\"top\")\n\t\t#NAME\n\t\ttk.Label(self.mainframe, text=\"Nome della pagina\").grid(row=0, column=0)\n\t\tself.name_entry = tk.Entry(self.mainframe, width=80)\n\t\tself.name_entry.insert(0, name)\n\t\tself.name_entry.grid(row=0, column=1, columnspan=2)\n\t\t#KEYWORDS\n\t\ttk.Label(self.mainframe, text=\"Keywords della pagina\").grid(row=1, column=0)\n\t\tself.keywords_entry = tk.Entry(self.mainframe, width=80)\n\t\tself.keywords_entry.insert(0, keywords)\n\t\tself.keywords_entry.grid(row=1, column=1, columnspan=2)\n\t\t#DESCRIPTION\n\t\ttk.Label(self.mainframe, text=\"Descrizione della pagina\").grid(row=2, column=0)\n\t\tself.description_entry = tk.Entry(self.mainframe, width=80)\n\t\tself.description_entry.insert(0, description)\n\t\tself.description_entry.grid(row=2, column=1, columnspan=2)\n\t\t#TITLE\n\t\ttk.Label(self.mainframe, text=\"Titolo della pagina\").grid(row=3, column=0)\n\t\tself.title_entry = tk.Entry(self.mainframe, width=80)\n\t\tself.title_entry.insert(0, title)\n\t\tself.title_entry.grid(row=3, column=1, columnspan=2)\n\t\t#CONTENT\n\t\ttk.Label(self.mainframe, text=\"Contenuto\").grid(row=4, column=0, pady=10, padx=10)\n\t\tself.desc_page = tk.Text(self.mainframe, height=10)\n\t\tself.desc_page.insert(tk.END, content)\n\t\tself.desc_page.grid(row=4, column=1, pady=10, padx=10, columnspan=2)\n\t\t#LANG_CHECKBOX\n\t\tself.lang = tk.StringVar()\n\t\tlang_chooser = tk.Checkbutton(self.mainframe, text=\"Inglese\", variable=self.lang, onvalue=\"en\", offvalue=\"it\")\n\t\tif lang.upper() == \"IT\":\n\t\t\tlang_chooser.deselect()\n\t\tlang_chooser.grid(row=5, column=1, pady=10, padx=10, columnspan=2)\n\t\tinsormod = \"Inserisci\"\n\t\tif name:\n\t\t\tinsormod = \"Modifica\"\n\t\ttk.Button(self.mainframe, text=insormod, command=self.makePageDict).grid(row=6, column=1, pady=10, padx=10)\n\t\t\n\tdef makePageDict(self):\n\t\t\"\"\"\n\t\tStub for the page creator. It simply calls makePageQ and then informs the user on the\n\t\tsuccess of makePageQ.\n\t\t\"\"\"\n\t\tif self.makePageQ(\n\t\t\t\t\t\tname=self.name_entry.get(), \n\t\t\t\t\t\ttitle=self.title_entry.get(), \n\t\t\t\t\t\tkeywords=self.keywords_entry.get(), \n\t\t\t\t\t\tdescription=self.description_entry.get(), \n\t\t\t\t\t\tcontent=self.desc_page.get(\"1.0\", tk.END), \n\t\t\t\t\t\tlang=self.lang):\n\t\t\ttry:\n\t\t\t\tself.mainframe.destroy()\n\t\t\texcept AttributeError:\n\t\t\t\tpass\n\t\t\tself.mainframe = tk.Frame(self)\n\t\t\tself.mainframe.pack(side=\"top\")\n\t\t\ttk.Label(self.mainframe, text=\"Pagina modificata\").grid(row=0, column=0)\n\t\telse:\n\t\t\ttry:\n\t\t\t\tself.mainframe.destroy()\n\t\t\texcept AttributeError:\n\t\t\t\tpass\n\t\t\tself.mainframe = tk.Frame(self)\n\t\t\tself.mainframe.pack(side=\"top\")\n\t\t\ttk.Label(self.mainframe, text=\"Pagina NON modificata\").grid(row=0, column=0)\n\t\n\tdef get_dictionary_from_entry(self):\n\t\t\"\"\"\n\t\tStub for the visit insertion method.\n\t\t\"\"\"\n\t\tif self.visittype == \"IND\":\n\t\t\ttable = \"visite-individuali\"\n\t\telif self.visittype == \"GRU\":\n\t\t\ttable = \"visite-gruppi\"\n\t\telif self.visittype == \"SCH\":\n\t\t\ttable = \"scuolevisite-individuali\"\n\t\telif self.visittype == \"CNM\":\n\t\t\ttable = \"conoscimi\"\n\t\telif self.visittype == \"MOD\":\n\t\t\ttable = \"\"\n\t\telif self.visittype == \"CEN\":\n\t\t\ttable = \"cenacoli\"\n\t\tif self.visittype in sq.visind_name:\n\t\t\tvalues = {\n\t\t\t\t\t\"nome\":self.name_entry.get(), \n\t\t\t\t\t\"meetingpoint\":self.meetingpoint_entry.get(),\n\t\t\t\t\t\"prezzotext\":self.price_entry.get(),\n\t\t\t\t\t\"description\":self.desc.get(\"1.0\", tk.END),\n\t\t\t\t\t\"additional\":self.pedant_entry.get(),\n\t\t\t\t\t\"additionalup\":self.additup_entry.get(),\n\t\t\t\t\t\"durata\":self.len_entry.get(),\n\t\t\t\t\t\"id\":self.vid,\n\t\t\t\t\t\"img\":\"\"\n\t\t\t}\n\t\t\tif self.visittype == \"IND\":\n\t\t\t\tvalues[\"date\"] = q_dates.string2date(self.date_entry.get())\n\t\t\t\tvalues[\"dispon\"] = self.dispon_entry.get()\n\t\t\t\tvalues[\"ore\"] = self.time_entry.get()\n\t\t\tif self.isNotFirst:\n\t\t\t\tself.commit_image()\n\t\t\t\tvalues[\"img\"] = uploads.uploadImage(self.img_temp_name)\n\t\telse:\n\t\t\t#Small vis\n\t\t\t#TODO: small vis\n\t\t\tvalues = {}\n\t\tquery = querymaker.querymaker(table, values)\n\t\tprotected.sendQuery(query, self.lang)\n\t\t#TODO: insert or modify the fucking visits!\n\t\n\tdef createSmallVis(self, typeof=\"CEN\", visid=0):\n\t\t\"\"\"\n\t\tStub for the method that should create a new small visit.\n\t\t\"\"\"\n\t\ttry:\n\t\t\tself.mainframe.destroy()\n\t\texcept AttributeError:\n\t\t\tpass\n\t\tif visid:\n\t\t\tvalues = sq.select(typeof, \"id\", visid)\n\t\t\tvalues = values[0]\n\t\telse:\n\t\t\tif typeof == \"CEN\":\n\t\t\t\tvalues = [\"\" for x in range(len(sq.vissec_vals))]\n\t\t\telse:\n\t\t\t\tvalues = [\"\" for x in range(len(sq.vissec_vals) + 1)]\n\t\tself.vid = visid\n\t\tdate = values[1]\n\t\tif date:\n\t\t\ttry:\n\t\t\t\tdate = q_dates.datetostring(date, \"IT\")\n\t\t\texcept TypeError:\n\t\t\t\tpass\n\t\tore = values[4]\n\t\tdispon = values[3]\n\t\taddit = values[2]\n\t\tif values[0]:\n\t\t\tself.vid = values[0]\n\t\tself.vid = visid\n\t\tself.visittype = typeof\n\t\tself.mainframe = tk.Frame(self)\n\t\t\n\t\ttk.Label(self.mainframe, text=\"Data della visita\").grid(row=1, column=0, pady=10, padx=10)\n\t\tself.date_entry = tk.Entry(self.mainframe, width=67)\n\t\tself.date_entry.grid(row=1, column=1, pady=10, padx=0)\n\t\tself.date_entry.insert(0, date)\n\t\tself.date_button = tk.Button(self.mainframe, width=10, text=\"Scegli\", command=self.ask4date)\n\t\tself.date_button.grid(row=1, column=2, pady=10, padx=0)\n\t\t\n\t\ttk.Label(self.mainframe, text=\"Ore\").grid(row=2, column=0, pady=10, padx=10)\n\t\tself.time_entry = tk.Entry(self.mainframe, width=80)\n\t\tself.time_entry.insert(0, ore)\n\t\tself.time_entry.grid(row=2, column=1, pady=10, padx=10, columnspan=2)\n\t\t\n\t\t\t\t\n\t\ttk.Label(self.mainframe, text=\"Pagamento entro il\").grid(row=8, column=0, pady=10, padx=10)\n\t\tself.pedant_entry = tk.Entry(self.mainframe, width=80)\n\t\tself.pedant_entry.insert(0, addit)\n\t\tself.pedant_entry.grid(row=8, column=1, pady=10, padx=10, columnspan=2)\n\t\ttk.Label(self.mainframe, text=\"Disponibili\").grid(row=9, column=0, pady=10, padx=10)\n\t\tself.dispon_entry = tk.Entry(self.mainframe, width=80)\n\t\tself.dispon_entry.insert(0, dispon)\n\t\tself.dispon_entry.grid(row=9, column=1, pady=10, padx=10, columnspan=2)\n\t\t\n\t\tif typeof == \"MOD\":\n\t\t\tpr = values[5]\t # @UnusedVariable\n\t\t\ttk.Label(self.mainframe, text=\"Tipo\").grid(row=0, column=0)\n\t\t\tself.mainlist = tk.Listbox(self.mainframe, width=120)\n\t\t\tscrollbar = tk.Scrollbar(self.mainframe)\n\t\t\tself.mainlist.grid(row=1, column=0)\n\t\t\tself.mainlist.config(yscrollcommand=scrollbar.set)\n\t\t\tscrollbar.grid(row=1, column=0, sticky=tk.N+tk.S+tk.E+tk.W)\n\t\t\tscrollbar['command'] = self.mainlist.yview\n\t\t\tpr_type = sq.select()\n\t\t\t\n\t\t\tfor t in pr_type:\n\t\t\t\tself.mainlist.insert(tk.END, t)\n\t\t\n\t\tself.lang = tk.StringVar()\n\t\tlang_chooser = tk.Checkbutton(self.mainframe, text=\"Inglese\", variable=self.lang, onvalue=\"en\", offvalue=\"it\")\n\t\tlang_chooser.deselect()\n\t\tlang_chooser.grid(row=11, column=1, pady=10, padx=10, columnspan=2)\n\t\t#Insert button\n\t\tinsormod = \"Inserisci\"\n\t\tif self.vid:\n\t\t\tinsormod = \"Modifica\"\n\t\ttk.Button(self.mainframe, text=insormod, command=self.get_dictionary_from_entry).grid(row=10, column=1, pady=10, padx=10)\n\t\tself.mainframe.pack(side=\"top\")\n\t\t\n\tdef createButtons(self):\n\t\t\"\"\"\n\t\tIt is called buttons because the first version had buttons instead of a menu\n\t\tto keep it simple. But basically this creates the menu with all of its functions\n\t\tand the name of the visits.\n\t\t\"\"\"\n\t\t#vis_ind = sq.select(\"IND\")\n\t\t#vis_gru = sq.select(\"GRU\")\n\t\t#vis_sch = sq.select(\"SCH\")\n\t\t#vis_cnm = sq.select(\"CNM\")\n\t\t#vis_sec = sq.select(\"MOD\")\n\t\t#vis_cen = sq.select(\"CEN\")\n\t\t#nm_off = 10\n\t\t#id_off = 8\n\t\t\t\n\t\tmenubar = tk.Menu(self)\n\t\tfont=tkFont.Font(family=\"Arial\", size=11)\n\t\t#=========COMMANDS==#\n\t\t#add_visit_ind = (lambda v=\"IND\":self.bigvis_maker(v))\n\t\t#add_visit_gru = (lambda v=\"GRU\":self.bigvis_maker(v))\n\t\t#add_visit_sch = (lambda v=\"SCH\":self.bigvis_maker(v))\n\t\t#add_visit_cen = (lambda v=\"CEN\":self.createSmallVis(v))\n\t\t#add_visit_mod = (lambda v=\"MOD\":self.createSmallVis(v))\n\t\t#add_visit_cnm = (lambda v=\"CNM\":self.bigvis_maker(v))\n\t\t#===VISITS===#\n\t\t\"\"\"menuvisits = tk.Menu(menubar, tearoff=0, font=font)\n\t\tmenuvisits.add_command(label=\"Aggiungi visita individuale\", command=add_visit_ind)\n\t\tmenuvisits.add_command(label=\"Aggiungi visita gruppi\", command=add_visit_gru)\n\t\tmenuvisits.add_command(label=\"Aggiungi visita scuole\", command=add_visit_sch)\n\t\tmenuvisits.add_command(label=\"Aggiungi visita ConosciMI\", command=add_visit_cnm)\n\t\tmenuvisits.add_command(label=\"Aggiungi visita Cenacolo\", command=add_visit_cen)\n\t\tmenuvisits.add_command(label=\"Aggiungi visita Palazzo Reale IT\", command=add_visit_mod)\n\t\tmenuvisits.add_command(label=\"Aggiungi visita Palazzo Reale EN\", command=add_visit_mod)\n\t\tmenuvisits.add_separator()\n\t\tmenumodind = tk.Menu(menuvisits, tearoff=0, font=font)\n\t\t#----------\n\t\tfor ind in sq.select(\"IND\"):\n\t\t\tname=html_fix(ind[nm_off])\n\t\t\tvis_id=ind[id_off]\n\t\t\tmenumodind.add_command(label=name, command=(lambda v=\"IND\", i=vis_id:self.bigvis_maker(v, i)))\n\t\t#----------\n\t\tmenumodsch = tk.Menu(menuvisits, tearoff=0, font=font)\n\t\tfor sch in sq.select(\"SCH\"):\n\t\t\tname=html_fix(sch[nm_off])\n\t\t\tvis_id=sch[id_off]\n\t\t\tmenumodsch.add_command(label=name, command=(lambda v=\"SCH\", i=vis_id:self.bigvis_maker(v, i)))\n\t\t#----------\n\t\tmenumodcnm = tk.Menu(menuvisits, tearoff=0, font=font)\n\t\tfor cnm in sq.select(\"CNM\"):\n\t\t\tname=html_fix(cnm[nm_off])\n\t\t\tvis_id=cnm[id_off]\n\t\t\tmenumodcnm.add_command(label=name, command=(lambda v=\"CNM\", i=vis_id:self.bigvis_maker(v, i)))\n\t\t#-----------\n\t\tmenumodgru = tk.Menu(menuvisits, tearoff=0, font=font)\n\t\tfor gru in sq.select(\"GRU\"):\n\t\t\tname=html_fix(gru[nm_off])\n\t\t\tvis_id=gru[id_off]\n\t\t\tmenumodgru.add_command(label=name, command=(lambda v=\"GRU\", i=vis_id:self.bigvis_maker(v, i)))\n\t\tmenumodcen = tk.Menu(menuvisits, tearoff=0, font=font)\n\t\tfor cen in sq.select(\"CEN\"):\n\t\t\tname = q_dates.datetostring(cen[sq.vissec_vals.index(\"data\")], \"IT\")\n\t\t\tvis_id = cen[sq.vissec_vals.index(\"id\")]\n\t\t\tmenumodcen.add_command(label=name, command=(lambda v=\"CEN\", i=vis_id:self.createSmallVis(v, i)))\n\t\tmenumodmod = tk.Menu(menuvisits, tearoff=0, font=font)\n\t\tfor mod in sq.select(\"MOD\"):\n\t\t\tname = sq.prTypeconvert(mod[sq.describe(\"MOD\").index(\"pr_type\")]) + q_dates.datetostring(mod[sq.vissec_vals.index(\"data\")], \"IT\")\n\t\t\tvis_id = mod[sq.vissec_vals.index(\"id\")]\n\t\t\tmenumodmod.add_command(label=name, command=(lambda v=\"MOD\", i=vis_id:self.createSmallVis(v, i)))\n\t\tmenuvisits.add_cascade(label=\"Modifica visita individuale\", menu=menumodind)\n\t\tmenuvisits.add_cascade(label=\"Modifica visita gruppi\", menu=menumodgru)\n\t\tmenuvisits.add_cascade(label=\"Modifica visita scuole\", menu=menumodsch)\n\t\tmenuvisits.add_cascade(label=\"Modifica visita ConosciMI\", menu=menumodcnm)\n\t\tmenuvisits.add_cascade(label=\"Modifica visita Cenacolo\", menu=menumodcen)\n\t\tmenuvisits.add_cascade(label=\"Modifica visita Palazzo Reale\", menu=menumodmod)\n\t\tmenubar.add_cascade(label=\"Visite\", menu=menuvisits)\n\t\t\"\"\"\n\t\t#===SITE===#\n\t\tmenusite = tk.Menu(menubar, tearoff=0, font=font)\n\t\t#-------------\n\t\tmenuheader = tk.Menu(menusite, tearoff=0, font=font)\n\t\tfor i in range(1,7):\n\t\t\tmenuheader.add_command(label=\"0\" + str(i) + \"...\", command=(lambda num=i:self.selectHeader(num)))\n\t\t#menupages = tk.Menu(menusite, tearoff=0, font=font)\n\t\t#for page in sq.select(sq.pages_name):\n\t\t\t#menupages.add_command(label=page[1], command=(lambda p=page[1]:self.makePage(p, \"it\")))\n\t\tmenuheader.add_command(label=\"Vedi gli header\", command=(lambda page=\"http://www.quattropassimilano.it/atarashii/_php/see_headers.php\":webbrowser.open(page)))\n\t\t#menusite.add_cascade(label=\"Modifica pagina\", menu=menupages)\n\t\t#menusite.add_command(label=\"Nuova pagina\", command=(lambda:self.makePage(\"\", \"\")))\n\t\tmenubar.add_cascade(label=\"Modifica header\", menu=menuheader)\n\t\tmenusite.add_command(label=\"Visite homepage IT\", command=(lambda:self.calendar_make(False, \"it\")))\n\t\tmenusite.add_command(label=\"Visite homepage EN\", command=(lambda:self.calendar_make(False, \"en\")))\n\t\tmenusite.add_command(label=\"Vai al sito\", command=(lambda page=\"http://www.quattropassimilano.it\":webbrowser.open(page)))\n\t\t#menusite.add_separator()\n\t\t#menusite.add_command(label=\"Modifica struttura sito\", command=add_visit_mod)\n\t\t#menusite.add_command(label=\"Modifica SEO\", command=add_visit_mod)\n\t\t#menusite.add_command(label=\"Analytics\", command=add_visit_mod)\t#Removed\n\t\tmenubar.add_cascade(label=\"Pagine e sito\", menu=menusite)\n\t\t\n\t\t#===EMAIL===#\n\t\t#menuemail = tk.Menu(menubar, tearoff=0, font=font)\n\t\t#menuemail.add_command(label=\"Ricevute\", command=self.showmails)\n\t\t#menubar.add_cascade(label=\"E-mail\", menu=menuemail)\n\t\t\n\t\t#===NEWSLETTER===#\n\t\tmenunews = tk.Menu(menubar, tearoff=0, font=font)\n\t\tmenunews.add_command(label=\"Componi calendario\", command=self.calendar_make)\n\t\t#menunews.add_command(label=\"Componi calendario\", command=self.calendar_make)\n\t\t#menunews.add_command(label=\"Componi newsletter...\", command=add_visit_mod)\n\t\t#menunews.add_separator()\n\t\t#menunews.add_command(label=\"Vedi iscritti\", command=self.see_subscribed)\n\t\t#menunews.add_command(label=\"Aggiungi iscritto...\", command=self.add_subscribed)\n\t\tmenubar.add_cascade(label=\"Calendario\", menu=menunews)\n\t\t\n\t\t\n\t\t#===OPTIONS===#\n\t\tmenuopt = tk.Menu(menubar, tearoff=0, font=font)\n\t\tmenuopt.add_command(label=\"GitHub Page\", command=(lambda page=\"https://github.com/Freonius/Quattropassi_ronin\":webbrowser.open(page)))\n\t\t#menuopt.add_command(label=\"Help\", command=add_visit_mod)\n\t\tmenuopt.add_separator()\n\t\tmenuopt.add_command(label=\"Esci\", command=self.quit)\n\t\tmenubar.add_cascade(label=\"Opzioni\", menu=menuopt)\n\t\tself.menubar = menubar\n\t\n\tdef selectHeader(self, num):\n\t\t\"\"\"\n\t\tPops up a file dialog that asks for a picture, resizes it for the three header\n\t\tsizes, crops them, saves them and uploads them.\n\t\t\"\"\"\n\t\tfile = tkFiledialog.askopenfilename()\n\t\ttry:\n\t\t\tb_img = image_resizer.Q_Image(file)\t#Big header\n\t\t\tb_img.crop_size(980, 275)\n\t\t\tb_img.crop()\n\t\t\tb_img.save(\"b0\" + str(num) + \".jpg\")\n\t\t\tm_img = image_resizer.Q_Image(file)\t#Medium header\n\t\t\tm_img.crop_size(800, 200)\n\t\t\tm_img.crop()\n\t\t\tm_img.save(\"b0\" + str(num) + \"m.jpg\")\n\t\t\ts_img = image_resizer.Q_Image(file)\t#Small header\n\t\t\ts_img.crop_size(500, 85)\n\t\t\ts_img.crop()\n\t\t\ts_img.save(\"b0\" + str(num) + \"s.jpg\")\n\t\t\tuploads.header(\"b0\" + str(num) + \".jpg\")\n\t\t\tuploads.header(\"b0\" + str(num) + \"m.jpg\")\n\t\t\tuploads.header(\"b0\" + str(num) + \"s.jpg\")\n\t\t\tos.remove(\"b0\" + str(num) + \".jpg\")\n\t\t\tos.remove(\"b0\" + str(num) + \"m.jpg\")\n\t\t\tos.remove(\"b0\" + str(num) + \"s.jpg\")\n\t\t\tb_img = None\n\t\t\tm_img = None\n\t\t\ts_img = None\n\t\texcept image_resizer.Q_ImageException:\n\t\t\tpass\n\n\tdef splash(self):\n\t\t\"\"\"\n\t\tSplash screen to make it feel \"shiny\".\n\t\tIt also fetches the emails and the visits from the server after the animation.\n\t\t\"\"\"\n\t\tself.splashimage=PIL.ImageTk.PhotoImage(PIL.Image.open(\"splash.gif\"))\n\t\t\n\t\tw = self.splashimage.width()\n\t\tsplashsteps = 60\t#How many steps to move\n\t\tsplasheachpix = 1 #Number of pixels to move each time\n\t\tsplashsteptime = 0.1\t#each steps last x seconds\n\t\tw -= (splashsteps-1) * splasheachpix\n\t\ty = self.splashimage.height()\n\t\tscreen_y = self.winfo_screenheight()\n\t\tself.ImbImage = tk.Canvas(self, width=w, height=screen_y)\n\t\tself.ImbImage.pack()\n\t\tw += (splashsteps-1) * splasheachpix\n\t\tw /= 2\n\t\tscreen_y /= 4\n\t\ty /= 2\n\t\ty += screen_y\n\t\tself.ImbImage.create_image(w, y, image=self.splashimage)\n\t\tfor x in range(splashsteps):\n\t\t\tx *= splasheachpix\n\t\t\ttime.sleep(splashsteptime)\n\t\t\tself.ImbImage.create_image(w-x, y, image=self.splashimage)\n\t\t\tself.ImbImage.update()\n\t\tself.ImbImage.destroy()\n\t\tself.splashimage = None\n\t\t#self.prepare()\n\t\treturn None\n\t\n\tdef prepare(self):\n\t\t\"\"\"\n\t\tFetches the visits, changes the cwd. Plus, initially, it did much more.\n\t\t\"\"\"\n\t\tpathname = os.path.dirname(sys.argv[0]) \n\t\tself_path = os.path.abspath(pathname)\n\t\told_cwd = os.getcwd()\n\t\tself_file = os.path.join(self_path, sys.argv[0])\n\t\tcurrent_path, selfname = os.path.split(os.path.realpath(self_file)) # @UnusedVariable\n\t\tif old_cwd != current_path:\n\t\t\tos.chdir(current_path)\n\t\tconnection_test = conn.testConn()\n\t\tfor lang in (\"IT\", \"EN\"):\n\t\t\tif connection_test:\n\t\t\t\tvis = conn.getAllVis(lang)\n\t\t\t\t#pag = conn.getAllPages(lang)\n\t\t\t\ttyp = conn.getPrTypes(lang)\n\t\t\telse:\n\t\t\t\tvis = None\n\t\t\t\t#pag = None\n\t\t\t\ttyp = None\n\t\t\tsq.save_visits(vis, lang)\n\t\t\t#sq.save_pages(pag, lang)\n\t\t\tsq.saveTypes(typ, lang)\n\t\t#test = (\"mail@address.com\", \"mailpassword\")\n\t\t#sq.save_emails(mail_stuff.getMails(user=test[0], pwd=test[1]))\n\ndef runGui():\n\tpathname = os.path.dirname(sys.argv[0]) \n\tself_path = os.path.abspath(pathname)\n\told_cwd = os.getcwd()\n\tself_file = os.path.join(self_path, sys.argv[0])\n\tcurrent_path = os.path.split(os.path.realpath(self_file))[0]\n\troot = tk.Tk()\n\tapp = Q_gui(master=root)\n\tapp.mainloop()\n\ttry:\n\t\troot.destroy()\n\texcept tk._tkinter.TclError:\n\t\tpass\n\texcept:\n\t\tpass\n\tfinally:\n\t\tif old_cwd != current_path:\n\t\t\tos.chdir(old_cwd)\n\t\tsys.exit(0)\n\nif __name__ == \"__main__\":\n\trunGui()","sub_path":"Nagamaki/q_gui/gui_main.py","file_name":"gui_main.py","file_ext":"py","file_size_in_byte":34921,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"584980001","text":"import sys\n\ndef displayCube():\n global cube\n print('*'*16, file=sys.stderr)\n print(cube[16:18], file=sys.stderr)\n print(cube[18:20], file=sys.stderr)\n print(cube[0:2]+' '+cube[4:6]+' '+cube[8:10]+' '+cube[12:14], file=sys.stderr)\n print(cube[2:4]+' '+cube[6:8]+' '+cube[10:12]+' '+cube[14:16], file=sys.stderr)\n print(cube[20:22], file=sys.stderr)\n print(cube[22:24], file=sys.stderr)\n print('*'*16, file=sys.stderr)\n\ndef setVal(s,i,v):\n return s[:i]+v+s[i+1:]\n\n# Shift for face rotation\ndef shift4(s,d,i1,i2,i3,i4):\n if d>0:\n val = [s[i4],s[i1],s[i2],s[i3]]\n else:\n val = [s[i2],s[i3],s[i4],s[i1]]\n s = setVal(s,i1,val[0])\n s = setVal(s,i2,val[1])\n s = setVal(s,i3,val[2])\n s = setVal(s,i4,val[3])\n return s\n\n# Shift for col/row rotation\ndef shift8(s,d,i1,i2,i3,i4,i5,i6,i7,i8):\n if d>0:\n val = [s[i7],s[i8],s[i1],s[i2],s[i3],s[i4],s[i5],s[i6]]\n else:\n val = [s[i3],s[i4],s[i5],s[i6],s[i7],s[i8],s[i1],s[i2]]\n s = setVal(s,i1,val[0])\n s = setVal(s,i2,val[1])\n s = setVal(s,i3,val[2])\n s = setVal(s,i4,val[3])\n s = setVal(s,i5,val[4])\n s = setVal(s,i6,val[5])\n s = setVal(s,i7,val[6])\n s = setVal(s,i8,val[7])\n return s\n\n# 16 17\n# 18 19\n# 00 01 04 05 08 09 12 l3\n# 02 03 06 07 10 11 14 15\n# 20 21\n# 22 23\n\ndef applyMove(cube,m):\n t,d = m\n # for each move, 1 roll + 1 rot\n if t=='F':\n cube=shift8(cube,d,18,19,4,6,21,20,15,13)\n cube=shift4(cube,d,0,1,3,2)\n elif t=='R':\n cube=shift8(cube,d,23,21,3,1,19,17,8,10)\n cube=shift4(cube,d,4,5,7,6)\n elif t=='B':\n cube=shift8(cube,d,7,5,17,16,12,14,22,23)\n cube=shift4(cube,d,8,9,11,10)\n elif t=='L':\n cube=shift8(cube,d,16,18,0,2,20,22,11,9)\n cube=shift4(cube,d,12,13,15,14)\n elif t=='U':\n cube=shift8(cube,d,13,12,9,8,5,4,1,0)\n cube=shift4(cube,d,16,17,19,18)\n elif t=='D':\n cube=shift8(cube,d,2,3,6,7,10,11,14,15)\n cube=shift4(cube,d,20,21,23,22)\n\n return cube\n\n# MAIN PROGRAM\ninp = input()\nmoves=[]\nmoveType=''\ndirection=1\nnb=0\nfor c in inp:\n if c in 'FBRLUD':\n for i in range(nb): moves.append([moveType,direction])\n moveType = c\n direction=1\n nb=1\n elif c =='\\'':\n direction=-1\n elif c in '23456789':\n # repeat\n nb=int(c)\nfor i in range(nb): moves.append([moveType,direction])\n\ncube='FFFFRRRRBBBBLLLLUUUUDDDD'\n#displayCube()\nfor m in moves:\n cube=applyMove(cube,m)\n #displayCube()\nprint(cube[0:2]+'\\n'+cube[2:4])\n\n\n\n\n\n","sub_path":"RubiksCube/2x2x2/Other coders/rubiksCubeMvt-OHER-Lvl29.py","file_name":"rubiksCubeMvt-OHER-Lvl29.py","file_ext":"py","file_size_in_byte":2564,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"386902665","text":"from Bio import SeqIO\n\ndef translate(seq):\n from Bio.Seq import Seq\n from Bio.Alphabet import generic_nucleotide\n return str(Seq(seq,generic_nucleotide).translate())\n\ndef contains_restriction_sites(enzymes,sequence):\n import re\n found = [re.search(e.site,sequence,flags=re.I)!=None for e in enzymes]\n foundenzymes = [e for e,f in zip(enzymes,found) if f]\n return (any(found), foundenzymes)\n\ndef rare_codon_count(seqstr, codon_table, thresh):\n aafrac = codon_table._aa_fraction\n seqstr = seqstr.lower()\n count = 0\n for idx in range(0,len(seqstr),3):\n if aafrac[seqstr[idx:(idx+3)]] < thresh:\n count += 1\n return count\n\ndef log_joint_codon_prob(seqstr, codon_table):\n import numpy as np\n logprob_dict = { K : np.log(V) for K,V in codon_table._aa_fraction.items() }\n seqstr = seqstr.lower()\n logprob = 0\n for idx in range(0,len(seqstr),3):\n codon = seqstr[idx:idx+3]\n logprob += logprob_dict[codon]\n return logprob\n\ndef df_to_fasta(df, filename, name_field='accession', seq_field = 'protein-sequence', description_field = None):\n\n with open(filename,'w') as f:\n for i,row in df.iterrows():\n print('>%s' % row[name_field]+((' %s' % row[description_field]) if description_field is not None else ''), file=f)\n print(row[seq_field],file=f)\n\n\ndef remove_start_stop(df, seq_field='protein-sequence', mut_field='protein-mutations'):\n idx = df[seq_field].str.contains('^M')\n df.loc[idx,seq_field] = [s[1:] for s in df.loc[idx,seq_field]]\n if mut_field is not None:\n df.loc[idx,mut_field] = df.loc[idx,mut_field].apply(lambda x: 'd1' if x=='wt' else 'd1 '+x)\n n1 = sum(idx)\n \n idx = df[seq_field].str.contains('\\*$')\n df.loc[idx,seq_field] = [s[:-1] for s in df.loc[idx,seq_field]]\n n2 = sum(idx)\n \n print('Removed %d STARTs and %d STOPs among %d sequences total.' % (n1,n2,len(df)))\n \n return df\n\ndef truncate_phobius_sp(df, seq_field='protein-sequence', mut_field='protein-mutations'):\n import re\n for i,row in df.iterrows():\n if '/' in row['PREDICTION']:\n altstart = int(re.search('(\\d*)$',row['PREDICTION'].split('/')[0]).groups()[0]) # 1-indexed\n newseq = 'G'+df.loc[i,seq_field][altstart:]\n df.loc[i,seq_field] = newseq\n if mut_field is not None:\n mutstr = 'd1-%d %s%dG%s' % (altstart, \n newseq[1],\n altstart+1,\n newseq[1]) \n\n currmutstr = df.loc[i,mut_field]\n df.loc[i,mut_field] = mutstr if currmutstr=='wt' else mutstr+' '+currmutstr\n return df\n\ndef blast_compare(query_seqlist, target_seqlist = None, datadir = 'data/',\n blast_path = '/home/jue/bin/ncbi-blast-2.5.0+/bin/', blast_program = 'blastp'):\n import json\n from subprocess import Popen,PIPE\n import os\n import numpy as np\n from Bio import SeqIO\n \n if target_seqlist:\n self = False\n else:\n self = True\n target_seqlist = query_seqlist\n \n id_mat = np.zeros([len(query_seqlist),len(target_seqlist)])\n alen_mat = np.zeros([len(query_seqlist),len(target_seqlist)])\n for idx_q,qseq in enumerate(query_seqlist):\n if self:\n id_mat[idx_q,idx_q] = len(qseq)\n for idx_t,tseq in enumerate(target_seqlist):\n if (not self) or (self and idx_t < idx_q):\n SeqIO.write(qseq,open(datadir+'qseq.fa','w'),'fasta')\n SeqIO.write(tseq,open(datadir+'tseq.fa','w'),'fasta')\n blastp = Popen([blast_path+blast_program,\n \"-query\",\"%s\" % datadir+'qseq.fa',\n \"-subject\",\"%s\" % datadir+'tseq.fa',\n \"-outfmt\",'15'],\n stdout=PIPE,stderr=PIPE)\n stdout, stderr = blastp.communicate()\n results = json.loads(stdout)\n\n if len(results['BlastOutput2'][0]['report']['results']['bl2seq'][0]['hits']) > 0:\n hsplist = results['BlastOutput2'][0]['report']['results']['bl2seq'][0]['hits'][0]['hsps']\n id_mat[idx_q,idx_t] = float(hsplist[0]['identity'])\n alen_mat[idx_q,idx_t] = float(hsplist[0]['align_len'])\n if self:\n id_mat[idx_t,idx_q] = id_mat[idx_q,idx_t]\n alen_mat[idx_t,idx_q] = alen_mat[idx_q,idx_t]\n os.remove(datadir+'qseq.fa')\n os.remove(datadir+'tseq.fa')\n return id_mat, alen_mat\n\ndef clustalo_align(seqs):\n from Bio import AlignIO\n from subprocess import Popen,PIPE\n from cStringIO import StringIO\n\n fasta = StringIO()\n SeqIO.write(seqs,fasta,'fasta')\n \n clustalo = Popen(['clustalo',\n '--dealign',\n '--pileup',\n '-i','-'],\n stdin=PIPE, stdout=PIPE,stderr=PIPE)\n stdout, stderr = clustalo.communicate(input=fasta.getvalue())\n\n return AlignIO.read(StringIO(stdout),'fasta')\n\n","sub_path":"juetools/sequence.py","file_name":"sequence.py","file_ext":"py","file_size_in_byte":5150,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"133812292","text":"import jsonpickle\nfrom medcat.config import BaseConfig\n\n\nclass ConfigMetaCAT(BaseConfig):\n jsonpickle.set_encoder_options('json', sort_keys=True, indent=2)\n\n def __init__(self):\n super().__init__()\n\n self.general = {\n 'device': 'cpu',\n 'disable_component_lock': False,\n 'seed': 13,\n 'category_name': None, # What category is this meta_cat model predicting/training\n 'category_value2id': {}, # Map from category values to ID, if empty it will be autocalculated during training\n 'vocab_size': None, # Will be set automatically if the tokenizer is provided during meta_cat init\n 'lowercase': True, # If true all input text will be lowercased\n 'cntx_left': 15, # Number of tokens to take from the left of the concept\n 'cntx_right': 10, # Number of tokens to take from the right of the concept\n 'replace_center': None, # If set the center (concept) will be replaced with this string\n 'batch_size_eval': 5000,\n 'annotate_overlapping': False, # If set meta_anns will be calcualted for doc._.ents, otherwise for doc.ents\n 'tokenizer_name': 'bbpe',\n # This is a dangerous option, if not sure ALWAYS set to False. If set, it will try to share the pre-calculated\n #context tokens between MetaCAT models when serving. It will ignore differences in tokenizer and context size,\n #so you need to be sure that the models for which this is turned on have the same tokenizer and context size, during\n #a deployment.\n 'save_and_reuse_tokens': False,\n 'pipe_batch_size_in_chars': 20000000,\n }\n self.model = {\n 'model_name': 'lstm',\n 'num_layers': 2,\n 'input_size': 300,\n 'hidden_size': 300,\n 'dropout': 0.5,\n 'num_directions': 2, # 2 - bidirectional model, 1 - unidirectional\n 'nclasses': 2, # Number of classes that this model will output\n 'padding_idx': -1,\n 'emb_grad': True, # If True the embeddings will also be trained\n 'ignore_cpos': False, # If set to True center positions will be ignored when calculating represenation\n }\n\n self.train = {\n 'batch_size': 100,\n 'nepochs': 50,\n 'lr': 0.001,\n 'test_size': 0.1,\n 'shuffle_data': True, # Used only during training, if set the dataset will be shuffled before train/test split\n 'class_weights': None,\n 'score_average': 'weighted', # What to use for averaging F1/P/R across labels\n 'prerequisites': {},\n 'cui_filter': None, # If set only this CUIs will be used for training\n 'auto_save_model': True, # Should do model be saved during training for best results\n }\n","sub_path":"medcat/config_meta_cat.py","file_name":"config_meta_cat.py","file_ext":"py","file_size_in_byte":3059,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"454092868","text":"\"\"\" Задание №2: Посчитать четные и нечетные цифры введенного натурального числа.\nНапример, если введено число 34560, то у него 3 четные цифры (4, 6 и 0) и 2 нечетные (3 и 5). \"\"\"\n\nusers_number = input('Здравствуйте! Введите число: ')\none = 0\ntwo = 0\nfor x in users_number:\n y = int(x)\n if y % 2 == 0:\n one += 1\n else:\n two += 1\n\nprint(f'Число {users_number} имеет {one} чётных цифр и {two} нечётных цифр')\n\n","sub_path":"Task_2_h_v_2.py","file_name":"Task_2_h_v_2.py","file_ext":"py","file_size_in_byte":605,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"242149477","text":"# import xlrd\nfrom xlutils.copy import copy\nimport xlrd.sheet\nimport Project_path\n\nclass MyXlrd(xlrd.sheet.Sheet):\n def __init__(self,filename,position=None,name=None,number=None):\n super(MyXlrd, self).__init__(self,position,name,number)\n self.book=xlrd.open_workbook(filename)\n self.name=name\n\nif __name__==\"__main__\":\n test_data_path = Project_path.TestData_path + \"case.xlsx\"\n r = MyXlrd(test_data_path)\n a = r.cell_value(1,1)\n print(a)","sub_path":"AITEST/common/myxlrd.py","file_name":"myxlrd.py","file_ext":"py","file_size_in_byte":475,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"56526598","text":"\r\ndef slurp(filename):\r\n \"\"\"\r\n Reads the entire file into a list that contains the lines of each file.\r\n :param filename: the name of the file to read.\r\n :return: a list containing one element for each line in the file\r\n \"\"\"\r\n with open(filename, 'r') as infile:\r\n return [line.rstrip() for line in infile.readlines()]\r\n\r\n\r\n#print(results)\r\ndef gematria(word_to_match, filename):\r\n results = []\r\n results += slurp(filename)\r\n results = [x.lower() for x in results]\r\n \"\"\"\r\n Takes a word and the name of a dictionary file, and then\r\n returns (a list of) all the entries from the dictionary that\r\n Gematrically match the given word.\r\n\r\n \"Gematria is the act of assigning numeric values to letters in an\r\n alphabet\"\r\n -- (https://en.wikipedia.org/wiki/Gematria,\r\n last access 10/7/2017).\r\n Once each letter is assigned a value you can compute the value of\r\n a word or phrase by simply summing the values of each letter in\r\n the word/phrase. Using a mapping of a=1, b=2, c=3, ..., z=26,\r\n \"Phil\" has a value of P=16 + h=8 + i=9 + l=12 == 45.\r\n Note that the case of a letter does not change its value.\r\n\r\n :param word_to_match: the word for which you are trying to find a Gematric match\r\n :param filename: the dictionary file containing other candidate words\r\n\r\n >>> g = gematria('Phil', 'small_dict.txt')\r\n >>> g\r\n ['bios', 'coder', 'gore', 'knife', 'racer']\r\n \"\"\"\r\n # replace pass below with your code\r\n match_this = {\r\n \"a\": 1,\r\n \"b\": 2,\r\n \"c\": 3,\r\n \"d\": 4,\r\n \"e\": 5,\r\n \"f\": 6,\r\n \"g\": 7,\r\n \"h\": 8,\r\n \"i\": 9,\r\n \"j\": 10,\r\n \"k\": 11,\r\n \"l\": 12,\r\n \"m\": 13,\r\n \"n\": 14,\r\n \"o\": 15,\r\n \"p\": 16,\r\n \"q\": 17,\r\n \"r\": 18,\r\n \"s\": 19,\r\n \"t\": 20,\r\n \"u\": 21,\r\n \"v\": 22,\r\n \"w\": 23,\r\n \"x\": 24,\r\n \"y\": 25,\r\n \"z\": 26\r\n };\r\n new_sum = []\r\n sump =0\r\n for i in results:\r\n for x,y in match_this.items():\r\n if(i.find(x) != -1):\r\n sump = sump +y\r\n return sump\r\nprint(gematria('tesr', 'small_dict.txt'))","sub_path":"gematria.py","file_name":"gematria.py","file_ext":"py","file_size_in_byte":2202,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"79173015","text":"#pymongo imports\n\n\nimport pymongo\nfrom pymongo import MongoClient\nfrom werkzeug.datastructures import ImmutableMultiDict\nfrom json2html import *\nfrom bson.objectid import ObjectId\nimport json\n\n\n#function imports\n\n\nimport os\nfrom datetime import datetime\nimport re\nimport string\nsession={}\nlog=[]\n\n\n#django imports\n\n\nfrom django.shortcuts import render\nfrom django.http import HttpResponse, HttpResponseNotFound, Http404, HttpResponseRedirect\nfrom django.urls import reverse\n\n\n#mongodb\nclient = MongoClient('localhost',27017)\ndb = client.School\ndata = db.Student\ndata_user = db.Logged\n\n# title function\ndef lowercase_match_group(matchobj):\n return matchobj.group().lower()\n\ndef title_extended(title):\n if title is not None:\n # Take advantage of title(), we'll fix the apostrophe issue afterwards\n title = title.title()\n\n # Special handling for contractions\n poss_regex = r\"(?<=[a-z])[\\']([A-Z])\"\n title = re.sub(poss_regex, lowercase_match_group, title)\n\n return title\n\ndef title_one_liner(title):\n return re.sub(r\"(?<=[a-z])[\\']([A-Z])\", lambda x: x.group().lower(), title.title())\n\n\n#django views\n\n\ndef login(request):\n if not session.get('logged_in'):\n return render(request , 'login/login.html')\n else:\n if session.get('type') == 'admin':\n return render(request , 'login/index.html')\n else:\n return render(request , 'login/login_user.html')\n\ndef auth(request):\n username = request.POST.get(\"username\")\n password = request.POST.get(\"password\")\n if (username == \"admin\" and password == \"123456\"):\n session['logged_in'] = True\n session['username'] = username\n session['password'] = password\n session['type'] = 'admin'\n created_time = datetime.now()\n log =[]\n x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR')\n if x_forwarded_for:\n ip = x_forwarded_for.split(',')[0]\n else:\n ip = request.META.get('REMOTE_ADDR')\n user = {'User': username , 'Type':'admin' , 'Login_Time' : created_time ,'Ip_address' : ip , 'Logout_time' : '' , 'Action' : []}\n _id = data_user.insert_one(user)\n session['ID'] = str(_id.inserted_id)\n return render(request , 'login/index.html')\n elif(username != 'admin'):\n session['logged_in'] = True\n session['username'] = username\n session['type'] = 'normal'\n created_time = datetime.now()\n log = []\n x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR')\n if x_forwarded_for:\n ip = x_forwarded_for.split(',')[0]\n else:\n ip = request.META.get('REMOTE_ADDR')\n user = {'User': username , 'Type':'Normal' , 'Login_Time' : created_time , 'Ip_address' : ip, 'Logout_time' : '' , 'Action' : []}\n _id = data_user.insert_one(user)\n session['ID'] = str(_id.inserted_id)\n return render(request ,'login/login_user.html', {'value' : session['username']} )\n else:\n return render(request , 'login/login.html')\n\ndef logout(request):\n if 'logged_in' in session:\n u = session['username']\n i = session['ID']\n print(i)\n lout = datetime.now()\n data_user.find_one_and_update({'_id':ObjectId(i)},{'$set':{'Logout_time':lout}})\n session.pop('username')\n del log[:]\n session['logged_in'] = False\n return HttpResponseRedirect(reverse('login'))\n else:\n return HttpResponseRedirect(reverse('login'))\n\ndef back(request):\n if (session['username'] == 'admin' and session['password'] == '123456'):\n return render(request , 'login/index.html')\n else:\n return render(request , 'login/login_user.html')\n\ndef index(request):\n if request.method == 'GET':\n if request.POST.get('submit') == 'all_students':\n return HttpResponseRedirect(reverse('all_students'))\n elif request.POST.get('submit') == 'particular':\n return HttpResponseRedirect(reverse('particular'))\n elif request.POST.get('submit') == 'new_student':\n return HttpResponseRedirect(reverse('new_student'))\n elif request.POST.get('submit') == 'logout':\n return HttpResponseRedirect(reverse('logout'))\n\ndef all_students(request):\n if 'logged_in' in session:\n if session['logged_in'] == True:\n sdata_c = data.find({} , {'_id' : False})\n sdata = list(sdata_c)\n #sdata = json2html.convert(json = sdata)\n log='searched all students at ' + str(datetime.now())\n i = session['ID']\n lout = datetime.now()\n data_user.find_one_and_update({'_id':ObjectId(i)},{'$push':{'Action':log}})\n data_user.find_one_and_update({'_id':ObjectId(i)},{'$set':{'Logout_time':lout}})\n return render(request , 'login/all_students.html' , {'task_json' : sdata})\n else:\n return HttpResponseRedirect(reverse('login'))\n else:\n return HttpResponseRedirect(reverse('login'))\n\ndef part2(request):\n if 'logged_in' in session:\n if session['logged_in'] == True:\n return render(request , 'login/particular.html')\n else:\n return HttpResponseRedirect(reverse('login'))\n else:\n return HttpResponseRedirect(reverse('login'))\n\n\n\ndef particular(request):\n if request.POST.get(\"submit\") == 'logout':\n return HttpResponseRedirect(reverse('logout'))\n else:\n sname = request.POST.get(\"NAME\")\n sname = title_extended(sname)\n srollno = request.POST.get(\"ROLLNO\")\n sclass = request.POST.get(\"CLASS\")\n ssection = request.POST.get(\"SECTION\")\n query = {}\n if sname != \"\":\n query['NAME'] = sname\n if srollno != \"\":\n query['ROLLNO'] = srollno\n if sclass != \"\":\n query['class'] = sclass\n if ssection != \"\":\n query['Section'] = ssection\n log = 'searched ' + str(query) + ' at ' + str(datetime.now())\n i = session['ID']\n lout = datetime.now()\n data_user.find_one_and_update({'_id':ObjectId(i)},{'$push':{'Action':log}})\n data_user.find_one_and_update({'_id':ObjectId(i)},{'$set':{'Logout_time':lout}})\n sdata_c = data.find(query , {'_id' : False})\n if (sdata_c.count() != 0):\n sdata = list(sdata_c)\n return render(request , 'login/one_student.html' , {'name':sname,'task_json' : sdata})\n else:\n return render(request ,'login/does_not_exist.html' , {'name':sname})\n return\n\n\ndef part3(request):\n if 'logged_in'in session:\n if session['logged_in'] == True:\n if session.get('type') == 'admin':\n return render(request , 'login/new_student.html')\n else:\n return render(request , 'login/not_allowed.html')\n else:\n return HttpResponseRedirect(reverse('login'))\n else:\n return HttpResponseRedirect(reverse('login'))\n\n\ndef new_student(request):\n if request.POST.get(\"submit\") == 'logout':\n return HttpResponseRedirect(reverse('logout'))\n else:\n sname = request.POST.get(\"NAME\")\n sname = title_extended(sname)\n srollno = request.POST.get(\"ROLLNO\")\n sclass = request.POST.get(\"class\")\n ssection = request.POST.get(\"Section\")\n vali = data.find({'class' : sclass , 'ROLLNO' : srollno , 'Section' : ssection})\n if (vali.count() == 0):\n data2 = {}\n data2['NAME'] = sname\n data2['ROLLNO'] = srollno\n data2['class'] = sclass\n data2['Section'] = ssection\n op = data.insert_one(data2)\n op = str(op.inserted_id)\n sname = title_extended(sname)\n log = 'added ' + sname + ' to the database ' + ' at ' + str(datetime.now())\n i = session['ID']\n lout = datetime.now()\n data_user.find_one_and_update({'_id':ObjectId(i)},{'$push':{'Action':log}})\n data_user.find_one_and_update({'_id':ObjectId(i)},{'$set':{'Logout_time':lout}})\n sdata_c = data.find({'_id':ObjectId(op)} , {'_id' : False})\n sdata = list(sdata_c)\n return render(request , 'login/added.html' , {'name' : sname , 'task_json' : sdata})\n else:\n query = {}\n query['ROLLNO'] = srollno\n query['class'] = sclass\n query['Section'] = ssection\n sdata_c = data.find(query , {'_id' : False})\n sdata = list(sdata_c)\n name = data.find_one({'class' : sclass , 'ROLLNO' : srollno , 'Section' : ssection} , {'_id' : False , 'ROLLNO' : False , 'class' : False , 'Section': False})\n return render(request , 'login/already_exist.html', {'name' : name['NAME'], 'task_json':sdata})\n","sub_path":"login/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":9056,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"39646821","text":"import numpy as np\r\nimport matplotlib.pyplot as plt\r\n\r\nimport torch\r\nfrom torch import nn\r\n\r\n# How many time-steps/data pts are in one batch of data\r\nseq_length = 20\r\n\r\n'''\r\nfirst example of test data.\r\n'''\r\n# generate evenly spaced data pts over specific interval\r\nstart = 0\r\nstop = np.pi\r\nnum = seq_length + 1\r\ntime_steps = np.linspace(start, stop, num)\r\ndata = np.sin((time_steps))\r\n# resizing to 21, 1\r\ndata.resize((seq_length + 1, 1))\r\n# x all but the last piece of data\r\nx = data[:-1]\r\n# all but the first piece\r\ny = data[1:]\r\n# plt.plot(time_steps[1:], x, 'r.', label='input, x')\r\n# plt.plot(time_steps[1:], y, 'b.', label='input, y')\r\n# plt.legend(loc='best')\r\n# plt.show()\r\n\r\n\r\nclass RNN(nn.Module):\r\n def __init__(self, input_size, output_size, hidden_dim, n_layers):\r\n super(RNN, self).__init__()\r\n self.hidden_dim = hidden_dim\r\n # defining the RNN parameters\r\n self.rnn = nn.RNN(input_size, hidden_dim, n_layers, batch_first=True)\r\n # setting up fully connected layers params\r\n self.fc = nn.Linear(hidden_dim, output_size)\r\n\r\n def forward(self, x, hidden):\r\n # hidden = (nlayers, batch_size, hidden_dim)\r\n # r_out (batch_size, time_step, hidden_size)\r\n r_out, hidden = self.rnn(x, hidden)\r\n r_out = r_out.view(-1, self.hidden_dim)\r\n output = self.fc(r_out)\r\n return output, hidden\r\n\r\n\r\ntest_rnn = RNN(input_size=1, output_size=1, hidden_dim=10, n_layers=2)\r\ntime_steps = np.linspace(0, np.pi, seq_length)\r\ndata = np.sin(time_steps)\r\ndata.resize((seq_length, 1))\r\ntest__input = torch.Tensor(data).unsqueeze(0)\r\nprint('Input size: {}'.format(test__input.size()))\r\ntest_out, test_h = test_rnn(test__input, None)\r\nprint('Output size:', test_out.size())\r\nprint('Hidden state size:', test_h.size())\r\n\r\ninput_size = 1\r\noutput_size = 1\r\nhidden_dim = 32\r\nn_layers = 2\r\nrnn = RNN(input_size, output_size, hidden_dim, n_layers)\r\n# because it's coordinate values use Mean squared Error\r\ncriterion = nn.MSELoss()\r\n# For RNN the optimizer is Adam by default.\r\noptimizer = torch.optim.Adam(rnn.parameters(), lr=0.01)\r\n\r\n\r\ndef train(rnn, n_steps, print_every):\r\n # initializing the hidden state\r\n hidden = None\r\n for batch_i, step, in enumerate(range(n_steps)):\r\n # creating the training data\r\n time_steps = np.linspace(step * np.pi, (step+1)*np.pi, seq_length+1)\r\n data = np.sin((time_steps))\r\n data.resize(seq_length+1, 1)\r\n x = data[:-1]\r\n y = data[1:]\r\n # convert to torch tensors\r\n x_tensor = torch.Tensor(x).unsqueeze(0)\r\n y_tensor = torch.Tensor(y)\r\n # getting out predicted output\r\n prediction, hidden = rnn(x_tensor, hidden)\r\n hidden = hidden.data\r\n loss = criterion(prediction, y_tensor)\r\n optimizer.zero_grad()\r\n loss.backward()\r\n optimizer.step()\r\n if batch_i % print_every == 0:\r\n print('loss:', loss.item())\r\n plt.plot(time_steps[1:], x, 'r.')\r\n plt.plot(time_steps[1:], prediction.data.numpy().flatten(), 'b.')\r\n plt.show()\r\n return rnn\r\n\r\n# initialize the number of steps to be taken.\r\nn_steps = 300\r\nprint_every = 100\r\ntrain_rnn = train(rnn, n_steps, print_every)\r\n","sub_path":"time_series.py","file_name":"time_series.py","file_ext":"py","file_size_in_byte":3219,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"560681271","text":"import os\nimport logging\nfrom dotenv import load_dotenv\nfrom aiogram import Bot, Dispatcher, executor, types\nimport MainMenu\nimport db\n\nload_dotenv()\n\nAPI_TOKEN = os.getenv('TELEGRAM_TOKEN')\n\n# Configure logging\nlogging.basicConfig(level=logging.INFO)\n\n# Initialize bot and dispatcher\nbot = Bot(token=API_TOKEN)\ndp = Dispatcher(bot)\n\n\n@dp.message_handler(commands=['start'])\nasync def send_welcome(message: types.Message):\n await bot.send_message(message.from_user.id, \"Привіт✋✋✋\\nЯ тестовий телеграм бот\\nНажимай на кнопки\", reply_markup=MainMenu.r_markup)\n\n@dp.message_handler(commands=['about'])\nasync def send_welcome(message: types.Message):\n await bot.send_message(message.from_user.id, \"Це мій перший телеграм бот\\nНе суди строго 🙏🙏🙏\\nCreate by _Shvets Yevhen_\", parse_mode=\"Markdown\")\n\n\n@dp.message_handler(content_types=['text'])\nasync def mm(message: types.Message):\n if message.text == \"Товари📦\":\n for t in db.data:\n await bot.send_message(message.from_user.id, db.output(t), parse_mode=\"Markdown\")\n elif message.text == \"Категорії🔡\":\n for c in db.get_categories():\n keyboard = types.InlineKeyboardMarkup()\n callback_button = types.InlineKeyboardButton(text=\"Вибрати👆\", callback_data=c[0])\n keyboard.add(callback_button)\n await bot.send_message(message.chat.id, \"*{c}*\".format(c=str(c[1])), reply_markup=keyboard, parse_mode=\"Markdown\")\n\n\n@dp.callback_query_handler(lambda c: True)\nasync def process_callback(callback_query: types.CallbackQuery):\n if callback_query.id:\n for id, name in db.get_categories():\n if callback_query.data == str(id):\n await bot.send_message(callback_query.message.chat.id, f\"`Категорія:` *{callback_query.message.text}*\\n`Товари:`\", parse_mode=\"Markdown\")\n for t in db.get_tovar(id):\n await bot.send_message(callback_query.message.chat.id, db.output(t), parse_mode=\"Markdown\")\n\nif __name__ == '__main__':\n executor.start_polling(dp, skip_updates=True)","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2179,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"203624922","text":"from django.contrib.auth.decorators import login_required\nfrom django.shortcuts import render, Http404, HttpResponseRedirect\n\nfrom comments.forms import CommentForm\nfrom comments.models import Comment\n\nfrom .models import Video, Category, TaggedItem\n\n@login_required\ndef video_detail(request, cat_slug, vid_slug):\n obj = Video.objects.get(slug=vid_slug)\n comments = obj.comment_set.all()\n\n try:\n cat = Category.objects.get(slug=cat_slug)\n except:\n raise Http404\n\n try:\n comment_form = CommentForm(request.POST or None)\n\n if comment_form.is_valid():\n parent_id = request.POST.get('parent_id')\n parent_comment = None\n if parent_id is not None:\n try:\n parent_comment = Comment.objects.get(id=parent_id)\n except:\n parent_comment = None\n\n comment_text = comment_form.cleaned_data['comment']\n new_comment = Comment.objects.create_comment(user=request.user, path=request.get_full_path(), text=comment_text, video=obj, parent=parent_comment)\n return HttpResponseRedirect(obj.get_absolute_url())\n\n template = \"videos/video_detail.html\"\n context = {\n \"obj\": obj,\n \"comments\" : comments,\n \"comment_form\" : comment_form\n }\n\n return render(request, template, context)\n except:\n raise Http404\n\n\ndef category_list(request):\n queryset = Category.objects.all()\n\n template = \"videos/category_list.html\"\n context = {\n \"queryset\" : queryset,\n }\n\n return render(request, template, context)\n\n@login_required\ndef category_detail(request, cat_slug):\n try:\n obj = Category.objects.get(slug=cat_slug)\n queryset = obj.video_set.all()\n\n template = \"videos/video_list.html\"\n context = {\n \"obj\" : obj,\n \"queryset\" : queryset\n }\n\n return render(request, template, context)\n except:\n raise Http404","sub_path":"videos/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2012,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"262176408","text":"# ShipListSubMenu Addition V2.\n# This modification of the Foundation allows you to get a submenu in the race list (ie Federation Ships -> Galaxy Class)\n# This modification is by MLeoDaalder\n\nimport App\nimport Foundation\n#import types # Not everyone has the types module, fake it...\n\nListType = type([])\nStringType = type(\"a\")\nDictType = type({})\n\n\nclass TreeNode:\n\tdef __init__(self, name, oShip=None, prefab = None):\n\t\tself.name = name\n\t\tself.oShip = oShip\n\t\tself.prefab = prefab\n\t\tself.children = {}\n\t\tself.bMVAM = 0\n\t\tself.bShip = 0\n\nif int(Foundation.version[0:8]) < 20040628:\n\timport FoundationMenu\n\n\tclass ShipMenuBuilderDef(FoundationMenu.MenuBuilderDef):\n\t\tdef __init__(self, tglDatabase):\n\t\t\tFoundationMenu.MenuBuilderDef.__init__(self, tglDatabase)\n\n\t\tdef __call__(self, raceShipList, menu, buttonType, uiHandler, fWidth = 0.0, fHeight = 0.0):\n\t\t\tfoundShips = {}\n\t\t\tfor race in raceShipList.keys():\n\t\t\t\tfor ship in raceShipList[race][0]:\n\t\t\t\t\tfoundShips[race] = 1\n\t\t\t\t\tbreak\n\n\t\t\traceList = foundShips.keys()\n\t\t\traceList.sort()\n\n\t\t\toRoot = TreeNode(\"Root\", prefab = menu)\n\t\t\tfor race in raceList:\n\n\t\t\t\tself.textButton(race)\n\t\t\t\tpRaceButton = self.textButton.MakeSubMenu()\n\t\t\t\toRace = TreeNode(race, prefab = pRaceButton)\n\t\t\t\toRoot.children[race] = oRace\n\n\t\t\t\tshipList = raceShipList[race][1].keys()\n\t\t\t\tshipList.sort()\n\n\t\t\t\tfor key in shipList:\n\t\t\t\t\tship = raceShipList[race][1][key]\n\t\t\t\t\tself.textButton(ship.name)\n\n\t\t\t\t\tif ship.__dict__.get(\"Do not display\", 0):\n\t\t\t\t\t\tcontinue\n\n\t\t\t\t\tif hasattr(ship, \"SubMenu\") and type(ship.SubMenu) != ListType:\n\t\t\t\t\t\tship.SubMenu = [ship.SubMenu]\n\t\t\t\t\tif hasattr(ship, \"SubSubMenu\") and type(ship.SubSubMenu) != ListType:\n\t\t\t\t\t\tship.SubSubMenu = [ship.SubSubMenu]\n\n\t\t\t\t\toWork = oRace\n\n\t\t\t\t\tfor name in (ship.__dict__.get(\"SubMenu\", []) + ship.__dict__.get(\"SubSubMenu\", [])):\n\t\t\t\t\t\toMenu = oWork.children.get(name + \"_m\", None)\n\t\t\t\t\t\tif not oMenu:\n\t\t\t\t\t\t\toMenu = TreeNode(name, prefab = App.STCharacterMenu_Create(name))\n\t\t\t\t\t\t\toWork.children[name + \"_m\"] = oMenu\n\t\t\t\t\t\toWork = oMenu\n\t\t\t\t\tbCreated = 0\n\t\t\t\t\tif HasMVAM():\n\t\t\t\t\t\toWork, bCreated = DoMVAMMenus(oWork, ship, buttonType, uiHandler, self, raceShipList, fWidth, fHeight)\n\t\t\t\t\tif not bCreated:\n\t\t\t\t\t\tappended = \"\"\n\t\t\t\t\t\twhile oWork.children.has_key(ship.name + appended):\n\t\t\t\t\t\t\tappended = appended + \" \"\n\t\t\t\t\t\toWork.children[ship.name + appended] = TreeNode(ship.name, oShip = ship)\n\t\t\t\t\t\toWork.children[ship.name + appended].bShip = 1\n\n\t\t\tBuildMenu(oRoot, self, buttonType, uiHandler, fWidth, fHeight)\n\n\tFoundationMenu.ShipMenuBuilderDef = ShipMenuBuilderDef\n\tFoundation.version = \"20040628\"\n\n\tdef BuildMenu(oMenu, self, buttonType, uiHandler, fWidth, fHeight, b = 0):\n\t\titems = oMenu.children.items()\n\t\titems.sort()\n\t\tfor sort, object in items:\n\t\t\tself.textButton(object.name)\n\n\t\t\tif object.bShip or (object.bMVAM and not len(object.children)):\n\t\t\t\tif not object.prefab:\n\t\t\t\t\tobject.prefab = self.textButton.MakeIntButton(buttonType, object.oShip.num, uiHandler, fWidth, fHeight)\n\t\t\telse:\n\t\t\t\tif len(object.children):\n\t\t\t\t\tif not object.prefab:\n\t\t\t\t\t\tobject.prefab = self.textButton.MakeSubMenu()\n\t\t\t\t\tif object.name == \"Human (Tau'ri) Ships\":\n\t\t\t\t\t\tBuildMenu(object, self, buttonType, uiHandler, fWidth, fHeight, 1)\n\t\t\t\t\telse:\n\t\t\t\t\t\tBuildMenu(object, self, buttonType, uiHandler, fWidth, fHeight)\n\n\t\t\t\t\tif object.bMVAM:\n\t\t\t\t\t\tobject.prefab.SetTwoClicks()\n\t\t\t\t\t\tpEvent = App.TGIntEvent_Create()\n\t\t\t\t\t\tpEvent.SetEventType(buttonType)\n\t\t\t\t\t\tpEvent.SetDestination(uiHandler)\n\t\t\t\t\t\tpEvent.SetSource(object.prefab)\n\t\t\t\t\t\tpEvent.SetInt(object.oShip.num)\n\t\t\t\t\t\tobject.prefab.SetActivationEvent(pEvent)\n\n\t\t\toMenu.prefab.AddChild(object.prefab)\n\tbHasMVAM = -1\n\tdef HasMVAM():\n\t\tglobal bHasMVAM\n\t\tif bHasMVAM != -1:\treturn bHasMVAM\n\t\ttry:\timport Custom.Autoload.Mvam\n\t\texcept:\tbHasMVAM = 0\n\t\telse:\tbHasMVAM = 1\n\t\treturn bHasMVAM\n\n\tdef DoMVAMMenus(oWork, ship, buttonType, uiHandler, self, raceShipList, fWidth, fHeight):\n\t\tif not ship.__dict__.get(\"bMvamMenu\", 1):\n\t\t\treturn oWork, 0\n\n\t\timport nt\n\t\timport string\n\n\t\tList = nt.listdir(\"scripts\\\\Custom\\\\Autoload\\\\Mvam\\\\\")\n\t\tMod = None\n\t\tfor i in List:\n\t\t\tPosModName = string.split(i, \".\")\n\t\t\tif len(PosModName) > 1 and PosModName[0] != \"__init__\":\n\t\t\t\ttry:\n\t\t\t\t\tPosMod = __import__(\"Custom.Autoload.Mvam.\" + PosModName[0])\n\t\t\t\t\tif PosMod and PosMod.__dict__.has_key(\"MvamShips\"):\n\t\t\t\t\t\tif ship.shipFile in PosMod.MvamShips:\n\t\t\t\t\t\t\tMod = PosMod\n\t\t\t\t\t\t\tbreak\n\t\t\t\texcept:\n\t\t\t\t\tcontinue\n\n\t\tif not Mod:\n\t\t\treturn oWork, 0\n\n\t\tshipB = None\n\t\tfoundShips = {}\n\t\tfor race in raceShipList.keys():\n\t\t\tfor dummyShip in raceShipList[race][0]:\n\t\t\t\tfoundShips[race] = 1\n\t\t\t\tbreak\n\n\t\traceList = foundShips.keys()\n\t\traceList.sort()\n\n\t\tfor race in raceList:\n\t\t\tshipB = findShip(Mod.MvamShips[0], raceShipList[race][1])\n\t\t\tif shipB:\n\t\t\t\tbreak\n\t\tif not shipB:\n\t\t\treturn oWork, 0\n\n\t\tif not shipB.__dict__.get(\"bMvamMenu\", 1):\n\t\t\treturn oWork, 0\n\n\t\toTemp = oWork.children.get(shipB.name, None)\n\t\tif not oTemp:\n\t\t\toTemp = TreeNode(shipB.name, oShip = shipB)\n\t\t\toTemp.bMVAM = 1\n\t\t\toWork.children[shipB.name] = oTemp\n\t\toWork = oTemp\n\t\treturn oWork, ship.shipFile == shipB.shipFile\n\n\tdef findShip(shipFile, raceShipList):\n\t\tshipList = raceShipList.keys()\n\t\tshipList.sort()\n\t\tfor key in shipList:\n\t\t\tship = raceShipList[key]\n\t\t\tif ship.shipFile == shipFile:\n\t\t\t\treturn ship\n\n","sub_path":"scripts/Custom/Autoload/000-Fixes20040628-ShipSubListV3_7Foundation.py","file_name":"000-Fixes20040628-ShipSubListV3_7Foundation.py","file_ext":"py","file_size_in_byte":5295,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"307378480","text":"# Body Mass Index\n# Write a program that calculates and displays a person’s body mass index (BMI). The BMI is\n# often used to determine whether a person is overweight or underweight for his or her height. A\n# person’s BMI is calculated with the following formula:\n# BMI=weight×703/height2\n# where weight is measured in pounds and height is measured in inches. The program should ask\n# the user to enter his or her weight and height, then display the user’s BMI. The program should\n# also display a message indicating whether the person has optimal weight, is underweight, or is\n# overweight. A person’s weight is considered to be optimal if his or her BMI is between 18.5 and\n# 25. If the BMI is less than 18.5, the person is considered to be underweight. If the BMI value is\n# greater than 25, the person is considered to be overweight.\n\nheight = int(input('What is your height in inches?'))\nweight = int(input('What is your weight in pounds?'))\n\nbmi = ((weight * 703) / (height**2))\n\nif bmi > 25:\n print(\"Your BMI\", bmi, \"is considered overweight.\")\nelif bmi < 18.5:\n print(\"Your BMI\", bmi, \"is considered underweight.\")\nelse:\n print(\"Your BMI\", bmi, \"is optimal.\")\n","sub_path":"Chapter 3/bmi.py","file_name":"bmi.py","file_ext":"py","file_size_in_byte":1186,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"93035708","text":"# Parameters:\n# nt, r , k\n# initial amount of food available\n# initial amount of power available\n\nn_t = 20.0 # could be selected randomly\nr = 2.8 # could be selected randomly\nk = 500 # could be selected randomly\n\ndata = []\n\nfor i in xrange(100):\n n_tplus1 = (r * (1-(n_t/k)) * n_t)\n n_t = n_tplus1\n data.append(n_t)\n\nplt.plot(data)\nplt.show()\n\n\n# In[2]:\n\nperson = Person(2, 42, 'm')\nperson2 = Person(6, 400, 'f')\nsim_time = 100\n\nprint(person.kcal_requirements(sim_time))\nprint(person2.kcal_requirements(sim_time))\n\npopulation = Population([person, person2], 4.0)\nprint(population.kcal_requirements(sim_time))\n\n\n# In[3]:\n\nfacility = Facility(20000, 20)\n\n\n# In[9]:\n\nperson = Person(2, 42, 'm')\nperson2 = Person(6, 400, 'f')\nsim_time = 100\npopulation = Population([person, person2], 4.0)\nfood = Food(facility, population, sim_time)\nsim_time += 1\nfood.calculate_food_production(sim_time)","sub_path":"code/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":892,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"415113801","text":"from django.urls import re_path\n\nfrom .views import LoginView,RegisterView,ActiveUserView,ForgetpwdView,ResetpwdView\nurlpatterns = [\n re_path('login/',LoginView.as_view(), name='login'),\n re_path('register/',RegisterView.as_view(), name='register'),\n re_path('active/(?P.*)/$',ActiveUserView.as_view(), name='active'),\n re_path('forgetpwd/$',ForgetpwdView.as_view(), name='forgetpwd'),\n re_path('resetpwd/(?P.*)/$',ResetpwdView.as_view(), name='resetpwd'),\n]\n","sub_path":"mydjango/apps/users/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":499,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"367004730","text":"# This practice is to start implementing relationships between \n# classes/types.\n\nclass Employee:\n def __init__(self, fullname, jobtitle, startdate):\n self.name = fullname\n self.job_title = jobtitle\n self.start_date = startdate\n\nclass Company:\n def __init__(self, bizname, address, industry):\n self.business_name = bizname\n self.address = address\n self.industry_type = industry\n self.employees = list()\n\n def list_employees(self):\n for employee in self.employees:\n print(f\"{employee.name} is an employee of {self.business_name}\")\n\nglobal_financial = Company(\"Global Financial\", \"132 Capital Way\", \"Banking\")\nhighpoint_medical = Company(\"Highpoint Medical\", \"400 Freedom Blvd\", \"Healthcare\")\n\njack = Employee(\"Jack Ma\", \"CEO\", \"11/01/01\")\nglobal_financial.employees.append(jack)\n\n\nbrady = Employee(\"Brady Green\", \"Banker\", \"10/20/19\")\nglobal_financial.employees.append(brady)\n\nsamantha = Employee(\"Samantha Sue\", \"Nurse\", \"05/14/15\")\nhighpoint_medical.employees.append(samantha)\n\nandrea = Employee(\"Andrea Barlowe\", \"Nurse\", \"07/17/17\")\nhighpoint_medical.employees.append(andrea)\n\nscott = Employee(\"Scott Branford\", \"Doctor\", \"01/20/18\")\nhighpoint_medical.employees.append(scott)\n\n# Ideally they want me to print a list of employees to terminal from an f-string... \nglobal_financial.list_employees()\nhighpoint_medical.list_employees()","sub_path":"classes/employees_departments.py","file_name":"employees_departments.py","file_ext":"py","file_size_in_byte":1409,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"124294352","text":"#--coding:utf-8--\r\n\r\nimport os\r\nfrom enum import Enum\r\nimport numpy as np\r\nfrom hashlib import md5\r\nimport re\r\n# from GlobalVariables import *\r\n\r\n# columns of line\r\nwindowSize = 10\r\n# log cluster:1 or sequencer:0\r\npattern_source = 1\r\n\r\n# relation between log_pattern log_key log_line\r\npattern2log = []\r\npattern_dic = {}\r\n\r\n# log input/output address\r\n\r\nRootPath='../k8s/LogClusterResult-k8s/'\r\nlog_file_dir = '../k8s/'\r\nlog_file_name = 'union.log'\r\nlog_time_file = RootPath+'Vectors/timediff.txt'\r\nlog_address = log_file_dir + log_file_name\r\nlog_pattern_address_sequencer = './sequence/linux.pat'\r\nlog_pattern_folder_cluster = RootPath+'clusters/'\r\nsequencer_out_file = '../Data/Vectors1'+log_file_name.split('.')[0]+'_LogKeys_sequencer'\r\nlog_cluster_out_file = '../Data/Vectors1/'+log_file_name.split('.')[0]+'_LogKeys_logcluster'\r\nlog_value_folder = RootPath+'values/'\r\nif pattern_source == 0:\r\n out_file = sequencer_out_file\r\nelse:\r\n out_file = log_cluster_out_file\r\n\r\n\r\n# 继承枚举类\r\nclass LineNumber(Enum):\r\n PATTERN_LINE = 0\r\n NUMBERS_LINE = 3\r\n\r\n\r\ndef parse_sequencer():\r\n if_first = True\r\n with open(log_pattern_address_sequencer, 'rb') as in_text:\r\n log_set = set()\r\n pattern_key = 0\r\n last_pattern = ''\r\n for line in in_text.readlines():\r\n if (not line.startswith('#'.encode(encoding='utf-8'))) and len(line.strip()):\r\n if line.startswith('%msgtime%'.encode(encoding='utf-8')):\r\n if if_first:\r\n last_pattern = line\r\n if_first = False\r\n continue\r\n pattern2log.append(log_set)\r\n pattern_dic[pattern_key] = last_pattern\r\n pattern_key = pattern_key + 1\r\n log_set = set()\r\n last_pattern = line\r\n else:\r\n line = line.decode(encoding='utf-8', errors='strict').strip()\r\n lineNumbers = line.split(' ')\r\n lineNumbers = [int(x) for x in lineNumbers]\r\n for x in lineNumbers:\r\n log_set.add(x)\r\n pattern2log.append(log_set)\r\n pattern_dic[pattern_key] = last_pattern\r\n\r\n\r\ndef parse_log_cluster():\r\n file_names = os.listdir(log_pattern_folder_cluster)\r\n pattern_key = 0\r\n for i in range(len(file_names)):\r\n with open(log_pattern_folder_cluster + file_names[i], 'r') as in_text:\r\n num_of_line = 0\r\n pattern = ''\r\n log_set = set()\r\n for line in in_text.readlines():\r\n if num_of_line == LineNumber.PATTERN_LINE.value:\r\n pattern = line\r\n num_of_line = num_of_line + 1\r\n elif num_of_line == LineNumber.NUMBERS_LINE.value:\r\n lineNumbers = line.strip().split(' ')\r\n lineNumbers = [int(x) for x in lineNumbers]\r\n for x in lineNumbers:\r\n log_set.add(x)\r\n pattern2log.append(log_set)\r\n pattern_dic[pattern_key] = pattern\r\n pattern_key = pattern_key + 1\r\n else:\r\n num_of_line = num_of_line + 1\r\n\r\n'''\r\n提取value函数\r\n参数tool表示使用的工具 0为sequence 1为logcluster\r\n输出到特定文件\r\n'''\r\ndef valueExtract(pattern, log, tool=0, timestamp=None):\r\n start_char = \"%\"\r\n if tool == 1:\r\n start_char = \"*\"\r\n pattern_arr = pattern.split()\r\n # pattern 写入\r\n if tool == 0 and not os.path.exists(md5(pattern.encode(\"utf-8\")).hexdigest()+\".txt\"):\r\n temp = []\r\n for pattern_str in pattern_arr:\r\n if pattern_str[0] == start_char and pattern_str[-1] == start_char:\r\n temp.append(pattern_str)\r\n with open(\"Data/Vectors2/\"+md5(pattern.encode(\"utf-8\")).hexdigest()+\".txt\", \"a\") as f:\r\n f.write(\", \".join(temp) + \"\\n\")\r\n # 对于单个日志\r\n # log_value = [last_timestamp]\r\n log_value = []\r\n if timestamp != None:\r\n log_value.append(timestamp)\r\n log_arr = log.split()\r\n log_index = 0\r\n cur_log_str = log_arr[log_index]\r\n last_is_pattern = False\r\n # 遍历模式字符串进行匹配\r\n for pattern_str in pattern_arr :\r\n # 如果是value\r\n # print(pattern_str, cur_log_str)\r\n if pattern_str[0] == start_char :\r\n # if pattern_str[0] == start_char and pattern_str[-1] == start_char:\r\n if pattern_str[1:-1] == \"msgtime\":\r\n cur_log_str += (\" \" + log_arr[log_index+1] + \" \" + log_arr[log_index+2])\r\n log_index += 2\r\n last_timestamp = cur_log_str\r\n elif pattern_str[1:-1] == \"time\":\r\n # time 共有4中情况 目前只能一一判断...\r\n if (cur_log_str.find(\"-\") == -1 and cur_log_str.find(\":\") == -1):\r\n log_index_add = 0\r\n if (log_arr[log_index + 2].find(\":\") != -1):\r\n log_index_add = 2\r\n elif (log_arr[log_index + 4].lower() == \"est\"):\r\n log_index_add = 5\r\n else:\r\n log_index_add = 4\r\n for i in range(1, log_index_add + 1):\r\n cur_log_str += (\" \" + log_arr[log_index + i])\r\n log_index += log_index_add\r\n log_len = 1\r\n if (tool == 1):\r\n log_len = int(pattern_str[2:pattern_str.find(',')])\r\n for i in range(1, log_len):\r\n cur_log_str += (\" \" + log_arr[log_index+i])\r\n log_value.append(cur_log_str)\r\n log_index += log_len\r\n if (log_index < len(log_arr)):\r\n cur_log_str = log_arr[log_index]\r\n last_is_pattern = True\r\n # 如果是匹配的单词\r\n elif tool == 1 and pattern_str[0] == '(':\r\n log_value.append(cur_log_str)\r\n log_index += 1\r\n if (log_index < len(log_arr)):\r\n cur_log_str = log_arr[log_index]\r\n elif cur_log_str.lower() == pattern_str.lower():\r\n log_index += 1\r\n if (log_index < len(log_arr)):\r\n cur_log_str = log_arr[log_index]\r\n last_is_pattern = False\r\n # 如果是单词前一部分匹配\r\n elif len(cur_log_str) >= len(pattern_str) and cur_log_str.lower()[0:len(pattern_str)] == pattern_str.lower():\r\n cur_log_str = cur_log_str[len(pattern_str):]\r\n last_is_pattern = False\r\n # 此时在前一个字符串中, 如果前一个字符串是value则需要重新取值\r\n elif last_is_pattern:\r\n log_index -= 1\r\n cur_log_str = log_value.pop()\r\n index = cur_log_str.find(pattern_str)\r\n log_value.append(cur_log_str[0:index])\r\n if index+len(pattern_str) == len(cur_log_str):\r\n log_index += 1\r\n if (log_index < len(log_arr)):\r\n cur_log_str = log_arr[log_index]\r\n else:\r\n cur_log_str = cur_log_str[index+len(pattern_str):]\r\n lines = [\", \".join(log_value) + \"\\n\"]\r\n with open(\"Data/Vectors1/\"+md5(pattern.encode(\"utf-8\")).hexdigest()+\".txt\", \"a+\") as f:\r\n f.writelines(lines)\r\n return log_value\r\n\r\nlast_timestamp = \"xxx\"\r\ndef timeExtract(file=None):\r\n global last_timestamp\r\n if file == None:\r\n print(\"No file input\")\r\n return\r\n times = []\r\n with open (log_file_dir + log_file_name) as f:\r\n for line in f:\r\n if len(line) > 22:\r\n times.append(str(timeDiff(line[14:22], last_timestamp)) + \"\\n\")\r\n last_timestamp = line[14:22]\r\n else:\r\n times.append(\"0\\n\")\r\n with open (log_time_file , \"w\") as f:\r\n f.writelines(times)\r\n\r\n# 时间差\r\n# 暂时使用时分秒做��法\r\n# month_str_num = {\"Jan\":1, \"Feb\":2, \"Mar\":3, \"Apr\":4, \"May\":5, \"Jun\":6,\r\n# \"Jul\":7, \"Aug\":8, \"Sep\":9, \"Oct\":10, \"Nov\":11, \"Dec\":12}\r\ndef timeDiff(t1, t2):\r\n if (t2 == \"xxx\"):\r\n return 0\r\n t1_hms_arr = t1.split(\":\")\r\n t2_hms_arr = t2.split(\":\")\r\n diff_hour = int(t1_hms_arr[0]) - int(t2_hms_arr[0])\r\n if (diff_hour == -23):\r\n diff_hour = 1\r\n diff_min = int(t1_hms_arr[1]) - int(t2_hms_arr[1])\r\n diff_sec = int(t1_hms_arr[2]) - int(t2_hms_arr[2])\r\n diff = diff_hour*3600 + diff_min*60 + diff_sec\r\n return diff\r\n\r\n# 向量化\r\n# 改成了对文件向量化\r\ndef toVector(pattern, tool=0, file=None):\r\n # 读取文件内容\r\n values = []\r\n with open(\"Data/Vectors1/\"+md5(pattern.encode(\"utf-8\")).hexdigest()+\".txt\",\"r\") as f:\r\n for line in f.readlines():\r\n line = line.strip('\\n')\r\n values.append(line.split(\", \"))\r\n new_values = []\r\n if (tool == 0):\r\n names = values[0]\r\n for i in range(1, len(values)):\r\n value = values[i]\r\n new_value = [timeDiff(value[1], value[0])]\r\n for j in range(len(names)):\r\n if (names[j] == \"%integer%\" or names[j] == \"%float%\"):\r\n new_value.append(value[j+1])\r\n new_values.append(new_value)\r\n else:\r\n ##------ Start of 新增-------------\r\n if len(values) <= 0:\r\n print(\"no values\")\r\n return \r\n val_num = len(values[0])\r\n isAlldigit = [1]*val_num\r\n for i in range(val_num):\r\n for value in values:\r\n val = value[i]\r\n if (val.isdigit() or (val[0] == \"-\" and val[1:].isdigit()) \r\n or re.match(r\"-?[0-9]+\\.[0-9]+$\", val)):\r\n #do nothing\r\n pass\r\n else:\r\n isAlldigit[i] = 0\r\n ##------ End of 新增-------------\r\n\r\n for value in values:\r\n new_value = []\r\n index=0\r\n for val in value:\r\n if isAlldigit[index]:\r\n if (val.isdigit() or (val[0] == \"-\" and val[1:].isdigit()) \r\n or re.match(r\"-?[0-9]+\\.[0-9]+$\", val)):\r\n new_value.append(val)\r\n index+=1\r\n new_values.append(new_value)\r\n \r\n # Normalize\r\n # print(new_values)\r\n new_values = np.array(new_values, dtype=float)\r\n new_values -= np.mean(new_values, axis=0)\r\n # print(new_values)\r\n std = np.std(new_values, axis=0)\r\n # print(std)\r\n std[std == 0.0] = 1.0\r\n new_values /= std\r\n lines = []\r\n for val in new_values:\r\n line = str(val[0])\r\n for i in range(1, len(val)):\r\n line += \", \" + str(val[i])\r\n lines.append(line + \"\\n\")\r\n if file == None:\r\n file = md5(pattern.encode(\"utf-8\")).hexdigest()+\"_vector.txt\"\r\n with open(file, \"w\") as f:\r\n f.writelines(lines)\r\n return new_values\r\n\r\n\r\nif __name__ == '__main__':\r\n if pattern_source == 0:\r\n parse_sequencer()\r\n else:\r\n parse_log_cluster()\r\n out_train=open(RootPath+\"logkey/logkey_train\",'w')\r\n out_test=open(RootPath+\"logkey/logkey_test\",'w')\r\n out_val=open(RootPath+\"logkey/logkey_val\",'w')\r\n out_abnormal=open(RootPath+\"logkey/logkey_abnormal\",'w')\r\n out_text=out_train\r\n with open(log_address, 'rb') as in_log:\r\n print(pattern2log[0])\r\n j = 0\r\n lineNum = 1\r\n for line in in_log.readlines():\r\n k=len(pattern2log)\r\n for i in range(len(pattern2log)):\r\n if lineNum in pattern2log[len(pattern2log)-1-i]:\r\n k=i\r\n break\r\n print(k+1, file=out_text, end='')\r\n print(' ', file=out_text, end='')\r\n j = j + 1\r\n # call method to get value (line, patten_dic[i])\r\n lineNum = lineNum + 1\r\n if lineNum>2000 and lineNum<2500:\r\n out_text=out_val\r\n if lineNum>2500 and lineNum<3000:\r\n out_text=out_test\r\n if lineNum>3000 and lineNum<3500:\r\n out_text=out_abnormal\r\n\r\n # #value extract\r\n # with open(log_file_dir + log_file_name) as o_log_file:\r\n # o_log_lines = o_log_file.readlines()\r\n # timeExtract( log_time_file)\r\n # for file in os.listdir(log_pattern_folder_cluster):\r\n # with open(log_pattern_folder_cluster + file) as f:\r\n # with open(log_time_file) as tf:\r\n # f_lines = f.readlines()\r\n # tf_lines = tf.readlines()\r\n # pattern = f_lines[0]\r\n # o_lines = f_lines[3].split()\r\n # for o_line in o_lines:\r\n # valueExtract(pattern, o_log_lines[int(o_line) - 1], 1, tf_lines[int(o_line) - 1].strip('\\n'))\r\n # toVector(pattern, 1, log_value_folder + file)\r\n # print(file + \" done\")\r\n outfile = './output.txt'\r\n with open(outfile, 'w') as file:\r\n file.write('2 100')","sub_path":"Backend/log_preprocessor.py","file_name":"log_preprocessor.py","file_ext":"py","file_size_in_byte":13007,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"334567100","text":"import sys\nsys.modules['FixTk'] = None\n\na = Analysis(['..\\\\leaguedirector\\\\app.py'],\n binaries = [],\n datas = [],\n hiddenimports = [],\n hookspath = [],\n runtime_hooks = [],\n excludes = ['FixTk', 'tcl', 'tk', '_tkinter', 'tkinter', 'Tkinter', 'lib2to3'],\n win_no_prefer_redirects = False,\n win_private_assemblies = False,\n cipher = None,\n noarchive = False\n)\npyz = PYZ(a.pure, a.zipped_data, cipher=None)\nexe = EXE(pyz, a.scripts, [],\n exclude_binaries = True,\n name = 'LeagueDirector',\n debug = False,\n bootloader_ignore_signals = False,\n strip = False,\n upx = True,\n console = False,\n icon = '..\\\\resources\\\\icon.ico'\n)\ncoll = COLLECT(exe, a.binaries, a.zipfiles, a.datas,\n strip = False,\n upx = True,\n name = 'LeagueDirector'\n)\n","sub_path":"build/build.spec","file_name":"build.spec","file_ext":"spec","file_size_in_byte":793,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"326704151","text":"from django.core.management.base import BaseCommand, CommandError\nfrom library.models import Book, Author\nfrom datetime import datetime\nclass Command(BaseCommand):\n help = 'Populates the Database'\n\n def handle(self, *args, **options):\n author1 = Author.objects.get_or_create(last_name='Tolkien', first_name='J.', middle1='R.', middle2='R.')[0]\n author2 = Author.objects.get_or_create(last_name='Machado', first_name='Carmen', middle1='Maria')[0]\n books = (\n ('The Lord of the Rings', datetime.strptime('29-07-1954','%d-%m-%Y'), author1),\n ('The Hobbit', datetime.strptime('21-09-1937', '%d-%m-%Y'), author1),\n ('In The Dream House', datetime.strptime('05-11-2019', '%d-%m-%Y'), author2),\n )\n for one_book in books:\n Book.objects.get_or_create(\n title = one_book[0],\n publish_date = one_book[1],\n author = one_book[2],\n )","sub_path":"Assignments/Eboni/django/lib_django/library/management/commands/populate.py","file_name":"populate.py","file_ext":"py","file_size_in_byte":1013,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"597699271","text":"import numpy as np\nfrom numpy.core.arrayprint import format_float_scientific\nimport pandas as pd\nfrom sklearn.model_selection import train_test_split\nimport matplotlib.pyplot as plt\nfrom sklearn import metrics\nfrom scipy import stats\n\nbase_dir = './generated_files/'\nmax_iter = 15000\nlr = .05\nprobability = .5\n\nclass KernelRegression():\n def __init__(self, lr=.01, probability=.5, use_beta=True):\n self.lr = lr\n self.probability = .5\n self.use_beta=use_beta\n \n def fit(self, X, y, p):\n self.X = X\n self.y = y\n self.p = p\n self.beta = 0\n self.weights = np.zeros(X.shape[1])\n self.wfile = np.zeros((max_iter, X.shape[1]))\n return self\n\n def train(self, max_iter=10000):\n X = self.X\n y = self.y\n lr = self.lr\n\n for iter in range(max_iter):\n kernels = self.kernel(X)\n z = kernels.dot(self.weights) + self.beta\n # predict\n y_hat = 1 / (1 + np.exp(- z))\n # Gradient descent\n self.weights -= lr * X.T.dot(y_hat - y) / len(X)\n if self.use_beta:\n self.beta -= lr * np.sum(y_hat - y) / len(X) * .5\n self.wfile[iter] = self.weights\n\n def predict(self, X_test, probs=False):\n # test\n kernels = self.kernel(X_test)\n # apply weights\n z = kernels.dot(self.weights) + self.beta\n # predict\n y_hats = 1 / (1 + np.exp(-z))\n\n if probs:\n return y_hats\n return [1 if i > self.probability else 0 for i in y_hats]\n\n def kernel(self, X):\n p = self.p\n kernel_values = np.zeros(X.shape)\n for i in range(X.shape[0]):\n row = X[i]\n value = [row[0]**p[0], row[1]**p[1], row[2]**p[2]]\n kernel_values[i] = value\n return kernel_values\n\n# preprocessing\ndata = pd.read_csv('./data/data.csv')\n# create train, test sets\nX = data[['radius_mean', 'texture_mean', 'symmetry_mean']].to_numpy()\ny = data['diagnosis'].to_numpy()\ny = [1 if i == 'M' else 0 for i in y]\nX_train, X_test, y_train, y_test = train_test_split(X, y, test_size=.25)\n\nnp.savetxt(base_dir + 'dataset.txt', X, delimiter=' ', fmt='%f')\nnp.savetxt(base_dir + 'target.txt', y, delimiter=' ', fmt='%f')\n\n# pearson's coefficients\np_vals = open(base_dir + \"p_vals.txt\", \"w\")\np0 = stats.pearsonr(X_train[:, 0], y_train)[0]\np1 = stats.pearsonr(X_train[:, 1], y_train)[0]\np2 = stats.pearsonr(X_train[:, 2], y_train)[0]\np_vals.write(str(p0) + ' ' + str(p1) + ' ' + str(p2))\n\n# Train\nmodel = KernelRegression(lr, probability)\nmodel.fit(X_train, y_train, [p0, p1, p2]).train(max_iter)\nnp.savetxt(base_dir + 'weights.txt', model.wfile, delimiter=' ', fmt='%f')\n\n# ROC\ny_probs = model.predict(X_test, probs=True)\nfpr, tpr, thresholds = metrics.roc_curve(y_test, y_probs)\nplt.xlabel(\"False Positives\")\nplt.ylabel(\"True Positives\")\nplt.plot(fpr, tpr)\nplt.show()\n\n# Performance\ny_pred = model.predict(X_test)\naccuracy = metrics.accuracy_score(y_test, y_pred)\nf1 = metrics.f1_score(y_test, y_pred)\nprint(\" - Kernel Regression\")\nprint(' - Accuracy:', np.round(accuracy, decimals=4))\nprint(' - F1:', np.round(f1, decimals=4))","sub_path":"Mehrab/kernel_regression.py","file_name":"kernel_regression.py","file_ext":"py","file_size_in_byte":3179,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"1127607","text":"#!/usr/bin/env python\n# encoding: utf-8\nimport json\nimport npyscreen\nimport sys\nfrom subprocess import run\nfrom subprocess import check_output\n\n\nclass Fmt(object):\n def __init__(self, fmtId, text):\n self.fmtId = fmtId\n self.text = text\n\n\nclass FmtList(npyscreen.SelectOne):\n def __init__(self, *args, **keywords):\n super(FmtList, self).__init__(*args, **keywords)\n\n def display_value(self, vl):\n return '{}'.format(vl.text)\n\n\nclass TestApp(npyscreen.NPSApp):\n audio_fmts = []\n video_fmts = []\n url = 'https://www.youtube.com/watch?v=2MpUj-Aua48'\n\n @staticmethod\n def get_size_string(kilobytes):\n unit = 'KiB'\n if kilobytes >= 1024:\n kilobytes = kilobytes / 1024\n unit = 'MiB'\n\n if kilobytes >= 1024:\n kilobytes = kilobytes / 1024\n unit = 'GiB'\n\n return '{}{}'.format(round(kilobytes, 2), unit)\n\n def append_fmt_to_list(self, lst, fmtId, description, bitrate, kilobytes):\n sizeString = self.get_size_string(kilobytes)\n s = '{}\\t- {}\\t{}kbps'.format(fmtId, description, bitrate).expandtabs(2)\n s = '{}\\t{}'.format(s, sizeString).expandtabs(8)\n lst.append(Fmt(fmtId, s))\n\n def download_json(self):\n if len(sys.argv) > 1:\n self.url = sys.argv[1]\n\n print('Querying formats for {}'.format(self.url))\n result = check_output(['youtube-dl -j {}'.format(self.url)], shell=True).decode('utf-8')\n # result = run( [ 'youtube-dl -j {}'.format(self.url) ], shell=True, capture_output=True, text=True )\n # j = json.loads(result.stdout)\n return json.loads(result)\n\n def fill_models(self):\n j = self.download_json()\n duration = j['duration']\n fmts = j['formats']\n\n for fmt in fmts:\n try:\n fmt_id = fmt['format_id']\n size = fmt['filesize']\n kilobytes = size / 1024\n bitrate = round((kilobytes / duration) * 8)\n\n if fmt['vcodec'] and fmt['vcodec'] != 'none':\n height = fmt['height']\n desc = '{}p'.format(height)\n self.append_fmt_to_list(self.video_fmts, fmt_id, desc, bitrate, kilobytes)\n else:\n acodec = fmt['acodec'][:4]\n self.append_fmt_to_list(self.audio_fmts, fmt_id, acodec, bitrate, kilobytes)\n except KeyError:\n print('Unknown id/codec.')\n\n def main(self):\n self.fill_models()\n\n formats = npyscreen.Form(name=\"Select preferred formats\", minimum_lines=20)\n\n formats.add(npyscreen.FixedText, value=\"Video\", max_width=40, editable=False)\n video = formats.add(FmtList, value=[0], name=\"Video\", max_width=40, max_height=16,\n values=self.video_fmts, scroll_exit=True, exit_right=True)\n\n formats.add(npyscreen.FixedText, value=\"Audio\", max_width=40, editable=False, relx=42, rely=2)\n audio = formats.add(FmtList, value=[0], name=\"Audio\", max_width=40, max_height=16,\n values=self.audio_fmts, scroll_exit=True, exit_left=True, relx=42, rely=3)\n\n # This lets the user interact with the Form.\n formats.edit()\n\n import curses\n curses.endwin()\n\n ids = [self.video_fmts[video.value[0]].fmtId,\n self.audio_fmts[audio.value[0]].fmtId]\n prefs = '{}+{}'.format(ids[0], ids[1])\n print(prefs)\n run([\"mpv --term-status-msg='Video bitrate: ${{video-bitrate}}, audio bitrate: ${{audio-bitrate}}' --ytdl-format {} {}\".format(\n prefs, self.url)], shell=True)\n\n\nif __name__ == \"__main__\":\n App = TestApp()\n App.run()\n","sub_path":"ytdl-tui.py","file_name":"ytdl-tui.py","file_ext":"py","file_size_in_byte":3730,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"510280095","text":"from django.urls import path, include\nfrom .views import relatorioedital,pdf_inscricaoDetelhada\n\napp_name = 'relatorios'\nurlpatterns = [\n\n path('pdf/edital/', relatorioedital, name='relatorioedital'),\n path('view/inscriçãod/pdf/', pdf_inscricaoDetelhada, name='inscricaodetalhada'),\n\n]\n","sub_path":"relatorios/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":310,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"307411048","text":"# Dado um determinado bloco de rede (tome como exemplo o bloco de rede 192.168.1.0/27), \r\n# fazer um programa em Python que a partir do bloco de rede dado:\r\n# (a)Calcule a máscara de rede (em decimal);\r\n# (b)Calcule a quantidade de sub-redes;\r\n# (c)Calcule a quantidade total de endereços por sub-rede;\r\n# (d)Informe o endereço de rede e broadcast de cada sub-rede;\r\n# (e)Informe quais os endereços válidos de cada sub-rede\r\n\r\nimport sys, os\r\n\r\ntry:\r\n # Limpando a tela\r\n #os.system('cls' if os.name == 'nt' else 'clear')\r\n os.system('cls||clear')\r\n\r\n # Solicita Ende.Rede/Rede no formato CIDR \r\n input_ip_rede = input('Informe o End.Rede/Rede Desejada (ex. 10.0.0.0/24): ')\r\n #input_ip_rede = '192.168.1.0/27'\r\n\r\n # Separa prefixo e rede\r\n [prefixo, num_uns] = input_ip_rede.split(\"/\")\r\n num_uns = int(num_uns)\r\n num_zeros = 32 - num_uns\r\n\r\n # Lista com os octetos em decimal\r\n oct_prefixo = [int(j) for j in prefixo.split(\".\")]\r\n\r\n # Octetos da subrede em binário\r\n prefixo_bin = []\r\n prefixo_bin_oct = [bin(i).split(\"b\")[1] for i in oct_prefixo]\r\n\r\n # Completando octetos com zeros\r\n for i in prefixo_bin_oct:\r\n if len(i) < 8:\r\n sub_lista = i.zfill(8)\r\n prefixo_bin.append(sub_lista)\r\n else:\r\n prefixo_bin.append(i)\r\n\r\n # Endereço de rede e máscara de rede\r\n end_rede_bin = \"\".join(prefixo_bin)\r\n mascara_rede_bin = []\r\n [mascara_rede_bin.append('1'* num_uns + '0' * num_zeros)]\r\n masc_rede_bin = \"\".join(mascara_rede_bin)\r\n\r\n # Calculando número de hosts\r\n num_hosts = abs(2 ** num_zeros - 2)\r\n\r\n # Calculando endereço de broadcast\r\n end_broadcast_bin = end_rede_bin[:num_uns] + \"1\" * num_zeros\r\n\r\n # Calculando enderecos com octetos\r\n end_rede_bin_octeto = []\r\n broadcast_bin_octeto = []\r\n mascara_rede_bin_octeto = []\r\n\r\n [mascara_rede_bin_octeto.append(i) for i in [masc_rede_bin[j:j+8]\r\n for j in range(0, len(masc_rede_bin), 8)]]\r\n [end_rede_bin_octeto.append(i) for i in [end_rede_bin[j:j+8]\r\n for j in range(0, len(end_rede_bin), 8)]]\r\n [broadcast_bin_octeto.append(i) for i in [end_broadcast_bin[j:j+8]\r\n for j in range(0,len(end_broadcast_bin),8)]]\r\n\r\n end_rede_dec = \".\".join([str(int(i,2)) for i in end_rede_bin_octeto])\r\n broadcast_dec = \".\".join([str(int(i,2)) for i in broadcast_bin_octeto])\r\n mascara_rede_dec = \".\".join([str(int(i,2)) for i in mascara_rede_bin_octeto])\r\n\r\n # Calculando faixa de IP\r\n primeiro_ip_host = end_rede_bin_octeto[0:3] + [(bin(int(end_rede_bin_octeto[3],2)+1).split(\"b\")[1].zfill(8))]\r\n primeiro_ip = \".\".join([str(int(i,2)) for i in primeiro_ip_host])\r\n\r\n ultimo_ip_host = broadcast_bin_octeto[0:3] + [bin(int(broadcast_bin_octeto[3],2) - 1).split(\"b\")[1].zfill(8)]\r\n ultimo_ip = \".\".join([str(int(i,2)) for i in ultimo_ip_host])\r\n\r\n # Calculando núm. de subredes\r\n num_subredes = str(2**abs(24 - num_uns))\r\n \r\n '''\r\n print(num_hosts)\r\n print(num_zeros)\r\n print(num_uns)\r\n print(\"Másc. de rede: \", mascara_rede_bin)\r\n print(\"Másc. de rede: \", mascara_rede_bin_octeto)\r\n print(\"Másc. de rede: \", mascara_rede_dec)\r\n print(\"End. de rede: \", end_rede_bin)\r\n print(\"End. de rede: \", end_rede_bin_octeto)\r\n print(\"End. de rede: \", end_rede_dec)\r\n print(\"End. de broadcast: \", end_broadcast_bin)\r\n print(\"End. de broadcast: \", broadcast_bin_octeto)\r\n print(\"End. de broadcast: \", broadcast_dec)\r\n '''\r\n\r\n # Resultados obtidos\r\n print (\"\\nO Prefixo/Rede fornecido foi: \" + input_ip_rede)\r\n print (\"A máscara de rede é: \" + mascara_rede_dec)\r\n print (\"Número de hosts por rede: {0}\".format(str(num_hosts)))\r\n print (\"Bits da máscara de rede: {0}\".format(str(num_uns)))\r\n print (\"O endereço de rede é: {0}\".format(end_rede_dec))\r\n print (\"O endereço de broadcast é: {0}\".format(broadcast_dec))\r\n print (\"A faixa de IP útil é: {0} - {1}\".format(primeiro_ip, ultimo_ip))\r\n print (\"Número de subredes é: \" + num_subredes)\r\n #'''\r\n\r\n# Tratamentos de excessões\r\nexcept KeyboardInterrupt:\r\n print (\"\\nInterrompido pelo usuário, encerrando.\\n\")\r\nexcept ValueError:\r\n print (\"\\nForam inseridos dados incorretos (ex. 10.0.0.0/24), encerrando.\\n\")\r\nexcept IndexError:\r\n print (\"\\nForam inseridos dados incorretos (ex. 10.0.0.0/24), encerrando.\\n\")\r\nexcept:\r\n print (\"\\nForam inseridos dados incorretos (ex. 10.0.0.0/24), encerrando.\\n\") ","sub_path":"Prova_Extra/Avaliacao_Extra_Q03.py","file_name":"Avaliacao_Extra_Q03.py","file_ext":"py","file_size_in_byte":4593,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"541969157","text":"# vmdMeasureHBonds.py \n\nfrom __future__ import division\n\nimport vmd, molecule\nfrom VMD import *\nimport sys\nimport os\nimport subprocess\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport matplotlib.mlab as mlab\nimport ast \nimport time \n\nUSAGE_STR = \"\"\"\n# Purpose:\n# This script utilizes VMD's measure command to extract all the hydrogen bonds within a specified trajectory \n\n# Usage: python vmdMeasureHBonds-ExternalLookup.py \n\n# Arguments:\n# Absolute path to trajectory to compute hydrogen bond contacts for \n# Absolute path to topology file \n# Absolute path to output file \n# <-stride> Optional flag to denote stride value other than default of 1\n# <-chain> Optional flag to denote specific chain to compute hydrogen bonds for \n# <-solv> Optional flag to denote solvent other than default of TIP3\n\n# Example:\n# TRAJ_PATH=\"/scratch/PI/rondror/akma327/DynamicNetworks/data/DynamicNetworksOutput/InteractionOutput/B2AR-active-Gs-BI-science2015/condition-22/rep_1/Prod_0/Prod_0_rewrapped.dcd\"\n# TOP_PATH=\"/scratch/PI/rondror/akma327/DynamicNetworks/data/DynamicNetworksOutput/InteractionOutput/B2AR-active-Gs-BI-science2015/condition-22/step5_assembly.mae\"\n# OUTPUT_FILE=\"/scratch/PI/rondror/akma327/DynamicNetworks/data/DynamicNetworksOutput/InteractionOutput/B2AR-active-Gs-BI-science2015/condition-22/rep_1/Prod_0/HB_3.5A_70D/hydrogen_bond_water_result.txt\"\n# python vmdMeasureHBonds-ExternalLookup.py $TRAJ_PATH $TOP_PATH $OUTPUT_FILE -chain R \n\n# Example VMD:\n# import sys\n# TRAJ_PATH=\"/scratch/PI/rondror/akma327/DynamicNetworks/data/DynamicNetworksOutput/InteractionOutput/B2AR-active-Gs-BI-science2015/condition-22/rep_1/Prod_0/Prod_0_rewrapped.dcd\"\n# TOP_PATH=\"/scratch/PI/rondror/akma327/DynamicNetworks/data/DynamicNetworksOutput/InteractionOutput/B2AR-active-Gs-BI-science2015/condition-22/step5_assembly.mae\"\n# OUTPUT_FILE=\"/scratch/PI/rondror/akma327/DynamicNetworks/data/DynamicNetworksOutput/InteractionOutput/B2AR-active-Gs-BI-science2015/condition-22/rep_1/Prod_0/HB_3.5A_70D/hydrogen_bond_water_result.txt\"\n# sys.argv = ['a', TRAJ_PATH, TOP_PATH, OUTPUT_FILE, '-chain', 'R']\n# execfile('vmdMeasureHBonds-ExternalLookup.py')\n\n\"\"\"\n\nK_MIN_ARG = 4\nstart=0\nstop=-1\nstride=1\nsmoothing=0\ntrajid = None\nsolvent_id = \"TIP3\"\nlookup_table = {}\n\n# Generate file descriptor for path \ndef createFileWriter(OutputPath):\n\tfilename = OutputPath\n\tprint(\"Output File Path: \" + filename)\n\tif not os.path.exists(os.path.dirname(filename)):\n\t\tos.makedirs(os.path.dirname(filename))\n\tf = open(filename, 'w')\n\treturn f\n\n# Script that checks whether there are any duplicates in the interaction key output \ndef debugRepeats(frame_index, dist_cutoff, angle_cutoff):\n\tdonors, acceptors = calcDonorAcceptors(frame_index, None, dist_cutoff, angle_cutoff)\n\tdonors, acceptors = removeDuplicateIndices(donors, acceptors)\n\tkey_pairs = []\n\tfor i, d in enumerate(donors):\n\t\tkey_pairs.append((donors[i], acceptors[i]))\n\tkey_dict = {}\n\tfor a in key_pairs:\n\t\tif(a not in key_dict):\n\t\t\tkey_dict[a] = 1\n\t\telse:\n\t\t\tkey_dict[a] += 1\n\tfor k in key_dict:\n\t\tv = key_dict[k]\n\t\tif(v > 1):\n\t\t\tprint(k,v)\n\tprint(len(key_dict))\n\n\n# Removes duplicate indice pairs that represent the same interaction key\ndef removeDuplicateIndices(donors, acceptors):\n\tpairs = []\n\tfor i, d in enumerate(donors):\n\t\tpairs.append((donors[i], acceptors[i]))\n\tpairs = sorted(list(set(pairs)))\n\tnewDonors, newAcceptors = [], []\n\tfor p in pairs:\n\t\tnewDonors.append(p[0])\n\t\tnewAcceptors.append(p[1])\n\treturn newDonors, newAcceptors\n\n\n# Extract suffix file type \ndef getFileType(fileName):\n\tfile_type = fileName.split(\".\")[-1].strip()\n\tif(file_type == \"nc\"): file_type = 'netcdf'\n\treturn file_type\n\n# Load trajectory and topology into VMD display\ndef load_traj(top_path, traj_path):\n\ttop_file_type = getFileType(top_path)\n\ttrajid = molecule.load(top_file_type, top_path)\n\tif(traj_path != None):\n\t\ttraj_file_type = getFileType(traj_path)\n\t\tmolecule.read(trajid, traj_file_type, traj_path, beg=start, end=stop, skip=stride, waitfor=-1)\n\n\n# Convert list of atom indices for a frame to atom labels \ndef indexToLabel(frame_index, hbond_index_list, crystal=False):\n\tglobal lookup_table\n\tprint(\"beg indexToLabel\", len(lookup_table))\n\tlabel_list = []\n\tfor display_index, atom_index in enumerate(hbond_index_list):\n\t\tif(atom_index in lookup_table):\n\t\t\tval = lookup_table[atom_index]\n\t\t\tlabel_list.append(val)\n\t\telse:\n\t\t\tif(display_index % 400 == 0): print(\"Adding key \" + str(atom_index) + \" to lookup_table\")\n\t\t\tkey = int(atom_index)\n\t\t\taselect = evaltcl(\"set sel [atomselect top \\\"index \" + str(atom_index) + \"\\\"]\")\n\t\t\tresname = evaltcl('$sel get resname')\n\t\t\tresid = evaltcl('$sel get resid')\n\t\t\tatom_name = evaltcl('$sel get name')\n\t\t\tvalue = resname + resid + \"-\" + atom_name\n\t\t\tevaltcl('$sel delete')\n\t\t\tlookup_table[key] = value \n\t\t\tlabel_list.append(lookup_table[atom_index])\n\treturn label_list\n\n\n# Generate atomselection command \ndef genHBondsAtomSelection(frame_index, dist_cutoff, angle_cutoff, chainId, solvent_id):\n\tif(solvent_id == \"IP3\"):\n\t\tif(chainId == None):\n\t\t\tx = evaltcl(\"measure hbonds \" + str(dist_cutoff) + \" \" + str(angle_cutoff) + \" [atomselect top \\\"(resname IP3 and within 3.5 of protein) or protein and not lipid and not carbon\\\" frame \" + str(frame_index) + \"]\")\n\t\telse:\n\t\t\tx = evaltcl(\"measure hbonds \" + str(dist_cutoff) + \" \" + str(angle_cutoff) + \" [atomselect top \\\"(resname IP3 and within 3.5 of protein and chain \" + str(chainId) + \") or protein and chain \" + str(chainId) + \" and not lipid and not carbon\\\" frame \" + str(frame_index) + \"]\")\n\telse:\n\t\tif(chainId == None):\n\t\t\tx = evaltcl(\"measure hbonds \" + str(dist_cutoff) + \" \" + str(angle_cutoff) + \" [atomselect top \\\"(water and within 3.5 of protein) or protein and not lipid and not carbon\\\" frame \" + str(frame_index) + \"]\")\n\t\telse:\n\t\t\tx = evaltcl(\"measure hbonds \" + str(dist_cutoff) + \" \" + str(angle_cutoff) + \" [atomselect top \\\"(water and within 3.5 of protein and chain \" + str(chainId) + \") or protein and chain \" + str(chainId) + \" and not lipid and not carbon\\\" frame \" + str(frame_index) + \"]\")\t\n\treturn x \n\n# Calculator donor and acceptor atom pairs for hydrogen bonds\ndef calcDonorAcceptors(frame_index, dist_cutoff, angle_cutoff, chainId=None):\n\tx = genHBondsAtomSelection(frame_index, dist_cutoff, angle_cutoff, chainId, solvent_id)\n\tlists = x.split(\"}\")\n\tlist1 = lists[0].split(\"{\")[1].split(\" \")\n\tdonors = [int(a) for a in list1]\n\tlist2 = lists[1].split(\"{\")[1].split(\" \")\n\tacceptors = [int(a) for a in list2]\n\treturn donors, acceptors\n\n# Calculate the hydrogen bonds for a single frame \ndef calcHBondFrame(f, frame_index, dist_cutoff, angle_cutoff, lookup_table, chainId=None, crystal=False):\n\tcrystalHBond = []\n\tif(frame_index %20 == 0): print(\"calcHBondFrame() for frame_index: \" + str(frame_index))\n\tdonors, acceptors = calcDonorAcceptors(frame_index, dist_cutoff, angle_cutoff, chainId) #indices \n\tdonors, acceptors = removeDuplicateIndices(donors, acceptors) # Remove duplicates \n\tdonor_label = indexToLabel(frame_index, donors, crystal)\n\tacceptor_label = indexToLabel(frame_index, acceptors, crystal)\n\tif(crystal == False): f.write(\"\\nHydrogen Bond Water Frame: \" + str(frame_index-1) + \"\\n\")\n\tfor index, v in enumerate(donor_label):\n\t\tif(crystal == True):\n\t\t\tdonor_atom = donor_label[index].replace(solvent_id, \"HOH\")\n\t\t\tacceptor_atom = acceptor_label[index].replace(solvent_id, \"HOH\")\n\t\t\tcrystalHBond.append((donor_atom, acceptor_atom))\n\t\telse:\n\t\t\thbond_label = donor_label[index] + \" -- \" + acceptor_label[index]\n\t\t\thbond_label = hbond_label.replace(solvent_id, \"HOH\")\n\t\t\tf.write(hbond_label + \" -- \" + str(donors[index]) + \" -- \" + str(acceptors[index]) + \"\\n\") #include index \n\tif(crystal == True): return crystalHBond\n\n# Calculate and write all hydrogen bonds for entire trajectory \ndef calcVMDHydrogenBondWaterResults(f, stride_val, TOP_PATH, TRAJ_PATH, solventId, chainId=None, crystal=False, dist_cutoff=3.5, angle_cutoff=70):\n\tglobal solvent_id\n\tglobal stride\n\tif(solventId != None):\n\t\tsolvent_id = solventId\n\tprint(stride_val, TOP_PATH, TRAJ_PATH, solvent_id, chainId)\n\tstride = stride_val \n\ttic = time.clock()\n\tload_traj(TOP_PATH, TRAJ_PATH)\n\tnumFrames = int(evaltcl('molinfo top get numframes'))\n\tif(crystal == True):\n\t\tcrystalHBond = list(set(calcHBondFrame(f, 0, dist_cutoff, angle_cutoff, lookup_table, chainId, crystal)))\n\t\treturn crystalHBond\n\telse:\n\t\tfor frame_index in range(1, numFrames):\n\t\t\tcalcHBondFrame(f, frame_index, dist_cutoff, angle_cutoff, lookup_table, chainId)\n\t\ttoc = time.clock()\n\t\tcomputingTime = toc - tic \n\t\tprint(\"calcVMDHydrogenBondWaterResults() Computing Time: \" + str(computingTime))\n\t\tprint(len(lookup_table))\n\t\treturn numFrames - 1, computingTime\n\n\n\n\n# Interactive module testing \nif __name__ == \"__main__\":\n\tif(len(sys.argv) < K_MIN_ARG):\n\t\tprint(USAGE_STR)\n\t\texit(1)\n\tTRAJ_PATH = sys.argv[1]\n\tTOP_PATH = sys.argv[2]\n\tOUTPUT_FILE = sys.argv[3]\n\tchainId = None \n\tstride = 1\n\tif(\"-stride\" in sys.argv):\n\t\tstride = int(sys.argv[sys.argv.index(\"-stride\")+1])\n\tif(\"-chain\" in sys.argv):\n\t\tchainId = sys.argv[sys.argv.index(\"-chain\") + 1]\n\tif(\"-solv\" in sys.argv):\n\t\tsolvent_id = sys.argv[sys.argv.index(\"-solv\") + 1]\n\tf = createFileWriter(OUTPUT_FILE)\n\tcalcVMDHydrogenBondWaterResults(f, stride, TOP_PATH, TRAJ_PATH, solvent_id, chainId)\n\n\n","sub_path":"src/interaction-geometry/old/vmdMeasureHBonds_101016_save.py","file_name":"vmdMeasureHBonds_101016_save.py","file_ext":"py","file_size_in_byte":9430,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"410517241","text":"\"\"\"This file contains code for use with \"Think Bayes\",\nby Allen B. Downey, available from greenteapress.com\n\nCopyright 2012 Allen B. Downey\nLicense: GNU GPLv3 http://www.gnu.org/licenses/gpl.html\n\"\"\"\n\nfrom src.thinkbayes import Suite\n\n\nclass Dice(Suite):\n \"\"\"Represents hypotheses about which die was rolled.\"\"\"\n\n def likelihood(self, data, hypo):\n \"\"\"Computes the likelihood of the data under the hypothesis.\n\n hypo: integer number of sides on the die\n data: integer die roll\n \"\"\"\n if hypo < data:\n return 0\n else:\n return 1.0/hypo\n\n\ndef main():\n ### QUESTION TO SOLVE: select a die from box at random, roll it and get a 6. What is the probability\n ### that each die was rolled? (prob of having rolled 4-sided, 6-sided, 8, 12, 20-sided dice).\n\n # HYPOTHESIS: 4,6,8,12,20-sided dice in tbe box\n # DATA: numbers 1 - 20 for respective dice.\n # LIKELIHOOD: if hypo likelihood = 0.\n # But otherwise, given hypo sides, chance of rolling data (element, one side) is 1/hypo, regardless of data.\n\n # Step 1: Prior: The 4-sided, 6-sided, 8, 12, 20 sided dice in the box.\n suite = Dice([4, 6, 8, 12, 20]) # step 1: setting all these hypos to have equal probability: 1/5\n\n suite.update(6) # Step 2: updating the numerator with likelihood, then normalizing.\n print('After one 6')\n suite.printSuite()\n\n # Note: the p(4) and p(6) become 0 because they are less than some data here.\n for roll in [6, 8, 7, 7, 5, 4]:\n suite.update(roll)\n\n # NOTE: the 8 has highest probability because it has lowest num sides after 4 and 6 which got eliminated,\n # and likewise, 20 has smallest chance because it has most sides.\n print('After more rolls')\n suite.printSuite()\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"AllenBDowney_ThinkBayes/src/dice.py","file_name":"dice.py","file_ext":"py","file_size_in_byte":1865,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"488977925","text":"#########################################\n# Filename: prepare.py\n# Author: Roni Shternberg\n# This script prepares the \"purchases1000_new.txt\" data file based on \"purchases1000.txt\" file.\n# 1. All the dates in \"purchases1000.txt\" file are from the date \"2012-01-01\".\n# 2. In order to have different dates, we create lists of RANDOM dates and times.\n# 3. We set dates and times into the purchase objects using the Purchase method set_date_and_time().\n#########################################\n\n#########################################\n# Import Statements\n#########################################\n\nfrom datetime import datetime\nimport random\nimport csv # comma seperated values\n\n#########################################\n# Class definitions\n#########################################\n\nclass Purchase:\n\n def __init__(self, date, time, store, category, price, payment):\n self.date = date\n self.time = time\n self.store = store\n self.category = category\n self.price = price\n self.payment = payment\n\n # we use this method to set random date and time into purchase objects.\n def set_date_and_time(self, date_obj, time_str):\n self.date = date_obj\n self.time = time_str\n\nclass Ledger: # account book, record book - \"a book or other collection of financial accounts of a particular type.\"\n\n def __init__(self):\n self.purchases_list = [] # list of purchase objects\n\n # add to list of purchases\n def add_purchase(self, purchase):\n self.purchases_list.append(purchase)\n\n # get purchase at index i\n def get_purchase_at(self, i):\n return self.purchases_list[i]\n\n############################################\n# Generate random dates and times, and hold them in temp lists.\n# values from these temp lists will be set into purchase objects using the set_date_and_time() method, later on.\n############################################\n\nlist_date_objects = []\nlist_time_strings = []\n\nfor i in range(1, 1001):\n # randomize yyyy-mm-dd values\n curr_year = random.randint(2000, 2020)\n curr_month = random.randint(1, 12)\n curr_day = random.randint(1, 28)\n\n # cast int values into strings\n date_str = str(curr_year) + '-' + str(curr_month) + '-' + str(curr_day)\n\n # format the date string\n date_obj = datetime.strptime(date_str, '%Y-%m-%d').date()\n\n # append date object into temp list\n list_date_objects.append(date_obj)\n\n # same for time values\n curr_hour = random.randint(0, 23)\n curr_min = random.randint(0, 59)\n\n # cast int values to strings\n time_str = str(curr_hour) + ':' + str(curr_min)\n time_obj = datetime.strptime(time_str, '%H:%M').time()\n time_str = str(time_obj)[:5]\n\n # unlike dates, we append the time string into the temp list, not the time object,\n # since we don't really do anything with times.\n list_time_strings.append(time_str)\n\n########################################\n# Create empty Ledger object\n########################################\n\nledger = Ledger()\n\n#########################################\n# read \"purchases1000.txt\" file\n#########################################\n\nwith open(\"purchases1000.txt\") as csv_file:\n csv_reader = csv.reader(csv_file, delimiter='\\t') # TAB delimited\n counter = 0\n\n for line in csv_reader:\n if counter == 1000:\n break\n counter += 1\n\n # Unpack variables\n date, time, store, category, price, payment = line\n\n # create Purchase object\n curr_purchase = Purchase(date, time, store, category, float(price), payment)\n\n # add purchase to ledger\n ledger.add_purchase(curr_purchase)\n\n##################################################################################\n# setting the random dates and times from the temp lists into purchase objects\n##################################################################################\n\nfor i in range(1000):\n ledger.get_purchase_at(i).set_date_and_time(list_date_objects[i], list_time_strings[i])\n\n\n##################################################################################\n# Writing the \"purchases1000_new.txt\" file\n##################################################################################\n\nwith open(\"purchases1000_new.txt\", mode='w', newline='') as csv_new_file:\n csv_writer = csv.writer(csv_new_file, delimiter='\\t', quotechar='\"', quoting=csv.QUOTE_MINIMAL)\n\n for i in range(1000):\n purchase = ledger.get_purchase_at(i)\n csv_writer.writerow(\n [purchase.date, purchase.time, purchase.store, purchase.category, purchase.price, purchase.payment])\n","sub_path":"prepare.py","file_name":"prepare.py","file_ext":"py","file_size_in_byte":4606,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"400503086","text":"import os\n\nfrom arelle.CntlrCmdLine import parseAndRun\n\n\nCONFORMANCE_SUITE = 'tests/resources/conformance_suites/XBRL-CONF-2014-12-10.zip'\nBASE_ARGS = [\n '--csvTestReport', './xbrl-conf-report.csv',\n '--file', os.path.abspath(os.path.join(CONFORMANCE_SUITE, 'xbrl.xml')),\n '--formula', 'run',\n '--logFile', './xbrl-conf-log.txt',\n '--calcPrecision',\n '--testcaseResultsCaptureWarnings',\n '--validate'\n]\n\n\ndef run_xbrl_conformance_suite(args):\n \"\"\"\n Kicks off the validation of the XBRL 2.1 conformance suite.\n\n :param args: The arguments to pass to Arelle in order to accurately validate the XBRL 2.1 conformance suite\n :param args: list of str\n :return: Returns the result of parseAndRun which in this case is the created controller object\n :rtype: ::class:: `~arelle.CntlrCmdLine.CntlrCmdLine`\n \"\"\"\n return parseAndRun(args)\n\n\nif __name__ == \"__main__\":\n print('Running XBRL 2.1 tests...')\n run_xbrl_conformance_suite(BASE_ARGS)\n","sub_path":"scripts/conformance_suites/run_xbrl_conformance_suite.py","file_name":"run_xbrl_conformance_suite.py","file_ext":"py","file_size_in_byte":982,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"287247006","text":"'''\nSample Input\n1\n5\n1 2 3 2 1\nSample Output\n3\n'''\nfor _ in range(int(input())):\n noe = int(input())\n arr = [int(x) for x in input().split()]\n left = arr[0]\n rite = sum(arr) - left\n mins = abs(rite - left)\n for i in range(1, noe-1):\n left += arr[i]\n rite -= arr[i]\n print(left, rite)\n mins = min(mins, abs(left - rite))\nprint(mins)","sub_path":"HackerEarth/Dell_1.py","file_name":"Dell_1.py","file_ext":"py","file_size_in_byte":377,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"426300834","text":"import time\n\nclass BatchInfo:\n appId:str=None\n batchTime:int=None\n submissionTime:int=-1\n processingStartTime:int=-1\n processingEndTime:int=-1\n\n def __init__(self, appId:str,batchTime:int=time.time()):\n self.appId = appId\n self.batchTime = batchTime\n\n def __str__(self):\n return \"a\"\n #return \"BatchInfo({},{},{},{},{})\".format(self.appId,self.batchTime,self.submissionTime,\n #self.processingStartTime,self.processingEndTime)\n\nif __name__ == \"__main__\":\n b1=BatchInfo(\"app1\")\n print(b1)\n\n# def submit_batch():\n# # batchs.append()\n\n# def complete_batch():","sub_path":"leetcode/src/main/python/py/BatchInfo.py","file_name":"BatchInfo.py","file_ext":"py","file_size_in_byte":619,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"370429901","text":"#\n# Default Flask settings\n#\nDEBUG = False\nSECRET_KEY = 'A_UNIQUE_KEY_FOR_YOUR_APPLICATION'\n\n\n#\n# Default Goonhilly settings\n#\nGOONHILLY_LOG_FILE = 'PATH_TO_LOGFILE'\nGOONHILLY_AUTHORIZED_SOURCE_TAGS = ['SOURCE_TAG_1',\n 'SOURCE_TAG_2', ]\n\n\n#\n# To implement user-agent logging, see the read-me\n#\nUA_PARSER = False\n","sub_path":"settings.py","file_name":"settings.py","file_ext":"py","file_size_in_byte":347,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"328539171","text":"from kemp.fdtd3d.util import common, common_exchange, common_buffer\nfrom fields import Fields\n\n\nclass Pbc:\n def __init__(self, fields, axes):\n \"\"\"\n \"\"\"\n\n common.check_type('fields', fields, Fields)\n common.check_type('axes', axes, str)\n\n assert len( set(axes).intersection(set('xyz')) ) > 0, 'axes option is wrong: %s is given' % repr(axes)\n\n # global variables\n self.mainf = fields\n self.axes = axes\n\n # append to the update list\n self.priority_type = 'pbc'\n self.mainf.append_instance(self)\n\n\n def update(self, e_or_h, part):\n for axis in list(self.axes):\n for str_f in common_exchange.str_fs_dict[axis][e_or_h]:\n f = self.mainf.get(str_f)\n sl_get = common_exchange.slice_dict[axis][e_or_h]['get']\n sl_set = common_exchange.slice_dict[axis][e_or_h]['set']\n sl_part = common_buffer.slice_dict[e_or_h][part]\n\n sl_src = common.overlap_two_slices(self.mainf.ns, sl_get, sl_part)\n sl_dest = common.overlap_two_slices(self.mainf.ns, sl_set, sl_part)\n f[sl_dest] = f[sl_src]\n\n\n def update_e(self, part=''):\n self.mainf.enqueue(self.update, ['e', part])\n\n\n def update_h(self, part=''):\n self.mainf.enqueue(self.update, ['h', part])\n","sub_path":"KEMP/v0.3/fdtd3d/cpu/pbc.py","file_name":"pbc.py","file_ext":"py","file_size_in_byte":1352,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"522746069","text":"\nimport os\n\nfrom setuptools import setup\n\n\ndef read(fname):\n with open(os.path.join(os.path.dirname(__file__), fname)) as fp:\n return fp.read()\n\n\nsetup(\n author=\"Russell Morley\",\n author_email=\"russ@compass-point.net\",\n classifiers=[\n \"Development Status :: 3 - Alpha\",\n \"Framework :: Django\",\n \"License :: OSI Approved :: MIT License\",\n ],\n description=\"Generic sockets server implementation for multitenant sites.\",\n install_requires=[\n ],\n keywords=\"channels sockets django\",\n license=\"MIT\",\n long_description=read(\"README.md\"),\n name=\"django_multitenant_sockets\",\n packages=[\"django_multitenant_sockets\"],\n url=\"https://github.com/russellmorley/django_multitenant\",\n version=\"0.0.1\",\n)\n","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":717,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"638828187","text":"from __future__ import print_function\n\nfrom nose import SkipTest\nfrom .. import interface\n\n\nclass TestScannerInterface(object):\n\n def test_interface(self):\n\n # This is mostly just a smoketest to touch parts of the code\n\n scanner = interface.ScannerInterface(\"localhost\", 2121,\n base_dir=\"test_data\")\n\n if not scanner.has_ftp_connection:\n raise SkipTest\n\n try:\n scanner.start()\n vol = scanner.get_volume(timeout=5)\n assert vol\n\n finally:\n scanner.shutdown()\n","sub_path":"rtfmri/tests/test_interface.py","file_name":"test_interface.py","file_ext":"py","file_size_in_byte":594,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"237299039","text":"'''\nexperimenting with realsense sdk python wrapper\n'''\nimport numpy as np\nfrom cv2 import cv2\nimport matplotlib.pyplot as plt\nfrom mpl_toolkits import mplot3d\n# from matplotlib.patches import FancyArrowPatch\n# from mpl_toolkits.mplot3d import proj3d\nfrom pyrealsense2 import pyrealsense2 as rs\n\n\n# Configure depth and color streams\npipeline = rs.pipeline()\nconfig = rs.config()\nconfig.enable_stream(rs.stream.depth, 640, 480, rs.format.z16, 30)\nconfig.enable_stream(rs.stream.color, 640, 480, rs.format.bgr8, 30)\n\n# Start streaming\nprofile = pipeline.start(config)\ndepth_sensor = profile.get_device().first_depth_sensor()\ndepth_scale = depth_sensor.get_depth_scale()\nalign = rs.align(rs.stream.color)\n\n# depth filter\n# dec_filter = rs.decimation_filter() # reduce depth frame density\ntemp_filter = rs.temporal_filter() # edge-preserving spatial smoothing\nspat_filter = rs.spatial_filter() # reduce temporal noise\n\nfig = plt.figure()\nplt.ion()\nax = plt.axes(projection='3d')\n\ntry:\n while True:\n # Wait for a coherent pair of frames: depth and color\n frames = pipeline.wait_for_frames()\n # depth_frame = frames.get_depth_frame()\n # color_frame = frames.get_color_frame()\n\n # align depth to color frame\n aligned_frames = align.process(frames)\n depth_frame = aligned_frames.get_depth_frame()\n color_frame = aligned_frames.get_color_frame()\n\n # filtered = dec_filter.process(depth_frame)\n filtered = spat_filter.process(depth_frame)\n filtered = temp_filter.process(filtered)\n\n if not depth_frame or not color_frame:\n continue\n\n # Convert images to numpy arrays\n depth_image = np.asanyarray(filtered.get_data())\n color_image = np.asanyarray(color_frame.get_data())\n\n # Apply colormap on depth image (image must be converted to 8-bit per pixel first)\n depth_colormap = cv2.applyColorMap(cv2.convertScaleAbs(\n depth_image, alpha=0.03), cv2.COLORMAP_JET)\n\n # draw overlay on color frame\n ROI_center = [320, 240]\n increment = 1\n start_point = (ROI_center[0]-increment, ROI_center[1]-increment)\n end_point = (ROI_center[0]+increment, ROI_center[1]+increment)\n color_image = cv2.rectangle(\n color_image, start_point, end_point, (20, 20, 80), 2)\n\n # find surface normal using depth gradient\n depth_intrin = depth_frame.profile.as_video_stream_profile().intrinsics\n\n depth_center = depth_frame.as_depth_frame(\n ).get_distance(ROI_center[0], ROI_center[1])\n\n depth_left = depth_frame.as_depth_frame(\n ).get_distance(ROI_center[0]-increment, ROI_center[1])\n\n depth_right = depth_frame.as_depth_frame(\n ).get_distance(ROI_center[0]+increment, ROI_center[1])\n\n depth_up = depth_frame.as_depth_frame(\n ).get_distance(ROI_center[0], ROI_center[1]-increment)\n\n depth_down = depth_frame.as_depth_frame(\n ).get_distance(ROI_center[0], ROI_center[1]+increment)\n\n dzdx = (depth_right - depth_left)/(2.0)\n dzdy = (depth_down - depth_up)/(2.0)\n\n direction = [-dzdx, -dzdy, 1.0]\n magnitude = np.sqrt(dzdx**2 + dzdy**2 + 1.0)\n norm_vec = direction/magnitude\n\n ROI_center_xyz = rs.rs2_deproject_pixel_to_point(\n depth_intrin, ROI_center, depth_center)\n point_x = [round(ROI_center_xyz[0], 4), norm_vec[0]]\n point_y = [round(ROI_center_xyz[1], 4), norm_vec[1]]\n point_z = [round(ROI_center_xyz[2], 4), norm_vec[2]]\n\n # plot points in 3D\n ax.cla()\n ax.set_xlabel('x [m]')\n ax.set_ylabel('y [m]')\n ax.set_zlabel('z [m]')\n ax.set_xlim(-0.06, 0.06)\n ax.set_ylim(-0.06, 0.06)\n ax.set_zlim(0.0, 1.0)\n ax.scatter3D(point_x, point_y, point_z, c=point_z, cmap='winter')\n ax.plot3D([0, norm_vec[0]], [0, norm_vec[1]], [0, norm_vec[2]], 'gray')\n plt.draw()\n plt.pause(.001)\n\n # Stack both images horizontally\n # images = np.vstack((color_image, depth_colormap))\n\n # Show images\n cv2.namedWindow('RealSense', cv2.WINDOW_AUTOSIZE)\n cv2.imshow('RealSense', color_image)\n key = cv2.waitKey(1)\n if key & 0xFF == ord('q') or key == 27:\n cv2.destroyAllWindows()\n break\nfinally:\n # Stop streaming\n pipeline.stop()\n","sub_path":"scripts/surface_normal.py","file_name":"surface_normal.py","file_ext":"py","file_size_in_byte":4396,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"366621377","text":"import logging\nimport re\nimport json\n\nfrom bs4 import BeautifulSoup\nfrom decimal import Decimal\n\nfrom storescraper.product import Product\nfrom storescraper.store import Store\nfrom storescraper.utils import session_with_proxy, html_to_markdown\nfrom storescraper.categories import WASHING_MACHINE\n\n\nclass Comandato(Store):\n @classmethod\n def categories(cls):\n return [\n WASHING_MACHINE,\n ]\n\n @classmethod\n def discover_urls_for_category(cls, category, extra_args=None):\n session = session_with_proxy(extra_args)\n product_urls = []\n\n if category != WASHING_MACHINE:\n return []\n\n url = 'https://www.comandato.com/lg?PS=200'\n soup = BeautifulSoup(session.get(url).text, 'html.parser')\n products = soup.findAll('div', 'producto')\n\n if not products:\n logging.warning('Empty url {}'.format(url))\n\n for product in products:\n product_url = product.find('a')['href']\n product_urls.append(product_url)\n\n return product_urls\n\n @classmethod\n def products_for_url(cls, url, category=None, extra_args=None):\n print(url)\n session = session_with_proxy(extra_args)\n response = session.get(url)\n\n if response.status_code == 404:\n return []\n\n data = response.text\n soup = BeautifulSoup(data, 'html.parser')\n\n name_container = soup.find('div', 'productDescriptionShort')\n\n if not name_container:\n return []\n\n name = name_container.text\n sku = soup.find('div', 'skuReference').text\n stock = 0\n if soup.find('link', {'itemprop': 'availability'})['href'] == \\\n 'http://schema.org/InStock':\n stock = -1\n\n pricing_data = re.search(r'vtex.events.addData\\(([\\S\\s]+?)\\);',\n data).groups()[0]\n pricing_data = json.loads(pricing_data)\n\n tax = Decimal('1.12')\n offer_price = Decimal(pricing_data['productPriceFrom'])*tax\n normal_price = Decimal(pricing_data['productListPriceFrom'])*tax\n\n picture_urls = [a['zoom'] for a in\n soup.findAll('a', {'id': 'botaoZoom'})]\n\n description = html_to_markdown(\n str(soup.find('div', {'id': 'caracteristicas'})))\n\n p = Product(\n name,\n cls.__name__,\n category,\n url,\n url,\n sku,\n stock,\n normal_price,\n offer_price,\n 'USD',\n sku=sku,\n picture_urls=picture_urls,\n description=description,\n )\n\n return [p]\n","sub_path":"storescraper/stores/comandato.py","file_name":"comandato.py","file_ext":"py","file_size_in_byte":2669,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"177641885","text":"# Licensed under a 3-clause BSD style license - see LICENSE.rst\n# -*- coding: utf-8 -*-\ndef unwrap_objid(objid):\n \"\"\"Unwrap CAS-style objID into run, camcol, field, id, rerun.\n\n See pydl.pydlutils.sdss.sdss_objid() for details on how the bits\n within an objID are assigned.\n\n Parameters\n ----------\n objid : :class:`numpy.ndarray`\n An array containing 64-bit integers or strings. If strings are passed,\n they will be converted to integers internally.\n\n Returns\n -------\n unwrap_objid : :class:`numpy.recarray`\n A record array with the same length as objid, with the columns\n 'run', 'camcol', 'frame', 'id', 'rerun', 'skyversion'.\n\n Notes\n -----\n For historical reasons, the inverse of this function,\n :func:`~pydl.pydlutils.sdss.sdss_objid` is not in the same namespace as this\n function.\n\n 'frame' is used instead of 'field' because record arrays have a method\n of the same name.\n\n Examples\n --------\n >>> from numpy import array\n >>> from pydl.photoop.photoobj import unwrap_objid\n >>> unwrap_objid(array([1237661382772195474]))\n rec.array([(2, 301, 3704, 3, 91, 146)],\n dtype=[('skyversion', '> 59, 2**4 - 1)\n unwrap.rerun = bitwise_and(tempobjid >> 48, 2**11 - 1)\n unwrap.run = bitwise_and(tempobjid >> 32, 2**16 - 1)\n unwrap.camcol = bitwise_and(tempobjid >> 29, 2**3 - 1)\n # unwrap.firstfield = bitwise_and(tempobjid >> 28, 2**1 - 1)\n unwrap.frame = bitwise_and(tempobjid >> 16, 2**12 - 1)\n unwrap.id = bitwise_and(tempobjid, 2**16 - 1)\n return unwrap\n","sub_path":"pydl/photoop/photoobj/unwrap_objid.py","file_name":"unwrap_objid.py","file_ext":"py","file_size_in_byte":2189,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"247699676","text":"# -*- coding: utf-8 -*-\n\"\"\"\n.. codeauthor:: Jaume Bonet \n\n.. affiliation::\n Laboratory of Protein Design and Immunoengineering \n Bruno Correia \n\n.. func:: plot_96well\n.. func:: plot_thermal_melt\n.. func:: plot_MALS\n.. func:: plot_CD\n.. func:: plot_SPR\n\"\"\"\n# Standard Libraries\nimport math\nimport string\n\n# External Libraries\nimport numpy as np\nimport pandas as pd\nimport seaborn as sns\nimport matplotlib.pyplot as plt\nfrom matplotlib import font_manager\nfrom matplotlib.lines import Line2D\n\n# This Library\n\n\n__all__ = ['plot_96wells', 'plot_thermal_melt', 'plot_MALS', 'plot_CD', 'plot_SPR']\n\n\ndef plot_96wells(cdata=None, sdata=None, bdata=None, bcolors=None, bmeans=None, **kwargs):\n \"\"\"Plot data of a 96 well plate into an equivalent-shaped plot.\n\n Allows up to three data sources at the same time comming from experiments performed in a\n `96 wells microplate `_. Two of this data\n sources can have to be numerical, and are represented as color and size, while an extra\n boolean dataset can be represented by the color of the border of each well.\n\n Plot is based on :func:`~matplotlib.pyplot.scatter`; some graphical properties to control\n the visuals (such as ``cmap``), can be provided through this function.\n\n :param cdata: Data contentainer to be represented by color coding. Has to contain 8 rows\n and 12 columns, like the 96 well plate. Contains **continuos numerical data**.\n :type cdata: :class:`~pandas.DataFrame`\n :param sdata: Data contentainer to be represented by size coding. Has to contain 8 rows\n and 12 columns, like the 96 well plate. Contains **continuos numerical data**.\n :type sdata: :class:`~pandas.DataFrame`\n :param bdata: Data contentainer to be represented by the edge color. Has to contain 8 rows\n and 12 columns, like the 96 well plate. Contains **boolean data**.\n :type bdata: :class:`~pandas.DataFrame`\n :param bcolors: List of the two colors to identify the differences in the border for binary\n data. It has to be a list of 2 colors only. First color represents :data:`True` instances\n while the second color is :data:`False`. Default is ``black`` and ``green``.\n :type bcolors: :func:`list` of :class:`str`\n :param bmeans: List with the meanings of the boolean condition (for the legend). First color\n represents :data:`True` instances while the second color is :data:`False`. Default is\n ``True`` and ``False``.\n :type bmeans: :func:`list` of :class:`str`\n\n :return: Union[:class:`~matplotlib.figure.Figure`, :class:`~matplotlib.axes.Axes`]\n\n :raises:\n :ValueError: If input data is not a :class:`~pandas.DataFrame`.\n :ValueError: If :class:`~pandas.DataFrame` do not has the proper shape.\n :ValueError: If ``bcolors`` of ``bmeans`` are provided with sizes different than 2.\n\n .. rubric:: Example\n\n .. ipython::\n\n In [1]: from rstoolbox.plot import plot_96wells\n ...: import numpy as np\n ...: import pandas as pd\n ...: import matplotlib.pyplot as plt\n ...: np.random.seed(0)\n ...: df = pd.DataFrame(np.random.randn(8, 12))\n ...: fig, ax = plot_96wells(cdata = df, sdata = -df, bdata = df<0)\n ...: plt.subplots_adjust(left=0.1, right=0.8, top=0.9, bottom=0.1)\n\n @savefig plot_96wells_docs.png width=5in\n In [2]: plt.show()\n \"\"\"\n\n # Changes in one of this parameters should change others to ensure size fit.\n fig = plt.figure(figsize=(15, 7))\n ax = plt.subplot2grid((1, 1), (0, 0), fig=fig)\n top = 2000\n bot = 50\n sizeOfFont = 15\n ticks_font = font_manager.FontProperties(style='normal', size=sizeOfFont, weight='normal')\n\n # Fixed: THIS CANNOT CHANGE!\n kwargs['x'] = list(range(1, 13)) * 8\n kwargs['y'] = sorted(list(range(1, 9)) * 12)\n\n # Modified by the input data.\n kwargs.setdefault('s', [top, ] * len(kwargs['y']))\n kwargs.setdefault('c', 'white')\n kwargs.setdefault('edgecolor', ['black', ] * len(kwargs['y']))\n kwargs.setdefault('linewidths', 1.5)\n kwargs.setdefault('cmap', \"Blues\")\n\n # Color Data\n if cdata is not None:\n if not isinstance(cdata, pd.DataFrame):\n raise ValueError('Wrong data type')\n if cdata.shape != (8, 12):\n raise ValueError('Wrong data shape')\n kwargs['c'] = cdata.values.flatten()\n\n # Size Data\n if sdata is not None:\n if not isinstance(sdata, pd.DataFrame):\n raise ValueError('Wrong data type')\n if sdata.shape != (8, 12):\n raise ValueError('Wrong data shape')\n p = sdata.values.flatten()\n p = ((p - np.min(p)) / np.ptp(p)) * (top - bot) + bot\n kwargs['s'] = p\n\n # Border Data\n if bdata is not None:\n if not isinstance(bdata, pd.DataFrame):\n raise ValueError('Wrong data type')\n if bdata.shape != (8, 12):\n raise ValueError('Wrong data shape')\n if not (bdata.dtypes == bool).all():\n raise ValueError('bdata has to be booleans')\n if bcolors is None:\n bcolors = ['black', 'green']\n if bmeans is None:\n bmeans = ['True', 'False']\n if len(bcolors) < 2:\n raise ValueError('At least to border colors need to be provided')\n if len(bmeans) < 2:\n raise ValueError('At least to binary names need to be provided')\n b = bdata.values.flatten()\n b = [bcolors[0] if _ else bcolors[1] for _ in b]\n kwargs['edgecolor'] = b\n\n # PLOT\n mesh = ax.scatter(**kwargs)\n\n # Make Color Bar\n if cdata is not None:\n plt.colorbar(mesh, fraction=0.046, pad=0.04)\n\n # Make Size Legend\n slegend = None\n if sdata is not None:\n poslab = 1.35 if cdata is not None else 1\n p = sdata.values.flatten()\n medv = ((max(p) - min(p)) / 2) + min(p)\n topl = \"{:.2f}\".format(max(sdata.values.flatten()))\n botl = \"{:.2f}\".format(min(sdata.values.flatten()))\n medl = \"{:.2f}\".format(medv)\n medv = ((medv - np.min(p)) / np.ptp(p)) * (top - bot) + bot\n\n legend_elements = [\n Line2D([0], [0], marker='o', color='w', label=topl,\n markeredgecolor='black', markersize=math.sqrt(top)),\n Line2D([0], [0], marker='o', color='w', label=medl,\n markeredgecolor='black', markersize=math.sqrt(medv)),\n Line2D([0], [0], marker='o', color='w', label=botl,\n markeredgecolor='black', markersize=math.sqrt(bot)),\n ]\n\n slegend = ax.legend(handles=legend_elements, labelspacing=5.5,\n handletextpad=2, borderpad=2,\n bbox_to_anchor=(poslab, 1.015))\n\n # Make Border Legend\n if bdata is not None:\n poslab = 1.35 if cdata is not None else 1\n legend_elements = [\n Line2D([0], [0], marker='o', color='w', label=bmeans[0],\n markeredgecolor=bcolors[0], markersize=math.sqrt(top)),\n Line2D([0], [0], marker='o', color='w', label=bmeans[1],\n markeredgecolor=bcolors[1], markersize=math.sqrt(top))\n ]\n\n ax.legend(handles=legend_elements, labelspacing=5.5,\n handletextpad=2, borderpad=2,\n bbox_to_anchor=(poslab, 0.32))\n if slegend is not None:\n ax.add_artist(slegend)\n\n # Image aspects\n ax.grid(False)\n ax.set_xticks(range(1, 13))\n ax.xaxis.tick_top()\n ax.set_yticks(range(1, 9))\n ax.set_yticklabels(string.ascii_uppercase[0:9])\n ax.set_ylim((8.5, 0.48))\n ax.set_aspect(1)\n ax.tick_params(axis='both', which='both', length=0)\n for spine in ax.spines.values():\n spine.set_visible(False)\n\n for label in ax.get_xticklabels():\n label.set_fontproperties(ticks_font)\n\n for label in ax.get_yticklabels():\n label.set_fontproperties(ticks_font)\n\n return fig, ax\n\n\ndef plot_thermal_melt( df, ax, linecolor=0, pointcolor=0, min_temperature=None ):\n \"\"\"Plot `Thermal Melt `_ data.\n\n Plot thermal melt and generate the fitting curve to the pointsself.\n\n The provied :class:`~pandas.DataFrame` must contain, at least, the following\n columns:\n\n =============== ===================================================\n Column Name Data Content\n =============== ===================================================\n **Temp** Temperatures (celsius).\n **MRE** Value at each temperature (10 deg^2 cm^2 dmol^-1).\n =============== ===================================================\n\n :param df: Data container.\n :type df: :class:`~pandas.DataFrame`\n :param ax: Axis in which to plot the data.\n :type ax: :class:`~matplotlib.axes.Axes`\n :param linecolor: Color for the fitting line. If a number, it takes from the current\n :mod:`seaborn` palette.\n :type linecolor: Union[:class:`int`, :class:`str`]\n :param pointcolor: Color for the points. If a number, it takes from the current\n :mod:`seaborn` palette.\n :type pointcolor: Union[:class:`int`, :class:`str`]\n :param float min_temperature: If provided, set minimum temperature in the Y axis\n of the plot.\n\n .. rubric:: Example\n\n .. ipython::\n\n In [1]: from rstoolbox.plot import plot_thermal_melt\n ...: import numpy as np\n ...: import pandas as pd\n ...: import matplotlib.pyplot as plt\n ...: df = pd.read_csv(\"../rstoolbox/tests/data/thermal_melt.csv\")\n ...: fig = plt.figure(figsize=(10, 6.7))\n ...: ax = plt.subplot2grid((1, 1), (0, 0))\n ...: plot_thermal_melt(df, ax)\n\n @savefig plot_tmelt_docs.png width=5in\n In [2]: plt.show()\n\n \"\"\"\n if isinstance(linecolor, int):\n linecolor = sns.color_palette()[linecolor]\n fit = np.poly1d(np.polyfit(df['Temp'].values, df['MRE'].values, 4))\n ax.plot(df['Temp'].values, fit(df['Temp'].values), color=linecolor)\n\n if isinstance(pointcolor, int):\n pointcolor = sns.color_palette()[pointcolor]\n ax.plot(df['Temp'].values, df['MRE'].values, marker='s', linestyle='None', color=pointcolor)\n\n ax.set_ylabel(r'MRE(10 deg$^3$ cm$^2$ dmol$^-1$)')\n ax.set_xlabel(r'Temperature ($^\\circ$C)')\n\n ax.set_xlim(ax.get_xlim()[0] if min_temperature is None else min_temperature)\n ax.set_ylim(ymax=0)\n\n\ndef plot_MALS( df, ax, uvcolor=0, lscolor=1, mwcolor=2, max_voltage=None, max_time=None ):\n \"\"\"Plot\n `Multi-Angle Light Scattering `_\n data.\n\n The provied :class:`~pandas.DataFrame` must contain, at least, the following\n columns:\n\n =============== ===================================================\n Column Name Data Content\n =============== ===================================================\n **Time** Time (min).\n **UV** UV data (V).\n **LS** Light Scattering data (V).\n **MW** Molecular Weight (Daltons).\n =============== ===================================================\n\n :param df: Data container.\n :type df: :class:`~pandas.DataFrame`\n :param ax: Axis in which to plot the data.\n :type ax: :class:`~matplotlib.axes.Axes`\n :param uvcolor: Color for the UV data. If a number, it takes from the current\n :mod:`seaborn` palette. If :data:`False`, UV data is not plotted.\n :type uvcolor: Union[:class:`int`, :class:`str`]\n :param lscolor: Color for the LS data. If a number, it takes from the current\n :mod:`seaborn` palette. If :data:`False`, LS data is not plotted.\n :type lscolor: Union[:class:`int`, :class:`str`]\n :param mwcolor: Color for the MW data. If a number, it takes from the current\n :mod:`seaborn` palette. If :data:`False`, MW data is not plotted.\n :type mwcolor: Union[:class:`int`, :class:`str`]\n :param float max_voltage: If provided, set maximum voltage in the Y axis\n of the plot.\n :param float max_time: If provided, set maximum time in the X axis\n of the plot.\n\n .. rubric:: Example\n\n .. ipython::\n\n In [1]: from rstoolbox.plot import plot_MALS\n ...: import numpy as np\n ...: import pandas as pd\n ...: import matplotlib.pyplot as plt\n ...: df = pd.read_csv(\"../rstoolbox/tests/data/mals.csv\")\n ...: fig = plt.figure(figsize=(10, 6.7))\n ...: ax = plt.subplot2grid((1, 1), (0, 0))\n ...: plot_MALS(df, ax)\n\n @savefig plot_mals_docs.png width=5in\n In [2]: plt.show()\n \"\"\"\n if lscolor is not False:\n if isinstance(lscolor, int):\n lscolor = sns.color_palette()[lscolor]\n df_ = df[np.isfinite(df['LS'])]\n ax.plot(df_['Time'].values, df_['LS'].values, color=lscolor, label='LS')\n if uvcolor is not False:\n if isinstance(uvcolor, int):\n uvcolor = sns.color_palette()[uvcolor]\n df_ = df[np.isfinite(df['UV'])]\n ax.plot(df_['Time'].values, df_['UV'].values, color=uvcolor, label='UV')\n\n # quarter = df['UV'].max()\n\n if max_voltage is not None:\n ax.set_ylim(0, max_voltage)\n else:\n ax.set_ylim(0, ax.get_ylim()[1])\n if max_time is not None:\n ax.set_xlim(0, max_time)\n else:\n ax.set_xlim(0)\n\n if mwcolor is not False:\n if isinstance(mwcolor, int):\n mwcolor = sns.color_palette()[mwcolor]\n ax2 = ax.twinx()\n df_ = df[np.isfinite(df['MW'])]\n ax2.plot(df_['Time'].values, df_['MW'].values, color=mwcolor)\n\n ax.set_ylabel('Detector Voltage (V)')\n ax.set_xlabel('Time (min)')\n ax.legend()\n\n meanW = sum(df_['MW'].values) / float(len(df_['MW'].values))\n maxW = (ax.get_ylim()[1] * meanW) / 0.8\n ax2.set_ylim(0, maxW)\n ax2.get_yaxis().set_visible(False)\n\n\ndef plot_CD( df, ax, color=0, wavelengths=None ):\n \"\"\"Plot `Circular Dichroism `_ data.\n\n The provied :class:`~pandas.DataFrame` must contain, at least, the following\n columns:\n\n =============== ===================================================\n Column Name Data Content\n =============== ===================================================\n **Wavelength** Wavelength (nm).\n **MRE** Value at each wavelength (10 deg^2 cm^2 dmol^-1).\n =============== ===================================================\n\n :param df: Data container.\n :type df: :class:`~pandas.DataFrame`\n :param ax: Axis in which to plot the data.\n :type ax: :class:`~matplotlib.axes.Axes`\n :param color: Color for the data. If a number, it takes from the current\n :mod:`seaborn` palette.\n :type color: Union[:class:`int`, :class:`str`]\n :param wavelengths: List with min and max wavelengths to plot.\n :type wavelengths: :func:`list` of :class:`float`\n\n .. rubric:: Example\n\n .. ipython::\n\n In [1]: from rstoolbox.plot import plot_CD\n ...: import numpy as np\n ...: import pandas as pd\n ...: import matplotlib.pyplot as plt\n ...: df = pd.read_csv(\"../rstoolbox/tests/data/cd.csv\")\n ...: fig = plt.figure(figsize=(10, 6.7))\n ...: ax = plt.subplot2grid((1, 1), (0, 0))\n ...: plot_CD(df, ax)\n\n @savefig plot_cd_docs.png width=5in\n In [2]: plt.show()\n \"\"\"\n if isinstance(color, int):\n color = sns.color_palette()[color]\n ax.plot(df['Wavelength'].values, df['MRE'].values, color=color)\n ax.plot(df['Wavelength'].values, [0, ] * len(df['Wavelength'].values),\n linestyle='dashed', color='grey')\n\n if isinstance(wavelengths, list) and len(wavelengths) == 2:\n ax.set_xlim(wavelengths[0], wavelengths[1])\n\n ax.set_ylabel(r'MRE(10 deg$^3$ cm$^2$ dmol$^-1$)')\n ax.set_xlabel('Wavelength (nm)')\n\n\ndef plot_SPR( df, ax, datacolor=0, fitcolor=0, max_time=None, max_response=None ):\n \"\"\"Plot `Surface Plasmon Resonance `_\n data.\n\n Plots **SPR** data as read by :func:`.read_SPR`. Only plots those concentrations for which\n a corresponding ``fitting curve`` exists.\n\n :param df: Data container.\n :type df: :class:`~pandas.DataFrame`\n :param ax: Axis in which to plot the data.\n :type ax: :class:`~matplotlib.axes.Axes`\n :param datacolor: Color for the raw data. If a number, it takes from the current\n :mod:`seaborn` palette.\n :type datacolor: Union[:class:`int`, :class:`str`]\n :param fitcolor: Color for the fitted data. If a number, it takes from the current\n :mod:`seaborn` palette.\n :type fitcolor: Union[:class:`int`, :class:`str`]\n :param float max_time: If provided, set maximum time in the X axis\n of the plot.\n :param float max_response: If provided, set maximum RU in the Y axis\n of the plot.\n\n .. seealso::\n :func:`.read_SPR`\n\n .. rubric:: Example\n\n .. ipython::\n\n In [1]: from rstoolbox.io import read_SPR\n ...: from rstoolbox.plot import plot_SPR\n ...: import pandas as pd\n ...: pd.set_option('display.width', 1000)\n ...: df = read_SPR(\"../rstoolbox/tests/data/spr_data.csv.gz\")\n ...: fig = plt.figure(figsize=(10, 6.7))\n ...: ax = plt.subplot2grid((1, 1), (0, 0))\n ...: plot_SPR(df, ax, datacolor='black', fitcolor='red')\n\n @savefig plot_spr_docs.png width=5in\n In [2]: plt.show()\n\n \"\"\"\n if isinstance(datacolor, int):\n datacolor = sns.color_palette()[datacolor]\n if isinstance(fitcolor, int):\n fitcolor = sns.color_palette()[fitcolor]\n\n conc = sorted(set(df['fitted'].columns.labels[0]))\n conc = df['fitted'].columns.levels[0].values[conc]\n\n raw = df['raw'][conc]\n fit = df['fitted'][conc]\n\n for curve in conc:\n data = raw[curve]\n ax.plot(data['X'].values, data['Y'].values, color=datacolor)\n data = fit[curve]\n ax.plot(data['X'].values, data['Y'].values, color=fitcolor)\n\n ax.set_ylabel('Response (RU)')\n ax.set_xlabel('Time (sec)')\n ax.set_xlim(0, ax.get_xlim()[1] if max_time is None else max_time)\n ax.set_ylim(0, ax.get_ylim()[1] if max_response is None else max_response)\n","sub_path":"rstoolbox/plot/experimental.py","file_name":"experimental.py","file_ext":"py","file_size_in_byte":18401,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"631262890","text":"import random\nimport statistics\nimport math\nimport configparser\nimport io\nimport os\n\n# Load the configuration file\nCONFIG = configparser.ConfigParser()\nCONFIG.read('./config/config.ini')\nCONFIG_MODEL = CONFIG['model']\nPROPERTY_INFLATION_PRICE = float(CONFIG_MODEL['property_buy_price_percentage'])\n\n# List of available strategies\nstrategyList = CONFIG_MODEL['active_strategies'].split(',')\n\n# Type of game\nACTIVE_GAME_TYPE = CONFIG_MODEL['game_type']\n\n\ndef emulateHawkDoveStrategy(hawk, dove):\n \"\"\"Hawk-Dove OR Dove-Hawk strategy\n\n Arguments:\n hawk {Agent} -- the hawkish agent\n dove {Agent} -- the dove agent\n \"\"\"\n # hawk gains resource\n if dove.owner > 0:\n hawk.owner = dove.owner\n dove.owner = 0\n hawk.saySomething('I am hawk. I gained ' + str(hawk.owner))\n # dove loses resource\n dove.saySomething('I am dove. I lost')\n\n\ndef emulateHawkHawkStrategy(hawkO, hawkNO):\n \"\"\"Hawk-Hawk strategy\n\n Arguments:\n hawkO {Agent} -- Hawk Owner Agent\n hawkNO {Agent} -- Hawk Intruder Agent\n \"\"\"\n owner = hawkO.owner\n h = getFightCost(owner)\n\n # if wealth/2 > h its the prisoners dilemma, otherwise its the chicken game\n # one of both will win while the other looses\n player = [hawkO, hawkNO]\n winner = random.choice(player)\n player.remove(winner)\n looser = player[0]\n # the winner is the (new) owner\n # the looser is no owner (anymore)\n # both have fighting costs that diminishes their wealth by h\n winner.wealth -= h\n winner.owner = owner\n looser.wealth -= h\n looser.owner = 0\n\n # Die if wealth is negative\n if looser.wealth < 0:\n looser.die()\n if winner.wealth < 0:\n winner.die()\n\n\ndef emulateDoveDoveStrategy(doveO, doveNO):\n \"\"\"Dove-Dove strategy\n\n Arguments:\n doveO {Agent} -- Dove Owner Agent\n doveNO {Agent} -- Dove Intruder Agent\n \"\"\"\n owner = doveO.owner\n player = [doveO, doveNO]\n # random dove retreats\n winner = random.choice(player)\n player.remove(winner)\n looser = player[0]\n # the winner takes it all\n winner.owner = owner\n looser.owner = 0\n winner.saySomething('I am dove ' +\n str(winner.unique_id) +\n '. I gained ' +\n str(owner))\n # the other dove doesn't gain anything\n looser.saySomething('I am dove ' + str(looser.unique_id) + \". I retreated\")\n\n\ndef emulateTradersStrategy(owner, intruder):\n \"\"\"Trading strategy\n\n Arguments:\n owner {Agent} -- Trader Owner Agent\n intruder {Agent} -- Trader Intruder Agent\n \"\"\"\n estimated_buying_price = owner.owner + \\\n (PROPERTY_INFLATION_PRICE * owner.owner)\n x = owner.owner + round((estimated_buying_price - owner.owner) / 2)\n owner.owner = 0\n owner.wealth += x\n intruder.owner = x\n intruder.wealth -= x\n owner.saySomething('We are trading')\n\n\n# Trader vs Trader with ToM0 or ToM1\ndef emulateTraderToMStrategy(owner, intruder):\n # intruder values the property V = 0.8 * intruder.wealth\n # owner values the property v = owner.owner\n # owner sells the property for x = (V + v) / 4\n # x = round((0.8 * intruder.wealth + owner.owner) / 2)\n v = owner.owner\n estimated_buying_price = v + (PROPERTY_INFLATION_PRICE * v)\n x = round((estimated_buying_price - v) / 4)\n owner.owner = 0\n owner.wealth += v + x\n intruder.owner = v + 3 * x\n intruder.wealth -= v + 3 * x\n owner.saySomething('We are trading')\n\n\n# Trader with ToM0 or ToM1 vs Trader\ndef emulateToMTraderStrategy(owner, intruder):\n # intruder values the property V = 0.8 * intruder.wealth\n # owner values the property v = owner.owner\n # owner sells the property for x = (V + v) / 4\n # x = round((0.8 * intruder.wealth + owner.owner) / 2)\n v = owner.owner\n estimated_buying_price = v + (PROPERTY_INFLATION_PRICE * v)\n x = round((estimated_buying_price - v) / 4)\n\n owner.owner = 0\n owner.wealth += v + 3 * x\n intruder.owner = v + x\n intruder.wealth -= v + x\n\n owner.saySomething('We are trading')\n\n\n# Trader with ToM0 or ToM1 vs Trader with ToM0 or ToM1\ndef emulateToMToMStrategy(owner, intruder):\n # v = owner.owner\n # estimated_buying_price = v + (PROPERTY_INFLATION_PRICE * v)\n #print(\"initial property owner:\", owner.owner, \"\\t \\t initial wealth owner:\", owner.wealth)\n #print(\"initial property intruder:\", intruder.owner, \"\\t \\t initial wealth intruder:\", intruder.wealth)\n p = owner.ToMAgent.play(intruder.ToMAgent)\n if p != None:\n x = p * intruder.wealth\n #print(\"excess paied:\",x)\n\n owner.owner = 0\n owner.wealth += x\n intruder.owner = x\n intruder.wealth -= x\n\n #print(\"final property owner:\", owner.owner, \"\\t \\tfinal wealth owner:\", owner.wealth)\n #print(\"final property intruder:\", intruder.owner, \"\\t \\tfinal wealth intruder:\", intruder.wealth)\n #print(\"____________________________________________________________________________________\")\n\n\n# Get cost of interaction or fight\ndef getFightCost(V):\n \"\"\"Get cost of interaction or fight\n\n Arguments:\n V {integer} -- Value of property being fought\n\n Returns:\n integer -- cost of the fight\n \"\"\"\n h = 0\n if ACTIVE_GAME_TYPE == 'prisoners-dilema':\n h = round(random.uniform(0, V / 2))\n elif ACTIVE_GAME_TYPE == 'chicken-game':\n h = round(random.uniform(V/2, V))\n elif ACTIVE_GAME_TYPE == 'no-predefined-game-type':\n h = round(random.uniform(0, V))\n return h\n\n\ndef naturalSelection(model):\n \"\"\"Kill agents with bad performing strategies and replicate the good strategies\n\n Arguments:\n model {Model} -- Mesa model object\n \"\"\"\n all_agents = model.schedule.agents\n agent_wealths = [agent.owner + agent.wealth for agent in all_agents]\n average_wealth = statistics.mean(agent_wealths)\n\n for strategy in strategyList:\n # get fresh list of agents after each iteration\n all_agents = model.schedule.agents\n strategy_specific_agents = [\n agent for agent in all_agents if agent.strategy == strategy]\n if len(strategy_specific_agents) == 0:\n continue\n strategy_specific_wealth = [\n agent.wealth + agent.owner for agent in strategy_specific_agents]\n strategy_average_wealth = statistics.mean(strategy_specific_wealth)\n\n # If this is a loosing strategy - kill weakest agents using this strategy\n # No. of agents to kill is proportional to how less the average\n # strategy wealth is below the overall average wealth\n if average_wealth > strategy_average_wealth:\n percentage_to_kill = (\n average_wealth - strategy_average_wealth) / average_wealth\n num_agents_to_kill = math.floor(\n percentage_to_kill * len(strategy_specific_agents))\n agents_to_kill = sorted(strategy_specific_agents, key=lambda agent: agent.wealth + agent.owner)[\n :num_agents_to_kill]\n for agent in agents_to_kill:\n agent.die()\n\n for strategy in strategyList:\n # get fresh list of agents after each iteration\n all_agents = model.schedule.agents\n strategy_specific_agents = [\n agent for agent in all_agents if agent.strategy == strategy]\n if len(strategy_specific_agents) == 0:\n continue\n strategy_specific_wealth = [\n agent.wealth + agent.owner for agent in strategy_specific_agents]\n strategy_average_wealth = statistics.mean(strategy_specific_wealth)\n\n # If this is a winning strategy - replicate more agents with this strategy\n # No. of replications is proportional to how high the average strategy\n # wealth is above the overall average wealth\n if strategy_average_wealth > average_wealth:\n percentage_to_replicate = (\n strategy_average_wealth - average_wealth) / average_wealth\n num_agents_to_replicate = math.floor(\n percentage_to_replicate * len(strategy_specific_agents))\n agents_to_replicate = random.sample(\n strategy_specific_agents, num_agents_to_replicate)\n\n # Give property to a defined percentage of agents\n num_owners = round(\n (int(CONFIG_MODEL['percentage_of_owners']) / 100) * num_agents_to_replicate)\n owner_agents = random.sample(agents_to_replicate, num_owners)\n\n # reproduce agents with property\n for agent in agents_to_replicate:\n reborn = agent.reproduce()\n if agent in owner_agents:\n reborn.assignPropertyToAgent()","sub_path":"strategies.py","file_name":"strategies.py","file_ext":"py","file_size_in_byte":8785,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"445107996","text":"import requests\n\nbase_url = \"https://api.telegram.org/bot{token}/{method}\"\n\ndef send_message(token, chat_id, text, reply_markup=None):\n url = base_url.format(token=token, method='sendMessage')\n\n headers = {'Content-Type': 'application/json'}\n\n payload = {\n 'chat_id': chat_id,\n 'text': text,\n 'reply_markup': {\n 'inline_keyboard': reply_markup\n }\n }\n r = requests.post(url, json=payload, headers=headers)\n if r.status_code == requests.codes.ok:\n return r.json.get('ok')\n else:\n return r.text\n\n\ndef send_chat_action(token, chat_id, action):\n \"\"\"Tell the user that something is happening on the bot's side.\n\n Args:\n token (String): telegram bot token\n chat_id (String): Unique identifier for the target chat or username of the target channel\n action (String): typing | upload_photo | record_video | upload_video | record_audio | upload_audio |\n upload_document | find_location | record_video_note | upload_video_note\n\n \"\"\"\n\n url = base_url.format(token=token, method='sendChatAction')\n\n headers = {'Content-Type': 'application/json'}\n\n payload = {\n 'chat_id': chat_id,\n 'action': action\n }\n\n r = requests.post(url, json=payload, headers=headers)\n\n if r.status_code == requests.codes.ok:\n return r.json().get('ok')\n else:\n return False\n\n\ndef send_photo(token, chat_id, photo, caption=None, reply_markup=None, parse_mode='Markdown'):\n \"\"\"Send a photo.\n\n Args:\n token (String): telegram bot token\n chat_id (String): Unique identifier for the target chat or username of the target channel\n photo (InputFile or String): file_id | url | file\n caption (String) : Photo caption. Optional.\n parse_mode (String) : Markdown or HTML. Optional.\n reply_markup (InlineKeyboardMarkup) : Additional interface options.\n \"\"\"\n\n url = base_url.format(token=token, method='sendPhoto')\n\n headers = {'Content-Type': 'application/json'}\n\n payload = {\n 'chat_id': chat_id,\n 'photo': photo,\n 'parse_mode': parse_mode,\n 'caption': caption,\n 'reply_markup': {\n 'inline_keyboard': [\n reply_markup\n ]\n }\n }\n r = requests.post(url, json=payload, headers=headers)\n\n if r.status_code == requests.codes.ok:\n return r.json().get('ok')\n else:\n return False\n","sub_path":"bothub/telegram_alpha.py","file_name":"telegram_alpha.py","file_ext":"py","file_size_in_byte":2460,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"7003970","text":"# Import the Libraries\nimport os\nimport sys\nimport argparse\nimport warnings\nfrom collections import defaultdict\nfrom pathlib import Path\nfrom timeit import default_timer as timer\n\nparent_dir = str(Path(__file__).parents[2])\nsys.path.insert(0, parent_dir)\n\nfrom lib.helpers.utils import read_json, write_json, read_tsv, concatenate_list_df, read_lines\nfrom lib.helpers.embedding_class import GetEmbeddings\nfrom lib.helpers.preprocessing_class import DataProcessing\n\n\n# For declaring and documenting the code\nparser = argparse.ArgumentParser(description='Wisdom Bot')\nparser.add_argument('--embedding_file', help='txt file containing embedding dictionary',\n default='full_conceptnet_dict.txt')\n#parser.add_argument('--list_of_quotes_files_to_emb', type=list, help='tsv file containing quotes', \\\n# default=['quotes.tsv'])\nparser.add_argument('--list_of_quotes_files_to_emb', type=list, help='tsv file containing quotes', \\\n default=['quotes.tsv'])\nparser.add_argument('--quotes_col_name', help='tsv file containing quotes', default='Quotes')\nparser.add_argument('--human_queries_col_name', help='tsv file containing quotes', default='Queries')\nparser.add_argument('--keywords_col_name', help='tsv file containing quotes', default='Key_Words')\nparser.add_argument('--authors_col_name', help='tsv file containing quotes', default='Author')\n\n\n# Ignore python warnings\nif not sys.warnoptions:\n warnings.simplefilter(\"ignore\")\n\n\ndef read_quotes_data_list(quotes_data_folder, list_of_quotes_files_to_emb):\n\n quotes_df_list = []\n\n for quote_file_name in list_of_quotes_files_to_emb:\n\n quote_file_path = os.path.join(quotes_data_folder, quote_file_name)\n quote_df = read_tsv(quote_file_path)\n quotes_df_list.append(quote_df)\n\n return quotes_df_list\n\n\ndef get_quotes_emb_dict(quotes_df_processed, col_name_emb, quote_col_name, emb_dict, idf_dict, stop_words):\n\n ge = GetEmbeddings(emb_dict)\n\n required_emb_dict = defaultdict(str)\n\n ret_sent_list = quotes_df_processed[col_name_emb]\n processed_ret_sent_list = quotes_df_processed['processed_' + col_name_emb]\n author_list = quotes_df_processed['Author']\n quote_col_list = quotes_df_processed[quote_col_name]\n id_col_list = quotes_df_processed['id']\n\n sent_dict = ge.sentences_list_embedding(processed_ret_sent_list, ret_sent_list, author_list, quote_col_list, id_col_list, idf_dict, stop_words)\n\n return sent_dict\n\n\ndef get_folders_paths(embedding_file):\n\n main_folder_path = str(Path(__file__).parents[1])\n\n output_dir = os.path.join(main_folder_path, 'data','output','dictionaries')\n axilliary_dir = os.path.join(main_folder_path, 'data','axillary')\n quotes_dir = os.path.join(main_folder_path, 'data','quotes')\n\n embedding_file = os.path.join(axilliary_dir, embedding_file)\n\n return output_dir, axilliary_dir, quotes_dir, embedding_file\n\n\nif __name__ == \"__main__\":\n\n start = timer()\n\n args = parser.parse_args()\n\n dp = DataProcessing()\n\n print('--- Get directories paths')\n output_dir, axilliary_dir, quotes_dir, embedding_file = get_folders_paths(args.embedding_file)\n\n print('--- Reading embeddings')\n emb_dict = read_json(os.path.join(axilliary_dir, embedding_file))\n #stop_words = read_lines(os.path.join(axilliary_dir, 'custom_stopwords'))\n stop_words = read_lines(os.path.join(axilliary_dir, 'nltk_stopwords'))\n\n print('--- Importing quotes datasets')\n quotes_df_list = read_quotes_data_list(quotes_dir, args.list_of_quotes_files_to_emb)\n\n print('--- Merging all quotes into a single dataframe')\n quotes_df = concatenate_list_df(quotes_df_list)\n hm_queries_quotes_df_formatted = dp.format_hm_queries(quotes_df, args.quotes_col_name, args.human_queries_col_name, args.authors_col_name, remove_nan=True)\n\n print('--- Data cleaning')\n quotes_df_processed = dp.cleaning_data(quotes_df, args.quotes_col_name, remove_nan = True)\n hm_queries_quotes_df_formatted = dp.cleaning_data(hm_queries_quotes_df_formatted, args.human_queries_col_name, remove_nan=True)\n keywords_df_processed = dp.cleaning_data(quotes_df, args.keywords_col_name, remove_nan=True)\n\n print('--- Compute IDF Scores')\n ge = GetEmbeddings(emb_dict)\n quotes_idf_dict = ge.compute_tf_idf(dp, list(set(quotes_df_processed['processed_Quotes'])))\n hm_queries_idf_dict = ge.compute_tf_idf(dp, list(set(hm_queries_quotes_df_formatted['processed_Queries'])))\n write_json(quotes_idf_dict, os.path.join(output_dir, 'quotes_word_idf_dict'))\n write_json(hm_queries_idf_dict, os.path.join(output_dir, 'hmq_word_idf_dict'))\n write_json({}, os.path.join(output_dir, 'keywords_emb_dict_idf_dict'))\n\n print('--- Get quotes embeddings dict')\n quotes_emb_dict = get_quotes_emb_dict(quotes_df_processed, args.quotes_col_name, args.quotes_col_name, emb_dict, quotes_idf_dict, stop_words)\n hmq_quotes_emb_dict = get_quotes_emb_dict(hm_queries_quotes_df_formatted, args.human_queries_col_name, args.quotes_col_name, emb_dict, hm_queries_idf_dict, stop_words)\n keywords_emb_dict = get_quotes_emb_dict(keywords_df_processed, args.keywords_col_name, args.quotes_col_name, emb_dict, {}, [])\n\n print('--- Save quotes embeddings dict')\n write_json(quotes_emb_dict, os.path.join(output_dir, 'quotes_emb_dict'))\n write_json(hmq_quotes_emb_dict, os.path.join(output_dir, 'hmq_quotes_emb_dict'))\n write_json(keywords_emb_dict, os.path.join(output_dir, 'keywords_quotes_emb_dict'))\n\n end = timer()\n\n end_time_min = round((end - start) / 60, 2)\n end_time_hour = round((end - start) / 3600, 2)\n\n print('Inference time in minutes: {}'.format(end_time_min))\n print('Inference time in hours : {}'.format(end_time_hour))","sub_path":"lib/embedders/main_corpus_embedding.py","file_name":"main_corpus_embedding.py","file_ext":"py","file_size_in_byte":5746,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"203569199","text":"#!usr/bin/env python\n\"\"\"\nthis is a queue example\n\"\"\"\n\nimport queue\nfrom time import sleep\nimport random\nimport threading\n\nTHREADS = []\n\n\nclass TestThread(threading.Thread):\n \"\"\"\n Attributes:\n queue\n \"\"\"\n def __init__(self, que):\n threading.Thread.__init__(self)\n self.queue = que\n\n def run(self):\n while True:\n item = self.queue.get()\n sleep(random.randrange(2, 3))\n print('queue is full, get {}'.format(item))\n self.queue.task_done()\n\n\ndef start_thread():\n \"\"\"\n aaa\n \"\"\"\n for thread in THREADS:\n thread.start()\n\nQ = queue.Queue(5)\n\n# 开启5个线程\nfor i in range(5):\n t = TestThread(Q)\n t.daemon = True\n # threads.append(t)\n t.start()\n\n# 总共有20个数据跑在五个线程里\nfor i in range(20):\n Q.put(i)\n\nQ.join()\n","sub_path":"thread_test.py","file_name":"thread_test.py","file_ext":"py","file_size_in_byte":845,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"572325943","text":"from ddparser import DDParser\nfrom main import build_conllx, cut_sent\nimport pandas as pd\nimport stanza\nfrom stanza.utils.conll import CoNLL\nimport spacy\n\n\nsample = open('sample_corpus.txt', 'r', encoding='utf-8').read()\nsample_sents = cut_sent(sample)\n\n'''Construct the sample corpus'''\n# begin ddparser\nddp = DDParser(use_pos=True)\ndata = ddp.parse(sample_sents)\nbuild_conllx(data, 'sample_ddparser.conllx')\nprint('DDParser has finished the parsing.')\n\n\n# begin SpaCy\nnlp = spacy.load('zh_core_web_sm')\nfile_spacy = open('sample_spacy.conllx', 'w', encoding ='utf-8')\n# file_spacy_gold = open('gold_spacy.conllx', 'r', encoding='utf-8')\nfor sent in sample_sents:\n file_spacy.write('\\n\\n')\n # file_spacy_gold.write('\\n\\n')\n for idx, token in enumerate(nlp(sent)):\n print(token.text)\n print(token.pos_)\n print(token.dep_)\n line = f'{idx+1}\\t{token.text}\\t{token.pos_}\\t{token.dep_}\\t{token.head}\\t{token.head.i}'\n file_spacy.write(line+'\\n')\n # file_spacy_gold.write(line + '\\n')\nfile_spacy.close()\n# file_spacy_gold.close()\nprint('SpaCy has finished the parsing.')\n\n# begin stanza\nstanza.download('zh', processors = 'tokenize, lemma, pos, depparse', logging_level='WARN')\nprint('Downloading finished.')\nnlpp = stanza.Pipeline('zh', processors = 'tokenize, lemma, pos, depparse', logging_level = 'WARN') #keep logging and only printing errors and warnings\nprint('Pipeline is ready.')\nfile_stanza = open('sample_stanza.conllx', 'w', encoding='utf-8')\n# file_stanza_gold = open('gold_stanza.conllx', 'r', encoding='utf-8')\nfor idx, sent in enumerate(sample_sents):\n # file_stanza_gold.write('\\n\\n' + '# ' + str(idx) + '\\n' + '#' + sent)\n dicts = nlpp(sent)\n dicts = dicts.to_dict()\n conll = CoNLL.convert_dict(dicts)\n for token in conll:\n file_stanza.write('\\n')\n # file_stanza_gold.write('\\n')\n for id, info in enumerate(token):\n file_stanza.write('\\n')\n # file_stanza_gold.write('\\n')\n for x in info:\n print(x)\n file_stanza.write(x+\"\\t\")\n # file_stanza_gold.write(x + \"\\t\")\n\nprint('Stanza has finished the parsing.')\n\n'''The following codes are related to accuracy tests of three models.'''\n# Read the dataframe\n\ndf_spacy_gold = pd.read_csv(\"gold_spacy.conllx\", delimiter='\\t')\ndf_spacy = pd.read_csv('sample_spacy.conllx', delimiter = '\\t')\ndf_ddparser= pd.read_csv('sample_ddparser.conllx', delimiter ='\\t', header= None)\ndf_ddparser_gold = pd.read_csv('gold_ddparser.conllx', delimiter='\\t', header = None)\ndf_ddparser_gold.columns = ['ID', 'FORM','LEMMA','POS','FEATS','HEAD','DEPREL']\ndf_stanza_gold = pd.read_csv('gold_stanza.conllx', delimiter='\\t')\ndf_stanza = pd.read_csv('sample_stanza.conllx', delimiter='\\t')\n\n\n'''Accuracy test of SpaCy'''\n# read the head column in the sample corpus and gold corpus respectively\nhead_spacy = df_spacy_gold[df_spacy_gold.columns[4]]\nhead_spacy2 = df_spacy[df_spacy.columns[4]]\n# read the deprel column in the sample corpus and gold corpus respectively\nrel_spacy = df_spacy_gold[df_spacy_gold.columns[3]]\nrel_spacy2 = df_spacy[df_spacy.columns[3]]\n\n# read the pos column in the sample corpus and gold corpus respectively\npos_spacy = df_spacy_gold[df_spacy_gold.columns[2]]\npos_spacy2 = df_spacy[df_spacy.columns[2]]\n\n# find the misassigned head\nmishead_spacy = []\nlas_spacy = []\npostag_spacy=[]\nfor i in range(len(head_spacy2)):\n if head_spacy[i] != head_spacy2[i]:\n mishead_spacy.append(head_spacy[i])\n\n# find the correctly assigned head and deprel\nfor i in range(len(head_spacy)):\n if head_spacy[i] == head_spacy2[i]:\n if rel_spacy[i] == rel_spacy2[i]:\n las_spacy.append(rel_spacy[i])\n\n# find the correctly assigned pos tag\nfor i in range(len(pos_spacy2)):\n if pos_spacy[i] == pos_spacy2[i]:\n postag_spacy.append(pos_spacy2[i])\n\n'''Accuracy test of DDParser'''\n# read the head column in the sample corpus and gold corpus respectively\nhead_ddparser = df_ddparser_gold[df_ddparser_gold.columns[5]]\nhead_ddparser2 = df_ddparser[df_ddparser.columns[5]]\n\n# read the deprel column in the sample corpus and gold corpus respectively\nrel_ddparser = df_ddparser_gold[df_ddparser_gold.columns[6]]\nrel_ddparser2 = df_ddparser[df_ddparser.columns[6]]\n\n# read the pos column in the sample corpus and the gold corpus respectively\npos_ddparser = df_ddparser_gold[df_ddparser_gold.columns[3]]\npos_ddparser2 = df_ddparser[df_ddparser.columns[3]]\n\n\n\nmishead_ddparser = []\nlas_ddparser = []\npostag_ddparser =[]\n\n# find the misassigned head\nfor i in range(len(head_ddparser2)):\n if head_ddparser[i] != head_ddparser2[i]:\n mishead_ddparser.append(rel_ddparser[i])\n\n# find the correctly assigned head and deprel\nfor i in range(len(head_ddparser)):\n if head_ddparser[i] == head_ddparser2[i]:\n if rel_ddparser[i] == rel_ddparser2[i]:\n las_ddparser.append(rel_ddparser[i])\n\n# find the correctly assigned pos tag\nfor i in range(len(pos_ddparser2)):\n if pos_ddparser[i] == pos_ddparser2[i]:\n postag_ddparser.append(pos_ddparser2[i])\n\n'''Accuracy test of stanza'''\n# read the head column in the sample corpus and gold corpus respectively\nhead_stanza = df_stanza_gold[df_stanza_gold.columns[6]]\nhead_stanza2 = df_stanza[df_stanza.columns[6]]\n\n# read the deprel column in the sample corpus and gold corpus respectively\nrel_stanza = df_stanza_gold[df_stanza_gold.columns[7]]\nrel_stanza2 = df_stanza[df_stanza.columns[7]]\n\n#read the pos column in the sample corpus and gold corpus respectively\npos_stanza = df_stanza_gold[df_stanza_gold.columns[3]]\npos_stanza2 = df_stanza[df_stanza.columns[3]]\nmishead_stanza = []\nlas_stanza = []\npostag_stanza =[]\n# find the misassigned head\nfor i in range(len(head_stanza2)):\n if head_stanza2[i] != head_stanza[i]:\n mishead_stanza.append(head_stanza[i])\n\n# find the correctly assigned head and deprel\nfor i in range(len(head_stanza2)):\n if head_stanza2[i] == head_stanza[i]:\n if rel_stanza[i] == rel_stanza2[i]:\n las_stanza.append(rel_stanza[i])\n\n# find the correctly assigned pos tag\nfor i in range(len(pos_stanza2)):\n if pos_stanza[i] == pos_stanza2[i]:\n postag_stanza.append(pos_stanza[i])\n\n\n# Get the UAS and LAS of the parsing results of different parsers.\nprint('The UAS of stanza is: ')\nprint(format((1-len(mishead_stanza)/len(head_stanza))*100,'.2f'), '%')\nprint('The LAS of staza is: ')\nprint(format(len(las_stanza)*100/len(head_stanza), '.2f'), '%')\nprint('The UAS of SapCay is: ')\nprint(format((1-len(mishead_spacy)/len(head_spacy2))*100,'.2f'), '%')\nprint('The LAS of SapCay is: ')\nprint(format(len(las_spacy)*100/len(head_spacy), '.2f'), '%')\nprint('The UAS of DDParser is: ')\nprint(format((1-len(mishead_ddparser)/len(head_ddparser2))*100,'.2f'), '%')\nprint('The LAS of DDParser is: ')\nprint(format(len(las_ddparser)*100/len(head_ddparser), '.2f'), '%')\n\n# get the pos tag accuracy\nprint('The POS arruracy of ddparser is ')\nprint(format(len(postag_ddparser)/len(pos_ddparser)*100, '.2f'), '%')\nprint('The POS arruracy of Spacy is ')\nprint(format(len(postag_spacy)/len(pos_spacy)*100, '.2f'), '%')\nprint('The POS arruracy of stanza is ')\nprint(format(len(postag_stanza)/len(pos_stanza)*100, '.2f'), '%')\n\n'''NER OF THREE MODELS'''\n\n# compute the NER accuracy of ddparser\n\n# read the named entity text\nentity = pd.read_csv(\"named_entities.csv\", sep=',')\nwords = list(entity.word)\nmydict = dict(zip(entity.word, entity.pos))\nddp_token=[]\nddp_pos =[]\n\nfor sent in data:\n for i, word in enumerate(sent['word']):\n if word in words:\n ddp_token.append(word)\n if sent['postag'][i] == mydict[word]:\n ddp_pos.append(sent['postag'][i])\n\nrecall_ddp = round(len(ddp_token)/len(words),2)\nprecision_ddp = round(len(ddp_pos)/len(ddp_token),2)\nf1_ddp = round(2*recall_ddp*precision_ddp/(recall_ddp+precision_ddp),2)\n\n\n# Form two lists containing the token and its pos tag respectively.\nspacy_token=[]\nspacy_pos =[]\nfor sent in sample_sents:\n for token in nlp(sent):\n spacy_token.append(token.text)\n spacy_pos.append(token.pos_)\n\n\nstanza_token = []\nstanza_pos =[]\nfor sent in sample_sents:\n parsed_stanza= nlpp(sent).to_dict()\n for token in parsed_stanza:\n for inf in token:\n stanza_token.append(inf['text'])\n stanza_pos.append(inf['upos'])\n\n# define a function to calculate the NER accuracy of SpaCy and Stanza\n# as the named entities are labeled as PROPN in both models\ndef ner(lst1, lst2):\n name_recall =[]\n name_prec =[]\n for i, word in enumerate(lst1):\n if word in words:\n name_recall.append(word)\n if lst2[i] =='PROPN':\n name_prec.append(token)\n recall = round(len(name_recall)/len(words),2)\n precision = round(len(name_prec)/len(name_recall),2)\n f1 = round(recall*precision*2/(recall+precision),2)\n return recall, precision,f1\n\nprint('The NER recall, precision and F1 of SpaCy is ', ner(spacy_token, spacy_pos))\nprint('The NER recall, precision and F1 of DDParser is ', recall_ddp, precision_ddp, f1_ddp)\nprint('The NER recall, precision and F1 of stanza is ', ner(stanza_token, stanza_pos))\n\n","sub_path":"Accuracy test/accuracy_test_of_parsers.py","file_name":"accuracy_test_of_parsers.py","file_ext":"py","file_size_in_byte":9197,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"256067574","text":"from datetime import datetime\nfrom aiden import Aiden\n\naiden = Aiden()\n\n\nclass DateTime:\n @staticmethod\n def current_time():\n local_time = datetime.now().time().strftime(\"%H:%M:%S\")\n print(local_time)\n aiden.speak(local_time)\n\n @staticmethod\n def current_date():\n local_date = datetime.today().date()\n day = DateTime.get_weekday(local_date.weekday())\n print(\"{}, {}\".format(day, local_date))\n aiden.speak(\"Today is {}, {}\".format(day, local_date))\n\n @staticmethod\n def get_weekday(day_num):\n return {\n 0: \"Monday\",\n 1: \"Tuesday\",\n 2: \"Wednesday\",\n 3: \"Thursday\",\n 4: \"Friday\",\n 5: \"Saturday\",\n 6: \"Sunday\",\n }[day_num]\n","sub_path":"time.py","file_name":"time.py","file_ext":"py","file_size_in_byte":777,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"364969575","text":"\"\"\"This module has tests for the change_detection functions.\"\"\"\n\n# This is free and unencumbered software released into the public domain.\n#\n# The authors of autocnet do not claim copyright on the contents of this file.\n# For more details about the LICENSE terms and the AUTHORS, you will\n# find files of those names at the top level of this repository.\n#\n# SPDX-License-Identifier: CC0-1.0\n\nimport contextlib\nimport unittest\nfrom pathlib import Path\nfrom subprocess import CalledProcessError\nfrom unittest.mock import patch\n\nfrom autocnet.utils import hirise\n\nclass TestISIS(unittest.TestCase):\n\n def setUp(self) -> None:\n self.resourcedir = Path(\"test-resources\")\n red50img = self.resourcedir / \"PSP_010502_2090_RED5_0.img\"\n red51img = self.resourcedir / \"PSP_010502_2090_RED5_1.img\"\n\n if not all((red50img.exists(), red51img.exists())):\n self.skipTest(\n f\"One or more files is missing from the {self.resourcedir} \"\n \"directory. Tests on real files skipped.\")\n\n def tearDown(self):\n with contextlib.suppress(FileNotFoundError):\n for g in (\"*.cub\", \"*.log\"):\n for p in self.resourcedir.glob(g):\n p.unlink()\n Path(\"print.prt\").unlink()\n\n def test_ingest_hirise(self):\n hirise.ingest_hirise(str(self.resourcedir))\n self.assertTrue((\n self.resourcedir / \"PSP_010502_2090_RED5.stitched.norm.cub\"\n ).exists())\n\n with patch(\n \"kalasiris.hi2isis\",\n side_effect=CalledProcessError(returncode=1, cmd=\"foo\")\n ):\n hirise.ingest_hirise(str(self.resourcedir))\n\n def test_segment_hirise(self):\n hirise.ingest_hirise(str(self.resourcedir))\n hirise.segment_hirise(str(self.resourcedir))\n base = self.resourcedir / \"PSP_010502_2090_RED5.stitched.norm.cub\"\n for f in (\n base.with_suffix(\".1_1325.cub\"),\n base.with_suffix(\".725_2349.cub\"),\n base.with_suffix(\".1749_3373.cub\"),\n base.with_suffix(\".2773_4000.cub\"),\n ):\n self.assertTrue(f.exists())","sub_path":"autocnet/utils/tests/test_hirise.py","file_name":"test_hirise.py","file_ext":"py","file_size_in_byte":2145,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"380888151","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\nimport os\n\nimport re\n\nPASTA_MAROTINHA = r''\n\ntokenRE = re.compile(\n r'\\\"(?P.[^\\\"]+)\\\"[\\t\\s]+\\\"(?P.[^\\\"]+)\\\"[\\n\\r][\\s\\t]*\\\"\\[english\\](?P=gabriel)\\\"[\\t\\s]+\\\"(?P.[^\\\"]+)\\\"',\n re.DOTALL)\nlineWithCaptionRE = re.compile(r'(\\<.[^>]+\\>){1,2}([\\w\\d\\s]+:\\s)?(?P.+)', re.DOTALL)\nescapeCharRE = re.compile(r\"\\||\\*|''+|\\[\\[+|~\")\n\narquivosdetextomarotos = {}\n\nqqeutofazendodaminhavida = {}\n\ndef jose_limpo(jose):\n res = lineWithCaptionRE.match(jose)\n if res:\n jose_limpo = res.group('line').strip()\n else:\n jose_limpo = jose.strip()\n\n return jose_da_escapada(jose_limpo)\n\n\ndef jose_da_escapada(jose):\n if escapeCharRE.search(jose):\n return '{0}'.format(jose)\n return jose\n\n\ndicionario_traduzido = {}\nfor idioma in arquivosdetextomarotos:\n with open(PASTA_MAROTINHA + os.sep + arquivosdetextomarotos[idioma], 'rb') as f:\n content = unicode(f.read(), \"utf-16\").encode(\"utf-8\")\n matches = tokenRE.findall(content)\n for match in matches:\n gabriel, jose_poliglota, jose_original = match\n if gabriel not in dicionario_traduzido:\n dicionario_traduzido[gabriel] = {'en': jose_original, idioma: jose_poliglota}\n else:\n dicionario_traduzido[gabriel][idioma] = jose_poliglota\n\noutput = {}\nfor gabriel in sorted(dicionario_traduzido.keys()):\n if not gabriel.startswith(''):\n continue\n final, maria = tuple(gabriel.split('_', 1))\n final = qqeutofazendodaminhavida[final]\n maria = maria.replace('_', ' ').lower()\n clones_de_jose = dicionario_traduzido[gabriel]\n dicionario = '\\n\\n{jose}:'.format(final=final.lower(), jose=jose_limpo(clones_de_jose['en'].lower()), maria=maria)\n dicionario += '\\n en: {jose}'.format(jose=jose_limpo(clones_de_jose['en']))\n\n idiomas = clones_de_jose.keys()\n idiomas.remove('en')\n for idioma in sorted(idiomas):\n dicionario += '\\n {idioma}: {jose}'.format(idioma=idioma, jose=jose_limpo(clones_de_jose[idioma]))\n output[final] = output.get(final, '') + dicionario\n\nwith open('barabba.txt', 'wb') as f:\n for final in sorted(output.keys()):\n f.write('\\n=== {0} ==='.format(final))\n f.write('\\n\\n')\n","sub_path":"valhalla/dict.py","file_name":"dict.py","file_ext":"py","file_size_in_byte":2368,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"530325080","text":"import click\n\nfrom globus_cli.helpers import CaseInsensitiveChoice\n\n\ndef add_and_update_opts(add=False):\n def inner_decorator(f):\n f = click.option('--hostname', required=add,\n help='Server Hostname.')(f)\n\n default_scheme = 'gsiftp' if add else None\n f = click.option(\n '--scheme', help='Scheme for the Server.',\n type=CaseInsensitiveChoice(('gsiftp', 'ftp')),\n default=default_scheme, show_default=add)(f)\n\n default_port = 2811 if add else None\n f = click.option(\n '--port', help='Port for Globus control channel connections.',\n type=int, default=default_port, show_default=add)(f)\n\n f = click.option(\n '--subject',\n help=('Subject of the X509 Certificate of the server. When '\n 'unspecified, the CN must match the server hostname.'))(f)\n\n return f\n return inner_decorator\n\n\ndef server_id_option(f):\n f = click.option('--server-id', required=True, help='ID of the Server')(f)\n return f\n","sub_path":"globus_cli/services/transfer/endpoint/server/helpers.py","file_name":"helpers.py","file_ext":"py","file_size_in_byte":1066,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"467174512","text":"# import custom JS animator\nfrom mlrefined_libraries.JSAnimation_slider_only import IPython_display_slider_only\n\n# import standard plotting and animation\nimport matplotlib.pyplot as plt\nimport matplotlib.animation as animation\nfrom IPython.display import clear_output\nimport time\nfrom matplotlib import gridspec\nfrom mpl_toolkits.mplot3d import proj3d\nfrom matplotlib.patches import FancyArrowPatch\nfrom matplotlib.text import Annotation\nfrom mpl_toolkits.mplot3d.proj3d import proj_transform\n\n# import autograd functionality\nfrom autograd import grad as compute_grad # The only autograd function you may ever need\nimport autograd.numpy as np\nimport math\n\ndef compare_2d3d(func1,func2,**kwargs):\n view = [20,-50]\n if 'view' in kwargs:\n view = kwargs['view']\n \n # construct figure\n fig = plt.figure(figsize = (12,4))\n \n # remove whitespace from figure\n fig.subplots_adjust(left=0, right=1, bottom=0, top=1) # remove whitespace\n fig.subplots_adjust(wspace=0.01,hspace=0.01)\n \n # create subplot with 3 panels, plot input function in center plot\n gs = gridspec.GridSpec(1, 3, width_ratios=[1,2,4]) \n \n ### draw 2d version ###\n ax1 = plt.subplot(gs[1]); \n grad = compute_grad(func1)\n \n # generate a range of values over which to plot input function, and derivatives\n w_plot = np.linspace(-3,3,200) # input range for original function\n g_plot = func1(w_plot)\n g_range = max(g_plot) - min(g_plot) # used for cleaning up final plot\n ggap = g_range*0.2\n w_vals = np.linspace(-2.5,2.5,200) \n\n # grab the next input/output tangency pair, the center of the next approximation(s)\n w_val = float(0)\n g_val = func1(w_val)\n\n # plot original function\n ax1.plot(w_plot,g_plot,color = 'k',zorder = 1,linewidth=2) \n\n # plot axis\n ax1.plot(w_plot,g_plot*0,color = 'k',zorder = 1,linewidth=1) \n # plot the input/output tangency point\n ax1.scatter(w_val,g_val,s = 80,c = 'lime',edgecolor = 'k',linewidth = 2,zorder = 3) # plot point of tangency\n\n #### plot first order approximation ####\n # plug input into the first derivative\n g_grad_val = grad(w_val)\n\n # determine width to plot the approximation -- so its length == width\n width = 4\n div = float(1 + g_grad_val**2)\n w1 = w_val - math.sqrt(width/div)\n w2 = w_val + math.sqrt(width/div)\n\n # compute first order approximation\n wrange = np.linspace(w1,w2, 100)\n h = g_val + g_grad_val*(wrange - w_val)\n\n # plot the first order approximation\n ax1.plot(wrange,h,color = 'lime',alpha = 0.5,linewidth = 3,zorder = 2) # plot approx\n \n #### clean up panel ####\n # fix viewing limits on panel\n v = 5\n ax1.set_xlim([-v,v])\n ax1.set_ylim([-1 - 0.3,v - 0.3])\n\n # label axes\n ax1.set_xlabel('$w$',fontsize = 12,labelpad = -60)\n ax1.set_ylabel('$g(w)$',fontsize = 25,rotation = 0,labelpad = 50)\n ax1.grid(False)\n ax1.yaxis.set_visible(False)\n ax1.spines['right'].set_visible(False)\n ax1.spines['top'].set_visible(False)\n ax1.spines['left'].set_visible(False)\n \n ### draw 3d version ###\n ax2 = plt.subplot(gs[2],projection='3d'); \n grad = compute_grad(func2)\n w_val = [float(0),float(0)]\n \n # define input space\n w_in = np.linspace(-2,2,200)\n w1_vals, w2_vals = np.meshgrid(w_in,w_in)\n w1_vals.shape = (len(w_in)**2,1)\n w2_vals.shape = (len(w_in)**2,1)\n w_vals = np.concatenate((w1_vals,w2_vals),axis=1).T\n g_vals = func2(w_vals) \n \n # evaluation points\n w_val = np.array([float(w_val[0]),float(w_val[1])])\n w_val.shape = (2,1)\n g_val = func2(w_val)\n grad_val = grad(w_val)\n grad_val.shape = (2,1) \n\n # create and evaluate tangent hyperplane\n w_tan = np.linspace(-1,1,200)\n w1tan_vals, w2tan_vals = np.meshgrid(w_tan,w_tan)\n w1tan_vals.shape = (len(w_tan)**2,1)\n w2tan_vals.shape = (len(w_tan)**2,1)\n wtan_vals = np.concatenate((w1tan_vals,w2tan_vals),axis=1).T\n\n #h = lambda weh: g_val + np.dot( (weh - w_val).T,grad_val)\n h = lambda weh: g_val + (weh[0]-w_val[0])*grad_val[0] + (weh[1]-w_val[1])*grad_val[1] \n h_vals = h(wtan_vals + w_val)\n zmin = min(np.min(h_vals),-0.5)\n zmax = max(np.max(h_vals),+0.5)\n\n # vals for cost surface, reshape for plot_surface function\n w1_vals.shape = (len(w_in),len(w_in))\n w2_vals.shape = (len(w_in),len(w_in))\n g_vals.shape = (len(w_in),len(w_in))\n w1tan_vals += w_val[0]\n w2tan_vals += w_val[1]\n w1tan_vals.shape = (len(w_tan),len(w_tan))\n w2tan_vals.shape = (len(w_tan),len(w_tan))\n h_vals.shape = (len(w_tan),len(w_tan))\n\n ### plot function ###\n ax2.plot_surface(w1_vals, w2_vals, g_vals, alpha = 0.5,color = 'w',rstride=25, cstride=25,linewidth=1,edgecolor = 'k',zorder = 2)\n\n ### plot z=0 plane ###\n ax2.plot_surface(w1_vals, w2_vals, g_vals*0, alpha = 0.1,color = 'w',zorder = 1,rstride=25, cstride=25,linewidth=0.3,edgecolor = 'k') \n\n ### plot tangent plane ###\n ax2.plot_surface(w1tan_vals, w2tan_vals, h_vals, alpha = 0.4,color = 'lime',zorder = 1,rstride=50, cstride=50,linewidth=1,edgecolor = 'k') \n\n # scatter tangency \n ax2.scatter(w_val[0],w_val[1],g_val,s = 70,c = 'lime',edgecolor = 'k',linewidth = 2)\n \n ### clean up plot ###\n # plot x and y axes, and clean up\n ax2.xaxis.pane.fill = False\n ax2.yaxis.pane.fill = False\n ax2.zaxis.pane.fill = False\n\n ax2.xaxis.pane.set_edgecolor('white')\n ax2.yaxis.pane.set_edgecolor('white')\n ax2.zaxis.pane.set_edgecolor('white')\n\n # remove axes lines and tickmarks\n ax2.w_zaxis.line.set_lw(0.)\n ax2.set_zticks([])\n ax2.w_xaxis.line.set_lw(0.)\n ax2.set_xticks([])\n ax2.w_yaxis.line.set_lw(0.)\n ax2.set_yticks([])\n\n # set viewing angle\n ax2.view_init(20,-65)\n\n # set vewing limits\n y = 4\n ax2.set_xlim([-y,y])\n ax2.set_ylim([-y,y])\n ax2.set_zlim([zmin,zmax])\n\n # label plot\n fontsize = 12\n ax2.set_xlabel(r'$w_1$',fontsize = fontsize,labelpad = -35)\n ax2.set_ylabel(r'$w_2$',fontsize = fontsize,rotation = 0,labelpad=-40)\n \n plt.show()\n \n# animator for recursive function\ndef visualize3d(func,**kwargs):\n grad = compute_grad(func) # gradient of input function\n colors = [[0,1,0.25],[0,0.75,1]] # set of custom colors used for plotting\n \n num_frames = 10\n if 'num_frames' in kwargs:\n num_frames = kwargs['num_frames']\n \n view = [20,-50]\n if 'view' in kwargs:\n view = kwargs['view']\n \n plot_descent = False\n if 'plot_descent' in kwargs:\n plot_descent = kwargs['plot_descent']\n \n pt1 = [0,0]\n pt2 = [-0.5,0.5]\n if 'pt' in kwargs:\n pt1 = kwargs['pt']\n if 'pt2' in kwargs:\n pt2 = kwargs['pt2']\n \n # construct figure\n fig = plt.figure(figsize = (9,6))\n \n # remove whitespace from figure\n fig.subplots_adjust(left=0, right=1, bottom=0, top=1) # remove whitespace\n fig.subplots_adjust(wspace=0.01,hspace=0.01)\n \n # create subplotting mechanism\n gs = gridspec.GridSpec(1, 1) \n ax1 = plt.subplot(gs[0],projection='3d'); \n \n # define input space\n w_in = np.linspace(-2,2,200)\n w1_vals, w2_vals = np.meshgrid(w_in,w_in)\n w1_vals.shape = (len(w_in)**2,1)\n w2_vals.shape = (len(w_in)**2,1)\n w_vals = np.concatenate((w1_vals,w2_vals),axis=1).T\n g_vals = func(w_vals) \n cont = 1\n for pt in [pt1]:\n # create axis for plotting\n if cont == 1:\n ax = ax1\n if cont == 2:\n ax = ax2\n\n cont+=1\n # evaluation points\n w_val = np.array([float(pt[0]),float(pt[1])])\n w_val.shape = (2,1)\n g_val = func(w_val)\n grad_val = grad(w_val)\n grad_val.shape = (2,1) \n\n # create and evaluate tangent hyperplane\n w_tan = np.linspace(-1,1,200)\n w1tan_vals, w2tan_vals = np.meshgrid(w_tan,w_tan)\n w1tan_vals.shape = (len(w_tan)**2,1)\n w2tan_vals.shape = (len(w_tan)**2,1)\n wtan_vals = np.concatenate((w1tan_vals,w2tan_vals),axis=1).T\n\n #h = lambda weh: g_val + np.dot( (weh - w_val).T,grad_val)\n h = lambda weh: g_val + (weh[0]-w_val[0])*grad_val[0] + (weh[1]-w_val[1])*grad_val[1] \n h_vals = h(wtan_vals + w_val)\n zmin = min(np.min(h_vals),-0.5)\n zmax = max(np.max(h_vals),+0.5)\n\n # vals for cost surface, reshape for plot_surface function\n w1_vals.shape = (len(w_in),len(w_in))\n w2_vals.shape = (len(w_in),len(w_in))\n g_vals.shape = (len(w_in),len(w_in))\n w1tan_vals += w_val[0]\n w2tan_vals += w_val[1]\n w1tan_vals.shape = (len(w_tan),len(w_tan))\n w2tan_vals.shape = (len(w_tan),len(w_tan))\n h_vals.shape = (len(w_tan),len(w_tan))\n\n ### plot function ###\n ax.plot_surface(w1_vals, w2_vals, g_vals, alpha = 0.1,color = 'w',rstride=25, cstride=25,linewidth=1,edgecolor = 'k',zorder = 2)\n\n ### plot z=0 plane ###\n ax.plot_surface(w1_vals, w2_vals, g_vals*0, alpha = 0.1,color = 'w',zorder = 1,rstride=25, cstride=25,linewidth=0.3,edgecolor = 'k') \n\n ### plot tangent plane ###\n ax.plot_surface(w1tan_vals, w2tan_vals, h_vals, alpha = 0.1,color = 'lime',zorder = 1,rstride=50, cstride=50,linewidth=1,edgecolor = 'k') \n\n ### plot particular points - origins and tangency ###\n # scatter origin\n ax.scatter(0,0,0,s = 60,c = 'k',edgecolor = 'w',linewidth = 2)\n\n # scatter tangency \n ax.scatter(w_val[0],w_val[1],g_val,s = 70,c = 'lime',edgecolor = 'k',linewidth = 2)\n\n ##### add arrows and annotations for steepest ascent direction #####\n # re-assign func variable to tangent\n cutoff_val = 0.1\n an = 1.7\n pname = 'g(' + str(pt[0]) + ',' + str(pt[1]) + ')'\n s = h([1,0]) - h([0,0])\n if abs(s) > cutoff_val:\n # draw arrow\n a = Arrow3D([0, s], [0, 0], [0, 0], mutation_scale=20,\n lw=2, arrowstyle=\"-|>\", color=\"b\")\n ax.add_artist(a)\n\n # label arrow\n q = h([an,0]) - h([0,0])\n name = r'$\\left(\\frac{\\mathrm{d}}{\\mathrm{d}w_1}' + pname + r',0\\right)$'\n annotate3D(ax, s=name, xyz=[q,0,0], fontsize=12, xytext=(-3,3),textcoords='offset points', ha='center',va='center') \n\n t = h([0,1]) - h([0,0])\n if abs(t) > cutoff_val:\n # draw arrow\n a = Arrow3D([0, 0], [0, t], [0, 0], mutation_scale=20,\n lw=2, arrowstyle=\"-|>\", color=\"b\")\n ax.add_artist(a) \n\n # label arrow\n q = h([0,an]) - h([0,0])\n name = r'$\\left(0,\\frac{\\mathrm{d}}{\\mathrm{d}w_2}' + pname + r'\\right)$'\n annotate3D(ax, s=name, xyz=[0,q,0], fontsize=12, xytext=(-3,3),textcoords='offset points', ha='center',va='center') \n\n # full gradient\n if abs(s) > cutoff_val and abs(t) > cutoff_val:\n a = Arrow3D([0, h([1,0])- h([0,0])], [0, h([0,1])- h([0,0])], [0, 0], mutation_scale=20,\n lw=2, arrowstyle=\"-|>\", color=\"k\")\n ax.add_artist(a) \n\n s = h([an+0.2,0]) - h([0,0])\n t = h([0,an+0.2]) - h([0,0])\n name = r'$\\left(\\frac{\\mathrm{d}}{\\mathrm{d}w_1}' + pname + r',\\frac{\\mathrm{d}}{\\mathrm{d}w_2}' + pname + r'\\right)$'\n annotate3D(ax, s=name, xyz=[s,t,0], fontsize=12, xytext=(-3,3),textcoords='offset points', ha='center',va='center') \n\n ###### add arrow and text for steepest descent direction #####\n if plot_descent == True:\n # full negative gradient\n if abs(s) > cutoff_val and abs(t) > cutoff_val:\n a = Arrow3D([0, - (h([1,0])- h([0,0]))], [0, - (h([0,1])- h([0,0]))], [0, 0], mutation_scale=20,\n lw=2, arrowstyle=\"-|>\", color=\"r\")\n ax.add_artist(a) \n\n s = - (h([an+0.2,0]) - h([0,0]))\n t = - (h([0,an+0.2]) - h([0,0]))\n name = r'$\\left(-\\frac{\\mathrm{d}}{\\mathrm{d}w_1}' + pname + r',-\\frac{\\mathrm{d}}{\\mathrm{d}w_2}' + pname + r'\\right)$'\n annotate3D(ax, s=name, xyz=[s,t,0], fontsize=12, xytext=(-3,3),textcoords='offset points', ha='center',va='center') \n\n \n ### clean up plot ###\n # plot x and y axes, and clean up\n ax.xaxis.pane.fill = False\n ax.yaxis.pane.fill = False\n ax.zaxis.pane.fill = False\n\n ax.xaxis.pane.set_edgecolor('white')\n ax.yaxis.pane.set_edgecolor('white')\n ax.zaxis.pane.set_edgecolor('white')\n\n # remove axes lines and tickmarks\n ax.w_zaxis.line.set_lw(0.)\n ax.set_zticks([])\n ax.w_xaxis.line.set_lw(0.)\n ax.set_xticks([])\n ax.w_yaxis.line.set_lw(0.)\n ax.set_yticks([])\n\n # set viewing angle\n ax.view_init(view[0],view[1])\n\n # set vewing limits\n y = 4.5\n ax.set_xlim([-y,y])\n ax.set_ylim([-y,y])\n ax.set_zlim([zmin,zmax])\n\n # label plot\n fontsize = 14\n ax.set_xlabel(r'$w_1$',fontsize = fontsize,labelpad = -20)\n ax.set_ylabel(r'$w_2$',fontsize = fontsize,rotation = 0,labelpad=-30)\n # plot\n plt.show()\n\n \n# animate ascent direction given by derivative for single input function over a range of values\ndef animate_visualize2d(**kwargs):\n g = kwargs['g'] # input function\n grad = compute_grad(g) # gradient of input function\n colors = [[0,1,0.25],[0,0.75,1]] # set of custom colors used for plotting\n \n num_frames = 300 # number of slides to create - the input range [-3,3] is divided evenly by this number\n if 'num_frames' in kwargs:\n num_frames = kwargs['num_frames']\n \n plot_descent = False\n if 'plot_descent' in kwargs:\n plot_descent = kwargs['plot_descent']\n \n # initialize figure\n fig = plt.figure(figsize = (16,8))\n artist = fig\n \n # create subplot with 3 panels, plot input function in center plot\n gs = gridspec.GridSpec(1, 3, width_ratios=[1,4, 1]) \n ax1 = plt.subplot(gs[0]); ax1.axis('off');\n ax3 = plt.subplot(gs[2]); ax3.axis('off');\n \n # plot input function\n ax = plt.subplot(gs[1])\n \n # generate a range of values over which to plot input function, and derivatives\n w_plot = np.linspace(-3,3,200) # input range for original function\n g_plot = g(w_plot)\n g_range = max(g_plot) - min(g_plot) # used for cleaning up final plot\n ggap = g_range*0.2\n w_vals = np.linspace(-3,3,num_frames) # range of values over which to plot first / second order approximations\n \n # animation sub-function\n print ('starting animation rendering...')\n def animate(k):\n # clear the panel\n ax.cla()\n \n # print rendering update \n if np.mod(k+1,25) == 0:\n print ('rendering animation frame ' + str(k+1) + ' of ' + str(num_frames))\n if k == num_frames - 1:\n print ('animation rendering complete!')\n time.sleep(1.5)\n clear_output()\n \n # grab the next input/output tangency pair, the center of the next approximation(s)\n w_val = w_vals[k]\n g_val = g(w_val)\n \n # plot original function\n ax.plot(w_plot,g_plot,color = 'k',zorder = 1,linewidth=4) # plot function\n \n # plot the input/output tangency point\n ax.scatter(w_val,g_val,s = 200,c = 'lime',edgecolor = 'k',linewidth = 2,zorder = 3) # plot point of tangency\n \n #### plot first order approximation ####\n # plug input into the first derivative\n g_grad_val = grad(w_val)\n \n # determine width to plot the approximation -- so its length == width\n width = 1\n div = float(1 + g_grad_val**2)\n w1 = w_val - math.sqrt(width/div)\n w2 = w_val + math.sqrt(width/div)\n \n # compute first order approximation\n wrange = np.linspace(w1,w2, 100)\n h = g_val + g_grad_val*(wrange - w_val)\n \n # plot the first order approximation\n ax.plot(wrange,h,color = 'lime',alpha = 0.5,linewidth = 6,zorder = 2) # plot approx\n \n #### plot derivative as vector ####\n func = lambda w: g_val + g_grad_val*w\n name = r'$\\frac{\\mathrm{d}}{\\mathrm{d}w}g(' + r'{:.2f}'.format(w_val) + r')$' \n if abs(func(1) - func(0)) >=0:\n head_width = 0.08*(func(1) - func(0))\n head_length = 0.2*(func(1) - func(0))\n \n # annotate arrow and annotation\n if func(1)-func(0) >= 0:\n ax.arrow(0, 0, func(1)-func(0),0, head_width=head_width, head_length=head_length, fc='k', ec='k',linewidth=2.5,zorder = 3)\n \n ax.annotate(name, xy=(2, 1), xytext=(func(1 + 0.3)-func(0),0),fontsize=22)\n elif func(1)-func(0) < 0:\n ax.arrow(0, 0, func(1)-func(0),0, head_width=-head_width, head_length=-head_length, fc='k', ec='k',linewidth=2.5,zorder = 3)\n \n ax.annotate(name, xy=(2, 1), xytext=(func(1+0.3) - 1.3 - func(0),0),fontsize=22)\n \n #### plot negative derivative as vector ####\n if plot_descent == True:\n ax.scatter(0,0,c = 'k',edgecolor = 'w',s = 100, linewidth = 0.5,zorder = 4)\n \n func = lambda w: g_val - g_grad_val*w\n name = r'$-\\frac{\\mathrm{d}}{\\mathrm{d}w}g(' + r'{:.2f}'.format(w_val) + r')$' \n if abs(func(1) - func(0)) >=0:\n head_width = 0.08*(func(1) - func(0))\n head_length = 0.2*(func(1) - func(0))\n \n # annotate arrow and annotation\n if func(1)-func(0) >= 0:\n ax.arrow(0, 0, func(1)-func(0),0, head_width=head_width, head_length=head_length, fc='r', ec='r',linewidth=2.5,zorder = 3)\n \n ax.annotate(name, xy=(2, 1), xytext=(func(1 + 0.3)-0.2-func(0),0),fontsize=22)\n elif func(1)-func(0) < 0:\n ax.arrow(0, 0, func(1)-func(0),0, head_width=-head_width, head_length=-head_length, fc='r', ec='r',linewidth=2.5,zorder = 3)\n \n ax.annotate(name, xy=(2, 1), xytext=(func(1+0.3) - 1.6 - func(0),0),fontsize=22) \n \n #### clean up panel ####\n # fix viewing limits on panel\n ax.set_xlim([-5,5])\n ax.set_ylim([min(min(g_plot) - ggap,-0.5),max(max(g_plot) + ggap,0.5)])\n \n # label axes\n ax.set_xlabel('$w$',fontsize = 25)\n ax.set_ylabel('$g(w)$',fontsize = 25,rotation = 0,labelpad = 50)\n ax.grid(False)\n ax.yaxis.set_visible(False)\n ax.spines['right'].set_visible(False)\n ax.spines['top'].set_visible(False)\n ax.spines['left'].set_visible(False)\n for tick in ax.xaxis.get_major_ticks():\n tick.label.set_fontsize(18) \n \n return artist,\n \n anim = animation.FuncAnimation(fig, animate,frames=len(w_vals), interval=len(w_vals), blit=True)\n \n return(anim)\n\n#### custom 3d arrow and annotator functions ### \n# nice arrow maker from https://stackoverflow.com/questions/11140163/python-matplotlib-plotting-a-3d-cube-a-sphere-and-a-vector\nclass Arrow3D(FancyArrowPatch):\n\n def __init__(self, xs, ys, zs, *args, **kwargs):\n FancyArrowPatch.__init__(self, (0, 0), (0, 0), *args, **kwargs)\n self._verts3d = xs, ys, zs\n\n def draw(self, renderer):\n xs3d, ys3d, zs3d = self._verts3d\n xs, ys, zs = proj3d.proj_transform(xs3d, ys3d, zs3d, renderer.M)\n self.set_positions((xs[0], ys[0]), (xs[1], ys[1]))\n FancyArrowPatch.draw(self, renderer)\n\n# great solution for annotating 3d objects - from https://datascience.stackexchange.com/questions/11430/how-to-annotate-labels-in-a-3d-matplotlib-scatter-plot\nclass Annotation3D(Annotation):\n '''Annotate the point xyz with text s'''\n\n def __init__(self, s, xyz, *args, **kwargs):\n Annotation.__init__(self,s, xy=(0,0), *args, **kwargs)\n self._verts3d = xyz \n\n def draw(self, renderer):\n xs3d, ys3d, zs3d = self._verts3d\n xs, ys, zs = proj_transform(xs3d, ys3d, zs3d, renderer.M)\n self.xy=(xs,ys)\n Annotation.draw(self, renderer) \n\ndef annotate3D(ax, s, *args, **kwargs):\n '''add anotation text s to to Axes3d ax'''\n\n tag = Annotation3D(s, *args, **kwargs)\n ax.add_artist(tag)","sub_path":"mlrefined_libraries/calculus_library/derivative_ascent_visualizer.py","file_name":"derivative_ascent_visualizer.py","file_ext":"py","file_size_in_byte":20589,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"38234761","text":"\"\"\"\r\nThis script calculates the average QALY loss due to long-COVID per hospitalisation group and age. \r\nThe calculation is based on the prevalence data from Wynberg et al. (https://academic.oup.com/cid/article/75/1/e482/6362727) \r\nand the QoL score related to long-COVID from KCE (https://www.kce.fgov.be/sites/default/files/2021-11/KCE_344_Long_Covid_scientific_report_1.pdf)\r\n\r\nFigures of intermediate results are saved to results/prepocessing/QALY_model_long_covid\r\nA dataframe with the mean, sd, lower and upper average QALY loss per hospitalisation group and age is saved to data/interim/QALY_model/long_covid\r\n\r\n\"\"\" \r\n\r\n__author__ = \"Wolf Demuynck\"\r\n__copyright__ = \"Copyright (c) 2022 by W. Demuynck, BIOMATH, Ghent University. All Rights Reserved.\"\r\n\r\n############################\r\n## Load required packages ##\r\n############################\r\n\r\nimport os\r\nimport numpy as np\r\nimport matplotlib.pyplot as plt\r\nimport pandas as pd\r\nimport xarray as xr\r\nimport matplotlib.cm as cm\r\nfrom scipy.integrate import quad\r\nfrom scipy.optimize import curve_fit\r\nfrom scipy import stats\r\nfrom scipy.optimize import minimize\r\n\r\nfrom covid19_DTM.models.QALY import life_table_QALY_model\r\nLife_table = life_table_QALY_model()\r\n\r\nfrom covid19_DTM.data import sciensano\r\nfrom covid19_DTM.data.utils import construct_initN\r\nfrom covid19_DTM.models.utils import output_to_visuals\r\nfrom covid19_DTM.models.utils import initialize_COVID19_SEIQRD_hybrid_vacc\r\nfrom covid19_DTM.visualization.output import _apply_tick_locator \r\nfrom covid19_DTM.models.QALY import life_table_QALY_model, lost_QALYs_hospital_care\r\n\r\nimport copy\r\nimport emcee\r\nfrom tqdm import tqdm\r\n\r\n###############\r\n## Load data ##\r\n###############\r\n\r\nprint('\\n(1) Loading data\\n')\r\n\r\nabs_dir = os.path.dirname(__file__)\r\nrel_dir = '../../data/covid19_DTM/raw/QALY_model/long_COVID/'\r\n\r\n# --------------- #\r\n# Prevalence data #\r\n# --------------- #\r\n\r\nseverity_groups = ['Mild','Moderate','Severe-Critical']\r\nhospitalisation_groups = ['Non-hospitalised','Cohort','ICU']\r\ncolor_dict = {'Mild':'g','Non-hospitalised':'g','Non-hospitalised (no AD)':'g','Moderate':'y','Cohort':'y','Severe-Critical':'r','ICU':'r'}\r\n\r\n# raw prevalence data per severity group\r\nprevalence_data_per_severity_group = pd.read_csv(os.path.join(abs_dir,rel_dir,'Long_COVID_prevalence.csv'),index_col=[0,1])\r\n\r\n# severity distribution in raw data\r\nseverity_distribution= pd.DataFrame(data=np.array([[(96-6)/(338-172),(145-72)/(338-172),((55+42)-(52+42))/(338-172)],\r\n [(6-0)/(172-42),(72-0)/(172-42),((52+42)-(0+42))/(172-42)],\r\n [0,0,1]]),\r\n columns=severity_groups,index=hospitalisation_groups)\r\nseverity_distribution.index.name='hospitalisation'\r\n\r\n# convert data per severity group to data per hospitalisation group\r\nindex = pd.MultiIndex.from_product([hospitalisation_groups,prevalence_data_per_severity_group .index.get_level_values('Months').unique()])\r\nprevalence_data_per_hospitalisation_group = pd.Series(index=index,dtype='float')\r\nfor hospitalisation,month in index:\r\n prevalence = sum(prevalence_data_per_severity_group.loc[(slice(None),month),:].values.squeeze()*severity_distribution.loc[hospitalisation,:].values)\r\n prevalence_data_per_hospitalisation_group[(hospitalisation,month)]=prevalence\r\n\r\n# -------- #\r\n# QoL data #\r\n# -------- #\r\n\r\nLE_table = Life_table.life_expectancy(SMR=1)\r\n\r\n# reference QoL scores\r\nage_bins = pd.IntervalIndex.from_tuples([(15,25),(25,35),(35,45),(45,55),(55,65),(65,75),(75,LE_table.index.values[-1])], closed='left')\r\nQoL_Belgium = pd.Series(index=age_bins, data=[0.85, 0.85, 0.82, 0.78, 0.78, 0.78, 0.66])\r\n\r\n# QoL decrease due to long-COVID\r\nmean_QoL_decrease_hospitalised = 0.24\r\nmean_QoL_decrease_non_hospitalised = 0.19\r\nsd_QoL_decrease_hospitalised = 0.41/np.sqrt(174) #(0.58-0.53)/1.96\r\nsd_QoL_decrease_non_hospitalised = 0.33/np.sqrt(1146) #(0.66-0.64)/1.96\r\nQoL_difference_data = pd.DataFrame(data=np.array([[mean_QoL_decrease_non_hospitalised,mean_QoL_decrease_hospitalised,mean_QoL_decrease_hospitalised],\r\n [sd_QoL_decrease_non_hospitalised,sd_QoL_decrease_hospitalised,sd_QoL_decrease_hospitalised]]).transpose(),\r\n columns=['mean','sd'],index=['Non-hospitalised','Cohort','ICU'])\r\n\r\n# ------- #\r\n# results #\r\n# ------- #\r\n\r\ndata_result_folder = '../../data/covid19_DTM/interim/QALY_model/long_COVID/'\r\nfig_result_folder = '../../results/covid19_DTM/preprocessing/QALY_model/long_COVID/'\r\n\r\n# Verify that the paths exist and if not, generate them\r\nfor directory in [data_result_folder, fig_result_folder]:\r\n if not os.path.exists(directory):\r\n os.makedirs(directory)\r\n\r\n################\r\n## Prevalence ##\r\n################\r\n\r\nprint('\\n(2) Calculate prevalence\\n')\r\nprint('\\n(2.1) Estimate tau\\n')\r\n\r\n# objective function to minimize\r\ndef WSSE_no_pAD(tau,x,y):\r\n y_model = np.exp(-x/tau)\r\n SSE = sum((y_model-y)**2)\r\n WSSE = sum((1/y)**2 * (y_model-y)**2)\r\n return WSSE\r\n\r\ndef WSSE(theta,x,y):\r\n tau,p_AD = theta\r\n y_model = p_AD + (1-p_AD)*np.exp(-x/tau)\r\n SSE = sum((y_model-y)**2)\r\n WSSE = sum((1/y)**2 * (y_model-y)**2)\r\n return WSSE\r\n\r\n# minimize objective function to find tau\r\ntaus = pd.Series(index=hospitalisation_groups+['Non-hospitalised (no AD)'],dtype='float')\r\np_ADs = pd.Series(index=hospitalisation_groups+['Non-hospitalised (no AD)'],dtype='float')\r\n\r\nfor hospitalisation in hospitalisation_groups+['Non-hospitalised (no AD)']:\r\n \r\n if hospitalisation == 'Non-hospitalised (no AD)':\r\n x = prevalence_data_per_hospitalisation_group.loc['Non-hospitalised'].index.values\r\n y = prevalence_data_per_hospitalisation_group.loc['Non-hospitalised'].values.squeeze()\r\n\r\n sol = minimize(WSSE_no_pAD,x0=3,args=(x,y))\r\n tau = sol.x[0]\r\n p_AD = 0\r\n else:\r\n x = prevalence_data_per_hospitalisation_group.loc[hospitalisation].index.values\r\n y = prevalence_data_per_hospitalisation_group.loc[hospitalisation].values.squeeze()\r\n\r\n sol = minimize(WSSE,x0=(3,min(y)),args=(x,y))\r\n tau = sol.x[0]\r\n p_AD = sol.x[1]\r\n \r\n p_ADs[hospitalisation] = p_AD\r\n taus[hospitalisation] = tau\r\n\r\n# visualise result\r\nt_max = 24\r\nt_steps = 1000\r\ntime = np.linspace(0, t_max, t_steps)\r\n\r\nprevalence_func = lambda t,tau, p_AD: p_AD + (1-p_AD)*np.exp(-t/tau)\r\n\r\nfor scenario,(fig,ax) in zip(('AD','no_AD'),(plt.subplots(),plt.subplots())):\r\n for hospitalisation in hospitalisation_groups:\r\n x = prevalence_data_per_hospitalisation_group.loc[hospitalisation].index.values\r\n y = prevalence_data_per_hospitalisation_group.loc[hospitalisation].values.squeeze()\r\n ax.plot(x,y,color_dict[hospitalisation]+'o',label=f'{hospitalisation} data')\r\n\r\n if hospitalisation =='Non-hospitalised' and scenario == 'no_AD':\r\n tau = taus['Non-hospitalised (no AD)']\r\n p_AD = p_ADs['Non-hospitalised (no AD)']\r\n else:\r\n tau = taus[hospitalisation]\r\n p_AD = p_ADs[hospitalisation]\r\n ax.plot(time,prevalence_func(time,tau,p_AD),color_dict[hospitalisation]+'--',alpha=0.7,\r\n label=f'{hospitalisation} fit\\n'rf'($\\tau$:{tau:.2f},'' $f_{AD}$'f':{p_AD:.2f})')\r\n \r\n ax.set_xlabel('Months after infection')\r\n ax.set_ylabel('Prevalence')\r\n ax.set_title('Prevalence of long-COVID symptoms')\r\n ax.legend(prop={'size': 12})\r\n ax.grid(False)\r\n fig.savefig(os.path.join(abs_dir,fig_result_folder,f'prevalence_first_fit_{scenario}'))\r\n\r\nprint('\\n(2.2) MCMC to estimate f_AD\\n')\r\n# objective functions for MCMC\r\ndef WSSE(theta,x,y):\r\n tau,p_AD = theta\r\n y_model = p_AD + (1-p_AD)*np.exp(-x/tau)\r\n SSE = sum((y_model-y)**2)\r\n WSSE = sum((1/y)**2 * (y_model-y)**2)\r\n return WSSE\r\n\r\ndef log_likelihood(theta, tau, x, y):\r\n p_AD = theta[0]\r\n y_model = p_AD + (1-p_AD)*np.exp(-x/tau)\r\n SSE = sum((y_model-y)**2)\r\n WSSE = sum((1/y)**2 * (y_model-y)**2)\r\n return -WSSE\r\n\r\ndef log_prior(theta,p_AD_bounds):\r\n p_AD = theta[0]\r\n if p_AD_bounds[0] < p_AD < p_AD_bounds[1]:\r\n return 0.0\r\n else:\r\n return -np.inf\r\n\r\ndef log_probability(theta, tau, x, y, bounds):\r\n lp = log_prior(theta,bounds)\r\n if not np.isfinite(lp):\r\n return -np.inf\r\n ll = log_likelihood(theta,tau, x, y)\r\n if np.isnan(ll):\r\n return -np.inf\r\n return lp + ll\r\n\r\n# run MCMC\r\nsamplers = {}\r\np_AD_summary = pd.DataFrame(index=hospitalisation_groups,columns=['mean','sd','lower','upper'],dtype='float64')\r\n\r\nfor hospitalisation in hospitalisation_groups:\r\n \r\n x = prevalence_data_per_hospitalisation_group.loc[hospitalisation].index.values\r\n y = prevalence_data_per_hospitalisation_group.loc[hospitalisation].values.squeeze()\r\n\r\n tau = taus[hospitalisation]\r\n p_AD = p_ADs[hospitalisation]\r\n \r\n nwalkers = 32\r\n ndim = 1\r\n pos = p_AD + p_AD*1e-1 * np.random.randn(nwalkers, ndim)\r\n\r\n bounds = (0,1)\r\n sampler = emcee.EnsembleSampler(\r\n nwalkers, ndim, log_probability, args=(tau,x,y,bounds)\r\n )\r\n samplers.update({hospitalisation:sampler})\r\n sampler.run_mcmc(pos, 20000, progress=True)\r\n\r\n flat_samples = sampler.get_chain(discard=1000, thin=30, flat=True)\r\n p_AD_summary['mean'][hospitalisation] = np.mean(flat_samples,axis=0)\r\n p_AD_summary['sd'][hospitalisation] = np.std(flat_samples,axis=0)\r\n p_AD_summary['lower'][hospitalisation] = np.quantile(flat_samples,0.025,axis=0)\r\n p_AD_summary['upper'][hospitalisation] = np.quantile(flat_samples,0.975,axis=0)\r\n\r\n# visualise MCMC results \r\nfig,axs = plt.subplots(2,2,figsize=(10,10),sharex=True,sharey=True)\r\naxs = axs.reshape(-1)\r\nfor ax,hospitalisation in zip(axs[:-1],hospitalisation_groups):\r\n x = prevalence_data_per_hospitalisation_group.loc[hospitalisation].index.values\r\n y = prevalence_data_per_hospitalisation_group.loc[hospitalisation].values.squeeze()\r\n ax.plot(x,y,color_dict[hospitalisation]+'o',label=f'{hospitalisation} data')\r\n axs[-1].plot(x,y,color_dict[hospitalisation]+'o',label=f'{hospitalisation} data')\r\n \r\n tau = taus[hospitalisation]\r\n prevalences = []\r\n for n in range(200):\r\n prevalences.append(prevalence_func(time,tau,np.random.normal(p_AD_summary.loc[hospitalisation]['mean'],\r\n p_AD_summary.loc[hospitalisation]['sd'])))\r\n mean = np.mean(prevalences,axis=0)\r\n lower = np.quantile(prevalences,0.025,axis=0)\r\n upper = np.quantile(prevalences,0.975,axis=0)\r\n\r\n ax.plot(time,mean,color_dict[hospitalisation]+'--',alpha=0.7)\r\n axs[-1].plot(time,mean,color_dict[hospitalisation]+'--',alpha=0.7,label=f'{hospitalisation} mean fit')\r\n ax.fill_between(time,lower, upper,alpha=0.2, color=color_dict[hospitalisation])\r\n ax.set_title(hospitalisation)\r\n ax.grid(False)\r\n\r\naxs[-1].set_xlabel('Months after infection')\r\naxs[-2].set_xlabel('Months after infection')\r\naxs[0].set_ylabel('Prevalence')\r\naxs[-2].set_ylabel('Prevalence')\r\naxs[-1].legend(prop={'size': 12})\r\naxs[-1].grid(False)\r\n\r\nfig.suptitle('Prevalence of long-COVID symptoms')\r\nfig.savefig(os.path.join(abs_dir,fig_result_folder,'prevalence_MCMC_fit.png'))\r\n\r\n#########\r\n## QoL ##\r\n#########\r\n\r\nprint('\\n(3) Fit exponential curve to QoL scores\\n')\r\n\r\nQoL_Belgium_func = Life_table.QoL_Belgium_func\r\n\r\n# visualise fit\r\nfig,ax = plt.subplots()\r\nfor index in QoL_Belgium.index:\r\n left = index.left\r\n right = index.right\r\n w = right-left\r\n ax.bar(left+w/2,QoL_Belgium[index],w-1,color='grey',alpha=0.5,label='data')\r\nax.plot(QoL_Belgium_func(LE_table.index.values),label='fit',color='b')\r\nax.set_xlabel('Age')\r\nax.set_ylabel('QoL Belgium')\r\nax.set_ylim([0.5, 0.9])\r\nax.grid(False)\r\nfig.savefig(os.path.join(abs_dir,fig_result_folder,'QoL_Belgium_fit.png'))\r\n\r\n#######################\r\n## Average QALY loss ##\r\n#######################\r\n\r\nprint('\\n(4) Calculate average QALY loss for each age\\n')\r\n\r\nprevalence_func = lambda t,tau, p_AD: p_AD + (1-p_AD)*np.exp(-t/tau)\r\n\r\n# QALY loss func for fixed QoL after but beta is absolute difference and changing over time due to decreasing QoL reference\r\ndef QALY_loss_func(t,tau,p_AD,age,QoL_after):\r\n beta = QoL_Belgium_func(age+t/12)-QoL_after\r\n return prevalence_func(t,tau,p_AD) * max(0,beta)\r\n\r\ndraws = 200\r\n\r\n# Pre-allocate new multi index series with index=hospitalisation,age,draw\r\nmulti_index = pd.MultiIndex.from_product([hospitalisation_groups+['Non-hospitalised (no AD)'],np.arange(draws),LE_table.index.values],names=['hospitalisation','draw','age'])\r\naverage_QALY_losses = pd.Series(index = multi_index, dtype=float)\r\n\r\n# Calculate average QALY loss for each age 'draws' times\r\nfor idx,(hospitalisation,draw,age) in enumerate(tqdm(multi_index)):\r\n LE = LE_table[age]*12\r\n\r\n # use the same samples for beta and p_AD to calculate average QALY loss for each age\r\n if age==0:\r\n if hospitalisation == 'Non-hospitalised (no AD)':\r\n p_AD = 0\r\n beta = np.random.normal(QoL_difference_data.loc['Non-hospitalised']['mean'],\r\n QoL_difference_data.loc['Non-hospitalised']['sd'])\r\n else:\r\n p_AD = np.random.normal(p_AD_summary.loc[hospitalisation]['mean'],\r\n p_AD_summary.loc[hospitalisation]['sd'])\r\n beta = np.random.normal(QoL_difference_data.loc[hospitalisation]['mean'],\r\n QoL_difference_data.loc[hospitalisation]['sd'])\r\n \r\n tau = taus[hospitalisation]\r\n\r\n # calculate the fixed QoL after getting infected for each age\r\n QoL_after = QoL_Belgium_func(age)-beta\r\n # integrate QALY_loss_func from 0 to LE \r\n QALY_loss = quad(QALY_loss_func,0,LE,args=(tau,p_AD,age,QoL_after))[0]/12 \r\n average_QALY_losses[idx] = QALY_loss\r\n\r\n# save result to dataframe\r\ndef get_lower(x):\r\n return np.quantile(x,0.025)\r\ndef get_upper(x):\r\n return np.quantile(x,0.975)\r\ndef get_upper(x):\r\n return np.quantile(x,0.975)\r\ndef get_sd(x):\r\n return np.std(x)\r\n\r\nmulti_index = pd.MultiIndex.from_product([hospitalisation_groups+['Non-hospitalised (no AD)'],LE_table.index.values],names=['hospitalisation','age'])\r\naverage_QALY_losses_summary = pd.DataFrame(index = multi_index, columns=['mean','sd','lower','upper'], dtype=float)\r\nfor hospitalisation in hospitalisation_groups+['Non-hospitalised (no AD)']:\r\n average_QALY_losses_summary['mean'][hospitalisation] = average_QALY_losses[hospitalisation].groupby(['age']).mean()\r\n average_QALY_losses_summary['sd'][hospitalisation] = average_QALY_losses[hospitalisation].groupby(['age']).apply(get_sd)\r\n average_QALY_losses_summary['lower'][hospitalisation] = average_QALY_losses[hospitalisation].groupby(['age']).apply(get_lower)\r\n average_QALY_losses_summary['upper'][hospitalisation] = average_QALY_losses[hospitalisation].groupby(['age']).apply(get_upper)\r\n\r\naverage_QALY_losses_summary.to_csv(os.path.join(abs_dir,data_result_folder,'average_QALY_losses.csv'))\r\n\r\n# Visualise results\r\nfig,axs = plt.subplots(2,2,sharex=True,sharey=True,figsize=(10,10))\r\naxs = axs.reshape(-1)\r\nfor ax,hospitalisation in zip(axs,['Non-hospitalised (no AD)']+hospitalisation_groups):\r\n mean = average_QALY_losses_summary.loc[hospitalisation]['mean']\r\n lower = average_QALY_losses_summary.loc[hospitalisation]['lower']\r\n upper = average_QALY_losses_summary.loc[hospitalisation]['upper']\r\n ax.plot(LE_table.index.values,mean,color_dict[hospitalisation],label=f'{hospitalisation}')\r\n ax.fill_between(LE_table.index.values,lower,upper,alpha=0.20, color = color_dict[hospitalisation])\r\n ax.set_title(hospitalisation)\r\n ax.grid(False)\r\n\r\naxs[-1].set_xlabel('Age when infected')\r\naxs[-2].set_xlabel('Age when infected')\r\naxs[0].set_ylabel('Average QALY loss')\r\naxs[-2].set_ylabel('Average QALY loss')\r\n\r\nfig.suptitle('Average QALY loss related to long-COVID')\r\nfig.savefig(os.path.join(abs_dir,fig_result_folder,'average_QALY_losses.png'))\r\n\r\n# QALY losses due COVID death\r\nQALY_D_per_age = Life_table.compute_QALY_D_x()\r\nfig,ax = plt.subplots(figsize=(12,4))\r\nax.plot(QALY_D_per_age,'b')\r\nax.set(xlabel='age', ylabel=r'$QALY_D$')\r\nax.grid(False)\r\nfig.savefig(os.path.join(abs_dir,fig_result_folder,'QALY_D.png'))","sub_path":"notebooks/preprocessing/woldmuyn_long_covid_average_QALY_loss.py","file_name":"woldmuyn_long_covid_average_QALY_loss.py","file_ext":"py","file_size_in_byte":16374,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"575418169","text":"#!/usr/bin/env python\n\nimport socket\nimport struct\nimport subprocess\nimport sys\n\nMCAST_GRP = '224.1.2.3'\nMCAST_PORT = 5007\n\n\nwhile True:\n try:\n sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)\n sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)\n sock.bind((MCAST_GRP, MCAST_PORT))\n mreq = struct.pack('4sl', socket.inet_aton(MCAST_GRP), socket.INADDR_ANY)\n sock.setsockopt(socket.IPPROTO_IP, socket.IP_ADD_MEMBERSHIP, mreq)\n mpd_host = sock.recv(10240)\n sock.close()\n subprocess.call([\"/usr/bin/cvlc\", \"http://\" + mpd_host + \":8000\", \"--play-and-exit\", \"-q\"])\n \n except socket.error as err:\n print (err[1])\n sys.exit()\n\n\n","sub_path":"mpd-receiver.py","file_name":"mpd-receiver.py","file_ext":"py","file_size_in_byte":735,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"37257042","text":"def calculate(exp):\n\n #returns evaluated simple expression if exp is formatted correctly, else returns -1\n #a simple expression is a string that is either a non-negative integer i = \"i\" with no leading zeroes\n #or in the form \"( exp1 op exp2 )\" where exp1 and exp2 are valid simple expressions and op is either +, -, *, or /\n #i.e. valid = \"42\" \"( 5 + 3 )\" \"( ( 728 - ( 10 + 2 ) ) * ( 10 - 6 ) )\"\n #i.e. invalid = 42 \"(5+3)\" \"003\" \"44.5\" \"-3\" \"( 40 / 0 )\" \"( 10 + 2 ) * 5\"\n\n try:\n print (\"Your input: \" + exp)\n\n #case 1: exp is a single non-negative int\n if is_valid_integer(exp):\n print(\"Evaluated expression: \" + exp)\n return exp\n\n #case 2: exp is in the form ( ... ) with the basic valid expression being ( e1 op e2 ) + CORRECT SPACING\n elif exp[0] == \"(\" and exp[exp.__len__()-1] == \")\":\n print(\"Evaluated expression: \" + evaluate(exp))\n return evaluate(exp)\n\n #case 3: exp is a hot mess, i.e. \"kjlksjdf\" or \"10 + 4)\" or \"(3+4)\" <-- watch your spacing\n else:\n print(\"Invalid expression format, spacing, or syntax\")\n return -1\n\n except TypeError:\n print(\"Encountered Type Error\")\n return -1\n\n except IndexError:\n print(\"Encountered IndexError\")\n return -1\n\n\ndef evaluate(exp):\n #the word of the day is STACK\n stack = []\n\n #splits expression into a list of characters - either (, ), an int, or an operand ( + - * / )\n charList = exp.split()\n\n #initialize stack with \"(\"\n stack.append(charList[0])\n index = 1\n\n while stack[0] == \"(\" and index < charList.__len__():\n #push things to stack and evaluate expressions as parentheses open and close\n stack.append(charList[index])\n index += 1\n\n #once a \")\" is reached, evaluate the basic expression\n if charList[index-1] == \")\":\n possibleExpression = []\n #generate a basic expression ( e1 op e2 ) from stack\n for i in range(0, 5):\n possibleExpression.insert(0, stack.pop())\n\n if is_valid_expression(possibleExpression) and get_value(possibleExpression) != -1:\n #evaluate value of basic expression and push back to top of stack\n evaluatedVal = str(get_value(possibleExpression))\n stack.append(evaluatedVal)\n else:\n #invalid basic expression\n return -1\n\n return evaluatedVal;\n\n\ndef is_valid_integer(num):\n # luckily, isinstance(int(str(num)), int) == False if num is a float\n try:\n #checks if its a valid non-negative int\n if isinstance(int(str(num)), int) and int(str(num)) >= 0:\n if num[0] == '0' and int(str(num)) != 0:\n #contains leading zeroes\n return False\n else:\n #valid int\n return True\n else:\n #not a non-negative integer\n return False\n except ValueError:\n return False\n\n\ndef is_valid_expression(expList):\n #checks if format of basic simple expression ( e1 op e2 ) is correct\n if expList[0] == \"(\" and expList[4] == \")\" and is_valid_integer(expList[1]) and is_valid_integer(expList[3]):\n if expList[2] == \"+\" or expList[2] == \"-\" or expList[2] == \"*\" or expList[2] == \"/\":\n return True;\n return False\n\n\ndef get_value(expList):\n #finds value of expList: [\"(\", \"int1\", \"op\", \"int2\", \")\"]\n a = int(expList[1])\n b = int(expList[3])\n if expList[2] == \"+\":\n return a + b\n elif expList[2] == \"-\":\n return a - b\n elif expList[2] == \"*\":\n return a * b\n elif expList[2] == \"/\" and b != 0:\n #assuming you want integer division here...\n return int(a/b)\n else:\n print(\"Cannot divide by zero\")\n return -1\n\n\n#*** Testing Area ***\n# calculate(\"\")\n# calculate(\"42\") # evaluates to 42\n# calculate(\"42.03\")\n# calculate(\"-34.2\")\n# calculate(44.5)\n# calculate(\"( ( 728 - ( 10 + 2 ) ) * ( 10 - 6 ) )\") # evaluates to 2864\n# calculate(\"( 40 / 0 )\")\n# calculate(\"( 10 + 2 ) *\")\n# calculate(\"10 / 2\")\n# calculate(\"( foo + 5 )\")\n# calculate(\"003\")","sub_path":"exercise3.py","file_name":"exercise3.py","file_ext":"py","file_size_in_byte":4197,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"312875574","text":"from tkinter import *\r\nfrom typing import Collection\r\nroot = Tk()\r\nroot.title(\"CodeBasic\")\r\nroot.geometry(\"640x480\")\r\n\r\n#btn1 = Button(root, text=\"버튼1\")\r\n#btn2 = Button(root, text=\"버튼2\")\r\n\r\n# pack\r\n# btn1.pack(side=\"left\")\r\n# btn2.pack(side=\"right\")\r\n\r\n# greed\r\n#btn1.grid(row=0, column=0)\r\n#btn2.grid(row=1, column=1)\r\n\r\n\r\n# 맨 윗줄\r\nbtn_f16 = Button(root, text=\"F16\", width=5, height=2)\r\nbtn_f17 = Button(root, text=\"F17\", width=5, height=2)\r\nbtn_f18 = Button(root, text=\"F18\", width=5, height=2)\r\nbtn_f19 = Button(root, text=\"F19\", width=5, height=2)\r\n\r\nbtn_f16.grid(row=0, column=0, sticky=N+E+W+S, padx=3, pady=3)\r\nbtn_f17.grid(row=0, column=1, sticky=N+E+W+S, padx=3, pady=3)\r\nbtn_f18.grid(row=0, column=2, sticky=N+E+W+S, padx=3, pady=3)\r\nbtn_f19.grid(row=0, column=3, sticky=N+E+W+S, padx=3, pady=3)\r\n\r\n# clear 줄\r\nbtn_clear = Button(root, text=\"clear\", width=5, height=2)\r\nbtn_equal = Button(root, text=\"=\", width=5, height=2)\r\nbtn_divide = Button(root, text=\"/\", width=5, height=2)\r\nbtn_multi = Button(root, text=\"*\", width=5, height=2)\r\n\r\nbtn_clear.grid(row=1, column=0, sticky=N+E+W+S, padx=3, pady=3)\r\nbtn_equal.grid(row=1, column=1, sticky=N+E+W+S, padx=3, pady=3)\r\nbtn_divide.grid(row=1, column=2, sticky=N+E+W+S, padx=3, pady=3)\r\nbtn_multi.grid(row=1, column=3, sticky=N+E+W+S, padx=3, pady=3)\r\n\r\n# number(7) 줄\r\nbtn_7 = Button(root, text=\"7\", width=5, height=2)\r\nbtn_8 = Button(root, text=\"8\", width=5, height=2)\r\nbtn_9 = Button(root, text=\"9\", width=5, height=2)\r\nbtn_sub = Button(root, text=\"-\", width=5, height=2)\r\n\r\nbtn_7.grid(row=2, column=0, sticky=N+E+W+S, padx=3, pady=3)\r\nbtn_8.grid(row=2, column=1, sticky=N+E+W+S, padx=3, pady=3)\r\nbtn_9.grid(row=2, column=2, sticky=N+E+W+S, padx=3, pady=3)\r\nbtn_sub.grid(row=2, column=3, sticky=N+E+W+S, padx=3, pady=3)\r\n\r\n# number(4) 줄\r\nbtn_4 = Button(root, text=\"4\", width=5, height=2)\r\nbtn_5 = Button(root, text=\"5\", width=5, height=2)\r\nbtn_6 = Button(root, text=\"6\", width=5, height=2)\r\nbtn_plus = Button(root, text=\"+\", width=5, height=2)\r\n\r\nbtn_4.grid(row=3, column=0, sticky=N+E+W+S, padx=3, pady=3)\r\nbtn_5.grid(row=3, column=1, sticky=N+E+W+S, padx=3, pady=3)\r\nbtn_6.grid(row=3, column=2, sticky=N+E+W+S, padx=3, pady=3)\r\nbtn_plus.grid(row=3, column=3, sticky=N+E+W+S, padx=3, pady=3)\r\n\r\n# number(1) 줄\r\nbtn_1 = Button(root, text=\"1\", width=5, height=2)\r\nbtn_2 = Button(root, text=\"2\", width=5, height=2)\r\nbtn_3 = Button(root, text=\"3\", width=5, height=2)\r\nbtn_enter = Button(root, text=\"enter\")\r\n\r\nbtn_1.grid(row=4, column=0, sticky=N+E+W+S, padx=3, pady=3)\r\nbtn_2.grid(row=4, column=1, sticky=N+E+W+S, padx=3, pady=3)\r\nbtn_3.grid(row=4, column=2, sticky=N+E+W+S, padx=3, pady=3)\r\nbtn_enter.grid(row=4, column=3, rowspan=2, sticky=N+E+W+S, padx=3, pady=3)\r\n\r\n# number(0) 줄\r\n\r\nbtn_0 = Button(root, text=\"0\", width=5, height=2)\r\nbtn_point = Button(root, text=\".\", width=5, height=2)\r\n\r\nbtn_0.grid(row=5, column=0, columnspan=2, sticky=N+E+W+S, padx=3, pady=3)\r\nbtn_point.grid(row=5, column=2, sticky=N+E+W+S, padx=3, pady=3)\r\n\r\n\r\nroot.mainloop()\r\n","sub_path":"GUI_Basic/14_grid.py","file_name":"14_grid.py","file_ext":"py","file_size_in_byte":3034,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"9545794","text":"from flask import Flask,render_template,request\n# import mysql.connector\n\napp = Flask(__name__)\n\n# conn = connector.connect(host='mysql',database='mysql',user='root',password='kremlin')\n# print(conn)\n\ndef fibonacci(n): \n a = 0\n b = 1\n if n < 0: \n print(\"Incorrect input\") \n elif n == 0: \n return a \n elif n == 1: \n return b \n else: \n for i in range(2,n): \n c = a + b \n a = b \n b = c \n return b \n\n@app.route('/')\ndef index():\n return render_template('index.html')\n \n\n@app.route('/predict',methods=['POST'])\ndef predict():\n result = [int(x) for x in request.form.values()]\n akhil = fibonacci(result[0])\n return render_template('index.html', prediction_text=' The value at index is {}'.format(akhil))\n\nif __name__ == '__main__':\n app.run(debug=True,host='0.0.0.0')","sub_path":"mult-container/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":869,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"157743654","text":"#IMBD case for Text Classification\r\n\r\n#1- Import key Modules\r\nimport tensorflow as tf\r\nfrom tensorflow import keras\r\nimport numpy\r\n#2- Data Loading and preparing\r\n\r\nimdb = keras.datasets.imdb\r\n# train-test split\r\n(train_data, train_labels), (test_data, test_labels) = imdb.load_data(num_words=10000)\r\nprint(\"Shape of feature train data\",train_data.shape)\r\nprint(\"shape of label train data\",train_labels.shape)\r\nprint(\"Shape of feature test data\",test_data.shape)\r\nprint(\"Shape of label test data\",test_labels.shape)\r\n# 3- Integer Encoded Data\r\n\r\n# A dictionary mapping words to an integer index\r\n_word_index = imdb.get_word_index()\r\n\r\nword_index = {k:(v+3) for k,v in _word_index.items()}\r\nword_index[\"\"] = 0\r\nword_index[\"\"] = 1\r\nword_index[\"\"] = 2 # unknown\r\nword_index[\"\"] = 3\r\n\r\nreverse_word_index = dict([(value, key) for (key, value) in word_index.items()])\r\n\r\ndef decode_review(text):\r\n\treturn \" \".join([reverse_word_index.get(i, \"?\") for i in text])\r\n\r\n# this function will return the decoded (human readable) reviews\r\n\r\n# 4- Preprocess the Data\r\n\r\ntrain_data = keras.preprocessing.sequence.pad_sequences(train_data, value=word_index[\"\"], padding=\"post\", maxlen=250)\r\ntest_data = keras.preprocessing.sequence.pad_sequences(test_data, value=word_index[\"\"], padding=\"post\", maxlen=250)\r\nprint(\"Shape of Training data after padding\",train_data.shape)\r\nprint(\"shape of Testing data after padding\",test_data.shape)\r\n# 5- Define the Model\r\n\r\nmodel = keras.Sequential()\r\nmodel.add(keras.layers.Embedding(80000, 16))\r\nmodel.add(keras.layers.GlobalAveragePooling1D())\r\nmodel.add(keras.layers.Dense(16, activation=\"relu\"))\r\nmodel.add(keras.layers.Dense(1, activation=\"sigmoid\"))\r\n\r\nmodel.summary() # prints a summary of the model\r\n\r\nmodel.compile(optimizer='Adam', loss='binary_crossentropy', metrics=[\"accuracy\"])\r\n\r\nx_val = train_data[:10000]\r\nx_train = train_data[10000:]\r\n\r\ny_val = train_labels[:10000]\r\ny_train = train_labels[10000:]\r\n\r\n# 6-Train Model\r\n\r\nfitModel = model.fit(x_train, y_train, epochs=40, batch_size=512, validation_data=(x_val, y_val), verbose=1)\r\n\r\n# 7- evaluate Model\r\n\r\nresults = model.evaluate(test_data, test_labels)\r\nprint(\"Probability Distribution of output:\",results)\r\n\r\n#8- Save model\r\nmodel.save(\"model.h5\") # name it whatever you want but end with .h5\r\n# 9- Make Prediction with new data\r\n\r\n# load saved model\r\nmodel = keras.models.load_model(\"model.h5\")\r\n\r\ndef review_encode(s):\r\n\tencoded = [11]\r\n\r\n\tfor word in s:\r\n\t\tif word.lower() in word_index:\r\n\t\t\tencoded.append(word_index[word.lower()])\r\n\t\telse:\r\n\t\t\tencoded.append(2)\r\n\r\n\treturn encoded\r\n\r\nwith open(\"test.txt\", encoding=\"utf-8\") as f:\r\n\tfor line in f.readlines():\r\n\t\tnline = line.replace(\",\", \"\").replace(\".\", \"\").replace(\"(\", \"\").replace(\")\", \"\").replace(\":\", \"\").replace(\"\\\"\",\"\").strip().split(\" \")\r\n\t\tencode = review_encode(nline)\r\n\t\tencode = keras.preprocessing.sequence.pad_sequences([encode], value=word_index[\"\"], padding=\"post\", maxlen=250) # make the data 250 words long\r\n\t\tpredict = model.predict(encode)\r\n\t\tprint(line)\r\n\t\tprint(encode)\r\n\t\tprint(predict[0])","sub_path":"TensorFlow2.0/4.Text Classification_imdb_review.py","file_name":"4.Text Classification_imdb_review.py","file_ext":"py","file_size_in_byte":3100,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"385085335","text":"import requests\nimport json\nimport time\n\ntoken = \"access_token=1cb664b7a063c1f916e43efbb6b4ff196b998f8d4d949a8ca7f589427d943a03b3121c47f03ff3c019752\"\nmethod = ['messages.send', \"messages.get\"]\nbody = \"https://api.vk.com/method/\"\nk = 10\nlast_mes = 159\nwhile True:\n params = 'out=0' + '&'\n request = body + method[1] + \"?\" + params + \"&\" + token\n r = requests.get(request)\n r_json = json.loads(r.text)\n print(r_json)\n try:\n user_id = r_json['response'][1]['uid']\n number_mes = r_json['response'][0]\n new_message = True\n except IndexError:\n new_message = False\n if new_message and number_mes != last_mes:\n text_mes = r_json['response'][1]['body']\n if text_mes != 'Chat-Bot':\n params = 'user_id=' + str(user_id) + '&' + 'message= ' + str(k) + ' ' + text_mes.upper()\n request_send_message = body + method[0] + \"?\" + params + \"&\" + token\n send_message = requests.get(request_send_message)\n send_message = send_message.text\n last_mes = number_mes\n else:\n while True:\n r = requests.get(request)\n user_id = r_json['response'][1]['uid']\n r_json = json.loads(r.text)\n print(r_json)\n try:\n number_mes = r_json['response'][0]\n new_message = True\n except IndexError:\n new_message = False\n if new_message and number_mes != last_mes:\n text_mes = r_json['response'][1]['body']\n\n print(send_message)\n k += 1\n time.sleep(0.5)\n","sub_path":"working.py","file_name":"working.py","file_ext":"py","file_size_in_byte":1644,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"129091499","text":"import matplotlib.pyplot as plt\nimport numpy as np\n\nfrom scipy import ndimage, exp, signal\nfrom scipy.io import loadmat\nfrom scipy.sparse import coo_matrix\nfrom scipy.special import comb\n\nfrom skimage.measure import block_reduce\nfrom sklearn import (manifold, datasets, metrics, decomposition, cluster, ensemble,discriminant_analysis, random_projection)\nfrom sklearn.neighbors import kneighbors_graph, KNeighborsClassifier\nfrom sklearn.cluster import KMeans\nfrom sklearn.preprocessing import StandardScaler\nfrom sklearn.multiclass import OneVsOneClassifier\nfrom sklearn.svm import LinearSVC\nfrom sklearn import svm\n\nimport skfuzzy as fuzz\n\n\n\ndef contingency_matrix(labels_true, labels_pred, eps=None):\n classes, class_idx = np.unique(labels_true, return_inverse=True)\n clusters, cluster_idx = np.unique(labels_pred, return_inverse=True)\n n_classes = classes.shape[0]\n n_clusters = clusters.shape[0]\n # Using coo_matrix to accelerate simple histogram calculation,\n # i.e. bins are consecutive integers\n # Currently, coo_matrix is faster than histogram2d for simple cases\n contingency = coo_matrix((np.ones(class_idx.shape[0]),\n (class_idx, cluster_idx)),\n shape=(n_classes, n_clusters),\n dtype=np.int).toarray()\n if eps is not None:\n # don't use += as contingency is integer\n contingency = contingency + eps\n return contingency\n\ndef check_clusterings(labels_true, labels_pred):\n \"\"\"Check that the two clusterings matching 1D integer arrays\"\"\"\n labels_true = np.asarray(labels_true)\n labels_pred = np.asarray(labels_pred)\n\n # input checks\n if labels_true.ndim != 1:\n raise ValueError(\n \"labels_true must be 1D: shape is %r\" % (labels_true.shape,))\n if labels_pred.ndim != 1:\n raise ValueError(\n \"labels_pred must be 1D: shape is %r\" % (labels_pred.shape,))\n if labels_true.shape != labels_pred.shape:\n raise ValueError(\n \"labels_true and labels_pred must have same size, got %d and %d\"\n % (labels_true.shape[0], labels_pred.shape[0]))\n return labels_true, labels_pred\n\ndef rand_score(labels_true, labels_pred):\n \n labels_true, labels_pred = check_clusterings(labels_true, labels_pred)\n n_samples = labels_true.shape[0]\n classes = np.unique(labels_true)\n clusters = np.unique(labels_pred)\n # Special limit cases: no clustering since the data is not split;\n # or trivial clustering where each document is assigned a unique cluster.\n # These are perfect matches hence return 1.0.\n if (classes.shape[0] == clusters.shape[0] == 1\n or classes.shape[0] == clusters.shape[0] == 0\n or classes.shape[0] == clusters.shape[0] == len(labels_true)):\n return 1.0\n\n contingency = contingency_matrix(labels_true, labels_pred)\n\n # Compute the ARI using the contingency data\n sum_comb_c = sum(comb2(n_c) for n_c in contingency.sum(axis=1))\n sum_comb_k = sum(comb2(n_k) for n_k in contingency.sum(axis=0))\n\n sum_comb = sum(comb2(n_ij) for n_ij in contingency.flatten())\n t_p=sum_comb\n f_p=sum_comb_c-sum_comb\n f_n=sum_comb_k-sum_comb\n t_n=float(comb(n_samples, 2))-t_p-f_p-f_n\n result=(t_n+t_p)/float(comb(n_samples, 2))\n return result\n\ndef comb2(n):\n # the exact version is faster for k == 2: use it by default globally in\n # this module instead of the float approximate variant\n return comb(n, 2, exact=1)\n\n\nif __name__ == '__main__':\n data = loadmat('Indian_pines_corrected.mat')\n data = data['indian_pines_corrected']\n\n gt = loadmat('Indian_pines_gt.mat')\n gt = gt['indian_pines_gt']\n \n sc = StandardScaler()\n data_std = sc.fit_transform(np.reshape(data,[145*145,200]))\n \n ######################\n LPCA = np.load(\"LPCA.npy\")\n Local_Split_PCA = np.load(\"Local_Split_PCA.npy\")\n Split_PCA = np.load(\"Split_PCA.npy\")\n GPCA = np.load(\"GPCA.npy\")\n \n ## Data can be LPCA, Local_Split_PCA, Split_PCA, GPCA, data\n Data = data \n N = np.shape(Data)[2]\n ######################\n # Stage 1: Uncomment C-mean OR K-mean\n # Cmeans:\n cntr, u, u0, d, jm, p, fpc = fuzz.cluster.cmeans(\n np.reshape(Data,[145*145,N]).T, 17, 2, error=0.005, maxiter=1000, init=None)\n labels = np.argmax(u,axis=0) \n \n # Kmeans \n# n_clusters = 17\n# Klabels = KMeans(n_clusters,n_init=145).fit_predict(np.reshape(Data,[145*145,N]))\n# labels=np.reshape(Klabels,(145,145))\n \n #Eliminating outliers: Uncomment First OR Second method\n # First Method_Using weights, Only applicable for C-means\n weights = np.amax(u,axis=0)\n threshold = 0.15\n inliers_indx = np.where(weights>threshold)\n inlier_labels = labels[inliers_indx]\n inliers = data_std[np.reshape(inliers_indx,[np.shape(inliers_indx)[1]]),:] \n \n \n # Second Method: Window Searching\n# window = 3\n# halfW = np.floor(window/2).astype(int)\n# inliers=np.empty([1,N])\n# inlier_labels=np.empty([1,1])\n# \n# for i in range(halfW,145-halfW):\n# for j in range(halfW,145-halfW):\n# ROI = np.reshape(labels,[145,145])[i-halfW:i+halfW,j-halfW:j+halfW]\n# if np.unique(ROI).shape[0]==1:\n# inliers=np.append(inliers,Data[i,j,:].reshape([1,N]),axis=0)\n# inlier_labels=np.append(inlier_labels,np.reshape(labels,[145,145])[i,j].reshape([1,1]),axis=0)\n# inliers=np.delete(inliers,0,axis=0)\n# inlier_labels=np.delete(inlier_labels,0,axis=0)\n# inlier_labels = np.reshape(inlier_labels,[inlier_labels.shape[0]])\n \n ######################\n # Stage 2: SVM\n SVM_labels = OneVsOneClassifier(LinearSVC(random_state=15)).fit(inliers, inlier_labels).predict(np.reshape(data_std,[145*145,200]))\n plt.imshow(gt) \n plt.imshow(np.reshape(SVM_labels,[145,145]))\n \n \n forgroundPix = np.where(gt>0)\n forgroundRows = forgroundPix[0]\n forgroundCols = forgroundPix[1]\n fgSVM = np.zeros([145,145])\n SVM_labels = np.reshape(SVM_labels,[145,145])\n fgSVM[forgroundRows,forgroundCols] = SVM_labels[forgroundRows,forgroundCols]\n fgXmean = np.zeros([145,145])\n labels = np.reshape(labels,[145,145])\n fgXmean[forgroundRows,forgroundCols] = labels[forgroundRows,forgroundCols]\n \n ######################\n # Results:\n print('rand score using SVM', 100*rand_score(np.reshape(gt[forgroundRows,forgroundCols],[forgroundRows.shape[0]]), np.reshape(SVM_labels[forgroundRows,forgroundCols],[forgroundRows.shape[0]])))\n print('rand score using Xmean', 100*rand_score(np.reshape(gt[forgroundRows,forgroundCols],[forgroundRows.shape[0]]), np.reshape(labels[forgroundRows,forgroundCols],[forgroundRows.shape[0]])))\n print('number of classes SVM: ',np.unique(inlier_labels).shape[0])\n print('number of classes Xmean: ',np.unique(labels).shape[0])\n plt.imshow(fgSVM)\n# plt.imsave(\"BestTwoStageAlg\",fgSVM)","sub_path":"cs4720/project 2/Hyper Spectral Image Segmentation/main_code/TwoStageClassification_Final.py","file_name":"TwoStageClassification_Final.py","file_ext":"py","file_size_in_byte":6879,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"100479600","text":"\"\"\"\nHtmlCrawler class\n\nWhen getting data from webpage, user HtmlCrawler\nit uses BeautifulSoup to find tag, class, id and etc.\n\"\"\"\n\n__author__ = 'sj'\n\nfrom bs4 import BeautifulSoup\nfrom BaseCrawler import BaseCrawler, CrawlerException\n\nclass HtmlCrawler(BaseCrawler):\n def getBs(self):\n try:\n data = BaseCrawler.getHtml(self)\n soup = BeautifulSoup(data, 'html.parser')\n except CrawlerException as e:\n raise CrawlerException(e)\n return soup","sub_path":"Crawler/181231/HtmlCrawler.py","file_name":"HtmlCrawler.py","file_ext":"py","file_size_in_byte":495,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"267248173","text":"#!/usr/bin/env python3\n#-*- coding:utf-8 -*-\n\n# pyCompact helper\n# copyright 2017-2018 Yun Dou (dixyes) \n# MIT License\n\n__author__=\"dixyes\"\n__copyright__=\"Copyright 2017-2018, dixyes\"\n__license__=\"MIT\"\n__version__=\"0.0.1\"\n__email__=\"me@dixy.es\"\n\nimport inspect,ntpath,sys,re\n\ncaller = lambda : \"{0[1]}:{0[2]}\".format(inspect.getouterframes(inspect.currentframe(),0)[2])\n\n# import cqapi or pesudoCqapi for commandline debug\nclass pseudoCqapi():\n '''\n pseudo cqapi module for console debug\n '''\n __author__=\"dixyes\"\n __copyright__=\"Copyright 2017-2018, dixyes\"\n __license__=\"MIT\"\n __version__=\"0.0.2\"\n __email__=\"me@dixy.es\"\n EVENT_IGNORE=1\t# 事件_忽略\n EVENT_BLOCK=2\t# 事件_拦截\n REQUEST_ALLOW=3\t# 请求_通过\n REQUEST_DENY=4\t# 请求_拒绝\n REQUEST_GROUPADD=5\t# 请求_群添加\n REQUEST_GROUPINVITE=6\t# 请求_群邀请\n LOGGER_DEBUG=1\t# 调试 灰色\n LOGGER_INFO=2\t# 信息 黑色\n LOGGER_INFOSUCCESS=3\t# 信息(成功) 紫色\n LOGGER_INFORECV=4\t# 信息(接收) 蓝色\n LOGGER_INFOSEND=5\t# 信息(发送) 绿色\n LOGGER_WARNING=6\t# 警告 橙色\n LOGGER_ERROR=7\t# 错误 红色\n LOGGER_FATAL=8\t# 致命错误 深红\n appdir=\"\"\n selfqq = 10000\n def logger(self,obj,type=LOGGER_DEBUG,tag=\"pseudoPyLogger\"):\n print(caller(),tag,obj.__repr__())\n def sendpm(self,qqid,msg):\n print(caller(), \"sending priv msg '%s' to %d\"%(msg,qqid))\n def sendgm(self,qqid,msg):\n print(caller(), \"sending group msg '%s' to %d\"%(msg,qqid))\n def senddm(self,qqid,msg):\n print(caller(), \"sending discuss msg '%s' to %d\"%(msg,qqid))\n def delmsg(self,msgid):\n print(caller(), \"deleting Message %d\"%(msgid))\ntry:\n cqapi = __import__(\"cqapi\")\nexcept ImportError as e:\n cqapi = pseudoCqapi()\n cqapi.log(\"using psudoCqapi\")\n raise e\nif not cqapi.__version__ == __version__:\n cqapi.log(\"not matched api version, update you helper.py!\", type=cqapi.LOGGER_WARNING, tag=\"develpoerWaring\")\ntry:\n from enum import Enum\nexcept ImportError:\n if sys.version_info[1] < 4:\n cqapi.logger(\"python is older then 3.4, install enum34 package!\", type=cqapi.LOGGER_WARNING, tag=\"develpoerWaring\")\n Enum = Object # dirty patch here\n\nclass MsgFrom(Enum):\n FRIEND = 11 # 来自好友\n ONLINESTATE = 1 # 来自在线状态\n GROUP =2 # 来自群\n DISCUSS =3 # 来自讨论组\n\ndef fuckGB(bytesMsg:bytes):\n \"\"\"you can also fuck GB18030 by this utility\"\"\"\n return bytesMsg.decode(\"GB18030\")\ndef defuckGB(strMsg:str):\n \"\"\"you can also defuck GB18030 by this utility\"\"\"\n return strMsg.encode(\"GB18030\")\n\nclass classproperty(object):\n def __init__(self, getter):\n self.getter= getter\n def __get__(self, instance, owner):\n return self.getter(owner)\n \nclass Event():\n known_events = {\n \"privMsg\":\"__eventPrivateMsg\",# v is string meaning it's alias\n \"PrivateMsg\":\"__eventPrivateMsg\",\n \"__eventPrivateMsg\":[(\"subType\",MsgFrom), \"msgId\", \"fromQQ\", (\"msg\", fuckGB), \"font\"],# [valueName,or (valueName, converter),...]\n \"grpMsg\":\"__eventGroupMsg\",\n \"__eventGroupMsg\":[(\"subType\",MsgFrom), \"msgId\", \"fromGroup\", \"fromQQ\", (\"fromAnonymous\", fuckGB), (\"msg\", fuckGB), \"font\"],\n }\n @classproperty\n def event_alias(cls):\n if hasattr(cls, \"_event_alias\"):\n return cls._event_alias\n cls._event_alias = {}\n for k in cls.known_events.keys():\n if isinstance(cls.known_events[k], str):\n if not cls._event_alias.get(cls.known_events[k]):\n cls._event_alias[cls.known_events[k]] = []\n cls._event_alias[cls.known_events[k]].append(k) \n return cls._event_alias\n def __init__(self, ev = (), name=\"BaseEvent\"):\n self._event = ev\n self._name = name\n \nclass DummyBot():\n \"\"\"\n BaseBot class\n \"\"\"\n name = \"BaseBot\"\n callbacks={}\n\n def __init__(self,name=None):\n self.name = name or self.name\n @staticmethod\n def recvEvent(eventName:str, event:tuple):\n \"\"\"\n parse event according to known_events dict\n \"\"\"\n ret = Event(event, eventName)\n if not eventName in Event.known_events: # not supported\n return ret\n if isinstance(Event.known_events[eventName],str): # this an alias\n eventName = Event.known_events[eventName]\n argFormats = Event.known_events.get(eventName,[])\n if not len(event) == len(argFormats):\n cqapi.logger('%s: different length between event and format' % caller(), tag=\"developerWaring\", type=cqapi.LOGGER_WARNING)\n for i in range(min(len(argFormats),len(event))):\n #print(i,argFormats[i],event[i])\n if isinstance(argFormats[i], str):\n setattr(ret, argFormats[i], event[i])\n else:\n setattr(ret, argFormats[i][0], argFormats[i][1](event[i]))\n #print(ret)\n return ret\n def on(self, eventName, defaultReturn = None):\n def _on(func):\n if not eventName in Event.known_events.keys():\n cqapi.logger('%s: unknown event name %s' % (caller(), eventName), tag=\"developerWaring\", type=cqapi.LOGGER_WARNING)\n def wrapper(event):\n g = func.__globals__\n eventDict = DummyBot.recvEvent(eventName,event)\n oldValue = g.get(\"event\", eventDict)\n g[\"event\"] = eventDict\n try:\n ret = func()\n finally:\n if oldValue is eventDict:\n del g['event']\n else:\n g['event'] = oldValue\n return ret\n if not self.callbacks.get(eventName):\n self.callbacks[eventName] = []\n self.callbacks[eventName].append(wrapper)\n return wrapper\n return _on\n #\n # PYCQAPI_VERSION 当前行为\n # 0.0.1 bot对象必须实现该方法:\n # emit(self:Bot, eventName:str, event:tuple)\n # 输入:self:bot对象, eventName:事件名称,event:时间数据\n def emit(self, eventName, event):\n #cqapi.logger(cbs)\n for cb in self.callbacks.get(eventName,[]):\n ret = cb(event)\n if ret and ret == cqapi.EVENT_BLOCK:\n return ret\n if eventName in Event.event_alias.keys():\n for alias in Event.event_alias[eventName]:\n print(alias,eventName)\n self.emit(alias, event)\n return cqapi.EVENT_IGNORE\n \n# from https://d.cqp.me/Pro/CQ%E7%A0%81\nclass CQCode():\n #class attr/methods\n _groupRe = None\n @classproperty\n def groupRe(cls):\n return cls._groupRe or re.compile(r\"\\[CQ:(?Pface|emoji|bface|sface|image|record|at|rps|dice|shake|anonymous|music|share)(?P[^]]*)\\]\")\n _argsRe = None\n @classproperty\n def argsRe(cls):\n return cls._groupRe or re.compile(r\",(?P[a-z]+)=(?P[^],]+) *\")\n @classmethod\n def parse(cls, s:str):\n ret = []\n for cq in cls.groupRe.findall(s):\n kwargs = {}\n for k,v in cls.argsRe.findall(cq[1]):\n kwargs[k] = v\n ret.append(CQCode(cq[0],**kwargs))\n return ret\n @staticmethod\n def isAt(s:str, qq:int):\n for cqc in CQCode.parse(s):\n if cqc.type == \"at\" and cqc.kvs[\"qq\"] == str(qq):\n return True\n return False\n @staticmethod\n def isAtMe(s:str):\n return CQCode.isAt(s, cqapi.selfqq)\n @classmethod\n def at(cls, qqid:int):\n return cls(\"at\",qq=str(qqid))\n # instance attr/methods\n def __init__(self, type, **args):\n self.type = type\n self.kvs = args\n #print(self.kvs)\n #print(self)\n def __str__(self):\n return \"[CQ:%s%s]\" % (self.type, \"\".join([\",%s=%s\" % (k,v) for k,v in self.kvs.items()]))\n def __repr__(self):\n return \"\" % (self.type, \"\".join([\",%s = \\\"%s\\\"\" % (k,v) for k,v in self.kvs.items()]))\n# TODO: multiple bot support\ndef addBot(bot):\n \"\"\"\n add bot.\n \"\"\"\n raise NotImplementedError\n \nif \"__main__\" == __name__:\n #recvEvent('__eventGroupMsg', (1, 469, 312123423, 123432231, b'', b'\\xd0\\xbb\\xd0\\xbb\\xd0\\xbb\\xd0\\xbb', 87760336))\n pass","sub_path":"pyfiles/helper.py","file_name":"helper.py","file_ext":"py","file_size_in_byte":8396,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"574379432","text":"import copy\nwith open(\"text1.txt\") as f:\n ol = f.read()\nol = ol.strip(\"\\n\")\n\nalp = [\"a\",\"b\",\"c\",\"d\",\"e\",\"f\",\"g\"]\n\nchr = []\nfor i in list(ol):\n if i in alp:\n chr.append(i)\n\nchr = sorted(list(set(chr)))\n\nbit_l = []\nfor i in range(2**len(chr)):\n l = copy.deepcopy(ol)\n for c in chr:\n nc = (i >> (len(chr)-chr.index(c)-1)) & 1\n l = l.replace(c,str(nc))\n l = l.replace(\"!\",\" not \").replace(\"&\", \" and \").replace(\"+\",\" or \")\n if eval(l):\n bit_l.append(i)\n\nif not bit_l:\n print(\"none\")\nelse:\n pl = []\n for cmb in bit_l:\n dc = {}\n for c in chr:\n if (cmb >> len(chr)-chr.index(c)-1) & 1:\n dc[c] = \"True\"\n else:\n dc[c] = \"False\"\n pl.append(dc)\n ans = []\n for l in pl:\n string = []\n for k in l:\n if l[k] == \"True\":\n string.append(k)\n else:\n string.append(\"!\"+k)\n st = \"&\".join(string)\n ans.append(st)\n ans = \"+\".join(ans)\n print(ans)\n\n\n\n","sub_path":"exam_problem/2013_win/problem5.py","file_name":"problem5.py","file_ext":"py","file_size_in_byte":1046,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"344703885","text":"#!/user/bin/python\nimport argparse\nfrom subprocess import call\nimport re\nimport os\n\ndefault_neo4j_url = 'http://neo4j.com/artifact.php?name=neo4j-community-2.1.6-unix.tar.gz'\np_tar = re.compile('(.*)\\?name=(.*)')\np_dir = re.compile('(.*)\\?name=(.*)(-unix\\.tar\\.gz)')\n\n\ndef download_and_extract(url):\n tar_path = p_tar.match(url).group(2)\n dir_path = p_dir.match(url).group(2)\n if not os.path.exists(tar_path):\n call(['wget','-O',tar_path, url])\n if not os.path.exists(dir_path):\n call(['tar', '-zxf', tar_path])\n\n\ndef start_neo4j(url):\n dir_path = p_dir.match(url).group(2)\n conf = os.path.join(dir_path, 'conf', 'neo4j.properties')\n call(['sed','-i','s/^#allow/allow/g', conf])\n jvm_conf = os.path.join(dir_path,'con','neo4j-wrapper.properties')\n call(['sed','-i','s/^#wrapper.java.initmemory/wrapper.java.initmemory/g',jvm_conf])\n call(['sed','-i','s/^#wrapper.java.maxmemory/wrapper.java.initmemory/g',jvm_conf])\n #call(['bash',os.path.join(dir_path,'bin','neo4j'),'start'])\n\nif __name__ == '__main__':\n\n parser = argparse.ArgumentParser()\n parser.add_argument(\"--url\", type=str, action=\"store\",\n default=default_neo4j_url, help=\"neo4j source url\")\n\n args = parser.parse_args()\n download_and_extract(args.url)\n start_neo4j(args.url)\n","sub_path":"bin/setup_neo4j.py","file_name":"setup_neo4j.py","file_ext":"py","file_size_in_byte":1321,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"397623764","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 ('cards', '0003_card_card_id'),\n ('games', '0018_auto_20150107_1807'),\n ]\n\n operations = [\n migrations.RemoveField(\n model_name='hand',\n name='cards',\n ),\n migrations.RemoveField(\n model_name='hand',\n name='player',\n ),\n migrations.DeleteModel(\n name='Hand',\n ),\n migrations.AlterModelOptions(\n name='player',\n options={'ordering': ['-order']},\n ),\n migrations.AddField(\n model_name='player',\n name='hand',\n field=models.ManyToManyField(blank=True, to='cards.Card'),\n preserve_default=True,\n ),\n migrations.AlterField(\n model_name='board',\n name='cards',\n field=models.ManyToManyField(blank=True, to='cards.Card'),\n preserve_default=True,\n ),\n ]\n","sub_path":"games/migrations/0019_auto_20150107_2035.py","file_name":"0019_auto_20150107_2035.py","file_ext":"py","file_size_in_byte":1088,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"84165089","text":"# -*- coding: utf-8 -*-\n\nfrom datetime import datetime, timedelta\nimport queue\nimport random\nimport itertools\nimport math\ntry:\n from cStringIO import StringIO\nexcept ImportError:\n from io import StringIO\nfrom moesifapi.moesif_api_client import *\nfrom .update_companies import Company\nfrom .update_users import User\nfrom .app_config import AppConfig\nfrom .parse_body import ParseBody\nfrom .logger_helper import LoggerHelper\nfrom .moesif_data_holder import DataHolder\nfrom .event_mapper import EventMapper\nfrom .send_batch_events import SendEventAsync\nfrom .client_ip import ClientIp\nfrom .http_response_catcher import HttpResponseCatcher\nfrom moesifpythonrequest.start_capture.start_capture import StartCapture\nfrom apscheduler.schedulers.background import BackgroundScheduler\nfrom apscheduler.triggers.interval import IntervalTrigger\nfrom apscheduler.events import EVENT_JOB_ERROR, EVENT_JOB_EXECUTED\nimport atexit\nimport logging\n\n\nclass MoesifMiddleware(object):\n \"\"\"WSGI Middleware for recording of request-response\"\"\"\n def __init__(self, app, settings):\n self.app = app\n try:\n self.request_counter = itertools.count().next # Threadsafe counter for Python 2\n except AttributeError:\n self.request_counter = itertools.count().__next__ # Threadsafe counter for Python 3\n\n if settings is None:\n raise Exception('Moesif Application ID is required in settings')\n self.settings = settings\n\n if settings.get('APPLICATION_ID', None):\n self.client = MoesifAPIClient(settings.get('APPLICATION_ID'))\n else:\n raise Exception('Moesif Application ID is required in settings')\n\n if settings.get('DEBUG', False):\n Configuration.BASE_URI = self.get_configuration_uri(settings, 'BASE_URI', 'LOCAL_MOESIF_BASEURL')\n Configuration.version = 'moesifwsgi-python/1.3.5'\n self.DEBUG = settings.get('DEBUG', False)\n if settings.get('CAPTURE_OUTGOING_REQUESTS', False):\n try:\n if self.DEBUG:\n print('Start capturing outgoing requests')\n # Start capturing outgoing requests\n StartCapture().start_capture_outgoing(settings)\n except:\n print('Error while starting to capture the outgoing events')\n self.api_version = settings.get('API_VERSION')\n self.api_client = self.client.api\n self.LOG_BODY = self.settings.get('LOG_BODY', True)\n if self.DEBUG:\n response_catcher = HttpResponseCatcher()\n self.api_client.http_call_back = response_catcher\n self.client_ip = ClientIp()\n self.app_config = AppConfig()\n self.parse_body = ParseBody()\n self.logger_helper = LoggerHelper()\n self.event_mapper = EventMapper()\n self.send_async_events = SendEventAsync()\n self.config_etag = None\n self.config = self.app_config.get_config(self.api_client, self.DEBUG)\n self.sampling_percentage = 100\n self.last_updated_time = datetime.utcnow()\n self.moesif_events_queue = queue.Queue()\n self.BATCH_SIZE = self.settings.get('BATCH_SIZE', 25)\n self.last_event_job_run_time = datetime(1970, 1, 1, 0, 0) # Assuming job never ran, set it to epoch start time\n self.scheduler = None\n self.is_event_job_scheduled = False\n try:\n if self.config:\n self.config_etag, self.sampling_percentage, self.last_updated_time = self.app_config.parse_configuration(\n self.config, self.DEBUG)\n except Exception as ex:\n if self.DEBUG:\n print('Error while parsing application configuration on initialization')\n print(str(ex))\n\n # Function to get configuration uri\n def get_configuration_uri(self, settings, field, deprecated_field):\n uri = settings.get(field)\n if uri:\n return uri\n else:\n return settings.get(deprecated_field, 'https://api.moesif.net')\n\n def __call__(self, environ, start_response):\n data_holder = DataHolder(\n self.settings.get('DISABLED_TRANSACTION_ID', False),\n self.request_counter(),\n environ['REQUEST_METHOD'],\n self.logger_helper.request_url(environ),\n self.client_ip.get_client_address(environ),\n self.logger_helper.get_user_id(environ, self.settings, self.app, self.DEBUG),\n self.logger_helper.get_company_id(environ, self.settings, self.app, self.DEBUG),\n self.logger_helper.get_metadata(environ, self.settings, self.app, self.DEBUG),\n self.logger_helper.get_session_token(environ, self.settings, self.app, self.DEBUG),\n [(k, v) for k,v in self.logger_helper.parse_request_headers(environ)],\n *self.logger_helper.request_body(environ)\n )\n\n def _start_response(status, response_headers, *args):\n # Capture status and response_headers for later processing\n data_holder.capture_response_status(status, response_headers)\n return start_response(status, response_headers, *args)\n\n response_chunks = data_holder.finish_response(self.app(environ, _start_response))\n\n # return data to WSGI server\n try:\n return response_chunks\n finally:\n if not self.logger_helper.should_skip(environ, self.settings, self.app, self.DEBUG):\n random_percentage = random.random() * 100\n\n self.sampling_percentage = self.app_config.get_sampling_percentage(self.config,\n self.logger_helper.get_user_id(environ, self.settings, self.app, self.DEBUG),\n self.logger_helper.get_company_id(environ, self.settings, self.app, self.DEBUG))\n\n if self.sampling_percentage >= random_percentage:\n # Prepare event to be sent to Moesif\n event_data = self.process_data(data_holder)\n if event_data:\n # Add Weight to the event\n event_data.weight = 1 if self.sampling_percentage == 0 else math.floor(100 / self.sampling_percentage)\n try:\n if not self.is_event_job_scheduled and datetime.utcnow() > self.last_event_job_run_time + timedelta(\n minutes=5):\n try:\n self.schedule_background_job()\n self.is_event_job_scheduled = True\n self.last_event_job_run_time = datetime.utcnow()\n except Exception as ex:\n self.is_event_job_scheduled = False\n if self.DEBUG:\n print('Error while starting the event scheduler job in background')\n print(str(ex))\n # Add Event to the queue\n if self.DEBUG:\n print('Add Event to the queue')\n self.moesif_events_queue.put(event_data)\n except Exception as ex:\n if self.DEBUG:\n print(\"Error while adding event to the queue\")\n print(str(ex))\n else:\n if self.DEBUG:\n print('Skipped Event as the moesif event model is None')\n else:\n if self.DEBUG:\n print(\"Skipped Event due to sampling percentage: \" + str(self.sampling_percentage) + \" and random percentage: \" + str(random_percentage))\n else:\n if self.DEBUG:\n print('Skipped Event using should_skip configuration option')\n\n def process_data(self, data):\n\n # Prepare Event Request Model\n event_req = self.event_mapper.to_request(data, self.LOG_BODY, self.api_version)\n\n # Prepare Event Response Model\n event_rsp = self.event_mapper.to_response(data, self.LOG_BODY, self.DEBUG)\n\n # Prepare Event Model\n event_model = self.event_mapper.to_event(data, event_req, event_rsp)\n\n # Mask Event Model\n return self.logger_helper.mask_event(event_model, self.settings, self.DEBUG)\n\n # Function to listen to the send event job response\n def moesif_event_listener(self, event):\n if event.exception:\n if self.DEBUG:\n print('Error reading response from the scheduled job')\n else:\n if event.retval:\n response_etag, self.last_event_job_run_time = event.retval\n if response_etag is not None \\\n and self.config_etag is not None \\\n and self.config_etag != response_etag \\\n and datetime.utcnow() > self.last_updated_time + timedelta(minutes=5):\n try:\n self.config = self.app_config.get_config(self.api_client, self.DEBUG)\n self.config_etag, self.sampling_percentage, self.last_updated_time = self.app_config.parse_configuration(\n self.config, self.DEBUG)\n except Exception as ex:\n if self.DEBUG:\n print('Error while updating the application configuration')\n print(str(ex))\n\n def schedule_background_job(self):\n try:\n if not self.scheduler:\n self.scheduler = BackgroundScheduler(daemon=True)\n if not self.scheduler.get_jobs():\n self.scheduler.add_listener(self.moesif_event_listener, EVENT_JOB_EXECUTED | EVENT_JOB_ERROR)\n self.scheduler.start()\n self.scheduler.add_job(\n func=lambda: self.send_async_events.batch_events(self.api_client, self.moesif_events_queue,\n self.DEBUG, self.BATCH_SIZE),\n trigger=IntervalTrigger(seconds=2),\n id='moesif_events_batch_job',\n name='Schedule events batch job every 2 second',\n replace_existing=True)\n\n # Avoid passing logging message to the ancestor loggers\n logging.getLogger('apscheduler.executors.default').setLevel(logging.WARNING)\n logging.getLogger('apscheduler.executors.default').propagate = False\n\n # Exit handler when exiting the app\n atexit.register(lambda: self.send_async_events.exit_handler(self.scheduler, self.DEBUG))\n except Exception as ex:\n if self.DEBUG:\n print(\"Error when scheduling the job\")\n print(str(ex))\n\n def update_user(self, user_profile):\n User().update_user(user_profile, self.api_client, self.DEBUG)\n\n def update_users_batch(self, user_profiles):\n User().update_users_batch(user_profiles, self.api_client, self.DEBUG)\n\n def update_company(self, company_profile):\n Company().update_company(company_profile, self.api_client, self.DEBUG)\n\n def update_companies_batch(self, companies_profiles):\n Company().update_companies_batch(companies_profiles, self.api_client, self.DEBUG)\n","sub_path":"moesifwsgi/middleware.py","file_name":"middleware.py","file_ext":"py","file_size_in_byte":11743,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"399061105","text":"import tkinter as tk\nfrom tkinter.ttk import LabelFrame, Combobox\n\nclass MenuMath(LabelFrame):\n def __init__(self, master=None,borderwidth=3, width=100, height=50, menu_display=None):\n super().__init__(master, borderwidth=borderwidth, width=width, height=height, relief='groove', text=\"math\")\n self.menu_display=menu_display\n self.grid_propagate(0)\n for k in range(2):\n self.columnconfigure(k, pad=3)\n for i in range(3):\n self.rowconfigure(i, pad=3)\n self.calc_combo = Combobox(self, values=[\"None\", \"C+C\", \"C-C\", \"C*C\"], width=10)\n self.calc_combo.current(0)\n self.calc_combo.grid(row=0, column=0, padx=3, pady=5)\n self.calc_combo.bind('', self.calc_combo_event_handler)\n self.cc_sel_channel1=Combobox(self, values=[\"1\"], width=10)\n self.cc_sel_channel2=Combobox(self, values=[\"1\"], width=10)\n self.cc_sel_channel1.bind('', self.set_math_active)\n self.cc_sel_channel2.bind('', self.set_math_active)\n self.lab_channel1=tk.Label(self, text=\"channel 1\")\n self.lab_channel2=tk.Label(self, text=\"channel 2\")\n self.nb_channel=1\n self.math_active=False\n \n def set_nb_channel(self, nb_channel):\n if nb_channel!=0:\n self.nb_channel=nb_channel\n \n def display_none_menu(self):\n \n self.cc_sel_channel1.grid_remove()\n self.cc_sel_channel2.grid_remove()\n self.lab_channel1.grid_remove()\n self.lab_channel2.grid_remove()\n \n def display_cc_menu(self):\n channel_list=[\"ch \"+str(k+1) for k in range(self.nb_channel)]\n self.cc_sel_channel1['values']=channel_list\n self.cc_sel_channel2['values']=channel_list\n self.cc_sel_channel1.current(0)\n self.cc_sel_channel2.current(0)\n self.cc_sel_channel1.grid(row=2, column=0, padx=3, pady=3)\n self.cc_sel_channel2.grid(row=2, column=1, padx=3, pady=3)\n self.lab_channel1.grid(row=1, column=0, padx=3, pady=3)\n self.lab_channel2.grid(row=1, column=1, padx=3, pady=3)\n def calc_combo_event_handler(self, event):\n calc=self.calc_combo.get()\n if calc==\"None\":\n self.display_none_menu()\n else:\n self.display_cc_menu()\n def get_calc(self):\n calc_cmd=dict()\n calc=self.calc_combo.get()\n if calc==\"None\":\n calc_cmd[\"calc\"]=\"None\"\n self.math_active=False\n else:\n ch1=self.cc_sel_channel1.get()[3:]\n ch2=self.cc_sel_channel2.get()[3:]\n print(ch1, ch2)\n if ch1.isnumeric():\n ch1_i=int(ch1)\n elif ch1==\"math\":\n ch1_i=-1\n else: \n ch1_i=0\n if ch2.isnumeric():\n ch2_i=int(ch2)\n elif ch2==\"math\":\n ch2_i=-1\n else:\n ch2_i=0\n if ch1_i==ch2_i:\n calc_cmd[\"calc\"]=\"None\"\n self.math_active=False\n else:\n calc_cmd[\"calc\"]=calc\n calc_cmd[\"ch1\"]=ch1_i-1\n calc_cmd[\"ch2\"]=ch2_i-1\n self.math_active=True\n return(calc_cmd)\n def set_math_active(self, event):\n calc_cmd=self.get_calc()\n if calc_cmd[\"calc\"]==\"None\":\n self.menu_display.set_math(False)\n else:\n self.menu_display.set_math(True)\n","sub_path":"menu_math.py","file_name":"menu_math.py","file_ext":"py","file_size_in_byte":3459,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"23116540","text":"import sys, os\n\ndef test_untabify( txt_tabbed, txt_untabbed ):\n open('a.txt','wb').write(txt_tabbed)\n\n os.system('%s %s -w 4 a.txt' % (sys.executable, '../untabtree.py'))\n\n buf = open('a.txt','rb').read()\n if buf != txt_untabbed:\n raise Exception(\"untabify FAILED\")\n else:\n print(\"untabify: OK\")\n\ndef test_tabify( txt_untabbed, txt_tabbed ):\n open('a.txt','wb').write(txt_untabbed)\n\n os.system('%s %s a.txt' % (sys.executable, '../tabtree.py'))\n\n buf = open('a.txt','rb').read()\n if buf != txt_tabbed:\n raise Exception(\"tabify FAILED\")\n else:\n print(\"tabify: OK\")\t\t\n\n\nuntabbed_1 = \"\"\"\n\\\"\\\"\\\"\n Two spaces inside a comment.\n\\\"\\\"\\\"\n\ndef aaa():\n\\x20\\x20\\x20\\x20i = 1\n\"\"\"\n\ntabbed_1 = \"\"\"\n\\\"\\\"\\\"\n Two spaces inside a comment.\n\\\"\\\"\\\"\n\ndef aaa():\n\\ti = 1\n\"\"\"\n\ntest_tabify(untabbed_1, tabbed_1)\n","sub_path":"disthelper/scripts/test/test_tabs_2.py","file_name":"test_tabs_2.py","file_ext":"py","file_size_in_byte":846,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"307516808","text":"def commandPeasant(peasant, coins):\n coin = peasant.findNearest(coins)\n if coin:\n hero.command(peasant, \"move\", coin.pos)\n\n\nfriends = hero.findFriends()\npeasants = {\n \"Aurum\": friends[0],\n \"Argentum\":friends[1],\n \"Cuprum\":friends[2]\n}\n\nwhile True:\n items = hero.findItems()\n goldCoins = [];\n silverCoins = [];\n bronzeCoins = [];\n for item in items:\n if item.value == 3:\n goldCoins.push(item)\n elif item.value == 2:\n silverCoins.push(item)\n elif item.value == 1:\n bronzeCoins.push(item)\n commandPeasant(peasants.Aurum, goldCoins)\n commandPeasant(peasants.Argentum, silverCoins)\n commandPeasant(peasants.Cuprum, bronzeCoins)\n","sub_path":"8_Cloudrip_Mountain/440-Resource_Valleys/resource_valley.py","file_name":"resource_valley.py","file_ext":"py","file_size_in_byte":723,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"635941986","text":"# U27.1 Quiz: Pick One\r\nprint(\"# U27.1 Quiz: Pick One\")\r\n# Define a procedure, pick_one, that takes three inputs: a Boolean\r\n# and two other values. If the first input is True, it should return\r\n# the second input. If the first input is False, it should return the\r\n# third input.\r\n\r\n# For example, pick_one(True, 37, 'hello') should return 37, and\r\n# pick_one(False, 37, 'hello') should return 'hello'.\r\n\r\n# moj:\r\ndef pick_one(m, n, p):\r\n if m == True:\r\n return n\r\n else:\r\n return p\r\n\r\n# njihov:\r\ndef pick_one(boolean, true_response, false_response):\r\n if boolean:\r\n return true_response\r\n else:\r\n return false_response\r\n\r\nprint(pick_one(True, 37, 'hello'))\r\n#>>> 37\r\nprint(pick_one(False, 37, 'hello'))\r\n#>>> hello\r\nprint(pick_one(True, 'red pill', 'blue pill'))\r\n#>>> red pill\r\nprint(pick_one(False, 'sunny', 'rainy'))\r\n#>>> rainy\r\n\r\n# U27.2 Quiz: Triangular Numbers\r\nprint(\"# U27.2 Quiz: Triangular Numbers\")\r\n# The triangular numbers are the numbers 1, 3, 6, 10, 15, 21, ...\r\n# They are calculated as follows.\r\n\r\n# 1\r\n# 1 + 2 = 3\r\n# 1 + 2 + 3 = 6\r\n# 1 + 2 + 3 + 4 = 10\r\n# 1 + 2 + 3 + 4 + 5 = 15\r\n\r\n# Write a procedure, triangular, that takes as its input a positive\r\n# integer n and returns the nth triangular number.\r\n\r\n# moj sa izrazom sa foruma:\r\ndef triangular(n):\r\n return int((n*(n+1))/2)\r\n\r\n# njihov:\r\ndef triangular(n):\r\n number = 0\r\n for i in range(1, n+1):\r\n number = number + i\r\n return number\r\nprint(triangular(1))\r\n#>>>1\r\nprint(triangular(3))\r\n#>>> 6\r\nprint(triangular(10))\r\n#>>> 55\r\n","sub_path":"exercise_6.py","file_name":"exercise_6.py","file_ext":"py","file_size_in_byte":1561,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"4177001","text":"# Copyright 2022 The KerasCV Authors\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# https://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\nimport tensorflow as tf\n\nfrom keras_cv import bounding_box\n\n\nclass BoundingBoxUtilTestCase(tf.test.TestCase):\n def test_clip_to_image(self):\n # Test xyxy format unbatched\n height = 256\n width = 256\n bboxes = tf.convert_to_tensor(\n [[200, 200, 400, 400, 0], [100, 100, 300, 300, 0]]\n )\n image = tf.ones(shape=(height, width, 3))\n bboxes_out = bounding_box.clip_to_image(\n bboxes, bounding_box_format=\"xyxy\", images=image\n )\n self.assertAllGreaterEqual(bboxes_out, 0)\n x1, y1, x2, y2, rest = tf.split(bboxes_out, [1, 1, 1, 1, -1], axis=1)\n self.assertAllLessEqual([x1, x2], width)\n self.assertAllLessEqual([y1, y2], height)\n # Test relative format batched\n image = tf.ones(shape=(1, height, width, 3))\n bboxes = tf.convert_to_tensor(\n [[[0.2, -1, 1.2, 0.3, 0], [0.4, 1.5, 0.2, 0.3, 0]]]\n )\n bboxes_out = bounding_box.clip_to_image(\n bboxes, bounding_box_format=\"rel_xyxy\", images=image\n )\n self.assertAllLessEqual(bboxes_out, 1)\n\n def test_clip_to_image_filters_fully_out_bounding_boxes(self):\n # Test xyxy format unbatched\n height = 256\n width = 256\n bounding_boxes = tf.convert_to_tensor(\n [[257, 257, 400, 400, 0], [100, 100, 300, 300, 0]]\n )\n image = tf.ones(shape=(height, width, 3))\n bounding_boxes = bounding_box.clip_to_image(\n bounding_boxes, bounding_box_format=\"xyxy\", images=image\n )\n self.assertAllEqual(\n bounding_boxes,\n tf.convert_to_tensor([[-1, -1, -1, -1, -1], [100, 100, 256, 256, 0]]),\n )\n\n def test_clip_to_image_filters_fully_out_bounding_boxes_negative_area(self):\n # Test xyxy format unbatched\n height = 256\n width = 256\n bounding_boxes = tf.convert_to_tensor(\n [[257, 257, 100, 100, 0], [100, 100, 300, 300, 0]]\n )\n image = tf.ones(shape=(height, width, 3))\n bounding_boxes = bounding_box.clip_to_image(\n bounding_boxes, bounding_box_format=\"xyxy\", images=image\n )\n self.assertAllEqual(\n bounding_boxes,\n tf.convert_to_tensor([[-1, -1, -1, -1, -1], [100, 100, 256, 256, 0]]),\n )\n\n def test_pad_with_sentinels(self):\n bounding_boxes = tf.ragged.constant(\n [[[1, 2, 3, 4, 5], [1, 2, 3, 4, 5]], [[1, 2, 3, 4, 5]]]\n )\n padded_bounding_boxes = bounding_box.pad_with_sentinels(bounding_boxes)\n expected_output = tf.constant(\n [\n [[1, 2, 3, 4, 5], [1, 2, 3, 4, 5]],\n [[1, 2, 3, 4, 5], [-1, -1, -1, -1, -1]],\n ]\n )\n self.assertAllEqual(padded_bounding_boxes, expected_output)\n\n def test_filter_sentinels(self):\n bounding_boxes = tf.ragged.constant(\n [[[1, 2, 3, 4, 5], [1, 2, 3, 4, 5], [1, 2, 3, 4, -1]], [[1, 2, 3, 4, 5]]]\n )\n filtered_bounding_boxes = bounding_box.filter_sentinels(bounding_boxes)\n expected_output = tf.ragged.constant(\n [[[1, 2, 3, 4, 5], [1, 2, 3, 4, 5]], [[1, 2, 3, 4, 5]]], ragged_rank=1\n )\n self.assertAllEqual(filtered_bounding_boxes, expected_output)\n\n def test_filter_sentinels_unbatched(self):\n bounding_boxes = tf.convert_to_tensor(\n [[1, 2, 3, 4, 5], [1, 2, 3, 4, 5], [1, 2, 3, 4, -1]]\n )\n filtered_bounding_boxes = bounding_box.filter_sentinels(bounding_boxes)\n expected_output = tf.convert_to_tensor(\n [[1, 2, 3, 4, 5], [1, 2, 3, 4, 5]],\n )\n print(filtered_bounding_boxes, expected_output)\n self.assertAllEqual(filtered_bounding_boxes, expected_output)\n\n def test_filter_sentinels_tensor(self):\n bounding_boxes = tf.convert_to_tensor(\n [\n [[1, 2, 3, 4, 5], [1, 2, 3, 4, 5]],\n [[1, 2, 3, 4, 5], [1, 2, 3, 4, -1]],\n ]\n )\n filtered_bounding_boxes = bounding_box.filter_sentinels(bounding_boxes)\n\n expected_output = tf.ragged.constant(\n [[[1, 2, 3, 4, 5], [1, 2, 3, 4, 5]], [[1, 2, 3, 4, 5]]], ragged_rank=1\n )\n self.assertAllEqual(filtered_bounding_boxes, expected_output)\n\n def test_pad_with_class_id_ragged(self):\n bounding_boxes = tf.ragged.constant(\n [[[1, 2, 3, 4], [1, 2, 3, 4]], [[1, 2, 3, 4]]]\n )\n padded_bounding_boxes = bounding_box.add_class_id(bounding_boxes)\n expected_output = tf.ragged.constant(\n [[[1, 2, 3, 4, 0], [1, 2, 3, 4, 0]], [[1, 2, 3, 4, 0]]]\n )\n self.assertAllEqual(padded_bounding_boxes, expected_output)\n\n def test_pad_with_class_id_unbatched(self):\n bounding_boxes = tf.convert_to_tensor([[1, 2, 3, 4], [1, 2, 3, 4]])\n padded_bounding_boxes = bounding_box.add_class_id(bounding_boxes)\n expected_output = tf.convert_to_tensor([[1, 2, 3, 4, 0], [1, 2, 3, 4, 0]])\n self.assertAllEqual(padded_bounding_boxes, expected_output)\n\n def test_pad_with_class_id_exists(self):\n bounding_boxes = tf.ragged.constant(\n [[[1, 2, 3, 4, 0], [1, 2, 3, 4, 0]], [[1, 2, 3, 4, 0]]]\n )\n with self.assertRaisesRegex(\n ValueError,\n \"The number of values along the final axis of `bounding_boxes` is \"\n \"expected to be 4. But got 5.\",\n ):\n bounding_box.add_class_id(bounding_boxes)\n\n def test_pad_with_class_id_wrong_rank(self):\n bounding_boxes = tf.ragged.constant(\n [[[[1, 2, 3, 4], [1, 2, 3, 4]], [[1, 2, 3, 4]]]]\n )\n with self.assertRaisesRegex(\n ValueError,\n f\"`bounding_boxes` should be of rank 2 or 3. However \"\n f\"add_class_id received `bounding_boxes` of rank={4}\",\n ):\n bounding_box.add_class_id(bounding_boxes)\n","sub_path":"keras_cv/bounding_box/utils_test.py","file_name":"utils_test.py","file_ext":"py","file_size_in_byte":6494,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"302777326","text":"import boto3\nimport os\nfrom cf_invalidate import perform_invalidation\n\nBUCKET_POLICY = \"\"\"{\"Version\": \"2012-10-17\",\"Statement\": [{\"Sid\": \"PublicReadGetObject\",\"Effect\": \"Allow\",\"Principal\": \"*\",\"Action\": \"s3:GetObject\",\"Resource\": \"arn:aws:s3:::freedom-generator/*\"}]}\"\"\"\nBUCKET_NAME = 'fendull-website'\nDOMAIN_NAME = \"fendull.com\"\n\ns3_client = boto3.client('s3')\ns3 = boto3.resource('s3')\nb = s3.Bucket(BUCKET_NAME)\n\nif b.creation_date is None:\n print('S3 Bucket does not exist: creating a new one.')\n b.create()\n bp = s3.BucketPolicy(BUCKET_NAME)\n bp.put(ConfirmRemoveSelfBucketAccess=False, Policy=BUCKET_POLICY)\n bw = s3.BucketWebsite(BUCKET_NAME)\n bw.put(WebsiteConfiguration={\n 'ErrorDocument': {\n 'Key': 'index.html'\n },\n 'IndexDocument': {\n 'Suffix': 'index.html'\n }\n })\nprint('Emptying S3 Bucket...')\nb.objects.all().delete()\n\nprint('Uploading build directory to S3...')\nfor root, directories, filenames in os.walk('../web/build'):\n for filename in filenames:\n f = os.path.join(root, filename)\n if 'html' in f:\n g = open(f, 'rb')\n b.put_object(Body=g.read(), Key=f.replace('\\\\', '/').replace('../web/build/',''), ContentType='text/html')\n g.close()\n elif 'css' in f:\n g = open(f, 'rb')\n b.put_object(Body=g.read(), Key=f.replace('\\\\', '/').replace('../web/build/',''), ContentType='text/css')\n g.close()\n else:\n b.upload_file(f, f.replace('\\\\', '/').replace('../web/build/',''))\n \nperform_invalidation(DOMAIN_NAME)\nprint('Web is now hosted at http://{}.s3-website-us-east-1.amazonaws.com/'.format(BUCKET_NAME))","sub_path":"deploy/deploy_web.py","file_name":"deploy_web.py","file_ext":"py","file_size_in_byte":1709,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"216289668","text":"from collections import namedtuple\n\nEMPTY_STRING = ''\nVIDEO_REQUIRED_FIELDS = {'id', 'uploader', 'uploader_id', 'uploader_url',\n 'channel_id', 'channel_url', 'upload_date',\n 'license', 'creator', 'title', 'alt_title',\n 'thumbnail', 'description', 'categories', 'tags', 'ext'}\n\n_LevelsEnum = namedtuple('PRIVACY_LEVELS', 'private, public, unlisted')\nPRIVACY_LEVELS = _LevelsEnum('private', 'public', 'unlisted')\n\nYOUTUBE_CATEGORIES = {'Film & Animation': 1, 'Autos & Vehicles': 2, 'Music': 10, 'Pets & Animals': 15, 'Sports': 17,\n 'Short Movies': 18, 'Travel & Events': 19, 'Gaming': 20, 'Videoblogging': 21,\n 'People & Blogs': 22, 'Comedy': 34, 'Entertainment': 24, 'News & Politics': 25,\n 'Howto & Style': 26, 'Education': 27, 'Science & Technology': 28, 'Movies': 30,\n 'Anime/Animation': 31, 'Action/Adventure': 32, 'Classics': 33, 'Documentary': 35, 'Drama': 36,\n 'Family': 37, 'Foreign': 38, 'Horror': 39, 'Sci-Fi/Fantasy': 40, 'Thriller': 41, 'Shorts': 42,\n 'Shows': 43, 'Trailers': 44}\nENTERTAINMENT_CATEGORY = 24\n\nPOSSIBLE_VIDEO_FORMATS = {\".webm\", \".mp4\", \".avi\", \".mkv\"}\n","sub_path":"private/utils/constants.py","file_name":"constants.py","file_ext":"py","file_size_in_byte":1278,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"6428918","text":"# Copyright 2017. Allen Institute. All rights reserved\n#\n# Redistribution and use in source and binary forms, with or without modification, are permitted provided that the\n# following conditions are met:\n#\n# 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following\n# disclaimer.\n#\n# 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following\n# disclaimer in the documentation and/or other materials provided with the distribution.\n#\n# 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote\n# products derived from this software without specific prior written permission.\n#\n# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES,\n# INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\n# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,\n# WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n#\nimport numpy as np\nimport tensorflow as tf\nfrom bmtk.simulator.mintnet.Image_Library_Supervised import Image_Library_Supervised\nimport h5py\n\nclass Readout_Layer (object):\n\n def __init__(self,node_name,input_layer,K,lam,alt_image_dir='',file_name=None):\n\n self.node_name = node_name\n self.K = K\n self.input_layer = input_layer\n self.weight_file = file_name\n self.lam = lam\n\n self.alt_image_dir = alt_image_dir\n\n if file_name==None:\n new_weights=True\n self.train_state = False\n else:\n\n weight_h5 = h5py.File(self.weight_file,'a')\n file_open=True\n\n if self.node_name in weight_h5.keys():\n\n new_weights = False\n weight_data = weight_h5[self.node_name]['weights'].value\n self.train_state = weight_h5[self.node_name]['train_state'].value\n\n else:\n\n new_weights = True\n self.train_state =False\n weight_h5.create_group(self.node_name)\n weight_h5[self.node_name]['train_state']=self.train_state\n\n self.input = self.input_layer.input\n #self.tf_sess = self.input_layer.tf_sess\n self.tf_sess = tf.Session()\n\n self.w_shape = (self.input_layer.K,self.K)\n\n if new_weights:\n #weights=1.0*np.ones(self.w_shape).astype(np.float32)\n weights=100000*np.random.normal(size=self.w_shape).astype(np.float32)\n if file_name!=None:\n weight_h5[self.node_name].create_dataset('weights',shape=weights.shape,dtype=np.float32,compression='gzip',compression_opts=9)\n weight_h5[self.node_name]['weights'][...]=weights\n else:\n weights=weight_data\n\n self.weights = tf.Variable(weights.astype(np.float32),trainable=True,name='weights')\n self.weights.initializer.run(session=self.tf_sess)\n self.bias = tf.Variable(np.zeros(self.K,dtype=np.float32),trainable=True,name='bias')\n self.bias.initializer.run(session=self.tf_sess)\n\n # sigmoid doesn't seem to work well, and is slow\n #self.output = tf.sigmoid(tf.matmul(self.input_layer.output,W)+self.bias) \n\n self.input_placeholder = tf.placeholder(tf.float32,shape=(None,self.input_layer.K))\n #self.output = tf.nn.softmax(tf.matmul(self.input_placeholder,self.weights) + self.bias)\n self.linear = tf.matmul(self.input_placeholder,self.weights) #+ self.bias\n\n self.output = tf.sign(self.linear)\n #self.output = tf.nn.softmax(self.linear)\n #self.output = tf.nn.softmax(tf.matmul(self.input_layer.output,self.weights) + self.bias)\n\n self.y = tf.placeholder(tf.float32,shape=(None,self.K))\n\n\n #self.cost = -tf.reduce_mean(self.y*tf.log(self.output))\n self.cost = tf.reduce_mean((self.y - self.output)**2) + self.lam*(tf.reduce_sum(self.weights))**2\n\n # not gonna do much with current cost function :)\n self.train_step = tf.train.GradientDescentOptimizer(0.1).minimize(self.cost)\n\n self.num_units = self.K\n\n if file_open:\n weight_h5.close()\n\n def compute_output(self,X):\n\n #return self.tf_sess.run(self.output,feed_dict={self.input:X}) \n\n rep = self.input_layer.tf_sess.run(self.input_layer.output,feed_dict={self.input:X})\n\n return self.tf_sess.run(self.output,feed_dict={self.input_placeholder:rep})\n\n def predict(self,X):\n\n y_vals = self.compute_output(X)\n\n return np.argmax(y_vals,axis=1) \n\n def train(self,image_dir,batch_size=10,image_shape=(256,256),max_iter=200):\n\n print(\"Training\")\n\n im_lib = Image_Library_Supervised(image_dir,new_size=image_shape)\n\n # let's use the linear regression version for now\n training_lib_size = 225\n y_vals, image_data = im_lib(training_lib_size,sequential=True)\n\n y_vals = y_vals.T[0].T\n y_vals = 2*y_vals - 1.0\n\n print(y_vals)\n # print y_vals\n # print image_data.shape\n\n # import matplotlib.pyplot as plt\n # plt.imshow(image_data[0,:,:,0])\n # plt.figure()\n # plt.imshow(image_data[1,:,:,0])\n # plt.figure()\n # plt.imshow(image_data[9,:,:,0])\n\n # plt.show()\n\n num_batches = int(np.ceil(2*training_lib_size/float(batch_size)))\n rep_list = []\n for i in range(num_batches):\n print(i)\n # if i==num_batches-1:\n # rep = self.input_layer.tf_sess.run(self.input_layer.output,feed_dict={self.input:image_data[i*batch_size:i*batch_size + training_lib_size%batch_size]})\n # else: \n rep = self.input_layer.tf_sess.run(self.input_layer.output,feed_dict={self.input:image_data[i*batch_size:(i+1)*batch_size]})\n rep_list += [rep]\n\n rep = np.vstack(rep_list)\n\n\n C = np.dot(rep.T,rep) + self.lam*np.eye(self.input_layer.K)\n W = np.dot(np.linalg.inv(C),np.dot(rep.T,y_vals)).astype(np.float32)\n\n self.tf_sess.run(self.weights.assign(tf.expand_dims(W,1)))\n\n train_result = self.tf_sess.run(self.output,feed_dict={self.input_placeholder:rep})\n\n print(W)\n print(train_result.flatten())\n print(y_vals.flatten())\n #print (train_result.flatten() - y_vals.flatten())\n print(\"train error = \", np.mean((train_result.flatten() != y_vals.flatten())))\n\n from scipy.stats import norm\n target_mask = y_vals==1\n dist_mask = np.logical_not(target_mask)\n hit_rate = np.mean(train_result.flatten()[target_mask] == y_vals.flatten()[target_mask])\n false_alarm = np.mean(train_result.flatten()[dist_mask] != y_vals.flatten()[dist_mask])\n dprime = norm.ppf(hit_rate) - norm.ppf(false_alarm)\n print(\"dprime = \", dprime)\n\n # Test error\n im_lib = Image_Library_Supervised('/Users/michaelbu/Data/SerreOlivaPoggioPNAS07/Train_Test_Set/Test',new_size=image_shape)\n\n testing_lib_size = 300\n y_vals_test, image_data_test = im_lib(testing_lib_size,sequential=True)\n\n y_vals_test = y_vals_test.T[0].T\n y_vals_test = 2*y_vals_test - 1.0\n\n num_batches = int(np.ceil(2*testing_lib_size/float(batch_size)))\n rep_list = []\n for i in range(num_batches):\n print(i)\n # if i==num_batches-1:\n # rep = self.input_layer.tf_sess.run(self.input_layer.output,feed_dict={self.input:image_data[i*batch_size:i*batch_size + training_lib_size%batch_size]})\n # else: \n rep = self.input_layer.tf_sess.run(self.input_layer.output,feed_dict={self.input:image_data_test[i*batch_size:(i+1)*batch_size]})\n rep_list += [rep]\n\n rep_test = np.vstack(rep_list)\n\n test_result = self.tf_sess.run(self.output,feed_dict={self.input_placeholder:rep_test})\n\n #print test_result\n print(\"test error = \", np.mean((test_result.flatten() != y_vals_test.flatten())))\n target_mask = y_vals_test==1\n dist_mask = np.logical_not(target_mask)\n hit_rate = np.mean(test_result.flatten()[target_mask] == y_vals_test.flatten()[target_mask])\n false_alarm = np.mean(test_result.flatten()[dist_mask] != y_vals_test.flatten()[dist_mask])\n dprime = norm.ppf(hit_rate) - norm.ppf(false_alarm)\n print(\"dprime = \", dprime)\n\n print(rep_test.shape)\n\n\n # logistic regression unit\n # import time\n # for n in range(max_iter):\n # start = time.time()\n # print \"\\tIteration \", n\n\n # y_vals, image_data = im_lib(batch_size,sequential=True)\n\n # print \"\\tComputing representation\"\n # rep = self.input_layer.tf_sess.run(self.input_layer.output,feed_dict={self.input:image_data})\n\n # print \"\\tGradient descent step\"\n # #print \"rep shape = \", rep.shape\n # self.tf_sess.run(self.train_step,feed_dict={self.input_placeholder:rep,self.y:y_vals})\n\n \n # #self.tf_sess.run(self.train_step,feed_dict={self.input:image_data,self.y:y_vals})\n\n # #print \"\\t\\ttraining batch cost = \", self.tf_sess.run(self.cost,feed_dict={self.input:image_data,self.y:y_vals})\n\n # print \"\\t\\tTraining error = \", np.mean(np.abs(np.argmax(y_vals,axis=1) - self.predict(image_data)))\n # print y_vals\n # print\n # print self.predict(image_data)\n # print \"\\t\\ttraining batch cost = \", self.tf_sess.run(self.cost,feed_dict={self.input_placeholder:rep,self.y:y_vals})\n # print \"\\t\\ttraining linear model = \", self.tf_sess.run(self.linear,feed_dict={self.input_placeholder:rep,self.y:y_vals})\n\n # print \"\\t\\ttotal time = \", time.time() - start\n\n","sub_path":"bmtk/simulator/mintnet/hmax/Readout_Layer.py","file_name":"Readout_Layer.py","file_ext":"py","file_size_in_byte":10246,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"19504706","text":"# coding:utf8\n\nfrom django.shortcuts import render\n\nfrom msblog.models import Blog, Category, Album\nfrom msblog import service\nfrom django.template.defaultfilters import register\nfrom django.core.paginator import Paginator, EmptyPage, PageNotAnInteger\nimport re\nfrom mblog.settings import SYSTEM_SKIN_NAME\nfrom django.views.decorators.cache import cache_page\nfrom django.views.generic.base import TemplateView\n\nskin = SYSTEM_SKIN_NAME\npage_size = 9\n\n\n@register.filter(name='cstrip')\ndef content_breviary(content, size):\n if not content:\n content = ''\n # 替换注释\n content = re.sub(r').*-->', '', content)\n # 替换标签\n content = re.sub(r'<.*?>', '', content)\n if content and len(content) > size:\n return content[:size] + \"...\"\n else:\n return content\n\n\n# 主页\ndef blog_home(request):\n blogs = service.hot_blogs(5)\n lastest = service.lastest_blogs(8)\n suggestion = service.visit_blogs(8)\n return render(request, skin + '/home.html', {'blogs': blogs, 'lastest': lastest, 'suggestion': suggestion})\n\n\nclass AboutView(TemplateView):\n template_name = skin + '/about.html'\n\n\ndef blog_shuo(request):\n return render(request, skin + '/shuo.html', {})\n\n\ndef blog_album(request):\n lastest = service.lastest_blogs(8)\n suggestion = service.visit_blogs(8)\n photos = Album.objects.all()\n return render(request, skin + '/album.html', {'lastest': lastest, 'suggestion': suggestion, 'photos': photos})\n\n\ndef blog_board(request):\n return render(request, 'board.html', {})\n\n\n@cache_page(30 * 60, key_prefix=skin)\ndef blog_category(request, category_slug):\n category = Category.objects.get(category_slug=category_slug)\n blog_list = Blog.objects.filter(category__category_slug=category_slug)\n paginator = Paginator(blog_list, page_size)\n lastest = service.lastest_blogs(8)\n suggestion = service.visit_blogs(8)\n page = request.GET.get('page')\n try:\n blogs = paginator.page(page)\n except PageNotAnInteger:\n blogs = paginator.page(1)\n except EmptyPage:\n blogs = paginator.page(paginator.num_pages)\n return render(request, skin + '/list.html',\n {'page': page, 'blogs': blogs, 'category': category, 'lastest': lastest, 'suggestion': suggestion})\n\n\n@cache_page(60 * 60 * 24, key_prefix=skin)\ndef blog_detail(request, blog_id):\n article = service.get_blog_and_add_visits(blog_id)\n visits = service.visit_blogs(8)\n suggestion = service.hot_blogs(8)\n return render(request, skin + '/blog.html', {'article': article, 'visits': visits, 'suggestion': suggestion})\n","sub_path":"msblog/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2603,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"367103385","text":"import discord\nimport json\nfrom discord.ext import commands\nfrom random import choice\n\nclass Biography():\n \n def __init__(self, bot):\n self.bot = bot\n with open(bot.BIOGRAPHY_PATH, 'r', encoding=\"utf8\") as file:\n self.biography = json.load(file)\n\n @commands.command(\n name='bio',\n description=\"send a funy description of a given user\",\n brief=\"get one's biography\",\n pass_context=True)\n async def bio(self, ctx):\n await self.bot.say(\"kuku\")\n\ndef setup(bot):\n bot.add_cog(Biography(bot))\n\ndef updateBio(self, bio):\n#update a JSON file\n with open(self.bot.BIOGRAPHY_PATH, 'w', encoding='utf8') as file:\n json.dump(bio, file, indent=4)","sub_path":"Extensions/biography.py","file_name":"biography.py","file_ext":"py","file_size_in_byte":717,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"288360149","text":"\nfrom openstack_dashboard.api import nova as nova_api\nimport openstack_dashboard.api.keystone as keystone_api\nimport openstack_dashboard.api.glance as glance_api\n\ndef get_result(request, results):\n servers = nova_api.server_list(request) #get list of servers\n server_ids = [x[\"nova_instance_id\"] for x in results] #get list of nova id's from results\n instance_servers = [x for x in servers if x.id in server_ids] # get servers if server id is in results\n flavors = novaclient.server_list(request)\n server_flavors = [x[\"flavor\"] for x in instance_servers]\n instance_flavors = [x for x in flavors if x.id in server_flavors]\n tenants= keystone_api.tenant_list(request)\n\n for instance in results:\n for server in instance_servers:\n if instance[\"nova_instance_id\"] == server.id:\n for flavor in instance_flavors:\n if server[\"flavor\"].id == flavor.id:\n instance[\"flavor\"] = flavor\n \n for tenant in tenants:\n if server[\"tenant_id\"] == tenant.id:\n instance[\"owner\"] = tenant.name\n\n \n instance[\"image\"] = glance_api.image_get(request, server[\"image\"].id)\n\n return results\n\ndef migrate(request, id, host):\n nova_api.server_live_migrate(request, id, host)\n","sub_path":"a10_horizon/dashboard/admin/a10networks/instances/helper.py","file_name":"helper.py","file_ext":"py","file_size_in_byte":1366,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"504271279","text":"# file level_sensor_get.py\nimport requests\nimport datetime\n\n\nnow = datetime.datetime.now()\ndate_stamp = now.strftime(\"%Y-%b-%d %H:%M\")\n\nr= requests.get(\"https://app.alphax.cloud/api/WHI?tag=WHI-WTR06\")\n#print(r)\n#print(r.json())\ndepth = str(r.json()[0][\"val_calibrated\"])\nbat = str(r.json()[1][\"val_calibrated\"])\nsignal = str(r.json()[2][\"val_calibrated\"])\n\n\n\nf = open('/home/pi/botanica-park-lake/level_data.txt','a')\nf.write(date_stamp + \",\" + depth + \",\" + bat + \",\" + signal + \"\\n\")\nf.close()\nprint(\"WHI-WTR06 data collected and saved\")\n","sub_path":"level_sensor_get.py","file_name":"level_sensor_get.py","file_ext":"py","file_size_in_byte":541,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"196479949","text":"from django.conf.urls import url\nfrom . import views\n\n\nurlpatterns = [\n url(r'^$', views.index, name=\"index\"),\n url(r'^details/(?P\\w{0,50})/$', views.details),\n url(r'^add/(?P\\w{0,50})/$', views.add, name=\"add\"),\n url(r'^delete/(?P\\w{0,50})/$', views.delete, name=\"delete\"),\n url(r'^Note', views.Note, name ='Note'),\n url(r'^removeNote/(?P\\w{0,50})/$', views.removeNote, name=\"removeNote\")\n]","sub_path":"todo/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":425,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"179240530","text":"import os\r\nimport codecs\r\nimport spacy\r\nfrom spacy.matcher import PhraseMatcher\r\nimport pickle\r\nimport numpy as np\r\nimport pandas as pd\r\nfrom networkx import Graph, shortest_path\r\nfrom argparse import ArgumentParser\r\n\r\n\r\n# part of speech dict\r\n# https://universaldependencies.org/u/pos/\r\nPOS = {'adj': 0, 'adp': 1, 'adv': 2, 'aux': 3, 'cconj': 4, 'conj': 5, 'det': 6, 'intj': 7, 'noun': 8,\r\n 'num': 9, 'part': 10, 'pron': 11, 'propn': 12, 'punct': 13, 'sconj': 14, 'sym': 15, 'verb': 16, 'x': 17}\r\n# dependency dict\r\n# https://universaldependencies.org/u/dep/\r\nDEP = {'acl': 0, 'acomp': 1, 'advcl': 2, 'advmod': 3, 'agent': 4, 'amod': 5, 'appos': 6, 'attr': 7, 'aux': 8, 'auxpass': 9, 'case': 10, 'cc': 11, 'ccomp': 12, 'complm': 13, 'compound': 14, 'conj': 15, 'csubj': 16, 'csubjpass': 17, 'dative': 18, 'dep': 19, 'det': 20, 'dobj': 21, 'expl': 22, 'hmod': 23, 'hyph': 24, 'infmod': 25, 'intj': 26, 'iobj': 27, 'mark': 28, 'meta': 29,\r\n 'neg': 30, 'nmod': 31, 'nn': 32, 'nounmod': 33, 'npadvmod': 34, 'npmod': 35, 'nsubj': 36, 'nsubjpass': 37, 'num': 38, 'number': 39, 'nummod': 40, 'oprd': 41, 'parataxis': 42, 'partmod': 43, 'pcomp': 44, 'pobj': 45, 'poss': 46, 'possessive': 47, 'preconj': 48, 'predet': 49, 'prep': 50, 'prt': 51, 'punct': 52, 'quantmod': 53, 'rcmod': 54, 'relcl': 55, 'root': 56, 'xcomp': 57}\r\nNLP = spacy.load(\"en_core_web_sm\")\r\n\r\n\r\ndef get_vocab():\r\n path = os.path.join(os.path.abspath(\"\"), \"dataset\")\r\n vocab = np.empty((0, 5))\r\n for dataset in [\"dataset_1_rnd\", \"dataset_1_lex\"]:\r\n for part in [\"train.tsv\", \"val.tsv\", \"test.tsv\"]:\r\n data_part = pd.read_csv(os.path.join(\r\n path, dataset, part), delimiter=\"\\t\", header=None).values\r\n d = [dataset for i in range(data_part.shape[0])]\r\n p = [part for i in range(data_part.shape[0])]\r\n data_part = np.hstack(\r\n [data_part, np.array(d)[:, None], np.array(p)[:, None]])\r\n vocab = np.vstack([vocab, data_part])\r\n return vocab\r\n\r\ndef parse_sp(x, y, sentence):\r\n doc = NLP(u\"\" + str(sentence))\r\n\r\n # Find x and y phrase chunks in sentence\r\n matcher = PhraseMatcher(NLP.vocab, attr=\"LOWER\")\r\n matcher.add(\"X\", None, NLP(x), NLP(x + \"s\"))\r\n matcher.add(\"Y\", None, NLP(y), NLP(y + \"s\"))\r\n matches = matcher(doc)\r\n\r\n # Delete overlapping matches\r\n del_idx = []\r\n for i in range(len(matches)):\r\n (match_id_i, start_i, end_i) = matches[i]\r\n for j in range(i + 1, len(matches)):\r\n (match_id_j, start_j, end_j) = matches[j]\r\n if end_i >= start_j and end_i >= end_j:\r\n del_idx.append(j)\r\n elif end_i >= start_j and end_i <= end_j:\r\n if end_i - start_i >= end_j - start_j:\r\n del_idx.append(j)\r\n else:\r\n del_idx.append(i)\r\n else:\r\n pass\r\n matches = [match for idx, match in enumerate(\r\n matches) if idx not in del_idx]\r\n matches = sorted(matches, key=lambda z: z[1], reverse=True)\r\n\r\n # Choose one chunk for x and one chunk for y\r\n seen = set()\r\n matches = [(a, b, c)\r\n for a, b, c in matches if not (a in seen or seen.add(a))]\r\n assert len(matches) == 2\r\n\r\n # Merge x and y chunks\r\n for (match_id, start, end) in matches:\r\n string_id = NLP.vocab.strings[match_id]\r\n if string_id == \"X\":\r\n x_span = doc[start:end]\r\n x_span.merge(x_span.root.tag_, x_span.root.lemma_,\r\n x_span.root.ent_type_)\r\n else:\r\n y_span = doc[start:end]\r\n y_span.merge(y_span.root.tag_, y_span.root.lemma_,\r\n y_span.root.ent_type_)\r\n\r\n # Track x and y chunks\r\n x = x_span.lower_ + str(x_span.start)\r\n y = y_span.lower_ + str(y_span.start)\r\n\r\n # Get directed and undirected graphs\r\n graph_edges = []\r\n for token in doc:\r\n for child in token.children:\r\n graph_edges.append((token.lower_ + str(token.i),\r\n child.lower_ + str(child.i)))\r\n undirected_graph = Graph(graph_edges)\r\n\r\n # Shortest path between x and y\r\n p = []\r\n sp = shortest_path(undirected_graph, source=x, target=y)\r\n for token in doc:\r\n for child in token.children:\r\n if token.lower_ + str(token.i) in sp and child.lower_ + str(child.i) in sp:\r\n p.append((token.lower_ + str(token.i),\r\n child.lower_ + str(child.i)))\r\n\r\n # Gather edges with POS and DEP labels\r\n edges = []\r\n for edge in p:\r\n for token in doc:\r\n for child in token.children:\r\n if edge == (token.lower_ + str(token.i), child.lower_ + str(child.i)):\r\n if token.lower_ + str(token.i) == x and child.lower_ + str(child.i) == y:\r\n edges.append((\"x\",\r\n token.pos_.lower(),\r\n child.dep_,\r\n \"y\"))\r\n elif token.lower_ + str(token.i) == y and child.lower_ + str(child.i) == x:\r\n edges.append((\"y\",\r\n token.pos_.lower(),\r\n child.dep_,\r\n \"x\"))\r\n elif token.lower_ + str(token.i) == x:\r\n edges.append((\"x\",\r\n token.pos_.lower(),\r\n child.dep_,\r\n child.lower_))\r\n elif child.lower_ + str(child.i) == x:\r\n edges.append((token.lower_,\r\n token.pos_.lower(),\r\n child.dep_,\r\n \"x\"))\r\n elif token.lower_ + str(token.i) == y:\r\n edges.append((\"y\",\r\n token.pos_.lower(),\r\n child.dep_,\r\n child.lower_))\r\n elif child.lower_ + str(child.i) == y:\r\n edges.append((token.lower_,\r\n token.pos_.lower(),\r\n child.dep_,\r\n \"y\"))\r\n else:\r\n edges.append((token.lower_,\r\n token.pos_.lower(),\r\n child.dep_,\r\n child.lower_))\r\n\r\n return np.array(edges)\r\n\r\n\r\nif __name__ == \"__main__\":\r\n parser = ArgumentParser()\r\n parser.add_argument(\"-f\", \"--file\", required=True,\r\n help=\"batch size to use in training\")\r\n args = vars(parser.parse_args())\r\n\r\n VOCAB = get_vocab()\r\n in_file = os.path.join(os.path.abspath(\"\"), \"corpus\",\r\n \"wiki_text_parts\", args[\"file\"])\r\n out_file = os.path.join(os.path.abspath(\r\n \"\"), \"corpus\", \"wiki_text_parts\", \"wiki_data_\" + args[\"file\"][-2:])\r\n with codecs.open(in_file, \"r\", 'utf-8') as f_in:\r\n with codecs.open(out_file, \"w\", 'utf-8') as f_out:\r\n # Read the next paragraph\r\n for paragraph in f_in:\r\n # Skip empty lines\r\n paragraph = paragraph.replace(\"'''\", '').strip()\r\n if len(paragraph) == 0:\r\n continue\r\n parsed_par = NLP(u\"\" + (paragraph))\r\n\r\n # Parse each sentence separately\r\n for sent in parsed_par.sents:\r\n for v in VOCAB:\r\n if v[0].lower() in sent.lower_ and v[1].lower() in sent.lower_:\r\n try:\r\n edges = parse_sp(v[0], v[1], sent)\r\n if v[2]:\r\n if edges.shape[0] > 1:\r\n f_out.write(\"\\t\".join([str(v_i) for v_i in v]) + \"\\t\" +\r\n str(sent) + \"\\t[\" + \" \".join([str(e_i) for e_i in edges.flatten()]) + \"]\\n\")\r\n f_out.flush()\r\n else:\r\n f_out.write(\"\\t\".join([str(v_i) for v_i in v]) + \"\\t\" +\r\n str(sent) + \"\\t[\" +\" \".join([str(e_i) for e_i in edges.flatten()]) + \"]\\n\")\r\n f_out.flush()\r\n except Exception as e:\r\n continue\r\n f_out.close()\r\n f_in.close()\r\n","sub_path":"corpus/wiki_parse.py","file_name":"wiki_parse.py","file_ext":"py","file_size_in_byte":8752,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"219286635","text":"\"\"\"\nEnergy meter from sensors providing power information.\n\nFor more details about this platform, please refer to the documentation at\nhttps://home-assistant.io/components/sensor.energy/\n\"\"\"\nimport logging\n\nimport voluptuous as vol\n\nimport homeassistant.util.dt as dt_util\nimport homeassistant.helpers.config_validation as cv\nfrom homeassistant.components.sensor import (DOMAIN, PLATFORM_SCHEMA)\nfrom homeassistant.const import (\n CONF_NAME, ATTR_UNIT_OF_MEASUREMENT, ATTR_ENTITY_ID)\nfrom homeassistant.core import callback\nfrom homeassistant.helpers.event import async_track_state_change\nfrom homeassistant.helpers.restore_state import RestoreEntity\n\n_LOGGER = logging.getLogger(__name__)\n\nATTR_SOURCE_ID = 'source'\nATTR_LAST_RESET = 'last reset'\n\nSERVICE_RESET = 'energy_reset'\n\nSERVICE_RESET_SCHEMA = vol.Schema({\n vol.Required(ATTR_ENTITY_ID): cv.entity_id,\n})\n\nCONF_SOURCE_SENSOR = 'source_sensor'\nCONF_ROUND_DIGITS = 'round'\n\nUNIT_WATTS = \"W\"\nUNIT_KILOWATTS = \"kW\"\nUNIT_KILOWATTS_HOUR = \"kWh\"\n\nUNIT_OF_MEASUREMENT = UNIT_KILOWATTS_HOUR\nICON = 'mdi:counter'\n\nDEFAULT_ROUND = 3\n\nPLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({\n vol.Optional(CONF_NAME): cv.string,\n vol.Required(CONF_SOURCE_SENSOR): cv.entity_id,\n vol.Optional(CONF_ROUND_DIGITS, default=DEFAULT_ROUND): vol.Coerce(int),\n})\n\n\nasync def async_setup_platform(hass, config, async_add_entities,\n discovery_info=None):\n \"\"\"Set up the energy sensor.\"\"\"\n meter = EnergySensor(hass, config[CONF_SOURCE_SENSOR],\n config.get(CONF_NAME),\n config[CONF_ROUND_DIGITS])\n\n async_add_entities([meter])\n\n async def async_reset_meter(service):\n if service.data.get(ATTR_ENTITY_ID) == meter.entity_id:\n await meter.async_reset()\n\n hass.services.async_register(DOMAIN, SERVICE_RESET,\n async_reset_meter,\n schema=SERVICE_RESET_SCHEMA)\n\n return True\n \n\nclass EnergySensor(RestoreEntity):\n \"\"\"Representation of an energy sensor.\"\"\"\n\n def __init__(self, hass, source_entity, name, round_digits):\n \"\"\"Initialize the min/max sensor.\"\"\"\n self._hass = hass\n self._sensor_source_id = source_entity\n self._source_entity_id = False\n self._round_digits = round_digits\n self._state = 0\n self._last_reset = None\n\n if name:\n self._name = name\n else:\n self._name = '{} meter'.format(source_entity)\n\n self._unit_of_measurement = \"kWh\"\n self._unit_of_measurement_scale = None\n\n async def async_reset(self):\n \"\"\"Reset meter counters.\"\"\"\n _LOGGER.debug(\"Reset energy meter %s\", self.name)\n self._state = 0\n self._last_reset = dt_util.utcnow()\n\n async def async_added_to_hass(self):\n \"\"\"Handle entity which will be added.\"\"\"\n await super().async_added_to_hass()\n state = await self.async_get_last_state()\n if state:\n self._state = float(state.state)\n\n @callback\n def async_calc_energy(entity, old_state, new_state):\n \"\"\"Handle the sensor state changes.\"\"\"\n if old_state is None:\n return\n\n if self._unit_of_measurement_scale is None:\n unit_of_measurement = new_state.attributes.get(\n ATTR_UNIT_OF_MEASUREMENT)\n if unit_of_measurement == UNIT_WATTS:\n self._source_entity_id = True\n self._unit_of_measurement_scale = 1000\n elif unit_of_measurement == UNIT_KILOWATTS:\n self._source_entity_id = True\n self._unit_of_measurement_scale = 1\n elif unit_of_measurement == UNIT_KILOWATTS_HOUR:\n self._unit_of_measurement_scale = 0\n else:\n _LOGGER.error(\"Unsupported power/energy unit: %s\",\n unit_of_measurement)\n return\n\n try:\n if self._source_entity_id:\n # energy as the Riemann integral of previous measures.\n elapsed_time = (new_state.last_updated\n - old_state.last_updated).total_seconds()\n area = (float(new_state.state)\n + float(old_state.state))*elapsed_time/2\n kwh = area / (self._unit_of_measurement_scale * 3600)\n else:\n kwh = float(new_state.state) - float(old_state.state)\n\n self._state += kwh\n\n except ValueError:\n _LOGGER.warning(\"Unable to store state. \"\n \"Only numerical states are supported\")\n\n self._hass.async_add_job(self.async_update_ha_state, True)\n\n async_track_state_change(\n self._hass, self._sensor_source_id, async_calc_energy)\n\n @property\n def name(self):\n \"\"\"Return the name of the sensor.\"\"\"\n return self._name\n\n @property\n def state(self):\n \"\"\"Return the state of the sensor.\"\"\"\n return round(self._state, self._round_digits)\n\n @property\n def unit_of_measurement(self):\n \"\"\"Return the unit the value is expressed in.\"\"\"\n return UNIT_OF_MEASUREMENT\n\n @property\n def should_poll(self):\n \"\"\"No polling needed.\"\"\"\n return False\n\n @property\n def device_state_attributes(self):\n \"\"\"Return the state attributes of the sensor.\"\"\"\n state_attr = {\n ATTR_SOURCE_ID: self._sensor_source_id,\n ATTR_LAST_RESET: self._last_reset,\n }\n return state_attr\n\n @property\n def icon(self):\n \"\"\"Return the icon to use in the frontend, if any.\"\"\"\n return ICON\n","sub_path":"sensor/energy.py","file_name":"energy.py","file_ext":"py","file_size_in_byte":5824,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"374705861","text":"# -*- coding: utf-8 -*-\n'''\n @File : Dimming_editPage.py\n @Time : 2019/2/19 10:34\n @Author : Chenzd\n @Project : 调光灯---编辑页面类\n @Software: PyCharm\n'''\nimport random\nimport time\n\nfrom page.basePage import BasePage\nfrom page.basePage import By\nfrom page.LeeBus.common import Common\nfrom page.LeeBus.light.lightPage import LightPage\nfrom page.common.homePage import HomePage\nclass dimming_editPage(BasePage):\n # 设备名\n nameTv = (By.ID, 'com.leelen.luxdomo:id/nameTv')\n # 设备位置\n locationTv = (By.ID, 'com.leelen.luxdomo:id/locationTv')\n # 隐藏按钮\n hideIv = (By.ID, 'com.leelen.luxdomo:id/hideIv')\n # 前沿调光\n ivForewordDimming = (By.ID, 'com.leelen.luxdomo:id/ivForewordDimming')\n\n # 智能插座开关\n cdbSwitch = (By.ID, 'com.leelen.luxdomo:id/cdbSwitch')\n\n location_text = []\n device_name = []\n def hide_is_normal(self):\n eles = self.get_elements(self.hideIv)\n ran = random.randint(0, len(eles)-1)\n self.click_element(eles[ran])\n print('步骤1:勾选隐藏')\n if self.is_element_exist(Common.msg) is True:\n Hide_text = self.getText(Common.msg)\n print('消息弹出框提示的内容:' + '【' + Hide_text + '】')\n self.click(LightPage.tvSecond)\n else:\n print('未弹出消息框存在问题!!!!')\n eles = self.get_elements(self.nameTv)\n device_name = self.getText_element(eles[ran])\n self.device_name.append(device_name)\n eles = self.get_elements(self.locationTv)\n loc_text = self.getText_element(eles[ran])\n self.location_text.append(loc_text)\n print('步骤2:获取出设备名'+'【'+device_name+'】及设备位置【%s】' % loc_text)\n self.click(Common.backTv)\n self.click(Common.backTv)\n self.click(HomePage.home_tab_home)\n print('步骤3:保存并退出到主界面')\n self.enter_room_for_hide()\n print('步骤4:进入对应逻辑设备的房间')\n\n def check_hide_is_normal(self):\n result = LightPage(self.driver).find_deviceName(self.device_name)\n while result == 0:\n # 上滑\n Common(self.driver).swipe_up_screen()\n result = LightPage(self.driver).find_deviceName(self.device_name)\n self.device_name = []\n return result\n\n nameTv_text = []\n def get_location_text(self):\n loc_text = self.getText(self.locationTv)\n eles = self.get_elements(self.nameTv)\n ran = random.randint(0, len(eles)-1)\n nTv_text = self.getText_element(eles[ran])\n self.nameTv_text.append(nTv_text)\n self.location_text.append(loc_text)\n # print(self.nameTv_text)\n\n '''根据text点击设备'''\n def find_deviceName_by_click(self, name):\n rlist = []\n device_list = self.get_elements(Common.deviceNameTv)\n for i in device_list:\n text = self.getText_element(i)\n rlist.append(text)\n suc = 0\n for k, v in enumerate(rlist):\n if rlist[k] == name:\n suc = 1\n self.findAU_click('text(\\\"'+name+'\\\")')\n break\n elif rlist[k] == '其他设备':\n suc = 1\n print('结果:对比到最后一个了')\n elif rlist[k] == '传感器':\n suc = 1\n print('结果:对比到最后一��了')\n else:\n suc = 0\n return suc\n\n '''根据text长按设备'''\n def find_deviceName_by_longPress(self, name):\n rlist = []\n device_list = self.get_elements(Common.deviceNameTv)\n for i in device_list:\n text = self.getText_element(i)\n rlist.append(text)\n suc = 0\n for k, v in enumerate(rlist):\n if rlist[k] == name:\n suc = 1\n ele = self.findAU('text(\\\"' + name + '\\\")')\n self.longPress(ele)\n elif rlist[k] == '其他设备':\n suc = 1\n print('结果:对比到最后一个了')\n elif rlist[k] == '传感器':\n suc = 1\n print('结果:对比到最后一个了')\n else:\n suc = 0\n return suc\n\n '''循环遍历主页'''\n def enter_logic_by_text(self, name):\n print('根据text点击设备')\n res = self.find_deviceName_by_click(name)\n while res == 0:\n self.swipe_up_Big()\n res = self.find_deviceName_by_click(name)\n\n '''循环遍历主页'''\n\n def longPress_logic_by_text(self, name):\n print('根据text长按设备')\n res = self.find_deviceName_by_longPress(name)\n while res == 0:\n self.swipe_up_Big()\n res = self.find_deviceName_by_longPress(name)\n\n\n enter_roomName = []\n def enter_room_for_hide(self):\n if len(self.location_text) > 0:\n self.click(Common.roomNameTv)\n text1 = self.getText(Common.floor1)\n text2 = [i for i in self.location_text[-1] if not i in text1]\n roomName = ''.join(text2)\n self.enter_roomName.append(roomName)\n ele = self.findAU('new UiSelector().textContains(\\\"'+roomName+'\\\")')\n while not ele:\n self.swipe_up_Big()\n ele = self.findAU('new UiSelector().textContains(\\\"' + roomName + '\\\")')\n self.click_element(ele)\n\n def cancel_hide(self):\n eles = self.get_elements(self.hideIv)\n for i in range(len(eles)):\n self.click_element(eles[i])\n if self.is_element_exist(Common.msg) is True:\n self.click(LightPage.tvFirst)\n else:\n break\n self.click(Common.backTv)\n self.click(Common.backTv)\n self.click(HomePage.home_tab_home)\n Common(self.driver).back_top()\n\n def enter_logicEdit(self, before_state, after_state):\n iconAndelement = Common(self.driver).get_iconAndelement(before_state, after_state)\n icon_befor = iconAndelement[0]\n element_befor = iconAndelement[1]\n print('步骤1:筛选出页面内参数对比的图标(不管开关),若当前页没有则下滑页面再筛选')\n print('步骤2:取出固定的图标与筛选后随机图标对比')\n if len(icon_befor) > 0:\n ran = random.randint(0, len(icon_befor) - 1)\n self.click_element(element_befor[ran])\n print('步骤3:点击图标')\n while len(icon_befor) < 1: # 判断 如果当前页面没有 上滑一下再对比\n time.sleep(1)\n self.swipe_up_Big()\n iconAndelement = Common(self.driver).get_iconAndelement(before_state, after_state)\n icon_befor = iconAndelement[0]\n element_befor = iconAndelement[1]\n if len(icon_befor) > 0:\n ran = random.randint(0, len(icon_befor)-1)\n self.click_element(element_befor[ran])\n print('步骤3:点击图标')\n\n def random_name_dimming(self):\n eles = self.get_elements(self.nameTv)\n ran = random.randint(0, len(eles)-1)\n self.click_element(eles[ran])\n\n def is_exit_element(self, ele):\n if self.is_element_exist(ele):\n return True\n else:\n return False\n\nif __name__ == '__main__':\n a = ['1楼名称最大限制值了默认房间最大限制值']\n b = '1楼名称最大限制值了'\n c = [i for i in a[0] if not i in b ]\n d = ''.join(c)\n print(d)","sub_path":"page/LeeBus/Dimming/Dimming_editPage.py","file_name":"Dimming_editPage.py","file_ext":"py","file_size_in_byte":7581,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"156674267","text":"\"\"\"\nFunctions and classes related to the creation of the VCS window.\n\"\"\"\nimport os\nimport sys\n\nimport pymel.core as pmc\nfrom maya.app.general import mayaMixin\nfrom Qt import QtWidgets, QtCore, QtGui\n\nfrom .. import utilities as util\nfrom .. import callbacks as callbacks\nfrom .. import checkinCheckout as cinout\nfrom chooseUserUI import ChooseUser\nfrom ..dirSearch import scene_in_use_dialog\nfrom OrcaMaya import filePaths, uiTools, aboutWinClass, baseWinClass, utilities\nimport lineEditClass as line_edit\nfrom listWidgetClass import *\nfrom environmentUI import EnvironmentPopup\nfrom PLUGIN_INFO import ORCA3DTEAMVCS\n\nplugin_path = filePaths.parse_file_path(os.path.abspath(os.path.join(__file__, \n '../../..')))\n\nENVIRONMENT = util.EnvironmentClass()\nENVIRONMENT.initial_set()\n\n\nclass CheckoutUI(baseWinClass.SuperWindow):\n \"\"\"New QMainWindow used for all of the functionality of the program.\n The class itself doesn't include a creation method but the creation\n of the main window is run from a show() function that invokes another\n function called create_window. This class includes a number of \n methods for advanced functionality and attributes to store data to \n be passed around to other methods and functions.\n \n Additional Superclass:\n SuperWindow -- Contains default window methods [centered]\n \n \"Private\" Methods:\n [_validate_starting_project, _disconnect_buttons, _checkout, _checkin,\n _ref, _checkout_button_trigger, _checkin_button_trigger, \n _reference_button_trigger, _abandon]\n\n Public Methods:\n [enable_plugin_window_items, run_add_to_batch, run_orca_asset_library,\n open_to_location, reset_action_cmd, add_title_callback, \n remove_title_callback, add_maya_exit_callback, remove_maya_exit_callback,\n commit_action, abandon_button]\n\n Overload:\n [__init__, show, keyPressEvent, focusOutEvent, focusInEvent]\n \n Instance Attributes:\n [self.vcs_info, self.title_callback, self.exit_callback, self.users_win,\n self.user]\n \"\"\"\n tool_name = 'CheckoutUI'\n \n def __init__(self, parent = None):\n \"\"\"\n **Keyword Arguments**\n\n :param parent: Main window instance\n \"\"\"\n baseWinClass.SuperWindow.__init__(self, parent = parent, \n VERSION = ORCA3DTEAMVCS['VERSION'])\n \n self.setObjectName(self.tool_name)\n\n self.close_callback = callbacks.CloseMayaCallback(self)\n self.users_win = None # The choose a user window attribute\n self.user = 'No User' # Initialized when ChooseUser class returns\n self.checked_out_item = None\n \n self.setMouseTracking(True)\n \n width = 475\n self.setWindowTitle('Orca Health 3D Team VCS: Check-Out')\n self.setMinimumWidth(width)\n self.centered()\n \n self.rt_commands = util.SaveOpenNewRTCommands(self)\n\n def _proj(self):\n proj_name = self.proj_combo_box.currentText()\n return ENVIRONMENT.get_top_level_dir().joinpath(proj_name)\n\n def _stage(self):\n stage_name = self.stage_combo_box.currentText().lower()\n if stage_name == 'modeling': stage_name = 'model'\n scenes_dir = self._proj().joinpath('scenes')\n return scenes_dir.joinpath(stage_name)\n\n def _type(self):\n type_name = self.scene_combo_box.currentText().lower()\n return self._stage().joinpath(type_name)\n\n def label_checked_out_item(self, selected_item):\n self.checked_out_item = selected_item\n if selected_item:\n self.checked_out_label.setText('Checked-Out: {0}'.format(\n selected_item.scene))\n self.checked_out_label.setStyleSheet('font-size: 15pt; color: green')\n else:\n self.checked_out_label.setText('Checked-Out: {0}'.format(\n None))\n self.checked_out_label.setStyleSheet('font-size: 15pt; color: red')\n ################################################################### \n #################### File menu Methods ############################\n ###################################################################\n ##################### Page Switching functions ####################\n def _disconnect_buttons(self):\n \"\"\"Disconnects buttons signals so that while the functionality\n changes between window type selection, the buttons can send a \n different signal and change functionality.\n \"\"\"\n try: self.load_close_button.clicked.disconnect()\n except Exception: pass\n try: self.load_button.clicked.disconnect()\n except Exception: pass\n \n def _checkout(self):\n \"\"\"Helper method that is used to update the buttons of the window\n when switched to the checkout page.\n \"\"\"\n # Update Buttons \n self.load_close_button.setText('Load Selected Scene AND Close')\n self.load_button.setText('Load Selected Scene')\n self.load_close_button.setEnabled(True)\n self.load_button.setEnabled(True)\n self.list_widg.clearFocus()\n self.setFocus()\n\n self._disconnect_buttons() # Force disconnect button connections\n self.load_close_button.clicked.connect(\n lambda: self._checkout_button_trigger(self.close))\n self.load_button.clicked.connect(\n lambda: self._checkout_button_trigger())\n\n def _checkin(self):\n \"\"\"Helper method that is used to update the buttons of the window\n when switched to the checkin page.\n \"\"\"\n # Update Buttons \n self.load_close_button.setText('Check-In Scene AND Close')\n self.load_button.setText('Check-In Scene')\n if self.list_widg.currentItem():\n self.list_widg.setFocus()\n self.chkin_notes.typing_notes()\n \n self._disconnect_buttons() # Force disconnect button connections\n self.load_close_button.clicked.connect(\n lambda: self._checkin_button_trigger(self.close))\n self.load_button.clicked.connect(\n lambda: self._checkin_button_trigger())\n\n def _ref(self):\n \"\"\"Helper method that is used to update the buttons of the window\n when switched to the reference page.\n \"\"\"\n # Update Buttons \n self.load_close_button.setText('Reference Scene AND Close')\n self.load_button.setText('Reference Scene')\n self.load_close_button.setEnabled(True)\n self.load_button.setEnabled(True)\n if self.list_widg.currentItem():\n self.list_widg.setFocus()\n\n self._disconnect_buttons() # Force disconnect button connections\n self.load_close_button.clicked.connect(\n lambda: self._reference_button_trigger(self.close))\n self.load_button.clicked.connect(\n lambda: self._reference_button_trigger())\n \n def enable_plugin_window_items(self, action, plugin_name, *try_cmds):\n \"\"\"Enables the QAction based on the condition of whether or not \n the plugin command is currently loaded.\n \n **Positional Arguments**\n\n :param action: QAction to enable or disable based on condition\n :type action: `QAction`\n :param plugin_name: Name of plugin for status tip when fails\n :type plugin_name: string\n :param try_cmds: list of commands to test that are supposed to be\n created when plugin is initialized by INIT plugin.\n :type try_cmds: List of cmds to test\n \"\"\"\n try:\n for cmd in try_cmds: cmd\n except AttributeError:\n action.setStatusTip('{plugin}.py plugin is not '\n 'enabled'.format(plugin = plugin_name))\n action.setEnabled(False)\n else:\n action.setStatusTip('')\n action.setEnabled(True)\n \n def run_add_to_batch(self):\n \"\"\"Runs the Orca Render Batch plugin.\"\"\"\n # Gets current selected scene to add to window\n selected_item = self.list_widg.currentItem()\n if not selected_item: \n sys.stderr.write('Please select a scene from within the dialog ' \n 'window in order to add it to the batch render'\n ' window.\\n')\n else:\n pmc.mel.eval('addToRenderBatch(\"{0}\");'.format(\n selected_item.scene_path))\n \n def run_orca_asset_library(self):\n \"\"\"Runs the Orca Asset Library plugin but only if it is loaded.\"\"\"\n pmc.mel.eval('orcaAssetLibrary();')\n \n def open_to_location(self):\n \"\"\"Opens the selected item within the UI in windows explorer and\n selects it.\n \"\"\"\n try:\n selected_item = self.list_widg.currentItem().scene_path\n except AttributeError:\n sys.stderr.write('Please make sure that you have an item selected'\n ' or you are currently in an open scene.\\n')\n selected_item = pmc.sceneName()\n # Open the selected item in windows explorer or mac finder\n filePaths.FileExplorer(selected_item).select()\n ################################################################### \n #################### Edit menu Methods ############################\n ###################################################################\n def reload_project_box(self):\n project_names = [d.name for d in ENVIRONMENT.get_top_level_dir().dirs()]\n self.proj_combo_box.clear()\n self.proj_combo_box.addItems(sorted(project_names, key = lambda d: d.lower()))\n \n def reset_action_cmd(self):\n \"\"\"Resets the window to its default state.\"\"\"\n self.reload_project_box()\n project = ENVIRONMENT.get_project_dir()\n index = self.proj_combo_box.findText(project.name)\n # Set to default project\n self.proj_combo_box.setCurrentIndex(index)\n self.stage_combo_box.setCurrentIndex(0)\n self.scene_combo_box.setCurrentIndex(0)\n # Erase line edit text\n self.create_txtline.setText('')\n self.chkin_notes.setText('')\n # Switch to checkout page\n self.chk_out_action.setChecked(1)\n self.chk_out_action.trigger()\n self.adjustSize() # Adjusts the size of the window back to default\n self.setFocus()\n scene_list = UpdateVCSSceneList(self)\n scene_list.update()\n ###################################################################\n #################### Button Methods ###############################\n ###################################################################\n # Button functionality changes based on what page you are on ######\n def _checkout_button_trigger(self, close_window = None):\n \"\"\"Functionality when bottom window buttons are pressed when on\n the checkout page.\n\n **Keyword Argument**\n\n :param close_window: Closes the window if passed in.\n :type close_window: self.close function\n \"\"\"\n selected_item = self.list_widg.currentItem()\n\n # Checkout item\n result = cinout.Checkout(selected_item, self.user).run()\n if result == 'Success':\n # Open the check-in window\n self.chk_in_action.trigger()\n # Keep track of current checked-out item\n self.label_checked_out_item(selected_item)\n \n self.rt_commands.overwrite_cmds()\n self.chkin_notes.setText('')\n \n self.close_callback.reload()\n \n if close_window:\n close_window()\n\n def _checkin_button_trigger(self, close_window = None):\n \"\"\"Functionality when bottom window buttons are pressed when on\n the checkin page.\n\n **Keyword Argument**\n\n :param close_window: Closes the window if passed in.\n :type close_window: self.close function\n \"\"\"\n # Save a new version to the repo\n notes = self.chkin_notes.text()\n checkin = cinout.Checkin(self.user, self.checked_out_item)\n checkin.run()\n checkin.commit(notes)\n self._abandon()\n if close_window:\n close_window()\n\n def _reference_button_trigger(self, close_window = None):\n \"\"\"Functionality when bottom window buttons are pressed when on\n the reference page.\n\n **Keyword Argument**\n\n :param close_window: Closes the window if passed in.\n :type close_window: self.close function\n \"\"\"\n selected_item = self.list_widg.currentItem()\n try:\n # Alert if there is a scene currently in use\n scene_in_use_dialog(ENVIRONMENT.get_vcs_dir(), \n selected_item.vcs_text_file, self)\n except AttributeError:\n raise RuntimeError('Select an item to reference.')\n \n cinout.Reference(selected_item).run()\n if close_window:\n close_window()\n \n def commit_action(self):\n \"\"\"Saves a version of the scene to the repo and keeps the scene\n Checked-Out at the same time. This allows for the user to keep \n periodic versions and continue to work.\n \"\"\"\n notes = self.chkin_notes.text()\n cinout.Checkin(self.user).commit(notes)\n self.chkin_notes.setText('') # Clear the notes line edit\n self.close_callback.reload()\n\n def _abandon(self):\n \"\"\"Run all the necessary commands to cleanup the scene and plugin.\n Checkin scene, do NOT add a commit, force open new file, rest the \n plugin window, and remove all callbacks.\n \"\"\"\n # Check-in scene. Skip this if an error is detected\n try: # If currently checked-in; skip\n cinout.Checkin(self.user).run()\n except RuntimeError: pass\n pmc.newFile(force = True)\n self.reset_action_cmd()\n try:\n self.close_callback.remove()\n except Exception: pass\n self.label_checked_out_item(None)\n \n def abandon_button(self):\n \"\"\"Check-in the given scene. Runs the check-in code found in the \n scene_action_button method. Passes in a True value for the \n abandon keyword argument and runs the necessary code. Throws out \n all changes done to the open scene, checks it in, no version is \n saved, and then opens up a new scene.\n \"\"\"\n message = QtWidgets.QMessageBox()\n message.setStandardButtons(QtWidgets.QMessageBox.Ok | \n QtWidgets.QMessageBox.Cancel)\n message.setIcon(QtWidgets.QMessageBox.Warning)\n message.setWindowTitle('Abandon Changes and Release Scene')\n message.setText('This operation will:\\n - Cancel all changes made '\\\n 'to the scene\\n - Check-In the scene AND update '\\\n 'the VCS text file\\n - Open a new scene within Maya')\n message.setWindowIcon(QtGui.QIcon('{path}/{name}.png'.format(\n path = filePaths.get_icon_path(), \n name = 'logo_bluewhale')))\n result = message.exec_()\n if result == QtWidgets.QMessageBox.Ok:\n self._abandon()\n else:\n utilities.mPrint('Operation cancelled.')\n ###################################################################\n ###################################################################\n ###################################################################\n def show(self, *args, **kwargs):\n \"\"\"Override the show method to convert main window to a dockable\n window. Also reload/add items to the window everytime the window is\n shown and made visible.\n \"\"\"\n mayaMixin.MayaQWidgetDockableMixin.show(self, *args, **kwargs)\n # Re-add items\n scene_list = UpdateVCSSceneList(_window)\n scene_list.update()\n \n def keyPressEvent(self, event):\n \"\"\"Key Press Event for main window. Toggle between Check-Out,\n Check-In, and Reference windows by pressing the left and right\n arrow buttons.\n \n **Positional Argument**\n\n :param event: Event provided by main window event loop\n :type event: keyPressEvent\n \"\"\"\n QtWidgets.QMainWindow.keyPressEvent(self, event)\n util.key_press_event(self, event)\n self.focusInEvent(event)\n\n def mousePressEvent(self, event):\n \"\"\"Focus on the window when main window is clicked.\n \n **Positional Argument**\n\n :param event: Event provided by main window event loop\n :type event: mousePressEvent\n \"\"\"\n QtWidgets.QMainWindow.mousePressEvent(self, event)\n self.setFocus()\n self.focusInEvent(event)\n\n def focusOutEvent(self, event):\n \"\"\"Focus out event for main window. Sources the original \n pickWalkLeft and pickWalkRight maya commands and resets the \n procedure upon focus out.\n \n **Positional Argument**\n :param event: Event provided by main window event loop\n :type event: focusOutEvent\n \"\"\"\n pmc.mel.eval('source \"{0}\";'.format(plugin_path + '/assets/pickWalkLeft.mel'))\n pmc.mel.eval('source \"{0}\";'.format(plugin_path + '/assets/pickWalkRight.mel'))\n \n def focusInEvent(self, event):\n \"\"\"Focus in event for main window. Overwrites the pickWalkLeft \n and pickWalkRight procedures to ignore pickwalking when the \n main window is in focus.\n \n **Positional Argument**\n\n :param event: Event provided by main window event loop\n :type event: focusInEvent\n \"\"\"\n pmc.mel.eval('global proc pickWalkLeft(){{}}')\n pmc.mel.eval('global proc pickWalkRight(){{}}')\n \n # def delete_instances(self):\n # \"\"\"Clears out and deletes the dock widget set by \n # MayaQWidgetDockableMixin. Cleans up and makes sure that the \n # reference doesn't exist anymore.\n # \"\"\"\n # mainMayaWindow = uiTools.get_maya_window()\n # for obj in mainMayaWindow.children():\n # if type(obj) == mayaMixin.MayaQDockWidget:\n # try:\n # if obj.widget().objectName() == self.__class__.tool_name:\n # mainMayaWindow.removeDockWidget(obj)\n # obj.setParent(None)\n # obj.deleteLater()\n # except Exception: pass\n \n # def floatingChanged(self, isFloating):\n # \"\"\"Force focus on window.\"\"\"\n # self.setFocus()\n \n\ndef create_window(parent = None):\n \"\"\"Creation function run by the window class contained in the parent \n argument.\n \n **Keyword Argument**\n\n :param parent: Main window instance (Default: None)\n\n :returns: window instance\n :rtype: `CheckoutUI`\n \n Instance Attributes: (win) -- CheckoutUI instance\n [win.menu_bar, win.file_menu, win.edit_menu, win.help_menu, \n win.file_action_grp, win.chk_out_action, win.chk_in_action, \n win.ref_action, win.orcaAssetLib_action, win.add_to_batch_action,\n win.open_file_location_action, win.change_user_action, win.users_win,\n win.reset_action, win.new_save_action, win.old_save_action, \n win.rm_callback, win.about_action, win.about, win.widg, win.checkout_page,\n win.checkin_page, win.ref_page, win.create_txtline, win.selection_widg,\n win.selection_hbox, win.proj_vbox, win.proj_label, win.proj_combo_box,\n win.stage_vbox, win.stage_label, win.stage_combo_box, win.scene_vbox,\n win.scene_label, win.scene_combo_box, win.list_widg, win.load_close_button,\n win.load_button, win.cancel_button, win.button_menu, win.abandon_action,\n win.button_hbox, win.chkin_notes, win.commit_button, win.stacked_widget,\n win.vbox]\n \"\"\"\n win = CheckoutUI(parent)\n\n win.statusBar()\n # Actions and Menu Bar\n ####################################################################\n ####################################################################\n win.menu_bar = win.menuBar()\n win.file_menu = uiTools.MenuClass('&File', win)\n win.edit_menu = uiTools.MenuClass('&Edit', win)\n win.help_menu = uiTools.MenuClass('&Help', win)\n win.file_menu.aboutToShow.connect(lambda: win.enable_plugin_window_items(\n win.add_to_batch_action,\n 'orcaRenderBatch', \n pmc.orcaRenderBatch, \n pmc.addToRenderBatch))\n win.file_menu.aboutToShow.connect(lambda: win.enable_plugin_window_items(\n win.orcaAssetLib_action,\n 'orcaAssetLibrary', \n pmc.orcaAssetLibrary))\n # Add menus to bar\n for menu in [win.file_menu, win.edit_menu, win.help_menu]:\n win.menu_bar.addMenu(menu)\n \n # File menu actions\n ####################################################################\n win.file_action_grp = QtWidgets.QActionGroup(win)\n win.file_action_grp.setExclusive(True)\n win.chk_out_action = QtWidgets.QAction('&Check-Out', win, checkable = True)\n win.chk_out_action.setChecked(True)\n win.chk_in_action = QtWidgets.QAction('C&heck-In', win, checkable = True)\n win.ref_action = QtWidgets.QAction('R&eference', win, checkable = True)\n # Add actions to action group\n for action in [win.chk_out_action, win.chk_in_action, win.ref_action]:\n win.file_action_grp.addAction(action)\n win.orcaAssetLib_action = QtWidgets.QAction('Run Orca Asset Library...', win)\n win.orcaAssetLib_action.triggered.connect(win.run_orca_asset_library)\n win.add_to_batch_action = QtWidgets.QAction('Add Scene to Batch Render Window', \n win)\n win.add_to_batch_action.triggered.connect(win.run_add_to_batch)\n win.open_file_location_action = QtWidgets.QAction('Open File Location...', win)\n win.open_file_location_action.triggered.connect(win.open_to_location)\n \n # Add file menu items using my customized menu class\n win.file_menu.addActions(win.chk_out_action, win.chk_in_action, \n win.ref_action, '-', win.add_to_batch_action, \n win.orcaAssetLib_action, \n win.open_file_location_action)\n \n # Edit menu actions\n ####################################################################\n win.change_user_action = QtWidgets.QAction('Change User...', win)\n win.users_win = ChooseUser(win)\n win.change_user_action.triggered.connect(lambda: win.users_win.exec_())\n\n win.set_env_action = QtWidgets.QAction('Set Environment...', win)\n envUI = EnvironmentPopup(win)\n win.set_env_action.triggered.connect(lambda: envUI.popup())\n\n win.reset_action = QtWidgets.QAction('&Reset Window', win)\n win.reset_action.triggered.connect(win.reset_action_cmd)\n\n win.new_save_action = QtWidgets.QAction('Set 3dTeamVCS Save, Open, New', win)\n win.new_save_action.triggered.connect(lambda: win.rt_commands.overwrite_cmds())\n\n win.old_save_action = QtWidgets.QAction('Revert to default Maya Save, Open, New', \n win)\n win.old_save_action.triggered.connect(lambda: win.rt_commands.set_maya_cmds())\n\n win.rm_callback = QtWidgets.QAction('Remove Callbacks', win)\n win.rm_callback.triggered.connect(lambda: win.close_callback.remove())\n\n # Add edit menu items using customized menu class\n win.edit_menu.addActions(win.change_user_action, win.set_env_action,\n win.new_save_action, win.old_save_action, \n win.rm_callback, '-', win.reset_action)\n \n # Help menu actions\n ####################################################################\n win.about_action = QtWidgets.QAction('&About', win)\n win.docs_action = QtWidgets.QAction('&Documentation', win)\n about = aboutWinClass.AboutPopup(ORCA3DTEAMVCS['TITLE'],\n ORCA3DTEAMVCS['NAME'],\n ORCA3DTEAMVCS['VERSION'],\n ORCA3DTEAMVCS['AUTHOR'],\n ORCA3DTEAMVCS['EMAIL'])\n doc_path = parse_file_path(filePaths.get_ORCA_HEALTH_LIBRARY_path().joinpath(\n 'docs', 'build', 'html', 'index.html'))\n win.about_action.triggered.connect(lambda: about.popup())\n win.docs_action.triggered.connect(lambda: filePaths.FileExplorer(doc_path).open())\n # Add elements to the help menu\n win.help_menu.addActions(win.about_action, win.docs_action)\n\n # Layout of window\n ####################################################################\n ####################################################################\n win.widg = QtWidgets.QWidget()\n win.setCentralWidget(win.widg)\n # Three window page widgets\n win.checkout_page = util.CreatePageClass(win.widg, window = win)\n win.checkout_page.set_layout(QtWidgets.QVBoxLayout())\n win.checkout_page.layout.setContentsMargins(0, 0, 0, 0)\n win.checkout_page.layout.setSpacing(0)\n \n win.checkin_page = util.CreatePageClass(win.widg, window = win)\n win.checkin_page.set_layout(QtWidgets.QVBoxLayout())\n win.checkin_page.layout.setContentsMargins(0, 0, 0, 0)\n win.checkin_page.layout.setSpacing(0)\n \n win.ref_page = util.CreatePageClass(win.widg, window = win)\n win.ref_page.set_layout(QtWidgets.QVBoxLayout())\n win.ref_page.layout.setContentsMargins(0, 0, 0, 0)\n win.ref_page.layout.setSpacing(0)\n \n # Checked-Out Label\n # win.label_checked_out_item(None)\n win.checked_out_label = QtWidgets.QLabel('Checked-Out: {0}'.format(win.checked_out_item))\n win.checked_out_label.setStyleSheet('font-size: 15pt; color: red')\n\n # Create Scene line edit\n ####################################################################\n win.create_txtline = line_edit.CreateSceneLineEdit(win)\n win.create_txtline.textChanged.connect(\n win.create_txtline._edit_line_when_pressing_keys)\n win.create_txtline.returnPressed.connect(win.create_txtline.create_scene)\n \n # Project and scene selection\n ####################################################################\n win.selection_widg = QtWidgets.QWidget() # Widget to add to stacked widget\n win.selection_hbox = QtWidgets.QHBoxLayout(win.selection_widg)\n # Project combo box\n win.proj_vbox = QtWidgets.QVBoxLayout()\n win.proj_label = QtWidgets.QLabel('Project Name:')\n win.proj_combo_box = QtWidgets.QComboBox() # Sorts project items to add\n win.proj_combo_box.setStatusTip('Select an Orca project to work')\n win.proj_combo_box.setToolTip('Select an Orca project to work')\n win.reload_project_box()\n project = ENVIRONMENT.get_project_dir()\n index = win.proj_combo_box.findText(project.name)\n win.proj_combo_box.setCurrentIndex(index) \n win.proj_vbox.addWidget(win.proj_label)\n win.proj_vbox.addWidget(win.proj_combo_box)\n # Stage combo box\n win.stage_vbox = QtWidgets.QVBoxLayout()\n win.stage_label = QtWidgets.QLabel('Stage of Production:')\n win.stage_vbox.addWidget(win.stage_label)\n win.stage_combo_box = QtWidgets.QComboBox()\n win.stage_combo_box.setStatusTip('What type of file is this?')\n win.stage_combo_box.setToolTip('What type of file is this?')\n win.stage_combo_box.addItems(['Modeling', 'Rigging', 'Animation', \n 'Lighting', 'Render'])\n win.stage_combo_box.setCurrentIndex(0)\n win.stage_vbox.addWidget(win.stage_combo_box)\n # Scene combo box\n win.scene_vbox = QtWidgets.QVBoxLayout()\n win.scene_label = QtWidgets.QLabel('Scene Type:')\n win.scene_vbox.addWidget(win.scene_label)\n win.scene_combo_box = QtWidgets.QComboBox()\n win.scene_combo_box.setStatusTip('Is this an Anatomy, Condition, or '\n 'Procedure scene?')\n win.scene_combo_box.setToolTip('Is this an Anatomy, Condition, or '\n 'Procedure scene?')\n win.scene_combo_box.setCurrentIndex(-1)\n win.scene_vbox.addWidget(win.scene_combo_box)\n \n # Add elements to the project selection layout\n win.selection_hbox.addLayout(win.proj_vbox)\n win.selection_hbox.addLayout(win.stage_vbox)\n win.selection_hbox.addLayout(win.scene_vbox)\n \n # Project selection combo box signals\n scene_list = UpdateVCSSceneList(win)\n win.proj_combo_box.activated.connect(lambda: scene_list.update())\n win.stage_combo_box.activated.connect(lambda: scene_list.update())\n win.scene_combo_box.activated.connect(\n lambda: scene_list.update(only_list = True))\n # List widget instance to display possible scenes\n ####################################################################\n win.list_widg = ListWidget(win) # Custom class instance\n win.list_widg.setMinimumHeight(350)\n \n # SPLITTER \n split1 = uiTools.Splitter('Scene VCS Text File Status:')\n\n # Add scene vcs info\n win.vcs_widget = QtWidgets.QWidget(win)\n status_layout = QtWidgets.QFormLayout()\n status_layout.setSpacing(2)\n status_layout.setLabelAlignment(QtCore.Qt.AlignLeft)\n win.status_label = QtWidgets.QLabel('N/A')\n win.date_label = QtWidgets.QLabel('N/A')\n win.time_label = QtWidgets.QLabel('N/A')\n win.by_user_label = QtWidgets.QLabel('N/A')\n status_layout.addRow(QtWidgets.QLabel('Status: '), win.status_label)\n status_layout.addRow(QtWidgets.QLabel('Date: '), win.date_label)\n status_layout.addRow(QtWidgets.QLabel('Time: '), win.time_label)\n status_layout.addRow(QtWidgets.QLabel('By User: '), win.by_user_label)\n win.vcs_widget.setLayout(status_layout)\n win.vcs_widget.setStyleSheet('QLabel{font-size: 15pt}')\n\n # SPLITTER \n split2 = uiTools.Splitter()\n \n # Bottom Buttons\n ####################################################################\n # Load/Load and Close\n win.load_close_button = QtWidgets.QPushButton('Load Selected Scene AND Close')\n win.load_close_button.setMinimumWidth(185)\n win.load_button = QtWidgets.QPushButton('Load Selected Scene')\n win.load_button.setMinimumWidth(70)\n # Cancel button\n win.cancel_button = QtWidgets.QToolButton(win)\n win.cancel_button.setText('Cancel')\n win.cancel_button.setMinimumWidth(62)\n win.cancel_button.setPopupMode(QtWidgets.QToolButton.MenuButtonPopup)\n win.cancel_button.clicked.connect(win.close)\n win.button_menu = QtWidgets.QMenu(win) # Cancel button menu\n # win.button_menu.internalSetSloppyAction()\n win.abandon_action = QtWidgets.QAction('[x] Abandon Changes and Release Scene', \n win)\n win.abandon_action.triggered.connect(win.abandon_button)\n win.button_menu.addAction(win.abandon_action)\n win.cancel_button.setMenu(win.button_menu)\n # Add buttons to button layout\n win.button_hbox = QtWidgets.QHBoxLayout()\n win.button_hbox.addWidget(win.load_close_button)\n win.button_hbox.addWidget(win.load_button)\n win.button_hbox.addWidget(win.cancel_button)\n \n # Checkin page buttons\n ####################################################################\n win.chkin_notes = line_edit.CommitSceneLineEdit(win)\n win.chkin_notes.returnPressed.connect(win.commit_action)\n win.commit_button = QtWidgets.QPushButton('Commit Changes')\n win.commit_button.clicked.connect(win.commit_action)\n win.chkin_notes.add_buttons([win.load_close_button, win.load_button, \n win.commit_button])\n win.chkin_notes.textChanged.connect(win.chkin_notes.typing_notes) \n \n # Create a list of elements for each page\n ####################################################################\n ####################################################################\n win.checkout_page.add_widgets(win.checked_out_label, win.create_txtline, \n win.selection_widg, win.list_widg, split1,\n win.vcs_widget, split2)\n win.checkin_page.add_widgets(win.checked_out_label, win.chkin_notes, \n win.commit_button)\n win.ref_page.add_widgets(win.selection_widg, win.list_widg)\n \n win.chk_out_action.triggered.connect(lambda: win.checkout_page.show_page(0))\n win.chk_in_action.triggered.connect(lambda: win.checkin_page.show_page(1))\n win.ref_action.triggered.connect(lambda: win.ref_page.show_page(2))\n \n # Create a stacked widget and add the pages to the stack\n win.stacked_widget = QtWidgets.QStackedWidget()\n for widg in [win.checkout_page, win.checkin_page, win.ref_page]:\n win.stacked_widget.addWidget(widg)\n \n # Add page switching functionality to each page\n win.checkout_page.update_run_function(win._checkout)\n win.checkin_page.update_run_function(win._checkin)\n win.ref_page.update_run_function(win._ref)\n \n # Add layout of window\n win.vbox = QtWidgets.QVBoxLayout(win.widg)\n win.vbox.addWidget(win.stacked_widget)\n win.vbox.addLayout(win.button_hbox)\n win.vbox.addStretch(1) \n\n return win\n\n_window = None\ndef create(mode, users_win = True):\n \"\"\"Function to initialize and display the main window appropriately.\n\n **Positional Arguments**\n\n :param mode: Starting page for the window (Check-Out, Check-In, Reference)\n :type mode: string\n\n **Keyword Argument**\n\n :param users_win: Whether or not the user window is activated upon\n start up.\n :type users_win: bool\n \"\"\"\n global _window\n parent = uiTools.get_maya_window()\n if _window is None:\n _window = create_window(parent)\n _window.run()\n # Choose which window to display\n actions = _window.findChildren(QtWidgets.QAction)\n for action in actions:\n if mode == action.text().replace('&', ''):\n action.trigger()\n break\n result = True\n # If the users window is open, prevent opening a second copy\n if not _window.users_win:\n _window.users_win = ChooseUser(_window)\n if users_win:\n if _window.user == 'No User':\n # Choose user popup but only if user not set yet\n result = _window.users_win.show()\n\n if not result:\n _window.rt_commands.set_maya_cmds() # Re-init maya default save functionality\n \n return _window\n\ndef delete():\n \"\"\"Delete the window and clear out any reference to it.\"\"\"\n global _window\n \n if _window is None:\n return\n \n _window.delete_instances()\n _window = None","sub_path":"OrcaMaya/plugins/orca3dTeamVCS/modules/UI/checkoutUI.py","file_name":"checkoutUI.py","file_ext":"py","file_size_in_byte":35177,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"496045474","text":"\n# coding: utf-8\n\n# In[1]:\n\n\nimport pandas as pd\nimport plotly.graph_objects as go\nimport numpy as np\nimport plotly.offline as py # para visualizar plots de plotly offline\n# Inicializar modalidad offline para visualizar plots, sin conexion a internet y sin generar link de plot\npy.offline.init_notebook_mode(connected=False)\n\n\n# In[2]:\n\n\ndef g_boxplot_varios(p0_data):\n \"\"\"\n :param p0_data: DataFrame : Data frame con 3 columnas con datos numericos, 1 columna por boxplot\n :return:\n debugging\n p0_data = pd.DataFrame({'var1': list(np.random.normal(0,1,12)),\n 'var2': list(np.random.normal(0,1,12)),\n 'var3': list(np.random.normal(0,1,12))})\n \"\"\"\n\n x_data = list(p0_data.columns)\n y_data = [p0_data.iloc[:, i]/max(p0_data.iloc[:, i]) for i in range(0, len(list(p0_data.columns)))]\n\n fig = go.Figure()\n\n for xd, yd in zip(x_data, y_data):\n q1 = yd.quantile(0.25)\n q3 = yd.quantile(0.75)\n iqr = q3 - q1\n out_yd = list(yd[(yd < (q1 - 1.5 * iqr)) | (yd > (q3 + 1.5 * iqr))].index)\n\n fig.add_trace(go.Box(y=yd, name=xd, boxpoints='all', jitter=0.5, whiskerwidth=0.5, marker_size=7,\n line_width=1, boxmean=True, selectedpoints=out_yd))\n\n fig.update_layout(title='Visualizacion de todas las variables (Normalizadas)',\n yaxis=dict(autorange=True, showgrid=True, dtick=5,\n gridcolor='rgb(255, 255, 255)', gridwidth=1),\n margin=dict(l=40, r=30, b=80, t=100),\n showlegend=False)\n\n fig.update_yaxes(hoverformat='.2f')\n\n # Mostrar figura\n # fig.show()\n\n return fig\n\n\n# In[3]:\n\n\nnp.random.seed(10)\np0_data = pd.DataFrame({'var1': list(np.random.normal(0,1,10)),\n 'var2': list(np.random.normal(0,1,10)),\n 'var3': list(np.random.normal(0,1,10))})\n\n\n# In[4]:\n\n\ngrafica = g_boxplot_varios(p0_data)\npy.iplot(grafica)\n\n","sub_path":"Boxplot.py","file_name":"Boxplot.py","file_ext":"py","file_size_in_byte":2039,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"221493793","text":"import socket\n\nif __name__ == '__main__':\n UDP_IP = \"192.168.1.25\"\n\n UDP_PORT = 5005\n sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) # UDP\n\n sock.bind((UDP_IP, UDP_PORT)) \n print(\"Init Done!\\n\")\n\n while True:\n data, addr = sock.recvfrom(100) # buffer size is 1024 bytes\n print(\"received message: {0}\".format(data))","sub_path":"Python/UDP Operation/UDP_Testing/Reading.py","file_name":"Reading.py","file_ext":"py","file_size_in_byte":357,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"346983248","text":"################################################################################\n##\n## O(n^3)\n##\n################################################################################\nfrom collections import defaultdict\nclass Solution:\n def mostVisitedPattern(self, username: List[str], timestamp: List[int], website: List[str]) -> List[str]:\n user_dic = defaultdict(list)\n for u,t,w in zip(username,timestamp,website):\n user_dic[u].append((t,w))\n #print(user_dic)\n pattern_dic = defaultdict(int)\n for user in user_dic:\n temp_set =set()\n user_dic[user].sort()\n L = len(user_dic[user])\n for i in range(L-2):\n for j in range(i+1,L-1):\n for k in range(j+1,L):\n pattern = tuple([user_dic[user][i][1],user_dic[user][j][1],user_dic[user][k][1]])\n if pattern not in temp_set:\n temp_set.add(pattern)\n pattern_dic[pattern]+=1\n max_pattern = None\n max_count = 0\n #print(pattern_dic)\n for pattern, count in pattern_dic.items():\n if count>max_count:\n max_pattern = pattern\n max_count = count\n elif count==max_count and pattern str:\n\n res = []\n res.append(\"Class table\")\n for key, value in self._class_table.items():\n res.append(f\" {key}: {dataclasses.asdict(value)}\")\n\n res.append(\"Subroutine table\")\n for key, value in self._subroutine_table.items():\n res.append(f\" {key}: {dataclasses.asdict(value)}\")\n\n return \"\\n\".join(res)\n\n def __getitem__(self, key: str) -> TableElement:\n \"\"\"Gets symbol attributes from table.\n\n Args:\n key (str): Name of the symbol.\n\n Returns:\n element (TableElement): Element of the symbol. If symbol of the\n given key is not found in table, an empty element is returned.\n \"\"\"\n\n if key in self._class_table:\n element = self._class_table[key]\n elif key in self._subroutine_table:\n element = self._subroutine_table[key]\n else:\n raise KeyError(f\"Not found key: {key}\")\n\n return element\n\n def __contains__(self, key: str) -> bool:\n \"\"\"Returns whether the specified key exists in table.\n\n Args:\n key (str): Name of the symbol.\n\n Returns:\n res (bool): Key exists or not in table.\n \"\"\"\n\n try:\n _ = self.__getitem__(key)\n except KeyError:\n return False\n\n return True\n\n def start_class(self) -> None:\n \"\"\"Resets class table at the start of class.\"\"\"\n\n self._class_table = {}\n self._number_table[\"static\"] = 0\n self._number_table[\"field\"] = 0\n self.start_subroutine()\n\n def start_subroutine(self) -> None:\n \"\"\"Resets subroutine table at the start of subroutine.\"\"\"\n\n self._subroutine_table = {}\n self._number_table[\"arg\"] = 0\n self._number_table[\"var\"] = 0\n\n def define(self, name: str, type: str, kind: str) -> None:\n \"\"\"Defines new symbol.\n\n Args:\n name (str): Name of new symbol.\n type (str): Type of new symbol.\n kind (str): Kind of new symbol.\n \"\"\"\n\n if kind not in self.possible_kind:\n raise ValueError(f\"Unexpected kind '{kind}'.\")\n\n if not name or not type:\n raise ValueError(\n f\"Empty string is not allowed: name={name}, type={type}\")\n\n number = self._number_table[kind]\n self._number_table[kind] += 1\n\n if kind in [\"static\", \"field\"]:\n self._class_table[name] = TableElement(\n name=name, type=type, kind=kind, number=number)\n else:\n self._subroutine_table[name] = TableElement(\n name=name, type=type, kind=kind, number=number)\n","sub_path":"nnttpy/jackcompiler/symbol_table.py","file_name":"symbol_table.py","file_ext":"py","file_size_in_byte":3203,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"209573680","text":"\"\"\"Manages Treadmill applications lifecycle.\n\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\nfrom __future__ import unicode_literals\n\nimport errno\nimport logging\nimport os\nimport shutil\nimport sys\n\nfrom treadmill import appcfg\nfrom treadmill import appevents\nfrom treadmill import fs\nfrom treadmill import supervisor\nfrom treadmill import utils\n\nfrom treadmill.appcfg import manifest as app_manifest\nfrom treadmill.apptrace import events\nfrom treadmill import runtime as app_runtime\n\n_LOGGER = logging.getLogger(__name__)\n\n\ndef load_runtime_manifest(tm_env, event, runtime):\n \"\"\"load manifest data and modify based on runtime\n :param tm_env:\n Full path to the application node event in the zookeeper cache.\n :type event:\n ``treadmill.appenv.AppEnvironment``\n :param event:\n Full path to the application node event in the zookeeper cache.\n :type event:\n ``str``\n :param runtime:\n The name of the runtime to use.\n :type runtime:\n ``str``\n :return:\n Application manifest object\n :rtype:\n ``dict``\n \"\"\"\n manifest_data = app_manifest.load(event)\n\n # apply runtime manipulation on manifest data\n runtime_cls = app_runtime.get_runtime_cls(runtime)\n runtime_cls.manifest(tm_env, manifest_data)\n return manifest_data\n\n\ndef configure(tm_env, event, runtime):\n \"\"\"Creates directory necessary for starting the application.\n\n This operation is idem-potent (it can be repeated).\n\n The directory layout is::\n\n - (treadmill root)/\n - apps/\n - (app unique name)/\n - data/\n - app_start\n - app.json\n - manifest.yml\n env/\n - TREADMILL_*\n run\n finish\n log/\n - run\n\n The 'run' script is responsible for creating container environment\n and starting the container.\n\n The 'finish' script is invoked when container terminates and will\n deallocate any resources (NAT rules, etc) that were allocated for the\n container.\n \"\"\"\n # Load the app from the event\n try:\n manifest_data = load_runtime_manifest(tm_env, event, runtime)\n except IOError:\n # File is gone. Nothing to do.\n _LOGGER.exception('No event to load: %r', event)\n return\n\n # Freeze the app data into a namedtuple object\n app = utils.to_obj(manifest_data)\n\n # Generate a unique name for the app\n uniq_name = appcfg.app_unique_name(app)\n\n # Write the actual container start script\n if os.name == 'nt':\n run_script = '{python} -m treadmill sproc run .'.format(\n python=sys.executable\n )\n else:\n run_script = '{python} -m treadmill sproc run ../'.format(\n python=sys.executable\n )\n\n # Create the service for that container\n container_svc = supervisor.create_service(\n tm_env.apps_dir,\n name=uniq_name,\n app_run_script=run_script,\n userid='root',\n downed=False,\n monitor_policy={\n 'limit': 0,\n 'interval': 60,\n 'tombstone': {\n 'uds': False,\n 'path': tm_env.running_tombstone_dir,\n 'id': app.name\n }\n },\n environ={},\n environment=app.environment\n )\n data_dir = container_svc.data_dir\n\n # Copy the original event as 'manifest.yml' in the container dir\n try:\n shutil.copyfile(\n event,\n os.path.join(data_dir, 'manifest.yml')\n )\n except IOError as err:\n # File is gone, cleanup.\n if err.errno == errno.ENOENT:\n shutil.rmtree(container_svc.directory)\n _LOGGER.exception('Event gone: %r', event)\n return\n else:\n raise\n\n # Store the app.json in the container directory\n fs.write_safe(\n os.path.join(data_dir, appcfg.APP_JSON),\n lambda f: f.writelines(\n utils.json_genencode(manifest_data)\n ),\n mode='w',\n permission=0o644\n )\n\n appevents.post(\n tm_env.app_events_dir,\n events.ConfiguredTraceEvent(\n instanceid=app.name,\n uniqueid=app.uniqueid\n )\n )\n\n return container_svc.directory\n","sub_path":"lib/python/treadmill/appcfg/configure.py","file_name":"configure.py","file_ext":"py","file_size_in_byte":4361,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"273463795","text":"import networkx as nx\r\nimport matplotlib.pyplot as ply\r\nimport random\r\nimport numpy as np\r\n\r\ndef check_existence(H,d):\r\n f = 0\r\n for each in H.nodes():\r\n if H.degree(each) <= d:\r\n f =1\r\n break\r\n return f\t\t\t\t \r\n \r\ndef find(H,it):\r\n set1=[]\r\n for each in H.nodes():\r\n if H.degree(each) <= it :\r\n set1.append(each)\t\r\n return set1\t\t\t\t\t\t\r\n\r\nG=nx.Graph() \r\nG = nx.read_edgelist('Graph_name.txt', nodetype = int)\r\nn = len(G.nodes())\r\n\r\nprint(\"no of nodes in graph:\"+str(n))\r\nN=list(G.nodes())\r\n\r\n''' Finding the buckets '''\r\nH = G.copy()\r\nit = 1\r\ntmp = []\r\nbuckets = []\r\nshell_no=[]\r\nwhile(1):\r\n flag =check_existence(H, it)\r\n if flag == 0:\r\n it = it+1\r\n buckets.append(tmp)\r\n tmp = []\r\n if flag ==1:\r\n node_set = find(H,it)\r\n for each in node_set:\r\n H.remove_node(each)\r\n tmp.append(each)\r\n if H.number_of_nodes() == 0:\r\n buckets.append(tmp)\r\n break\r\nfor w in range(n):\r\n shell_no.append(0)\r\nk=len(buckets)\r\nprint(\"no of shells: \"+str(k))\r\nmaximum = k-1\r\nj=0\r\nr=0\r\nsmallest_paths = [] \r\nfor j in range(len(N)):\r\n for r in range(k):\r\n if(N[j] in buckets[r]):shell_no[j] = r \r\n\r\nfor i in range(len(N)-1):\r\n for j in range(i+1, len(N)):\r\n \r\n if(nx.has_path(G,N[i],N[j]) == True):smallest_paths.append(nx.shortest_path(G,N[i],N[j]))\r\nsmallest_paths.sort(key=len)\t\t\t \r\n\r\nd = len(smallest_paths[len(smallest_paths)-1]) - 1\r\ndiameter = []\r\nfor i in range(len(smallest_paths) - 1, -1, -1):\r\n if(len(smallest_paths[i]) == d):diameter.append(smallest_paths[i])\r\nprint('diameter length of graph is: '+ str(d) )\t \r\n#print(diameter)\t \r\ndiameter_shells = []\r\ni=0\r\nj=0\r\ninner_encountered=[]\r\ninner_hit = []\r\nfor i in range(len(diameter)):\r\n diameter_shells = []\r\n number = 0\r\n hit = 0\r\n for j in range(len(diameter[i])):\r\n diameter_shells.append(shell_no[diameter[i][j]])\r\n if(shell_no[diameter[i][j]] == maximum) :\r\n number = number +1\r\n hit = 1\r\n inner_encountered.append(number)\r\n inner_hit.append(hit)\t\r\n print(i)\t\r\n print(diameter_shells)\r\n print('no of times the diameter passed through inner nodes are : '+str(number))\r\n\t \r\navg = sum(inner_encountered)/len(inner_encountered)\r\navgg = sum(inner_hit)/len(inner_hit)\r\nprint(\"no of tiimes it hit inner shell in each iteration: \")\r\nprint(inner_encountered)\r\nprint(\"to see whether it hit the inner shell : \")\r\nprint(inner_hit)\r\nprint('no of times on an average the diameter encountered the inner nodes is : '+str(avg))\r\nprint(\"no of times on an average the diameter hit the inner shell is : \"+str(avgg))\r\n\r\n\r\n","sub_path":"diameter_coreness.py","file_name":"diameter_coreness.py","file_ext":"py","file_size_in_byte":3007,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"604689906","text":"from .pages.main_page import MainPage\nfrom .pages.locators import MainPageLocators\n\ndef test_guest_can_go_to_login_page(browser):\n\n page = MainPage(browser, MainPageLocators.LINK)\n page.open()\n page.go_to_login_page()\n\ndef test_guest_should_see_login_link(browser):\n\n page = MainPage(browser, MainPageLocators.LINK)\n page.open()\n page.should_be_login_link()\n","sub_path":"env_stepik/test_main_page.py","file_name":"test_main_page.py","file_ext":"py","file_size_in_byte":376,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"258840414","text":"#Junhee Lee, Michael Lin\n#SoftDev1 pd1\n#K10 -- Jinja Tuning\n#2019-09-20\n\nfrom flask import Flask, render_template\nimport csv,random\n\napp = Flask(__name__)\n\n@app.route(\"/\")\ndef hello_world():\n print(__name__)\n return '''\n \n Main\n \n \n This was made using Flask
\n \n '''\n\n@app.route(\"/occupyflaskst\")\ndef occupations():\n rows = []\n with open('data/occupations.csv', 'r') as csvFile:\n csvreader = csv.reader(csvFile)\n for row in csvreader:\n rows.append(row)\n\n occDict = {}\n for item in rows[1: len( rows) - 1]:\n key = item[0] #key is the occupation name\n occDict[key] = (float(item[1]),item[2]) #key is a tuple (percentage, link)\n chosen = random.random() * float(rows[len(rows) - 1][1]) #random number [0.0, 1.0] multiplied by total\n\n for occupation in occDict.keys():\n chosen -= occDict[occupation][0] #keep subtracting the percentage of occupation\n if chosen <= 0: #if the chosen number is less than or equal to zero, then we found the occupation\n random_occupation = occupation \n break\n \n\n return render_template(\"table.html\",\n title=\"Occupation Data\",\n header=(\"Junhee Lee, Michael Lin\", \"SoftDev1 pd1\", \"K10 -- Jinja Tuning\", \"2019-09-20\"),\n heading=\"Occupations in the United States and Percentage of Workforce\",\n occupation=random_occupation,\n tHead=['Occupation Title','Percentage of Workforce'],\n entries=occDict)\n\nif __name__ == \"__main__\":\n app.debug = True \n app.run()","sub_path":"10_occ/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":1652,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"228147277","text":"\ndef bellman_ford_predecessor_and_distance(G, source, target=None,\n cutoff=None, weight='weight'):\n \"\"\"Compute shortest path lengths and predecessors on shortest paths\n in weighted graphs.\n\n The algorithm has a running time of $O(mn)$ where $n$ is the number of\n nodes and $m$ is the number of edges. It is slower than Dijkstra but\n can handle negative edge weights.\n\n Parameters\n ----------\n G : NetworkX graph\n The algorithm works for all types of graphs, including directed\n graphs and multigraphs.\n\n source: node label\n Starting node for path\n\n weight : string or function\n If this is a string, then edge weights will be accessed via the\n edge attribute with this key (that is, the weight of the edge\n joining `u` to `v` will be ``G.edges[u, v][weight]``). If no\n such edge attribute exists, the weight of the edge is assumed to\n be one.\n\n If this is a function, the weight of an edge is the value\n returned by the function. The function must accept exactly three\n positional arguments: the two endpoints of an edge and the\n dictionary of edge attributes for that edge. The function must\n return a number.\n\n Returns\n -------\n pred, dist : dictionaries\n Returns two dictionaries keyed by node to predecessor in the\n path and to the distance from the source respectively.\n Warning: If target is specified, the dicts are incomplete as they\n only contain information for the nodes along a path to target.\n\n Raises\n ------\n NetworkXUnbounded\n If the (di)graph contains a negative cost (di)cycle, the\n algorithm raises an exception to indicate the presence of the\n negative cost (di)cycle. Note: any negative weight edge in an\n undirected graph is a negative cost cycle.\n\n Examples\n --------\n >>> import networkx as nx\n >>> G = nx.path_graph(5, create_using = nx.DiGraph())\n >>> pred, dist = nx.bellman_ford_predecessor_and_distance(G, 0)\n >>> sorted(pred.items())\n [(0, [None]), (1, [0]), (2, [1]), (3, [2]), (4, [3])]\n >>> sorted(dist.items())\n [(0, 0), (1, 1), (2, 2), (3, 3), (4, 4)]\n\n >>> pred, dist = nx.bellman_ford_predecessor_and_distance(G, 0, 1)\n >>> sorted(pred.items())\n [(0, [None]), (1, [0])]\n >>> sorted(dist.items())\n [(0, 0), (1, 1)]\n\n >>> from nose.tools import assert_raises\n >>> G = nx.cycle_graph(5, create_using = nx.DiGraph())\n >>> G[1][2]['weight'] = -7\n >>> assert_raises(nx.NetworkXUnbounded, \\\n nx.bellman_ford_predecessor_and_distance, G, 0)\n\n Notes\n -----\n Edge weight attributes must be numerical.\n Distances are calculated as sums of weighted edges traversed.\n\n The dictionaries returned only have keys for nodes reachable from\n the source.\n\n In the case where the (di)graph is not connected, if a component\n not containing the source contains a negative cost (di)cycle, it\n will not be detected.\n\n \"\"\"\n if source not in G:\n raise nx.NodeNotFound(\"Node %s is not found in the graph\" % source)\n weight = _weight_function(G, weight)\n if any(weight(u, v, d) < 0 for u, v, d in nx.selfloop_edges(G, data=True)):\n raise nx.NetworkXUnbounded(\"Negative cost cycle detected.\")\n\n dist = {source: 0}\n pred = {source: [None]}\n\n if len(G) == 1:\n return pred, dist\n\n weight = _weight_function(G, weight)\n\n dist = _bellman_ford(G, [source], weight, pred=pred, dist=dist,\n cutoff=cutoff, target=target)\n return (pred, dist)\n\n\n\ndef _bellman_ford(G, source, weight, pred=None, paths=None, dist=None,\n cutoff=None, target=None):\n \"\"\"Relaxation loop for Bellman–Ford algorithm\n\n Parameters\n ----------\n G : NetworkX graph\n\n source: list\n List of source nodes\n\n weight : function\n The weight of an edge is the value returned by the function. The\n function must accept exactly three positional arguments: the two\n endpoints of an edge and the dictionary of edge attributes for\n that edge. The function must return a number.\n\n pred: dict of lists, optional (default=None)\n dict to store a list of predecessors keyed by that node\n If None, predecessors are not stored\n\n paths: dict, optional (default=None)\n dict to store the path list from source to each node, keyed by node\n If None, paths are not stored\n\n dist: dict, optional (default=None)\n dict to store distance from source to the keyed node\n If None, returned dist dict contents default to 0 for every node in the\n source list\n\n cutoff: integer or float, optional\n Depth to stop the search. Only paths of length <= cutoff are returned\n\n target: node label, optional\n Ending node for path. Path lengths to other destinations may (and\n probably will) be incorrect.\n\n Returns\n -------\n Returns a dict keyed by node to the distance from the source.\n Dicts for paths and pred are in the mutated input dicts by those names.\n\n Raises\n ------\n NetworkXUnbounded\n If the (di)graph contains a negative cost (di)cycle, the\n algorithm raises an exception to indicate the presence of the\n negative cost (di)cycle. Note: any negative weight edge in an\n undirected graph is a negative cost cycle\n \"\"\"\n\n if pred is None:\n pred = {v: [None] for v in source}\n\n if dist is None:\n dist = {v: 0 for v in source}\n\n G_succ = G.succ if G.is_directed() else G.adj\n inf = float('inf')\n n = len(G)\n\n count = {}\n q = deque(source)\n in_q = set(source)\n while q:\n u = q.popleft()\n in_q.remove(u)\n\n # Skip relaxations if any of the predecessors of u is in the queue.\n if all(pred_u not in in_q for pred_u in pred[u]):\n dist_u = dist[u]\n for v, e in G_succ[u].items():\n dist_v = dist_u + weight(v, u, e)\n\n if cutoff is not None:\n if dist_v > cutoff:\n continue\n\n if target is not None:\n if dist_v > dist.get(target, inf):\n continue\n\n if dist_v < dist.get(v, inf):\n if v not in in_q:\n q.append(v)\n in_q.add(v)\n count_v = count.get(v, 0) + 1\n if count_v == n:\n raise nx.NetworkXUnbounded(\n \"Negative cost cycle detected.\")\n count[v] = count_v\n dist[v] = dist_v\n pred[v] = [u]\n\n elif dist.get(v) is not None and dist_v == dist.get(v):\n pred[v].append(u)\n\n if paths is not None:\n dsts = [target] if target is not None else pred\n for dst in dsts:\n\n path = [dst]\n cur = dst\n\n while pred[cur][0] is not None:\n cur = pred[cur][0]\n path.append(cur)\n\n path.reverse()\n paths[dst] = path\n\n return dist\n\n\ndef bellman_ford_path(G, source, target, weight='weight'):\n \"\"\"Returns the shortest path from source to target in a weighted graph G.\n\n Parameters\n ----------\n G : NetworkX graph\n\n source : node\n Starting node\n\n target : node\n Ending node\n\n weight: string, optional (default='weight')\n Edge data key corresponding to the edge weight\n\n Returns\n -------\n path : list\n List of nodes in a shortest path.\n\n Raises\n ------\n NetworkXNoPath\n If no path exists between source and target.\n\n Examples\n --------\n >>> G=nx.path_graph(5)\n >>> print(nx.bellman_ford_path(G, 0, 4))\n [0, 1, 2, 3, 4]\n\n Notes\n -----\n Edge weight attributes must be numerical.\n Distances are calculated as sums of weighted edges traversed.\n\n See Also\n --------\n dijkstra_path(), bellman_ford_path_length()\n \"\"\"\n length, path = single_source_bellman_ford(G, source,\n target=target, weight=weight)\n return path\n\n\n\ndef bellman_ford_path_length(G, source, target, weight='weight'):\n \"\"\"Returns the shortest path length from source to target\n in a weighted graph.\n\n Parameters\n ----------\n G : NetworkX graph\n\n source : node label\n starting node for path\n\n target : node label\n ending node for path\n\n weight: string, optional (default='weight')\n Edge data key corresponding to the edge weight\n\n Returns\n -------\n length : number\n Shortest path length.\n\n Raises\n ------\n NetworkXNoPath\n If no path exists between source and target.\n\n Examples\n --------\n >>> G=nx.path_graph(5)\n >>> print(nx.bellman_ford_path_length(G,0,4))\n 4\n\n Notes\n -----\n Edge weight attributes must be numerical.\n Distances are calculated as sums of weighted edges traversed.\n\n See Also\n --------\n dijkstra_path_length(), bellman_ford_path()\n \"\"\"\n if source == target:\n return 0\n\n weight = _weight_function(G, weight)\n\n length = _bellman_ford(G, [source], weight, target=target)\n\n try:\n return length[target]\n except KeyError:\n raise nx.NetworkXNoPath(\n \"node %s not reachable from %s\" % (source, target))\n\n\n\ndef single_source_bellman_ford_path(G, source, cutoff=None, weight='weight'):\n \"\"\"Compute shortest path between source and all other reachable\n nodes for a weighted graph.\n\n Parameters\n ----------\n G : NetworkX graph\n\n source : node\n Starting node for path.\n\n weight: string, optional (default='weight')\n Edge data key corresponding to the edge weight\n\n cutoff : integer or float, optional\n Depth to stop the search. Only paths of length <= cutoff are returned.\n\n Returns\n -------\n paths : dictionary\n Dictionary of shortest path lengths keyed by target.\n\n Examples\n --------\n >>> G=nx.path_graph(5)\n >>> path=nx.single_source_bellman_ford_path(G,0)\n >>> path[4]\n [0, 1, 2, 3, 4]\n\n Notes\n -----\n Edge weight attributes must be numerical.\n Distances are calculated as sums of weighted edges traversed.\n\n See Also\n --------\n single_source_dijkstra(), single_source_bellman_ford()\n\n \"\"\"\n (length, path) = single_source_bellman_ford(\n G, source, cutoff=cutoff, weight=weight)\n return path\n\n\n\ndef single_source_bellman_ford_path_length(G, source,\n cutoff=None, weight='weight'):\n \"\"\"Compute the shortest path length between source and all other\n reachable nodes for a weighted graph.\n\n Parameters\n ----------\n G : NetworkX graph\n\n source : node label\n Starting node for path\n\n weight: string, optional (default='weight')\n Edge data key corresponding to the edge weight.\n\n cutoff : integer or float, optional\n Depth to stop the search. Only paths of length <= cutoff are returned.\n\n Returns\n -------\n length : iterator\n (target, shortest path length) iterator\n\n Examples\n --------\n >>> G = nx.path_graph(5)\n >>> length = dict(nx.single_source_bellman_ford_path_length(G, 0))\n >>> length[4]\n 4\n >>> for node in [0, 1, 2, 3, 4]:\n ... print('{}: {}'.format(node, length[node]))\n 0: 0\n 1: 1\n 2: 2\n 3: 3\n 4: 4\n\n Notes\n -----\n Edge weight attributes must be numerical.\n Distances are calculated as sums of weighted edges traversed.\n\n See Also\n --------\n single_source_dijkstra(), single_source_bellman_ford()\n\n \"\"\"\n weight = _weight_function(G, weight)\n return _bellman_ford(G, [source], weight, cutoff=cutoff)\n\n\n\ndef single_source_bellman_ford(G, source,\n target=None, cutoff=None, weight='weight'):\n \"\"\"Compute shortest paths and lengths in a weighted graph G.\n\n Uses Bellman-Ford algorithm for shortest paths.\n\n Parameters\n ----------\n G : NetworkX graph\n\n source : node label\n Starting node for path\n\n target : node label, optional\n Ending node for path\n\n cutoff : integer or float, optional\n Depth to stop the search. Only paths of length <= cutoff are returned.\n\n Returns\n -------\n distance, path : pair of dictionaries, or numeric and list\n If target is None, returns a tuple of two dictionaries keyed by node.\n The first dictionary stores distance from one of the source nodes.\n The second stores the path from one of the sources to that node.\n If target is not None, returns a tuple of (distance, path) where\n distance is the distance from source to target and path is a list\n representing the path from source to target.\n\n\n Examples\n --------\n >>> G = nx.path_graph(5)\n >>> length, path = nx.single_source_bellman_ford(G, 0)\n >>> print(length[4])\n 4\n >>> for node in [0, 1, 2, 3, 4]:\n ... print('{}: {}'.format(node, length[node]))\n 0: 0\n 1: 1\n 2: 2\n 3: 3\n 4: 4\n >>> path[4]\n [0, 1, 2, 3, 4]\n >>> length, path = nx.single_source_bellman_ford(G, 0, 1)\n >>> length\n 1\n >>> path\n [0, 1]\n\n Notes\n -----\n Edge weight attributes must be numerical.\n Distances are calculated as sums of weighted edges traversed.\n\n See Also\n --------\n single_source_dijkstra()\n single_source_bellman_ford_path()\n single_source_bellman_ford_path_length()\n \"\"\"\n if source == target:\n return (0, [source])\n\n weight = _weight_function(G, weight)\n\n paths = {source: [source]} # dictionary of paths\n dist = _bellman_ford(G, [source], weight, paths=paths, cutoff=cutoff,\n target=target)\n if target is None:\n return (dist, paths)\n try:\n return (dist[target], paths[target])\n except KeyError:\n msg = \"Node %s not reachable from %s\" % (source, target)\n raise nx.NetworkXNoPath(msg)\n\n\n\ndef all_pairs_bellman_ford_path_length(G, cutoff=None, weight='weight'):\n \"\"\" Compute shortest path lengths between all nodes in a weighted graph.\n\n Parameters\n ----------\n G : NetworkX graph\n\n weight: string, optional (default='weight')\n Edge data key corresponding to the edge weight\n\n cutoff : integer or float, optional\n Depth to stop the search. Only paths of length <= cutoff are returned.\n\n Returns\n -------\n distance : iterator\n (source, dictionary) iterator with dictionary keyed by target and\n shortest path length as the key value.\n\n Examples\n --------\n >>> G = nx.path_graph(5)\n >>> length = dict(nx.all_pairs_bellman_ford_path_length(G))\n >>> for node in [0, 1, 2, 3, 4]:\n ... print('1 - {}: {}'.format(node, length[1][node]))\n 1 - 0: 1\n 1 - 1: 0\n 1 - 2: 1\n 1 - 3: 2\n 1 - 4: 3\n >>> length[3][2]\n 1\n >>> length[2][2]\n 0\n\n Notes\n -----\n Edge weight attributes must be numerical.\n Distances are calculated as sums of weighted edges traversed.\n\n The dictionary returned only has keys for reachable node pairs.\n \"\"\"\n length = single_source_bellman_ford_path_length\n for n in G:\n yield (n, dict(length(G, n, cutoff=cutoff, weight=weight)))\n\n\n\ndef all_pairs_bellman_ford_path(G, cutoff=None, weight='weight'):\n \"\"\" Compute shortest paths between all nodes in a weighted graph.\n\n Parameters\n ----------\n G : NetworkX graph\n\n weight: string, optional (default='weight')\n Edge data key corresponding to the edge weight\n\n cutoff : integer or float, optional\n Depth to stop the search. Only paths of length <= cutoff are returned.\n\n Returns\n -------\n distance : dictionary\n Dictionary, keyed by source and target, of shortest paths.\n\n Examples\n --------\n >>> G = nx.path_graph(5)\n >>> path = dict(nx.all_pairs_bellman_ford_path(G))\n >>> print(path[0][4])\n [0, 1, 2, 3, 4]\n\n Notes\n -----\n Edge weight attributes must be numerical.\n Distances are calculated as sums of weighted edges traversed.\n\n See Also\n --------\n floyd_warshall(), all_pairs_dijkstra_path()\n\n \"\"\"\n path = single_source_bellman_ford_path\n # TODO This can be trivially parallelized.\n for n in G:\n yield (n, path(G, n, cutoff=cutoff, weight=weight))\n","sub_path":"aprilia's routing/NetworkX module/_bellman_ford_networkX.py","file_name":"_bellman_ford_networkX.py","file_ext":"py","file_size_in_byte":16459,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"384252278","text":"# coding: utf-8\nfrom riotpy.resources.game import GameResource\nfrom base import Manager\n\n\nclass GameManager(Manager):\n \"\"\"\n Game Manager. Show information about recent games.\n \"\"\"\n\n def get_recent_games(self, summoner_id):\n \"\"\" get a single user recent games\"\"\"\n content = self._get('api/lol/{}/{}/game/by-summoner/{}/recent'.format(\n self.api.region,\n self.version,\n summoner_id)\n )\n return self._dict_to_resource(content, resource_class=GameResource)\n","sub_path":"riotpy/managers/game.py","file_name":"game.py","file_ext":"py","file_size_in_byte":530,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"608020555","text":"class Solution(object):\n def addBinary(self, a, b):\n \"\"\"\n :type a: str\n :type b: str\n :rtype: str\n \"\"\"\n import itertools\n result = []\n c = 0\n for m, n in itertools.izip_longest(reversed(a), reversed(b), fillvalue='0'):\n r = int(m) + int(n) + c\n if r > 1:\n result.append(str(r-2))\n c = 1\n else:\n result.append(str(r))\n c = 0\n if c == 1:\n result.append('1')\n return ''.join(reversed(result))\n\n","sub_path":"python2/l0067_add_binary.py","file_name":"l0067_add_binary.py","file_ext":"py","file_size_in_byte":576,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"159966668","text":"\"\"\"PQI\nUsage:\n pqi ls\n pqi use \n pqi show\n pqi (-h | --help)\n pqi (-v | --version)\nOptions:\n -h --help Show this screen.\n -v --version Show version.\n\"\"\"\n\"\"\"\n _ __ _,.---._ .=-.-.\n .-`.' ,`. ,-.' - , `. /==/_ /\n /==/, - \\/==/ , - \\ |==|, |\n|==| _ .=. |==| - .=. , ||==| |\n|==| , '=',|==| : ;=: - ||==|- |\n|==|- '..'|==|, '=' , ||==| ,|\n|==|, | \\==\\ _ - ;|==|- |\n/==/ - | '.='. , ; -\\/==/. /\n`--`---' `--`--'' `--`--`-`\n\n ---- A Terminal Tools For Python\n\n\"\"\"\nfrom __future__ import print_function\n\nimport os\nimport re\nimport sys\nfrom docopt import docopt\ntry:\n import configparser\nexcept:\n import ConfigParser as configparser\n\n\nSOURCES = {\n \"pypi\": \"https://pypi.python.org/simple/\",\n \"tuna\": \"https://pypi.tuna.tsinghua.edu.cn/simple\",\n \"douban\": \"http://pypi.douban.com/simple/\",\n \"aliyun\": \"http://mirrors.aliyun.com/pypi/simple/\"\n}\n\nAPP_DESC = \"\"\"\n PQI\n ---- A Terminal Tools For Python\n @author Yanghangfeng (https:/github.com/Fenghuapiao)\n last_update 2016-10-29 08:58\n\"\"\"\n\ndef list_all_source():\n print(\"\\n\")\n for key in SOURCES.keys():\n print(key, \"\\t\", SOURCES[key])\n print(\"\\n\")\n\ndef write_file(name):\n path = os.path.expanduser(\"~/.pip/pip.conf\")\n file_ = os.path.dirname(path)\n if not os.path.exists(file_):\n os.mkdir(file_)\n with open(path,'w') as fp:\n str_ = \"[global]\\nindex-url = {0}\\n[install]\\ntrusted-host = {1}\".format(\n SOURCES[name], SOURCES[name].split('/')[2])\n fp.write(str_)\n\ndef select_source_name(name):\n if name not in SOURCES.keys():\n print(\"\\nSource name is not in the list.\\n\")\n else:\n write_file(name)\n print(\"\\nSource is changed to {name}.\\n\".format(name=name))\n\ndef show_current_source():\n config = configparser.ConfigParser()\n path = os.path.expanduser(\"~/.pip/pip.conf\")\n config.read(path)\n index_url = config.get(\"global\", \"index-url\")\n for key in SOURCES.keys():\n if index_url == SOURCES[key]:\n print(\"\\nCurrent source is {key}\\n\".format(key=key))\n break\n else:\n print(\"\\nUnknown source\\n\")\n\n\ndef main():\n arguments = docopt(__doc__, version='1.0.1')\n if arguments['ls']:\n list_all_source()\n elif arguments['use']:\n select_source_name(arguments[''])\n elif arguments['show']:\n show_current_source()\n else:\n print('input error!')\n\nif __name__ == '__main__':\n print(APP_DESC)\n main()\n","sub_path":"PQI/pqi.py","file_name":"pqi.py","file_ext":"py","file_size_in_byte":2577,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"638234019","text":"#!/usr/bin/env python\n\nimport argparse\nimport sys\n\nfrom operator import itemgetter\n\n#keep track of file\n#dict fileList[]\n\nclass HashTable:\n #mod hash value\n #modValue = 10\n \n def __init__(self):\n self.keys = [None]\n self.data = [None]\n\n def insertValue(self, key, data):\n \n #mod hash value\n modValue = 10 \n\n #generate a new hash value, \n hashValue = self.hashFunction(key, modValue)\n\n if self.keys[hashValue] == None:\n self.keys[hashValue] = key\n self.data[hashValue] = data\n else:\n if self.keys[hashValue] == key:\n # key is found, replace current data with new data\n self.data[hashValue] = data\n else:\n #collision occured, rehash a new value\n nextKey = self.rehash(hashValue, modValue)\n while self.keys[nextKey] != None and \\\n self.keys[nextKey] != key:\n nextKey = self.rehash(nextKey, modValue)\n #if no key is present set key and data\n if self.keys[nextKey] == None:\n self.keys[nextKey] = key\n self.data[nextkey] = data\n else:\n #key is found, replace existing data with new data\n self.data[nextKey] = data\n \n #Generate a hash value key modulo modValue\n def hashFunction(self, key, modValue):\n return key%modValue\n \n #Generate a new hash value (old value + 1) % moduloValue\n def rehash(self, hashValue, modValue):\n return (hashvalue + 1)%modValue\n \n #Calls hashfunction to find key, if collison occured and key placed \n #in a rehashed position will call rehash function. Stops when key is found\n #or if returns to initial position.\n def findValue(self, key):\n modValue = 10\n #find initial hash value\n intialPosition = self.hashFunction(key, modValue)\n \n data = None\n found = False\n stop = False\n \n position = initialPosition\n\n while self.keys[position] != None and not found and \\\n not stop:\n #Key is in initial position, data is returned\n if self.keys[position] == key:\n found = True\n data = self.data[position]\n #Key is not in initial position, rehash is called\n else:\n position = self.rehash(position, moduloValue)\n #Key has not been found, the rehashed position\n #has returned to the initial position\n if position == initialPosition:\n stop = True\n return data\n #Overload the getitem method\n #def __getitem__(self, key):\n # return self.findValue(key)\n \n #overload the setitem method\n #def __setitem_(self, key, data):\n # self.insertValue(key, data)\n\n#Prints barcodes to file\ndef tofile(l):\n \n #Writes reads with same BX: to file\n #ToDo: add hashtable to keep track of files if current code is to slow\n for i in range (len(l)):\n k = l[i]; \n with open('%s.txt' % k[0], 'a') as myFile: \n temp = l[i]\n myFile.write('@HD' + temp.pop(0) + '\\n')\n myFile.write('\\t'.join(temp) + '\\n')\n myFile.close()\n\n#write list to std out\ndef printOut(l):\n for i in range(len(l)):\n #to stdout as a list\n #sys.stdout.write(str(l[i]) + '\\n' + '\\n')\n \n temp = l[i]\n #pops BX barcode, sets as header\n print('@HD ' + temp.pop(0))\n #prints list contents delimited with a tab\n print('\\t'.join(temp) + '\\n')\n\n# Removes the BX: from barcode\ndef removeBX(s):\n return s[5:]\n\ndef main():\n fields = []\n barcodes = []\n temp = []\n count = 1\n #argparse declarations\n parser = argparse.ArgumentParser()\n parser.add_argument('--inputFile', '-f', help = \"Enter the\" + \\\n \" of the input file.\", type = str, required = True)\n\n args=parser.parse_args()\n\n with open(args.inputFile, 'r') as input:\n for line in input:\n \n fields = line.strip().split('\\t')\n if len(fields) > 1:\n for i in range (len(fields)):\n if fields[i].startswith('BX:'):\n fields.insert(0, str(removeBX(fields.pop(i)))) \n barcodes.append(fields)\n #printOut(fields)\n \n #printOut(barcodes)\n temp = sorted(barcodes, key = itemgetter(0, 1))\n #printOut(temp)\n tofile(temp);\n###############################################################################\nif __name__ == '__main__':\n main()\n","sub_path":"tools/barcode_sort.py","file_name":"barcode_sort.py","file_ext":"py","file_size_in_byte":4746,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"186054434","text":"from django.test import TestCase\nfrom django.core.urlresolvers import reverse\n\n\nclass MarkerTestCase(TestCase):\n\n def test_marker(self):\n ''' Test the marker page. '''\n resp = self.client.get(reverse('marker_page',\n kwargs={'marker': 'rs2476601'}))\n self.assertEqual(resp.status_code, 200)\n # check we've used the right template\n self.assertTemplateUsed(resp, 'marker/marker.html')\n","sub_path":"django_template/local_apps/marker/tests/tests_marker.py","file_name":"tests_marker.py","file_ext":"py","file_size_in_byte":458,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"122594264","text":"def is_pal(number):\n return True if reverse(number) == str(number) else False\n \ndef make_positive(number):\n return abs(int(number))\n\ndef reverse(number):\n return str(number)[::-1]\n\ndef reverse_add(low, high):\n \n if low == high:\n if is_pal(low):\n print('Is already PAL')\n return\n else:\n for num in range(low, high + 1):\n result = num\n count = 0\n while not is_pal(result):\n orig_result = result\n result = int(reverse(result)) + result\n if count >= 100:\n print('NOT PAL (' + str(count) + ' steps)')\n break\n count += 1\n print(str(count) + '. ' + str(orig_result) + ' + ' + reverse(str(orig_result)) + ' = ' + str(result))\n else:\n for num in range(low, high + 1):\n result = num\n count = 0\n while not is_pal(result):\n result = int(reverse(result)) + result\n if count >= 100:\n break\n count += 1\n if count >= 100:\n print(str(num) + ': NOT PAL (' + str(count) + ' steps)')\n else:\n print(str(num) + ': PAL (' + str(count) + ' steps)')\n \n\n ''' Executes the reverse and add algorithm for integers\n in the range low to high. For example, if low is 10 and\n high is 50, then the function would run the reverse and add\n procedure on the numbers 10, 11, .., 49, 50. Or, the user could be interested in a single number such as 89. In \n this case, low and high are both 89.\n '''\n#1 - take positive integer\n#2 - check if the int is pal.\n#3 - is pal. stop\n#4 - else: reverse digits\n#5 - add reverse to x\n#6 check if pal: stop if it is\n#7 - otherwise, 4 - 6 with result\n \n \n \ndef main():\n ''' The program driver. '''\n\n # set cmd to anything except quit()\n cmd = ''\n \n # process the user commands\n cmd = input('> ')\n while cmd != 'quit':\n i = 0\n while i < len(cmd) and cmd[i] != ' ':\n i += 1\n if ' ' in cmd: \n low = int(cmd[:i+1])\n high = int(cmd[i+1:]) \n else:\n low = int(cmd)\n high = low\n reverse_add(low, high)\n cmd = input('> ')\n\nmain()","sub_path":"Palindrome Creator.py","file_name":"Palindrome Creator.py","file_ext":"py","file_size_in_byte":2413,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"146398995","text":"#coding:utf-8\n__all__ = [\"Woe\"]\nimport numpy as np\nfrom collections import OrderedDict\nfrom score_card_model.utils.discretization.sharing import discrete, discrete_features\nfrom score_card_model.utils.check import check_array_binary, check_array_continuous\nfrom score_card_model.utils.count import count_binary\n\n\nclass Woe(object):\n \"\"\"\n 注意woe和iv方法如果有discrete参数,必须是tuple(func,dict)或者list(tuple(func,dict)).\n\n 使用的时候先实例化,然后使用`iv`或者`woe`或者调用`__call__`来获取其对应的值.\n\n Property:\n WOE_MIN (number): - WOE的最小值,如果rate_event为0就将它替换为woe_min\n WOE_MAX (number): - WOE的最大值,如果ratenon_event为0就将它替换为woe_max\n X (np.ndarray): - 输入的2-D矩阵\n tag (np.ndarray): - 输入的1-D数组,布尔标签数据\n event (Any): - 为True的标签\n label (Union[None, List[str]]): - 各项特征的名字列表\n discrete (Union[None, Tuple[Callable, Dict], List[Tuple[Callable, Dict]]]): - 处理各项特征分区间的tuple(func,args)数据\n \"\"\"\n @staticmethod\n def _x_result_line(x,discrete= None, **kwargs):\n if discrete:\n x = discrete(x, **kwargs)\n return x\n @staticmethod\n def _posibility(x, tag, event=1):\n \"\"\"\n 计算占总体的好坏占比\n \"\"\"\n if not check_array_binary(tag):\n raise AttributeError(\"tag must be a binary array\")\n if check_array_continuous(x):\n raise AttributeError(\"input array must not continuous\")\n event_total, non_event_total = count_binary(tag, event=event)\n x_labels = np.unique(x)\n pos_dic = {}\n for x1 in x_labels:\n y1 = tag[np.where(x == x1)[0]]\n event_count, non_event_count = count_binary(y1, event=event)\n rate_event = 1.0 * event_count / event_total\n rate_non_event = 1.0 * non_event_count / non_event_total\n pos_dic[x1] = (rate_event, rate_non_event)\n return pos_dic\n\n @staticmethod\n def weight_of_evidence(x, tag, event=1, woe_min=-20, woe_max=20):\n r'''对单独一项自变量(列,特征)计算其woe值.\n woe计算公式:\n\n .. math:: woe_i = log(\\frac {\\frac {Bad_i} {Bad_{total}}} {\\frac {Good_i} {Good_{total}}})\n '''\n woe_dict = {}\n pos_dic = Woe._posibility(x=x, tag=tag, event=event)\n for l, (rate_event, rate_non_event) in pos_dic.items():\n if rate_event == 0:\n woe1 = woe_min\n elif rate_non_event == 0:\n woe1 = woe_max\n else:\n woe1 = np.log(rate_event / rate_non_event) # np.log就是ln\n woe_dict[l] = woe1\n return woe_dict\n\n @staticmethod\n def information_value(x, tag, event=1, woe_min=-20, woe_max=20):\n '''对单独一项自变量(列,特征)计算其woe和iv值.\n iv计算公式:\n\n .. math:: IV_i=({\\\\frac {Bad_i}{Bad_{total}}}-{\\\\frac{Good_i}{Good_{total}}})*log(\\\\frac{\\\\frac{Bad_i}{Bad_{total}}}{\\\\frac{Good_i}{Good_{total}}})\n\n .. math:: IV = \\\\sum_{k=0}^n IV_i\n '''\n\n iv = 0\n pos_dic= Woe._posibility(x=x, tag=tag, event=event)\n for l, (rate_event, rate_non_event) in pos_dic.items():\n if rate_event == 0:\n woe1 = woe_min\n elif rate_non_event == 0:\n woe1 = woe_max\n else:\n woe1 = np.log(rate_event / rate_non_event)\n iv += (rate_event - rate_non_event) * woe1\n return iv\n\n @property\n def WOE_MIN(self):\n return self.__WOE_MIN\n @property\n def WOE_MAX(self):\n return self.__WOE_MAX\n @property\n def X(self):\n return self.__X\n @property\n def tag(self):\n return self.__tag\n @property\n def event(self):\n return self.__event\n @property\n def label(self):\n return self.__label\n @property\n def discrete(self):\n return self.__discrete\n\n\n\n\n def __init__(self,X, tag, event=1, label=None,\n discrete = None,\n min_v=-20, max_v=20):\n \"\"\"\n 初始化一个woe对象.\n\n Parameters:\n min_v (number): - WOE的最小值,如果rate_event为0就将它替换为woe_min\n max_v (number): - WOE的最大值,如果ratenon_event为0就将它替换为woe_max\n X (np.ndarray): - 输入的2-D矩阵\n tag (np.ndarray): - 输入的1-D数组,布尔标签数据\n event (Any): - 为True的标签\n label (Union[None, List[str]]): - 各项特征的名字列表\n discrete (Union[None, Tuple[Callable, Dict], List[Tuple[Callable, Dict]]]): - 处理各项特征分区间的tuple(func,args)数据\n\n Raises:\n AttributeError(\"label must have the same len with the features' number\") : - label如果长度与特征数不符则报错\n\n AttributeError(\"discrete method list must have the same len with the features' number\") : - discrete如果是列表,如果其长度与特征数不符则报错\n\n \"\"\"\n if label:\n if len(label) != X.shape[-1]:\n raise AttributeError(\"label must have the same len with the features' number\")\n\n if isinstance(discrete,list):\n if len(discrete) != X.shape[-1]:\n raise AttributeError(\"discrete method list must have the same len with the features' number\")\n self.__WOE_MIN = min_v\n self.__WOE_MAX = max_v\n self.__X = X\n self.__tag = tag\n self.__event = event\n self.__label = label\n self.__discrete = discrete\n self.__woe = None\n self.__iv = None\n self.X_result = None\n if self.discrete:\n if isinstance(discrete, tuple):\n discrete = [discrete for i in range(self.X.shape[-1])]\n result = []\n for i in range(self.X.shape[-1]):\n if len(discrete[i]) == 1:\n discretefunc = discrete[i][0]\n x = Woe._x_result_line(self.X[:, i],discrete=discretefunc)\n elif len(discrete[i]) == 2:\n discretefunc, kws = discrete[i]\n x= Woe._x_result_line(self.X[:, i],discrete=discretefunc, **kws)\n else:\n raise AttributeError(\"discrete argument must a tuple of the objects :func,args\")\n result.append(x)\n self.X_result = np.array(result).T\n else:\n self.X_result = self.X\n\n\n\n def __calcul(self,func):\n \"\"\"用于计算iv或者woe\n \"\"\"\n result = {}\n if not self.label:\n for i in range(self.X.shape[-1]):\n result[str(i)] = func(self.X_result[:, i], self.tag, self.event,woe_min=self.WOE_MIN, woe_max=self.WOE_MAX)\n else:\n for i in range(self.X.shape[-1]):\n result[self.label[i]] = func(self.X_result[:, i], self.tag, self.event,woe_min=self.WOE_MIN, woe_max=self.WOE_MAX)\n\n return result\n @property\n def iv(self):\n\n if self.__iv :\n return self.__iv\n result = self.__calcul(Woe.information_value)\n result = OrderedDict(sorted(result.items(), key=lambda t: t[1], reverse=True))\n\n self.__iv = result\n return result\n\n @property\n def woe(self):\n if self.__woe:\n return self.__woe\n result = self.__calcul(Woe.weight_of_evidence)\n self.__woe = result\n return result\n\n def __call__(self):\n\n iv = self.iv\n woe = self.woe\n result = {}\n for l,_ in iv.items():\n result[l] = {\"iv\":iv.get(l),\n \"woe\":woe.get(l)\n }\n result = OrderedDict(sorted(result.items(), key=lambda t: t[1][\"iv\"], reverse=True))\n return result\n","sub_path":"ScoreCardModel/feature_selection/weight_of_evidence.py","file_name":"weight_of_evidence.py","file_ext":"py","file_size_in_byte":7903,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"322501056","text":"from . import web\n\nfrom flask_login import login_user\nfrom flask import redirect, make_response\n\nfrom handlers import user\n\nfrom models import User, User_auth\n\nfrom init_app import login_manager, db, oid\n\n@web.errorhandler(401)\ndef page_not_found(e):\n return redirect('/login')\n\n@login_manager.user_loader\ndef load_user(user_id):\n if user_id != 'None':\n real_user = db.session.query(User).filter(User.steamid == user_id).one()\n auth_user = User_auth(real_user.steamid)\n auth_user.user_identifier = real_user.user_identifier\n\n return auth_user\n\n@oid.after_login\ndef login_handling(steam_response):\n steamid = steam_response.identity_url.split('/')[5]\n\n if db.session.query(User).filter(User.steamid == steamid).count():\n login_user(User_auth(steamid))\n\n else:\n new_user = User(steamid)\n\n db.session.add(new_user)\n db.session.commit()\n\n login_user(User_auth(steamid))\n\n user.update_user_identifier(steamid)\n\n response = make_response(redirect('/'))\n\n response.set_cookie('user_identifier', db.session.query(User).filter(User.steamid == steamid).one().user_identifier)\n\n return response\n","sub_path":"web/others.py","file_name":"others.py","file_ext":"py","file_size_in_byte":1174,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"230150867","text":"from django.shortcuts import render\nimport requests\n\npogoda_api_key = 'fa0c69065a227aae0ae1081d5953bcfa'\n\npogoda_url = 'https://api.openweathermap.org/data/2.5/weather?q={city},{state}&lang=ru&appid={api_key}&units=metric'\n\n\ndef current_weather(request):\n weathers = {\n 'osh': 36.4,\n 'bishkek': 31.4,\n 'london': 24.5\n }\n return render(request, 'weather_template.html', {\n 'osh': weathers['osh'],\n 'bishkek': weathers['bishkek']\n })\n\n\ndef weather_online(request):\n return render(request, 'weather_online.html')\n\n\ndef get_weather_online(request):\n city_for_url = request.POST.get('city_input')\n state_for_url = request.POST.get('state_input')\n \n pogoda_url_final = pogoda_url.format(\n city = city_for_url, \n state = state_for_url, \n api_key = pogoda_api_key\n )\n\n pogo_otvet = requests.get(pogoda_url_final)\n pogo_otvet_json = pogo_otvet.json()\n\n temp = pogo_otvet_json['main']['temp']\n\n return render(request, 'weather_online.html', {\n 'pogoda_otvet': pogo_otvet_json,\n 'temperature': temp,\n 'city_for_url': city_for_url\n })","sub_path":"valuta_django/weather/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1145,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"556816228","text":"import numpy as np\nfrom optparse import OptionParser\nimport gym\nimport gym_minigrid\nimport sys, time\nfrom tqdm import tqdm\nfrom sarsa_agent import SarsaAgent, DifferentialSarsaAgent\n\ndef visualize_after_training(env, agent, pause_length):\n\n obs = env.reset()\n action = agent.agent_start(obs)\n\n for _ in range(100):\n\n obs, reward, done, info = env.step(action)\n action = agent.choose_action(obs)\n renderer = env.render()\n time.sleep(pause_length)\n\n if renderer.window is None:\n break\n\ndef run_sarsa():\n\n parser = OptionParser()\n parser.add_option(\n \"-e\",\n \"--env-name\",\n dest=\"env_name\",\n help=\"gym environment to load\",\n default='MiniGrid-Empty-8x8-v0'\n )\n parser.add_option(\n \"--seed\",\n type=int,\n help=\"random seed (default: 1)\",\n default=1000\n )\n parser.add_option(\n \"--pause\",\n type=float,\n default=0.1,\n help=\"pause duration between two consequent actions of the agent\"\n )\n parser.add_option(\n \"--num_runs\",\n type=int,\n help=\"number of runs of experiment to average over\",\n default=10\n )\n parser.add_option(\n \"--num_eps\", # for usual (non-differential) Sarsa\n type=int,\n help=\"number of episodes in a single run\",\n default=1500\n )\n (options, args) = parser.parse_args()\n\n # step_sizes = [1e-3, 1e-2, 1e-1, 1.0]\n step_sizes = [1e-1]\n\n all_rewards = np.ndarray((len(step_sizes), options.num_runs, options.num_eps), dtype=np.int)\n log_data = {\"step_sizes\": step_sizes, \"num_runs\": options.num_runs, \"betas\" : []}\n\n for step_idx, step_size in enumerate(step_sizes):\n\n tqdm.write('Sarsa : Alpha=%f' % (step_size))\n\n for run in tqdm(range(options.num_runs), file=sys.stdout):\n\n seed = options.seed + run\n # Load the gym environment\n env = gym.make(options.env_name)\n env.seed(seed)\n\n agent = SarsaAgent()\n agent_info = {\"num_states\": 64,\n \"num_actions\": 4,\n \"epsilon\": 0.2,\n \"step-size\": step_size,\n \"random_seed\": seed}\n agent.agent_init(agent_info=agent_info)\n\n # rewards = []\n\n for eps in range(options.num_eps):\n\n sum_rewards = 0.0\n num_steps = 0\n done = 0\n obs = env.reset()\n action = agent.agent_start(obs)\n\n while done==0:\n\n obs, reward, done, info = env.step(action)\n if done!=1:\n action = agent.agent_step(reward, obs)\n else:\n agent.agent_end(reward)\n # no update when agent time-outs (done=2)\n\n sum_rewards += reward\n num_steps += 1\n\n ### For visualization\n # renderer = env.render()\n # time.sleep(options.pause)\n\n # if renderer.window is None:\n # break\n\n all_rewards[step_idx][run][eps] = num_steps\n\n log_data[\"action_values\"] = agent.q_values\n ### Visualization after training\n # visualize_after_training(env, agent, options.pause)\n\n # all_rewards.append(rewards)\n tqdm.write('AvgReward_total\\t\\t= %f' % (1.0/(np.mean(np.mean(all_rewards[step_idx])))))\n\n log_data[\"all_rewards\"] = all_rewards\n np.save('results/rewards_sarsa', log_data)\n\n\ndef run_diff_sarsa():\n parser = OptionParser()\n parser.add_option(\n \"-e\",\n \"--env-name\",\n dest=\"env_name\",\n help=\"gym environment to load\",\n default='MiniGrid-Empty-8x8-cont-v0'\n )\n parser.add_option(\n \"--seed\",\n type=int,\n help=\"random seed (default: 1)\",\n default=1000\n )\n parser.add_option(\n \"--pause\",\n type=float,\n default=0.1,\n help=\"pause duration between two consequent actions of the agent\"\n )\n parser.add_option(\n \"--num_runs\",\n type=int,\n help=\"number of runs of experiment to average over\",\n default=10\n )\n parser.add_option(\n \"--run_length\",\n type=int,\n help=\"number of timesteps of a single run\",\n default=20000\n )\n (options, args) = parser.parse_args()\n\n # step_sizes = [1e-3, 1e-2, 1e-1, 1.0]\n # betas = [1e-3, 1e-2, 1e-1, 1.0]\n step_sizes = [1e-1]\n betas = [1e-2]\n # kappas = [1e-3, 1e-2, 1e-1, 1.0]\n kappas = [0.1, 0.2, 0.4, 0.6, 0.8, 0.9]\n # kappas = [0.45, 0.55, 0.6, 0.65, 0.7]\n\n all_rewards = np.ndarray((len(step_sizes), len(betas), len(kappas), options.num_runs, options.run_length))\n avg_values = np.ndarray((len(step_sizes), len(betas), len(kappas), options.num_runs))\n log_data = {\"step_sizes\": step_sizes, \"betas\": betas, \"kappas\": kappas, \"num_runs\": options.num_runs}\n\n for step_idx, step_size in enumerate(step_sizes):\n\n for beta_idx, beta in enumerate(betas):\n\n for kappa_idx, kappa in enumerate(kappas):\n\n tqdm.write('DiffSarsa : Alpha=%f, Beta=%f, Kappa=%f' % (step_size, beta, kappa))\n\n for run in tqdm(range(options.num_runs), file=sys.stdout):\n\n seed = options.seed + run\n # Load the gym environment\n env = gym.make(options.env_name)\n env.seed(seed)\n\n agent = DifferentialSarsaAgent()\n agent_info = {\"num_states\": 64,\n \"num_actions\": 4,\n \"epsilon\": 0.2,\n \"step-size\": step_size,\n \"beta\": beta,\n \"kappa\": kappa,\n \"random_seed\": seed}\n agent.agent_init(agent_info=agent_info)\n\n obs = env.reset()\n action = agent.agent_start(obs)\n\n # sum_rewards = 0.0\n # rewards = []\n avg_rewards = []\n\n for timestep in range(options.run_length):\n\n obs, reward, done, info = env.step(action)\n action = agent.agent_step(reward, obs)\n\n # sum_rewards += reward\n all_rewards[step_idx][beta_idx][kappa_idx][run][timestep] = reward\n\n\n avg_rewards.append(agent.avg_reward)\n ### For visualization\n # renderer = env.render()\n # time.sleep(options.pause)\n\n # if renderer.window is None:\n # break\n\n # Visualization after training\n # obs = env.reset()\n # action = agent.agent_start(obs)\n #\n # for _ in range(100):\n #\n # obs, reward, done, info = env.step(action)\n # action = agent.choose_action(obs)\n # renderer = env.render()\n # time.sleep(options.pause)\n #\n # if renderer.window is None:\n # break\n\n log_data[\"action_values\"] = agent.q_values\n log_data[\"average_rewards\"] = avg_rewards\n avg_values[step_idx][beta_idx][kappa_idx][run] = agent.avg_value\n # tqdm.write(\"Avg. reward : %f\" % agent.avg_reward)\n\n # all_rewards.append(rewards)\n\n tqdm.write('AvgReward_total\\t\\t= %f' % (np.mean(all_rewards[step_idx][beta_idx][kappa_idx])))\n tqdm.write('AvgReward_last1000\\t= %f\\n' % (np.mean(all_rewards[step_idx,beta_idx,kappa_idx,:,-1000:])))\n\n log_data[\"all_rewards\"] = all_rewards\n log_data[\"avg_values\"] = avg_values\n np.save('results/rewards_diff_sarsa', log_data)\n\n\ndef main():\n\n run_diff_sarsa()\n # run_sarsa()\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"experiment.py","file_name":"experiment.py","file_ext":"py","file_size_in_byte":8247,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"149434277","text":"import os\nimport time\nimport inspect\nimport numpy as np\nimport pandas as pd\nfrom random import sample\nfrom multiprocessing import Process, Manager\n\nfrom .tools import *\n\nclass AI:\n def __init__(self, main):\n '''Analyze AI state.'''\n self.main = main\n self.data = main.get_data()\n\n def get_corr(self, list1, list2=None, proc_id=None, rtr_dict=None,\n print_proc=False):\n ''' get correlations of 1 (auto) or 2 lists of spikes or etc. '''\n # multiprocessing\n if proc_id is not None and rtr_dict is not None and print_proc:\n print('get_corr() proc {} start'.format(proc_id))\n\n if type(list2) is not list: # list2 no data, use the same list\n flg_samepop = True\n else:\n flg_samepop = False\n\n coef_list = []\n for i, hist1 in enumerate(list1):\n if flg_samepop:\n idxs = list(range(i + 1, len(list1)))\n else:\n idxs = list(range(len(list2)))\n for j in idxs:\n if flg_samepop:\n hist2 = list1[j]\n else:\n hist2 = list2[j]\n if np.sum(hist1) != 0 and np.sum(hist2) != 0:\n coef = np.corrcoef(hist1, hist2)[0, 1]\n coef_list.append(coef)\n else:\n print('oops, no data in one/both histograms')\n\n # multiprocessing\n if proc_id is not None and rtr_dict is not None:\n rtr_dict[str(proc_id)] = coef_list\n if print_proc:\n print('get_corr() proc {} end'.format(proc_id))\n\n return coef_list\n\n def calc_ai(self, begin, end, bw=10, seg_len=5000., n_sample=140,\n n_spk_thr=5, n_layer=4):\n '''\n calculate AI scores: 1. pairwise spike count correlation 2. CV of ISI\n '''\n t0 = time.time()\n # setup\n df = self.main.df['spike_detector']\n segs = gen_segs(begin, end, seg_len)\n df_corr = pd.DataFrame(\n columns=['layer', 'segment', 'mu', 'SD', 'SEM', 'n'])\n df_cv = pd.DataFrame(\n columns=['layer', 'segment', 'mu', 'SD', 'SEM', 'n'])\n\n ''' calculation part '''\n # multiprocessing\n return_dict, procs = Manager().dict(), []\n\n # filter and sample\n for i, (head, tail) in enumerate(segs):\n # unfiltered segment data (for corr)\n df_seg = df[(df.time >= head) & (df.time < tail)]\n # filtered segment data (for cv)\n df_seg_cv = df_seg.groupby('id').filter(lambda x:\n len(x) >= n_spk_thr).reset_index(drop=True)\n # loop layers\n for j, lyr in enumerate(list(range(n_layer))):\n # sample n_sample per layer\n set_corr = set(df_seg[df_seg.layer==lyr].id)\n sample_corr = df_seg[df_seg.id.isin(sample(set_corr,\n min(len(set_corr), n_sample)))]\n set_cv = set(df_seg_cv[df_seg_cv.layer==lyr].id)\n sample_cv = df_seg_cv[df_seg_cv.id.isin(sample(set_cv,\n min(len(set_cv), n_sample)))]\n\n # corr calculation\n hists = []\n for id in list(set(sample_corr.id)):\n ts = sample_corr[sample_corr.id == id].time.values\n hist_bins = np.arange(head, tail + bw, bw)\n hist = np.histogram(ts, bins=hist_bins)[0]\n hists.append(hist)\n\n # set multiprocessing (corr)\n proc = Process(target=self.get_corr,\n args=(hists, None, int(i*n_layer + lyr), return_dict))\n procs.append(proc)\n proc.start()\n\n # cv of isi calculation\n cvs = []\n for k, id in enumerate(list(set(sample_cv.id))):\n ts = sample_cv[sample_cv.id == id].time.values\n ISIs = np.diff(ts)\n cvs.append(np.std(ISIs) / np.mean(ISIs))\n df_cv = df_cv.append(\n {'layer': lyr, 'segment': i,\n 'mu': np.mean(cvs), 'SD': np.std(cvs),\n 'SEM': np.std(cvs)/np.sqrt(len(cvs)),\n 'n': len(cvs)}, ignore_index=True)\n\n # join multiprocessing (corr)\n for proc in procs:\n proc.join()\n\n # collect corr data\n for i, (head, tail) in enumerate(segs):\n for lyr in range(n_layer):\n try:\n corrs = return_dict[str(int(i*n_layer + lyr))]\n df_corr = df_corr.append(\n {'layer': lyr, 'segment': i,\n 'mu': np.mean(corrs), 'SD': np.std(corrs),\n 'SEM': np.std(corrs)/np.sqrt(len(corrs)),\n 'n': len(corrs)}, ignore_index=True)\n except KeyError:\n pass\n\n ''' save part '''\n # save for scan analysis\n corr_mu, corr_n, cv_mu, cv_n = [], [], [], []\n for i in self.main.rdict['results_lyr'].layer_idx:\n corr_mu.append(df_corr[df_corr.layer==i].mu.mean())\n corr_n.append(int(df_corr[df_corr.layer==i].n.mean()))\n cv_mu.append(df_cv[df_cv.layer==i].mu.mean())\n cv_n.append(int(df_cv[df_cv.layer==i].n.mean()))\n self.main.rdict['results_lyr']['corr_data_mu'] = corr_mu\n self.main.rdict['results_lyr']['corr_data_n'] = corr_n\n self.main.rdict['results_lyr']['cv_data_mu'] = cv_mu\n self.main.rdict['results_lyr']['cv_data_n'] = cv_n\n\n # save to .csv (obsolete)\n df_corr.to_csv(os.path.join(self.main.path, 'data-corr.csv'), index=False)\n df_cv.to_csv(os.path.join(self.main.path, 'data-cv.csv'), index=False)\n\n # save to self\n for i in range(n_layer):\n self.main.rdict['corrs'].append(\n df_corr[df_corr.layer==i] \\\n [['mu', 'SD', 'SEM', 'n']].mean(axis=0).values.tolist())\n self.main.rdict['cvs'].append(\n df_cv[df_cv.layer==i] \\\n [['mu', 'SD', 'SEM', 'n']].mean(axis=0).values.tolist())\n\n # print\n print('calc_ai() pair. corr. and CV of ISI:')\n print([self.main.rdict['results_lyr']['corr_data_mu'].values.round(decimals=3).tolist(),\n self.main.rdict['results_lyr']['cv_data_mu'].values.round(decimals=3).tolist()])\n\n print('{}() running time = {:.3f} s'.format(inspect.stack()[0][3],\n time.time()-t0))\n","sub_path":"analysis/ai.py","file_name":"ai.py","file_ext":"py","file_size_in_byte":6557,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"65643098","text":"from django.conf.urls import patterns, include, url\n\nurlpatterns = patterns('production.views',\n url(r'categories/$', 'show_categories', name= 'show_categories'),\n url(r'categories/(?P\\d+)/$', 'show_category', name='show_category'),\n url(r'product/(?P\\d+)/$', 'show_product', name='show_product'),\n url(r'add_compare/(?P\\d+)/$', 'add_to_compare', name='add_compare'),\n url(r'add_comment/(?P\\d+)/$', 'add_comment', name='add_comment'),\n url(r'added_wishlist/(?P\\d+)/$', 'added_to_wishlist', name='added_wishlist'),\n url(r'added_compare/(?P\\d+)/$', 'added_to_compare', name='added_compare'),\n url(r'added_shopping_cart/(?P\\d+)/$', 'added_to_checkout', name='added_checkout'),\n url(r'add_wishlist/(?P\\d+)/$', 'add_to_wish_list', name='add_wishlist'),\n url(r'discounts/$', 'show_discounts', name='show_discounts'),\n url(r'discounts/(?P\\d+)/$', 'show_discount', name='show_discount'),\n)\n","sub_path":"shop/production/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1234,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"62255363","text":"# uncompyle6 version 3.7.4\n# Python bytecode 3.6 (3379)\n# Decompiled from: Python 3.6.9 (default, Apr 18 2020, 01:56:04) \n# [GCC 8.4.0]\n# Embedded file name: build/bdist.linux-x86_64/egg/Zeras/test.py\n# Compiled at: 2020-03-15 07:46:43\n# Size of source mod 2**32: 474 bytes\nimport tensorflow as tf\n\ndef test_tensorflow_gpu():\n \"\"\"\n \"\"\"\n a = tf.constant([1.0, 2.0, 3.0, 4.0, 5.0, 6.0], shape=[2, 3], name='a')\n b = tf.constant([1.0, 2.0, 3.0, 4.0, 5.0, 6.0], shape=[3, 2], name='b')\n c = tf.matmul(a, b)\n sess = tf.Session(config=tf.ConfigProto(log_device_placement=True))\n print(sess.run(c))\n\n\nif __name__ == '__main__':\n test_tensorflow_gpu()","sub_path":"pycfiles/Zeras-0.4.4-py3.6/test.cpython-36.py","file_name":"test.cpython-36.py","file_ext":"py","file_size_in_byte":667,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"568228666","text":"# 3. Написати функцію яка приймає список елементів і знаходить суму, до функції написати декоратор\n# який перед тим як запустити функцію видаляє з списку всі не чисельні типи даних, але якщо є строка,\n# яку можна перевести в число, (наприклад “1”) то строка приводиться до чисельного типу даних\n\n\ndef check_data(func):\n def wrap(list_):\n def check_convert_to_float(el_):\n try:\n float(el_)\n return True\n except ValueError:\n return False\n filter_list = []\n for el in list_:\n check_int = isinstance(el, int)\n check_float = isinstance(el, float)\n check_convert_to_int = str(el).isdigit()\n if check_int or check_float:\n filter_list.append(el)\n elif check_convert_to_int:\n convert_el = int(el)\n filter_list.append(convert_el)\n elif check_convert_to_float(el):\n convert_el = float(el)\n filter_list.append(convert_el)\n result = func(filter_list)\n print(list_)\n print(filter_list)\n print(f\"The sum of the items in the filtered list = {result}\")\n return result\n\n return wrap\n\n\n@check_data\ndef sum_list(list_):\n sum_el = sum(list_)\n return sum_el\n\n\nsum_list([1, '6', 2.0, 't', '4r', '4.5'])\n\n# [1, '6', 2.0, 't', '4r', '4.5']\n# [1, 6, 2.0, 4.5]\n# The sum of the items in the filtered list = 13.5\n","sub_path":"#13_Decorators/Task_3.py","file_name":"Task_3.py","file_ext":"py","file_size_in_byte":1699,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"406769243","text":"import pandas as pd\nimport matplotlib.pyplot as plt\nimport numpy as np\n\n\ndef disable_grid_form_axis(axis):\n axis.get_xaxis().set_visible(False)\n axis.get_yaxis().set_visible(False)\n\n\ndef scatter_plot_from_dataframe(dataframe, color_filter, magnitude_amplifier):\n fig, (ax1) = plt.subplots(frameon=False)\n # ax1.grid(color='#cccccc', axis='y')\n grid_color = '#cccccc'\n colors = []\n if color_filter=='album':\n for value in dataframe['album']:\n #jack johnson\n if value == 'BF':\n colors.append('#DBE2EB')\n elif value == 'onandon':\n colors.append('#009B94')\n elif value == 'inbetweendreams':\n colors.append('#EFCE10')\n # avicii\n elif value == 'true':\n colors.append('#0E4691')\n elif value == 'stories':\n colors.append('#DC5463')\n else:\n colors.append('#EABE67')\n elif color_filter=='sentiment':\n for value in dataframe['score']:\n if value < 0:\n colors.append('red')\n elif value > 0:\n colors.append('green')\n else:\n colors.append(grid_color)\n sizes = []\n for size in dataframe['magnitude']:\n sizes.append(size*magnitude_amplifier)\n x_values = dataframe['score']\n ax1.plot([0, 0], [0, max(dataframe['magnitude'])+1], c=grid_color, linewidth=1, zorder=1)\n ax1.scatter(x_values, dataframe['magnitude'], c=colors, s=sizes, alpha=0.5, zorder=2)\n plt.ylabel('magnitude')\n plt.xlabel('sentiment')\n ax1.spines['right'].set_visible(False)\n ax1.spines['bottom'].set_visible(False)\n ax1.spines['top'].set_visible(False)\n ax1.spines['left'].set_visible(False)\n ax1.spines['bottom'].set_color(grid_color)\n ax1.spines['left'].set_color(grid_color)\n ax1.xaxis.label.set_color(grid_color)\n ax1.tick_params(axis='x', colors=grid_color)\n ax1.yaxis.label.set_color(grid_color)\n ax1.tick_params(axis='y', colors=grid_color)\n ax1.set_ylim(ymin=0, ymax=max(dataframe['magnitude'])+(max(dataframe['magnitude'])*0.1))\n ax1.set_xlim(xmin=(max(dataframe['score'])+0.1)*-1, xmax=max(dataframe['score'])+0.1)\n ax1.get_yaxis().set_visible(False)\n ax1.get_yaxis().set_visible(False)\n disable_grid_form_axis(ax1)\n plt.show()\n\n\ndef convert_xlsx_into_dataframe(xlsx_file):\n xls = pd.ExcelFile(xlsx_file)\n df = xls.parse(xls.sheet_names[0])\n return df\n\nscatter_plot_from_dataframe(convert_xlsx_into_dataframe('output/song_sentiment_jj_first_three_discography.xlsx'), 'album', 28)","sub_path":"visualise.py","file_name":"visualise.py","file_ext":"py","file_size_in_byte":2618,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"594789910","text":"from openerp import fields,models\nclass etudiant(models.Model):\n _name = 'etudiant'\n matricule=fields.char('matricule',size=30,required=True, help='the name')\n nom=fields.char('nom',size=30,required=True, help='the first name')\n dateN=fields.date('dateN',size=30,required=True, help='the birth date')\n prenom=fields.char('prenom',size=50, help='the email')\n id_encadreur=many2one('encadreur')\n sessionEncadrementEtudiant_ids=one2many('sessionEncadrementEtudiant','id_etudiant')\n\netudiant()\nclass doctorant(models.Model):\n _name = 'doctorant'\n nom=fields.char('first name',size=30,required=True, help='the first name')\n dateN=fields.date('date',size=30,required=True, help='the birth date')\n prenom=fields.char('email',size=50, help='the email')\n etat=fields.char('etat',size=50,help='the stat of the doctorant')\n id_encadreurD = many2one('encadreur')\n id_these=many2one('these')\n sessionEncadrementDoctorant_ids = one2many('sessionEncadrementDoctorant', 'id_doctorant')\n sessionEvaluation_ids = one2many('sessionEvaluation', 'doctorant_id')\n\ndoctorant()\nclass encadreur(models.Model):\n _name = 'encadreur'\n nom=fields.char('nom',size=30,required=True, help='the name')\n prenom=fields.char('prenom',size=30,required=True, help='the first name')\n dateN=fields.date('dateN',size=30,required=True, help='the birth date')\n fonction=fields.char('fonction',size=50, help='the job')\n etudiant_ids = one2many('etudiant','id_encadreur')\n doctorant_ids = one2many('doctorant', 'id_encadreurD')\n\nencadreur()\nclass jury(models.Model):\n _name = 'jury'\n nom=fields.char('nom',size=30,required=True, help='the name')\n prenom=fields.char('prenom',size=30,required=True, help='the first name')\n dateN=fields.date('dateN',size=30,required=True, help='the birth date')\n fonction=fields.char('fonction',size=50, help='the job')\n sessionEvaluation_ids = one2many('sessionEvaluation','jury_id')\n\njury()\nclass these(models.Model):\n _name = 'these'\n titre=fields.char('titre',size=30,required=True, help='the title')\n description=fields.char('description',size=30,required=True, help='the description')\n doctorant_ids = one2many('doctorant','id_these')\n\nthese()\nclass formulaireE(models.Model):\n _name = 'formulaireE'\n note=fields.integer('note',size=30,required=True, help='the mark')\n motifs=fields.char('motifs',size=30,required=True, help='motives')\n remarques=fields.char('remarques',size=50, help='the notes')\n sessionEvaluation_id = one2many('sessionEvaluation','formulaireE_id')\n\nformulaireE()\nclass sessionEvaluation(models.Model):\n _name = 'sessionEvaluation'\n heure=fields.char('titre',size=30,required=True, help='the title')\n date = fields.date('date', size=30, required=True)\n lieux = fields.char('lieux',size=30,required=True)\n doctorant_id=fields.many2one('doctorant')\n jury_id=many2one('jury')\n formulaireE_id = many2one('formulaireE')\n\n\nclass sessionEncadrementEtudiant(models.Model):\n _name = 'sessionEncadrement'\n heure=fields.char('titre',size=30,required=True, help='the time')\n date = fields.date('date', size=30, required=True)\n etatAvancement = fields.char('etatAvancement', size=50, help='')\n remarques = fields.char('remarques', size=50, help='the notes')\n id_etudiant=many2one('etudiant')\n\nclass sessionEncadrementDoctorant(models.Model):\n _name = 'sessionEncadrement'\n heure=fields.char('titre',size=30,required=True, help='the time')\n date = fields.date('date', size=30, required=True)\n etatAvancement = fields.char('etatAvancement', size=50, help='')\n remarques = fields.char('remarques', size=50, help='the notes')\n id_doctorant=many2one('doctorant')\n\n","sub_path":"Etudiant_et_Doctorant/etudiants_et_doctorants.py","file_name":"etudiants_et_doctorants.py","file_ext":"py","file_size_in_byte":3730,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"548888551","text":"import numpy as np\nimport pandas as pd\n\n\nHQ = '../../../rcc-uchicago/PCNO/CSV/chicago/contracts_w_hq_addresses.csv'\nGEO = '../../../rcc-uchicago/PCNO/CSV/chicago/Geocoded Service Addresses/map1_addresses_geocoded.csv'\nMAP1 = '../../../rcc-uchicago/PCNO/CSV/chicago/Maps/map1.csv'\n\ndef read_geo():\n '''\n Reads in the geocoded addresses for map 1. Drops the 'Match Score' column.\n Returns a dataframe.\n '''\n\n df = pd.read_csv(GEO)\n df = df.drop(['Match Score','AddressID'],axis=1)\n\n return df\n\n\ndef read_contracts():\n '''\n Reads in the contracts with headquarter addresses. Returns a dataframe.\n '''\n\n df = pd.read_csv(HQ)\n\n return df\n\n\ndef sum_amounts(df):\n '''\n Takes in a dataframe. Adds a column with the sum of the amounts by vendor\n ID. Returns a dataframe.\n '''\n\n summer = df.groupby('CSDS_Vendor_ID')['Amount'].sum()\n summer = summer.to_frame().reset_index()\n\n df = df.merge(summer,how='right')\n\n return df\n\n\ndef merge():\n '''\n Reads in the geocoded headquarter addresses and the contracts. Gets the sum\n of amounts by vendor ID. Merges the dataframes together and returns a\n dataframe.\n '''\n\n geo = read_geo()\n\n contracts = read_contracts()\n summed = sum_amounts(contracts)\n\n df = summed.merge(geo)\n\n return df[['Amount','CSDS_Vendor_ID','Address','City','State','Zip',\n 'Longitude','Latitude','VendorName']]\n\n\nif __name__ == '__main__':\n\n merged = merge()\n merged.to_csv(MAP1,index=False)\n","sub_path":"PCNO/map1.py","file_name":"map1.py","file_ext":"py","file_size_in_byte":1507,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"9579081","text":"import concurrent.futures as cf\nfrom tkinter import *\nfrom classes.OverallProperties import OverallProperties\nfrom classes.Result import Result\nfrom classes.GUI import GUI\nfrom classes.Plot import Plot\nfrom tkinter import messagebox\n\nMAX_PROCESSES = 3\nMAX_THREADS = 2 # per process\nCHUNKSIZE = 1\n\n\ndef thread_worker(result):\n result,overallProperties = result\n\n if(OverallProperties):\n pass\n result.getResult(overallProperties.amount_of_graphs,\n overallProperties.graph_choice,\n overallProperties.link_loss_choise,\n overallProperties.srgg_distribution_choise,\n overallProperties.time_steps,\n overallProperties.lambd_l_l,\n overallProperties.mu_l_l,\n overallProperties.sigma_l_l,\n overallProperties.lambd_srgg,\n overallProperties.mu_srgg,\n overallProperties.sigma_srgg,\n overallProperties.scenario,\n overallProperties.coverage_type)\n return (result.id, result)\n\n\ndef process_worker(results):\n\n with cf.ThreadPoolExecutor(max_workers=MAX_THREADS) as t:\n result = list(t.map(thread_worker, results))\n return result\n\n\nif __name__ == \"__main__\":\n def start(amount_graphs,\n amount_nodes,\n coverage_radius,\n graph_choice,\n link_loss_choise,\n srgg_distribution_choise,\n timesteps,\n lambd_l_l,\n mu_l_l,\n sigma_l_l,\n lambd_srgg,\n mu_srgg,\n sigma_srgg,\n scenario,\n coverage_type):\n overallProperties = OverallProperties(amount_graphs,\n amount_nodes,\n coverage_radius,\n graph_choice,\n link_loss_choise,\n srgg_distribution_choise,\n timesteps,\n lambd_l_l,\n mu_l_l,\n sigma_l_l,\n lambd_srgg,\n mu_srgg,\n sigma_srgg,\n scenario,\n coverage_type)\n node_amount_coverage_combinations = list(\n (a, b) for a in overallProperties.amount_nodes for b in overallProperties.coverage_radii)\n\n results = [(Result(i, amount_nodes, coverage_radius),overallProperties) for i, (amount_nodes, coverage_radius) in\n enumerate(node_amount_coverage_combinations)]\n\n assert all(results[i][0].id == i for i in range(len(results)))\n\n with cf.ProcessPoolExecutor(max_workers=MAX_PROCESSES) as p:\n for result_list in p.map(process_worker,\n (results[i: i + CHUNKSIZE] for i in range(0, len(results), CHUNKSIZE))):\n for id, result in result_list:\n results[id] = result\n\n assert all(results[i].id == i for i in range(len(results)))\n\n multi_result_dict = {}\n print('build dict')\n for node_amount in overallProperties.amount_nodes:\n multi_result_dict[node_amount] = {}\n for coverage_radius in overallProperties.coverage_radii:\n multi_result_dict[node_amount][coverage_radius] = None\n print('results')\n for result in results:\n multi_result_dict[result.graph_properties['amount_nodes']][\n result.graph_properties['coverage_radius']] = result\n\n print(multi_result_dict)\n overallProperties.multi_result_dict = multi_result_dict\n overallProperties.dump_multi_result_obj_as_json()\n\n multi_obj = overallProperties.multi_result_dict[350][0.225]\n Plot(image_type='png').plot_graph_time_behavior((350,0.225),multi_obj.analysis_list)\n #overallProperties.plot_amount_nodes_comparison()\n\n messagebox.showinfo('Done', 'Finished computation')\n\n root = Tk()\n gui = GUI(root)\n\n gui.build_label(\"Amount of graphs:\", row=1)\n amount_graphs_field = gui.build_input(0, \"20\", row=1, col=1)\n\n gui.build_label(\"Amount of nodes per graph:\", row=2)\n amount_nodes_field = gui.build_input(1, \"100,150,200,250,300,350\", row=2, col=1)\n\n gui.build_label(\"Node coverage radius\", row=3)\n coverage_radius_field = gui.build_input(2, \"0.2\", row=3, col=1)\n\n gui.build_label(\"Number of timesteps:\", row=4)\n timesteps_field = gui.build_input(3, \"1\", row=4, col=1)\n\n gui.build_label(\"Choose type of graph:\", row=5)\n gui.build_radio_buttons(gui.graph_type, gui.graph_types, gui.get_graph_choice())\n\n row = 4 + len(gui.graph_types) + 1\n\n probability_fields = gui.build_probability_radio_button_section()\n\n gui.build_label(\"Choose graph scenario:\", row=1, col=4)\n gui.build_radio_buttons(gui.scenario, gui.scenarios, gui.get_scenario(), col=4, row = 1)\n\n row_col_4 = 2 + len(gui.scenarios)\n gui.build_label(\"Choose coverage type:\", row=row_col_4, col=4)\n gui.build_radio_buttons(gui.coverage_type, gui.coverage_types, gui.get_coverage_type(), col=4, row=row_col_4)\n\n Button(root, text='Start', width=20, command=lambda: start(gui.get_amount_graphs(amount_graphs_field),\n gui.get_amount_nodes(amount_nodes_field),\n gui.get_coverage_radius(coverage_radius_field),\n gui.get_graph_choice(),\n gui.get_link_loss_choice(),\n gui.get_srgg_distribution_choice(),\n int(gui.get_timesteps(timesteps_field)),\n int(gui.get_lambda_l_l(probability_fields[0])),\n float(gui.get_mu_l_l(probability_fields[1])),\n float(gui.get_sigma_l_l(probability_fields[2])),\n int(gui.get_lambda_srgg(probability_fields[3])),\n float(gui.get_mu_srgg(probability_fields[4])),\n float(gui.get_sigma_srgg(probability_fields[5])),\n gui.get_scenario(),\n gui.get_coverage_type())).grid(\n pady=4,\n padx=5,\n column=5)\n\n Button(root, text='Quit', width=20, command=root.quit).grid(\n pady=4,\n padx=5,\n column=5)\n\n mainloop()\n","sub_path":"main_gui.py","file_name":"main_gui.py","file_ext":"py","file_size_in_byte":7298,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"341620196","text":"from wagtail.contrib.modeladmin.options import (\n ModelAdmin,\n ModelAdminGroup,\n modeladmin_register,\n)\nfrom wagtailorderable.modeladmin.mixins import OrderableMixin\n\nfrom rca.programmes.models import DegreeLevel, ProgrammeType, Subject\n\n\nclass DegreeLevelModelAdmin(ModelAdmin):\n model = DegreeLevel\n menu_icon = \"tag\"\n\n\nclass SubjectModelAdmin(ModelAdmin):\n model = Subject\n menu_icon = \"tag\"\n\n\nclass ProgrammeTypeModelAdmin(OrderableMixin, ModelAdmin):\n model = ProgrammeType\n menu_icon = \"tag\"\n ordering = [\"sort_order\"]\n\n\nclass TaxonomiesModelAdminGroup(ModelAdminGroup):\n menu_label = \"Taxonomies\"\n items = (DegreeLevelModelAdmin, ProgrammeTypeModelAdmin, SubjectModelAdmin)\n menu_icon = \"tag\"\n\n\nmodeladmin_register(TaxonomiesModelAdminGroup)\n","sub_path":"rca/utils/wagtail_hooks.py","file_name":"wagtail_hooks.py","file_ext":"py","file_size_in_byte":788,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"461099736","text":"#https://xlinux.nist.gov/dads/HTML/bag.html aka bag\n#http://web.engr.oregonstate.edu/~sinisa/courses/OSU/CS261/CS261_Textbook/Chapter08.pdf\nfrom collections import defaultdict\n\n\nclass multiset():\n def __init__(self):\n self.data = defaultdict(lambda: 0)\n self._size = 0\n\n def add(self, val):\n self.data[val] += 1\n self._size += 1\n\n def size(self, val='all'):\n if val == 'all':\n return self._size\n return self.data[val]\n\n def contain(self, val):\n if self.data[val]:\n return True\n return False\n\n def remove(self, val):\n self._size -= self.data[val]\n del self.data[val]\n\n\nif __name__ == \"__main__\":\n test = multiset()\n test.add(1)\n test.add(2)\n test.add(1)\n assert test.size() == 3\n assert test.size(1) == 2\n assert test.contain(3) == False\n test.remove(2)\n assert test.contain(2) == False","sub_path":"abstract data type/python/multiset/multiset.py","file_name":"multiset.py","file_ext":"py","file_size_in_byte":919,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"587587679","text":"from __future__ import annotations\n\nimport asyncio\nimport contextlib\nimport socket\nfrom dataclasses import dataclass\nfrom ipaddress import IPv4Address, IPv6Address\nfrom typing import Union, cast\n\nimport zeroconf\nimport zeroconf.asyncio\n\nfrom .core import APIConnectionError, ResolveAPIError\n\nZeroconfInstanceType = Union[zeroconf.Zeroconf, zeroconf.asyncio.AsyncZeroconf, None]\n\n\n@dataclass(frozen=True)\nclass Sockaddr:\n pass\n\n\n@dataclass(frozen=True)\nclass IPv4Sockaddr(Sockaddr):\n address: str\n port: int\n\n\n@dataclass(frozen=True)\nclass IPv6Sockaddr(Sockaddr):\n address: str\n port: int\n flowinfo: int\n scope_id: int\n\n\n@dataclass(frozen=True)\nclass AddrInfo:\n family: int\n type: int\n proto: int\n sockaddr: Sockaddr\n\n\nasync def _async_zeroconf_get_service_info(\n zeroconf_instance: ZeroconfInstanceType,\n service_type: str,\n service_name: str,\n timeout: float,\n) -> \"zeroconf.ServiceInfo\" | None:\n # Use or create zeroconf instance, ensure it's an AsyncZeroconf\n if zeroconf_instance is None:\n try:\n zc = zeroconf.asyncio.AsyncZeroconf()\n except Exception:\n raise ResolveAPIError(\n \"Cannot start mDNS sockets, is this a docker container without \"\n \"host network mode?\"\n )\n do_close = True\n elif isinstance(zeroconf_instance, zeroconf.asyncio.AsyncZeroconf):\n zc = zeroconf_instance\n do_close = False\n elif isinstance(zeroconf_instance, zeroconf.Zeroconf):\n zc = zeroconf.asyncio.AsyncZeroconf(zc=zeroconf_instance)\n do_close = False\n else:\n raise ValueError(\n f\"Invalid type passed for zeroconf_instance: {type(zeroconf_instance)}\"\n )\n\n try:\n info = await zc.async_get_service_info(\n service_type, service_name, int(timeout * 1000)\n )\n except Exception as exc:\n raise ResolveAPIError(\n f\"Error resolving mDNS {service_name} via mDNS: {exc}\"\n ) from exc\n finally:\n if do_close:\n await zc.async_close()\n return info\n\n\nasync def _async_resolve_host_zeroconf(\n host: str,\n port: int,\n *,\n timeout: float = 3.0,\n zeroconf_instance: ZeroconfInstanceType = None,\n) -> list[AddrInfo]:\n service_type = \"_esphomelib._tcp.local.\"\n service_name = f\"{host}.{service_type}\"\n\n info = await _async_zeroconf_get_service_info(\n zeroconf_instance, service_type, service_name, timeout\n )\n\n if info is None:\n return []\n\n addrs: list[AddrInfo] = []\n for raw in info.addresses_by_version(zeroconf.IPVersion.All):\n is_ipv6 = len(raw) == 16\n sockaddr: Sockaddr\n if is_ipv6:\n sockaddr = IPv6Sockaddr(\n address=socket.inet_ntop(socket.AF_INET6, raw),\n port=port,\n flowinfo=0,\n scope_id=0,\n )\n else:\n sockaddr = IPv4Sockaddr(\n address=socket.inet_ntop(socket.AF_INET, raw),\n port=port,\n )\n\n addrs.append(\n AddrInfo(\n family=socket.AF_INET6 if is_ipv6 else socket.AF_INET,\n type=socket.SOCK_STREAM,\n proto=socket.IPPROTO_TCP,\n sockaddr=sockaddr,\n )\n )\n return addrs\n\n\nasync def _async_resolve_host_getaddrinfo(host: str, port: int) -> list[AddrInfo]:\n try:\n # Limit to TCP IP protocol and SOCK_STREAM\n res = await asyncio.get_event_loop().getaddrinfo(\n host, port, type=socket.SOCK_STREAM, proto=socket.IPPROTO_TCP\n )\n except OSError as err:\n raise APIConnectionError(f\"Error resolving IP address: {err}\")\n\n addrs: list[AddrInfo] = []\n for family, type_, proto, _, raw in res:\n sockaddr: Sockaddr\n if family == socket.AF_INET:\n raw = cast(tuple[str, int], raw)\n address, port = raw\n sockaddr = IPv4Sockaddr(address=address, port=port)\n elif family == socket.AF_INET6:\n raw = cast(tuple[str, int, int, int], raw)\n address, port, flowinfo, scope_id = raw\n sockaddr = IPv6Sockaddr(\n address=address, port=port, flowinfo=flowinfo, scope_id=scope_id\n )\n else:\n # Unknown family\n continue\n\n addrs.append(\n AddrInfo(family=family, type=type_, proto=proto, sockaddr=sockaddr)\n )\n return addrs\n\n\ndef _async_ip_address_to_addrs(host: str, port: int) -> list[AddrInfo]:\n \"\"\"Convert an ipaddress to AddrInfo.\"\"\"\n with contextlib.suppress(ValueError):\n return [\n AddrInfo(\n family=socket.AF_INET6,\n type=socket.SOCK_STREAM,\n proto=socket.IPPROTO_TCP,\n sockaddr=IPv6Sockaddr(\n address=str(IPv6Address(host)), port=port, flowinfo=0, scope_id=0\n ),\n )\n ]\n\n with contextlib.suppress(ValueError):\n return [\n AddrInfo(\n family=socket.AF_INET,\n type=socket.SOCK_STREAM,\n proto=socket.IPPROTO_TCP,\n sockaddr=IPv4Sockaddr(\n address=str(IPv4Address(host)),\n port=port,\n ),\n )\n ]\n\n return []\n\n\nasync def async_resolve_host(\n host: str,\n port: int,\n zeroconf_instance: ZeroconfInstanceType = None,\n) -> AddrInfo:\n addrs: list[AddrInfo] = []\n\n zc_error = None\n if host.endswith(\".local\"):\n name = host[: -len(\".local\")]\n try:\n addrs.extend(\n await _async_resolve_host_zeroconf(\n name, port, zeroconf_instance=zeroconf_instance\n )\n )\n except APIConnectionError as err:\n zc_error = err\n\n if not addrs:\n addrs.extend(_async_ip_address_to_addrs(host, port))\n\n if not addrs:\n addrs.extend(await _async_resolve_host_getaddrinfo(host, port))\n\n if not addrs:\n if zc_error:\n # Only show ZC error if getaddrinfo also didn't work\n raise zc_error\n raise ResolveAPIError(f\"Could not resolve host {host} - got no results from OS\")\n\n # Use first matching result\n # Future: return all matches and use first working one\n return addrs[0]\n","sub_path":"aioesphomeapi/host_resolver.py","file_name":"host_resolver.py","file_ext":"py","file_size_in_byte":6354,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"450418189","text":"H,W = map(int,input().split())\n\nINF = 10000000000\n\ngrid = [[\".\" for _ in range(W+1)]]\n\nfor _ in range(H):\n in_list = list(\".\" + input())\n grid.append(in_list)\n\n# dp[i][j] = x x: これまでに何ブロックあったか\ndp = [[INF for _ in range(W+1)] for _ in range(H+1)]\ndp[1][0] = 0\ndp[0][1] = 0\n\n\n# if grid[0][0] = \"#\":\n# dp[0][0] = 1\n# else:\n# dp[0][0] = 0\n\nfor j in range(1,W+1):\n for i in range(1,H+1):\n if grid[i][j] == \".\": # 白の場合\n dp[i][j] = min(dp[i-1][j],dp[i][j-1])\n else: # 黒の場合\n # route_top\n if grid[i-1][j] == \"#\": # 上も黒ならそのまあ\n route_top = dp[i-1][j]\n else:\n route_top = dp[i-1][j] + 1\n\n # route_left\n if grid[i][j-1] == \"#\": # 上も黒ならそのまあ\n route_left = dp[i][j-1]\n else:\n route_left = dp[i][j-1] + 1\n \n dp[i][j] = min(route_top,route_left)\nprint(dp[-1][-1])","sub_path":"AtCoder/AGC/2020031_AGC/a.py","file_name":"a.py","file_ext":"py","file_size_in_byte":1015,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"166527749","text":"import json\nimport requests\nfrom bs4 import BeautifulSoup\nimport datetime\n\n\nbase_url = 'https://habr.com/ru/news/'\nanother_url = 'https://arstechnica.com/gadgets/'\ncurrent = datetime.datetime.now()\ncreation_date = current.strftime(\"%d-%m-%y\")\njpath = 'articles.json'\n\n\ndef get_html_page(url):\n news_request = requests.get(url)\n news_content = news_request.text\n return news_content\n\n\ndef find_articles(html_page):\n parsed_page = BeautifulSoup(html_page, 'html.parser')\n headings = parsed_page.find_all('a', class_='post__title_link')\n quantity = len(headings)\n title_list = list()\n for i in range(quantity):\n title_list.append(headings[i].text)\n return title_list\n\n\ndef find_another_articles(html_page):\n parsed_page = BeautifulSoup(html_page, 'html.parser')\n headings = parsed_page.find_all('h2')\n quantity = len(headings)\n title_list = list()\n for i in range(quantity):\n title_list.append(headings[i].text)\n return title_list\n\n\ndef publish_report(path, articles, another_articles):\n articles_dict = []\n another_articles_dict = []\n for i in range(len(articles)):\n articles_dict.append({\"title\": articles[i]})\n for j in range(len(another_articles)):\n another_articles_dict.append({\"title\": another_articles[j]})\n titles = {\n \"creationDate\": creation_date,\n \"habrUrl\": base_url,\n \"habrArticles\": articles_dict,\n \"arsUrl\": another_url,\n \"arsArticles\": another_articles_dict\n }\n\n with open(path, 'w', encoding='utf-8') as file:\n json.dump(titles, file, indent=2, ensure_ascii=False)\n\n\nif __name__ == '__main__':\n publish_report(jpath, find_articles(get_html_page(base_url)), find_another_articles(get_html_page(another_url)))\n\n","sub_path":"requests_prep_kis_yu.py","file_name":"requests_prep_kis_yu.py","file_ext":"py","file_size_in_byte":1763,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"198611621","text":"import pymatgen as mg\r\n\r\nimport numpy as np\r\nimport math\r\nimport os\r\n\r\nfull_structure = mg.Structure.from_file(os.path.dirname(__file__)+\"/YSO.cif\")\r\n\r\nstructure = mg.Structure.from_file(os.path.dirname(__file__)+\"/YSO.cif\")\r\nstructure.remove_species([\"O\"])\r\n#print(structure)\r\ng_g = np.matrix(\"3.070 -3.124 3.396; -3.124 8.156 -5.756; 3.396 -5.756 5.787\")\r\ng_gII = np.matrix(\"3.070 -3.124 -3.396; -3.124 8.156 5.756; -3.396 5.756 5.787\")\r\ng_e = np.matrix(\"1.950 -2.212 3.584; -2.212 4.232 -4.986; 3.584 -4.986 7.888\")\r\ng_eII = np.matrix(\"1.950 -2.212 -3.584; -2.212 4.232 4.986; -3.584 4.986 7.888\")\r\n\r\ng_g2 = np.matrix(\"14.651 -2.115 2.552; -2.115 1.965 -0.550; 2.552 -0.550 0.902\")\r\ng_g2II = np.matrix(\"14.651 -2.115 -2.552; -2.115 1.965 0.550; -2.552 0.550 0.902\")\r\ng_e2 = np.matrix(\"12.032 -0.582 4.518; -0.582 0.212 -0.296; 4.518 -0.296 1.771\")\r\ng_e2II = np.matrix(\"12.032 -0.582 -4.518; -0.582 0.212 0.296; -4.518 0.296 1.771\")\r\n\r\n\r\ndef xyz_to_D1D2b(xyz, rot=None):\r\n \"\"\" Transform from (x,y,z) cartesian coordinates in pymatgen.structure\r\n to (D1,D2,b) coordinates. \r\n - rot: rotation matrix (such that D1D2b = rot.xyz)\r\n as a default, use rotation matrix for YSO \"\"\"\r\n \r\n if hasattr(xyz, \"__iter__\") and type(xyz[0]) in [list,np.ndarray]:\r\n return [xyz_to_D1D2b(xyz_vec) for xyz_vec in xyz]\r\n \r\n if rot is None:\r\n # the original (y,z) coordinate axes are aligned with the (b,c) crystal axes,\r\n # but between D1 and c there is an angle of 102.65-78.7 deg. \r\n c_D1 = -(102.65-78.7) * np.pi/180\r\n rot = np.matrix([\r\n [-np.sin(c_D1), np.cos(c_D1), 0],\r\n [0,0,1],\r\n [np.cos(c_D1), np.sin(c_D1), 0]\r\n ]).getT()\r\n \r\n if type(xyz) is list or xyz.shape == (3,):\r\n return np.array(rot.dot(np.matrix(xyz).getT()))[:,0]\r\n elif xyz.shape == (3,1):\r\n return rot.dot(xyz)\r\n elif xyz.shape == (1,3):\r\n return (rot.dot(xyz.getT())).getT()\r\n raise Exception(\"Warning: could not transform xyz vector of shape {}!\".format(xyz.shape))\r\n\r\n\r\n\r\ndef abc_to_xyz(abc, struc=None):\r\n \"\"\" Transform fractional coordinates (a,b,c) to cartesian coordinates (x,y,z). \r\n By default, (y,z) are aligned with the (b,c) crystal axes. \"\"\"\r\n \r\n if hasattr(abc, \"__iter__\") and type(abc[0]) in [list,np.ndarray]:\r\n return [abc_to_xyz(abc_vec) for abc_vec in abc]\r\n \r\n if type(abc) is list or abc.shape == (3,) or abc.shape== (1,3):\r\n return structure.lattice.get_cartesian_coords(abc)\r\n elif abc.shape == (3,1):\r\n return structure.lattice.get_cartesian_coords(abc.getT()).getT()\r\n raise Exception(\"Warning: could not transform abc vector of shape {}!\".format(abc.shape))\r\n\r\n\r\ndef abc_to_D1D2b(abc, struc=None):\r\n \"\"\" Transform fractional coordinates (a,b,c) to cartesian coordinates (D1,D2,b). \"\"\"\r\n \r\n if hasattr(abc, \"__iter__\") and type(abc[0]) in [list,np.ndarray]:\r\n return [abc_to_D1D2b(abc_vec) for abc_vec in abc]\r\n \r\n xyz = abc_to_xyz(abc, struc=struc)\r\n D1D2b = xyz_to_D1D2b(xyz)\r\n return D1D2b\r\n\r\n\r\ndef D1D2b_to_thetaphi(D1D2b):\r\n \"\"\" Transform (D1,D2,b) coordinates to angles (theta,phi)\r\n with polar angle theta (from b) and azimuthal angle phi (in D1-D2 plane, from D1). \"\"\"\r\n \r\n if hasattr(D1D2b, \"__iter__\") and type(D1D2b[0]) in [list,np.ndarray,np.matrix] \\\r\n and type(D1D2b) not in [np.matrix]:\r\n angles = np.zeros([len(D1D2b),2])\r\n for i,vec in enumerate(D1D2b):\r\n angles[i] = D1D2b_to_thetaphi(vec)\r\n return angles\r\n \r\n if type(D1D2b) is list or np.shape(D1D2b) == (3,):\r\n D1D2b = np.matrix(D1D2b).getT()\r\n elif np.shape(D1D2b) == (1,3):\r\n D1D2b = D1D2b.getT()\r\n \r\n r_vec = D1D2b / np.linalg.norm(D1D2b)\r\n x,y,z = [r_vec[0,0],r_vec[1,0],r_vec[2,0]]\r\n \r\n theta = math.acos(z) *180/np.pi\r\n phi = np.arctan2(y,x) *180/np.pi\r\n if phi < 0:\r\n phi += 360\r\n return (phi,theta)\r\n\r\n\r\n\r\ndef get_axis(D1=None, D2=None, b=None, phi=None, theta=None):\r\n \"\"\" Construct an axis vector (unity length). \r\n Either use (D1,D2,b) coordinates or (phi,theta) angles to specify the axis. \r\n - phi: azimuthal angle in deg (from D1)\r\n - theta: polar angle in deg (from b)\r\n Returns a column matrix (3,1)\r\n \"\"\"\r\n \r\n if None not in [D1,D2,b]:\r\n axis = np.matrix([[D1],[D2],[b]])\r\n axis = axis / np.linalg.norm(axis)\r\n return axis\r\n \r\n if None not in [phi,theta]:\r\n phi, theta = np.pi/180 * np.array([phi, theta])\r\n axis = np.matrix([[np.sin(theta)*np.cos(phi)],\r\n [np.sin(theta)*np.sin(phi)],\r\n [np.cos(theta)]])\r\n return axis\r\n \r\n raise Exception(\"Could not construct axis!\")\r\n\r\n\r\n\r\ndef find_Y_neighbour_vecs(max_distance, origin_site=None, shape=(3,1), return_distance=False, site_filter=None, structure=structure):\r\n \"\"\"Find all (Y) neighbours in the structure with a maximum distance. \r\n Returns list of (D1,D2,b) vectors, sorted by distance. \"\"\"\r\n if origin_site is None:\r\n origin_site = structure[0]\r\n \r\n neighbours = structure.get_neighbors(origin_site, max_distance)\r\n neighbours.sort(key=lambda n: n[1])\r\n if site_filter is not None:\r\n # assume that the site_filter requires a Site object, not a tuple (site, distance)\r\n neighbours = filter(lambda neighbour: site_filter(neighbour[0]), neighbours)\r\n \r\n r_vecs = []\r\n distances = []\r\n for i,n in enumerate(neighbours):\r\n neighbour_site, dist = n, i\r\n \r\n #r_vec = neighbour_site.coords - origin_site.coords\r\n \r\n r_vec = xyz_to_D1D2b(neighbour_site.coords) \\\r\n - xyz_to_D1D2b(origin_site.coords)\r\n r_vec = np.reshape(r_vec, shape)\r\n if len(shape) >= 2:\r\n r_vec = np.matrix(r_vec)\r\n r_vecs.append(r_vec)\r\n distances.append(dist)\r\n \r\n if return_distance:\r\n return r_vecs, distances\r\n return r_vecs\r\n\r\n\r\ndef which_site(site):\r\n \"\"\"Return (site, class) tuple for Y sites in YSO. \r\n e.g. (1,1) and (1,2) for site 1, classes I and II. \"\"\"\r\n \r\n r1, r2, r3 = find_Y_neighbour_vecs(max_distance=4, origin_site=site, shape=(3,))[0:3]\r\n \r\n chirality = int(np.dot(np.cross(r1,r2),r3))\r\n \r\n Y_site = 1 if np.abs(chirality) == 21 else 2\r\n \r\n #TODO I don't know if there is any convention which crystal sites are class I or class II.\r\n # Might be the other way round\r\n Y_class = 1 if chirality > 0 else 2\r\n \r\n return (Y_site, Y_class)","sub_path":"library/crystal/YSO_si.py","file_name":"YSO_si.py","file_ext":"py","file_size_in_byte":6649,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"243971535","text":"# import logging\nfrom datetime import date\nfrom pathlib import Path\n\nfrom miranda.eccc import aggregate_nc_files\nfrom miranda.utils import eccc_cf_daily_metadata\n\n# from functools import partial\n# from multiprocessing import Pool\n# from miranda.eccc import convert_daily_flat_files\n\nif __name__ == \"__main__\":\n\n var_codes = [\n 1,\n 2,\n 3,\n 10,\n 11,\n 12,\n 13,\n 14,\n 15,\n 16,\n 17,\n 18,\n 19,\n 20,\n 21,\n 22,\n 23,\n 24,\n 25,\n ]\n station_file = \"/home/tjs/Desktop/ec_data/Station Inventory EN.csv\"\n source_data = Path(\"/home/tjs/Desktop/ec_data/eccc_all\")\n #\n # func = partial(convert_daily_flat_files, source_data, source_data)\n # logging.info(func)\n #\n # p = Pool()\n # p.map(func, var_codes)\n # p.close()\n # p.join()\n\n # convert_daily_flat_files(\n # source_files=source_data, output_folder=source_data, variables=var_codes\n # )\n\n for var in var_codes:\n var_name = eccc_cf_daily_metadata(var)[\"nc_name\"]\n out_file = source_data.joinpath(\n \"eccc_daily_{}\".format(date.today().strftime(\"%Y%m%d\"))\n )\n aggregate_nc_files(\n source_files=source_data,\n output_file=out_file,\n variables=var,\n station_inventory=station_file,\n time_step=\"daily\",\n )\n","sub_path":"miranda/templates/eccc_raw_daily_conversion.py","file_name":"eccc_raw_daily_conversion.py","file_ext":"py","file_size_in_byte":1420,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"582281252","text":"import numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nfrom statsmodels.tsa.stattools import adfuller\nfrom statsmodels.graphics.tsaplots import plot_acf, plot_pacf\nfrom scipy.interpolate import lagrange\nfrom statsmodels.tsa.arima_model import ARMA,ARIMA\nfrom datetime import datetime\nimport statsmodels.api as sm\nfrom utils.mysql_util import *\n\n\ndef arma_predict(data):\n day_data = data.resample('1D').last()['x']\n # day_data.index = pd.to_datetime(day_data.index)\n # plt.plot(day_data.index.values,day_data.values)\n # plt.xticks(rotation=50)\n # plt.show()\n\n print(np.shape(day_data)[0])\n day_std = (day_data.std())\n day_mean = day_data.mean()\n\n # day_data.index.astype('0')\n dt = day_data.interpolate()\n # dt = day_data.fillna(method='ffill')\n # f = plt.figure(facecolor='white')\n # ax1 = f.add_subplot(211)\n # # plot_acf(dt, lags=31, ax=ax1)\n # ax2 = f.add_subplot(212)\n # plot_pacf(dt, lags=31, ax=ax2)\n # plt.show()\n # dftest = adfuller(dt)\n # print(dftest)\n\n\n pmax = int((dt.shape[0])/10) #一般阶数不超过length/10\n qmax = int((dt.shape[0])/10) #一般阶数不超过length/10\n\n # diff_num = 0\n # flag = True\n # while flag:\n # t = adfuller(dt.values)\n # if t[2] > 0.05:\n # flag = False\n\n order_A2 = sm.tsa.arma_order_select_ic(dt,ic='aic')['aic_min_order']\n\n\n df = dt[:-5,]\n model = ARIMA(df,(1,1,1)).fit()\n ans = model.predict(start=len(df),end=len(dt)-1)\n # ans = model.forecast(5)\n ans = ans.cumsum()+dt.values[len(df)-1]\n\n plt.plot(dt.index,dt.values,'r')\n # plt.plot(dt.index,ans[0],'g'\n plt.plot(ans.index,ans.values)\n plt.legend(['True','predict'])\n plt.xticks(rotation=50)\n plt.show()\n\n dt_diff = dt.diff(1)\n dt_diff.dropna(inplace=True)\n\n\n order_A2 = sm.tsa.arma_order_select_ic(dt,ic='aic')['aic_min_order']\n model_A2 = ARMA(dt_diff,order=order_A2)\n results_A2 = model_A2.fit()\n print(results_A2.forcast(3))\n #\n #\n prd = model_A2.predict(params=results_A2.params,start=1,end=len(dt_diff+10))\n # prd.cumsum(axis=1)\n res = pd.DataFrame(index=dt_diff.index.values,data=prd)\n diff_shift_ts = dt.shift(1)\n diff_shift_ts.dropna(inplace=True)\n diff_recover_1 = res.values.reshape(res.values.shape[0],1)+diff_shift_ts.values.reshape(res.values.shape[0],1)\n\n plt.figure(facecolor='white')\n\n plt.plot(diff_shift_ts.index,diff_recover_1,'r')\n plt.plot(dt.index,dt.values,'g')\n plt.show()\n from sklearn.metrics import mean_squared_error\n print(mean_squared_error(diff_recover_1,dt.values[:-1]))\n\n\nif __name__ == \"__main__\":\n sql = 'select recordTime as gps_time,offsetHeight as z,offsetEast as x,offsetNorth as y from' \\\n ' bdmc.dataGnss where mac = \"%s\" and recordTime > \"2019-6-16\"' % ('000300000079')\n # url = 'http://cloud.bdsmc.net:8006/devicedata?mac=%s&num=1500'%'000300000079'\n # data = pd.read_json(url).set_index('gps_time')\n data = pd.read_sql(sql, mysql_conn, index_col='gps_time')\n arma_predict(data)","sub_path":"main/back_arma_displacement_predict.py","file_name":"back_arma_displacement_predict.py","file_ext":"py","file_size_in_byte":3055,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"409686202","text":"from dealer.globals import *\nfrom dealer.dealer import Dealer\nfrom dealer.player_state import PlayerState\nfrom dealer.species import Species\nfrom dealer.traitcard import TraitCard\n\n\nclass Convert(object):\n \"\"\"\n Methods for converting between JSON input and Python objects\n \"\"\"\n def __init__(self):\n pass\n\n @classmethod\n def json_to_dealer(cls, json_config):\n \"\"\"\n Converts a JSON Configuration into a Dealer object\n :param json_config: A JSON Configuration as specified by the data definition at\n http://www.ccs.neu.edu/home/matthias/4500-s16/8.html\n :return: a Dealer object\n \"\"\"\n assert(len(json_config) == CONFIG_LENGTH)\n [json_lop, wh_food, json_deck] = json_config\n lop = [cls.json_to_player(json_player) for json_player in json_lop]\n deck = [cls.json_to_trait(trait_card) for trait_card in json_deck]\n dealer = Dealer(lop, wh_food, deck)\n dealer.validate_attributes()\n return dealer\n\n @classmethod\n def dealer_to_json(cls, dealer):\n \"\"\"\n Converts a Dealer object into a JSON Configuration\n :param dealer: a Dealer object\n :return: a JSON Configuration as specified by the data definition at\n http://www.ccs.neu.edu/home/matthias/4500-s16/8.html\n \"\"\"\n dealer.validate_attributes()\n json_players = [cls.player_to_json(player) for player in dealer.list_of_players]\n json_deck = [cls.trait_to_json(trait_card) for trait_card in dealer.deck]\n return [json_players, dealer.watering_hole, json_deck]\n\n @classmethod\n def json_to_feeding(cls, json_feeding):\n \"\"\"\n Converts a JSON Feeding into a Python representation of a Feeding\n :param json_feeding: a Feeding as specified by the data definition at\n http://www.ccs.neu.edu/home/matthias/4500-s16/6.html\n :return: [PlayerState, Natural+, [PlayerState,...]] representing the attacking PlayerState,\n the available watering hole food, and the PlayerStates of other players in the game\n \"\"\"\n assert(len(json_feeding) == FEEDING_LENGTH)\n [json_player, wh_food, json_lop] = json_feeding\n assert(wh_food > MIN_WATERING_HOLE)\n player = cls.json_to_player(json_player)\n other_players = [cls.json_to_player(op) for op in json_lop]\n return [player, wh_food, other_players]\n\n @classmethod\n def json_to_player(cls, json_player):\n \"\"\"\n Converts a JSON Player+ to a PlayerState\n :param json_player: a JSON Player+ as specified by the data definition at\n http://www.ccs.neu.edu/home/matthias/4500-s16/8.html\n :return: a PlayerState object\n \"\"\"\n gdict = globals()\n if len(json_player) == PLAYER_LENGTH:\n [[gdict[ID], player_id], [gdict[SPECIES], json_los], [gdict[BAG], food_bag]] = json_player\n cards = []\n else:\n [[gdict[ID], player_id], [gdict[SPECIES], json_los],\n [gdict[BAG], food_bag], [gdict[CARDS], cards]] = json_player\n\n player_species = [cls.json_to_species(json_species) for json_species in json_los]\n player_hand = [cls.json_to_trait(trait_card) for trait_card in cards]\n player_obj = PlayerState(name=player_id, hand=player_hand, food_bag=food_bag, species=player_species)\n player_obj.validate_attributes()\n return player_obj\n\n @classmethod\n def player_to_json(cls, player):\n \"\"\"\n Converts a PlayerState to a JSON Player+. Does not render empty hands.\n :param player: a PlayerState object\n :return: a JSON Player+ as specified by the data definition at\n http://www.ccs.neu.edu/home/matthias/4500-s16/8.html\n \"\"\"\n player.validate_attributes()\n json_species = [cls.species_to_json(species_obj) for species_obj in player.species]\n json_hand = [cls.trait_to_json(trait_card) for trait_card in player.hand]\n json_player = [[ID, player.name], [SPECIES, json_species], [BAG, player.food_bag]]\n if json_hand:\n json_player.append([CARDS, json_hand])\n return json_player\n\n\n @classmethod\n def json_to_species(cls, json_species):\n \"\"\"\n Converts a JSON Species+ into a Species.\n :param json_species: a JSON Species+ as specified by the data definition at\n http://www.ccs.neu.edu/home/matthias/4500-s16/6.html\n :return: a Species object\n \"\"\"\n gdict = globals()\n if len(json_species) == SPECIES_LENGTH:\n [[gdict[FOOD], species_food], [gdict[BODY], species_body], [gdict[POPULATION], species_pop],\n [gdict[TRAITS], json_species_traits]] = json_species\n fat_food = False\n else:\n [[gdict[FOOD], species_food], [gdict[BODY], species_body], [gdict[POPULATION], species_pop],\n [gdict[TRAITS], json_species_traits], [gdict[FATFOOD], fat_food]] = json_species\n\n species_traits = [cls.json_to_trait(trait) for trait in json_species_traits]\n species_obj = Species(species_pop, species_food, species_body, species_traits, fat_food)\n species_obj.validate_attributes()\n return species_obj\n\n @classmethod\n def species_to_json(cls, species_obj):\n \"\"\"\n Converts a Species object into a JSON Species+. Does not render empty fat-food.\n :param species_obj: a Species object\n :return: a JSON Species+ as specified by the data definition at\n http://www.ccs.neu.edu/home/matthias/4500-s16/6.html\n \"\"\"\n species_obj.validate_attributes()\n json_traits = [cls.trait_to_json(trait) for trait in species_obj.traits]\n json_species = [[FOOD, species_obj.food], [BODY, species_obj.body],\n [POPULATION, species_obj.population], [TRAITS, json_traits]]\n if species_obj.fat_storage:\n json_species.append([FATFOOD, species_obj.fat_storage])\n return json_species\n\n @classmethod\n def json_to_trait(cls, json_trait):\n \"\"\"\n Converts a JSON Trait or SpeciesCard into a TraitCard\n :param json_trait: a JSON Trait or SpeciesCard as specified by the data definitions at\n http://www.ccs.neu.edu/home/matthias/4500-s16/5.html and\n http://www.ccs.neu.edu/home/matthias/4500-s16/8.html, respectively.\n :return: a TraitCard object\n \"\"\"\n if isinstance(json_trait, basestring):\n [food, trait] = [False, json_trait]\n else:\n [food, trait] = json_trait\n trait_card = TraitCard(trait, food)\n trait_card.validate_attributes()\n return trait_card\n\n @classmethod\n def trait_to_json(cls, trait_card):\n \"\"\"\n Converts a TraitCard into a JSON Trait or SpeciesCard\n :param trait_card: a TraitCard object\n :return: a JSON Trait or SpeciesCard as specified by the data definitions at\n http://www.ccs.neu.edu/home/matthias/4500-s16/5.html and\n http://www.ccs.neu.edu/home/matthias/4500-s16/8.html, respectively.\n \"\"\"\n trait_card.validate_attributes()\n return trait_card.trait if trait_card.food_points is False else [trait_card.food_points, trait_card.trait]\n","sub_path":"10/convert.py","file_name":"convert.py","file_ext":"py","file_size_in_byte":7387,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"383259662","text":"# coding: utf-8\n\nDEBUG = True\n\nTEMPLATE_DEBUG = DEBUG\n\n\nDATABASES = {\n 'default': {\n 'ENGINE': 'django.db.backends.sqlite3',\n 'NAME': '/home/alex/42-test.sqlite3',\n }\n}\n\n\n# SwampDragon settings\nDRAGON_URL = 'http://localhost:9999/'\n\n# CorsHeaders settings\nCORS_ORIGIN_WHITELIST = ('localhost:3000',)\n","sub_path":"docs/local.py","file_name":"local.py","file_ext":"py","file_size_in_byte":320,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"564049452","text":"from __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport os\nimport shutil\nimport subprocess\nimport utils\nimport argparse\nimport pretty_midi\n\n# find midi files in INPUT_DIR, and align it using Nakamura's alignment tool.\n# (https://midialignment.github.io/demo.html)\n# midi.mid in same subdirectory will be regarded as score file.\n# make alignment result files in same directory. read Nakamura's manual for detail.\n\nINPUT_DIR = '/home/ilcobo2/chopin'\n\nparser = argparse.ArgumentParser()\nparser.add_argument(\"--input_dir\", default=INPUT_DIR,\n help=\"Abs path to midi folder\")\nparser.add_argument(\"--align_dir\", default='/home/ilcobo2/AlignmentTool_v2',\n help=\"Abs path to Nakamura's Alignment tool\")\nargs = parser.parse_args()\n\n\nos.chdir(args.align_dir)\n\n'''\n# read from text list\nf = open('temp_fix.txt', 'rb')\nlines = f.readlines()\nf.close()\nmidi_files = [el.strip() for el in lines]\n'''\n\n# read from folder\nmidi_files = utils.find_files_in_subdir(INPUT_DIR, '*.mid')\n\nn_match = 0\nn_unmatch = 0\nfor midi_file in midi_files:\n if 'midi.mid' in midi_file or 'XP.mid' in midi_file:\n continue\n\n if 'Chopin_Etude_op_25/10/KOLESO02.mid' in midi_file:\n continue\n\n if os.path.isfile(midi_file.replace('.mid', '_infer_corresp.txt')):\n n_match += 1\n continue\n\n file_folder, file_name = utils.split_head_and_tail(midi_file)\n perform_midi = midi_file\n score_midi = os.path.join(file_folder, 'midi.mid')\n print(perform_midi)\n print(score_midi)\n\n mid = pretty_midi.PrettyMIDI(score_midi)\n\n n_notes = len(mid.instruments[0].notes)\n\n '''\n if n_notes >= 8000:\n n_unmatch +=1\n continue\n '''\n\n shutil.copy(perform_midi, os.path.join(args.align_dir, 'infer.mid'))\n shutil.copy(score_midi, os.path.join(args.align_dir, 'score.mid'))\n\n try:\n subprocess.check_call([\"sudo\", \"sh\", \"MIDIToMIDIAlign.sh\", \"score\", \"infer\"])\n except:\n print('Error to process {}'.format(midi_file))\n pass\n else:\n shutil.move('infer_corresp.txt', midi_file.replace('.mid', '_infer_corresp.txt'))\n shutil.move('infer_match.txt', midi_file.replace('.mid', '_infer_match.txt'))\n shutil.move('infer_spr.txt', midi_file.replace('.mid', '_infer_spr.txt'))\n shutil.move('score_spr.txt', os.path.join(args.align_dir, '_score_spr.txt'))\nprint('match:{:d}, unmatch:{:d}'.format(n_match, n_unmatch))\n\n\n","sub_path":"copy_and_align.py","file_name":"copy_and_align.py","file_ext":"py","file_size_in_byte":2486,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"60591388","text":"########################################################################################################################\n# 1. Поработайте с переменными, создайте несколько, выведите на экран, запросите у пользователя несколько чисел и строк\n# и сохраните в переменные, выведите на экран.\n########################################################################################################################\n\n# Узнаем имя пользователя. Попросим ввести два числа и выведем сумму этих чисел.\n\nname = input('Как Вас зовут? ')\nn1 = int(input('Отлично, {}. Введите первое число: ' .format(name)))\nn2 = int(input('Введите второе число: '))\nsum = n1 + n2\nprint('{}, Вы ввели числа {} и {}.\\n {} + {} = {}' .format(name, n1, n2, n1, n2, sum))\n","sub_path":"HW_1/HW_1_T_1.py","file_name":"HW_1_T_1.py","file_ext":"py","file_size_in_byte":1001,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"190230719","text":"import sys\nsys.path.insert(0, '../')\nfrom model import TextCNN\nimport torch\nimport torch.autograd as autograd\nimport torch.nn as nn\nimport torch.optim as optim\nimport torch.nn.functional as F\nimport argparse\nfrom torch.utils.data import DataLoader\nimport time\nfrom tool.data_loader import build_vocab\nfrom tool.data_loader import load_vocab\nfrom tool.data_loader import TextDataSet\nfrom torch.utils.tensorboard import SummaryWriter\nimport os, glob, shutil\n\nparser = argparse.ArgumentParser()\nparser.add_argument('--lr', type=float, default=0.001)\nparser.add_argument('--batch_size', type=int, default=32)\nparser.add_argument('--epoch', type=int, default=100)\nparser.add_argument('--filter_count', type=int, default=128)\nparser.add_argument('--seed', type=int, default=1992)\nparser.add_argument('--embedding_dim', type=int, default=300)\nparser.add_argument('--embedding_droprate', type=float, default=0.5)\nparser.add_argument('--sequence_len', type=int, default=64)\nparser.add_argument('--kernel_size', type=list, nargs='+', default=[2,3,4])\nparser.add_argument('--conv_droprate', type=float, default=0.5)\nparser.add_argument('--train', type=str, default='train.txt')\nparser.add_argument('--dev', type=str, default='dev.txt')\nparser.add_argument('--test', type=str, default='test.txt')\nparser.add_argument('--mode', type=str, default='train')\nparser.add_argument('--output_vocab_label', type=str, default='./model/class.txt')\nparser.add_argument('--output_vocab_word', type=str, default='./model/vocab.txt')\nparser.add_argument('--tensorboard', type=str, default='tensorboard')\nparser.add_argument('--save_model', type=str, default='./model')\nargs = parser.parse_args()\nkernel_size = [int(k[0]) for k in args.kernel_size]\n\ntorch.manual_seed(args.seed)\ndevice = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\nprint(device)\n# clear tensorboard logs\nif os.path.exists(args.tensorboard):\n shutil.rmtree(args.tensorboard)\nos.mkdir(args.tensorboard)\nwriter = SummaryWriter(log_dir=args.tensorboard, flush_secs=60)\n\ncheckpoint_path = \"checkpoints\"\nif os.path.exists(checkpoint_path):\n shutil.rmtree(checkpoint_path)\nos.mkdir(checkpoint_path)\nmodel_name = \"textcnn.pt\"\n\n# do text parsing, get vocab size and class count\nbuild_vocab(args.train, args.output_vocab_label, args.output_vocab_word)\nlabel2id, id2label = load_vocab(args.output_vocab_label)\nword2id, id2word = load_vocab(args.output_vocab_word)\n\nvocab_size = len(word2id)\nnum_class = len(label2id)\n\n# set model\nmodel = TextCNN(vocab_size = vocab_size, num_class=num_class, emb_dim=args.embedding_dim, emb_droprate=args.embedding_droprate, seq_len=args.sequence_len, filter_count=args.filter_count, kernel_size=kernel_size, conv_droprate=args.conv_droprate)\nmodel.build()\nmodel.to(device)\ncriterion = nn.CrossEntropyLoss().to(device)\noptimizer = optim.Adam(model.parameters(), lr=args.lr, weight_decay=1e-6)\nwriter.add_graph(model, torch.randint(low=0,high=1000, size=(args.batch_size, args.sequence_len), dtype=torch.long).to(device))\n\n# padding sequence with \ndef padding(data, fix_length, pad, add_first=\"\", add_last=\"\"):\n if add_first:\n data.insert(0, add_first)\n if add_last:\n data.append(add_last)\n pad_data = []\n data_len = len(data)\n for idx in range(fix_length):\n if idx < data_len:\n pad_data.append(data[idx])\n else:\n pad_data.append(pad)\n return pad_data\n\ndef generate_batch(batch):\n # TextDataSet yield one line contain label and input\n batch_label, batch_input = [], []\n for data in batch:\n num_input = []\n label, sentence = data.split('\\t')\n batch_label.append(label2id[label])\n words = sentence.split()\n # pad to fix length\n words = padding(words, args.sequence_len, '', add_first='', add_last='')\n for w in words:\n if w in word2id:\n num_input.append(word2id[w])\n else:\n num_input.append(word2id[''])\n batch_input.append(num_input)\n\n tensor_label = torch.tensor(batch_label, dtype=torch.long)\n tensor_input = torch.tensor(batch_input, dtype=torch.long)\n\n return tensor_label.to(device), tensor_input.to(device)\n\ndef save_checkpoint(state, is_best, filename=\"checkpoint\"):\n name = \"%s_epoch:%s_validacc:%s.pt\" % (filename, state['epoch'], state['valid_acc'])\n torch.save(state, \"%s/%s\" % (checkpoint_path, name))\n if is_best:\n shutil.copyfile(\"%s/%s\" % (checkpoint_path, name), \"%s/%s\" % (args.save_model, model_name))\n\ndef train(train_data):\n train_loss = 0\n train_acc = 0\n train_dataset = TextDataSet(train_data)\n data = DataLoader(train_dataset, batch_size=args.batch_size, shuffle=True, collate_fn=generate_batch)\n for i, (label, inp) in enumerate(data):\n optimizer.zero_grad()\n output = model(inp)\n loss = criterion(output, label)\n train_loss += loss.item()\n loss.backward()\n optimizer.step()\n train_acc += (output.argmax(1) == label).sum().item()\n\n return train_loss / len(train_dataset), train_acc / len(train_dataset)\n\ndef test(test_data):\n valid_loss = 0\n valid_acc = 0\n test_dataset = TextDataSet(test_data)\n data = DataLoader(test_dataset, batch_size=args.batch_size, collate_fn=generate_batch)\n for i, (label, inp) in enumerate(data):\n with torch.no_grad():\n output = model(inp)\n loss = criterion(output, label)\n valid_loss += loss.item()\n valid_acc += (output.argmax(1) == label).sum().item()\n\n return valid_loss / len(test_dataset), valid_acc / len(test_dataset)\n\nif __name__ == \"__main__\":\n if args.mode == 'train':\n best_valid_acc = 0.0\n for epoch in range(args.epoch):\n start_time = time.time()\n train_loss, train_acc = train(args.train)\n valid_loss, valid_acc = test(args.dev)\n\n # save best model\n if valid_acc > best_valid_acc:\n save_checkpoint({\n 'epoch': epoch + 1,\n 'state_dict': model.state_dict(),\n 'valid_acc': valid_acc\n }, True)\n\n secs = int(time.time() - start_time)\n mins = secs / 60\n secs = secs % 60\n writer.add_scalars(\"Loss\", {\n 'train': train_loss,\n 'valid': valid_loss\n }, epoch)\n writer.add_scalars(\"Acc\", {\n 'train': train_acc,\n 'valid': valid_acc\n }, epoch)\n\n print(\"Epoch: %d\" % (epoch + 1), \" | time in %d minutes, %d seconds\" % (mins, secs))\n print(f\"\\tLoss: {train_loss:.4f}(train)\\t|\\tAcc: {train_acc * 100:.1f}%(train)\")\n print(f\"\\tLoss: {valid_loss:.4f}(valid)\\t|\\tAcc: {valid_acc * 100:.1f}%(valid)\")\n\n # test\n saved_params = torch.load(\"%s/%s\" % (args.save_model, model_name))\n print(\"epoch:%s best_valid_acc:%s\" % (saved_params['epoch'], saved_params['valid_acc']))\n model.load_state_dict(saved_params['state_dict'])\n loss, acc = test(args.test)\n print(\"test set loss: %s\" % loss)\n print(\"test set acc: %s\" % acc)\n","sub_path":"cnn/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":7206,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"383787137","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 ('productos', '0019_product_date_expiration'),\n ]\n\n operations = [\n migrations.AddField(\n model_name='product',\n name='is_antibiotico',\n field=models.BooleanField(default=False, verbose_name=b'Antibiotico'),\n ),\n ]\n","sub_path":"productos/migrations/0020_product_is_antibiotico.py","file_name":"0020_product_is_antibiotico.py","file_ext":"py","file_size_in_byte":448,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"276008082","text":"#! /usr/bin/env python\n\n## IMPORTS ##\n# Basic\nimport rospy, numpy, math\nfrom pygame import mixer\nfrom playsound import playsound\n\n# Intera\nimport intera_interface\nfrom std_msgs.msg import (\n\tBool,\n\tString,\n\tInt32,\n\tFloat64,\n\tFloat64MultiArray,\n\tUInt16,\n\tEmpty\n)\nimport sensor_msgs\nimport intera_core_msgs\n\n# Custom\nfrom limb_plus import LimbPlus\nfrom sawyer.msg import *\n\nclass Module():\n\t\n\t## INITIALIZE ROS AND SAWYER ##\n\tdef __init__(self):\n\t\t# Initialize Sawyer\n\t\trospy.init_node('Sawyer_comm_node', anonymous=True)\n\t\tintera_interface.HeadDisplay().display_image('logo.png')\n\n\t\t# Publishing topics\n\t\tsuppress_cuff_interaction = rospy.Publisher('/robot/limb/right/suppress_cuff_interaction', Empty, queue_size=1)\n\t\tself.endpoint_topic = rospy.Publisher('/EndpointInfo', EndpointInfo, queue_size=10)\n\n\t\t# Subscribing topics\n\t\trospy.Subscriber('/robot/limb/right/endpoint_state', intera_core_msgs.msg.EndpointState, self.forwardEndpointState)\n\n\t\t# Lights\n\t\tself.lights = intera_interface.Lights()\n\t\tfor light in self.lights.list_all_lights():\n\t\t\tself.lights.set_light_state(light,False)\n\n\t\t# Initialization complete. Spin.\n\t\trospy.loginfo('Ready.')\n\t\tr = rospy.Rate(10)\n\t\twhile not rospy.is_shutdown():\n\t\t\tsuppress_cuff_interaction.publish()\n\t\t\tr.sleep()\n\n\t## HELPER FUNCTIONS ##\n\t# Returns true if two positions equal each other or are at least within a given tolerance\n\n\tdef forwardEndpointState(self, data): \n\t\tendpoint_msg = EndpointInfo()\n\t\tendpoint_msg.position.x = data.pose.position.x\n\t\tendpoint_msg.position.y = data.pose.position.y\n\t\tendpoint_msg.position.z = data.pose.position.z\n\t\tendpoint_msg.orientation.x = data.pose.orientation.x\n\t\tendpoint_msg.orientation.y = data.pose.orientation.y\n\t\tendpoint_msg.orientation.z = data.pose.orientation.z\n\t\tendpoint_msg.orientation.w = data.pose.orientation.w\n\t\tself.endpoint_topic.publish(endpoint_msg)\n\n\n## DEFINE IMPORTANT CONSTANTS ##\nif __name__ == '__main__':\n\n\tModule()\n","sub_path":"robot/src/sawyer/src/subscribe.py","file_name":"subscribe.py","file_ext":"py","file_size_in_byte":1929,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"84487483","text":"import sys\n\ndef MinutesToHours(Minutes):\n #取一个整型输入,返回整型的小时和整型的分钟\n Hours = Minutes // 60\n Minutes = Minutes % 60\n return Hours,Minutes\n\nif __name__ == '__main__':\n\n try:\n Minutes = int(sys.argv[1])\n except:\n print(\"error\")\n\n if Minutes < 0:\n print(\"number error\")\n else:\n Hours,Minutes = MinutesToHours(Minutes)\n print(Hours,\"H,\",Minutes,\"M\")\n","sub_path":"函数练习1.py","file_name":"函数练习1.py","file_ext":"py","file_size_in_byte":443,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"309459527","text":"from django.core.exceptions import ObjectDoesNotExist, ValidationError\nfrom django.db import transaction\nfrom django.utils.translation import gettext_lazy as _\n\nfrom rest_framework import status as response_status\nfrom rest_framework.exceptions import NotAcceptable, NotFound, ValidationError as ValidationErrorResponse\nfrom rest_framework.response import Response\nfrom rest_framework.viewsets import ViewSet\n\n\nclass ViewSetGetObjMixin(ViewSet):\n @transaction.atomic\n def get_object(self, uuid=None, is_update=False):\n queryset = self.queryset()\n\n try:\n if is_update:\n queryset = queryset.select_for_update().get(uuid=uuid)\n else:\n queryset = queryset.get(uuid=uuid)\n except ObjectDoesNotExist:\n raise NotFound()\n except ValidationError as e:\n raise ValidationErrorResponse(detail=str(e))\n\n return queryset\n\n\nclass ViewSetDestroyObjMixin(ViewSet):\n @transaction.atomic\n def destroy(self, request, uuid=None, format=None):\n queryset = self.get_object(uuid=uuid)\n \n try:\n queryset.delete(request=request)\n except ValidationError as e:\n raise NotAcceptable(detail=' '.join(e))\n\n return Response({'detail': _(\"Delete success!\")},\n status=response_status.HTTP_200_OK)\n","sub_path":"utils/mixin/viewsets.py","file_name":"viewsets.py","file_ext":"py","file_size_in_byte":1364,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"289655744","text":"import tarfile, zlib, os\nimport cPickle as pickle\n\n\nclass Segment(object):\n\t\"\"\"\n\tObject which stores sequences up to a given length. Allows performing\n\tbasic operations on sequences.\n\t\"\"\"\n\n\tdef __init__(self, archivePath, segmentName, maxSegmentSize, sequence):\n\t\t\"\"\"Create Segment object.\"\"\"\n\n\t\tself._archivePath = str(archivePath)\n\t\tself._segmentName = str(segmentName)\n\t\tself._maxSegmentSize = int(maxSegmentSize)\n\t\tself._sequence = str(sequence)\n\t\tself._segmentSize = len(self._sequence)\n\n\n\tdef _setPath(self, archivePath):\n\t\t\"\"\"Change archivePath. Private method used only after loading\n\t\ta ZPObject to ensure that sequences will be extracted from the\n\t\tappropriate archive even if it has been renamed or moved in the\n\t\tfilesystem.\"\"\"\n\n\t\tself._archivePath = str(archivePath)\n\n\n\tdef setPath(self, archivePath):\n\t\t\"\"\"Change archivePath. Results in removal of file containing\n\t\tthe sequence from old archive and from the filesystem. Sequence\n\t\twill be stored as an attribute in the Segment object until save\n\t\tcommand is invoked.\"\"\"\n\n\t\t#if sequence is saved in the filesystem\n\t\t#and archivePath is different than before\n\t\tif self._sequence == None and self._archivePath != archivePath:\n\t\t\t#keep sequence explicitly in Segment instance\n\t\t\tself._sequence = self.getSequence()\n\n\t\t\t#extract file containing sequence from archive\n\t\t\twith tarfile.open(self._archivePath, \"r\") as tar:\n\t\t\t\ttar.extract(self._segmentName)\n\n\t\t\t#remove extracted file from filesystem\n\t\t\tos.remove(self._segmentName)\n\n\t\t#change archivePath\n\t\tself._archivePath = str(archivePath)\n\n\n\tdef getSize(self):\n\t\t\"\"\"Get current length of sequence contained in Segment.\"\"\"\n\n\t\treturn self._segmentSize\n\n\n\tdef getMaxSize(self):\n\t\t\"\"\"Get maximal allowed size for Segment.\"\"\"\n\n\t\treturn self._maxSegmentSize\n\n\n\tdef getSequence(self, start=0, end=None):\n\t\t\"\"\"Access sequence (or subsequence) kept in Segment.\"\"\"\n\n\t\t#if end is not specified,\n\t\t#set it to the last character in sequence\n\t\tif end == None:\n\t\t\tend = self._segmentSize\n\n\t\t#if sequence is stored explicitly in Segment instance\n\t\tif self._sequence != None:\n\t\t\treturn self._sequence[start:end]\n\n\t\t#if sequence is stored in the archive\n\t\telse:\n\t\t\t#access archive\n\t\t\twith tarfile.open(self._archivePath, \"r\") as tar:\n\t\t\t\t#load and decompress sequence\n\t\t\t\tsequence = zlib.decompress( \\\n\t\t\t\t\tpickle.load( \\\n\t\t\t\t\ttar.extractfile(self._segmentName) \\\n\t\t\t\t\t\t\t) )\n\n\t\t\treturn sequence[start:end]\n\n\n\tdef setSequence(self, newSeq, start=0, end=None):\n\t\t\"\"\"Change sequence (or subsequence) kept in Segment. Results in\n\t\tremoval of file containing the sequence from archive and from\n\t\tthe filesystem. Sequence will be stored as an attribute in the\n\t\tSegment object until save command is invoked. In case changed\n\t\tsequence is longer than maximal Segment size, this fuction returns\n\t\tthe suffix which sticked out (it may be an empty string).\"\"\"\n\n\t\t#if end is not specified,\n\t\t#set it to the last character in sequence\n\t\tif end == None:\n\t\t\tend = self._segmentSize\n\n\t\t#get current sequence\n\t\tseq = self.getSequence()\n\t\t\n\t\t#if sequence is stored in the archive\n\t\tif self._sequence == None:\n\t\t\t#access archive\n\t\t\twith tarfile.open(self._archivePath, \"r\") as tar:\n\t\t\t\t#extract file containing sequence from archive\n\t\t\t\ttar.extract(self._segmentName)\n\n\t\t\t#remove extracted file from filesystem\n\t\t\tos.remove(self._segmentName)\n\n\t\t#prepare new sequence\n\t\tseq = seq[:start] + newSeq + seq[end:]\n\n\t\t#if sequence is longer than specified limit\n\t\tif len(seq) > self._maxSegmentSize:\n\t\t\t#saved new trimmed sequence\n\t\t\tself._sequence = seq[:self._maxSegmentSize]\n\n\t\t#if sequence length is within specified limit\n\t\telse:\n\t\t\t#save whole new sequence\n\t\t\tself._sequence = seq\n\n\t\t#update current segment size\n\t\tself._segmentSize = len(self._sequence)\n\n\t\t#return excesive sequence\n\t\treturn seq[self._segmentSize:]\n\n\n\tdef appendSequence(self, sequence):\n\t\t\"\"\"Convenience function for appending sequences. See setSequence\n\t\tfor details.\"\"\"\n\n\t\treturn self.setSequence(sequence, self._segmentSize)\n\n\n\tdef prependSequence(self, sequence):\n\t\t\"\"\"Convenience function for prepending sequences. See setSequence\n\t\tfor details.\"\"\"\n\n\t\treturn self.setSequence(sequence, end=0)\n\n\n\tdef delSequence(self, start=0, end=None):\n\t\t\"\"\"Convenience function for deleting sequences. See setSequence\n\t\tfor details. It does not return any excesive sequence.\"\"\"\n\n\t\tself.setSequence('', start, end)\n\n\n\tdef save(self):\n\t\t\"\"\"Save the sequence contained in Segment to the archive.\"\"\"\n\n\t\t#if sequence is not already in the archive\n\t\tif self._sequence:\n\t\t\t#compress and save sequence to a file\n\t\t\tpickle.dump( \\\n\t\t\t\tzlib.compress(self._sequence), \\\n\t\t\t\topen(self._segmentName, \"wb\") \\\n\t\t\t\t)\n\n\t\t\t#add saved sequence file to the archive\n\t\t\twith tarfile.open(self._archivePath, \"a\") as tar:\n\t\t\t\ttar.add(self._segmentName)\n\n\t\t\t#update status of sequence attribute\n\t\t\t#it no longer stores sequence explicitly\n\t\t\tself._sequence = None\n\n\t\t\t#remove unnecessary file in filesystem\n\t\t\tos.remove(self._segmentName)\n","sub_path":"Bio/ZP/Segment.py","file_name":"Segment.py","file_ext":"py","file_size_in_byte":4952,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"309700867","text":"# -*- coding: utf-8 -*-\nfrom export import export, exportDatabase\n'''\nAqui defino las clases que se van a utilizar en\nel programa de loader. Principalmente factura, pl y bl\nmas que todo para poder almacenar la información que se lea\nde los documentos.\n'''\n\nclass Importation():\n def __init__(self):\n self.processID = None\n self.department = \"SC\"\n self.district = None\n self.regime = None\n self.status = \"SHIPPED\"\n self.pls = []\n self.shipID = None\n self.project = None\n self.supplier = None\n self.invoices = []\n self.incoterm = 'CIP'\n self.fob = 0\n self.freight = 0\n self.insurance = 0\n self.total = 0\n self.cases = 0\n self.grossWeight = 0.0\n self.netWeight = 0.0\n self.volume = 0.0\n self.description = 'Telecom Equipment'\n self.bls = []\n self.forwarder = None\n self.containers = []\n self.warnings = []\n def exportExcel(self):\n export(self)\n\n def exportDB(self, db):\n exportDatabase(self, db)\n \n def totalize(self):\n #totaliza las propiedades\n for inv in self.invoices:\n self.fob+= inv.fob\n self.freight+= inv.freight\n self.insurance+= inv.insurance\n self.total+= inv.total\n self.supplier = inv.supplier\n self.incoterm = inv.incoterm\n self.description = inv.description\n if inv.warning:\n self.warnings.append(inv.warning)\n \n for pl in self.pls:\n self.cases += pl.cases\n self.grossWeight += pl.grossWeight\n self.netWeight += pl.netWeight\n self.volume += pl.volume\n for bl in self.bls:\n self.forwarder = bl.forwarder\n for container in bl.containers:\n self.containers.append(container)\n\n\nclass Invoice():\n def __init__(self):\n self.number = None\n self.supplier = None\n self.description = None\n self.fob = 0\n self.freight = 0\n self.insurance = 0\n self.total = 0\n self.incoterm = \"CIP\"\n self.pl = None\n def validate(self):\n if self.total == self.fob + self.freight + self.insurance:\n self.warning = None\n else:\n self.warning = 'Math error, invoice %s' %self.number\n\nclass Packinglist():\n def __init__(self):\n self.number = None\n self.cases = 0\n self.grossWeight = 0.00\n self.netWeight = 0.00\n self.volume=0.0\n\nclass BL():\n def __init__(self):\n self.number = None\n self.forwarder = None\n self.cases = None\n self.grossWeight = None\n self.volume= None\n self.containerized = False\n self.containers = []\n def totalize(self):\n #solo para carga contenedorizada\n if self.containerized:\n for container in self.containers:\n try:\n self.cases += container.cases\n except:\n self.cases = container.cases\n try:\n self.grossWeight += container.weight\n except:\n self.grossWeight = container.weight\n try:\n self.volume += container.volume\n except:\n self.volume = container.volume\n\n if self.number and self.cases and self.grossWeight and self.volume and self.containers:\n self.complete = True\n else:\n self.complete = False\n\nclass Container():\n def __init__(self):\n self.number = None\n self.capacity = None\n self.cases = None\n self.weight = None\n self.volume = None\n\n\n# imp = Importation()\n# print imp.cases, imp.description, imp.freight, imp.incoterm\n","sub_path":"loader/loaderClasses.py","file_name":"loaderClasses.py","file_ext":"py","file_size_in_byte":3846,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"135172012","text":"#!/usr/bin/python3\n# -*- coding:utf-8 -*-\nfrom typing import List\n\nimport numpy as np\n\n\nclass Solution:\n def numOfSubarrays(self, arr: List[int], k: int, threshold: int) -> int:\n n = len(arr)\n right = 0\n ans = 0\n while right + k <= n:\n temp = np.average(arr[right:right + k])\n if temp >= threshold:\n ans += 1\n right += 1\n return ans\n\n\nif __name__ == '__main__':\n s = Solution()\n arr = [2, 2, 2, 2, 5, 5, 5, 8]\n k = 3\n threshold = 4\n print(s.numOfSubarrays(arr, k, threshold))\n","sub_path":"双指针/1343.py","file_name":"1343.py","file_ext":"py","file_size_in_byte":577,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"502114858","text":"# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements. See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership. The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License. You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied. See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"Unit tests for geocoding\"\"\"\nimport threading\nimport time\n\nimport pandas as pd\nimport simplejson as json\nfrom sqlalchemy import Float, Integer, MetaData, String\nfrom sqlalchemy.engine import reflection\nfrom sqlalchemy.ext.declarative import declarative_base\n\nimport superset.models.core as models\nfrom superset import conf, db\nfrom superset.connectors.sqla.models import SqlaTable, TableColumn\nfrom superset.exceptions import TableNotFoundException\nfrom superset.models.core import Database\nfrom superset.utils import core as utils\nfrom superset.utils.geocoders import BaseGeocoder\nfrom superset.views.geocoding import Geocoder as GeocoderApi\n\nfrom .base_tests import SupersetTestCase\n\n\nclass GeocoderMock(BaseGeocoder):\n geocoded_data = {\n \"Oberseestrasse 10 Rapperswil Switzerland\": [47.224, 8.8181],\n \"Grossmünsterplatz Zürich Switzerland\": [47.370, 8.544],\n \"Uetliberg Zürich Switzerland\": [47.353, 8.492],\n \"Zürichbergstrasse 221 Zürich Switzerland\": [47.387, 8.574],\n \"Bahnhofstrasse Zürich Switzerland\": [47.372, 8.539],\n }\n\n def _get_coordinates_from_address(self, address: str):\n time.sleep(2)\n return [self.geocoded_data.get(address), 0.81]\n\n def check_api_key(self):\n pass\n\n\nclass GeocodingTests(SupersetTestCase):\n test_database = None\n test_table = None\n\n def __init__(self, *args, **kwargs):\n super(GeocodingTests, self).__init__(*args, **kwargs)\n\n def setUp(self):\n self.login()\n GeocoderApi.geocoder = GeocoderMock(conf)\n self.create_table_in_view()\n\n def create_table_in_view(self):\n self.test_database = utils.get_example_database()\n self.test_database.allow_dml = True\n\n params = {\"remote_id\": 1234, \"database_name\": self.test_database.name}\n self.test_table = SqlaTable(\n id=1234, table_name=\"Departments\", params=json.dumps(params)\n )\n self.test_table.columns.append(\n TableColumn(column_name=\"department_id\", type=\"INTEGER\")\n )\n self.test_table.columns.append(TableColumn(column_name=\"name\", type=\"STRING\"))\n self.test_table.columns.append(TableColumn(column_name=\"street\", type=\"STRING\"))\n self.test_table.columns.append(TableColumn(column_name=\"city\", type=\"STRING\"))\n self.test_table.columns.append(\n TableColumn(column_name=\"country\", type=\"STRING\")\n )\n self.test_table.columns.append(TableColumn(column_name=\"lat\", type=\"FLOAT\"))\n self.test_table.columns.append(TableColumn(column_name=\"lon\", type=\"FLOAT\"))\n self.test_table.database = self.test_database\n self.test_table.database_id = self.test_table.database.id\n db.session.add(self.test_table)\n db.session.commit()\n\n data = {\n \"department_id\": [1, 2, 3, 4, 5],\n \"name\": [\n \"Logistics\",\n \"Marketing\",\n \"Facility Management\",\n \"Personal\",\n \"Finances\",\n ],\n \"street\": [\n \"Oberseestrasse 10\",\n \"Grossmünsterplatz\",\n \"Uetliberg\",\n \"Zürichbergstrasse 221\",\n \"Bahnhofstrasse\",\n ],\n \"city\": [\"Rapperswil\", \"Zürich\", \"Zürich\", \"Zürich\", \"Zürich\"],\n \"country\": [\n \"Switzerland\",\n \"Switzerland\",\n \"Switzerland\",\n \"Switzerland\",\n \"Switzerland\",\n ],\n \"lat\": [None, None, None, None, 4.789],\n \"lon\": [None, None, None, 1.234, None],\n }\n df = pd.DataFrame(data=data)\n\n # because of caching problem with postgres load database a second time\n # without this, the sqla engine throws an exception\n database = utils.get_example_database()\n if database:\n engine = database.get_sqla_engine()\n df.to_sql(\n self.test_table.table_name,\n engine,\n if_exists=\"replace\",\n chunksize=500,\n dtype={\n \"department_id\": Integer,\n \"name\": String(60),\n \"street\": String(60),\n \"city\": String(60),\n \"country\": String(60),\n \"lat\": Float,\n \"lon\": Float,\n },\n index=False,\n )\n\n def doCleanups(self):\n self.logout()\n if self.test_database and self.test_table:\n db.session.delete(self.test_table)\n self.test_database.allow_dml = False\n db.session.commit()\n\n base = declarative_base()\n metadata = MetaData(db.engine, reflect=True)\n table = metadata.tables.get(self.test_table.table_name)\n if table is not None:\n base.metadata.drop_all(db.engine, [table], checkfirst=True)\n\n def test_menu_entry_geocode_exist(self):\n url = \"/dashboard/list/\"\n dashboard_page = self.get_resp(url)\n assert \"Geocode Addresses\" in dashboard_page\n\n def test_geocode_addresses_view_load(self):\n url = \"/geocoder/geocoding\"\n form_get = self.get_resp(url)\n assert \"Geocode Addresses\" in form_get\n\n def test_get_columns(self):\n url = \"/geocoder/geocoding/columns\"\n table_dto = models.TableDto(\n self.test_table.id,\n self.test_table.table_name,\n self.test_table.schema,\n self.test_table.database_id,\n )\n data = {\"table\": table_dto.to_json()}\n\n columns = reflection.Inspector.from_engine(db.engine).get_columns(\n self.test_table.table_name\n )\n\n response = self.get_resp(url, json_=data)\n assert columns[0].get(\"name\") in response\n\n def test_get_invalid_columns(self):\n url = \"/geocoder/geocoding/columns\"\n table_dto = models.TableDto(10001, \"no_table\")\n data = {\"table\": table_dto.to_json()}\n\n response = self.get_resp(url, json_=data)\n\n error_message = \"No columns found for table with name undefined\"\n assert error_message in response\n\n def test_does_valid_column_name_exist(self):\n column_name = self.test_table.columns[0].column_name\n\n response = GeocoderApi()._does_column_name_exist(self.test_table, column_name)\n assert True is response\n\n def test_does_column_name_not_exist(self):\n column_name = \"no_column\"\n\n response = GeocoderApi()._does_column_name_exist(self.test_table, column_name)\n assert False is response\n\n def test_does_table_not_exist(self):\n table_id = -1\n\n error_message = f\"Table with ID {table_id} does not exists\"\n with self.assertRaisesRegex(TableNotFoundException, error_message):\n GeocoderApi()._get_table_with_columns(table_id)\n\n def test_load_data_from_columns_fail(self):\n table = self.test_table\n geo_columns = [\"street\", \"city\", \"country\"]\n lat_column = \"lat\"\n lon_column = \"lon\"\n\n data = GeocoderApi()._load_data_from_columns(\n table, geo_columns, lat_column, lon_column, False\n )\n assert 5 == len(data)\n assert (\"Oberseestrasse 10\", \"Rapperswil\", \"Switzerland\") in data\n\n def test_load_data_from_columns_append(self):\n table = self.test_table\n geo_columns = [\"street\", \"city\", \"country\"]\n lat_column = \"lat\"\n lon_column = \"lon\"\n\n data = GeocoderApi()._load_data_from_columns(\n table, geo_columns, lat_column, lon_column, True\n )\n assert 5 == len(data)\n assert (\"Oberseestrasse 10\", \"Rapperswil\", \"Switzerland\") in data\n\n def test_add_lat_lon_columns(self):\n table = self.test_table\n lat_column_name = \"latitude\"\n lon_column_name = \"longitude\"\n\n columns = self.test_table.columns\n number_of_columns_before = len(columns)\n\n GeocoderApi()._create_columns(\n lat_column_name, False, lon_column_name, False, table\n )\n\n columns = self.test_table.columns\n number_of_columns_after = len(columns)\n\n assert number_of_columns_after == number_of_columns_before + 2\n column_names = [column.column_name for column in columns]\n assert lon_column_name in column_names\n assert lat_column_name in column_names\n\n def test_insert_geocoded_data(self):\n lat_column_name = \"lat\"\n lon_column_name = \"lon\"\n table_name = self.test_table.table_name\n table = self.test_table\n geo_columns = [\"street\", \"city\", \"country\"]\n data = [\n (\"Oberseestrasse 10\", \"Rapperswil\", \"Switzerland\", 47.224, 8.8181),\n (\"Grossmünsterplatz\", \"Zürich\", \"Switzerland\", 47.370, 8.544),\n (\"Uetliberg\", \"Zürich\", \"Switzerland\", 47.353, 8.492),\n (\"Zürichbergstrasse 221\", \"Zürich\", \"Switzerland\", 47.387, 8.574),\n (\"Bahnhofstrasse\", \"Zürich\", \"Switzerland\", 47.372, 8.539),\n ]\n\n GeocoderApi()._insert_geocoded_data(\n table, lat_column_name, lon_column_name, geo_columns, data\n )\n\n quote = self.test_database.get_sqla_engine().dialect.identifier_preparer.quote\n result = db.engine.execute(\n f\"SELECT street, city, country, {lat_column_name}, {lon_column_name} FROM {quote(table_name)}\"\n )\n for row in result:\n assert row in data\n\n def _geocode_post(self):\n table_dto = models.TableDto(\n self.test_table.id,\n self.test_table.table_name,\n self.test_table.schema,\n self.test_table.database_id,\n )\n return {\n \"datasource\": table_dto.to_json(),\n \"streetColumn\": \"street\",\n \"cityColumn\": \"city\",\n \"countryColumn\": \"country\",\n \"latitudeColumnName\": \"lat\",\n \"longitudeColumnName\": \"lon\",\n \"ifExists\": \"replace\",\n \"saveOnErrorOrInterrupt\": True,\n }\n\n def test_geocode(self):\n url = \"/geocoder/geocoding/geocode\"\n\n response = self.get_resp(url, json_=self._geocode_post())\n assert \"OK\" in response\n\n def test_progress(self):\n geocode_url = \"/geocoder/geocoding/geocode\"\n progress_url = \"/geocoder/geocoding/progress\"\n geocode = threading.Thread(\n target=self.get_resp,\n args=(geocode_url, None, True, True, self._geocode_post()),\n )\n geocode.start()\n time.sleep(\n 4\n ) # Wait to be sure geocode has geocoded some data, but not all (5 addresses * 2 sec)\n progress = json.loads(self.get_resp(progress_url))\n assert 0 < progress.get(\"progress\", 0)\n assert progress.get(\"is_in_progress\") is True\n assert 0 < progress.get(\"success_counter\", 0)\n\n geocode.join()\n\n def test_interrupt(self):\n geocode_url = \"/geocoder/geocoding/geocode\"\n interrupt_url = \"/geocoder/geocoding/interrupt\"\n progress_url = \"/geocoder/geocoding/progress\"\n\n geocode = threading.Thread(\n target=self.get_resp,\n args=(geocode_url, None, True, True, self._geocode_post()),\n )\n geocode.start()\n time.sleep(\n 4\n ) # Wait to be sure geocode has geocoded some data, but not all (5 addresses * 2 sec)\n\n interrupt = self.get_resp(interrupt_url, json_=json.dumps(\"{}\"))\n assert '\"OK\"' in interrupt\n\n time.sleep(4) # Wait to be sure geocode has geocoded another data\n\n progress = json.loads(self.get_resp(progress_url))\n assert 5 >= progress.get(\"success_counter\", 0)\n assert 0 == progress.get(\"progress\", 5)\n assert progress.get(\"is_in_progress\", True) is False\n\n geocode.join()\n","sub_path":"tests/geocoding_tests.py","file_name":"geocoding_tests.py","file_ext":"py","file_size_in_byte":12627,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"573871708","text":"#!/usr/bin/env python3\n# -*- coding:utf-8 -*-\n# Copyright (c) Megvii, Inc. and its affiliates.\nimport torch.backends.cudnn as cudnn\nfrom yolox.core import Trainer\n\nimport random\nimport warnings\nfrom loguru import logger\nimport torch\nimport json\nfrom yolox.data.datasets import COCO_CLASSES\nfrom yolox.exp import get_exp\nfrom yolox.utils import fuse_model, get_model_info, postprocess, vis\nfrom tools.demo import Predictor\nimport os\nimport cv2\n\nIMAGE_EXT = [\".jpg\", \".jpeg\", \".webp\", \".bmp\", \".png\"]\n\n##\n\nimport dtlpy as dl\nfrom dtlpy import entities\n\n\nclass Dummy:\n def __init__(self, d):\n for k, v in d.items():\n self.__setattr__(k, v)\n\n\nclass ModelAdapter(dl.BaseModelAdapter):\n @staticmethod\n def default_train_configurations():\n return {\n \"experiment_name\": None,\n \"name\": None, # help=\"model name\")\n \"dist_backend\": \"nccl\", # type=str, help=\"distributed backend\"\n \"dist-url\": None, # type=str, help=\"url used to set up distributed training\",\n \"batch_size\": 4, # help=\"batch size\")\n \"devices\": None, # type=int, help=\"device for training\"\n \"local_rank\": 0, # type=int, help=\"local rank for dist training\"\n \"exp_file\": None, # type=str, help=\"plz input your expriment description file\",\n \"resume\": False, # action=\"store_true\", help=\"resume training\"\n \"ckpt\": None, # type=str, help=\"checkpoint file\")\n \"start_epoch\": None, # type=int, help=\"resume training start epoch\",\n \"num_machines\": 1, # type=int, help=\"num of node for training\"\n \"machine_rank\": 0, # type=int, help=\"node rank for multi-node training\"\n \"fp16\": False, # action=\"store_true\", help=\"Adopting mix precision training.\",\n \"cache\": False, # action = \"store_true\", help = \"Caching imgs to RAM for fast training.\",\n \"occupy\": False, # action=\"store_true\", help=\"occupy GPU memory first for training.\",\n \"opts\": None, # help=\"Modify config options using the command-line\", nargs=argparse.REMAINDER,\n }\n\n @staticmethod\n def default_inference_configurations():\n return {\"demo\": \"image\", # help=\"demo type, eg. image, video and webcam\" )\n \"experiment_name\": None,\n \"name\": None, # help=\"model name\")\n \"path\": \"./assets/dog.jpg\", # help=\"path to images or video\" )\n \"camid\": 0, # help=\"webcam demo camera id\")\n \"save_result\": False,\n # action=\"store_true\", help=\"whether to save the inference result of image/video\", )\n \"exp_file\": None, # type=str, help=\"pls input your expriment description file\", )\n \"ckpt\": None, # type=str, help=\"ckpt for eval\")\n \"device\": \"cpu\",\n # type=str, help=\"device to run our model, can either be cpu or gpu\", )\n \"conf\": 0.25, # type=float, help=\"test conf\")\n \"nms\": 0.4, # type=float, help=\"test nms threshold\")\n \"tsize\": None, # type=int, help=\"test img size\")\n \"fp16\": False, # action=\"store_true\", help=\"Adopting mix precision evaluating.\", )\n \"fuse\": False, # action=\"store_true\", help=\"Fuse conv and bn for testing.\", )\n \"trt\": False, # action=\"store_true\", help=\"Using TensorRT model for testing.\",\n } # )\n\n def load(self, local_path, **kwargs):\n \"\"\" Loads model and populates self.model with a `runnable` model\n\n Virtual method - need to implement\n\n This function is called by load_from_snapshot (download to local and then loads)\n\n :param local_path: `str` directory path in local FileSystem\n \"\"\"\n\n configuration = self.default_inference_configurations()\n configuration.update(self.configuration)\n configuration.update({'ckpt': os.path.join(local_path, configuration['ckpt']),\n 'classes_filename': os.path.join(local_path, configuration['classes_filename'])})\n self.configuration = configuration\n args = Dummy(configuration)\n exp = get_exp(args.exp_file, args.name)\n with open(configuration['classes_filename'], 'r') as f:\n labels_map = json.load(f)\n self.snapshot.label_map = labels_map\n exp.num_classes = len(self.snapshot.label_map)\n if not args.experiment_name:\n args.experiment_name = exp.exp_name\n\n file_name = os.path.join(exp.output_dir, args.experiment_name)\n os.makedirs(file_name, exist_ok=True)\n\n if args.save_result:\n vis_folder = os.path.join(file_name, \"vis_res\")\n os.makedirs(vis_folder, exist_ok=True)\n\n if args.trt:\n args.device = \"gpu\"\n\n logger.info(\"Args: {}\".format(args))\n\n if args.conf is not None:\n exp.test_conf = args.conf\n if args.nms is not None:\n exp.nmsthre = args.nms\n if args.tsize is not None:\n exp.test_size = (args.tsize, args.tsize)\n\n model = exp.get_model()\n logger.info(\"Model Summary: {}\".format(get_model_info(model, exp.test_size)))\n\n if args.device == \"gpu\":\n model.cuda()\n model.eval()\n\n if not args.trt:\n if args.ckpt is None:\n ckpt_file = os.path.join(file_name, \"best_ckpt.pth\")\n else:\n ckpt_file = args.ckpt\n logger.info(\"loading checkpoint\")\n ckpt = torch.load(ckpt_file, map_location=\"cpu\")\n # load the model state dict\n model.load_state_dict(ckpt[\"model\"])\n logger.info(\"loaded checkpoint done.\")\n\n if args.fuse:\n logger.info(\"\\tFusing model...\")\n model = fuse_model(model)\n\n if args.trt:\n assert not args.fuse, \"TensorRT model is not support model fusing!\"\n trt_file = os.path.join(file_name, \"model_trt.pth\")\n assert os.path.exists(\n trt_file\n ), \"TensorRT model is not found!\\n Run python3 tools/trt.py first!\"\n model.head.decode_in_inference = False\n decoder = model.head.decode_outputs\n logger.info(\"Using TensorRT to inference\")\n else:\n trt_file = None\n decoder = None\n self.predictor = Predictor(model, exp, list(labels_map.values()), trt_file, decoder, args.device)\n\n def save(self, local_path, **kwargs):\n \"\"\" saves configuration and weights locally\n\n Virtual method - need to implement\n\n the function is called in save_to_snapshot which first save locally and then uploads to snapshot entity\n\n :param local_path: `str` directory path in local FileSystem\n \"\"\"\n self.snapshot.configuration = self.configuration\n self.snapshot.configuration['label_map'] = self.label_map\n self.snapshot.configuration['ckpt'] = 'latest_ckpt.pth'\n self.snapshot.configuration['classes_filename'] = 'classes.json'\n self.snapshot.update()\n with open(os.path.join(local_path, 'classes.json'), 'w') as f:\n json.dump(self.label_map, f, indent=2)\n\n def train(self, data_path, output_path, **kwargs):\n \"\"\" Train the model according to data in local_path and save the snapshot to dump_path\n Virtual method - need to implement\n :param data_path: `str` local File System path to where the data was downloaded and converted at\n :param output_path: `str` local File System path where to dump training mid-results (checkpoints, logs...)\n \"\"\"\n from exps.example.dataloop.custom import DtlpyExp\n configuration = self.default_train_configurations()\n configuration.update(self.configuration)\n configuration['experiment_name'] = ''\n args = Dummy(configuration)\n exp = DtlpyExp(\n train_path=os.path.join(data_path, 'train'),\n val_path=os.path.join(data_path, 'validation'),\n dtlpy_dataset=self.snapshot.dataset)\n loader = exp.get_data_loader(batch_size=1,\n is_distributed=False)\n exp.num_classes = len(loader.dataset.dtlpy_loader.id_to_label_map)\n self.label_map = loader.dataset.dtlpy_loader.id_to_label_map\n # exp.merge(args.opts)\n exp.output_dir = output_path\n exp.max_epoch = args.max_epoch\n exp.input_size = args.input_size\n exp.test_size = args.input_size\n\n num_gpu = torch.cuda.device_count() if args.devices is None else args.devices\n assert num_gpu <= torch.cuda.device_count()\n if exp.seed is not None:\n random.seed(exp.seed)\n torch.manual_seed(exp.seed)\n cudnn.deterministic = True\n warnings.warn(\n \"You have chosen to seed training. This will turn on the CUDNN deterministic setting, \"\n \"which can slow down your training considerably! You may see unexpected behavior \"\n \"when restarting from checkpoints.\"\n )\n # set environment variables for distributed training\n cudnn.benchmark = True\n trainer = Trainer(exp, args)\n trainer.train()\n self.model = trainer.model\n\n def predict(self, batch, **kwargs):\n \"\"\" Model inference (predictions) on batch of images\n\n Virtual method - need to implement\n\n :param batch: `np.ndarray`\n :return: `list[dl.AnnotationCollection]` each collection is per each image / item in the batch\n \"\"\"\n visualize = kwargs.get('visualize', False)\n save_result = kwargs.get('save_result', False)\n save_folder = kwargs.get('save_folder', False)\n\n batch_results = list()\n for i_image, image in enumerate(batch):\n outputs, img_info = self.predictor.inference(image)\n annotation_collection = dl.AnnotationCollection(item=None)\n if outputs[0] is not None:\n for output in outputs[0].cpu().numpy():\n cls = int(output[6])\n scores = output[4] * output[5]\n # preprocessing: resize\n left = int(output[0] / img_info['ratio'])\n top = int(output[1] / img_info['ratio'])\n right = int(output[2] / img_info['ratio'])\n bottom = int(output[3] / img_info['ratio'])\n annotation_collection.add(annotation_definition=dl.Box(top=top,\n left=left,\n right=right,\n bottom=bottom,\n label=self.predictor.cls_names[cls]\n ),\n model_info={'confidence': scores,\n 'name': 'tmp'})\n batch_results.append(annotation_collection)\n\n if visualize:\n result_image = self.predictor.visual(outputs[0], img_info, self.predictor.confthre)\n if save_result:\n os.makedirs(save_folder, exist_ok=True)\n save_file_name = os.path.join(save_folder, '{}.jpg'.format(i_image))\n logger.info(\"Saving detection result in {}\".format(save_file_name))\n cv2.imwrite(save_file_name, result_image)\n return batch_results\n\n def convert_from_dtlpy(self, data_path, **kwargs):\n \"\"\" Convert Dataloop structure data to model structured\n\n Virtual method - need to implement\n\n e.g. take dlp dir structure and construct annotation file\n\n :param data_path: `str` local File System directory path where we already downloaded the data from dataloop platform\n :return:\n \"\"\"\n pass\n\n def convert_to_dtlpy(self, items: entities.PagedEntities):\n \"\"\" This should implement similar to convert only to work on dlp items.\n -> meaning create the converted version from items entities\n \"\"\"\n # TODO\n pass\n\n\ndef test_predict():\n dl.setenv('prod')\n project = dl.projects.get('COCO ors')\n # model = project.models.create(model_name='yolox',\n # is_global=True,\n # src_path=r'E:\\ModelsZoo\\YOLOX-main',\n # entry_point='model_adapter.py')\n model = project.models.get('yolox')\n # pretrained snapshot\n\n # snapshot = model.snapshots.create(snapshot_name='coco-pretrained',\n # dataset_id=None,\n # configuration={'ckpt': 'yolox_l.pth',\n # 'name': 'yolox-l',\n # 'device': 'cpu'},\n # bucket=dl.LocalBucket(\n # local_path=r'E:\\ModelsZoo\\YOLOX-main\\YOLOX_outputs\\yolox_l'),\n # labels=[])\n snapshot = model.snapshots.get('coco-pretrained')\n\n adapter = model.build()\n adapter.load_from_snapshot(snapshot=snapshot,\n local_path=snapshot.bucket.local_path)\n\n file = r'E:\\ModelsZoo\\YOLOX-main\\assets\\dog.jpg'\n image = cv2.imread(file)\n adapter.predict([image])\n\n dl.setenv('prod')\n # for coco\n item = dl.items.get(item_id='610a21a41d5b00986dd13d3b')\n # for fruit\n item = dl.items.get(item_id='6110d4b4d996e5124fc1da57')\n adapter.predict_items([item], with_upload=True)\n\n\ndef model_and_snapshot_creation():\n dl.setenv('prod')\n project = dl.projects.get('DataloopModels')\n\n codebase = dl.GitCodebase(git_url='https://github.com/dataloop-ai/YOLOX',\n git_tag='main')\n model = project.models.create(model_name='YOLOX',\n output_type=dl.AnnotationType.BOX,\n is_global=True,\n codebase=codebase,\n entry_point='model_adapter.py')\n\n # bucket = dl.LocalBucket(local_path=r'E:\\ModelsZoo\\YOLOX-main\\YOLOX_outputs\\yolox_l')\n bucket = dl.buckets.create(dl.BucketType.GCS,\n gcs_project_name='viewo-main',\n gcs_bucket_name='model-mgmt-snapshots',\n gcs_prefix='YOLOX')\n snapshot = model.snapshots.create(snapshot_name='coco-pretrained',\n description='COCO pretrained model',\n dataset_id=None,\n is_global=True,\n configuration={'ckpt': 'yolox_l.pth',\n 'classes_filename': 'classes.json',\n 'name': 'yolox-l'},\n project_id=project.id,\n bucket=bucket,\n labels=\n [\"person\", \"bicycle\", \"car\", \"motorcycle\", \"airplane\", \"bus\", \"train\",\n \"truck\", \"boat\", \"traffic light\",\n \"fire hydrant\", \"stop sign\", \"parking meter\", \"bench\", \"bird\", \"cat\",\n \"dog\", \"horse\", \"sheep\", \"cow\",\n \"elephant\", \"bear\", \"zebra\", \"giraffe\", \"backpack\", \"umbrella\", \"handbag\",\n \"tie\", \"suitcase\", \"frisbee\",\n \"skis\", \"snowboard\", \"sports ball\", \"kite\", \"baseball bat\",\n \"baseball glove\", \"skateboard\", \"surfboard\",\n \"tennis racket\", \"bottle\", \"wine glass\", \"cup\", \"fork\", \"knife\", \"spoon\",\n \"bowl\", \"banana\", \"apple\",\n \"sandwich\", \"orange\", \"broccoli\", \"carrot\", \"hot dog\", \"pizza\", \"donut\",\n \"cake\", \"chair\", \"couch\",\n \"potted plant\", \"bed\", \"dining table\", \"toilet\", \"tv\", \"laptop\", \"mouse\",\n \"remote\", \"keyboard\", \"cell phone\",\n \"microwave\", \"oven\", \"toaster\", \"sink\", \"refrigerator\", \"book\", \"clock\",\n \"vase\", \"scissors\", \"teddy bear\",\n \"hair drier\", \"toothbrush\"])\n","sub_path":"model_adapter.py","file_name":"model_adapter.py","file_ext":"py","file_size_in_byte":17075,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"587957519","text":"#!/usr/bin/env python\n\"\"\"Grapical User Interface for X-ray beam stabilization\nFriedrich Schotte, Nov 23, 2015 - Mar 6, 2017\n\"\"\"\nfrom pdb import pm # for debugging\nfrom logging import debug,warn,info,error\n##import logging; logging.basicConfig(level=logging.DEBUG)\nfrom xray_beam_stabilization import Xray_Beam_Stabilization\nfrom Panel import BasePanel,PropertyPanel,ButtonPanel,TogglePanel,TweakPanel\nfrom BeamProfile_window import BeamProfile\nfrom TimeChart import TimeChart\nfrom persistent_property import persistent_property\nimport wx\n__version__ = \"1.2\" # TimeChart new API\n\nclass Panel(BasePanel,Xray_Beam_Stabilization):\n standard_view = [\n \"Image\",\n \"Image filename\",\n \"Nominal X [mm]\",\n \"Nominal Y [mm]\",\n \"Beam X [mm]\",\n \"Beam Y [mm]\",\n \"Calibration X [mrad/mm]\",\n \"Calibration Y [V/mm]\",\n \"Control X [mrad]\",\n \"Control Y [V]\",\n \"Control X corr. [mrad]\",\n \"Control Y corr. [V]\",\n \"Correct X\",\n \"Correct Y\",\n ]\n saturation_level = persistent_property(\"saturation_level\",10000.0) # counts\n\n def __init__(self,parent=None):\n Xray_Beam_Stabilization.__init__(self)\n \n parameters = [\n [[BeamProfile, \"Image\", self ],{}],\n [[TimeChart, \"History X\", self.log,\"date time\",\"x\"],{\"axis_label\":\"X [mm]\",\"name\":self.name+\".TimeChart\"}],\n [[TimeChart, \"History Y\", self.log,\"date time\",\"y\"],{\"axis_label\":\"Y [mm]\",\"name\":self.name+\".TimeChart\"}],\n [[TimeChart, \"History Control X\", self.log,\"date time\",\"x_control\"],{\"axis_label\":\"Control X [mrad]\",\"name\":self.name+\".TimeChart\"}],\n [[TimeChart, \"History Control Y\", self.log,\"date time\",\"y_control\"],{\"axis_label\":\"Control Y [V]\" ,\"name\":self.name+\".TimeChart\"}],\n [[PropertyPanel,\"History Length\", self,\"history_length\" ],{}],\n [[PropertyPanel,\"History filter\", self,\"history_filter\" ],{\"choices\":[\"\",\"1pulses\",\"5pulses\"]}],\n [[PropertyPanel,\"Logfile\", self.log,\"filename\" ],{}],\n [[PropertyPanel,\"Image filename\", self,\"image_basename\" ],{\"read_only\":True}],\n [[PropertyPanel,\"Image timestamp\", self,\"image_timestamp\" ],{\"type\":\"date\",\"read_only\":True}],\n [[PropertyPanel,\"Analysis filter\", self,\"analysis_filter\" ],{\"choices\":[\"\",\"1pulses\",\"5pulses\"]}],\n [[PropertyPanel,\"Image usable\", self,\"image_OK\" ],{\"type\":\"Unusable/OK\",\"read_only\":True}],\n [[PropertyPanel,\"Overloaded pixels\", self,\"image_overloaded\" ],{\"read_only\":True}],\n [[PropertyPanel,\"Signal-to-noise ratio\", self,\"SNR\" ],{\"digits\":1,\"read_only\":True}],\n [[TogglePanel, \"Auto update\", self,\"auto_update\" ],{\"type\":\"Off/On\"}],\n [[TweakPanel, \"Average count\", self,\"average_samples\" ],{\"digits\":0}],\n [[TweakPanel, \"ROI center X [mm]\", self,\"x_ROI_center\" ],{\"digits\":3}],\n [[TweakPanel, \"ROI center Y [mm]\", self,\"y_ROI_center\" ],{\"digits\":3}],\n [[TweakPanel, \"ROI width [mm]\", self,\"ROI_width\" ],{\"digits\":3}],\n [[TweakPanel, \"Saturation level\", self,\"saturation_level\" ],{\"digits\":0}],\n [[TweakPanel, \"Nominal X [mm]\", self,\"x_nominal\" ],{\"digits\":3}],\n [[TweakPanel, \"Nominal Y [mm]\", self,\"y_nominal\" ],{\"digits\":3}],\n [[PropertyPanel,\"Beam X [mm]\", self,\"x_beam\" ],{\"digits\":3,\"read_only\":True}],\n [[PropertyPanel,\"Beam Y [mm]\", self,\"y_beam\" ],{\"digits\":3,\"read_only\":True}],\n [[PropertyPanel,\"Beam X avg. [mm]\", self,\"x_average\" ],{\"digits\":3,\"read_only\":True}],\n [[PropertyPanel,\"Beam Y avg. [mm]\", self,\"y_average\" ],{\"digits\":3,\"read_only\":True}],\n [[TweakPanel, \"Calibration X [mrad/mm]\",self,\"x_gain\" ],{\"digits\":4}],\n [[TweakPanel, \"Calibration Y [V/mm]\", self,\"y_gain\" ],{\"digits\":4}],\n [[PropertyPanel,\"Control X PV\", self,\"x_PV\" ],{}],\n [[PropertyPanel,\"Control Y PV\", self,\"y_PV\" ],{}],\n [[PropertyPanel,\"Control X read PV\", self,\"x_read_PV\" ],{}],\n [[PropertyPanel,\"Control Y read PV\", self,\"y_read_PV\" ],{}],\n [[TweakPanel, \"Control X [mrad]\", self,\"x_control\" ],{\"digits\":4}],\n [[TweakPanel, \"Control Y [V]\", self,\"y_control\" ],{\"digits\":4}],\n [[TweakPanel, \"Control X avg. [mrad]\", self,\"x_control_average\" ],{\"digits\":4}],\n [[TweakPanel, \"Control Y avg. [V]\", self,\"y_control_average\" ],{\"digits\":4}],\n [[PropertyPanel,\"Control X corr. [mrad]\", self,\"x_control_corrected\"],{\"digits\":4,\"read_only\":True}],\n [[PropertyPanel,\"Control Y corr. [V]\", self,\"y_control_corrected\"],{\"digits\":4,\"read_only\":True}],\n [[TogglePanel, \"Stabilization X\", self,\"x_enabled\" ],{\"type\":\"Off/On\"}],\n [[TogglePanel, \"Stabilization Y\", self,\"y_enabled\" ],{\"type\":\"Off/On\"}],\n [[ButtonPanel, \"Correct X\", self,\"apply_x_correction\" ],{\"label\":\"Correct X\"}],\n [[ButtonPanel, \"Correct Y\", self,\"apply_y_correction\" ],{\"label\":\"Correct Y\"}],\n [[ButtonPanel, \"Correct Position\", self,\"apply_correction\" ],{\"label\":\"Correct\"}],\n ]\n BasePanel.__init__(self,\n parent=parent,\n name=self.name,\n title=\"X-Ray Beam Stabilization\",\n parameters=parameters,\n standard_view=self.standard_view,\n refresh=True,\n live=True,\n )\n \n\nif __name__ == '__main__':\n import logging; logging.basicConfig(level=logging.DEBUG)\n # Needed to initialize WX library\n if not \"app\" in globals(): app = wx.App(redirect=False)\n panel = Panel()\n app.MainLoop()\n","sub_path":"XRayBeamStabilizationPanel.py","file_name":"XRayBeamStabilizationPanel.py","file_ext":"py","file_size_in_byte":6297,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"379553620","text":"num=12\r\nwin = False\r\nfor i in range(1,4):\r\n guess=eval(input(\"Make a guess: \"))\r\n if guess == num:\r\n win = True\r\n break;\r\nif not win: \r\n print(\"No more guesses, you lose\")\r\nelse:\r\n print(\"You have it\");\r\n","sub_path":"C05_feb8/from_quiz.py","file_name":"from_quiz.py","file_ext":"py","file_size_in_byte":231,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"272732181","text":"from __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nfrom typing import List, Text\n\nimport absl\nimport tensorflow as tf\nimport keras\nimport keras.backend as K\nfrom keras.utils import generic_utils\nfrom PIL import Image\nimport PIL\nfrom keras.models import Sequential, Model, load_model, model_from_json\nfrom keras import layers\nfrom keras.layers import Dense, Flatten, Dropout, Activation, LeakyReLU, Reshape, Concatenate, Input\nfrom keras.layers import Conv2D, UpSampling2D, Conv2DTranspose, MaxPool2D\nfrom keras.layers.normalization import BatchNormalization\nfrom keras import optimizers, losses\nfrom copy import deepcopy\nfrom tfx.components.trainer.fn_args_utils import FnArgs\nfrom IPython.display import display, Image, Markdown, SVG\nfrom keras.utils.vis_utils import model_to_dot\nimport itertools\nimport numpy as np\nIMAGE_SZ = 128\nIMAGE_KEY = 'image_raw'\nLABEL_KEY = 'label'\n# logdir = \"/content/tfx/logs/train_data/\"\n\ndef transformed_name(key):\n return key + '_xf'\n\ndef generator_conv_block(layer_input, filters, kernel_size, name,strides, padding='same', activation='relu', norm=True, dilation_rate=1):\n conv = Conv2D(filters, name=name,kernel_size=kernel_size, strides=strides, dilation_rate=(dilation_rate, dilation_rate), padding=padding)(layer_input)\n if activation=='relu':\n conv = Activation('relu')(conv)\n if norm:\n conv = BatchNormalization()(conv)\n return conv\n\ndef generator_Deconv_block(layer_input, filters, kernel_size, strides,name, padding='same', activation='relu'):\n deconv = Conv2DTranspose(filters, name=name,kernel_size = kernel_size, strides = strides, padding = 'same')(layer_input)\n if activation == 'relu':\n deconv = Activation('relu')(deconv)\n return deconv\n\n\ndef build_generator():\n\n generator_input = Input(name='image_raw', shape=(128, 128, 3)) ## These are masked or Padded Images of shape 128x128 but the 0 to 32 and 96 to 128 will be masked\n\n ##### Encoder #####\n g1 = generator_conv_block(generator_input, 64, 5, strides=1,name=\"Gen_Layer_1\")\n g2 = generator_conv_block(g1, 128, 3, strides=2,name=\"Gen_Layer_2\")\n g3 = generator_conv_block(g2, 256, 3, strides=1, name=\"Gen_Layer_3\")\n # Dilated Convolutions\n g4 = generator_conv_block(g3, 256, 3, strides=1, dilation_rate=2,name=\"Gen_Layer_4\")\n g5 = generator_conv_block(g4, 256, 3, strides=1, dilation_rate=4,name=\"Gen_Layer_5\")\n g6 = generator_conv_block(g5, 256, 3, strides=1, dilation_rate=8,name=\"Gen_Layer_6\")\n g7 = generator_conv_block(g6, 256, 3, strides=1,name=\"Gen_Layer_7\")\n\n #### Decoder ####\n g8 = generator_Deconv_block(g7, 128, 4, strides=2,name=\"Gen_Layer_8\")\n g9 = generator_conv_block(g8, 64, 3, strides=1,name=\"Gen_Layer_9\")\n \n generator_output = Conv2D(3, kernel_size=3, name=\"Gen_Layer_10\",strides=(1,1), activation='sigmoid', padding='same', dilation_rate=(1,1))(g9) ### Some people used 'tanh' instead of sigmoid check later\n \n return Model(generator_input, generator_output)\n\n#discriminator\ndef create_discriminator_layer(layer_input, filters, kernel_size = 5, strides = 2, padding = 'same', activation='leakyrelu', dropout_rate=0.25, norm=True,name='layer'):\n conv = Conv2D(filters=filters, kernel_size=kernel_size, strides=strides, padding=padding, name=name+'conv2d')(layer_input)\n if activation == 'leakyrelu':\n conv = LeakyReLU(alpha=0.2,name=name+'leakyRelu')(conv)\n if dropout_rate:\n conv = Dropout(rate=dropout_rate,name=name+'dropRate')(conv)\n if norm:\n conv = BatchNormalization(name=name+'batch')(conv)\n return conv\n\ndef build_discriminator():\n\n discriminator_input = Input(name='image_raw', shape=(128, 128, 3)) ## These are masked or Padded Images of shape 128x128 but the 0 to 32 and 96 to 128 will be masked\n\n model = create_discriminator_layer(discriminator_input, 32, 5, norm=False,name='layer1')\n model = create_discriminator_layer(model, 64, 5, 2,name='layer2')\n model = create_discriminator_layer(model, 64, 5, 2,name='layer3')\n model = create_discriminator_layer(model, 64, 5, 2,name='layer4')\n model = create_discriminator_layer(model, 64, 5, 2,name='layer5')\n\n model = Flatten()(model)\n model = Dense(512, activation='relu')(model)\n\n discriminator_output = Dense(1, activation='sigmoid')(model)\n\n return Model(discriminator_input, discriminator_output)\n#gan starts here \ndef build_gan(generator,discriminator):\n discriminator.trainable = False\n\n gan_input = Input(name='image_raw', shape=(128, 128, 3))\n print(\"GAN INPUT INFO\")\n print(type(gan_input))\n print(gan_input.shape)\n print(type(generator))\n generated_image = generator(gan_input)\n print(\"Generator output shape:\", generated_image.shape)\n gan_output = discriminator(generated_image)\n \n gan = Model(gan_input,[generated_image, gan_output])\n return gan\n\n\n###############################\n##Feature engineering functions\ndef feature_engg_features(features):\n #resize and decode\n image = tf.io.decode_raw(features['image_raw'], tf.uint8)\n image = tf.reshape(image, [-1, 128, 128, 3])\n image = image/255\n features['image_raw'] = image\n\n return features\n\ndef label_engg_features(label):\n #resize and decode\n label = tf.io.decode_raw(label, tf.uint8)\n label = tf.reshape(label, [-1,128, 128, 3])\n label = label/255\n return label\n \n#To be called from TF\ndef feature_engg(features, label):\n #Add new features\n features = feature_engg_features(features)\n label = label_engg_features(label)\n\n return(features, label)\n\ndef make_input_fn(data_root, mode, vnum_epochs = None, batch_size = 512):\n def decode_tfr(serialized_example):\n # 1. define a parser\n features = tf.io.parse_example(\n serialized_example,\n # Defaults are not specified since both keys are required.\n features={\n 'image_raw': tf.io.FixedLenFeature([], tf.string),\n 'label': tf.io.FixedLenFeature([], tf.string),\n })\n\n return features, features['label']\n\n def _input_fn(v_test=False):\n # Get the list of files in this directory (all compressed TFRecord files)\n tfrecord_filenames = tf.io.gfile.glob(data_root)\n\n # Create a `TFRecordDataset` to read these files\n dataset = tf.data.TFRecordDataset(tfrecord_filenames, compression_type=\"GZIP\")\n\n if mode == tf.estimator.ModeKeys.TRAIN:\n num_epochs = vnum_epochs # indefinitely\n else:\n num_epochs = 1 \n\n dataset = dataset.batch(batch_size)\n dataset = dataset.prefetch(buffer_size = batch_size)\n\n #Convert TFRecord data to dict\n dataset = dataset.map(decode_tfr)\n\n #Feature engineering\n dataset = dataset.map(feature_engg)\n\n if mode == tf.estimator.ModeKeys.TRAIN:\n num_epochs = vnum_epochs # indefinitely\n dataset = dataset.shuffle(buffer_size = batch_size)\n else:\n num_epochs = 1 # end-of-input after this\n\n dataset = dataset.repeat(num_epochs) \n \n if v_test == True:\n print(next(dataset.__iter__()))\n \n return dataset\n return _input_fn\n\ndef save_model(model, model_save_path):\n @tf.function\n def serving(image_raw):\n ##Feature engineering( calculate distance ) \n\n payload = {\n 'image_raw': image_raw\n }\n \n predictions = model(payload)\n return predictions\n\n serving = serving.get_concrete_function(image_raw=tf.TensorSpec([None, 128,128,3], dtype=tf.uint8, name='image_raw')\n )\n # version = \"1\" #{'serving_default': call_output}\n tf.saved_model.save(\n model,\n model_save_path + \"/\",\n signatures=serving\n )\n\n\ndef show_images(dataset):\n for data in itertools.islice(dataset, None, 5):\n images, label = data\n masked_images = images['image_raw']\n print(\"masked image\",masked_images.shape)\n img_norm = (np.asarray(masked_images[0])*255.0).astype(np.uint8)\n print(\"image_norm shape\",img_norm.shape)\n display(PIL.Image.fromarray(img_norm,'RGB'))\n print(\"real image\")\n \n img_norm = (np.asarray(label[0])*255.0).astype(np.uint8)\n display(PIL.Image.fromarray(img_norm,'RGB'))\n\n# Main function called by TFX\ndef run_fn(fn_args: FnArgs):\n \"\"\"\n Train the model based on given args.\n Args:\n fn_args: Holds args used to train the model as name/value pairs.\n \"\"\"\n print(\"Starting Training!!!!!!!!!!!!!!\")\n # Getting custom arguments\n batch_size = fn_args.custom_config['batch_size']\n gen_epoch = fn_args.custom_config['gen_epoch']\n dis_epoch = fn_args.custom_config['dis_epoch']\n gan_epoch = fn_args.custom_config['gan_epoch']\n data_size = fn_args.custom_config['data_size']\n\n steps_per_epoch = 1\n\n train_dataset = make_input_fn(data_root = fn_args.train_files,\n mode = tf.estimator.ModeKeys.TRAIN,\n batch_size = batch_size)()\n\n validation_dataset = make_input_fn(data_root = fn_args.eval_files,\n mode = tf.estimator.ModeKeys.EVAL,\n batch_size = batch_size)() \n\n mirrored_strategy = tf.distribute.MirroredStrategy()\n with mirrored_strategy.scope():\n discriminator = build_discriminator()\n discriminator.trainable = False\n discriminator.compile(loss = losses.MSE, optimizer = optimizers.Adam(lr=0.0001, beta_1=0.5))\n\n generator = build_generator()\n generator.compile(loss = 'mse', optimizer = optimizers.Adam(lr=0.0001, beta_1=0.5))\n\n gan = build_gan(generator,discriminator)\n alpha=0.0004\n gan.compile(loss = [losses.MSE, losses.MSE], optimizer = optimizers.Adam(lr=0.0001, beta_1=0.5), loss_weights = [1, alpha])\n\n tensorboard_callback = tf.keras.callbacks.TensorBoard(log_dir=fn_args.model_run_dir, update_freq='batch')\n\n print(\"Generator Model Summary\")\n print(generator.summary())\n print(\"Discriminator Model Summary\")\n print(discriminator.summary())\n print(\"Gan Model Summary\")\n print(gan.summary())\n\n show_images(train_dataset)\n # Training Generator\n print(\"Training Generator\")\n generator.fit(\n train_dataset,\n epochs = gen_epoch,\n steps_per_epoch=steps_per_epoch,\n validation_data=validation_dataset,\n validation_steps=2,\n callbacks=[tensorboard_callback])\n\n # Training Discriminator\n print(\"Training Discriminator\")\n for current_epoch in range(dis_epoch):\n print('Epoch {}/{}'.format(current_epoch, dis_epoch))\n progressbar = generic_utils.Progbar(steps_per_epoch)\n for data in itertools.islice(train_dataset, None, steps_per_epoch):\n images, label = data\n masked_images = images['image_raw']\n\n fake_images = generator.predict(masked_images)\n disc_loss_real = discriminator.train_on_batch(label, np.ones(len(label), dtype='float32'))\n disc_loss_fake = discriminator.train_on_batch(fake_images, np.zeros(len(fake_images), dtype='float32'))\n\n disc_loss = (disc_loss_real + disc_loss_fake)/2\n progressbar.add(1, values = [('Discriminator Loss', disc_loss)])\n\n # Training Gan\n print(\"Training Gan\")\n for current_epoch in range(gan_epoch):\n print('Epoch {}/{}'.format(current_epoch, gan_epoch))\n progressbar = generic_utils.Progbar(steps_per_epoch)\n for data in itertools.islice(train_dataset, None, steps_per_epoch):\n images, label = data\n masked_images = images['image_raw']\n fake_images = generator.predict(masked_images)\n\n disc_loss_real = discriminator.train_on_batch(label, np.ones(len(label), dtype='float32'))\n disc_loss_fake = discriminator.train_on_batch(fake_images, np.zeros(len(fake_images), dtype='float32'))\n\n disc_loss = (disc_loss_real + disc_loss_fake)/2\n\n gan_loss = gan.train_on_batch(masked_images, [label, np.ones((len(label), 1), dtype='float32')])\n\n progressbar.add(1, values = [('Discriminator Loss', disc_loss), ('GAN Loss', gan_loss[0]), ('Generator Loss', gan_loss[1])])\n\n save_model(generator,fn_args.serving_model_dir)\n print('serving model dir',fn_args.serving_model_dir)\n","sub_path":"kubeflow/model/trainer.py","file_name":"trainer.py","file_ext":"py","file_size_in_byte":12479,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"55022475","text":"import csv, png\n\nwith open('GZ_clean_abridged.csv') as inputfile:\n\tdata = csv.DictReader(inputfile)\n\twith open('training_data_abridged.csv', 'w', newline='') as outputfile:\n\t\twriter = csv.DictWriter(outputfile, ['OBJID', 'pixels', 'class'])\n\t\twriter.writeheader()\n\t\t\n\t\tfor line in data:\n\t\t\tr = png.Reader(\"./images/\" + line['OBJID'] + \".png\")\n\t\t\twidth, height, pixels, metadata = r.asRGB()\n\n\t\t\ti = 0\n\t\t\tluminance = [0.2126, 0.7152, 0.0722]\n\t\t\tlum_sum = 0\n\t\t\timg_lum = []\n\n\t\t\t\n\t\t\tfor row in pixels:\n\t\t\t\tfor p in row:\n\t\t\t\t\tlum_sum += p * luminance[i]\n\t\t\t\t\ti += 1\n\t\t\t\t\tif (i > 2):\n\t\t\t\t\t\ti = 0\n\t\t\t\t\t\timg_lum.append(lum_sum)\n\t\t\t\t\t\tlum_sum = 0\n\n\t\t\tmax_lum = max(img_lum)\n\t\t\timg_lum = [str(l / max_lum) for l in img_lum]\n\n\t\t\t# stringify img_lum array and add to csv file\n\t\t\tc = '0'\n\t\t\tif (line['ELLIPTICAL'] == '1'):\n\t\t\t\tc = '1'\n\t\t\tif (line['UNCERTAIN'] == '1'):\n\t\t\t\tc = '2'\n\n\t\t\tpixels_string = ' '.join(img_lum)\n\t\t\t#print(pixels_string)\n\t\t\trow = {'OBJID': line['OBJID'], 'pixels': pixels_string, 'class': c}\n\t\t\twriter.writerow(row)\n\t\t\t\t\n\n\n","sub_path":"training.py","file_name":"training.py","file_ext":"py","file_size_in_byte":1034,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"6541262","text":"import os\nimport sys\n\nROOT_PATH = os.path.dirname(os.path.abspath(sys.argv[0])) + os.sep\n\nINI_PATH = ROOT_PATH + 'config.ini'\nINI_SECTION = 'ZebraServer'\nINI_OPTION = 'printer_name'\n\nSOCKET_HOST = ''\nSOCKET_PORT = 5000\nSOCKET_MAX_CLIENT = 5\nSOCKET_BUFFER = 1024","sub_path":"package/config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":265,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"414055280","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 ('clinic', '0002_auto_20150302_0021'),\n ]\n\n operations = [\n migrations.AddField(\n model_name='doctor',\n name='photo',\n field=models.FilePathField(verbose_name='/home/bulat/projects/Okulist/clinic/static/clinic', default='/home/bulat/projects/Okulist/clinic/static/clinic/'),\n preserve_default=False,\n ),\n ]\n","sub_path":"clinic/migrations/0003_doctor_photo.py","file_name":"0003_doctor_photo.py","file_ext":"py","file_size_in_byte":551,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"579161225","text":"import tensorflow as tf\nimport keras\nimport cv2\nfrom PIL import Image \nimport numpy as np\nfrom keras.models import Model, model_from_json, save_model\nfrom keras.layers import Reshape, Input, Lambda, Dense, Dropout, Activation, Flatten, Input, Conv2D, MaxPooling2D\nfrom keras.layers.merge import add\nfrom keras import regularizers\n\nweights_path= \"./dronet/best_weights.h5\"\njson_model_path=\"./dronet/model_struct.json\"\n\nwith open(json_model_path, 'r') as json_file:\n loaded_model_json = json_file.read()\noldModel = model_from_json(loaded_model_json)\noldModel.load_weights(weights_path)\noldModel.compile(loss='mse', optimizer='sgd')\noldModel.summary()\n\noutput_dim = 1\nimg_input = Input(shape=(200, 200, 1))\nx1 = Lambda(lambda x: x*(1.0/255.0))(img_input)\nx1 = Conv2D(32, (5, 5), strides=[2,2], padding='same')(x1)\n\nx1 = MaxPooling2D(pool_size=(3, 3), strides=[2,2])(x1)\n\n# First residual block\nx2 = keras.layers.normalization.BatchNormalization()(x1)\n\nx2 = Activation('relu')(x2)\n\nx2 = Conv2D(32, (3, 3), strides=[2,2], padding='same',\n kernel_initializer=\"he_normal\",\n kernel_regularizer=regularizers.l2(1e-4))(x2)\n\nx2 = keras.layers.normalization.BatchNormalization()(x2)\n\nx2 = Activation('relu')(x2)\n\n\nx2 = Conv2D(32, (3, 3), padding='same',\n kernel_initializer=\"he_normal\",\n kernel_regularizer=regularizers.l2(1e-4))(x2)\n\nx1 = Conv2D(32, (1, 1), strides=[2,2], padding='same')(x1)\n\nx3 = add([x1, x2])\n\n\n# Second residual block\nx4 = keras.layers.normalization.BatchNormalization()(x3)\nx4 = Activation('relu')(x4)\nx4 = Conv2D(64, (3, 3), strides=[2,2], padding='same',\n kernel_initializer=\"he_normal\",\n kernel_regularizer=regularizers.l2(1e-4))(x4)\n\nx4 = keras.layers.normalization.BatchNormalization()(x4)\nx4 = Activation('relu')(x4)\nx4 = Conv2D(64, (3, 3), padding='same',\n kernel_initializer=\"he_normal\",\n kernel_regularizer=regularizers.l2(1e-4))(x4)\n\nx3 = Conv2D(64, (1, 1), strides=[2,2], padding='same')(x3)\nx5 = add([x3, x4])\n\n# Third residual block\nx6 = keras.layers.normalization.BatchNormalization()(x5)\nx6 = Activation('relu')(x6)\nx6 = Conv2D(128, (3, 3), strides=[2,2], padding='same',\n kernel_initializer=\"he_normal\",\n kernel_regularizer=regularizers.l2(1e-4))(x6)\n\nx6 = keras.layers.normalization.BatchNormalization()(x6)\nx6 = Activation('relu')(x6)\nx6 = Conv2D(128, (3, 3), padding='same',\n kernel_initializer=\"he_normal\",\n kernel_regularizer=regularizers.l2(1e-4))(x6)\n\nx5 = Conv2D(128, (1, 1), strides=[2,2], padding='same')(x5)\nx7 = add([x5, x6])\n\nx = Flatten()(x7)\nx = Activation('relu')(x)\nx = Dropout(0.5)(x)\n\n# Steering channel\nsteer = Dense(output_dim)(x)\n\n# Collision channel\ncoll = Dense(output_dim)(x)\ncoll = Activation('sigmoid')(coll)\n\n# Define steering-collision model\nnewModel = Model(inputs=[img_input], outputs=[steer, coll])\nnewModel.summary()\n\nnewModel.set_weights(oldModel.get_weights())\n\n\nmodel_json = newModel.to_json()\nwith open(\"./dronet/model.json\", \"w\") as json_file:\n json_file.write(model_json)\n# serialize weights to HDF5\nnewModel.save_weights(\"./dronet/model_weights.h5\")\nprint(\"Saved model to disk\")\nsave_model(newModel,'./dronet/model.h5')\nconverter = tf.lite.TFLiteConverter.from_keras_model(newModel)\ntfmodel = converter.convert()\nopen (\"./dronet/model.tflite\" , \"wb\") .write(tfmodel)\n\n\n\nnewModel.compile(loss='mse', optimizer='sgd')\nimg = Image.open('./images/1.jpg')\nimg = np.asarray(img)\ncv_image = np.asarray(img.reshape(200,200,1))\nouts = newModel.predict_on_batch([cv_image[None]])\nsteer, coll = outs[0][0], outs[1][0]\nprint(steer)\nprint(coll)\n","sub_path":"dronet_modifier.py","file_name":"dronet_modifier.py","file_ext":"py","file_size_in_byte":3637,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"57966310","text":"from _thread import get_ident # 获取线程的唯一标识\n# from flask import Flask\nimport threading\n\n# 自定义一个支持协程的threading\n\n# 1.先实现基本的threading\n# 将唯一标识号当作字典的key,从而隔离各个线程之间的数据\n\n\nclass Local(object):\n def __init__(self):\n self.storage = {}\n self.get_ident = get_ident()\n\n def set(self, k, v):\n ident = get_ident\n orgin = self.storage.get(ident)\n if not orgin:\n orgin = {k: v}\n else:\n orgin[k] = v\n self.storage[ident] = orgin\n\n def get(self, k):\n ident = get_ident\n orgin = self.storage.get(ident)\n if not orgin:\n return None\n return orgin.get(k, None)\n\n\nlocal_values = Local()\n\n\ndef task(num):\n local_values.set('name', num)\n import time\n time.sleep(1)\n print(local_values.get('name'), threading.current_thread().name)\n\n\nfor i in range(20):\n th = threading.Thread(target=task, args=(i,), name='thread %s' % i)\n th.start()\n\n# app = Flask(__name__)\n#\n#\n# # @app.route('/')\n# # def hello_world():\n# # return 'Hello World!'\n# #\n# #\n# # if __name__ == '__main__':\n# # app.run()\n","sub_path":"context_process/threading_base.py","file_name":"threading_base.py","file_ext":"py","file_size_in_byte":1204,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"523083129","text":"from django.apps.registry import apps\nfrom django.conf import settings\nfrom django.core.management import call_command\nfrom django.core.management.base import BaseCommand\nfrom django.utils.encoding import smart_bytes\nfrom datetime import datetime\nfrom io import BytesIO\nfrom json import dump\nfrom os import path\nfrom tarfile import TarInfo, TarFile\nfrom ... import __version__\nfrom django.db import models\n\n\nclass MixedIO(BytesIO):\n \"\"\"\n A BytesIO that accepts and encodes Unicode data.\n This class was born out of a need for a BytesIO that would accept writes of\n both bytes and Unicode data - allowing identical usage from both Python 2\n and Python 3.\n \"\"\"\n\n def rewind(self):\n \"\"\"\n Seeks to the beginning and returns the size.\n \"\"\"\n size = self.tell()\n self.seek(0)\n return size\n\n def write(self, data):\n \"\"\"\n Writes the provided data, converting Unicode to bytes as needed.\n \"\"\"\n BytesIO.write(self, smart_bytes(data))\n\n\nclass Command(BaseCommand):\n \"\"\"\n Create a compressed archive of database tables and uploaded media.\n \"\"\"\n\n help = \"Create a compressed archive of database tables and uploaded media.\"\n\n def handle(self, *args, **kwargs):\n \"\"\"\n Process the command.\n \"\"\"\n tar = self._create_archive()\n self._dump_db(tar)\n self._dump_files(tar)\n self._dump_meta(tar)\n self.stdout.write(\"Backup completed.\")\n\n def _create_archive(self):\n \"\"\"\n Create the archive and return the TarFile.\n \"\"\"\n filename = getattr(settings, 'surveyArchive', '%Y-%m-%d--%H-%M-%S')\n fmt = getattr(settings, '.zip', 'bz2')\n absolute_path = path.join(\n getattr(settings, 'SurveyRepo', ''),\n '%s.tar.%s' % (datetime.today().strftime(filename), fmt)\n )\n return TarFile.open(absolute_path, 'w:%s' % fmt)\n\n def _dump_db(self, tar):\n \"\"\"\n Dump the rows in each model to the archive.\n \"\"\"\n\n # Determine the list of models to exclude\n exclude = getattr(settings, 'ARCHIVE_EXCLUDE', (\n 'auth.Permission',\n 'contenttypes.ContentType',\n 'sessions.Session',\n ))\n\n # Dump the tables to a MixedIO\n data = MixedIO()\n call_command('dumpdata', all=True, format='json', exclude=exclude, stdout=data)\n info = TarInfo('data.json')\n info.size = data.rewind()\n tar.addfile(info, data)\n\n def _dump_files(self, tar):\n \"\"\"\n Dump all uploaded media to the archive.\n \"\"\"\n\n # Loop through all models and find FileFields\n for model in apps.get_models():\n\n # Get the name of all file fields in the model\n field_names = []\n for field in model._meta.fields:\n if isinstance(field, models.FileField):\n field_names.append(field.name)\n\n # If any were found, loop through each row\n if len(field_names):\n for row in model.objects.all():\n for field_name in field_names:\n field = getattr(row, field_name)\n if field:\n field.open()\n info = TarInfo(field.name)\n info.size = field.size\n tar.addfile(info, field)\n field.close()\n\n def _dump_meta(self, tar):\n \"\"\"\n Dump metadata to the archive.\n \"\"\"\n data = MixedIO()\n dump({'version': __version__}, data)\n info = TarInfo('meta.json')\n info.size = data.rewind()\n tar.addfile(info, data)\n","sub_path":"survey/management/commands/archive.py","file_name":"archive.py","file_ext":"py","file_size_in_byte":3739,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"608518283","text":"# --------------------------------------------------------\n# Tensorflow GCA-Net\n# Licensed under The MIT License [see LICENSE for details]\n# Written by Yimeng Li\n# --------------------------------------------------------\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport tensorflow as tf\nfrom nltk.corpus import wordnet as wn\nimport json\nimport numpy as np\nfrom model.config import cfg\n\nanswer_dict = json.load(open('/home/mm/workspace/VQA-oqv/dataset/activityNet/qa_anno/dict/answer_one_dic.json'))\nclass Network(object):\n def __init__(self, handle_types, handle_shapes):\n self._predictions = {}\n self._losses = {}\n self._layers = {}\n self._act_summaries = []\n self._score_summaries = {}\n self._train_summaries = []\n self._event_summaries = {}\n self.handle_types = handle_types\n self.handle_shapes = handle_shapes\n\n def _add_act_summary(self, tensor):\n tf.summary.histogram('ACT/' + tensor.op.name + '/activations', tensor)\n tf.summary.scalar('ACT/' + tensor.op.name + '/zero_fraction',\n tf.nn.zero_fraction(tensor))\n\n def _add_score_summary(self, key, tensor):\n tf.summary.histogram('SCORE/' + tensor.op.name + '/' + key + '/scores', tensor)\n\n def _add_train_summary(self, var):\n tf.summary.histogram('TRAIN/' + var.op.name, var)\n\n def _build_co_atten(self, activate_tensor, object_tensor, shapes, scope):\n # activate_tensor [batch_size, reduce_dim, activate_dim]\n # object_tensor [batch_size, reduce_dim, oobject_dim]\n\n with tf.variable_scope(scope):\n activate_reduce = shapes[0]\n activate_dim = shapes[1]\n object_reduce = shapes[2]\n object_dim = shapes[3]\n atten_size = shapes[4]\n\n # activate att step.1\n embedding_activate = tf.reshape(activate_tensor, [-1,activate_dim])\n w_embedding = tf.get_variable('activate_w', [activate_dim, atten_size], initializer=self.initializer, regularizer=self.weights_regularizer)\n # [batch_size*activate_reduce, atten_size]\n embeded_activate = tf.nn.tanh(tf.matmul(embedding_activate, w_embedding))\n w_activate_g1 = tf.get_variable('w_activate_g1', [atten_size, 1], initializer=self.initializer, regularizer=self.weights_regularizer)\n activate_h1 = tf.reshape(tf.matmul(embeded_activate, w_activate_g1), [-1, activate_reduce])\n activate_p1 = tf.nn.softmax(activate_h1, dim=-1)\n activate_p1 = tf.reshape(activate_p1, [-1, 1, activate_reduce])\n # [batch_size, activate_dim]\n feature_activateAtt1 = tf.reshape(tf.matmul(activate_p1, activate_tensor), (-1, activate_dim))\n\n # obj att step\n embedding_object = tf.reshape(object_tensor, [-1, object_dim])\n w_object = tf.get_variable('object_w', [object_dim, atten_size], initializer=self.initializer, regularizer=self.weights_regularizer)\n # [batch_size*object_reduce, atten_size]\n obj_embedded = tf.matmul(embedding_object, w_object)\n\n w_activateAtt1_embed = tf.get_variable('w_activateAtt1_embed', [activate_dim, atten_size], initializer=self.initializer, regularizer=self.weights_regularizer)\n activateAtt1_embeded = tf.matmul(feature_activateAtt1, w_activateAtt1_embed)\n # [batch_size, object_reduce, ATTEN_SIZE]\n activateAtt1_broadcast = tf.tile(tf.reshape(activateAtt1_embeded, [-1,1,atten_size]), [1,object_reduce,1])\n # [batch_size*object_reduce, ATTEN_SIZE]\n activateAtt1_broadcast = tf.reshape(activateAtt1_broadcast, [-1,atten_size])\n obj_h = tf.nn.tanh(tf.add(obj_embedded, activateAtt1_broadcast))\n obj_h = tf.reshape(obj_h, [-1, atten_size])\n w_obj_g = tf.get_variable('w_obj_g', [atten_size, 1], initializer=self.initializer, regularizer=self.weights_regularizer)\n # [batch_size, object_reduce]\n obj_p = tf.reshape(tf.matmul(obj_h, w_obj_g), [-1,object_reduce])\n obj_p = tf.nn.softmax(obj_p, dim=-1)\n out_ojb_p= tf.tile(tf.reshape(obj_p, (-1,object_reduce,1)), (1,1,object_dim))\n # [batch_size, object_reduce, object_dim]\n out_feature_objAtt = tf.multiply(out_ojb_p, object_tensor)\n # [batch_size, 1, object_reduce]\n obj_p = tf.reshape(obj_p, [-1, 1, object_reduce])\n # [batch_size, object_dim]\n feature_objAtt = tf.reshape(tf.matmul(obj_p, object_tensor), (-1, object_dim))\n # [batch_size, object_dim]\n\n # activate att step2\n activate_embed_2 = tf.reshape(activate_tensor, [-1, activate_dim])\n w_activate_embed2 = tf.get_variable('activate_embed2', [activate_dim, atten_size], initializer=self.initializer, regularizer=self.weights_regularizer)\n activate_embeded_2 = tf.nn.tanh(tf.matmul(activate_embed_2, w_activate_embed2))\n # [batch_size, activate_reduce, atten_size]\n activate_embeded_2 = tf.reshape(activate_embeded_2, [-1, activate_reduce, atten_size])\n\n w_objAtt_fc = tf.get_variable('w_objAtt_fc', [object_dim, atten_size], initializer=self.initializer, regularizer=self.weights_regularizer)\n # [batch, ATTEN_size]\n objAtt_fced = tf.matmul(feature_objAtt, w_objAtt_fc)\n # [batch_size, activate_reduce, atten_size]\n objAtt_broadcast = tf.tile(tf.reshape(objAtt_fced, [-1,1,atten_size]), [1,activate_reduce,1])\n activate_h_2 = tf.nn.tanh(tf.add(activate_embeded_2, objAtt_broadcast))\n activate_h_2 = tf.reshape(activate_h_2, [-1, atten_size])\n w_activate_g_2 = tf.get_variable('w_ques_g_2', [atten_size, 1], initializer=self.initializer, regularizer=self.weights_regularizer)\n # [batch_size, activate_reduce]\n activate_p_2 = tf.reshape(tf.matmul(activate_h_2, w_activate_g_2), [-1, activate_reduce])\n activate_p_2 = tf.nn.softmax(activate_p_2, dim=-1)\n activate_p_2 = tf.reshape(activate_p_2, [-1,1,activate_reduce])\n # [batch_size, activate_dim]\n feature_activateAtt2 = tf.reshape(tf.matmul(activate_p_2, activate_tensor), (-1,activate_dim))\n out_feature_activateAtt2 = tf.tile(tf.reshape(feature_activateAtt2, [-1,1,activate_dim]), (1, object_reduce, 1))\n\n # [batch_size, object_reduce, activate_dim+object_dim]\n return tf.concat((out_feature_activateAtt2, out_feature_objAtt), axis=-1)\n\n def _build_lstm(self, input_tensor, lstm_size, scope):\n with tf.variable_scope(scope):\n lstm_cell = tf.contrib.rnn.BasicLSTMCell(lstm_size)\n lstm_out, state = tf.nn.dynamic_rnn(lstm_cell, input_tensor, dtype=tf.float32)\n return lstm_out\n\n def _build_network(self, is_training=True):\n # select initializers\n\n q2o_atten = tf.reduce_sum(self._question, axis=-2)\n # [batch_size, frame_number, ques_size]\n q2o_atten = tf.tile(tf.reshape(q2o_atten, (-1,1,1,cfg.QUES_SIZE)), (1,cfg.FRAME_NUMBER,cfg.OBJECT_NUMBER,1))\n with tf.variable_scope('o_atten'):\n q2o_atten = tf.reshape(q2o_atten, (-1, cfg.QUES_SIZE))\n w_q = tf.get_variable('q2o_wq', (cfg.QUES_SIZE, cfg.ATTEN_SIZE), initializer=self.initializer, regularizer=self.weights_regularizer)\n # [batch_size*frame_number*object_number, atten_size)]\n q2o_q_wed = tf.matmul(q2o_atten, w_q)\n\n q2o_objec = tf.reshape(self._obj_feature, (-1, cfg.OBJECT_SIZE))\n w_o = tf.get_variable('q2o_wo', (cfg.OBJECT_SIZE, cfg.ATTEN_SIZE), initializer=self.initializer, regularizer=self.weights_regularizer)\n # [batch_size*frame_number*object_number, atten_size]\n q2o_o_wed = tf.reshape(tf.matmul(q2o_objec, w_o), (-1, cfg.ATTEN_SIZE))\n\n q2o_p = tf.tanh(tf.add(q2o_o_wed, q2o_q_wed))\n #q2o_p = tf.reshape(q2o_p, (-1, cfg.ATTEN_SIZE))\n q2o_w = tf.get_variable('q2o_w', (cfg.ATTEN_SIZE, 1), initializer=self.initializer, regularizer=self.weights_regularizer)\n q2o_softmax = tf.nn.softmax(tf.reshape(tf.matmul(q2o_p, q2o_w), (-1, cfg.OBJECT_NUMBER)))\n #[batch_size*frame_nubmer, 1, object_nubmer]\n q2o_softmax = tf.reshape(q2o_softmax, (-1, 1, cfg.OBJECT_NUMBER))\n # [bathc_size*frame_nubmer, object_number, object_size]\n obj = tf.reshape(self._obj_feature, (-1, cfg.OBJECT_NUMBER, cfg.OBJECT_SIZE))\n o_tten_out = tf.reshape(tf.matmul(q2o_softmax, obj), (-1, cfg.FRAME_NUMBER, cfg.OBJECT_SIZE))\n\n qo_co_atten = self._build_co_atten(self._question, o_tten_out, [cfg.QUES_SEQ, cfg.QUES_SIZE, cfg.FRAME_NUMBER, cfg.OBJECT_SIZE, cfg.ATTEN_SIZE], 'qo-co-attention')\n lstm_2_out = self._build_lstm(qo_co_atten, cfg.LSTM_SIZE, 'lstm2')\n\n softmax_input = lstm_2_out[:,-1]\n with tf.variable_scope('final'):\n\n w_class = tf.get_variable('w_class', [cfg.LSTM_SIZE, cfg.VOCAB_SIZE], initializer=self.initializer, regularizer=self.weights_regularizer)\n softmax_input = tf.matmul(softmax_input, w_class)\n softmax_output = tf.nn.softmax(softmax_input, dim=-1)\n word_pred = tf.reshape(tf.argmax(softmax_output, axis=1, name='word_pred'), (-1,1))\n cross_entropy = tf.losses.log_loss(self._answer, softmax_output)\n self._loss = tf.reduce_mean(cross_entropy)\n\n self._losses['class_loss'] = self._loss\n self._losses['reg_loss'] = tf.add_n(tf.get_collection(tf.GraphKeys.REGULARIZATION_LOSSES), name='reg_loss')\n self._losses['all_loss'] = self._losses['class_loss']+ 0.1*self._losses['reg_loss']\n self._event_summaries.update(self._losses)\n answer_word = tf.reshape(tf.argmax(self._answer, axis=1, name='word'), (-1,1))\n self._answer_code = answer_word\n word_accuracy = tf.to_float(tf.equal(word_pred, answer_word))\n\n # Set learning rate and momentum\n self.lr = tf.Variable(cfg.TRAIN.LEARNING_RATE, trainable=False)\n #self.optimizer = tf.train.MomentumOptimizer(self.lr, cfg.TRAIN.MOMENTUM)\n self.optimizer = tf.train.AdamOptimizer(self.lr)\n\n # Compute the gradients with regard to the loss\n gvs = self.optimizer.compute_gradients(self._losses['all_loss'])\n self.gvs = gvs\n self.train_op = self.optimizer.apply_gradients(gvs)\n\n\n #[ batch_size, 1001]\n self._predictions['word_score'] = softmax_output\n self._predictions['word_pred'] = word_pred\n self._predictions['word_accuracy'] = word_accuracy\n\n self._score_summaries.update(self._predictions)\n\n\n return word_pred\n\n\n def create_architecture(self, mode, tag=None):\n self.initializer = tf.random_uniform_initializer(-0.01, 0.01)\n self.weights_regularizer = tf.contrib.layers.l2_regularizer(cfg.TRAIN.WEIGHT_DECAY)\n self.handle = tf.placeholder(tf.string, [])\n data_iterator = tf.data.Iterator.from_string_handle(self.handle, self.handle_types, self.handle_shapes)\n features = data_iterator.get_next()\n _vgg_feature = tf.reshape((features['video_feature'][:,:,0,:4096]), [-1,20,4096])\n _c3d_feature = tf.reshape((features['video_feature'][:,:,1,:4096]), [-1,20,4096])\n self._video_feature = tf.add(0.5*_vgg_feature, 0.5*_c3d_feature)\n self._obj_feature = features['video_feature'][:,:,2:,:4096]\n _question = tf.cast(features['question'], tf.float32)\n with tf.variable_scope('question_embedding'):\n w = tf.get_variable('q_embed', (1001, cfg.QUES_SIZE), initializer=self.initializer, regularizer=self.weights_regularizer)\n _question = tf.reshape(_question, (-1, 1001))\n self._question = tf.reshape(tf.matmul(_question, w), (-1, cfg.QUES_SEQ, cfg.QUES_SIZE))\n self._answer = tf.cast(features['answer'], tf.float32)\n self.qtype = tf.cast(features['qtype'], tf.int32)\n\n #batch_mean_answer = tf.reshape(tf.reduce_mean(self._answer, axis=0), (1,1001))\n #answer_code = tf.argmax(self._answer, axis=-1)\n # [batch_size, 1]\n #no_label_index = tf.reshape(tf.cast(tf.equal(answer_code, 0), tf.float32), (-1,1))\n #add_answer = tf.matmul(no_label_index, batch_mean_answer)\n #self.loss_answer = self._answer\n\n training = mode == 'TRAIN'\n testing = mode == 'TEST'\n\n assert tag != None\n\n #regularizers\n\n word_pred = self._build_network(training)\n layers_to_output = {'word_pred':word_pred}\n for var in tf.trainable_variables():\n self._train_summaries.append(var)\n\n layers_to_output.update(self._losses)\n\n val_summaries = []\n with tf.device(\"/cpu:0\"):\n for key, var in self._event_summaries.items():\n val_summaries.append(tf.summary.scalar(key, var))\n for key, var in self._score_summaries.items():\n self._add_score_summary(key, var)\n for var in self._train_summaries:\n self._add_train_summary(var)\n\n self._summary_op = tf.summary.merge_all()\n self._summary_op_val = tf.summary.merge(val_summaries)\n\n layers_to_output.update(self._predictions)\n\n return layers_to_output\n\n def get_summary(self, sess, handle):\n feed_dict = {self.handle: handle}\n summary = sess.run(self._summary_op_val, feed_dict=feed_dict)\n\n return summary\n\n def test_step(self, sess, handle):\n feed_dict = {self.handle:handle}\n qtype, word_pred_code, answer_code, word_pred_accuracy, loss = sess.run([\n self.qtype,\n self._predictions['word_pred'],\n self._answer_code,\n self._predictions['word_accuracy'],\n self._loss,\n ], feed_dict=feed_dict)\n\n qtype= qtype[0][0]\n word_pred_code= word_pred_code[0][0]\n word_pred_accuracy= word_pred_accuracy[0][0]\n answer_code = answer_code[0][0]\n\n if answer_code == word_pred_code:\n return [qtype, 1, 1, loss]\n if answer_code == 0:\n return [qtype, word_pred_accuracy, -1, loss]\n else:\n answer = wn.synsets(answer_dict[str(answer_code)][0])\n if len(answer) == 0:\n return [qtype, word_pred_accuracy, -1, loss]\n answer = answer[0]\n if word_pred_code == 0:\n return [qtype, word_pred_accuracy, 0, loss]\n else:\n predic = wn.synsets(answer_dict[str(word_pred_code)][0])\n if len(predic) != 0:\n predic = predic[0]\n wup_value = answer.wup_similarity(predic)\n if wup_value:\n return [qtype, word_pred_accuracy, wup_value, loss]\n else:\n return [qtype, word_pred_accuracy, 0, loss]\n else:\n return [qtype, word_pred_accuracy, 0, loss]\n\n def train_step(self, sess, handle):\n feed_dict = {self.handle:handle}\n qtype, word_pred_code, answer_code, word_pred_accuracy, gvs, loss, _ = sess.run([\n self.qtype,\n self._predictions['word_pred'],\n self._answer_code,\n self._predictions['word_accuracy'],\n self.gvs,\n self._loss,\n self.train_op\n ], feed_dict=feed_dict)\n qtype= np.reshape(qtype, [-1])\n word_pred_code= np.reshape(word_pred_code, [-1])\n word_pred_accuracy= np.reshape(word_pred_accuracy, [-1])\n answer_code = np.reshape(answer_code, [-1])\n\n accuracy = np.zeros((5,4), dtype='float')\n for i in range(len(qtype)):\n accuracy[qtype[i]][0] += 1\n accuracy[qtype[i]][1] += word_pred_accuracy[i]\n if answer_code[i] == 0:\n if word_pred_code[i] == 0:\n accuracy[qtype[i]][2]+=1\n accuracy[qtype[i]][3]+=1\n continue\n else:\n answer = wn.synsets(answer_dict[str(answer_code[i])][0])\n if len(answer) == 0:\n continue\n answer = answer[0]\n accuracy[qtype[i]][2] += 1\n if word_pred_code[i] != 0:\n predic = wn.synsets(answer_dict[str(word_pred_code[i])][0])\n if len(predic) != 0:\n predic = predic[0]\n wup_value = answer.wup_similarity(predic)\n if wup_value:\n accuracy[qtype[i]][3] += answer.wup_similarity(predic)\n\n return accuracy, loss\n\n def train_step_with_summary(self, sess, handle):\n feed_dict = {self.handle:handle}\n qtype, word_pred_code, answer_code, word_pred_accuracy ,loss, summary, _ = sess.run([\n self.qtype,\n self._predictions['word_pred'],\n self._answer_code,\n self._predictions['word_accuracy'],\n self._loss,\n self._summary_op,\n self.train_op\n ], feed_dict=feed_dict)\n\n qtype= np.reshape(qtype, [-1])\n word_pred_code= np.reshape(word_pred_code, [-1])\n word_pred_accuracy= np.reshape(word_pred_accuracy, [-1])\n answer_code = np.reshape(answer_code, [-1])\n\n\n accuracy = np.zeros((5,4))\n for i in range(len(qtype)):\n accuracy[qtype[i]][0] += 1\n accuracy[qtype[i]][1] += word_pred_accuracy[i]\n if answer_code[i] == 0:\n if word_pred_code[i] == 0:\n accuracy[qtype[i]][2]+=1\n accuracy[qtype[i]][3]+=1\n continue\n else:\n answer = wn.synsets(answer_dict[str(answer_code[i])][0])\n if len(answer) == 0:\n continue\n answer = answer[0]\n accuracy[qtype[i]][2] += 1\n if word_pred_code[i] != 0:\n predic = wn.synsets(answer_dict[str(word_pred_code[i])][0])\n if len(predic) != 0:\n predic = predic[0]\n wup_value = answer.wup_similarity(predic)\n if wup_value:\n accuracy[qtype[i]][3] += answer.wup_similarity(predic)\n\n return accuracy, loss, summary\n\n\n","sub_path":"lib/nets/a.py","file_name":"a.py","file_ext":"py","file_size_in_byte":18456,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"356248097","text":"stage = 0\r\nresult = 0\r\n# while stage < 10000:\r\n# stage += 7\r\n#\r\n# if ((stage%2==1) and (stage%3==2) and (stage%5==4) and (stage%6==5) ) == True:\r\n# print(\"MATCH! %d\"%(stage))\r\n# result += 1\r\n# break\r\n# else: print(\"UNMATCH stage(now stage is %d\"%(stage))\r\n#\r\n# if result == 1:\r\n# print(\"匹配出最少阶梯数为%d\"%(stage))\r\n# else: print(\"该范围内无匹配结果\")\r\nfor stage in range(0,10000,7):\r\n if (stage % 2 ==1) and (stage % 3 ==2) and (stage % 5 ==4) and (stage % 6 == 5) ==True:\r\n print(stage)\r\n result += 1\r\n break\r\nif result == 0:\r\n print(\"当前范围内无匹配项\")\r\nelse: print(\"范围内匹配到值,最少的匹配值为:%d\"%(stage))\r\n# while True:\r\n# year = input(\"输入一个年份试试\")\r\n# if not year.isdigit():\r\n# print(\"这个不是一个数字哦\")\r\n# else:\r\n# inty=int(year)\r\n# print(\"你输入的是%d,容我算算\" %(inty))\r\n# if inty < 400:\r\n# if (inty % 4 == 0) and (inty % 100 != 0):\r\n# print(\"这是闰年\")\r\n# else:\r\n# print(\"这不是闰年\")\r\n#\r\n# else:\r\n# if (inty % 400 == 0):\r\n# print(\"这是闰年\")\r\n# else:\r\n# print(\"这不是闰年\")\r\n#\r\n","sub_path":"runnian.py","file_name":"runnian.py","file_ext":"py","file_size_in_byte":1326,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"639537275","text":"tab = [15, 8, 31, 47, 2, 19, 6]\nsuma = 0\nn = 0\n\n\nfor i in tab:\n if i%2 != 0:\n suma += i\n n += 1\n \nwynik = suma/n\nprint(f'Srednia aretmetyczna wynosi: {wynik}')","sub_path":"02-ControlStructures/during class/22.py","file_name":"22.py","file_ext":"py","file_size_in_byte":179,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"52442674","text":"from subprocess import Popen, PIPE, STDOUT\nimport signal, sys\n\ndef runWithInput(script, user_input):\n # Store the original handler and set a new one\n original_sigint = signal.getsignal(signal.SIGINT)\n signal.signal(signal.SIGINT, _graceful_handler)\n\n p = Popen([sys.executable, '-i', script], stdout=PIPE, stdin=PIPE, stderr=PIPE)\n out, err = p.communicate(input=user_input.encode('utf-8'))\n if out:\n out = out.decode('utf-8')\n if err:\n err = err.decode('utf-8')\n\n # Restore the handler\n signal.signal(signal.SIGINT, original_sigint)\n\n return out, err\n\ndef _graceful_handler(signum, frame):\n print(\"\\n\\033[91mLooks like you pushed Ctrl-C.\\033[0m\")\n print(\"Feel free to push it again if you actually want to quit the script.\\n\")\n","sub_path":"lib/runner/tester.py","file_name":"tester.py","file_ext":"py","file_size_in_byte":778,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"295538946","text":"import requests\nimport json\nimport concurrent\nfrom concurrent.futures import ThreadPoolExecutor, wait\nimport subprocess\nfrom injectBd import injectBD\nimport sys\nimport os\n\nclass DownloadBDY:\n inited = False\n def __init__(self):\n ibd = injectBD()\n self.tm, self.rand, self.devuid, self.bduss, self.stoken = ibd.Init('百度网盘')\n self.cookie = 'BDUSS=' + self.bduss + ';STOKEN=' + self.stoken \n self.params = '?devuid='+self.devuid+'&time='+self.tm+'&rand='+self.rand+'&method=locatedownload&app_id=250528&ver=4.0'\n self.Headers = {\n # 'Host':'baidu.com',\n # 'Range': 'bytes=0-',\n 'Cookie':self.cookie,\n 'User-Agent':'netdisk;2.2.3;pc;pc-mac;10.15.1;macbaiduyunguanjia'\n }\n print('Cookie::', self.cookie)\n\n def list_files(self,dir='/'):\n host = 'https://pan.baidu.com'\n u = '/api/list' + self.params + '&dir=' + dir\n ret = []\n r = requests.get(host+u,headers=self.Headers)\n file_list = json.loads(r.content)['list']\n for l in file_list:\n d = {'isdir':l['isdir'], 'server_filename': l['server_filename']}\n ret.append(d)\n self.filelist = ret\n\n def get_list_files(self, dir='/'):\n host = 'https://pan.baidu.com'\n u = '/api/list' + self.params + '&dir=' + dir\n ret = []\n r = requests.get(host+u,headers=self.Headers)\n file_list = json.loads(r.content)['list']\n for l in file_list:\n d = {'isdir':l['isdir'], 'server_filename': l['server_filename']}\n ret.append(d)\n return ret\n\n def Download_from_path(self,file_name='氯化虫4_x264.mp4'):\n host = 'https://d.pcs.baidu.com'\n u = '/rest/2.0/pcs/file'+self.params+'&path=/'+file_name\n r = requests.get(host+u,headers=self.Headers)\n u = json.loads(r.content)['urls'][0]['url']\n self.Download_from_url(u,file_name)\n \n def Download_from_url(self, u,file_name):\n print('Downloading from url:'+ u)\n # print(os.path.split(os.path.realpath(__file__))[0])\n dir = os.path.dirname(os.path.realpath(sys.argv[0]))\n print(dir)\n cmd = dir + '/aria2c \"'+u + '\" --out \"'+file_name+'\" --header \"User-Agent: netdisk;2.2.3;pc;pc-mac;10.15.1;macbaiduyunguanjia\" --header \"Cookie: '+self.cookie+'\" -s 128 -k 1M --max-connection-per-server=128 --continue=true '+ ' --dir='+os.path.expanduser('~/Downloads')\n # p = subprocess.Popen(cmd,shell=True,stdout=subprocess.PIPE)\n # for i in iter(p.stdout.readline,'b'):\n # if not i:\n # break\n # print(i.decode('utf-8'), end='')\n \n # Using pexpect can show progress\n import pexpect\n process = pexpect.spawn(cmd)\n process.interact()\n\nif __name__ == \"__main__\":\n print('Downloading...')\n # Download_from_path('阳光电影www.ygdy8.com.速度与激情:特别行动.HD.1080p.中英双字幕.mkv')\n # Download_from_url('https://d.pcs.baidu.com/file/f0fc7e66973f129974e5d35e7d560049?fid=2712021640-250528-533246122739205&dstime=1572172464&rt=sh&sign=FDtAERV-DCb740ccc5511e5e8fedcff06b081203-Qfd4wQ4LK3KxgqE4OLNNHTf%2Buwc%3D&expires=8h&chkv=1&chkbd=0&chkpc=&dp-logid=6952602860418330679&dp-callid=0&shareid=2837947211&r=798114631','ps.dmg')\n print('Done!')","sub_path":"DownloadBaiduYun.py","file_name":"DownloadBaiduYun.py","file_ext":"py","file_size_in_byte":3387,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"485999183","text":"import serial\n# from serial.tools import list_ports\nimport re\nimport sys\nsys.path.append(\"..\")\nfrom slave.model import Model\nimport threading\nimport random\nfrom time import sleep\nimport pdb\n\n\nclass Slave(object):\n \"\"\"docstring for Slave\"\"\"\n def __init__(self):\n super(Slave, self).__init__()\n #self.arg = arg\n self.currentSendLive = True\n self.running = True\n self.port = 'com15'\n self.br = 9600\n\n def __init__slaveStatus(self):\n self.isSeedOpen = True\n self.seedcurrentre = False\n self.seedpulsere = False\n self.seedfrequecere = False\n self.seedcurrent = 1\n self.seedpulse = 1\n self.seedfrequece = 1\n self.firstcurrent = 1\n self.seedsecondcurrent = 1\n self.isFirstPumpOpen = False\n self.isSecondPumpOpen = False\n\n def currentSend(self,ser):\n while self.currentSendLive is True:\n\n currentmsg = self.sendmsg['sendplot']\n cb = int(random.uniform(2,10)*100)\n cb = cb.to_bytes(2,'big')\n #print(currentmsg,':',cb)\n currentmsg = currentmsg.replace(b'\\xFF\\xFF',cb)\n #print(currentmsg)\n cp = 0\n print('发送电流:',currentmsg,': int ',cb,int().from_bytes(cb,'big'))\n\n ser.write(currentmsg)\n\n sleep(1)\n #return currentmsg\n\n def randomSend(self,ser):\n while self.currentSendLive is True:\n self.sendmsglist = [v for k,v in self.sendmsg.items()]\n rd = int(random.uniform(2,len(self.sendmsglist)))\n\n print('发送:',self.sendmsglist[rd])\n ser.write(self.sendmsglist[rd])\n sleep(60)\n #return currentmsg\n\n def powerSend(self,ser):\n #currentmsg = self.sendmsg['sendplot']\n while True:\n #print(currentmsg)\n cp1,cp2,cp3,cp4 = self.rdcreate(8,12,1),self.rdcreate(),self.rdcreate(20,60,1,head = 'little'),self.rdcreate(3,6,1)\n currentmsg = b'\\x9A'+ cp1 +cp2 + cp3 + cp4 +b'\\xFF\\xFF'+b'\\xA9'\n # print('发功:',currentmsg)\n # pdb.set_trace()\n # print('发送电流:',currentmsg,': ',int().from_bytes(cb1,'big'),int().from_bytes(cb2,'big'),int().from_bytes(cb3,'big'),int().from_bytes(cb4,'big')\n ser.write(currentmsg)\n sleep(0.02)\n\n\n def bigPowerSend(self,ser):\n #currentmsg = self.sendmsg['sendplot']\n while True:\n #print(currentmsg)\n cp1,cp2,cp3,cp4 = self.rdcreate(8,12,1),self.rdcreate(),self.rdcreate(2,1000,1,head = 'little'),self.rdcreate(3,6,1)\n currentmsg = b'\\x9A'+ cp1 +cp2 + cp3 + cp4 +b'\\xFF\\xFF'+b'\\xA9'\n print('发功:',currentmsg)\n # pdb.set_trace()\n # print('发送电流:',currentmsg,': ',int().from_bytes(cb1,'big'),int().from_bytes(cb2,'big'),int().from_bytes(cb3,'big'),int().from_bytes(cb4,'big')\n ser.write(currentmsg)\n sleep(10)\n\n def errorSend(self,ser):\n errorlist = [\n b'\\x9A\\xA9',\n b'\\x9A\\xA9\\x9A\\xA9\\x9A\\xA9\\x9A\\xA9\\x9A\\xA9',\n b'\\x9A\\x01\\x01\\x03\\x08\\x9A\\xA9',\n b'\\x9A\\x23\\x90\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\xA9'\n ]\n while True:\n for x in errorlist:\n print('send error msg')\n ser.write(x)\n sleep(10)\n\n\n def process(self):\n\n devState={\n 'comNum':'com3',\n 'comState':'open',\n 'seedState':'open',\n '1stState':'close',\n '1stValue':'0',\n '2stState':'close',\n '2stValue':'0'\n }\n\n\n # self.seedcurrent = 1\n # self.seedpulse = 1\n # self.seedfrequece = 1\n # self.firstcurrent = 1\n # self.seedsecondcurrent = 1\n\n\n # port_list = list(list_ports.comports())\n\n model = Model()\n model.set_port(self.port)\n self.ser = serial.Serial(self.port, self.br, timeout=120)\n #model.begin()\n #model.start()\n model.setSer(self.ser)\n\n self.sendmsg = model.get_msgDict()\n self.entry = model.getEntry()\n self.msgDictHex = self.entry['msgDictHex']\n self.msgDictStr = self.entry['msgDictStr']\n self.sendmsgrec = self.entry['sendmsgrec']\n\n\n #self.sendmsgrec = dict([(v,k) for k,v in self.sendmsg.items()])\n\n # ser = model.get_ser()\n ser = self.ser\n print(ser)\n\n print('上位机信号包大小为:',len(self.sendmsgrec))\n #ser = serial.Serial(port_serial,9600,timeout = 120)\n print('下位机模拟器启动')\n print(\"check which port was really used >\",ser.name)\n #threading.Thread()\n #ser.write(b'\\xEB\\x90\\x04\\x05\\x09\\x07\\x08\\x09\\x90\\xEB')\n # 开个线程定时发送电流\n # threading.Thread(target=Slave.currentSend,args=(self,ser,)).start()\n #开个线程随机发送信号\n #threading.Thread(target=Slave.randomSend,args=(self,ser,)).start()\n # 开个线程发功\n threading.Thread(target=self.powerSend,args=(ser,)).start()\n # 开个线程发噪声\n threading.Thread(target=self.bigPowerSend,args=(ser,)).start()\n #开个线程发error信息\n threading.Thread(target=self.errorSend,args=(ser,)).start()\n while True:\n sertext = model.analysisbit()\n #sertext=ser.read(7)\n if len(sertext) > 0:\n sertext = b'\\xEB\\x90'+sertext+b'\\x90\\xEB'\n print('下位机接收并返回:',sertext)\n ser.write(sertext)\n self.msganalysis(sertext)\n\n #print(self.sendmsgrec.get(sertext))\n\n ser.close()\n\n def rdcreate(self,a = 2, b =10 ,c =100 , head = 'big'):\n cb = int(random.uniform(a,b)*c)\n cb = cb.to_bytes(2,head)\n return cb\n\n def msganalysis(self,sertext):\n # self.msgDictHex = entry['msgDictHex']\n # self.msgDictStr = entry['msgDictStr']\n # self.sendmsgrec = entry['sendmsgrec']\n if sertext:\n serstr = self.sendmsgrec.get(sertext)\n if serstr:\n if serstr == 'openseed':\n self.isSeedOpen = True\n print(serstr)\n elif serstr == 'closeseed':\n self.isSeedOpen = False\n print(serstr)\n elif serstr == 'openseedLED':\n print(serstr)\n self.isLEDOpen = True\n elif serstr == 'closeseedLED':\n print(serstr)\n self.isLEDOpen = False\n elif serstr == 'openfirstpump':\n print(serstr)\n self.isFirstPumpOpen = True\n elif serstr == 'opensecondpump':\n self.isSecondPumpOpen = True\n print(serstr)\n elif serstr == 'closefirstpump':\n print(serstr)\n self.isFirstPumpOpen = False\n elif serstr == 'closesecondpump':\n print(serstr)\n self.isSecondPumpOpen = False\n elif serstr == 'seedcurrentvalueget':\n # pdb.set_trace()\n writehex = sertext[:4] + self.seedcurrent.to_bytes(2, 'big') + sertext[-2:]\n print(serstr,writehex)\n self.ser.write(writehex)\n elif serstr == 'seedpulseread':\n writehex = sertext[:4] + self.seedpulse.to_bytes(2, 'big') + sertext[-2:]\n print(serstr,writehex)\n self.ser.write(writehex)\n elif serstr == 'seedfreread':\n writehex = sertext[:4] + self.seedfrequece.to_bytes(2, 'big') + sertext[-2:]\n print(serstr,writehex)\n self.ser.write(writehex)\n\n else:\n print('in dict error:',serstr,sertext)\n# key changed canot find in dict\n else:\n value = sertext[4:6]\n value = int().from_bytes(value,'big')\n sertext = sertext[0:4] + b'\\xFF\\xFF' + sertext[-2:]\n serstr = self.sendmsgrec.get(sertext)\n if serstr:\n if serstr == 'seedcurrentvalueset':\n self.seedcurrent = value\n print(serstr,value)\n elif serstr == 'seedpulseset':\n self.seedpulse = value\n print(serstr,value)\n elif serstr == 'seedfreset':\n self.seedfrequece = value\n print(serstr,value)\n elif serstr == 'setfirstcurrent':\n print(serstr,value)\n print('晓光说不要发送一级的电流,还不快关掉!!!')\n self.firstcurrent = value\n elif serstr == 'setsecondcurrent':\n print(serstr,value)\n self.seedsecondcurrent = value\n else:\n print('out dict error:',serstr,sertext)\n\n\n\n\n\n\n\n\n # def analysisbit(self,ser):\n # '''\n # return without package\n # '''\n # readlive = True\n # # xebstatue = False\n # # x90statue = False\n # bitlist = list()\n # while readlive and self.running:\n # databit = self.readbit(ser)\n # if databit == b'\\xeb':\n # print(databit,'1')\n # databit = self.readbit(ser)\n # if databit == b'\\x90':\n # while True:\n # print(databit,'2')\n # databit = self.readbit(ser)\n # if databit == b'\\x90':\n # databit = self.readbit(ser)\n # data = b''.join(bitlist)\n # print(data)\n # return data\n # bitlist.append(databit)\n\n\n # def readbit(self,ser):\n # sleep(0.1)\n # try:\n # data = ser.read(1)\n # except Exception as e:\n # raise e\n # except portNotOpenError :\n # sleep(1)\n # return data\n\n\n\n\nif __name__=='__main__':\n slave = Slave()\n slave.process()\n\n\n","sub_path":"slave/slavepump.py","file_name":"slavepump.py","file_ext":"py","file_size_in_byte":10500,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"114067001","text":"#!/usr/bin/env python\n\n\ndef repeatedString(s, n):\n # get number of 'a's in s\n # get number of repetitions of len(s) in n -- n / len(s)\n # get remainder of string and number of 'a's in the remainder\n\n num_a_in_s = 0\n for char in s:\n if char == 'a':\n num_a_in_s += 1\n repetitions_of_s_in_n = n//len(s)\n a_count = repetitions_of_s_in_n * num_a_in_s\n print(a_count)\n num_leftover = n % len(s)\n print(num_leftover)\n remaining_string = s[:num_leftover]\n for char in remaining_string:\n if char == 'a':\n a_count += 1\n return a_count\n\n\ndef main():\n print(repeatedString('aba', 10))\n print(repeatedString('a', 1000000000000))\n print(repeatedString('gfcaaaecbg', 547602))\n\nif __name__ == '__main__':\n main()\n","sub_path":"ariana_prep/HR_repeated_string.py","file_name":"HR_repeated_string.py","file_ext":"py","file_size_in_byte":784,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"571255836","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Fri Jul 13 10:57:52 2018\n\n@author: zyv57124\n\"\"\"\nimport scipy.io as sio\nimport tensorflow as tf\nfrom tensorflow import keras\nimport numpy as np\nimport matplotlib\nimport matplotlib.pyplot as plt\nfrom tensorflow.python.training import gradient_descent\n\n\nfrom time import time\nclass TimingCallback(keras.callbacks.Callback):\n def __init__(self):\n self.logs=[]\n def on_epoch_begin(self, epoch, logs={}):\n self.starttime=time()\n def on_epoch_end(self, epoch, logs={}):\n self.logs.append(time()-self.starttime)\n#Load data ------------------------------------------------------\ndef loadMATData(file1):\n return sio.loadmat(file1)\n\n#Load Data-------------------------------------------------------\ndef convertLabels(labels,samplesize,out):\n label = np.zeros((samplesize,out),dtype=np.float32)\n for i in range(0,len(labels)):\n assi = labels[i]\n if labels[i] == 10:\n assi = 0\n label[i][assi] = 1.0\n label[i] = np.transpose(label[i])\n return label\n\ndata = loadMATData('ex3data1.mat')\nfeatures = data['X']\nlabels = data['y']\n\nfilter = labels ==10\nlabels[filter] = 0\n\n#shuffle data---------------------------------------------------\n\nran = np.arange(features.shape[0])\nnp.random.shuffle(ran)\nfeatures = features[ran]\nlabels = labels[ran]\n\ntraining_features = features[:3500]\ntraining_labels = labels[:3500]\ntest_features = features[3501:]\ntest_labels = labels[3501:]\ntraining_labels = convertLabels(training_labels,training_labels.shape[0],10)\nfor i in np.arange(1,50, 1):\n #TF Neaural Network Builder--------------------------------------\n\n layers = []\n layers.append(keras.layers.Dense(i, input_dim=400, activation=tf.nn.relu))\n \n# for cfd in range(0,i):\n# \n# layers.append(keras.layers.Dense(12, activation=tf.nn.relu))\n\n \n layers.append(keras.layers.Dense(10, activation=None))\n layers.append(keras.layers.Softmax(axis=0))\n \n model = keras.Sequential(layers)\n\n print(layers)\n# loss_fn = keras.losses.categorical_crossentropy(y_true, y_pred)\n\n model.compile(optimizer=tf.train.GradientDescentOptimizer(learning_rate=0.1), loss=keras.losses.categorical_crossentropy, metrics=['accuracy'])\n \n predictions = model.predict(test_features)\n \n cb=TimingCallback()\n history = model.fit(training_features, training_labels, batch_size=60, epochs=500, verbose=2, callbacks=[cb])\n \n #Store eoch number and loss values in .txt file\n loss_data = (history.history['loss'])\n f = open(\"Benchmarking\\Final Data\\VWidth\\TF_loss_data_batchnum_\"+str(i)+\".txt\",\"w\")\n for xx in range(1,len(loss_data)+1):\n if xx==1:\n delta_loss = 'Nan'\n else:\n delta_loss = (loss_data[xx-2] - loss_data[xx-1])\n #Epoch #Loss #Batch size #Time #Change in loss\n if i ==0:\n f.write(str(xx) + \",\" + str(i+1) + \",\" + str(loss_data[xx-1]) + \",\" + str(delta_loss) + \",\" +str(cb.logs[xx-1]) + \"\\n\" )\n else:\n f.write(str(xx) + \",\" + str(i) + \",\" + str(loss_data[xx-1]) + \",\" + str(delta_loss) + \",\" +str(cb.logs[xx-1]) + \"\\n\" )\n\n f.close()\n\n predictions = model.predict(test_features)\n#%%\n count = 0\n for i in range(0, len(test_labels)):\n pred = (np.argmax(predictions[i]))\n if test_labels[i][0] == pred:\n count +=1\n \n print(count)","sub_path":"Benchmarking/Keras/Tensorflow/TF_DepthVariation.py","file_name":"TF_DepthVariation.py","file_ext":"py","file_size_in_byte":3447,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"536874446","text":"#!/usr/bin/python\n# -*- coding: utf-8 -*-\n\nfrom django.http import HttpResponse, HttpResponseRedirect, Http404\nfrom django.template.context import Context, RequestContext\nfrom django.shortcuts import render_to_response, redirect\nfrom django.conf import settings\nfrom account.models import Announcement\nfrom account.forms import *\nfrom django.contrib.auth import authenticate, login as auth_login, logout as auth_logout\nfrom recaptcha.client import captcha\n\ndef login(request):\n \"\"\"\n View for handling login of users and redirecting to the respective dashboards on successful login.\n \"\"\"\n if request.method == 'POST':\n username = request.POST.get('username', '')\n password = request.POST.get('password', '')\n user = authenticate(username=username, password=password)\n if user is not None and user.is_active and not user.is_superuser:\n auth_login(request, user)\n nextURL = request.GET.get('next','')\n if nextURL != '':\n nextURL = nextURL[1:] # For removing the leading slash from in front of the next parameter\n redirectURL = settings.SITE_URL + nextURL\n return HttpResponseRedirect(redirectURL)\n if user.get_profile().is_core_of:\n return redirect('core.views.core_dashboard',username=user)\n else:\n return redirect('coord.views.coord_home')\n invalid_login = True\n login_form = LoginForm()\n return render_to_response('index.html', locals(), context_instance=RequestContext(request))\n else:\n if request.user.is_authenticated():\n if request.user.get_profile().is_core_of:\n return redirect('core.views.core_dashboard',username=request.user)\n else:\n return redirect('coord.views.coord_home')\n else:\n login_form = LoginForm()\n return render_to_response('index.html', locals(), context_instance=RequestContext(request))\n\ndef register(request):\n \"\"\"\n View for handling Registration of new users after checking for reCAPTCHA.\n \"\"\"\n if request.method == 'POST':\n register_form = RegistrationForm(request.POST)\n captcha_response = '' # Added so that nothing gets displayed in the template if this variable is not set\n # talk to the reCAPTCHA service\n response = captcha.submit(\n request.POST.get('recaptcha_challenge_field'),\n request.POST.get('recaptcha_response_field'),\n settings.RECAPTCHA_PRIVATE_KEY,\n request.META['REMOTE_ADDR'],)\n\n if response.is_valid:\n if register_form.is_valid():\n data = register_form.cleaned_data\n new_user = User(first_name = data['first_name'],\n last_name = data['last_name'],\n username = data['rollno'],\n email = data['email'])\n new_user.set_password(data['password'])\n new_user.is_active = True\n new_user.save()\n new_profile = UserProfile(user = new_user,\n nick = data['nick'],\n room_no = data['room_no'],\n hostel = data['hostel'],\n cgpa = data['cgpa'],\n ph_no = data['ph_no'],\n city = data['city'],\n summer_location = data['summer_location'],)\n new_profile.save()\n registered = True\n else:\n captcha_response = response.error_code\n else:\n captcha_response = '' # Added so that nothing gets displayed in the template if this variable is not set\n register_form = RegistrationForm()\n return render_to_response('account/register.html', locals(), context_instance=RequestContext(request))\n\n\ndef logout(request):\n \"\"\"\n View for logging out users from the session.\n \"\"\"\n if request.user.is_authenticated():\n auth_logout(request)\n return redirect('portal.views.home')\n else:\n return redirect('portal.views.home')\n\ndef editprofile(request):\n \"\"\"\n View for editting the profile details of the currently logged in user.\n \"\"\"\n user = request.user\n user_profile = user.get_profile()\n if request.method == 'POST':\n edit_form = EditUserProfileForm(request.POST, instance = user_profile)\n if edit_form.is_valid():\n edit_form.save()\n user.first_name = edit_form.cleaned_data['first_name']\n user.last_name = edit_form.cleaned_data['last_name']\n user.save()\n editted = True\n else:\n values = {'first_name': user.first_name,\n 'last_name' : user.last_name,}\n edit_form = EditUserProfileForm(instance = user_profile, initial = values)\n return render_to_response('account/editprofile.html', locals(), context_instance=RequestContext(request))\n\n","sub_path":"account/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":5158,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"611326863","text":"'''List sections from the output of get_schedule.py'''\nfrom __future__ import print_function\nimport sys\nimport json\nimport re\n\nsections = json.load(sys.stdin)\nsections.sort(key = lambda s: s['Section']['Sort Key'])\nprimary_num = 0\nfor s in sections:\n course_num = s['Course']['Number']\n r = r'(^\\D?)(\\d+)(\\D*)$'\n m = re.match(r, course_num)\n m1 = m.group(1)\n m2 = m.group(2)\n m3 = m.group(3)\n just_num = (m1 + m2 + m3).ljust(6, ' ')\n if s['Section']['Primary']:\n primary = 'primary'\n primary_num += 1\n else:\n primary = ''\n print(s['Course']['Department'], just_num, s['Section']['Type'], s['Section']['Number'], s['Section']['Class'], primary)\nprint('{} section(s) found'.format(len(sections)), file = sys.stderr)\nprint('{} primary section(s) found'.format(primary_num), file = sys.stderr)\n","sub_path":"list_sections.py","file_name":"list_sections.py","file_ext":"py","file_size_in_byte":841,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"217973247","text":"import numpy as np\n\nfrom minerva.utils import copy_resources\nfrom .tasks import *\nfrom .config import SOLUTION_CONFIG\nfrom .pipelines import localization_pipeline, alignment_pipeline, classification_pipeline\nfrom .registry import registered_tasks, registered_scores\nfrom .trainer import Trainer\nfrom ..backend.task_manager import TaskSolutionParser\n\npipeline_dict = {'localization': localization_pipeline,\n 'alignment': alignment_pipeline,\n 'classification': classification_pipeline}\n\n\ndef dry_run(sub_problem, eval_mode, dev_mode, cloud_mode):\n if cloud_mode:\n copy_resources()\n\n pipeline = pipeline_dict[sub_problem]\n trainer = Trainer(pipeline, SOLUTION_CONFIG, dev_mode, cloud_mode, sub_problem)\n if eval_mode:\n _evaluate(trainer, sub_problem)\n else:\n trainer.train()\n _evaluate(trainer, sub_problem)\n\n\ndef submit_task(sub_problem, task_nr, filepath, dev_mode, cloud_mode):\n if cloud_mode:\n copy_resources()\n\n pipeline = pipeline_dict[sub_problem]\n trainer = Trainer(pipeline, SOLUTION_CONFIG, dev_mode, cloud_mode, sub_problem)\n user_task_solution, user_config = _fetch_task_solution(filepath)\n task_handler = registered_tasks[task_nr](trainer)\n new_trainer = task_handler.substitute(user_task_solution, user_config)\n new_trainer.train()\n _evaluate(new_trainer, sub_problem)\n\n\ndef _fetch_task_solution(filepath):\n with TaskSolutionParser(filepath) as task_solution:\n user_solution = task_solution['solution']\n user_config = task_solution['CONFIG']\n return user_solution, user_config\n\n\ndef _evaluate(trainer, sub_problem):\n score_valid, score_test = trainer.evaluate()\n print('\\nValidation score is {0:.4f}'.format(score_valid))\n print('Test score is {0:.4f}'.format(score_test))\n\n if np.abs(score_test - score_valid) > registered_scores[sub_problem]['score_std']:\n print('Sorry, your validation split is messed up. Fix it please.')\n else:\n print('That is a solid validation')\n\n if score_test < registered_scores[sub_problem]['score']:\n print('Congrats you solved the task!')\n else:\n print('Sorry, but this score is not high enough to pass the task')\n","sub_path":"minerva/whales/problem_manager.py","file_name":"problem_manager.py","file_ext":"py","file_size_in_byte":2246,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"214067897","text":"import numpy as np\nimport matplotlib.pyplot as plt\nfrom mpl_toolkits.mplot3d import Axes3D\nimport matplotlib.cm as cm\nimport pylab\nimport h5py\nfrom sklearn.model_selection import train_test_split\n\nname = \"Project_officer\"\nwi_data = np.loadtxt(name+'.xyz', delimiter=' ')\nwi_input_data = np.loadtxt(name+'_input.xyz', delimiter=' ')\ngiven_input_data = np.loadtxt('../PU-net_test/'+name+'.xyz', delimiter=' ')\n\nfile = h5py.File( '../PU-Net_input/Project_officer.h5', 'r')\nwi = np.array(file['wi'])\ngt = np.array(file['gt'])\nfile.close()\n\ndef plot(a,b,c):\n fig = plt.figure()\n ax = fig.gca(projection='3d')\n ax.scatter(a, b, c, cmap = cm.jet)\n ax.set_xlim(-1,1)\n ax.set_ylim(-1,1)\n ax.set_zlim(-1,1)\n ax.set_xlabel('x')\n ax.set_ylabel('y')\n ax.set_zlabel('z')\n# pylab.show()\n# for angle in range(0, 360):\n ax.view_init(30, 0)\n plt.show()\n\nplot(gt[0,:,0],gt[0,:,1],gt[0,:,2])\nplot(wi[0,:,0],wi[0,:,1],wi[0,:,2])\nplot(given_input_data[:,0],given_input_data[:,1],given_input_data[:,2])\nplot(wi_input_data[:,0],wi_input_data[:,1],wi_input_data[:,2])\nplot(wi_data[:,0],wi_data[:,1],wi_data[:,2])\n#np.save(name+'out.npy',wi_data)","sub_path":"PU-net_output/plot.py","file_name":"plot.py","file_ext":"py","file_size_in_byte":1160,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"98301881","text":"\n#-----Statement of Authorship----------------------------------------#\n#\n# By submitting this task the signatories below agree that it\n# represents our own work and that we both contributed to it. We\n# are aware of the University rule that a student must not\n# act in a manner which constitutes academic dishonesty as stated\n# and explained in QUT's Manual of Policies and Procedures,\n# Section C/5.3 \"Academic Integrity\" and Section E/2.1 \"Student\n# Code of Conduct\".\n#\n# First student's no: n8888141\n# First student's name: James Clelland\n# Portfolio contribution: 25%\n#\n# Second student's no: n8857954\n# Second student's name: Damon Jones\n# Portfolio contribution: 75%\n#\n# Contribution percentages refer to the whole portfolio, not just this\n# task. Percentage contributions should sum to 100%. A 50/50 split is\n# NOT necessarily expected. The percentages will not affect your marks\n# except in EXTREME cases.\n#\n#--------------------------------------------------------------------#\n\n\n#-----Task Description-----------------------------------------------#\n#\n# CRYPTO REVERSO\n#\n# In this task you develop two functions for encrypting and\n# decrypting secret messages. However, where cryptography usually\n# relies on complex mathematical properties, here we merely\n# rearrange the letters of the message to disguise it.\n#--------------------------------------------------------------------#\n\n\n#-----Acceptance Tests-----------------------------------------------#\n#\n# This section contains the unit tests that your program must\n# pass. You may not change anything in this section. NB: When\n# your program is marked the following tests will all be used as\n# well as some additional tests (not provided) to ensure your\n# solution works for other cases.\n#\n\"\"\"\n---------------------- Encrypt function tests ------------------------\n\nEmpty message\n>>> encrypt('', 4) # Test 1\n''\n\nEncryption that changes nothing\n>>> encrypt('MADAM', 2) # Test 2\n'MADAM'\n\nA message with one word, no spaces, and block size one\n>>> encrypt ('CRYPTOGRAPHY', 1) # Test 3\n'YHPARGOTPYRC'\n\nA message that exactly fills two blocks\n>>> encrypt('WHO WATCHES THE WATCHERS', 2) # Test 4\n'SEHCTAWXOHWXSREHCTAWXEHT'\n\nA message with one word in the final block\n>>> encrypt('PARANOIA IS OUR PROFESSION', 3) # Test 5\n'RUOXSIXAIONARAPXNOISSEFORP'\n\nA message that needs padding at both ends\n>>> encrypt('THE PRICE OF FREEDOM IS ETERNAL VIGILENCE', 4) # Test 6\n'MODEERFXFOXECIRPXEHTXECNELIGIVXLANRETEXSI'\n\nThe same message but a different block size\n>>> encrypt('THE PRICE OF FREEDOM IS ETERNAL VIGILENCE', 5) # Test 7\n'SIXMODEERFXFOXECIRPXEHTXECNELIGIVXLANRETE'\n\nExtreme case - blocks of size one\n>>> encrypt('BIG BROTHER IS WATCHING', 1) # Test 8\n'GIBXREHTORBXSIXGNIHCTAW'\n\n---------------------- Decrypt function tests ------------------------\n\nDecrypting nothing\n>>> decrypt('', 8) # Test 9\n''\n\nDecrypting a single word\n>>> decrypt('NOITPYRCNE', 3) # Test 10\n'ENCRYPTION'\n\nDecrypting some ciphertext with the block size used to encrypt it\n>>> decrypt('TONXSIXYTIRUCESXTUBXTCUDORPXAXSSECORPXA', 3) # Test 11\n'SECURITY IS NOT A PRODUCT BUT A PROCESS'\n\nDecrypting the same ciphertext but with the wrong block size\n>>> decrypt('TONXSIXYTIRUCESXTUBXTCUDORPXAXSSECORPXA', 4) # Test 12\n'BUT SECURITY IS NOT A PROCESS A PRODUCT'\n\nDecrypting some long ciphertext\n>>> decrypt('EVIHCRAXTONXODXOHWXESOHTXOTX' + \\\n 'DENMEDNOCXERAXTSAPXEHTXTIXEPYTER', 5) # Test 13\n'THOSE WHO DO NOT ARCHIVE THE PAST ARE CONDEMNED TO RETYPE IT'\n\n---------------- Encryption and decryption tests ---------------------\n\nEncrypting and decrypting a short phrase\n>>> decrypt(encrypt('PRIVACY IS NOT FOR THE PASSIVE', 3), 3) # Test 14\n'PRIVACY IS NOT FOR THE PASSIVE'\n\nAnd a final test for good measure\n>>> decrypt(encrypt('EVEN A PARANOID CAN HAVE ENEMIES', 5), 5) # Test 15\n'EVEN A PARANOID CAN HAVE ENEMIES'\n\n\"\"\"\n#\n#--------------------------------------------------------------------#\n\n\n#-----Students' Solution---------------------------------------------#\n#\n# Complete the task by filling in the template below.\n\n\n##### PUT YOUR encrypt AND decrypt FUNCTIONS HERE\n\n########## Replacing Spaces with X ###############\n\ndef crypt(text,block,gap,holder):\n message = ''\n if len(text) == 0:\n return message\n\n spaces = [0]\n for _ in range (text.count(gap)):\t\t\t#Replaces spaces with ‘x’ and save their positions as \n spaces.append(text.find(gap))\t\t\t#those are normally word ends were blocks may form\n text = text.replace(gap, holder,1)\n\n\n############Debugging###############\n#print 'spaces', spaces\n#########End of Debugging########### \n\n \n##########Making The Blocks ############\n\n totblock = float(len(spaces))/block\t\t #Finds total number of blocks to be made\n from math import ceil #ceil rounds up to next whole number\n totblock = int(ceil(totblock)) # for 4 spaces/word in blocks of 3\n if totblock == 0: # 4/3 is 1.333 or 1 as far as python is concerned\n totblock = 1 #ceil fixes this it makes it 2 blocks\n elif len(spaces) == 1:\n totblock = 1\n\n \n#############Dubugging###############\n#print 'totblock', totblock\n#########End of Debugging###########\n \n blocks = []\n for runs in range(totblock):\n startpoint = spaces[block*runs]\n \n#############Dubugging############## \n#print 'run', runs\n#########End of Debugging###########\n \n if (runs+1) >= totblock:\n blocks.append (text[startpoint:len(text)])\n break\n endpoint = spaces[block*(runs+1)]\n blocks.append (text[startpoint:endpoint])\n \n##########End of Making the blocks########### \n\n\n################Debugging#################### \n#print blocks\n#print 'blocks', blocks\n#reversing the blocks\n#############End of Debugging################\n\n############## Reversing the blocks##########\n \n total = 0\n while total+1 <= totblock:\n message = message + holder + blocks[total][::-1] # Reversing blocks [::-1]\n total = total + 1\n message = message.replace(holder+holder,holder)\n if message[len(message)-1] == holder:\n message = message[:len(message)-1]\n if message[0] == holder:\n message = message[1:]\n return message\n\n############## End of Reversing###############\n\n\n\n###################Calling Encrypt and Decrypt#######################\n\ndef encrypt(text,block):\n return crypt(text,block,' ','X')\ndef decrypt(text,block):\n return crypt(text,block,'X',' ')\n\n\n#--------------------------------------------------------------------#\n\n\n#-----Automatic Testing----------------------------------------------#\n#\n# The following code will automatically run the acceptance tests\n# when the program is \"run\". If you want to prevent the tests\n# from running, and test your functions manually, comment out the\n# code below.\n#\nif __name__ == '__main__':\n from doctest import testmod\n testmod(verbose=True)\n#\n#--------------------------------------------------------------------#\n","sub_path":"CryptoReverso-instructions/crypto_reverso.py","file_name":"crypto_reverso.py","file_ext":"py","file_size_in_byte":7183,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"639755699","text":"import tensorflow as tf\nfrom keras import backend as K\n\ndef weighted_categorical_crossentropy(weights):\n \"\"\"\n Weighted version of keras.objectives.categorical_crossentropy.\n Use this loss function with median frequency weights for class balance.\n \"\"\"\n # Convert weights to a constant tensor\n weights = tf.constant(weights, dtype=tf.float32)\n\n def loss(y_true, y_pred):\n # Scale predictions so that the class probas of each sample sum to 1\n y_pred /= tf.reduce_sum(y_pred, axis=-1, keepdims=True)\n\n # Clip to prevent NaN's and Inf's\n _epsilon = tf.convert_to_tensor(K.epsilon(), y_pred.dtype.base_dtype)\n y_pred = tf.clip_by_value(y_pred, _epsilon, 1.0 - _epsilon)\n\n # Do the loss calculation\n loss = y_true * tf.log(y_pred) * 1.0/weights\n return -tf.reduce_sum(loss, axis=-1)\n\n return loss\n\ndef focal_loss(alpha=0.25, gamma=2.0):\n \"\"\"\n alpha: Scale the focal weight with alpha.\n gamma: Take the power of the focal weight with gamma.\n \"\"\"\n def loss(y_true, y_pred):\n # Scale predictions so that the class probas of each sample sum to 1\n y_pred /= tf.reduce_sum(y_pred, axis=-1, keepdims=True)\n\n # Clip to prevent NaN's and Inf's\n _epsilon = tf.convert_to_tensor(K.epsilon(), y_pred.dtype.base_dtype)\n y_pred = tf.clip_by_value(y_pred, _epsilon, 1.0 - _epsilon)\n\n # Do the loss calculation\n pt = tf.where(tf.equal(y_true, 1), y_pred, 1 - y_pred)\n loss = alpha * tf.pow(1.0 - pt, gamma) * tf.log(pt)\n return -tf.reduce_sum(loss, axis=-1)\n\n return loss\n\ndef weighted_focal_loss(weights, gamma=2.0):\n \"\"\"\n weights: Median frequency weights for class balance\n gamma: Take the power of the focal weight with gamma.\n \"\"\"\n # Convert weights to a constant tensor\n weights = tf.constant(weights, dtype=tf.float32)\n\n def loss(y_true, y_pred):\n alpha=1.0/weights\n\n # Scale predictions so that the class probas of each sample sum to 1\n y_pred /= tf.reduce_sum(y_pred, axis=-1, keepdims=True)\n\n # Clip to prevent NaN's and Inf's\n _epsilon = tf.convert_to_tensor(K.epsilon(), y_pred.dtype.base_dtype)\n y_pred = tf.clip_by_value(y_pred, _epsilon, 1.0 - _epsilon)\n\n # Do the loss calculation\n pt = tf.where(tf.equal(y_true, 1), y_pred, 1 - y_pred)\n loss = alpha * tf.pow(1.0 - pt, gamma) * tf.log(pt)\n return -tf.reduce_sum(loss, axis=-1)\n\n return loss\n\n# For Keras, custom metrics can be passed at the compilation step but\n# the function would need to take (y_true, y_pred) as arguments and return a single tensor value.\n# Note: seems like this implementation is not stable; it sometimes returns 0 in standalone tests\ndef three_classes_mean_iou(y_true, y_pred):\n \"\"\"\n Calculate per-step mean Intersection-Over-Union (mIOU).\n Computes the IOU for each semantic class and then computes the average over classes.\n \"\"\"\n num_classes = 3\n score, up_opt = tf.metrics.mean_iou(y_true, y_pred, num_classes)\n K.get_session().run(tf.local_variables_initializer())\n with tf.control_dependencies([up_opt]):\n score = tf.identity(score)\n return score\n","sub_path":"tools/loss_metrics_tools.py","file_name":"loss_metrics_tools.py","file_ext":"py","file_size_in_byte":3207,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"430302112","text":"import os\nimport json\nimport urllib\nimport re\n\nfrom bs4 import BeautifulSoup\nimport traceback\n\nfrom ..lib.misc import get_fileext, random_string\n\nfrom ..model.model_tracks import Track, Tag, Attachment, Lyrics, _attachment_types\n\nfrom ..model import init_DBSession, DBSession, commit\nfrom ..model.actions import get_tag\n\n\nimport logging\nlog = logging.getLogger(__name__)\n\n#-------------------------------------------------------------------------------\n# Constants\n#-------------------------------------------------------------------------------\n\nversion = \"0.0\"\n\nfile_component_separator = r'[ .\\\\/\\[\\]]'\n\ndef sep(text):\n return r'%s%s\\d?%s' % (file_component_separator, text, file_component_separator)\ndef or_sep(*args):\n return r'|'.join(args)\n\ntag_extractors = {\n 'opening' : re.compile(or_sep('open','intro','opening','op'), re.IGNORECASE),\n 'ending' : re.compile(or_sep('end' ,'outro','ending' ,'ed'), re.IGNORECASE),\n 'anime' : re.compile(r'anime', re.IGNORECASE),\n}\n\n#skippy = 'string in filename to skip to'\n\n#-------------------------------------------------------------------------------\n# Import from URL\n#-------------------------------------------------------------------------------\ndef walk_url(uri):\n webpage = urllib.request.urlopen(uri)\n soup = BeautifulSoup(webpage.read())\n webpage.close()\n for href in [link.get('href') for link in soup.find_all('a')]:\n if href.endswith('/'):\n log.warn(\"directory crawling from urls is not implmented yet: %s\" % href)\n elif href.endswith('.json'):\n absolute_filename = uri + href #AllanC - todo - this is not absolute if dir's are crawled!\n with urllib.request.urlopen(absolute_filename) as file:\n import_json_data(file, absolute_filename)\n\n\n#-------------------------------------------------------------------------------\n# Import from local filesystem\n#-------------------------------------------------------------------------------\ndef walk_local(uri):\n for root, dirs, files in os.walk(uri):\n for json_filename in [f for f in files if get_fileext(f)=='json']:\n absolute_filename = os.path.join(root , json_filename)\n #relative_path = root.replace(uri,'')\n #relative_filename = os.path.join(relative_path, json_filename)\n with open(absolute_filename, 'r') as file:\n import_json_data(file, absolute_filename)\n\n\n#-------------------------------------------------------------------------------\n# Process JSON leaf\n#-------------------------------------------------------------------------------\ndef import_json_data(source, location=''):\n \"\"\"\n source should be a filetype object for a json file to import\n it shouldnt be relevent that it is local or remote\n \"\"\"\n \n def gen_id_for_track(track):\n id = ''\n \n # Gen 3 letter ID from category,from,title\n def get_tag_name(tags,parent):\n for tag in tags:\n if tag.parent and tag.parent.name == parent:\n return tag.name\n return ''\n def get_first_alpha_char(s):\n for char in s:\n if re.match('[a-zA-Z]',char):\n return char\n return ''\n for tag_name in [get_tag_name(track.tags,tag_type) for tag_type in ['category','from','title']]:\n id += get_first_alpha_char(tag_name)\n \n # If the tags were not present; then split the title string and get the first 3 characters\n if not id:\n s = [f.strip() for f in track.title.split(\" \") if '-' not in f]\n try:\n id = \"\".join([get_first_alpha_char(s[0]), get_first_alpha_char(s[1]), get_first_alpha_char(s[2])])\n except Exception as e:\n id = random_string()\n \n # Normaize to uppercase\n id = id.lower()\n \n # Check for colistions and make unique number\n def get_id_number(id):\n count = 0\n while DBSession.query(Track).filter_by(id=id+str(count)).count():\n count += 1\n return str(count)\n id += get_id_number(id)\n \n return id\n \n \n def get_data():\n try:\n if hasattr(source,'read'):\n data = source.read()\n if isinstance(data, bytes):\n data = data.decode('utf-8')\n return json.loads(data)\n except Exception as e:\n log.warn('Failed to process %s' % location)\n traceback.print_exc()\n \n data = get_data()\n if not data:\n return\n \n # AllanC - useful code to skip to a particular track in processing - i've needed it a couple if times so just leaving it here.\n #global skippy\n #if skippy:\n # if skippy not in location: return\n # skippy = False\n \n if 'description.json' in location:\n try:\n folder = data['name']\n log.info('Importing %s' % folder)\n \n track = Track()\n #track.id = get_id_from_foldername(folder)#data['videos'][0]['encode-hash']\n track.source = ''\n track.duration = data['videos'][0]['length']\n track.title = data['name']\n \n # Add Attachments\n for attachment_type in _attachment_types.enums:\n for attachment_data in data.get(\"%ss\"%attachment_type,[]):\n attachment = Attachment()\n attachment.type = attachment_type\n attachment.location = os.path.join(folder, attachment_data.get('url'))\n \n extra_fields = {}\n for key,value in attachment_data.items():\n if key in ['target','vcodec']:\n #print (\"%s %s\" % (key,value))\n extra_fields[key] = value\n attachment.extra_fields = extra_fields\n \n track.attachments.append(attachment)\n \n # Add Lyrics\n for subtitle in data.get('subtitles',[]):\n lyrics = Lyrics()\n lyrics.language = subtitle.get('language','eng')\n lyrics.content = \"\\n\".join(subtitle.get('lines',[]))\n track.lyrics.append(lyrics)\n \n # Import tags.txt\n try:\n with open(os.path.join(os.path.dirname(location),'tags.txt'), 'r') as tag_file:\n for tag_string in tag_file:\n tag_string = tag_string.strip()\n tag = get_tag(tag_string, create_if_missing=True) \n if tag:\n track.tags.append(tag)\n elif tag_string:\n log.warn('%s: null tag \"%s\"' % (location, tag_string))\n except Exception as e:\n log.warn('Unable to imports tags')\n #traceback.print_exc()\n #exit()\n \n for duplicate_tag in [tag for tag in track.tags if track.tags.count(tag) > 1]:\n log.warn('Unneeded duplicate tag found %s in %s' %(duplicate_tag, location))\n track.tags.remove(duplicate_tag)\n \n # AllanC TODO: if there is a duplicate track.id we may still want to re-add the attachments rather than fail the track entirely\n \n # Finally, use the tags to make a unique id for this track\n track.id = gen_id_for_track(track)\n \n DBSession.add(track)\n commit()\n except Exception as e:\n log.warn('Unable to process %s because %s' % (location, e))\n traceback.print_exc()\n #exit()\n\n\n#-------------------------------------------------------------------------------\n# Import - URI crawl method selector\n#-------------------------------------------------------------------------------\n\ndef import_media(uri):\n \"\"\"\n Recursivly traverse uri location searching for .json files to import\n should be able to traverse local file system and urls\n \"\"\"\n if (uri.startswith('http')):\n walk_url(uri)\n else:\n walk_local(uri)\n\n\n#-------------------------------------------------------------------------------\n# Command Line\n#-------------------------------------------------------------------------------\n\ndef get_args():\n import argparse\n # Command line argument handling\n parser = argparse.ArgumentParser(\n description=\"\"\"Import media to local Db\"\"\",\n epilog=\"\"\"\"\"\"\n )\n parser.add_argument('source_uri' , help='uri of track media data')\n parser.add_argument('--config_uri', help='config .ini file for logging configuration', default='development.ini')\n parser.add_argument('--version', action='version', version=version)\n\n return parser.parse_args()\n\ndef main():\n args = get_args()\n \n # Setup Logging and Db from .ini\n from pyramid.paster import get_appsettings, setup_logging\n #setup_logging(args.config_uri)\n logging.basicConfig(level=logging.INFO)\n settings = get_appsettings(args.config_uri)\n init_DBSession(settings)\n \n import_media(args.source_uri)\n \n \nif __name__ == \"__main__\":\n main()","sub_path":"website/karakara/scripts/import_tracks.py","file_name":"import_tracks.py","file_ext":"py","file_size_in_byte":9326,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"207420698","text":"# coding=utf-8\n\"\"\"\nThis file is sort of a function for the TypeScript front end and handles requests to classify data.\n\"\"\"\nimport sys\nfrom pathlib import Path\n\nimport pandas\nfrom pandas import DataFrame\nfrom sklearn.impute import SimpleImputer\n\nsys.path.append(str(Path(__file__).parent.parent))\n\nimport json\nimport os\n\nfrom buildModel.buildModel import IllegalArgumentError\nfrom buildModel.buildModel import extract_features\nfrom database.database import Database\n\n\ndef fetch_parameters():\n \"\"\"\n This method extracts the command line arguments and resolves them into usable data for this script.\n This means the name of the temporary json file where the post request parameters are stored in.\n The json file needs to contain the following data in exact the described format in order to be usable:\n\n {\n 'dataSet': 1,\n\n 'classifier': \n }\n\n The numbers in 'datasets' are just the ids of the datasets to use in the model.\n\n The string at 'classifier' is the id of the classifier in its data base.\n\n The file must of course be correct json format.\n\n If there is more information in the json file, this is no problem.\n\n There is no checking, if the given values are valid!\n\n :return: All the contents of the specified json file as dict.\n \"\"\"\n if len(sys.argv) < 2:\n raise IllegalArgumentError()\n file_path: str = \" \".join(sys.argv[1:])\n with open(file_path) as file:\n data: dict = json.load(file)\n file.close()\n os.remove(file_path)\n if \"dataSet\" not in data:\n raise IndexError()\n if \"classifier\" not in data:\n raise IndexError()\n return data\n\n\nif __name__ == \"__main__\":\n exec_params = fetch_parameters()\n database = Database([exec_params[\"dataSet\"]], 0)\n data_sets: list[DataFrame] = database.get_data_sets()\n classifier, scaler, sensors, labels, features = database.get_stuff(exec_params[\"classifier\"])\n data_sets: DataFrame = extract_features(features, data_sets, [], SimpleImputer())\n scaled_data = scaler.transform(data_sets)\n prediction = classifier.predict(scaled_data)\n for x in prediction:\n if x == -1:\n print(\"UNKNOWN PATTERN\")\n continue\n print(labels[str(x)])\n","sub_path":"src/classify/classify.py","file_name":"classify.py","file_ext":"py","file_size_in_byte":2251,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"216997167","text":"import time, os, json, requests\nimport pickle\nimport xml.etree.ElementTree\nfrom farmware_tools import log\nfrom farmware_tools import send_celery_script as send\nimport CeleryPy as cp\nfrom os.path import dirname, join\n\n##List of functions and classes for ease of use\n\"\"\"\nSECONDARY FUNCTION CLASSES:\nPlantType(name, lightNeeded, growthTimeS, growthTimeP, growthTimeF)\nPlant(kind, pot)\nPot(region, posx, posy, posz)\nRegion(ident, gs, position)\nStructure()\n___________________________________________________________________\nparameter lists of Structure:\nplantTypeList = plant type repository for accessing data for growth needs\nwaterList = [time] --> when to water which pot\nrepotList = dict[time] = [Plant] --> when to repot a certain plant\nplantList = current plants\npotList = a list of pots. This is useful for watering.\nregionList = a list of the regions... for specific tasks\n___________________________________________________________________\nmethods of Structure:\ncurrDate()\ncurrTime()\nuWaterList(step) --> step = interval between water checks\nuRepotList()\ncheckDead()\ninitFarmLayout()\ninitPlantTypes()\nsendMail(kind) --> kind defines which message to send\n\"\"\"\n\n##CLASSES\nclass PlantType():\n def __init__(self, name, hole, growthTimeS, growthTimeP, growthTimeF, seedx, seedy, seedz):\n \"\"\"\n name : string\n lightNeeded : int (lumen)\n waterNeeded : int (ml/day)\n growthTimeS : int (days)\n growthTimeP : int (days)\n growthTimeF : int (days)\n \"\"\"\n self.hole = hole\n self.name = name\n self.growthTime0 = growthTimeS\n self.growthTime1 = growthTimeP\n self.growthTime2 = growthTimeF\n self.x = seedx\n self.y = seedy\n self.z = seedz\n \nclass Plant():\n growthStage = 0\n daysInStage = 0\n plantId = 0\n def __init__(self, kind, pot):\n \"\"\"\n kind : PlantType\n pot : Pot\n \"\"\"\n self.kind = kind\n self.pot = pot\n self.id = str(Plant.plantId)\n Plant.plantId += 1\n \nclass Pot():\n \"\"\"\n plant : Plant\n full : boolean (presence of peat)\n \"\"\"\n plant = None \n full = False\n def __init__(self, ident, region, posx, posy, posz):\n \"\"\"\n region : Region\n posx : Int\n poxy : Int\n ident : String\n \"\"\"\n self.region = region\n self.ident = ident\n self.x = posx\n self.y = posy\n self.z = posz\n \nclass Region():\n def __init__(self, ident, gs, position, xw, yw, zw):\n \"\"\"\n gs : int\n position : ((,),(,))\n ident : string\n \"\"\"\n self.growthStage = gs\n self.position = position\n self.ident = ident\n self.xWater = xw\n self.yWater = yw\n self.zWater = zw\n\n\nclass Structure():\n \n ##LIST AND VARIABLE INITIALIZATIONS\n plantTypeList = [] #plant type repository for accessing data for growth needs\n waterList = [] #[time] --> when to water\n waterAccessList = [] #[[Int,Int,Int]] --> water access point coords\n repotList = {} #dict[time] = [Plant] --> when to repot a certain plant\n plantList = [] #current plants\n potList = [] #a list of pots. This is useful for watering.\n regionList = {} #a list of the regions... for specific tasks\n toolList = {\"seeder\":[0,0,0], \"planter\":[0,0,0], \"soilSensor\":[0,0,0]}\n\n def __init__(self):\n self.initPlantTypes()\n self.initFarmLayout()\n self.uWaterList(2)\n self.loadPlants()\n self.loadPots()\n self.uRepotList()\n self.initTools()\n \n ##TIME AND DATE FUNCTIONS\n def currDate(self):\n \"\"\"\n return current date as string in dd/mm/yyyy format\n \"\"\"\n return str(time.localtime(time.time())[2]) + \"/\" + str(time.localtime(time.time())[1]) + \"/\" + str(time.localtime(time.time())[0])\n \n def currTime(self):\n \"\"\"\n return current time as string in hh:mm format\n \"\"\"\n return str(time.localtime(time.time())[3]) + \":\" + str(time.localtime(time.time())[4]) \n \n ##UPDATE FUNCTIONS\n def uWaterList(self, step):\n \"\"\"\n Divide up the day, to water at regular intervals (step).\n \"\"\"\n for i in range(0, 24):\n if i % step == 0:\n self.waterList.append(i)\n return\n \n \n def uRepotList(self):\n \"\"\"\n empty old repotList and check each plant for the remaining days, before repot.\n \"\"\"\n self.repotList == {}\n for plant in self.plantList:\n if plant.growthStage == 0:\n remTime = plant.kind.growthTime0 - plant.daysInStage\n elif plant.growthStage == 1:\n remTime = plant.kind.growthTime1 - plant.daysInStage\n elif plant.growthStage == 2:\n remTime = plant.kind.growthTime2 - plant.daysInStage\n \n if remTime in self.repotList:\n self.repotList[remTime].append(plant)\n return\n \n ##INITIALIZATION FUNCTIONS\n def initFarmLayout(self):\n filer = join(dirname(__file__), 'potLayout.xml')\n try:\n e = xml.etree.ElementTree.parse(filer).getroot()\n except Exception as error:\n log(repr(error))\n log(\"Accessed potLayout.xml\", message_type='struct')\n for region in e:\n #init regions\n x1 = int(region.attrib[\"x1\"])\n x2 = int(region.attrib[\"x2\"])\n y1 = int(region.attrib[\"y1\"])\n y2 = int(region.attrib[\"y2\"])\n gs = int(region.attrib[\"gs\"])\n ident = int(region.attrib[\"id\"])\n xw = int(region.attrib[\"xw\"])\n yw = int(region.attrib[\"yw\"])\n zw = int(region.attrib[\"zw\"])\n \n self.regionList[region.attrib[\"id\"]] = Region(ident, gs, ((x1, y1), (x2, y2)), xw, yw, zw)\n self.waterAccessList.append([xw, yw, zw])\n \n if region.attrib[\"gs\"] == \"0\":\n #init bacs in region 0\n for bac in region:\n x1 = int(bac.attrib[\"x1\"])\n x2 = int(bac.attrib[\"x2\"])\n y1 = int(bac.attrib[\"y1\"])\n y2 = int(bac.attrib[\"y2\"])\n z = int(bac.attrib[\"z\"])\n border = int(bac.attrib[\"border\"])\n dist = int(bac.attrib[\"dist\"])\n \n for i in range(x1 + border, x2 - border, dist):\n for j in range(y1 + border, y2 - border, dist):\n pot = Pot(region.attrib[\"id\"] + \",\" + str(i) + \",\" + str(j), self.regionList[region.attrib[\"id\"]], i, j, z)\n self.potList.append(pot)\n \n else:\n #init pots in other regions\n for pot in region:\n pot = Pot(pot.attrib[\"id\"], self.regionList[region.attrib[\"id\"]], int(pot.attrib[\"x\"]), int(pot.attrib[\"y\"]), int(pot.attrib[\"z\"]))\n self.potList.append(pot)\n log(\"Loaded pot layout.\", message_type='info')\n\n def initPlantTypes(self):\n filer = join(dirname(__file__), 'plantTypes.xml')\n try:\n e = xml.etree.ElementTree.parse(filer).getroot()\n except Exception as error:\n log(repr(error))\n log(\"Accessed plantTypes.xml\", message_type='info')\n for plantType in e:\n name = plantType.attrib[\"name\"]\n if int(plantType.attrib[\"hole\"]) == 1:\n hole = True\n else:\n hole = False\n gt0 = int(plantType.attrib[\"gt0\"])\n gt1 = int(plantType.attrib[\"gt1\"]) \n gt2 = int(plantType.attrib[\"gt2\"]) \n seedx = int(plantType.attrib[\"x\"])\n seedy = int(plantType.attrib[\"y\"])\n seedz = int(plantType.attrib[\"z\"])\n \n \n self.plantTypeList.append(PlantType(name, hole, gt0, gt1, gt2, seedx, seedy, seedz))\n log(\"Loaded plant types.\", message_type='info')\n \n def initTools(self):\n filer = join(dirname(__file__), 'tools.xml')\n try:\n e = xml.etree.ElementTree.parse(filer).getroot()\n except Exception as error:\n log(repr(error))\n log(\"Accessed tools.xml\", message_type='info')\n for tool in e:\n ident = tool.attrib[\"ident\"]\n pos = [int(tool.attrib[\"x\"]),int(tool.attrib[\"y\"]),int(tool.attrib[\"z\"])] \n \n self.toolList[ident] = pos\n log(\"Loaded plant types.\", message_type='info')\n \n def savePlants(self):\n try:\n for plant in self.plantList:\n fname = plant.id + \".txt\"\n filer = join(dirname(__file__), 'plants', fname)\n f = open(filer, \"wb\")\n pickle.dump(plant, f)\n f.close()\n except Exception as error:\n log(repr(error))\n log(\"Saved plant objects.\", message_type='info')\n \n def loadPlants(self):\n log(\"Loading plants.\", message_type='info')\n try:\n for file in os.listdir(join(dirname(__file__), 'plants')):\n if file != \"save.txt\":\n if file.endswith(\".txt\"):\n f = open(\"./plants/\" + file, \"rb\")\n plant = pickle.Unpickler(f).load()\n self.plantList.append(plant)\n f.close()\n except Exception as error:\n log(repr(error))\n log(\"Loaded plant objects.\", message_type='info')\n \n def savePots(self):\n try:\n for pot in self.potList:\n fname = pot.ident + \".txt\"\n filer = join(dirname(__file__), 'pots', fname)\n f = open(filer, \"wb\")\n pickle.dump(pot, f)\n f.close()\n except Exception as error:\n log(repr(error))\n log(\"Saved pot objects.\", message_type='info')\n \n def loadPots(self):\n log(\"Loading pots.\", message_type='info')\n try:\n for file in os.listdir(join(dirname(__file__), 'pots')):\n if file != \"save.txt\":\n if file.endswith(\".txt\"):\n f = open(\"./pots/\" + file, \"rb\")\n pot = pickle.Unpickler(f).load()\n self.potList.append(pot)\n f.close()\n except Exception as error:\n log(repr(error))\n log(\"Loaded pot objects.\", message_type='info')\n \n ##SEND MAIL FUNCTION(S)\n def sendMail(self, kind):\n \"\"\"\n NOT FUNCTIONAL!!!!!!!\n Send a mail to the agriculturist, informing hime of \n 0 : Plants that are ready to be moved\n 1 : Empty pot spots\n 2 : ...\n \n else : an error\n \"\"\"\n me = \"email\"\n you = \"me\"\n if kind == 0:\n textfile = \"./plantsDonemsg.txt\"\n subject = \"There are plants done.\"\n elif kind == 1:\n textfile = \"./needPeatmsg.txt\"\n subject = \"Some pots need new peat.\"\n else:\n textfile = \"./errormsg.txt\"\n subject = \"An error occurred.\"\n \nclass Sequence:\n def __init__(self, name='New Sequence', color='gray'):\n self.sequence = {\n 'name': name,\n 'color': color,\n 'body': []\n }\n self.add = self.sequence['body'].append\n\n \n##=================================================================##\n##=== MAIN PART OF THE PROGRAM ===##\n##=================================================================##\n \nclass MyFarmware(): \n coords = [0,0,0]\n TOKEN = ''\n def __init__(self,farmwarename):\n self.farmwarename = farmwarename\n\n ##FUNCTION CONTROL\n def read(self, pin, mode, label):\n \"\"\" pin : int 64 soil sensor\n mode : 0 digital 1 analog\n label : description str\n \"\"\"\n try:\n info = send(cp.read_pin(number=pin, mode=mode, label = label))\n return info\n except Exception as error:\n log(\"Read --> \" + repr(error))\n \n def reading(self, pin, signal ):\n \"\"\"\n pin : int pin number\n signal : 1 analog / 0 digital\n \"\"\"\n\n #Sequence reading pin value \n ss = Sequence(\"40\", \"green\")\n ss.add(log(\"Read pin {}.\".format(pin), message_type='info'))\n ss.add(self.read(pin, signal,'Soil'))\n ss.add(log(\"Sensor read.\", message_type='info'))\n send(cp.create_node(kind='execute', args=ss.sequence))\n \n def waterSensor(self):\n self.reading(63,0)\n self.waiting(2000)\n self.reading(64,1)\n \n headers = {'Authorization': 'bearer {}'.format(os.environ['FARMWARE_TOKEN']), 'content-type': \"application/json\"}\n\n response = requests.get(os.environ['FARMWARE_URL'] + 'api/v1/bot/state', headers=headers)\n\n bot_state = response.json()\n value = bot_state['pins']['64']['value']\n log(str(value), message_type='info')\n return (value > 400)\n \n def waterFall(self, mm): #<-- implement\n try:\n self.water_on()\n self.waiting(mm*100)\n self.water_off()\n except Exception as error:\n log(\"Water --> \" + repr(error))\n def Write(self, pin, val, m):\n \"\"\"\n pin : int 10 for vaccum (0 up to 69)\n val : 1 on / 0 off\n m : 0 digital / 1 analog\n \"\"\"\n info = send(cp.write_pin(number=pin, value=val , mode=m))\n return info\n\n def vacuum_on(self):\n on = Sequence(\"0\", \"green\")\n on.add(log(\"Vaccum on \", message_type='info'))\n on.add(self.Write(10,1,0))\n send(cp.create_node(kind='execute', args=on.sequence))\n\n def vacuum_off(self):\n off = Sequence(\"01\", \"green\")\n off.add(log(\"Vaccum off \", message_type='info'))\n off.add(self.Write(10,0,0))\n send(cp.create_node(kind='execute', args=off.sequence)) \n\n def water_on(self):\n won = Sequence(\"02\", \"green\")\n won.add(self.Write(9,1,0))\n won.add(log(\"Water on \", message_type='info'))\n send(cp.create_node(kind='execute', args=won.sequence)) \n\n def water_off(self):\n wof = Sequence(\"03\", \"green\")\n wof.add(self.Write(9,0,0))\n wof.add(log(\"Water off \", message_type='info'))\n send(cp.create_node(kind='execute', args=wof.sequence))\n \n ##MOVEMENT\n def moveRel(self, distx, disty, distz, spd):\n \"\"\"\n distx:Int ,disty:Int ,distz:Int\n spd :Int\n \"\"\"\n log(\"moving \" + str(distx) + \", \" + str(disty) + \", \" + str(distz), message_type='debug')\n info = send(cp.move_relative(distance=(distx, disty, distz), speed=spd))\n return info\n \n def move(self, posx, posy, posz, spd):\n \"\"\"\n posx:Int ,posy:Int ,posz:Int\n spd :Int\n \"\"\"\n log(\"going to \" + str(posx) + \", \" + str(posy) + \", \" + str(posz), message_type='debug')\n info = send(cp.move_absolute(location=[posx, posy, posz], offset=[0,0,0], speed=spd))\n self.coords = [posx, posy, posz]\n return info\n \n def waiting(self,time):\n try:\n log(\"Waiting {} ms\".format(time), message_type='debug')\n info = send(cp.wait(milliseconds=time))\n return info\n except Exception as error:\n log(\"Wait --> \" + repr(error))\n \n def goto(self, x, y, z):\n s = Sequence(\"goto\", \"green\")\n s.add(self.move(self.coords[0], self.coords[1], 0, 100))\n s.add(self.move(self.coords[0], y, 0, 100))\n s.add(self.move(x, y, 0, 100))\n s.add(self.move(x, y, z, 100))\n s.add(log(\"Moved to \"+str(x)+\", \"+str(y)+\", \"+str(z)+\".\", message_type='info'))\n info = send(cp.create_node(kind='execute', args=s.sequence)) \n self.coords = [x, y, z]\n return info\n \n def getTool(self, tool):\n l = self.struct.toolList[tool]\n s = Sequence(\"getTool\", \"green\")\n s.add(self.goto(l[0] , l[1], l[2]))\n s.add(self.move(l[0] - 100, l[1], l[2], 50))\n s.add(log(\"Getting \"+tool+\".\", message_type='info'))\n info = send(cp.create_node(kind='execute', args=s.sequence)) \n self.coords = [l[0] -100, l[1],l[2]]\n return info\n \n def putTool(self, tool):\n l = self.struct.toolList[tool]\n s = Sequence(\"putTool\", \"green\")\n s.add(self.goto(l[0] - 100 , l[1], l[2]-22))\n s.add(self.move(l[0], l[1], l[2], 50))\n s.add(self.move(l[0], l[1], l[2] + 100, 50))\n s.add(log(\"Putting back \"+tool+\".\", message_type='info'))\n send(cp.create_node(kind='execute', args=s.sequence)) \n self.coords = [l[0], l[1],l[2] + 100]\n \n def calibrate(self):\n i = 0\n while True and i<21:\n try:\n s = Sequence(\"xCalib\", \"green\")\n s.add(self.moveRel(-100,0,0,50))\n s.add(log(\"Calibrating x axis.\", message_type='info'))\n send(cp.create_node(kind='execute', args=s.sequence)) \n i += 1\n except:\n break\n \n i = 0\n while True and i<14:\n try:\n s = Sequence(\"yCalib\", \"green\")\n s.add(self.moveRel(0,-100,0,50))\n s.add(log(\"Calibrating y axis.\", message_type='info'))\n send(cp.create_node(kind='execute', args=s.sequence)) \n i += 1\n except:\n break\n \n i = 0\n while True and i<4:\n try:\n s = Sequence(\"zCalib\", \"green\")\n s.add(self.moveRel(0,0,100,50))\n s.add(log(\"Calibrating z axis.\", message_type='info'))\n send(cp.create_node(kind='execute', args=s.sequence)) \n i += 1\n except:\n break\n \n ##SEQUENCES \n def water(self):\n whereWater = [] #a list that is going to contain a value for each access point, determining how much water is needed. i.e. if the point is full, the value will be 0\n \n l = self.struct.waterAccessList #this list is read into memory when the program starts. It contains the position of each water access hole, read from potLayout.xml.\n \n self.getTool(\"soilSensor\") #self explanatory. It gets the soil sensor tool.\n \n for i in l: # for each water access point\n self.goto(i[0], i[1], i[2]+78) # moves the arm to a position above the water access point. The +78 is the length of the soil sensor tool, so the arm needs to go to 78mm above the position, putting the tip of the sensor exactly to the right position.\n sensor = self.waterSensor() # this function checks if the soil sensor has contact with water, so sensor is \"True\" if there is water at that height.\n \n while sensor == False and self.coords[2] >= -500: # while the sensor doesn't find water <-- !!!INSERT PROPER FLOOR HEIGHT HERE\n s = Sequence(\"findWater\", \"green\") # create a sequence (basically a wrapper for the whole action, to keep the robot from deadlocking)\n s.add(self.move(i[0], i[1], self.coords[2] - 10, 20)) # move down 1cm. (This also implies that the height of the water is measured to an accuracy of 1cm. Since this is not rocket science, this is largely sufficient. You just need to keep it in mind when setting the position of the water access point, as the maximum height needs a little leeway.\n s.add(log(\"Looking for water.\", message_type='info')) # This log gives absolutely no useful information, but the last action in a sequence always has to be a log, so it HAS to be there.\n send(cp.create_node(kind='execute', args=s.sequence)) # send the sequence to the API. If you want, you can backtrack this through \"farmware_tools.py\" and \"CeleryPy.py\". It puts it into a format understandable by farmbot (CeleryScript) and puts it into JSON format before sending it to the API.\n \n self.coords[2] -= 10 # This adjusts the robot's position. As it is a pain to get information from the API, we found it easier to internally remember the position, instead of sending a query to the robot each time, to get it. \n sensor = self.waterSensor() # reads the sensor again\n self.waiting(2000) # waits two seconds, as the sensor can take a moment sometimes.\n \n whereWater.append(i[2]+78-self.coords[2]) # Adds the level of water that is missing to the list\n #WHILE END\n \n self.putTool(\"soilSensor\") # puts back the soil sensor.\n \n for i in range(len(l)): # for each water access point\n if whereWater[i] > 0: # if the level in whereWater is > 0 (so if the level of water needed is not nada)\n self.goto(l[i][0], l[i][1], l[i][2]+100) # go to the access point (This time without the offset for the tool)\n self.waterFall(whereWater[i]) # unleash the water :) The value entered here is in mm. The function \"waterFall\" (391) transforms this value into seconds. <-- WE NEVER MEASURED THE OUTPUT PER SECOND; SO THE VALUE IN THIS FUNCTION HAS TO BE ADJUSTED!!!\n \n self.goto(0,-100,0)\n self.goto(0,0,0)\n log(\"finished watering sequence\", message_type='info')\n \n def makePlant(self, pot, tplant): #This just creates a virtual image of a plant with a lot of infos. Don't worry about this one.\n if pot.plant == None:\n plantTyper = next((y for y in self.struct.plantTypeList if y.name == tplant), None)\n plant = Plant(plantTyper, pot)\n pot.plant = plant\n self.struct.plantList.append(plant)\n \n \n mess= plant\n mes = str(mess)\n log( mes , message_type='info')\n \n mess= plant.kind\n mes = str(mess)\n log( mes , message_type='info')\n \n \n log(\"self\", message_type='info')\n \n if plant.kind.hole == 1:\n log(\"if\", message_type='info')\n return plant,plant\n else:\n log(\"else\", message_type='info')\n return None,plant\n \n def plant(self):\n log(\"Starting the plant sequence\", message_type='info')\n filer = join(dirname(__file__), 'input.txt') # path to the input file. This part has to be changed obviously if you get the proper webapp working.\n holeL = [] # list of the plants to be planted that need a hole for the seed\n plantL = [] # list of all plants to be planted\n readL = [] # list to read the unsorted information from \"input.txt\" into.\n\n #READ INPUT\n f = open(filer, \"rb\") # opens the file for reading\n for line in f: # read one line from f into a STRING called \"line\" (each line contains a plantType and a number)\n if not(line.isspace()): \n line = line.split() # split the line at the \" \" symbol. This makes line into an array of strings with line[0] being the number of plants and line[1] being the plant type.\n readL.append((line[0],line[1])) # adds the number and type to readL in a tuple. \n f.close() # closes the file for reading.\n log(\"file read\", message_type='info')\n #FILL holeL and plantL\n for p in readL: # for every tuple (number, type) in readL\n for z in range(int(p[0])): # makes the next part execute \"number\" times \n potter = next((pot for pot in self.struct.potList if pot.plant == None), None) # pot generator. This automatically chooses the next best !empty! pot from struct.potList, which contains the pot objects created from the data read from \"potLayout.xml\". \n log(\"potter seems to work\", message_type='info')\n x = self.makePlant(potter, p[1]) # uses the makePlant function on line 556 to create a plant object corresponding to the soon to be planted plant. The plant is initialized with a pot (potter) and a type (p[1])\n log(\"x doesnt work currently\", message_type='info')\n if x[0] != None: # This is a bit weird. The makePlant function returns a tuple of either (None, ) if no hole is needed or (, ) if a hole is needed.\n holeL.append(x[0]) # if a hole is needed, append the plant object to the holeL list.\n log(\"if dont know worked\", message_type='info')\n plantL.append(x[1]) # either way, append the plant object to the planting list.\n log(\"did the for read loop\", message_type='info') \n self.struct.savePlants() # saves the plants to the \"plants\" folder using Pickler.\n self.struct.savePots() # saves the pots to the \"pots\" folder using Pickler.\n self.getTool(\"planter\") # gets the 3D printed cone tool also known as a \"hole-poker\" in very professional terms...\n log(\"got the planter\", message_type='info')\n #HOLES\n for p in holeL: # for each plant in the (w)hole list (pardon the pun)\n self.goto(p.pot.x, p.pot.y, p.pot.z) # goto the position of the pot. Since this position puts the arm exactly on the surface of the pot, the tool (which protrudes a little further) will automatically be inside the pot.\n\n self.putTool(\"planter\") # put the \"hole-poker\" back\n self.getTool(\"seeder\") # get the suction needle tool\n\n #PLANTING\n for p in plantL: # for each plant in the planting list\n self.goto(p.kind.x, p.kind.y, p.kind.z) # goto the position of the seed container defined in \"plantTypes.xml\"\n self.vacuum_on() # commence suction :)\n self.goto(p.pot.x + 15, p.pot.y, p.pot.z + 75) # goto the pot where the seed is needed. Notice the offset again, due to the length of the tool which has to be taken into account.\n self.vacuum_off() # stop suction. (Seed will hopefully drop into the pot...)\n \n self.putTool(\"seeder\") # put back the suction needle tool \n log(\"used the seeder\", message_type='info')\n f = open(filer, \"wb\") # This opens the file for writing, effectively overwriting anything inside. So don't be surprised if your test only works once. The commands don't stick around.\n f.close() # close the now empty file\n \n def repot(self): # This was supposed to be implemented as soon as the grabber tool for pots was functional, but we never got that far.\n return \n \n \n ##START POINT\n def run(self):\t\t\t\t\t\t#START POINT OF THE PROGRAM\n log(\"Farmware running...\", message_type='info')\n self.struct = Structure()\t\t\t\t#This initializes the layout of the farm. It loads pots and plants that were created in a former run of the program from the \"plants\" and \"pots\" directories. It loads all existing pots from potLayout.xml. The pots are determined be coords, so the existing pots should normally not be overwritten by this.\n log(\"Data loaded.\", message_type='info')\t\t#Just some fancy information.\n \n self.goto(0,0,0) #send the bot to 0,0,0. Not necessary, but a nice check to see if the origin is properly set.\n # self.water()\t\t\t\t\t\t#Water sequence at line 525\n send_message(message='Hello World!', message_type='success', channel=toast)\n \n send_message(message='Does this work?', message_type='info', channel=toast)\n \n send_message(message='Hello World!', message_type='success', channel=email)\n self.plant() #Plant sequence at line 561\n log(\"Execution successful.\", message_type='info')\n \n ##TESTS\n \n #self.s.sendMail(0)\n #self.s.initFarmLayout()\n #self.s.initPlantTypes()\n #print(struct.currDate())\n #print(struct.currTime())\n #print(list(pot.region.ident for pot in self.s.potList))\n #print(list(self.s.regionList[region].ident for region in self.s.regionList))\n #print(list(pt.name for pt in self.s.plantTypeList))\n #print(\"lol Sylvain\") \n #plant pickle test\n #self.s.plantList.append(Plant(\"plant1\", potList[0].ident))\n #print(list(plant.id for plant in plantList))\n #savePlants()\n \"\"\"\n print(self.struct.toolList, \" <-- toollist\")\n print(self.struct.plantList, \" <-- plantlist\")\n print(self.struct.waterAccessList, \" <-- waterAccessList\")\n print(self.struct.plantTypeList, \" <-- plantTypeList\")\n print(self.struct.waterList, \" <-- waterList\")\n print(self.struct.repotList, \" <-- repotList\")\n print(len(self.struct.potList), \" <-- potList\")\n print(self.struct.regionList, \" <-- regionList\")\n print(self.struct.toolList, \" <-- toolList\")\n \"\"\"\n #loadPlants()\n \n \n ##MAIN WHILE\n while True:\n \"\"\"\n check timelists for tasks, else wait the remaining time\n \"\"\"\n break\n currHour = int(self.s.currTime().split(\":\")[0])\n if (currHour in self.s.waterList) and (self.s.waterList != []):\n self.water()\n self.s.waterList = self.s.waterList[1:]\n \n if (currHour in self.s.repotList) and (self.s.repotList != []):\n self.repot()\n del self.s.repotList[currHour] \n \n currMin = int(self.s.currTime().split(\":\")[1]) \n self.waiting((59 - currMin)*60*1000) #59 instead of 60 as safety\n \n \n \n","sub_path":"FARMWARE.py","file_name":"FARMWARE.py","file_ext":"py","file_size_in_byte":30880,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"98308725","text":"import logging\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nfrom core import utils\nfrom core import layers\nfrom core import backbones\nnumber_of_features_per_level = utils.number_of_features_per_level\nSingleConv = layers.SingleConv\nDoubleConv = layers.DoubleConv\n_DoubleConv = layers._DoubleConv\nDecoder = layers.Decoder\nConv_Bn_Activation = layers.Conv_Bn_Activation\ncreat_torchvision_backbone = backbones.creat_torchvision_backbone\n\n\n\nclass UNet_2d_backbone(nn.Module):\n def __init__(self, in_channels, out_channels, basic_module, f_maps=64, layer_order='bcr',\n num_groups=8, num_levels=4, is_segmentation=True, testing=False,\n conv_kernel_size=3, pool_kernel_size=2, conv_padding=1, backbone='resnet50', pretrained=True, **kwargs):\n super(UNet_2d_backbone, self).__init__()\n self.out_channels = out_channels\n if in_channels != 3 and pretrained:\n logging.info('Reinitialized first layer')\n\n if isinstance(f_maps, int):\n f_maps = number_of_features_per_level(f_maps, num_levels=num_levels)\n\n assert isinstance(f_maps, list) or isinstance(f_maps, tuple)\n assert len(f_maps) > 1, \"Required at least 2 levels in the U-Net\"\n\n # create encoder path\n self.encoders = create_encoder(in_channels, backbone, pretrained=pretrained, final_flatten=False)\n \n # create decoder path\n self.decoders = create_decoders(f_maps, basic_module, conv_kernel_size, conv_padding, layer_order, \n num_groups, upsample=True, conv_type='2d')\n\n \n self.conv = basic_module(f_maps[0], f_maps[0]//2, conv_type='2d',\n encoder=False,\n kernel_size=conv_kernel_size,\n order='bcr',\n num_groups=num_groups,\n padding=conv_padding)\n # self.classifier = Conv_Bn_Activation(in_channels=f_maps[0], out_channels=self.out_channels, activation=None)\n self.classifier = SingleConv(f_maps[0]//2, out_channels, conv_type='2d', kernel_size=1, order='bc')\n\n def forward(self, x):\n # encoder part\n encoders_features = []\n for encoder in self.encoders:\n x = encoder(x)\n # reverse the encoder outputs to be aligned with the decoder\n encoders_features.insert(0, x)\n\n # remove the last encoder's output from the list\n # !!remember: it's the 1st in the list\n encoders_features = encoders_features[1:]\n\n # decoder part\n for decoder, encoder_features in zip(self.decoders, encoders_features):\n # pass the output from the corresponding encoder and the output\n # of the previous decoder\n x = decoder(encoder_features, x)\n\n # # apply final_activation (i.e. Sigmoid or Softmax) only during prediction. During training the network outputs\n # # logits and it's up to the user to normalize it before visualising with tensorboard or computing validation metric\n # if self.testing and self.final_activation is not None:\n # x = self.final_activation(x)\n # return x\n \n x = F.interpolate(x, size=x.size()[2]*2, mode='bilinear')\n x = self.conv(x)\n x = self.classifier(x)\n return nn.Sigmoid()(x)\n\n\n\n # def forward(self, x):\n # f1 = self.conv1(x)\n # f2 = self.conv2(f1)\n # f3 = self.conv3(f2)\n # f4 = self.conv4(f3)\n # f5 = self.conv5(f4)\n\n # features = [f1, f2, f3, f4, f5]\n # x = self.decoder(features)\n # pass\n # return x\n\n\nclass UNet_2d(nn.Module):\n def __init__(self, input_channels, num_class, pool_kernel_size=2, stages=5, root_channel=32, bilinear=True):\n super(UNet_2d, self).__init__()\n self.bilinear = bilinear\n self.name = '2d_unet'\n\n # model2 = nn.Sequential(collections.OrderedDict([\n # ('conv1', Conv_Bn_Activation(in_channels=root_channel, out_channels=root_channel)),\n # ('conv2', nn.ReLU()),\n # ('conv3', nn.Conv2d(20,64,5)),\n # ('conv4', nn.ReLU())\n # ]))\n\n self.conv1 = _DoubleConv(in_channels=input_channels, out_channels=root_channel, mid_channels=root_channel)\n self.conv2 = _DoubleConv(in_channels=root_channel, out_channels=root_channel*2)\n self.conv3 = _DoubleConv(in_channels=root_channel*2, out_channels=root_channel*4)\n self.conv4 = _DoubleConv(in_channels=root_channel*4, out_channels=root_channel*8)\n\n self.intermedia = _DoubleConv(in_channels=root_channel*8, out_channels=root_channel*8)\n\n self.conv5 = _DoubleConv(in_channels=root_channel*16, out_channels=root_channel*4)\n self.conv6 = _DoubleConv(in_channels=root_channel*8, out_channels=root_channel*2)\n self.conv7 = _DoubleConv(in_channels=root_channel*4, out_channels=root_channel)\n self.conv8 = _DoubleConv(in_channels=root_channel*2, out_channels=root_channel)\n\n self.pooling = nn.MaxPool2d(kernel_size=pool_kernel_size)\n # self.upsampling = F.interpolate(x, size=size)\n self.classifier = Conv_Bn_Activation(in_channels=root_channel, out_channels=num_class, activation=None)\n\n def forward(self, x):\n # TODO: dynamic\n align_corner = False\n low_level = []\n x = self.conv1(x)\n low_level.append(x)\n x = self.pooling(x)\n\n x = self.conv2(x)\n low_level.append(x)\n x = self.pooling(x)\n \n x = self.conv3(x)\n low_level.append(x)\n x = self.pooling(x)\n \n x = self.conv4(x)\n low_level.append(x)\n x = self.pooling(x)\n\n x = self.intermedia(x)\n tensor_size = list(x.size())\n x = F.interpolate(x, size=(tensor_size[2]*2, tensor_size[3]*2), mode='bilinear', align_corners=align_corner)\n\n x = torch.cat([x, low_level.pop()],1)\n x = self.conv5(x)\n tensor_size = list(x.size())\n x = F.interpolate(x, size=(tensor_size[2]*2, tensor_size[3]*2), mode='bilinear', align_corners=align_corner)\n \n x = torch.cat([x, low_level.pop()],1)\n x = self.conv6(x)\n tensor_size = list(x.size())\n x = F.interpolate(x, size=(tensor_size[2]*2, tensor_size[3]*2), mode='bilinear', align_corners=align_corner)\n\n x = torch.cat([x, low_level.pop()],1)\n x = self.conv7(x)\n tensor_size = list(x.size())\n x = F.interpolate(x, size=(tensor_size[2]*2, tensor_size[3]*2), mode='bilinear', align_corners=align_corner)\n\n x = torch.cat([x, low_level.pop()],1)\n x = self.conv8(x)\n return nn.Sigmoid()(self.classifier(x))\n\n\ndef create_encoder(in_channels, backbone, pretrained=True, final_flatten=False):\n base_model = creat_torchvision_backbone(in_channels, backbone, pretrained=pretrained, final_flatten=False)\n base_layers = list(base_model.children())[0]\n conv1 = nn.Sequential(*base_layers[:3])\n conv2 = nn.Sequential(*base_layers[3:5])\n conv3 = nn.Sequential(*base_layers[5])\n conv4 = nn.Sequential(*base_layers[6])\n conv5 = nn.Sequential(*base_layers[7])\n encoders = [conv1, conv2, conv3, conv4, conv5]\n return nn.ModuleList(encoders)\n\n\ndef create_decoders(f_maps, basic_module, conv_kernel_size, conv_padding, layer_order, num_groups, upsample, conv_type):\n # create decoder path consisting of the Decoder modules. The length of the decoder list is equal to `len(f_maps) - 1`\n decoders = []\n reversed_f_maps = list(reversed(f_maps))\n for i in range(len(reversed_f_maps) - 1):\n if basic_module == DoubleConv:\n in_feature_num = reversed_f_maps[i] + reversed_f_maps[i + 1]\n else:\n in_feature_num = reversed_f_maps[i]\n\n out_feature_num = reversed_f_maps[i + 1]\n\n # TODO: if non-standard pooling was used, make sure to use correct striding for transpose conv\n # currently strides with a constant stride: (2, 2, 2)\n\n _upsample = True\n if i == 0:\n # upsampling can be skipped only for the 1st decoder, afterwards it should always be present\n _upsample = upsample\n\n decoder = Decoder(in_feature_num, out_feature_num, conv_type,\n basic_module=basic_module,\n conv_layer_order=layer_order,\n conv_kernel_size=conv_kernel_size,\n num_groups=num_groups,\n padding=conv_padding,\n upsample=_upsample)\n decoders.append(decoder)\n return nn.ModuleList(decoders)\n","sub_path":"core/unet/unet_2d.py","file_name":"unet_2d.py","file_ext":"py","file_size_in_byte":8700,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"559076648","text":"from sqlalchemy import create_engine\nimport os\nimport pandas as pd\nfrom flaskgolf.data_pulls import pull_player_info, pull_leaderboard, pull_round_results, pull_full_tourney_data, scoreboard_pull\n\ndef load_player_info():\n '''\n Load player info db\n '''\n df_player = pull_player_info()\n engine = create_engine(os.environ['AWS_DB_ENGINE'])\n df_player.to_sql(\"golferinfo\", engine, if_exists='replace', index=False)\n\n\ndef load_round_results():\n '''\n Load round_results\n '''\n df_lb = pull_round_results()\n engine = create_engine(os.environ['AWS_DB_ENGINE'])\n df_lb.to_sql(\"round_results\", engine, if_exists='replace', index=False)\n\n\ndef load_leaderboard():\n '''\n Load leaderboard\n '''\n df_lb = pull_leaderboard()\n engine = create_engine(os.environ['AWS_DB_ENGINE'])\n df_lb.to_sql(\"leaderboard\", engine, if_exists='replace', index=False)\n\n\ndef load_scoreboard():\n '''\n Load game scoreboard\n '''\n df_scoreboard = scoreboard_pull()\n engine = create_engine(os.environ['AWS_DB_ENGINE'])\n df_scoreboard.to_sql(\"scoreboard\", engine, if_exists='replace', index=False)\n\n\ndef load_tourney_info():\n '''\n Load full tourney data\n '''\n df_tourney = pull_full_tourney_data()\n engine = create_engine(os.environ['AWS_DB_ENGINE'])\n df_tourney.to_sql(\"tourney_info\", engine, if_exists='replace', index=False)\n\n\ndef load_world_rankings():\n '''\n Manual right now.\n Update the .xlsx -> run function\n '''\n df_wr = pd.read_excel('world_rankings.xlsx')\n engine = create_engine(os.environ['AWS_DB_ENGINE'])\n df_wr.to_sql(\"world_rankings\", engine, if_exists='replace', index=False)\n\n\nif __name__==\"__main__\":\n load_round_results()\n load_scoreboard()\n load_leaderboard()\n","sub_path":"flaskgolf/data_loads.py","file_name":"data_loads.py","file_ext":"py","file_size_in_byte":1757,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"580131660","text":"#!/usr/bin/env python\n\nimport cv2 \nimport re, sys\nimport fnmatch, shutil, subprocess\nfrom IPython.utils import io\nimport glob\nimport random\nimport json\nimport os \n\nimport numpy as np\nfrom keras.models import *\nfrom keras.layers import Input, concatenate, merge, Conv2D, MaxPooling2D, UpSampling2D, Dropout, Cropping2D\nfrom keras.optimizers import *\nfrom keras.callbacks import ModelCheckpoint, LearningRateScheduler\nfrom keras.preprocessing.image import ImageDataGenerator, array_to_img, img_to_array, load_img\nfrom keras.losses import binary_crossentropy\nimport keras.backend as K\nfrom keras import backend as keras\n#from helper_functions import *\nfrom helper_utilities import *\n\nfrom loss_functions import *\n\n\n#from helpers_dicom import DicomWrapper as dicomwrapper\n\n#Fix the random seeds for numpy (this is for Keras) and for tensorflow backend to reduce the run-to-run variance\nfrom numpy.random import seed\nseed(12345)\nfrom tensorflow import set_random_seed\nset_random_seed(12345)\n\n#import matplotlib.pyplot as plt\n#%matplotlib inline\n\nimport tensorflow as tf\n#GPU_CLUSTER = \"0,1,2,3,4,5,6,7\"\nGPU_CLUSTER = \"4,5\"\nos.environ[\"CUDA_VISIBLE_DEVICES\"] = GPU_CLUSTER\nGPUs = len(GPU_CLUSTER.split(','))\n# os.environ[\"CUDA_VISIBLE_DEVICES\"] = \"0,1\"\n# #os.environ[\"CUDA_VISIBLE_DEVICES\"] = \"4,5,6,7\"\n# #os.environ[\"CUDA_VISIBLE_DEVICES\"] = \"0,1,2,3\"\n# #os.environ[\"CUDA_VISIBLE_DEVICES\"] = \"3,4,5,6\"\n# #os.environ[\"CUDA_VISIBLE_DEVICES\"] = \"5,6, 7\"\n\nfrom modelmgpu import ModelMGPU\n\nimport time\n\nstart = time.time()\nprint(\"START:\", start)\n\nconfig = tf.ConfigProto()\nconfig.gpu_options.allow_growth = True\nconfig.gpu_options.per_process_gpu_memory_fraction = 0.90\nsession = tf.Session(config=config)\n\nprint(\"\\nSuccessfully imported packages!!!\\n\")\n\n\nclass myUnet(object):\n def __init__(self, model_name = \"unet\", image_size = 256, dropout = True, optimizer = 'Adam', lr=.00001, loss_fn=\"dice_loss\"):\n self.img_rows = image_size\n self.img_cols = image_size\n self.parallel_model = None\n self.patient = None\n self.data_source = None\n self.file_source = None\n self.image_size = None\n self.source_type = None\n self.test_source_path = None\n self.image_4d_file = None\n self.image_source_file = None\n self.image_one_file = None\n self.sourcedict = dict()\n self.model_name = model_name\n self.train_size = 0\n ### Model training parameters\n self.nGPUs = GPUs\n self.lossfn_str = loss_fn\n self.dropout = dropout\n self.learningrate_str = str(lr)\n if loss_fn == 'dice_loss':\n self.loss_fn = dice_loss\n elif loss_fn == 'log_dice_loss':\n self.loss_fn = log_dice_loss\n elif loss_fn == 'bce_dice_loss':\n self.loss_fn = bce_dice_loss\n elif loss_fn == 'binary_crossentropy':\n self.loss_fn = 'binary_crossentropy'\n else :\n self.loss_fn = 'binary_crossentropy'\n \n self.optimizer_str = optimizer \n if optimizer == 'Adam':\n self.optimizer = Adam(lr = lr)\n elif optimizer == 'RMSprop':\n self.optimizer = RMSprop(lr = lr)\n else :\n print (\"unknown optimizer: default to Adam\", optimizer)\n self.optimizer = Adam(lr = lr) \n self.learningrate = lr\n self.metrics = [dice_coeff, 'binary_accuracy']\n self.epoch = 50 # gets updated later\n self.batch_size = 16 # gets updated later\n \n self.build_unet()\n\n \n def load_data(self, train_data, test_data):\n print('-'*30)\n print(\"loading data\")\n self.train_images, self.train_labels = load_images_and_labels(train_data, normalize= True)\n self.test_images, self.test_labels = load_images_and_labels(test_data, normalize= True) \n print(\"loading data done\")\n print('-'*30)\n \n\n def get_crop_shape(self, src, dest):\n # width, the 3rd dimension\n cw = (src.get_shape()[2] - dest.get_shape()[2]).value\n assert (cw >= 0)\n if cw % 2 != 0:\n cw1, cw2 = int(cw/2), int(cw/2) + 1\n else:\n cw1, cw2 = int(cw/2), int(cw/2)\n # height, the 2nd dimension\n ch = (src.get_shape()[1] - dest.get_shape()[1]).value\n assert (ch >= 0)\n if ch % 2 != 0:\n ch1, ch2 = int(ch/2), int(ch/2) + 1\n else:\n ch1, ch2 = int(ch/2), int(ch/2)\n\n return (ch1, ch2), (cw1, cw2)\n \n def build_unet2(self):\n \n '''\n Input shape\n 4D tensor with shape: (samples, channels, rows, cols) if data_format='channels_first' \n or 4D tensor with shape: (samples, rows, cols, channels) if data_format='channels_last' (default format).\n \n Output shape\n 4D tensor with shape: (samples, filters, new_rows, new_cols) if data_format='channels_first' or \n 4D tensor with shape: (samples, new_rows, new_cols, filters) if data_format='channels_last'. \n rows and cols values might have changed due to padding.\n '''\n print('-'*30)\n print (\"Building U-net model\")\n print('-'*30)\n \n inputs = Input((self.img_rows, self.img_cols,1))\n \n conv0 = Conv2D(32, 3, activation = 'relu', padding = 'same', kernel_initializer = 'he_normal')(inputs)\n print (\"conv0 shape:\",conv0.shape)\n \n conv0 = Conv2D(32, 3, activation = 'relu', padding = 'same', kernel_initializer = 'he_normal')(conv0)\n print (\"conv0 shape:\",conv0.shape)\n pool0 = MaxPooling2D(pool_size=(2, 2))(conv0)\n print (\"pool0 shape:\",pool0.shape)\n\n conv1 = Conv2D(64, 3, activation = 'relu', padding = 'same', kernel_initializer = 'he_normal')(inputs)\n print (\"conv1 shape:\",conv1.shape)\n \n conv1 = Conv2D(64, 3, activation = 'relu', padding = 'same', kernel_initializer = 'he_normal')(conv1)\n print (\"conv1 shape:\",conv1.shape)\n pool1 = MaxPooling2D(pool_size=(2, 2))(conv1)\n print (\"pool1 shape:\",pool1.shape)\n\n conv2 = Conv2D(128, 3, activation = 'relu', padding = 'same', kernel_initializer = 'he_normal')(pool1)\n print (\"conv2 shape:\",conv2.shape)\n conv2 = Conv2D(128, 3, activation = 'relu', padding = 'same', kernel_initializer = 'he_normal')(conv2)\n print (\"conv2 shape:\",conv2.shape)\n pool2 = MaxPooling2D(pool_size=(2, 2))(conv2)\n print (\"pool2 shape:\",pool2.shape)\n\n conv3 = Conv2D(256, 3, activation = 'relu', padding = 'same', kernel_initializer = 'he_normal')(pool2)\n print (\"conv3 shape:\",conv3.shape)\n conv3 = Conv2D(256, 3, activation = 'relu', padding = 'same', kernel_initializer = 'he_normal')(conv3)\n print (\"conv3 shape:\",conv3.shape)\n pool3 = MaxPooling2D(pool_size=(2, 2))(conv3)\n print (\"pool3 shape:\",pool3.shape)\n\n conv4 = Conv2D(512, 3, activation = 'relu', padding = 'same', kernel_initializer = 'he_normal')(pool3)\n conv4 = Conv2D(512, 3, activation = 'relu', padding = 'same', kernel_initializer = 'he_normal')(conv4)\n #drop4 = Dropout(0.5)(conv4)\n pool4 = MaxPooling2D(pool_size=(2, 2))(conv4)\n\n conv5 = Conv2D(1024, 3, activation = 'relu', padding = 'same', kernel_initializer = 'he_normal')(pool4)\n conv5 = Conv2D(1024, 3, activation = 'relu', padding = 'same', kernel_initializer = 'he_normal')(conv5)\n print (\"Adding .5 dropout layer\")\n drop5 = Dropout(0.5)(conv5)\n\n up6 = Conv2D(512, 2, activation = 'relu', padding = 'same', kernel_initializer = 'he_normal')(UpSampling2D(size = (2,2))(drop5))\n ch, cw = self.get_crop_shape(conv4, up6)\n crop_conv4 = Cropping2D(cropping=(ch,cw))(conv4)\n merge6 = concatenate([crop_conv4,up6], axis = 3)\n conv6 = Conv2D(512, 3, activation = 'relu', padding = 'same', kernel_initializer = 'he_normal')(merge6)\n conv6 = Conv2D(512, 3, activation = 'relu', padding = 'same', kernel_initializer = 'he_normal')(conv6)\n if self.dropout == True:\n print (\"Adding .5 dropout layer\")\n conv6 = Dropout(0.5)(conv6)\n\n up7 = Conv2D(256, 2, activation = 'relu', padding = 'same', kernel_initializer = 'he_normal')(UpSampling2D(size = (2,2))(conv6))\n ch, cw = self.get_crop_shape(conv3, up7)\n crop_conv3 = Cropping2D(cropping=(ch,cw))(conv3)\n merge7 = concatenate([crop_conv3,up7], axis = 3)\n conv7 = Conv2D(256, 3, activation = 'relu', padding = 'same', kernel_initializer = 'he_normal')(merge7)\n conv7 = Conv2D(256, 3, activation = 'relu', padding = 'same', kernel_initializer = 'he_normal')(conv7)\n if self.dropout == True:\n print (\"Adding .5 dropout layer\")\n conv7 = Dropout(0.5)(conv7)\n\n up8 = Conv2D(128, 2, activation = 'relu', padding = 'same', kernel_initializer = 'he_normal')(UpSampling2D(size = (2,2))(conv7))\n ch, cw = self.get_crop_shape(conv2, up8)\n crop_conv2 = Cropping2D(cropping=(ch,cw))(conv2)\n merge8 = concatenate([crop_conv2,up8], axis = 3)\n conv8 = Conv2D(128, 3, activation = 'relu', padding = 'same', kernel_initializer = 'he_normal')(merge8)\n conv8 = Conv2D(128, 3, activation = 'relu', padding = 'same', kernel_initializer = 'he_normal')(conv8)\n if self.dropout == True:\n print (\"Adding .5 dropout layer\")\n conv8 = Dropout(0.5)(conv8)\n \n up9 = Conv2D(64, 2, activation = 'relu', padding = 'same', kernel_initializer = 'he_normal')(UpSampling2D(size = (2,2))(conv8))\n ch, cw = self.get_crop_shape(conv1, up9)\n crop_conv1 = Cropping2D(cropping=(ch,cw))(conv1)\n merge9 = concatenate([crop_conv1,up9], axis = 3)\n conv9 = Conv2D(64, 3, activation = 'relu', padding = 'same', kernel_initializer = 'he_normal')(merge9)\n conv9 = Conv2D(64, 3, activation = 'relu', padding = 'same', kernel_initializer = 'he_normal')(conv9)\n if self.dropout == True:\n print (\"Adding .5 dropout layer\")\n conv9 = Dropout(0.5)(conv9)\n \n up10 = Conv2D(64, 2, activation = 'relu', padding = 'same', kernel_initializer = 'he_normal')(UpSampling2D(size = (2,2))(conv9))\n ch, cw = self.get_crop_shape(conv0, up10)\n crop_conv0 = Cropping2D(cropping=(ch,cw))(conv0)\n merge10 = concatenate([crop_conv0,up10], axis = 3)\n conv10 = Conv2D(64, 3, activation = 'relu', padding = 'same', kernel_initializer = 'he_normal')(merge10)\n conv10 = Conv2D(64, 3, activation = 'relu', padding = 'same', kernel_initializer = 'he_normal')(conv10) \n \n #conv9 = Conv2D(2, 3, activation = 'relu', padding = 'same', kernel_initializer = 'he_normal')(conv9)\n conv11 = Conv2D(1, 1, activation = 'sigmoid')(conv10)\n\n print (\"compiling the model\")\n self.model = Model(input = inputs, output = conv11)\n self.parallel_model = ModelMGPU(self.model, GPUs)\n\n #self.model.compile(optimizer=RMSprop(lr=0.0001), loss=penalized_bce_loss(weight=0.08), metrics=['binary_accuracy'])\n #self.model.compile(optimizer=RMSprop(lr=0.0001), loss=dice_loss, metrics=[dice_coeff])\n\n #metrics=['accuracy'] calculates accuracy automatically from cost function. So using binary_crossentropy shows binary \n #accuracy, not categorical accuracy.Using categorical_crossentropy automatically switches to categorical accuracy\n #One can get both categorical and binary accuracy by using metrics=['binary_accuracy', 'categorical_accuracy']\n \n #self.parallel_model.compile(optimizer = Adam(lr = 1e-4), loss = dice_loss, metrics = [dice_coeff])\n #self.model.compile(optimizer = Adam(lr = 1e-4), loss = dice_loss, metrics = [dice_coeff])\n \n print (\"compiling the model\")\n #self.model.compile(optimizer = self.optimizer, loss = self.loss_fn, metrics = self.metrics)\n try:\n self.parallel_model.compile(optimizer = self.optimizer, loss = self.loss_fn, metrics = self.metrics)\n\n #self.parallel_model.compile(optimizer = Adam(lr = 1e-4), loss = bce_dice_loss, metrics = [dice_coeff])\n except ValueError:\n print (\"Error invalid parameters to model compilation\")\n\n \n \n def build_unet(self):\n \n '''\n Input shape\n 4D tensor with shape: (samples, channels, rows, cols) if data_format='channels_first' \n or 4D tensor with shape: (samples, rows, cols, channels) if data_format='channels_last' (default format).\n \n Output shape\n 4D tensor with shape: (samples, filters, new_rows, new_cols) if data_format='channels_first' or \n 4D tensor with shape: (samples, new_rows, new_cols, filters) if data_format='channels_last'. \n rows and cols values might have changed due to padding.\n '''\n print('-'*30)\n print (\"Building U-net model\")\n print('-'*30)\n \n inputs = Input((self.img_rows, self.img_cols,1))\n\n conv1 = Conv2D(64, 3, activation = 'relu', padding = 'same', kernel_initializer = 'he_normal')(inputs)\n print (\"conv1 shape:\",conv1.shape)\n conv1 = Conv2D(64, 3, activation = 'relu', padding = 'same', kernel_initializer = 'he_normal')(conv1)\n print (\"conv1 shape:\",conv1.shape)\n pool1 = MaxPooling2D(pool_size=(2, 2))(conv1)\n print (\"pool1 shape:\",pool1.shape)\n\n conv2 = Conv2D(128, 3, activation = 'relu', padding = 'same', kernel_initializer = 'he_normal')(pool1)\n print (\"conv2 shape:\",conv2.shape)\n conv2 = Conv2D(128, 3, activation = 'relu', padding = 'same', kernel_initializer = 'he_normal')(conv2)\n print (\"conv2 shape:\",conv2.shape)\n pool2 = MaxPooling2D(pool_size=(2, 2))(conv2)\n print (\"pool2 shape:\",pool2.shape)\n\n conv3 = Conv2D(256, 3, activation = 'relu', padding = 'same', kernel_initializer = 'he_normal')(pool2)\n print (\"conv3 shape:\",conv3.shape)\n conv3 = Conv2D(256, 3, activation = 'relu', padding = 'same', kernel_initializer = 'he_normal')(conv3)\n print (\"conv3 shape:\",conv3.shape)\n pool3 = MaxPooling2D(pool_size=(2, 2))(conv3)\n print (\"pool3 shape:\",pool3.shape)\n\n conv4 = Conv2D(512, 3, activation = 'relu', padding = 'same', kernel_initializer = 'he_normal')(pool3)\n conv4 = Conv2D(512, 3, activation = 'relu', padding = 'same', kernel_initializer = 'he_normal')(conv4)\n #drop4 = Dropout(0.5)(conv4)\n drop4 = conv4\n pool4 = MaxPooling2D(pool_size=(2, 2))(drop4)\n\n conv5 = Conv2D(1024, 3, activation = 'relu', padding = 'same', kernel_initializer = 'he_normal')(pool4)\n conv5 = Conv2D(1024, 3, activation = 'relu', padding = 'same', kernel_initializer = 'he_normal')(conv5)\n drop5 = conv5\n if self.dropout == True:\n print (\"Adding dropout layer\")\n drop5 = Dropout(0.5)(drop5)\n\n up6 = Conv2D(512, 2, activation = 'relu', padding = 'same', kernel_initializer = 'he_normal')(UpSampling2D(size = (2,2))(drop5))\n merge6 = concatenate([drop4,up6], axis = 3)\n conv6 = Conv2D(512, 3, activation = 'relu', padding = 'same', kernel_initializer = 'he_normal')(merge6)\n conv6 = Conv2D(512, 3, activation = 'relu', padding = 'same', kernel_initializer = 'he_normal')(conv6)\n if self.dropout == True:\n print (\"Adding dropout layer\")\n conv6 = Dropout(0.5)(conv6)\n\n up7 = Conv2D(256, 2, activation = 'relu', padding = 'same', kernel_initializer = 'he_normal')(UpSampling2D(size = (2,2))(conv6))\n merge7 = concatenate([conv3,up7], axis = 3)\n conv7 = Conv2D(256, 3, activation = 'relu', padding = 'same', kernel_initializer = 'he_normal')(merge7)\n conv7 = Conv2D(256, 3, activation = 'relu', padding = 'same', kernel_initializer = 'he_normal')(conv7)\n if self.dropout == True:\n print (\"Adding dropout layer\")\n conv7 = Dropout(0.5)(conv7)\n\n up8 = Conv2D(128, 2, activation = 'relu', padding = 'same', kernel_initializer = 'he_normal')(UpSampling2D(size = (2,2))(conv7))\n merge8 = concatenate([conv2,up8], axis = 3)\n conv8 = Conv2D(128, 3, activation = 'relu', padding = 'same', kernel_initializer = 'he_normal')(merge8)\n conv8 = Conv2D(128, 3, activation = 'relu', padding = 'same', kernel_initializer = 'he_normal')(conv8)\n if self.dropout == True:\n print (\"Adding dropout layer\")\n conv8 = Dropout(0.5)(conv8)\n \n up9 = Conv2D(64, 2, activation = 'relu', padding = 'same', kernel_initializer = 'he_normal')(UpSampling2D(size = (2,2))(conv8))\n merge9 = concatenate([conv1,up9], axis = 3)\n conv9 = Conv2D(64, 3, activation = 'relu', padding = 'same', kernel_initializer = 'he_normal')(merge9)\n conv9 = Conv2D(64, 3, activation = 'relu', padding = 'same', kernel_initializer = 'he_normal')(conv9)\n #conv9 = Conv2D(2, 3, activation = 'relu', padding = 'same', kernel_initializer = 'he_normal')(conv9)\n conv10 = Conv2D(1, 1, activation = 'sigmoid')(conv9)\n\n self.model = Model(input = inputs, output = conv10)\n self.parallel_model = ModelMGPU(self.model, GPUs)\n\n #self.model.compile(optimizer=RMSprop(lr=0.0001), loss=penalized_bce_loss(weight=0.08), metrics=['binary_accuracy'])\n #self.model.compile(optimizer=RMSprop(lr=0.0001), loss=dice_loss, metrics=[dice_coeff])\n\n #metrics=['accuracy'] calculates accuracy automatically from cost function. So using binary_crossentropy shows binary \n #accuracy, not categorical accuracy.Using categorical_crossentropy automatically switches to categorical accuracy\n #One can get both categorical and binary accuracy by using metrics=['binary_accuracy', 'categorical_accuracy']\n \n #self.parallel_model.compile(optimizer = Adam(lr = 1e-4), loss = dice_loss, metrics = [dice_coeff])\n #self.model.compile(optimizer = Adam(lr = 1e-4), loss = dice_loss, metrics = [dice_coeff])\n \n print (\"compiling the model\")\n #self.model.compile(optimizer = self.optimizer, loss = self.loss_fn, metrics = self.metrics)\n try:\n self.parallel_model.compile(optimizer = self.optimizer, loss = self.loss_fn, metrics = self.metrics)\n\n #self.parallel_model.compile(optimizer = Adam(lr = 1e-4), loss = bce_dice_loss, metrics = [dice_coeff])\n except ValueError:\n print (\"Error invalid parameters to model compilation\")\n \n\n\n #self.model.compile(optimizer = Adam(lr = 1e-4), loss = bce_dice_loss, metrics = [dice_coeff])\n\n #self.model.compile(optimizer = Adam(lr = 1e-4), loss = 'binary_crossentropy', metrics = [dice_coeff])\n #self.model.compile(optimizer = Adam(lr = 1e-4), loss = my_bce_loss, metrics = ['binary_accuracy'])\n \n def load_pretrained_weights(self, model_file):\n self.model_file = model_file\n print('-'*30)\n print('Loading pre-trained weights...')\n self.parallel_model.load_weights(self.model_file)\n #self.model.load_weights(self.model_file)\n print('-'*30) \n\n def predict(self, test_image_array, test_label_array =\"none\"):\n self.test_images = test_image_array\n self.test_labels = test_label_array\n print('-'*30)\n print('predict test data....')\n self.predictions = self.parallel_model.predict(self.test_images, batch_size=1, verbose=1)\n #self.predictions = self.model.predict(self.test_images, batch_size=1, verbose=1)\n print('-'*30)\n print('-'*30)\n \n\n if self.test_labels != \"none\" :\n scores = self.parallel_model.evaluate (self.predictions, self.test_labels, batch_size=4)\n #scores = self.model.evaluate (self.predictions, self.test_labels, batch_size=4)\n print (\"Prediction Scores before rounding\", scores)\n\n pred2 = np.round(self.predictions)\n scores = self.parallel_model.evaluate (pred2, self.test_labels, batch_size=4)\n #scores = self.model.evaluate (pred2, self.test_labels, batch_size=4)\n print (\"Prediction Scores after rounding\", scores)\n\n def train_and_predict(self, model_path, batch_size = 4, nb_epoch = 10, augmentation = False): \n \n model_file = model_path + model_name + '.hdf5'\n self.model_file = model_file #path to save the weights with best model\n self.batch_size = batch_size\n self.epoch = nb_epoch\n model_checkpoint = ModelCheckpoint(self.model_file, monitor='loss',verbose=0, save_best_only=True)\n \n if augmentation == True :\n print (\"perform augmentation\")\n sample_size, x_val, y_val, ax = self.train_images.shape\n #save original train images\n self.original_train_images = self.train_images\n self.original_train_labels = self.train_labels\n # we create two instances with the same arguments\n# data_gen_args = dict(\n# rotation_range=90.,\n# width_shift_range=0.05,\n# height_shift_range=0.05,\n# zoom_range=0.1)\n data_gen_args = dict(\n rotation_range=90.,\n width_shift_range=0.025,\n height_shift_range=0.025,\n zoom_range=0.05)\n\n image_datagen = ImageDataGenerator(**data_gen_args)\n mask_datagen = ImageDataGenerator(**data_gen_args)\n \n # Provide the same seed and keyword arguments to the fit and flow methods\n seed = 1\n image_generator = image_datagen.flow(self.train_images, y=None, seed = seed, batch_size=sample_size)\n mask_generator = mask_datagen.flow(self.train_labels, y=None, seed = seed, batch_size=sample_size)\n train_generator = zip(image_generator, mask_generator)\n\n MAX_AUG=3\n print('-'*30)\n print('Augmenting training data...')\n augmentation_round = 0\n for img_tr, mask_tr in train_generator:\n self.train_images = np.concatenate((self.train_images, img_tr), axis=0)\n self.train_labels = np.concatenate((self.train_labels, mask_tr), axis=0)\n print (\"Augmentation round: \", augmentation_round+1, img_tr.shape, self.train_images.shape, self.train_labels.shape)\n augmentation_round += 1\n if (augmentation_round == MAX_AUG):\n break\n \n samples, x, y, z = self.train_images.shape\n print (\"samples, x, y\", samples, x, y)\n self.train_size = samples\n print('-'*30)\n print('Fitting model...')\n print('-'*30)\n self.history = self.parallel_model.fit(self.train_images, self.train_labels, batch_size, nb_epoch, verbose=1,validation_split=0.2, shuffle=True, callbacks=[model_checkpoint])\n #self.history = self.model.fit(self.train_images, self.train_labels, batch_size, nb_epoch, verbose=1,validation_split=0.2, shuffle=True, callbacks=[model_checkpoint])\n\n print('-'*30)\n print('predict test data....')\n #first load the pre-trained weights that were saved from best run\n self.load_pretrained_weights(self.model_file)\n \n self.predictions = self.parallel_model.predict(self.test_images, batch_size=1, verbose=1)\n #self.predictions = self.model.predict(self.test_images, batch_size=1, verbose=1)\n self.scores = self.parallel_model.evaluate (self.predictions, self.test_labels, batch_size=4)\n #self.scores = self.model.evaluate (self.predictions, self.test_labels, batch_size=4)\n print (\"Prediction Scores\", self.parallel_model.metrics_names, self.scores)\n #print(\"%s: %.2f%%\" % (self.model.metrics_names[1], self.scores[1]*100))\n print('-'*30)\n \n\n \n def save_model_info(self, mypath = \"./\"):\n learn_file = self.model_name + \"_learning_history.json\"\n learn_file = mypath + learn_file\n hist = self.history.history\n #Append model name and training parameters to the dictionary\n hist['tr_model_name'] = self.model_name \n hist['tr_size'] = self.train_size\n ### Model training parameters\n hist['tr_nGPUs'] = self.nGPUs\n hist['tr_dropout'] = str(self.dropout) \n hist['tr_loss_fn'] = self.lossfn_str \n hist['tr_optimizer'] = self.optimizer_str\n hist['tr_lrrate'] = self.learningrate_str \n hist['tr_epoch'] = self.epoch \n hist['tr_batchsize'] = self.batch_size \n print('-'*30)\n print (\"Saving Evaluation Scores on test set\")\n for i in range (len(self.scores)):\n hist['eval_'+ self.parallel_model.metrics_names[i]] = self.scores[i]\n print('-'*30) \n print (\"Saving learning history\", learn_file)\n with open(learn_file, 'w') as file:\n json.dump(self.history.history, file, indent=2)\n \n pred_file = self.model_name + \"_predictions.npy\"\n pred_file = mypath + pred_file\n print (\"Saving predictions\", pred_file)\n np.save(pred_file, self.predictions)\n \n \n# pred_file = self.model_name + \"_predictions_rounded.npy\"\n# pred_file = mypath + pred_file\n# np.save(pred_file, np.round(self.predictions))\n print('-'*30)\n \n print (\"Saving Performance Statistics\")\n perf = get_performance_statistics (self.test_labels, self.predictions)\n #Append model name and training parameters to the dictionary\n perf['tr_model_name'] = self.model_name \n perf['tr_size'] = self.train_size\n ### Model training parameters\n perf['tr_nGPUs'] = self.nGPUs\n perf['tr_dropout'] = str(self.dropout)\n perf['tr_loss_fn'] = self.lossfn_str \n perf['tr_optimizer'] = self.optimizer_str\n perf['tr_lrrate'] = self.learningrate_str \n perf['tr_epoch'] = self.epoch \n perf['tr_batchsize'] = self.batch_size \n \n print (\"Saving Evaluation Scores on test set\")\n for i in range (len(self.scores)):\n perf['eval_'+ self.parallel_model.metrics_names[i]] = self.scores[i]\n \n self.perf = perf\n print (\"Perf Statistics: \", self.perf)\n \n perf_file = self.model_name + \"_performance.json\"\n perf_file = mypath + perf_file\n \n print (\"Saving Performance values\", perf_file)\n with open(perf_file, 'w') as file:\n json.dump(self.perf, file, indent=2)\n print('-'*30)\n\n\n \n#################\n# Method to create a U-net model and train it\n# Create a U-Net model, train the model and run the predictions and save the trained weights and predictions\n#\n##########################\n# /masvol/heartsmart/unet_model/data/sunnybrook_176_train_images.npy \n# /masvol/heartsmart/unet_model/data/sunnybrook_176_train_images.npy \n# /masvol/heartsmart/unet_model/data/sunnybrook_176_train_labels.npy\n\ndef train_unet_model (model_name, image_size, training_images, training_labels, test_images, test_labels, model_path, dropout, optimizer, learningrate, lossfun, batch_size, epochs, augmentation = False, model_summary = False):\n \n #samples, x, y, z = pred.shape\n \n train_data = {}\n test_data = {}\n\n train_data[\"images\"] = training_images\n train_data[\"labels\"] = training_labels\n test_data[\"images\"] = test_images\n test_data[\"labels\"] = test_labels\n\n \n if not os.path.exists(model_path):\n print (\"creating dir \", model_path)\n os.makedirs(model_path)\n \n # get the u-net model and load train and test data\n myunet = myUnet(model_name = model_name, image_size = image_size, dropout = dropout, optimizer = optimizer, lr=learningrate, loss_fn = lossfn)\n myunet.load_data (train_data, test_data)\n\n if (model_summary == True):\n print (\"Printing model summary \")\n #myunet.model.summary()\n myunet.parallel_model.summary()\n \n res = myunet.train_and_predict(model_path, batch_size = batch_size, nb_epoch = epochs, augmentation = augmentation)\n \n# if (augmentation == True) :\n# res = myunet.train_with_augmentation(model_file, batch_size = batch_size, nb_epoch = epochs)\n# else :\n# res = myunet.train_and_predict(model_file, batch_size = batch_size, nb_epoch = epochs)\n \n return myunet\n\n\nif __name__ == \"__main__\":\n img_size_list = [176, 256]\n args = sys.argv[1:]\n print (\"total arguments\", len(args), args)\n if len(args) != 15:\n print (\"insufficient arguments \")\n print (\" enter model_name, image_size, training_images, training_labels, test_images, test_labels, model_path, dropout (True or False), optimizer, learningrate, loss_function, batch_size, epochs, augmentation (True or False), model_summary (True or False)\")\n sys.exit() \n \n model_name = sys.argv[1]\n image_size = int(sys.argv[2])\n training_images = sys.argv[3]\n training_labels = sys.argv[4]\n test_images = sys.argv[5]\n test_labels = sys.argv[6]\n model_path = sys.argv[7]\n if (sys.argv[8] == \"True\"):\n dropout = True\n else:\n dropout = False\n \n optimizer = sys.argv[9]\n lr = float(sys.argv[10])\n lossfn = sys.argv[11]\n batch_size = int(sys.argv[12])\n epochs = int(sys.argv[13])\n if (sys.argv[14] == \"True\"):\n augmentation = True\n else:\n augmentation = False\n \n if (sys.argv[15] == \"True\"):\n model_summary = True\n else:\n model_summary = False\n\n \n if image_size not in img_size_list:\n print (\"image size %d is not supported\"%image_size)\n sys.exit()\n \n mymodel = train_unet_model (model_name, image_size, training_images, training_labels, test_images, test_labels, model_path, dropout, optimizer, lr, lossfn, batch_size, epochs, augmentation, model_summary)\n \n mymodel.save_model_info(model_path) \n\n\n end = time.time()\n print (\"END:\", end - start)\n","sub_path":"unet_model/unet_train_sk.py","file_name":"unet_train_sk.py","file_ext":"py","file_size_in_byte":30168,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"453956020","text":"import sys, string, json\nfrom benchClient import runDoryLatencyTest\n\n# FILL IN\nclients = [\"1.2.3.4\"]\nmaster = \"5.6.7.8\"\nreplicas = [\"1.1.1.1\", \"2.2.2.2\"]\n\nbloomFilterSzList = [1120, 1280, 1440, 1600, 1800, 2000, 2240, 2520, 2800, 3120, 3480]\n\nisMalicious = True \nbreakdown = True\n\nf = open(\"out/tab7.dat\", \"w\")\n\n# Measure number of documents 2^10 to 2^20\nfor i in range(11):\n numDocs = 2 ** (i + 10)\n print((\"Number of docs = %d, Bloom filter size = %d\") % (numDocs, bloomFilterSzList[i]))\n latencies = runDoryLatencyTest(bloomFilterSzList[i], numDocs, 10000, isMalicious, 0)\n print(\"-------------------------\")\n f.write((\"Number of docs = 2^%d, Bloom filter size = %d\\n\") % (i + 10, bloomFilterSzList[i]))\n if not breakdown: \n print((\"Time: %s ms\") % latencies[2])\n f.write(str(latencies[len(latencies) - 1]) + \"\\n\")\n else:\n print((\"Total time: %s ms\") % (latencies[6]))\n print((\"-> Consensus time: %s ms\") % (latencies[2]))\n print((\"-> Client time: %s ms\") % (latencies[3]))\n print((\"-> Network time: %s ms\") % (latencies[4]))\n print((\"-> Server time: %s ms\") % (latencies[5]))\n \n f.write((\"Total time: %s ms\\n\") % (latencies[6]))\n f.write((\"-> Consensus time: %s ms\\n\") % (latencies[2]))\n f.write((\"-> Client time: %s ms\\n\") % (latencies[3]))\n f.write((\"-> Network time: %s ms\\n\") % (latencies[4]))\n f.write((\"-> Server time: %s ms\\n\\n\") % (latencies[5]))\n \nf.close()\n","sub_path":"bench/exp_tab7.py","file_name":"exp_tab7.py","file_ext":"py","file_size_in_byte":1483,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"307368461","text":"# For python 3 portability\nfrom __future__ import (absolute_import, division,\n print_function, unicode_literals)\n\nfrom builtins import (dict, str, super)\nfrom collections import namedtuple\nimport gc\n\nimport numpy\n\nfrom pyWAT.core.errorHandling import fatalError\nfrom pyWAT.core.wrfVariable import wrfVariable\nfrom pyWAT.io.wrfNetcdfFile import wrfNetcdfFile\n\n\nRd = 287 # [ J K-1 kg-1 ]\n\nRv = 461.495 # [ J K-1 kg-1 ]\n\ng = 9.81 # [m/s2 ] \n\nepsilon = 0.622 # Rd / Rv\n\nT0 = 273.15\n\nP0 = 100000 # [Pa]\n\nreferencePressure = 100000.0 # [Pa]\n\ngridCartesianCoordinatesTuple = namedtuple('gridCartesianCoordinatesTuple', ['x', 'y', 'z'], verbose=False)\n\nstaggeredDimensionsDefinitions = { 0 : [u'bottom_top', u'south_north', u'west_east'] ,\n None : [u'bottom_top', u'south_north', u'west_east'],\n 1 : [u'bottom_top', u'south_north', u'west_east_stag'] ,\n 'x' : [u'bottom_top', u'south_north', u'west_east_stag'],\n 2 : [u'bottom_top', u'south_north_stag', u'west_east'] ,\n 'y' : [u'bottom_top', u'south_north_stag', u'west_east'],\n 3 : [u'bottom_top_stag', u'south_north', u'west_east'] ,\n 'z' : [u'bottom_top_stag', u'south_north', u'west_east'] \n }\n\n\ndegToRad = 180 / numpy.pi\nRadToDeg = numpy.pi / 180\n\ndef getStageredDimension(dimensions):\n if 'bottom_top_stag' in dimensions:\n return 'z'\n elif 'west_east_stag' in dimensions:\n return 'x'\n elif 'south_north_stag' in dimensions:\n return 'y'\n else:\n return None\n \n\n\nvariableDefinition = namedtuple('variableDefinition',\n ['variableName', \n 'isThreeDimensional', \n 'hasHorizontalPlanes', \n 'associatedVariable'],\n verbose=False\n )\n\n\ncomputedVariablesDefinitions = { \n 'Rainrate' : variableDefinition('Rainrate', False, True, 'RAINCV') ,\n 'TotalRainAccumulation' : variableDefinition('TotalRainAccumulation', False, True, 'RAINC') ,\n 'Pressure' : variableDefinition('Pressure', True, True, 'P') ,\n 'Density' : variableDefinition('Density', True, True, 'P') ,\n 'VaporPressure' : variableDefinition('VaporPressure', True, True, 'QVAPOR') ,\n 'Temperature' : variableDefinition('Temperature', True, True, 'T') ,\n 'ThetaE' : variableDefinition('ThetaE', True, True, 'T') ,\n #'ThetaEGradient' : variableDefinition('ThetaEGradient', True, True, 'T') ,\n 'Theta' : variableDefinition('Theta', True, True, 'T') ,\n 'SaturationVaporPressure' : variableDefinition('SaturationVaporPressure', True, True, 'QVAPOR') ,\n 'SaturationVaporMixingRatio' : variableDefinition('SaturationVaporMixingRatio', True, True, 'QVAPOR') ,\n 'PrecipitableWater' : variableDefinition('PrecipitableWater', False, True, 'RAINC') ,\n 'Geopotential' : variableDefinition('Geopotential', True, True, 'PH') ,\n 'GeopotentialHeight' : variableDefinition('GeopotentialHeight', True, True, 'PH') ,\n 'HorizontalWind' : variableDefinition('HorizontalWind', True, True, 'P') ,\n 'WindDirection' : variableDefinition('WindDirection', True, True, 'P') ,\n 'DewPointTemperature' : variableDefinition('DewPointTemperature', True, True, 'T'),\n #'MSLP' : variableDefinition('MSLP', False, True, 'RAINCV') ,\n # 'Buoyancy' : variableDefinition('Buoyancy', True, True) ,\n #'CAPE' : variableDefinition('CAPE', False, True, 'RAINC'),\n #'CIN' : variableDefinition('CIN', False, True, 'RAINC'),\n #'GeopotentialAtPresureLevel' : variableDefinition('GeopotentialAtPresureLevel', False, True, 'RAINC'),\n #'TemperatureAtPresureLevel' : variableDefinition('TemperatureAtPresureLevel', False, True, 'RAINC'),\n #'UgAtPressureLevel' : variableDefinition('UgAtPressureLevel', False, True, 'RAINC'),\n #'VgAtPressureLevel' : variableDefinition('VgAtPressureLevel', False, True, 'RAINC'),\n #'UwindAtPressureLevel' : variableDefinition('UwindAtPressureLevel', False, True, 'RAINC'),\n #'VwindAtPressureLevel' : variableDefinition('VwindAtPressureLevel', False, True, 'RAINC'),\n #'Q1AtPressureLevel' : variableDefinition('Q1AtPressureLevel', False, True, 'RAINC'),\n #'Q2AtPressureLevel' : variableDefinition('Q2AtPressureLevel', False, True, 'RAINC'),\n #'QDivergenceAtPresureLevel' : variableDefinition('QDivergenceAtPresureLevel', False, True, 'RAINC'),\n #'Frontogenesis' : variableDefinition('Frontogenesis', False, True, 'RAINC')\n } \n\n \n \n \nclass wrfOutput(wrfNetcdfFile):\n ''' \n Class to handle the WRF output files (wrfout_d##).\n \n This class add functionalities to the :py:class:`~pyWAT.io.wrfNetcdfFile.wrfNetcdfFile`\n to support variables that need to be computed.\n \n The class is initialized as in the :py:class:`~pyWAT.io.wrfNetcdfFile.wrfNetcdfFile` class::\n \n from pyWAT.io.wrfOutput import wrfOutput\n myOutputFile = wrfOutput(path/to/the/netcdf/file, mode='r')\n \n The list of supported computed variables can be printed using::\n print(wrfOutput.computedVariablesDefinitions.keys())\n \n See :py:meth:`__init__` for a description of the initialization parameters\n \n '''\n \n computedVariablesDefinitions = computedVariablesDefinitions \n\n def __init__(self, wrfOutputFilePath, mode='r' , timeIndex=0):\n ''' \n Constructor\n \n See :func:`pyWAT.io.wrfNetcdfFile.wrfNetcdfFile.__init__` for a description of the initialization parameters\n '''\n \n \n super().__init__(self, wrfOutputFilePath, mode=mode, timeIndex=timeIndex)\n \n self.availableComputedVariables = None\n \n self.cleanBuffers()\n \n self.updateAvailableVariables()\n \n \n def __getitem__(self, key):\n \"\"\"\n x.__getitem__(y) <==> x[y]\n \n Item getter\n \n See :func:`wrfNetcdfFile.__getitem__` for a description of the initialization parameters\n \n \"\"\"\n return self.getVariable(key) \n\n def cleanBuffers(self):\n ''' Clean all the object internal buffers and free memory '''\n \n self.gridCartesianCoordinates = dict()\n \n for computedVariableName in self.computedVariablesDefinitions:\n setattr(self, \"_\" + computedVariableName , None)\n setattr(self, \"_\" + computedVariableName + \"Kwargs\", None)\n \n self._computeGeostrophicWindsAtPressureLevelKwargs = None\n self._TemperatureAtPresureLevelKwargs = None\n self._GeopotentialAtPresureLevelKwargs = None\n self._computeQVectorsAtPressureLevelKwargs = None\n self._UwindAtPresureLevelKwargs = None\n self._VwindAtPresureLevelKwargs = None\n \n self._dx = None\n self._dy = None\n \n wrfNetcdfFile.cleanBuffers(self)\n \n \n def updateAvailableVariables(self):\n ''' Update the internal list of available variables'''\n \n super(wrfOutput, self).updateAvailableVariables()\n \n self.availableComputedVariables = list()\n \n for variableName, definitionsTuple in self.computedVariablesDefinitions.iteritems():\n \n self.variablesDimensions[variableName] = self.dataset[definitionsTuple.associatedVariable].dimensions \n \n self.horizontalPlaneVariables[variableName] = definitionsTuple.hasHorizontalPlanes\n self.threeDimensionalVariables[variableName] = definitionsTuple.isThreeDimensional\n \n self.availableComputedVariables.append(variableName)\n \n self.availableVariables += self.availableComputedVariables \n self.availableVariables.sort()\n \n \n \n def getVariable(self, variableName, **kwargs):\n \"\"\" \n Get a variable from the wrfOutput file or a computed one.\n \n For a list of all the available computed variables execute in python:\n \n >>> from pyWAT.io.wrfOutput import computedVariablesDefinitions \n >>> print computedVariablesDefinitions.keys()\n \n See Also\n --------\n :py:meth:`pyWAT.io.wrfNetcdfFile.wrfNetcdfFile.getVariable` and \n :py:meth:`_getComputedVariable`\n \"\"\"\n \n if variableName not in self.availableVariables:\n raise fatalError(\"Variable '\" + variableName + \"' not available\",\n \"File:%s\" % self.filePath,\n \"Class:%s\" % self.__class__ ,\n \"Available vars:\", str(self.availableVariables))\n else:\n if variableName in self.dataset.variables.keys():\n return self.dataset.variables[variableName]\n else: \n return self._getComputedVariable(variableName, **kwargs)\n \n \n def _getComputedVariable(self, variableName, **kwargs):\n \"\"\"\n Get a computed variable.\n\n Parameters\n ----------\n key : str\n Variable Name\n \n Return\n ------\n variable : :py:class:`pyWAT.core.wrfVariable.wrfVariable` instance\n \"\"\"\n \n return getattr(self, 'get' + variableName)(**kwargs)\n \n \n # Computed variables definitions \n \n def getRainrate(self, **kwargs):\n \"\"\" Get the Rain Rate in mm/hr\"\"\" \n \n if self._Rainrate is None:\n _Rainrate = self.zeros('RAINCV')\n _Rainrate[:] = (self['RAINCV'][:] + self['RAINSHV'][:] + self['RAINNCV'][:])\n \n _Rainrate *= (3600 / self.dataset.DT)\n \n self._Rainrate = wrfVariable(_Rainrate , 'Rainrate', \"mm / hr\" ,\n self.getVariableType('RAINCV'),\n self.getVariableDimensions('RAINCV'))\n \n return self._Rainrate\n \n def getTotalRainAccumulation(self, **kwargs):\n \"\"\"\n Get the total rain accumulation from the beginning of the simulation in mm\n \n Parameters\n ----------\n \n type : str , optional\n Type of precipitation. Accepted values:\n * 'cumulus' : Cumulus convection rain only\n * 'noncumulus' : Non Cumulus rain (from micriphysics)\n * None : default, cumulus + non cumulus rain\n \"\"\" \n \n if kwargs != self._TotalRainAccumulationKwargs:\n self._TotalRainAccumulation = None\n \n \n if self._TotalRainAccumulation is None:\n \n self._TotalRainAccumulationKwargs = kwargs.copy()\n precipType = kwargs.pop('type',None) \n \n # RAINNC : Non convective accumulation\n # RAINSH : Shallow cumulus accumulation\n # RAINC : ACCUMULATED TOTAL CUMULUS PRECIPITATION \n \n if precipType is None:\n _TotalRainAccumulation = self['RAINC'][:] + self['RAINSH'][:] + self['RAINNC'][:]\n else:\n if precipType.lower() == \"Cumulus\":\n _TotalRainAccumulation = self['RAINSH'][:] + self['RAINC'][:]\n elif precipType.lower() == \"NonCumulus\":\n _TotalRainAccumulation = self['RAINNC'][:]\n \n \n self._TotalRainAccumulation = wrfVariable(_TotalRainAccumulation ,\n 'TotalRainAccumulation', \"mm\" ,\n self['RAINC'].dtype,\n self.getVariableDimensions('RAINC'))\n \n return self._TotalRainAccumulation\n \n \n def getWindDirection(self, **kwargs):\n \"\"\"\n Get the Horizontal wind direction\n \"\"\"\n \n if self._WindDirection is None:\n _WindDirection = numpy.angle(self.getUnstaggeredVariable('V')[:] + 1j * self.getUnstaggeredVariable('U')[:], deg=True)\n \n _WindDirection[_WindDirection < 0] += 360 \n self._WindDirection = wrfVariable(_WindDirection ,\n 'Horizontal Wind Direction', \"degrees\" ,\n self['U'].dtype,\n self.getVariableDimensions('P'))\n return self._WindDirection\n \n \n \n def getHorizontalWind(self, **kwargs):\n \"\"\"Get the Horizontal wind magnitude\"\"\"\n if self._HorizontalWind is None:\n _HorizontalWind = numpy.sqrt(self.getUnstaggeredVariable('U')[:] ** 2 + self.getUnstaggeredVariable('V')[:] ** 2)\n self._HorizontalWind = wrfVariable(_HorizontalWind ,\n 'Horizontal Wind', \"m/s\" ,\n self['U'].dtype,\n self.getVariableDimensions('P'))\n return self._HorizontalWind\n \n \n def getDewPointTemperature(self, **kwargs):\n \"\"\"\n Get the Dew Point Temperature in Celsius Degrees\n \n From Markowsky page 13\n \n \"\"\"\n if self._DewPointTemperature is None:\n _DewPointTemperature = 243.5 / ((17.67 / numpy.log(self['VaporPressure'][:] * 0.01 / 6.112)) - 1.)\n \n self._DewPointTemperature = wrfVariable(_DewPointTemperature ,\n 'Dew Point Temperature', \"C\" ,\n self['T'].dtype,\n self.getVariableDimensions('T'))\n return self._DewPointTemperature\n \n \n def getDensity(self,**kwargs):\n \"\"\" Get moist air density \"\"\"\n if self._Density is None:\n \n _temp = self['Temperature'][:]+T0\n _qvapor = self['QVAPOR'][:]\n R = 287. * (1. + _qvapor/epsilon)/(1.+_qvapor)\n \n _Density = self['Pressure'][:] / (R*_temp)\n \n self._Density = wrfVariable(_Density ,\n 'Density', \"kg/m3\" ,\n self['P'].dtype,\n self.getVariableDimensions('P'))\n \n return self._Density\n \n \n \n def getPressure(self, **kwargs):\n \"\"\" Get the Pressure in Pa \"\"\"\n if self._Pressure is None:\n _Pressure = self['P'][:] + self['PB'][:]\n self._Pressure = wrfVariable(_Pressure ,\n 'Pressure', \"Pa\" ,\n self['P'].dtype,\n self.getVariableDimensions('P'))\n \n return self._Pressure\n \n \n def getTheta(self, **kwargs):\n \"\"\" Get the Potential Temperature in Kelvin degrees \"\"\"\n if self._Theta is None:\n _Theta = self.zeros('T')\n _Theta[:] = self['T'][:] + 300.0\n \n self._Theta = wrfVariable(_Theta ,\n 'Potential Temperature', \"K\" ,\n self['T'].dtype,\n self.getVariableDimensions('T'))\n \n return self._Theta\n \n\n\n\n def getVaporPressure(self, **kwargs):\n \"\"\" Get the vapor pressure in Pa\"\"\"\n if self._VaporPressure is None:\n \n _VaporPressure = self.zeros('QVAPOR')\n \n QVAPOR = self.getVariableData('QVAPOR',**kwargs)\n \n minimumQvapor = 0.00001 \n \n QVAPOR[QVAPOR < minimumQvapor] = minimumQvapor\n \n _VaporPressure[:] = self['Pressure'][:] * QVAPOR / (epsilon + QVAPOR)\n \n self._VaporPressure = wrfVariable(_VaporPressure ,\n 'Vapor Pressure', \"Pa\" ,\n self['QVAPOR'].dtype,\n self.getVariableDimensions('QVAPOR'))\n \n return self._VaporPressure\n \n \n \n def getThetaE(self, **kwargs):\n \"\"\"\n Get the Equivalent Potential Temperature in Kelvin degrees.\n \n Using Markowski and Richarson (2010), pag. 16:\n \n .. math::\n T_L = \\frac{2840}{3.5 ln(T) - ln(e) - 4.805} + 55.\n \n \\Theta_e = &T * \\frac{P_0}{P}^{0.2854(1-0.28q_v)} \n &\\times exp\\bigg\\[ q_v(1+0.81q_v) \\bigg( \\frac{3376}{T_L} - 2.54 \\bigg) \\bigg\\] \n Where:\n \n :math:`T_L` : Temperature at wich the air parcel becomes saturated\n :math:`q_v` : Vapor Mixing Ratio in kg/kg\n :math:`P_0` : Reference Pressure ( 1000hpa) \n :math:`P` : Pressure in Pa\n :math:`e` : Vapor Pressure in Pa\n :math:`T` : Temprature in Kelvin degrees \n \n \"\"\"\n if self._ThetaE is None:\n\n temperature = self['Temperature'][:] + T0\n QVAPOR = self['QVAPOR'][:]\n vaporPressure = self['VaporPressure'][:] * 0.01\n \n TL = (2840. / (3.5 * numpy.log(temperature) - numpy.log(vaporPressure) - 4.805)) + 55. \n \n _ThetaE = (temperature * numpy.power((P0 / self['Pressure'][:]) , 0.2854 * (1. - 0.28 * QVAPOR[:])) * \n numpy.exp(QVAPOR[:] * (1. + 0.81 * QVAPOR[:]) * ((3376. / TL) - 2.54)))\n \n self._ThetaE = wrfVariable(_ThetaE ,\n 'Equivalent Potential Temperature',\n \"K\" ,\n self.getVariableType('T'),\n self.getVariableDimensions('T'))\n \n del temperature \n del TL \n del vaporPressure \n gc.collect()\n \n return self._ThetaE\n \n \n# def getThetaEGradient(self, **kwargs): \n# \"\"\" Get the Equivalent Potential Temperature Horizontal Gradient in [Kelvin degrees]/[km] \"\"\"\n# if self._ThetaEGradient is None:\n# \n# _ThetaE = self['ThetaE'][:]\n# \n# _ThetaEGradient = self.zeros('T') \n# \n# horizontalGradient = self.zeros('T')\n# \n# horizontalGradient[:, :, :, 1:-1 ] = _ThetaE[:, :, :, 2:] - _ThetaE[:, :, :, 0:-2] \n# \n# horizontalGradient[:] /= 2.*self.getAttribute('DX') / 1000.\n# \n# \n# verticalGradient = self.zeros('ThetaE') \n# verticalGradient[:, :, 1:-1, : ] = _ThetaE[:, :, 2:, :] - _ThetaE[:, :, 0:-2, :]\n# verticalGradient[:] /= 2.*self.getAttribute('DY') / 1000.\n# \n# _ThetaEGradient = numpy.sqrt(horizontalGradient ** 2 + verticalGradient ** 2) \n# \n# self._ThetaEGradient = wrfVariable(_ThetaEGradient ,\n# 'Equivalent Potential Temperature Gradient', \" K / km\" ,\n# self.getVariableType('T'),\n# self.getVariableDimensions('T'))\n# \n# return self._ThetaEGradient\n# \n \n def getTemperature(self, **kwargs):\n \"\"\" Get the temperature in Celsius degrees \"\"\"\n if self._Temperature is None:\n \n \n _Temperature = self['Theta'][:] * numpy.power((self['Pressure'][:] / referencePressure), 0.2854) - T0\n \n self._Temperature = wrfVariable(_Temperature ,\n 'Temperature', \"C\" ,\n self.getVariableType('P'),\n self.getVariableDimensions('P'))\n \n return self._Temperature\n\n \n #TODO: Level limits check!\n def getPrecipitableWater(self, **kwargs):\n \"\"\"\n Get precipitable water in each vertical column\n \n Parameters\n ----------\n \n levels : tuple or list , optional\n Levels range for precipitation integration. Default, all levels.\n \"\"\"\n _PrecipitableWater = self['Temperature'] \n if self._SaturationVaporPressure is None:\n \n #print kwargs\n mySlice = [slice(None)] * 4\n \n #_QVAPOR = self['QVAPOR']\n #_Pressure = self['Pressure']\n \n \n levels = kwargs.pop('levels', None) \n if levels is not None:\n if isinstance(levels, (list, tuple)):\n levels = sorted(levels)\n mySlice[1] = slice(levels[0], levels[1]+1)\n else:\n raise fatalError(\"Error computing precipitable water\",\n \"levels keyword should be a list or a tuple\",\n \"levels keyword type: %s\"%type(levels))\n\n # _PrecipitableWater = numpy.trapz(self['QVAPOR'][:,0:15,:,:], self['Pressure'][:,0:15,:,:], axis=1)/(-g)\n _PrecipitableWater = numpy.trapz(self['QVAPOR'][mySlice], self['Pressure'][mySlice], axis=1) / (-g)\n \n self._PrecipitableWater = wrfVariable(_PrecipitableWater ,\n 'Precipitable Water', \"mm\" ,\n self.getVariableType('RAINNC'),\n self.getVariableDimensions('RAINNC'))\n \n return self._PrecipitableWater\n \n \n \n def getSaturationVaporPressure(self, **kwargs):\n \"\"\" Get the saturation vapor pressure in Pa \"\"\" \n _temperature = self['Temperature'][:] \n if self._SaturationVaporPressure is None:\n \n _SaturationVaporPressure = 611.2 * numpy.exp(17.67 * _temperature / (_temperature + 243.5))\n \n self._SaturationVaporPressure = wrfVariable(_SaturationVaporPressure ,\n 'Saturation Vapor Pressure', \"Pa\" ,\n self.getVariableType('P'),\n self.getVariableDimensions('P'))\n \n return self._SaturationVaporPressure\n \n def getSaturationVaporMixingRatio(self, **kwargs):\n \"\"\" Get the saturation vapor mixing ratio in kg/kg \"\"\"\n \n if self._SaturationVaporMixingRatio is None:\n \n _SaturationVaporMixingRatio = (self['SaturationVaporPressure'][:] * 0.622 / \n (self['Pressure'][:] - self['SaturationVaporPressure'][:]) \n )\n \n self._SaturationVaporMixingRatio = wrfVariable(_SaturationVaporMixingRatio ,\n 'Saturation Vapor Mixing Ratio', \"Kg/Kg\" ,\n self.getVariableType('P'),\n self.getVariableDimensions('P'))\n return self._SaturationVaporMixingRatio\n \n \n \n\n\n def getGeopotentialHeight(self, **kwargs):\n \"\"\" Get the geopotential Height in meters\"\"\"\n if self._GeopotentialHeight is None:\n _GeopotentialHeight = self.zeros('PH')\n \n _GeopotentialHeight[:] = self['Geopotential'][:] / g\n \n self._GeopotentialHeight = wrfVariable(_GeopotentialHeight ,\n 'Geopotential Height', \"m\" ,\n self.getVariableType('PH'),\n self.getVariableDimensions('PH'))\n \n return self._GeopotentialHeight\n\n def getGeopotential(self, **kwargs):\n \"\"\" Get the geopotential in \"[m2]/[s2]\"\"\"\n if self._Geopotential is None:\n \n _Geopotential = numpy.zeros(self.getVariableShape('PHB') ,\n dtype=self.getVariableType('PHB'))\n \n _Geopotential[:] = self['PH'][:] + self['PHB'][:]\n \n self._Geopotential = wrfVariable(_Geopotential ,\n 'Geopotential', \"m2/s2\" ,\n self.getVariableType('PH'),\n self.getVariableDimensions('PH'))\n \n \n pressureLevel = kwargs.pop(\"pressureLevel\", None) \n if pressureLevel is not None:\n # Interpolate into the pressure levels\n # If pressure less than surface presssure then assume a dry adiabatic lapse rate\n # and compute the geopotential at that pressure (Holton,2004 ; pag 25, E.g. 1.16)\n \n return self._Geopotential\n \n else: \n return self._Geopotential\n \n\n def getCartesianCoordinates(self, variableName=None , staggeredDimension=None , timeIndex=None):\n \"\"\" \n Get the cartesian coordinates for a given variable\n \n If no variable name is passed the staggeredDimension name argument is used.\n \n \n Parameters\n ----------\n \n variableName : str\n Variable Name\n \n staggeredDimension : int\n None or 0 : Cartesian grid for un-staggered grid\n 'x' or 1 : Cartesian grid for grid staggered in the x direction\n 'y' or 2 : Cartesian grid for grid staggered in the y direction\n 'z' or 3 : Cartesian grid for grid staggered in the z direction\n \n timeIndex : By default the internal timeIndex is used\n \n Returns\n -------\n \n gridCartesianCoordinates : :func:`gridCartesianCoordinatesTuple` instance\n \n \"\"\"\n \n if timeIndex is None:\n timeIndex = self.timeIndex\n \n \n \n # Buffer\n if timeIndex not in self.gridCartesianCoordinates:\n self.gridCartesianCoordinates[timeIndex] = dict() \n \n \n if variableName is not None:\n dimensions = self.getVariableDimensions(variableName)\n else: \n dimensions = staggeredDimensionsDefinitions[staggeredDimension]\n \n dimensions = list(dimensions)\n \n if 'Time' in dimensions:\n dimensions.remove('Time')\n \n \n _staggeredDimension = getStageredDimension(dimensions)\n if _staggeredDimension in self.gridCartesianCoordinates[timeIndex]:\n return self.gridCartesianCoordinates[timeIndex][_staggeredDimension]\n else:\n \n \n # Only one dimension can be staggered for a given variable\n \n if 'bottom_top_stag' in dimensions:\n z = self.getGeopotentialHeight()[timeIndex, :] # Staggered in z\n else:\n z = self.getUnstaggeredVariable('GeopotentialHeight')[timeIndex, :]\n \n z = z.swapaxes(0, 2)\n \n \n if 'west_east_stag' in dimensions:\n \n x = (numpy.arange(0, len('west_east_stag') - 0.5)) * self.getAttribute(\"DX\")\n \n newZShape = list(z.shape)\n newZShape[0] += 2 \n newZ = numpy.zeros(newZShape)\n newZ[1:-1, :, :] = z[:]\n newZ[0, :, :] = z[0, :, :]\n newZ[-1, :, :] = z[-1:, :, :]\n \n z = 0.5 * (newZ[1:, :, :] + newZ[-1:, :, :])\n \n \n else:\n x = numpy.arange(0, len('west_east')) * self.getAttribute(\"DX\")\n \n \n if 'south_north_stag' in dimensions:\n \n y = (numpy.arange(0, len('south_north_stag')) - 0.5) * self.getAttribute(\"DY\")\n \n newZShape = list(z.shape)\n newZShape[1] += 2 \n newZ = numpy.zeros(newZShape)\n newZ[:, 1:-1, :] = z[:]\n newZ[:, 0, :] = z[:, 0, :]\n newZ[:, -1, :] = z[:, -1, :]\n \n z = 0.5 * (newZ[:, 1:, :] + newZ[:, -1:, :])\n \n \n else:\n y = numpy.arange(0, len('south_north')) * self.getAttribute(\"DY\")\n \n \n x, y = numpy.meshgrid(x, y, indexing='ij')\n \n self.gridCartesianCoordinates[timeIndex][_staggeredDimension] = gridCartesianCoordinatesTuple(x=x, y=y, z=z)\n \n return self.gridCartesianCoordinates[timeIndex][_staggeredDimension]\n \n \n \n \n# def getSounding(self, timeIndex, latIndex, lonIndex,factor=1):\n# \"\"\" Sounding in format expected by the skew-t class \"\"\"\n# soundingData = dict()\n# \n# soundingData['temp'] = self['Temperature'][timeIndex, :, latIndex, lonIndex]\n# \n# QVAPOR = self['QVAPOR'][timeIndex, :, latIndex, lonIndex]*factor\n# \n# _VaporPressure = self['Pressure'][timeIndex, :, latIndex, lonIndex] * QVAPOR / (epsilon + QVAPOR)\n# \n# _temperature = self['Temperature'][timeIndex, :, latIndex, lonIndex] \n# \n# _SaturationVaporPressure = 611.2 * numpy.exp(17.67 * _temperature / (_temperature + 243.5))\n# \n# aboveSat = _VaporPressure>_SaturationVaporPressure\n# _VaporPressure[aboveSat]= _SaturationVaporPressure[aboveSat] \n# _DewPointTemperature = 243.5 / ((17.67 / numpy.log(_VaporPressure * 0.01 / 6.112)) - 1.)\n# \n# soundingData['dwpt'] = _DewPointTemperature\n# \n# soundingData['pres'] = self['Pressure'][timeIndex, :, latIndex, lonIndex] / 100. # In Hpa\n# soundingData['sknt'] = self['HorizontalWind'][timeIndex, :, latIndex, lonIndex] * 1.94384\n# soundingData['drct'] = self['WindDirection'][timeIndex, :, latIndex, lonIndex]\n# soundingData['hght'] = self.getUnstaggeredVariable('GeopotentialHeight')[timeIndex, :, latIndex, lonIndex]\n# \n# \n# return Sounding(soundingdata=soundingData)\n \n \n# # TODO: Improve using messinger method as an option\n# def getMSLP(self, **kwargs):\n# \"\"\"\n# \n# \n# Calculate MSLP using the hypsometric equation in the following form:\n# \n# \n# \n# MSLP =Psfc*exp^g*dz/(R*T)\n# \n# TODO Check this!\n# \n# \"\"\"\n# \n# if self._MSLP is None:\n# \n# if ('PSFC' in self.availableVariables and \n# 'T2' in self.availableVariables) :\n# pressure = self['PSFC'][:]\n# temperature = self['T2'][:] \n# else:\n# pressure = self.getVariableData('Pressure', levels=0, squeeze=True)\n# temperature = self.getVariableData('Temperature', levels=0, squeeze=True) + T0\n# \n# \n# terrainHeight = self['HGT'][:]\n# \n# _MSLP = pressure * numpy.exp(9.81 * terrainHeight / (287.04 * temperature)) \n# self._MSLP = wrfVariable(_MSLP ,\n# 'Mean Sea Level Temperature', \"Pa\" ,\n# self.getVariableType('RAINCV'),\n# self.getVariableDimensions('RAINCV'))\n# \n# return self._MSLP \n# \n# \n# def _computeCAPEAndCIN(self, **kwargs):\n# \"\"\" Get the CAPE and CIN for each column \"\"\"\n# \n# mostUnstable = kwargs.pop('mostUnstable', True)\n# fullFields = kwargs.pop('fullFields', 0)\n# myParcelAnalysis = parcelAnalysis(self['Pressure'],\n# self['Temperature'] + T0,\n# self['DewPointTemperature'] + T0,\n# mostUnstable=mostUnstable,\n# fullFields=fullFields)\n# \n# \n# self._CAPE = wrfVariable(myParcelAnalysis['CAPE'] ,\n# 'CAPE', \"J/Kg\" ,\n# self.getVariableType('RAINCV'),\n# self.getVariableDimensions('RAINCV'))\n# \n# # print self._CAPE[:].min(), self._CAPE[:].max()\n# \n# self._CIN = wrfVariable(myParcelAnalysis['CIN'] ,\n# 'CIN', \"J/Kg\" ,\n# self.getVariableType('RAINCV'),\n# self.getVariableDimensions('RAINCV'))\n# \n# \n# \n# def getCIN(self, **kwargs):\n# \"\"\" Get the CAPE for each column \"\"\"\n# \n# # Also get the CIN in this step \n# if self._CIN is None:\n# self._computeCAPEAndCIN(**kwargs)\n# \n# \n# return self._CIN\n# \n# \n# def getCAPE(self, **kwargs):\n# \"\"\" Get the CAPE for each column \"\"\"\n# \n# # Also get the CIN in this step \n# if self._CAPE is None:\n# self._computeCAPEAndCIN()\n# \n# \n# return self._CAPE\n# \n# \n# def _computeQVectorsAtPressureLevel(self, **kwargs):\n# \n# \n# if kwargs != self._computeQVectorsAtPressureLevelKwargs:\n# self._Q1AtPressureLevel = None\n# self._Q2AtPressureLevel = None\n# \n# \n# if self._Q1AtPressureLevel is None or self._Q1AtPressureLevel is None:\n# \n# self._computeQVectorsAtPressureLevelKwargs = kwargs.copy() \n# \n# kwargs['pressureLevel'] = kwargs.pop('pressureLevel', 50000)\n# kwargs['sigma'] = kwargs.pop('sigma', 7)\n# \n# sigma = kwargs['sigma']\n# pressureLevel = kwargs['pressureLevel']\n# \n# print \"pressureLevel\", pressureLevel\n# self._computeGeostrophicWindsAtPressureLevel(**kwargs)\n# \n# \n# # ---- Compute gradient of T at P ---------------------------------------------------------------\n# temperatureAtP = self.getTemperatureAtPresureLevel(**kwargs)\n# dT_dx , dT_dy = self.horizontalGradientAtP(temperatureAtP)\n# # ------------------------------------------------------------------------------------------------\n# \n# \n# # ---- Compute Ug and Vg gradients --------------------------------------------------------------\n# \n# dUg_dx , dUg_dy = self.horizontalGradientAtP(self._ugAtP) \n# dVg_dx , dVg_dy = self.horizontalGradientAtP(self._vgAtP)\n# \n# # --------------------------------------------------------------------------------------\n# \n# self._Q1AtPressureLevel = (dUg_dx * dT_dx + dVg_dx * dT_dy) * (-Rs_da / pressureLevel) \n# self._Q2AtPressureLevel = (dUg_dy * dT_dx + dVg_dy * dT_dy) * (-Rs_da / pressureLevel)\n# \n# \n# thetaAtP = _getVariableAtPresureLevel(pressureLevel,\n# self['Theta'][:],\n# self['Pressure'][:],\n# conserved=1)\n# if sigma is not None:\n# thetaAtP = gaussian_filter(thetaAtP, sigma)\n# \n# \n# \n# dTheta_dx , dTheta_dy = self.horizontalGradientAtP(thetaAtP)\n# gradientNorm = numpy.sqrt(dTheta_dx * dTheta_dx + dTheta_dy * dTheta_dy)\n# \n# self._QnVersor = ((dTheta_dx / gradientNorm) , (dTheta_dy / gradientNorm))\n# self._QnAtPressureLevel = (self._Q1AtPressureLevel * self._QnVersor[0] + \n# self._Q2AtPressureLevel * self._QnVersor[1])\n# \n# \n# \n# \n# def getFrontogenesis(self, **kwargs):\n# \n# kwargs['pressureLevel'] = kwargs.pop('pressureLevel', 50000)\n# kwargs['sigma'] = kwargs.pop('sigma', 7)\n# \n# sigma = kwargs['sigma']\n# pressureLevel = kwargs['pressureLevel']\n# \n# thetaAtP = _getVariableAtPresureLevel(pressureLevel,\n# self['Theta'][:],\n# self['Pressure'][:],\n# conserved=1)\n# if sigma is not None:\n# thetaAtP = gaussian_filter(thetaAtP, sigma)\n# \n# \n# dTheta_dx , dTheta_dy = self.horizontalGradientAtP(thetaAtP)\n# \n# gradientNorm = numpy.sqrt(dTheta_dx * dTheta_dx + dTheta_dy * dTheta_dy)\n# \n# \n# \n# U = _getVariableAtPresureLevel(pressureLevel,\n# self.getUnstaggeredVariable('U'),\n# self['Pressure'][:],\n# conserved=0) \n# \n# U = gaussian_filter(U, sigma)\n# \n# \n# \n# dU_dx , dU_dy = self.horizontalGradientAtP(U)\n# \n# V = _getVariableAtPresureLevel(pressureLevel,\n# self.getUnstaggeredVariable('V'),\n# self['Pressure'][:],\n# conserved=0) \n# V = gaussian_filter(V, sigma)\n# \n# dV_dx , dV_dy = self.horizontalGradientAtP(V) \n# _frontogenesis = -((dTheta_dx) * (dU_dx * dTheta_dx + dV_dx * dTheta_dy) + \n# (dTheta_dy) * (dU_dy * dTheta_dx + dV_dy * dTheta_dy)) / gradientNorm\n# \n# return _frontogenesis\n# \n# \n# def getQDivergenceAtPresureLevel(self, **kwargs):\n# \n# if kwargs != self._computeQVectorsAtPressureLevelKwargs:\n# self._Q1AtPressureLevel = None\n# self._Q2AtPressureLevel = None\n# \n# if self._Q1AtPressureLevel is None or self._Q2AtPressureLevel is None:\n# self._computeQVectorsAtPressureLevel(**kwargs)\n# \n# \n# \n# # _QDivergenceAtPresureLevel = self.horizontalDivergenceAtP(self._Q1AtPressureLevel,\n# # self._Q2AtPressureLevel) \n# # \n# \n# _QDivergenceAtPresureLevel = self.horizontalDivergenceAtP(self._QnAtPressureLevel * self._QnVersor[0],\n# self._QnAtPressureLevel * self._QnVersor[1]) \n# \n# \n# self._QDivergenceAtPresureLevel = wrfVariable(_QDivergenceAtPresureLevel ,\n# 'Q Divergence', \"asd\" ,\n# self.getVariableType('RAINCV'),\n# self.getVariableDimensions('RAINCV'))\n# \n# return self._QDivergenceAtPresureLevel\n# \n# def horizontalDivergenceAtP(self, *variableData, **kwargs):\n# \n# \n# unstaggered = kwargs.pop(\"unstaggered\", True)\n# \n# if len(variableData) == 1:\n# variableData_x = variableData[0][0]\n# variableData_y = variableData[0][1]\n# elif len(variableData) == 2:\n# variableData_x = variableData[0]\n# variableData_y = variableData[1] \n# else:\n# raise fatalError(\"Incorrect number of arguments\",\n# \"Possible inputs:\",\n# \"horizontalDivergenceAtP (variableData) , with variableData a two element tuple/list\",\n# \"horizontalDivergenceAtP (variableData_x , variableData_y)\")\n# \n# \n# if variableData_x.ndim != 3:\n# # dimensions expected (u'Time', u'south_north', u'west_east')\n# raise fatalError(\"Dimension not supported for variable at x\",\n# \"Dimensions expected (u'Time', u'south_north', u'west_east')\")\n# \n# if variableData_y.ndim != 3:\n# # dimensions expected (u'Time', u'south_north', u'west_east')\n# raise fatalError(\"Dimension not supported for variable at y\",\n# \"Dimensions expected (u'Time', u'south_north', u'west_east')\")\n# \n# \n# if unstaggered:\n# \n# lat = self['XLAT'][:]\n# lon = self['XLONG'][:] \n# xFactor, yFactor = getMapFactors(lat, lon, self.getAttribute('TRUELAT1'))\n# factor = xFactor * yFactor\n# \n# myDivergence_x = numpy.gradient(variableData_x * yFactor,\n# self.getAttribute('DX'),\n# axis=(2))\n# \n# myDivergence_y = numpy.gradient(variableData_y * xFactor,\n# self.getAttribute('DY'),\n# axis=(1))\n# \n# \n# else:\n# raise fatalError(\"Staggered not supported\")\n# \n# \n# return (myDivergence_x + myDivergence_y) * factor\n# \n# \n# \n# def horizontalGradientAtP(self, variableData, unstaggered=True):\n# \"\"\"Return a tuple\"\"\"\n# \n# if variableData.ndim != 3:\n# # dimensions expected (u'Time', u'south_north', u'west_east')\n# raise fatalError(\"Dimension not supported\",\n# \"Dimensions expected (u'Time', u'south_north', u'west_east')\")\n# \n# if unstaggered:\n# myGradient = numpy.gradient(variableData,\n# self.getAttribute('DX'),\n# self.getAttribute('DY'),\n# axis=(2, 1))\n# \n# \n# lat = self['XLAT'][:]\n# lon = self['XLONG'][:] \n# xFactor, yFactor = getMapFactors(lat, lon, self.getAttribute('TRUELAT1'))\n# \n# myGradient[0] *= xFactor\n# myGradient[1] *= yFactor\n# else:\n# raise fatalError(\"Staggered not supported\")\n# \n# \n# return myGradient[0], myGradient[1]\n# \n# def _computeGeostrophicWindsAtPressureLevel(self, **kwargs):\n# \"\"\" Compute geostrophic wind\"\"\"\n# \n# if kwargs != self._computeGeostrophicWindsAtPressureLevelKwargs:\n# self._ugAtP, self._vgAtP = None, None\n# \n# \n# if self._ugAtP is None or self._vgAtP is None:\n# self._computeGeostrophicWindsAtPressureLevelKwargs = kwargs.copy() \n# pressureLevel = kwargs.pop('pressureLevel', 50000)\n# sigma = kwargs.pop('sigma', 7)\n# \n# geopotentialAtP = self.getGeopotentialAtPresureLevel(pressureLevel=pressureLevel, sigma=sigma, **kwargs)[:]\n# \n# # dimensions (u'Time', u'south_north', u'west_east')\n# \n# geopotentialGradient = self.horizontalGradientAtP(geopotentialAtP)\n# \n# f = 1.458e-4 * numpy.sin(self['XLAT'][:] * RadToDeg)\n# \n# ug = -geopotentialGradient[0] / f\n# vg = geopotentialGradient[1] / f\n# \n# self._ugAtP = wrfVariable(ug ,\n# 'U Geostrophic Wind at %.0f hPa' % (pressureLevel / 100), \"m/s\" ,\n# self.getVariableType('RAINCV'),\n# self.getVariableDimensions('RAINCV'))\n# \n# self._vgAtP = wrfVariable(vg ,\n# 'V Geostrophic Wind at %.0f hPa' % (pressureLevel / 100), \"m/s\" ,\n# self.getVariableType('RAINCV'),\n# self.getVariableDimensions('RAINCV'))\n# \n# \n# \n# \n# \n# def getTemperatureAtPresureLevel(self, **kwargs):\n# \"\"\" Get the Temperature at a given pressure level (unstaggered grid)\"\"\"\n# \n# if kwargs != self._TemperatureAtPresureLevelKwargs: \n# self._temperatureAtPresureLevel = None\n# \n# \n# if self._temperatureAtPresureLevel is None:\n# self._TemperatureAtPresureLevelKwargs = kwargs.copy() \n# pressureLevel = kwargs.pop('pressureLevel', 50000)\n# sigma = kwargs.pop('sigma', 7)\n# \n# _temperatureAtPresureLevel = _getTemperatureAtPresureLevel(pressureLevel,\n# self['Temperature'] + degCtoK,\n# self['Pressure'])\n# \n# if sigma is not None:\n# _temperatureAtPresureLevel = gaussian_filter(_temperatureAtPresureLevel, sigma)\n# \n# self._temperatureAtPresureLevel = wrfVariable(_temperatureAtPresureLevel ,\n# 'TemperatureAtPresureLevel', \"K\" ,\n# self.getVariableType('RAINCV'),\n# self.getVariableDimensions('RAINCV'))\n# \n# return self._temperatureAtPresureLevel \n# \n# \n# def getGeopotentialAtPresureLevel(self, **kwargs):\n# \"\"\" Get the Geopotential at a given pressure level (unstaggered grid)\"\"\"\n# \n# if kwargs != self._GeopotentialAtPresureLevelKwargs: \n# self._geopotentialAtPresureLevel = None\n# \n# \n# if self._geopotentialAtPresureLevel is None:\n# self._GeopotentialAtPresureLevelKwargs = kwargs \n# pressureLevel = kwargs.pop('pressureLevel', 50000)\n# sigma = kwargs.pop('sigma', 7)\n# \n# \n# geopotentialAtPresureLevel = _getGeopotentialAtPresureLevel(pressureLevel,\n# self.getVariableData('Geopotential', unstaggered=True),\n# self['Pressure'],\n# self['Temperature'])\n# \n# if sigma is not None:\n# geopotentialAtPresureLevel = gaussian_filter(geopotentialAtPresureLevel, sigma)\n# \n# self._geopotentialAtPresureLevel = wrfVariable(geopotentialAtPresureLevel ,\n# 'GeopotentialAtPresureLevel', \"J/Kg\" ,\n# self.getVariableType('RAINCV'),\n# self.getVariableDimensions('RAINCV'))\n# \n# return self._geopotentialAtPresureLevel\n# \n# \n# \n# \n# def getQ1AtPressureLevel(self, *args, **kwargs):\n# self._computeQVectorsAtPressureLevel(*args, **kwargs)\n# return self._Q1AtPressureLevel\n# \n# def getQ2AtPressureLevel(self, *args, **kwargs):\n# \n# self._computeQVectorsAtPressureLevel(*args, **kwargs)\n# return self._Q2AtPressureLevel\n# \n# \n# def getUwindAtPressureLevel(self, *args, **kwargs):\n# \n# if kwargs != self._UwindAtPresureLevelKwargs: \n# self._UwindAtPresureLevel = None\n# \n# \n# if self._UwindAtPresureLevel is None:\n# self._UwindAtPresureLevelKwargs = kwargs \n# pressureLevel = kwargs.pop('pressureLevel', 50000)\n# sigma = kwargs.pop('sigma', 7)\n# \n# UwindAtPresureLevel = _getVariableAtPresureLevel(pressureLevel,\n# self.getVariableData('U', unstaggered=True),\n# self['Pressure'])\n# \n# # if sigma is not None:\n# # UwindAtPresureLevel = gaussian_filter(UwindAtPresureLevel, sigma)\n# \n# self._UwindAtPresureLevel = wrfVariable(UwindAtPresureLevel ,\n# 'UwindAtPresureLevel', \"m/s\" ,\n# self.getVariableType('RAINCV'),\n# self.getVariableDimensions('RAINCV')\n# )\n# \n# return self._UwindAtPresureLevel\n# \n# \n# def getVwindAtPressureLevel(self, *args, **kwargs):\n# \n# if kwargs != self._VwindAtPresureLevelKwargs: \n# self._VwindAtPresureLevel = None\n# \n# \n# if self._VwindAtPresureLevel is None:\n# self._VwindAtPresureLevel = kwargs \n# pressureLevel = kwargs.pop('pressureLevel', 50000)\n# sigma = kwargs.pop('sigma', 7)\n# \n# \n# VwindAtPresureLevel = _getVariableAtPresureLevel(pressureLevel,\n# self.getVariableData('V', unstaggered=True),\n# self['Pressure'])\n# \n# # if sigma is not None:\n# # VwindAtPresureLevel = gaussian_filter(VwindAtPresureLevel, sigma)\n# \n# self._VwindAtPresureLevel = wrfVariable(VwindAtPresureLevel ,\n# 'VwindAtPresureLevel', \"m/s\" ,\n# self.getVariableType('RAINCV'),\n# self.getVariableDimensions('RAINCV')\n# )\n# \n# return self._VwindAtPresureLevel\n# \n# \n# def getUgAtPressureLevel(self, *args, **kwargs):\n# self._computeGeostrophicWindsAtPressureLevel(*args, **kwargs)\n# return self._ugAtP\n# \n# def getVgAtPressureLevel(self, *args, **kwargs):\n# \n# self._computeGeostrophicWindsAtPressureLevel(*args, **kwargs)\n# return self._vgAtP\n# \n# \n# \n# def getBuoyancy(self):\n# \"\"\" Get the Buoyancy . Not working \"\"\"\n# if self._Buoyancy is None:\n# _Buoyancy = self.zeros('PB')\n# \n# MuBase = self['MUB']\n# PHB = self['PHB'] \n# pressureBase = self['PB']\n# pressureReference = P0\n# \n# inverseDensityBase = self.zeros('PB')\n# thetaBase = self.zeros('PB')\n# \n# times , levels, _ , _ = self['PB'].shape\n# \n# geopotentialVerticalGradient = (PHB[:, 1:, :, :] - PHB[:, :-1, :, :])\n# \n# for time in range(0, times): \n# for level in range(0, levels):\n# geopotentialVerticalGradient[time, level, :, :] *= self['RDNW'][time, level]\n# \n# inverseDensityBase[:, level, :, :] = -geopotentialVerticalGradient[:, level, :, :] / MuBase[:]\n# \n# invGamma = 1. / 1.4 \n# \n# for timeIndex in range(0, times):\n# thetaBase[timeIndex, :, :, :] = numpy.power(pressureBase[timeIndex, :] / pressureReference , invGamma)\n# \n# thetaBase[:] *= pressureBase[:] * inverseDensityBase[:] / Rd\n# \n# _Buoyancy[:] = g * ((self['Theta'][:] / thetaBase[:]) - 1. + 0.61 * self['QVAPOR'][:]) \n# self._Buoyancy = wrfVariable(_Buoyancy ,\n# 'Buoyancy', \"m/s2\" ,\n# self.getVariableType('PB'),\n# self.getVariableDimensions('PB'))\n# \n# del(inverseDensityBase)\n# del(thetaBase)\n# del(geopotentialVerticalGradient)\n# gc.collect()\n# \n# return self._Buoyancy\n\n\n \n\n \n \n","sub_path":"pyWAT/io/wrfOutput.py","file_name":"wrfOutput.py","file_ext":"py","file_size_in_byte":55023,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"612273842","text":"import matplotlib.pyplot as plt\nimport numpy as np\n\nx = np.array([0, 4, 8, 10])\ny = np.array([0, 0, 1, 0])\n\nplt.ylabel('u(t)')\nplt.xlabel('t')\nplt.suptitle('Square Pulse')\nplt.grid(True, linestyle='--', color='lightgrey')\nsquare = plt.step(x, y)\nplt.xticks(np.arange(0, 11, 1))\nplt.show()\n","sub_path":"lab2/square_pulse/square_pulse.py","file_name":"square_pulse.py","file_ext":"py","file_size_in_byte":289,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"107267919","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n##############################################################################\n# File: demo_cv.py\n# Created: 2016-10-17\n# Last modification: 2016-10-24\n# Author: Michael Hufschmidt \n# \n# Copyright: (C) Michael Hufschmidt 2016\n# License (CC BY 4.0): https://creativecommons.org/licenses/by/4.0/deed.de\n###############################################################################\n\nfrom cold_chuck_tools import * # cold_chuck_tools.py in currrent directory\ndatafile = 'FTH200N_04_DiodeS_14_2015-11-05_4.cv'\nccd = ColdChuckData(datafile) # create a data file object\np = CVPlot(ccd) # create plot object\np.make_plot() # create the plot\np.save_plot() # save plot as .pdf \nplt.show() # show plot\n","sub_path":"demo_cv.py","file_name":"demo_cv.py","file_ext":"py","file_size_in_byte":1006,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"571746246","text":"from matplotlib.pyplot import *\nfrom numpy import *\n\ndef draw_sin():\n x1 = linspace(0,10,10)\n y1 = sin(x1)\n plot(x1,y1)\n x2 = linspace(0, 10, 1000)\n y2 = sin(x2)\n plot(x2, y2, ':')\n show()\n\ndef draw_sin_ext():\n x0 = 0.0\n x1 = 10.0\n dx = 1.0\n n = int(ceil((x1-x0)/dx) + 1)\n x = zeros((n,1),float)\n y = zeros((n,1), float)\n for i in range(n):\n x[i] = x0 + (i-1)*dx\n y[i] = sin(x[i])\n\n plot(x,y)\n show()\n\nif __name__ == \"__main__\":\n draw_sin()","sub_path":"examples/vectorization.py","file_name":"vectorization.py","file_ext":"py","file_size_in_byte":505,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"45656558","text":"# uncompyle6 version 3.7.4\n# Python bytecode 2.7 (62211)\n# Decompiled from: Python 3.6.9 (default, Apr 18 2020, 01:56:04) \n# [GCC 8.4.0]\n# Embedded file name: /code/s3direct/utils.py\n# Compiled at: 2019-07-27 06:21:33\nimport hashlib, hmac\nfrom collections import namedtuple\nfrom django.conf import settings\ntry:\n from botocore import session\nexcept ImportError:\n session = None\n\nAWSCredentials = namedtuple('AWSCredentials', [\n 'token', 'secret_key', 'access_key'])\n\ndef get_s3direct_destinations():\n \"\"\"Returns s3direct destinations.\n\n NOTE: Don't use constant as it will break ability to change at runtime.\n \"\"\"\n return getattr(settings, 'S3DIRECT_DESTINATIONS', None)\n\n\ndef sign(key, message):\n return hmac.new(key, message.encode('utf-8'), hashlib.sha256).digest()\n\n\ndef get_aws_v4_signing_key(key, signing_date, region, service):\n datestamp = signing_date.strftime('%Y%m%d')\n date_key = sign(('AWS4' + key).encode('utf-8'), datestamp)\n k_region = sign(date_key, region)\n k_service = sign(k_region, service)\n k_signing = sign(k_service, 'aws4_request')\n return k_signing\n\n\ndef get_aws_v4_signature(key, message):\n return hmac.new(key, message.encode('utf-8'), hashlib.sha256).hexdigest()\n\n\ndef get_key(key, file_name, dest):\n if hasattr(key, '__call__'):\n fn_args = [file_name]\n args = dest.get('key_args')\n if args:\n fn_args.append(args)\n object_key = key(*fn_args)\n elif key == '/':\n object_key = file_name\n else:\n object_key = '%s/%s' % (key.strip('/'), file_name)\n return object_key\n\n\ndef get_aws_credentials():\n access_key = getattr(settings, 'AWS_ACCESS_KEY_ID', None)\n secret_key = getattr(settings, 'AWS_SECRET_ACCESS_KEY', None)\n if access_key and secret_key:\n return AWSCredentials(None, secret_key, access_key)\n else:\n if not session:\n return AWSCredentials(None, None, None)\n else:\n creds = session.get_session().get_credentials()\n if creds:\n return AWSCredentials(creds.token, creds.secret_key, creds.access_key)\n return AWSCredentials(None, None, None)\n\n return","sub_path":"pycfiles/django-s3direct-1.1.5.tar/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":2185,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"374224357","text":"# -*- Mode: Python; tab-width: 4 -*-\n# -*- coding: utf-8 -*-\n# -----------------------------------------------------------------------------------------------------------------------\n##\tName:\t\tgenerico\n# -----------------------------------------------------------------------------------------------------------------------\n\nfrom collections import OrderedDict\nfrom datetime import timedelta\nfrom decimal import Decimal\nfrom os.path import basename\n\nfrom aquaclasses import *\nfrom aquaerrors import DataMissingError, CostCodeMissingError, InvalidDataError\nfrom inputreader import InputReader\nfrom logger import Logger\n\n##======================================================================================================================\n\nlogger = Logger(filename=__file__, log_filename=globals()['log_filename'], prefix='--- ', debug_mode=False)\nlogger.config()\n\nfpro = None # Dati di fatturazione dell'azienda\nfprol = [] # letture\nfproc = [] # costi\nfprot = [] # tariffe\nfpros = [] # scaglioni\n\nresults = []\ntipo_lettura = ''\n\n# Lettura file dei dati in input\nlogger.debug('InputReader().read(): Starting')\naqua_data = InputReader(aqua_classes, globals()['input_filename']).read()\nlogger.debug('InputReader().read(): Done')\n\n##======================================================================================================================\n\n\ndef write_output(res):\n\t\"\"\"\n\tScrive i risultati nel file di output\n\n\t:param res: <[Output()]>\n\t:return \n\t\"\"\"\n\twith open(globals()['output_filename'], \"w\") as fout:\n\t\tfout.writelines([str(o) + '\\n' for o in res])\n\n\ndef output_line(numfat, cs, codart, qta, importo):\n\to = Output()\n\to.fpo_numfat = numfat\n\to.fpo_cs = cs\n\to.fpo_bcodart = codart\n\to.fpo_costo = importo\n\to.fpo_qta = qta\n\treturn o\n\n\ndef scaglione(tar, mc):\n\t\"\"\"\n\tScaglione Acqua\n\n\t:param tar: Fatprot() - Tariffa\n\t:param mc: int - metri cubi\n\t:return Decimal()\n\t\"\"\"\n\tassert isinstance(tar, Fatprot)\n\tassert isinstance(mc, (int, Decimal))\n\n\treturn Decimal(round(tar.fpt_quota * mc / 1000) if tar.fpt_quota < 99999 else 99999)\n\n\ndef costo(tar, qta):\n\t\"\"\"\n\tPrepara un record di Output() di costi\n\n\t:param tar: - Tariffa applicata\n\t:param qta: - Quantità\n\t:return Output()\n\t\"\"\"\n\tassert isinstance(tar, Fatprot)\n\tassert isinstance(qta, (Decimal, int))\n\n\tcodart = tar.fpt_bcodart_s if tipo_lettura == 'S' else tar.fpt_bcodart_r\n\treturn output_line(tar.fpt_bgiorni, 'C', codart, qta, tar.fpt_costo_tot)\n\n\ndef costo_acqua_calda(qta):\n\t\"\"\"\n\tCalcola il costo dell'acqua calda\n\n\t:param qta: - Quantità consumata\n\t:return